Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/bundled/codex/rpc.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { expect, it, vi } from "vitest";
import { checkReplyChunking } from "../../../tests/reply-chunking";
import type { HostProcessOptions } from "../../features/host/service";
import { AppServer, type Wire } from "./rpc";
function fixture() {
Expand Down Expand Up @@ -60,6 +61,23 @@ it("correlates out-of-order JSONL responses across chunk boundaries and rejects
expect(two).not.toHaveBeenCalled();
await f.rpc.close();
});
it("delivers the same Codex replies at every stdout split", async () => {
const servers: AppServer[] = [];
try {
await checkReplyChunking(async () => {
const f = fixture();
servers.push(f.rpc);
await f.open();
const replies = Array.from({ length: 3 }, () => f.rpc.request("example"));
const ids = f.sent
.filter((wire) => wire.method === "example")
.map((wire) => wire.id);
return { replies, ids, stdout: f.raw };
});
} finally {
await Promise.all(servers.map((rpc) => rpc.close()));
}
});
it("contains consumer exceptions and closes malformed output while rejecting pending work", async () => {
const f = fixture();
await f.open();
Expand Down
17 changes: 11 additions & 6 deletions src/bundled/codex/rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export class AppServer {
private process?: HostProcess;
private failure?: Error;
private buffer = "";
private newline = -1;
private stderr = "";
private listeners = new Set<(message: Wire) => void>();
private readonly unconfirmedReleases = new Set<string>();
Expand Down Expand Up @@ -135,6 +136,7 @@ export class AppServer {
this.closing = undefined;
this.gone = false;
this.buffer = this.stderr = "";
this.newline = -1;
this.unconfirmedReleases.clear();
return this.open(spawn, cwd, protectedRuntime);
}
Expand Down Expand Up @@ -172,13 +174,16 @@ export class AppServer {
// Always return to Tauri's channel handler, including malformed output or
// a throwing consumer; otherwise the final exit event can be stranded.
try {
if (this.newline < 0) {
const next = data.indexOf("\n");
if (next >= 0) this.newline = this.buffer.length + next;
}
this.buffer += data;
let newline = this.buffer.indexOf("\n");
while (newline >= 0) {
if (newline > 4 * 1024 * 1024) throw new Oversized();
const line = this.buffer.slice(0, newline);
this.buffer = this.buffer.slice(newline + 1);
newline = this.buffer.indexOf("\n");
while (this.newline >= 0) {
if (this.newline > 4 * 1024 * 1024) throw new Oversized();
const line = this.buffer.slice(0, this.newline);
this.buffer = this.buffer.slice(this.newline + 1);
this.newline = this.buffer.indexOf("\n");
if (!line.trim()) continue;
const message: Wire = JSON.parse(line);
const waiter =
Expand Down
24 changes: 24 additions & 0 deletions src/bundled/pi/pi.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { expect, it, vi } from "vitest";
import { checkReplyChunking } from "../../../tests/reply-chunking";
import { AGENT_KEY } from "../../features/agents/membership";
import hostSource from "./host.mjs?raw";
import manifest from "./manifest.json";
Expand Down Expand Up @@ -104,6 +105,29 @@ it("reads messages split across chunks, and several in one", async () => {
});
});

it("delivers the same Pi replies at every stdout split", async () => {
await checkReplyChunking(async () => {
const written = deferred();
const hold = deferred();
const host = fakeHost({
example: ({ sequence }) => {
if (sequence === 3) written.resolve();
return hold.promise;
},
});
const pi = new Pi(() => host.spawn, handlers());
const replies = [1, 2, 3].map((sequence) =>
pi.request("example", { sequence }),
);
await written.promise;
return {
replies,
ids: host.requests("example").map((request) => request.id),
stdout: (data) => host.processes[0]?.options.onStdout?.(data),
};
});
});

it("says why a host could not start, and starts another for the next request", async () => {
const host = fakeHost({ ping: () => ({ pong: true }) }, { ready: false });
const pi = new Pi(() => host.spawn, handlers());
Expand Down
6 changes: 5 additions & 1 deletion src/bundled/pi/pi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,7 @@ export class Pi {
};
});
let buffer = "";
let newline = -1;
let stderr = "";
const connection: Connection = {
lifetime: new AbortController(),
Expand Down Expand Up @@ -402,8 +403,11 @@ export class Pi {
}
: {}),
onStdout: (data) => {
if (newline < 0) {
const next = data.indexOf("\n");
if (next >= 0) newline = buffer.length + next;
}
buffer += data;
let newline = buffer.indexOf("\n");
while (newline >= 0) {
const line = buffer.slice(0, newline).trim();
buffer = buffer.slice(newline + 1);
Expand Down
14 changes: 14 additions & 0 deletions src/features/agent-harness/acp/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
fakeSpawn as fakeGoose,
flush,
} from "../../../bundled/goose/goose-testing";
import { checkReplyChunking } from "../../../../tests/reply-chunking";
import { GOOSE } from "../../../bundled/goose/goose";
import { AgentProcess } from "../../../bundled/goose/sessions";
import type {
Expand Down Expand Up @@ -256,6 +257,19 @@ describe("starting a harness", () => {
});
});

it("delivers the same ACP replies at every stdout split", async () => {
await checkReplyChunking(async () => {
const harness = fakeHarness({ silent: ["example"] });
const acp = await start(harness);
const replies = [1, 2, 3].map(() => acp.request("example", {}));
return {
replies,
ids: harness.sent("example").map((request) => request.id),
stdout: (data) => harness.started[0]?.options.onStdout?.(data),
};
});
});

it("refuses a harness that cannot take Buzz tools over HTTP MCP", async () => {
for (const http of [false, undefined, "yes"]) {
const harness = fakeHarness({
Expand Down
14 changes: 9 additions & 5 deletions src/features/agent-harness/acp/process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ export class AcpProcess {
private readonly calls = new Map<number, Pending>();
private requests = 0;
private buffer = "";
private newline = -1;
private stderr = "";
private alive = true;
private code: number | null | undefined;
Expand Down Expand Up @@ -520,12 +521,15 @@ export class AcpProcess {
this.stderr = (this.stderr + data).slice(-STDERR_LIMIT);
}
private read(data: string) {
if (this.newline < 0) {
const next = data.indexOf("\n");
if (next >= 0) this.newline = this.buffer.length + next;
}
this.buffer += data;
let newline = this.buffer.indexOf("\n");
while (newline >= 0) {
const line = this.buffer.slice(0, newline).trim();
this.buffer = this.buffer.slice(newline + 1);
newline = this.buffer.indexOf("\n");
while (this.newline >= 0) {
const line = this.buffer.slice(0, this.newline).trim();
this.buffer = this.buffer.slice(this.newline + 1);
this.newline = this.buffer.indexOf("\n");
if (!line) continue;
let message: Wire;
try {
Expand Down
40 changes: 40 additions & 0 deletions tests/reply-chunking.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { expect } from "vitest";

type Wire = {
ids: (number | string | undefined)[];
replies: Promise<unknown>[];
stdout: (chunk: string) => void;
};

export async function checkReplyChunking(open: () => Promise<Wire>) {
async function deliver(split: (payload: string) => string[]) {
const { ids, replies, stdout } = await open();
expect(ids).toHaveLength(3);
const lines = ids.map((id, index) =>
JSON.stringify({ jsonrpc: "2.0", id, result: index + 1 }),
);
const payload = `${lines[1]}\r\n\n ${lines[0]} \n${lines[2]}`;
const delivered: unknown[] = [];
const answers = replies.map((reply) =>
reply.then((value) => delivered.push(value)),
);
for (const chunk of split(payload)) stdout(chunk);
await Promise.all(answers.slice(0, 2));
const beforeNewline = [...delivered];
stdout("\n");
await Promise.all(answers);
return { length: payload.length, beforeNewline, delivered };
}

const whole = await deliver((payload) => [payload]);
expect(whole.beforeNewline).toEqual([2, 1]);
expect(whole.delivered).toEqual([2, 1, 3]);
for (let cut = 0; cut <= whole.length; cut++) {
const split = await deliver((payload) => [
payload.slice(0, cut),
payload.slice(cut),
]);
expect(split, `split at ${cut}`).toEqual(whole);
}
expect(await deliver((payload) => [...payload])).toEqual(whole);
}
Loading