From c5dff1335e58e8489a8d2bbd98da613007f1d93b Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 20 Nov 2026 16:44:33 +0100 Subject: [PATCH] My tasks review fixes: the room, pool takers, job starts and the planner count a runner only for the task of the step asked about (a queued job whose repo has takers but none that takes its task says "No Task Runner takes tasks on "), a call of a task no ready runner takes is not counted as a call ahead, and task saves on the Connect page run one after another with only the latest setting the boxes Co-Authored-By: Claude Opus 5.5 --- docs/operations.md | 2 +- src/agents/call.ts | 15 +++++++++------ src/remote/queue-view.ts | 3 ++- src/remote/room.ts | 17 +++++++++-------- src/runner/autopilot.ts | 17 +++++++++++------ src/runner/concurrency.ts | 24 +++++++++++++++++------- src/runner/jobs.ts | 4 ++-- src/runner/runner.ts | 8 ++++---- test/planner-taker.test.ts | 22 +++++++++++++++++++++- test/remote-room-repos.test.ts | 21 +++++++++++++++++++++ web/src/modules/connect/MySettings.tsx | 23 +++++++++++++++-------- 11 files changed, 112 insertions(+), 44 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 0f20f21f..452fab3d 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -391,7 +391,7 @@ A call goes to a maintainer or operator whose cached GitHub permission is `write | Submit | A failed reply (`ok: false`, error `helper: `) or a reply from another model family than claimed sends the call back to the queue with its next attempt, not offered to that login for 10 minutes; it fails when the prompt's attempts are used up. A submit repeated after an accepted one is accepted again. | | Ended lease | Every lease route answers 410 for a secret whose lease was submitted, failed, expired, released or sent back to the queue (the secret hashes are kept 24 hours), and 401 only for a secret never issued; a 410 does not count toward the failed-authentication limit. | | Caller gone | A queued or leased call whose job stopped polling for 5 minutes fails. | -| No taker | A taker of a call is a Task Runner that reported `ready` in the last 6 minutes, whose user is not cooling off, and that may take the call: the role rules, write permission (only a non-write permission confirmed within 10 minutes leaves a user out) and My repos narrowed by the Task Runner's own list, and My tasks. Busy Task Runners count, and so do Manual only ones (their user may pick the call), though they are no room. Once a minute the dashboard marks each queued call with a live caller that has no taker; a call marked for 10 minutes is withdrawn ("no Task Runner can take calls on ", or "… of the task (My tasks)" when a taker of its repos has unticked its task). A taker that comes back clears the mark. Follow-up turns and calls with a pick that counts keep their own rules. The pool unit that made the call is skipped: no failure, no failure backoff and no attempt against its item; the job counts it as a skipped item, so the planner runs the step again. A job that the withdrawal ends finishes as done ("skipped: …"). Pools never start a unit with no taker, and the runner leaves a queued job of a step that calls Claude queued while its repo has no taker. The planner proposes no such job (the stage's status and the repo's items on the Next page read "No Task Runner takes "); one already queued, for example an operator's, stays queued with that reason in the Jobs list and on the job page, and holds neither a repo of `step_parallel` nor part of the daily limit. The planner runs again when the set of Task Runners or their repos changes. | +| No taker | A taker of a call is a Task Runner that reported `ready` in the last 6 minutes, whose user is not cooling off, and that may take the call: the role rules, write permission (only a non-write permission confirmed within 10 minutes leaves a user out) and My repos narrowed by the Task Runner's own list, and My tasks. Busy Task Runners count, and so do Manual only ones (their user may pick the call), though they are no room. Once a minute the dashboard marks each queued call with a live caller that has no taker; a call marked for 10 minutes is withdrawn ("no Task Runner can take calls on ", or "… of the task (My tasks)" when a taker of its repos has unticked its task). A taker that comes back clears the mark. Follow-up turns and calls with a pick that counts keep their own rules. The pool unit that made the call is skipped: no failure, no failure backoff and no attempt against its item; the job counts it as a skipped item, so the planner runs the step again. A job that the withdrawal ends finishes as done ("skipped: …"). Pools never start a unit with no taker, and the runner leaves a queued job of a step that calls Claude queued while its repo has no taker that takes the step's task; the room the runner and pools count is that of such takers too. The planner proposes no such job (the stage's status and the repo's items on the Next page read "No Task Runner takes ", or "No Task Runner takes tasks on " when the takers of the repo have unticked its task); one already queued, for example an operator's, stays queued with that reason in the Jobs list and on the job page, and holds neither a repo of `step_parallel` nor part of the daily limit. The planner runs again when the set of Task Runners or their repos changes. | | Waiting | The runner leaves at most 12 hours of queue time out of a job's deadline and no-progress stop; a call still queued after that is withdrawn ("no Task Runner took the call in time") and the job stops. | Ended calls are kept 24 hours for task status and follow-ups; the dashboard deletes older ones once a minute. diff --git a/src/agents/call.ts b/src/agents/call.ts index 65dc6094..cdb2f20a 100644 --- a/src/agents/call.ts +++ b/src/agents/call.ts @@ -146,16 +146,19 @@ const callRepos = (repos: readonly string[] | undefined): readonly string[] | un * above the class and that those Task Runners may take (src/remote/room.ts). */ export function queueRoom(db: DatabaseSync, cls: 0 | 1 | 2 = currentClass(), repos?: readonly string[]): number { - if (inferenceMode(db) === "user-local") return remoteRoom(db, cls, Date.now(), callRepos(repos)); + if (inferenceMode(db) === "user-local") return remoteRoom(db, cls, Date.now(), callRepos(repos), context?.step); const ahead = (db.prepare("SELECT COUNT(*) AS n FROM model_waits WHERE provider = 'claude' AND eligible = 1 AND seen_at >= ? AND class >= ?").get(Date.now() - allocation.staleMs, cls) as { n: number }).n; return Math.max(0, freeSlots(db) - Number(ahead)); } -/** Room questions answered from one reading of the helpers (queueRoomPass). */ +/** + * Room questions answered from one reading of the helpers (queueRoomPass). `step`: the step of the calls asked about, for the + * tasks the runners take (src/remote/my-tasks.ts); left out, the current job's step (none outside a job: every task counts). + */ export type RoomPass = { - room(cls: 0 | 1 | 2, repos?: readonly string[]): number; + room(cls: 0 | 1 | 2, repos?: readonly string[], step?: string): number; /** Whether a call naming `repos` has a taker (src/remote/takers.ts; always in the server-account mode). A call naming no repo (none given and no job repo) has one only in an operator's Task Runner, as the sweep reads it. */ - taker(repos?: readonly string[]): boolean; + taker(repos?: readonly string[], step?: string): boolean; }; /** queueRoom for many questions at one moment (the runner's pass over queued jobs, a pool's round): in the user-local mode the helpers, their permissions and repos are read once. */ @@ -167,8 +170,8 @@ export function queueRoomPass(db: DatabaseSync): RoomPass { // The taker rule of src/remote/takers.ts, read once per pass. const takes = takerTest(db, nowMs); return { - room: (cls, repos) => roomOf(db, state(), cls, nowMs, callRepos(repos)), - taker: (repos) => takes({ prompt_id: "", repos: callRepos(repos) ?? [] }), + room: (cls, repos, step = context?.step) => roomOf(db, state(), cls, nowMs, callRepos(repos), step), + taker: (repos, step = context?.step) => takes({ prompt_id: "", repos: callRepos(repos) ?? [], step }), }; } diff --git a/src/remote/queue-view.ts b/src/remote/queue-view.ts index d9414554..2cfae7a9 100644 --- a/src/remote/queue-view.ts +++ b/src/remote/queue-view.ts @@ -104,7 +104,8 @@ export function queueView(db: DatabaseSync, nowMs: number, showPicker: boolean, const followUp = r.parent_id !== null; const n = ahead.get(r.tier) ?? 0; const why = whyWaiting({ tier: r.tier, promptId: r.prompt_id, step: r.step, repos: r.repos, followUp, picked: picked === null ? null : { login: showPicker ? picked : null } }, runners, n, canWrite); - if (!followUp && picked === null) ahead.set(r.tier, n + 1); + // A call of a task no ready runner takes is passed over, so it is no call ahead of the next. + if (!followUp && picked === null && why.code !== "task-off") ahead.set(r.tier, n + 1); calls.push({ id: r.id, step: r.step, promptId: r.prompt_id, tier: r.tier, model: x.asked_model, refs: r.refs, repos: r.repos, authors: r.authors, waitedMs: Number(x.queued_ms) + (x.queued_since === null ? 0 : Math.max(0, nowMs - Number(x.queued_since))), followUp, gating: gating(r), diff --git a/src/remote/room.ts b/src/remote/room.ts index 791d4ae8..29c1c9d0 100644 --- a/src/remote/room.ts +++ b/src/remote/room.ts @@ -17,7 +17,7 @@ import { STATUS_FRESH_MS } from "./helpers.ts"; import { manualSql } from "./manual-only.ts"; import { userMaxCalls } from "./max-calls.ts"; import { claimRepos } from "./my-repos.ts"; -import { userSkips } from "./my-tasks.ts"; +import { taskOfStep, userSkips } from "./my-tasks.ts"; import { scaled } from "./time-scale.ts"; import { HEARTBEAT_S } from "./protocol.ts"; @@ -33,7 +33,7 @@ const LIVE_LEASE_MS = 3 * scaled(HEARTBEAT_S * 1000); /** * Room for calls of class `cls` that name `repos` (undefined: any repo, every helper counts; empty: no repo, which only - * operators take). A helper's fast-lane slot takes only small-tier and gating calls, and the planner does not + * operators take) and are of `step` (only helpers whose users take its task count; undefined: every task). A helper's fast-lane slot takes only small-tier and gating calls, and the planner does not * know which calls it is about to make, so the fast lane is not room. The status names no fast lane: a helper reporting 2 * or more slots is taken to run one (work adds it to `--parallel N`, except for a harness that runs one call at a time, * which reports 1, and on macOS at `--parallel 16`, which this undercounts by one). A lease in the fast lane is not told @@ -44,8 +44,8 @@ const LIVE_LEASE_MS = 3 * scaled(HEARTBEAT_S * 1000); * lately still gets calls; the claim then checks the permission itself. The helper's repos are those of its last idle claim * (`idle_repos`) narrowed by the user's current My repos. */ -export function remoteRoom(db: DatabaseSync, cls: number, nowMs: number = Date.now(), repos?: readonly string[]): number { - return roomOf(db, roomState(db, nowMs), cls, nowMs, repos); +export function remoteRoom(db: DatabaseSync, cls: number, nowMs: number = Date.now(), repos?: readonly string[], step?: string): number { + return roomOf(db, roomState(db, nowMs), cls, nowMs, repos, step); } /** @@ -90,13 +90,14 @@ function takersOf(db: DatabaseSync, st: RoomState, nowMs: number): NonNullable boolean = () => true; - if (repos !== undefined && st.active.length) { + if ((repos !== undefined || step !== undefined) && st.active.length) { const t = takersOf(db, st, nowMs); - const fit = t.list.filter(({ active, r }) => active && runnerTakes(r, { prompt_id: "", repos }, t.canWrite)); + const task = step === undefined ? undefined : taskOfStep(step); + const fit = t.list.filter(({ active, r }) => active && (repos === undefined ? !(task !== undefined && r.skip.has(task)) : runnerTakes(r, { prompt_id: "", repos, step }, t.canWrite))); takers = fit.map((x) => x.h); takes = (c) => fit.some(({ r }) => runnerTakes(r, c, t.canWrite)); } diff --git a/src/runner/autopilot.ts b/src/runner/autopilot.ts index 48e3b714..a0394c71 100644 --- a/src/runner/autopilot.ts +++ b/src/runner/autopilot.ts @@ -55,7 +55,7 @@ import { takerSignature } from "../remote/takers.ts"; import { tripReasonOfStep } from "../push-outcomes.ts"; import { STEP_STAGE } from "../core/push-outcome.ts"; import { NO_TAKER_SKIP } from "./leases.ts"; -import { jobBlock, noRunnerFor, stepParallel, untakenTest, type Active, type UntakenTest } from "./concurrency.ts"; +import { jobBlock, stepParallel, untakenTest, type Active, type UntakenTest } from "./concurrency.ts"; import { knownStep, loadSteps, STEPS, modelsOf, usesClaude, type Params, type StepDef } from "./steps.ts"; import { pilotItems, scopeRepos } from "../pilot.ts"; import { refreshOutsideHolds } from "../outside.ts"; @@ -922,7 +922,8 @@ export async function detectAutopilot(db: DatabaseSync, opts: PlanOptions = {}): if (jobBlock(db, steps, { step: stepName, repo: repo0, number: typeof params.number === "number" ? params.number : null }, { extra: pending, precheck, untaken })) return null; const reason = pausedWhy(stepName); if (reason) { note(stepName, reason); return null; } - if (repo0 !== null && untaken({ step: stepName, repo: repo0, params })) { note(stepName, noRunnerFor(repo0)); return null; } + const waits = repo0 === null ? null : untaken({ step: stepName, repo: repo0, params }); + if (waits !== null) { note(stepName, waits); return null; } if (lane) { const repo = typeof params.repo === "string" ? params.repo : null; const fp = fingerprintOf(db, lane, stepName, params, seqs); @@ -1140,10 +1141,14 @@ export function laneItems(db: DatabaseSync, ctx: PlanCtx, lane: Pick(), all: LaneItem[] = []; // A repo whose jobs of every step of the lane wait for a Task Runner: the planner proposes none for it. - const untaken = (ctx.untaken ??= untakenTest(db)), noRunner = new Map(); - const waits = (repo: string): boolean => { + const untaken = (ctx.untaken ??= untakenTest(db)), noRunner = new Map(); + // Why the repo's jobs wait (the first step's reason), or null when some step of the lane has a taker. + const waits = (repo: string): string | null => { let w = noRunner.get(repo); - if (w === undefined) noRunner.set(repo, (w = !!lane.steps?.length && lane.steps.every((step) => untaken({ step, repo })))); + if (w === undefined) { + const why = lane.steps?.map((step) => untaken({ step, repo })) ?? []; + noRunner.set(repo, (w = why.length > 0 && why.every((x) => x !== null) ? why[0]! : null)); + } return w; }; const add = (f: Planned["facts"] | PlannedItem["facts"], state: string, a: Action) => { @@ -1151,7 +1156,7 @@ export function laneItems(db: DatabaseSync, ctx: PlanCtx, lane: Pick= FAST_FLOOR; all.push({ repo: f.repo, number: f.number, kind: "kind" in f ? f.kind : "pr", action: a.kind, bucket: typeof a.params?.bucket === "string" ? a.params.bucket : null, diff --git a/src/runner/concurrency.ts b/src/runner/concurrency.ts index 3239736e..5fb9d0cf 100644 --- a/src/runner/concurrency.ts +++ b/src/runner/concurrency.ts @@ -4,6 +4,7 @@ import type { DatabaseSync } from "node:sqlite"; import { audit } from "../dash/audit.ts"; import { inferenceMode } from "../remote/mode.ts"; +import { taskOfStep, TASK_CHOICES } from "../remote/my-tasks.ts"; import { takerTest } from "../remote/takers.ts"; import { knownStep, modelsOf, usesClaude, type Params, type StepDef } from "./steps.ts"; @@ -48,19 +49,25 @@ export function activeJobs(db: DatabaseSync, states: ("queued" | "running")[] = /** A job or proposal as untakenTest reads it: `params` as an object or the stored JSON. */ export type JobOfRepo = { step: string; repo: string | null; params?: Params | string | null }; -/** Whether a job waits for a Task Runner: see untakenTest. */ -export type UntakenTest = (j: JobOfRepo) => boolean; +/** Why a job waits for a Task Runner, or null when it does not: see untakenTest. */ +export type UntakenTest = (j: JobOfRepo) => string | null; /** The reason a job of `repo` waits: shown for the step, the lane's items and the queued job. */ export const noRunnerFor = (repo: string): string => `No Task Runner takes ${repo}`; +/** The reason a job of `step` on `repo` waits when Task Runners take the repo but none takes the step's task (My tasks). */ +export const noRunnerForTask = (repo: string, step: string): string => { + const task = taskOfStep(step); + return `No Task Runner takes ${TASK_CHOICES.find((t) => t.id === task)?.title ?? task} tasks on ${repo}`; +}; /** - * Whether a job waits for a Task Runner: in the user-local mode, a job of a step that calls Claude, for a repo no Task Runner - * may take now (src/remote/takers.ts, the rule the runner's job starts and the pools use). The runners are read once, on the - * first such job, so one test serves a whole pass. Never in the server-account mode, nor for a job with no repo. + * Why a job waits for a Task Runner, or null: in the user-local mode, a job of a step that calls Claude, for a repo no Task + * Runner may take now or whose step's task none of those takes (src/remote/takers.ts, the rule the runner's job starts and the + * pools use). The runners are read once, on the first such job, so one test serves a whole pass. Never in the server-account + * mode, nor for a job with no repo. */ export function untakenTest(db: DatabaseSync, steps?: Map, nowMs: number = Date.now()): UntakenTest { - if (inferenceMode(db) !== "user-local") return () => false; + if (inferenceMode(db) !== "user-local") return () => null; const takes = takerTest(db, nowMs); const claude = (j: JobOfRepo): boolean => { let params: Params = {}; @@ -68,7 +75,10 @@ export function untakenTest(db: DatabaseSync, steps?: Map, nowM else if (j.params) params = j.params; return usesClaude(modelsOf(steps?.get(j.step) ?? knownStep(j.step), params)); }; - return (j) => j.repo !== null && claude(j) && !takes({ prompt_id: "", repos: [j.repo] }); + return (j) => { + if (j.repo === null || !claude(j) || takes({ prompt_id: "", repos: [j.repo], step: j.step })) return null; + return takes({ prompt_id: "", repos: [j.repo] }) ? noRunnerForTask(j.repo, j.step) : noRunnerFor(j.repo); + }; } /** Two jobs of one step do the same work: the same repo (and finding), or one of them is not about a single repo. */ diff --git a/src/runner/jobs.ts b/src/runner/jobs.ts index 3d7548e8..fe758a14 100644 --- a/src/runner/jobs.ts +++ b/src/runner/jobs.ts @@ -11,7 +11,7 @@ import { knownStep, loadSteps, modelsOf, ParamError, validateParams, type StepDe import { shownLookup } from "../dash/api/shown.ts"; import { blankIfHidden } from "../dash/api/visible.ts"; import { withdrawJobCalls } from "../remote/calls.ts"; -import { noRunnerFor, untakenTest, type UntakenTest } from "./concurrency.ts"; +import { untakenTest, type UntakenTest } from "./concurrency.ts"; export const JOB_STATES: JobState[] = ["queued", "running", "done", "failed", "cancelled"]; /** Error text of jobs ended by a runner stop or restart; the autopilot does not count them as failures. */ @@ -58,7 +58,7 @@ export function toJob(r: JobRow, accounts: string[] = [], waiting: string | null export function toJobs(db: DatabaseSync, rows: JobRow[]): Job[] { const labels = accountLabelsByJob(db, rows.map((r) => r.id)); let untaken: UntakenTest | undefined; - return rows.map((r) => toJob(r, labels.get(r.id), r.state === "queued" && r.repo !== null && (untaken ??= untakenTest(db))(r) ? noRunnerFor(r.repo) : null)); + return rows.map((r) => toJob(r, labels.get(r.id), r.state === "queued" ? (untaken ??= untakenTest(db))(r) : null)); } export function jobRow(db: DatabaseSync, id: number): JobRow | undefined { diff --git a/src/runner/runner.ts b/src/runner/runner.ts index e086ded4..abf13309 100644 --- a/src/runner/runner.ts +++ b/src/runner/runner.ts @@ -420,7 +420,7 @@ export class Runner { .sort((a, b) => (steps.get(b.step)?.priority ?? 0) - (steps.get(a.step)?.priority ?? 0) || a.id - b.id); // Automatic jobs wait while the pipeline is off; they are cancelled when it is switched off. While it drains, nothing new starts. const on = isEnabled(this.db), draining = isDraining(this.db); - // Room by class, then by the job's repo ("" for a job without one). + // Room by class, then by the job's step and repo ("" for a job without one): a runner counts only for the tasks it takes. const room = new Map>(); const pass = queueRoomPass(this.db); for (const q of queued) { @@ -437,9 +437,9 @@ export class Runner { const cls = step.priority ?? 0; let byRepo = room.get(cls); if (!byRepo) room.set(cls, (byRepo = new Map())); - const key = q.repo ?? ""; - const roomOf = (): number => byRepo.get(key) ?? pass.room(cls, q.repo ? [q.repo] : undefined); - if (claude && q.repo && !pass.taker([q.repo])) continue; + const key = `${q.step}\n${q.repo ?? ""}`; + const roomOf = (): number => byRepo.get(key) ?? pass.room(cls, q.repo ? [q.repo] : undefined, q.step); + if (claude && q.repo && !pass.taker([q.repo], q.step)) continue; if (claude && !this.db.prepare("SELECT 1 FROM jobs WHERE step = ? AND state = 'running' LIMIT 1").get(step.name)) { // Nothing of the step runs: it starts anyway, and takes a slot of the room. } else if (claude) { diff --git a/test/planner-taker.test.ts b/test/planner-taker.test.ts index 3391cd88..1f00d70d 100644 --- a/test/planner-taker.test.ts +++ b/test/planner-taker.test.ts @@ -11,12 +11,13 @@ process.env.AUTOCRAFT_EXTRA_STEPS = fileURLToPath(new URL("./runner-steps.ts", i const { connect } = await import("../src/db.ts"); const { enqueue, getJob } = await import("../src/runner/jobs.ts"); -const { setStepParallel } = await import("../src/runner/concurrency.ts"); +const { noRunnerFor, noRunnerForTask, setStepParallel } = await import("../src/runner/concurrency.ts"); const { applyProposals, detectAutopilot, reservedByJobs } = await import("../src/runner/autopilot.ts"); const { createToken } = await import("../src/dash/mcp/tokens.ts"); const { parseStatus, storeStatus } = await import("../src/remote/helpers.ts"); const { setInferenceMode } = await import("../src/remote/mode.ts"); const { setUserRepos } = await import("../src/remote/my-repos.ts"); +const { setUserTasks, taskOfStep, TASK_CHOICES } = await import("../src/remote/my-tasks.ts"); mkdirSync(SCRATCH, { recursive: true }); @@ -48,3 +49,22 @@ test("a Task Runner that takes only deckcraft: deckcraft is planned, photocraft assert.equal(getJob(db, ids[0]!).waiting, null); assert.equal(reservedByJobs(db, "test-model"), 5, "only the deckcraft job keeps its limit"); }); + +test("a Task Runner whose user unticked the step's task: nothing is planned, a queued job waits with the task as the reason", async () => { + const db = connect(join(mkdtempSync(join(SCRATCH, "planner-taker-task-")), "t.db")); + setInferenceMode(db, "user-local", "test"); + db.prepare("INSERT INTO tracked_repos (name, pipeline) VALUES ('deckcraft', 1) ON CONFLICT (name) DO UPDATE SET pipeline = 1").run(); + db.prepare("INSERT INTO access (login, role) VALUES ('olga', 'operator')").run(); + const token = createToken(db, "olga", "helper", { kind: "runner" }).row.id; + storeStatus(db, token, "olga", parseStatus({ slots: 1, busy: 0, readiness: "ready", harness: "claude", models: { top: "opus" }, reserve: { fiveHour: 0, weekly: 0 } })); + setUserTasks(db, "olga", TASK_CHOICES.map((t) => t.id).filter((t) => t !== taskOfStep("test-model"))); + + const lane = [{ name: "model", steps: ["test-model"], perRepo: true, detect: () => [{ step: "test-model", params: { repo: "deckcraft" } }] }]; + const found = await detectAutopilot(db, { lanes: lane }); + assert.equal(found.proposals.length, 0); + assert.equal(found.status?.["test-model"], noRunnerForTask("deckcraft", "test-model")); + assert.notEqual(noRunnerForTask("deckcraft", "test-model"), noRunnerFor("deckcraft"), "the runner takes the repo: the reason names the task"); + const queued = await enqueue(db, "test-model", { repo: "deckcraft", limit: 5 }, "olga"); + assert.equal(getJob(db, queued.id).waiting, noRunnerForTask("deckcraft", "test-model")); + assert.equal(reservedByJobs(db, "test-model"), 0); +}); diff --git a/test/remote-room-repos.test.ts b/test/remote-room-repos.test.ts index 4028e944..da11918a 100644 --- a/test/remote-room-repos.test.ts +++ b/test/remote-room-repos.test.ts @@ -11,6 +11,7 @@ import { enqueueCall } from "../src/remote/calls.ts"; import { parseStatus, storeStatus } from "../src/remote/helpers.ts"; import { setInferenceMode } from "../src/remote/mode.ts"; import { setUserRepos } from "../src/remote/my-repos.ts"; +import { setUserTasks, TASK_CHOICES } from "../src/remote/my-tasks.ts"; import { remoteRoom } from "../src/remote/room.ts"; import { SCRATCH } from "./scratch.ts"; @@ -75,3 +76,23 @@ test("room is counted per repo: runners with disjoint repos, a call nobody may t setCallContext(null); } }); + +test("room counts only the runners whose users take the call's task (My tasks)", () => { + const db = connect(join(mkdtempSync(join(SCRATCH, "remote-room-tasks-")), "t.db")); + setInferenceMode(db, "user-local", "test"); + db.prepare("INSERT INTO access (login, role) VALUES ('olga', 'operator')").run(); + const id = createToken(db, "olga", "helper", { kind: "runner" }).row.id; + storeStatus(db, id, "olga", parseStatus({ slots: 1, busy: 0, readiness: "ready", harness: "claude", models: { top: "opus" }, reserve: { fiveHour: 0, weekly: 0 } })); + db.prepare("UPDATE mcp_tokens SET idle_claim_at = ? WHERE id = ?").run(Date.now(), id); + setUserTasks(db, "olga", TASK_CHOICES.map((t) => t.id).filter((t) => t !== "review")); + const room = (repos: string[] | undefined, step: string) => remoteRoom(db, 0, Date.now(), repos, step); + assert.ok(room(["deckcraft"], "fixissue") > 0); + assert.equal(room(["deckcraft"], "opus-review"), 0, "the only runner's user unticked Review"); + assert.equal(room(undefined, "opus-review"), 0, "with no repo named as well"); + setCallContext({ jobId: 1, step: "opus-review", stage: 5, repo: "deckcraft", cancelled: () => false }); + try { + assert.equal(queueRoom(db, 0, ["deckcraft"]), 0, "a review job's calls get no room"); + } finally { + setCallContext(null); + } +}); diff --git a/web/src/modules/connect/MySettings.tsx b/web/src/modules/connect/MySettings.tsx index aceb3c9f..eefb0d83 100644 --- a/web/src/modules/connect/MySettings.tsx +++ b/web/src/modules/connect/MySettings.tsx @@ -30,6 +30,9 @@ export function MySettings() { // save of the latest change may say Saved, so one that ends after a newer edit or save does not. const [saving, setSaving] = useState(0); const latest = useRef(0); + // Task saves run one after another, so the server ends with the latest selection. `confirmed` is the server's last answer; + // only the latest save sets the boxes from its answer, or back to `confirmed` when it fails. + const taskSaves = useRef({ chain: Promise.resolve() as Promise, n: 0, confirmed: [] as string[] }); const edited = () => { latest.current++; setSavedAt(null); @@ -45,6 +48,7 @@ export function MySettings() { setVals({ fiveHour: String(data.reserve.fiveHour), weekly: String(data.reserve.weekly) }); setPicks(data.repos); setTasks(data.tasks); + taskSaves.current.confirmed = data.tasks; setMaxCalls(data.maxCalls === null ? "" : String(data.maxCalls)); }, [data]); if (!data || !vals) return error ? : null; @@ -71,15 +75,18 @@ export function MySettings() { }); }; const saveTasks = (next: string[]) => { - const was = tasks; + const s = taskSaves.current, n = ++s.n; setTasks(next); - saveRun("tasks", async () => { - try { - setTasks((await api.me.settings.put({ tasks: next })).tasks); - } catch (e) { - setTasks(was); - throw e; - } + saveRun("tasks", () => { + const run = s.chain.then(async () => { + try { + s.confirmed = (await api.me.settings.put({ tasks: next })).tasks; + } finally { + if (n === s.n) setTasks(s.confirmed); + } + }); + s.chain = run.catch(() => undefined); + return run; }); }; const allTasks = data.taskChoices.map((t) => t.id);