tasks run as the agent in their own session under a per-task mode, with a plain result and a notification; task editor and toast strings in all eight languages
This commit is contained in:
1 parent
be1a871349
commit
158a42d8b6
17 files changed
+295
-17
No files matched your search
@@ -612,7 +612,10 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
if (r) { r.events?.close(); r.gw.close(); await r.hp.stop(); }
|
||||
}
|
||||
|
||||
return { status, runTurn, goalCommand, approve, stop, pendingFor, close, sessionOf: chatId => sessionMap[chatId]?.sessionId ?? null, isRunning: chatId => !!chats.get(chatId)?.turn, _debug: () => ({ rt, sessionMap }) };
|
||||
/** Let go of a chat's Harness session mapping (a task starts every run in a session of its own). */
|
||||
function forget(chatId) { if (chats.get(chatId)?.turn) return; delete sessionMap[chatId]; chats.delete(chatId); persist(); }
|
||||
|
||||
return { status, runTurn, goalCommand, forget, approve, stop, pendingFor, close, sessionOf: chatId => sessionMap[chatId]?.sessionId ?? null, isRunning: chatId => !!chats.get(chatId)?.turn, _debug: () => ({ rt, sessionMap }) };
|
||||
}
|
||||
|
||||
/** A goal that stopped by itself, in words. */
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* A scheduled task as the agent: a Harness session of its own, under the mode the task was given, tools included.
|
||||
*
|
||||
* Nobody is at the screen when it runs, so a request for approval is answered "no" at once and reported in the result: nothing is
|
||||
* changed without a person saying yes. (Plan changes nothing; Manual therefore stops at the first change and says what it was; Bypass
|
||||
* is full access and asks nothing.) Every run starts a fresh session, so yesterday's run does not fill today's context.
|
||||
*/
|
||||
import { taskReport } from '../task-report.mjs';
|
||||
|
||||
/**
|
||||
* @param {{agent: object, choice: () => ({instanceId:string}|{connectionId:string, modelId:string}|null), workspace: string}} deps `choice` names the model the task runs on
|
||||
* @returns {(task: object, signal?: AbortSignal) => Promise<{text:string, attention:string|null, demo:boolean}|null>} null = no local model is ready (the caller falls back)
|
||||
*/
|
||||
export function createAgentTaskRunner({ agent, choice, workspace }) {
|
||||
return async function runAgentTask(task, signal) {
|
||||
const model = choice();
|
||||
if (!model) return null;
|
||||
const chatId = `task:${task.id}`;
|
||||
const cards = new Map();
|
||||
let text = '', failure = null;
|
||||
const stop = () => void agent.stop(chatId).catch(() => {});
|
||||
signal?.addEventListener('abort', stop, { once: true });
|
||||
try {
|
||||
await agent.runTurn({
|
||||
chatId, message: task.prompt, workspacePath: workspace, choice: model, mode: task.mode ?? 'plan', history: [],
|
||||
onFrame: frame => {
|
||||
if (frame.type === 'delta') text += frame.text ?? '';
|
||||
else if (frame.type === 'error') failure = frame.message;
|
||||
else if (frame.type === 'agent-tool') {
|
||||
cards.set(frame.tool.id, { ...(cards.get(frame.tool.id) ?? {}), ...frame.tool });
|
||||
if (frame.tool.state === 'proposed') void agent.approve({ chatId, callId: frame.tool.id, decision: 'deny' }).catch(() => {});
|
||||
}
|
||||
},
|
||||
});
|
||||
} finally { signal?.removeEventListener('abort', stop); agent.forget(chatId); }
|
||||
signal?.throwIfAborted();
|
||||
if (failure) throw new Error(failure);
|
||||
return taskReport({ text, cards: [...cards.values()] });
|
||||
};
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { resolvePython, shellPrefix } from './python-resolver.mjs';
|
||||
import { chooseFolder, typedFolder, TYPE_A_PATH } from './folder-dialog.mjs';
|
||||
import { createLocalShare } from './local-share.mjs';
|
||||
import { createTaskService, validateTask } from './tasks.mjs';
|
||||
import { createAgentTaskRunner } from './agent/task-run.mjs';
|
||||
import { migrateSetup } from './setup.mjs';
|
||||
import { skillEdit } from './skill-edits.mjs';
|
||||
import { systemFonts } from './fonts.mjs';
|
||||
@@ -705,10 +706,21 @@ const timeskip = createTimeSkip({
|
||||
env: { ...process.env, STRATA_TIMESKIP_DIR: process.env.STRATA_TIMESKIP_DIR ?? '' },
|
||||
});
|
||||
|
||||
const runAgentTask = createAgentTaskRunner({
|
||||
agent, workspace: WORKSPACE,
|
||||
// The loaded local model. (STRATA_TASK_REMOTE_MODEL="<connection id>:<model id>" lets a developer or an API-only setup name a saved API model instead.)
|
||||
choice: () => {
|
||||
try { return { instanceId: native.resolveInstance(native.state().defaultId).id }; } catch { /* no local model is ready */ }
|
||||
const [connectionId, ...rest] = String(process.env.STRATA_TASK_REMOTE_MODEL ?? '').split(':');
|
||||
return connectionId && rest.length ? { connectionId, modelId: rest.join(':') } : null;
|
||||
},
|
||||
});
|
||||
const tasks = createTaskService({
|
||||
read: () => store.get().tasks ?? [],
|
||||
write: records => store.update({ tasks: records }),
|
||||
notify: task => hub.send('task', { id: task.id, title: task.title, status: task.status, attention: task.attention ?? null, error: task.error ?? null }),
|
||||
run: async (task, signal) => {
|
||||
if (agent.status().state !== 'unavailable') { const agentResult = await runAgentTask(task, signal); if (agentResult) return agentResult; }
|
||||
let text = '', failure = null, demo = !models.REAL;
|
||||
await runTurn({ message: task.prompt, signal, client: `Task: ${task.title}`, onFrame: frame => {
|
||||
if (frame.type === 'delta') text += frame.text ?? '';
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* What a task that ran as the agent shows in Tasks ("Last result"): the agent's own answer, then a short plain list of what it
|
||||
* did, then - if it hit something that needed a person's yes - exactly what that was. Pure, so it is tested without an agent.
|
||||
*/
|
||||
const clip = (value, max) => {
|
||||
const text = String(value ?? '').replace(/\s+/g, ' ').trim();
|
||||
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
||||
};
|
||||
|
||||
/** One card as a line a person can read. */
|
||||
export function cardLine(card) {
|
||||
const what = clip(card.effect || card.preview || card.name, 140);
|
||||
const detail = card.preview && card.effect && card.preview !== card.effect ? ` (${clip(card.preview, 100)})` : '';
|
||||
if (card.state === 'denied') return `- Could not do this by itself: ${what}${detail}. Nothing was changed.`;
|
||||
if (card.state === 'error') return `- Tried: ${what}${detail}. It did not work.`;
|
||||
return `- ${what}${detail}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{text:string, cards:Array}} run
|
||||
* @returns {{text:string, attention:string|null, demo:boolean}}
|
||||
*/
|
||||
export function taskReport({ text, cards }) {
|
||||
const done = cards.filter(c => c.state !== 'proposed');
|
||||
const refused = cards.filter(c => c.state === 'denied');
|
||||
const lines = done.map(cardLine);
|
||||
const answer = String(text ?? '').trim();
|
||||
let out = answer || (cards.length ? 'The task ran.' : 'The task ran and had nothing to report.');
|
||||
if (lines.length) out += `\n\n---\n\n**What it did**\n\n${lines.join('\n')}`;
|
||||
const attention = refused.length
|
||||
? `This task wanted to change something and needed a yes, which nobody could give while it ran by itself: ${refused.map(c => clip(c.effect || c.name, 100)).join('; ')}. Nothing was changed. Edit the task and let it make changes if you want it to.`
|
||||
: null;
|
||||
if (attention) out += `\n\n> ${attention}`;
|
||||
return { text: out, attention, demo: false };
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
/** Small host-owned schedules. No tools, shell commands or catch-up bursts. */
|
||||
/**
|
||||
* Small host-owned schedules. No catch-up bursts. A task runs as the agent (a Harness session of its own) under the mode it was
|
||||
* given when it was created: `plan` (looks, changes nothing), `manual` (asks first: nobody is there to answer, so it stops at the
|
||||
* first thing that needs a yes and says what that was) or `bypass` (full access). The default is `plan`.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto';
|
||||
const frequencies = ['hourly', 'daily', 'weekdays', 'weekly'];
|
||||
export const TASK_MODES = ['plan', 'manual', 'bypass'];
|
||||
export function validateTask(input) {
|
||||
const title = String(input.title ?? '').trim(), prompt = String(input.prompt ?? '').trim();
|
||||
if (!title || title.length > 120) throw new Error('Use a task name of 1–120 characters.');
|
||||
@@ -11,7 +16,9 @@ export function validateTask(input) {
|
||||
if (!Number.isInteger(weekday) || weekday < 0 || weekday > 6) throw new Error('Choose a weekday.');
|
||||
const timeZone = String(input.timeZone ?? 'UTC');
|
||||
new Intl.DateTimeFormat('en', { timeZone }).format();
|
||||
return { title, prompt, frequency: input.frequency, at: input.at, weekday, timeZone, enabled: input.enabled !== false };
|
||||
const mode = input.mode ?? 'plan';
|
||||
if (!TASK_MODES.includes(mode)) throw new Error('Choose what this task may do.');
|
||||
return { title, prompt, frequency: input.frequency, at: input.at, weekday, timeZone, mode, enabled: input.enabled !== false };
|
||||
}
|
||||
export function nextRun(task, after = Date.now()) {
|
||||
const format = new Intl.DateTimeFormat('en-GB', { timeZone: task.timeZone, year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'short', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' });
|
||||
@@ -33,7 +40,7 @@ export function nextRun(task, after = Date.now()) {
|
||||
}
|
||||
throw new Error('Could not calculate the next run.');
|
||||
}
|
||||
export function createTaskService({ read, write, run, now = Date.now }) {
|
||||
export function createTaskService({ read, write, run, notify = () => {}, now = Date.now, timeoutMs = 15 * 60_000 }) {
|
||||
let records = read().map(t => ({ ...t, status: t.status === 'running' ? 'interrupted' : t.status, nextRunAt: t.enabled && !t.archived ? nextRun(t, now()) : null }));
|
||||
const controllers = new Map();
|
||||
const save = () => write(records);
|
||||
@@ -54,10 +61,10 @@ export function createTaskService({ read, write, run, now = Date.now }) {
|
||||
const controller = new AbortController(); controllers.set(id, controller);
|
||||
t.status = 'running'; t.lastRunAt = new Date(now()).toISOString(); t.error = null;
|
||||
t.nextRunAt = t.enabled ? nextRun(t, now()) : null; save();
|
||||
const timeout = setTimeout(() => controller.abort(), 120000); timeout.unref?.();
|
||||
try { const result = await run(t, controller.signal); t.output = result.text.slice(0, 100000); t.demo = result.demo; t.status = 'done'; }
|
||||
const timeout = setTimeout(() => controller.abort(), timeoutMs); timeout.unref?.();
|
||||
try { const result = await run(t, controller.signal); t.output = result.text.slice(0, 100000); t.demo = result.demo; t.attention = result.attention ?? null; t.status = 'done'; }
|
||||
catch (e) { t.status = controller.signal.aborted ? 'cancelled' : 'error'; t.error = controller.signal.aborted ? 'Run stopped.' : String(e.message ?? e); }
|
||||
finally { clearTimeout(timeout); controllers.delete(id); save(); }
|
||||
finally { clearTimeout(timeout); controllers.delete(id); save(); try { notify(t); } catch { /* a notification is a courtesy */ } }
|
||||
}
|
||||
function tick() { for (const t of records) if (t.enabled && !t.archived && t.status !== 'running' && t.nextRunAt && Date.parse(t.nextRunAt) <= now()) void execute(t.id); }
|
||||
return { list, put, execute, tick, stop: id => controllers.get(id)?.abort(), close: () => controllers.forEach(c => c.abort()) };
|
||||
|
||||
@@ -53,6 +53,7 @@ export function TaskEditor({ task, assistant = false, onClose, onSaved }: {
|
||||
</> : <>
|
||||
<div className="task-schedule-summary"><strong>{editor.title}</strong><p className="small muted">{editor.prompt}</p></div>
|
||||
<div className="task-schedule"><div className="input-field"><span>{tr("Repeat")}</span><Select ariaLabel={tr("Repeat task")} value={editor.frequency} options={[{ value: 'hourly', label: 'Every hour' }, { value: 'daily', label: 'Every day' }, { value: 'weekdays', label: 'Weekdays' }, { value: 'weekly', label: 'Every week' }]} onChange={frequency => setEditor({ ...editor, frequency })}/></div>{tr(editor.frequency !== 'hourly' ? <label className="input-field"><span>{tr("Time")}</span><input type="time" className="st-input" disabled={pending} value={editor.at} onChange={e => setEditor({ ...editor, at: e.target.value })}/></label> : null)}{tr(editor.frequency === 'weekly' ? <div className="input-field"><span>{tr("Day")}</span><Select ariaLabel={tr("Day of week")} value={String(editor.weekday)} options={['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'].map((label, i) => ({ value: String(i), label }))} onChange={v => setEditor({ ...editor, weekday: Number(v) })}/></div> : null)}</div>
|
||||
<div className="input-field"><span>{tr("What this task may do")}</span><Select ariaLabel={tr("What this task may do")} value={editor.mode ?? 'plan'} options={[{ value: 'plan', label: 'Look only, change nothing' }, { value: 'manual', label: 'Stop and tell me before changing anything' }, { value: 'bypass', label: 'Allowed to make changes' }]} onChange={mode => setEditor({ ...editor, mode: mode as Task['mode'] })}/></div>
|
||||
<label className="row small"><input type="checkbox" disabled={pending} checked={editor.enabled} onChange={e => setEditor({ ...editor, enabled: e.target.checked })}/>{tr("Run on schedule")}</label>
|
||||
<p className="xs muted">{tr(editor.timeZone)}{tr(" \u00B7 Missed runs are skipped while Strata is closed.")}</p>
|
||||
</>)}
|
||||
|
||||
@@ -628,6 +628,14 @@ function applyEvent(e: StreamEvent) {
|
||||
case 'setup':
|
||||
set({ setup: data as unknown as SetupState });
|
||||
break;
|
||||
case 'task': {
|
||||
// A task finished on its own (the host ran it on schedule): say so, and say when it needs a person's yes or failed.
|
||||
const t = data as unknown as { title?: string; status?: string; attention?: string | null; error?: string | null };
|
||||
if (t.status === 'error') pushToast('error', 'Task failed', String(t.title ?? ''));
|
||||
else if (t.attention) pushToast('warn', 'Task needs your yes', String(t.title ?? ''));
|
||||
else if (t.status === 'done') pushToast('success', 'Task finished', String(t.title ?? ''));
|
||||
break;
|
||||
}
|
||||
case 'agent':
|
||||
if (typeof data.sessionId === 'string') patchSession(data.sessionId, s => ({ ...s, agents: updateAgent(s.agents ?? [], data.agent) }));
|
||||
break;
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
export interface Task { id?: string; title: string; prompt: string; frequency: string; at: string; weekday: number; timeZone: string; enabled: boolean; archived?: boolean; nextRunAt?: string; lastRunAt?: string; status?: string; output?: string; demo?: boolean; error?: string; }
|
||||
export const blankTask = (): Task => ({ title:'', prompt:'', frequency:'daily', at:'09:00', weekday:1, timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone, enabled:true });
|
||||
export interface Task { id?: string; title: string; prompt: string; frequency: string; at: string; weekday: number; timeZone: string; mode?: 'plan' | 'manual' | 'bypass'; enabled: boolean; archived?: boolean; nextRunAt?: string; lastRunAt?: string; status?: string; output?: string; demo?: boolean; error?: string; attention?: string | null; }
|
||||
export const blankTask = (): Task => ({ title:'', prompt:'', frequency:'daily', at:'09:00', weekday:1, timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone, mode:'plan', enabled:true });
|
||||
@@ -2568,5 +2568,12 @@
|
||||
"s2567": "Prüfe, ob die Engine verbunden und dieses Modell installiert ist, und versuche es erneut.",
|
||||
"s2568": "Ausgeführt",
|
||||
"s2569": "In diesem Modus nicht erlaubt. Es wurde nichts ausgeführt.",
|
||||
"s2570": "Vorschau erneut abspielen"
|
||||
"s2570": "Vorschau erneut abspielen",
|
||||
"s2571": "Was diese Aufgabe darf",
|
||||
"s2572": "Nur ansehen, nichts ändern",
|
||||
"s2573": "Vor jeder Änderung anhalten und mir Bescheid geben",
|
||||
"s2574": "Darf Änderungen vornehmen",
|
||||
"s2575": "Aufgabe abgeschlossen",
|
||||
"s2576": "Aufgabe braucht Ihr Ja",
|
||||
"s2577": "Aufgabe fehlgeschlagen"
|
||||
}
|
||||
@@ -2568,5 +2568,12 @@
|
||||
"s2567": "Check that the engine is connected and this model is installed, then try again.",
|
||||
"s2568": "Ran",
|
||||
"s2569": "Not allowed in this mode. Nothing ran.",
|
||||
"s2570": "Replay preview"
|
||||
"s2570": "Replay preview",
|
||||
"s2571": "What this task may do",
|
||||
"s2572": "Look only, change nothing",
|
||||
"s2573": "Stop and tell me before changing anything",
|
||||
"s2574": "Allowed to make changes",
|
||||
"s2575": "Task finished",
|
||||
"s2576": "Task needs your yes",
|
||||
"s2577": "Task failed"
|
||||
}
|
||||
@@ -2568,5 +2568,12 @@
|
||||
"s2567": "Comprueba que el motor esté conectado y este modelo esté instalado. Después, inténtalo de nuevo.",
|
||||
"s2568": "Ejecutado",
|
||||
"s2569": "No se permite en este modo. No se ejecutó nada.",
|
||||
"s2570": "Repetir vista previa"
|
||||
"s2570": "Repetir vista previa",
|
||||
"s2571": "Qué puede hacer esta tarea",
|
||||
"s2572": "Solo mirar, no cambiar nada",
|
||||
"s2573": "Detenerse y avisarme antes de cambiar algo",
|
||||
"s2574": "Puede hacer cambios",
|
||||
"s2575": "Tarea terminada",
|
||||
"s2576": "La tarea necesita tu visto bueno",
|
||||
"s2577": "La tarea falló"
|
||||
}
|
||||
@@ -2568,5 +2568,12 @@
|
||||
"s2567": "エンジンが接続され、このモデルがインストールされていることを確認してから、もう一度お試しください。",
|
||||
"s2568": "実行済み",
|
||||
"s2569": "このモードでは許可されていません。何も実行していません。",
|
||||
"s2570": "プレビューを再生"
|
||||
"s2570": "プレビューを再生",
|
||||
"s2571": "このタスクができること",
|
||||
"s2572": "見るだけで何も変更しない",
|
||||
"s2573": "変更の前に止まって知らせる",
|
||||
"s2574": "変更を許可する",
|
||||
"s2575": "タスクが完了しました",
|
||||
"s2576": "タスクに許可が必要です",
|
||||
"s2577": "タスクが失敗しました"
|
||||
}
|
||||
@@ -2568,5 +2568,12 @@
|
||||
"s2567": "엔진이 연결되어 있고 이 모델이 설치되어 있는지 확인한 후 다시 시도하세요.",
|
||||
"s2568": "실행됨",
|
||||
"s2569": "이 모드에서는 허용되지 않습니다. 실행된 항목이 없습니다.",
|
||||
"s2570": "미리보기 다시 재생"
|
||||
"s2570": "미리보기 다시 재생",
|
||||
"s2571": "이 작업이 할 수 있는 일",
|
||||
"s2572": "보기만 하고 아무것도 바꾸지 않기",
|
||||
"s2573": "변경하기 전에 멈추고 알려 주기",
|
||||
"s2574": "변경 허용",
|
||||
"s2575": "작업 완료",
|
||||
"s2576": "작업에 승인이 필요합니다",
|
||||
"s2577": "작업 실패"
|
||||
}
|
||||
@@ -2568,5 +2568,12 @@
|
||||
"s2567": "Verifique se o mecanismo está conectado e este modelo está instalado. Depois, tente novamente.",
|
||||
"s2568": "Executado",
|
||||
"s2569": "Não permitido neste modo. Nada foi executado.",
|
||||
"s2570": "Repetir prévia"
|
||||
"s2570": "Repetir prévia",
|
||||
"s2571": "O que esta tarefa pode fazer",
|
||||
"s2572": "Só olhar, sem alterar nada",
|
||||
"s2573": "Parar e avisar antes de alterar algo",
|
||||
"s2574": "Pode fazer alterações",
|
||||
"s2575": "Tarefa concluída",
|
||||
"s2576": "A tarefa precisa do seu sim",
|
||||
"s2577": "A tarefa falhou"
|
||||
}
|
||||
@@ -2568,5 +2568,12 @@
|
||||
"s2567": "Убедитесь, что движок подключён и эта модель установлена, затем повторите попытку.",
|
||||
"s2568": "Выполнено",
|
||||
"s2569": "В этом режиме не разрешено. Ничего не запущено.",
|
||||
"s2570": "Повторить просмотр"
|
||||
"s2570": "Повторить просмотр",
|
||||
"s2571": "Что может делать эта задача",
|
||||
"s2572": "Только смотреть, ничего не менять",
|
||||
"s2573": "Остановиться и сообщить перед изменением",
|
||||
"s2574": "Разрешено вносить изменения",
|
||||
"s2575": "Задача выполнена",
|
||||
"s2576": "Задаче нужно ваше согласие",
|
||||
"s2577": "Задача не удалась"
|
||||
}
|
||||
@@ -2568,5 +2568,12 @@
|
||||
"s2567": "请确认引擎已连接且此模型已安装,然后重试。",
|
||||
"s2568": "已运行",
|
||||
"s2569": "此模式下不允许,未执行任何操作。",
|
||||
"s2570": "重播预览"
|
||||
"s2570": "重播预览",
|
||||
"s2571": "此任务可以做什么",
|
||||
"s2572": "只查看,不做任何更改",
|
||||
"s2573": "更改前先停下并告诉我",
|
||||
"s2574": "允许进行更改",
|
||||
"s2575": "任务已完成",
|
||||
"s2576": "任务需要你的确认",
|
||||
"s2577": "任务失败"
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* Tasks as the agent: a scheduled task runs in a Harness session of its own, under the mode it was given, and its result and a
|
||||
* notification reach the person. Pure tests always run; the rest need a built Harness (STRATA_HARNESS_DIR).
|
||||
*/
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { existsSync, mkdtempSync, mkdirSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { startScriptedWorker } from './helpers/scripted-worker.mjs';
|
||||
import { createAgentBridge } from '../server/agent/agent-bridge.mjs';
|
||||
import { createAgentTaskRunner } from '../server/agent/task-run.mjs';
|
||||
import { resolveHarness } from '../server/agent/harness-runtime.mjs';
|
||||
import { createTaskService, validateTask, nextRun, TASK_MODES } from '../server/tasks.mjs';
|
||||
import { taskReport, cardLine } from '../server/task-report.mjs';
|
||||
|
||||
const HARNESS = process.env.STRATA_HARNESS_DIR;
|
||||
const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false;
|
||||
const cleanup = dir => { try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ } };
|
||||
const fwd = p => p.replaceAll('\\', '/');
|
||||
const base = { title: 'Open downloads', prompt: 'open my downloads folder', frequency: 'daily', at: '09:00', timeZone: 'UTC' };
|
||||
|
||||
test('a task carries the mode it was created with: plan by default, manual and bypass on request, nothing else', () => {
|
||||
assert.deepEqual(TASK_MODES, ['plan', 'manual', 'bypass']);
|
||||
assert.equal(validateTask(base).mode, 'plan');
|
||||
assert.equal(validateTask({ ...base, mode: 'bypass' }).mode, 'bypass');
|
||||
assert.throws(() => validateTask({ ...base, mode: 'auto' }), /what this task may do/);
|
||||
});
|
||||
|
||||
test('the result lists what it did in plain words and says exactly what needed a yes', () => {
|
||||
const report = taskReport({ text: 'Done.', cards: [
|
||||
{ name: 'pwsh', state: 'done', effect: 'List the files', preview: 'Get-ChildItem' },
|
||||
{ name: 'pwsh', state: 'denied', effect: 'Run a command that may change things: open the folder', preview: 'explorer.exe C:/Users/x/Downloads' },
|
||||
] });
|
||||
assert.match(report.text, /^Done\./);
|
||||
assert.match(report.text, /\*\*What it did\*\*/);
|
||||
assert.match(report.text, /- List the files \(Get-ChildItem\)/);
|
||||
assert.match(report.text, /Could not do this by itself: Run a command that may change things: open the folder/);
|
||||
assert.match(report.attention, /needed a yes, which nobody could give while it ran by itself/);
|
||||
assert.match(report.attention, /Nothing was changed/);
|
||||
assert.equal(taskReport({ text: '', cards: [] }).text, 'The task ran and had nothing to report.');
|
||||
assert.equal(taskReport({ text: 'ok', cards: [] }).attention, null);
|
||||
assert.match(cardLine({ state: 'error', effect: 'Opens a web page.', preview: 'https://x' }), /It did not work/);
|
||||
});
|
||||
|
||||
test('a task scheduled two minutes ahead runs when its minute comes (fake clock), is reported through notify, and the schedule moves on', async () => {
|
||||
let clock = Date.parse('2026-10-16T10:00:20Z');
|
||||
const stored = [];
|
||||
const notified = [];
|
||||
const at = new Date(clock + 2 * 60_000).toISOString().slice(11, 16); // 10:02
|
||||
const service = createTaskService({
|
||||
read: () => stored, write: records => { stored.length = 0; stored.push(...records); }, now: () => clock,
|
||||
notify: task => notified.push({ title: task.title, status: task.status, attention: task.attention }),
|
||||
run: async () => ({ text: 'Opened.', attention: null, demo: false }),
|
||||
});
|
||||
const task = service.put({ ...base, at, mode: 'bypass' });
|
||||
assert.equal(task.nextRunAt, `2026-10-16T${at}:00.000Z`);
|
||||
service.tick(); await new Promise(r => setTimeout(r, 20));
|
||||
assert.equal(notified.length, 0, 'not yet');
|
||||
clock = Date.parse(`2026-10-16T${at}:05Z`);
|
||||
service.tick(); await new Promise(r => setTimeout(r, 50));
|
||||
assert.deepEqual(notified, [{ title: 'Open downloads', status: 'done', attention: null }]);
|
||||
assert.equal(service.list()[0].output, 'Opened.');
|
||||
assert.equal(service.list()[0].nextRunAt, nextRun({ ...base, at }, clock), 'tomorrow, not again now');
|
||||
service.close();
|
||||
});
|
||||
|
||||
async function rig(t, { slots = 2 } = {}) {
|
||||
const worker = await startScriptedWorker({});
|
||||
const dir = mkdtempSync(join(tmpdir(), 'strata-task-'));
|
||||
const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });
|
||||
const local = [{ id: 'inst-1', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots }];
|
||||
const agent = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 });
|
||||
t.after(async () => { await agent.close(); await worker.close(); cleanup(dir); });
|
||||
const runner = createAgentTaskRunner({ agent, workspace: ws, choice: () => ({ instanceId: 'inst-1' }) });
|
||||
return { worker, agent, ws, runner, dir };
|
||||
}
|
||||
|
||||
test('a task runs as the agent in each mode: Plan changes nothing, Manual stops at the first change and says so, Bypass does it', { skip }, async (t) => {
|
||||
const r = await rig(t);
|
||||
const file = join(r.ws, 'made-by-task.txt');
|
||||
const prompt = `SCRIPT:call write ${JSON.stringify({ file_path: fwd(file), content: 'task was here' })}`;
|
||||
|
||||
const plan = await r.runner({ id: 'tp', prompt, mode: 'plan' });
|
||||
assert.equal(existsSync(file), false); assert.equal(plan.attention, null, 'Plan refuses without asking anybody');
|
||||
|
||||
const manual = await r.runner({ id: 'tm', prompt, mode: 'manual' });
|
||||
assert.equal(existsSync(file), false, 'nobody was there to say yes');
|
||||
assert.match(manual.attention, /needed a yes/); assert.match(manual.text, /Could not do this by itself: Create or replace the file/);
|
||||
assert.equal(r.agent.status().pendingApprovals, 0, 'nothing is left waiting for an answer');
|
||||
|
||||
const bypass = await r.runner({ id: 'tb', prompt, mode: 'bypass' });
|
||||
assert.equal(existsSync(file), true); assert.equal(bypass.attention, null);
|
||||
assert.match(bypass.text, /What it did/);
|
||||
});
|
||||
|
||||
test('every run of a task starts a session of its own, and a model that is not ready falls back to the caller', { skip }, async (t) => {
|
||||
const r = await rig(t);
|
||||
await r.runner({ id: 'ts', prompt: 'SCRIPT:echo one', mode: 'plan' });
|
||||
assert.equal(r.agent.sessionOf('task:ts'), null, 'the mapping is dropped after the run');
|
||||
const first = r.worker.requests.length;
|
||||
await r.runner({ id: 'ts', prompt: 'SCRIPT:echo two', mode: 'plan' });
|
||||
assert.ok(r.worker.requests.length > first);
|
||||
const none = createAgentTaskRunner({ agent: r.agent, workspace: r.ws, choice: () => null });
|
||||
assert.equal(await none({ id: 'x', prompt: 'hi' }), null);
|
||||
});
|
||||
|
||||
test('Stop on the task ends its agent run', { skip }, async (t) => {
|
||||
const r = await rig(t);
|
||||
const controller = new AbortController();
|
||||
const run = r.runner({ id: 'tstop', prompt: 'SCRIPT:slow 300', mode: 'plan' }, controller.signal);
|
||||
await new Promise(res => setTimeout(res, 3500));
|
||||
controller.abort();
|
||||
await assert.rejects(run);
|
||||
assert.equal(r.agent.status().activeTurns, 0);
|
||||
});
|
||||
Reference in new issue
Block a user