Skip to content

Commit acc7523

Browse files
committed
Hub.rpc: the hub's own jobs' requests (client 0) are applied again on a hub with no client 0
bb783cc made Hub.rpc drop any request whose client is not connected. The hub's jobs report as client 0 (GitJob.say: thread.worktree, thread.local, thread.note; a dead push token's drop), and a headless hub (the JS service, backplane-serve) has no client 0: every env-worktree thread made since then got no WorktreeSet/WorktreeSkipped, so its turn waited out Worktree.wait() and ran in the project root. Other unknown clients are still dropped. test/tools/worktree_e2e.ts: a git project's thread gets WorktreeSet and its agent runs in the worktree, a plain folder's gets WorktreeSkipped; both answer within 30 s. Fixes far_e2e's 3 FAILs (ordinary thread answer, its background task, the turn over).
1 parent 1900588 commit acc7523

2 files changed

Lines changed: 87 additions & 1 deletion

File tree

‎src/server/server.bend‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11195,10 +11195,20 @@ def Hub.rpc.thin_cap(thin: Bool, h: Hub, +client: U32, +text: String, +now: Nat)
1119511195
case True{}: Hub.rpc.thin_short(TVW.Wire.within(text, 262144n), h, client, text, now)
1119611196
case False{}: Hub.rpc.parse(h, client, text, now)
1119711197

11198+
# A request from no connected client is dropped (a client that left),
11199+
# except client 0: the hub's own jobs (GitJob.say: a thread's worktree, its
11200+
# notes; a dead push token) and the in-process window send theirs as 0, and
11201+
# a headless hub has no client 0. Dropping those lost every new thread's
11202+
# worktree, so its first turn never started (far_e2e on a headless hub).
11203+
def Hub.rpc.own(own: Bool, h: Hub, +client: U32, +text: String, +now: Nat) -> IO(Hub):
11204+
match own:
11205+
case True{}: Hub.rpc.thin_cap(False{}, h, client, text, now)
11206+
case False{}: IO.pure(Hub, h)
11207+
1119811208
def Hub.rpc.client(c: Maybe<&2, Client>, h: Hub, +client: U32, +text: String, +now: Nat) -> IO(Hub):
1119911209
match c:
1120011210
case Some{c}: Hub.rpc.thin_cap(Client.thin(c), h, client, text, now)
11201-
case None{}: IO.pure(Hub, h)
11211+
case None{}: Hub.rpc.own(U32.is_eq(client, 0), h, client, text, now)
1120211212

1120311213
def Hub.rpc(h: Hub, +client: U32, +text: String, +now: Nat) -> IO(Hub):
1120411214
match h:

‎test/tools/worktree_e2e.ts‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// End to end: a new project thread's worktree. The hub's own jobs report
2+
// back to it as client 0 (server.bend GitJob.say: thread.worktree,
3+
// thread.local, thread.note); a hub with no client 0 (headless: the JS
4+
// service, backplane-serve) dropped them from bb783cc13 on (Hub.rpc.client),
5+
// so a thread never got its worktree and its first turn waited out
6+
// Worktree.wait() and ran in the project folder. On one headless hub whose
7+
// only client is this test's: a thread in a git project gets WorktreeSet
8+
// (a path under .backplane/worktrees) and its agent starts there; one in a
9+
// plain folder gets WorktreeSkipped and its agent starts in the folder;
10+
// both answer, well inside the 120 s wait. Prints "ok ..." / "FAIL ...".
11+
//
12+
// bun test/tools/worktree_e2e.ts [BINARY] [WIREDIR]
13+
//
14+
// BINARY defaults to build/backplane-serve, WIREDIR to build/wire.
15+
import { mkdtempSync, readdirSync, readFileSync, writeFileSync, chmodSync, mkdirSync } from "node:fs";
16+
import { tmpdir } from "node:os";
17+
import { join, resolve } from "node:path";
18+
const [bin = "build/backplane-serve", wire = "build/wire"] = process.argv.slice(2);
19+
let failed = false;
20+
const check = (name: string, ok: boolean, got?: unknown) => { console.log(ok ? `ok ${name}` : `FAIL ${name}: ${JSON.stringify(got)?.slice(0, 600)}`); if (!ok) failed = true; };
21+
for (const f of readdirSync(wire).filter((f) => f.endsWith(".js"))) (0, eval)(readFileSync(`${wire}/${f}`, "utf8"));
22+
const W = (globalThis as any).Wire;
23+
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
24+
const root = mkdtempSync(join(tmpdir(), "bp-ord-"));
25+
const fake = join(root, "bin"); mkdirSync(fake);
26+
writeFileSync(join(fake, "claude"), `#!/bin/sh
27+
case "$*" in *--version*) echo "2.0.0"; exit 0 ;; esac
28+
echo "$(pwd)" >> ${root}/claude.log
29+
while IFS= read -r line; do case "$line" in *'"type":"user"'*)
30+
printf '%s\\n' '{"type":"assistant","message":{"id":"m1","content":[{"type":"text","text":"pong"}]}}'
31+
printf '%s\\n' '{"type":"result","is_error":false,"result":"pong"}' ;; esac; done
32+
`);
33+
chmodSync(join(fake, "claude"), 0o755);
34+
for (const n of ["codex", "grok", "muse"]) { writeFileSync(join(fake, n), "#!/bin/sh\nexit 1\n"); chmodSync(join(fake, n), 0o755); }
35+
const s = Bun.listen({ hostname: "127.0.0.1", port: 0, socket: { data() {} } }); const port = s.port; s.stop(true);
36+
const home = join(root, "home");
37+
const proc = Bun.spawn([resolve(bin), "--home", home, "--port", String(port), "--no-tailscale"], {
38+
env: { ...process.env, HOME: join(root, "fh"), DISPLAY: "", BACKPLANE_NO_UPDATE: "1", BACKPLANE_AGENTS: fake, PATH: `${fake}:/usr/bin:/bin` },
39+
stdout: "ignore", stderr: Bun.file(join(root, "hub.err")) });
40+
try {
41+
for (let i = 0; i < 300; i++) { try { if ((await fetch(`http://127.0.0.1:${port}/hello`)).ok) break; } catch {} await sleep(100); }
42+
const seen: any[] = []; const replies = new Map<number, any>(); let n = 0;
43+
const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`); ws.binaryType = "arraybuffer";
44+
ws.onmessage = (e) => { const o = JSON.parse(W.decode(new Uint8Array(e.data as ArrayBuffer))); for (const x of o.items ?? []) seen.push(x); if (o.t === "reply") replies.set(Number(o.id), o); };
45+
await new Promise((r) => (ws.onopen = r));
46+
const rpc = async (m: string, p: object) => { const id = ++n; ws.send(W.encode(JSON.stringify({ id, m, p }))); for (let i = 0; i < 200 && !replies.has(id); i++) await sleep(50); return replies.get(id); };
47+
const one = async (name: string, git: boolean) => {
48+
const pp = join(root, name); mkdirSync(pp);
49+
if (git) Bun.spawnSync(["sh", "-c", `cd ${pp} && git init -q && git -c user.email=a@b -c user.name=a commit -q --allow-empty -m init`]);
50+
await rpc("project.add", { path: pp });
51+
for (let i = 0; i < 100 && !seen.find((c) => c.$ === "ProjectCreated" && c.root === pp); i++) await sleep(50);
52+
const pc = seen.find((c) => c.$ === "ProjectCreated" && c.root === pp);
53+
const title = `WT ${name}`;
54+
await rpc("thread.create", { project: pc?.id, title });
55+
for (let i = 0; i < 100 && !seen.find((c) => c.$ === "ThreadCreated" && c.title === title); i++) await sleep(50);
56+
const th = seen.find((c) => c.$ === "ThreadCreated" && c.title === title)?.id;
57+
const t0 = Date.now();
58+
await rpc("turn.start", { thread: th, text: "hello", msg: `${name}-m1`, mode: "queue" });
59+
const want = git ? "WorktreeSet" : "WorktreeSkipped";
60+
let wt: any;
61+
for (let i = 0; i < 600 && !wt; i++) { wt = seen.find((c) => c.$ === want && c.id === th); if (!wt) await sleep(50); }
62+
check(`${name}: the job's ${want} reaches the hub`, !!wt, seen.filter((c) => c.thread === th || c.id === th).map((c) => c.$));
63+
if (git) check(`${name}: the worktree is under .backplane/worktrees`, !!wt && String(wt.worktree).includes("/.backplane/worktrees/"), wt);
64+
let pong: any;
65+
for (let i = 0; i < 600 && !pong; i++) { pong = seen.find((c) => c.$ === "MessagePosted" && c.thread === th && c.text === "pong"); if (!pong) await sleep(50); }
66+
check(`${name}: the turn starts and answers within 30 s (not the 120 s wait)`, !!pong && Date.now() - t0 < 30000, { ms: Date.now() - t0 });
67+
let cwds: string[] = [];
68+
try { cwds = readFileSync(join(root, "claude.log"), "utf8").trim().split("\n"); } catch {}
69+
const where = git ? wt?.worktree : pp;
70+
check(`${name}: the agent runs in ${git ? "the worktree" : "the folder"}`, !!where && cwds.includes(where), { where, cwds });
71+
};
72+
await one("repo", true);
73+
await one("plain", false);
74+
} finally { proc.kill(); await proc.exited; }
75+
console.log(failed ? "worktree e2e: FAIL" : "worktree e2e: ok");
76+
process.exit(failed ? 1 : 0);

0 commit comments

Comments
 (0)