mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-27 20:09:10 +01:00
Merge branch 'codex/boat-environment-core' into codex/boat-environment
* codex/boat-environment-core: fix(computers): keep shared desktop input outside agent ownership fix(computers): reserve lifecycle traffic capacity during workspace setup
This commit is contained in:
commit
1f358b7079
5 files changed
+88
-9
No files matched your search
@@ -19,6 +19,11 @@ import { afterEach, describe, it, expect, vi } from "vitest";
|
||||
import { boatBackend, createBoatTransportAdmission, desktopReadinessProgram, processProgram } from "./boat.js";
|
||||
import { buildGitAuthInvocation } from "../../../services/git-credentials.js";
|
||||
import type { ComputerRecord } from "../domain/ledger.js";
|
||||
const sshFactory = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@paperclipai/adapter-utils/ssh", async importOriginal => ({
|
||||
...await importOriginal<typeof import("@paperclipai/adapter-utils/ssh")>(),
|
||||
createSshCommandManagedRuntimeRunner: sshFactory,
|
||||
}));
|
||||
const record: ComputerRecord = {
|
||||
id: "computer",
|
||||
companyId: "company",
|
||||
@@ -530,16 +535,28 @@ describe("Boat desktop input readiness", () => {
|
||||
const bin = join(temp, "bin");
|
||||
const healthy = join(temp, "healthy");
|
||||
const calls = join(temp, "repairs");
|
||||
const units = join(temp, "units");
|
||||
mkdirSync(runtime, { mode: 0o700 });
|
||||
mkdirSync(bin);
|
||||
if (initiallyHealthy) writeFileSync(healthy, "ready");
|
||||
writeFileSync(join(bin, "ibus"), "#!/bin/sh\ntest \"$HOME\" = /home/user && test \"$XDG_CONFIG_HOME\" = /home/user/.config && test \"$XDG_CACHE_HOME\" = /home/user/.cache || exit 1\nprintf '%s\\n' 'unix:path=/test/ibus'\n", { mode: 0o700 });
|
||||
writeFileSync(join(bin, "gdbus"), `#!/bin/sh\ntest -f '${healthy}'\n`, { mode: 0o700 });
|
||||
writeFileSync(join(bin, "ibus-daemon"), `#!/bin/sh\nprintf '%s\\n' "$*" >> '${calls}'\ntouch '${healthy}'\n`, { mode: 0o700 });
|
||||
const call = (program = desktopReadinessProgram) => spawnSync("python3", ["-c", program.replaceAll("/run/user/", `${temp}/`)], {
|
||||
writeFileSync(join(bin, "systemd-run"), `#!/usr/bin/env python3
|
||||
import os,sys,json
|
||||
args=sys.argv[1:]
|
||||
with open(${JSON.stringify(units)},'a') as target:target.write(json.dumps(args)+'\\n')
|
||||
env=dict(os.environ)
|
||||
for arg in args:
|
||||
if arg.startswith('--setenv='):
|
||||
key,value=arg[len('--setenv='):].split('=',1);env[key]=value
|
||||
command=args[args.index('--')+1:]
|
||||
os.execve(command[0],command,env)
|
||||
`, { mode: 0o700 });
|
||||
const call = (program = desktopReadinessProgram) => spawnSync("python3", ["-c", program.replaceAll("/run/user/", `${temp}/`).replaceAll("/usr/bin/ibus-daemon", join(bin, "ibus-daemon"))], {
|
||||
encoding: "utf8", env: { ...process.env, HOME: join(temp, "agent-home"), XDG_CONFIG_HOME: join(temp, "agent-config"), XDG_CACHE_HOME: join(temp, "agent-cache"), PATH: `${bin}:${process.env.PATH}` },
|
||||
});
|
||||
return { temp, runtime, healthy, calls, call };
|
||||
return { temp, runtime, healthy, calls, units, call };
|
||||
}
|
||||
|
||||
it("preserves a healthy input service and emits no MCP protocol output", () => {
|
||||
@@ -555,6 +572,9 @@ describe("Boat desktop input readiness", () => {
|
||||
expect(f.call().status).toBe(0);
|
||||
const expected = `--replace --daemonize --xim --address unix:path=${f.runtime}/paperclip-ibus/bus\n`;
|
||||
expect(readFileSync(f.calls, "utf8")).toBe(expected);
|
||||
const unit = JSON.parse(readFileSync(f.units, "utf8").trim());
|
||||
expect(unit).toEqual(expect.arrayContaining(["--slice=app.slice", "--collect", "--property=ExitType=cgroup", "--setenv=HOME=/home/user"]));
|
||||
expect(unit.find((value: string) => value.startsWith("--unit="))).toMatch(/^--unit=paperclip-desktop-input-[a-f0-9]{32}\.service$/);
|
||||
expect(f.call().status).toBe(0);
|
||||
expect(readFileSync(f.calls, "utf8")).toBe(expected);
|
||||
rmSync(f.healthy);
|
||||
@@ -562,6 +582,24 @@ describe("Boat desktop input readiness", () => {
|
||||
expect(readFileSync(f.calls, "utf8")).toBe(expected.repeat(2));
|
||||
});
|
||||
|
||||
it("checks input on explicit Connect but reuses credentials without daemon work during presence", async () => {
|
||||
const id = randomUUID();
|
||||
const scoped = { ...record, id, providerId: `bx_${id}` };
|
||||
const execute = vi.fn(async () => ({ exitCode: 0, stdout: "{}", stderr: "", timedOut: false, signal: null, pid: null, startedAt: "" }));
|
||||
sshFactory.mockReturnValue({ execute });
|
||||
const fetcher = vi.fn(async (url: string | URL | Request) => String(url).endsWith("/sshkey")
|
||||
? json({ hostKey: "ssh-ed25519 AAAA", sshEndpoint: "fixture.invalid:2222" })
|
||||
: json({ desktopUrl: "https://fixture.on.boat.dev/" }));
|
||||
const backend = boatBackend(async () => "fixture-key", fetcher);
|
||||
const viewer = await backend.desktop(scoped);
|
||||
expect(execute).toHaveBeenCalledOnce();
|
||||
expect(await backend.desktop(scoped, { checkInput: false })).toEqual(viewer);
|
||||
expect(execute).toHaveBeenCalledOnce();
|
||||
expect(await backend.desktop(scoped)).toEqual(viewer);
|
||||
expect(execute).toHaveBeenCalledTimes(2);
|
||||
expect(fetcher.mock.calls.filter(([url]) => String(url).endsWith("/desktop"))).toHaveLength(1);
|
||||
sshFactory.mockReset();
|
||||
});
|
||||
it("rejects a symlink input directory without replacing the daemon", () => {
|
||||
const f = desktopFixture(false);
|
||||
symlinkSync(f.temp, join(f.runtime, "paperclip-ibus"));
|
||||
@@ -607,6 +645,34 @@ describe("Boat SSH admission", () => {
|
||||
await Promise.all(jobs);
|
||||
expect(runner.execute).toHaveBeenCalledTimes(12);
|
||||
});
|
||||
it("classifies checkout and file operations below reserved lifecycle capacity", async () => {
|
||||
const id = randomUUID();
|
||||
const scoped = { ...record, id, providerId: `bx_${id}` };
|
||||
const completions: Array<() => void> = [];
|
||||
const execute = vi.fn(async (_input: { stdin?: string }) => new Promise<typeof result>(resolve => {
|
||||
completions.push(() => resolve({ ...result, stdout: "{}" }));
|
||||
}));
|
||||
sshFactory.mockReturnValue({ execute });
|
||||
const backend = boatBackend(async () => "fixture-key", vi.fn(async () => json({
|
||||
hostKey: "ssh-ed25519 AAAA", sshEndpoint: "fixture.invalid:2222",
|
||||
})));
|
||||
const jobs = Array.from({ length: 8 }, (_, index) => backend.remote(scoped, {
|
||||
action: index % 2 ? "workspace" : "list", root: "/home/user/paperclip/company/project",
|
||||
}));
|
||||
await vi.waitFor(() => expect(execute).toHaveBeenCalledTimes(6));
|
||||
jobs.push(backend.retire(scoped, { id: "owner", generation: 1, kind: "runner", phase: "retiring", port: 43127,
|
||||
deadline: null, absoluteDeadline: null, process: null }));
|
||||
jobs.push(backend.remote(scoped, { action: "owned-port", port: 5173, ownerId: "owner" }));
|
||||
await vi.waitFor(() => expect(execute).toHaveBeenCalledTimes(8));
|
||||
const actions = execute.mock.calls.map(([input]) => JSON.parse(input.stdin!).action);
|
||||
expect(actions.filter(action => action === "workspace" || action === "list")).toHaveLength(6);
|
||||
expect(actions).toContain("retire"); expect(actions).toContain("owned-port");
|
||||
completions.splice(0).forEach(finish => finish());
|
||||
await vi.waitFor(() => expect(execute).toHaveBeenCalledTimes(10));
|
||||
completions.splice(0).forEach(finish => finish());
|
||||
await Promise.all(jobs);
|
||||
sshFactory.mockReset();
|
||||
});
|
||||
it("expires queued work without starting it and preserves the original remaining timeout", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
|
||||
@@ -80,7 +80,7 @@ const desktopCache = new Map<
|
||||
{ viewerUrl: string; expiresAt: string }
|
||||
>();
|
||||
export const desktopReadinessProgram = String.raw`
|
||||
import os,sys,json,stat,fcntl,subprocess,time
|
||||
import os,sys,json,stat,fcntl,subprocess,time,uuid
|
||||
# Boat restores its persistent home, but Unix sockets there can refer to stale
|
||||
# kernel listeners. Keep a healthy IBus unchanged; repair only a failed probe.
|
||||
uid=os.getuid();runtime='/run/user/'+str(uid)
|
||||
@@ -103,7 +103,13 @@ fd=os.open(root+'/lock',os.O_CREAT|os.O_RDWR|os.O_NOFOLLOW,0o600)
|
||||
with os.fdopen(fd,'a') as lock:
|
||||
fcntl.flock(lock,fcntl.LOCK_EX)
|
||||
if not healthy():
|
||||
result=subprocess.run(['ibus-daemon','--replace','--daemonize','--xim','--address','unix:path='+root+'/bus'],env=env,capture_output=True,timeout=20)
|
||||
# IBus serves the whole desktop. A Cua launcher can be inside an agent slice;
|
||||
# start the repaired daemon in app.slice so retiring that agent cannot kill it.
|
||||
desktop_keys=['HOME','XDG_CONFIG_HOME','XDG_CACHE_HOME','DISPLAY','XAUTHORITY','DBUS_SESSION_BUS_ADDRESS','XDG_RUNTIME_DIR','IBUS_ENABLE_SYNC_MODE']
|
||||
command=['systemd-run','--user','--quiet','--collect','--service-type=exec','--expand-environment=no','--slice=app.slice','--unit=paperclip-desktop-input-'+uuid.uuid4().hex+'.service','--property=ExitType=cgroup','--property=KillMode=control-group']
|
||||
command.extend('--setenv='+key+'='+env[key] for key in desktop_keys)
|
||||
command.extend(['--','/usr/bin/ibus-daemon','--replace','--daemonize','--xim','--address','unix:path='+root+'/bus'])
|
||||
result=subprocess.run(command,env=env,capture_output=True,timeout=20)
|
||||
if result.returncode:raise RuntimeError('desktop input repair failed')
|
||||
for attempt in range(10):
|
||||
if healthy():break
|
||||
@@ -342,9 +348,10 @@ export function boatBackend(
|
||||
record: ComputerRecord,
|
||||
code: string,
|
||||
payload: unknown,
|
||||
control = true,
|
||||
) {
|
||||
const result = await (
|
||||
await runner(record, { control: true })
|
||||
await runner(record, { control })
|
||||
).execute({
|
||||
command: "python3",
|
||||
args: ["-c", code],
|
||||
@@ -502,8 +509,9 @@ print('{}')
|
||||
args: ["-c", `${desktopReadinessProgram}\nos.execv('/opt/ascii/cua-driver/cua-driver',['cua-driver','mcp','--socket','/run/ascii-cua/driver.sock'])`],
|
||||
};
|
||||
},
|
||||
async desktop(record) {
|
||||
await execute(record, `${desktopReadinessProgram}\nprint('{}')`, {});
|
||||
async desktop(record, options) {
|
||||
if (options?.checkInput !== false)
|
||||
await execute(record, `${desktopReadinessProgram}\nprint('{}')`, {});
|
||||
const cached = desktopCache.get(record.id);
|
||||
if (cached && Date.parse(cached.expiresAt) > Date.now() + 60_000)
|
||||
return cached;
|
||||
@@ -550,7 +558,9 @@ print('{}')
|
||||
return { url: url.toString(), secretHeaders: { Cookie: cookie } };
|
||||
},
|
||||
async remote(record, input) {
|
||||
return execute(record, remoteProgram, input);
|
||||
// Git setup and file I/O may wait on locks or transfer substantial data.
|
||||
// Keep lifecycle capacity reserved; only the short owned-port probe uses it.
|
||||
return execute(record, remoteProgram, input, input.action === "owned-port");
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -56,6 +56,7 @@ export interface ComputerBackend {
|
||||
computerTool(): { command: string; args: string[] };
|
||||
desktop(
|
||||
record: ComputerRecord,
|
||||
options?: { checkInput?: boolean },
|
||||
): Promise<{ viewerUrl: string; expiresAt: string }>;
|
||||
ingress(
|
||||
record: ComputerRecord,
|
||||
|
||||
@@ -248,6 +248,7 @@ describe("computer ownership", () => {
|
||||
})
|
||||
).expiresAt,
|
||||
).toBe(viewer.expiresAt);
|
||||
expect(f.backend.desktop).toHaveBeenLastCalledWith(expect.anything(), { checkInput: false });
|
||||
f.advance(1_001);
|
||||
await expect(
|
||||
f.service.renewViewer({
|
||||
|
||||
@@ -629,7 +629,8 @@ finally:
|
||||
"conflict",
|
||||
"Computer connection expired; connect again",
|
||||
);
|
||||
const viewer = await backend.desktop(record);
|
||||
// Presence refreshes credentials; desktop readiness belongs to explicit Connect.
|
||||
const viewer = await backend.desktop(record, { checkInput: false });
|
||||
return {
|
||||
...viewer,
|
||||
expiresAt: new Date(
|
||||
|
||||
Reference in new issue
Block a user