okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

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

main
13.6 KiB234 linesraw
1import type { Ask } from './ask';
2import type { Session, ToolCall } from './types';
3import type { Task } from './tasks';
4
5/**
6 * The task board (Tasks screen, "Board"). One pure function turns what the app already knows (scheduled tasks from the host, chats and
7 * their loops from the browser, the approvals the host is holding) into cards in four columns. Nothing here is stored as "board state":
8 * 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
9 * like loop.ts.
10 *
11 * One card per thing: a chat shows once, in the first place that fits (waiting for you, running, needs attention, done), and a task
12 * shows once. A task or chat the person dismissed stays off the board until a newer run or turn brings a problem back.
13 */
14
15export type BoardColumn = 'running' | 'waiting' | 'attention' | 'done';
16
17/** What a button on a card does. The component maps each one to a call; the order of `menu` is the order shown. */
18export type BoardAction = 'stop-task' | 'run-again' | 'open-task' | 'open-chat' | 'stop-chat' | 'stop-loop' | 'approve' | 'deny' | 'continue' | 'dismiss' | 'view-result';
19
20/** Why a card needs the person. `kind` names the sentence; the component writes it in the person's language. */
21export interface BoardReason {
22  tone: 'bad' | 'warn' | 'ask';
23  kind: 'task-failed' | 'task-stopped' | 'task-closed' | 'task-needs-yes' | 'chat-failed' | 'loop-failed' | 'ask';
24  /** The original error text, for the failures a person can open under Details. */
25  detail?: string;
26  /** The approval question, for `ask`. */
27  ask?: Ask;
28  /** What the tool wants to do, when the host sent no question. */
29  fallback?: string;
30  params?: (string | number)[];
31}
32
33export interface BoardCard {
34  /** Stable across refreshes: the source and its id. */
35  key: string;
36  column: BoardColumn;
37  source: 'task' | 'chat' | 'loop';
38  /** Task id for a task; chat id for a chat or a loop. */
39  id: string;
40  title: string;
41  /** Milliseconds. What the time on the card is about, and the sort key (newest first). */
42  at: number;
43  timeKind: 'started' | 'waiting' | 'next' | 'stopped' | 'plain';
44  /** For a loop that is running: when its next answer is due. */
45  nextAt?: number;
46  /** A loop's rhythm in milliseconds, for "Loop · every 10 min". */
47  everyMs?: number;
48  folder?: string;
49  /** The muted part after the folder: "2 helpers working", "answer 3 of 6". */
50  meta?: { text: string; params?: (string | number)[] };
51  line?: string;
52  reason?: BoardReason;
53  /** Done cards: the chip beside the button. */
54  chip?: { text: string; tone: 'good' | 'plain' };
55  /** A card whose run is going on shows a moving bar. */
56  busy?: boolean;
57  primary: BoardAction;
58  menu: BoardAction[];
59  /** Set on a Waiting card that may be answered from the board (a file read or write inside the chat's folder). */
60  approve?: { messageId: string; toolId: string };
61}
62
63export interface BoardPending { chatId: string; callIds: string[]; at?: number; folder?: string | null }
64
65export interface BoardInput {
66  tasks: readonly Task[];
67  sessions: readonly Session[];
68  /** Chats with a turn going. */
69  liveChats: readonly string[];
70  /** Chats with a /loop going. */
71  loopChats: readonly string[];
72  /** 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. */
73  pending: readonly BoardPending[] | null;
74  activeSession: string | null;
75  now: number;
76  days?: number;
77}
78
79export interface BoardResult {
80  columns: Record<BoardColumn, BoardCard[]>;
81  /** Waiting for you plus Needs attention: the number the sidebar shows. */
82  need: number;
83  /** The next scheduled runs. */
84  upcoming: { id: string; title: string; at: number }[];
85  /** Task ids that have a problem the person has not dismissed (the sidebar's dot). */
86  problemTasks: string[];
87}
88
89export const BOARD_DAYS = 7;
90const DAY = 86_400_000;
91
92const time = (iso?: string | null) => { const n = iso ? Date.parse(iso) : NaN; return Number.isFinite(n) ? n : 0; };
93
94/** The last folder name of a path: how a chat's working folder is shown on a card. */
95export function folderName(path?: string | null): string | undefined {
96  const parts = String(path ?? '').split(/[\\/]+/).filter(Boolean);
97  return parts.length ? parts[parts.length - 1] : undefined;
98}
99
100const normal = (p: string) => p.replace(/\\/g, '/').replace(/\/+$/, '');
101
102/**
103 * Is `target` inside `folder`? Relative paths count (the agent works in the folder) unless they climb out with "..". Anything else
104 * (another drive, another tree, a path that cannot be told) is not: those need the whole conversation in front of the person.
105 */
106export function isInside(target: string | undefined | null, folder: string | undefined | null): boolean {
107  if (!target || !folder) return false;
108  const t = normal(String(target).trim()), f = normal(String(folder).trim());
109  if (!t || !f || t.split('/').includes('..')) return false;
110  const windows = /^[a-z]:/i.test(f) || String(folder).includes('\\');
111  const absolute = /^([a-z]:)?\//i.test(t);
112  if (!absolute) return !/^[a-z]:/i.test(t);
113  const a = windows ? t.toLowerCase() : t, b = windows ? f.toLowerCase() : f;
114  return a === b || a.startsWith(b + '/');
115}
116
117/** 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. */
118export function canApproveOnBoard(tool: Pick<ToolCall, 'scope' | 'target'>, folder: string | undefined | null): boolean {
119  return (tool.scope === 'read' || tool.scope === 'write') && isInside(tool.target, folder);
120}
121
122/** One plain line from an answer: markdown off, first sentence (or two when the first is tiny), cut at 160 characters. */
123export function plainLine(text: string | undefined | null, max = 160): string {
124  let body = String(text ?? '').replace(/```[\s\S]*?```/g, ' ').replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/^\s*(#{1,6}|[-*+]|\d+[.)]|>)\s+/gm, '').replace(/[*_`~]/g, '');
125  body = body.replace(/\s+/g, ' ').trim();
126  if (!body) return '';
127  const sentence = /^.*?[.!?](?=\s|$)/.exec(body)?.[0] ?? body;
128  const two = /^.*?[.!?](?=\s|$)\s*.*?[.!?](?=\s|$)/.exec(body)?.[0] ?? body;
129  const pick = sentence.length < 24 && body.length > sentence.length ? two : sentence;
130  return pick.length > max ? `${pick.slice(0, max - 1).trimEnd()}…` : pick;
131}
132
133function lastAssistant(s: Session) {
134  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; }
135  return undefined;
136}
137
138/** Dismissed: the person dismissed it at or after the moment of the thing shown. */
139const dismissed = (ackedAt: string | null | undefined, since: number) => !!ackedAt && time(ackedAt) >= since;
140
141export function boardCards(input: BoardInput): BoardResult {
142  const { now } = input, window = (input.days ?? BOARD_DAYS) * DAY;
143  const live = new Set(input.liveChats), loops = new Set(input.loopChats);
144  const columns: Record<BoardColumn, BoardCard[]> = { running: [], waiting: [], attention: [], done: [] };
145  const problemTasks: string[] = [];
146  const upcoming: BoardResult['upcoming'] = [];
147
148  /* ---- scheduled tasks ---- */
149  for (const t of input.tasks) {
150    if (t.archived || !t.id) continue;
151    const base = { key: `task:${t.id}`, source: 'task' as const, id: t.id, title: t.title };
152    const ran = time(t.lastRunAt), fin = time(t.finishedAt) || ran;
153    if (t.enabled && t.nextRunAt) upcoming.push({ id: t.id, title: t.title, at: time(t.nextRunAt) });
154    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; }
155    if (dismissed(t.ackedAt, fin)) continue;
156    const failed = t.status === 'error' || t.status === 'cancelled' || t.status === 'interrupted';
157    if (failed) {
158      problemTasks.push(t.id);
159      const kind = t.status === 'error' ? 'task-failed' : t.status === 'cancelled' ? 'task-stopped' : 'task-closed';
160      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'] });
161    } else if (t.attention) {
162      problemTasks.push(t.id);
163      // A run that was auto-denied: the useful next step is a chat that can carry on with the person's yes.
164      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'] });
165    } else if (t.status === 'done' && fin && now - fin <= window) {
166      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'] });
167    }
168  }
169
170  /* ---- chats and loops ---- */
171  const pendingBy = new Map((input.pending ?? []).map(p => [p.chatId, p]));
172  for (const s of input.sessions) {
173    if (s.archived || s.showcase) continue;
174    const base = { id: s.id, title: s.title, folder: folderName(s.workspace) };
175    const answer = lastAssistant(s);
176
177    // Waiting for you: a card the host still holds.
178    const held = pendingBy.get(s.id);
179    let proposed: { messageId: string; tool: ToolCall } | undefined;
180    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; }
181    if (proposed) {
182      const { tool, messageId } = proposed;
183      const folder = held?.folder ?? s.workspace;
184      const ok = canApproveOnBoard(tool, folder);
185      columns.waiting.push({ ...base, key: `chat:${s.id}`, source: 'chat', column: 'waiting', at: held?.at || time(s.updatedAt), timeKind: 'waiting',
186        reason: { tone: 'ask', kind: 'ask', ...(tool.ask ? { ask: tool.ask } : {}), fallback: tool.effect || tool.preview || tool.name },
187        primary: ok ? 'approve' : 'open-chat', menu: ok ? ['deny', 'open-chat'] : [], ...(ok ? { approve: { messageId, toolId: tool.id } } : {}) });
188      continue;
189    }
190
191    // Running: a loop that is going, or a turn that is.
192    if (loops.has(s.id) && s.loop) {
193      const l = s.loop;
194      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,
195        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'] });
196      continue;
197    }
198    if (live.has(s.id)) {
199      const helpers = (s.agents ?? []).filter(a => a.status === 'working').length;
200      const lastUser = [...s.messages].reverse().find(m => m.role === 'user');
201      columns.running.push({ ...base, key: `chat:${s.id}`, source: 'chat', column: 'running', at: time(lastUser?.at) || time(s.updatedAt), timeKind: 'started', busy: true,
202        ...(helpers ? { meta: { text: helpers === 1 ? '1 helper working' : '{0} helpers working', params: [helpers] } } : {}), line: plainLine(answer?.content) || undefined, primary: 'open-chat', menu: ['stop-chat'] });
203      continue;
204    }
205
206    // A loop that ended (or that the window closed on) speaks for the whole chat.
207    if (s.loop) {
208      const l = s.loop;
209      const why = l.state === 'running' ? 'closed' : l.endedWhy ?? 'closed';
210      const when = l.endedAt ?? time(s.updatedAt);
211      if (dismissed(s.ackedAt, when) || now - when > window) continue;
212      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 };
213      if (why === 'failures') columns.attention.push({ ...common, column: 'attention', reason: { tone: 'bad', kind: 'loop-failed' }, primary: 'open-chat', menu: ['continue', 'dismiss'] });
214      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'] });
215      continue;
216    }
217
218    // Chats: only what has something to do, in the window.
219    const when = time(s.updatedAt);
220    if (!when || now - when > window || dismissed(s.ackedAt, when) || !answer || answer.streaming) continue;
221    if (answer.error) {
222      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'] });
223      continue;
224    }
225    const unread = s.id !== input.activeSession && (s.lastReadAt ? s.updatedAt > s.lastReadAt : s.messages.length > 0);
226    if (unread && answer.content?.trim() && s.messages[s.messages.length - 1] === answer) {
227      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'] });
228    }
229  }
230
231  for (const list of Object.values(columns)) list.sort((a, b) => b.at - a.at);
232  upcoming.sort((a, b) => a.at - b.at);
233  return { columns, need: columns.waiting.length + columns.attention.length, upcoming: upcoming.slice(0, 5), problemTasks };
234}