diff --git a/packages/adapter-utils/src/execution-target.ts b/packages/adapter-utils/src/execution-target.ts index 73595d5cfa6..19a62ca4262 100644 --- a/packages/adapter-utils/src/execution-target.ts +++ b/packages/adapter-utils/src/execution-target.ts @@ -247,7 +247,7 @@ export interface AdapterComputerExecutionTarget extends Omit; retainWarm(idleTimeoutMs: number): Promise; /** False means admission superseded this owner; callers must not close its process. */ - retire(): Promise; + retire(options?: { beforeStop?: () => Promise }): Promise; computerTool: { command: string; args: string[] }; } diff --git a/packages/adapters/opencode-local/src/server/execute.remote.test.ts b/packages/adapters/opencode-local/src/server/execute.remote.test.ts index 7472e11ffe5..2271749e335 100644 --- a/packages/adapters/opencode-local/src/server/execute.remote.test.ts +++ b/packages/adapters/opencode-local/src/server/execute.remote.test.ts @@ -153,6 +153,7 @@ describe("opencode remote execution", () => { config: { command: "opencode", model: "opencode/gpt-5-nano", + extraArgs: ["--", "--dir"], ...(managed ? { managedAiConnection: { provider: "openrouter", method: "api_key" }, } : {}), @@ -236,6 +237,7 @@ describe("opencode remote execution", () => { `${managedRemoteWorkspace}/.paperclip-runtime/opencode/xdgConfig`, ); expect(modelProbeCall?.[3].remoteExecution?.remoteCwd).toBe("/remote/workspace"); + expect(runCall?.[2].slice(-4)).toEqual(["--dir", managedRemoteWorkspace, "--", "--dir"]); const call = runCall as | [string, string, string[], { env: Record; remoteExecution?: { remoteCwd: string } | null }] | undefined; @@ -335,7 +337,7 @@ describe("opencode remote execution", () => { expect(startAdapterExecutionTargetPaperclipBridge).not.toHaveBeenCalled(); }); - it("resumes saved OpenCode sessions for remote SSH execution only when the identity matches", async () => { + it("resumes matching remote sessions and preserves an explicit run directory", async () => { const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-opencode-remote-resume-")); cleanupDirs.push(rootDir); const workspaceDir = path.join(rootDir, "workspace"); @@ -370,6 +372,7 @@ describe("opencode remote execution", () => { config: { command: "opencode", model: "opencode/gpt-5-nano", + extraArgs: ["--dir", "/operator-supplied"], }, context: { paperclipWorkspace: { @@ -397,5 +400,7 @@ describe("opencode remote execution", () => { | undefined; expect(call?.[2]).toContain("--session"); expect(call?.[2]).toContain("session-123"); + expect(call?.[2].slice(-2)).toEqual(["--dir", "/operator-supplied"]); + expect(call?.[2].filter((arg) => arg === "--dir" || arg.startsWith("--dir="))).toHaveLength(1); }); }); diff --git a/packages/adapters/opencode-local/src/server/execute.ts b/packages/adapters/opencode-local/src/server/execute.ts index a7458fd3d97..7171067d005 100644 --- a/packages/adapters/opencode-local/src/server/execute.ts +++ b/packages/adapters/opencode-local/src/server/execute.ts @@ -621,6 +621,13 @@ export async function execute(ctx: AdapterExecutionContext): Promise arg === "--dir" || arg.startsWith("--dir="))) { + args.push("--dir", effectiveExecutionCwd); + } if (extraArgs.length > 0) args.push(...extraArgs); return args; }; diff --git a/packages/adapters/pi-local/src/server/models.test.ts b/packages/adapters/pi-local/src/server/models.test.ts index df777544a17..881c86defc1 100644 --- a/packages/adapters/pi-local/src/server/models.test.ts +++ b/packages/adapters/pi-local/src/server/models.test.ts @@ -1,3 +1,6 @@ +import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { ensurePiModelConfiguredAndAvailable, @@ -30,4 +33,34 @@ describe("pi models", () => { }), ).rejects.toThrow(); }); + + it("does not embed the model catalogue when the configured model is unavailable", async () => { + const directory = await mkdtemp(join(tmpdir(), "paperclip-pi-models-")); + const command = join(directory, "pi"); + const modelIds = Array.from({ length: 13 }, (_, index) => `provider/model-${index}`); + await writeFile( + command, + `#!/bin/sh\nprintf 'provider model\\n';\n${modelIds + .map((id) => { + const [provider, model] = id.split("/"); + return `printf '${provider} ${model}\\n'`; + }) + .join(";\n")}\n`, + ); + await chmod(command, 0o755); + + try { + await expect( + ensurePiModelConfiguredAndAvailable({ + command, + model: "provider/missing", + }), + ).rejects.toMatchObject({ + message: + "Configured Pi model is unavailable: provider/missing. 13 models are available; list them with `pi --list-models`.", + }); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); }); diff --git a/packages/adapters/pi-local/src/server/models.ts b/packages/adapters/pi-local/src/server/models.ts index a6081cad738..06b1a803474 100644 --- a/packages/adapters/pi-local/src/server/models.ts +++ b/packages/adapters/pi-local/src/server/models.ts @@ -188,9 +188,8 @@ export async function ensurePiModelConfiguredAndAvailable(input: { } if (!models.some((entry) => entry.id === model)) { - const sample = models.slice(0, 12).map((entry) => entry.id).join(", "); throw new Error( - `Configured Pi model is unavailable: ${model}. Available models: ${sample}${models.length > 12 ? ", ..." : ""}`, + `Configured Pi model is unavailable: ${model}. ${models.length} models are available; list them with \`pi --list-models\`.`, ); } diff --git a/server/src/modules/computers/adapters/boat.test.ts b/server/src/modules/computers/adapters/boat.test.ts index 00e65b5afff..2c2535116b0 100644 --- a/server/src/modules/computers/adapters/boat.test.ts +++ b/server/src/modules/computers/adapters/boat.test.ts @@ -180,13 +180,13 @@ describe("confined computer files", () => { const chunk = Buffer.alloc(1024 * 1024, 19); for (const offset of [0, chunk.length]) expect(f.call({ action: "seed-chunk", seedId, path: "memory/data", offset, base64: chunk.toString("base64") })).toEqual({}); expect(existsSync(f.root)).toBe(false); - const staging = readdirSync(f.temp).find(name => name.startsWith(".paperclip-seed-"))!; + const staging = readdirSync(f.temp).find(name => name.startsWith(".paperclip-seed-") && statSync(join(f.temp, name)).isDirectory())!; expect(statSync(join(f.temp, staging)).mode & 0o777).toBe(0o700); expect(statSync(join(f.temp, staging, "tree", "memory", "data")).mode & 0o777).toBe(0o600); expect(f.call({ action: "seed-chunk", seedId, path: "memory/data", offset: 0, base64: "" })).toEqual({ error: "conflict" }); expect(f.call({ action: "seed-commit", seedId })).toEqual({ seeded: true }); expect(readFileSync(join(f.root, "memory", "data"))).toEqual(Buffer.concat([chunk, chunk])); - expect(readdirSync(f.temp)).toEqual(["home"]); + expect(readdirSync(f.temp)).toEqual([".paperclip-seed-home.lock", "home"]); expect(f.call({ action: "seed-begin", seedId: randomUUID() })).toEqual({ started: false }); const g = fixture(); const partial = randomUUID(); g.call({ action: "seed-begin", seedId: partial }); @@ -194,7 +194,7 @@ describe("confined computer files", () => { expect(g.call({ action: "seed-chunk", seedId: partial, path: "large", offset: 0, base64: Buffer.alloc(1024 * 1024 + 1).toString("base64") })).toEqual({ error: "invalid" }); expect(g.call({ action: "seed-abort", seedId: partial })).toEqual({}); expect(existsSync(g.root)).toBe(false); - expect(readdirSync(g.temp)).toEqual([]); + expect(readdirSync(g.temp)).toEqual([".paperclip-seed-home.lock"]); }); it("does not replace a home created while its initial upload was in progress", () => { const f = fixture(); const seedId = randomUUID(); @@ -203,7 +203,49 @@ describe("confined computer files", () => { mkdirSync(f.root); expect(f.call({ action: "seed-commit", seedId })).toEqual({ seeded: false }); expect(readdirSync(f.root)).toEqual([]); - expect(readdirSync(f.temp)).toEqual(["home"]); + expect(readdirSync(f.temp)).toEqual([".paperclip-seed-home.lock", "home"]); + }); + it("reclaims only the expired receipted upload after an interrupted seed", () => { + const f = fixture(); const first = randomUUID(); const next = randomUUID(); + const receiptPath = join(f.temp, ".paperclip-seed-home.json"); + const oldStage = join(f.temp, `.paperclip-seed-home-${first}`); + const unrelated = join(f.temp, `.paperclip-seed-home-${randomUUID()}`); + mkdirSync(unrelated); writeFileSync(join(unrelated, "user-file"), "keep"); + expect(f.call({ action: "seed-begin", seedId: first })).toEqual({ started: true }); + expect(f.call({ action: "seed-chunk", seedId: first, path: "partial", offset: 0, base64: Buffer.alloc(1024 * 1024).toString("base64") })).toEqual({}); + expect(f.call({ action: "seed-begin", seedId: next })).toEqual({ error: "conflict" }); + const receipt = JSON.parse(readFileSync(receiptPath, "utf8")); + expect(receipt.seedId).toBe(first); expect(receipt.updatedAt).toBeGreaterThan(0); + writeFileSync(receiptPath, JSON.stringify({ ...receipt, updatedAt: Date.now() / 1000 - 180 })); + expect(f.call({ action: "seed-begin", seedId: next })).toEqual({ error: "conflict" }); + writeFileSync(receiptPath, JSON.stringify({ ...receipt, updatedAt: 0 })); + expect(f.call({ action: "seed-begin", seedId: next })).toEqual({ started: true }); + expect(existsSync(oldStage)).toBe(false); + expect(f.call({ action: "seed-chunk", seedId: first, path: "late", offset: 0, base64: "" })).toEqual({ error: "conflict" }); + expect(readFileSync(join(unrelated, "user-file"), "utf8")).toBe("keep"); + expect(f.call({ action: "seed-abort", seedId: first })).toEqual({}); + expect(JSON.parse(readFileSync(receiptPath, "utf8")).seedId).toBe(next); + expect(f.call({ action: "seed-chunk", seedId: next, path: "complete", offset: 0, base64: Buffer.from("done").toString("base64") })).toEqual({}); + expect(f.call({ action: "seed-commit", seedId: next })).toEqual({ seeded: true }); + expect(readFileSync(join(f.root, "complete"), "utf8")).toBe("done"); + expect(existsSync(receiptPath)).toBe(false); + }); + it("cleans abandoned upload receipts on home admission but preserves unverified content", () => { + const f = fixture(); const seedId = randomUUID(); + const receiptPath = join(f.temp, ".paperclip-seed-home.json"); + const stage = join(f.temp, `.paperclip-seed-home-${seedId}`); + f.call({ action: "seed-begin", seedId }); + f.call({ action: "seed-chunk", seedId, path: "partial", offset: 0, base64: Buffer.from("partial").toString("base64") }); + mkdirSync(f.root); writeFileSync(join(f.root, "user-file"), "keep"); + const receipt = JSON.parse(readFileSync(receiptPath, "utf8")); + writeFileSync(receiptPath, JSON.stringify({ ...receipt, updatedAt: 0 })); + writeFileSync(join(stage, "owner.json"), JSON.stringify({ purpose: "user-owned" })); + expect(f.call({ action: "list", limit: 1 })).toEqual({ error: "invalid" }); + expect(readFileSync(join(stage, "tree", "partial"), "utf8")).toBe("partial"); + writeFileSync(join(stage, "owner.json"), JSON.stringify({ purpose: receipt.purpose, root: receipt.root, seedId })); + expect(f.call({ action: "list", limit: 1 }).entries[0].name).toBe("user-file"); + expect(existsSync(stage)).toBe(false); expect(existsSync(receiptPath)).toBe(false); + expect(readFileSync(join(f.root, "user-file"), "utf8")).toBe("keep"); }); it("hashes and deletes files over the read limit while fencing changed bytes", () => { const f = fixture(); @@ -532,3 +574,29 @@ describe("Boat SSH admission", () => { expect(runner.execute).toHaveBeenCalledTimes(12); }); }); + + +describe("remote graceful retirement fence", () => { + it("records the exact generation deadline and blocks late launch or generation reuse", () => { + const root = realpathSync(mkdtempSync(join(tmpdir(), "computer-grace-"))); + roots.push(root); + const owners = join(root, "owners"); + const boot = join(root, "boot"); + writeFileSync(boot, "boot-id"); + const code = processProgram.replaceAll("/home/user/.paperclip-owners", owners) + .replaceAll("/proc/sys/kernel/random/boot_id", boot); + const invoke = (action: string, owner: Record) => { + const result = spawnSync("python3", ["-c", code], { input: JSON.stringify({ action, owner }), encoding: "utf8" }); + expect(result.status, result.stderr).toBe(0); + return JSON.parse(result.stdout); + }; + const owner = { id: "owned", generation: 7, phase: "retiring", retirementDeadline: "2099-01-01T00:00:00Z" }; + expect(invoke("advance", owner)).toEqual({}); + const marker = readFileSync(join(owners, "owned", "retiring.json"), "utf8"); + expect(JSON.parse(marker).deadline).toBe(Date.parse(owner.retirementDeadline)); + expect(invoke("launch", owner)).toEqual({ error: "conflict" }); + expect(invoke("advance", { ...owner, phase: "active", generation: 8 })).toEqual({ error: "conflict" }); + expect(invoke("advance", { ...owner, generation: 6 })).toEqual({ error: "conflict" }); + expect(readFileSync(join(owners, "owned", "retiring.json"), "utf8")).toBe(marker); + }); +}); diff --git a/server/src/modules/computers/adapters/boat.ts b/server/src/modules/computers/adapters/boat.ts index bf35376117d..9944f1d222b 100644 --- a/server/src/modules/computers/adapters/boat.ts +++ b/server/src/modules/computers/adapters/boat.ts @@ -112,7 +112,7 @@ with os.fdopen(fd,'a') as lock: `; export const processProgram = String.raw` -import os,sys,json,fcntl,subprocess,shutil,re +import os,sys,json,fcntl,subprocess,shutil,re,datetime p=json.load(sys.stdin);base='/home/user/.paperclip-owners';os.makedirs(base,exist_ok=True) def retire_owner(root,oid): open(os.path.join(root,'retired'),'a').close() @@ -151,6 +151,11 @@ with open(os.path.join(root,'lock'),'a') as lock: if owner['generation']1024*1024 or type(offset)!=int or offset<0 or offset+len(data)>256*1024*1024:fail('invalid') - destfd=directory(['tree']+parts[:-1],create=True,start=stagefd) - try:fd=os.open(parts[-1],os.O_WRONLY|os.O_CREAT|os.O_NOFOLLOW,0o600,dir_fd=destfd) - finally:os.close(destfd) - with os.fdopen(fd,'r+b') as f: + parentfd=directory(os.path.dirname(root).split('/'),create=act in seed_actions) + name=os.path.basename(root);receipt_name='.paperclip-seed-'+name+'.json' + leasefd=os.open('.paperclip-seed-'+name+'.lock',os.O_CREAT|os.O_RDWR|os.O_NOFOLLOW,0o600,dir_fd=parentfd) + info=os.fstat(leasefd) + if not stat.S_ISREG(info.st_mode) or info.st_nlink!=1:fail('invalid') + fcntl.flock(leasefd,fcntl.LOCK_EX) + def read_metadata(directory_fd,name): + fd=os.open(name,os.O_RDONLY|os.O_NOFOLLOW,dir_fd=directory_fd) + with os.fdopen(fd,'rb') as f: info=os.fstat(f.fileno()) - if not stat.S_ISREG(info.st_mode) or info.st_nlink!=1:fail('invalid') - if info.st_size!=offset:fail('conflict') - f.seek(offset);f.write(data) - print('{}') - else: - libc=ctypes.CDLL(None,use_errno=True) - if hasattr(libc,'renameat2'):status=libc.renameat2(stagefd,b'tree',parentfd,os.fsencode(name),1) - elif hasattr(libc,'renameatx_np'):status=libc.renameatx_np(stagefd,b'tree',parentfd,os.fsencode(name),4) - else:fail('invalid') - if status!=0: - code=ctypes.get_errno() - if code not in (errno.EEXIST,errno.ENOTEMPTY):raise OSError(code,os.strerror(code)) - if not stat.S_ISDIR(os.stat(name,dir_fd=parentfd,follow_symlinks=False).st_mode):fail('invalid') - print(json.dumps({'seeded':status==0})) + if not stat.S_ISREG(info.st_mode) or info.st_nlink!=1 or info.st_size>4096:fail('invalid') + return json.loads(f.read(4097)) + def save_receipt(value): + if value is None: + try:os.unlink(receipt_name,dir_fd=parentfd) + except FileNotFoundError:pass + else: + temporary=receipt_name+'.tmp' + fd=os.open(temporary,os.O_CREAT|os.O_WRONLY|os.O_NOFOLLOW,0o600,dir_fd=parentfd) + with os.fdopen(fd,'wb') as f: + info=os.fstat(f.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_nlink!=1:fail('invalid') + f.truncate(0);f.write(json.dumps(value).encode());f.flush();os.fsync(f.fileno()) + os.rename(temporary,receipt_name,src_dir_fd=parentfd,dst_dir_fd=parentfd) + os.fsync(parentfd) + def identity(token):return {'purpose':'paperclip-initial-home-v1','root':root,'seedId':token} + def remove_receipted_upload(receipt): + staging='.paperclip-seed-'+name+'-'+receipt['seedId'] + try:fd=os.open(staging,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=parentfd) + except FileNotFoundError:return + try: + try:marker=read_metadata(fd,'owner.json') + except FileNotFoundError: + # Receipt is durable before mkdir. An interrupted begin can only leave + # an empty directory here; never recursively remove unmarked content. + os.rmdir(staging,dir_fd=parentfd);return + if marker!=identity(receipt['seedId']):fail('invalid') + finally:os.close(fd) + shutil.rmtree(staging,dir_fd=parentfd) + try:receipt=read_metadata(parentfd,receipt_name) + except FileNotFoundError:receipt=None + if receipt is not None: + if not isinstance(receipt,dict) or receipt.get('purpose')!='paperclip-initial-home-v1' or receipt.get('root')!=root:fail('invalid') + if str(uuid.UUID(receipt.get('seedId','')))!=receipt['seedId']:fail('invalid') + updated=receipt.get('updatedAt') + if not isinstance(updated,(int,float)) or not math.isfinite(updated):fail('invalid') + # Exceeds the 120s queued+executing backend deadline, with restart margin. + if time.time()-updated>300: + remove_receipted_upload(receipt);save_receipt(None);receipt=None + if act in seed_actions: + token=p.get('seedId','') + if str(uuid.UUID(token))!=token:fail('invalid') + staging='.paperclip-seed-'+name+'-'+token + if act=='seed-begin': + try: + existing=os.stat(name,dir_fd=parentfd,follow_symlinks=False) + if not stat.S_ISDIR(existing.st_mode):fail('invalid') + print(json.dumps({'started':False}));sys.exit(0) + except FileNotFoundError:pass + if receipt is not None:fail('conflict') + # Reserve only an absent random path before persisting its exact identity. + try:os.stat(staging,dir_fd=parentfd,follow_symlinks=False);fail('conflict') + except FileNotFoundError:pass + receipt={**identity(token),'updatedAt':time.time()};save_receipt(receipt) + os.mkdir(staging,0o700,dir_fd=parentfd) + stagefd=os.open(staging,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=parentfd) + markerfd=os.open('owner.json',os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600,dir_fd=stagefd) + with os.fdopen(markerfd,'wb') as f:f.write(json.dumps(identity(token)).encode());f.flush();os.fsync(f.fileno()) + os.mkdir('tree',0o700,dir_fd=stagefd) + print(json.dumps({'started':True})) + elif act=='seed-abort': + if receipt is not None and receipt['seedId']==token: + remove_receipted_upload(receipt);save_receipt(None) + print('{}') + else: + if receipt is None or receipt['seedId']!=token:fail('conflict') + stagefd=os.open(staging,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=parentfd) + if read_metadata(stagefd,'owner.json')!=identity(token):fail('invalid') + if act=='seed-chunk': + relative=p.get('path','');safe(relative) + parts=[part for part in relative.split('/') if part not in ('','.')] + if not parts:fail('invalid') + data=base64.b64decode(p['base64'],validate=True);offset=p.get('offset') + if len(data)>1024*1024 or type(offset)!=int or offset<0 or offset+len(data)>256*1024*1024:fail('invalid') + destfd=directory(['tree']+parts[:-1],create=True,start=stagefd) + try:fd=os.open(parts[-1],os.O_WRONLY|os.O_CREAT|os.O_NOFOLLOW,0o600,dir_fd=destfd) + finally:os.close(destfd) + with os.fdopen(fd,'r+b') as f: + info=os.fstat(f.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_nlink!=1:fail('invalid') + if info.st_size!=offset:fail('conflict') + f.seek(offset);f.write(data) + receipt['updatedAt']=time.time();save_receipt(receipt) + print('{}') + else: + libc=ctypes.CDLL(None,use_errno=True) + if hasattr(libc,'renameat2'):status=libc.renameat2(stagefd,b'tree',parentfd,os.fsencode(name),1) + elif hasattr(libc,'renameatx_np'):status=libc.renameatx_np(stagefd,b'tree',parentfd,os.fsencode(name),4) + else:fail('invalid') + if status!=0: + code=ctypes.get_errno() + if code not in (errno.EEXIST,errno.ENOTEMPTY):raise OSError(code,os.strerror(code)) + if not stat.S_ISDIR(os.stat(name,dir_fd=parentfd,follow_symlinks=False).st_mode):fail('invalid') + remove_receipted_upload(receipt);save_receipt(None) + print(json.dumps({'seeded':status==0})) except FileNotFoundError:fail('not_found') - except (OSError,ValueError):fail('invalid') + except (OSError,ValueError,TypeError,AttributeError):fail('invalid') finally: - if lockfd is not None:os.close(lockfd) if stagefd is not None:os.close(stagefd) - if act=='seed-commit': - try:shutil.rmtree(staging,dir_fd=parentfd) - except FileNotFoundError:pass - os.close(parentfd) - sys.exit(0) + if leasefd is not None:os.close(leasefd) + if parentfd is not None:os.close(parentfd) + if act in seed_actions:sys.exit(0) try:rootfd=directory(root.split('/')) except FileNotFoundError:fail('not_found') except OSError:fail('invalid') diff --git a/server/src/modules/computers/application/service.test.ts b/server/src/modules/computers/application/service.test.ts index 3a908f9fdcd..1de6b30a7dd 100644 --- a/server/src/modules/computers/application/service.test.ts +++ b/server/src/modules/computers/application/service.test.ts @@ -327,10 +327,11 @@ describe("computer ownership", () => { expect(f.backend.stop).toHaveBeenCalledOnce(); }, ); - it("preserves recoverable running owners and gives completed warm owners their idle interval", async () => { + it("fences warm work at its deadline and bounds crashed-controller shutdown grace", async () => { const f = fixture(); await f.attach(); const binding = await f.admit(); + await binding.launch({ command: "runner" }); f.advance(180_000); await f.service.reconcile(); expect(f.backend.retire).not.toHaveBeenCalled(); @@ -343,6 +344,13 @@ describe("computer ownership", () => { await f.service.reconcile(); expect(f.backend.retire).not.toHaveBeenCalled(); f.advance(60_001); + await expect(f.admit()).rejects.toMatchObject({ code: "conflict" }); + await expect(binding.runner.execute({ command: "new work" })).rejects.toMatchObject({ code: "conflict" }); + await binding.process.runner.execute({ command: "close provider" }); + await f.service.reconcile(); + expect(f.backend.retire).not.toHaveBeenCalled(); + f.advance(30_000); + await expect(binding.process.ingress()).rejects.toMatchObject({ code: "conflict" }); await f.service.reconcile(); expect(f.backend.retire).toHaveBeenCalledOnce(); }); @@ -698,3 +706,107 @@ describe("computer retirement proof", () => { expect(f.backend.inspect).not.toHaveBeenCalled(); }); }); + + +describe("computer graceful retirement", () => { + it("fences admission and ordinary execution while allowing the exact pinned process to close", async () => { + const f = fixture(); + await f.attach(); + const binding = await f.admit(); + await binding.launch({ command: "runner" }); + let finish!: () => void; + let entered!: () => void; + const closing = new Promise((resolve) => { finish = resolve; }); + const started = new Promise((resolve) => { entered = resolve; }); + const beforeStop = vi.fn(async () => { entered(); await closing; }); + const retiring = f.service.retire({ ...f.scope, owner: binding.owner, beforeStop }); + await started; + expect((await f.repository.get(f.scope)).ledger.owners[0]).toMatchObject({ phase: "retiring" }); + await expect(f.admit()).rejects.toMatchObject({ code: "conflict" }); + await expect(binding.runner.execute({ command: "forbidden" })).rejects.toMatchObject({ code: "conflict" }); + await expect(binding.launch({ command: "forbidden" })).rejects.toMatchObject({ code: "conflict" }); + await binding.process.runner.execute({ command: "close" }); + await binding.process.ingress(); + expect(f.backend.retire).not.toHaveBeenCalled(); + const repeated = f.service.retire({ ...f.scope, owner: binding.owner, beforeStop }); + finish(); + expect(await retiring).toEqual({ retired: true }); + expect(await repeated).toEqual({ retired: true }); + expect(beforeStop).toHaveBeenCalledOnce(); + expect(f.backend.retire).toHaveBeenCalledOnce(); + await expect(binding.process.ingress()).rejects.toMatchObject({ code: "conflict" }); + expect((await f.admit()).owner.ownerId).not.toBe(binding.owner.ownerId); + }); + it("never invokes a stale generation callback and always stops after callback failure", async () => { + const f = fixture(); + await f.attach(); + const old = await f.admit(); + await old.launch({ command: "runner" }); + await f.service.retainWarm({ ...f.scope, owner: old.owner, idleTimeoutMs: 60_000 }); + const current = await f.admit(); + const stale = vi.fn(async () => {}); + expect(await f.service.retire({ ...f.scope, owner: old.owner, beforeStop: stale })).toEqual({ retired: false }); + expect(stale).not.toHaveBeenCalled(); + expect(await f.service.retire({ ...f.scope, owner: current.owner, beforeStop: async () => { throw new Error("provider close failed"); } })).toEqual({ retired: true }); + expect(f.backend.retire).toHaveBeenCalledOnce(); + }); + it("bounds a stalled graceful close and denies late process control", async () => { + vi.useFakeTimers(); + try { + const f = fixture(); + await f.attach(); + const binding = await f.admit(); + await binding.launch({ command: "runner" }); + let entered!: () => void; + const started = new Promise((resolve) => { entered = resolve; }); + const retiring = f.service.retire({ ...f.scope, owner: binding.owner, beforeStop: async () => { + entered(); await new Promise(() => {}); + } }); + await started; + f.advance(30_001); + await expect(binding.process.runner.execute({ command: "late" })).rejects.toMatchObject({ code: "conflict" }); + await vi.advanceTimersByTimeAsync(30_000); + expect(await retiring).toEqual({ retired: true }); + expect(f.backend.retire).toHaveBeenCalledOnce(); + } finally { vi.useRealTimers(); } + }); + it("does not extend the original warm shutdown deadline when retirement starts late", async () => { + vi.useFakeTimers(); + try { + const f = fixture(); + await f.attach(); + const binding = await f.admit(); + await binding.launch({ command: "runner" }); + await f.service.retainWarm({ ...f.scope, owner: binding.owner, idleTimeoutMs: 60_000 }); + f.advance(80_000); + let entered!: () => void; + const started = new Promise((resolve) => { entered = resolve; }); + const retiring = f.service.retire({ ...f.scope, owner: binding.owner, beforeStop: async () => { + entered(); await new Promise(() => {}); + } }); + await started; + expect((await f.repository.get(f.scope)).ledger.owners[0]!.retirementDeadline).toBe("2026-10-10T12:01:30.000Z"); + f.advance(10_000); + await vi.advanceTimersByTimeAsync(10_000); + expect(await retiring).toEqual({ retired: true }); + expect(f.backend.retire).toHaveBeenCalledOnce(); + } finally { vi.useRealTimers(); } + }); + it("reconciles a crashed controller reservation only after its durable deadline", async () => { + const f = fixture(); + await f.attach(); + const binding = await f.admit(); + await binding.launch({ command: "runner" }); + await f.repository.update(f.scope, (record) => { + record.ledger.owners[0]!.phase = "retiring"; + record.ledger.owners[0]!.retirementDeadline = "2026-10-10T12:00:30.000Z"; + }); + await f.service.reconcile(); + expect(f.backend.retire).not.toHaveBeenCalled(); + await expect(f.service.retire({ ...f.scope, owner: binding.owner })).rejects.toMatchObject({ code: "conflict" }); + f.advance(30_001); + await f.service.reconcile(); + expect(f.backend.retire).toHaveBeenCalledOnce(); + expect((await f.repository.get(f.scope)).ledger.owners[0]!.phase).toBe("retired"); + }); +}); diff --git a/server/src/modules/computers/application/service.ts b/server/src/modules/computers/application/service.ts index 3fb06c0a1c1..5ad160d8370 100644 --- a/server/src/modules/computers/application/service.ts +++ b/server/src/modules/computers/application/service.ts @@ -23,6 +23,8 @@ class ComputerSessionBusyError extends ComputerError { } } +// This is shutdown time only; admission and ordinary work stop at the warm deadline. +const RETIREMENT_GRACE_MS = 30_000; type Scope = { companyId: string; environmentId: string }; export function createComputerService( repository: ComputerRepository, @@ -38,6 +40,15 @@ export function createComputerService( ownerId: owner.id, generation: owner.generation, }); + const retirements = new Map>(); + const retirementGraceOpen = (owner: Owner) => owner.phase === "retiring" && + !!owner.retirementDeadline && Date.parse(owner.retirementDeadline) > now().getTime(); + const warmShutdownGraceOpen = (owner: Owner) => owner.kind === "runner" && owner.phase === "warm" && + !!owner.deadline && Date.parse(owner.deadline) + RETIREMENT_GRACE_MS > now().getTime(); + const processControlAllowed = (owner: Owner) => + ((owner.phase === "active" || owner.phase === "starting") && !expired(owner, now())) || + (owner.phase === "warm" && (!expired(owner, now()) || warmShutdownGraceOpen(owner))) || + retirementGraceOpen(owner); const base = (record: ComputerRecord) => `/home/user/paperclip/${segment(record.companyId)}`; async function admitRecord( @@ -173,14 +184,19 @@ export function createComputerService( const control = await backend.runner(record, { control: true }); let pinnedProcess = owner.process ? structuredClone(owner.process) : null; async function processScope() { - if (!pinnedProcess) return scoped({ ...record, owner: ownerRef }); + if (!pinnedProcess) { + const current = await scoped({ ...record, owner: ownerRef }); + if (!["active", "starting", "warm"].includes(current.owner.phase) || expired(current.owner, now())) + throw new ComputerError("conflict", "Computer process capability has expired"); + return current; + } const latest = await repository.get(record); const candidate = latest.ledger.owners.find( (value) => value.id === owner.id, ); if ( !candidate?.process || - !["active", "starting", "warm"].includes(candidate.phase) || + !processControlAllowed(candidate) || candidate.process.nonce !== pinnedProcess.nonce || candidate.process.unitName !== pinnedProcess.unitName || candidate.process.bootId !== pinnedProcess.bootId || @@ -200,7 +216,8 @@ export function createComputerService( const current = await (processScoped ? processScope() : scoped({ ...record, owner: ownerRef })); - if (!["active", "starting", "warm"].includes(current.owner.phase)) + if ((!["active", "starting", "warm"].includes(current.owner.phase) || expired(current.owner, now())) && + !(processScoped && pinnedProcess && processControlAllowed(current.owner))) throw new ComputerError("conflict", "Computer owner is retired"); // Start a command unit under the same owner slice while holding the remote tombstone lock. // The lock is released only after systemd knows the unit, so retirement cannot miss a delayed launch. @@ -235,6 +252,9 @@ try: with open(root+'/lock','a') as lock: fcntl.flock(lock,fcntl.LOCK_EX) if os.path.exists(root+'/retired'):raise RuntimeError('computer owner retired') + if os.path.exists(root+'/retiring.json'): + with open(root+'/retiring.json') as retirement:deadline=json.load(retirement)['deadline'] + if not p.get('processClaim') or time.time()*1000>=deadline:raise RuntimeError('computer owner is retiring') if p.get('processClaim'): claim=json.load(open(root+'/claim.json')) if any(claim[k]!=p['processClaim'][k] for k in ['nonce','unitName','bootId','launchGeneration']) or claim['bootId']!=open('/proc/sys/kernel/random/boot_id').read().strip():raise RuntimeError('computer process superseded') @@ -347,7 +367,7 @@ finally: }, async ingress(input?: { port?: number; path?: string }) { const current = await scoped({ ...record, owner: ownerRef }); - if (current.owner.phase === "retired") + if (!["active", "starting", "warm"].includes(current.owner.phase) || expired(current.owner, now())) throw new ComputerError("conflict", "Computer owner retired"); return backend.ingress( current.record, @@ -389,10 +409,7 @@ finally: if (owner && owner.phase !== "warm") throw new ComputerSessionBusyError(owner.runId, owner.agentId); if (owner && expired(owner, now())) - throw new ComputerError( - "conflict", - "Computer warm session is retiring", - ); + throw new ComputerSessionBusyError(owner.runId, owner.agentId); if (owner) { owner.generation++; owner.phase = "starting"; @@ -504,19 +521,53 @@ finally: owner.runId === input.runId, ); } - async function retire(input: Scope & { owner: OwnerRef }) { + async function retire(input: Scope & { owner: OwnerRef; beforeStop?: () => Promise }) { + const key = `${input.companyId}:${input.environmentId}:${input.owner.computerId}:${input.owner.ownerId}:${input.owner.generation}`; + const existing = retirements.get(key); + if (existing) return existing; + const pending = performRetirement(input); + retirements.set(key, pending); + try { return await pending; } + finally { if (retirements.get(key) === pending) retirements.delete(key); } + } + async function performRetirement(input: Scope & { owner: OwnerRef; beforeStop?: () => Promise }) { const state = await repository.update(input, (record) => { - const owner = record.ledger.owners.find( - (value) => value.id === input.owner.ownerId, - ); + const owner = record.ledger.owners.find((value) => value.id === input.owner.ownerId); if (record.id !== input.owner.computerId || !owner) throw new ComputerError("not_found", "Computer owner not found"); if (owner.generation !== input.owner.generation) return null; - if (owner.phase !== "retired") owner.phase = "retiring"; - return { record: structuredClone(record), owner: structuredClone(owner) }; + if (retirementGraceOpen(owner)) + throw new ComputerError("conflict", "Computer graceful retirement is pending"); + const retirementDeadline = owner.phase === "warm" && owner.deadline + ? Math.min(now().getTime() + RETIREMENT_GRACE_MS, Date.parse(owner.deadline) + RETIREMENT_GRACE_MS) + : now().getTime() + RETIREMENT_GRACE_MS; + const graceful = owner.phase !== "retiring" && owner.phase !== "retired" && + owner.kind === "runner" && !!owner.process && !!input.beforeStop && retirementDeadline > now().getTime(); + if (owner.phase !== "retired") { + owner.phase = "retiring"; + owner.retirementDeadline = graceful ? new Date(retirementDeadline).toISOString() : null; + } + return { record: structuredClone(record), owner: structuredClone(owner), graceful }; }); if (!state) return { retired: false }; if (state.owner.phase === "retired") return { retired: true }; + if (state.graceful) { + let timer: ReturnType | undefined; + try { + await Promise.race([ + (async () => { + await backend.advance(state.record, state.owner); + if (retirementGraceOpen(state.owner)) await input.beforeStop!(); + })(), + new Promise((resolve) => { timer = setTimeout(resolve, Math.max(0, Date.parse(state.owner.retirementDeadline!) - now().getTime())); }), + ]); + } catch { + // Graceful provider shutdown is best effort; physical retirement is mandatory. + } finally { if (timer) clearTimeout(timer); } + await repository.update(input, (record) => { + exactOwner(record, input.owner).retirementDeadline = null; + }); + } if (state.owner.kind === "runner") { const status = await backend.inspect(state.record); if (!["stopped", "archived"].includes(status.state)) @@ -526,6 +577,7 @@ finally: const owner = exactOwner(record, input.owner); owner.phase = "retired"; owner.deadline = null; + owner.retirementDeadline = null; }); return { retired: true }; } @@ -885,7 +937,8 @@ finally: } record = await repository.get(record); for (const owner of liveOwners(record.ledger)) - if (owner.phase === "retiring" || expired(owner, now())) + if (owner.phase === "retiring" ? !retirementGraceOpen(owner) + : expired(owner, now()) && !warmShutdownGraceOpen(owner)) await retire({ ...record, owner: ref(record, owner) }); await repository.update(record, (current) => { current.ledger.owners = current.ledger.owners.filter( diff --git a/server/src/modules/computers/domain/ledger.ts b/server/src/modules/computers/domain/ledger.ts index 136e0c444a6..c433e576b81 100644 --- a/server/src/modules/computers/domain/ledger.ts +++ b/server/src/modules/computers/domain/ledger.ts @@ -23,6 +23,8 @@ export interface Owner { port: number; deadline: string | null; absoluteDeadline: string | null; + /** Bounded graceful shutdown reservation; only pinned process control remains valid. */ + retirementDeadline?: string | null; process: ProcessClaim | null; } export interface Ledger { diff --git a/server/src/services/computer-environment-driver.ts b/server/src/services/computer-environment-driver.ts index fd1e0ef8dcd..505c2885ca7 100644 --- a/server/src/services/computer-environment-driver.ts +++ b/server/src/services/computer-environment-driver.ts @@ -121,8 +121,8 @@ export async function computerExecutionTarget(db: Db, lease: EnvironmentLease, i workspaceRealization: { mode: "in_place", authoritativeRoot: binding.remoteCwd, pathAliases: [], outboundRestorePaths: [] }, launch: binding.launch, inspectProcess: binding.inspectProcess, retainWarm: (idleTimeoutMs) => computers.retainWarm({ ...scope, owner, idleTimeoutMs }), - retire: async () => { - const result = await computers.retire({ ...scope, owner }); + retire: async (options) => { + const result = await computers.retire({ ...scope, owner, beforeStop: options?.beforeStop }); if (result.retired) await environmentService(db).releaseLease(lease.id, "released", { cleanupStatus: "success", remoteExecutionTermination: remoteTerminationReceipt(lease, { providerLeaseId: lease.providerLeaseId, state: "stopped" }) }); return result.retired; diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index 272976eb92d..d40cf055daa 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -1,4 +1,4 @@ -import { nativeSessionBootstrapTimeoutMs } from "./native-session-executor.js"; +import { compareAndSealRetiredComputerCheckpoint, retiredComputerCheckpointIsSettled, retireUnlaunchedComputerAttempt, nativeSessionBootstrapTimeoutMs } from "./native-session-executor.js"; import { prepareHeartbeatGitHubLaunchers } from "../heartbeat-github-launchers.js"; import { gunzipSync } from "node:zlib"; import { configuredEnvironmentProjection } from "../../vendor/paperclip-runner/index.js"; @@ -7698,7 +7698,7 @@ describe("native warm session supervision", () => { const name = `computer-owner-${suffix}`; const current = { ...execution, binding: { ...execution.binding, runId: name, agentId: name, executionWorkspaceId: name }, session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 60_000 } } } as NativeExecutionInputV1; - const close = vi.fn(async () => undefined), retainWarm = vi.fn(async () => undefined), retire = vi.fn(async () => true); + const close = vi.fn(async () => undefined), retainWarm = vi.fn(async () => undefined), retire = vi.fn(async (options?: { beforeStop?: () => Promise }) => { await options?.beforeStop?.(); return true; }); const target = { kind: "remote" as const, transport: "computer" as const, environmentId: "shared-computer", remoteCwd: `/home/user/${name}`, listenerPort: suffix === "a" ? 45001 : 45002, resourceAuthority: { kind: "computer-owner", computerId: "computer", ownerId: name, generation: 1 }, @@ -7731,7 +7731,7 @@ describe("native warm session supervision", () => { const current = { ...execution, binding: { ...execution.binding, runId: `${name}-one`, agentId: name, executionWorkspaceId: name }, session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 60_000 } } } as NativeExecutionInputV1; const firstClose = vi.fn(async () => undefined), secondClose = vi.fn(async () => undefined); - const firstRetire = vi.fn(async () => true), secondRetire = vi.fn(async () => true); + const firstRetire = vi.fn(async (options?: { beforeStop?: () => Promise }) => { await options?.beforeStop?.(); return true; }), secondRetire = vi.fn(async (options?: { beforeStop?: () => Promise }) => { await options?.beforeStop?.(); return true; }); const target = { kind: "remote", transport: "computer", environmentId: name, remoteCwd: `/home/user/${name}`, resourceAuthority: { kind: "computer-owner", computerId: name, ownerId: "prior-owner", generation: 1 }, retainWarm: vi.fn(async () => undefined), retire: firstRetire }; @@ -7768,7 +7768,7 @@ describe("native warm session supervision", () => { const detachControllerForRestart = vi.fn(async () => undefined); const session = { close, detachControllerForRestart }; let generation = 1; - const retire = vi.fn(async () => generation === 1); + const retire = vi.fn(async (options?: { beforeStop?: () => Promise }) => { if (generation !== 1) return false; await options?.beforeStop?.(); return true; }); const target = { kind: "remote", transport: "computer", environmentId: name, remoteCwd: `/home/user/${name}`, resourceAuthority: { kind: "computer-owner", computerId: name, ownerId: name, generation: 1 }, retainWarm: vi.fn(async () => undefined), retire }; @@ -7796,14 +7796,14 @@ describe("native warm session supervision", () => { expect(close).not.toHaveBeenCalled(); expect(detachControllerForRestart).not.toHaveBeenCalled(); const next = { ...current, binding: { ...current.binding, runId: `${name}-two` } }; - const nextRetire = vi.fn(async () => true); + const nextRetire = vi.fn(async (options?: { beforeStop?: () => Promise }) => { await options?.beforeStop?.(); return true; }); await executePaperclipNativeSession({ db: leaseDb(next), execution: next, runnerInstanceId: name, runnerEnvironment: await environmentForRun(next.binding.runId), runnerExecutionTarget: { ...target, resourceAuthority: { ...target.resourceAuthority, generation: 2 }, retire: nextRetire } as never }); await closeWarmNativeSessionsForRun({ runId: next.binding.runId, reason: "fixture cleanup" }); expect(nextRetire).toHaveBeenCalledOnce(); - expect(detachControllerForRestart).toHaveBeenCalledOnce(); - expect(close).not.toHaveBeenCalled(); + expect(detachControllerForRestart).not.toHaveBeenCalled(); + expect(close).toHaveBeenCalledOnce(); } finally { vi.useRealTimers(); } }); @@ -13512,6 +13512,49 @@ describe("runnerd provider runtime wiring", () => { } finally { await rm(root, { recursive: true, force: true }); } }); + it("keeps computer checkpoints remote through close and the next session preparation", async () => { + const remoteRoot = "/remote/persistent-agent"; + const runnerId = "persistent-computer-runner"; + const runnerState = { schema: "paperclip.runner.durable.state.v1", lifecycle: "suspended", runnerInstanceId: runnerId, + normalizedSessionId: execution.session.normalizedSessionId, runId: execution.binding.runId }; + const providerState = { schema: "paperclip.runner.codex-provider-state.v1", lifecycle: "session_open", threadId: "durable-thread", + activeProviderTurnId: null, config: { provider: "codex", driver: "codex_app_server" } }; + const syncOut = vi.fn(async () => { throw new Error("persistent checkpoint must not copy back"); }); + const syncIn = vi.fn(async () => { throw new Error("persistent checkpoint must not restore host history"); }); + const remoteExecute = vi.fn(async (command: { command: string; args?: string[] }) => { + const script = command.args?.[1] ?? ""; + let stdout = ""; + if (command.args?.[0] === "--build-metadata") stdout = JSON.stringify({ + schema: "paperclip-runner/runnerd-build-metadata/v1", binaryName: "paperclip-runnerd", packageName: "@paperclipai/paperclip-runner", + binaryContractVersion: 2, durableSessionCapabilities: ["unlimited_runtime", "connection_lease_renewal"], prpTransportModes: ["listen_ws"], + }); + else if (command.args?.[0] === "--version") stdout = "codex-cli 0.160.0"; + else if (script.includes("command -v paperclip-runnerd")) stdout = "/usr/bin/paperclip-runnerd\n"; + else if (script.includes("command -v codex")) stdout = "/usr/bin/codex\n"; + else if (script.includes("base64 <")) stdout = Buffer.from(JSON.stringify(script.endsWith("codex-provider-state.json'") ? providerState : runnerState)).toString("base64"); + if (script.includes("tar ")) throw new Error("persistent checkpoint must not archive"); + return { exitCode: 0, timedOut: false, signal: null, stdout, stderr: "" }; + }); + const target = { kind: "remote", transport: "computer", environmentId: "environment", leaseId: "lease", providerKey: "boat", + remoteCwd: remoteRoot, listenerPort: 43127, effectiveCapabilities: { runnerWebSocketIngress: true }, + fileAuthority: { kind: "remote-persistent", root: remoteRoot, agentHome: remoteRoot, placementId: "placement" }, + runner: { execute: remoteExecute, syncIn, syncOut }, processRunner: { execute: remoteExecute, syncIn, syncOut }, + getRunnerIngressEndpoint: async () => ({ url: "wss://example.test/runner", close: async () => undefined }) }; + await createRunnerdBackend({ db: leaseDb(execution), execution, runnerInstanceId: runnerId, + runnerIngressAuthorized: true, runnerExecutionTarget: target as never }); + state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!(); + const transport = state.createTransport.mock.calls.at(-1)![0] as RunnerTransportOptions & { + controlPlaneRegistration: (authority: unknown) => Promise<{ checkpoint: (settlement: string) => Promise }>; + prepareExternalRunnerState: () => Promise; + }; + const registration = await transport.controlPlaneRegistration({}); + await expect(registration.checkpoint("settled")).resolves.toBeUndefined(); + expect(remoteExecute.mock.calls.some(([command]) => command.args?.[1]?.endsWith("codex-provider-state.json'"))).toBe(true); + await expect(transport.prepareExternalRunnerState()).resolves.toBeUndefined(); + expect(syncOut).not.toHaveBeenCalled(); expect(syncIn).not.toHaveBeenCalled(); + await expect(access(join(transport.stateDirectory!, "failover-backups", "current"))).rejects.toThrow(); + }); + it.each([ { override: undefined, expected: "@openai/codex@0.160.0" }, { override: "@openai/codex@0.159.0", expected: "@openai/codex@0.159.0" }, @@ -13792,3 +13835,145 @@ describe("computer provider-pack bootstrap policy", () => { expect(nativeSessionBootstrapTimeoutMs(provider, target)).toBe(expected); }); }); + +describe("computer idle authority transition", () => { + function settled() { + const identity = { runId: execution.binding.runId, normalizedSessionId: execution.session.normalizedSessionId!, + runnerInstanceId: "prior-runner", environmentLeaseId: "prior-lease", turnId: "turn", itemId: "item" }; + const current = { ...execution, binding: { ...execution.binding, runId: "next-run" } }; + const checkpoint = { driverKind: "codex_app_server", providerSessionId: "thread", activeTurnId: null, + pendingRuntimeRequests: [], identity: { ...execution.binding, sessionId: execution.session.normalizedSessionId } }; + return { identity, execution: current, priorExecution: execution, + runner: { schema: "paperclip.runner.durable.state.v1", ...identity, lifecycle: "ready", outbox: [], pendingTerminalDelivery: null }, + control: { identity, commands: [{ status: "completed" }], committedEvents: [{ eventType: "run.terminal", envelope: identity }] }, + provider: { schema: "paperclip.runner.codex-provider-state.v1", lifecycle: "session_open", threadId: "thread", + config: { provider: "codex", driver: "codex_app_server" }, activeProviderTurnId: null, completedTurnAuthoritative: true }, + checkpoint, currentCheckpoint: { ...checkpoint, identity: { ...checkpoint.identity, runId: current.binding.runId } } }; + } + + it("requires a terminal provider checkpoint with matching prior and successor scope", () => { + expect(retiredComputerCheckpointIsSettled(settled())).toBe(true); + }); + it.each(["pending-command", "pending-event", "unsettled-provider", "wrong-run", "wrong-thread", "active-turn", "config-change", "acpx"])( + "does not manufacture suspension from %s evidence", (condition) => { + const input = settled(); + if (condition === "pending-command") input.control.commands[0]!.status = "pending"; + if (condition === "pending-event") (input.runner.outbox as unknown[]).push({ event: "unacked" }); + if (condition === "unsettled-provider") input.provider.completedTurnAuthoritative = false; + if (condition === "wrong-run") input.currentCheckpoint.identity.runId = "foreign"; + if (condition === "wrong-thread") input.currentCheckpoint.providerSessionId = "foreign"; + if (condition === "active-turn") Object.assign(input.currentCheckpoint, { activeTurnId: "active" }); + if (condition === "config-change") input.execution = { ...input.execution, provider: { ...input.execution.provider, model: "changed" } }; + if (condition === "acpx") input.execution = { ...input.execution, provider: { ...input.execution.provider, kind: "acpx" } } as typeof input.execution; + expect(retiredComputerCheckpointIsSettled(input)).toBe(false); + }); + + it.each(["unchanged", "runner-changed", "provider-changed", "symlink", "interrupted"])( + "atomically seals only the unchanged remote bytes (%s)", async (condition) => { + const root = await mkdtemp(join(tmpdir(), "computer-retired-cas-")); + const runnerPath = join(root, "runner.json"), providerPath = join(root, "provider.json"); + const runnerBytes = Buffer.from(JSON.stringify(settled().runner)), providerBytes = Buffer.from(JSON.stringify(settled().provider)); + await writeFile(runnerPath, runnerBytes); await writeFile(providerPath, providerBytes); + const runner = { execute: async (command: { command: string; args?: string[] }) => { + if (condition === "runner-changed") await writeFile(runnerPath, JSON.stringify({ lifecycle: "active" })); + if (condition === "provider-changed") await writeFile(providerPath, JSON.stringify({ activeTurn: "new" })); + if (condition === "symlink") { await rm(runnerPath); await symlink(providerPath, runnerPath); } + if (condition === "interrupted") return { exitCode: null, signal: "SIGTERM", timedOut: true, stdout: "", stderr: "" }; + try { return { exitCode: 0, signal: null, timedOut: false, stderr: "", stdout: execFileSync(command.command, command.args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) }; } + catch { return { exitCode: 1, signal: null, timedOut: false, stdout: "", stderr: "CAS refused" }; } + } }; + try { + const action = compareAndSealRetiredComputerCheckpoint({ runner: runner as never, runnerPath, providerPath, runnerBytes, providerBytes }); + if (condition === "unchanged") { + await expect(action).resolves.toBeUndefined(); + expect(JSON.parse(await readFile(runnerPath, "utf8"))).toEqual({ ...settled().runner, lifecycle: "suspended" }); + } else { + await expect(action).rejects.toThrow("runner_remote_retirement_checkpoint_cas_failed"); + expect(JSON.parse(await readFile(runnerPath, "utf8")).lifecycle).not.toBe("suspended"); + } + expect((await readdir(root)).filter(name => name.startsWith(".retired-checkpoint-"))).toEqual([]); + } finally { await rm(root, { recursive: true, force: true }); } + }); + + it.each(["unlaunched", "launched", "claimed", "unknown", "superseded"])( + "permits same-run admission retry only after exact prelaunch retirement (%s)", async condition => { + let active = true; + const retire = vi.fn(async () => { if (condition === "superseded") return false; active = false; return true; }); + const inspectProcess = vi.fn(async () => { + if (condition === "unknown") throw new Error("inspection unavailable"); + return { running: false, claim: condition === "claimed" ? { nonce: "prior-process" } : null }; + }); + const target = { kind: "remote", transport: "computer", inspectProcess, retire } as never; + const action = retireUnlaunchedComputerAttempt(target, condition === "launched"); + if (["unknown", "superseded"].includes(condition)) await expect(action).rejects.toThrow(); + else await expect(action).resolves.toBeUndefined(); + const admitSameRun = () => { if (active) throw new Error("Computer session already has an active turn"); }; + if (condition === "unlaunched") expect(admitSameRun).not.toThrow(); + else expect(admitSameRun).toThrow("active turn"); + if (["launched", "claimed", "unknown"].includes(condition)) expect(retire).not.toHaveBeenCalled(); + }); +}); + +describe("computer graceful idle reservation", () => { + it.each(["codex", "acpx"])("suspends %s before retiring descendants and admits the next idle turn", async kind => { + const name = `graceful-idle-${kind}`; + const current = { ...execution, binding: { ...execution.binding, runId: `${name}-one`, agentId: name }, + provider: kind === "codex" ? execution.provider : { kind: "acpx", agent: "claude", model: null }, + session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm", idleTimeoutMs: 60_000 } } } as NativeExecutionInputV1; + let phase = "active"; + let checkpoint = "ready"; + const close = vi.fn(async () => { expect(phase).toBe("retiring"); checkpoint = "suspended"; }); + const target = { kind: "remote", transport: "computer", environmentId: name, remoteCwd: "/remote/agent", + resourceAuthority: { kind: "computer-owner", computerId: name, ownerId: name, generation: 1 }, + retainWarm: async () => { phase = "warm"; }, + retire: vi.fn(async (options?: { beforeStop?: () => Promise }) => { + phase = "retiring"; + await options?.beforeStop?.(); + expect(checkpoint).toBe("suspended"); + phase = "retired"; + return true; + }) }; + const result = { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" }, turnId: name, + normalizedSessionId: name, providerSessionId: name, driverKind: "test", driverVersion: "1", nativeEventCount: 1, + highestContiguousSourceSeq: 1, usage: null }; + state.execute.mockReset().mockImplementationOnce(async options => { await options.onSession?.({ close }); return result; }) + .mockImplementationOnce(async options => { expect(options.existingSession).toBeUndefined(); expect(checkpoint).toBe("suspended"); return result; }); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + await executePaperclipNativeSession({ db: leaseDb(current), execution: current, runnerInstanceId: name, runnerExecutionTarget: target as never }); + await vi.advanceTimersByTimeAsync(60_000); + expect(phase).toBe("retired"); expect(close).toHaveBeenCalledOnce(); + const next = { ...current, binding: { ...current.binding, runId: `${name}-two` } }; + await executePaperclipNativeSession({ db: leaseDb(next), execution: next, runnerInstanceId: `${name}-fresh`, + runnerExecutionTarget: { ...target, resourceAuthority: { ...target.resourceAuthority, ownerId: "new-owner" } } as never }); + } finally { vi.useRealTimers(); } + }); + + it.each(["failed-close", "expired-reservation", "superseded"])("does not report clean close when %s", async condition => { + const name = `graceful-${condition}`; + const current = { ...execution, binding: { ...execution.binding, runId: name, agentId: name }, + session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm", idleTimeoutMs: 60_000 } } } as NativeExecutionInputV1; + const close = vi.fn(async () => { throw new Error("protocol close failed"); }); + const detach = vi.fn(async () => undefined); + let retired = false; + const retire = vi.fn(async (options?: { beforeStop?: () => Promise }) => { + if (condition === "superseded") return false; + if (condition === "failed-close") await options?.beforeStop?.().catch(() => undefined); + retired = true; + return true; + }); + state.execute.mockReset().mockImplementationOnce(async options => { await options.onSession?.({ close, detachControllerForRestart: detach }); + return { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" }, turnId: name, + normalizedSessionId: name, providerSessionId: name, driverKind: "test", driverVersion: "1", nativeEventCount: 1, + highestContiguousSourceSeq: 1, usage: null }; }); + await executePaperclipNativeSession({ db: leaseDb(current), execution: current, runnerInstanceId: name, + runnerExecutionTarget: { kind: "remote", transport: "computer", environmentId: name, remoteCwd: "/remote/agent", + resourceAuthority: { kind: "computer-owner", computerId: name, ownerId: name, generation: 1 }, + retainWarm: async () => undefined, retire } as never }); + const result = await closeWarmNativeSessionsForRun({ runId: name, reason: "cancel exact task" }); + expect(result.failed).toBe(1); + expect(retired).toBe(condition !== "superseded"); + if (condition === "superseded") { expect(close).not.toHaveBeenCalled(); expect(detach).not.toHaveBeenCalled(); } + else expect(detach).toHaveBeenCalledOnce(); + }); +}); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 2129dc862b8..fb970884ff3 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -473,35 +473,51 @@ type WarmNativeSession = { lastActivityAt: string; }; +/** A scoped preparation failure is retryable only after exact retirement fences + * queued commands. A process claim or invoked launcher keeps normal recovery. */ +export async function retireUnlaunchedComputerAttempt( + target: AdapterExecutionTarget | null | undefined, + launchAttempted: boolean, +): Promise { + if (target?.kind !== "remote" || target.transport !== "computer" || launchAttempted) return; + const process = await target.inspectProcess(); + if (process.running || process.claim !== null) return; + if (!(await target.retire())) throw new NativeSessionCleanupQuarantinedError(); +} + class ComputerOwnerSupersededError extends Error { constructor() { super("computer_owner_retirement_superseded"); } } async function closeWarmNativeSession(entry: WarmNativeSession, reason: string, preserveInstructionsForRunId?: string) { - // Computer admission can advance while an old idle timer is firing. Only - // the exact durable owner may stop the runner or its controller transport. - if (entry.computerTarget && !(await entry.computerTarget.retire())) { + let closeFailure: unknown; + let closeCompleted = false; + const close = async () => { + try { await entry.session.close({ reason }); closeCompleted = true; } + catch (error) { closeFailure = error; throw error; } + }; + // Reserve the exact generation before protocol close. A winning admission + // must never receive a stale controller's suspend/kill command. The module + // always hard-retires descendants after the bounded graceful window. + if (entry.computerTarget && !(await entry.computerTarget.retire({ beforeStop: close }))) { throw new ComputerOwnerSupersededError(); } - // Revoke before awaiting process retirement/checkpoint IO. const stopping = entry.githubAccess?.stop(); try { try { - if (entry.computerTarget && entry.session.detachControllerForRestart) { - await entry.session.detachControllerForRestart(); - } else { - await entry.session.close({ reason }); + if (!entry.computerTarget) await close(); + if (closeFailure || !closeCompleted) { + await entry.session.detachControllerForRestart?.(); + throw closeFailure ?? new NativeSessionCleanupQuarantinedError(); } - } - catch (error) { + } catch (error) { try { await entry.instructionWorkingCopy?.retirementFailed?.(); } catch (receiptError) { throw new AggregateError([error, receiptError], "Warm instruction retirement and receipt both failed"); } throw error; } await entry.instructionWorkingCopy?.collectStopped(); if (entry.instructionCopy?.runId !== preserveInstructionsForRunId) await entry.instructionCopy?.collectStopped(); - } - finally { await stopping; } + } finally { await stopping; } } const warmNativeSessions = new Map(); @@ -8746,6 +8762,8 @@ async function executePaperclipNativeSessionWithinScope( }, } : input.execution; + let remoteLaunchAttempted = false; + let remoteBackendPreparationStarted = false; const leaseRenewal = startNativeSessionExecutionLeaseRenewal({ db: input.db, runId: input.execution.binding.runId, @@ -8773,6 +8791,7 @@ async function executePaperclipNativeSessionWithinScope( input.db, input.execution.binding, ); + remoteBackendPreparationStarted = input.useRunnerd === true && input.backend === undefined; const runnerdBackend = input.useRunnerd && input.backend === undefined ? await createRunnerdBackend({ @@ -8783,6 +8802,7 @@ async function executePaperclipNativeSessionWithinScope( execution: input.execution, runnerInstanceId: effectiveRunnerInstanceId, durableEnvironmentLeaseId: durableRunnerBinding?.environmentLeaseId, + onRemoteLaunchAttempt: () => { remoteLaunchAttempted = true; }, trace, toolTrace, }) @@ -9168,6 +9188,15 @@ async function executePaperclipNativeSessionWithinScope( // with a retry or release the still-live runner's lease. throw new NativeControllerDetachedForRestartError(); } + if (remoteBackendPreparationStarted) { + try { + await retireUnlaunchedComputerAttempt(input.runnerExecutionTarget, remoteLaunchAttempted); + } catch { + // Failure to establish the exact tombstone leaves queued commands or + // a lost launch acknowledgement ambiguous. Never retry that owner. + error = new NativeSessionCleanupQuarantinedError(); + } + } const protocolIntegrityFailure = error instanceof NativeSessionProtocolIntegrityError ? error : null; const ownershipUnverified = @@ -10823,6 +10852,134 @@ export async function syncRemoteRunnerDirectoryOut(input: { } } +/** A dead computer runner may retain a ready checkpoint after controller loss. + * Match the local quiescent-recovery proof before sealing it for normal rotation. + */ +export function retiredComputerCheckpointIsSettled(input: { + execution: NativeExecutionInput; + priorExecution: NativeExecutionInput; + identity: RunnerdDurableIdentity; + runner: Record; + control: Record; + provider: Record; + checkpoint: Record; + currentCheckpoint: Record; +}): boolean { + const { execution, priorExecution, identity, runner, control, provider, checkpoint, currentCheckpoint } = input; + if (execution.provider.kind !== "codex" || priorExecution.provider.kind !== "codex") return false; + const events = control.committedEvents; + const commands = control.commands; + const terminal = record(record(Array.isArray(events) ? events.at(-1) : null).envelope); + const fields = ["runId", "normalizedSessionId", "runnerInstanceId", "environmentLeaseId", "turnId", "itemId"] as const; + if (runner.schema !== RUNNERD_STATE_SCHEMA || runner.lifecycle !== "ready" || + fields.some(key => runner[key] !== identity[key] || record(control.identity)[key] !== identity[key]) || + !Array.isArray(runner.outbox) || runner.outbox.length !== 0 || runner.pendingTerminalDelivery !== null || + !Array.isArray(commands) || commands.some(command => record(command).status !== "completed") || + !Array.isArray(events) || record(events.at(-1)).eventType !== "run.terminal" || + terminal.runId !== identity.runId || terminal.normalizedSessionId !== identity.normalizedSessionId || + provider.completedTurnAuthoritative !== true || priorExecution.binding.runId !== identity.runId || + priorExecution.binding.issueId !== execution.binding.issueId || + nativeSessionScopeKey(priorExecution) !== nativeSessionScopeKey(execution) || + nativeSessionConfigDigest(priorExecution) !== nativeSessionConfigDigest(execution)) return false; + const providerIdentity = providerSessionIdentityFromDurableProviderState({ execution: priorExecution, providerState: provider }); + if (!providerIdentity.providerSessionId) return false; + return [checkpoint, currentCheckpoint].every((value, index) => { + const binding = record(value.identity); + return value.providerSessionId === providerIdentity.providerSessionId && + value.driverKind === priorExecution.session.driverKind && value.activeTurnId === null && + Array.isArray(value.pendingRuntimeRequests) && value.pendingRuntimeRequests.length === 0 && + binding.runId === (index === 0 ? identity.runId : execution.binding.runId) && + binding.sessionId === identity.normalizedSessionId && binding.companyId === execution.binding.companyId && + binding.agentId === execution.binding.agentId && binding.issueId === execution.binding.issueId; + }); +} + +async function sealRetiredComputerRunnerState(input: { + db: Db; execution: NativeExecutionInput; root: string; + target: Extract; + runner: CommandManagedRuntimeRunner; stateDirectory: string; +}): Promise { + const identity = readRunnerdDurableIdentity(input.root); + if (!identity || identity.runId === input.execution.binding.runId || input.execution.provider.kind !== "codex") return; + if (!durableIdentityMatchesSession(identity, input.execution)) throw new Error("runner_remote_retirement_scope_mismatch"); + const controlPath = resolve(input.root, "control-plane", "control-plane-state.json"); + const controlBytes = readBoundedNativeFile(controlPath, NATIVE_CONTROL_PLANE_STATE_MAX_BYTES, "recovery_state_too_large"); + const runnerPath = posix.join(input.stateDirectory, "runner-state.json"); + const providerPath = posix.join(input.stateDirectory, runnerProviderStateFilename(input.execution)); + const read = await input.runner.execute({ command: "python3", args: ["-c", String.raw` +import sys,os,stat,json,base64 +rows=[] +for p in sys.argv[1:]: + s=os.lstat(p) + if not stat.S_ISREG(s.st_mode) or s.st_size>16777216:raise RuntimeError('unsafe recovery state') + with os.fdopen(os.open(p,os.O_RDONLY|os.O_NOFOLLOW),'rb') as f:data=f.read(16777217) + if len(data)>16777216:raise RuntimeError('unsafe recovery state') + rows.append(base64.b64encode(data).decode()) +print(json.dumps(rows))`, runnerPath, providerPath], bypassSession: true, timeoutMs: 10_000 }); + if (read.exitCode !== 0 || read.timedOut) throw new Error("runner_remote_retirement_state_unavailable"); + const [runnerBytes, providerBytes] = (JSON.parse(read.stdout) as string[]).map(value => Buffer.from(value, "base64")); + const runner = record(JSON.parse(runnerBytes!.toString("utf8"))); + if (runner.lifecycle === "suspended") return; + const runs = await input.db.select({ id: heartbeatRuns.id, status: heartbeatRuns.status, runnerProfileJson: heartbeatRuns.runnerProfileJson }) + .from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, input.execution.binding.companyId), + eq(heartbeatRuns.agentId, input.execution.binding.agentId), + inArray(heartbeatRuns.id, [identity.runId, input.execution.binding.runId]))); + const prior = runs.find(run => run.id === identity.runId); + const current = runs.find(run => run.id === input.execution.binding.runId); + if (!prior || !current || !TERMINAL_HEARTBEAT_RUN_STATUSES.has(prior.status)) + throw new Error("runner_remote_retirement_authority_unverified"); + const profile = record(prior.runnerProfileJson); + const previous = parseNativeExecutionInput(profile.nativeExecutionInput); + if (!retiredComputerCheckpointIsSettled({ execution: input.execution, priorExecution: previous, identity, runner, + control: record(JSON.parse(controlBytes.toString("utf8"))), provider: record(JSON.parse(providerBytes!.toString("utf8"))), + checkpoint: record(profile.sessionCheckpoint), currentCheckpoint: record(record(current.runnerProfileJson).sessionCheckpoint) }) || + await verifyPriorRunnerdStateForSessionScope({ db: input.db, root: input.root, identity, execution: input.execution, + allowVerifiedBackup: false, allowRetainedWarmRunner: false, remoteRunnerState: true, runnerExecutionTarget: input.target }) !== "verified") + throw new Error("runner_remote_retirement_checkpoint_unsettled"); + // Recheck exact durable retirement after all awaited reads; never infer death + // from a missing PID or turn status. The compare-and-swap preserves ambiguity. + const workspace = readNativeComputerWorkspaceReference(profile.nativeComputerWorkspace); + if (!workspace || !input.target.environmentId || !(await computerService(input.db).isRetired({ + companyId: input.execution.binding.companyId, environmentId: input.target.environmentId, + owner: workspace.computerOwner, agentId: input.execution.binding.agentId, runId: identity.runId, + })) || !controlBytes.equals(readBoundedNativeFile(controlPath, NATIVE_CONTROL_PLANE_STATE_MAX_BYTES, "recovery_state_too_large"))) + throw new Error("runner_remote_retirement_evidence_changed"); + await compareAndSealRetiredComputerCheckpoint({ runner: input.runner, runnerPath, providerPath, + runnerBytes: runnerBytes!, providerBytes: providerBytes! }); +} + +/** Exact retirement is checked by the caller; publication must still compare + * the complete bytes so a changed or interrupted checkpoint is never rotated. */ +export async function compareAndSealRetiredComputerCheckpoint(input: { + runner: CommandManagedRuntimeRunner; runnerPath: string; providerPath: string; + runnerBytes: Buffer; providerBytes: Buffer; +}): Promise { + const result = await input.runner.execute({ command: "python3", args: ["-c", String.raw` +import sys,os,stat,json,hashlib,tempfile +runner,provider,expected_runner,expected_provider=sys.argv[1:] +for p,digest in [(runner,expected_runner),(provider,expected_provider)]: + s=os.lstat(p) + if not stat.S_ISREG(s.st_mode) or s.st_size>16777216:raise RuntimeError('unsafe recovery state') + with os.fdopen(os.open(p,os.O_RDONLY|os.O_NOFOLLOW),'rb') as f:data=f.read(16777217) + if len(data)>16777216:raise RuntimeError('unsafe recovery state') + if hashlib.sha256(data).hexdigest()!=digest:raise RuntimeError('recovery evidence changed') + if p==runner:state=json.loads(data) +state['lifecycle']='suspended' +fd,tmp=tempfile.mkstemp(prefix='.retired-checkpoint-',dir=os.path.dirname(runner)) +try: + with os.fdopen(fd,'w') as f:json.dump(state,f,separators=(',',':'));f.flush();os.fsync(f.fileno()) + # Recheck immediately before publication, including the provider checkpoint. + for p,digest in [(runner,expected_runner),(provider,expected_provider)]: + with os.fdopen(os.open(p,os.O_RDONLY|os.O_NOFOLLOW),'rb') as f:current=f.read(16777217) + if hashlib.sha256(current).hexdigest()!=digest:raise RuntimeError('recovery evidence changed') + os.replace(tmp,runner) +finally: + if os.path.exists(tmp):os.unlink(tmp) +`, input.runnerPath, input.providerPath, createHash("sha256").update(input.runnerBytes).digest("hex"), createHash("sha256").update(input.providerBytes).digest("hex")], + bypassSession: true, timeoutMs: 10_000 }); + if (result.exitCode !== 0 || result.timedOut) throw new Error("runner_remote_retirement_checkpoint_cas_failed"); +} + async function readRemoteRunnerState(input: { runner: CommandManagedRuntimeRunner; stateDirectory: string; @@ -11100,9 +11257,11 @@ export function createRemoteRunnerProcessLauncher(input: { onLog?: (stream: "stdout" | "stderr", chunk: string) => Promise; trace?: NativeRunTrace; onRunnerProcessSpawned?: () => void; + onLaunchAttempt?: () => void; }): (spec: RunnerProcessLaunchSpec) => RunnerProcessHandle { const runner = input.runner; return (spec) => { + input.onLaunchAttempt?.(); let launchedIdentity: { nonce: string; pid: number; @@ -11404,6 +11563,7 @@ export async function createRunnerdBackend(input: { chatAttachmentReadScope?: NativeChatAttachmentReadScope; restartRecovery?: NativeRestartRecoveryClaim; durableEnvironmentLeaseId?: string; + onRemoteLaunchAttempt?: () => void; onSpawn?: (meta: { pid: number; processGroupId: number | null; @@ -13064,6 +13224,10 @@ async function createRunnerdBackendWithinSessionClaim( if (incompleteFailure) throw incompleteFailure; return; } + // The computer ledger and exact remote placement are the recovery authority. + // Its durable provider state stays on the persistent machine; importing the + // sandbox archive would create a second authority and delay bounded shutdown. + if (remoteTarget?.transport === "computer") return; const backupSpanAttributes = { provider: input.execution.provider.kind, harness: input.execution.session.driverKind, @@ -13207,6 +13371,10 @@ async function createRunnerdBackendWithinSessionClaim( runnerIngressAuthorized: input.runnerIngressAuthorized === true, }); await ensureRemoteRunner(false); + if (remoteTarget.transport === "computer" && remoteStateDirectory) { + await sealRetiredComputerRunnerState({ db: input.db, execution: input.execution, root, + target: remoteTarget, runner: remoteCommandRunner, stateDirectory: remoteStateDirectory }); + } } : undefined; const archiveExternalRunnerState = @@ -13277,6 +13445,7 @@ async function createRunnerdBackendWithinSessionClaim( onLog: input.onLog, trace: input.trace, onRunnerProcessSpawned: () => resolveRemoteRunnerProcessSpawned?.(), + onLaunchAttempt: input.onRemoteLaunchAttempt, }) : undefined; const runnerExecution: NativeExecutionInput = remoteTarget diff --git a/ui/src/components/EmailMessageCard.tsx b/ui/src/components/EmailMessageCard.tsx index be4a083e15f..b1c374e1ac4 100644 --- a/ui/src/components/EmailMessageCard.tsx +++ b/ui/src/components/EmailMessageCard.tsx @@ -42,7 +42,9 @@ export function EmailMessageCard({ message, publication, issueId, + contextNotice = false, }: { + contextNotice?: boolean; message: EmailMessage; publication?: EmailPublicationSummary; issueId: string; @@ -57,7 +59,7 @@ export function EmailMessageCard({ aria-label={ message.direction === "inbound" ? "Email received" : "Email sent" } - className="space-y-4 rounded-xl border border-border bg-card p-5" + className={contextNotice ? "task-context-notice space-y-3" : "space-y-4 rounded-xl border border-border bg-card p-5"} >
diff --git a/ui/src/components/EmailTaskActivity.tsx b/ui/src/components/EmailTaskActivity.tsx index 6f442b1372c..6a384fb1d0e 100644 --- a/ui/src/components/EmailTaskActivity.tsx +++ b/ui/src/components/EmailTaskActivity.tsx @@ -36,6 +36,7 @@ export function EmailTaskActivity({ )} {messages.map((m) => (

{p.request.subject ?? "Email reply"}

{p.request.to &&

To: {p.request.to.join(", ")}

} diff --git a/ui/src/components/ExecutionBlockerNotice.test.tsx b/ui/src/components/ExecutionBlockerNotice.test.tsx index 3960f71070b..980f0a6fdf1 100644 --- a/ui/src/components/ExecutionBlockerNotice.test.tsx +++ b/ui/src/components/ExecutionBlockerNotice.test.tsx @@ -36,8 +36,7 @@ describe("stopped task recovery notice", () => { const notice = container.querySelector('[role="status"][aria-label="Task recovery"]')!; expect(notice.textContent).toContain("Recorded work is preserved"); expect(notice.textContent).toContain("Retry"); - expect(notice.classList.contains("border")).toBe(true); - expect(notice.classList.contains("bg-muted")).toBe(true); + expect(notice.classList.contains("task-context-notice")).toBe(true); expect(notice.querySelector("a")?.getAttribute("href")).toBe("/agents/agent/runs/failed-run"); }); it.each([false, true])("explains cancelled runs and saved input; continue eligibility %s", async canContinue => { diff --git a/ui/src/components/ExecutionBlockerNotice.tsx b/ui/src/components/ExecutionBlockerNotice.tsx index c157a359b5d..0cb1eb0b775 100644 --- a/ui/src/components/ExecutionBlockerNotice.tsx +++ b/ui/src/components/ExecutionBlockerNotice.tsx @@ -4,9 +4,11 @@ import { agentsApi } from "../api/agents"; import { activityApi } from "../api/activity"; import { queryKeys } from "../lib/queryKeys"; import { Button } from "./ui/button"; +import { cn } from "../lib/utils"; import { Link } from "../lib/router"; -export function ExecutionBlockerNotice({ companyId, issueId, blocker, onRetried }: { +export function ExecutionBlockerNotice({ companyId, issueId, blocker, onRetried, className }: { + className?: string; companyId: string; issueId: string; blocker: ExecutionBlocker; @@ -33,7 +35,7 @@ export function ExecutionBlockerNotice({ companyId, issueId, blocker, onRetried }, }); return ( -
+

{modelRejected ? "Model unavailable." : "Recovery needed."}{blocker.runError ? ` ${blocker.runError}` : ""}

{modelRejected &&

Choose a supported model or clear the task's model override, then retry.

} diff --git a/ui/src/components/WorkspaceExportRecovery.tsx b/ui/src/components/WorkspaceExportRecovery.tsx index 23ae74319b1..98376816817 100644 --- a/ui/src/components/WorkspaceExportRecovery.tsx +++ b/ui/src/components/WorkspaceExportRecovery.tsx @@ -3,12 +3,14 @@ import { useMutation } from "@tanstack/react-query"; import type { IssueRecoveryAction } from "@paperclipai/shared"; import { isNativeWorkspaceExportRepairCause } from "@paperclipai/shared"; import { issuesApi } from "../api/issues"; +import { cn } from "../lib/utils"; import { Button } from "./ui/button"; import { Label } from "./ui/label"; import { Textarea } from "./ui/textarea"; /** Copyback repair preserves the accepted result and never wakes the provider. */ -export function WorkspaceExportRecovery({ issueId, action, canManage, onQueued }: { +export function WorkspaceExportRecovery({ issueId, action, canManage, onQueued, className }: { + className?: string; issueId: string; action: IssueRecoveryAction | null; canManage: boolean; onQueued: () => void; }) { const noteId = useId(); @@ -23,7 +25,7 @@ export function WorkspaceExportRecovery({ issueId, action, canManage, onQueued } if (!action || !isNativeWorkspaceExportRepairCause(action.cause) || action.ownerType !== "board" || !["active", "escalated"].includes(action.status) || typeof action.evidence.runId !== "string") return null; const queued = queuedActionVersion === String(action.updatedAt) || action.wakePolicy?.kind === "resume_native_run"; - return
+ return

Workspace export needs repair

{queued ?

Export is queued for the saved result. The agent will not repeat its work.

: <>

{"Automatic workspace export retries stopped. Inspect the export failure, restore provider or destination availability, and preserve the saved files in the retained sandbox. Retry export here when the cause is resolved."}

diff --git a/ui/src/components/chat/ExternallyConnectedTaskBanner.tsx b/ui/src/components/chat/ExternallyConnectedTaskBanner.tsx index 221f28c14aa..bb92647d243 100644 --- a/ui/src/components/chat/ExternallyConnectedTaskBanner.tsx +++ b/ui/src/components/chat/ExternallyConnectedTaskBanner.tsx @@ -17,6 +17,7 @@ import { Checkbox } from "@/components/ui/checkbox"; import { Textarea } from "@/components/ui/textarea"; import { useToast } from "@/context/ToastContext"; import { Link } from "@/lib/router"; +import { cn } from "@/lib/utils"; import { queryKeys } from "@/lib/queryKeys"; import { useChatConnectorsEnabled, chatProviderVisible } from "@/hooks/useChatConnectorsEnabled"; import { issuesApi } from "@/api/issues"; @@ -124,6 +125,7 @@ export function useIssueChatBinding(companyId: string, issueId: string) { } type ConnectedTaskProps = { + className?: string; attachments?: IssueAttachment[]; companyId: string; issueId: string; @@ -148,6 +150,7 @@ export function ExternallyConnectedTaskBanner(props: ConnectedTaskProps) { } function ConnectedTaskComposer({ + className, attachments = [], companyId, issueId, @@ -486,7 +489,7 @@ function ConnectedTaskComposer({ return (
diff --git a/ui/src/index.css b/ui/src/index.css index c45d030ffc3..ce91a3a3dba 100644 --- a/ui/src/index.css +++ b/ui/src/index.css @@ -3120,11 +3120,13 @@ span.paperclip-mention-chip[data-mention-kind="external-object"] { inset-inline: 0; } -/* Task recovery panel uses the shared spacing, radius, and type scales. */ -.execution-blocker-notice { - gap: calc(var(--spacing) * 2); - padding: calc(var(--spacing) * 2) calc(var(--spacing) * 3); - border-radius: var(--radius-md); +/* Connection and recovery cards share one surface and spacing scale. */ +.task-context-notice { + padding: calc(var(--spacing) * 3); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + background-color: var(--muted); + color: var(--foreground); font-size: var(--text-sm); line-height: var(--text-sm--line-height); } diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index a7b7ff66094..b7ebb693a9a 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -7642,6 +7642,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS {taskChatShellEnabled ? null : createdFromNote} + {resolvedDetailTab === "chat" && ( + + )} + {resolvedDetailTab === "chat" && issue.executionBlocker && ( + + )} + {issue.status === "in_review" && issue.externalConversationState === "waiting" && (

Reply sent. Send a message to continue.

)} @@ -7952,11 +7962,6 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS : undefined } > - - {issue.executionBlocker && ( - - )} {resolvedDetailTab === "chat" ? ( { invalidateIssueDetail(); invalidateIssueCollections(); }} unavailableReason={!canManageBoardRuntime || !canResolveBoardRecoveryAction ? "You don’t have permission to repair this task’s workspace." diff --git a/ui/storybook/stories/task-context-notices.stories.tsx b/ui/storybook/stories/task-context-notices.stories.tsx new file mode 100644 index 00000000000..f92b8ffaaac --- /dev/null +++ b/ui/storybook/stories/task-context-notices.stories.tsx @@ -0,0 +1,68 @@ +import { useState } from "react"; +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { expect, within } from "storybook/test"; +import { ExternallyConnectedTaskBanner } from "@/components/chat/ExternallyConnectedTaskBanner"; +import { ExecutionBlockerNotice } from "@/components/ExecutionBlockerNotice"; +import { EmailMessageCard } from "@/components/EmailMessageCard"; +import { queryKeys } from "@/lib/queryKeys"; + +const shellSectionClass = "mx-auto w-full max-w-(--tc-shell-max-w)"; + +function TaskContextNotices() { + const [client] = useState(() => { + const cache = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false } } }); + cache.setQueryData(queryKeys.instance.experimentalSettings, { enableChatConnectors: true }); + cache.setQueryData(["issue-chat-binding", "demo", "context-notices"], { + endpointId: "slack-demo", provider: "slack", externalLabel: "#design · Card styling", + externalUrl: "https://slack.com", conversationId: "demo-thread", assignedAgentLocked: true, + }); + cache.setQueryData(queryKeys.issues.runs("context-notices"), []); + return cache; + }); + return ( + +
+
+

Chat connection and recovery

+ + {}} + blocker={{ recoveryActionId: "demo-recovery", runId: null, agentId: null, cause: "action_outcome_unknown", + nextAction: "Inspect the run before continuing. Recorded work is preserved." }} /> +
+ +
+
+
+
+ ); +} + +const meta = { + title: "Tasks/Context notices", + component: TaskContextNotices, + parameters: { layout: "fullscreen" }, +} satisfies Meta; +export default meta; +type Story = StoryObj; + +export const ConnectionAndRecovery: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + const connection = await canvas.findByRole("region", { name: "External conversation" }); + const recovery = canvas.getByRole("status", { name: "Task recovery" }); + const email = canvas.getByRole("article", { name: "Email received" }); + for (const card of [recovery, email]) { + await expect(card.getBoundingClientRect().width).toBe(connection.getBoundingClientRect().width); + await expect(getComputedStyle(card).backgroundColor).toBe(getComputedStyle(connection).backgroundColor); + await expect(getComputedStyle(card).padding).toBe(getComputedStyle(connection).padding); + await expect(getComputedStyle(card).borderRadius).toBe(getComputedStyle(connection).borderRadius); + } + }, +};