Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

allowlist grok/kimi in the CoS runner and stop losing spawn errors

[._.]/ Adam Eivy5ec90f3e1559
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 6858b7a36c..83a2ab0481 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -12,6 +12,7 @@
## Fixed
- **The Antigravity card on the Usage page loads quota again after `agy` 1.1.x renamed its limit rows.** The `/usage` panel still groups Gemini / Claude+GPT windows the same way, but each window header grew a trailing "Remaining" (`Weekly Limit Remaining`, `Five Hour Limit Remaining`). The parser required the line to end on bare `Limit`, so it found the groups and returned zero meters — the card looked broken with "No quota data found." Both the new labels and the older bare-`Limit` form parse to the same keys.
+- **Grok and Kimi agents now actually start, and an agent that fails to spawn says why.** Picking the Grok or Kimi provider for a CoS agent produced a task that never opened a shell: the durable agent runner keeps an allowlist of CLI commands it is permitted to spawn, and `grok` and `kimi` were never added to it even though both ship as selectable providers. Both are allowlisted now, and a test keeps that list in step with the shipped provider catalog so the next provider added without an entry fails in CI rather than in a silent agent. The reporting around it was the worse half of the bug: a rejected spawn was logged and dropped, never reaching the agent record. A TUI agent sat in "initializing" for a minute until the zombie sweeper finalized it as "Agent process terminated unexpectedly" — a message that named no cause — and the CLI equivalent was worse still, staying "working" indefinitely because the stale in-memory entry made every cleanup sweep skip it. Both paths now finalize immediately with the runner's actual error, the runner names the offending command instead of returning one opaque "missing or invalid fields", and an agent reaped without ever having recorded a process id is reported as never having started rather than as a crash.
- **The labels on LoRA training dataset images are readable again.** The source chip ("upload", "generated", "sheet crop", "gallery") and the view label ("front three-quarter") were tinted overlays — 20%-opacity color on top of whatever the training image happened to be — so over a bright photo, or under a light theme, the text all but disappeared. They were also pinned to opposite corners of the thumbnail, so a long view label collided with the source chip in a narrow column and the two printed on top of each other. Both chips now carry their own near-opaque plate with light text, and they share one wrapping row so a long label drops to a second line instead of overlapping.
- **The Antigravity code reviewer no longer looks like it isn't installed.** Antigravity's command is `agy`, but every agent prompt named the reviewer by its internal slug, `antigravity` — a command that exists on no machine. A review-loop agent went looking for it, found nothing, concluded there was no reviewer available, reviewed its own work instead, and merged the PR. Prompts now name the actual command, and a reviewer whose command genuinely isn't installed blocks the merge with a note on the PR instead of quietly being replaced by a self-review.
- **Pull requests opened by a CoS agent under a "merge when CI is green" policy now actually get merged.** The check that watches those PRs only ran when an app's optional "PR Watcher" scheduled task fired — and that task ships disabled, since its default prompt is a review-and-comment agent most setups don't want. So PortOS was queueing green PRs into a list nothing ever read: they sat open indefinitely, and because the retry counter never advanced, the safety net that gives up and notifies you after a few hours never fired either. The watch now runs on the normal CoS cadence, independent of that task.
diff --git a/PLAN.md b/PLAN.md
index d6c476695d..40348ab92c 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -256,6 +256,10 @@ The `kimi-cli`/`kimi-tui` providers shipped without a live `kimi` binary in the
- [ ] **Confirm the TUI auto-approve + print flags.** Verify `--yolo` (TUI auto-approve), `--print`/`--afk` (headless), and `--prompt`/`-p` (prompt value) are the real flag names, and that `--print` implies `--afk`. Adjust `ensureKimiTuiArgs`/`ensureKimiHeadlessArgs` if the CLI differs.
- [ ] **Kimi usage/quota family (out of scope of issue-2815).** Once the `kimi` usage command is confirmed, add a `FAMILIES` entry in `server/services/providerUsage.js` so the provider surfaces a quota card (currently maps to no family, like ollama-backed wrappers).
+### Warn at provider-save time when a command the CoS Runner can't spawn is configured
+
+- [ ] **Surface `isAllowedCommand` in the provider editor.** The runner's hand-curated allowlist (`server/cos-runner/allowedCommands.js`) is the exec boundary for `/spawn` and `/spawn-tui`, and it must stay hand-curated — `data/providers.json` is user-writable at runtime through `POST/PUT /api/providers` with an unconstrained `z.string()` command (`server/lib/validation.js` `providerSchema`), so deriving the allowlist from it would let a config write choose the exec target. A parity test now covers every SHIPPED provider (`server/cos-runner/allowedCommands.test.js`), but a **user-created** provider whose command isn't allowlisted still saves fine and then fails at spawn time — now with a legible "Command not allowed: X. Permitted commands: …" on the agent record rather than a mystery, which is why this is polish rather than a bug. Do NOT hard-reject on save: direct (non-runner) spawn does not consult this allowlist at all, so a custom provider can legitimately work today in direct mode, and rejecting would break that config. Right shape is an informational warning in the provider editor (and/or a badge like the "not installed" reviewer badge) when `command` is outside the runner allowlist, explaining that the provider will only run in direct-spawn mode. Deferred from the grok/kimi allowlist fix to keep that PR scoped to the paths that were actually broken.
+
### Loading-skeleton rollout follow-ups (#2843)
- [ ] **Chief of Staff has no dimension-reserving skeleton** (`client/src/pages/ChiefOfStaff.jsx` ~line 587). It still shows a centered `BrailleSpinner` because it is a bespoke two-pane shell (`lg:grid-cols-[320px_1fr]` avatar panel + chat pane), not the list/detail shape `PageSkeleton` models — a card skeleton there would misrepresent the layout worse than the spinner does. Wants either a two-pane `layout` mode on `PageSkeleton` or a local `CoSSkeleton`.
diff --git a/server/cos-runner/allowedCommands.js b/server/cos-runner/allowedCommands.js
index ae4f876a23..b1a6f741e2 100644
--- a/server/cos-runner/allowedCommands.js
+++ b/server/cos-runner/allowedCommands.js
@@ -7,7 +7,14 @@
import { basename } from 'path';
-/** Commands permitted to be spawned by the runner. */
+/**
+ * Commands permitted to be spawned by the runner.
+ *
+ * Every `command` of a shipped provider in `data.reference/providers.json` (and
+ * the toolkit's `providers.sample.json`) MUST appear here — a provider whose
+ * command is missing 400s at `/spawn-tui` and the agent dies before it ever gets
+ * a shell. `allowedCommands.test.js` enforces that parity.
+ */
export const ALLOWED_COMMANDS = new Set([
'claude',
'aider',
@@ -15,6 +22,8 @@ export const ALLOWED_COMMANDS = new Set([
'copilot',
'agy',
'gemini',
+ 'grok',
+ 'kimi',
'opencode'
]);
diff --git a/server/cos-runner/allowedCommands.test.js b/server/cos-runner/allowedCommands.test.js
index 0c454ca03d..7c9c2d11c5 100644
--- a/server/cos-runner/allowedCommands.test.js
+++ b/server/cos-runner/allowedCommands.test.js
@@ -1,6 +1,19 @@
import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'fs';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
import { isAllowedCommand, ALLOWED_COMMANDS } from './allowedCommands.js';
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+
+/** Every `command` declared by a provider in a shipped provider catalog. */
+function shippedProviderCommands(relativePath) {
+ const catalog = JSON.parse(readFileSync(join(REPO_ROOT, relativePath), 'utf8'));
+ return Object.entries(catalog.providers || {})
+ .filter(([, p]) => typeof p?.command === 'string' && p.command)
+ .map(([id, p]) => ({ id, command: p.command }));
+}
+
describe('isAllowedCommand', () => {
describe('permitted plain names', () => {
it.each([...ALLOWED_COMMANDS])('allows "%s" by exact name', (name) => {
@@ -103,6 +116,32 @@ describe('isAllowedCommand', () => {
});
});
+ // Regression guard. `grok` (and `kimi`) shipped as enabled-able providers while
+ // absent from this allowlist, so selecting grok-tui 400'd at the runner's
+ // /spawn-tui, the agent never got a PTY, and the zombie reaper finalized it a
+ // minute later as "Agent process terminated unexpectedly" — the user saw a task
+ // that simply never produced a shell. Any future provider added to a shipped
+ // catalog without an allowlist entry fails here instead.
+ describe('parity with shipped provider catalogs', () => {
+ describe.each([
+ ['data.reference/providers.json'],
+ ['server/lib/aiToolkit/defaults/providers.sample.json'],
+ ])('%s', (catalogPath) => {
+ const providers = shippedProviderCommands(catalogPath);
+
+ it('declares at least one provider command (guards against a silently empty parse)', () => {
+ expect(providers.length).toBeGreaterThan(0);
+ });
+
+ it.each(providers.map(({ id, command }) => [id, command]))(
+ 'provider "%s" runs allowlisted command "%s"',
+ (_id, command) => {
+ expect(isAllowedCommand(command)).toBe(true);
+ }
+ );
+ });
+ });
+
describe('invalid / edge inputs', () => {
it('returns false for null', () => {
expect(isAllowedCommand(null)).toBe(false);
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.js
index af1e530876..e8c61244e1 100644
--- a/server/cos-runner/index.js
+++ b/server/cos-runner/index.js
@@ -146,8 +146,19 @@ app.post('/spawn-tui', async (req, res) => {
doneSentinelPath = null,
} = req.body;
- if (!agentId || !taskId || !sessionId || !isAllowedCommand(command)) {
- return res.status(400).json({ error: 'Missing or invalid TUI spawn fields' });
+ // Name the offending field. A single opaque "missing or invalid fields" 400
+ // sent a grok-tui agent to the zombie reaper with no shell and no clue why —
+ // the real cause (`grok` absent from ALLOWED_COMMANDS) was invisible.
+ const missing = Object.entries({ agentId, taskId, sessionId })
+ .filter(([, value]) => !value)
+ .map(([key]) => key);
+ if (missing.length) {
+ return res.status(400).json({ error: `Missing TUI spawn fields: ${missing.join(', ')}` });
+ }
+ if (!isAllowedCommand(command)) {
+ return res.status(400).json({
+ error: `Command not allowed: ${command}. Permitted commands: ${[...ALLOWED_COMMANDS].join(', ')}`
+ });
}
if (!Array.isArray(args)) {
return res.status(400).json({ error: 'Invalid args: expected an array' });
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index e26f663847..3caaf1d12b 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -49,7 +49,7 @@ import { ensureDir, PATHS, sleep, tryReadFile } from '../lib/fileUtils.js';
import { createToolExecution, startExecution, completeExecution, errorExecution } from './toolStateMachine.js';
import { determineLane, acquire, release } from './executionLanes.js';
import { analyzeAgentFailure } from './agentErrorAnalysis.js';
-import { createAgentRun, checkForTaskCommit } from './agentRunTracking.js';
+import { createAgentRun, checkForTaskCommit, completeAgentRun } from './agentRunTracking.js';
import { buildAgentPrompt, getAppWorkspace } from './agentPromptBuilder.js';
import { isOllamaClaudeProvider, isClaudeCommand, providerSuppliesGithubToken } from '../lib/providerModels.js';
import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';
@@ -73,7 +73,7 @@ import { resolveAgentProviderAndModel } from './agentProviderResolution.js';
import { prepareAgentWorkspace } from './agentWorkspacePrep.js';
import { cleanupAgentWorktree } from './agentWorktreeCleanup.js';
import { runAgentCompletionCleanup } from './agentCompletionCleanup.js';
-import { dispatchRecoveredTaskOutputHook, finalizeAgent, stampLiExecutionVerdict } from './agentFinalization.js';
+import { dispatchRecoveredTaskOutputHook, finalizeAgent, releaseAgentLane, stampLiExecutionVerdict } from './agentFinalization.js';
import { extractFinalSummary } from './agentSummaryExtraction.js';
import { handleOrphanedTask } from './agentManagement.js';
@@ -733,26 +733,52 @@ export async function spawnViaRunner(agentId, task, opts) {
providerSuppliesGithubToken(provider) ? Promise.resolve({}) : resolveForgeTokenEnv(workspacePath),
]);
- const result = await spawnAgentViaRunner({
- agentId,
- taskId: task.id,
- prompt,
- workspacePath,
- model,
- // A DELTA, not a full env — the cos-runner bases it on its own process.env
- // and does the PWD pin / CLAUDECODE strip. composeProviderEnv owns the layer
- // order: forgeTokenEnv before provider.envVars so an explicit provider
- // override wins, and the OpenCode declared-models map after it so the
- // injected `--model ollama/<id>` is accepted (#2243/#2190 — this path was
- // the site that sweep originally missed).
- envVars: composeProviderEnv({
- before: { ...forgeTokenEnv, ...claudeSettingsEnv },
- provider,
+ // The runner can reject the spawn outright — a command missing from its
+ // allowlist, malformed cliArgs — or be unreachable. No child ever exists, so
+ // NO runner event will ever arrive to complete this agent. Left unhandled the
+ // throw reaches subAgentSpawner's `task:ready` listener, which only logs; and
+ // because `runnerAgents` still holds the entry, `isAgentOwnedLocally` makes
+ // the orphan sweep skip the record too, so the 3s timer above flips it to
+ // `working` and it sits there for the life of the process. Finalize with the
+ // real error instead — same shape as the runner's own `agent:error` handling
+ // in subAgentSpawner.js. (The TUI arm of this dispatch owns the equivalent
+ // handling inside spawnTuiAgent, where `finish()` is the idempotent finalizer.)
+ let result;
+ try {
+ result = await spawnAgentViaRunner({
+ agentId,
+ taskId: task.id,
+ prompt,
+ workspacePath,
model,
- }),
- cliCommand: cliConfig.command,
- cliArgs: cliConfig.args
- });
+ // A DELTA, not a full env — the cos-runner bases it on its own process.env
+ // and does the PWD pin / CLAUDECODE strip. composeProviderEnv owns the layer
+ // order: forgeTokenEnv before provider.envVars so an explicit provider
+ // override wins, and the OpenCode declared-models map after it so the
+ // injected `--model ollama/<id>` is accepted (#2243/#2190 — this path was
+ // the site that sweep originally missed).
+ envVars: composeProviderEnv({
+ before: { ...forgeTokenEnv, ...claudeSettingsEnv },
+ provider,
+ model,
+ }),
+ cliCommand: cliConfig.command,
+ cliArgs: cliConfig.args
+ });
+ } catch (err) {
+ const message = err?.message || String(err);
+ clearTimeout(agentInfo.initializationTimeout);
+ runnerAgents.delete(agentId);
+ releaseAgentLane({ agentId, success: false, exitCode: 1, executionId, laneName, errorExecutionMessage: message });
+ // validationPassed is the null sentinel (#2344): no success criterion was
+ // ever evaluated, so this records "not declared" rather than a false
+ // "declared and failed".
+ await completeAgent(agentId, { success: false, validationPassed: null, error: message });
+ await completeAgentRun(runId, '', 1, 0, { message, category: 'runner-error' });
+ emitLog('error', `Agent ${agentId} failed to spawn via runner: ${message}`, { agentId, taskId: task.id });
+ cosEvents.emit('agent:error', { agentId, taskId: task.id, error: message });
+ return null;
+ }
// Store PID in persisted state for zombie detection
await updateAgent(agentId, { pid: result.pid });
diff --git a/server/services/agentLifecycle.spawnViaRunner.test.js b/server/services/agentLifecycle.spawnViaRunner.test.js
new file mode 100644
index 0000000000..76f7e6496f
--- /dev/null
+++ b/server/services/agentLifecycle.spawnViaRunner.test.js
@@ -0,0 +1,194 @@
+/**
+ * `spawnViaRunner` — the runner-CLI arm of the spawn dispatch.
+ *
+ * The case under test is a spawn the runner REJECTS: no child process is ever
+ * created, so no `agent:completed` / `agent:error` event will ever arrive to
+ * finalize the record. Before this was handled the throw propagated to
+ * subAgentSpawner's `task:ready` listener, which only logs — and because the
+ * `runnerAgents` entry survived, `isAgentOwnedLocally` made the orphan sweep
+ * skip the record too, so the 3s initialization timer flipped it to `working`
+ * and it stayed there for the life of the process. (The TUI arm of the same
+ * dispatch had the same hole with a shorter tail: the zombie reaper eventually
+ * finalized it with a generic message that named no cause.)
+ *
+ * Lives in its own file because agentLifecycle.test.js deliberately imports no
+ * part of the orchestrator graph — it reads the source as a string. Driving the
+ * real function needs the leaves mocked, which would change that file's whole
+ * character.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('./cosRunnerClient.js', () => ({
+ spawnAgentViaRunner: vi.fn(),
+ // Reported healthy and long-lived so waitForRunnerStability returns on its
+ // first check — the failure under test is the spawn call, not the wait.
+ getRunnerHealth: vi.fn().mockResolvedValue({ available: true, uptime: 3600 }),
+}));
+
+vi.mock('./cosAgentLifecycle.js', () => ({
+ registerAgent: vi.fn().mockResolvedValue(undefined),
+ updateAgent: vi.fn().mockResolvedValue(undefined),
+ completeAgent: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock('./agentRunTracking.js', () => ({
+ createAgentRun: vi.fn().mockResolvedValue(undefined),
+ checkForTaskCommit: vi.fn().mockResolvedValue(false),
+ completeAgentRun: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock('./agentFinalization.js', () => ({
+ dispatchRecoveredTaskOutputHook: vi.fn().mockResolvedValue(undefined),
+ finalizeAgent: vi.fn().mockResolvedValue(undefined),
+ releaseAgentLane: vi.fn(),
+ stampLiExecutionVerdict: vi.fn(async (update) => update),
+}));
+
+vi.mock('./cosEvents.js', () => ({
+ emitLog: vi.fn(),
+ cosEvents: { emit: vi.fn(), on: vi.fn() },
+}));
+
+vi.mock('./cos.js', () => ({
+ getConfig: vi.fn().mockResolvedValue({}),
+ updateTask: vi.fn().mockResolvedValue(undefined),
+ getTaskById: vi.fn().mockResolvedValue(null),
+ getAgentRecord: vi.fn().mockResolvedValue(null),
+}));
+
+vi.mock('./git.js', () => ({ resolveForgeTokenEnv: vi.fn().mockResolvedValue({}) }));
+
+vi.mock('./agentCliSpawning.js', () => ({
+ buildCliSpawnConfig: vi.fn(),
+ isClaudeCliProvider: vi.fn().mockReturnValue(false),
+ isTuiProvider: vi.fn().mockReturnValue(false),
+ getClaudeSettingsEnv: vi.fn().mockResolvedValue({}),
+ spawnDirectly: vi.fn(),
+}));
+
+vi.mock('./agentTuiSpawning.js', () => ({
+ buildTuiSpawnConfig: vi.fn(),
+ spawnTuiAgent: vi.fn(),
+}));
+
+vi.mock('./agentProviderResolution.js', () => ({ resolveAgentProviderAndModel: vi.fn() }));
+vi.mock('./agentWorkspacePrep.js', () => ({ prepareAgentWorkspace: vi.fn() }));
+vi.mock('./agentWorktreeCleanup.js', () => ({ cleanupAgentWorktree: vi.fn() }));
+vi.mock('./agentCompletionCleanup.js', () => ({ runAgentCompletionCleanup: vi.fn() }));
+vi.mock('./agentSummaryExtraction.js', () => ({ extractFinalSummary: vi.fn() }));
+vi.mock('./agentManagement.js', () => ({ handleOrphanedTask: vi.fn() }));
+vi.mock('./agentPromptBuilder.js', () => ({ buildAgentPrompt: vi.fn(), getAppWorkspace: vi.fn() }));
+vi.mock('./agentErrorAnalysis.js', () => ({ analyzeAgentFailure: vi.fn().mockReturnValue(null) }));
+vi.mock('./appActivity.js', () => ({ releaseAppReviewMarker: vi.fn().mockResolvedValue(undefined) }));
+vi.mock('./instances.js', () => ({ ensureInstanceId: vi.fn().mockResolvedValue('instance-1') }));
+vi.mock('./toolStateMachine.js', () => ({
+ createToolExecution: vi.fn(() => ({ id: 'exec-1' })),
+ startExecution: vi.fn(),
+ completeExecution: vi.fn(),
+ errorExecution: vi.fn(),
+}));
+vi.mock('./executionLanes.js', () => ({
+ determineLane: vi.fn(() => 'standard'),
+ acquire: vi.fn(() => ({ success: true })),
+ release: vi.fn(),
+}));
+
+import { spawnViaRunner } from './agentLifecycle.js';
+import { spawnAgentViaRunner } from './cosRunnerClient.js';
+import { completeAgent, updateAgent } from './cosAgentLifecycle.js';
+import { completeAgentRun } from './agentRunTracking.js';
+import { releaseAgentLane } from './agentFinalization.js';
+import { runnerAgents } from './agentState.js';
+
+const REJECTION = 'Command not allowed: grok. Permitted commands: claude, codex';
+
+function runnerOpts() {
+ return {
+ prompt: 'do the thing',
+ workspacePath: '/tmp/ws',
+ model: 'some-model',
+ provider: { id: 'grok-cli', name: 'Grok Build CLI', command: 'grok', envVars: {} },
+ runId: 'run-1',
+ cliConfig: { command: 'grok', args: [] },
+ executionId: 'exec-1',
+ laneName: 'standard',
+ };
+}
+
+describe('spawnViaRunner — the runner rejects the spawn', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ runnerAgents.clear();
+ });
+
+ it('resolves instead of throwing, so the caller is not left to log-and-forget', async () => {
+ vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(new Error(REJECTION));
+ await expect(spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts())).resolves.toBeNull();
+ });
+
+ it('finalizes the agent record with the runner\'s actual error', async () => {
+ vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(new Error(REJECTION));
+
+ await spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts());
+
+ expect(completeAgent).toHaveBeenCalledWith('agent-1', expect.objectContaining({
+ success: false,
+ // No success criterion was ever evaluated — the null sentinel (#2344)
+ // keeps "never ran" out of the declared-and-failed bucket.
+ validationPassed: null,
+ error: expect.stringContaining('Command not allowed: grok'),
+ }));
+ expect(completeAgentRun).toHaveBeenCalledWith(
+ 'run-1', '', 1, 0, expect.objectContaining({ category: 'runner-error' })
+ );
+ });
+
+ it('drops the runnerAgents entry so the orphan sweep can see the record', async () => {
+ vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(new Error(REJECTION));
+
+ await spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts());
+
+ // Left behind, isAgentOwnedLocally() reports the agent as live and every
+ // sweep skips it — the record never gets reconciled at all.
+ expect(runnerAgents.has('agent-1')).toBe(false);
+ });
+
+ it('releases the lane and tool execution', async () => {
+ vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(new Error(REJECTION));
+
+ await spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts());
+
+ expect(releaseAgentLane).toHaveBeenCalledWith(expect.objectContaining({
+ agentId: 'agent-1',
+ success: false,
+ executionId: 'exec-1',
+ laneName: 'standard',
+ errorExecutionMessage: expect.stringContaining('Command not allowed: grok'),
+ }));
+ });
+
+ it('cancels the 3s initialization timer so the record cannot flip to "working"', async () => {
+ vi.useFakeTimers();
+ vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(new Error(REJECTION));
+
+ await spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts());
+ vi.mocked(updateAgent).mockClear();
+ await vi.advanceTimersByTimeAsync(5000);
+ vi.useRealTimers();
+
+ expect(vi.mocked(updateAgent).mock.calls.some(
+ ([, patch]) => patch?.metadata?.phase === 'working'
+ )).toBe(false);
+ });
+
+ it('still records the pid and returns the agent id on a successful spawn', async () => {
+ vi.mocked(spawnAgentViaRunner).mockResolvedValueOnce({ pid: 4242 });
+
+ await expect(spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts())).resolves.toBe('agent-1');
+
+ expect(updateAgent).toHaveBeenCalledWith('agent-1', { pid: 4242 });
+ expect(completeAgent).not.toHaveBeenCalled();
+ expect(runnerAgents.has('agent-1')).toBe(true);
+ });
+});
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 543af9001d..46ae505a5b 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -894,20 +894,41 @@ export async function spawnTuiAgent({
? {}
: await git.resolveForgeTokenEnv(cwd);
- const session = await createAgentTuiSession({
- agentId,
- taskId: task.id,
- provider,
- model,
- tuiConfig,
- cwd,
- forgeTokenEnv,
- doneSentinelPath,
- useDurableRunner,
- onData: handleData,
- onExit: handleExit,
- onInitialCommandSent: () => { commandInjected = true; },
- });
+ // A spawn failure here (a runner 400 for a command missing from its allowlist,
+ // an unreachable runner, a PTY that won't open) used to propagate raw out of
+ // spawnTuiAgent. The caller in subAgentSpawner only logs it, so the agent
+ // record stayed `initializing` with the real error nowhere but the server log
+ // until the zombie reaper finalized it ~a minute later as the generic "Agent
+ // process terminated unexpectedly". Finalize it here instead, carrying the
+ // spawn error into the record. Runs outside the Express request lifecycle, so
+ // there is no middleware to bubble to.
+ let session;
+ try {
+ session = await createAgentTuiSession({
+ agentId,
+ taskId: task.id,
+ provider,
+ model,
+ tuiConfig,
+ cwd,
+ forgeTokenEnv,
+ doneSentinelPath,
+ useDurableRunner,
+ onData: handleData,
+ onExit: handleExit,
+ onInitialCommandSent: () => { commandInjected = true; },
+ });
+ } catch (err) {
+ const message = err?.message || String(err);
+ appendLine(`❌ Failed to start ${provider.name || provider.id} TUI: ${message}`);
+ await finish({
+ success: false,
+ exitCode: 1,
+ error: `Failed to start TUI session: ${message}`,
+ reason: 'spawn-error',
+ });
+ return null;
+ }
sessionId = session.sessionId;
if (!sessionId) {
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index b42af7738f..42b015298b 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -2118,6 +2118,33 @@ describe('spawnTuiAgent runtime', () => {
);
});
});
+
+ // A session that never spawns at all. The runner rejects the spawn (e.g. its
+ // command allowlist doesn't carry the provider's CLI), createAgentTuiSession
+ // throws, and before this was handled the throw propagated out of
+ // spawnTuiAgent to a caller that only logs — leaving the agent record stuck in
+ // `initializing` until the zombie reaper finalized it a minute later with a
+ // generic message, so the real cause never reached the user.
+ describe('spawn failure', () => {
+ it('finalizes with the spawn error instead of throwing', async () => {
+ vi.mocked(spawnTuiSessionViaRunner).mockRejectedValueOnce(
+ new Error('Command not allowed: grok. Permitted commands: claude, codex')
+ );
+
+ // Resolves, does not reject.
+ await expect(runSpawn({ useDurableRunner: true })).resolves.toBeNull();
+ await flushMicrotasks();
+
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agent-1',
+ success: false,
+ completionReason: 'spawn-error',
+ error: expect.stringContaining('Command not allowed: grok'),
+ })
+ );
+ });
+ });
});
// Issue #2074 — the idle reaper must extend its grace while a swarm orchestrator
diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.js
index 810142e909..8f152ca26c 100644
--- a/server/services/cosAgentLifecycle.js
+++ b/server/services/cosAgentLifecycle.js
@@ -622,13 +622,26 @@ export async function cleanupZombieAgents() {
if (ageMs < 30000) continue;
}
- // Agent is not tracked anywhere and process is dead — it's a zombie
- console.log(`🧟 Zombie agent detected: ${agent.id} (PID ${agent.pid || 'unknown'} not running)`);
+ // Agent is not tracked anywhere and process is dead — it's a zombie.
+ // A record that never recorded a pid never spawned at all (the pid is
+ // written only after a successful spawn), so "terminated unexpectedly"
+ // is the wrong diagnosis: it points at a crash when the real cause is
+ // upstream, at spawn time. Spawn failures now finalize themselves with
+ // the actual error, so reaching here without a pid means the spawn died
+ // somewhere that still doesn't report — say so rather than inventing a
+ // termination that never happened.
+ const neverStarted = !agent.pid;
+ console.log(`🧟 Zombie agent detected: ${agent.id} (${neverStarted ? 'no process was ever launched' : `PID ${agent.pid} not running`})`);
state.agents[agent.id] = {
...agent,
status: 'completed',
completedAt: new Date().toISOString(),
- result: { success: false, error: 'Agent process terminated unexpectedly' }
+ result: {
+ success: false,
+ error: neverStarted
+ ? 'Agent never started — no process was ever launched (check the provider command and CoS Runner logs)'
+ : 'Agent process terminated unexpectedly'
+ }
};
cleaned.push(agent.id);
}