Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(cli): retry fetch on network failures in DaemonClient (#23)

Gener0bbaa41a1b91
diff --git a/src/cli/daemon/client.test.ts b/src/cli/daemon/client.test.ts
index dd8e7b9d5..7156fed0f 100644
--- a/src/cli/daemon/client.test.ts
+++ b/src/cli/daemon/client.test.ts
@@ -310,6 +310,76 @@ describe("DaemonClient.deregister() with mocked fetch", () => {
});
});
+// ---------------------------------------------------------------------------
+// DaemonClient fetch retry tests
+// ---------------------------------------------------------------------------
+
+describe("DaemonClient retries on TypeError (network failure)", () => {
+ const originalFetch = globalThis.fetch;
+
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ });
+
+ it("retries up to 3 times on TypeError then succeeds", async () => {
+ const fetchMock = vi.fn()
+ .mockRejectedValueOnce(new TypeError("fetch failed"))
+ .mockRejectedValueOnce(new TypeError("fetch failed"))
+ .mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ tasks: [] }),
+ });
+ globalThis.fetch = fetchMock;
+
+ const client = new DaemonClient("http://localhost:8080");
+ const result = await client.poll("tok", "d1", 1);
+
+ expect(result.tasks).toEqual([]);
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ });
+
+ it("throws TypeError after exhausting all retries", async () => {
+ const fetchMock = vi.fn().mockRejectedValue(new TypeError("fetch failed"));
+ globalThis.fetch = fetchMock;
+
+ const client = new DaemonClient("http://localhost:8080");
+ await expect(client.poll("tok", "d1", 1)).rejects.toThrow(TypeError);
+
+ expect(fetchMock).toHaveBeenCalledTimes(4); // 1 initial + 3 retries
+ });
+
+ it("does not retry on non-TypeError errors (e.g. HTTP errors)", async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: false,
+ status: 500,
+ text: () => Promise.resolve("Internal Server Error"),
+ });
+ globalThis.fetch = fetchMock;
+
+ const client = new DaemonClient("http://localhost:8080");
+ await expect(client.completeTask("tok", "t1", { output: "done" })).rejects.toThrow("HTTP 500");
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("retries downloadArtifact on TypeError", async () => {
+ const fetchMock = vi.fn()
+ .mockRejectedValueOnce(new TypeError("fetch failed"))
+ .mockResolvedValueOnce({
+ ok: true,
+ arrayBuffer: () => Promise.resolve(new ArrayBuffer(4)),
+ });
+ globalThis.fetch = fetchMock;
+
+ const client = new DaemonClient("http://localhost:8080");
+ const buf = await client.downloadArtifact("tok", "art1", "ws1");
+
+ expect(buf.byteLength).toBe(4);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+});
+
// ---------------------------------------------------------------------------
// DaemonClient has no heartbeat() or claimTask() methods
// ---------------------------------------------------------------------------
diff --git a/src/cli/daemon/client.ts b/src/cli/daemon/client.ts
index 41dc104d4..3e0787590 100644
--- a/src/cli/daemon/client.ts
+++ b/src/cli/daemon/client.ts
@@ -19,14 +19,31 @@ export class DaemonClient {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
};
- const res = await fetch(this.baseURL + path, {
- method,
- headers,
- body: body ? JSON.stringify(body) : undefined,
- });
- if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
- if (res.status === 204) return undefined as T;
- return res.json();
+ const MAX_RETRIES = 3;
+ const BASE_DELAY_MS = 500;
+ let lastError: unknown;
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
+ try {
+ const res = await fetch(this.baseURL + path, {
+ method,
+ headers,
+ body: body ? JSON.stringify(body) : undefined,
+ });
+ if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
+ if (res.status === 204) return undefined as T;
+ return res.json();
+ } catch (e) {
+ if (e instanceof TypeError) {
+ lastError = e;
+ if (attempt < MAX_RETRIES) {
+ await new Promise((r) => setTimeout(r, BASE_DELAY_MS * 2 ** attempt));
+ continue;
+ }
+ }
+ throw e;
+ }
+ }
+ throw lastError;
}
async register(
@@ -122,14 +139,31 @@ export class DaemonClient {
artifactId: string,
workspaceId: string,
): Promise<ArrayBuffer> {
- const res = await fetch(
- `${this.baseURL}/api/artifacts/${artifactId}/content?workspace_id=${encodeURIComponent(workspaceId)}`,
- { headers: { Authorization: `Bearer ${token}` } },
- );
- if (!res.ok) {
- throw new Error(`artifact download failed: HTTP ${res.status}`);
+ const MAX_RETRIES = 3;
+ const BASE_DELAY_MS = 500;
+ let lastError: unknown;
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
+ try {
+ const res = await fetch(
+ `${this.baseURL}/api/artifacts/${artifactId}/content?workspace_id=${encodeURIComponent(workspaceId)}`,
+ { headers: { Authorization: `Bearer ${token}` } },
+ );
+ if (!res.ok) {
+ throw new Error(`artifact download failed: HTTP ${res.status}`);
+ }
+ return res.arrayBuffer();
+ } catch (e) {
+ if (e instanceof TypeError) {
+ lastError = e;
+ if (attempt < MAX_RETRIES) {
+ await new Promise((r) => setTimeout(r, BASE_DELAY_MS * 2 ** attempt));
+ continue;
+ }
+ }
+ throw e;
+ }
}
- return res.arrayBuffer();
+ throw lastError;
}
reportMessages(