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: connectors only in runs that allow them, allowed tools, honest Scheduled results
Claudebf497ad8c8f4
diff --git a/src/app/api/assist/schedules/[scheduleId]/run/route.ts b/src/app/api/assist/schedules/[scheduleId]/run/route.tsindex 4d54e9c9..208ac82e 100644--- a/src/app/api/assist/schedules/[scheduleId]/run/route.ts+++ b/src/app/api/assist/schedules/[scheduleId]/run/route.ts@@ -1,12 +1,17 @@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. */+/**+ * Run a task now, off schedule: a new chat starts and the agent works in the background (202). No new+ * chat: 409 while the last run is still going; 422 with the reason when the run couldn't start (its+ * project is gone, so the task paused, or the chat failed to start).+ */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 });+ const started = await startSchedule((await ctx.params).scheduleId, { manual: true });+ if (started.threadId === null) return Response.json({ threadId: null, reason: started.reason, error: started.message }, { status: started.reason === "busy" ? 409 : 422 });+ after(() => started.done);+ return Response.json({ threadId: started.threadId }, { status: 202 });} catch (e) {return Response.json({ error: (e as Error).message }, { status: e instanceof ScheduleError ? e.status : 500 });}diff --git a/src/components/assist/connectors-settings.tsx b/src/components/assist/connectors-settings.tsxindex 8808463b..bf61cb6d 100644--- a/src/components/assist/connectors-settings.tsx+++ b/src/components/assist/connectors-settings.tsx@@ -19,7 +19,7 @@ import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import { Skeleton } from "@/components/ui/skeleton";import { Switch } from "@/components/ui/switch";-import { checkConnectorUrl, MAX_CONNECTOR_NAME, MAX_CONNECTORS, type ConnectorView } from "@/lib/assist-connectors";+import { checkConnectorUrl, MAX_CONNECTOR_NAME, MAX_CONNECTORS, parseToolList, type ConnectorView } from "@/lib/assist-connectors";import { useConnectorActions, useConnectors } from "./hooks";/**@@ -38,10 +38,17 @@ export function ConnectorSettings({ claudeReady }: { claudeReady: boolean }) {<div className="space-y-4"><div className="flex items-start gap-2.5 rounded-xl bg-muted px-3 py-2.5 text-[13px] text-muted-foreground"><Info className="mt-0.5 size-4 shrink-0" />- <p>- Connectors work in Claude chats (Smart, or Manual with a Claude model){claudeReady ? "" : " — add an Anthropic API key above first"}. Claude reaches them from Anthropic's servers, so each needs a- public https address. Chats on Ollama or the offline planner can't use them. Tool calls cost Claude tokens; the chat lists each connector tool Claude used.- </p>+ <div className="space-y-1.5">+ <p>+ Connectors work in Claude chats (Smart, or Manual with a Claude model){claudeReady ? "" : " — add an Anthropic API key above first"}. Claude reaches them from Anthropic's servers, so each needs a+ public https address. Chats on Ollama or the offline planner can't use them. Tool calls cost Claude tokens; the chat lists each connector tool Claude used.+ </p>+ <p>+ <span className="font-medium text-foreground">Connector tools run without asking.</span> Claude calls them inside its reply, so approval cards (Ask first) and auto-run's cost cap don't+ cover them; Claude is told to check with you in chat before changing anything. Limit a connector to the tools you trust with <span className="font-medium text-foreground">Allowed tools</span>.+ Scheduled tasks use connectors only when the task says so.+ </p>+ </div></div>{list.isLoading ? (<Skeleton className="h-16 rounded-xl" />@@ -88,6 +95,15 @@ function Row({ c, onEdit }: { c: ConnectorView; onEdit: () => void }) {<KeyRound className="mr-1 inline size-3 align-[-2px]" aria-hidden />{c.hasToken ? <span className="font-mono">{c.token}</span> : "No token"} · Claude sees it as <span className="font-mono">{c.slug}</span></p>+ <p className="text-[11px] break-words text-muted-foreground">+ {c.tools ? (+ <>+ Only: <span className="font-mono">{c.tools.join(", ")}</span>+ </>+ ) : (+ "Every tool it lists"+ )}+ </p>{c.warning && (<p className="mt-1 flex items-start gap-1 text-[11px] text-amber-800 dark:text-amber-300"><AlertTriangle className="mt-px size-3 shrink-0" aria-hidden /> {c.warning}@@ -128,16 +144,19 @@ function Row({ c, onEdit }: { c: ConnectorView; onEdit: () => void }) {/** Add a connector, or edit one: an empty token field keeps the saved token. */function ConnectorForm({ connector, onDone }: { connector?: ConnectorView; onDone: () => void }) {const actions = useConnectorActions();- const ids = { name: useId(), url: useId(), token: useId(), hint: useId() };+ const ids = { name: useId(), url: useId(), token: useId(), hint: useId(), tools: useId(), toolsHint: useId() };const [name, setName] = useState(connector?.name ?? "");const [url, setUrl] = useState("");const [token, setToken] = useState("");+ const [tools, setTools] = useState(connector?.tools?.join(", ") ?? "");const [dropToken, setDropToken] = useState(false);const [busy, setBusy] = useState(false);// The server enforces the http rule (it knows FUOBE_ALLOW_PRIVATE_URLS); here only the shape is checked.const check = url.trim() ? checkConnectorUrl(url, true) : null;const urlError = check && "error" in check ? check.error : null;- const canSave = !!name.trim() && (connector ? !urlError : !!url.trim() && !urlError);+ const toolList = parseToolList(tools);+ const toolsError = "error" in toolList ? toolList.error : null;+ const canSave = !!name.trim() && !toolsError && (connector ? !urlError : !!url.trim() && !urlError);const save = async (e: React.FormEvent) => {e.preventDefault();@@ -149,10 +168,11 @@ function ConnectorForm({ connector, onDone }: { connector?: ConnectorView; onDonname: name.trim(),...(url.trim() && { url: url.trim() }),...(dropToken ? { token: "" } : token.trim() ? { token: token.trim() } : {}),+ tools: tools.trim() || null,});toast.success("Connector saved", { duration: 1500 });} else {- await actions.create({ name: name.trim(), url: url.trim(), ...(token.trim() && { token: token.trim() }) });+ await actions.create({ name: name.trim(), url: url.trim(), ...(token.trim() && { token: token.trim() }), ...(tools.trim() && { tools: tools.trim() }) });toast.success(`${name.trim()} connected`, { description: "Claude chats can use its tools from the next message.", duration: 2500 });}onDone();@@ -216,6 +236,26 @@ function ConnectorForm({ connector, onDone }: { connector?: ConnectorView; onDon</label>)}</div>+ <div className="space-y-1.5">+ <Label htmlFor={ids.tools} className="text-[13px]">+ Allowed tools <span className="font-normal text-muted-foreground">(optional)</span>+ </Label>+ <Input+ id={ids.tools}+ autoComplete="off"+ spellCheck={false}+ value={tools}+ onChange={(e) => setTools(e.target.value)}+ placeholder="Every tool — or only these, e.g. search_pages, get_page"+ aria-invalid={!!toolsError}+ aria-describedby={ids.toolsHint}+ className="font-mono text-[13px]"+ />+ <p id={ids.toolsHint} className={toolsError ? "text-[12px] text-destructive" : "text-[12px] text-muted-foreground"}>+ {toolsError ??+ "Tool names as the server lists them (its docs, or the chat's “Notion · search_pages” lines), separated by commas. Leave it empty to allow every tool; prefer read-only ones for scheduled tasks."}+ </p>+ </div><div className="flex flex-wrap gap-2"><Button type="submit" size="sm" disabled={busy || !canSave}>{busy && <Loader2 className="animate-spin" />} {connector ? "Save" : "Add connector"}diff --git a/src/components/assist/hooks.ts b/src/components/assist/hooks.tsindex d52ab876..2d4e5e92 100644--- a/src/components/assist/hooks.ts+++ b/src/components/assist/hooks.ts@@ -330,6 +330,7 @@ export interface ScheduleForm {capUsd?: number | null;engine: Engine;mode?: AssistModeChoice | null;+ connectors?: boolean;paused?: boolean;}@@ -365,11 +366,13 @@ export function useScheduleActions() {await send(`/api/assist/schedules/${id}`, "DELETE");refresh();},+ /** The new chat's id; null while the last run is still going; throws with the reason when the run couldn't start. */runNow: async (id: string) => {const r = await fetch(`/api/assist/schedules/${id}/run`, { method: "POST" });const body = (await r.json().catch(() => ({}))) as { threadId?: string | null; error?: string };- if (!r.ok && r.status !== 409) throw new Error(body.error ?? `Request failed (${r.status})`);refresh();+ if (r.status === 409) return null;+ if (!r.ok) throw new Error(body.error ?? `Request failed (${r.status})`);return body.threadId ?? null;},};@@ -391,12 +394,12 @@ export function useConnectorActions() {const qc = useQueryClient();const refresh = () => void qc.invalidateQueries({ queryKey: ["assist-connectors"] });return {- create: async (f: { name: string; url: string; token?: string }) => {+ create: async (f: { name: string; url: string; token?: string; tools?: string | null }) => {const c = await send<ConnectorView>("/api/assist/connectors", "POST", f);refresh();return c;},- update: async (id: string, f: { name?: string; url?: string; token?: string; enabled?: boolean }) => {+ update: async (id: string, f: { name?: string; url?: string; token?: string; tools?: string | null; enabled?: boolean }) => {// Optimistic for the on / off switch.if (f.enabled !== undefined) qc.setQueryData<ConnectorView[]>(["assist-connectors"], (old) => old?.map((c) => (c.id === id ? { ...c, enabled: f.enabled! } : c)));try {diff --git a/src/components/assist/schedule-dialog.tsx b/src/components/assist/schedule-dialog.tsxindex 73660a1a..b39ffad0 100644--- a/src/components/assist/schedule-dialog.tsx+++ b/src/components/assist/schedule-dialog.tsx@@ -4,6 +4,7 @@ import { CalendarClock, Loader2, X } from "lucide-react";import { useId, useMemo, useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";+import { Checkbox } from "@/components/ui/checkbox";import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";@@ -32,7 +33,7 @@ import {} from "@/lib/assist-schedule";import type { Engine } from "@/lib/catalog/types";import { cn } from "@/lib/utils";-import { useChats, useProjects, useScheduleActions, type ScheduleRuleInput } from "./hooks";+import { useChats, useConnectors, useProjects, useScheduleActions, type ScheduleRuleInput } from "./hooks";import { ModePicker } from "./mode-picker";import { ProjectDot } from "./project-dot";@@ -108,6 +109,9 @@ function Form({ schedule, seed, onDone }: { schedule?: ScheduleView; seed?: Scheconst [cap, setCap] = useState(String(schedule?.capUsd ?? DEFAULT_SCHEDULE_CAP_USD));const [engine, setEngine] = useState<Engine>(schedule?.engine ?? seed?.engine ?? preferred);const [mode, setMode] = useState<AssistModeChoice | null>((schedule?.mode as AssistModeChoice | null) ?? seed?.mode ?? null);+ // Off unless the task opts in: connector tools run inside Claude's reply, where no approval reaches them.+ const [connectors, setConnectors] = useState(schedule?.connectors ?? false);+ const connectorNames = (useConnectors().data ?? []).filter((c) => c.enabled).map((c) => c.name);const [busy, setBusy] = useState(false);const zones = useMemo(() => {const list = allZones();@@ -142,6 +146,7 @@ function Form({ schedule, seed, onDone }: { schedule?: ScheduleView; seed?: SchecapUsd: approval === "auto" ? capUsd : null,engine,mode,+ connectors,};const s = schedule ? await actions.update(schedule.id, body) : await actions.create(body);toast.success(schedule ? "Schedule saved" : "Scheduled", { description: s.nextRunAt ? `Next run ${formatWhen(s.nextRunAt, s.tz)}` : undefined, duration: 2500 });@@ -340,7 +345,11 @@ function Form({ schedule, seed, onDone }: { schedule?: ScheduleView; seed?: Sche<div role="radiogroup" aria-label="Approval" onKeyDown={radioKeys} className="grid gap-2">{([- { id: "ask", title: "Ask me first", body: "Each run plans the job, then waits in its chat for your OK. Nothing is spent until you approve." },+ {+ id: "ask",+ title: "Ask me first",+ body: "Each run plans the job, then waits in its chat for your OK — nothing is generated until you approve. A run on Claude uses your Anthropic key to plan.",+ },{ id: "auto", title: "Run on its own, within a cap", body: "Plans start without asking while they fit the cap. A plan that would pass it, or has no known price, waits for you." },] as const).map((o) => (@@ -371,6 +380,22 @@ function Form({ schedule, seed, onDone }: { schedule?: ScheduleView; seed?: Sche</div>)}</fieldset>++ {(connectorNames.length > 0 || connectors) && (+ <fieldset className="space-y-2">+ <legend className="text-sm font-medium">Connectors</legend>+ <label className="flex items-start gap-2.5 rounded-xl border px-3.5 py-2.5">+ <Checkbox checked={connectors} onCheckedChange={(v) => setConnectors(v === true)} className="mt-0.5" />+ <span className="min-w-0">+ <span className="block text-[13px] font-medium">Let runs use my connectors{connectorNames.length ? ` (${connectorNames.join(", ")})` : ""}</span>+ <span className="block text-[12px] text-muted-foreground">+ Claude runs only. Their tools run without asking — even with Ask me first — and nobody is watching, so turn this on only for connectors you trust unattended. Settings → Assist · connectors can+ limit each one to some tools.+ </span>+ </span>+ </label>+ </fieldset>+ )}</div><DialogFooter className="mx-0 mb-0 border-t px-5 py-3"><Button type="button" variant="ghost" onClick={onDone}>diff --git a/src/components/assist/scheduled-view.tsx b/src/components/assist/scheduled-view.tsxindex 92b99e89..28aea874 100644--- a/src/components/assist/scheduled-view.tsx+++ b/src/components/assist/scheduled-view.tsx@@ -97,7 +97,7 @@ export function ScheduledView({ projectId }: { projectId?: string } = {}) {<CalendarClock /></EmptyMedia><EmptyTitle>No scheduled tasks yet</EmptyTitle>- <EmptyDescription>Schedule a prompt here, or from any chat's menu. You choose whether each run asks you first.</EmptyDescription>+ <EmptyDescription>Schedule a prompt here, or with the Schedule button in any chat. You choose whether each run asks you first.</EmptyDescription></EmptyHeader><EmptyContent><Button size="sm" onClick={() => setCreating(true)}>@@ -203,7 +203,10 @@ function TaskRow({ s, showProject }: { s: ScheduleView; showProject: boolean })<div className="min-w-0"><dt className="text-muted-foreground">Next run</dt><dd className="font-medium">{s.paused ? "Paused" : s.nextRunAt ? `${formatWhen(s.nextRunAt, s.tz)} (${untilText(s.nextRunAt, now)})` : "None — it ran"}</dd>- <dd className="text-muted-foreground">{s.approval === "ask" ? "Asks before spending" : s.capUsd ? `Runs on its own up to ${formatCost(s.capUsd)} a run` : "Runs free plans on its own"}</dd>+ <dd className="text-muted-foreground">+ {s.approval === "ask" ? "Asks before generating" : s.capUsd ? `Runs on its own up to ${formatCost(s.capUsd)} a run` : "Runs free plans on its own"}+ {s.connectors ? " · uses your connectors" : ""}+ </dd></div><div className="min-w-0"><dt className="text-muted-foreground">diff --git a/src/components/command-palette.tsx b/src/components/command-palette.tsxindex 1f7e22e3..1b6ef782 100644--- a/src/components/command-palette.tsx+++ b/src/components/command-palette.tsx@@ -1,7 +1,7 @@"use client";import { useQuery } from "@tanstack/react-query";-import { Bell, Clapperboard, Cpu, Film, KeyRound, Layers, LayoutGrid, Loader2, Plus, Scale, Server, Settings2, ShieldCheck, Sparkles, Wand2, type LucideIcon } from "lucide-react";+import { Bell, Clapperboard, Cpu, Film, KeyRound, Layers, LayoutGrid, Loader2, Plug, Plus, Scale, Server, Settings2, ShieldCheck, Sparkles, Wand2, type LucideIcon } from "lucide-react";import { useRouter } from "next/navigation";import { createContext, lazy, Suspense, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";import { NAV } from "@/components/nav-items";@@ -59,6 +59,7 @@ const SETTINGS: { id: string; label: string; icon: LucideIcon; keywords: string;href: "/settings/models",},{ id: "text-ai", label: "Prompt enhancement", icon: Sparkles, keywords: "claude ollama enhancer llm" },+ { id: "assist-connectors", label: "Assist connectors", icon: Plug, keywords: "mcp connector claude tools notion linear slack server token" },{ id: "notifications", label: "Notifications", icon: Bell, keywords: "browser done alerts" },{ id: "security", label: "Password and API tokens", icon: ShieldCheck, keywords: "security sign in mcp token" },{ id: "demo", label: "Demo mode", icon: Settings2, keywords: "placeholder free try" },diff --git a/src/instrumentation.ts b/src/instrumentation.tsindex 2e2adc9e..fba1630f 100644--- a/src/instrumentation.ts+++ b/src/instrumentation.ts@@ -12,7 +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).+ // Assist's scheduled tasks: a 30 s sweep starts the runs that are due (a run missed while the server was off happens once, a few seconds after boot).const { ensureScheduleRunner } = await import("./server/assist/schedules");- ensureScheduleRunner();+ ensureScheduleRunner({ soon: true });}diff --git a/src/lib/assist-connectors.ts b/src/lib/assist-connectors.tsindex 76f6535a..7393d746 100644--- a/src/lib/assist-connectors.ts+++ b/src/lib/assist-connectors.ts@@ -1,27 +1,34 @@/*** 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).+ * remote MCP server URL, an optional token and, optionally, the only tools Claude may call on it.+ * 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 parts of the URL that+ * often carry a key: its query and any id-like path segment).+ *+ * Connector tools run inside Claude's reply, on Anthropic's side: Fuobe's approval cards can't stop+ * them. The allow-list is how a user keeps a connector to tools they trust.*/export const MAX_CONNECTORS = 20;export const MAX_CONNECTOR_URL = 2048;export const MAX_CONNECTOR_NAME = 60;export const MAX_CONNECTOR_TOKEN = 4096;+export const MAX_CONNECTOR_TOOLS = 64;-/** A connector as the browser sees it: the token and the URL's query masked. */+/** A connector as the browser sees it: the token and the URL's secret-looking parts 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. */+ /** The URL with its query, fragment and id-like path segments masked. */url: string;enabled: boolean;hasToken: boolean;- /** The token masked ("sk-a••••9f3c"), empty when there's none. */+ /** The token masked ("sk-a••••9f3c", or only its last 2 characters when it's short), empty when there's none. */token: string;+ /** The only tools Claude may call on it; null: every tool the server lists. */+ tools: string[] | null;/** Why Claude may not reach it (a local or private address), shown as a warning. */warning?: string;createdAt: number;@@ -63,17 +70,56 @@ export function checkConnectorUrl(raw: string, allowPrivate = false): { url: strreturn { url: u.toString(), ...(warning && { warning }) };}-/** The URL with its query and fragment masked: many MCP servers put a key there. */+/** A path segment shown as is: a short lowercase word ("api", "mcp", "sse", "servers") or a version ("v1"). */+const PLAIN_SEGMENT = /^(?:[a-z]{1,8}|v\d{1,2})$/;++/**+ * The URL as the browser may show it. Many MCP servers carry a key in the URL — in the query+ * (`?api_key=…`) or as a path segment (Zapier's `/api/mcp/s/<secret>/mcp`) — so the query and fragment+ * become "?••••" and every path segment that isn't a short plain word becomes "…".+ */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 ? "?••••" : ""}`;+ const segments = u.pathname+ .split("/")+ .slice(1)+ .map((s) => (!s || PLAIN_SEGMENT.test(s) ? s : "…"))+ .filter((s, i, all) => !(s === "…" && all[i - 1] === "…"));+ const path = segments.join("/");+ return `${u.origin}${path ? `/${path}` : ""}${hidden ? "?••••" : ""}`;} catch {return "••••";}}+/**+ * A connector token as the browser may show it. MCP tokens are often short, so the usual "first 4 and+ * last 4" would show most of one: under 24 characters only the last 2 show.+ */+export function maskToken(token: string): string {+ if (!token) return "";+ if (token.length >= 24) return `${token.slice(0, 4)}••••${token.slice(-4)}`;+ return token.length > 8 ? `••••${token.slice(-2)}` : "••••";+}++const TOOL_NAME = /^[A-Za-z0-9_.-]{1,128}$/;++/**+ * The tools a connector is limited to, typed as "search_pages, get_page" (commas, spaces or new lines)+ * or sent as a list. Empty: every tool. Names are the server's own (the chat shows them as+ * "Notion · search_pages"); a name the server doesn't have simply matches nothing.+ */+export function parseToolList(input: string | readonly string[] | null | undefined): { tools: string[] | null } | { error: string } {+ const parts = (typeof input === "string" ? input.split(/[\s,]+/) : (input ?? [])).map((t) => t.trim()).filter(Boolean);+ const bad = parts.find((t) => !TOOL_NAME.test(t));+ if (bad) return { error: `“${bad.slice(0, 40)}” isn't a tool name — use the names the server lists, like search_pages` };+ const tools = [...new Set(parts)];+ if (tools.length > MAX_CONNECTOR_TOOLS) return { error: `Allow at most ${MAX_CONNECTOR_TOOLS} tools` };+ return { tools: tools.length ? tools : null };+}+/*** 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).diff --git a/src/lib/assist-schedule.ts b/src/lib/assist-schedule.tsindex f7c7712e..b700a0de 100644--- a/src/lib/assist-schedule.ts+++ b/src/lib/assist-schedule.ts@@ -42,6 +42,8 @@ export interface ScheduleView {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;+ /** Whether runs may use the connectors in Settings (Claude runs only). Their tools run without asking, so it's off unless the task opts in. */+ connectors: boolean;paused: boolean;/** When it runs next (null: paused, or a one-off that has run). */nextRunAt: number | null;diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.tsindex 8c65b2af..3b5967e5 100644--- a/src/server/assist/agent.ts+++ b/src/server/assist/agent.ts@@ -111,6 +111,7 @@ interface StateRow {schedule_id: string | null;cap_usd: number | null;spent_usd: number | null;+ connectors: number | null;}/** Per-chat state beside the transcript (assist_thread_state). */@@ -129,6 +130,8 @@ interface Ext {/** With auto-run on: the most generations may cost without asking (USD), and what they have cost. */capUsd: number | null;spentUsd: number;+ /** Whether Claude gets the custom MCP connectors here (every chat, except a scheduled run whose task leaves them off). */+ connectors: boolean;}interface State {@@ -156,6 +159,7 @@ function loadExt(id: string): Ext {scheduleId: r?.schedule_id ?? null,capUsd: r?.cap_usd ?? null,spentUsd: r?.spent_usd ?? 0,+ connectors: r?.connectors !== 0,};}@@ -230,10 +234,11 @@ function save(s: State): void {});db().prepare(- `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)+ `INSERT INTO assist_thread_state (thread_id, project_id, mode, model, effort, skills_json, context, sent_json, schedule_id, cap_usd, spent_usd, connectors)+ VALUES (@thread_id, @project_id, @mode, @model, @effort, @skills_json, @context, @sent_json, @schedule_id, @cap_usd, @spent_usd, @connectors)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, schedule_id = @schedule_id, cap_usd = @cap_usd, spent_usd = @spent_usd`,+ skills_json = @skills_json, context = @context, sent_json = @sent_json, schedule_id = @schedule_id, cap_usd = @cap_usd, spent_usd = @spent_usd,+ connectors = @connectors`,).run({thread_id: s.thread.id,@@ -247,6 +252,7 @@ function save(s: State): void {schedule_id: s.ext.scheduleId,cap_usd: s.ext.capUsd,spent_usd: s.ext.spentUsd,+ connectors: s.ext.connectors ? 1 : 0,});})();}@@ -444,9 +450,12 @@ 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. */+/** The connectors Claude gets in this chat: none on other agents, or in a scheduled run that leaves them off. */+const chatConnectors = (s: State): Connector[] => (s.thread.agent === "claude" && s.ext.connectors ? activeConnectors() : []);++/** Connectors need Claude: a chat on Ollama or the offline planner (that would otherwise use them) 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;+ if (s.thread.agent === "claude" || !s.ext.connectors || 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.` });@@ -465,6 +474,8 @@ export function createThread(opts: {/** A scheduled run: the task that started it, and auto-run's cost cap for it. */scheduleId?: string | null;capUsd?: number | null;+ /** false: Claude doesn't get the custom MCP connectors here (a scheduled run that leaves them off). */+ connectors?: boolean;/** A quiet line at the top of the chat (a scheduled run says which task it is). */note?: string;}): AssistThread {@@ -485,6 +496,7 @@ export function createThread(opts: {scheduleId: opts.scheduleId ?? null,capUsd: opts.capUsd ?? null,spentUsd: 0,+ connectors: opts.connectors !== false,},};if (opts.note) push(s, { role: "notice", tone: "info", text: opts.note });@@ -600,7 +612,10 @@ export const claude: ModelCall = async ({ system, messages, tools, settings, conconst 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.+ // Custom MCP connectors: Anthropic's servers call them; their tools come after Fuobe's own. Under+ // mcp-client-2025-11-20 each request lists the servers' tools again; a connector switched on, off or+ // deleted mid-chat changes `tools` (and a deleted one's history is rewritten below), so Claude's+ // earlier thinking in that chat is dropped (drop_block) and re-done — a cost, not an error.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@@ -1121,8 +1136,16 @@ function ordered(results: ToolResult[], order: string[]): ToolResult[] {* The chat's system prompt and, when something changed since the model last looked, the* "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, capUsd: s.ext.capUsd, scheduleId: s.ext.scheduleId });+function contextFor(s: State, connectors: Connector[]): { 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,+ capUsd: s.ext.capUsd,+ scheduleId: s.ext.scheduleId,+ connectors: connectors.map((c) => c.name),+ });const sent = factMap(facts);if (!s.ext.context) {s.ext.context = renderContext(facts);@@ -1150,7 +1173,8 @@ function connectorItems(s: State, content: Anthropic.Beta.BetaContentBlock[]): vasync function step(s: State, model: ModelCall): Promise<"continue" | "stop"> {const ctx = toolCtx(s);- const { system, update, sent } = contextFor(s);+ const connectors = chatConnectors(s);+ const { system, update, sent } = contextFor(s, connectors);const active = s.ext.skills.map((n) => getSkill(n)).filter((x): x is NonNullable<typeof x> => !!x);const res = await model({system,@@ -1159,7 +1183,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() }),+ ...(connectors.length && { connectors }),});if (res.stop_reason === "refusal") {diff --git a/src/server/assist/connectors.ts b/src/server/assist/connectors.tsindex ca5fe435..e4ac5975 100644--- a/src/server/assist/connectors.ts+++ b/src/server/assist/connectors.ts@@ -6,20 +6,23 @@ import {cleanToken,connectorSlug,maskConnectorUrl,+ maskToken,MAX_CONNECTOR_NAME,MAX_CONNECTOR_TOKEN,MAX_CONNECTORS,+ parseToolList,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.+ * Custom MCP connectors (Settings → Assist → Connectors). Claude chats that use connectors (every+ * ordinary chat; a scheduled run only when its task allows it) 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 — all of them, or only the connector's allow-list (beta+ * `mcp-client-2025-11-20`). Anthropic's servers connect to the URL and call the tools inside the+ * reply, so Fuobe's approval cards never see those calls. 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). */@@ -40,6 +43,7 @@ interface Row {slug: string;url: string;token: string | null;+ tools_json: string | null;enabled: number;created_at: number;updated_at: number;@@ -52,12 +56,16 @@ export interface Connector {slug: string;url: string;token: string | null;+ /** The only tools Claude may call; null: all of them. */+ tools: 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 });+const toolsOf = (r: Row): string[] | null => (r.tools_json ? (JSON.parse(r.tools_json) as string[]) : null);++const toConnector = (r: Row): Connector => ({ id: r.id, name: r.name, slug: r.slug, url: r.url, token: r.token, tools: toolsOf(r), enabled: !!r.enabled });function toView(r: Row): ConnectorView {const check = checkConnectorUrl(r.url, allowPrivate());@@ -68,7 +76,8 @@ function toView(r: Row): ConnectorView {url: maskConnectorUrl(r.url),enabled: !!r.enabled,hasToken: !!r.token,- token: r.token ? mask(r.token) : "",+ token: r.token ? maskToken(r.token) : "",+ tools: toolsOf(r),...("warning" in check && check.warning && { warning: check.warning }),...("error" in check && { warning: check.error }),createdAt: r.created_at,@@ -96,6 +105,8 @@ export interface ConnectorInput {url?: string;/** A new token; "" removes it; undefined keeps the saved one. */token?: string;+ /** The only tools Claude may call ("a, b" or a list); empty or null: every tool; undefined keeps the saved list. */+ tools?: string | string[] | null;enabled?: boolean;}@@ -119,6 +130,12 @@ function cleanSecret(token: string): string | null {return t || null;}+function cleanTools(tools: string | string[] | null): string | null {+ const c = parseToolList(tools);+ if ("error" in c) throw new ConnectorError(c.error);+ return c.tools ? JSON.stringify(c.tools) : 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`);@@ -131,17 +148,20 @@ export function createConnector(input: ConnectorInput, now = Date.now()): Connecslug: connectorSlug(name, existing.map((r) => r.slug)),url,token: input.token ? cleanSecret(input.token) : null,+ tools_json: input.tools === undefined ? null : cleanTools(input.tools),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)")+ .prepare(+ "INSERT INTO assist_connectors (id, name, slug, url, token, tools_json, enabled, created_at, updated_at) VALUES (@id, @name, @slug, @url, @token, @tools_json, @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. */+/** Rename, move, replace or remove the token, change the allowed tools, 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;@@ -152,8 +172,11 @@ export function updateConnector(id: string, input: ConnectorInput): ConnectorVieif (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.tools !== undefined) next.tools_json = cleanTools(input.tools);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);+ db()+ .prepare("UPDATE assist_connectors SET name = @name, url = @url, token = @token, tools_json = @tools_json, enabled = @enabled, updated_at = @updated_at WHERE id = @id")+ .run(next);return toView(next);}@@ -174,12 +197,19 @@ export interface McpParams {toolsets: Anthropic.Beta.BetaMCPToolset[];}-/** The request's MCP fields for these connectors: one server and one toolset each, joined by the slug. */+/**+ * The request's MCP fields for these connectors: one server and one toolset each, joined by the slug.+ * A connector limited to some tools turns the rest off (`default_config` off, those tools on).+ */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 })),+ toolsets: list.map((c) => ({+ type: "mcp_toolset",+ mcp_server_name: c.slug,+ ...(c.tools?.length && { default_config: { enabled: false }, configs: Object.fromEntries(c.tools.map((t) => [t, { enabled: true }])) }),+ })),};}diff --git a/src/server/assist/context.ts b/src/server/assist/context.tsindex c1a8da00..b90402d3 100644--- a/src/server/assist/context.ts+++ b/src/server/assist/context.ts@@ -32,6 +32,8 @@ export interface ChatInfo {capUsd?: number | null;/** The scheduled task that started the chat. */scheduleId?: string | null;+ /** The custom MCP connectors Claude has in this chat (their names). */+ connectors?: string[];}export function engineLine(engine: Engine): string {@@ -60,6 +62,24 @@ function scheduleLine(id: string): string | null {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.`;}+/**+ * What the model must know about custom MCP connectors: their tools run the moment it calls them,+ * inside its reply, so approval cards (Ask first) and auto-run's cap don't cover them. It reads with+ * them freely; a change outside Fuobe (posting, sending, creating, editing, deleting) needs the user's+ * word — asked in chat, or already in a scheduled task's prompt.+ */+export function connectorsLine(names: string[], o: { autoApprove: boolean; scheduled: boolean }): string {+ const list = names.join(", ");+ const how = "Their tools run the moment you call them, inside your reply — approval cards and the cost cap don't cover them.";+ const writes = o.scheduled+ ? "Use them to look things up. Only post, send, create, edit or delete something with them when the task's prompt asks for exactly that" ++ (o.autoApprove ? "." : ", and not before the results it depends on exist: plans here wait for the user's approval, so say in your summary what's left to do once they approve.")+ : o.autoApprove+ ? "Use them to look things up; only change things with them (post, send, create, edit, delete) when the user asked for that."+ : "Use them to look things up; before one that changes something (posts, sends, creates, edits or deletes), say what you'll do and wait for the user's OK in chat.";+ return `Connected apps (custom MCP connectors): ${list}. ${how} ${writes}`;+}+/** 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) ?? [];@@ -87,6 +107,7 @@ export function chatFacts(c: ChatInfo, now = new Date()): ContextFact[] {];const scheduled = c.scheduleId ? scheduleLine(c.scheduleId) : null;if (scheduled) facts.push({ section: "now", key: "scheduled", text: scheduled });+ if (c.connectors?.length) facts.push({ section: "now", key: "connectors", text: connectorsLine(c.connectors, { autoApprove: c.autoApprove, scheduled: !!c.scheduleId }) });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 a92cf903..53435ba9 100644--- a/src/server/assist/projects.ts+++ b/src/server/assist/projects.ts@@ -147,8 +147,11 @@ export function deleteProject(id: string): boolean {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.+ // The last result becomes the reason (not the last run's chat, which the page would read instead).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 = ?")+ .prepare(+ "UPDATE assist_schedules SET project_id = NULL, paused = 1, last_thread_id = NULL, 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;})();diff --git a/src/server/assist/schedules.ts b/src/server/assist/schedules.tsindex aee3f2c9..d5ae19ed 100644--- a/src/server/assist/schedules.ts+++ b/src/server/assist/schedules.ts@@ -24,8 +24,10 @@ import { getProject } from "./projects";* 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()).+ * (no generation starts 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()).+ * Custom MCP connectors are off in runs unless the task opts in (`connectors`): their tools run inside+ * Claude's reply, where neither mode can hold them back.* A run the server missed (it was off) happens once when it's back, not once per missed time.*/@@ -39,6 +41,8 @@ export class ScheduleError extends Error {}const SWEEP_MS = 30_000;+/** The first sweep after boot. */+const BOOT_SWEEP_MS = 5_000;/** At most this many tasks start in one sweep; the rest start on the next. */const PER_SWEEP = 10;@@ -52,6 +56,7 @@ interface Row {tz: string;approval: ScheduleApproval;cap_usd: number | null;+ connectors: number;engine: "cloud" | "open";mode_json: string | null;paused: number;@@ -79,21 +84,33 @@ export interface ScheduleInput {capUsd?: number | null;engine: "cloud" | "open";mode?: AssistModeChoice | null;+ /** Whether runs may use the connectors in Settings (off unless set). */+ connectors?: boolean;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). */+/**+ * How the last run went. A run that made a chat is read from the chat itself (so an approval given+ * later shows); a skip, a failure to start or a pause (no chat of its own: last_thread_id is cleared+ * then) shows the stored reason.+ */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 };+ // The chat was deleted: what was stored stands, but a run that never reported back isn't still going.+ if (!view) {+ const lost = stored.status === "running" || stored.status === "waiting";+ return { threadId: null, status: lost ? "failed" : stored.status, text: lost ? CHAT_DELETED : stored.text };+ }return { threadId: r.last_thread_id, ...summarize(view.thread.status, view.thread.items) };}+const CHAT_DELETED = "Its chat was deleted";+/** 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…" };@@ -125,6 +142,7 @@ function toView(r: Row): ScheduleView {capUsd: r.cap_usd,engine: r.engine,mode: r.mode_json ? (JSON.parse(r.mode_json) as ScheduleView["mode"]) : null,+ connectors: !!r.connectors,paused: !!r.paused,nextRunAt: r.paused ? null : r.next_run_at,lastRunAt: r.last_run_at,@@ -161,7 +179,11 @@ function checked(input: ScheduleInput, prev: Row | undefined, now: number): Omitconst bad = ruleError(rule);if (bad) throw new ScheduleError(bad);const paused = input.paused ?? !!prev?.paused;- const next = nextRun(rule, input.tz, now);+ const ruleJson = JSON.stringify(rule);+ // An edit that leaves when it runs alone (a rename, a new prompt) keeps the next time, even one that+ // is due and not yet swept; a new rule or zone, or resuming, picks it from now.+ const unchanged = prev && !prev.paused && !paused && prev.next_run_at !== null && prev.rule_json === ruleJson && prev.tz === input.tz;+ const next = unchanged ? prev.next_run_at : 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 {@@ -169,10 +191,11 @@ function checked(input: ScheduleInput, prev: Row | undefined, now: number): Omitprompt: input.prompt.trim(),attachments_json: JSON.stringify(input.attachments ?? []),project_id: input.projectId ?? null,- rule_json: JSON.stringify(rule),+ rule_json: ruleJson,tz: input.tz,approval: input.approval,cap_usd: cap === null ? null : Math.round(cap * 100) / 100,+ connectors: (input.connectors ?? !!prev?.connectors) ? 1 : 0,engine: input.engine,mode_json: input.mode ? JSON.stringify(input.mode) : null,paused: paused ? 1 : 0,@@ -185,17 +208,17 @@ export function createSchedule(input: ScheduleInput, now = Date.now()): Scheduleconst row: Row = { id: nanoid(10), ...checked(input, undefined, now), last_run_at: null, last_thread_id: null, last_status: null, last_text: null, runs: 0, created_at: now };db().prepare(- `INSERT INTO assist_schedules (id, title, prompt, attachments_json, project_id, rule_json, tz, approval, cap_usd, 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)`,+ `INSERT INTO assist_schedules (id, title, prompt, attachments_json, project_id, rule_json, tz, approval, cap_usd, connectors, 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, @connectors, @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. */+/** Edit any part; pausing keeps the task, resuming picks the next time from now, and an edit that leaves the timing alone keeps it. */export function updateSchedule(id: string, patch: Partial<ScheduleInput>, now = Date.now()): ScheduleView | null {const r = getRow(id);if (!r) return null;@@ -211,14 +234,15 @@ export function updateSchedule(id: string, patch: Partial<ScheduleInput>, now =capUsd: patch.capUsd !== undefined ? patch.capUsd : current.capUsd,engine: patch.engine ?? current.engine,mode: patch.mode !== undefined ? patch.mode : (current.mode as AssistModeChoice | null),+ connectors: patch.connectors ?? current.connectors,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`,+ tz = @tz, approval = @approval, cap_usd = @cap_usd, connectors = @connectors, 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);@@ -238,32 +262,51 @@ function record(id: string, fields: Partial<Pick<Row, "last_run_at" | "last_thre.run({ id, ...set });}+/** A chat one of this task's runs started that is still working (a run interrupted by a restart isn't). */+function runningChat(id: string): string | null {+ const rows = db()+ .prepare("SELECT s.thread_id AS id FROM assist_thread_state s JOIN assist_threads t ON t.id = s.thread_id WHERE s.schedule_id = ? AND t.status = 'running'")+ .all(id) as { id: string }[];+ return rows.find((r) => getThread(r.id)?.thread.status === "running")?.id ?? null;+}++/**+ * What starting a run came to: a new chat (`threadId`, with `done` settling when the agent stops),+ * or none and why — `busy` (the run before is still going), `paused` (its project is gone) or+ * `failed` (the chat couldn't be started) — with the text the Scheduled page shows.+ */+export type ScheduleStart = { threadId: string; done: Promise<void> } | { threadId: null; done: Promise<void>; reason: "busy" | "paused" | "failed"; message: string };+/*** 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).+ * asking first or auto-running within its cap, with connectors only when the task allows them.+ * Resolves once the chat exists; `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> }> {+export async function startSchedule(id: string, o: { now?: number; model?: ModelCall; manual?: boolean } = {}): Promise<ScheduleStart> {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;+ const none = (reason: "busy" | "paused" | "failed", message: string): ScheduleStart => ({ threadId: null, done: Promise.resolve(), reason, message });+ if (runningChat(id)) {+ // A scheduled time that passes while the last run works is recorded; a Run now click just gets the answer.+ if (!o.manual) record(id, { last_status: "skipped", last_text: `Skipped at ${formatWhen(now, r.tz)}: the run before was still going` });+ return none("busy", "The last run is still going — try again when it stops");}+ // A failure without a chat of its own clears last_thread_id, so the reason shows instead of the previous run's chat.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 message = "Its project was deleted — edit the task to pick another";+ record(id, { last_run_at: now, last_thread_id: null, last_status: "failed", last_text: message, paused: 1 });+ return none("paused", message);}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 m = await resolveMode(mode);+ const uses = !!r.connectors && m.agent === "claude";const t = createThread({engine: r.engine,agent: m.agent,@@ -275,22 +318,26 @@ export async function startSchedule(id: string, o: { now?: number; model?: Modeleffort: m.effort,scheduleId: r.id,capUsd: cap,- note: `Scheduled run of “${r.title}” · ${describeRule(rule)} · ${how}.${m.note ? ` ${m.note}` : ""}`,+ connectors: !!r.connectors,+ note: `Scheduled run of “${r.title}” · ${describeRule(rule)} · ${how}${uses ? " · connectors on (their tools run without asking)" : ""}.${m.note ? ` ${m.note}` : ""}`,});threadId = t.id;addMessage(t.id, r.prompt, JSON.parse(r.attachments_json) as string[]);} catch (e) {- record(id, { last_run_at: now, last_status: "failed", last_text: (e as Error).message, addRun: true });- return idle;+ const message = (e as Error).message || "The run couldn't start";+ record(id, { last_run_at: now, last_thread_id: null, last_status: "failed", last_text: message, addRun: true });+ return none("failed", message);}record(id, { last_run_at: now, last_thread_id: threadId, last_status: "running", last_text: "Working…", addRun: true });const done = run(threadId, o.model).catch((e: Error) => console.warn(`[fuobe] scheduled task ${id} failed: ${e.message}`)).finally(() => {+ // Only while this run is still the task's last (a pause since then keeps its reason).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 });+ const s = view ? summarize(view.thread.status, view.thread.items) : { status: "failed" as const, text: CHAT_DELETED };+ db()+ .prepare("UPDATE assist_schedules SET last_status = ?, last_text = ? WHERE id = ? AND last_thread_id = ?")+ .run(s.status, s.text, id, threadId);});return { threadId, done };}@@ -308,7 +355,7 @@ export async function sweepSchedules(now = Date.now(), o: { model?: ModelCall }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 });+ record(r.id, { last_run_at: now, last_thread_id: null, last_status: "failed", last_text: e.message });return null;});if (begun?.threadId) started.push(begun.threadId);@@ -324,8 +371,12 @@ declare global {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 {+/**+ * Start the 30 s sweep (once per process: at boot, and when a task is created). At boot (`soon`) the+ * first sweep also runs a few seconds in, so a run missed while the server was off doesn't wait for+ * the first interval.+ */+export function ensureScheduleRunner(o: { soon?: boolean } = {}): void {const cur = globalThis.__fuobeScheduleRunner;if (cur) {// After a dev hot reload, point the timer at this module's code.@@ -335,4 +386,5 @@ export function ensureScheduleRunner(): void {const state = { tick, timer: setInterval(() => globalThis.__fuobeScheduleRunner?.tick(), SWEEP_MS) };state.timer.unref?.();globalThis.__fuobeScheduleRunner = state;+ if (o.soon) setTimeout(() => globalThis.__fuobeScheduleRunner?.tick(), BOOT_SWEEP_MS).unref?.();}diff --git a/src/server/assist/schemas.ts b/src/server/assist/schemas.tsindex 71ebf5fb..01917f3e 100644--- a/src/server/assist/schemas.ts+++ b/src/server/assist/schemas.ts@@ -54,6 +54,8 @@ export const ScheduleBody = z.object({capUsd: z.number().min(0).max(MAX_SCHEDULE_CAP_USD).nullish(),engine: z.enum(["cloud", "open"]),mode: ModeChoice.nullish(),+ /** Whether runs may use the connectors in Settings (Claude only; their tools run without asking). */+ connectors: z.boolean().optional(),paused: z.boolean().optional(),});@@ -61,5 +63,6 @@ export const ConnectorBody = z.object({name: z.string().max(200).optional(),url: z.string().max(4096).optional(),token: z.string().max(8192).optional(),+ tools: z.union([z.string().max(8192), z.array(z.string().max(200)).max(200)]).nullish(),enabled: z.boolean().optional(),});diff --git a/src/server/db.ts b/src/server/db.tsindex d9c43b46..72c5bc93 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -493,9 +493,10 @@ const MIGRATIONS: string[] = [);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.+ // auto-run within a cost cap, whether its runs may use connectors, and how the last run went), custom MCP+ // connectors (name, URL, token — a secret, masked before it reaches the browser — and the tools they're+ // limited to), and on each chat the task that started it, what that run has spent on its own, and whether+ // it uses connectors.`CREATE TABLE IF NOT EXISTS assist_schedules (id TEXT PRIMARY KEY,title TEXT NOT NULL,@@ -506,6 +507,7 @@ const MIGRATIONS: string[] = [tz TEXT NOT NULL,approval TEXT NOT NULL DEFAULT 'ask',cap_usd REAL,+ connectors INTEGER NOT NULL DEFAULT 0,engine TEXT NOT NULL DEFAULT 'cloud',mode_json TEXT,paused INTEGER NOT NULL DEFAULT 0,@@ -526,6 +528,7 @@ const MIGRATIONS: string[] = [slug TEXT NOT NULL UNIQUE,url TEXT NOT NULL,token TEXT,+ tools_json TEXT,enabled INTEGER NOT NULL DEFAULT 1,created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL@@ -533,6 +536,7 @@ const MIGRATIONS: string[] = [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;+ ALTER TABLE assist_thread_state ADD COLUMN connectors INTEGER NOT NULL DEFAULT 1;CREATE INDEX IF NOT EXISTS assist_thread_state_schedule ON assist_thread_state(schedule_id);`,];diff --git a/src/server/generations.ts b/src/server/generations.tsindex c076ee6d..7266ec95 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -324,6 +324,7 @@ export const ASSET_FREE: Record<string, string> = {"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",+ "assist_connectors.tools_json": "the tool names a connector is limited to",};/** 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.tsindex 1d159d72..a61b243d 100644--- a/tests/assist-connectors.test.ts+++ b/tests/assist-connectors.test.ts@@ -53,9 +53,15 @@ describe("connector URLs", () => {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?••••");+ it("masks the query and id-like path segments (keys often live there), names connectors and cleans pasted tokens", () => {+ expect(lib.maskConnectorUrl("https://mcp.example.com/mcp?key=SECRET")).toBe("https://mcp.example.com/mcp?••••");+ // Zapier's URL is itself the secret: /api/mcp/s/<secret>/mcp.+ expect(lib.maskConnectorUrl("https://mcp.zapier.com/api/mcp/s/ODk1YjQ2NzQtSECRET0123456789/mcp")).toBe("https://mcp.zapier.com/api/mcp/s/…/mcp");+ expect(lib.maskConnectorUrl("https://mcp.pipedream.net/6d1c3f2a-58e1-4b55-9e0a-0123456789ab/notion")).toBe("https://mcp.pipedream.net/…/notion");+ expect(lib.maskConnectorUrl("https://server.example.com/u/Abc123/k/Def456/v1/sse")).toBe("https://server.example.com/u/…/k/…/v1/sse");+ expect(lib.maskConnectorUrl("https://x.example.com/Secret_Token-xyz/another-one#frag")).toBe("https://x.example.com/…?••••");expect(lib.maskConnectorUrl("https://mcp.example.com/")).toBe("https://mcp.example.com");+ expect(lib.maskConnectorUrl("not a url")).toBe("••••");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");@@ -63,6 +69,23 @@ describe("connector URLs", () => {expect(lib.cleanToken("Bearer abc.def")).toBe("abc.def");expect(lib.cleanToken("Authorization: Bearer abc")).toBe("abc");});++ it("masks short tokens harder than long API keys", () => {+ expect(lib.maskToken(TOKEN)).toBe("sk-l••••cdef");+ expect(lib.maskToken("abcd12wxyz")).toBe("••••yz");+ expect(lib.maskToken("lin_api_SECRETSECRET")).toBe("••••ET");+ expect(lib.maskToken("short")).toBe("••••");+ expect(lib.maskToken("")).toBe("");+ });++ it("reads an allow-list of tool names", () => {+ expect(lib.parseToolList("search_pages, get_page\nget_page list-items")).toEqual({ tools: ["search_pages", "get_page", "list-items"] });+ expect(lib.parseToolList(["a.b", "c"])).toEqual({ tools: ["a.b", "c"] });+ expect(lib.parseToolList(" ")).toEqual({ tools: null });+ expect(lib.parseToolList(null)).toEqual({ tools: null });+ expect(lib.parseToolList("search pages!")).toMatchObject({ error: expect.stringMatching(/“pages!” isn't a tool name/) });+ expect(lib.parseToolList(Array.from({ length: 65 }, (_, i) => `t${i}`))).toMatchObject({ error: expect.stringMatching(/at most 64/) });+ });});describe("connectors in Settings", () => {@@ -79,7 +102,7 @@ describe("connectors in Settings", () => {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 });+ expect(JSON.parse(text)).toMatchObject({ slug: "linear", hasToken: true, token: "••••ET", tools: null });// The secret is only what the Claude request reads.expect(connectors.activeConnectors().map((x) => [x.slug, x.token])).toEqual([["notion", TOKEN],@@ -87,11 +110,24 @@ describe("connectors in Settings", () => {]);});+ it("never sends a secret kept in the URL's path to the browser", async () => {+ const secret = "ODk1YjQ2NzQtZmFrZS1zZWNyZXQtMTIzNDU2";+ const c = connectors.createConnector({ name: "Zapier", url: `https://mcp.zapier.com/api/mcp/s/${secret}/mcp` });+ expect(c.url).toBe("https://mcp.zapier.com/api/mcp/s/…/mcp");+ const body = await (await listRoute.GET()).text();+ expect(body).not.toContain(secret);+ // The full URL stays on the server: the duplicate check and the Claude request use it.+ expect(() => connectors.createConnector({ name: "Zapier again", url: `https://mcp.zapier.com/api/mcp/s/${secret}/mcp` })).toThrow(/already/);+ expect(connectors.activeConnectors().find((x) => x.slug === "zapier")?.url).toContain(secret);+ connectors.deleteConnector(c.id);+ });+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/);+ expect(() => connectors.createConnector({ name: "Tools", url: "https://c.example.com", tools: "rm -rf /" })).toThrow(/isn't a tool name/);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");@@ -107,6 +143,13 @@ describe("connectors in Settings", () => {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);+ // An allow-list: set, kept by other edits, cleared with "" (or null).+ const limited = await oneRoute.PATCH(new Request("http://x", { method: "PATCH", body: JSON.stringify({ tools: "search_pages, get_page" }) }), ctx);+ expect(await limited.json()).toMatchObject({ tools: ["search_pages", "get_page"] });+ await oneRoute.PATCH(new Request("http://x", { method: "PATCH", body: JSON.stringify({ name: "Notion work" }) }), ctx);+ expect(connectors.activeConnectors().find((x) => x.slug === "notion")?.tools).toEqual(["search_pages", "get_page"]);+ const bad = await oneRoute.PATCH(new Request("http://x", { method: "PATCH", body: JSON.stringify({ tools: "search pages!" }) }), ctx);+ expect(bad.status).toBe(400);});});@@ -115,8 +158,8 @@ describe("the Claude request", () => {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 },+ { id: "a", name: "Notion", slug: "notion", url: "https://mcp.notion.com/mcp", token: TOKEN, tools: ["search_pages", "get_page"], enabled: true },+ { id: "b", name: "Docs", slug: "docs", url: "https://docs.example.com/mcp", token: null, tools: null, enabled: true },]),).toEqual({mcp_servers: [@@ -124,7 +167,8 @@ describe("the Claude request", () => {{ type: "url", url: "https://docs.example.com/mcp", name: "docs" },],toolsets: [- { type: "mcp_toolset", mcp_server_name: "notion" },+ // An allow-list: every tool off by default, the listed ones on.+ { type: "mcp_toolset", mcp_server_name: "notion", default_config: { enabled: false }, configs: { search_pages: { enabled: true }, get_page: { enabled: true } } },{ type: "mcp_toolset", mcp_server_name: "docs" },],});@@ -167,9 +211,13 @@ describe("the Claude request", () => {]);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: "notion", default_config: { enabled: false }, configs: { search_pages: { enabled: true }, get_page: { enabled: true } } },{ type: "mcp_toolset", mcp_server_name: "linear" },]);+ // Claude is told the connector tools run without asking, and to check first in an Ask-first chat.+ const system = JSON.stringify(body.system);+ expect(system).toContain("Connected apps (custom MCP connectors): Notion work, Linear.");+ expect(system).toContain("say what you'll do and wait for the user's OK in chat");// Fuobe's own tools are still there, first.expect(tools[0].name).toBeTruthy();const items = agent.getThread(t.id)!.thread.items;@@ -218,6 +266,30 @@ describe("the Claude request", () => {}});+ it("a chat started without connectors (a scheduled run that leaves them off) sends none", async () => {+ setSetting("anthropicKey", "sk-ant-test");+ const sent: Record<string, unknown>[] = [];+ const realFetch = globalThis.fetch;+ globalThis.fetch = (async (_url: string, init: RequestInit) => {+ sent.push(JSON.parse(String(init.body)) as Record<string, unknown>);+ return claudeStream({ content: [{ type: "text", text: "Hi" }], stop_reason: "end_turn" });+ }) as typeof fetch;+ try {+ expect(connectors.activeConnectors().length).toBeGreaterThan(0);+ const t = agent.createThread({ engine: "cloud", agent: "claude", mode: "smart", connectors: false });+ agent.addMessage(t.id, "Hi");+ await agent.run(t.id);+ expect(sent[0].mcp_servers).toBeUndefined();+ expect(JSON.stringify(sent[0].system)).not.toContain("Connected apps");+ // Nor does it get the "connectors need Claude" note on another agent.+ const o = agent.createThread({ engine: "cloud", agent: "offline", mode: "free", connectors: false });+ expect(agent.getThread(o.id)!.thread.items).toEqual([]);+ } finally {+ globalThis.fetch = realFetch;+ setSetting("anthropicKey", "");+ }+ });+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));diff --git a/tests/assist-schedules.test.ts b/tests/assist-schedules.test.tsindex 4684a61c..5829a331 100644--- a/tests/assist-schedules.test.ts+++ b/tests/assist-schedules.test.ts@@ -11,6 +11,13 @@ 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";+// No real 30 s sweep in this process: the fixtures' times are due by the real clock too, and a sweep+// with Date.now() would start extra runs. A runner that is already "running" (its timer cleared) keeps+// ensureScheduleRunner from starting one; the first test checks that saving a task starts it.+const stubTimer = setInterval(() => {}, 60_000);+clearInterval(stubTimer);+globalThis.__fuobeScheduleRunner = { tick: () => {}, timer: stubTimer };+const { setSetting } = await import("@/server/settings");const agent = await import("@/server/assist/agent");const tools = await import("@/server/assist/tools");@@ -18,8 +25,10 @@ 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 connectors = await import("@/server/assist/connectors");const listRoute = await import("@/app/api/assist/schedules/route");const oneRoute = await import("@/app/api/assist/schedules/[scheduleId]/route");+const runRoute = await import("@/app/api/assist/schedules/[scheduleId]/run/route");type Block = Anthropic.Beta.BetaContentBlock;const text = (t: string) => ({ type: "text", text: t, citations: null }) as Block;@@ -29,10 +38,10 @@ const job = (prompt: string) => ({ summary: prompt, jobs: [{ model_id: "nano-ban/** 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 }[] = [];+ const seen: { system: string; messages: string; connectors?: string[] }[] = [];let n = 0;- const call: import("@/server/assist/agent").ModelCall = async ({ system }) => {- seen.push({ system: system.turn });+ const call: import("@/server/assist/agent").ModelCall = async ({ system, messages, connectors }) => {+ seen.push({ system: system.turn, messages: JSON.stringify(messages), connectors: connectors?.map((c) => c.slug) });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");};@@ -56,10 +65,15 @@ describe("scheduled tasks", () => {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 });// Saving a task makes sure the sweep is running (it also starts at boot).+ const stub = globalThis.__fuobeScheduleRunner;+ globalThis.__fuobeScheduleRunner = undefined;+ const s = sched.createSchedule({ ...base, title: "Every 6h", rule: { kind: "hours", every: 6 } }, now);expect(globalThis.__fuobeScheduleRunner).toBeDefined();+ clearInterval(globalThis.__fuobeScheduleRunner!.timer);+ globalThis.__fuobeScheduleRunner = stub;+ expect(s.rule).toEqual({ kind: "hours", every: 6, from: now });+ expect(s.connectors).toBe(false);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();@@ -143,10 +157,92 @@ describe("the sweep (fake clock)", () => {// 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);+ expect(sched.getSchedule(s.id)!.last).toMatchObject({ threadId: id, status: "done" });projects.deleteProject(p.id);- expect(sched.getSchedule(s.id)).toMatchObject({ projectId: null, paused: true, nextRunAt: null });+ // The reason shows, not the last run's chat (which finished fine).+ expect(sched.getSchedule(s.id)).toMatchObject({ projectId: null, paused: true, nextRunAt: null, last: { threadId: null, status: "failed", text: "Paused: its project was deleted" } });expect(await sched.sweepSchedules(T("2026-10-28T09:00:00Z"), { model: scripted().call })).toEqual([]);});++ it("a project that vanished before a start: Run now says why, and so does the task", async () => {+ const p = projects.createProject({ name: "Gone" });+ const s = sched.createSchedule({ ...base, title: "Orphan", projectId: p.id, rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));+ const [first] = await sched.sweepSchedules(T("2026-10-27T09:00:00Z"), { model: scripted().call });+ expect(first).toBeTruthy();+ // Removed behind deleteProject's back (another process, a restore): the start finds no project.+ db().prepare("DELETE FROM assist_projects WHERE id = ?").run(p.id);+ const res = await runRoute.POST(new Request("http://x", { method: "POST" }), { params: Promise.resolve({ scheduleId: s.id }) });+ expect(res.status).toBe(422);+ expect(await res.json()).toMatchObject({ threadId: null, reason: "paused", error: "Its project was deleted — edit the task to pick another" });+ expect(sched.getSchedule(s.id)).toMatchObject({ paused: true, last: { threadId: null, status: "failed", text: "Its project was deleted — edit the task to pick another" } });+ });++ it("Run now: 202 with the new chat; 409 while the last run is still going", async () => {+ const s = sched.createSchedule({ ...base, title: "Now", rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));+ const ctx = { params: Promise.resolve({ scheduleId: s.id }) };+ let release!: () => void;+ const slow: import("@/server/assist/agent").ModelCall = () => new Promise((r) => (release = () => r(reply([text("Made it.")], "end_turn"))));+ const begun = await sched.startSchedule(s.id, { model: slow });+ expect(begun.threadId).toBeTruthy();+ await vi.waitFor(() => expect(release).toBeTypeOf("function"));+ const busy = await runRoute.POST(new Request("http://x", { method: "POST" }), ctx);+ expect(busy.status).toBe(409);+ expect(await busy.json()).toMatchObject({ threadId: null, reason: "busy" });+ // The click isn't recorded as a skipped run: the task still shows the run that's going.+ expect(sched.getSchedule(s.id)!.last).toMatchObject({ threadId: begun.threadId, status: "running" });+ release();+ await begun.done;+ expect(sched.getSchedule(s.id)!.last).toMatchObject({ threadId: begun.threadId, status: "done", text: "Made it." });+ expect((await runRoute.POST(new Request("http://x", { method: "POST" }), { params: Promise.resolve({ scheduleId: "nope" }) })).status).toBe(404);+ });++ it("a run whose chat is deleted doesn't stay 'running'", async () => {+ const s = sched.createSchedule({ ...base, title: "Deleted chat", rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));+ // A run the server lost track of (it restarted mid-run): stored as running.+ const t = agent.createThread({ engine: "cloud", agent: "offline", scheduleId: s.id });+ db().prepare("UPDATE assist_schedules SET last_thread_id = ?, last_status = 'running', last_text = 'Working…', last_run_at = ? WHERE id = ?").run(t.id, T("2026-10-27T09:00:00Z"), s.id);+ agent.deleteThread(t.id);+ expect(sched.getSchedule(s.id)!.last).toEqual({ threadId: null, status: "failed", text: "Its chat was deleted" });+ // A finished run whose chat is deleted keeps what it reported, without the link.+ const begun = await sched.startSchedule(s.id, { model: scripted().call });+ await begun.done;+ agent.deleteThread(begun.threadId!);+ expect(sched.getSchedule(s.id)!.last).toEqual({ threadId: null, status: "done", text: "Done — your ad is rendering." });+ });++ it("an edit that leaves the timing alone keeps a due run; a new time or zone doesn't", async () => {+ const s = sched.createSchedule({ ...base, title: "Due", rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));+ // Renamed at 09:00:10, before the sweep at 09:00:30: the 09:00 run still happens.+ expect(sched.updateSchedule(s.id, { title: "Due (renamed)", prompt: "A new prompt" }, T("2026-10-27T09:00:10Z"))!.nextRunAt).toBe(T("2026-10-27T09:00:00Z"));+ expect(await sched.sweepSchedules(T("2026-10-27T09:00:30Z"), { model: scripted().call })).toHaveLength(1);+ expect(sched.getSchedule(s.id)!.nextRunAt).toBe(T("2026-10-28T09:00:00Z"));+ // A new time is counted from now.+ expect(sched.updateSchedule(s.id, { rule: { kind: "daily", time: "10:00" } }, T("2026-10-27T09:30:00Z"))!.nextRunAt).toBe(T("2026-10-27T10:00:00Z"));+ expect(sched.updateSchedule(s.id, { tz: "Europe/Berlin" }, T("2026-10-27T09:30:00Z"))!.nextRunAt).toBe(T("2026-10-28T09:00:00Z"));+ });++ it("the runner started at boot sweeps a few seconds in, then every 30 s", () => {+ vi.useFakeTimers();+ const stub = globalThis.__fuobeScheduleRunner;+ globalThis.__fuobeScheduleRunner = undefined;+ try {+ sched.ensureScheduleRunner({ soon: true });+ const runner = globalThis.__fuobeScheduleRunner!;+ const ticks = vi.fn();+ runner.tick = ticks;+ vi.advanceTimersByTime(5_000);+ expect(ticks).toHaveBeenCalledTimes(1);+ vi.advanceTimersByTime(25_000);+ expect(ticks).toHaveBeenCalledTimes(2);+ // A second call (a hot reload) keeps the one timer.+ sched.ensureScheduleRunner({ soon: true });+ expect(globalThis.__fuobeScheduleRunner).toBe(runner);+ clearInterval(runner.timer);+ } finally {+ globalThis.__fuobeScheduleRunner = stub;+ vi.useRealTimers();+ }+ });});describe("approval and the cost cap", () => {@@ -219,3 +315,47 @@ describe("approval and the cost cap", () => {}});});++describe("connectors in scheduled runs", () => {+ afterEach(() => {+ setSetting("anthropicKey", "");+ for (const c of connectors.listConnectors()) connectors.deleteConnector(c.id);+ });++ it("are off unless the task allows them; when on, Claude is told they run without asking", async () => {+ setSetting("anthropicKey", "sk-ant-test");+ connectors.createConnector({ name: "Slack", url: "https://mcp.slack.example.com/mcp", token: "xoxb-0123456789abcdefghij" });+ const off = sched.createSchedule({ ...base, title: "No connectors", mode: { mode: "smart" }, rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));+ const m1 = scripted();+ const [a] = await sched.sweepSchedules(T("2026-10-27T09:00:00Z"), { model: m1.call });+ expect(threadOf(a).agent).toBe("claude");+ expect(m1.seen[0].connectors).toBeUndefined();+ expect(m1.seen[0].system).not.toMatch(/Connected apps/);+ expect(threadOf(a).items[0]).toMatchObject({ text: expect.not.stringMatching(/connectors on/) });+ sched.deleteSchedule(off.id);++ const on = sched.createSchedule({ ...base, title: "With Slack", mode: { mode: "smart" }, connectors: true, rule: { kind: "daily", time: "09:00" } }, T("2026-10-27T08:00:00Z"));+ expect(on.connectors).toBe(true);+ const m2 = scripted();+ const [b] = await sched.sweepSchedules(T("2026-10-27T09:00:00Z"), { model: m2.call });+ expect(m2.seen[0].connectors).toEqual(["slack"]);+ expect(m2.seen[0].system).toMatch(/Connected apps \(custom MCP connectors\): Slack\. Their tools run the moment you call them/);+ // Ask first: nothing that depends on unapproved results goes out.+ expect(m2.seen[0].system).toMatch(/plans here wait for the user's approval/);+ expect(threadOf(b).items[0]).toMatchObject({ text: expect.stringMatching(/connectors on \(their tools run without asking\)/) });+ // Turning it off again applies to the next run.+ expect(sched.updateSchedule(on.id, { connectors: false })!.connectors).toBe(false);+ });++ it("an ordinary Claude chat in Ask first is told to check before a connector changes anything", async () => {+ setSetting("anthropicKey", "sk-ant-test");+ connectors.createConnector({ name: "Linear", url: "https://mcp.linear.example.com/mcp" });+ const t = agent.createThread({ engine: "cloud", agent: "claude", mode: "smart" });+ agent.addMessage(t.id, "What's on my board?");+ const m = scripted();+ await agent.run(t.id, m.call);+ expect(m.seen[0].connectors).toEqual(["linear"]);+ expect(m.seen[0].system).toMatch(/approval cards and the cost cap don't cover them/);+ expect(m.seen[0].system).toMatch(/say what you'll do and wait for the user's OK in chat/);+ });+});