feat(cron): guest jobs start on Sonnet; the local ones move to it once #23

Open
gabrielvidal wants to merge 1 commits from guest-jobs-sonnet into main
pull from: guest-jobs-sonnet
16 changed files with 138 additions and 47 deletions

No files matched your search

+1 -1
View File
@@ -23,7 +23,7 @@ class GuestCronBody(BaseModel):
name: str | None = None
schedule: str | None = None
prompt: str | None = None
model: str | None = None # "qwen" | "sonnet"
model: str | None = None # "sonnet" | "qwen"
project: str | None = None # "" = their own folder
email: bool | None = None
mailHtml: str | None = None # the mail's HTML from a project file ("" = none)
+46 -6
View File
@@ -7,11 +7,13 @@ job differs from an owner's in every way that matters:
* **its prompt is in the store** (``prompt``), not in a ``.claude/agents``
file of the lab repo — a guest can't write there;
* **it says what it runs on with one word**, ``model``: ``qwen`` (the
default — the EVOX2's local model, Inkling 2 Mini since 2026-11-23, the pi
harness, $0; the key predates it) or ``sonnet``. A local
job whose box can't take it within ``FALLBACK_WAIT_S`` runs on Sonnet
instead, which then counts toward their budget like any Sonnet run;
* **it says what it runs on with one word**, ``model``: ``sonnet`` (the
default since 2026-11-27, under their budget) or ``qwen`` (the EVOX2's
local model, Inkling 2 Mini since 2026-11-23, the pi harness, $0; the key
predates it — it was the default until its runs looped on one command, see
:func:`move_local_jobs_to_sonnet`). A local job whose box can't take it
within ``FALLBACK_WAIT_S`` runs on Sonnet instead, which then counts toward
their budget like any Sonnet run;
* **it always runs lean**, with an allowlist: :data:`BASE_ALLOW` (``web``
— search, news and fetch for a model with no web tools — and
``notify-done``) plus ``allow``, programs only the owner adds to a job
@@ -32,6 +34,7 @@ fire at most once an hour (its minute field is a single value).
from __future__ import annotations
import datetime
import json
import logging
import os
import re
@@ -49,8 +52,10 @@ log = logging.getLogger(__name__)
# The models a guest job runs on (the UI's two chips). "qwen" is the stored
# name of the *local* choice — the EVOX2's default local model, Inkling 2 Mini
# since 2026-11-23 (Qwen 3.8 27B before; the key stayed so saved jobs keep it).
# A job starts on Sonnet since 2026-11-27: Inkling looped on the same command
# until the run was stopped (the mail secretary's and Arthur's veille pharma).
MODELS = ("qwen", "sonnet")
DEFAULT_MODEL = "qwen"
DEFAULT_MODEL = "sonnet"
QWEN_MODEL = os.environ.get("GUEST_JOB_QWEN_MODEL", "inkling-2-mini")
# How long a local job waits for the EVOX2 (asleep, or its GPU taken) before
# it runs on Sonnet.
@@ -785,7 +790,42 @@ def deliver_sweep(deps) -> int:
return n
# Written next to the cron store once :func:`move_local_jobs_to_sonnet` ran.
SONNET_MOVE_MARKER = "guest-jobs-on-sonnet.done"
def move_local_jobs_to_sonnet(deps) -> list[str]:
"""Once (2026-11-27): every guest job still on the local model — ``qwen``,
or no ``model`` (the old default) — moves to Sonnet, and so does the
owner's saved "new jobs start on" policy. Inkling 2 Mini looped on one
command until its runs were stopped; Gabriel chose Sonnet for them all.
A guest (or the owner) may still pick the local model again afterwards:
the marker file keeps this from running twice. The ids moved."""
store = deps.cron_store
marker = store.path.with_name(SONNET_MOVE_MARKER)
if marker.exists():
return []
moved = []
for job in store.list():
if is_guest_job(job) and (job.get("model") or "qwen") == "qwen":
store.update_guest(job["id"], {"model": "sonnet"})
moved.append(job["id"])
if limits(deps).get("defaultModel") == "qwen":
deps.users.set_defaults({"cronLimits": {"defaultModel": "sonnet"}})
marker.write_text(json.dumps({"at": datetime.datetime.now().isoformat(timespec="seconds"),
"moved": moved}) + "\n")
if moved:
log.info("guest jobs moved from the local model to Sonnet: %s", ", ".join(moved))
deps.hub.publish({"type": "cron"})
return moved
def start(deps, every_s: float = SWEEP_S) -> None:
try:
move_local_jobs_to_sonnet(deps)
except Exception:
log.exception("moving the guest jobs to Sonnet failed")
def loop():
while True:
time.sleep(every_s)
+3 -3
View File
@@ -117,8 +117,8 @@ class GuestCronJob(Schema):
schedule: str
enabled: bool
prompt: str
# "qwen" (the EVOX2's local model — Inkling 2 Mini —, Sonnet when it
# can't; the key predates Inkling) | "sonnet".
# "sonnet" (the default) | "qwen" (the EVOX2's local model — Inkling 2
# Mini —, Sonnet when it can't; the key predates Inkling).
model: str
# The project it runs in (one they hold chat on); None = their own folder.
project: Optional[str] = None
@@ -139,7 +139,7 @@ class GuestCronJob(Schema):
class GuestCronLimits(Schema):
maxJobs: int
defaultModel: str = "qwen"
defaultModel: str = "sonnet"
class GuestCronJobsResponse(Schema):
+2 -2
View File
@@ -589,9 +589,9 @@ class AnimationCurve(Schema):
class GuestCronLimitsOut(Schema):
"""How many scheduled jobs of their own each guest may have, and the model
a new one starts on ("qwen" | "sonnet")."""
a new one starts on ("sonnet" | "qwen")."""
maxJobs: int = 5
defaultModel: str = "qwen"
defaultModel: str = "sonnet"
class GuestDefaults(Schema):
+42 -7
View File
@@ -1,7 +1,8 @@
"""A guest's own scheduled jobs (cron/guests.py, cron/guest_routes.py): the
REST a guest's page and their runs' `ai-agent cron` use, the limits, how a
firing is pinned (as the guest, lean, confined, on Qwen with a Sonnet
fallback), the owner's view and extras, read-only runs + « Discuter », and
firing is pinned (as the guest, lean, confined, on Sonnet — or on the local
model with a Sonnet fallback), the one-time move of the local jobs to Sonnet,
the owner's view and extras, read-only runs + « Discuter », and
the delivery of a run's result.
Imports ``main`` against throwaway paths (no startup event → no threads)."""
@@ -80,8 +81,9 @@ class GuestCron(unittest.TestCase):
self.assertEqual(r.status_code, 200, r.text)
j = r.json()
self.assertTrue(j["id"].startswith("arthur-"))
# a new job starts on Sonnet (the local model looped — 2026-11-27)
self.assertEqual((j["model"], j["project"], j["email"], j["allow"]),
("qwen", None, False, []))
("sonnet", None, False, []))
self.assertIsNotNone(j["nextRun"])
stored = DEPS.cron_store.get(j["id"])
self.assertEqual(stored["owner"], "arthur")
@@ -89,11 +91,11 @@ class GuestCron(unittest.TestCase):
# the owner hears of it
self.assertTrue(any("Arthur scheduled a job" in p["title"] for p in self.pings))
self.assertEqual([x["id"] for x in g.get("/api/me/cron").json()["jobs"]], [j["id"]])
r = g.put(f"/api/me/cron/{j['id']}", json={"model": "sonnet", "email": True,
r = g.put(f"/api/me/cron/{j['id']}", json={"model": "qwen", "email": True,
"enabled": False}, headers=ORIGIN)
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual((r.json()["model"], r.json()["email"], r.json()["enabled"]),
("sonnet", True, False))
("qwen", True, False))
self.assertIsNone(r.json()["nextRun"])
self.assertEqual(g.delete(f"/api/me/cron/{j['id']}", headers=ORIGIN).status_code, 200)
self.assertIsNone(DEPS.cron_store.get(j["id"]))
@@ -148,7 +150,7 @@ class GuestCron(unittest.TestCase):
# ── firing ───────────────────────────────────────────────────────────────
def test_a_qwen_job_fires_as_the_guest_lean_and_confined(self):
calls = self._capture()
job = guests.create(DEPS, guest_from_record(DEPS.users.get("arthur")), dict(JOB))
job = guests.create(DEPS, guest_from_record(DEPS.users.get("arthur")), {**JOB, "model": "qwen"})
out = guests.fire(DEPS, job)
prompt, kw = calls[0]
self.assertTrue(prompt.startswith('<ai-agent-from user="arthur"'))
@@ -164,9 +166,42 @@ class GuestCron(unittest.TestCase):
self.assertEqual(m["cron"]["guest"], "arthur")
self.assertEqual(DEPS.cron_store.get(job["id"])["lastStatus"], "ok")
def test_the_fallback_runs_on_sonnet_with_web_tools(self):
def test_a_new_job_runs_on_sonnet_with_no_fallback(self):
calls = self._capture()
job = guests.create(DEPS, guest_from_record(DEPS.users.get("arthur")), dict(JOB))
self.assertIsNone(guests.run_config(job)["fallback"])
guests.fire(DEPS, job)
_, kw = calls[0]
self.assertEqual((kw["harness"], kw["model"]), ("claude", "sonnet"))
self.assertIn("WebSearch", kw["lean"]["tools"])
def test_the_local_jobs_move_to_sonnet_once(self):
arthur = guest_from_record(DEPS.users.get("arthur"))
local = guests.create(DEPS, arthur, {**JOB, "model": "qwen"})
old = guests.create(DEPS, arthur, {**JOB, "name": "Avant", "model": "qwen"})
with DEPS.cron_store._lock: # a job from before `model` was stored
DEPS.cron_store._data[old["id"]].pop("model")
DEPS.cron_store._save()
sonnet = guests.create(DEPS, arthur, {**JOB, "name": "Déjà", "model": "sonnet"})
DEPS.users.set_defaults({"cronLimits": {"defaultModel": "qwen"}})
self.addCleanup(DEPS.users.set_defaults, {"cronLimits": {"defaultModel": "sonnet"}})
marker = DEPS.cron_store.path.with_name(guests.SONNET_MOVE_MARKER)
marker.unlink(missing_ok=True)
self.addCleanup(marker.unlink, missing_ok=True)
self.assertEqual(sorted(guests.move_local_jobs_to_sonnet(DEPS)), sorted([local["id"], old["id"]]))
for j in (local, old, sonnet):
self.assertEqual(DEPS.cron_store.get(j["id"])["model"], "sonnet")
self.assertEqual(guests.limits(DEPS)["defaultModel"], "sonnet")
self.assertTrue(marker.exists())
# never twice: a job set back to the local model by hand stays there
guests.update(DEPS, arthur, DEPS.cron_store.get(local["id"]), {"model": "qwen"})
self.assertEqual(guests.move_local_jobs_to_sonnet(DEPS), [])
self.assertEqual(DEPS.cron_store.get(local["id"])["model"], "qwen")
def test_the_fallback_runs_on_sonnet_with_web_tools(self):
calls = self._capture()
job = guests.create(DEPS, guest_from_record(DEPS.users.get("arthur")), {**JOB, "model": "qwen"})
guests.fire(DEPS, job, fallback="EVOX2 asleep")
_, kw = calls[0]
self.assertEqual((kw["harness"], kw["model"], kw["account"]), ("claude", "sonnet", "personal"))
+3 -3
View File
@@ -392,8 +392,8 @@ def clean_computer_limits(raw, base: dict | None = None) -> dict:
# A guest's own scheduled jobs (cron/guests.py): how many each may have, and
# the model a new one starts on (qwen | sonnet).
DEFAULT_CRON_LIMITS = {"maxJobs": 5, "defaultModel": "qwen"}
# the model a new one starts on (sonnet | qwen — sonnet since 2026-11-27).
DEFAULT_CRON_LIMITS = {"maxJobs": 5, "defaultModel": "sonnet"}
def clean_cron_limits(raw, base: dict | None = None) -> dict:
@@ -406,7 +406,7 @@ def clean_cron_limits(raw, base: dict | None = None) -> dict:
pass
if raw.get("defaultModel") in ("qwen", "sonnet"):
cur["defaultModel"] = raw["defaultModel"]
model = cur["defaultModel"] if cur.get("defaultModel") in ("qwen", "sonnet") else "qwen"
model = cur["defaultModel"] if cur.get("defaultModel") in ("qwen", "sonnet") else "sonnet"
return {"maxJobs": int(cur["maxJobs"]), "defaultModel": model}
+1 -1
View File
@@ -1664,7 +1664,7 @@ def build_parser() -> argparse.ArgumentParser:
cr.add_argument("--cron", help="add/edit: a 5-field cron expression instead (at most hourly)")
cr.add_argument("--prompt", help="add/edit: what the job does each time")
cr.add_argument("--model", choices=("qwen", "sonnet"),
help="add/edit: qwen (default: the local model, Inkling 2 Mini — free, Sonnet when the box can't) | sonnet")
help="add/edit: sonnet (default) | qwen (the local model, Inkling 2 Mini — free, Sonnet when the box can't)")
cr.add_argument("--project", help="add/edit: run in this project of theirs ('' = their own folder)")
cr.add_argument("--name", help="edit: rename it")
cr.add_argument("--email", dest="email", action="store_true", default=None,
+4 -4
View File
@@ -36,10 +36,10 @@ ai-agent cron rm JOB
`1-5`). `--cron 'M H * * D'` takes a cron expression instead. A job runs
**at most once an hour** (a single minute), and each person has a few jobs
at most — the hub says so when the limit is reached.
- **Model**: `qwen` (the default — Qwen 3.8 on the lab's own GPU, free; if
the box can't take it within 10 minutes the run goes to Sonnet, which
counts toward their budget) or `sonnet` (Claude, better at long reading and
careful writing; counts toward their budget every time).
- **Model**: `sonnet` (the default — Claude, reliable on long reading and
careful writing; counts toward their budget every time) or `qwen` (the
lab's own local model, Inkling 2 Mini, free but it can loop on a command; if
the box can't take it within 10 minutes the run goes to Sonnet).
- **Where**: `--project P` runs it in one of their projects (it can read and
write there); without it, in a private folder of its own.
- **A designed mail** (`--email` + `--project P`): `--mail-html PATH` (a
+4 -4
View File
@@ -23783,7 +23783,7 @@
"defaultModel": {
"type": "string",
"title": "Defaultmodel",
"default": "qwen"
"default": "sonnet"
}
},
"type": "object",
@@ -23802,12 +23802,12 @@
"defaultModel": {
"type": "string",
"title": "Defaultmodel",
"default": "qwen"
"default": "sonnet"
}
},
"type": "object",
"title": "GuestCronLimitsOut",
"description": "How many scheduled jobs of their own each guest may have, and the model\na new one starts on (\"qwen\" | \"sonnet\")."
"description": "How many scheduled jobs of their own each guest may have, and the model\na new one starts on (\"sonnet\" | \"qwen\")."
},
"GuestCronRunResult": {
"properties": {
@@ -23860,7 +23860,7 @@
"$ref": "#/components/schemas/GuestCronLimitsOut",
"default": {
"maxJobs": 5,
"defaultModel": "qwen"
"defaultModel": "sonnet"
}
}
},
@@ -121,8 +121,8 @@ function WhenField({ expr, onChange }: { expr: string; onChange: (e: string) =>
function ModelChoice({ value, onChange }: { value: "qwen" | "sonnet"; onChange: (v: "qwen" | "sonnet") => void }) {
const opts = [
{ v: "qwen" as const, label: t("Inkling 2 Mini · local, free"), hint: t("on the host's own GPU; Sonnet takes over when it's busy or asleep") },
{ v: "sonnet" as const, label: "Sonnet", hint: t("Claude — better at long reading; counts toward your budget") },
{ v: "qwen" as const, label: t("Inkling 2 Mini · local, free"), hint: t("on the host's own GPU; Sonnet takes over when it's busy or asleep") },
];
return (
<Group label={t("Model")}>
@@ -156,7 +156,7 @@ export function JobEditor({
open,
onClose,
job,
defaultModel = "qwen",
defaultModel = "sonnet",
}: {
open: boolean;
onClose: () => void;
@@ -169,7 +169,7 @@ export function JobEditor({
const [schedule, setSchedule] = useState(job?.schedule ?? "30 7 * * *");
const [prompt, setPrompt] = useState(job?.prompt ?? "");
const [model, setModel] = useState<"qwen" | "sonnet">(
((job?.model ?? defaultModel) === "sonnet" ? "sonnet" : "qwen"),
((job?.model ?? defaultModel) === "qwen" ? "qwen" : "sonnet"),
);
const [project, setProject] = useState(job?.project ?? "");
const [email, setEmail] = useState(!!job?.email);
+4 -4
View File
@@ -104,7 +104,7 @@ function JobCard({ job, onEdit }: { job: GuestCronJob; onEdit: () => void }) {
</div>
<div className="mt-1.5 flex flex-wrap gap-1 pl-6">
<span className={cn(CHIP, "bg-primary/10 text-primary")}>
{job.model === "sonnet" ? "Sonnet" : t("Inkling 2 Mini · free")}
{job.model === "qwen" ? t("Inkling 2 Mini · free") : "Sonnet"}
</span>
{job.project && <span className={cn(CHIP, "bg-muted text-muted-foreground")}>{job.project}</span>}
{job.email && (
@@ -141,8 +141,8 @@ function JobCard({ job, onEdit }: { job: GuestCronJob; onEdit: () => void }) {
/**
* Settings → Scheduled jobs (`/settings/jobs`, guests only): prompts that run
* on their own at the times they pick — on Inkling 2 Mini on the host's GPU by
* default, Sonnet when it can't or when they choose it — whose result is
* on their own at the times they pick — on Sonnet by default, or Inkling 2
* Mini on the host's GPU when they choose it (Sonnet when it can't) — whose result is
* pushed (and mailed, if they like) when each run ends (backend
* `cron/guests.py`). Their runs can also set one up (`ai-agent cron`).
*/
@@ -197,7 +197,7 @@ export function MyJobsPage() {
open
onClose={() => setEditing(null)}
job={editing === "new" ? undefined : editing}
defaultModel={data?.limits.defaultModel ?? "qwen"}
defaultModel={data?.limits.defaultModel ?? "sonnet"}
/>
)}
</main>
@@ -653,13 +653,13 @@ function GuestJobCard({ job, defaultOpen }: { job: CronJob; defaultOpen: boolean
<div className="flex flex-col gap-3 sm:flex-row">
<Field label="Model">
<select
value={job.model === "sonnet" ? "sonnet" : "qwen"}
value={job.model === "qwen" ? "qwen" : "sonnet"}
disabled={busy !== ""}
onChange={(e) => void act("field", () => updateCronJob(job.id, { model: e.target.value }))}
className={`${SELECT} w-full`}
>
<option value="qwen">Inkling 2 Mini (pi, EVOX2) — Sonnet fallback</option>
<option value="sonnet">Sonnet</option>
<option value="qwen">Inkling 2 Mini (pi, EVOX2) — Sonnet fallback</option>
</select>
</Field>
<Field label="Sonnet effort" hint="yours to set — not shown to them">
@@ -182,7 +182,7 @@ function ComputerLimitsPolicy({ saved }: { saved?: ComputerLimits }) {
/** Every guest's scheduled jobs (backend cron/guests.py): how many, and the model a new one starts on. */
function CronLimitsPolicy({ saved }: { saved?: { maxJobs?: number; defaultModel?: string } | null }) {
const maxSaved = saved?.maxJobs ?? 5;
const modelSaved = saved?.defaultModel === "sonnet" ? "sonnet" : "qwen";
const modelSaved = saved?.defaultModel === "qwen" ? "qwen" : "sonnet";
const [max, setMax] = useState(String(maxSaved));
const [seed, setSeed] = useState(maxSaved);
const [busy, setBusy] = useState(false);
@@ -208,13 +208,13 @@ function CronLimitsPolicy({ saved }: { saved?: { maxJobs?: number; defaultModel?
<ItemCard
icon={<CalendarClock className="h-3.5 w-3.5 shrink-0 text-violet-500" />}
title="Scheduled jobs"
secondLine={`${maxSaved} per guest · at most hourly · new ones on ${modelSaved === "sonnet" ? "Sonnet" : "Inkling 2 Mini"}`}
secondLine={`${maxSaved} per guest · at most hourly · new ones on ${modelSaved === "qwen" ? "Inkling 2 Mini" : "Sonnet"}`}
>
<p className="text-[11px] leading-relaxed text-muted-foreground">
Every guest may schedule prompts of their own (their Settings → Scheduled jobs, or by asking a
conversation — their runs have the ai-agent CLI, on by default for every guest). They run on the lab as
them, lean and confined, at most once an hour; Qwen jobs fall back on Sonnet when the EVOX2 can&apos;t take
them. All of them:{" "}
them, lean and confined, at most once an hour; Inkling 2 Mini jobs fall back on Sonnet when the EVOX2
can&apos;t take them. All of them:{" "}
<Link to="/settings/cron?runner=guests" className="text-primary hover:underline">
Settings → Cron → Guests
</Link>
@@ -247,8 +247,8 @@ function CronLimitsPolicy({ saved }: { saved?: { maxJobs?: number; defaultModel?
onChange={(e) => void save({ defaultModel: e.target.value })}
className={cn(SELECT, "w-full")}
>
<option value="qwen">Inkling 2 Mini (local, free; Sonnet fallback)</option>
<option value="sonnet">Sonnet</option>
<option value="qwen">Inkling 2 Mini (local, free; Sonnet fallback)</option>
</select>
</Field>
</div>
@@ -24,7 +24,7 @@ export function GuestJobs({ uid }: { uid: string }) {
<CalendarClock className={cn("h-3.5 w-3.5 shrink-0", j.enabled ? "text-violet-500" : "text-muted-foreground")} />
<span className="min-w-0 flex-1 truncate font-medium">{j.name}</span>
<span className="shrink-0 text-[11px] text-muted-foreground">
{describe(j.schedule)} · {j.model === "sonnet" ? "Sonnet" : "Inkling 2 Mini"}
{describe(j.schedule)} · {j.model === "qwen" ? "Inkling 2 Mini" : "Sonnet"}
{j.enabled ? "" : " · paused"}
</span>
</Link>
@@ -7,7 +7,7 @@
/**
* How many scheduled jobs of their own each guest may have, and the model
* a new one starts on ("qwen" | "sonnet").
* a new one starts on ("sonnet" | "qwen").
*/
export interface GuestCronLimitsOut {
maxJobs?: number;
+16
View File
@@ -1848,6 +1848,22 @@ export async function handle(url: URL, init: RequestInit | undefined, request?:
return json({ revoked });
}
}
// A guest's own scheduled jobs (Settings → Scheduled jobs, backend
// cron/guests.py) — read-only here: one job, and the policy's default model.
if (p === "/api/me/cron" && method === "GET") {
const dm = (guestDefaults as { cronLimits?: { defaultModel?: string } }).cronLimits?.defaultModel;
return json({
jobs: [
{
id: "dom-revue-de-presse", owner: "dom", name: "Revue de presse", schedule: "15 8 * * 1-5",
enabled: true, prompt: "Les 5 nouvelles cinéma du jour, en français.", model: "sonnet",
project: null, email: true, mailHtml: "", allow: [], effort: "",
nextRun: "2026-11-30T08:15+01:00", lastStatus: "ok", createdAt: "2026-11-20T09:00:00", runs: [],
},
],
limits: { maxJobs: 5, defaultModel: dm === "qwen" ? "qwen" : "sonnet" },
});
}
if (p === "/api/guest-defaults") {
if (method === "PUT") {
const patch = await body<Partial<GuestDefaults>>();