Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9153: feat(dev): dev-fixtures task kind holds a running agent task (#10924)
Jiayuan Zhangdea291501487
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex e5bd579300..8c886c1c3c 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -738,7 +738,7 @@ fixtures:```bashmake up C=api,web ARGS="--ephemeral"-make env-exec ARGS="-- node scripts/dev-fixtures.mjs all" # or: chat builder issue, --json+make env-exec ARGS="-- node scripts/dev-fixtures.mjs all" # or: chat builder issue task, --jsonmake destroy ARGS="--yes"```@@ -749,6 +749,30 @@ fixture runtime with the profile token and completes each task with cannedMarkdown through the daemon API, so it also works inside a daemon-managed task.It prints the URL of everything it created and exits.+`task` is for UI and CLI work that needs an agent mid-run: agent status,+the issue's execution log, Working / Idle filters, task panels. It assigns a new+issue to the `Fixture Worker` agent, claims and starts the task, writes a few+execution log entries and moves the issue to In Progress, then leaves the task+running. `--queued` adds a second task queued behind it on the same issue.+With `--json` it also prints `task_id`, `agent_id` and the task's `mat_`+`auth_token`, which is what the CLI needs to run as that agent inside a task+checkout:++```bash+make env-exec ARGS="-- node scripts/dev-fixtures.mjs task --queued --json"+make env-exec ARGS="-- node scripts/dev-fixtures.mjs task --hold" # Ctrl-C to stop+```++Nothing heartbeats for the fixture runtime by default, so it shows offline+about 150 seconds after the run. The held tasks are unaffected: the server+fails them only once the runtime has been silent for its reconnect grace+(`MULTICA_RUNTIME_RECONNECT_GRACE`, 3 hours by default), and an API restart does+not touch them. When a screenshot needs the runtime or agent shown online, add+`--hold`: the script then keeps heartbeating until Ctrl-C instead of exiting. A+new environment, or `make destroy`, drops every held task with its database;+run `task` again there. The fixture runtime reports the checkout's+`git describe` version as its CLI version.+### Desktop```bashdiff --git a/scripts/dev-env.sh b/scripts/dev-env.shindex bcf3ad757f..12eb028808 100755--- a/scripts/dev-env.sh+++ b/scripts/dev-env.sh@@ -1962,8 +1962,8 @@ Components: api (Go backend), web (Next.js), daemon (agent daemon),desktop (Electron). Anything selected implies api.Every environment has an onboarded workspace with two issues, signed in-through its CLI profile; scripts/dev-fixtures.mjs adds chat, Agent Builder and-wide-markdown issue content. desktop starts signed in. --cdp exposes a Chrome+through its CLI profile; scripts/dev-fixtures.mjs adds chat, Agent Builder,+wide-markdown issue content and a running agent task. desktop starts signed in. --cdp exposes a ChromeDevTools Protocol port (printed by up and status --json) for Playwright'sconnectOverCDP; the port is kept for later runs until --no-cdp.diff --git a/scripts/dev-fixtures.mjs b/scripts/dev-fixtures.mjsindex bb1ab1297c..d5550a6845 100644--- a/scripts/dev-fixtures.mjs+++ b/scripts/dev-fixtures.mjs@@ -5,28 +5,42 @@// make up C=api,web ARGS="--ephemeral"// make env-exec ARGS="-- node scripts/dev-fixtures.mjs all"// make env-exec ARGS="-- node scripts/dev-fixtures.mjs chat issue --json"+// make env-exec ARGS="-- node scripts/dev-fixtures.mjs task --queued --json"//// Replies come from the daemon API, driven with the environment profile's user// token: the script registers a fixture runtime, then claims, starts and// completes each task it caused with canned Markdown, so content appears without-// running a model through `make up C=daemon`. Every run adds new sessions and-// issues and then exits; nothing keeps running.+// running a model through `make up C=daemon`. The `task` fixture claims and+// starts its task but never completes it. Every run adds new sessions and+// issues and then exits; nothing keeps running unless `task --hold` was asked+// to heartbeat.+import { execFileSync } from "node:child_process";import { readFileSync } from "node:fs";import { homedir } from "node:os";-import { join } from "node:path";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";-const KINDS = ["chat", "builder", "issue"];+const KINDS = ["chat", "builder", "issue", "task"];const FIXTURE_DAEMON_ID = "dev-fixtures";const FIXTURE_AGENT_NAME = "Fixture Agent";+const FIXTURE_WORKER_NAME = "Fixture Worker";+// Matches the daemon's own heartbeat period.+const HEARTBEAT_INTERVAL_MS = 15_000;-const USAGE = `Usage: node scripts/dev-fixtures.mjs <all | chat | builder | issue>... [--json]+const USAGE = `Usage: node scripts/dev-fixtures.mjs <all | chat | builder | issue | task>... [--queued] [--hold] [--json]chat a chat session: a user message and an assistant reply with a table, code and a long log linebuilder an Agent Builder session with the same kind of reply and a filled-in draftissue an issue with a wide description and a comment holding a diff- all all three- --json print the created ids and URLs as JSON instead of text+ task an issue assigned to the Fixture Worker agent whose task stays running, with an execution log+ all all four+ --queued task: also leave a second task queued behind the running one, on the same issue+ --hold task: keep the fixture runtime heartbeating until Ctrl-C, so it stays online+ --json print the created ids and URLs as JSON instead of text; task adds task_id, auth_token and agent_id++A held task stays running for the server's reconnect grace (MULTICA_RUNTIME_RECONNECT_GRACE,+3 hours by default), but without --hold the runtime itself shows offline after about 150 seconds.Run through \`make env-exec ARGS="-- node scripts/dev-fixtures.mjs all"\`.`;@@ -38,17 +52,22 @@ function fail(message) {function parseCli(argv) {const kinds = new Set();let json = false;+ let queued = false;+ let hold = false;for (const arg of argv) {if (arg === "-h" || arg === "--help") {console.log(USAGE);process.exit(0);} else if (arg === "--json") json = true;+ else if (arg === "--queued") queued = true;+ else if (arg === "--hold") hold = true;else if (arg === "all") KINDS.forEach((kind) => kinds.add(kind));else if (KINDS.includes(arg)) kinds.add(arg);else fail(`unknown argument ${arg}\n\n${USAGE}`);}if (kinds.size === 0) fail(`name at least one fixture.\n\n${USAGE}`);- return { kinds: KINDS.filter((kind) => kinds.has(kind)), json };+ if ((queued || hold) && !kinds.has("task")) fail(`--queued and --hold apply to the task fixture.\n\n${USAGE}`);+ return { kinds: KINDS.filter((kind) => kinds.has(kind)), json, queued, hold };}function loadProfile(env) {@@ -233,14 +252,63 @@ const ISSUE_COMMENT = `Found it: the prepare lease is extended before the cache| 2 | 51.9 s | 5.8 s | 1 || 3 | 47.0 s | 6.4 s | 1 |`;+const TASK_ISSUE_DESCRIPTION = `Find out why the prepare lease on \`cloud-pool-b\` is extended twice per claim, and propose a fix.++The agent's task on this issue is held in \`running\` by \`scripts/dev-fixtures.mjs\`; it never finishes on its own.`;++const TASK_QUEUED_COMMENT = "When that is done, check whether `cloud-pool-a` shows the same pattern after the next deploy.";++const TASK_MESSAGES = [+ { type: "text", content: "Looking for where the daemon extends the prepare lease during a claim." },+ {+ type: "tool_use",+ call_id: "fixture-1",+ tool: "Bash",+ input: { command: "rg -n ExtendPrepareLease server/internal/daemon" },+ },+ {+ type: "tool_result",+ call_id: "fixture-1",+ tool: "Bash",+ output:+ "server/internal/daemon/prepare.go:112:\tif err := p.client.ExtendPrepareLease(ctx, task.RuntimeID, task.ID); err != nil {\nserver/internal/daemon/lease.go:41:func (c *Client) ExtendPrepareLease(ctx context.Context, runtimeID, taskID string) error {",+ },+ { type: "tool_use", call_id: "fixture-2", tool: "Read", input: { file_path: "server/internal/daemon/prepare.go" } },+ {+ type: "tool_result",+ call_id: "fixture-2",+ tool: "Read",+ output:+ "112\tif err := p.client.ExtendPrepareLease(ctx, task.RuntimeID, task.ID); err != nil {\n113\t\treturn fmt.Errorf(\"extend prepare lease: %w\", err)\n114\t}\n115\tif err := p.cache.CopyInto(ctx, task.WorkDir, cache.Options{Concurrency: 8}); err != nil {",+ },+ {+ type: "text",+ content: "The lease is extended before the dependency cache copy starts, so a slow copy always needs a second extension. Measuring the copy time on `cloud-pool-b` next.",+ },+];+// -------------------------------------------------------------- fixtures ---+// The version a daemon built from this checkout reports, as the Makefile+// derives it, so UI that parses the CLI version sees a realistic value.+function cliVersion() {+ try {+ return execFileSync("git", ["describe", "--tags", "--match", "v[0-9]*", "--always", "--dirty"], {+ cwd: dirname(fileURLToPath(import.meta.url)),+ encoding: "utf8",+ stdio: ["ignore", "pipe", "ignore"],+ }).trim();+ } catch {+ return "dev";+ }+}+async function ensureRuntime(request, workspaceId) {const registered = await request("POST", "/api/daemon/register", {workspace_id: workspaceId,daemon_id: FIXTURE_DAEMON_ID,device_name: "Dev fixtures",- cli_version: "dev-fixtures",+ cli_version: cliVersion(),runtimes: [{ name: "Fixture runtime", type: "claude", version: "fixture", status: "online" }],});const runtime = registered?.runtimes?.[0];@@ -248,33 +316,44 @@ async function ensureRuntime(request, workspaceId) {return runtime;}-async function ensureAgent(request, runtime) {+async function ensureAgent(request, runtime, { name, ...fields }) {const agents = (await request("GET", "/api/agents")) ?? [];const existing = (Array.isArray(agents) ? agents : agents.agents ?? []).find(- (agent) => agent.name === FIXTURE_AGENT_NAME && agent.runtime_id === runtime.id,+ (agent) => agent.name === name && agent.runtime_id === runtime.id,);if (existing) return existing;- return request("POST", "/api/agents", {- name: FIXTURE_AGENT_NAME,- description: "Answers with canned Markdown from scripts/dev-fixtures.mjs.",- instructions: "Fixture agent for local UI evidence. Its replies are written by scripts/dev-fixtures.mjs.",- runtime_id: runtime.id,- visibility: "workspace",- });+ return request("POST", "/api/agents", { name, ...fields, runtime_id: runtime.id, visibility: "workspace" });}-// A send enqueues the task; the fixture runtime is the only claimer, so the-// expected task arrives within a few polls. Anything else it holds is left-// over from an interrupted run and is answered too, so it cannot block ours.-async function answer(request, runtime, taskId, output) {+// The Fixture Agent's tasks finish at once, but the Fixture Worker's stay+// running for hours, so they get separate agents: held tasks must not use up+// the concurrency the chat fixtures need.+const FIXTURE_AGENT = {+ name: FIXTURE_AGENT_NAME,+ description: "Answers with canned Markdown from scripts/dev-fixtures.mjs.",+ instructions: "Fixture agent for local UI evidence. Its replies are written by scripts/dev-fixtures.mjs.",+};+const FIXTURE_WORKER = {+ name: FIXTURE_WORKER_NAME,+ description: "Holds tasks in running or queued for scripts/dev-fixtures.mjs.",+ instructions: "Fixture agent for local UI evidence. Its tasks are started by scripts/dev-fixtures.mjs and never finish.",+ max_concurrent_tasks: 50,+};++// A send or an assignment enqueues the task; the fixture runtime is the only+// claimer, so the expected task arrives within a few polls. Anything else it+// can claim is left over from an interrupted run and is answered, so it cannot+// block ours. Held tasks are never claimable again: they are running already,+// or queued behind a running task on the same issue.+async function claimAndStart(request, runtime, taskId, leftoverOutput) {const deadline = Date.now() + 30_000;for (;;) {const claimed = await request("POST", `/api/daemon/runtimes/${runtime.id}/tasks/claim`, {});const task = claimed?.task;if (task) {await request("POST", `/api/daemon/tasks/${task.id}/start`);- await request("POST", `/api/daemon/tasks/${task.id}/complete`, { output });- if (task.id === taskId) return;+ if (task.id === taskId) return task;+ await request("POST", `/api/daemon/tasks/${task.id}/complete`, { output: leftoverOutput });continue;}if (Date.now() > deadline) throw new Error(`task ${taskId} was never offered to the fixture runtime`);@@ -282,6 +361,26 @@ async function answer(request, runtime, taskId, output) {}}+async function answer(request, runtime, taskId, output) {+ await claimAndStart(request, runtime, taskId, output);+ await request("POST", `/api/daemon/tasks/${taskId}/complete`, { output });+}++// An assignment or a comment enqueues server-side, so the new task is found+// in the issue's task runs rather than in the response.+async function waitForQueuedTask(request, issueId, agentId, ignore = new Set()) {+ const deadline = Date.now() + 10_000;+ for (;;) {+ const runs = (await request("GET", `/api/issues/${issueId}/task-runs`)) ?? [];+ const task = (Array.isArray(runs) ? runs : runs.tasks ?? []).find(+ (run) => run.agent_id === agentId && run.status === "queued" && !ignore.has(run.id),+ );+ if (task) return task;+ if (Date.now() > deadline) throw new Error(`no queued task for ${FIXTURE_WORKER_NAME} appeared on issue ${issueId}`);+ await sleep(300);+ }+}+async function seedChat({ request, runtime, agent, appUrl, slug }) {const session = await request("POST", "/api/chat/sessions", {agent_id: agent.id,@@ -310,33 +409,86 @@ async function seedIssue({ request, appUrl, slug }) {description: ISSUE_DESCRIPTION,status: "in_progress",priority: "high",+ allow_duplicate: true,});await request("POST", `/api/issues/${issue.id}/comments`, { content: ISSUE_COMMENT });return { issue_id: issue.id, identifier: issue.identifier, url: `${appUrl}/${slug}/issues/${issue.identifier}` };}+async function seedTask({ request, profile, runtime, worker, appUrl, slug, queued }) {+ const issue = await request("POST", "/api/issues", {+ title: "Fixture: agent task in progress",+ description: TASK_ISSUE_DESCRIPTION,+ status: "todo",+ priority: "medium",+ assignee_type: "agent",+ assignee_id: worker.id,+ allow_duplicate: true,+ });+ const pending = await waitForQueuedTask(request, issue.id, worker.id);+ const task = await claimAndStart(request, runtime, pending.id, ASSISTANT_REPLY);+ await request("POST", `/api/daemon/tasks/${task.id}/messages`, {+ messages: TASK_MESSAGES.map((message, index) => ({ seq: index + 1, ...message })),+ });+ // A real run moves its issue with its own task token, so the activity is the agent's.+ const asAgent = client({ ...profile, token: task.auth_token });+ await asAgent("PUT", `/api/issues/${issue.id}`, { status: "in_progress" });++ const result = {+ issue_id: issue.id,+ identifier: issue.identifier,+ url: `${appUrl}/${slug}/issues/${issue.identifier}`,+ task_id: task.id,+ auth_token: task.auth_token,+ agent_id: worker.id,+ runtime_id: runtime.id,+ };+ if (queued) {+ await request("POST", `/api/issues/${issue.id}/comments`, { content: TASK_QUEUED_COMMENT });+ result.queued_task_id = (await waitForQueuedTask(request, issue.id, worker.id, new Set([task.id]))).id;+ }+ return result;+}++// Keeps the runtime online, and its held tasks with it, the way a daemon does.+// A failed beat (an API restart) is reported and retried on the next tick.+async function holdRuntime(request, runtime) {+ console.error(`[dev-fixtures] holding: ${runtime.name} heartbeats every ${HEARTBEAT_INTERVAL_MS / 1000}s; Ctrl-C to stop.`);+ for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => process.exit(0));+ for (;;) {+ await sleep(HEARTBEAT_INTERVAL_MS);+ try {+ await request("POST", "/api/daemon/heartbeat", { runtime_id: runtime.id });+ } catch (error) {+ console.error(`[dev-fixtures] heartbeat failed, retrying: ${error.message}`);+ }+ }+}+async function main() {- const { kinds, json } = parseCli(process.argv.slice(2));+ const { kinds, json, queued, hold } = parseCli(process.argv.slice(2));const profile = loadProfile(process.env);const request = client(profile);const workspaces = (await request("GET", "/api/workspaces")) ?? [];const workspace = workspaces.find((ws) => ws.id === profile.workspaceId);if (!workspace) fail(`the profile's workspace ${profile.workspaceId} is not visible to its token.`);- const context = { request, appUrl: profile.appUrl, slug: workspace.slug };+ const context = { request, profile, appUrl: profile.appUrl, slug: workspace.slug, queued };- if (kinds.includes("chat") || kinds.includes("builder")) {+ if (kinds.some((kind) => kind !== "issue")) {context.runtime = await ensureRuntime(request, profile.workspaceId);}- if (kinds.includes("chat")) context.agent = await ensureAgent(request, context.runtime);+ if (kinds.includes("chat")) context.agent = await ensureAgent(request, context.runtime, FIXTURE_AGENT);+ if (kinds.includes("task")) context.worker = await ensureAgent(request, context.runtime, FIXTURE_WORKER);- const seeders = { chat: seedChat, builder: seedBuilder, issue: seedIssue };+ const seeders = { chat: seedChat, builder: seedBuilder, issue: seedIssue, task: seedTask };const result = {};for (const kind of kinds) {result[kind] = await seeders[kind](context);if (!json) console.log(`[dev-fixtures] ${kind.padEnd(8)}${result[kind].url}`);}if (json) console.log(JSON.stringify(result, null, 2));+ if (hold) await holdRuntime(request, context.runtime);}main().catch((error) => fail(error?.stack || String(error)));