Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Chat: hide raw [DECISIONS] blocks in older replies, show read-only chips (#138)
pixel-botcde9d66b4237
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5b182067..85b9b95c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -56,6 +56,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).its input (usually the task's own id given as evidence), the bot's corrected call asked again, so onechallenge could need two cards. The corrected call now goes through on the first card (at most twocorrections per stage), and the task's own id is no longer refused as evidence.+- **No raw `[DECISIONS]` text in older channel replies.** Replies saved in a team channel could end with+ the bot's raw `[DECISIONS] … [/DECISIONS]` block. The chat now hides it and shows its choices as+ read-only chips (a line it can't read is dropped, never shown); a block being typed live is hidden too.- **A restart no longer leaves an audit running.** An audit cut off mid-turn by a restart ends`interrupted` and says so in the task's history; one still waiting to start runs after the restart(or is skipped if the auditor was turned off).diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex d042f833..b8320638 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -41,7 +41,7 @@ import { routeReasonText } from '../routeReason';import { BudgetPausedNotice, HandoffCappedNotice, InterruptedNotice, SystemNotice } from './SystemNotice';import { chainBudgetApi, parseBudgetPaused, parseHandoffCapped } from '../chainBudget';import { isSystemNotice, parseInterruption, retryTargets } from '../interruptions';-import { consultedNames, parseDecisions, parseWorkAhead } from '../decideFirst';+import { consultedNames, hideStreamingDecisions, messageDecisions, parseWorkAhead } from '../decideFirst';import { approvalScrollAction, fullyVisible, isNearBottom, nextFollowing } from '../approvalVisibility';import { DecidingLine, DecisionChips, WorkAheadBody } from './Proactive';@@ -889,7 +889,10 @@ export const ChatView: React.FC<ChatViewProps> = ({const tokens = isUser ? null : replyTokens(msg.tokens_used, msg.meta);// Any auto-routed channel, not only #general: the server attaches `routing` wherever it picked the bot.const routed = isUser ? null : parseRoutingMeta(msg.meta);- const decisions = isUser ? [] : parseDecisions(msg.meta);+ // Older channel replies still hold a raw [DECISIONS] block: hidden here, its lines shown as chips+ const shownDecisions = isUser ? null : messageDecisions(msg.text, msg.meta);+ const decisions = shownDecisions?.decisions ?? [];+ const text = shownDecisions ? shownDecisions.text : msg.text;const workAhead = isUser ? null : parseWorkAhead(msg.meta);const displayName = isUser ? 'You' : (msg.sender_id && msg.sender_id.length > 20 ? title : msg.sender_id);@@ -969,7 +972,7 @@ export const ChatView: React.FC<ChatViewProps> = ({)}{/* Message Body Bubble */}- {!filesOnly && (msg.text.trim() || !files.length) && (+ {!filesOnly && (text.trim() || !files.length) && (<divclassName={`px-3.5 py-3 sm:p-5 rounded-2xl text-sm leading-relaxed shadow-sm w-full ${isUser@@ -983,9 +986,9 @@ export const ChatView: React.FC<ChatViewProps> = ({{isUser ? (<div className="whitespace-pre-wrap break-words">{renderFormattedText(msg.text)}</div>) : workAhead ? (- <WorkAheadBody messageId={msg.id} text={msg.text} />+ <WorkAheadBody messageId={msg.id} text={text} />) : (- <MarkdownRenderer content={msg.text} />+ <MarkdownRenderer content={text} />)}</div>)}@@ -996,7 +999,7 @@ export const ChatView: React.FC<ChatViewProps> = ({messageId={msg.id}decisions={decisions}consulted={consultedNames(msg.meta)}- onChange={onChangeDecision ? (index, picked) => onChangeDecision(msg, index, picked) : undefined}+ onChange={onChangeDecision && !shownDecisions?.readOnly ? (index, picked) => onChangeDecision(msg, index, picked) : undefined}/>)}@@ -1007,7 +1010,7 @@ export const ChatView: React.FC<ChatViewProps> = ({<div className="mt-1.5 flex items-center gap-2 text-zinc-500 text-xs max-w-full min-w-0"><buttontype="button"- onClick={() => handleCopy(msg.text, msg.id)}+ onClick={() => handleCopy(text, msg.id)}className="px-2 py-1 rounded-md hover:bg-zinc-900 hover:text-zinc-300 transition-colors flex items-center gap-1.5 text-[11px] cursor-pointer"title="Copy response">@@ -1322,7 +1325,7 @@ export const ChatView: React.FC<ChatViewProps> = ({: `${queued.speaker} is busy with other work; this starts as soon as one of those finishes.`}</p>) : streamingText ? (- <MarkdownRenderer content={stripDiscussionMarkers(streamingText)} isStreaming={true} />+ <MarkdownRenderer content={hideStreamingDecisions(stripDiscussionMarkers(streamingText))} isStreaming={true} />) : awaitingAnswer ? (<p className="text-zinc-400" role="status">{awaitingBrowserdiff --git a/frontend/src/decideFirst.ts b/frontend/src/decideFirst.tsindex ec6f43eb..e8d9ddb5 100644--- a/frontend/src/decideFirst.ts+++ b/frontend/src/decideFirst.ts@@ -42,6 +42,84 @@ export function parseDecisions(raw: unknown): Decision[] {return out;}+// ---------------------------------------------------------------------------+// A raw [DECISIONS] block left in a reply's text++// Messages saved before the server took the block off every reply (channel rounds skipped it)+// still carry it in their text. The chat hides it and, when meta has no decisions, shows the+// block's lines as read-only chips. Same line format as src/server/decide.rs parse_line.++const OPEN_RE = /\[DECISIONS\]/gi;+const CLOSE_RE = /\[\/DECISIONS\]/i;+const MAX_DECISIONS = 6;++function field(part: string, name: string): string | null {+ const i = part.indexOf(':');+ if (i < 0) return null;+ return part.slice(0, i).trim().toLowerCase() === name ? part.slice(i + 1).trim() : null;+}++function parseBlockLine(line: string): Omit<Decision, 'index'> | null {+ const parts = line.trim().replace(/^[-*•\s]+/, '').split('|');+ const get = (name: string) => parts.map((p) => field(p, name)).find((v) => v !== null) ?? null;+ const question = get('question');+ const optionsRaw = get('options');+ const pickedRaw = get('picked');+ if (!question || optionsRaw === null || pickedRaw === null) return null;+ const options = optionsRaw.split(';').map((o) => o.trim()).filter(Boolean);+ if (options.length < 2 || options.length > 6) return null;+ const norm = (s: string) => s.trim().replace(/^["“”.]+|["“”.]+$/g, '').toLowerCase();+ const picked = options.find((o) => norm(o) === norm(pickedRaw));+ if (!picked) return null;+ return { question, options, picked, why: get('why') ?? '', status: 'decided', changed_to: null };+}++/**+ * Takes the last `[DECISIONS] … [/DECISIONS]` block (or an unclosed one at the end) out of a+ * reply: the text without it, and its valid lines. Lines that don't parse are dropped, never+ * shown; two decisions run together on one line are split at "question:".+ */+export function takeDecisionsBlock(text: string): { text: string; decisions: Decision[] } {+ let start = -1;+ let tagLen = 0;+ for (const m of text.matchAll(OPEN_RE)) {+ start = m.index ?? -1;+ tagLen = m[0].length;+ }+ if (start < 0) return { text, decisions: [] };+ const after = text.slice(start + tagLen);+ const close = CLOSE_RE.exec(after);+ const body = close ? after.slice(0, close.index) : after;+ const rest = close ? after.slice(close.index + close[0].length).trim() : '';+ const decisions: Decision[] = [];+ for (const line of body.split('\n').flatMap((l) => l.split(/\s+(?=question\s*:)/i))) {+ const d = parseBlockLine(line);+ if (d && decisions.length < MAX_DECISIONS) decisions.push({ index: decisions.length, ...d });+ }+ const head = text.slice(0, start).trimEnd();+ return { text: (rest ? `${head}\n\n${rest}` : head).trim(), decisions };+}++/** While a reply streams in: hides a block being written, including a half-typed opening tag. */+export function hideStreamingDecisions(text: string): string {+ const shown = takeDecisionsBlock(text).text;+ if (shown !== text) return shown;+ const tail = /\[[A-Za-z]{0,9}$/.exec(text);+ return tail && '[DECISIONS'.startsWith(tail[0].toUpperCase()) ? text.slice(0, tail.index).trimEnd() : text;+}++/**+ * What a bot message shows: its text without a raw block, and its decisions. Decisions saved on+ * the message win and can be changed; ones read from the text are read-only (the Change route+ * only knows saved ones).+ */+export function messageDecisions(text: string, meta: unknown): { text: string; decisions: Decision[]; readOnly: boolean } {+ const saved = parseDecisions(meta);+ const taken = takeDecisionsBlock(text);+ if (saved.length) return { text: taken.text, decisions: saved, readOnly: false };+ return { text: taken.text, decisions: taken.decisions, readOnly: true };+}+/** What the chip says: the current choice. */export const decisionLabel = (d: Decision): string => (d.status === 'changed' ? `You chose: ${d.changed_to}` : `Decided: ${d.picked}`);diff --git a/frontend/tests/decisionsBlock.test.mjs b/frontend/tests/decisionsBlock.test.mjsnew file mode 100644index 00000000..639c99f0--- /dev/null+++ b/frontend/tests/decisionsBlock.test.mjs@@ -0,0 +1,106 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { readFileSync } from 'node:fs';+import { loadBundled } from './bundle.mjs';++const p = await loadBundled(`export * from './src/decideFirst';`);+const src = readFileSync(new URL('../src/components/ChatView.tsx', import.meta.url), 'utf8');++// The reply from Oleks's #general screenshot, as the channel round saved it+const REPLY = 'I updated the "Daily morning overview" with both. Next I expect you\'ll want a pick-up route.';+const BLOCK =+ '[DECISIONS]\n' ++ 'question: Arrival buffer for "Leave by" | options: 5 min; 10 min; 15 min | picked: 10 min | why: leaves time to park and walk in before 08:10\n' ++ 'question: Traffic section on days without school | options: Run Maps anyway; One-line "no school run" note | picked: One-line "no school run" note | why: next week is Herbstferien\n' ++ '[/DECISIONS]';++test('a raw block is hidden and its lines become read-only chips', () => {+ const r = p.messageDecisions(`${REPLY}\n\n${BLOCK}`, null);+ assert.equal(r.text, REPLY);+ assert.equal(r.readOnly, true);+ assert.equal(r.decisions.length, 2);+ assert.deepEqual(r.decisions[0], {+ index: 0,+ question: 'Arrival buffer for "Leave by"',+ options: ['5 min', '10 min', '15 min'],+ picked: '10 min',+ why: 'leaves time to park and walk in before 08:10',+ status: 'decided',+ changed_to: null,+ });+ assert.equal(r.decisions[1].picked, 'One-line "no school run" note');+});++test('decisions saved on the message win and stay changeable; the block is still hidden', () => {+ const saved = { index: 0, question: 'Q', options: ['A', 'B'], picked: 'B', why: '', status: 'decided', changed_to: null };+ const r = p.messageDecisions(`${REPLY}\n\n${BLOCK}`, JSON.stringify({ decisions: [saved] }));+ assert.equal(r.text, REPLY);+ assert.equal(r.readOnly, false);+ assert.deepEqual(r.decisions, [saved]);+});++test('two decisions run together on one line are split at "question:"', () => {+ const oneLine = BLOCK.replace('08:10\nquestion:', '08:10 question:');+ const r = p.takeDecisionsBlock(`${REPLY} ${oneLine}`);+ assert.equal(r.text, REPLY);+ assert.deepEqual(r.decisions.map((d) => d.picked), ['10 min', 'One-line "no school run" note']);+});++test('a malformed or unclosed block is hidden without chips, never shown raw', () => {+ for (const bad of [+ '[DECISIONS]\nquestion: Q | options: only one | picked: only one\n[/DECISIONS]',+ '[DECISIONS]\nquestion: Q | options: A; B | picked: C\n[/DECISIONS]',+ '[DECISIONS]\njust some words\n[/DECISIONS]',+ '[DECISIONS]\nquestion: Q | options: A; B',+ '[decisions] question: Q | options: A; B | picked: A [/decisions]',+ ]) {+ const r = p.messageDecisions(`${REPLY}\n\n${bad}`, null);+ assert.equal(r.text, REPLY, bad);+ assert.doesNotMatch(r.text, /DECISIONS/i);+ }+ // The last case is valid apart from the lowercase tags+ assert.equal(p.takeDecisionsBlock('[decisions] question: Q | options: A; B | picked: A [/decisions]').decisions.length, 1);+});++test('text after the block is kept, and normal text is untouched', () => {+ assert.equal(p.takeDecisionsBlock(`Before.\n${BLOCK}\nAfter.`).text, 'Before.\n\nAfter.');+ for (const t of ['Plain reply.', 'A [link](https://x.y) and [brackets]', '']) {+ const r = p.messageDecisions(t, null);+ assert.equal(r.text, t);+ assert.deepEqual(r.decisions, []);+ }+ // At most six chips, like the server+ const many = `[DECISIONS]\n${Array.from({ length: 8 }, (_, i) => `question: Q${i} | options: A; B | picked: A`).join('\n')}\n[/DECISIONS]`;+ assert.equal(p.takeDecisionsBlock(many).decisions.length, 6);+});++test('a block being streamed in is hidden, including a half-typed tag', () => {+ assert.equal(p.hideStreamingDecisions(`${REPLY}\n\n[DECISIONS]\nquestion: Arr`), REPLY);+ assert.equal(p.hideStreamingDecisions(`${REPLY}\n\n[DECIS`), REPLY);+ assert.equal(p.hideStreamingDecisions('See [the docs'), 'See [the docs');+ assert.equal(p.hideStreamingDecisions(REPLY), REPLY);+});++test('the chat renders the cleaned text and keeps client-read chips read-only', () => {+ assert.match(src, /messageDecisions\(msg\.text, msg\.meta\)/);+ assert.match(src, /<MarkdownRenderer content=\{text\} \/>/);+ assert.match(src, /onChangeDecision && !shownDecisions\?\.readOnly/);+ assert.match(src, /hideStreamingDecisions\(stripDiscussionMarkers\(streamingText\)\)/);+ assert.match(src, /handleCopy\(text, msg\.id\)/);+});++test('client-read chips render without a Change button', async () => {+ globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };+ const ui = await loadBundled(`+ import React from 'react';+ import { renderToStaticMarkup } from 'react-dom/server.browser';+ import { DecisionChips } from './src/components/Proactive';+ export const chips = (props) => renderToStaticMarkup(React.createElement(DecisionChips, props));+ `);+ const { decisions } = p.messageDecisions(`${REPLY}\n\n${BLOCK}`, null);+ const html = ui.chips({ messageId: 'm1', decisions });+ assert.match(html, /Decided: 10 min/);+ assert.match(html, /Decided: One-line "no school run" note/);+ assert.doesNotMatch(html, /Change/);+ assert.doesNotMatch(html, /DECISIONS/);+});