Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(agent): /jobs, so background subagents are visible instead of fire and forget (#183)

Abdurrahman Fakhrulf8b5eac78517
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index d5ea0464..d2102175 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,12 +8,13 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Added**
-- `tui` configurable keybinds, with the defaults kept byte-identical
+- `agent` /jobs, so background subagents are visible instead of fire and forget
+- `tui` configurable keybinds, with the defaults kept byte-identical (#182)
- `agent` show the todo checklist in the TUI and in the status row (#179)
**Changed**
-- `tui` share the cell and pane primitives instead of growing a second copy
+- `tui` share the cell and pane primitives instead of growing a second copy (#186)
**Tests**
@@ -22,7 +23,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Docs**
-- `tui` add the retained renderer plan and classify it
+- `tui` plan the retained renderer, M0 (#185)
- `migration` correct the "2.8x" claim that justified cancelling Phase 4
- `bench` the after-side comparison, and a status header that was no longer true
diff --git a/lib/agent/subagent-jobs.test.ts b/lib/agent/subagent-jobs.test.ts
index 57fd6e5d..78d10820 100644
--- a/lib/agent/subagent-jobs.test.ts
+++ b/lib/agent/subagent-jobs.test.ts
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import {
startSubagentJob,
getSubagentJob,
+ listSubagentJobs,
cancelSubagentJob,
_resetSubagentJobsForTest,
MAX_CONCURRENT_PER_PRINCIPAL,
@@ -125,4 +126,32 @@ describe("background subagent jobs", () => {
expect(getSubagentJob(j2.jobId, "p-a").status).toBe("completed");
expect(getSubagentJob(runningIds[0], "p-2").status).toBe("running");
});
+
+ it("9. listSubagentJobs isolates principals, orders newest first, caps list and truncates resultPreview", async () => {
+ const longText = "x".repeat(200);
+ const j1 = await startSubagentJob({ ...base, principal: "p-list", name: "first" }, vi.fn(async () => ok(longText)));
+ await new Promise((r) => setTimeout(r, 10));
+ const j2 = await startSubagentJob({ ...base, principal: "p-list", name: "second" }, vi.fn<SubagentRunnerFn>(() => new Promise(() => {})));
+ await startSubagentJob({ ...base, principal: "p-other", name: "other" }, vi.fn<SubagentRunnerFn>(() => new Promise(() => {})));
+
+ const list = listSubagentJobs("p-list");
+ expect(list.length).toBe(2);
+ expect(list[0].jobId).toBe(j2.jobId);
+ expect(list[0].status).toBe("running");
+ expect(list[0].resultPreview).toBeUndefined();
+ expect((list[0] as Record<string, unknown>).result).toBeUndefined();
+
+ expect(list[1].jobId).toBe(j1.jobId);
+ expect(list[1].status).toBe("completed");
+ expect(list[1].resultPreview).toBe("x".repeat(120));
+ expect((list[1] as Record<string, unknown>).result).toBeUndefined();
+
+ const capped = listSubagentJobs("p-list", 1);
+ expect(capped.length).toBe(1);
+ expect(capped[0].jobId).toBe(j2.jobId);
+
+ const otherList = listSubagentJobs("p-other");
+ expect(otherList.length).toBe(1);
+ expect(otherList[0].name).toBe("other");
+ });
});
diff --git a/lib/agent/subagent-jobs.ts b/lib/agent/subagent-jobs.ts
index 8fb2ca3b..3942c4d4 100644
--- a/lib/agent/subagent-jobs.ts
+++ b/lib/agent/subagent-jobs.ts
@@ -156,6 +156,31 @@ export function getSubagentJob(jobId: string, principal: string) {
return publicJob(ownedJob(jobId, principal));
}
+export function listSubagentJobs(principal: string, limit = MAX_RETAINED_JOBS, now = Date.now()) {
+ cleanup(now);
+ return [...jobs.values()]
+ .filter((j) => j.principal === principal)
+ .sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt))
+ .slice(0, Math.max(0, limit))
+ .map((job) => {
+ const isFinished = job.status !== "running" && Boolean(job.finishedAt);
+ const endMs = isFinished ? Date.parse(job.finishedAt!) : now;
+ const elapsedMs = Math.max(0, endMs - Date.parse(job.startedAt));
+ const resultPreview = job.status === "completed" && typeof job.result === "string"
+ ? job.result.slice(0, 120)
+ : undefined;
+ return {
+ jobId: job.jobId,
+ status: job.status,
+ name: job.name,
+ startedAt: job.startedAt,
+ ...(job.finishedAt ? { finishedAt: job.finishedAt } : {}),
+ elapsedMs,
+ ...(resultPreview !== undefined ? { resultPreview } : {}),
+ };
+ });
+}
+
export function cancelSubagentJob(jobId: string, principal: string) {
const job = ownedJob(jobId, principal);
if (job.status === "running" && job.controller) {
diff --git a/lib/mcp/tools-subagents.ts b/lib/mcp/tools-subagents.ts
index f18a5125..150e5bf0 100644
--- a/lib/mcp/tools-subagents.ts
+++ b/lib/mcp/tools-subagents.ts
@@ -2,10 +2,11 @@ import { runSessionSubagent } from "@/lib/agent/subagent-runner";
import {
startSubagentJob,
getSubagentJob,
+ listSubagentJobs,
cancelSubagentJob,
} from "@/lib/agent/subagent-jobs";
import { allows, parseScope } from "./scope";
-import { type McpTool, S, str } from "./tool-kit";
+import { type McpTool, S, opt, str } from "./tool-kit";
function validateSubagentDelegation(a: Record<string, unknown>, context: Parameters<McpTool["run"]>[1]) {
if (!context.principal || !context.sessionId) throw new Error("subagent requires a conversation-bound MSO session");
@@ -64,15 +65,16 @@ export const SUBAGENT_TOOLS: McpTool[] = [
},
{
name: "agent_subagent_status",
- description: "Read status of one background subagent job owned by this client. Completed results are retained in-memory for 30 minutes after completion, after which status transitions to expired and result is discarded. Jobs disappear if the process restarts.",
+ description: "Read status of one background subagent job owned by this client, or list all recent jobs when job_id is omitted. Completed results are retained in-memory for 30 minutes after completion, after which status transitions to expired and result is discarded. Jobs disappear if the process restarts.",
chatgptDescription: "Check background worker.",
scope: "read",
annotations: { readOnlyHint: true, idempotentHint: true },
limit: { key: "exec.job.status", max: 120, windowMs: 60_000 },
- inputSchema: S({ job_id: { type: "string", description: "Exact job id returned by agent_subagent_start." } }, ["job_id"]),
+ inputSchema: S({ job_id: { type: "string", description: "Optional job id returned by agent_subagent_start. If omitted, returns all recent background subagent jobs for this caller." } }),
run: (a, context) => {
if (!context.principal) throw new Error("subagent requires an authenticated MSO client");
- return Promise.resolve(getSubagentJob(str(a, "job_id"), context.principal));
+ const id = opt(a, "job_id");
+ return Promise.resolve(id ? getSubagentJob(id, context.principal) : listSubagentJobs(context.principal));
},
},
{
diff --git a/scripts/mso-agent-commands.mjs b/scripts/mso-agent-commands.mjs
index 1d1ed5b1..fe8e3dac 100644
--- a/scripts/mso-agent-commands.mjs
+++ b/scripts/mso-agent-commands.mjs
@@ -16,6 +16,7 @@ import {
} from "./mso-agent-cmd-parity.mjs";
import { handleInspectCommand } from "./mso-agent-cmd-inspect.mjs";
import { handleSessionCommand } from "./mso-agent-cmd-session.mjs";
+import { handleJobsCommand } from "./mso-agent-jobs.mjs";
export { SHARE_UNAVAILABLE_MESSAGE, buildExportArgv };
@@ -94,6 +95,8 @@ export async function handleSlash(rl, line, session, { runTurn, runSubagent }) {
const parityOutcome = await handleParityCommand(ctx, cmd, args);
if (parityOutcome !== null) return parityOutcome;
+ if (cmd === "/jobs") return handleJobsCommand(ctx, args);
+
switch (cmd) {
case "/help":
printHelp();
diff --git a/scripts/mso-agent-help.mjs b/scripts/mso-agent-help.mjs
index 37cdb5de..8a6eb683 100644
--- a/scripts/mso-agent-help.mjs
+++ b/scripts/mso-agent-help.mjs
@@ -31,6 +31,7 @@ export const HELP_LINES = [
" /message <target> <msg> send notify-only local agent data",
" /delegate <target> <job> correlated local task; else remote A2A peer",
" /spawn [--name N] [--scope S] <job> run foreground isolated subagent in this session",
+ " /jobs [id|cancel <id>] list background subagent jobs, inspect, or cancel",
" /inbox show native local agent messages for this session",
" /skills [query] browse available slash skills",
" /skill <id> [prompt] select exact skill id (ambiguity escape hatch)",
diff --git a/scripts/mso-agent-jobs.mjs b/scripts/mso-agent-jobs.mjs
new file mode 100644
index 00000000..488b866e
--- /dev/null
+++ b/scripts/mso-agent-jobs.mjs
@@ -0,0 +1,179 @@
+import { api, C } from "./mso-agent-runtime.mjs";
+import { executeTool } from "./mso-agent-turn.mjs";
+
+export function formatElapsed(ms) {
+ if (typeof ms !== "number" || Number.isNaN(ms) || ms <= 0) return "0s";
+ if (ms < 1000) return `${ms}ms`;
+ const sec = Math.floor(ms / 1000);
+ if (sec < 60) return `${(ms / 1000).toFixed(1).replace(/\.0$/, "")}s`;
+ return `${Math.floor(sec / 60)}m ${sec % 60}s`;
+}
+
+function getJobElapsed(job, now = Date.now()) {
+ if (job.status === "running" && job.startedAt) {
+ const start = Date.parse(job.startedAt);
+ if (!Number.isNaN(start)) return Math.max(0, now - start);
+ }
+ if (typeof job.elapsedMs === "number" && !Number.isNaN(job.elapsedMs)) return Math.max(0, job.elapsedMs);
+ if (job.startedAt) {
+ const start = Date.parse(job.startedAt);
+ const end = job.finishedAt ? Date.parse(job.finishedAt) : now;
+ if (!Number.isNaN(start) && !Number.isNaN(end)) return Math.max(0, end - start);
+ }
+ return 0;
+}
+
+export function parseJobsResult(result) {
+ if (result == null) return [];
+ let parsed = result;
+ if (typeof result === "string") {
+ try { parsed = JSON.parse(result); } catch { return []; }
+ }
+ if (!Array.isArray(parsed)) return [];
+ const jobs = [];
+ for (const item of parsed) {
+ if (!item || typeof item !== "object" || Array.isArray(item)) continue;
+ const jobId = typeof item.jobId === "string" ? item.jobId : (typeof item.job_id === "string" ? item.job_id : "");
+ if (!jobId) continue;
+ const clean = {
+ jobId,
+ status: typeof item.status === "string" ? item.status : "unknown",
+ name: typeof item.name === "string" && item.name ? item.name : "worker",
+ startedAt: typeof item.startedAt === "string" ? item.startedAt : "",
+ ...(typeof item.finishedAt === "string" ? { finishedAt: item.finishedAt } : {}),
+ elapsedMs: typeof item.elapsedMs === "number" && !Number.isNaN(item.elapsedMs) ? Math.max(0, item.elapsedMs) : 0,
+ };
+ if (typeof item.resultPreview === "string") clean.resultPreview = item.resultPreview;
+ if (typeof item.result === "string") clean.result = item.result;
+ if (typeof item.error === "string") clean.error = item.error;
+ jobs.push(clean);
+ }
+ return jobs;
+}
+
+export function parseJobResult(result) {
+ if (result == null) return null;
+ let parsed = result;
+ if (typeof result === "string") {
+ try { parsed = JSON.parse(result); } catch { return null; }
+ }
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
+ const jobId = typeof parsed.jobId === "string" ? parsed.jobId : (typeof parsed.job_id === "string" ? parsed.job_id : "");
+ if (!jobId) return null;
+ return {
+ jobId,
+ status: typeof parsed.status === "string" ? parsed.status : "unknown",
+ name: typeof parsed.name === "string" && parsed.name ? parsed.name : "worker",
+ startedAt: typeof parsed.startedAt === "string" ? parsed.startedAt : "",
+ ...(typeof parsed.finishedAt === "string" ? { finishedAt: parsed.finishedAt } : {}),
+ ...(parsed.result !== undefined ? { result: String(parsed.result) } : {}),
+ ...(parsed.error !== undefined ? { error: String(parsed.error) } : {}),
+ elapsedMs: typeof parsed.elapsedMs === "number" && !Number.isNaN(parsed.elapsedMs) ? Math.max(0, parsed.elapsedMs) : 0,
+ };
+}
+
+export function formatJobsBlock(jobs, { colors = {}, maxItems = 12, now = Date.now() } = {}) {
+ const items = Array.isArray(jobs) ? jobs : parseJobsResult(jobs);
+ if (!items.length) return "no background subagent jobs found";
+ const { dim = "", reset = "", c: accent = colors?.cyan || "", err = "", warn = "" } = colors;
+ const effectiveMax = typeof maxItems === "number" && maxItems >= 0 ? maxItems : 12;
+ const lines = items.slice(0, effectiveMax).map((job) => {
+ const call = dim ? `${dim}${job.jobId || "unknown"}${reset}` : (job.jobId || "unknown");
+ const elapsed = dim ? `${dim}${formatElapsed(getJobElapsed(job, now))}${reset}` : formatElapsed(getJobElapsed(job, now));
+ const s = job.status || "unknown";
+ let state = s;
+ if (reset) {
+ if (s === "completed" || s === "running") state = `${accent}${s}${reset}`;
+ else if (s === "failed") state = `${err}${s}${reset}`;
+ else if (s === "cancelled") state = `${warn}${s}${reset}`;
+ else if (s === "expired") state = `${dim}${s}${reset}`;
+ }
+ return ` ${call} ${state} ${job.name || "worker"} ${elapsed}`;
+ });
+ if (items.length > effectiveMax) {
+ const text = `… ${items.length - effectiveMax} more jobs`;
+ lines.push(` ${dim ? `${dim}${text}${reset}` : text}`);
+ }
+ return lines.join("\n");
+}
+
+export function formatJobDetail(job, { colors = {}, now = Date.now() } = {}) {
+ if (!job) return "job not found";
+ const { dim = "", reset = "", bold = "" } = colors;
+ const lines = [
+ `Job: ${job.jobId}`,
+ `Status: ${job.status}`,
+ `Name: ${job.name}`,
+ `Elapsed: ${formatElapsed(getJobElapsed(job, now))}`,
+ ];
+ if (job.startedAt) lines.push(`Started: ${dim}${job.startedAt}${reset}`);
+ if (job.finishedAt) lines.push(`Finished: ${dim}${job.finishedAt}${reset}`);
+ if (job.status === "completed" && job.result !== undefined) lines.push("", `${bold}Result:${reset}`, job.result);
+ if (job.status === "failed" && job.error !== undefined) lines.push("", `${bold}Error:${reset}`, job.error);
+ return lines.join("\n");
+}
+
+export function printJobs(jobs, { colors, maxItems, print = console.log, now } = {}) {
+ const formatted = formatJobsBlock(jobs, { colors, maxItems, now });
+ print(formatted);
+ return formatted;
+}
+
+export async function handleJobsCommand(ctx, args = []) {
+ const { api: request = api, session, rl, C: colors = C } = ctx;
+ const sessionId = session?.agentSession?.id;
+ const subcommand = args[0];
+
+ if (!subcommand) {
+ try {
+ const out = await request("/api/v1/agent-tools", {
+ method: "POST",
+ body: JSON.stringify({ name: "agent_subagent_status", input: {}, ...(sessionId ? { sessionId } : {}) }),
+ });
+ if (!out?.ok) {
+ console.error(`${colors.err || ""}${out?.result || "could not list subagent jobs"}${colors.reset || ""}`);
+ return "handled";
+ }
+ printJobs(parseJobsResult(out.result), { colors });
+ } catch (err) {
+ console.error(`${colors.err || ""}${err instanceof Error ? err.message : String(err)}${colors.reset || ""}`);
+ }
+ return "handled";
+ }
+
+ if (subcommand === "cancel") {
+ const jobId = args[1]?.trim();
+ if (!jobId) { console.log("usage: /jobs cancel <id>"); return "handled"; }
+ if (!sessionId) { console.log("cannot cancel: active agent session required for tool approval"); return "handled"; }
+ try {
+ const tool = session?.state?.tools?.find((t) => t.name === "agent_subagent_cancel") || { name: "agent_subagent_cancel", scope: "exec" };
+ const call = { id: `slash_cancel_${Date.now()}`, name: "agent_subagent_cancel", input: { job_id: jobId } };
+ const outcome = await executeTool(rl, tool, call, session.agentSession, session.permission, undefined, null, { approvalState: session });
+ if (!outcome?.ok) { console.log(outcome?.result || "cancel failed"); return "handled"; }
+ const job = parseJobResult(outcome.result);
+ if (job) console.log(formatJobDetail(job, { colors }));
+ else console.log(outcome.result || "job cancelled");
+ } catch (err) {
+ console.error(`${colors.err || ""}${err instanceof Error ? err.message : String(err)}${colors.reset || ""}`);
+ }
+ return "handled";
+ }
+
+ const jobId = subcommand.trim();
+ try {
+ const out = await request("/api/v1/agent-tools", {
+ method: "POST",
+ body: JSON.stringify({ name: "agent_subagent_status", input: { job_id: jobId }, ...(sessionId ? { sessionId } : {}) }),
+ });
+ if (!out?.ok) {
+ console.error(`${colors.err || ""}${out?.result || `job ${jobId} not found`}${colors.reset || ""}`);
+ return "handled";
+ }
+ const job = parseJobResult(out.result);
+ if (job) console.log(formatJobDetail(job, { colors }));
+ else console.log(out.result || `job ${jobId} not found`);
+ } catch (err) {
+ console.error(`${colors.err || ""}${err instanceof Error ? err.message : String(err)}${colors.reset || ""}`);
+ }
+ return "handled";
+}
diff --git a/scripts/mso-agent-jobs.test.ts b/scripts/mso-agent-jobs.test.ts
new file mode 100644
index 00000000..3a6c0912
--- /dev/null
+++ b/scripts/mso-agent-jobs.test.ts
@@ -0,0 +1,138 @@
+import { describe, expect, it } from "vitest";
+import {
+ formatElapsed,
+ formatJobDetail,
+ formatJobsBlock,
+ parseJobResult,
+ parseJobsResult,
+} from "./mso-agent-jobs.mjs";
+
+describe("MSO Agent jobs view", () => {
+ it("1. a completed job, a running job and an expired job render correctly, with running showing live elapsed time and no NaN", () => {
+ const fixedNow = 1_700_000_100_000;
+ const jobs = [
+ {
+ jobId: "subagent_job_c1",
+ status: "completed",
+ name: "analyzer",
+ startedAt: new Date(fixedNow - 5_000).toISOString(),
+ finishedAt: new Date(fixedNow - 1_000).toISOString(),
+ elapsedMs: 4_000,
+ resultPreview: "done",
+ },
+ {
+ jobId: "subagent_job_r1",
+ status: "running",
+ name: "indexer",
+ startedAt: new Date(fixedNow - 3_500).toISOString(),
+ },
+ {
+ jobId: "subagent_job_e1",
+ status: "expired",
+ name: "collector",
+ startedAt: new Date(fixedNow - 60_000).toISOString(),
+ finishedAt: new Date(fixedNow - 30_000).toISOString(),
+ elapsedMs: 30_000,
+ },
+ {
+ jobId: "subagent_job_no_time",
+ status: "completed",
+ name: "fallback",
+ elapsedMs: Number.NaN,
+ },
+ ];
+
+ const output = formatJobsBlock(jobs, { now: fixedNow });
+ expect(output).not.toContain("NaN");
+ expect(output).not.toContain("-");
+
+ expect(output).toContain("subagent_job_c1");
+ expect(output).toContain("completed");
+ expect(output).toContain("analyzer");
+ expect(output).toContain("4s");
+
+ expect(output).toContain("subagent_job_r1");
+ expect(output).toContain("running");
+ expect(output).toContain("indexer");
+ expect(output).toContain("3.5s");
+
+ expect(output).toContain("subagent_job_e1");
+ expect(output).toContain("expired");
+ expect(output).toContain("collector");
+ expect(output).toContain("30s");
+
+ expect(output).toContain("subagent_job_no_time");
+ expect(output).toContain("0s");
+ });
+
+ it("2. an empty list says so plainly rather than printing an empty frame", () => {
+ const output = formatJobsBlock([]);
+ expect(output).toBe("no background subagent jobs found");
+ expect(formatJobsBlock(null)).toBe("no background subagent jobs found");
+ });
+
+ it("3. unparseable result and a non-array payload do not throw", () => {
+ expect(() => parseJobsResult("not json {")).not.toThrow();
+ expect(parseJobsResult("not json {")).toEqual([]);
+
+ expect(() => parseJobsResult({ error: "some object" })).not.toThrow();
+ expect(parseJobsResult({ error: "some object" })).toEqual([]);
+
+ expect(() => parseJobsResult(null)).not.toThrow();
+ expect(parseJobsResult(null)).toEqual([]);
+
+ expect(() => parseJobsResult(12345)).not.toThrow();
+ expect(parseJobsResult(12345)).toEqual([]);
+
+ expect(() => parseJobResult("invalid json")).not.toThrow();
+ expect(parseJobResult("invalid json")).toBeNull();
+
+ expect(() => parseJobResult([1, 2, 3])).not.toThrow();
+ expect(parseJobResult([1, 2, 3])).toBeNull();
+ });
+
+ it("4. /jobs <id> output includes the result for a completed job", () => {
+ const job = {
+ jobId: "subagent_job_42",
+ status: "completed",
+ name: "tester",
+ startedAt: "2026-10-30T10:00:00.000Z",
+ finishedAt: "2026-10-30T10:00:05.000Z",
+ elapsedMs: 5000,
+ result: "all unit tests passed successfully with 0 regressions",
+ };
+
+ const detail = formatJobDetail(job);
+ expect(detail).toContain("subagent_job_42");
+ expect(detail).toContain("completed");
+ expect(detail).toContain("tester");
+ expect(detail).toContain("5s");
+ expect(detail).toContain("Result:");
+ expect(detail).toContain("all unit tests passed successfully with 0 regressions");
+ });
+
+ it("5. maxItems is respected and withheld items are reported", () => {
+ const jobs = Array.from({ length: 5 }, (_, i) => ({
+ jobId: `job_${i + 1}`,
+ status: "running",
+ name: `w_${i + 1}`,
+ elapsedMs: 1000,
+ }));
+
+ const output = formatJobsBlock(jobs, { maxItems: 3 });
+ expect(output).toContain("job_1");
+ expect(output).toContain("job_3");
+ expect(output).not.toContain("job_4");
+ expect(output).toContain("… 2 more jobs");
+ });
+
+ it("6. formatElapsed handles edge cases cleanly without NaN or negative values", () => {
+ expect(formatElapsed(undefined as unknown as number)).toBe("0s");
+ expect(formatElapsed(Number.NaN)).toBe("0s");
+ expect(formatElapsed(-500)).toBe("0s");
+ expect(formatElapsed(0)).toBe("0s");
+ expect(formatElapsed(250)).toBe("250ms");
+ expect(formatElapsed(1500)).toBe("1.5s");
+ expect(formatElapsed(65000)).toBe("1m 5s");
+ });
+});