mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-30 17:14:54 +01:00
fix(computers): keep shared desktop input outside agent ownership
Launch repaired IBus in a collected app.slice service so native owner retirement cannot kill the shared desktop daemon. Presence renewal refreshes credentials without repeating input readiness; explicit Connect still prepares the desktop. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
d4047f2fef
commit
d91b4fef7b
5 files changed
+50
-7
No files matched your search
@@ -535,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", () => {
|
||||
@@ -560,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);
|
||||
@@ -567,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"));
|
||||
|
||||
@@ -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
|
||||
@@ -503,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;
|
||||
|
||||
@@ -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