From d4047f2fefd3db2c46f51c114bae67df6c47fc82 Mon Sep 17 00:00:00 2001 From: Dotta Date: Sat, 10 Oct 2026 12:19:06 -0500 Subject: [PATCH 1/2] fix(computers): reserve lifecycle traffic capacity during workspace setup Route project setup and file operations through ordinary SSH admission, retaining reserved control capacity for owned-port inspection and lifecycle operations. Co-Authored-By: Paperclip --- .../modules/computers/adapters/boat.test.ts | 33 +++++++++++++++++++ server/src/modules/computers/adapters/boat.ts | 7 ++-- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/server/src/modules/computers/adapters/boat.test.ts b/server/src/modules/computers/adapters/boat.test.ts index 5485df95652..8c072c152e3 100644 --- a/server/src/modules/computers/adapters/boat.test.ts +++ b/server/src/modules/computers/adapters/boat.test.ts @@ -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(), + createSshCommandManagedRuntimeRunner: sshFactory, +})); const record: ComputerRecord = { id: "computer", companyId: "company", @@ -607,6 +612,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(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 { diff --git a/server/src/modules/computers/adapters/boat.ts b/server/src/modules/computers/adapters/boat.ts index 9944f1d222b..16bd5c27c2e 100644 --- a/server/src/modules/computers/adapters/boat.ts +++ b/server/src/modules/computers/adapters/boat.ts @@ -342,9 +342,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], @@ -550,7 +551,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"); }, }; } From d91b4fef7bc48f8cc78aad639e2c6492148b965c Mon Sep 17 00:00:00 2001 From: Dotta Date: Sat, 10 Oct 2026 12:21:34 -0500 Subject: [PATCH 2/2] 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 --- .../modules/computers/adapters/boat.test.ts | 37 ++++++++++++++++++- server/src/modules/computers/adapters/boat.ts | 15 ++++++-- .../modules/computers/application/ports.ts | 1 + .../computers/application/service.test.ts | 1 + .../modules/computers/application/service.ts | 3 +- 5 files changed, 50 insertions(+), 7 deletions(-) diff --git a/server/src/modules/computers/adapters/boat.test.ts b/server/src/modules/computers/adapters/boat.test.ts index 8c072c152e3..fc08211e16b 100644 --- a/server/src/modules/computers/adapters/boat.test.ts +++ b/server/src/modules/computers/adapters/boat.test.ts @@ -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")); diff --git a/server/src/modules/computers/adapters/boat.ts b/server/src/modules/computers/adapters/boat.ts index 16bd5c27c2e..030fde7af36 100644 --- a/server/src/modules/computers/adapters/boat.ts +++ b/server/src/modules/computers/adapters/boat.ts @@ -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; diff --git a/server/src/modules/computers/application/ports.ts b/server/src/modules/computers/application/ports.ts index 649acafc2ba..c8c7d478dcb 100644 --- a/server/src/modules/computers/application/ports.ts +++ b/server/src/modules/computers/application/ports.ts @@ -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, diff --git a/server/src/modules/computers/application/service.test.ts b/server/src/modules/computers/application/service.test.ts index bf3cdfb3f8c..fe44159f256 100644 --- a/server/src/modules/computers/application/service.test.ts +++ b/server/src/modules/computers/application/service.test.ts @@ -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({ diff --git a/server/src/modules/computers/application/service.ts b/server/src/modules/computers/application/service.ts index cb63c1b3c19..d5c5548e73f 100644 --- a/server/src/modules/computers/application/service.ts +++ b/server/src/modules/computers/application/service.ts @@ -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(