From 898aa3c2844d919acdbfec200c109a359a48385e Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Thu, 26 Nov 2026 20:43:34 +0800 Subject: [PATCH 01/12] =?UTF-8?q?refactor(tasks):=20=E6=8F=90=E5=8F=96?= =?UTF-8?q?=E6=A1=8C=E9=9D=A2=E4=BB=BB=E5=8A=A1=E8=A1=8C=E3=80=81=E5=88=86?= =?UTF-8?q?=E7=BB=84=E6=8E=92=E5=BA=8F=E4=B8=8E=E5=8E=86=E5=8F=B2=E5=8D=A1?= =?UTF-8?q?=20/=20extract=20shared=20desktop=20task=20rows,=20sorting=20an?= =?UTF-8?q?d=20history?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/redesign/TaskInspectionParts.tsx | 119 +++++++++++ .../src/renderer/src/redesign/TasksPane.tsx | 198 ++---------------- 2 files changed, 137 insertions(+), 180 deletions(-) create mode 100644 apps/desktop/src/renderer/src/redesign/TaskInspectionParts.tsx diff --git a/apps/desktop/src/renderer/src/redesign/TaskInspectionParts.tsx b/apps/desktop/src/renderer/src/redesign/TaskInspectionParts.tsx new file mode 100644 index 00000000..8830e8de --- /dev/null +++ b/apps/desktop/src/renderer/src/redesign/TaskInspectionParts.tsx @@ -0,0 +1,119 @@ +import { useMemo, useState, type MouseEvent, type ReactNode } from 'react' +import { CalendarClock, Clock } from 'lucide-react' +import type { TaskRecord, TaskStatus } from '../../../preload' +import { useI18n } from '../i18n/i18n' + +/** Shared Desktop task markup. Data reads, calculations and actions belong to the host. */ +export const TASK_GROUP_ORDER: TaskStatus[] = ['active', 'paused', 'error', 'completed'] +export const TASK_GROUP_KEY: Record = { + active: 'tasks.groupActive', paused: 'tasks.groupPaused', error: 'tasks.groupError', completed: 'tasks.groupCompleted' +} + +type TaskOrder = Pick +/** Within a status group, order saved occurrences first; newest creation wins ties. */ +export function compareTaskRows(a: TaskOrder, b: TaskOrder): number { + const an = a.nextRunAt ?? Number.POSITIVE_INFINITY + const bn = b.nextRunAt ?? Number.POSITIVE_INFINITY + return an !== bn ? an - bn : b.createdAt - a.createdAt +} + +export function TaskRailRow({ task, scheduleText, active, onClick, onContext, testId }: { + task: Pick; scheduleText: string; active: boolean + onClick: () => void; onContext?: (e: MouseEvent) => void; testId?: string +}): React.JSX.Element { + const { t } = useI18n() + return ( + + ) +} + +export function TaskDetailHeading({ task, as: Title = 'div' }: { + task: Pick; as?: 'div' | 'h3' +}): React.JSX.Element { + const { t } = useI18n() + return <> +
+ {task.title || t('chat.untitled')} +
+ {t(TASK_GROUP_KEY[task.status])} +
+ +} + +type TaskRun = TaskRecord['runs'][number] +type TaskRunStatus = TaskRun['status'] +export const runStatusKey: Record = { + ok: 'tasks.runOk', skipped: 'tasks.runSkipped', aborted: 'tasks.runAborted', error: 'tasks.runError' +} + +/** Same fixed-width status circle for the last run and run history. */ +const RUN_ICON_MARK: Record = { + ok: , + error: <>, + aborted: <>, + skipped: <> +} + +export function RunStatusIcon({ status, label, detail }: { + status: TaskRunStatus; label: string; detail?: string +}): React.JSX.Element { + const title = detail ? `${label}:${detail}` : label + return ( + + + + {RUN_ICON_MARK[status]} + + + ) +} + +const HISTORY_PREVIEW = 5 +export function TaskRunHistory({ runs, formatTime, headerAction, renderRunText }: { + runs: TaskRun[]; formatTime: (ts: number) => ReactNode; headerAction?: ReactNode; renderRunText?: (run: TaskRun) => ReactNode +}): React.JSX.Element { + const { t } = useI18n() + const history = useMemo(() => [...runs].reverse(), [runs]) + const [historyAll, setHistoryAll] = useState(false) + const shownHistory = historyAll ? history : history.slice(0, HISTORY_PREVIEW) + return ( +
+
+
{t('tasks.runHistory')}
+ {headerAction} +
+ {history.length === 0 ?
{t('tasks.historyEmpty')}
: ( +
+ {shownHistory.map((run, i) => ( +
+ {formatTime(run.firedAt)} + + {renderRunText ? renderRunText(run) : (run.summary || run.error) && ( + {run.summary || run.error} + )} +
+ ))} +
+ )} + {history.length > HISTORY_PREVIEW && ( + + )} +
+ ) +} diff --git a/apps/desktop/src/renderer/src/redesign/TasksPane.tsx b/apps/desktop/src/renderer/src/redesign/TasksPane.tsx index f23da7b5..fd938134 100644 --- a/apps/desktop/src/renderer/src/redesign/TasksPane.tsx +++ b/apps/desktop/src/renderer/src/redesign/TasksPane.tsx @@ -4,9 +4,7 @@ import { useEffect, useMemo, useState } from 'react' import { AlertTriangle, - CalendarClock, ChevronRight, - Clock, MessageCircle, Pause, Pencil, @@ -43,19 +41,10 @@ import { DragBar, DEFAULT_PERSONA_ID, useRelativeTime, fill, Avatar } from './sh import { ContextMenu } from './ContextMenu' import { memberPersona } from './MemberBar' import { AddMenu, GroupFace } from './Rail' +import { RunStatusIcon, TASK_GROUP_KEY, TASK_GROUP_ORDER, TaskDetailHeading, TaskRailRow, TaskRunHistory, compareTaskRows, runStatusKey } from './TaskInspectionParts' /* ============================ 定时任务标签页 ============================ */ -/** 分组展示顺序:进行中 → 已暂停 → 出错 → 已完成。 */ -const TASK_GROUP_ORDER: TaskStatus[] = ['active', 'paused', 'error', 'completed'] - -const TASK_GROUP_KEY: Record = { - active: 'tasks.groupActive', - paused: 'tasks.groupPaused', - error: 'tasks.groupError', - completed: 'tasks.groupCompleted' -} - /** 绝对本地时间(简短):用于「下次触发 / 上次运行」展示,跟随界面语言。 */ function fmtAbs(ts: number, locale: 'zh-CN' | 'en'): string { try { @@ -136,13 +125,7 @@ export function TasksPane({ error: [] } for (const task of tasks) g[task.status].push(task) - const byNext = (a: TaskRecord, b: TaskRecord): number => { - const an = a.nextRunAt ?? Number.POSITIVE_INFINITY - const bn = b.nextRunAt ?? Number.POSITIVE_INFINITY - if (an !== bn) return an - bn - return b.createdAt - a.createdAt - } - ;(Object.keys(g) as TaskStatus[]).forEach((k) => g[k].sort(byNext)) + ;(Object.keys(g) as TaskStatus[]).forEach((k) => g[k].sort(compareTaskRows)) return g }, [tasks]) @@ -390,7 +373,7 @@ function TasksRail({ {shown.out[k].length} {shown.out[k].map((task) => ( - void - /** 右键唤起删除菜单(阻默认系统菜单,定位到光标)。 */ - onContext: (e: React.MouseEvent) => void +/** Native schedule descriptions are read through IPC, outside the shared row. */ +function NativeTaskRailRow({ task, active, onClick, onContext }: { + task: TaskRecord; active: boolean; onClick: () => void; onContext: (e: React.MouseEvent) => void }): React.JSX.Element { - const { t } = useI18n() const desc = useSchedulePreview(task.schedule) - return ( - - ) -} - -/** 任务详情运行历史默认展示的条数(最近 N 次),超出折叠在「展开全部」后。 */ -const HISTORY_PREVIEW = 5 - -type TaskRunStatus = TaskRecord['runs'][number]['status'] - -/** - * 运行状态图标的圆内符号(圆框共用):对勾 / 叉 / i(中止)/ 双箭头(追赶跳过)。 - * 中止与对话里「已停止本轮回复」的提示同一个图标(lucide Info)、同为黄色,两处说的是同一件事。 - */ -const RUN_ICON_MARK: Record = { - ok: , - error: ( - <> - - - - ), - aborted: ( - <> - - - - ), - skipped: ( - <> - - - - ) -} - -/** - * 运行状态图标(任务详情「上次」与运行历史共用,对比稿 design/run-status-icons.html 方案 A):同宽线框圆形, - * 文字徽标长短不一会把后面的摘要挤得对不齐。悬停显示状态文字,失败时连同原因。 - */ -function RunStatusIcon({ - status, - label, - detail -}: { - status: TaskRunStatus - label: string - detail?: string -}): React.JSX.Element { - const title = detail ? `${label}:${detail}` : label - return ( - - - - {RUN_ICON_MARK[status]} - - - ) + return } /** @@ -559,34 +450,13 @@ function TaskDetail({ const desc = useSchedulePreview(task.schedule) const lastRun = task.runs.length > 0 ? task.runs[task.runs.length - 1] : undefined - const runKey = (s: TaskRunStatus): string => - s === 'ok' - ? 'tasks.runOk' - : s === 'skipped' - ? 'tasks.runSkipped' - : s === 'aborted' - ? 'tasks.runAborted' - : 'tasks.runError' - // 运行历史按时间降序(最近在上)。 - const history = useMemo(() => [...task.runs].reverse(), [task.runs]) - // 默认只列最近 HISTORY_PREVIEW 次,超出时给「展开全部」开关(组件按 task.id 取 key,切任务即复位收起)。 - const [historyAll, setHistoryAll] = useState(false) - const shownHistory = historyAll ? history : history.slice(0, HISTORY_PREVIEW) return (
-
- -
-
{task.title || t('chat.untitled')}
-
- - {t(TASK_GROUP_KEY[task.status])} - -
+
@@ -613,7 +483,7 @@ function TaskDetail({ {rel(lastRun.firedAt)} @@ -664,46 +534,14 @@ function TaskDetail({
-
- {/* 标题右侧:一个任务只有一个对话,每次运行在里面追加一轮,所以只放一个入口,不逐行放。 */} -
-
{t('tasks.runHistory')}
- {onOpenChat && ( - - )} -
- {history.length === 0 ? ( -
{t('tasks.historyEmpty')}
- ) : ( -
- {shownHistory.map((run, i) => ( -
- {fmtAbs(run.firedAt, locale)} - - {(run.summary || run.error) && ( - {run.summary || run.error} - )} -
- ))} -
- )} - {history.length > HISTORY_PREVIEW && ( - - )} -
+ {/* One task conversation contains every run. Keep its link in the history header. */} + fmtAbs(ts, locale)} headerAction={onOpenChat && ( + + )} />
From 66cc72ee3ca126d4a54793a3cc4abce70e460de2 Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Thu, 26 Nov 2026 20:43:34 +0800 Subject: [PATCH 02/12] =?UTF-8?q?feat(tasks):=20=E5=A4=8D=E7=94=A8?= =?UTF-8?q?=E6=A1=8C=E9=9D=A2=E7=AE=97=E6=B3=95=E8=AE=A1=E7=AE=97=E6=9C=89?= =?UTF-8?q?=E7=95=8C=E6=97=A5=E7=A8=8B=E9=A2=84=E8=A7=88=20/=20share=20des?= =?UTF-8?q?ktop=20schedule=20calculations=20in=20bounded=20preview=20worke?= =?UTF-8?q?rs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/services/schedule-preview.ts | 38 ++++ apps/desktop/src/main/services/tasks.ts | 44 +---- apps/headless/scripts/build-provider.mjs | 11 +- apps/headless/src/tasks/preview-worker.mjs | 11 ++ apps/headless/src/tasks/preview.mjs | 157 +++++++++++++++ apps/headless/test/task-preview.test.mjs | 185 ++++++++++++++++++ 6 files changed, 403 insertions(+), 43 deletions(-) create mode 100644 apps/desktop/src/main/services/schedule-preview.ts create mode 100644 apps/headless/src/tasks/preview-worker.mjs create mode 100644 apps/headless/src/tasks/preview.mjs create mode 100644 apps/headless/test/task-preview.test.mjs diff --git a/apps/desktop/src/main/services/schedule-preview.ts b/apps/desktop/src/main/services/schedule-preview.ts new file mode 100644 index 00000000..4fc1955a --- /dev/null +++ b/apps/desktop/src/main/services/schedule-preview.ts @@ -0,0 +1,38 @@ +import { describeSchedule, isValidTimeZone, nextRun, parseCron, parseWallIso } from './schedule' +import type { TaskSchedule } from './tasks-types' + +/** 预览结果:成功带人读摘要与下次触发(epoch ms,null=无更多触发);失败带与 createTask 一致的错误码。 */ +export type PreviewScheduleResult = + | { ok: true; description: string; nextRunAt: number | null } + | { ok: false; error: 'invalid-input' | 'invalid-tz' | 'invalid-cron' | 'invalid-once' } + +/** + * 校验日程并返回人读摘要 + 下次触发。预览不读写任务、不创建任务。 + * `allowPast` 默认 false:名片编辑态把过期的 once 视为错误。已创建任务的只读展示传 true, + * 合法但过期的 once 仍返回人读摘要(nextRunAt=null)。`now` 为本次预览的评估时刻(epoch ms)。 + */ +export function previewSchedule( + schedule: TaskSchedule, + locale: 'zh-CN' | 'en' = 'zh-CN', + allowPast = false, + now = Date.now() +): PreviewScheduleResult { + if (!schedule || typeof schedule !== 'object') return { ok: false, error: 'invalid-input' } + if (!isValidTimeZone(schedule.tz)) return { ok: false, error: 'invalid-tz' } + if (schedule.kind === 'recurring') { + if (!parseCron(schedule.cron ?? '')) return { ok: false, error: 'invalid-cron' } + const next = nextRun(schedule, now) + if (next == null) return { ok: false, error: 'invalid-cron' } // 病态但语法合法(如 2/30) + return { ok: true, description: describeSchedule(schedule, locale), nextRunAt: next } + } + if (schedule.kind === 'once') { + const next = nextRun(schedule, now) + if (next == null) { + if (allowPast && parseWallIso(schedule.at ?? '')) + return { ok: true, description: describeSchedule(schedule, locale), nextRunAt: null } + return { ok: false, error: 'invalid-once' } // 非法或(编辑态下)已过期 + } + return { ok: true, description: describeSchedule(schedule, locale), nextRunAt: next } + } + return { ok: false, error: 'invalid-input' } +} diff --git a/apps/desktop/src/main/services/tasks.ts b/apps/desktop/src/main/services/tasks.ts index b1354744..f8514b37 100644 --- a/apps/desktop/src/main/services/tasks.ts +++ b/apps/desktop/src/main/services/tasks.ts @@ -5,7 +5,8 @@ import { randomUUID } from 'crypto' import { getDevaHome } from './config' import { publishSessionsChanged } from './chat-bus' import { listSessions, rebindSessionPersona, syncSessionBinding } from './chat-store' -import { nextRun, parseCron, isValidTimeZone, describeSchedule, parseWallIso } from './schedule' +import { nextRun, parseCron, isValidTimeZone } from './schedule' +import { previewSchedule, type PreviewScheduleResult } from './schedule-preview' import { ERROR_PAUSE_THRESHOLD, MAX_RUNS_PER_TASK, @@ -431,46 +432,7 @@ export function applyRunResult( return { task: t, autoPausedError } } -// ── 日程预览(确认名片实时校验 + 人读摘要 + 下次触发)────────────────────── - -/** 预览结果:成功带人读摘要与下次触发(epoch ms,null=无更多触发);失败带与 createTask 一致的错误码。 */ -export type PreviewScheduleResult = - | { ok: true; description: string; nextRunAt: number | null } - | { ok: false; error: 'invalid-input' | 'invalid-tz' | 'invalid-cron' | 'invalid-once' } - -/** - * 校验一份日程并返回人读摘要 + 下次触发,供确认名片实时预览(与 createTask 校验同源,所见即所得)。 - * 纯读、不落盘、不建任务——名片编辑期的只读推演。 - * - * `allowPast`(默认 false):名片编辑态用默认——一次性时间已过视为错误(invalid-once),供用户改后重建。 - * 任务列表/详情为**已创建任务的只读展示**(如已完成的一次性任务其墙钟必然已过),传 true—— - * 一次性时间虽已过但日程本身合法时回落人读摘要(nextRunAt=null),避免把「已执行完毕」误标为「日程无效」。 - */ -export function previewSchedule( - schedule: TaskSchedule, - locale: 'zh-CN' | 'en' = 'zh-CN', - allowPast = false -): PreviewScheduleResult { - if (!schedule || typeof schedule !== 'object') return { ok: false, error: 'invalid-input' } - if (!isValidTimeZone(schedule.tz)) return { ok: false, error: 'invalid-tz' } - if (schedule.kind === 'recurring') { - if (!parseCron(schedule.cron ?? '')) return { ok: false, error: 'invalid-cron' } - const next = nextRun(schedule, Date.now()) - if (next == null) return { ok: false, error: 'invalid-cron' } // 病态但语法合法(如 2/30) - return { ok: true, description: describeSchedule(schedule, locale), nextRunAt: next } - } - if (schedule.kind === 'once') { - const next = nextRun(schedule, Date.now()) - if (next == null) { - // 时间已过:仅当墙钟本身可解析(即合法但过期,非畸形)且允许过去时,回落人读摘要。 - if (allowPast && parseWallIso(schedule.at ?? '')) - return { ok: true, description: describeSchedule(schedule, locale), nextRunAt: null } - return { ok: false, error: 'invalid-once' } // 非法或(编辑态下)已过期 - } - return { ok: true, description: describeSchedule(schedule, locale), nextRunAt: next } - } - return { ok: false, error: 'invalid-input' } -} +export { previewSchedule, type PreviewScheduleResult } // ── 可注入运行器(scheduler 装载后接管 run-now / 触发)────────────────────── diff --git a/apps/headless/scripts/build-provider.mjs b/apps/headless/scripts/build-provider.mjs index e1e20c60..b28aa4af 100644 --- a/apps/headless/scripts/build-provider.mjs +++ b/apps/headless/scripts/build-provider.mjs @@ -5,15 +5,18 @@ import { fileURLToPath } from 'node:url' const root = fileURLToPath(new URL('../../../', import.meta.url)) const dest = new URL('../dist/', import.meta.url) -async function compile(name, entry) { +async function compile(name, entry, { pureInputs } = {}) { const result = await build({ absWorkingDir: root, entryPoints: [entry], bundle: true, platform: 'node', format: 'esm', target: 'node22', metafile: true, write: false, logLevel: 'silent', plugins: [{ name: 'reject-desktop-runtime', setup(b) { b.onResolve({ filter: /^(?:electron(?:\/|$)|@electron-toolkit\/|electron-updater$)/ }, a => ({ errors: [{ text: `Desktop dependency in ${name}: ${a.path}` }] })) } }] }) + for (const input of Object.keys(result.metafile.inputs)) { + if (pureInputs && !pureInputs.includes(input)) throw Error(`Unexpected source in ${name}: ${input}`) + } for (const out of Object.values(result.metafile.outputs)) for (const dep of out.imports) { - if (dep.external && !isBuiltin(dep.path)) throw Error(`Unexpected external dependency: ${dep.path}`) + if (pureInputs || (dep.external && !isBuiltin(dep.path))) throw Error(`Unexpected dependency in ${name}: ${dep.path}`) } await writeFile(new URL(`${name}.mjs`, dest), result.outputFiles[0].contents) console.log(`Built headless ${name} from shared desktop modules (${Object.keys(result.metafile.inputs).length} inputs)`) @@ -22,3 +25,7 @@ await mkdir(dest, { recursive: true }) await compile('provider-core', 'apps/desktop/src/main/providers/core.ts') await compile('chat-core', 'apps/headless/scripts/chat-core.ts') await compile('library-core', 'apps/headless/scripts/library-core.ts') +const services = 'apps/desktop/src/main/services/' +await compile('schedule-core', `${services}schedule-preview.ts`, { + pureInputs: ['schedule-preview.ts', 'schedule.ts', 'tasks-types.ts'].map(file => `${services}${file}`) +}) diff --git a/apps/headless/src/tasks/preview-worker.mjs b/apps/headless/src/tasks/preview-worker.mjs new file mode 100644 index 00000000..41ab5385 --- /dev/null +++ b/apps/headless/src/tasks/preview-worker.mjs @@ -0,0 +1,11 @@ +import { parentPort, workerData } from 'node:worker_threads' +import { previewSchedule } from '../../dist/schedule-core.mjs' + +// A single calculation using Desktop's rules, not a scheduler. For example, +// an LA spring gap may be observed during a cron scan and filled at 03:00; +// a once at 02:30 resolves to 01:30 under Desktop's two-offset calculation. +// An ambiguous once uses that same calculation, not necessarily the earlier +// instant. A cron scan in the repeated hour may find the second occurrence +// if its cutoff is already on/after the first occurrence. +const { request: { schedule, locale, allowPast }, timestamp } = workerData +parentPort.postMessage(previewSchedule(schedule, locale, allowPast, timestamp)) diff --git a/apps/headless/src/tasks/preview.mjs b/apps/headless/src/tasks/preview.mjs new file mode 100644 index 00000000..553aeb25 --- /dev/null +++ b/apps/headless/src/tasks/preview.mjs @@ -0,0 +1,157 @@ +import { addAbortListener } from 'node:events' +import { Worker } from 'node:worker_threads' + +const workerFile = new URL('./preview-worker.mjs', import.meta.url) +const MAX_WORKERS = 2 +const BUDGET_MS = 2_000 +const MAX_CRON_LENGTH = 512 +const MAX_ZONE_LENGTH = 128 +const qualifiedZone = /^[A-Za-z][A-Za-z0-9._+-]*(?:\/[A-Za-z0-9._+-]+)+$/u +// IANA tzdb also has unqualified names/links. ICU accepts additional strings +// such as PST and fixed offset syntax, which are not IANA identifiers. +const unqualifiedZones = new Set(( + 'UTC GMT GMT+0 GMT-0 GMT0 Greenwich UCT Universal Zulu CET CST6CDT Cuba EET Egypt Eire EST EST5EDT ' + + 'GB GB-Eire Hongkong HST Iceland Iran Israel Jamaica Japan Kwajalein Libya MET MST MST7MDT Navajo ' + + 'NZ NZ-CHAT Poland Portugal PRC PST8PDT ROC ROK Singapore Turkey W-SU WET' +).toLowerCase().split(' ')) + +export class TaskPreviewError extends Error { + constructor(code) { + super(code) + this.name = 'TaskPreviewError' + this.code = code + } +} + +function exactRecord(value, fields) { + if (value === null || typeof value !== 'object') return false + const proto = Object.getPrototypeOf(value) + if ((proto !== Object.prototype && proto !== null) || Reflect.ownKeys(value).length !== fields.length) return false + return fields.every(key => { + const field = Object.getOwnPropertyDescriptor(value, key) + return field?.enumerable && Object.hasOwn(field, 'value') + }) +} + +function validWallMinute(at) { + if (typeof at !== 'string' || (at.length !== 16 && at.length !== 19)) return false + const parts = /^(\d{4})-(\d{2})-(\d{2})[T ]([01]\d|2[0-3]):[0-5]\d(?::00)?$/u.exec(at) + if (!parts) return false + const [, year, month, day] = parts.map(Number) + // Date.UTC in the shared Desktop engine maps 00–99 to 1900–1999. + if (year < 100) return false + const date = new Date(Date.UTC(year, month - 1, day)) + return date.getUTCFullYear() === year && date.getUTCMonth() + 1 === month && date.getUTCDate() === day +} + +const failure = error => ({ ok: false, error }) + +function validate(input) { + if (!exactRecord(input, ['schedule', 'locale', 'allowPast'])) return failure('invalid-input') + const { schedule, locale, allowPast } = input + if ((locale !== 'en' && locale !== 'zh-CN') || typeof allowPast !== 'boolean') return failure('invalid-input') + const once = exactRecord(schedule, ['kind', 'tz', 'at']) && schedule.kind === 'once' + const recurring = exactRecord(schedule, ['kind', 'tz', 'cron']) && schedule.kind === 'recurring' + if (!once && !recurring) return failure('invalid-input') + const { kind, tz } = schedule + if (typeof tz !== 'string' || tz.length > MAX_ZONE_LENGTH || + (!qualifiedZone.test(tz) && !unqualifiedZones.has(tz.toLowerCase()))) return failure('invalid-tz') + if (once) { + if (!validWallMinute(schedule.at)) return failure('invalid-once') + return { ok: true, request: { schedule: { kind, tz, at: schedule.at }, locale, allowPast } } + } + const { cron } = schedule + if (typeof cron !== 'string' || cron.length === 0 || cron.length > MAX_CRON_LENGTH) return failure('invalid-cron') + return { ok: true, request: { schedule: { kind, tz, cron }, locale, allowPast } } +} + +function startPreview(workerData, signal, release) { + const deadline = performance.now() + BUDGET_MS + const worker = new Worker(workerFile, { + workerData, execArgv: [], env: {}, stdout: true, stderr: true, + resourceLimits: { maxOldGenerationSizeMb: 32, maxYoungGenerationSizeMb: 8, stackSizeMb: 2 } + }) + worker.stdout.resume() + worker.stderr.resume() + const { promise: result, resolve, reject } = Promise.withResolvers() + const { promise: exited, resolve: finishExit } = Promise.withResolvers() + let settled = false, response, abortListener + const timer = setTimeout(() => stop('preview_timeout'), Math.max(0, Math.ceil(deadline - performance.now()))) + + function settle(error) { + if (settled) return + settled = true + clearTimeout(timer) + abortListener?.[Symbol.dispose]() + if (error) reject(new TaskPreviewError(error)) + else resolve(response) + } + + function stop(error) { + if (settled) return + settle(error) + // The caller receives cancellation immediately; capacity stays occupied until exit. + void worker.terminate().catch(() => {}) + } + + worker.once('message', value => { response = value }) + worker.once('error', () => stop('preview_unavailable')) + worker.once('messageerror', () => stop('preview_unavailable')) + worker.once('exit', code => { + if (!settled) { + if (performance.now() >= deadline) settle('preview_timeout') + else settle(code === 0 && response ? undefined : 'preview_unavailable') + } + release() + finishExit() + }) + if (signal) abortListener = addAbortListener(signal, () => stop('preview_aborted')) + return { result, exited, stop } +} + +/** + * Open a read-only preview runner. Supply one instance per HTTP host. Responses + * use the Desktop result union; lifecycle and capacity faults reject separately. + * `now` is a trusted host clock (epoch ms), never taken from the request body. + */ +export function openTaskPreview({ now = Date.now } = {}) { + if (typeof now !== 'function') throw TypeError('Task preview clock must be a function') + const active = new Set() + let closed = false, draining + + async function preview(input, signal) { + if (signal !== undefined && !(signal instanceof AbortSignal)) throw TypeError('Expected an AbortSignal') + if (closed) throw new TaskPreviewError('preview_closed') + if (signal?.aborted) throw new TaskPreviewError('preview_aborted') + const checked = validate(input) + if (!checked.ok) return checked + if (active.size >= MAX_WORKERS) throw new TaskPreviewError('preview_busy') + let timestamp + try { timestamp = now() } catch { throw new TaskPreviewError('preview_unavailable') } + if (!Number.isSafeInteger(timestamp)) throw new TaskPreviewError('preview_unavailable') + if (closed) throw new TaskPreviewError('preview_closed') + if (signal?.aborted) throw new TaskPreviewError('preview_aborted') + if (active.size >= MAX_WORKERS) throw new TaskPreviewError('preview_busy') + + let job + try { + job = startPreview({ request: checked.request, timestamp }, signal, () => active.delete(job)) + } catch { + throw new TaskPreviewError('preview_unavailable') + } + active.add(job) + return job.result + } + + function close() { + if (!draining) { + closed = true + const jobs = [...active] + for (const job of jobs) job.stop('preview_closed') + draining = Promise.all(jobs.map(job => job.exited)).then(() => {}) + } + return draining + } + + return { preview, close } +} diff --git a/apps/headless/test/task-preview.test.mjs b/apps/headless/test/task-preview.test.mjs new file mode 100644 index 00000000..0e03dcff --- /dev/null +++ b/apps/headless/test/task-preview.test.mjs @@ -0,0 +1,185 @@ +import assert from 'node:assert/strict' +import { test } from 'node:test' +import { fileURLToPath } from 'node:url' +import { build } from 'esbuild' +import { previewSchedule as desktopPreview } from '../dist/schedule-core.mjs' +import { openTaskPreview } from '../src/tasks/preview.mjs' + +const UTC = 'UTC' +const SHANGHAI = 'Asia/Shanghai' +const LA = 'America/Los_Angeles' +const once = (at, tz = UTC) => ({ kind: 'once', at, tz }) +const recurring = (cron, tz = UTC) => ({ kind: 'recurring', cron, tz }) +const request = (schedule, locale = 'en', allowPast = false) => ({ schedule, locale, allowPast }) +const valid = request(recurring('*/15 * * * *')) +const invalid = error => ({ ok: false, error }) +const success = (description, next) => ({ ok: true, description, nextRunAt: next === null ? null : Date.parse(next) }) +const fault = code => ({ name: 'TaskPreviewError', code }) + +function fixture(t, time = '2026-01-01T00:00:00Z') { + const api = openTaskPreview({ now: () => Date.parse(time) }) + t.after(api.close) + return api +} + +test('preview preserves Desktop descriptions and computes against the explicit Shanghai and LA zones', async t => { + const clock = Date.parse('2026-01-01T00:00:00Z') + const { preview } = fixture(t) + for (const [schedule, locale, description, instant] of [ + [recurring('0 10 * * *', SHANGHAI), 'zh-CN', '每天 10:00', '2026-01-01T02:00:00Z'], + [recurring('0 10 * * *', LA), 'en', 'daily at 10:00', '2026-01-01T18:00:00Z'], + [once('2026-01-02T10:00', SHANGHAI), 'en', 'once at 2026-01-02 10:00', '2026-01-02T02:00:00Z'], + [once('2026-01-02 10:00:00', LA), 'zh-CN', '2026-01-02 10:00 一次', '2026-01-02T18:00:00Z'], + [recurring('0 10 * * *', 'Etc/GMT+8'), 'en', 'daily at 10:00', '2026-01-01T18:00:00Z'], + [recurring('0 10 * * *', 'US/Pacific'), 'en', 'daily at 10:00', '2026-01-01T18:00:00Z'] + ]) { + const expected = success(description, instant) + assert.deepEqual(desktopPreview(schedule, locale, false, clock), expected) + assert.deepEqual(await preview(request(schedule, locale)), expected) + } +}) + +test('calendar validation handles leap days and cron retains Desktop day-of-week OR semantics', async t => { + const { preview } = fixture(t) + assert.deepEqual(await preview(request(once('2028-02-29T12:34'))), success('once at 2028-02-29 12:34', '2028-02-29T12:34:00Z')) + assert.deepEqual(await preview(request(recurring('0 0 29 2 *'))), success('cron: 0 0 29 2 *', '2028-02-29T00:00:00Z')) + assert.deepEqual(await preview(request(recurring('0 0 30 2 *'))), invalid('invalid-cron')) + assert.deepEqual(await preview(request(recurring('0 10 30 2 1'))), success('cron: 0 10 30 2 1', '2026-02-02T10:00:00Z')) + const century = fixture(t, '2096-02-29T00:00:00Z') + assert.equal((await century.preview(request(recurring('0 0 29 2 *')))).nextRunAt, Date.parse('2104-02-29T00:00:00Z')) + + for (const wall of ['2028-02-30T12:34', '2100-02-29T12:34', '2028-04-31T12:34', '2028-01-00T12:34', '2028-01-31T24:00', '0099-01-31T10:00', '2028-01-01T12:34:01']) { + assert.deepEqual(await preview(request(once(wall), 'en', true)), invalid('invalid-once'), wall) + } + // These tighten the server boundary only: Desktop retains normalization and minute truncation. + const time = Date.parse('2026-01-01T00:00:00Z') + assert.equal(desktopPreview(once('2028-02-30T12:34'), 'en', false, time).nextRunAt, Date.parse('2028-03-01T12:34:00Z')) + assert.equal(desktopPreview(once('2028-01-01T12:34:01'), 'en', false, time).nextRunAt, Date.parse('2028-01-01T12:34:00Z')) +}) + +test('preview matches Desktop around DST gaps and repeated wall minutes', async t => { + const cases = [ + // The scan traverses 01:59 -> 03:00, or starts after 01:59 and misses the gap. + [recurring('30 2 * * *', LA), '2026-03-08T09:58:00Z', '2026-03-08T10:00:00Z'], + [recurring('30 2 * * *', LA), '2026-03-08T09:59:00Z', '2026-03-09T09:30:00Z'], + // Desktop's two-offset once conversion lands at 01:30, not 03:00, in this LA gap. + [once('2026-03-08T02:30', LA), '2026-03-08T08:00:00Z', '2026-03-08T09:30:00Z'], + // The cron scan returns the first match strictly after the cutoff; both 01:30s can match. + [recurring('30 1 * * *', LA), '2026-11-01T07:00:00Z', '2026-11-01T08:30:00Z'], + [recurring('30 1 * * *', LA), '2026-11-01T08:30:00Z', '2026-11-01T09:30:00Z'], + // Ambiguous once resolves via the offset calculation: earlier in LA, later in Berlin. + [once('2026-11-01T01:30', LA), '2026-11-01T07:00:00Z', '2026-11-01T08:30:00Z'], + [once('2026-10-25T02:30', 'Europe/Berlin'), '2026-10-25T00:00:00Z', '2026-10-25T01:30:00Z'] + ] + for (const [schedule, after, next] of cases) { + const { preview } = fixture(t, after) + const desktop = desktopPreview(schedule, 'en', false, Date.parse(after)) + assert.equal(desktop.nextRunAt, Date.parse(next)) + assert.deepEqual(await preview(request(schedule)), desktop) + } +}) + +test('past once and equality with the evaluation instant respect allowPast', async t => { + const { preview } = fixture(t) + for (const [wall, description] of [ + ['2025-12-31T23:59', 'once at 2025-12-31 23:59'], + ['2026-01-01T00:00', 'once at 2026-01-01 00:00'] + ]) { + assert.deepEqual(await preview(request(once(wall))), invalid('invalid-once')) + assert.deepEqual(await preview(request(once(wall), 'en', true)), success(description, null)) + } + assert.deepEqual(await preview(request(once('2026-01-01T00:01'))), success('once at 2026-01-01 00:01', '2026-01-01T00:01:00Z')) +}) + +test('rejects extra or mistyped fields, offsets, oversized fields, and client clocks/code', async t => { + const { preview } = fixture(t) + const { schedule, locale, allowPast } = valid + const accessor = { locale, allowPast, get schedule() { assert.fail('accessor invoked') } } + const proto = Object.create({ schedule }) + for (const input of [null, [], accessor, proto, { schedule, locale }, { schedule, allowPast }, + { ...valid, locale: 'en-US' }, { ...valid, allowPast: 'false' }, { ...valid, allowPast: 0 }, + { ...valid, now: 0 }, { ...valid, timestamp: 0 }, { ...valid, code: 'return true' }, + { ...valid, schedule: { ...schedule, at: '2026-01-01T00:01' } }, + { ...valid, schedule: { ...schedule, taskId: 'other' } }, + { ...valid, schedule: { ...schedule, kind: 'other' } }, + { ...valid, schedule: { kind: 'once', at: '2026-01-01T00:01' } }, + { ...valid, schedule: { kind: 'recurring', tz: UTC } }]) { + assert.deepEqual(await preview(input), invalid('invalid-input')) + } + for (const tz of [0, '', 'PST', '+08:00', 'UTC+08:00', 'Mars/Olympus_Mons', `Asia/${'A'.repeat(128)}`]) { + assert.deepEqual(await preview(request(recurring('*/15 * * * *', tz))), invalid('invalid-tz')) + } + for (const cron of [0, '', '* * * * * *', '60 * * * *', '*/0 * * * *', 'z'.repeat(513)]) { + assert.deepEqual(await preview(request(recurring(cron))), invalid('invalid-cron')) + } + for (const wall of [0, '2026-01-01T00:10:59', '2026-01-01T00:10Z', '2026-01-01T00:10:00.000', ' 2026-01-01T00:10 ', 'z'.repeat(20)]) { + assert.deepEqual(await preview(request(once(wall))), invalid('invalid-once')) + } +}) + +test('samples each accepted preview clock once and bypasses Desktop default when supplied', async t => { + const time = Date.parse('2026-01-01T00:00:00Z') + const clock = t.mock.method(Date, 'now', () => time) + const schedule = once('2026-01-01T00:01') + assert.equal(desktopPreview(schedule).nextRunAt, time + 60_000) + assert.equal(clock.mock.callCount(), 1) + assert.equal(desktopPreview(schedule, 'en', false, time + 60_000).ok, false) + assert.equal(clock.mock.callCount(), 1) + const runner = openTaskPreview() + t.after(runner.close) + assert.equal((await runner.preview(request(schedule))).nextRunAt, time + 60_000) + assert.equal(clock.mock.callCount(), 2) + assert.deepEqual(await runner.preview({ ...valid, now: time }), invalid('invalid-input')) + assert.equal(clock.mock.callCount(), 2) +}) + +test('limits concurrency without a queue, aborts work, and recovers capacity after exit', async t => { + const { preview } = fixture(t) + const alreadyAborted = AbortSignal.abort() + await assert.rejects(preview(valid, alreadyAborted), fault('preview_aborted')) + const cancel = new AbortController() + const first = assert.rejects(preview(valid, cancel.signal), fault('preview_aborted')) + const second = preview(valid) + const overflow = assert.rejects(preview(valid), fault('preview_busy')) + cancel.abort() + // The cancelled worker is still charged to the limit until its exit event. + const stillFull = assert.rejects(preview(valid), fault('preview_busy')) + await Promise.all([first, overflow, stillFull]) + const expected = success('every 15 min', '2026-01-01T00:15:00Z') + assert.deepEqual(await second, expected) + assert.deepEqual(await preview(valid), expected) +}) + +test('close settles all pending previews and drains workers; repeated close is idempotent', async t => { + const { preview, close } = fixture(t) + const first = assert.rejects(preview(valid), fault('preview_closed')) + const second = assert.rejects(preview(valid), fault('preview_closed')) + const draining = close() + assert.equal(close(), draining) + await Promise.all([first, second, draining]) + await assert.rejects(preview(valid), fault('preview_closed')) +}) + +test('the wall timer terminates an in-flight worker at the preview budget', async t => { + const { preview, close } = fixture(t) + t.mock.timers.enable({ apis: ['setTimeout'] }) + // Advance the main-thread clock before it can consume a real worker result. + const timedOut = assert.rejects(preview(valid), fault('preview_timeout')) + t.mock.timers.tick(2_000) + await timedOut + await close() +}) + +test('worker and parent dependency graphs expose no task store, filesystem, network or model access', async () => { + const root = fileURLToPath(new URL('../../../', import.meta.url)) + const parent = 'apps/headless/src/tasks/preview.mjs' + const worker = 'apps/headless/src/tasks/preview-worker.mjs' + const core = 'apps/headless/dist/schedule-core.mjs' + const { metafile } = await build({ + absWorkingDir: root, entryPoints: [parent, worker], outdir: 'task-preview-dependency-check', + bundle: true, platform: 'node', format: 'esm', metafile: true, write: false + }) + assert.deepEqual(Object.keys(metafile.inputs).sort(), [parent, worker, core].sort()) + const imports = Object.values(metafile.outputs).flatMap(output => output.imports.map(dep => dep.path)) + assert.deepEqual([...new Set(imports)].sort(), ['node:events', 'node:worker_threads']) +}) From 7fff90290005e86e0c2dd839185c3fea0d0841d3 Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Thu, 26 Nov 2026 20:43:34 +0800 Subject: [PATCH 03/12] =?UTF-8?q?feat(tasks):=20=E8=AF=BB=E5=8F=96?= =?UTF-8?q?=E5=8E=9F=E7=94=9F=E8=AE=B0=E5=BD=95=E5=B9=B6=E7=A1=AE=E8=AE=A4?= =?UTF-8?q?=E6=9A=82=E5=81=9C=E5=8D=95=E9=A1=B9=E4=BB=BB=E5=8A=A1=20/=20in?= =?UTF-8?q?spect=20native=20records=20and=20conditionally=20pause=20one=20?= =?UTF-8?q?task?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/headless/src/tasks/errors.mjs | 7 + apps/headless/src/tasks/native.mjs | 138 ++++++++ apps/headless/src/tasks/packed.mjs | 90 ++++++ apps/headless/src/tasks/storage.mjs | 156 +++++++++ apps/headless/src/tasks/store.mjs | 85 +++++ .../test/task-store-publication.test.mjs | 95 ++++++ apps/headless/test/task-store.test.mjs | 305 ++++++++++++++++++ 7 files changed, 876 insertions(+) create mode 100644 apps/headless/src/tasks/errors.mjs create mode 100644 apps/headless/src/tasks/native.mjs create mode 100644 apps/headless/src/tasks/packed.mjs create mode 100644 apps/headless/src/tasks/storage.mjs create mode 100644 apps/headless/src/tasks/store.mjs create mode 100644 apps/headless/test/task-store-publication.test.mjs create mode 100644 apps/headless/test/task-store.test.mjs diff --git a/apps/headless/src/tasks/errors.mjs b/apps/headless/src/tasks/errors.mjs new file mode 100644 index 00000000..eb52c3b6 --- /dev/null +++ b/apps/headless/src/tasks/errors.mjs @@ -0,0 +1,7 @@ +import { HttpError } from '../http/policy.mjs' + +export const taskUnsupported = () => new HttpError(409, 'task_file_unsupported') +export const taskConflict = () => new HttpError(409, 'task_conflict') +export const taskUnconfirmed = () => new HttpError(503, 'task_storage_unconfirmed') +export const taskLimit = () => new HttpError(413, 'task_limit') +export const taskUnauthorized = () => new HttpError(401, 'unauthorized') diff --git a/apps/headless/src/tasks/native.mjs b/apps/headless/src/tasks/native.mjs new file mode 100644 index 00000000..8b0a8914 --- /dev/null +++ b/apps/headless/src/tasks/native.mjs @@ -0,0 +1,138 @@ +import { createHash } from 'node:crypto' +import { decodeUtf8 } from '../files/workspace-files-fd.mjs' +import { taskLimit, taskUnsupported } from './errors.mjs' +import { patchTaskStatus, taskRecordSpans } from './packed.mjs' + +export const MAX_TASK_FILE_BYTES = 1024 * 1024 +const MAX_TASKS = 128 +const MAX_RUNS = 50 // Desktop MAX_RUNS_PER_TASK +const statusValues = new Set(['active', 'paused', 'completed', 'error']) +const runStatuses = new Set(['ok', 'error', 'skipped', 'aborted']) +const displayControls = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu +const metadataControls = /[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u +const digest = bytes => createHash('sha256').update(bytes).digest('hex') +const absentRevision = digest('deva:native-tasks:v1:absent\0') + +export const validTaskId = value => typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}(?![\s\S])/u.test(value) +export const validTaskRevision = value => typeof value === 'string' && value.length === 64 && !/[^0-9a-f]/u.test(value) +export const validTaskTime = value => Number.isSafeInteger(value) && Math.abs(value) <= 8_640_000_000_000_000 +export const taskRevision = file => file ? digest(file.bytes) : absentRevision + +function object(value) { + if (value === null || typeof value !== 'object' || Array.isArray(value)) throw taskUnsupported() + return value +} + +function string(value, max, { raw = false, prompt = false } = {}) { + if (typeof value !== 'string') throw taskUnsupported() + if (Buffer.byteLength(value) > max) throw taskLimit() + if (prompt) return value.toWellFormed() + if (!value.isWellFormed() || (!raw && metadataControls.test(value))) throw taskUnsupported() + return value +} + +// Prompt syntax remains literal (including HTML/Markdown-like text). Consumers render it +// as a text node, never as HTML or Markdown; neither markup nor path-looking text is resolved. +const plainPrompt = value => string(value, 64 * 1024, { prompt: true }).replace(/\r\n?/gu, '\n').replace(displayControls, '') + +function id(value) { + string(value, 128) + if (!validTaskId(value)) throw taskUnsupported() + return value +} +const optionalId = value => value === undefined || value === null || value === '' ? null : id(value) +const optionalAuth = (value, max) => value === undefined || value === null || value === '' ? null : string(value, max) + +function ms(value) { + if (!validTaskTime(value)) throw taskUnsupported() + return value +} +const optionalMs = value => value === undefined || value === null ? null : ms(value) + +function scheduleView(value) { + const { kind, at, cron, tz } = object(value) + const timezone = string(tz, 128) + if (!timezone.trim()) throw taskUnsupported() + if (kind === 'once' && typeof at === 'string' && at.trim()) return { kind, at: string(at, 64), tz: timezone } + if (kind === 'recurring' && typeof cron === 'string' && cron.trim()) return { kind, cron: string(cron, 256), tz: timezone } + throw taskUnsupported() +} + +function authView(value) { + const { personaId, modelRef } = value === undefined ? {} : object(value) + return { personaId: optionalAuth(personaId, 128), modelRef: optionalAuth(modelRef, 512) } +} + +function runView(value) { + const { firedAt, finishedAt, status, summary, error, handoff } = object(value) + if (!runStatuses.has(status)) throw taskUnsupported() + const run = { firedAt: ms(firedAt), status } + if (finishedAt !== undefined) run.finishedAt = ms(finishedAt) + if (summary !== undefined) run.summary = string(summary, 16 * 1024, { raw: true }) + if (error !== undefined) run.error = string(error, 16 * 1024, { raw: true }) + if (handoff !== undefined) { + const { summary, needsAction } = object(handoff) + if (typeof needsAction !== 'boolean') throw taskUnsupported() + run.handoff = { summary: string(summary, 16 * 1024, { raw: true }), needsAction } + } + return run +} + +function entryView(value, writable) { + const task = object(value) + if (!statusValues.has(task.status)) throw taskUnsupported() + // Older v1 records may omit runtime defaults; a present field must have the native type. + const { runs = [], consecutiveErrors = 0 } = task + if (!Array.isArray(runs) || !Number.isSafeInteger(consecutiveErrors) || consecutiveErrors < 0) throw taskUnsupported() + if (runs.length > MAX_RUNS) throw taskLimit() + const summary = { + id: id(task.id), + title: string(task.title, 512, { raw: true }), + status: task.status, + schedule: scheduleView(task.schedule), + createdAt: ms(task.createdAt), + updatedAt: ms(task.updatedAt), + lastRunAt: optionalMs(task.lastRunAt), + nextRunAt: optionalMs(task.nextRunAt), + runCount: runs.length + } + const detail = { + ...summary, + prompt: plainPrompt(task.prompt), + auth: authView(task.auth), + sessionId: id(task.sessionId), + ownerSessionId: optionalId(task.ownerSessionId), + originSessionId: optionalId(task.originSessionId), + consecutiveErrors, + runs: runs.map(runView), + pauseAllowed: writable && task.status === 'active' + } + return { summary, detail } +} + +export function parseNativeTasks(file) { + if (file === null) return { entries: [] } + let text, value + try { + text = decodeUtf8(file.bytes) + value = JSON.parse(text) + } catch { throw taskUnsupported() } + if (!value || value.version !== 1 || !Array.isArray(value.tasks)) throw taskUnsupported() + if (value.tasks.length > MAX_TASKS) throw taskLimit() + const spans = taskRecordSpans(text) + const ids = new Set() + const entries = value.tasks.map((task, index) => { + const entry = entryView(task, file.writable) + const { id } = entry.summary + if (ids.has(id) || !spans[index]?.status || !spans[index]?.updatedAt) throw taskUnsupported() + ids.add(id) + return { ...entry, spans: spans[index] } + }) + return { text, entries } +} + +export function pauseNativeTask(document, entry, updatedAt) { + const bytes = patchTaskStatus(document.text, entry.spans, updatedAt) + if (bytes.length > MAX_TASK_FILE_BYTES) throw taskLimit() + return bytes +} diff --git a/apps/headless/src/tasks/packed.mjs b/apps/headless/src/tasks/packed.mjs new file mode 100644 index 00000000..23b3fa98 --- /dev/null +++ b/apps/headless/src/tasks/packed.mjs @@ -0,0 +1,90 @@ +import { taskLimit, taskUnsupported } from './errors.mjs' + +// After JSON.parse establishes the grammar, inspect the same source for duplicate keys, +// bounded nesting, and the exact spans of the only editable native values. Byte-equivalent +// splicing keeps opaque fields, numeric precision, whitespace and record order intact. +export function taskRecordSpans(text) { + const spans = [] + const quote = /["\\]/g + const space = /[\t\n\r ]*/y + const atom = /[^\t\n\r ,}\]]+/y + let offset = 0 + let nodes = 0 + + function skipSpace() { + space.lastIndex = offset + space.exec(text) + offset = space.lastIndex + } + + function readString() { + quote.lastIndex = ++offset + for (let match; (match = quote.exec(text));) { + if (match[0] === '"') { + offset = quote.lastIndex + return + } + quote.lastIndex++ + } + throw taskUnsupported() + } + + function value(depth, role, fields) { + if (++nodes > 262_144 || depth > 32) throw taskLimit() + skipSpace() + const start = offset + const next = text[offset] + if (next === '{') { + const keys = new Set() + offset++ + skipSpace() + while (text[offset] !== '}') { + const keyStart = offset + readString() + const key = JSON.parse(text.slice(keyStart, offset)) + if (keys.has(key)) throw taskUnsupported() + keys.add(key) + if (++nodes > 262_144) throw taskLimit() + skipSpace() + offset++ // colon + const span = value(depth + 1, role === 'root' && key === 'tasks' ? 'records' : null) + if (role === 'record' && (key === 'status' || key === 'updatedAt')) fields[key] = span + skipSpace() + if (text[offset] !== ',') break + offset++ + skipSpace() + } + offset++ + } else if (next === '[') { + offset++ + skipSpace() + while (text[offset] !== ']') { + const fields = role === 'records' ? {} : undefined + if (fields) spans.push(fields) + value(depth + 1, fields ? 'record' : null, fields) + skipSpace() + if (text[offset] !== ',') break + offset++ + skipSpace() + } + offset++ + } else if (next === '"') { + readString() + } else { + atom.lastIndex = offset + if (!atom.exec(text)) throw taskUnsupported() + offset = atom.lastIndex + } + return [start, offset] + } + + value(0, 'root') + return spans +} + +export function patchTaskStatus(text, spans, updatedAt) { + const patches = [[spans.status, '"paused"'], [spans.updatedAt, JSON.stringify(updatedAt)]] + .sort(([a], [b]) => b[0] - a[0]) + for (const [[start, end], replacement] of patches) text = text.slice(0, start) + replacement + text.slice(end) + return Buffer.from(text, 'utf8') +} diff --git a/apps/headless/src/tasks/storage.mjs b/apps/headless/src/tasks/storage.mjs new file mode 100644 index 00000000..c1bb95ae --- /dev/null +++ b/apps/headless/src/tasks/storage.mjs @@ -0,0 +1,156 @@ +import { randomBytes } from 'node:crypto' +import { + closeSync, constants as C, fchmodSync, fstatSync, fsyncSync, lstatSync, openSync, readSync, + renameSync, unlinkSync, writeFileSync +} from 'node:fs' +import { PATH, fdPath, mountId, openAbsoluteDirectory, sameInode } from '../files/workspace-files-fd.mjs' +import { HttpError } from '../http/policy.mjs' +import { taskConflict, taskLimit, taskUnconfirmed } from './errors.mjs' +import { MAX_TASK_FILE_BYTES, taskRevision } from './native.mjs' + +const stats = { bigint: true } +const TASK_FILE = 'tasks.json' +const readFlags = C.O_RDONLY | C.O_NONBLOCK +const writeFlags = C.O_WRONLY | C.O_CREAT | C.O_EXCL | C.O_NOFOLLOW | C.O_NONBLOCK +const signature = ['uid', 'gid', 'mode', 'nlink', 'size', 'mtimeNs', 'ctimeNs'] +const same = (a, b) => sameInode(a, b) && signature.every(key => a[key] === b[key]) +const perms = stat => stat.mode & 0o7777n +const ownerDirectory = (stat, uid) => stat.isDirectory() && stat.uid === uid && + (perms(stat) & 0o7022n) === 0n && (perms(stat) & 0o500n) === 0o500n +const ownerFile = (stat, uid) => stat.isFile() && stat.uid === uid && stat.nlink === 1n && + (perms(stat) & 0o7022n) === 0n && (perms(stat) & 0o400n) === 0o400n + +function lstat(path) { + try { return lstatSync(path, stats) } catch (error) { if (error?.code === 'ENOENT') return null; throw error } +} + +const storageError = error => error instanceof HttpError ? error : taskUnconfirmed() + +// Every operation pins the fixed directory and closes all of its own descriptors. Production +// uses the existing exclusive workbench volume writer lock. The final synchronous read/CAS +// and atomic rename serialize with cooperating writers; a same-UID writer which ignores that +// lock can still race a syscall boundary (plain rename has no compare-inode precondition). +export function withTaskStorage(root, operation) { + let dirPin + try { + const uid = BigInt(process.geteuid()) + dirPin = openAbsoluteDirectory(root) // O_NOFOLLOW for every path component. + const dirIdentity = fstatSync(dirPin, stats) + const mount = mountId(dirPin) + if (!ownerDirectory(dirIdentity, uid)) throw taskUnconfirmed() + const path = fdPath(dirPin, TASK_FILE) + + function directory() { + const pin = openAbsoluteDirectory(root) + try { + const held = fstatSync(dirPin, stats) + const live = fstatSync(pin, stats) + if (!ownerDirectory(held, uid) || !ownerDirectory(live, uid) || !sameInode(dirIdentity, live) || + perms(held) !== perms(live) || mountId(pin) !== mount) throw taskUnconfirmed() + return held + } finally { closeSync(pin) } + } + + function currentIdentity(expected) { + if (expected === null) { + if (lstat(path) !== null) throw taskUnconfirmed() + return + } + const pin = openSync(path, PATH) + try { + if (!same(expected, fstatSync(pin, stats)) || mountId(pin) !== mount) throw taskUnconfirmed() + } finally { closeSync(pin) } + } + + function read() { + directory() + const named = lstat(path) + if (named === null) { + directory() + currentIdentity(null) + return null + } + if (!ownerFile(named, uid)) throw taskUnconfirmed() + if (named.size > BigInt(MAX_TASK_FILE_BYTES)) throw taskLimit() + // O_PATH pins the regular file before opening for data; a racing FIFO or device is + // never opened for reading. The anchored proc path refers only to our held descriptor. + const pin = openSync(path, PATH) + try { + const pinned = fstatSync(pin, stats) + if (!same(named, pinned) || mountId(pin) !== mount) throw taskUnconfirmed() + const fd = openSync(fdPath(pin), readFlags) + try { + const opened = fstatSync(fd, stats) + if (!same(pinned, opened) || mountId(fd) !== mount) throw taskUnconfirmed() + const bytes = Buffer.allocUnsafe(Number(opened.size)) + for (let offset = 0; offset < bytes.length;) { + const count = readSync(fd, bytes, offset, bytes.length - offset, offset) + if (!count) throw taskUnconfirmed() + offset += count + } + const env = directory() + currentIdentity(opened) + if (!same(opened, fstatSync(fd, stats))) throw taskUnconfirmed() + // Legacy owner 0644 and other safe read-only modes can be inspected. Require exact + // 0700 data directory + 0600 native file for publication; leave legacy permissions alone. + return { bytes, identity: opened, writable: perms(env) === 0o700n && perms(opened) === 0o600n } + } finally { closeSync(fd) } + } finally { closeSync(pin) } + } + + function check(before, revision, writing = false) { + const actual = read() + if (taskRevision(actual) !== revision || !actual) throw taskConflict() + if (writing && !actual.writable) throw taskUnconfirmed() + if (!same(before.identity, actual.identity)) throw taskConflict() + return actual + } + + function publish(before, revision, bytes, verifyOwner) { + const tmp = fdPath(dirPin, `.tasks.json.${randomBytes(16).toString('hex')}.tmp`) + let result, failure, dir, fd, staged, renamed = false + try { + if (!before.writable || perms(directory()) !== 0o700n) throw taskUnconfirmed() + dir = openSync(fdPath(dirPin), readFlags | C.O_DIRECTORY) + fd = openSync(tmp, writeFlags, 0o600) + fchmodSync(fd, 0o600) + writeFileSync(fd, bytes) + fsyncSync(fd) + staged = fstatSync(fd, stats) + verifyOwner() // Synchronous, immediately before the final on-disk comparison and publication. + const actual = check(before, revision, true) + const named = lstat(tmp) + if (!named || !ownerFile(staged, uid) || perms(staged) !== 0o600n || !same(staged, named) || + !same(staged, fstatSync(fd, stats)) || perms(directory()) !== 0o700n) throw taskUnconfirmed() + currentIdentity(actual.identity) + renameSync(tmp, path) + renamed = true + fsyncSync(dir) + } catch (error) { failure = storageError(error) } + + // Always make a full disk observation after an attempted publication, including OS + // failures. A write is acknowledged only for the exact bytes on our own renamed inode. + // In particular, a concurrent external edit to an equivalent task is never a success. + try { + result = read() + if (!renamed || !result?.writable || !sameInode(staged, result.identity) || !result.bytes.equals(bytes)) { + failure ??= taskUnconfirmed() + } + } catch { failure ??= taskUnconfirmed() } + try { + if (fd !== undefined && !renamed) { + const named = lstat(tmp) + if (named && sameInode(named, fstatSync(fd, stats))) unlinkSync(tmp) + } + } catch { failure ??= taskUnconfirmed() } + finally { + try { if (fd !== undefined) closeSync(fd) } finally { if (dir !== undefined) closeSync(dir) } + } + if (failure) throw failure + return result + } + + return operation({ read, check, publish }) + } catch (error) { throw storageError(error) } + finally { if (dirPin !== undefined) closeSync(dirPin) } +} diff --git a/apps/headless/src/tasks/store.mjs b/apps/headless/src/tasks/store.mjs new file mode 100644 index 00000000..c847f5d8 --- /dev/null +++ b/apps/headless/src/tasks/store.mjs @@ -0,0 +1,85 @@ +import { isAbsolute, resolve } from 'node:path' +import { HttpError } from '../http/policy.mjs' +import { taskConflict, taskUnauthorized, taskUnconfirmed } from './errors.mjs' +import { parseNativeTasks, pauseNativeTask, taskRevision, validTaskId, validTaskRevision, validTaskTime } from './native.mjs' +import { withTaskStorage } from './storage.mjs' + +const execution = 'inactive' +const invalidId = () => new HttpError(400, 'invalid_task_id') + +function taskEntry(document, id) { + const entry = document.entries.find(item => item.summary.id === id) + if (!entry) throw new HttpError(404, 'task_not_found') + return entry +} + +function authenticate(verifyOwner, id) { + if (typeof verifyOwner !== 'function') throw taskUnauthorized() + let verification + try { verification = verifyOwner(id) } + catch (error) { + if (error?.code === 'AUTH_FAILED') throw new HttpError(401, 'auth') + throw error + } + if (typeof verification?.then === 'function') { + Promise.resolve(verification).catch(() => {}) + throw taskUnauthorized() + } + if (verification === false) throw taskUnauthorized() +} + +/** + * Owner-authorized caller; read authorization is the caller's responsibility. Pause also + * takes a required synchronous assertion of the *original* owner's current authorization. + * Native storage is reopened per operation, so this store needs no close or global cache. + */ +export function openTaskStore({ dataDir, now = Date.now }) { + if (typeof dataDir !== 'string' || !isAbsolute(dataDir) || typeof now !== 'function') throw taskUnconfirmed() + const root = resolve(dataDir) + + return Object.freeze({ + async list() { + return withTaskStorage(root, storage => { + const file = storage.read() + const { entries } = parseNativeTasks(file) + const tasks = entries.map(entry => entry.summary).sort((a, b) => a.createdAt - b.createdAt) + return { tasks, revision: taskRevision(file), execution } + }) + }, + async get(id) { + if (!validTaskId(id)) throw invalidId() + return withTaskStorage(root, storage => { + const file = storage.read() + const { detail: task } = taskEntry(parseNativeTasks(file), id) + return { task, revision: taskRevision(file), execution } + }) + }, + async pause(id, revision, verifyOwner) { + if (!validTaskId(id)) throw invalidId() + if (!validTaskRevision(revision)) throw new HttpError(400, 'invalid_task_revision') + authenticate(verifyOwner, id) + return withTaskStorage(root, storage => { + const before = storage.read() + if (taskRevision(before) !== revision) throw taskConflict() + const document = parseNativeTasks(before) + const entry = taskEntry(document, id) + const reauthorize = () => authenticate(verifyOwner, id) + if (entry.summary.status === 'paused') { + reauthorize() + // Idempotent retry still checks disk after reauthorization, and performs no write. + const current = storage.check(before, revision) + return { task: taskEntry(parseNativeTasks(current), id).detail, revision, execution } + } + if (entry.summary.status !== 'active') throw new HttpError(409, 'task_state') + if (!entry.detail.pauseAllowed) throw taskUnconfirmed() + const updatedAt = now() + if (!validTaskTime(updatedAt)) throw taskUnconfirmed() + // Desktop pauses by changing only status and updatedAt, retaining nextRunAt and counters. + const bytes = pauseNativeTask(document, entry, updatedAt) + const confirmed = storage.publish(before, revision, bytes, reauthorize) + const { detail: task } = taskEntry(parseNativeTasks(confirmed), id) + return { task, revision: taskRevision(confirmed), execution } + }) + } + }) +} diff --git a/apps/headless/test/task-store-publication.test.mjs b/apps/headless/test/task-store-publication.test.mjs new file mode 100644 index 00000000..6b6ef3a5 --- /dev/null +++ b/apps/headless/test/task-store-publication.test.mjs @@ -0,0 +1,95 @@ +import assert from 'node:assert/strict' +import { createHash } from 'node:crypto' +import fs from 'node:fs' +import { syncBuiltinESMExports } from 'node:module' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import test from 'node:test' +import { openTaskStore } from '../src/tasks/store.mjs' + +const initial = '{"version":1,"tasks":[{"id":"test-1","title":"fixture","prompt":"Inspect only","schedule":{"kind":"once",' + + '"at":"2026-12-01T17:00","tz":"UTC"},"sessionId":"task-test-1","status":"active","createdAt":10,"updatedAt":11}]}' +const authorize = () => true + +function fixture(t) { + const root = fs.mkdtempSync(join(tmpdir(), 'deva-task-publication-')) + assert.equal(dirname(root), tmpdir()) + t.after(() => fs.rmSync(root, { recursive: true, force: true })) + const dataDir = join(root, 'data') + fs.mkdirSync(dataDir, { mode: 0o700 }) + const path = join(dataDir, 'tasks.json') + fs.writeFileSync(path, initial, { mode: 0o600 }) + return { root, path, dataDir, store: openTaskStore({ dataDir, now: () => 12 }) } +} + +function mockFs(t, name, wrap) { + t.mock.method(fs, name, wrap(fs[name])) + syncBuiltinESMExports() + t.after(() => { t.mock.restoreAll(); syncBuiltinESMExports() }) +} + +const unconfirmed = { status: 503, code: 'task_storage_unconfirmed' } + +test('confirms disk after a rename failure without trusting staged bytes', async t => { + const { path, dataDir, store } = fixture(t) + const { revision } = await store.list() + let failed = false + let readback = '' + mockFs(t, 'renameSync', original => (from, to) => { + if (!from.includes('.tasks.json.')) return original(from, to) + failed = true + throw Object.assign(new Error('fixture rename failure'), { code: 'EIO' }) + }) + mockFs(t, 'readSync', original => (fd, buffer, offset, length, ...args) => { + const count = original(fd, buffer, offset, length, ...args) + if (failed) readback += buffer.toString('utf8', offset, offset + count) + return count + }) + await assert.rejects(store.pause('test-1', revision, authorize), unconfirmed) + assert.equal(readback, initial) + assert.equal(fs.readFileSync(path, 'utf8'), initial) + assert.deepEqual(fs.readdirSync(dataDir), ['tasks.json']) +}) + +test('even exact bytes are unconfirmed after failed directory fsync or replacement by another inode', async t => { + await t.test('directory fsync failure', async t => { + const { path, store } = fixture(t) + const { revision } = await store.list() + let failed = false + let readback = '' + mockFs(t, 'fsyncSync', original => fd => { + if (!fs.fstatSync(fd).isDirectory()) return original(fd) + failed = true + throw Object.assign(new Error('fixture directory sync failure'), { code: 'EIO' }) + }) + mockFs(t, 'readSync', original => (fd, buffer, offset, length, ...args) => { + const count = original(fd, buffer, offset, length, ...args) + if (failed) readback += buffer.toString('utf8', offset, offset + count) + return count + }) + await assert.rejects(store.pause('test-1', revision, authorize), unconfirmed) + assert.equal(readback, initial.replace('"active"', '"paused"').replace('"updatedAt":11', '"updatedAt":12')) + assert.equal(readback, fs.readFileSync(path, 'utf8')) + }) + + await t.test('foreign equivalent write', async t => { + const { root, path, store } = fixture(t) + const { revision } = await store.list() + let stagedInode + mockFs(t, 'renameSync', original => (from, to) => { + original(from, to) + if (from.includes('.tasks.json.')) { + stagedInode = fs.statSync(to).ino + const replacement = join(root, 'external-temporary') + fs.writeFileSync(replacement, fs.readFileSync(to), { mode: 0o600 }) + original(replacement, to) + } + }) + await assert.rejects(store.pause('test-1', revision, authorize), unconfirmed) + assert.ok(stagedInode) + assert.notEqual(fs.statSync(path).ino, stagedInode) + const bytes = fs.readFileSync(path) + assert.equal(bytes.toString(), initial.replace('"active"', '"paused"').replace('"updatedAt":11', '"updatedAt":12')) + assert.equal((await store.get('test-1')).revision, createHash('sha256').update(bytes).digest('hex')) + }) +}) diff --git a/apps/headless/test/task-store.test.mjs b/apps/headless/test/task-store.test.mjs new file mode 100644 index 00000000..a3672c6a --- /dev/null +++ b/apps/headless/test/task-store.test.mjs @@ -0,0 +1,305 @@ +import assert from 'node:assert/strict' +import { createHash } from 'node:crypto' +import { chmodSync, chownSync, existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import test from 'node:test' +import { openTaskStore } from '../src/tasks/store.mjs' + +const ID = '2a29ffa0-9778-4b4b-a3cb-cbce444b11f3' +const NOW = 1_795_715_400_001 +const runAt = NOW - 1_000 +const nextAt = NOW + 1_000 +const authOwner = () => ({ role: 'owner', id: 'original-login' }) +const digest = bytes => createHash('sha256').update(bytes).digest('hex') + +function nativeTask(overrides = {}) { + return { + id: ID, title: 'Daily report', prompt: 'Collect the report\r\n\u0000\u202e[local](file:///prompt-fixture) as text', + schedule: { kind: 'recurring', cron: '30 8 * * 1-5', tz: 'Asia/Shanghai', scratchPath: '/private/schedule' }, + auth: { personaId: 'persona-1', modelRef: 'openrouter:example/model', allowedTools: ['irrelevant'], focusRoot: '/private/root' }, + sessionId: `task-${ID}`, ownerSessionId: 'sess_owner', originSessionId: 'sess_origin', status: 'active', + createdAt: NOW - 20_000, updatedAt: NOW - 10_000, lastRunAt: runAt, nextRunAt: nextAt, consecutiveErrors: 2, + runs: [ + { firedAt: runAt - 3_000, status: 'skipped', summary: 'One missed run' }, + { firedAt: runAt - 2_000, finishedAt: runAt - 1_500, status: 'ok', summary: 'Reporting complete ✅', + handoff: { summary: 'Team notified', needsAction: true, extra: '/private/handoff' }, transcriptPath: '/private/run' }, + { firedAt: runAt - 1_000, status: 'aborted', summary: 'Stopped\r\nby owner' }, + { firedAt: runAt, finishedAt: runAt + 5, status: 'error', error: 'Network error' } + ], + privateNative: { config: '/private/native' }, ...overrides + } +} + +function fixture(t, now = () => NOW) { + const parent = mkdtempSync(join(tmpdir(), 'deva-task-store-')) + assert.equal(dirname(parent), tmpdir()) + t.after(() => rmSync(parent, { recursive: true, force: true })) + const dataDir = join(parent, 'home') + mkdirSync(dataDir, { mode: 0o700 }) + const path = join(dataDir, 'tasks.json') + const store = openTaskStore({ dataDir, now }) + const put = (tasks, root = {}) => writeFileSync(path, JSON.stringify({ version: 1, tasks, ...root }), { mode: 0o600 }) + return { parent, dataDir, path, store, put } +} + +const err = (status, code) => ({ status, code }) + +test('reports confirmed absence without materializing anything; ordinary native list and detail are typed allowlists', async t => { + const { dataDir, path, store, put } = fixture(t) + const missing = await store.list() + assert.deepEqual(missing.tasks, []) + assert.match(missing.revision, /^[0-9a-f]{64}$/) + assert.equal(missing.execution, 'inactive') + assert.deepEqual(readdirSync(dataDir), []) + await assert.rejects(store.get(ID), err(404, 'task_not_found')) + await assert.rejects(store.pause(ID, missing.revision, authOwner), err(404, 'task_not_found')) + put([]) + assert.notEqual((await store.list()).revision, missing.revision) + + const task = nativeTask() + const once = nativeTask({ id: 'task_once', sessionId: 'task-task_once', status: 'completed', + schedule: { kind: 'once', at: '2026-11-26T20:00', tz: 'UTC', cron: 'private' }, lastRunAt: null, nextRunAt: null }) + put([task, once], { nativePrivate: '/private/root-file' }) + const summary = { + id: ID, title: task.title, status: 'active', schedule: { kind: 'recurring', cron: '30 8 * * 1-5', tz: 'Asia/Shanghai' }, + createdAt: task.createdAt, updatedAt: task.updatedAt, lastRunAt: runAt, nextRunAt: nextAt, runCount: 4 + } + const list = await store.list() + assert.deepEqual(list, { tasks: [summary, { id: once.id, title: once.title, status: 'completed', + schedule: { kind: 'once', at: '2026-11-26T20:00', tz: 'UTC' }, createdAt: once.createdAt, updatedAt: once.updatedAt, + lastRunAt: null, nextRunAt: null, runCount: 4 }], revision: digest(readFileSync(path)), execution: 'inactive' }) + const detail = await store.get(ID) + for (const projection of [list, detail]) { + assert.doesNotMatch(JSON.stringify(projection), /\/private\/|allowedTools|scratchPath|focusRoot|transcriptPath|nativePrivate|privateNative/) + } + assert.deepEqual(detail, { + task: { ...summary, prompt: 'Collect the report\n[local](file:///prompt-fixture) as text', + auth: { personaId: 'persona-1', modelRef: 'openrouter:example/model' }, sessionId: task.sessionId, + ownerSessionId: 'sess_owner', originSessionId: 'sess_origin', consecutiveErrors: 2, pauseAllowed: true, + runs: [task.runs[0], { firedAt: task.runs[1].firedAt, finishedAt: task.runs[1].finishedAt, status: 'ok', + summary: 'Reporting complete ✅', handoff: { summary: 'Team notified', needsAction: true } }, task.runs[2], task.runs[3]] }, + revision: list.revision, execution: 'inactive' + }) + assert.equal((await store.get(once.id)).task.pauseAllowed, false) + assert.deepEqual(Object.keys(store), ['list', 'get', 'pause']) + assert.equal(store.resume, undefined) + assert.equal(store.run, undefined) + assert.equal(store.create, undefined) +}) + +test('pause preserves every other source byte, retains native scheduling/history, and retries with only the current revision', async t => { + let clockReads = 0 + const { dataDir, path, store, put } = fixture(t, () => { clockReads++; return NOW }) + const other = nativeTask({ id: 'other', status: 'error', createdAt: 0 }) + put([nativeTask(), other]) + const compact = readFileSync(path, 'utf8') + const before = `${compact.slice(0, -1)}, "opaque": { "unsafeNumber":9.007199254740993e15,"2":1,"1":2 } }\r\n` + .replace('"status":"active"', '"st\\u0061tus" : "acti\\u0076e"') + writeFileSync(path, before) + const initial = await store.get(ID) + const observed = [] + const paused = await store.pause(ID, initial.revision, id => { observed.push(id) }) + assert.deepEqual(observed, [ID, ID]) + assert.equal(clockReads, 1) + const expected = before.replace('"acti\\u0076e"', '"paused"').replace(`"updatedAt":${NOW - 10_000}`, `"updatedAt":${NOW}`) + assert.equal(readFileSync(path, 'utf8'), expected) + assert.equal(statSync(path).mode & 0o777, 0o600) + assert.deepEqual(readdirSync(dataDir), ['tasks.json']) + assert.deepEqual(paused, { task: { ...initial.task, status: 'paused', updatedAt: NOW, pauseAllowed: false }, + revision: digest(expected), execution: 'inactive' }) + const inode = statSync(path).ino + assert.deepEqual(await store.pause(ID, paused.revision, authOwner), paused) + assert.equal(statSync(path).ino, inode) + assert.equal(clockReads, 1) + await assert.rejects(store.pause(ID, initial.revision, authOwner), err(409, 'task_conflict')) + await assert.rejects(store.pause('missing', initial.revision, authOwner), err(409, 'task_conflict')) + await assert.rejects(store.pause('other', paused.revision, authOwner), err(409, 'task_state')) + await assert.rejects(store.pause(ID, paused.revision, false), err(401, 'unauthorized')) + // Desktop list order is by creation time, even though the later task is first on disk. + assert.deepEqual((await store.list()).tasks.map(task => task.id), [other.id, ID]) + assert.deepEqual(JSON.parse(readFileSync(path, 'utf8')).tasks.map(task => task.id), [ID, other.id]) +}) + +test('publication reauthorizes the original owner and CAS detects edits to nonmatching records or bytes', async t => { + const { dataDir, path, put, store } = fixture(t) + put([nativeTask(), nativeTask({ id: 'other' })]) + const before = readFileSync(path) + const initial = await store.list() + let calls = 0 + await assert.rejects(store.pause(ID, initial.revision, () => ++calls === 1), err(401, 'unauthorized')) + assert.equal(calls, 2) + assert.deepEqual(readFileSync(path), before) + assert.deepEqual(readdirSync(dataDir), ['tasks.json']) + + calls = 0 + await assert.rejects(store.pause(ID, initial.revision, () => { + if (++calls === 2) throw Object.assign(new Error('expired'), { code: 'AUTH_FAILED' }) + return true + }), err(401, 'auth')) + assert.deepEqual(readFileSync(path), before) + assert.deepEqual(readdirSync(dataDir), ['tasks.json']) + + calls = 0 + const external = Buffer.concat([before, Buffer.from('\n')]) + await assert.rejects(store.pause(ID, initial.revision, () => { + if (++calls === 2) writeFileSync(path, external) + return true + }), err(409, 'task_conflict')) + assert.deepEqual(readFileSync(path), external) + assert.equal((await store.get(ID)).task.status, 'active') + assert.deepEqual(readdirSync(dataDir), ['tasks.json']) + + const updated = await store.get(ID) + await assert.rejects(store.pause(ID, updated.revision, async () => true), err(401, 'unauthorized')) + assert.deepEqual(readFileSync(path), external) + + calls = 0 + await assert.rejects(store.pause(ID, updated.revision, () => { + if (++calls === 2) { + const tmp = readdirSync(dataDir).find(name => name.startsWith('.tasks.json.')) + assert.ok(tmp) + writeFileSync(join(dataDir, tmp), '{"version":1,"tasks":[]}') + } + return true + }), err(503, 'task_storage_unconfirmed')) + assert.deepEqual(readFileSync(path), external) + assert.deepEqual(readdirSync(dataDir), ['tasks.json']) + + put([nativeTask({ status: 'completed' })]) + await assert.rejects(store.pause(ID, (await store.list()).revision, authOwner), err(409, 'task_state')) + await assert.rejects(store.pause(ID, 'bad-revision', authOwner), err(400, 'invalid_task_revision')) + await assert.rejects(store.pause(ID, `${initial.revision}\n`, authOwner), err(400, 'invalid_task_revision')) +}) + +test('path and ownership checks reject unsafe native targets while legacy owner mode permits inspection only', async t => { + const { parent, path, dataDir, store, put } = fixture(t) + const external = join(parent, 'outside.json') + const bytes = JSON.stringify({ version: 1, tasks: [nativeTask()] }) + writeFileSync(external, bytes, { mode: 0o600 }) + for (const id of ['../outside', 'nested/path', 'nested\\path', '%2E%2E', '\u0000x', 'a\n', 'a'.repeat(129), {}, undefined]) { + await assert.rejects(store.get(id), err(400, 'invalid_task_id')) + await assert.rejects(store.pause(id, digest(bytes), authOwner), err(400, 'invalid_task_id')) + } + symlinkSync(external, path) + await assert.rejects(store.list(), err(503, 'task_storage_unconfirmed')) + assert.equal(readFileSync(external, 'utf8'), bytes) + rmSync(path) + linkSync(external, path) + await assert.rejects(store.get(ID), err(503, 'task_storage_unconfirmed')) + rmSync(path) + mkdirSync(path, { mode: 0o700 }) + await assert.rejects(store.list(), err(503, 'task_storage_unconfirmed')) + rmSync(path, { recursive: true }) + + put([nativeTask()]) + const linkDir = join(parent, 'link') + symlinkSync(dataDir, linkDir, 'dir') + await assert.rejects(openTaskStore({ dataDir: linkDir }).list(), err(503, 'task_storage_unconfirmed')) + const nested = join(dataDir, 'nested') + mkdirSync(nested, { mode: 0o700 }) + writeFileSync(join(nested, 'tasks.json'), bytes, { mode: 0o600 }) + await assert.rejects(openTaskStore({ dataDir: join(linkDir, 'nested') }).list(), err(503, 'task_storage_unconfirmed')) + await assert.rejects(openTaskStore({ dataDir: join(parent, 'absent-home') }).list(), err(503, 'task_storage_unconfirmed')) + assert.equal(existsSync(join(parent, 'absent-home')), false) + + chmodSync(path, 0o644) + const legacy = await store.get(ID) + assert.equal(legacy.task.pauseAllowed, false) + await assert.rejects(store.pause(ID, legacy.revision, authOwner), err(503, 'task_storage_unconfirmed')) + assert.equal(statSync(path).mode & 0o777, 0o644) + chmodSync(path, 0o664) + await assert.rejects(store.list(), err(503, 'task_storage_unconfirmed')) + chmodSync(path, 0o600) + chmodSync(dataDir, 0o755) + assert.equal((await store.get(ID)).task.pauseAllowed, false) + await assert.rejects(store.pause(ID, legacy.revision, authOwner), err(503, 'task_storage_unconfirmed')) + chmodSync(dataDir, 0o772) + await assert.rejects(store.list(), err(503, 'task_storage_unconfirmed')) + chmodSync(dataDir, 0o700) + if (process.geteuid() === 0) { + chownSync(path, 65_534, 65_534) + await assert.rejects(store.list(), err(503, 'task_storage_unconfirmed')) + chownSync(path, 0, 0) + chownSync(dataDir, 65_534, 65_534) + await assert.rejects(store.list(), err(503, 'task_storage_unconfirmed')) + } +}) + +test('directory replacement between owner checks fails closed and cleans only the pinned staging directory', async t => { + const { parent, path, dataDir, store, put } = fixture(t) + put([nativeTask()]) + const before = readFileSync(path) + const { revision } = await store.list() + const displaced = join(parent, 'displaced-home') + const external = '{"version":1,"tasks":[]}' + let calls = 0 + await assert.rejects(store.pause(ID, revision, () => { + if (++calls === 2) { + renameSync(dataDir, displaced) + mkdirSync(dataDir, { mode: 0o700 }) + writeFileSync(path, external, { mode: 0o600 }) + } + return true + }), err(503, 'task_storage_unconfirmed')) + assert.equal(readFileSync(path, 'utf8'), external) + assert.deepEqual(readFileSync(join(displaced, 'tasks.json')), before) + assert.deepEqual(readdirSync(displaced), ['tasks.json']) + assert.deepEqual((await store.list()).tasks, []) +}) + +test('fails closed on unsupported data, and bounds the whole file and every record without skipping rows', async t => { + const { path, store, put } = fixture(t) + for (const malformed of ['', '{', Buffer.from([255]), '{"version":2,"tasks":[]}', + '{"version":1,"version":1,"tasks":[]}', '{"version":1,"tasks":{}}', + '{"version":1,"tasks":[],"opaque":{"x":1,"\\u0078":2}}']) { + writeFileSync(path, malformed, { mode: 0o600 }) + await assert.rejects(store.list(), err(409, 'task_file_unsupported')) + } + for (const bad of [null, {}, nativeTask({ status: 'running' }), nativeTask({ runs: [{}] }), + nativeTask({ auth: { personaId: ['private'] } }), nativeTask({ updatedAt: '1234' }), + nativeTask({ nextRunAt: 8_640_000_000_000_001 }), nativeTask({ lastRunAt: 1.25 }), + nativeTask({ sessionId: '../somewhere' }), nativeTask({ schedule: { kind: 'recurring', tz: 'UTC' } })]) { + put([nativeTask(), bad]) + await assert.rejects(store.get(ID), err(409, 'task_file_unsupported')) + await assert.rejects(store.list(), err(409, 'task_file_unsupported')) + } + const maxRun = { firedAt: 12, finishedAt: 19, status: 'ok', summary: 'done' } + const maxRows = Array.from({ length: 128 }, (_, index) => nativeTask({ id: `task-${index}`, runs: Array(50).fill(maxRun) })) + put(maxRows) + assert.equal((await store.list()).tasks.length, 128) + assert.equal((await store.get('task-127')).task.runs.length, 50) + put([...maxRows, nativeTask()]) + await assert.rejects(store.list(), err(413, 'task_limit')) + put([nativeTask({ runs: Array(51).fill(maxRun) })]) + await assert.rejects(store.list(), err(413, 'task_limit')) + put([nativeTask({ title: '中'.repeat(200) })]) + await assert.rejects(store.list(), err(413, 'task_limit')) + put([nativeTask({ prompt: 'a'.repeat(65_537) })]) + await assert.rejects(store.list(), err(413, 'task_limit')) + put([nativeTask({ runs: [{ ...maxRun, summary: 'a'.repeat(16_385) }] })]) + await assert.rejects(store.get(ID), err(413, 'task_limit')) + writeFileSync(path, Buffer.alloc(1_048_577, 32)) + await assert.rejects(store.get(ID), err(413, 'task_limit')) + + put([nativeTask({ auth: undefined, lastRunAt: undefined, nextRunAt: undefined, runs: undefined, + consecutiveErrors: undefined, ownerSessionId: undefined, originSessionId: undefined })]) + const legacy = (await store.get(ID)).task + assert.deepEqual(legacy.auth, { personaId: null, modelRef: null }) + assert.equal(legacy.lastRunAt, null) + assert.equal(legacy.nextRunAt, null) + assert.equal(legacy.runCount, 0) + assert.equal(legacy.consecutiveErrors, 0) + assert.equal(legacy.ownerSessionId, null) + assert.equal(legacy.originSessionId, null) +}) + +test('a clock outside the representable Date range leaves the fully readable original untouched', async t => { + const { dataDir, path, store, put } = fixture(t, () => 8_640_000_000_000_001) + put([nativeTask({ lastRunAt: -8_640_000_000_000_000, nextRunAt: 8_640_000_000_000_000 })]) + const before = readFileSync(path) + const { revision } = await store.list() + await assert.rejects(store.pause(ID, revision, authOwner), err(503, 'task_storage_unconfirmed')) + assert.deepEqual(readFileSync(path), before) + assert.deepEqual(readdirSync(dataDir), ['tasks.json']) +}) From b091fc68ac5e0f40292a0966adb74b24063c0eed Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Thu, 26 Nov 2026 20:43:34 +0800 Subject: [PATCH 04/12] =?UTF-8?q?feat(headless):=20=E6=9A=B4=E9=9C=B2?= =?UTF-8?q?=E5=B7=B2=E8=AE=A4=E8=AF=81=E7=9A=84=E4=BB=BB=E5=8A=A1=E6=9F=A5?= =?UTF-8?q?=E7=9C=8B=E5=92=8C=E9=A2=84=E8=A7=88=20/=20expose=20authenticat?= =?UTF-8?q?ed=20task=20inspection=20and=20previews?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/headless/src/business/handlers.mjs | 20 ++++- apps/headless/src/http/session-routes.mjs | 3 +- apps/headless/src/tasks/routes.mjs | 89 +++++++++++++++++++ .../test/task-inspection-http.test.mjs | 88 ++++++++++++++++++ 4 files changed, 195 insertions(+), 5 deletions(-) create mode 100644 apps/headless/src/tasks/routes.mjs create mode 100644 apps/headless/test/task-inspection-http.test.mjs diff --git a/apps/headless/src/business/handlers.mjs b/apps/headless/src/business/handlers.mjs index 9e243e75..490e8f1f 100644 --- a/apps/headless/src/business/handlers.mjs +++ b/apps/headless/src/business/handlers.mjs @@ -9,6 +9,9 @@ import { chatRoutes } from '../chat/routes.mjs' import { browserRoutes } from '../browser/routes.mjs' import { gitViewRoutes } from '../git/routes.mjs' import { openGitService } from '../git/service.mjs' +import { openTaskStore } from '../tasks/store.mjs' +import { openTaskPreview } from '../tasks/preview.mjs' +import { taskRoutes } from '../tasks/routes.mjs' import { HttpError, json, readJson } from '../http/policy.mjs' import { openSettings } from './settings.mjs' import { allowedModelOrigins } from './provider-fetch.mjs' @@ -50,10 +53,13 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi const settings = await openSettings({ dataDir, vault }) const lifetime = new AbortController() const journal = createEventJournal() - let library, turns, uploads, browser, closingBrowser, git, closingGit + let library, turns, uploads, browser, closingBrowser, git, closingGit, taskStore, preview, tasks, closingTasks try { library = await openLibrary({ dataDir, workspaceRoot, workspaceWritable, privateRoots, gitProjects }) if (library.gitGrants.enabled) git = openGitService({ grants: library.gitGrants, auth }) + // No scheduler is installed in this process. Task records are read only on a human request. + taskStore = openTaskStore({ dataDir }); preview = openTaskPreview() + tasks = taskRoutes({ store: taskStore, preview }) uploads = await openUploadStore({ dataDir }) turns = createTextTurns({ dataDir, settings, journal, ...opts, resolveRole: library.resolveRole, withWorkspace: library.withWorkspace, uploads, deliveries: true }) @@ -62,7 +68,11 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi const { createManualBrowser } = await import('../browser/manual-browser.mjs') browser = createManualBrowser({ runDir: browserRunDir, auth, sessionExists: turns.hasBrowserSession }) } - } catch (err) { journal.close(); await git?.close(); await Promise.allSettled([turns?.close(), uploads?.close(), library?.close()]); throw err } + } catch (err) { + journal.close() + await Promise.allSettled([git?.close(), ...(tasks ? [tasks.close()] : [preview?.close(), taskStore?.close?.()]), + turns?.close(), uploads?.close(), library?.close()]); throw err + } const handleGit = gitViewRoutes(git) const handleBrowser = browserRoutes(browser) const chats = chatRoutes(turns, { withRoleForChat: library.withRoleForChat }) @@ -70,19 +80,21 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi const deliveries = deliveryRoutes({ turns, files: library.deliveryFiles }) function beginShutdown() { lifetime.abort(); attachments.close() + if (!closingTasks) { closingTasks = tasks.close(); void closingTasks.catch(() => {}) } if (git && !closingGit) { closingGit = git.close(); void closingGit.catch(() => {}) } if (browser && !closingBrowser) { closingBrowser = Promise.resolve(browser.close()); void closingBrowser.catch(() => {}) } } return { beginShutdown, capabilities: Object.freeze({ textChat: true, library: true, workspaceFiles: library.workspaceFilesEnabled, attachments: true, - browserPanel: !!browser, gitInspect: !!git, deliveries: typeof turns.deliverySnapshot === 'function', + browserPanel: !!browser, gitInspect: !!git, taskInspection: Boolean(tasks), deliveries: typeof turns.deliverySnapshot === 'function', sessionWorkspaces: typeof turns.getWorkspace === 'function' && typeof turns.setWorkspace === 'function', sessionPreferences: typeof turns.patchPreferences === 'function' && typeof journal.watchSessions === 'function' }), createRealtime: ({ auth, policy }) => createChatWebSocket({ turns, journal, auth, policy }), getConfig: () => settings.getPublicConfig(), async handle(req, res, { auth, policy }) { const path = (req.url ?? '').split('?', 1)[0] + if ((path === '/api/v1/tasks' || path.startsWith('/api/v1/tasks/')) && await tasks.handle(req, res, { auth, policy })) return true if (path.startsWith('/api/v1/workspaces/') && path.includes('/git/') && await handleGit(req, res, { auth, policy })) return true if (path.includes('/browser') && await handleBrowser(req, res, { auth, policy })) return true if (path === '/api/v1/chats' || path.startsWith('/api/v1/chats/')) { @@ -135,7 +147,7 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi try { await turns.close() } finally { journal.close() try { - const results = await Promise.allSettled([closingBrowser, closingGit]) + const results = await Promise.allSettled([closingBrowser, closingGit, closingTasks]) if (results.some(row => row.status === 'rejected')) throw Error('Optional service shutdown unconfirmed') } finally { try { await uploads.close() } finally { await library.close() } } } diff --git a/apps/headless/src/http/session-routes.mjs b/apps/headless/src/http/session-routes.mjs index be385a1d..514c6a97 100644 --- a/apps/headless/src/http/session-routes.mjs +++ b/apps/headless/src/http/session-routes.mjs @@ -51,7 +51,8 @@ export function sessionRoutes({ auth, policy, version, getConfig, capabilities } workspaceFiles: capabilities?.workspaceFiles === true, attachments: capabilities?.attachments === true, browserPanel: capabilities?.browserPanel === true, sessionPreferences: capabilities?.sessionPreferences === true, deliveries: capabilities?.deliveries === true, gitInspect: capabilities?.gitInspect === true, - sessionWorkspaces: capabilities?.sessionWorkspaces === true } }) + sessionWorkspaces: capabilities?.sessionWorkspaces === true, + taskInspection: capabilities?.taskInspection === true } }) return true } if (path === '/api/v1/auth/logout') { diff --git a/apps/headless/src/tasks/routes.mjs b/apps/headless/src/tasks/routes.mjs new file mode 100644 index 00000000..26d6420b --- /dev/null +++ b/apps/headless/src/tasks/routes.mjs @@ -0,0 +1,89 @@ +import { HttpError, json, readJson } from '../http/policy.mjs' + +const collection = '/api/v1/tasks' +const item = /^\/api\/v1\/tasks\/([A-Za-z0-9][A-Za-z0-9_-]{0,127})(\/status)?$/u +const failureStatus = new Map([ + ['preview_busy', 429], ['preview_timeout', 503], ['preview_closed', 503], + ['preview_aborted', 409], ['preview_unavailable', 503] +]) + +/** Exact owner operations only. There is deliberately no dispatcher for running, resuming, + * creating or deleting a desktop agent task. Preview computes a date, not an execution. */ +export function taskRoutes({ store, preview }) { + const lifetime = new AbortController(), live = new Set() + let closed = false, drain + + async function serve(req, res, {auth, policy}, path, operation, id, permitted) { + const changing = permitted !== 'GET', cancel = new AbortController() + const signal = AbortSignal.any([lifetime.signal, cancel.signal]) + const disconnect = () => { if (!res.writableEnded) cancel.abort() } + res.once('close', disconnect) + try { + // Validate the method's origin, even when the caller intentionally chose a wrong method. + policy.check(req, req.method !== 'GET' && req.method !== 'HEAD') + const cookie = policy.cookie(req) + let actor + const verify = () => { + if (signal.aborted || closed || res.destroyed) throw new HttpError(503, 'task_closed') + const current = changing ? auth.identify(cookie, req.headers['x-deva-csrf']) : auth.identify(cookie) + if (!current || current.role !== 'owner' || (actor && (current.ownerId !== actor.ownerId || current.loginSessionId !== actor.loginSessionId))) { + throw new HttpError(401, 'auth') + } + actor ??= current + return actor + } + if (req.url !== path) throw new HttpError(400, 'unexpected_query') + if (req.method !== permitted) { json(res,405,{error:'method'},{allow:permitted});return } + verify() + let result + if (operation === 'list') result = await store.list() + else if (operation === 'get') result = await store.get(id) + else if (operation === 'preview') { + const body = await readJson(req, 2048) + verify() + result = await preview.preview(body, signal) + } else { + const body = await readJson(req, 512) + if (Object.keys(body).length !== 2 || !Object.hasOwn(body,'revision') || !Object.hasOwn(body,'status') || + body.status !== 'paused' || typeof body.revision !== 'string' || body.revision.length !== 64 || /[^0-9a-f]/u.test(body.revision)) { + throw new HttpError(400, 'invalid_task_pause') + } + verify() + result = await store.pause(id, body.revision, verify) + } + verify() // A slow disk/preview response must not deliver private data to a revoked login. + json(res,200,result) + } catch (error) { + const known = error instanceof HttpError, previewFailure = failureStatus.get(error?.code) + const status = known ? error.status : error?.code === 'AUTH_FAILED' ? 401 : previewFailure ?? 500 + const code = known || previewFailure ? error.code : status === 401 ? 'auth' : 'internal' + if (!res.headersSent && !res.destroyed) json(res,status,{error:code},changing ? {connection:'close'} : {}) + } finally { res.off('close',disconnect) } + } + return { + async handle(req, res, ctx) { + const path = (req.url ?? '').split('?',1)[0] + const matched = item.exec(path) + // Native app records may use the literal ID "preview"; GET still inspects that + // record, whereas an explicit POST to this exact resource previews a schedule. + const op = path === collection ? 'list' : path === `${collection}/preview` && req.method === 'POST' ? 'preview' + : matched ? matched[2] ? 'pause' : 'get' : null + if (!op) return false + const permitted = op === 'preview' ? 'POST' : op === 'pause' ? 'PATCH' : 'GET' + if (closed || live.size >= 8) { json(res,closed?503:429,{error:closed?'task_closed':'task_busy'},{connection:'close'}); return true } + const request = serve(req,res,ctx,path,op,matched?.[1],permitted) + live.add(request) + try { await request } finally { live.delete(request) } + return true + }, + close() { + if (!drain) { + closed=true;lifetime.abort() + drain = (async () => { + try { await Promise.all([preview.close(), ...live]) } finally { await store.close?.() } + })() + } + return drain + } + } +} diff --git a/apps/headless/test/task-inspection-http.test.mjs b/apps/headless/test/task-inspection-http.test.mjs new file mode 100644 index 00000000..c2333180 --- /dev/null +++ b/apps/headless/test/task-inspection-http.test.mjs @@ -0,0 +1,88 @@ +import assert from 'node:assert/strict' +import { createHash, randomBytes } from 'node:crypto' +import { chmod, lstat, mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import test from 'node:test' +import { requestControl } from '../src/control/socket.mjs' +import { startWorkbench } from '../src/server.mjs' +import { initializeMasterKey } from '../src/storage/vault.mjs' + +const limits={timeout:40_000} +const id='d724414e-05e0-4e96-9088-ca198e3072b3', other='42fa2490-808b-4660-ae2b-48951765c016' +const instant=Date.UTC(2026,0,15,9), secretMarker='synthetic-hidden-field-v1' +const hash=b=>createHash('sha256').update(b).digest('hex') +function record(id,status,title,prompt) { + return {id,title,prompt,status,schedule:status==='active'?{kind:'recurring',cron:'17 13 * * *',tz:'UTC'}:{kind:'once',at:'2026-01-15T09:00',tz:'UTC'}, + auth:{personaId:null,modelRef:null,extension:secretMarker},sessionId:'task-'+id,createdAt:instant-86400_000,updatedAt:instant, + lastRunAt:instant,nextRunAt:status==='active'?instant+86400_000:null,consecutiveErrors:0, + runs:[{status:'ok',firedAt:instant,finishedAt:instant+100,summary:'Recorded result, not a new run.'}],extraNativeTag:secretMarker} +} +async function fixture(t) { + const base=await realpath(tmpdir()),root=await mkdtemp(join(base,'deva-task-api-')),original=await lstat(root) + const dataDir=join(root,'data'),keyFile=join(root,'keys','master.key'),runDir=join(root,'run'),file=join(dataDir,'tasks.json') + const options={dataDir,keyFile,runDir,webDir:join(root,'web'),port:0} + let app, a,b + t.after(async()=>{try{await app?.close()}finally{ + const st=await lstat(root);assert.equal(dirname(root),base);assert.equal(await realpath(root),root);assert.equal(st.dev,original.dev);assert.equal(st.ino,original.ino);await rm(root,{recursive:true,force:false}) + }}) + await mkdir(dataDir,{mode:0o700});await mkdir(dirname(keyFile),{mode:0o700});await initializeMasterKey(keyFile) + const data={version:1,extraAppField:secretMarker,tasks:[record(id,'active','Editorial check','Read literally.'),record(other,'completed','Index pass','Unrelated instruction.')]} + await writeFile(file,JSON.stringify(data,null,2)+'\n',{mode:0o600,flag:'wx'}) + app=await startWorkbench(options) + const password=randomBytes(24).toString('base64url') + async function req(path,method='GET',body,login=a,headers={}) { + const r=await fetch(app.origin+'/api/v1/'+path,{method,headers:{...(login?{cookie:login.cookie}:{}), + ...(body===undefined?{}:{origin:app.origin,'content-type':'application/json',...(login?{'x-deva-csrf':login.csrf}:{})}),...headers}, + ...(body===undefined?{}:{body:JSON.stringify(body)}),signal:AbortSignal.timeout(6500)}) + return {status:r.status,value:await r.json(),cookie:r.headers.get('set-cookie')?.split(';')[0],cache:r.headers.get('cache-control')} + } + const signin=async(path,input)=>{const r=await req(path,'POST',input,null);assert.equal(r.status,200);return {cookie:r.cookie,csrf:r.value.csrf}} + const {credential}=await requestControl({runDir,op:'claim'});a=await signin('auth/claim',{credential,password});b=await signin('auth/login',{password}) + async function ok(path,method,body,login){const r=await req(path,method,body,login);assert.equal(r.status,200,r.value?.error);assert.equal(r.cache,'no-store');return r.value} + const state=async()=>({main:await readFile(file),stat:await lstat(file,{bigint:true})}) + const restart=async()=>{await app.close();app=await startWorkbench(options);assert.equal((await req('tasks','GET',undefined,a)).status,401);a=await signin('auth/login',{password})} + return {req,ok,a,b,state,root,data,file,restart} +} + +test('human reads and previews leave the desktop task store and agent sessions unchanged', limits, async t=>{ + const f=await fixture(t), before=await f.state();assert.equal((await f.ok('bootstrap')).capabilities.taskInspection,true) + assert.equal((await f.req('tasks','GET',undefined,null)).status,401) + assert.equal((await f.req('tasks?x=1')).status,400) + const list=await f.ok('tasks');assert.equal(list.execution,'inactive');assert.equal(list.revision,hash(before.main));assert.equal(list.tasks.length,2) + assert.ok(list.tasks.some(x=>x.id===id && x.status==='active' && x.runCount===1));assert.ok(!JSON.stringify(list).includes(secretMarker)) + for(const item of list.tasks)for(const k of ['prompt','auth','runs','sessionId'])assert.equal(Object.hasOwn(item,k),false,k) + const detail=await f.ok('tasks/'+id);assert.equal(detail.task.prompt,'Read literally.');assert.equal(detail.task.pauseAllowed,true) + assert.equal(detail.task.runs[0].summary,f.data.tasks[0].runs[0].summary);assert.ok(!JSON.stringify(detail).includes(secretMarker)) + assert.deepEqual(detail.task.auth,{personaId:null,modelRef:null}) + const preview={schedule:{kind:'once',at:'2088-05-12T08:15',tz:'Asia/Shanghai'},locale:'en',allowPast:false} + const answer=await f.ok('tasks/preview','POST',preview);assert.equal(answer.ok,true);assert.equal(answer.nextRunAt,Date.UTC(2088,4,12,0,15));assert.ok(answer.description.length) + assert.deepEqual(await f.ok('tasks/preview','POST',{...preview,schedule:{kind:'once',at:'2020-01-01T00:00',tz:'UTC'}}),{ok:false,error:'invalid-once'}) + assert.equal((await f.req('tasks/preview','POST',preview,f.a,{'x-deva-csrf':'bad'})).status,401) + assert.equal((await f.req('tasks/preview','POST',preview,f.a,{origin:'https://other.invalid'})).status,403) + for(const action of ['run','resume','delete'])assert.equal((await f.req(`tasks/${id}/${action}`,'POST',{})).status,404) + assert.equal((await f.req('tasks','POST',{})).status,405) + assert.deepEqual((await f.ok('chats')).sessions,[]) + const after=await f.state();assert.deepEqual(after.main,before.main);assert.equal(after.stat.mtimeNs,before.stat.mtimeNs) +}) + +test('only confirmed native pause is writable, survives recreation and rejects stale or foreign intents', limits, async t=>{ + const f=await fixture(t), initial=await f.ok('tasks'), path=`tasks/${id}/status`, pause={status:'paused',revision:initial.revision} + for(const status of ['active','completed','error','run'])assert.equal((await f.req(path,'PATCH',{...pause,status})).status,400) + assert.equal((await f.req(path,'PATCH',{...pause,cmd:'unexpected'})).status,400) + assert.equal((await f.req(`tasks/${other}/status`,'PATCH',pause)).status,409) + assert.equal((await f.req(path,'PATCH',pause,f.a,{'x-deva-csrf':'invalid'})).status,401) + assert.equal((await f.req(path,'PATCH',pause,f.a,{origin:'https://other.invalid'})).status,403) + const confirm=await f.ok(path,'PATCH',pause);assert.equal(confirm.task.status,'paused');assert.notEqual(confirm.revision,initial.revision) + assert.equal(confirm.task.nextRunAt,f.data.tasks[0].nextRunAt);assert.equal(confirm.task.pauseAllowed,false) + const old=await f.req(path,'PATCH',pause,f.b);assert.equal(old.status,409);assert.equal(old.value.error,'task_conflict') + const bytes=await readFile(f.file), saved=JSON.parse(bytes);assert.equal(confirm.revision,hash(bytes)) + const expected=structuredClone(f.data);expected.tasks[0].status='paused';expected.tasks[0].updatedAt=saved.tasks[0].updatedAt + assert.deepEqual(saved,expected);assert.ok(saved.tasks[0].updatedAt>f.data.tasks[0].updatedAt) + const oldstat=await lstat(f.file,{bigint:true});await f.ok(path,'PATCH',{...pause,revision:confirm.revision});assert.equal((await lstat(f.file,{bigint:true})).mtimeNs,oldstat.mtimeNs) + await f.restart();assert.equal((await f.ok('tasks/'+id)).task.status,'paused');assert.deepEqual((await f.ok('chats')).sessions,[]) + // A bad native task file is a truthful error from this view, not a blank task dashboard. + await writeFile(f.file,'{"version":1,"tasks": [');await chmod(f.file,0o600) + const corrupted=await f.req('tasks');assert.ok([409,503].includes(corrupted.status));assert.equal('tasks' in corrupted.value,false) + assert.equal((await f.ok('bootstrap')).capabilities.textChat,true) +}) From d49e6e6a595c8b228bc61016018e2e29c976c6e7 Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Thu, 26 Nov 2026 20:43:34 +0800 Subject: [PATCH 05/12] =?UTF-8?q?feat(workbench):=20=E6=8E=A5=E5=85=A5?= =?UTF-8?q?=E6=A1=8C=E9=9D=A2=E4=BB=BB=E5=8A=A1=E8=A7=86=E5=9B=BE=E4=B8=8E?= =?UTF-8?q?=E6=98=BE=E5=BC=8F=E6=9A=82=E5=81=9C=20/=20add=20the=20desktop?= =?UTF-8?q?=20task=20view=20and=20confirmed=20pause=20to=20the=20workbench?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../workbench/task-inspection-controller.ts | 171 ++++++++++ .../src/workbench/task-inspection-copy.ts | 52 +++ .../src/workbench/task-inspection-time.ts | 26 ++ .../workbench/task-inspection-transport.ts | 117 +++++++ .../src/workbench/task-inspection-ui.tsx | 173 ++++++++++ .../desktop/src/workbench/task-inspection.css | 67 ++++ apps/desktop/src/workbench/text-workbench.tsx | 38 ++- apps/desktop/src/workbench/transport.ts | 3 +- scripts/workbench/task-inspection-ui.test.mjs | 313 ++++++++++++++++++ 9 files changed, 951 insertions(+), 9 deletions(-) create mode 100644 apps/desktop/src/workbench/task-inspection-controller.ts create mode 100644 apps/desktop/src/workbench/task-inspection-copy.ts create mode 100644 apps/desktop/src/workbench/task-inspection-time.ts create mode 100644 apps/desktop/src/workbench/task-inspection-transport.ts create mode 100644 apps/desktop/src/workbench/task-inspection-ui.tsx create mode 100644 apps/desktop/src/workbench/task-inspection.css create mode 100644 scripts/workbench/task-inspection-ui.test.mjs diff --git a/apps/desktop/src/workbench/task-inspection-controller.ts b/apps/desktop/src/workbench/task-inspection-controller.ts new file mode 100644 index 00000000..b1724fb8 --- /dev/null +++ b/apps/desktop/src/workbench/task-inspection-controller.ts @@ -0,0 +1,171 @@ +import type { PreviewScheduleResult } from '../shared/host-conversations' +import { HttpFailure } from './transport' +import { InvalidTaskReceipt, type PreviewInput, type TaskDetail, type TaskInspectionTransport, type TaskList } from './task-inspection-transport' + +export type TaskIssue = 'malformed' | 'unsupported' | 'unconfirmed' | 'forbidden' | 'missing' | 'limit' | 'busy' | + 'conflict' | 'stateChanged' | 'invalidPreview' | 'listFailed' | 'detailFailed' | 'previewFailed' | 'pauseUnconfirmed' +type Read = { pending: true } | { data: T } | { issue: TaskIssue } +type SuccessfulPreview = Extract & { zone: string } +type PreviewRead = Read | { validation: Extract['error'] } +export type TaskInspectionView = { + open: boolean; list?: Read; selected?: string; detail?: Read + preview?: PreviewRead; confirming?: boolean; pausing?: boolean; statusIssue?: TaskIssue +} +const closed: TaskInspectionView = { open: false } +type Lane = 'list' | 'detail' | 'preview' | 'pause' + +function issueOf(error: unknown, fallback: TaskIssue): TaskIssue { + if (error instanceof InvalidTaskReceipt && fallback !== 'pauseUnconfirmed') return 'malformed' + if (error instanceof HttpFailure) { + if (error.code === 'task_file_unsupported') return 'unsupported' + if (error.code === 'task_storage_unconfirmed') return 'unconfirmed' + if (error.code === 'task_state') return 'stateChanged' + if (error.status === 409 && fallback === 'pauseUnconfirmed') return 'conflict' + if (error.status === 403) return 'forbidden' + if (error.status === 404 && (fallback === 'detailFailed' || fallback === 'pauseUnconfirmed')) return 'missing' + if (error.status === 413) return 'limit' + if (error.status === 429) return 'busy' + if (error.status === 400 && fallback === 'previewFailed') return 'invalidPreview' + } + return fallback +} + +export function createTaskInspection(api: TaskInspectionTransport, { expired, beforePause }: { + expired: () => void; beforePause: () => Promise +}) { + let view = closed + let pauseSent = false + const requests: Partial> = {} + const listeners = new Set<() => void>() + const set = (next: TaskInspectionView): void => { view = next; listeners.forEach((fn) => fn()) } + const update = (patch: Partial): void => set({ ...view, ...patch }) + function abort(lane: Lane): void { + requests[lane]?.abort() + delete requests[lane] + } + function start(lane: Lane): AbortController { + abort(lane) + return requests[lane] = new AbortController() + } + function live(lane: Lane, request: AbortController): boolean { + return view.open && requests[lane] === request && !request.signal.aborted + } + function finish(lane: Lane, request: AbortController): boolean { + if (!live(lane, request)) return false + delete requests[lane] + return true + } + function close(): void { + for (const lane of ['list', 'detail', 'preview', 'pause'] as const) abort(lane) + pauseSent = false + if (view.open) set(closed) + } + function failed(lane: Lane, request: AbortController, error: unknown, fallback: TaskIssue): TaskIssue | undefined { + if (!finish(lane, request)) return undefined + if (error instanceof HttpFailure && error.status === 401) { + close() + expired() + return undefined + } + return issueOf(error, fallback) + } + + async function readDetail(id: string): Promise { + const request = start('detail') + update({ detail: { pending: true } }) + try { + const data = await api.detail(id, request.signal) + if (finish('detail', request)) update({ detail: { data } }) + } catch (error) { + const issue = failed('detail', request, error, 'detailFailed') + if (issue) update({ detail: { issue } }) + } + } + async function refresh(): Promise { + if (!view.open || view.pausing) return + const request = start('list') + abort('detail') + update({ list: { pending: true }, detail: undefined, confirming: false, statusIssue: undefined }) + try { + const data = await api.list(request.signal) + if (!finish('list', request)) return + const selected = data.tasks.some(({ id }) => id === view.selected) ? view.selected : undefined + if (!selected && view.selected) clearPreview() + update({ list: { data }, selected }) + if (selected) await readDetail(selected) + } catch (error) { + const issue = failed('list', request, error, 'listFailed') + if (issue) update({ list: { issue } }) + } + } + async function open(): Promise { + if (view.open) return + set({ open: true }) + await refresh() + } + async function select(id: string): Promise { + if (!view.open || id === view.selected || !view.list || !('data' in view.list) || !view.list.data.tasks.some((task) => task.id === id)) return + const uncertain = view.pausing && pauseSent + abort('pause') + pauseSent = false + abort('preview') + update({ selected: id, detail: undefined, preview: undefined, confirming: false, pausing: false, + ...(uncertain && { statusIssue: 'pauseUnconfirmed' }) }) + await readDetail(id) + } + function clearPreview(): void { + abort('preview') + if (view.preview) update({ preview: undefined }) + } + async function preview(input: PreviewInput): Promise { + if (!view.open) return + const request = start('preview') + update({ preview: { pending: true } }) + try { + const result = await api.preview(input, request.signal) + if (finish('preview', request)) update({ preview: result.ok ? { data: { ...result, zone: input.schedule.tz } } : { validation: result.error } }) + } catch (error) { + const issue = failed('preview', request, error, 'previewFailed') + if (issue) update({ preview: { issue } }) + } + } + + function canPause(): TaskDetail | undefined { + if (!view.open || view.pausing || view.statusIssue || !view.detail || !('data' in view.detail)) return undefined + const detail = view.detail.data + return detail.task.pauseAllowed && detail.task.status === 'active' ? detail : undefined + } + function askPause(): void { if (canPause()) update({ confirming: true }) } + function cancelPause(): void { if (view.confirming) update({ confirming: false }) } + async function confirmPause(): Promise { + const current = view.confirming ? canPause() : undefined + if (!current) return + const request = start('pause') + update({ confirming: false, pausing: true }) + try { + await beforePause() + if (!live('pause', request)) return + pauseSent = true + await api.pause(current.task.id, current.revision, request.signal) + if (finish('pause', request)) { + pauseSent = false + update({ pausing: false, detail: undefined }) + await refresh() + } + } catch (error) { + const issue = failed('pause', request, error, 'pauseUnconfirmed') + if (issue) { + pauseSent = false + update({ pausing: false, statusIssue: issue }) + } + } + } + return { snapshot: () => view, subscribe: (fn: () => void) => { + listeners.add(fn) + return () => { listeners.delete(fn) } + }, open, close, refresh, select, preview, clearPreview, askPause, cancelPause, confirmPause } +} + +export type TaskInspection = ReturnType +export const closedTaskSnapshot = (): TaskInspectionView => closed +export const idleTaskSubscription = (): (() => void) => () => {} diff --git a/apps/desktop/src/workbench/task-inspection-copy.ts b/apps/desktop/src/workbench/task-inspection-copy.ts new file mode 100644 index 00000000..8fdba38a --- /dev/null +++ b/apps/desktop/src/workbench/task-inspection-copy.ts @@ -0,0 +1,52 @@ +export const taskInspectionCopy = { + en: { + inactive: 'Server execution inactive; these are recorded desktop schedules.', refresh: 'Refresh', close: 'Close tasks', list: 'Recorded tasks', + empty: 'No recorded desktop tasks.', choose: 'Select a task to inspect its saved details.', detail: 'Recorded task details', + listLoading: 'Reading recorded tasks…', detailLoading: 'Reading task details…', malformed: 'The server returned an invalid task receipt. Refresh to try again.', + unsupported: 'The saved task file is unsupported or corrupt. Refresh after the file has been repaired.', + unconfirmed: 'The task store could not confirm its current state. Refresh and review the saved record.', + forbidden: 'The server denied access to this task operation.', missing: 'This task is no longer available. Refresh the list.', + limit: 'The saved task data exceeds the inspection limit.', busy: 'The task service is busy. Try again manually.', + conflict: 'The saved task revision changed. Refresh and review the current state before confirming again.', + stateChanged: 'The saved task state changed and cannot be paused. Refresh to see the current state.', + listFailed: 'Could not read the recorded task list. Refresh to try again.', detailFailed: 'Could not read the task detail. Refresh to try again.', + previewFailed: 'Could not calculate the schedule preview. Try Preview again.', invalidPreview: 'The preview request is invalid. Check the schedule fields.', + pauseUnconfirmed: 'Pause was not confirmed. Refresh and review the saved state before another change.', + created: 'Saved creation time', updated: 'Saved update time', last: 'Saved last-run time', next: 'Saved next-run time', + timezone: 'IANA time zone', zoneUnknown: 'recorded zone unavailable in this browser', absent: 'Not recorded', runCount: 'Recorded run count', + consecutiveErrors: 'Consecutive errors', session: 'Task session ID', ownerSession: 'Owner session ID', originSession: 'Origin session ID', + prompt: 'Saved task instructions', finished: 'Finished', handoff: 'Recorded handoff', needsAction: 'Follow-up recorded', + pause: 'Pause saved task', pauseTitle: 'Confirm pause', pauseMessage: 'Change the saved status to paused? This changes the desktop record only.', + pausedLoading: 'Saving pause…', cancel: 'Cancel', confirm: 'Confirm pause', + previewTitle: 'Schedule preview', previewHint: 'Calculate an example schedule. Preview neither saves a task nor activates execution.', + scheduleFields: 'Schedule fields', allowPast: 'Allow past one-time dates', preview: 'Preview', previewing: 'Calculating preview…', + predicted: 'Calculated next occurrence', noNext: 'No future occurrence', + 'invalid-input': 'Enter a valid schedule.', 'invalid-tz': 'Enter a valid IANA time zone, such as America/New_York or UTC.', + 'invalid-cron': 'Enter a valid recurring schedule or cron expression.', 'invalid-once': 'Enter a valid one-time date and time, or allow past dates.' + }, + 'zh-CN': { + inactive: '服务器未启用任务执行;此处展示桌面端记录的日程。', refresh: '刷新', close: '关闭任务面板', list: '已记录的任务', + empty: '没有桌面端任务记录。', choose: '选择任务以查看已保存的详情。', detail: '任务记录详情', + listLoading: '正在读取任务记录…', detailLoading: '正在读取任务详情…', malformed: '服务器返回的任务数据格式有误。请刷新重试。', + unsupported: '已保存的任务文件损坏或格式暂未兼容。修复后请刷新。', + unconfirmed: '任务存储未确认当前状态。请刷新并核对已保存的记录。', + forbidden: '服务器未授权此任务操作。', missing: '该任务已不可用。请刷新列表。', + limit: '已保存的任务数据超过查看上限。', busy: '任务服务繁忙。请手动重试。', + conflict: '任务记录版本已变更。请刷新并核对当前状态,再次确认。', + stateChanged: '任务状态已变更,当前状态无法暂停。请刷新查看最新状态。', + listFailed: '读取任务列表失败。请刷新重试。', detailFailed: '读取任务详情失败。请刷新重试。', + previewFailed: '日程预览计算失败。请再次点击预览。', invalidPreview: '预览请求无效,请检查日程字段。', + pauseUnconfirmed: '暂停未获确认。请刷新并核对已保存的状态,再进行修改。', + created: '记录创建时间', updated: '记录更新时间', last: '保存的上次运行时间', next: '保存的下次运行时间', + timezone: 'IANA 时区', zoneUnknown: '当前浏览器无法识别记录的时区', absent: '未记录', runCount: '已记录的运行次数', + consecutiveErrors: '连续错误次数', session: '任务会话 ID', ownerSession: '所属会话 ID', originSession: '来源会话 ID', + prompt: '已保存的任务指令', finished: '结束', handoff: '交接记录', needsAction: '记录需后续处理', + pause: '暂停已保存的任务', pauseTitle: '确认暂停', pauseMessage: '将保存的状态改为已暂停?这只会修改桌面端记录。', + pausedLoading: '正在保存暂停状态…', cancel: '取消', confirm: '确认暂停', + previewTitle: '日程预览', previewHint: '计算示例日程。预览仅计算时间,既无需创建任务,也无需启动执行。', + scheduleFields: '日程字段', allowPast: '允许已过去的一次性日期', preview: '预览', previewing: '正在计算预览…', + predicted: '计算出的下次时间', noNext: '没有未来日期', + 'invalid-input': '请输入有效日程。', 'invalid-tz': '请输入有效的 IANA 时区,例如 Asia/Shanghai 或 UTC。', + 'invalid-cron': '请输入有效的周期日程或 cron 表达式。', 'invalid-once': '请输入有效的一次性日期和时间,或勾选允许过去日期。' + } +} diff --git a/apps/desktop/src/workbench/task-inspection-time.ts b/apps/desktop/src/workbench/task-inspection-time.ts new file mode 100644 index 00000000..82241065 --- /dev/null +++ b/apps/desktop/src/workbench/task-inspection-time.ts @@ -0,0 +1,26 @@ +import type { TaskSchedule } from '../shared/host-conversations' +import type { RecordedSchedule, TaskLocale } from './task-inspection-transport' + +export function formatTaskInstant(ts: number, zone: string, locale: TaskLocale): string | undefined { + try { + const date = new Intl.DateTimeFormat(locale === 'en' ? 'en-US' : locale, { + timeZone: zone, timeZoneName: 'short', year: 'numeric', month: 'short', day: 'numeric', + hour: '2-digit', minute: '2-digit', second: '2-digit' + }).format(ts) + return `${date} [${zone}]` + } catch { return undefined } +} + +export function recordedScheduleText(schedule: RecordedSchedule): string { + // A Desktop once value is already a wall-clock time in its own zone. Parsing it + // with the browser's Date constructor would shift it to the browser's zone. + return `${schedule.kind === 'once' ? schedule.at.replace('T', ' ') : schedule.cron} [${schedule.tz}]` +} + +export function defaultPreviewSchedule(zone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC', now = Date.now()): TaskSchedule { + const parts = new Intl.DateTimeFormat('en-CA', { + timeZone: zone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' + }).formatToParts(now + 3_600_000) + const field = (key: Intl.DateTimeFormatPartTypes): string => parts.find((item) => item.type === key)!.value + return { kind: 'recurring', cron: '0 10 * * *', at: `${field('year')}-${field('month')}-${field('day')}T${field('hour')}:${field('minute')}`, tz: zone } +} diff --git a/apps/desktop/src/workbench/task-inspection-transport.ts b/apps/desktop/src/workbench/task-inspection-transport.ts new file mode 100644 index 00000000..11d8ada1 --- /dev/null +++ b/apps/desktop/src/workbench/task-inspection-transport.ts @@ -0,0 +1,117 @@ +import type { PreviewScheduleResult, TaskAuthorization, TaskRun, TaskSchedule, TaskStatus } from '../shared/host-conversations' +import type { Transport } from './transport' + +export type TaskLocale = 'en' | 'zh-CN' +export type RecordedSchedule = { kind: 'once'; at: string; tz: string } | { kind: 'recurring'; cron: string; tz: string } +export type TaskSummary = { + id: string; title: string; status: TaskStatus; schedule: RecordedSchedule + createdAt: number; updatedAt: number; lastRunAt: number | null; nextRunAt: number | null; runCount: number +} +export type InspectedTask = TaskSummary & { + prompt: string; auth: TaskAuthorization; sessionId: string; ownerSessionId: string | null; originSessionId: string | null + consecutiveErrors: number; runs: TaskRun[]; pauseAllowed: boolean +} +export type TaskList = { tasks: TaskSummary[]; revision: string; execution: 'inactive' } +export type TaskDetail = { task: InspectedTask; revision: string; execution: 'inactive' } +export type PreviewInput = { schedule: TaskSchedule; locale: TaskLocale; allowPast: boolean } + +const statuses = ['active', 'paused', 'completed', 'error'] as const +const runStatuses = ['ok', 'error', 'skipped', 'aborted'] as const +const previewErrors = ['invalid-input', 'invalid-tz', 'invalid-cron', 'invalid-once'] as const +const text = (x: unknown): x is string => typeof x === 'string' +const nullableText = (x: unknown): x is string | null => x === null || text(x) +const instant = (x: unknown): x is number => typeof x === 'number' && Number.isSafeInteger(x) && Math.abs(x) <= 8_640_000_000_000_000 +const nullableInstant = (x: unknown): x is number | null => x === null || instant(x) +const count = (x: unknown): x is number => typeof x === 'number' && Number.isSafeInteger(x) && x >= 0 +const isOneOf = (values: readonly T[], x: unknown): x is T => values.some((value) => value === x) +const taskId = (x: unknown): x is string => text(x) && /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u.exec(x)?.[0] === x +const revision = (x: unknown): x is string => text(x) && /^[a-f0-9]{64}$/u.exec(x)?.[0] === x +const record = (x: unknown): x is Record => typeof x === 'object' && x !== null && !Array.isArray(x) +export class InvalidTaskReceipt extends Error { + constructor() { super('Invalid task inspection receipt') } +} +const invalid = (): never => { throw new InvalidTaskReceipt() } + +function schedule(x: unknown): RecordedSchedule { + if (record(x) && text(x.tz)) { + if (x.kind === 'once' && text(x.at)) return { kind: 'once', at: x.at, tz: x.tz } + if (x.kind === 'recurring' && text(x.cron)) return { kind: 'recurring', cron: x.cron, tz: x.tz } + } + return invalid() +} + +function summary(x: unknown): TaskSummary { + if (!record(x)) return invalid() + const { id, title, status, createdAt, updatedAt, lastRunAt, nextRunAt, runCount } = x + if (!taskId(id) || !text(title) || !isOneOf(statuses, status) || !instant(createdAt) || !instant(updatedAt) || + !nullableInstant(lastRunAt) || !nullableInstant(nextRunAt) || !count(runCount)) return invalid() + return { id, title, status, schedule: schedule(x.schedule), createdAt, updatedAt, lastRunAt, nextRunAt, runCount } +} + +function run(x: unknown): TaskRun { + if (!record(x)) return invalid() + const { firedAt, finishedAt, status, summary, error, handoff } = x + if (!instant(firedAt) || !isOneOf(runStatuses, status) || (finishedAt !== undefined && !instant(finishedAt)) || + (summary !== undefined && !text(summary)) || (error !== undefined && !text(error))) return invalid() + const result: TaskRun = { firedAt, status, ...(finishedAt !== undefined && { finishedAt }), + ...(summary !== undefined && { summary }), ...(error !== undefined && { error }) } + if (handoff !== undefined) { + if (!record(handoff) || !text(handoff.summary) || typeof handoff.needsAction !== 'boolean') return invalid() + result.handoff = { summary: handoff.summary, needsAction: handoff.needsAction } + } + return result +} + +function detail(x: unknown, id: string): InspectedTask { + if (!record(x) || x.id !== id) return invalid() + const { prompt, auth, sessionId, ownerSessionId, originSessionId, consecutiveErrors, runs, pauseAllowed } = x + if (!text(prompt) || !record(auth) || !nullableText(auth.personaId) || !nullableText(auth.modelRef) || !text(sessionId) || + !nullableText(ownerSessionId) || !nullableText(originSessionId) || !count(consecutiveErrors) || !Array.isArray(runs) || + typeof pauseAllowed !== 'boolean') return invalid() + return { ...summary(x), prompt, auth: { personaId: auth.personaId, modelRef: auth.modelRef }, sessionId, ownerSessionId, + originSessionId, consecutiveErrors, runs: runs.map(run), pauseAllowed } +} + +function receipt(x: unknown): { raw: Record; revision: string; execution: 'inactive' } { + if (!record(x) || x.execution !== 'inactive' || !revision(x.revision)) return invalid() + return { raw: x, revision: x.revision, execution: x.execution } +} + +export function createTaskInspectionTransport(transport: Transport, csrf: string) { + const path = (id: string): string => taskId(id) ? `/tasks/${encodeURIComponent(id)}` : invalid() + const write = (route: string, method: 'POST' | 'PATCH', body: object, signal: AbortSignal): Promise => { + if (!csrf) return invalid() + // A same-origin referrer policy lets Fetch supply the real Origin on writes. + return transport.request(route, method, body, csrf, { signal, referrerPolicy: 'same-origin' }) + } + return { + async list(signal: AbortSignal): Promise { + const { raw, ...meta } = receipt(await transport.request('/tasks', 'GET', undefined, undefined, { signal })) + if (!Array.isArray(raw.tasks)) return invalid() + const tasks = raw.tasks.map(summary) + if (new Set(tasks.map((task) => task.id)).size !== tasks.length) return invalid() + return { ...meta, tasks } + }, + async detail(id: string, signal: AbortSignal): Promise { + const { raw, ...meta } = receipt(await transport.request(path(id), 'GET', undefined, undefined, { signal })) + return { ...meta, task: detail(raw.task, id) } + }, + async preview(input: PreviewInput, signal: AbortSignal): Promise { + if ((input.locale !== 'en' && input.locale !== 'zh-CN') || typeof input.allowPast !== 'boolean') return invalid() + const x = await write('/tasks/preview', 'POST', { schedule: schedule(input.schedule), locale: input.locale, allowPast: input.allowPast }, signal) + if (record(x)) { + if (x.ok === true && text(x.description) && nullableInstant(x.nextRunAt)) return { ok: true, description: x.description, nextRunAt: x.nextRunAt } + if (x.ok === false && isOneOf(previewErrors, x.error)) return { ok: false, error: x.error } + } + return invalid() + }, + async pause(id: string, expected: string, signal: AbortSignal): Promise { + if (!revision(expected)) return invalid() + // Mutation responses are acknowledgments only; the controller re-reads list and detail. + const { raw } = receipt(await write(`${path(id)}/status`, 'PATCH', { revision: expected, status: 'paused' }, signal)) + if (detail(raw.task, id).status !== 'paused') return invalid() + } + } +} + +export type TaskInspectionTransport = ReturnType diff --git a/apps/desktop/src/workbench/task-inspection-ui.tsx b/apps/desktop/src/workbench/task-inspection-ui.tsx new file mode 100644 index 00000000..9fc487c2 --- /dev/null +++ b/apps/desktop/src/workbench/task-inspection-ui.tsx @@ -0,0 +1,173 @@ +import { useId, useLayoutEffect, useRef, useState, type ReactNode } from 'react' +import { Pause, RefreshCw, X } from 'lucide-react' +import { ScheduleEditor } from '../renderer/src/features/chat/ScheduleEditor' +import { useI18n } from '../renderer/src/i18n/i18n' +import { TASK_GROUP_KEY, TASK_GROUP_ORDER, TaskDetailHeading, TaskRailRow, TaskRunHistory, compareTaskRows } from '../renderer/src/redesign/TaskInspectionParts' +import type { TaskRun, TaskSchedule } from '../shared/host-conversations' +import type { TaskInspection, TaskInspectionView, TaskIssue } from './task-inspection-controller' +import { taskInspectionCopy } from './task-inspection-copy' +import { defaultPreviewSchedule, formatTaskInstant, recordedScheduleText } from './task-inspection-time' +import type { InspectedTask, TaskLocale } from './task-inspection-transport' +import './task-inspection.css' + +function TaskAlert({ issue }: { issue: TaskIssue }): React.JSX.Element { + const { locale } = useI18n() + return

{taskInspectionCopy[locale][issue]}

+} + +export function TaskInspectionPanel({ api, view, close, id }: { + api: TaskInspection; view: TaskInspectionView; close: () => void; id: string +}): React.JSX.Element { + const { t, locale } = useI18n() + const c = taskInspectionCopy[locale] + const closeButton = useRef(null) + const details = useRef(null) + const pauseButton = useRef(null) + const titleId = useId() + useLayoutEffect(() => { closeButton.current?.focus() }, []) + const list = view.list && 'data' in view.list ? view.list.data.tasks : undefined + const task = view.detail && 'data' in view.detail ? view.detail.data.task : undefined + const dismissConfirmation = (): void => { api.cancelPause(); pauseButton.current?.focus() } + return
{ + if (event.key !== 'Escape' || event.defaultPrevented) return + event.preventDefault() + if (view.confirming) dismissConfirmation() + else close() + }}> +
+

{t('cf.tabTasks')}

+ + +
+

{c.inactive}

+ {view.statusIssue && } +
+ +
+ {view.detail && 'pending' in view.detail &&

{c.detailLoading}

} + {view.detail && 'issue' in view.detail && } + {!!list?.length && !view.selected &&

{c.choose}

} + {task && + {task.pauseAllowed && task.status === 'active' &&
+ +
} + {view.confirming && { + details.current?.focus({ preventScroll: true }) + void api.confirmPause() + }} />} + {view.pausing &&

{c.pausedLoading}

} + } />} + +
+
+
+} + +function PauseConfirmation({ cancel, confirm }: { cancel: () => void; confirm: () => void }): React.JSX.Element { + const { locale } = useI18n() + const c = taskInspectionCopy[locale] + const titleId = useId() + const first = useRef(null) + useLayoutEffect(() => { first.current?.focus() }, []) + return
+

{c.pauseTitle}

{c.pauseMessage}

+
+ + +
+
+} + +function TaskTime({ value, zone, locale }: { value: number | null; zone: string; locale: TaskLocale }): React.JSX.Element { + const c = taskInspectionCopy[locale] + if (value === null) return <>{c.absent} + const iso = new Date(value).toISOString() + return +} + +function RecordedDetail({ task, actions }: { task: InspectedTask; actions: ReactNode }): React.JSX.Element { + const { t, locale } = useI18n() + const c = taskInspectionCopy[locale] + const zone = task.schedule.tz + const time = (value: number | null) => + const runText = (run: TaskRun) => (run.summary || run.error || run.finishedAt !== undefined || run.handoff) && +
+ {run.summary &&
{run.summary}
} + {run.error &&
{run.error}
} + {run.finishedAt !== undefined &&
{c.finished}: {time(run.finishedAt)}
} + {run.handoff &&
{c.handoff}: {run.handoff.summary}{run.handoff.needsAction && ` (${c.needsAction})`}
} +
+ return
+ +
+ {recordedScheduleText(task.schedule)} + {time(task.createdAt)}{time(task.updatedAt)} + {time(task.lastRunAt)}{time(task.nextRunAt)} + {task.runCount}{task.consecutiveErrors} + {task.auth.personaId ?? c.absent} + {task.auth.modelRef ?? c.absent} + {task.sessionId}{task.ownerSessionId ?? c.absent} + {task.originSessionId ?? c.absent} +
+
+

{c.prompt}

+
{task.prompt}
+
+ {actions} + +
+} + +function Meta({ label, children }: { label: string; children: ReactNode }): React.JSX.Element { + return
{label}
{children}
+} + +function TaskSchedulePreview({ api, view }: { api: TaskInspection; view: TaskInspectionView['preview'] }): React.JSX.Element { + const { locale } = useI18n() + const c = taskInspectionCopy[locale] + const [initial] = useState(defaultPreviewSchedule) + const [zone, setZone] = useState(initial.tz) + const [schedule, setSchedule] = useState(initial) + const [allowPast, setAllowPast] = useState(false) + const title = useId() + useLayoutEffect(() => { api.clearPreview() }, [api, locale]) + return
+

{c.previewTitle}

{c.previewHint}

+ +
{c.scheduleFields} + { api.clearPreview(); setSchedule(next) }} /> +
+ + + {view && 'pending' in view &&

{c.previewing}

} + {view && 'issue' in view && } + {view && 'validation' in view &&

{c[view.validation]}

} + {view && 'data' in view &&
+
{view.data.description}
+
{c.predicted}: {view.data.nextRunAt === null ? c.noNext : }
+
} +
+} diff --git a/apps/desktop/src/workbench/task-inspection.css b/apps/desktop/src/workbench/task-inspection.css new file mode 100644 index 00000000..cf9d2aba --- /dev/null +++ b/apps/desktop/src/workbench/task-inspection.css @@ -0,0 +1,67 @@ +.wb-tasks { + flex: 1; + min-height: 0; + min-width: 0; + display: flex; + flex-direction: column; + container-type: inline-size; + user-select: text; +} +.wb-tasks__toggle { flex: none; } +.wb-tasks__toggle[aria-expanded='true'] { background: var(--bg-hover); color: var(--fg); } +.wb-tasks__head { + display: flex; + align-items: center; + gap: var(--space-2); + padding: var(--space-3) var(--space-4) var(--space-2); +} +.wb-tasks__head h2 { margin: 0 auto 0 0; } +.wb-tasks__notice, .wb-tasks__alert { + margin: 0; + padding: var(--space-2) var(--space-4); + font-size: 13px; + overflow-wrap: anywhere; +} +.wb-tasks__notice { color: var(--fg-muted); } +.wb-tasks__alert { color: var(--danger); } +.wb-tasks__body { + display: grid; + grid-template-columns: minmax(12rem, 28%) minmax(0, 1fr); + min-height: 0; + flex: 1; + border-top: 1px solid var(--border); +} +.wb-tasks__list { border-inline-end: 1px solid var(--border); min-width: 0; overflow: auto; } +.wb-tasks__list h3 { margin: 0; } +.wb-tasks__detail { min-width: 0; overflow: auto; } +.wb-tasks__detail:focus { outline: none; } +.wb-tasks__detail:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } +.wb-tasks__card { padding: var(--space-4); } +.wb-tasks__card :is(h3, h4) { margin: 0; } +.wb-tasks__card dl, .wb-tasks__card dd { margin: 0; } +.wb-tasks__card .cf-profile__v { overflow-wrap: anywhere; } +.wb-tasks__card .cf-truns { grid-template-columns: minmax(0, auto) max-content minmax(0, 1fr); } +.wb-tasks__card .cf-trun__time { overflow-wrap: anywhere; } +.wb-tasks__run.cf-trun__msg, .wb-tasks__prompt { white-space: pre-wrap; overflow-wrap: anywhere; } +.wb-tasks__prompt { margin-top: var(--space-2); } +.wb-tasks__confirm, .wb-tasks__preview { + padding: var(--space-4); + border: 1px solid var(--border); + border-radius: var(--radius); +} +.wb-tasks__preview { margin: var(--space-4) auto; width: min(calc(100% - 2 * var(--space-4)), 42rem); } +.wb-tasks__preview h3 { margin: 0; } +.wb-tasks__muted { color: var(--fg-muted); } +.wb-tasks__zone { display: grid; gap: var(--space-2); max-width: 22rem; } +.wb-tasks__fields { min-width: 0; border: 0; margin: var(--space-3) 0; padding: 0; } +.wb-tasks__fields legend { margin-bottom: var(--space-2); } +.wb-tasks__fields .sched__row { flex-wrap: wrap; } +.wb-tasks__allow { display: flex; align-items: center; gap: var(--space-2); margin-bottom: var(--space-3); } +.wb-tasks__receipt { margin-top: var(--space-3); white-space: pre-wrap; overflow-wrap: anywhere; } +.wb-tasks :is(button, input):focus-visible, .wb-tasks__toggle:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } +@container (max-width: 610px) { + .wb-tasks__body { grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(0, auto) minmax(0, 1fr); } + .wb-tasks__list { max-height: min(30vh, 14rem); border-inline-end: 0; border-bottom: 1px solid var(--border); } + .wb-tasks__card .cf-truns { grid-template-columns: minmax(0, 1fr) max-content; } + .wb-tasks__run { grid-column: 1 / -1; } +} diff --git a/apps/desktop/src/workbench/text-workbench.tsx b/apps/desktop/src/workbench/text-workbench.tsx index 7eabfe63..59878767 100644 --- a/apps/desktop/src/workbench/text-workbench.tsx +++ b/apps/desktop/src/workbench/text-workbench.tsx @@ -1,5 +1,5 @@ -import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from 'react' -import { Archive, ArrowLeft, Globe, Plus, Search } from 'lucide-react' +import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from 'react' +import { Archive, ArrowLeft, CalendarClock, Globe, Plus, Search } from 'lucide-react' import { useI18n } from '../renderer/src/i18n/i18n' import { findActive, useModels } from '../renderer/src/store/models' import { ChatSurface, ConversationHeader, ConversationScroller, ConversationSurface } from '../renderer/src/redesign/ChatSurface' @@ -29,6 +29,9 @@ import { createPreferenceTransport, matchesPreferences, projectSession } from '. import { SessionHeaderActions, SessionModelPicker, SessionPreferenceStatus, SessionRenameDialog } from './session-preference-ui' import { createSessionWorkspaceTransport } from './session-workspace-transport' import { AttachedWorkspaceLabel, SessionWorkspaceControls, useSessionWorkspace } from './session-workspace-ui' +import { closedTaskSnapshot, createTaskInspection, idleTaskSubscription } from './task-inspection-controller' +import { createTaskInspectionTransport } from './task-inspection-transport' +import { TaskInspectionPanel } from './task-inspection-ui' import type { Bootstrap, LibraryQueue, Transport } from './transport' import { useTextWorkbench } from './use-text-workbench' import { WorkspaceFilesPanel } from './workspace-dialog' @@ -71,6 +74,19 @@ export default function TextWorkbench({ transport, bootstrap, beforeWrite, onExp return () => { alive = false } }, [library]) const [settingsOpen, setSettingsOpen] = useState(false) + const tasksEnabled = bootstrap.capabilities?.taskInspection === true + const tasks = useMemo(() => tasksEnabled ? createTaskInspection(createTaskInspectionTransport(transport, bootstrap.csrf), { + expired: onExpired, beforePause: beforeWrite + }) : undefined, [tasksEnabled, transport, bootstrap.csrf, beforeWrite, onExpired]) + const taskView = useSyncExternalStore(tasks?.subscribe ?? idleTaskSubscription, tasks?.snapshot ?? closedTaskSnapshot) + const tasksButton = useRef(null) + const tasksPanelId = useId() + useLayoutEffect(() => { + if (locked) tasks?.close() + return () => tasks?.close() + }, [locked, tasks]) + const tasksVisible = !!tasks && !locked && taskView.open + const closeTasks = (): void => { tasks?.close(); tasksButton.current?.focus() } const [compact, setCompact] = useState(() => window.innerWidth < 780) const [sidebarWidth, setSidebarWidth] = useState(SIDEBAR_DEFAULT) const [query, setQuery] = useState('') @@ -99,6 +115,7 @@ export default function TextWorkbench({ transport, bootstrap, beforeWrite, onExp openWorkspaceProject(files, workspace.id, signal)) : undefined const manualFilesSid = useRef() const openFiles = files ? () => { + tasks?.close() if (controlledOpen && bound.confirmed?.workspace?.state === 'available' && !bound.pending && !bound.needsReview) { controlledOpen() return @@ -165,7 +182,7 @@ export default function TextWorkbench({ transport, bootstrap, beforeWrite, onExp const [browserOpen, setBrowserOpen] = useState<{ sid: string; transport: BrowserTransport; panel: ManualBrowserPanel }>() const browserVisible = browserOpen && browserOpen.sid === sid && browserOpen.transport === browser && !locked && !settingsOpen useEffect(() => { if (browserOpen && !browserVisible) setBrowserOpen(undefined) }, [browserOpen, browserVisible]) - const dropFiles = wk.attachments && sid ? (event: React.DragEvent): void => { + const dropFiles = !tasksVisible && wk.attachments && sid ? (event: React.DragEvent): void => { if (!event.dataTransfer.types.includes('Files') || !event.currentTarget.contains(event.target as Node)) return event.preventDefault() event.stopPropagation() @@ -180,8 +197,8 @@ export default function TextWorkbench({ transport, bootstrap, beforeWrite, onExp window.removeEventListener('drop', preventFileDrop) } }, []) - const start = (): void => { setQuery(''); setArchivedView(false); void wk.create() } - const openSettings = (): void => setSettingsOpen(true) + const start = (): void => { tasks?.close(); setQuery(''); setArchivedView(false); void wk.create() } + const openSettings = (): void => { tasks?.close(); setSettingsOpen(true) } const surface =
{!compact && setSidebarWidth((w) => clampSidebar(w, window.innerWidth))} onReset={() => setSidebarWidth(SIDEBAR_DEFAULT)} />} setCompact((value) => !value)} listCollapsed={compact} onOpenSettings={openSettings} chatAlert={false} unavailable={c.unavailable} - library={library ? { openProfile: () => setPanel('profile'), openRoster: () => setPanel('roster') } : undefined} /> + library={library ? { openProfile: () => { tasks?.close(); setPanel('profile') }, openRoster: () => { tasks?.close(); setPanel('roster') } } : undefined} />
} + } {settingsOpen && renderSettings(() => setSettingsOpen(false))} diff --git a/apps/desktop/src/workbench/transport.ts b/apps/desktop/src/workbench/transport.ts index 5d1b3f7b..95025b3d 100644 --- a/apps/desktop/src/workbench/transport.ts +++ b/apps/desktop/src/workbench/transport.ts @@ -14,7 +14,7 @@ export interface Bootstrap { config: RecordValue csrf: string expiresAt: number - capabilities?: { textChat?: true; library?: true; workspaceFiles?: true; attachments?: true; browserPanel?: true; sessionPreferences?: true; deliveries?: true; gitInspect?: true; sessionWorkspaces?: true } + capabilities?: { textChat?: true; library?: true; workspaceFiles?: true; attachments?: true; browserPanel?: true; sessionPreferences?: true; deliveries?: true; gitInspect?: true; sessionWorkspaces?: true; taskInspection?: true } } export type SessionScreen = { mode: 'authenticated'; bootstrap: Bootstrap } | { mode: 'claim' | 'login' } @@ -123,6 +123,7 @@ export function createTransport(send: Fetch = fetch) { if (result.capabilities.deliveries === true) capabilities.deliveries = true if (result.capabilities.gitInspect === true) capabilities.gitInspect = true if (result.capabilities.sessionWorkspaces === true) capabilities.sessionWorkspaces = true + if (result.capabilities.taskInspection === true) capabilities.taskInspection = true } return { protocol, version, platform, config, csrf, expiresAt, ...(Object.keys(capabilities).length ? { capabilities } : {}) } } diff --git a/scripts/workbench/task-inspection-ui.test.mjs b/scripts/workbench/task-inspection-ui.test.mjs new file mode 100644 index 00000000..3987119c --- /dev/null +++ b/scripts/workbench/task-inspection-ui.test.mjs @@ -0,0 +1,313 @@ +import assert from 'node:assert/strict' +import { readFile } from 'node:fs/promises' +import { createRequire } from 'node:module' +import test from 'node:test' + +const require = createRequire(new URL('../../apps/desktop/package.json', import.meta.url)) +const ts = require('typescript') +const React = require('react') +const { renderToStaticMarkup } = require('react-dom/server') +const src = new URL('../../apps/desktop/src/', import.meta.url) +async function load(path, imports = {}) { + const js = ts.transpileModule(await readFile(new URL(path, src), 'utf8'), { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX } + }).outputText + const mod = { exports: {} } + new Function('require', 'module', 'exports', js)((name) => Object.hasOwn(imports, name) ? imports[name] : require(name), mod, mod.exports) + return mod.exports +} +const base = await load('workbench/transport.ts') +const transport = await load('workbench/task-inspection-transport.ts') +const { createTaskInspection } = await load('workbench/task-inspection-controller.ts', { + './transport': base, './task-inspection-transport': transport +}) +const time = await load('workbench/task-inspection-time.ts') +const copy = await load('workbench/task-inspection-copy.ts') +const messages = (await load('renderer/src/i18n/messages.ts')).messages +let uiLocale = 'en' +const i18n = { useI18n: () => ({ locale: uiLocale, t: (key) => key.split('.').reduce((part, name) => part?.[name], messages[uiLocale]) ?? key }) } +const reactSSR = { ...React, useLayoutEffect: React.useEffect } +const parts = await load('renderer/src/redesign/TaskInspectionParts.tsx', { '../i18n/i18n': i18n }) +const desktopSchedule = await load('renderer/src/features/chat/schedule.ts') +const editor = await load('renderer/src/features/chat/ScheduleEditor.tsx', { '../../i18n/i18n': i18n, + '../../components/Select': await load('renderer/src/components/Select.tsx', { react: reactSSR }), './schedule': desktopSchedule }) +const { TaskInspectionPanel } = await load('workbench/task-inspection-ui.tsx', { + react: reactSSR, '../renderer/src/features/chat/ScheduleEditor': editor, '../renderer/src/i18n/i18n': i18n, + '../renderer/src/redesign/TaskInspectionParts': parts, './task-inspection-copy': copy, './task-inspection-time': time, + './task-inspection.css': {} +}) +const { createTransport, HttpFailure } = base +const { createTaskInspectionTransport } = transport + +const a = 'bd437558-f2d4-4054-b0e4-9a454b68ac03', b = 'native_task_2' +const revision = 'a'.repeat(64), newer = 'b'.repeat(64), execution = 'inactive' +const now = Date.UTC(2031, 6, 1, 17, 13, 0) +const once = { kind: 'once', at: '2031-07-01T13:13', tz: 'America/New_York' } +const recurring = { kind: 'recurring', cron: '17 13 * * *', tz: 'UTC' } +const summary = (id = a, extra = {}) => ({ id, title: 'Native schedule', status: 'active', schedule: once, + createdAt: now, updatedAt: now, lastRunAt: now, nextRunAt: now, runCount: 1, ...extra }) +const task = (id = a, extra = {}) => ({ ...summary(id), prompt: '\n**plain**', auth: { personaId: null, modelRef: 'local:model' }, + sessionId: `task-${id}`, ownerSessionId: null, originSessionId: null, consecutiveErrors: 1, pauseAllowed: true, + runs: [{ firedAt: now, finishedAt: now + 1_000, status: 'error', summary: '', error: 'Recorded ' }], ...extra }) +const list = (tasks = [summary(), summary(b)]) => ({ tasks, revision, execution }) +const detail = (record = task(), rev = revision) => ({ task: record, revision: rev, execution }) +const preview = { ok: true, description: 'Schedule calculation only', nextRunAt: now } +const boot = { protocol: 1, version: '1', platform: 'linux', csrf: 'private-csrf', config: {}, expiresAt: now } +const json = (value, status = 200) => new Response(JSON.stringify(value), { status }) +function deferred() { + let resolve, reject + const promise = new Promise((ok, bad) => { resolve = ok; reject = bad }) + return { promise, resolve, reject } +} +function fixture(overrides = {}, beforePause = async () => {}) { + let expiries = 0 + const calls = [] + const reads = { list: async () => list(), detail: async (id) => detail(task(id)), preview: async () => preview, + pause: async () => {}, ...overrides } + const api = Object.fromEntries(Object.entries(reads).map(([method, call]) => [method, (...args) => { + calls.push({ method, args: args.slice(0, -1), signal: args.at(-1) }) + return call(...args) + }])) + return { api: createTaskInspection(api, { expired: () => { expiries++ }, beforePause }), calls, expired: () => expiries } +} + +const input = { schedule: recurring, locale: 'en', allowPast: false } + +test('exact capability and wire receipts; paths, methods, bodies and CSRF are scoped', async () => { + const signal = new AbortController().signal + const steps = [ + ['GET', '/bootstrap', undefined, { ...boot, capabilities: { taskInspection: 'true' } }], + ['GET', '/bootstrap', undefined, { ...boot, capabilities: { taskInspection: true } }], + ['GET', '/tasks', undefined, list([{ ...summary(), prompt: 'ignored in the list', other: '/private/path' }])], + ['GET', `/tasks/${a}`, undefined, detail()], + ['POST', '/tasks/preview', input, preview], + ['POST', '/tasks/preview', { schedule: once, locale: 'zh-CN', allowPast: true }, { ok: true, description: '已过去', nextRunAt: null }], + ['PATCH', `/tasks/${a}/status`, { revision, status: 'paused' }, detail(task(a, { status: 'paused', pauseAllowed: false }), newer)] + ] + const root = createTransport(async (url, init) => { + const [method, path, body, data] = steps.shift() + assert.equal(url, `/api/v1${path}`) + assert.equal(init.method, method) + assert.deepEqual(init.body ? JSON.parse(init.body) : undefined, body) + assert.equal(init.cache, 'no-store') + assert.equal(init.credentials, 'same-origin') + assert.equal(init.redirect, 'error') + if (path !== '/bootstrap') assert.equal(init.signal, signal) + if (method === 'GET') assert.equal(init.headers['x-deva-csrf'], undefined) + else { + assert.equal(init.headers['x-deva-csrf'], boot.csrf) + assert.equal(init.headers['content-type'], 'application/json') + assert.equal(init.referrerPolicy, 'same-origin') + } + return json(data) + }) + assert.equal((await root.inspect()).bootstrap.capabilities?.taskInspection, undefined) + assert.equal((await root.inspect()).bootstrap.capabilities?.taskInspection, true) + const api = createTaskInspectionTransport(root, boot.csrf) + assert.deepEqual(await api.list(signal), list([summary()])) + assert.deepEqual(await api.detail(a, signal), detail()) + assert.deepEqual(await api.preview({ ...input, schedule: { ...recurring, at: 'discarded', prompt: 'private' } }, signal), preview) + assert.deepEqual(await api.preview({ schedule: { ...once, cron: 'discarded' }, locale: 'zh-CN', allowPast: true }, signal), + { ok: true, description: '已过去', nextRunAt: null }) + await api.pause(a, revision, signal) + assert.deepEqual(steps, []) +}) + +test('rejects malformed receipt, mismatched detail and unsafe IDs with no route injection', async () => { + const responses = [list([summary(), summary()]), { ...list(), revision: 'not-a-revision' }, { ...list(), execution: 'active' }, + detail(task(b)), detail(task(a, { runs: [{ firedAt: now, status: 'running' }] })), { ok: false, error: 'invalid-cron' }, + { ok: false, error: '' }] + const api = createTaskInspectionTransport(createTransport(async () => json(responses.shift())), boot.csrf) + const signal = new AbortController().signal + const bad = /Invalid task inspection receipt/ + for (const id of ['..', 'a/b', `${a}?x=secret`, `${a}\n`, `${a}#hash`, '%2f']) await assert.rejects(api.detail(id, signal), bad) + await assert.rejects(api.pause(a, 'bad', signal), bad) + assert.equal(responses.length, 7) + for (let i = 0; i < 3; i++) await assert.rejects(api.list(signal), bad) + for (let i = 0; i < 2; i++) await assert.rejects(api.detail(a, signal), bad) + assert.deepEqual(await api.preview(input, signal), { ok: false, error: 'invalid-cron' }) + await assert.rejects(api.preview(input, signal), bad) + assert.deepEqual(responses, []) +}) + +test('only an open panel reads summaries; selection and preview are explicit and independent', async () => { + const { api, calls } = fixture() + await api.refresh() + await api.select(a) + await api.preview(input) + api.askPause() + await api.confirmPause() + assert.deepEqual(calls, []) + await api.open() + assert.deepEqual(calls.map(({ method }) => method), ['list']) + assert.equal(api.snapshot().detail, undefined) + await api.preview(input) + assert.equal(api.snapshot().preview.data.description, preview.description) + await api.select(a) + assert.equal(api.snapshot().preview, undefined) + assert.deepEqual(api.snapshot().detail.data, detail()) + await api.refresh() + assert.deepEqual(calls.map(({ method }) => method), ['list', 'preview', 'detail', 'list', 'detail']) +}) + +test('close, switch and draft changes abort stale reads, and only current 401 expires the session', async () => { + const oldRead = deferred(), oldPreview = deferred(), pendingRead = deferred() + let reads = 0 + const f = fixture({ detail: (id) => id === a ? oldRead.promise : ++reads === 1 ? detail(task(b)) : pendingRead.promise, + preview: () => oldPreview.promise }) + await f.api.open() + const pendingA = f.api.select(a) + await f.api.select(b) + assert.equal(f.calls[1].signal.aborted, true) + oldRead.reject(new HttpFailure(401, 'auth')) + await pendingA + assert.equal(f.expired(), 0) + assert.equal(f.api.snapshot().detail.data.task.id, b) + const calculating = f.api.preview(input) + f.api.clearPreview() + assert.equal(f.calls.at(-1).signal.aborted, true) + oldPreview.resolve(preview) + await calculating + assert.equal(f.api.snapshot().preview, undefined) + const refreshing = f.api.refresh() + await Promise.resolve() + assert.equal(f.calls.at(-1).method, 'detail') + f.api.close() + assert.equal(f.calls.at(-1).signal.aborted, true) + pendingRead.resolve(detail(task(b))) + await refreshing + assert.deepEqual(f.api.snapshot(), { open: false }) + for (const route of ['list', 'detail', 'preview', 'pause']) { + const fail = async () => { throw new HttpFailure(401, 'auth') } + const f = fixture({ [route]: fail }) + await f.api.open() + if (route === 'detail' || route === 'pause') await f.api.select(a) + if (route === 'preview') await f.api.preview(input) + if (route === 'pause') { f.api.askPause(); await f.api.confirmPause() } + assert.equal(f.expired(), 1, route) + assert.deepEqual(f.api.snapshot(), { open: false }, route) + } +}) + +test('cancel has no write; conflict blocks retry until refresh and success uses fresh observations', async () => { + let pauses = 0, savedStatus = 'active', savedRevision = revision + const f = fixture({ + list: async () => ({ ...list([summary(a, { status: savedStatus })]), revision: savedRevision }), + detail: async () => detail(task(a, { status: savedStatus, pauseAllowed: savedStatus === 'active' }), savedRevision), + pause: async (id, expected) => { + assert.equal(id, a) + if (++pauses === 1) { assert.equal(expected, revision); savedRevision = newer; throw new HttpFailure(409, 'task_conflict') } + assert.equal(expected, newer) + savedStatus = 'paused' + } + }) + await f.api.open(); await f.api.select(a) + await f.api.confirmPause() + f.api.askPause() + assert.equal(f.api.snapshot().confirming, true) + f.api.cancelPause(); await f.api.confirmPause() + assert.equal(pauses, 0) + f.api.askPause(); await f.api.confirmPause() + assert.equal(f.api.snapshot().statusIssue, 'conflict') + f.api.askPause(); await f.api.confirmPause() + assert.deepEqual(f.calls.map(({ method }) => method), ['list', 'detail', 'pause']) + await f.api.refresh() + assert.equal(f.api.snapshot().statusIssue, undefined) + f.api.askPause(); await f.api.confirmPause() + assert.deepEqual(f.calls.map(({ method }) => method), ['list', 'detail', 'pause', 'list', 'detail', 'pause', 'list', 'detail']) + assert.equal(f.api.snapshot().detail.data.task.status, 'paused') + assert.equal(f.api.snapshot().detail.data.task.nextRunAt, now) + assert.equal(f.api.snapshot().list.data.tasks[0].status, 'paused') + f.api.askPause(); await f.api.confirmPause() + assert.equal(pauses, 2) +}) + +test('unsupported/corrupt and busy are distinct; leaving before queued pause sends nothing', async () => { + for (const [code, status, label] of [['task_file_unsupported', 409, 'unsupported'], ['task_storage_unconfirmed', 503, 'unconfirmed'], + ['task_state', 409, 'stateChanged'], ['task_busy', 429, 'busy']]) { + const f = fixture({ pause: async () => { throw new HttpFailure(status, code) } }) + await f.api.open(); await f.api.select(a) + f.api.askPause(); await f.api.confirmPause(); await f.api.confirmPause() + assert.equal(f.api.snapshot().statusIssue, label) + assert.equal(f.calls.filter(({ method }) => method === 'pause').length, 1) + } + const beforeWrite = deferred() + const f = fixture({}, () => beforeWrite.promise) + await f.api.open(); await f.api.select(a) + f.api.askPause() + const saving = f.api.confirmPause() + f.api.close() + beforeWrite.resolve() + await saving + assert.deepEqual(f.calls.map(({ method }) => method), ['list', 'detail']) + assert.deepEqual(f.api.snapshot(), { open: false }) +}) + +test('a sent pause abandoned on selection changes never adopts a late acknowledgment or retries', async () => { + const ack = deferred() + const f = fixture({ pause: () => ack.promise }) + await f.api.open(); await f.api.select(a) + f.api.askPause(); const saving = f.api.confirmPause() + await Promise.resolve() + const patch = f.calls.at(-1) + assert.equal(patch.method, 'pause') + await f.api.select(b) + assert.equal(patch.signal.aborted, true) + ack.resolve() + await saving + assert.equal(f.api.snapshot().statusIssue, 'pauseUnconfirmed') + assert.equal(f.api.snapshot().detail.data.task.id, b) + assert.deepEqual(f.calls.map(({ method }) => method), ['list', 'detail', 'pause', 'detail']) +}) + +test('the Web rail shares Desktop ordering: soonest, newest tie-break, then null', async () => { + const rows = [summary('never', { nextRunAt: null, createdAt: now + 100 }), summary('last', { nextRunAt: now + 5 }), + summary('older', { nextRunAt: now }), summary('newer', { nextRunAt: now, createdAt: now + 1 })] + const expected = ['newer', 'older', 'last', 'never'] + const f = fixture({ list: async () => list(rows) }) + await f.api.open() + const html = renderToStaticMarkup(React.createElement(TaskInspectionPanel, { api: f.api, view: f.api.snapshot(), close: f.api.close, id: 'tasks' })) + assert.deepEqual([...html.matchAll(/data-task-id="([^"]+)"/g)].map(([, id]) => id), expected) + assert.deepEqual([...rows].sort(parts.compareTaskRows).map(({ id }) => id), expected) + assert.deepEqual(f.api.snapshot().list.data.tasks.map(({ id }) => id), ['never', 'last', 'older', 'newer']) +}) + +test('real Desktop row, detail, history and schedule editor render ordinary escaped text and zone-correct times', async () => { + const f = fixture() + const render = (view = f.api.snapshot()) => renderToStaticMarkup(React.createElement(TaskInspectionPanel, { api: f.api, view, close: f.api.close, id: 'tasks' })) + await f.api.open() + let html = render() + assert.match(html, /Server execution inactive; these are recorded desktop schedules/) + assert.match(html, /class="cf-trow"[^>]*data-testid="workbench-task-row"/) + assert.match(html, /Native <img src=x> schedule/) + assert.doesNotMatch(html, /workbench-task-detail|<script>/) + assert.match(html, /class="sched__row"/) + assert.match(html, /data-testid="workbench-task-preview-zone"/) + assert.match(html, /data-testid="workbench-task-preview-allow-past"/) + assert.deepEqual(f.calls.map(({ method }) => method), ['list']) + await f.api.select(a) + html = render() + assert.match(html, /<script>alert\(1\)<\/script>\n\*\*plain\*\*/) + assert.match(html, /<img src=x onerror=alert\(1\)>/) + assert.match(html, /