diff --git a/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml b/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml new file mode 100644 index 000000000..a70437d44 --- /dev/null +++ b/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml @@ -0,0 +1,22 @@ +id: bugfix-1901 +title: afx-tower-is-not-running-repor +protocol: bugfix +phase: verified +plan_phases: [] +current_plan_phase: null +gates: + pr: + status: approved + requested_at: '2026-11-24T21:25:35.735Z' + approved_at: '2026-11-25T00:47:43.268Z' +iteration: 1 +build_complete: false +history: [] +started_at: '2026-11-16T21:51:51.349Z' +updated_at: '2026-11-25T00:47:45.750Z' +pr_history: + - phase: pr + pr_number: 1976 + branch: builder/bugfix-1901 + created_at: '2026-11-24T21:15:26.038Z' +pr_ready_for_human: false diff --git a/codev/state/bugfix-1901_thread.md b/codev/state/bugfix-1901_thread.md new file mode 100644 index 000000000..5a38b2e64 --- /dev/null +++ b/codev/state/bugfix-1901_thread.md @@ -0,0 +1,159 @@ +# bugfix-1901 thread + +Issue #1901: afx reports "Tower is not running" under high load while Tower is up; the real +`/health` probe error is discarded. + +## 2026-11-16 — investigate (in progress, no code written yet) + +**Where I stopped:** still in the porch `investigate` phase (`porch done` not yet run). Root cause +is mostly established (below). Next step: confirm it **without machine load**, using a stalled local +HTTP server or an injected fetch, then signal PHASE_COMPLETE. + +### Architect ruling (binding) +- **No synthetic machine load on this Mac, ever.** My repro ran 36 CPU-burner `node -e` loops for + ~90 s, twice. Load reached 76 and slowed the owner's machine. Reproduce only with an injected + slow/failing fetch in a unit test, or one stalled local HTTP server. +- Run only the test files I touch until the PR step. + +### Findings so far +- `TowerClient.isRunning()` (`packages/sdk/src/tower-client.ts` ~L358) collapses every `/health` + failure to `false`. `request()` maps its catch to `{status: 0, error}`, and the error is dropped. +- Also: the `message.includes('ECONNREFUSED')` check in `request()` likely never matches with Node's + undici fetch, because the thrown error is `TypeError: fetch failed` and the code lives on + `err.cause`. This needs confirming with a closed port; that test is load-free. +- Tower binds `127.0.0.1:4100` (IPv4 only). The client uses `localhost`, which resolves to + `[::1, 127.0.0.1]`, so `::1` is refused and `127.0.0.1` connects. Happy-eyeballs is not the cause + in the data below. +- Probe that mirrors the SDK request (fresh node process per probe, captures the cause chain): + - load ~13: 200/200 ok, p95 1.1 s. + - load ~44: 59/300 failed, and **every failure was `TimeoutError` after the 10 s + `AbortSignal.timeout`**. There were no ECONNREFUSED/ECONNRESET failures. + - curl at load ~40: **connect was always ≤ 8 ms** (kernel accepts immediately), but + time-to-first-byte reached 29 s on `/api/version`, and `/health` did not answer within 40 s. +- So, on this machine: **Tower is listening but answers slowly** (CPU starvation of Tower's single + event loop). It is not an accept-queue or connect failure. `/health` is the heaviest route: it runs + `getInstances()` plus a full `ps -A -ww` census (~1.2 MB, 757 lines) per request + (`process-census.ts`, 5 s ps timeout). Caveat: my probes ran 10–12 `/health` calls concurrently, + which inflated this. + +## 2026-11-24 — investigate complete (resumed after reboot) + +Load-free repro (`scratchpad/repro/stalled.mjs`: local servers on ephemeral ports, nothing +touching Tower or machine load) feeds each shape through an exact copy of the SDK's catch mapping: + +| endpoint | fetch throws | `request()` keeps | `isRunning()` | +|---|---|---|---| +| nothing listening | `TypeError: fetch failed`, `cause.code=ECONNREFUSED` | `"fetch failed"` | false | +| listening, never answers | `TimeoutError` | `"Request timeout"` | false | +| listening, resets | `TypeError: fetch failed`, `cause.code=ECONNRESET` | `"fetch failed"` | false | + +**Root cause.** +1. `isRunning()` returns a bare boolean, so every failure shape becomes "Tower is not running" in + the callers. +2. `request()`'s `message.includes('ECONNREFUSED')` is dead code under Node's fetch, because the + errno code lives on `err.cause`. So even the raw result cannot tell refused from reset. +3. Under load the live failure mode is (2) in the table: Tower is listening, but its event loop is + starved past the 10 s abort. + +**Worse adjacent paths found (same false negative, destructive follow-on):** +- `afx workspace start` (`start.ts`): a false negative calls `towerStart()`. That probes + `/api/status` with a 2 s timeout, decides "port in use but not responding", and **SIGTERMs the PID + on 4100, i.e. the live Tower**. Running `afx tower start` by hand, as the old message suggests, + hits the same branch. +- `afx workspace stop` (`stop.ts`): a false negative skips the Tower kills but still runs + `clearRuntime()`, wiping the builder registry while Tower keeps those builders running. +- `rename.ts`, `shell.ts` and `open.ts` print "not running" for any `status === 0`. +- `ide.ts` is already correct: it uses `http.request`, so `err.code` is reliable, and it reports + timeouts separately. No change needed. + +**Scope:** fits BUGFIX (estimate ~250 LOC with tests). One open decision is flagged to the +architect, not changed here: `towerStart()`'s zombie-kill policy, i.e. what `afx tower start` +should do when the port is held but `/api/status` misses a 2 s probe. + +### Architect ruling 2026-11-24: towerStart in this PR, option (b) +1. `towerStart` goes through the same `probeHealth` helper. + - not-running (refused): start, as today. + - running: say it is already running, as today. + - unresponsive: **do not kill**. Exit non-zero and print the listening PID and its command + line. Say that if the machine is busy the user should wait and retry, and that to replace the + process deliberately they run `afx tower stop` and then `afx tower start`. Stopping a Tower is + a human decision, never a side effect of start. +2. `afx tower stop` must still stop an unresponsive Tower. Verified: `towerStop()` kills the PIDs + from `getProcessesOnPort()` (lsof) and does no health probe. Leave it unrouted. +3. Tests use a stalled local server (child process, ephemeral port): + - start does not signal the PID and exits non-zero with the message; + - a refused port starts normally; + - stop still kills the stalled server. +4. This is Tower lifecycle code: dispatch the Windows workflow on the branch and link the run in + the PR. +5. The PRFT write-up gives the towerStart change its own paragraph, as a behaviour change: start no + longer replaces a hung Tower by itself. + +## 2026-11-24 — fix committed (98d72e49f fix, 5522a861e test) + +- AIR #1950 (merged to main mid-project) had already fixed the dead ECONNREFUSED check and added + `connectionRefused` to `request()`. I reused it rather than adding a parallel flag, and tightened + it: a localhost AggregateError counts as refused only when every attempt refused. +- The shared helper lives in its own module (`lib/tower-check.ts`), so the many tests that mock all + of `lib/tower-client.js` only needed a one-line `probeHealth` mapped from their `isRunning` mock. +- Hazard caught: the #1691 and windows-launch towerStart tests stubbed `node:http` to fake a + refusal. With the probe moved to fetch they would have hit the LIVE Tower on 4100, so both now + stub `TowerClient.probeHealth`. +- Fails-without-fix confirmed. Pre-fix `tower.ts` makes the stalled-holder test fail (it SIGTERMs + the holder). Removing the every-address rule fails the `::1` masking test. +- End to end, with the real built CLI, isolated HOME, a stalled holder on a spare port: + `afx tower start --port P` exits 1 after 21 s naming the PID and command line, and the holder + survives. `afx tower stop --port P` kills it. Stop needed the SIGKILL fallback there only because + the harness parent was blocked in `spawnSync` and could not reap its child (zombie answers + kill -0). +- `status --json` still reports `tower.running: false` for an unresponsive Tower; the human output + says "not answering" with the reason. Left as is (minimal). + +## 2026-11-24 — PR #1976, CMAP round 1 + +- codex REQUEST_CHANGES (real): `workspace stop` guarded only the health probe. A healthy probe + followed by an unanswered `deactivateWorkspace()` still fell into legacy cleanup and + `clearRuntime()`. Fixed: the SDK passes through `status`/`connectionRefused`, and stop aborts + when Tower took the request but never answered. A test pins it (fails without the guard). +- claude APPROVE, non-blocking. Fixed in place: + - Broken-IPv6 regression: `ENETUNREACH` on `::1` plus a refused `127.0.0.1` read as unresponsive, + so `workspace start` would have exited instead of starting Tower. Refused now means "at least + one attempt refused and every attempt failed before reaching a server". + - `open` could exit 1 silently. + - The start/stop guards had no tests; added (start fails without its guard). +- Deferred, suggested as follow-ups: + - `/health` cost under load (`getInstances` plus a full `ps` census, probed up to twice per gate); + server-side. + - `send` stacking `--retry` over `checkTower`'s own retry. + - `status --json` not distinguishing busy from down. +- Owner ruling main-42: the 900000 ms tests timeout is now in the shared config.json, so I dropped + my local override. + +## 2026-11-24 — architect round: merge with Spec 1940, two follow-ups pulled in + +- Merged origin/main (merge 325ae5022), which brought PR #1957 (named architects). It also changes + `send.ts` and the SDK client. Read as one piece: + - an unresponsive `/health` stops at the gate, before any send or address-book question; + - an unanswered send is a timeout and never asks the address book, which only a NOT_FOUND triggers; + - **gap:** NOT_FOUND followed by an unanswered address-book check was reported as the bare + not-found. `getAddressBook()` now marks a failure with no HTTP answer as `unanswered`, and + send says the check went unanswered and to retry. An answered failure still leaves the + not-found, as Spec 1940's test pins. +- Retry ownership: `checkTower` takes `retries` (default 1). `send --retry N` passes 0, so the budget + owns the retrying: N + 1 probes, not 2(N + 1). Without `--retry` it stays at 2. +- `status --json`: `tower` is `{running, state, error}`. `running` is unchanged for existing + scripts, and `error` is null unless unresponsive. +- Follow-up (1), the cheap liveness route, was filed by the architect as #1977. +- Fails-without-change confirmed for each: retry-line revert → probe-count test fails; merged-head + send.ts/status.ts → address-book test and all 3 status-json tests fail. + +### Planned fix (per the issue's Fix section) +One shared helper over the SDK probe that classifies the failure: +- connect refused (nothing listening) → "Tower is not running. Start it with: afx tower start" +- timeout / reset / bad response → retry once after a short pause; if that also fails, report + "Tower did not answer /health () after N ms; it appears to be up, retry", with no + suggestion to start Tower. + +Route `send`, `interrupt`, `reset`, `rename`, `ide`, `status`, `self-refresh` and the other +`isRunning()` callers through that helper. Unit tests use an injected fetch, as the issue's Testing +section describes. diff --git a/packages/codev/src/agent-farm/__tests__/air-1893-status-live-state.test.ts b/packages/codev/src/agent-farm/__tests__/air-1893-status-live-state.test.ts index 10b7f177b..3147be31f 100644 --- a/packages/codev/src/agent-farm/__tests__/air-1893-status-live-state.test.ts +++ b/packages/codev/src/agent-farm/__tests__/air-1893-status-live-state.test.ts @@ -29,6 +29,7 @@ vi.mock('../state.js', () => ({ loadState: (...a: any[]) => mockLoadState(...a) vi.mock('../lib/tower-client.js', () => ({ getTowerClient: () => ({ isRunning: (...a: any[]) => mockIsRunning(...a), + probeHealth: async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }), getHealth: (...a: any[]) => mockGetHealth(...a), getWorkspaceStatus: (...a: any[]) => mockGetWorkspaceStatus(...a), getOverview: (...a: any[]) => mockGetOverview(...a), diff --git a/packages/codev/src/agent-farm/__tests__/air-1950-send-exit-retry.test.ts b/packages/codev/src/agent-farm/__tests__/air-1950-send-exit-retry.test.ts index 8ed098a31..a4eb15bce 100644 --- a/packages/codev/src/agent-farm/__tests__/air-1950-send-exit-retry.test.ts +++ b/packages/codev/src/agent-farm/__tests__/air-1950-send-exit-retry.test.ts @@ -18,6 +18,7 @@ vi.mock('../lib/tower-client.js', async (importOriginal) => ({ ...(await importOriginal()), TowerClient: class { isRunning = isRunningMock; + probeHealth = async () => ((await isRunningMock()) ? { state: 'running' } : { state: 'not-running' }); sendMessage = sendMessageMock; }, })); diff --git a/packages/codev/src/agent-farm/__tests__/bugfix-1691-tower-start-surface-refusal.test.ts b/packages/codev/src/agent-farm/__tests__/bugfix-1691-tower-start-surface-refusal.test.ts index 1de7fbcee..0dfd78619 100644 --- a/packages/codev/src/agent-farm/__tests__/bugfix-1691-tower-start-surface-refusal.test.ts +++ b/packages/codev/src/agent-farm/__tests__/bugfix-1691-tower-start-surface-refusal.test.ts @@ -38,18 +38,18 @@ const h = vi.hoisted(() => { vi.mock('../lib/tower-client.js', () => ({ DEFAULT_TOWER_PORT: 4100, AGENT_FARM_DIR: h.agentFarmDir, + // towerStart's "is one already up?" probe (#1901): nothing is listening, so it spawns. + TowerClient: class { + async probeHealth() { + return { state: 'not-running' }; + } + }, })); vi.mock('../utils/config.js', () => ({ getConfig: () => ({ serversDir: h.agentFarmDir }), })); -// isPortInUse() = !isPortAvailable(); "available" keeps towerStart off the -// zombie-cleanup branch and straight onto the spawn path. -vi.mock('../utils/shell.js', () => ({ - isPortAvailable: vi.fn(async () => true), -})); - // The readiness probe uses http.request; a request that immediately errors makes // isServerResponding() resolve false (the port never comes up on a refusal). vi.mock('node:http', () => { diff --git a/packages/codev/src/agent-farm/__tests__/bugfix-1901-send-unresponsive.test.ts b/packages/codev/src/agent-farm/__tests__/bugfix-1901-send-unresponsive.test.ts new file mode 100644 index 000000000..f8d3ebd46 --- /dev/null +++ b/packages/codev/src/agent-farm/__tests__/bugfix-1901-send-unresponsive.test.ts @@ -0,0 +1,161 @@ +/** + * Issue #1901 × Spec 1940 — `afx send` against a Tower that is up but not answering. + * + * Two changes meet in send's failure handling. Spec 1940 asks the address book when a + * `:architect:` send comes back not found, to tell an older Tower. #1901 tells a + * Tower that is not running from one that took the connection and did not answer. A busy Tower + * must read as busy at every step: not "not running", not "older Tower", and not a not-found + * that nobody could check. And `--retry` must not stack on the health gate's own retry: one loop + * owns the retrying, and the total number of probes is pinned here. + * + * Same harness as `spec-1940-older-tower-send.test.ts`: the real command and the real SDK client, + * over a transport that answers as the Tower under test does. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { mkdirSync, mkdtempSync, realpathSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { stripVTControlCharacters } from 'node:util'; +import { TowerClient as SdkTowerClient } from '@cluesmith/codev-sdk/tower-client'; + +const transport = vi.hoisted(() => ({ fetchFn: undefined as unknown as typeof fetch })); + +vi.mock('../lib/tower-client.js', () => ({ + TowerClient: class extends SdkTowerClient { + constructor() { + super({ fetchFn: (...args: Parameters) => transport.fetchFn(...args) }); + } + }, +})); + +const { send } = await import('../commands/send.js'); + +type Route = () => Response | Error; + +function json(status: number, payload: unknown): Response { + return new Response(JSON.stringify(payload), { status, headers: { 'Content-Type': 'application/json' } }); +} + +/** What Node's fetch throws when the 10 s abort fires before Tower answers. */ +const noAnswer = () => Object.assign(new Error('The operation was aborted due to timeout'), { name: 'TimeoutError' }); +const healthy = () => json(200, { status: 'healthy' }); +/** The not-found an older Tower gives `codev:architect:review` (it reads `architect:review` as a builder). */ +const olderNotFound = () => + json(404, { error: 'NOT_FOUND', message: "Agent 'architect:review' not found in workspace 'codev'." }); + +/** A Tower as a transport: each route answers, or throws to stand for no answer. Records the paths asked. */ +function tower(routes: { health: Route; send?: Route; addressBook?: Route }): string[] { + const asked: string[] = []; + transport.fetchFn = (async (input: Parameters[0]) => { + const { pathname } = new URL(String(input)); + asked.push(pathname); + const route = { '/health': routes.health, '/api/send': routes.send, '/api/address-book': routes.addressBook }[pathname]; + if (!route) throw new Error(`unexpected request: ${pathname}`); + const outcome = route(); + if (outcome instanceof Error) throw outcome; + return outcome; + }) as typeof fetch; + return asked; +} + +class Exit extends Error { + constructor(readonly code: number) { + super(`exit ${code}`); + } +} + +const UNANSWERED_HEALTH = /^\[error\] Tower did not answer \/health \(Request timeout\) after \d+ ms; it appears to be up, retry$/; + +describe('afx send against a busy Tower (#1901 × Spec 1940)', () => { + let workspace: string; + let errors: string[]; + const cwd = process.cwd(); + const architectName = process.env.CODEV_ARCHITECT_NAME; + + beforeEach(() => { + workspace = realpathSync(mkdtempSync(join(tmpdir(), 'bugfix-1901-send-'))); + mkdirSync(join(workspace, '.git')); + process.chdir(workspace); + process.env.CODEV_ARCHITECT_NAME = 'main'; + errors = []; + vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation((...args) => void errors.push(stripVTControlCharacters(args.join(' ')))); + vi.spyOn(process, 'exit').mockImplementation(((code?: number) => { + throw new Exit(code ?? 0); + }) as never); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + process.chdir(cwd); + if (architectName === undefined) delete process.env.CODEV_ARCHITECT_NAME; + else process.env.CODEV_ARCHITECT_NAME = architectName; + rmSync(workspace, { recursive: true, force: true }); + }); + + /** Run `send`, letting faked retry pauses elapse, and return how it exited. */ + async function sendExpectingExit(options: Parameters[0]): Promise { + vi.useFakeTimers(); + const settled = expect(send(options)).rejects.toMatchObject({ code: 1 }); + await vi.runAllTimersAsync(); + await settled; + } + + describe('a three-part address', () => { + it('reports an unanswered /health as unresponsive, before any send or address-book question', async () => { + const asked = tower({ health: noAnswer }); + + await sendExpectingExit({ builder: 'codev:architect:review', message: 'hello' }); + + expect(errors).toHaveLength(1); + expect(errors[0]).toMatch(UNANSWERED_HEALTH); + expect(asked).toEqual(['/health', '/health']); + }); + + it('reports an unanswered address-book check as unresponsive, not as an older Tower or a not-found', async () => { + const asked = tower({ health: healthy, send: olderNotFound, addressBook: noAnswer }); + + await sendExpectingExit({ builder: 'codev:architect:review', message: 'hello' }); + + expect(errors).toEqual([ + '[error] Tower did not answer the address-book check (Request timeout) needed to tell whether ' + + 'codev:architect:review is missing or this Tower predates that address form; it appears to be up, retry', + ]); + expect(asked).toEqual(['/health', '/api/send', '/api/address-book']); + }); + + it('reports an unanswered send as a timeout, and asks the address book nothing', async () => { + const asked = tower({ health: healthy, send: noAnswer }); + + await sendExpectingExit({ builder: 'codev:architect:review', message: 'hello' }); + + expect(errors).toEqual(['[error] Request timeout']); + expect(asked).toEqual(['/health', '/api/send']); + }); + }); + + describe('who owns the retry', () => { + it('without --retry, the health gate retries once: two probes in all', async () => { + const asked = tower({ health: noAnswer }); + + await sendExpectingExit({ builder: 'spir-42', message: 'hello' }); + + expect(asked).toEqual(['/health', '/health']); + expect(errors.filter((line) => line.startsWith('[retry]'))).toEqual([]); + }); + + it('with --retry N, that budget owns the retrying and the gate probes once per attempt: N + 1 probes', async () => { + const asked = tower({ health: noAnswer }); + + await sendExpectingExit({ builder: 'spir-42', message: 'hello', retry: 2 }); + + expect(asked).toEqual(['/health', '/health', '/health']); + const retries = errors.filter((line) => line.startsWith('[retry]')); + expect(retries).toHaveLength(2); + expect(retries[0]).toContain('Tower did not answer /health (Request timeout); nothing has been sent. Retry 1/2'); + expect(errors.at(-1)).toMatch(UNANSWERED_HEALTH); + }); + }); +}); diff --git a/packages/codev/src/agent-farm/__tests__/bugfix-1901-status-json.test.ts b/packages/codev/src/agent-farm/__tests__/bugfix-1901-status-json.test.ts new file mode 100644 index 000000000..0205ac2d9 --- /dev/null +++ b/packages/codev/src/agent-farm/__tests__/bugfix-1901-status-json.test.ts @@ -0,0 +1,73 @@ +/** + * Issue #1901 — `afx status --json` tells a busy Tower from a down one. + * + * `tower.running` stays as it was (false for both, so existing scripts read the same). `state` + * says which (`running`, `not-running`, `unresponsive`), and `error` says why an unresponsive + * Tower did not answer, null otherwise: the file's nullable-not-optional contract. + * + * Mocking harness mirrors status-fleet-observability.test.ts. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; + +const mockProbe = vi.fn(); + +vi.mock('../utils/config.js', () => ({ + getConfig: vi.fn(() => ({ workspaceRoot: '/fake/workspace' })), +})); +vi.mock('../state.js', () => ({ + loadState: () => ({ architect: null, architects: [], builders: [], utils: [], annotations: [] }), +})); +vi.mock('../lib/tower-client.js', () => ({ + getTowerClient: () => ({ + probeHealth: (...a: unknown[]) => mockProbe(...a), + getHealth: async () => ({ status: 'healthy', uptime: 1, activeWorkspaces: 0, memoryUsage: 0 }), + getWorkspaceStatus: async () => null, + getOverview: async () => null, + }), +})); +vi.mock('../../lib/config.js', () => ({ loadConfig: vi.fn(() => ({})) })); +vi.mock('../utils/logger.js', () => ({ + logger: { header: vi.fn(), success: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn(), info: vi.fn(), kv: vi.fn(), blank: vi.fn(), row: vi.fn() }, + fatal: vi.fn((msg: string) => { + throw new Error(msg); + }), +})); + +import { status } from '../commands/status.js'; + +describe('afx status --json: busy apart from down (#1901)', () => { + let logSpy: ReturnType; + + beforeEach(() => { + mockProbe.mockReset(); + logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); + }); + + afterEach(() => { + logSpy.mockRestore(); + }); + + async function towerField(): Promise { + await status({ json: true }); + expect(logSpy).toHaveBeenCalledTimes(1); + return JSON.parse(String(logSpy.mock.calls[0][0])).tower; + } + + it('reports an unresponsive Tower with its reason', async () => { + mockProbe.mockResolvedValue({ state: 'unresponsive', error: 'Request timeout' }); + expect(await towerField()).toEqual({ running: false, state: 'unresponsive', error: 'Request timeout' }); + }); + + it('reports a down Tower as not-running, error null (present, not omitted)', async () => { + mockProbe.mockResolvedValue({ state: 'not-running' }); + const tower = await towerField(); + expect(tower).toEqual({ running: false, state: 'not-running', error: null }); + expect(Object.prototype.hasOwnProperty.call(tower, 'error')).toBe(true); + }); + + it('reports a running Tower as before, with state running', async () => { + mockProbe.mockResolvedValue({ state: 'running' }); + expect(await towerField()).toEqual({ running: true, state: 'running', error: null }); + }); +}); diff --git a/packages/codev/src/agent-farm/__tests__/bugfix-1901-tower-check.test.ts b/packages/codev/src/agent-farm/__tests__/bugfix-1901-tower-check.test.ts new file mode 100644 index 000000000..0167f408a --- /dev/null +++ b/packages/codev/src/agent-farm/__tests__/bugfix-1901-tower-check.test.ts @@ -0,0 +1,73 @@ +/** + * Issue #1901 — every CLI command's Tower gate goes through `checkTower`. + * + * Under heavy load a live Tower accepts the connection at once but its starved event loop misses + * the request timeout. The old gate (`isRunning()`, a bare boolean) reported that as "Tower is not + * running. Start it with: afx tower start". These tests drive the real CLI client with an + * injected fetch, the way Node's fetch fails, and pin the three outcomes the issue asks for. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { TowerClient } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; + +const errno = (code: string) => Object.assign(new Error(`connect ${code}`), { code }); +/** Node's fetch over `localhost`: one attempt per address, wrapped as the cause. */ +const refused = () => + Object.assign(new TypeError('fetch failed'), { + cause: Object.assign(new AggregateError([errno('ECONNREFUSED'), errno('ECONNREFUSED')], ''), { code: 'ECONNREFUSED' }), + }); +const reset = () => Object.assign(new TypeError('fetch failed'), { cause: errno('ECONNRESET') }); +const timeout = () => Object.assign(new Error('The operation was aborted due to timeout'), { name: 'TimeoutError' }); +const healthy = () => + ({ ok: true, status: 200, json: async () => ({ status: 'healthy' }), text: async () => '' }) as Response; + +/** A fetch that plays `steps` in order: an Error is thrown, anything else is returned. */ +function scriptedFetch(...steps: Array<() => Error | Response>) { + const queue = [...steps]; + return vi.fn(async () => { + const step = queue.shift(); + if (!step) throw new Error('scriptedFetch: called more times than scripted'); + const outcome = step(); + if (outcome instanceof Error) throw outcome; + return outcome; + }) as unknown as typeof fetch & ReturnType; +} + +const clientWith = (fetchFn: typeof fetch) => new TowerClient({ port: 4199, getAuthKey: () => null, fetchFn }); + +describe('checkTower (#1901)', () => { + it('says "not running" and suggests starting Tower only when the connection is refused', async () => { + const fetchFn = scriptedFetch(refused); + const check = await checkTower(clientWith(fetchFn), { retryDelayMs: 0 }); + expect(check).toEqual({ state: 'not-running', message: 'Tower is not running. Start it with: afx tower start' }); + expect(fetchFn).toHaveBeenCalledTimes(1); + }); + + it('passes silently when a reset is followed by a healthy answer', async () => { + const fetchFn = scriptedFetch(reset, healthy); + expect(await checkTower(clientWith(fetchFn), { retryDelayMs: 0 })).toEqual({ state: 'running' }); + expect(fetchFn).toHaveBeenCalledTimes(2); + }); + + it('passes silently when a timeout is followed by a healthy answer', async () => { + const fetchFn = scriptedFetch(timeout, healthy); + expect(await checkTower(clientWith(fetchFn), { retryDelayMs: 0 })).toEqual({ state: 'running' }); + }); + + it('after two failures reports the underlying error and never suggests starting Tower', async () => { + const fetchFn = scriptedFetch(timeout, reset); + const check = await checkTower(clientWith(fetchFn), { retryDelayMs: 0 }); + expect(check.state).toBe('unresponsive'); + if (check.state !== 'unresponsive') return; + expect(check.message).toMatch(/^Tower did not answer \/health \(fetch failed: ECONNRESET\) after \d+ ms; it appears to be up, retry$/); + expect(check.message).not.toContain('not running'); + expect(check.message).not.toContain('afx tower start'); + expect(fetchFn).toHaveBeenCalledTimes(2); + }); + + it('names the caller\'s own start command in the "not running" message', async () => { + const check = await checkTower(clientWith(scriptedFetch(refused)), { startCommand: 'afx workspace start' }); + expect(check).toMatchObject({ message: 'Tower is not running. Start it with: afx workspace start' }); + }); +}); diff --git a/packages/codev/src/agent-farm/__tests__/bugfix-1901-tower-start-unresponsive.test.ts b/packages/codev/src/agent-farm/__tests__/bugfix-1901-tower-start-unresponsive.test.ts new file mode 100644 index 000000000..3b464125c --- /dev/null +++ b/packages/codev/src/agent-farm/__tests__/bugfix-1901-tower-start-unresponsive.test.ts @@ -0,0 +1,146 @@ +/** + * Issue #1901 — `afx tower start` must never stop a Tower because the machine is busy. + * + * The old start probed `/api/status` with a 2 s timeout and, when that missed, decided "port in + * use but not responding", SIGTERMed every PID on the port and started a new Tower. Under load + * that PID is the live Tower. Start now probes `/health` through `checkTower`: a refused port is + * started on as before; a holder that accepted the connection but did not answer is left alone, + * named, and the command exits non-zero. Replacing it is `afx tower stop`, which must still work. + * + * The stalled holder is a real child process listening on an ephemeral port that never answers, + * so these tests cannot reach the developer's Tower on 4100. Only the client's request timeout is + * shortened (300 ms); the fetch, the port lookup and the process table are real. + */ + +import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest'; +import type { ChildProcess } from 'node:child_process'; +import fs from 'node:fs'; +import net from 'node:net'; +import path from 'node:path'; + +const h = vi.hoisted(() => { + const nodeOs = require('node:os') as typeof import('node:os'); + const nodePath = require('node:path') as typeof import('node:path'); + const nodeFs = require('node:fs') as typeof import('node:fs'); + const nodeEvents = require('node:events') as typeof import('node:events'); + const dir = nodeFs.mkdtempSync(nodePath.join(nodeOs.tmpdir(), 'af-1901-')); + // A dummy compiled server so towerStart takes the `node ` branch; spawn is stubbed. + nodeFs.writeFileSync(nodePath.join(dir, 'tower-server.js'), '// stub'); + const fakeDaemon = () => Object.assign(new nodeEvents.EventEmitter(), { pid: 999_999, unref: () => {} }); + return { dir, fakeDaemon }; +}); + +vi.mock('../lib/tower-client.js', async (importOriginal) => { + const actual = await importOriginal(); + class ShortTimeoutTowerClient extends actual.TowerClient { + constructor(options: import('../lib/tower-client.js').TowerClientOptions = {}) { + super({ ...options, getAuthKey: () => null, requestTimeoutMs: 300 }); + } + } + return { ...actual, AGENT_FARM_DIR: h.dir, TowerClient: ShortTimeoutTowerClient }; +}); + +vi.mock('../utils/config.js', () => ({ + getConfig: () => ({ serversDir: h.dir }), +})); + +vi.mock('node:child_process', async () => { + const actual = await vi.importActual('node:child_process'); + return { ...actual, spawn: vi.fn(() => h.fakeDaemon()) }; +}); + +const { towerStart, towerStop } = await import('../commands/tower.js'); +const { spawn: daemonSpawn } = await import('node:child_process'); +const { spawn: realSpawn } = await vi.importActual('node:child_process'); + +const STALLED_SERVER = "require('node:http').createServer(() => {}).listen(0, '127.0.0.1', function () { console.log(this.address().port); })"; + +/** A process that accepts every connection on its port and never answers. */ +async function startStalledServer(): Promise<{ child: ChildProcess; port: number }> { + const child = realSpawn(process.execPath, ['-e', STALLED_SERVER], { stdio: ['ignore', 'pipe', 'inherit'] }); + children.push(child); + const port = await new Promise((resolve, reject) => { + child.stdout!.once('data', (chunk) => resolve(Number(String(chunk).trim()))); + child.once('exit', (code) => reject(new Error(`stalled server exited before listening (code ${code})`))); + }); + return { child, port }; +} + +async function refusedPort(): Promise { + const server = net.createServer(); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address() as net.AddressInfo; + await new Promise((resolve) => server.close(() => resolve())); + return port; +} + +const isAlive = (child: ChildProcess) => child.exitCode === null && child.signalCode === null; + +const children: ChildProcess[] = []; +let stderr: string[]; + +beforeEach(() => { + stderr = []; + vi.mocked(daemonSpawn).mockClear(); + vi.spyOn(console, 'error').mockImplementation((...args: unknown[]) => { + stderr.push(args.map(String).join(' ')); + }); + vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(process, 'exit').mockImplementation(((code?: number) => { + throw new Error(`process.exit:${code ?? 0}`); + }) as never); +}); + +afterEach(() => { + vi.restoreAllMocks(); + for (const child of children.splice(0)) { + if (isAlive(child)) child.kill('SIGKILL'); + } +}); + +afterAll(() => { + fs.rmSync(h.dir, { recursive: true, force: true }); +}); + +describe('afx tower start against a port it cannot get an answer from (#1901)', () => { + it('signals nothing, exits non-zero, and names the process holding the port', async () => { + const { child, port } = await startStalledServer(); + const kill = vi.spyOn(process, 'kill'); + + await expect(towerStart({ port, wait: false })).rejects.toThrow('process.exit:1'); + + expect(kill).not.toHaveBeenCalledWith(child.pid, expect.anything()); + expect(isAlive(child)).toBe(true); + expect(daemonSpawn).not.toHaveBeenCalled(); + + const output = stderr.join('\n'); + expect(output).toContain(`A process is listening on port ${port} but did not answer /health`); + expect(output).toContain(`PID ${child.pid}: `); + expect(output).toContain('createServer'); + expect(output).toContain('If the machine is busy, wait and run afx tower start again.'); + expect(output).toContain('To replace it deliberately: afx tower stop, then afx tower start.'); + expect(output).not.toContain('Tower is not running'); + }, 30_000); + + it('starts normally when the connection is refused (nothing listening)', async () => { + const port = await refusedPort(); + + await towerStart({ port, wait: false }); + + expect(daemonSpawn).toHaveBeenCalledTimes(1); + const [, args] = vi.mocked(daemonSpawn).mock.calls[0]; + expect(args).toEqual(expect.arrayContaining([path.join(h.dir, 'tower-server.js'), String(port)])); + }, 30_000); +}); + +describe('afx tower stop against the same unresponsive holder (#1901)', () => { + it('still stops it: replacing a hung Tower stays the deliberate path', async () => { + const { child, port } = await startStalledServer(); + const exited = new Promise((resolve) => child.once('exit', resolve)); + + await towerStop({ port }); + await exited; + + expect(isAlive(child)).toBe(false); + }, 30_000); +}); diff --git a/packages/codev/src/agent-farm/__tests__/bugfix-1901-workspace-start-stop.test.ts b/packages/codev/src/agent-farm/__tests__/bugfix-1901-workspace-start-stop.test.ts new file mode 100644 index 000000000..9b3b59a7b --- /dev/null +++ b/packages/codev/src/agent-farm/__tests__/bugfix-1901-workspace-start-stop.test.ts @@ -0,0 +1,101 @@ +/** + * Issue #1901 — `afx workspace start` and `afx workspace stop` must not act on a Tower that is + * busy rather than down. + * + * Both used to treat any failed health probe as "Tower is not running". Start then started one, + * falling into `towerStart`'s old "zombie" branch that SIGTERMed the live Tower. Stop fell back + * to a local cleanup ending in `clearRuntime()`, wiping the registry of builders that were still + * running. That fallback is for a Tower that answered with an error or is not running. A Tower + * that took the request and never answered may still be running everything, so stop aborts and + * clears nothing: at the health probe, and again at the deactivation request itself. + */ + +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +const mockProbe = vi.fn(); +const mockDeactivate = vi.fn(); +const mockActivate = vi.fn(); +const mockClearRuntime = vi.fn(); +const mockTowerStart = vi.fn(); + +vi.mock('../lib/tower-client.js', () => ({ + DEFAULT_TOWER_PORT: 4100, + getTowerClient: () => ({ + probeHealth: (...a: unknown[]) => mockProbe(...a), + deactivateWorkspace: (...a: unknown[]) => mockDeactivate(...a), + activateWorkspace: (...a: unknown[]) => mockActivate(...a), + getWorkspaceUrl: () => 'http://localhost:4100/workspace/alpha/', + killTerminal: vi.fn(), + }), +})); +vi.mock('../commands/tower.js', () => ({ towerStart: (...a: unknown[]) => mockTowerStart(...a) })); +vi.mock('../state.js', () => ({ + loadState: () => ({ builders: [], utils: [], architects: [] }), + clearRuntime: (...a: unknown[]) => mockClearRuntime(...a), + getArchitects: () => [], +})); +vi.mock('../utils/config.js', () => ({ getConfig: () => ({ workspaceRoot: '/work/alpha' }) })); +vi.mock('../utils/index.js', () => ({ getConfig: () => ({ workspaceRoot: '/work/alpha' }) })); +vi.mock('../utils/shell.js', () => ({ openBrowser: vi.fn() })); +vi.mock('../utils/logger.js', () => ({ + logger: { header: vi.fn(), info: vi.fn(), success: vi.fn(), debug: vi.fn(), blank: vi.fn(), warn: vi.fn(), error: vi.fn(), kv: vi.fn() }, + fatal: (message: string) => { + throw new Error(`FATAL: ${message}`); + }, +})); + +const { start } = await import('../commands/start.js'); +const { stop } = await import('../commands/stop.js'); + +const unresponsive = { state: 'unresponsive', error: 'Request timeout' }; + +beforeEach(() => { + for (const mock of [mockProbe, mockDeactivate, mockActivate, mockClearRuntime, mockTowerStart]) mock.mockReset(); + mockActivate.mockResolvedValue({ ok: true }); +}); + +describe('afx workspace start against a busy Tower (#1901)', () => { + it('exits with the reason and never starts (or replaces) a Tower', async () => { + mockProbe.mockResolvedValue(unresponsive); + + await expect(start({ noBrowser: true })).rejects.toThrow(/FATAL: Tower did not answer \/health \(Request timeout\)/); + expect(mockTowerStart).not.toHaveBeenCalled(); + expect(mockActivate).not.toHaveBeenCalled(); + }); + + it('starts Tower when the connection is refused, as before', async () => { + mockProbe.mockResolvedValue({ state: 'not-running' }); + + await start({ noBrowser: true }); + expect(mockTowerStart).toHaveBeenCalledTimes(1); + expect(mockActivate).toHaveBeenCalledWith('/work/alpha'); + }); +}); + +describe('afx workspace stop against a busy Tower (#1901)', () => { + it('aborts without clearing anything when /health is not answered', async () => { + mockProbe.mockResolvedValue(unresponsive); + + await expect(stop()).rejects.toThrow(/FATAL: Tower did not answer \/health \(Request timeout\)/); + expect(mockDeactivate).not.toHaveBeenCalled(); + expect(mockClearRuntime).not.toHaveBeenCalled(); + }); + + it('aborts without clearing anything when the deactivation request is not answered', async () => { + mockProbe.mockResolvedValue({ state: 'running' }); + mockDeactivate.mockResolvedValue({ ok: false, status: 0, error: 'Request timeout' }); + + await expect(stop()).rejects.toThrow( + 'FATAL: Tower did not answer the deactivation request (Request timeout); nothing was cleared.', + ); + expect(mockClearRuntime).not.toHaveBeenCalled(); + }); + + it('still falls back to local cleanup when Tower answers with an error', async () => { + mockProbe.mockResolvedValue({ state: 'running' }); + mockDeactivate.mockResolvedValue({ ok: false, status: 404, error: 'Workspace not found' }); + + await stop(); + expect(mockClearRuntime).toHaveBeenCalledWith('/work/alpha'); + }); +}); diff --git a/packages/codev/src/agent-farm/__tests__/send-hold-warning.test.ts b/packages/codev/src/agent-farm/__tests__/send-hold-warning.test.ts index a682175ac..33f832d9d 100644 --- a/packages/codev/src/agent-farm/__tests__/send-hold-warning.test.ts +++ b/packages/codev/src/agent-farm/__tests__/send-hold-warning.test.ts @@ -31,6 +31,7 @@ vi.mock('../lib/tower-client.js', async (importOriginal) => ({ ...(await importOriginal()), TowerClient: class { isRunning = isRunningMock; + probeHealth = async () => ((await isRunningMock()) ? { state: 'running' } : { state: 'not-running' }); sendMessage = sendMessageMock; }, })); diff --git a/packages/codev/src/agent-farm/__tests__/send.test.ts b/packages/codev/src/agent-farm/__tests__/send.test.ts index a1283499c..8152c51ab 100644 --- a/packages/codev/src/agent-farm/__tests__/send.test.ts +++ b/packages/codev/src/agent-farm/__tests__/send.test.ts @@ -18,6 +18,7 @@ const { mockIsRunning, mockSendMessage, mockLoadState } = vi.hoisted(() => ({ vi.mock('../lib/tower-client.js', () => ({ TowerClient: vi.fn().mockImplementation(function (this: any) { this.isRunning = mockIsRunning; + this.probeHealth = async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }); this.sendMessage = mockSendMessage; }), })); diff --git a/packages/codev/src/agent-farm/__tests__/spec-1057-status-owner.test.ts b/packages/codev/src/agent-farm/__tests__/spec-1057-status-owner.test.ts index 69ed1c766..be3789eb1 100644 --- a/packages/codev/src/agent-farm/__tests__/spec-1057-status-owner.test.ts +++ b/packages/codev/src/agent-farm/__tests__/spec-1057-status-owner.test.ts @@ -33,6 +33,7 @@ vi.mock('../state.js', () => ({ vi.mock('../lib/tower-client.js', () => ({ getTowerClient: () => ({ isRunning: (...a: any[]) => mockIsRunning(...a), + probeHealth: async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }), getHealth: (...a: any[]) => mockGetHealth(...a), getWorkspaceStatus: (...a: any[]) => mockGetWorkspaceStatus(...a), // Spec 1313 round 3: status now reads the overview for held-mail awareness. These suites diff --git a/packages/codev/src/agent-farm/__tests__/spec-1273-interrupt.test.ts b/packages/codev/src/agent-farm/__tests__/spec-1273-interrupt.test.ts index b18424e8f..a1a5230e8 100644 --- a/packages/codev/src/agent-farm/__tests__/spec-1273-interrupt.test.ts +++ b/packages/codev/src/agent-farm/__tests__/spec-1273-interrupt.test.ts @@ -110,6 +110,7 @@ const { mockSendMessage, mockIsRunning, mockDetectWorkspaceRoot, mockDetectCurre vi.mock('../lib/tower-client.js', () => ({ TowerClient: class { isRunning = mockIsRunning; + probeHealth = async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }); sendMessage = mockSendMessage; }, })); diff --git a/packages/codev/src/agent-farm/__tests__/spec-1273-reset-command.test.ts b/packages/codev/src/agent-farm/__tests__/spec-1273-reset-command.test.ts index 215641f2a..f3559bb4b 100644 --- a/packages/codev/src/agent-farm/__tests__/spec-1273-reset-command.test.ts +++ b/packages/codev/src/agent-farm/__tests__/spec-1273-reset-command.test.ts @@ -44,6 +44,7 @@ const { vi.mock('../lib/tower-client.js', () => ({ TowerClient: class { isRunning = mockIsRunning; + probeHealth = async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }); sendMessage = mockSendMessage; getTerminal = mockGetTerminal; getTerminalOutput = mockGetTerminalOutput; diff --git a/packages/codev/src/agent-farm/__tests__/spec-1313-status-held.test.ts b/packages/codev/src/agent-farm/__tests__/spec-1313-status-held.test.ts index e75b149a3..721a8bc61 100644 --- a/packages/codev/src/agent-farm/__tests__/spec-1313-status-held.test.ts +++ b/packages/codev/src/agent-farm/__tests__/spec-1313-status-held.test.ts @@ -33,6 +33,7 @@ vi.mock('../state.js', () => ({ vi.mock('../lib/tower-client.js', () => ({ getTowerClient: () => ({ isRunning: (...a: any[]) => mockIsRunning(...a), + probeHealth: async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }), getHealth: (...a: any[]) => mockGetHealth(...a), getWorkspaceStatus: (...a: any[]) => mockGetWorkspaceStatus(...a), getOverview: (...a: any[]) => mockGetOverview(...a), diff --git a/packages/codev/src/agent-farm/__tests__/spec-1470-self-refresh-command.test.ts b/packages/codev/src/agent-farm/__tests__/spec-1470-self-refresh-command.test.ts index b518a8728..5b85e5a5e 100644 --- a/packages/codev/src/agent-farm/__tests__/spec-1470-self-refresh-command.test.ts +++ b/packages/codev/src/agent-farm/__tests__/spec-1470-self-refresh-command.test.ts @@ -50,6 +50,7 @@ vi.mock('../lib/tower-client.js', async importOriginal => { ...actual, TowerClient: class { isRunning = mockIsRunning; + probeHealth = async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }); sendMessage = mockSendMessage; }, }; diff --git a/packages/codev/src/agent-farm/__tests__/status-fleet-observability.test.ts b/packages/codev/src/agent-farm/__tests__/status-fleet-observability.test.ts index 18d97c350..755c3bd2c 100644 --- a/packages/codev/src/agent-farm/__tests__/status-fleet-observability.test.ts +++ b/packages/codev/src/agent-farm/__tests__/status-fleet-observability.test.ts @@ -25,6 +25,7 @@ vi.mock('../state.js', () => ({ vi.mock('../lib/tower-client.js', () => ({ getTowerClient: () => ({ isRunning: (...a: any[]) => mockIsRunning(...a), + probeHealth: async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }), getHealth: (...a: any[]) => mockGetHealth(...a), getWorkspaceStatus: (...a: any[]) => mockGetWorkspaceStatus(...a), // Spec 1313 round 3: status reads the overview for held-mail awareness; null → "no held info". diff --git a/packages/codev/src/agent-farm/__tests__/status-naming.test.ts b/packages/codev/src/agent-farm/__tests__/status-naming.test.ts index 4ac906200..d6d67e354 100644 --- a/packages/codev/src/agent-farm/__tests__/status-naming.test.ts +++ b/packages/codev/src/agent-farm/__tests__/status-naming.test.ts @@ -30,11 +30,13 @@ vi.mock('../state.js', () => ({ vi.mock('../lib/tower-client.js', () => ({ TowerClient: vi.fn().mockImplementation(function (this: any) { this.isRunning = (...a: any[]) => mockIsRunning(...a); + this.probeHealth = async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }); this.getHealth = (...a: any[]) => mockGetHealth(...a); this.getWorkspaceStatus = (...a: any[]) => mockGetWorkspaceStatus(...a); }), getTowerClient: () => ({ isRunning: (...a: any[]) => mockIsRunning(...a), + probeHealth: async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }), getHealth: (...a: any[]) => mockGetHealth(...a), getWorkspaceStatus: (...a: any[]) => mockGetWorkspaceStatus(...a), // Spec 1313 round 3: status reads the overview for held-mail awareness; null → "no held info". diff --git a/packages/codev/src/agent-farm/__tests__/tower-sweep-husks.test.ts b/packages/codev/src/agent-farm/__tests__/tower-sweep-husks.test.ts index 56184abbc..254c5311e 100644 --- a/packages/codev/src/agent-farm/__tests__/tower-sweep-husks.test.ts +++ b/packages/codev/src/agent-farm/__tests__/tower-sweep-husks.test.ts @@ -12,6 +12,7 @@ const mockSweepHusks = vi.fn(); vi.mock('../lib/tower-client.js', () => ({ getTowerClient: () => ({ isRunning: mockIsRunning, + probeHealth: async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }), findHuskCandidates: mockFindHuskCandidates, sweepHusks: mockSweepHusks, }), diff --git a/packages/codev/src/agent-farm/__tests__/tower-windows-launch.test.ts b/packages/codev/src/agent-farm/__tests__/tower-windows-launch.test.ts index ce87d3147..4191ac164 100644 --- a/packages/codev/src/agent-farm/__tests__/tower-windows-launch.test.ts +++ b/packages/codev/src/agent-farm/__tests__/tower-windows-launch.test.ts @@ -29,7 +29,16 @@ const h = vi.hoisted(() => { }; }); -vi.mock('../lib/tower-client.js', () => ({ DEFAULT_TOWER_PORT: 4100, AGENT_FARM_DIR: h.agentFarmDir })); +vi.mock('../lib/tower-client.js', () => ({ + DEFAULT_TOWER_PORT: 4100, + AGENT_FARM_DIR: h.agentFarmDir, + // towerStart's "is one already up?" probe (#1901): nothing is listening, so it launches. + TowerClient: class { + async probeHealth() { + return { state: 'not-running' }; + } + }, +})); vi.mock('../utils/config.js', () => ({ getConfig: () => ({ serversDir: h.agentFarmDir }) })); vi.mock('../utils/shell.js', () => ({ isPortAvailable: vi.fn(async () => true) })); vi.mock('node:http', () => { diff --git a/packages/codev/src/agent-farm/commands/interrupt.ts b/packages/codev/src/agent-farm/commands/interrupt.ts index 61d115bbc..43f191e51 100644 --- a/packages/codev/src/agent-farm/commands/interrupt.ts +++ b/packages/codev/src/agent-farm/commands/interrupt.ts @@ -22,6 +22,7 @@ import type { InterruptOptions } from '../types.js'; import { logger, fatal } from '../utils/logger.js'; import { TowerClient } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; import { detectWorkspaceRoot, detectCurrentBuilderId, architectSenderId } from './send.js'; import { namesATower, CROSS_TOWER_UNAVAILABLE_MESSAGE } from '../utils/agent-names.js'; @@ -52,8 +53,9 @@ export async function interrupt(options: InterruptOptions): Promise { } const client = new TowerClient(); - if (!(await client.isRunning())) { - fatal('Tower is not running. Start it with: afx tower start'); + const tower = await checkTower(client); + if (tower.state !== 'running') { + fatal(tower.message); } try { diff --git a/packages/codev/src/agent-farm/commands/open.ts b/packages/codev/src/agent-farm/commands/open.ts index 6c6d0500b..b82b111c1 100644 --- a/packages/codev/src/agent-farm/commands/open.ts +++ b/packages/codev/src/agent-farm/commands/open.ts @@ -16,10 +16,14 @@ interface OpenOptions { } /** - * Try to create a file tab via the Tower API - * Returns the file tab ID if successful, null if Tower not available + * Try to create a file tab via the Tower API. On failure, `refused` says whether nothing was + * listening (Tower not running); any other failure has already been reported (#1901). */ -async function tryTowerApi(client: TowerClient, workspacePath: string, filePath: string): Promise { +async function tryTowerApi( + client: TowerClient, + workspacePath: string, + filePath: string, +): Promise<{ ok: true; tabId: string } | { ok: false; refused: boolean }> { const encodedPath = encodeWorkspacePath(workspacePath); const result = await client.request<{ id: string; existing?: boolean }>( @@ -36,16 +40,18 @@ async function tryTowerApi(client: TowerClient, workspacePath: string, filePath: if (result.data.existing) { logger.info('(File was already open)'); } - return result.data.id; + return { ok: true, tabId: result.data.id }; } - if (result.error) { - logger.error(`Tower API error (HTTP ${result.status}): ${result.error}`); - logger.kv('Workspace', workspacePath); - logger.kv('File', filePath); + if (result.connectionRefused) { + return { ok: false, refused: true }; } - return null; + logger.error(`Tower API error (HTTP ${result.status}): ${result.error ?? 'no file tab in the response'}`); + logger.kv('Workspace', workspacePath); + logger.kv('File', filePath); + + return { ok: false, refused: false }; } /** @@ -89,17 +95,18 @@ export async function open(options: OpenOptions): Promise { // Try to use Tower API const client = new TowerClient(); - const tabId = await tryTowerApi(client, workspacePath, filePath); + const opened = await tryTowerApi(client, workspacePath, filePath); - if (tabId) { + if (opened.ok) { // Tab created server-side — dashboard picks it up via state polling. // No need to open a browser; the user already has the dashboard open. return; } - // Tower not available - tell user to start it - logger.error('Tower is not running.'); - logger.info('Start it with: afx tower start'); - logger.info('Then try again: afx open ' + options.file); + if (opened.refused) { + logger.error('Tower is not running.'); + logger.info('Start it with: afx tower start'); + logger.info('Then try again: afx open ' + options.file); + } process.exit(1); } diff --git a/packages/codev/src/agent-farm/commands/rename.ts b/packages/codev/src/agent-farm/commands/rename.ts index 2eb1ac639..bcefbb414 100644 --- a/packages/codev/src/agent-farm/commands/rename.ts +++ b/packages/codev/src/agent-farm/commands/rename.ts @@ -40,8 +40,10 @@ export async function rename(options: RenameOptions): Promise { fatal('Cannot rename builder/architect terminals'); } else if (result.status === 404) { fatal('Session not found — it may have been closed'); - } else if (result.status === 0) { + } else if (result.connectionRefused) { fatal('Tower is not running'); + } else if (result.status === 0) { + fatal(`Tower did not answer (${result.error}); it appears to be up, retry`); } else { fatal(result.error || 'Rename failed'); } diff --git a/packages/codev/src/agent-farm/commands/reset.ts b/packages/codev/src/agent-farm/commands/reset.ts index 5ffd2b766..f43f175bd 100644 --- a/packages/codev/src/agent-farm/commands/reset.ts +++ b/packages/codev/src/agent-farm/commands/reset.ts @@ -20,6 +20,7 @@ import { existsSync, readFileSync, readdirSync, writeFileSync, statSync } from 'node:fs'; import { TowerClient } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; import { logger, fatal } from '../utils/logger.js'; import { MAX_MESSAGE_BYTES, messageLimitError } from '../utils/message-format.js'; import { findBuilderById } from '../lib/builder-lookup.js'; @@ -115,8 +116,9 @@ export async function refresh(options: ResetOptions): Promise { } const client = new TowerClient(); - if (!(await client.isRunning())) { - fatal('Tower is not running. Start it with: afx tower start'); + const tower = await checkTower(client); + if (tower.state !== 'running') { + fatal(tower.message); } const addendum = buildAddendum(options); diff --git a/packages/codev/src/agent-farm/commands/self-refresh.ts b/packages/codev/src/agent-farm/commands/self-refresh.ts index c4db610f8..2f4bea845 100644 --- a/packages/codev/src/agent-farm/commands/self-refresh.ts +++ b/packages/codev/src/agent-farm/commands/self-refresh.ts @@ -41,6 +41,7 @@ import { existsSync, readFileSync, realpathSync, statSync, unlinkSync, writeFile import { isAbsolute, relative, resolve, sep } from 'node:path'; import { execFileSync } from 'node:child_process'; import { TowerClient } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; import { logger, fatal } from '../utils/logger.js'; import { getBuilder } from '../state.js'; import { getConfig } from '../utils/index.js'; @@ -277,11 +278,11 @@ export async function selfRefresh(options: SelfRefreshOptions): Promise { // proceed with Tower down — reporting a clean dry run in that state would be // the rehearsal lying about the thing most likely to stop the real run. const client = new TowerClient(); - if (!(await client.isRunning())) { + const tower = await checkTower(client); + if (tower.state !== 'running') { fatal( - 'Tower is not running, so the post-clear re-entry cannot be scheduled. Refusing to ' + - 'clear — a cleared builder with no re-entry is a builder nobody is coming back for. ' + - 'Start it with: afx tower start', + `${tower.message}\nThe post-clear re-entry cannot be scheduled, so refusing to clear — ` + + 'a cleared builder with no re-entry is a builder nobody is coming back for.', ); return; } diff --git a/packages/codev/src/agent-farm/commands/send.ts b/packages/codev/src/agent-farm/commands/send.ts index 45a24bd10..c2576201a 100644 --- a/packages/codev/src/agent-farm/commands/send.ts +++ b/packages/codev/src/agent-farm/commands/send.ts @@ -22,6 +22,7 @@ import { matchBuilderRow, parseBuilderWorktreePath, type BuilderWorktreeRow } fr import { BUILDER_WORKTREE_ENV } from '../../lib/agent-env.js'; import { hostPaths } from '../../lib/platform/host-paths.js'; import { TowerClient } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; import { ARCHITECT_NAME_PATTERN, MAX_ARCHITECT_NAME_LENGTH } from '../utils/architect-name.js'; import { MAX_MESSAGE_BYTES, messageLimitError } from '../utils/message-format.js'; import { formatVerdict, isUnverifiableVerdict } from '@cluesmith/codev-sdk/hold-verdict'; @@ -353,16 +354,28 @@ function namesAnArchitectInAWorkspace(to: string): boolean { * is the older one; a Tower that answers knows the form, and its not-found stands. * * Only on that failure, so a send that succeeds, or fails any other way, costs nothing more. + * + * Returns what to report in place of the Tower's not-found, or null when it stands. A Tower + * that gives no answer to the question at all is busy, not older, and its not-found cannot be + * judged either way, so that is said instead (#1901). */ -async function failedForAnOlderTower( +async function explainNotFound( client: TowerClient, to: string, result: SendResult, caller: { workspace?: string; from: string }, -): Promise { - if (result.errorCode !== 'NOT_FOUND' || !namesAnArchitectInAWorkspace(to)) return false; +): Promise { + if (result.errorCode !== 'NOT_FOUND' || !namesAnArchitectInAWorkspace(to)) return null; const book = await client.getAddressBook(caller); - return !book.ok && book.unknownRoute === true; + if (book.ok) return null; + if (book.unknownRoute) return olderTowerError('does not know an address of the form :architect:'); + if (book.unanswered) { + return ( + `Tower did not answer the address-book check (${book.error}) needed to tell whether ${to} is ` + + `missing or this Tower predates that address form; it appears to be up, retry` + ); + } + return null; } /** @@ -535,13 +548,18 @@ export async function send(options: SendOptions): Promise { } // Ensure Tower is running. The health probe sends nothing, so under --retry every failure of - // it may be retried. + // it may be retried. One loop owns the retrying (#1901): with --retry it is that budget, and + // the gate probes once per attempt; without it, the gate's own single retry applies. const client = new TowerClient(); const retry = retryBudget(options.retry ?? 0); - while (!(await client.isRunning())) { - if (!(await retry('Tower is not running; nothing has been sent.'))) { - fatal('Tower is not running. Start it with: afx tower start'); + const gate = (options.retry ?? 0) > 0 ? { retries: 0 } : {}; + let tower = await checkTower(client, gate); + while (tower.state !== 'running') { + const why = tower.state === 'not-running' ? 'Tower is not running' : `Tower did not answer /health (${tower.error})`; + if (!(await retry(`${why}; nothing has been sent.`))) { + fatal(tower.message); } + tower = await checkTower(client, gate); } if (options.all) { @@ -584,10 +602,8 @@ export async function send(options: SendOptions): Promise { }, retry); if (!result.ok) { - if (await failedForAnOlderTower(client, target!, result, { workspace, from })) { - throw new Error(olderTowerError('does not know an address of the form :architect:')); - } - throw new Error(result.error || 'Unknown error'); + const explained = await explainNotFound(client, target!, result, { workspace, from }); + throw new Error(explained ?? (result.error || 'Unknown error')); } // Report the real first outcome (Spec 1307 `--delay` + Spec 1313 mailbox). A diff --git a/packages/codev/src/agent-farm/commands/shell.ts b/packages/codev/src/agent-farm/commands/shell.ts index 1f1acf01e..bb913bc4e 100644 --- a/packages/codev/src/agent-farm/commands/shell.ts +++ b/packages/codev/src/agent-farm/commands/shell.ts @@ -38,8 +38,9 @@ async function tryTowerApi( return { ok: true, connectionRefused: false }; } - // status=0 means the request never reached the server (ECONNREFUSED, timeout, etc.) - const connectionRefused = result.status === 0; + // Only a refused connection means nothing is listening. A timeout (status 0 too) comes from a + // Tower that accepted the connection, so it is reported as an error, not "not running" (#1901). + const connectionRefused = result.connectionRefused === true; return { ok: false, connectionRefused, error: result.error }; } diff --git a/packages/codev/src/agent-farm/commands/start.ts b/packages/codev/src/agent-farm/commands/start.ts index 005d28d2c..85232b0d6 100644 --- a/packages/codev/src/agent-farm/commands/start.ts +++ b/packages/codev/src/agent-farm/commands/start.ts @@ -10,6 +10,7 @@ import { getConfig } from '../utils/index.js'; import { logger, fatal } from '../utils/logger.js'; import { openBrowser } from '../utils/shell.js'; import { getTowerClient, DEFAULT_TOWER_PORT } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; import { towerStart } from './tower.js'; /** @@ -30,8 +31,13 @@ export async function start(options: StartOptions = {}): Promise { // Create tower client const client = getTowerClient(); - // Check if tower is running - const towerRunning = await client.isRunning(); + // Check if tower is running. Only a refused connection means "start one": a Tower that + // accepted the connection but did not answer is left alone, never replaced (#1901). + const tower = await checkTower(client); + if (tower.state === 'unresponsive') { + fatal(tower.message); + } + const towerRunning = tower.state === 'running'; if (!towerRunning) { logger.info('Starting tower daemon...'); diff --git a/packages/codev/src/agent-farm/commands/status.ts b/packages/codev/src/agent-farm/commands/status.ts index ccca45314..a2cce2cbf 100644 --- a/packages/codev/src/agent-farm/commands/status.ts +++ b/packages/codev/src/agent-farm/commands/status.ts @@ -8,6 +8,7 @@ import { loadState } from '../state.js'; import { logger } from '../utils/logger.js'; import { getConfig } from '../utils/config.js'; import { getTowerClient } from '../lib/tower-client.js'; +import { checkTower, type TowerCheck } from '../lib/tower-check.js'; import { getTypeColor } from '../utils/display.js'; import { currentArchitectName } from '../utils/architect-name.js'; import { discoverBuilders, type StoredBuilderIdentity } from '../servers/overview.js'; @@ -288,7 +289,7 @@ function renderActivity(visible: Builder[], views: Map) * stdout in `--json` mode — safe for tooling to `JSON.parse`. */ function emitStatusJson(params: { - towerRunning: boolean; + tower: TowerCheck; // `name` is explicitly nullable (not optional): an unregistered workspace // must still emit `"name": null` so the machine-readable contract is stable // for tooling — `JSON.stringify` would otherwise drop an `undefined` key. @@ -304,10 +305,16 @@ function emitStatusJson(params: { visible: Builder[]; views: Map; }): void { - const { towerRunning, workspace, architects, visible, views, ownerFilter, fleet, mailbox } = params; + const { tower, workspace, architects, visible, views, ownerFilter, fleet, mailbox } = params; const payload = { - tower: { running: towerRunning }, + // `running: false` covers both a Tower that is down and one that took the connection but did + // not answer; `state` tells them apart and `error` says why it did not answer (#1901). + tower: { + running: tower.state === 'running', + state: tower.state, + error: tower.state === 'unresponsive' ? tower.error : null, + }, workspace, fleet, mailbox, @@ -356,7 +363,8 @@ export async function status(options: StatusOptions = {}): Promise { // Try tower API first (Phase 3 - Spec 0090) const client = getTowerClient(); - const towerRunning = await client.isRunning(); + const tower = await checkTower(client); + const towerRunning = tower.state === 'running'; // Builder ownership (`spawnedByArchitect`) lives in state.db, so load it up // front — it's the canonical owner source whether or not Tower is running. @@ -405,7 +413,7 @@ export async function status(options: StatusOptions = {}): Promise { } } emitStatusJson({ - towerRunning, + tower, workspace: { path: workspacePath, name: workspaceName ?? null, active: workspaceActive }, architects, visible, @@ -516,9 +524,14 @@ export async function status(options: StatusOptions = {}): Promise { return; } - // Tower not running - show message and fall back to local state - logger.kv('Tower', chalk.gray('not running')); - logger.info(`Run 'afx tower start' to start the tower daemon`); + // Tower not reachable - show why and fall back to local state + if (tower.state === 'unresponsive') { + logger.kv('Tower', chalk.yellow('not answering')); + logger.warn(tower.message); + } else { + logger.kv('Tower', chalk.gray('not running')); + logger.info(`Run 'afx tower start' to start the tower daemon`); + } showArtifactConfig(workspacePath); diff --git a/packages/codev/src/agent-farm/commands/stop.ts b/packages/codev/src/agent-farm/commands/stop.ts index 4bba83bfa..0aa5d1eea 100644 --- a/packages/codev/src/agent-farm/commands/stop.ts +++ b/packages/codev/src/agent-farm/commands/stop.ts @@ -6,9 +6,10 @@ */ import { loadState, clearRuntime, getArchitects } from '../state.js'; -import { logger } from '../utils/logger.js'; +import { logger, fatal } from '../utils/logger.js'; import { getConfig } from '../utils/config.js'; import { getTowerClient } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; /** * Stop all agent farm processes @@ -24,7 +25,13 @@ export async function stop(): Promise { // Try tower API first (Phase 3 - Spec 0090) const client = getTowerClient(); - const towerRunning = await client.isRunning(); + // An unresponsive Tower is not a stopped one: the legacy path below would clear the + // runtime state of builders that are still running (#1901). + const tower = await checkTower(client); + if (tower.state === 'unresponsive') { + fatal(tower.message); + } + const towerRunning = tower.state === 'running'; if (towerRunning) { logger.info('Deactivating workspace via tower...'); @@ -47,6 +54,12 @@ export async function stop(): Promise { return; } + // Tower took the request and never answered: it may or may not have deactivated, so nothing + // local is cleared on a guess (#1901). + if (result.status === 0 && !result.connectionRefused) { + fatal(`Tower did not answer the deactivation request (${result.error}); nothing was cleared. Retry afx workspace stop.`); + } + // If tower returned error (e.g., workspace not found), fall through to legacy cleanup logger.debug(`Tower deactivation failed: ${result.error}, trying legacy cleanup`); } diff --git a/packages/codev/src/agent-farm/commands/tower-sweep-husks.ts b/packages/codev/src/agent-farm/commands/tower-sweep-husks.ts index ea9a34deb..60723a38e 100644 --- a/packages/codev/src/agent-farm/commands/tower-sweep-husks.ts +++ b/packages/codev/src/agent-farm/commands/tower-sweep-husks.ts @@ -5,6 +5,7 @@ import { logger } from '../utils/logger.js'; import { getTowerClient } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; import { confirm } from '../../lib/cli-prompts.js'; import type { HuskCandidate } from '../lib/tower-client.js'; @@ -39,9 +40,9 @@ function printCandidates(candidates: HuskCandidate[]): void { export async function towerSweepHusks(options: TowerSweepHusksOptions = {}): Promise { const client = getTowerClient(); - const towerRunning = await client.isRunning(); - if (!towerRunning) { - logger.error('Tower is not running. Start it with `afx tower start`.'); + const tower = await checkTower(client); + if (tower.state !== 'running') { + logger.error(tower.message); process.exitCode = 1; return; } diff --git a/packages/codev/src/agent-farm/commands/tower.ts b/packages/codev/src/agent-farm/commands/tower.ts index 5188ae430..d75c6fbb5 100644 --- a/packages/codev/src/agent-farm/commands/tower.ts +++ b/packages/codev/src/agent-farm/commands/tower.ts @@ -8,10 +8,11 @@ import http from 'node:http'; import { logger, fatal } from '../utils/logger.js'; import { spawn, type SpawnOptions } from 'node:child_process'; import { getConfig } from '../utils/config.js'; -import { DEFAULT_TOWER_PORT, AGENT_FARM_DIR } from '../lib/tower-client.js'; +import { DEFAULT_TOWER_PORT, AGENT_FARM_DIR, TowerClient } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; +import { listProcessCensus } from '../servers/process-census.js'; import { ensureLocalKey } from '@cluesmith/codev-core/auth'; import { TOWER_KEY_HEADER } from '@cluesmith/codev-types'; -import { isPortAvailable } from '../utils/shell.js'; import Database from 'better-sqlite3'; import { openDatabase } from '../../lib/sqlite.js'; import { getGlobalDbPath } from '../db/index.js'; @@ -108,10 +109,28 @@ function logToFile(message: string): void { } /** - * Check if a port is already in use (inverse of isPortAvailable from shell utils) + * Why `afx tower start` refuses a port whose holder accepted the connection but did not + * answer (#1901): name the process, so the reader can see whether it is a Tower, and leave + * replacing it to them. */ -async function isPortInUse(port: number): Promise { - return !(await isPortAvailable(port)); +async function unresponsivePortMessage(port: number, tower: { error: string; elapsedMs: number }): Promise { + const pids = getProcessesOnPort(port); + let describe = (pid: number): string => `PID ${pid}`; + if (pids.length > 0) { + try { + const census = await listProcessCensus(); + describe = (pid) => `PID ${pid}: ${census.find((p) => p.pid === pid)?.cmdline || '(command line not readable)'}`; + } catch (err) { + describe = (pid) => `PID ${pid} (process table unreadable: ${err instanceof Error ? err.message : String(err)})`; + } + } + return [ + `A process is listening on port ${port} but did not answer /health within ` + + `${Math.round(tower.elapsedMs / 1000)} s (${tower.error}):`, + ...(pids.length > 0 ? pids.map((pid) => ` ${describe(pid)}`) : [' (no listening PID found)']), + 'If the machine is busy, wait and run afx tower start again.', + 'To replace it deliberately: afx tower stop, then afx tower start.', + ].join('\n'); } /** @@ -245,28 +264,17 @@ export async function towerStart(options: TowerStartOptions = {}): Promise return; } - // Check if already running and responding - if (await isServerResponding(port)) { - const dashboardUrl = `http://localhost:${port}`; - logger.info(`Tower already running at ${dashboardUrl}`); + // Only a refused connection means "start one" (#1901). A process that accepted the connection + // but did not answer is, under load, usually a live Tower: stopping it is a human's decision + // (afx tower stop), never a side effect of start. + const tower = await checkTower(new TowerClient({ port, host: '127.0.0.1' })); + if (tower.state === 'running') { + logger.info(`Tower already running at http://localhost:${port}`); return; } - - // Check if port is in use but not responding (zombie process?) - if (await isPortInUse(port)) { - logger.warn(`Port ${port} is in use but tower not responding. Attempting cleanup...`); - logToFile(`Port ${port} in use but not responding, attempting cleanup`); - const pids = getProcessesOnPort(port); - for (const pid of pids) { - try { - process.kill(pid, 'SIGTERM'); - logToFile(`Killed process ${pid} on port ${port}`); - } catch { - // Process may have already exited - } - } - // Wait for port to be released - await new Promise((r) => setTimeout(r, 1000)); + if (tower.state === 'unresponsive') { + logToFile(`Port ${port} held but /health unanswered (${tower.error}); refusing to start`); + fatal(await unresponsivePortMessage(port, tower)); } const config = getConfig(); diff --git a/packages/codev/src/agent-farm/commands/workspace-add-architect.ts b/packages/codev/src/agent-farm/commands/workspace-add-architect.ts index 2780f31e4..7febb9a61 100644 --- a/packages/codev/src/agent-farm/commands/workspace-add-architect.ts +++ b/packages/codev/src/agent-farm/commands/workspace-add-architect.ts @@ -15,6 +15,7 @@ import { getConfig } from '../utils/index.js'; import { logger } from '../utils/logger.js'; import { getTowerClient } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; import { validateArchitectName } from '../utils/architect-name.js'; export interface WorkspaceAddArchitectOptions { @@ -49,9 +50,9 @@ export async function workspaceAddArchitect( } const client = getTowerClient(); - const towerRunning = await client.isRunning(); - if (!towerRunning) { - logger.error('Tower is not running. Start it with `afx workspace start` first.'); + const tower = await checkTower(client, { startCommand: 'afx workspace start' }); + if (tower.state !== 'running') { + logger.error(tower.message); process.exit(1); } diff --git a/packages/codev/src/agent-farm/commands/workspace-remove-architect.ts b/packages/codev/src/agent-farm/commands/workspace-remove-architect.ts index 60018ec55..bf939c541 100644 --- a/packages/codev/src/agent-farm/commands/workspace-remove-architect.ts +++ b/packages/codev/src/agent-farm/commands/workspace-remove-architect.ts @@ -13,6 +13,7 @@ import { getConfig } from '../utils/index.js'; import { logger } from '../utils/logger.js'; import { getTowerClient } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; export interface WorkspaceRemoveArchitectOptions { name: string; @@ -35,9 +36,9 @@ export async function workspaceRemoveArchitect( } const client = getTowerClient(); - const towerRunning = await client.isRunning(); - if (!towerRunning) { - logger.error('Tower is not running. Start it with `afx workspace start` first.'); + const tower = await checkTower(client, { startCommand: 'afx workspace start' }); + if (tower.state !== 'running') { + logger.error(tower.message); process.exit(1); } diff --git a/packages/codev/src/agent-farm/lib/tower-check.ts b/packages/codev/src/agent-farm/lib/tower-check.ts new file mode 100644 index 000000000..192ce8be4 --- /dev/null +++ b/packages/codev/src/agent-farm/lib/tower-check.ts @@ -0,0 +1,61 @@ +/** + * The one Tower liveness gate every CLI command goes through (#1901). + * + * A bare `isRunning()` boolean turned every `/health` failure into "Tower is not running. + * Start it with: afx tower start". Under heavy load a live Tower accepts the connection at + * once but its starved event loop misses the 10 s request timeout, so commands told people to + * start a second Tower while the first was up. Here only a refused connection reads as "not + * running". Anything else is retried once after a short pause, then reported with the + * underlying error and no advice to start Tower. + */ + +import type { TowerHealthProbe } from './tower-client.js'; + +export const TOWER_RETRY_DELAY_MS = 1000; + +export type TowerCheck = + | { state: 'running' } + | { state: 'not-running'; message: string } + | { state: 'unresponsive'; message: string; error: string; elapsedMs: number }; + +export interface TowerCheckOptions { + /** The command a "not running" message tells the reader to run. */ + startCommand?: string; + /** + * Extra probes after an unresponsive one (default 1). A caller with its own retry loop passes + * 0, so the two do not stack. + */ + retries?: number; + retryDelayMs?: number; +} + +export async function checkTower( + client: { probeHealth(): Promise }, + options: TowerCheckOptions = {}, +): Promise { + const startedAt = Date.now(); + let probe = await client.probeHealth(); + for (let left = options.retries ?? 1; probe.state === 'unresponsive' && left > 0; left--) { + await new Promise((resolve) => setTimeout(resolve, options.retryDelayMs ?? TOWER_RETRY_DELAY_MS)); + probe = await client.probeHealth(); + } + + switch (probe.state) { + case 'running': + return { state: 'running' }; + case 'not-running': + return { + state: 'not-running', + message: `Tower is not running. Start it with: ${options.startCommand ?? 'afx tower start'}`, + }; + case 'unresponsive': { + const elapsedMs = Date.now() - startedAt; + return { + state: 'unresponsive', + error: probe.error, + elapsedMs, + message: `Tower did not answer /health (${probe.error}) after ${elapsedMs} ms; it appears to be up, retry`, + }; + } + } +} diff --git a/packages/codev/src/agent-farm/lib/tower-client.ts b/packages/codev/src/agent-farm/lib/tower-client.ts index 1a263f114..b1a0abe30 100644 --- a/packages/codev/src/agent-farm/lib/tower-client.ts +++ b/packages/codev/src/agent-farm/lib/tower-client.ts @@ -54,6 +54,7 @@ export { type TowerWorkspace, type TowerWorkspaceStatus, type TowerHealth, + type TowerHealthProbe, type TowerTunnelStatus, type TowerStatus, type TowerTerminal, diff --git a/packages/sdk/src/__tests__/tower-client.test.ts b/packages/sdk/src/__tests__/tower-client.test.ts index c469f4636..371052038 100644 --- a/packages/sdk/src/__tests__/tower-client.test.ts +++ b/packages/sdk/src/__tests__/tower-client.test.ts @@ -132,6 +132,54 @@ describe('TowerClient REST', () => { }); }); +describe('TowerClient.probeHealth (#1901)', () => { + const throwing = (err: unknown) => vi.fn(async () => { throw err; }) as unknown as typeof fetch; + const errno = (code: string) => Object.assign(new Error(`connect ${code}`), { code }); + /** Node's fetch over `localhost`: one attempt per address, the aggregate's code copied from the first. */ + const nodeFetchFailure = (...codes: string[]) => + Object.assign(new TypeError('fetch failed'), { + cause: Object.assign(new AggregateError(codes.map(errno), ''), { code: codes[0] }), + }); + + it('reports running with the health payload on a healthy answer', async () => { + const { impl } = jsonFetch(200, { status: 'healthy', uptime: 5 }); + expect(await new TowerClient(opts(impl)).probeHealth()).toMatchObject({ state: 'running', health: { uptime: 5 } }); + }); + + it('reports not-running only when every address refused the connection', async () => { + const client = new TowerClient(opts(throwing(nodeFetchFailure('ECONNREFUSED', 'ECONNREFUSED')))); + expect(await client.probeHealth()).toEqual({ state: 'not-running' }); + }); + + it('still reports not-running when ::1 is unreachable and 127.0.0.1 refused (broken IPv6)', async () => { + const client = new TowerClient(opts(throwing(nodeFetchFailure('ENETUNREACH', 'ECONNREFUSED')))); + expect(await client.probeHealth()).toEqual({ state: 'not-running' }); + }); + + it('does not let a refused ::1 mask a 127.0.0.1 that failed another way', async () => { + const client = new TowerClient(opts(throwing(nodeFetchFailure('ECONNREFUSED', 'ECONNRESET')))); + expect((await client.probeHealth()).state).toBe('unresponsive'); + }); + + it('reports a timeout as unresponsive, not as not-running', async () => { + const timeout = Object.assign(new Error('The operation was aborted due to timeout'), { name: 'TimeoutError' }); + const client = new TowerClient(opts(throwing(timeout))); + expect(await client.probeHealth()).toEqual({ state: 'unresponsive', error: 'Request timeout' }); + expect(await client.isRunning()).toBe(false); + }); + + it('keeps the reset reason Node puts on the cause', async () => { + const reset = Object.assign(new TypeError('fetch failed'), { cause: errno('ECONNRESET') }); + const client = new TowerClient(opts(throwing(reset))); + expect(await client.probeHealth()).toEqual({ state: 'unresponsive', error: 'fetch failed: ECONNRESET' }); + }); + + it('reports an error status as unresponsive with the status and body', async () => { + const { impl } = jsonFetch(503, { error: 'BUSY' }); + expect(await new TowerClient(opts(impl)).probeHealth()).toEqual({ state: 'unresponsive', error: 'HTTP 503: BUSY' }); + }); +}); + describe('parseSseText', () => { it('decodes one complete data: envelope and returns no tail', () => { const seen: SseEnvelope[] = []; diff --git a/packages/sdk/src/tower-client.ts b/packages/sdk/src/tower-client.ts index 60995ee37..ac052e375 100644 --- a/packages/sdk/src/tower-client.ts +++ b/packages/sdk/src/tower-client.ts @@ -184,6 +184,16 @@ export interface TowerHealth { timestamp: string; } +/** + * One `/health` probe, classified (#1901). `not-running`: the connection was refused, so + * nothing is listening. `unresponsive`: something accepted the connection but did not answer + * healthily; `error` carries the reason. + */ +export type TowerHealthProbe = + | { state: 'running'; health: TowerHealth } + | { state: 'not-running' } + | { state: 'unresponsive'; error: string }; + /** Issue #1227: a shellper the husk sweep would reap (or has reaped). */ export interface HuskCandidate { pid: number; @@ -317,6 +327,11 @@ export interface TowerClientOptions { * to the global fetch, which exists in browsers, Node 18+, and React Native. */ fetchFn?: typeof fetch; + /** + * How long one request may wait for Tower's answer, in ms. Defaults to 10 000. A test against + * a deliberately stalled server sets it short (#1901). + */ + requestTimeoutMs?: number; } // ── Client ───────────────────────────────────────────────────── @@ -327,10 +342,23 @@ import { encodeWorkspacePath } from './workspace.js'; * Whether a fetch failure was a refused TCP connection: nothing was listening, so the * request provably never reached Tower. Node's fetch reports it as `fetch failed` with the * `ECONNREFUSED` on `err.cause`, which a check of `err.message` alone never sees (#1950). + * + * `localhost` resolves to both `::1` and `127.0.0.1`, and when every address fails Node's cause + * is an AggregateError whose `code` is copied from the FIRST attempt only. So each attempt is + * judged (#1901): the connection counts as refused when at least one attempt was refused and + * every other one also failed before reaching a server (an unreachable `::1` on a machine with + * broken IPv6, say). A refused `::1` must not mask a `127.0.0.1` that was reached and then + * failed, such as a reset. */ +const NEVER_REACHED_CODES = new Set(['ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH', 'EADDRNOTAVAIL']); + function isConnectionRefused(err: unknown): boolean { if (!(err instanceof Error)) return String(err).includes('ECONNREFUSED'); - const cause = (err as { cause?: { code?: unknown; message?: unknown } }).cause; + const cause = (err as { cause?: { code?: unknown; message?: unknown; errors?: unknown } }).cause; + if (Array.isArray(cause?.errors) && cause.errors.length > 0) { + const codes = cause.errors.map((attempt) => (attempt as { code?: unknown } | null)?.code); + return codes.includes('ECONNREFUSED') && codes.every((code) => typeof code === 'string' && NEVER_REACHED_CODES.has(code)); + } return ( err.message.includes('ECONNREFUSED') || cause?.code === 'ECONNREFUSED' || @@ -390,6 +418,7 @@ export class TowerClient { private readonly baseUrl: string; private readonly getAuthKey: () => string | null; private readonly fetchFn: typeof fetch; + private readonly requestTimeoutMs: number; constructor(portOrOptions?: number | TowerClientOptions) { let options: TowerClientOptions; @@ -403,6 +432,7 @@ export class TowerClient { this.baseUrl = `http://${host}:${port}`; this.getAuthKey = options.getAuthKey ?? (() => null); this.fetchFn = options.fetchFn ?? globalThis.fetch.bind(globalThis); + this.requestTimeoutMs = options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS; } /** @@ -427,7 +457,7 @@ export class TowerClient { const response = await this.fetchFn(`${this.baseUrl}${path}`, { ...options, headers, - signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + signal: AbortSignal.timeout(this.requestTimeoutMs), }); if (!response.ok) { @@ -453,13 +483,30 @@ export class TowerClient { if (message.includes('timeout')) { return { ok: false, status: 0, error: 'Request timeout' }; } - return { ok: false, status: 0, error: message }; + // Node's fetch says only `fetch failed`; the reason (ECONNRESET, …) is on the cause (#1901). + const causeCode = (err as { cause?: { code?: unknown } } | null)?.cause?.code; + return { ok: false, status: 0, error: typeof causeCode === 'string' ? `${message}: ${causeCode}` : message }; } } - async isRunning(): Promise { + /** + * Probe `/health` once and say why it failed, not just that it did (#1901). Only a refused + * connection means nothing is listening; a timeout, a reset, an error status or an unreadable + * body all come from something that accepted the connection, which under load is usually a + * live Tower whose event loop is starved. Retrying, and wording the result for a person, is + * the caller's policy. + */ + async probeHealth(): Promise { const result = await this.request('/health'); - return result.ok && result.data?.status === 'healthy'; + if (result.ok && result.data?.status === 'healthy') return { state: 'running', health: result.data }; + if (result.connectionRefused) return { state: 'not-running' }; + if (result.status === 0) return { state: 'unresponsive', error: result.error ?? 'no response' }; + if (!result.ok) return { state: 'unresponsive', error: `HTTP ${result.status}: ${result.error}` }; + return { state: 'unresponsive', error: `reported status ${JSON.stringify(result.data?.status)}` }; + } + + async isRunning(): Promise { + return (await this.probeHealth()).state === 'running'; } async getHealth(): Promise { @@ -595,7 +642,7 @@ export class TowerClient { async deactivateWorkspace( workspacePath: string - ): Promise<{ ok: boolean; stopped?: number[]; error?: string }> { + ): Promise<{ ok: boolean; stopped?: number[]; error?: string; status?: number; connectionRefused?: boolean }> { const encoded = encodeWorkspacePath(workspacePath); const result = await this.request<{ success: boolean; stopped?: number[]; error?: string }>( `/api/workspaces/${encoded}/deactivate`, @@ -603,7 +650,9 @@ export class TowerClient { ); if (!result.ok) { - return { ok: false, error: result.error }; + // `status` 0 without `connectionRefused` means Tower took the request and never answered, + // so the caller cannot know whether it deactivated (#1901). + return { ok: false, error: result.error, status: result.status, connectionRefused: result.connectionRefused }; } return { @@ -652,7 +701,7 @@ export class TowerClient { */ async getAddressBook( caller: { workspace?: string; from?: string } = {}, - ): Promise<{ ok: true; result: AddressBookResponse } | { ok: false; error: string; unknownRoute?: true }> { + ): Promise<{ ok: true; result: AddressBookResponse } | { ok: false; error: string; unknownRoute?: true; unanswered?: true }> { const query = new URLSearchParams(); if (caller.workspace !== undefined) query.set('workspace', caller.workspace); if (caller.from !== undefined) query.set('from', caller.from); @@ -660,7 +709,9 @@ export class TowerClient { const result = await this.request(`/api/address-book${text === '' ? '' : `?${text}`}`); if (!result.ok || result.data === undefined) { const failure = { ok: false as const, error: result.error ?? `Tower answered ${result.status}` }; - return isUnknownRoute(result) ? { ...failure, unknownRoute: true } : failure; + if (isUnknownRoute(result)) return { ...failure, unknownRoute: true }; + // No HTTP answer at all (timeout, reset, refused): says nothing about which Tower it is (#1901). + return result.status === 0 ? { ...failure, unanswered: true } : failure; } return { ok: true, result: result.data }; } @@ -861,7 +912,7 @@ export class TowerClient { async renameTerminal( sessionId: string, name: string, - ): Promise<{ ok: boolean; status: number; data?: { id: string; name: string }; error?: string }> { + ): Promise<{ ok: boolean; status: number; data?: { id: string; name: string }; error?: string; connectionRefused?: boolean }> { return this.request<{ id: string; name: string }>(`/api/terminals/${sessionId}/rename`, { method: 'PATCH', body: JSON.stringify({ name }), @@ -899,7 +950,7 @@ export class TowerClient { method: 'POST', headers, body, - signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + signal: AbortSignal.timeout(this.requestTimeoutMs), }); if (!response.ok) { const text = await response.text(); @@ -1181,7 +1232,7 @@ export class TowerClient { const response = await this.fetchFn(`${this.baseUrl}${path}`, { ...options, headers, - signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + signal: AbortSignal.timeout(this.requestTimeoutMs), }); const text = await response.text(); let body: unknown = null; @@ -1217,7 +1268,7 @@ export class TowerClient { } const response = await this.fetchFn(`${this.baseUrl}${path}`, { headers, - signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + signal: AbortSignal.timeout(this.requestTimeoutMs), }); if (response.ok) { const bytes = new Uint8Array(await response.arrayBuffer());