Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Schedules: failures never turn a routine off; every skipped or held-up run leaves a row; default run limits
milind-soni026dd777a256
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.mdindex bf2c510630..bf9de124b8 100644--- a/docs/cloud-pro.md+++ b/docs/cloud-pro.md@@ -1719,6 +1719,7 @@ wait for the next read, `truncated: true`):"botId": "<uuid>", "threadId": "<uuid>", "seq": 12 }],"turns": { "started15m": 6, "failed15m": 3, "started24h": 40, "failed24h": 5 },"routines": [{ "routineId": "<uuid>", "status": "failed", "at": 1790000200000, "consecutiveFailures": 2 }],+ "schedule": { "unreadable": false, "slowStops": 0 },"engines": [{ "kind": "codex", "used": true, "available": true, "authenticated": false, "version": "0.130.0" }],"connectors": { "checkedAt": 1790000000000, "failed": false, "items": [{ "slug": "gmail", "connected": false }] },"browser": { "available": true, "installing": false, "interrupted": 0 },@@ -1794,7 +1795,16 @@ place's state (`shared/place-view.ts`); a cause the server words itselfelse `unknown`. A turn that ends in `shutdown_timeout`, `auth_required`,`update_required`, `spawn_error` or `rpc_error` without a failed row of its owncounts once too. `turns` counts turns started and failed rows per minute;-`routines` keeps each routine's last outcome and its failures in a row.+`routines` gives, for each routine that is on and each outside trigger, its last+outcome and its failures in a row, counted from the saved run rows at every read,+so a restart does not start the count again. A row that only counts occurrences+skipped while the routine was at work is not a result and is left out. `schedule.unreadable` is true while+the home cannot read its saved routines (none runs until it can), and+`schedule.slowStops` counts, since boot, the times stopping a turn took the+scheduler longer than 10 seconds and it went on without waiting. This `schedule`+section carries no `v`: a reader that requires a versioned section (`v: 1` with+every field of that version) takes it as "no section", which is intended. The+versioned section, with its required fields, comes with the run ledger.**What it never carries:** a failure's words, a bot's name, a thread's title,a prompt, a URL, an email address, a token, or an engine's accountdiff --git a/docs/routine-schedules.md b/docs/routine-schedules.mdindex 4b783d124d..bec19d8f29 100644--- a/docs/routine-schedules.md+++ b/docs/routine-schedules.md@@ -90,10 +90,77 @@ use an appropriate event/webhook workflow instead of a fake weekly schedule.for the same cron routine does not accumulate overlapping copies (a run iswaiting while teammates still owe it results on the job runtime,docs/runtime-contract.md §9).+- Every occurrence that does not run leaves a **Missed** row with its reason in+ the routine's log. Occurrences skipped behind the same earlier run share one+ row, which counts them ("Skipped 12 scheduled runs because the previous run+ of this routine is still running") and keeps the first and the last time, so+ a schedule every minute behind a long run adds one row. Such a row is shown+ as already seen and is never the routine's "latest run", a failure in a row,+ or one of its "N of M runs OK": it asks nothing of you. A run that has waited+ on you for 30 minutes when an occurrence is skipped behind it is the+ exception: you are told once, and that row shows under To review.+- Failures never turn a routine off. When a routine's cloud desktop does not+ start three runs in a row, the routine stays on and its scheduled runs are+ spaced out instead: the next one starts no sooner than an hour after the+ third failure, and four hours after each later one, because every such run+ spends the bot's AI for minutes before it fails. You are told once, the list+ says "Its cloud desktop did not start N runs in a row", and the occurrences+ held back share one Missed row. While it is spaced, the routine's next due+ time (what wakes a sleeping Cloud, keeps a desktop awake, and holds back a+ restart) is the first occurrence after the spacing, not one it will skip.+ The first run whose cloud desktop starts, **Run now**, or any change to the+ routine ends the spacing.+- A routine that an earlier version turned off after three such failures is+ turned back on, once per installation, at the first start of a version with+ this rule, when it can be told apart from one you turned off: it is off+ without a hold, its three newest results are that failure, the third ended+ within the last 30 days, and the routine has not been changed since that+ moment. Its bot says so in one quiet line in its own chat ("Turned back on:+ …"), with nothing to answer. One you edited after it was turned off, one+ that a workspace restore brought back (a restore leaves every routine off+ and counts as a change), one switched off longer ago, or one whose failed+ runs are no longer in the log, stays off: turn it on in the list. A copy+ frozen by a move to another home turns nothing back on until the freeze+ lifts.+- A run stops when it reaches its limit, ends as failed with the limit named+ ("Stopped: this run ran longer than the 3-hour limit"), and the schedule+ carries on. A routine may set its own limit, 5 minutes to 24 hours: that one+ counts the time since the run started, less the time its approvals and+ questions were open. Without one, the default applies to every run, whether+ the schedule, an event or **Run now** started it: 3 hours of work for a+ bot's run, 12 hours for a room goal's run (which stays running across every+ member's turn). Work is the time the run spent running since its current+ start: the time it is queued (behind a busy bot, for its one retry, for a+ usage limit's reset) and the time it waits (on your approval or answer, on a+ conversation left with you, on work it handed to teammates) is not in it.+ It is added up a minute at a time while the app runs, so the hours a+ computer slept, or a clock that was changed, are not in it either.+- A scheduled run queued behind its busy bot for an hour ends as Missed ("Did+ not run: the bot was busy for more than 60 minutes"), and the next+ occurrence starts as usual. Only the time it was seen waiting counts, not+ the time the computer slept or the app was closed, and the count starts+ again if the run starts and is queued once more. A run an event or **Run+ now** started has no next occurrence and waits as long as it takes; so does+ a run waiting behind its own routine's earlier run (overlap **queue**).+- Stopping a run's turn is given 10 seconds. If the AI has not confirmed the+ stop by then, the scheduler goes on with the other routines, but starts no+ new run of that routine until the stop is confirmed or 5 minutes have+ passed, so two runs of one routine never work side by side. The stop is sent+ again each minute, and the stopped run's row says so; a stop that was never+ confirmed stays written on it.+- `routines.json` is written through a temporary file and a rename. If it+ cannot be read, nothing in it is overwritten: no routine runs, changes are+ refused, the Automations list says so, a copy of the file is kept beside it+ (`routines.json.unreadable-…`, one per content, five at most), and the file is+ read again every minute. Once it can be read, the desktop app and a+ self-hosted server load it and do again what start does with routines+ (phone adoption, run-on-startup, the quiet lines above); a Cloud home+ restarts itself instead, because who owns its routines is settled only at+ start.- A run that asks you for an approval or an answer waits for you. Its card andthe Routines log say what it waits for ("Waiting for your approval to useCOMPOSIO_SEARCH_TOOLS"), the approval notification names the routine, and the- time it waits does not count toward its optional run limit, which bounds+ time it waits does not count toward its run limit, which boundsactive work only. If the engine's own wait for an approval runs out withnobody's answer, the run stops with "Stopped: nobody answered the approval touse …" and the routine-failed notification. A run still waiting when itsdiff --git a/packages/phone-protocol/src/routine-request.ts b/packages/phone-protocol/src/routine-request.tsindex 2edcfd2899..9be9baf139 100644--- a/packages/phone-protocol/src/routine-request.ts+++ b/packages/phone-protocol/src/routine-request.ts@@ -53,7 +53,7 @@ export interface RoutineRequestDefinition {runOn: RoutineRequestRunOn;/** Calendar/display length only: it does not stop an active run. */durationMinutes: number;- /** Optional safety cap for active work. Missing means no timeout. */+ /** Optional limit on a run, 5 to 1,440 minutes. Missing means the default limit on its work (ROUTINE_RUN_LIMIT_MINUTES). */timeoutMinutes?: number;/** Carry the previous run's report into the next run. */continuity?: boolean;diff --git a/packages/phone-protocol/src/routines.ts b/packages/phone-protocol/src/routines.tsindex cf01c5cea4..bd00b2f7a0 100644--- a/packages/phone-protocol/src/routines.ts+++ b/packages/phone-protocol/src/routines.ts@@ -109,6 +109,14 @@ export type RoutineRetryCause = "stalled" | "restarted" | "rate_limited" | "prov* not been acknowledged. */export const ROUTINE_PROBLEM_STATUSES: readonly RoutineRunStatus[] = ["failed", "missed"];+/** Minutes of work a run may do when its routine sets no limit of its own: a bot's run, and a room goal's run, which+ * stays running across every member's turn. */+export const ROUTINE_RUN_LIMIT_MINUTES = 180;+export const ROUTINE_GOAL_RUN_LIMIT_MINUTES = 720;+/** The longest limit a routine may set for itself (`timeoutMinutes`), and the shortest. */+export const ROUTINE_RUN_LIMIT_MAX_MINUTES = 1_440;+export const ROUTINE_RUN_LIMIT_MIN_MINUTES = 5;+/** A run's `attention` while it waits only on work it handed to teammates: nothing is asked of the person. */export const ROUTINE_HANDOFF_WAIT = "Waiting for work it handed on to finish";@@ -116,6 +124,12 @@ export function isRoutineProblemRun(run: { status: RoutineRunStatus }): booleanreturn ROUTINE_PROBLEM_STATUSES.includes(run.status);}+/** A missed row that only counts occurrences skipped while the routine was otherwise at work, or while its tries are+ * spaced out, and that the owner was not told about: it belongs in the history, and is never the routine's latest result. */+export function isCountedSkip(run: Pick<RoutineRun, "skipped">): boolean {+ return run.skipped !== undefined && run.skipped.told !== true;+}+/** The logs view's status filter: every run, the composite problem set the* indicators count, or one exact status. */export type RoutineRunStatusFilter = "all" | "problems" | RoutineRunStatus;@@ -132,7 +146,8 @@ export interface Routine {enabled: boolean;schedule: RoutineSchedule;durationMinutes: number;- /** Optional wall-clock safety limit. Missing means the run is unlimited. */+ /** How many minutes a run may take before it is stopped, 5 to 1,440. Missing means the default limit on its work:+ * ROUTINE_RUN_LIMIT_MINUTES, or ROUTINE_GOAL_RUN_LIMIT_MINUTES for a room goal. */timeoutMinutes?: number;overlap?: "skip" | "queue";/** Each run starts with the previous run's report. */@@ -156,6 +171,9 @@ export interface Routine {skippedRuns?: number;lastSkippedAt?: number;failureStreak?: number;+ /** Its newest runs in a row whose cloud computer did not start, once there are enough that its scheduled runs are+ * spaced out for it. It stays on. */+ noStartStreak?: number;/** Runs that finished in the last seven days, and how many of them completed. */weekRuns?: { ok: number; total: number };/** A plain sentence when the routine names a path that cannot exist on the computer that runs it. */@@ -222,6 +240,9 @@ export interface RoutineRun {deliver?: RoutineDelivery;/** The items its routine's checks handed this run, so they are kept or released once it ends. */checkKey?: string;+ /** On a missed row that stands for occurrences skipped for one cause: how many, the first and last scheduled time,+ * and whether the owner was told. Its `error` says why. */+ skipped?: { count: number; firstAt: number; lastAt: number; told?: true };createdAt: number;seenAt?: number;}diff --git a/server/cloud-health.test.ts b/server/cloud-health.test.tsindex 5a24134a54..7d4219122d 100644--- a/server/cloud-health.test.ts+++ b/server/cloud-health.test.ts@@ -210,13 +210,17 @@ describe("the ledger", () => {expect(w.health.report(null).turns).toEqual({ started15m: 0, failed15m: 0, started24h: 0, failed24h: 0 });});- it("follows each routine's last outcome and its failures in a row", () => {- const w = world();- const run = (id: string, status: "completed" | "failed" | "missed" | "running") => w.health.noteRoutineRun({ id, routineId: "routine-1", status, finishedAt: w.now() });- run("r1", "failed"); run("r1", "failed"); run("r2", "running"); run("r2", "missed");- expect(w.health.report(null).routines).toEqual([{ routineId: "routine-1", status: "missed", at: START, consecutiveFailures: 2 }]);- run("r3", "completed");- expect(w.health.report(null).routines).toEqual([{ routineId: "routine-1", status: "completed", at: START, consecutiveFailures: 0 }]);+ it("reports each routine's last outcome and failures in a row as the saved run rows give them, so a restart hides none", () => {+ const rows = [{ routineId: "routine-1", status: "missed" as const, at: START, consecutiveFailures: 2 }, { routineId: "not an id!", status: "failed" as const, at: START, consecutiveFailures: 9 }];+ const caps: number[] = [];+ const deps = { routines: (cap: number) => { caps.push(cap); return rows; }, schedule: () => ({ unreadable: true, slowStops: 2 }) };+ for (const w of [world(deps), world(deps)]) {+ const report = w.health.report(null);+ expect(report.routines).toEqual([rows[0]]);+ expect(report.schedule).toEqual({ unreadable: true, slowStops: 2 });+ }+ expect(caps).toEqual([100, 100]);+ expect(world().health.report(null)).toMatchObject({ routines: [], schedule: null });});});@@ -267,8 +271,7 @@ describe("the report", () => {it("stays under 64 KB, and the cursor picks up what did not fit", () => {let clock = START;const routines = Array.from({ length: 100 }, (_, i) => `r${String(i).padStart(63, "0")}`);- const w = world({ now: () => clock });- for (const routineId of routines) w.health.noteRoutineRun({ id: routineId, routineId, status: "failed" });+ const w = world({ now: () => clock, routines: () => routines.map((routineId) => ({ routineId, status: "failed" as const, at: START, consecutiveFailures: 1 })) });const ledger = w.health.ledger;for (let i = 0; i < HEALTH_BUCKET_CAP; i++) {const thread = `t${String(i).padStart(63, "0")}`;diff --git a/server/cloud-health.ts b/server/cloud-health.tsindex beb8cd939c..365357e5d8 100644--- a/server/cloud-health.ts+++ b/server/cloud-health.ts@@ -5,7 +5,6 @@ import { accessSync, constants, readFileSync, statfsSync } from "node:fs";import { availableParallelism, freemem, loadavg, totalmem } from "node:os";import { failedTurnCause } from "../shared/failed-turn.ts";import { PLACE_STATES } from "../shared/place-view.ts";-import type { RoutineRunStatus } from "../shared/routines.ts";import { trialCreditKind } from "../shared/trial-credit.ts";import type { BoxReport } from "./bot-box/box.ts";import type { RoomReport } from "./engine-memory.ts";@@ -14,6 +13,7 @@ import type { ValueReport } from "./host/value-ledger.ts";import type { ProviderSnapshot, RuntimeEvent } from "./contracts.ts";import { createCloudSpeed, type CloudSpeed } from "./cloud-speed.ts";import { classifyError } from "./drivers/retry.ts";+import type { RoutineHealth } from "./routine-health.ts";import type { Message, StoreChange } from "./store.ts";/** The report's largest JSON body; incidents past it wait for the next poll. */@@ -59,7 +59,7 @@ export interface HealthIncident {kind: HealthIncidentKind; code: string; engine: string | null;count: number; firstAt: number; lastAt: number; botId: string | null; threadId: string | null; seq: number;}-export interface RoutineHealth { routineId: string; status: RoutineRunStatus; at: number; consecutiveFailures: number }+export type { RoutineHealth };export interface TurnRates { started15m: number; failed15m: number; started24h: number; failed24h: number }interface Pending { at: number; botId: string | null; engine: string | null; fallback: string }@@ -87,7 +87,7 @@ const remember = <K, V>(map: Map<K, V>, key: K, value: V, cap: number) => {/*** Failed turns since boot, bucketed by kind, code and engine. Fed by one tap on the store (every failed-turn row, the one- * place they are written) and the runtime bus (turn starts, stop reasons, engine kinds); routines by their runs.+ * place they are written) and the runtime bus (turn starts, stop reasons, engine kinds).*/export function createCloudHealthLedger(options: { botOf?: (threadId: string) => string | null; now?: () => number } = {}) {const now = options.now ?? Date.now;@@ -98,7 +98,6 @@ export function createCloudHealthLedger(options: { botOf?: (threadId: string) =>const lastRowAt = new Map<string, number>();const engines = new Map<string, string>();const minutes = new Map<number, { started: number; failed: number }>();- const routines = new Map<string, RoutineHealth & { runId: string }>();const tally = (at: number, field: "started" | "failed") => {const minute = Math.floor(at / MINUTE);@@ -168,17 +167,6 @@ export function createCloudHealthLedger(options: { botOf?: (threadId: string) =>record("turn", event.stopReason, engines.get(event.threadId) ?? match(KIND, event.provider), at, options.botOf?.(event.threadId) ?? null, event.threadId);}},- noteRoutineRun(run: { id: string; routineId: string; status: RoutineRunStatus; finishedAt?: number }) {- if (!["completed", "failed", "missed", "cancelled"].includes(run.status)) return;- const routineId = match(ID, run.routineId);- if (!routineId) return;- const previous = routines.get(routineId);- if (previous?.runId === run.id && previous.status === run.status) return;- const failed = run.status === "failed" || run.status === "missed";- const sameRun = previous?.runId === run.id && (previous.status === "failed" || previous.status === "missed");- const consecutiveFailures = failed ? (previous?.consecutiveFailures ?? 0) + (sameRun ? 0 : 1) : run.status === "completed" ? 0 : previous?.consecutiveFailures ?? 0;- remember(routines, routineId, { routineId, runId: run.id, status: run.status, at: run.finishedAt ?? now(), consecutiveFailures }, ROUTINE_CAP);- },/** Buckets changed after `after` (a cursor from an earlier read of this boot; anything else reads from the start), oldest change first. */read(after: string | null | undefined) {settleStale();@@ -192,7 +180,7 @@ export function createCloudHealthLedger(options: { botOf?: (threadId: string) =>turns.started24h += slot.started; turns.failed24h += slot.failed;if (minute > current - WINDOW_15M) { turns.started15m += slot.started; turns.failed15m += slot.failed; }}- return { since, seq, incidents, turns, routines: [...routines.values()].map(({ runId: _runId, ...routine }) => routine) };+ return { since, seq, incidents, turns };},cursor: (at: number) => `${bootedAt}.${at}`,};@@ -254,6 +242,10 @@ export interface CloudHealthDeps {firstHour?: () => { firstHour?: FirstHourReport; value?: ValueReport };/** The last day's memory pressure (engine-memory.ts), where this home watches it. */room?: () => RoomReport;+ /** Each routine's newest ended run and its failures in a row, from the saved run rows (routine-health.ts), at most `cap`. */+ routines?: (cap: number) => RoutineHealth[];+ /** Whether routines.json cannot be read, and how often stopping a turn outlasted the scheduler's wait since boot. */+ schedule?: () => { unreadable: boolean; slowStops: number };/** CPU steal and pressure, boot and wake times, and how long messages wait for their engine. */speed?: CloudSpeed;now?: () => number;@@ -295,13 +287,13 @@ export function createCloudHealth(deps: CloudHealthDeps) {return {ledger,speed,- noteRoutineRun: ledger.noteRoutineRun,report(after: string | null | undefined) {const read = ledger.read(after);const memory = memoryBytes(), browser = deps.browser(), first = deps.firstHour?.();const base = {v: 1 as const, version, image, bootedAt: ledger.bootedAt, at: now(),- turns: read.turns, routines: read.routines, engines: engines(), connectors: connectorState(),+ turns: read.turns, routines: (deps.routines?.(ROUTINE_CAP) ?? []).filter((routine) => match(ID, routine.routineId)), schedule: deps.schedule?.() ?? null,+ engines: engines(), connectors: connectorState(),browser: { available: browser.available, installing: browser.installing, interrupted: browser.interrupted },box: boxSummary(deps.box?.()),firstHour: first?.firstHour ?? null, value: first?.value ?? null, room: deps.room?.() ?? null, speed: speed.report(),diff --git a/server/host/brief.test.ts b/server/host/brief.test.tsindex ecf29caec3..9a57bec81e 100644--- a/server/host/brief.test.ts+++ b/server/host/brief.test.ts@@ -215,6 +215,19 @@ describe("the brief", () => {expect(actions.filter(([, type]) => type === "open_thread")).toHaveLength(3);});+ it("takes a routine's real run for its latest, not a row that only counts occurrences skipped behind it", async () => {+ const s = setup({ needsYou: [{ kind: "signed-out", id: "x", at: 0, instanceId: "claude", botIds: [] }] });+ const base = { routineId: "tidy", routineName: "Tidy my inbox", target: "bot" as const, botId: s.chief.id, runOn: "maus" as const, manual: false };+ const done: RoutineRun = { ...base, id: "done", scheduledFor: s.now(), status: "completed", createdAt: s.now(), finishedAt: s.now() + 1_000, output: "Filed twelve emails." };+ const counted: RoutineRun = { ...base, id: "counted", scheduledFor: s.now() + 500, status: "missed", createdAt: s.now() + 500, finishedAt: s.now() + 2_000, seenAt: s.now() + 500,+ error: "Skipped because the previous run of this routine is still running", skipped: { count: 1, firstAt: s.now() + 500, lastAt: s.now() + 500, behind: "done" } };+ s.runs.push(done, counted);+ await s.brief.active("desktop", "UTC");+ expect(s.shown()).toContain("Filed twelve emails.");+ expect(s.shown()).not.toContain("Skipped because");+ expect(s.shown()).not.toContain("missed");+ });+it("a watch run's answer becomes rows and a prep card, and tells the person once", async () => {const s = setup();await s.brief.active("desktop", "UTC");diff --git a/server/host/brief.ts b/server/host/brief.tsindex c2732ac5c3..4f3dee0e78 100644--- a/server/host/brief.ts+++ b/server/host/brief.ts@@ -8,6 +8,7 @@ import { readFileSync } from "node:fs";import { join } from "node:path";import { z } from "zod";+import { isCountedSkip } from "../../shared/routines.ts";import type { NeedsYouItem } from "../../shared/today.ts";import type { WidgetText } from "../../shared/widget-text.ts";import type { WidgetAction, WidgetRoot } from "../../shared/widget.ts";@@ -240,7 +241,7 @@ export function createBrief(deps: BriefDeps) {const latest = new Map<string, RoutineRun>();for (const run of deps.runs()) {const end = run.finishedAt ?? run.createdAt;- if (end < since || !["completed", "failed", "missed"].includes(run.status) || run.report?.state === "quiet") continue;+ if (end < since || !["completed", "failed", "missed"].includes(run.status) || run.report?.state === "quiet" || isCountedSkip(run)) continue;if (run.status === "completed" && run.deliver === "brief") continue;const seen = latest.get(run.routineId);if (!seen || (seen.finishedAt ?? seen.createdAt) <= end) latest.set(run.routineId, run);diff --git a/server/host/routines-turned-back-on.test.ts b/server/host/routines-turned-back-on.test.tsnew file mode 100644index 0000000000..a580064bbc--- /dev/null+++ b/server/host/routines-turned-back-on.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from "vitest";++import { Store } from "../store.ts";+import { tellTurnedBackOn } from "./routines-turned-back-on.ts";++describe("routines turned back on after an earlier version switched them off", () => {+ it("are named in one quiet line per bot, in that bot's own chat: no card, nothing to answer", () => {+ const store = new Store(() => ({ instanceId: "claude", model: "claude-sonnet-5" }));+ const ada = store.createBot({ name: "Ada" }), ben = store.createBot({ name: "Ben" }), idle = store.createBot({ name: "Idle" });+ tellTurnedBackOn(store, [{ botId: ada.id, name: "Fix new bugs" }, { botId: ben.id, name: "Morning check" }, { botId: ada.id, name: "Triage inbox" }, { botId: "gone", name: "Orphan" }]);+ const lines = (threadId: string) => store.messagesFor(threadId).filter((row) => row.kind === "activity").map((row) => [row.kind, row.tool?.name, row.card]);+ expect(lines(ada.threadId)).toEqual([["activity", "notice: Turned back on: Fix new bugs, Triage inbox. An earlier version switched them off after their cloud desktops failed to start.", undefined]]);+ expect(lines(ben.threadId)).toEqual([["activity", "notice: Turned back on: Morning check. An earlier version switched it off after its cloud desktop failed to start.", undefined]]);+ expect(lines(idle.threadId)).toEqual([]);+ });++ it("say nothing when nothing was turned back on", () => {+ const store = new Store(() => ({ instanceId: "claude", model: "claude-sonnet-5" }));+ const ada = store.createBot({ name: "Ada" });+ const before = store.messagesFor(ada.threadId).length;+ tellTurnedBackOn(store, []);+ expect(store.messagesFor(ada.threadId)).toHaveLength(before);+ });+});diff --git a/server/host/routines-turned-back-on.ts b/server/host/routines-turned-back-on.tsnew file mode 100644index 0000000000..33d66ee96e--- /dev/null+++ b/server/host/routines-turned-back-on.ts@@ -0,0 +1,17 @@+// Routines an earlier version switched off after their cloud desktop failed to start come back on once+// (routine-no-start.ts). Each bot that has one gets a single quiet line in its own chat saying which: no card, nothing+// to answer, no notification.+import type { Routine } from "../routines.ts";+import { conversationLanguage, serverLine } from "../server-lines.ts";+import type { Store } from "../store.ts";++export function tellTurnedBackOn(store: Pick<Store, "bot" | "appendMessage">, routines: readonly Pick<Routine, "botId" | "name">[]): void {+ const byBot = new Map<string, string[]>();+ for (const routine of routines) byBot.set(routine.botId, [...(byBot.get(routine.botId) ?? []), routine.name]);+ for (const [botId, names] of byBot) {+ const bot = store.bot(botId);+ if (!bot) continue;+ const line = serverLine(conversationLanguage(bot.threadId), names.length === 1 ? "server.routines.turnedBackOn" : "server.routines.turnedBackOnMany", { names: names.join(", ") });+ store.appendMessage(bot.threadId, { role: "bot", kind: "activity", tool: { name: `notice: ${line}`, ok: true } });+ }+}diff --git a/server/index.ts b/server/index.tsindex ba50e85191..8c6c0e9bc1 100644--- a/server/index.ts+++ b/server/index.ts@@ -284,7 +284,7 @@ import { createCloudMoveRoutes } from "./cloud-move-http.ts";import { RESTART_EXIT_CODE } from "./restart.ts";import { applyIncludedXMessage, holdIncludedServices, hostingCredential, researchCredential, trialCreditCredential, xCredential, xResearchStatus } from "./included-services.ts"; import { applyPhoneLinkMessage, phoneLinkPart } from "./phone-link.ts"; import { createResearchAvailability } from "./research.ts";import { CloudCreditProvider } from "./cloud-credit-provider.ts";-import { createCreditMoves } from "./cloud-credit-moves.ts"; import { createRoutineHoldsHost } from "./host/routine-holds-host.ts";+import { createCreditMoves } from "./cloud-credit-moves.ts"; import { createRoutineHoldsHost } from "./host/routine-holds-host.ts"; import { tellTurnedBackOn } from "./host/routines-turned-back-on.ts";import { TRIAL_CREDIT_OWN_AI, TRIAL_KEY_HELD } from "./trial-credit.ts"; import { createHeldKeys } from "./cloud-held-keys.ts";import type { ProviderInstance } from "./contracts.ts";import { readyToRun, selectDefaultModelSelection, withInstanceConfig, withNewBotEffort, type SelectableInstance } from "./default-model-selection.ts"; import { configIdentity, createTestedAi } from "./tested-ai.ts"; import { instanceLook } from "./provider-icon.ts";@@ -2848,7 +2848,7 @@ const phones = createPhones({active: (turn) => internalCapabilityIsActive(turn as InternalCapability),});const cloudPlanTier = createCloudPlanTier({ dataDir: DATA_DIR, cloudHome: Boolean(CLOUD_HOME), changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterAwake = createStarterAwake({ dataDir: DATA_DIR, starter: () => cloudPlanTier.starter(), bots: () => store.bots, changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterCaps = createStarterCaps({ starter: () => cloudPlanTier.starter(), awake: starterAwake, waitsOnOthers: (threadId) => coordinator.outstandingFor(threadId).length > 0, laneOwned: (threadId) => burst.laneOwned(threadId), botName: (botId) => store.bot(botId)?.name, pausedLine: (language, limit) => serverLine(language, "server.botPaused", { limit }), refused: () => broadcast({ kind: "config", ...configStatus() }) }); engineMemory.useCap(starterCaps.engine); const botHolds = createBotHolds({ dataDir: DATA_DIR, bots: () => store.bots, line: (language, key, params) => serverLine(language, key, params), changed: () => broadcast({ kind: "config", ...configStatus() }) }); let cloudPower: CloudPower | null = null; // The sleep handshake of a plan that sleeps (server/cloud-power.ts), made just before the server listens.-const teamWelcome = createTeamWelcomeStore(DATA_DIR); const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, invited: (email, by) => teamWelcome.invited(personKey({ id: "", email }), by), memberBrowserOff: () => managedPolicy.remoteAccessRefusal() !== undefined, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); teamSlack?.memberLeft(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE,+const teamWelcome = createTeamWelcomeStore(DATA_DIR); const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, invited: (email, by) => teamWelcome.invited(personKey({ id: "", email }), by), memberBrowserOff: () => managedPolicy.remoteAccessRefusal() !== undefined, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); teamSlack?.memberLeft(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE, routines: (cap) => routines?.health(cap) ?? [], schedule: () => routines?.schedulerState() ?? { unreadable: false, slowStops: 0 },engines: () => registry.instances().map((instance) => ({ instanceId: instance.instanceId, driverKind: instance.driverKind, snapshot: registry.knownSnapshot(instance.instanceId) })),connectors: () => emailHost.health(composio.configured(cfg) ? composio.connectedServices(cfg) : null),browser: () => ({ available: browserReady(undefined), installing: Boolean(browserEngineInstall), interrupted: browserRuntime.interruptedCount() }), firstHour: () => firstHourHooks.health(), ...(engineMemory.enabled ? { room: () => engineMemory.dayPressure() } : {}) } });@@ -8870,10 +8870,9 @@ routines = new RoutineManager({}},interruptGoal: interruptRoutineGroupGoal,- onRunChanged: (run) => { cloudHealth?.noteRoutineRun(run); syncRoutineRunToSource(run); },+ onRunChanged: (run) => { syncRoutineRunToSource(run); }, moveFrozen: () => moveFreeze.frozen(), restartsToReload: () => { if (!CLOUD_HOME) return false; restartRequested = true; gracefulShutdown(); return true; }, onReadable: routinesReadable,onRunCut: (run) => run.groupId ? coordinator.cancelRoom(run.groupId, run.threadId!, ROUTINE_RESTARTED) : coordinator.cancelDirect(run.threadId!, ROUTINE_RESTARTED),onRunFailed: (run, alert) => {- cloudHealth?.noteRoutineRun(run);const bot = store.bot(run.botId);if (!bot || alert === null || run.deliver === "brief") return;const said = alert?.detail ?? run.error, detail = said ? `${run.routineName}: ${said}` : run.routineName;@@ -8890,7 +8889,8 @@ routines = new RoutineManager({notify(buildNotification("routine-deferred", routineSourceOwner(run)?.bot ?? bot, routineSourceThread(run) ?? bot.threadId, detail));},});-phones.adoptRoutines(); routineHolds?.attach(routines); outsideLineage.settle(routines.listRuns(), automationDestinations.eventChat);+/** What start does with the routines once they are made, done again when routines.json could not be read at start and can be now. A Cloud home starts afresh instead (`restartsToReload`): who owns its routines is settled only at start. */ function routinesReadable() { phones.adoptRoutines(); routineHolds?.attach(routines!); outsideLineage.settle(routines!.listRuns(), automationDestinations.eventChat); tellTurnedBackOn(store, routines!.takeTurnedBackOn()); routines!.clearFrozenResultsThreads(); broadcast({ kind: "config", ...configStatus() }); }+phones.adoptRoutines(); routineHolds?.attach(routines); outsideLineage.settle(routines.listRuns(), automationDestinations.eventChat); tellTurnedBackOn(store, routines.takeTurnedBackOn());// Settle Cloud ownership before anything is served and before any routine can run.if (CLOUD_HOME && CLOUD_OWNER_KEY && cloudRoutineAuthors) {cloudHome = settleCloudHome({ file: join(DATA_DIR, "cloud-owner.json"), machineId: CLOUD_HOME.machineId, ownerKey: CLOUD_OWNER_KEY, nobodyKey: CLOUD_NOBODY_KEY,@@ -11710,7 +11710,7 @@ function configStatus() {const eventLogMaxBytes = threadEventLogMaxBytes(cfg);const eventLogRetentionDays = threadEventLogRetentionDays(cfg);return {- cloudStarter: cloudPlanTier.starter(), waitingForRoom: engineMemory.waiting(), planTurns: starterCaps.status(), awakeLimit: starterAwake.limit(), pausedBots: starterAwake.paused(), pausedByPerson: botHolds.state(), heldBots: botHolds.heldBots(), xai: keyStatus(cfg.xai?.key),+ cloudStarter: cloudPlanTier.starter(), waitingForRoom: engineMemory.waiting(), planTurns: starterCaps.status(), awakeLimit: starterAwake.limit(), pausedBots: starterAwake.paused(), pausedByPerson: botHolds.state(), heldBots: botHolds.heldBots(), ...(routines?.schedulerState().unreadable ? { routinesUnreadable: true } : {}), xai: keyStatus(cfg.xai?.key),mistral: keyStatus(cfg.mistral?.key),cerebras: keyStatus(cfg.cerebras?.key),groq: keyStatus(cfg.groq?.key), greenference: keyStatus(cfg.greenference?.key), modelgo: keyStatus(cfg.modelgo?.key),diff --git a/server/routine-attachments.ts b/server/routine-attachments.tsindex a308985954..508c7f1dd1 100644--- a/server/routine-attachments.ts+++ b/server/routine-attachments.ts@@ -1,3 +1,4 @@+import { ROUTINE_RUN_LIMIT_MAX_MINUTES, ROUTINE_RUN_LIMIT_MIN_MINUTES } from "../shared/routines.ts";import { z } from "zod";import type { RoutineContextAttachment } from "../shared/routines.ts";@@ -52,8 +53,8 @@ export function attachmentsMalformed(owners: ReadonlyArray<{ attachments?: unknoexport function cleanTimeoutMinutes(value: unknown): number | undefined {if (value == null) return undefined;- if (typeof value !== "number" || !Number.isInteger(value) || value < 5 || value > 240) {- throw new Error("Run limit must be a whole number from 5 to 240 minutes");+ if (typeof value !== "number" || !Number.isInteger(value) || value < ROUTINE_RUN_LIMIT_MIN_MINUTES || value > ROUTINE_RUN_LIMIT_MAX_MINUTES) {+ throw new Error(`Run limit must be a whole number from ${ROUTINE_RUN_LIMIT_MIN_MINUTES} to ${ROUTINE_RUN_LIMIT_MAX_MINUTES} minutes`);}return value;}diff --git a/server/routine-bounds.test.ts b/server/routine-bounds.test.tsnew file mode 100644index 0000000000..1f66b8c538--- /dev/null+++ b/server/routine-bounds.test.ts@@ -0,0 +1,261 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { ROUTINE_GOAL_RUN_LIMIT_MINUTES, ROUTINE_RUN_LIMIT_MINUTES } from "../shared/routines.ts";+import {+ COUNT_STEP_CAP_MS, COUNT_STEP_MS, RunClock, SCHEDULER_STOP_WAIT_MS, STOP_CONFIRM_WAIT_MS, STOP_RETRY_MS, SlowStops, busyWait, markStop, runLimitAt, runOverLimit,+ withBoundedStops, type StopState,+} from "./routine-bounds.ts";+import { ROUTINE_BUSY_WAIT_MS } from "./routine-recovery.ts";+import type { RoutineManagerOptions, RoutineRun } from "./routines.ts";++const MINUTE = 60_000, HOUR = 60 * MINUTE;+const run = (more: Partial<RoutineRun> = {}): RoutineRun => ({+ id: "run", routineId: "r", routineName: "Check", target: "bot", botId: "bot-1", runOn: "maus", scheduledFor: 0, status: "running", manual: false, createdAt: 0, startedAt: 0, ...more,+});+/** Scheduler passes a minute apart from `from` to `to`, as while a run works. */+const passes = (row: RoutineRun, clock: RunClock, from: number, to: number) => {+ let over = null;+ for (let at = from; at <= to && !over; at += MINUTE) over = runOverLimit(row, clock, at);+ return over;+};++afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); });++describe("the work a run has done", () => {+ it("is added up pass by pass while it is running, from its start", () => {+ const row = run(), clock = new RunClock();+ clock.from(row, "workedMs", 0);+ expect(passes(row, clock, MINUTE, 90 * MINUTE)).toBeNull();+ expect(row.workedMs).toBe(90 * MINUTE);+ });++ it("leaves out the hours a computer slept, and a clock that jumped: one pass adds two steps at most", () => {+ const row = run(), clock = new RunClock();+ clock.from(row, "workedMs", 0);+ passes(row, clock, MINUTE, 10 * MINUTE);+ expect(runOverLimit(row, clock, 10 * MINUTE + 9 * HOUR)).toBeNull();+ expect(row.workedMs).toBe(10 * MINUTE + COUNT_STEP_CAP_MS);+ expect(runOverLimit(row, clock, 10 * MINUTE + 9 * HOUR - 30 * MINUTE)).toBeNull();+ expect(row.workedMs).toBe(10 * MINUTE + COUNT_STEP_CAP_MS);+ expect(COUNT_STEP_CAP_MS).toBe(2 * COUNT_STEP_MS);+ });++ it("leaves out every wait, and counts on from when the run goes back to work", () => {+ const row = run(), clock = new RunClock();+ clock.from(row, "workedMs", 0);+ passes(row, clock, MINUTE, 30 * MINUTE);+ clock.rest(row, 30 * MINUTE + 20_000);+ Object.assign(row, { status: "waiting", waitingSince: 30 * MINUTE + 20_000 });+ expect(row.workedMs).toBe(30 * MINUTE + 20_000);+ expect(passes(row, clock, 31 * MINUTE, 40 * HOUR)).toBeNull();+ expect(row.workedMs).toBe(30 * MINUTE + 20_000);+ clock.work(row, 40 * HOUR);+ expect(row).toMatchObject({ status: "running" });+ passes(row, clock, 40 * HOUR + MINUTE, 40 * HOUR + 10 * MINUTE);+ expect(row.workedMs).toBe(40 * MINUTE + 20_000);+ });++ it("adds nothing for the time before a process first saw the run", () => {+ const row = run({ workedMs: 20 * MINUTE }), clock = new RunClock();+ expect(runOverLimit(row, clock, 50 * HOUR)).toBeNull();+ expect(runOverLimit(row, clock, 50 * HOUR + MINUTE)).toBeNull();+ expect(row.workedMs).toBe(21 * MINUTE);+ });+});++describe("the run limit", () => {+ it("stops a bot's run with no limit of its own once it has worked three hours, and names that limit", () => {+ expect(ROUTINE_RUN_LIMIT_MINUTES).toBe(180);+ const row = run(), clock = new RunClock();+ clock.from(row, "workedMs", 0);+ expect(passes(row, clock, MINUTE, 3 * HOUR - MINUTE)).toBeNull();+ expect(runOverLimit(row, clock, 3 * HOUR)).toEqual({ text: "Stopped: this run ran longer than the 3-hour limit", codes: { errorCode: "routines.server.overLimit", errorParams: { hours: 3 } } });+ });++ it("gives a room goal's run, which stays running across its members' turns, twelve hours", () => {+ expect(ROUTINE_GOAL_RUN_LIMIT_MINUTES).toBe(720);+ const row = run({ target: "room-goal" }), clock = new RunClock();+ clock.from(row, "workedMs", 0);+ expect(passes(row, clock, MINUTE, 12 * HOUR - MINUTE)).toBeNull();+ expect(row.workedMs).toBe(12 * HOUR - MINUTE);+ expect(runOverLimit(row, clock, 12 * HOUR)).toEqual({ text: "Stopped: this run ran longer than the 12-hour limit", codes: { errorCode: "routines.server.overLimit", errorParams: { hours: 12 } } });+ });++ it("does not stop a room goal that says it needs input, however long it waits", () => {+ const row = run({ target: "room-goal", status: "waiting", goalStatus: "needs-input", waitingSince: HOUR, workedMs: HOUR }), clock = new RunClock();+ expect(passes(row, clock, HOUR, 40 * HOUR)).toBeNull();+ expect(runLimitAt(row, 40 * HOUR)).toBeNull();+ });++ it("asks the scheduler back a minute on while a run works under the default limit, sooner when less is left", () => {+ expect(runLimitAt(run({ workedMs: HOUR }), 5 * HOUR)).toBe(5 * HOUR + COUNT_STEP_MS);+ expect(runLimitAt(run({ workedMs: 3 * HOUR - 20_000 }), 5 * HOUR)).toBe(5 * HOUR + 20_000);+ expect(runLimitAt(run({ workedMs: 4 * HOUR }), 5 * HOUR)).toBe(5 * HOUR);+ expect(runLimitAt(run({ status: "waiting", waitingSince: HOUR }), 5 * HOUR)).toBeNull();+ });++ it("leaves a queued or finished run alone", () => {+ const clock = new RunClock();+ for (const status of ["queued", "completed", "failed", "missed", "cancelled"] as const) {+ expect(runOverLimit(run({ status, workedMs: 9 * HOUR }), clock, 30 * HOUR)).toBeNull();+ expect(runLimitAt(run({ status }), 30 * HOUR)).toBeNull();+ }+ expect(runOverLimit(run({ startedAt: undefined }), clock, 30 * HOUR)).toBeNull();+ });++ it("keeps a routine's own limit, in its own words, counted as it always was", () => {+ const clock = new RunClock();+ const own = run({ timeoutMinutes: 10 });+ expect(runOverLimit(own, clock, 10 * MINUTE - 1)).toBeNull();+ expect(runOverLimit(own, clock, 10 * MINUTE)).toEqual({ text: "Stopped after reaching the 10-minute run limit", codes: { errorCode: undefined, errorParams: undefined } });+ const long = run({ timeoutMinutes: 1_440 });+ expect(runOverLimit(long, clock, 24 * HOUR - 1)).toBeNull();+ expect(runOverLimit(long, clock, 24 * HOUR)?.text).toBe("Stopped after reaching the 1440-minute run limit");+ const handedOn = run({ timeoutMinutes: 10, status: "waiting", waitingSince: MINUTE });+ expect(runOverLimit(handedOn, clock, 10 * MINUTE)?.text).toBe("Stopped after reaching the 10-minute run limit");+ expect(runLimitAt(handedOn, 5 * MINUTE)).toBe(10 * MINUTE);+ const asked = run({ timeoutMinutes: 10, status: "waiting", waitingSince: MINUTE, asked: { approval: false, subject: "Which?", since: MINUTE } });+ expect(runOverLimit(asked, clock, 5 * HOUR)).toBeNull();+ expect(runLimitAt(asked, 5 * HOUR)).toBeNull();+ });+});++describe("a queued run behind its busy bot", () => {+ const queued = (more: Partial<RoutineRun> = {}) => run({ status: "queued", startedAt: undefined, ...more });+ const seen = (row: RoutineRun, clock: RunClock, from: number, to: number, counts = true) => {+ let last = busyWait(row, clock, counts, from);+ for (let at = from + 10_000; at <= to && !last.missed; at += 10_000) last = busyWait(row, clock, counts, at);+ return last;+ };++ it("is given up once the passes that saw it busy add up to an hour, with the reason", () => {+ const row = queued(), clock = new RunClock();+ expect(busyWait(row, clock, true, 1_000)).toEqual({ changed: true, missed: null });+ expect(row.busyMs).toBe(0);+ expect(seen(row, clock, 1_000, 1_000 + ROUTINE_BUSY_WAIT_MS - 10_000).missed).toBeNull();+ expect(busyWait(row, clock, true, 1_000 + ROUTINE_BUSY_WAIT_MS).missed).toEqual({ text: "Did not run: the bot was busy for more than 60 minutes",+ codes: { errorCode: "routines.server.busyTooLong", errorParams: { minutes: 60 } } });+ });++ it("is worth saving once a minute, not at every pass", () => {+ const row = queued(), clock = new RunClock();+ const changes = [0, 10, 20, 30, 40, 50, 60, 70].map((seconds) => busyWait(row, clock, true, seconds * 1_000).changed);+ expect(changes).toEqual([true, false, false, false, false, false, true, false]);+ });++ it("does not count the hours a computer slept, or the time a process was down", () => {+ const row = queued(), clock = new RunClock();+ seen(row, clock, 0, 10 * MINUTE);+ expect(busyWait(row, clock, true, 10 * MINUTE + 8 * HOUR).missed).toBeNull();+ expect(row.busyMs).toBe(10 * MINUTE + COUNT_STEP_CAP_MS);+ const afterRestart = new RunClock();+ expect(busyWait(row, afterRestart, true, 90 * HOUR).missed).toBeNull();+ expect(row.busyMs).toBe(10 * MINUTE + COUNT_STEP_CAP_MS);+ });++ it("drops the count as soon as it is not that wait: a run of checked items, an event's or a person's run, or one behind its own routine", () => {+ const row = queued(), clock = new RunClock();+ seen(row, clock, 0, 30 * MINUTE);+ expect(busyWait(row, clock, false, 31 * MINUTE)).toEqual({ changed: true, missed: null });+ expect(row).not.toHaveProperty("busyMs");+ expect(seen(row, clock, 31 * MINUTE, 30 * HOUR, false)).toEqual({ changed: false, missed: null });+ expect(seen(row, clock, 30 * HOUR, 30 * HOUR + 59 * MINUTE).missed).toBeNull();+ expect(row.busyMs).toBe(59 * MINUTE);+ });+});++describe("stopping a turn from the scheduler", () => {+ const base = { botState: () => "ready" as const, createTask: () => null, startTurn: async () => {} } satisfies RoutineManagerOptions;+ const watch = (now: () => number = Date.now) => {+ const states: Array<[string, StopState]> = [];+ return { states, slow: new SlowStops(now, (threadId, state) => states.push([threadId, state])) };+ };++ it("goes on after ten seconds when the engine never answers, counts it, and holds the conversation as not confirmed", async () => {+ vi.useFakeTimers();+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const { slow, states } = watch();+ const options = withBoundedStops({ ...base, interruptTurn: () => new Promise<void>(() => {}), interruptGoal: () => new Promise<void>(() => {}) }, slow);+ let done = 0;+ void options.interruptTurn!("bot-1", "thread-1").then(() => { done += 1; });+ void options.interruptGoal!("room-1", "thread-2", { status: "stopped", detail: "x" }).then(() => { done += 1; });+ await vi.advanceTimersByTimeAsync(SCHEDULER_STOP_WAIT_MS - 1);+ expect([done, slow.count]).toEqual([0, 0]);+ await vi.advanceTimersByTimeAsync(1);+ expect([done, slow.count]).toEqual([2, 2]);+ expect(states).toEqual([["thread-1", "pending"], ["thread-2", "pending"]]);+ expect([slow.holds("thread-1"), slow.holds("thread-2"), slow.holds("thread-3"), slow.holds(undefined)]).toEqual([true, true, false, false]);+ expect(warn).toHaveBeenCalledTimes(2);+ expect(vi.getTimerCount()).toBe(0);+ });++ it("confirms the stop when it returns late, or when the turn's end arrives, and lets go then", async () => {+ vi.useFakeTimers();+ vi.spyOn(console, "warn").mockImplementation(() => {});+ const { slow, states } = watch();+ let finish = () => {};+ const options = withBoundedStops({ ...base, interruptTurn: (_botId, threadId) => threadId === "late" ? new Promise<void>((resolve) => { finish = resolve; }) : new Promise<void>(() => {}) }, slow);+ void options.interruptTurn!("bot-1", "late");+ void options.interruptTurn!("bot-1", "event");+ await vi.advanceTimersByTimeAsync(SCHEDULER_STOP_WAIT_MS);+ finish();+ await vi.advanceTimersByTimeAsync(0);+ slow.confirmed("event");+ slow.confirmed("never-stopped");+ expect(states).toEqual([["late", "pending"], ["event", "pending"], ["late", "confirmed"], ["event", "confirmed"]]);+ expect([slow.holds("late"), slow.holds("event")]).toEqual([false, false]);+ });++ it("sends the stop again each minute, and gives up after five", () => {+ vi.spyOn(console, "warn").mockImplementation(() => {});+ let now = 0;+ const { slow, states } = watch(() => now);+ slow.timedOut("thread-1");+ now = STOP_RETRY_MS - 1; expect(slow.sweep()).toEqual([]);+ now = STOP_RETRY_MS; expect(slow.sweep()).toEqual(["thread-1"]);+ now = STOP_RETRY_MS + 1_000; expect(slow.sweep()).toEqual([]);+ slow.timedOut("thread-1");+ now = 2 * STOP_RETRY_MS; expect(slow.sweep()).toEqual(["thread-1"]);+ now = STOP_CONFIRM_WAIT_MS - 1; slow.sweep(); expect(slow.holds("thread-1")).toBe(true);+ now = STOP_CONFIRM_WAIT_MS; expect(slow.sweep()).toEqual([]);+ expect(slow.holds("thread-1")).toBe(false);+ expect(states).toEqual([["thread-1", "pending"], ["thread-1", "unconfirmed"]]);+ expect(slow.count).toBe(2);+ });++ it("returns as soon as the stop does, passes a failure on, and leaves no timer behind", async () => {+ vi.useFakeTimers();+ const { slow, states } = watch();+ const stops: string[] = [];+ const source: RoutineManagerOptions = { ...base, interruptTurn: async (_botId, threadId) => { stops.push(threadId); if (threadId === "bad") throw new Error("gone"); } };+ const options = withBoundedStops(source, slow);+ await options.interruptTurn!("bot-1", "thread-1");+ await expect(options.interruptTurn!("bot-1", "bad")).rejects.toThrow("gone");+ expect([stops, slow.count, states, vi.getTimerCount()]).toEqual([["thread-1", "bad"], 0, [], 0]);+ });++ it("stays a live view of the options: one set later is used, and one never set stays unset", async () => {+ const source: RoutineManagerOptions = { ...base };+ const options = withBoundedStops(source, watch().slow);+ expect(options.interruptTurn).toBeUndefined();+ expect(options.botState("bot-1")).toBe("ready");+ const stops: string[] = [];+ source.interruptTurn = async (_botId, threadId) => { stops.push(threadId); };+ source.pausedText = () => "paused";+ await options.interruptTurn!("bot-1", "thread-9");+ expect([stops, options.pausedText?.("bot-1")]).toEqual([["thread-9"], "paused"]);+ });++ it("marks the finished run's row while its stop is outstanding, clears the mark once confirmed, and says so for good when it never is", () => {+ const row = run({ status: "failed", error: "Stopped after reaching the 30-minute run limit" });+ expect(markStop(row, "pending")).toBe(true);+ expect(row).toMatchObject({ attention: "Its turn has not confirmed that it stopped. The next run waits for that, up to 5 minutes.", attentionCode: "routines.server.stopPending", attentionParams: { minutes: 5 } });+ expect(markStop(row, "confirmed")).toBe(true);+ expect(row.attention).toBeUndefined();+ expect(markStop(row, "confirmed")).toBe(false);+ markStop(row, "pending");+ expect(markStop(row, "unconfirmed")).toBe(true);+ expect(row).toMatchObject({ attention: "Its turn never confirmed that it stopped, so the next run started without that.", attentionCode: "routines.server.stopUnconfirmed", error: "Stopped after reaching the 30-minute run limit" });+ expect(markStop(run({ status: "running" }), "pending")).toBe(false);+ });+});diff --git a/server/routine-bounds.ts b/server/routine-bounds.tsnew file mode 100644index 0000000000..5b714ff210--- /dev/null+++ b/server/routine-bounds.ts@@ -0,0 +1,183 @@+// Nothing a bot does on its own holds a routine's schedule up without end: a started run stops after a limit of work, a+// scheduled run queued behind its busy bot is given up after an hour, and stopping a turn never keeps the scheduler+// from its other routines. Each ends with its reason on the run's row. The work and the busy wait are added up one+// scheduler pass at a time, each step capped, so the hours a computer slept, or a clock that jumped, are in neither.+import { ROUTINE_GOAL_RUN_LIMIT_MINUTES, ROUTINE_RUN_LIMIT_MINUTES } from "../shared/routines.ts";+import { DUE_CLOCK_MS } from "./due-timer.ts";+import { codedLine, fittedLine, type RoutineLine } from "./routine-lines.ts";+import { ROUTINE_BUSY_WAIT_MS } from "./routine-recovery.ts";+import { activeMs } from "./routine-waits.ts";+import type { RoutineManagerOptions, RoutineRun } from "./routines.ts";++/** How often the scheduler passes while a run works, to count that work. */+export const COUNT_STEP_MS = DUE_CLOCK_MS;+/** The most one pass adds to a count: a longer gap is the computer asleep or the clock moved, not work. */+export const COUNT_STEP_CAP_MS = 2 * COUNT_STEP_MS;+/** How long the scheduler waits for a turn to stop before it goes on to its other work. */+export const SCHEDULER_STOP_WAIT_MS = 10_000;+/** After a stop that did not finish in that time, its routine starts no new run until the stop is confirmed, or this long has passed. */+export const STOP_CONFIRM_WAIT_MS = 5 * 60_000;+/** While it waits, the stop is sent again this often. */+export const STOP_RETRY_MS = 60_000;++type Counted = "workedMs" | "busyMs";++/** Adds up a run's `workedMs` (time in status running since its current start) and `busyMs` (time a scheduled run has+ * been seen queued behind its busy bot), pass by pass. When each was last counted is kept in memory only, so the time a+ * process was down is in neither. */+export class RunClock {+ private readonly counted = new WeakMap<RoutineRun, Partial<Record<Counted, number>>>();++ /** Adds the time since `field` was last counted, at most COUNT_STEP_CAP_MS; the first sight of a run adds nothing. The total. */+ count(run: RoutineRun, field: Counted, now: number): number {+ const at = this.counted.get(run) ?? {}, since = at[field];+ this.counted.set(run, { ...at, [field]: now });+ run[field] = (run[field] ?? 0) + (since === undefined ? 0 : Math.min(COUNT_STEP_CAP_MS, Math.max(0, now - since)));+ return run[field];+ }++ /** Counting starts from `now`: nothing before it is added. */+ from(run: RoutineRun, field: Counted, now: number): void { this.counted.set(run, { ...this.counted.get(run), [field]: now }); }++ /** Counting stops. `forget` drops the total too. */+ stop(run: RoutineRun, field: Counted, forget = false): void {+ const { [field]: _stopped, ...rest } = this.counted.get(run) ?? {};+ this.counted.set(run, rest);+ if (forget) delete run[field];+ }++ /** The run goes to work, at its start or after a wait. */+ work(run: RoutineRun, now: number): void {+ this.from(run, "workedMs", now);+ Object.assign(run, { status: "running", attention: undefined } satisfies Partial<RoutineRun>);+ }++ /** The run begins to wait: its work so far is counted, and the wait is not. */+ rest(run: RoutineRun, now: number): void {+ if (run.status === "running") this.count(run, "workedMs", now);+ this.stop(run, "workedMs");+ }+}++type Started = Pick<RoutineRun, "status" | "startedAt" | "timeoutMinutes" | "waitedMs" | "workedMs" | "asked" | "target">;+const defaultLimitMs = (run: Pick<RoutineRun, "target">) => (run.target === "room-goal" ? ROUTINE_GOAL_RUN_LIMIT_MINUTES : ROUTINE_RUN_LIMIT_MINUTES) * 60_000;+const started = (run: Started) => run.startedAt != null && (run.status === "running" || run.status === "waiting");++/** When the scheduler must next look at a started run: when a routine's own limit is reached, or, under the default+ * limit, at the next step of counting its work. Null while neither applies (it is not started, it waits under the+ * default limit, or a request of its own is open, which no limit counts). */+export function runLimitAt(run: Started, now: number): number | null {+ if (!started(run)) return null;+ if (run.timeoutMinutes != null) return run.asked ? null : now + Math.max(0, run.timeoutMinutes * 60_000 - activeMs(run, now));+ return run.status === "running" ? now + Math.min(COUNT_STEP_MS, Math.max(0, defaultLimitMs(run) - (run.workedMs ?? 0))) : null;+}++/** Counts this pass's work for a running run, and says why a started run must stop now; null while it is within its+ * limit. A routine's own limit counts as it always has (`activeMs`: the time since the run started, less its open+ * approvals and questions). The default one counts work only, so it never ends a run that waits. */+export function runOverLimit(run: RoutineRun, clock: RunClock, now: number): RoutineLine | null {+ if (!started(run)) return null;+ const worked = run.status === "running" ? clock.count(run, "workedMs", now) : run.workedMs ?? 0;+ if (run.timeoutMinutes != null) return activeMs(run, now) >= run.timeoutMinutes * 60_000 ? fittedLine("error", `Stopped after reaching the ${run.timeoutMinutes}-minute run limit`, undefined) : null;+ return run.status === "running" && worked >= defaultLimitMs(run) ? codedLine("error", "routines.server.overLimit", { hours: defaultLimitMs(run) / 3_600_000 }) : null;+}++/** A queued run that cannot start because its bot is busy. While `counts` (a scheduled occurrence, not one of checked+ * items, not behind its own routine's earlier run), the passes that see it so add up in `busyMs`, and the line is why it+ * is given up once that reaches ROUTINE_BUSY_WAIT_MS: its routine's next occurrence does the work. Any other run waits+ * as long as it takes (nothing comes after an event's or a person's run), and `busyMs` is dropped. `changed`: worth saving. */+export function busyWait(run: RoutineRun, clock: RunClock, counts: boolean, now: number): { changed: boolean; missed: RoutineLine | null } {+ const before = run.busyMs;+ if (!counts) {+ clock.stop(run, "busyMs", true);+ return { changed: before !== undefined, missed: null };+ }+ const total = clock.count(run, "busyMs", now);+ const changed = before === undefined || Math.floor(before / 60_000) !== Math.floor(total / 60_000);+ return { changed, missed: total >= ROUTINE_BUSY_WAIT_MS ? codedLine("error", "routines.server.busyTooLong", { minutes: ROUTINE_BUSY_WAIT_MS / 60_000 }) : null };+}++export type StopState = "pending" | "confirmed" | "unconfirmed";++/** Stops of a turn that did not finish in SCHEDULER_STOP_WAIT_MS, by conversation: the old turn may still be running, so+ * its routine starts nothing new until the stop is confirmed (the stop returns, or the turn's end arrives) or+ * STOP_CONFIRM_WAIT_MS passes. `changed` hears each state, to mark the run's row. */+export class SlowStops {+ /** How often a stop did not finish in time, since this process started. */+ count = 0;+ private readonly open = new Map<string, { since: number; triedAt: number }>();+ private readonly now: () => number;+ private readonly changed: (threadId: string, state: StopState) => void;++ constructor(now: () => number, changed: (threadId: string, state: StopState) => void) {+ this.now = now;+ this.changed = changed;+ }++ timedOut(threadId: string): void {+ this.count += 1;+ console.warn(`routines: stopping a turn did not finish in ${SCHEDULER_STOP_WAIT_MS / 1000} s; the scheduler went on without it`);+ if (this.open.has(threadId)) return;+ this.open.set(threadId, { since: this.now(), triedAt: this.now() });+ this.changed(threadId, "pending");+ }++ confirmed(threadId: string): void {+ if (this.open.delete(threadId)) this.changed(threadId, "confirmed");+ }++ holds(threadId: string | undefined): boolean {+ return threadId !== undefined && this.open.has(threadId);+ }++ /** Gives up on stops outstanding for STOP_CONFIRM_WAIT_MS; the conversations whose stop is due to be sent again. */+ sweep(): string[] {+ const now = this.now(), again: string[] = [];+ for (const [threadId, stop] of this.open) {+ if (now - stop.since >= STOP_CONFIRM_WAIT_MS) {+ this.open.delete(threadId);+ this.changed(threadId, "unconfirmed");+ } else if (now - stop.triedAt >= STOP_RETRY_MS) {+ stop.triedAt = now;+ again.push(threadId);+ }+ }+ return again;+ }+}++/** Marks a finished run's row while its stop is outstanding, and says so for good when it was never confirmed; a stop+ * confirmed in time leaves no mark. False when the row is as it was. */+export function markStop(run: RoutineRun, state: StopState): boolean {+ if (["queued", "running", "waiting"].includes(run.status)) return false;+ if (state === "confirmed") {+ if (run.attentionCode !== "routines.server.stopPending") return false;+ Object.assign(run, { attention: undefined, attentionCode: undefined, attentionParams: undefined } satisfies Partial<RoutineRun>);+ return true;+ }+ const line = state === "pending" ? codedLine("attention", "routines.server.stopPending", { minutes: STOP_CONFIRM_WAIT_MS / 60_000 }) : codedLine("attention", "routines.server.stopUnconfirmed");+ Object.assign(run, line.codes, { attention: line.text } satisfies Partial<RoutineRun>);+ return true;+}++async function within(work: Promise<void>, slow: SlowStops, threadId: string): Promise<void> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const late = new Promise<"late">((resolve) => { timer = setTimeout(() => resolve("late"), SCHEDULER_STOP_WAIT_MS); timer.unref?.(); });+ try {+ if (await Promise.race([work, late]) !== "late") return slow.confirmed(threadId);+ slow.timedOut(threadId);+ work.then(() => slow.confirmed(threadId), () => {});+ } finally {+ clearTimeout(timer);+ }+}++/** A live view of the same options in which each stop of a turn or goal is given SCHEDULER_STOP_WAIT_MS: an engine that+ * never answers its interrupt is noted in `slow` and left behind, while the stop itself keeps going. */+export function withBoundedStops(options: RoutineManagerOptions, slow: SlowStops): RoutineManagerOptions {+ return Object.create(options, {+ interruptTurn: { get: () => options.interruptTurn && (async (botId: string, threadId: string) => within(options.interruptTurn!(botId, threadId), slow, threadId)) },+ interruptGoal: { get: () => options.interruptGoal && (async (groupId: string | undefined, threadId: string, outcome?: { status: "stopped" | "limit-reached"; detail: string }) =>+ within(options.interruptGoal!(groupId, threadId, outcome), slow, threadId)) },+ }) as RoutineManagerOptions;+}diff --git a/server/routine-due.test.ts b/server/routine-due.test.tsindex 684f491b3e..f423ab1b1c 100644--- a/server/routine-due.test.ts+++ b/server/routine-due.test.ts@@ -56,9 +56,9 @@ describe("schedulerDueOf: when this process's scheduler next has work", () => {type Run = Parameters<typeof schedulerDueOf>[1][number];const run = (fields: Partial<Run>) => ({ status: "running", ...fields }) as Run;- it("is null with nothing enabled, queued or limited", () => {+ it("is null with nothing enabled, queued or started", () => {expect(schedulerDueOf([], [], NOW, NOW)).toBeNull();- expect(schedulerDueOf([{ enabled: false, nextRunAt: NOW }], [run({ status: "completed" }), run({ startedAt: NOW })], NOW, NOW)).toBeNull();+ expect(schedulerDueOf([{ enabled: false, nextRunAt: NOW }], [run({ status: "completed" }), run({ status: "failed", startedAt: NOW })], NOW, NOW)).toBeNull();});it("the next run, a check no sooner than checks may start, and a check's meeting wake", () => {@@ -79,5 +79,11 @@ describe("schedulerDueOf: when this process's scheduler next has work", () => {expect(schedulerDueOf([], [run({ startedAt: NOW - 10 * MINUTE, timeoutMinutes: 30 })], NOW, NOW)).toBe(NOW + 20 * MINUTE);expect(schedulerDueOf([], [run({ status: "waiting", startedAt: NOW - 10 * MINUTE, waitedMs: 5 * MINUTE, timeoutMinutes: 30 })], NOW, NOW)).toBe(NOW + 25 * MINUTE);expect(schedulerDueOf([], [run({ startedAt: NOW - 40 * MINUTE, timeoutMinutes: 30 })], NOW, NOW)).toBe(NOW);+ // Under the default limit the scheduler comes back each minute to count the run's work, sooner when less is left.+ expect(schedulerDueOf([], [run({ startedAt: NOW - 10 * MINUTE, target: "bot" })], NOW, NOW)).toBe(NOW + MINUTE);+ expect(schedulerDueOf([], [run({ startedAt: NOW - 400 * MINUTE, workedMs: 180 * MINUTE - 20_000, target: "bot" })], NOW, NOW)).toBe(NOW + 20_000);+ expect(schedulerDueOf([], [run({ startedAt: NOW - 400 * MINUTE, workedMs: 180 * MINUTE - 20_000, target: "room-goal" })], NOW, NOW)).toBe(NOW + MINUTE);+ expect(schedulerDueOf([], [run({ status: "waiting", startedAt: NOW - 400 * MINUTE })], NOW, NOW)).toBeNull();+ expect(schedulerDueOf([], [run({ status: "waiting", startedAt: NOW - 10 * MINUTE, timeoutMinutes: 30, asked: { approval: true, subject: "to run it", since: NOW - MINUTE } })], NOW, NOW)).toBeNull();});});diff --git a/server/routine-due.ts b/server/routine-due.tsindex 4f9d08df17..4f12558177 100644--- a/server/routine-due.ts+++ b/server/routine-due.ts@@ -1,7 +1,7 @@// When routines next need this machine: the desktop's keep-awake (`wakeHold`) and a Cloud home's sleep check// (server/cloud-power.ts). Pure over RoutineManager's routines and runs.import type { Routine, RoutineRun } from "./routines.ts";-import { activeMs } from "./routine-waits.ts";+import { runLimitAt } from "./routine-bounds.ts";type Due = Pick<Routine, "enabled" | "nextRunAt" | "checks" | "wakeAt" | "checkedAt">;type Run = Pick<RoutineRun, "status" | "retryAt">;@@ -42,9 +42,9 @@ export function nextDueOf(routines: readonly Due[], runs: readonly Run[], now: nreturn due.length ? Math.min(...due) : null;}-type Started = Run & Pick<RoutineRun, "startedAt" | "timeoutMinutes" | "waitedMs" | "asked">;+type Started = Run & Pick<RoutineRun, "startedAt" | "timeoutMinutes" | "waitedMs" | "workedMs" | "asked" | "target">;/** When this process's scheduler next has work: a routine's next run, or its checks once `checksFrom` has passed; a queued- * run (now, or its retry); a started run reaching its time limit. `skip` leaves out routines whose target is gone. */+ * run (now, or its retry); a started run reaching its limit (routine-bounds.ts). `skip` leaves out routines whose target is gone. */export function schedulerDueOf<R extends Due>(routines: readonly R[], runs: readonly Started[], now: number, checksFrom: number, skip: (routine: R) => boolean = () => false): number | null {let at = Infinity;for (const routine of routines) {@@ -54,9 +54,7 @@ export function schedulerDueOf<R extends Due>(routines: readonly R[], runs: read}for (const run of runs) {if (run.status === "queued") at = Math.min(at, run.retryAt ?? now);- else if ((run.status === "running" || run.status === "waiting") && run.startedAt != null && run.timeoutMinutes != null) {- at = Math.min(at, now + Math.max(0, run.timeoutMinutes * 60_000 - activeMs(run, now)));- }+ else at = Math.min(at, runLimitAt(run, now) ?? Infinity);}return at === Infinity ? null : at;}diff --git a/server/routine-execution.ts b/server/routine-execution.tsindex b8c48434d4..b4a4fa782a 100644--- a/server/routine-execution.ts+++ b/server/routine-execution.ts@@ -136,16 +136,9 @@ export function routineFailure(error: string | undefined, stopReason: string | n/** How long a routine may be held up before it acts: a deferred run tells the owner, a waiting run gives way. */export const ROUTINE_DEFERRAL_NOTICE_MS = 30 * 60_000;export const ROUTINE_SUPERSEDED = "Stopped waiting: the next scheduled run of this routine started instead";-export const ROUTINE_SKIPPED_WHILE_WAITING = "Skipped because the previous run of this routine is still waiting";/** Waiting since a notice window before its routine's next occurrence came due, with no hand-off still open: that occurrence starts instead. */export function supersededBy(dueAt: number, run: Pick<RoutineRun, "status" | "waitingSince" | "threadId">, handedOffWorkLive?: (threadId: string) => boolean): boolean {return run.status === "waiting" && run.waitingSince !== undefined && run.waitingSince <= dueAt - ROUTINE_DEFERRAL_NOTICE_MS &&!(run.threadId && handedOffWorkLive?.(run.threadId));}--/** Once per wait: the first occurrence skipped after the waiting run blocking it passed the notice window. */-export function skipNeedsNotice(dueAt: number, waitingSince: number, previousSkipAt: number | undefined): boolean {- const staleAt = waitingSince + ROUTINE_DEFERRAL_NOTICE_MS;- return dueAt >= staleAt && (previousSkipAt === undefined || previousSkipAt < staleAt);-}diff --git a/server/routine-file.test.ts b/server/routine-file.test.tsnew file mode 100644index 0000000000..21988d7219--- /dev/null+++ b/server/routine-file.test.ts@@ -0,0 +1,60 @@+import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { basename, dirname, join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { keepUnreadableAside, readRoutineFile } from "./routine-file.ts";++const dirs: string[] = [];+const tempFile = () => { const dir = mkdtempSync(join(tmpdir(), "omb-routine-file-")); dirs.push(dir); return join(dir, "routines.json"); };+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++describe("reading routines.json", () => {+ it("tells a file that is not there from one that cannot be read", () => {+ const file = tempFile();+ expect(readRoutineFile(file, 0)).toEqual({ state: "missing" });+ writeFileSync(file, '{"version":1,"routines":[{"name":"Secret plan"');+ expect(readRoutineFile(file, 0)).toEqual({ state: "unreadable", reason: "invalid JSON" });+ writeFileSync(file, "[]");+ expect(readRoutineFile(file, 0)).toEqual({ state: "unreadable", reason: "Invalid routines file" });+ writeFileSync(file, JSON.stringify({ version: 1, routines: [], runs: "none" }));+ expect(readRoutineFile(file, 0)).toEqual({ state: "unreadable", reason: "Invalid routines file: runs is not a list" });+ });++ it("reads a saved file back, with the text it was read from", () => {+ const file = tempFile();+ const text = JSON.stringify({ version: 1, frozenResultsCleared: true, routines: [], runs: [], holds: ["no_connections"], startupLaunchId: "launch-1" });+ writeFileSync(file, text);+ expect(readRoutineFile(file, 0)).toMatchObject({ state: "ok", text, routines: [], runs: [], frozenPending: false, holds: ["no_connections"], startupLaunchId: "launch-1", malformedAttachments: false, noStartOffsChecked: false });+ writeFileSync(file, JSON.stringify({ version: 1, routines: [], runs: [], noStartOffsChecked: true }));+ expect(readRoutineFile(file, 0)).toMatchObject({ state: "ok", noStartOffsChecked: true, startupLaunchId: undefined });+ });+});++describe("an unreadable routines.json", () => {+ it("is copied beside itself once per content, private to its owner, and stays where it is", () => {+ const file = tempFile();+ const broken = '{"version":1,"routines":[{"name":"Morning check"';+ writeFileSync(file, broken);+ const aside = keepUnreadableAside(file)!;+ expect(aside).toMatch(/routines\.json\.unreadable-[0-9a-f]{12}$/);+ expect(readFileSync(aside, "utf8")).toBe(broken);+ expect(readFileSync(file, "utf8")).toBe(broken);+ if (process.platform !== "win32") expect(statSync(aside).mode & 0o777).toBe(0o600);+ expect(keepUnreadableAside(file)).toBe(aside);+ expect(readdirSync(dirname(file)).sort()).toEqual(["routines.json", basename(aside)].sort());+ });++ it("keeps a copy of each different content, up to five", () => {+ const file = tempFile();+ for (let index = 0; index < 5; index += 1) { writeFileSync(file, `{broken ${index}`); expect(keepUnreadableAside(file)).not.toBeNull(); }+ writeFileSync(file, "{broken again");+ expect(keepUnreadableAside(file)).toBeNull();+ expect(readdirSync(dirname(file)).filter((name) => name.includes(".unreadable-"))).toHaveLength(5);+ expect(readFileSync(file, "utf8")).toBe("{broken again");+ });++ it("answers null when there is no file to copy", () => {+ expect(keepUnreadableAside(tempFile())).toBeNull();+ });+});diff --git a/server/routine-file.ts b/server/routine-file.tsnew file mode 100644index 0000000000..a0280a5255--- /dev/null+++ b/server/routine-file.ts@@ -0,0 +1,87 @@+// routines.json as it is read at start, and again while it cannot be read. A file that is there but unreadable is never+// taken for an empty one: the caller refuses every save while it stays so, a copy is set aside the first time each+// unreadable content is seen, and the read is tried again until it works.+import { createHash } from "node:crypto";+import { chmodSync, constants, copyFileSync, existsSync, readdirSync, readFileSync } from "node:fs";+import { basename, dirname } from "node:path";++import type { RoutineHoldCause } from "../shared/routines.ts";+import { attachmentsMalformed } from "./routine-attachments.ts";+import { loadEventReceipts, type EventRunReceipt } from "./routine-event-receipts.ts";+import { holdCauses } from "./routine-holds.ts";+import { loadRequestReceipts, loadRoutine, loadRun } from "./routine-load.ts";+import { loadOwnerNotices, type RoutineOwnerNotice } from "./routine-recovery.ts";+import type { Routine, RoutineRequestReceipt, RoutineRun } from "./routines.ts";++/** While routines.json cannot be read, the read is tried again this often. */+export const UNREADABLE_RETRY_MS = 60_000;+/** Copies of unreadable content kept beside the file; a further one is not copied. */+const ASIDE_COPIES = 5;++export interface RoutineFileContents {+ text: string;+ routines: Routine[];+ /** Rows whose schedule could not load: written back unchanged. */+ unloadedRoutines: Routine[];+ runs: RoutineRun[];+ malformedAttachments: boolean;+ routineRequestReceipts: RoutineRequestReceipt[];+ webhookRunReceipts: EventRunReceipt[];+ frozenPending: boolean;+ ownerNotices: RoutineOwnerNotice[];+ holds: RoutineHoldCause[];+ startupLaunchId: string | undefined;+ /** The one look for routines an earlier version switched off (routine-no-start.ts) was taken. */+ noStartOffsChecked: boolean;+}++/** `reason` never quotes the file: a JSON error can echo a fragment of it. */+export type RoutineFileRead = { state: "missing" } | { state: "unreadable"; reason: string } | ({ state: "ok" } & RoutineFileContents);++export function readRoutineFile(file: string, now: number): RoutineFileRead {+ try {+ const text = readFileSync(file, "utf8"), disk = JSON.parse(text) as Record<string, unknown> | null;+ if (disk === null || typeof disk !== "object" || Array.isArray(disk)) throw new Error("Invalid routines file");+ for (const key of ["routines", "runs", "routineRequestReceipts", "webhookRunReceipts"]) {+ if (key in disk && !Array.isArray(disk[key])) throw new Error(`Invalid routines file: ${key} is not a list`);+ }+ const saved = (disk.routines ?? []) as Routine[], unloadedRoutines: Routine[] = [];+ const routines = saved.flatMap((routine) => {+ const loaded = loadRoutine(routine, now);+ if (loaded) return [loaded];+ console.warn(`routines: keeping ${String(routine.id)} on disk unscheduled; its schedule could not load`);+ unloadedRoutines.push(routine);+ return [];+ });+ const runs = ((disk.runs ?? []) as RoutineRun[]).map(loadRun);+ return {+ state: "ok", text, routines, unloadedRoutines, runs,+ malformedAttachments: attachmentsMalformed([...saved, ...((disk.runs ?? []) as RoutineRun[])]),+ routineRequestReceipts: loadRequestReceipts(disk.routineRequestReceipts),+ webhookRunReceipts: loadEventReceipts(disk.webhookRunReceipts, runs, now),+ frozenPending: disk.frozenResultsCleared !== true,+ ownerNotices: loadOwnerNotices(disk.ownerNotices),+ holds: holdCauses(disk.holds),+ startupLaunchId: typeof disk.startupLaunchId === "string" ? disk.startupLaunchId : undefined,+ noStartOffsChecked: disk.noStartOffsChecked === true,+ };+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { state: "missing" };+ return { state: "unreadable", reason: error instanceof SyntaxError ? "invalid JSON" : error instanceof Error ? error.message : "unable to read routines" };+ }+}++/** Copies the unreadable file beside itself, named by its content so the same content is copied once. Returns the copy's+ * path, or null when there is nothing to copy or the copy cannot be made. The file itself stays where it is. */+export function keepUnreadableAside(file: string): string | null {+ try {+ const aside = `${file}.unreadable-${createHash("sha256").update(readFileSync(file)).digest("hex").slice(0, 12)}`;+ if (existsSync(aside)) return aside;+ if (readdirSync(dirname(file)).filter((name) => name.startsWith(`${basename(file)}.unreadable-`)).length >= ASIDE_COPIES) return null;+ copyFileSync(file, aside, constants.COPYFILE_EXCL);+ chmodSync(aside, 0o600);+ return aside;+ } catch {+ return null;+ }+}diff --git a/server/routine-health.test.ts b/server/routine-health.test.tsnew file mode 100644index 0000000000..1ccb5cffcf--- /dev/null+++ b/server/routine-health.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from "vitest";++import { routineHealthOf } from "./routine-health.ts";+import type { RoutineRun } from "./routines.ts";++const run = (routineId: string, status: RoutineRun["status"], finishedAt: number, more: Partial<RoutineRun> = {}): RoutineRun => ({+ id: `${routineId}-${finishedAt}`, routineId, routineName: "Planted name", prompt: "Planted prompt", target: "bot", botId: "bot-1", runOn: "maus",+ scheduledFor: finishedAt, status, manual: false, createdAt: finishedAt, finishedAt, ...more,+});+const on = (id: string) => ({ id, enabled: true });++describe("a routine's health, from its saved run rows", () => {+ it("counts the failed and missed runs since the last one that completed, newest first", () => {+ const runs = [run("a", "completed", 10), run("a", "failed", 20), run("a", "missed", 30), run("a", "failed", 40)];+ expect(routineHealthOf([on("a")], runs, 100)).toEqual([{ routineId: "a", status: "failed", at: 40, consecutiveFailures: 3 }]);+ expect(routineHealthOf([on("a")], [...runs, run("a", "completed", 50)], 100)).toEqual([{ routineId: "a", status: "completed", at: 50, consecutiveFailures: 0 }]);+ });++ it("gives the same count however the rows are ordered, and to a process that has only just read them", () => {+ const runs = [run("a", "failed", 40), run("a", "completed", 10), run("a", "failed", 20)];+ expect(routineHealthOf([on("a")], runs, 100)).toEqual(routineHealthOf([on("a")], JSON.parse(JSON.stringify(runs)).reverse(), 100));+ expect(routineHealthOf([on("a")], runs, 100)[0]).toMatchObject({ consecutiveFailures: 2 });+ });++ it("neither counts a cancelled run nor lets it end the row, and ignores runs still going", () => {+ const runs = [run("a", "failed", 10), run("a", "cancelled", 20), run("a", "failed", 30), run("a", "running", 40, { finishedAt: undefined }), run("a", "queued", 50, { finishedAt: undefined })];+ expect(routineHealthOf([on("a")], runs, 100)).toEqual([{ routineId: "a", status: "failed", at: 30, consecutiveFailures: 2 }]);+ });++ it("leaves out a routine that is off or deleted, and keeps an outside trigger's runs", () => {+ const runs = [run("off", "failed", 10), run("gone", "failed", 20), run("hook", "failed", 30, { webhookId: "hook", triggerSource: "webhook" }), run("a", "completed", 40)];+ expect(routineHealthOf([on("a"), { id: "off", enabled: false }], runs, 100).map((health) => health.routineId)).toEqual(["a", "hook"]);+ });++ it("does not take a row that only counts skipped occurrences for a failure, unless the owner was told", () => {+ const counted = run("a", "missed", 30, { skipped: { count: 4, firstAt: 25, lastAt: 30, behind: "a-20" } });+ expect(routineHealthOf([on("a")], [run("a", "completed", 10), run("a", "failed", 20), counted], 100)).toEqual([{ routineId: "a", status: "failed", at: 20, consecutiveFailures: 1 }]);+ expect(routineHealthOf([on("a")], [run("a", "completed", 20), counted], 100)).toEqual([{ routineId: "a", status: "completed", at: 20, consecutiveFailures: 0 }]);+ expect(routineHealthOf([on("a")], [counted], 100)).toEqual([]);+ const told = { ...counted, skipped: { ...counted.skipped!, told: true as const } };+ expect(routineHealthOf([on("a")], [run("a", "failed", 20), told], 100)).toEqual([{ routineId: "a", status: "missed", at: 30, consecutiveFailures: 2 }]);+ });++ it("keeps the newest up to the cap, and says nothing of a routine's words", () => {+ const runs = Array.from({ length: 5 }, (_, index) => run(`r${index}`, "failed", index + 1));+ const health = routineHealthOf(runs.map((row) => on(row.routineId)), runs, 2);+ expect(health.map((row) => row.routineId)).toEqual(["r4", "r3"]);+ expect(JSON.stringify(health)).not.toMatch(/Planted/);+ expect(Object.keys(health[0]!).sort()).toEqual(["at", "consecutiveFailures", "routineId", "status"]);+ });+});diff --git a/server/routine-health.ts b/server/routine-health.tsnew file mode 100644index 0000000000..feae4df73f--- /dev/null+++ b/server/routine-health.ts@@ -0,0 +1,35 @@+// What a Cloud home's health report says about each routine, read from the saved run rows every time: failures in a row+// counted in memory would start again from zero at each restart and hide a routine that fails every day.+import { isCountedSkip, type RoutineRunStatus } from "../shared/routines.ts";+import type { Routine, RoutineRun } from "./routines.ts";++/** An id and counts only: nothing of the routine's name, prompt or output. */+export interface RoutineHealth { routineId: string; status: RoutineRunStatus; at: number; consecutiveFailures: number }++const ENDED = new Set<RoutineRunStatus>(["completed", "failed", "missed", "cancelled"]);+const endedAt = (run: RoutineRun) => run.finishedAt ?? run.createdAt;++/** Each routine that is on, and each outside trigger, with a run that ended: its newest ended run, and how many runs in a+ * row before it failed or were missed since the last one that completed (a cancelled run neither counts nor ends the+ * row). A row that only counts occurrences skipped while the routine was at work is no result and is left out, as is a+ * routine that is off or deleted, which is expected to run nothing. Newest first, at most `cap`. */+export function routineHealthOf(routines: readonly Pick<Routine, "id" | "enabled">[], runs: readonly RoutineRun[], cap: number): RoutineHealth[] {+ const on = new Set(routines.filter((routine) => routine.enabled).map((routine) => routine.id));+ const ended = new Map<string, RoutineRun[]>();+ for (const run of runs) {+ if (!ENDED.has(run.status) || isCountedSkip(run) || !(on.has(run.routineId) || run.webhookId === run.routineId)) continue;+ const rows = ended.get(run.routineId);+ if (rows) rows.push(run); else ended.set(run.routineId, [run]);+ }+ const health: RoutineHealth[] = [];+ for (const [routineId, rows] of ended) {+ rows.sort((a, b) => endedAt(b) - endedAt(a) || b.createdAt - a.createdAt);+ let consecutiveFailures = 0;+ for (const run of rows) {+ if (run.status === "completed") break;+ if (run.status !== "cancelled") consecutiveFailures += 1;+ }+ health.push({ routineId, status: rows[0]!.status, at: endedAt(rows[0]!), consecutiveFailures });+ }+ return health.sort((a, b) => b.at - a.at).slice(0, cap);+}diff --git a/server/routine-lines.ts b/server/routine-lines.tsindex cceee48718..2e6ae5b589 100644--- a/server/routine-lines.ts+++ b/server/routine-lines.ts@@ -20,6 +20,16 @@ export const ROUTINE_LINE = {"routines.server.part.provider": "a temporary error","routines.server.part.failed": "a failure","routines.server.backupSignedOut": "Starting again on the backup AI: this bot's AI is signed out",+ "routines.server.busyTooLong": "Did not run: the bot was busy for more than {minutes} minutes",+ "routines.server.overLimit": "Stopped: this run ran longer than the {hours}-hour limit",+ "routines.server.stopPending": "Its turn has not confirmed that it stopped. The next run waits for that, up to {minutes} minutes.",+ "routines.server.stopUnconfirmed": "Its turn never confirmed that it stopped, so the next run started without that.",+ "routines.server.skippedOne": "Skipped because {why}",+ "routines.server.skippedMany": "Skipped {count} scheduled runs because {why}",+ "routines.server.part.stillWaiting": "the previous run of this routine is still waiting",+ "routines.server.part.stillRunning": "the previous run of this routine is still running",+ "routines.server.part.notStarted": "the previous run of this routine has not started yet",+ "routines.server.part.computerNoStart": "its cloud desktop has not started, so its next tries are spaced out",} as const;export type RoutineLineKey = keyof typeof ROUTINE_LINE;diff --git a/server/routine-load.ts b/server/routine-load.tsindex 93fadcb9f3..41927253c7 100644--- a/server/routine-load.ts+++ b/server/routine-load.ts@@ -11,7 +11,8 @@ import { loadAttachments, loadTimeoutMinutes } from "./routine-attachments.ts";import { isRoutineHoldCause } from "./routine-holds.ts";import { MAX_DATE_MS } from "./routine-intervals.ts";import { loadSchedule } from "./routine-schedules.ts";-import type { Routine, RoutineGoalStatus, RoutinePackageStamp, RoutineRequestReceipt, RoutineRun, RoutineTarget } from "./routines.ts";+import { loadSkips } from "./routine-skips.ts";+import type { Routine, RoutineGoalStatus, RoutinePackageStamp, RoutineRequestCommit, RoutineRequestReceipt, RoutineRun, RoutineTarget } from "./routines.ts";const persistedSourceThreadId = z.string().trim().min(1).optional().catch(undefined);@@ -114,6 +115,7 @@ export function loadRoutine(routine: Routine, now: number): Routine | null {heldFor: isRoutineHoldCause(routine.heldFor) ? routine.heldFor : undefined,};delete loaded.failureStreak;+ delete loaded.noStartStreak;return withCheckFields(withoutUndefined(loaded, ["timeoutMinutes", "runOnStartup", "modelSelection", "installedPackage", "checkedAt", "checkTrouble", "checkTroubleCode", "wakeAt", "heldFor"]));}@@ -132,8 +134,11 @@ export function loadRun(run: RoutineRun): RoutineRun {access: run.access === "read-and-draft" ? "read-and-draft" : undefined,deliver: run.deliver === "brief" ? "brief" : undefined,checkKey: typeof run.checkKey === "string" && /^[\w-]{1,128}$/.test(run.checkKey) ? run.checkKey : undefined,+ busyMs: instant(run.busyMs),+ workedMs: instant(run.workedMs),+ skipped: loadSkips(run.skipped),};- return withoutUndefined(loaded, ["timeoutMinutes", "access", "deliver", "checkKey"]);+ return withoutUndefined(loaded, ["timeoutMinutes", "access", "deliver", "checkKey", "busyMs", "workedMs", "skipped"]);}const REQUEST_ACTIONS = new Set<RoutineRequestOperation["action"]>(["create", "update", "pause", "resume", "run_now", "delete"]);@@ -152,3 +157,30 @@ export function loadRequestReceipts(value: unknown): RoutineRequestReceipt[] {typeof receipt?.resultId === "string" &&Number.isFinite(receipt?.appliedAt));}++/** The receipt of a request already applied; null when there is none. One that names another card throws. */+export function matchingRequestReceipt(receipts: readonly RoutineRequestReceipt[], request: RoutineRequestCommit): RoutineRequestReceipt | null {+ const receipt = receipts.find((candidate) => candidate.requestId === request.requestId);+ if (!receipt) return null;+ if (+ receipt.action !== request.action ||+ receipt.messageId !== request.messageId ||+ receipt.botId !== request.botId ||+ receipt.threadId !== request.threadId ||+ receipt.fingerprintVersion !== request.fingerprintVersion ||+ receipt.fingerprint !== request.fingerprint+ ) {+ throw new Error("Routine request receipt does not match this confirmation card");+ }+ return receipt;+}++/** Keeps the receipt of a request just applied, newest first; applied before with another result, it throws. */+export function rememberRequest(receipts: RoutineRequestReceipt[], request: RoutineRequestCommit, resultId: string, appliedAt: number): void {+ const existing = matchingRequestReceipt(receipts, request);+ if (existing) {+ if (existing.resultId !== resultId) throw new Error("Routine request receipt has another result");+ return;+ }+ receipts.unshift({ ...request, resultId, appliedAt });+}diff --git a/server/routine-no-start.test.ts b/server/routine-no-start.test.tsnew file mode 100644index 0000000000..ae5d4cf3a0--- /dev/null+++ b/server/routine-no-start.test.ts@@ -0,0 +1,116 @@+import { describe, expect, it } from "vitest";++import { RUN_COMPUTER_LINES } from "../shared/cloud-computer-recovery.ts";+import { NO_START_FIRST_SPACING_MS, NO_START_SPACING_MS, SWITCHED_OFF_WITHIN_MS, afterSpacing, failedToStartComputer, noStartAlert, noStartSpacing, switchedOffByNoStarts, turnBackOn } from "./routine-no-start.ts";++const NO_START = "Maus's cloud desktop didn't start. Change where this routine runs.";+const failed = (id: string, at: number, error = NO_START, routineId = "r") => ({ id, routineId, status: "failed", error, createdAt: at, finishedAt: at + 50 });+const completed = (id: string, at: number, routineId = "r") => ({ id, routineId, status: "completed", createdAt: at, finishedAt: at + 50 });++describe("a routine whose cloud computer does not start", () => {+ it("knows that failure from one that passes by itself", () => {+ expect(failedToStartComputer(failed("a", 1))).toBe(true);+ expect(failedToStartComputer(failed("a", 1, "Cloud computers are busy right now. Try again in a few minutes."))).toBe(false);+ expect(failedToStartComputer(completed("a", 1))).toBe(false);+ });++ it("does not take a run that never started, because its computer was not ready, for that failure: the next scheduled run tries again", () => {+ for (const line of Object.values(RUN_COMPUTER_LINES)) expect(failedToStartComputer(failed("a", 1, line)), line).toBe(false);+ const notReady = [1, 2, 3, 4].map((at) => failed(`run-${at}`, at * 100, RUN_COMPUTER_LINES.noAnswer));+ expect(noStartSpacing({ id: "r", updatedAt: 0 }, notReady)).toBeNull();+ expect(noStartAlert({ id: "r", updatedAt: 0 }, notReady.slice(0, 3), notReady[2]!)).toBeUndefined();+ });++ it("spaces its scheduled runs an hour after the third failure in a row and four hours after each later one", () => {+ const routine = { id: "r", updatedAt: 0 };+ expect(noStartSpacing(routine, [failed("a", 100), failed("b", 200)])).toBeNull();+ expect(noStartSpacing(routine, [failed("a", 100), failed("b", 200), failed("c", 300)])).toMatchObject({ streak: 3, until: 350 + NO_START_FIRST_SPACING_MS, last: { id: "c" } });+ expect(noStartSpacing(routine, [failed("a", 100), failed("b", 200), failed("c", 300), failed("d", 400)])).toMatchObject({ streak: 4, until: 450 + NO_START_SPACING_MS });+ });++ it("ends the spacing with the first run that works, another kind of failure, or a change to the routine", () => {+ const three = [failed("a", 100), failed("b", 200), failed("c", 300)];+ expect(noStartSpacing({ id: "r", updatedAt: 0 }, [...three, completed("d", 400)])).toBeNull();+ expect(noStartSpacing({ id: "r", updatedAt: 0 }, [...three, failed("d", 400, "The bot did not complete this run")])).toBeNull();+ expect(noStartSpacing({ id: "r", updatedAt: 250 }, three)).toBeNull();+ expect(noStartSpacing({ id: "other", updatedAt: 0 }, three)).toBeNull();+ });++ it("tells the owner once, at the failure that begins the spacing", () => {+ const routine = { id: "r", updatedAt: 0 };+ const [a, b, c, d] = [failed("a", 100), failed("b", 200), failed("c", 300), failed("d", 400)];+ expect(noStartAlert(routine, [a, b], b)).toBeUndefined();+ expect(noStartAlert(routine, [a, b, c], c)).toEqual({ detail: `${NO_START} 3 runs in a row failed this way. It stays on, and tries again less often until its cloud desktop starts.` });+ expect(noStartAlert(routine, [a, b, c, d], d)).toBeUndefined();+ expect(noStartAlert(undefined, [a, b, c], c)).toBeUndefined();+ });+});++describe("a spaced routine's next run, for planning when the computer must be awake", () => {+ const HOUR = 60 * 60_000;+ const three = [failed("a", 100), failed("b", 200), failed("c", 300)];+ const every = (minutes: number) => (_schedule: unknown, after: number) => (Math.floor(after / (minutes * 60_000)) + 1) * minutes * 60_000;+ const routine = (nextRunAt: number | null, more: Record<string, unknown> = {}) => ({ id: "r", updatedAt: 0, enabled: true, nextRunAt, schedule: {}, ...more });++ it("is the first occurrence at or after the spacing's end, not one it will skip", () => {+ const until = 350 + NO_START_FIRST_SPACING_MS;+ expect(afterSpacing(routine(5 * 60_000), three, 1_000, every(5)).nextRunAt).toBe(65 * 60_000);+ expect(afterSpacing(routine(5 * 60_000), three, 1_000, every(5)).nextRunAt).toBeGreaterThanOrEqual(until);+ expect(afterSpacing(routine(5 * 60_000), three, 1_000, (_schedule, after) => after + 1).nextRunAt).toBe(until);+ });++ it("is the routine's own next run when it is not spaced, the spacing is over, or the run is after it anyway", () => {+ const plain = routine(5 * 60_000);+ expect(afterSpacing(plain, three.slice(0, 2), 1_000, every(5))).toBe(plain);+ expect(afterSpacing(plain, three, 350 + NO_START_FIRST_SPACING_MS, every(5))).toBe(plain);+ const daily = routine(24 * HOUR);+ expect(afterSpacing(daily, three, 1_000, every(5))).toBe(daily);+ const off = routine(null, { enabled: false });+ expect(afterSpacing(off, three, 1_000, every(5))).toBe(off);+ });+});++describe("routines an earlier version turned off after three such failures", () => {+ const three = [failed("a", 100), failed("b", 200), failed("c", 300)];+ const off = (more: Record<string, unknown> = {}) => ({ id: "r", enabled: false, nextRunAt: null, updatedAt: 350, schedule: { type: "interval" }, ...more });++ it("are recognised by their last change being the instant the third failure ended", () => {+ expect(switchedOffByNoStarts([off()], three, 10_000)).toHaveLength(1);+ expect(switchedOffByNoStarts([off({ updatedAt: 351 })], three, 10_000)).toHaveLength(1);+ });++ it("are left as they are when the switch-off is more than thirty days old", () => {+ expect(switchedOffByNoStarts([off()], three, 350 + SWITCHED_OFF_WITHIN_MS)).toHaveLength(1);+ expect(switchedOffByNoStarts([off()], three, 350 + SWITCHED_OFF_WITHIN_MS + 1)).toEqual([]);+ });++ it.each([+ ["one a person turned off later", off({ updatedAt: 350 + 60_000 }), three],+ ["one changed before the failure ended", off({ updatedAt: 349 }), three],+ ["one held because its owner left", off({ heldFor: "no_connections" }), three],+ ["one that is on", off({ enabled: true }), three],+ ["a one-time routine", off({ schedule: { type: "once" } }), three],+ ["one with two such failures", off({ updatedAt: 250 }), three.slice(0, 2)],+ ["one whose failures differ in wording", off(), [failed("a", 100), failed("b", 200, "Ada's cloud desktop didn't start."), failed("c", 300)]],+ ["one whose newest outcome is another failure", off({ updatedAt: 450 }), [...three, failed("d", 400, "The bot did not complete this run")]],+ ["one that ran again since", off(), [...three, { id: "d", routineId: "r", status: "running", createdAt: 400 }]],+ ["one whose failed runs are gone", off(), []],+ ])("leave alone %s", (_what, routine, runs) => {+ expect(switchedOffByNoStarts([routine], runs, 10_000)).toEqual([]);+ });++ it("come back on from now, counted as changed so the next run is not held back", () => {+ const routine = off();+ expect(turnBackOn([routine], three, undefined, 10_000, () => 12_000)).toEqual([routine]);+ expect(routine).toMatchObject({ enabled: true, nextRunAt: 12_000, updatedAt: 10_000 });+ expect(noStartSpacing(routine, three)).toBeNull();+ expect(turnBackOn([routine], three, undefined, 20_000, () => 22_000)).toEqual([]);+ });++ it("stay off under the cause that holds every routine, stamped so they come back when it ends", () => {+ const routine = off();+ turnBackOn([routine], three, "no_connections", 10_000, () => 12_000);+ expect(routine).toMatchObject({ enabled: false, nextRunAt: null, heldFor: "no_connections" });+ expect(switchedOffByNoStarts([routine], three, 20_000)).toEqual([]);+ });+});diff --git a/server/routine-no-start.ts b/server/routine-no-start.tsnew file mode 100644index 0000000000..12b0fab722--- /dev/null+++ b/server/routine-no-start.ts@@ -0,0 +1,84 @@+// A routine whose cloud computer does not start is never turned off for it: each such run spends the bot's AI for minutes+// before it fails, so after a few in a row its scheduled runs are spaced out instead, and every occurrence held back is+// counted on one `missed` row (routine-skips.ts). The first run whose computer starts, turning the routine on again, or+// any change to it ends the spacing.+import { PLACE_EN } from "../shared/place-view.ts";+import { outcomesNewestFirst } from "./routine-outcomes.ts";+import type { RoutineAlert } from "./routine-recovery.ts";++type Outcome = { id: string; routineId: string; status: string; error?: string | null; createdAt: number; finishedAt?: number | null };+type Spaced = { id: string; updatedAt: number };++/** Runs in a row that failed this way before the routine's next scheduled runs are spaced out. */+export const NO_START_RUNS_BEFORE_SPACING = 3;+/** How long after the last such failure the next scheduled run waits: at the third in a row, and from the fourth on. */+export const NO_START_FIRST_SPACING_MS = 60 * 60_000;+export const NO_START_SPACING_MS = 4 * 60 * 60_000;++const [beforeBot, afterBot] = PLACE_EN["place.view.ccNoStart.line"].split("{bot}").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));+const NO_START = new RegExp(`^${beforeBot}.+${afterBot}`);++/** The run failed because its cloud computer did not start. A busy or unavailable Cloud service reads differently and is not this. */+export const failedToStartComputer = (run: Pick<Outcome, "status" | "error">): boolean => run.status === "failed" && Boolean(run.error) && NO_START.test(run.error!);++/** The routine's newest outcomes, since it was last turned on or changed, that all failed because its cloud computer did not start. */+export function noStartRuns<T extends Outcome>(routine: Spaced, runs: readonly T[]): T[] {+ const outcomes = outcomesNewestFirst(runs, routine.id);+ const end = outcomes.findIndex((run) => !failedToStartComputer(run) || run.createdAt < routine.updatedAt);+ return end < 0 ? outcomes : outcomes.slice(0, end);+}++/** Until when the routine's scheduled runs are held back, and the failure the spacing counts from; null when they are not. */+export function noStartSpacing<T extends Outcome>(routine: Spaced, runs: readonly T[]): { until: number; last: T; streak: number } | null {+ const failed = noStartRuns(routine, runs), last = failed[0];+ if (!last || failed.length < NO_START_RUNS_BEFORE_SPACING) return null;+ const wait = failed.length === NO_START_RUNS_BEFORE_SPACING ? NO_START_FIRST_SPACING_MS : NO_START_SPACING_MS;+ return { until: (last.finishedAt ?? last.createdAt) + wait, last, streak: failed.length };+}++/** What the owner is told, once, by the failure that begins the spacing. */+export function noStartAlert<T extends Outcome>(routine: Spaced | undefined, runs: readonly T[], run: T): RoutineAlert | undefined {+ if (!routine || !failedToStartComputer(run) || noStartRuns(routine, runs).length !== NO_START_RUNS_BEFORE_SPACING || noStartRuns(routine, runs)[0]?.id !== run.id) return undefined;+ return { detail: `${run.error} ${NO_START_RUNS_BEFORE_SPACING} runs in a row failed this way. It stays on, and tries again less often until its cloud desktop starts.` };+}++/** The routine as the computer's wake and sleep planning should see it: while its runs are spaced out, its next run is the+ * first occurrence at or after the spacing's end (`next` gives a schedule's first occurrence after a time), not one that+ * will only be skipped. */+export function afterSpacing<R extends Spaced & { enabled: boolean; nextRunAt: number | null; schedule: unknown }, T extends Outcome>(routine: R, runs: readonly T[], now: number, next: (schedule: R["schedule"], after: number) => number | null): R {+ const spaced = routine.enabled && routine.nextRunAt !== null ? noStartSpacing(routine, runs) : null;+ if (!spaced || spaced.until <= now || routine.nextRunAt! >= spaced.until) return routine;+ return { ...routine, nextRunAt: next(routine.schedule, spaced.until - 1) };+}++type Switched<Hold> = Spaced & { enabled: boolean; heldFor?: Hold; nextRunAt: number | null; schedule: { type: string } };+/** How far apart the failure's end and the routine's last change may be for the switch-off to be the failure's own: both+ * were stamped in one synchronous step. */+const SAME_STEP_MS = 1_000;+/** A switch-off older than this is left as the person has lived with it. */+export const SWITCHED_OFF_WITHIN_MS = 30 * 24 * 60 * 60_000;++/** Routines that an earlier version turned off after three such failures in a row, which left no marker: one is+ * recognised only when it is off without a hold, its three newest outcomes are that failure with one wording, the+ * newest of them ended within SWITCHED_OFF_WITHIN_MS, and its last change is the instant that one ended. One changed+ * since (a person's edit, a workspace restore), or whose failed runs are gone, is not among them. */+export function switchedOffByNoStarts<R extends Switched<unknown>, T extends Outcome>(routines: readonly R[], runs: readonly T[], now: number): R[] {+ return routines.filter((routine) => {+ if (routine.enabled || routine.heldFor !== undefined || routine.schedule.type === "once") return false;+ const newest = outcomesNewestFirst(runs, routine.id).slice(0, NO_START_RUNS_BEFORE_SPACING), last = newest[0];+ if (!last || newest.length < NO_START_RUNS_BEFORE_SPACING || newest.some((run) => !failedToStartComputer(run) || run.error !== last.error)) return false;+ const gap = routine.updatedAt - (last.finishedAt ?? NaN);+ return gap >= 0 && gap <= SAME_STEP_MS && now - last.finishedAt! <= SWITCHED_OFF_WITHIN_MS && !runs.some((run) => run.routineId === routine.id && run.createdAt > routine.updatedAt);+ });+}++/** Turns those routines back on from `now` (`next` is a schedule's first occurrence from then), or, while a cause holds+ * every routine (`hold`), stamps them with it so they come back when it ends. Each counts as changed, so its spacing starts afresh. */+export function turnBackOn<Hold, R extends Switched<Hold>, T extends Outcome>(routines: readonly R[], runs: readonly T[], hold: Hold | undefined, now: number, next: (schedule: R["schedule"], now: number) => number | null): R[] {+ const back = switchedOffByNoStarts(routines, runs, now);+ for (const routine of back) {+ const at = next(routine.schedule, now);+ Object.assign(routine, hold !== undefined ? { heldFor: hold } : at === null ? {} : { enabled: true, nextRunAt: at }, { updatedAt: Math.max(now, routine.updatedAt + 1) });+ }+ return back;+}diff --git a/server/routine-outcomes.ts b/server/routine-outcomes.tsindex a747005241..1c59dab8e4 100644--- a/server/routine-outcomes.ts+++ b/server/routine-outcomes.ts@@ -1,5 +1,3 @@-import { PLACE_EN } from "../shared/place-view.ts";-type Outcome = { id: string; routineId: string; status: string; error?: string | null; createdAt: number; finishedAt?: number | null };/** A routine's finished runs (failed or completed), newest first. */@@ -13,19 +11,3 @@ export function failsLikeLastOutcome<T extends Outcome>(runs: readonly T[], run:const last = outcomesNewestFirst(runs, run.routineId, run.id)[0];return last?.status === "failed" && last.error === run.error;}--/** Runs in a row, since the routine was last turned on or changed, that failed because its cloud computer didn't start. */-export const NO_START_RUNS_BEFORE_OFF = 3;-const [beforeBot, afterBot] = PLACE_EN["place.view.ccNoStart.line"].split("{bot}").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));-const NO_START = new RegExp(`^${beforeBot}.+${afterBot}`);--/** Each run on a cloud computer that doesn't start spends the bot's AI for minutes before it fails, so the third such- * run in a row turns the routine off and says so. Turning it on again, or any change, starts the count afresh. A busy- * or unavailable Cloud service is not counted: that passes by itself, and nothing would turn the routine back on. */-export function offAfterNoStarts<R extends { enabled: boolean; nextRunAt: number | null; updatedAt: number }, T extends Outcome>(routine: R | undefined, runs: readonly T[], run: T, now: number): { routine: R; alert: { detail: string } } | undefined {- if (!routine?.enabled || run.status !== "failed" || !run.error || run.createdAt < routine.updatedAt || !NO_START.test(run.error)) return undefined;- const earlier = outcomesNewestFirst(runs, run.routineId, run.id).slice(0, NO_START_RUNS_BEFORE_OFF - 1);- if (earlier.length < NO_START_RUNS_BEFORE_OFF - 1 || earlier.some((other) => other.status !== "failed" || other.error !== run.error || other.createdAt < routine.updatedAt)) return undefined;- Object.assign(routine, { enabled: false, nextRunAt: null, updatedAt: Math.max(now, routine.updatedAt + 1) });- return { routine, alert: { detail: `${run.error} It was turned off after ${NO_START_RUNS_BEFORE_OFF} runs in a row failed this way: turn it on again once its computer starts.` } };-}diff --git a/server/routine-recovery.ts b/server/routine-recovery.tsindex 26065cc092..0465455918 100644--- a/server/routine-recovery.ts+++ b/server/routine-recovery.ts@@ -5,7 +5,7 @@// A teammate's failed thread takes the same verdict (host/chief-notices.ts).import type { RuntimeEvent } from "../shared/runtime-events.ts";import type { ServerText } from "../shared/server-text.ts";-import type { RoutineRetryCause } from "../shared/routines.ts";+import { isCountedSkip, type RoutineRetryCause } from "../shared/routines.ts";import { engineFailureKind } from "./drivers/engine-errors.ts";import { classifyError } from "./drivers/retry.ts";import { nextOccurrence } from "./routine-schedules.ts";@@ -218,7 +218,7 @@ export function loadOwnerNotices(value: unknown): RoutineOwnerNotice[] {export function weekRuns(runs: readonly RoutineRun[], routineId: string, now: number): { ok: number; total: number } | undefined {let ok = 0, total = 0;for (const run of runs) {- if (run.routineId !== routineId || !["completed", "failed", "missed"].includes(run.status) || (run.finishedAt ?? run.createdAt) < now - WEEK_MS) continue;+ if (run.routineId !== routineId || !["completed", "failed", "missed"].includes(run.status) || isCountedSkip(run) || (run.finishedAt ?? run.createdAt) < now - WEEK_MS) continue;total += 1;if (run.status === "completed") ok += 1;}diff --git a/server/routine-reliability.test.ts b/server/routine-reliability.test.tsnew file mode 100644index 0000000000..a9b59fcbae--- /dev/null+++ b/server/routine-reliability.test.ts@@ -0,0 +1,847 @@+// What a schedule may count on: failures never turn a routine off, nothing holds it up without end, every occurrence+// that does not run leaves a row, and a routines.json that cannot be read is kept, reported and read again.+import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";++import { SCHEDULER_STOP_WAIT_MS, STOP_CONFIRM_WAIT_MS } from "./routine-bounds.ts";+import { UNREADABLE_RETRY_MS } from "./routine-file.ts";+import { RoutineManager, type RoutineManagerOptions, type RoutineRun } from "./routines.ts";++const MINUTE = 60_000, HOUR = 60 * MINUTE;+const START = Date.parse("2026-11-16T08:00:00Z");+const NO_START = "Maus's cloud desktop didn't start. Change where this routine runs.";+const dirs: string[] = [];++function harness(start = START, file?: string) {+ let now = start, bot: "ready" | "busy" | "missing" = "ready", task = 0;+ if (!file) { const dir = mkdtempSync(join(tmpdir(), "omb-routine-reliability-")); dirs.push(dir); file = join(dir, "routines.json"); }+ const started: string[] = [], interrupted: string[] = [], emitted: Array<Record<string, unknown>> = [], changed: RoutineRun[] = [];+ const failed: Array<{ run: RoutineRun; alert: unknown }> = [], deferred: RoutineRun[] = [];+ const options: RoutineManagerOptions = {+ file, now: () => now, emit: (payload) => emitted.push(payload), botState: () => bot,+ createTask: () => ({ threadId: `thread-${++task}` }),+ startTurn: async (_botId, threadId) => { started.push(threadId); },+ interruptTurn: async (_botId, threadId) => { interrupted.push(threadId); },+ onRunChanged: (run) => changed.push(run), onRunFailed: (run, alert) => failed.push({ run, alert }), onRunDeferred: (run) => deferred.push(run),+ };+ const h = {+ file, options, started, interrupted, emitted, changed, failed, deferred, manager: new RoutineManager(options),+ at: (value: number) => { now = value; }, bot: (value: typeof bot) => { bot = value; },+ tickAt: async (value: number) => { now = value; await h.manager.tick(); },+ /** A scheduler pass every `step` up to `to`, as the running scheduler makes while a run works or waits to start. */+ passTo: async (to: number, step = MINUTE) => { while (now + step <= to) { now += step; await h.manager.tick(); } if (now < to) { now = to; await h.manager.tick(); } },+ /** The process ends and another starts on the same file: the first one's scheduler does nothing more. */+ restart: () => { h.manager.close(); return (h.manager = new RoutineManager(options)); },+ event: (threadId: string, type: string, more: Record<string, unknown> = {}) =>+ h.manager.handleRuntimeEvent({ eventId: `${type}-${threadId}`, provider: "fake", threadId, createdAt: new Date(now).toISOString(), type, ...more } as Parameters<RoutineManager["handleRuntimeEvent"]>[0]),+ done: (threadId: string) => h.event(threadId, "turn.completed", { ok: true }),+ runs: () => h.manager.listRuns().sort((a, b) => a.createdAt - b.createdAt || a.scheduledFor - b.scheduledFor),+ routine: () => h.manager.listRoutines()[0]!,+ disk: () => JSON.parse(readFileSync(file!, "utf8")) as { routines: Array<Record<string, unknown>>; runs: RoutineRun[] },+ };+ return h;+}++const every = (minutes: number, more: Record<string, unknown> = {}) => ({ name: "Fix new bugs", prompt: "Look for new bug reports and fix them", botId: "maus-1",+ schedule: { type: "interval" as const, everyMinutes: minutes, anchorAt: START }, ...more });++afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++describe("a routine whose runs fail", () => {+ it("stays on through three cloud-computer start failures in a row, and runs its next occurrence once the computer works", async () => {+ const h = harness();+ h.manager.create(every(24 * 60));+ for (const day of [1, 2, 3]) {+ await h.tickAt(START + day * 24 * HOUR);+ h.manager.failThread(`thread-${day}`, NO_START, { cause: "refused" });+ expect(h.routine()).toMatchObject({ enabled: true, nextRunAt: START + (day + 1) * 24 * HOUR });+ }+ expect(h.routine()).toMatchObject({ enabled: true, failureStreak: 3, noStartStreak: 3 });+ expect(h.failed.map((failure) => failure.alert)).toEqual([undefined, null, { detail: expect.stringContaining("3 runs in a row failed this way. It stays on") }]);++ await h.tickAt(START + 4 * 24 * HOUR);+ expect(h.started).toEqual(["thread-1", "thread-2", "thread-3", "thread-4"]);+ h.done("thread-4");+ expect(h.runs().map((run) => run.status)).toEqual(["failed", "failed", "failed", "completed"]);+ expect(h.routine()).toMatchObject({ enabled: true, nextRunAt: START + 5 * 24 * HOUR });+ expect(h.routine()).not.toHaveProperty("noStartStreak");+ expect(h.restart().listRoutines()[0]).toMatchObject({ enabled: true, nextRunAt: START + 5 * 24 * HOUR });+ });++ it("spaces a frequent routine's tries instead of starting one every few minutes, on one row, and starts again by itself", async () => {+ const h = harness();+ h.manager.create(every(5));+ for (const turn of [1, 2, 3]) {+ await h.tickAt(START + turn * 5 * MINUTE);+ h.manager.failThread(`thread-${turn}`, NO_START, { cause: "refused" });+ }+ const failedAt = START + 15 * MINUTE;+ for (let minute = 20; minute <= 70; minute += 5) await h.tickAt(START + minute * MINUTE);+ expect(h.started).toHaveLength(3);+ expect(h.routine()).toMatchObject({ enabled: true, noStartStreak: 3, skippedRuns: 11 });+ const held = h.runs().filter((run) => run.skipped);+ expect(held).toMatchObject([{ status: "missed", error: "Skipped 11 scheduled runs because its cloud desktop has not started, so its next tries are spaced out",+ skipped: { count: 11, firstAt: START + 20 * MINUTE, lastAt: START + 70 * MINUTE }, seenAt: START + 20 * MINUTE }]);+ expect(h.failed).toHaveLength(3);++ await h.tickAt(failedAt + HOUR);+ expect(h.started).toHaveLength(4);+ h.manager.failThread("thread-4", NO_START, { cause: "refused" });+ await h.tickAt(failedAt + HOUR + 3 * HOUR + 55 * MINUTE);+ expect(h.started).toHaveLength(4);+ await h.tickAt(failedAt + HOUR + 4 * HOUR);+ expect(h.started).toHaveLength(5);+ h.done("thread-5");+ await h.tickAt(failedAt + HOUR + 4 * HOUR + 5 * MINUTE);+ expect(h.started).toHaveLength(6);+ expect(h.routine()).not.toHaveProperty("noStartStreak");+ });++ it("lets the person start a run by hand, or change the routine, while its tries are spaced out", async () => {+ const h = harness();+ const routine = h.manager.create(every(5));+ for (const turn of [1, 2, 3]) {+ await h.tickAt(START + turn * 5 * MINUTE);+ h.manager.failThread(`thread-${turn}`, NO_START, { cause: "refused" });+ }+ h.manager.runNow(routine.id); await h.tickAt(START + 16 * MINUTE);+ expect(h.started).toHaveLength(4);+ h.manager.failThread("thread-4", NO_START, { cause: "refused" });+ await h.tickAt(START + 20 * MINUTE);+ expect(h.started).toHaveLength(4);+ h.manager.update(routine.id, { prompt: "Look for new bug reports, fix them, and say what changed" });+ await h.tickAt(START + 25 * MINUTE);+ expect(h.started).toHaveLength(5);+ });++ it("counts failures in a row from the saved rows, so a restart between two failures hides neither", async () => {+ const h = harness();+ const routine = h.manager.create(every(60));+ await h.tickAt(START + HOUR);+ h.manager.failThread("thread-1", "The bot did not complete this run", { cause: "refused" });+ expect(h.manager.health(100)).toEqual([{ routineId: routine.id, status: "failed", at: START + HOUR, consecutiveFailures: 1 }]);+ h.restart();+ expect(h.manager.health(100)).toEqual([{ routineId: routine.id, status: "failed", at: START + HOUR, consecutiveFailures: 1 }]);+ await h.tickAt(START + 2 * HOUR);+ h.manager.failThread("thread-2", "The bot did not complete this run", { cause: "refused" });+ h.restart();+ expect(h.manager.health(100)).toEqual([{ routineId: routine.id, status: "failed", at: START + 2 * HOUR, consecutiveFailures: 2 }]);+ expect(h.routine().failureStreak).toBe(2);+ await h.tickAt(START + 3 * HOUR);+ h.done("thread-3");+ expect(h.manager.health(100)).toEqual([{ routineId: routine.id, status: "completed", at: START + 3 * HOUR, consecutiveFailures: 0 }]);+ });+});++describe("routines an earlier version turned off after three cloud-computer start failures", () => {+ const saved = (id: string, more: Record<string, unknown> = {}) => ({ id, ...every(60), target: "bot", runOn: "maus", durationMinutes: 30, enabled: false, nextRunAt: null, createdAt: START, updatedAt: START + 3 * HOUR + 50, ...more });+ const failures = (routineId: string) => [1, 2, 3].map((hour): RoutineRun => ({ id: `${routineId}-${hour}`, routineId, routineName: "Fix new bugs", target: "bot", botId: "maus-1", runOn: "maus",+ scheduledFor: START + hour * HOUR, status: "failed", manual: false, error: NO_START, createdAt: START + hour * HOUR, startedAt: START + hour * HOUR, finishedAt: START + hour * HOUR + 50 }));++ it("come back on at the next start, and only those: one a person paused, one changed since and one held stay as they are", () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-routine-reliability-")); dirs.push(dir);+ const file = join(dir, "routines.json");+ const routines = [saved("switched-off"), saved("paused-by-person", { updatedAt: START + 5 * HOUR }), saved("renamed-since", { name: "Renamed", updatedAt: START + 4 * HOUR }),+ saved("held", { heldFor: "no_connections" }), saved("on", { enabled: true, nextRunAt: START + 9 * HOUR })];+ writeFileSync(file, JSON.stringify({ version: 1, routines, runs: routines.flatMap((routine) => failures(routine.id)) }));+ const h = harness(START + 7 * HOUR + 10 * MINUTE, file);+ const after = Object.fromEntries(h.manager.listRoutines().map((routine) => [routine.id, routine]));+ expect(after["switched-off"]).toMatchObject({ enabled: true, nextRunAt: START + 8 * HOUR, updatedAt: START + 7 * HOUR + 10 * MINUTE });+ expect(after["switched-off"]).not.toHaveProperty("noStartStreak");+ expect(after["paused-by-person"]).toMatchObject({ enabled: false, nextRunAt: null, updatedAt: START + 5 * HOUR });+ expect(after["renamed-since"]).toMatchObject({ enabled: false, nextRunAt: null, updatedAt: START + 4 * HOUR });+ expect(after.held).toMatchObject({ enabled: false, heldFor: "no_connections", updatedAt: START + 3 * HOUR + 50 });+ expect(after.on).toMatchObject({ enabled: true, nextRunAt: START + 9 * HOUR });+ expect(h.manager.takeTurnedBackOn().map((routine) => [routine.id, routine.botId, routine.name])).toEqual([["switched-off", "maus-1", "Fix new bugs"]]);+ expect(h.manager.takeTurnedBackOn()).toEqual([]);+ });++ it("are looked for once per install: a later start turns nothing back on, even one that matches", () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-routine-reliability-")); dirs.push(dir);+ const file = join(dir, "routines.json");+ writeFileSync(file, JSON.stringify({ version: 1, routines: [saved("switched-off")], runs: failures("switched-off") }));+ const h = harness(START + 7 * HOUR, file);+ expect(h.routine().enabled).toBe(true);+ h.manager.close();+ const disk = JSON.parse(readFileSync(file, "utf8"));+ expect(disk.noStartOffsChecked).toBe(true);+ // The same shape again, as a copy of an older file dropped into place would give it.+ writeFileSync(file, JSON.stringify({ ...disk, routines: [saved("switched-off")], runs: failures("switched-off") }));+ h.manager = new RoutineManager(h.options);+ expect(h.routine()).toMatchObject({ enabled: false, nextRunAt: null, updatedAt: START + 3 * HOUR + 50 });+ expect(h.manager.takeTurnedBackOn()).toEqual([]);+ h.manager.update("switched-off", { enabled: true });+ expect(h.disk()).toMatchObject({ noStartOffsChecked: true });+ });++ it("are left alone while this copy is frozen by a move, and looked for at the first start after the freeze lifts", () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-routine-reliability-")); dirs.push(dir);+ const file = join(dir, "routines.json");+ writeFileSync(file, JSON.stringify({ version: 1, routines: [saved("switched-off")], runs: failures("switched-off") }));+ const h = harness(START + 7 * HOUR, file);+ let frozen = true;+ h.options.moveFrozen = () => frozen;+ h.restart();+ // The first manager, made before the option was set, did the look: put the file back as the frozen copy holds it.+ h.manager.close();+ writeFileSync(file, JSON.stringify({ version: 1, routines: [saved("switched-off")], runs: failures("switched-off") }));+ h.manager = new RoutineManager(h.options);+ expect(h.routine()).toMatchObject({ enabled: false });+ expect(h.manager.takeTurnedBackOn()).toEqual([]);+ h.manager.markAllSeen();+ expect(h.disk()).not.toHaveProperty("noStartOffsChecked");+ frozen = false;+ expect(h.restart().listRoutines()[0]).toMatchObject({ enabled: true });+ });++ it("stay off when the switch-off is more than thirty days old, or when a workspace restore has stamped them since", () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-routine-reliability-")); dirs.push(dir);+ const file = join(dir, "routines.json");+ writeFileSync(file, JSON.stringify({ version: 1, routines: [saved("old")], runs: failures("old") }));+ expect(harness(START + 3 * HOUR + 31 * 24 * HOUR, file).routine()).toMatchObject({ enabled: false });+ const restoredAt = START + 2 * 24 * HOUR;+ writeFileSync(file, JSON.stringify({ version: 1, routines: [saved("restored", { updatedAt: restoredAt })], runs: failures("restored") }));+ const h = harness(restoredAt + HOUR, file);+ expect(h.routine()).toMatchObject({ enabled: false, updatedAt: restoredAt });+ expect(h.manager.takeTurnedBackOn()).toEqual([]);+ });++ it("run their next occurrence, stay on across another start, and stay off once the person turns them off", async () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-routine-reliability-")); dirs.push(dir);+ const file = join(dir, "routines.json");+ writeFileSync(file, JSON.stringify({ version: 1, routines: [saved("switched-off")], runs: failures("switched-off") }));+ const h = harness(START + 7 * HOUR + 10 * MINUTE, file);+ await h.tickAt(START + 8 * HOUR);+ expect(h.started).toEqual(["thread-1"]);+ h.done("thread-1");+ expect(h.disk().routines[0]).toMatchObject({ enabled: true });+ h.manager.update("switched-off", { enabled: false });+ expect(h.restart().listRoutines()[0]).toMatchObject({ enabled: false, nextRunAt: null });+ });++ it("wait under the cause that holds every routine, and come back when it ends", () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-routine-reliability-")); dirs.push(dir);+ const file = join(dir, "routines.json");+ writeFileSync(file, JSON.stringify({ version: 1, routines: [saved("switched-off")], runs: failures("switched-off"), holds: ["no_connections"] }));+ const h = harness(START + 7 * HOUR + 10 * MINUTE, file);+ expect(h.routine()).toMatchObject({ enabled: false, heldFor: "no_connections" });+ expect(h.manager.takeTurnedBackOn()).toEqual([]);+ h.manager.holdFor([]);+ expect(h.routine()).toMatchObject({ enabled: true, nextRunAt: START + 8 * HOUR });+ expect(h.routine()).not.toHaveProperty("heldFor");+ });+});++describe("a row that only counts skipped occurrences", () => {+ it("is no failure: one failed run and an overlap skip read as one failure in health, and the week counts real runs only", async () => {+ const h = harness();+ const routine = h.manager.create(every(5));+ await h.tickAt(START + 5 * MINUTE);+ await h.tickAt(START + 10 * MINUTE);+ h.manager.failThread("thread-1", "The bot did not complete this run", { cause: "refused" });+ expect(h.runs().map((run) => [run.status, run.skipped?.count])).toEqual([["failed", undefined], ["missed", 1]]);+ expect(h.manager.health(100)).toEqual([{ routineId: routine.id, status: "failed", at: START + 10 * MINUTE, consecutiveFailures: 1 }]);+ expect(h.routine()).toMatchObject({ failureStreak: 1, weekRuns: { ok: 0, total: 1 } });+ });++ it("leaves a routine whose runs always overlap the next occurrence healthy: every run OK, newest result completed", async () => {+ const h = harness();+ const routine = h.manager.create(every(5));+ for (let turn = 1; turn <= 4; turn += 1) {+ await h.tickAt(START + (turn * 10 - 5) * MINUTE);+ await h.tickAt(START + turn * 10 * MINUTE);+ h.done(`thread-${turn}`);+ }+ expect(h.runs().filter((run) => run.skipped)).toHaveLength(4);+ expect(h.manager.health(100)).toEqual([{ routineId: routine.id, status: "completed", at: START + 40 * MINUTE, consecutiveFailures: 0 }]);+ expect(h.routine()).toMatchObject({ weekRuns: { ok: 4, total: 4 } });+ expect(h.routine()).not.toHaveProperty("failureStreak");+ });++ it("still counts when the owner was told: a run that waited past the notice window is a result", async () => {+ const h = harness();+ h.options.hasPendingDelegations = () => true; h.options.handedOffWorkLive = () => true;+ const routine = h.manager.create(every(5));+ await h.tickAt(START + 5 * MINUTE);+ h.done("thread-1");+ for (let minute = 10; minute <= 40; minute += 5) await h.tickAt(START + minute * MINUTE);+ expect(h.runs().filter((run) => run.skipped)).toMatchObject([{ skipped: { told: true } }]);+ expect(h.manager.health(100)).toEqual([{ routineId: routine.id, status: "missed", at: START + 40 * MINUTE, consecutiveFailures: 1 }]);+ expect(h.routine()).toMatchObject({ weekRuns: { ok: 0, total: 1 } });+ });+});++describe("a spaced routine and a home that sleeps", () => {+ it("reports its next due time as the first occurrence after the spacing, so nothing wakes or waits for runs it will skip", async () => {+ const h = harness();+ h.manager.create(every(5));+ expect(h.manager.nextDueAt()).toBe(START + 5 * MINUTE);+ for (const turn of [1, 2, 3]) {+ await h.tickAt(START + turn * 5 * MINUTE);+ h.manager.failThread(`thread-${turn}`, NO_START, { cause: "refused" });+ }+ expect(h.routine().nextRunAt).toBe(START + 20 * MINUTE);+ expect(h.manager.nextDueAt()).toBe(START + 75 * MINUTE);+ expect(h.manager.wakeHold(30 * MINUTE)).toEqual({ hold: false });+ await h.tickAt(START + 20 * MINUTE);+ expect(h.manager.nextDueAt()).toBe(START + 75 * MINUTE);+ await h.tickAt(START + 76 * MINUTE);+ expect(h.started).toHaveLength(4);+ h.done("thread-4");+ expect(h.manager.nextDueAt()).toBe(START + 80 * MINUTE);+ });+});++describe("deliberate pauses still hold", () => {+ it("keeps a routine the person paused off, and one held because its owner left off until the cause ends", async () => {+ const h = harness();+ const paused = h.manager.create(every(60, { name: "Paused by hand" }));+ const held = h.manager.create(every(60, { name: "Held" }));+ h.manager.update(paused.id, { enabled: false });+ expect(h.manager.holdFor(["no_connections"])).toEqual(["no_connections"]);+ await h.tickAt(START + 2 * HOUR);+ expect(h.started).toEqual([]);+ const after = h.restart().listRoutines();+ expect(after.find((routine) => routine.id === paused.id)).toMatchObject({ enabled: false });+ expect(after.find((routine) => routine.id === paused.id)).not.toHaveProperty("heldFor");+ expect(after.find((routine) => routine.id === held.id)).toMatchObject({ enabled: false, heldFor: "no_connections" });+ h.manager.holdFor([]);+ expect(h.manager.listRoutines().map((routine) => [routine.name, routine.enabled]).sort()).toEqual([["Held", true], ["Paused by hand", false]]);+ });++ it("lets a bot the person paused drop its scheduled runs quietly", async () => {+ const h = harness();+ h.options.pausedText = () => "Maus is paused, so it takes no new work."; h.options.held = () => true;+ h.manager.create(every(60));+ await h.tickAt(START + HOUR);+ expect(h.runs().map((run) => [run.status, run.error])).toEqual([["cancelled", "Maus is paused, so it takes no new work."]]);+ expect([h.started, h.failed]).toEqual([[], []]);+ expect(h.routine().enabled).toBe(true);+ });+});++describe("a run queued behind a busy bot", () => {+ it("ends as missed after an hour of that wait, with the reason, and the schedule carries on", async () => {+ const h = harness(); h.bot("busy");+ h.manager.create(every(120));+ const due = START + 2 * HOUR;+ await h.tickAt(due);+ await h.passTo(due + 59 * MINUTE);+ expect(h.runs()).toMatchObject([{ status: "queued", deferredAt: due, busyMs: 59 * MINUTE }]);+ expect(h.deferred).toHaveLength(1);+ await h.passTo(due + HOUR);+ expect(h.runs()).toMatchObject([{ status: "missed", finishedAt: due + HOUR, error: "Did not run: the bot was busy for more than 60 minutes",+ errorCode: "routines.server.busyTooLong", errorParams: { minutes: 60 } }]);+ expect(h.failed.map((failure) => [failure.run.status, failure.alert])).toEqual([["missed", undefined]]);+ expect(h.routine()).toMatchObject({ enabled: true, nextRunAt: START + 4 * HOUR });++ h.bot("ready");+ await h.tickAt(START + 4 * HOUR);+ expect(h.started).toEqual(["thread-1"]);+ expect(h.runs().map((run) => run.status)).toEqual(["missed", "running"]);+ });++ it("counts only the time it was seen busy: not the time the process was down, nor the hours the computer slept", async () => {+ const h = harness(); h.bot("busy");+ h.manager.create(every(24 * 60));+ const due = START + 24 * HOUR;+ await h.tickAt(due);+ await h.passTo(due + 30 * MINUTE);+ h.at(due + 5 * HOUR); h.restart();+ expect(h.runs()).toMatchObject([{ status: "queued", busyMs: 30 * MINUTE }]);+ await h.tickAt(due + 5 * HOUR);+ await h.passTo(due + 5 * HOUR + 10 * MINUTE);+ expect(h.runs()).toMatchObject([{ status: "queued", busyMs: 40 * MINUTE }]);+ await h.tickAt(due + 13 * HOUR);+ expect(h.runs()).toMatchObject([{ status: "queued", busyMs: 42 * MINUTE }]);+ await h.passTo(due + 13 * HOUR + 18 * MINUTE);+ expect(h.runs()).toMatchObject([{ status: "missed" }]);+ });++ it("forgets the wait once the run starts: a run that waited, started, and is queued again hours later is not missed at once", async () => {+ const h = harness(); h.bot("busy");+ h.manager.create({ ...every(60), schedule: { type: "once", at: START + HOUR } });+ await h.tickAt(START + HOUR);+ await h.passTo(START + HOUR + 50 * MINUTE);+ expect(h.runs()).toMatchObject([{ status: "queued", busyMs: 50 * MINUTE }]);+ h.bot("ready");+ await h.tickAt(START + HOUR + 51 * MINUTE);+ expect(h.runs()).toMatchObject([{ status: "running" }]);+ expect(h.runs()[0]).not.toHaveProperty("busyMs");+ expect(h.disk().runs[0]).not.toHaveProperty("busyMs");++ h.at(START + 4 * HOUR);+ h.event("thread-1", "runtime.error", { message: "The AI service is overloaded (529)" });+ h.event("thread-1", "turn.completed", { ok: false, stopReason: "error" });+ expect(h.runs()).toMatchObject([{ status: "queued", retried: "provider" }]);+ h.bot("busy");+ await h.tickAt(START + 4 * HOUR + MINUTE);+ await h.passTo(START + 4 * HOUR + 30 * MINUTE);+ expect(h.runs()).toMatchObject([{ status: "queued", busyMs: 29 * MINUTE }]);+ h.bot("ready");+ await h.tickAt(START + 4 * HOUR + 31 * MINUTE);+ expect(h.runs()).toMatchObject([{ status: "running" }]);+ expect(h.failed).toEqual([]);+ });++ it("keeps an event's run and a run started by hand waiting as long as it takes: nothing comes after them", async () => {+ const h = harness(); h.bot("busy");+ const routine = h.manager.create(every(24 * 60));+ h.manager.enqueueWebhook({ webhookId: "hook", webhookName: "New lead", prompt: "Handle it", botId: "maus-1", runOn: "maus", deliveryId: "d1", receivedAt: START });+ h.manager.runNow(routine.id);+ await h.tickAt(START + MINUTE);+ await h.passTo(START + 3 * HOUR);+ expect(h.runs().map((run) => [run.triggerSource, run.status, run.busyMs])).toEqual([["webhook", "queued", undefined], ["manual", "queued", undefined]]);+ expect(h.failed).toEqual([]);+ h.bot("ready");+ await h.tickAt(START + 3 * HOUR + MINUTE);+ expect(h.started).toHaveLength(2);+ });++ it("does not give up a run queued behind its own routine's earlier run", async () => {+ const h = harness();+ h.manager.create(every(30, { overlap: "queue" }));+ await h.tickAt(START + 30 * MINUTE);+ await h.passTo(START + 150 * MINUTE);+ expect(h.runs().filter((run) => !run.skipped).map((run) => [run.status, run.busyMs])).toEqual([["running", undefined], ["queued", undefined]]);+ h.done("thread-1");+ await h.tickAt(START + 151 * MINUTE);+ expect(h.started).toEqual(["thread-1", "thread-2"]);+ });+});++describe("a run held until its cloud computer is ready", () => {+ it("is asked for only once its bot is free, adds nothing to the busy wait while it is held, and starts when the computer answers", async () => {+ const h = harness(); h.bot("busy");+ const asked: number[] = [];+ let ready: (reason: string | null) => void = () => {};+ h.options.preparing = "Waiting for its cloud computer to wake and answer";+ h.options.prepareRun = () => { asked.push(1); return new Promise((resolve) => { ready = resolve; }); };+ h.manager.create(every(24 * 60));+ const due = START + 24 * HOUR;+ await h.tickAt(due);+ await h.passTo(due + 20 * MINUTE);+ expect(asked).toEqual([]);+ expect(h.runs()).toMatchObject([{ status: "queued", busyMs: 20 * MINUTE }]);+ h.bot("ready");+ await h.passTo(due + 3 * HOUR);+ expect(asked).toEqual([1]);+ expect(h.runs()).toMatchObject([{ status: "queued", busyMs: 20 * MINUTE, attention: "Waiting for its cloud computer to wake and answer" }]);+ expect(h.failed).toEqual([]);+ ready(null);+ await new Promise((resolve) => setImmediate(resolve));+ await h.tickAt(due + 3 * HOUR + MINUTE);+ expect(h.started).toEqual(["thread-1"]);+ expect(h.runs()[0]).not.toHaveProperty("busyMs");+ });++ it("fails with the computer's reason when it is not ready, which never spaces the routine out: its next occurrence tries again", async () => {+ const h = harness();+ const reason = "The cloud computer did not answer in time, so this run did not start. The next scheduled run tries again.";+ h.options.prepareRun = () => Promise.resolve(reason);+ h.manager.create(every(5));+ for (const turn of [1, 2, 3, 4]) {+ await h.tickAt(START + turn * 5 * MINUTE);+ await new Promise((resolve) => setImmediate(resolve));+ await h.manager.tick();+ }+ expect(h.runs().map((run) => [run.status, run.error])).toEqual(Array(4).fill(["failed", reason]));+ expect(h.routine()).toMatchObject({ enabled: true, failureStreak: 4, nextRunAt: START + 25 * MINUTE });+ expect(h.routine()).not.toHaveProperty("noStartStreak");+ expect(h.manager.nextDueAt()).toBe(START + 25 * MINUTE);+ expect(h.started).toEqual([]);+ });+});++describe("occurrences that land while an earlier run of the routine is going", () => {+ it("leave one missed row for the whole run, with their count and first and last time, and are shown as already seen", async () => {+ const h = harness();+ h.manager.create(every(5));+ await h.tickAt(START + 5 * MINUTE);+ for (let minute = 10; minute <= 170; minute += 5) await h.tickAt(START + minute * MINUTE);+ const [running, skipped, ...rest] = h.runs();+ expect(rest).toEqual([]);+ expect(running).toMatchObject({ status: "running", threadId: "thread-1" });+ expect(skipped).toMatchObject({ status: "missed", scheduledFor: START + 10 * MINUTE, finishedAt: START + 170 * MINUTE, seenAt: START + 10 * MINUTE,+ error: "Skipped 33 scheduled runs because the previous run of this routine is still running",+ skipped: { count: 33, firstAt: START + 10 * MINUTE, lastAt: START + 170 * MINUTE, behind: running!.id } });+ expect(h.failed).toEqual([]);+ expect(h.changed.filter((run) => run.id === skipped!.id)).toEqual([]);+ expect(h.emitted.filter((frame) => frame.kind === "routine.run" && (frame.run as RoutineRun).id === skipped!.id)).toHaveLength(33);+ expect(h.routine()).toMatchObject({ skippedRuns: 33, lastSkippedAt: START + 170 * MINUTE });+ expect(h.disk().runs.find((run) => run.id === skipped!.id)?.skipped).toMatchObject({ count: 33 });++ h.done("thread-1");+ await h.tickAt(START + 175 * MINUTE);+ await h.tickAt(START + 180 * MINUTE);+ expect(h.runs().map((run) => [run.status, run.skipped?.count])).toEqual([["completed", undefined], ["missed", 33], ["running", undefined], ["missed", 1]]);+ });++ it("keeps the count across a restart", async () => {+ const h = harness();+ h.options.hasPendingDelegations = () => true;+ h.manager.create(every(5));+ await h.tickAt(START + 5 * MINUTE);+ h.done("thread-1");+ await h.tickAt(START + 10 * MINUTE);+ h.restart();+ await h.tickAt(START + 15 * MINUTE);+ expect(h.runs().filter((run) => run.skipped)).toMatchObject([{ skipped: { count: 2, firstAt: START + 10 * MINUTE, lastAt: START + 15 * MINUTE } }]);+ });+});++describe("the default run limit", () => {+ it("stops a run after three hours of work, fails it with the reason, and starts the next occurrence", async () => {+ const h = harness();+ h.manager.create(every(240));+ const due = START + 4 * HOUR;+ await h.tickAt(due);+ await h.passTo(due + 3 * HOUR - MINUTE);+ expect(h.runs()).toMatchObject([{ status: "running", workedMs: 3 * HOUR - MINUTE }]);+ await h.passTo(due + 3 * HOUR);+ expect(h.runs()).toMatchObject([{ status: "failed", finishedAt: due + 3 * HOUR, error: "Stopped: this run ran longer than the 3-hour limit", errorCode: "routines.server.overLimit", errorParams: { hours: 3 } }]);+ expect(h.interrupted).toEqual(["thread-1"]);+ expect(h.failed.map((failure) => failure.run.error)).toEqual(["Stopped: this run ran longer than the 3-hour limit"]);+ expect(h.routine()).toMatchObject({ enabled: true, nextRunAt: START + 8 * HOUR });+ expect(h.event("thread-1", "turn.completed", { ok: false, stopReason: "interrupted" })).toBeNull();+ await h.tickAt(START + 8 * HOUR);+ expect(h.started).toEqual(["thread-1", "thread-2"]);+ expect(h.runs().map((run) => run.status)).toEqual(["failed", "running"]);+ });++ it("does not fail a run for the hours the computer slept, or for a clock that jumped", async () => {+ const h = harness();+ h.manager.create({ ...every(60), schedule: { type: "once", at: START + HOUR } });+ const due = START + HOUR;+ await h.tickAt(due);+ await h.passTo(due + 30 * MINUTE);+ // The lid closes for nine hours: on wake one pass sees the whole gap.+ await h.tickAt(due + 30 * MINUTE + 9 * HOUR);+ expect(h.runs()).toMatchObject([{ status: "running", workedMs: 32 * MINUTE }]);+ // The clock is set back a day, then forward again.+ await h.tickAt(due - 24 * HOUR);+ await h.tickAt(due + 30 * MINUTE + 9 * HOUR + MINUTE);+ expect(h.runs()).toMatchObject([{ status: "running", workedMs: 34 * MINUTE }]);+ expect(h.failed).toEqual([]);+ await h.passTo(due + 30 * MINUTE + 9 * HOUR + MINUTE + 146 * MINUTE);+ expect(h.runs()).toMatchObject([{ status: "failed", error: "Stopped: this run ran longer than the 3-hour limit" }]);+ });++ it("does not count the time an approval or question is open, nor a wait on work handed on", async () => {+ const h = harness();+ let handedOn = false;+ h.options.hasPendingDelegations = () => handedOn;+ h.manager.create({ ...every(60), schedule: { type: "once", at: START + HOUR } });+ const due = START + HOUR;+ await h.tickAt(due);+ await h.passTo(due + HOUR);+ h.event("thread-1", "request.opened", { requestType: "question", tool: "ask", summary: "Which repository?" });+ await h.passTo(due + 11 * HOUR, 10 * MINUTE);+ expect(h.runs()).toMatchObject([{ status: "waiting", workedMs: HOUR }]);+ h.event("thread-1", "request.resolved", { behavior: "answer", source: "user" });+ await h.passTo(due + 12 * HOUR);+ expect(h.runs()).toMatchObject([{ status: "running", workedMs: 2 * HOUR }]);+ handedOn = true; h.done("thread-1");+ expect(h.runs()).toMatchObject([{ status: "waiting", waitingSince: due + 12 * HOUR }]);+ await h.passTo(due + 40 * HOUR, 30 * MINUTE);+ expect(h.runs()).toMatchObject([{ status: "waiting", workedMs: 2 * HOUR }]);+ h.event("thread-1", "turn.started");+ await h.passTo(due + 41 * HOUR - MINUTE);+ expect(h.runs()).toMatchObject([{ status: "running", workedMs: 3 * HOUR - MINUTE }]);+ await h.passTo(due + 41 * HOUR);+ expect(h.runs()).toMatchObject([{ status: "failed", error: "Stopped: this run ran longer than the 3-hour limit" }]);+ });++ it("keeps the work of a run that waits across a restart, and counts on when it goes back to work", async () => {+ const h = harness();+ h.options.hasPendingDelegations = () => true;+ h.manager.create({ ...every(60), schedule: { type: "once", at: START + HOUR } });+ await h.tickAt(START + HOUR);+ await h.passTo(START + 3 * HOUR);+ h.done("thread-1");+ h.at(START + 30 * HOUR); h.restart();+ expect(h.runs()).toMatchObject([{ status: "waiting", workedMs: 2 * HOUR }]);+ h.event("thread-1", "turn.started");+ await h.passTo(START + 31 * HOUR - MINUTE);+ expect(h.runs()).toMatchObject([{ status: "running" }]);+ await h.passTo(START + 31 * HOUR);+ expect(h.runs()).toMatchObject([{ status: "failed", error: "Stopped: this run ran longer than the 3-hour limit" }]);+ });++ it("does not count the time a run is queued, and starts its count afresh at each start", async () => {+ const h = harness(); h.bot("busy");+ h.manager.create({ ...every(60), schedule: { type: "once", at: START + HOUR } });+ await h.tickAt(START + HOUR);+ await h.passTo(START + HOUR + 50 * MINUTE);+ h.bot("ready");+ await h.passTo(START + 3 * HOUR);+ expect(h.runs()).toMatchObject([{ status: "running", startedAt: START + HOUR + 51 * MINUTE, workedMs: 69 * MINUTE }]);+ h.event("thread-1", "runtime.error", { message: "The AI service is overloaded (529)" });+ h.event("thread-1", "turn.completed", { ok: false, stopReason: "error" });+ expect(h.runs()).toMatchObject([{ status: "queued", retried: "provider" }]);+ await h.passTo(START + 3 * HOUR + MINUTE);+ expect(h.runs()).toMatchObject([{ status: "running", startedAt: START + 3 * HOUR + MINUTE }]);+ expect(h.runs()[0]!.workedMs ?? 0).toBe(0);+ await h.passTo(START + 6 * HOUR);+ expect(h.runs()).toMatchObject([{ status: "running" }]);+ await h.passTo(START + 6 * HOUR + MINUTE);+ expect(h.runs()).toMatchObject([{ status: "failed" }]);+ });++ it("gives a room goal's run twelve hours, and names that limit when it stops it", async () => {+ const h = harness();+ const goals: Array<{ threadId: string; outcome?: unknown }> = [];+ h.options.goalState = () => "ready"; h.options.createGoalTask = () => ({ threadId: "goal-thread-1" }); h.options.startGoal = async () => {};+ h.options.interruptGoal = async (_groupId, threadId, outcome) => { goals.push({ threadId, outcome }); };+ h.manager.create({ ...every(60), name: "Team goal", target: "room-goal", botId: "chief-1", groupId: "room-1", schedule: { type: "once", at: START + HOUR } });+ await h.tickAt(START + HOUR);+ await h.passTo(START + 13 * HOUR - MINUTE);+ expect(h.runs()).toMatchObject([{ status: "running", target: "room-goal", workedMs: 12 * HOUR - MINUTE }]);+ await h.passTo(START + 13 * HOUR);+ expect(h.runs()).toMatchObject([{ status: "failed", goalStatus: "limit-reached", error: "Stopped: this run ran longer than the 12-hour limit", errorParams: { hours: 12 } }]);+ expect(goals).toEqual([{ threadId: "goal-thread-1", outcome: { status: "limit-reached", detail: "Stopped: this run ran longer than the 12-hour limit" } }]);+ });++ it("applies to an event's run and to a run started by hand, and gives way to a routine's own limit of up to a day", async () => {+ const h = harness();+ const own = h.manager.create(every(24 * 60, { name: "Long build", timeoutMinutes: 1_440 }));+ expect(() => h.manager.update(own.id, { timeoutMinutes: 1_441 })).toThrow("from 5 to 1440 minutes");+ h.manager.enqueueWebhook({ webhookId: "hook", webhookName: "New lead", prompt: "Handle it", botId: "maus-2", runOn: "maus", deliveryId: "d1", receivedAt: START });+ await h.tickAt(START + MINUTE);+ h.manager.runNow(own.id);+ await h.tickAt(START + 2 * MINUTE);+ await h.passTo(START + 3 * HOUR + MINUTE);+ expect(h.runs().map((run) => [run.triggerSource, run.status])).toEqual([["webhook", "failed"], ["manual", "running"]]);+ await h.passTo(START + 24 * HOUR + MINUTE);+ expect(h.runs().find((run) => run.manual)).toMatchObject({ status: "running" });+ await h.passTo(START + 24 * HOUR + 2 * MINUTE);+ expect(h.runs().find((run) => run.manual)).toMatchObject({ status: "failed", error: "Stopped after reaching the 1440-minute run limit" });+ });++ it("wakes the scheduler each minute while a run works, with no other work due, and stops it at the limit", async () => {+ vi.useFakeTimers({ now: START });+ const h = harness();+ h.options.now = () => Date.now();+ h.restart();+ h.manager.create({ ...every(60), schedule: { type: "once", at: START + MINUTE } });+ h.manager.start();+ await vi.advanceTimersByTimeAsync(MINUTE);+ expect(h.runs()).toMatchObject([{ status: "running" }]);+ await vi.advanceTimersByTimeAsync(3 * HOUR - MINUTE);+ expect(h.runs()).toMatchObject([{ status: "running" }]);+ expect(h.runs()[0]!.workedMs).toBeGreaterThan(2 * HOUR + 55 * MINUTE);+ await vi.advanceTimersByTimeAsync(3 * MINUTE);+ expect(h.runs()).toMatchObject([{ status: "failed", error: "Stopped: this run ran longer than the 3-hour limit" }]);+ h.manager.stop();+ });+});++describe("a turn that does not stop", () => {+ const hung = () => {+ vi.useFakeTimers({ now: START });+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const h = harness();+ const stops: string[] = [];+ h.options.now = () => Date.now();+ h.options.interruptTurn = (_botId, threadId) => { stops.push(threadId); return new Promise<void>(() => {}); };+ h.restart();+ /** A pass that waits out a stop that never answers. */+ const pass = async () => { const done = h.manager.tick(); await vi.advanceTimersByTimeAsync(SCHEDULER_STOP_WAIT_MS); await done; };+ return { h, stops, warn, pass };+ };++ it("holds the scheduler ten seconds, then the other routines fire", async () => {+ const { h, warn } = hung();+ h.manager.create(every(240, { name: "Runs too long", timeoutMinutes: 30 }));+ h.manager.create(every(270, { name: "Must still fire", botId: "maus-2" }));+ vi.setSystemTime(START + 4 * HOUR); await h.manager.tick();+ expect(h.started).toEqual(["thread-1"]);++ vi.setSystemTime(START + 4 * HOUR + 30 * MINUTE);+ let finished = false;+ const pass = h.manager.tick().then(() => { finished = true; });+ await vi.advanceTimersByTimeAsync(SCHEDULER_STOP_WAIT_MS - 1);+ expect([finished, h.manager.isTicking, h.started.length]).toEqual([false, true, 1]);+ await vi.advanceTimersByTimeAsync(1);+ await pass;+ expect([finished, h.manager.isTicking]).toEqual([true, false]);+ expect(h.started).toEqual(["thread-1", "thread-2"]);+ expect(h.runs().map((run) => [run.routineName, run.status])).toEqual([["Runs too long", "failed"], ["Must still fire", "running"]]);+ expect(h.manager.schedulerState()).toEqual({ unreadable: false, slowStops: 1 });+ expect(warn.mock.calls.flat().join(" ")).toContain("did not finish in 10 s");+ });++ it("starts no new run of that routine while the stop is outstanding, sends the stop again, and says so on the row", async () => {+ const { h, stops, pass } = hung();+ const routine = h.manager.create(every(60, { timeoutMinutes: 30 }));+ vi.setSystemTime(START + HOUR); await h.manager.tick();+ vi.setSystemTime(START + HOUR + 30 * MINUTE); await pass();+ expect(h.runs()).toMatchObject([{ status: "failed", error: "Stopped after reaching the 30-minute run limit", attentionCode: "routines.server.stopPending",+ attention: "Its turn has not confirmed that it stopped. The next run waits for that, up to 5 minutes." }]);+ expect(stops).toEqual(["thread-1"]);++ // Its next occurrence comes due, and the person presses Run now: neither starts beside the turn that may still be running.+ vi.setSystemTime(START + HOUR + 30 * MINUTE + 30_000);+ h.manager.runNow(routine.id); await h.manager.tick();+ expect(h.started).toEqual(["thread-1"]);+ vi.setSystemTime(START + HOUR + 31 * MINUTE + 15_000); await pass();+ expect(stops).toEqual(["thread-1", "thread-1"]);+ expect(h.started).toEqual(["thread-1"]);+ expect(h.runs().at(-1)).toMatchObject({ status: "queued", manual: true });+ expect(h.runs().at(-1)).not.toHaveProperty("busyMs");++ // The turn's end arrives: the stop is confirmed, the mark goes, and the waiting run starts.+ h.event("thread-1", "turn.completed", { ok: false, stopReason: "interrupted" });+ expect(h.runs()[0]).toMatchObject({ status: "failed", error: "Stopped after reaching the 30-minute run limit" });+ expect(h.runs()[0]!.attention).toBeUndefined();+ await h.manager.tick();+ expect(h.started).toEqual(["thread-1", "thread-2"]);+ });++ it("stops waiting after five minutes, starts the next run, and leaves the row saying the stop was never confirmed", async () => {+ const { h, pass } = hung();+ h.manager.create(every(60, { timeoutMinutes: 55 }));+ vi.setSystemTime(START + HOUR); await h.manager.tick();+ vi.setSystemTime(START + HOUR + 55 * MINUTE); await pass();+ vi.setSystemTime(START + 2 * HOUR); await pass();+ expect(h.started).toEqual(["thread-1"]);+ expect(h.runs().filter((run) => !run.skipped).map((run) => run.status)).toEqual(["failed", "queued"]);+ vi.setSystemTime(START + HOUR + 55 * MINUTE + STOP_CONFIRM_WAIT_MS + SCHEDULER_STOP_WAIT_MS); await pass();+ expect(h.started).toEqual(["thread-1", "thread-2"]);+ expect(h.runs()[0]).toMatchObject({ status: "failed", attentionCode: "routines.server.stopUnconfirmed", attention: "Its turn never confirmed that it stopped, so the next run started without that." });+ expect(h.disk().runs[0]).toMatchObject({ attentionCode: "routines.server.stopUnconfirmed" });+ });++ it("does not keep a cancelled run's caller waiting either", async () => {+ const { h } = hung();+ const routine = h.manager.create(every(60));+ h.manager.runNow(routine.id); await h.manager.tick();+ const cancelled = h.manager.cancelRun(h.runs()[0]!.id, "Stopped by the person");+ await vi.advanceTimersByTimeAsync(SCHEDULER_STOP_WAIT_MS);+ await expect(cancelled).resolves.toMatchObject({ status: "cancelled" });+ });+});++describe("a routines.json that cannot be read", () => {+ const broken = '{"version":1,"routines":[{"id":"r1","name":"Fix new bugs","prompt":"Look for new bug rep';+ const corrupt = () => {+ const h = harness();+ h.manager.create(every(60));+ const good = readFileSync(h.file, "utf8");+ h.manager.close();+ writeFileSync(h.file, broken);+ const error = vi.spyOn(console, "error").mockImplementation(() => {});+ h.at(START + 10 * MINUTE); h.manager = new RoutineManager(h.options);+ return { h, good, error };+ };++ it("is left as it is with a copy beside it, runs nothing, refuses changes, and is flagged for the app and the health report", async () => {+ const { h, error } = corrupt();+ expect(h.manager.listRoutines()).toEqual([]);+ expect(h.manager.schedulerState()).toEqual({ unreadable: true, slowStops: 0 });+ expect(() => h.manager.create(every(30))).toThrow("Saved routines could not be read");+ await h.tickAt(START + HOUR);+ h.manager.holdFor(["no_connections"]); h.manager.markAllSeen(); h.manager.stop(); h.manager.close();+ expect(readFileSync(h.file, "utf8")).toBe(broken);+ const copies = readdirSync(dirname(h.file)).filter((name) => name.startsWith("routines.json.unreadable-"));+ expect(copies).toHaveLength(1);+ expect(readFileSync(join(dirname(h.file), copies[0]!), "utf8")).toBe(broken);+ expect(error).toHaveBeenCalledTimes(1);+ const logged = error.mock.calls.flat().join(" ");+ expect(logged).toContain("cannot be read (invalid JSON)");+ expect(logged).toContain(copies[0]);+ expect(logged).not.toContain("Fix new bugs");+ expect(h.started).toEqual([]);+ });++ it("is read again until it works: its routines come back, the app is told, and the run that was due starts", async () => {+ const { h, good, error } = corrupt();+ let readable = 0;+ h.options.onReadable = () => { readable += 1; };+ await h.tickAt(START + 20 * MINUTE);+ await h.tickAt(START + 30 * MINUTE);+ expect([readable, h.manager.schedulerState().unreadable, error.mock.calls.length]).toEqual([0, true, 1]);++ writeFileSync(h.file, good);+ h.emitted.length = 0;+ await h.tickAt(START + HOUR);+ expect([readable, h.manager.schedulerState().unreadable]).toEqual([1, false]);+ expect(h.manager.listRoutines()).toMatchObject([{ name: "Fix new bugs", enabled: true }]);+ expect(h.emitted.some((frame) => frame.kind === "routine")).toBe(true);+ expect(h.started).toEqual(["thread-1"]);+ expect(h.disk().runs).toMatchObject([{ status: "running" }]);+ expect(h.manager.create(every(30, { name: "Another" }))).toMatchObject({ name: "Another" });+ });++ it("does again what start does once it can be read: a routine that runs at startup runs, and the host is told after the routines are loaded", async () => {+ const h = harness();+ h.options.launchId = "launch-1";+ h.restart();+ h.manager.create(every(24 * 60, { runOnStartup: true }));+ const good = readFileSync(h.file, "utf8");+ h.manager.close();+ writeFileSync(h.file, broken);+ vi.spyOn(console, "error").mockImplementation(() => {});+ h.options.launchId = "launch-2";+ const seen: number[] = [];+ h.options.onReadable = () => { seen.push(h.manager.listRoutines().length); };+ h.at(START + 10 * MINUTE); h.manager = new RoutineManager(h.options);+ h.manager.start();+ expect(h.started).toEqual([]);+ writeFileSync(h.file, good);+ await h.tickAt(START + 11 * MINUTE);+ expect(seen).toEqual([1]);+ expect(h.runs()).toMatchObject([{ triggerSource: "startup", status: "running" }]);+ await h.tickAt(START + 12 * MINUTE);+ expect(h.runs()).toHaveLength(1);+ h.manager.stop();+ });++ it("loads nothing where the host starts the process afresh instead, so what settles at start sees the routines first", async () => {+ const { h, good } = corrupt();+ let asked = 0, readable = 0;+ h.options.restartsToReload = () => { asked += 1; return true; };+ h.options.onReadable = () => { readable += 1; };+ await h.tickAt(START + 20 * MINUTE);+ expect(asked).toBe(0);+ writeFileSync(h.file, good);+ await h.tickAt(START + 21 * MINUTE);+ expect([asked, readable, h.manager.schedulerState().unreadable, h.manager.listRoutines().length, h.started.length]).toEqual([1, 0, true, 0, 0]);+ expect(readFileSync(h.file, "utf8")).toBe(good);+ // The fresh process reads it at start.+ expect(h.restart().listRoutines()).toMatchObject([{ name: "Fix new bugs" }]);+ });++ it("is looked at again every minute by the running scheduler, with nothing else due", async () => {+ const h = harness();+ h.manager.create(every(60));+ const good = readFileSync(h.file, "utf8");+ h.manager.close();+ writeFileSync(h.file, broken);+ vi.spyOn(console, "error").mockImplementation(() => {});+ vi.useFakeTimers({ now: START + HOUR });+ h.options.now = () => Date.now();+ h.restart();+ h.manager.start();+ await vi.advanceTimersByTimeAsync(3 * UNREADABLE_RETRY_MS);+ expect(h.manager.schedulerState().unreadable).toBe(true);+ writeFileSync(h.file, good);+ await vi.advanceTimersByTimeAsync(UNREADABLE_RETRY_MS + 1_000);+ expect(h.manager.schedulerState().unreadable).toBe(false);+ expect(h.started).toEqual(["thread-1"]);+ h.manager.stop();+ });++ it("saves through a temporary file and a rename, so a reader never sees half a file", () => {+ const h = harness();+ h.manager.create(every(60));+ expect(readdirSync(dirname(h.file))).toEqual(["routines.json"]);+ expect(() => JSON.parse(readFileSync(h.file, "utf8"))).not.toThrow();+ });+});diff --git a/server/routine-request-schemas.ts b/server/routine-request-schemas.tsindex d7349e0e2d..48316a9b9b 100644--- a/server/routine-request-schemas.ts+++ b/server/routine-request-schemas.ts@@ -175,7 +175,7 @@ export const storedDefinitionSchema = z.object({schedule: storedScheduleSchema,runOn: z.enum(["maus", "cloud"]),durationMinutes: z.number().int().min(5).max(240),- timeoutMinutes: z.number().int().min(5).max(240).optional(),+ timeoutMinutes: z.number().int().min(5).max(1_440).optional(),continuity: z.boolean().optional(),overlap: z.enum(["skip", "queue"]).optional(),runOnStartup: z.boolean().optional(),@@ -185,7 +185,7 @@ export const storedChangesSchema = storedDefinitionSchema.partial().extend({schedule: storedScheduleChangesSchema.optional(),- timeoutMinutes: z.number().int().min(5).max(240).nullable().optional(),+ timeoutMinutes: z.number().int().min(5).max(1_440).nullable().optional(),}).strict().refine(diff --git a/server/routine-requests.test.ts b/server/routine-requests.test.tsindex ebb22467bf..25fb4f1bcf 100644--- a/server/routine-requests.test.ts+++ b/server/routine-requests.test.ts@@ -711,7 +711,7 @@ describe("RoutineRequestService", () => {threadId: "thread-a",proposal: createProposal({ timeoutMinutes: 4 }),}),- ).rejects.toThrow("timeoutMinutes must be a whole number from 5 to 240");+ ).rejects.toThrow("timeoutMinutes must be a whole number from 5 to 1440");await expect(service.propose({botId: "bot-a",@@ -781,7 +781,7 @@ describe("RoutineRequestService", () => {expect(proposed.summary).toContain("Monday, Friday");expect(proposed.summary).toContain("during 9:00–17:00 India time");expect(proposed.summary).toContain("Sep 30, 2026");- expect(proposed.summary).toContain("no run limit");+ expect(proposed.summary).toContain("default run limit (3 hours of work)");expect(store.messagesFor("thread-a")[0]?.card?.routineRequest?.operation).toMatchObject({action: "create",routine: {diff --git a/server/routine-requests.ts b/server/routine-requests.tsindex 45c0732387..0e7f7160ec 100644--- a/server/routine-requests.ts+++ b/server/routine-requests.ts@@ -1,7 +1,7 @@import { instructionsUpdateRefusal } from "./automation-instructions.ts";import { createHash } from "node:crypto";import { isDeepStrictEqual } from "node:util";-+import { ROUTINE_RUN_LIMIT_MINUTES } from "../shared/routines.ts";import { formatInstant, routineCronText } from "./routine-cron-text.ts";import { conversationLanguage } from "./server-lines.ts";import { plainClock, plainTimeZone, plainWeekdays } from "../shared/plain-time-zone.ts";@@ -215,8 +215,8 @@ function duration(value: number | undefined): number {function timeout(value: number | null | undefined): number | null | undefined {if (value == null) return value;- if (!Number.isInteger(value) || value < 5 || value > 240) {- throw new RoutineRequestError("timeoutMinutes must be a whole number from 5 to 240");+ if (!Number.isInteger(value) || value < 5 || value > 1_440) {+ throw new RoutineRequestError("timeoutMinutes must be a whole number from 5 to 1440");}return value;}@@ -677,7 +677,7 @@ function cardCopy(// Credential-shaped values never travel back through the bot's MCP response or into the transcript.const visibleInstructions = redactSecretsInText(definition.instructions);const runLimit = definition.timeoutMinutes === undefined- ? "no run limit"+ ? `default run limit (${ROUTINE_RUN_LIMIT_MINUTES / 60} hours of work)`: `${definition.timeoutMinutes} min limit`;return {title,diff --git a/server/routine-skips.test.ts b/server/routine-skips.test.tsnew file mode 100644index 0000000000..47386c7035--- /dev/null+++ b/server/routine-skips.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from "vitest";++import { ROUTINE_DEFERRAL_NOTICE_MS } from "./routine-execution.ts";+import { blockingRun, loadSkips, recordSkip } from "./routine-skips.ts";+import type { RoutineRun } from "./routines.ts";++const MINUTE = 60_000;+const run = (id: string, status: RoutineRun["status"], more: Partial<RoutineRun> = {}): RoutineRun => ({+ id, routineId: "r", routineName: "Check", target: "bot", botId: "bot-1", runOn: "maus", scheduledFor: 0, status, manual: false, createdAt: 0, ...more,+});++describe("the run an occurrence is skipped behind", () => {+ it("is the routine's own run that waits, else the one working, else the one not started", () => {+ expect(blockingRun([run("other", "running", { routineId: "x" }), run("done", "completed")], "r")).toBeUndefined();+ expect(blockingRun([run("q", "queued")], "r")).toMatchObject({ run: { id: "q" }, why: "routines.server.part.notStarted" });+ expect(blockingRun([run("q", "queued"), run("w", "running", { startedAt: 5 })], "r")).toMatchObject({ run: { id: "w" }, why: "routines.server.part.stillRunning" });+ expect(blockingRun([run("w", "running"), run("p", "waiting", { waitingSince: 7 })], "r")).toEqual({ run: expect.objectContaining({ id: "p" }), why: "routines.server.part.stillWaiting", waitingSince: 7 });+ });+});++describe("occurrences skipped for one cause", () => {+ it("share one missed row that counts them and keeps the first and last time", () => {+ const runs: RoutineRun[] = [];+ const make = () => { const row = run(`row-${runs.length}`, "queued"); runs.push(row); return row; };+ const cause = { behind: "blocker", why: "routines.server.part.stillRunning" as const };+ expect(recordSkip(runs, make, cause, 1 * MINUTE, 1 * MINUTE)).toMatchObject({ added: true, tell: false });+ expect(runs).toEqual([expect.objectContaining({ status: "missed", finishedAt: MINUTE, seenAt: MINUTE, error: "Skipped because the previous run of this routine is still running",+ errorCode: "routines.server.skippedOne", errorParams: { why: "routines.server.part.stillRunning" }, skipped: { count: 1, firstAt: MINUTE, lastAt: MINUTE, behind: "blocker" } })]);+ for (let minute = 2; minute <= 180; minute += 1) expect(recordSkip(runs, make, cause, minute * MINUTE, minute * MINUTE).added).toBe(false);+ expect(runs).toHaveLength(1);+ expect(runs[0]).toMatchObject({ finishedAt: 180 * MINUTE, error: "Skipped 180 scheduled runs because the previous run of this routine is still running",+ errorCode: "routines.server.skippedMany", errorParams: { count: 180, why: "routines.server.part.stillRunning" }, skipped: { count: 180, firstAt: MINUTE, lastAt: 180 * MINUTE } });+ });++ it("start a new row for another cause", () => {+ const runs: RoutineRun[] = [];+ const make = () => { const row = run(`row-${runs.length}`, "queued"); runs.push(row); return row; };+ recordSkip(runs, make, { behind: "first", why: "routines.server.part.stillRunning" }, 1, 1);+ recordSkip(runs, make, { behind: "no-start:first", why: "routines.server.part.computerNoStart" }, 2, 2);+ expect(runs.map((row) => [row.skipped?.behind, row.error])).toEqual([+ ["first", "Skipped because the previous run of this routine is still running"],+ ["no-start:first", "Skipped because its cloud desktop has not started, so its next tries are spaced out"],+ ]);+ });++ it("tell the owner once per waiting run, when it has waited a notice window, and show the row as unseen from then", () => {+ const runs: RoutineRun[] = [];+ const make = () => { const row = run(`row-${runs.length}`, "queued"); runs.push(row); return row; };+ const cause = { behind: "waiter", why: "routines.server.part.stillWaiting" as const, waitingSince: 0 };+ expect(recordSkip(runs, make, cause, ROUTINE_DEFERRAL_NOTICE_MS - 1, 10).tell).toBe(false);+ expect(runs[0]!.seenAt).toBe(10);+ expect(recordSkip(runs, make, cause, ROUTINE_DEFERRAL_NOTICE_MS, 20).tell).toBe(true);+ expect(runs[0]).not.toHaveProperty("seenAt");+ expect(runs[0]!.skipped).toMatchObject({ count: 2, told: true });+ expect(recordSkip(runs, make, cause, ROUTINE_DEFERRAL_NOTICE_MS * 2, 30).tell).toBe(false);+ expect(runs).toHaveLength(1);+ });+});++describe("skip counts read back from routines.json", () => {+ it("keep a whole record and drop anything out of shape", () => {+ expect(loadSkips({ count: 3, firstAt: 1, lastAt: 9, behind: "no-start:abc-1", told: true, extra: "x" })).toEqual({ count: 3, firstAt: 1, lastAt: 9, behind: "no-start:abc-1", told: true });+ expect(loadSkips({ count: 3, firstAt: 1, lastAt: 9, behind: "abc" })).toEqual({ count: 3, firstAt: 1, lastAt: 9, behind: "abc" });+ for (const bad of [undefined, null, "x", {}, { count: 0, firstAt: 1, lastAt: 1, behind: "a" }, { count: 1.5, firstAt: 1, lastAt: 1, behind: "a" }, { count: 1, firstAt: 1, lastAt: 1, behind: "a b" }, { count: 1, firstAt: "1", lastAt: 1, behind: "a" }]) {+ expect(loadSkips(bad)).toBeUndefined();+ }+ });+});diff --git a/server/routine-skips.ts b/server/routine-skips.tsnew file mode 100644index 0000000000..3a7a4678b0--- /dev/null+++ b/server/routine-skips.ts@@ -0,0 +1,57 @@+// A scheduled occurrence that does not run always leaves a `missed` row saying why. Occurrences skipped for one cause+// (the same earlier run still going, the same spacing after a cloud computer that did not start) share one row, which+// counts them and keeps the first and last time: a schedule every minute behind a run of hours adds one row, not hundreds.+import { ROUTINE_DEFERRAL_NOTICE_MS } from "./routine-execution.ts";+import { codedLine, type RoutineLineKey } from "./routine-lines.ts";+import type { RoutineRun } from "./routines.ts";++/** What a `missed` row stands for when it counts skipped occurrences. */+export interface RoutineSkips {+ /** Occurrences skipped for this cause. */+ count: number;+ /** The scheduled times of the first and the last of them. */+ firstAt: number;+ lastAt: number;+ /** The cause: the id of the run they waited behind, or `no-start:` and the id of the last run whose computer did not start. */+ behind: string;+ /** The owner was told about this cause. */+ told?: true;+}++export type SkipWhy = Extract<RoutineLineKey, "routines.server.part.stillWaiting" | "routines.server.part.stillRunning" | "routines.server.part.notStarted" | "routines.server.part.computerNoStart">;++/** A run of the same routine that an occurrence is skipped behind, and, for one that waits, since when. */+export function blockingRun(runs: readonly RoutineRun[], routineId: string): { run: RoutineRun; why: SkipWhy; waitingSince?: number } | undefined {+ const active = runs.filter((run) => run.routineId === routineId && ["queued", "running", "waiting"].includes(run.status));+ const run = active.find((candidate) => candidate.status === "waiting" && candidate.waitingSince !== undefined) ?? active.find((candidate) => candidate.status !== "queued") ?? active[0];+ if (!run) return undefined;+ if (run.status === "waiting" && run.waitingSince !== undefined) return { run, why: "routines.server.part.stillWaiting", waitingSince: run.waitingSince };+ return { run, why: run.status === "queued" ? "routines.server.part.notStarted" : "routines.server.part.stillRunning" };+}++/** Counts the occurrence at `scheduledFor` on its cause's row, which `make` adds the first time. `tell` is true once per+ * waiting run, for the first occurrence skipped after it had waited a notice window: the owner is told then, and the row+ * shows as not yet seen. Any other skip is on a row already seen: a run that is still working when the next one comes+ * due, or a spacing the owner was told about when it began, asks nothing more of them. */+export function recordSkip(runs: readonly RoutineRun[], make: () => RoutineRun, cause: { behind: string; why: SkipWhy; waitingSince?: number }, scheduledFor: number, now: number): { row: RoutineRun; added: boolean; tell: boolean } {+ const found = runs.findLast((run) => run.status === "missed" && run.skipped?.behind === cause.behind);+ const row = found ?? make();+ const skipped: RoutineSkips = found?.skipped+ ? { ...found.skipped, count: found.skipped.count + 1, lastAt: Math.max(found.skipped.lastAt, scheduledFor) }+ : { count: 1, firstAt: scheduledFor, lastAt: scheduledFor, behind: cause.behind };+ const tell = !skipped.told && cause.waitingSince !== undefined && scheduledFor >= cause.waitingSince + ROUTINE_DEFERRAL_NOTICE_MS;+ if (tell) skipped.told = true;+ const line = skipped.count === 1 ? codedLine("error", "routines.server.skippedOne", { why: cause.why }) : codedLine("error", "routines.server.skippedMany", { count: skipped.count, why: cause.why });+ Object.assign(row, line.codes, { status: "missed", error: line.text, finishedAt: now, skipped } satisfies Partial<RoutineRun>);+ if (tell) delete row.seenAt;+ else if (!found) row.seenAt = now;+ return { row, added: !found, tell };+}++/** Skip counts as routines.json may hold them; anything out of shape is dropped. */+export function loadSkips(value: unknown): RoutineSkips | undefined {+ const skips = value as Partial<RoutineSkips> | null | undefined;+ if (!skips || typeof skips !== "object" || !Number.isSafeInteger(skips.count) || skips.count! < 1 || !Number.isSafeInteger(skips.firstAt) || !Number.isSafeInteger(skips.lastAt) ||+ typeof skips.behind !== "string" || !/^[\w:-]{1,160}$/.test(skips.behind)) return undefined;+ return { count: skips.count!, firstAt: skips.firstAt!, lastAt: skips.lastAt!, behind: skips.behind, ...(skips.told === true ? { told: true } : {}) };+}diff --git a/server/routines.test.ts b/server/routines.test.tsindex 01bae8b774..151961d82a 100644--- a/server/routines.test.ts+++ b/server/routines.test.ts@@ -6,8 +6,8 @@ import { afterEach, describe, expect, it, vi } from "vitest";import type { GroupGoalRunStatus } from "../shared/group-goal-run.ts";import { isRoutineProblemRun } from "../shared/routines.ts";-import { ROUTINE_SKIPPED_WHILE_WAITING, ROUTINE_SUPERSEDED } from "./routine-execution.ts";-import { offAfterNoStarts } from "./routine-outcomes.ts";+import { ROUTINE_SUPERSEDED } from "./routine-execution.ts";+import { noStartSpacing } from "./routine-no-start.ts";import { RUN_PROGRESS_WINDOW_MS } from "./routine-progress-save.ts";import {nextOccurrence,@@ -19,6 +19,8 @@ import {} from "./routines.ts";const dirs: string[] = [];+/** Runs that were made to start: a `missed` row that only counts skipped occurrences is left out. */+const realRuns = (runs: RoutineRun[]) => runs.filter((run) => !run.skipped);const routineTurn = (id: string, name: string, text: string, trigger: "schedule" | "manual" = "schedule") =>`[${trigger === "schedule" ? "Scheduled routine" : "Routine"} ${JSON.stringify(name)} — do this now:]\nTrigger id: ${id}\n${text}`;@@ -130,7 +132,7 @@ describe("bounded scheduled overlap and run health", () => {it.each<RoutineSchedule>([input().schedule,{ type: "cron", expression: "*/5 * * * *", timeZone: "UTC" },- { type: "daily", time: "09:00", weekdays: [0, 1, 2, 3, 4, 5, 6] },+ { type: "cron", expression: "0 * * * *", timeZone: "UTC" },])("persists skipped occurrences once without changing the definition revision: %j", async schedule => {const h = harness(start);const routine = h.manager.create({ ...input(), schedule });@@ -141,6 +143,7 @@ describe("bounded scheduled overlap and run health", () => {const saved = h.manager.listRoutines()[0];expect(saved).toMatchObject({ skippedRuns: 1, lastSkippedAt: skippedAt, updatedAt: routine.updatedAt });expect(h.emitted.filter(event => event.kind === "routine").at(-1)?.routine).toMatchObject({ skippedRuns: 1 });+ expect(h.manager.listRuns().filter(run => run.skipped)).toMatchObject([{ status: "missed", scheduledFor: skippedAt, skipped: { count: 1, firstAt: skippedAt, lastAt: skippedAt } }]);expect(new RoutineManager(h.options).listRoutines()[0]).toMatchObject({ skippedRuns: 1, lastSkippedAt: skippedAt, nextRunAt: saved.nextRunAt });});@@ -155,7 +158,7 @@ describe("bounded scheduled overlap and run health", () => {h.setNow(start + 10 * 60_000); await h.manager.tick();h.setNow(start + 15 * 60_000); await h.manager.tick();expect(h.started).toHaveLength(1);- expect(h.manager.listRuns().map(run => run.status).sort()).toEqual(["queued", "waiting"]);+ expect(realRuns(h.manager.listRuns()).map(run => run.status).sort()).toEqual(["queued", "waiting"]);expect(h.manager.listRoutines()[0].skippedRuns).toBe(1);pending = false; finish(h, "thread-1", true); await h.manager.tick();await expect.poll(() => h.started.length).toBe(2);@@ -169,7 +172,8 @@ describe("bounded scheduled overlap and run health", () => {for (let minute = 5; minute <= 50; minute += 5) {h.setNow(start + minute * 60_000); await h.manager.tick();}- expect(h.manager.listRuns()).toHaveLength(1);+ expect(realRuns(h.manager.listRuns())).toHaveLength(1);+ expect(h.manager.listRuns().filter(run => run.skipped)).toMatchObject([{ status: "missed", skipped: { count: 9, firstAt: start + 10 * 60_000, lastAt: start + 50 * 60_000 } }]);expect(h.manager.listRoutines()[0]).toMatchObject({ skippedRuns: 9, overlap: "queue" });expect(new RoutineManager(h.options).listRoutines()[0]).toMatchObject({ skippedRuns: 9, overlap: "queue" });expect(h.manager.update(routine.id, { name: "Renamed" })?.overlap).toBe("queue");@@ -330,7 +334,7 @@ describe("bounded scheduled overlap and run health", () => {expect(alerts).toEqual([undefined, null, undefined, undefined]);});- it("turns a routine off after three runs in a row on a cloud computer that didn't start, and counts afresh once turned on", async () => {+ it("keeps a routine on after three runs in a row on a cloud computer that didn't start, tells the owner once, and counts afresh once it is changed", async () => {const h = harness(start);const alerts: unknown[] = [];h.options.onRunFailed = (_run, alert) => alerts.push(alert);@@ -346,24 +350,24 @@ describe("bounded scheduled overlap and run health", () => {await attempt(noStart);await attempt(noStart);expect(h.manager.listRoutines()[0]).toMatchObject({ enabled: true });+ expect(h.manager.listRoutines()[0]).not.toHaveProperty("noStartStreak");await attempt(noStart);- expect(h.manager.listRoutines()[0]).toMatchObject({ enabled: false, nextRunAt: null });- expect(alerts.at(-1)).toEqual({ detail: expect.stringContaining("turned off after 3 runs in a row") });- h.manager.update(routine.id, { enabled: true });+ expect(h.manager.listRoutines()[0]).toMatchObject({ enabled: true, nextRunAt: routine.nextRunAt, noStartStreak: 3 });+ expect(alerts.at(-1)).toEqual({ detail: expect.stringContaining("3 runs in a row failed this way. It stays on") });await attempt(noStart);- expect(h.manager.listRoutines()[0]).toMatchObject({ enabled: true });+ expect(h.manager.listRoutines()[0]).toMatchObject({ enabled: true, noStartStreak: 4 });expect(alerts.at(-1)).toBeNull();+ h.manager.update(routine.id, { name: "Renamed" });+ expect(h.manager.listRoutines()[0]).not.toHaveProperty("noStartStreak");});- it("does not count a run that started before the routine was last changed toward turning it off", () => {+ it("does not count a run that started before the routine was last changed toward spacing its runs out", () => {const error = "Maus's cloud desktop didn't start. Change where this routine runs.";const run = (id: string, createdAt: number) => ({ id, routineId: "r", status: "failed", error, createdAt, finishedAt: createdAt + 50 });const afterEdit = [run("a", 150), run("b", 160)];- const routine = () => ({ enabled: true, nextRunAt: 1, updatedAt: 100 });- const queuedBeforeEdit = run("old", 50);- expect(offAfterNoStarts(routine(), [...afterEdit, queuedBeforeEdit], queuedBeforeEdit, 300)).toBeUndefined();- const third = run("c", 170);- expect(offAfterNoStarts(routine(), [...afterEdit, third], third, 300)?.routine).toMatchObject({ enabled: false, nextRunAt: null });+ const routine = { id: "r", updatedAt: 100 };+ expect(noStartSpacing(routine, [run("old", 50), ...afterEdit])).toBeNull();+ expect(noStartSpacing(routine, [...afterEdit, run("c", 170)])).toMatchObject({ streak: 3, until: 220 + 60 * 60_000 });});it("counts restart recovery only once and sanitizes obsolete or invalid health metadata", async () => {@@ -435,13 +439,13 @@ describe("a run left waiting for the person", () => {h.setNow(first + minutes(45)); ask(h, "thread-1");h.setNow(first + minutes(60)); await h.manager.tick();- expect(h.manager.listRuns()).toHaveLength(1);- expect(h.manager.listRuns()[0]).toMatchObject({ status: "waiting", waitingSince: first + minutes(45) });+ expect(realRuns(h.manager.listRuns())).toHaveLength(1);+ expect(realRuns(h.manager.listRuns())[0]).toMatchObject({ status: "waiting", waitingSince: first + minutes(45) });expect(h.manager.listRoutines()[0]).toMatchObject({ skippedRuns: 1, lastSkippedAt: first + minutes(60) });expect(h.failed).toEqual([]);h.setNow(first + minutes(120)); await h.manager.tick();- const [next, asked] = h.manager.listRuns();+ const [next, asked] = realRuns(h.manager.listRuns());expect(asked).toMatchObject({ status: "cancelled", error: ROUTINE_SUPERSEDED, threadId: "thread-1" });expect(next).toMatchObject({ status: "running", scheduledFor: first + minutes(120), threadId: "thread-2" });expect(h.interruptedTurns).toEqual([{ botId: "maus-1", threadId: "thread-1" }]);@@ -511,7 +515,7 @@ describe("a run left waiting for the person", () => {it.each(["skip", "queue"] as const)("keeps today's %s overlap behind a run that was answered and is still working", async (overlap) => {const h = harness(monday);- const routine = h.manager.create({ ...daily, ...(overlap === "queue" ? { overlap } : {}) });+ const routine = h.manager.create({ ...daily, schedule: { type: "interval", everyMinutes: 60, anchorAt: monday }, ...(overlap === "queue" ? { overlap } : {}) });h.setNow(routine.nextRunAt!); await h.manager.tick();h.setNow(routine.nextRunAt! + minutes(5)); ask(h, "thread-1");h.setNow(routine.nextRunAt! + minutes(10));@@ -525,7 +529,8 @@ describe("a run left waiting for the person", () => {expect(h.failed).toEqual([]);expect(h.manager.listRuns().find((run) => run.threadId === "thread-1")?.status).toBe("running");if (overlap === "skip") {- expect(h.manager.listRuns()).toHaveLength(1);+ expect(realRuns(h.manager.listRuns())).toHaveLength(1);+ expect(h.manager.listRuns().filter((run) => run.skipped)).toMatchObject([{ status: "missed", error: "Skipped because the previous run of this routine is still running", seenAt: day2 }]);expect(h.manager.listRoutines()[0]).toMatchObject({ skippedRuns: 1, lastSkippedAt: day2 });expect(h.deferred).toEqual([]);} else {@@ -545,8 +550,10 @@ describe("a run left waiting for the person", () => {}const missed = h.manager.listRuns().filter((run) => run.status === "missed");- expect(missed).toEqual([expect.objectContaining({ error: ROUTINE_SKIPPED_WHILE_WAITING, scheduledFor: monday + minutes(35) })]);- expect(h.failed.map((run) => run.id)).toEqual([missed[0]!.id]);+ expect(missed).toEqual([expect.objectContaining({ error: "Skipped 23 scheduled runs because the previous run of this routine is still waiting", scheduledFor: monday + minutes(10),+ skipped: expect.objectContaining({ count: 23, firstAt: monday + minutes(10), lastAt: monday + minutes(120), told: true }) })]);+ expect(missed[0]).not.toHaveProperty("seenAt");+ expect(h.failed).toEqual([expect.objectContaining({ id: missed[0]!.id, error: "Skipped 6 scheduled runs because the previous run of this routine is still waiting" })]);expect(h.manager.listRuns().find((run) => run.threadId === "thread-1")?.status).toBe("waiting");expect(h.interruptedTurns).toEqual([]);expect(h.started).toHaveLength(1);@@ -591,11 +598,11 @@ describe("a run left waiting for the person", () => {expect(restarted.listRuns()[0]).toMatchObject({ status: "waiting", waitingSince: day2 - minutes(20) });h.setNow(day2); await restarted.tick();- expect(restarted.listRuns()).toHaveLength(1);+ expect(realRuns(restarted.listRuns())).toHaveLength(1);expect(restarted.listRoutines()[0].skippedRuns).toBe(1);const day3 = restarted.listRoutines()[0].nextRunAt!;h.setNow(day3); await restarted.tick();- expect(restarted.listRuns().map((run) => [run.threadId, run.status])).toEqual([["thread-2", "running"], ["thread-1", "cancelled"]]);+ expect(realRuns(restarted.listRuns()).map((run) => [run.threadId, run.status])).toEqual([["thread-2", "running"], ["thread-1", "cancelled"]]);});it("keeps the wait when this computer was offline too long to start the occurrence", async () => {@@ -806,14 +813,13 @@ describe("cron routines use the existing persistent scheduler", () => {const routine = h.manager.create(input({ ...monthly, expression: "* * * * *" }));h.setNow(routine.nextRunAt!); await h.manager.tick();h.setNow(start + 5 * 60_000); await h.manager.tick();- expect(h.manager.listRuns()).toHaveLength(1);- expect(h.manager.listRuns()[0].status).toBe("queued");+ expect(realRuns(h.manager.listRuns())).toMatchObject([{ status: "queued" }]);h.setBot("ready"); await h.manager.tick();h.setNow(start + 6 * 60_000); await h.manager.tick();- expect(h.manager.listRuns()).toHaveLength(1); expect(h.started).toHaveLength(1);+ expect(realRuns(h.manager.listRuns())).toHaveLength(1); expect(h.started).toHaveLength(1);h.manager.handleRuntimeEvent({ eventId: "done", provider: "fake", threadId: "thread-1", createdAt: new Date().toISOString(), type: "turn.completed", ok: true });h.setNow(start + 7 * 60_000); await h.manager.tick();- expect(h.manager.listRuns()).toHaveLength(2); expect(h.started).toHaveLength(2);+ expect(realRuns(h.manager.listRuns())).toHaveLength(2); expect(h.started).toHaveLength(2);});it("stamps busy-target deferral, notices once past the window, then dispatches normally", async () => {@@ -830,13 +836,13 @@ describe("cron routines use the existing persistent scheduler", () => {expect(h.deferred).toHaveLength(1);h.setNow(routine.nextRunAt! + 45 * 60_000); await h.manager.tick();expect(h.deferred).toHaveLength(1);- expect(h.manager.listRuns()[0]).toMatchObject({+ expect(realRuns(h.manager.listRuns())[0]).toMatchObject({status: "queued",deferredNoticeAt: routine.nextRunAt! + 30 * 60_000,});h.setBot("ready"); await h.manager.tick();expect(h.started).toHaveLength(1);- expect(h.manager.listRuns()[0]?.status).toBe("running");+ expect(realRuns(h.manager.listRuns())[0]?.status).toBe("running");});it("leaves promptly dispatched runs unstamped and quiet", async () => {@@ -847,7 +853,7 @@ describe("cron routines use the existing persistent scheduler", () => {h.setBot("ready"); h.setNow(routine.nextRunAt! + 5 * 60_000); await h.manager.tick();expect(h.deferred).toHaveLength(0);expect(h.started).toHaveLength(1);- expect(h.manager.listRuns()[0]?.status).toBe("running");+ expect(realRuns(h.manager.listRuns())[0]?.status).toBe("running");const clean = harness(start);const prompt = clean.manager.create(input({ ...monthly, expression: "* * * * *" }));clean.setNow(prompt.nextRunAt!); await clean.manager.tick();@@ -1380,8 +1386,9 @@ describe("RoutineManager", () => {expect(routine.timeoutMinutes).toBe(5);expect(h.manager.update(routine.id, { timeoutMinutes: null })).not.toHaveProperty("timeoutMinutes");expect(h.manager.create({ ...input, name: "Unlimited" })).not.toHaveProperty("timeoutMinutes");- expect(() => h.manager.create({ ...input, timeoutMinutes: 4 })).toThrow(/5 to 240/);- expect(() => h.manager.create({ ...input, timeoutMinutes: 241 })).toThrow(/5 to 240/);+ expect(() => h.manager.create({ ...input, timeoutMinutes: 4 })).toThrow(/5 to 1440/);+ expect(h.manager.create({ ...input, name: "A long build", timeoutMinutes: 1_440 }).timeoutMinutes).toBe(1_440);+ expect(() => h.manager.create({ ...input, timeoutMinutes: 1_441 })).toThrow(/5 to 1440/);});it("validates interval cadence and preserves its explicit anchor", () => {@@ -1985,13 +1992,13 @@ describe("RoutineManager", () => {h.setNow(anchorAt + 5 * 60_000);await h.manager.tick();- expect(h.manager.listRuns()).toHaveLength(1);+ expect(realRuns(h.manager.listRuns())).toHaveLength(1);expect(h.manager.listRoutines()[0]?.nextRunAt).toBe(anchorAt + 10 * 60_000);h.manager.failThread("thread-1", "Finished test run", { cause: "refused" });h.setNow(anchorAt + 10 * 60_000);await h.manager.tick();- expect(h.manager.listRuns()).toHaveLength(2);+ expect(realRuns(h.manager.listRuns())).toHaveLength(2);expect(h.started).toHaveLength(2);});@@ -2119,7 +2126,7 @@ describe("RoutineManager", () => {h.setBot("ready");await h.manager.tick();- expect(h.manager.listRuns()).toMatchObject([{+ expect(realRuns(h.manager.listRuns())).toMatchObject([{status: "running",scheduledFor: latestAt,threadId: "thread-1",diff --git a/server/routines.ts b/server/routines.tsindex 2c92c918dd..7e04c3b7f5 100644--- a/server/routines.ts+++ b/server/routines.ts@@ -1,5 +1,5 @@import { randomUUID } from "node:crypto";-import { mkdirSync, readFileSync } from "node:fs";+import { mkdirSync } from "node:fs";import { dirname, join } from "node:path";import { DATA_DIR } from "./config.ts";@@ -20,17 +20,20 @@ import {} from "../shared/routines.ts";import type { PartPair, RoutinePart } from "./package-parts.ts";import {- composeExecutionPrompt, continuityCarry, ROUTINE_DEFERRAL_NOTICE_MS, ROUTINE_SKIPPED_WHILE_WAITING, ROUTINE_SUPERSEDED,- routineFailure, routineHostWarning, skipNeedsNotice, supersededBy,+ composeExecutionPrompt, continuityCarry, ROUTINE_DEFERRAL_NOTICE_MS, ROUTINE_SUPERSEDED,+ routineFailure, routineHostWarning, supersededBy,} from "./routine-execution.ts";import {- dispatchRefusal, engineFacts, loadOwnerNotices, nextScheduledRun, recoverRun, requeueOnce, weekRuns, type RoutineAlert, type RoutineFailureFacts, type RoutineOwnerNotice,+ dispatchRefusal, engineFacts, nextScheduledRun, recoverRun, requeueOnce, weekRuns, type RoutineAlert, type RoutineFailureFacts, type RoutineOwnerNotice,} from "./routine-recovery.ts";-import { activeMs, askOf, settleAsk, waitingFor, type RoutineRunAsk } from "./routine-waits.ts";-import { failsLikeLastOutcome, offAfterNoStarts, outcomesNewestFirst } from "./routine-outcomes.ts"; import { createRunGate, type RunPreparation } from "./routine-run-gate.ts";-import { EVENT_RETRY_WINDOW_MS, loadEventReceipts, MAX_EVENT_RECEIPTS, type EventRunReceipt } from "./routine-event-receipts.ts";-import { attachmentPathsOf, attachmentsMalformed, cloneAttachments } from "./routine-attachments.ts";-import { loadInstalledPackage, loadRequestReceipts, loadRoutine, loadRun } from "./routine-load.ts";+import { askOf, settleAsk, waitingFor, type RoutineRunAsk } from "./routine-waits.ts";+import { failsLikeLastOutcome, outcomesNewestFirst } from "./routine-outcomes.ts"; import { createRunGate, type RunPreparation } from "./routine-run-gate.ts";+import { busyWait, markStop, RunClock, runOverLimit, SlowStops, withBoundedStops, type StopState } from "./routine-bounds.ts"; import { keepUnreadableAside, readRoutineFile, UNREADABLE_RETRY_MS } from "./routine-file.ts";+import { afterSpacing, noStartAlert, noStartSpacing, turnBackOn } from "./routine-no-start.ts"; import { blockingRun, recordSkip, type RoutineSkips } from "./routine-skips.ts";+import { routineHealthOf, type RoutineHealth } from "./routine-health.ts";+import { EVENT_RETRY_WINDOW_MS, MAX_EVENT_RECEIPTS, type EventRunReceipt } from "./routine-event-receipts.ts";+import { attachmentPathsOf, cloneAttachments } from "./routine-attachments.ts";+import { loadInstalledPackage, matchingRequestReceipt, rememberRequest } from "./routine-load.ts";import { applyHolds, holdCauses, type AppliedHolds } from "./routine-holds.ts";import { cancelUnfinishedRuns, interruptRunTurns } from "./routine-stops.ts";import { sanitizeInput } from "./routine-input.ts";@@ -48,7 +51,6 @@ export type RoutineRunOn = "maus" | "cloud";export type RoutineTarget = "bot" | "room-goal";export type RoutineGoalStatus = Exclude<GroupGoalRunStatus, "working">;-export interface Routine extends RoutineTroubleCode {id: string;name: string;@@ -75,6 +77,8 @@ export interface Routine extends RoutineTroubleCode {skippedRuns?: number;lastSkippedAt?: number;failureStreak?: number;+ /** Its newest runs in a row whose cloud computer did not start, while its scheduled runs are spaced out for it. */+ noStartStreak?: number;weekRuns?: { ok: number; total: number };warning?: string;heldFor?: RoutineHoldCause;@@ -110,6 +114,10 @@ export interface RoutineRun extends RoutineLineCodes {manual: boolean;deferredAt?: number;deferredNoticeAt?: number;+ /** How long a scheduled run has been seen queued behind its bot's other work, added up pass by pass (routine-bounds.ts `busyWait`). */+ busyMs?: number;+ /** On a `missed` row: the occurrences it stands for (routine-skips.ts). */+ skipped?: RoutineSkips;/** A queued run starts no earlier than this. */retryAt?: number;retried?: RoutineRetryCause;@@ -118,6 +126,8 @@ export interface RoutineRun extends RoutineLineCodes {asked?: RoutineRunAsk;/** Time spent waiting on the person's answers, which the run limit does not count. */waitedMs?: number;+ /** Time spent in status `running` since its current start, added up pass by pass: what the default run limit counts (routine-bounds.ts). */+ workedMs?: number;triggerSource?: RoutineRunTrigger;/** "app": a connected-app event started it; "wait": a wait's follow-up did (its triggerSource stays "webhook", an outside event). sameConversation: its trigger keeps one conversation (routine-same-conversation.ts). */eventSource?: "app" | "wait"; sameConversation?: true;@@ -196,6 +206,7 @@ interface RoutineFile {routineRequestReceipts?: RoutineRequestReceipt[];webhookRunReceipts?: EventRunReceipt[];startupLaunchId?: string;+ noStartOffsChecked?: true;ownerNotices?: RoutineOwnerNotice[];holds?: RoutineHoldCause[];}@@ -276,6 +287,13 @@ export interface RoutineManagerOptions {/** A Cloud home woken from a sleep it was stopped for (server/cloud-power.ts): not a startup, so no "run on startup". */skipStartupRuns?: boolean; /** What a run needs before it starts (its cloud computer awake and answering): null when nothing, else resolves null when ready or with why the run cannot start. `preparing` is the run's line meanwhile. Only a run nobody started by hand is held; the signal aborts once the run no longer waits to start. */ prepareRun?: RunPreparation<RoutineRun>; preparing?: string;checks?: RoutineChecks;+ /** routines.json, unreadable at start, can be read now. True: the host starts the process afresh instead, so that what+ * settles at start (who owns a Cloud's routines, its holds) sees them before any runs; nothing is loaded here. */+ restartsToReload?: () => boolean;+ /** routines.json became readable again while this process ran, and its routines are loaded. */+ onReadable?: () => void;+ /** This copy is frozen by a move to another home (move-freeze.ts): nothing here is turned back on. */+ moveFrozen?: () => boolean;}const CATCH_UP_MS = 12 * 60 * 60_000;@@ -319,47 +337,31 @@ export class RoutineManager {private holds: RoutineHoldCause[] = [];private readonly failureFacts = new Map<string, RoutineFailureFacts>();/** Saves are refused while unreadable, so an empty state never overwrites the file; malformedAttachments: a saved list failed to load, so no clear may trust attachmentPaths(). */- private unreadable = false; private malformedAttachments = false;+ private unreadable = false; private malformedAttachments = false; private noStartOffsChecked = false; private turnedBackOn: Routine[] = [];+ private readonly clock = new RunClock(); private readonly slowStops = new SlowStops(() => this.now(), (threadId, state) => this.stopChanged(threadId, state));private frozenPending = false;private readonly bootedAt: number;private readonly checking = new Set<string>(); private readonly progress = new RunProgressSave(() => this.file, () => this.save()); private readonly gate = createRunGate<RoutineRun>((run, signal) => this.options.prepareRun?.(cloneRun(run), signal) ?? null, () => this.tickInBackground());constructor(options: RoutineManagerOptions) {- this.options = options;+ this.options = withBoundedStops(options, this.slowStops);this.file = options.file ?? join(DATA_DIR, "routines.json"); this.disk = new OwnedFile(this.file, { mode: 0o600 });this.now = options.now ?? Date.now;this.bootedAt = this.now();- try {- const text = readFileSync(this.file, "utf8"), disk = JSON.parse(text) as Partial<RoutineFile>; this.disk.loaded(text);- if (disk === null || typeof disk !== "object" || Array.isArray(disk)) throw new Error("Invalid routines file");- for (const key of ["routines", "runs", "routineRequestReceipts", "webhookRunReceipts"] as const) {- if (key in disk && !Array.isArray(disk[key])) throw new Error(`Invalid routines file: ${key} is not a list`);- }- this.routines = Array.isArray(disk.routines) ? disk.routines.flatMap((routine) => {- const loaded = loadRoutine(routine, this.now());- if (!loaded) {- console.warn(`routines: keeping ${String(routine.id)} on disk unscheduled; its schedule could not load`);- this.unloadedRoutines.push(routine);- }- return loaded ? [loaded] : [];- }) : [];- this.runs = Array.isArray(disk.runs) ? disk.runs.map(loadRun) : []; this.malformedAttachments = attachmentsMalformed([...(disk.routines ?? []), ...(disk.runs ?? [])]);- this.routineRequestReceipts = loadRequestReceipts(disk.routineRequestReceipts);- this.webhookRunReceipts = loadEventReceipts(disk.webhookRunReceipts, this.runs, this.now());- this.frozenPending = disk.frozenResultsCleared !== true;- this.ownerNotices = loadOwnerNotices(disk.ownerNotices);- this.holds = holdCauses(disk.holds);- if (typeof disk.startupLaunchId === "string") this.startupLaunchId = disk.startupLaunchId;- } catch (error) {- this.routines = []; this.unloadedRoutines = []; this.runs = []; this.routineRequestReceipts = []; this.webhookRunReceipts = [];- if ((error as NodeJS.ErrnoException).code !== "ENOENT") {- this.unreadable = true;- // JSON.parse errors can echo a fragment of the input, so they never reach the log.- const reason = error instanceof SyntaxError ? "invalid JSON"- : error instanceof Error ? error.message : "unable to read routines";- console.error(`routines: ignoring unreadable ${this.file}: ${reason}`);- }- }+ this.load();+ }++ /** Reads routines.json into memory; false while it is there but cannot be read, when nothing in memory is trusted or saved. */+ private load(read = readRoutineFile(this.file, this.now())): boolean {+ const before = this.unreadable;+ this.unreadable = read.state === "unreadable";+ // The file's path and a fixed reason only: its content never reaches the log.+ if (read.state === "unreadable" && !before) console.error(`routines: ${this.file} cannot be read (${read.reason}), so no routine runs until it can; it is left as it is, with a copy at ${keepUnreadableAside(this.file) ?? "no path (the copy failed)"}`);+ if (read.state !== "ok") return read.state === "missing";+ ({ routines: this.routines, unloadedRoutines: this.unloadedRoutines, runs: this.runs, malformedAttachments: this.malformedAttachments, routineRequestReceipts: this.routineRequestReceipts,+ webhookRunReceipts: this.webhookRunReceipts, frozenPending: this.frozenPending, ownerNotices: this.ownerNotices, holds: this.holds,+ startupLaunchId: this.startupLaunchId, noStartOffsChecked: this.noStartOffsChecked } = read);+ this.disk.loaded(read.text);const cut: RoutineRun[] = [];for (const run of this.runs.filter((candidate) => candidate.status === "running" || candidate.status === "waiting")) {settleAsk(run, undefined, this.now());@@ -373,12 +375,16 @@ export class RoutineManager {}cut.push(cloneRun(run));}- if (cut.length > 0) this.saveLater();+ const look = !this.noStartOffsChecked && this.options.moveFrozen?.() !== true;+ if (look) this.turnedBackOn = turnBackOn(this.routines, this.runs, this.holds[0], this.now(), (schedule, now) => this.initialOccurrence(schedule, now)).filter((routine) => routine.enabled);+ if (look) this.noStartOffsChecked = true;+ if (cut.length > 0 || look) this.saveLater();for (const run of cut) {if (run.threadId) this.options.onRunCut?.(run);this.notifyRunChanged(run);if (run.status === "failed") this.options.onRunFailed?.(run);}+ return true;}/** Files every saved routine and run names, unloaded rows too; null while routines.json is unreadable or a row's attachments are malformed, so nothing can clear them. */@@ -403,8 +409,8 @@ export class RoutineManager {const success = outcomes.findIndex(run => run.status === "completed");const failures = success < 0 ? outcomes.length : success;const { installedPackage: _installedPackage, ...visible } = cloneRoutine(routine);- const warning = routineHostWarning(routine), week = weekRuns(this.runs, routine.id, this.now());- return { ...visible, ...(failures ? { failureStreak: failures } : {}), ...(week ? { weekRuns: week } : {}), ...(warning ? { warning } : {}) };+ const warning = routineHostWarning(routine), week = weekRuns(this.runs, routine.id, this.now()), spaced = noStartSpacing(routine, this.runs);+ return { ...visible, ...(failures ? { failureStreak: failures } : {}), ...(spaced ? { noStartStreak: spaced.streak } : {}), ...(week ? { weekRuns: week } : {}), ...(warning ? { warning } : {}) };}packageStamps(): Array<{ routineId: string; botId: string; enabled: boolean; stamp: RoutinePackageStamp }> {@@ -424,10 +430,17 @@ export class RoutineManager {return true;}- wakeHold(horizonMs = WAKE_HORIZON_MS) { return wakeHoldOf(this.routines, this.runs, this.now(), horizonMs); }+ /** Whether routines.json cannot be read, and how often stopping a turn outlasted its wait: for the app and the health report. */+ schedulerState(): { unreadable: boolean; slowStops: number } { return { unreadable: this.unreadable, slowStops: this.slowStops.count }; }+ health(cap: number): RoutineHealth[] { return routineHealthOf(this.routines, this.runs, cap); }+ /** Routines an earlier version had switched off that this start turned back on, handed over once, for a line to their bots. */+ takeTurnedBackOn(): Routine[] { return this.turnedBackOn.splice(0).map(cloneRoutine); }+ /** Each routine with the next run it will really make: one whose runs are spaced out is not due for the occurrences it skips. */+ private planned(routines: readonly Routine[]): Routine[] { return routines.map((routine) => routine.checks || runsOnce(routine.schedule) ? routine : afterSpacing(routine, this.runs, this.now(), nextOccurrence)); }+ wakeHold(horizonMs = WAKE_HORIZON_MS) { return wakeHoldOf(this.planned(this.routines), this.runs, this.now(), horizonMs); }/** A Cloud home's sleep check (server/routine-due.ts). */hasActiveRuns(): boolean { return activeRunsOf(this.runs, this.now()); }- nextDueAt(): number | null { return nextDueOf(this.routines.filter((routine) => routine.target === "room-goal" || !this.options.pausedText?.(routine.botId)), this.runs, this.now()); }+ nextDueAt(): number | null { return nextDueOf(this.planned(this.routines.filter((routine) => routine.target === "room-goal" || !this.options.pausedText?.(routine.botId))), this.runs, this.now()); }listRuns(from?: number, to?: number): RoutineRun[] {return this.runs@@ -932,7 +945,7 @@ export class RoutineManager {if (this.closing || this.timer) return;if (!this.startupRunsQueued) this.startupRunsQueued = this.queueStartupRuns();this.timer = startDueTimer({ run: () => this.tick(), now: this.now, onError: (error) => console.error("routines: a scheduler pass failed", error),- next: () => schedulerDueOf(this.routines, this.runs, this.now(), this.bootedAt + CHECK_BOOT_HOLD_MS, (routine) => this.targetState(routine) === "missing") });+ next: () => this.unreadable ? this.now() + UNREADABLE_RETRY_MS : schedulerDueOf(this.routines, this.runs, this.now(), this.bootedAt + CHECK_BOOT_HOLD_MS, (routine) => this.targetState(routine) === "missing") });}stop() {@@ -988,10 +1001,16 @@ export class RoutineManager {this.ticking = true;try {const now = this.now(); this.gate.sweep((id) => this.runs.some((run) => run.id === id && run.status === "queued"));+ if (this.unreadable) {+ const read = readRoutineFile(this.file, now);+ if (read.state === "unreadable" || this.options.restartsToReload?.() === true) return;+ this.load(read); this.startupRunsQueued = this.queueStartupRuns();+ this.options.onReadable?.(); for (const routine of this.routines) this.emitRoutine(routine);+ }+ for (const threadId of this.slowStops.sweep()) interruptRunTurns(this.runs.filter((run) => run.threadId === threadId).slice(-1), this.options);for (const run of this.runs) {- if (!["running", "waiting"].includes(run.status) || run.startedAt == null || run.timeoutMinutes == null ||- activeMs(run, now) < run.timeoutMinutes * 60_000) continue;- await this.stopRun(run, `Stopped after reaching the ${run.timeoutMinutes}-minute run limit`, "limit-reached");+ const over = runOverLimit(run, this.clock, now);+ if (over) await this.stopRun(Object.assign(run, over.codes), over.text, "limit-reached");}const isDue = (routine: Routine) => !this.closing && routine.enabled && this.targetState(routine) !== "missing" && (!routine.checks? routine.nextRunAt != null && routine.nextRunAt <= now@@ -1003,7 +1022,7 @@ export class RoutineManager {for (const run of stale) await this.cancelRun(run.id, ROUTINE_SUPERSEDED);}const dueRoutines = this.routines.filter(isDue);- const scheduledRuns: RoutineRun[] = [];+ const scheduledRuns: RoutineRun[] = [], countedSkips: RoutineRun[] = [];const allocations: ResultsThreadAllocation[] = [];const checks: Array<{ id: string; hold?: CheckHold }> = [];if (dueRoutines.length > 0) {@@ -1021,12 +1040,12 @@ export class RoutineManager {const scheduledFor = routine.schedule.type === "interval" && late <= CATCH_UP_MS? latestIntervalOccurrence(routine.schedule, now) ?? pendingAt: pendingAt;- const overlapping = !runsOnce(routine.schedule) && this.runs.some(- (run) => run.routineId === routine.id && ["queued", "running", "waiting"].includes(run.status),- );+ const once = runsOnce(routine.schedule), blocker = once ? undefined : blockingRun(this.runs, routine.id), spaced = once ? null : noStartSpacing(routine, this.runs);const scheduledQueued = this.runs.some(run => run.routineId === routine.id && run.status === "queued" &&(run.triggerSource ?? (run.manual ? "manual" : "schedule")) === "schedule");- if (!overlapping || (routine.overlap === "queue" && !scheduledQueued)) {+ const skipFor = blocker && !(routine.overlap === "queue" && !scheduledQueued) ? { behind: blocker.run.id, why: blocker.why, waitingSince: blocker.waitingSince }+ : spaced && spaced.until > now ? { behind: `no-start:${spaced.last.id}`, why: "routines.server.part.computerNoStart" as const } : undefined;+ if (!skipFor) {const run = this.newRun(routine, scheduledFor, false, allocations);// A reset is a state, not a moment: it still holds however late the computer wakes.if (late > CATCH_UP_MS && routine.schedule.type !== "limit_reset") {@@ -1036,15 +1055,8 @@ export class RoutineManager {}scheduledRuns.push(run);} else {- const waiting = this.runs.find((run) => run.routineId === routine.id && run.status === "waiting" && run.waitingSince !== undefined);- // Once per wait, an occurrence skipped behind it leaves a missed receipt, so the owner is told.- if (waiting && skipNeedsNotice(scheduledFor, waiting.waitingSince!, routine.lastSkippedAt)) {- const missed = this.newRun(routine, scheduledFor, false, allocations);- missed.status = "missed";- missed.finishedAt = now;- missed.error = ROUTINE_SKIPPED_WHILE_WAITING;- scheduledRuns.push(missed);- }+ const skip = recordSkip(this.runs, () => this.newRun(routine, scheduledFor, false, allocations), skipFor, scheduledFor, now);+ (skip.tell ? scheduledRuns : countedSkips).push(skip.row);routine.skippedRuns = Math.min(Number.MAX_SAFE_INTEGER, (routine.skippedRuns ?? 0) + 1);routine.lastSkippedAt = scheduledFor;}@@ -1055,6 +1067,8 @@ export class RoutineManager {// Publish only after the scheduler batch is durable: reporting may persist transcript cards.for (const routine of dueRoutines) this.emitRoutine(routine);for (const run of scheduledRuns) this.emitRun(run);+ // A counted skip the owner is not told about changes its row only: no card, no notice.+ for (const run of countedSkips) this.options.emit?.({ kind: "routine.run", run: cloneRun(run) });for (const run of scheduledRuns) {if (run.status === "missed") this.options.onRunFailed?.(cloneRun(run));}@@ -1096,7 +1110,8 @@ export class RoutineManager {}const sameRoutineWorking = (triggerSource === "schedule" || run.sameConversation) && this.runs.some(other =>other.id !== run.id && other.routineId === run.routineId && ["running", "waiting"].includes(other.status));- const state = sameRoutineWorking ? "busy" : this.targetState(run);+ const held = sameRoutineWorking || this.runs.some((other) => other.routineId === run.routineId && this.slowStops.holds(other.threadId));+ const state = held ? "busy" : this.targetState(run);if (state === "busy") {if (run.deferredAt == null) {run.deferredAt = now;@@ -1109,6 +1124,9 @@ export class RoutineManager {this.emitRun(run);this.options.onRunDeferred?.(cloneRun(run));}+ const busy = busyWait(run, this.clock, triggerSource === "schedule" && !held && run.checkKey === undefined, now);+ if (busy.missed) this.failRun(Object.assign(run, busy.missed.codes), busy.missed.text, "missed");+ else if (busy.changed) this.saveLater();continue;}if (state === "missing") { this.failRun(run, this.missingTargetMessage(run.target)); continue; }@@ -1131,7 +1149,7 @@ export class RoutineManager {: "Could not create a task for this run");continue;}- Object.assign(run, { threadId: task.threadId, startedAt, status: "running" } satisfies Partial<RoutineRun>);+ Object.assign(run, { threadId: task.threadId, startedAt, status: "running" } satisfies Partial<RoutineRun>); this.clock.from(run, "workedMs", startedAt); delete run.workedMs; this.clock.stop(run, "busyMs", true);try { this.save(); } catch (error) { Object.assign(run, { status: "queued", startedAt: undefined } satisfies Partial<RoutineRun>); throw error; }this.emitRun(run);try {@@ -1228,6 +1246,7 @@ export class RoutineManager {handleRuntimeEvent(event: RuntimeEvent): RoutineRun | null {const run = this.runs.find((r) => r.threadId === event.threadId && ["running", "waiting"].includes(r.status));+ if (event.type === "turn.completed") this.slowStops.confirmed(event.threadId);if (!run || (run.target === "bot" && run.status === "waiting" && !run.asked && this.options.routineTurn?.(event.threadId) === false)) return null;if (event.type === "turn.started" || event.type === "turn.completed") settleAsk(run, undefined, this.now());// A room goal's orchestrator owns its result (finishGoalRun); a member's completion is intermediate.@@ -1239,8 +1258,7 @@ export class RoutineManager {)) return null;if (event.type === "turn.started") {- run.status = "running";- run.attention = undefined;+ this.clock.work(run, this.now());} else if (event.type === "request.opened") {run.asked ??= askOf(event, this.now());this.wait(run, waitingFor(run.asked));@@ -1250,8 +1268,7 @@ export class RoutineManager {void this.stopRun(run, unanswered, "stopped");return cloneRun(run);}- run.status = "running";- run.attention = undefined;+ this.clock.work(run, this.now());} else if (event.type === "item.completed" && event.itemType === "assistant_text") {run.output = clipRunOutput(redactSecretsInText(event.text).trim(), 2_000);} else if (event.type === "runtime.error") {@@ -1341,7 +1358,7 @@ export class RoutineManager {/** Timed from when it began, so a later occurrence can tell a wait that went unanswered. */private wait(run: RoutineRun, attention: string | undefined) {if (run.status !== "waiting" || run.waitingSince === undefined) run.waitingSince = this.now();- Object.assign(run, { status: "waiting", attention } satisfies Partial<RoutineRun>);+ this.clock.rest(run, this.now()); Object.assign(run, { status: "waiting", attention } satisfies Partial<RoutineRun>);}private async stopRun(run: RoutineRun, detail: string, status: "stopped" | "limit-reached") {@@ -1354,10 +1371,10 @@ export class RoutineManager {private failRun(run: RoutineRun, message: string, status: "failed" | "missed" = "failed", alert?: RoutineAlert | null) {Object.assign(run, { status, attention: undefined, error: redactSecretsInText(message).slice(0, 500), finishedAt: this.now() } satisfies Partial<RoutineRun>);- const off = offAfterNoStarts(this.routines.find((routine) => routine.id === run.routineId), this.runs, run, this.now());- this.saveLater(); this.emitRun(run); if (off) this.emitRoutine(off.routine);+ const spaced = status === "failed" ? noStartAlert(this.routines.find((routine) => routine.id === run.routineId), this.runs, run) : undefined;+ this.saveLater(); this.emitRun(run);const repeat = failsLikeLastOutcome(this.runs, run) || (run.checkKey !== undefined && outcomesNewestFirst(this.runs, run.routineId, run.id)[0]?.status === "failed");- this.options.onRunFailed?.(cloneRun(run), off?.alert ?? (alert === undefined && repeat ? null : alert));+ this.options.onRunFailed?.(cloneRun(run), spaced ?? (alert === undefined && repeat ? null : alert));}private advancePastOccurrence(routine: Routine, now: number, occurrence: number) {@@ -1472,33 +1489,13 @@ export class RoutineManager {}}- private matchingRoutineRequestReceipt(request: RoutineRequestCommit): RoutineRequestReceipt | null {- const receipt = this.routineRequestReceipts.find((candidate) => candidate.requestId === request.requestId);- if (!receipt) return null;- if (- receipt.action !== request.action ||- receipt.messageId !== request.messageId ||- receipt.botId !== request.botId ||- receipt.threadId !== request.threadId ||- receipt.fingerprintVersion !== request.fingerprintVersion ||- receipt.fingerprint !== request.fingerprint- ) {- throw new Error("Routine request receipt does not match this confirmation card");- }- return receipt;- }+ private matchingRoutineRequestReceipt(request: RoutineRequestCommit): RoutineRequestReceipt | null { return matchingRequestReceipt(this.routineRequestReceipts, request); }+ private rememberRoutineRequest(request: RoutineRequestCommit, resultId: string, appliedAt: number) { rememberRequest(this.routineRequestReceipts, request, resultId, appliedAt); }- private rememberRoutineRequest(- request: RoutineRequestCommit,- resultId: string,- appliedAt: number,- ) {- const existing = this.matchingRoutineRequestReceipt(request);- if (existing) {- if (existing.resultId !== resultId) throw new Error("Routine request receipt has another result");- return;- }- this.routineRequestReceipts.unshift({ ...request, resultId, appliedAt });+ /** The row of a run whose stop did not finish in time says so, until the stop is confirmed. */+ private stopChanged(threadId: string, state: StopState) {+ const run = this.runs.findLast((candidate) => candidate.threadId === threadId);+ if (run && markStop(run, state)) { this.saveLater(); this.timer?.poke(); this.options.emit?.({ kind: "routine.run", run: cloneRun(run) }); }}private assertWritable(): void {@@ -1546,7 +1543,7 @@ export class RoutineManager {runs: this.runs,routineRequestReceipts: this.routineRequestReceipts,webhookRunReceipts: this.webhookRunReceipts,- ...(this.startupLaunchId === undefined ? {} : { startupLaunchId: this.startupLaunchId }),+ ...(this.startupLaunchId === undefined ? {} : { startupLaunchId: this.startupLaunchId }), ...(this.noStartOffsChecked ? { noStartOffsChecked: true } : {}),...(this.ownerNotices.length ? { ownerNotices: this.ownerNotices } : {}),...(this.holds.length ? { holds: this.holds } : {}),} satisfies RoutineFile));diff --git a/server/workspace-backup.test.ts b/server/workspace-backup.test.tsindex 96e1335f60..93fb1da4b1 100644--- a/server/workspace-backup.test.ts+++ b/server/workspace-backup.test.ts@@ -240,6 +240,8 @@ describe("encrypted full workspace backups", () => {expect(followup).not.toHaveProperty("prompt");} finally { restoredDb.close(); }expect(readJson(join(target, "routines.json"))).toMatchObject({ routines: [{ enabled: false }], runs: [{ status: "failed" }, { status: "completed" }] });+ // A restore counts as a change to each routine, so nothing later reads an old stamp as the moment something else switched it off.+ expect(Date.now() - readJson(join(target, "routines.json")).routines[0].updatedAt).toBeLessThan(5 * 60_000);expect(readJson(join(target, "webhooks.json"))).toMatchObject({ webhooks: [{ enabled: false }], deliveries: [{ id: "delivery" }] });expect(readJson(join(target, "webhooks.json")).webhooks[0].secretHash).toMatch(/^[a-f0-9]{64}$/);expect(readJson(join(target, "webhooks.json")).webhooks[0].secretHash).not.toBe("a".repeat(64));diff --git a/server/workspace-backup.ts b/server/workspace-backup.tsindex a397329755..513d4d8872 100644--- a/server/workspace-backup.ts+++ b/server/workspace-backup.ts@@ -763,6 +763,8 @@ function prepareRestore(dataDir: string, id: string, manifest: Manifest): stringif (!record(value)) throw new Error("Invalid routine definitions in workspace backup.");if (Array.isArray(value.routines)) for (const routine of value.routines) if (record(routine)) {routine.enabled = false;+ // A restore is a change to the routine: nothing may read its old stamp as the moment something else switched it off.+ routine.updatedAt = Math.max(Date.now(), (typeof routine.updatedAt === "number" ? routine.updatedAt : 0) + 1);if (typeof routine.prompt === "string") routine.prompt = paths.text(routine.prompt);}if (Array.isArray(value.runs)) for (const run of value.runs) {diff --git a/shared/package-format.ts b/shared/package-format.tsindex bf372c9fe7..1928892497 100644--- a/shared/package-format.ts+++ b/shared/package-format.ts@@ -244,7 +244,7 @@ const packageDocumentV1Schema = z.object({runOn: z.enum(["maus", "cloud"]),schedule: packageRoutineScheduleSchema,durationMinutes: z.number().int().min(5).max(240),- timeoutMinutes: z.number().int().min(5).max(240).optional(),+ timeoutMinutes: z.number().int().min(5).max(1_440).optional(),overlap: z.enum(["skip", "queue"]).optional(),enabledAfterInstall: z.literal(false),})).max(50).optional(),diff --git a/shared/team-backup.ts b/shared/team-backup.tsindex 368e29dbea..e438a86152 100644--- a/shared/team-backup.ts+++ b/shared/team-backup.ts@@ -149,7 +149,7 @@ const backupSchema = z.object({target: z.enum(["bot", "room-goal"]), botId: key, groupId: key.optional(),runOn: z.enum(["maus", "cloud"]), schedule,durationMinutes: z.number().finite().positive(),- timeoutMinutes: z.number().int().min(5).max(240).optional(),+ timeoutMinutes: z.number().int().min(5).max(1_440).optional(),checks: z.array(z.enum(["calendar", "mail", "runs"])).max(3).optional(),access: z.literal("read-and-draft").optional(),deliver: z.literal("brief").optional(),diff --git a/src/components/RoutineCalendarPage.tsx b/src/components/RoutineCalendarPage.tsxindex fb5a7472b9..7216ca11f4 100644--- a/src/components/RoutineCalendarPage.tsx+++ b/src/components/RoutineCalendarPage.tsx@@ -81,7 +81,7 @@ import {type RoutineSchedule,type RoutineScheduleInput,type RoutineTarget,-} from "@/lib/routines";+} from "@/lib/routines"; import { ROUTINE_GOAL_RUN_LIMIT_MINUTES, ROUTINE_RUN_LIMIT_MAX_MINUTES, ROUTINE_RUN_LIMIT_MINUTES } from "@/lib/routines";import { api, openBotThread, openThread, useStore, type Bot, type Group } from "@/state/store";import { RoutineScheduleNote } from "./RoutineScheduleNote";import { CalendarEventCard, HOUR_HEIGHT, statusState } from "./routines/CalendarEventCard";@@ -89,7 +89,7 @@ import { CalendarEventCard, HOUR_HEIGHT, statusState } from "./routines/Calendarconst ALL_DAYS = [0, 1, 2, 3, 4, 5, 6];const WEEKDAYS = [1, 2, 3, 4, 5];const INTERVAL_PRESETS = [5, 10, 15, 30, 60];-const EVENT_DURATION_OPTIONS = Array.from({ length: 240 / CALENDAR_SLOT_MINUTES }, (_, index) => (index + 1) * CALENDAR_SLOT_MINUTES);+const EVENT_DURATION_OPTIONS = Array.from({ length: 240 / CALENDAR_SLOT_MINUTES }, (_, index) => (index + 1) * CALENDAR_SLOT_MINUTES), RUN_LIMIT_OPTIONS = [...EVENT_DURATION_OPTIONS, 300, 360, 480, 720, ROUTINE_RUN_LIMIT_MAX_MINUTES];import { BOT_DRAG_TYPE, EVENT_DRAG_TYPE, LimitResetMarker, type ResetDrop } from "./routines/LimitResetMarkers";export type EventKind = "routine" | "call";@@ -766,20 +766,20 @@ export function EventEditor({)}</>);- const runLimitControls = kind === "routine" && (+ const defaultRunLimit = durationLabel(isRoomGoal ? ROUTINE_GOAL_RUN_LIMIT_MINUTES : ROUTINE_RUN_LIMIT_MINUTES), runLimitControls = kind === "routine" && (<details className="rounded-xl border border-hairline/40 bg-inset/40 px-3 py-2.5"><summary className="cursor-pointer select-none text-[12px] font-medium text-ink-secondary hover:text-ink">- {timeoutMinutes == null ? t("routines.runLimit.none") : t("routines.runLimit.some", { duration: durationLabel(timeoutMinutes) })}+ {timeoutMinutes == null ? t("routines.runLimit.none", { duration: defaultRunLimit }) : t("routines.runLimit.some", { duration: durationLabel(timeoutMinutes) })}</summary><div className="mt-3 border-t border-hairline/35 pt-3"><label className="flex flex-wrap items-center gap-2 text-[12px] text-ink"><span>{t("routines.runLimit.stopAfter")}</span><Select aria-label={t("routines.runLimit.label")} value={timeoutMinutes ?? ""} onChange={(event) => setTimeoutMinutes(event.target.value ? Number(event.target.value) : null)}>- <option value="">{t("routines.runLimit.noLimit")}</option>- {EVENT_DURATION_OPTIONS.map((minutes) => <option key={minutes} value={minutes}>{durationLabel(minutes)}</option>)}+ <option value="">{t("routines.runLimit.noLimit", { duration: defaultRunLimit })}</option>+ {RUN_LIMIT_OPTIONS.map((minutes) => <option key={minutes} value={minutes}>{durationLabel(minutes)}</option>)}</Select></label>- <div className="mt-1.5 text-[11px] leading-relaxed text-ink-secondary">{t("routines.runLimit.help")}</div>+ <div className="mt-1.5 text-[11px] leading-relaxed text-ink-secondary">{t("routines.runLimit.help", { duration: defaultRunLimit })}</div>{recurrence !== "none" && <div className="mt-3"><label className="flex flex-wrap items-center gap-2 text-[12px] text-ink"><span>{t("routines.overlapLabel")}</span>@@ -1468,7 +1468,7 @@ export function EventDetails({)}{!isCall && !isRoomGoal && <DrawerField label={t("routines.results.label")}><div className="text-[13px] text-ink">{resultsTitle}</div></DrawerField>}{attachments.length > 0 && <DrawerField label={t("routines.drawer.attachments")}><AttachmentChips attachments={attachments} />{call && <div className="mt-1.5 text-[11px] leading-relaxed text-ink-secondary">{t(call.botIds.length > 1 ? "routines.drawer.callSharedHelp" : "routines.drawer.callKeptHelp")}</div>}</DrawerField>}- {advanced && !isCall && <DrawerField label={t("routines.drawer.runLimit")}><div className="text-[13px] text-ink">{safetyLimit == null ? t("routines.drawer.noTimeLimit") : t("routines.drawer.stopsAfter", { duration: durationLabel(safetyLimit) })}</div></DrawerField>}+ {advanced && !isCall && <DrawerField label={t("routines.drawer.runLimit")}><div className="text-[13px] text-ink">{safetyLimit == null ? t("routines.drawer.noTimeLimit", { duration: durationLabel(isRoomGoal ? ROUTINE_GOAL_RUN_LIMIT_MINUTES : ROUTINE_RUN_LIMIT_MINUTES) }) : t("routines.drawer.stopsAfter", { duration: durationLabel(safetyLimit) })}</div></DrawerField>}{!isCall && (<DrawerField label={t("routines.logs")} action={routine && <button type="button" onClick={() => { dispatch({ type: "showRoutines", section: "logs", routineId: routine.id, botId: routine.botId }); onClose(); }} className="flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[11px] text-accent-text hover:bg-raised"><FileText size={11} />{t("routines.drawer.allRuns")}</button>}>{recentRuns.length === 0diff --git a/src/components/TriggerCard.tsx b/src/components/TriggerCard.tsxindex 57463113f1..5695c2cfed 100644--- a/src/components/TriggerCard.tsx+++ b/src/components/TriggerCard.tsx@@ -2,7 +2,7 @@ import { lazy, Suspense, useState } from "react";import { createPortal } from "react-dom";import { Undo2, Zap } from "lucide-react";-import { automationFor, automationSentence, automationStatus, capital, cardAutomation, firstRunLine, lastWhen, nextWhen, runLine } from "@/lib/automations";+import { automationFor, automationSentence, automationStatus, capital, cardAutomation, firstRunLine, lastWhen, latestRun, nextWhen, runLine } from "@/lib/automations";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { saveWebhookCredential, webhookCredentialStore } from "@/lib/webhook-credentials";@@ -45,7 +45,7 @@ export function TriggerCard({ card, threadId }: { card: OptionCardData; threadIdconst botName = state.bots.find((bot) => bot.id === automation.botId)?.name ?? t("routines.unavailableBot");const sentence = automationSentence(automation, botName);const status = automationStatus(automation);- const last = automation.runs.find((run) => run.status !== "queued");+ const last = latestRun(automation);const next = automation.nextRunAt != null ? nextWhen(automation.nextRunAt) : null;const lastRan = last && `${t("automations.card.lastRan", { when: lastWhen(last.startedAt ?? last.scheduledFor) })} ${runLine(last).mark} ${runLine(last).text}`;let line: string;diff --git a/src/components/TriggersPage.tsx b/src/components/TriggersPage.tsxindex 4944adb8bb..23965f6f03 100644--- a/src/components/TriggersPage.tsx+++ b/src/components/TriggersPage.tsx@@ -107,7 +107,8 @@ export function TriggersPage({ onBack, onOpenRoom }: { onBack: () => void; onOpe<div className="min-h-0 flex-1 overflow-y-auto"><div className="mx-auto w-full max-w-3xl p-4 sm:p-6"><LimitWarnings botFilter={showFilter ? botFilter : "all"} />- {all.length === 0 && state.routinesLoadState !== "loading" && state.hydrated ? (+ {state.config?.routinesUnreadable && <div role="alert" className="mb-4 rounded-lg bg-danger/10 p-3 text-[12px] leading-relaxed text-danger" data-routines-unreadable="">{t("routines.unreadable")}</div>}+ {all.length === 0 && !state.config?.routinesUnreadable && state.routinesLoadState !== "loading" && state.hydrated ? (<section aria-label={t("automations.empty.title")} className="px-6 py-16 text-center"><div className="mx-auto mb-4 flex size-12 items-center justify-center rounded-2xl bg-accent/10 text-accent"><Zap size={22} /></div><h2 className="text-[17px] font-semibold text-ink">{t("automations.empty.title")}</h2>@@ -134,6 +135,7 @@ export function TriggersPage({ onBack, onOpenRoom }: { onBack: () => void; onOpe<span aria-hidden="true" className="size-2 shrink-0 self-center rounded-full bg-danger" /><span>{problemLine.when} {problemLine.mark} {problemLine.text}</span></button>}+ {!!automation.noStartStreak && <div className="mt-1 text-[13px] text-warning" data-automation-no-start="">{t("routines.noStartStreak", { count: automation.noStartStreak })}</div>}{actions.error && actions.errorFor?.endsWith(`:${automation.id}`) && <p role="alert" className="mt-1 text-[12px] text-danger">{actions.error}</p>}</div>{status.state !== "done" && <Switch checked={automation.enabled} disabled={actions.busy === `toggle:${automation.id}`} aria-label={t("automations.toggle", { name: automation.name })} onClick={() => void actions.toggle(automation)} className="relative z-10 mt-0.5 shrink-0" />}diff --git a/src/components/bot-panel/pages.tsx b/src/components/bot-panel/pages.tsxindex 3cab2897dc..732a232837 100644--- a/src/components/bot-panel/pages.tsx+++ b/src/components/bot-panel/pages.tsx@@ -147,6 +147,7 @@ export function RoutinesPage({ bot, derived }: PageContext) {heldBots={state.config?.heldBots}loading={state.routinesLoadState === "loading" && derived.botRoutines.length === 0}error={state.routinesLoadState === "error"}+ unreadable={state.config?.routinesUnreadable}onOpen={setEditing}onLogs={(routine) => dispatch({ type: "showRoutines", section: "logs", botId: bot.id, routineId: routine.id })}onToggle={(routine) => dispatch({ type: "updateRoutine", routineId: routine.id, patch: { enabled: !routine.enabled } })}diff --git a/src/components/bot-settings/RoutinesSection.tsx b/src/components/bot-settings/RoutinesSection.tsxindex d775c78009..5075651abc 100644--- a/src/components/bot-settings/RoutinesSection.tsx+++ b/src/components/bot-settings/RoutinesSection.tsx@@ -17,7 +17,7 @@ export function RoutinesSection({ bot, routines, runs, defaultRunOn }: { bot: Bo<button type="button" onClick={() => dispatch({ type: "showRoutines", section: "logs", botId: bot.id })} className="flex items-center gap-1.5 rounded-lg bg-control px-3 py-2 text-[12px] text-ink hover:bg-raised-hover"><FileText size={13} />{t("routines.logs")}</button></div></div>- <RoutineList routines={routines} runs={runs} pausedBots={state.config?.pausedBots} heldBots={state.config?.heldBots} loading={state.routinesLoadState === "loading" && routines.length === 0} error={state.routinesLoadState === "error"} onOpen={setEditing} onLogs={(routine) => dispatch({ type: "showRoutines", section: "logs", botId: bot.id, routineId: routine.id })} onToggle={(routine) => dispatch({ type: "updateRoutine", routineId: routine.id, patch: { enabled: !routine.enabled } })} />+ <RoutineList routines={routines} runs={runs} pausedBots={state.config?.pausedBots} heldBots={state.config?.heldBots} loading={state.routinesLoadState === "loading" && routines.length === 0} error={state.routinesLoadState === "error"} unreadable={state.config?.routinesUnreadable} onOpen={setEditing} onLogs={(routine) => dispatch({ type: "showRoutines", section: "logs", botId: bot.id, routineId: routine.id })} onToggle={(routine) => dispatch({ type: "updateRoutine", routineId: routine.id, patch: { enabled: !routine.enabled } })} /><button type="button" onClick={() => dispatch({ type: "showRoutines", section: "schedule", view: "list", botId: bot.id })} className="self-start text-[12px] text-accent hover:underline">{t("computer.routines.openTitle")} <ChevronRight size={14} aria-hidden="true" className="inline align-[-2px] rtl:-scale-x-100" /></button>{editing && <RoutineEditor key={bot.id} routine={editing === "new" ? undefined : editing} bots={[bot]} lockedBotId={bot.id} defaultRunOn={defaultRunOn} onClose={() => setEditing(null)} />}</div>;diff --git a/src/components/routines/RoutineList.tsx b/src/components/routines/RoutineList.tsxindex 2a874df256..c09d927aea 100644--- a/src/components/routines/RoutineList.tsx+++ b/src/components/routines/RoutineList.tsx@@ -8,7 +8,7 @@ import { latestRoutineRun, routineDateTime, routineFinished, routineHeldNote, roimport type { Bot } from "@/state/store";import { Switch } from "../SettingsPrimitives";-export function RoutineList({ routines, runs, bots, pausedBots, heldBots, loading, error, onOpen, onLogs, onToggle }: {+export function RoutineList({ routines, runs, bots, pausedBots, heldBots, loading, error, unreadable, onOpen, onLogs, onToggle }: {routines: Routine[];runs: RoutineRun[];bots?: Bot[];@@ -18,6 +18,8 @@ export function RoutineList({ routines, runs, bots, pausedBots, heldBots, loadinheldBots?: readonly string[];loading?: boolean;error?: boolean;+ /** The server cannot read its saved routines. */+ unreadable?: boolean;onOpen: (routine: Routine) => void;onLogs: (routine: Routine) => void;onToggle?: (routine: Routine) => void;@@ -25,8 +27,9 @@ export function RoutineList({ routines, runs, bots, pausedBots, heldBots, loadinconst sorted = [...routines].sort((a, b) => Number(b.enabled) - Number(a.enabled) || (a.nextRunAt ?? Infinity) - (b.nextRunAt ?? Infinity) || a.name.localeCompare(b.name));return <div className="space-y-3" aria-label={t("routines.list")}>{error && <div role="alert" className="rounded-lg bg-danger/10 p-3 text-[12px] text-danger">{t("routines.loadError")}</div>}+ {unreadable && <div role="alert" className="rounded-lg bg-danger/10 p-3 text-[12px] leading-relaxed text-danger" data-routines-unreadable="">{t("routines.unreadable")}</div>}{loading && <p role="status" className="flex items-center gap-2 p-3 text-[12px] text-ink-secondary"><Loader2 size={14} className="animate-spin" />{t("routines.loading")}</p>}- {!loading && !error && sorted.length === 0 && <div className="rounded-xl border border-dashed border-hairline/50 p-5 text-center text-[13px] text-ink-secondary"><Repeat2 size={20} className="mx-auto mb-2 opacity-60" />{t("routines.empty")}</div>}+ {!loading && !error && !unreadable && sorted.length === 0 && <div className="rounded-xl border border-dashed border-hairline/50 p-5 text-center text-[13px] text-ink-secondary"><Repeat2 size={20} className="mx-auto mb-2 opacity-60" />{t("routines.empty")}</div>}{sorted.map((routine) => {const latest = latestRoutineRun(routine.id, runs);const said = latest && (latest.attention ? "attention" : latest.error ? "error" : latest.output ? "output" : null);@@ -51,6 +54,7 @@ export function RoutineList({ routines, runs, bots, pausedBots, heldBots, loadin</div>{latest && said && <p className={cn("mt-2 line-clamp-2 whitespace-pre-wrap text-[12px] leading-relaxed", latest.error ? "text-danger" : "text-ink-secondary")}>{routineRunText(latest, said)}</p>}{!!routine.failureStreak && <p className="mt-2 text-[12px] text-danger">{t("routines.failureStreak", { count: routine.failureStreak })}</p>}+ {!!routine.noStartStreak && <p className="mt-2 text-[12px] leading-relaxed text-warning" data-routine-no-start="">{t("routines.noStartStreak", { count: routine.noStartStreak })}</p>}{routine.weekRuns && <p className="mt-2 text-[12px] text-ink-secondary">{t(routine.weekRuns.total === 1 ? "routines.weekRunsOne" : "routines.weekRuns", routine.weekRuns)}</p>}{routine.warning && <p className="mt-2 text-[12px] leading-relaxed text-warning">{routine.warning}</p>}{routine.enabled && pausedBots?.includes(routine.botId) && <p className="mt-2 text-[12px] leading-relaxed text-warning" data-routine-bot-paused="">diff --git a/src/components/routines/RoutineViews.test.ts b/src/components/routines/RoutineViews.test.tsindex e1f7cb5f99..538ab393b9 100644--- a/src/components/routines/RoutineViews.test.ts+++ b/src/components/routines/RoutineViews.test.ts@@ -28,6 +28,25 @@ describe("routine list", () => {expect(list()).not.toContain("Swap awake bots");});+ it("says a routine whose cloud desktop keeps failing to start stays on, in the person's language", () => {+ const markup = list({ routines: [{ ...routine, failureStreak: 3, noStartStreak: 3 }] });+ expect(markup).toContain("Its cloud desktop did not start 3 runs in a row. This routine stays on and tries again less often until the cloud desktop starts.");+ expect(markup).toContain("data-routine-no-start");+ expect(list()).not.toContain("data-routine-no-start");+ setLocale("pt-br");+ try {+ expect(list({ routines: [{ ...routine, noStartStreak: 4 }] })).toContain("O desktop na nuvem não iniciou em 4 execuções seguidas. Esta rotina continua ligada");+ } finally { setLocale("en"); }+ });++ it("says saved routines could not be read instead of showing an empty list", () => {+ const markup = list({ routines: [], runs: [], unreadable: true });+ expect(markup).toContain("Your saved routines could not be read, so none of them can run right now. Nothing was deleted");+ expect(markup).toContain('role="alert"');+ expect(markup).not.toContain("No schedules yet");+ expect(list({ routines: [], runs: [] })).not.toContain("data-routines-unreadable");+ });+it("shows saved skips and recent failure streaks without claiming all offline occurrences were counted", () => {const markup = list({ routines: [{ ...routine, skippedRuns: 3, lastSkippedAt: 100, failureStreak: 2 }] });expect(markup).toContain("Scheduled occurrences skipped while busy: 3");@@ -110,6 +129,16 @@ describe("routine list", () => {expect(list({ routines: [{ ...routine, enabled: false }] })).not.toContain("Next Jan");});+ it("keeps showing the run at work as the latest while occurrences are skipped behind it", () => {+ const working = { ...run, id: "working", createdAt: 200, scheduledFor: 200, status: "running" as const, output: undefined };+ const counted = { ...run, id: "counted", createdAt: 300, scheduledFor: 300, status: "missed" as const, output: undefined, seenAt: 300,+ error: "Skipped 4 scheduled runs because the previous run of this routine is still running", skipped: { count: 4, firstAt: 300, lastAt: 900 } };+ expect(latestRoutineRun(routine.id, [working, counted])).toBe(working);+ expect(list({ runs: [working, counted] })).toContain("Latest: Running");+ const told = { ...counted, seenAt: undefined, skipped: { ...counted.skipped, told: true as const } };+ expect(latestRoutineRun(routine.id, [working, told])).toBe(told);+ });+it("chooses a new pending run ahead of an older run that finished later", () => {const pending = { ...run, id: "new", createdAt: 200, scheduledFor: 200, status: "waiting" as const, attention: "Waiting for work it handed on to finish" };expect(latestRoutineRun(routine.id, [{ ...run, finishedAt: 300 }, pending])).toBe(pending);diff --git a/src/lib/automations.test.ts b/src/lib/automations.test.tsindex db57dda73a..a5bd40d5c0 100644--- a/src/lib/automations.test.ts+++ b/src/lib/automations.test.ts@@ -107,6 +107,17 @@ describe("status: Working, Paused, Needs you", () => {expect(automationStatus(automation([run("failed", at(0, 9), { error: "Provider crashed" }), run("completed", at(-1, 9)), run("failed", at(-2, 9))])).state).toBe("working");});+ it("does not take a row that only counts skipped occurrences for a failure, or for the latest run", () => {+ const counted = run("missed", at(0, 9, 5), { error: "Skipped because the previous run of this routine is still running", seenAt: at(0, 9, 5), skipped: { count: 1, firstAt: at(0, 9, 5), lastAt: at(0, 9, 5) } });+ const withOneFailure = automation([counted, run("failed", at(0, 9), { error: "Provider crashed" }), run("completed", at(-1, 9))]);+ expect(automationStatus(withOneFailure).state).toBe("working");+ expect(statusLine(automation([counted, run("completed", at(0, 9, 2))]), NOW)).toBe("On · last ran today 9:02 AM · next: Monday 9:00 AM");+ expect(statusLine(automation([counted, run("running", at(0, 9, 2))]), NOW)).toContain("running now");+ // One the owner was told about is a result like any other.+ const told = { ...counted, seenAt: undefined, skipped: { ...counted.skipped!, told: true as const } };+ expect(automationStatus(automation([told, run("failed", at(0, 9), { error: "Provider crashed" })])).state).toBe("needs-you");+ });+it("is Paused when switched off, whatever its runs", () => {expect(automationStatus(automation([run("failed", at(0, 9)), run("failed", at(-1, 9))], { enabled: false })).state).toBe("paused");});diff --git a/src/lib/automations.ts b/src/lib/automations.tsindex 66003bff6f..daedc06e0f 100644--- a/src/lib/automations.ts+++ b/src/lib/automations.ts@@ -4,7 +4,7 @@ import { cronPresetText, cronText } from "@/lib/cron-text";import { clockOptions } from "@/lib/clock-time";import { activeLocale, t } from "@/lib/i18n";import type { LocaleKey } from "@/locales";-import { ROUTINE_HANDOFF_WAIT, isRoutineProblemRun, type Routine, type RoutineRun, type RoutineSchedule } from "@/lib/routines";+import { ROUTINE_HANDOFF_WAIT, isCountedSkip, isRoutineProblemRun, type Routine, type RoutineRun, type RoutineSchedule } from "@/lib/routines";import type { WebhookAttempt, WebhookTrigger } from "@/lib/webhooks";import type { AppTrigger } from "@/lib/app-triggers";import { appProblem, appStatusParts, appWhen, skippedToday } from "@/lib/app-automations";@@ -35,6 +35,8 @@ export interface Automation {checkTroubleCode?: string;/** Its runs read and draft only. */readsAndDrafts?: boolean;+ /** Its newest runs in a row whose cloud desktop did not start, while its scheduled runs are spaced out for it. */+ noStartStreak?: number;}const runTime = (run: RoutineRun) => run.startedAt ?? run.scheduledFor ?? run.createdAt;@@ -49,7 +51,7 @@ export function automationsFrom(sources: { routines: readonly Routine[]; webhookkind: "schedule", id: routine.id, name: routine.name, botId: routine.botId, instructions: routine.prompt, enabled: routine.enabled,schedule: routine.schedule, nextRunAt: routine.enabled ? routine.nextRunAt : null, runs: runsOf(routine.id),...(routine.checkedAt !== undefined ? { checkedAt: routine.checkedAt } : {}), ...(routine.checkTrouble ? { checkTrouble: routine.checkTrouble, ...(routine.checkTroubleCode ? { checkTroubleCode: routine.checkTroubleCode } : {}) } : {}),- ...(routine.access === "read-and-draft" ? { readsAndDrafts: true } : {}),+ ...(routine.access === "read-and-draft" ? { readsAndDrafts: true } : {}), ...(routine.noStartStreak ? { noStartStreak: routine.noStartStreak } : {}),})),...sources.webhooks.map((webhook): Automation => ({kind: "webhook", id: webhook.id, name: webhook.name, botId: webhook.botId, instructions: webhook.prompt, enabled: webhook.enabled,@@ -237,6 +239,8 @@ export interface AutomationStatus {}const isProblem = (run: RoutineRun) => run.status === "failed" || run.status === "missed";+/** The automation's newest run that started or was due to: not one still queued, nor a row that only counts skipped occurrences. */+export const latestRun = (automation: Pick<Automation, "runs">): RoutineRun | undefined => automation.runs.find((run) => run.status !== "queued" && !isCountedSkip(run));const SIGNED_OUT = /sign(ed)?[ -]?(in|out)\b|log(ged)?[ -]?(in|out)\b|unauthori[sz]ed|\b401\b|not authenticated|authentication (failed|required)|(token|session|credential)s? (has |have )?expired|expired (token|session|credential)|invalid api key|reconnect/i;const OUT_OF_CREDIT = /credit|quota|billing|payment|insufficient|out of tokens|usage limit|rate.?limit|\b429\b|limit (reached|exceeded)|plan limit/i;const OUT_OF_TIME = /run limit|time limit|timed out|minute limit/i;@@ -266,7 +270,7 @@ export function automationStatus(automation: Pick<Automation, "enabled" | "runs"const app = automation.appTrigger && appProblem(automation.appTrigger);if (app) return { state: "needs-you", ...app };if (automation.checkTrouble) return { state: "needs-you", reason: routineLineText(automation.checkTroubleCode, automation.checkTrouble), fix: SIGNED_OUT.test(automation.checkTrouble) ? "reconnect" : "run" };- const settled = automation.runs.filter((run) => run.status !== "cancelled" && run.status !== "queued");+ const settled = automation.runs.filter((run) => run.status !== "cancelled" && run.status !== "queued" && !isCountedSkip(run));const latest = settled[0];if (runAwaitingAnswer(settled)) return { state: "needs-you", reason: t("automations.reason.answer"), fix: "answer" };if (latest && isProblem(latest)) {@@ -312,7 +316,7 @@ export function statusLine(automation: Automation, now = Date.now()): string {const first = firstRunLine(automation, now);if (first) return automation.readsAndDrafts ? `${first} · ${t("automations.readsAndDrafts")}` : first;const status = automationStatus(automation, now);- const latest = automation.runs.find((run) => run.status !== "queued");+ const latest = latestRun(automation);const parts = [t(STATUS_WORD[status.state])];if (latest?.status === "running") parts.push(t("automations.runningNow"));else if (automation.checkedAt !== undefined && (!latest || automation.checkedAt >= (latest.finishedAt ?? runTime(latest)))) parts.push(t("automations.checkedNothingNew", { when: lastWhen(automation.checkedAt, now) }));diff --git a/src/lib/routine-display.ts b/src/lib/routine-display.tsindex b92f903ce4..7b93acdd17 100644--- a/src/lib/routine-display.ts+++ b/src/lib/routine-display.ts@@ -1,4 +1,4 @@-import type { Routine, RoutineRun } from "./routines";+import { isCountedSkip, type Routine, type RoutineRun } from "./routines";import { activeLocale, t } from "./i18n";import { routineLineText } from "./activity-text";import { clockOptions } from "./clock-time";@@ -7,8 +7,9 @@ export function routineRunTime(run: RoutineRun): number {return run.createdAt || run.startedAt || run.scheduledFor;}+/** The routine's newest run, leaving out a row that only counts skipped occurrences. */export function latestRoutineRun(routineId: string, runs: readonly RoutineRun[]): RoutineRun | undefined {- return runs.filter((run) => run.routineId === routineId)+ return runs.filter((run) => run.routineId === routineId && !isCountedSkip(run)).reduce<RoutineRun | undefined>((latest, run) => !latest || routineRunTime(run) > routineRunTime(latest) ? run : latest, undefined);}diff --git a/src/lib/routines.ts b/src/lib/routines.tsindex c3e2322a90..0c0c5a69f5 100644--- a/src/lib/routines.ts+++ b/src/lib/routines.ts@@ -12,4 +12,4 @@ export type {RoutineRun,RoutineInput,} from "../../shared/routines";-export { ROUTINE_HANDOFF_WAIT, ROUTINE_PROBLEM_STATUSES, isRoutineProblemRun, type RoutineRunStatusFilter } from "../../shared/routines";+export { ROUTINE_GOAL_RUN_LIMIT_MINUTES, ROUTINE_HANDOFF_WAIT, ROUTINE_PROBLEM_STATUSES, ROUTINE_RUN_LIMIT_MAX_MINUTES, ROUTINE_RUN_LIMIT_MINUTES, isCountedSkip, isRoutineProblemRun, type RoutineRunStatusFilter } from "../../shared/routines";diff --git a/src/locales/de.json b/src/locales/de.jsonindex ea4e52a668..fdd32fb3b8 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -3035,6 +3035,8 @@"server.routines.held.planCancelled": "Deine Routinen sind pausiert, weil der Tarif gekündigt wurde. Damit eine bis zum Ende des Tarifs weiterläuft, schalte sie unter Routines wieder ein.","server.routines.held.noEngine": "Deine Routinen sind pausiert: Keines deiner KI-Konten ist hier noch angemeldet. Sie schalten sich von selbst wieder ein, wenn du dich erneut anmeldest.","server.routines.held.noConnections": "Deine Routinen sind pausiert: Alle verbundenen Apps und MCP-Server wurden entfernt. Sie schalten sich wieder ein, wenn du eine App oder einen MCP-Server verbindest oder eine Routine unter Routines wieder einschaltest.",+ "server.routines.turnedBackOn": "Wieder eingeschaltet: {names}. Eine frühere Version hatte sie ausgeschaltet, nachdem ihr Cloud-Desktop nicht gestartet war.",+ "server.routines.turnedBackOnMany": "Wieder eingeschaltet: {names}. Eine frühere Version hatte sie ausgeschaltet, nachdem ihre Cloud-Desktops nicht gestartet waren.","voice.everyReply": "Sprachnachricht zu jeder Antwort","voice.everyReply.allHelp": "Jeder Bot schickt jede Antwort auch als Sprachnachricht. In den Einstellungen eines Bots kannst du das nur für ihn ein- oder ausschalten.","voice.everyReply.followsOn": "Folgt deiner Spracheinstellung (an)",diff --git a/src/locales/en.json b/src/locales/en.jsonindex af765bf9e1..9248d1da10 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -5361,6 +5361,8 @@"routines.overlapSkipHelp": "Skip scheduled occurrences while this routine is working. Manual runs are separate.","routines.overlapQueueHelp": "Keep one scheduled run waiting until this routine finishes. Skip further occurrences until it starts. Manual runs are separate.","routines.failureStreak": "Recent consecutive failures: {count}",+ "routines.noStartStreak": "Its cloud desktop did not start {count} runs in a row. This routine stays on and tries again less often until the cloud desktop starts.",+ "routines.unreadable": "Your saved routines could not be read, so none of them can run right now. Nothing was deleted: the file is kept as it is, and OpenMausBot keeps trying to read it.","routines.weekRuns": "{ok} of {total} runs OK this week","routines.skippedRuns": "Scheduled occurrences skipped while busy: {count}","routines.lastSkipped": "Last: {date}",@@ -8589,12 +8591,12 @@"routines.interval.invalidMinutes": "Choose a whole number from 5 to 1,440 minutes.","routines.interval.invalidDays": "Choose at least one day.","routines.interval.invalidWindow": "Choose a same-day window at least {minutes} minutes long.",- "routines.runLimit.none": "Advanced · no run limit",+ "routines.runLimit.none": "Advanced · stops after {duration} of work","routines.runLimit.some": "Advanced · {duration} run limit","routines.runLimit.stopAfter": "Stop if still running after","routines.runLimit.label": "Routine safety limit",- "routines.runLimit.noLimit": "No limit",- "routines.runLimit.help": "Optional. The clock starts when work actually begins and does not control how often the routine starts.",+ "routines.runLimit.noLimit": "Default ({duration} of work)",+ "routines.runLimit.help": "A run with no limit of its own stops after {duration} of work; the time it waits on you is not counted. A limit set here counts from when the run starts. It does not control how often the routine starts.","routines.editor.groupContext": "Use the group’s shared context","routines.attachment.add": "Add attachment","routines.attachment.routineHelp": "Attachments are passed to each local routine run and excluded from shared team files.",@@ -8640,7 +8642,7 @@"routines.drawer.attachments": "Attachments","routines.drawer.callSharedHelp": "These references will be shared in the group when the event starts.","routines.drawer.callKeptHelp": "These references stay with the event and are available when you join the group.",- "routines.drawer.noTimeLimit": "No time limit",+ "routines.drawer.noTimeLimit": "Default: stops after {duration} of work","routines.drawer.stopsAfter": "Stops if still running after {duration}","routines.drawer.pauseRoutine": "Pause routine","routines.drawer.resumeRoutine": "Resume routine",@@ -10067,6 +10069,16 @@"serverError.mcp.addressChanged": "The MCP server address changed. Reload the server and try again.","serverError.attachment.alreadyInMessage": "This file is already in a message, so it stays.","routines.server.backupSignedOut": "Starting again on the backup AI: this bot's AI is signed out",+ "routines.server.busyTooLong": "Did not run: the bot was busy for more than {minutes} minutes",+ "routines.server.overLimit": "Stopped: this run ran longer than the {hours}-hour limit",+ "routines.server.stopPending": "Its turn has not confirmed that it stopped. The next run waits for that, up to {minutes} minutes.",+ "routines.server.stopUnconfirmed": "Its turn never confirmed that it stopped, so the next run started without that.",+ "routines.server.skippedOne": "Skipped because {why}",+ "routines.server.skippedMany": "Skipped {count} scheduled runs because {why}",+ "routines.server.part.stillWaiting": "the previous run of this routine is still waiting",+ "routines.server.part.stillRunning": "the previous run of this routine is still running",+ "routines.server.part.notStarted": "the previous run of this routine has not started yet",+ "routines.server.part.computerNoStart": "its cloud desktop has not started, so its next tries are spaced out","approval.applied.waitFollowUp": "Then {name} will: {followUp}","chat.notice.waitDone.urlContains": "{label}: done. {url} now says “{text}”.","chat.notice.waitDone.urlMissing": "{label}: done. {url} no longer says “{text}”.",@@ -10170,6 +10182,8 @@"server.routines.held.planCancelled": "Your routines are paused because the plan was cancelled. To keep one running until the plan ends, turn it back on in Routines.","server.routines.held.noEngine": "Your routines are paused: none of your AI accounts is signed in here any more. They turn back on by themselves when you sign in again.","server.routines.held.noConnections": "Your routines are paused: every connected app and MCP server was removed. They turn back on when you connect one, or turn one back on in Routines.",+ "server.routines.turnedBackOn": "Turned back on: {names}. An earlier version switched it off after its cloud desktop failed to start.",+ "server.routines.turnedBackOnMany": "Turned back on: {names}. An earlier version switched them off after their cloud desktops failed to start.","mcp.request.change": "Change","mcp.request.remove": "Remove","secretCard.greenference.description": "Runs Greenference models with your own key.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex da216e5d0f..cb34cd06ae 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -5044,6 +5044,8 @@"routines.overlapSkipHelp": "Pula as ocorrências agendadas enquanto esta rotina está em andamento. Execuções manuais são separadas.","routines.overlapQueueHelp": "Mantém uma execução agendada na fila até esta rotina terminar. Pula as demais ocorrências até a execução na fila começar. Execuções manuais são separadas.","routines.failureStreak": "Falhas consecutivas recentes: {count}",+ "routines.noStartStreak": "O desktop na nuvem não iniciou em {count} execuções seguidas. Esta rotina continua ligada e tenta de novo com menos frequência até o desktop na nuvem iniciar.",+ "routines.unreadable": "Não foi possível ler suas rotinas salvas, então nenhuma delas pode rodar agora. Nada foi apagado: o arquivo foi mantido como está, e o OpenMausBot continua tentando ler.","routines.weekRuns": "{ok} de {total} execuções bem-sucedidas nesta semana","routines.skippedRuns": "Ocorrências agendadas puladas com a rotina em andamento: {count}","routines.lastSkipped": "Última: {date}",@@ -8535,12 +8537,12 @@"routines.interval.invalidMinutes": "Escolha um número inteiro de 5 a 1.440 minutos.","routines.interval.invalidDays": "Escolha pelo menos um dia.","routines.interval.invalidWindow": "Escolha um período de pelo menos {minutes} minutos, com início e fim no mesmo dia.",- "routines.runLimit.none": "Avançado · sem limite de execução",+ "routines.runLimit.none": "Avançado · para depois de {duration} de trabalho","routines.runLimit.some": "Avançado · limite de execução de {duration}","routines.runLimit.stopAfter": "Parar se ainda estiver rodando depois de","routines.runLimit.label": "Limite de segurança da rotina",- "routines.runLimit.noLimit": "Sem limite",- "routines.runLimit.help": "Opcional. O tempo só começa a contar quando o trabalho começa de fato. Esse limite não muda a frequência com que a rotina roda.",+ "routines.runLimit.noLimit": "Padrão ({duration} de trabalho)",+ "routines.runLimit.help": "Sem um limite próprio, a execução para depois de {duration} de trabalho. O tempo em que ela espera por você não conta. Um limite definido aqui conta desde o início da execução. Ele não muda a frequência com que a rotina roda.","routines.editor.groupContext": "Usar o contexto compartilhado do grupo","routines.attachment.add": "Adicionar anexo","routines.attachment.routineHelp": "Os anexos vão para cada execução local da rotina e ficam fora dos arquivos compartilhados da equipe.",@@ -8586,7 +8588,7 @@"routines.drawer.attachments": "Anexos","routines.drawer.callSharedHelp": "Estas referências serão compartilhadas no grupo quando o evento começar.","routines.drawer.callKeptHelp": "Estas referências ficam com o evento e estarão disponíveis quando você entrar no grupo.",- "routines.drawer.noTimeLimit": "Sem limite de tempo",+ "routines.drawer.noTimeLimit": "Padrão: para depois de {duration} de trabalho","routines.drawer.stopsAfter": "Para se ainda estiver rodando depois de {duration}","routines.drawer.pauseRoutine": "Pausar rotina","routines.drawer.resumeRoutine": "Retomar rotina",@@ -9998,6 +10000,16 @@"serverError.mcp.addressChanged": "O endereço do servidor MCP mudou. Recarregue o servidor e tente novamente.","serverError.attachment.alreadyInMessage": "Este arquivo já está em uma mensagem, então ele será mantido.","routines.server.backupSignedOut": "Começando novamente na IA reserva: a IA deste bot está sem login",+ "routines.server.busyTooLong": "Não rodou: o bot ficou ocupado por mais de {minutes} minutos",+ "routines.server.overLimit": "Interrompida: esta execução passou do limite de {hours} horas",+ "routines.server.stopPending": "O turno ainda não confirmou que parou. A próxima execução espera por isso, por até {minutes} minutos.",+ "routines.server.stopUnconfirmed": "O turno nunca confirmou que parou, então a próxima execução começou sem essa confirmação.",+ "routines.server.skippedOne": "Pulada porque {why}",+ "routines.server.skippedMany": "{count} execuções agendadas foram puladas porque {why}",+ "routines.server.part.stillWaiting": "a execução anterior desta rotina ainda está esperando",+ "routines.server.part.stillRunning": "a execução anterior desta rotina ainda está em andamento",+ "routines.server.part.notStarted": "a execução anterior desta rotina ainda não começou",+ "routines.server.part.computerNoStart": "o desktop na nuvem dela não iniciou, então as próximas tentativas ficam mais espaçadas","approval.applied.waitFollowUp": "Depois da espera, {name} fará o seguinte: {followUp}","chat.notice.waitDone.urlContains": "Espera concluída: {label}. {url} agora contém “{text}”.","chat.notice.waitDone.urlMissing": "Espera concluída: {label}. {url} não contém mais “{text}”.",@@ -10101,6 +10113,8 @@"server.routines.held.planCancelled": "Suas rotinas estão pausadas porque o plano foi cancelado. Para manter uma delas rodando até o fim do plano, ligue-a novamente em “Rotinas”.","server.routines.held.noEngine": "Suas rotinas estão pausadas: nenhuma das suas contas de IA continua conectada aqui. O app liga as rotinas automaticamente quando você entrar novamente.","server.routines.held.noConnections": "Suas rotinas estão pausadas: todos os apps conectados e servidores MCP foram removidos. O app liga as rotinas quando você conectar um deles. Você também pode ligar uma rotina novamente em “Rotinas”.",+ "server.routines.turnedBackOn": "Rotina ligada novamente: {names}. Uma versão anterior tinha desligado essa rotina depois que o desktop na nuvem dela não iniciou.",+ "server.routines.turnedBackOnMany": "Rotinas ligadas novamente: {names}. Uma versão anterior tinha desligado essas rotinas depois que o desktop na nuvem delas não iniciou.","mcp.request.change": "Alterar","mcp.request.remove": "Remover","secretCard.greenference.description": "Roda modelos do Greenference com sua própria chave.",diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.jsonindex 3230206f5d..3bb065348a 100644--- a/src/locales/source-hashes.json+++ b/src/locales/source-hashes.json@@ -3992,7 +3992,9 @@"server.botHeldDepartment": "ad3c5b51e8e3c5271f998a9ce283fe62a5fd23660096f757050a942168ab7361","devices.computers.pairButton": "60f8288e33f9f57d2b51409fdb540b47a89c25447061bd354122442818a36ee0","devices.computers.pairTitle": "b7cda6a11ab410daa4b8977624ca72261c0168e7c3d83ae0eed93ac4e3540bc8",- "devices.computers.typeCode": "2a528dfe78f6b331e8cca951872961169ca6f340a886e40e84cc0b53d441c174"+ "devices.computers.typeCode": "2a528dfe78f6b331e8cca951872961169ca6f340a886e40e84cc0b53d441c174",+ "server.routines.turnedBackOn": "e091ee76b804f84c0ac8a9b0f40adefd1661708a4b933be334c4a398f6917b6d",+ "server.routines.turnedBackOnMany": "b9b1f8055114f9a1b59fc53167a4d2d3be904e945cbe33f829142a8195a1ec4f"},"es": {"whop.description": "1a07cf04ef17029448d3781415cbac16d54e66b821907a40d94e0e6349710e70",@@ -33950,12 +33952,12 @@"routines.interval.invalidMinutes": "689a1a7c9b65dd9cca5d6911ef692b82b32576cf7cd96848f90e9c990d9895b3","routines.interval.invalidDays": "56f423871f48777cf33d510aa1ee13d6433293f5d7c17da631359122f908ac14","routines.interval.invalidWindow": "e5af673150b8e9c74594e1c8402d75222d12eafcea352481e3d9a2c700a6377d",- "routines.runLimit.none": "08d05ab72eab935758aac06f9417541c7df8bd404f2c443086113a43d0e4eaae",+ "routines.runLimit.none": "0a2edb591c2a1324cba74d62dfb2c02213989279988dfc2659f534da7a99e161","routines.runLimit.some": "25fc25ff6942341f8cfd3a693f0d62ad7681dcc32f11996725fa013c13fa6201","routines.runLimit.stopAfter": "164bf53b5b71eb008b48252a5114d5fb649fb8c4f446267da78af09778103f9a","routines.runLimit.label": "8600999a5aa21747cdf307932564466ad9eb5f6ce3676f068c3620ea87634b8c",- "routines.runLimit.noLimit": "f7fcff0d8feaf039c6bb00bd75849972a927b20ba79d26452d2776b493117b4b",- "routines.runLimit.help": "7df3faafb51d792460c13cc41387924ecbc4e6435e715b9176c671af5bd7e39b",+ "routines.runLimit.noLimit": "ae08c04c51d035c9bc78f6c5f327bc4a92d50feb7563fdd2c7237519660d3530",+ "routines.runLimit.help": "efb1f3b24baabadf837528b841563cd6cc22fea4f2ccd9c5c88deb338340f18e","routines.editor.groupContext": "3a2b5924d3c68fcbada029768e3730783a11cbb2351d56b57455fb612c365867","routines.attachment.add": "ebda695e767a518ecf7fdbbe5ffcb55d5b361d30088cc899aa346bc724d05ada","routines.attachment.routineHelp": "5ced08860f9a46a15641016f9e88c1ef6df899457cabd52f04e9d928ff02a591",@@ -34001,7 +34003,7 @@"routines.drawer.attachments": "634de114775082f002bb5cfdba0a28e768be807c798159c549e7bc930525b476","routines.drawer.callSharedHelp": "4a4555e38c0d530274e268eca8b23a2f5fe5ec62b60442d195b7f44533dd26b2","routines.drawer.callKeptHelp": "68998956a27cc0a0b8a558cff59937a0245286ffc957dbfd240bac5047a5d4f6",- "routines.drawer.noTimeLimit": "436b4b94e38ea005601ce4b25ee1d4e9088d356cf0f0c6496f33094956aaa61c",+ "routines.drawer.noTimeLimit": "c39b37e29a3473b18a58e3a6e412b9cefe894aa8eed74f5868dfbab0a3335af5","routines.drawer.stopsAfter": "2008477d12936926f2ca13daf6e3774d2f05456c508ed37aee43c384dc889b09","routines.drawer.pauseRoutine": "8026fe750281a71a99cf197f6edb08a954044a466dd881a8a27e99ca2e4c034f","routines.drawer.resumeRoutine": "773345cd2d70d50ad5548e8c8036ce9c9027e4808a915cdc749815c7a847ea48",@@ -36966,7 +36968,21 @@"remote.diagnosis.next.otherCopy": "29f59104ac96620533eecfef5e6bd7e612e84c6b2a6f71ebdb02550d4cd3518e","devices.computers.pairButton": "60f8288e33f9f57d2b51409fdb540b47a89c25447061bd354122442818a36ee0","devices.computers.pairTitle": "b7cda6a11ab410daa4b8977624ca72261c0168e7c3d83ae0eed93ac4e3540bc8",- "devices.computers.typeCode": "2a528dfe78f6b331e8cca951872961169ca6f340a886e40e84cc0b53d441c174"+ "devices.computers.typeCode": "2a528dfe78f6b331e8cca951872961169ca6f340a886e40e84cc0b53d441c174",+ "routines.noStartStreak": "fb107024c4705682465cf381239f9ecfc60e2e5dca2776c8082236b44ef38a9d",+ "routines.unreadable": "389a5c2a0eaa1366fc44c538daef1c28f2271aba90e806be13da78c14c1d3ced",+ "routines.server.busyTooLong": "4127f973deb204a8156c2c823319287c125b4e457d6ffe467c3597846b656d3b",+ "routines.server.overLimit": "8e1a3ad5aec3d7358cc462e8619c11670223b57fa7584688c6cde5daa57b98a5",+ "routines.server.stopPending": "ecef0da55ffc3ec91dea265385106d4dd5db12a75328772b3f571bab189cf1e6",+ "routines.server.stopUnconfirmed": "325194f89d84fa5bed6ad357614fd516eb53ca92bb0dbb3cb34683f397f45cfd",+ "routines.server.skippedOne": "810d0808a5d18387746ab48b22609928a22a23b24e61683a6134003256f2da67",+ "routines.server.skippedMany": "90adef9a8d06fb810a7de6a9f0c72047638bd816866717f0d37192b1caa76f64",+ "routines.server.part.stillWaiting": "bbe0bd65555f33dad78b594155eba6012ec8675d62911c0e1df75554de05d0c8",+ "routines.server.part.stillRunning": "cd6a3743e230f16c3d418e8dc5979a549b9c172ee0a959cb7d114723d0291db0",+ "routines.server.part.notStarted": "f9dca9af97df19cd027e3c0b452cc7ec520c886f489275601d05193d32df0207",+ "routines.server.part.computerNoStart": "1e1166d01f459bda1f8f5d5f47a750770f92da7874a0d56a5ac94edf7a3de7cd",+ "server.routines.turnedBackOn": "e091ee76b804f84c0ac8a9b0f40adefd1661708a4b933be334c4a398f6917b6d",+ "server.routines.turnedBackOnMany": "b9b1f8055114f9a1b59fc53167a4d2d3be904e945cbe33f829142a8195a1ec4f"},"zh": {"pro.fromPrice": "a48a04a457d60b08b54fc83e7a6c4584ffedb1e23621859084900c8521a3af7b",@@ -45527,12 +45543,12 @@"routines.interval.invalidMinutes": "689a1a7c9b65dd9cca5d6911ef692b82b32576cf7cd96848f90e9c990d9895b3","routines.interval.invalidDays": "56f423871f48777cf33d510aa1ee13d6433293f5d7c17da631359122f908ac14","routines.interval.invalidWindow": "e5af673150b8e9c74594e1c8402d75222d12eafcea352481e3d9a2c700a6377d",- "routines.runLimit.none": "08d05ab72eab935758aac06f9417541c7df8bd404f2c443086113a43d0e4eaae",+ "routines.runLimit.none": "0a2edb591c2a1324cba74d62dfb2c02213989279988dfc2659f534da7a99e161","routines.runLimit.some": "25fc25ff6942341f8cfd3a693f0d62ad7681dcc32f11996725fa013c13fa6201","routines.runLimit.stopAfter": "164bf53b5b71eb008b48252a5114d5fb649fb8c4f446267da78af09778103f9a","routines.runLimit.label": "8600999a5aa21747cdf307932564466ad9eb5f6ce3676f068c3620ea87634b8c",- "routines.runLimit.noLimit": "f7fcff0d8feaf039c6bb00bd75849972a927b20ba79d26452d2776b493117b4b",- "routines.runLimit.help": "7df3faafb51d792460c13cc41387924ecbc4e6435e715b9176c671af5bd7e39b",+ "routines.runLimit.noLimit": "ae08c04c51d035c9bc78f6c5f327bc4a92d50feb7563fdd2c7237519660d3530",+ "routines.runLimit.help": "efb1f3b24baabadf837528b841563cd6cc22fea4f2ccd9c5c88deb338340f18e","routines.editor.groupContext": "3a2b5924d3c68fcbada029768e3730783a11cbb2351d56b57455fb612c365867","routines.attachment.add": "ebda695e767a518ecf7fdbbe5ffcb55d5b361d30088cc899aa346bc724d05ada","routines.attachment.routineHelp": "5ced08860f9a46a15641016f9e88c1ef6df899457cabd52f04e9d928ff02a591",@@ -45578,7 +45594,7 @@"routines.drawer.attachments": "634de114775082f002bb5cfdba0a28e768be807c798159c549e7bc930525b476","routines.drawer.callSharedHelp": "4a4555e38c0d530274e268eca8b23a2f5fe5ec62b60442d195b7f44533dd26b2","routines.drawer.callKeptHelp": "68998956a27cc0a0b8a558cff59937a0245286ffc957dbfd240bac5047a5d4f6",- "routines.drawer.noTimeLimit": "436b4b94e38ea005601ce4b25ee1d4e9088d356cf0f0c6496f33094956aaa61c",+ "routines.drawer.noTimeLimit": "c39b37e29a3473b18a58e3a6e412b9cefe894aa8eed74f5868dfbab0a3335af5","routines.drawer.stopsAfter": "2008477d12936926f2ca13daf6e3774d2f05456c508ed37aee43c384dc889b09","routines.drawer.pauseRoutine": "8026fe750281a71a99cf197f6edb08a954044a466dd881a8a27e99ca2e4c034f","routines.drawer.resumeRoutine": "773345cd2d70d50ad5548e8c8036ce9c9027e4808a915cdc749815c7a847ea48",@@ -47167,7 +47183,21 @@"chat.notice.devinAccountRefused": "6f12d9c4c2912bc75bfbc26d0b43a2da3b02c1e4e16a807a9162670fcdab80fc","devices.computers.pairButton": "60f8288e33f9f57d2b51409fdb540b47a89c25447061bd354122442818a36ee0","devices.computers.pairTitle": "b7cda6a11ab410daa4b8977624ca72261c0168e7c3d83ae0eed93ac4e3540bc8",- "devices.computers.typeCode": "2a528dfe78f6b331e8cca951872961169ca6f340a886e40e84cc0b53d441c174"+ "devices.computers.typeCode": "2a528dfe78f6b331e8cca951872961169ca6f340a886e40e84cc0b53d441c174",+ "routines.noStartStreak": "fb107024c4705682465cf381239f9ecfc60e2e5dca2776c8082236b44ef38a9d",+ "routines.unreadable": "389a5c2a0eaa1366fc44c538daef1c28f2271aba90e806be13da78c14c1d3ced",+ "routines.server.busyTooLong": "4127f973deb204a8156c2c823319287c125b4e457d6ffe467c3597846b656d3b",+ "routines.server.overLimit": "8e1a3ad5aec3d7358cc462e8619c11670223b57fa7584688c6cde5daa57b98a5",+ "routines.server.stopPending": "ecef0da55ffc3ec91dea265385106d4dd5db12a75328772b3f571bab189cf1e6",+ "routines.server.stopUnconfirmed": "325194f89d84fa5bed6ad357614fd516eb53ca92bb0dbb3cb34683f397f45cfd",+ "routines.server.skippedOne": "810d0808a5d18387746ab48b22609928a22a23b24e61683a6134003256f2da67",+ "routines.server.skippedMany": "90adef9a8d06fb810a7de6a9f0c72047638bd816866717f0d37192b1caa76f64",+ "routines.server.part.stillWaiting": "bbe0bd65555f33dad78b594155eba6012ec8675d62911c0e1df75554de05d0c8",+ "routines.server.part.stillRunning": "cd6a3743e230f16c3d418e8dc5979a549b9c172ee0a959cb7d114723d0291db0",+ "routines.server.part.notStarted": "f9dca9af97df19cd027e3c0b452cc7ec520c886f489275601d05193d32df0207",+ "routines.server.part.computerNoStart": "1e1166d01f459bda1f8f5d5f47a750770f92da7874a0d56a5ac94edf7a3de7cd",+ "server.routines.turnedBackOn": "e091ee76b804f84c0ac8a9b0f40adefd1661708a4b933be334c4a398f6917b6d",+ "server.routines.turnedBackOnMany": "b9b1f8055114f9a1b59fc53167a4d2d3be904e945cbe33f829142a8195a1ec4f"},"zh-tw": {"whop.description": "1a07cf04ef17029448d3781415cbac16d54e66b821907a40d94e0e6349710e70",@@ -55176,12 +55206,9 @@"routines.interval.invalidMinutes": "689a1a7c9b65dd9cca5d6911ef692b82b32576cf7cd96848f90e9c990d9895b3","routines.interval.invalidDays": "56f423871f48777cf33d510aa1ee13d6433293f5d7c17da631359122f908ac14","routines.interval.invalidWindow": "e5af673150b8e9c74594e1c8402d75222d12eafcea352481e3d9a2c700a6377d",- "routines.runLimit.none": "08d05ab72eab935758aac06f9417541c7df8bd404f2c443086113a43d0e4eaae","routines.runLimit.some": "25fc25ff6942341f8cfd3a693f0d62ad7681dcc32f11996725fa013c13fa6201","routines.runLimit.stopAfter": "164bf53b5b71eb008b48252a5114d5fb649fb8c4f446267da78af09778103f9a","routines.runLimit.label": "8600999a5aa21747cdf307932564466ad9eb5f6ce3676f068c3620ea87634b8c",- "routines.runLimit.noLimit": "f7fcff0d8feaf039c6bb00bd75849972a927b20ba79d26452d2776b493117b4b",- "routines.runLimit.help": "7df3faafb51d792460c13cc41387924ecbc4e6435e715b9176c671af5bd7e39b","routines.editor.groupContext": "3a2b5924d3c68fcbada029768e3730783a11cbb2351d56b57455fb612c365867","routines.attachment.add": "ebda695e767a518ecf7fdbbe5ffcb55d5b361d30088cc899aa346bc724d05ada","routines.attachment.routineHelp": "5ced08860f9a46a15641016f9e88c1ef6df899457cabd52f04e9d928ff02a591",@@ -55227,7 +55254,6 @@"routines.drawer.attachments": "634de114775082f002bb5cfdba0a28e768be807c798159c549e7bc930525b476","routines.drawer.callSharedHelp": "4a4555e38c0d530274e268eca8b23a2f5fe5ec62b60442d195b7f44533dd26b2","routines.drawer.callKeptHelp": "68998956a27cc0a0b8a558cff59937a0245286ffc957dbfd240bac5047a5d4f6",- "routines.drawer.noTimeLimit": "436b4b94e38ea005601ce4b25ee1d4e9088d356cf0f0c6496f33094956aaa61c","routines.drawer.stopsAfter": "2008477d12936926f2ca13daf6e3774d2f05456c508ed37aee43c384dc889b09","routines.drawer.pauseRoutine": "8026fe750281a71a99cf197f6edb08a954044a466dd881a8a27e99ca2e4c034f","routines.drawer.resumeRoutine": "773345cd2d70d50ad5548e8c8036ce9c9027e4808a915cdc749815c7a847ea48",diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex e6fc38f881..2c3eed4510 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -8001,12 +8001,9 @@"routines.interval.invalidMinutes": "請選擇 5 到 1,440 之間的整數分鐘。","routines.interval.invalidDays": "請至少選擇一天。","routines.interval.invalidWindow": "請選擇同一天內至少 {minutes} 分鐘的時段。",- "routines.runLimit.none": "進階 · 沒有執行時間上限","routines.runLimit.some": "進階 · 執行時間上限 {duration}","routines.runLimit.stopAfter": "若超過以下時間仍在執行則停止","routines.runLimit.label": "例行工作安全上限",- "routines.runLimit.noLimit": "沒有上限",- "routines.runLimit.help": "選填。計時從實際開始工作時起算,不會影響例行工作的啟動頻率。","routines.editor.groupContext": "使用群組的共用背景資訊","routines.attachment.add": "新增附件","routines.attachment.routineHelp": "附件會傳給每次本機例行工作執行,並且不包含在共用的團隊檔案中。",@@ -8052,7 +8049,6 @@"routines.drawer.attachments": "附件","routines.drawer.callSharedHelp": "活動開始時,這些參考資料會分享到群組中。","routines.drawer.callKeptHelp": "這些參考資料會保留在活動中,你加入群組時即可使用。",- "routines.drawer.noTimeLimit": "沒有時間上限","routines.drawer.stopsAfter": "若超過 {duration} 仍在執行則停止","routines.drawer.pauseRoutine": "暫停例行工作","routines.drawer.resumeRoutine": "繼續例行工作",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex 02583b3f9e..45cb42433b 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -4993,6 +4993,8 @@"routines.overlapSkipHelp": "此例行任务运行期间,跳过已计划的运行。手动运行不受影响。","routines.overlapQueueHelp": "等此例行任务完成后,保留一次已计划的运行。开始后略过后续调度。手动运行不受影响。","routines.failureStreak": "最近连续失败次数:{count}",+ "routines.noStartStreak": "云端桌面已连续 {count} 次运行未能启动。这个例行任务保持开启,在云端桌面能启动之前会降低重试频率。",+ "routines.unreadable": "无法读取已保存的例行任务,所以它们现在都无法运行。没有删除任何内容:文件保持原样,OpenMausBot 会继续尝试读取。","routines.weekRuns": "本周 {total} 次执行中 {ok} 次成功","routines.skippedRuns": "忙碌期间略过的调度次数:{count}","routines.lastSkipped": "上次:{date}",@@ -7734,6 +7736,16 @@"serverError.mcp.addressChanged": "MCP 服务地址有变化。请重新加载该服务后重试。","serverError.attachment.alreadyInMessage": "这个文件已经在消息里了,所以会保留。","routines.server.backupSignedOut": "正在改用备用 AI 重新开始:这个机器人的 AI 已退出登录",+ "routines.server.busyTooLong": "没有运行:机器人忙碌超过了 {minutes} 分钟",+ "routines.server.overLimit": "已停止:这次运行超过了 {hours} 小时的上限",+ "routines.server.stopPending": "它的回合还没有确认已停止。下一次运行会等待确认,最多 {minutes} 分钟。",+ "routines.server.stopUnconfirmed": "它的回合始终没有确认已停止,所以下一次运行没有等到确认就开始了。",+ "routines.server.skippedOne": "已跳过,因为{why}",+ "routines.server.skippedMany": "已跳过 {count} 次调度运行,因为{why}",+ "routines.server.part.stillWaiting": "这个例行任务的上一次运行仍在等待",+ "routines.server.part.stillRunning": "这个例行任务的上一次运行仍在进行",+ "routines.server.part.notStarted": "这个例行任务的上一次运行还没有开始",+ "routines.server.part.computerNoStart": "它的云端桌面未能启动,所以之后的尝试会隔得更久","approval.applied.waitFollowUp": "然后 {name} 会:{followUp}","chat.notice.waitDone.urlContains": "{label}:完成。{url} 现在显示“{text}”。","chat.notice.waitDone.urlMissing": "{label}:完成。{url} 不再显示“{text}”。",@@ -7833,6 +7845,8 @@"server.routines.held.planCancelled": "你的例行任务已暂停,因为方案被取消了。如果想让某个任务持续运行到方案结束,请在“例行任务”中重新打开它。","server.routines.held.noEngine": "你的例行任务已暂停:你所有的 AI 账号都已退出这里的登录。重新登录后它们会自动恢复。","server.routines.held.noConnections": "你的例行任务已暂停:所有已连接的应用和 MCP 服务都被移除了。连接一个之后它们会恢复,你也可以在“例行任务”中重新打开一个。",+ "server.routines.turnedBackOn": "已重新开启:{names}。之前的版本在它的云端桌面未能启动后把它关闭了。",+ "server.routines.turnedBackOnMany": "已重新开启:{names}。之前的版本在它们的云端桌面未能启动后把它们关闭了。","mcp.request.change": "更改","mcp.request.remove": "移除","secretCard.greenference.description": "用你自己的密钥运行 Greenference 模型。",@@ -9796,12 +9810,12 @@"routines.interval.invalidMinutes": "请选择 5 到 1,440 之间的整数分钟。","routines.interval.invalidDays": "请至少选择一天。","routines.interval.invalidWindow": "请选择同一天内至少 {minutes} 分钟的时段。",- "routines.runLimit.none": "高级 · 不限运行时长",+ "routines.runLimit.none": "高级 · 工作 {duration}后停止","routines.runLimit.some": "高级 · 运行上限 {duration}","routines.runLimit.stopAfter": "如果仍在运行,则在此之后停止","routines.runLimit.label": "例行任务安全上限",- "routines.runLimit.noLimit": "不限",- "routines.runLimit.help": "可选。计时从工作真正开始时开始,不影响例行任务的启动频率。",+ "routines.runLimit.noLimit": "默认(工作 {duration})",+ "routines.runLimit.help": "未设置上限时,运行在工作 {duration}后停止;等待你的时间不计入。在这里设置的上限从运行开始时计时,不影响例行任务的启动频率。","routines.editor.groupContext": "使用群组的共享上下文","routines.attachment.add": "添加附件","routines.attachment.routineHelp": "附件会传给每次本地例行任务运行,并且不会进入团队共享文件。",@@ -9847,7 +9861,7 @@"routines.drawer.attachments": "附件","routines.drawer.callSharedHelp": "活动开始时,这些引用会在群组里共享。","routines.drawer.callKeptHelp": "这些引用会随活动保留,你加入群组时可用。",- "routines.drawer.noTimeLimit": "不限时长",+ "routines.drawer.noTimeLimit": "默认:工作 {duration}后停止","routines.drawer.stopsAfter": "如果仍在运行,则在 {duration} 后停止","routines.drawer.pauseRoutine": "暂停例行任务","routines.drawer.resumeRoutine": "继续例行任务",diff --git a/src/state/config-status.ts b/src/state/config-status.tsindex fd4dcea86b..579027f84a 100644--- a/src/state/config-status.ts+++ b/src/state/config-status.ts@@ -76,6 +76,8 @@ export interface ConfigStatus {pausedByPerson?: { bots: string[]; departments: string[] };/** Every bot taking no new work because the person paused it or its department. */heldBots?: string[];+ /** The server cannot read its saved routines, so none runs until it can. */+ routinesUnreadable?: true;threads?: { maxConcurrentPerBot: number; eventLogMaxBytes?: number; eventLogRetentionDays?: number };automaticRecovery?: { enabled: boolean; backup?: ModelSelection };/** Prompt-cache keep-warm for idle Claude threads. Absent from older servers. */