The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Scheduled tasks: a task can run a saved skill on its schedule, with each file input fixed or the newest upload
Claudebfa7f3bf544e
diff --git a/src/lib/assist-schedule.ts b/src/lib/assist-schedule.tsindex 313603e7..e2c20a2c 100644--- a/src/lib/assist-schedule.ts+++ b/src/lib/assist-schedule.ts@@ -21,6 +21,16 @@ export type ScheduleRule =/** Ask first: the plan waits in the chat as an approval card. Auto: plans run up to `capUsd` per run. */export type ScheduleApproval = "ask" | "auto";+/**+ * A task that runs a saved skill (package W4): no model plans it. `values` are one set of the recipe's inputs as text+ * (a file is its /api/files/… URL); an input in `sources` takes the newest upload of its kind when the run starts.+ */+export interface ScheduleSkill {+ name: string;+ values: Record<string, string>;+ sources?: Record<string, "newest">;+}+export const SCHEDULE_HOURS = [1, 2, 3, 4, 6, 8, 12, 24, 48, 72, 168] as const;export const MAX_SCHEDULE_HOURS = 168;export const MAX_SCHEDULE_PROMPT = 4000;@@ -44,6 +54,8 @@ export interface ScheduleView {mode: { mode: "free" | "smart" | "manual"; agent?: "claude" | "hosted" | "local" | "ollama" | "offline"; provider?: string | null; model?: string | null; effort?: "low" | "medium" | "high" | "xhigh" | "max" | null } | null;/** Whether runs may use the connectors in Settings (Claude runs only). Their tools run without asking, so it's off unless the task opts in. */connectors: boolean;+ /** A task that runs a skill instead of a request (null: a request Assist plans). */+ skill: ScheduleSkill | null;paused: boolean;/** When it runs next (null: paused, or a one-off that has run). */nextRunAt: number | null;@@ -259,6 +271,31 @@ export function zoneLabel(tz: string, at = Date.now()): string {}}+// ---------------------------------------------------------------------------+// A skill on a schedule++const KIND_WORDS = { image: "image", video: "video", audio: "audio file" } as const;++/** "your newest image upload": what a "newest upload" input reads when the run starts. */+export const newestWords = (type: "image" | "video" | "audio"): string => `your newest ${KIND_WORDS[type]} upload`;++/**+ * "/weekly-promo Product photo: your newest image upload · Product name: Lumen lamp": a skill task in one line (its+ * stored prompt). A run's first message passes `files`, which names each file it attaches ("file 1"), the newest+ * upload it read included.+ */+export function skillTaskLine(skill: ScheduleSkill, params: { id: string; label: string; type: string }[], files?: (url: string) => string): string {+ const parts = params.flatMap((p) => {+ const v = skill.values[p.id];+ const file = p.type === "image" || p.type === "video" || p.type === "audio";+ if (skill.sources?.[p.id] === "newest" && file) return [`${p.label}: ${newestWords(p.type)}${files && v ? ` (${files(v)})` : ""}`];+ if (v === undefined || v === "") return [];+ if (file && /^(\/api\/files\/|https?:\/\/)/i.test(v)) return [`${p.label}: ${files ? files(v) : "a file you picked"}`];+ return [`${p.label}: ${v.length > 80 ? `${v.slice(0, 79).trimEnd()}…` : v}`];+ });+ return parts.length ? `/${skill.name} ${parts.join(" · ")}` : `/${skill.name}`;+}+// ---------------------------------------------------------------------------// Spending: what a scheduled run may start on its owndiff --git a/src/server/assist/schedules.ts b/src/server/assist/schedules.tsindex 987a02ed..bb1c9899 100644--- a/src/server/assist/schedules.ts+++ b/src/server/assist/schedules.ts@@ -1,21 +1,31 @@import "server-only";+import type Anthropic from "@anthropic-ai/sdk";import { nanoid } from "nanoid";import { normalizeAgent, threadTitle, type AssistItem, type AssistModeChoice } from "@/lib/assist";import {DEFAULT_SCHEDULE_CAP_USD,describeRule,formatWhen,+ newestWords,nextRun,ruleError,+ skillTaskLine,validTimeZone,type ScheduleApproval,type ScheduleResult,type ScheduleRule,+ type ScheduleSkill,type ScheduleView,} from "@/lib/assist-schedule";+import type { Engine } from "@/lib/catalog/types";import { formatCost } from "@/lib/format";+import { checkValues, isMediaType } from "@/lib/recipe";import { db } from "../db";+import { recipeEngines } from "../recipes";+import { getSkill, skillRecipe } from "../skills";+import { listAssets } from "../storage";import { addMessage, createThread, getThread, resolveMode, run, type ModelCall } from "./agent";+import { canUseSkill } from "./context";import { getProject } from "./projects";/**@@ -29,6 +39,10 @@ import { getProject } from "./projects";* Custom MCP connectors are off in runs unless the task opts in (`connectors`): their tools run inside* Claude's reply, where neither mode can hold them back.* A run the server missed (it was off) happens once when it's back, not once per missed time.+ *+ * A task can run a saved skill instead (Skills W4, `skill`): each run is still a chat, with the same approval and cap,+ * but no model plans it — a fixed reply (skillCall) makes one run_skill call with the task's values, and a file input+ * set to "newest upload" reads the newest upload of its kind when the run starts.*/export class ScheduleError extends Error {@@ -59,6 +73,7 @@ interface Row {connectors: number;engine: "cloud" | "open";mode_json: string | null;+ skill_json: string | null;paused: number;next_run_at: number | null;last_run_at: number | null;@@ -86,6 +101,8 @@ export interface ScheduleInput {mode?: AssistModeChoice | null;/** Whether runs may use the connectors in Settings (off unless set). */connectors?: boolean;+ /** Run this skill instead of a request (null: a request). */+ skill?: ScheduleSkill | null;paused?: boolean;}@@ -149,6 +166,7 @@ function toView(r: Row): ScheduleView {engine: r.engine,mode: r.mode_json ? modeOf(r.mode_json) : null,connectors: !!r.connectors,+ skill: r.skill_json ? (JSON.parse(r.skill_json) as ScheduleSkill) : null,paused: !!r.paused,nextRunAt: r.paused ? null : r.next_run_at,lastRunAt: r.last_run_at,@@ -173,9 +191,52 @@ export function getSchedule(id: string): ScheduleView | null {return r ? toView(r) : null;}+const ENGINE_WORDS: Record<Engine, string> = { cloud: "the cloud", open: "your GPU" };+/** What a "newest upload" input is checked with when the task is saved (the real file is read when it runs). */+const NEWEST_STAND_IN = "/api/files/uploads/newest";++/** One line of what's wrong: "needs product (image)", or the first value that doesn't fit. */+const firstError = (errors: Record<string, string>) => Object.values(errors)[0] ?? "Check the skill's inputs";++/**+ * A skill task as it's saved: a skill here that runs by itself, is on, may run in the task's project and on its engine,+ * with values that fit its inputs (a "newest upload" input is checked with a stand-in file). Returns what's stored.+ */+function checkedSkill(task: ScheduleSkill, projectId: string | null, engine: Engine): { task: ScheduleSkill; title: string; line: string } {+ const name = task.name.replace(/^\//, "").trim();+ const s = getSkill(name);+ if (!s) throw new ScheduleError(`There's no skill called /${name}`, 404);+ const recipe = s.recipe ? skillRecipe(name) : null;+ if (!recipe) throw new ScheduleError(`/${name} doesn't run by itself: pick a skill that does, or schedule a request`);+ if (!s.enabled) throw new ScheduleError(`/${name} is switched off — switch it on in Skills first`);+ if (!canUseSkill(name, projectId)) throw new ScheduleError(`/${name} isn't one of this project's skills: add it to the project, or pick no project`);+ const engines = recipeEngines(recipe);+ if (!engines.includes(engine)) {+ throw new ScheduleError(engines.length ? `/${name} runs on ${engines.map((e) => ENGINE_WORDS[e]).join(" or ")} only: pick that engine` : `/${name} can't run on this install as it is`);+ }+ const params = new Map(recipe.params.map((p) => [p.id, p]));+ const unknown = [...Object.keys(task.values), ...Object.keys(task.sources ?? {})].find((k) => !params.has(k));+ if (unknown) throw new ScheduleError(`/${name} has no input “${unknown}”`);+ const sources = Object.keys(task.sources ?? {});+ const notFile = sources.find((id) => !isMediaType(params.get(id)!.type));+ if (notFile) throw new ScheduleError(`${params.get(notFile)!.label} isn't a file: only a file input can take your newest upload`);+ const values = Object.fromEntries(Object.entries(task.values).filter(([id, v]) => !sources.includes(id) && v.trim() !== ""));+ const check = checkValues(recipe, { ...values, ...Object.fromEntries(sources.map((id) => [id, NEWEST_STAND_IN])) });+ if (!check.values) throw new ScheduleError(firstError(check.errors));+ const clean: ScheduleSkill = { name, values, ...(sources.length && { sources: Object.fromEntries(sources.map((id) => [id, "newest" as const])) }) };+ return { task: clean, title: s.title, line: skillTaskLine(clean, recipe.params) };+}+function checked(input: ScheduleInput, prev: Row | undefined, now: number): Omit<Row, "id" | "last_run_at" | "last_thread_id" | "last_status" | "last_text" | "runs" | "created_at"> {if (!validTimeZone(input.tz)) throw new ScheduleError("Pick a time zone");if (input.projectId && !getProject(input.projectId)) throw new ScheduleError("That project doesn't exist anymore", 404);+ const paused = input.paused ?? !!prev?.paused;+ // A skill task is checked when it's saved, changed or resumed; an edit that leaves it alone (a pause, a new name)+ // keeps it, so a task whose skill went away can still be paused, renamed or deleted.+ const sameSkill =+ !!prev?.skill_json && !!input.skill && JSON.stringify(input.skill) === prev.skill_json && prev.project_id === (input.projectId ?? null) && prev.engine === input.engine && (paused || !prev.paused);+ const skill = input.skill ? (sameSkill ? { task: input.skill, title: prev!.title, line: prev!.prompt } : checkedSkill(input.skill, input.projectId ?? null, input.engine)) : null;+ if (!skill && !input.prompt.trim()) throw new ScheduleError("Write what Assist should do each time");const before = prev ? (JSON.parse(prev.rule_json) as ScheduleRule) : null;// "Every N hours" counts from when it was set up; an unchanged one keeps counting from then.const rule: ScheduleRule =@@ -184,7 +245,6 @@ function checked(input: ScheduleInput, prev: Row | undefined, now: number): Omit: (input.rule as ScheduleRule);const bad = ruleError(rule);if (bad) throw new ScheduleError(bad);- const paused = input.paused ?? !!prev?.paused;const ruleJson = JSON.stringify(rule);// An edit that leaves when it runs alone (a rename, a new prompt) keeps the next time, even one that// is due and not yet swept; a new rule or zone, or resuming, picks it from now.@@ -193,17 +253,20 @@ function checked(input: ScheduleInput, prev: Row | undefined, now: number): Omitif (next === null && !paused) throw new ScheduleError(rule.kind === "once" ? "That time has passed — pick a later one" : "This schedule never runs");const cap = input.approval === "auto" ? (input.capUsd ?? DEFAULT_SCHEDULE_CAP_USD) : null;return {- title: input.title.trim().slice(0, 80) || threadTitle(input.prompt),- prompt: input.prompt.trim(),- attachments_json: JSON.stringify(input.attachments ?? []),+ title: input.title.trim().slice(0, 80) || (skill ? skill.title.slice(0, 80) : threadTitle(input.prompt)),+ // A skill task's prompt is what it runs, in words (the Scheduled page shows it).+ prompt: skill ? skill.line : input.prompt.trim(),+ attachments_json: JSON.stringify(skill ? [] : (input.attachments ?? [])),project_id: input.projectId ?? null,rule_json: ruleJson,tz: input.tz,approval: input.approval,cap_usd: cap === null ? null : Math.round(cap * 100) / 100,- connectors: (input.connectors ?? !!prev?.connectors) ? 1 : 0,+ // No model plans a skill task's runs: no mode, and no connectors (they're Claude's).+ connectors: !skill && (input.connectors ?? !!prev?.connectors) ? 1 : 0,engine: input.engine,- mode_json: input.mode ? JSON.stringify(input.mode) : null,+ mode_json: !skill && input.mode ? JSON.stringify(input.mode) : null,+ skill_json: skill ? JSON.stringify(skill.task) : null,paused: paused ? 1 : 0,next_run_at: next,updated_at: now,@@ -214,9 +277,9 @@ export function createSchedule(input: ScheduleInput, now = Date.now()): Scheduleconst row: Row = { id: nanoid(10), ...checked(input, undefined, now), last_run_at: null, last_thread_id: null, last_status: null, last_text: null, runs: 0, created_at: now };db().prepare(- `INSERT INTO assist_schedules (id, title, prompt, attachments_json, project_id, rule_json, tz, approval, cap_usd, connectors, engine, mode_json, paused,+ `INSERT INTO assist_schedules (id, title, prompt, attachments_json, project_id, rule_json, tz, approval, cap_usd, connectors, engine, mode_json, skill_json, paused,next_run_at, last_run_at, last_thread_id, last_status, last_text, runs, created_at, updated_at)- VALUES (@id, @title, @prompt, @attachments_json, @project_id, @rule_json, @tz, @approval, @cap_usd, @connectors, @engine, @mode_json, @paused,+ VALUES (@id, @title, @prompt, @attachments_json, @project_id, @rule_json, @tz, @approval, @cap_usd, @connectors, @engine, @mode_json, @skill_json, @paused,@next_run_at, @last_run_at, @last_thread_id, @last_status, @last_text, @runs, @created_at, @updated_at)`,).run(row);@@ -241,13 +304,14 @@ export function updateSchedule(id: string, patch: Partial<ScheduleInput>, now =engine: patch.engine ?? current.engine,mode: patch.mode !== undefined ? patch.mode : (current.mode as AssistModeChoice | null),connectors: patch.connectors ?? current.connectors,+ skill: patch.skill !== undefined ? patch.skill : current.skill,paused: patch.paused ?? current.paused,};const next = { ...r, ...checked(merged, r, now) };db().prepare(`UPDATE assist_schedules SET title = @title, prompt = @prompt, attachments_json = @attachments_json, project_id = @project_id, rule_json = @rule_json,- tz = @tz, approval = @approval, cap_usd = @cap_usd, connectors = @connectors, engine = @engine, mode_json = @mode_json, paused = @paused,+ tz = @tz, approval = @approval, cap_usd = @cap_usd, connectors = @connectors, engine = @engine, mode_json = @mode_json, skill_json = @skill_json, paused = @paused,next_run_at = @next_run_at, updated_at = @updated_at WHERE id = @id`,).run(next);@@ -276,6 +340,62 @@ function runningChat(id: string): string | null {return rows.find((r) => getThread(r.id)?.thread.status === "running")?.id ?? null;}+type MessageReply = Anthropic.Beta.BetaMessage;++/**+ * A skill task's "model": no LLM. Its first turn makes one run_skill call with the task's values (on an approval card+ * when the task asks first, or within its cap); once the call has an answer it says the run started, and a call that+ * couldn't start ends the run with the reason (the task then shows it as failed).+ */+export function skillCall(skill: { name: string; title: string }, values: Record<string, string>, engine: Engine): ModelCall {+ const reply = (content: unknown[], stop: Anthropic.Beta.BetaStopReason): MessageReply =>+ ({ id: `msg_sched_${nanoid(8)}`, type: "message", role: "assistant", model: "skill", content, stop_reason: stop, stop_sequence: null, stop_details: null, usage: null }) as unknown as MessageReply;+ const text = (t: string) => ({ type: "text", text: t, citations: null });+ return async ({ messages }) => {+ const last = messages.findLast((m) => m.role !== "system");+ const blocks = last && last.role === "user" && typeof last.content !== "string" ? last.content : [];+ const result = blocks.find((b) => b.type === "tool_result");+ if (!result) {+ const use = { type: "tool_use", id: `toolu_sched_${nanoid(10)}`, name: "run_skill", input: { name: skill.name, values, engine }, caller: { type: "direct" } };+ return reply([text(`Running ${skill.title} with this task's inputs.`), use], "tool_use");+ }+ const body = typeof result.content === "string" ? result.content : (result.content ?? []).map((c) => (c.type === "text" ? c.text : "")).join(" ");+ if (result.is_error) {+ let why = body;+ try {+ why = (JSON.parse(body) as { error?: string }).error ?? body;+ } catch {+ // Plain words already.+ }+ throw new Error(`${skill.title} didn't start: ${why || "no reason given"}`);+ }+ return reply([text(`Started ${skill.title}. The results appear here and in your Library as they finish.`)], "end_turn");+ };+}++/** A skill task's run, ready to start: its values with each "newest upload" read now, the files to attach and its first message. */+type SkillRun = { name: string; title: string; values: Record<string, string>; files: string[]; line: string } | { stop: "paused" | "failed"; message: string };++function prepareSkillRun(task: ScheduleSkill, projectId: string | null): SkillRun {+ const s = getSkill(task.name);+ if (!s) return { stop: "paused", message: "Its skill was deleted — edit the task to pick another" };+ const recipe = s.recipe ? skillRecipe(task.name) : null;+ if (!recipe) return { stop: "paused", message: "Its skill no longer runs by itself — edit the task to pick another" };+ if (!s.enabled) return { stop: "failed", message: `/${task.name} is switched off — switch it on in Skills, then run the task again` };+ if (!canUseSkill(task.name, projectId)) return { stop: "failed", message: `/${task.name} isn't one of its project's skills any more — add it back, or edit the task` };+ const values = { ...task.values };+ for (const p of recipe.params) {+ if (task.sources?.[p.id] !== "newest" || !isMediaType(p.type)) continue;+ // The owner's newest upload of that kind, as the Library's Uploads list shows it.+ const newest = listAssets({ source: "upload", kind: p.type, limit: 1 })[0];+ if (!newest) return { stop: "failed", message: `There's no ${newestWords(p.type).replace(/^your newest /, "")} yet for “${p.label}” — upload one, or edit the task to pick a file` };+ values[p.id] = newest.url;+ }+ const files = [...new Set(recipe.params.flatMap((p) => (isMediaType(p.type) && values[p.id]?.startsWith("/api/files/") ? [values[p.id]] : [])))].slice(0, 8);+ const line = skillTaskLine({ ...task, values }, recipe.params, (url) => (files.includes(url) ? `file ${files.indexOf(url) + 1}` : url));+ return { name: task.name, title: s.title, values, files, line };+}+/*** What starting a run came to: a new chat (`threadId`, with `done` settling when the agent stops),* or none and why — `busy` (the run before is still going), `paused` (its project is gone) or@@ -305,14 +425,23 @@ export async function startSchedule(id: string, o: { now?: number; model?: Modelrecord(id, { last_run_at: now, last_thread_id: null, last_status: "failed", last_text: message, paused: 1 });return none("paused", message);}+ // A skill task: its skill must still run here, and each "newest upload" input is read now.+ const task = r.skill_json ? (JSON.parse(r.skill_json) as ScheduleSkill) : null;+ const skill = task ? prepareSkillRun(task, r.project_id) : null;+ if (skill && "stop" in skill) {+ if (skill.stop === "paused") record(id, { last_run_at: now, last_thread_id: null, last_status: "failed", last_text: skill.message, paused: 1 });+ else record(id, { last_run_at: now, last_thread_id: null, last_status: "failed", last_text: skill.message, addRun: true });+ return none(skill.stop, skill.message);+ }const rule = JSON.parse(r.rule_json) as ScheduleRule;const mode = r.mode_json ? (JSON.parse(r.mode_json) as AssistModeChoice) : undefined;const cap = r.approval === "auto" ? (r.cap_usd ?? DEFAULT_SCHEDULE_CAP_USD) : null;const how = cap === null ? "plans wait for your approval" : cap === 0 ? "only free plans run on their own" : `plans up to ${formatCost(cap)} run on their own`;let threadId: string;try {- const m = await resolveMode(mode);- const uses = !!r.connectors && m.agent === "claude";+ // A skill task's chat is on the offline planner: no model plans it, and an approval later resumes it without one.+ const m = await resolveMode(skill ? { mode: "manual", agent: "offline" } : mode);+ const uses = !skill && !!r.connectors && m.agent === "claude";const t = createThread({engine: r.engine,agent: m.agent,@@ -325,18 +454,21 @@ export async function startSchedule(id: string, o: { now?: number; model?: Modeleffort: m.effort,scheduleId: r.id,capUsd: cap,- connectors: !!r.connectors,- note: `Scheduled run of “${r.title}” · ${describeRule(rule)} · ${how}${uses ? " · connectors on (their tools run without asking)" : ""}.${m.note ? ` ${m.note}` : ""}`,+ connectors: !skill && !!r.connectors,+ note: skill+ ? `Scheduled run of “${r.title}” · ${describeRule(rule)} · ${how} · runs the ${skill.title} skill as it was saved, with no AI model planning it.`+ : `Scheduled run of “${r.title}” · ${describeRule(rule)} · ${how}${uses ? " · connectors on (their tools run without asking)" : ""}.${m.note ? ` ${m.note}` : ""}`,});threadId = t.id;- addMessage(t.id, r.prompt, JSON.parse(r.attachments_json) as string[]);+ if (skill) addMessage(t.id, skill.line, skill.files);+ else addMessage(t.id, r.prompt, JSON.parse(r.attachments_json) as string[]);} catch (e) {const message = (e as Error).message || "The run couldn't start";record(id, { last_run_at: now, last_thread_id: null, last_status: "failed", last_text: message, addRun: true });return none("failed", message);}record(id, { last_run_at: now, last_thread_id: threadId, last_status: "running", last_text: "Working…", addRun: true });- const done = run(threadId, o.model)+ const done = run(threadId, skill ? skillCall(skill, skill.values, r.engine) : o.model).catch((e: Error) => console.warn(`[fuobe] scheduled task ${id} failed: ${e.message}`)).finally(() => {// Only while this run is still the task's last (a pause since then keeps its reason).diff --git a/src/server/assist/schemas.ts b/src/server/assist/schemas.tsindex 6d93b085..22d79c12 100644--- a/src/server/assist/schemas.ts+++ b/src/server/assist/schemas.ts@@ -49,10 +49,17 @@ export const ScheduleRuleSchema = z.discriminatedUnion("kind", [z.object({ kind: z.literal("once"), at: z.string().regex(/^\d{4}-\d{2}-\d{2}T([01]\d|2[0-3]):[0-5]\d$/, "Pick a date and time") }),]);-/** A scheduled task as the dialog sends it (create: everything; edit: any part). */+/** A skill a task runs (W4): its name, one set of values as text, and the media inputs that take the newest upload. */+export const ScheduleSkillSchema = z.object({+ name: z.string().trim().min(1).max(64),+ values: z.record(z.string().max(64), z.string().max(4000)).refine((v) => Object.keys(v).length <= 24, "Too many inputs"),+ sources: z.record(z.string().max(64), z.literal("newest")).optional(),+});++/** A scheduled task as the dialog sends it (create: everything; edit: any part). A task that runs a skill needs no prompt. */export const ScheduleBody = z.object({title: z.string().trim().min(1).max(80),- prompt: z.string().trim().min(1).max(MAX_SCHEDULE_PROMPT),+ prompt: z.string().trim().max(MAX_SCHEDULE_PROMPT),attachments: z.array(z.string().startsWith("/api/files/")).max(8).optional(),projectId: z.string().max(40).nullish(),rule: ScheduleRuleSchema,@@ -63,6 +70,8 @@ export const ScheduleBody = z.object({mode: ModeChoice.nullish(),/** Whether runs may use the connectors in Settings (Claude only; their tools run without asking). */connectors: z.boolean().optional(),+ /** Run a saved skill instead of a request (null: back to a request). */+ skill: ScheduleSkillSchema.nullish(),paused: z.boolean().optional(),});diff --git a/src/server/db.ts b/src/server/db.tsindex 41614237..54344c08 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -605,6 +605,10 @@ export const MIGRATIONS: string[] = [CREATE INDEX IF NOT EXISTS assets_account ON assets(account_id, created_at DESC);CREATE INDEX IF NOT EXISTS assets_rel ON assets(rel_path);CREATE INDEX IF NOT EXISTS assets_generation ON assets(generation_id);`,+ // originals (o/w2s-w4): a scheduled task can run a saved skill (Skills W4) instead of a request Assist plans: the+ // skill's name, one set of its inputs as text (a file is its /api/files/… URL) and the file inputs that take the+ // newest upload of their kind when the run starts. NULL: a request, as before.+ `ALTER TABLE assist_schedules ADD COLUMN skill_json TEXT;`,];/**diff --git a/src/server/generations.ts b/src/server/generations.tsindex f8c0ffc4..f5f97bc7 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -405,8 +405,8 @@ export const ASSET_REFS: AssetRef[] = [{ table: "katana_jobs", cols: ["data_json"], what: "Katana job", name: "json_extract(data_json, '$.title')" },// Content Factory: a series' reference clip and its thumbnail.{ table: "content_series", cols: ["data_json"], what: "Content Factory series", name: "COALESCE(json_extract(data_json, '$.name'), json_extract(data_json, '$.reference.title'))" },- // Assist's scheduled tasks: the files the prompt runs with.- { table: "assist_schedules", cols: ["attachments_json"], what: "scheduled task", name: "title" },+ // Assist's scheduled tasks: the files the prompt runs with, and the files a skill task's inputs name.+ { table: "assist_schedules", cols: ["attachments_json", "skill_json"], what: "scheduled task", name: "title" },// Character Swap Studio: the character picture, each clip and its 24 fps copy, masks, anchors, takes and their masters.{ table: "swap_projects", cols: ["data_json"], what: "Character Swap project", name: "name" },// A user skill's bundled text files: its recipe.json names the files a run starts from (an example, a fixed logo).diff --git a/src/server/skills.ts b/src/server/skills.tsindex 78f36a51..c97d094f 100644--- a/src/server/skills.ts+++ b/src/server/skills.ts@@ -299,9 +299,25 @@ export function updateSkill(name: string, patch: Partial<SkillInput>): Skill {/*** Keep the skill lists of projects and chats in step with a rename (`to`) or a delete (`to` null):- * a project whose only skill went away would otherwise have no skills at all.+ * a project whose only skill went away would otherwise have no skills at all. A scheduled task that runs the skill+ * follows a rename; a delete pauses it with the reason, as a deleted project does.*/function renameSkillRefs(from: string, to: string | null): void {+ const tasks = db()+ .prepare("SELECT id, prompt, skill_json FROM assist_schedules WHERE skill_json IS NOT NULL AND (CASE WHEN json_valid(skill_json) THEN json_extract(skill_json, '$.name') END) = ?")+ .all(from) as { id: string; prompt: string; skill_json: string }[];+ for (const t of tasks) {+ if (to) {+ // The task's prompt is its skill in words ("/name Input: value · …"): it names the skill as it's called now.+ const prompt = t.prompt === `/${from}` || t.prompt.startsWith(`/${from} `) ? `/${to}${t.prompt.slice(from.length + 1)}` : t.prompt;+ db().prepare("UPDATE assist_schedules SET skill_json = ?, prompt = ? WHERE id = ?").run(JSON.stringify({ ...JSON.parse(t.skill_json), name: to }), prompt, t.id);+ } else {+ // The last result becomes the reason (not the last run's chat, which the page would read instead).+ db()+ .prepare("UPDATE assist_schedules SET paused = 1, last_thread_id = NULL, last_status = 'failed', last_text = 'Paused: its skill was deleted', updated_at = ? WHERE id = ?")+ .run(Date.now(), t.id);+ }+ }const like = `%${JSON.stringify(from)}%`;for (const [table, key] of [["assist_projects", "id"],diff --git a/tests/assist-schedules.test.ts b/tests/assist-schedules.test.tsindex 570bcc86..2c082177 100644--- a/tests/assist-schedules.test.ts+++ b/tests/assist-schedules.test.ts@@ -23,7 +23,7 @@ const agent = await import("@/server/assist/agent");const tools = await import("@/server/assist/tools");const sched = await import("@/server/assist/schedules");const projects = await import("@/server/assist/projects");-const { db } = await import("@/server/db");+const { db, MIGRATIONS } = await import("@/server/db");const { spendOf } = await import("@/lib/assist-schedule");const connectors = await import("@/server/assist/connectors");const listRoute = await import("@/app/api/assist/schedules/route");@@ -367,3 +367,199 @@ describe("connectors in scheduled runs", () => {expect(m.seen[0].system).toMatch(/say what you'll do and wait for the user's OK in chat/);});});++describe("a skill on a schedule (Skills W4)", () => {+ const skills = () => import("@/server/skills");+ const recipes = () => import("@/server/recipes");+ /** A model that must never be called: a skill task's runs have no model planning them. */+ const noModel: import("@/server/assist/agent").ModelCall = async () => {+ throw new Error("a skill task called a model");+ };+ const at = T("2026-10-27T08:00:00Z");+ const daily = { kind: "daily" as const, time: "09:00" };++ async function promoSkill(name = "weekly-promo") {+ const s = await skills();+ if (s.getSkill(name)) return name;+ s.createSkill({ name, title: "Weekly promo", description: "A promo still from a product photo.", body: "# Weekly promo\n\n1. Stage the product." });+ (await recipes()).saveRecipe(name, {+ fuobeRecipe: 1,+ params: [+ { id: "product", label: "Product photo", type: "image", required: true },+ { id: "name", label: "Product name", type: "text", required: true, max: 200 },+ ],+ steps: [{ key: "ad", kind: "generate", request: { feature: "skill", modelId: "nano-banana-pro", op: "edit", prompt: "{{name}} on a sunlit plinth", inputs: { images: ["{{product}}"] } } }],+ });+ return name;+ }++ async function upload(name: string, createdAt: number) {+ const { saveFile } = await import("@/server/storage");+ const { encodePng } = await import("@/server/png");+ const a = saveFile({ data: encodePng({ width: 8, height: 8, data: Buffer.alloc(8 * 8 * 4, 200) }), contentType: "image/png", source: "upload", name });+ db().prepare("UPDATE assets SET created_at = ? WHERE id = ?").run(createdAt, a.id);+ return a;+ }++ const stored = (threadId: string) => JSON.parse((db().prepare("SELECT messages_json FROM assist_threads WHERE id = ?").get(threadId) as { messages_json: string }).messages_json) as Anthropic.Beta.BetaMessageParam[];++ it("newest upload with no upload of that kind yet: the run fails and says why, and the task stays on", async () => {+ const name = await promoSkill();+ const s = sched.createSchedule({ ...base, prompt: "", title: "", skill: { name, values: { name: "Lumen lamp" }, sources: { product: "newest" } }, rule: daily }, at);+ expect(await sched.sweepSchedules(T("2026-10-27T09:00:00Z"), { model: noModel })).toEqual([]);+ expect(sched.getSchedule(s.id)).toMatchObject({ paused: false, runs: 1, last: { threadId: null, status: "failed", text: "There's no image upload yet for “Product photo” — upload one, or edit the task to pick a file" } });+ });++ it("is checked when saved: the skill, its inputs and the engine; and needs no prompt or model", async () => {+ const name = await promoSkill();+ const save = (skill: import("@/lib/assist-schedule").ScheduleSkill, extra: Partial<import("@/server/assist/schedules").ScheduleInput> = {}) =>+ sched.createSchedule({ ...base, prompt: "", title: "", skill, rule: daily, ...extra }, at);+ expect(() => save({ name: "nope", values: {} })).toThrow("There's no skill called /nope");+ expect(() => save({ name: "product-photoshoot", values: {} })).toThrow(/doesn't run by itself/);+ expect(() => save({ name, values: { colour: "red" }, sources: { product: "newest" } })).toThrow("/weekly-promo has no input “colour”");+ expect(() => save({ name, values: { product: "/api/files/uploads/x.png" }, sources: { name: "newest" } })).toThrow(/Product name isn't a file/);+ expect(() => save({ name, values: {}, sources: { product: "newest" } })).toThrow("Product name is needed");+ expect(() => save({ name, values: { name: "Lumen" }, sources: { product: "newest" } }, { engine: "open" })).toThrow(/runs on the cloud only/);+ expect(() => sched.createSchedule({ ...base, prompt: " ", title: "x", rule: daily }, at)).toThrow("Write what Assist should do each time");+ const s = save({ name, values: { name: "Lumen lamp" }, sources: { product: "newest" } }, { mode: { mode: "smart" }, connectors: true, attachments: ["/api/files/uploads/a.png"] });+ expect(s).toMatchObject({+ title: "Weekly promo",+ prompt: "/weekly-promo Product photo: your newest image upload · Product name: Lumen lamp",+ skill: { name, values: { name: "Lumen lamp" }, sources: { product: "newest" } },+ // No model plans it, so no mode and no connectors; a request's files don't apply.+ mode: null,+ connectors: false,+ attachments: [],+ });+ // Through the route, with no prompt; switching back to a request needs one.+ const res = await listRoute.POST(new Request("http://x", { method: "POST", body: JSON.stringify({ ...base, prompt: "", title: "Promo", skill: { name, values: { name: "Lumen" }, sources: { product: "newest" } }, rule: daily }) }));+ expect(res.status).toBe(201);+ const ctx = { params: Promise.resolve({ scheduleId: (await res.json()).id }) };+ const back = await oneRoute.PATCH(new Request("http://x", { method: "PATCH", body: JSON.stringify({ skill: null, prompt: "" }) }), ctx);+ expect(back.status).toBe(400);+ expect((await back.json()).error).toBe("Write what Assist should do each time");+ });++ it("ask first: one card with the skill's price, and the newest upload is read when the run starts", async () => {+ const name = await promoSkill();+ const older = await upload("old.png", T("2026-10-26T08:00:00Z"));+ const s = sched.createSchedule({ ...base, prompt: "", title: "", skill: { name, values: { name: "Lumen lamp" }, sources: { product: "newest" } }, rule: daily }, at);+ // Uploaded after the task was saved: the run uses it.+ const newer = await upload("new.png", T("2026-10-27T08:30:00Z"));+ const [id] = await sched.sweepSchedules(T("2026-10-27T09:00:00Z"), { model: noModel });+ const t = threadOf(id);+ expect(t).toMatchObject({ status: "waiting", agent: "offline", scheduleId: s.id });+ expect(t.items[0]).toMatchObject({ role: "notice", text: expect.stringMatching(/^Scheduled run of “Weekly promo” · Every day at 09:00 · plans wait for your approval · runs the Weekly promo skill as it was saved, with no AI model planning it\.$/) });+ expect(t.items[1]).toMatchObject({ role: "user", text: "Product photo: your newest image upload (file 1) · Product name: Lumen lamp", skills: [name], attachments: [newer.url] });+ const card = t.items.find((i) => i.role === "approval");+ const price = (await recipes()).estimateRecipe(name, { values: { product: newer.url, name: "Lumen lamp" } }, "cloud");+ expect(card).toMatchObject({ status: "pending", summary: "Weekly promo", totalUsd: price.total });+ expect(card?.role === "approval" && card.jobs.map((j) => [j.tool, j.modelId])).toEqual([["run_skill", "nano-banana-pro"]]);+ // The offline planner's note isn't under a skill task's card: no planner made it.+ expect(t.items.some((i) => i.role === "notice" && /Offline planner/.test(i.text))).toBe(false);+ const use = stored(id).flatMap((m) => (typeof m.content === "string" ? [] : m.content)).find((b) => b.type === "tool_use");+ expect(use).toMatchObject({ name: "run_skill", input: { name, values: { name: "Lumen lamp", product: newer.url }, engine: "cloud" } });+ expect(older.url).not.toBe(newer.url);+ expect(sched.getSchedule(s.id)!.last).toMatchObject({ threadId: id, status: "waiting", text: expect.stringMatching(/^A plan waits for your approval/) });+ // Approved later: the skill's steps start with the file that was newest when it ran.+ await agent.answerApproval(id, true);+ await agent.run(id);+ const made = threadOf(id).items.flatMap((i) => (i.role === "generations" ? i.ids : []));+ expect(made).toHaveLength(1);+ const { getGeneration } = await import("@/server/generations");+ expect(getGeneration(made[0])!.request).toMatchObject({ prompt: "Lumen lamp on a sunlit plinth", inputs: { images: [newer.url] }, skill: { name } });+ expect(sched.getSchedule(s.id)!.last).toMatchObject({ status: "done", text: "Started 1 result" });+ });++ it("auto-run: within the cap it starts on its own; over the cap it waits, with the reason", async () => {+ const name = await promoSkill();+ const photo = await upload("cap.png", T("2026-10-27T08:40:00Z"));+ setSetting("falKey", "fal-test-key");+ const realFetch = globalThis.fetch;+ // The paid job is queued for fal; no request may leave this test.+ globalThis.fetch = (async () => new Response("offline", { status: 503 })) as typeof fetch;+ try {+ const price = spendOf(tools.planFor("run_skill", { name, values: { product: photo.url, name: "Lumen" } }, { engine: "cloud" }).jobs)!;+ expect(price).toBeGreaterThan(0);+ const skill = { name, values: { name: "Lumen", product: photo.url } };+ const fits = sched.createSchedule({ ...base, prompt: "", title: "Fits", approval: "auto", capUsd: Math.round(price * 150) / 100, skill, rule: daily }, at);+ const [a] = await sched.sweepSchedules(T("2026-10-27T09:00:00Z"), { model: noModel });+ expect(threadOf(a)).toMatchObject({ status: "idle", spentUsd: price });+ expect(threadOf(a).items.some((i) => i.role === "approval")).toBe(false);+ expect(threadOf(a).items.filter((i) => i.role === "generations")).toHaveLength(1);+ expect(threadOf(a).items.at(-1)).toMatchObject({ role: "assistant", text: "Started Weekly promo. The results appear here and in your Library as they finish." });+ expect(sched.getSchedule(fits.id)!.last).toMatchObject({ status: "done", text: "Started 1 result" });+ sched.deleteSchedule(fits.id);++ const cap = Math.floor(price * 50) / 100;+ sched.createSchedule({ ...base, prompt: "", title: "Over", approval: "auto", capUsd: cap, skill, rule: daily }, at);+ const [b] = await sched.sweepSchedules(T("2026-10-27T09:00:00Z"), { model: noModel });+ const t = threadOf(b);+ expect(t.status).toBe("waiting");+ expect(t.items.some((i) => i.role === "generations")).toBe(false);+ expect(t.items.find((i) => i.role === "approval")).toMatchObject({ status: "pending", summary: "Weekly promo" });+ expect(t.items.at(-1)).toMatchObject({ role: "notice", text: expect.stringMatching(/^Waiting for you: it costs about \$[\d.]+ and this run has \$[\d.]+ left of its \$[\d.]+ cap\./) });+ } finally {+ globalThis.fetch = realFetch;+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();+ }+ });++ it("a fixed file keeps its task's file out of Empty trash; a value that no longer fits fails the run with the reason", async () => {+ const name = await promoSkill();+ const photo = await upload("fixed.png", T("2026-10-27T08:45:00Z"));+ const s = sched.createSchedule({ ...base, prompt: "", title: "Fixed", skill: { name, values: { name: "Lumen", product: photo.url } }, rule: daily }, at);+ const { assetUses } = await import("@/server/generations");+ expect(assetUses(photo.id)).toContainEqual({ what: "scheduled task", key: s.id, name: "Fixed" });+ // The skill's inputs changed after the task was saved (a new required input): the run says what's missing.+ (await recipes()).saveRecipe(name, {+ fuobeRecipe: 1,+ params: [+ { id: "product", label: "Product photo", type: "image", required: true },+ { id: "name", label: "Product name", type: "text", required: true, max: 200 },+ { id: "tagline", label: "Tagline", type: "text", required: true },+ ],+ steps: [{ key: "ad", kind: "generate", request: { feature: "skill", modelId: "nano-banana-pro", op: "edit", prompt: "{{name}}: {{tagline}}", inputs: { images: ["{{product}}"] } } }],+ });+ const [id] = await sched.sweepSchedules(T("2026-10-27T09:00:00Z"), { model: noModel });+ expect(threadOf(id).items.some((i) => i.role === "approval")).toBe(false);+ expect(sched.getSchedule(s.id)!.last).toMatchObject({ threadId: id, status: "failed", text: "Weekly promo didn't start: /weekly-promo needs tagline (text)" });+ (await skills()).deleteSkill(name);+ });++ it("a renamed skill keeps its tasks; a deleted one pauses them and says why", async () => {+ const s0 = await skills();+ const name = await promoSkill("monday-promo");+ const s = sched.createSchedule({ ...base, prompt: "", title: "Monday", skill: { name, values: { name: "Lumen" }, sources: { product: "newest" } }, rule: daily }, at);+ s0.updateSkill(name, { name: "monday-ad" });+ expect(sched.getSchedule(s.id)).toMatchObject({ paused: false, skill: { name: "monday-ad" }, prompt: "/monday-ad Product photo: your newest image upload · Product name: Lumen" });+ s0.deleteSkill("monday-ad");+ expect(sched.getSchedule(s.id)).toMatchObject({ paused: true, nextRunAt: null, last: { threadId: null, status: "failed", text: "Paused: its skill was deleted" } });+ expect(await sched.sweepSchedules(T("2026-10-28T09:00:00Z"), { model: noModel })).toEqual([]);+ // It can still be renamed or deleted; resuming says why it can't run.+ expect(sched.updateSchedule(s.id, { title: "Monday (old)" })!.title).toBe("Monday (old)");+ expect(() => sched.updateSchedule(s.id, { paused: false })).toThrow("There's no skill called /monday-ad");+ // A skill removed behind deleteSkill's back: the start finds no skill and pauses the task.+ const other = await promoSkill("tuesday-promo");+ const t = sched.createSchedule({ ...base, prompt: "", title: "Tuesday", skill: { name: other, values: { name: "Lumen" }, sources: { product: "newest" } }, rule: daily }, at);+ db().prepare("DELETE FROM skills WHERE name = ?").run(other);+ const res = await runRoute.POST(new Request("http://x", { method: "POST" }), { params: Promise.resolve({ scheduleId: t.id }) });+ expect(res.status).toBe(422);+ expect(await res.json()).toMatchObject({ threadId: null, reason: "paused", error: "Its skill was deleted — edit the task to pick another" });+ expect(sched.getSchedule(t.id)).toMatchObject({ paused: true });+ });++ it("the migration adds skill_json to a database from before, and its tasks keep running as requests", () => {+ const d = db();+ const id = MIGRATIONS.findIndex((m) => m.includes("ALTER TABLE assist_schedules ADD COLUMN skill_json"));+ expect(id).toBe(MIGRATIONS.length - 1);+ const old = sched.createSchedule({ ...base, title: "From before", rule: daily }, at);+ d.exec("ALTER TABLE assist_schedules DROP COLUMN skill_json");+ d.prepare("DELETE FROM _migrations WHERE id = ?").run(id);+ d.close();+ globalThis.__fuobeDb = undefined;+ const cols = (db().prepare("PRAGMA table_info(assist_schedules)").all() as { name: string }[]).map((c) => c.name);+ expect(cols).toContain("skill_json");+ expect(sched.getSchedule(old.id)).toMatchObject({ title: "From before", prompt: "Make today's perfume ad", skill: null });+ });+});