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
16.9 KiB249 linesraw
1// 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
2// stays true (a new run clears the last problem; the loop and chat records the board reads).
3import test from 'node:test';
4import assert from 'node:assert/strict';
5import { build } from 'esbuild';
6import { createTaskService } from '../server/tasks.mjs';
7import { lastLine } from '../server/task-report.mjs';
8
9const 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' } });
10const { boardCards, isInside, canApproveOnBoard, plainLine, folderName, LoopScheduler, chatHandoverMessage } = await import(`data:text/javascript;base64,${Buffer.from(compiled.outputFiles[0].text).toString('base64')}`);
11
12const NOW = Date.parse('2026-10-19T12:00:00Z');
13const ago = ms => new Date(NOW - ms).toISOString();
14const MIN = 60_000, HOUR = 3_600_000, DAY = 86_400_000;
15const 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 });
16const msg = (role, content, over = {}) => ({ id: `m${Math.random()}`, role, content, at: ago(HOUR), ...over });
17const 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 });
18const input = (over = {}) => ({ tasks: [], sessions: [], liveChats: [], loopChats: [], pending: null, activeSession: null, now: NOW, ...over });
19const 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 });
20const waitingChat = (tool, over = {}) => chat({ messages: [msg('user', 'go'), msg('assistant', '', { tools: [tool] })], ...over });
21const ids = list => list.map(c => c.id);
22
23test('a scheduled task lands where its state puts it', () => {
24  const b = boardCards(input({ tasks: [
25    task({ id: 'run', status: 'running', lastRunAt: ago(2 * MIN), finishedAt: null }),
26    task({ id: 'err', status: 'error', error: 'no model loaded' }),
27    task({ id: 'stop', status: 'cancelled', error: 'Run stopped.' }),
28    task({ id: 'gone', status: 'interrupted' }),
29    task({ id: 'yes', status: 'done', attention: 'It wanted a yes.', lastLine: 'All 4 folders read.' }),
30    task({ id: 'ok', status: 'done', lastLine: 'Twelve changes this week.' }),
31    task({ id: 'new', status: 'idle', lastRunAt: undefined, finishedAt: undefined }),
32    task({ id: 'old', status: 'done', finishedAt: ago(8 * DAY), lastRunAt: ago(8 * DAY) }),
33    task({ id: 'arch', status: 'error', archived: true, error: 'x' }),
34  ] }));
35  assert.deepEqual(ids(b.columns.running), ['run']);
36  assert.deepEqual(ids(b.columns.attention).sort(), ['err', 'gone', 'stop', 'yes']);
37  assert.deepEqual(ids(b.columns.done), ['ok'], 'older than 7 days, archived and never-run tasks are not on the board');
38  assert.deepEqual(b.columns.waiting, []);
39  assert.equal(b.need, 4);
40  assert.deepEqual(b.problemTasks.sort(), ['err', 'gone', 'stop', 'yes']);
41});
42
43test('a task card has one next step and a menu, by what happened', () => {
44  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' })] }));
45  const by = id => Object.values(b.columns).flat().find(c => c.id === id);
46  assert.deepEqual([by('run').primary, by('run').menu], ['stop-task', ['open-task']]);
47  assert.deepEqual([by('err').primary, by('err').menu], ['run-again', ['open-task', 'continue', 'dismiss']]);
48  assert.deepEqual([by('yes').primary, by('yes').menu], ['continue', ['open-task', 'dismiss']], 'a run that needed a yes continues in a new chat');
49  assert.deepEqual([by('ok').primary, by('ok').menu], ['view-result', ['dismiss']], 'a Done card can be dismissed too');
50  assert.equal(by('err').reason.tone, 'bad');
51  assert.equal(by('yes').reason.tone, 'warn');
52});
53
54test('dismissing a task hides that run only; a newer run brings its problem back', () => {
55  const failed = task({ status: 'error', error: 'boom', finishedAt: ago(3 * HOUR) });
56  assert.equal(boardCards(input({ tasks: [{ ...failed, ackedAt: ago(HOUR) }] })).need, 0);
57  assert.equal(boardCards(input({ tasks: [{ ...failed, ackedAt: ago(4 * HOUR) }] })).need, 1, 'dismissed before this run ended');
58  const done = task({ ackedAt: ago(MIN) });
59  assert.equal(boardCards(input({ tasks: [done] })).columns.done.length, 0);
60});
61
62test('the next scheduled runs are listed soonest first, paused tasks left out', () => {
63  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 })] }));
64  assert.deepEqual(b.upcoming.map(u => u.id), ['a', 'b']);
65});
66
67test('a chat waits only while the host still holds the approval', () => {
68  const s = waitingChat(ask());
69  assert.deepEqual(ids(boardCards(input({ sessions: [s], liveChats: ['c1'], pending: [{ chatId: 'c1', callIds: ['tool1'], at: NOW - 4 * MIN }] })).columns.waiting), ['c1']);
70  const gone = boardCards(input({ sessions: [s], pending: [] }));
71  assert.equal(gone.columns.waiting.length, 0, 'the host no longer holds it: a stale card is not a question');
72  assert.equal(boardCards(input({ sessions: [s], pending: null })).columns.waiting.length, 1, 'unknown: trust the card');
73  const card = boardCards(input({ sessions: [s], liveChats: ['c1'], pending: [{ chatId: 'c1', callIds: ['tool1'], at: NOW - 4 * MIN }] })).columns.waiting[0];
74  assert.equal(card.at, NOW - 4 * MIN);
75  assert.equal(boardCards(input({ sessions: [s], liveChats: ['c1'], pending: [{ chatId: 'c1', callIds: ['tool1'] }] })).columns.running.length, 0, 'a waiting chat is not also running');
76});
77
78test('Approve on the card is for file read and write inside the chat folder; the rest opens the chat', () => {
79  const card = tool => boardCards(input({ sessions: [waitingChat(tool)] })).columns.waiting[0];
80  const ok = card(ask());
81  assert.equal(ok.primary, 'approve');
82  assert.deepEqual(ok.menu, ['deny', 'open-chat']);
83  assert.deepEqual(ok.approve.toolId, 'tool1');
84  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 })]) {
85    const c = card(tool);
86    assert.equal(c.primary, 'open-chat', JSON.stringify(tool));
87    assert.equal(c.approve, undefined);
88  }
89  assert.equal(canApproveOnBoard({ scope: 'read', target: 'src/a.ts' }, 'C:\\work\\billing-api'), true, 'a relative path is in the folder');
90  assert.equal(canApproveOnBoard({ scope: 'read', target: 'c:\\WORK\\Billing-API\\a.ts' }, 'C:\\work\\billing-api'), true, 'Windows paths ignore case');
91  assert.equal(isInside('/home/me/proj/a.ts', '/home/me/proj'), true);
92  assert.equal(isInside('/home/me/project2/a.ts', '/home/me/proj'), false, 'a sibling with the same start is outside');
93  assert.equal(isInside('/home/me/Proj/a.ts', '/home/me/proj'), false, 'Linux paths do not ignore case');
94});
95
96test('a running chat and a running loop are one card each, never two for the same chat', () => {
97  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.' };
98  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'] }));
99  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])));
100  const l = b.columns.running.find(c => c.source === 'loop');
101  assert.deepEqual(l.meta, { text: 'answer {0} of {1}', params: [3, 6] });
102  assert.equal(l.nextAt, NOW + 4 * MIN);
103  assert.equal(b.columns.running.find(c => c.id === 'c2').meta.params[0], 1);
104});
105
106test('a loop that ended is Done, unless 3 runs in a row failed; then it needs attention', () => {
107  const ended = why => chat({ loop: { prompt: 'watch', everyMs: 5 * MIN, startedAt: NOW - HOUR, state: 'ended', endedWhy: why, endedAt: NOW - 10 * MIN, answers: 3 } });
108  for (const why of ['count', 'said-done', 'time', 'cap', 'stopped', 'closed']) {
109    const b = boardCards(input({ sessions: [ended(why)] }));
110    assert.equal(b.columns.done.length, 1, why);
111    assert.equal(b.columns.attention.length, 0, why);
112  }
113  const bad = boardCards(input({ sessions: [ended('failures')] })).columns.attention[0];
114  assert.equal(bad.reason.kind, 'loop-failed');
115  assert.deepEqual([bad.primary, bad.menu], ['open-chat', ['continue', 'dismiss']]);
116  const running = chat({ loop: { prompt: 'x', everyMs: MIN, startedAt: NOW - HOUR, state: 'running', answers: 1 } });
117  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');
118});
119
120test('chats show up only with something to do, from the last 7 days', () => {
121  const b = boardCards(input({ sessions: [
122    chat({ id: 'unread', lastReadAt: ago(2 * HOUR) }),
123    chat({ id: 'seen', lastReadAt: ago(30 * MIN) }),
124    chat({ id: 'open' }),
125    chat({ id: 'old', updatedAt: ago(8 * DAY), lastReadAt: ago(9 * DAY) }),
126    chat({ id: 'bad', messages: [msg('user', 'go'), msg('assistant', '', { error: 'The model stopped while starting.' })] }),
127    chat({ id: 'typing', messages: [msg('user', 'hello')] }),
128    chat({ id: 'stream', lastReadAt: ago(DAY), messages: [msg('user', 'go'), msg('assistant', 'part', { streaming: true })] }),
129    chat({ id: 'arch', archived: true, lastReadAt: ago(DAY) }),
130  ], activeSession: 'open' }));
131  assert.deepEqual(ids(b.columns.done), ['unread']);
132  assert.deepEqual(ids(b.columns.attention), ['bad']);
133  assert.deepEqual([b.columns.attention[0].primary, b.columns.attention[0].menu], ['open-chat', ['continue', 'dismiss']]);
134  assert.equal(b.columns.done[0].folder, 'billing-api');
135});
136
137test('dismissing a chat card hides it until something newer happens in that chat', () => {
138  const bad = chat({ messages: [msg('user', 'go'), msg('assistant', '', { error: 'boom' })], updatedAt: ago(HOUR) });
139  assert.equal(boardCards(input({ sessions: [{ ...bad, ackedAt: ago(30 * MIN) }] })).need, 0);
140  assert.equal(boardCards(input({ sessions: [{ ...bad, ackedAt: ago(2 * HOUR) }] })).need, 1);
141  const endedLoop = chat({ loop: { prompt: 'x', everyMs: MIN, startedAt: NOW - HOUR, state: 'ended', endedWhy: 'failures', endedAt: NOW - 20 * MIN, answers: 0 } });
142  assert.equal(boardCards(input({ sessions: [{ ...endedLoop, ackedAt: ago(10 * MIN) }] })).need, 0);
143});
144
145test('every column is newest first', () => {
146  const b = boardCards(input({ tasks: [task({ id: 'a', finishedAt: ago(3 * HOUR) }), task({ id: 'b', finishedAt: ago(HOUR) })] }));
147  assert.deepEqual(ids(b.columns.done), ['b', 'a']);
148});
149
150test('small helpers: one plain line, a folder name', () => {
151  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.');
152  assert.equal(plainLine('# Report\n\n- first thing\n- second'), 'Report first thing second');
153  assert.equal(folderName('C:\\work\\billing-api\\'), 'billing-api');
154  assert.equal(folderName(''), undefined);
155});
156
157/* ---- what the host and the loop keep for the board ---- */
158
159test('the host line for a card is the first plain sentence, without the list of steps or the note', () => {
160  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.');
161  assert.equal(lastLine('**All 4** backup folders were found and read.\n\n> note'), 'All 4 backup folders were found and read.');
162  assert.equal(lastLine(''), '');
163  assert.ok(lastLine('x'.repeat(500)).length <= 160);
164});
165
166function service(run, seed = []) {
167  let db = seed, t = Date.parse('2026-10-19T12:00:00Z');
168  const svc = createTaskService({ read: () => db, write: r => { db = JSON.parse(JSON.stringify(r)); }, run, now: () => t });
169  return { svc, advance: ms => { t += ms; }, db: () => db };
170}
171const draft = { title: 'T', prompt: 'p', frequency: 'daily', at: '08:00', weekday: 1, timeZone: 'UTC', mode: 'plan' };
172
173test('a run records when it ended and its one plain line; a failure keeps only the newest problem', async () => {
174  let n = 0;
175  const { svc, advance } = service(async () => {
176    n += 1;
177    if (n === 1) return { text: 'All 4 folders read.\n\n> It wanted a yes.', attention: 'It wanted a yes.' };
178    if (n === 2) throw new Error('first problem');
179    if (n === 3) throw new Error('second problem');
180    return { text: 'Fine now.' };
181  });
182  const id = svc.put(draft).id;
183  await svc.execute(id);
184  let t = svc.list()[0];
185  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);
186  advance(MIN);
187  await svc.execute(id);
188  t = svc.list()[0];
189  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');
190  advance(MIN);
191  await svc.execute(id);
192  assert.equal(svc.list()[0].error, 'second problem', 'only the newest problem is kept');
193  await svc.execute(id);
194  t = svc.list()[0];
195  assert.equal(t.error, null); assert.equal(t.status, 'done');
196});
197
198test('Dismiss is a mark on the task (ackedAt) that a new run clears', async () => {
199  const { svc } = service(async () => { throw new Error('boom'); });
200  const id = svc.put(draft).id;
201  await svc.execute(id);
202  const mark = new Date().toISOString();
203  svc.put({ ackedAt: mark }, id);
204  assert.equal(svc.list()[0].ackedAt, mark);
205  assert.equal(svc.list()[0].error, 'boom', 'dismissing keeps the result');
206  await svc.execute(id);
207  assert.equal(svc.list()[0].ackedAt, null);
208  svc.put({ title: 'Renamed' }, id);
209  assert.equal(svc.list()[0].ackedAt, null, 'an edit that does not mention it leaves it alone');
210});
211
212test('a loop leaves a record on its chat: running with the next time, then how it ended', async () => {
213  const records = [];
214  let clock = 1_000, timer = null;
215  const sched = new LoopScheduler({
216    send: async () => ({ answered: true, text: 'Build is still red: 2 tests fail.', failed: false }),
217    note: () => {}, exists: () => true, ready: () => true, now: () => clock,
218    setTimer: (fn, ms) => { timer = { fn, ms }; return timer; }, clearTimer: () => { timer = null; },
219    track: (id, record) => records.push({ id, ...record }),
220  });
221  await sched.start('c1', { everyMs: 10 * MIN, prompt: 'check the build', maxRuns: 2 });
222  assert.deepEqual(sched.ids(), ['c1']);
223  const waiting = records.at(-1);
224  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);
225  clock += 10 * MIN;
226  await timer.fn();
227  await new Promise(r => setImmediate(r));
228  const ended = records.at(-1);
229  assert.equal(ended.state, 'ended'); assert.equal(ended.endedWhy, 'count'); assert.equal(ended.answers, 2);
230  assert.deepEqual(sched.ids(), []);
231
232  await sched.start('c2', { everyMs: MIN, prompt: 'x' });
233  assert.equal(sched.stop('c2'), true);
234  assert.equal(records.at(-1).endedWhy, 'stopped');
235});
236
237test('"Continue in a new chat" on a chat starts from what was asked, what went wrong and the last answer', () => {
238  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 })] });
239  const text = chatHandoverMessage(s);
240  assert.match(text, /Continuing from the chat “Fix rounding”/);
241  assert.match(text, /Update the dependencies/);
242  assert.match(text, /The model stopped while starting\./);
243  assert.match(text, /Working on it\./);
244  assert.doesNotMatch(text, /note/);
245  assert.match(text, /Please help me take it from here\.$/);
246  const loopText = chatHandoverMessage(chat({ loop: { prompt: 'watch the deploy', everyMs: MIN, startedAt: 0, state: 'ended', endedWhy: 'failures', endedAt: 1, answers: 0 } }));
247  assert.match(loopText, /watch the deploy/);
248  assert.match(loopText, /3 runs in a row did not work/);
249});