Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Batch J: #2062 #2047 (#2063)

0xken15eb4591d9408e
diff --git a/cli/src/gateway/accountHttp.spec.ts b/cli/src/gateway/accountHttp.spec.ts
index 215e9426a..9e8c387c1 100644
--- a/cli/src/gateway/accountHttp.spec.ts
+++ b/cli/src/gateway/accountHttp.spec.ts
@@ -82,6 +82,38 @@ describe('account HTTP in the gateway', () => {
}
})
+ // Diego 10-29: a body that timed out after the headers, or HTML from a proxy, read as '200 OK, {}'.
+ it('answers a body that times out after the headers as a timeout, not as an empty success', async () => {
+ const { api, request } = setup()
+ for (const name of ['TimeoutError', 'AbortError']) {
+ const stalled = new ReadableStream({ start(controller) { controller.error(new DOMException('late', name)) } })
+ request.mockResolvedValueOnce(new Response(stalled, { status: 200 }))
+ expect(await api.backend('GET', '/api/auth/me')).toEqual({ status: 504, body: { success: false, error: { code: 'BACKEND_TIMEOUT',
+ message: 'The Harness backend did not answer GET /api/auth/me within 20s. Try again in a moment.' } } })
+ }
+ })
+ // A refusal must keep its status whatever its body does: 401/403 sign out, 426 asks for an update, 429/5xx carry Retry-After.
+ it('keeps a refusal\'s status with {} when its body stalls or is not JSON', async () => {
+ const { api, request } = setup()
+ const stalled = (status: number, headers: Record<string, string> = {}) => new Response(
+ new ReadableStream({ start(controller) { controller.error(new DOMException('late', 'TimeoutError')) } }), { status, headers })
+ request.mockResolvedValueOnce(stalled(401))
+ expect(await api.backend('GET', '/api/auth/me')).toEqual({ status: 401, body: {} })
+ request.mockResolvedValueOnce(stalled(503, { 'retry-after': '30' }))
+ expect(await api.backend('POST', '/api/product-usage/report', {})).toEqual({ status: 503, body: {}, retryAfterMs: 30_000 })
+ request.mockResolvedValueOnce(new Response('<html>Upgrade Required</html>', { status: 426 }))
+ expect(await api.backend('GET', '/api/super-tabs/hosts/machine-1/changes?full=1')).toEqual({ status: 426, body: {} })
+ })
+ it('answers a success whose body is not JSON as a bad response, and an empty one as {}', async () => {
+ const { api, request } = setup()
+ request.mockResolvedValueOnce(new Response('<html>Bad gateway</html>', { status: 200 }))
+ expect(await api.backend('GET', '/api/auth/me')).toMatchObject({ status: 502, body: { success: false, error: { code: 'BACKEND_BAD_RESPONSE' } } })
+ request.mockResolvedValueOnce(new Response(null, { status: 204 }))
+ expect(await api.backend('POST', '/api/product-usage/report', {})).toEqual({ status: 204, body: {} })
+ request.mockResolvedValueOnce(new Response('', { status: 200, headers: { 'content-length': '0' } }))
+ expect(await api.backend('POST', '/api/product-usage/report', {})).toEqual({ status: 200, body: {} })
+ })
+
it('keeps the guest list local and never asks for a token', async () => {
const { api, account, request, changed } = setup()
account({ machineId: null, signIn: null })
diff --git a/cli/src/gateway/accountHttp.ts b/cli/src/gateway/accountHttp.ts
index f797b25eb..a7078d777 100644
--- a/cli/src/gateway/accountHttp.ts
+++ b/cli/src/gateway/accountHttp.ts
@@ -23,6 +23,7 @@ interface AccountHttpDeps {
const failure = (status: number, code: string, message: string): HttpAnswer =>
({ status, body: { success: false, error: { code, message } } })
+const timedOut = (error: Error) => error?.name === 'TimeoutError' || error?.name === 'AbortError'
/** A Retry-After header as milliseconds from [now]: delta-seconds or an HTTP date; null when absent or unreadable. */
export function retryAfterMs(header: string | null, now = Date.now()): number | null {
@@ -64,13 +65,26 @@ export function createAccountHttp(deps: AccountHttpDeps) {
})
} catch (error) {
const e = error as Error & { cause?: { message?: string } }
- if (e.name === 'TimeoutError' || e.name === 'AbortError') {
- return failure(504, 'BACKEND_TIMEOUT', `The Harness backend did not answer ${method} ${path} within ${timeoutMs / 1000}s. Try again in a moment.`)
- }
+ if (timedOut(e)) return timeout()
return failure(502, 'BACKEND_UNREACHABLE', `Could not reach the Harness backend (${e.cause?.message ?? e.message}). Check the connection and try again.`)
}
+ // The timeout also covers the body: a success that stalls after the headers, or a proxy's HTML page, is not an empty
+ // success (Diego 10-29). A refusal keeps its status whatever its body does: 401/403 sign out, 426 asks for an update.
+ let answer: Record<string, unknown> = {}
+ if (res.body !== null && res.headers?.get?.('content-length') !== '0') {
+ try { answer = await res.json() as Record<string, unknown> } catch (error) {
+ if (res.status >= 200 && res.status < 300) {
+ return timedOut(error as Error) ? timeout()
+ : failure(502, 'BACKEND_BAD_RESPONSE', `The Harness backend answered ${method} ${path} with an unreadable reply. Try again in a moment.`)
+ }
+ }
+ }
const retry = res.status === 429 || res.status >= 500 ? retryAfterMs(res.headers?.get?.('retry-after') ?? null) : null
- return { status: res.status, body: await res.json().catch(() => ({})) as Record<string, unknown>, ...(retry !== null ? { retryAfterMs: retry } : {}) }
+ return { status: res.status, body: answer, ...(retry !== null ? { retryAfterMs: retry } : {}) }
+
+ function timeout(): HttpAnswer {
+ return failure(504, 'BACKEND_TIMEOUT', `The Harness backend did not answer ${method} ${path} within ${timeoutMs / 1000}s. Try again in a moment.`)
+ }
}
const cache = new MachineListCache(() => backend('GET', '/api/machines'), () => deps.computer.id,
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index 6d25b2566..050abec36 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -14,6 +14,7 @@ import { SwarmReads } from './swarmReads.js'
import { retainedHarnesses, retentionFile } from './retention.js'
import { observerSource } from './observers.js'
import { ContributedMachines } from './machines.js'
+import { createAccountHttp } from '../gateway/accountHttp.js'
const roots: string[] = []
const hosts: SuperTabHost[] = []
@@ -159,6 +160,23 @@ describe('the host tick on the host form', () => {
expect(vi.mocked(t.call).mock.calls.filter(([, path]) => path.includes('/hosts/'))).toHaveLength(2)
expect(t.log).toHaveBeenCalledTimes(1)
})
+ // Diego 10-29: a host form whose body timed out after the headers read as '200 OK, {}', so the host paused this machine's
+ // Swarm work for a minute behind 'Update Harness'. Through the gateway's real backend helper, it is a timeout that is logged and retried.
+ it('logs a feed read that times out after the headers as unreachable and reads again the next second', async () => {
+ const t = setup(), host = t.open()
+ const stalled = () => new Response(new ReadableStream({ start(controller) { controller.error(new DOMException('late', 'TimeoutError')) } }), { status: 200 })
+ const gateway = createAccountHttp({ tokens: { accessToken: async () => 'token' }, account: () => ({ machineId: 'account', signIn: null }),
+ computer: { id: 'computer', name: 'Mac', hostname: 'mac' }, environment: 'test', base: () => 'https://backend.invalid',
+ request: vi.fn<typeof fetch>(async () => stalled()), log: vi.fn() })
+ vi.mocked(t.call).mockImplementation((method, path, body) => gateway.backend(method, path, body))
+ await host.tick()
+ t.wait(1_000)
+ await host.tick()
+ expect(t.log.mock.calls.map(([line]) => line)).toEqual([
+ 'The Harness backend did not answer GET /api/super-tabs/hosts/machine-1/changes?full=1 within 20s. Try again in a moment.',
+ 'The Harness backend did not answer GET /api/super-tabs/hosts/machine-1/changes?full=1 within 20s. Try again in a moment.'])
+ expect(vi.mocked(t.call).mock.calls.filter(([, path]) => path.includes('/hosts/'))).toHaveLength(2)
+ })
})
describe('Super Tab native delivery handoff', () => {
diff --git a/desktop/macos/Runner/AppDelegate.swift b/desktop/macos/Runner/AppDelegate.swift
index de4a533b1..5aeac1da5 100644
--- a/desktop/macos/Runner/AppDelegate.swift
+++ b/desktop/macos/Runner/AppDelegate.swift
@@ -37,6 +37,21 @@ class AppDelegate: FlutterAppDelegate {
UserDefaults.standard.register(defaults: ["NSInitialToolTipDelay": 500])
}
+ // Hidden or covered, Harness would be App Napped: its timers stall for minutes, the daemon drops
+ // its idle local socket and the Swarm tabs empty. This keeps it awake but still lets the Mac sleep.
+ // FlutterAppDelegate implements neither callback, so there is no super to call.
+ private(set) var appNapActivity: NSObjectProtocol?
+
+ override func applicationDidFinishLaunching(_ notification: Notification) {
+ appNapActivity = ProcessInfo.processInfo.beginActivity(
+ options: .userInitiatedAllowingIdleSystemSleep, reason: "Keep agents and Swarm updates live while hidden")
+ }
+
+ override func applicationWillTerminate(_ notification: Notification) {
+ if let activity = appNapActivity { ProcessInfo.processInfo.endActivity(activity) }
+ appNapActivity = nil
+ }
+
override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}
diff --git a/desktop/macos/RunnerTests/RunnerTests.swift b/desktop/macos/RunnerTests/RunnerTests.swift
index 0e83e9987..4f14d6062 100644
--- a/desktop/macos/RunnerTests/RunnerTests.swift
+++ b/desktop/macos/RunnerTests/RunnerTests.swift
@@ -12,6 +12,37 @@ class RunnerTests: XCTestCase {
}
+/// App Nap: hidden, Harness keeps its timers and sockets running, and the Mac still sleeps when idle.
+final class AppNapTests: XCTestCase {
+ /// The power assertions this process holds that keep an idle Mac awake.
+ private func sleepPreventingAssertions() throws -> [String] {
+ let pmset = Process()
+ let pipe = Pipe()
+ pmset.executableURL = URL(fileURLWithPath: "/usr/bin/pmset")
+ pmset.arguments = ["-g", "assertions"]
+ pmset.standardOutput = pipe
+ try pmset.run()
+ let output = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
+ pmset.waitUntilExit()
+ let pid = ProcessInfo.processInfo.processIdentifier
+ return output.split(separator: "\n").map(String.init)
+ .filter { $0.contains("pid \(pid)(") && $0.contains("PreventUserIdleSystemSleep") }
+ }
+
+ func testTheRunningAppHoldsTheActivity() {
+ XCTAssertNotNil((NSApp.delegate as? AppDelegate)?.appNapActivity)
+ }
+
+ func testLaunchHoldsTheActivityAndQuitEndsIt() throws {
+ let app = AppDelegate()
+ app.applicationDidFinishLaunching(Notification(name: NSApplication.didFinishLaunchingNotification))
+ XCTAssertNotNil(app.appNapActivity)
+ XCTAssertEqual(try sleepPreventingAssertions(), [], "the activity must still let an idle Mac sleep")
+ app.applicationWillTerminate(Notification(name: NSApplication.willTerminateNotification))
+ XCTAssertNil(app.appNapActivity)
+ }
+}
+
/// The native tab row: it scrolls only sideways, and each tab's × sits in the middle of the tab's body.
final class SwarmTabStripTests: XCTestCase {
private func verticalSwipe(_ dy: Int32) -> NSEvent {