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
Assist: scheduled tasks and custom MCP connectors on the server
Claude26f84981e531
diff --git a/src/app/api/assist/connectors/[connectorId]/route.ts b/src/app/api/assist/connectors/[connectorId]/route.tsnew file mode 100644index 00000000..b6677c2d--- /dev/null+++ b/src/app/api/assist/connectors/[connectorId]/route.ts@@ -0,0 +1,18 @@+import { ConnectorError, deleteConnector, updateConnector } from "@/server/assist/connectors";+import { ConnectorBody } from "@/server/assist/schemas";++/** Rename, change the URL, replace the token ("" removes it; leave it out to keep it), switch on or off. */+export async function PATCH(request: Request, ctx: RouteContext<"/api/assist/connectors/[connectorId]">) {+ const parsed = ConnectorBody.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Invalid change" }, { status: 400 });+ try {+ const c = updateConnector((await ctx.params).connectorId, parsed.data);+ return c ? Response.json(c) : Response.json({ error: "Not found" }, { status: 404 });+ } catch (e) {+ return Response.json({ error: (e as Error).message }, { status: e instanceof ConnectorError ? e.status : 500 });+ }+}++export async function DELETE(_req: Request, ctx: RouteContext<"/api/assist/connectors/[connectorId]">) {+ return deleteConnector((await ctx.params).connectorId) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });+}diff --git a/src/app/api/assist/connectors/route.ts b/src/app/api/assist/connectors/route.tsnew file mode 100644index 00000000..8295fc7f--- /dev/null+++ b/src/app/api/assist/connectors/route.ts@@ -0,0 +1,19 @@+import { connection } from "next/server";+import { ConnectorError, createConnector, listConnectors } from "@/server/assist/connectors";+import { ConnectorBody } from "@/server/assist/schemas";++/** Custom MCP connectors, tokens masked. */+export async function GET() {+ await connection();+ return Response.json({ items: listConnectors() });+}++export async function POST(request: Request) {+ const parsed = ConnectorBody.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Check the connector's name, URL and token" }, { status: 400 });+ try {+ return Response.json(createConnector(parsed.data), { status: 201 });+ } catch (e) {+ return Response.json({ error: (e as Error).message }, { status: e instanceof ConnectorError ? e.status : 500 });+ }+}diff --git a/src/app/api/assist/schedules/[scheduleId]/route.ts b/src/app/api/assist/schedules/[scheduleId]/route.tsnew file mode 100644index 00000000..b5857eeb--- /dev/null+++ b/src/app/api/assist/schedules/[scheduleId]/route.ts@@ -0,0 +1,28 @@+import { connection } from "next/server";+import { deleteSchedule, getSchedule, ScheduleError, updateSchedule } from "@/server/assist/schedules";+import { ScheduleBody } from "@/server/assist/schemas";++const Patch = ScheduleBody.partial();++export async function GET(_req: Request, ctx: RouteContext<"/api/assist/schedules/[scheduleId]">) {+ await connection();+ const s = getSchedule((await ctx.params).scheduleId);+ return s ? Response.json(s) : Response.json({ error: "Not found" }, { status: 404 });+}++/** Edit, pause (`{paused: true}`) or resume a task. */+export async function PATCH(request: Request, ctx: RouteContext<"/api/assist/schedules/[scheduleId]">) {+ const parsed = Patch.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: parsed.error.issues[0]?.message ?? "Invalid change" }, { status: 400 });+ try {+ const s = updateSchedule((await ctx.params).scheduleId, parsed.data);+ return s ? Response.json(s) : Response.json({ error: "Not found" }, { status: 404 });+ } catch (e) {+ return Response.json({ error: (e as Error).message }, { status: e instanceof ScheduleError ? e.status : 500 });+ }+}++/** Delete the task; the chats its runs made stay. */+export async function DELETE(_req: Request, ctx: RouteContext<"/api/assist/schedules/[scheduleId]">) {+ return deleteSchedule((await ctx.params).scheduleId) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });+}diff --git a/src/app/api/assist/schedules/[scheduleId]/run/route.ts b/src/app/api/assist/schedules/[scheduleId]/run/route.tsnew file mode 100644index 00000000..4d54e9c9--- /dev/null+++ b/src/app/api/assist/schedules/[scheduleId]/run/route.ts@@ -0,0 +1,13 @@+import { after } from "next/server";+import { ScheduleError, startSchedule } from "@/server/assist/schedules";++/** Run a task now, off schedule: a new chat starts and the agent works in the background. */+export async function POST(_req: Request, ctx: RouteContext<"/api/assist/schedules/[scheduleId]/run">) {+ try {+ const { threadId, done } = await startSchedule((await ctx.params).scheduleId);+ after(() => done);+ return Response.json({ threadId }, { status: threadId ? 202 : 409 });+ } catch (e) {+ return Response.json({ error: (e as Error).message }, { status: e instanceof ScheduleError ? e.status : 500 });+ }+}diff --git a/src/app/api/assist/schedules/route.ts b/src/app/api/assist/schedules/route.tsnew file mode 100644index 00000000..26c0fc07--- /dev/null+++ b/src/app/api/assist/schedules/route.ts@@ -0,0 +1,22 @@+import { connection } from "next/server";+import { createSchedule, listSchedules, ScheduleError } from "@/server/assist/schedules";+import { ScheduleBody } from "@/server/assist/schemas";++const issue = (e: { issues: { message: string }[] }) => e.issues[0]?.message ?? "Check the schedule";++/** Scheduled tasks (all, `?project=<id>`, or `?project=none` for those outside projects). */+export async function GET(request: Request) {+ await connection();+ const project = new URL(request.url).searchParams.get("project");+ return Response.json({ items: listSchedules({ project: project === "none" ? null : (project ?? undefined) }) });+}++export async function POST(request: Request) {+ const parsed = ScheduleBody.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: issue(parsed.error) }, { status: 400 });+ try {+ return Response.json(createSchedule(parsed.data), { status: 201 });+ } catch (e) {+ return Response.json({ error: (e as Error).message }, { status: e instanceof ScheduleError ? e.status : 500 });+ }+}diff --git a/src/instrumentation.ts b/src/instrumentation.tsindex b3ae0fbf..2e2adc9e 100644--- a/src/instrumentation.ts+++ b/src/instrumentation.ts@@ -1,7 +1,7 @@/*** Runs once when the server starts: start the generation runner right away, so jobs that were in* flight before a restart keep advancing (and live updates flow) even when the UI only lists them.- * Also empties what has been in the Trash for 30 days (then daily).+ * Also empties what has been in the Trash for 30 days (then daily), and starts Assist's scheduled tasks.*/export async function register() {if (process.env.NEXT_RUNTIME !== "nodejs" || process.env.NEXT_PHASE === "phase-production-build") return;@@ -12,4 +12,7 @@ export async function register() {// Faceless / Explainer renders whose narration was timed while the server was down continue with their scenes.const { ensureFacelessRunner } = await import("./server/faceless");ensureFacelessRunner();+ // Assist's scheduled tasks: a 30 s sweep starts the runs that are due (a run missed while the server was off happens once).+ const { ensureScheduleRunner } = await import("./server/assist/schedules");+ ensureScheduleRunner();}diff --git a/src/lib/assist-connectors.ts b/src/lib/assist-connectors.tsnew file mode 100644index 00000000..76f6535a--- /dev/null+++ b/src/lib/assist-connectors.ts@@ -0,0 +1,101 @@+/**+ * Assist's custom MCP connectors (Supercomputer's "Custom MCP connector (HTTP header)"): a name, a+ * remote MCP server URL and an optional token. Claude reaches them through the Messages API's MCP+ * connector, from Anthropic's servers — Fuobe itself never connects to them, and the browser never+ * sees the token (or the URL's query, which often carries a key).+ */++export const MAX_CONNECTORS = 20;+export const MAX_CONNECTOR_URL = 2048;+export const MAX_CONNECTOR_NAME = 60;+export const MAX_CONNECTOR_TOKEN = 4096;++/** A connector as the browser sees it: the token and the URL's query masked. */+export interface ConnectorView {+ id: string;+ name: string;+ /** The name Claude and the chat use for it (letters, numbers, - and _). */+ slug: string;+ /** The URL with any query string and fragment masked. */+ url: string;+ enabled: boolean;+ hasToken: boolean;+ /** The token masked ("sk-a••••9f3c"), empty when there's none. */+ token: string;+ /** Why Claude may not reach it (a local or private address), shown as a warning. */+ warning?: string;+ createdAt: number;+ updatedAt: number;+}++const LOOPBACK = /^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i;+const PRIVATE_V4 = /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|169\.254\.|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.|0\.)/;++const isLoopback = (host: string) => LOOPBACK.test(host) || host.endsWith(".localhost");+const isPrivateHost = (host: string) => isLoopback(host) || PRIVATE_V4.test(host) || /^\[(f[cd]|fe[89ab])/i.test(host) || /\.(local|internal|lan|home\.arpa)$/i.test(host);++/**+ * Check a connector URL someone typed: https, or plain http only for this machine (localhost) unless+ * FUOBE_ALLOW_PRIVATE_URLS=1; no user name or password in it (the token has its own field); at most+ * 2,048 characters. Returns the normalised URL and, for a local or private address, a warning: Claude+ * connects from Anthropic's servers, so such an address only works through a public tunnel.+ */+export function checkConnectorUrl(raw: string, allowPrivate = false): { url: string; warning?: string } | { error: string } {+ const s = raw.trim();+ if (!s) return { error: "Enter the connector's URL" };+ if (s.length > MAX_CONNECTOR_URL) return { error: `That URL is too long (at most ${MAX_CONNECTOR_URL.toLocaleString("en")} characters)` };+ let u: URL;+ try {+ u = new URL(s);+ } catch {+ return { error: "Enter a full URL, like https://mcp.example.com/mcp" };+ }+ if (u.protocol !== "https:" && u.protocol !== "http:") return { error: "Connectors use https:// URLs" };+ if (u.username || u.password) return { error: "Put the token in the token field, not in the URL" };+ const host = u.hostname.toLowerCase();+ if (!host) return { error: "Enter a full URL, like https://mcp.example.com/mcp" };+ if (u.protocol === "http:" && !isLoopback(host) && !allowPrivate) return { error: "Use https:// — plain http is only allowed for localhost" };+ const warning = isPrivateHost(host)+ ? "This address is on your machine or network. Claude connects from Anthropic's servers, so it only works through a public tunnel."+ : u.protocol === "http:"+ ? "Plain http: the token travels unencrypted."+ : undefined;+ return { url: u.toString(), ...(warning && { warning }) };+}++/** The URL with its query and fragment masked: many MCP servers put a key there. */+export function maskConnectorUrl(url: string): string {+ try {+ const u = new URL(url);+ const hidden = u.search || u.hash;+ return `${u.origin}${u.pathname === "/" && !hidden ? "" : u.pathname}${hidden ? "?••••" : ""}`;+ } catch {+ return "••••";+ }+}++/**+ * The name Claude sees for a connector, from its display name: lowercase letters, numbers, - and _,+ * at most 40 characters, unique among `taken` (a number is added).+ */+export function connectorSlug(name: string, taken: Iterable<string> = []): string {+ const base =+ name+ .normalize("NFKD")+ .replace(/[̀-ͯ]/g, "")+ .toLowerCase()+ .replace(/[^a-z0-9_-]+/g, "-")+ .replace(/^[-_]+|[-_]+$/g, "")+ .slice(0, 36) || "connector";+ const used = new Set(taken);+ if (!used.has(base)) return base;+ for (let i = 2; ; i++) if (!used.has(`${base}-${i}`)) return `${base}-${i}`;+}++/** A pasted "Bearer abc" or "Authorization: Bearer abc" is the token "abc" (Claude sends it as a Bearer token). */+export const cleanToken = (t: string) =>+ t+ .trim()+ .replace(/^authorization\s*:\s*/i, "")+ .replace(/^bearer\s+/i, "")+ .trim();diff --git a/src/lib/assist-schedule.ts b/src/lib/assist-schedule.tsnew file mode 100644index 00000000..f7c7712e--- /dev/null+++ b/src/lib/assist-schedule.ts@@ -0,0 +1,286 @@+/**+ * Assist's scheduled tasks (Supercomputer's "Scheduled Tasks"): a prompt that runs as a new chat on+ * the server's clock — daily, on some weekdays, every N hours or once — in an IANA time zone.+ * Pure, so the server's sweep and the schedule dialog's "Next run" preview share it.+ *+ * Clock changes: a time a spring-forward skips runs as much later as the clocks jumped (02:30 on+ * the night the clocks go 02:00 → 03:00 runs at 03:30); a time a fall-back repeats runs once, the+ * first time. "Every N hours" counts real hours, so it doesn't move with the clocks.+ */++export type ScheduleRule =+ /** Every day at a wall-clock time ("09:00"). */+ | { kind: "daily"; time: string }+ /** Some weekdays (0 = Sunday … 6 = Saturday) at a wall-clock time. */+ | { kind: "weekly"; days: number[]; time: string }+ /** Every N real hours, counted from `from` (when the task was saved). */+ | { kind: "hours"; every: number; from: number }+ /** Once, at a wall-clock date and time ("2026-10-30T14:00"). */+ | { kind: "once"; at: string };++/** 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";++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;+/** The most a run may spend on its own, per run. */+export const MAX_SCHEDULE_CAP_USD = 500;+export const DEFAULT_SCHEDULE_CAP_USD = 2;++/** A scheduled task as the UI sees it. */+export interface ScheduleView {+ id: string;+ title: string;+ prompt: string;+ attachments: string[];+ projectId: string | null;+ rule: ScheduleRule;+ tz: string;+ approval: ScheduleApproval;+ capUsd: number | null;+ engine: "cloud" | "open";+ /** The mode choice runs start with (null: the default from Settings). */+ mode: { mode: "free" | "smart" | "manual"; agent?: "claude" | "ollama" | "offline"; model?: string | null; effort?: "low" | "medium" | "high" | "xhigh" | "max" | null } | null;+ paused: boolean;+ /** When it runs next (null: paused, or a one-off that has run). */+ nextRunAt: number | null;+ lastRunAt: number | null;+ last: ScheduleResult | null;+ runs: number;+ createdAt: number;+ updatedAt: number;+}++/** How the last run went, read live from its chat. */+export interface ScheduleResult {+ threadId: string | null;+ /** running: still going; waiting: a plan waits for approval; done: finished; failed: an error stopped it; skipped: the run before was still going. */+ status: "running" | "waiting" | "done" | "failed" | "skipped";+ /** Results it started, a short reason, or the error. */+ text: string;+}++const TIME = /^([01]\d|2[0-3]):([0-5]\d)$/;+const LOCAL = /^(\d{4})-(\d{2})-(\d{2})T([01]\d|2[0-3]):([0-5]\d)$/;++/** Whether this runtime knows the IANA zone ("Europe/Berlin"). */+export function validTimeZone(tz: string): boolean {+ if (!tz || tz.length > 64) return false;+ try {+ new Intl.DateTimeFormat("en-US", { timeZone: tz });+ return true;+ } catch {+ return false;+ }+}++/** The rule's problem in words, or null when it's valid. */+export function ruleError(rule: ScheduleRule): string | null {+ switch (rule.kind) {+ case "daily":+ return TIME.test(rule.time) ? null : "Pick a time";+ case "weekly":+ if (!rule.days.length || rule.days.some((d) => !Number.isInteger(d) || d < 0 || d > 6)) return "Pick at least one day";+ return TIME.test(rule.time) ? null : "Pick a time";+ case "hours":+ return Number.isInteger(rule.every) && rule.every >= 1 && rule.every <= MAX_SCHEDULE_HOURS ? null : `Every 1 to ${MAX_SCHEDULE_HOURS} hours`;+ case "once": {+ const m = LOCAL.exec(rule.at);+ if (!m) return "Pick a date and time";+ const [, y, mo, d] = m.map(Number);+ const date = new Date(Date.UTC(y, mo - 1, d));+ return date.getUTCMonth() === mo - 1 && date.getUTCDate() === d ? null : "Pick a real date";+ }+ }+}++// ---------------------------------------------------------------------------+// Wall clocks in a time zone (Intl only: no time-zone library)++const formatters = new Map<string, Intl.DateTimeFormat>();+function formatter(tz: string): Intl.DateTimeFormat {+ let f = formatters.get(tz);+ if (!f) {+ f = new Intl.DateTimeFormat("en-US", { timeZone: tz, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" });+ formatters.set(tz, f);+ }+ return f;+}++export interface WallClock {+ y: number;+ mo: number;+ d: number;+ h: number;+ mi: number;+ /** 0 = Sunday. */+ weekday: number;+}++function clockParts(ms: number, tz: string): WallClock & { s: number } {+ const p = Object.fromEntries(formatter(tz).formatToParts(new Date(ms)).map((x) => [x.type, x.value]));+ const y = Number(p.year);+ const mo = Number(p.month);+ const d = Number(p.day);+ return { y, mo, d, h: Number(p.hour) % 24, mi: Number(p.minute), s: Number(p.second), weekday: new Date(Date.UTC(y, mo - 1, d)).getUTCDay() };+}++/** The date and time a clock in `tz` shows at the instant `ms`. */+export function wallClock(ms: number, tz: string): WallClock {+ const { y, mo, d, h, mi, weekday } = clockParts(ms, tz);+ return { y, mo, d, h, mi, weekday };+}++/** Minutes `tz` is ahead of UTC at the instant `ms`. */+function offsetMinutes(ms: number, tz: string): number {+ const w = clockParts(ms, tz);+ return Math.round((Date.UTC(w.y, w.mo - 1, w.d, w.h, w.mi, w.s) - Math.floor(ms / 1000) * 1000) / 60_000);+}++const sameWall = (ms: number, tz: string, y: number, mo: number, d: number, h: number, mi: number) => {+ const w = wallClock(ms, tz);+ return w.y === y && w.mo === mo && w.d === d && w.h === h && w.mi === mi;+};++/**+ * The instant a clock in `tz` shows this date and time. A repeated time (fall-back) gives its first+ * instant; a skipped one (spring-forward) gives the instant as late as the clocks jumped.+ */+export function zonedToUtc(y: number, mo: number, d: number, h: number, mi: number, tz: string): number {+ const guess = Date.UTC(y, mo - 1, d, h, mi);+ const DAY = 86_400_000;+ // The offsets a day either side cover any clock change near this time.+ const before = offsetMinutes(guess - DAY, tz);+ const after = offsetMinutes(guess + DAY, tz);+ const candidates = [...new Set([guess - before * 60_000, guess - after * 60_000])].filter((t) => sameWall(t, tz, y, mo, d, h, mi));+ if (candidates.length) return Math.min(...candidates);+ // Skipped: read the time with the offset from before the jump.+ return guess - before * 60_000;+}++const parseTime = (t: string) => t.split(":").map(Number) as [number, number];++/** The calendar day `k` days after y-mo-d. */+function addDays(y: number, mo: number, d: number, k: number): { y: number; mo: number; d: number; weekday: number } {+ const t = new Date(Date.UTC(y, mo - 1, d + k));+ return { y: t.getUTCFullYear(), mo: t.getUTCMonth() + 1, d: t.getUTCDate(), weekday: t.getUTCDay() };+}++/** When the rule runs next, strictly after `after` (null: a one-off whose time has passed, or a broken rule). */+export function nextRun(rule: ScheduleRule, tz: string, after: number): number | null {+ if (ruleError(rule) || !validTimeZone(tz)) return null;+ switch (rule.kind) {+ case "hours": {+ const period = rule.every * 3_600_000;+ if (after < rule.from) return rule.from + period;+ return rule.from + (Math.floor((after - rule.from) / period) + 1) * period;+ }+ case "once": {+ const [, y, mo, d, h, mi] = LOCAL.exec(rule.at)!.map(Number);+ const at = zonedToUtc(y, mo, d, h, mi, tz);+ return at > after ? at : null;+ }+ case "daily":+ case "weekly": {+ const [h, mi] = parseTime(rule.time);+ const today = wallClock(after, tz);+ // A day back covers a time a clock change moved past midnight; 8 ahead covers a weekly rule.+ for (let k = -1; k <= 8; k++) {+ const day = addDays(today.y, today.mo, today.d, k);+ if (rule.kind === "weekly" && !rule.days.includes(day.weekday)) continue;+ const at = zonedToUtc(day.y, day.mo, day.d, h, mi, tz);+ if (at > after) return at;+ }+ return null;+ }+ }+}++// ---------------------------------------------------------------------------+// Words++export const WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] as const;+/** Monday first, as the day picker shows them. */+export const WEEK_ORDER = [1, 2, 3, 4, 5, 6, 0] as const;++const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];++function dayList(days: number[]): string {+ const set = [...new Set(days)].sort((a, b) => WEEK_ORDER.indexOf(a as 0) - WEEK_ORDER.indexOf(b as 0));+ if (set.length === 7) return "Every day";+ if (set.length === 5 && [1, 2, 3, 4, 5].every((d) => set.includes(d))) return "Weekdays";+ if (set.length === 2 && set.includes(0) && set.includes(6)) return "Weekends";+ const names = set.map((d) => `${WEEKDAYS[d]}s`);+ return names.length === 1 ? names[0] : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`;+}++/** "Every day at 09:00", "Mondays and Thursdays at 18:30", "Every 6 hours", "Once, 30 Oct 2026 at 14:00". */+export function describeRule(rule: ScheduleRule): string {+ switch (rule.kind) {+ case "daily":+ return `Every day at ${rule.time}`;+ case "weekly":+ return `${dayList(rule.days)} at ${rule.time}`;+ case "hours":+ return rule.every === 1 ? "Every hour" : rule.every % 24 === 0 && rule.every > 24 ? `Every ${rule.every / 24} days` : `Every ${rule.every} hours`;+ case "once": {+ const m = LOCAL.exec(rule.at);+ if (!m) return "Once";+ return `Once, ${Number(m[3])} ${MONTHS[Number(m[2]) - 1]} ${m[1]} at ${m[4]}:${m[5]}`;+ }+ }+}++/** "Tue 28 Oct, 09:00" in the task's zone. */+export function formatWhen(ms: number, tz: string): string {+ const w = wallClock(ms, tz);+ return `${WEEKDAYS[w.weekday].slice(0, 3)} ${w.d} ${MONTHS[w.mo - 1]}, ${String(w.h).padStart(2, "0")}:${String(w.mi).padStart(2, "0")}`;+}++/** "in 5 min", "in 3 h", "in 2 days" (or "now" when it's due). */+export function untilText(ms: number, now: number): string {+ const s = Math.round((ms - now) / 1000);+ if (s < 60) return "now";+ if (s < 3600) return `in ${Math.round(s / 60)} min`;+ if (s < 86_400 * 2) return `in ${Math.round(s / 3600)} h`;+ return `in ${Math.round(s / 86_400)} days`;+}++/** A short zone label: "Europe/Berlin (GMT+1)". */+export function zoneLabel(tz: string, at = Date.now()): string {+ try {+ const name = new Intl.DateTimeFormat("en-US", { timeZone: tz, timeZoneName: "shortOffset" }).formatToParts(new Date(at)).find((p) => p.type === "timeZoneName")?.value;+ return name ? `${tz.replace(/_/g, " ")} (${name})` : tz;+ } catch {+ return tz;+ }+}++// ---------------------------------------------------------------------------+// Spending: what a scheduled run may start on its own++/**+ * Whether an auto-run plan priced `price` may start without asking, when this run has already+ * spent `spent` of `cap` (both USD). No cap: anything runs (a chat with Ask first off). An unknown+ * price, or one that would pass the cap, waits for the user, with the reason.+ */+export function withinCap(cap: number | null, spent: number, price: number | null): { ok: true } | { ok: false; reason: string } {+ if (cap === null) return { ok: true };+ if (price === null) return { ok: false, reason: "its price isn't known in advance" };+ if (spent + price > cap + 1e-9) {+ const left = Math.max(0, cap - spent);+ return { ok: false, reason: `it costs about $${price.toFixed(2)} and this run has $${left.toFixed(2)} left of its $${cap.toFixed(2)} cap` };+ }+ return { ok: true };+}++/**+ * What a plan would really spend: demo jobs cost nothing and jobs that can't run don't start; null+ * when a job that would run for real has no price.+ */+export function spendOf(jobs: { costUsd: number | null; demo: boolean; error?: string }[]): number | null {+ const real = jobs.filter((j) => !j.demo && !j.error);+ if (real.some((j) => j.costUsd === null)) return null;+ return Math.round(real.reduce((n, j) => n + (j.costUsd ?? 0), 0) * 1000) / 1000;+}diff --git a/src/lib/assist.ts b/src/lib/assist.tsindex 40d6df70..5c715a38 100644--- a/src/lib/assist.ts+++ b/src/lib/assist.ts@@ -37,8 +37,8 @@ export const planRunnable = (jobs: PlannedJob[]): boolean => jobs.some((j) => !jexport type AssistItem =| { id: string; role: "user"; text: string; attachments?: string[]; skills?: string[] }| { id: string; role: "assistant"; text: string }- /** `studio`: a job a studio took ("Layers"); its card offers "Open in Layers" (href). */- | { id: string; role: "tool"; text: string; href?: string; studio?: string }+ /** `studio`: a job a studio took ("Layers"); its card offers "Open in Layers" (href). `connector`: a tool of a custom MCP connector Claude used. */+ | { id: string; role: "tool"; text: string; href?: string; studio?: string; connector?: string; failed?: boolean }/** `opens`: the studios the plan's jobs open in; `notes`: why a studio job runs in the Library instead. */| { id: string; role: "approval"; summary: string; jobs: PlannedJob[]; totalUsd: number | null; status: "pending" | "approved" | "declined"; opens?: string[]; notes?: string[] }| { id: string; role: "generations"; ids: string[]; storyboard?: boolean }@@ -69,6 +69,11 @@ export interface AssistThread {effort?: AssistEffort | null;/** Skills loaded into this chat (by `/name` or by the agent). */skills?: string[];+ /** The scheduled task that started this chat. */+ scheduleId?: string;+ /** Auto-run's cost cap for this chat (a scheduled run's), and what ran without asking has cost. */+ capUsd?: number;+ spentUsd?: number;}export interface AssistThreadSummary {diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.tsindex 5a6100d3..8c65b2af 100644--- a/src/server/assist/agent.ts+++ b/src/server/assist/agent.ts@@ -32,6 +32,8 @@ import { offeredDefault } from "../model-access";import { engineMode, getSetting } from "../settings";import { getSkill } from "../skills";import { readRef } from "../storage";+import { spendOf, withinCap } from "@/lib/assist-schedule";+import { activeConnectors, connectorName, MCP_BETA, mcpParams, withoutMissingServers, type Connector } from "./connectors";import { canUseSkill, chatFacts } from "./context";import { getProject, touchProject } from "./projects";import { apiTools, cardTitle, executeTool, getTool, planFor, validateInput, type ToolContext } from "./tools";@@ -62,6 +64,8 @@ export interface ModelRequest {settings?: { model?: string | null; effort?: AssistEffort | null };/** Skills loaded in the chat (the offline planner uses their hints). */skills?: SkillMeta[];+ /** Custom MCP connectors (Settings → Assist): Claude gets them through the MCP connector; other agents can't use them. */+ connectors?: Connector[];}export type ModelCall = (req: ModelRequest) => Promise<Anthropic.Beta.BetaMessage>;@@ -104,6 +108,9 @@ interface StateRow {skills_json: string;context: string | null;sent_json: string | null;+ schedule_id: string | null;+ cap_usd: number | null;+ spent_usd: number | null;}/** Per-chat state beside the transcript (assist_thread_state). */@@ -117,6 +124,11 @@ interface Ext {context: string | null;/** The facts the model has seen, to send only what changed. */sent: Record<string, string> | null;+ /** The scheduled task that started this chat. */+ scheduleId: string | null;+ /** With auto-run on: the most generations may cost without asking (USD), and what they have cost. */+ capUsd: number | null;+ spentUsd: number;}interface State {@@ -141,11 +153,23 @@ function loadExt(id: string): Ext {skills: r ? (JSON.parse(r.skills_json) as string[]) : [],context: r?.context ?? null,sent: r?.sent_json ? (JSON.parse(r.sent_json) as Record<string, string>) : null,+ scheduleId: r?.schedule_id ?? null,+ capUsd: r?.cap_usd ?? null,+ spentUsd: r?.spent_usd ?? 0,};}function withExt(t: AssistThread, e: Ext): AssistThread {- return { ...t, projectId: e.projectId, mode: e.mode ?? (t.agent === "claude" ? "smart" : "free"), model: e.model, effort: e.effort, skills: e.skills };+ return {+ ...t,+ projectId: e.projectId,+ mode: e.mode ?? (t.agent === "claude" ? "smart" : "free"),+ model: e.model,+ effort: e.effort,+ skills: e.skills,+ ...(e.scheduleId && { scheduleId: e.scheduleId }),+ ...(e.capUsd !== null && { capUsd: e.capUsd, spentUsd: e.spentUsd }),+ };}function load(id: string): State | null {@@ -206,10 +230,10 @@ function save(s: State): void {});db().prepare(- `INSERT INTO assist_thread_state (thread_id, project_id, mode, model, effort, skills_json, context, sent_json)- VALUES (@thread_id, @project_id, @mode, @model, @effort, @skills_json, @context, @sent_json)+ `INSERT INTO assist_thread_state (thread_id, project_id, mode, model, effort, skills_json, context, sent_json, schedule_id, cap_usd, spent_usd)+ VALUES (@thread_id, @project_id, @mode, @model, @effort, @skills_json, @context, @sent_json, @schedule_id, @cap_usd, @spent_usd)ON CONFLICT(thread_id) DO UPDATE SET project_id = @project_id, mode = @mode, model = @model, effort = @effort,- skills_json = @skills_json, context = @context, sent_json = @sent_json`,+ skills_json = @skills_json, context = @context, sent_json = @sent_json, schedule_id = @schedule_id, cap_usd = @cap_usd, spent_usd = @spent_usd`,).run({thread_id: s.thread.id,@@ -220,6 +244,9 @@ function save(s: State): void {skills_json: JSON.stringify(s.ext.skills),context: s.ext.context,sent_json: s.ext.sent ? JSON.stringify(s.ext.sent) : null,+ schedule_id: s.ext.scheduleId,+ cap_usd: s.ext.capUsd,+ spent_usd: s.ext.spentUsd,});})();}@@ -322,6 +349,7 @@ export async function updateThread(id: string, patch: ThreadPatch): Promise<Assis.ext.model = r.model;s.ext.effort = r.effort;if (r.note) push(s, { role: "notice", tone: "info", text: r.note });+ connectorNote(s);}save(s);return s.thread;@@ -416,6 +444,15 @@ export async function resolveMode(choice?: Partial<AssistModeChoice>): Promise<Rreturn { mode: "manual", agent: "offline", model: null, effort: null };}+/** Connectors need Claude: a chat on Ollama or the offline planner says so once. */+function connectorNote(s: State): void {+ if (s.thread.agent === "claude" || s.thread.items.some((i) => i.role === "notice" && i.text.startsWith(CONNECTOR_NOTE))) return;+ const names = activeConnectors().map((c) => c.name);+ if (!names.length) return;+ push(s, { role: "notice", tone: "info", text: `${CONNECTOR_NOTE} (${names.slice(0, 3).join(", ")}${names.length > 3 ? "…" : ""}); this chat runs on ${s.thread.agent === "ollama" ? "a local model" : "the offline planner"}, so it can't use them.` });+}+const CONNECTOR_NOTE = "Connectors work in Claude chats";+export function createThread(opts: {engine: Engine;agent: AssistThread["agent"];@@ -425,6 +462,11 @@ export function createThread(opts: {mode?: AssistMode | null;model?: string | null;effort?: AssistEffort | null;+ /** A scheduled run: the task that started it, and auto-run's cost cap for it. */+ scheduleId?: string | null;+ capUsd?: number | null;+ /** A quiet line at the top of the chat (a scheduled run says which task it is). */+ note?: string;}): AssistThread {const now = Date.now();if (opts.projectId && !getProject(opts.projectId)) throw new Error("That project doesn't exist anymore");@@ -432,8 +474,21 @@ export function createThread(opts: {thread: { id: nanoid(12), title: opts.title ?? "New chat", status: "idle", agent: opts.agent, engine: opts.engine, autoApprove: !!opts.autoApprove, items: [], createdAt: now, updatedAt: now },messages: [],pending: null,- ext: { projectId: opts.projectId ?? null, mode: opts.mode ?? null, model: opts.model ?? null, effort: opts.effort ?? null, skills: [], context: null, sent: null },+ ext: {+ projectId: opts.projectId ?? null,+ mode: opts.mode ?? null,+ model: opts.model ?? null,+ effort: opts.effort ?? null,+ skills: [],+ context: null,+ sent: null,+ scheduleId: opts.scheduleId ?? null,+ capUsd: opts.capUsd ?? null,+ spentUsd: 0,+ },};+ if (opts.note) push(s, { role: "notice", tone: "info", text: opts.note });+ connectorNote(s);save(s);if (opts.projectId) touchProject(opts.projectId);return s.thread;@@ -540,11 +595,14 @@ const FALLBACK_MODELS = new Set(["claude-opus-5-5", "claude-sonnet-5-5", "claude*/export const maxTokensFor = (effort: AssistEffort): number => (effort === "xhigh" || effort === "max" ? 64_000 : 32_000);-export const claude: ModelCall = async ({ system, messages, tools, settings }) => {+export const claude: ModelCall = async ({ system, messages, tools, settings, connectors }) => {const client = new Anthropic({ apiKey: getSetting("anthropicKey") });const model = settings?.model && CLAUDE_MODELS.some((m) => m.id === settings.model) ? settings.model : DEFAULT_CLAUDE_MODEL;const fallback = FALLBACK_MODELS.has(model);const effort = settings?.effort ?? DEFAULT_EFFORT;+ // Custom MCP connectors: Anthropic's servers call them; their tools come after Fuobe's own.+ const mcp = mcpParams(connectors ?? []);+ const history = withoutMissingServers(messages, new Set(mcp?.mcp_servers.map((m) => m.name)));// Streamed, so long thinking at high effort never runs into an HTTP timeout; only the final// message is used (the UI shows the reply once it's complete).const stream = client.beta.messages.stream({@@ -554,7 +612,7 @@ export const claude: ModelCall = async ({ system, messages, tools, settings }) =// before contexts were frozen) is dropped instead of failing the request.thinking: { type: "adaptive", block_binding: { prefix_mismatch_behavior: "drop_block" } },output_config: { effort },- betas: [...(fallback ? (["server-side-fallback-2026-07-01"] as const) : []), "thinking-binding-controls-2026-08-01"],+ betas: [...(fallback ? (["server-side-fallback-2026-07-01"] as const) : []), "thinking-binding-controls-2026-08-01", ...(mcp ? [MCP_BETA] : [])],...(fallback && { fallbacks: "default" as const }),// The fixed instructions and the chat's frozen context are cached; so is the conversation so far.cache_control: { type: "ephemeral" },@@ -562,8 +620,9 @@ export const claude: ModelCall = async ({ system, messages, tools, settings }) ={ type: "text", text: system.stable, cache_control: { type: "ephemeral" } },{ type: "text", text: system.turn, cache_control: { type: "ephemeral" } },],- tools,- messages: await hydrate(messages),+ tools: mcp ? [...tools, ...mcp.toolsets] : tools,+ ...(mcp && { mcp_servers: mcp.mcp_servers }),+ messages: await hydrate(history),});return stream.finalMessage();};@@ -1063,7 +1122,7 @@ function ordered(results: ToolResult[], order: string[]): ToolResult[] {* "Context update" message to append. The first call freezes the context into the system prompt.*/function contextFor(s: State): { system: ModelRequest["system"]; update: MessageParam | null; sent: Record<string, string> } {- const facts = chatFacts({ engine: s.thread.engine, autoApprove: s.thread.autoApprove, projectId: s.ext.projectId, skills: s.ext.skills });+ const facts = chatFacts({ engine: s.thread.engine, autoApprove: s.thread.autoApprove, projectId: s.ext.projectId, skills: s.ext.skills, capUsd: s.ext.capUsd, scheduleId: s.ext.scheduleId });const sent = factMap(facts);if (!s.ext.context) {s.ext.context = renderContext(facts);@@ -1075,6 +1134,20 @@ function contextFor(s: State): { system: ModelRequest["system"]; update: Messagereturn { system: { stable: STABLE_SYSTEM, turn: s.ext.context }, update: text ? { role: "system", content: text } : null, sent };}+/** "Notion · search_pages": each connector tool Claude used in a reply, marked when it failed. */+function connectorItems(s: State, content: Anthropic.Beta.BetaContentBlock[]): void {+ const shown = new Map<string, AssistItem>();+ for (const b of content) {+ if (b.type === "mcp_tool_use") {+ const name = connectorName(b.server_name);+ shown.set(b.id, push(s, { role: "tool", text: `${name} · ${b.name}`, connector: name }));+ } else if (b.type === "mcp_tool_result" && b.is_error) {+ const item = shown.get(b.tool_use_id);+ if (item?.role === "tool") item.failed = true;+ }+ }+}+async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {const ctx = toolCtx(s);const { system, update, sent } = contextFor(s);@@ -1086,6 +1159,7 @@ async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {ctx,settings: { model: s.ext.model, effort: s.ext.effort },skills: active,+ ...(s.thread.agent === "claude" && { connectors: activeConnectors() }),});if (res.stop_reason === "refusal") {@@ -1103,6 +1177,7 @@ async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {s.ext.sent = sent;}s.messages.push({ role: "assistant", content: res.content });+ connectorItems(s, res.content);const text = res.content.filter((b): b is Anthropic.Beta.BetaTextBlock => b.type === "text").map((b) => b.text)@@ -1125,23 +1200,39 @@ async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {const results: ToolResult[] = [];const gated: Pending["gated"] = [];+ // Why auto-run left a plan for the user: it would pass this chat's cost cap.+ const held: string[] = [];// The rule-based planner says so in a quiet line under its plan (or under the jobs it started).const offlineNote = () => {if (model === offline) push(s, { role: "notice", tone: "info", text: OFFLINE_NOTE });};for (const u of uses) {- if (getTool(u.name)?.gated && !s.thread.autoApprove) {- // Malformed arguments (common from small local models) go straight back as an error the model can fix, not onto an approval card.- const invalid = validateInput(u.name, u.input);- if (invalid) {- results.push({ type: "tool_result", tool_use_id: u.id, is_error: true, content: invalid });+ let price: number | null = null;+ if (getTool(u.name)?.gated) {+ let ask = !s.thread.autoApprove;+ // Auto-run with a cap (a scheduled run): what fits starts on its own, the rest waits for the user.+ if (!ask && s.ext.capUsd !== null) {+ price = spendOf(planFor(u.name, u.input, ctx).jobs);+ const fits = withinCap(s.ext.capUsd, s.ext.spentUsd, price);+ if (!fits.ok) {+ ask = true;+ held.push(fits.reason);+ }+ }+ if (ask) {+ // Malformed arguments (common from small local models) go straight back as an error the model can fix, not onto an approval card.+ const invalid = validateInput(u.name, u.input);+ if (invalid) {+ results.push({ type: "tool_result", tool_use_id: u.id, is_error: true, content: invalid });+ continue;+ }+ gated.push({ id: u.id, name: u.name, input: u.input });continue;}- gated.push({ id: u.id, name: u.name, input: u.input });- continue;}const { result, items } = await runTool(u.name, u.input, ctx);results.push({ ...result, tool_use_id: u.id });+ if (price && !result.is_error) s.ext.spentUsd = Math.round((s.ext.spentUsd + price) * 1000) / 1000;for (const it of items) push(s, it);}const order = uses.map((u) => u.id);@@ -1154,6 +1245,7 @@ async function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {// Two calls that fall back for the same reason say it once.const notes = [...new Set(plans.flatMap((p) => (p.fallback ? [`${p.fallback}.`] : [])))];const item = push(s, { role: "approval", summary, jobs, totalUsd: total, status: "pending", ...(opens.length && { opens }), ...(notes.length && { notes }) });+ if (held.length) push(s, { role: "notice", tone: "info", text: `Waiting for you: ${[...new Set(held)].join("; ")}. Auto-run only starts what fits the cap.` });offlineNote();s.pending = { approvalItemId: item.id, results, gated, order };s.thread.status = "waiting";@@ -1211,6 +1303,7 @@ function refreshFlags(s: State): void {function errorText(e: unknown): string {if (e instanceof Anthropic.AuthenticationError) return "Your Anthropic API key was rejected. Check it in Settings → API keys.";if (e instanceof Anthropic.RateLimitError) return "Claude is rate-limited right now. Try again in a minute.";+ if (e instanceof Anthropic.BadRequestError && /\bmcp\b|connector/i.test(e.message)) return `A connector didn't work: ${e.message}. Check it in Settings → Assist connectors, or switch it off.`;if (e instanceof Anthropic.APIError) return `Claude returned an error (${e.status ?? "network"}): ${e.message}`;if (e instanceof DOMException && e.name === "TimeoutError") return "The model took too long to answer. Try again, or pick a smaller model.";return (e as Error).message || "Something went wrong";@@ -1229,7 +1322,8 @@ export function addMessage(id: string, text: string, attachments: string[] = [])const titles = slash.skills.map((n) => getSkill(n)?.title ?? n);// With only "/katana" (and files), the model still needs words to act on.const words = slash.text || (slash.skills.length ? `Use the ${titles.join(" and ")} skill${titles.length > 1 ? "s" : ""}${attachments.length ? " with the attached files" : ""}.` : text);- if (!s.thread.items.some((i) => i.role === "user")) s.thread.title = threadTitle(slash.text || titles.join(", ") || text);+ // The first message names the chat, unless it was started with a name (a scheduled run's).+ if (!s.thread.items.some((i) => i.role === "user") && s.thread.title === "New chat") s.thread.title = threadTitle(slash.text || titles.join(", ") || text);// Tool results first: they answer the assistant's last turn.const results = s.pending ? decline(s, "The user replied with new instructions instead of approving; follow them.") : [];if (!results.length) closeDanglingToolUses(s.messages);diff --git a/src/server/assist/connectors.ts b/src/server/assist/connectors.tsnew file mode 100644index 00000000..ca5fe435--- /dev/null+++ b/src/server/assist/connectors.ts@@ -0,0 +1,216 @@+import "server-only";+import type Anthropic from "@anthropic-ai/sdk";+import { nanoid } from "nanoid";+import {+ checkConnectorUrl,+ cleanToken,+ connectorSlug,+ maskConnectorUrl,+ MAX_CONNECTOR_NAME,+ MAX_CONNECTOR_TOKEN,+ MAX_CONNECTORS,+ type ConnectorView,+} from "@/lib/assist-connectors";+import { db } from "../db";+import { mask } from "../settings";++/**+ * Custom MCP connectors (Settings → Assist → Connectors). Claude chats get every enabled one through+ * the Messages API's MCP connector: `mcp_servers` names each server (URL and token), and an+ * `mcp_toolset` in `tools` turns its tools on (beta `mcp-client-2025-11-20`). Anthropic's servers+ * connect to the URL, never Fuobe's. Tokens are secrets like the API keys in Settings: kept in+ * SQLite, masked in everything the browser gets.+ */++/** The MCP connector beta the request names (both halves — servers and toolsets — need it). */+export const MCP_BETA = "mcp-client-2025-11-20";++export class ConnectorError extends Error {+ constructor(+ message: string,+ readonly status = 400,+ ) {+ super(message);+ }+}++interface Row {+ id: string;+ name: string;+ slug: string;+ url: string;+ token: string | null;+ enabled: number;+ created_at: number;+ updated_at: number;+}++/** A connector with its secret, for the request to Claude only. */+export interface Connector {+ id: string;+ name: string;+ slug: string;+ url: string;+ token: string | null;+ enabled: boolean;+}++const allowPrivate = () => process.env.FUOBE_ALLOW_PRIVATE_URLS === "1";++const toConnector = (r: Row): Connector => ({ id: r.id, name: r.name, slug: r.slug, url: r.url, token: r.token, enabled: !!r.enabled });++function toView(r: Row): ConnectorView {+ const check = checkConnectorUrl(r.url, allowPrivate());+ return {+ id: r.id,+ name: r.name,+ slug: r.slug,+ url: maskConnectorUrl(r.url),+ enabled: !!r.enabled,+ hasToken: !!r.token,+ token: r.token ? mask(r.token) : "",+ ...("warning" in check && check.warning && { warning: check.warning }),+ ...("error" in check && { warning: check.error }),+ createdAt: r.created_at,+ updatedAt: r.updated_at,+ };+}++const rows = () => db().prepare("SELECT * FROM assist_connectors ORDER BY created_at").all() as Row[];++/** Every connector, as the browser may see them. */+export function listConnectors(): ConnectorView[] {+ return rows().map(toView);+}++/** The enabled connectors, with their tokens (the Claude request only). */+export function activeConnectors(): Connector[] {+ return rows()+ .filter((r) => r.enabled && "url" in checkConnectorUrl(r.url, allowPrivate()))+ .slice(0, MAX_CONNECTORS)+ .map(toConnector);+}++export interface ConnectorInput {+ name?: string;+ url?: string;+ /** A new token; "" removes it; undefined keeps the saved one. */+ token?: string;+ enabled?: boolean;+}++function cleanName(name: string): string {+ const n = name.trim().replace(/\s+/g, " ");+ if (!n) throw new ConnectorError("Give the connector a name");+ if (n.length > MAX_CONNECTOR_NAME) throw new ConnectorError(`Keep the name under ${MAX_CONNECTOR_NAME} characters`);+ return n;+}++function cleanUrl(url: string): string {+ const c = checkConnectorUrl(url, allowPrivate());+ if ("error" in c) throw new ConnectorError(c.error);+ return c.url;+}++function cleanSecret(token: string): string | null {+ const t = cleanToken(token);+ if (t.length > MAX_CONNECTOR_TOKEN) throw new ConnectorError("That token is too long");+ if (/\s/.test(t)) throw new ConnectorError("Paste only the token — no spaces or line breaks");+ return t || null;+}++export function createConnector(input: ConnectorInput, now = Date.now()): ConnectorView {+ const existing = rows();+ if (existing.length >= MAX_CONNECTORS) throw new ConnectorError(`You can add up to ${MAX_CONNECTORS} connectors`);+ const name = cleanName(input.name ?? "");+ const url = cleanUrl(input.url ?? "");+ if (existing.some((r) => r.url === url)) throw new ConnectorError("That URL is already a connector");+ const row: Row = {+ id: nanoid(10),+ name,+ slug: connectorSlug(name, existing.map((r) => r.slug)),+ url,+ token: input.token ? cleanSecret(input.token) : null,+ enabled: input.enabled === false ? 0 : 1,+ created_at: now,+ updated_at: now,+ };+ db()+ .prepare("INSERT INTO assist_connectors (id, name, slug, url, token, enabled, created_at, updated_at) VALUES (@id, @name, @slug, @url, @token, @enabled, @created_at, @updated_at)")+ .run(row);+ return toView(row);+}++/** Rename, move, replace or remove the token, switch on or off. The name Claude sees (slug) stays. */+export function updateConnector(id: string, input: ConnectorInput): ConnectorView | null {+ const r = db().prepare("SELECT * FROM assist_connectors WHERE id = ?").get(id) as Row | undefined;+ if (!r) return null;+ const next: Row = { ...r, updated_at: Date.now() };+ if (input.name !== undefined) next.name = cleanName(input.name);+ if (input.url !== undefined) {+ next.url = cleanUrl(input.url);+ if (next.url !== r.url && rows().some((x) => x.id !== id && x.url === next.url)) throw new ConnectorError("That URL is already a connector");+ }+ if (input.token !== undefined) next.token = input.token === "" ? null : cleanSecret(input.token);+ if (input.enabled !== undefined) next.enabled = input.enabled ? 1 : 0;+ db().prepare("UPDATE assist_connectors SET name = @name, url = @url, token = @token, enabled = @enabled, updated_at = @updated_at WHERE id = @id").run(next);+ return toView(next);+}++export function deleteConnector(id: string): boolean {+ return db().prepare("DELETE FROM assist_connectors WHERE id = ?").run(id).changes > 0;+}++/** The display name of a connector Claude called by its slug (the chat shows this). */+export function connectorName(slug: string): string {+ return (db().prepare("SELECT name FROM assist_connectors WHERE slug = ?").get(slug) as { name: string } | undefined)?.name ?? slug;+}++// ---------------------------------------------------------------------------+// The Messages API request++export interface McpParams {+ mcp_servers: Anthropic.Beta.BetaRequestMCPServerURLDefinition[];+ toolsets: Anthropic.Beta.BetaMCPToolset[];+}++/** The request's MCP fields for these connectors: one server and one toolset each, joined by the slug. */+export function mcpParams(list: Connector[]): McpParams | null {+ if (!list.length) return null;+ return {+ mcp_servers: list.map((c) => ({ type: "url", url: c.url, name: c.slug, ...(c.token && { authorization_token: c.token }) })),+ toolsets: list.map((c) => ({ type: "mcp_toolset", mcp_server_name: c.slug })),+ };+}++type Msg = Anthropic.Beta.BetaMessageParam;++/**+ * History blocks from a connector the request no longer names (deleted or switched off) become+ * plain text in the request, so the conversation stays valid; the stored history keeps them.+ */+export function withoutMissingServers(messages: Msg[], servers: Set<string>): Msg[] {+ const gone = new Map<string, string>();+ for (const m of messages) {+ if (m.role !== "assistant" || typeof m.content === "string") continue;+ for (const b of m.content) if (b.type === "mcp_tool_use" && !servers.has(b.server_name)) gone.set(b.id, `${b.server_name} · ${b.name}`);+ }+ if (!gone.size) return messages;+ return messages.map((m) => {+ if (typeof m.content === "string") return m;+ let changed = false;+ const content = m.content.map((b) => {+ if (b.type === "mcp_tool_use" && gone.has(b.id)) {+ changed = true;+ return { type: "text" as const, text: `[Used ${gone.get(b.id)} — that connector is no longer available]` };+ }+ if (b.type === "mcp_tool_result" && gone.has(b.tool_use_id)) {+ changed = true;+ const body = typeof b.content === "string" ? b.content : (b.content ?? []).map((t) => t.text).join("\n");+ return { type: "text" as const, text: `[${b.is_error ? "Error" : "Result"}: ${body.slice(0, 4000)}]` };+ }+ return b;+ });+ return changed ? ({ ...m, content } as Msg) : m;+ });+}diff --git a/src/server/assist/context.ts b/src/server/assist/context.tsindex 6af1731a..c1a8da00 100644--- a/src/server/assist/context.ts+++ b/src/server/assist/context.ts@@ -1,6 +1,8 @@import "server-only";import type { AssistMemory, ContextFact, Skill } from "@/lib/assist";+import { describeRule, zoneLabel, type ScheduleRule } from "@/lib/assist-schedule";import type { Engine } from "@/lib/catalog/types";+import { db } from "../db";import { engineMode } from "../settings";import { enabledSkills, getSkill } from "../skills";import { memoriesFor } from "./memory";@@ -26,6 +28,10 @@ export interface ChatInfo {projectId: string | null;/** Loaded skills. */skills: string[];+ /** Auto-run's cost cap in USD (a scheduled run's). */+ capUsd?: number | null;+ /** The scheduled task that started the chat. */+ scheduleId?: string | null;}export function engineLine(engine: Engine): string {@@ -39,11 +45,21 @@ export function engineLine(engine: Engine): string {: "The user prefers paid cloud models (best quality); open-source models are available too.";}-export const approvalLine = (autoApprove: boolean) =>+export const approvalLine = (autoApprove: boolean, capUsd: number | null = null) =>autoApprove- ? "Auto-run is on: generations start without an approval card, so keep plans within what the user asked for. Memories you save are kept straight away."+ ? capUsd !== null+ ? `Auto-run is on up to $${capUsd.toFixed(2)} for this chat: generations within it start without an approval card; a plan that would pass it, or whose price isn't known, waits for the user's approval. Keep plans within what the user asked for.`+ : "Auto-run is on: generations start without an approval card, so keep plans within what the user asked for. Memories you save are kept straight away.": "Ask-first is on: each generate call (and each memory you save) shows an approval card.";+/** The line a scheduled run's context gets: nobody is watching, so the job is done end to end. */+function scheduleLine(id: string): string | null {+ const r = db().prepare("SELECT title, rule_json, tz FROM assist_schedules WHERE id = ?").get(id) as { title: string; rule_json: string; tz: string } | undefined;+ if (!r) return null;+ const when = `${describeRule(JSON.parse(r.rule_json) as ScheduleRule)}, ${zoneLabel(r.tz)}`;+ return `This chat is a scheduled run of the task “${r.title}” (${when}). Nobody is watching it live: don't ask questions — make sensible choices, do the whole job, and end with a short summary of what you made.`;+}+/** A project's own skills that still exist (a deleted or renamed one drops out). */function projectSkills(project: { skills: string[] } | null): Skill[] {return project?.skills.map((n) => getSkill(n)).filter((s): s is Skill => !!s) ?? [];@@ -67,8 +83,10 @@ export function chatFacts(c: ChatInfo, now = new Date()): ContextFact[] {const facts: ContextFact[] = [{ section: "now", key: "date", text: `Today is ${now.toISOString().slice(0, 10)}.` },{ section: "now", key: "engine", text: engineLine(c.engine) },- { section: "now", key: "approval", text: approvalLine(c.autoApprove) },+ { section: "now", key: "approval", text: approvalLine(c.autoApprove, c.capUsd ?? null) },];+ const scheduled = c.scheduleId ? scheduleLine(c.scheduleId) : null;+ if (scheduled) facts.push({ section: "now", key: "scheduled", text: scheduled });const project = c.projectId ? getProject(c.projectId) : null;if (project) {facts.push({diff --git a/src/server/assist/projects.ts b/src/server/assist/projects.tsindex 7b1cd29c..a92cf903 100644--- a/src/server/assist/projects.ts+++ b/src/server/assist/projects.ts@@ -146,6 +146,10 @@ export function deleteProject(id: string): boolean {db().prepare("DELETE FROM assist_project_sources WHERE project_id = ?").run(id);deleteProjectMemories(id);db().prepare("UPDATE assist_thread_state SET project_id = NULL WHERE project_id = ?").run(id);+ // Its scheduled tasks move out with the chats, paused: they were written for the project's brief.+ db()+ .prepare("UPDATE assist_schedules SET project_id = NULL, paused = 1, last_status = 'failed', last_text = 'Paused: its project was deleted', updated_at = ? WHERE project_id = ?")+ .run(Date.now(), id);return db().prepare("DELETE FROM assist_projects WHERE id = ?").run(id).changes;})();return n > 0;diff --git a/src/server/assist/schedules.ts b/src/server/assist/schedules.tsnew file mode 100644index 00000000..aee3f2c9--- /dev/null+++ b/src/server/assist/schedules.ts@@ -0,0 +1,338 @@+import "server-only";+import { nanoid } from "nanoid";+import { threadTitle, type AssistItem, type AssistModeChoice } from "@/lib/assist";+import {+ DEFAULT_SCHEDULE_CAP_USD,+ describeRule,+ formatWhen,+ nextRun,+ ruleError,+ validTimeZone,+ type ScheduleApproval,+ type ScheduleResult,+ type ScheduleRule,+ type ScheduleView,+} from "@/lib/assist-schedule";+import { formatCost } from "@/lib/format";+import { db } from "../db";+import { addMessage, createThread, getThread, resolveMode, run, type ModelCall } from "./agent";+import { getProject } from "./projects";++/**+ * Assist's scheduled tasks. A task is a prompt with a rule (daily, weekly, every N hours, once) in a+ * time zone; each run is a new chat (in the task's project, when it has one) that the server's sweep+ * starts — `ensureScheduleRunner()`, started at boot by src/instrumentation.ts, checks every 30 s.+ *+ * Approval per task: "ask" runs the chat until its first plan, which then waits as an approval card+ * (nothing is spent until the user approves); "auto" lets plans start on their own while they fit the+ * task's cost cap for that run, and leaves the rest waiting (see withinCap and the agent's step()).+ * A run the server missed (it was off) happens once when it's back, not once per missed time.+ */++export class ScheduleError extends Error {+ constructor(+ message: string,+ readonly status = 400,+ ) {+ super(message);+ }+}++const SWEEP_MS = 30_000;+/** At most this many tasks start in one sweep; the rest start on the next. */+const PER_SWEEP = 10;++interface Row {+ id: string;+ title: string;+ prompt: string;+ attachments_json: string;+ project_id: string | null;+ rule_json: string;+ tz: string;+ approval: ScheduleApproval;+ cap_usd: number | null;+ engine: "cloud" | "open";+ mode_json: string | null;+ paused: number;+ next_run_at: number | null;+ last_run_at: number | null;+ last_thread_id: string | null;+ last_status: ScheduleResult["status"] | null;+ last_text: string | null;+ runs: number;+ created_at: number;+ updated_at: number;+}++/** A rule as the dialog sends it: "every N hours" gets its start (`from`) here. */+export type RuleInput = ScheduleRule extends infer R ? (R extends { kind: "hours" } ? Omit<R, "from"> & { from?: number } : R) : never;++export interface ScheduleInput {+ title: string;+ prompt: string;+ attachments?: string[];+ projectId?: string | null;+ rule: RuleInput;+ tz: string;+ approval: ScheduleApproval;+ capUsd?: number | null;+ engine: "cloud" | "open";+ mode?: AssistModeChoice | null;+ paused?: boolean;+}++const getRow = (id: string) => db().prepare("SELECT * FROM assist_schedules WHERE id = ?").get(id) as Row | undefined;++/** How a run's chat went, read from the chat itself (so an approval given later shows). */+function resultOf(r: Row): ScheduleResult | null {+ if (!r.last_status) return null;+ const stored: ScheduleResult = { threadId: r.last_thread_id, status: r.last_status, text: r.last_text ?? "" };+ if (r.last_status === "skipped" || !r.last_thread_id) return stored;+ const view = getThread(r.last_thread_id);+ if (!view) return { ...stored, threadId: null, text: stored.status === "running" ? "Its chat was deleted" : stored.text };+ return { threadId: r.last_thread_id, ...summarize(view.thread.status, view.thread.items) };+}++/** A chat's outcome in a few words: still going, a plan waiting, an error, or what it made. */+export function summarize(status: "idle" | "running" | "waiting", items: AssistItem[]): Omit<ScheduleResult, "threadId"> {+ if (status === "running") return { status: "running", text: "Working…" };+ if (status === "waiting") {+ const card = items.findLast((i) => i.role === "approval");+ const price = card?.role === "approval" ? (card.totalUsd === null ? "" : ` (${card.totalUsd === 0 ? "free" : formatCost(card.totalUsd)})`) : "";+ return { status: "waiting", text: `A plan waits for your approval${price}` };+ }+ const lastUser = items.findLastIndex((i) => i.role === "user");+ const after = items.slice(lastUser + 1);+ const error = after.findLast((i) => i.role === "notice" && i.tone === "error");+ if (error?.role === "notice" && !after.slice(after.indexOf(error) + 1).some((i) => i.role === "assistant")) return { status: "failed", text: error.text };+ const made = items.reduce((n, i) => n + (i.role === "generations" ? i.ids.length : 0), 0);+ const said = after.findLast((i) => i.role === "assistant");+ const text = made ? `Started ${made} result${made === 1 ? "" : "s"}` : said?.role === "assistant" ? said.text.replace(/\s+/g, " ").slice(0, 140) : "Finished";+ return { status: "done", text };+}++function toView(r: Row): ScheduleView {+ return {+ id: r.id,+ title: r.title,+ prompt: r.prompt,+ attachments: JSON.parse(r.attachments_json) as string[],+ projectId: r.project_id,+ rule: JSON.parse(r.rule_json) as ScheduleRule,+ tz: r.tz,+ approval: r.approval,+ capUsd: r.cap_usd,+ engine: r.engine,+ mode: r.mode_json ? (JSON.parse(r.mode_json) as ScheduleView["mode"]) : null,+ paused: !!r.paused,+ nextRunAt: r.paused ? null : r.next_run_at,+ lastRunAt: r.last_run_at,+ last: resultOf(r),+ runs: r.runs,+ createdAt: r.created_at,+ updatedAt: r.updated_at,+ };+}++/** Tasks, soonest first (paused ones last). `project`: one project's; null: those outside projects. */+export function listSchedules(f: { project?: string | null } = {}): ScheduleView[] {+ const where = f.project === null ? "WHERE project_id IS NULL" : f.project ? "WHERE project_id = ?" : "";+ const rows = db()+ .prepare(`SELECT * FROM assist_schedules ${where} ORDER BY paused, next_run_at IS NULL, next_run_at, created_at DESC LIMIT 200`)+ .all(...(f.project ? [f.project] : [])) as Row[];+ return rows.map(toView);+}++export function getSchedule(id: string): ScheduleView | null {+ const r = getRow(id);+ return r ? toView(r) : null;+}++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 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 =+ input.rule.kind === "hours"+ ? { kind: "hours", every: input.rule.every, from: before?.kind === "hours" && before.every === input.rule.every ? before.from : (input.rule.from ?? now) }+ : (input.rule as ScheduleRule);+ const bad = ruleError(rule);+ if (bad) throw new ScheduleError(bad);+ const paused = input.paused ?? !!prev?.paused;+ const next = nextRun(rule, input.tz, now);+ if (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 ?? []),+ project_id: input.projectId ?? null,+ rule_json: JSON.stringify(rule),+ tz: input.tz,+ approval: input.approval,+ cap_usd: cap === null ? null : Math.round(cap * 100) / 100,+ engine: input.engine,+ mode_json: input.mode ? JSON.stringify(input.mode) : null,+ paused: paused ? 1 : 0,+ next_run_at: next,+ updated_at: now,+ };+}++export function createSchedule(input: ScheduleInput, now = Date.now()): ScheduleView {+ const 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, engine, mode_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, @engine, @mode_json, @paused, @next_run_at,+ @last_run_at, @last_thread_id, @last_status, @last_text, @runs, @created_at, @updated_at)`,+ )+ .run(row);+ ensureScheduleRunner();+ return toView(row);+}++/** Edit any part; pausing keeps the task, resuming picks the next time from now. */+export function updateSchedule(id: string, patch: Partial<ScheduleInput>, now = Date.now()): ScheduleView | null {+ const r = getRow(id);+ if (!r) return null;+ const current = toView(r);+ const merged: ScheduleInput = {+ title: patch.title ?? current.title,+ prompt: patch.prompt ?? current.prompt,+ attachments: patch.attachments ?? current.attachments,+ projectId: patch.projectId !== undefined ? patch.projectId : current.projectId,+ rule: patch.rule ?? current.rule,+ tz: patch.tz ?? current.tz,+ approval: patch.approval ?? current.approval,+ capUsd: patch.capUsd !== undefined ? patch.capUsd : current.capUsd,+ engine: patch.engine ?? current.engine,+ mode: patch.mode !== undefined ? patch.mode : (current.mode as AssistModeChoice | null),+ 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, engine = @engine, mode_json = @mode_json, paused = @paused, next_run_at = @next_run_at,+ updated_at = @updated_at WHERE id = @id`,+ )+ .run(next);+ return toView(next);+}++/** Delete the task; the chats its runs made stay. */+export function deleteSchedule(id: string): boolean {+ return db().prepare("DELETE FROM assist_schedules WHERE id = ?").run(id).changes > 0;+}++function record(id: string, fields: Partial<Pick<Row, "last_run_at" | "last_thread_id" | "last_status" | "last_text" | "paused">> & { addRun?: boolean }): void {+ const { addRun, ...set } = fields;+ const cols = Object.keys(set).map((k) => `${k} = @${k}`);+ if (addRun) cols.push("runs = runs + 1");+ db()+ .prepare(`UPDATE assist_schedules SET ${cols.join(", ")} WHERE id = @id`)+ .run({ id, ...set });+}++/**+ * Start one run of a task: a new chat with the task's prompt, in its project, on its engine and mode,+ * asking first or auto-running within its cap. Resolves once the chat exists (`threadId`); `done`+ * settles when the agent stops (a finished reply, or a plan waiting for approval).+ */+export async function startSchedule(id: string, o: { now?: number; model?: ModelCall } = {}): Promise<{ threadId: string | null; done: Promise<void> }> {+ const now = o.now ?? Date.now();+ const r = getRow(id);+ if (!r) throw new ScheduleError("No such scheduled task", 404);+ const idle = { threadId: null, done: Promise.resolve() };+ const prev = r.last_thread_id ? getThread(r.last_thread_id) : null;+ if (prev?.thread.status === "running") {+ record(id, { last_status: "skipped", last_text: `Skipped at ${formatWhen(now, r.tz)}: the run before was still going` });+ return idle;+ }+ if (r.project_id && !getProject(r.project_id)) {+ record(id, { last_run_at: now, last_status: "failed", last_text: "Its project was deleted — edit the task to pick another", paused: 1 });+ return idle;+ }+ const rule = JSON.parse(r.rule_json) as ScheduleRule;+ const mode = r.mode_json ? (JSON.parse(r.mode_json) as AssistModeChoice) : undefined;+ const m = await resolveMode(mode);+ 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 t = createThread({+ engine: r.engine,+ agent: m.agent,+ autoApprove: r.approval === "auto",+ title: `${r.title} · ${formatWhen(now, r.tz)}`,+ projectId: r.project_id,+ mode: m.mode,+ model: m.model,+ effort: m.effort,+ scheduleId: r.id,+ capUsd: cap,+ note: `Scheduled run of “${r.title}” · ${describeRule(rule)} · ${how}.${m.note ? ` ${m.note}` : ""}`,+ });+ threadId = t.id;+ addMessage(t.id, r.prompt, JSON.parse(r.attachments_json) as string[]);+ } catch (e) {+ record(id, { last_run_at: now, last_status: "failed", last_text: (e as Error).message, addRun: true });+ return idle;+ }+ record(id, { last_run_at: now, last_thread_id: threadId, last_status: "running", last_text: "Working…", addRun: true });+ const done = run(threadId, o.model)+ .catch((e: Error) => console.warn(`[fuobe] scheduled task ${id} failed: ${e.message}`))+ .finally(() => {+ const view = getThread(threadId);+ if (!view) return;+ const s = summarize(view.thread.status, view.thread.items);+ record(id, { last_status: s.status, last_text: s.text });+ });+ return { threadId, done };+}++/**+ * Start every task that is due at `now`. Each task's next time is claimed first (a compare-and-set+ * on next_run_at), so two sweeps never start the same run. Resolves when the started runs settle.+ */+export async function sweepSchedules(now = Date.now(), o: { model?: ModelCall } = {}): Promise<string[]> {+ const due = db().prepare("SELECT * FROM assist_schedules WHERE paused = 0 AND next_run_at IS NOT NULL AND next_run_at <= ? ORDER BY next_run_at LIMIT ?").all(now, PER_SWEEP) as Row[];+ const started: string[] = [];+ const runs: Promise<void>[] = [];+ for (const r of due) {+ const next = nextRun(JSON.parse(r.rule_json) as ScheduleRule, r.tz, now);+ const claimed = db().prepare("UPDATE assist_schedules SET next_run_at = ? WHERE id = ? AND next_run_at = ? AND paused = 0").run(next, r.id, r.next_run_at).changes;+ if (!claimed) continue;+ const begun = await startSchedule(r.id, { now, model: o.model }).catch((e: Error) => {+ record(r.id, { last_run_at: now, last_status: "failed", last_text: e.message });+ return null;+ });+ if (begun?.threadId) started.push(begun.threadId);+ if (begun) runs.push(begun.done);+ }+ await Promise.all(runs);+ return started;+}++declare global {+ var __fuobeScheduleRunner: { tick: () => void; timer: NodeJS.Timeout } | undefined;+}++const tick = () => void sweepSchedules().catch((e: Error) => console.warn(`[fuobe] schedule sweep failed: ${e.message}`));++/** Start the 30 s sweep (once per process: at boot, and when a task is created). */+export function ensureScheduleRunner(): void {+ const cur = globalThis.__fuobeScheduleRunner;+ if (cur) {+ // After a dev hot reload, point the timer at this module's code.+ cur.tick = tick;+ return;+ }+ const state = { tick, timer: setInterval(() => globalThis.__fuobeScheduleRunner?.tick(), SWEEP_MS) };+ state.timer.unref?.();+ globalThis.__fuobeScheduleRunner = state;+}diff --git a/src/server/assist/schemas.ts b/src/server/assist/schemas.tsindex 05e31362..71ebf5fb 100644--- a/src/server/assist/schemas.ts+++ b/src/server/assist/schemas.ts@@ -1,5 +1,6 @@import { z } from "zod";import { ASSIST_EFFORTS, ASSIST_MODES, MEMORY_CATEGORIES, PROJECT_COLORS } from "@/lib/assist";+import { MAX_SCHEDULE_CAP_USD, MAX_SCHEDULE_HOURS, MAX_SCHEDULE_PROMPT } from "@/lib/assist-schedule";export const AssistMessage = z.object({text: z.string().trim().min(1).max(8000),@@ -31,3 +32,34 @@ export const ProjectBody = z.object({skills: z.array(z.string().max(64)).max(30).optional(),usePersonalMemory: z.boolean().optional(),});++const Time = z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/, "Pick a time");++export const ScheduleRuleSchema = z.discriminatedUnion("kind", [+ z.object({ kind: z.literal("daily"), time: Time }),+ z.object({ kind: z.literal("weekly"), days: z.array(z.number().int().min(0).max(6)).min(1).max(7), time: Time }),+ z.object({ kind: z.literal("hours"), every: z.number().int().min(1).max(MAX_SCHEDULE_HOURS) }),+ 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). */+export const ScheduleBody = z.object({+ title: z.string().trim().min(1).max(80),+ prompt: z.string().trim().min(1).max(MAX_SCHEDULE_PROMPT),+ attachments: z.array(z.string().startsWith("/api/files/")).max(8).optional(),+ projectId: z.string().max(40).nullish(),+ rule: ScheduleRuleSchema,+ tz: z.string().min(1).max(64),+ approval: z.enum(["ask", "auto"]),+ capUsd: z.number().min(0).max(MAX_SCHEDULE_CAP_USD).nullish(),+ engine: z.enum(["cloud", "open"]),+ mode: ModeChoice.nullish(),+ paused: z.boolean().optional(),+});++export const ConnectorBody = z.object({+ name: z.string().max(200).optional(),+ url: z.string().max(4096).optional(),+ token: z.string().max(8192).optional(),+ enabled: z.boolean().optional(),+});diff --git a/src/server/db.ts b/src/server/db.tsindex e0a6bb5d..d9c43b46 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -492,6 +492,48 @@ const MIGRATIONS: string[] = [updated_at INTEGER NOT NULL);CREATE INDEX IF NOT EXISTS shares_target ON shares(kind, target_id);`,+ // round 4 (r4/assist-connectors): Assist's scheduled tasks (a prompt, its rule and time zone, ask-first or+ // auto-run within a cost cap, and how the last run went), custom MCP connectors (name, URL, token — a+ // secret, masked before it reaches the browser), and on each chat the task that started it and what+ // that run has spent on its own.+ `CREATE TABLE IF NOT EXISTS assist_schedules (+ id TEXT PRIMARY KEY,+ title TEXT NOT NULL,+ prompt TEXT NOT NULL,+ attachments_json TEXT NOT NULL DEFAULT '[]',+ project_id TEXT,+ rule_json TEXT NOT NULL,+ tz TEXT NOT NULL,+ approval TEXT NOT NULL DEFAULT 'ask',+ cap_usd REAL,+ engine TEXT NOT NULL DEFAULT 'cloud',+ mode_json TEXT,+ paused INTEGER NOT NULL DEFAULT 0,+ next_run_at INTEGER,+ last_run_at INTEGER,+ last_thread_id TEXT,+ last_status TEXT,+ last_text TEXT,+ runs INTEGER NOT NULL DEFAULT 0,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS assist_schedules_due ON assist_schedules(paused, next_run_at);+ CREATE INDEX IF NOT EXISTS assist_schedules_project ON assist_schedules(project_id);+ CREATE TABLE IF NOT EXISTS assist_connectors (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ slug TEXT NOT NULL UNIQUE,+ url TEXT NOT NULL,+ token TEXT,+ enabled INTEGER NOT NULL DEFAULT 1,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ ALTER TABLE assist_thread_state ADD COLUMN schedule_id TEXT;+ ALTER TABLE assist_thread_state ADD COLUMN cap_usd REAL;+ ALTER TABLE assist_thread_state ADD COLUMN spent_usd REAL NOT NULL DEFAULT 0;+ CREATE INDEX IF NOT EXISTS assist_thread_state_schedule ON assist_thread_state(schedule_id);`,];declare global {diff --git a/src/server/generations.ts b/src/server/generations.tsindex cdc166e4..c076ee6d 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -292,6 +292,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" },];/**@@ -319,6 +321,9 @@ export const ASSET_FREE: Record<string, string> = {"shares.tags_json": "words","shares.items_json": "generation ids: a share link shows what still exists and keeps no file alive","lora_mirrors.licence_json": "the licence and civitai permissions a LoRA copy was made under",+ "assist_schedules.rule_json": "when a scheduled task runs",+ "assist_schedules.mode_json": "the Assist mode a scheduled run starts in",+ "assist_connectors.url": "a remote MCP server Claude connects to, never one of ours",};/** The query that finds the rows of one ASSET_REFS table naming a file (@id), except the purged generation's own (@g). */diff --git a/tests/assist-connectors.test.ts b/tests/assist-connectors.test.tsnew file mode 100644index 00000000..1d159d72--- /dev/null+++ b/tests/assist-connectors.test.ts@@ -0,0 +1,258 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, describe, expect, it, vi } from "vitest";+import type Anthropic from "@anthropic-ai/sdk";+import { claudeStream } from "./fixtures/claude-sse";++vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));+vi.setConfig({ testTimeout: 60_000 });+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-conn-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";+process.env.OLLAMA_URL = "http://127.0.0.1:9";+delete process.env.FUOBE_ALLOW_PRIVATE_URLS;++const { setSetting } = await import("@/server/settings");+const agent = await import("@/server/assist/agent");+const connectors = await import("@/server/assist/connectors");+const lib = await import("@/lib/assist-connectors");+const listRoute = await import("@/app/api/assist/connectors/route");+const oneRoute = await import("@/app/api/assist/connectors/[connectorId]/route");++afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++const TOKEN = "sk-live-0123456789abcdef";++describe("connector URLs", () => {+ const check = lib.checkConnectorUrl;+ it("takes https anywhere and http only on this machine", () => {+ expect(check("https://mcp.example.com/mcp")).toEqual({ url: "https://mcp.example.com/mcp" });+ expect(check(" https://mcp.example.com ")).toEqual({ url: "https://mcp.example.com/" });+ expect(check("http://localhost:8787/mcp")).toMatchObject({ url: "http://localhost:8787/mcp", warning: expect.stringMatching(/public tunnel/) });+ expect(check("http://127.0.0.1:3001/mcp")).toMatchObject({ url: "http://127.0.0.1:3001/mcp" });+ expect(check("http://[::1]:3001/mcp")).toMatchObject({ url: "http://[::1]:3001/mcp" });+ expect(check("http://mcp.example.com/mcp")).toEqual({ error: "Use https:// — plain http is only allowed for localhost" });+ expect(check("http://192.168.1.20/mcp")).toEqual({ error: "Use https:// — plain http is only allowed for localhost" });+ });++ it("FUOBE_ALLOW_PRIVATE_URLS=1 allows plain http elsewhere, with a warning", () => {+ expect(check("http://192.168.1.20/mcp", true)).toMatchObject({ url: "http://192.168.1.20/mcp", warning: expect.stringMatching(/public tunnel/) });+ expect(check("http://mcp.example.com/mcp", true)).toMatchObject({ url: "http://mcp.example.com/mcp", warning: expect.stringMatching(/unencrypted/) });+ });++ it("refuses other schemes, credentials in the URL, garbage and very long URLs", () => {+ expect(check("ftp://mcp.example.com")).toEqual({ error: "Connectors use https:// URLs" });+ expect(check("javascript:alert(1)")).toEqual({ error: "Connectors use https:// URLs" });+ expect(check("file:///etc/passwd")).toEqual({ error: "Connectors use https:// URLs" });+ expect(check("https://user:[email protected]/")).toEqual({ error: "Put the token in the token field, not in the URL" });+ expect(check("mcp.example.com")).toEqual({ error: "Enter a full URL, like https://mcp.example.com/mcp" });+ expect(check("")).toEqual({ error: "Enter the connector's URL" });+ expect(check(`https://mcp.example.com/${"a".repeat(2100)}`)).toMatchObject({ error: expect.stringMatching(/too long/) });+ // https to a private address is allowed (Anthropic's servers make the call) but flagged.+ expect(check("https://10.0.0.5/mcp")).toMatchObject({ warning: expect.stringMatching(/public tunnel/) });+ });++ it("masks the query (keys often live there), names connectors and cleans pasted tokens", () => {+ expect(lib.maskConnectorUrl("https://mcp.zapier.com/api/mcp/s/abc?key=SECRET")).toBe("https://mcp.zapier.com/api/mcp/s/abc?••••");+ expect(lib.maskConnectorUrl("https://mcp.example.com/")).toBe("https://mcp.example.com");+ expect(lib.connectorSlug("Notion (work)")).toBe("notion-work");+ expect(lib.connectorSlug("Ünïcode Tööls")).toBe("unicode-tools");+ expect(lib.connectorSlug("Notion", ["notion", "notion-2"])).toBe("notion-3");+ expect(lib.connectorSlug("!!!")).toBe("connector");+ expect(lib.cleanToken("Bearer abc.def")).toBe("abc.def");+ expect(lib.cleanToken("Authorization: Bearer abc")).toBe("abc");+ });+});++describe("connectors in Settings", () => {+ it("keeps the token on the server: every view masks it, and the API never returns it", async () => {+ const c = connectors.createConnector({ name: "Notion", url: "https://mcp.notion.com/mcp?workspace=SECRET", token: `Bearer ${TOKEN}` });+ expect(c).toMatchObject({ name: "Notion", slug: "notion", url: "https://mcp.notion.com/mcp?••••", hasToken: true, enabled: true, token: "sk-l••••cdef" });+ const res = await listRoute.GET();+ const body = await res.text();+ expect(body).not.toContain(TOKEN);+ expect(body).not.toContain("SECRET");+ expect(JSON.parse(body).items).toHaveLength(1);+ // Created through the route: the response is masked too.+ const created = await listRoute.POST(new Request("http://x/api/assist/connectors", { method: "POST", body: JSON.stringify({ name: "Linear", url: "https://mcp.linear.app/mcp", token: "lin_api_SECRETSECRET" }) }));+ expect(created.status).toBe(201);+ const text = await created.text();+ expect(text).not.toContain("lin_api_SECRETSECRET");+ expect(JSON.parse(text)).toMatchObject({ slug: "linear", hasToken: true });+ // The secret is only what the Claude request reads.+ expect(connectors.activeConnectors().map((x) => [x.slug, x.token])).toEqual([+ ["notion", TOKEN],+ ["linear", "lin_api_SECRETSECRET"],+ ]);+ });++ it("validates input, refuses duplicates and caps the list", async () => {+ expect(() => connectors.createConnector({ name: "", url: "https://a.example.com" })).toThrow(/name/);+ expect(() => connectors.createConnector({ name: "Plain", url: "http://a.example.com" })).toThrow(/https/);+ expect(() => connectors.createConnector({ name: "Again", url: "https://mcp.linear.app/mcp" })).toThrow(/already/);+ expect(() => connectors.createConnector({ name: "Spaces", url: "https://b.example.com", token: "two words" })).toThrow(/only the token/);+ const bad = await listRoute.POST(new Request("http://x", { method: "POST", body: JSON.stringify({ name: "x", url: "ftp://x" }) }));+ expect(bad.status).toBe(400);+ expect((await bad.json()).error).toBe("Connectors use https:// URLs");+ });++ it("edits keep the token unless a new one is given; off connectors aren't sent", async () => {+ const [notion] = connectors.listConnectors();+ const ctx = { params: Promise.resolve({ connectorId: notion.id }) };+ const r = await oneRoute.PATCH(new Request("http://x", { method: "PATCH", body: JSON.stringify({ name: "Notion work", enabled: false }) }), ctx);+ expect(await r.json()).toMatchObject({ name: "Notion work", slug: "notion", enabled: false, hasToken: true });+ expect(connectors.activeConnectors().map((x) => x.slug)).toEqual(["linear"]);+ await oneRoute.PATCH(new Request("http://x", { method: "PATCH", body: JSON.stringify({ enabled: true, token: "" }) }), ctx);+ expect(connectors.activeConnectors().find((x) => x.slug === "notion")?.token).toBeNull();+ await oneRoute.PATCH(new Request("http://x", { method: "PATCH", body: JSON.stringify({ token: TOKEN }) }), ctx);+ expect(connectors.activeConnectors().find((x) => x.slug === "notion")?.token).toBe(TOKEN);+ });+});++describe("the Claude request", () => {+ it("builds one mcp_servers entry and one mcp_toolset per connector, joined by name", () => {+ expect(connectors.mcpParams([])).toBeNull();+ expect(+ connectors.mcpParams([+ { id: "a", name: "Notion", slug: "notion", url: "https://mcp.notion.com/mcp", token: TOKEN, enabled: true },+ { id: "b", name: "Docs", slug: "docs", url: "https://docs.example.com/mcp", token: null, enabled: true },+ ]),+ ).toEqual({+ mcp_servers: [+ { type: "url", url: "https://mcp.notion.com/mcp", name: "notion", authorization_token: TOKEN },+ { type: "url", url: "https://docs.example.com/mcp", name: "docs" },+ ],+ toolsets: [+ { type: "mcp_toolset", mcp_server_name: "notion" },+ { type: "mcp_toolset", mcp_server_name: "docs" },+ ],+ });+ });++ it("sends the connectors through the SDK with the MCP beta, and the chat shows the connector tools used", async () => {+ setSetting("anthropicKey", "sk-ant-test");+ const sent: { headers: Headers; body: Record<string, unknown> }[] = [];+ const realFetch = globalThis.fetch;+ let turn = 0;+ globalThis.fetch = (async (_url: string, init: RequestInit) => {+ sent.push({ headers: new Headers(init.headers), body: JSON.parse(String(init.body)) as Record<string, unknown> });+ turn++;+ // First reply: Claude used two Notion tools on Anthropic's side (one failed), then answered.+ return claudeStream(+ turn === 1+ ? {+ content: [+ { type: "mcp_tool_use", id: "mcptoolu_1", name: "search_pages", server_name: "notion", input: { query: "launch plan" } },+ { type: "mcp_tool_result", tool_use_id: "mcptoolu_1", is_error: false, content: [{ type: "text", text: "Launch plan: 3 ads" }] },+ { type: "mcp_tool_use", id: "mcptoolu_2", name: "get_page", server_name: "notion", input: { id: "x" } },+ { type: "mcp_tool_result", tool_use_id: "mcptoolu_2", is_error: true, content: [{ type: "text", text: "not found" }] },+ { type: "text", text: "Your launch plan asks for 3 ads." },+ ],+ stop_reason: "end_turn",+ }+ : { content: [{ type: "text", text: "Done." }], stop_reason: "end_turn" },+ );+ }) as typeof fetch;+ try {+ const r = await agent.resolveMode({ mode: "smart" });+ const t = agent.createThread({ engine: "cloud", agent: r.agent, mode: r.mode, model: r.model, effort: r.effort });+ agent.addMessage(t.id, "What does my launch plan in Notion say?");+ await agent.run(t.id);+ const body = sent[0].body;+ expect(sent[0].headers.get("anthropic-beta")).toContain(connectors.MCP_BETA);+ expect(body.mcp_servers).toEqual([+ { type: "url", url: "https://mcp.notion.com/mcp?workspace=SECRET", name: "notion", authorization_token: TOKEN },+ { type: "url", url: "https://mcp.linear.app/mcp", name: "linear", authorization_token: "lin_api_SECRETSECRET" },+ ]);+ const tools = body.tools as { type?: string; name?: string; mcp_server_name?: string }[];+ expect(tools.filter((x) => x.type === "mcp_toolset")).toEqual([+ { type: "mcp_toolset", mcp_server_name: "notion" },+ { type: "mcp_toolset", mcp_server_name: "linear" },+ ]);+ // Fuobe's own tools are still there, first.+ expect(tools[0].name).toBeTruthy();+ const items = agent.getThread(t.id)!.thread.items;+ expect(items.filter((i) => i.role === "tool")).toMatchObject([+ { text: "Notion work · search_pages", connector: "Notion work" },+ { text: "Notion work · get_page", connector: "Notion work", failed: true },+ ]);+ expect(items.find((i) => i.role === "assistant")).toMatchObject({ text: "Your launch plan asks for 3 ads." });++ // The connector is deleted: the next request doesn't name it, and its history goes as text.+ connectors.deleteConnector(connectors.listConnectors().find((c) => c.slug === "notion")!.id);+ agent.addMessage(t.id, "Thanks");+ await agent.run(t.id);+ const second = sent[1].body;+ expect((second.mcp_servers as { name: string }[]).map((m) => m.name)).toEqual(["linear"]);+ const history = JSON.stringify(second.messages);+ expect(history).not.toContain('"mcp_tool_use"');+ expect(history).toContain("[Used notion · search_pages — that connector is no longer available]");+ // The stored history keeps what Claude returned.+ expect(JSON.stringify(agent.getThread(t.id))).toContain("Your launch plan");+ } finally {+ globalThis.fetch = realFetch;+ setSetting("anthropicKey", "");+ }+ });++ it("no connectors: no MCP fields and no MCP beta", async () => {+ for (const c of connectors.listConnectors()) connectors.updateConnector(c.id, { enabled: false });+ setSetting("anthropicKey", "sk-ant-test");+ const sent: { headers: Headers; body: Record<string, unknown> }[] = [];+ const realFetch = globalThis.fetch;+ globalThis.fetch = (async (_url: string, init: RequestInit) => {+ sent.push({ headers: new Headers(init.headers), body: JSON.parse(String(init.body)) as Record<string, unknown> });+ return claudeStream({ content: [{ type: "text", text: "Hi" }], stop_reason: "end_turn" });+ }) as typeof fetch;+ try {+ const t = agent.createThread({ engine: "cloud", agent: "claude", mode: "smart" });+ agent.addMessage(t.id, "Hi");+ await agent.run(t.id);+ expect(sent[0].body.mcp_servers).toBeUndefined();+ expect(sent[0].headers.get("anthropic-beta")).not.toContain("mcp-client");+ } finally {+ globalThis.fetch = realFetch;+ setSetting("anthropicKey", "");+ for (const c of connectors.listConnectors()) connectors.updateConnector(c.id, { enabled: true });+ }+ });++ it("a chat on Ollama or the offline planner says connectors need Claude, once", async () => {+ const t = agent.createThread({ engine: "cloud", agent: "offline", mode: "free" });+ const notes = () => agent.getThread(t.id)!.thread.items.filter((i) => i.role === "notice" && /Connectors work in Claude chats/.test(i.text));+ expect(notes()).toHaveLength(1);+ expect(notes()[0]).toMatchObject({ text: expect.stringContaining("(Linear)") });+ await agent.updateThread(t.id, { mode: { mode: "free" } });+ expect(notes()).toHaveLength(1);+ // Claude chats don't get it.+ const c = agent.createThread({ engine: "cloud", agent: "claude", mode: "smart" });+ expect(agent.getThread(c.id)!.thread.items).toEqual([]);+ });++ it("history from a connector that's gone becomes text in the request only", () => {+ type Msg = Anthropic.Beta.BetaMessageParam;+ const messages: Msg[] = [+ { role: "user", content: "hi" },+ {+ role: "assistant",+ content: [+ { type: "mcp_tool_use", id: "m1", name: "find", server_name: "old", input: {} },+ { type: "mcp_tool_result", tool_use_id: "m1", is_error: false, content: [{ type: "text", text: "found it" }] },+ { type: "mcp_tool_use", id: "m2", name: "list", server_name: "kept", input: {} },+ { type: "text", text: "ok" },+ ],+ },+ ];+ const out = connectors.withoutMissingServers(messages, new Set(["kept"]));+ expect(out[1].content).toEqual([+ { type: "text", text: "[Used old · find — that connector is no longer available]" },+ { type: "text", text: "[Result: found it]" },+ { type: "mcp_tool_use", id: "m2", name: "list", server_name: "kept", input: {} },+ { type: "text", text: "ok" },+ ]);+ expect(messages[1].content).toHaveLength(4);+ expect((messages[1].content as { type: string }[])[0].type).toBe("mcp_tool_use");+ expect(connectors.withoutMissingServers(messages, new Set(["old", "kept"]))).toBe(messages);+ });+});diff --git a/tests/assist-schedule.test.ts b/tests/assist-schedule.test.tsnew file mode 100644index 00000000..78443396--- /dev/null+++ b/tests/assist-schedule.test.ts@@ -0,0 +1,162 @@+import { describe, expect, it } from "vitest";+import {+ describeRule,+ formatWhen,+ nextRun,+ ruleError,+ spendOf,+ untilText,+ validTimeZone,+ wallClock,+ withinCap,+ zonedToUtc,+ type ScheduleRule,+} from "@/lib/assist-schedule";++const iso = (ms: number | null) => (ms === null ? null : new Date(ms).toISOString());+const at = (s: string) => Date.parse(s);+const NY = "America/New_York";+const BERLIN = "Europe/Berlin";++describe("zonedToUtc", () => {+ it("reads a wall-clock time in a zone, both sides of a clock change", () => {+ expect(iso(zonedToUtc(2026, 7, 1, 9, 0, BERLIN))).toBe("2026-07-01T07:00:00.000Z");+ expect(iso(zonedToUtc(2026, 12, 1, 9, 0, BERLIN))).toBe("2026-12-01T08:00:00.000Z");+ expect(iso(zonedToUtc(2026, 1, 15, 23, 59, "UTC"))).toBe("2026-01-15T23:59:00.000Z");+ expect(iso(zonedToUtc(2026, 6, 1, 9, 0, "Asia/Kolkata"))).toBe("2026-06-01T03:30:00.000Z");+ });++ it("a time the spring-forward skips lands as much later as the clocks jumped", () => {+ // New York, 8 Mar 2026: 02:00 EST → 03:00 EDT. 02:30 doesn't exist: it's read as 03:30 EDT.+ const t = zonedToUtc(2026, 3, 8, 2, 30, NY);+ expect(iso(t)).toBe("2026-03-08T07:30:00.000Z");+ expect(wallClock(t, NY)).toMatchObject({ h: 3, mi: 30 });+ });++ it("a time the fall-back repeats is its first instant", () => {+ // New York, 1 Nov 2026: 01:30 happens at 05:30Z (EDT) and again at 06:30Z (EST).+ expect(iso(zonedToUtc(2026, 11, 1, 1, 30, NY))).toBe("2026-11-01T05:30:00.000Z");+ // Berlin, 25 Oct 2026: 02:30 happens at 00:30Z (CEST) and 01:30Z (CET).+ expect(iso(zonedToUtc(2026, 10, 25, 2, 30, BERLIN))).toBe("2026-10-25T00:30:00.000Z");+ });+});++describe("nextRun", () => {+ const daily = (time: string): ScheduleRule => ({ kind: "daily", time });++ it("a daily time keeps its wall-clock hour across the autumn change (the UTC hour moves)", () => {+ const rule = daily("09:00");+ const first = nextRun(rule, BERLIN, at("2026-10-23T10:00:00Z"))!;+ expect(iso(first)).toBe("2026-10-24T07:00:00.000Z"); // CEST+ const second = nextRun(rule, BERLIN, first)!;+ expect(iso(second)).toBe("2026-10-25T08:00:00.000Z"); // CET+ expect(wallClock(second, BERLIN)).toMatchObject({ d: 25, h: 9, mi: 0 });+ });++ it("a daily time in the skipped hour runs an hour later that day, then normally", () => {+ const rule = daily("02:30");+ const skipped = nextRun(rule, NY, at("2026-03-07T08:00:00Z"))!;+ expect(iso(skipped)).toBe("2026-03-08T07:30:00.000Z"); // 03:30 EDT+ expect(iso(nextRun(rule, NY, skipped))).toBe("2026-03-09T06:30:00.000Z"); // 02:30 EDT+ });++ it("a daily time in the repeated hour runs once, not twice", () => {+ const rule = daily("01:30");+ const first = nextRun(rule, NY, at("2026-10-31T12:00:00Z"))!;+ expect(iso(first)).toBe("2026-11-01T05:30:00.000Z");+ // From the first run, and from between the two 01:30s, the next is the next day.+ expect(iso(nextRun(rule, NY, first))).toBe("2026-11-02T06:30:00.000Z");+ expect(iso(nextRun(rule, NY, at("2026-11-01T06:00:00Z")))).toBe("2026-11-02T06:30:00.000Z");+ });++ it("strictly after: a run due right now moves to the next day", () => {+ expect(iso(nextRun(daily("09:00"), "UTC", at("2026-10-27T09:00:00Z")))).toBe("2026-10-28T09:00:00.000Z");+ expect(iso(nextRun(daily("09:00"), "UTC", at("2026-10-27T08:59:59Z")))).toBe("2026-10-27T09:00:00.000Z");+ });++ it("weekly picks the next listed weekday, across a month end and a clock change", () => {+ const rule: ScheduleRule = { kind: "weekly", days: [1, 4], time: "18:30" }; // Mondays and Thursdays+ // Tue 27 Oct 2026 → Thu 29 Oct.+ const thu = nextRun(rule, BERLIN, at("2026-10-27T12:00:00Z"))!;+ expect(iso(thu)).toBe("2026-10-29T17:30:00.000Z");+ expect(iso(nextRun(rule, BERLIN, thu))).toBe("2026-11-02T17:30:00.000Z");+ // Sunday only, from the Saturday before Berlin's autumn change.+ expect(iso(nextRun({ kind: "weekly", days: [0], time: "10:00" }, BERLIN, at("2026-10-24T12:00:00Z")))).toBe("2026-10-25T09:00:00.000Z");+ });++ it("every N hours counts real hours from when it was set up, whatever the clocks do", () => {+ const from = at("2026-10-24T22:00:00Z");+ const rule: ScheduleRule = { kind: "hours", every: 6, from };+ expect(iso(nextRun(rule, BERLIN, from - 1000))).toBe("2026-10-25T04:00:00.000Z");+ expect(iso(nextRun(rule, BERLIN, from + 3_600_000))).toBe("2026-10-25T04:00:00.000Z");+ expect(iso(nextRun(rule, BERLIN, at("2026-10-25T04:00:00Z")))).toBe("2026-10-25T10:00:00.000Z");+ // A server that was off for two days: the next slot from now, not the missed ones.+ expect(iso(nextRun(rule, BERLIN, at("2026-10-27T11:00:00Z")))).toBe("2026-10-27T16:00:00.000Z");+ });++ it("once runs at its time and then never again; a past time never runs", () => {+ const rule: ScheduleRule = { kind: "once", at: "2026-11-01T01:30" };+ const t = nextRun(rule, NY, at("2026-10-27T00:00:00Z"));+ expect(iso(t)).toBe("2026-11-01T05:30:00.000Z");+ expect(nextRun(rule, NY, t!)).toBeNull();+ });++ it("a broken rule or an unknown zone never runs", () => {+ expect(nextRun(daily("25:00"), "UTC", 0)).toBeNull();+ expect(nextRun(daily("09:00"), "Mars/Olympus", 0)).toBeNull();+ expect(nextRun({ kind: "weekly", days: [], time: "09:00" }, "UTC", 0)).toBeNull();+ });+});++describe("rules in words", () => {+ it("describes each kind", () => {+ expect(describeRule({ kind: "daily", time: "09:00" })).toBe("Every day at 09:00");+ expect(describeRule({ kind: "weekly", days: [4, 1], time: "18:30" })).toBe("Mondays and Thursdays at 18:30");+ expect(describeRule({ kind: "weekly", days: [1, 2, 3, 4, 5], time: "08:00" })).toBe("Weekdays at 08:00");+ expect(describeRule({ kind: "weekly", days: [6, 0], time: "10:00" })).toBe("Weekends at 10:00");+ expect(describeRule({ kind: "weekly", days: [0, 1, 2, 3, 4, 5, 6], time: "10:00" })).toBe("Every day at 10:00");+ expect(describeRule({ kind: "weekly", days: [0, 3, 5], time: "07:15" })).toBe("Wednesdays, Fridays and Sundays at 07:15");+ expect(describeRule({ kind: "hours", every: 1, from: 0 })).toBe("Every hour");+ expect(describeRule({ kind: "hours", every: 6, from: 0 })).toBe("Every 6 hours");+ expect(describeRule({ kind: "hours", every: 72, from: 0 })).toBe("Every 3 days");+ expect(describeRule({ kind: "once", at: "2026-10-30T14:00" })).toBe("Once, 30 Oct 2026 at 14:00");+ });++ it("says when, in the task's zone, and how long until", () => {+ expect(formatWhen(at("2026-10-25T08:00:00Z"), BERLIN)).toBe("Sun 25 Oct, 09:00");+ const now = at("2026-10-27T09:00:00Z");+ expect(untilText(now + 20_000, now)).toBe("now");+ expect(untilText(now + 25 * 60_000, now)).toBe("in 25 min");+ expect(untilText(now + 5 * 3_600_000, now)).toBe("in 5 h");+ expect(untilText(now + 4 * 86_400_000, now)).toBe("in 4 days");+ });++ it("checks rules and zones", () => {+ expect(ruleError({ kind: "daily", time: "9:00" })).toBe("Pick a time");+ expect(ruleError({ kind: "weekly", days: [7], time: "09:00" })).toBe("Pick at least one day");+ expect(ruleError({ kind: "hours", every: 0, from: 0 })).toMatch(/Every 1 to 168 hours/);+ expect(ruleError({ kind: "once", at: "2026-02-30T10:00" })).toBe("Pick a real date");+ expect(ruleError({ kind: "once", at: "2026-02-28T10:00" })).toBeNull();+ expect(validTimeZone("Europe/Berlin")).toBe(true);+ expect(validTimeZone("Europe/Nowhere")).toBe(false);+ expect(validTimeZone("")).toBe(false);+ });+});++describe("what a scheduled run may start on its own", () => {+ it("fits within the cap, or waits with the reason", () => {+ expect(withinCap(null, 50, 10)).toEqual({ ok: true });+ expect(withinCap(2, 0, 1.5)).toEqual({ ok: true });+ expect(withinCap(2, 1.5, 0.5)).toEqual({ ok: true });+ expect(withinCap(2, 1.5, 0.6)).toEqual({ ok: false, reason: "it costs about $0.60 and this run has $0.50 left of its $2.00 cap" });+ expect(withinCap(2, 0, null)).toEqual({ ok: false, reason: "its price isn't known in advance" });+ expect(withinCap(0, 0, 0)).toEqual({ ok: true });+ });++ it("counts only what really runs: demo jobs are free, broken jobs don't start", () => {+ expect(spendOf([{ costUsd: 0.15, demo: true }])).toBe(0);+ expect(spendOf([{ costUsd: 0.15, demo: false }, { costUsd: 0.5, demo: false }])).toBe(0.65);+ expect(spendOf([{ costUsd: null, demo: false }])).toBeNull();+ expect(spendOf([{ costUsd: null, demo: false, error: "no input" }, { costUsd: 1, demo: false }])).toBe(1);+ });+});diff --git a/tests/assist-schedules.test.ts b/tests/assist-schedules.test.tsnew file mode 100644index 00000000..3c899ad4--- /dev/null+++ b/tests/assist-schedules.test.ts@@ -0,0 +1,219 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";+import type Anthropic from "@anthropic-ai/sdk";++vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));+vi.setConfig({ testTimeout: 60_000 });+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-sched-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";+process.env.OLLAMA_URL = "http://127.0.0.1:9";++const { setSetting } = await import("@/server/settings");+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 { spendOf } = await import("@/lib/assist-schedule");+const listRoute = await import("@/app/api/assist/schedules/route");+const oneRoute = await import("@/app/api/assist/schedules/[scheduleId]/route");++type Block = Anthropic.Beta.BetaContentBlock;+const text = (t: string) => ({ type: "text", text: t, citations: null }) as Block;+const generateCall = (id: string, input: unknown) => ({ type: "tool_use", id, name: "generate", input }) as unknown as Block;+const reply = (content: Block[], stop: Anthropic.Beta.BetaStopReason) => ({ content, stop_reason: stop, stop_details: null }) as Anthropic.Beta.BetaMessage;+const job = (prompt: string) => ({ summary: prompt, jobs: [{ model_id: "nano-banana-pro", prompt }] });++/** A model that makes one generate call per turn listed, then says it's done; it records what it saw. */+function scripted(...prompts: string[]) {+ const seen: { system: string }[] = [];+ let n = 0;+ const call: import("@/server/assist/agent").ModelCall = async ({ system }) => {+ seen.push({ system: system.turn });+ const p = prompts[n++];+ return p ? reply([text("On it."), generateCall(`toolu_${n}`, job(p))], "tool_use") : reply([text("Done — your ad is rendering.")], "end_turn");+ };+ return { call, seen };+}++const T = (s: string) => Date.parse(s);+const base = { prompt: "Make today's perfume ad", tz: "UTC", engine: "cloud" as const, approval: "ask" as const };+const threadOf = (id: string) => agent.getThread(id)!.thread;++beforeAll(() => setSetting("demoMode", "auto"));+afterEach(() => {+ setSetting("falKey", "");+ db().prepare("DELETE FROM assist_schedules").run();+});+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++describe("scheduled tasks", () => {+ it("are checked when saved: the zone, a time that has passed, the project", () => {+ const now = T("2026-10-27T08:00:00Z");+ expect(() => sched.createSchedule({ ...base, title: "x", tz: "Mars/Base", rule: { kind: "daily", time: "09:00" } }, now)).toThrow("Pick a time zone");+ expect(() => sched.createSchedule({ ...base, title: "x", rule: { kind: "once", at: "2026-10-26T09:00" } }, now)).toThrow(/passed/);+ expect(() => sched.createSchedule({ ...base, title: "x", projectId: "nope", rule: { kind: "daily", time: "09:00" } }, now)).toThrow(/project/);+ const s = sched.createSchedule({ ...base, title: "Every 6h", rule: { kind: "hours", every: 6 } }, now);+ expect(s.rule).toEqual({ kind: "hours", every: 6, from: now });+ expect(s.nextRunAt).toBe(now + 6 * 3_600_000);+ // Ask first has no cap; auto gets the default unless one is given.+ expect(s.capUsd).toBeNull();+ expect(sched.createSchedule({ ...base, title: "auto", approval: "auto", rule: { kind: "daily", time: "09:00" } }, now).capUsd).toBe(2);+ // Pausing hides the next run; resuming picks it from now; an unchanged "every N hours" keeps counting from its start.+ const paused = sched.updateSchedule(s.id, { paused: true }, now + 1000)!;+ expect(paused).toMatchObject({ paused: true, nextRunAt: null });+ const resumed = sched.updateSchedule(s.id, { paused: false }, now + 7 * 3_600_000)!;+ expect(resumed.nextRunAt).toBe(now + 12 * 3_600_000);+ expect(sched.updateSchedule(s.id, { rule: { kind: "hours", every: 2 } }, now + 7 * 3_600_000)!.nextRunAt).toBe(now + 9 * 3_600_000);+ });++ it("the routes validate the body and say what's wrong", async () => {+ const bad = await listRoute.POST(new Request("http://x", { method: "POST", body: JSON.stringify({ ...base, title: "x", rule: { kind: "daily", time: "9am" } }) }));+ expect(bad.status).toBe(400);+ expect((await bad.json()).error).toBe("Pick a time");+ const ok = await listRoute.POST(new Request("http://x", { method: "POST", body: JSON.stringify({ ...base, title: "Daily", rule: { kind: "weekly", days: [1, 3], time: "09:00" } }) }));+ expect(ok.status).toBe(201);+ const created = await ok.json();+ expect((await (await listRoute.GET(new Request("http://x/api/assist/schedules?project=none"))).json()).items).toHaveLength(1);+ const ctx = { params: Promise.resolve({ scheduleId: created.id }) };+ expect(await (await oneRoute.PATCH(new Request("http://x", { method: "PATCH", body: JSON.stringify({ paused: true }) }), ctx)).json()).toMatchObject({ paused: true });+ expect((await oneRoute.DELETE(new Request("http://x"), ctx)).status).toBe(204);+ expect((await oneRoute.GET(new Request("http://x"), ctx)).status).toBe(404);+ });+});++describe("the sweep (fake clock)", () => {+ it("starts what's due, once, as a new chat — and moves the task to its next time", async () => {+ const s = sched.createSchedule({ ...base, title: "Perfume ad", rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));+ expect(s.nextRunAt).toBe(T("2026-10-27T09:00:00Z"));+ const m = scripted("A perfume ad");+ expect(await sched.sweepSchedules(T("2026-10-27T08:59:59Z"), { model: m.call })).toEqual([]);+ // Two sweeps at once (a hot reload's second timer): one run.+ const [a, b] = await Promise.all([sched.sweepSchedules(T("2026-10-27T09:00:30Z"), { model: m.call }), sched.sweepSchedules(T("2026-10-27T09:00:30Z"), { model: m.call })]);+ expect([...a, ...b]).toHaveLength(1);+ const view = sched.getSchedule(s.id)!;+ expect(view).toMatchObject({ runs: 1, lastRunAt: T("2026-10-27T09:00:30Z"), nextRunAt: T("2026-10-28T09:00:00Z") });+ const t = threadOf([...a, ...b][0]);+ expect(t).toMatchObject({ title: "Perfume ad · Tue 27 Oct, 09:00", scheduleId: s.id, autoApprove: false });+ expect(t.items[0]).toMatchObject({ role: "notice", text: expect.stringMatching(/^Scheduled run of “Perfume ad” · Every day at 09:00 · plans wait for your approval/) });+ expect(t.items[1]).toMatchObject({ role: "user", text: "Make today's perfume ad" });+ // The model was told nobody is watching.+ expect(m.seen[0].system).toMatch(/scheduled run of the task “Perfume ad” \(Every day at 09:00, UTC/);+ expect(m.seen[0].system).toMatch(/don't ask questions/);+ });++ it("a run the server missed while it was off happens once, then the next time is from now", async () => {+ const s = sched.createSchedule({ ...base, title: "Missed", rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));+ const started = await sched.sweepSchedules(T("2026-10-30T12:00:00Z"), { model: scripted().call });+ expect(started).toHaveLength(1);+ expect(sched.getSchedule(s.id)).toMatchObject({ runs: 1, nextRunAt: T("2026-10-31T09:00:00Z") });+ expect(await sched.sweepSchedules(T("2026-10-30T12:00:01Z"), { model: scripted().call })).toEqual([]);+ });++ it("a one-off runs once, then has no next time; paused tasks don't run", async () => {+ const once = sched.createSchedule({ ...base, title: "Once", rule: { kind: "once", at: "2026-10-27T10:00" } }, T("2026-10-27T08:00:00Z"));+ const paused = sched.createSchedule({ ...base, title: "Paused", paused: true, rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));+ expect(await sched.sweepSchedules(T("2026-10-27T10:00:00Z"), { model: scripted().call })).toHaveLength(1);+ expect(sched.getSchedule(once.id)).toMatchObject({ runs: 1, nextRunAt: null, last: { status: "done", text: "Done — your ad is rendering." } });+ expect(sched.getSchedule(paused.id)).toMatchObject({ runs: 0, paused: true });+ expect(await sched.sweepSchedules(T("2026-10-29T10:00:00Z"), { model: scripted().call })).toEqual([]);+ });++ it("skips a run while the one before is still going", async () => {+ const s = sched.createSchedule({ ...base, title: "Slow", rule: { kind: "hours", every: 1 } }, T("2026-10-27T08:00:00Z"));+ let release!: () => void;+ const slow: import("@/server/assist/agent").ModelCall = () => new Promise((r) => (release = () => r(reply([text("Finally.")], "end_turn"))));+ const first = sched.sweepSchedules(T("2026-10-27T09:00:00Z"), { model: slow });+ await vi.waitFor(() => expect(release).toBeTypeOf("function"));+ expect(await sched.sweepSchedules(T("2026-10-27T10:00:00Z"), { model: scripted().call })).toEqual([]);+ expect(sched.getSchedule(s.id)!.last).toMatchObject({ status: "skipped", text: expect.stringMatching(/the run before was still going/) });+ release();+ await first;+ expect(sched.getSchedule(s.id)).toMatchObject({ runs: 1, last: { status: "done", text: "Finally." } });+ });++ it("a task whose project was deleted pauses and says why", async () => {+ const p = projects.createProject({ name: "Launch" });+ const s = sched.createSchedule({ ...base, title: "In a project", projectId: p.id, rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));+ // Runs inside the project.+ const [id] = await sched.sweepSchedules(T("2026-10-27T09:00:00Z"), { model: scripted().call });+ expect(threadOf(id).projectId).toBe(p.id);+ projects.deleteProject(p.id);+ expect(sched.getSchedule(s.id)).toMatchObject({ projectId: null, paused: true, nextRunAt: null });+ expect(await sched.sweepSchedules(T("2026-10-28T09:00:00Z"), { model: scripted().call })).toEqual([]);+ });+});++describe("approval and the cost cap", () => {+ it("ask first: the plan waits as an approval card, and nothing runs", async () => {+ const s = sched.createSchedule({ ...base, title: "Ask", rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));+ const [id] = await sched.sweepSchedules(T("2026-10-27T09:00:00Z"), { model: scripted("A perfume ad").call });+ const t = threadOf(id);+ expect(t.status).toBe("waiting");+ expect(t.items.filter((i) => i.role === "approval")).toHaveLength(1);+ expect(t.items.some((i) => i.role === "generations")).toBe(false);+ expect(sched.getSchedule(s.id)!.last).toMatchObject({ threadId: id, status: "waiting", text: expect.stringMatching(/^A plan waits for your approval/) });+ // Approving it later shows in the task's last result.+ await agent.answerApproval(id, true);+ await agent.run(id, scripted().call);+ expect(sched.getSchedule(s.id)!.last).toMatchObject({ status: "done", text: "Started 1 result" });+ });++ it("auto-run: a plan within the cap starts on its own (demo runs cost nothing)", async () => {+ const s = sched.createSchedule({ ...base, title: "Auto", approval: "auto", capUsd: 0, rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));+ const [id] = await sched.sweepSchedules(T("2026-10-27T09:00:00Z"), { model: scripted("A perfume ad").call });+ const t = threadOf(id);+ expect(t).toMatchObject({ status: "idle", autoApprove: true, capUsd: 0, spentUsd: 0 });+ expect(t.items.some((i) => i.role === "approval")).toBe(false);+ expect(t.items.filter((i) => i.role === "generations")).toHaveLength(1);+ expect(t.items[0]).toMatchObject({ text: expect.stringMatching(/only free plans run on their own/) });+ expect(sched.getSchedule(s.id)!.last).toMatchObject({ status: "done" });+ });++ it("auto-run: what fits runs and counts against the cap; the plan that would pass it waits, with the reason", async () => {+ setSetting("falKey", "fal-test-key");+ const realFetch = globalThis.fetch;+ // The paid job that fits 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("generate", job("x"), { engine: "cloud" }).jobs)!;+ expect(price).toBeGreaterThan(0);+ const cap = Math.round(price * 1.5 * 100) / 100;+ const s = sched.createSchedule({ ...base, title: "Capped", approval: "auto", capUsd: cap, rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));+ const m = scripted("First ad", "Second ad");+ const [id] = await sched.sweepSchedules(T("2026-10-27T09:00:00Z"), { model: m.call });+ const t = threadOf(id);+ expect(m.seen[0].system).toMatch(new RegExp(`Auto-run is on up to \\$${cap.toFixed(2)}`));+ expect(t).toMatchObject({ status: "waiting", spentUsd: price, capUsd: cap });+ expect(t.items.filter((i) => i.role === "generations")).toHaveLength(1);+ const card = t.items.find((i) => i.role === "approval");+ expect(card).toMatchObject({ status: "pending", summary: "Second ad" });+ const left = (cap - price).toFixed(2);+ expect(t.items.at(-1)).toMatchObject({ role: "notice", text: `Waiting for you: it costs about $${price.toFixed(2)} and this run has $${left} left of its $${cap.toFixed(2)} cap. Auto-run only starts what fits the cap.` });+ expect(sched.getSchedule(s.id)!.last).toMatchObject({ status: "waiting" });+ } finally {+ globalThis.fetch = realFetch;+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();+ }+ });++ it("an ordinary chat with auto-run on has no cap", async () => {+ setSetting("falKey", "fal-test-key");+ const t = agent.createThread({ engine: "cloud", agent: "offline", autoApprove: true });+ expect(threadOf(t.id).capUsd).toBeUndefined();+ const realFetch = globalThis.fetch;+ globalThis.fetch = (async () => new Response("offline", { status: 503 })) as typeof fetch;+ try {+ agent.addMessage(t.id, "go");+ await agent.run(t.id, scripted("One", "Two").call);+ expect(threadOf(t.id).items.filter((i) => i.role === "generations")).toHaveLength(2);+ expect(threadOf(t.id).items.some((i) => i.role === "approval")).toBe(false);+ } finally {+ globalThis.fetch = realFetch;+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();+ }+ });+});diff --git a/tests/fixtures/claude-sse.ts b/tests/fixtures/claude-sse.tsindex f05ecb34..254cb43e 100644--- a/tests/fixtures/claude-sse.ts+++ b/tests/fixtures/claude-sse.ts@@ -1,8 +1,15 @@/*** A Messages API reply as the server-sent events the SDK's stream reads (Assist's Claude calls- * stream and keep the final message). Text and tool_use blocks only.+ * stream and keep the final message). Text, tool_use, and the MCP connector's mcp_tool_use /+ * mcp_tool_result blocks.*/-export function claudeStream(reply: { content: ({ type: "text"; text: string } | { type: "tool_use"; id: string; name: string; input: unknown })[]; stop_reason: string; model?: string }): Response {+type Block =+ | { type: "text"; text: string }+ | { type: "tool_use"; id: string; name: string; input: unknown }+ | { type: "mcp_tool_use"; id: string; name: string; server_name: string; input: unknown }+ | { type: "mcp_tool_result"; tool_use_id: string; is_error: boolean; content: { type: "text"; text: string }[] };++export function claudeStream(reply: { content: Block[]; stop_reason: string; model?: string }): Response {const events: Record<string, unknown>[] = [{type: "message_start",@@ -13,8 +20,10 @@ export function claudeStream(reply: { content: ({ type: "text"; text: string } |if (b.type === "text") {events.push({ type: "content_block_start", index, content_block: { type: "text", text: "", citations: null } });events.push({ type: "content_block_delta", index, delta: { type: "text_delta", text: b.text } });+ } else if (b.type === "mcp_tool_result") {+ events.push({ type: "content_block_start", index, content_block: b });} else {- events.push({ type: "content_block_start", index, content_block: { type: "tool_use", id: b.id, name: b.name, input: {} } });+ events.push({ type: "content_block_start", index, content_block: { ...b, input: {} } });events.push({ type: "content_block_delta", index, delta: { type: "input_json_delta", partial_json: JSON.stringify(b.input) } });}events.push({ type: "content_block_stop", index });