Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Show session-tied crons as ongoing work in the web UI (#1711)

Joshua France4becece43f20
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.ts
index 64a34529a..603aa41d3 100644
--- a/plugins/web-ui/src/chat.ts
+++ b/plugins/web-ui/src/chat.ts
@@ -179,6 +179,7 @@ import {
backgroundLabel,
clearWorking,
conversationBackground,
+ cronRowMeta,
isAbandonedNewChat,
shouldStartProactiveOpener,
markWorking,
@@ -2412,20 +2413,12 @@ export function createChatSurface(
<a class="bg-row-head" href=${deepLinkPath(UI_BASE, "crons", null, null, c.id)}>
${icon(Clock3, 13)}
<span class="bg-row-cmd">Cron: <bdi>${c.title ?? "scheduled task"}</bdi></span>
- <span class="bg-row-meta">${c.nextFireAt ? `next fire ${nextFireIn(c.nextFireAt)}` : "paused"}</span>
+ <span class="bg-row-meta">${cronRowMeta(c)}</span>
</a>
</div>
`;
}
- function nextFireIn(at: number): string {
- const mins = Math.round((at - Date.now()) / 60_000);
- if (mins <= 0) return "due now";
- if (mins < 60) return `in ${mins}m`;
- if (mins < 1440) return `in ${Math.floor(mins / 60)}h ${String(mins % 60).padStart(2, "0")}m`;
- return `in ${Math.floor(mins / 1440)}d`;
- }
-
function backgroundWatchRow(w: SessionBackgroundView["watches"][number]): TemplateResult {
const what = w.pattern ? `output matching /${w.pattern}/` : "any new output";
const note = w.instructions?.trim();
diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.ts
index da8e7a1c1..4c0bd8075 100644
--- a/plugins/web-ui/src/core-bridge.ts
+++ b/plugins/web-ui/src/core-bridge.ts
@@ -221,7 +221,12 @@ export interface SessionBackgroundView {
expiresAt: number;
lastFiredAt?: number;
}>;
- crons: Array<{ id: string; title?: string; nextFireAt?: number }>;
+ crons: Array<{
+ id: string;
+ title?: string;
+ nextFireAt?: number;
+ lastFire?: { firedAt: number; status?: string };
+ }>;
}
export interface SessionBackgroundOutput {
diff --git a/plugins/web-ui/src/session-list.ts b/plugins/web-ui/src/session-list.ts
index 6fa2964de..ccf10342b 100644
--- a/plugins/web-ui/src/session-list.ts
+++ b/plugins/web-ui/src/session-list.ts
@@ -1,4 +1,10 @@
-import { sharedContextLabel, type CoreContext, type CoreProject, type CoreSession } from "./core-bridge.ts";
+import {
+ sharedContextLabel,
+ type CoreContext,
+ type CoreProject,
+ type CoreSession,
+ type SessionBackgroundView,
+} from "./core-bridge.ts";
import { subagentCounts } from "./subagent-activity.ts";
import { relTime } from "./ui.ts";
@@ -260,3 +266,18 @@ export function shouldStartProactiveOpener(state: {
!state.sessions.some((session) => session.id && !session.threadRef.startsWith("cron:"))
);
}
+
+export function cronRowMeta(c: SessionBackgroundView["crons"][number]): string {
+ const next = c.nextFireAt ? `next fire ${nextFireIn(c.nextFireAt)}` : "paused";
+ if (!c.lastFire) return next;
+ if (c.lastFire.status === "running") return `${next} · running now`;
+ return `${next} · last ${c.lastFire.status ?? "fired"} ${relTime(c.lastFire.firedAt)}`;
+}
+
+function nextFireIn(at: number): string {
+ const mins = Math.round((at - Date.now()) / 60_000);
+ if (mins <= 0) return "due now";
+ if (mins < 60) return `in ${mins}m`;
+ if (mins < 1440) return `in ${Math.floor(mins / 60)}h ${String(mins % 60).padStart(2, "0")}m`;
+ return `in ${Math.floor(mins / 1440)}d`;
+}
diff --git a/plugins/web-ui/test/session-list.test.ts b/plugins/web-ui/test/session-list.test.ts
index 4b5a1e826..61900601a 100644
--- a/plugins/web-ui/test/session-list.test.ts
+++ b/plugins/web-ui/test/session-list.test.ts
@@ -2,6 +2,7 @@ import { test } from "node:test";
import assert from "node:assert/strict";
import {
activityOf,
+ cronRowMeta,
sidebarSessions,
applySessionState,
isAbandonedNewChat,
@@ -549,3 +550,17 @@ test("sidebar excludes attached subagents including pinned and orphaned children
const detached = saved("detached", "agent:main:subagent:detached");
assert.deepEqual(sidebarSessions([parent, child, pinned, orphan, detached]), [parent, detached]);
});
+
+test("cronRowMeta shows the next fire and the last result of a session's cron", () => {
+ const now = Date.now();
+ assert.equal(cronRowMeta({ id: "c", nextFireAt: now + 10 * 60_000 + 1_000 }), "next fire in 10m");
+ assert.equal(
+ cronRowMeta({
+ id: "c",
+ nextFireAt: now + 5 * 60_000 + 1_000,
+ lastFire: { firedAt: now - 3 * 60_000, status: "ok" },
+ }),
+ "next fire in 5m · last ok 3m ago",
+ );
+ assert.equal(cronRowMeta({ id: "c", lastFire: { firedAt: now - 1_000, status: "running" } }), "paused · running now");
+});
diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.ts
index f66b768de..fb0d46a06 100644
--- a/src/api/agent-api-catalog.ts
+++ b/src/api/agent-api-catalog.ts
@@ -319,7 +319,7 @@ const FAMILIES: AgentApiFamily[] = [
method: "POST",
path: "/v1/crons",
summary:
- 'schedule future or recurring work — a 2-5 word `title` naming what the cron is for (distinctive in a list, not the command) plus `task` (re-run at fire time) or exact `text`, optionally addressed by name to a teammate (`recipient`), a channel (`channel`), or a group DM (`participants`: its other members, which must already exist as a group DM — reach it once first, which opens it; same venue rule as /v1/reach — narrowest audience, a channel only when explicitly requested or genuinely room-wide), or run privately for whoever asked at their own scope (`scope:"personal"`, even from a channel); pass `unfurlLinks:false` to suppress Slack previews (to send now instead, use /v1/reach)',
+ 'schedule future or recurring work — a 2-5 word `title` naming what the cron is for (distinctive in a list, not the command) plus `task` (re-run at fire time) or exact `text`, optionally addressed by name to a teammate (`recipient`), a channel (`channel`), or a group DM (`participants`: its other members, which must already exist as a group DM — reach it once first, which opens it; same venue rule as /v1/reach — narrowest audience, a channel only when explicitly requested or genuinely room-wide), or run privately for whoever asked at their own scope (`scope:"personal"`, even from a channel); pass `unfurlLinks:false` to suppress Slack previews; the cron is tied to this conversation so it shows as ongoing work here unless `session:false` (to send now instead, use /v1/reach)',
},
{ method: "GET", path: "/v1/crons", summary: "list your crons" },
{
diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.ts
index a1ac429c8..911875375 100644
--- a/src/api/app-sessions.ts
+++ b/src/api/app-sessions.ts
@@ -18,6 +18,7 @@ import { swallowAs } from "../util/errors.ts";
import { SEARCH_HIT_LIMIT, entrySearchText, searchSnippet, searchTerms } from "../sessions/entry-search.ts";
import { supportsProcessSessions } from "../sandbox/sandbox.ts";
import { processIsGone } from "../sandbox/process-poll.ts";
+import { cronIsActive, cronTiedTo } from "../cron/cron-store.ts";
import { cronRef, deployRef, encodeRef, fileRef, parseRef, skillRef } from "../acl/resource-ref.ts";
import { samePerson } from "../directory/person.ts";
import { AdminError } from "../admin/admin-service.ts";
@@ -427,8 +428,10 @@ export function createSessionMethods(
}
const cronCounts = new Map<string, number>();
for (const c of await deps.crons.list()) {
- if (!c.enabled || c.archived || !c.destination) continue;
- cronCounts.set(c.destination.target, (cronCounts.get(c.destination.target) ?? 0) + 1);
+ if (!cronIsActive(c)) continue;
+ for (const ref of new Set([c.destination?.target, c.sessionRef])) {
+ if (ref) cronCounts.set(ref, (cronCounts.get(ref) ?? 0) + 1);
+ }
}
const failedChildren = new Set<string>();
for (const s of sessions) {
@@ -510,14 +513,20 @@ export function createSessionMethods(
expiresAt: m.expiresAt,
...(m.lastFiredAt !== undefined ? { lastFiredAt: m.lastFiredAt } : {}),
}));
- const crons = (await deps.crons.list())
- .filter((c) => c.enabled && !c.archived && c.destination?.target === session.threadRef)
- .sort((a, b) => b.createdAt - a.createdAt)
- .map((c) => ({
- id: c.id,
- ...(c.title !== undefined ? { title: c.title } : {}),
- ...(c.nextFireAt !== undefined ? { nextFireAt: c.nextFireAt } : {}),
- }));
+ const crons = await Promise.all(
+ (await deps.crons.list())
+ .filter((c) => cronIsActive(c) && cronTiedTo(c, session.threadRef))
+ .sort((a, b) => b.createdAt - a.createdAt)
+ .map(async (c) => {
+ const last = (await deps.crons.listFires(c.id, { limit: 1 })).runs[0];
+ return {
+ id: c.id,
+ ...(c.title !== undefined ? { title: c.title } : {}),
+ ...(c.nextFireAt !== undefined ? { nextFireAt: c.nextFireAt } : {}),
+ ...(last ? { lastFire: { firedAt: last.firedAt, ...(last.status ? { status: last.status } : {}) } } : {}),
+ };
+ }),
+ );
return { jobs, watches, crons };
},
diff --git a/src/api/app-types.ts b/src/api/app-types.ts
index 2db10afdc..a802f1336 100644
--- a/src/api/app-types.ts
+++ b/src/api/app-types.ts
@@ -228,7 +228,12 @@ interface SessionBackgroundView {
expiresAt: number;
lastFiredAt?: number;
}>;
- crons: Array<{ id: string; title?: string; nextFireAt?: number }>;
+ crons: Array<{
+ id: string;
+ title?: string;
+ nextFireAt?: number;
+ lastFire?: { firedAt: number; status?: CronFireLogEntry["status"] };
+ }>;
}
interface SessionBackgroundOutput {
diff --git a/src/api/control-service.ts b/src/api/control-service.ts
index d190c0657..e8191dc77 100644
--- a/src/api/control-service.ts
+++ b/src/api/control-service.ts
@@ -44,6 +44,7 @@ export interface CronCreateRequest {
runAs?: "owner" | "scopeFloor" | "scopeShared";
unfurlLinks?: boolean;
unattendedGrants?: string[];
+ session?: boolean;
}
export type CronCreateResult =
@@ -95,6 +96,7 @@ export interface CronPatchRequest {
unfurlLinks?: boolean;
runAs?: "owner" | "scopeFloor" | "scopeShared";
unattendedGrants?: string[];
+ session?: boolean;
}
export interface CronRunsRequest {
@@ -108,7 +110,7 @@ export interface CronRunsResult {
}
export const CRON_PATCH_NOTHING_TO_CHANGE =
- "nothing to change — pass title, task, schedule, enabled, archived, unfurlLinks, runAs, or unattendedGrants";
+ "nothing to change — pass title, task, schedule, enabled, archived, unfurlLinks, runAs, unattendedGrants, or session";
export const CRON_FIRE_NOTE_MAX_CHARS = 400;
@@ -228,10 +230,18 @@ function hasCronPatchField(req: CronPatchRequest): boolean {
req.archived !== undefined ||
req.unfurlLinks !== undefined ||
req.runAs !== undefined ||
- req.unattendedGrants !== undefined
+ req.unattendedGrants !== undefined ||
+ req.session !== undefined
);
}
+function liveSessionRef(
+ capability: Pick<CapabilityClaims, "threadRef" | "triggered" | "scopeId">,
+ cronScopeId: string,
+): string | undefined {
+ return capability.triggered || capability.scopeId !== cronScopeId ? undefined : capability.threadRef;
+}
+
function cronPatchChanges(before: Cron, patch: CronPatch): boolean {
return (Object.entries(patch) as Array<[keyof CronPatch, unknown]>).some(
([key, value]) => !isDeepStrictEqual(before[key as keyof Cron], value),
@@ -315,7 +325,16 @@ async function patchFromCronPatchRequest(
message: "unfurlLinks can only be set on a cron with a delivery destination",
};
}
+ const sessionRef = req.session ? liveSessionRef(capability, before.ownerScopeId) : undefined;
+ if (req.session && !sessionRef) {
+ return {
+ ok: false,
+ code: "bad_request",
+ message: "session:true needs a live conversation in the cron's own scope to tie it to",
+ };
+ }
return {
+ ...(req.session !== undefined && sessionRef !== before.sessionRef ? { sessionRef: sessionRef ?? null } : {}),
...(req.runtime !== undefined ? { runtime: req.runtime } : {}),
...(req.title !== undefined ? { title: req.title } : {}),
...(req.action !== undefined ? { action: req.action } : {}),
@@ -544,6 +563,8 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
...(runAs === "scopeShared" && openShared ? { ownerResourcesRequireOpen: true } : {}),
...(req.unattendedGrants !== undefined ? { unattendedGrants: req.unattendedGrants } : {}),
};
+ const sessionRef = req.session === false ? undefined : liveSessionRef(capability, ownerScopeId);
+ if (sessionRef) input.sessionRef = sessionRef;
try {
const cron = await app.createCron(input);
if (consentRecipient) {
@@ -644,6 +665,8 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
if (req.archived !== undefined) changeSummary.push(`archived=${req.archived}`);
if (req.unfurlLinks !== undefined) changeSummary.push(`unfurlLinks=${req.unfurlLinks}`);
if (patch.runAs !== undefined) changeSummary.push(`mode=${patch.runAs}`);
+ if (req.session !== undefined)
+ changeSummary.push(req.session ? "tied to a session" : "untied from its session");
const detail: CronEditDetail =
req.schedule !== undefined ? { schedule: withDefaultTimezone(req.schedule, capability) } : {};
await notifyEdit(cron, capability, changeSummary, detail);
diff --git a/src/api/routes/crons.ts b/src/api/routes/crons.ts
index 43eb82b8e..32fd2411a 100644
--- a/src/api/routes/crons.ts
+++ b/src/api/routes/crons.ts
@@ -49,6 +49,7 @@ type CapabilityCronBody = {
scope?: unknown;
unfurlLinks?: unknown;
unattendedGrants?: unknown;
+ session?: unknown;
};
function taskText(b: CapabilityCronBody): string | undefined {
@@ -108,6 +109,7 @@ function isCronPatch(b: unknown): b is {
unfurlLinks?: boolean;
runAs?: "owner" | "scopeFloor" | "scopeShared";
unattendedGrants?: string[];
+ session?: boolean;
} {
if (!isObj(b) || !isCronRuntime(b.runtime)) return false;
if (!hasCronPatchFields(b)) return true;
@@ -133,6 +135,7 @@ function isCronPatch(b: unknown): b is {
)
return false;
if (hasSchedule && userScheduleFromBody(b.schedule) === null) return false;
+ if (b.session !== undefined && typeof b.session !== "boolean") return false;
return true;
}
@@ -147,7 +150,8 @@ function hasCronPatchFields(b: Record<string, unknown>): boolean {
b.archived !== undefined ||
b.unfurlLinks !== undefined ||
b.runAs !== undefined ||
- b.unattendedGrants !== undefined
+ b.unattendedGrants !== undefined ||
+ b.session !== undefined
);
}
@@ -211,6 +215,7 @@ async function createCron(ctx: ApiCtx): Promise<void> {
...(b.runAs === "owner" || b.runAs === "scopeFloor" || b.runAs === "scopeShared" ? { runAs: b.runAs } : {}),
...(typeof b.unfurlLinks === "boolean" ? { unfurlLinks: b.unfurlLinks } : {}),
...(Array.isArray(b.unattendedGrants) ? { unattendedGrants: b.unattendedGrants } : {}),
+ ...(typeof b.session === "boolean" ? { session: b.session } : {}),
},
capability,
);
@@ -349,7 +354,7 @@ async function cronRuns(ctx: ApiCtx): Promise<void> {
}
const CRON_PATCH_BAD_REQUEST =
- "expected a cron patch: title (string), task (string), schedule, enabled (boolean), archived (boolean), unfurlLinks (boolean), runAs (owner/scopeFloor/scopeShared), and/or unattendedGrants (string[])";
+ "expected a cron patch: title (string), task (string), schedule, enabled (boolean), archived (boolean), unfurlLinks (boolean), runAs (owner/scopeFloor/scopeShared), unattendedGrants (string[]), and/or session (boolean)";
async function cronById(ctx: ApiCtx): Promise<void> {
const { res, app, pathname, method, body, capability } = ctx;
@@ -386,6 +391,7 @@ async function cronById(ctx: ApiCtx): Promise<void> {
...(body.unfurlLinks !== undefined ? { unfurlLinks: body.unfurlLinks } : {}),
...(body.runAs !== undefined ? { runAs: body.runAs } : {}),
...(body.unattendedGrants !== undefined ? { unattendedGrants: body.unattendedGrants } : {}),
+ ...(body.session !== undefined ? { session: body.session } : {}),
},
capability,
);
diff --git a/src/cron/cron-store.ts b/src/cron/cron-store.ts
index b8278510f..b8a59a46c 100644
--- a/src/cron/cron-store.ts
+++ b/src/cron/cron-store.ts
@@ -38,6 +38,7 @@ export interface CreateCronInput extends CreateTriggerInput {
members?: Principal[];
unattendedGrants?: string[];
loopId?: string;
+ sessionRef?: string;
}
export interface CronPatch {
@@ -53,6 +54,7 @@ export interface CronPatch {
runAs?: Cron["runAs"];
ownerResourcesRequireOpen?: boolean;
unattendedGrants?: string[];
+ sessionRef?: string | null;
}
export const DEFAULT_FIRE_RUNNING_STALE_MS = 24 * 60 * 60 * 1000;
@@ -89,6 +91,16 @@ export interface CronStore {
due(now: number): Promise<Array<Cron & { scheduledAt: number }>>;
}
+export function cronIsActive(cron: Pick<Cron, "enabled" | "archived" | "schedule" | "lastFiredAt">): boolean {
+ if (!cron.enabled || cron.archived) return false;
+ const oneShot = cron.schedule.cron === undefined && cron.schedule.everyMs === undefined;
+ return !(oneShot && cron.lastFiredAt !== undefined);
+}
+
+export function cronTiedTo(cron: Pick<Cron, "destination" | "sessionRef">, threadRef: string): boolean {
+ return cron.destination?.target === threadRef || cron.sessionRef === threadRef;
+}
+
export function isDeferred(cron: Pick<Cron, "deferUntil">, now: number): boolean {
return cron.deferUntil !== undefined && now < cron.deferUntil;
}
@@ -140,6 +152,7 @@ export function createCronStore(
...(input.members ? { members: input.members } : {}),
...(input.unattendedGrants ? { unattendedGrants: input.unattendedGrants } : {}),
...(input.loopId ? { loopId: input.loopId } : {}),
+ ...(input.sessionRef ? { sessionRef: input.sessionRef } : {}),
...(input.runtime ? { runtime: input.runtime } : {}),
}));
},
@@ -167,6 +180,7 @@ export function createCronStore(
if (patch.runAs !== undefined) fields.runAs = patch.runAs;
if (patch.ownerResourcesRequireOpen === true) fields.ownerResourcesRequireOpen = true;
if (patch.unattendedGrants !== undefined) fields.unattendedGrants = patch.unattendedGrants;
+ if (patch.sessionRef !== undefined) fields.sessionRef = patch.sessionRef ?? undefined;
return backing.merge(id, fields);
},
delete: (id) => backing.delete(id),
diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.ts
index 8f04bd992..2c55b3b58 100644
--- a/src/harness/agent-tools.ts
+++ b/src/harness/agent-tools.ts
@@ -2362,6 +2362,12 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
destinationKey: Type.Optional(
Type.String({ description: 'create/retarget: a key from the "Where scheduled tasks post" menu.' }),
),
+ session: Type.Optional(
+ Type.Boolean({
+ description:
+ "create/patch: tie the cron to this conversation so it shows as ongoing work here. Created crons are tied by default; pass false to leave it untied, or patch true/false to tie or untie it.",
+ }),
+ ),
unfurlLinks: Type.Optional(
Type.Boolean({
description:
@@ -2464,6 +2470,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
...(params.destinationKey !== undefined ? { destinationKey: params.destinationKey } : {}),
...(params.runAs !== undefined ? { runAs: params.runAs } : {}),
...(params.unfurlLinks !== undefined ? { unfurlLinks: params.unfurlLinks } : {}),
+ ...(params.session !== undefined ? { session: params.session } : {}),
});
if (isUnavailable(r)) return unavailable(callId, "cron");
if (!r.ok) {
@@ -2594,6 +2601,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
...(params.archived !== undefined ? { archived: params.archived } : {}),
...(params.unfurlLinks !== undefined ? { unfurlLinks: params.unfurlLinks } : {}),
...(params.runAs !== undefined ? { runAs: params.runAs } : {}),
+ ...(params.session !== undefined ? { session: params.session } : {}),
});
if (isUnavailable(r)) return unavailable(callId, "cron");
if (!r.ok) return recordResult(callId, { tool: "cron", error: r.code }, text(`[error] ${r.message}`), true);
diff --git a/src/types.ts b/src/types.ts
index f08c55e88..c807bc626 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -289,6 +289,7 @@ export interface Cron extends TriggerBase {
ownerResourcesRequireOpen?: boolean;
members?: Principal[];
unattendedGrants?: string[];
+ sessionRef?: string;
fireLog?: CronFireLogEntry[];
lastFireNote?: CronFireNote;
diff --git a/test/cron-session-link.test.ts b/test/cron-session-link.test.ts
new file mode 100644
index 000000000..f408ecf30
--- /dev/null
+++ b/test/cron-session-link.test.ts
@@ -0,0 +1,103 @@
+import "./support/auto-fake-sprites.ts";
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { buildApp } from "../src/wiring.ts";
+import { createControlService } from "../src/api/control-service.ts";
+import { cronIsActive } from "../src/cron/cron-store.ts";
+import { scopeId, type TurnRequest } from "../src/types.ts";
+import { CAPABILITY_TTL_MS, type CapabilityClaims } from "../src/auth/capability-token.ts";
+import { testConfig } from "./support/test-config.ts";
+
+const THREAD = "web:U1:watching";
+
+function claims(extra: Partial<CapabilityClaims> = {}): CapabilityClaims {
+ return {
+ actorId: "U1",
+ scopeId: scopeId("personal", "U1"),
+ destination: { type: "slack", target: "D1", audienceScopeId: scopeId("personal", "U1") },
+ exp: Date.now() + CAPABILITY_TTL_MS,
+ threadRef: THREAD,
+ ...extra,
+ };
+}
+
+function dm(text: string, threadRef: string): TurnRequest {
+ return { surface: "test", actor: { externalId: "U1" }, conversation: { kind: "dm", threadRef }, text };
+}
+
+async function setup() {
+ const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "cron-session-")) }));
+ const control = createControlService(built.app, built.scheduler, built.admin);
+ const session = await built.app.turn(dm("watch CI for me", THREAD));
+ await built.app.turn(dm("unrelated", "web:U1:other"));
+ return { built, control, sessionId: session.sessionId! };
+}
+
+const watch = { schedule: { everyMs: 600_000 }, action: "check CI", title: "CI watch" };
+
+test("a cron created from a live session is tied to it and shows as that session's background work", async () => {
+ const { built, control, sessionId } = await setup();
+ const created = await control.createCron(watch, claims());
+ assert.ok(created.ok, JSON.stringify(created));
+ assert.equal(created.cron.sessionRef, THREAD);
+ assert.equal(created.cron.destination?.target, "D1", "delivery stays where it was addressed");
+
+ const list = await built.app.listSessions("U1");
+ assert.equal(list.find((s) => s.threadRef === THREAD)?.crons, 1);
+ assert.ok(!list.find((s) => s.threadRef === "web:U1:other")?.crons);
+
+ await built.crons.recordFire(created.cron.id, {
+ fireKey: "f1",
+ threadRef: `cron:${created.cron.id}:fire:1`,
+ firedAt: 1_000,
+ status: "ok",
+ });
+ const bg = await built.app.sessionBackground(sessionId, "U1");
+ assert.deepEqual(bg?.crons, [
+ {
+ id: created.cron.id,
+ title: "CI watch",
+ nextFireAt: created.cron.nextFireAt,
+ lastFire: { firedAt: 1_000, status: "ok" },
+ },
+ ]);
+
+ await control.patchCron(created.cron.id, { enabled: false }, claims());
+ assert.ok(!(await built.app.listSessions("U1")).find((s) => s.threadRef === THREAD)?.crons, "paused crons drop off");
+});
+
+test("session:false and triggered turns leave a cron untied, and patch ties or unties it", async () => {
+ const { built, control } = await setup();
+ const untied = await control.createCron({ ...watch, session: false }, claims());
+ assert.ok(untied.ok && untied.cron.sessionRef === undefined);
+ const elsewhere = await control.patchCron(
+ untied.cron.id,
+ { session: true },
+ claims({ scopeId: scopeId("channel", "C9") }),
+ );
+ assert.equal(elsewhere.ok ? "" : elsewhere.code, "bad_request", "a cron only ties to sessions in its own scope");
+ const fromFire = await control.createCron({ ...watch, title: "Fire child" }, claims({ triggered: true }));
+ assert.ok(fromFire.ok && fromFire.cron.sessionRef === undefined);
+
+ const noop = await control.patchCron(untied.cron.id, { session: false }, claims());
+ assert.ok(noop.ok && noop.cron.sessionRef === undefined);
+ const tied = await control.patchCron(untied.cron.id, { session: true }, claims());
+ assert.ok(tied.ok && tied.cron.sessionRef === THREAD);
+ const refused = await control.patchCron(untied.cron.id, { session: true }, claims({ threadRef: undefined }));
+ assert.equal(refused.ok ? "" : refused.code, "bad_request");
+ const cleared = await control.patchCron(untied.cron.id, { session: false }, claims());
+ assert.ok(cleared.ok && cleared.cron.sessionRef === undefined);
+ assert.ok(!(await built.app.listSessions("U1")).find((s) => s.threadRef === THREAD)?.crons);
+});
+
+test("a one-shot cron stops counting as active once it has fired", () => {
+ const base = { enabled: true, archived: false, schedule: { firstFireAt: 5 } };
+ assert.equal(cronIsActive(base), true);
+ assert.equal(cronIsActive({ ...base, lastFiredAt: 6 }), false);
+ assert.equal(cronIsActive({ ...base, schedule: { everyMs: 60_000, firstFireAt: 5 }, lastFiredAt: 6 }), true);
+ assert.equal(cronIsActive({ ...base, archived: true }), false);
+});