diff --git a/docs/getting-started.md b/docs/getting-started.md index 78ba01f3..3bd9b6f9 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -276,11 +276,12 @@ until the app runs a newer version. Machines that autoscaling starts and stops, or that you set up without signing in on them, enroll themselves with one of the workspace's -**enrollment tokens**. Its admins make one under **Enrollment tokens** on -its Runners tab (or with `fctl runners enrollment-tokens create`): a name, -how long it works, how many runners it may enroll at once, whether each -waits for an admin's approval, and whether runners that stay offline are -removed. The token is shown once. On each machine, from its boot script +**enrollment tokens**. Its admins make one with **New pool** under +**Pools** on its Runners tab (or with `fctl runners enrollment-tokens +create`): a name, its labels and placement, how long it works, how many +runners it may enroll at once, whether each waits for an admin's +approval, and whether runners that stay offline are removed. The token is +shown once. On each machine, from its boot script (cloud-init's user data, a launch template) or a shell: ```sh @@ -316,8 +317,12 @@ them, don't run sessions on it. The runners a token enrolls are a **pool**. Give the token labels (`--labels aws,large`), and a project that asks for them (`fctl projects set -p ml ---runners large`) runs its sessions only on runners -that have them, which wait for one and say so. A token that removes offline +--runners large`, or the pool by its name in the project's Settings → +Runners) runs its sessions only on runners +that have them, which wait for one and say so. On the Runners tab, each +pool is a card with its runners under it and what it needs now: how many +of its runners are busy, the sessions that wait for it and for how long, +and whether it grows or is at its limit. A token that removes offline runners packs sessions onto its busiest runners with room, so that idle machines empty out and can go. What a pool needs now, for an autoscaler, comes from `fctl runners demand` (`--json`, `--cloudwatch`), or from `GET diff --git a/docs/llms.txt b/docs/llms.txt index 8640654b..e2581895 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -213,7 +213,7 @@ Each recipe says who does what: some steps take a person with a role in the proj 9. **GitHub Issues as the tracker**: the default; agents use `gh issue` in the repositories they write to. `fctl projects set -p my-app --tickets github --tickets-repo owner/name` keeps them to one repository's issues (through `fctl ticket` when they write to other repositories too); `--tickets none` keeps them away from trackers. A maintainer can start a session that reaches GitHub's issues whatever the tracker says, to move them into Linear, say (`fctl run --github-issues`). 10. **Plan or review without changes**: `fctl run -p my-app -d --github read "Plan the move to Postgres: what changes, in what order, what can break."` or a project-wide cap: `fctl projects set -p my-app --github comment`. 11. **Set up a project** (a workspace admin): `fctl projects create "My app" --repo my-org/my-app -w acme`, then `fctl projects set -p my-app --setup-script 'npm ci' --idle-timeout 30 --pr-descriptions balanced`, more repositories with `fctl projects repos add my-org/my-lib --write -p my-app`, an image with `--image ghcr.io/acme/agent:1` or `--build Dockerfile`, size with `--cpus 8 --memory 16g`, shared package caches with `--package-caches on`, its agents' instructions, model and effort with `--instructions-file agents.md --model opus --effort high`, the context size Claude compacts their sessions near with `--compact-window 400k` (100k to 1m; `default` for Claude's, near the model's whole window), opening pull requests when they finish with `--auto-pull-request on|off`, how they handle pull requests and issues with `--pr-instructions-file prs.md` (`fctl projects show my-app --pr-instructions` prints fctl's rules to start from), Remote Control and claude.ai connectors with `--remote-control on|off --connectors on|off`, its name, description and default branch with `--name "Web app" --description "The storefront" --default-branch develop`, and its icon in the sidebar and on its page with `--icon store --icon-color yellow --icon-style duotone` (an [IconMCP](https://iconmcp.com) glyph's name; ink, yellow, pink, blue or a color of its own as `'#rrggbb'`; outline, duotone or solid; `--icon ""` for the one that fits its name). Secrets: `fctl projects secrets set STRIPE_KEY -p my-app`, the value typed at its prompt or piped in; `fctl projects secrets -p my-app` lists their names. People: `fctl projects members add grace@example.com --role maintainer -p my-app` (`viewer`, `editor`, `maintainer`, `owner`), `fctl projects members role …`, `fctl projects members remove …`. -12. **Bring a machine online** (its owner, at its terminal): install Apple's `container` (macOS 26+, `container system start`; a host on the apple driver starts it again after the Mac restarts, stops a sandbox whose VM stops answering, which would hold up every other: its session fails and resumes in it, and restarts Apple's `container` when its sandboxes lose the network while the Mac has it, at most every 30 minutes: sessions wait meanwhile rather than fail), Lima, or Docker (on Linux, Docker Engine with `sudo systemctl enable --now docker`; `fctl host install` offers to add the user to the `docker` group, and fctl takes the group itself, with no new login), or on Linux with KVM `passt` and `e2fsprogs` for `--driver firecracker`; then `fctl login`, `fctl host install --workspace acme` (or `--token fctl_rt_…` from the workspace's Runners tab), `fctl host doctor`, `fctl host status`. Maintenance: `fctl host drain --wait` (`--timeout 60s` stops what still runs after that long, as a cloud takes the machine; give it a minute less than the notice), `fctl host undrain`; a machine that should go once idle: `fctl host install --retire-when-idle 20m --retire-command '…'`; an autopilot whose own session's sandbox is on a draining runner moves off at its next wake once its turn has ended, in a fresh session on another runner, as it does while the machine is away and another runner would run it, and `fctl host status` lists the autopilots that wake there, with when each wakes. Many machines, or ones autoscaling starts: a workspace admin makes an enrollment token (`fctl runners enrollment-tokens create "Build fleet" -w acme --max-runners 20 --remove-offline-after 5m`, `--approval` to approve each), or any member one for their own sessions (`--personal`), and each machine's boot script runs `FCTL_SERVER=https://app.fctl.sh FCTL_ENROLL_TOKEN=fctl_et_… fctl host install` with no sign-in (and, for someone who keeps their Claude token on their runners, `fctl host claude set-token < /run/secrets/claude-token`); `fctl runners --pending`, `fctl runners approve `, `fctl runners reject `, `fctl runners remove `. Pools: `--labels aws,large` on the token, `fctl runners enrollment-tokens set "AWS large" -w acme --placement packed --max-runners 40`, `fctl projects set -p ml --runners large`; an autoscaler reads `GET /api/v1/runner/enroll/demand` with the enrollment token (KEDA: `valueLocation: wanted`), or `fctl runners demand -w acme --pool "AWS large" --json`. +12. **Bring a machine online** (its owner, at its terminal): install Apple's `container` (macOS 26+, `container system start`; a host on the apple driver starts it again after the Mac restarts, stops a sandbox whose VM stops answering, which would hold up every other: its session fails and resumes in it, and restarts Apple's `container` when its sandboxes lose the network while the Mac has it, at most every 30 minutes: sessions wait meanwhile rather than fail), Lima, or Docker (on Linux, Docker Engine with `sudo systemctl enable --now docker`; `fctl host install` offers to add the user to the `docker` group, and fctl takes the group itself, with no new login), or on Linux with KVM `passt` and `e2fsprogs` for `--driver firecracker`; then `fctl login`, `fctl host install --workspace acme` (or `--token fctl_rt_…` from the workspace's Runners tab), `fctl host doctor`, `fctl host status`. Maintenance: `fctl host drain --wait` (`--timeout 60s` stops what still runs after that long, as a cloud takes the machine; give it a minute less than the notice), `fctl host undrain`; a machine that should go once idle: `fctl host install --retire-when-idle 20m --retire-command '…'`; an autopilot whose own session's sandbox is on a draining runner moves off at its next wake once its turn has ended, in a fresh session on another runner, as it does while the machine is away and another runner would run it, and `fctl host status` lists the autopilots that wake there, with when each wakes. Many machines, or ones autoscaling starts: a workspace admin makes an enrollment token (`fctl runners enrollment-tokens create "Build fleet" -w acme --max-runners 20 --remove-offline-after 5m`, `--approval` to approve each), or any member one for their own sessions (`--personal`), and each machine's boot script runs `FCTL_SERVER=https://app.fctl.sh FCTL_ENROLL_TOKEN=fctl_et_… fctl host install` with no sign-in (and, for someone who keeps their Claude token on their runners, `fctl host claude set-token < /run/secrets/claude-token`); `fctl runners --pending`, `fctl runners approve `, `fctl runners reject `, `fctl runners remove `. Pools: `--labels aws,large` on the token, `fctl runners enrollment-tokens set "AWS large" -w acme --placement packed --max-runners 40`, `fctl projects set -p ml --runners large` (in the web app: Pools on the Runners tab, and a pool by its name in a project's Settings → Runners); an autoscaler reads `GET /api/v1/runner/enroll/demand` with the enrollment token (KEDA: `valueLocation: wanted`), or `fctl runners demand -w acme --pool "AWS large" --json`. 13. **Dashboards and reports**: a token with `--access read` lists sessions, transcripts, memory and retrospectives and starts nothing: `fctl sessions --active --json`, `fctl sessions --since 1d --json` (at work in the last day, those that ended in it too), `fctl pulls --json` (the open pull requests agents opened, each once with the sessions that list it; `-p my-app`, `--state merged|closed|all`, `--mine`; archived sessions' too, a session marked `(asks you)` or `(archived)`, `archived` and `question` in its JSON; the app's `/pulls` page sorts the open ones by what each needs next: waiting for your answer, ready for review, checks failing, agents at work, merge queue, drafts), `fctl retro list -p my-app --json`, `fctl search "flaky test" --json`, `fctl logs my-app#12 --json`, `fctl diff my-app#12` (the branch's changes as git prints them; `--json` for each file's patch). 14. **Keep agents informed**: `fctl memory add -p my-app "Deploys happen on Thursdays: merge migrations by Tuesday."`; delete every stale note at once with `fctl memory delete --stale -p my-app` (a project keeps 1,000 notes, stale ones included), or have fctl delete notes once they have been stale a number of days with `fctl projects set -p my-app --stale-note-days 7` (1 to 365; `never` by default); read what they learned with `fctl memory -p my-app` and `fctl retro list -p my-app --outcome blocked`. 15. **Hand a session to someone** (its owners): `fctl share grace@example.com` lets someone in its workspace view it and message its agent (`--role viewer` only views it, `--role owner` also stops, resumes, archives and shares it), `fctl share ` lists who it is shared with, `fctl unshare grace@example.com` takes it back. Anyone who can message the agent can have it hand over the sandbox's secrets and tokens. `fctl archive ` takes a finished session out of the lists and stops follow-ups reaching it (`fctl unarchive`, `fctl sessions --archived`). diff --git a/web/src/components/project/settings.test.tsx b/web/src/components/project/settings.test.tsx index 06dded7d..3c139e04 100644 --- a/web/src/components/project/settings.test.tsx +++ b/web/src/components/project/settings.test.tsx @@ -145,6 +145,7 @@ describe("a project's Settings", () => { "Agents", "Pull requests", "Tickets", + "Runners", "Sandbox", "Secrets", "Identity OIDC", @@ -421,3 +422,116 @@ describe("a project's Settings", () => { expect(s.button("Save")).toBeDefined(); }); }); + +describe("a project's Runners page", () => { + const acme = { id: "wsp_acme", slug: "acme", name: "Acme" } as G.WorkspaceRef; + const runner = (r: Partial & { id: string }): G.Runner => + ({ + name: r.id, + status: "online", + drivers: [], + capacity: 4, + active_sessions: 0, + labels: [], + created_at: 0, + workspaces: [], + yours: false, + personal: [], + ...r, + }) as G.Runner; + const pool: G.PoolDemand = { + pool: { id: "enr_large", name: "AWS large", labels: ["aws", "large"], placement: "packed" }, + runners: { online: 4, busy: 2, draining: 0, pending: 0, starting: 0, offline: 0 }, + slots: { capacity: 16, busy: 5, free: 11 }, + waiting: { sessions: 0 }, + wanted: 2, + shape: { capacity: 4, cpus: 16, memory_mb: 65536, driver: "docker", version: "0.38.0", seen_at: 0 }, + at: 0, + }; + + /** The page, with Acme's runners and pools as its admins read them. */ + function runners(labels: string[], fallback?: number) { + queryClient.setQueryData(keys.workspace("wsp_acme"), { + ...acme, + primary: { id: "usr_ada", name: "Ada" }, + } as G.Workspace); + queryClient.setQueryData(keys.workspaceRunners("wsp_acme"), { + runners: [ + runner({ id: "rnr_1", labels: ["aws", "large"], pool: { id: "enr_large", name: "AWS large" } }), + runner({ id: "rnr_mac", name: "studio-mac" }), + ], + }); + queryClient.setQueryData(keys.workspaceDemand("wsp_acme"), { + pools: [pool], + waiting: { sessions: 0 }, + unpooled: 0, + at: 0, + }); + return open( + "runners", + project({ + workspace: acme, + settings: { ...settings, runner_labels: labels, runner_fallback_minutes: fallback ?? null }, + }), + ); + } + const shown = (s: ReturnType, n = 0) => + s.container + .querySelectorAll('[role="combobox"]') + [n]?.querySelector("span:not([aria-hidden]) > span:not([aria-hidden])")?.textContent; + + it("offers any runner, or a pool by its name with what its runners give", () => { + vi.useFakeTimers(); + try { + const s = runners([]); + expect(s.heading()).toBe("Runners"); + expect(shown(s)).toBe("Any runner"); + act(() => (s.container.querySelector('[role="combobox"]') as HTMLElement).click()); + const options = [...s.container.querySelectorAll('[role="option"]')].map( + (o) => o.textContent, + ); + expect(options).toContain("AWS large4 runners with 16 CPUs and 64 GiB · aws, large"); + const large = [...s.container.querySelectorAll('[role="option"]')].find((o) => + o.textContent?.startsWith("AWS large"), + ); + act(() => large?.click()); + act(() => vi.advanceTimersByTime(1000)); + expect((s.container.querySelector("input.font-mono") as HTMLInputElement).value).toBe("aws, large"); + expect(s.button("Save")).toBeDefined(); + } finally { + vi.useRealTimers(); + } + }); + + it("names the pool a project's labels choose, and how long its sessions wait for it", () => { + const s = runners(["large", "aws"], 15); + expect(shown(s)).toBe("AWS large"); + expect(shown(s, 1)).toBe("After 15 minutes, any runner"); + expect(s.container.textContent).toContain( + "Its sessions wait for one of those runners, then go to any of Acme's.", + ); + expect(s.container.querySelector(".text-amber")).toBeNull(); + }); + + it("says in amber when no runner has its labels, and who adds one", () => { + const s = runners(["gpu"]); + expect(shown(s)).toBe("Runners with labels you choose"); + expect(s.container.querySelector(".text-amber")?.textContent).toBe( + "No runner of Acme has the label gpu: its sessions wait until one does. Ada and its other admins add runners and pools on its Runners tab.", + ); + }); + + it("saves the labels and the wait, for sessions that start from then on", async () => { + const s = runners(["gpu"]); + const input = s.container.querySelector("input.font-mono") as HTMLInputElement; + act(() => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(input, "gpu, Large"); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + await act(async () => s.button("Save").click()); + expect(updates.at(-1)?.body.settings).toMatchObject({ + runner_labels: ["gpu", "large"], + runner_fallback_minutes: null, + }); + }); +}); diff --git a/web/src/components/project/settings.tsx b/web/src/components/project/settings.tsx index 843b86f7..a61313f5 100644 --- a/web/src/components/project/settings.tsx +++ b/web/src/components/project/settings.tsx @@ -15,6 +15,7 @@ import { GitPullRequest, KeyRound, type LucideIcon, + Server, SlidersHorizontal, Ticket, Webhook, @@ -46,7 +47,7 @@ import { } from "@/components/ui"; import { WebhooksPanel, webhooksLead } from "@/components/webhooks/panel"; import type * as G from "@/gen"; -import { ApiFailure, api } from "@/lib/api"; +import { ApiFailure, api, workspaces } from "@/lib/api"; import { cn } from "@/lib/cn"; import { showHex } from "@/lib/color"; import { @@ -70,6 +71,16 @@ import { withSource, } from "@/lib/images"; import { ALIASES, chosenModel, EFFORTS, type ModelChoice, modelChoice } from "@/lib/models"; +import { + FALLBACKS, + fallbackOf, + labelProblem, + labelsWords, + parseLabels, + poolChoices, + poolFor, + sameLabels, +} from "@/lib/pools"; import { areDefaults, shownInstructions } from "@/lib/pr-instructions"; import { ICON_COLORS, iconDef, iconOf } from "@/lib/project-icons"; import { @@ -84,7 +95,7 @@ import { settingsPagesFor, } from "@/lib/project-page"; import { DAY_CHOICES, DEFAULT_DAYS, lasts } from "@/lib/published"; -import { keys, queryClient, useInstance, useMe, useRunners } from "@/lib/queries"; +import { keys, queryClient, useInstance, useMe, useRunners, useWorkspace } from "@/lib/queries"; import type { Gist } from "@/lib/settings"; import type { LinearOutcome } from "@/lib/tickets"; @@ -94,6 +105,7 @@ const ICONS: Record = { agents: Bot, "pull-requests": GitPullRequest, tickets: Ticket, + runners: Server, sandbox: Box, secrets: KeyRound, identity: Fingerprint, @@ -254,6 +266,8 @@ function SettingsBody({ return ; case "tickets": return ; + case "runners": + return ; case "sandbox": return ; case "secrets": @@ -955,6 +969,201 @@ function PullRequests({ project }: { project: G.Project }) { const sameFollowUps = (a: G.FollowUps, b: G.FollowUps) => a.comments === b.comments && a.checks === b.checks && a.conflicts === b.conflicts && a.closed === b.closed; +// ───────────────────────────── runners ───────────────────────────── + +/** + * Which of its workspace's runners take its sessions: any, a pool's, chosen by name, or runners with + * labels of its own choosing; and whether its sessions wait for those however long, or go to any + * runner after a while. A project whose labels no runner has says so, and who adds one. + */ +function Runners({ project }: { project: G.Project }) { + const wid = project.workspace?.id ?? ""; + const w = useWorkspace(wid || undefined).data; + const runners = useQuery({ + queryKey: keys.workspaceRunners(wid), + queryFn: () => workspaces.runners(wid), + enabled: !!wid, + }); + // The pools its admins manage say what each gives; others see them through their runners. + const demand = useQuery({ + queryKey: keys.workspaceDemand(wid), + queryFn: () => workspaces.demand(wid), + enabled: !!wid, + retry: false, + }); + const choices = poolChoices(demand.data?.pools, runners.data?.runners ?? []); + const saved = { + typed: (project.settings.runner_labels ?? []).join(", "), + fallback: project.settings.runner_fallback_minutes ?? null, + }; + const { draft: d, set, setDraft, dirty, reset } = useDraft(saved); + const [custom, setCustom] = useState(false); + const labels = parseLabels(d.typed); + const problem = labelProblem(labels); + const pool = choices.find((c) => c.labels.length > 0 && sameLabels(c.labels, labels)); + const choice = custom ? "labels" : labels.length === 0 ? "any" : (pool?.id ?? "labels"); + const where = (p: G.Project) => { + const l = p.settings.runner_labels ?? []; + const named = choices.find((c) => c.labels.length > 0 && sameLabels(c.labels, l)); + return l.length === 0 ? "any runner" : named ? named.name : `runners with ${l.join(", ")}`; + }; + const save = useSave( + project, + "Saved", + () => { + if (problem) + throw new ApiFailure(400, { code: "validation", field: "settings.runner_labels", message: problem }); + return { + settings: { + ...project.settings, + runner_labels: labels, + runner_fallback_minutes: labels.length ? d.fallback : null, + }, + }; + }, + (p) => { + setCustom(false); + setDraft({ + typed: (p.settings.runner_labels ?? []).join(", "), + fallback: p.settings.runner_fallback_minutes ?? null, + }); + toast(`Sessions that start from now on run on ${where(p)}`); + }, + ); + const err = (f: string) => (failedField(save.error) === f ? save.error?.message : undefined); + const workspaceName = w?.name ?? project.workspace?.name ?? "the workspace"; + // Nothing has them: its sessions wait for nothing that comes. + const has = (r: G.Runner) => labels.every((l) => r.labels.includes(l)); + const none = + labels.length > 0 && + !problem && + runners.data !== undefined && + !runners.data.runners.some(has) && + !poolFor(labels, demand.data?.pools ?? []); + const fallback = fallbackOf(d.fallback); + const fallbacks = FALLBACKS.some((f) => f.value === fallback.value) ? FALLBACKS : [...FALLBACKS, fallback]; + return ( +
+
{ + e.preventDefault(); + if (dirty) save.mutate(); + }} + > +
+ + {(id) => ( + set({ typed: e.target.value })} + placeholder="aws, large" + className="font-mono" + /> + )} + + )} + {labels.length > 0 && ( + + {(id) => ( + setName(e.target.value)} />} + + + {(id) => ( + setLabels(e.target.value)} + placeholder="aws, large" + className="font-mono" + /> + )} + +
+ + {(id) => ( + setLimit(e.target.value)} + placeholder="No limit" + /> + )} + +
+ {save.error && !field && {save.error.message}} +
+ + +
+ + + ); +} + /** * Makes an enrollment token, and shows it once with the commands that enroll a machine: an admin's * for everyone's sessions or their own, a member's for their own. @@ -683,7 +940,7 @@ function NewEnrollmentToken({ open={open} onClose={close} wide - title={created ? `${created.token.name} is ready` : "New enrollment token"} + title={created ? `${created.token.name} is ready` : "New pool"} description={ created ? describeEnrollment( @@ -771,6 +1028,33 @@ function TokenForm({ )} )} +
+ + {(id) => ( + set({ labels: e.target.value })} + placeholder="aws, large" + className="font-mono" + /> + )} + + + {(id) => ( +