Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

Task board: Schedule | Board view on Tasks, derivation with tests, loop record, sidebar count, all 8 locales

Niko1221dca9770ef4f7
diff --git a/apps/host/src/app/TaskTree.tsx b/apps/host/src/app/TaskTree.tsx
index f24b29d43..3da952288 100644
--- a/apps/host/src/app/TaskTree.tsx
+++ b/apps/host/src/app/TaskTree.tsx
@@ -6,6 +6,7 @@ import { navigate, href, useLocation } from '../lib/router';
import { blankTask, type Task } from '../lib/tasks';
import { TaskEditor } from '../components/TaskEditor';
import { pushToast, setNavOpen } from '../lib/store';
+import { useBoard } from '../lib/use-board';
type TaskLeaf = Task & {
id: string;
};
@@ -14,6 +15,7 @@ export function TaskTree({ collapsed }: {
}) {
const [editor, setEditor] = useState<Task | null>(null);
const location = useLocation();
+ const { board } = useBoard();
const [open, setOpen] = useState(() => localStorage.getItem('strata.tasks-open') !== 'false');
const [tasks, setTasks] = useState<TaskLeaf[]>([]), [remove, setRemove] = useState<TaskLeaf | null>(null), [error, setError] = useState(''), [busy, setBusy] = useState(false);
const [leaving, setLeaving] = useState<string | null>(null);
@@ -76,8 +78,8 @@ export function TaskTree({ collapsed }: {
if (collapsed)
return dialogs;
return <section className="task-tree" aria-label={tr("Scheduled tasks")}>
- <div className="ws__head"><button className="navgroup__label task-tree__heading" aria-expanded={open} onClick={() => { setOpen(!open); localStorage.setItem('strata.tasks-open', String(!open)); }}>{tr("Tasks")}<Icon name="chevron" size={12} className={`ws__chev ${open ? 'is-open' : ''}`}/></button><div className="ws__tools"><IconBtn name="plus" title={tr("Add a task")} onClick={() => { setNavOpen(false); setEditor(blankTask()); }}/></div></div>
- {tr(open ? <div className="navsessions">{tr(tasks.map(t => <div className="ws__session row task-tree-row" data-leaving={leaving === t.id || undefined} key={t.id}><a className="navsession" href={href('tasks', t.id)} aria-current={location.route === 'tasks' && location.param === t.id ? 'page' : undefined} title={t.title}><span className="navsession__title">{t.title}</span>{tr(!t.enabled ? <Icon name="clock" size={12}/> : null)}</a><button className="st-btn st-btn--icon session-overflow" aria-label={tr("Edit task {0}", [t.title])} title={tr("Edit {0}", [t.title])} disabled={t.status === 'running'} onClick={() => { setNavOpen(false); setEditor({ ...t }); }}><Icon name="pencil" size={15}/></button><button className="st-btn st-btn--icon session-overflow" aria-label={tr("Delete task {0}", [t.title])} disabled={t.status === 'running'} title={tr(t.status === 'running' ? 'Stop this task before deleting' : `Delete ${t.title}`)} onClick={() => { setNavOpen(false); setRemove(t); setError(''); }}><Icon name="trash" size={15}/></button></div>))}{tr(!tasks.length ? <p className="small muted ws__empty">{tr("No tasks yet")}</p> : null)}{tr(error && !remove ? <p className="xs inline-error">{tr("Couldn\u2019t load tasks.")}</p> : null)}</div> : null)}
+ <div className="ws__head"><button className="navgroup__label task-tree__heading" aria-expanded={open} onClick={() => { setOpen(!open); localStorage.setItem('strata.tasks-open', String(!open)); }}>{tr("Tasks")}{tr(board.need ? <span className="navcount" title={tr("{0} need your attention", [board.need])}><span className="sr-only">{tr("{0} need your attention", [board.need])}</span><span aria-hidden="true">{board.need}</span></span> : null)}<Icon name="chevron" size={12} className={`ws__chev ${open ? 'is-open' : ''}`}/></button><div className="ws__tools"><IconBtn name="plus" title={tr("Add a task")} onClick={() => { setNavOpen(false); setEditor(blankTask()); }}/></div></div>
+ {tr(open ? <div className="navsessions"><div className="ws__session row task-tree-row"><a className="navsession" href="#/tasks?view=board" aria-current={location.route === 'tasks' && !location.param && location.query.get('view') === 'board' ? 'page' : undefined} onClick={() => setNavOpen(false)}><span className="navsession__title">{tr("Task board")}</span></a></div>{tr(tasks.map(t => <div className="ws__session row task-tree-row" data-leaving={leaving === t.id || undefined} key={t.id}><a className="navsession" href={href('tasks', t.id)} aria-current={location.route === 'tasks' && location.param === t.id ? 'page' : undefined} title={t.title}><span className="navsession__title">{t.title}</span>{tr(board.problemTasks.includes(t.id) ? <span className="navsession__dot navsession__dot--warn" role="img" aria-label={tr("Needs attention")} title={tr("Needs attention")}/> : null)}{tr(!t.enabled ? <Icon name="clock" size={12}/> : null)}</a><button className="st-btn st-btn--icon session-overflow" aria-label={tr("Edit task {0}", [t.title])} title={tr("Edit {0}", [t.title])} disabled={t.status === 'running'} onClick={() => { setNavOpen(false); setEditor({ ...t }); }}><Icon name="pencil" size={15}/></button><button className="st-btn st-btn--icon session-overflow" aria-label={tr("Delete task {0}", [t.title])} disabled={t.status === 'running'} title={tr(t.status === 'running' ? 'Stop this task before deleting' : `Delete ${t.title}`)} onClick={() => { setNavOpen(false); setRemove(t); setError(''); }}><Icon name="trash" size={15}/></button></div>))}{tr(!tasks.length ? <p className="small muted ws__empty">{tr("No tasks yet")}</p> : null)}{tr(error && !remove ? <p className="xs inline-error">{tr("Couldn\u2019t load tasks.")}</p> : null)}</div> : null)}
{dialogs}
</section>;
}
diff --git a/apps/host/src/components/TaskBoard.tsx b/apps/host/src/components/TaskBoard.tsx
new file mode 100644
index 000000000..43e3e67e5
--- /dev/null
+++ b/apps/host/src/components/TaskBoard.tsx
@@ -0,0 +1,202 @@
+import { useRef, useState, type ReactNode } from 'react';
+import { tr, localeTag } from '../lib/i18n';
+import { api } from '../lib/client';
+import { go, answerChatTool, continueChatInNewChat, continueTaskInNewChat, dismissChat, selectSession, stopChat, stopLoop } from '../lib/store';
+import { pushToast } from '../lib/store';
+import { askQuestion } from '../lib/ask';
+import { LOOP_MAX_FAILURES, loopEvery } from '../lib/loop';
+import { plainFailure } from '../lib/plain-errors';
+import { userError } from '../lib/format';
+import { type BoardAction, type BoardCard, type BoardColumn, type BoardReason } from '../lib/board';
+import { useBoard, refreshBoard } from '../lib/use-board';
+import { Btn, Icon, IconBtn, type IconName } from './ui';
+import { FloatingMenu } from './FloatingMenu';
+
+/**
+ * The task board: what is running, what waits for a yes, what found a problem and what finished, in four columns. The cards come from
+ * src/lib/board.ts; this file only draws them and calls the same endpoints and store functions the rest of the app uses. Cards are not
+ * dragged: they move by themselves when the facts change.
+ */
+
+const COLUMNS: { id: BoardColumn; name: string; hint?: string; tone: 'run' | 'wait' | 'bad' | 'done' }[] = [
+ { id: 'running', name: 'Running', tone: 'run' },
+ { id: 'waiting', name: 'Waiting for you', hint: 'Stopped at a question only you can answer.', tone: 'wait' },
+ { id: 'attention', name: 'Needs attention', hint: 'Found a problem. Stays here until you deal with it.', tone: 'bad' },
+ { id: 'done', name: 'Done', hint: 'Finished cleanly in the last 7 days.', tone: 'done' },
+];
+
+const ACTION: Record<BoardAction, { label: string; icon?: IconName }> = {
+ 'stop-task': { label: 'Stop', icon: 'stop' },
+ 'run-again': { label: 'Run again', icon: 'refresh' },
+ 'open-task': { label: 'Open task', icon: 'pencil' },
+ 'open-chat': { label: 'Open chat', icon: 'chat' },
+ 'stop-chat': { label: 'Stop chat', icon: 'stop' },
+ 'stop-loop': { label: 'Stop loop', icon: 'stop' },
+ approve: { label: 'Approve', icon: 'check' },
+ deny: { label: 'Deny' },
+ continue: { label: 'Continue in a new chat', icon: 'chat' },
+ dismiss: { label: 'Dismiss', icon: 'x' },
+ 'view-result': { label: 'View result' },
+};
+
+/* ------------------------------------------------------------------ words */
+
+/** "every 10 min": short enough for a card; whole hours keep the loop's own words ("every hour"). */
+const everyShort = (ms: number) => (ms % 3_600_000 === 0 || ms < 60_000 ? loopEvery(ms) : tr('every {0} min', [Math.round(ms / 60_000)]));
+
+const span = (ms: number) => {
+ const min = Math.floor(ms / 60_000);
+ if (min < 1) return tr('under 1 min');
+ if (min < 60) return tr('{0} min', [min]);
+ if (min < 48 * 60) return tr('{0} h', [Math.floor(min / 60)]);
+ return tr('{0} d', [Math.floor(min / 1440)]);
+};
+const ago = (ms: number) => (ms < 60_000 ? tr('just now') : tr('{0} ago', [span(ms)]));
+const clock = (at: number) => new Date(at).toLocaleTimeString(localeTag(), { hour: '2-digit', minute: '2-digit' });
+/** "today 07:00", "yesterday", "Mon 07:00" for a day that has a time on it. */
+function day(at: number, now: number) {
+ const d = new Date(at), n = new Date(now);
+ const midnight = (x: Date) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();
+ const days = Math.round((midnight(n) - midnight(d)) / 86_400_000);
+ if (days <= 0) return tr('today {0}', [clock(at)]);
+ if (days === 1) return tr('yesterday');
+ return d.toLocaleDateString(localeTag(), { weekday: 'short', day: 'numeric', month: 'short' });
+}
+
+export function cardTime(card: BoardCard, now: number): string {
+ switch (card.timeKind) {
+ case 'started': return tr('started {0}', [ago(now - card.at)]);
+ case 'waiting': return tr('waiting {0}', [span(now - card.at)]);
+ case 'next': return card.nextAt && card.nextAt > now ? tr('next in {0}', [span(card.nextAt - now)]) : tr('answering now');
+ case 'stopped': return tr('stopped {0}', [now - card.at < 86_400_000 ? clock(card.at) : day(card.at, now)]);
+ default: return card.source === 'task' ? day(card.at, now) : now - card.at < 86_400_000 ? ago(now - card.at) : day(card.at, now);
+ }
+}
+
+function ReasonText({ reason }: { reason: BoardReason }) {
+ let text = '', raw: string | undefined;
+ switch (reason.kind) {
+ case 'task-failed': case 'chat-failed': {
+ const plain = plainFailure(reason.detail ?? '');
+ const known = plain.kind !== 'plain';
+ text = known ? tr(plain.message) : tr(userError(String(reason.detail ?? '').slice(0, 240)) || 'It did not finish.');
+ // The words a person reads are the sentence; the original text stays one click away for experts.
+ raw = known ? (plain.detail ?? reason.detail) : undefined;
+ if (!known && !reason.detail) text = tr('It did not finish.');
+ break;
+ }
+ case 'task-stopped': text = tr('This run was stopped before it finished.'); break;
+ case 'task-closed': text = tr('Strata closed while this was running, so it did not finish.'); break;
+ case 'task-needs-yes': text = tr('Finished, but wanted to change something and could not ask. Nothing was changed.'); break;
+ case 'loop-failed': text = tr('Stopped: {0} runs in a row did not work.', [LOOP_MAX_FAILURES]); break;
+ default: text = reason.ask ? askQuestion(reason.ask) : reason.fallback ?? '';
+ }
+ return <span>{text}{raw ? <details className="bcard__detail"><summary>{tr('Details')}</summary><pre>{raw}</pre></details> : null}</span>;
+}
+
+/* ------------------------------------------------------------------- card */
+
+function Card({ card, now, busy, canRun, run, openMenu }: { card: BoardCard; now: number; busy: boolean; canRun: boolean; run: (card: BoardCard, action: BoardAction) => void; openMenu: (card: BoardCard, anchor: HTMLElement) => void }) {
+ const titleId = `bcard-${card.key.replace(/[^a-z0-9]+/gi, '-')}`;
+ const source = card.source === 'task' ? <><Icon name="clock" size={14}/>{tr('Scheduled task')}</> : card.source === 'chat' ? <><Icon name="chat" size={14}/>{tr('Chat')}</> : <><Icon name="refresh" size={14}/>{tr('Loop · {0}', [everyShort(card.everyMs ?? 0)])}</>;
+ const where = card.folder || card.meta ? <div className="bcard__where">{card.folder ? <><Icon name="folder" size={14}/>{card.folder}</> : null}{card.folder && card.meta ? ' · ' : ''}{card.meta ? tr(card.meta.text, card.meta.params) : null}</div> : null;
+ const button = (action: BoardAction, variant: 'primary' | 'secondary' | 'ghost') => {
+ const a = ACTION[action];
+ const off = busy || (action === 'run-again' && !canRun);
+ return <Btn key={action} size="sm" variant={variant} icon={variant === 'ghost' ? undefined : a.icon} disabled={off} title={action === 'run-again' && !canRun ? tr('Load a model first') : undefined} onClick={() => run(card, action)}>{tr(a.label)}</Btn>;
+ };
+ const iconFor = (action: BoardAction, label?: string) => <IconBtn key={action} name={ACTION[action].icon ?? 'x'} title={tr(label ?? ACTION[action].label)} disabled={busy} onClick={() => run(card, action)}/>;
+
+ let actions: ReactNode;
+ if (card.column === 'waiting') {
+ actions = card.approve
+ ? <>{button('approve', 'primary')}{button('deny', 'secondary')}<span className="spacer"/>{iconFor('open-chat')}</>
+ : <>{button(card.primary, 'secondary')}</>;
+ } else if (card.column === 'done') {
+ actions = <>{card.chip ? <span className={`bchip${card.chip.tone === 'good' ? ' bchip--good' : ''}`}><Icon name="check" size={12}/>{tr(card.chip.text)}</span> : null}<span className="spacer"/>{button(card.primary, 'ghost')}{iconFor('dismiss')}</>;
+ } else {
+ const variant = card.column === 'attention' ? 'primary' : 'secondary';
+ actions = <>{button(card.primary, variant)}<span className="spacer"/>
+ {card.menu.length === 1 ? iconFor(card.menu[0]) : card.menu.length > 1
+ ? <button type="button" className="st-btn st-btn--icon" aria-haspopup="menu" aria-label={tr('More actions for {0}', [card.title])} title={tr('More actions')} disabled={busy} onClick={e => openMenu(card, e.currentTarget)}><Icon name="ellipsis" size={19}/></button> : null}</>;
+ }
+
+ return <article className="bcard" aria-labelledby={titleId} data-source={card.source}>
+ <div className="bcard__top"><span className="bsrc">{source}</span><span className="btime">{cardTime(card, now)}</span></div>
+ <h3 className="bcard__title" id={titleId}>{card.title}</h3>
+ {where}
+ {card.line ? <p className="bcard__line">{card.line}</p> : null}
+ {card.reason ? <div className={`bcard__why bcard__why--${card.reason.tone}`}><Icon name={card.reason.tone === 'bad' ? 'error' : card.reason.tone === 'warn' ? 'warning' : 'shield'} size={16}/><ReasonText reason={card.reason}/></div> : null}
+ {card.busy ? <div className="bcard__bar bcard__bar--busy" aria-hidden="true"><i/></div> : null}
+ <div className="bcard__actions">{actions}</div>
+ </article>;
+}
+
+/* ------------------------------------------------------------------ board */
+
+export function TaskBoard({ query, canRun, onViewResult }: { query: string; canRun: boolean; onViewResult: (taskId: string) => void }) {
+ const { board, ready, tasks } = useBoard();
+ const [busy, setBusy] = useState<Record<string, boolean>>({});
+ const [menu, setMenu] = useState<{ card: BoardCard; anchor: HTMLElement } | null>(null);
+ const now = Date.now();
+ const q = query.trim().toLowerCase();
+ const shown = (list: BoardCard[]) => (q ? list.filter(c => `${c.title} ${c.line ?? ''} ${c.folder ?? ''}`.toLowerCase().includes(q)) : list);
+ const guard = useRef(new Set<string>());
+
+ async function run(card: BoardCard, action: BoardAction) {
+ if (guard.current.has(card.key)) return;
+ const task = card.source === 'task' ? tasks.find(t => t.id === card.id) : undefined;
+ const local = () => {
+ if (action === 'open-chat') { selectSession(card.id); go('chat', card.id); }
+ else if (action === 'open-task') go('tasks', card.id);
+ else if (action === 'view-result') onViewResult(card.id);
+ else if (action === 'stop-chat') stopChat(card.id);
+ else if (action === 'stop-loop') stopLoop(card.id);
+ else if (action === 'approve' || action === 'deny') { if (card.approve) answerChatTool(card.id, card.approve.messageId, card.approve.toolId, action === 'approve'); }
+ else if (action === 'continue') { if (task) continueTaskInNewChat(task); else continueChatInNewChat(card.id); }
+ else if (action === 'dismiss' && card.source !== 'task') dismissChat(card.id);
+ else return false;
+ return true;
+ };
+ if (local()) return;
+ guard.current.add(card.key);
+ setBusy(b => ({ ...b, [card.key]: true }));
+ try {
+ if (action === 'stop-task') await api.post(`/api/tasks/${card.id}/stop`);
+ else if (action === 'run-again') await api.post(`/api/tasks/${card.id}/run`);
+ else if (action === 'dismiss') await api.patch(`/api/tasks/${card.id}`, { ackedAt: new Date().toISOString() });
+ window.dispatchEvent(new Event('strata:tasks'));
+ } catch (e) {
+ pushToast('error', 'That did not work', e instanceof Error ? e.message : String(e));
+ } finally {
+ guard.current.delete(card.key);
+ setBusy(b => ({ ...b, [card.key]: false }));
+ refreshBoard();
+ }
+ }
+
+ const openMenu = (card: BoardCard, anchor: HTMLElement) => setMenu(m => (m?.card.key === card.key ? null : { card, anchor }));
+ const total = Object.values(board.columns).reduce((n, c) => n + c.length, 0);
+
+ return <div className="board-wrap">
+ <p className="board-note"><Icon name="info" size={16}/>{tr('Cards move on their own as things happen. A card in Needs attention stays there until you deal with it or dismiss it.')}</p>
+ <p className="sr-only" role="status" aria-live="polite">{board.need ? tr('{0} need your attention', [board.need]) : tr('Nothing needs you right now.')}</p>
+ <div className="board">
+ {COLUMNS.map(col => {
+ const cards = shown(board.columns[col.id]);
+ const headId = `bcol-${col.id}`;
+ return <section key={col.id} className={`bcol bcol--${col.id}`} data-tone={col.tone} aria-labelledby={headId}>
+ <div className="bcol__head"><span className="bcol__dot" aria-hidden="true"/><h2 className="bcol__name" id={headId}>{tr(col.name)}</h2><span className="bcol__count" aria-label={tr('{0} cards', [cards.length])}>{cards.length}</span></div>
+ {col.hint ? <p className="bcol__hint">{tr(col.hint)}</p> : null}
+ {cards.map(card => <Card key={card.key} card={card} now={now} busy={!!busy[card.key]} canRun={canRun} run={run} openMenu={openMenu}/>)}
+ {!cards.length ? <p className="bcol__empty">{ready ? tr(q && total ? 'No matching cards.' : 'Nothing here right now.') : tr('Loading tasks…')}</p> : null}
+ </section>;
+ })}
+ </div>
+ {board.upcoming.length ? <div className="upnext" role="region" aria-label={tr('Coming up')}><Icon name="clock" size={18}/><span className="navgroup__label">{tr('Coming up')}</span>
+ {board.upcoming.map((u, i) => <span className="upnext__item" key={u.id}>{i ? <span className="sep" aria-hidden="true"/> : null}<a href={`#/tasks/${u.id}`}>{u.title}</a> <span className="i">{day(u.at, now)}</span></span>)}</div> : null}
+ {menu ? <FloatingMenu anchor={menu.anchor} title={tr('More actions for {0}', [menu.card.title])} width={230} onClose={() => setMenu(null)}>
+ {menu.card.menu.map(action => <div key={action}>{action === 'dismiss' && menu.card.menu.length > 1 ? <hr className="board-menu-sep"/> : null}<button type="button" role="menuitem" className="menu__item" onClick={() => { const card = menu.card; setMenu(null); void run(card, action); }}><Icon name={ACTION[action].icon ?? 'x'}/>{tr(ACTION[action].label)}</button></div>)}
+ </FloatingMenu> : null}
+ </div>;
+}
diff --git a/apps/host/src/components/ui.tsx b/apps/host/src/components/ui.tsx
index 3297162b6..a319355fe 100644
--- a/apps/host/src/components/ui.tsx
+++ b/apps/host/src/components/ui.tsx
@@ -128,6 +128,7 @@ export function Seg<T extends string>({ value, options, onChange, ariaLabel, pan
options: {
value: T;
label: string;
+ icon?: IconName;
title?: string;
disabled?: boolean;
}[];
@@ -150,7 +151,7 @@ export function Seg<T extends string>({ value, options, onChange, ariaLabel, pan
onChange(options[next].value);
(e.currentTarget.parentElement?.children[next] as HTMLElement)?.focus();
}} title={tr(o.title)} onClick={() => onChange(o.value)}>
- {tr(o.label)}
+ {tr(o.icon ? <Icon name={o.icon}/> : null)}{tr(o.label)}
</button>)))}
</div>);
}
diff --git a/apps/host/src/lib/board.ts b/apps/host/src/lib/board.ts
new file mode 100644
index 000000000..7ad7c830a
--- /dev/null
+++ b/apps/host/src/lib/board.ts
@@ -0,0 +1,234 @@
+import type { Ask } from './ask';
+import type { Session, ToolCall } from './types';
+import type { Task } from './tasks';
+
+/**
+ * The task board (Tasks screen, "Board"). One pure function turns what the app already knows (scheduled tasks from the host, chats and
+ * their loops from the browser, the approvals the host is holding) into cards in four columns. Nothing here is stored as "board state":
+ * a card is where the facts put it, and it moves when the facts change. It never touches the DOM, the store or the clock, so it is tested
+ * like loop.ts.
+ *
+ * One card per thing: a chat shows once, in the first place that fits (waiting for you, running, needs attention, done), and a task
+ * shows once. A task or chat the person dismissed stays off the board until a newer run or turn brings a problem back.
+ */
+
+export type BoardColumn = 'running' | 'waiting' | 'attention' | 'done';
+
+/** What a button on a card does. The component maps each one to a call; the order of `menu` is the order shown. */
+export type BoardAction = 'stop-task' | 'run-again' | 'open-task' | 'open-chat' | 'stop-chat' | 'stop-loop' | 'approve' | 'deny' | 'continue' | 'dismiss' | 'view-result';
+
+/** Why a card needs the person. `kind` names the sentence; the component writes it in the person's language. */
+export interface BoardReason {
+ tone: 'bad' | 'warn' | 'ask';
+ kind: 'task-failed' | 'task-stopped' | 'task-closed' | 'task-needs-yes' | 'chat-failed' | 'loop-failed' | 'ask';
+ /** The original error text, for the failures a person can open under Details. */
+ detail?: string;
+ /** The approval question, for `ask`. */
+ ask?: Ask;
+ /** What the tool wants to do, when the host sent no question. */
+ fallback?: string;
+ params?: (string | number)[];
+}
+
+export interface BoardCard {
+ /** Stable across refreshes: the source and its id. */
+ key: string;
+ column: BoardColumn;
+ source: 'task' | 'chat' | 'loop';
+ /** Task id for a task; chat id for a chat or a loop. */
+ id: string;
+ title: string;
+ /** Milliseconds. What the time on the card is about, and the sort key (newest first). */
+ at: number;
+ timeKind: 'started' | 'waiting' | 'next' | 'stopped' | 'plain';
+ /** For a loop that is running: when its next answer is due. */
+ nextAt?: number;
+ /** A loop's rhythm in milliseconds, for "Loop · every 10 min". */
+ everyMs?: number;
+ folder?: string;
+ /** The muted part after the folder: "2 helpers working", "answer 3 of 6". */
+ meta?: { text: string; params?: (string | number)[] };
+ line?: string;
+ reason?: BoardReason;
+ /** Done cards: the chip beside the button. */
+ chip?: { text: string; tone: 'good' | 'plain' };
+ /** A card whose run is going on shows a moving bar. */
+ busy?: boolean;
+ primary: BoardAction;
+ menu: BoardAction[];
+ /** Set on a Waiting card that may be answered from the board (a file read or write inside the chat's folder). */
+ approve?: { messageId: string; toolId: string };
+}
+
+export interface BoardPending { chatId: string; callIds: string[]; at?: number; folder?: string | null }
+
+export interface BoardInput {
+ tasks: readonly Task[];
+ sessions: readonly Session[];
+ /** Chats with a turn going. */
+ liveChats: readonly string[];
+ /** Chats with a /loop going. */
+ loopChats: readonly string[];
+ /** What the host holds, per chat. `null` while it is not known (not asked yet or unreachable): the cards in the chats are trusted then. */
+ pending: readonly BoardPending[] | null;
+ activeSession: string | null;
+ now: number;
+ days?: number;
+}
+
+export interface BoardResult {
+ columns: Record<BoardColumn, BoardCard[]>;
+ /** Waiting for you plus Needs attention: the number the sidebar shows. */
+ need: number;
+ /** The next scheduled runs. */
+ upcoming: { id: string; title: string; at: number }[];
+ /** Task ids that have a problem the person has not dismissed (the sidebar's dot). */
+ problemTasks: string[];
+}
+
+export const BOARD_DAYS = 7;
+const DAY = 86_400_000;
+
+const time = (iso?: string | null) => { const n = iso ? Date.parse(iso) : NaN; return Number.isFinite(n) ? n : 0; };
+
+/** The last folder name of a path: how a chat's working folder is shown on a card. */
+export function folderName(path?: string | null): string | undefined {
+ const parts = String(path ?? '').split(/[\\/]+/).filter(Boolean);
+ return parts.length ? parts[parts.length - 1] : undefined;
+}
+
+const normal = (p: string) => p.replace(/\\/g, '/').replace(/\/+$/, '');
+
+/**
+ * Is `target` inside `folder`? Relative paths count (the agent works in the folder) unless they climb out with "..". Anything else
+ * (another drive, another tree, a path that cannot be told) is not: those need the whole conversation in front of the person.
+ */
+export function isInside(target: string | undefined | null, folder: string | undefined | null): boolean {
+ if (!target || !folder) return false;
+ const t = normal(String(target).trim()), f = normal(String(folder).trim());
+ if (!t || !f || t.split('/').includes('..')) return false;
+ const windows = /^[a-z]:/i.test(f) || String(folder).includes('\\');
+ const absolute = /^([a-z]:)?\//i.test(t);
+ if (!absolute) return !/^[a-z]:/i.test(t);
+ const a = windows ? t.toLowerCase() : t, b = windows ? f.toLowerCase() : f;
+ return a === b || a.startsWith(b + '/');
+}
+
+/** Can this waiting card be answered from the board? A file read or write inside the chat's folder; shell commands and connected tools open the chat. */
+export function canApproveOnBoard(tool: Pick<ToolCall, 'scope' | 'target'>, folder: string | undefined | null): boolean {
+ return (tool.scope === 'read' || tool.scope === 'write') && isInside(tool.target, folder);
+}
+
+/** One plain line from an answer: markdown off, first sentence (or two when the first is tiny), cut at 160 characters. */
+export function plainLine(text: string | undefined | null, max = 160): string {
+ let body = String(text ?? '').replace(/```[\s\S]*?```/g, ' ').replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/^\s*(#{1,6}|[-*+]|\d+[.)]|>)\s+/gm, '').replace(/[*_`~]/g, '');
+ body = body.replace(/\s+/g, ' ').trim();
+ if (!body) return '';
+ const sentence = /^.*?[.!?](?=\s|$)/.exec(body)?.[0] ?? body;
+ const two = /^.*?[.!?](?=\s|$)\s*.*?[.!?](?=\s|$)/.exec(body)?.[0] ?? body;
+ const pick = sentence.length < 24 && body.length > sentence.length ? two : sentence;
+ return pick.length > max ? `${pick.slice(0, max - 1).trimEnd()}…` : pick;
+}
+
+function lastAssistant(s: Session) {
+ for (let i = s.messages.length - 1; i >= 0; i--) { const m = s.messages[i]; if (m.role === 'assistant' && !(m as { local?: boolean }).local) return m; }
+ return undefined;
+}
+
+/** Dismissed: the person dismissed it at or after the moment of the thing shown. */
+const dismissed = (ackedAt: string | null | undefined, since: number) => !!ackedAt && time(ackedAt) >= since;
+
+export function boardCards(input: BoardInput): BoardResult {
+ const { now } = input, window = (input.days ?? BOARD_DAYS) * DAY;
+ const live = new Set(input.liveChats), loops = new Set(input.loopChats);
+ const columns: Record<BoardColumn, BoardCard[]> = { running: [], waiting: [], attention: [], done: [] };
+ const problemTasks: string[] = [];
+ const upcoming: BoardResult['upcoming'] = [];
+
+ /* ---- scheduled tasks ---- */
+ for (const t of input.tasks) {
+ if (t.archived || !t.id) continue;
+ const base = { key: `task:${t.id}`, source: 'task' as const, id: t.id, title: t.title };
+ const ran = time(t.lastRunAt), fin = time(t.finishedAt) || ran;
+ if (t.enabled && t.nextRunAt) upcoming.push({ id: t.id, title: t.title, at: time(t.nextRunAt) });
+ if (t.status === 'running') { columns.running.push({ ...base, column: 'running', at: ran, timeKind: 'started', line: plainLine(t.lastLine ?? '') || undefined, busy: true, primary: 'stop-task', menu: ['open-task'] }); continue; }
+ if (dismissed(t.ackedAt, fin)) continue;
+ const failed = t.status === 'error' || t.status === 'cancelled' || t.status === 'interrupted';
+ if (failed) {
+ problemTasks.push(t.id);
+ const kind = t.status === 'error' ? 'task-failed' : t.status === 'cancelled' ? 'task-stopped' : 'task-closed';
+ columns.attention.push({ ...base, column: 'attention', at: fin || ran, timeKind: 'plain', reason: { tone: 'bad', kind, ...(t.status === 'error' && t.error ? { detail: t.error } : {}) }, primary: 'run-again', menu: ['open-task', 'continue', 'dismiss'] });
+ } else if (t.attention) {
+ problemTasks.push(t.id);
+ // A run that was auto-denied: the useful next step is a chat that can carry on with the person's yes.
+ columns.attention.push({ ...base, column: 'attention', at: fin || ran, timeKind: 'plain', line: plainLine(t.lastLine ?? t.output) || undefined, reason: { tone: 'warn', kind: 'task-needs-yes', detail: t.attention }, primary: 'continue', menu: ['open-task', 'dismiss'] });
+ } else if (t.status === 'done' && fin && now - fin <= window) {
+ columns.done.push({ ...base, column: 'done', at: fin, timeKind: 'plain', line: plainLine(t.lastLine ?? t.output) || undefined, chip: { text: 'Finished', tone: 'good' }, primary: 'view-result', menu: ['dismiss'] });
+ }
+ }
+
+ /* ---- chats and loops ---- */
+ const pendingBy = new Map((input.pending ?? []).map(p => [p.chatId, p]));
+ for (const s of input.sessions) {
+ if (s.archived || s.showcase) continue;
+ const base = { id: s.id, title: s.title, folder: folderName(s.workspace) };
+ const answer = lastAssistant(s);
+
+ // Waiting for you: a card the host still holds.
+ const held = pendingBy.get(s.id);
+ let proposed: { messageId: string; tool: ToolCall } | undefined;
+ for (const m of s.messages) for (const tool of m.tools ?? []) if (tool.live && tool.state === 'proposed' && (input.pending === null || held?.callIds.includes(tool.id))) { proposed = { messageId: m.id, tool }; break; }
+ if (proposed) {
+ const { tool, messageId } = proposed;
+ const folder = held?.folder ?? s.workspace;
+ const ok = canApproveOnBoard(tool, folder);
+ columns.waiting.push({ ...base, key: `chat:${s.id}`, source: 'chat', column: 'waiting', at: held?.at || time(s.updatedAt), timeKind: 'waiting',
+ reason: { tone: 'ask', kind: 'ask', ...(tool.ask ? { ask: tool.ask } : {}), fallback: tool.effect || tool.preview || tool.name },
+ primary: ok ? 'approve' : 'open-chat', menu: ok ? ['deny', 'open-chat'] : [], ...(ok ? { approve: { messageId, toolId: tool.id } } : {}) });
+ continue;
+ }
+
+ // Running: a loop that is going, or a turn that is.
+ if (loops.has(s.id) && s.loop) {
+ const l = s.loop;
+ columns.running.push({ ...base, key: `loop:${s.id}`, source: 'loop', column: 'running', at: l.startedAt, timeKind: 'next', nextAt: live.has(s.id) ? undefined : l.nextAt, everyMs: l.everyMs, title: l.prompt || s.title,
+ meta: { text: l.maxRuns ? 'answer {0} of {1}' : 'answer {0}', params: l.maxRuns ? [l.answers + 1, l.maxRuns] : [l.answers + 1] }, line: plainLine(l.lastText) || undefined, busy: live.has(s.id), primary: 'stop-loop', menu: ['open-chat'] });
+ continue;
+ }
+ if (live.has(s.id)) {
+ const helpers = (s.agents ?? []).filter(a => a.status === 'working').length;
+ const lastUser = [...s.messages].reverse().find(m => m.role === 'user');
+ columns.running.push({ ...base, key: `chat:${s.id}`, source: 'chat', column: 'running', at: time(lastUser?.at) || time(s.updatedAt), timeKind: 'started', busy: true,
+ ...(helpers ? { meta: { text: helpers === 1 ? '1 helper working' : '{0} helpers working', params: [helpers] } } : {}), line: plainLine(answer?.content) || undefined, primary: 'open-chat', menu: ['stop-chat'] });
+ continue;
+ }
+
+ // A loop that ended (or that the window closed on) speaks for the whole chat.
+ if (s.loop) {
+ const l = s.loop;
+ const why = l.state === 'running' ? 'closed' : l.endedWhy ?? 'closed';
+ const when = l.endedAt ?? time(s.updatedAt);
+ if (dismissed(s.ackedAt, when) || now - when > window) continue;
+ const common = { ...base, key: `loop:${s.id}`, source: 'loop' as const, at: when, timeKind: 'stopped' as const, everyMs: l.everyMs, title: l.prompt || s.title, line: plainLine(l.lastText) || undefined };
+ if (why === 'failures') columns.attention.push({ ...common, column: 'attention', reason: { tone: 'bad', kind: 'loop-failed' }, primary: 'open-chat', menu: ['continue', 'dismiss'] });
+ else columns.done.push({ ...common, column: 'done', chip: why === 'stopped' ? { text: 'Stopped by you', tone: 'plain' } : why === 'closed' ? { text: 'Stopped when Strata closed', tone: 'plain' } : { text: 'Ended on its own', tone: 'plain' }, primary: 'open-chat', menu: ['dismiss'] });
+ continue;
+ }
+
+ // Chats: only what has something to do, in the window.
+ const when = time(s.updatedAt);
+ if (!when || now - when > window || dismissed(s.ackedAt, when) || !answer || answer.streaming) continue;
+ if (answer.error) {
+ columns.attention.push({ ...base, key: `chat:${s.id}`, source: 'chat', column: 'attention', at: when, timeKind: 'plain', reason: { tone: 'bad', kind: 'chat-failed', detail: answer.error }, primary: 'open-chat', menu: ['continue', 'dismiss'] });
+ continue;
+ }
+ const unread = s.id !== input.activeSession && (s.lastReadAt ? s.updatedAt > s.lastReadAt : s.messages.length > 0);
+ if (unread && answer.content?.trim() && s.messages[s.messages.length - 1] === answer) {
+ columns.done.push({ ...base, key: `chat:${s.id}`, source: 'chat', column: 'done', at: when, timeKind: 'plain', line: plainLine(answer.content) || undefined, chip: { text: 'Finished', tone: 'good' }, primary: 'open-chat', menu: ['dismiss'] });
+ }
+ }
+
+ for (const list of Object.values(columns)) list.sort((a, b) => b.at - a.at);
+ upcoming.sort((a, b) => a.at - b.at);
+ return { columns, need: columns.waiting.length + columns.attention.length, upcoming: upcoming.slice(0, 5), problemTasks };
+}
diff --git a/apps/host/src/lib/loop-runner.ts b/apps/host/src/lib/loop-runner.ts
index 6f489136c..22d66979e 100644
--- a/apps/host/src/lib/loop-runner.ts
+++ b/apps/host/src/lib/loop-runner.ts
@@ -1,4 +1,5 @@
import { tr } from './i18n';
+import type { LoopRecord } from './types';
import { LOOP_MAX_FAILURES, LOOP_MAX_RUNS, judgeAnswer, loopEndNote, loopEvery, loopLimitNote, withStopRule, type LoopLimits, type LoopStop } from './loop';
/**
@@ -20,6 +21,8 @@ export interface LoopHost {
now(): number;
setTimer(fn: () => void, ms: number): unknown;
clearTimer(handle: unknown): void;
+ /** Keep a small record of the loop on the chat (running, or how it ended) so the task board can show it. Optional: the tests do not need it. */
+ track?(sessionId: string, record: LoopRecord): void;
}
export interface LoopStart extends LoopLimits { everyMs: number; prompt: string }
@@ -30,6 +33,8 @@ interface LoopState extends LoopStart {
startedAt: number;
timer: unknown;
running: boolean;
+ lastText?: string;
+ nextAt?: number;
}
export class LoopScheduler {
@@ -41,6 +46,15 @@ export class LoopScheduler {
isRunning(sessionId: string | null): boolean { return !!sessionId && this.loops.has(sessionId); }
+ /** The chats that have a loop going. */
+ ids(): string[] { return [...this.loops.keys()]; }
+
+ private record(sessionId: string, loop: LoopState, endedWhy?: NonNullable<LoopRecord['endedWhy']>) {
+ const record: LoopRecord = { prompt: loop.prompt, everyMs: loop.everyMs, startedAt: loop.startedAt, state: endedWhy ? 'ended' : 'running', answers: loop.answers, ...(loop.maxRuns !== undefined ? { maxRuns: loop.maxRuns } : {}), ...(loop.lastText ? { lastText: loop.lastText } : {}) };
+ if (endedWhy) { record.endedAt = this.host.now(); record.endedWhy = endedWhy; } else if (loop.nextAt !== undefined) record.nextAt = loop.nextAt;
+ try { this.host.track?.(sessionId, record); } catch { /* the record is a courtesy to the board */ }
+ }
+
/** What the person is told for /loop with nothing after it. */
describe(sessionId: string): string | null {
const loop = this.loops.get(sessionId);
@@ -49,11 +63,15 @@ export class LoopScheduler {
return tr('A loop is running in this chat: it sends "{0}" {1}, while this chat is open. Type /loop stop to stop it.', [loop.prompt, loopEvery(loop.everyMs)]) + (limit ? ' ' + limit : '');
}
- stop(sessionId: string): boolean {
+ /** The person stopped it (/loop stop or the board's Stop loop). */
+ stop(sessionId: string): boolean { return this.end(sessionId, 'stopped'); }
+
+ private end(sessionId: string, why: NonNullable<LoopRecord['endedWhy']>): boolean {
const loop = this.loops.get(sessionId);
if (!loop) return false;
if (loop.timer) this.host.clearTimer(loop.timer);
this.loops.delete(sessionId);
+ this.record(sessionId, loop, why);
return true;
}
@@ -62,6 +80,7 @@ export class LoopScheduler {
if (this.loops.has(sessionId)) { this.host.note(sessionId, tr('This chat already has a loop. Type /loop stop first, then start a new one.')); return false; }
const loop: LoopState = { ...command, answers: 0, failures: 0, startedAt: this.host.now(), timer: null, running: false };
this.loops.set(sessionId, loop);
+ this.record(sessionId, loop);
const limit = loopLimitNote(loop);
this.host.note(sessionId, tr('Loop started: "{0}" {1}, while this chat is open. Type /loop stop to stop it. For work that must go on with Strata closed, use the Tasks screen.', [loop.prompt, loopEvery(loop.everyMs)]) + (limit ? ' ' + limit : ''));
await this.run(sessionId);
@@ -79,6 +98,7 @@ export class LoopScheduler {
// The person may have typed /loop stop while the answer was coming: nothing more happens then.
if (this.loops.get(sessionId) !== loop) return;
if (result.answered) {
+ loop.lastText = String(result.text ?? '').replace(/\s+/g, ' ').trim().slice(0, 200);
if (result.failed) loop.failures += 1; else { loop.failures = 0; loop.answers += 1; }
why = judgeAnswer(loop, loop, result, this.host.now());
}
@@ -94,13 +114,15 @@ export class LoopScheduler {
}
private finish(sessionId: string, loop: LoopState, why: LoopStop) {
- this.stop(sessionId);
+ this.end(sessionId, why);
this.host.note(sessionId, loopEndNote(why, loop.answers));
}
private schedule(sessionId: string, ms: number) {
const loop = this.loops.get(sessionId);
if (!loop) return;
+ loop.nextAt = this.host.now() + ms;
+ this.record(sessionId, loop);
loop.timer = this.host.setTimer(() => void this.tick(sessionId), ms);
}
@@ -108,7 +130,7 @@ export class LoopScheduler {
const loop = this.loops.get(sessionId);
if (!loop) return;
loop.timer = null;
- if (!this.host.exists(sessionId)) { this.stop(sessionId); return; }
+ if (!this.host.exists(sessionId)) { this.end(sessionId, 'stopped'); return; }
// The time is up, or the count is reached: never fire again, even if the last answer was not judged (a busy chat).
if (loop.maxMs !== undefined && this.host.now() - loop.startedAt >= loop.maxMs) { this.finish(sessionId, loop, 'time'); return; }
if (loop.maxRuns !== undefined && loop.answers >= loop.maxRuns) { this.finish(sessionId, loop, 'count'); return; }
diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.ts
index 6613a8d98..74ee2b48e 100644
--- a/apps/host/src/lib/store.ts
+++ b/apps/host/src/lib/store.ts
@@ -16,7 +16,7 @@ import { photoData, uploadChatPhotos, photoHistorySlots, pendingChatPhotos, take
import { applyNativeEvent, nativeState } from './native';
import { pictureStatus } from './pictures';
import { noModelNotice } from './no-model';
-import { taskHandoverMessage, taskHandoverTitle } from './task-handover';
+import { taskHandoverMessage, taskHandoverTitle, chatHandoverMessage, chatHandoverTitle } from './task-handover';
import type { Task } from './tasks';
import { postWithFolderFallback } from './folder-pick';
import { setTranslationLanguage, tr, validLanguage, type Language } from './i18n';
@@ -1475,10 +1475,55 @@ const loopScheduler = new LoopScheduler({
now: () => Date.now(),
setTimer: (fn, ms) => setTimeout(fn, ms),
clearTimer: handle => clearTimeout(handle as ReturnType<typeof setTimeout>),
+ track: (sessionId, loop) => patchSession(sessionId, s => ({ ...s, loop })),
});
export function loopIsRunning(sessionId: string | null): boolean { return loopScheduler.isRunning(sessionId); }
+/* ------------------------------------------------------------- task board */
+
+/** The chats with a turn going, and the chats with a loop going: what the board needs besides the sessions themselves. */
+export function liveChatIds(): string[] { return [...liveTurns.keys()]; }
+export function loopChatIds(): string[] { return loopScheduler.ids(); }
+
+/** Stop any chat's turn, not only the open one (the board's Stop). Same two-step as stopStreaming. */
+export function stopChat(id: string) {
+ const turn = liveTurns.get(id);
+ if (!turn) return;
+ const abort = () => { turn.abort.abort(); };
+ void api.post<{ stopped: boolean }>('/api/chat/stop', { sessionId: id }).then(
+ result => { if (!result.stopped) abort(); else setTimeout(() => { if (liveTurns.get(id) === turn) abort(); }, 30000); },
+ abort,
+ );
+}
+
+/** Stop a chat's loop from the board. The chat gets the same line /loop stop writes. */
+export function stopLoop(id: string) {
+ if (loopScheduler.stop(id)) addNote(id, tr('The loop is stopped.'));
+}
+
+/** Dismiss a chat's (or its loop's) card: it leaves the board until something newer goes wrong. The chat itself is untouched. */
+export function dismissChat(id: string) {
+ const sessions = state.sessions.map(s => (s.id === id ? { ...s, ackedAt: new Date().toISOString() } : s));
+ persistSessions(sessions);
+ set({ sessions });
+}
+
+/** Answer a waiting tool card in any chat (the board's Approve and Deny). Only a live card has an approval behind it. */
+export function answerChatTool(sessionId: string, messageId: string, toolId: string, approved: boolean) {
+ const tool = state.sessions.find(s => s.id === sessionId)?.messages.find(m => m.id === messageId)?.tools?.find(t => t.id === toolId);
+ if (tool?.live && tool.state === 'proposed') answerAgentTool(sessionId, messageId, tool, approved);
+}
+
+/** "Continue in a new chat" on a chat or a loop that went wrong: a new chat that starts from what happened (src/lib/task-handover.ts). */
+export function continueChatInNewChat(sessionId: string) {
+ const old = state.sessions.find(s => s.id === sessionId);
+ if (!old) return;
+ const session = newSession();
+ go('chat', session.id);
+ void sendMessage(chatHandoverMessage(old), { title: chatHandoverTitle(old), markdown: true });
+}
+
async function runLoopCommand(command: LoopCommand) {
const sessionId = state.activeSession ?? newSession().id;
const say = (content: string) => { addNote(sessionId, content); go('chat', sessionId); };
@@ -1805,6 +1850,12 @@ export function bootOnce() {
if ((globalThis as { __strataBooted?: boolean }).__strataBooted) return;
(globalThis as { __strataBooted?: boolean }).__strataBooted = true;
for (const session of state.sessions) for (const run of session.timeSkips ?? []) { scheduleTimeSkip(session.id, run); if (run.job && !run.completedAt) { markTurn(session.id, { abort: new AbortController(), agent: false }); void followTimeSkip(session.id, run.id); } }
+ // A loop lives in the window: one the last window left "running" has ended, and the board says so.
+ if (state.sessions.some(s => s.loop?.state === 'running')) {
+ const sessions = state.sessions.map(s => s.loop?.state === 'running' ? { ...s, loop: { ...s.loop, state: 'ended' as const, endedWhy: 'closed' as const, endedAt: Date.parse(s.updatedAt) || Date.now() } } : s);
+ persistSessions(sessions);
+ set({ sessions });
+ }
void bootstrap();
void reconcileAgentTools();
}
diff --git a/apps/host/src/lib/task-handover.ts b/apps/host/src/lib/task-handover.ts
index ff3d5d5dd..8301d09f5 100644
--- a/apps/host/src/lib/task-handover.ts
+++ b/apps/host/src/lib/task-handover.ts
@@ -1,5 +1,8 @@
import { tr, localeTag } from './i18n';
import type { Task } from './tasks';
+import type { Session } from './types';
+import { loopEndNote } from './loop';
+import { sessionTitle } from './session-title';
/**
* "Continue in a new chat" on a task: the first message of the new chat. It carries what the task found, what it did and the files it made, in the
@@ -42,3 +45,26 @@ export function taskHandoverMessage(task: Task): string {
parts.push(tr('Please help me take it from here.'));
return parts.join('\n\n');
}
+
+export const chatHandoverTitle = (session: Pick<Session, 'title' | 'messages' | 'defaultTitle'>) => tr('Continuing from the chat “{0}”', [sessionTitle(session)]);
+
+/**
+ * "Continue in a new chat" on a chat or a loop that went wrong (the board): what was asked last, what went wrong or what the last answer
+ * was, and, for a loop, how it ended, so the new chat can take it from there.
+ */
+export function chatHandoverMessage(session: Session): string {
+ const real = session.messages.filter(m => !m.local);
+ const answer = [...real].reverse().find(m => m.role === 'assistant');
+ const asked = [...real].reverse().find(m => m.role === 'user');
+ const parts = [`**${chatHandoverTitle(session)}**`];
+ const loop = session.loop;
+ if (loop) {
+ const ended = loop.endedWhy && loop.endedWhy !== 'stopped' && loop.endedWhy !== 'closed' ? `\n\n${loopEndNote(loop.endedWhy, loop.answers)}` : '';
+ parts.push(`**${tr('The loop')}**\n\n${loop.prompt}${ended}`);
+ } else if (asked?.content) parts.push(`**${tr('What I asked')}**\n\n${asked.content.trim().slice(0, 1500)}`);
+ if (answer?.error) parts.push(`**${tr('What went wrong')}**\n\n${String(answer.error).trim()}`);
+ const said = (answer?.content ?? '').trim() || (loop?.lastText ?? '');
+ if (said) parts.push(`**${tr('The last answer')}**\n\n${said.slice(0, 2000)}`);
+ parts.push(tr('Please help me take it from here.'));
+ return parts.join('\n\n');
+}
diff --git a/apps/host/src/lib/types.ts b/apps/host/src/lib/types.ts
index 530884bcf..1e8b053ef 100644
--- a/apps/host/src/lib/types.ts
+++ b/apps/host/src/lib/types.ts
@@ -406,7 +406,30 @@ export interface SessionAgent {
export type ChatMode = 'auto' | 'manual' | 'accept-edits' | 'plan' | 'bypass';
+/**
+ * What the board needs to know about a /loop after the window closes: loops live in memory, so the chat keeps a small record of the
+ * last one (running, or how it ended). A record that says `running` with no loop behind it is a loop the window closed on.
+ */
+export interface LoopRecord {
+ prompt: string;
+ everyMs: number;
+ startedAt: number;
+ state: 'running' | 'ended';
+ answers: number;
+ maxRuns?: number;
+ /** When the next answer is due (ms), while running. */
+ nextAt?: number;
+ endedAt?: number;
+ /** count, said-done, time, failures, cap; `stopped` when the person typed /loop stop; `closed` when the window closed on it. */
+ endedWhy?: 'count' | 'said-done' | 'time' | 'failures' | 'cap' | 'stopped' | 'closed';
+ /** The last answer's first words, for the card. */
+ lastText?: string;
+}
+
export interface Session {
+ /** The person dismissed this chat's (or its loop's) card on the board at this time. A later problem brings it back. */
+ ackedAt?: string;
+ loop?: LoopRecord;
timeSkips?: import('./time-skip').TimeSkipRun[];
showcase?: boolean;
agents?: SessionAgent[];
diff --git a/apps/host/src/lib/use-board.ts b/apps/host/src/lib/use-board.ts
new file mode 100644
index 000000000..46411101c
--- /dev/null
+++ b/apps/host/src/lib/use-board.ts
@@ -0,0 +1,65 @@
+import { useEffect, useMemo, useState } from 'react';
+import { api } from './client';
+import { boardCards, type BoardPending, type BoardResult } from './board';
+import { liveChatIds, loopChatIds, useStore } from './store';
+import type { Task } from './tasks';
+
+/**
+ * What the board and the sidebar's count read: the host's tasks and its waiting approvals (asked every few seconds, by one timer however
+ * many parts of the page use them), turned into cards together with the chats in this browser.
+ */
+interface Shared { tasks: Task[]; pending: BoardPending[] | null; ready: boolean; error: string }
+let shared: Shared = { tasks: [], pending: null, ready: false, error: '' };
+const listeners = new Set<() => void>();
+let timer: ReturnType<typeof setInterval> | null = null;
+let inFlight = false;
+
+async function refresh() {
+ if (inFlight) return;
+ inFlight = true;
+ try {
+ const [tasks, waiting] = await Promise.all([
+ api.get<{ tasks: Task[] }>('/api/tasks'),
+ api.get<{ chats: { chatId: string; folder: string | null; pending: { callId: string; at: number }[] }[] }>('/api/agent/pending').catch(() => null),
+ ]);
+ shared = {
+ tasks: tasks.tasks,
+ // Unknown (the host did not answer) is not the same as "nothing waits": the chats' own cards are trusted then.
+ pending: waiting ? waiting.chats.map(c => ({ chatId: c.chatId, folder: c.folder, callIds: c.pending.map(p => p.callId), at: Math.min(...c.pending.map(p => p.at)) })) : null,
+ ready: true, error: '',
+ };
+ } catch (e) {
+ shared = { ...shared, ready: true, error: e instanceof Error ? e.message : String(e) };
+ } finally {
+ inFlight = false;
+ listeners.forEach(l => l());
+ }
+}
+
+/** Ask now (after an action), instead of waiting for the next tick. */
+export function refreshBoard() { void refresh(); }
+
+function subscribe(listener: () => void) {
+ listeners.add(listener);
+ if (listeners.size === 1) { void refresh(); timer = setInterval(() => void refresh(), 4000); window.addEventListener('strata:tasks', refreshBoard); }
+ return () => {
+ listeners.delete(listener);
+ if (!listeners.size && timer) { clearInterval(timer); timer = null; window.removeEventListener('strata:tasks', refreshBoard); }
+ };
+}
+
+export function useBoard(): { board: BoardResult; ready: boolean; error: string; tasks: Task[] } {
+ const [, tick] = useState(0);
+ useEffect(() => subscribe(() => tick(n => n + 1)), []);
+ const sessions = useStore(s => s.sessions), activeSession = useStore(s => s.activeSession), live = useStore(s => s.liveChats);
+ // The clock moves the "waiting 4 min" labels and the seven-day window on, without needing a new fetch.
+ const [minute, setMinute] = useState(() => Math.floor(Date.now() / 60_000));
+ useEffect(() => { const t = setInterval(() => setMinute(Math.floor(Date.now() / 60_000)), 30_000); return () => clearInterval(t); }, []);
+ const board = useMemo(
+ () => boardCards({ tasks: shared.tasks, sessions, liveChats: liveChatIds(), loopChats: loopChatIds(), pending: shared.pending, activeSession, now: Date.now() }),
+ // `live` (how many chats are mid-turn) changes whenever a turn starts or ends; the shared snapshot changes by object identity.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [shared, sessions, activeSession, live, minute],
+ );
+ return { board, ready: shared.ready, error: shared.error, tasks: shared.tasks };
+}
diff --git a/apps/host/src/locales/de.json b/apps/host/src/locales/de.json
index 7b4177511..e24fe16f9 100644
--- a/apps/host/src/locales/de.json
+++ b/apps/host/src/locales/de.json
@@ -3286,5 +3286,62 @@
"s7401": "Der Assistent möchte die Webseite {0} öffnen. Die Seite sieht die Anfrage.",
"s7402": "Den Assistenten ohne Nachfrage im Web suchen lassen",
"s7403": "Im Modus „Manuell“ fragt der Assistent pro Chat einmal nach, bevor er im Web sucht oder eine Webseite öffnet. Schalte das ein, um die Nachfrage zu überspringen.",
- "s7404": "DuckDuckGo oder Bing, wenn DuckDuckGo ausgelastet ist"
+ "s7404": "DuckDuckGo oder Bing, wenn DuckDuckGo ausgelastet ist",
+ "s8201": "unter 1 Min.",
+ "s8202": "{0} Min.",
+ "s8203": "{0} Std.",
+ "s8204": "{0} T.",
+ "s8205": "vor {0}",
+ "s8206": "heute {0}",
+ "s8207": "gestern",
+ "s8208": "gestartet {0}",
+ "s8209": "wartet seit {0}",
+ "s8210": "nächste in {0}",
+ "s8211": "antwortet gerade",
+ "s8212": "gestoppt {0}",
+ "s8213": "Es wurde nicht fertig.",
+ "s8214": "Dieser Lauf wurde gestoppt, bevor er fertig war.",
+ "s8215": "Strata wurde geschlossen, während dies lief, daher wurde es nicht fertig.",
+ "s8216": "Fertig, wollte aber etwas ändern und konnte nicht nachfragen. Es wurde nichts geändert.",
+ "s8217": "Gestoppt: {0} Läufe in Folge haben nicht funktioniert.",
+ "s8218": "Geplante Aufgabe",
+ "s8219": "Schleife · {0}",
+ "s8220": "Laden Sie zuerst ein Modell",
+ "s8221": "Weitere Aktionen für {0}",
+ "s8222": "Karten wandern von selbst, wenn sich etwas ändert. Eine Karte unter „Braucht Aufmerksamkeit“ bleibt dort, bis Sie sich darum gekümmert oder sie geschlossen haben.",
+ "s8223": "{0} brauchen Ihre Aufmerksamkeit",
+ "s8224": "Im Moment braucht nichts Ihre Aufmerksamkeit.",
+ "s8225": "{0} Karten",
+ "s8226": "Als Nächstes",
+ "s8227": "Weiter im Chat „{0}“",
+ "s8228": "Die Schleife",
+ "s8229": "Was ich gefragt habe",
+ "s8230": "Die letzte Antwort",
+ "s8231": "Aufgabenübersicht",
+ "s8232": "Braucht Aufmerksamkeit",
+ "s8233": "Wartet auf Sie",
+ "s8234": "Bei einer Frage angehalten, die nur Sie beantworten können.",
+ "s8235": "Problem gefunden. Bleibt hier, bis Sie sich darum kümmern.",
+ "s8236": "In den letzten 7 Tagen sauber abgeschlossen.",
+ "s8237": "Erneut ausführen",
+ "s8238": "Aufgabe öffnen",
+ "s8239": "Chat öffnen",
+ "s8240": "Chat stoppen",
+ "s8241": "Schleife stoppen",
+ "s8242": "Ergebnis ansehen",
+ "s8243": "Abgeschlossen",
+ "s8244": "Von Ihnen gestoppt",
+ "s8245": "Beim Schließen von Strata gestoppt",
+ "s8246": "Von selbst beendet",
+ "s8247": "Antwort {0} von {1}",
+ "s8248": "Antwort {0}",
+ "s8249": "1 Helfer arbeitet",
+ "s8250": "{0} Helfer arbeiten",
+ "s8251": "Übersicht",
+ "s8252": "Ansicht",
+ "s8253": "Alles, was läuft, auf Sie wartet oder einen Blick braucht.",
+ "s8254": "Das hat nicht geklappt",
+ "s8255": "Keine passenden Karten.",
+ "s8256": "Im Moment nichts hier.",
+ "s8257": "alle {0} Min."
}
diff --git a/apps/host/src/locales/en.json b/apps/host/src/locales/en.json
index 8260511eb..44dc7202b 100644
--- a/apps/host/src/locales/en.json
+++ b/apps/host/src/locales/en.json
@@ -3286,5 +3286,62 @@
"s7401": "The assistant wants to open the web page {0}. The page's site sees the request.",
"s7402": "Let the assistant search the web without asking",
"s7403": "In Manual mode the assistant asks once per chat before it searches the web or opens a web page. Turn this on to skip that question.",
- "s7404": "DuckDuckGo, or Bing when DuckDuckGo is busy"
+ "s7404": "DuckDuckGo, or Bing when DuckDuckGo is busy",
+ "s8201": "under 1 min",
+ "s8202": "{0} min",
+ "s8203": "{0} h",
+ "s8204": "{0} d",
+ "s8205": "{0} ago",
+ "s8206": "today {0}",
+ "s8207": "yesterday",
+ "s8208": "started {0}",
+ "s8209": "waiting {0}",
+ "s8210": "next in {0}",
+ "s8211": "answering now",
+ "s8212": "stopped {0}",
+ "s8213": "It did not finish.",
+ "s8214": "This run was stopped before it finished.",
+ "s8215": "Strata closed while this was running, so it did not finish.",
+ "s8216": "Finished, but wanted to change something and could not ask. Nothing was changed.",
+ "s8217": "Stopped: {0} runs in a row did not work.",
+ "s8218": "Scheduled task",
+ "s8219": "Loop · {0}",
+ "s8220": "Load a model first",
+ "s8221": "More actions for {0}",
+ "s8222": "Cards move on their own as things happen. A card in Needs attention stays there until you deal with it or dismiss it.",
+ "s8223": "{0} need your attention",
+ "s8224": "Nothing needs you right now.",
+ "s8225": "{0} cards",
+ "s8226": "Coming up",
+ "s8227": "Continuing from the chat “{0}”",
+ "s8228": "The loop",
+ "s8229": "What I asked",
+ "s8230": "The last answer",
+ "s8231": "Task board",
+ "s8232": "Needs attention",
+ "s8233": "Waiting for you",
+ "s8234": "Stopped at a question only you can answer.",
+ "s8235": "Found a problem. Stays here until you deal with it.",
+ "s8236": "Finished cleanly in the last 7 days.",
+ "s8237": "Run again",
+ "s8238": "Open task",
+ "s8239": "Open chat",
+ "s8240": "Stop chat",
+ "s8241": "Stop loop",
+ "s8242": "View result",
+ "s8243": "Finished",
+ "s8244": "Stopped by you",
+ "s8245": "Stopped when Strata closed",
+ "s8246": "Ended on its own",
+ "s8247": "answer {0} of {1}",
+ "s8248": "answer {0}",
+ "s8249": "1 helper working",
+ "s8250": "{0} helpers working",
+ "s8251": "Board",
+ "s8252": "View",
+ "s8253": "Everything that is running, waiting for you, or needs a look.",
+ "s8254": "That did not work",
+ "s8255": "No matching cards.",
+ "s8256": "Nothing here right now.",
+ "s8257": "every {0} min"
}
diff --git a/apps/host/src/locales/es.json b/apps/host/src/locales/es.json
index 57b033b8d..a61b6d859 100644
--- a/apps/host/src/locales/es.json
+++ b/apps/host/src/locales/es.json
@@ -3286,5 +3286,62 @@
"s7401": "El asistente quiere abrir la página web {0}. El sitio de la página ve la solicitud.",
"s7402": "Dejar que el asistente busque en la web sin preguntar",
"s7403": "En el modo Manual, el asistente pregunta una vez por chat antes de buscar en la web o abrir una página web. Actívalo para omitir esa pregunta.",
- "s7404": "DuckDuckGo, o Bing cuando DuckDuckGo está ocupado"
+ "s7404": "DuckDuckGo, o Bing cuando DuckDuckGo está ocupado",
+ "s8201": "menos de 1 min",
+ "s8202": "{0} min",
+ "s8203": "{0} h",
+ "s8204": "{0} d",
+ "s8205": "hace {0}",
+ "s8206": "hoy {0}",
+ "s8207": "ayer",
+ "s8208": "iniciada {0}",
+ "s8209": "esperando desde hace {0}",
+ "s8210": "próxima en {0}",
+ "s8211": "respondiendo ahora",
+ "s8212": "detenida {0}",
+ "s8213": "No terminó.",
+ "s8214": "Esta ejecución se detuvo antes de terminar.",
+ "s8215": "Strata se cerró mientras esto se ejecutaba, así que no terminó.",
+ "s8216": "Terminó, pero quería cambiar algo y no pudo preguntar. No se cambió nada.",
+ "s8217": "Detenido: {0} ejecuciones seguidas no funcionaron.",
+ "s8218": "Tarea programada",
+ "s8219": "Bucle · {0}",
+ "s8220": "Carga primero un modelo",
+ "s8221": "Más acciones para {0}",
+ "s8222": "Las tarjetas se mueven solas según pasan las cosas. Una tarjeta en «Requiere atención» se queda ahí hasta que la resuelvas o la descartes.",
+ "s8223": "{0} necesitan tu atención",
+ "s8224": "Ahora mismo nada necesita tu atención.",
+ "s8225": "{0} tarjetas",
+ "s8226": "Próximamente",
+ "s8227": "Continuando desde el chat «{0}»",
+ "s8228": "El bucle",
+ "s8229": "Lo que pregunté",
+ "s8230": "La última respuesta",
+ "s8231": "Tablero de tareas",
+ "s8232": "Requiere atención",
+ "s8233": "Esperando por ti",
+ "s8234": "Se detuvo en una pregunta que solo tú puedes responder.",
+ "s8235": "Encontró un problema. Se queda aquí hasta que lo resuelvas.",
+ "s8236": "Terminado sin problemas en los últimos 7 días.",
+ "s8237": "Ejecutar de nuevo",
+ "s8238": "Abrir tarea",
+ "s8239": "Abrir chat",
+ "s8240": "Detener chat",
+ "s8241": "Detener bucle",
+ "s8242": "Ver resultado",
+ "s8243": "Terminado",
+ "s8244": "Detenido por ti",
+ "s8245": "Detenido al cerrar Strata",
+ "s8246": "Terminó por sí solo",
+ "s8247": "respuesta {0} de {1}",
+ "s8248": "respuesta {0}",
+ "s8249": "1 ayudante trabajando",
+ "s8250": "{0} ayudantes trabajando",
+ "s8251": "Tablero",
+ "s8252": "Vista",
+ "s8253": "Todo lo que se está ejecutando, espera por ti o necesita que le eches un vistazo.",
+ "s8254": "Eso no funcionó",
+ "s8255": "No hay tarjetas que coincidan.",
+ "s8256": "Nada por aquí ahora mismo.",
+ "s8257": "cada {0} min"
}
diff --git a/apps/host/src/locales/ja.json b/apps/host/src/locales/ja.json
index e6e9dd1be..2ea9e8cb5 100644
--- a/apps/host/src/locales/ja.json
+++ b/apps/host/src/locales/ja.json
@@ -3286,5 +3286,62 @@
"s7401": "アシスタントがウェブページ {0} を開こうとしています。そのサイトにリクエストが見えます。",
"s7402": "確認せずにアシスタントがウェブを検索できるようにする",
"s7403": "手動モードでは、アシスタントはウェブ検索やウェブページを開く前に、チャットごとに1回確認します。オンにすると確認を省略します。",
- "s7404": "DuckDuckGo(混雑時は Bing)"
+ "s7404": "DuckDuckGo(混雑時は Bing)",
+ "s8201": "1分未満",
+ "s8202": "{0}分",
+ "s8203": "{0}時間",
+ "s8204": "{0}日",
+ "s8205": "{0}前",
+ "s8206": "今日 {0}",
+ "s8207": "昨日",
+ "s8208": "開始 {0}",
+ "s8209": "{0}待機中",
+ "s8210": "次回まで {0}",
+ "s8211": "回答中",
+ "s8212": "停止 {0}",
+ "s8213": "完了しませんでした。",
+ "s8214": "この実行は完了する前に停止されました。",
+ "s8215": "実行中に Strata が閉じられたため、完了しませんでした。",
+ "s8216": "完了しましたが、何かを変更しようとして確認できませんでした。何も変更されていません。",
+ "s8217": "停止しました:{0}回続けて失敗しました。",
+ "s8218": "スケジュール済みタスク",
+ "s8219": "ループ · {0}",
+ "s8220": "先にモデルを読み込んでください",
+ "s8221": "{0}のその他の操作",
+ "s8222": "カードは状況に応じて自動で移動します。「要確認」のカードは、対応するか閉じるまでそこに残ります。",
+ "s8223": "{0}件が対応を待っています",
+ "s8224": "今のところ対応が必要なものはありません。",
+ "s8225": "{0}枚のカード",
+ "s8226": "今後の予定",
+ "s8227": "チャット「{0}」の続き",
+ "s8228": "ループ",
+ "s8229": "私の質問",
+ "s8230": "最後の回答",
+ "s8231": "タスクボード",
+ "s8232": "要確認",
+ "s8233": "あなたの返答待ち",
+ "s8234": "あなただけが答えられる質問で止まっています。",
+ "s8235": "問題が見つかりました。対応するまでここに残ります。",
+ "s8236": "過去7日間に問題なく完了したもの。",
+ "s8237": "もう一度実行",
+ "s8238": "タスクを開く",
+ "s8239": "チャットを開く",
+ "s8240": "チャットを停止",
+ "s8241": "ループを停止",
+ "s8242": "結果を見る",
+ "s8243": "完了",
+ "s8244": "あなたが停止",
+ "s8245": "Strata を閉じたときに停止",
+ "s8246": "自動的に終了",
+ "s8247": "{1}回中{0}回目の回答",
+ "s8248": "{0}回目の回答",
+ "s8249": "ヘルパー1件が作業中",
+ "s8250": "ヘルパー{0}件が作業中",
+ "s8251": "ボード",
+ "s8252": "表示",
+ "s8253": "実行中のもの、あなたを待っているもの、確認が必要なものがすべて見られます。",
+ "s8254": "うまくいきませんでした",
+ "s8255": "一致するカードはありません。",
+ "s8256": "今は何もありません。",
+ "s8257": "{0}分ごと"
}
diff --git a/apps/host/src/locales/ko.json b/apps/host/src/locales/ko.json
index daedbabbe..5acfc7034 100644
--- a/apps/host/src/locales/ko.json
+++ b/apps/host/src/locales/ko.json
@@ -3286,5 +3286,62 @@
"s7401": "어시스턴트가 웹 페이지 {0}을(를) 열려고 합니다. 해당 사이트에 요청이 표시됩니다.",
"s7402": "묻지 않고 어시스턴트가 웹을 검색하도록 허용",
"s7403": "수동 모드에서는 어시스턴트가 웹을 검색하거나 웹 페이지를 열기 전에 채팅당 한 번 묻습니다. 켜면 이 질문을 건너뜁니다.",
- "s7404": "DuckDuckGo, DuckDuckGo가 바쁠 때는 Bing"
+ "s7404": "DuckDuckGo, DuckDuckGo가 바쁠 때는 Bing",
+ "s8201": "1분 미만",
+ "s8202": "{0}분",
+ "s8203": "{0}시간",
+ "s8204": "{0}일",
+ "s8205": "{0} 전",
+ "s8206": "오늘 {0}",
+ "s8207": "어제",
+ "s8208": "시작 {0}",
+ "s8209": "{0} 동안 대기 중",
+ "s8210": "{0} 후 다음 실행",
+ "s8211": "지금 답변 중",
+ "s8212": "중지됨 {0}",
+ "s8213": "끝나지 않았습니다.",
+ "s8214": "이 실행은 끝나기 전에 중지되었습니다.",
+ "s8215": "실행 중에 Strata가 종료되어 끝나지 않았습니다.",
+ "s8216": "끝났지만 무언가를 바꾸려 했고 물어볼 수 없었습니다. 바뀐 것은 없습니다.",
+ "s8217": "중지됨: {0}번 연속으로 실행되지 않았습니다.",
+ "s8218": "예약된 작업",
+ "s8219": "반복 · {0}",
+ "s8220": "먼저 모델을 불러오세요",
+ "s8221": "{0}의 추가 작업",
+ "s8222": "카드는 상황에 따라 저절로 이동합니다. '확인 필요'의 카드는 처리하거나 닫을 때까지 그대로 남습니다.",
+ "s8223": "{0}개가 확인을 기다립니다",
+ "s8224": "지금은 확인할 것이 없습니다.",
+ "s8225": "카드 {0}개",
+ "s8226": "예정",
+ "s8227": "채팅 '{0}'에서 이어가기",
+ "s8228": "반복",
+ "s8229": "내가 한 질문",
+ "s8230": "마지막 답변",
+ "s8231": "작업 보드",
+ "s8232": "확인 필요",
+ "s8233": "내 답을 기다리는 중",
+ "s8234": "당신만 답할 수 있는 질문에서 멈췄습니다.",
+ "s8235": "문제가 발견되었습니다. 처리할 때까지 여기에 남습니다.",
+ "s8236": "최근 7일 동안 문제없이 끝난 것.",
+ "s8237": "다시 실행",
+ "s8238": "작업 열기",
+ "s8239": "채팅 열기",
+ "s8240": "채팅 중지",
+ "s8241": "반복 중지",
+ "s8242": "결과 보기",
+ "s8243": "끝남",
+ "s8244": "직접 중지함",
+ "s8245": "Strata를 닫을 때 중지됨",
+ "s8246": "저절로 끝남",
+ "s8247": "답변 {0}/{1}",
+ "s8248": "답변 {0}",
+ "s8249": "도우미 1개가 작업 중",
+ "s8250": "도우미 {0}개가 작업 중",
+ "s8251": "보드",
+ "s8252": "보기",
+ "s8253": "실행 중이거나, 내 답을 기다리거나, 확인이 필요한 모든 것.",
+ "s8254": "실패했습니다",
+ "s8255": "일치하는 카드가 없습니다.",
+ "s8256": "지금은 아무것도 없습니다.",
+ "s8257": "{0}분마다"
}
diff --git a/apps/host/src/locales/pt.json b/apps/host/src/locales/pt.json
index 7d8b47399..06614f99e 100644
--- a/apps/host/src/locales/pt.json
+++ b/apps/host/src/locales/pt.json
@@ -3286,5 +3286,62 @@
"s7401": "O assistente quer abrir a página web {0}. O site da página vê a solicitação.",
"s7402": "Deixar o assistente pesquisar na web sem perguntar",
"s7403": "No modo Manual, o assistente pergunta uma vez por chat antes de pesquisar na web ou abrir uma página web. Ative para pular essa pergunta.",
- "s7404": "DuckDuckGo, ou Bing quando o DuckDuckGo está ocupado"
+ "s7404": "DuckDuckGo, ou Bing quando o DuckDuckGo está ocupado",
+ "s8201": "menos de 1 min",
+ "s8202": "{0} min",
+ "s8203": "{0} h",
+ "s8204": "{0} d",
+ "s8205": "há {0}",
+ "s8206": "hoje {0}",
+ "s8207": "ontem",
+ "s8208": "iniciada {0}",
+ "s8209": "aguardando há {0}",
+ "s8210": "próxima em {0}",
+ "s8211": "respondendo agora",
+ "s8212": "parada {0}",
+ "s8213": "Não terminou.",
+ "s8214": "Esta execução foi parada antes de terminar.",
+ "s8215": "O Strata foi fechado durante a execução, então não terminou.",
+ "s8216": "Terminou, mas queria alterar algo e não pôde perguntar. Nada foi alterado.",
+ "s8217": "Parado: {0} execuções seguidas não funcionaram.",
+ "s8218": "Tarefa agendada",
+ "s8219": "Repetição · {0}",
+ "s8220": "Carregue um modelo primeiro",
+ "s8221": "Mais ações para {0}",
+ "s8222": "Os cartões se movem sozinhos conforme as coisas acontecem. Um cartão em «Precisa de atenção» fica lá até você resolver ou dispensar.",
+ "s8223": "{0} precisam da sua atenção",
+ "s8224": "Nada precisa de você agora.",
+ "s8225": "{0} cartões",
+ "s8226": "A seguir",
+ "s8227": "Continuando do chat «{0}»",
+ "s8228": "A repetição",
+ "s8229": "O que eu perguntei",
+ "s8230": "A última resposta",
+ "s8231": "Quadro de tarefas",
+ "s8232": "Precisa de atenção",
+ "s8233": "Aguardando você",
+ "s8234": "Parou em uma pergunta que só você pode responder.",
+ "s8235": "Encontrou um problema. Fica aqui até você resolver.",
+ "s8236": "Concluído sem problemas nos últimos 7 dias.",
+ "s8237": "Executar de novo",
+ "s8238": "Abrir tarefa",
+ "s8239": "Abrir chat",
+ "s8240": "Parar chat",
+ "s8241": "Parar repetição",
+ "s8242": "Ver resultado",
+ "s8243": "Concluído",
+ "s8244": "Parado por você",
+ "s8245": "Parado quando o Strata foi fechado",
+ "s8246": "Terminou sozinho",
+ "s8247": "resposta {0} de {1}",
+ "s8248": "resposta {0}",
+ "s8249": "1 ajudante trabalhando",
+ "s8250": "{0} ajudantes trabalhando",
+ "s8251": "Quadro",
+ "s8252": "Visualização",
+ "s8253": "Tudo o que está em execução, aguarda você ou precisa de uma olhada.",
+ "s8254": "Isso não funcionou",
+ "s8255": "Nenhum cartão correspondente.",
+ "s8256": "Nada aqui por enquanto.",
+ "s8257": "a cada {0} min"
}
diff --git a/apps/host/src/locales/ru.json b/apps/host/src/locales/ru.json
index a3885803b..51bae0e13 100644
--- a/apps/host/src/locales/ru.json
+++ b/apps/host/src/locales/ru.json
@@ -3286,5 +3286,62 @@
"s7401": "Ассистент хочет открыть веб-страницу {0}. Сайт страницы увидит этот запрос.",
"s7402": "Разрешить ассистенту искать в интернете без вопросов",
"s7403": "В ручном режиме ассистент один раз за чат спрашивает, прежде чем искать в интернете или открывать веб-страницу. Включите, чтобы пропускать этот вопрос.",
- "s7404": "DuckDuckGo или Bing, когда DuckDuckGo занят"
+ "s7404": "DuckDuckGo или Bing, когда DuckDuckGo занят",
+ "s8201": "менее 1 мин",
+ "s8202": "{0} мин",
+ "s8203": "{0} ч",
+ "s8204": "{0} д",
+ "s8205": "{0} назад",
+ "s8206": "сегодня {0}",
+ "s8207": "вчера",
+ "s8208": "запущена {0}",
+ "s8209": "ждёт {0}",
+ "s8210": "следующая через {0}",
+ "s8211": "отвечает сейчас",
+ "s8212": "остановлена {0}",
+ "s8213": "Не завершилось.",
+ "s8214": "Этот запуск остановили до завершения.",
+ "s8215": "Strata закрылась во время выполнения, поэтому задача не завершилась.",
+ "s8216": "Завершено, но задача хотела что-то изменить и не смогла спросить. Ничего не изменено.",
+ "s8217": "Остановлено: {0} запуска подряд не удались.",
+ "s8218": "Запланированная задача",
+ "s8219": "Цикл · {0}",
+ "s8220": "Сначала загрузите модель",
+ "s8221": "Другие действия для {0}",
+ "s8222": "Карточки перемещаются сами, когда что-то происходит. Карточка в «Нужно внимание» остаётся там, пока вы не разберётесь с ней или не скроете её.",
+ "s8223": "Требуют внимания: {0}",
+ "s8224": "Сейчас ничего не требует вашего внимания.",
+ "s8225": "Карточек: {0}",
+ "s8226": "Скоро",
+ "s8227": "Продолжение чата «{0}»",
+ "s8228": "Цикл",
+ "s8229": "О чём я спрашивал",
+ "s8230": "Последний ответ",
+ "s8231": "Доска задач",
+ "s8232": "Нужно внимание",
+ "s8233": "Ждёт вас",
+ "s8234": "Остановилось на вопросе, ответить на который можете только вы.",
+ "s8235": "Найдена проблема. Остаётся здесь, пока вы с ней не разберётесь.",
+ "s8236": "Успешно завершено за последние 7 дней.",
+ "s8237": "Запустить снова",
+ "s8238": "Открыть задачу",
+ "s8239": "Открыть чат",
+ "s8240": "Остановить чат",
+ "s8241": "Остановить цикл",
+ "s8242": "Посмотреть результат",
+ "s8243": "Завершено",
+ "s8244": "Остановлено вами",
+ "s8245": "Остановлено при закрытии Strata",
+ "s8246": "Завершилось само",
+ "s8247": "ответ {0} из {1}",
+ "s8248": "ответ {0}",
+ "s8249": "работает 1 помощник",
+ "s8250": "работают помощники: {0}",
+ "s8251": "Доска",
+ "s8252": "Вид",
+ "s8253": "Всё, что выполняется, ждёт вас или требует внимания.",
+ "s8254": "Не получилось",
+ "s8255": "Нет подходящих карточек.",
+ "s8256": "Сейчас здесь пусто.",
+ "s8257": "каждые {0} мин"
}
diff --git a/apps/host/src/locales/zh.json b/apps/host/src/locales/zh.json
index 7576dba28..e0cf24ecb 100644
--- a/apps/host/src/locales/zh.json
+++ b/apps/host/src/locales/zh.json
@@ -3286,5 +3286,62 @@
"s7401": "助手想打开网页 {0}。该网站会看到这次请求。",
"s7402": "允许助手无需询问即可搜索网页",
"s7403": "在手动模式下,助手每个聊天会先询问一次,再搜索网页或打开网页。开启后将跳过这个询问。",
- "s7404": "DuckDuckGo;DuckDuckGo 繁忙时使用 Bing"
+ "s7404": "DuckDuckGo;DuckDuckGo 繁忙时使用 Bing",
+ "s8201": "不到 1 分钟",
+ "s8202": "{0} 分钟",
+ "s8203": "{0} 小时",
+ "s8204": "{0} 天",
+ "s8205": "{0}前",
+ "s8206": "今天 {0}",
+ "s8207": "昨天",
+ "s8208": "开始于 {0}",
+ "s8209": "已等待 {0}",
+ "s8210": "{0}后下一次",
+ "s8211": "正在回答",
+ "s8212": "停止于 {0}",
+ "s8213": "没有完成。",
+ "s8214": "这次运行在完成前被停止了。",
+ "s8215": "运行期间 Strata 被关闭,因此没有完成。",
+ "s8216": "已完成,但它想更改某些内容却无法询问。没有任何更改。",
+ "s8217": "已停止:连续 {0} 次运行失败。",
+ "s8218": "定时任务",
+ "s8219": "循环 · {0}",
+ "s8220": "请先加载模型",
+ "s8221": "{0} 的更多操作",
+ "s8222": "卡片会随情况自动移动。“需要关注”中的卡片会一直留在那里,直到你处理或关闭它。",
+ "s8223": "{0} 项需要你处理",
+ "s8224": "目前没有需要你处理的事项。",
+ "s8225": "{0} 张卡片",
+ "s8226": "即将运行",
+ "s8227": "接续聊天“{0}”",
+ "s8228": "循环",
+ "s8229": "我的提问",
+ "s8230": "最后一次回答",
+ "s8231": "任务看板",
+ "s8232": "需要关注",
+ "s8233": "等你处理",
+ "s8234": "停在了只有你能回答的问题上。",
+ "s8235": "发现了问题。在你处理之前会一直留在这里。",
+ "s8236": "过去 7 天内顺利完成的事项。",
+ "s8237": "再次运行",
+ "s8238": "打开任务",
+ "s8239": "打开聊天",
+ "s8240": "停止聊天",
+ "s8241": "停止循环",
+ "s8242": "查看结果",
+ "s8243": "已完成",
+ "s8244": "你已停止",
+ "s8245": "Strata 关闭时已停止",
+ "s8246": "已自动结束",
+ "s8247": "第 {0} 次回答,共 {1} 次",
+ "s8248": "第 {0} 次回答",
+ "s8249": "1 个助手正在工作",
+ "s8250": "{0} 个助手正在工作",
+ "s8251": "看板",
+ "s8252": "视图",
+ "s8253": "所有正在运行、等你处理或需要查看的事项。",
+ "s8254": "操作没有成功",
+ "s8255": "没有匹配的卡片。",
+ "s8256": "目前这里没有内容。",
+ "s8257": "每 {0} 分钟"
}
diff --git a/apps/host/src/main.tsx b/apps/host/src/main.tsx
index a35e3f836..7162366c1 100644
--- a/apps/host/src/main.tsx
+++ b/apps/host/src/main.tsx
@@ -24,3 +24,5 @@ import './styles/time-skip.css';
import './styles/model-run.css';
import './styles/onboarding.css';
+
+import './styles/board.css';
diff --git a/apps/host/src/screens/Tasks.tsx b/apps/host/src/screens/Tasks.tsx
index 971ff0f6b..4ac52d071 100644
--- a/apps/host/src/screens/Tasks.tsx
+++ b/apps/host/src/screens/Tasks.tsx
@@ -2,7 +2,9 @@ import {localeTag} from '../lib/i18n';
import { tr } from '../lib/i18n';
import { useLocation, navigate } from '../lib/router';
import { useEffect, useState } from 'react';
-import { Btn, Dialog, Icon, IconBtn, Select, ErrorNotice } from '../components/ui';
+import { Btn, Dialog, Icon, IconBtn, Select, Seg, ErrorNotice } from '../components/ui';
+import { TaskBoard } from '../components/TaskBoard';
+import { useNative } from '../lib/native';
import { Markdown } from '../components/Markdown';
import { Screen } from '../components/layout';
import { api } from '../lib/client';
@@ -13,6 +15,7 @@ import { TaskDetail } from '../components/TaskDetail';
export function TasksScreen() {
const location = useLocation();
const library = useStore(s => s.library);
+ const native = useNative();
const loaded = library?.variants.find(v => v.id === library.loaded);
const [tasks, setTasks] = useState<Task[]>([]), [query, setQuery] = useState(''), [sort, setSort] = useState('next'), archived = false;
const [editor, setEditor] = useState<Task | null>(null), [assistant, setAssistant] = useState(false), [pending, setPending] = useState(false), [error, setError] = useState(''), [ready, setReady] = useState(false), [result, setResult] = useState<string | null>(null), [removeTask, setRemoveTask] = useState(false);
@@ -65,6 +68,9 @@ export function TasksScreen() {
navigate('tasks', location.param ?? undefined);
}
const currentTask = tasks.find(t => t.id === location.param);
+ // Schedule | Board: the board is #/tasks?view=board, the same screen (no route of its own).
+ const view: 'schedule' | 'board' = location.query.get('view') === 'board' && !location.param ? 'board' : 'schedule';
+ const setView = (next: 'schedule' | 'board') => navigate('tasks', undefined, next === 'board' ? { view: 'board' } : undefined);
const visible = tasks.filter(t => (!location.param || t.id === location.param) && !!t.archived === archived && `${t.title} ${t.prompt}`.toLowerCase().includes(query.toLowerCase())).sort((a, b) => sort === 'name' ? a.title.localeCompare(b.title) : (a.nextRunAt ?? 'z').localeCompare(b.nextRunAt ?? 'z'));
const selected = tasks.find(t => t.id === result);
const taskHeader = currentTask ? <div className="task-header-actions">
@@ -74,12 +80,13 @@ export function TasksScreen() {
{tr(currentTask.lastRunAt || currentTask.output || currentTask.error ? <Btn icon="chat" disabled={pending || currentTask.status === 'running'} onClick={() => continueTaskInNewChat(currentTask)}>{tr("Continue in a new chat")}</Btn> : null)}
<Btn variant="primary" icon={currentTask.status === 'running' ? 'stop' : 'bolt'} disabled={pending || !loaded && currentTask.status !== 'running'} onClick={() => void action(() => api.post(`/api/tasks/${currentTask.id}/${currentTask.status === 'running' ? 'stop' : 'run'}`))}>{tr(currentTask.status === 'running' ? 'Stop' : 'Run now')}</Btn>
</div> : null;
- return <Screen title={currentTask ? <span className="sr-only">{currentTask.title}</span> : "Tasks"} sub={currentTask ? undefined : "Run a prompt on a schedule, or whenever you need it."} actions={currentTask ? taskHeader : <div className="tasks-actions"><input className="st-input tasks-search" type="search" aria-label={tr("Search tasks")} placeholder={tr("Search tasks…")} value={query} onChange={e => setQuery(e.target.value)}/><Select ariaLabel={tr("Sort tasks")} value={sort} options={[{ value: 'next', label: 'Next run' }, { value: 'name', label: 'Name' }]} onChange={setSort}/><IconBtn name="plus" title={tr("New task")} onClick={() => open(blank())}/></div>}>
+ return <Screen width={view === 'board' && !currentTask ? 'full' : 'normal'} title={currentTask ? <span className="sr-only">{currentTask.title}</span> : "Tasks"} sub={currentTask ? undefined : view === 'board' ? "Everything that is running, waiting for you, or needs a look." : "Run a prompt on a schedule, or whenever you need it."} actions={currentTask ? taskHeader : <div className="tasks-actions"><Seg ariaLabel="View" value={view} onChange={setView} options={[{ value: 'schedule', label: 'Schedule', icon: 'clock' }, { value: 'board', label: 'Board', icon: 'panel' }]}/><input className="st-input tasks-search" type="search" aria-label={tr("Search tasks")} placeholder={tr("Search tasks…")} value={query} onChange={e => setQuery(e.target.value)}/>{tr(view === 'board' ? null : <Select ariaLabel={tr("Sort tasks")} value={sort} options={[{ value: 'next', label: 'Next run' }, { value: 'name', label: 'Name' }]} onChange={setSort}/>)}<IconBtn name="plus" title={tr("New task")} onClick={() => open(blank())}/></div>}>
<div className="tasks-page">
- {tr(!currentTask && <p className="task-runtime small muted"><Icon name="clock" size={16}/>{tr(library?.mode === 'simulated' ? 'Example model · sample answers. ' : '')}{tr("Runs while Strata\u2019s host is open. Runs saved instructions using the loaded model.")}</p>)}
+ {tr(!currentTask && view !== 'board' && <p className="task-runtime small muted"><Icon name="clock" size={16}/>{tr(library?.mode === 'simulated' ? 'Example model · sample answers. ' : '')}{tr("Runs while Strata\u2019s host is open. Runs saved instructions using the loaded model.")}</p>)}
{tr(error && !editor ? <ErrorNotice message={error} onRetry={() => void refresh()}/> : null)}
- {tr(currentTask ? null : !ready ? <p className="muted">{tr("Loading tasks\u2026")}</p> : !visible.length ? <div className="tasks-empty"><Icon name="clock" size={72}/><h2 className="h3">{tr(query ? 'No matching tasks' : 'No scheduled tasks yet')}</h2><p className="muted">{tr(query ? 'Try another search.' : 'Create one with the + button.')}</p></div> : <div className="task-list">{tr(visible.map(t => <article key={t.id} className="task-row"><span className="task-icon"><Icon name="clock" size={24}/></span><div className="task-copy"><h2 className="h4">{t.title}</h2><p className="small muted">{tr(t.status === 'running' ? 'Running…' : t.enabled ? (t.nextRunAt ? `Next: ${new Date(t.nextRunAt).toLocaleString(localeTag(), { dateStyle: 'medium', timeStyle: 'short' })}` : 'Scheduled · calculating next run') : 'Paused')} · {tr(t.timeZone)}</p>{tr(t.error ? <button className="task-failed text-action" onClick={() => setResult(t.id!)}>{tr("Last run failed \u00B7 View")}</button> : null)}{tr(t.output ? <button className="text-action" onClick={() => setResult(t.id!)}>{tr("View last result")}{tr(t.demo ? ' · Example' : '')}</button> : null)}</div><div className="row"><><IconBtn name="pencil" title={tr("Edit {0}", [t.title])} disabled={pending || t.status === 'running'} onClick={() => open(t)}/><Btn size="sm" icon={t.status === 'running' ? 'stop' : 'bolt'} title={tr(t.status === 'running' ? `Stop ${t.title}` : `Run ${t.title} now`)} disabled={pending || !loaded} onClick={() => void action(() => api.post(`/api/tasks/${t.id}/${t.status === 'running' ? 'stop' : 'run'}`))}>{tr(t.status === 'running' ? 'Stop' : 'Run now')}</Btn><label className="row small"><span>{tr("On schedule")}</span><button className="st-toggle" role="switch" aria-label={tr("Schedule {0}", [t.title])} aria-checked={t.enabled} disabled={pending || t.status === 'running'} onClick={() => void action(() => api.patch(`/api/tasks/${t.id}`, { enabled: !t.enabled }))}/></label></></div></article>))}</div>)}
+ {tr(currentTask || view === 'board' ? null : !ready ? <p className="muted">{tr("Loading tasks\u2026")}</p> : !visible.length ? <div className="tasks-empty"><Icon name="clock" size={72}/><h2 className="h3">{tr(query ? 'No matching tasks' : 'No scheduled tasks yet')}</h2><p className="muted">{tr(query ? 'Try another search.' : 'Create one with the + button.')}</p></div> : <div className="task-list">{tr(visible.map(t => <article key={t.id} className="task-row"><span className="task-icon"><Icon name="clock" size={24}/></span><div className="task-copy"><h2 className="h4">{t.title}</h2><p className="small muted">{tr(t.status === 'running' ? 'Running…' : t.enabled ? (t.nextRunAt ? `Next: ${new Date(t.nextRunAt).toLocaleString(localeTag(), { dateStyle: 'medium', timeStyle: 'short' })}` : 'Scheduled · calculating next run') : 'Paused')} · {tr(t.timeZone)}</p>{tr(t.error ? <button className="task-failed text-action" onClick={() => setResult(t.id!)}>{tr("Last run failed \u00B7 View")}</button> : null)}{tr(t.output ? <button className="text-action" onClick={() => setResult(t.id!)}>{tr("View last result")}{tr(t.demo ? ' · Example' : '')}</button> : null)}</div><div className="row"><><IconBtn name="pencil" title={tr("Edit {0}", [t.title])} disabled={pending || t.status === 'running'} onClick={() => open(t)}/><Btn size="sm" icon={t.status === 'running' ? 'stop' : 'bolt'} title={tr(t.status === 'running' ? `Stop ${t.title}` : `Run ${t.title} now`)} disabled={pending || !loaded} onClick={() => void action(() => api.post(`/api/tasks/${t.id}/${t.status === 'running' ? 'stop' : 'run'}`))}>{tr(t.status === 'running' ? 'Stop' : 'Run now')}</Btn><label className="row small"><span>{tr("On schedule")}</span><button className="st-toggle" role="switch" aria-label={tr("Schedule {0}", [t.title])} aria-checked={t.enabled} disabled={pending || t.status === 'running'} onClick={() => void action(() => api.patch(`/api/tasks/${t.id}`, { enabled: !t.enabled }))}/></label></></div></article>))}</div>)}
+ {tr(!currentTask && view === 'board' ? <TaskBoard query={query} canRun={!!loaded || !!native?.instances.some(i => i.status === 'ready')} onViewResult={setResult}/> : null)}
{tr(currentTask ? <TaskDetail task={currentTask}/> : null)}
</div>
{tr(editor ? <TaskEditor task={editor} assistant={assistant} onClose={closeEditor}/> : null)}
diff --git a/apps/host/src/styles/board.css b/apps/host/src/styles/board.css
new file mode 100644
index 000000000..f3562dd89
--- /dev/null
+++ b/apps/host/src/styles/board.css
@@ -0,0 +1,73 @@
+/* The task board (Tasks > Board) and its sidebar count. Only the kit's tokens: no new colours. */
+
+.navcount { display: inline-grid; place-items: center; min-width: 18px; height: 18px; margin-left: 8px; padding: 0 5px; border-radius: var(--st-r-pill); background: var(--st-warn-tint); color: var(--st-warn-text); font: 700 11px/1 var(--st-font); letter-spacing: 0; text-transform: none; }
+.navsession__dot { flex: none; width: 6px; height: 6px; border-radius: 50%; background: var(--st-accent); }
+.navsession__dot--warn { background: var(--st-warn); }
+
+.board-wrap { container-type: inline-size; min-width: 0; }
+.board-note { display: flex; align-items: center; gap: 8px; margin: 0 0 14px; font-size: var(--st-fs-sm); color: var(--st-ink-muted); }
+.board-note svg { flex: none; }
+.board { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; align-items: start; }
+@container (max-width: 1080px) { .board { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
+@container (max-width: 560px) { .board { grid-template-columns: minmax(0, 1fr); } }
+
+.bcol { background: var(--st-surface-2); border: 1px solid var(--st-line-soft); border-radius: var(--st-r-lg); padding: 12px 12px 14px; display: flex; flex-direction: column; gap: 10px; min-width: 0; }
+[data-theme='dark'] .bcol { background: var(--st-surface); }
+.bcol__head { display: flex; align-items: center; gap: 8px; padding: 2px 4px 4px; }
+.bcol__dot { width: 8px; height: 8px; border-radius: 50%; background: var(--st-ink-muted); flex: none; }
+.bcol[data-tone='run'] .bcol__dot { background: var(--st-accent); box-shadow: 0 0 0 4px var(--st-accent-tint); }
+.bcol[data-tone='wait'] .bcol__dot { background: var(--st-info); box-shadow: 0 0 0 4px var(--st-info-tint); }
+.bcol[data-tone='bad'] .bcol__dot { background: var(--st-warn); box-shadow: 0 0 0 4px var(--st-warn-tint); }
+.bcol__name { margin: 0; font-size: 11px; font-weight: 700; letter-spacing: 0.06em; text-transform: uppercase; color: var(--st-ink-soft); }
+.bcol__count { margin-left: auto; font-size: var(--st-fs-xs); font-weight: 700; color: var(--st-ink-muted); font-variant-numeric: tabular-nums; }
+.bcol__hint { margin: -4px 4px 2px; font-size: var(--st-fs-xs); color: var(--st-ink-muted); line-height: 1.4; }
+.bcol__empty { margin: 2px 4px 6px; font-size: var(--st-fs-sm); color: var(--st-ink-muted); }
+
+.bcard { position: relative; background: var(--st-surface); border: 1px solid var(--st-line); border-radius: var(--st-r-md); box-shadow: var(--st-sh-card); padding: 14px 14px 12px; display: flex; flex-direction: column; gap: 6px; min-width: 0; }
+[data-theme='dark'] .bcard { background: var(--st-surface-2); }
+.bcard__top { display: flex; align-items: center; flex-wrap: wrap; gap: 2px 8px; font-size: var(--st-fs-xs); color: var(--st-ink-muted); }
+.bsrc { display: inline-flex; align-items: center; gap: 5px; font-weight: 700; color: var(--st-ink-muted); min-width: 0; white-space: nowrap; }
+.bsrc svg { flex: none; }
+.btime { margin-left: auto; font-variant-numeric: tabular-nums; text-align: right; white-space: nowrap; }
+.bcard__title { margin: 0; font-size: var(--st-fs-base); font-weight: 700; line-height: 1.3; overflow-wrap: anywhere; }
+.bcard__where { display: flex; align-items: center; gap: 6px; font-size: var(--st-fs-xs); color: var(--st-ink-muted); }
+.bcard__where svg { flex: none; }
+.bcard__line { margin: 2px 0 0; font-size: var(--st-fs-sm); line-height: 1.45; color: var(--st-ink-soft); display: -webkit-box; -webkit-line-clamp: 2; line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; overflow-wrap: anywhere; }
+.bcard__why { display: flex; align-items: flex-start; gap: 6px; margin-top: 2px; padding: 8px 10px; border-radius: 10px; font-size: var(--st-fs-sm); line-height: 1.4; overflow-wrap: anywhere; }
+.bcard__why > svg { flex: none; margin-top: 1px; }
+.bcard__why--bad { background: var(--st-danger-tint); color: var(--st-danger-text); }
+.bcard__why--warn { background: var(--st-warn-tint); color: var(--st-warn-text); }
+.bcard__why--ask { background: var(--st-info-tint); color: var(--st-info-text); }
+.bcard__detail { margin-top: 4px; font-size: var(--st-fs-xs); }
+.bcard__detail summary { cursor: pointer; }
+.bcard__detail pre { margin: 4px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; opacity: 0.85; }
+.bcard__bar { height: 4px; border-radius: var(--st-r-pill); background: var(--st-line-soft); overflow: hidden; margin-top: 4px; }
+.bcard__bar i { display: block; height: 100%; width: 38%; background: var(--st-accent); border-radius: inherit; animation: board-slide 1.8s ease-in-out infinite; }
+@keyframes board-slide { 0% { transform: translateX(-110%); } 100% { transform: translateX(270%); } }
+@media (prefers-reduced-motion: reduce) { .bcard__bar i { animation: none; width: 100%; opacity: 0.45; } }
+html[data-motion='reduced'] .bcard__bar i { animation: none; width: 100%; opacity: 0.45; }
+.bcard__actions { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
+.bcard__actions .spacer { flex: 1; }
+.bcard__actions .st-btn--icon { width: 32px; height: 32px; }
+.bchip { display: inline-flex; align-items: center; gap: 5px; height: 22px; padding: 0 8px; border-radius: var(--st-r-pill); font-size: 11px; font-weight: 700; background: var(--st-surface-2); color: var(--st-ink-muted); border: 1px solid var(--st-line); }
+[data-theme='dark'] .bchip { background: var(--st-surface); }
+.bchip--good { background: var(--st-accent-tint); color: var(--st-accent-text); border-color: transparent; }
+.bcol--done .bcard { opacity: 0.96; }
+.board-menu-sep { border: 0; border-top: 1px solid var(--st-line-soft); margin: 4px 2px; }
+
+.upnext { margin-top: 16px; padding: 12px 16px; display: flex; align-items: center; flex-wrap: wrap; gap: 8px 14px; background: var(--st-surface); border: 1px solid var(--st-line); border-radius: var(--st-r-md); font-size: var(--st-fs-sm); color: var(--st-ink-soft); }
+.upnext > svg { color: var(--st-icon); flex: none; }
+.upnext .navgroup__label { padding: 0; }
+.upnext__item { display: inline-flex; align-items: center; gap: 6px; min-width: 0; }
+.upnext__item a { color: inherit; text-decoration: none; }
+.upnext__item a:hover { text-decoration: underline; }
+.upnext .i { color: var(--st-ink-muted); }
+.upnext .sep { width: 1px; height: 18px; background: var(--st-line); margin-right: 8px; }
+
+.tasks-actions .st-tabs { flex: none; }
+.bcol--done .bcard__actions { flex-wrap: nowrap; }
+.bcol--done .bcard__actions > .st-btn { flex: none; }
+.bchip { flex: 0 1 auto; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.bchip svg { flex: none; }
+.bcol--done .bcard__actions { gap: 4px; }
+.bcol--done .bcard__actions .st-btn--ghost { padding-inline: 8px; }
diff --git a/apps/host/tests/board.test.mjs b/apps/host/tests/board.test.mjs
new file mode 100644
index 000000000..579e4bd9b
--- /dev/null
+++ b/apps/host/tests/board.test.mjs
@@ -0,0 +1,249 @@
+// The task board: what lands in which column, which button a card gets, what a dismissal hides, and what the host keeps so that it
+// stays true (a new run clears the last problem; the loop and chat records the board reads).
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { build } from 'esbuild';
+import { createTaskService } from '../server/tasks.mjs';
+import { lastLine } from '../server/task-report.mjs';
+
+const compiled = await build({ stdin: { contents: "export * from './src/lib/board'; export * from './src/lib/loop-runner'; export * from './src/lib/task-handover'; export * from './src/lib/i18n';", resolveDir: process.cwd(), loader: 'ts' }, bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json' } });
+const { boardCards, isInside, canApproveOnBoard, plainLine, folderName, LoopScheduler, chatHandoverMessage } = await import(`data:text/javascript;base64,${Buffer.from(compiled.outputFiles[0].text).toString('base64')}`);
+
+const NOW = Date.parse('2026-10-19T12:00:00Z');
+const ago = ms => new Date(NOW - ms).toISOString();
+const MIN = 60_000, HOUR = 3_600_000, DAY = 86_400_000;
+const task = (over = {}) => ({ id: 't1', title: 'Backup check', prompt: 'p', frequency: 'daily', at: '02:00', weekday: 1, timeZone: 'UTC', enabled: true, nextRunAt: new Date(NOW + HOUR).toISOString(), status: 'done', lastRunAt: ago(2 * HOUR), finishedAt: ago(2 * HOUR - MIN), ...over });
+const msg = (role, content, over = {}) => ({ id: `m${Math.random()}`, role, content, at: ago(HOUR), ...over });
+const chat = (over = {}) => ({ id: 'c1', title: 'Fix rounding', workspace: 'C:\\work\\billing-api', createdAt: ago(DAY), updatedAt: ago(HOUR), messages: [msg('user', 'fix it'), msg('assistant', 'Fixed. Totals now round to the cent.')], tokensIn: 0, tokensOut: 0, ...over });
+const input = (over = {}) => ({ tasks: [], sessions: [], liveChats: [], loopChats: [], pending: null, activeSession: null, now: NOW, ...over });
+const ask = (over = {}) => ({ id: 'tool1', name: 'write_file', args: {}, preview: 'logs/a.txt', effect: 'Change a file', scope: 'write', target: 'C:\\work\\billing-api\\logs\\a.txt', state: 'proposed', live: true, ...over });
+const waitingChat = (tool, over = {}) => chat({ messages: [msg('user', 'go'), msg('assistant', '', { tools: [tool] })], ...over });
+const ids = list => list.map(c => c.id);
+
+test('a scheduled task lands where its state puts it', () => {
+ const b = boardCards(input({ tasks: [
+ task({ id: 'run', status: 'running', lastRunAt: ago(2 * MIN), finishedAt: null }),
+ task({ id: 'err', status: 'error', error: 'no model loaded' }),
+ task({ id: 'stop', status: 'cancelled', error: 'Run stopped.' }),
+ task({ id: 'gone', status: 'interrupted' }),
+ task({ id: 'yes', status: 'done', attention: 'It wanted a yes.', lastLine: 'All 4 folders read.' }),
+ task({ id: 'ok', status: 'done', lastLine: 'Twelve changes this week.' }),
+ task({ id: 'new', status: 'idle', lastRunAt: undefined, finishedAt: undefined }),
+ task({ id: 'old', status: 'done', finishedAt: ago(8 * DAY), lastRunAt: ago(8 * DAY) }),
+ task({ id: 'arch', status: 'error', archived: true, error: 'x' }),
+ ] }));
+ assert.deepEqual(ids(b.columns.running), ['run']);
+ assert.deepEqual(ids(b.columns.attention).sort(), ['err', 'gone', 'stop', 'yes']);
+ assert.deepEqual(ids(b.columns.done), ['ok'], 'older than 7 days, archived and never-run tasks are not on the board');
+ assert.deepEqual(b.columns.waiting, []);
+ assert.equal(b.need, 4);
+ assert.deepEqual(b.problemTasks.sort(), ['err', 'gone', 'stop', 'yes']);
+});
+
+test('a task card has one next step and a menu, by what happened', () => {
+ const b = boardCards(input({ tasks: [task({ id: 'run', status: 'running', finishedAt: null }), task({ id: 'err', status: 'error', error: 'boom' }), task({ id: 'yes', attention: 'a' }), task({ id: 'ok' })] }));
+ const by = id => Object.values(b.columns).flat().find(c => c.id === id);
+ assert.deepEqual([by('run').primary, by('run').menu], ['stop-task', ['open-task']]);
+ assert.deepEqual([by('err').primary, by('err').menu], ['run-again', ['open-task', 'continue', 'dismiss']]);
+ assert.deepEqual([by('yes').primary, by('yes').menu], ['continue', ['open-task', 'dismiss']], 'a run that needed a yes continues in a new chat');
+ assert.deepEqual([by('ok').primary, by('ok').menu], ['view-result', ['dismiss']], 'a Done card can be dismissed too');
+ assert.equal(by('err').reason.tone, 'bad');
+ assert.equal(by('yes').reason.tone, 'warn');
+});
+
+test('dismissing a task hides that run only; a newer run brings its problem back', () => {
+ const failed = task({ status: 'error', error: 'boom', finishedAt: ago(3 * HOUR) });
+ assert.equal(boardCards(input({ tasks: [{ ...failed, ackedAt: ago(HOUR) }] })).need, 0);
+ assert.equal(boardCards(input({ tasks: [{ ...failed, ackedAt: ago(4 * HOUR) }] })).need, 1, 'dismissed before this run ended');
+ const done = task({ ackedAt: ago(MIN) });
+ assert.equal(boardCards(input({ tasks: [done] })).columns.done.length, 0);
+});
+
+test('the next scheduled runs are listed soonest first, paused tasks left out', () => {
+ const b = boardCards(input({ tasks: [task({ id: 'b', title: 'B', nextRunAt: new Date(NOW + 2 * HOUR).toISOString() }), task({ id: 'a', title: 'A', nextRunAt: new Date(NOW + HOUR).toISOString() }), task({ id: 'p', enabled: false })] }));
+ assert.deepEqual(b.upcoming.map(u => u.id), ['a', 'b']);
+});
+
+test('a chat waits only while the host still holds the approval', () => {
+ const s = waitingChat(ask());
+ assert.deepEqual(ids(boardCards(input({ sessions: [s], liveChats: ['c1'], pending: [{ chatId: 'c1', callIds: ['tool1'], at: NOW - 4 * MIN }] })).columns.waiting), ['c1']);
+ const gone = boardCards(input({ sessions: [s], pending: [] }));
+ assert.equal(gone.columns.waiting.length, 0, 'the host no longer holds it: a stale card is not a question');
+ assert.equal(boardCards(input({ sessions: [s], pending: null })).columns.waiting.length, 1, 'unknown: trust the card');
+ const card = boardCards(input({ sessions: [s], liveChats: ['c1'], pending: [{ chatId: 'c1', callIds: ['tool1'], at: NOW - 4 * MIN }] })).columns.waiting[0];
+ assert.equal(card.at, NOW - 4 * MIN);
+ assert.equal(boardCards(input({ sessions: [s], liveChats: ['c1'], pending: [{ chatId: 'c1', callIds: ['tool1'] }] })).columns.running.length, 0, 'a waiting chat is not also running');
+});
+
+test('Approve on the card is for file read and write inside the chat folder; the rest opens the chat', () => {
+ const card = tool => boardCards(input({ sessions: [waitingChat(tool)] })).columns.waiting[0];
+ const ok = card(ask());
+ assert.equal(ok.primary, 'approve');
+ assert.deepEqual(ok.menu, ['deny', 'open-chat']);
+ assert.deepEqual(ok.approve.toolId, 'tool1');
+ for (const tool of [ask({ scope: 'shell', target: 'rm -rf logs' }), ask({ scope: 'connected', target: 'github' }), ask({ target: 'C:\\work\\other\\a.txt' }), ask({ target: 'C:\\work\\billing-api\\..\\secret.txt' }), ask({ target: undefined })]) {
+ const c = card(tool);
+ assert.equal(c.primary, 'open-chat', JSON.stringify(tool));
+ assert.equal(c.approve, undefined);
+ }
+ assert.equal(canApproveOnBoard({ scope: 'read', target: 'src/a.ts' }, 'C:\\work\\billing-api'), true, 'a relative path is in the folder');
+ assert.equal(canApproveOnBoard({ scope: 'read', target: 'c:\\WORK\\Billing-API\\a.ts' }, 'C:\\work\\billing-api'), true, 'Windows paths ignore case');
+ assert.equal(isInside('/home/me/proj/a.ts', '/home/me/proj'), true);
+ assert.equal(isInside('/home/me/project2/a.ts', '/home/me/proj'), false, 'a sibling with the same start is outside');
+ assert.equal(isInside('/home/me/Proj/a.ts', '/home/me/proj'), false, 'Linux paths do not ignore case');
+});
+
+test('a running chat and a running loop are one card each, never two for the same chat', () => {
+ const loop = { prompt: 'check the build', everyMs: 10 * MIN, startedAt: NOW - 20 * MIN, state: 'running', answers: 2, maxRuns: 6, nextAt: NOW + 4 * MIN, lastText: 'Build is still red.' };
+ const b = boardCards(input({ sessions: [chat({ loop }), chat({ id: 'c2', title: 'Refactor', agents: [{ id: 'a', name: 'h', description: '', status: 'working', durationMs: 0, tokens: 0 }] })], liveChats: ['c2'], loopChats: ['c1'] }));
+ assert.deepEqual(b.columns.running.map(c => [c.key, c.primary, c.menu]), [['chat:c2', 'open-chat', ['stop-chat']], ['loop:c1', 'stop-loop', ['open-chat']]].sort((x, y) => b.columns.running.findIndex(c => c.key === x[0]) - b.columns.running.findIndex(c => c.key === y[0])));
+ const l = b.columns.running.find(c => c.source === 'loop');
+ assert.deepEqual(l.meta, { text: 'answer {0} of {1}', params: [3, 6] });
+ assert.equal(l.nextAt, NOW + 4 * MIN);
+ assert.equal(b.columns.running.find(c => c.id === 'c2').meta.params[0], 1);
+});
+
+test('a loop that ended is Done, unless 3 runs in a row failed; then it needs attention', () => {
+ const ended = why => chat({ loop: { prompt: 'watch', everyMs: 5 * MIN, startedAt: NOW - HOUR, state: 'ended', endedWhy: why, endedAt: NOW - 10 * MIN, answers: 3 } });
+ for (const why of ['count', 'said-done', 'time', 'cap', 'stopped', 'closed']) {
+ const b = boardCards(input({ sessions: [ended(why)] }));
+ assert.equal(b.columns.done.length, 1, why);
+ assert.equal(b.columns.attention.length, 0, why);
+ }
+ const bad = boardCards(input({ sessions: [ended('failures')] })).columns.attention[0];
+ assert.equal(bad.reason.kind, 'loop-failed');
+ assert.deepEqual([bad.primary, bad.menu], ['open-chat', ['continue', 'dismiss']]);
+ const running = chat({ loop: { prompt: 'x', everyMs: MIN, startedAt: NOW - HOUR, state: 'running', answers: 1 } });
+ assert.equal(boardCards(input({ sessions: [running] })).columns.done[0].chip.text, 'Stopped when Strata closed', 'a record that says running with no loop behind it is a loop the window closed on');
+});
+
+test('chats show up only with something to do, from the last 7 days', () => {
+ const b = boardCards(input({ sessions: [
+ chat({ id: 'unread', lastReadAt: ago(2 * HOUR) }),
+ chat({ id: 'seen', lastReadAt: ago(30 * MIN) }),
+ chat({ id: 'open' }),
+ chat({ id: 'old', updatedAt: ago(8 * DAY), lastReadAt: ago(9 * DAY) }),
+ chat({ id: 'bad', messages: [msg('user', 'go'), msg('assistant', '', { error: 'The model stopped while starting.' })] }),
+ chat({ id: 'typing', messages: [msg('user', 'hello')] }),
+ chat({ id: 'stream', lastReadAt: ago(DAY), messages: [msg('user', 'go'), msg('assistant', 'part', { streaming: true })] }),
+ chat({ id: 'arch', archived: true, lastReadAt: ago(DAY) }),
+ ], activeSession: 'open' }));
+ assert.deepEqual(ids(b.columns.done), ['unread']);
+ assert.deepEqual(ids(b.columns.attention), ['bad']);
+ assert.deepEqual([b.columns.attention[0].primary, b.columns.attention[0].menu], ['open-chat', ['continue', 'dismiss']]);
+ assert.equal(b.columns.done[0].folder, 'billing-api');
+});
+
+test('dismissing a chat card hides it until something newer happens in that chat', () => {
+ const bad = chat({ messages: [msg('user', 'go'), msg('assistant', '', { error: 'boom' })], updatedAt: ago(HOUR) });
+ assert.equal(boardCards(input({ sessions: [{ ...bad, ackedAt: ago(30 * MIN) }] })).need, 0);
+ assert.equal(boardCards(input({ sessions: [{ ...bad, ackedAt: ago(2 * HOUR) }] })).need, 1);
+ const endedLoop = chat({ loop: { prompt: 'x', everyMs: MIN, startedAt: NOW - HOUR, state: 'ended', endedWhy: 'failures', endedAt: NOW - 20 * MIN, answers: 0 } });
+ assert.equal(boardCards(input({ sessions: [{ ...endedLoop, ackedAt: ago(10 * MIN) }] })).need, 0);
+});
+
+test('every column is newest first', () => {
+ const b = boardCards(input({ tasks: [task({ id: 'a', finishedAt: ago(3 * HOUR) }), task({ id: 'b', finishedAt: ago(HOUR) })] }));
+ assert.deepEqual(ids(b.columns.done), ['b', 'a']);
+});
+
+test('small helpers: one plain line, a folder name', () => {
+ assert.equal(plainLine('**Fixed.** Totals now round to the cent and the tests pass. More text.'), 'Fixed. Totals now round to the cent and the tests pass.');
+ assert.equal(plainLine('# Report\n\n- first thing\n- second'), 'Report first thing second');
+ assert.equal(folderName('C:\\work\\billing-api\\'), 'billing-api');
+ assert.equal(folderName(''), undefined);
+});
+
+/* ---- what the host and the loop keep for the board ---- */
+
+test('the host line for a card is the first plain sentence, without the list of steps or the note', () => {
+ assert.equal(lastLine('Two things need your attention. Disk space is low.\n\n---\n\n**What it did**\n\n- Read the log\n\n> needed a yes'), 'Two things need your attention.');
+ assert.equal(lastLine('**All 4** backup folders were found and read.\n\n> note'), 'All 4 backup folders were found and read.');
+ assert.equal(lastLine(''), '');
+ assert.ok(lastLine('x'.repeat(500)).length <= 160);
+});
+
+function service(run, seed = []) {
+ let db = seed, t = Date.parse('2026-10-19T12:00:00Z');
+ const svc = createTaskService({ read: () => db, write: r => { db = JSON.parse(JSON.stringify(r)); }, run, now: () => t });
+ return { svc, advance: ms => { t += ms; }, db: () => db };
+}
+const draft = { title: 'T', prompt: 'p', frequency: 'daily', at: '08:00', weekday: 1, timeZone: 'UTC', mode: 'plan' };
+
+test('a run records when it ended and its one plain line; a failure keeps only the newest problem', async () => {
+ let n = 0;
+ const { svc, advance } = service(async () => {
+ n += 1;
+ if (n === 1) return { text: 'All 4 folders read.\n\n> It wanted a yes.', attention: 'It wanted a yes.' };
+ if (n === 2) throw new Error('first problem');
+ if (n === 3) throw new Error('second problem');
+ return { text: 'Fine now.' };
+ });
+ const id = svc.put(draft).id;
+ await svc.execute(id);
+ let t = svc.list()[0];
+ assert.equal(t.status, 'done'); assert.equal(t.attention, 'It wanted a yes.'); assert.equal(t.lastLine, 'All 4 folders read.'); assert.ok(t.finishedAt);
+ advance(MIN);
+ await svc.execute(id);
+ t = svc.list()[0];
+ assert.equal(t.status, 'error'); assert.equal(t.error, 'first problem'); assert.equal(t.attention, null, 'a stale "needed a yes" does not survive a later run');
+ advance(MIN);
+ await svc.execute(id);
+ assert.equal(svc.list()[0].error, 'second problem', 'only the newest problem is kept');
+ await svc.execute(id);
+ t = svc.list()[0];
+ assert.equal(t.error, null); assert.equal(t.status, 'done');
+});
+
+test('Dismiss is a mark on the task (ackedAt) that a new run clears', async () => {
+ const { svc } = service(async () => { throw new Error('boom'); });
+ const id = svc.put(draft).id;
+ await svc.execute(id);
+ const mark = new Date().toISOString();
+ svc.put({ ackedAt: mark }, id);
+ assert.equal(svc.list()[0].ackedAt, mark);
+ assert.equal(svc.list()[0].error, 'boom', 'dismissing keeps the result');
+ await svc.execute(id);
+ assert.equal(svc.list()[0].ackedAt, null);
+ svc.put({ title: 'Renamed' }, id);
+ assert.equal(svc.list()[0].ackedAt, null, 'an edit that does not mention it leaves it alone');
+});
+
+test('a loop leaves a record on its chat: running with the next time, then how it ended', async () => {
+ const records = [];
+ let clock = 1_000, timer = null;
+ const sched = new LoopScheduler({
+ send: async () => ({ answered: true, text: 'Build is still red: 2 tests fail.', failed: false }),
+ note: () => {}, exists: () => true, ready: () => true, now: () => clock,
+ setTimer: (fn, ms) => { timer = { fn, ms }; return timer; }, clearTimer: () => { timer = null; },
+ track: (id, record) => records.push({ id, ...record }),
+ });
+ await sched.start('c1', { everyMs: 10 * MIN, prompt: 'check the build', maxRuns: 2 });
+ assert.deepEqual(sched.ids(), ['c1']);
+ const waiting = records.at(-1);
+ assert.equal(waiting.state, 'running'); assert.equal(waiting.answers, 1); assert.equal(waiting.nextAt, 1_000 + 10 * MIN); assert.equal(waiting.lastText, 'Build is still red: 2 tests fail.'); assert.equal(waiting.maxRuns, 2);
+ clock += 10 * MIN;
+ await timer.fn();
+ await new Promise(r => setImmediate(r));
+ const ended = records.at(-1);
+ assert.equal(ended.state, 'ended'); assert.equal(ended.endedWhy, 'count'); assert.equal(ended.answers, 2);
+ assert.deepEqual(sched.ids(), []);
+
+ await sched.start('c2', { everyMs: MIN, prompt: 'x' });
+ assert.equal(sched.stop('c2'), true);
+ assert.equal(records.at(-1).endedWhy, 'stopped');
+});
+
+test('"Continue in a new chat" on a chat starts from what was asked, what went wrong and the last answer', () => {
+ const s = chat({ messages: [msg('user', 'Update the dependencies'), msg('assistant', 'Working on it.', { error: 'The model stopped while starting.' }), msg('assistant', 'note', { local: true })] });
+ const text = chatHandoverMessage(s);
+ assert.match(text, /Continuing from the chat “Fix rounding”/);
+ assert.match(text, /Update the dependencies/);
+ assert.match(text, /The model stopped while starting\./);
+ assert.match(text, /Working on it\./);
+ assert.doesNotMatch(text, /note/);
+ assert.match(text, /Please help me take it from here\.$/);
+ const loopText = chatHandoverMessage(chat({ loop: { prompt: 'watch the deploy', everyMs: MIN, startedAt: 0, state: 'ended', endedWhy: 'failures', endedAt: 1, answers: 0 } }));
+ assert.match(loopText, /watch the deploy/);
+ assert.match(loopText, /3 runs in a row did not work/);
+});