From 7af1306a552bda1d2a96c63c1b13b5832efdc619 Mon Sep 17 00:00:00 2001 From: Steve Dempsey Date: Mon, 2 Nov 2026 19:02:12 -0500 Subject: [PATCH 01/18] Local stack: the installed ds-bot@0.2.6 patch on top of v0.2.6 Byte for byte the tree installed in the desktop profile on 2026-11-02 (78 of 78 files match). --- ds-bot/README.md | 2 +- ds-bot/client.js | 87 +++++++++++++++++++++++++++--------- ds-bot/src/host/constants.js | 2 +- ds-bot/src/host/delivery.js | 10 ++++- ds-bot/src/host/handoffs.js | 46 ++++++++++++++++--- ds-bot/src/host/privacy.js | 5 +++ ds-bot/src/host/prompt.js | 3 +- ds-bot/src/host/tools.js | 33 ++++++++++++++ ds-bot/src/host/turns.js | 27 +++++++++-- 9 files changed, 183 insertions(+), 32 deletions(-) diff --git a/ds-bot/README.md b/ds-bot/README.md index 97cad49ae6..1c7cef2fa2 100644 --- a/ds-bot/README.md +++ b/ds-bot/README.md @@ -11,7 +11,7 @@ Tested with dsh `0.2.1-rc.4` (Web) and `0.2.0-rc.2` (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, progress, choices, confirmations and short forms; an interactive card waits for your answer. +- **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, progress, choices, confirmations and short forms; an interactive card waits for your answer. - **Group chats**: members speak one at a time, and each one reads the latest messages first. A message can `@Name` a member to pass the turn on; type `@` to pick one from a list. **+ → Reference a chat** adds another Bot's chat to a message as context, and in a group the members who answer get it. A member with nothing new to add stays quiet (`[PASS]`). 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 24d0962b56..74f36c2587 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: "搜索", @@ -2406,10 +2407,10 @@ function useLinger(value, ms) { // src/client/styles.js var SHELL_CSS = ` -body{--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;-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-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;-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-shape,.bt-swatch,.bt-color,.bt-newchat,.bt-task-day,.bt-task-remove,.bt-fb-btn){touch-action:manipulation} -body[data-ds-dark-theme]{--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)} +body[data-ds-dark-theme]{--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} ${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} @@ -2500,6 +2501,15 @@ 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} +/* A Bot whose own turn is over but whose handed-on work has not come back: it cannot + wear the working badge, and a Main Bot's star arrives first in the one badge slot, so + the wait gets a slot of its own. The clock sits opposite the star, so a Main Bot keeps + both its identity and its state, and the slow tick carries the eye at 12px. */ +.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} @@ -2522,6 +2532,11 @@ 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)} +/* Main Bots tile in a grid: the shell's sidebar holds the whole Bot list here, so the + first rows are the Bots that answer for the team rather than a single seat. */ +.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:12px;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)} @@ -2543,14 +2558,16 @@ body[data-bt-motion=quiet] .bt-mark[data-poke]{cursor:default} Mica the app styles DSH's sidebar the same way, via --bt-leftcol-fill there); it stays under the shell's title-bar switch (z 30) and the popovers (z 60), and the floating drawer keeps the opaque fill over the conversation. */ -.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)} +.bt-leftcol{position:relative;left:auto;top:auto;bottom:auto;z-index:auto;display:flex;flex-direction:column;min-height:0;--bt-lc-clear:0px;background:none;border-right:none;box-sizing:border-box;padding:0;color:var(--bt-ink);font-family:var(--bt-font)} +/* The shell's column is the resizer here, and our edge drag would fight it. */ +.bt-leftcol>.bt-leftcol-grip{display:none} html[data-windows-titlebar] .bt-leftcol,html[data-platform=darwin] .bt-leftcol{border-right:none} .bt-leftcol-grip{position:absolute;right:-4px;top:0;bottom:0;width:8px;cursor:col-resize;z-index:3;touch-action:none} .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). Our own collapse of it lands without the shell's slide. */ -[class*="_frame"][data-sidebar-collapsed][data-rightbar-collapsed]:has(>[class*="_sidebarCol"]){grid-template-columns:0px minmax(0,1fr) 0px!important} +/* 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%} @@ -3760,6 +3777,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); @@ -3788,7 +3813,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, + 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) { @@ -9368,7 +9394,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 = isMainOf(roster, id) || 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]); @@ -9632,13 +9658,13 @@ function useListGlide(listRef, layout, key) { tops.current = { layout, map: next }; }, [layout, key]); } -function LeftColumn({ mode, width, onGrip, children }) { - return (0, import_react_dom3.createPortal)((0, import_react19.createElement)( +function LeftColumn({ mode, onGrip, children }) { + return (0, import_react19.createElement)( "div", - { className: "bt-leftcol", "data-left": mode, style: { width: `${width}px` } }, + { className: "bt-leftcol", "data-left": mode }, children, (0, import_react19.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; @@ -9684,7 +9710,7 @@ function TeamSidebar(props) { const order = (0, import_react19.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 })) @@ -9692,6 +9718,7 @@ function TeamSidebar(props) { return entries2.sort((a, b) => Number(Boolean(b.item.pinned)) - Number(Boolean(a.item.pinned)) || b.at - a.at); }, [roster, updated]); 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((candidate) => candidate !== void 0 && candidate.id === bot.id) === index); useListGlide(listRef, wideContent, order.map((entry) => entry.item.id).join(",")); useLandOnMainBot(roster, useSessions, actions); const openWidth = drag?.width ?? frameSnap.sidebarWidth; @@ -9699,7 +9726,7 @@ function TeamSidebar(props) { const pushed = mode === "open" ? openWidth : mode === "hidden" ? 0 : RAIL_WIDTH; (0, import_react19.useLayoutEffect)(() => { if (typeof document === "undefined") return; - chatRoom.setLeft(Math.max(0, pushed - (frameSnap.collapsedWidth ?? 0))); + chatRoom.setLeft(null); }, [pushed, frameSnap.collapsedWidth]); (0, import_react19.useEffect)(() => () => { if (typeof document !== "undefined") chatRoom.setLeft(null); @@ -9828,7 +9855,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; @@ -9874,7 +9900,7 @@ function TeamSidebar(props) { event.preventDefault(); actions.openPalette(event.key); }; - const onToggle = () => actions.toggleLeftHidden?.(); + const onToggle = () => (actions.toggleSidebar ?? actions.toggleLeftHidden)?.(); const toggleRef = (0, import_react19.useRef)(onToggle); toggleRef.current = onToggle; (0, import_react19.useEffect)(() => { @@ -9905,11 +9931,11 @@ function TeamSidebar(props) { main ? (0, import_react19.createElement)(BotRow, { ...rowProps, bot: main, marked: markedUnread[main.id] === true }) : roster.ready ? null : (0, import_react19.createElement)("div", { className: "bt-hint" }, uiNow.bootFailed ? bootHint() : t("Setting up your Main Bot…")), (0, import_react19.createElement)("span", { className: "bt-rail-sep", "aria-hidden": true }) ); - const foot = wideContent ? (0, import_react19.createElement)("div", { className: "bt-leftcol-foot" }, (0, import_react19.createElement)(AccountLauncher, { seat: false, actions })) : (0, import_react19.createElement)( + const foot = wideContent ? uiNow.accountSeated ? null : (0, import_react19.createElement)("div", { className: "bt-leftcol-foot" }, (0, import_react19.createElement)(AccountLauncher, { seat: false, actions })) : (0, import_react19.createElement)( "div", { className: "bt-leftcol-foot bt-leftcol-foot-rail" }, (0, import_react19.createElement)("button", { type: "button", className: "bt-round", "aria-label": t("New…"), title: t("New…"), onClick: () => actions.openNewChat("new") }, (0, import_react19.createElement)(PlusIcon)), - (0, import_react19.createElement)(AccountLauncher, { seat: false, actions }) + uiNow.accountSeated ? null : (0, import_react19.createElement)(AccountLauncher, { seat: false, actions }) ); const content = (0, import_react19.createElement)( "div", @@ -9919,7 +9945,7 @@ function TeamSidebar(props) { (0, import_react19.createElement)( "div", { ref: listRef, className: "bt-list", role: "region", "aria-label": t("Bot list") }, - wideContent ? main ? (0, import_react19.createElement)(BotRow, { ...rowProps, bot: main, marked: markedUnread[main.id] === true }) : roster.ready ? null : (0, import_react19.createElement)("div", { className: "bt-hint" }, uiNow.bootFailed ? bootHint() : t("Setting up your Main Bot…")) : null, + wideContent ? tileBots.length > 0 ? (0, import_react19.createElement)("div", { className: "bt-tile-grid" }, tileBots.map((bot) => (0, import_react19.createElement)(BotRow, { key: bot.id, ...rowProps, bot, marked: markedUnread[bot.id] === true }))) : roster.ready ? null : (0, import_react19.createElement)("div", { className: "bt-hint" }, uiNow.bootFailed ? bootHint() : t("Setting up your Main Bot…")) : null, order.map((entry) => entry.kind === "bot" ? (0, import_react19.createElement)(BotRow, { key: entry.item.id, ...rowProps, bot: entry.item, marked: markedUnread[entry.item.id] === true }) : entry.kind === "room" ? (0, import_react19.createElement)(RoomRow, { key: entry.item.id, ...rowProps, room: entry.item, marked: markedUnread[entry.item.id] === true }) : (0, import_react19.createElement)(AgentRow, { key: entry.item.id, ...rowProps, agent: entry.item, marked: markedUnread[entry.item.id] === true })) ), foot @@ -10271,7 +10297,7 @@ function useLandOnMainBot(roster, useSessions, actions) { const lastBot = (0, import_react19.useRef)(null); (0, import_react19.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 }; @@ -10284,7 +10310,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; } @@ -20551,6 +20577,25 @@ var inject = ["sessions", "uiWorkspace", "uiConversation", "slots", "theme", "la function apply(ctx) { ctx.effect(() => installLocale(ctx.get("locale")), "ds-bot: interface copy"); const roster = createSource(EMPTY_ROSTER); + ctx.effect(() => { + const publish2 = () => { + const snap = roster.getSnapshot(); + const ids = [.../* @__PURE__ */ new Set([ + ...snap.bots.flatMap((bot) => [bot.id, currentPart(bot), ...bot.parts ?? []]), + ...snap.rooms.flatMap((room2) => [room2.id, ...room2.parts ?? []]), + ...Object.keys(snap.agentOf ?? {}) + ])]; + window.__dshBotSessions = ids; + window.dispatchEvent(new CustomEvent("dsh-bot:sessions", { detail: ids })); + }; + const off = roster.subscribe(publish2); + publish2(); + return () => { + off(); + window.__dshBotSessions = []; + window.dispatchEvent(new CustomEvent("dsh-bot:sessions", { detail: [] })); + }; + }, "ds-bot: publish owned sessions"); migrateStorage(); const unreadStore = sharedMap(STORAGE.unread); const reactionStore = sharedMap(STORAGE.reactions); @@ -21448,7 +21493,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 && snap.byId[main] === void 0 && snap.roomsById[main] === void 0 && !(snap.rooms ?? []).some((room2) => room2.sessionId === main || (room2.parts ?? []).includes(main)); + const plain = isAgentSessionId(main) || snap.ready && unowned; setPlain(plain); if (plain) dropPanels(); if (main === previous) return; diff --git a/ds-bot/src/host/constants.js b/ds-bot/src/host/constants.js index 988bff72a1..c466322db4 100644 --- a/ds-bot/src/host/constants.js +++ b/ds-bot/src/host/constants.js @@ -64,7 +64,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/delivery.js b/ds-bot/src/host/delivery.js index 557d690e65..d8011a6563 100644 --- a/ds-bot/src/host/delivery.js +++ b/ds-bot/src/host/delivery.js @@ -27,6 +27,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]' @@ -54,7 +55,10 @@ 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, toId, sessionId, text, role, replyTo, roomId, audience, note, exchangeId = randomUUID(), steer = false, deferred = false, resumed = false, retried = false, resent = false, merged = false, askedBy, fromRoomId, 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, toId, sessionId, text, role, replyTo, roomId, audience, note, exchangeId = randomUUID(), steer = false, deferred = false, resumed = false, retried = false, resent = false, merged = false, handedBack = false, askedBy, fromRoomId, files = [], length, work }) { const from = rt.botOf(fromId) const to = rt.botOf(toId) if (to === undefined) throw new Error(`Unknown Bot ${toId}`) @@ -74,6 +78,7 @@ export function install(rt) { ...(roomId ? { roomId } : {}), ...(audience === 'user' ? { audience } : {}), ...(deferred ? { deferred: true } : {}), + ...(handedBack ? { handedBack: true } : {}), ...(resumed ? { resumed: true } : {}), ...(retried ? { retried: true } : {}), ...(askedBy ? { askedBy } : {}), @@ -119,6 +124,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 0dbaa81267..58ef7f8e52 100644 --- a/ds-bot/src/host/handoffs.js +++ b/ds-bot/src/host/handoffs.js @@ -258,17 +258,47 @@ export function install(rt) { .filter(([id, work]) => work.to !== undefined && work.open.length > 0 && !busy.has(id)) .map(([id, work]) => ({ id, work, out: work.open.map(childId => works()[childId]).filter(Boolean) })) 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 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(child => child.room !== undefined || onIt(child.to)) + if (live.length === 0) continue const entry = view[work.to] ??= { bots: [], rooms: [], for: [] } - for (const child of out) add(child.room ? entry.rooms : entry.bots, child.room ?? child.to) + for (const child of live) add(child.room ? entry.rooms : entry.bots, child.room ?? child.to) add(entry.for, work.from) } + for (const work of sentOnOwn()) if (onIt(work.to)) add((view[work.from] ??= { bots: [], rooms: [], for: [] }).bots, work.to) return view } @@ -308,12 +338,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(child => child.room !== 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(child => (child.room ? `group "${rt.roomOf(child.room)?.name ?? 'a group'}"` : child.name ?? nameOf(child.to) ?? 'a teammate')))] + const on = [...new Set(live.map(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') 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 682b53d54b..5c594001c0 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. list_bots shows every group.', diff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.js index 5a74daac2a..95ca21a616 100644 --- a/ds-bot/src/host/tools.js +++ b/ds-bot/src/host/tools.js @@ -700,6 +700,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({ diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.js index abc7a971d6..6d55232d4a 100644 --- a/ds-bot/src/host/turns.js +++ b/ds-bot/src/host/turns.js @@ -107,6 +107,11 @@ const RETRY_PROMISE_TEXT = 'Your last reply said you would start working, but yo const PROMISED_WORK = /(?:^(?:收到|好的|明白|好|行|没问题|了解)[,,、。.!!:\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 @@ -261,7 +266,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' @@ -590,6 +595,7 @@ 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 @@ -798,6 +804,7 @@ export function install(rt) { 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 } } 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) @@ -825,17 +832,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 @@ -869,6 +879,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() return wroteCall && reply === '' ? 'Tried to run a tool but wrote the call as text, so it did not run.' : reply @@ -940,12 +960,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)) } break From 0d69df2110e5e65f2c8ac7ce349ab862b5a928f5 Mon Sep 17 00:00:00 2001 From: Steve Dempsey Date: Mon, 2 Nov 2026 19:24:09 -0500 Subject: [PATCH 02/18] Card gate: decisions on a Bot-sent job go back to the Bot that sent it In a turn another Bot opened, a Bot that is not a Main Bot can no longer show the user a question card or a plan review. ask_user is refused and exit_plan_mode is refused by a guard; both refusals name the sender and tell the Bot to send it a DECISION instead. Still allowed: Main Bots, turns the user typed, requests whose audience is the user, a 'deploy to production' card (the production guard reads only the runner's own transcript), and a job carrying CARD-IT-YOURSELF. A Main Bot message carrying PLAN-APPROVED turns plan mode off in the Bot it reaches (queued when a turn is open). DSH_CARD_GATE=off turns all of it off. Each refusal and relayed approval is one JSON line in /logs/card-gate.log. --- ds-bot/src/host/card-gate.js | 124 +++++++++++++++++++ ds-bot/src/host/delivery.js | 4 + ds-bot/src/host/tools.js | 14 +++ ds-bot/src/host/turns.js | 8 +- ds-bot/test/card-gate.test.js | 226 ++++++++++++++++++++++++++++++++++ ds-bot/test/questions.test.js | 2 +- 6 files changed, 374 insertions(+), 4 deletions(-) create mode 100644 ds-bot/src/host/card-gate.js create mode 100644 ds-bot/test/card-gate.test.js diff --git a/ds-bot/src/host/card-gate.js b/ds-bot/src/host/card-gate.js new file mode 100644 index 0000000000..e25ce3c145 --- /dev/null +++ b/ds-bot/src/host/card-gate.js @@ -0,0 +1,124 @@ +// 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, a card whose option is the production approval +// (the production guard only reads the transcript of the Bot that runs the +// command), and a job whose text carries CARD-IT-YOURSELF. +// +// DSH_CARD_GATE=off turns all of it off. + +import { appendFile, mkdir } from 'node:fs/promises' +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' + +/** + * The gate's view of the turn running in a Session: undefined when the turn is not + * one a Bot opened (no gate), else who runs it, who sent it, and whether it may card. + */ +export function gatedTurn(rt, sessionId) { + if (!gateOn()) return undefined + const { state } = rt + const entry = rt.live?.get(sessionId) + const turn = entry?.turn + if (turn === undefined || !(state.exchangeTurns?.[sessionId] ?? []).includes(turn)) return undefined + const botId = rt.chatOwners?.get(sessionId) + if (botId === undefined || rt.isMain?.(botId)) return undefined + 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 undefined + 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 { + bot: rt.botOf?.(botId)?.name ?? botId, + manager: senderOf(rt, info), + cardItYourself: texts.some(text => text.includes(CARD_IT_YOURSELF)), + } +} + +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.` + +/** Whether ask_user in this Session is refused; the refusal text, or undefined. */ +export function refuseCard(rt, sessionId, options) { + const gated = gatedTurn(rt, sessionId) + if (gated === undefined || gated.cardItYourself) return undefined + if ((options ?? []).some(option => isProductionLabel(option?.label))) return undefined + return { ...gated, text: cardRefusal(gated.manager) } +} + +/** 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. */ +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) } : {}) }) + return mkdir(dirname(path), { recursive: true }) + .then(() => appendFile(path, `${line}\n`, 'utf8')) + .catch(error => rt.warn?.('ds-bot: card gate log not written: %s', error?.code ?? error)) +} + +/** + * A Main Bot's message that relays a plan approval turns plan mode off in the + * Session it reaches: at once between turns, from the next step inside one. + * Returns what planMode.set said, or undefined when nothing was done. + */ +export function relayPlanApproval(rt, { fromId, toId, agent, text }) { + if (!gateOn() || !String(text ?? '').includes(PLAN_APPROVED)) return undefined + if (fromId === undefined || !rt.isMain?.(fromId) || fromId === toId) return undefined + const planMode = rt.ctx?.get?.('planMode') + if (planMode === undefined || agent === undefined) return undefined + let outcome + try { + const now = planMode.get(agent) + if (!(now.pending ?? now.active)) return undefined + outcome = planMode.set(agent, false) + } catch (error) { + rt.warn?.('ds-bot: relayed plan approval not applied: %s', error) + return undefined + } + void logGate(rt, { bot: rt.botOf?.(toId)?.name ?? toId, manager: rt.botOf?.(fromId)?.name ?? fromId, tool: 'plan-approved', outcome }) + return outcome +} diff --git a/ds-bot/src/host/delivery.js b/ds-bot/src/host/delivery.js index d8011a6563..70e72e2885 100644 --- a/ds-bot/src/host/delivery.js +++ b/ds-bot/src/host/delivery.js @@ -1,6 +1,7 @@ // 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 { 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' @@ -96,6 +97,9 @@ 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). + relayPlanApproval(rt, { fromId, toId, agent, text }) if (steer) agent.steer(message) else agent.followup(message) await ctx.sessions.flush(agent.session) diff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.js index 95ca21a616..a3d11d3376 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, logGate, planTitle, refuseCard, refusePlan } 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' @@ -680,6 +681,12 @@ 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 refused = refuseCard(rt, id, options) + if (refused !== undefined) { + void logGate(rt, { bot: refused.bot, manager: refused.manager, tool: 'ask_user', title: String(args.question ?? '') }) + return refused.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 @@ -927,6 +934,13 @@ Reason: ${why}` : ''}` ctx.tools.guard((exec) => { if (!rt.isBotSession(exec.agent?.id)) return undefined 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.` + 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 6d55232d4a..1d8b12c957 100644 --- a/ds-bot/src/host/turns.js +++ b/ds-bot/src/host/turns.js @@ -369,8 +369,10 @@ 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 // 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) @@ -599,7 +601,7 @@ export function install(rt) { 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 } @@ -696,7 +698,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. diff --git a/ds-bot/test/card-gate.test.js b/ds-bot/test/card-gate.test.js new file mode 100644 index 0000000000..2faad328d1 --- /dev/null +++ b/ds-bot/test/card-gate.test.js @@ -0,0 +1,226 @@ +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' + }, + } +} + +async function start({ planMode } = {}) { + const home = mkdtempSync(join(tmpdir(), 'ds-bot-card-gate-')) + writeFileSync(join(home, 'state.json'), JSON.stringify(TEAM)) + const ctx = fakeContext({ services: planMode ? { planMode } : {} }) + 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' } }) + } + const log = async () => { + 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)) + return existsSync(path) ? readFileSync(path, 'utf8').split('\n').filter(Boolean).map(line => JSON.parse(line)) : [] + } + await rt.teamTools.find(d => d.name === 'list_bots').execute({}, { agent: { id: 'chief' } }) + return { rt, emit, ask, guard, fromBot, fromUser, log, delivered, stop: async () => { await ctx.dispose(); 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 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('the production approval card stays with the Bot that runs it', async (t) => { + const { rt, ask, fromBot, stop } = await start() + t.after(stop) + fromBot('coder', 'chief', 'Merge PR 12 when Steve approves') + assert.match(await ask('coder', [{ label: 'deploy to production (Recommended)' }, { label: 'Hold' }]), /card is on screen/) + assert.ok(rt.state.questions.coder) + delete rt.state.questions.coder + fromBot('writer', 'chief', 'Ship it') + assert.match(await ask('writer', [{ label: 'Deploy to production' }, { label: 'Hold' }]), /card is on screen/) + // A look-alike label is not the approval. + fromBot('writer', 'chief', 'Ship it again') + assert.match(await ask('writer', [{ label: 'deploy to production now' }, { label: 'Hold' }]), /^This job came from Chief/) +}) + +test('CARD-IT-YOURSELF in the job lets the Bot card the user', async (t) => { + const { rt, ask, fromBot, 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) +}) + +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 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 log() + assert.deepEqual([entry.bot, entry.manager, entry.tool, entry.outcome], ['Coder', 'Chief', 'plan-approved', 'committed']) +}) + +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 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, []) +}) diff --git a/ds-bot/test/questions.test.js b/ds-bot/test/questions.test.js index ed9a473a82..bcf8693c1d 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?') From 9889b96e563001152fe9f42f9228a5259bef43bf Mon Sep 17 00:00:00 2001 From: Steve Dempsey Date: Tue, 3 Nov 2026 07:06:18 -0500 Subject: [PATCH 03/18] Plan mode: release through the preset realm, and Bot Sessions start with it off Two faults kept Bots stuck in plan mode: 1. DSH's shipped presets (standard, ptc, cordis) pin plan mode on for every new Session (defaultActive: true). DS Bot makes every Bot chat, group Session and handoff part on `standard`, so each one started in plan mode. 2. Under a preset, plan mode lives in an isolated group (isolate.planMode), so rt.ctx.get('planMode') found nothing and a relayed PLAN-APPROVED was a silent no-op. The lookup now reads agentPresets.serviceFor(agent, 'planMode') first, as parts.js already does for compaction. ensurePlanOff switches a Bot Session out of plan mode once (recorded in state.planDefaultOff), on creation, on resume and on first delivery. A later /plan in that chat stays on. A Bot with planMode 'on', or named in /plan-mode-keep.json, is left alone. DSH_PLAN_DEFAULT_OFF=off turns it off. Every attempt is logged to card-gate.log with its outcome. --- ds-bot/src/host/card-gate.js | 107 ++++++++++++++++-- ds-bot/src/host/delivery.js | 5 +- ds-bot/src/host/parts.js | 7 +- ds-bot/src/host/roster.js | 3 + ds-bot/test/card-gate.test.js | 202 ++++++++++++++++++++++++++++++++-- 5 files changed, 305 insertions(+), 19 deletions(-) diff --git a/ds-bot/src/host/card-gate.js b/ds-bot/src/host/card-gate.js index e25ce3c145..63edefc33f 100644 --- a/ds-bot/src/host/card-gate.js +++ b/ds-bot/src/host/card-gate.js @@ -14,6 +14,7 @@ // // DSH_CARD_GATE=off turns all of it off. +import { readFileSync } from 'node:fs' import { appendFile, mkdir } from 'node:fs/promises' import { dirname, join } from 'node:path' @@ -100,25 +101,115 @@ export function logGate(rt, entry) { .catch(error => rt.warn?.('ds-bot: card gate log not written: %s', error?.code ?? error)) } +// 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 turns plan mode off in the - * Session it reaches: at once between turns, from the next step inside one. + * 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() || !String(text ?? '').includes(PLAN_APPROVED)) return undefined - if (fromId === undefined || !rt.isMain?.(fromId) || fromId === toId) return undefined - const planMode = rt.ctx?.get?.('planMode') - if (planMode === undefined || agent === undefined) return undefined + 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 }) + } + if (fromId !== undefined && fromId === toId) { log('self'); return undefined } + if (fromId === undefined || !rt.isMain?.(fromId)) { log('sender-not-main'); 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)) return undefined + 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 } - void logGate(rt, { bot: rt.botOf?.(toId)?.name ?? toId, manager: rt.botOf?.(fromId)?.name ?? fromId, tool: 'plan-approved', outcome }) + log(outcome) return outcome } + +/** + * 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', orderRelease: orderReleaseOn(), planDefaultOff: planDefaultOffOn(), lookup: 'agentPresets.serviceFor' }) +} diff --git a/ds-bot/src/host/delivery.js b/ds-bot/src/host/delivery.js index 70e72e2885..92a2e2479b 100644 --- a/ds-bot/src/host/delivery.js +++ b/ds-bot/src/host/delivery.js @@ -1,12 +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 { relayPlanApproval } from './card-gate.js' +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) @@ -99,6 +101,7 @@ export function install(rt) { }) // 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) diff --git a/ds-bot/src/host/parts.js b/ds-bot/src/host/parts.js index cce1737c07..91cea9cba6 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' @@ -317,7 +318,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 diff --git a/ds-bot/src/host/roster.js b/ds-bot/src/host/roster.js index 0aa22ea14a..79ca569c29 100644 --- a/ds-bot/src/host/roster.js +++ b/ds-bot/src/host/roster.js @@ -4,6 +4,7 @@ import { mkdir } from 'node:fs/promises' import { MAX_AVATAR_IMAGE, ROOM_MAX_MEMBERS, ROOM_MODES, ROOM_NAME_MAX, ROOM_NOTICE_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])?))*$/ @@ -89,6 +90,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/test/card-gate.test.js b/ds-bot/test/card-gate.test.js index 2faad328d1..7ac225f5fe 100644 --- a/ds-bot/test/card-gate.test.js +++ b/ds-bot/test/card-gate.test.js @@ -39,10 +39,21 @@ function fakePlanMode(active = {}) { } } -async function start({ planMode } = {}) { +// `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)) - const ctx = fakeContext({ services: planMode ? { planMode } : {} }) + 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 () => {} }, @@ -87,14 +98,20 @@ async function start({ planMode } = {}) { nextTurn(sessionId) emit(sessionId, 'user/message', { content: [{ type: 'text', text: body }], source: { kind: 'user' } }) } - const log = async () => { + // 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)) - return existsSync(path) ? readFileSync(path, 'utf8').split('\n').filter(Boolean).map(line => JSON.parse(line)) : [] + 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' } }) - return { rt, emit, ask, guard, fromBot, fromUser, log, delivered, stop: async () => { await ctx.dispose(); rmSync(home, { recursive: true, force: true, maxRetries: 5 }) } } + 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) => { @@ -105,7 +122,7 @@ test('ask_user in a job another Bot sent is refused and names the manager', asyn 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 log() + const [entry] = await anyLines(log) assert.equal(entry.bot, 'Writer') assert.equal(entry.manager, 'Chief') assert.equal(entry.tool, 'ask_user') @@ -166,7 +183,7 @@ test('exit_plan_mode in a job another Bot sent is refused', async (t) => { 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 log() + 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') @@ -183,7 +200,7 @@ test('PLAN-APPROVED from a Main Bot turns plan mode off', async (t) => { assert.deepEqual(planMode.calls, [['coder', false]]) assert.equal(planMode.active.coder, false) assert.equal(delivered.length, 1) - const [entry] = await log() + const [entry] = await anyLines(log) assert.deepEqual([entry.bot, entry.manager, entry.tool, entry.outcome], ['Coder', 'Chief', 'plan-approved', 'committed']) }) @@ -200,6 +217,78 @@ test('PLAN-APPROVED from a Bot that is not a Main Bot changes nothing', async (t 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-main']) +}) + +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) @@ -224,3 +313,98 @@ test('DSH_CARD_GATE=off turns the gate off', async (t) => { 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, []) +}) From 9603b013e22435acfd3f0202034647aec658b4d1 Mon Sep 17 00:00:00 2001 From: Steve Dempsey Date: Tue, 3 Nov 2026 14:34:13 -0500 Subject: [PATCH 04/18] Write the card gate log synchronously The gate's log line was a fire-and-forget async mkdir and append. A line logged near the end of a test could land after the host stopped and its temp home was being removed, so teardown failed with ENOTEMPTY on the Node 22 CI job (blocking-question and scoped-tools-creation). The line is tiny, so it is now written in the same call. Also keeps the old package name out of the owned-sessions test comment. --- ds-bot/src/host/card-gate.js | 19 +++++++++++++------ ds-bot/test/owned-sessions.test.js | 2 +- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/ds-bot/src/host/card-gate.js b/ds-bot/src/host/card-gate.js index 63edefc33f..b07b57eb01 100644 --- a/ds-bot/src/host/card-gate.js +++ b/ds-bot/src/host/card-gate.js @@ -14,8 +14,7 @@ // // DSH_CARD_GATE=off turns all of it off. -import { readFileSync } from 'node:fs' -import { appendFile, mkdir } from 'node:fs/promises' +import { appendFileSync, mkdirSync, readFileSync } from 'node:fs' import { dirname, join } from 'node:path' export const CARD_IT_YOURSELF = 'CARD-IT-YOURSELF' @@ -91,14 +90,22 @@ export function refusePlan(rt, sessionId) { return { ...gated, text: planRefusal(gated.manager) } } -/** One JSON line in /logs/card-gate.log. Only names, the tool and a title. */ +/** + * 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) } : {}) }) - return mkdir(dirname(path), { recursive: true }) - .then(() => appendFile(path, `${line}\n`, 'utf8')) - .catch(error => rt.warn?.('ds-bot: card gate log not written: %s', error?.code ?? error)) + 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 diff --git a/ds-bot/test/owned-sessions.test.js b/ds-bot/test/owned-sessions.test.js index 9e55632f61..3cf79bc1a3 100644 --- a/ds-bot/test/owned-sessions.test.js +++ b/ds-bot/test/owned-sessions.test.js @@ -1,6 +1,6 @@ // 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 as window.__dshBotSessions and the dsh-bot:sessions event. +// 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' From a1f2df83e4b8d90ce28298aa85e02ab6206d7fca Mon Sep 17 00:00:00 2001 From: Steve Dempsey Date: Tue, 3 Nov 2026 16:53:32 -0500 Subject: [PATCH 05/18] Record the verified 0.2.7 install in the repo state files Phase 4 of dsbot-027-upgrade proved all five checks on the live boot, including the HANDED_BACK pointer hand-back read from the session logs. The state files keep that record in the repo. --- CURRENT_STATE.md | 11 +++++++++++ DEPLOYMENT_LEDGER.md | 12 ++++++++++++ NEXT_SESSION_PROMPT.md | 12 ++++++++++++ OPEN_ISSUES.md | 9 +++++++++ VERIFICATION_RESULTS.md | 17 +++++++++++++++++ 5 files changed, 61 insertions(+) create mode 100644 CURRENT_STATE.md create mode 100644 DEPLOYMENT_LEDGER.md create mode 100644 NEXT_SESSION_PROMPT.md create mode 100644 OPEN_ISSUES.md create mode 100644 VERIFICATION_RESULTS.md diff --git a/CURRENT_STATE.md b/CURRENT_STATE.md new file mode 100644 index 0000000000..b2f91c7f3b --- /dev/null +++ b/CURRENT_STATE.md @@ -0,0 +1,11 @@ +# CURRENT_STATE (ds-bot, NeoTech installed stack) + +## 2026-11-03 dsbot-027-upgrade: 0.2.7 plus local patches installed and proven live + +- The live profile `C:\Users\SteveDempsey\.dsh\profiles\desktop` runs ds-bot 0.2.7 with the local patch stack replayed on top. +- Branch `stack/installed-0.2.7` on the fork (neotechnet/DS-Bot), head `9603b01`, two commits over upstream `v0.2.7`: `21eff5d` (carry the 0.2.6 stack onto 0.2.7) and `9603b01` (write the card gate log synchronously). +- PR https://github.com/neotechnet/DS-Bot/pull/4, base `upstream/v0.2.7`. It records the installed stack; it is not merged and is not meant for upstream as is. +- Installed 2026-11-03 19:52:28Z to 19:52:37Z with `pnpm install`: 82 of 82 files match `9603b01`, patch_hash `73316542d9efddc6b01a6c36f13d71dab5922c272b97d6c8ae828f499e9ecba9`. +- DeepSeek Harness 0.2.1-rc.5 restarted twice afterwards (about 21:12Z and 21:38Z). All five phase 4 proofs pass on the second boot (see VERIFICATION_RESULTS.md). +- Rollback: copy back the 3 files in `C:\Users\SteveDempsey\.claude\Exports\2026-11-03_dsbot-pre-027-snapshot\` and run `pnpm install` in the profile. +- Known red: the CI leak scan, accepted under LE-20261103-033 (the `dsh-bot:sessions` to `ds-bot:sessions` rename). diff --git a/DEPLOYMENT_LEDGER.md b/DEPLOYMENT_LEDGER.md new file mode 100644 index 0000000000..1433de1c6b --- /dev/null +++ b/DEPLOYMENT_LEDGER.md @@ -0,0 +1,12 @@ +# DEPLOYMENT_LEDGER (ds-bot, NeoTech installed stack) + +ds-bot is local desktop software. Nothing deploys on merge; a change ships only when it is installed into the live profile and proven running. + +## 2026-11-03 ds-bot 0.2.7 plus local stack into the live desktop profile + +- Target: `C:\Users\SteveDempsey\.dsh\profiles\desktop` (DeepSeek Harness 0.2.1-rc.5). +- Source: `stack/installed-0.2.7` at `9603b01` (fork PR #4). +- Installed: 2026-11-03 19:52:28Z to 19:52:37Z, `pnpm install` (pnpm 11.28.5) exit 0. patch_hash `73316542d9efddc6b01a6c36f13d71dab5922c272b97d6c8ae828f499e9ecba9`. +- Live from: app restart about 21:12Z, again 21:38Z (operator restarts, not forced by the agent). +- Proven: all five phase 4 proofs, see VERIFICATION_RESULTS.md 2026-11-03. +- Previous: 0.2.6 plus local stack. Snapshot `C:\Users\SteveDempsey\.claude\Exports\2026-11-03_dsbot-pre-027-snapshot\`. diff --git a/NEXT_SESSION_PROMPT.md b/NEXT_SESSION_PROMPT.md new file mode 100644 index 0000000000..54a6081af5 --- /dev/null +++ b/NEXT_SESSION_PROMPT.md @@ -0,0 +1,12 @@ +# NEXT_SESSION_PROMPT (ds-bot, NeoTech installed stack) - snapshot 2026-11-03 + +ds-bot 0.2.7 plus the local stack is installed and proven live (fork branch `stack/installed-0.2.7`, head `9603b01`, PR neotechnet/DS-Bot#4). Read CURRENT_STATE.md and VERIFICATION_RESULTS.md first. + +Next, in order: +1. Close fork PRs #1 to #3 if still open, delete their branches, read back. +2. 06-ds-bot-plugin.md playbook draft to Igor. +3. dsbot-view-guard-patch-name write-up. +4. dsbot-card-routing-overlord (approved, Choice A plus H3): new worktree from `stack/installed-0.2.7`, scope `ds-bot/src/host`, `ds-bot/test`. +5. LE-20261103-033 rename, due 2026-11-10. + +Rules: never write `~\.dsh\bot\state.json`; never force-restart the app; proof from live reads only. For hand-back proofs, decode the session logs (`C:\Projects\logs\2026-11-03-dsbot-027\tools\scan_handback.mjs`), not chat-index.sqlite alone. diff --git a/OPEN_ISSUES.md b/OPEN_ISSUES.md new file mode 100644 index 0000000000..d4c3f1a0c6 --- /dev/null +++ b/OPEN_ISSUES.md @@ -0,0 +1,9 @@ +# OPEN_ISSUES (ds-bot, NeoTech installed stack) - snapshot 2026-11-03 + +- LE-20261103-033: rename `dsh-bot:sessions` to `ds-bot:sessions` in ds-bot and deepseek-harness, Harness listening on both names for one release. Owner Harness Code, due 2026-11-10. Clears the red CI leak scan, which stays accepted until then. +- dsbot-card-routing-overlord: PLAN-APPROVED (Choice A plus H3), queued. Drop the `refuseCard` production-label exemption (card-gate.js line 83), gate interactive show_view in gated turns, log allowed cards with the deciding label, accept a non-Main manager on the PLAN-APPROVED release (today `sender-not-main`), tests for all. +- dsbot-view-guard-patch-name: change write-up for `ds_bot_view_guard.py` (Harness Code writes the description only, not the file). +- 06-ds-bot-plugin.md playbook draft for Igor. +- Fork PRs #1 to #3 on neotechnet/DS-Bot to close (superseded by #4). +- chat-index.sqlite lags the session logs (seen 2026-11-03, index 30 min behind). Any proof that reads only the index can miss recent events; read the session logs. +- Not ours: H1 and H2 (guard-composio-write-coverage) belong to NeoTech Code. diff --git a/VERIFICATION_RESULTS.md b/VERIFICATION_RESULTS.md new file mode 100644 index 0000000000..cc1da72a41 --- /dev/null +++ b/VERIFICATION_RESULTS.md @@ -0,0 +1,17 @@ +# VERIFICATION_RESULTS (ds-bot, NeoTech installed stack) + +## 2026-11-03 dsbot-027-upgrade: phase 4 live proof, all five PASS + +Evidence folder: `C:\Projects\logs\2026-11-03-dsbot-027\`. + +| # | Proof | Result | Evidence | +|---|---|---|---| +| 0 | Gates before install | npm test 1660 run, 1658 pass, 0 fail, 2 skipped. `build-client --check` exit 0. Lint 0 errors. CI run 41704581395: Node 22 and Node 24 green, leak scan red (LE-20261103-033). | `gate-test-2.txt`, `gate-check.txt`, `gate-lint.txt` | +| 0 | Install read-back | 82 of 82 installed files match `9603b01`, all 9 markers present. | `live-compare.json`, `live-markers.txt` | +| 1 | Processes started after the install | 30 processes, earliest 2026-11-03T21:38:51.80Z, main window PID 47400; old PIDs gone. | `phase4-processes-2.json` | +| 2 | Gate loaded after restart | `card-gate.log` gate-loaded lines at 21:13:14.662Z and 21:39:25.029Z. | `C:\Users\SteveDempsey\.dsh\bot\logs\card-gate.log` | +| 3 | void_question in the installed build | installed package.json 0.2.7; void_question in constants.js:67, tools.js:714, privacy.js:198, prompt.js:34, turns.js:283. | live profile `node_modules\ds-bot\src\host\` | +| 4 | HANDED_BACK fires | PASS. Igor's session `session-bbf16cbd` seq 1479 at 2026-11-03T21:48:10.750Z: message from Eye In The Sky with `source.deferred=true, handedBack=true`, answered at seq 1480. First boot also fired at seq 1279, 21:29:10.580Z. | `phase4-handedback-pass.txt` (sha256 84826C04...91B4D6), `phase4-handedback-scan.txt` | +| 5 | Screenshot of the running GUI | PID 47400 window, 1477x874. | `phase4-gui-2.png` sha256 B35B6B42...8E7E | + +Note on #4: `chat-index.sqlite` lags the session logs (max row 21:22:14Z at read time), so an index-only read reports no hand-back after the restart. The pass comes from decoding the zstd session logs frame by frame (`tools\scan_handback.mjs`). From 8fd0b19d2218e18ece447e83783474a5884b1446 Mon Sep 17 00:00:00 2001 From: Steve Dempsey Date: Tue, 3 Nov 2026 16:59:07 -0500 Subject: [PATCH 06/18] Correct the proof 5 screenshot record The first capture was DPI unaware and kept only the top-left part of the window, which read as text cut off at the right edge. The DPI aware capture shows the whole window with the chat wrapping. --- VERIFICATION_RESULTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/VERIFICATION_RESULTS.md b/VERIFICATION_RESULTS.md index cc1da72a41..983359a0d6 100644 --- a/VERIFICATION_RESULTS.md +++ b/VERIFICATION_RESULTS.md @@ -12,6 +12,6 @@ Evidence folder: `C:\Projects\logs\2026-11-03-dsbot-027\`. | 2 | Gate loaded after restart | `card-gate.log` gate-loaded lines at 21:13:14.662Z and 21:39:25.029Z. | `C:\Users\SteveDempsey\.dsh\bot\logs\card-gate.log` | | 3 | void_question in the installed build | installed package.json 0.2.7; void_question in constants.js:67, tools.js:714, privacy.js:198, prompt.js:34, turns.js:283. | live profile `node_modules\ds-bot\src\host\` | | 4 | HANDED_BACK fires | PASS. Igor's session `session-bbf16cbd` seq 1479 at 2026-11-03T21:48:10.750Z: message from Eye In The Sky with `source.deferred=true, handedBack=true`, answered at seq 1480. First boot also fired at seq 1279, 21:29:10.580Z. | `phase4-handedback-pass.txt` (sha256 84826C04...91B4D6), `phase4-handedback-scan.txt` | -| 5 | Screenshot of the running GUI | PID 47400 window, 1477x874. | `phase4-gui-2.png` sha256 B35B6B42...8E7E | +| 5 | Screenshot of the running GUI | PASS. Full window 2584x1529 at DPI 168, captured DPI aware; chat text wraps inside its bubble. The earlier 1477x874 capture was DPI unaware and cropped to the top-left 57% (the vision SUSPECT "cut off at the right edge" was that crop). | `phase4-gui-3.png` sha256 A88ACDB9...46364F, `phase4-gui-3.json`; superseded `phase4-gui-2.png` | Note on #4: `chat-index.sqlite` lags the session logs (max row 21:22:14Z at read time), so an index-only read reports no hand-back after the restart. The pass comes from decoding the zstd session logs frame by frame (`tools\scan_handback.mjs`). From 051e199413abbe0cea7106efe126f2285d6bf89c Mon Sep 17 00:00:00 2001 From: Steve Dempsey Date: Tue, 3 Nov 2026 17:30:30 -0500 Subject: [PATCH 07/18] Send every card on a manager's job back to the manager Steve's rule (2026-11-03): cards on a job a manager dispatched go to that manager, not to him. The gate still let two kinds through: a card whose option was the production approval, and interactive show_view cards, which were never gated. A deploy approval now always goes back to the manager, CARD-IT-YOURSELF included, and show_view is judged like ask_user. Every card decided in a Bot Session is logged with the reason that decided it, so an allowed card can be traced as well as a refused one. A plan release is now honoured from the admin of a group the receiving Bot is in, as well as from a Main Bot: SEO Overlord is the manager for its group but is not a Main Bot, and its releases were logged as sender-not-main and did nothing. --- ds-bot/src/host/card-gate.js | 105 ++++++++++++++++++++++++++------ ds-bot/src/host/tools.js | 14 +++-- ds-bot/test/card-gate.test.js | 107 +++++++++++++++++++++++++++++---- ds-bot/test/view-reply.test.js | 5 +- 4 files changed, 194 insertions(+), 37 deletions(-) diff --git a/ds-bot/src/host/card-gate.js b/ds-bot/src/host/card-gate.js index b07b57eb01..2b5b902c05 100644 --- a/ds-bot/src/host/card-gate.js +++ b/ds-bot/src/host/card-gate.js @@ -8,9 +8,15 @@ // 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, a card whose option is the production approval -// (the production guard only reads the transcript of the Bot that runs the -// command), and a job whose text carries CARD-IT-YOURSELF. +// 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. @@ -45,42 +51,92 @@ export const planTitle = (plan) => { const senderOf = (rt, info) => rt.botOf?.(info?.senderSessionId)?.name ?? info?.senderName ?? 'the Bot that sent this job' /** - * The gate's view of the turn running in a Session: undefined when the turn is not - * one a Bot opened (no gate), else who runs it, who sent it, and whether it may card. + * 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 gatedTurn(rt, sessionId) { - if (!gateOn()) return undefined +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 undefined + if (turn === undefined || !(state.exchangeTurns?.[sessionId] ?? []).includes(turn)) return { reason: 'not-bot-turn' } const botId = rt.chatOwners?.get(sessionId) - if (botId === undefined || rt.isMain?.(botId)) return undefined + 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 undefined + 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 gated = gatedTurn(rt, sessionId) - if (gated === undefined || gated.cardItYourself) return undefined - if ((options ?? []).some(option => isProductionLabel(option?.label))) return undefined - return { ...gated, text: cardRefusal(gated.manager) } + 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. */ @@ -133,10 +189,12 @@ export function relayPlanApproval(rt, { fromId, toId, agent, text }) { 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 }) + 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 } - if (fromId === undefined || !rt.isMain?.(fromId)) { log('sender-not-main'); 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 @@ -153,6 +211,19 @@ export function relayPlanApproval(rt, { fromId, toId, agent, text }) { 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 @@ -218,5 +289,5 @@ export function ensurePlanOff(rt, agent, why, { fresh = false } = {}) { /** 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', orderRelease: orderReleaseOn(), planDefaultOff: planDefaultOffOn(), lookup: 'agentPresets.serviceFor' }) + 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/tools.js b/ds-bot/src/host/tools.js index 1d618f08b1..52e7264c91 100644 --- a/ds-bot/src/host/tools.js +++ b/ds-bot/src/host/tools.js @@ -3,7 +3,7 @@ import { randomUUID } from 'node:crypto' import { defineTool } from '@deepseek-ai/dsh-tools' import { readAvatar } from './avatar.js' -import { EXIT_PLAN_MODE, logGate, planTitle, refuseCard, refusePlan } from './card-gate.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' @@ -685,11 +685,9 @@ export function install(rt) { .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 refused = refuseCard(rt, id, options) - if (refused !== undefined) { - void logGate(rt, { bot: refused.bot, manager: refused.manager, tool: 'ask_user', title: String(args.question ?? '') }) - return refused.text - } + 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 @@ -763,6 +761,10 @@ Reason: ${why}` : ''}` 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 diff --git a/ds-bot/test/card-gate.test.js b/ds-bot/test/card-gate.test.js index 7ac225f5fe..c2ef3fd088 100644 --- a/ds-bot/test/card-gate.test.js +++ b/ds-bot/test/card-gate.test.js @@ -154,26 +154,44 @@ test('a request whose audience is the user cards as before', async (t) => { assert.equal(rt.state.questions.writer.question, 'Which name?') }) -test('the production approval card stays with the Bot that runs it', async (t) => { - const { rt, ask, fromBot, stop } = await start() +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) - delete rt.state.questions.coder - fromBot('writer', 'chief', 'Ship it') - assert.match(await ask('writer', [{ label: 'Deploy to production' }, { label: 'Hold' }]), /card is on screen/) - // A look-alike label is not the approval. - fromBot('writer', 'chief', 'Ship it again') - assert.match(await ask('writer', [{ label: 'deploy to production now' }, { label: 'Hold' }]), /^This job came from Chief/) + 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', async (t) => { - const { rt, ask, fromBot, stop } = await start() +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) => { @@ -201,7 +219,7 @@ test('PLAN-APPROVED from a Main Bot turns plan mode off', async (t) => { 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], ['Coder', 'Chief', 'plan-approved', 'committed']) + 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) => { @@ -243,7 +261,7 @@ test('an ORDER from a Bot that is not a Main Bot changes nothing and says why', 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-main']) + assert.deepEqual([entry.tool, entry.outcome], ['order', 'sender-not-manager']) }) test('ORDER mid-text is not an order', async (t) => { @@ -408,3 +426,68 @@ test('DSH_PLAN_DEFAULT_OFF=off leaves plan mode alone', async (t) => { 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/view-reply.test.js b/ds-bot/test/view-reply.test.js index 6b22b5f3fe..db2d0862ba 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) From 34560c3bfe0afac70d1c0b38caa2dd7c7d004696 Mon Sep 17 00:00:00 2001 From: Steve Dempsey Date: Tue, 3 Nov 2026 17:54:01 -0500 Subject: [PATCH 08/18] Move the repo state record off the public fork The five root state files (CURRENT_STATE, DEPLOYMENT_LEDGER, NEXT_SESSION_PROMPT, OPEN_ISSUES, VERIFICATION_RESULTS) carried local paths, Bot names, session ids and job names. This fork is public, so the record moves to a private home and this branch keeps code only. The files are kept byte for byte outside the repo; no secrets were in them. --- CURRENT_STATE.md | 11 ----------- DEPLOYMENT_LEDGER.md | 12 ------------ NEXT_SESSION_PROMPT.md | 12 ------------ OPEN_ISSUES.md | 9 --------- VERIFICATION_RESULTS.md | 17 ----------------- 5 files changed, 61 deletions(-) delete mode 100644 CURRENT_STATE.md delete mode 100644 DEPLOYMENT_LEDGER.md delete mode 100644 NEXT_SESSION_PROMPT.md delete mode 100644 OPEN_ISSUES.md delete mode 100644 VERIFICATION_RESULTS.md diff --git a/CURRENT_STATE.md b/CURRENT_STATE.md deleted file mode 100644 index b2f91c7f3b..0000000000 --- a/CURRENT_STATE.md +++ /dev/null @@ -1,11 +0,0 @@ -# CURRENT_STATE (ds-bot, NeoTech installed stack) - -## 2026-11-03 dsbot-027-upgrade: 0.2.7 plus local patches installed and proven live - -- The live profile `C:\Users\SteveDempsey\.dsh\profiles\desktop` runs ds-bot 0.2.7 with the local patch stack replayed on top. -- Branch `stack/installed-0.2.7` on the fork (neotechnet/DS-Bot), head `9603b01`, two commits over upstream `v0.2.7`: `21eff5d` (carry the 0.2.6 stack onto 0.2.7) and `9603b01` (write the card gate log synchronously). -- PR https://github.com/neotechnet/DS-Bot/pull/4, base `upstream/v0.2.7`. It records the installed stack; it is not merged and is not meant for upstream as is. -- Installed 2026-11-03 19:52:28Z to 19:52:37Z with `pnpm install`: 82 of 82 files match `9603b01`, patch_hash `73316542d9efddc6b01a6c36f13d71dab5922c272b97d6c8ae828f499e9ecba9`. -- DeepSeek Harness 0.2.1-rc.5 restarted twice afterwards (about 21:12Z and 21:38Z). All five phase 4 proofs pass on the second boot (see VERIFICATION_RESULTS.md). -- Rollback: copy back the 3 files in `C:\Users\SteveDempsey\.claude\Exports\2026-11-03_dsbot-pre-027-snapshot\` and run `pnpm install` in the profile. -- Known red: the CI leak scan, accepted under LE-20261103-033 (the `dsh-bot:sessions` to `ds-bot:sessions` rename). diff --git a/DEPLOYMENT_LEDGER.md b/DEPLOYMENT_LEDGER.md deleted file mode 100644 index 1433de1c6b..0000000000 --- a/DEPLOYMENT_LEDGER.md +++ /dev/null @@ -1,12 +0,0 @@ -# DEPLOYMENT_LEDGER (ds-bot, NeoTech installed stack) - -ds-bot is local desktop software. Nothing deploys on merge; a change ships only when it is installed into the live profile and proven running. - -## 2026-11-03 ds-bot 0.2.7 plus local stack into the live desktop profile - -- Target: `C:\Users\SteveDempsey\.dsh\profiles\desktop` (DeepSeek Harness 0.2.1-rc.5). -- Source: `stack/installed-0.2.7` at `9603b01` (fork PR #4). -- Installed: 2026-11-03 19:52:28Z to 19:52:37Z, `pnpm install` (pnpm 11.28.5) exit 0. patch_hash `73316542d9efddc6b01a6c36f13d71dab5922c272b97d6c8ae828f499e9ecba9`. -- Live from: app restart about 21:12Z, again 21:38Z (operator restarts, not forced by the agent). -- Proven: all five phase 4 proofs, see VERIFICATION_RESULTS.md 2026-11-03. -- Previous: 0.2.6 plus local stack. Snapshot `C:\Users\SteveDempsey\.claude\Exports\2026-11-03_dsbot-pre-027-snapshot\`. diff --git a/NEXT_SESSION_PROMPT.md b/NEXT_SESSION_PROMPT.md deleted file mode 100644 index 54a6081af5..0000000000 --- a/NEXT_SESSION_PROMPT.md +++ /dev/null @@ -1,12 +0,0 @@ -# NEXT_SESSION_PROMPT (ds-bot, NeoTech installed stack) - snapshot 2026-11-03 - -ds-bot 0.2.7 plus the local stack is installed and proven live (fork branch `stack/installed-0.2.7`, head `9603b01`, PR neotechnet/DS-Bot#4). Read CURRENT_STATE.md and VERIFICATION_RESULTS.md first. - -Next, in order: -1. Close fork PRs #1 to #3 if still open, delete their branches, read back. -2. 06-ds-bot-plugin.md playbook draft to Igor. -3. dsbot-view-guard-patch-name write-up. -4. dsbot-card-routing-overlord (approved, Choice A plus H3): new worktree from `stack/installed-0.2.7`, scope `ds-bot/src/host`, `ds-bot/test`. -5. LE-20261103-033 rename, due 2026-11-10. - -Rules: never write `~\.dsh\bot\state.json`; never force-restart the app; proof from live reads only. For hand-back proofs, decode the session logs (`C:\Projects\logs\2026-11-03-dsbot-027\tools\scan_handback.mjs`), not chat-index.sqlite alone. diff --git a/OPEN_ISSUES.md b/OPEN_ISSUES.md deleted file mode 100644 index d4c3f1a0c6..0000000000 --- a/OPEN_ISSUES.md +++ /dev/null @@ -1,9 +0,0 @@ -# OPEN_ISSUES (ds-bot, NeoTech installed stack) - snapshot 2026-11-03 - -- LE-20261103-033: rename `dsh-bot:sessions` to `ds-bot:sessions` in ds-bot and deepseek-harness, Harness listening on both names for one release. Owner Harness Code, due 2026-11-10. Clears the red CI leak scan, which stays accepted until then. -- dsbot-card-routing-overlord: PLAN-APPROVED (Choice A plus H3), queued. Drop the `refuseCard` production-label exemption (card-gate.js line 83), gate interactive show_view in gated turns, log allowed cards with the deciding label, accept a non-Main manager on the PLAN-APPROVED release (today `sender-not-main`), tests for all. -- dsbot-view-guard-patch-name: change write-up for `ds_bot_view_guard.py` (Harness Code writes the description only, not the file). -- 06-ds-bot-plugin.md playbook draft for Igor. -- Fork PRs #1 to #3 on neotechnet/DS-Bot to close (superseded by #4). -- chat-index.sqlite lags the session logs (seen 2026-11-03, index 30 min behind). Any proof that reads only the index can miss recent events; read the session logs. -- Not ours: H1 and H2 (guard-composio-write-coverage) belong to NeoTech Code. diff --git a/VERIFICATION_RESULTS.md b/VERIFICATION_RESULTS.md deleted file mode 100644 index 983359a0d6..0000000000 --- a/VERIFICATION_RESULTS.md +++ /dev/null @@ -1,17 +0,0 @@ -# VERIFICATION_RESULTS (ds-bot, NeoTech installed stack) - -## 2026-11-03 dsbot-027-upgrade: phase 4 live proof, all five PASS - -Evidence folder: `C:\Projects\logs\2026-11-03-dsbot-027\`. - -| # | Proof | Result | Evidence | -|---|---|---|---| -| 0 | Gates before install | npm test 1660 run, 1658 pass, 0 fail, 2 skipped. `build-client --check` exit 0. Lint 0 errors. CI run 41704581395: Node 22 and Node 24 green, leak scan red (LE-20261103-033). | `gate-test-2.txt`, `gate-check.txt`, `gate-lint.txt` | -| 0 | Install read-back | 82 of 82 installed files match `9603b01`, all 9 markers present. | `live-compare.json`, `live-markers.txt` | -| 1 | Processes started after the install | 30 processes, earliest 2026-11-03T21:38:51.80Z, main window PID 47400; old PIDs gone. | `phase4-processes-2.json` | -| 2 | Gate loaded after restart | `card-gate.log` gate-loaded lines at 21:13:14.662Z and 21:39:25.029Z. | `C:\Users\SteveDempsey\.dsh\bot\logs\card-gate.log` | -| 3 | void_question in the installed build | installed package.json 0.2.7; void_question in constants.js:67, tools.js:714, privacy.js:198, prompt.js:34, turns.js:283. | live profile `node_modules\ds-bot\src\host\` | -| 4 | HANDED_BACK fires | PASS. Igor's session `session-bbf16cbd` seq 1479 at 2026-11-03T21:48:10.750Z: message from Eye In The Sky with `source.deferred=true, handedBack=true`, answered at seq 1480. First boot also fired at seq 1279, 21:29:10.580Z. | `phase4-handedback-pass.txt` (sha256 84826C04...91B4D6), `phase4-handedback-scan.txt` | -| 5 | Screenshot of the running GUI | PASS. Full window 2584x1529 at DPI 168, captured DPI aware; chat text wraps inside its bubble. The earlier 1477x874 capture was DPI unaware and cropped to the top-left 57% (the vision SUSPECT "cut off at the right edge" was that crop). | `phase4-gui-3.png` sha256 A88ACDB9...46364F, `phase4-gui-3.json`; superseded `phase4-gui-2.png` | - -Note on #4: `chat-index.sqlite` lags the session logs (max row 21:22:14Z at read time), so an index-only read reports no hand-back after the restart. The pass comes from decoding the zstd session logs frame by frame (`tools\scan_handback.mjs`). From 41186163dd9077126d79801f864eaa823e34ca65 Mon Sep 17 00:00:00 2001 From: Steve Dempsey Date: Wed, 4 Nov 2026 13:26:16 -0500 Subject: [PATCH 09/18] Show each Bot's Active and Unresolved tasks for the operator Steve wants to stop guessing what an agent still needs from him. The details panel gets two sections below Scheduled tasks, and the chat header shows how many Unresolved tasks a Bot has, with no number at 0. Unresolved is what waits on the operator: open question and answer cards, pending key requests, tool approvals, and open decision loose ends the Bot owns in ~/.claude/state/loose-ends/register.jsonl, which is read only (config looseEnds or DS_BOT_LOOSE_ENDS can move it, false turns it off). Active is derived: the running turn, orders other Bots handed it, and who it waits on. Git, CI and merges reach none of these sources, so nothing needs filtering out. The list rides in the live part of the state answer, so the count follows a card being answered or a decision closing without a reload. --- ds-bot/client.js | 3802 ++++++++++++++------------- ds-bot/index.js | 3 +- ds-bot/src/client/details-drawer.js | 2 + ds-bot/src/client/header.js | 2 + ds-bot/src/client/i18n.js | 25 + ds-bot/src/client/index.js | 3 + ds-bot/src/client/operator-tasks.js | 87 + ds-bot/src/client/sources.js | 2 +- ds-bot/src/host/channel.js | 1 + ds-bot/src/host/operator-tasks.js | 137 + ds-bot/test/operator-tasks.test.js | 145 + 11 files changed, 2364 insertions(+), 1845 deletions(-) create mode 100644 ds-bot/src/client/operator-tasks.js create mode 100644 ds-bot/src/host/operator-tasks.js create mode 100644 ds-bot/test/operator-tasks.test.js diff --git a/ds-bot/client.js b/ds-bot/client.js index 1757630a7e..cb98ee124d 100644 --- a/ds-bot/client.js +++ b/ds-bot/client.js @@ -1173,6 +1173,31 @@ var ZH = { "New task": "新建任务", "No scheduled tasks yet.": "还没有定时任务。", "No scheduled tasks yet. Add one": "还没有定时任务,去添加", + "Active Tasks": "进行中的任务", + "Unresolved Tasks": "待你处理的任务", + "{title} · {count}": "{title} · {count}", + "Nothing running right now.": "现在没有在进行的工作。", + "Nothing waiting on you.": "没有等你处理的事。", + "1 task waits on you": "有 1 件事等你处理", + "{count} tasks wait on you": "有 {count} 件事等你处理", + "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 或群聊", @@ -1367,14 +1392,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) { @@ -1385,7 +1410,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; }; @@ -1580,8 +1605,8 @@ function bodyOf(def, paint, flat = false) { return ""; } } -var eyeMarkup = ([cx, cy, w, h52, tilt]) => ``; -var happyEyeMarkup = ([cx, cy, w, h52, tilt]) => ``; +var eyeMarkup = ([cx, cy, w, h53, tilt]) => ``; +var happyEyeMarkup = ([cx, cy, w, h53, 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%"; @@ -1636,7 +1661,7 @@ function createSource(initial) { } }; } -var EMPTY_ROSTER = { revision: -1, mainBotId: null, mainBotIds: [], bots: [], rooms: [], agents: [], 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: [], 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([ @@ -1864,8 +1889,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), @@ -2360,12 +2385,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 h52 = dt / steps; + const h53 = dt / steps; let moving = false; for (const value of values.values()) { for (let index = 0; index < steps; index += 1) { - value.v += (-value.k * (value.x - value.to) - value.c * value.v) * h52; - value.x += value.v * h52; + value.v += (-value.k * (value.x - value.to) - value.c * value.v) * h53; + value.x += value.v * h53; } if (Math.abs(value.x - value.to) < 0.05 && Math.abs(value.v) < 1) { value.x = value.to; @@ -11221,16 +11246,103 @@ var SIDEBAR_CSS = ` @media (prefers-reduced-motion:reduce){.bt-agent-sub{transition:none}.bt-agent-sub .bt-agent-sub-row{animation:none}} `; -// src/client/header.js +// src/client/operator-tasks.js var import_react22 = require("react"); +var EMPTY = { active: [], unresolved: [] }; +var operatorTasksOf = (roster, botId) => roster.operatorTasks?.[botId] ?? EMPTY; +var unresolvedCount = (roster, botId) => operatorTasksOf(roster, botId).unresolved.length; +var nameOf = (roster, id) => roster.byId?.[id]?.name ?? roster.roomsById?.[id]?.name ?? t("a teammate"); +var where = (roster, item) => item.roomId ? t('in group "{name}"', { name: roster.roomsById?.[item.roomId]?.name ?? t("a group") }) : ""; +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 ?? "" }; + } +} +function activeLine(item, roster) { + switch (item.kind) { + case "turn": { + const doing = item.switching ? t("Moving on to a fresh part") : item.tool ? item.target ? t("Running {tool} on {target}", { tool: item.tool, target: item.target }) : t("Running {tool}", { tool: item.tool }) : item.text || t("Working"); + return { label: t("Working now"), text: [doing, where(roster, item)].filter(Boolean).join(" ") }; + } + case "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 ?? "" }; + } +} +function TaskList({ title, items, line, roster, empty }) { + return (0, import_react22.createElement)( + "div", + { className: "bt-ops" }, + (0, import_react22.createElement)("div", { className: "bt-section-title" }, items.length === 0 ? title : t("{title} · {count}", { title, count: items.length })), + items.length === 0 ? (0, import_react22.createElement)("div", { className: "bt-ops-empty" }, empty) : (0, import_react22.createElement)("ul", { className: "bt-ops-list" }, items.map((item) => { + const shown = line(item, roster); + return (0, import_react22.createElement)( + "li", + { key: item.key, className: "bt-ops-item", "data-kind": item.kind }, + (0, import_react22.createElement)( + "div", + { className: "bt-ops-top" }, + (0, import_react22.createElement)("span", { className: "bt-ops-label" }, shown.label), + item.at ? (0, import_react22.createElement)("span", { className: "bt-ops-age", title: new Date(item.at).toLocaleString() }, relativeShort(item.at)) : null + ), + shown.text ? (0, import_react22.createElement)("div", { className: "bt-ops-text" }, shown.text) : null, + shown.note ? (0, import_react22.createElement)("div", { className: "bt-ops-note" }, shown.note) : null + ); + })) + ); +} +function OperatorTasks({ bot, roster }) { + const tasks = operatorTasksOf(roster, bot.id); + return [ + (0, import_react22.createElement)(TaskList, { key: "active", title: t("Active Tasks"), items: tasks.active, line: activeLine, roster, empty: t("Nothing running right now.") }), + (0, import_react22.createElement)(TaskList, { key: "unresolved", title: t("Unresolved Tasks"), items: tasks.unresolved, line: unresolvedLine, roster, empty: t("Nothing waiting on you.") }) + ]; +} +function UnresolvedBadge({ count }) { + if (!(count > 0)) return null; + const label = count === 1 ? t("1 task waits on you") : t("{count} tasks wait on you", { count }); + return (0, import_react22.createElement)("span", { className: "bt-pill-tasks", title: label, "aria-label": label }, count > 99 ? "99+" : String(count)); +} +var 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;min-width:18px;height:18px;padding:0 5px;border-radius:999px;background:var(--bt-danger);color:var(--bt-main);font-size:11px;line-height:18px;font-weight:600;text-align:center;font-variant-numeric:tabular-nums} +`; + +// src/client/header.js +var import_react23 = require("react"); var import_react_dom4 = require("react-dom"); -var GoArrow = () => (0, import_react22.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_react22.createElement)("path", { d: "M-7 0H7M2 -5L7 0L2 5" })); +var GoArrow = () => (0, import_react23.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_react23.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_react22.useState)(false); - (0, import_react22.useEffect)(() => { + const [shown, setShown] = (0, import_react23.useState)(false); + (0, import_react23.useEffect)(() => { const left = seen + MEMORY_NOTICE_MS - Date.now(); setShown(seen > 0 && left > 0); if (seen === 0 || left <= 0) return void 0; @@ -11240,16 +11352,16 @@ function useMemoryNotice(ids, useMemoryNews) { return shown; } function MemoryNotice({ shown }) { - const inner = (0, import_react22.useRef)(null); - const [width, setWidth] = (0, import_react22.useState)(0); + const inner = (0, import_react23.useRef)(null); + const [width, setWidth] = (0, import_react23.useState)(0); const label = t("Memory updated"); - (0, import_react22.useLayoutEffect)(() => { + (0, import_react23.useLayoutEffect)(() => { if (shown) setWidth(inner.current?.scrollWidth ?? 0); }, [label, shown]); - return (0, import_react22.createElement)( + return (0, import_react23.createElement)( "span", { className: "bt-pill-mem", "aria-hidden": true, style: { "--bt-mem-w": `${width}px` } }, - (0, import_react22.createElement)("span", { className: "bt-pill-mem-in", ref: inner }, (0, import_react22.createElement)("span", { className: "bt-pill-mem-ico" }, (0, import_react22.createElement)(MemoryIcon)), label) + (0, import_react23.createElement)("span", { className: "bt-pill-mem-in", ref: inner }, (0, import_react23.createElement)("span", { className: "bt-pill-mem-ico" }, (0, import_react23.createElement)(MemoryIcon)), label) ); } function HeaderPill({ sessionId, useRoster, useSessions, useSessionStatus, useSession, useActivity, useMemoryNews, useTurnClock, useUi, useLive, useWork, useStore, useConversationViews, selectView, actions }) { @@ -11267,7 +11379,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_react22.useEffect)(() => { + (0, import_react23.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"); @@ -11290,17 +11402,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_react22.useEffect)(() => { + (0, import_react23.useEffect)(() => { document.body.style.setProperty("--bt-placeholder", JSON.stringify(name ? t("Message {name}", { name }) : t("Message"))); }, [name, t("Message")]); - (0, import_react22.useEffect)(() => { + (0, import_react23.useEffect)(() => { document.body.style.setProperty("--bt-steer-unread", JSON.stringify(t("Not read yet"))); }, [t("Not read yet")]); - (0, import_react22.useEffect)(() => { + (0, import_react23.useEffect)(() => { actions.beginVisit(sessionId); return () => actions.endVisit(sessionId); }, [sessionId]); - (0, import_react22.useEffect)(() => { + (0, import_react23.useEffect)(() => { if (room2) document.body.dataset.btRoom = ""; else delete document.body.dataset.btRoom; return () => { @@ -11309,14 +11421,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_react22.useEffect)(() => { + (0, import_react23.useEffect)(() => { if (showGoal) document.body.dataset.btGoal = ""; else delete document.body.dataset.btGoal; return () => { delete document.body.dataset.btGoal; }; }, [showGoal]); - const pill = (0, import_react22.createElement)( + const pill = (0, import_react23.createElement)( "button", { type: "button", @@ -11327,29 +11439,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_react22.createElement)(BotAvatar, { bot, size: 24, state: botState(running, doing, roster.questions?.[currentPart(bot)] !== void 0), badge: false }) : room2 ? (0, import_react22.createElement)(RoomAvatar, { room: room2, roster, size: 24 }) : null, - goalShown ? (0, import_react22.createElement)( + bot ? (0, import_react23.createElement)(BotAvatar, { bot, size: 24, state: botState(running, doing, roster.questions?.[currentPart(bot)] !== void 0), badge: false }) : room2 ? (0, import_react23.createElement)(RoomAvatar, { room: room2, roster, size: 24 }) : null, + goalShown ? (0, import_react23.createElement)( "span", { className: "bt-pill-swap" }, - (0, import_react22.createElement)("span", { className: "bt-pill-goal" }, (0, import_react22.createElement)("span", { className: "bt-pill-ico", "aria-hidden": true }, (0, import_react22.createElement)(GoalIcon)), (0, import_react22.createElement)("span", { className: "bt-pill-title" }, view.title)), - (0, import_react22.createElement)("span", { className: "bt-pill-name" }, name) - ) : (0, import_react22.createElement)("span", { className: "bt-pill-name" }, away ? t("Back to chat") : bot?.name ?? room2?.name ?? (title || t("New chat"))), - goalShown && view?.number !== void 0 ? (0, import_react22.createElement)("span", { className: "bt-pill-count" }, `${view.number}/${view.count}`) : null, - (0, import_react22.createElement)(MemoryNotice, { shown: memoryNotice }), - (0, import_react22.createElement)("span", { className: "bt-pill-go", "aria-hidden": true }, (0, import_react22.createElement)(GoArrow)) + (0, import_react23.createElement)("span", { className: "bt-pill-goal" }, (0, import_react23.createElement)("span", { className: "bt-pill-ico", "aria-hidden": true }, (0, import_react23.createElement)(GoalIcon)), (0, import_react23.createElement)("span", { className: "bt-pill-title" }, view.title)), + (0, import_react23.createElement)("span", { className: "bt-pill-name" }, name) + ) : (0, import_react23.createElement)("span", { className: "bt-pill-name" }, away ? t("Back to chat") : bot?.name ?? room2?.name ?? (title || t("New chat"))), + bot && !away ? (0, import_react23.createElement)(UnresolvedBadge, { count: unresolvedCount(roster, bot.id) }) : null, + goalShown && view?.number !== void 0 ? (0, import_react23.createElement)("span", { className: "bt-pill-count" }, `${view.number}/${view.count}`) : null, + (0, import_react23.createElement)(MemoryNotice, { shown: memoryNotice }), + (0, import_react23.createElement)("span", { className: "bt-pill-go", "aria-hidden": true }, (0, import_react23.createElement)(GoArrow)) ); - return (0, import_react22.createElement)( + return (0, import_react23.createElement)( "div", { className: "bt-head" }, - showGoal ? (0, import_react22.createElement)(GoalIsland, { room: room2, goal, view, open: goalOpen, composing: goalCompose, roomWork, roster, actions, pill }) : pill, - (0, import_react22.createElement)("span", { className: "bt-sr", role: "status" }, memoryNotice ? t("Memory updated") : ""), - (0, import_react22.createElement)(NewMessagePills, { key: sessionId, sessionId, useSessions, useUi, useTurnClock }), - (0, import_react22.createElement)(ActivityIndicator, { key: `activity:${sessionId}`, sessionId, useRoster, useSessionStatus, useSession, useLive, useWork, actions }) + showGoal ? (0, import_react23.createElement)(GoalIsland, { room: room2, goal, view, open: goalOpen, composing: goalCompose, roomWork, roster, actions, pill }) : pill, + (0, import_react23.createElement)("span", { className: "bt-sr", role: "status" }, memoryNotice ? t("Memory updated") : ""), + (0, import_react23.createElement)(NewMessagePills, { key: sessionId, sessionId, useSessions, useUi, useTurnClock }), + (0, import_react23.createElement)(ActivityIndicator, { key: `activity:${sessionId}`, sessionId, useRoster, useSessionStatus, useSession, useLive, useWork, actions }) ); } function useTranscriptView() { - const [view, setView] = (0, import_react22.useState)(null); - (0, import_react22.useEffect)(() => { + const [view, setView] = (0, import_react23.useState)(null); + (0, import_react23.useEffect)(() => { let frame = 0; let watched = null; const observer = new MutationObserver(() => schedule()); @@ -11418,18 +11531,18 @@ function NewMessagePills({ sessionId, useSessions, useUi, useTurnClock }) { }); const view = useTranscriptView(); const unpinned = view?.unpinned === true; - const [release, setRelease] = (0, import_react22.useState)({ base: null, dismissed: false }); - const [above, setAbove] = (0, import_react22.useState)({ seen: false, dismissed: false }); - (0, import_react22.useEffect)(() => { + const [release, setRelease] = (0, import_react23.useState)({ base: null, dismissed: false }); + const [above, setAbove] = (0, import_react23.useState)({ seen: false, dismissed: false }); + (0, import_react23.useEffect)(() => { setRelease({ base: unpinned ? replies : null, dismissed: false }); }, [unpinned]); - (0, import_react22.useEffect)(() => { + (0, import_react23.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_react22.useEffect)(() => { + (0, import_react23.useEffect)(() => { const scroller = document.querySelector("[data-conversation-scroll]"); if (!scroller) return void 0; scroller.toggleAttribute("data-bt-news", showDown); @@ -11437,16 +11550,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_react22.createElement)( + const pill = (direction, count, style, onJump, onDismiss) => (0, import_react23.createElement)( "div", { className: "bt-news", "data-direction": direction, style }, - (0, import_react22.createElement)( + (0, import_react23.createElement)( "button", { type: "button", className: "bt-news-jump", onClick: onJump }, - (0, import_react22.createElement)("span", { className: "bt-news-ico" }, (0, import_react22.createElement)(direction === "up" ? ArrowUpIcon : ArrowDownIcon)), + (0, import_react23.createElement)("span", { className: "bt-news-ico" }, (0, import_react23.createElement)(direction === "up" ? ArrowUpIcon : ArrowDownIcon)), label(count) ), - (0, import_react22.createElement)("button", { + (0, import_react23.createElement)("button", { type: "button", className: "bt-news-x", "aria-label": t("Dismiss new messages"), @@ -11454,7 +11567,7 @@ function NewMessagePills({ sessionId, useSessions, useUi, useTurnClock }) { event.stopPropagation(); onDismiss(); } - }, (0, import_react22.createElement)(CloseIcon)) + }, (0, import_react23.createElement)(CloseIcon)) ); const toLatest = () => { const scroller = document.querySelector("[data-conversation-scroll]"); @@ -11464,8 +11577,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_dom4.createPortal)( - (0, import_react22.createElement)( - import_react22.Fragment, + (0, import_react23.createElement)( + import_react23.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 @@ -11493,18 +11606,18 @@ var steerQueued = async (session) => { }; // src/client/composer.js -var import_react23 = require("react"); +var import_react24 = require("react"); var import_react_dom5 = require("react-dom"); var speechApi = () => window.SpeechRecognition ?? window.webkitSpeechRecognition; var keepComposerFocus = (event) => event.preventDefault(); function useDictation(onText) { - const [listening, setListening] = (0, import_react23.useState)(false); - const [note, setNote] = (0, import_react23.useState)(""); - const recognition = (0, import_react23.useRef)(null); - const latest = (0, import_react23.useRef)(onText); + const [listening, setListening] = (0, import_react24.useState)(false); + const [note, setNote] = (0, import_react24.useState)(""); + const recognition = (0, import_react24.useRef)(null); + const latest = (0, import_react24.useRef)(onText); latest.current = onText; - (0, import_react23.useEffect)(() => () => recognition.current?.abort(), []); - (0, import_react23.useEffect)(() => { + (0, import_react24.useEffect)(() => () => recognition.current?.abort(), []); + (0, import_react24.useEffect)(() => { if (!note) return void 0; const timer = setTimeout(() => setNote(""), 2600); return () => clearTimeout(timer); @@ -11554,8 +11667,8 @@ function useDictation(onText) { } function ComposerVoice({ sessionId, inputActions, actions, useUi, useRoster }) { const enterToSend = useRoster((state) => sendsOnEnter(state.prefs)); - const composerRoot = (0, import_react23.useRef)(null); - (0, import_react23.useEffect)(() => { + const composerRoot = (0, import_react24.useRef)(null); + (0, import_react24.useEffect)(() => { const root = composerRoot.current?.closest("[data-composer-card]"); if (enterToSend || !inputActions || !root) return void 0; const onKey = (event) => insertComposerNewline(event, inputActions); @@ -11566,7 +11679,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_react23.useEffect)(() => { + (0, import_react24.useEffect)(() => { if (!quote || !inputActions) return; actions.clearQuote(quote.token); const excerpt = quote.text.replace(/\s+/g, " ").trim(); @@ -11584,10 +11697,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_react23.createElement)( - import_react23.Fragment, + return (0, import_react24.createElement)( + import_react24.Fragment, null, - pluginMic ? null : (0, import_react23.createElement)("button", { + pluginMic ? null : (0, import_react24.createElement)("button", { type: "button", className: "bt-mic", "aria-label": dictation.listening ? t("Stop dictation") : t("Dictate"), @@ -11595,8 +11708,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_react23.createElement)(MicIcon)), - (0, import_react23.createElement)("button", { + }, (0, import_react24.createElement)(MicIcon)), + (0, import_react24.createElement)("button", { ref: composerRoot, type: "button", className: "bt-voice", @@ -11604,8 +11717,8 @@ function ComposerVoice({ sessionId, inputActions, actions, useUi, useRoster }) { title: t("Voice chat"), onMouseDown: keepComposerFocus, onClick: () => actions.openVoice(sessionId) - }, (0, import_react23.createElement)(WaveIcon, { size: 18 })), - dictation.note ? (0, import_react23.createElement)("span", { className: "bt-mic-note", role: "status" }, dictation.note) : null + }, (0, import_react24.createElement)(WaveIcon, { size: 18 })), + dictation.note ? (0, import_react24.createElement)("span", { className: "bt-mic-note", role: "status" }, dictation.note) : null ); } function menuIcons(roster) { @@ -11613,23 +11726,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_react23.createElement)(BotMark, { bot: roster.getSnapshot().byId[id] ?? row.bot, size })); + if (!marks.has(id)) marks.set(id, ({ size = 14 }) => (0, import_react24.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_react23.useState)(null); + const [open, setOpen] = (0, import_react24.useState)(null); const [shown, leaving] = useLinger(open, 120); - const button = (0, import_react23.useRef)(null); - const menu = (0, import_react23.useRef)(null); + const button = (0, import_react24.useRef)(null); + const menu = (0, import_react24.useRef)(null); const tick = useViewport(); - const inputNow = (0, import_react23.useRef)(void 0); + const inputNow = (0, import_react24.useRef)(void 0); const ready = useInput?.((state) => { inputNow.current = state; return steerable(state); }) === true; - (0, import_react23.useEffect)(() => { + (0, import_react24.useEffect)(() => { if (!open) return void 0; const onDown = (event) => { if (![button.current, menu.current].some((node) => node?.contains(event.target))) setOpen(null); @@ -11647,13 +11760,13 @@ function ComposerPlus({ sessionId, inputActions, useInput, useRoster, actions }) window.removeEventListener("keydown", onKey, true); }; }, [open]); - (0, import_react23.useEffect)(() => { + (0, import_react24.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_react23.useEffect)(() => { + (0, import_react24.useEffect)(() => { let steering = false; const onKey = (event) => { if (steering || event.defaultPrevented || open) return; @@ -11675,7 +11788,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_react23.useMemo)(() => { + const place = (0, import_react24.useMemo)(() => { if (!shown || !button.current) return null; const rect = button.current.getBoundingClientRect(); return { left: rect.left, bottom: viewBottom() - rect.top + 8 }; @@ -11708,10 +11821,10 @@ function ComposerPlus({ sessionId, inputActions, useInput, useRoster, actions }) setOpen(null); actions.composeGoal(room2.id); }; - return (0, import_react23.createElement)( - import_react23.Fragment, + return (0, import_react24.createElement)( + import_react24.Fragment, null, - (0, import_react23.createElement)("button", { + (0, import_react24.createElement)("button", { ref: button, type: "button", className: "bt-plus", @@ -11721,8 +11834,8 @@ function ComposerPlus({ sessionId, inputActions, useInput, useRoster, actions }) "aria-expanded": Boolean(open), onMouseDown: keepComposerFocus, onClick: toggle - }, (0, import_react23.createElement)(PlusIcon)), - shown ? (0, import_react_dom5.createPortal)((0, import_react23.createElement)( + }, (0, import_react24.createElement)(PlusIcon)), + shown ? (0, import_react_dom5.createPortal)((0, import_react24.createElement)( "div", { ref: menu, @@ -11732,10 +11845,10 @@ function ComposerPlus({ sessionId, inputActions, useInput, useRoster, actions }) style: place ?? {}, "data-leaving": leaving || void 0 }, - shown.files ? (0, import_react23.createElement)("button", { type: "button", role: "menuitem", onClick: attach }, (0, import_react23.createElement)(PaperclipIcon), (0, import_react23.createElement)("span", { className: "bt-menu-label" }, t("Add files"))) : null, - canReference ? (0, import_react23.createElement)("button", { type: "button", role: "menuitem", onMouseDown: keepComposerFocus, onClick: reference }, (0, import_react23.createElement)(ChatsIcon), (0, import_react23.createElement)("span", { className: "bt-menu-label" }, t("Reference a chat"))) : null, - canSetGoal(room2, roster) ? (0, import_react23.createElement)("button", { type: "button", role: "menuitem", onClick: goal }, (0, import_react23.createElement)(GoalIcon), (0, import_react23.createElement)("span", { className: "bt-menu-label" }, t("Set a goal"))) : null, - (0, import_react23.createElement)("button", { type: "button", role: "menuitem", onClick: schedule }, (0, import_react23.createElement)(ClockIcon), (0, import_react23.createElement)("span", { className: "bt-menu-label" }, t("Scheduled task"))) + shown.files ? (0, import_react24.createElement)("button", { type: "button", role: "menuitem", onClick: attach }, (0, import_react24.createElement)(PaperclipIcon), (0, import_react24.createElement)("span", { className: "bt-menu-label" }, t("Add files"))) : null, + canReference ? (0, import_react24.createElement)("button", { type: "button", role: "menuitem", onMouseDown: keepComposerFocus, onClick: reference }, (0, import_react24.createElement)(ChatsIcon), (0, import_react24.createElement)("span", { className: "bt-menu-label" }, t("Reference a chat"))) : null, + canSetGoal(room2, roster) ? (0, import_react24.createElement)("button", { type: "button", role: "menuitem", onClick: goal }, (0, import_react24.createElement)(GoalIcon), (0, import_react24.createElement)("span", { className: "bt-menu-label" }, t("Set a goal"))) : null, + (0, import_react24.createElement)("button", { type: "button", role: "menuitem", onClick: schedule }, (0, import_react24.createElement)(ClockIcon), (0, import_react24.createElement)("span", { className: "bt-menu-label" }, t("Scheduled task"))) ), document.body) : null ); } @@ -11961,9 +12074,9 @@ function drawerMenuKeys({ bot, room: room2, canBrowse, canTerminal, canFiles }) } // src/client/side-chat.js -var import_react24 = require("react"); +var import_react25 = require("react"); function SideEntry({ chatId, entry, actions }) { - const [cancelling, setCancelling] = (0, import_react24.useState)(false); + const [cancelling, setCancelling] = (0, import_react25.useState)(false); const question = typeof entry.question === "string" ? entry.question : ""; const answer = typeof entry.answer === "string" ? entry.answer : ""; const cancel = () => { @@ -11972,15 +12085,15 @@ function SideEntry({ chatId, entry, actions }) { Promise.resolve(actions.cancelSide(chatId, entry.id)).catch(() => { }).finally(() => setCancelling(false)); }; - return (0, import_react24.createElement)( + return (0, import_react25.createElement)( "div", { className: "bt-side-pair", "data-status": entry.status }, - (0, import_react24.createElement)("div", { className: "bt-side-qrow" }, (0, import_react24.createElement)("div", { className: "bt-side-q" }, question)), - entry.status === "answering" ? (0, import_react24.createElement)( + (0, import_react25.createElement)("div", { className: "bt-side-qrow" }, (0, import_react25.createElement)("div", { className: "bt-side-q" }, question)), + entry.status === "answering" ? (0, import_react25.createElement)( "div", { className: "bt-side-a" }, - (0, import_react24.createElement)("span", { className: "bt-shimmer" }, t("Answering…")), - (0, import_react24.createElement)("button", { + (0, import_react25.createElement)("span", { className: "bt-shimmer" }, t("Answering…")), + (0, import_react25.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: cancelling, @@ -11988,23 +12101,23 @@ function SideEntry({ chatId, entry, actions }) { "aria-label": t("Cancel this side question"), onClick: cancel }, t("Cancel")) - ) : (0, import_react24.createElement)( + ) : (0, import_react25.createElement)( "div", { className: "bt-side-a" }, - entry.status === "cancelled" ? (0, import_react24.createElement)("p", { className: "bt-side-status" }, t("Cancelled")) : null, - entry.status === "failed" ? (0, import_react24.createElement)("p", { className: "bt-side-fail" }, failureText(entry)) : null, - answer !== "" ? (0, import_react24.createElement)(import_dsh_client_ui_primitives.MarkdownText, { text: answer, labels: mdLabels2(), variant: "compact" }) : null + entry.status === "cancelled" ? (0, import_react25.createElement)("p", { className: "bt-side-status" }, t("Cancelled")) : null, + entry.status === "failed" ? (0, import_react25.createElement)("p", { className: "bt-side-fail" }, failureText(entry)) : null, + answer !== "" ? (0, import_react25.createElement)(import_dsh_client_ui_primitives.MarkdownText, { text: answer, labels: mdLabels2(), variant: "compact" }) : null ) ); } function SideChatView({ subject, chat, roster, actions }) { - const scroll = (0, import_react24.useRef)(null); - const [draft, setDraft] = (0, import_react24.useState)(""); - const [fail2, setFail] = (0, import_react24.useState)(null); + const scroll = (0, import_react25.useRef)(null); + const [draft, setDraft] = (0, import_react25.useState)(""); + const [fail2, setFail] = (0, import_react25.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_react24.useEffect)(() => { + (0, import_react25.useEffect)(() => { const node = scroll.current; if (node) node.scrollTop = node.scrollHeight; }, [chat?.id, entries2.length, last?.status]); @@ -12019,19 +12132,19 @@ function SideChatView({ subject, chat, roster, actions }) { setFail(hostText(error?.message ?? "")); }); }; - return (0, import_react24.createElement)( + return (0, import_react25.createElement)( "div", { className: "bt-side" }, - (0, import_react24.createElement)("p", { className: "bt-side-note" }, t("Answered from progress so far; nothing was run")), - (0, import_react24.createElement)( + (0, import_react25.createElement)("p", { className: "bt-side-note" }, t("Answered from progress so far; nothing was run")), + (0, import_react25.createElement)( "div", { className: "bt-side-scroll", ref: scroll }, - entries2.map((entry) => (0, import_react24.createElement)(SideEntry, { key: entry.id, chatId: chat.id, entry, actions })) + entries2.map((entry) => (0, import_react25.createElement)(SideEntry, { key: entry.id, chatId: chat.id, entry, actions })) ), - (0, import_react24.createElement)( + (0, import_react25.createElement)( "div", { className: "bt-side-form" }, - (0, import_react24.createElement)("textarea", { + (0, import_react25.createElement)("textarea", { className: "bt-side-input", rows: 1, value: draft, @@ -12049,14 +12162,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_react24.createElement)("button", { + (0, import_react25.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_react24.createElement)(ArrowUpIcon)), - fail2 !== null ? (0, import_react24.createElement)("p", { className: "bt-side-fail" }, fail2) : null + }, (0, import_react25.createElement)(ArrowUpIcon)), + fail2 !== null ? (0, import_react25.createElement)("p", { className: "bt-side-fail" }, fail2) : null ) ); } @@ -12407,7 +12520,7 @@ function installHeaderNavigation(slots, face, component, priority) { } // src/client/model-menu.js -var import_react25 = require("react"); +var import_react26 = require("react"); var import_react_dom6 = require("react-dom"); var MENU_EXIT_MS = 120; function groupModels(models) { @@ -12437,8 +12550,8 @@ function modelOf(bot, roster) { } var effortCache = /* @__PURE__ */ new Map(); function useEfforts(served, ref, actions) { - const [fetched, setFetched] = (0, import_react25.useState)(void 0); - (0, import_react25.useEffect)(() => { + const [fetched, setFetched] = (0, import_react26.useState)(void 0); + (0, import_react26.useEffect)(() => { setFetched(void 0); if (ref === void 0 || served?.reasoning !== void 0 || actions?.efforts === void 0) return void 0; let live = true; @@ -12463,12 +12576,12 @@ function effortRows(reasoning) { ]; } function EffortRows({ reasoning, current, onPick }) { - return (0, import_react25.createElement)( - import_react25.Fragment, + return (0, import_react26.createElement)( + import_react26.Fragment, null, - (0, import_react25.createElement)("div", { className: "bt-menu-sep", role: "separator" }), - (0, import_react25.createElement)("div", { className: "bt-model-group", role: "presentation" }, t("Thinking level")), - effortRows(reasoning).map((row) => (0, import_react25.createElement)( + (0, import_react26.createElement)("div", { className: "bt-menu-sep", role: "separator" }), + (0, import_react26.createElement)("div", { className: "bt-model-group", role: "presentation" }, t("Thinking level")), + effortRows(reasoning).map((row) => (0, import_react26.createElement)( "button", { key: row.effort ?? "default", @@ -12477,17 +12590,17 @@ function EffortRows({ reasoning, current, onPick }) { "aria-checked": (row.effort ?? null) === (current ?? null), onClick: () => onPick(row.effort) }, - (0, import_react25.createElement)("span", { className: "bt-menu-label" }, row.label), - (0, import_react25.createElement)("span", { className: "bt-model-tick", "aria-hidden": true }, (row.effort ?? null) === (current ?? null) ? (0, import_react25.createElement)(CheckIcon) : null) + (0, import_react26.createElement)("span", { className: "bt-menu-label" }, row.label), + (0, import_react26.createElement)("span", { className: "bt-model-tick", "aria-hidden": true }, (row.effort ?? null) === (current ?? null) ? (0, import_react26.createElement)(CheckIcon) : null) )) ); } function ModelRows({ roster, current, onPick }) { - return groupModels(roster.models).map(([provider, list]) => (0, import_react25.createElement)( - import_react25.Fragment, + return groupModels(roster.models).map(([provider, list]) => (0, import_react26.createElement)( + import_react26.Fragment, { key: list[0].provider ?? provider }, - (0, import_react25.createElement)("div", { className: "bt-model-group", role: "presentation" }, provider), - list.map((model) => (0, import_react25.createElement)( + (0, import_react26.createElement)("div", { className: "bt-model-group", role: "presentation" }, provider), + list.map((model) => (0, import_react26.createElement)( "button", { key: model.ref, @@ -12497,25 +12610,25 @@ function ModelRows({ roster, current, onPick }) { title: model.ref, onClick: () => onPick(model.ref) }, - (0, import_react25.createElement)("span", { className: "bt-menu-label" }, model.name), - model.ref === roster.defaultModel ? (0, import_react25.createElement)("span", { className: "bt-menu-hint" }, t("Default")) : null, - (0, import_react25.createElement)("span", { className: "bt-model-tick", "aria-hidden": true }, model.ref === current ? (0, import_react25.createElement)(CheckIcon) : null) + (0, import_react26.createElement)("span", { className: "bt-menu-label" }, model.name), + model.ref === roster.defaultModel ? (0, import_react26.createElement)("span", { className: "bt-menu-hint" }, t("Default")) : null, + (0, import_react26.createElement)("span", { className: "bt-model-tick", "aria-hidden": true }, model.ref === current ? (0, import_react26.createElement)(CheckIcon) : null) )) )); } -var Caret = () => (0, import_react25.createElement)("svg", { className: "bt-model-caret", width: 12, height: 12, viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: 1.8, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true }, (0, import_react25.createElement)("path", { d: "M5.5 8l4.5 4.5L14.5 8" })); +var Caret = () => (0, import_react26.createElement)("svg", { className: "bt-model-caret", width: 12, height: 12, viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: 1.8, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true }, (0, import_react26.createElement)("path", { d: "M5.5 8l4.5 4.5L14.5 8" })); function useAnchoredMenu() { - const [anchor, setAnchor] = (0, import_react25.useState)(null); - const [place, setPlace] = (0, import_react25.useState)(null); + const [anchor, setAnchor] = (0, import_react26.useState)(null); + const [place, setPlace] = (0, import_react26.useState)(null); const [shownPlace, leaving] = useLinger(place, MENU_EXIT_MS); - const button = (0, import_react25.useRef)(null); - const menu = (0, import_react25.useRef)(null); + const button = (0, import_react26.useRef)(null); + const menu = (0, import_react26.useRef)(null); const tick = useViewport(); const close = () => { setAnchor(null); setPlace(null); }; - (0, import_react25.useEffect)(() => { + (0, import_react26.useEffect)(() => { if (place === null) return void 0; const onDown = (event) => { if (menu.current?.contains(event.target) || button.current?.contains(event.target)) return; @@ -12541,7 +12654,7 @@ function useAnchoredMenu() { }; }, [place]); const open = () => setAnchor({}); - (0, import_react25.useLayoutEffect)(() => { + (0, import_react26.useLayoutEffect)(() => { if (anchor === null || !button.current) return; const rect = button.current.getBoundingClientRect(); const width = Math.max(240, rect.width); @@ -12580,10 +12693,10 @@ function ModelMenu({ bot, roster, actions, run: run2, wide = false, onPick, onPi }; const models = roster.models ?? []; const manage = manageModels(actions); - return (0, import_react25.createElement)( - import_react25.Fragment, + return (0, import_react26.createElement)( + import_react26.Fragment, null, - (0, import_react25.createElement)( + (0, import_react26.createElement)( "button", { ref: button, @@ -12596,34 +12709,34 @@ function ModelMenu({ bot, roster, actions, run: run2, wide = false, onPick, onPi "data-missing": shown !== void 0 && !shown.served && models.length > 0 ? "" : void 0, onClick: toggle }, - (0, import_react25.createElement)( + (0, import_react26.createElement)( "span", { className: "bt-model-copy" }, - (0, import_react25.createElement)("span", { className: "bt-model-name" }, shown?.name ?? t("Choose a model")), - shown ? (0, import_react25.createElement)("span", { className: "bt-model-provider" }, shown.served || models.length === 0 ? !withEfforts || effortLabel === void 0 ? shown.provider : `${shown.provider} · ${effortLabel}` : t("{provider} · not available", { provider: shown.provider })) : null + (0, import_react26.createElement)("span", { className: "bt-model-name" }, shown?.name ?? t("Choose a model")), + shown ? (0, import_react26.createElement)("span", { className: "bt-model-provider" }, shown.served || models.length === 0 ? !withEfforts || effortLabel === void 0 ? shown.provider : `${shown.provider} · ${effortLabel}` : t("{provider} · not available", { provider: shown.provider })) : null ), - (0, import_react25.createElement)(Caret) + (0, import_react26.createElement)(Caret) ), - shownPlace ? (0, import_react_dom6.createPortal)((0, import_react25.createElement)( + shownPlace ? (0, import_react_dom6.createPortal)((0, import_react26.createElement)( "div", { ref: menu, className: `bt-menu bt-model-menu${shownPlace.bottom !== void 0 ? " bt-menu-up" : ""}`, role: "menu", "aria-label": t("Model for {name}", { name: bot.name }), style: shownPlace, "data-leaving": leaving || void 0 }, - models.length > 0 ? (0, import_react25.createElement)(ModelRows, { roster, current, onPick: pick2 }) : (0, import_react25.createElement)("div", { className: "bt-model-none" }, t("No models are set up in DeepSeek Harness yet.")), - withEfforts && effortRows(reasoning).length > 0 ? (0, import_react25.createElement)(EffortRows, { reasoning, current: picked, onPick: pickEffort }) : null, - manage ? (0, import_react25.createElement)("div", { className: "bt-menu-sep", role: "separator" }) : null, - manage ? (0, import_react25.createElement)("button", { type: "button", role: "menuitem", onClick: () => { + models.length > 0 ? (0, import_react26.createElement)(ModelRows, { roster, current, onPick: pick2 }) : (0, import_react26.createElement)("div", { className: "bt-model-none" }, t("No models are set up in DeepSeek Harness yet.")), + withEfforts && effortRows(reasoning).length > 0 ? (0, import_react26.createElement)(EffortRows, { reasoning, current: picked, onPick: pickEffort }) : null, + manage ? (0, import_react26.createElement)("div", { className: "bt-menu-sep", role: "separator" }) : null, + manage ? (0, import_react26.createElement)("button", { type: "button", role: "menuitem", onClick: () => { close(); manage(); - } }, (0, import_react25.createElement)(SlidersIcon), (0, import_react25.createElement)("span", { className: "bt-menu-label" }, t("Models and providers…"))) : null + } }, (0, import_react26.createElement)(SlidersIcon), (0, import_react26.createElement)("span", { className: "bt-menu-label" }, t("Models and providers…"))) : null ), document.body) : null ); } function ModelChoiceDock({ sessionId, useRoster, actions }) { const roster = useRoster((value) => value); const bot = roster.byId[sessionId]; - const [busy, setBusy] = (0, import_react25.useState)(""); - const [error, setError] = (0, import_react25.useState)(""); + const [busy, setBusy] = (0, import_react26.useState)(""); + const [error, setError] = (0, import_react26.useState)(""); const shown = Boolean(bot) && currentPart(bot) === sessionId && roster.ready; - (0, import_react25.useEffect)(() => { + (0, import_react26.useEffect)(() => { if (shown) void actions.refreshModels?.(); }, [shown, sessionId]); if (!bot || currentPart(bot) !== sessionId || !roster.ready) return null; @@ -12642,12 +12755,12 @@ function ModelChoiceDock({ sessionId, useRoster, actions }) { }).finally(() => setBusy("")); }; const text = lost ? t("{model} is not available anymore. Pick another model for me.", { model: bot.model.split("/").slice(1).join("/") }) : keyFor ? t("Hi, I'm {name}. I need a {provider} API key before I can start.", { name: bot.name, provider: keyFor.providerName ?? keyFor.provider }) : usable.length === 0 ? t("Hi, I'm {name}. I don't have a model yet. How do you want to set one up?", { name: bot.name }) : t("Hi, I'm {name}. Pick a model for me first. You can change it later in my details.", { name: bot.name }); - const choices = usable.length === 0 ? setupChoices(actions).map(([label, run2]) => (0, import_react25.createElement)("button", { key: label, type: "button", className: "bt-model-chip", onClick: run2 }, label)) : [ - ...groupModels(usable).map(([provider, list]) => (0, import_react25.createElement)( + const choices = usable.length === 0 ? setupChoices(actions).map(([label, run2]) => (0, import_react26.createElement)("button", { key: label, type: "button", className: "bt-model-chip", onClick: run2 }, label)) : [ + ...groupModels(usable).map(([provider, list]) => (0, import_react26.createElement)( "div", { key: list[0].provider ?? provider, className: "bt-model-choice-group", role: "group", "aria-label": provider }, - (0, import_react25.createElement)("div", { className: "bt-model-choice-provider", "aria-hidden": true }, provider), - (0, import_react25.createElement)("div", { className: "bt-model-choice-chips" }, list.map((model) => (0, import_react25.createElement)("button", { + (0, import_react26.createElement)("div", { className: "bt-model-choice-provider", "aria-hidden": true }, provider), + (0, import_react26.createElement)("div", { className: "bt-model-choice-chips" }, list.map((model) => (0, import_react26.createElement)("button", { key: model.ref, type: "button", className: "bt-model-chip", @@ -12656,36 +12769,36 @@ function ModelChoiceDock({ sessionId, useRoster, actions }) { "aria-label": `${model.name} · ${provider}`, title: model.ref === roster.defaultModel ? `${model.ref} · ${t("Harness default")}` : model.ref, onClick: () => pick2(model.ref) - }, model.name, busy === model.ref ? (0, import_react25.createElement)("span", { className: "bt-model-spin", "aria-label": t("Saving…") }) : null))) + }, model.name, busy === model.ref ? (0, import_react26.createElement)("span", { className: "bt-model-spin", "aria-label": t("Saving…") }) : null))) )), - manage ? (0, import_react25.createElement)("button", { key: "manage", type: "button", className: "bt-model-chip bt-model-chip-quiet", onClick: manage }, (0, import_react25.createElement)(SlidersIcon), t("Manage models")) : null + manage ? (0, import_react26.createElement)("button", { key: "manage", type: "button", className: "bt-model-chip bt-model-chip-quiet", onClick: manage }, (0, import_react26.createElement)(SlidersIcon), t("Manage models")) : null ]; - return (0, import_react25.createElement)( + return (0, import_react26.createElement)( "div", { className: "bt-model-dock" }, - (0, import_react25.createElement)( + (0, import_react26.createElement)( "div", { className: "bt-astack", "data-lead": "" }, - (0, import_react25.createElement)( + (0, import_react26.createElement)( "div", { className: "bt-msg" }, - (0, import_react25.createElement)( + (0, import_react26.createElement)( "div", { className: "bt-msg-line" }, - (0, import_react25.createElement)(BotMark, { bot, size: 22 }), - (0, import_react25.createElement)("div", { className: "bt-bubble" }, text) + (0, import_react26.createElement)(BotMark, { bot, size: 22 }), + (0, import_react26.createElement)("div", { className: "bt-bubble" }, text) ) ) ), - keyFor ? (0, import_react25.createElement)(ModelKeyCard, { key: keyFor.provider, model: keyFor, actions }) : (0, import_react25.createElement)("div", { className: "bt-model-chips", role: "group", "aria-label": t("Choose a model") }, choices), - error ? (0, import_react25.createElement)("div", { className: "bt-secret-error bt-model-error", role: "alert" }, error) : null + keyFor ? (0, import_react26.createElement)(ModelKeyCard, { key: keyFor.provider, model: keyFor, actions }) : (0, import_react26.createElement)("div", { className: "bt-model-chips", role: "group", "aria-label": t("Choose a model") }, choices), + error ? (0, import_react26.createElement)("div", { className: "bt-secret-error bt-model-error", role: "alert" }, error) : null ); } var DEEPSEEK_KEYS_URL = "https://platform.deepseek.com/api_keys"; function ModelKeyCard({ model, actions, onSaved }) { - const [value, setValue] = (0, import_react25.useState)(""); - const [busy, setBusy] = (0, import_react25.useState)(false); - const [error, setError] = (0, import_react25.useState)(""); + const [value, setValue] = (0, import_react26.useState)(""); + const [busy, setBusy] = (0, import_react26.useState)(false); + const [error, setError] = (0, import_react26.useState)(""); const label = t("{provider} API key", { provider: model.providerName ?? model.provider }); const ready = value.trim() !== "" && !busy; const save = () => { @@ -12698,23 +12811,23 @@ function ModelKeyCard({ model, actions, onSaved }) { }, (failure) => setError(hostText(failure?.message ?? String(failure)))).finally(() => setBusy(false)); }; const official = model.provider === "deepseek-official"; - return (0, import_react25.createElement)( + return (0, import_react26.createElement)( "div", { className: "bt-q bt-model-key", role: "group", "aria-label": label }, - (0, import_react25.createElement)("div", { className: "bt-model-key-title" }, (0, import_react25.createElement)(KeyIcon), label), - (0, import_react25.createElement)("label", { className: "bt-q-field bt-secret-field" }, (0, import_react25.createElement)(MaskedInput, { value, onChange: setValue, onEnter: save, label, autoFocus: true })), - official ? (0, import_react25.createElement)( + (0, import_react26.createElement)("div", { className: "bt-model-key-title" }, (0, import_react26.createElement)(KeyIcon), label), + (0, import_react26.createElement)("label", { className: "bt-q-field bt-secret-field" }, (0, import_react26.createElement)(MaskedInput, { value, onChange: setValue, onEnter: save, label, autoFocus: true })), + official ? (0, import_react26.createElement)( "div", { className: "bt-model-key-help" }, - (0, import_react25.createElement)("a", { className: "bt-model-key-link", href: DEEPSEEK_KEYS_URL, target: "_blank", rel: "noopener noreferrer" }, t("Create a key on the DeepSeek platform ↗")), - (0, import_react25.createElement)("span", { className: "bt-model-key-note" }, t("The API is billed by usage; the account needs a balance first.")) + (0, import_react26.createElement)("a", { className: "bt-model-key-link", href: DEEPSEEK_KEYS_URL, target: "_blank", rel: "noopener noreferrer" }, t("Create a key on the DeepSeek platform ↗")), + (0, import_react26.createElement)("span", { className: "bt-model-key-note" }, t("The API is billed by usage; the account needs a balance first.")) ) : null, - error ? (0, import_react25.createElement)("div", { className: "bt-secret-error", role: "alert" }, error) : null, - (0, import_react25.createElement)( + error ? (0, import_react26.createElement)("div", { className: "bt-secret-error", role: "alert" }, error) : null, + (0, import_react26.createElement)( "div", { className: "bt-q-foot" }, - actions.openModels ? (0, import_react25.createElement)("button", { type: "button", className: "bt-q-btn bt-model-key-other", onClick: actions.openModels }, t("Another provider")) : null, - (0, import_react25.createElement)("button", { type: "button", className: "bt-q-submit", disabled: !ready, onClick: save }, busy ? t("Saving…") : t("Save")) + actions.openModels ? (0, import_react26.createElement)("button", { type: "button", className: "bt-q-btn bt-model-key-other", onClick: actions.openModels }, t("Another provider")) : null, + (0, import_react26.createElement)("button", { type: "button", className: "bt-q-submit", disabled: !ready, onClick: save }, busy ? t("Saving…") : t("Save")) ) ); } @@ -12731,14 +12844,14 @@ function DeepSeekSignIn({ useUi, actions }) { const open = useUi((state) => state.signIn); const entry = open ? actions.signInEntry?.() : null; if (!entry) return null; - return (0, import_react25.createElement)(SignInHost, { key: open, entry, actions }); + return (0, import_react26.createElement)(SignInHost, { key: open, entry, actions }); } function SignInHost({ entry, actions }) { - const [ops] = (0, import_react25.useState)(() => entry.inject?.() ?? {}); + const [ops] = (0, import_react26.useState)(() => entry.inject?.() ?? {}); const close = () => actions.closeSignIn(); - const useHook = (source) => (selector) => (0, import_react25.useSyncExternalStore)(source.subscribe, () => selector(source.getSnapshot())); - const [hooks] = (0, import_react25.useState)(() => ({ useAccount: useHook(ops.hooks.account), useTheme: useHook(ops.hooks.theme) })); - return (0, import_react25.createElement)(entry.component, { + const useHook = (source) => (selector) => (0, import_react26.useSyncExternalStore)(source.subscribe, () => selector(source.getSnapshot())); + const [hooks] = (0, import_react26.useState)(() => ({ useAccount: useHook(ops.hooks.account), useTheme: useHook(ops.hooks.theme) })); + return (0, import_react26.createElement)(entry.component, { ...ops, ...hooks, t: actions.accountT(), @@ -12798,7 +12911,7 @@ var MODEL_CSS = ` `; // src/client/turn-error.js -var import_react26 = require("react"); +var import_react27 = require("react"); var OFFICIAL = "deepseek-official"; var ACCOUNT = "deepseek-account"; var TOP_UP_URL = "https://platform.deepseek.com/top_up"; @@ -12868,10 +12981,10 @@ var NO_SUBSCRIBE2 = () => () => { var NO_VIEW = () => null; function useAccountView(actions) { const entry = actions.signInEntry?.() ?? null; - const ops = (0, import_react26.useMemo)(() => entry?.inject?.() ?? {}, [entry]); + const ops = (0, import_react27.useMemo)(() => entry?.inject?.() ?? {}, [entry]); const source = ops.hooks?.account; const read = source ? () => source.getSnapshot()?.view ?? null : NO_VIEW; - return (0, import_react26.useSyncExternalStore)(source?.subscribe ?? NO_SUBSCRIBE2, read, read); + return (0, import_react27.useSyncExternalStore)(source?.subscribe ?? NO_SUBSCRIBE2, read, read); } var topUpOf = (view) => { const url = view?.links?.topUpUrl; @@ -12897,7 +13010,7 @@ function failureFacts(data, blocked) { return facts; } function TechnicalDetails({ facts }) { - const [copied, setCopied] = (0, import_react26.useState)(false); + const [copied, setCopied] = (0, import_react27.useState)(false); if (facts.length === 0) return null; const copy2 = () => { const text = facts.map(([name, , value]) => `${name}: ${value}`).join("\n"); @@ -12907,12 +13020,12 @@ function TechnicalDetails({ facts }) { }).catch(() => { }); }; - return (0, import_react26.createElement)( + return (0, import_react27.createElement)( "details", { className: "bt-fail-tech" }, - (0, import_react26.createElement)("summary", null, t("Technical details")), - (0, import_react26.createElement)("dl", null, facts.map(([name, label, value]) => [(0, import_react26.createElement)("dt", { key: `${name}:t` }, label), (0, import_react26.createElement)("dd", { key: `${name}:d` }, value)])), - (0, import_react26.createElement)("button", { type: "button", className: "bt-mini bt-fail-copy", onClick: copy2 }, copied ? (0, import_react26.createElement)(CheckIcon) : (0, import_react26.createElement)(CopyIcon), copied ? t("Copied") : t("Copy")) + (0, import_react27.createElement)("summary", null, t("Technical details")), + (0, import_react27.createElement)("dl", null, facts.map(([name, label, value]) => [(0, import_react27.createElement)("dt", { key: `${name}:t` }, label), (0, import_react27.createElement)("dd", { key: `${name}:d` }, value)])), + (0, import_react27.createElement)("button", { type: "button", className: "bt-mini bt-fail-copy", onClick: copy2 }, copied ? (0, import_react27.createElement)(CheckIcon) : (0, import_react27.createElement)(CopyIcon), copied ? t("Copied") : t("Copy")) ); } function FailureCell({ node, sessionId, useRoster, useTurnClock, actions }) { @@ -12923,10 +13036,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_react26.useState)(false); - const [retry, setRetry] = (0, import_react26.useState)("idle"); - const [error, setError] = (0, import_react26.useState)(""); - const [joining, setJoining] = (0, import_react26.useState)(null); + const [keying, setKeying] = (0, import_react27.useState)(false); + const [retry, setRetry] = (0, import_react27.useState)("idle"); + const [error, setError] = (0, import_react27.useState)(""); + const [joining, setJoining] = (0, import_react27.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 }); @@ -12943,7 +13056,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_react26.useEffect)(() => { + (0, import_react27.useEffect)(() => { if (joining === null || !signedIn) return void 0; if (bot === void 0 || bot.model !== joining.from) { setJoining(null); @@ -12961,11 +13074,11 @@ function FailureCell({ node, sessionId, useRoster, useTurnClock, actions }) { }, ACCOUNT_MODELS_WAIT_MS); return () => clearTimeout(timer); }, [joining, signedIn, listed]); - const settled = () => (0, import_react26.createElement)( + const settled = () => (0, import_react27.createElement)( "div", { className: "bt-fail", "data-settled": "", role: "status" }, - (0, import_react26.createElement)("div", { className: "bt-fail-head" }, (0, import_react26.createElement)("span", { className: "bt-fail-dot", "aria-hidden": true }), (0, import_react26.createElement)("span", { className: "bt-fail-text" }, text)), - (0, import_react26.createElement)(TechnicalDetails, { facts }) + (0, import_react27.createElement)("div", { className: "bt-fail-head" }, (0, import_react27.createElement)("span", { className: "bt-fail-dot", "aria-hidden": true }), (0, import_react27.createElement)("span", { className: "bt-fail-text" }, text)), + (0, import_react27.createElement)(TechnicalDetails, { facts }) ); if (!current) return settled(); const official = provider === OFFICIAL; @@ -13003,22 +13116,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_react26.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_react27.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_react26.createElement)("button", { key: fix, type: "button", className, "aria-expanded": toggles ? keying : void 0, onClick: () => runs[fix]() }, FIX_LABELS[fix](signedIn)); + return (0, import_react27.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_react26.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_react27.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_react26.createElement)( + return (0, import_react27.createElement)( "div", { className: "bt-fail", role: "status" }, - (0, import_react26.createElement)("div", { className: "bt-fail-head" }, (0, import_react26.createElement)("span", { className: "bt-fail-dot", "aria-hidden": true }), (0, import_react26.createElement)("span", { className: "bt-fail-text" }, text)), - (0, import_react26.createElement)("div", { className: "bt-fail-actions" }, row), - keying && keyHere ? (0, import_react26.createElement)(ModelKeyCard, { model: { provider, providerName: providerName(roster, provider) }, actions, onSaved: () => setKeying(false) }) : null, - error ? (0, import_react26.createElement)("div", { className: "bt-fail-error", role: "alert" }, error) : null, - (0, import_react26.createElement)(TechnicalDetails, { facts }) + (0, import_react27.createElement)("div", { className: "bt-fail-head" }, (0, import_react27.createElement)("span", { className: "bt-fail-dot", "aria-hidden": true }), (0, import_react27.createElement)("span", { className: "bt-fail-text" }, text)), + (0, import_react27.createElement)("div", { className: "bt-fail-actions" }, row), + keying && keyHere ? (0, import_react27.createElement)(ModelKeyCard, { model: { provider, providerName: providerName(roster, provider) }, actions, onSaved: () => setKeying(false) }) : null, + error ? (0, import_react27.createElement)("div", { className: "bt-fail-error", role: "alert" }, error) : null, + (0, import_react27.createElement)(TechnicalDetails, { facts }) ); } var TURN_ERROR_CSS = ` @@ -13045,12 +13158,12 @@ var TURN_ERROR_CSS = ` `; // src/client/palette.js -var import_react27 = require("react"); +var import_react28 = require("react"); var PALETTE_EXIT_MS = 160; function CommandPalette({ start, token, roster, actions, useSessions }) { - const [query, setQuery] = (0, import_react27.useState)(start ?? ""); - const [cursor, setCursor] = (0, import_react27.useState)(0); - const [leaving, setLeaving] = (0, import_react27.useState)(false); + const [query, setQuery] = (0, import_react28.useState)(start ?? ""); + const [cursor, setCursor] = (0, import_react28.useState)(0); + const [leaving, setLeaving] = (0, import_react28.useState)(false); const wanted = query.trim().toLowerCase(); const close = () => { if (leaving) return; @@ -13086,7 +13199,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_react27.createElement)(BotAvatar, { bot, size: 24, badge: false, live: false }), + avatar: (0, import_react28.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, @@ -13097,7 +13210,7 @@ function CommandPalette({ start, token, roster, actions, useSessions }) { })), ...roster.rooms.filter((room2) => matchesName(room2.name)).map((room2) => ({ key: room2.id, - avatar: (0, import_react27.createElement)(RoomAvatar, { room: room2, roster, size: 24 }), + avatar: (0, import_react28.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, @@ -13110,7 +13223,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_react27.createElement)("span", { className: "bt-palette-agent" }, (0, import_react27.createElement)(import_dsh_client_ui_primitives.FishLogo, { size: 18 })), + avatar: (0, import_react28.createElement)("span", { className: "bt-palette-agent" }, (0, import_react28.createElement)(import_dsh_client_ui_primitives.FishLogo, { size: 18 })), title: "DSH Agent", subtitle: t("Plain dsh session"), run: () => actions.openAgent(agent.id) @@ -13123,16 +13236,16 @@ function CommandPalette({ start, token, roster, actions, useSessions }) { key: `${id}:${turn}`, title: bot?.name ?? room2?.name ?? t("Bot"), subtitle: snippet, - avatar: bot ? (0, import_react27.createElement)(BotAvatar, { bot, size: 24, badge: false, live: false }) : (0, import_react27.createElement)(RoomAvatar, { room: room2, roster, size: 24 }), + avatar: bot ? (0, import_react28.createElement)(BotAvatar, { bot, size: 24, badge: false, live: false }) : (0, import_react28.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_react27.createElement)(PlusIcon), title: t("New chat"), run: () => actions.openNewChat("new") }, - { key: "cmd:bot", icon: (0, import_react27.createElement)(PlusIcon), title: t("Create Bot"), run: () => actions.openNewChat("create") }, - { key: "cmd:group", icon: (0, import_react27.createElement)(PeopleIcon), title: t("Create group chat"), run: () => actions.openNewChat("group") }, - { key: "cmd:settings", icon: (0, import_react27.createElement)(GearIcon), title: t("Bot settings"), run: () => actions.openSettings("general") } + { key: "cmd:new", icon: (0, import_react28.createElement)(PlusIcon), title: t("New chat"), run: () => actions.openNewChat("new") }, + { key: "cmd:bot", icon: (0, import_react28.createElement)(PlusIcon), title: t("Create Bot"), run: () => actions.openNewChat("create") }, + { key: "cmd:group", icon: (0, import_react28.createElement)(PeopleIcon), title: t("Create group chat"), run: () => actions.openNewChat("group") }, + { key: "cmd:settings", icon: (0, import_react28.createElement)(GearIcon), title: t("Bot settings"), run: () => actions.openSettings("general") } ].filter((command) => matchesName(command.title)); if (commands.length) sections.push([t("Commands"), commands]); const rows2 = sections.flatMap(([, items]) => items); @@ -13142,7 +13255,7 @@ function CommandPalette({ start, token, roster, actions, useSessions }) { ${shown}`, { axis: "y", ...QUICK_EDGES }); const listRef = glide.box; useFlip(listRef, shown, "[data-flip]"); - (0, import_react27.useEffect)(() => { + (0, import_react28.useEffect)(() => { listRef.current?.querySelector("[aria-selected=true]")?.scrollIntoView({ block: "nearest" }); }, [active, query]); const choose = (row) => { @@ -13151,18 +13264,18 @@ ${shown}`, { axis: "y", ...QUICK_EDGES }); close(); }; let index = -1; - return (0, import_react27.createElement)( + return (0, import_react28.createElement)( "div", { className: "bt-palette-layer", "data-leaving": leaving || void 0 }, - (0, import_react27.createElement)("div", { className: "bt-backdrop", onMouseDown: close }), - (0, import_react27.createElement)( + (0, import_react28.createElement)("div", { className: "bt-backdrop", onMouseDown: close }), + (0, import_react28.createElement)( "div", { className: "bt-palette", role: "dialog", "aria-label": t("Search"), "aria-modal": true }, - (0, import_react27.createElement)( + (0, import_react28.createElement)( "div", { className: "bt-palette-head" }, - (0, import_react27.createElement)("span", { className: "bt-palette-glyph", "aria-hidden": true }, (0, import_react27.createElement)(SearchIcon)), - (0, import_react27.createElement)("input", { + (0, import_react28.createElement)("span", { className: "bt-palette-glyph", "aria-hidden": true }, (0, import_react28.createElement)(SearchIcon)), + (0, import_react28.createElement)("input", { autoFocus: true, value: query, placeholder: t("Search Bots, chats and messages"), @@ -13188,29 +13301,29 @@ ${shown}`, { axis: "y", ...QUICK_EDGES }); } } }), - query ? (0, import_react27.createElement)("button", { type: "button", className: "bt-palette-clear", "aria-label": t("Clear search"), onClick: () => { + query ? (0, import_react28.createElement)("button", { type: "button", className: "bt-palette-clear", "aria-label": t("Clear search"), onClick: () => { setQuery(""); setCursor(0); - } }, (0, import_react27.createElement)(CloseIcon)) : null + } }, (0, import_react28.createElement)(CloseIcon)) : null ), - (0, import_react27.createElement)( + (0, import_react28.createElement)( "div", { ref: listRef, id: "bt-palette-list", className: "bt-palette-list", role: "listbox", "aria-label": t("Results") }, - (0, import_react27.createElement)("span", { ref: glide.thumb, className: "bt-thumb", "aria-hidden": true }), - rows2.length === 0 ? (0, import_react27.createElement)( + (0, import_react28.createElement)("span", { ref: glide.thumb, className: "bt-thumb", "aria-hidden": true }), + rows2.length === 0 ? (0, import_react28.createElement)( "div", { className: "bt-palette-empty" }, - (0, import_react27.createElement)("span", { className: "bt-palette-empty-icon", "aria-hidden": true }, (0, import_react27.createElement)(SearchIcon)), - (0, import_react27.createElement)("span", { className: "bt-palette-empty-label" }, t("No results")), - (0, import_react27.createElement)("span", { className: "bt-palette-empty-hint" }, t("Try a Bot name or words from a message")) - ) : sections.map(([title, items]) => (0, import_react27.createElement)( - import_react27.Fragment, + (0, import_react28.createElement)("span", { className: "bt-palette-empty-icon", "aria-hidden": true }, (0, import_react28.createElement)(SearchIcon)), + (0, import_react28.createElement)("span", { className: "bt-palette-empty-label" }, t("No results")), + (0, import_react28.createElement)("span", { className: "bt-palette-empty-hint" }, t("Try a Bot name or words from a message")) + ) : sections.map(([title, items]) => (0, import_react28.createElement)( + import_react28.Fragment, { key: title }, - (0, import_react27.createElement)("div", { className: "bt-palette-section", role: "presentation", "data-flip": `section:${title}` }, title), + (0, import_react28.createElement)("div", { className: "bt-palette-section", role: "presentation", "data-flip": `section:${title}` }, title), items.map((row) => { index += 1; const at = index; - return (0, import_react27.createElement)( + return (0, import_react28.createElement)( "button", { key: row.key, @@ -13224,14 +13337,14 @@ ${shown}`, { axis: "y", ...QUICK_EDGES }); }, onClick: () => choose(row) }, - (0, import_react27.createElement)("span", { className: "bt-palette-lead" }, row.avatar ?? (0, import_react27.createElement)("span", { className: "bt-palette-cmd" }, row.icon)), - (0, import_react27.createElement)( + (0, import_react28.createElement)("span", { className: "bt-palette-lead" }, row.avatar ?? (0, import_react28.createElement)("span", { className: "bt-palette-cmd" }, row.icon)), + (0, import_react28.createElement)( "span", { className: "bt-palette-text" }, - (0, import_react27.createElement)("span", { className: "bt-palette-title" }, row.title), - row.subtitle ? (0, import_react27.createElement)("span", { className: "bt-palette-sub" }, row.subtitle) : null + (0, import_react28.createElement)("span", { className: "bt-palette-title" }, row.title), + row.subtitle ? (0, import_react28.createElement)("span", { className: "bt-palette-sub" }, row.subtitle) : null ), - row.badge ? (0, import_react27.createElement)("span", { className: "bt-palette-badge" }, row.badge) : null + row.badge ? (0, import_react28.createElement)("span", { className: "bt-palette-badge" }, row.badge) : null ); }) )) @@ -13241,17 +13354,17 @@ ${shown}`, { axis: "y", ...QUICK_EDGES }); } // src/client/folder-menu.js -var import_react28 = require("react"); +var import_react29 = require("react"); var import_react_dom7 = require("react-dom"); var folderName = (path) => String(path).replace(/[\\/]+$/, "").split(/[\\/]/).pop() || String(path); -var Tick = ({ on }) => (0, import_react28.createElement)("span", { className: "bt-model-tick", "aria-hidden": true }, on ? (0, import_react28.createElement)(CheckIcon) : null); +var Tick = ({ on }) => (0, import_react29.createElement)("span", { className: "bt-model-tick", "aria-hidden": true }, on ? (0, import_react29.createElement)(CheckIcon) : null); function FolderMenu({ value, group = false, team = false, actions, run: run2, onPick, wide = false, disabled = false }) { const { isOpen, shownPlace, leaving, button, menu, open, close } = useAnchoredMenu(); - const [info, setInfo] = (0, import_react28.useState)(null); - const [view, setView] = (0, import_react28.useState)("list"); - const [draft, setDraft] = (0, import_react28.useState)(""); - const [listing, setListing] = (0, import_react28.useState)(null); - const [problem, setProblem] = (0, import_react28.useState)(""); + const [info, setInfo] = (0, import_react29.useState)(null); + const [view, setView] = (0, import_react29.useState)("list"); + const [draft, setDraft] = (0, import_react29.useState)(""); + const [listing, setListing] = (0, import_react29.useState)(null); + const [problem, setProblem] = (0, import_react29.useState)(""); const fallback = group ? t("Each Bot's own folder") : t("Team workspace"); const toggle = () => { if (isOpen) { @@ -13284,35 +13397,35 @@ function FolderMenu({ value, group = false, team = false, actions, run: run2, on }; const known = info?.folders ?? []; const folders = value && !known.some((folder) => folder.path === value) ? [{ path: value, title: folderName(value) }, ...known] : known; - const listView = (0, import_react28.createElement)( + const listView = (0, import_react29.createElement)( "div", { key: "list", className: "bt-folder-view" }, - team ? null : (0, import_react28.createElement)( + team ? null : (0, import_react29.createElement)( "button", { type: "button", role: "menuitemradio", "aria-checked": !value, title: group ? void 0 : info?.team ?? void 0, onClick: () => choose("") }, - (0, import_react28.createElement)("span", { className: "bt-menu-label" }, fallback), - (0, import_react28.createElement)(Tick, { on: !value }) + (0, import_react29.createElement)("span", { className: "bt-menu-label" }, fallback), + (0, import_react29.createElement)(Tick, { on: !value }) ), - folders.length > 0 ? (0, import_react28.createElement)("div", { className: "bt-model-group", role: "presentation" }, t("Folders")) : null, - folders.map((folder) => (0, import_react28.createElement)( + folders.length > 0 ? (0, import_react29.createElement)("div", { className: "bt-model-group", role: "presentation" }, t("Folders")) : null, + folders.map((folder) => (0, import_react29.createElement)( "button", { key: folder.path, type: "button", role: "menuitemradio", "aria-checked": folder.path === value, title: folder.path, onClick: () => choose(folder.path) }, - (0, import_react28.createElement)("span", { className: "bt-folder-copy" }, (0, import_react28.createElement)("span", { className: "bt-menu-label" }, folder.title), (0, import_react28.createElement)("span", { className: "bt-folder-path" }, folder.path)), - (0, import_react28.createElement)(Tick, { on: folder.path === value }) + (0, import_react29.createElement)("span", { className: "bt-folder-copy" }, (0, import_react29.createElement)("span", { className: "bt-menu-label" }, folder.title), (0, import_react29.createElement)("span", { className: "bt-folder-path" }, folder.path)), + (0, import_react29.createElement)(Tick, { on: folder.path === value }) )), - (0, import_react28.createElement)("div", { className: "bt-menu-sep", role: "separator" }), - info?.picker === "native" ? (0, import_react28.createElement)("button", { type: "button", role: "menuitem", onClick: pickNative }, (0, import_react28.createElement)(FolderIcon), (0, import_react28.createElement)("span", { className: "bt-menu-label" }, t("Choose a folder…"))) : null, - info?.picker === "browse" ? (0, import_react28.createElement)("button", { type: "button", role: "menuitem", onClick: () => browse(value) }, (0, import_react28.createElement)(FolderIcon), (0, import_react28.createElement)("span", { className: "bt-menu-label" }, t("Browse folders…"))) : null, - (0, import_react28.createElement)("button", { type: "button", role: "menuitem", onClick: () => { + (0, import_react29.createElement)("div", { className: "bt-menu-sep", role: "separator" }), + info?.picker === "native" ? (0, import_react29.createElement)("button", { type: "button", role: "menuitem", onClick: pickNative }, (0, import_react29.createElement)(FolderIcon), (0, import_react29.createElement)("span", { className: "bt-menu-label" }, t("Choose a folder…"))) : null, + info?.picker === "browse" ? (0, import_react29.createElement)("button", { type: "button", role: "menuitem", onClick: () => browse(value) }, (0, import_react29.createElement)(FolderIcon), (0, import_react29.createElement)("span", { className: "bt-menu-label" }, t("Browse folders…"))) : null, + (0, import_react29.createElement)("button", { type: "button", role: "menuitem", onClick: () => { setDraft(value ?? ""); setView("type"); - } }, (0, import_react28.createElement)(PencilIcon), (0, import_react28.createElement)("span", { className: "bt-menu-label" }, t("Enter a path…"))) + } }, (0, import_react29.createElement)(PencilIcon), (0, import_react29.createElement)("span", { className: "bt-menu-label" }, t("Enter a path…"))) ); - const typeView = (0, import_react28.createElement)( + const typeView = (0, import_react29.createElement)( "div", { key: "type", className: "bt-folder-view" }, - (0, import_react28.createElement)("button", { type: "button", className: "bt-folder-back", onClick: () => setView("list") }, (0, import_react28.createElement)(ChevronLeftIcon), (0, import_react28.createElement)("span", { className: "bt-menu-label" }, t("Back"))), - (0, import_react28.createElement)("input", { + (0, import_react29.createElement)("button", { type: "button", className: "bt-folder-back", onClick: () => setView("list") }, (0, import_react29.createElement)(ChevronLeftIcon), (0, import_react29.createElement)("span", { className: "bt-menu-label" }, t("Back"))), + (0, import_react29.createElement)("input", { className: "bt-folder-input", autoFocus: true, value: draft, @@ -13324,33 +13437,33 @@ function FolderMenu({ value, group = false, team = false, actions, run: run2, on if (event.key === "Enter" && !event.nativeEvent.isComposing) typed(); } }), - (0, import_react28.createElement)("button", { type: "button", className: "bt-folder-use", disabled: draft.trim() === "", onClick: typed }, t("Use this folder")) + (0, import_react29.createElement)("button", { type: "button", className: "bt-folder-use", disabled: draft.trim() === "", onClick: typed }, t("Use this folder")) ); const parent = listing?.crumbs?.length > 1 ? listing.crumbs.at(-2) : void 0; const inside = listing?.entries?.filter((entry) => !entry.hidden) ?? []; - const browseView = listing ? (0, import_react28.createElement)( + const browseView = listing ? (0, import_react29.createElement)( "div", { key: `browse:${listing.path}`, className: "bt-folder-view" }, - (0, import_react28.createElement)("button", { type: "button", className: "bt-folder-back", onClick: () => setView("list") }, (0, import_react28.createElement)(ChevronLeftIcon), (0, import_react28.createElement)("span", { className: "bt-menu-label" }, t("Back"))), - (0, import_react28.createElement)("div", { className: "bt-folder-path bt-folder-here" }, listing.path), - parent ? (0, import_react28.createElement)("button", { type: "button", role: "menuitem", title: parent.path, onClick: () => browse(parent.path) }, (0, import_react28.createElement)(FolderIcon), (0, import_react28.createElement)("span", { className: "bt-menu-label" }, t("Up one level"))) : null, - inside.map((entry) => (0, import_react28.createElement)( + (0, import_react29.createElement)("button", { type: "button", className: "bt-folder-back", onClick: () => setView("list") }, (0, import_react29.createElement)(ChevronLeftIcon), (0, import_react29.createElement)("span", { className: "bt-menu-label" }, t("Back"))), + (0, import_react29.createElement)("div", { className: "bt-folder-path bt-folder-here" }, listing.path), + parent ? (0, import_react29.createElement)("button", { type: "button", role: "menuitem", title: parent.path, onClick: () => browse(parent.path) }, (0, import_react29.createElement)(FolderIcon), (0, import_react29.createElement)("span", { className: "bt-menu-label" }, t("Up one level"))) : null, + inside.map((entry) => (0, import_react29.createElement)( "button", { key: entry.path, type: "button", role: "menuitem", onClick: () => browse(entry.path) }, - (0, import_react28.createElement)(FolderIcon), - (0, import_react28.createElement)("span", { className: "bt-menu-label" }, entry.name), - (0, import_react28.createElement)(ChevronRightIcon) + (0, import_react29.createElement)(FolderIcon), + (0, import_react29.createElement)("span", { className: "bt-menu-label" }, entry.name), + (0, import_react29.createElement)(ChevronRightIcon) )), - inside.length === 0 ? (0, import_react28.createElement)("div", { className: "bt-model-none" }, t("No folders inside.")) : null, - listing.truncated ? (0, import_react28.createElement)("div", { className: "bt-folder-path bt-folder-here" }, t("Some folders are not shown.")) : null, - (0, import_react28.createElement)("div", { className: "bt-menu-sep", role: "separator" }), - (0, import_react28.createElement)("button", { type: "button", className: "bt-folder-use", onClick: () => choose(listing.path) }, t("Use this folder")) + inside.length === 0 ? (0, import_react29.createElement)("div", { className: "bt-model-none" }, t("No folders inside.")) : null, + listing.truncated ? (0, import_react29.createElement)("div", { className: "bt-folder-path bt-folder-here" }, t("Some folders are not shown.")) : null, + (0, import_react29.createElement)("div", { className: "bt-menu-sep", role: "separator" }), + (0, import_react29.createElement)("button", { type: "button", className: "bt-folder-use", onClick: () => choose(listing.path) }, t("Use this folder")) ) : null; const shownView = view === "type" ? typeView : view === "browse" && browseView ? browseView : listView; - return (0, import_react28.createElement)( - import_react28.Fragment, + return (0, import_react29.createElement)( + import_react29.Fragment, null, - (0, import_react28.createElement)( + (0, import_react29.createElement)( "button", { ref: button, @@ -13364,19 +13477,19 @@ function FolderMenu({ value, group = false, team = false, actions, run: run2, on onClick: toggle, disabled }, - (0, import_react28.createElement)( + (0, import_react29.createElement)( "span", { className: "bt-model-copy" }, - (0, import_react28.createElement)("span", { className: "bt-model-name" }, value ? folderName(value) : fallback), - value ? (0, import_react28.createElement)("span", { className: "bt-model-provider" }, value) : null + (0, import_react29.createElement)("span", { className: "bt-model-name" }, value ? folderName(value) : fallback), + value ? (0, import_react29.createElement)("span", { className: "bt-model-provider" }, value) : null ), - (0, import_react28.createElement)(Caret) + (0, import_react29.createElement)(Caret) ), - shownPlace ? (0, import_react_dom7.createPortal)((0, import_react28.createElement)( + shownPlace ? (0, import_react_dom7.createPortal)((0, import_react29.createElement)( "div", { ref: menu, className: `bt-menu bt-model-menu bt-folder-menu${shownPlace.bottom !== void 0 ? " bt-menu-up" : ""}`, role: "menu", "aria-label": team ? t("Team workspace") : t("Working folder"), style: shownPlace, "data-leaving": leaving || void 0 }, shownView, - problem ? (0, import_react28.createElement)("div", { className: "bt-folder-error", role: "alert" }, problem) : null + problem ? (0, import_react29.createElement)("div", { className: "bt-folder-error", role: "alert" }, problem) : null ), document.body) : null ); } @@ -13397,7 +13510,7 @@ var FOLDER_CSS = ` `; // src/client/schedules.js -var import_react29 = require("react"); +var import_react30 = require("react"); var POLL_MS = 3e4; var shared = null; var listeners = /* @__PURE__ */ new Set(); @@ -13406,8 +13519,8 @@ function publish(view) { for (const listener of listeners) listener(view); } function useSchedules(actions) { - const [view, setView] = (0, import_react29.useState)(shared); - (0, import_react29.useEffect)(() => { + const [view, setView] = (0, import_react30.useState)(shared); + (0, import_react30.useEffect)(() => { listeners.add(setView); let stopped = false; let timer; @@ -13468,10 +13581,10 @@ var nextText = (task) => { return task.status === "active" ? t("Next: {time}", { time: dayAndTime(Date.parse(task.scheduledAt)) }) : t("Finished"); }; function TaskRow2({ task, actions, onView, showBot, roster }) { - const [confirming, setConfirming] = (0, import_react29.useState)(false); - const [expanded, setExpanded] = (0, import_react29.useState)(false); - const [busy, setBusy] = (0, import_react29.useState)(false); - (0, import_react29.useEffect)(() => { + const [confirming, setConfirming] = (0, import_react30.useState)(false); + const [expanded, setExpanded] = (0, import_react30.useState)(false); + const [busy, setBusy] = (0, import_react30.useState)(false); + (0, import_react30.useEffect)(() => { if (!confirming) return void 0; const timer = setTimeout(() => setConfirming(false), 3e3); return () => clearTimeout(timer); @@ -13485,19 +13598,19 @@ function TaskRow2({ task, actions, onView, showBot, roster }) { void actions.scheduleDelete(task.sessionId, task.id).then(onView, () => setBusy(false)); }; const room2 = task.roomId ? roster.roomsById[task.roomId] : void 0; - return (0, import_react29.createElement)( + return (0, import_react30.createElement)( "div", { className: "bt-set-row bt-task", "data-done": task.status === "active" ? void 0 : "", "data-busy": busy || void 0 }, - showBot ? (0, import_react29.createElement)(BotAvatar, { bot: roster.byId[task.botId], size: 28, badge: false, live: false }) : null, - (0, import_react29.createElement)( + showBot ? (0, import_react30.createElement)(BotAvatar, { bot: roster.byId[task.botId], size: 28, badge: false, live: false }) : null, + (0, import_react30.createElement)( "button", { type: "button", className: "bt-set-copy bt-task-copy", "aria-expanded": expanded || void 0, onClick: () => setExpanded((open) => !open) }, - (0, import_react29.createElement)("span", { className: "bt-task-title" }, task.title), - (0, import_react29.createElement)("span", { className: "bt-set-hint" }, [timingText(task), room2 ? t("in {name}", { name: room2.name }) : ""].filter(Boolean).join(" · ")), - task.prompt && task.prompt !== task.title ? (0, import_react29.createElement)("span", { className: "bt-task-prompt", "data-open": expanded || void 0 }, task.prompt) : null + (0, import_react30.createElement)("span", { className: "bt-task-title" }, task.title), + (0, import_react30.createElement)("span", { className: "bt-set-hint" }, [timingText(task), room2 ? t("in {name}", { name: room2.name }) : ""].filter(Boolean).join(" · ")), + task.prompt && task.prompt !== task.title ? (0, import_react30.createElement)("span", { className: "bt-task-prompt", "data-open": expanded || void 0 }, task.prompt) : null ), - (0, import_react29.createElement)("span", { className: "bt-task-next", "data-state": task.state === "overdue" ? "overdue" : void 0 }, nextText(task)), - (0, import_react29.createElement)("button", { + (0, import_react30.createElement)("span", { className: "bt-task-next", "data-state": task.state === "overdue" ? "overdue" : void 0 }, nextText(task)), + (0, import_react30.createElement)("button", { type: "button", className: "bt-mini bt-task-remove", "data-confirm": confirming || void 0, @@ -13505,7 +13618,7 @@ function TaskRow2({ task, actions, onView, showBot, roster }) { "aria-label": confirming ? t("Click again to delete") : t("Delete task"), title: confirming ? void 0 : t("Delete task"), onClick: remove - }, confirming ? t("Delete") : (0, import_react29.createElement)(TrashIcon)) + }, confirming ? t("Delete") : (0, import_react30.createElement)(TrashIcon)) ); } var pad = (number) => String(number).padStart(2, "0"); @@ -13517,17 +13630,17 @@ function inAnHour() { var KINDS = [["at", "Once"], ["daily", "Every day"], ["weekly", "Every week"], ["every", "Repeat"]]; var UNITS = [["minutes", 1, "minutes"], ["hours", 60, "hours"], ["days", 1440, "days"]]; function TaskForm({ roster, actions, start, onDone, onCancel }) { - const [target, setTarget] = (0, import_react29.useState)(start ?? roster.bots[0]?.id ?? ""); - const [title, setTitle] = (0, import_react29.useState)(""); - const [prompt, setPrompt] = (0, import_react29.useState)(""); - const [kind, setKind] = (0, import_react29.useState)("daily"); - const [at, setAt] = (0, import_react29.useState)(inAnHour); - const [time, setTime] = (0, import_react29.useState)("09:00"); - const [weekdays, setWeekdays] = (0, import_react29.useState)([1, 2, 3, 4, 5]); - const [count, setCount] = (0, import_react29.useState)(1); - const [unit, setUnit] = (0, import_react29.useState)("hours"); - const [busy, setBusy] = (0, import_react29.useState)(false); - const [error, setError] = (0, import_react29.useState)(""); + const [target, setTarget] = (0, import_react30.useState)(start ?? roster.bots[0]?.id ?? ""); + const [title, setTitle] = (0, import_react30.useState)(""); + const [prompt, setPrompt] = (0, import_react30.useState)(""); + const [kind, setKind] = (0, import_react30.useState)("daily"); + const [at, setAt] = (0, import_react30.useState)(inAnHour); + const [time, setTime] = (0, import_react30.useState)("09:00"); + const [weekdays, setWeekdays] = (0, import_react30.useState)([1, 2, 3, 4, 5]); + const [count, setCount] = (0, import_react30.useState)(1); + const [unit, setUnit] = (0, import_react30.useState)("hours"); + const [busy, setBusy] = (0, import_react30.useState)(false); + const [error, setError] = (0, import_react30.useState)(""); const timing = () => { if (kind === "at") return { kind, at: new Date(at).toISOString() }; if (kind === "every") return { kind, minutes: Math.round(Number(count) * UNITS.find(([id]) => id === unit)[1]) }; @@ -13552,107 +13665,107 @@ function TaskForm({ roster, actions, start, onDone, onCancel }) { }); }; const toggleDay = (day) => setWeekdays((days) => days.includes(day) ? days.filter((item) => item !== day) : [...days, day].sort()); - return (0, import_react29.createElement)( + return (0, import_react30.createElement)( "form", { className: "bt-set-card bt-task-form", onSubmit: submit }, - (0, import_react29.createElement)( + (0, import_react30.createElement)( "label", { className: "bt-set-row bt-bs-row" }, - (0, import_react29.createElement)("span", { className: "bt-set-copy" }, (0, import_react29.createElement)("span", { className: "bt-bs-label" }, t("Send to"))), - (0, import_react29.createElement)( + (0, import_react30.createElement)("span", { className: "bt-set-copy" }, (0, import_react30.createElement)("span", { className: "bt-bs-label" }, t("Send to"))), + (0, import_react30.createElement)( "select", { className: "bt-select bt-task-bot", value: target, onChange: (event) => setTarget(event.target.value) }, - (0, import_react29.createElement)("optgroup", { label: t("Bots") }, roster.bots.map((bot) => (0, import_react29.createElement)("option", { key: bot.id, value: bot.id }, bot.name))), - roster.rooms.length > 0 ? (0, import_react29.createElement)("optgroup", { label: t("Group chats") }, roster.rooms.map((room2) => (0, import_react29.createElement)("option", { key: room2.id, value: room2.id }, room2.name))) : null + (0, import_react30.createElement)("optgroup", { label: t("Bots") }, roster.bots.map((bot) => (0, import_react30.createElement)("option", { key: bot.id, value: bot.id }, bot.name))), + roster.rooms.length > 0 ? (0, import_react30.createElement)("optgroup", { label: t("Group chats") }, roster.rooms.map((room2) => (0, import_react30.createElement)("option", { key: room2.id, value: room2.id }, room2.name))) : null ) ), - (0, import_react29.createElement)( + (0, import_react30.createElement)( "label", { className: "bt-set-row bt-bs-row" }, - (0, import_react29.createElement)("span", { className: "bt-set-copy" }, (0, import_react29.createElement)("span", { className: "bt-bs-label" }, t("Name"))), - (0, import_react29.createElement)("input", { className: "bt-bs-input", value: title, maxLength: 120, placeholder: t("Morning briefing"), autoFocus: true, onChange: (event) => setTitle(event.target.value) }) + (0, import_react30.createElement)("span", { className: "bt-set-copy" }, (0, import_react30.createElement)("span", { className: "bt-bs-label" }, t("Name"))), + (0, import_react30.createElement)("input", { className: "bt-bs-input", value: title, maxLength: 120, placeholder: t("Morning briefing"), autoFocus: true, onChange: (event) => setTitle(event.target.value) }) ), - (0, import_react29.createElement)( + (0, import_react30.createElement)( "label", { className: "bt-set-row bt-bs-row bt-bs-stack" }, - (0, import_react29.createElement)("span", { className: "bt-set-copy" }, (0, import_react29.createElement)("span", { className: "bt-bs-label" }, t("What to do"))), - (0, import_react29.createElement)("textarea", { className: "bt-bs-input bt-bs-area", value: prompt, rows: 3, placeholder: t("Sum up what changed since yesterday and what needs me today."), onChange: (event) => setPrompt(event.target.value) }) + (0, import_react30.createElement)("span", { className: "bt-set-copy" }, (0, import_react30.createElement)("span", { className: "bt-bs-label" }, t("What to do"))), + (0, import_react30.createElement)("textarea", { className: "bt-bs-input bt-bs-area", value: prompt, rows: 3, placeholder: t("Sum up what changed since yesterday and what needs me today."), onChange: (event) => setPrompt(event.target.value) }) ), - (0, import_react29.createElement)( + (0, import_react30.createElement)( "div", { className: "bt-set-row bt-bs-row bt-bs-stack" }, - (0, import_react29.createElement)("span", { className: "bt-set-copy" }, (0, import_react29.createElement)("span", { className: "bt-bs-label" }, t("When"))), - (0, import_react29.createElement)(Segmented, { label: t("When"), value: kind }, KINDS.map(([id, label]) => (0, import_react29.createElement)("button", { key: id, type: "button", "aria-pressed": kind === id, onClick: () => setKind(id) }, t(label)))), - (0, import_react29.createElement)( + (0, import_react30.createElement)("span", { className: "bt-set-copy" }, (0, import_react30.createElement)("span", { className: "bt-bs-label" }, t("When"))), + (0, import_react30.createElement)(Segmented, { label: t("When"), value: kind }, KINDS.map(([id, label]) => (0, import_react30.createElement)("button", { key: id, type: "button", "aria-pressed": kind === id, onClick: () => setKind(id) }, t(label)))), + (0, import_react30.createElement)( "div", { key: kind, className: "bt-task-when bt-veil" }, - kind === "at" ? (0, import_react29.createElement)("input", { className: "bt-input", type: "datetime-local", value: at, "aria-label": t("Date and time"), onChange: (event) => setAt(event.target.value) }) : null, - kind === "weekly" ? (0, import_react29.createElement)("div", { className: "bt-task-days", role: "group", "aria-label": t("Days") }, [1, 2, 3, 4, 5, 6, 7].map((day) => (0, import_react29.createElement)("button", { + kind === "at" ? (0, import_react30.createElement)("input", { className: "bt-input", type: "datetime-local", value: at, "aria-label": t("Date and time"), onChange: (event) => setAt(event.target.value) }) : null, + kind === "weekly" ? (0, import_react30.createElement)("div", { className: "bt-task-days", role: "group", "aria-label": t("Days") }, [1, 2, 3, 4, 5, 6, 7].map((day) => (0, import_react30.createElement)("button", { key: day, type: "button", className: "bt-task-day", "aria-pressed": weekdays.includes(day), onClick: () => toggleDay(day) }, when2(Date.UTC(2024, 0, day), { weekday: "narrow", timeZone: "UTC" })))) : null, - kind === "daily" || kind === "weekly" ? (0, import_react29.createElement)("input", { className: "bt-input bt-task-time", type: "time", value: time, "aria-label": t("Time"), onChange: (event) => setTime(event.target.value) }) : null, - kind === "every" ? (0, import_react29.createElement)( - import_react29.Fragment, + kind === "daily" || kind === "weekly" ? (0, import_react30.createElement)("input", { className: "bt-input bt-task-time", type: "time", value: time, "aria-label": t("Time"), onChange: (event) => setTime(event.target.value) }) : null, + kind === "every" ? (0, import_react30.createElement)( + import_react30.Fragment, null, - (0, import_react29.createElement)("span", { className: "bt-task-every" }, t("Every")), - (0, import_react29.createElement)("input", { className: "bt-input bt-task-count", type: "number", min: 1, value: count, "aria-label": t("How many"), onChange: (event) => setCount(event.target.value) }), - (0, import_react29.createElement)( + (0, import_react30.createElement)("span", { className: "bt-task-every" }, t("Every")), + (0, import_react30.createElement)("input", { className: "bt-input bt-task-count", type: "number", min: 1, value: count, "aria-label": t("How many"), onChange: (event) => setCount(event.target.value) }), + (0, import_react30.createElement)( "select", { className: "bt-select bt-task-unit", value: unit, "aria-label": t("Unit"), onChange: (event) => setUnit(event.target.value) }, - UNITS.map(([id, , label]) => (0, import_react29.createElement)("option", { key: id, value: id }, t(label))) + UNITS.map(([id, , label]) => (0, import_react30.createElement)("option", { key: id, value: id }, t(label))) ) ) : null ) ), - error ? (0, import_react29.createElement)("div", { className: "bt-set-row" }, (0, import_react29.createElement)("span", { className: "bt-danger bt-set-hint" }, error)) : null, - (0, import_react29.createElement)( + error ? (0, import_react30.createElement)("div", { className: "bt-set-row" }, (0, import_react30.createElement)("span", { className: "bt-danger bt-set-hint" }, error)) : null, + (0, import_react30.createElement)( "div", { className: "bt-set-row bt-task-foot" }, - (0, import_react29.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: onCancel }, t("Cancel")), - (0, import_react29.createElement)("button", { type: "submit", className: "bt-send bt-soft-sm", disabled: busy || !target || title.trim() === "" || prompt.trim() === "" }, busy ? t("Creating…") : t("Create task")) + (0, import_react30.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: onCancel }, t("Cancel")), + (0, import_react30.createElement)("button", { type: "submit", className: "bt-send bt-soft-sm", disabled: busy || !target || title.trim() === "" || prompt.trim() === "" }, busy ? t("Creating…") : t("Create task")) ) ); } function AutomationOff({ actions }) { - return (0, import_react29.createElement)( + return (0, import_react30.createElement)( "div", { className: "bt-set-card bt-task-off" }, - (0, import_react29.createElement)("span", { className: "bt-task-off-mark" }, (0, import_react29.createElement)(ClockIcon)), - (0, import_react29.createElement)("span", { className: "bt-task-off-title" }, t("Turn on Automation tasks in DSH")), - (0, import_react29.createElement)("span", { className: "bt-set-hint" }, t("Switch on Automation tasks on the Plugins page in Harness settings.")), - actions.openHarnessSettings ? (0, import_react29.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: actions.openHarnessSettings }, t("Open Harness settings")) : null + (0, import_react30.createElement)("span", { className: "bt-task-off-mark" }, (0, import_react30.createElement)(ClockIcon)), + (0, import_react30.createElement)("span", { className: "bt-task-off-title" }, t("Turn on Automation tasks in DSH")), + (0, import_react30.createElement)("span", { className: "bt-set-hint" }, t("Switch on Automation tasks on the Plugins page in Harness settings.")), + actions.openHarnessSettings ? (0, import_react30.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: actions.openHarnessSettings }, t("Open Harness settings")) : null ); } function SchedulesPage({ roster, actions, start }) { const view = useSchedules(actions); const owner = start?.startsWith("bot:") ? start.slice(4) : start?.startsWith("room:") ? start.slice(5) : null; - const [adding, setAdding] = (0, import_react29.useState)(Boolean(start) && owner === null); - if (view === null) return (0, import_react29.createElement)("div", { className: "bt-set-hint" }, t("Loading…")); - if (!view.available) return (0, import_react29.createElement)(AutomationOff, { actions }); + const [adding, setAdding] = (0, import_react30.useState)(Boolean(start) && owner === null); + if (view === null) return (0, import_react30.createElement)("div", { className: "bt-set-hint" }, t("Loading…")); + if (!view.available) return (0, import_react30.createElement)(AutomationOff, { actions }); const shown = (next) => { publish(next); setAdding(false); }; const byChat = [ - ...roster.bots.map((bot) => [bot.id, (0, import_react29.createElement)(BotAvatar, { bot, size: 18, badge: false, live: false }), bot.name, view.tasks.filter((task) => task.botId === bot.id)]), - ...roster.rooms.map((room2) => [room2.id, (0, import_react29.createElement)(RoomAvatar, { room: room2, roster, size: 18 }), room2.name, view.tasks.filter((task) => task.botId === void 0 && task.roomId === room2.id)]) + ...roster.bots.map((bot) => [bot.id, (0, import_react30.createElement)(BotAvatar, { bot, size: 18, badge: false, live: false }), bot.name, view.tasks.filter((task) => task.botId === bot.id)]), + ...roster.rooms.map((room2) => [room2.id, (0, import_react30.createElement)(RoomAvatar, { room: room2, roster, size: 18 }), room2.name, view.tasks.filter((task) => task.botId === void 0 && task.roomId === room2.id)]) ].filter(([id, , , tasks]) => tasks.length > 0 && (owner === null || id === owner)); return [ - adding ? (0, import_react29.createElement)(TaskForm, { key: "form", roster, actions, start: owner ?? start, onDone: shown, onCancel: () => setAdding(false) }) : (0, import_react29.createElement)( + adding ? (0, import_react30.createElement)(TaskForm, { key: "form", roster, actions, start: owner ?? start, onDone: shown, onCancel: () => setAdding(false) }) : (0, import_react30.createElement)( "div", { key: "add", className: "bt-actions" }, - (0, import_react29.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm bt-with-icon", onClick: () => setAdding(true) }, (0, import_react29.createElement)(PlusIcon), t("New task")), - owner !== null ? (0, import_react29.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => actions.openSettings("schedules") }, t("Show all")) : null + (0, import_react30.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm bt-with-icon", onClick: () => setAdding(true) }, (0, import_react30.createElement)(PlusIcon), t("New task")), + owner !== null ? (0, import_react30.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => actions.openSettings("schedules") }, t("Show all")) : null ), - byChat.length === 0 && !adding ? (0, import_react29.createElement)("div", { key: "none", className: "bt-set-card" }, (0, import_react29.createElement)("div", { className: "bt-set-row" }, (0, import_react29.createElement)("span", { className: "bt-set-hint" }, t("No scheduled tasks yet.")))) : byChat.map(([id, avatar, name, tasks]) => (0, import_react29.createElement)( + byChat.length === 0 && !adding ? (0, import_react30.createElement)("div", { key: "none", className: "bt-set-card" }, (0, import_react30.createElement)("div", { className: "bt-set-row" }, (0, import_react30.createElement)("span", { className: "bt-set-hint" }, t("No scheduled tasks yet.")))) : byChat.map(([id, avatar, name, tasks]) => (0, import_react30.createElement)( "section", { key: id, className: "bt-set-section" }, - (0, import_react29.createElement)("h3", { className: "bt-task-head" }, avatar, name), - (0, import_react29.createElement)("div", { className: "bt-set-card" }, tasks.map((task) => (0, import_react29.createElement)(TaskRow2, { key: task.id, task, actions, roster, onView: publish }))) + (0, import_react30.createElement)("h3", { className: "bt-task-head" }, avatar, name), + (0, import_react30.createElement)("div", { className: "bt-set-card" }, tasks.map((task) => (0, import_react30.createElement)(TaskRow2, { key: task.id, task, actions, roster, onView: publish }))) )) ]; } @@ -13660,21 +13773,21 @@ function BotSchedules({ bot, roster, actions }) { const view = useSchedules(actions); if (view === null) return null; const tasks = view.available ? view.tasks.filter((task) => task.botId === bot.id) : []; - return (0, import_react29.createElement)( + return (0, import_react30.createElement)( "section", { className: "bt-set-section" }, - (0, import_react29.createElement)("h3", null, t("Scheduled tasks")), - (0, import_react29.createElement)( + (0, import_react30.createElement)("h3", null, t("Scheduled tasks")), + (0, import_react30.createElement)( "div", { className: "bt-set-card" }, - !view.available ? (0, import_react29.createElement)( + !view.available ? (0, import_react30.createElement)( "div", { className: "bt-set-row bt-bs-row" }, - (0, import_react29.createElement)("span", { className: "bt-set-copy" }, (0, import_react29.createElement)("span", { className: "bt-set-hint" }, t("Switch on Automation tasks on the Plugins page in Harness settings."))), - actions.openHarnessSettings ? (0, import_react29.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: actions.openHarnessSettings }, t("Open Harness settings")) : null + (0, import_react30.createElement)("span", { className: "bt-set-copy" }, (0, import_react30.createElement)("span", { className: "bt-set-hint" }, t("Switch on Automation tasks on the Plugins page in Harness settings."))), + actions.openHarnessSettings ? (0, import_react30.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: actions.openHarnessSettings }, t("Open Harness settings")) : null ) : [ - ...tasks.map((task) => (0, import_react29.createElement)(TaskRow2, { key: task.id, task, actions, roster, onView: publish })), - (0, import_react29.createElement)("button", { key: "new", type: "button", className: "bt-set-row bt-bs-row bt-gs-add", onClick: () => actions.openSettings("schedules", bot.id) }, (0, import_react29.createElement)(PlusIcon), t("New task")) + ...tasks.map((task) => (0, import_react30.createElement)(TaskRow2, { key: task.id, task, actions, roster, onView: publish })), + (0, import_react30.createElement)("button", { key: "new", type: "button", className: "bt-set-row bt-bs-row bt-gs-add", onClick: () => actions.openSettings("schedules", bot.id) }, (0, import_react30.createElement)(PlusIcon), t("New task")) ] ) ); @@ -13682,16 +13795,16 @@ function BotSchedules({ bot, roster, actions }) { function ScheduleSummary({ bot, actions }) { const view = useSchedules(actions); const tasks = view?.available ? view.tasks.filter((task) => task.botId === bot.id && task.status === "active") : []; - return (0, import_react29.createElement)( + return (0, import_react30.createElement)( "div", null, - (0, import_react29.createElement)("div", { className: "bt-section-title" }, tasks.length === 0 ? t("Scheduled tasks") : t("Scheduled tasks · {count}", { count: tasks.length })), - tasks.length === 0 ? (0, import_react29.createElement)("button", { type: "button", className: "bt-more", onClick: () => actions.openSettings("schedules", bot.id) }, view?.available === false ? t("Switch on Automation tasks on the Plugins page in Harness settings.") : t("No scheduled tasks yet. Add one")) : (0, import_react29.createElement)("div", { className: "bt-task-list" }, tasks.slice(0, 3).map((task) => (0, import_react29.createElement)( + (0, import_react30.createElement)("div", { className: "bt-section-title" }, tasks.length === 0 ? t("Scheduled tasks") : t("Scheduled tasks · {count}", { count: tasks.length })), + tasks.length === 0 ? (0, import_react30.createElement)("button", { type: "button", className: "bt-more", onClick: () => actions.openSettings("schedules", bot.id) }, view?.available === false ? t("Switch on Automation tasks on the Plugins page in Harness settings.") : t("No scheduled tasks yet. Add one")) : (0, import_react30.createElement)("div", { className: "bt-task-list" }, tasks.slice(0, 3).map((task) => (0, import_react30.createElement)( "button", { key: task.id, type: "button", className: "bt-task-line", onClick: () => actions.openSettings("schedules", `bot:${bot.id}`) }, - (0, import_react29.createElement)(ClockIcon), - (0, import_react29.createElement)("span", { className: "bt-task-line-title" }, task.title), - (0, import_react29.createElement)("span", { className: "bt-task-line-when" }, timingText(task)) + (0, import_react30.createElement)(ClockIcon), + (0, import_react30.createElement)("span", { className: "bt-task-line-title" }, task.title), + (0, import_react30.createElement)("span", { className: "bt-task-line-when" }, timingText(task)) ))) ); } @@ -13745,7 +13858,7 @@ var SCHEDULE_CSS = ` `; // src/client/capability-settings.js -var import_react30 = require("react"); +var import_react31 = require("react"); var blank = () => ({ name: "", kind: "mcp", description: "", transport: "stdio", command: "", argsText: "", envText: "{}", url: "", headersText: "{}", content: "", items: [] }); var parseMap = (text, label) => { let value; @@ -13759,11 +13872,11 @@ var parseMap = (text, label) => { }; var statusText = (status) => !status ? void 0 : status.state === "ready" ? t("Ready") : status.state === "needs-approval" ? t("Needs approval") : status.state === "error" ? t("Could not connect: {error}", { error: status.error ?? "" }) : t("Connecting…"); function Field({ label, value, onChange, multiline = false, disabled = false, placeholder }) { - return (0, import_react30.createElement)( + return (0, import_react31.createElement)( "label", { className: "bt-set-row bt-bs-row bt-bs-stack" }, - (0, import_react30.createElement)("span", { className: "bt-set-copy" }, (0, import_react30.createElement)("span", { className: "bt-bs-label" }, t(label))), - (0, import_react30.createElement)(multiline ? "textarea" : "input", { + (0, import_react31.createElement)("span", { className: "bt-set-copy" }, (0, import_react31.createElement)("span", { className: "bt-bs-label" }, t(label))), + (0, import_react31.createElement)(multiline ? "textarea" : "input", { className: multiline ? "bt-input bt-input-area" : "bt-input", value, disabled, @@ -13775,7 +13888,7 @@ function Field({ label, value, onChange, multiline = false, disabled = false, pl ); } function CapabilityForm({ draft, setDraft, items, actions, onClose }) { - const [error, setError] = (0, import_react30.useState)(""); + const [error, setError] = (0, import_react31.useState)(""); const set = (key, value) => setDraft((previous) => ({ ...previous, [key]: value })); const submit = async (event) => { event.preventDefault(); @@ -13806,95 +13919,95 @@ function CapabilityForm({ draft, setDraft, items, actions, onClose }) { } }; const available = items.filter((item) => item.name !== draft.name && ["mcp", "skill"].includes(item.kind)); - return (0, import_react30.createElement)( + return (0, import_react31.createElement)( "form", { className: "bt-connector-form", onSubmit: submit }, - (0, import_react30.createElement)(Field, { label: "Name", value: draft.name, disabled: draft.originalName !== void 0, onChange: (value) => set("name", value), placeholder: "my-tool" }), - (0, import_react30.createElement)( + (0, import_react31.createElement)(Field, { label: "Name", value: draft.name, disabled: draft.originalName !== void 0, onChange: (value) => set("name", value), placeholder: "my-tool" }), + (0, import_react31.createElement)( "label", { className: "bt-set-row bt-bs-row bt-bs-stack" }, - (0, import_react30.createElement)("span", { className: "bt-set-copy" }, (0, import_react30.createElement)("span", { className: "bt-bs-label" }, t("Type"))), - (0, import_react30.createElement)( + (0, import_react31.createElement)("span", { className: "bt-set-copy" }, (0, import_react31.createElement)("span", { className: "bt-bs-label" }, t("Type"))), + (0, import_react31.createElement)( "select", { className: "bt-input", value: draft.kind, disabled: draft.originalName !== void 0, onChange: (event) => set("kind", event.target.value) }, - ["mcp", "skill", "pack"].map((kind) => (0, import_react30.createElement)("option", { key: kind, value: kind }, t(kind === "mcp" ? "MCP server" : kind === "skill" ? "Skill" : "Pack"))) + ["mcp", "skill", "pack"].map((kind) => (0, import_react31.createElement)("option", { key: kind, value: kind }, t(kind === "mcp" ? "MCP server" : kind === "skill" ? "Skill" : "Pack"))) ) ), - (0, import_react30.createElement)(Field, { label: "Description", value: draft.description, onChange: (value) => set("description", value) }), - draft.kind === "mcp" ? (0, import_react30.createElement)( + (0, import_react31.createElement)(Field, { label: "Description", value: draft.description, onChange: (value) => set("description", value) }), + draft.kind === "mcp" ? (0, import_react31.createElement)( "label", { className: "bt-set-row bt-bs-row bt-bs-stack" }, - (0, import_react30.createElement)("span", { className: "bt-set-copy" }, (0, import_react30.createElement)("span", { className: "bt-bs-label" }, t("Connection"))), - (0, import_react30.createElement)( + (0, import_react31.createElement)("span", { className: "bt-set-copy" }, (0, import_react31.createElement)("span", { className: "bt-bs-label" }, t("Connection"))), + (0, import_react31.createElement)( "select", { className: "bt-input", value: draft.transport, onChange: (event) => set("transport", event.target.value) }, - (0, import_react30.createElement)("option", { value: "stdio" }, t("Local command")), - (0, import_react30.createElement)("option", { value: "streamable-http" }, t("HTTP server")) + (0, import_react31.createElement)("option", { value: "stdio" }, t("Local command")), + (0, import_react31.createElement)("option", { value: "streamable-http" }, t("HTTP server")) ) ) : null, - draft.kind === "mcp" && draft.transport === "stdio" ? (0, import_react30.createElement)( + draft.kind === "mcp" && draft.transport === "stdio" ? (0, import_react31.createElement)( "div", null, - (0, import_react30.createElement)(Field, { label: "Command", value: draft.command, onChange: (value) => set("command", value) }), - (0, import_react30.createElement)(Field, { label: "Arguments (one per line)", value: draft.argsText, onChange: (value) => set("argsText", value), multiline: true }), - (0, import_react30.createElement)(Field, { label: "Environment (JSON)", value: draft.envText, onChange: (value) => set("envText", value), multiline: true, placeholder: t('{"API_KEY": "$DSH_SECRET_MY_KEY"}') }) + (0, import_react31.createElement)(Field, { label: "Command", value: draft.command, onChange: (value) => set("command", value) }), + (0, import_react31.createElement)(Field, { label: "Arguments (one per line)", value: draft.argsText, onChange: (value) => set("argsText", value), multiline: true }), + (0, import_react31.createElement)(Field, { label: "Environment (JSON)", value: draft.envText, onChange: (value) => set("envText", value), multiline: true, placeholder: t('{"API_KEY": "$DSH_SECRET_MY_KEY"}') }) ) : null, - draft.kind === "mcp" && draft.transport === "streamable-http" ? (0, import_react30.createElement)( + draft.kind === "mcp" && draft.transport === "streamable-http" ? (0, import_react31.createElement)( "div", null, - (0, import_react30.createElement)(Field, { label: "URL", value: draft.url, onChange: (value) => set("url", value) }), - (0, import_react30.createElement)(Field, { label: "Headers (JSON)", value: draft.headersText, onChange: (value) => set("headersText", value), multiline: true, placeholder: t('{"API_KEY": "$DSH_SECRET_MY_KEY"}') }) + (0, import_react31.createElement)(Field, { label: "URL", value: draft.url, onChange: (value) => set("url", value) }), + (0, import_react31.createElement)(Field, { label: "Headers (JSON)", value: draft.headersText, onChange: (value) => set("headersText", value), multiline: true, placeholder: t('{"API_KEY": "$DSH_SECRET_MY_KEY"}') }) ) : null, - draft.kind === "skill" ? (0, import_react30.createElement)(Field, { label: "Skill instructions", value: draft.content, onChange: (value) => set("content", value), multiline: true }) : null, - draft.kind === "pack" ? (0, import_react30.createElement)( + draft.kind === "skill" ? (0, import_react31.createElement)(Field, { label: "Skill instructions", value: draft.content, onChange: (value) => set("content", value), multiline: true }) : null, + draft.kind === "pack" ? (0, import_react31.createElement)( "div", { className: "bt-set-card" }, - available.length === 0 ? (0, import_react30.createElement)("div", { className: "bt-set-row" }, (0, import_react30.createElement)("span", { className: "bt-set-hint" }, t("Save an MCP server or skill first."))) : available.map((item) => (0, import_react30.createElement)( + available.length === 0 ? (0, import_react31.createElement)("div", { className: "bt-set-row" }, (0, import_react31.createElement)("span", { className: "bt-set-hint" }, t("Save an MCP server or skill first."))) : available.map((item) => (0, import_react31.createElement)( "label", { key: item.name, className: "bt-set-row bt-bs-row" }, - (0, import_react30.createElement)("span", { className: "bt-set-copy" }, (0, import_react30.createElement)("span", { className: "bt-bs-label" }, item.name)), - (0, import_react30.createElement)("input", { type: "checkbox", checked: draft.items.includes(item.name), onChange: (event) => set("items", event.target.checked ? [...draft.items, item.name] : draft.items.filter((name) => name !== item.name)) }) + (0, import_react31.createElement)("span", { className: "bt-set-copy" }, (0, import_react31.createElement)("span", { className: "bt-bs-label" }, item.name)), + (0, import_react31.createElement)("input", { type: "checkbox", checked: draft.items.includes(item.name), onChange: (event) => set("items", event.target.checked ? [...draft.items, item.name] : draft.items.filter((name) => name !== item.name)) }) )) ) : null, - error ? (0, import_react30.createElement)("div", { className: "bt-connector-error", role: "alert" }, error) : null, - (0, import_react30.createElement)( + error ? (0, import_react31.createElement)("div", { className: "bt-connector-error", role: "alert" }, error) : null, + (0, import_react31.createElement)( "div", { className: "bt-connector-form-row" }, - (0, import_react30.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: onClose }, t("Cancel")), - (0, import_react30.createElement)("button", { type: "submit", className: "bt-soft bt-soft-sm" }, draft.originalName ? t("Save changes") : t("Add capability")) + (0, import_react31.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: onClose }, t("Cancel")), + (0, import_react31.createElement)("button", { type: "submit", className: "bt-soft bt-soft-sm" }, draft.originalName ? t("Save changes") : t("Add capability")) ) ); } function CapabilityRow({ item, onEdit, onDelete, onApprove, confirming }) { const detail = item.kind === "pack" ? `${t("Pack")}: ${(item.items ?? []).join(", ") || t("No items")}` : item.kind === "mcp" ? item.transport === "stdio" ? t("Local command") : t("HTTP server") : t("Skill"); const secondary = item.kind === "pack" ? [item.description, (item.items ?? []).join(", ") || t("No items")].filter(Boolean).join(" · ") : item.description || detail; - return (0, import_react30.createElement)( + return (0, import_react31.createElement)( "div", { className: "bt-connector" }, - (0, import_react30.createElement)( + (0, import_react31.createElement)( "div", { className: "bt-connector-head" }, - (0, import_react30.createElement)( + (0, import_react31.createElement)( "span", { className: "bt-connector-text" }, - (0, import_react30.createElement)("span", { className: "bt-connector-name" }, item.name), - (0, import_react30.createElement)("span", { className: "bt-connector-status" }, secondary) + (0, import_react31.createElement)("span", { className: "bt-connector-name" }, item.name), + (0, import_react31.createElement)("span", { className: "bt-connector-status" }, secondary) ), - (0, import_react30.createElement)( + (0, import_react31.createElement)( "span", { className: "bt-connector-actions" }, - item.kind === "mcp" && item.transport === "stdio" && !item.approved ? (0, import_react30.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: onApprove }, t("Allow")) : null, - (0, import_react30.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: onEdit }, t("Edit")), - (0, import_react30.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: onDelete }, confirming ? t("Click again to delete.") : t("Delete")) + item.kind === "mcp" && item.transport === "stdio" && !item.approved ? (0, import_react31.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: onApprove }, t("Allow")) : null, + (0, import_react31.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: onEdit }, t("Edit")), + (0, import_react31.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: onDelete }, confirming ? t("Click again to delete.") : t("Delete")) ) ) ); } function CapabilitiesPage({ roster, actions, run: run2 }) { const items = [...roster.capabilities ?? []].sort((a, b) => a.name.localeCompare(b.name)); - const [draft, setDraft] = (0, import_react30.useState)(null); - const [confirming, setConfirming] = (0, import_react30.useState)(""); - (0, import_react30.useEffect)(() => { + const [draft, setDraft] = (0, import_react31.useState)(null); + const [confirming, setConfirming] = (0, import_react31.useState)(""); + (0, import_react31.useEffect)(() => { if (!confirming) return void 0; const timer = setTimeout(() => setConfirming(""), 4e3); return () => clearTimeout(timer); @@ -13917,20 +14030,20 @@ function CapabilitiesPage({ roster, actions, run: run2 }) { setConfirming(""); void run2(actions.deleteCapability(item.name)); }; - return (0, import_react30.createElement)( + return (0, import_react31.createElement)( "section", { className: "bt-set-section" }, - (0, import_react30.createElement)("h3", null, t("Shared capabilities")), - (0, import_react30.createElement)( + (0, import_react31.createElement)("h3", null, t("Shared capabilities")), + (0, import_react31.createElement)( "div", { className: "bt-actions" }, - (0, import_react30.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: startNew }, t("Add capability")) + (0, import_react31.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: startNew }, t("Add capability")) ), - draft ? (0, import_react30.createElement)(CapabilityForm, { draft, setDraft, items, actions, onClose: () => setDraft(null) }) : null, - (0, import_react30.createElement)( + draft ? (0, import_react31.createElement)(CapabilityForm, { draft, setDraft, items, actions, onClose: () => setDraft(null) }) : null, + (0, import_react31.createElement)( "div", { className: "bt-set-card bt-connectors-card" }, - items.length === 0 ? (0, import_react30.createElement)("div", { className: "bt-set-row" }, (0, import_react30.createElement)("span", { className: "bt-set-hint" }, t("No capabilities saved"))) : items.map((item) => (0, import_react30.createElement)(CapabilityRow, { + items.length === 0 ? (0, import_react31.createElement)("div", { className: "bt-set-row" }, (0, import_react31.createElement)("span", { className: "bt-set-hint" }, t("No capabilities saved"))) : items.map((item) => (0, import_react31.createElement)(CapabilityRow, { key: item.name, item, confirming: confirming === item.name, @@ -13946,10 +14059,10 @@ function BotCapabilitiesCard({ bot, roster, actions, run: run2, Card: Card3, Swi const attached = new Set(bot.capabilities ?? []); const statuses = roster.capabilityStatuses?.[bot.id] ?? {}; if (items.length === 0) return null; - return (0, import_react30.createElement)( + return (0, import_react31.createElement)( Card3, { title: t("Capabilities") }, - items.map((item) => (0, import_react30.createElement)(SwitchRow2, { + items.map((item) => (0, import_react31.createElement)(SwitchRow2, { key: item.name, label: item.name, hint: attached.has(item.name) ? statusText(statuses[item.name]) : void 0, @@ -13960,7 +14073,7 @@ function BotCapabilitiesCard({ bot, roster, actions, run: run2, Card: Card3, Swi } // src/client/avatar-library.js -var import_react31 = require("react"); +var import_react32 = require("react"); var CHUNK = 20; var PAGE = 24; async function avatarImage(file) { @@ -14007,14 +14120,14 @@ async function loadLibrary(actions, { offset = 0, limit = PAGE } = {}) { return { items, total: value?.total ?? items.length, next: value?.next ?? offset + items.length }; } function AvatarLibraryPanel({ actions, onPick }) { - const [items, setItems] = (0, import_react31.useState)(null); - const [total, setTotal] = (0, import_react31.useState)(0); - const [offset, setOffset] = (0, import_react31.useState)(0); - const [busy, setBusy] = (0, import_react31.useState)(false); - const [error, setError] = (0, import_react31.useState)(""); - const [report, setReport] = (0, import_react31.useState)(null); - const fileRef = (0, import_react31.useRef)(null); - const load = (0, import_react31.useCallback)(async (from = 0, append = false) => { + const [items, setItems] = (0, import_react32.useState)(null); + const [total, setTotal] = (0, import_react32.useState)(0); + const [offset, setOffset] = (0, import_react32.useState)(0); + const [busy, setBusy] = (0, import_react32.useState)(false); + const [error, setError] = (0, import_react32.useState)(""); + const [report, setReport] = (0, import_react32.useState)(null); + const fileRef = (0, import_react32.useRef)(null); + const load = (0, import_react32.useCallback)(async (from = 0, append = false) => { try { const page = await loadLibrary(actions, { offset: from }); setItems((previous) => append ? [...previous ?? [], ...page.items] : page.items); @@ -14024,7 +14137,7 @@ function AvatarLibraryPanel({ actions, onPick }) { setError(failure?.message ?? String(failure)); } }, [actions]); - (0, import_react31.useEffect)(() => { + (0, import_react32.useEffect)(() => { void load(); }, [load]); const importFiles = async (files) => { @@ -14059,18 +14172,18 @@ function AvatarLibraryPanel({ actions, onPick }) { } }; const shown = items?.length ?? 0; - return (0, import_react31.createElement)( + return (0, import_react32.createElement)( "div", { className: "bt-lib" }, - (0, import_react31.createElement)( + (0, import_react32.createElement)( "div", { className: "bt-lib-bar" }, - (0, import_react31.createElement)( + (0, import_react32.createElement)( "button", { type: "button", className: "bt-soft bt-soft-sm", disabled: busy, onClick: () => fileRef.current?.click() }, busy ? t("Importing photos…") : t("Import photos") ), - (0, import_react31.createElement)("input", { + (0, import_react32.createElement)("input", { ref: fileRef, type: "file", accept: "image/png,image/jpeg,image/webp,image/gif", @@ -14083,35 +14196,35 @@ function AvatarLibraryPanel({ actions, onPick }) { } }) ), - error ? (0, import_react31.createElement)("div", { className: "bt-error", role: "alert" }, error) : null, - items === null ? (0, import_react31.createElement)("div", { className: "bt-note" }, t("Loading…")) : null, - items?.length === 0 && !error ? (0, import_react31.createElement)("div", { className: "bt-note" }, t("No photos in the library yet.")) : null, - items?.length ? (0, import_react31.createElement)("div", { className: "bt-lib-grid" }, items.map((entry) => (0, import_react31.createElement)( + error ? (0, import_react32.createElement)("div", { className: "bt-error", role: "alert" }, error) : null, + items === null ? (0, import_react32.createElement)("div", { className: "bt-note" }, t("Loading…")) : null, + items?.length === 0 && !error ? (0, import_react32.createElement)("div", { className: "bt-note" }, t("No photos in the library yet.")) : null, + items?.length ? (0, import_react32.createElement)("div", { className: "bt-lib-grid" }, items.map((entry) => (0, import_react32.createElement)( "div", { key: entry.id, className: "bt-lib-cell" }, - (0, import_react31.createElement)( + (0, import_react32.createElement)( "button", { type: "button", className: "bt-lib-pick", title: entry.name, "aria-label": t("Use this photo"), onClick: () => onPick(entry) }, - (0, import_react31.createElement)("img", { src: entry.image, alt: "" }) + (0, import_react32.createElement)("img", { src: entry.image, alt: "" }) ), - (0, import_react31.createElement)( + (0, import_react32.createElement)( "button", { type: "button", className: "bt-lib-del", "aria-label": t("Remove photo from the library"), onClick: () => void remove(entry) }, - (0, import_react31.createElement)(TrashIcon) + (0, import_react32.createElement)(TrashIcon) ) ))) : null, - shown < total ? (0, import_react31.createElement)( + shown < total ? (0, import_react32.createElement)( "div", { className: "bt-lib-more" }, - (0, import_react31.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => void load(offset, true) }, t("Show more photos")), - (0, import_react31.createElement)("span", { className: "bt-note" }, t("Showing {shown} of {total} photos", { shown, total })) + (0, import_react32.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => void load(offset, true) }, t("Show more photos")), + (0, import_react32.createElement)("span", { className: "bt-note" }, t("Showing {shown} of {total} photos", { shown, total })) ) : null, - report ? (0, import_react31.createElement)( + report ? (0, import_react32.createElement)( "div", { className: "bt-lib-report" }, - report.imported.length ? (0, import_react31.createElement)("div", { className: "bt-note" }, report.imported.length === 1 ? t("1 photo imported") : t("{count} photos imported", { count: report.imported.length })) : null, - report.duplicates.length ? (0, import_react31.createElement)("div", { className: "bt-note" }, report.duplicates.length === 1 ? t("1 photo was already in the library") : t("{count} photos were already in the library", { count: report.duplicates.length })) : null, - report.failed.map((item, index) => (0, import_react31.createElement)( + report.imported.length ? (0, import_react32.createElement)("div", { className: "bt-note" }, report.imported.length === 1 ? t("1 photo imported") : t("{count} photos imported", { count: report.imported.length })) : null, + report.duplicates.length ? (0, import_react32.createElement)("div", { className: "bt-note" }, report.duplicates.length === 1 ? t("1 photo was already in the library") : t("{count} photos were already in the library", { count: report.duplicates.length })) : null, + report.failed.map((item, index) => (0, import_react32.createElement)( "div", { key: index, className: "bt-note bt-danger" }, t("{name}: {reason}", { name: item.name || t("photo"), reason: hostText(item.message) }) @@ -14136,7 +14249,7 @@ var AVATAR_LIBRARY_CSS = ` `; // src/client/memory-panel.js -var import_react32 = require("react"); +var import_react33 = require("react"); var POLL_MS2 = 1500; var MENU_EXIT_MS2 = 120; var counts = /* @__PURE__ */ new Map(); @@ -14147,8 +14260,8 @@ function noteCount(id, count) { for (const listener of countListeners) listener(); } function useMemoryCount(id, actions) { - const [count, setCount] = (0, import_react32.useState)(counts.get(id) ?? null); - (0, import_react32.useEffect)(() => { + const [count, setCount] = (0, import_react33.useState)(counts.get(id) ?? null); + (0, import_react33.useEffect)(() => { const listener = () => setCount(counts.get(id) ?? null); countListeners.add(listener); listener(); @@ -14167,16 +14280,16 @@ function useMemoryCount(id, actions) { function MemoryRow({ owner, actions }) { const count = useMemoryCount(owner.id, actions); const label = count === null ? t("Loading…") : count === 0 ? t("Nothing saved yet") : count === 1 ? t("1 entry") : t("{count} entries", { count }); - return (0, import_react32.createElement)( + return (0, import_react33.createElement)( "div", null, - (0, import_react32.createElement)("div", { className: "bt-section-title" }, t("Memory")), - (0, import_react32.createElement)( + (0, import_react33.createElement)("div", { className: "bt-section-title" }, t("Memory")), + (0, import_react33.createElement)( "button", { type: "button", className: "bt-mem-row", "aria-label": t("Manage {name}'s memory", { name: owner.name }), onClick: () => actions.openMemory(owner.id) }, - (0, import_react32.createElement)(MemoryIcon), - (0, import_react32.createElement)("span", { className: "bt-mem-row-copy" }, label), - (0, import_react32.createElement)("span", { className: "bt-mem-row-go" }, t("Manage"), (0, import_react32.createElement)(ChevronRightIcon)) + (0, import_react33.createElement)(MemoryIcon), + (0, import_react33.createElement)("span", { className: "bt-mem-row-copy" }, label), + (0, import_react33.createElement)("span", { className: "bt-mem-row-go" }, t("Manage"), (0, import_react33.createElement)(ChevronRightIcon)) ) ); } @@ -14191,45 +14304,45 @@ function ago(at, now) { return format.format(-Math.round(hours / 24), "day"); } function Skeleton({ label }) { - return (0, import_react32.createElement)( + return (0, import_react33.createElement)( "div", { className: "bt-mem-skel", "aria-busy": true }, - [0, 1].map((block) => (0, import_react32.createElement)( + [0, 1].map((block) => (0, import_react33.createElement)( "div", { key: block, className: "bt-mem-skel-block" }, - (0, import_react32.createElement)("span", { className: "bt-mem-skel-head" }), - (0, import_react32.createElement)("span", null), - (0, import_react32.createElement)("span", null), - (0, import_react32.createElement)("span", { style: { width: block === 0 ? "62%" : "48%" } }) + (0, import_react33.createElement)("span", { className: "bt-mem-skel-head" }), + (0, import_react33.createElement)("span", null), + (0, import_react33.createElement)("span", null), + (0, import_react33.createElement)("span", { style: { width: block === 0 ? "62%" : "48%" } }) )), - label ? (0, import_react32.createElement)("div", { className: "bt-mem-skel-label" }, label) : null + label ? (0, import_react33.createElement)("div", { className: "bt-mem-skel-label" }, label) : null ); } function Summary({ owner, view, regenerate }) { if (view.entries.length === 0) { - return (0, import_react32.createElement)( + return (0, import_react33.createElement)( "div", { className: "bt-mem-empty" }, - (0, import_react32.createElement)("div", { className: "bt-mem-empty-mark" }, (0, import_react32.createElement)(MemoryIcon)), - (0, import_react32.createElement)("div", { className: "bt-mem-empty-title" }, owner.group ? t("Nothing is saved for this group yet") : t("{name} has not saved anything yet", { name: owner.name })), - (0, import_react32.createElement)("div", { className: "bt-mem-empty-text" }, owner.group ? t("A group keeps the decisions, rules, and facts its work needs, for its members to read here. Tell it below, or in the group.") : t("Bots keep lasting preferences, decisions, and what you ask them to remember. Tell {name} below, or in its chat.", { name: owner.name })) + (0, import_react33.createElement)("div", { className: "bt-mem-empty-mark" }, (0, import_react33.createElement)(MemoryIcon)), + (0, import_react33.createElement)("div", { className: "bt-mem-empty-title" }, owner.group ? t("Nothing is saved for this group yet") : t("{name} has not saved anything yet", { name: owner.name })), + (0, import_react33.createElement)("div", { className: "bt-mem-empty-text" }, owner.group ? t("A group keeps the decisions, rules, and facts its work needs, for its members to read here. Tell it below, or in the group.") : t("Bots keep lasting preferences, decisions, and what you ask them to remember. Tell {name} below, or in its chat.", { name: owner.name })) ); } - const failed = view.error && !view.summarizing ? (0, import_react32.createElement)( + const failed = view.error && !view.summarizing ? (0, import_react33.createElement)( "div", { className: "bt-mem-failed", role: "alert" }, - (0, import_react32.createElement)("span", null, view.summary ? t("The summary is out of date: {reason}", { reason: hostText(view.error) }) : t("The summary could not be written: {reason}", { reason: hostText(view.error) })), - (0, import_react32.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: regenerate }, t("Try again")) + (0, import_react33.createElement)("span", null, view.summary ? t("The summary is out of date: {reason}", { reason: hostText(view.error) }) : t("The summary could not be written: {reason}", { reason: hostText(view.error) })), + (0, import_react33.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: regenerate }, t("Try again")) ) : null; - if (!view.summary) return (0, import_react32.createElement)(import_react32.Fragment, null, failed, failed ? null : (0, import_react32.createElement)(Skeleton, { label: t("Writing the summary…") })); - return (0, import_react32.createElement)( - import_react32.Fragment, + if (!view.summary) return (0, import_react33.createElement)(import_react33.Fragment, null, failed, failed ? null : (0, import_react33.createElement)(Skeleton, { label: t("Writing the summary…") })); + return (0, import_react33.createElement)( + import_react33.Fragment, null, failed, - (0, import_react32.createElement)( + (0, import_react33.createElement)( "div", { key: view.summary.at, className: "bt-mem-summary", "data-stale": !view.fresh || void 0 }, - summaryBlocks(view.summary.text).map((block, index) => block.kind === "h" ? (0, import_react32.createElement)("h3", { key: index }, block.text) : (0, import_react32.createElement)("p", { key: index }, block.text)) + summaryBlocks(view.summary.text).map((block, index) => block.kind === "h" ? (0, import_react33.createElement)("h3", { key: index }, block.text) : (0, import_react33.createElement)("p", { key: index }, block.text)) ) ); } @@ -14241,9 +14354,9 @@ var groupEntries = (entries2) => entries2.reduce((groups, entry) => { return groups; }, []); function EntryRow({ entry, remove }) { - const [confirming, setConfirming] = (0, import_react32.useState)(false); - const [busy, setBusy] = (0, import_react32.useState)(false); - (0, import_react32.useEffect)(() => { + const [confirming, setConfirming] = (0, import_react33.useState)(false); + const [busy, setBusy] = (0, import_react33.useState)(false); + (0, import_react33.useEffect)(() => { if (!confirming) return void 0; const timer = setTimeout(() => setConfirming(false), 3e3); return () => clearTimeout(timer); @@ -14258,16 +14371,16 @@ function EntryRow({ entry, remove }) { setBusy(true); if (!await remove(entry)) setBusy(false); }; - return (0, import_react32.createElement)( + return (0, import_react33.createElement)( "li", { className: "bt-mem-entry", "data-busy": busy || void 0 }, - (0, import_react32.createElement)( + (0, import_react33.createElement)( "div", { className: "bt-mem-entry-copy" }, - (0, import_react32.createElement)("span", { className: "bt-mem-entry-text" }, entry.text), - meta ? (0, import_react32.createElement)("span", { className: "bt-mem-entry-meta" }, meta) : null + (0, import_react33.createElement)("span", { className: "bt-mem-entry-text" }, entry.text), + meta ? (0, import_react33.createElement)("span", { className: "bt-mem-entry-meta" }, meta) : null ), - (0, import_react32.createElement)("button", { + (0, import_react33.createElement)("button", { type: "button", className: "bt-mem-remove", "data-confirm": confirming || void 0, @@ -14275,7 +14388,7 @@ function EntryRow({ entry, remove }) { "aria-label": confirming ? t("Click again to remove") : t("Remove from memory"), title: confirming ? void 0 : t("Remove from memory"), onClick: click - }, confirming ? t("Remove") : (0, import_react32.createElement)(TrashIcon)) + }, confirming ? t("Remove") : (0, import_react33.createElement)(TrashIcon)) ); } function Entries({ owner, view, remove }) { @@ -14284,25 +14397,25 @@ function Entries({ owner, view, remove }) { { scope: "own", title: t("{name}'s memory", { name: owner.name }), size: view.sizes.own }, { scope: "team", title: t("Team memory"), hint: t("Every Bot reads it"), size: view.sizes.team } ]; - return (0, import_react32.createElement)( + return (0, import_react33.createElement)( "div", { className: "bt-mem-entries" }, - sections.map((section) => (0, import_react32.createElement)( + sections.map((section) => (0, import_react33.createElement)( "section", { key: section.scope, className: "bt-mem-section" }, - (0, import_react32.createElement)( + (0, import_react33.createElement)( "div", { className: "bt-mem-section-head" }, - (0, import_react32.createElement)("h3", null, section.title), - section.hint ? (0, import_react32.createElement)("span", null, section.hint) : null, - (0, import_react32.createElement)("span", { className: "bt-mem-size", title: t("MEMORY.md, which every conversation reads") }, t("{used} of {limit} characters", { used: section.size.toLocaleString(dateLocale()), limit: view.limits.main.toLocaleString(dateLocale()) })) + (0, import_react33.createElement)("h3", null, section.title), + section.hint ? (0, import_react33.createElement)("span", null, section.hint) : null, + (0, import_react33.createElement)("span", { className: "bt-mem-size", title: t("MEMORY.md, which every conversation reads") }, t("{used} of {limit} characters", { used: section.size.toLocaleString(dateLocale()), limit: view.limits.main.toLocaleString(dateLocale()) })) ), - groups.some((group) => group.scope === section.scope) ? groups.filter((group) => group.scope === section.scope).map((group) => (0, import_react32.createElement)( - import_react32.Fragment, + groups.some((group) => group.scope === section.scope) ? groups.filter((group) => group.scope === section.scope).map((group) => (0, import_react33.createElement)( + import_react33.Fragment, { key: group.key }, - group.topic ? (0, import_react32.createElement)("div", { className: "bt-mem-topic" }, group.topic) : null, - (0, import_react32.createElement)("ul", { className: "bt-mem-list" }, group.entries.map((entry) => (0, import_react32.createElement)(EntryRow, { key: `${entry.topic ?? ""}:${entry.text}`, entry, remove }))) - )) : (0, import_react32.createElement)("div", { className: "bt-mem-none" }, t("Nothing saved yet")) + group.topic ? (0, import_react33.createElement)("div", { className: "bt-mem-topic" }, group.topic) : null, + (0, import_react33.createElement)("ul", { className: "bt-mem-list" }, group.entries.map((entry) => (0, import_react33.createElement)(EntryRow, { key: `${entry.topic ?? ""}:${entry.text}`, entry, remove }))) + )) : (0, import_react33.createElement)("div", { className: "bt-mem-none" }, t("Nothing saved yet")) )) ); } @@ -14320,9 +14433,9 @@ function historyLine(row) { return row.scope === "team" ? t("Added to team memory: {text}", { text }) : t("Added: {text}", { text }); } function HistoryRow({ row, undo, now }) { - const [confirming, setConfirming] = (0, import_react32.useState)(false); - const [busy, setBusy] = (0, import_react32.useState)(false); - (0, import_react32.useEffect)(() => { + const [confirming, setConfirming] = (0, import_react33.useState)(false); + const [busy, setBusy] = (0, import_react33.useState)(false); + (0, import_react33.useEffect)(() => { if (!confirming) return void 0; const timer = setTimeout(() => setConfirming(false), 3e3); return () => clearTimeout(timer); @@ -14337,16 +14450,16 @@ function HistoryRow({ row, undo, now }) { setBusy(true); if (!await undo(row)) setBusy(false); }; - return (0, import_react32.createElement)( + return (0, import_react33.createElement)( "li", { className: "bt-mem-entry", "data-busy": busy || void 0 }, - (0, import_react32.createElement)( + (0, import_react33.createElement)( "div", { className: "bt-mem-entry-copy" }, - (0, import_react32.createElement)("span", { className: "bt-mem-entry-text" }, historyLine(row)), - (0, import_react32.createElement)("span", { className: "bt-mem-entry-meta" }, meta) + (0, import_react33.createElement)("span", { className: "bt-mem-entry-text" }, historyLine(row)), + (0, import_react33.createElement)("span", { className: "bt-mem-entry-meta" }, meta) ), - row.restored ? (0, import_react32.createElement)("span", { className: "bt-mem-undone" }, t("Undone")) : (0, import_react32.createElement)("button", { + row.restored ? (0, import_react33.createElement)("span", { className: "bt-mem-undone" }, t("Undone")) : (0, import_react33.createElement)("button", { type: "button", className: "bt-mem-remove", "data-confirm": confirming || void 0, @@ -14358,15 +14471,15 @@ function HistoryRow({ row, undo, now }) { ); } function History({ owner, actions, undo, now }) { - const [rows2, setRows] = (0, import_react32.useState)(null); - const [more, setMore] = (0, import_react32.useState)(null); - const [paging, setPaging] = (0, import_react32.useState)(false); - const load = (0, import_react32.useCallback)(async (before) => { + const [rows2, setRows] = (0, import_react33.useState)(null); + const [more, setMore] = (0, import_react33.useState)(null); + const [paging, setPaging] = (0, import_react33.useState)(false); + const load = (0, import_react33.useCallback)(async (before) => { const page = await actions.memoryHistory(owner.id, before); setRows(before === void 0 ? page.rows : [...rows2 ?? [], ...page.rows]); setMore(page.more); }, [owner.id, rows2]); - (0, import_react32.useEffect)(() => { + (0, import_react33.useEffect)(() => { void load(); }, [owner.id]); const reload = async () => { @@ -14383,50 +14496,50 @@ function History({ owner, actions, undo, now }) { setPaging(false); } }; - if (rows2 === null) return (0, import_react32.createElement)(Skeleton); - if (rows2.length === 0) return (0, import_react32.createElement)("div", { className: "bt-mem-none" }, t("No changes yet")); - return (0, import_react32.createElement)( + if (rows2 === null) return (0, import_react33.createElement)(Skeleton); + if (rows2.length === 0) return (0, import_react33.createElement)("div", { className: "bt-mem-none" }, t("No changes yet")); + return (0, import_react33.createElement)( "div", { className: "bt-mem-entries" }, - (0, import_react32.createElement)("ul", { className: "bt-mem-list" }, rows2.map((row) => (0, import_react32.createElement)(HistoryRow, { key: row.id, row, undo: undoRow, now }))), - more ? (0, import_react32.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: paging, onClick: () => void moreClick() }, t("Load more")) : null + (0, import_react33.createElement)("ul", { className: "bt-mem-list" }, rows2.map((row) => (0, import_react33.createElement)(HistoryRow, { key: row.id, row, undo: undoRow, now }))), + more ? (0, import_react33.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: paging, onClick: () => void moreClick() }, t("Load more")) : null ); } function Reply({ answer, dismiss }) { - return (0, import_react32.createElement)( + return (0, import_react33.createElement)( "div", { className: "bt-mem-reply", role: "status" }, - (0, import_react32.createElement)( + (0, import_react33.createElement)( "div", { className: "bt-mem-reply-head" }, - (0, import_react32.createElement)("span", { className: "bt-mem-reply-asked" }, answer.asked), - answer.pending ? null : (0, import_react32.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Dismiss"), onClick: dismiss }, (0, import_react32.createElement)(CloseIcon)) + (0, import_react33.createElement)("span", { className: "bt-mem-reply-asked" }, answer.asked), + answer.pending ? null : (0, import_react33.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Dismiss"), onClick: dismiss }, (0, import_react33.createElement)(CloseIcon)) ), - answer.pending ? (0, import_react32.createElement)("div", { className: "bt-mem-reply-text bt-shimmer" }, t("Thinking…")) : answer.error ? (0, import_react32.createElement)("div", { className: "bt-mem-reply-text bt-danger" }, hostText(answer.error)) : (0, import_react32.createElement)( - import_react32.Fragment, + answer.pending ? (0, import_react33.createElement)("div", { className: "bt-mem-reply-text bt-shimmer" }, t("Thinking…")) : answer.error ? (0, import_react33.createElement)("div", { className: "bt-mem-reply-text bt-danger" }, hostText(answer.error)) : (0, import_react33.createElement)( + import_react33.Fragment, null, - answer.reply ? (0, import_react32.createElement)("div", { className: "bt-mem-reply-text" }, answer.reply) : null, - answer.changes.length > 0 ? (0, import_react32.createElement)("ul", { className: "bt-mem-changes" }, answer.changes.map((change, index) => (0, import_react32.createElement)( + answer.reply ? (0, import_react33.createElement)("div", { className: "bt-mem-reply-text" }, answer.reply) : null, + answer.changes.length > 0 ? (0, import_react33.createElement)("ul", { className: "bt-mem-changes" }, answer.changes.map((change, index) => (0, import_react33.createElement)( "li", { key: index, "data-ok": change.ok || void 0 }, - change.ok ? (0, import_react32.createElement)(CheckIcon) : (0, import_react32.createElement)(CloseIcon), - (0, import_react32.createElement)("span", null, changeLine(change)) + change.ok ? (0, import_react33.createElement)(CheckIcon) : (0, import_react33.createElement)(CloseIcon), + (0, import_react33.createElement)("span", null, changeLine(change)) ))) : null ) ); } function useMemoryView(id, actions) { - const [view, setView] = (0, import_react32.useState)(null); - const [error, setError] = (0, import_react32.useState)(""); - const timer = (0, import_react32.useRef)(0); - const latest = (0, import_react32.useRef)(0); - const alive = (0, import_react32.useRef)(true); - const show2 = (0, import_react32.useCallback)((next) => { + const [view, setView] = (0, import_react33.useState)(null); + const [error, setError] = (0, import_react33.useState)(""); + const timer = (0, import_react33.useRef)(0); + const latest = (0, import_react33.useRef)(0); + const alive = (0, import_react33.useRef)(true); + const show2 = (0, import_react33.useCallback)((next) => { setView(next); setError(""); noteCount(id, next.entries.length); }, [id]); - const load = (0, import_react32.useCallback)(async (flags = {}) => { + const load = (0, import_react33.useCallback)(async (flags = {}) => { clearTimeout(timer.current); const ticket = ++latest.current; try { @@ -14438,7 +14551,7 @@ function useMemoryView(id, actions) { if (alive.current && ticket === latest.current) setError(failure?.message ?? String(failure)); } }, [id]); - (0, import_react32.useEffect)(() => { + (0, import_react33.useEffect)(() => { alive.current = true; void load({ summarize: true }); return () => { @@ -14449,8 +14562,8 @@ function useMemoryView(id, actions) { return { view, error, load, show: show2 }; } function useNow(every) { - const [now, setNow] = (0, import_react32.useState)(Date.now()); - (0, import_react32.useEffect)(() => { + const [now, setNow] = (0, import_react33.useState)(Date.now()); + (0, import_react33.useEffect)(() => { const id = setInterval(() => setNow(Date.now()), every); return () => clearInterval(id); }, [every]); @@ -14458,18 +14571,18 @@ function useNow(every) { } function MemoryDialog({ owner, actions, leaving = false }) { const { view, error, load, show: show2 } = useMemoryView(owner.id, actions); - const [page, setPage] = (0, import_react32.useState)("summary"); - const [menu, setMenu] = (0, import_react32.useState)(false); + const [page, setPage] = (0, import_react33.useState)("summary"); + const [menu, setMenu] = (0, import_react33.useState)(false); const [menuShown, menuLeaving] = useLinger(menu, MENU_EXIT_MS2); - const [text, setText] = (0, import_react32.useState)(""); - const [answer, setAnswer] = (0, import_react32.useState)(null); - const menuRef = (0, import_react32.useRef)(null); - const dotsRef = (0, import_react32.useRef)(null); - const inputRef = (0, import_react32.useRef)(null); + const [text, setText] = (0, import_react33.useState)(""); + const [answer, setAnswer] = (0, import_react33.useState)(null); + const menuRef = (0, import_react33.useRef)(null); + const dotsRef = (0, import_react33.useRef)(null); + const inputRef = (0, import_react33.useRef)(null); const now = useNow(3e4); - const close = (0, import_react32.useCallback)(() => actions.closeMemory(), []); + const close = (0, import_react33.useCallback)(() => actions.closeMemory(), []); useEscape(close); - (0, import_react32.useEffect)(() => { + (0, import_react33.useEffect)(() => { if (!menu) return void 0; const onDown = (event) => { if (menuRef.current?.contains(event.target) || dotsRef.current?.contains(event.target)) return; @@ -14544,57 +14657,57 @@ function MemoryDialog({ owner, actions, leaving = false }) { const when3 = view?.summary ? ago(view.summary.at, now) : null; const status = view === null ? "" : page === "entries" ? count === 1 ? t("1 entry") : t("{count} entries", { count }) : view.summarizing && view.summary ? t("Updating…") : view.summary && view.fresh ? when3 ? t("Updated {time}", { time: when3 }) : t("Updated just now") : ""; const busy = answer?.pending === true; - return (0, import_react32.createElement)( + return (0, import_react33.createElement)( "div", { className: "bt-mem-layer", "data-leaving": leaving || void 0 }, - (0, import_react32.createElement)("div", { className: "bt-scrim bt-mem-scrim", onMouseDown: close }), - (0, import_react32.createElement)( + (0, import_react33.createElement)("div", { className: "bt-scrim bt-mem-scrim", onMouseDown: close }), + (0, import_react33.createElement)( "div", { className: "bt-mem", role: "dialog", "aria-modal": true, "aria-label": t("{name}'s memory", { name: owner.name }) }, - (0, import_react32.createElement)( + (0, import_react33.createElement)( "div", { className: "bt-mem-head" }, - page === "summary" ? null : (0, import_react32.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Back to the summary"), onClick: backToSummary }, (0, import_react32.createElement)(ChevronLeftIcon)), - (0, import_react32.createElement)("h2", null, page === "entries" ? t("All entries") : page === "history" ? t("Change history") : t("Memory summary")), - (0, import_react32.createElement)("span", { className: "bt-mem-status" }, page === "summary" ? [owner.name, status].filter(Boolean).join(" · ") : page === "entries" ? status : ""), - (0, import_react32.createElement)("span", { className: "bt-mem-head-gap" }), - (0, import_react32.createElement)("button", { ref: dotsRef, type: "button", className: "bt-icon-btn", "aria-label": t("Memory options"), "aria-haspopup": "menu", "aria-expanded": menu, onClick: () => setMenu((value) => !value) }, (0, import_react32.createElement)(DotsIcon)), - (0, import_react32.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Close memory"), onClick: close }, (0, import_react32.createElement)(CloseIcon)), - menuShown ? (0, import_react32.createElement)( + page === "summary" ? null : (0, import_react33.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Back to the summary"), onClick: backToSummary }, (0, import_react33.createElement)(ChevronLeftIcon)), + (0, import_react33.createElement)("h2", null, page === "entries" ? t("All entries") : page === "history" ? t("Change history") : t("Memory summary")), + (0, import_react33.createElement)("span", { className: "bt-mem-status" }, page === "summary" ? [owner.name, status].filter(Boolean).join(" · ") : page === "entries" ? status : ""), + (0, import_react33.createElement)("span", { className: "bt-mem-head-gap" }), + (0, import_react33.createElement)("button", { ref: dotsRef, type: "button", className: "bt-icon-btn", "aria-label": t("Memory options"), "aria-haspopup": "menu", "aria-expanded": menu, onClick: () => setMenu((value) => !value) }, (0, import_react33.createElement)(DotsIcon)), + (0, import_react33.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Close memory"), onClick: close }, (0, import_react33.createElement)(CloseIcon)), + menuShown ? (0, import_react33.createElement)( "div", { ref: menuRef, className: "bt-menu bt-mem-menu", role: "menu", "aria-label": t("Memory options"), "data-leaving": menuLeaving || void 0 }, - (0, import_react32.createElement)( + (0, import_react33.createElement)( "button", { type: "button", role: "menuitem", onClick: openEntries }, - (0, import_react32.createElement)("span", { className: "bt-menu-label" }, t("All entries")), - (0, import_react32.createElement)("span", { className: "bt-menu-hint" }, String(count)) + (0, import_react33.createElement)("span", { className: "bt-menu-label" }, t("All entries")), + (0, import_react33.createElement)("span", { className: "bt-menu-hint" }, String(count)) ), - (0, import_react32.createElement)( + (0, import_react33.createElement)( "button", { type: "button", role: "menuitem", onClick: openHistory }, - (0, import_react32.createElement)("span", { className: "bt-menu-label" }, t("Change history")) + (0, import_react33.createElement)("span", { className: "bt-menu-label" }, t("Change history")) ), - (0, import_react32.createElement)( + (0, import_react33.createElement)( "button", { type: "button", role: "menuitem", disabled: count === 0 || view?.summarizing, onClick: regenerate }, - (0, import_react32.createElement)("span", { className: "bt-menu-label" }, t("Regenerate summary")) + (0, import_react33.createElement)("span", { className: "bt-menu-label" }, t("Regenerate summary")) ) ) : null ), - (0, import_react32.createElement)( + (0, import_react33.createElement)( "div", { className: "bt-mem-body" }, - error ? (0, import_react32.createElement)("div", { className: "bt-error", role: "alert", style: { padding: 0 } }, hostText(error)) : null, - view === null ? error ? null : (0, import_react32.createElement)(Skeleton) : page === "entries" ? (0, import_react32.createElement)(Entries, { owner, view, remove }) : page === "history" ? (0, import_react32.createElement)(History, { owner, actions, undo, now }) : (0, import_react32.createElement)(Summary, { owner, view, regenerate }) + error ? (0, import_react33.createElement)("div", { className: "bt-error", role: "alert", style: { padding: 0 } }, hostText(error)) : null, + view === null ? error ? null : (0, import_react33.createElement)(Skeleton) : page === "entries" ? (0, import_react33.createElement)(Entries, { owner, view, remove }) : page === "history" ? (0, import_react33.createElement)(History, { owner, actions, undo, now }) : (0, import_react33.createElement)(Summary, { owner, view, regenerate }) ), - (0, import_react32.createElement)( + (0, import_react33.createElement)( "div", { className: "bt-mem-foot" }, - answer ? (0, import_react32.createElement)(Reply, { answer, dismiss: () => setAnswer(null) }) : null, - (0, import_react32.createElement)( + answer ? (0, import_react33.createElement)(Reply, { answer, dismiss: () => setAnswer(null) }) : null, + (0, import_react33.createElement)( "form", { className: "bt-mem-ask", onSubmit: ask }, - (0, import_react32.createElement)("input", { + (0, import_react33.createElement)("input", { ref: inputRef, className: "bt-mem-input", value: text, @@ -14604,10 +14717,10 @@ function MemoryDialog({ owner, actions, leaving = false }) { "aria-label": t("Ask about or update {name}'s memory", { name: owner.name }), onChange: (event) => setText(event.target.value) }), - (0, import_react32.createElement)( + (0, import_react33.createElement)( "button", { type: "submit", className: "bt-mem-send", disabled: busy || text.trim() === "", "aria-label": t("Send") }, - busy ? (0, import_react32.createElement)("span", { className: "bt-mem-spin", "aria-hidden": true }) : (0, import_react32.createElement)(ArrowUpIcon) + busy ? (0, import_react33.createElement)("span", { className: "bt-mem-spin", "aria-hidden": true }) : (0, import_react33.createElement)(ArrowUpIcon) ) ) ) @@ -14616,11 +14729,11 @@ function MemoryDialog({ owner, actions, leaving = false }) { } // src/client/bot-settings.js -var import_react33 = require("react"); +var import_react34 = require("react"); var capitalize = (word) => word[0].toUpperCase() + word.slice(1); function InlineText({ label, value, placeholder, required = false, maxLength, multiline = false, onSave }) { - const [draft, setDraft] = (0, import_react33.useState)(null); - const reverting = (0, import_react33.useRef)(false); + const [draft, setDraft] = (0, import_react34.useState)(null); + const reverting = (0, import_react34.useRef)(false); const commit = () => { const next = draft?.trim(); setDraft(null); @@ -14631,7 +14744,7 @@ function InlineText({ label, value, placeholder, required = false, maxLength, mu if (next === void 0 || next === (value ?? "") || required && next === "") return; void onSave(next); }; - return (0, import_react33.createElement)(multiline ? "textarea" : "input", { + return (0, import_react34.createElement)(multiline ? "textarea" : "input", { className: multiline ? "bt-bs-input bt-bs-area" : "bt-bs-input", value: draft ?? value ?? "", placeholder, @@ -14652,29 +14765,29 @@ function InlineText({ label, value, placeholder, required = false, maxLength, mu }); } function Row({ label, hint, stack = false, children }) { - return (0, import_react33.createElement)( + return (0, import_react34.createElement)( "label", { className: stack ? "bt-set-row bt-bs-row bt-bs-stack" : "bt-set-row bt-bs-row" }, - (0, import_react33.createElement)("span", { className: "bt-set-copy" }, (0, import_react33.createElement)("span", { className: "bt-bs-label" }, label), hint ? (0, import_react33.createElement)("span", { className: "bt-set-hint" }, hint) : null), + (0, import_react34.createElement)("span", { className: "bt-set-copy" }, (0, import_react34.createElement)("span", { className: "bt-bs-label" }, label), hint ? (0, import_react34.createElement)("span", { className: "bt-set-hint" }, hint) : null), children ); } function Card2({ title, children }) { - return (0, import_react33.createElement)("section", { className: "bt-set-section" }, title ? (0, import_react33.createElement)("h3", null, title) : null, (0, import_react33.createElement)("div", { className: "bt-set-card" }, children)); + return (0, import_react34.createElement)("section", { className: "bt-set-section" }, title ? (0, import_react34.createElement)("h3", null, title) : null, (0, import_react34.createElement)("div", { className: "bt-set-card" }, children)); } function Switch({ on, label, disabled, onChange }) { - return (0, import_react33.createElement)( + return (0, import_react34.createElement)( "button", { type: "button", role: "switch", className: "bt-switch", "aria-checked": on, "aria-label": label, disabled, onClick: () => onChange(!on) }, - (0, import_react33.createElement)("span", { className: "bt-switch-knob", "aria-hidden": true }) + (0, import_react34.createElement)("span", { className: "bt-switch-knob", "aria-hidden": true }) ); } function SwitchRow({ label, hint, on, disabled, onChange }) { - return (0, import_react33.createElement)( + return (0, import_react34.createElement)( "div", { className: "bt-set-row bt-bs-row" }, - (0, import_react33.createElement)("span", { className: "bt-set-copy" }, (0, import_react33.createElement)("span", { className: "bt-bs-label" }, label), hint ? (0, import_react33.createElement)("span", { className: "bt-set-hint" }, hint) : null), - (0, import_react33.createElement)(Switch, { on, label, disabled, onChange }) + (0, import_react34.createElement)("span", { className: "bt-set-copy" }, (0, import_react34.createElement)("span", { className: "bt-bs-label" }, label), hint ? (0, import_react34.createElement)("span", { className: "bt-set-hint" }, hint) : null), + (0, import_react34.createElement)(Switch, { on, label, disabled, onChange }) ); } function modelHint(bot, roster) { @@ -14685,22 +14798,22 @@ function modelHint(bot, roster) { return t("Applies from the next message."); } function ShapeRing({ shape, size }) { - const maskId = (0, import_react33.useRef)(""); + const maskId = (0, import_react34.useRef)(""); if (maskId.current === "") maskId.current = `bt-ring-${nextMarkSerial()}`; const def = shapeOf(shape); const unit = def.size / size; const markup = `${holes(def, `${bodyOf(def, "#000", true)}`)}${bodyOf(def, "currentColor", true)}`; - return (0, import_react33.createElement)("svg", { className: "bt-ring", viewBox: `0 0 ${def.size} ${def.size}`, "aria-hidden": true, dangerouslySetInnerHTML: { __html: markup } }); + return (0, import_react34.createElement)("svg", { className: "bt-ring", viewBox: `0 0 ${def.size} ${def.size}`, "aria-hidden": true, dangerouslySetInnerHTML: { __html: markup } }); } function CharacterGrid({ look, hasPhoto = false, onShape, onColor }) { const shapes = [...PICKER_SHAPES, ...Object.keys(SHAPES).filter((id) => !Object.hasOwn(CHARACTERS, id))]; if (!shapes.includes(look.shape)) shapes.push(look.shape); const rows2 = []; for (let index = 0; index < shapes.length; index += PICKER_COLUMNS) rows2.push(shapes.slice(index, index + PICKER_COLUMNS)); - return (0, import_react33.createElement)( - import_react33.Fragment, + return (0, import_react34.createElement)( + import_react34.Fragment, null, - (0, import_react33.createElement)("div", { className: "bt-shapes", role: "group", "aria-label": t("Character shape") }, rows2.map((row, index) => (0, import_react33.createElement)("div", { key: index, className: "bt-shape-row" }, row.map((id) => (0, import_react33.createElement)("button", { + (0, import_react34.createElement)("div", { className: "bt-shapes", role: "group", "aria-label": t("Character shape") }, rows2.map((row, index) => (0, import_react34.createElement)("div", { key: index, className: "bt-shape-row" }, row.map((id) => (0, import_react34.createElement)("button", { key: id, type: "button", className: "bt-shape", @@ -14708,8 +14821,8 @@ function CharacterGrid({ look, hasPhoto = false, onShape, onColor }) { title: t(shapeOf(id).label), "aria-pressed": !hasPhoto && look.shape === id, onClick: () => onShape(id) - }, (0, import_react33.createElement)(ShapeRing, { shape: id, size: 36 }), (0, import_react33.createElement)(BotMark, { look: { shape: id, color: look.color }, size: 36 })))))), - (0, import_react33.createElement)("div", { className: "bt-colors", role: "group", "aria-label": t("Character color") }, CHARACTER_COLORS.map((color) => (0, import_react33.createElement)("button", { + }, (0, import_react34.createElement)(ShapeRing, { shape: id, size: 36 }), (0, import_react34.createElement)(BotMark, { look: { shape: id, color: look.color }, size: 36 })))))), + (0, import_react34.createElement)("div", { className: "bt-colors", role: "group", "aria-label": t("Character color") }, CHARACTER_COLORS.map((color) => (0, import_react34.createElement)("button", { key: color, type: "button", className: "bt-color", @@ -14717,19 +14830,19 @@ function CharacterGrid({ look, hasPhoto = false, onShape, onColor }) { title: t(capitalize(color)), "aria-pressed": look.color === color, onClick: () => onColor(color) - }, (0, import_react33.createElement)("span", { style: { background: paintCss(color) } })))) + }, (0, import_react34.createElement)("span", { style: { background: paintCss(color) } })))) ); } function AvatarEditor({ bot, actions, run: run2, onClose }) { const look = lookOf(bot); - const [tab, setTab] = (0, import_react33.useState)(look.image ? "upload" : "bot"); - const [over, setOver] = (0, import_react33.useState)(false); - const ref = (0, import_react33.useRef)(null); - const fileRef = (0, import_react33.useRef)(null); + const [tab, setTab] = (0, import_react34.useState)(look.image ? "upload" : "bot"); + const [over, setOver] = (0, import_react34.useState)(false); + const ref = (0, import_react34.useRef)(null); + const fileRef = (0, import_react34.useRef)(null); const upload = (file) => { if (file) void run2(avatarImage(file).then((image) => actions.updateBot(bot.id, { avatar: { ...bot.avatar ?? {}, image } }))); }; - (0, import_react33.useEffect)(() => { + (0, import_react34.useEffect)(() => { const onDown = (event) => { if (!(event.target instanceof Element) || ref.current?.contains(event.target) || event.target.closest(".bt-avatar-trigger")) return; onClose(); @@ -14747,7 +14860,7 @@ function AvatarEditor({ bot, actions, run: run2, onClose }) { window.removeEventListener("keydown", onKey, true); }; }, [onClose]); - (0, import_react33.useEffect)(() => { + (0, import_react34.useEffect)(() => { if (tab !== "upload") return void 0; const onPaste = (event) => { const file = [...event.clipboardData?.files ?? []].find((item) => item.type.startsWith("image/")); @@ -14761,32 +14874,32 @@ function AvatarEditor({ bot, actions, run: run2, onClose }) { }, [tab, bot]); const hasPhoto = Boolean(look.image); const glide = useGlide(tab); - return (0, import_react33.createElement)( + return (0, import_react34.createElement)( "div", { ref, className: "bt-avedit", role: "dialog", "aria-label": t("Avatar editor") }, - (0, import_react33.createElement)( + (0, import_react34.createElement)( "div", { className: "bt-avedit-top" }, - (0, import_react33.createElement)( + (0, import_react34.createElement)( "div", { ref: glide.box, role: "tablist", "aria-label": t("Avatar source"), className: "bt-avedit-tabs" }, - (0, import_react33.createElement)("span", { ref: glide.thumb, className: "bt-thumb", "aria-hidden": true }), - [["bot", "Bot"], ["upload", "Upload"], ["library", "Library"]].map(([id, label]) => (0, import_react33.createElement)("button", { key: id, type: "button", role: "tab", className: "bt-avedit-tab", "aria-selected": tab === id, onClick: () => setTab(id) }, t(label))) + (0, import_react34.createElement)("span", { ref: glide.thumb, className: "bt-thumb", "aria-hidden": true }), + [["bot", "Bot"], ["upload", "Upload"], ["library", "Library"]].map(([id, label]) => (0, import_react34.createElement)("button", { key: id, type: "button", role: "tab", className: "bt-avedit-tab", "aria-selected": tab === id, onClick: () => setTab(id) }, t(label))) ), - (0, import_react33.createElement)("button", { + (0, import_react34.createElement)("button", { type: "button", className: "bt-avedit-tab bt-avedit-reset", title: t("Reset character to default"), onClick: () => run2(actions.updateBot(bot.id, { avatar: null, color: null })) }, t("Reset")) ), - tab === "bot" ? (0, import_react33.createElement)(CharacterGrid, { + tab === "bot" ? (0, import_react34.createElement)(CharacterGrid, { look, hasPhoto, onShape: (shape) => run2(actions.updateBot(bot.id, { avatar: { shape } })), onColor: (color) => run2(actions.updateBot(bot.id, { color })) }) : null, - tab === "upload" ? (0, import_react33.createElement)( + tab === "upload" ? (0, import_react34.createElement)( "div", { className: "bt-dropzone", @@ -14802,15 +14915,15 @@ function AvatarEditor({ bot, actions, run: run2, onClose }) { upload(event.dataTransfer.files?.[0]); } }, - hasPhoto ? (0, import_react33.createElement)("img", { src: look.image, alt: "" }) : null, - (0, import_react33.createElement)("div", null, t("Drag, drop, or paste an image")), - (0, import_react33.createElement)( + hasPhoto ? (0, import_react34.createElement)("img", { src: look.image, alt: "" }) : null, + (0, import_react34.createElement)("div", null, t("Drag, drop, or paste an image")), + (0, import_react34.createElement)( "div", { className: "bt-actions", style: { justifyContent: "center" } }, - (0, import_react33.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => fileRef.current?.click() }, hasPhoto ? t("Replace") : t("Browse files")), - hasPhoto ? (0, import_react33.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => run2(actions.updateBot(bot.id, { avatar: hasShape(bot.avatar?.shape) ? { shape: bot.avatar.shape } : null })) }, t("Remove photo")) : null + (0, import_react34.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => fileRef.current?.click() }, hasPhoto ? t("Replace") : t("Browse files")), + hasPhoto ? (0, import_react34.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => run2(actions.updateBot(bot.id, { avatar: hasShape(bot.avatar?.shape) ? { shape: bot.avatar.shape } : null })) }, t("Remove photo")) : null ), - (0, import_react33.createElement)("input", { ref: fileRef, type: "file", accept: "image/png,image/jpeg,image/webp,image/gif", hidden: true, onChange: (event) => { + (0, import_react34.createElement)("input", { ref: fileRef, type: "file", accept: "image/png,image/jpeg,image/webp,image/gif", hidden: true, onChange: (event) => { const file = event.target.files?.[0]; event.target.value = ""; upload(file); @@ -14818,7 +14931,7 @@ function AvatarEditor({ bot, actions, run: run2, onClose }) { ) : null, // A photo from the library is the same photo the user uploaded before: the Bot // keeps its own copy, and the library keeps its entry. - tab === "library" ? (0, import_react33.createElement)(AvatarLibraryPanel, { + tab === "library" ? (0, import_react34.createElement)(AvatarLibraryPanel, { actions, onPick: (entry) => run2(actions.updateBot(bot.id, { avatar: { ...bot.avatar, image: entry.image } })) }) : null @@ -14827,22 +14940,22 @@ function AvatarEditor({ bot, actions, run: run2, onClose }) { function MemoryCard({ bot, actions }) { const count = useMemoryCount(bot.id, actions); const label = count === null ? t("Loading…") : count === 0 ? t("Nothing saved yet") : count === 1 ? t("1 entry") : t("{count} entries", { count }); - return (0, import_react33.createElement)( + return (0, import_react34.createElement)( Card2, { title: t("Memory") }, - (0, import_react33.createElement)( + (0, import_react34.createElement)( "button", { type: "button", className: "bt-set-row bt-bs-row", "aria-label": t("Manage {name}'s memory", { name: bot.name }), onClick: () => actions.openMemory(bot.id) }, - (0, import_react33.createElement)("span", { className: "bt-set-copy" }, (0, import_react33.createElement)("span", { className: "bt-bs-label" }, label)), - (0, import_react33.createElement)("span", { className: "bt-mem-row-go" }, t("Manage"), (0, import_react33.createElement)(ChevronRightIcon)) + (0, import_react34.createElement)("span", { className: "bt-set-copy" }, (0, import_react34.createElement)("span", { className: "bt-bs-label" }, label)), + (0, import_react34.createElement)("span", { className: "bt-mem-row-go" }, t("Manage"), (0, import_react34.createElement)(ChevronRightIcon)) ) ); } function BotSettingsForm({ bot, roster, actions, run: run2 }) { - const [editing, setEditing] = (0, import_react33.useState)(false); - const [confirming, setConfirming] = (0, import_react33.useState)(false); - const closeEditor = (0, import_react33.useCallback)(() => setEditing(false), []); - (0, import_react33.useEffect)(() => { + const [editing, setEditing] = (0, import_react34.useState)(false); + const [confirming, setConfirming] = (0, import_react34.useState)(false); + const closeEditor = (0, import_react34.useCallback)(() => setEditing(false), []); + (0, import_react34.useEffect)(() => { if (!confirming) return void 0; const timer = setTimeout(() => setConfirming(false), 4e3); return () => clearTimeout(timer); @@ -14859,63 +14972,63 @@ function BotSettingsForm({ bot, roster, actions, run: run2 }) { if (confirming) void run2(actions.deleteBot(bot.id)); else setConfirming(true); }; - (0, import_react33.useEffect)(() => { + (0, import_react34.useEffect)(() => { void actions.refreshModels?.(); }, [bot.id]); - return (0, import_react33.createElement)( + return (0, import_react34.createElement)( "div", { className: "bt-bs" }, - (0, import_react33.createElement)( + (0, import_react34.createElement)( "div", { className: "bt-bs-hero" }, - (0, import_react33.createElement)( + (0, import_react34.createElement)( "div", { className: "bt-avatar-anchor" }, - (0, import_react33.createElement)( + (0, import_react34.createElement)( "button", { type: "button", className: "bt-avatar-trigger", "aria-label": t("Edit Bot avatar"), "aria-expanded": editing, onClick: () => setEditing((value) => !value) }, - (0, import_react33.createElement)(BotMark, { bot, size: 64, live: true }), - (0, import_react33.createElement)("span", { className: "bt-avatar-pencil", "aria-hidden": true }, (0, import_react33.createElement)(PencilIcon)) + (0, import_react34.createElement)(BotMark, { bot, size: 64, live: true }), + (0, import_react34.createElement)("span", { className: "bt-avatar-pencil", "aria-hidden": true }, (0, import_react34.createElement)(PencilIcon)) ), - editing ? (0, import_react33.createElement)(AvatarEditor, { bot, actions, run: run2, onClose: closeEditor }) : null + editing ? (0, import_react34.createElement)(AvatarEditor, { bot, actions, run: run2, onClose: closeEditor }) : null ), - (0, import_react33.createElement)( + (0, import_react34.createElement)( "div", { className: "bt-bs-who" }, - (0, import_react33.createElement)("span", { className: "bt-bs-name" }, bot.name), - (0, import_react33.createElement)("span", { className: "bt-bs-sub" }, [bot.role, isMainBot ? t("Main Bot") : ""].filter(Boolean).join(" · ") || t("Bot")) + (0, import_react34.createElement)("span", { className: "bt-bs-name" }, bot.name), + (0, import_react34.createElement)("span", { className: "bt-bs-sub" }, [bot.role, isMainBot ? t("Main Bot") : ""].filter(Boolean).join(" · ") || t("Bot")) ) ), - (0, import_react33.createElement)( + (0, import_react34.createElement)( Card2, { title: t("Profile") }, - (0, import_react33.createElement)(Row, { label: t("Name") }, (0, import_react33.createElement)(InlineText, { label: t("Name"), value: bot.name, placeholder: "Bob", required: true, maxLength: 40, onSave: (name) => save({ name }) })), - (0, import_react33.createElement)(Row, { label: t("Label"), hint: t("Optional. Shown under the name.") }, (0, import_react33.createElement)(InlineText, { label: t("Label"), value: bot.role, placeholder: t("Research, admin…"), maxLength: 24, onSave: (role) => save({ role }) })) + (0, import_react34.createElement)(Row, { label: t("Name") }, (0, import_react34.createElement)(InlineText, { label: t("Name"), value: bot.name, placeholder: "Bob", required: true, maxLength: 40, onSave: (name) => save({ name }) })), + (0, import_react34.createElement)(Row, { label: t("Label"), hint: t("Optional. Shown under the name.") }, (0, import_react34.createElement)(InlineText, { label: t("Label"), value: bot.role, placeholder: t("Research, admin…"), maxLength: 24, onSave: (role) => save({ role }) })) ), - (0, import_react33.createElement)( + (0, import_react34.createElement)( Card2, { title: t("Model") }, - (0, import_react33.createElement)( + (0, import_react34.createElement)( "div", { className: "bt-set-row bt-bs-row" }, - (0, import_react33.createElement)("span", { className: "bt-set-copy" }, (0, import_react33.createElement)("span", { className: "bt-bs-label" }, t("Model")), (0, import_react33.createElement)("span", { className: "bt-set-hint" }, modelHint(bot, roster))), - (0, import_react33.createElement)(ModelMenu, { bot, roster, actions, run: run2 }) + (0, import_react34.createElement)("span", { className: "bt-set-copy" }, (0, import_react34.createElement)("span", { className: "bt-bs-label" }, t("Model")), (0, import_react34.createElement)("span", { className: "bt-set-hint" }, modelHint(bot, roster))), + (0, import_react34.createElement)(ModelMenu, { bot, roster, actions, run: run2 }) ) ), - (0, import_react33.createElement)( + (0, import_react34.createElement)( Card2, { title: t("Working folder") }, - (0, import_react33.createElement)( + (0, import_react34.createElement)( "div", { className: "bt-set-row bt-bs-row" }, - (0, import_react33.createElement)("span", { className: "bt-set-copy" }, (0, import_react33.createElement)("span", { className: "bt-bs-label" }, t("Folder"))), - (0, import_react33.createElement)(FolderMenu, { value: bot.workDir, actions, run: run2, onPick: (workDir) => save({ workDir }) }) + (0, import_react34.createElement)("span", { className: "bt-set-copy" }, (0, import_react34.createElement)("span", { className: "bt-bs-label" }, t("Folder"))), + (0, import_react34.createElement)(FolderMenu, { value: bot.workDir, actions, run: run2, onPick: (workDir) => save({ workDir }) }) ) ), - (0, import_react33.createElement)( + (0, import_react34.createElement)( Card2, { title: t("Privacy") }, - (0, import_react33.createElement)(SwitchRow, { + (0, import_react34.createElement)(SwitchRow, { label: t("Private"), hint: privacyHint, on: bot.private === true, @@ -14923,32 +15036,32 @@ function BotSettingsForm({ bot, roster, actions, run: run2 }) { onChange: (value) => save({ private: value }) }) ), - (0, import_react33.createElement)( + (0, import_react34.createElement)( Card2, { title: t("Instructions") }, - (0, import_react33.createElement)( + (0, import_react34.createElement)( Row, { label: t("What this Bot does"), hint: t("Its job on the team. Part of the Bot's system prompt."), stack: true }, - (0, import_react33.createElement)(InlineText, { label: t("Instructions"), value: bot.instructions, multiline: true, placeholder: t("What this Bot is responsible for…"), onSave: (instructions) => save({ instructions }) }) + (0, import_react34.createElement)(InlineText, { label: t("Instructions"), value: bot.instructions, multiline: true, placeholder: t("What this Bot is responsible for…"), onSave: (instructions) => save({ instructions }) }) ) ), - (0, import_react33.createElement)(BotCapabilitiesCard, { bot, roster, actions, run: run2, Card: Card2, SwitchRow }), - roster.memory === false ? null : (0, import_react33.createElement)(MemoryCard, { bot, actions }), - (0, import_react33.createElement)(BotSchedules, { bot, roster, actions }), - (0, import_react33.createElement)( + (0, import_react34.createElement)(BotCapabilitiesCard, { bot, roster, actions, run: run2, Card: Card2, SwitchRow }), + roster.memory === false ? null : (0, import_react34.createElement)(MemoryCard, { bot, actions }), + (0, import_react34.createElement)(BotSchedules, { bot, roster, actions }), + (0, import_react34.createElement)( Card2, { title: t("Main Bot") }, - onlyMain ? (0, import_react33.createElement)( + onlyMain ? (0, import_react34.createElement)( "div", { className: "bt-set-row bt-bs-row" }, - (0, import_react33.createElement)( + (0, import_react34.createElement)( "span", { className: "bt-set-copy" }, - (0, import_react33.createElement)("span", { className: "bt-bs-label" }, t("Main Bot")), - (0, import_react33.createElement)("span", { className: "bt-set-hint" }, t("The only Main Bot. To hand the role to another Bot, use Main Bot on the Bots page.")) + (0, import_react34.createElement)("span", { className: "bt-bs-label" }, t("Main Bot")), + (0, import_react34.createElement)("span", { className: "bt-set-hint" }, t("The only Main Bot. To hand the role to another Bot, use Main Bot on the Bots page.")) ), - (0, import_react33.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => actions.openSettings("bots") }, t("Change")) - ) : (0, import_react33.createElement)(SwitchRow, { + (0, import_react34.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => actions.openSettings("bots") }, t("Change")) + ) : (0, import_react34.createElement)(SwitchRow, { label: t("Main Bot"), hint: bot.private === true ? t("A private Bot cannot be a Main Bot.") : t("Can create and change Bots, and runs every group chat."), on: isMainBot, @@ -14957,31 +15070,31 @@ function BotSettingsForm({ bot, roster, actions, run: run2 }) { }) ), // The Main Bot tile is always first and always shown, like in the context menu. - isTile ? null : (0, import_react33.createElement)( + isTile ? null : (0, import_react34.createElement)( Card2, { title: t("Sidebar") }, - (0, import_react33.createElement)(SwitchRow, { label: t("Pin"), hint: t("Kept above the other chats."), on: bot.pinned === true, onChange: (pinned) => run2(actions.setFlags(bot.id, { pinned })) }), - isMainBot ? null : (0, import_react33.createElement)(SwitchRow, { label: t("Hide from sidebar"), hint: t("Search still finds it."), on: bot.hidden === true, onChange: (hidden) => run2(actions.setFlags(bot.id, { hidden })) }) + (0, import_react34.createElement)(SwitchRow, { label: t("Pin"), hint: t("Kept above the other chats."), on: bot.pinned === true, onChange: (pinned) => run2(actions.setFlags(bot.id, { pinned })) }), + isMainBot ? null : (0, import_react34.createElement)(SwitchRow, { label: t("Hide from sidebar"), hint: t("Search still finds it."), on: bot.hidden === true, onChange: (hidden) => run2(actions.setFlags(bot.id, { hidden })) }) ), - (0, import_react33.createElement)( + (0, import_react34.createElement)( Card2, { title: t("Manage") }, - bot.private === true ? null : (0, import_react33.createElement)( + bot.private === true ? null : (0, import_react34.createElement)( "button", { type: "button", className: "bt-set-row bt-bs-row", onClick: duplicate }, - (0, import_react33.createElement)("span", { className: "bt-set-copy" }, (0, import_react33.createElement)("span", { className: "bt-bs-label" }, t("Duplicate")), (0, import_react33.createElement)("span", { className: "bt-set-hint" }, t("A copy with the same job and model, and fresh memory."))), - (0, import_react33.createElement)("span", { className: "bt-chevron" }, (0, import_react33.createElement)(ChevronRightIcon)) + (0, import_react34.createElement)("span", { className: "bt-set-copy" }, (0, import_react34.createElement)("span", { className: "bt-bs-label" }, t("Duplicate")), (0, import_react34.createElement)("span", { className: "bt-set-hint" }, t("A copy with the same job and model, and fresh memory."))), + (0, import_react34.createElement)("span", { className: "bt-chevron" }, (0, import_react34.createElement)(ChevronRightIcon)) ), - isMainBot ? null : (0, import_react33.createElement)( + isMainBot ? null : (0, import_react34.createElement)( "button", { type: "button", className: "bt-set-row bt-bs-row bt-bs-danger", "data-confirm": confirming || void 0, onClick: remove }, - (0, import_react33.createElement)( + (0, import_react34.createElement)( "span", { className: "bt-set-copy" }, - (0, import_react33.createElement)("span", { className: "bt-bs-label" }, confirming ? t("Delete {name}?", { name: bot.name }) : t("Delete Bot")), - (0, import_react33.createElement)("span", { className: "bt-set-hint" }, confirming ? t("Click again to delete. Its chats are archived.") : t("Removes the Bot from the team.")) + (0, import_react34.createElement)("span", { className: "bt-bs-label" }, confirming ? t("Delete {name}?", { name: bot.name }) : t("Delete Bot")), + (0, import_react34.createElement)("span", { className: "bt-set-hint" }, confirming ? t("Click again to delete. Its chats are archived.") : t("Removes the Bot from the team.")) ), - (0, import_react33.createElement)("span", { className: "bt-chevron" }, (0, import_react33.createElement)(ChevronRightIcon)) + (0, import_react34.createElement)("span", { className: "bt-chevron" }, (0, import_react34.createElement)(ChevronRightIcon)) ) ) ); @@ -15041,7 +15154,7 @@ function createPayload({ name, look, image, model, effort, brief }) { } // src/client/create-bot.js -var import_react34 = require("react"); +var import_react35 = require("react"); var pick = (list) => list[Math.floor(Math.random() * list.length)]; var randomLook = (avoid = {}) => { const shapes = DEFAULT_SHAPES.filter((shape) => shape !== avoid.shape); @@ -15049,18 +15162,18 @@ var randomLook = (avoid = {}) => { return { shape: pick(shapes), color: pick(colors) }; }; function CreateBot({ roster, actions, start, brief = "", onBack, canGoBack, onCreated, inline = false }) { - const [look, setLook] = (0, import_react34.useState)(() => randomLook()); - const [image, setImage] = (0, import_react34.useState)(null); - const [library, setLibrary] = (0, import_react34.useState)(false); - const [name, setName] = (0, import_react34.useState)(start?.name ?? ""); - const [model, setModel] = (0, import_react34.useState)(() => startModel(roster)); - const [effort, setEffort] = (0, import_react34.useState)(void 0); - const [busy, setBusy] = (0, import_react34.useState)(false); - const [error, setError] = (0, import_react34.useState)(""); - const fileRef = (0, import_react34.useRef)(null); - const frame = (0, import_react34.useRef)(null); + const [look, setLook] = (0, import_react35.useState)(() => randomLook()); + const [image, setImage] = (0, import_react35.useState)(null); + const [library, setLibrary] = (0, import_react35.useState)(false); + const [name, setName] = (0, import_react35.useState)(start?.name ?? ""); + const [model, setModel] = (0, import_react35.useState)(() => startModel(roster)); + const [effort, setEffort] = (0, import_react35.useState)(void 0); + const [busy, setBusy] = (0, import_react35.useState)(false); + const [error, setError] = (0, import_react35.useState)(""); + const fileRef = (0, import_react35.useRef)(null); + const frame = (0, import_react35.useRef)(null); useEscape(onBack); - (0, import_react34.useEffect)(() => { + (0, import_react35.useEffect)(() => { if (inline) frame.current?.scrollIntoView({ block: "start", behavior: "smooth" }); }, []); const fallbackName = freshBotName(roster, t("New Bot")); @@ -15085,25 +15198,25 @@ function CreateBot({ roster, actions, start, brief = "", onBack, canGoBack, onCr avatarImage(file).then(setImage, (failure) => setError(failure?.message ?? String(failure))); }; const previewLook = image ? { ...look, image } : look; - const card = (0, import_react34.createElement)( + const card = (0, import_react35.createElement)( "div", { className: "bt-create-card" }, - (0, import_react34.createElement)( + (0, import_react35.createElement)( "div", { className: "bt-create-preview" }, // The key remounts the mark, so every new pick plays the pop. - (0, import_react34.createElement)( + (0, import_react35.createElement)( "span", { key: `${look.shape}:${look.color}:${image ? "photo" : ""}`, className: "bt-create-pop" }, - (0, import_react34.createElement)(BotMark, { look: previewLook, bot: { id: "new-bot" }, size: 88, live: true, gaze: true, pokeable: true }) + (0, import_react35.createElement)(BotMark, { look: previewLook, bot: { id: "new-bot" }, size: 88, live: true, gaze: true, pokeable: true }) ), - (0, import_react34.createElement)("span", { className: "bt-create-name" }, finalName) + (0, import_react35.createElement)("span", { className: "bt-create-name" }, finalName) ), - (0, import_react34.createElement)("div", { className: "bt-create-step" }, t("Look")), - (0, import_react34.createElement)( + (0, import_react35.createElement)("div", { className: "bt-create-step" }, t("Look")), + (0, import_react35.createElement)( "div", { className: "bt-create-looks" }, - (0, import_react34.createElement)(CharacterGrid, { + (0, import_react35.createElement)(CharacterGrid, { look, hasPhoto: Boolean(image), onShape: (shape) => { @@ -15115,17 +15228,17 @@ function CreateBot({ roster, actions, start, brief = "", onBack, canGoBack, onCr setLook((current) => ({ ...current, color })); } }), - (0, import_react34.createElement)( + (0, import_react35.createElement)( "div", { className: "bt-actions bt-create-lookbar" }, - (0, import_react34.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => { + (0, import_react35.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => { setImage(null); setLook((current) => randomLook(current)); } }, t("Shuffle")), - (0, import_react34.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => fileRef.current?.click() }, image ? t("Replace photo") : t("Upload photo")), - (0, import_react34.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", "aria-expanded": library, onClick: () => setLibrary((value) => !value) }, t("Library")), - image ? (0, import_react34.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => setImage(null) }, t("Remove photo")) : null, - (0, import_react34.createElement)("input", { ref: fileRef, type: "file", accept: "image/png,image/jpeg,image/webp,image/gif", hidden: true, onChange: (event) => { + (0, import_react35.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => fileRef.current?.click() }, image ? t("Replace photo") : t("Upload photo")), + (0, import_react35.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", "aria-expanded": library, onClick: () => setLibrary((value) => !value) }, t("Library")), + image ? (0, import_react35.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => setImage(null) }, t("Remove photo")) : null, + (0, import_react35.createElement)("input", { ref: fileRef, type: "file", accept: "image/png,image/jpeg,image/webp,image/gif", hidden: true, onChange: (event) => { const file = event.target.files?.[0]; event.target.value = ""; upload(file); @@ -15133,15 +15246,15 @@ function CreateBot({ roster, actions, start, brief = "", onBack, canGoBack, onCr ) ), // The library is a block of its own under the look, not a part of the button row. - library ? (0, import_react34.createElement)(AvatarLibraryPanel, { actions, onPick: (entry) => { + library ? (0, import_react35.createElement)(AvatarLibraryPanel, { actions, onPick: (entry) => { setImage(entry.image); setLibrary(false); } }) : null, - (0, import_react34.createElement)( + (0, import_react35.createElement)( "label", { className: "bt-field" }, - (0, import_react34.createElement)("span", { className: "bt-field-label" }, t("Name")), - (0, import_react34.createElement)("input", { + (0, import_react35.createElement)("span", { className: "bt-field-label" }, t("Name")), + (0, import_react35.createElement)("input", { className: "bt-input", autoFocus: !inline, value: name, @@ -15156,54 +15269,54 @@ function CreateBot({ roster, actions, start, brief = "", onBack, canGoBack, onCr } } }), - problem ? (0, import_react34.createElement)("span", { className: "bt-note bt-danger" }, hostText(problem)) : clash ? (0, import_react34.createElement)("span", { className: "bt-note bt-danger" }, t("A Bot named {name} already exists", { name: finalName })) : null + problem ? (0, import_react35.createElement)("span", { className: "bt-note bt-danger" }, hostText(problem)) : clash ? (0, import_react35.createElement)("span", { className: "bt-note bt-danger" }, t("A Bot named {name} already exists", { name: finalName })) : null ), - (0, import_react34.createElement)( + (0, import_react35.createElement)( "div", { className: "bt-field" }, - (0, import_react34.createElement)("span", { className: "bt-field-label" }, t("Model")), - (0, import_react34.createElement)(ModelMenu, { bot: { id: "new-bot", name: finalName, model: model || void 0, effort }, roster, actions, wide: true, onPick: (ref) => { + (0, import_react35.createElement)("span", { className: "bt-field-label" }, t("Model")), + (0, import_react35.createElement)(ModelMenu, { bot: { id: "new-bot", name: finalName, model: model || void 0, effort }, roster, actions, wide: true, onPick: (ref) => { setModel(ref); setEffort(void 0); }, onPickEffort: (picked) => setEffort(picked ?? null) }), - (0, import_react34.createElement)("span", { className: "bt-note" }, model ? t("The Bot runs on this model. You can change it later in its details.") : (roster.models ?? []).length > 0 ? t("Pick a model here, or the Bot asks for one in its chat.") : t("Add a provider and a model in DeepSeek Harness first, or pick one in the Bot's chat later.")) + (0, import_react35.createElement)("span", { className: "bt-note" }, model ? t("The Bot runs on this model. You can change it later in its details.") : (roster.models ?? []).length > 0 ? t("Pick a model here, or the Bot asks for one in its chat.") : t("Add a provider and a model in DeepSeek Harness first, or pick one in the Bot's chat later.")) ), - error ? (0, import_react34.createElement)("div", { className: "bt-error", role: "alert", style: { padding: 0 } }, error) : null, - (0, import_react34.createElement)( + error ? (0, import_react35.createElement)("div", { className: "bt-error", role: "alert", style: { padding: 0 } }, error) : null, + (0, import_react35.createElement)( "div", { className: "bt-create-foot" }, - (0, import_react34.createElement)("button", { type: "button", className: "bt-soft", onClick: onBack }, canGoBack ? t("Back") : t("Cancel")), - (0, import_react34.createElement)("button", { type: "button", className: "bt-send bt-create-go", disabled: busy || clash || Boolean(problem), onClick: () => void create() }, busy ? t("Creating…") : t("Create")) + (0, import_react35.createElement)("button", { type: "button", className: "bt-soft", onClick: onBack }, canGoBack ? t("Back") : t("Cancel")), + (0, import_react35.createElement)("button", { type: "button", className: "bt-send bt-create-go", disabled: busy || clash || Boolean(problem), onClick: () => void create() }, busy ? t("Creating…") : t("Create")) ) ); - if (inline) return (0, import_react34.createElement)("div", { ref: frame, className: "bt-create-inline", role: "group", "aria-label": t("Create Bot") }, card); - return (0, import_react34.createElement)( + if (inline) return (0, import_react35.createElement)("div", { ref: frame, className: "bt-create-inline", role: "group", "aria-label": t("Create Bot") }, card); + return (0, import_react35.createElement)( "div", { className: "bt-create", role: "dialog", "aria-label": t("Create Bot") }, - (0, import_react34.createElement)( + (0, import_react35.createElement)( "div", { className: "bt-create-head" }, - canGoBack ? (0, import_react34.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Back to new chat"), onClick: onBack }, (0, import_react34.createElement)(ChevronLeftIcon)) : (0, import_react34.createElement)("span", { className: "bt-create-gap" }), - (0, import_react34.createElement)("span", { className: "bt-create-title" }, t("Create Bot")), - (0, import_react34.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Close"), onClick: () => actions.closeOverlay() }, (0, import_react34.createElement)(CloseIcon)) + canGoBack ? (0, import_react35.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Back to new chat"), onClick: onBack }, (0, import_react35.createElement)(ChevronLeftIcon)) : (0, import_react35.createElement)("span", { className: "bt-create-gap" }), + (0, import_react35.createElement)("span", { className: "bt-create-title" }, t("Create Bot")), + (0, import_react35.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Close"), onClick: () => actions.closeOverlay() }, (0, import_react35.createElement)(CloseIcon)) ), - (0, import_react34.createElement)("div", { className: "bt-create-body" }, card) + (0, import_react35.createElement)("div", { className: "bt-create-body" }, card) ); } // src/client/new-chat.js -var import_react35 = require("react"); +var import_react36 = require("react"); function NewChat({ mode, roster, actions }) { - const [query, setQuery] = (0, import_react35.useState)(""); - const [picked, setPicked] = (0, import_react35.useState)([]); - const [group, setGroup] = (0, import_react35.useState)(mode === "group"); - const [admin, setAdmin] = (0, import_react35.useState)(null); - const [message, setMessage] = (0, import_react35.useState)(""); - const [busy, setBusy] = (0, import_react35.useState)(false); - const [error, setError] = (0, import_react35.useState)(""); - const [cursor, setCursor] = (0, import_react35.useState)(0); - const [draft, setDraft] = (0, import_react35.useState)(mode === "create" ? { name: "", fromList: false } : null); - const inputRef = (0, import_react35.useRef)(null); + const [query, setQuery] = (0, import_react36.useState)(""); + const [picked, setPicked] = (0, import_react36.useState)([]); + const [group, setGroup] = (0, import_react36.useState)(mode === "group"); + const [admin, setAdmin] = (0, import_react36.useState)(null); + const [message, setMessage] = (0, import_react36.useState)(""); + const [busy, setBusy] = (0, import_react36.useState)(false); + const [error, setError] = (0, import_react36.useState)(""); + const [cursor, setCursor] = (0, import_react36.useState)(0); + const [draft, setDraft] = (0, import_react36.useState)(mode === "create" ? { name: "", fromList: false } : null); + const inputRef = (0, import_react36.useRef)(null); const close = () => actions.closeOverlay(); useEscape(close); const paneLeft = usePaneLeft(); @@ -15289,14 +15402,14 @@ function NewChat({ mode, roster, actions }) { }); const options = []; if (!group && picked.length === 0 && mode !== "search" && wanted === "") { - options.push({ key: "new", icon: (0, import_react35.createElement)(PlusIcon), label: t("Create new Bot"), run: createBot }); - options.push({ key: "group", icon: (0, import_react35.createElement)(PeopleIcon), label: t("Create group chat"), run: () => { + options.push({ key: "new", icon: (0, import_react36.createElement)(PlusIcon), label: t("Create new Bot"), run: createBot }); + options.push({ key: "group", icon: (0, import_react36.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_react35.createElement)(import_dsh_client_ui_primitives.FishLogo, { size: 16 }), label: t("Add DSH Agent"), run: () => run2(async () => { + options.push({ key: "agent", icon: (0, import_react36.createElement)(import_dsh_client_ui_primitives.FishLogo, { size: 16 }), label: t("Add DSH Agent"), run: () => run2(async () => { await actions.addAgent(); close(); }) }); @@ -15305,19 +15418,19 @@ function NewChat({ mode, roster, actions }) { for (const bot of matches) { 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_react35.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_react36.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_react35.useRef)(null); + const drop = (0, import_react36.useRef)(null); useMorph(drop, listed); if (draft) { - return (0, import_react35.createElement)( + return (0, import_react36.createElement)( "div", { className: "bt-pane", style: { left: paneLeft } }, - (0, import_react35.createElement)(CreateBot, { + (0, import_react36.createElement)(CreateBot, { roster, actions, start: draft, @@ -15338,33 +15451,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_react35.createElement)( + return (0, import_react36.createElement)( "div", { className: "bt-pane", style: { left: paneLeft } }, - (0, import_react35.createElement)( + (0, import_react36.createElement)( "div", { className: "bt-newchat", role: "dialog", "aria-label": mode === "search" ? t("Search") : t("New chat") }, - (0, import_react35.createElement)( + (0, import_react36.createElement)( "div", { className: "bt-to" }, - (0, import_react35.createElement)("span", { className: "bt-to-label" }, t("To:")), - adminBot ? (0, import_react35.createElement)( + (0, import_react36.createElement)("span", { className: "bt-to-label" }, t("To:")), + adminBot ? (0, import_react36.createElement)( "span", { key: adminBot.id, className: "bt-token bt-token-admin", title: t("Admin") }, - (0, import_react35.createElement)(BotMark, { bot: adminBot, size: 16 }), + (0, import_react36.createElement)(BotMark, { bot: adminBot, size: 16 }), adminBot.name, - (0, import_react35.createElement)(AdminStar), - (0, import_react35.createElement)("button", { type: "button", "aria-label": t("Remove {name}", { name: adminBot.name }), onClick: () => setAdmin(null) }, "×") + (0, import_react36.createElement)(AdminStar), + (0, import_react36.createElement)("button", { type: "button", "aria-label": t("Remove {name}", { name: adminBot.name }), onClick: () => setAdmin(null) }, "×") ) : null, - choosingAdmin ? (0, import_react35.createElement)("span", { className: "bt-to-star", "aria-hidden": true }, (0, import_react35.createElement)(AdminStar)) : null, - pickedBots.map((bot) => (0, import_react35.createElement)( + choosingAdmin ? (0, import_react36.createElement)("span", { className: "bt-to-star", "aria-hidden": true }, (0, import_react36.createElement)(AdminStar)) : null, + pickedBots.map((bot) => (0, import_react36.createElement)( "span", { key: bot.id, className: "bt-token" }, - (0, import_react35.createElement)(BotMark, { bot, size: 16 }), + (0, import_react36.createElement)(BotMark, { bot, size: 16 }), bot.name, - (0, import_react35.createElement)("button", { type: "button", "aria-label": t("Remove {name}", { name: bot.name }), onClick: () => setPicked((current) => current.filter((id) => id !== bot.id)) }, "×") + (0, import_react36.createElement)("button", { type: "button", "aria-label": t("Remove {name}", { name: bot.name }), onClick: () => setPicked((current) => current.filter((id) => id !== bot.id)) }, "×") )), - (0, import_react35.createElement)("input", { + (0, import_react36.createElement)("input", { ref: inputRef, autoFocus: true, value: query, @@ -15388,20 +15501,20 @@ ${listed}`, { axis: "y", ...QUICK_EDGES }); } else if (event.key === "Backspace" && query === "") unpick(); } }), - group && admin !== null ? (0, import_react35.createElement)("button", { + group && admin !== null ? (0, import_react36.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_react35.createElement)("button", { type: "button", className: "bt-x", "aria-label": t("Close new chat"), onClick: close }, "×") + (0, import_react36.createElement)("button", { type: "button", className: "bt-x", "aria-label": t("Close new chat"), onClick: close }, "×") ), - (0, import_react35.createElement)("div", { ref: drop, className: "bt-drop" }, (0, import_react35.createElement)( + (0, import_react36.createElement)("div", { ref: drop, className: "bt-drop" }, (0, import_react36.createElement)( "div", { ref: glide.box, role: "listbox", "aria-label": t("Recipients"), className: "bt-drop-list" }, - (0, import_react35.createElement)("span", { ref: glide.thumb, className: "bt-thumb", "aria-hidden": true }), - options.length === 0 ? (0, import_react35.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_react35.createElement)( + (0, import_react36.createElement)("span", { ref: glide.thumb, className: "bt-thumb", "aria-hidden": true }), + options.length === 0 ? (0, import_react36.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_react36.createElement)( "button", { key: option.key, @@ -15413,21 +15526,21 @@ ${listed}`, { axis: "y", ...QUICK_EDGES }); onMouseEnter: () => setCursor(index), onClick: option.run }, - option.bot ? (0, import_react35.createElement)(BotMark, { bot: option.bot, size: 22 }) : (0, import_react35.createElement)("span", { className: "bt-option-icon" }, option.icon), - (0, import_react35.createElement)("span", { className: "bt-option-label" }, option.label), - option.hint && index === active ? (0, import_react35.createElement)("span", { className: "bt-option-hint" }, option.hint) : null + option.bot ? (0, import_react36.createElement)(BotMark, { bot: option.bot, size: 22 }) : (0, import_react36.createElement)("span", { className: "bt-option-icon" }, option.icon), + (0, import_react36.createElement)("span", { className: "bt-option-label" }, option.label), + option.hint && index === active ? (0, import_react36.createElement)("span", { className: "bt-option-hint" }, option.hint) : null )) )), - (0, import_react35.createElement)("div", { className: "bt-nc-spacer" }), - error ? (0, import_react35.createElement)("div", { className: "bt-error" }, error) : null, - (0, import_react35.createElement)( + (0, import_react36.createElement)("div", { className: "bt-nc-spacer" }), + error ? (0, import_react36.createElement)("div", { className: "bt-error" }, error) : null, + (0, import_react36.createElement)( "div", { className: "bt-nc-compose" }, - (0, import_react35.createElement)( + (0, import_react36.createElement)( "div", { className: "bt-nc-card" }, - (0, import_react35.createElement)("span", { className: "bt-nc-plus", "aria-hidden": true }, (0, import_react35.createElement)(PlusIcon)), - (0, import_react35.createElement)("textarea", { + (0, import_react36.createElement)("span", { className: "bt-nc-plus", "aria-hidden": true }, (0, import_react36.createElement)(PlusIcon)), + (0, import_react36.createElement)("textarea", { rows: 1, value: message, placeholder, @@ -15440,7 +15553,7 @@ ${listed}`, { axis: "y", ...QUICK_EDGES }); } } }), - (0, import_react35.createElement)("button", { type: "button", className: "bt-nc-send", "aria-label": t("Send message"), disabled: busy || message.trim() === "" || picked.length === 0, onClick: sendMessage }, (0, import_react35.createElement)(ArrowUpIcon)) + (0, import_react36.createElement)("button", { type: "button", className: "bt-nc-send", "aria-label": t("Send message"), disabled: busy || message.trim() === "" || picked.length === 0, onClick: sendMessage }, (0, import_react36.createElement)(ArrowUpIcon)) ) ) ) @@ -15448,14 +15561,14 @@ ${listed}`, { axis: "y", ...QUICK_EDGES }); } // src/client/exchange.js -var import_react36 = require("react"); +var import_react37 = require("react"); var SHEET_EXIT_MS = 220; function ExchangeDialog({ pair, roster, actions }) { - const [entries2, setEntries] = (0, import_react36.useState)(null); - const [leaving, setLeaving] = (0, import_react36.useState)(false); - const log = (0, import_react36.useRef)(null); - const atEnd = (0, import_react36.useRef)(true); - (0, import_react36.useLayoutEffect)(() => { + const [entries2, setEntries] = (0, import_react37.useState)(null); + const [leaving, setLeaving] = (0, import_react37.useState)(false); + const log = (0, import_react37.useRef)(null); + const atEnd = (0, import_react37.useRef)(true); + (0, import_react37.useLayoutEffect)(() => { if (entries2 !== null && atEnd.current && log.current) log.current.scrollTop = log.current.scrollHeight; }, [entries2]); const close = () => { @@ -15464,7 +15577,7 @@ function ExchangeDialog({ pair, roster, actions }) { setTimeout(() => actions.closeOverlay(), SHEET_EXIT_MS); }; useEscape(close); - (0, import_react36.useEffect)(() => { + (0, import_react37.useEffect)(() => { let stop = false; let timer; let seen = null; @@ -15491,53 +15604,53 @@ function ExchangeDialog({ pair, roster, actions }) { const flat = layoutOf(roster.prefs) === "flat"; let lastDay = 0; const paneLeft = usePaneLeft(); - return (0, import_react36.createElement)( + return (0, import_react37.createElement)( "div", { className: "bt-pane bt-exchange", style: { left: paneLeft }, "data-leaving": leaving || void 0 }, - (0, import_react36.createElement)( + (0, import_react37.createElement)( "div", { className: "bt-dialog", role: "dialog", "aria-label": t("Bot exchange") }, - (0, import_react36.createElement)("div", { className: "bt-head" }, (0, import_react36.createElement)( + (0, import_react37.createElement)("div", { className: "bt-head" }, (0, import_react37.createElement)( "span", { className: "bt-pill", style: { cursor: "default" } }, - left ? (0, import_react36.createElement)(BotMark, { bot: left, size: 22 }) : null, + left ? (0, import_react37.createElement)(BotMark, { bot: left, size: 22 }) : null, left?.name ?? "?", - (0, import_react36.createElement)("span", { className: "bt-swap" }, "⇄"), - right ? (0, import_react36.createElement)(BotMark, { bot: right, size: 22 }) : null, + (0, import_react37.createElement)("span", { className: "bt-swap" }, "⇄"), + right ? (0, import_react37.createElement)(BotMark, { bot: right, size: 22 }) : null, right?.name ?? "?" )), - (0, import_react36.createElement)( + (0, import_react37.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_react36.createElement)("div", { className: "bt-hint" }, t("Loading…")) : entries2.length === 0 ? (0, import_react36.createElement)("div", { className: "bt-hint" }, t("No messages yet")) : entries2.map((entry) => { + entries2 === null ? (0, import_react37.createElement)("div", { className: "bt-hint" }, t("Loading…")) : entries2.length === 0 ? (0, import_react37.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_react36.createElement)("span", { className: "bt-lead" }, (0, import_react36.createElement)(BotMark, { bot, size: 22 })); - return (0, import_react36.createElement)( - import_react36.Fragment, + const lead = (0, import_react37.createElement)("span", { className: "bt-lead" }, (0, import_react37.createElement)(BotMark, { bot, size: 22 })); + return (0, import_react37.createElement)( + import_react37.Fragment, { key: entry.id }, - showDay ? (0, import_react36.createElement)("time", { className: "bt-time" }, dayLabel(entry.time)) : null, - (0, import_react36.createElement)( + showDay ? (0, import_react37.createElement)("time", { className: "bt-time" }, dayLabel(entry.time)) : null, + (0, import_react37.createElement)( "div", { className: "bt-group-msg" }, - (0, import_react36.createElement)("span", { className: "bt-group-name", style: flat ? void 0 : { color: inkText(colorOf(bot)) } }, flat ? lead : null, bot.name), - (0, import_react36.createElement)(Bubbles, { texts: [stripLongNote(entry.text)], roster, selfId: bot.id, actions, whole, lead: flat ? null : lead }) + (0, import_react37.createElement)("span", { className: "bt-group-name", style: flat ? void 0 : { color: inkText(colorOf(bot)) } }, flat ? lead : null, bot.name), + (0, import_react37.createElement)(Bubbles, { texts: [stripLongNote(entry.text)], roster, selfId: bot.id, actions, whole, lead: flat ? null : lead }) ) ); }) ), - (0, import_react36.createElement)("div", { className: "bt-dialog-foot" }, (0, import_react36.createElement)("button", { type: "button", className: "bt-soft", onClick: close }, t("Close Chat"))) + (0, import_react37.createElement)("div", { className: "bt-dialog-foot" }, (0, import_react37.createElement)("button", { type: "button", className: "bt-soft", onClick: close }, t("Close Chat"))) ) ); } // src/client/voice.js -var import_react37 = require("react"); +var import_react38 = 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", @@ -15569,8 +15682,8 @@ function watchReply(read, watch, consume) { }; } function useMicLevel(enabled) { - const [level, setLevel] = (0, import_react37.useState)(0); - (0, import_react37.useEffect)(() => { + const [level, setLevel] = (0, import_react38.useState)(0); + (0, import_react38.useEffect)(() => { if (!enabled || !navigator.mediaDevices?.getUserMedia) return void 0; let stream = null; let audio = null; @@ -15620,18 +15733,18 @@ function VoiceMode({ sessionId, roster, actions, useSessions, useSessionStatus } const entry = Array.isArray(outline) ? outline[outline.length - 1] : void 0; return entry ? `${outline.length}|${entry.turn}` : "0|"; }); - const [speech] = (0, import_react37.useState)(() => actions.speech()); - const [phase, setPhase] = (0, import_react37.useState)(speech ? "starting" : speechApi() ? "listening" : "unsupported"); - const [catalog, setCatalog] = (0, import_react37.useState)(null); - const [heard, setHeard] = (0, import_react37.useState)(""); - const [said, setSaid] = (0, import_react37.useState)(""); - const [note, setNote] = (0, import_react37.useState)(""); - const [serviceLevel, setServiceLevel] = (0, import_react37.useState)(0); - const [cycle, setCycle] = (0, import_react37.useState)(0); - const waiting = (0, import_react37.useRef)(null); - const reply = (0, import_react37.useRef)(lastReply); + const [speech] = (0, import_react38.useState)(() => actions.speech()); + const [phase, setPhase] = (0, import_react38.useState)(speech ? "starting" : speechApi() ? "listening" : "unsupported"); + const [catalog, setCatalog] = (0, import_react38.useState)(null); + const [heard, setHeard] = (0, import_react38.useState)(""); + const [said, setSaid] = (0, import_react38.useState)(""); + const [note, setNote] = (0, import_react38.useState)(""); + const [serviceLevel, setServiceLevel] = (0, import_react38.useState)(0); + const [cycle, setCycle] = (0, import_react38.useState)(0); + const waiting = (0, import_react38.useRef)(null); + const reply = (0, import_react38.useRef)(lastReply); reply.current = lastReply; - const turn = (0, import_react37.useRef)(0); + const turn = (0, import_react38.useRef)(0); const paneLeft = usePaneLeft(); const close = () => { turn.current += 1; @@ -15651,12 +15764,12 @@ function VoiceMode({ sessionId, roster, actions, useSessions, useSessionStatus } dictation.stop(); submit(text); }); - (0, import_react37.useEffect)(() => { + (0, import_react38.useEffect)(() => { if (!note) return void 0; const timer = setTimeout(() => setNote(""), 2600); return () => clearTimeout(timer); }, [note]); - (0, import_react37.useEffect)(() => { + (0, import_react38.useEffect)(() => { if (!speech) return void 0; let live = true; speechCatalog(speech).then(({ catalog: next, usable }) => { @@ -15671,16 +15784,16 @@ function VoiceMode({ sessionId, roster, actions, useSessions, useSessionStatus } }; }, [speech]); const listen = phase === "listening"; - (0, import_react37.useEffect)(() => { + (0, import_react38.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_react37.useEffect)(() => { + (0, import_react38.useEffect)(() => { if (phase !== "listening") dictation.stop(); }, [phase]); - (0, import_react37.useEffect)(() => { + (0, import_react38.useEffect)(() => { if (!speech || !catalog || !listen) return void 0; const own = turn.current; let capture = null; @@ -15742,7 +15855,7 @@ function VoiceMode({ sessionId, roster, actions, useSessions, useSessionStatus } setServiceLevel(0); }; }, [speech, catalog, listen, cycle]); - (0, import_react37.useEffect)(() => { + (0, import_react38.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)); @@ -15777,7 +15890,7 @@ function VoiceMode({ sessionId, roster, actions, useSessions, useSessionStatus } } ); }, [phase, running, lastReply]); - (0, import_react37.useEffect)(() => () => window.speechSynthesis?.cancel(), []); + (0, import_react38.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"; @@ -15791,7 +15904,7 @@ function VoiceMode({ sessionId, roster, actions, useSessions, useSessionStatus } window.speechSynthesis?.cancel(); setPhase("paused"); }; - (0, import_react37.useEffect)(() => { + (0, import_react38.useEffect)(() => { if (phase !== "preparing" || !speech) return void 0; let stopped = false; let timer; @@ -15843,55 +15956,55 @@ function VoiceMode({ sessionId, roster, actions, useSessions, useSessionStatus } }; const caption = phase === "speaking" ? said : heard; const shownNote = note || dictation.note; - return (0, import_react37.createElement)( + return (0, import_react38.createElement)( "div", { className: "bt-pane bt-voice-pane", style: { left: paneLeft } }, - (0, import_react37.createElement)( + (0, import_react38.createElement)( "div", { className: "bt-voice-stage", role: "dialog", "aria-label": t("Voice chat with {name}", { name }), "data-phase": phase === "transcribing" ? "thinking" : phase }, - (0, import_react37.createElement)( + (0, import_react38.createElement)( "div", { className: "bt-voice-orb", style: { "--bt-level": level } }, - (0, import_react37.createElement)("span", { className: "bt-voice-ring", "aria-hidden": true }), - (0, import_react37.createElement)("span", { className: "bt-voice-ring bt-voice-ring-2", "aria-hidden": true }), - bot ? (0, import_react37.createElement)(BotMark, { bot, size: 112, state: markState, live: true, gaze: phase === "listening" }) : room2 ? (0, import_react37.createElement)(RoomAvatar, { room: room2, roster, size: 112 }) : null + (0, import_react38.createElement)("span", { className: "bt-voice-ring", "aria-hidden": true }), + (0, import_react38.createElement)("span", { className: "bt-voice-ring bt-voice-ring-2", "aria-hidden": true }), + bot ? (0, import_react38.createElement)(BotMark, { bot, size: 112, state: markState, live: true, gaze: phase === "listening" }) : room2 ? (0, import_react38.createElement)(RoomAvatar, { room: room2, roster, size: 112 }) : null ), - (0, import_react37.createElement)("div", { className: "bt-voice-name" }, name), - (0, import_react37.createElement)( + (0, import_react38.createElement)("div", { className: "bt-voice-name" }, name), + (0, import_react38.createElement)( "div", { className: "bt-voice-status", role: "status" }, - phase === "thinking" ? (0, import_react37.createElement)(Shimmer, null, t("Thinking…")) : phase === "transcribing" ? (0, import_react37.createElement)(Shimmer, null, t("Recognizing…")) : VOICE_LABELS[phase] ? t(VOICE_LABELS[phase]) : "" + phase === "thinking" ? (0, import_react38.createElement)(Shimmer, null, t("Thinking…")) : phase === "transcribing" ? (0, import_react38.createElement)(Shimmer, null, t("Recognizing…")) : VOICE_LABELS[phase] ? t(VOICE_LABELS[phase]) : "" ), - (0, import_react37.createElement)("div", { className: "bt-voice-caption", key: `${phase}:${caption.slice(0, 12)}` }, caption), - openSetup ? (0, import_react37.createElement)("button", { type: "button", className: "bt-voice-setup", onClick: startSetup }, t("Set up voice input")) : null, - shownNote ? (0, import_react37.createElement)("div", { className: "bt-voice-note" }, shownNote) : null + (0, import_react38.createElement)("div", { className: "bt-voice-caption", key: `${phase}:${caption.slice(0, 12)}` }, caption), + openSetup ? (0, import_react38.createElement)("button", { type: "button", className: "bt-voice-setup", onClick: startSetup }, t("Set up voice input")) : null, + shownNote ? (0, import_react38.createElement)("div", { className: "bt-voice-note" }, shownNote) : null ), - (0, import_react37.createElement)( + (0, import_react38.createElement)( "div", { className: "bt-voice-bar" }, - (0, import_react37.createElement)("button", { + (0, import_react38.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_react37.createElement)(MicIcon, { size: 20 }), phase === "paused" ? (0, import_react37.createElement)("span", { className: "bt-voice-slash", "aria-hidden": true }) : null), - (0, import_react37.createElement)("button", { type: "button", className: "bt-voice-btn bt-voice-end", "aria-label": t("End voice chat"), onClick: close }, (0, import_react37.createElement)(CloseIcon)) + }, (0, import_react38.createElement)(MicIcon, { size: 20 }), phase === "paused" ? (0, import_react38.createElement)("span", { className: "bt-voice-slash", "aria-hidden": true }) : null), + (0, import_react38.createElement)("button", { type: "button", className: "bt-voice-btn bt-voice-end", "aria-label": t("End voice chat"), onClick: close }, (0, import_react38.createElement)(CloseIcon)) ) ); } // src/client/permission-picker.js -var import_react38 = require("react"); +var import_react39 = require("react"); var LABELS = { "read-only": "Read only", "workspace-write": "Workspace", "danger-full-access": "Full access" }; var DANGER = /* @__PURE__ */ new Set(["danger-full-access"]); var presetDanger = (value) => DANGER.has(value); var presetName = (value, catalog) => LABELS[value] ? t(LABELS[value]) : catalog?.options?.find((option) => option.value === value)?.name ?? value; function PermissionPicker({ catalog, saved, onPick, repick = false }) { - const [pending, setPending] = (0, import_react38.useState)(null); - const flight = (0, import_react38.useRef)({ value: void 0, latest: void 0 }); - (0, import_react38.useEffect)(() => { + const [pending, setPending] = (0, import_react39.useState)(null); + const flight = (0, import_react39.useRef)({ value: void 0, latest: void 0 }); + (0, import_react39.useEffect)(() => { const flying = flight.current.value; if (pending === saved && (flying === void 0 || flying === pending)) setPending(null); }, [pending, saved]); @@ -15918,10 +16031,10 @@ function PermissionPicker({ catalog, saved, onPick, repick = false }) { } send(value); }; - return (0, import_react38.createElement)( + return (0, import_react39.createElement)( Segmented, { label: t("Permissions"), value: current }, - catalog.options.map((option) => (0, import_react38.createElement)("button", { + catalog.options.map((option) => (0, import_react39.createElement)("button", { key: option.value, type: "button", "aria-pressed": option.value === current, @@ -15933,7 +16046,7 @@ function PermissionPicker({ catalog, saved, onPick, repick = false }) { } // src/client/group-settings.js -var import_react39 = require("react"); +var import_react40 = require("react"); var ROOM_MODES = [ ["admin", "Admin leads", "Plain messages go to the admin, who calls others with @Name."], ["everyone", "Everyone", "Every member answers in turn, admin first."] @@ -15946,26 +16059,26 @@ function roomSubtitle(room2, roster) { function GroupPermission({ room: room2, catalog, update }) { if (!catalog?.options?.length) return null; const shared2 = room2.permission !== void 0; - return (0, import_react39.createElement)( + return (0, import_react40.createElement)( Card2, { title: t("Permissions") }, - (0, import_react39.createElement)(SwitchRow, { + (0, import_react40.createElement)(SwitchRow, { label: t("Same for every member"), hint: t("Replaces each member's own permissions in this group."), on: shared2, onChange: (on) => update({ permission: on ? catalog.defaultPreset ?? catalog.options[0].value : null }) }), - shared2 ? (0, import_react39.createElement)( + shared2 ? (0, import_react40.createElement)( "div", { className: "bt-set-row bt-bs-row bt-bs-stack bt-gs-perm bt-veil" }, - (0, import_react39.createElement)(PermissionPicker, { catalog, saved: room2.permission, onPick: (permission) => update({ permission }) }) + (0, import_react40.createElement)(PermissionPicker, { catalog, saved: room2.permission, onPick: (permission) => update({ permission }) }) ) : null ); } function GroupSettingsForm({ room: room2, roster, actions, run: run2, onDeleted }) { - const [adding, setAdding] = (0, import_react39.useState)(false); - const [confirming, setConfirming] = (0, import_react39.useState)(false); - (0, import_react39.useEffect)(() => { + const [adding, setAdding] = (0, import_react40.useState)(false); + const [confirming, setConfirming] = (0, import_react40.useState)(false); + (0, import_react40.useEffect)(() => { if (!confirming) return void 0; const timer = setTimeout(() => setConfirming(false), 4e3); return () => clearTimeout(timer); @@ -15989,41 +16102,41 @@ function GroupSettingsForm({ room: room2, roster, actions, run: run2, onDeleted if (done) onDeleted?.(); }); }; - return (0, import_react39.createElement)( + return (0, import_react40.createElement)( "div", { className: "bt-bs" }, - (0, import_react39.createElement)( + (0, import_react40.createElement)( "div", { className: "bt-bs-hero" }, - (0, import_react39.createElement)(RoomAvatar, { room: room2, roster, size: 64 }), - (0, import_react39.createElement)( + (0, import_react40.createElement)(RoomAvatar, { room: room2, roster, size: 64 }), + (0, import_react40.createElement)( "div", { className: "bt-bs-who" }, - (0, import_react39.createElement)("span", { className: "bt-bs-name" }, room2.name), - (0, import_react39.createElement)("span", { className: "bt-bs-sub" }, roomSubtitle(room2, roster)) + (0, import_react40.createElement)("span", { className: "bt-bs-name" }, room2.name), + (0, import_react40.createElement)("span", { className: "bt-bs-sub" }, roomSubtitle(room2, roster)) ) ), - (0, import_react39.createElement)( + (0, import_react40.createElement)( Card2, { title: t("Profile") }, - (0, import_react39.createElement)( + (0, import_react40.createElement)( Row, { label: t("Name"), hint: t("Leave it empty to name the group after its members.") }, - (0, import_react39.createElement)(InlineText, { label: t("Group name"), value: room2.named ? room2.name : "", placeholder: t("Name after members"), maxLength: 60, onSave: (name) => update({ name }) }) + (0, import_react40.createElement)(InlineText, { label: t("Group name"), value: room2.named ? room2.name : "", placeholder: t("Name after members"), maxLength: 60, onSave: (name) => update({ name }) }) ), - (0, import_react39.createElement)( + (0, import_react40.createElement)( Row, { label: t("Notice"), hint: t("Every member reads it before speaking in this group."), stack: true }, - (0, import_react39.createElement)(InlineText, { label: t("Group notice"), value: room2.notice, multiline: true, maxLength: 2e3, placeholder: t("Shared instructions every member reads before speaking…"), onSave: (notice) => update({ notice }) }) + (0, import_react40.createElement)(InlineText, { label: t("Group notice"), value: room2.notice, multiline: true, maxLength: 2e3, placeholder: t("Shared instructions every member reads before speaking…"), onSave: (notice) => update({ notice }) }) ) ), - (0, import_react39.createElement)( + (0, import_react40.createElement)( Card2, { title: t("Who answers") }, - (0, import_react39.createElement)( + (0, import_react40.createElement)( "div", { className: "bt-set-row bt-bs-row bt-bs-stack" }, - (0, import_react39.createElement)(Segmented, { label: t("Who answers"), value: mode }, ROOM_MODES.map(([id, label]) => (0, import_react39.createElement)("button", { + (0, import_react40.createElement)(Segmented, { label: t("Who answers"), value: mode }, ROOM_MODES.map(([id, label]) => (0, import_react40.createElement)("button", { key: id, type: "button", "aria-pressed": mode === id, @@ -16033,87 +16146,87 @@ function GroupSettingsForm({ room: room2, roster, actions, run: run2, onDeleted if (mode !== id) void update({ mode: id }); } }, t(label)))), - (0, import_react39.createElement)("span", { key: mode, className: "bt-set-hint bt-veil" }, `${t(modeHint)} ${t("@mentions always pick who answers.")}`) + (0, import_react40.createElement)("span", { key: mode, className: "bt-set-hint bt-veil" }, `${t(modeHint)} ${t("@mentions always pick who answers.")}`) ) ), - (0, import_react39.createElement)( + (0, import_react40.createElement)( Card2, { title: t("Working folder") }, - (0, import_react39.createElement)( + (0, import_react40.createElement)( "div", { className: "bt-set-row bt-bs-row" }, - (0, import_react39.createElement)("span", { className: "bt-set-copy" }, (0, import_react39.createElement)("span", { className: "bt-bs-label" }, t("Folder"))), - (0, import_react39.createElement)(FolderMenu, { value: room2.workDir, group: true, actions, run: run2, onPick: (workDir) => update({ workDir }) }) + (0, import_react40.createElement)("span", { className: "bt-set-copy" }, (0, import_react40.createElement)("span", { className: "bt-bs-label" }, t("Folder"))), + (0, import_react40.createElement)(FolderMenu, { value: room2.workDir, group: true, actions, run: run2, onPick: (workDir) => update({ workDir }) }) ) ), - (0, import_react39.createElement)(GroupPermission, { room: room2, catalog: roster.permissions, update }), - (0, import_react39.createElement)( + (0, import_react40.createElement)(GroupPermission, { room: room2, catalog: roster.permissions, update }), + (0, import_react40.createElement)( Card2, { title: t("Members · {count}", { count: members.length }) }, members.map((member) => { const leads = room2.admin === member.id; - return (0, import_react39.createElement)( + return (0, import_react40.createElement)( "div", { key: member.id, className: "bt-set-row bt-bs-row bt-gs-member" }, - (0, import_react39.createElement)( + (0, import_react40.createElement)( "button", { type: "button", className: "bt-gs-who", title: t("Open {name}'s chat", { name: member.name }), onClick: () => openBot(member.id) }, - (0, import_react39.createElement)(BotAvatar, { bot: member, size: 26, main: isMainOf(roster, member.id), admin: leads, live: false }), - (0, import_react39.createElement)("span", { className: "bt-row-title" }, member.name), - leads ? (0, import_react39.createElement)("span", { className: "bt-tag" }, t("Admin")) : null + (0, import_react40.createElement)(BotAvatar, { bot: member, size: 26, main: isMainOf(roster, member.id), admin: leads, live: false }), + (0, import_react40.createElement)("span", { className: "bt-row-title" }, member.name), + leads ? (0, import_react40.createElement)("span", { className: "bt-tag" }, t("Admin")) : null ), - leads ? (0, import_react39.createElement)("button", { type: "button", className: "bt-mini", title: t("Leave the group without an admin"), onClick: () => update({ admin: null }) }, t("Unset")) : (0, import_react39.createElement)("button", { type: "button", className: "bt-mini", onClick: () => update({ admin: member.id }) }, t("Make admin")), - members.length > 2 ? (0, import_react39.createElement)("button", { type: "button", className: "bt-x", "aria-label": t("Remove {name} from the group", { name: member.name }), title: t("Remove from group"), onClick: () => update({ remove: [member.id] }) }, "×") : null + leads ? (0, import_react40.createElement)("button", { type: "button", className: "bt-mini", title: t("Leave the group without an admin"), onClick: () => update({ admin: null }) }, t("Unset")) : (0, import_react40.createElement)("button", { type: "button", className: "bt-mini", onClick: () => update({ admin: member.id }) }, t("Make admin")), + members.length > 2 ? (0, import_react40.createElement)("button", { type: "button", className: "bt-x", "aria-label": t("Remove {name} from the group", { name: member.name }), title: t("Remove from group"), onClick: () => update({ remove: [member.id] }) }, "×") : null ); }), adding ? [ - ...outside.map((bot) => (0, import_react39.createElement)( + ...outside.map((bot) => (0, import_react40.createElement)( "button", { key: bot.id, type: "button", className: "bt-set-row bt-bs-row bt-gs-pick", onClick: () => { setAdding(false); void update({ add: [bot.id] }); } }, - (0, import_react39.createElement)(BotMark, { bot, size: 22 }), - (0, import_react39.createElement)("span", { className: "bt-set-copy" }, (0, import_react39.createElement)("span", { className: "bt-bs-label" }, bot.name)), - (0, import_react39.createElement)("span", { className: "bt-set-hint" }, t("Add")) + (0, import_react40.createElement)(BotMark, { bot, size: 22 }), + (0, import_react40.createElement)("span", { className: "bt-set-copy" }, (0, import_react40.createElement)("span", { className: "bt-bs-label" }, bot.name)), + (0, import_react40.createElement)("span", { className: "bt-set-hint" }, t("Add")) )), - (0, import_react39.createElement)("button", { key: "cancel", type: "button", className: "bt-set-row bt-bs-row bt-gs-add", onClick: () => setAdding(false) }, t("Cancel")) - ] : outside.length > 0 ? (0, import_react39.createElement)("button", { type: "button", className: "bt-set-row bt-bs-row bt-gs-add", onClick: () => setAdding(true) }, (0, import_react39.createElement)(PlusIcon), t("Add member")) : null, - (0, import_react39.createElement)("div", { className: "bt-set-row bt-gs-note" }, (0, import_react39.createElement)( + (0, import_react40.createElement)("button", { key: "cancel", type: "button", className: "bt-set-row bt-bs-row bt-gs-add", onClick: () => setAdding(false) }, t("Cancel")) + ] : outside.length > 0 ? (0, import_react40.createElement)("button", { type: "button", className: "bt-set-row bt-bs-row bt-gs-add", onClick: () => setAdding(true) }, (0, import_react40.createElement)(PlusIcon), t("Add member")) : null, + (0, import_react40.createElement)("div", { className: "bt-set-row bt-gs-note" }, (0, import_react40.createElement)( "span", { className: "bt-set-hint" }, // The host checks for two members on every change, even a rename. members.length < 2 ? t("Add a Bot first: a group chat needs at least two.") : admin ? t("{name} leads this group: it can call members with @Name, change the group, and post here.", { name: admin.name }) : t("No admin yet. An admin can call members with @Name, change the group, and post here.") )) ), - (0, import_react39.createElement)( + (0, import_react40.createElement)( Card2, { title: t("Sidebar") }, - (0, import_react39.createElement)(SwitchRow, { label: t("Pin"), hint: t("Kept above the other chats."), on: room2.pinned === true, onChange: (pinned) => run2(actions.setFlags(room2.id, { pinned })) }), - (0, import_react39.createElement)(SwitchRow, { label: t("Hide from sidebar"), hint: t("Search still finds it."), on: room2.hidden === true, onChange: (hidden) => run2(actions.setFlags(room2.id, { hidden })) }) + (0, import_react40.createElement)(SwitchRow, { label: t("Pin"), hint: t("Kept above the other chats."), on: room2.pinned === true, onChange: (pinned) => run2(actions.setFlags(room2.id, { pinned })) }), + (0, import_react40.createElement)(SwitchRow, { label: t("Hide from sidebar"), hint: t("Search still finds it."), on: room2.hidden === true, onChange: (hidden) => run2(actions.setFlags(room2.id, { hidden })) }) ), - (0, import_react39.createElement)( + (0, import_react40.createElement)( Card2, { title: t("Manage") }, - (0, import_react39.createElement)( + (0, import_react40.createElement)( "button", { type: "button", className: "bt-set-row bt-bs-row bt-bs-danger", "data-confirm": confirming || void 0, onClick: remove }, - (0, import_react39.createElement)( + (0, import_react40.createElement)( "span", { className: "bt-set-copy" }, - (0, import_react39.createElement)("span", { className: "bt-bs-label" }, confirming ? t("Delete {name}?", { name: room2.name }) : t("Delete group")), - (0, import_react39.createElement)("span", { className: "bt-set-hint" }, confirming ? t("Click again to delete. Its history is archived.") : t("Removes the group chat. Its members stay on the team.")) + (0, import_react40.createElement)("span", { className: "bt-bs-label" }, confirming ? t("Delete {name}?", { name: room2.name }) : t("Delete group")), + (0, import_react40.createElement)("span", { className: "bt-set-hint" }, confirming ? t("Click again to delete. Its history is archived.") : t("Removes the group chat. Its members stay on the team.")) ), - (0, import_react39.createElement)("span", { className: "bt-chevron" }, (0, import_react39.createElement)(ChevronRightIcon)) + (0, import_react40.createElement)("span", { className: "bt-chevron" }, (0, import_react40.createElement)(ChevronRightIcon)) ) ) ); } function NewGroupForm({ roster, actions, run: run2, onCreated, onCancel }) { - const [admin, setAdmin] = (0, import_react39.useState)(null); - const [members, setMembers] = (0, import_react39.useState)([]); - const [name, setName] = (0, import_react39.useState)(""); - const [busy, setBusy] = (0, import_react39.useState)(false); + const [admin, setAdmin] = (0, import_react40.useState)(null); + const [members, setMembers] = (0, import_react40.useState)([]); + const [name, setName] = (0, import_react40.useState)(""); + const [busy, setBusy] = (0, import_react40.useState)(false); const toggle = (id) => setMembers((list) => list.includes(id) ? list.filter((item) => item !== id) : [...list, id]); const pickAdmin = (id) => { setAdmin(id); @@ -16129,48 +16242,48 @@ function NewGroupForm({ roster, actions, run: run2, onCreated, onCancel }) { if (done && room2) onCreated(room2); else setBusy(false); }; - const chip = (bot, on, onClick, role) => (0, import_react39.createElement)("button", { + const chip = (bot, on, onClick, role) => (0, import_react40.createElement)("button", { key: bot.id, type: "button", role, className: "bt-ng-chip", "aria-checked": on, onClick - }, (0, import_react39.createElement)(BotAvatar, { bot, size: 22, badge: false, live: false }), (0, import_react39.createElement)("span", { className: "bt-ng-name" }, bot.name), on && role === "radio" ? (0, import_react39.createElement)(AdminStar) : null); - return (0, import_react39.createElement)( + }, (0, import_react40.createElement)(BotAvatar, { bot, size: 22, badge: false, live: false }), (0, import_react40.createElement)("span", { className: "bt-ng-name" }, bot.name), on && role === "radio" ? (0, import_react40.createElement)(AdminStar) : null); + return (0, import_react40.createElement)( "div", { className: "bt-set-card bt-ng" }, - (0, import_react39.createElement)( + (0, import_react40.createElement)( "div", { className: "bt-set-row bt-bs-row bt-bs-stack" }, - (0, import_react39.createElement)("span", { className: "bt-set-copy" }, (0, import_react39.createElement)("span", { className: "bt-bs-label bt-ng-label" }, (0, import_react39.createElement)(AdminStar), t("Choose the group admin"))), - (0, import_react39.createElement)( + (0, import_react40.createElement)("span", { className: "bt-set-copy" }, (0, import_react40.createElement)("span", { className: "bt-bs-label bt-ng-label" }, (0, import_react40.createElement)(AdminStar), t("Choose the group admin"))), + (0, import_react40.createElement)( "div", { className: "bt-ng-picks", role: "radiogroup", "aria-label": t("Group admin") }, roster.bots.map((bot) => chip(bot, admin === bot.id, () => pickAdmin(bot.id), "radio")) ) ), - admin === null ? null : (0, import_react39.createElement)( + admin === null ? null : (0, import_react40.createElement)( "div", { className: "bt-set-row bt-bs-row bt-bs-stack bt-ng-step" }, - (0, import_react39.createElement)("span", { className: "bt-set-copy" }, (0, import_react39.createElement)("span", { className: "bt-bs-label" }, t("Who to chat with…"))), - (0, import_react39.createElement)( + (0, import_react40.createElement)("span", { className: "bt-set-copy" }, (0, import_react40.createElement)("span", { className: "bt-bs-label" }, t("Who to chat with…"))), + (0, import_react40.createElement)( "div", { className: "bt-ng-picks", role: "group", "aria-label": t("Members") }, roster.bots.filter((bot) => bot.id !== admin).map((bot) => chip(bot, members.includes(bot.id), () => toggle(bot.id), "checkbox")) ) ), - admin === null || members.length === 0 ? null : (0, import_react39.createElement)( + admin === null || members.length === 0 ? null : (0, import_react40.createElement)( "label", { className: "bt-set-row bt-bs-row bt-ng-step" }, - (0, import_react39.createElement)("span", { className: "bt-set-copy" }, (0, import_react39.createElement)("span", { className: "bt-bs-label" }, t("Name"))), - (0, import_react39.createElement)("input", { className: "bt-bs-input", value: name, maxLength: 60, placeholder: t("Name after members"), onChange: (event) => setName(event.target.value) }) + (0, import_react40.createElement)("span", { className: "bt-set-copy" }, (0, import_react40.createElement)("span", { className: "bt-bs-label" }, t("Name"))), + (0, import_react40.createElement)("input", { className: "bt-bs-input", value: name, maxLength: 60, placeholder: t("Name after members"), onChange: (event) => setName(event.target.value) }) ), - (0, import_react39.createElement)( + (0, import_react40.createElement)( "div", { className: "bt-set-row bt-task-foot" }, - (0, import_react39.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: onCancel }, t("Cancel")), - (0, import_react39.createElement)("button", { type: "button", className: "bt-send bt-soft-sm", disabled: busy || admin === null || members.length === 0, onClick: () => void create() }, t("Create group chat")) + (0, import_react40.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: onCancel }, t("Cancel")), + (0, import_react40.createElement)("button", { type: "button", className: "bt-send bt-soft-sm", disabled: busy || admin === null || members.length === 0, onClick: () => void create() }, t("Create group chat")) ) ); } @@ -16198,11 +16311,11 @@ var GROUP_SETTINGS_CSS = ` `; // src/client/kept-private.js -var import_react40 = require("react"); +var import_react41 = require("react"); function KeptPrivateSection({ roster, actions, run: run2, Section, Row: Row3 }) { const kept = roster.privateArchives ?? []; - const [confirming, setConfirming] = (0, import_react40.useState)(null); - (0, import_react40.useEffect)(() => { + const [confirming, setConfirming] = (0, import_react41.useState)(null); + (0, import_react41.useEffect)(() => { if (confirming === null) return void 0; const timer = setTimeout(() => setConfirming(null), 4e3); return () => clearTimeout(timer); @@ -16216,14 +16329,14 @@ function KeptPrivateSection({ roster, actions, run: run2, Section, Row: Row3 }) setConfirming(null); void run2(actions.releasePrivate(entry.id)); }; - return (0, import_react40.createElement)( + return (0, import_react41.createElement)( Section, { title: t("Closed after deletion · {count}", { count: kept.length }) }, - kept.map((entry) => (0, import_react40.createElement)(Row3, { + kept.map((entry) => (0, import_react41.createElement)(Row3, { key: entry.id, label: entry.name, hint: confirming === entry.id ? t("Click again to remove. Other Bots can then read its folder, memory and chats.") : entry.workDir - }, (0, import_react40.createElement)("button", { type: "button", className: `bt-soft bt-soft-sm${confirming === entry.id ? " bt-danger" : ""}`, onClick: () => release(entry) }, t("Remove protection")))) + }, (0, import_react41.createElement)("button", { type: "button", className: `bt-soft bt-soft-sm${confirming === entry.id ? " bt-danger" : ""}`, onClick: () => release(entry) }, t("Remove protection")))) ); } @@ -16360,7 +16473,7 @@ function percent2(part, whole) { } // src/client/usage-page.js -var import_react41 = require("react"); +var import_react42 = require("react"); var HEAT_WEEKS = 53; var TOP_SERIES = 7; var RING_R = 42; @@ -16407,9 +16520,9 @@ function titleOf2(range, bucket) { return dates({ year: "numeric", month: "long" }).format(bucket.start); } function useTween(value) { - const [shown, setShown] = (0, import_react41.useState)(0); - const from = (0, import_react41.useRef)(0); - (0, import_react41.useEffect)(() => { + const [shown, setShown] = (0, import_react42.useState)(0); + const from = (0, import_react42.useRef)(0); + (0, import_react42.useEffect)(() => { if (reducedMotion() || typeof requestAnimationFrame !== "function") { from.current = value; setShown(value); @@ -16429,9 +16542,9 @@ function useTween(value) { }, [value]); return shown; } -var glyphBox = (size, icon2) => (0, import_react41.createElement)("span", { className: "bt-us-glyph", style: { width: size, height: size } }, (0, import_react41.createElement)(icon2)); +var glyphBox = (size, icon2) => (0, import_react42.createElement)("span", { className: "bt-us-glyph", style: { width: size, height: size } }, (0, import_react42.createElement)(icon2)); function ModelGlyph({ name, paint, size }) { - return (0, import_react41.createElement)("span", { + return (0, import_react42.createElement)("span", { className: "bt-us-model", "aria-hidden": true, style: { width: size, height: size, fontSize: Math.round(size * 0.42), background: `color-mix(in srgb, ${paint} 20%, var(--bt-card))`, color: `color-mix(in srgb, ${paint} 72%, var(--bt-ink))` } @@ -16448,7 +16561,7 @@ function ownerFace(owner, roster) { sub: owner.deleted ? t("Deleted") : role.toLowerCase() === name.toLowerCase() ? "" : role, paint: paintCss(colorOf(bot)), stops: GRADIENTS[colorOf(bot)], - glyph: (size) => (0, import_react41.createElement)(BotAvatar, { bot, size, badge: false, live: false }) + glyph: (size) => (0, import_react42.createElement)(BotAvatar, { bot, size, badge: false, live: false }) }; } if (owner.kind === "room") { @@ -16458,7 +16571,7 @@ function ownerFace(owner, roster) { name: owner.name || t("Deleted group chat"), sub: owner.deleted ? t("Deleted") : t("Group chat"), paint: "var(--bt-us-rest)", - glyph: (size) => room2 ? (0, import_react41.createElement)(RoomAvatar, { room: room2, roster, size }) : glyphBox(size, ChatsIcon) + glyph: (size) => room2 ? (0, import_react42.createElement)(RoomAvatar, { room: room2, roster, size }) : glyphBox(size, ChatsIcon) }; } if (owner.kind === "agent") { @@ -16480,30 +16593,30 @@ function Tabs({ label, value, options, onChange, boxRef }) { const names = options.map(([, text]) => text).join("\n"); const glide = useGlide(`${value} ${names}`, { box: boxRef }); - return (0, import_react41.createElement)( + return (0, import_react42.createElement)( "div", { ref: glide.box, className: "bt-us-tabs", role: "group", "aria-label": label }, - (0, import_react41.createElement)("span", { ref: glide.thumb, className: "bt-thumb", "aria-hidden": true }), - options.map(([id, text, icon2]) => (0, import_react41.createElement)("button", { key: id, type: "button", "aria-pressed": value === id, onClick: () => onChange(id) }, icon2 ? (0, import_react41.createElement)(icon2) : null, text)) + (0, import_react42.createElement)("span", { ref: glide.thumb, className: "bt-thumb", "aria-hidden": true }), + options.map(([id, text, icon2]) => (0, import_react42.createElement)("button", { key: id, type: "button", "aria-pressed": value === id, onClick: () => onChange(id) }, icon2 ? (0, import_react42.createElement)(icon2) : null, text)) ); } function Stats({ range, total, previous }) { const shown = useTween(total.total); const change = previous > 0 ? Math.round((total.total - previous) / previous * 100) : null; - const cell = (label, value) => (0, import_react41.createElement)("div", { className: "bt-us-stat" }, (0, import_react41.createElement)("span", { className: "bt-us-stat-label" }, label), (0, import_react41.createElement)("span", { className: "bt-us-stat-value" }, value)); - return (0, import_react41.createElement)( + const cell = (label, value) => (0, import_react42.createElement)("div", { className: "bt-us-stat" }, (0, import_react42.createElement)("span", { className: "bt-us-stat-label" }, label), (0, import_react42.createElement)("span", { className: "bt-us-stat-value" }, value)); + return (0, import_react42.createElement)( "section", { className: "bt-us-stats", style: { "--i": 0 } }, - (0, import_react41.createElement)( + (0, import_react42.createElement)( "div", { className: "bt-us-stat bt-us-stat-main" }, - (0, import_react41.createElement)("span", { className: "bt-us-stat-label" }, lastText(range)), - (0, import_react41.createElement)( + (0, import_react42.createElement)("span", { className: "bt-us-stat-label" }, lastText(range)), + (0, import_react42.createElement)( "span", { className: "bt-us-stat-value" }, compact(shown), - (0, import_react41.createElement)("small", null, t("tokens")), - change === null ? null : (0, import_react41.createElement)( + (0, import_react42.createElement)("small", null, t("tokens")), + change === null ? null : (0, import_react42.createElement)( "span", { className: "bt-us-delta", title: compareText(range) }, `${change >= 0 ? "↑" : "↓"} ${Math.abs(change)}%` @@ -16521,83 +16634,83 @@ function niceTop(max) { return [1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10].map((scale) => scale * step).find((value) => value >= max); } function Chart({ range, columns: columns2, series, tipSeries, by, onBy, onPick }) { - const [hover, setHover] = (0, import_react41.useState)(null); + const [hover, setHover] = (0, import_react42.useState)(null); const top = niceTop(Math.max(0, ...columns2.map((column) => column.total))); const count = columns2.length; const fillOf = new Map(series.map((entry) => [entry.key, entry.fill])); const tipOf = new Map(tipSeries.map((entry) => [entry.key, entry])); const tip = hover === null ? null : columns2[hover]; const tipSide = hover !== null && hover >= count / 2 ? { right: `calc(${(count - hover) / count * 100}% + 8px)` } : { left: `calc(${(hover + 1) / count * 100}% + 8px)` }; - return (0, import_react41.createElement)( + return (0, import_react42.createElement)( "section", { className: "bt-us-card bt-us-chart", style: { "--i": 1 } }, - (0, import_react41.createElement)( + (0, import_react42.createElement)( "div", { className: "bt-us-card-head" }, - (0, import_react41.createElement)("h3", null, t("Tokens over time"), (0, import_react41.createElement)("span", null, unitLabel(range.unit))), - onBy ? (0, import_react41.createElement)(Tabs, { label: t("Group usage by"), value: by, onChange: onBy, options: [["bot", t("By Bot")], ["model", t("By model")]] }) : null + (0, import_react42.createElement)("h3", null, t("Tokens over time"), (0, import_react42.createElement)("span", null, unitLabel(range.unit))), + onBy ? (0, import_react42.createElement)(Tabs, { label: t("Group usage by"), value: by, onChange: onBy, options: [["bot", t("By Bot")], ["model", t("By model")]] }) : null ), - (0, import_react41.createElement)( + (0, import_react42.createElement)( "div", { className: "bt-us-chart-body" }, - (0, import_react41.createElement)( + (0, import_react42.createElement)( "div", { className: "bt-us-plot", "data-hover": hover === null ? void 0 : "", onMouseLeave: () => setHover(null) }, - [1, 0.5].map((level) => (0, import_react41.createElement)("div", { key: level, className: "bt-us-grid", style: { bottom: `${level * 100}%` } }, (0, import_react41.createElement)("span", null, compact(top * level)))), - (0, import_react41.createElement)("div", { className: "bt-us-grid bt-us-base", style: { bottom: 0 } }, (0, import_react41.createElement)("span", null, "0")), - (0, import_react41.createElement)( + [1, 0.5].map((level) => (0, import_react42.createElement)("div", { key: level, className: "bt-us-grid", style: { bottom: `${level * 100}%` } }, (0, import_react42.createElement)("span", null, compact(top * level)))), + (0, import_react42.createElement)("div", { className: "bt-us-grid bt-us-base", style: { bottom: 0 } }, (0, import_react42.createElement)("span", null, "0")), + (0, import_react42.createElement)( "div", { className: "bt-us-cols" }, - columns2.map((column, at) => (0, import_react41.createElement)("div", { + columns2.map((column, at) => (0, import_react42.createElement)("div", { key: `${range.from ? `${range.from}~${range.to}` : range.id}:${column.key}`, className: "bt-us-col", "data-on": hover === at ? "" : void 0, onMouseEnter: () => setHover(at) - }, column.total > 0 ? (0, import_react41.createElement)( + }, column.total > 0 ? (0, import_react42.createElement)( "div", { className: "bt-us-stack", style: { height: `${column.total / top * 100}%`, "--i": at } }, - column.parts.map(([key, value]) => value > 0 ? (0, import_react41.createElement)("i", { key, style: { flexGrow: value, background: fillOf.get(key) } }) : null) - ) : (0, import_react41.createElement)("div", { className: "bt-us-stub" }))) + column.parts.map(([key, value]) => value > 0 ? (0, import_react42.createElement)("i", { key, style: { flexGrow: value, background: fillOf.get(key) } }) : null) + ) : (0, import_react42.createElement)("div", { className: "bt-us-stub" }))) ), - tip ? (0, import_react41.createElement)( + tip ? (0, import_react42.createElement)( "div", { className: "bt-us-tip", style: tipSide }, - (0, import_react41.createElement)("div", { className: "bt-us-tip-title" }, tip.title), - (0, import_react41.createElement)("div", { className: "bt-us-tip-total" }, t("{count} tokens", { count: full(tip.total) })), - tip.tip.filter(([, value]) => value > 0).sort((a, b) => b[1] - a[1]).map(([key, value]) => (0, import_react41.createElement)( + (0, import_react42.createElement)("div", { className: "bt-us-tip-title" }, tip.title), + (0, import_react42.createElement)("div", { className: "bt-us-tip-total" }, t("{count} tokens", { count: full(tip.total) })), + tip.tip.filter(([, value]) => value > 0).sort((a, b) => b[1] - a[1]).map(([key, value]) => (0, import_react42.createElement)( "div", { key, className: "bt-us-tip-row" }, - (0, import_react41.createElement)("i", { className: "bt-us-dot", style: { background: tipOf.get(key)?.fill } }), - (0, import_react41.createElement)("span", null, tipOf.get(key)?.name), - (0, import_react41.createElement)("b", null, compact(value)) + (0, import_react42.createElement)("i", { className: "bt-us-dot", style: { background: tipOf.get(key)?.fill } }), + (0, import_react42.createElement)("span", null, tipOf.get(key)?.name), + (0, import_react42.createElement)("b", null, compact(value)) )) ) : null ), - (0, import_react41.createElement)( + (0, import_react42.createElement)( "div", { className: "bt-us-ticks", "aria-hidden": true }, // A preset counts its labels back from now; a picked span forward from its first day. - columns2.map((column, at) => (0, import_react41.createElement)( + columns2.map((column, at) => (0, import_react42.createElement)( "span", { key: column.key, "data-now": at === count - 1 && range.ends !== false ? "" : void 0 }, (range.from ? at : count - 1 - at) % range.stride === 0 ? column.tick : "" )) ) ), - series.length > 1 || series[0]?.pick ? (0, import_react41.createElement)( + series.length > 1 || series[0]?.pick ? (0, import_react42.createElement)( "div", { className: "bt-us-legend" }, - series.map((entry) => (0, import_react41.createElement)(entry.pick ? "button" : "span", { + series.map((entry) => (0, import_react42.createElement)(entry.pick ? "button" : "span", { key: entry.key, className: "bt-us-key", ...entry.pick ? { type: "button", onClick: () => onPick(entry.pick) } : {} - }, (0, import_react41.createElement)("i", { className: "bt-us-dot", style: { background: entry.fill } }), entry.name)) + }, (0, import_react42.createElement)("i", { className: "bt-us-dot", style: { background: entry.fill } }), entry.name)) ) : null ); } function Row2({ kind, glyph, name, sub, sum, whole, fill: fill2, index, onClick }) { const width = whole > 0 ? Math.max(sum.total > 0 ? 2 : 0, sum.total / whole * 100) : 0; - return (0, import_react41.createElement)( + return (0, import_react42.createElement)( onClick ? "button" : "div", { className: "bt-us-row", @@ -16606,69 +16719,69 @@ function Row2({ kind, glyph, name, sub, sum, whole, fill: fill2, index, onClick title: t("{tokens} tokens · {calls} calls", { tokens: full(sum.total), calls: full(sum.calls) }), ...onClick ? { type: "button", onClick } : {} }, - glyph ? (0, import_react41.createElement)("span", { className: "bt-us-row-glyph" }, glyph) : null, - (0, import_react41.createElement)( + glyph ? (0, import_react42.createElement)("span", { className: "bt-us-row-glyph" }, glyph) : null, + (0, import_react42.createElement)( "span", { className: "bt-us-row-body" }, - (0, import_react41.createElement)( + (0, import_react42.createElement)( "span", { className: "bt-us-row-line" }, - (0, import_react41.createElement)("span", { className: "bt-us-row-name" }, name), - sub ? (0, import_react41.createElement)("span", { className: "bt-us-row-sub" }, sub) : null + (0, import_react42.createElement)("span", { className: "bt-us-row-name" }, name), + sub ? (0, import_react42.createElement)("span", { className: "bt-us-row-sub" }, sub) : null ), - (0, import_react41.createElement)("span", { className: "bt-us-track" }, (0, import_react41.createElement)("span", { style: { width: `${width}%`, background: fill2 } })) + (0, import_react42.createElement)("span", { className: "bt-us-track" }, (0, import_react42.createElement)("span", { style: { width: `${width}%`, background: fill2 } })) ), - (0, import_react41.createElement)("span", { className: "bt-us-row-num" }, (0, import_react41.createElement)("b", null, compact(sum.total)), (0, import_react41.createElement)("small", null, `${percent2(sum.total, whole)}%`)) + (0, import_react42.createElement)("span", { className: "bt-us-row-num" }, (0, import_react42.createElement)("b", null, compact(sum.total)), (0, import_react42.createElement)("small", null, `${percent2(sum.total, whole)}%`)) ); } function ListCard({ title, count, index, children }) { - return (0, import_react41.createElement)( + return (0, import_react42.createElement)( "section", { className: "bt-us-card", style: { "--i": index } }, - (0, import_react41.createElement)("div", { className: "bt-us-card-head" }, (0, import_react41.createElement)("h3", null, title, count === void 0 ? null : (0, import_react41.createElement)("span", null, count))), - (0, import_react41.createElement)("div", { className: "bt-us-rows" }, children) + (0, import_react42.createElement)("div", { className: "bt-us-card-head" }, (0, import_react42.createElement)("h3", null, title, count === void 0 ? null : (0, import_react42.createElement)("span", null, count))), + (0, import_react42.createElement)("div", { className: "bt-us-rows" }, children) ); } function Profile({ face, share, range }) { const arc = Math.max(0, Math.min(1, share)) * RING; - return (0, import_react41.createElement)( + return (0, import_react42.createElement)( "section", { className: "bt-us-profile" }, - (0, import_react41.createElement)( + (0, import_react42.createElement)( "span", { className: "bt-us-ring" }, - (0, import_react41.createElement)( + (0, import_react42.createElement)( "svg", { viewBox: "0 0 96 96", "aria-hidden": true }, - face.stops ? (0, import_react41.createElement)("defs", null, (0, import_react41.createElement)( + face.stops ? (0, import_react42.createElement)("defs", null, (0, import_react42.createElement)( "linearGradient", { id: "bt-us-ring-paint", x1: 0, y1: 1, x2: 1, y2: 0 }, - face.stops.map(([offset, color]) => (0, import_react41.createElement)("stop", { key: offset, offset, stopColor: color })) + face.stops.map(([offset, color]) => (0, import_react42.createElement)("stop", { key: offset, offset, stopColor: color })) )) : null, - (0, import_react41.createElement)("circle", { className: "bt-us-ring-track", cx: 48, cy: 48, r: RING_R }), - arc > 0 ? (0, import_react41.createElement)("circle", { className: "bt-us-ring-arc", cx: 48, cy: 48, r: RING_R, style: { stroke: face.stops ? "url(#bt-us-ring-paint)" : face.paint, strokeDasharray: `${arc} ${RING}` } }) : null + (0, import_react42.createElement)("circle", { className: "bt-us-ring-track", cx: 48, cy: 48, r: RING_R }), + arc > 0 ? (0, import_react42.createElement)("circle", { className: "bt-us-ring-arc", cx: 48, cy: 48, r: RING_R, style: { stroke: face.stops ? "url(#bt-us-ring-paint)" : face.paint, strokeDasharray: `${arc} ${RING}` } }) : null ), - (0, import_react41.createElement)("span", { className: "bt-us-ring-face" }, face.glyph(64)) + (0, import_react42.createElement)("span", { className: "bt-us-ring-face" }, face.glyph(64)) ), - (0, import_react41.createElement)( + (0, import_react42.createElement)( "div", { className: "bt-us-profile-copy" }, - (0, import_react41.createElement)("h3", null, face.name), - face.sub ? (0, import_react41.createElement)("span", { className: "bt-us-profile-sub" }, face.sub) : null, - (0, import_react41.createElement)("span", { className: "bt-us-profile-share" }, range.from ? t("{share}% of all usage from {span}", { share: percent2(share, 1), span: spanText(range.from, range.to) }) : t("{share}% of all usage in the last {range}", { share: percent2(share, 1), range: rangeLabel(range.id) })) + (0, import_react42.createElement)("h3", null, face.name), + face.sub ? (0, import_react42.createElement)("span", { className: "bt-us-profile-sub" }, face.sub) : null, + (0, import_react42.createElement)("span", { className: "bt-us-profile-share" }, range.from ? t("{share}% of all usage from {span}", { share: percent2(share, 1), span: spanText(range.from, range.to) }) : t("{share}% of all usage in the last {range}", { share: percent2(share, 1), range: rangeLabel(range.id) })) ) ); } var monthOf = (ms) => Date.UTC(yearOf(ms), new Date(ms).getUTCMonth(), 1); var addMonths = (ms, count) => Date.UTC(yearOf(ms), new Date(ms).getUTCMonth() + count, 1); function SpanPicker({ span, today, oldest, active, near, onPick, onClose }) { - const box = (0, import_react41.useRef)(null); + const box = (0, import_react42.useRef)(null); const todayMs = hourMs(today); const thisMonth = monthOf(todayMs); - const [right, setRight] = (0, import_react41.useState)(() => Math.max(addMonths(oldest, 1), monthOf(hourMs(span?.to ?? today)))); - const [anchor, setAnchor] = (0, import_react41.useState)(null); - const [hover, setHover] = (0, import_react41.useState)(null); - (0, import_react41.useEffect)(() => { + const [right, setRight] = (0, import_react42.useState)(() => Math.max(addMonths(oldest, 1), monthOf(hourMs(span?.to ?? today)))); + const [anchor, setAnchor] = (0, import_react42.useState)(null); + const [hover, setHover] = (0, import_react42.useState)(null); + (0, import_react42.useEffect)(() => { const onDown = (event) => { if (![box, near].some((ref) => ref.current?.contains(event.target))) onClose(); }; @@ -16694,17 +16807,17 @@ function SpanPicker({ span, today, oldest, active, near, onPick, onClose }) { const [from, to] = [anchor, key].sort(); onPick(from, to); }; - const weekdays = (0, import_react41.useMemo)(() => Array.from({ length: 7 }, (_, at) => dates({ weekday: "narrow" }).format(Date.UTC(2024, 0, 1 + at))), []); + const weekdays = (0, import_react42.useMemo)(() => Array.from({ length: 7 }, (_, at) => dates({ weekday: "narrow" }).format(Date.UTC(2024, 0, 1 + at))), []); const month = (start, side) => { const length = new Date(addMonths(start, 1) - DAY_MS).getUTCDate(); const lead = (new Date(start).getUTCDay() + 6) % 7; - const cells = Array.from({ length: lead }, (_, at) => (0, import_react41.createElement)("span", { key: `b${at}` })); + const cells = Array.from({ length: lead }, (_, at) => (0, import_react42.createElement)("span", { key: `b${at}` })); for (let day = 1; day <= length; day += 1) { const ms = start + (day - 1) * DAY_MS; const key = dayKey(ms); const weekday = (lead + day - 1) % 7; const flag = (on) => on ? "" : void 0; - cells.push((0, import_react41.createElement)("button", { + cells.push((0, import_react42.createElement)("button", { key, type: "button", className: "bt-us-day", @@ -16720,15 +16833,15 @@ function SpanPicker({ span, today, oldest, active, near, onPick, onClose }) { "data-has": flag(active.has(key)), onMouseEnter: () => setHover(key), onClick: () => press(key) - }, (0, import_react41.createElement)("b", null, day))); + }, (0, import_react42.createElement)("b", null, day))); } - const nav = side === "left" ? (0, import_react41.createElement)("button", { type: "button", className: "bt-us-month-nav", "data-side": "left", "aria-label": t("Previous month"), disabled: start <= oldest, onClick: () => setRight(addMonths(right, -1)) }, (0, import_react41.createElement)(ChevronLeftIcon)) : (0, import_react41.createElement)("button", { type: "button", className: "bt-us-month-nav", "data-side": "right", "aria-label": t("Next month"), disabled: start >= thisMonth, onClick: () => setRight(addMonths(right, 1)) }, (0, import_react41.createElement)(ChevronRightIcon)); - return (0, import_react41.createElement)( + const nav = side === "left" ? (0, import_react42.createElement)("button", { type: "button", className: "bt-us-month-nav", "data-side": "left", "aria-label": t("Previous month"), disabled: start <= oldest, onClick: () => setRight(addMonths(right, -1)) }, (0, import_react42.createElement)(ChevronLeftIcon)) : (0, import_react42.createElement)("button", { type: "button", className: "bt-us-month-nav", "data-side": "right", "aria-label": t("Next month"), disabled: start >= thisMonth, onClick: () => setRight(addMonths(right, 1)) }, (0, import_react42.createElement)(ChevronRightIcon)); + return (0, import_react42.createElement)( "div", { key: start, className: "bt-us-month" }, - (0, import_react41.createElement)("div", { className: "bt-us-month-head" }, nav, (0, import_react41.createElement)("span", null, dates({ year: "numeric", month: "long" }).format(start))), - (0, import_react41.createElement)("div", { className: "bt-us-weekdays", "aria-hidden": true }, weekdays.map((name, at) => (0, import_react41.createElement)("span", { key: at }, name))), - (0, import_react41.createElement)("div", { className: "bt-us-days", onMouseLeave: () => setHover(null) }, cells) + (0, import_react42.createElement)("div", { className: "bt-us-month-head" }, nav, (0, import_react42.createElement)("span", null, dates({ year: "numeric", month: "long" }).format(start))), + (0, import_react42.createElement)("div", { className: "bt-us-weekdays", "aria-hidden": true }, weekdays.map((name, at) => (0, import_react42.createElement)("span", { key: at }, name))), + (0, import_react42.createElement)("div", { className: "bt-us-days", onMouseLeave: () => setHover(null) }, cells) ); }; const shortcuts = [ @@ -16737,30 +16850,30 @@ function SpanPicker({ span, today, oldest, active, near, onPick, onClose }) { ["year", t("This year"), `${today.slice(0, 4)}-01-01`, today] ]; const count = low === null ? 0 : Math.round((hourMs(high) - hourMs(low)) / DAY_MS) + 1; - return (0, import_react41.createElement)( + return (0, import_react42.createElement)( "div", { ref: box, className: "bt-us-pick", role: "dialog", "aria-label": t("Custom range") }, - (0, import_react41.createElement)( + (0, import_react42.createElement)( "div", { className: "bt-us-pick-quick" }, - shortcuts.map(([id, label, from, to]) => (0, import_react41.createElement)("button", { + shortcuts.map(([id, label, from, to]) => (0, import_react42.createElement)("button", { key: id, type: "button", "aria-pressed": span?.from === from && span?.to === to, onClick: () => onPick(from, to) }, label)) ), - (0, import_react41.createElement)("div", { className: "bt-us-pick-months" }, month(addMonths(right, -1), "left"), month(right, "right")), - (0, import_react41.createElement)( + (0, import_react42.createElement)("div", { className: "bt-us-pick-months" }, month(addMonths(right, -1), "left"), month(right, "right")), + (0, import_react42.createElement)( "div", { className: "bt-us-pick-foot", role: "status" }, - (0, import_react41.createElement)("span", null, anchor ? t("Pick the last day") : t("Pick the first day")), - low === null ? null : (0, import_react41.createElement)("span", null, (0, import_react41.createElement)("b", null, spanText(low, high)), ` · ${daysText(count)}`) + (0, import_react42.createElement)("span", null, anchor ? t("Pick the last day") : t("Pick the first day")), + low === null ? null : (0, import_react42.createElement)("span", null, (0, import_react42.createElement)("b", null, spanText(low, high)), ` · ${daysText(count)}`) ) ); } function Heat({ view, keep, paint, index }) { - const [hover, setHover] = (0, import_react41.useState)(null); + const [hover, setHover] = (0, import_react42.useState)(null); const today = hourMs(`${view.now.slice(0, 10)} 00`); const first = mondayOf(today) - (HEAT_WEEKS - 1) * 7 * DAY_MS; const from = dayKey(first); @@ -16776,13 +16889,13 @@ function Heat({ view, keep, paint, index }) { for (let week = 0; week < HEAT_WEEKS; week += 1) { const monday = first + week * 7 * DAY_MS; if (week > 0 && new Date(monday).getUTCMonth() !== new Date(monday - 7 * DAY_MS).getUTCMonth()) { - months.push((0, import_react41.createElement)("span", { key: week, style: { gridColumn: week + 1 } }, dates({ month: "short" }).format(monday))); + months.push((0, import_react42.createElement)("span", { key: week, style: { gridColumn: week + 1 } }, dates({ month: "short" }).format(monday))); } for (let day = 0; day < 7; day += 1) { const ms = monday + day * DAY_MS; const value = daily.get(dayKey(ms)) ?? 0; const level = value > 0 ? Math.max(1, Math.ceil(4 * Math.sqrt(value / most))) : 0; - cells.push((0, import_react41.createElement)("span", { + cells.push((0, import_react42.createElement)("span", { key: ms, className: "bt-us-cell", style: { "--w": week }, @@ -16790,7 +16903,7 @@ function Heat({ view, keep, paint, index }) { "data-future": ms > today ? "" : void 0, "data-today": ms === today ? "" : void 0, onMouseEnter: ms > today ? void 0 : () => setHover({ ms, week, day }) - }, level > 0 ? (0, import_react41.createElement)("i", { style: { background: soften(paint, levels[level - 1]) } }) : null)); + }, level > 0 ? (0, import_react42.createElement)("i", { style: { background: soften(paint, levels[level - 1]) } }) : null)); } } const tipSide = hover ? { @@ -16799,68 +16912,68 @@ function Heat({ view, keep, paint, index }) { } : null; const active = [...daily.values()].filter((value) => value > 0).length; const summary = active === 1 ? t("Active on 1 day in the last year") : t("Active on {count} days in the last year", { count: active }); - return (0, import_react41.createElement)( + return (0, import_react42.createElement)( "section", { className: "bt-us-card bt-us-heat", style: { "--i": index } }, - (0, import_react41.createElement)("div", { className: "bt-us-card-head" }, (0, import_react41.createElement)("h3", null, t("Activity")), (0, import_react41.createElement)("span", { className: "bt-us-head-note" }, summary)), - (0, import_react41.createElement)("div", { className: "bt-us-heat-months", "aria-hidden": true }, months), - (0, import_react41.createElement)( + (0, import_react42.createElement)("div", { className: "bt-us-card-head" }, (0, import_react42.createElement)("h3", null, t("Activity")), (0, import_react42.createElement)("span", { className: "bt-us-head-note" }, summary)), + (0, import_react42.createElement)("div", { className: "bt-us-heat-months", "aria-hidden": true }, months), + (0, import_react42.createElement)( "div", { className: "bt-us-heat-plot", onMouseLeave: () => setHover(null) }, - (0, import_react41.createElement)("div", { className: "bt-us-heat-grid", role: "img", "aria-label": summary }, cells), - hover ? (0, import_react41.createElement)( + (0, import_react42.createElement)("div", { className: "bt-us-heat-grid", role: "img", "aria-label": summary }, cells), + hover ? (0, import_react42.createElement)( "div", { className: "bt-us-tip bt-us-heat-tip", style: tipSide }, - (0, import_react41.createElement)("div", { className: "bt-us-tip-title" }, dates({ month: "long", day: "numeric", weekday: "short" }).format(hover.ms)), - (0, import_react41.createElement)("div", { className: "bt-us-tip-total" }, t("{count} tokens", { count: full(daily.get(dayKey(hover.ms)) ?? 0) })) + (0, import_react42.createElement)("div", { className: "bt-us-tip-title" }, dates({ month: "long", day: "numeric", weekday: "short" }).format(hover.ms)), + (0, import_react42.createElement)("div", { className: "bt-us-tip-total" }, t("{count} tokens", { count: full(daily.get(dayKey(hover.ms)) ?? 0) })) ) : null ), - (0, import_react41.createElement)( + (0, import_react42.createElement)( "div", { className: "bt-us-heat-scale", "aria-hidden": true }, t("Light"), - levels.map((level) => (0, import_react41.createElement)("span", { key: level, className: "bt-us-cell" }, (0, import_react41.createElement)("i", { style: { background: soften(paint, level) } }))), + levels.map((level) => (0, import_react42.createElement)("span", { key: level, className: "bt-us-cell" }, (0, import_react42.createElement)("i", { style: { background: soften(paint, level) } }))), t("Heavy") ) ); } function Skeleton2() { - return (0, import_react41.createElement)( + return (0, import_react42.createElement)( "div", { className: "bt-us", "aria-busy": true }, - (0, import_react41.createElement)("div", { className: "bt-us-skel", style: { height: 32, width: 320, borderRadius: 999 } }), - (0, import_react41.createElement)( + (0, import_react42.createElement)("div", { className: "bt-us-skel", style: { height: 32, width: 320, borderRadius: 999 } }), + (0, import_react42.createElement)( "div", { className: "bt-us-sheet bt-us-skel-sheet" }, - (0, import_react41.createElement)("div", { className: "bt-us-skel", style: { height: 94 } }), - (0, import_react41.createElement)("div", { className: "bt-us-skel", style: { height: 318 } }), - (0, import_react41.createElement)( + (0, import_react42.createElement)("div", { className: "bt-us-skel", style: { height: 94 } }), + (0, import_react42.createElement)("div", { className: "bt-us-skel", style: { height: 318 } }), + (0, import_react42.createElement)( "div", { className: "bt-us-pair" }, - (0, import_react41.createElement)("div", { className: "bt-us-skel", style: { height: 200 } }), - (0, import_react41.createElement)("div", { className: "bt-us-skel", style: { height: 200 } }) + (0, import_react42.createElement)("div", { className: "bt-us-skel", style: { height: 200 } }), + (0, import_react42.createElement)("div", { className: "bt-us-skel", style: { height: 200 } }) ) ) ); } var focusOf = (id) => typeof id !== "string" ? null : id.startsWith("model:") ? { kind: "model", key: id.slice("model:".length) } : id.startsWith("owner:") ? { kind: "owner", key: id.slice("owner:".length) } : null; function UsagePage({ roster, actions, focusId }) { - const [view, setView] = (0, import_react41.useState)(null); - const [error, setError] = (0, import_react41.useState)(""); - const [rangeId, setRangeId] = (0, import_react41.useState)("7d"); - const [span, setSpan] = (0, import_react41.useState)(null); - const [picking, setPicking] = (0, import_react41.useState)(false); - const [by, setBy] = (0, import_react41.useState)("bot"); - const tabs = (0, import_react41.useRef)(null); + const [view, setView] = (0, import_react42.useState)(null); + const [error, setError] = (0, import_react42.useState)(""); + const [rangeId, setRangeId] = (0, import_react42.useState)("7d"); + const [span, setSpan] = (0, import_react42.useState)(null); + const [picking, setPicking] = (0, import_react42.useState)(false); + const [by, setBy] = (0, import_react42.useState)("bot"); + const tabs = (0, import_react42.useRef)(null); const focus = focusOf(focusId); - (0, import_react41.useEffect)(() => { + (0, import_react42.useEffect)(() => { let stopped = false; let timer; const load = async () => { try { const value = await actions.usage(); if (stopped) return; - (0, import_react41.startTransition)(() => setView(value)); + (0, import_react42.startTransition)(() => setView(value)); setError(""); timer = setTimeout(load, value.scanning ? 3e3 : 2e4); } catch (failure) { @@ -16877,7 +16990,7 @@ function UsagePage({ roster, actions, focusId }) { }, []); const today = view?.now.slice(0, 10); const range = rangeId === "custom" && span ? { ...spanRange(span.from, span.to), ends: span.to >= today } : RANGES.find((item) => item.id === rangeId); - const shaped = (0, import_react41.useMemo)(() => { + const shaped = (0, import_react42.useMemo)(() => { if (!view) return null; const faces2 = view.owners.map((owner) => ownerFace(owner, roster)); const lifetime = /* @__PURE__ */ new Map(); @@ -16886,7 +16999,7 @@ function UsagePage({ roster, actions, focusId }) { const models2 = view.models.map((model, at) => { const name = model.name || model.model || t("Unknown model"); const paint = modelPaint.get(at) ?? "var(--bt-us-rest)"; - return { kind: "model", name, sub: model.providerName ?? model.provider, paint, glyph: (size) => (0, import_react41.createElement)(ModelGlyph, { name, paint, size }) }; + return { kind: "model", name, sub: model.providerName ?? model.provider, paint, glyph: (size) => (0, import_react42.createElement)(ModelGlyph, { name, paint, size }) }; }); const ownerAt2 = focus?.kind === "owner" ? view.owners.findIndex((owner) => owner.key === focus.key) : -1; const modelAt = focus?.kind === "model" ? view.models.findIndex((model) => model.key === focus.key) : -1; @@ -16934,23 +17047,23 @@ function UsagePage({ roster, actions, focusId }) { }); return { faces: faces2, models: models2, ownerAt: ownerAt2, modelAt, face: face2, keep: keep2, all: all2, part: part2, series: series2, tipSeries: tipSeries2, fillOf: fillOf2, columns: columns3, ranked: ranked2, isBot: isBot2, activeDays: activeDays2, oldest: oldest2 }; }, [view, rangeId, span, by, focusId, roster]); - const root = (0, import_react41.useRef)(null); - (0, import_react41.useEffect)(() => { + const root = (0, import_react42.useRef)(null); + (0, import_react42.useEffect)(() => { root.current?.closest(".bt-settings-scroll")?.scrollTo?.({ top: 0 }); }, [focusId]); if (!view) { - return error ? (0, import_react41.createElement)("div", { className: "bt-error", role: "alert", style: { padding: 0 } }, error) : (0, import_react41.createElement)(Skeleton2); + return error ? (0, import_react42.createElement)("div", { className: "bt-error", role: "alert", style: { padding: 0 } }, error) : (0, import_react42.createElement)(Skeleton2); } if (view.rows.length === 0) { - return (0, import_react41.createElement)( + return (0, import_react42.createElement)( "div", { className: "bt-us" }, - (0, import_react41.createElement)( + (0, import_react42.createElement)( "div", { className: "bt-us-empty" }, - (0, import_react41.createElement)(BotMark, { look: MAIN_LOOK, size: 56, live: true }), - (0, import_react41.createElement)("b", null, view.scanning ? t("Reading your chats…") : t("No usage yet.")), - (0, import_react41.createElement)("span", null, t("Token usage shows up here after a model is called.")) + (0, import_react42.createElement)(BotMark, { look: MAIN_LOOK, size: 56, live: true }), + (0, import_react42.createElement)("b", null, view.scanning ? t("Reading your chats…") : t("No usage yet.")), + (0, import_react42.createElement)("span", null, t("Token usage shows up here after a model is called.")) ) ); } @@ -16975,7 +17088,7 @@ function UsagePage({ roster, actions, focusId }) { ["custom", rangeId === "custom" && span ? spanText(span.from, span.to) : t("Custom"), CalendarIcon] ]; const whole = part.total.total; - const ownerRow = ([at, sum], index, total = whole) => (0, import_react41.createElement)(Row2, { + const ownerRow = ([at, sum], index, total = whole) => (0, import_react42.createElement)(Row2, { key: `o${at}`, kind: faces[at].kind, glyph: faces[at].glyph(32), @@ -16987,7 +17100,7 @@ function UsagePage({ roster, actions, focusId }) { fill: face ? soften(face.paint, 0.8) : fillOf.get(`o${at}`) ?? soften(faces[at].paint), onClick: () => pick2({ kind: "owner", key: view.owners[at].key }) }); - const modelRow = ([at, sum], index) => (0, import_react41.createElement)(Row2, { + const modelRow = ([at, sum], index) => (0, import_react42.createElement)(Row2, { key: `m${at}`, kind: "model", glyph: models[at].glyph(32), @@ -16999,30 +17112,30 @@ function UsagePage({ roster, actions, focusId }) { fill: face ? soften(face.paint, 0.8) : fillOf.get(`m${at}`) ?? soften(models[at].paint), onClick: () => pick2({ kind: "model", key: view.models[at].key }) }); - const nothing = (0, import_react41.createElement)("div", { className: "bt-us-none" }, t("Nothing in this range.")); + const nothing = (0, import_react42.createElement)("div", { className: "bt-us-none" }, t("Nothing in this range.")); let body; if (face) { const kinds = ranked(part.kinds); const usedModels = ranked(part.models); const owners = ranked(part.owners); body = [ - (0, import_react41.createElement)(Profile, { key: "profile", face, range, share: all.total.total > 0 ? whole / all.total.total : 0 }), - (0, import_react41.createElement)( + (0, import_react42.createElement)(Profile, { key: "profile", face, range, share: all.total.total > 0 ? whole / all.total.total : 0 }), + (0, import_react42.createElement)( "div", { key: "sheet", className: "bt-us-sheet" }, - (0, import_react41.createElement)(Stats, { key: "stats", range, total: part.total, previous: part.previous }), - (0, import_react41.createElement)(Chart, { key: "chart", range, columns: columns2, series, tipSeries, onPick: pick2 }), - (0, import_react41.createElement)( + (0, import_react42.createElement)(Stats, { key: "stats", range, total: part.total, previous: part.previous }), + (0, import_react42.createElement)(Chart, { key: "chart", range, columns: columns2, series, tipSeries, onPick: pick2 }), + (0, import_react42.createElement)( "div", { key: "pair", className: "bt-us-pair" }, - ownerAt >= 0 ? (0, import_react41.createElement)(ListCard, { title: t("Models"), count: usedModels.length, index: 2 }, usedModels.length > 0 ? usedModels.map(modelRow) : nothing) : (0, import_react41.createElement)(ListCard, { title: t("Who used it"), count: owners.length, index: 2 }, owners.length > 0 ? owners.map((entry, index) => ownerRow(entry, index)) : nothing), - (0, import_react41.createElement)( + ownerAt >= 0 ? (0, import_react42.createElement)(ListCard, { title: t("Models"), count: usedModels.length, index: 2 }, usedModels.length > 0 ? usedModels.map(modelRow) : nothing) : (0, import_react42.createElement)(ListCard, { title: t("Who used it"), count: owners.length, index: 2 }, owners.length > 0 ? owners.map((entry, index) => ownerRow(entry, index)) : nothing), + (0, import_react42.createElement)( ListCard, { title: t("What for"), index: 3 }, - kinds.length > 0 ? kinds.map(([at, sum], index) => (0, import_react41.createElement)(Row2, { key: at, name: kindLabel(view.kinds[at], ownerAt >= 0 && isBot(ownerAt)), sum, whole, index, fill: soften(face.paint, 0.8) })) : nothing + kinds.length > 0 ? kinds.map(([at, sum], index) => (0, import_react42.createElement)(Row2, { key: at, name: kindLabel(view.kinds[at], ownerAt >= 0 && isBot(ownerAt)), sum, whole, index, fill: soften(face.paint, 0.8) })) : nothing ) ), - (0, import_react41.createElement)(Heat, { key: "heat", view, keep, paint: face.paint, index: 4 }) + (0, import_react42.createElement)(Heat, { key: "heat", view, keep, paint: face.paint, index: 4 }) ) ]; } else { @@ -17031,39 +17144,39 @@ function UsagePage({ roster, actions, focusId }) { const rest = owners.filter(([at]) => !isBot(at)); const usedModels = ranked(all.models); body = [ - (0, import_react41.createElement)( + (0, import_react42.createElement)( "div", { key: "sheet", className: "bt-us-sheet" }, - (0, import_react41.createElement)(Stats, { key: "stats", range, total: all.total, previous: all.previous }), - (0, import_react41.createElement)(Chart, { key: "chart", range, columns: columns2, series, tipSeries, by, onBy: setBy, onPick: pick2 }), - (0, import_react41.createElement)( + (0, import_react42.createElement)(Stats, { key: "stats", range, total: all.total, previous: all.previous }), + (0, import_react42.createElement)(Chart, { key: "chart", range, columns: columns2, series, tipSeries, by, onBy: setBy, onPick: pick2 }), + (0, import_react42.createElement)( "div", { key: "pair", className: "bt-us-pair" }, - (0, import_react41.createElement)( + (0, import_react42.createElement)( ListCard, { title: t("Bots"), count: bots.length, index: 2 }, owners.length > 0 ? null : nothing, bots.map((entry, index) => ownerRow(entry, index)), - bots.length > 0 && rest.length > 0 ? (0, import_react41.createElement)("div", { className: "bt-us-split", role: "separator" }) : null, + bots.length > 0 && rest.length > 0 ? (0, import_react42.createElement)("div", { className: "bt-us-split", role: "separator" }) : null, rest.map((entry, index) => ownerRow(entry, bots.length + index)) ), - (0, import_react41.createElement)(ListCard, { title: t("Models"), count: usedModels.length, index: 3 }, usedModels.length > 0 ? usedModels.map(modelRow) : nothing) + (0, import_react42.createElement)(ListCard, { title: t("Models"), count: usedModels.length, index: 3 }, usedModels.length > 0 ? usedModels.map(modelRow) : nothing) ), - (0, import_react41.createElement)(Heat, { key: "heat", view, keep, paint: "var(--bt-accent)", index: 4 }) + (0, import_react42.createElement)(Heat, { key: "heat", view, keep, paint: "var(--bt-accent)", index: 4 }) ) ]; } - return (0, import_react41.createElement)( + return (0, import_react42.createElement)( "div", { ref: root, className: "bt-us", key: focusId ?? "all" }, - (0, import_react41.createElement)( + (0, import_react42.createElement)( "div", { className: "bt-us-top" }, - (0, import_react41.createElement)(Tabs, { label: t("Time range"), value: rangeId, onChange: chooseRange, options: rangeOptions, boxRef: tabs }), - view.scanning ? (0, import_react41.createElement)("span", { className: "bt-us-note", role: "status" }, t("Still reading older chats; totals may grow.")) : null, - picking ? (0, import_react41.createElement)(SpanPicker, { span, today, oldest, active: activeDays, near: tabs, onPick: pickSpan, onClose: () => setPicking(false) }) : null + (0, import_react42.createElement)(Tabs, { label: t("Time range"), value: rangeId, onChange: chooseRange, options: rangeOptions, boxRef: tabs }), + view.scanning ? (0, import_react42.createElement)("span", { className: "bt-us-note", role: "status" }, t("Still reading older chats; totals may grow.")) : null, + picking ? (0, import_react42.createElement)(SpanPicker, { span, today, oldest, active: activeDays, near: tabs, onPick: pickSpan, onClose: () => setPicking(false) }) : null ), - error ? (0, import_react41.createElement)("div", { className: "bt-error", role: "alert", style: { padding: 0 } }, error) : null, + error ? (0, import_react42.createElement)("div", { className: "bt-error", role: "alert", style: { padding: 0 } }, error) : null, body ); } @@ -17236,12 +17349,12 @@ button.bt-us-row:hover{background:var(--bt-hover)} `; // src/client/connectors.js -var import_react42 = require("react"); +var import_react43 = require("react"); var TOKEN_URL = "https://github.com/settings/personal-access-tokens/new"; -var GitHubMark = () => (0, import_react42.createElement)( +var GitHubMark = () => (0, import_react43.createElement)( "svg", { width: 20, height: 20, viewBox: "0 0 16 16", fill: "currentColor", "aria-hidden": true }, - (0, import_react42.createElement)("path", { d: "M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z" }) + (0, import_react43.createElement)("path", { d: "M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z" }) ); var MARKS = { github: GitHubMark }; var ABOUT = { github: () => t("Repositories, issues, and pull requests") }; @@ -17252,10 +17365,10 @@ function statusText2(connector) { return ABOUT[connector.id]?.() ?? ""; } function ConnectorRow({ connector, actions }) { - const [form, setForm] = (0, import_react42.useState)(false); - const [token, setToken] = (0, import_react42.useState)(""); - const [busy, setBusy] = (0, import_react42.useState)(false); - const [error, setError] = (0, import_react42.useState)(null); + const [form, setForm] = (0, import_react43.useState)(false); + const [token, setToken] = (0, import_react43.useState)(""); + const [busy, setBusy] = (0, import_react43.useState)(false); + const [error, setError] = (0, import_react43.useState)(null); const run2 = (task, after) => { setBusy(true); setError(null); @@ -17272,58 +17385,58 @@ function ConnectorRow({ connector, actions }) { }; const on = connector.state !== "off"; const Mark = MARKS[connector.id]; - const row = (0, import_react42.useRef)(null); + const row = (0, import_react43.useRef)(null); useMorph(row, `${form}:${error !== null}:${connector.state}`); - return (0, import_react42.createElement)( + return (0, import_react43.createElement)( "div", { ref: row, className: "bt-connector", "data-state": connector.state }, - (0, import_react42.createElement)( + (0, import_react43.createElement)( "div", { className: "bt-connector-head" }, - (0, import_react42.createElement)("span", { className: "bt-connector-mark" }, Mark ? (0, import_react42.createElement)(Mark) : null), - (0, import_react42.createElement)( + (0, import_react43.createElement)("span", { className: "bt-connector-mark" }, Mark ? (0, import_react43.createElement)(Mark) : null), + (0, import_react43.createElement)( "span", { className: "bt-connector-text" }, - (0, import_react42.createElement)("span", { className: "bt-connector-name" }, connector.name), - (0, import_react42.createElement)("span", { className: "bt-connector-status" }, statusText2(connector)) + (0, import_react43.createElement)("span", { className: "bt-connector-name" }, connector.name), + (0, import_react43.createElement)("span", { className: "bt-connector-status" }, statusText2(connector)) ), - (0, import_react42.createElement)( + (0, import_react43.createElement)( "span", { className: "bt-connector-actions" }, - connector.state === "error" ? (0, import_react42.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: busy, onClick: () => void run2(actions.connectorRetry(connector.id)) }, t("Try again")) : null, - on ? (0, import_react42.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: busy, onClick: () => void run2(actions.connectorDisconnect(connector.id)) }, t("Disconnect")) : form ? null : (0, import_react42.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => setForm(true) }, t("Connect")) + connector.state === "error" ? (0, import_react43.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: busy, onClick: () => void run2(actions.connectorRetry(connector.id)) }, t("Try again")) : null, + on ? (0, import_react43.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: busy, onClick: () => void run2(actions.connectorDisconnect(connector.id)) }, t("Disconnect")) : form ? null : (0, import_react43.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => setForm(true) }, t("Connect")) ) ), - !on && form ? (0, import_react42.createElement)( + !on && form ? (0, import_react43.createElement)( "div", { className: "bt-connector-form" }, - (0, import_react42.createElement)("label", { className: "bt-q-field bt-secret-field" }, (0, import_react42.createElement)(MaskedInput, { value: token, onChange: setToken, onEnter: connect, label: t("GitHub token"), autoFocus: true })), - (0, import_react42.createElement)( + (0, import_react43.createElement)("label", { className: "bt-q-field bt-secret-field" }, (0, import_react43.createElement)(MaskedInput, { value: token, onChange: setToken, onEnter: connect, label: t("GitHub token"), autoFocus: true })), + (0, import_react43.createElement)( "div", { className: "bt-connector-form-row" }, - (0, import_react42.createElement)("a", { className: "bt-connector-link", href: TOKEN_URL, target: "_blank", rel: "noopener noreferrer" }, t("Create a token on GitHub")), - (0, import_react42.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: busy, onClick: () => { + (0, import_react43.createElement)("a", { className: "bt-connector-link", href: TOKEN_URL, target: "_blank", rel: "noopener noreferrer" }, t("Create a token on GitHub")), + (0, import_react43.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: busy, onClick: () => { setForm(false); setToken(""); setError(null); } }, t("Cancel")), - (0, import_react42.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: busy || token.trim() === "", onClick: connect }, busy ? t("Connecting…") : t("Connect")) + (0, import_react43.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: busy || token.trim() === "", onClick: connect }, busy ? t("Connecting…") : t("Connect")) ) ) : null, - error ? (0, import_react42.createElement)("div", { className: "bt-connector-error", role: "alert" }, error) : null + error ? (0, import_react43.createElement)("div", { className: "bt-connector-error", role: "alert" }, error) : null ); } function ConnectorsPage({ roster, actions }) { const list = roster?.connectors ?? []; - return (0, import_react42.createElement)( + return (0, import_react43.createElement)( "section", { className: "bt-set-section" }, - (0, import_react42.createElement)("div", { className: "bt-set-card bt-connectors-card" }, list.length === 0 ? (0, import_react42.createElement)("div", { className: "bt-set-row" }, (0, import_react42.createElement)("span", { className: "bt-set-hint" }, t("No connectors"))) : list.map((connector) => (0, import_react42.createElement)(ConnectorRow, { key: connector.id, connector, actions }))) + (0, import_react43.createElement)("div", { className: "bt-set-card bt-connectors-card" }, list.length === 0 ? (0, import_react43.createElement)("div", { className: "bt-set-row" }, (0, import_react43.createElement)("span", { className: "bt-set-hint" }, t("No connectors"))) : list.map((connector) => (0, import_react43.createElement)(ConnectorRow, { key: connector.id, connector, actions }))) ); } // src/client/browser-settings.js -var import_react43 = require("react"); +var import_react44 = require("react"); var ACTIONS = [["post", "Post"], ["upload", "Upload"], ["download", "Download"], ["delete", "Delete"]]; var DURATIONS = [["hour", "1 hour"], ["today", "Today"], ["week", "7 days"], ["permanent", "Permanent"]]; var expired = (grant) => Number.isFinite(grant.until) && grant.until <= Date.now(); @@ -17342,13 +17455,13 @@ function grantKinds(grant) { } function BrowserPage({ roster, actions, run: run2, Section, Row: Row3 }) { const bots = roster.bots ?? []; - const [botId, setBotId] = (0, import_react43.useState)(bots[0]?.id ?? ""); - const [site, setSite] = (0, import_react43.useState)(""); - const [kinds, setKinds] = (0, import_react43.useState)(["post"]); - const [duration, setDuration] = (0, import_react43.useState)("hour"); - const [busy, setBusy] = (0, import_react43.useState)(false); + const [botId, setBotId] = (0, import_react44.useState)(bots[0]?.id ?? ""); + const [site, setSite] = (0, import_react44.useState)(""); + const [kinds, setKinds] = (0, import_react44.useState)(["post"]); + const [duration, setDuration] = (0, import_react44.useState)("hour"); + const [busy, setBusy] = (0, import_react44.useState)(false); const selectedBot = bots.find((bot) => bot.id === botId); - (0, import_react43.useEffect)(() => { + (0, import_react44.useEffect)(() => { if (!bots.some((bot) => bot.id === botId)) setBotId(bots[0]?.id ?? ""); }, [bots, botId]); const grants = bots.flatMap((bot) => (bot.browserGrants ?? []).map((grant, index) => ({ @@ -17381,37 +17494,37 @@ function BrowserPage({ roster, actions, run: run2, Section, Row: Row3 }) { const toggleKind = (kind, checked) => { setKinds((current) => checked ? current.includes(kind) ? current : [...current, kind] : current.filter((value) => value !== kind)); }; - return (0, import_react43.createElement)( + return (0, import_react44.createElement)( "div", { className: "bt-browser-settings" }, - (0, import_react43.createElement)( + (0, import_react44.createElement)( Section, { title: t("Browser access") }, - (0, import_react43.createElement)("p", { className: "bt-browser-note" }, t("Bots browse, click and fill in forms freely. Posting, uploading, downloading and deleting ask you first unless you allow them here. Payments are always yours: the Bot hands the page to you.")) + (0, import_react44.createElement)("p", { className: "bt-browser-note" }, t("Bots browse, click and fill in forms freely. Posting, uploading, downloading and deleting ask you first unless you allow them here. Payments are always yours: the Bot hands the page to you.")) ), - (0, import_react43.createElement)( + (0, import_react44.createElement)( Section, { title: t("Allowed actions") }, - grants.length === 0 ? (0, import_react43.createElement)(Row3, { label: t("Nothing allowed yet.") }) : grants.map(({ bot, grant, index, expired: expired2 }) => (0, import_react43.createElement)( + grants.length === 0 ? (0, import_react44.createElement)(Row3, { label: t("Nothing allowed yet.") }) : grants.map(({ bot, grant, index, expired: expired2 }) => (0, import_react44.createElement)( "div", { key: `${bot.id}:${index}`, className: `bt-browser-grant${expired2 ? " bt-browser-grant-expired" : ""}` }, - (0, import_react43.createElement)( + (0, import_react44.createElement)( "div", { className: "bt-browser-grant-who" }, - (0, import_react43.createElement)(BotAvatar, { bot, size: 28 }), - (0, import_react43.createElement)("span", null, bot.name) + (0, import_react44.createElement)(BotAvatar, { bot, size: 28 }), + (0, import_react44.createElement)("span", null, bot.name) ), - (0, import_react43.createElement)( + (0, import_react44.createElement)( "div", { className: "bt-browser-grant-meta" }, - (0, import_react43.createElement)("span", { className: "bt-browser-grant-site" }, grant.site === "*" ? t("All sites") : grant.site), - (0, import_react43.createElement)("div", { className: "bt-browser-grant-kinds" }, grantKinds(grant).map((label) => (0, import_react43.createElement)("span", { key: label, className: "bt-chip" }, label))), - (0, import_react43.createElement)("span", { className: "bt-set-hint" }, grantTime(grant)) + (0, import_react44.createElement)("span", { className: "bt-browser-grant-site" }, grant.site === "*" ? t("All sites") : grant.site), + (0, import_react44.createElement)("div", { className: "bt-browser-grant-kinds" }, grantKinds(grant).map((label) => (0, import_react44.createElement)("span", { key: label, className: "bt-chip" }, label))), + (0, import_react44.createElement)("span", { className: "bt-set-hint" }, grantTime(grant)) ), - (0, import_react43.createElement)("button", { + (0, import_react44.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => remove(bot, index), @@ -17419,25 +17532,25 @@ function BrowserPage({ roster, actions, run: run2, Section, Row: Row3 }) { }, t("Remove grant")) )) ), - (0, import_react43.createElement)( + (0, import_react44.createElement)( Section, { title: t("Allow an action") }, - (0, import_react43.createElement)( + (0, import_react44.createElement)( "form", { className: "bt-browser-form", onSubmit: add }, - (0, import_react43.createElement)( + (0, import_react44.createElement)( Row3, { label: t("Bot") }, - (0, import_react43.createElement)( + (0, import_react44.createElement)( "select", { className: "bt-select", value: botId, onChange: (event) => setBotId(event.target.value), disabled: bots.length === 0 }, - bots.map((bot) => (0, import_react43.createElement)("option", { key: bot.id, value: bot.id }, bot.name)) + bots.map((bot) => (0, import_react44.createElement)("option", { key: bot.id, value: bot.id }, bot.name)) ) ), - (0, import_react43.createElement)( + (0, import_react44.createElement)( Row3, { label: t("Site") }, - (0, import_react43.createElement)("input", { + (0, import_react44.createElement)("input", { className: "bt-select bt-browser-site", type: "text", value: site, @@ -17445,16 +17558,16 @@ function BrowserPage({ roster, actions, run: run2, Section, Row: Row3 }) { onChange: (event) => setSite(event.target.value) }) ), - (0, import_react43.createElement)( + (0, import_react44.createElement)( Row3, { label: t("Actions") }, - (0, import_react43.createElement)( + (0, import_react44.createElement)( "div", { className: "bt-browser-action-list" }, - ACTIONS.map(([kind, label]) => (0, import_react43.createElement)( + ACTIONS.map(([kind, label]) => (0, import_react44.createElement)( "label", { key: kind, className: "bt-browser-action-choice" }, - (0, import_react43.createElement)("input", { + (0, import_react44.createElement)("input", { type: "checkbox", checked: kinds.includes(kind), onChange: (event) => toggleKind(kind, event.target.checked) @@ -17463,13 +17576,13 @@ function BrowserPage({ roster, actions, run: run2, Section, Row: Row3 }) { )) ) ), - (0, import_react43.createElement)( + (0, import_react44.createElement)( Row3, { label: t("Duration") }, - (0, import_react43.createElement)( + (0, import_react44.createElement)( "div", { className: "bt-browser-duration", role: "group", "aria-label": t("Duration") }, - DURATIONS.map(([key, label]) => (0, import_react43.createElement)("button", { + DURATIONS.map(([key, label]) => (0, import_react44.createElement)("button", { key, type: "button", className: "bt-browser-duration-choice", @@ -17478,10 +17591,10 @@ function BrowserPage({ roster, actions, run: run2, Section, Row: Row3 }) { }, t(label))) ) ), - (0, import_react43.createElement)( + (0, import_react44.createElement)( "div", { className: "bt-browser-form-foot" }, - (0, import_react43.createElement)("button", { + (0, import_react44.createElement)("button", { type: "submit", className: "bt-soft", disabled: busy || !selectedBot || kinds.length === 0 @@ -17493,12 +17606,12 @@ function BrowserPage({ roster, actions, run: run2, Section, Row: Row3 }) { } // src/client/feedback.js -var import_react44 = require("react"); -var FeedbackIcon = () => (0, import_react44.createElement)( +var import_react45 = require("react"); +var FeedbackIcon = () => (0, import_react45.createElement)( "svg", { width: 15, height: 15, viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true }, - (0, import_react44.createElement)("path", { d: "M4 4.5h12a1 1 0 0 1 1 1v7a1 1 0 0 1-1 1H9l-3.5 3v-3H4a1 1 0 0 1-1-1v-7a1 1 0 0 1 1-1z" }), - (0, import_react44.createElement)("path", { d: "M10 7v2.6M10 11.4h.01" }) + (0, import_react45.createElement)("path", { d: "M4 4.5h12a1 1 0 0 1 1 1v7a1 1 0 0 1-1 1H9l-3.5 3v-3H4a1 1 0 0 1-1-1v-7a1 1 0 0 1 1-1z" }), + (0, import_react45.createElement)("path", { d: "M10 7v2.6M10 11.4h.01" }) ); function download(name, text) { const url = URL.createObjectURL(new Blob([text], { type: "text/plain;charset=utf-8" })); @@ -17536,16 +17649,16 @@ function issueWindow() { }; } function FeedbackPage({ actions, run: run2, Section, Row: Row3 }) { - const [what, setWhat] = (0, import_react44.useState)(""); - const [report, setReport] = (0, import_react44.useState)(null); - const [preview, setPreview] = (0, import_react44.useState)(false); - const [note, setNote] = (0, import_react44.useState)(""); + const [what, setWhat] = (0, import_react45.useState)(""); + const [report, setReport] = (0, import_react45.useState)(null); + const [preview, setPreview] = (0, import_react45.useState)(false); + const [note, setNote] = (0, import_react45.useState)(""); const fetchReport = () => actions.diagnostics({ client: clientFacts(), clientErrors: clientErrors() }).then((next) => { setReport(next); return next; }); const load = () => fetchReport().then(() => void 0); - (0, import_react44.useEffect)(() => { + (0, import_react45.useEffect)(() => { void run2(load()); }, []); const copyReport = () => run2(fetchReport().then(async (next) => { @@ -17553,7 +17666,7 @@ function FeedbackPage({ actions, run: run2, Section, Row: Row3 }) { setNote(copied ? t("Copied the diagnostics.") : t("Could not copy. Select the text below and copy it.")); if (!copied) setPreview(true); })); - const [issueLink, setIssueLink] = (0, import_react44.useState)(null); + const [issueLink, setIssueLink] = (0, import_react45.useState)(null); const openIssue = () => { const target = issueWindow(); run2(fetchReport().then(async (next) => { @@ -17579,59 +17692,59 @@ function FeedbackPage({ actions, run: run2, Section, Row: Row3 }) { const total = (report?.total ?? 0) + browserErrors.length; const shown = entries2.slice(0, 8); return [ - (0, import_react44.createElement)( + (0, import_react45.createElement)( Section, { key: "report", title: t("Report a problem") }, - (0, import_react44.createElement)( + (0, import_react45.createElement)( "div", { className: "bt-set-row bt-set-paste bt-fb-what" }, - (0, import_react44.createElement)( + (0, import_react45.createElement)( "label", { className: "bt-set-copy", htmlFor: "bt-fb-what" }, - (0, import_react44.createElement)("span", null, t("What happened?")), - (0, import_react44.createElement)("span", { className: "bt-set-hint" }, t("What you did, what you expected, and what happened instead. It goes into the issue.")) + (0, import_react45.createElement)("span", null, t("What happened?")), + (0, import_react45.createElement)("span", { className: "bt-set-hint" }, t("What you did, what you expected, and what happened instead. It goes into the issue.")) ), - (0, import_react44.createElement)("textarea", { id: "bt-fb-what", className: "bt-input bt-input-area", value: what, maxLength: WHAT_MAX, placeholder: t("For example: I asked Writer in the group chat and it showed an error."), onChange: (event) => setWhat(event.target.value) }) + (0, import_react45.createElement)("textarea", { id: "bt-fb-what", className: "bt-input bt-input-area", value: what, maxLength: WHAT_MAX, placeholder: t("For example: I asked Writer in the group chat and it showed an error."), onChange: (event) => setWhat(event.target.value) }) ), - (0, import_react44.createElement)( + (0, import_react45.createElement)( Row3, { label: t("Diagnostics"), hint: t("Versions, system, models, and the latest errors. Saved keys, tokens, and your home folder are hidden.") }, - (0, import_react44.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => setPreview(!preview), "aria-expanded": preview }, preview ? t("Hide") : t("Show")), - (0, import_react44.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: copyReport }, t("Copy")) + (0, import_react45.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => setPreview(!preview), "aria-expanded": preview }, preview ? t("Hide") : t("Show")), + (0, import_react45.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: copyReport }, t("Copy")) ), - preview ? (0, import_react44.createElement)("div", { className: "bt-set-row bt-fb-preview" }, (0, import_react44.createElement)("pre", { tabIndex: 0, "aria-label": t("Diagnostics") }, report?.markdown || t("Loading…"))) : null, - (0, import_react44.createElement)( + preview ? (0, import_react45.createElement)("div", { className: "bt-set-row bt-fb-preview" }, (0, import_react45.createElement)("pre", { tabIndex: 0, "aria-label": t("Diagnostics") }, report?.markdown || t("Loading…"))) : null, + (0, import_react45.createElement)( Row3, { label: t("GitHub issue"), hint: t("Opens a new issue in the DS Bot repository with all of this filled in. Nothing is sent until you submit it there.") }, - (0, import_react44.createElement)("button", { type: "button", className: "bt-fb-primary", onClick: openIssue }, t("Report on GitHub")) + (0, import_react45.createElement)("button", { type: "button", className: "bt-fb-primary", onClick: openIssue }, t("Report on GitHub")) ) ), - note ? (0, import_react44.createElement)( + note ? (0, import_react45.createElement)( "div", { key: "note", className: "bt-note bt-fb-note", role: "status" }, note, - issueLink ? [" ", (0, import_react44.createElement)("a", { key: "link", href: issueLink, target: "_blank", rel: "noopener noreferrer" }, t("Open the issue"))] : null + issueLink ? [" ", (0, import_react45.createElement)("a", { key: "link", href: issueLink, target: "_blank", rel: "noopener noreferrer" }, t("Open the issue"))] : null ) : null, - (0, import_react44.createElement)( + (0, import_react45.createElement)( Section, { key: "errors", title: report ? t("Recent errors · {count}", { count: total }) : t("Recent errors") }, - shown.length === 0 ? (0, import_react44.createElement)(Row3, { label: t("No errors recorded."), hint: t("Failed model calls and DS Bot problems show here, newest first.") }) : shown.map((entry, index) => (0, import_react44.createElement)( + shown.length === 0 ? (0, import_react45.createElement)(Row3, { label: t("No errors recorded."), hint: t("Failed model calls and DS Bot problems show here, newest first.") }) : shown.map((entry, index) => (0, import_react45.createElement)( "div", { key: `${entry.time}-${index}`, className: "bt-set-row bt-fb-entry", title: entry.text }, - (0, import_react44.createElement)("span", { className: "bt-fb-dot", "data-level": entry.level, "aria-hidden": true }), - (0, import_react44.createElement)( + (0, import_react45.createElement)("span", { className: "bt-fb-dot", "data-level": entry.level, "aria-hidden": true }), + (0, import_react45.createElement)( "div", { className: "bt-set-copy" }, - (0, import_react44.createElement)("span", { className: "bt-fb-text" }, entrySummary(entry)), - (0, import_react44.createElement)("span", { className: "bt-set-hint" }, [whenText(entry.time), entry.bot, entry.where, t(SOURCES[entry.source] ?? "DS Bot")].filter(Boolean).join(" · ")) + (0, import_react45.createElement)("span", { className: "bt-fb-text" }, entrySummary(entry)), + (0, import_react45.createElement)("span", { className: "bt-set-hint" }, [whenText(entry.time), entry.bot, entry.where, t(SOURCES[entry.source] ?? "DS Bot")].filter(Boolean).join(" · ")) ), - entry.code ? (0, import_react44.createElement)("span", { className: "bt-tag bt-fb-code" }, entry.status ? `${entry.code} ${entry.status}` : entry.code) : null + entry.code ? (0, import_react45.createElement)("span", { className: "bt-tag bt-fb-code" }, entry.status ? `${entry.code} ${entry.status}` : entry.code) : null )), - (0, import_react44.createElement)( + (0, import_react45.createElement)( Row3, { label: t("Error log"), hint: t("Kept on this computer across restarts, up to about 1 MB.") }, - (0, import_react44.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: downloadLog }, t("Download")), - (0, import_react44.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: clearLog, disabled: !report || total === 0 }, t("Clear")) + (0, import_react45.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: downloadLog }, t("Download")), + (0, import_react45.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: clearLog, disabled: !report || total === 0 }, t("Clear")) ) ) ]; @@ -17639,8 +17752,8 @@ function FeedbackPage({ actions, run: run2, Section, Row: Row3 }) { var TOAST_MS = 6e3; function ErrorToast({ useUi, actions }) { const toast = useUi((state) => state.toast); - const [leaving, setLeaving] = (0, import_react44.useState)(false); - (0, import_react44.useEffect)(() => { + const [leaving, setLeaving] = (0, import_react45.useState)(false); + (0, import_react45.useEffect)(() => { if (!toast) return void 0; setLeaving(false); const fade = setTimeout(() => setLeaving(true), TOAST_MS); @@ -17651,15 +17764,15 @@ function ErrorToast({ useUi, actions }) { }; }, [toast?.token]); if (!toast) return null; - return (0, import_react44.createElement)( + return (0, import_react45.createElement)( "div", { className: "bt-toast", role: "alert", "data-leaving": leaving || void 0 }, - (0, import_react44.createElement)("span", { className: "bt-toast-text" }, toast.text), - (0, import_react44.createElement)("button", { type: "button", className: "bt-toast-link", onClick: () => { + (0, import_react45.createElement)("span", { className: "bt-toast-text" }, toast.text), + (0, import_react45.createElement)("button", { type: "button", className: "bt-toast-link", onClick: () => { actions.dismissToast(toast.token); actions.openSettings("feedback"); } }, t("Details")), - (0, import_react44.createElement)("button", { type: "button", className: "bt-icon-btn bt-toast-close", "aria-label": t("Dismiss"), onClick: () => actions.dismissToast(toast.token) }, (0, import_react44.createElement)(CloseIcon)) + (0, import_react45.createElement)("button", { type: "button", className: "bt-icon-btn bt-toast-close", "aria-label": t("Dismiss"), onClick: () => actions.dismissToast(toast.token) }, (0, import_react45.createElement)(CloseIcon)) ); } var FEEDBACK_CSS = ` @@ -17691,7 +17804,7 @@ var FEEDBACK_CSS = ` `; // src/client/about.js -var import_react45 = require("react"); +var import_react46 = require("react"); var CHEER_MS = 1800; var starCount = (count) => new Intl.NumberFormat(dateLocale(), { notation: "compact", maximumFractionDigits: 1 }).format(count); function botHint(update) { @@ -17739,9 +17852,9 @@ function dshHint(dsh, shown) { var linkProps = (href) => ({ className: "bt-soft bt-soft-sm bt-about-link", href, target: "_blank", rel: "noopener noreferrer" }); function AboutPage({ useUpdate, actions, run: run2, Section, Row: Row3 }) { const update = useUpdate((value) => value) ?? {}; - const [checking, setChecking] = (0, import_react45.useState)(false); - const [stars, setStars] = (0, import_react45.useState)(null); - (0, import_react45.useEffect)(() => { + const [checking, setChecking] = (0, import_react46.useState)(false); + const [stars, setStars] = (0, import_react46.useState)(null); + (0, import_react46.useEffect)(() => { let live = true; actions.repoStars().then((count) => { if (live && Number.isInteger(count)) setStars(count); @@ -17751,8 +17864,8 @@ function AboutPage({ useUpdate, actions, run: run2, Section, Row: Row3 }) { live = false; }; }, []); - const [cheer, setCheer] = (0, import_react45.useState)(true); - (0, import_react45.useEffect)(() => { + const [cheer, setCheer] = (0, import_react46.useState)(true); + (0, import_react46.useEffect)(() => { if (!cheer) return void 0; const timer = setTimeout(() => setCheer(false), CHEER_MS); return () => clearTimeout(timer); @@ -17767,37 +17880,37 @@ function AboutPage({ useUpdate, actions, run: run2, Section, Row: Row3 }) { const phase = update.phase ?? "idle"; const dsh = update.dsh; const dshPhase = dsh?.phase ?? "idle"; - (0, import_react45.useEffect)(() => { + (0, import_react46.useEffect)(() => { if (phase === "installed" || phase === "updated" || dshPhase === "installed") setCheer(true); }, [phase, dshPhase]); const markState = checking ? "searching" : phase === "installing" || dshPhase === "installing" ? "working" : cheer ? "done" : "idle"; const dshNew = showsDshRow(dsh, update.app); const dshShown = dshNew && dsh.available; const ownRow = update.source === "app" ? ownAppRow(update.ownApp) : null; - const ownControl = ownRow?.button === "restart" ? (0, import_react45.createElement)("button", { type: "button", className: "bt-fb-primary", onClick: () => run2(actions.installOwnApp()) }, t("Restart to update")) : ownRow?.button === "check" ? (0, import_react45.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => run2(actions.checkOwnApp()) }, t("Check for updates")) : ownRow?.button === "open" ? (0, import_react45.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => run2(actions.openOwnApp()) }, t("Download")) : null; - const botControl = ownRow !== null ? ownControl : phase === "installed" || phase === "updated" || update.source === "app" ? null : update.available || phase === "installing" ? (0, import_react45.createElement)( + const ownControl = ownRow?.button === "restart" ? (0, import_react46.createElement)("button", { type: "button", className: "bt-fb-primary", onClick: () => run2(actions.installOwnApp()) }, t("Restart to update")) : ownRow?.button === "check" ? (0, import_react46.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => run2(actions.checkOwnApp()) }, t("Check for updates")) : ownRow?.button === "open" ? (0, import_react46.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => run2(actions.openOwnApp()) }, t("Download")) : null; + const botControl = ownRow !== null ? ownControl : phase === "installed" || phase === "updated" || update.source === "app" ? null : update.available || phase === "installing" ? (0, import_react46.createElement)( "button", { type: "button", className: "bt-fb-primary", disabled: phase === "installing", onClick: () => run2(actions.installUpdate()) }, phase === "installing" ? t("Updating…") : phase === "failed" ? t("Try again") : t("Update") - ) : (0, import_react45.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: checking || update.enabled === false, onClick: check }, checking ? t("Checking…") : t("Check for updates")); - const dshControl = !dshNew || dshPhase === "installed" ? null : dsh.kind === "app" ? dsh.available ? (0, import_react45.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => run2(actions.openAppUpdates(dsh.verified)) }, t("Open updates")) : null : dsh.available || dshPhase !== "idle" ? (0, import_react45.createElement)( + ) : (0, import_react46.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: checking || update.enabled === false, onClick: check }, checking ? t("Checking…") : t("Check for updates")); + const dshControl = !dshNew || dshPhase === "installed" ? null : dsh.kind === "app" ? dsh.available ? (0, import_react46.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => run2(actions.openAppUpdates(dsh.verified)) }, t("Open updates")) : null : dsh.available || dshPhase !== "idle" ? (0, import_react46.createElement)( "button", { type: "button", className: "bt-fb-primary", disabled: dshPhase === "installing", onClick: () => run2(actions.installDshUpdate()) }, dshPhase === "installing" ? t("Updating…") : dshPhase === "failed" ? t("Try again") : t("Update") ) : null; const repo = update.repoUrl; return [ - (0, import_react45.createElement)( + (0, import_react46.createElement)( "div", { key: "hero", className: "bt-about-hero" }, - (0, import_react45.createElement)("span", { className: "bt-about-mark" }, (0, import_react45.createElement)(BotMark, { look: MAIN_LOOK, bot: { id: "about" }, size: 52, state: markState, live: true, gaze: true, pokeable: true })), - (0, import_react45.createElement)( + (0, import_react46.createElement)("span", { className: "bt-about-mark" }, (0, import_react46.createElement)(BotMark, { look: MAIN_LOOK, bot: { id: "about" }, size: 52, state: markState, live: true, gaze: true, pokeable: true })), + (0, import_react46.createElement)( "div", { className: "bt-about-copy" }, - (0, import_react45.createElement)("span", { className: "bt-about-name" }, "DS Bot"), - update.current ? (0, import_react45.createElement)("span", { className: "bt-about-version" }, t("Version {version}", { version: update.current })) : null + (0, import_react46.createElement)("span", { className: "bt-about-name" }, "DS Bot"), + update.current ? (0, import_react46.createElement)("span", { className: "bt-about-version" }, t("Version {version}", { version: update.current })) : null ), - repo ? (0, import_react45.createElement)( + repo ? (0, import_react46.createElement)( "a", { className: "bt-star", @@ -17807,23 +17920,23 @@ function AboutPage({ useUpdate, actions, run: run2, Section, Row: Row3 }) { title: t("Star DS Bot on GitHub"), "aria-label": stars === null ? t("Star DS Bot on GitHub") : `${t("Star DS Bot on GitHub")} · ${t("{count} stars", { count: stars })}` }, - (0, import_react45.createElement)("span", { className: "bt-star-main" }, (0, import_react45.createElement)("span", { className: "bt-star-icon" }, (0, import_react45.createElement)(StarLineIcon)), "Star"), - stars === null ? null : (0, import_react45.createElement)("span", { className: "bt-star-count" }, starCount(stars)) + (0, import_react46.createElement)("span", { className: "bt-star-main" }, (0, import_react46.createElement)("span", { className: "bt-star-icon" }, (0, import_react46.createElement)(StarLineIcon)), "Star"), + stars === null ? null : (0, import_react46.createElement)("span", { className: "bt-star-count" }, starCount(stars)) ) : null ), - repo ? (0, import_react45.createElement)("p", { key: "ask", className: "bt-about-ask" }, t("If DS Bot helps you, a star on GitHub helps more people find it.")) : null, - (0, import_react45.createElement)( + repo ? (0, import_react46.createElement)("p", { key: "ask", className: "bt-about-ask" }, t("If DS Bot helps you, a star on GitHub helps more people find it.")) : null, + (0, import_react46.createElement)( Section, { key: "updates", title: t("Updates") }, - (0, import_react45.createElement)(Row3, { label: "DS Bot", hint: ownRow?.hint ?? botHint(update) }, botControl, update.available && update.notesUrl ? (0, import_react45.createElement)("a", linkProps(update.notesUrl), t("What's new")) : null), - dsh?.current ? (0, import_react45.createElement)(Row3, { label: "DeepSeek Harness", hint: dshHint(dsh, dshShown) }, dshControl) : null + (0, import_react46.createElement)(Row3, { label: "DS Bot", hint: ownRow?.hint ?? botHint(update) }, botControl, update.available && update.notesUrl ? (0, import_react46.createElement)("a", linkProps(update.notesUrl), t("What's new")) : null), + dsh?.current ? (0, import_react46.createElement)(Row3, { label: "DeepSeek Harness", hint: dshHint(dsh, dshShown) }, dshControl) : null ), - (0, import_react45.createElement)( + (0, import_react46.createElement)( Section, { key: "links", title: t("Links") }, - repo ? (0, import_react45.createElement)(Row3, { label: t("Source code"), hint: repo.replace(/^https:\/\//, "") }, (0, import_react45.createElement)("a", linkProps(repo), (0, import_react45.createElement)(GitHubMark), t("Open"))) : null, - update.notesUrl ? (0, import_react45.createElement)(Row3, { label: t("Release notes") }, (0, import_react45.createElement)("a", linkProps(update.notesUrl), t("Open"))) : null, - (0, import_react45.createElement)(Row3, { label: t("Report a problem") }, (0, import_react45.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => actions.openSettings("feedback") }, t("Open"))) + repo ? (0, import_react46.createElement)(Row3, { label: t("Source code"), hint: repo.replace(/^https:\/\//, "") }, (0, import_react46.createElement)("a", linkProps(repo), (0, import_react46.createElement)(GitHubMark), t("Open"))) : null, + update.notesUrl ? (0, import_react46.createElement)(Row3, { label: t("Release notes") }, (0, import_react46.createElement)("a", linkProps(update.notesUrl), t("Open"))) : null, + (0, import_react46.createElement)(Row3, { label: t("Report a problem") }, (0, import_react46.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => actions.openSettings("feedback") }, t("Open"))) ) ]; } @@ -17856,7 +17969,7 @@ body:not([data-bt-motion=quiet]) .bt-about-mark:hover .bt-mark[data-live][data-s `; // src/client/providers-page.js -var import_react46 = require("react"); +var import_react47 = require("react"); var PROTOCOL_NAMES = { "openai-completions": "OpenAI Chat Completions", "openai-responses": "OpenAI Responses", "anthropic-messages": "Anthropic Messages" }; var ENDPOINT_HINTS = { "anthropic-messages": "https://gateway.example" }; var SHOWN_MODELS = 8; @@ -17864,22 +17977,22 @@ var translated = (promise) => Promise.resolve(promise).catch((failure) => { throw new Error(hostText(failure?.message ?? String(failure))); }); function ProvidersPage({ actions, run: run2, Section }) { - const [view, setView] = (0, import_react46.useState)(null); - const [open, setOpen] = (0, import_react46.useState)(null); - const [adding, setAdding] = (0, import_react46.useState)(false); + const [view, setView] = (0, import_react47.useState)(null); + const [open, setOpen] = (0, import_react47.useState)(null); + const [adding, setAdding] = (0, import_react47.useState)(false); const apply2 = (promise) => run2(translated(promise).then((next) => { if (next?.providers) setView(next); })); - (0, import_react46.useEffect)(() => { + (0, import_react47.useEffect)(() => { void apply2(actions.providers()); }, []); if (view === null) return null; - if (!view.available) return (0, import_react46.createElement)("p", { className: "bt-set-hint" }, t("This DSH cannot set up model providers.")); + if (!view.available) return (0, import_react47.createElement)("p", { className: "bt-set-hint" }, t("This DSH cannot set up model providers.")); return [ - (0, import_react46.createElement)( + (0, import_react47.createElement)( Section, { key: "list", title: t("Model providers · {count}", { count: view.providers.length }) }, - view.providers.map((provider) => (0, import_react46.createElement)(ProviderRow, { + view.providers.map((provider) => (0, import_react47.createElement)(ProviderRow, { key: provider.id, provider, apply: apply2, @@ -17887,9 +18000,9 @@ function ProvidersPage({ actions, run: run2, Section }) { open: open === provider.id, onToggle: () => setOpen(open === provider.id ? null : provider.id) })), - adding ? (0, import_react46.createElement)(AddProvider, { key: "add", view, apply: apply2, actions, onDone: () => setAdding(false) }) : null + adding ? (0, import_react47.createElement)(AddProvider, { key: "add", view, apply: apply2, actions, onDone: () => setAdding(false) }) : null ), - adding ? null : (0, import_react46.createElement)("div", { key: "add", className: "bt-actions" }, (0, import_react46.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => setAdding(true) }, t("Add a provider"))) + adding ? null : (0, import_react47.createElement)("div", { key: "add", className: "bt-actions" }, (0, import_react47.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => setAdding(true) }, t("Add a provider"))) ]; } function keyState(key) { @@ -17898,58 +18011,58 @@ function keyState(key) { return key.writable ? ["set", t("Key set")] : ["outside", t("Key set outside DS Bot")]; } function ProviderRow({ provider, apply: apply2, actions, open, onToggle }) { - const [confirm, setConfirm] = (0, import_react46.useState)(false); - (0, import_react46.useEffect)(() => { + const [confirm, setConfirm] = (0, import_react47.useState)(false); + (0, import_react47.useEffect)(() => { if (!open) setConfirm(false); }, [open]); const state = keyState(provider.key); const shown = provider.models.slice(0, SHOWN_MODELS); const hint = provider.error ?? (provider.models.length === 0 ? t("No models") : t("{count} models", { count: provider.models.length })); - return (0, import_react46.createElement)( + return (0, import_react47.createElement)( "div", { className: "bt-secret-item bt-provider", "data-open": open ? "" : void 0 }, - (0, import_react46.createElement)( + (0, import_react47.createElement)( "button", { type: "button", className: "bt-set-row bt-secret-summary", "aria-expanded": open, onClick: onToggle }, - (0, import_react46.createElement)( + (0, import_react47.createElement)( "span", { className: "bt-set-copy" }, - (0, import_react46.createElement)("span", { className: "bt-secret-title" }, provider.name, provider.name !== provider.id ? (0, import_react46.createElement)("span", { className: "bt-provider-id" }, provider.id) : null), - (0, import_react46.createElement)("span", { className: "bt-set-hint", "data-error": provider.error ? "" : void 0 }, hint) + (0, import_react47.createElement)("span", { className: "bt-secret-title" }, provider.name, provider.name !== provider.id ? (0, import_react47.createElement)("span", { className: "bt-provider-id" }, provider.id) : null), + (0, import_react47.createElement)("span", { className: "bt-set-hint", "data-error": provider.error ? "" : void 0 }, hint) ), - state ? (0, import_react46.createElement)("span", { className: "bt-set-control" }, (0, import_react46.createElement)("span", { className: "bt-provider-state", "data-state": state[0] }, state[1])) : null + state ? (0, import_react47.createElement)("span", { className: "bt-set-control" }, (0, import_react47.createElement)("span", { className: "bt-provider-state", "data-state": state[0] }, state[1])) : null ), - open ? (0, import_react46.createElement)( + open ? (0, import_react47.createElement)( "div", { className: "bt-secret-edit" }, - provider.key?.writable ? (0, import_react46.createElement)(KeyEditor, { provider, apply: apply2, actions }) : null, - provider.key && !provider.key.writable ? (0, import_react46.createElement)("div", { className: "bt-set-hint" }, t("This key comes from outside DS Bot, such as an environment variable, and cannot be changed here.")) : null, - provider.models.length > 0 ? (0, import_react46.createElement)( + provider.key?.writable ? (0, import_react47.createElement)(KeyEditor, { provider, apply: apply2, actions }) : null, + provider.key && !provider.key.writable ? (0, import_react47.createElement)("div", { className: "bt-set-hint" }, t("This key comes from outside DS Bot, such as an environment variable, and cannot be changed here.")) : null, + provider.models.length > 0 ? (0, import_react47.createElement)( "div", { className: "bt-secret-edit-block" }, - (0, import_react46.createElement)("div", { className: "bt-secret-edit-label" }, t("Models")), - (0, import_react46.createElement)( + (0, import_react47.createElement)("div", { className: "bt-secret-edit-label" }, t("Models")), + (0, import_react47.createElement)( "div", { className: "bt-provider-models" }, - shown.map((model) => (0, import_react46.createElement)("span", { key: model.ref, className: "bt-tag", title: model.ref }, model.name)), - provider.models.length > shown.length ? (0, import_react46.createElement)("span", { className: "bt-set-hint" }, t("and {count} more", { count: provider.models.length - shown.length })) : null + shown.map((model) => (0, import_react47.createElement)("span", { key: model.ref, className: "bt-tag", title: model.ref }, model.name)), + provider.models.length > shown.length ? (0, import_react47.createElement)("span", { className: "bt-set-hint" }, t("and {count} more", { count: provider.models.length - shown.length })) : null ) ) : null, - provider.removable ? (0, import_react46.createElement)( + provider.removable ? (0, import_react47.createElement)( "div", { className: "bt-secret-row-actions" }, confirm ? [ - (0, import_react46.createElement)("span", { key: "q", className: "bt-set-hint" }, t("Remove {name}? Bots on its models need another model.", { name: provider.name })), - (0, import_react46.createElement)("button", { key: "no", type: "button", className: "bt-soft bt-soft-sm", onClick: () => setConfirm(false) }, t("Keep")), - (0, import_react46.createElement)("button", { key: "yes", type: "button", className: "bt-soft bt-soft-sm bt-secret-danger", onClick: () => apply2(actions.removeProvider(provider.id)) }, t("Remove")) - ] : (0, import_react46.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm bt-secret-danger", onClick: () => setConfirm(true) }, (0, import_react46.createElement)(TrashIcon), t("Remove provider")) + (0, import_react47.createElement)("span", { key: "q", className: "bt-set-hint" }, t("Remove {name}? Bots on its models need another model.", { name: provider.name })), + (0, import_react47.createElement)("button", { key: "no", type: "button", className: "bt-soft bt-soft-sm", onClick: () => setConfirm(false) }, t("Keep")), + (0, import_react47.createElement)("button", { key: "yes", type: "button", className: "bt-soft bt-soft-sm bt-secret-danger", onClick: () => apply2(actions.removeProvider(provider.id)) }, t("Remove")) + ] : (0, import_react47.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm bt-secret-danger", onClick: () => setConfirm(true) }, (0, import_react47.createElement)(TrashIcon), t("Remove provider")) ) : null ) : null ); } function KeyEditor({ provider, apply: apply2, actions }) { - const [value, setValue] = (0, import_react46.useState)(""); - const [saved, setSaved] = (0, import_react46.useState)(false); + const [value, setValue] = (0, import_react47.useState)(""); + const [saved, setSaved] = (0, import_react47.useState)(false); const ready = value.trim() !== ""; const save = () => { if (!ready) return; @@ -17965,29 +18078,29 @@ function KeyEditor({ provider, apply: apply2, actions }) { setSaved(false); }; const label = t("{provider} API key", { provider: provider.name }); - return (0, import_react46.createElement)( + return (0, import_react47.createElement)( "div", { className: "bt-secret-edit-block" }, - (0, import_react46.createElement)("div", { className: "bt-secret-edit-label" }, provider.key.configured ? t("Replace the API key") : t("API key")), - (0, import_react46.createElement)( + (0, import_react47.createElement)("div", { className: "bt-secret-edit-label" }, provider.key.configured ? t("Replace the API key") : t("API key")), + (0, import_react47.createElement)( "div", { className: "bt-secret-inline" }, - (0, import_react46.createElement)("label", { className: "bt-q-field bt-secret-field" }, (0, import_react46.createElement)(KeyIcon), (0, import_react46.createElement)(MaskedInput, { value, onChange: edit, onEnter: save, label })), - (0, import_react46.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: !ready, onClick: save }, t("Save")), - provider.key.configured ? (0, import_react46.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm bt-secret-danger", onClick: () => apply2(actions.setProviderKey(provider.id, null)) }, t("Remove key")) : null + (0, import_react47.createElement)("label", { className: "bt-q-field bt-secret-field" }, (0, import_react47.createElement)(KeyIcon), (0, import_react47.createElement)(MaskedInput, { value, onChange: edit, onEnter: save, label })), + (0, import_react47.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: !ready, onClick: save }, t("Save")), + provider.key.configured ? (0, import_react47.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm bt-secret-danger", onClick: () => apply2(actions.setProviderKey(provider.id, null)) }, t("Remove key")) : null ), - saved ? (0, import_react46.createElement)("div", { className: "bt-set-hint bt-secret-ok", role: "status" }, (0, import_react46.createElement)(CheckIcon), t("Saved.")) : null + saved ? (0, import_react47.createElement)("div", { className: "bt-set-hint bt-secret-ok", role: "status" }, (0, import_react47.createElement)(CheckIcon), t("Saved.")) : null ); } function AddProvider({ view, apply: apply2, actions, onDone }) { - const [mode, setMode] = (0, import_react46.useState)(view.addable.length > 0 ? "known" : "custom"); - return (0, import_react46.createElement)( + const [mode, setMode] = (0, import_react47.useState)(view.addable.length > 0 ? "known" : "custom"); + return (0, import_react47.createElement)( "div", { className: "bt-set-row bt-set-paste bt-provider-add" }, - (0, import_react46.createElement)( + (0, import_react47.createElement)( Segmented, { label: t("Kind of provider"), value: mode }, - [["known", t("Known provider")], ["custom", t("Custom API")]].map(([id, label]) => (0, import_react46.createElement)("button", { + [["known", t("Known provider")], ["custom", t("Custom API")]].map(([id, label]) => (0, import_react47.createElement)("button", { key: id, type: "button", "aria-pressed": mode === id, @@ -17996,13 +18109,13 @@ function AddProvider({ view, apply: apply2, actions, onDone }) { }, label)) ), // Both forms stay mounted, so switching keeps what is typed in the other. - (0, import_react46.createElement)("div", { hidden: mode !== "known" }, (0, import_react46.createElement)(KnownForm, { view, apply: apply2, actions, onDone })), - (0, import_react46.createElement)("div", { hidden: mode !== "custom" }, (0, import_react46.createElement)(CustomForm, { view, apply: apply2, actions, onDone })) + (0, import_react47.createElement)("div", { hidden: mode !== "known" }, (0, import_react47.createElement)(KnownForm, { view, apply: apply2, actions, onDone })), + (0, import_react47.createElement)("div", { hidden: mode !== "custom" }, (0, import_react47.createElement)(CustomForm, { view, apply: apply2, actions, onDone })) ); } function KnownForm({ view, apply: apply2, actions, onDone }) { - const [provider, setProvider] = (0, import_react46.useState)(""); - const [key, setKey] = (0, import_react46.useState)(""); + const [provider, setProvider] = (0, import_react47.useState)(""); + const [key, setKey] = (0, import_react47.useState)(""); const options = [...view.addable].sort((a, b) => a.name.localeCompare(b.name)); const add = () => { if (provider === "") return; @@ -18010,24 +18123,24 @@ function KnownForm({ view, apply: apply2, actions, onDone }) { if (ok) onDone(); }); }; - return (0, import_react46.createElement)( + return (0, import_react47.createElement)( "div", { className: "bt-provider-form" }, - (0, import_react46.createElement)( + (0, import_react47.createElement)( "select", { className: "bt-select", "aria-label": t("Provider"), value: provider, onChange: (event) => setProvider(event.target.value) }, - (0, import_react46.createElement)("option", { value: "", disabled: true }, t("Choose a provider")), - options.map((option) => (0, import_react46.createElement)("option", { key: option.id, value: option.id }, option.name)) + (0, import_react47.createElement)("option", { value: "", disabled: true }, t("Choose a provider")), + options.map((option) => (0, import_react47.createElement)("option", { key: option.id, value: option.id }, option.name)) ), - (0, import_react46.createElement)("label", { className: "bt-q-field bt-secret-field" }, (0, import_react46.createElement)(KeyIcon), (0, import_react46.createElement)(MaskedInput, { value: key, onChange: setKey, onEnter: add, label: t("API key") })), - (0, import_react46.createElement)(FormActions, { onCancel: onDone, onAdd: add, ready: provider !== "" }) + (0, import_react47.createElement)("label", { className: "bt-q-field bt-secret-field" }, (0, import_react47.createElement)(KeyIcon), (0, import_react47.createElement)(MaskedInput, { value: key, onChange: setKey, onEnter: add, label: t("API key") })), + (0, import_react47.createElement)(FormActions, { onCancel: onDone, onAdd: add, ready: provider !== "" }) ); } function CustomForm({ view, apply: apply2, actions, onDone }) { - const [draft, setDraft] = (0, import_react46.useState)({ provider: "", name: "", baseURL: "", api: view.protocols[0], key: "", typed: "" }); - const [found, setFound] = (0, import_react46.useState)(null); - const [picked, setPicked] = (0, import_react46.useState)([]); - const [asking, setAsking] = (0, import_react46.useState)(false); + const [draft, setDraft] = (0, import_react47.useState)({ provider: "", name: "", baseURL: "", api: view.protocols[0], key: "", typed: "" }); + const [found, setFound] = (0, import_react47.useState)(null); + const [picked, setPicked] = (0, import_react47.useState)([]); + const [asking, setAsking] = (0, import_react47.useState)(false); const set = (field, value) => setDraft((current) => ({ ...current, [field]: value })); const typed = draft.typed.split(/[\s,]+/).map((id) => id.trim()).filter(Boolean); const models = [...(found ?? []).filter((model) => picked.includes(model.id)), ...typed.filter((id) => !picked.includes(id)).map((id) => ({ id }))]; @@ -18046,7 +18159,7 @@ function CustomForm({ view, apply: apply2, actions, onDone }) { if (ok) onDone(); }); }; - const input = (field, label, placeholder) => (0, import_react46.createElement)("input", { + const input = (field, label, placeholder) => (0, import_react47.createElement)("input", { className: "bt-input", "aria-label": label, placeholder, @@ -18055,55 +18168,55 @@ function CustomForm({ view, apply: apply2, actions, onDone }) { autoComplete: "off", onChange: (event) => set(field, event.target.value) }); - return (0, import_react46.createElement)( + return (0, import_react47.createElement)( "div", { className: "bt-provider-form" }, - (0, import_react46.createElement)( + (0, import_react47.createElement)( "div", { className: "bt-provider-pair" }, input("provider", t("Provider ID"), t("Provider ID, e.g. my-gateway")), input("name", t("Name"), t("Name (optional)")) ), - (0, import_react46.createElement)( + (0, import_react47.createElement)( "div", { className: "bt-provider-pair" }, input("baseURL", t("Endpoint"), ENDPOINT_HINTS[draft.api] ?? "https://gateway.example/v1"), - (0, import_react46.createElement)( + (0, import_react47.createElement)( "select", { className: "bt-select", "aria-label": t("Protocol"), value: draft.api, onChange: (event) => set("api", event.target.value) }, - view.protocols.map((api) => (0, import_react46.createElement)("option", { key: api, value: api }, PROTOCOL_NAMES[api] ?? api)) + view.protocols.map((api) => (0, import_react47.createElement)("option", { key: api, value: api }, PROTOCOL_NAMES[api] ?? api)) ) ), - (0, import_react46.createElement)("label", { className: "bt-q-field bt-secret-field" }, (0, import_react46.createElement)(KeyIcon), (0, import_react46.createElement)(MaskedInput, { value: draft.key, onChange: (value) => set("key", value), label: t("API key") })), - (0, import_react46.createElement)( + (0, import_react47.createElement)("label", { className: "bt-q-field bt-secret-field" }, (0, import_react47.createElement)(KeyIcon), (0, import_react47.createElement)(MaskedInput, { value: draft.key, onChange: (value) => set("key", value), label: t("API key") })), + (0, import_react47.createElement)( "div", { className: "bt-secret-edit-block" }, - (0, import_react46.createElement)( + (0, import_react47.createElement)( "div", { className: "bt-provider-models-head" }, - (0, import_react46.createElement)("span", { className: "bt-secret-edit-label" }, t("Models")), - (0, import_react46.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: asking || draft.baseURL.trim() === "", onClick: fetchModels }, asking ? t("Asking…") : t("Fetch models")) + (0, import_react47.createElement)("span", { className: "bt-secret-edit-label" }, t("Models")), + (0, import_react47.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: asking || draft.baseURL.trim() === "", onClick: fetchModels }, asking ? t("Asking…") : t("Fetch models")) ), - found !== null && found.length === 0 ? (0, import_react46.createElement)("div", { className: "bt-set-hint" }, t("The endpoint lists no models. Enter their ids below.")) : null, - found !== null && found.length > 0 ? (0, import_react46.createElement)("div", { className: "bt-secret-bots bt-provider-found" }, found.map((model) => (0, import_react46.createElement)("button", { + found !== null && found.length === 0 ? (0, import_react47.createElement)("div", { className: "bt-set-hint" }, t("The endpoint lists no models. Enter their ids below.")) : null, + found !== null && found.length > 0 ? (0, import_react47.createElement)("div", { className: "bt-secret-bots bt-provider-found" }, found.map((model) => (0, import_react47.createElement)("button", { key: model.id, type: "button", className: "bt-secret-bot", "aria-pressed": picked.includes(model.id), title: model.name && model.name !== model.id ? model.name : void 0, onClick: () => toggle(model.id) - }, (0, import_react46.createElement)("code", null, model.id), picked.includes(model.id) ? (0, import_react46.createElement)(CheckIcon) : null))) : null, + }, (0, import_react47.createElement)("code", null, model.id), picked.includes(model.id) ? (0, import_react47.createElement)(CheckIcon) : null))) : null, input("typed", t("Model ids"), t("Model ids, separated by commas")) ), - (0, import_react46.createElement)(FormActions, { onCancel: onDone, onAdd: add, ready }) + (0, import_react47.createElement)(FormActions, { onCancel: onDone, onAdd: add, ready }) ); } function FormActions({ onCancel, onAdd, ready }) { - return (0, import_react46.createElement)( + return (0, import_react47.createElement)( "div", { className: "bt-secret-row-actions" }, - (0, import_react46.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: onCancel }, t("Cancel")), - (0, import_react46.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: !ready, onClick: onAdd }, t("Add")) + (0, import_react47.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: onCancel }, t("Cancel")), + (0, import_react47.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: !ready, onClick: onAdd }, t("Add")) ); } var PROVIDERS_CSS = ` @@ -18134,24 +18247,24 @@ var PROVIDERS_CSS = ` `; // src/client/settings.js -var import_react47 = require("react"); +var import_react48 = require("react"); var capitalize2 = (word) => word[0].toUpperCase() + word.slice(1); var SETTINGS_PAGES = [["general", "General"], ["models", "Models"], ["bots", "Bots"], ["groups", "Group chats"], ["connectors", "Connectors"], ["capabilities", "Capabilities"], ["browser", "Browser"], ["schedules", "Scheduled tasks"], ["usage", "Usage"], ["secrets", "Secrets"], ["feedback", "Feedback"], ["about", "About DS Bot"]]; var PAGE_ICONS = { ...SETTINGS_ICONS, models: SlidersIcon, connectors: ConnectorIcon, capabilities: PlugIcon, browser: ConnectorIcon, schedules: ClockIcon, secrets: KeyIcon, feedback: FeedbackIcon, about: InfoIcon }; function SetSection({ title, className = "", children }) { - return (0, import_react47.createElement)("section", { className: `bt-set-section ${className}`.trim() }, (0, import_react47.createElement)("h3", null, title), (0, import_react47.createElement)("div", { className: "bt-set-card" }, children)); + return (0, import_react48.createElement)("section", { className: `bt-set-section ${className}`.trim() }, (0, import_react48.createElement)("h3", null, title), (0, import_react48.createElement)("div", { className: "bt-set-card" }, children)); } function SetRow({ label, hint, children, className = "" }) { - return (0, import_react47.createElement)( + return (0, import_react48.createElement)( "div", { className: `bt-set-row ${className}`.trim() }, - (0, import_react47.createElement)("div", { className: "bt-set-copy" }, (0, import_react47.createElement)("span", null, label), hint ? (0, import_react47.createElement)("span", { className: "bt-set-hint" }, hint) : null), - children ? (0, import_react47.createElement)("div", { className: "bt-set-control" }, children) : null + (0, import_react48.createElement)("div", { className: "bt-set-copy" }, (0, import_react48.createElement)("span", null, label), hint ? (0, import_react48.createElement)("span", { className: "bt-set-hint" }, hint) : null), + children ? (0, import_react48.createElement)("div", { className: "bt-set-control" }, children) : null ); } var LAYOUTS = [["bubble", "Bubble"], ["flat", "Flat"]]; function Choice({ label, value, options, pick: pick2 }) { - return (0, import_react47.createElement)(Segmented, { label, value, className: "bt-look-seg" }, options.map(([id, text]) => (0, import_react47.createElement)("button", { + return (0, import_react48.createElement)(Segmented, { label, value, className: "bt-look-seg" }, options.map(([id, text]) => (0, import_react48.createElement)("button", { key: id, type: "button", "aria-pressed": value === id, @@ -18161,12 +18274,12 @@ function Choice({ label, value, options, pick: pick2 }) { }, t(text)))); } function WidthSlider({ label, value, save }) { - const [width, setWidth] = (0, import_react47.useState)(value); - const pending = (0, import_react47.useRef)(null); - const timer = (0, import_react47.useRef)(0); - const saveRef = (0, import_react47.useRef)(save); + const [width, setWidth] = (0, import_react48.useState)(value); + const pending = (0, import_react48.useRef)(null); + const timer = (0, import_react48.useRef)(0); + const saveRef = (0, import_react48.useRef)(save); saveRef.current = save; - (0, import_react47.useEffect)(() => { + (0, import_react48.useEffect)(() => { if (pending.current === null) setWidth(value); }, [value]); const flush = () => { @@ -18174,7 +18287,7 @@ function WidthSlider({ label, value, save }) { pending.current = null; if (next !== null) saveRef.current(next); }; - (0, import_react47.useEffect)(() => () => { + (0, import_react48.useEffect)(() => () => { clearTimeout(timer.current); flush(); }, []); @@ -18185,46 +18298,46 @@ function WidthSlider({ label, value, save }) { timer.current = setTimeout(flush, 350); }; const { min, max, step } = MESSAGE_WIDTH; - return (0, import_react47.createElement)( + return (0, import_react48.createElement)( "div", { className: "bt-range", style: { "--bt-fill": `${(width - min) / (max - min) * 100}%` } }, - (0, import_react47.createElement)("input", { type: "range", min, max, step, value: width, "aria-label": label, "aria-valuetext": `${width}%`, onChange: (event) => pick2(Number(event.target.value)) }), - (0, import_react47.createElement)("output", null, `${width}%`) + (0, import_react48.createElement)("input", { type: "range", min, max, step, value: width, "aria-label": label, "aria-valuetext": `${width}%`, onChange: (event) => pick2(Number(event.target.value)) }), + (0, import_react48.createElement)("output", null, `${width}%`) ); } function GeneralPage({ roster, actions, run: run2 }) { const prefs = roster.prefs ?? {}; const themes = allThemes(); const current = themes[prefs.theme] ? prefs.theme : "deepseek"; - const [custom, setCustom] = (0, import_react47.useState)(prefs.accent ?? "#4d6bfe"); - const timer = (0, import_react47.useRef)(0); - (0, import_react47.useEffect)(() => () => clearTimeout(timer.current), []); + const [custom, setCustom] = (0, import_react48.useState)(prefs.accent ?? "#4d6bfe"); + const timer = (0, import_react48.useRef)(0); + (0, import_react48.useEffect)(() => () => clearTimeout(timer.current), []); const pickCustom = (value) => { setCustom(value); clearTimeout(timer.current); timer.current = setTimeout(() => run2(actions.setPrefs({ accent: value })), 350); }; return [ - (0, import_react47.createElement)( + (0, import_react48.createElement)( SetSection, { key: "look", title: t("Appearance") }, - (0, import_react47.createElement)( + (0, import_react48.createElement)( SetRow, { label: t("Theme"), hint: t("Colors for the whole team, on every device.") }, - (0, import_react47.createElement)( + (0, import_react48.createElement)( "select", { className: "bt-select", "aria-label": t("Theme"), value: current, onChange: (event) => run2(actions.setPrefs({ theme: event.target.value })) }, - Object.entries(themes).map(([id, theme]) => (0, import_react47.createElement)("option", { key: id, value: id }, t(theme.label))) + Object.entries(themes).map(([id, theme]) => (0, import_react48.createElement)("option", { key: id, value: id }, t(theme.label))) ) ), - (0, import_react47.createElement)( + (0, import_react48.createElement)( SetRow, { label: t("Accent"), hint: t("Unread marks, badges, and the brand mark.") }, - (0, import_react47.createElement)( + (0, import_react48.createElement)( "div", { className: "bt-swatches" }, - (0, import_react47.createElement)("button", { type: "button", className: "bt-swatch bt-swatch-default", title: t("Theme accent"), "aria-label": t("Theme accent"), "aria-pressed": !prefs.accent, onClick: () => run2(actions.setPrefs({ accent: null })) }), - ACCENT_INKS.map((ink) => (0, import_react47.createElement)("button", { + (0, import_react48.createElement)("button", { type: "button", className: "bt-swatch bt-swatch-default", title: t("Theme accent"), "aria-label": t("Theme accent"), "aria-pressed": !prefs.accent, onClick: () => run2(actions.setPrefs({ accent: null })) }), + ACCENT_INKS.map((ink) => (0, import_react48.createElement)("button", { key: ink, type: "button", className: "bt-swatch", @@ -18234,26 +18347,26 @@ function GeneralPage({ roster, actions, run: run2 }) { style: { background: INKS[ink][0] }, onClick: () => run2(actions.setPrefs({ accent: INKS[ink][0] })) })), - (0, import_react47.createElement)( + (0, import_react48.createElement)( "label", { className: "bt-swatch bt-swatch-custom", title: t("Custom accent"), "data-on": Boolean(prefs.accent) && !ACCENT_INKS.some((ink) => INKS[ink][0] === prefs.accent) }, - (0, import_react47.createElement)("input", { type: "color", value: custom, "aria-label": t("Custom accent"), onChange: (event) => pickCustom(event.target.value) }) + (0, import_react48.createElement)("input", { type: "color", value: custom, "aria-label": t("Custom accent"), onChange: (event) => pickCustom(event.target.value) }) ) ) ), - (0, import_react47.createElement)(SetRow, { label: t("Message layout") }, (0, import_react47.createElement)(Choice, { label: t("Message layout"), value: layoutOf(prefs), options: LAYOUTS, pick: (id) => run2(actions.setPrefs({ layout: id })) })), + (0, import_react48.createElement)(SetRow, { label: t("Message layout") }, (0, import_react48.createElement)(Choice, { label: t("Message layout"), value: layoutOf(prefs), options: LAYOUTS, pick: (id) => run2(actions.setPrefs({ layout: id })) })), // The flat layout's text has a width of its own; the bubble width stays for the user's messages. - layoutOf(prefs) === "flat" ? (0, import_react47.createElement)(SetRow, { label: t("Text width") }, (0, import_react47.createElement)(WidthSlider, { label: t("Text width"), value: flatWidthOf(prefs), save: (flatWidth) => run2(actions.setPrefs({ flatWidth })) })) : null, - (0, import_react47.createElement)(SetRow, { label: t("Bubble width") }, (0, import_react47.createElement)(WidthSlider, { label: t("Bubble width"), value: widthOf(prefs), save: (width) => run2(actions.setPrefs({ width })) })), - (0, import_react47.createElement)(SetRow, { label: t("Show thinking") }, (0, import_react47.createElement)(Switch, { label: t("Show thinking"), on: thinkingShown(prefs), onChange: (thinking) => run2(actions.setPrefs({ thinking })) })) + layoutOf(prefs) === "flat" ? (0, import_react48.createElement)(SetRow, { label: t("Text width") }, (0, import_react48.createElement)(WidthSlider, { label: t("Text width"), value: flatWidthOf(prefs), save: (flatWidth) => run2(actions.setPrefs({ flatWidth })) })) : null, + (0, import_react48.createElement)(SetRow, { label: t("Bubble width") }, (0, import_react48.createElement)(WidthSlider, { label: t("Bubble width"), value: widthOf(prefs), save: (width) => run2(actions.setPrefs({ width })) })), + (0, import_react48.createElement)(SetRow, { label: t("Show thinking") }, (0, import_react48.createElement)(Switch, { label: t("Show thinking"), on: thinkingShown(prefs), onChange: (thinking) => run2(actions.setPrefs({ thinking })) })) ), - (0, import_react47.createElement)( + (0, import_react48.createElement)( SetSection, { key: "new", title: t("New Bots") }, - (0, import_react47.createElement)( + (0, import_react48.createElement)( SetRow, { label: t("Default model"), className: "bt-set-model" }, - (0, import_react47.createElement)(ModelMenu, { + (0, import_react48.createElement)(ModelMenu, { bot: { id: "new-bots", name: t("New Bots"), model: prefs.defaultBotModel }, roster, actions, @@ -18262,37 +18375,37 @@ function GeneralPage({ roster, actions, run: run2 }) { withEfforts: false, onPick: (ref) => run2(actions.setPrefs({ defaultBotModel: ref })) }), - prefs.defaultBotModel ? (0, import_react47.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => run2(actions.setPrefs({ defaultBotModel: null })) }, t("Reset")) : null + prefs.defaultBotModel ? (0, import_react48.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => run2(actions.setPrefs({ defaultBotModel: null })) }, t("Reset")) : null ) ), - (0, import_react47.createElement)( + (0, import_react48.createElement)( SetSection, { key: "input", title: t("Input") }, - (0, import_react47.createElement)( + (0, import_react48.createElement)( SetRow, { label: t("Enter sends message") }, - (0, import_react47.createElement)(Switch, { label: t("Enter sends message"), on: prefs.enterToSend !== false, onChange: (enterToSend) => run2(actions.setPrefs({ enterToSend })) }) + (0, import_react48.createElement)(Switch, { label: t("Enter sends message"), on: prefs.enterToSend !== false, onChange: (enterToSend) => run2(actions.setPrefs({ enterToSend })) }) ) ), - actions.setSurface ? (0, import_react47.createElement)( + actions.setSurface ? (0, import_react48.createElement)( SetSection, { key: "mode", title: t("Mode") }, - (0, import_react47.createElement)( + (0, import_react48.createElement)( SetRow, { label: t("Classic Agent mode") }, - (0, import_react47.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => actions.setSurface("agent") }, t("Switch")) + (0, import_react48.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => actions.setSurface("agent") }, t("Switch")) ) ) : null, - (0, import_react47.createElement)(LocationsSection, { key: "places", actions, run: run2 }) + (0, import_react48.createElement)(LocationsSection, { key: "places", actions, run: run2 }) ]; } function LocationsSection({ actions, run: run2 }) { const app = globalThis.dsBotApp; - const [team, setTeam] = (0, import_react47.useState)(null); - const [data, setData] = (0, import_react47.useState)(null); - const [moving, setMoving] = (0, import_react47.useState)(false); - const busy = (0, import_react47.useRef)(false); - (0, import_react47.useEffect)(() => { + const [team, setTeam] = (0, import_react48.useState)(null); + const [data, setData] = (0, import_react48.useState)(null); + const [moving, setMoving] = (0, import_react48.useState)(false); + const busy = (0, import_react48.useRef)(false); + (0, import_react48.useEffect)(() => { void Promise.resolve(actions.folders()).then((info) => setTeam(info?.team ?? null)).catch(() => { }); if (app !== void 0) void Promise.resolve(app.dataLocation()).then(setData).catch(() => { @@ -18310,18 +18423,18 @@ function LocationsSection({ actions, run: run2 }) { setMoving(false); })); }; - return (0, import_react47.createElement)( + return (0, import_react48.createElement)( SetSection, { title: t("Locations"), className: "bt-set-places" }, - (0, import_react47.createElement)( + (0, import_react48.createElement)( SetRow, { label: t("Team workspace"), hint: t("Where Bots without a folder of their own work.") }, - team === null ? null : (0, import_react47.createElement)(FolderMenu, { value: team, team: true, actions, run: run2, onPick: pickTeam, disabled: moving }) + team === null ? null : (0, import_react48.createElement)(FolderMenu, { value: team, team: true, actions, run: run2, onPick: pickTeam, disabled: moving }) ), - data === null ? null : (0, import_react47.createElement)( + data === null ? null : (0, import_react48.createElement)( SetRow, { label: t("Data location"), hint: data.path }, - data.fixed ? null : (0, import_react47.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: moving, onClick: () => { + data.fixed ? null : (0, import_react48.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: moving, onClick: () => { if (!busy.current) void run2(app.moveData(team ?? void 0)); } }, t("Change…")) ) @@ -18331,52 +18444,52 @@ function MainBotsSection({ roster, actions, run: run2 }) { const mains = (roster.mainBotIds ?? []).map((id) => roster.byId[id]).filter(Boolean); const [first, ...others] = mains; const candidates = roster.bots.filter((bot) => !isMainOf(roster, bot.id)); - return (0, import_react47.createElement)( + return (0, import_react48.createElement)( SetSection, { title: t("Main Bot") }, - (0, import_react47.createElement)( + (0, import_react48.createElement)( SetRow, { label: t("Main Bot"), hint: first ? t("First in the sidebar. Pick another Bot to hand it the role; {name} then stops being a Main Bot.", { name: first.name }) : void 0 }, - (0, import_react47.createElement)("select", { + (0, import_react48.createElement)("select", { className: "bt-select", "aria-label": t("Main Bot"), value: first?.id ?? "", onChange: (event) => run2(actions.setMain(event.target.value, true, first ? { replace: first.id } : {})) - }, first ? null : (0, import_react47.createElement)("option", { value: "" }, t("Choose a Bot…")), roster.bots.map((bot) => (0, import_react47.createElement)("option", { key: bot.id, value: bot.id }, bot.name))) + }, first ? null : (0, import_react48.createElement)("option", { value: "" }, t("Choose a Bot…")), roster.bots.map((bot) => (0, import_react48.createElement)("option", { key: bot.id, value: bot.id }, bot.name))) ), - others.map((bot) => (0, import_react47.createElement)( + others.map((bot) => (0, import_react48.createElement)( SetRow, { key: bot.id, label: bot.name, hint: t("Also a Main Bot.") }, - (0, import_react47.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => run2(actions.setMain(bot.id, true, { primary: true })) }, t("Move to first")), - (0, import_react47.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => run2(actions.setMain(bot.id, false)) }, t("Remove Main Bot role")) + (0, import_react48.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => run2(actions.setMain(bot.id, true, { primary: true })) }, t("Move to first")), + (0, import_react48.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", onClick: () => run2(actions.setMain(bot.id, false)) }, t("Remove Main Bot role")) )), - candidates.length > 0 ? (0, import_react47.createElement)( + candidates.length > 0 ? (0, import_react48.createElement)( SetRow, { label: t("Add a Main Bot"), hint: t("Main Bots can create and change Bots, and run every group chat.") }, - (0, import_react47.createElement)("select", { + (0, import_react48.createElement)("select", { className: "bt-select", "aria-label": t("Add a Main Bot"), value: "", onChange: (event) => { if (event.target.value) void run2(actions.setMain(event.target.value, true)); } - }, (0, import_react47.createElement)("option", { value: "" }, t("Choose a Bot…")), candidates.map((bot) => (0, import_react47.createElement)("option", { key: bot.id, value: bot.id }, bot.name))) + }, (0, import_react48.createElement)("option", { value: "" }, t("Choose a Bot…")), candidates.map((bot) => (0, import_react48.createElement)("option", { key: bot.id, value: bot.id }, bot.name))) ) : null ); } var MOTIONS = [["quiet", "Quiet"], ["normal", "Normal"], ["lively", "Lively"]]; function MotionSection({ roster, actions, run: run2 }) { const motion = roster.prefs?.motion === "quiet" || roster.prefs?.motion === "lively" ? roster.prefs.motion : "normal"; - return (0, import_react47.createElement)( + return (0, import_react48.createElement)( SetSection, { title: t("Animation") }, - (0, import_react47.createElement)( + (0, import_react48.createElement)( SetRow, { label: t("Bot animation") }, - (0, import_react47.createElement)(Segmented, { label: t("Bot animation"), value: motion, className: "bt-motion-seg" }, MOTIONS.map(([id, label]) => (0, import_react47.createElement)("button", { + (0, import_react48.createElement)(Segmented, { label: t("Bot animation"), value: motion, className: "bt-motion-seg" }, MOTIONS.map(([id, label]) => (0, import_react48.createElement)("button", { key: id, type: "button", "aria-pressed": motion === id, @@ -18388,70 +18501,70 @@ function MotionSection({ roster, actions, run: run2 }) { ); } function BotsPage({ roster, actions, run: run2 }) { - const [creating, setCreating] = (0, import_react47.useState)(false); + const [creating, setCreating] = (0, import_react48.useState)(false); return [ - (0, import_react47.createElement)(MainBotsSection, { key: "main", roster, actions, run: run2 }), - (0, import_react47.createElement)(MotionSection, { key: "motion", roster, actions, run: run2 }), - creating ? (0, import_react47.createElement)(CreateBot, { key: "create", roster, actions, inline: true, onBack: () => setCreating(false), onCreated: (bot) => actions.openSettings("bots", bot.id) }) : (0, import_react47.createElement)( + (0, import_react48.createElement)(MainBotsSection, { key: "main", roster, actions, run: run2 }), + (0, import_react48.createElement)(MotionSection, { key: "motion", roster, actions, run: run2 }), + creating ? (0, import_react48.createElement)(CreateBot, { key: "create", roster, actions, inline: true, onBack: () => setCreating(false), onCreated: (bot) => actions.openSettings("bots", bot.id) }) : (0, import_react48.createElement)( "div", { key: "new", className: "bt-actions" }, - (0, import_react47.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm bt-with-icon", onClick: () => setCreating(true) }, (0, import_react47.createElement)(PlusIcon), t("New Bot")) + (0, import_react48.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm bt-with-icon", onClick: () => setCreating(true) }, (0, import_react48.createElement)(PlusIcon), t("New Bot")) ), - (0, import_react47.createElement)( + (0, import_react48.createElement)( SetSection, { key: "bots", title: t("Bots · {count}", { count: roster.bots.length }) }, - roster.bots.map((bot) => (0, import_react47.createElement)( + roster.bots.map((bot) => (0, import_react48.createElement)( "button", { key: bot.id, type: "button", className: "bt-set-row", onClick: () => actions.openSettings("bots", bot.id) }, - (0, import_react47.createElement)( + (0, import_react48.createElement)( "span", { className: "bt-set-bot" }, - (0, import_react47.createElement)(BotAvatar, { bot, size: 28, badge: false, live: false }), - (0, import_react47.createElement)("span", { className: "bt-row-title" }, bot.name), - bot.role ? (0, import_react47.createElement)("span", { className: "bt-tag" }, bot.role) : null, - isMainOf(roster, bot.id) ? (0, import_react47.createElement)("span", { className: "bt-tag" }, t("Main Bot")) : null, - bot.hidden && !isMainOf(roster, bot.id) ? (0, import_react47.createElement)("span", { className: "bt-tag" }, t("Hidden")) : null + (0, import_react48.createElement)(BotAvatar, { bot, size: 28, badge: false, live: false }), + (0, import_react48.createElement)("span", { className: "bt-row-title" }, bot.name), + bot.role ? (0, import_react48.createElement)("span", { className: "bt-tag" }, bot.role) : null, + isMainOf(roster, bot.id) ? (0, import_react48.createElement)("span", { className: "bt-tag" }, t("Main Bot")) : null, + bot.hidden && !isMainOf(roster, bot.id) ? (0, import_react48.createElement)("span", { className: "bt-tag" }, t("Hidden")) : null ), - (0, import_react47.createElement)("span", { className: "bt-chevron" }, (0, import_react47.createElement)(ChevronRightIcon)) + (0, import_react48.createElement)("span", { className: "bt-chevron" }, (0, import_react48.createElement)(ChevronRightIcon)) )) ), - (0, import_react47.createElement)(KeptPrivateSection, { key: "kept", roster, actions, run: run2, Section: SetSection, Row: SetRow }) + (0, import_react48.createElement)(KeptPrivateSection, { key: "kept", roster, actions, run: run2, Section: SetSection, Row: SetRow }) ]; } function GroupsPage({ roster, actions, run: run2 }) { - const [creating, setCreating] = (0, import_react47.useState)(false); + const [creating, setCreating] = (0, import_react48.useState)(false); return [ - creating ? (0, import_react47.createElement)(NewGroupForm, { key: "create", roster, actions, run: run2, onCancel: () => setCreating(false), onCreated: (room2) => actions.openSettings("groups", room2.id) }) : (0, import_react47.createElement)( + creating ? (0, import_react48.createElement)(NewGroupForm, { key: "create", roster, actions, run: run2, onCancel: () => setCreating(false), onCreated: (room2) => actions.openSettings("groups", room2.id) }) : (0, import_react48.createElement)( "div", { key: "new", className: "bt-actions" }, - (0, import_react47.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm bt-with-icon", disabled: roster.bots.length < 2, title: roster.bots.length < 2 ? t("A group chat needs at least two Bots") : void 0, onClick: () => setCreating(true) }, (0, import_react47.createElement)(PlusIcon), t("Create group chat")) + (0, import_react48.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm bt-with-icon", disabled: roster.bots.length < 2, title: roster.bots.length < 2 ? t("A group chat needs at least two Bots") : void 0, onClick: () => setCreating(true) }, (0, import_react48.createElement)(PlusIcon), t("Create group chat")) ), - (0, import_react47.createElement)( + (0, import_react48.createElement)( SetSection, { key: "groups", title: t("Group chats · {count}", { count: roster.rooms.length }) }, - roster.rooms.length === 0 ? (0, import_react47.createElement)(SetRow, { label: t("No group chats yet."), hint: t("A group chat lets several Bots work on one thing with you.") }) : roster.rooms.map((room2) => { + roster.rooms.length === 0 ? (0, import_react48.createElement)(SetRow, { label: t("No group chats yet."), hint: t("A group chat lets several Bots work on one thing with you.") }) : roster.rooms.map((room2) => { const admin = roster.byId[room2.admin]; - return (0, import_react47.createElement)( + return (0, import_react48.createElement)( "button", { key: room2.id, type: "button", className: "bt-set-row", onClick: () => actions.openSettings("groups", room2.id) }, - (0, import_react47.createElement)( + (0, import_react48.createElement)( "span", { className: "bt-set-bot" }, - (0, import_react47.createElement)(RoomAvatar, { room: room2, roster, size: 28 }), - (0, import_react47.createElement)("span", { className: "bt-row-title" }, room2.name), - (0, import_react47.createElement)("span", { className: "bt-tag" }, t("{count} members", { count: room2.members.length })), - admin ? (0, import_react47.createElement)("span", { className: "bt-tag bt-tag-admin" }, (0, import_react47.createElement)(AdminStar), admin.name) : null, - room2.hidden ? (0, import_react47.createElement)("span", { className: "bt-tag" }, t("Hidden")) : null + (0, import_react48.createElement)(RoomAvatar, { room: room2, roster, size: 28 }), + (0, import_react48.createElement)("span", { className: "bt-row-title" }, room2.name), + (0, import_react48.createElement)("span", { className: "bt-tag" }, t("{count} members", { count: room2.members.length })), + admin ? (0, import_react48.createElement)("span", { className: "bt-tag bt-tag-admin" }, (0, import_react48.createElement)(AdminStar), admin.name) : null, + room2.hidden ? (0, import_react48.createElement)("span", { className: "bt-tag" }, t("Hidden")) : null ), - (0, import_react47.createElement)("span", { className: "bt-chevron" }, (0, import_react47.createElement)(ChevronRightIcon)) + (0, import_react48.createElement)("span", { className: "bt-chevron" }, (0, import_react48.createElement)(ChevronRightIcon)) ); }) ) ]; } function SettingsDialog({ page, id, roster, actions, useUpdate, leaving = false }) { - const [error, setError] = (0, import_react47.useState)(""); - const close = (0, import_react47.useCallback)(() => actions.closeSettings(), []); + const [error, setError] = (0, import_react48.useState)(""); + const close = (0, import_react48.useCallback)(() => actions.closeSettings(), []); useEscape(close); const run2 = (promise) => Promise.resolve(promise).then(() => { setError(""); @@ -18470,32 +18583,32 @@ function SettingsDialog({ page, id, roster, actions, useUpdate, leaving = false const nav = useGlide(shown, { axis: "y" }); const pageKey = `${shown}:${bot?.id ?? room2?.id ?? ""}`; const depth = bot || room2 ? 1 : 0; - const last = (0, import_react47.useRef)({ key: pageKey, depth, move: "up" }); + const last = (0, import_react48.useRef)({ key: pageKey, depth, move: "up" }); if (last.current.key !== pageKey) { last.current = { key: pageKey, depth, move: depth > last.current.depth ? "in" : depth < last.current.depth ? "out" : "up" }; } - const [usageOpened, setUsageOpened] = (0, import_react47.useState)(shown === "usage"); + const [usageOpened, setUsageOpened] = (0, import_react48.useState)(shown === "usage"); if (shown === "usage" && !usageOpened) setUsageOpened(true); - const errorLine = error ? (0, import_react47.createElement)("div", { className: "bt-error", role: "alert", style: { padding: 0 } }, error) : null; - return (0, import_react47.createElement)( + const errorLine = error ? (0, import_react48.createElement)("div", { className: "bt-error", role: "alert", style: { padding: 0 } }, error) : null; + return (0, import_react48.createElement)( "div", { className: "bt-settings-layer", "data-leaving": leaving || void 0 }, - (0, import_react47.createElement)("div", { className: "bt-scrim", onMouseDown: close }), - (0, import_react47.createElement)( + (0, import_react48.createElement)("div", { className: "bt-scrim", onMouseDown: close }), + (0, import_react48.createElement)( "div", { className: "bt-settings", role: "dialog", "aria-modal": true, "aria-label": t("DS Bot settings") }, - (0, import_react47.createElement)( + (0, import_react48.createElement)( "nav", { ref: nav.box, className: "bt-settings-nav", "aria-label": t("Settings pages") }, - (0, import_react47.createElement)("span", { ref: nav.thumb, className: "bt-thumb", "aria-hidden": true }), - pages.map(([key, text]) => (0, import_react47.createElement)("button", { + (0, import_react48.createElement)("span", { ref: nav.thumb, className: "bt-thumb", "aria-hidden": true }), + pages.map(([key, text]) => (0, import_react48.createElement)("button", { key, type: "button", className: "bt-settings-item", "aria-current": shown === key ? "page" : void 0, onClick: () => actions.openSettings(key) - }, (0, import_react47.createElement)(PAGE_ICONS[key]), t(text))), - actions.openHarnessSettings ? (0, import_react47.createElement)("button", { + }, (0, import_react48.createElement)(PAGE_ICONS[key]), t(text))), + actions.openHarnessSettings ? (0, import_react48.createElement)("button", { type: "button", className: "bt-settings-item bt-settings-shell", title: t("Models, providers, and the rest of DeepSeek Harness"), @@ -18503,67 +18616,67 @@ function SettingsDialog({ page, id, roster, actions, useUpdate, leaving = false close(); actions.openHarnessSettings(); } - }, (0, import_react47.createElement)(SlidersIcon), t("Harness settings")) : null + }, (0, import_react48.createElement)(SlidersIcon), t("Harness settings")) : null ), - (0, import_react47.createElement)( + (0, import_react48.createElement)( "div", { className: "bt-settings-main" }, - (0, import_react47.createElement)( + (0, import_react48.createElement)( "div", { className: "bt-settings-head" }, - back ? (0, import_react47.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": back, title: back, onClick: () => actions.openSettings(shown) }, (0, import_react47.createElement)(ChevronLeftIcon)) : null, - (0, import_react47.createElement)("h2", { key: bot?.id ?? room2?.id ?? shown }, bot?.name ?? room2?.name ?? label) + back ? (0, import_react48.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": back, title: back, onClick: () => actions.openSettings(shown) }, (0, import_react48.createElement)(ChevronLeftIcon)) : null, + (0, import_react48.createElement)("h2", { key: bot?.id ?? room2?.id ?? shown }, bot?.name ?? room2?.name ?? label) ), - shown === "usage" ? null : (0, import_react47.createElement)( + shown === "usage" ? null : (0, import_react48.createElement)( "div", { key: pageKey, className: "bt-settings-scroll bt-settings-page", "data-move": last.current.move }, errorLine, - shown === "general" ? (0, import_react47.createElement)(GeneralPage, { roster, actions, run: run2 }) : null, - shown === "models" ? (0, import_react47.createElement)(ProvidersPage, { actions, run: run2, Section: SetSection }) : null, - bot ? (0, import_react47.createElement)("div", { className: "bt-settings-form" }, (0, import_react47.createElement)(BotSettingsForm, { key: bot.id, bot, roster, actions, run: run2 })) : null, - shown === "bots" && !bot ? (0, import_react47.createElement)(BotsPage, { roster, actions, run: run2 }) : null, - room2 ? (0, import_react47.createElement)("div", { className: "bt-settings-form" }, (0, import_react47.createElement)(GroupSettingsForm, { key: room2.id, room: room2, roster, actions, run: run2 })) : null, - shown === "groups" && !room2 ? (0, import_react47.createElement)(GroupsPage, { roster, actions, run: run2 }) : null, - shown === "connectors" ? (0, import_react47.createElement)(ConnectorsPage, { roster, actions }) : null, - shown === "capabilities" ? (0, import_react47.createElement)(CapabilitiesPage, { roster, actions, run: run2 }) : null, - shown === "browser" ? (0, import_react47.createElement)(BrowserPage, { roster, actions, run: run2, Section: SetSection, Row: SetRow }) : null, - shown === "schedules" ? (0, import_react47.createElement)(SchedulesPage, { roster, actions, start: id ?? void 0 }) : null, - shown === "secrets" ? (0, import_react47.createElement)(SecretsPage, { roster, actions, run: run2, Section: SetSection }) : null, - shown === "feedback" ? (0, import_react47.createElement)(FeedbackPage, { actions, run: run2, Section: SetSection, Row: SetRow }) : null, - shown === "about" ? (0, import_react47.createElement)(AboutPage, { useUpdate, actions, run: run2, Section: SetSection, Row: SetRow }) : null + shown === "general" ? (0, import_react48.createElement)(GeneralPage, { roster, actions, run: run2 }) : null, + shown === "models" ? (0, import_react48.createElement)(ProvidersPage, { actions, run: run2, Section: SetSection }) : null, + bot ? (0, import_react48.createElement)("div", { className: "bt-settings-form" }, (0, import_react48.createElement)(BotSettingsForm, { key: bot.id, bot, roster, actions, run: run2 })) : null, + shown === "bots" && !bot ? (0, import_react48.createElement)(BotsPage, { roster, actions, run: run2 }) : null, + room2 ? (0, import_react48.createElement)("div", { className: "bt-settings-form" }, (0, import_react48.createElement)(GroupSettingsForm, { key: room2.id, room: room2, roster, actions, run: run2 })) : null, + shown === "groups" && !room2 ? (0, import_react48.createElement)(GroupsPage, { roster, actions, run: run2 }) : null, + shown === "connectors" ? (0, import_react48.createElement)(ConnectorsPage, { roster, actions }) : null, + shown === "capabilities" ? (0, import_react48.createElement)(CapabilitiesPage, { roster, actions, run: run2 }) : null, + shown === "browser" ? (0, import_react48.createElement)(BrowserPage, { roster, actions, run: run2, Section: SetSection, Row: SetRow }) : null, + shown === "schedules" ? (0, import_react48.createElement)(SchedulesPage, { roster, actions, start: id ?? void 0 }) : null, + shown === "secrets" ? (0, import_react48.createElement)(SecretsPage, { roster, actions, run: run2, Section: SetSection }) : null, + shown === "feedback" ? (0, import_react48.createElement)(FeedbackPage, { actions, run: run2, Section: SetSection, Row: SetRow }) : null, + shown === "about" ? (0, import_react48.createElement)(AboutPage, { useUpdate, actions, run: run2, Section: SetSection, Row: SetRow }) : null ), - usageOpened ? (0, import_react47.createElement)( + usageOpened ? (0, import_react48.createElement)( "div", { key: "usage", className: "bt-settings-scroll bt-settings-usage", "data-off": shown === "usage" ? void 0 : "", "aria-hidden": shown === "usage" ? void 0 : true }, shown === "usage" ? errorLine : null, - (0, import_react47.createElement)(UsagePage, { roster, actions, focusId: usageFocus }) + (0, import_react48.createElement)(UsagePage, { roster, actions, focusId: usageFocus }) ) : null ), - (0, import_react47.createElement)("button", { type: "button", className: "bt-settings-close", "aria-label": t("Close settings"), onClick: close }, (0, import_react47.createElement)(CloseIcon)) + (0, import_react48.createElement)("button", { type: "button", className: "bt-settings-close", "aria-label": t("Close settings"), onClick: close }, (0, import_react48.createElement)(CloseIcon)) ) ); } // src/client/context-menu.js -var import_react48 = require("react"); +var import_react49 = require("react"); function ContextMenu({ menu, roster, actions, leaving = false }) { useEscape(() => actions.closeMenu()); - (0, import_react48.useEffect)(() => { + (0, import_react49.useEffect)(() => { const onDown = (event) => { if (!(event.target instanceof Element) || !event.target.closest(".bt-menu")) actions.closeMenu(); }; window.addEventListener("mousedown", onDown); return () => window.removeEventListener("mousedown", onDown); }, []); - const ref = (0, import_react48.useRef)(null); - const [place, setPlace] = (0, import_react48.useState)({ left: menu.x, top: menu.y }); + const ref = (0, import_react49.useRef)(null); + const [place, setPlace] = (0, import_react49.useState)({ left: menu.x, top: menu.y }); const tick = useViewport(); - (0, import_react48.useLayoutEffect)(() => { + (0, import_react49.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_react48.createElement)(AgentMenu, { menu, roster, actions, leaving }); + if (menu.kind === "agent" || menu.kind === "agent-session") return (0, import_react49.createElement)(AgentMenu, { menu, roster, actions, leaving }); const bot = roster.byId[menu.id]; const room2 = roster.roomsById[menu.id]; const entry = bot ?? room2; @@ -18594,14 +18707,14 @@ function ContextMenu({ menu, roster, actions, 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_react48.createElement)( + return (0, import_react49.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_react48.createElement)( - import_react48.Fragment, + groups.map((group, index) => (0, import_react49.createElement)( + import_react49.Fragment, { key: index }, - index > 0 ? (0, import_react48.createElement)("div", { className: "bt-menu-sep", role: "separator" }) : null, - group.map(([label, Icon, run2, danger]) => (0, import_react48.createElement)("button", { + index > 0 ? (0, import_react49.createElement)("div", { className: "bt-menu-sep", role: "separator" }) : null, + group.map(([label, Icon, run2, danger]) => (0, import_react49.createElement)("button", { key: label, type: "button", role: "menuitem", @@ -18610,15 +18723,15 @@ function ContextMenu({ menu, roster, actions, leaving = false }) { actions.closeMenu(); void Promise.resolve(run2()).catch((error) => actions.reportError(error, "menu")); } - }, (0, import_react48.createElement)(Icon), label)) + }, (0, import_react49.createElement)(Icon), label)) )) ); } function AgentMenu({ menu, roster, actions, leaving }) { - const ref = (0, import_react48.useRef)(null); - const [place, setPlace] = (0, import_react48.useState)({ left: menu.x, top: menu.y }); + const ref = (0, import_react49.useRef)(null); + const [place, setPlace] = (0, import_react49.useState)({ left: menu.x, top: menu.y }); const tick = useViewport(); - (0, import_react48.useLayoutEffect)(() => { + (0, import_react49.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)) }); @@ -18640,14 +18753,14 @@ function AgentMenu({ menu, roster, actions, leaving }) { [t("Archive"), TrashIcon, () => actions.archiveAgentSession(agent.id, menu.id), true] ] ]; - return (0, import_react48.createElement)( + return (0, import_react49.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_react48.createElement)( - import_react48.Fragment, + groups.map((group, index) => (0, import_react49.createElement)( + import_react49.Fragment, { key: index }, - index > 0 ? (0, import_react48.createElement)("div", { className: "bt-menu-sep", role: "separator" }) : null, - group.map(([label, Icon, run2, danger]) => (0, import_react48.createElement)("button", { + index > 0 ? (0, import_react49.createElement)("div", { className: "bt-menu-sep", role: "separator" }) : null, + group.map(([label, Icon, run2, danger]) => (0, import_react49.createElement)("button", { key: label, type: "button", role: "menuitem", @@ -18656,13 +18769,13 @@ function AgentMenu({ menu, roster, actions, leaving }) { actions.closeMenu(); void Promise.resolve(run2()).catch((error) => console.warn("[ds-bot]", error)); } - }, (0, import_react48.createElement)(Icon), label)) + }, (0, import_react49.createElement)(Icon), label)) )) ); } // src/client/member-status.js -var import_react49 = require("react"); +var import_react50 = require("react"); var NO_WORK = { bots: {}, rooms: {}, approvals: [] }; var FACES_MAX2 = 3; var DOCK_EXIT_MS = 160; @@ -18723,15 +18836,15 @@ function dockModel(sessionId, roster, work) { }; } function Face({ bot, ask, state }) { - return (0, import_react49.createElement)( + return (0, import_react50.createElement)( "span", { className: "bt-mw-face", "data-ask": ask || void 0 }, - (0, import_react49.createElement)(BotMark, { bot, size: 20, state: ask ? "alert" : state }) + (0, import_react50.createElement)(BotMark, { bot, size: 20, state: ask ? "alert" : state }) ); } function useFitWidth(inner, key) { - const [width, setWidth] = (0, import_react49.useState)(null); - (0, import_react49.useLayoutEffect)(() => { + const [width, setWidth] = (0, import_react50.useState)(null); + (0, import_react50.useLayoutEffect)(() => { setWidth(key && inner.current ? inner.current.offsetWidth : null); }, [key]); return width; @@ -18742,91 +18855,91 @@ 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_react49.useRef)(null); + const inner = (0, import_react50.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_react49.createElement)( + return (0, import_react50.createElement)( "div", { className: "bt-mw-dock", "data-leaving": leaving || void 0 }, - (0, import_react49.createElement)( + (0, import_react50.createElement)( "button", { type: "button", className: "bt-mw-pill", "aria-label": label, onClick: open, disabled: leaving, style: width ? { width } : void 0 }, - (0, import_react49.createElement)( + (0, import_react50.createElement)( "span", { ref: inner, className: "bt-mw-pill-in" }, - (0, import_react49.createElement)("span", { className: "bt-mw-faces", "aria-hidden": true }, faces.map((face) => (0, import_react49.createElement)(Face, { key: face.id, ...face }))), - (0, import_react49.createElement)( + (0, import_react50.createElement)("span", { className: "bt-mw-faces", "aria-hidden": true }, faces.map((face) => (0, import_react50.createElement)(Face, { key: face.id, ...face }))), + (0, import_react50.createElement)( "span", { key: label, className: "bt-mw-label", "aria-hidden": true }, - model.waiting ? (0, import_react49.createElement)("span", { className: "bt-mw-ask" }, model.waiting) : null, - model.waiting && model.doing ? (0, import_react49.createElement)("span", { className: "bt-mw-dot" }, "·") : null, - model.doing ? (0, import_react49.createElement)("span", { className: "bt-mw-doing" }, (0, import_react49.createElement)(Shimmer, null, model.doing)) : null + model.waiting ? (0, import_react50.createElement)("span", { className: "bt-mw-ask" }, model.waiting) : null, + model.waiting && model.doing ? (0, import_react50.createElement)("span", { className: "bt-mw-dot" }, "·") : null, + model.doing ? (0, import_react50.createElement)("span", { className: "bt-mw-doing" }, (0, import_react50.createElement)(Shimmer, null, model.doing)) : null ) ) ) ); } -var stateLine = (className, at, ...what) => (0, import_react49.createElement)( +var stateLine = (className, at, ...what) => (0, import_react50.createElement)( "span", { className }, - (0, import_react49.createElement)("span", { className: "bt-member-what" }, ...what), - typeof at === "number" ? (0, import_react49.createElement)(Elapsed, { at, className: "bt-member-time" }) : null + (0, import_react50.createElement)("span", { className: "bt-member-what" }, ...what), + typeof at === "number" ? (0, import_react50.createElement)(Elapsed, { at, className: "bt-member-time" }) : null ); function ApprovalCard({ approval, bot, actions }) { - const [busy, setBusy] = (0, import_react49.useState)(false); + const [busy, setBusy] = (0, import_react50.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_react49.createElement)( + return (0, import_react50.createElement)( "div", { className: "bt-mw-card", role: "group", "aria-label": t("{name} is waiting for your approval", { name: bot.name }) }, - (0, import_react49.createElement)("div", { className: "bt-mw-tool" }, approval.tool), - approval.detail?.text ? (0, import_react49.createElement)("div", { className: "bt-mw-text" }, approval.detail.text) : null, - approval.reason ? (0, import_react49.createElement)("div", { className: "bt-mw-reason" }, approval.reason) : null, - approval.detail?.code ? (0, import_react49.createElement)("code", { className: "bt-mw-code", title: approval.detail.code }, approval.detail.code) : null, - approval.answerable ? (0, import_react49.createElement)( + (0, import_react50.createElement)("div", { className: "bt-mw-tool" }, approval.tool), + approval.detail?.text ? (0, import_react50.createElement)("div", { className: "bt-mw-text" }, approval.detail.text) : null, + approval.reason ? (0, import_react50.createElement)("div", { className: "bt-mw-reason" }, approval.reason) : null, + approval.detail?.code ? (0, import_react50.createElement)("code", { className: "bt-mw-code", title: approval.detail.code }, approval.detail.code) : null, + approval.answerable ? (0, import_react50.createElement)( "div", { className: "bt-mw-actions" }, - (0, import_react49.createElement)("button", { type: "button", className: "bt-q-btn", disabled: busy, onClick: () => answer("reject") }, t("Reject")), - (0, import_react49.createElement)("button", { type: "button", className: "bt-q-submit", disabled: busy, onClick: () => answer("allow") }, t("Allow once")) - ) : (0, import_react49.createElement)( + (0, import_react50.createElement)("button", { type: "button", className: "bt-q-btn", disabled: busy, onClick: () => answer("reject") }, t("Reject")), + (0, import_react50.createElement)("button", { type: "button", className: "bt-q-submit", disabled: busy, onClick: () => answer("allow") }, t("Allow once")) + ) : (0, import_react50.createElement)( "div", { className: "bt-mw-actions" }, - (0, import_react49.createElement)("button", { type: "button", className: "bt-q-btn", onClick: () => actions.openSession(bot.id) }, t("Open {name}'s chat", { name: bot.name })) + (0, import_react50.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_react49.createElement)(Shimmer, null, `${workPhrase(entry.doing)}…`)); + return stateLine("bt-member-state", entry.doing.since, (0, import_react50.createElement)(Shimmer, null, `${workPhrase(entry.doing)}…`)); } function StopMemberWork({ entry, bot, room: room2, actions }) { - const [stopping, setStopping] = (0, import_react49.useState)(false); + const [stopping, setStopping] = (0, import_react50.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_react49.createElement)("button", { type: "button", className: "bt-member-stop", disabled: stopping, "aria-label": `${t("Stop")} · ${bot.name}`, onClick: stop }, t("Stop")); + return (0, import_react50.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_react49.useState)(false); + const [stopping, setStopping] = (0, import_react50.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_react49.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_react50.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_react49.createElement)("div", { className: "bt-member-cards" }, entry.approvals.map((approval) => (0, import_react49.createElement)(ApprovalCard, { key: approval.id, approval, bot, actions }))); + return (0, import_react50.createElement)("div", { className: "bt-member-cards" }, entry.approvals.map((approval) => (0, import_react50.createElement)(ApprovalCard, { key: approval.id, approval, bot, actions }))); } function useMemberWork(room2, useWork) { const work = useWork?.((value) => value) ?? NO_WORK; @@ -18890,7 +19003,7 @@ body[data-ds-dark-theme] .bt-member-state.bt-mw-ask{color:#f0b84a} `; // src/client/details-drawer.js -var import_react50 = require("react"); +var import_react51 = 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 ""; @@ -18915,17 +19028,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_react50.createElement)( + return (0, import_react51.createElement)( "div", { className: "bt-drawer-permission" }, - (0, import_react50.createElement)("div", { className: "bt-section-title" }, t("Permissions")), + (0, import_react51.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_react50.createElement)(PermissionPicker, { catalog, saved: bot.permission ?? catalog.defaultPreset, repick: bot.permission === void 0, onPick: (permission) => run2(actions.updateBot(bot.id, { permission })) }) + (0, import_react51.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_react50.useState)(null); - (0, import_react50.useEffect)(() => { + const [values, setValues] = (0, import_react51.useState)(null); + (0, import_react51.useEffect)(() => { if (!actions.runStats) return void 0; let current = true; actions.runStats(bot.id).then( @@ -18942,56 +19055,56 @@ function RunStats({ bot, part, running, actions }) { }, [bot.id, part, running]); const shown = runStatsOf(values); if (shown.length === 0) return null; - return (0, import_react50.createElement)( + return (0, import_react51.createElement)( "div", { className: "bt-run-stats" }, - shown.map((entry, index) => (0, import_react50.createElement)( - import_react50.Fragment, + shown.map((entry, index) => (0, import_react51.createElement)( + import_react51.Fragment, { key: entry.key }, - index > 0 ? (0, import_react50.createElement)("span", { className: "bt-run-sep", "aria-hidden": true }, "·") : null, - (0, import_react50.createElement)("span", { title: entry.title }, entry.text) + index > 0 ? (0, import_react51.createElement)("span", { className: "bt-run-sep", "aria-hidden": true }, "·") : null, + (0, import_react51.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_react50.useEffect)(() => { + (0, import_react51.useEffect)(() => { actions.browserEnsure?.(bot.id); }, [bot.id]); if (roster.browser !== true || !actions.browserShow) { - return (0, import_react50.createElement)("div", { className: "bt-muted" }, t("The browser is in DSH Desktop and the DS Bot app.")); + return (0, import_react51.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_react50.createElement)( + return (0, import_react51.createElement)( "div", { className: "bt-browser-empty-mark" }, - (0, import_react50.createElement)(BotMark, { bot, size: 40, state: "idle", live: true }), - (0, import_react50.createElement)("div", { className: "bt-browser-empty-title" }, t("{name}'s browser", { name: bot.name })), - (0, import_react50.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_react50.createElement)("button", { type: "button", className: "bt-browser-retry", onClick: () => actions.openBrowser(sessionId) }, t("Open browser")) + (0, import_react51.createElement)(BotMark, { bot, size: 40, state: "idle", live: true }), + (0, import_react51.createElement)("div", { className: "bt-browser-empty-title" }, t("{name}'s browser", { name: bot.name })), + (0, import_react51.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_react51.createElement)("button", { type: "button", className: "bt-browser-retry", onClick: () => actions.openBrowser(sessionId) }, t("Open browser")) ); } - return (0, import_react50.createElement)( + return (0, import_react51.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_react50.createElement)( + return (0, import_react51.createElement)( "div", { key: tabId, className: "bt-bcard", "data-active": state.active === tabId || void 0, style: { animationDelay: `${index * 30}ms` } }, - (0, import_react50.createElement)( + (0, import_react51.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_react50.createElement)( + page.excerpt ? (0, import_react51.createElement)( "span", { className: "bt-bcard-preview" }, - (0, import_react50.createElement)("span", { className: "bt-bcard-ptitle" }, label), - (0, import_react50.createElement)("span", { className: "bt-bcard-excerpt" }, page.excerpt) - ) : (0, import_react50.createElement)("span", { className: "bt-bcard-blank" }, (0, import_react50.createElement)(GlobeIcon2), (0, import_react50.createElement)("span", null, label)) + (0, import_react51.createElement)("span", { className: "bt-bcard-ptitle" }, label), + (0, import_react51.createElement)("span", { className: "bt-bcard-excerpt" }, page.excerpt) + ) : (0, import_react51.createElement)("span", { className: "bt-bcard-blank" }, (0, import_react51.createElement)(GlobeIcon2), (0, import_react51.createElement)("span", null, label)) ), - (0, import_react50.createElement)("button", { + (0, import_react51.createElement)("button", { type: "button", className: "bt-bcard-x", "aria-label": t("Close tab"), @@ -19000,29 +19113,29 @@ function BrowserCards({ bot, sessionId, roster, actions, useBrowserTabs, useBrow void actions.browserCloseTab(bot.id, tabId); } }, "×"), - (0, import_react50.createElement)( + (0, import_react51.createElement)( "div", { className: "bt-bcard-row" }, - (0, import_react50.createElement)(Favicon, { src: page.favicon, className: "bt-bcard-fav" }), - (0, import_react50.createElement)("span", { className: "bt-bcard-title" }, label), - page.url ? (0, import_react50.createElement)("span", { className: "bt-bcard-host" }, hostOf2(page.url)) : null + (0, import_react51.createElement)(Favicon, { src: page.favicon, className: "bt-bcard-fav" }), + (0, import_react51.createElement)("span", { className: "bt-bcard-title" }, label), + page.url ? (0, import_react51.createElement)("span", { className: "bt-bcard-host" }, hostOf2(page.url)) : null ) ); }), - (0, import_react50.createElement)("button", { type: "button", className: "bt-bcard-new", style: { animationDelay: `${state.ids.length * 30}ms` }, onClick: () => actions.browserNewTab(sessionId) }, (0, import_react50.createElement)(PlusIcon), t("New tab")) + (0, import_react51.createElement)("button", { type: "button", className: "bt-bcard-new", style: { animationDelay: `${state.ids.length * 30}ms` }, onClick: () => actions.browserNewTab(sessionId) }, (0, import_react51.createElement)(PlusIcon), t("New tab")) ); } function About({ text, title = "About" }) { - const [open, setOpen] = (0, import_react50.useState)(false); + const [open, setOpen] = (0, import_react51.useState)(false); const long = text.split("\n").length > 5 || text.length > 240; - const body = (0, import_react50.useRef)(null); + const body = (0, import_react51.useRef)(null); useMorph(body, open); - return (0, import_react50.createElement)( + return (0, import_react51.createElement)( "div", null, - (0, import_react50.createElement)("div", { className: "bt-section-title" }, t(title)), - (0, import_react50.createElement)("div", { ref: body, className: "bt-about", "data-open": open || void 0 }, text), - long ? (0, import_react50.createElement)("button", { type: "button", className: "bt-more", onClick: () => setOpen((value) => !value) }, open ? t("Show less") : t("Show more")) : null + (0, import_react51.createElement)("div", { className: "bt-section-title" }, t(title)), + (0, import_react51.createElement)("div", { ref: body, className: "bt-about", "data-open": open || void 0 }, text), + long ? (0, import_react51.createElement)("button", { type: "button", className: "bt-more", onClick: () => setOpen((value) => !value) }, open ? t("Show less") : t("Show more")) : null ); } var PILE_MAX = 4; @@ -19030,57 +19143,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_react50.createElement)( + return (0, import_react51.createElement)( "span", { className: "bt-pile", "aria-hidden": true }, - shown.map((bot, index) => (0, import_react50.createElement)("span", { key: bot.id, className: "bt-pile-face", style: { animationDelay: `${index * 40}ms` } }, (0, import_react50.createElement)(BotMark, { bot, size: 44, live: true }))), - more > 0 ? (0, import_react50.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_react51.createElement)("span", { key: bot.id, className: "bt-pile-face", style: { animationDelay: `${index * 40}ms` } }, (0, import_react51.createElement)(BotMark, { bot, size: 44, live: true }))), + more > 0 ? (0, import_react51.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_react50.createElement)( + return (0, import_react51.createElement)( "div", { role: "listitem", className: "bt-member" }, - (0, import_react50.createElement)( + (0, import_react51.createElement)( "div", { className: "bt-member-row" }, - (0, import_react50.createElement)( + (0, import_react51.createElement)( "button", { type: "button", className: "bt-member-open", title: t("Open {name}'s chat", { name: member.name }), onClick: () => actions.openSession(member.id) }, - (0, import_react50.createElement)(BotMark, { bot: member, size: 32, state: markOf(entry) }), - (0, import_react50.createElement)( + (0, import_react51.createElement)(BotMark, { bot: member, size: 32, state: markOf(entry) }), + (0, import_react51.createElement)( "span", { className: "bt-member-text" }, - (0, import_react50.createElement)( + (0, import_react51.createElement)( "span", { className: "bt-member-line" }, - (0, import_react50.createElement)("span", { className: "bt-member-name" }, member.name), - room2.admin === member.id ? (0, import_react50.createElement)("span", { className: "bt-tag" }, t("Admin")) : null + (0, import_react51.createElement)("span", { className: "bt-member-name" }, member.name), + room2.admin === member.id ? (0, import_react51.createElement)("span", { className: "bt-tag" }, t("Admin")) : null ), - (0, import_react50.createElement)(MemberState, { entry, bot: member, room: room2, roster }) + (0, import_react51.createElement)(MemberState, { entry, bot: member, room: room2, roster }) ) ), - (0, import_react50.createElement)(StopMemberWork, { entry, bot: member, room: room2, actions }) + (0, import_react51.createElement)(StopMemberWork, { entry, bot: member, room: room2, actions }) ), - (0, import_react50.createElement)(MemberApprovals, { entry, bot: member, actions }) + (0, import_react51.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_react50.createElement)(About, { key: "notice", title: "Notice", text: room2.notice }) : (0, import_react50.createElement)("button", { key: "notice", type: "button", className: "bt-more", onClick: openSettings }, t("Add a notice in group settings")), - (0, import_react50.createElement)( + room2.notice ? (0, import_react51.createElement)(About, { key: "notice", title: "Notice", text: room2.notice }) : (0, import_react51.createElement)("button", { key: "notice", type: "button", className: "bt-more", onClick: openSettings }, t("Add a notice in group settings")), + (0, import_react51.createElement)( "div", { key: "members" }, - (0, import_react50.createElement)( + (0, import_react51.createElement)( "div", { className: "bt-members-head" }, - (0, import_react50.createElement)("div", { className: "bt-section-title" }, t("Members · {count}", { count: members.length })), - (0, import_react50.createElement)(StopRoomWork, { room: room2, entries: entries2, actions }) + (0, import_react51.createElement)("div", { className: "bt-section-title" }, t("Members · {count}", { count: members.length })), + (0, import_react51.createElement)(StopRoomWork, { room: room2, entries: entries2, actions }) ), - (0, import_react50.createElement)("div", { className: "bt-members", role: "list" }, members.map((member) => (0, import_react50.createElement)(MemberRow, { + (0, import_react51.createElement)("div", { className: "bt-members", role: "list" }, members.map((member) => (0, import_react51.createElement)(MemberRow, { key: member.id, member, entry: entries2.find((item) => item.id === member.id), @@ -19089,16 +19202,16 @@ function GroupOverview({ room: room2, roster, actions, usage, useWork, openSetti actions }))) ), - (0, import_react50.createElement)( + (0, import_react51.createElement)( "div", { key: "goal" }, - (0, import_react50.createElement)("div", { className: "bt-section-title" }, t("Goal")), - (0, import_react50.createElement)( + (0, import_react51.createElement)("div", { className: "bt-section-title" }, t("Goal")), + (0, import_react51.createElement)( "div", { className: "bt-kv" }, room2.goal ? [ - (0, import_react50.createElement)("span", { key: "t" }, room2.goal.title, " ", (0, import_react50.createElement)("span", { className: "bt-note" }, goalView(room2.goal, { roster })?.barLabel ?? "")), - (0, import_react50.createElement)("button", { + (0, import_react51.createElement)("span", { key: "t" }, room2.goal.title, " ", (0, import_react51.createElement)("span", { className: "bt-note" }, goalView(room2.goal, { roster })?.barLabel ?? "")), + (0, import_react51.createElement)("button", { key: "s", type: "button", className: "bt-soft bt-soft-sm", @@ -19107,7 +19220,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_react50.createElement)("button", { + ] : (0, import_react51.createElement)("button", { type: "button", className: "bt-soft bt-soft-sm", disabled: !canSetGoal(room2, roster), @@ -19116,24 +19229,24 @@ function GroupOverview({ room: room2, roster, actions, usage, useWork, openSetti }, t("Set a goal")) ) ), - (0, import_react50.createElement)( + (0, import_react51.createElement)( "div", { key: "mode" }, - (0, import_react50.createElement)("div", { className: "bt-section-title" }, t("Who answers")), - (0, import_react50.createElement)("div", { className: "bt-kv" }, (0, import_react50.createElement)("span", null, t(ROOM_MODES.find(([id]) => id === shownMode(room2, roster))?.[1] ?? "Everyone"))) + (0, import_react51.createElement)("div", { className: "bt-section-title" }, t("Who answers")), + (0, import_react51.createElement)("div", { className: "bt-kv" }, (0, import_react51.createElement)("span", null, t(ROOM_MODES.find(([id]) => id === shownMode(room2, roster))?.[1] ?? "Everyone"))) ), - room2.permission ? (0, import_react50.createElement)( + room2.permission ? (0, import_react51.createElement)( "div", { key: "permission" }, - (0, import_react50.createElement)("div", { className: "bt-section-title" }, t("Permissions")), - (0, import_react50.createElement)("div", { className: "bt-kv" }, (0, import_react50.createElement)("span", { className: presetDanger(room2.permission) ? "bt-perm-danger" : void 0 }, presetName(room2.permission, roster.permissions))) + (0, import_react51.createElement)("div", { className: "bt-section-title" }, t("Permissions")), + (0, import_react51.createElement)("div", { className: "bt-kv" }, (0, import_react51.createElement)("span", { className: presetDanger(room2.permission) ? "bt-perm-danger" : void 0 }, presetName(room2.permission, roster.permissions))) ) : null, - roster.memory === false ? null : (0, import_react50.createElement)(MemoryRow, { key: "memory", owner: { id: room2.id, name: room2.name, group: true }, actions }), - usage ? (0, import_react50.createElement)( + roster.memory === false ? null : (0, import_react51.createElement)(MemoryRow, { key: "memory", owner: { id: room2.id, name: room2.name, group: true }, actions }), + usage ? (0, import_react51.createElement)( "div", { key: "usage" }, - (0, import_react50.createElement)("div", { className: "bt-section-title" }, t("Usage")), - (0, import_react50.createElement)("div", { className: "bt-kv" }, (0, import_react50.createElement)("span", null, room2.name), (0, import_react50.createElement)("span", null, usage)) + (0, import_react51.createElement)("div", { className: "bt-section-title" }, t("Usage")), + (0, import_react51.createElement)("div", { className: "bt-kv" }, (0, import_react51.createElement)("span", null, room2.name), (0, import_react51.createElement)("span", null, usage)) ) : null ]; } @@ -19141,15 +19254,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_react50.useState)("details"); + const [tab, setTab] = (0, import_react51.useState)("details"); const room2 = roster.roomsById[sessionId]; - const [view, setView] = (0, import_react50.useState)(startTab === "settings" && (owner || room2) ? "settings" : "overview"); - const [editing, setEditing] = (0, import_react50.useState)(Boolean(startRenaming && (roster.byId[sessionId] || roster.roomsById[sessionId]))); - const [draftName, setDraftName] = (0, import_react50.useState)(roster.byId[sessionId]?.name ?? (roster.roomsById[sessionId]?.named ? roster.roomsById[sessionId].name : "")); - const [copied, setCopied] = (0, import_react50.useState)(false); - const [error, setError] = (0, import_react50.useState)(""); + const [view, setView] = (0, import_react51.useState)(startTab === "settings" && (owner || room2) ? "settings" : "overview"); + const [editing, setEditing] = (0, import_react51.useState)(Boolean(startRenaming && (roster.byId[sessionId] || roster.roomsById[sessionId]))); + const [draftName, setDraftName] = (0, import_react51.useState)(roster.byId[sessionId]?.name ?? (roster.roomsById[sessionId]?.named ? roster.roomsById[sessionId].name : "")); + const [copied, setCopied] = (0, import_react51.useState)(false); + const [error, setError] = (0, import_react51.useState)(""); const glide = useGlide(tab); - const last = (0, import_react50.useRef)({ view, tab, move: void 0 }); + const last = (0, import_react51.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; @@ -19174,21 +19287,21 @@ function DetailsDrawer({ sessionId, startRenaming, startTab, hasStrip, roster, a setTimeout(() => setCopied(false), 1600); }); }; - const errorLine = error ? (0, import_react50.createElement)("div", { className: "bt-error", role: "alert", style: { padding: 0 } }, error) : null; + const errorLine = error ? (0, import_react51.createElement)("div", { className: "bt-error", role: "alert", style: { padding: 0 } }, error) : null; if ((bot || room2) && view === "settings") { return [ - (0, import_react50.createElement)( + (0, import_react51.createElement)( "div", { key: "head", className: "bt-subhead", "data-move": move }, - (0, import_react50.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Back to details"), onClick: () => setView("overview") }, (0, import_react50.createElement)(ChevronLeftIcon)), - (0, import_react50.createElement)("span", { className: "bt-subhead-title" }, bot ? t("Settings") : t("Group settings")), - hasStrip ? null : (0, import_react50.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Close details"), onClick: close }, (0, import_react50.createElement)(CloseIcon)) + (0, import_react51.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Back to details"), onClick: () => setView("overview") }, (0, import_react51.createElement)(ChevronLeftIcon)), + (0, import_react51.createElement)("span", { className: "bt-subhead-title" }, bot ? t("Settings") : t("Group settings")), + hasStrip ? null : (0, import_react51.createElement)("button", { type: "button", className: "bt-icon-btn", "aria-label": t("Close details"), onClick: close }, (0, import_react51.createElement)(CloseIcon)) ), - (0, import_react50.createElement)( + (0, import_react51.createElement)( "div", { key: "set-body", className: "bt-drawer-body bt-set-body", "data-move": move }, errorLine, - bot ? (0, import_react50.createElement)(BotSettingsForm, { bot, roster, actions, run: run2 }) : (0, import_react50.createElement)(GroupSettingsForm, { room: room2, roster, actions, run: run2, onDeleted: close }) + bot ? (0, import_react51.createElement)(BotSettingsForm, { bot, roster, actions, run: run2 }) : (0, import_react51.createElement)(GroupSettingsForm, { room: room2, roster, actions, run: run2, onDeleted: close }) ) ]; } @@ -19199,18 +19312,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_react50.createElement)( + const top = (0, import_react51.createElement)( "div", { className: "bt-drawer-top", "data-move": side }, - bot || room2 ? (0, import_react50.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_react50.createElement)(GearIcon)) : null, - more.length > 0 ? (0, import_react50.createElement)("span", { "data-info-row": "more" }, (0, import_react50.createElement)(PanelMenu, { items: more, className: "bt-round", "aria-label": t("More") })) : null, - bot || room2 ? (0, import_react50.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_react50.createElement)("span", { key: "copied", className: "bt-pop-in" }, "✓") : (0, import_react50.createElement)(ShareIcon)) : null, - hasStrip ? null : (0, import_react50.createElement)("button", { type: "button", className: "bt-round", "aria-label": t("Close details"), onClick: close }, (0, import_react50.createElement)(CloseIcon)) + bot || room2 ? (0, import_react51.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_react51.createElement)(GearIcon)) : null, + more.length > 0 ? (0, import_react51.createElement)("span", { "data-info-row": "more" }, (0, import_react51.createElement)(PanelMenu, { items: more, className: "bt-round", "aria-label": t("More") })) : null, + bot || room2 ? (0, import_react51.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_react51.createElement)("span", { key: "copied", className: "bt-pop-in" }, "✓") : (0, import_react51.createElement)(ShareIcon)) : null, + hasStrip ? null : (0, import_react51.createElement)("button", { type: "button", className: "bt-round", "aria-label": t("Close details"), onClick: close }, (0, import_react51.createElement)(CloseIcon)) ); if (!bot && !room2) { return [ - (0, import_react50.createElement)(import_react50.Fragment, { key: "top" }, top), - (0, import_react50.createElement)("div", { key: "body", className: "bt-drawer-body" }, (0, import_react50.createElement)("div", { className: "bt-muted" }, t("This conversation is not part of your Bot team."))) + (0, import_react51.createElement)(import_react51.Fragment, { key: "top" }, top), + (0, import_react51.createElement)("div", { key: "body", className: "bt-drawer-body" }, (0, import_react51.createElement)("div", { className: "bt-muted" }, t("This conversation is not part of your Bot team."))) ]; } const current = bot?.name ?? room2.name; @@ -19224,12 +19337,12 @@ function DetailsDrawer({ sessionId, startRenaming, startTab, hasStrip, roster, a const subtitle = bot ? bot.role : roomSubtitle(room2, roster); const tabs = bot ? ["details", "browser"] : ["details"]; return [ - (0, import_react50.createElement)(import_react50.Fragment, { key: "top" }, top), - (0, import_react50.createElement)( + (0, import_react51.createElement)(import_react51.Fragment, { key: "top" }, top), + (0, import_react51.createElement)( "div", { key: "id", className: "bt-drawer-id", "data-move": side }, - bot ? (0, import_react50.createElement)(BotAvatar, { bot, size: 64, state: botState(running, doing, roster.questions?.[part] !== void 0), main: isMainBot, badge: false, gaze: true, pokeable: true }) : (0, import_react50.createElement)(MemberPile, { room: room2, roster }), - editing ? (0, import_react50.createElement)("input", { + bot ? (0, import_react51.createElement)(BotAvatar, { bot, size: 64, state: botState(running, doing, roster.questions?.[part] !== void 0), main: isMainBot, badge: false, gaze: true, pokeable: true }) : (0, import_react51.createElement)(MemberPile, { room: room2, roster }), + editing ? (0, import_react51.createElement)("input", { className: "bt-drawer-name-input", autoFocus: true, value: draftName, @@ -19244,50 +19357,51 @@ function DetailsDrawer({ sessionId, startRenaming, startTab, hasStrip, roster, a setEditing(false); } } - }) : (0, import_react50.createElement)("button", { type: "button", className: "bt-drawer-name", "aria-label": t("Rename {name}", { name: current }), title: t("Rename"), onClick: () => { + }) : (0, import_react51.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_react50.createElement)("span", { className: "bt-drawer-role" }, subtitle) : null + subtitle ? (0, import_react51.createElement)("span", { className: "bt-drawer-role" }, subtitle) : null ), - tabs.length > 1 ? (0, import_react50.createElement)( + tabs.length > 1 ? (0, import_react51.createElement)( "div", { key: "tabs", ref: glide.box, className: "bt-tabs", role: "tablist", "data-move": side }, - (0, import_react50.createElement)("span", { ref: glide.thumb, className: "bt-thumb", "aria-hidden": true }), - tabs.map((key) => (0, import_react50.createElement)("button", { key, type: "button", role: "tab", className: "bt-tab", "aria-selected": tab === key, onClick: () => setTab(key) }, t(TAB_LABELS[key]))) + (0, import_react51.createElement)("span", { ref: glide.thumb, className: "bt-thumb", "aria-hidden": true }), + tabs.map((key) => (0, import_react51.createElement)("button", { key, type: "button", role: "tab", className: "bt-tab", "aria-selected": tab === key, onClick: () => setTab(key) }, t(TAB_LABELS[key]))) ) : null, - (0, import_react50.createElement)( + (0, import_react51.createElement)( "div", { key: `body:${tab}`, className: "bt-drawer-body", "data-move": move }, errorLine, - room2 && tab === "details" ? (0, import_react50.createElement)(GroupOverview, { room: room2, roster, actions, usage, useWork, openSettings: () => setView("settings") }) : null, + room2 && tab === "details" ? (0, import_react51.createElement)(GroupOverview, { room: room2, roster, actions, usage, useWork, openSettings: () => setView("settings") }) : null, bot && tab === "details" ? [ - (0, import_react50.createElement)(RunStats, { key: "stats", bot, part, running, actions }), - (0, import_react50.createElement)( + (0, import_react51.createElement)(RunStats, { key: "stats", bot, part, running, actions }), + (0, import_react51.createElement)( "div", { key: "model", className: "bt-drawer-model" }, - (0, import_react50.createElement)("div", { className: "bt-section-title" }, t("Model")), - (0, import_react50.createElement)(ModelMenu, { bot, roster, actions, run: run2, wide: true }), - modelOf(bot, roster) ? null : (0, import_react50.createElement)("div", { className: "bt-note" }, t("Pick a model and {name} can start.", { name: bot.name })) + (0, import_react51.createElement)("div", { className: "bt-section-title" }, t("Model")), + (0, import_react51.createElement)(ModelMenu, { bot, roster, actions, run: run2, wide: true }), + modelOf(bot, roster) ? null : (0, import_react51.createElement)("div", { className: "bt-note" }, t("Pick a model and {name} can start.", { name: bot.name })) ), - (0, import_react50.createElement)(PermissionRow, { key: "permission", bot, roster, actions, run: run2 }), - (0, import_react50.createElement)( + (0, import_react51.createElement)(PermissionRow, { key: "permission", bot, roster, actions, run: run2 }), + (0, import_react51.createElement)( "div", { key: "folder", className: "bt-drawer-model" }, - (0, import_react50.createElement)("div", { className: "bt-section-title" }, t("Working folder")), - (0, import_react50.createElement)(FolderMenu, { value: bot.workDir, actions, run: run2, wide: true, onPick: (workDir) => run2(actions.updateBot(bot.id, { workDir })) }) + (0, import_react51.createElement)("div", { className: "bt-section-title" }, t("Working folder")), + (0, import_react51.createElement)(FolderMenu, { value: bot.workDir, actions, run: run2, wide: true, onPick: (workDir) => run2(actions.updateBot(bot.id, { workDir })) }) ), - bot.instructions ? (0, import_react50.createElement)(About, { key: "about", text: bot.instructions }) : (0, import_react50.createElement)("button", { key: "about", type: "button", className: "bt-more", onClick: () => setView("settings") }, t("Add instructions in Bot settings")), - roster.memory === false ? null : (0, import_react50.createElement)(MemoryRow, { key: "memory", owner: { id: bot.id, name: bot.name }, actions }), - usage ? (0, import_react50.createElement)( + bot.instructions ? (0, import_react51.createElement)(About, { key: "about", text: bot.instructions }) : (0, import_react51.createElement)("button", { key: "about", type: "button", className: "bt-more", onClick: () => setView("settings") }, t("Add instructions in Bot settings")), + roster.memory === false ? null : (0, import_react51.createElement)(MemoryRow, { key: "memory", owner: { id: bot.id, name: bot.name }, actions }), + usage ? (0, import_react51.createElement)( "div", { key: "usage" }, - (0, import_react50.createElement)("div", { className: "bt-section-title" }, t("Usage")), - (0, import_react50.createElement)("div", { className: "bt-kv" }, (0, import_react50.createElement)("span", null, bot.name), (0, import_react50.createElement)("span", null, usage)) + (0, import_react51.createElement)("div", { className: "bt-section-title" }, t("Usage")), + (0, import_react51.createElement)("div", { className: "bt-kv" }, (0, import_react51.createElement)("span", null, bot.name), (0, import_react51.createElement)("span", null, usage)) ) : null, - (0, import_react50.createElement)(ScheduleSummary, { key: "routines", bot, actions }) + (0, import_react51.createElement)(ScheduleSummary, { key: "routines", bot, actions }), + (0, import_react51.createElement)(OperatorTasks, { key: "operator-tasks", bot, roster }) ] : null, - bot && tab === "browser" ? (0, import_react50.createElement)(BrowserCards, { bot, sessionId, roster, actions, useBrowserTabs, useBrowserPages }) : null + bot && tab === "browser" ? (0, import_react51.createElement)(BrowserCards, { bot, sessionId, roster, actions, useBrowserTabs, useBrowserPages }) : null ) ]; } @@ -19298,7 +19412,7 @@ function rectsOverlap(a, b) { } // src/client/browser-pane.js -var import_react51 = require("react"); +var import_react52 = require("react"); var import_react_dom8 = require("react-dom"); var PANEL_LINGER_MS = 300; var WIDTH_KEY = STORAGE.browserWidth; @@ -19312,10 +19426,10 @@ var EMPTY_TABS2 = { ids: [], active: null }; var SPRING_LEAD2 = springEasing(576, 39.4); var SPRING_TRAIL2 = springEasing(144, 19.7); var icon = (paths) => function BrowserIcon() { - return (0, import_react51.createElement)( + return (0, import_react52.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_react51.createElement)("path", { key: index, d })) + paths.map((d, index) => (0, import_react52.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"]); @@ -19330,9 +19444,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_react51.useState)(null); - if (!src || failed === src) return (0, import_react51.createElement)("span", { className: `${className} bt-ptab-globe` }, (0, import_react51.createElement)(GlobeIcon2)); - return (0, import_react51.createElement)("img", { className, src, alt: "", "aria-hidden": true, onError: () => setFailed(src) }); + const [failed, setFailed] = (0, import_react52.useState)(null); + if (!src || failed === src) return (0, import_react52.createElement)("span", { className: `${className} bt-ptab-globe` }, (0, import_react52.createElement)(GlobeIcon2)); + return (0, import_react52.createElement)("img", { className, src, alt: "", "aria-hidden": true, onError: () => setFailed(src) }); } var savedWidth = () => { try { @@ -19348,9 +19462,9 @@ 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_react51.useState)(false); - const wrap = (0, import_react51.useRef)(null); - (0, import_react51.useEffect)(() => { + const [open, setOpen] = (0, import_react52.useState)(false); + const wrap = (0, import_react52.useRef)(null); + (0, import_react52.useEffect)(() => { if (!open) return void 0; const onDown = (event) => { if (wrap.current && !wrap.current.contains(event.target)) setOpen(false); @@ -19368,10 +19482,10 @@ function PanelMenu({ items, className, "aria-label": label }) { }; }, [open]); if (items.length === 0) return null; - return (0, import_react51.createElement)( + return (0, import_react52.createElement)( "span", { className: "bt-pmenu", ref: wrap }, - (0, import_react51.createElement)("button", { + (0, import_react52.createElement)("button", { type: "button", className, "aria-label": label, @@ -19379,11 +19493,11 @@ function PanelMenu({ items, className, "aria-label": label }) { "aria-haspopup": "menu", "aria-expanded": open, onClick: () => setOpen((value) => !value) - }, (0, import_react51.createElement)(DotsIcon)), - open ? (0, import_react51.createElement)( + }, (0, import_react52.createElement)(DotsIcon)), + open ? (0, import_react52.createElement)( "div", { className: "bt-pmenu-pop", role: "menu" }, - items.map((item, index) => item.sep ? (0, import_react51.createElement)("span", { key: `sep-${index}`, className: "bt-pmenu-sep", role: "separator" }) : (0, import_react51.createElement)("button", { + items.map((item, index) => item.sep ? (0, import_react52.createElement)("span", { key: `sep-${index}`, className: "bt-pmenu-sep", role: "separator" }) : (0, import_react52.createElement)("button", { key: item.key, type: "button", role: "menuitem", @@ -19392,7 +19506,7 @@ function PanelMenu({ items, className, "aria-label": label }) { setOpen(false); item.onPick(); } - }, (0, import_react51.createElement)(item.icon), (0, import_react51.createElement)("span", null, item.label))) + }, (0, import_react52.createElement)(item.icon), (0, import_react52.createElement)("span", null, item.label))) ) : null ); } @@ -19418,12 +19532,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_react51.useRef)(null); - const ind = (0, import_react51.useRef)(null); - const spot = (0, import_react51.useRef)(null); - const under = (0, import_react51.useRef)(null); - const watcher = (0, import_react51.useRef)(null); - (0, import_react51.useLayoutEffect)(() => { + const wrap = (0, import_react52.useRef)(null); + const ind = (0, import_react52.useRef)(null); + const spot = (0, import_react52.useRef)(null); + const under = (0, import_react52.useRef)(null); + const watcher = (0, import_react52.useRef)(null); + (0, import_react52.useLayoutEffect)(() => { const box = wrap.current; const capsule = ind.current; if (!box || !capsule) return void 0; @@ -19456,7 +19570,7 @@ function PanelStrip({ bot, subject, view, ids, active, sides, side, canBrowse, r trail.cancel(); }; }); - (0, import_react51.useEffect)(() => { + (0, import_react52.useEffect)(() => { const box = wrap.current; if (!box) return void 0; const observer = new ResizeObserver(() => { @@ -19480,13 +19594,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_react51.createElement)( + return (0, import_react52.createElement)( "div", { className: "bt-ptabs", role: "tablist", "aria-label": t("Panel tabs") }, - (0, import_react51.createElement)( + (0, import_react52.createElement)( "div", { className: "bt-ptabs-in", ref: wrap }, - (0, import_react51.createElement)( + (0, import_react52.createElement)( "button", { type: "button", @@ -19496,13 +19610,13 @@ function PanelStrip({ bot, subject, view, ids, active, sides, side, canBrowse, r title: bot.name, onClick: () => onView("details") }, - (0, import_react51.createElement)(BotMark, { bot, size: 20, state: reading ? "searching" : "idle" }), - view === "details" ? (0, import_react51.createElement)("span", { className: "bt-ptab-name" }, bot.name) : null + (0, import_react52.createElement)(BotMark, { bot, size: 20, state: reading ? "searching" : "idle" }), + view === "details" ? (0, import_react52.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_react51.createElement)( + return (0, import_react52.createElement)( "button", { key: tabId, @@ -19523,9 +19637,9 @@ function PanelStrip({ bot, subject, view, ids, active, sides, side, canBrowse, r } } }, - (0, import_react51.createElement)(Favicon, { src: page.favicon, className: "bt-ptab-fav" }), - (0, import_react51.createElement)("span", { className: "bt-ptab-title" }, tabLabel(page)), - (0, import_react51.createElement)("span", { + (0, import_react52.createElement)(Favicon, { src: page.favicon, className: "bt-ptab-fav" }), + (0, import_react52.createElement)("span", { className: "bt-ptab-title" }, tabLabel(page)), + (0, import_react52.createElement)("span", { className: "bt-ptab-x", role: "button", "aria-label": t("Close tab"), @@ -19539,7 +19653,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_react51.createElement)( + return (0, import_react52.createElement)( "button", { key: chat.id, @@ -19557,9 +19671,9 @@ function PanelStrip({ bot, subject, view, ids, active, sides, side, canBrowse, r } } }, - (0, import_react51.createElement)("span", { className: "bt-ptab-globe", "aria-hidden": true }, (0, import_react51.createElement)(SideIcon)), - (0, import_react51.createElement)("span", { className: "bt-ptab-title" }, sideTitle(chat)), - (0, import_react51.createElement)("span", { + (0, import_react52.createElement)("span", { className: "bt-ptab-globe", "aria-hidden": true }, (0, import_react52.createElement)(SideIcon)), + (0, import_react52.createElement)("span", { className: "bt-ptab-title" }, sideTitle(chat)), + (0, import_react52.createElement)("span", { className: "bt-ptab-x", role: "button", "aria-label": t("Close side chat"), @@ -19571,30 +19685,30 @@ function PanelStrip({ bot, subject, view, ids, active, sides, side, canBrowse, r }, "×") ); }), - (0, import_react51.createElement)("span", { ref: ind, className: "bt-ptab-ind", "aria-hidden": true }) + (0, import_react52.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_react51.createElement)(PanelMenu, { items, className: "bt-ptab-new", "aria-label": t("More") }), - (0, import_react51.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_react51.createElement)(CloseIcon3)) + (0, import_react52.createElement)(PanelMenu, { items, className: "bt-ptab-new", "aria-label": t("More") }), + (0, import_react52.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_react52.createElement)(CloseIcon3)) ); } function BrowserView({ bot, tabId, leaving, landed, actions, useBrowserPages, hold }) { const page = useBrowserPages((pages) => pages[tabId ?? ""]) ?? EMPTY_PAGE; - const frame = (0, import_react51.useRef)(null); - const input = (0, import_react51.useRef)(null); - const [draft, setDraft] = (0, import_react51.useState)(null); - const [covered, setCovered] = (0, import_react51.useState)(false); + const frame = (0, import_react52.useRef)(null); + const input = (0, import_react52.useRef)(null); + const [draft, setDraft] = (0, import_react52.useState)(null); + const [covered, setCovered] = (0, import_react52.useState)(false); const imports = actions.browserImport; - const [flow, setFlow] = (0, import_react51.useState)(null); - const flowRef = (0, import_react51.useRef)(null); - const [sources, setSources] = (0, import_react51.useState)(null); - const [busy, setBusy] = (0, import_react51.useState)(false); + const [flow, setFlow] = (0, import_react52.useState)(null); + const flowRef = (0, import_react52.useRef)(null); + const [sources, setSources] = (0, import_react52.useState)(null); + const [busy, setBusy] = (0, import_react52.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_react51.useEffect)(() => { + (0, import_react52.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())); @@ -19609,7 +19723,7 @@ function BrowserView({ bot, tabId, leaving, landed, actions, useBrowserPages, ho window.removeEventListener("resize", update); }; }, []); - (0, import_react51.useEffect)(() => { + (0, import_react52.useEffect)(() => { setFlowTracked(null); return () => { const id = typeof flowRef.current === "object" && flowRef.current !== null ? flowRef.current.id : null; @@ -19653,7 +19767,7 @@ function BrowserView({ bot, tabId, leaving, landed, actions, useBrowserPages, ho if (id) void imports?.cancel(id).catch(() => { }); }; - (0, import_react51.useLayoutEffect)(() => { + (0, import_react52.useLayoutEffect)(() => { const element = frame.current; if (!element || leaving || !tabId) { void actions.browserShow(null); @@ -19679,7 +19793,7 @@ function BrowserView({ bot, tabId, leaving, landed, actions, useBrowserPages, ho window.removeEventListener("resize", schedule); }; }, [tabId, showGuest, leaving]); - (0, import_react51.useEffect)(() => { + (0, import_react52.useEffect)(() => { setDraft(null); if (landed && !page.url) input.current?.focus(); }, [tabId, landed]); @@ -19695,38 +19809,38 @@ function BrowserView({ bot, tabId, leaving, landed, actions, useBrowserPages, ho }; const editing = draft !== null; const secure = /^https:/i.test(page.url); - return (0, import_react51.createElement)( + return (0, import_react52.createElement)( "div", { className: "bt-panel-view bt-panel-browser", "aria-label": t("{name}'s browser", { name: bot.name }) }, - actions.browserTakeover ? (0, import_react51.createElement)( + actions.browserTakeover ? (0, import_react52.createElement)( "div", { className: "bt-browser-takeover", "data-held": hold?.by === "user" || void 0 }, - (0, import_react51.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_react51.createElement)("button", { type: "button", onClick: () => void actions.browserGiveBack(bot.id) }, t("Give back")) : (0, import_react51.createElement)( + (0, import_react52.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_react52.createElement)("button", { type: "button", onClick: () => void actions.browserGiveBack(bot.id) }, t("Give back")) : (0, import_react52.createElement)( "span", { className: "bt-browser-takeover-actions" }, - (0, import_react51.createElement)("button", { type: "button", onClick: () => void actions.browserTakeover(bot.id) }, t("Take over")), - (0, import_react51.createElement)("button", { type: "button", onClick: () => void actions.browserStop(bot.id) }, t("Stop")) + (0, import_react52.createElement)("button", { type: "button", onClick: () => void actions.browserTakeover(bot.id) }, t("Take over")), + (0, import_react52.createElement)("button", { type: "button", onClick: () => void actions.browserStop(bot.id) }, t("Stop")) ) ) : null, - (0, import_react51.createElement)( + (0, import_react52.createElement)( "div", { className: "bt-browser-bar" }, - (0, import_react51.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_react51.createElement)(BackIcon)), - (0, import_react51.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_react51.createElement)(ForwardIcon)), - (0, import_react51.createElement)("button", { + (0, import_react52.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_react52.createElement)(BackIcon)), + (0, import_react52.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_react52.createElement)(ForwardIcon)), + (0, import_react52.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_react51.createElement)(page.loading ? StopIcon : ReloadIcon)), - (0, import_react51.createElement)( + }, (0, import_react52.createElement)(page.loading ? StopIcon : ReloadIcon)), + (0, import_react52.createElement)( "form", { className: "bt-browser-address", onSubmit: go, "data-editing": editing || void 0 }, - (0, import_react51.createElement)("span", { className: "bt-browser-scheme", "aria-hidden": true }, (0, import_react51.createElement)(secure && !editing ? LockIcon2 : GlobeIcon2)), - (0, import_react51.createElement)("input", { + (0, import_react52.createElement)("span", { className: "bt-browser-scheme", "aria-hidden": true }, (0, import_react52.createElement)(secure && !editing ? LockIcon2 : GlobeIcon2)), + (0, import_react52.createElement)("input", { ref: input, type: "text", spellCheck: false, @@ -19750,14 +19864,14 @@ function BrowserView({ bot, tabId, leaving, landed, actions, useBrowserPages, ho } }) ), - (0, import_react51.createElement)("button", { + (0, import_react52.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_react51.createElement)(PlusTabIcon)), - imports ? (0, import_react51.createElement)("button", { + }, (0, import_react52.createElement)(PlusTabIcon)), + imports ? (0, import_react52.createElement)("button", { type: "button", className: "bt-icon-btn bt-import-btn", "aria-label": t("Import cookies"), @@ -19768,29 +19882,29 @@ function BrowserView({ bot, tabId, leaving, landed, actions, useBrowserPages, ho if (flow === "menu") setFlowTracked(null); else openImport(); } - }, (0, import_react51.createElement)(ImportIcon)) : null, - page.loading ? (0, import_react51.createElement)("span", { className: "bt-browser-progress", "aria-hidden": true }) : null + }, (0, import_react52.createElement)(ImportIcon)) : null, + page.loading ? (0, import_react52.createElement)("span", { className: "bt-browser-progress", "aria-hidden": true }) : null ), - (0, import_react51.createElement)( + (0, import_react52.createElement)( "div", { ref: frame, className: "bt-browser-frame", "data-guest": showGuest || void 0 }, - flow === "menu" ? (0, import_react51.createElement)(ImportMenu, { sources, busy, onFile: pickFile, onSource: pickSource, onClose: () => setFlowTracked(null) }) : null, - typeof flow === "object" && flow !== null ? (0, import_react51.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_react51.createElement)( + flow === "menu" ? (0, import_react52.createElement)(ImportMenu, { sources, busy, onFile: pickFile, onSource: pickSource, onClose: () => setFlowTracked(null) }) : null, + typeof flow === "object" && flow !== null ? (0, import_react52.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_react52.createElement)( "div", { className: "bt-browser-empty" }, - (0, import_react51.createElement)("div", { className: "bt-browser-empty-title" }, t("This page didn’t load")), - (0, import_react51.createElement)("div", { className: "bt-browser-empty-text" }, t(page.error)), - page.url ? (0, import_react51.createElement)("button", { type: "button", className: "bt-browser-retry", onClick: () => { + (0, import_react52.createElement)("div", { className: "bt-browser-empty-title" }, t("This page didn’t load")), + (0, import_react52.createElement)("div", { className: "bt-browser-empty-text" }, t(page.error)), + page.url ? (0, import_react52.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_react51.createElement)( + ) : flow === null && !page.url ? (0, import_react52.createElement)( "div", { className: "bt-browser-empty" }, - (0, import_react51.createElement)(BotMark, { bot, size: 48, state: "idle", live: true }), - (0, import_react51.createElement)("div", { className: "bt-browser-empty-title" }, t("{name}'s browser", { name: bot.name })), - (0, import_react51.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_react51.createElement)("button", { type: "button", className: "bt-browser-retry", onClick: openImport }, t("Import cookies")) : null + (0, import_react52.createElement)(BotMark, { bot, size: 48, state: "idle", live: true }), + (0, import_react52.createElement)("div", { className: "bt-browser-empty-title" }, t("{name}'s browser", { name: bot.name })), + (0, import_react52.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_react52.createElement)("button", { type: "button", className: "bt-browser-retry", onClick: openImport }, t("Import cookies")) : null ) : null ) ); @@ -19802,25 +19916,25 @@ function importError(error) { return String(error); } function ImportMenu({ sources, busy, onFile, onSource, onClose }) { - (0, import_react51.useEffect)(() => { + (0, import_react52.useEffect)(() => { const close = (event) => { if (event.key === "Escape") onClose(); }; window.addEventListener("keydown", close); return () => window.removeEventListener("keydown", close); }, [onClose]); - return (0, import_react51.createElement)( + return (0, import_react52.createElement)( "div", { className: "bt-import-menu", role: "menu", "aria-label": t("Import cookies") }, - (0, import_react51.createElement)("div", { className: "bt-import-menu-title" }, t("Import cookies")), - (0, import_react51.createElement)( + (0, import_react52.createElement)("div", { className: "bt-import-menu-title" }, t("Import cookies")), + (0, import_react52.createElement)( "button", { type: "button", className: "bt-import-item", role: "menuitem", disabled: busy, onClick: onFile }, - (0, import_react51.createElement)(FileIcon, { className: "bt-import-item-icon" }), - (0, import_react51.createElement)("span", { className: "bt-import-item-name" }, t("From a file…")), - (0, import_react51.createElement)("span", { className: "bt-import-item-sub" }, t("cookies.txt, JSON, storageState")) + (0, import_react52.createElement)(FileIcon, { className: "bt-import-item-icon" }), + (0, import_react52.createElement)("span", { className: "bt-import-item-name" }, t("From a file…")), + (0, import_react52.createElement)("span", { className: "bt-import-item-sub" }, t("cookies.txt, JSON, storageState")) ), - sources === null ? (0, import_react51.createElement)("div", { className: "bt-import-menu-note" }, t("Loading…")) : sources.length === 0 ? (0, import_react51.createElement)("div", { className: "bt-import-menu-note" }, t("No browsers found")) : sources.map((source) => (0, import_react51.createElement)( + sources === null ? (0, import_react52.createElement)("div", { className: "bt-import-menu-note" }, t("Loading…")) : sources.length === 0 ? (0, import_react52.createElement)("div", { className: "bt-import-menu-note" }, t("No browsers found")) : sources.map((source) => (0, import_react52.createElement)( "button", { key: source.id, @@ -19830,83 +19944,83 @@ function ImportMenu({ sources, busy, onFile, onSource, onClose }) { disabled: busy, onClick: () => onSource(source) }, - (0, import_react51.createElement)(WindowIcon, { className: "bt-import-item-icon" }), - (0, import_react51.createElement)("span", { className: "bt-import-item-name" }, source.label), - (0, import_react51.createElement)("span", { className: "bt-import-item-sub" }, t("Copy of its cookies")) + (0, import_react52.createElement)(WindowIcon, { className: "bt-import-item-icon" }), + (0, import_react52.createElement)("span", { className: "bt-import-item-name" }, source.label), + (0, import_react52.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_react51.createElement)("div", { className: "bt-import-card" }, (0, import_react51.createElement)( + return (0, import_react52.createElement)("div", { className: "bt-import-card" }, (0, import_react52.createElement)( "div", { className: "bt-import-box" }, - (0, import_react51.createElement)("div", { className: "bt-import-title" }, t("{name} is running", { name: flow.source.name })), - (0, import_react51.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_react51.createElement)( + (0, import_react52.createElement)("div", { className: "bt-import-title" }, t("{name} is running", { name: flow.source.name })), + (0, import_react52.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_react52.createElement)( "div", { className: "bt-import-actions" }, - (0, import_react51.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_react51.createElement)("button", { type: "button", className: "bt-import-plain", disabled: busy, onClick: onCancel }, t("Cancel")) + (0, import_react52.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_react52.createElement)("button", { type: "button", className: "bt-import-plain", disabled: busy, onClick: onCancel }, t("Cancel")) ) )); } if (stage === "error") { - return (0, import_react51.createElement)("div", { className: "bt-import-card" }, (0, import_react51.createElement)( + return (0, import_react52.createElement)("div", { className: "bt-import-card" }, (0, import_react52.createElement)( "div", { className: "bt-import-box" }, - (0, import_react51.createElement)("div", { className: "bt-import-title" }, t("Import failed")), - (0, import_react51.createElement)("div", { className: "bt-import-text" }, flow.message), - (0, import_react51.createElement)("div", { className: "bt-import-actions" }, (0, import_react51.createElement)("button", { type: "button", className: "bt-import-plain", onClick: onCancel }, t("Close"))) + (0, import_react52.createElement)("div", { className: "bt-import-title" }, t("Import failed")), + (0, import_react52.createElement)("div", { className: "bt-import-text" }, flow.message), + (0, import_react52.createElement)("div", { className: "bt-import-actions" }, (0, import_react52.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_react51.createElement)("div", { className: "bt-import-card" }, (0, import_react51.createElement)( + return (0, import_react52.createElement)("div", { className: "bt-import-card" }, (0, import_react52.createElement)( "div", { className: "bt-import-box" }, - (0, import_react51.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_react51.createElement)("div", { className: "bt-import-sub" }, flow.label) : null, - problems.length ? (0, import_react51.createElement)( + (0, import_react52.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_react52.createElement)("div", { className: "bt-import-sub" }, flow.label) : null, + problems.length ? (0, import_react52.createElement)( "div", { className: "bt-import-list" }, - problems.slice(0, 8).map((item, index) => (0, import_react51.createElement)( + problems.slice(0, 8).map((item, index) => (0, import_react52.createElement)( "div", { key: index, className: "bt-import-line" }, - (0, import_react51.createElement)("span", { className: "bt-import-line-name" }, item.name ?? "—"), - (0, import_react51.createElement)("span", { className: "bt-import-line-reason" }, item.reason) + (0, import_react52.createElement)("span", { className: "bt-import-line-name" }, item.name ?? "—"), + (0, import_react52.createElement)("span", { className: "bt-import-line-reason" }, item.reason) )), - problems.length > 8 ? (0, import_react51.createElement)("div", { className: "bt-import-line" }, (0, import_react51.createElement)("span", { className: "bt-import-line-reason" }, t("and {count} more", { count: problems.length - 8 }))) : null + problems.length > 8 ? (0, import_react52.createElement)("div", { className: "bt-import-line" }, (0, import_react52.createElement)("span", { className: "bt-import-line-reason" }, t("and {count} more", { count: problems.length - 8 }))) : null ) : null, - (0, import_react51.createElement)( + (0, import_react52.createElement)( "div", { className: "bt-import-actions" }, - page.url ? (0, import_react51.createElement)("button", { type: "button", className: "bt-import-plain", onClick: onReload }, t("Reload the page")) : null, - (0, import_react51.createElement)("button", { type: "button", className: "bt-import-primary", onClick: onDone }, t("Done")) + page.url ? (0, import_react52.createElement)("button", { type: "button", className: "bt-import-plain", onClick: onReload }, t("Reload the page")) : null, + (0, import_react52.createElement)("button", { type: "button", className: "bt-import-primary", onClick: onDone }, t("Done")) ) )); } const { preview } = flow; - return (0, import_react51.createElement)("div", { className: "bt-import-card" }, (0, import_react51.createElement)( + return (0, import_react52.createElement)("div", { className: "bt-import-card" }, (0, import_react52.createElement)( "div", { className: "bt-import-box" }, - (0, import_react51.createElement)("div", { className: "bt-import-title" }, t("Import {count} cookies", { count: preview.cookies })), - (0, import_react51.createElement)( + (0, import_react52.createElement)("div", { className: "bt-import-title" }, t("Import {count} cookies", { count: preview.cookies })), + (0, import_react52.createElement)( "div", { className: "bt-import-sub" }, preview.source?.label ?? "", flow.restarted ? ` · ${t("the browser was restarted")}` : "" ), - preview.sites.length ? (0, import_react51.createElement)( + preview.sites.length ? (0, import_react52.createElement)( "div", { className: "bt-import-list" }, - preview.sites.map((site) => (0, import_react51.createElement)( + preview.sites.map((site) => (0, import_react52.createElement)( "div", { key: site.site, className: "bt-import-line" }, - (0, import_react51.createElement)("span", { className: "bt-import-line-name" }, site.site), - (0, import_react51.createElement)( + (0, import_react52.createElement)("span", { className: "bt-import-line-name" }, site.site), + (0, import_react52.createElement)( "span", { className: "bt-import-line-count" }, t("{count}", { count: site.cookies }), @@ -19914,35 +20028,35 @@ function ImportCard({ flow, page, busy, onApply, onCancel, onCloseAndImport, onD ) )) ) : null, - preview.skipped.length ? (0, import_react51.createElement)( + preview.skipped.length ? (0, import_react52.createElement)( "div", { className: "bt-import-list" }, - (0, import_react51.createElement)("div", { className: "bt-import-note" }, t("{count} skipped", { count: preview.skipped.length })), - preview.skipped.slice(0, 5).map((item, index) => (0, import_react51.createElement)( + (0, import_react52.createElement)("div", { className: "bt-import-note" }, t("{count} skipped", { count: preview.skipped.length })), + preview.skipped.slice(0, 5).map((item, index) => (0, import_react52.createElement)( "div", { key: index, className: "bt-import-line" }, - (0, import_react51.createElement)("span", { className: "bt-import-line-name" }, item.name ?? item.where), - (0, import_react51.createElement)("span", { className: "bt-import-line-reason" }, item.reason) + (0, import_react52.createElement)("span", { className: "bt-import-line-name" }, item.name ?? item.where), + (0, import_react52.createElement)("span", { className: "bt-import-line-reason" }, item.reason) )), - preview.skipped.length > 5 ? (0, import_react51.createElement)("div", { className: "bt-import-line" }, (0, import_react51.createElement)("span", { className: "bt-import-line-reason" }, t("and {count} more", { count: preview.skipped.length - 5 }))) : null + preview.skipped.length > 5 ? (0, import_react52.createElement)("div", { className: "bt-import-line" }, (0, import_react52.createElement)("span", { className: "bt-import-line-reason" }, t("and {count} more", { count: preview.skipped.length - 5 }))) : null ) : null, - preview.warnings.length ? (0, import_react51.createElement)( + preview.warnings.length ? (0, import_react52.createElement)( "details", { className: "bt-import-warns" }, - (0, import_react51.createElement)("summary", null, t("{count} adjusted", { count: preview.warnings.reduce((n, w) => n + w.count, 0) })), - preview.warnings.map((w, index) => (0, import_react51.createElement)( + (0, import_react52.createElement)("summary", null, t("{count} adjusted", { count: preview.warnings.reduce((n, w) => n + w.count, 0) })), + preview.warnings.map((w, index) => (0, import_react52.createElement)( "div", { key: index, className: "bt-import-line" }, - (0, import_react51.createElement)("span", { className: "bt-import-line-reason" }, `${w.count} × ${w.message}`) + (0, import_react52.createElement)("span", { className: "bt-import-line-reason" }, `${w.count} × ${w.message}`) )) ) : null, - preview.notes.includes("session-cookies") ? (0, import_react51.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_react51.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_react51.createElement)( + preview.notes.includes("session-cookies") ? (0, import_react52.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_react52.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_react52.createElement)( "div", { className: "bt-import-actions" }, - (0, import_react51.createElement)("button", { type: "button", className: "bt-import-primary", disabled: busy, onClick: onApply }, busy ? t("Importing…") : t("Import")), - (0, import_react51.createElement)("button", { type: "button", className: "bt-import-plain", disabled: busy, onClick: onCancel }, t("Cancel")) + (0, import_react52.createElement)("button", { type: "button", className: "bt-import-primary", disabled: busy, onClick: onApply }, busy ? t("Importing…") : t("Import")), + (0, import_react52.createElement)("button", { type: "button", className: "bt-import-plain", disabled: busy, onClick: onCancel }, t("Cancel")) ) )); } @@ -19956,41 +20070,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_react51.useRef)(null); - const fly = (0, import_react51.useRef)(null); - const [landed, setLanded] = (0, import_react51.useState)(false); - const [settling, setSettling] = (0, import_react51.useState)(false); - const [width, setWidth] = (0, import_react51.useState)(savedWidth); - const [dragging, setDragging] = (0, import_react51.useState)(false); - const [resizing, setResizing] = (0, import_react51.useState)(false); + const root = (0, import_react52.useRef)(null); + const fly = (0, import_react52.useRef)(null); + const [landed, setLanded] = (0, import_react52.useState)(false); + const [settling, setSettling] = (0, import_react52.useState)(false); + const [width, setWidth] = (0, import_react52.useState)(savedWidth); + const [dragging, setDragging] = (0, import_react52.useState)(false); + const [resizing, setResizing] = (0, import_react52.useState)(false); const instant = dragging || resizing; - const [reading, setReading] = (0, import_react51.useState)(false); + const [reading, setReading] = (0, import_react52.useState)(false); const panelWidth = fitWidth(width ?? (view === "browser" ? DEFAULT_WIDTH : DETAILS_WIDTH), widthRange(view, room2)); - (0, import_react51.useLayoutEffect)(() => { + (0, import_react52.useLayoutEffect)(() => { if (view === "browser" && width === null) setWidth(DEFAULT_WIDTH); }, [view, width]); - (0, import_react51.useLayoutEffect)(() => { + (0, import_react52.useLayoutEffect)(() => { chatRoom.hold(instant); }, [instant]); - const [last, setLast] = (0, import_react51.useState)({ view, width: panelWidth }); + const [last, setLast] = (0, import_react52.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_react51.useRef)(view); - (0, import_react51.useLayoutEffect)(() => { + const shownView = (0, import_react52.useRef)(view); + (0, import_react52.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_react51.useEffect)(() => () => { + (0, import_react52.useEffect)(() => () => { chatRoom.setRight(null); chatRoom.hold(false); }, []); - const mounted = (0, import_react51.useRef)(false); - (0, import_react51.useEffect)(() => { + const mounted = (0, import_react52.useRef)(false); + (0, import_react52.useEffect)(() => { if (!mounted.current) { mounted.current = true; return void 0; @@ -19999,31 +20113,31 @@ function BotPanel({ pane, leaving, room: room2, overlay, roster, actions, useSes const timer = setTimeout(() => setResizing(false), 160); return () => clearTimeout(timer); }, [room2]); - (0, import_react51.useEffect)(() => { + (0, import_react52.useEffect)(() => { if (!settling) return void 0; const timer = setTimeout(() => setSettling(false), SPRING_SHAPE.duration + 40); return () => clearTimeout(timer); }, [settling, view]); - (0, import_react51.useEffect)(() => { + (0, import_react52.useEffect)(() => { const timer = setTimeout(() => setLanded(true), 360); return () => clearTimeout(timer); }, []); - (0, import_react51.useEffect)(() => { + (0, import_react52.useEffect)(() => { if (canBrowse) actions.browserEnsure(bot.id); }, [bot?.id, canBrowse]); - (0, import_react51.useEffect)(() => { + (0, import_react52.useEffect)(() => { if (view === "browser" && (active === null || !tabState.ids.includes(active))) actions.setPanelView("details"); }, [view, active, tabState.ids.length]); - (0, import_react51.useEffect)(() => { + (0, import_react52.useEffect)(() => { if (pane.view === "side" && sideChat === void 0) actions.setPanelView("details"); }, [pane.view, sideChat]); - (0, import_react51.useEffect)(() => { + (0, import_react52.useEffect)(() => { if (view !== "browser" || leaving) void actions.browserShow?.(null); }, [view, leaving]); - (0, import_react51.useEffect)(() => () => { + (0, import_react52.useEffect)(() => () => { void actions.browserShow?.(null); }, []); - (0, import_react51.useEffect)(() => { + (0, import_react52.useEffect)(() => { if (!page.readAt || Date.now() - page.readAt > READ_FLASH_MS) return void 0; setReading(true); const timer = setTimeout(() => setReading(false), READ_FLASH_MS); @@ -20067,7 +20181,7 @@ function BotPanel({ pane, leaving, room: room2, overlay, roster, actions, useSes return actions[name](...args); }; } - (0, import_react51.useLayoutEffect)(() => { + (0, import_react52.useLayoutEffect)(() => { const move = fly.current; if (!move) return; fly.current = null; @@ -20150,7 +20264,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_react51.createElement)( + return (0, import_react52.createElement)( "aside", { ref: root, @@ -20168,15 +20282,15 @@ function BotPanel({ pane, leaving, room: room2, overlay, roster, actions, useSes if (event.target === event.currentTarget) setLanded(true); } }, - leaving || overlay ? null : (0, import_react51.createElement)("div", { className: "bt-panel-grip", role: "separator", "aria-orientation": "vertical", "aria-label": t("Resize panel"), onPointerDown: startResize }), + leaving || overlay ? null : (0, import_react52.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_dom8.createPortal)((0, import_react51.createElement)("div", { className: "bt-drag-shield", "aria-hidden": true }), document.body) : null, - hasStrip ? (0, import_react51.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_react51.createElement)(BrowserView, { key: `browser:${active}`, bot, tabId: active, leaving, landed: landed && !settling, actions, useBrowserPages, hold }) : view === "side" && sideChat ? (0, import_react51.createElement)("div", { key: `side:${sideChat.id}`, className: "bt-panel-view" }, (0, import_react51.createElement)(SideChatView, { subject: pane.id, chat: sideChat, roster, actions: panelActions })) : (0, import_react51.createElement)( + dragging ? (0, import_react_dom8.createPortal)((0, import_react52.createElement)("div", { className: "bt-drag-shield", "aria-hidden": true }), document.body) : null, + hasStrip ? (0, import_react52.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_react52.createElement)(BrowserView, { key: `browser:${active}`, bot, tabId: active, leaving, landed: landed && !settling, actions, useBrowserPages, hold }) : view === "side" && sideChat ? (0, import_react52.createElement)("div", { key: `side:${sideChat.id}`, className: "bt-panel-view" }, (0, import_react52.createElement)(SideChatView, { subject: pane.id, chat: sideChat, roster, actions: panelActions })) : (0, import_react52.createElement)( "div", { key: `details:${pane.id}:${pane.renaming ? "rename" : ""}:${pane.tab ?? ""}`, className: "bt-panel-view" }, - (0, import_react51.createElement)(DetailsDrawer, { + (0, import_react52.createElement)(DetailsDrawer, { sessionId: pane.id, startRenaming: pane.renaming, startTab: pane.tab, @@ -20318,7 +20432,7 @@ var BROWSER_CSS = ` `; // src/client/overlays.js -var import_react52 = require("react"); +var import_react53 = require("react"); var import_react_dom9 = require("react-dom"); var DIALOG_EXIT_MS = 160; var MENU_EXIT_MS3 = 120; @@ -20329,8 +20443,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_react52.useRef)(current); - (0, import_react52.useEffect)(() => { + const previous = (0, import_react53.useRef)(current); + (0, import_react53.useEffect)(() => { if (previous.current === current) return; previous.current = current; if (current) actions.followPanel?.(current); @@ -20344,8 +20458,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_react52.useState)(shown); - (0, import_react52.useEffect)(() => { + const [kept, setKept] = (0, import_react53.useState)(shown); + (0, import_react53.useEffect)(() => { if (shown) { setKept(shown); return void 0; @@ -20364,17 +20478,17 @@ function Overlays({ useRoster, useUi, useSessions, useSessionStatus, useActivity const [memory, memoryLeaving] = useLinger(ui2.memory && memoryOwner(ui2.memory) ? ui2.memory : null, DIALOG_EXIT_MS); const owner = memory ? memoryOwner(memory) : null; const [menu, menuLeaving] = useLinger(ui2.menu, MENU_EXIT_MS3); - return (0, import_react52.createElement)( - import_react52.Fragment, + return (0, import_react53.createElement)( + import_react53.Fragment, null, - pane ? (0, import_react_dom9.createPortal)((0, import_react52.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_dom9.createPortal)((0, import_react52.createElement)(NewChat, { key: ui2.newChat, mode: ui2.newChat, roster, actions }), document.body) : null, - ui2.palette ? (0, import_react_dom9.createPortal)((0, import_react52.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_dom9.createPortal)((0, import_react52.createElement)(ExchangeDialog, { pair: ui2.exchange, roster, actions }), document.body) : null, - ui2.voice ? (0, import_react_dom9.createPortal)((0, import_react52.createElement)(VoiceMode, { key: ui2.voice, sessionId: ui2.voice, roster, actions, useSessions, useSessionStatus }), document.body) : null, - menu ? (0, import_react_dom9.createPortal)((0, import_react52.createElement)(ContextMenu, { key: `${menu.kind ?? ""}:${menu.id}:${menu.x}:${menu.y}`, menu, roster, actions, leaving: menuLeaving }), document.body) : null, - settings ? (0, import_react_dom9.createPortal)((0, import_react52.createElement)(SettingsDialog, { page: settings.page, id: settings.id, roster, actions, useUpdate, leaving: settingsLeaving }), document.body) : null, - owner ? (0, import_react_dom9.createPortal)((0, import_react52.createElement)(MemoryDialog, { key: owner.id, owner, actions, leaving: memoryLeaving }), document.body) : null + pane ? (0, import_react_dom9.createPortal)((0, import_react53.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_dom9.createPortal)((0, import_react53.createElement)(NewChat, { key: ui2.newChat, mode: ui2.newChat, roster, actions }), document.body) : null, + ui2.palette ? (0, import_react_dom9.createPortal)((0, import_react53.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_dom9.createPortal)((0, import_react53.createElement)(ExchangeDialog, { pair: ui2.exchange, roster, actions }), document.body) : null, + ui2.voice ? (0, import_react_dom9.createPortal)((0, import_react53.createElement)(VoiceMode, { key: ui2.voice, sessionId: ui2.voice, roster, actions, useSessions, useSessionStatus }), document.body) : null, + menu ? (0, import_react_dom9.createPortal)((0, import_react53.createElement)(ContextMenu, { key: `${menu.kind ?? ""}:${menu.id}:${menu.x}:${menu.y}`, menu, roster, actions, leaving: menuLeaving }), document.body) : null, + settings ? (0, import_react_dom9.createPortal)((0, import_react53.createElement)(SettingsDialog, { page: settings.page, id: settings.id, roster, actions, useUpdate, leaving: settingsLeaving }), document.body) : null, + owner ? (0, import_react_dom9.createPortal)((0, import_react53.createElement)(MemoryDialog, { key: owner.id, owner, actions, leaving: memoryLeaving }), document.body) : null ); } @@ -20457,7 +20571,7 @@ function readPage(limits) { items.push(item); return { item, number: items.length, secret }; }; - const nameOf = (el, text2, secret) => collapse( + const nameOf2 = (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) => { @@ -20633,7 +20747,7 @@ ${body2 || "(no text)"} const found = itemFor(el, style); const mark = found ? `[#${found.number}]` : ""; if (tag === "input" || tag === "textarea" || tag === "select") { - if (found) found.item.name = nameOf(el, tag === "select" ? "" : el.labels?.[0] ? collapse(el.labels[0].textContent) : "", found.secret); + if (found) found.item.name = nameOf2(el, tag === "select" ? "" : el.labels?.[0] ? collapse(el.labels[0].textContent) : "", found.secret); return mark ? ` ${mark} ` : ""; } let body2; @@ -20651,7 +20765,7 @@ ${body2 || "(no text)"} } else { body2 = children(el, { ...next, pre: keepsSpace }); } - if (found) found.item.name = nameOf(el, oneLine(body2), found.secret); + if (found) found.item.name = nameOf2(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); @@ -20779,7 +20893,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 }; @@ -20931,7 +21045,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); @@ -21432,13 +21546,13 @@ function lineDiff(before, after) { } // src/client/learning-card.js -var import_react53 = require("react"); +var import_react54 = require("react"); var failedAnswers = /* @__PURE__ */ new Map(); function ProposalCard({ proposal, initialError = "", onFailure, onResolved, actions }) { - const [busy, setBusy] = (0, import_react53.useState)(false); - const [error, setError] = (0, import_react53.useState)(initialError); - const busyRef = (0, import_react53.useRef)(false); - const titleId = (0, import_react53.useId)(); + const [busy, setBusy] = (0, import_react54.useState)(false); + const [error, setError] = (0, import_react54.useState)(initialError); + const busyRef = (0, import_react54.useRef)(false); + const titleId = (0, import_react54.useId)(); const answer = (approve) => { if (busyRef.current) return; busyRef.current = true; @@ -21454,58 +21568,58 @@ function ProposalCard({ proposal, initialError = "", onFailure, onResolved, acti }); }; const update = proposal.action === "update"; - const rows2 = (0, import_react53.useMemo)(() => lineDiff(update ? proposal.previous?.content : "", proposal.content), [update, proposal.previous?.content, proposal.content]); + const rows2 = (0, import_react54.useMemo)(() => lineDiff(update ? proposal.previous?.content : "", proposal.content), [update, proposal.previous?.content, proposal.content]); if (proposal.kind === "agents") { const 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 })) ]); - return (0, import_react53.createElement)( + return (0, import_react54.createElement)( "section", { className: "bt-q bt-learning-card", role: "group", "aria-labelledby": titleId, "aria-busy": busy }, - (0, import_react53.createElement)(ProposalHead, { titleId, icon: PencilIcon, title: t("AGENTS.md update") }), - (0, import_react53.createElement)(FileBox, { name: "AGENTS.md", path: proposal.folder, state: proposal.exists === false ? "Added" : "Modified", blocks }), - proposal.edits.map((edit, index) => edit.why ? (0, import_react53.createElement)("p", { className: "bt-learning-why", key: index }, edit.why) : null), - error ? (0, import_react53.createElement)("div", { className: "bt-learning-error", role: "alert" }, error) : null, - (0, import_react53.createElement)(ProposalFoot, { busy, answer }) + (0, import_react54.createElement)(ProposalHead, { titleId, icon: PencilIcon, title: t("AGENTS.md update") }), + (0, import_react54.createElement)(FileBox, { name: "AGENTS.md", path: proposal.folder, state: proposal.exists === false ? "Added" : "Modified", blocks }), + proposal.edits.map((edit, index) => edit.why ? (0, import_react54.createElement)("p", { className: "bt-learning-why", key: index }, edit.why) : null), + error ? (0, import_react54.createElement)("div", { className: "bt-learning-error", role: "alert" }, error) : null, + (0, import_react54.createElement)(ProposalFoot, { busy, answer }) ); } const oldDetail = update && typeof proposal.previous?.description === "string" && proposal.previous.description !== proposal.description ? proposal.previous.description : void 0; - return (0, import_react53.createElement)( + return (0, import_react54.createElement)( "section", { className: "bt-q bt-learning-card", role: "group", "aria-labelledby": titleId, "aria-busy": busy }, - (0, import_react53.createElement)(ProposalHead, { titleId, title: proposal.name, kind: t(update ? "Skill update" : "New skill"), detail: proposal.description, oldDetail }), - (0, import_react53.createElement)(FileBox, { name: "SKILL.md", path: `skills/${proposal.name}`, state: update ? "Updated" : "Added", blocks: [rows2] }), - proposal.why ? (0, import_react53.createElement)("p", { className: "bt-learning-why" }, proposal.why) : null, - error ? (0, import_react53.createElement)("div", { className: "bt-learning-error", role: "alert" }, error) : null, - (0, import_react53.createElement)(ProposalFoot, { busy, answer }) + (0, import_react54.createElement)(ProposalHead, { titleId, title: proposal.name, kind: t(update ? "Skill update" : "New skill"), detail: proposal.description, oldDetail }), + (0, import_react54.createElement)(FileBox, { name: "SKILL.md", path: `skills/${proposal.name}`, state: update ? "Updated" : "Added", blocks: [rows2] }), + proposal.why ? (0, import_react54.createElement)("p", { className: "bt-learning-why" }, proposal.why) : null, + error ? (0, import_react54.createElement)("div", { className: "bt-learning-error", role: "alert" }, error) : null, + (0, import_react54.createElement)(ProposalFoot, { busy, answer }) ); } function ProposalHead({ titleId, icon: icon2 = MemoryIcon, title, kind, detail, oldDetail }) { - return (0, import_react53.createElement)( + return (0, import_react54.createElement)( "div", { className: "bt-q-head" }, - (0, import_react53.createElement)("span", { className: "bt-learning-icon", "aria-hidden": true }, (0, import_react53.createElement)(icon2)), - (0, import_react53.createElement)( + (0, import_react54.createElement)("span", { className: "bt-learning-icon", "aria-hidden": true }, (0, import_react54.createElement)(icon2)), + (0, import_react54.createElement)( "div", { className: "bt-q-text" }, - (0, import_react53.createElement)("p", { className: "bt-q-title", id: titleId }, title), - kind ? (0, import_react53.createElement)("div", { className: "bt-q-detail" }, kind) : null, - oldDetail ? (0, import_react53.createElement)("p", { className: "bt-learning-description bt-learning-old" }, (0, import_react53.createElement)("del", null, oldDetail)) : null, - detail ? (0, import_react53.createElement)("p", { className: "bt-learning-description" }, detail) : null + (0, import_react54.createElement)("p", { className: "bt-q-title", id: titleId }, title), + kind ? (0, import_react54.createElement)("div", { className: "bt-q-detail" }, kind) : null, + oldDetail ? (0, import_react54.createElement)("p", { className: "bt-learning-description bt-learning-old" }, (0, import_react54.createElement)("del", null, oldDetail)) : null, + detail ? (0, import_react54.createElement)("p", { className: "bt-learning-description" }, detail) : null ), - (0, import_react53.createElement)("span", { className: "bt-q-badge bt-learning-status" }, (0, import_react53.createElement)("span", { className: "bt-learning-dot", "aria-hidden": true }), t("Awaiting approval")) + (0, import_react54.createElement)("span", { className: "bt-q-badge bt-learning-status" }, (0, import_react54.createElement)("span", { className: "bt-learning-dot", "aria-hidden": true }), t("Awaiting approval")) ); } function ProposalFoot({ busy, answer }) { - return (0, import_react53.createElement)( + return (0, import_react54.createElement)( "div", { className: "bt-q-foot bt-learning-foot" }, - (0, import_react53.createElement)("button", { type: "button", className: "bt-learning-btn bt-learning-decline", disabled: busy, onClick: () => answer(false) }, t("Decline")), - (0, import_react53.createElement)( + (0, import_react54.createElement)("button", { type: "button", className: "bt-learning-btn bt-learning-decline", disabled: busy, onClick: () => answer(false) }, t("Decline")), + (0, import_react54.createElement)( "button", { type: "button", className: "bt-learning-btn bt-learning-approve", disabled: busy, onClick: () => answer(true) }, - (0, import_react53.createElement)(CheckIcon), + (0, import_react54.createElement)(CheckIcon), t("Approve") ) ); @@ -21513,43 +21627,43 @@ function ProposalFoot({ busy, answer }) { var COLLAPSE_ROWS = 8; var SIGNS = { added: "+", removed: "−", same: "" }; function FileBox({ name, path, state, blocks }) { - const [open, setOpen] = (0, import_react53.useState)(false); + const [open, setOpen] = (0, import_react54.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_react53.createElement)( + return (0, import_react54.createElement)( "div", { className: "bt-learning-file" }, - (0, import_react53.createElement)( + (0, import_react54.createElement)( "div", { className: "bt-learning-filehead" }, - (0, import_react53.createElement)("span", { className: "bt-learning-name" }, name), - path ? (0, import_react53.createElement)("span", { className: "bt-learning-path" }, path) : null, - (0, import_react53.createElement)("span", { className: "bt-learning-spacer" }), - added > 0 ? (0, import_react53.createElement)("span", { className: "bt-learning-plus" }, `+${added}`) : null, - removed > 0 ? (0, import_react53.createElement)("span", { className: "bt-learning-minus" }, `−${removed}`) : null, - (0, import_react53.createElement)("span", { className: `bt-learning-state bt-learning-state-${state.toLowerCase()}` }, t(state)) + (0, import_react54.createElement)("span", { className: "bt-learning-name" }, name), + path ? (0, import_react54.createElement)("span", { className: "bt-learning-path" }, path) : null, + (0, import_react54.createElement)("span", { className: "bt-learning-spacer" }), + added > 0 ? (0, import_react54.createElement)("span", { className: "bt-learning-plus" }, `+${added}`) : null, + removed > 0 ? (0, import_react54.createElement)("span", { className: "bt-learning-minus" }, `−${removed}`) : null, + (0, import_react54.createElement)("span", { className: `bt-learning-state bt-learning-state-${state.toLowerCase()}` }, t(state)) ), - (0, import_react53.createElement)( + (0, import_react54.createElement)( "div", { className: shut ? "bt-learning-code bt-learning-shut" : "bt-learning-code" }, blocks.map((rows2, blockIndex) => [ - blockIndex > 0 ? (0, import_react53.createElement)("div", { className: "bt-learning-gap", key: `gap-${blockIndex}` }) : null, - ...rows2.map((row, rowIndex) => (0, import_react53.createElement)( + blockIndex > 0 ? (0, import_react54.createElement)("div", { className: "bt-learning-gap", key: `gap-${blockIndex}` }) : null, + ...rows2.map((row, rowIndex) => (0, import_react54.createElement)( "div", { className: `bt-learning-row bt-learning-${row.kind}`, key: `${blockIndex}-${rowIndex}` }, - (0, import_react53.createElement)("span", { className: "bt-learning-num", "aria-hidden": true }, row.number ?? ""), - (0, import_react53.createElement)("span", { className: "bt-learning-sign", "aria-hidden": true }, SIGNS[row.kind]), - (0, import_react53.createElement)("span", { className: "bt-learning-text" }, row.line || " ") + (0, import_react54.createElement)("span", { className: "bt-learning-num", "aria-hidden": true }, row.number ?? ""), + (0, import_react54.createElement)("span", { className: "bt-learning-sign", "aria-hidden": true }, SIGNS[row.kind]), + (0, import_react54.createElement)("span", { className: "bt-learning-text" }, row.line || " ") )) ]) ), - folds ? (0, import_react53.createElement)( + folds ? (0, import_react54.createElement)( "div", { className: shut ? "bt-learning-morebar bt-learning-morebar-shut" : "bt-learning-morebar" }, - (0, import_react53.createElement)( + (0, import_react54.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 }) @@ -21560,7 +21674,7 @@ function FileBox({ name, path, state, blocks }) { function LearningProposals({ turn, dock, sessionId, useRoster, actions }) { const roster = useRoster((value) => value); const facts = useTurnFacts(sessionId, actions); - const [failed, setFailed] = (0, import_react53.useState)({}); + const [failed, setFailed] = (0, import_react54.useState)({}); const bot = roster.byId?.[sessionId]; if (!bot || currentPart(bot) !== sessionId) return null; const proposals = roster.learning?.[bot.id] ?? []; @@ -21587,10 +21701,10 @@ function LearningProposals({ turn, dock, sessionId, useRoster, actions }) { delete next[id]; return next; }); - return (0, import_react53.createElement)("div", { className: dock ? "bt-learning-stack bt-learning-dock" : "bt-learning-stack" }, cards.map((proposal) => (0, import_react53.createElement)( + return (0, import_react54.createElement)("div", { className: dock ? "bt-learning-stack bt-learning-dock" : "bt-learning-stack" }, cards.map((proposal) => (0, import_react54.createElement)( "div", { className: "bt-q-inline", key: proposal.id }, - (0, import_react53.createElement)(ProposalCard, { + (0, import_react54.createElement)(ProposalCard, { proposal, initialError: failed[proposal.id]?.error ?? failedAnswers.get(proposal.id)?.error, onFailure, @@ -21600,10 +21714,10 @@ function LearningProposals({ turn, dock, sessionId, useRoster, actions }) { ))); } function LearningTurnTail(props) { - return (0, import_react53.createElement)(LearningProposals, { ...props, dock: false }); + return (0, import_react54.createElement)(LearningProposals, { ...props, dock: false }); } function LearningDock(props) { - return (0, import_react53.createElement)(LearningProposals, { ...props, dock: true }); + return (0, import_react54.createElement)(LearningProposals, { ...props, dock: true }); } var LEARNING_CSS = ` .bt-learning-stack{display:flex;flex-direction:column;gap:4px} @@ -21686,7 +21800,7 @@ function createSwitchWindow(settle) { } // src/client/user-message.js -var import_react54 = require("react"); +var import_react55 = require("react"); var ui = __toESM(require("@deepseek-ai/dsh-client-ui-primitives"), 1); var canDrawUserMessages = () => typeof ui.projectUserText === "function"; function contentParts(content) { @@ -21718,38 +21832,38 @@ function userTextParts(text, bots, referenceLabels = []) { return parts; } function UserText({ text, bots, referenceLabels, skillNames, references, actions }) { - return userTextParts(text, bots, referenceLabels).map((part, index) => part.bot ? (0, import_react54.createElement)( + return userTextParts(text, bots, referenceLabels).map((part, index) => part.bot ? (0, import_react55.createElement)( "button", { key: index, type: "button", className: "bt-umention", title: `@${part.bot.name}`, onClick: () => actions.openSession(part.bot.id) }, - (0, import_react54.createElement)(BotMark, { bot: part.bot, size: 16 }), + (0, import_react55.createElement)(BotMark, { bot: part.bot, size: 16 }), part.label - ) : (0, import_react54.createElement)(import_react54.Fragment, { key: index }, ui.projectUserText(part.text, referenceLabels, skillNames, "skill", references))); + ) : (0, import_react55.createElement)(import_react55.Fragment, { key: index }, ui.projectUserText(part.text, referenceLabels, skillNames, "skill", references))); } function Attachments({ attachments, renderMessageImages }) { const compact2 = attachments.length > 1; - return (0, import_react54.createElement)("div", { className: "bt-uattach" }, attachments.map((block, index) => { + return (0, import_react55.createElement)("div", { className: "bt-uattach" }, attachments.map((block, index) => { if (block.type === "image") { - return renderMessageImages ? (0, import_react54.createElement)(import_react54.Fragment, { key: index }, renderMessageImages({ images: [{ attachment: block.attachment }], align: "end", compact: compact2 })) : null; + return renderMessageImages ? (0, import_react55.createElement)(import_react55.Fragment, { key: index }, renderMessageImages({ images: [{ attachment: block.attachment }], align: "end", compact: compact2 })) : null; } const file = block.attachment; const meta = [ui.fileExtension?.(file.name)?.toUpperCase().slice(0, 8), ui.fileSizeText?.(file.bytes)].filter(Boolean).join(" · "); - return (0, import_react54.createElement)( + return (0, import_react55.createElement)( "span", { key: index, className: "bt-ufile", title: file.name }, - ui.FileTypeIcon ? (0, import_react54.createElement)(ui.FileTypeIcon, { path: file.name, className: "bt-ufile-icon" }) : null, - (0, import_react54.createElement)("span", { className: "bt-ufile-text" }, (0, import_react54.createElement)("span", { className: "bt-ufile-name" }, file.name), meta ? (0, import_react54.createElement)("span", { className: "bt-ufile-meta" }, meta) : null) + ui.FileTypeIcon ? (0, import_react55.createElement)(ui.FileTypeIcon, { path: file.name, className: "bt-ufile-icon" }) : null, + (0, import_react55.createElement)("span", { className: "bt-ufile-text" }, (0, import_react55.createElement)("span", { className: "bt-ufile-name" }, file.name), meta ? (0, import_react55.createElement)("span", { className: "bt-ufile-meta" }, meta) : null) ); })); } function CopyButton({ text }) { - const [copied, setCopied] = (0, import_react54.useState)(false); + const [copied, setCopied] = (0, import_react55.useState)(false); const copy2 = () => { void navigator.clipboard?.writeText(text).then(() => { setCopied(true); setTimeout(() => setCopied(false), 1e3); }); }; - return (0, import_react54.createElement)("button", { type: "button", className: "bt-tool", "aria-label": copied ? t("Copied") : t("Copy"), title: copied ? t("Copied") : t("Copy"), onClick: copy2 }, copied ? (0, import_react54.createElement)(CheckIcon) : (0, import_react54.createElement)(CopyIcon)); + return (0, import_react55.createElement)("button", { type: "button", className: "bt-tool", "aria-label": copied ? t("Copied") : t("Copy"), title: copied ? t("Copied") : t("Copy"), onClick: copy2 }, copied ? (0, import_react55.createElement)(CheckIcon) : (0, import_react55.createElement)(CopyIcon)); } var clock3 = (time) => typeof time === "number" ? new Date(time).toLocaleTimeString(dateLocale(), { hour: "numeric", minute: "2-digit" }) : void 0; function UserMessageCell({ node, sessionId, useRoster, actions, renderMessageImages, openFile, openSkill }) { @@ -21761,10 +21875,10 @@ function UserMessageCell({ node, sessionId, useRoster, actions, renderMessageIma const steering = node.kind === "steering"; const sentAt = Number.isFinite(data.time) ? messageClock(data.time) : void 0; const { shown, folded, control } = useFold(text, { markdown: false }); - const body = (0, import_react54.createElement)(UserText, { text: shown, bots: mentionableBots(roster, sessionId), referenceLabels, skillNames: data.skillNames ?? [], references, actions }); - const row = (0, import_react54.useRef)(null); - const [toolsOpen, setToolsOpen] = (0, import_react54.useState)(false); - (0, import_react54.useEffect)(() => { + const body = (0, import_react55.createElement)(UserText, { text: shown, bots: mentionableBots(roster, sessionId), referenceLabels, skillNames: data.skillNames ?? [], references, actions }); + const row = (0, import_react55.useRef)(null); + const [toolsOpen, setToolsOpen] = (0, import_react55.useState)(false); + (0, import_react55.useEffect)(() => { if (!toolsOpen) return void 0; const onDown = (event) => { if (!row.current?.contains(event.target)) setToolsOpen(false); @@ -21780,24 +21894,24 @@ function UserMessageCell({ node, sessionId, useRoster, actions, renderMessageIma if (!noHover() || event.target instanceof Element && event.target.closest("a,button,input,textarea,select,pre,code,[role=button],[role=link]")) return; setToolsOpen((value) => !value); }; - return (0, import_react54.createElement)( + return (0, import_react55.createElement)( "div", { ref: row, className: "bt-umsg", "data-steering": steering || void 0 }, - (0, import_react54.createElement)( + (0, import_react55.createElement)( "div", { className: "bt-ustack" }, - attachments.length > 0 ? (0, import_react54.createElement)(Attachments, { attachments, renderMessageImages }) : null, - text !== "" || rest.length > 0 ? (0, import_react54.createElement)( + attachments.length > 0 ? (0, import_react55.createElement)(Attachments, { attachments, renderMessageImages }) : null, + text !== "" || rest.length > 0 ? (0, import_react55.createElement)( "div", { className: "bt-ubody", title: clock3(data.time), "data-folded": folded || void 0, onClick: tapTools }, - control ? (0, import_react54.createElement)("div", { className: "bt-fold-body" }, body) : body, + control ? (0, import_react55.createElement)("div", { className: "bt-fold-body" }, body) : body, control, - rest.map((block, index) => ui.JsonBlock ? (0, import_react54.createElement)(ui.JsonBlock, { key: index, label: t("Content"), payload: block }) : null) + rest.map((block, index) => ui.JsonBlock ? (0, import_react55.createElement)(ui.JsonBlock, { key: index, label: t("Content"), payload: block }) : null) ) : null, - referenceLabels.length > 0 ? (0, import_react54.createElement)("div", { className: "bt-urefs" }, t("Referenced {labels}", { labels: referenceLabels.join(t(", ")) })) : null, - sentAt ? (0, import_react54.createElement)("div", { className: "bt-utime", title: clockLabel(data.time) }, sentAt) : null + referenceLabels.length > 0 ? (0, import_react55.createElement)("div", { className: "bt-urefs" }, t("Referenced {labels}", { labels: referenceLabels.join(t(", ")) })) : null, + sentAt ? (0, import_react55.createElement)("div", { className: "bt-utime", title: clockLabel(data.time) }, sentAt) : null ), - text === "" ? null : (0, import_react54.createElement)("div", { className: "bt-utools", "data-open": toolsOpen || void 0 }, (0, import_react54.createElement)(CopyButton, { text })) + text === "" ? null : (0, import_react55.createElement)("div", { className: "bt-utools", "data-open": toolsOpen || void 0 }, (0, import_react55.createElement)(CopyButton, { text })) ); } var USER_MESSAGE_CSS = ` @@ -22009,6 +22123,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.btwCards !== void 0 && JSON.stringify(value.btwCards) !== JSON.stringify(current.btwCards ?? {})) live2.btwCards = value.btwCards; if (value.sideChats !== void 0 && JSON.stringify(value.sideChats) !== JSON.stringify(current.sideChats ?? {})) live2.sideChats = value.sideChats; @@ -22734,6 +22849,7 @@ function apply(ctx) { () => installCompiledStyles(MODEL_CSS + FOLDER_CSS + BOT_SETTINGS_CSS + GROUP_SETTINGS_CSS + AVATAR_LIBRARY_CSS, "models"), () => installCompiledStyles(USAGE_CSS, "usage"), () => installCompiledStyles(SCHEDULE_CSS, "schedules"), + () => installCompiledStyles(OPERATOR_TASKS_CSS, "operator-tasks"), () => installCompiledStyles(FEEDBACK_CSS, "feedback"), () => installCompiledStyles(ABOUT_CSS, "about"), () => installCompiledStyles(MEMBER_CSS, "members"), diff --git a/ds-bot/index.js b/ds-bot/index.js index a524d3603a..36259ed9a8 100644 --- a/ds-bot/index.js +++ b/ds-bot/index.js @@ -39,6 +39,7 @@ 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 officeSkills from './src/host/office-skills.js' @@ -54,7 +55,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, goals, approvals, resume, memory, parts, images, avatarLibrary, secrets, connectors, capabilities, learning, schedules, browser, browserPlugins, usage, update, dshUpdate, thinking, feed, channel, officeSkills, goalSkills] +const MODULES = [diagnostics, store, models, providers, permissions, turns, steer, handoffs, requests, delivery, roster, folders, privacy, agents, prompt, timeContext, tools, chatIndex, groups, goals, approvals, resume, memory, parts, images, avatarLibrary, secrets, connectors, capabilities, learning, schedules, browser, browserPlugins, usage, update, dshUpdate, thinking, feed, operatorTasks, channel, officeSkills, goalSkills] export function apply(ctx, config = {}) { createRuntime(ctx, config) diff --git a/ds-bot/src/client/details-drawer.js b/ds-bot/src/client/details-drawer.js index 2a3132b80a..9971341e46 100644 --- a/ds-bot/src/client/details-drawer.js +++ b/ds-bot/src/client/details-drawer.js @@ -12,6 +12,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' @@ -305,6 +306,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 038592a374..27285d76a8 100644 --- a/ds-bot/src/client/header.js +++ b/ds-bot/src/client/header.js @@ -6,6 +6,7 @@ import { botState, BotAvatar, RoomAvatar } from './mark.js' import { ActivityIndicator } from './activity-row.js' import { clockLabel, openingTurn, unseenSince } from './cells.js' import { GoalIsland, goalView } from './goal.js' +import { UnresolvedBadge, unresolvedCount } from './operator-tasks.js' import { viewBottom } from './motion.js' import { t } from './i18n.js' @@ -127,6 +128,7 @@ export function HeaderPill({ sessionId, useRoster, useSessions, useSessionStatus h('span', { className: 'bt-pill-goal' }, h('span', { className: 'bt-pill-ico', 'aria-hidden': true }, h(GoalIcon)), h('span', { className: 'bt-pill-title' }, view.title)), h('span', { className: 'bt-pill-name' }, name)) : h('span', { className: 'bt-pill-name' }, away ? t('Back to chat') : bot?.name ?? room?.name ?? (title || t('New chat'))), + bot && !away ? h(UnresolvedBadge, { count: unresolvedCount(roster, bot.id) }) : null, 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 689d1e65f3..6b33784150 100644 --- a/ds-bot/src/client/i18n.js +++ b/ds-bot/src/client/i18n.js @@ -1126,6 +1126,31 @@ const ZH = { 'New task': '新建任务', 'No scheduled tasks yet.': '还没有定时任务。', 'No scheduled tasks yet. Add one': '还没有定时任务,去添加', + 'Active Tasks': '进行中的任务', + 'Unresolved Tasks': '待你处理的任务', + '{title} · {count}': '{title} · {count}', + 'Nothing running right now.': '现在没有在进行的工作。', + 'Nothing waiting on you.': '没有等你处理的事。', + '1 task waits on you': '有 1 件事等你处理', + '{count} tasks wait on you': '有 {count} 件事等你处理', + '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/index.js b/ds-bot/src/client/index.js index 922b890d5c..eee4ac6bf9 100644 --- a/ds-bot/src/client/index.js +++ b/ds-bot/src/client/index.js @@ -35,6 +35,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' @@ -198,6 +199,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.btwCards !== undefined && JSON.stringify(value.btwCards) !== JSON.stringify(current.btwCards ?? {})) live.btwCards = value.btwCards if (value.sideChats !== undefined && JSON.stringify(value.sideChats) !== JSON.stringify(current.sideChats ?? {})) live.sideChats = value.sideChats @@ -944,6 +946,7 @@ export function apply(ctx) { () => installCompiledStyles(MODEL_CSS + FOLDER_CSS + BOT_SETTINGS_CSS + GROUP_SETTINGS_CSS + AVATAR_LIBRARY_CSS, 'models'), () => installCompiledStyles(USAGE_CSS, 'usage'), () => installCompiledStyles(SCHEDULE_CSS, 'schedules'), + () => installCompiledStyles(OPERATOR_TASKS_CSS, 'operator-tasks'), () => installCompiledStyles(FEEDBACK_CSS, 'feedback'), () => installCompiledStyles(ABOUT_CSS, 'about'), () => installCompiledStyles(MEMBER_CSS, 'members'), diff --git a/ds-bot/src/client/operator-tasks.js b/ds-bot/src/client/operator-tasks.js new file mode 100644 index 0000000000..09c84771f5 --- /dev/null +++ b/ds-bot/src/client/operator-tasks.js @@ -0,0 +1,87 @@ +// A Bot's operator tasks in its details panel, and the count after its name in the +// chat header. The host builds the list (src/host/operator-tasks.js): Unresolved is +// what waits on the user, Active what the Bot works on. The header counts +// Unresolved only, so its number always means "this needs you". +import { createElement as h } from 'react' +import { relativeShort } from './text.js' +import { t } from './i18n.js' + +const EMPTY = { active: [], unresolved: [] } + +export const operatorTasksOf = (roster, botId) => roster.operatorTasks?.[botId] ?? EMPTY +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 ?? '' } + } +} + +function activeLine(item, roster) { + switch (item.kind) { + case 'turn': { + const doing = item.switching ? t('Moving on to a fresh part') + : item.tool ? (item.target ? t('Running {tool} on {target}', { tool: item.tool, target: item.target }) : t('Running {tool}', { tool: item.tool })) + : item.text || t('Working') + return { label: t('Working now'), text: [doing, where(roster, item)].filter(Boolean).join(' ') } + } + case '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 ?? '' } + } +} + +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: 'active', title: t('Active Tasks'), items: tasks.active, line: activeLine, roster, empty: t('Nothing running right now.') }), + h(TaskList, { key: 'unresolved', title: t('Unresolved Tasks'), items: tasks.unresolved, line: unresolvedLine, roster, empty: t('Nothing waiting on you.') }), + ] +} + +// After the Bot's name in the chat header; nothing at all when the count is 0. +export function UnresolvedBadge({ count }) { + if (!(count > 0)) return null + const label = count === 1 ? t('1 task waits on you') : t('{count} tasks wait on you', { count }) + return h('span', { className: 'bt-pill-tasks', title: label, 'aria-label': label }, count > 99 ? '99+' : String(count)) +} + +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;min-width:18px;height:18px;padding:0 5px;border-radius:999px;background:var(--bt-danger);color:var(--bt-main);font-size:11px;line-height:18px;font-weight:600;text-align:center;font-variant-numeric:tabular-nums} +` diff --git a/ds-bot/src/client/sources.js b/ds-bot/src/client/sources.js index a71ccdb905..7679825632 100644 --- a/ds-bot/src/client/sources.js +++ b/ds-bot/src/client/sources.js @@ -16,7 +16,7 @@ export function createSource(initial) { } } -export const EMPTY_ROSTER = { revision: -1, mainBotId: null, mainBotIds: [], bots: [], rooms: [], agents: [], 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: [], 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) diff --git a/ds-bot/src/host/channel.js b/ds-bot/src/host/channel.js index 5ce6b836a4..5e82ee3a02 100644 --- a/ds-bot/src/host/channel.js +++ b/ds-bot/src/host/channel.js @@ -98,6 +98,7 @@ export function install(rt) { learning: rt.learningView(), connectors: rt.connectorsView(), capabilityStatuses: rt.capabilityStatusesView(), + 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/operator-tasks.js b/ds-bot/src/host/operator-tasks.js new file mode 100644 index 0000000000..96a9aac84d --- /dev/null +++ b/ds-bot/src/host/operator-tasks.js @@ -0,0 +1,137 @@ +// Operator tasks: per Bot, what waits on the user (Unresolved) and what the Bot is +// working on (Active). Built only from sources the host already keeps, plus the +// operator's loose-ends register, which this module reads and never writes. +// Git, CI and merges reach none of these sources, so no text filter is needed. +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 +} +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] ??= { 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 }) + } + + for (const [botId, work] of Object.entries(rt.workView?.() ?? {})) { + add(botId, 'active', { kind: 'turn', key: 'turn', at: work.since, ...(work.tool ? { tool: work.tool } : {}), ...(work.target ? { target: work.target } : {}), ...(work.said ? { text: clip(work.said, 160) } : {}), ...(work.switching ? { switching: true } : {}), ...(work.roomId ? { roomId: work.roomId } : {}) }) + } + for (const [id, work] of Object.entries(state.works ?? {})) { + if (work?.to === undefined || work.from === undefined || work.to === work.from) continue + add(work.to, 'active', { kind: 'order', key: `order:${id}`, from: work.from, at: work.at }) + } + for (const [botId, waiting] of Object.entries(rt.waitingView?.() ?? {})) { + add(botId, 'active', { kind: 'waiting', key: 'waiting', bots: waiting.bots ?? [], rooms: waiting.rooms ?? [] }) + } + + // Oldest first: what has waited longest sits on top. + for (const entry of Object.values(view)) { + for (const list of [entry.active, entry.unresolved]) list.sort((a, b) => (a.at ?? Infinity) - (b.at ?? Infinity)) + } + return view + } + + rt.operatorTasksView = operatorTasksView +} diff --git a/ds-bot/test/operator-tasks.test.js b/ds-bot/test/operator-tasks.test.js new file mode 100644 index 0000000000..4b247a34cb --- /dev/null +++ b/ds-bot/test/operator-tasks.test.js @@ -0,0 +1,145 @@ +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 { install, openDecisions } from '../src/host/operator-tasks.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.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('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, {}) +}) From a527046b1acaab6eff38ff29d31f4274eef2a899 Mon Sep 17 00:00:00 2001 From: Steve Dempsey Date: Wed, 4 Nov 2026 13:34:36 -0500 Subject: [PATCH 10/18] Publish owned Sessions on ds-bot:sessions as well as the legacy name The Harness listener is moving to the ds-bot:sessions event name. The installed Harness still listens on dsh-bot:sessions, so the client sends both, new name first, from one helper in sources.js. The legacy name sits in its own constant so a later release can drop it in one line (LE-20261103-033). --- ds-bot/client.js | 16 +++++++++------- ds-bot/src/client/index.js | 11 +++-------- ds-bot/src/client/sources.js | 11 +++++++++++ ds-bot/test/owned-sessions.test.js | 25 +++++++++++++++++++++++++ 4 files changed, 48 insertions(+), 15 deletions(-) diff --git a/ds-bot/client.js b/ds-bot/client.js index 1757630a7e..f261bfe7a6 100644 --- a/ds-bot/client.js +++ b/ds-bot/client.js @@ -1662,6 +1662,13 @@ function indexRoster(value) { } return { ...value, agents: value.agents ?? [], 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; @@ -21897,17 +21904,12 @@ function apply(ctx) { } const roster = createSource({ ...EMPTY_ROSTER, prefs: savedPrefs }); ctx.effect(() => { - const publish2 = () => { - const ids = ownedSessionIds(roster.getSnapshot()); - window.__dshBotSessions = ids; - window.dispatchEvent(new CustomEvent("dsh-bot:sessions", { detail: ids })); - }; + const publish2 = () => publishOwnedSessions(window, ownedSessionIds(roster.getSnapshot())); const off = roster.subscribe(publish2); publish2(); return () => { off(); - window.__dshBotSessions = []; - window.dispatchEvent(new CustomEvent("dsh-bot:sessions", { detail: [] })); + publishOwnedSessions(window, []); }; }, "ds-bot: publish owned sessions"); const unreadStore = sharedMap(STORAGE.unread); diff --git a/ds-bot/src/client/index.js b/ds-bot/src/client/index.js index 922b890d5c..6fcadbaae0 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, ownedSessionIds } 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' @@ -65,17 +65,12 @@ export function apply(ctx) { // 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 = () => { - const ids = ownedSessionIds(roster.getSnapshot()) - window.__dshBotSessions = ids - window.dispatchEvent(new CustomEvent('dsh-bot:sessions', { detail: ids })) - } + const publish = () => publishOwnedSessions(window, ownedSessionIds(roster.getSnapshot())) const off = roster.subscribe(publish) publish() return () => { off() - window.__dshBotSessions = [] - window.dispatchEvent(new CustomEvent('dsh-bot:sessions', { detail: [] })) + publishOwnedSessions(window, []) } }, 'ds-bot: publish owned sessions') const unreadStore = sharedMap(STORAGE.unread) diff --git a/ds-bot/src/client/sources.js b/ds-bot/src/client/sources.js index a71ccdb905..5ca6d2d588 100644 --- a/ds-bot/src/client/sources.js +++ b/ds-bot/src/client/sources.js @@ -55,6 +55,17 @@ export function indexRoster(value) { return { ...value, agents: value.agents ?? [], 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/test/owned-sessions.test.js b/ds-bot/test/owned-sessions.test.js index 3cf79bc1a3..f194ebe442 100644 --- a/ds-bot/test/owned-sessions.test.js +++ b/ds-bot/test/owned-sessions.test.js @@ -31,4 +31,29 @@ test('the owned Sessions are every Bot part, every group Session and every Agent test('an empty roster owns nothing', () => { assert.deepEqual(ownedSessionIds(indexRoster({ bots: [], rooms: [] })), []) +}) + +// The installed shell listens on the legacy name and an updated one on the new name, +// so both events go out, the new one first (LE-20261103-033). +const { SESSIONS_EVENT, legacySessionsEvent, publishOwnedSessions } = await import('../src/client/sources.js') +const fakeWindow = () => { + const seen = [] + return { seen, dispatchEvent: (event) => { seen.push([event.type, event.detail]); return true } } +} + +test('owned Sessions go out on the new event and on the legacy one, in that order', () => { + const win = fakeWindow() + const ids = ['s1', 's2'] + publishOwnedSessions(win, ids) + assert.equal(SESSIONS_EVENT, 'ds-bot:sessions') + assert.equal(legacySessionsEvent, 'dsh-bot:sessions') + assert.deepEqual(win.seen, [['ds-bot:sessions', ids], ['dsh-bot:sessions', ids]]) + assert.deepEqual(win.__dshBotSessions, ids) +}) + +test('clearing publishes an empty list on both events', () => { + const win = fakeWindow() + publishOwnedSessions(win, []) + assert.deepEqual(win.seen, [['ds-bot:sessions', []], ['dsh-bot:sessions', []]]) + assert.deepEqual(win.__dshBotSessions, []) }) \ No newline at end of file From 23f9823f33c4494abd16a162370534cd7abd3502 Mon Sep 17 00:00:00 2001 From: Steve Dempsey Date: Wed, 4 Nov 2026 13:47:45 -0500 Subject: [PATCH 11/18] Add a Brainstorm row to the composer's + menu Steve wants one click to start a brainstorm. The row types "brainstorm " at the caret and does nothing else: the word itself is what turns on the show-options-first stance in his AGENTS.md, so no mode flips and nothing stays switched on after the turn. The row only shows where the composer offers insertText. --- ds-bot/client.js | 16 ++++++++++++++++ ds-bot/src/client/brainstorm.js | 12 ++++++++++++ ds-bot/src/client/composer.js | 8 +++++++- ds-bot/src/client/i18n.js | 1 + ds-bot/src/client/icons.js | 2 ++ ds-bot/test/composer-brainstorm.test.js | 20 ++++++++++++++++++++ 6 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 ds-bot/src/client/brainstorm.js create mode 100644 ds-bot/test/composer-brainstorm.test.js diff --git a/ds-bot/client.js b/ds-bot/client.js index 1757630a7e..da067a242d 100644 --- a/ds-bot/client.js +++ b/ds-bot/client.js @@ -1121,6 +1121,7 @@ var ZH = { "Add files": "添加文件", "Reference a chat": "引用对话", "Chat with {name}": "与 {name} 的对话", + Brainstorm: "头脑风暴", "Scheduled task": "定时任务", "Send to": "发给", "Scheduled task: {text}": "定时任务:{text}", @@ -4111,6 +4112,7 @@ var SwitchIcon = lineIcon(["M4 7h9.5M10.5 3.5L14 7l-3.5 3.5", "M16 13H6.5M9.5 9. 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"]); @@ -11492,6 +11494,15 @@ 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_react23 = require("react"); var import_react_dom5 = require("react-dom"); @@ -11703,6 +11714,10 @@ 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); @@ -11734,6 +11749,7 @@ function ComposerPlus({ sessionId, inputActions, useInput, useRoster, actions }) }, shown.files ? (0, import_react23.createElement)("button", { type: "button", role: "menuitem", onClick: attach }, (0, import_react23.createElement)(PaperclipIcon), (0, import_react23.createElement)("span", { className: "bt-menu-label" }, t("Add files"))) : null, canReference ? (0, import_react23.createElement)("button", { type: "button", role: "menuitem", onMouseDown: keepComposerFocus, onClick: reference }, (0, import_react23.createElement)(ChatsIcon), (0, import_react23.createElement)("span", { className: "bt-menu-label" }, t("Reference a chat"))) : null, + canBrainstorm(inputActions) ? (0, import_react23.createElement)("button", { type: "button", role: "menuitem", onMouseDown: keepComposerFocus, onClick: brainstorm }, (0, import_react23.createElement)(BulbIcon), (0, import_react23.createElement)("span", { className: "bt-menu-label" }, t("Brainstorm"))) : null, canSetGoal(room2, roster) ? (0, import_react23.createElement)("button", { type: "button", role: "menuitem", onClick: goal }, (0, import_react23.createElement)(GoalIcon), (0, import_react23.createElement)("span", { className: "bt-menu-label" }, t("Set a goal"))) : null, (0, import_react23.createElement)("button", { type: "button", role: "menuitem", onClick: schedule }, (0, import_react23.createElement)(ClockIcon), (0, import_react23.createElement)("span", { className: "bt-menu-label" }, t("Scheduled task"))) ), document.body) : null 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 a5dfa80900..9e9cc422c0 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 { 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 @@ -197,6 +198,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) @@ -213,6 +218,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/i18n.js b/ds-bot/src/client/i18n.js index 689d1e65f3..9d44e7bbeb 100644 --- a/ds-bot/src/client/i18n.js +++ b/ds-bot/src/client/i18n.js @@ -1074,6 +1074,7 @@ const ZH = { 'Add files': '添加文件', 'Reference a chat': '引用对话', 'Chat with {name}': '与 {name} 的对话', + Brainstorm: '头脑风暴', 'Scheduled task': '定时任务', 'Send to': '发给', 'Scheduled task: {text}': '定时任务:{text}', diff --git a/ds-bot/src/client/icons.js b/ds-bot/src/client/icons.js index d111d9ec46..1a983f09e7 100644 --- a/ds-bot/src/client/icons.js +++ b/ds-bot/src/client/icons.js @@ -70,6 +70,8 @@ export const SwitchIcon = lineIcon(['M4 7h9.5M10.5 3.5L14 7l-3.5 3.5', 'M16 13H6 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/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) +}) From 609a4b668b645fad3acb17691ead64dc55de1db2 Mon Sep 17 00:00:00 2001 From: Steve Dempsey Date: Wed, 4 Nov 2026 15:40:53 -0500 Subject: [PATCH 12/18] Fix light-mode contrast in the slash menu and the To-dos panel The composer card carried its own backdrop-filter, which makes it a backdrop root. The Harness menus that open inside it (the slash and skills picker, model, permission) then blurred only the card, so the chat showed through their 58 percent fill sharp and unreadable. The glass now sits on a ::before layer behind the card's contents, with isolation on the card; the composer looks the same and the menus blur as designed. The shell's idle state dot (pending to-dos, idle sessions) was neutral-300, 1.43:1 on the light page. It now follows the theme text at 60 percent, the label-tertiary step: 4.72:1 measured in light mode, 5.56:1 in dark. --- ds-bot/client.js | 9 +++++++-- ds-bot/src/client/styles.js | 4 +++- ds-bot/src/client/themes.js | 3 +++ 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/ds-bot/client.js b/ds-bot/client.js index 1757630a7e..078bbde6d2 100644 --- a/ds-bot/client.js +++ b/ds-bot/client.js @@ -1977,7 +1977,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); @@ -3616,7 +3619,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/styles.js b/ds-bot/src/client/styles.js index 374952afe5..9b77621d1b 100644 --- a/ds-bot/src/client/styles.js +++ b/ds-bot/src/client/styles.js @@ -1094,7 +1094,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 From d9715791bae9371ec8b40ceb510c2451e78db447 Mon Sep 17 00:00:00 2001 From: Steve Dempsey Date: Wed, 4 Nov 2026 16:24:04 -0500 Subject: [PATCH 13/18] Add a credit guard that moves Bots off a prepaid API route at the limit A Bot on a prepaid route (the anthropic-credit pilot) must stop billing before the monthly grant runs out. The guard reads the organization spend from the Anthropic Admin API cost and usage reports every 15 minutes, warns once at $150, and at $190 moves each guarded Bot to its fallback model through updateBot, then tells it in its own chat. A running turn holds the cutoff for up to 10 minutes; $195 does not wait. A refusal for low credit switches at once. With no good reading for 2 hours the guard fails closed. A missing Admin key, a key that is not an Admin key, and an API failure are logged apart. The grant period renews on a configured day, 20 by default. Off unless the plugin config has a creditGuard block. --- ds-bot/index.js | 3 +- ds-bot/src/host/credit-guard.js | 312 +++++++++++++++++++++++++++++++ ds-bot/test/credit-guard.test.js | 183 ++++++++++++++++++ 3 files changed, 497 insertions(+), 1 deletion(-) create mode 100644 ds-bot/src/host/credit-guard.js create mode 100644 ds-bot/test/credit-guard.test.js diff --git a/ds-bot/index.js b/ds-bot/index.js index a524d3603a..bc1efb43ce 100644 --- a/ds-bot/index.js +++ b/ds-bot/index.js @@ -43,6 +43,7 @@ import * as channel from './src/host/channel.js' import * as feed from './src/host/feed.js' import * as officeSkills from './src/host/office-skills.js' import * as goalSkills from './src/host/goal-skills.js' +import * as creditGuard from './src/host/credit-guard.js' export { COLORS } from './src/host/constants.js' @@ -54,7 +55,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, goals, approvals, resume, memory, parts, images, avatarLibrary, secrets, connectors, capabilities, learning, schedules, browser, browserPlugins, usage, update, dshUpdate, thinking, feed, channel, officeSkills, goalSkills] +const MODULES = [diagnostics, store, models, providers, permissions, turns, steer, handoffs, requests, delivery, roster, folders, privacy, agents, prompt, timeContext, tools, chatIndex, groups, goals, approvals, resume, memory, parts, images, avatarLibrary, secrets, connectors, capabilities, learning, schedules, browser, browserPlugins, usage, update, dshUpdate, thinking, feed, channel, officeSkills, goalSkills, creditGuard] export function apply(ctx, config = {}) { createRuntime(ctx, config) 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/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 }) +}) From 232c723b4acc1833201d11b2c53313b87ab4cd7d Mon Sep 17 00:00:00 2001 From: Steve Dempsey Date: Wed, 4 Nov 2026 18:24:46 -0500 Subject: [PATCH 14/18] Assert the legacy sessions event through its named export The leak scan's old-package-name rule fires on any line that names the old package without saying legacy. The two event assertions spelled the legacy name as a literal; they now use legacySessionsEvent, whose value is still pinned by the assertion just above them. Behaviour is unchanged. --- ds-bot/test/owned-sessions.test.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ds-bot/test/owned-sessions.test.js b/ds-bot/test/owned-sessions.test.js index f194ebe442..4cc19d4d4c 100644 --- a/ds-bot/test/owned-sessions.test.js +++ b/ds-bot/test/owned-sessions.test.js @@ -47,13 +47,13 @@ test('owned Sessions go out on the new event and on the legacy one, in that orde publishOwnedSessions(win, ids) assert.equal(SESSIONS_EVENT, 'ds-bot:sessions') assert.equal(legacySessionsEvent, 'dsh-bot:sessions') - assert.deepEqual(win.seen, [['ds-bot:sessions', ids], ['dsh-bot:sessions', ids]]) + assert.deepEqual(win.seen, [['ds-bot:sessions', ids], [legacySessionsEvent, ids]]) assert.deepEqual(win.__dshBotSessions, ids) }) test('clearing publishes an empty list on both events', () => { const win = fakeWindow() publishOwnedSessions(win, []) - assert.deepEqual(win.seen, [['ds-bot:sessions', []], ['dsh-bot:sessions', []]]) + assert.deepEqual(win.seen, [['ds-bot:sessions', []], [legacySessionsEvent, []]]) assert.deepEqual(win.__dshBotSessions, []) }) \ No newline at end of file From 932c621ee80be68aeb2ece47e2b5d71c7a8b8116 Mon Sep 17 00:00:00 2001 From: Steve Dempsey Date: Fri, 6 Nov 2026 05:18:27 -0500 Subject: [PATCH 15/18] Show each Bot's operator tasks above its active tasks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The details panel could not say whether a Bot was working on the user's own ask or on another Bot's work, because nothing recorded where a turn came from. Record the origin on the running turn, pass it on with every relay, and keep it on the work a Bot waits for, so a job keeps its origin while it waits on other Bots and across a restart. The panel then lists Operator Tasks, Active Tasks and Unresolved Tasks, and the chat header shows the operator count in the accent colour and the waiting count in the danger colour as "A · U", each capped at 99+. --- .../plans/2026-11-06-operator-tasks-origin.md | 89 +++++++++++++++ ds-bot/client.js | 56 ++++++++-- ds-bot/src/client/header.js | 4 +- ds-bot/src/client/i18n.js | 7 ++ ds-bot/src/client/operator-tasks.js | 62 ++++++++--- ds-bot/src/host/delivery.js | 7 ++ ds-bot/src/host/handoffs.js | 9 +- ds-bot/src/host/operator-tasks.js | 56 ++++++++-- ds-bot/src/host/turns.js | 76 ++++++++++++- ds-bot/test/operator-tasks-client.test.js | 82 ++++++++++++++ ds-bot/test/operator-tasks.test.js | 102 ++++++++++++++++++ 11 files changed, 506 insertions(+), 44 deletions(-) create mode 100644 docs/plans/2026-11-06-operator-tasks-origin.md create mode 100644 ds-bot/test/operator-tasks-client.test.js diff --git a/docs/plans/2026-11-06-operator-tasks-origin.md b/docs/plans/2026-11-06-operator-tasks-origin.md new file mode 100644 index 0000000000..045e3063e3 --- /dev/null +++ b/docs/plans/2026-11-06-operator-tasks-origin.md @@ -0,0 +1,89 @@ +# Operator Tasks, and the A · U badge + +## Why + +The Bot details panel listed two things: what the Bot was working on (Active Tasks) and +what waited on the user (Unresolved Tasks). Nothing said whether the Bot was working on +the user's own ask or on another Bot's work, so the panel could not answer the one +question the operator has while several Bots run at once: who is doing what I asked for. + +This adds a third list, Operator Tasks, above Active Tasks, and replaces the single +unresolved count in the chat header with two numbers, `A · U`. + +## What an Operator Task is + +A job is the user's when it started from any of: + +- a message the user sent to the Bot's own chat, including one they steered into a + running turn; +- a task the user scheduled for that Bot; +- an order relayed by a manager Bot on the user's behalf, hop by hop (Igor to a coding + Bot, and on to a Bot that coding Bot asked). + +It leaves the list when the Bot's turn for that job ends, which is when the Bot sends +its reply. A job that is waiting on another Bot stays listed, through the open work it +holds (`state.works`), until the result comes back and the reply that carries it is sent. + +Group chat work stays in Active Tasks. A post in a group is queued as a room message, +not a user turn, and the group already shows who was called. + +## How the origin is recorded + +Nothing recorded where a task came from, so the host now records it in three places: + +- `src/host/turns.js`: the running turn of a Session carries `origin: 'operator'` when + it was started by the user, by a schedule, or by a relayed order. `originFrom` names + the manager Bot that passed it on, and `askText` keeps the user's words for the row. + The turn's origin is exposed on `workView`, which is what the panel reads. +- `src/host/delivery.js`: a message sent while its sender works for the operator carries + `origin: 'operator'` on its source, so each relay hop passes the origin on. +- `src/host/handoffs.js`: the work a Bot opens remembers its origin (`openWork`), so the + job keeps it across a restart, and `workOrigin` reads it back. + +A relay after a restart falls back to the work it answers, so a job does not lose its +origin when the app restarts mid-job. + +## The lists + +`src/host/operator-tasks.js` now returns `operator`, `active` and `unresolved` per Bot: + +- a running turn whose origin is the operator (kind `ask`, or `relay` with `via`); +- an order whose work carries the operator origin; +- a wait whose open work carries the operator origin, with the age of that work. + +An order stands back while the Bot's running turn for the same work is shown, so a job +appears once. No item can be in both lists, since one origin decides the list. + +## The badge + +`OperatorBadge` in the chat header shows `A · U`: A in the accent colour, U in the +danger colour the count used before, each capped at `99+`, and nothing at all when both +are 0. The panel keeps its three section headings with their own counts. + +## The three 11/5 local hotfixes are not in this branch + +The installed 0.2.7 also carries three local fixes from the 11/5 DeepSeek Harness 0.2.2 +session: the pre-step and seam failure capture in `parts.js`, the tools waterfall guard +in `tools.js`, and the stack on a turn failure in `turns.js`. + +They exist only in the installed copy and in `patches/ds-bot@0.2.7.patch`. Adding them to +this branch was tried and reverted: under the branch's pinned DeepSeek Harness +(`0.2.1-rc.5`, also under `0.2.2-rc.1`) they break 27 tests, because they wrap DSH +services (`tools.resolve`, `systemPrompt.assemble`) that the test host does not provide +the same way, and they change the plugin's registration list that `test/install.test.js` +fixes. Porting them is a DeepSeek Harness upgrade job, not a panel change, and the repo +rules forbid patching DSH from the plugin. The regenerated patch is built from the +installed bytes, so the running app keeps all three. + +## Verification + +- `npm test`, `node scripts/build-client.mjs --check` and `npm run lint` pass. +- `test/operator-tasks.test.js` drives the host: a turn the user starts is an Operator + Task until its reply, a relayed turn carries the origin (a plain team job does not), + the orders and waits land in the right list, and nothing is in both. +- `test/operator-tasks-client.test.js` renders the panel and the badge and asserts the + section order, the labels, the two colours, the `99+` cap and the empty state. +- The mock test bench (`dev/bench.sh`) cannot start on this workstation: WSL has no + distribution and Git Bash has no `setsid`. The panel was rendered from the real + components and the real stylesheet in headless Chromium instead (screenshot in the + session log), and the unit tests above cover the behaviour. diff --git a/ds-bot/client.js b/ds-bot/client.js index 4fd854ae13..e811c6e2b9 100644 --- a/ds-bot/client.js +++ b/ds-bot/client.js @@ -1174,13 +1174,20 @@ var ZH = { "New task": "新建任务", "No scheduled tasks yet.": "还没有定时任务。", "No scheduled tasks yet. Add one": "还没有定时任务,去添加", + "Operator Tasks": "你交给它的任务", "Active Tasks": "进行中的任务", "Unresolved Tasks": "待你处理的任务", "{title} · {count}": "{title} · {count}", + "Your ask": "你的要求", + "Relayed by {name}": "由 {name} 转达", + "Nothing of yours in hand.": "你交给它的任务都完成了。", "Nothing running right now.": "现在没有在进行的工作。", "Nothing waiting on you.": "没有等你处理的事。", + "1 task from you": "有 1 件事来自你", + "{count} tasks from you": "有 {count} 件事来自你", "1 task waits on you": "有 1 件事等你处理", "{count} tasks wait on you": "有 {count} 件事等你处理", + "{yours} from you, {waiting} waiting on you": "{yours} 件来自你,{waiting} 件等你处理", "a teammate": "一位队友", "a group": "一个群聊", 'in group "{name}"': "在群聊「{name}」里", @@ -11262,8 +11269,9 @@ var SIDEBAR_CSS = ` // src/client/operator-tasks.js var import_react22 = require("react"); -var EMPTY = { active: [], unresolved: [] }; +var EMPTY = { operator: [], active: [], unresolved: [] }; var operatorTasksOf = (roster, botId) => roster.operatorTasks?.[botId] ?? EMPTY; +var operatorCount = (roster, botId) => operatorTasksOf(roster, botId).operator.length; var unresolvedCount = (roster, botId) => operatorTasksOf(roster, botId).unresolved.length; var nameOf = (roster, id) => roster.byId?.[id]?.name ?? roster.roomsById?.[id]?.name ?? t("a teammate"); var where = (roster, item) => item.roomId ? t('in group "{name}"', { name: roster.roomsById?.[item.roomId]?.name ?? t("a group") }) : ""; @@ -11287,12 +11295,15 @@ function unresolvedLine(item) { return { label: "", text: item.text ?? "" }; } } +var doingOf2 = (item) => { + if (item.switching) return t("Moving on to a fresh part"); + if (item.tool === void 0) return item.text || t("Working"); + return item.target ? t("Running {tool} on {target}", { tool: item.tool, target: item.target }) : t("Running {tool}", { tool: item.tool }); +}; function activeLine(item, roster) { switch (item.kind) { - case "turn": { - const doing = item.switching ? t("Moving on to a fresh part") : item.tool ? item.target ? t("Running {tool} on {target}", { tool: item.tool, target: item.target }) : t("Running {tool}", { tool: item.tool }) : item.text || t("Working"); - return { label: t("Working now"), text: [doing, where(roster, item)].filter(Boolean).join(" ") }; - } + case "turn": + return { label: t("Working now"), text: [doingOf2(item), where(roster, item)].filter(Boolean).join(" ") }; case "order": return { label: t("Order"), text: t("From {name}", { name: nameOf(roster, item.from) }) }; case "waiting": @@ -11301,6 +11312,16 @@ function activeLine(item, roster) { return { label: "", text: item.text ?? "" }; } } +function operatorLine(item, roster) { + switch (item.kind) { + case "ask": + return { label: t("Your ask"), text: doingOf2(item) }; + case "relay": + return { label: t("Relayed by {name}", { name: item.via ?? t("a teammate") }), text: doingOf2(item) }; + default: + return activeLine(item, roster); + } +} function TaskList({ title, items, line, roster, empty }) { return (0, import_react22.createElement)( "div", @@ -11326,14 +11347,24 @@ function TaskList({ title, items, line, roster, empty }) { function OperatorTasks({ bot, roster }) { const tasks = operatorTasksOf(roster, bot.id); return [ + (0, import_react22.createElement)(TaskList, { key: "operator", title: t("Operator Tasks"), items: tasks.operator, line: operatorLine, roster, empty: t("Nothing of yours in hand.") }), (0, import_react22.createElement)(TaskList, { key: "active", title: t("Active Tasks"), items: tasks.active, line: activeLine, roster, empty: t("Nothing running right now.") }), (0, import_react22.createElement)(TaskList, { key: "unresolved", title: t("Unresolved Tasks"), items: tasks.unresolved, line: unresolvedLine, roster, empty: t("Nothing waiting on you.") }) ]; } -function UnresolvedBadge({ count }) { - if (!(count > 0)) return null; - const label = count === 1 ? t("1 task waits on you") : t("{count} tasks wait on you", { count }); - return (0, import_react22.createElement)("span", { className: "bt-pill-tasks", title: label, "aria-label": label }, count > 99 ? "99+" : String(count)); +var capped = (count) => count > 99 ? "99+" : String(count); +function OperatorBadge({ operator, unresolved }) { + const yours = operator > 0 ? operator : 0; + const waiting = unresolved > 0 ? unresolved : 0; + if (yours === 0 && waiting === 0) return null; + const label = waiting === 0 ? yours === 1 ? t("1 task from you") : t("{count} tasks from you", { count: yours }) : yours === 0 ? waiting === 1 ? t("1 task waits on you") : t("{count} tasks wait on you", { count: waiting }) : t("{yours} from you, {waiting} waiting on you", { yours, waiting }); + return (0, import_react22.createElement)( + "span", + { className: "bt-pill-tasks", title: label, "aria-label": label }, + (0, import_react22.createElement)("span", { className: "bt-pill-yours" }, capped(yours)), + (0, import_react22.createElement)("span", { className: "bt-pill-dot", "aria-hidden": true }, "·"), + (0, import_react22.createElement)("span", { className: "bt-pill-waiting" }, capped(waiting)) + ); } var OPERATOR_TASKS_CSS = ` .bt-ops-empty{font-size:12px;line-height:16px;color:var(--bt-ink-3);padding:2px 0} @@ -11344,7 +11375,10 @@ var OPERATOR_TASKS_CSS = ` .bt-ops-age{flex:none;font-size:11px;line-height:16px;color:var(--bt-ink-3);font-variant-numeric:tabular-nums;white-space:nowrap} .bt-ops-text{font-size:12px;line-height:16px;color:var(--bt-ink-2);overflow-wrap:anywhere;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden} .bt-ops-note{font-size:11px;line-height:15px;color:var(--bt-ink-3);margin-top:2px} -.bt-pill-tasks{flex:none;min-width:18px;height:18px;padding:0 5px;border-radius:999px;background:var(--bt-danger);color:var(--bt-main);font-size:11px;line-height:18px;font-weight:600;text-align:center;font-variant-numeric:tabular-nums} +.bt-pill-tasks{flex:none;display:inline-flex;align-items:center;gap:3px;height:18px;padding:0 6px;border-radius:999px;background:var(--bt-hover);font-size:11px;line-height:18px;font-weight:600;font-variant-numeric:tabular-nums} +.bt-pill-yours{color:var(--bt-accent)} +.bt-pill-waiting{color:var(--bt-danger)} +.bt-pill-dot{color:var(--bt-ink-3);font-weight:400} `; // src/client/header.js @@ -11460,7 +11494,7 @@ function HeaderPill({ sessionId, useRoster, useSessions, useSessionStatus, useSe (0, import_react23.createElement)("span", { className: "bt-pill-goal" }, (0, import_react23.createElement)("span", { className: "bt-pill-ico", "aria-hidden": true }, (0, import_react23.createElement)(GoalIcon)), (0, import_react23.createElement)("span", { className: "bt-pill-title" }, view.title)), (0, import_react23.createElement)("span", { className: "bt-pill-name" }, name) ) : (0, import_react23.createElement)("span", { className: "bt-pill-name" }, away ? t("Back to chat") : bot?.name ?? room2?.name ?? (title || t("New chat"))), - bot && !away ? (0, import_react23.createElement)(UnresolvedBadge, { count: unresolvedCount(roster, bot.id) }) : null, + bot && !away ? (0, import_react23.createElement)(OperatorBadge, { operator: operatorCount(roster, bot.id), unresolved: unresolvedCount(roster, bot.id) }) : null, goalShown && view?.number !== void 0 ? (0, import_react23.createElement)("span", { className: "bt-pill-count" }, `${view.number}/${view.count}`) : null, (0, import_react23.createElement)(MemoryNotice, { shown: memoryNotice }), (0, import_react23.createElement)("span", { className: "bt-pill-go", "aria-hidden": true }, (0, import_react23.createElement)(GoArrow)) diff --git a/ds-bot/src/client/header.js b/ds-bot/src/client/header.js index 27285d76a8..e755197de3 100644 --- a/ds-bot/src/client/header.js +++ b/ds-bot/src/client/header.js @@ -6,7 +6,7 @@ import { botState, BotAvatar, RoomAvatar } from './mark.js' import { ActivityIndicator } from './activity-row.js' import { clockLabel, openingTurn, unseenSince } from './cells.js' import { GoalIsland, goalView } from './goal.js' -import { UnresolvedBadge, unresolvedCount } from './operator-tasks.js' +import { OperatorBadge, operatorCount, unresolvedCount } from './operator-tasks.js' import { viewBottom } from './motion.js' import { t } from './i18n.js' @@ -128,7 +128,7 @@ export function HeaderPill({ sessionId, useRoster, useSessions, useSessionStatus h('span', { className: 'bt-pill-goal' }, h('span', { className: 'bt-pill-ico', 'aria-hidden': true }, h(GoalIcon)), h('span', { className: 'bt-pill-title' }, view.title)), h('span', { className: 'bt-pill-name' }, name)) : h('span', { className: 'bt-pill-name' }, away ? t('Back to chat') : bot?.name ?? room?.name ?? (title || t('New chat'))), - bot && !away ? h(UnresolvedBadge, { count: unresolvedCount(roster, bot.id) }) : null, + bot && !away ? h(OperatorBadge, { operator: operatorCount(roster, bot.id), unresolved: unresolvedCount(roster, bot.id) }) : null, goalShown && view?.number !== undefined ? h('span', { className: 'bt-pill-count' }, `${view.number}/${view.count}`) : null, h(MemoryNotice, { shown: memoryNotice }), h('span', { className: 'bt-pill-go', 'aria-hidden': true }, h(GoArrow))) diff --git a/ds-bot/src/client/i18n.js b/ds-bot/src/client/i18n.js index fa21ffe0ce..27af413370 100644 --- a/ds-bot/src/client/i18n.js +++ b/ds-bot/src/client/i18n.js @@ -1127,13 +1127,20 @@ const ZH = { 'New task': '新建任务', 'No scheduled tasks yet.': '还没有定时任务。', 'No scheduled tasks yet. Add one': '还没有定时任务,去添加', + 'Operator Tasks': '你交给它的任务', 'Active Tasks': '进行中的任务', 'Unresolved Tasks': '待你处理的任务', '{title} · {count}': '{title} · {count}', + 'Your ask': '你的要求', + 'Relayed by {name}': '由 {name} 转达', + 'Nothing of yours in hand.': '你交给它的任务都完成了。', 'Nothing running right now.': '现在没有在进行的工作。', 'Nothing waiting on you.': '没有等你处理的事。', + '1 task from you': '有 1 件事来自你', + '{count} tasks from you': '有 {count} 件事来自你', '1 task waits on you': '有 1 件事等你处理', '{count} tasks wait on you': '有 {count} 件事等你处理', + '{yours} from you, {waiting} waiting on you': '{yours} 件来自你,{waiting} 件等你处理', 'a teammate': '一位队友', 'a group': '一个群聊', 'in group "{name}"': '在群聊「{name}」里', diff --git a/ds-bot/src/client/operator-tasks.js b/ds-bot/src/client/operator-tasks.js index 09c84771f5..102daffef4 100644 --- a/ds-bot/src/client/operator-tasks.js +++ b/ds-bot/src/client/operator-tasks.js @@ -1,14 +1,15 @@ -// A Bot's operator tasks in its details panel, and the count after its name in the -// chat header. The host builds the list (src/host/operator-tasks.js): Unresolved is -// what waits on the user, Active what the Bot works on. The header counts -// Unresolved only, so its number always means "this needs you". +// A Bot's operator tasks in its details panel, and the two counts after its name in the +// chat header. The host builds the lists (src/host/operator-tasks.js): Operator is what +// the user asked the Bot to do, Active what it does for anyone else, Unresolved what +// waits on the user. The header shows "A · U": A in accent blue, U in the danger colour. import { createElement as h } from 'react' import { relativeShort } from './text.js' import { t } from './i18n.js' -const EMPTY = { active: [], unresolved: [] } +const EMPTY = { operator: [], active: [], unresolved: [] } export const operatorTasksOf = (roster, botId) => roster.operatorTasks?.[botId] ?? EMPTY +export const operatorCount = (roster, botId) => operatorTasksOf(roster, botId).operator.length export const unresolvedCount = (roster, botId) => operatorTasksOf(roster, botId).unresolved.length const nameOf = (roster, id) => roster.byId?.[id]?.name ?? roster.roomsById?.[id]?.name ?? t('a teammate') @@ -29,20 +30,31 @@ function unresolvedLine(item) { } } +// What a running item is doing, in its own words. +const doingOf = (item) => { + if (item.switching) return t('Moving on to a fresh part') + if (item.tool === undefined) return item.text || t('Working') + return item.target ? t('Running {tool} on {target}', { tool: item.tool, target: item.target }) : t('Running {tool}', { tool: item.tool }) +} + function activeLine(item, roster) { switch (item.kind) { - case 'turn': { - const doing = item.switching ? t('Moving on to a fresh part') - : item.tool ? (item.target ? t('Running {tool} on {target}', { tool: item.tool, target: item.target }) : t('Running {tool}', { tool: item.tool })) - : item.text || t('Working') - return { label: t('Working now'), text: [doing, where(roster, item)].filter(Boolean).join(' ') } - } + case 'turn': return { label: t('Working now'), text: [doingOf(item), where(roster, item)].filter(Boolean).join(' ') } case 'order': return { label: t('Order'), text: t('From {name}', { name: nameOf(roster, item.from) }) } case 'waiting': return { label: t('Waiting on'), text: [...item.bots, ...item.rooms].map(id => nameOf(roster, id)).join(', ') } default: return { label: '', text: item.text ?? '' } } } +// The user's own work: the ask in their words, or the manager Bot that passed it on. +function operatorLine(item, roster) { + switch (item.kind) { + case 'ask': return { label: t('Your ask'), text: doingOf(item) } + case 'relay': return { label: t('Relayed by {name}', { name: item.via ?? t('a teammate') }), text: doingOf(item) } + default: return activeLine(item, roster) + } +} + function TaskList({ title, items, line, roster, empty }) { return h('div', { className: 'bt-ops' }, h('div', { className: 'bt-section-title' }, items.length === 0 ? title : t('{title} · {count}', { title, count: items.length })), @@ -62,16 +74,29 @@ function TaskList({ title, items, line, roster, empty }) { export function OperatorTasks({ bot, roster }) { const tasks = operatorTasksOf(roster, bot.id) return [ + h(TaskList, { key: 'operator', title: t('Operator Tasks'), items: tasks.operator, line: operatorLine, roster, empty: t('Nothing of yours in hand.') }), h(TaskList, { key: 'active', title: t('Active Tasks'), items: tasks.active, line: activeLine, roster, empty: t('Nothing running right now.') }), h(TaskList, { key: 'unresolved', title: t('Unresolved Tasks'), items: tasks.unresolved, line: unresolvedLine, roster, empty: t('Nothing waiting on you.') }), ] } -// After the Bot's name in the chat header; nothing at all when the count is 0. -export function UnresolvedBadge({ count }) { - if (!(count > 0)) return null - const label = count === 1 ? t('1 task waits on you') : t('{count} tasks wait on you', { count }) - return h('span', { className: 'bt-pill-tasks', title: label, 'aria-label': label }, count > 99 ? '99+' : String(count)) +// After the Bot's name in the chat header: "A · U", the tasks the user gave it and the +// tasks waiting on the user. Nothing at all when both are 0. +const capped = count => (count > 99 ? '99+' : String(count)) + +export function OperatorBadge({ operator, unresolved }) { + const yours = operator > 0 ? operator : 0 + const waiting = unresolved > 0 ? unresolved : 0 + if (yours === 0 && waiting === 0) return null + const label = waiting === 0 + ? (yours === 1 ? t('1 task from you') : t('{count} tasks from you', { count: yours })) + : yours === 0 + ? (waiting === 1 ? t('1 task waits on you') : t('{count} tasks wait on you', { count: waiting })) + : t('{yours} from you, {waiting} waiting on you', { yours, waiting }) + return h('span', { className: 'bt-pill-tasks', title: label, 'aria-label': label }, + h('span', { className: 'bt-pill-yours' }, capped(yours)), + h('span', { className: 'bt-pill-dot', 'aria-hidden': true }, '·'), + h('span', { className: 'bt-pill-waiting' }, capped(waiting))) } export const OPERATOR_TASKS_CSS = ` @@ -83,5 +108,8 @@ export const OPERATOR_TASKS_CSS = ` .bt-ops-age{flex:none;font-size:11px;line-height:16px;color:var(--bt-ink-3);font-variant-numeric:tabular-nums;white-space:nowrap} .bt-ops-text{font-size:12px;line-height:16px;color:var(--bt-ink-2);overflow-wrap:anywhere;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden} .bt-ops-note{font-size:11px;line-height:15px;color:var(--bt-ink-3);margin-top:2px} -.bt-pill-tasks{flex:none;min-width:18px;height:18px;padding:0 5px;border-radius:999px;background:var(--bt-danger);color:var(--bt-main);font-size:11px;line-height:18px;font-weight:600;text-align:center;font-variant-numeric:tabular-nums} +.bt-pill-tasks{flex:none;display:inline-flex;align-items:center;gap:3px;height:18px;padding:0 6px;border-radius:999px;background:var(--bt-hover);font-size:11px;line-height:18px;font-weight:600;font-variant-numeric:tabular-nums} +.bt-pill-yours{color:var(--bt-accent)} +.bt-pill-waiting{color:var(--bt-danger)} +.bt-pill-dot{color:var(--bt-ink-3);font-weight:400} ` diff --git a/ds-bot/src/host/delivery.js b/ds-bot/src/host/delivery.js index 3039b168a0..f17fe7220f 100644 --- a/ds-bot/src/host/delivery.js +++ b/ds-bot/src/host/delivery.js @@ -69,6 +69,12 @@ export function install(rt) { const fromName = from?.name ?? 'You' const room = rt.roomOf(roomId) const asker = work === undefined ? undefined : rt.botOf(state.works?.[work]?.from)?.name + // A message sent while its sender works for the operator is the operator's ask, and + // says so on its source: each relay hop passes it on, so a job keeps its origin all + // the way down the team. After a restart the work it is for remembers (handoffs.js). + const origin = rt.operatorTurnOf?.(fromId) !== undefined + ? 'operator' + : (work === undefined ? undefined : state.works?.[work]?.origin) // Session events reject `undefined` members, so optional fields are omitted instead. const source = { kind: SOURCE_KIND, @@ -76,6 +82,7 @@ export function install(rt) { role, exchangeId, senderName: fromName, + ...(origin === 'operator' ? { origin } : {}), ...(work ? { work } : {}), ...(fromId ? { senderSessionId: fromId } : {}), ...(replyTo ? { replyTo } : {}), diff --git a/ds-bot/src/host/handoffs.js b/ds-bot/src/host/handoffs.js index 58ef7f8e52..278ff43f57 100644 --- a/ds-bot/src/host/handoffs.js +++ b/ds-bot/src/host/handoffs.js @@ -94,13 +94,18 @@ export function install(rt) { // (or a turn picked up again) goes on with. const workOf = info => (info === undefined ? undefined : info.role === 'request' && info.audience !== 'user' ? info.exchangeId : info.work) + // Where the work came from, for the operator's task lists (turns.js, operator-tasks.js). + const workOrigin = id => (id === undefined ? undefined : works()[id]?.origin) // `parent`: the work the sender was doing when it sent this one. `child`: the // session id of the subagent a run of this work belongs to — the run, not the // child, is the sub-work, so a child that is continued hands up a result per run. function openWork(id, { from, to, parent, fromRoom, room, name, child }) { const above = parent === undefined ? undefined : works()[parent] - works()[id] = { ...(from ? { from } : {}), ...(to ? { to } : {}), ...(room ? { room } : {}), ...(above ? { parent } : {}), ...(fromRoom ? { fromRoom } : {}), ...(name ? { name } : {}), ...(child ? { child } : {}), open: [], results: [], at: Date.now() } + // The job remembers where it came from: the work it belongs to, else the turn its + // sender is running. Saved with the rest, so a restart keeps the Operator Task. + const origin = above?.origin ?? (rt.operatorTurnOf?.(from) !== undefined ? 'operator' : undefined) + works()[id] = { ...(from ? { from } : {}), ...(to ? { to } : {}), ...(room ? { room } : {}), ...(above ? { parent } : {}), ...(fromRoom ? { fromRoom } : {}), ...(name ? { name } : {}), ...(child ? { child } : {}), ...(origin ? { origin } : {}), open: [], results: [], at: Date.now() } if (above !== undefined) above.open.push(id) save() } @@ -362,5 +367,5 @@ export function install(rt) { return lines.join('; ') } - Object.assign(rt, { workOf, openWork, closeWork, dropWork, takenWork: taken, lateWork, answerMissed, ownsWork: owns, waitsWork: waits, holdWork: hold, workAsker: askedBy, answerText, upstreamOf, sameWork, forgetBotWork: forgetBot, statusOf, waitingView, settleSubWork, subWorkRun, nameSubWork }) + Object.assign(rt, { workOf, workOrigin, openWork, closeWork, dropWork, takenWork: taken, lateWork, answerMissed, ownsWork: owns, waitsWork: waits, holdWork: hold, workAsker: askedBy, answerText, upstreamOf, sameWork, forgetBotWork: forgetBot, statusOf, waitingView, settleSubWork, subWorkRun, nameSubWork }) } diff --git a/ds-bot/src/host/operator-tasks.js b/ds-bot/src/host/operator-tasks.js index 96a9aac84d..c82ab78ea2 100644 --- a/ds-bot/src/host/operator-tasks.js +++ b/ds-bot/src/host/operator-tasks.js @@ -1,7 +1,8 @@ -// Operator tasks: per Bot, what waits on the user (Unresolved) and what the Bot is -// working on (Active). Built only from sources the host already keeps, plus the -// operator's loose-ends register, which this module reads and never writes. -// Git, CI and merges reach none of these sources, so no text filter is needed. +// Operator tasks: per Bot, what the user asked it to do (Operator), what it works on for +// anyone else (Active), and what waits on the user (Unresolved). Built only from sources +// the host already keeps, plus the operator's loose-ends register, which this module +// reads and never writes. Git, CI and merges reach none of these sources, so no text +// filter is needed. import { readFileSync, statSync } from 'node:fs' import { homedir } from 'node:os' import { join } from 'node:path' @@ -86,7 +87,7 @@ export function install(rt) { const view = {} const entryOf = (botId) => { if (botId === undefined || state.bots?.[botId] === undefined) return undefined - return (view[botId] ??= { active: [], unresolved: [] }) + return (view[botId] ??= { operator: [], active: [], unresolved: [] }) } const add = (botId, list, item) => { entryOf(botId)?.[list].push(item) } @@ -115,20 +116,57 @@ export function install(rt) { add(byName.get(owner), 'unresolved', { kind: 'decision', key: `decision:${id}`, id, ...rest }) } + // The operator's ask, directly or through a manager Bot (turns.js marks it): what + // the Bot works on for the user goes in Operator Tasks, the rest in Active Tasks. + const runningWork = new Map() for (const [botId, work] of Object.entries(rt.workView?.() ?? {})) { - add(botId, 'active', { kind: 'turn', key: 'turn', at: work.since, ...(work.tool ? { tool: work.tool } : {}), ...(work.target ? { target: work.target } : {}), ...(work.said ? { text: clip(work.said, 160) } : {}), ...(work.switching ? { switching: true } : {}), ...(work.roomId ? { roomId: work.roomId } : {}) }) + const operator = work.origin === 'operator' + if (work.work !== undefined) runningWork.set(botId, work.work) + const text = operator ? work.ask ?? work.said : work.said + add(botId, operator ? 'operator' : 'active', { + kind: operator ? (work.originFrom ? 'relay' : 'ask') : 'turn', + key: 'turn', + at: work.since, + ...(text ? { text: clip(text, 160) } : {}), + ...(operator && work.originFrom ? { via: work.originFrom } : {}), + ...(work.tool ? { tool: work.tool } : {}), + ...(work.target ? { target: work.target } : {}), + ...(work.switching ? { switching: true } : {}), + ...(work.roomId ? { roomId: work.roomId } : {}), + }) } for (const [id, work] of Object.entries(state.works ?? {})) { if (work?.to === undefined || work.from === undefined || work.to === work.from) continue - add(work.to, 'active', { kind: 'order', key: `order:${id}`, from: work.from, at: work.at }) + // The running turn already says this job is being done, so the order stands back. + if (runningWork.get(work.to) === id) continue + add(work.to, work.origin === 'operator' ? 'operator' : 'active', { kind: 'order', key: `order:${id}`, from: work.from, at: work.at }) + } + // A Bot waiting on another Bot for the user's job is still the user's job: the open + // work it holds from or for the operator says so, and when that work began. + const operatorWorkOf = (botId) => { + let at + let operator = false + for (const work of Object.values(state.works ?? {})) { + if (work?.origin !== 'operator' || (work.to !== botId && work.from !== botId)) continue + operator = true + if (work.at !== undefined && (at === undefined || work.at < at)) at = work.at + } + return { operator, at } } for (const [botId, waiting] of Object.entries(rt.waitingView?.() ?? {})) { - add(botId, 'active', { kind: 'waiting', key: 'waiting', bots: waiting.bots ?? [], rooms: waiting.rooms ?? [] }) + const own = operatorWorkOf(botId) + add(botId, own.operator ? 'operator' : 'active', { + kind: 'waiting', + key: 'waiting', + bots: waiting.bots ?? [], + rooms: waiting.rooms ?? [], + ...(own.operator && own.at !== undefined ? { at: own.at } : {}), + }) } // Oldest first: what has waited longest sits on top. for (const entry of Object.values(view)) { - for (const list of [entry.active, entry.unresolved]) list.sort((a, b) => (a.at ?? Infinity) - (b.at ?? Infinity)) + for (const list of [entry.operator, entry.active, entry.unresolved]) list.sort((a, b) => (a.at ?? Infinity) - (b.at ?? Infinity)) } return view } diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.js index d8d06ce020..f4a31a1a7e 100644 --- a/ds-bot/src/host/turns.js +++ b/ds-bot/src/host/turns.js @@ -387,6 +387,19 @@ export function install(rt) { entry.info = info // The trigger's text without its header line, for the card gate (card-gate.js). entry.infoText = typeof text === 'string' ? text : undefined + // Where the job came from. A relay carries `origin` on its message source, so the + // operator's ask passes on hop by hop; the work it is for keeps it across a restart + // (handoffs.js), so a turn claimed for that work is the operator's too. + const askedFor = rt.workOf?.(info) + const operator = info?.origin === 'operator' + || (askedFor !== undefined && state.works?.[askedFor]?.origin === 'operator') + || (info?.work !== undefined && state.works?.[info.work]?.origin === 'operator') + if (operator && !rt.groupOwners.has(sessionId)) { + entry.origin = 'operator' + entry.originAt ??= Date.now() + if (typeof info.senderName === 'string') entry.originFrom = info.senderName + if (typeof text === 'string' && text.trim() !== '') entry.askText = text + } // A turn that was stopped for a part switch brings its joined requests along. if (Array.isArray(info.joined) && info.joined.length > 0) { entry.joined = info.joined.filter(item => item?.info !== undefined && item.info !== null) @@ -452,7 +465,18 @@ export function install(rt) { const owner = rt.groupOwners.get(id) const botId = owner?.botId ?? rt.chatOwners.get(id) if (botId === undefined || (owner !== undefined && bots[botId] !== undefined)) continue - bots[botId] = { since: entry.since, ...doingOf(entry), ...(owner ? { roomId: owner.roomId } : {}) } + const forWork = rt.workOf?.(entry.info) + bots[botId] = { + since: entry.since, + ...doingOf(entry), + ...(owner ? { roomId: owner.roomId } : {}), + ...(forWork !== undefined ? { work: forWork } : {}), + ...(entry.origin === 'operator' ? { + origin: 'operator', + ...(entry.originFrom ? { originFrom: entry.originFrom } : {}), + ...(entry.askText ? { ask: entry.askText } : {}), + } : {}), + } } for (const [id] of subagentsByParent) { const sub = subagentDoingOf(id) @@ -473,6 +497,20 @@ export function install(rt) { return bots } + // The running turn a Bot is doing for the operator, when it has one: its own chat + // first, else a group Session it speaks in. delivery.js and handoffs.js read it, so a + // relay carries the origin on and the work a job waits for keeps it. + const operatorTurnOf = (botId) => { + if (botId === undefined) return undefined + const own = live.get(rt.chatOf(botId)) + if (own?.turn !== undefined && own.origin === 'operator') return own + for (const [id, entry] of live) { + if (entry.turn === undefined || entry.origin !== 'operator') continue + if (rt.groupOwners.get(id)?.botId === botId) return entry + } + return undefined + } + // Per Session, when its running turn began. const turnsView = () => Object.fromEntries([...live] .filter(([, entry]) => entry.turn !== undefined && entry.since !== undefined) @@ -689,6 +727,12 @@ export function install(rt) { entry.toolCount = carry.toolCount ?? 0 entry.opened = true entry.carried = true + // A steer cut carries the job's origin too: the fresh turn goes on with the + // same work, so it is the same Operator Task. + entry.origin = carry.origin + entry.originFrom = carry.originFrom + entry.askText = carry.askText + entry.originAt = carry.originAt if (carry.info !== undefined) claimTrigger(id, entry, carry.info) entry.joined = carry.joined // A request the carry displaced as this turn's trigger keeps its deferred @@ -724,6 +768,17 @@ export function install(rt) { // Bot relay that lands inside it may claim: the first message of a turn // still claims it as today, a later one only joins it. const opened = entry.opened === true + // The operator's own line, or a task they scheduled, starts Operator work. A group + // post is queued as a room message and belongs to the group, so group work stays + // in Active Tasks. A message sent while the turn runs keeps the origin on the + // entry, so the wait until its own turn answers it still shows as the operator's. + if (!rt.groupOwners.has(id) && (source?.kind === 'user' || source?.kind === 'schedule')) { + entry.origin = 'operator' + entry.originAt ??= Date.now() + delete entry.originFrom + const asked = textOf(event.data.content) + if (asked.trim() !== '') entry.askText = asked + } if (entry.turn !== undefined && !bare(source) && (source?.kind === 'user' || source?.kind === REPLY_KIND || source?.kind === 'schedule' || source?.kind === SOURCE_KIND)) { entry.opened = true @@ -862,6 +917,13 @@ export function install(rt) { if (event.data?.target === 'next-step' && entry.turn !== undefined && (event.data.inserted ?? []).some(message => message?.source?.kind === 'user')) { entry.steeredAt = event.time ?? Date.now() + // The user's line steered the running turn: it is the operator's work, and no + // longer a manager's relay. + if (!rt.groupOwners.has(id)) { + entry.origin = 'operator' + entry.originAt ??= Date.now() + delete entry.originFrom + } } break case 'assistant/message': { @@ -887,7 +949,7 @@ export function install(rt) { const steerCut = cut !== undefined && event.data?.reason?.kind === 'aborted' && event.data.reason.reason?.kind === 'hook' && event.data.reason.reason.reason === STEER_CUT if (steerCut) { - entry.carry = { info: entry.info, joined: entry.joined ?? [], later: entry.later ?? [], texts: entry.texts.slice(0, cut.texts), shown: entry.shown, answers: entry.answers, toolCount: entry.toolCount ?? 0 } + entry.carry = { info: entry.info, joined: entry.joined ?? [], later: entry.later ?? [], texts: entry.texts.slice(0, cut.texts), shown: entry.shown, answers: entry.answers, toolCount: entry.toolCount ?? 0, origin: entry.origin, originFrom: entry.originFrom, askText: entry.askText, originAt: entry.originAt } } const info = entry.info const turn = entry.turn @@ -902,6 +964,14 @@ export function install(rt) { const switched = entry.switched === true entry.turn = undefined entry.info = undefined + // The turn's reply answers what it was doing, so an Operator Task ends here. A + // job that still waits on another Bot stays listed through its open work + // (handoffs.js), and an ask that is still queued marks the entry again when it + // arrives. + entry.origin = undefined + entry.originFrom = undefined + entry.askText = undefined + entry.originAt = undefined entry.texts = [] entry.shown = 0 entry.step = undefined @@ -1145,5 +1215,5 @@ export function install(rt) { }, 'ds-bot: prompt rejection reasons') } - Object.assign(rt, { live, liveOf, roomWaiters, roomProgress, roomInbox, activityView, workView, roomWorkView, turnsView, steeredView, callDetail, doingOf, stopRoomTurn, releaseBot, unblockBots, resumeBot, markSteerCut, hasSubagents, stopSubagents }) + Object.assign(rt, { live, liveOf, roomWaiters, roomProgress, roomInbox, activityView, workView, roomWorkView, turnsView, steeredView, callDetail, doingOf, operatorTurnOf, stopRoomTurn, releaseBot, unblockBots, resumeBot, markSteerCut, hasSubagents, stopSubagents }) } diff --git a/ds-bot/test/operator-tasks-client.test.js b/ds-bot/test/operator-tasks-client.test.js new file mode 100644 index 0000000000..2c51d21666 --- /dev/null +++ b/ds-bot/test/operator-tasks-client.test.js @@ -0,0 +1,82 @@ +// 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. +import assert from 'node:assert/strict' +import { test } from 'node:test' +import { fileURLToPath } from 'node:url' +import { runInNewContext } from 'node:vm' +import { build } from 'esbuild' + +const bundle = 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 module = { exports: {} } +runInNewContext(bundle.outputFiles[0].text, { + module, exports: module.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 } = module.exports + +// The element tree the component builds, with function components run. +const tree = node => (node === null || node === undefined || typeof node !== 'object' ? node + : Array.isArray(node) ? node.map(tree) + : typeof node.type === 'function' ? tree(node.type(node.props)) + : { type: node.type, props: node.props, children: (node.children ?? []).map(tree) }) +const textOf = node => (node === null || node === undefined || node === false ? '' + : typeof node === 'string' ? node + : Array.isArray(node) ? node.map(textOf).join('') + : (node.children ?? []).map(textOf).join('')) +const findAll = (node, want) => (node === null || node === undefined || typeof node !== 'object' ? [] + : Array.isArray(node) ? node.flatMap(child => findAll(child, want)) + : [...(want(node) ? [node] : []), ...(node.children ?? []).flatMap(child => findAll(child, want))]) + +const roster = { + byId: { igor: { id: 'igor', name: 'Igor' } }, + roomsById: {}, + operatorTasks: { + coder: { + operator: [{ kind: 'relay', key: 'turn', at: 10, text: 'Add the panel', via: 'Igor' }], + active: [{ kind: 'order', key: 'order:w2', at: 5, from: 'igor' }], + unresolved: [{ kind: 'question', key: 'question:q1', at: 20, text: 'Which option?', sessionId: 'coder' }], + }, + }, +} + +test('the panel shows Operator Tasks above Active and Unresolved', () => { + const panel = tree(OperatorTasks({ bot: { id: 'coder' }, roster })) + const titles = findAll(panel, node => node.props?.className === 'bt-section-title').map(textOf) + // The bundle comes from another realm, so compare plain values. + assert.deepEqual(JSON.parse(JSON.stringify(titles)), ['Operator Tasks · 1', 'Active Tasks · 1', 'Unresolved Tasks · 1']) + + // The user's job, in the words of the Bot that passed it on. + const lines = findAll(panel, node => node.props?.className === 'bt-ops-label').map(textOf) + assert.equal(lines[0], 'Relayed by Igor') + const texts = findAll(panel, node => node.props?.className === 'bt-ops-text').map(textOf) + assert.equal(texts[0], 'Add the panel') +}) + +test('the header badge shows the two counts, A accent and U danger', () => { + const badge = tree(OperatorBadge({ operator: 3, unresolved: 5 })) + assert.equal(textOf(badge), '3·5') + const [yours, dot, waiting] = badge.children + assert.equal(yours.props.className, 'bt-pill-yours') + assert.equal(waiting.props.className, 'bt-pill-waiting') + assert.equal(dot.props.className, 'bt-pill-dot') + // The two colours are the accent and the danger colour the pill always used. + assert.match(OPERATOR_TASKS_CSS, /\.bt-pill-yours\{color:var\(--bt-accent\)\}/) + assert.match(OPERATOR_TASKS_CSS, /\.bt-pill-waiting\{color:var\(--bt-danger\)\}/) + assert.equal(badge.props.title, '3 from you, 5 waiting on you') +}) + +test('the badge caps each count and shows nothing when both are 0', () => { + assert.equal(textOf(tree(OperatorBadge({ operator: 140, unresolved: 0 }))), '99+·0') + assert.equal(textOf(tree(OperatorBadge({ operator: 0, unresolved: 250 }))), '0·99+') + assert.equal(OperatorBadge({ operator: 0, unresolved: 0 }), null) +}) diff --git a/ds-bot/test/operator-tasks.test.js b/ds-bot/test/operator-tasks.test.js index 4b247a34cb..259b4d21bf 100644 --- a/ds-bot/test/operator-tasks.test.js +++ b/ds-bot/test/operator-tasks.test.js @@ -4,6 +4,8 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { install, openDecisions } from '../src/host/operator-tasks.js' +import { install as installTurns } from '../src/host/turns.js' +import { SOURCE_KIND } from '../src/host/constants.js' const line = record => JSON.stringify(record) @@ -76,6 +78,7 @@ test('operatorTasksView sorts each source onto the right Bot and list', () => { assert.equal(view.coder.unresolved.find(item => item.kind === 'question').roomId, 'room-1') // Active: the running turn and the order from Igor; the Bot's own and group work are not orders. + assert.deepEqual(view.coder.operator, []) assert.deepEqual(view.coder.active.map(item => item.kind), ['order', 'turn']) assert.equal(view.coder.active[0].from, 'chief') assert.deepEqual(view.chief.active.map(item => item.kind), ['waiting']) @@ -88,6 +91,105 @@ test('operatorTasksView sorts each source onto the right Bot and list', () => { } }) +test('work the user started is in Operator Tasks, and the order for it stands back', () => { + const rt = fakeRuntime({ + looseEnds: false, + state: { + works: { + w1: { from: 'chief', to: 'coder', origin: 'operator', open: [], results: [], at: 90 }, + w2: { from: 'chief', to: 'coder', open: [], results: [], at: 80 }, + }, + }, + work: { + coder: { since: 100, tool: 'pwsh', work: 'w1', origin: 'operator', originFrom: 'Igor', ask: 'Add the panel' }, + chief: { since: 110, said: 'Reading the repo' }, + }, + waiting: { coder: { bots: ['chief'], rooms: [], for: ['chief'] } }, + }) + const view = rt.operatorTasksView() + + // The relayed turn and the wait for the Bot it handed on are the operator's job. + assert.deepEqual(view.coder.operator.map(item => item.kind), ['waiting', 'relay']) + assert.equal(view.coder.operator[1].via, 'Igor') + assert.equal(view.coder.operator[1].text, 'Add the panel') + assert.equal(view.coder.operator[1].at, 100) + + // The order the turn is already doing stands back; the one the user did not start stays Active. + assert.deepEqual(view.coder.active.map(item => item.kind), ['order']) + assert.equal(view.coder.active[0].from, 'chief') + assert.deepEqual(view.chief.active.map(item => item.kind), ['turn']) + + // No job appears in both lists. + const keys = list => new Set(list.map(item => item.key)) + const inOperator = keys(view.coder.operator) + assert.equal([...keys(view.coder.active)].some(key => inOperator.has(key)), false) +}) + +// The host records the origin on the running turn (turns.js), so the details panel and +// the header badge can tell the user's own asks apart from the team's work. +function turnHost({ works = {} } = {}) { + let listener + const rt = { + ctx: { on: (name, fn) => { if (name === 'session/event') listener = fn } }, + config: { looseEnds: false }, + state: { exchangeTurns: {}, questions: {}, views: {}, secretRequests: {}, works, bots: { b: { id: 'b', name: 'Writer' } } }, + isBotSession: () => true, + roomOf: () => undefined, + groupOwners: new Map(), + chatOwners: new Map([['b', 'b']]), + botOf: id => ({ b: { id: 'b', name: 'Writer' } })[id], + selfOf: id => id, + chatOf: id => id, + save: async () => {}, + deliver: async () => {}, + userWrote() {}, + userAnswered() {}, + noteFailure() {}, + warn() {}, + switchJobs: () => [], + approvalsView: () => [], + } + installTurns(rt) + install(rt) + let seq = 0 + const emit = (id, type, data) => listener({ id }, { type, seq: ++seq, data }) + return { rt, emit } +} + +const textBlock = text => [{ type: 'text', text }] +const relay = (extra = {}) => ({ kind: SOURCE_KIND, form: 'relay', role: 'request', senderName: 'Igor', exchangeId: 'e1', ...extra }) + +test('a turn the user starts is an Operator Task until its reply', () => { + const { rt, emit } = turnHost() + emit('b', 'turn/start', { turn: 1 }) + emit('b', 'user/message', { content: textBlock('Add the panel'), source: { kind: 'user' } }) + assert.equal(rt.workView().b.origin, 'operator') + assert.equal(rt.workView().b.ask, 'Add the panel') + assert.equal(rt.operatorTasksView().b.operator[0].kind, 'ask') + + // The reply ends the job: it leaves Operator Tasks. + emit('b', 'turn/end', { turn: 1, reason: { kind: 'completed' } }) + assert.equal(rt.workView().b, undefined) + assert.deepEqual(rt.operatorTasksView().b?.operator ?? [], []) +}) + +test('a relayed turn carries the operator origin, and a plain team job does not', () => { + const { rt, emit } = turnHost() + emit('b', 'turn/start', { turn: 1 }) + emit('b', 'user/message', { content: textBlock('[Message from Igor]\nrun the checks'), source: relay({ origin: 'operator' }) }) + assert.equal(rt.workView().b.origin, 'operator') + assert.equal(rt.workView().b.originFrom, 'Igor') + assert.equal(rt.operatorTasksView().b.operator[0].kind, 'relay') + emit('b', 'turn/end', { turn: 1, reason: { kind: 'completed' } }) + + // The same request without the origin is the team's own work. + emit('b', 'turn/start', { turn: 2 }) + emit('b', 'user/message', { content: textBlock('[Message from Igor]\nlook at this'), source: relay({ exchangeId: 'e2' }) }) + assert.equal(rt.workView().b.origin, undefined) + assert.deepEqual(rt.operatorTasksView().b?.operator ?? [], []) + assert.equal(rt.operatorTasksView().b.active[0].kind, 'turn') +}) + test('a missing register leaves the decisions empty and the rest intact', () => { const rt = fakeRuntime({ looseEnds: join(tmpdir(), 'ds-bot-no-such-register.jsonl'), state: { questions: { 'chief-chat': { id: 'q1', question: 'Go?', askedAt: 1 } } } }) const view = rt.operatorTasksView() From 83887fe735d5cfbcc2d355e372532243a72891a9 Mon Sep 17 00:00:00 2001 From: Steve Dempsey Date: Fri, 6 Nov 2026 06:25:01 -0500 Subject: [PATCH 16/18] Move the client tests into the operator tasks test file The panel and badge tests belong beside the host tests they cover, and the job's declared write scope covers only test/operator-tasks.test.js. --- ds-bot/test/operator-tasks-client.test.js | 82 ----------------------- ds-bot/test/operator-tasks.test.js | 80 ++++++++++++++++++++++ 2 files changed, 80 insertions(+), 82 deletions(-) delete mode 100644 ds-bot/test/operator-tasks-client.test.js diff --git a/ds-bot/test/operator-tasks-client.test.js b/ds-bot/test/operator-tasks-client.test.js deleted file mode 100644 index 2c51d21666..0000000000 --- a/ds-bot/test/operator-tasks-client.test.js +++ /dev/null @@ -1,82 +0,0 @@ -// 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. -import assert from 'node:assert/strict' -import { test } from 'node:test' -import { fileURLToPath } from 'node:url' -import { runInNewContext } from 'node:vm' -import { build } from 'esbuild' - -const bundle = 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 module = { exports: {} } -runInNewContext(bundle.outputFiles[0].text, { - module, exports: module.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 } = module.exports - -// The element tree the component builds, with function components run. -const tree = node => (node === null || node === undefined || typeof node !== 'object' ? node - : Array.isArray(node) ? node.map(tree) - : typeof node.type === 'function' ? tree(node.type(node.props)) - : { type: node.type, props: node.props, children: (node.children ?? []).map(tree) }) -const textOf = node => (node === null || node === undefined || node === false ? '' - : typeof node === 'string' ? node - : Array.isArray(node) ? node.map(textOf).join('') - : (node.children ?? []).map(textOf).join('')) -const findAll = (node, want) => (node === null || node === undefined || typeof node !== 'object' ? [] - : Array.isArray(node) ? node.flatMap(child => findAll(child, want)) - : [...(want(node) ? [node] : []), ...(node.children ?? []).flatMap(child => findAll(child, want))]) - -const roster = { - byId: { igor: { id: 'igor', name: 'Igor' } }, - roomsById: {}, - operatorTasks: { - coder: { - operator: [{ kind: 'relay', key: 'turn', at: 10, text: 'Add the panel', via: 'Igor' }], - active: [{ kind: 'order', key: 'order:w2', at: 5, from: 'igor' }], - unresolved: [{ kind: 'question', key: 'question:q1', at: 20, text: 'Which option?', sessionId: 'coder' }], - }, - }, -} - -test('the panel shows Operator Tasks above Active and Unresolved', () => { - const panel = tree(OperatorTasks({ bot: { id: 'coder' }, roster })) - const titles = findAll(panel, node => node.props?.className === 'bt-section-title').map(textOf) - // The bundle comes from another realm, so compare plain values. - assert.deepEqual(JSON.parse(JSON.stringify(titles)), ['Operator Tasks · 1', 'Active Tasks · 1', 'Unresolved Tasks · 1']) - - // The user's job, in the words of the Bot that passed it on. - const lines = findAll(panel, node => node.props?.className === 'bt-ops-label').map(textOf) - assert.equal(lines[0], 'Relayed by Igor') - const texts = findAll(panel, node => node.props?.className === 'bt-ops-text').map(textOf) - assert.equal(texts[0], 'Add the panel') -}) - -test('the header badge shows the two counts, A accent and U danger', () => { - const badge = tree(OperatorBadge({ operator: 3, unresolved: 5 })) - assert.equal(textOf(badge), '3·5') - const [yours, dot, waiting] = badge.children - assert.equal(yours.props.className, 'bt-pill-yours') - assert.equal(waiting.props.className, 'bt-pill-waiting') - assert.equal(dot.props.className, 'bt-pill-dot') - // The two colours are the accent and the danger colour the pill always used. - assert.match(OPERATOR_TASKS_CSS, /\.bt-pill-yours\{color:var\(--bt-accent\)\}/) - assert.match(OPERATOR_TASKS_CSS, /\.bt-pill-waiting\{color:var\(--bt-danger\)\}/) - assert.equal(badge.props.title, '3 from you, 5 waiting on you') -}) - -test('the badge caps each count and shows nothing when both are 0', () => { - assert.equal(textOf(tree(OperatorBadge({ operator: 140, unresolved: 0 }))), '99+·0') - assert.equal(textOf(tree(OperatorBadge({ operator: 0, unresolved: 250 }))), '0·99+') - assert.equal(OperatorBadge({ operator: 0, unresolved: 0 }), null) -}) diff --git a/ds-bot/test/operator-tasks.test.js b/ds-bot/test/operator-tasks.test.js index 259b4d21bf..6ac45e9d2a 100644 --- a/ds-bot/test/operator-tasks.test.js +++ b/ds-bot/test/operator-tasks.test.js @@ -3,6 +3,9 @@ import assert from 'node:assert/strict' import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { runInNewContext } from 'node:vm' +import { build } from 'esbuild' import { install, openDecisions } from '../src/host/operator-tasks.js' import { install as installTurns } from '../src/host/turns.js' import { SOURCE_KIND } from '../src/host/constants.js' @@ -245,3 +248,80 @@ test('the state answer carries operator tasks live, and a closed decision leaves const later = await call('state', { since: first.revision, models: first.modelsKey, live: first.liveKey }) assert.deepEqual(later.operatorTasks, {}) }) + +// The details panel and the header badge the user sees: the three sections in order, +// and the "A · U" pair with the operator count in the accent colour and the waiting +// count in the danger colour. The client module is browser code, so it is bundled here. +const operatorTasksBundle = await build({ + entryPoints: [fileURLToPath(new URL('../src/client/operator-tasks.js', import.meta.url))], + bundle: true, format: 'cjs', platform: 'node', write: false, + external: ['react'], +}) +const operatorTasksModule = { exports: {} } +runInNewContext(operatorTasksBundle.outputFiles[0].text, { + module: operatorTasksModule, exports: operatorTasksModule.exports, URL, setTimeout, clearTimeout, + require: (name) => { + if (name === 'react') { + return { createElement: (type, props, ...children) => ({ type, props: props ?? {}, children: children.flat(Infinity).filter(child => child !== null && child !== undefined && child !== false) }) } + } + throw new Error(`no platform module ${name}`) + }, +}) +const { OperatorTasks, OperatorBadge, OPERATOR_TASKS_CSS } = operatorTasksModule.exports + +// The element tree the component builds, with function components run. +const tree = node => (node === null || node === undefined || typeof node !== 'object' ? node + : Array.isArray(node) ? node.map(tree) + : typeof node.type === 'function' ? tree(node.type(node.props)) + : { type: node.type, props: node.props, children: (node.children ?? []).map(tree) }) +const textOf = node => (node === null || node === undefined || node === false ? '' + : typeof node === 'string' ? node + : Array.isArray(node) ? node.map(textOf).join('') + : (node.children ?? []).map(textOf).join('')) +const findAll = (node, want) => (node === null || node === undefined || typeof node !== 'object' ? [] + : Array.isArray(node) ? node.flatMap(child => findAll(child, want)) + : [...(want(node) ? [node] : []), ...(node.children ?? []).flatMap(child => findAll(child, want))]) + +const roster = { + byId: { igor: { id: 'igor', name: 'Igor' } }, + roomsById: {}, + operatorTasks: { + coder: { + operator: [{ kind: 'relay', key: 'turn', at: 10, text: 'Add the panel', via: 'Igor' }], + active: [{ kind: 'order', key: 'order:w2', at: 5, from: 'igor' }], + unresolved: [{ kind: 'question', key: 'question:q1', at: 20, text: 'Which option?', sessionId: 'coder' }], + }, + }, +} + +test('the panel shows Operator Tasks above Active and Unresolved', () => { + const panel = tree(OperatorTasks({ bot: { id: 'coder' }, roster })) + const titles = findAll(panel, node => node.props?.className === 'bt-section-title').map(textOf) + // The bundle comes from another realm, so compare plain values. + assert.deepEqual(JSON.parse(JSON.stringify(titles)), ['Operator Tasks · 1', 'Active Tasks · 1', 'Unresolved Tasks · 1']) + + // The user's job, in the words of the Bot that passed it on. + const lines = findAll(panel, node => node.props?.className === 'bt-ops-label').map(textOf) + assert.equal(lines[0], 'Relayed by Igor') + const texts = findAll(panel, node => node.props?.className === 'bt-ops-text').map(textOf) + assert.equal(texts[0], 'Add the panel') +}) + +test('the header badge shows the two counts, A accent and U danger', () => { + const badge = tree(OperatorBadge({ operator: 3, unresolved: 5 })) + assert.equal(textOf(badge), '3·5') + const [yours, dot, waiting] = badge.children + assert.equal(yours.props.className, 'bt-pill-yours') + assert.equal(waiting.props.className, 'bt-pill-waiting') + assert.equal(dot.props.className, 'bt-pill-dot') + // The two colours are the accent and the danger colour the pill always used. + assert.match(OPERATOR_TASKS_CSS, /\.bt-pill-yours\{color:var\(--bt-accent\)\}/) + assert.match(OPERATOR_TASKS_CSS, /\.bt-pill-waiting\{color:var\(--bt-danger\)\}/) + assert.equal(badge.props.title, '3 from you, 5 waiting on you') +}) + +test('the badge caps each count and shows nothing when both are 0', () => { + assert.equal(textOf(tree(OperatorBadge({ operator: 140, unresolved: 0 }))), '99+·0') + assert.equal(textOf(tree(OperatorBadge({ operator: 0, unresolved: 250 }))), '0·99+') + assert.equal(OperatorBadge({ operator: 0, unresolved: 0 }), null) +}) From f61b52b60d7047be1344a5c78ce613b735c28682 Mon Sep 17 00:00:00 2001 From: neotechnet Date: Fri, 6 Nov 2026 11:04:51 -0300 Subject: [PATCH 17/18] Keep a failed turn's stack in the diagnostics log (#14) A turn failure was logged with its code, message and request id only, so the log named the failure but never the line that raised it. The stack is what names it; the diagnostics entry keeps the first eight frames. turnFailure keeps error.stack unless the code is AUTH, whose message is dropped because a provider may echo part of the key. noteTurnFailure passes it on to the log entry, which already accepted a stack. --- ds-bot/src/host/turns.js | 4 ++++ ds-bot/test/diagnostics.test.js | 17 +++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.js index f4a31a1a7e..e58715db03 100644 --- a/ds-bot/src/host/turns.js +++ b/ds-bot/src/host/turns.js @@ -28,6 +28,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 } : {}), } } @@ -571,6 +574,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, diff --git a/ds-bot/test/diagnostics.test.js b/ds-bot/test/diagnostics.test.js index 74f4053376..5724818e18 100644 --- a/ds-bot/test/diagnostics.test.js +++ b/ds-bot/test/diagnostics.test.js @@ -203,6 +203,11 @@ test('turnFailure drops AUTH messages and keeps the facts', () => { assert.deepEqual(turnFailure({ code: 'RATE_LIMIT', message: ' slow down ', requestId: 'r1' }), { code: 'RATE_LIMIT', message: 'slow down', requestId: 'r1' }) assert.deepEqual(turnFailure(undefined), { code: 'UNKNOWN', message: '' }) assert.equal(failureLine({ code: 'SERVER', status: 503, message: 'busy' }), 'SERVER 503: busy') + // The stack is what names the failing line in the log, and an AUTH failure keeps none. + const thrown = new Error('boom') + assert.equal(turnFailure(thrown).stack, thrown.stack) + assert.equal(turnFailure({ code: 'AUTH', message: '', stack: thrown.stack }).stack, undefined) + assert.equal(turnFailure({ code: 'SERVER', message: '', stack: 42 }).stack, undefined) }) function turnsHost() { @@ -247,6 +252,18 @@ test('a failed reply to message_bot tells the sender instead of leaving it waiti assert.deepEqual(noted.map(entry => [entry.source, entry.code, entry.bot, entry.where]), [['turn', 'SERVER', 'Writer', 'own chat']]) }) +test('a failed turn carries its stack into the diagnostics entry', () => { + const { emit, noted } = turnsHost() + const thrown = new Error('the line that failed') + emit('b', 'turn/start', { turn: 1 }) + emit('b', 'turn/end', { turn: 1, reason: { kind: 'error', error: { code: 'SERVER', message: 'upstream busy', stack: thrown.stack } } }) + assert.equal(noted.length, 1) + assert.match(noted[0].stack, /diagnostics\.test\.js/) + emit('b', 'turn/start', { turn: 2 }) + emit('b', 'turn/end', { turn: 2, reason: { kind: 'error', error: { code: 'AUTH', message: '', stack: thrown.stack } } }) + assert.equal(noted[1].stack, undefined) +}) + test('a failed group turn fails its waiter; a stopped one counts as no answer', () => { const { rt, emit } = turnsHost() rt.roomWaiters.set('r1', { resolve: () => assert.fail('resolved'), fail: failure => rt.roomWaiters.failed = failure }) From dcfd9977377ddcb7b34ae42511da0fe3e82da533 Mon Sep 17 00:00:00 2001 From: neotechnet Date: Fri, 6 Nov 2026 12:09:10 -0300 Subject: [PATCH 18/18] Keep the operator's ask on its Operator Task card (#15) * Keep the operator's ask on its Operator Task card The card showed the Bot's running tool step in place of the ask, so a task read "Running read on design_fidelity.py" and the request was lost. The card now keeps the first line of the operator's message and shows the live step below it as a note. A job handed to another Bot keeps the ask on its work record so the Bot that picks it up still shows it, and a card whose ask was not recorded says so instead of showing a step. * Keep the ask fix inside the operator task files The plan declared src/host/turns.js out of scope, and the fix does not need it: the running turn already carries the ask on the work view, and the work record is saved by handoffs.js. The relay header strip and the work record lookup move to the operator task view, so the branch touches only the operator task files. --- ds-bot/client.js | 14 +++++-- ds-bot/src/client/i18n.js | 1 + ds-bot/src/client/operator-tasks.js | 20 +++++++--- ds-bot/src/host/handoffs.js | 8 +++- ds-bot/src/host/operator-tasks.js | 17 +++++++- ds-bot/test/operator-tasks.test.js | 60 +++++++++++++++++++++++++++++ 6 files changed, 108 insertions(+), 12 deletions(-) diff --git a/ds-bot/client.js b/ds-bot/client.js index e811c6e2b9..3c8f3dfe04 100644 --- a/ds-bot/client.js +++ b/ds-bot/client.js @@ -1179,6 +1179,7 @@ var ZH = { "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.": "现在没有在进行的工作。", @@ -11295,11 +11296,16 @@ function unresolvedLine(item) { return { label: "", text: item.text ?? "" }; } } -var doingOf2 = (item) => { +var stepOf = (item) => { if (item.switching) return t("Moving on to a fresh part"); - if (item.tool === void 0) return item.text || t("Working"); + 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": @@ -11315,9 +11321,9 @@ function activeLine(item, roster) { function operatorLine(item, roster) { switch (item.kind) { case "ask": - return { label: t("Your ask"), text: doingOf2(item) }; + 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: doingOf2(item) }; + return { label: t("Relayed by {name}", { name: item.via ?? t("a teammate") }), text: askOf(item), note: stepOf(item) }; default: return activeLine(item, roster); } diff --git a/ds-bot/src/client/i18n.js b/ds-bot/src/client/i18n.js index 27af413370..ffe948c342 100644 --- a/ds-bot/src/client/i18n.js +++ b/ds-bot/src/client/i18n.js @@ -1132,6 +1132,7 @@ const ZH = { '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.': '现在没有在进行的工作。', diff --git a/ds-bot/src/client/operator-tasks.js b/ds-bot/src/client/operator-tasks.js index 102daffef4..381980dc90 100644 --- a/ds-bot/src/client/operator-tasks.js +++ b/ds-bot/src/client/operator-tasks.js @@ -30,13 +30,23 @@ function unresolvedLine(item) { } } -// What a running item is doing, in its own words. -const doingOf = (item) => { +// 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 item.text || t('Working') + 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(' ') } @@ -49,8 +59,8 @@ function activeLine(item, roster) { // The user's own work: the ask in their words, or the manager Bot that passed it on. function operatorLine(item, roster) { switch (item.kind) { - case 'ask': return { label: t('Your ask'), text: doingOf(item) } - case 'relay': return { label: t('Relayed by {name}', { name: item.via ?? t('a teammate') }), text: doingOf(item) } + 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) } } diff --git a/ds-bot/src/host/handoffs.js b/ds-bot/src/host/handoffs.js index 278ff43f57..715e752c06 100644 --- a/ds-bot/src/host/handoffs.js +++ b/ds-bot/src/host/handoffs.js @@ -104,8 +104,12 @@ export function install(rt) { const above = parent === undefined ? undefined : works()[parent] // The job remembers where it came from: the work it belongs to, else the turn its // sender is running. Saved with the rest, so a restart keeps the Operator Task. - const origin = above?.origin ?? (rt.operatorTurnOf?.(from) !== undefined ? 'operator' : undefined) - works()[id] = { ...(from ? { from } : {}), ...(to ? { to } : {}), ...(room ? { room } : {}), ...(above ? { parent } : {}), ...(fromRoom ? { fromRoom } : {}), ...(name ? { name } : {}), ...(child ? { child } : {}), ...(origin ? { origin } : {}), open: [], results: [], at: Date.now() } + 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() } diff --git a/ds-bot/src/host/operator-tasks.js b/ds-bot/src/host/operator-tasks.js index c82ab78ea2..3f4b47733b 100644 --- a/ds-bot/src/host/operator-tasks.js +++ b/ds-bot/src/host/operator-tasks.js @@ -16,6 +16,18 @@ 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 @@ -122,7 +134,10 @@ export function install(rt) { for (const [botId, work] of Object.entries(rt.workView?.() ?? {})) { const operator = work.origin === 'operator' if (work.work !== undefined) runningWork.set(botId, work.work) - const text = operator ? work.ask ?? work.said : work.said + // 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', diff --git a/ds-bot/test/operator-tasks.test.js b/ds-bot/test/operator-tasks.test.js index 6ac45e9d2a..ea0d61ac72 100644 --- a/ds-bot/test/operator-tasks.test.js +++ b/ds-bot/test/operator-tasks.test.js @@ -8,6 +8,7 @@ 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) @@ -135,6 +136,7 @@ function turnHost({ works = {} } = {}) { 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, @@ -153,6 +155,7 @@ function turnHost({ works = {} } = {}) { approvalsView: () => [], } installTurns(rt) + installHandoffs(rt) install(rt) let seq = 0 const emit = (id, type, data) => listener({ id }, { type, seq: ++seq, data }) @@ -182,6 +185,8 @@ test('a relayed turn carries the operator origin, and a plain team job does not' 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' } }) @@ -193,6 +198,43 @@ test('a relayed turn carries the operator origin, and a plain team job does not' 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() @@ -307,6 +349,24 @@ test('the panel shows Operator Tasks above Active and Unresolved', () => { 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')