mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 22:49:00 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The native Runner starts each agent harness and owns its lifecycle, credentials and recovery > - Google Antigravity is Google's only first-party coding harness, and it is the harness for Gemini 4 Neon > - The Runner had an Antigravity integration, but only as a pending candidate: ACP server 1.4.3, macOS ARM64 only, Google sign-in only, closed unless an operator opened it for one company and one model > - Cloud sandboxes run Linux and use API keys, so the candidate could not run there, and it had one attended test cell > - This pull request moves the integration to ACP server 1.5.2, makes it run on Linux and with a Gemini API key, adds the tests the other ACPX harnesses have, and removes the code paths that would block recovery after release > - The benefit is that the release of Antigravity becomes a small declaration change after the live suites pass. The profile stays `pending` in this pull request. ## Linked Issues or Issue Description Refs #98 Refs #6559 Refs #8523 Refs #21121 (a separate legacy-style `agy_local` adapter that uses the CLI print protocol; this pull request does not replace or include it) ## What Changed **Runtime** - Pin Antigravity ACP server 1.5.2 (was 1.4.3). Owned admission patch is `1.5.2-paperclip.2`. - Verified patched closures for `darwin-arm64`, `linux-x64` and `linux-arm64`. `darwin-x64` stays inventory-only. - The patcher reads Mach-O and ELF builds. It signs macOS output only. One admission source serves all platforms. - Platform gates in TypeScript, Rust, the sidecar schema and the server admit each host that has a verified closure. **Auth and models** - Gemini API-key auth reaches an exact-model session receipt. Admission accepts a model only when the base model and the thinking level both match the requested ID. - API-key connections get a model list on local and cloud environments. The list is generated at build time from the pinned runtime. The server starts no process to read it. - Gemini 4 Neon, Carbon, Argon and Hydrogen are selectable. The picker marks them "needs a paid Gemini API plan" for API-key connections. - One shared module maps model ID to family and thinking level. - `google/gemini-4-neon` is added to the OpenCode model list. A new model audit is in `doc/adapter-model-audit-2026-11-22.md`. **Lifecycle and failures** - A provider error no longer completes the turn. The driver classifies it: overloaded, rate limit, quota, auth rejected, model unavailable. - Overload retries are bounded (3 attempts, about 14 seconds). - A refused session reload maps to incompatible saved state, so the automatic replacement conversation applies. - Server gates that refused restart recovery, remote targets and shared state for Antigravity now apply only while the profile is pending. - A Google sign-in connection with a cloud environment is refused at save and at Test, with a plain message. - A released profile rejects candidate grants in TypeScript and in Rust. **Launch cost and integrity (all native ACPX providers)** - Each closure is verified one time into a sealed read-only store. Later launches check file identities and hash the exact executable they start. - Remote provider-pack verification is recorded per sandbox lease. Later runs check kernel identity and fall back to the full hash on any difference. - Superseded stores are removed in the background after a launch. **Provider pack and image** - The provider pack carries Antigravity for `linux-x64` as a candidate provider. It becomes an ordinary provider from the profile status alone. - The Daytona image build accepts the candidate. A credential-free smoke runs in the build. **Tests and CI** - New `antigravity-qualification` suite: 24 cells, local and Daytona. - New model lineup suites: 14 API-key cells and 14 Gemini 4 cells. Each cell requires the exact model in the Runner receipt. - Antigravity can run the `chat-features` cases with `--profile runner-acpx-antigravity`. - `runner-full-stack-e2e.yml` passes `GEMINI_API_KEY` for the new profile and derives candidate providers from the selected Daytona cells. **Docs** - `doc/plans/2026-11-22-antigravity-qualification.md` is the current release contract, acceptance ledger and operator recipe. ## Verification Commands that passed on the final revision: - `pnpm build` - Typecheck for all packages, including the runner-e2e test projects - `pnpm test:e2e:runner:unit`: 11,665 Vitest tests passed, 25 skipped; 386 node tests passed - `cargo test -p paperclip-runner-core -- --test-threads=4`: 1,199 passed, 2 failed. The 2 failures are Codex transport timing tests that pass alone and on `master`. - `cargo fmt --check`, `check:acpx-profiles`, `check:protocol-types`, `node scripts/check-maps.mjs` - Native patch tests: 9 of 9 on `darwin-arm64` and 9 of 9 on `linux-x64` - UI picker tests: 397 of 397 Known failures that also fail on `master`: - 11 runner package script tests (browser, Pi and package-boundary checks) - 6 `runtime-selection` tests that read an untracked local skill file Live evidence, without a prompt: - Clean provisioning on `darwin-arm64` and on `linux-x64` in a Daytona sandbox. The closure digests reproduce. A changed or missing file is rejected. - `initialize` reports 1.5.2. An API-key session returns a receipt for exactly `gemini-3.8-flash-low` and the exact instruction bytes, on both platforms. - All 28 model IDs (14 Gemini 3, 14 Gemini 4) return an exact receipt under an API key. - A session survives a process kill and resumes in a new process with exact receipts, on both platforms. - The server's remote path verifies the provider pack in a Daytona sandbox. - Run start to native `initialize`: 3.45 s to 1.46 s on macOS, 3.65 s to 1.74 s on Linux x64, before the per-launch executable hash was restored (about 60 ms on macOS; not measured on Linux). - Remote pack verification on a reused sandbox lease: about 4.3 s to about 0.25 s. Live evidence, with a prompt, on an already-released harness: - Pi native, `pi-native.runner-acpx-pi.local.agent-files-fresh-run`, on `darwin-arm64` at `427e9b088b`: 1 of 1 passed, 14 of 14 checks, both native runs succeeded (25.5 s and 25.7 s). The process started from the new launch store with no fallback warning. - The same cell and `native-pending-controller-restart` failed in the paid workflow on this branch and on `master` in the same way, before any native start. The workflow does not install the Pi runtime for local cells, so the agent setup check fails. That is a workflow gap, not part of this change. **Not run.** No Antigravity prompt completed on 1.5.2 on any platform. The only Gemini key available is on the free tier, and Google returned 503 or 429 for each attempt on two days. These gates are open: - All 24 `antigravity-qualification` cells - Both model lineup suites, including inference on Gemini 4 Neon - The attended Google sign-in journey on 1.5.2 - The chat cases under Antigravity - Image pull time and startup time on a published image - A native start on `linux-arm64` - A live provider-death cell for Kimi, Pi or Copilot on the new launch store (one ordinary Pi cell passed live; see above) ## Risks - **The launch store changes how every native ACPX provider starts** (Kimi, Copilot, Cursor, Pi), not only Antigravity. A review found two defects in the first version (an executable swap was possible, and Pi launches broke). Both are fixed with tests. One live Pi cell passed on this branch on macOS. No live provider-death cell and no Linux cell ran for those providers. - The profile digest changes. Saved Antigravity candidate sessions and existing candidate grants stop working. The new release refuses old state by name and starts a replacement conversation. - The Linux provider pack and the Daytona image grow by about 834 MB (about 274 MB compressed) when Antigravity is included. - The pack verification record is in server memory. The first run after a server restart pays the full hash again. - Antigravity 1.5.2 reads the workspace `GEMINI.md` and `AGENTS.md` as user rules. This is deliberate and matches Codex. Any other rule file is refused. - Orchestrator mode is not available. ACP server 1.5.2 does not expose it. - Antigravity stays `pending`. Normal users cannot run it until a later change removes the pending status. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`) planned, briefed and integrated the work, with tool use. - Claude Opus 5.5 (`claude-opus-5-5`) subagents wrote the code and ran the tests, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
240 lines
20 KiB
TypeScript
240 lines
20 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { join } from "node:path";
|
|
import { expect, type Page } from "@playwright/test";
|
|
import { pollUntil, type RunnerApi } from "./api.js";
|
|
import { collectRunEvents } from "./run-observations.js";
|
|
import { createTaskThroughUi } from "./user-actions.js";
|
|
import { createDeniedTargetFixture, exists, observeRunProcesses } from "./copilot-local-fixtures.js";
|
|
import { assertCopilotRemoteRetirement, copilotRemoteDeniedSample, prepareCopilotRemoteAction, type CopilotRemoteBootstrap, type CopilotRemoteFixture, type CopilotRemoteSnapshot } from "./copilot-protection-evidence.js";
|
|
import { cursorDeniedCommand } from "./cursor-native-evidence.js";
|
|
import { assertActiveStopRetirement, readActiveStopCaller, observeActiveStopPending, readActiveStopSettlement, readDeniedPermissionSettlement, type ActiveStopRemoteObservation, type ActiveStopCaller, type ActiveStopPending, type ActiveStopScope } from "./native-active-stop-evidence.js";
|
|
import type { BootstrapReadProof } from "./native-bootstrap-read-proof.js";
|
|
import type { LiveFixtureValues } from "./live-fixtures.js";
|
|
import type { MatrixExecution } from "./types.js";
|
|
type Row = Record<string, any>;
|
|
type Check = { id: string; passed: boolean; detail: string };
|
|
export interface ActiveStopState { run: Row; issue: Row; events: readonly unknown[] }
|
|
/** Retain a real pending API observation before the only mutating request.
|
|
* Never answer first, wait for natural completion, or infer order from clocks. */
|
|
export async function stopAtPendingPermission(input: {
|
|
scope: ActiveStopScope; caller: ActiveStopCaller; bootstrap?: BootstrapReadProof; deadlineAt: number;
|
|
load(): Promise<ActiveStopState>;
|
|
retain(receipt: ActiveStopPending): Promise<void>;
|
|
stop(runId: string, cancellationRequestId: string): Promise<Row>;
|
|
}) {
|
|
const cancellationRequestId = randomUUID();
|
|
const state = await input.load();
|
|
const pending = observeActiveStopPending({ ...state, scope: input.scope, caller: input.caller, cancellationRequestId, bootstrap: input.bootstrap });
|
|
await input.retain(pending);
|
|
const fresh = observeActiveStopPending({ ...await input.load(), scope: input.scope, caller: input.caller, cancellationRequestId, bootstrap: input.bootstrap });
|
|
if (fresh.requestRowSha256 !== pending.requestRowSha256 || fresh.permissionRowSha256 !== pending.permissionRowSha256
|
|
|| fresh.toolOriginRowSha256 !== pending.toolOriginRowSha256 || fresh.toolStartedRowSha256 !== pending.toolStartedRowSha256
|
|
|| Date.now() >= input.deadlineAt) throw new Error("Native active Stop pending boundary changed or expired");
|
|
const dispatchMonotonicNs = process.hrtime.bigint().toString();
|
|
const stopped = await input.stop(input.scope.runId, cancellationRequestId);
|
|
if (stopped.id !== input.scope.runId || stopped.resultJson?.nativeCancellation?.intentId !== `native-cancellation:${cancellationRequestId}`) throw new Error("Native active Stop response has a foreign intent");
|
|
const label = "cancelled unanswered native permission";
|
|
const final = await pollUntil({ label, deadlineAt: input.deadlineAt, intervalMs: 200, load: async () => {
|
|
const value = await input.load();
|
|
if (["succeeded", "failed", "timed_out"].includes(value.run.status)) throw new Error(`Stopped waiting for ${label}: unexpected run terminal`);
|
|
return value;
|
|
}, accept: value => { readActiveStopSettlement({ ...value, pending, dispatchMonotonicNs, bootstrap: input.bootstrap }); return true; } });
|
|
return { pending, dispatchMonotonicNs, settlement: readActiveStopSettlement({ ...final, pending, dispatchMonotonicNs, bootstrap: input.bootstrap }) };
|
|
}
|
|
export async function runNativeActiveStopFlow(input: {
|
|
page: Page; api: RunnerApi; fixtures: LiveFixtureValues; execution: MatrixExecution; nonce: string; workspacePath: string; deadlineAt: number;
|
|
remoteBootstrap?: CopilotRemoteBootstrap;
|
|
registerCleanupAssertion(callback: () => Promise<Check[]>): void;
|
|
registerBeforeEnvironmentTeardownAssertion(callback: () => Promise<Check[]>): void;
|
|
observe(issue: Row, runs: Row[]): void;
|
|
capture(id: string, label: string, file: string): Promise<void>;
|
|
evidence(name: string, value: unknown): Promise<void>;
|
|
}) {
|
|
const { api, page, fixtures, execution, nonce } = input, provider = execution.profile.qualificationCandidate;
|
|
// Browser denial before Stop has a canonical-stream oracle only for Antigravity.
|
|
const denyFirst = execution.task.id === "permission-deny-stop" && provider === "antigravity";
|
|
if ((provider !== "cursor" && provider !== "copilot" && provider !== "antigravity") || (execution.task.id !== "pending-permission-stop" && !denyFirst)) throw new Error("Unknown native active Stop case");
|
|
const remote = execution.environment.id === "daytona";
|
|
if ((!remote && execution.environment.id !== "local") || (remote && !input.remoteBootstrap)) throw new Error("Active Stop requires an isolated admitted environment");
|
|
const checks: Check[] = []; let issue: Row = {}, runs: Row[] = [], events: Row[] = [];
|
|
const check = (id: string, passed: boolean, detail: string) => { checks.push({ id, passed, detail }); expect(passed, detail).toBe(true); };
|
|
const name = `active-stop-${nonce}.txt`, local = remote ? undefined : await createDeniedTargetFixture(input.workspacePath, name);
|
|
const target = local?.targetRelativePath ?? name;
|
|
let command = provider === "cursor" && local ? cursorDeniedCommand(local.targetPath) : undefined;
|
|
const observer = remote ? undefined : observeRunProcesses();
|
|
let processes: { captured: boolean; live: number[] } = { captured: false, live: [] };
|
|
let processIdentity: string | undefined, processError = false;
|
|
const remoteObservations: ActiveStopRemoteObservation[] = [];
|
|
let retirement: ReturnType<typeof assertActiveStopRetirement> | undefined;
|
|
const samples: Array<{ phase: string; absent: boolean }> = [];
|
|
let fixture: CopilotRemoteFixture | undefined, baseline: CopilotRemoteSnapshot | undefined, sealed: CopilotRemoteSnapshot | undefined;
|
|
let completed: Awaited<ReturnType<typeof stopAtPendingPermission>> | undefined;
|
|
let denied: { pending: ActiveStopPending; stopDispatched: boolean; settlement: ReturnType<typeof readDeniedPermissionSettlement> } | undefined;
|
|
const settle = async () => denied
|
|
? readDeniedPermissionSettlement({ ...await load(), pending: denied.pending, stopDispatched: denied.stopDispatched })
|
|
: readActiveStopSettlement({ ...await load(), ...completed!, bootstrap: bootstrap() });
|
|
const observeProcesses = () => {
|
|
const run = runs[0], authority = run?.processPid ? { pid: run.processPid, groupId: run.processGroupId, startedAt: run.processStartedAt, runId: run.id } : undefined;
|
|
if (authority) { const key = JSON.stringify(authority); if (processIdentity && processIdentity !== key) processError = true; processIdentity ??= key; }
|
|
if (observer) processes = observer.sample(authority);
|
|
};
|
|
const load = async (): Promise<ActiveStopState> => {
|
|
if (issue.id) issue = await api.get<Row>(`/api/issues/${issue.id}`);
|
|
const list = await api.get<Row[]>(`/api/companies/${fixtures.company.id}/heartbeat-runs?limit=100`);
|
|
runs = await Promise.all(list.map(r => api.get<Row>(`/api/heartbeat-runs/${r.id}`)));
|
|
if (runs.length > 1) throw new Error("Native active Stop dispatched an extra run");
|
|
events = runs[0] ? await collectRunEvents<Row>((afterSeq, limit) => api.get(`/api/heartbeat-runs/${runs[0]!.id}/events?afterSeq=${afterSeq}&limit=${limit}`)) : [];
|
|
observeProcesses(); input.observe(issue, runs); return { run: runs[0] ?? {}, issue, events };
|
|
};
|
|
const sample = async (phase: string) => {
|
|
let value: boolean;
|
|
if (remote) {
|
|
if (!fixture || !baseline) throw new Error("Missing remote active Stop observer");
|
|
if (phase !== "pending") throw new Error("Remote filesystem phase requires a fresh live snapshot");
|
|
const snap = await fixture.snapshot(phase);
|
|
remoteObservations.push({ phase, source: "live-snapshot", snapshot: snap });
|
|
value = !copilotRemoteDeniedSample(snap, baseline, target, "pending").exists;
|
|
await input.evidence(`active-stop-${phase}-remote.json`, snap);
|
|
} else value = !await exists(local!.targetPath);
|
|
samples.push({ phase, absent: value }); check(`no-effect-${phase}`, value, "Exact target remains absent at the causal observation boundary");
|
|
};
|
|
const scope = (): ActiveStopScope => ({ provider, companyId: fixtures.company.id, issueId: issue.id, runId: runs[0]!.id, target, ...(command ? { commandSha256: command.commandSha256 } : {}) });
|
|
const bootstrap = (): BootstrapReadProof | undefined => fixture ? { actionFile: fixture.actionFile, events } : undefined;
|
|
const cleanup = async () => {
|
|
const receipt: Check[] = [];
|
|
try {
|
|
await load();
|
|
if (remote) {
|
|
if (!fixture || !baseline) throw new Error("Remote observer was never armed");
|
|
sealed ??= await fixture.finish(); assertCopilotRemoteRetirement(sealed, baseline); processes = sealed.processes;
|
|
} else if (processes.captured && processes.live.length) {
|
|
await pollUntil({ label: "active Stop provider retirement", deadlineAt: Date.now() + 5000, intervalMs: 100, load: async () => { observeProcesses(); return processes; }, accept: p => p.live.length === 0 });
|
|
}
|
|
if (!remote) await sample("after-cleanup");
|
|
const watch = remote ? sealed!.watcher : local!.watcher.finish();
|
|
retirement = assertActiveStopRetirement({ completed: Boolean(completed ?? denied), identityChanged: processError, processes, watcher: watch,
|
|
...(remote ? { environment: "daytona" as const, remote: { scope: scope(), observations: remoteObservations } } : { environment: "local" as const, samples }) });
|
|
if (!completed && !denied) throw new Error("Missing active Stop settlement");
|
|
await settle();
|
|
receipt.push({ id: "active-stop-retired-no-effects", passed: true, detail: remote ? "Exact run root/descendants retired with continuous no-effects proof through retirement; later UI/API checks do not claim fresh filesystem observation" : "Exact run root/descendants retired; unanswered target remained absent through cleanup" });
|
|
return receipt;
|
|
} finally {
|
|
if (timer) clearInterval(timer);
|
|
try {
|
|
await input.evidence("native-active-stop-cleanup.json", { processes, processError, samples, remoteObservations, retirement, sealed, watcher: local?.watcher.finish(), checks: receipt });
|
|
} finally {
|
|
if (remote) await fixture?.close();
|
|
}
|
|
}
|
|
};
|
|
const timer = observer ? setInterval(() => { try { observeProcesses(); } catch { processError = true; } }, 100) : undefined;
|
|
(remote ? input.registerBeforeEnvironmentTeardownAssertion : input.registerCleanupAssertion)(cleanup);
|
|
const prompt = () => provider === "cursor"
|
|
? `${execution.task.buildPrompt(nonce)}\nUse this exact native shell command once:\n${command!.command}`
|
|
: `${execution.task.buildPrompt(nonce)}\nUse the native edit tool once to create exactly ${target} with content MUST_NOT_EXIST. Do not use a shell command.`;
|
|
try {
|
|
const caller = readActiveStopCaller(await api.get("/api/health"), await api.get("/api/auth/get-session"));
|
|
const agent = await api.get<Row>(`/api/agents/${fixtures.agent.id}`);
|
|
const configured = await api.patch<Row>(`/api/agents/${fixtures.agent.id}`, { adapterConfig: { ...agent.adapterConfig, acpxPermissionMode: "approve-reads", ...(provider === "cursor" ? { acpxSessionMode: "agent" } : {}), timeoutSec: 120, lifecycleMode: "per_turn" } });
|
|
check("explicit-per-turn-policy", configured.adapterConfig?.acpxPermissionMode === "approve-reads" && configured.adapterConfig?.lifecycleMode === "per_turn" && (provider !== "cursor" || configured.adapterConfig?.acpxSessionMode === "agent"), "Agent mode and per-turn restrictive permission policy selected before startup");
|
|
const project = await api.post<Row>(`/api/companies/${fixtures.company.id}/projects`, { name: `Native active Stop ${nonce}`, executionWorkspacePolicy: { enabled: true, defaultMode: "shared_workspace", sharedWorkspaceConcurrency: "serialize", allowIssueOverride: false, environmentId: fixtures.environment.id, workspaceStrategy: { type: "project_primary" } }, workspace: { name: "Primary", sourceType: "local_path", cwd: input.workspacePath, isPrimary: true } });
|
|
if (!remote) await sample("before-request");
|
|
await createTaskThroughUi({ page, issuePrefix: fixtures.company.issuePrefix!, agentName: fixtures.agent.name, title: execution.task.buildTitle(nonce), prompt: remote ? input.remoteBootstrap!.prompt(nonce) : prompt(), workMode: "standard", projectName: project.name });
|
|
issue = (await pollUntil({ label: "browser-created active Stop task", deadlineAt: input.deadlineAt, load: async () => (await api.get<Row[]>(`/api/companies/${fixtures.company.id}/issues?limit=100`)).find(i => i.title === execution.task.buildTitle(nonce)), accept: Boolean }))!;
|
|
if (remote) {
|
|
await pollUntil({ label: "active Stop remote bootstrap", deadlineAt: input.deadlineAt, load, accept: state => state.run.status === "running" });
|
|
const bound = await input.remoteBootstrap!.bindAndRelease({ issueId: issue.id, runId: runs[0]!.id, targets: [target], actionPrompt: async value => {
|
|
fixture = value; if (provider === "cursor") command = cursorDeniedCommand(join(value.remoteCwd, target));
|
|
const prepared = await prepareCopilotRemoteAction({ fixture: value, companyId: fixtures.company.id, environmentId: fixtures.environment.id, runId: runs[0]!.id, target, prompt: prompt() });
|
|
baseline = prepared.baseline;
|
|
remoteObservations.push({ phase: "before-request", source: "live-snapshot", snapshot: baseline });
|
|
await input.evidence("active-stop-before-request-remote.json", baseline); return prepared.prompt;
|
|
} });
|
|
if (bound !== fixture) throw new Error("Remote active Stop publication identity changed");
|
|
}
|
|
const label = "unanswered native permission";
|
|
await pollUntil({ label, deadlineAt: input.deadlineAt, intervalMs: 200, load: async () => {
|
|
const state = await load(); if (["failed", "timed_out", "cancelled", "succeeded"].includes(state.run.status)) throw new Error(`Stopped waiting for ${label}: provider ended without pending callback`); return state;
|
|
}, accept: state => { observeActiveStopPending({ ...state, scope: scope(), caller, cancellationRequestId: randomUUID(), bootstrap: bootstrap() }); return true; } });
|
|
await page.goto(`/${fixtures.company.issuePrefix}/issues/${issue.identifier ?? issue.id}`);
|
|
const card = page.getByTestId("task-chat-runtime-request").filter({ visible: true });
|
|
await expect(card).toHaveCount(1); await expect(card.getByRole("button", { name: "Deny", exact: true })).toBeEnabled();
|
|
await input.capture("pending-permission", denyFirst ? "Native permission awaiting the operator's denial" : "Native permission left unanswered before Stop", "pending-permission.png"); await sample("pending");
|
|
if (denyFirst) {
|
|
const cancellationRequestId = randomUUID();
|
|
const pending = observeActiveStopPending({ ...await load(), scope: scope(), caller, cancellationRequestId, bootstrap: bootstrap() });
|
|
await input.evidence("native-permission-denial-pending.json", pending);
|
|
const route = `/api/heartbeat-runs/${pending.scope.runId}/runtime-requests/${encodeURIComponent(pending.requestId)}/resolve`;
|
|
const posted = page.waitForRequest(request => new URL(request.url()).pathname === route && request.method() === "POST");
|
|
await card.getByRole("button", { name: "Deny", exact: true }).click();
|
|
const answer = (await posted).postDataJSON();
|
|
check("browser-exact-denial", answer.turnId === pending.turnId && answer.requestKind === "permission_approval" && answer.resolution?.action === "decline",
|
|
"The browser's Deny declines this exact run, turn and native request");
|
|
// The operator then stops the unfinished task. A turn the provider already
|
|
// ended after the denial leaves nothing to stop; the settlement says which.
|
|
let stopDispatched = false;
|
|
try {
|
|
const stopped = await api.post<Row>(`/api/heartbeat-runs/${pending.scope.runId}/cancel`, { cancellationRequestId });
|
|
stopDispatched = stopped.id === pending.scope.runId;
|
|
} catch { stopDispatched = false; }
|
|
const label = "denied native permission settlement";
|
|
const attempt = async () => readDeniedPermissionSettlement({ ...await load(), pending, stopDispatched });
|
|
const settlement = await pollUntil({ label, deadlineAt: input.deadlineAt, intervalMs: 200,
|
|
load: async () => { try { return await attempt(); } catch { return null; } }, accept: Boolean })
|
|
// Surface the exact unmet condition rather than a bare timeout.
|
|
.catch(() => attempt());
|
|
denied = { pending, stopDispatched, settlement: settlement! };
|
|
check("native-denial-delivered", true, `Decline reached the exact native request before the turn ended (${denied.settlement.branch})`);
|
|
await input.evidence("native-permission-denial-settlement.json", denied);
|
|
} else {
|
|
completed = await stopAtPendingPermission({ scope: scope(), caller, bootstrap: bootstrap(), deadlineAt: input.deadlineAt, load,
|
|
retain: proof => input.evidence("native-active-stop-pending.json", proof), stop: (runId, cancellationRequestId) => api.post(`/api/heartbeat-runs/${runId}/cancel`, { cancellationRequestId }) });
|
|
check("pending-callback-cancelled", true, "Unanswered native permission closed through a cancelled provider turn and the exact caller-owned Stop acknowledgement");
|
|
await input.evidence("native-active-stop-settlement.json", completed);
|
|
}
|
|
const answered = denied?.pending ?? completed!.pending;
|
|
// Only after confirmed settlement: test the real public stale-response fence.
|
|
const response = await api.request.post(`/api/heartbeat-runs/${runs[0]!.id}/runtime-requests/${encodeURIComponent(answered.requestId)}/resolve`, { data: { turnId: answered.turnId, requestKind: "permission_approval", resolution: { action: "accept" } } });
|
|
check("stale-answer-refused", response.status() === 409, "Stopped permission rejects a later answer rather than replaying work");
|
|
await settle();
|
|
if (remote) {
|
|
// finish drains the observer's automatic retirement seal. It does not
|
|
// extend the remote watch through subsequent host UI/cleanup assertions.
|
|
sealed = await fixture!.finish(); assertCopilotRemoteRetirement(sealed, baseline!); processes = sealed.processes;
|
|
remoteObservations.push({ phase: "owned-process-retirement", source: "retirement-seal", snapshot: sealed });
|
|
await input.evidence("active-stop-owned-process-retirement-remote.json", sealed);
|
|
} else await sample("after-stop");
|
|
await page.reload();
|
|
const finalUiTimeout = () => {
|
|
const remaining = input.deadlineAt - Date.now();
|
|
if (remaining <= 0) throw new Error("Active Stop final UI deadline elapsed");
|
|
return Math.min(30_000, remaining);
|
|
};
|
|
// Absence of a permission button during React loading is not proof that a
|
|
// stopped request is unanswerable. First observe the actual task/run UI.
|
|
const stoppedRun = !denied || denied.settlement.branch === "denied_then_stopped";
|
|
if (stoppedRun) {
|
|
await expect(page.getByTestId("issue-detail-header").getByRole("button", {
|
|
name: "Change status (current: In Progress)", exact: true,
|
|
})).toBeVisible({ timeout: finalUiTimeout() });
|
|
await expect(page.getByTestId("task-chat-thread").getByTestId("task-chat-collapsible-marker")
|
|
.filter({ has: page.getByText("Run cancelled", { exact: true }) }))
|
|
.toBeVisible({ timeout: finalUiTimeout() });
|
|
}
|
|
await expect(page.getByTestId("task-chat-history-loading"))
|
|
.toHaveCount(0, { timeout: finalUiTimeout() });
|
|
await expect(card.getByRole("button", { name: "Deny", exact: true }))
|
|
.toHaveCount(0, { timeout: finalUiTimeout() });
|
|
await settle();
|
|
check("one-unfinished-cancelled-run", runs.length === 1 && (stoppedRun ? issue.status === "in_progress" && runs[0]!.status === "cancelled" : issue.status !== "done"),
|
|
"No automatic follow-up run or false task completion");
|
|
await input.capture("final-state", "Stopped native permission is no longer answerable", "final-state.png");
|
|
await input.evidence("api-state.json", { issue, run: runs[0], runs, checks, samples, remoteObservations, runEvents: events, runEventsByRun: [{ runId: runs[0]!.id, events }], activeStop: completed, permissionDenial: denied });
|
|
return { issue, runs, checks };
|
|
} finally {
|
|
// Local observation continues through cleanup. Remote cleanup revalidates
|
|
// the lifetime seal and fresh API state without claiming later file reads.
|
|
await input.evidence("native-active-stop-checks.json", { issue, runs, checks, samples, remoteObservations, completed });
|
|
}
|
|
}
|