From dca9770ef4f78d353dc06a98c35a775cc1a4ffb1 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 19 Oct 2026 21:05:20 +0200 Subject: [PATCH] Task board: Schedule | Board view on Tasks, derivation with tests, loop record, sidebar count, all 8 locales --- apps/host/src/app/TaskTree.tsx | 6 +- apps/host/src/components/TaskBoard.tsx | 202 ++++++++++++++++++++ apps/host/src/components/ui.tsx | 3 +- apps/host/src/lib/board.ts | 234 +++++++++++++++++++++++ apps/host/src/lib/loop-runner.ts | 28 ++- apps/host/src/lib/store.ts | 53 +++++- apps/host/src/lib/task-handover.ts | 26 +++ apps/host/src/lib/types.ts | 23 +++ apps/host/src/lib/use-board.ts | 65 +++++++ apps/host/src/locales/de.json | 59 +++++- apps/host/src/locales/en.json | 59 +++++- apps/host/src/locales/es.json | 59 +++++- apps/host/src/locales/ja.json | 59 +++++- apps/host/src/locales/ko.json | 59 +++++- apps/host/src/locales/pt.json | 59 +++++- apps/host/src/locales/ru.json | 59 +++++- apps/host/src/locales/zh.json | 59 +++++- apps/host/src/main.tsx | 2 + apps/host/src/screens/Tasks.tsx | 15 +- apps/host/src/styles/board.css | 73 ++++++++ apps/host/tests/board.test.mjs | 249 +++++++++++++++++++++++++ 21 files changed, 1432 insertions(+), 19 deletions(-) create mode 100644 apps/host/src/components/TaskBoard.tsx create mode 100644 apps/host/src/lib/board.ts create mode 100644 apps/host/src/lib/use-board.ts create mode 100644 apps/host/src/styles/board.css create mode 100644 apps/host/tests/board.test.mjs diff --git a/apps/host/src/app/TaskTree.tsx b/apps/host/src/app/TaskTree.tsx index f24b29d4..3da95228 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(null); const location = useLocation(); + const { board } = useBoard(); const [open, setOpen] = useState(() => localStorage.getItem('strata.tasks-open') !== 'false'); const [tasks, setTasks] = useState([]), [remove, setRemove] = useState(null), [error, setError] = useState(''), [busy, setBusy] = useState(false); const [leaving, setLeaving] = useState(null); @@ -76,8 +78,8 @@ export function TaskTree({ collapsed }: { if (collapsed) return dialogs; return
-
{ setNavOpen(false); setEditor(blankTask()); }}/>
- {tr(open ?
{tr(tasks.map(t =>
{t.title}{tr(!t.enabled ? : null)}
))}{tr(!tasks.length ?

{tr("No tasks yet")}

: null)}{tr(error && !remove ?

{tr("Couldn\u2019t load tasks.")}

: null)}
: null)} +
{ setNavOpen(false); setEditor(blankTask()); }}/>
+ {tr(open ?
{tr(tasks.map(t =>
{t.title}{tr(board.problemTasks.includes(t.id) ? : null)}{tr(!t.enabled ? : null)}
))}{tr(!tasks.length ?

{tr("No tasks yet")}

: null)}{tr(error && !remove ?

{tr("Couldn\u2019t load tasks.")}

: null)}
: null)} {dialogs}
; } diff --git a/apps/host/src/components/TaskBoard.tsx b/apps/host/src/components/TaskBoard.tsx new file mode 100644 index 00000000..43e3e67e --- /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 = { + '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 {text}{raw ?
{tr('Details')}
{raw}
: null}
; +} + +/* ------------------------------------------------------------------- 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' ? <>{tr('Scheduled task')} : card.source === 'chat' ? <>{tr('Chat')} : <>{tr('Loop · {0}', [everyShort(card.everyMs ?? 0)])}; + const where = card.folder || card.meta ?
{card.folder ? <>{card.folder} : null}{card.folder && card.meta ? ' · ' : ''}{card.meta ? tr(card.meta.text, card.meta.params) : null}
: null; + const button = (action: BoardAction, variant: 'primary' | 'secondary' | 'ghost') => { + const a = ACTION[action]; + const off = busy || (action === 'run-again' && !canRun); + return run(card, action)}>{tr(a.label)}; + }; + const iconFor = (action: BoardAction, label?: string) => run(card, action)}/>; + + let actions: ReactNode; + if (card.column === 'waiting') { + actions = card.approve + ? <>{button('approve', 'primary')}{button('deny', 'secondary')}{iconFor('open-chat')} + : <>{button(card.primary, 'secondary')}; + } else if (card.column === 'done') { + actions = <>{card.chip ? {tr(card.chip.text)} : null}{button(card.primary, 'ghost')}{iconFor('dismiss')}; + } else { + const variant = card.column === 'attention' ? 'primary' : 'secondary'; + actions = <>{button(card.primary, variant)} + {card.menu.length === 1 ? iconFor(card.menu[0]) : card.menu.length > 1 + ? : null}; + } + + return
+
{source}{cardTime(card, now)}
+

{card.title}

+ {where} + {card.line ?

{card.line}

: null} + {card.reason ?
: null} + {card.busy ? : null} +
{actions}
+
; +} + +/* ------------------------------------------------------------------ board */ + +export function TaskBoard({ query, canRun, onViewResult }: { query: string; canRun: boolean; onViewResult: (taskId: string) => void }) { + const { board, ready, tasks } = useBoard(); + const [busy, setBusy] = useState>({}); + 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()); + + 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
+

{tr('Cards move on their own as things happen. A card in Needs attention stays there until you deal with it or dismiss it.')}

+

{board.need ? tr('{0} need your attention', [board.need]) : tr('Nothing needs you right now.')}

+
+ {COLUMNS.map(col => { + const cards = shown(board.columns[col.id]); + const headId = `bcol-${col.id}`; + return
+
+ {col.hint ?

{tr(col.hint)}

: null} + {cards.map(card => )} + {!cards.length ?

{ready ? tr(q && total ? 'No matching cards.' : 'Nothing here right now.') : tr('Loading tasks…')}

: null} +
; + })} +
+ {board.upcoming.length ?
{tr('Coming up')} + {board.upcoming.map((u, i) => {i ? )}
: null} + {menu ? setMenu(null)}> + {menu.card.menu.map(action =>
{action === 'dismiss' && menu.card.menu.length > 1 ?
: null}
)} +
: null} +
; +} diff --git a/apps/host/src/components/ui.tsx b/apps/host/src/components/ui.tsx index 3297162b..a319355f 100644 --- a/apps/host/src/components/ui.tsx +++ b/apps/host/src/components/ui.tsx @@ -128,6 +128,7 @@ export function Seg({ value, options, onChange, ariaLabel, pan options: { value: T; label: string; + icon?: IconName; title?: string; disabled?: boolean; }[]; @@ -150,7 +151,7 @@ export function Seg({ 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 ? : null)}{tr(o.label)} )))} ); } diff --git a/apps/host/src/lib/board.ts b/apps/host/src/lib/board.ts new file mode 100644 index 00000000..7ad7c830 --- /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; + /** 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, 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 = { 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 6f489136..22d66979 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) { + 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): 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 6613a8d9..74ee2b48 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), + 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 ff3d5d5d..8301d09f 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) => 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 530884bc..1e8b053e 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 00000000..46411101 --- /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 | 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 7b417751..e24fe16f 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 8260511e..44dc7202 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 57b033b8..a61b6d85 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 e6e9dd1b..2ea9e8cb 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 daedbabb..5acfc703 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 7d8b4739..06614f99 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 a3885803..51bae0e1 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 7576dba2..e0cf24ec 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 a35e3f83..7162366c 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 971ff0f6..4ac52d07 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([]), [query, setQuery] = useState(''), [sort, setSort] = useState('next'), archived = false; const [editor, setEditor] = useState(null), [assistant, setAssistant] = useState(false), [pending, setPending] = useState(false), [error, setError] = useState(''), [ready, setReady] = useState(false), [result, setResult] = useState(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 ?
@@ -74,12 +80,13 @@ export function TasksScreen() { {tr(currentTask.lastRunAt || currentTask.output || currentTask.error ? continueTaskInNewChat(currentTask)}>{tr("Continue in a new chat")} : null)} void action(() => api.post(`/api/tasks/${currentTask.id}/${currentTask.status === 'running' ? 'stop' : 'run'}`))}>{tr(currentTask.status === 'running' ? 'Stop' : 'Run now')}
: null; - return {currentTask.title}
: "Tasks"} sub={currentTask ? undefined : "Run a prompt on a schedule, or whenever you need it."} actions={currentTask ? taskHeader :
setQuery(e.target.value)}/> setQuery(e.target.value)}/>{tr(view === 'board' ? null :