Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(teamhub-cli): preserve operation IDs after unreadable write responses

Afloate04536f20038
diff --git a/apps/teamhub-cli/README.md b/apps/teamhub-cli/README.md
index dcbc7d45..092b1f58 100644
--- a/apps/teamhub-cli/README.md
+++ b/apps/teamhub-cli/README.md
@@ -40,6 +40,8 @@ An Agent reads, edits and manages every Document its Human has; no access reques
Write commands that accept `--operation-id` should use one unique ID per logical operation. The CLI keeps no local receipts: after an unknown outcome, rerun the same command and input with the operation ID the error printed, and TeamHub returns the original result. Without `--operation-id` every run is a new write. An operation ID does not replace CAS. `duplicate_request: true` means TeamHub reused the original result and comes with a `reason`; neither a conflict nor an unknown outcome is a success. When a Connected Apps write has an unknown outcome, check the external application first; the CLI never resends it.
+A TeamHub write with an operation ID also reports `outcome_unknown` when its successful HTTP response has an interrupted, malformed, oversized, or non-object JSON body. The error preserves the same operation ID for a deliberate retry; receiving success headers alone does not cause the CLI to invent a result or resend the write. A successful `204 No Content` remains a complete empty result.
+
Task completion uses only the generation, attempt and input revision accepted before work started; Runtime-managed configuration freezes them. `task list` returns authorized summaries only; it does not replace the original Task input or refresh the submission baseline of an old result.
The current entry points are the ones help lists.
diff --git a/apps/teamhub-cli/src/http-client.test.ts b/apps/teamhub-cli/src/http-client.test.ts
index b8d80af7..559c8383 100644
--- a/apps/teamhub-cli/src/http-client.test.ts
+++ b/apps/teamhub-cli/src/http-client.test.ts
@@ -74,6 +74,136 @@ describe("direct TeamHub HTTP client", () => {
});
expect(fetcher).toHaveBeenCalledTimes(1);
});
+ describe.each(["api", "request"] as const)("%s writes", (transport) => {
+ it.each([
+ {
+ name: "interrupted body",
+ response: () =>
+ new Response(
+ new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.error(new Error("response body disconnected"));
+ },
+ }),
+ { status: 201 },
+ ),
+ },
+ {
+ name: "truncated JSON",
+ response: () => new Response('{"accepted":', { status: 201 }),
+ },
+ {
+ name: "unexpected JSON shape",
+ response: () => Response.json([], { status: 201 }),
+ },
+ {
+ name: "oversized body",
+ response: () =>
+ new Response(new Uint8Array(8 * 1024 * 1024 + 1), { status: 201 }),
+ },
+ ])(
+ "retains the write operation ID after a successful status with $name",
+ async ({ response }) => {
+ const fetcher = vi.fn<typeof fetch>().mockResolvedValue(response());
+ const client = createTeamHubClient(config, { fetch: fetcher });
+ await expect(
+ transport === "api"
+ ? client.api.POST("/api/agent/v1/direct-messages", {
+ body: {} as never,
+ headers: operationHeaders("stable-reply"),
+ })
+ : client.request("/api/agent/v1/messages/commit", {
+ method: "POST",
+ headers: operationHeaders("stable-reply"),
+ body: new FormData(),
+ }),
+ ).rejects.toMatchObject({
+ code: "outcome_unknown",
+ details: { operation_id: "stable-reply" },
+ });
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ },
+ );
+ });
+ it("keeps malformed read responses as invalid responses", async () => {
+ const client = createTeamHubClient(config, {
+ fetch: vi.fn<typeof fetch>().mockResolvedValue(new Response("{")),
+ });
+ await expect(
+ client.api.GET("/api/agent/v1/files", {
+ params: { query: { after_id: "", limit: 100 } },
+ }),
+ ).rejects.toMatchObject({ code: "invalid_response", details: {} });
+ });
+ it("accepts a successful write with no response body", async () => {
+ const fetcher = vi
+ .fn<typeof fetch>()
+ .mockResolvedValue(new Response(null, { status: 204 }));
+ const client = createTeamHubClient(config, { fetch: fetcher });
+ expect(
+ await teamHubData(
+ client.api.POST("/api/agent/v1/direct-messages", {
+ body: {} as never,
+ headers: operationHeaders("stable-reply"),
+ }),
+ ),
+ ).toEqual({});
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ });
+ it("keeps direct successful write responses readable with their metadata", async () => {
+ const body = '{\n "accepted": true\n}\n';
+ const fetcher = vi.fn<typeof fetch>().mockResolvedValue(
+ new Response(body, {
+ status: 201,
+ statusText: "Created",
+ headers: {
+ "content-type": "application/json",
+ "content-length": String(Buffer.byteLength(body)),
+ "x-request-id": "request-write",
+ },
+ }),
+ );
+ const client = createTeamHubClient(config, { fetch: fetcher });
+ const response = await client.request("/api/agent/v1/messages/commit", {
+ method: "POST",
+ headers: operationHeaders("stable-reply"),
+ body: new FormData(),
+ });
+ expect(response.status).toBe(201);
+ expect(response.statusText).toBe("Created");
+ expect(response.headers.get("x-request-id")).toBe("request-write");
+ expect(response.bodyUsed).toBe(false);
+ expect(response.headers.get("content-length")).toBe(
+ String(Buffer.byteLength(body)),
+ );
+ expect(await response.text()).toBe(body);
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ });
+ it("keeps direct empty successful writes complete", async () => {
+ const fetcher = vi
+ .fn<typeof fetch>()
+ .mockResolvedValue(new Response(null, { status: 204 }));
+ const client = createTeamHubClient(config, { fetch: fetcher });
+ const response = await client.request("/api/agent/v1/messages/commit", {
+ method: "POST",
+ headers: operationHeaders("stable-reply"),
+ });
+ expect(response.status).toBe(204);
+ expect(response.body).toBeNull();
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ });
+ it("does not consume or apply the JSON limit to byte reads", async () => {
+ const bytes = new Uint8Array(8 * 1024 * 1024 + 1).fill(255);
+ const original = new Response(bytes);
+ const client = createTeamHubClient(config, {
+ fetch: vi.fn<typeof fetch>().mockResolvedValue(original),
+ });
+ const response = await client.request(
+ "/api/agent/v1/files/document_one/content",
+ );
+ expect(original.bodyUsed).toBe(false);
+ expect(Buffer.from(await response.arrayBuffer()).equals(bytes)).toBe(true);
+ });
it("preserves structured TeamHub permission and conflict errors", async () => {
const client = createTeamHubClient(config, {
fetch: vi.fn<typeof fetch>().mockResolvedValue(
@@ -90,10 +220,16 @@ describe("direct TeamHub HTTP client", () => {
),
});
await expect(
- client.api.POST("/api/agent/v1/documents", { body: {} as never }),
+ client.api.POST("/api/agent/v1/documents", {
+ body: {} as never,
+ headers: operationHeaders("stable-document"),
+ }),
).rejects.toMatchObject({
code: "version_conflict",
- details: { current_version_id: "v2" },
+ details: {
+ current_version_id: "v2",
+ operation_id: "stable-document",
+ },
});
});
it("sends configured identity assertions and the Run to the credential authority and keeps shared links anonymous", async () => {
diff --git a/apps/teamhub-cli/src/http-client.ts b/apps/teamhub-cli/src/http-client.ts
index 53ad120f..49c857bb 100644
--- a/apps/teamhub-cli/src/http-client.ts
+++ b/apps/teamhub-cli/src/http-client.ts
@@ -89,13 +89,8 @@ export function createTeamHubClient(
method,
outcome: "failure",
});
- throw new CliError(
- operationId ? "outcome_unknown" : "connection_failed",
- operationId
- ? "The operation outcome is unknown. Retry with --operation-id set to this Operation ID."
- : "Could not reach TeamHub.",
- operationId ? { operation_id: operationId } : {},
- );
+ if (operationId) throw unknownWriteOutcome(operationId);
+ throw new CliError("connection_failed", "Could not reach TeamHub.");
}
if (timing) {
const returnedId = response.headers.get("x-request-id");
@@ -147,6 +142,13 @@ export function createTeamHubClient(
},
);
}
+ if (operationId && response.status !== 204) {
+ try {
+ return await jsonResponse(response);
+ } catch {
+ throw unknownWriteOutcome(operationId);
+ }
+ }
return response;
};
// The base URL only shapes the Request: the transport above prefixes the
@@ -160,19 +162,36 @@ export function createTeamHubClient(
headers: call.headers,
...(call.body ? { body: await call.text() } : {}),
});
- if (response.status === 204) return response;
- const value = await readJson(response);
- if (!record(value))
- throw new CliError(
- "invalid_response",
- "TeamHub returned an invalid JSON response.",
- );
- return Response.json(value, { status: response.status });
+ if (response.status === 204 || call.headers.get("x-teamhub-operation-id"))
+ return response;
+ return jsonResponse(response);
},
});
return { config, api, request };
}
+async function jsonResponse(response: Response): Promise<Response> {
+ const content = await readBounded(response, 8 * 1024 * 1024);
+ if (!record(parseJson(content)))
+ throw new CliError(
+ "invalid_response",
+ "TeamHub returned an invalid JSON response.",
+ );
+ return new Response(content, {
+ status: response.status,
+ statusText: response.statusText,
+ headers: response.headers,
+ });
+}
+
+function unknownWriteOutcome(operationId: string): CliError {
+ return new CliError(
+ "outcome_unknown",
+ "The operation outcome is unknown. Retry with --operation-id set to this Operation ID.",
+ { operation_id: operationId },
+ );
+}
+
function timedResponse(
response: Response,
timing: CliTiming,
@@ -226,7 +245,9 @@ function record(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
export async function readJson(response: Response): Promise<unknown> {
- const content = await readBounded(response, 8 * 1024 * 1024);
+ return parseJson(await readBounded(response, 8 * 1024 * 1024));
+}
+function parseJson(content: Buffer): unknown {
try {
return JSON.parse(content.toString("utf8"));
} catch {
@@ -239,7 +260,7 @@ export async function readJson(response: Response): Promise<unknown> {
export async function readBounded(
response: Response,
limit: number,
-): Promise<Buffer> {
+): Promise<Buffer<ArrayBuffer>> {
if (!response.body) return Buffer.alloc(0);
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
diff --git a/apps/teamhub-cli/src/message-send-executor.test.ts b/apps/teamhub-cli/src/message-send-executor.test.ts
index b466febb..fe0ea096 100644
--- a/apps/teamhub-cli/src/message-send-executor.test.ts
+++ b/apps/teamhub-cli/src/message-send-executor.test.ts
@@ -12,9 +12,9 @@ import {
import type { FileHandle } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { executeMessageSend } from "./message-send-executor.js";
-import type { TeamHubHttpClient } from "./http-client.js";
+import { createTeamHubClient, type TeamHubHttpClient } from "./http-client.js";
import { displayText } from "./display-text.js";
const roots: string[] = [];
@@ -65,6 +65,44 @@ function result(body: FormData) {
});
}
describe("atomic message resource execution", () => {
+ it("retains the operation ID when a successful message response is unreadable", async () => {
+ const cwd = await root();
+ const fetcher = vi
+ .fn<typeof fetch>()
+ .mockResolvedValue(new Response('{"accepted":', { status: 201 }));
+ const transport = createTeamHubClient(
+ {
+ url: "https://example.test",
+ token: "th_agent_fixture",
+ identityKey: "test-identity",
+ },
+ { fetch: fetcher },
+ );
+ await expect(
+ executeMessageSend(
+ {
+ inbox_id: "room_example",
+ message_segments: [{ type: "text", content: "On it" }],
+ },
+ {
+ client: transport,
+ cwd,
+ stateRoot: cwd,
+ operationId: "operation-reply",
+ target: { type: "room", id: "room_example" },
+ },
+ ),
+ ).rejects.toMatchObject({
+ code: "outcome_unknown",
+ details: { operation_id: "operation-reply" },
+ });
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ expect(
+ new Headers(fetcher.mock.calls[0]![1]!.headers).get(
+ "x-teamhub-operation-id",
+ ),
+ ).toBe("operation-reply");
+ });
it("sends the continuation declaration only when declared and one invocation per operation", async () => {
const cwd = await root();
const observed: unknown[] = [];