mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-21 16:27:18 +02:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - A provider must work through normal installed packages on local and Daytona environments. > - Candidate-only success does not prove that the shipped package contains the manifest and native runtime needed for Daytona. > - The release must preserve saved-token access and task lifecycle guarantees. > - This pull request will qualify Copilot and include the exact-source remote manifest in normal release archives. > - The benefit is a reviewable part of the Copilot production release. ## Linked Issues or Issue Description Refs #15701, #15703 and #15705. Supersedes qualification work in #15563 and the original candidate in #14434. Base: #15705. ## What Changed - Keep Copilot discovery passive during reconnect reconciliation; refresh on explicit opening, account/environment changes and reconnect. - Retain the selected Product cases, permission/continuity evidence and cleanup checks. - Build the Linux provider manifest from the existing pinned Docker stage in the cloud. - Join all four native daemon receipts with that manifest before server packing. - Reject missing or incompatible remote authority during normal release assembly; retain historical workflow compatibility. - Promote the completed profile47 qualification marker, publish the current qualification record and preserve every failed attempt. - Keep one current release checklist and the shipped-canary gates explicit. ## Verification Runtime #15701 is merged at `d855e550ad8d2a267312983f26457aabf5393c3a`. History #15703 is merged at `df80616d98119cbf5abd40549794d9980a5fabf6`. Remaining source [`42bcbd61299655f7e37aabe6bb5f19bba770ad1d`](https://github.com/paperclipai/paperclip/commit/42bcbd61299655f7e37aabe6bb5f19bba770ad1d) contains the four-file authorization repair. The remaining PR trees preserve six nonoverlapping files from the newer public mainline managed-settings fix and the CI-owned lockfile. No unrelated provider is enabled. The security finding is repaired: existing-agent discovery requires `agent_config:update` before connection selection or token resolution. The saved environment is the default. Authorized editors can select a prospective environment. Both denied board-viewer and agent-reader regressions fail on the original source. All49 route tests and server typecheck pass with the fix. Denied requests perform no connection selection, credential resolution or probe. Current-head security scans pass on both remaining PRs; the repaired thread is resolved. Copilot CLI1.0.88 and profile47 retain digest `sha256:55044aa235e88b3fe36ec8a556ee1e3382590870aab907e4462ef7d64af49cea`. The [qualification record](https://github.com/paperclipai/paperclip/blob/42bcbd61299655f7e37aabe6bb5f19bba770ad1d/doc/plans/2026-10-20-copilot-qualification-v47.json) reports20/20 Product cells,154 assertions and7/7 protocol cases,46 assertions against frozen normal installed source `c2616370800f5f6df45246b0890ba35a7cd2faab`. The exact qualification model is `gpt-5.6-luna`. Every passing Product case confirms cleanup. Original failures remain recorded; automatic behavior retries are disabled. The route-only authorization repair changes no bound runtime/profile bytes and does not relabel the frozen campaign. The ordinary installed remote journey passed saved-token selection, model discovery, normal UI save/reopen, metadata-only Test, completed task, accepted receipt and exact19-byte browser download. An open model catalog caused no additional discovery requests during117seconds. Actual installed runtime smokes passed on macOS ARM64, macOS x64 under Rosetta and native Linux x64 on Daytona. Raw token browser entry was not exercised; encrypted connection creation used the normal API. The first Daytona file attempt timed out during delayed semantic dispatch; its precise stalled layer remains unresolved. Independent ordinary remote delivery and the other19 Product cells passed before one instrumented recheck passed8/8 with unchanged source,prompt,assertions and deadlines. No causal latency repair is claimed. Before the authorization repair, all four final PR heads passed required verify/E2E and fresh Greptile5/5 reviews with zero unresolved threads. Current-head CI/review is running for the two repaired heads. Local focused checks retain129 connection,59 runner,72 shared-eval and88 recovery/workspace passes, plus migration safety and token gates. The additive Copilot migration is361; released master history is preserved. [Cloud normal-package run39414239704](https://github.com/paperclipai/paperclip/actions/runs/39414239704) builds the pre-security source4f3f. All four native producers and Linux package assembly pass; the final clean installed consumers are finishing. All18 retained archives match their hashes;37,863 regular files contain zero selected credentials. That package does not contain the later route repair. The actual final published package must include it and pass the local/Daytona live canaries. The frozen Daytona image remains published and independently verified. No separate full-image scan is claimed. Docker builds run in the cloud. **Remaining:** current-head CI/review, setup and qualification merges, final publication, and ordinary local/Daytona canaries against the actual shipped package. The user explicitly authorizes the maintainer review override; CI remains a merge gate. No production deployment is claimed. Provider USD remains unknown and GitHub-attributed. ## Risks An omitted or mismatched image manifest prevents ordinary Daytona startup. Final normal archives must contain the matching image authority and platform daemons. The completed runtime campaign remains bound to its original source; the final UI-only repair needs its own normal-install setup proof. Credit notices are not measured USD receipts. Native steering, native plan mode and detached work remain outside this release. ## Model Used OpenAI Codex, based on GPT-6. The exact serving model ID and context window are not exposed in this task. Used for code changes, review and tool-assisted verification. ## 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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
276 lines
23 KiB
TypeScript
276 lines
23 KiB
TypeScript
import { readCopilotStopAcknowledgement, type CopilotStopAcknowledgement } from "./copilot-stop-acknowledgement.js";
|
|
import { copilotPendingPermissionCard } from "./copilot-permission-card.js";
|
|
import { assertCopilotProviderDeath } from "./copilot-provider-death.js";
|
|
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 { approveCopilotContextThroughUi, prepareCopilotContext } from "./copilot-context-permission.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 { assertActiveStopRetirement, readActiveStopCaller, observeActiveStopPending, readActiveStopSettlement, type ActiveStopRemoteObservation, type ActiveStopCaller, type ActiveStopPending, type ActiveStopScope } from "./copilot-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[] }
|
|
/** Observe the same public state without serializing independent reads while
|
|
* the provider is held at a permission boundary. Every result is still awaited. */
|
|
export async function readCopilotActiveStopState(api: Pick<RunnerApi, "get">, issue: Row) {
|
|
const [observedIssue, list] = await Promise.all([
|
|
issue.id ? api.get<Row>(`/api/issues/${issue.id}`) : Promise.resolve(issue),
|
|
api.get<Row[]>(`/api/companies/${issue.companyId}/heartbeat-runs?limit=100`),
|
|
]);
|
|
if (list.length > 1) throw new Error("Native active Stop dispatched an extra run");
|
|
const [runs, events] = await Promise.all([
|
|
Promise.all(list.map(run => api.get<Row>(`/api/heartbeat-runs/${run.id}`))),
|
|
list[0] ? collectRunEvents<Row>((afterSeq, limit) => api.get(
|
|
`/api/heartbeat-runs/${list[0]!.id}/events?afterSeq=${afterSeq}&limit=${limit}`,
|
|
)) : Promise.resolve([] as Row[]),
|
|
]);
|
|
return { run: runs[0] ?? {}, issue: observedIssue, runs, events };
|
|
}
|
|
/** Remote runs use the attested sandbox root, never a controller transport PID. */
|
|
export function localActiveStopProcessAuthority(run: Row | undefined, remote: boolean) {
|
|
if (remote || !run?.processPid) return undefined;
|
|
return { pid: run.processPid, groupId: run.processGroupId, startedAt: run.processStartedAt, runId: run.id };
|
|
}
|
|
/** The API's Linux proc timestamp can refresh for the same kernel process.
|
|
* Once admitted, retain the independently observed birth identity instead. */
|
|
export function activeStopOwnedProcessKey(authority: ReturnType<typeof localActiveStopProcessAuthority>, processes: {
|
|
captured: boolean; journal?: Array<{ pid: number; bootId?: string; startTicks?: string }>;
|
|
}): string | undefined {
|
|
if (!authority || !processes.captured) return undefined;
|
|
const root = processes.journal?.find(p => p.pid === authority.pid);
|
|
return JSON.stringify(root?.bootId && root.startTicks
|
|
? { pid: authority.pid, groupId: authority.groupId, runId: authority.runId, bootId: root.bootId, startTicks: root.startTicks }
|
|
: authority);
|
|
}
|
|
|
|
/** 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>;
|
|
retainAcknowledgement?(receipt: CopilotStopAcknowledgement): 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);
|
|
const stopAcknowledgement = readCopilotStopAcknowledgement(stopped,
|
|
{ companyId: input.scope.companyId, issueId: input.scope.issueId, runId: input.scope.runId, callerUserId: input.caller.userId }, cancellationRequestId, dispatchMonotonicNs);
|
|
await input.retainAcknowledgement?.(stopAcknowledgement);
|
|
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, stopAcknowledgement, bootstrap: input.bootstrap }); return true; } });
|
|
return { pending, dispatchMonotonicNs, stopAcknowledgement, settlement: readActiveStopSettlement({ ...final, pending, dispatchMonotonicNs, stopAcknowledgement, 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;
|
|
if ((provider !== "copilot") || !["pending-permission-stop", "pending-permission-provider-death"].includes(execution.task.id)) throw new Error("Unknown native active Stop case");
|
|
const remote = execution.environment.id === "daytona";
|
|
const providerDeath = execution.task.id === "pending-permission-provider-death";
|
|
let deathPending: ActiveStopPending | undefined;
|
|
let deathSettlement: ReturnType<typeof assertCopilotProviderDeath> | undefined;
|
|
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;
|
|
const observer = remote ? undefined : observeRunProcesses();
|
|
let processes: { captured: boolean; live: number[]; identityChanged?: boolean; journal?: Array<{ pid: number; bootId?: string; startTicks?: string }> } = { captured: false, live: [] };
|
|
let processIdentity: string | undefined, processError = false;
|
|
const processErrorReasons = new Set<string>();
|
|
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;
|
|
const observeProcesses = () => {
|
|
const authority = localActiveStopProcessAuthority(runs[0], remote);
|
|
if (observer) processes = observer.sample(authority);
|
|
const key = activeStopOwnedProcessKey(authority, processes);
|
|
if (key) { if (processIdentity && processIdentity !== key) { processError = true; processErrorReasons.add("owned-process-key-changed"); } processIdentity ??= key; }
|
|
if (processes.identityChanged) { processError = true; processErrorReasons.add("observed-process-birth-changed"); }
|
|
};
|
|
const load = async (): Promise<ActiveStopState> => {
|
|
const state = await readCopilotActiveStopState(api, { ...issue, companyId: fixtures.company.id });
|
|
issue = state.issue; runs = state.runs; events = state.events;
|
|
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, requireContextRead: true });
|
|
const bootstrap = (): BootstrapReadProof | undefined => fixture ? { actionFile: fixture.actionFile, events } : undefined;
|
|
const assertSettlement = async () => {
|
|
const state = await load();
|
|
if (providerDeath) {
|
|
if (!deathPending || !deathSettlement) throw new Error("Missing provider-death settlement");
|
|
return assertCopilotProviderDeath({ ...state, pending: deathPending, bootstrap: bootstrap() });
|
|
}
|
|
if (!completed) throw new Error("Missing active Stop settlement");
|
|
return readActiveStopSettlement({ ...state, ...completed, bootstrap: bootstrap() });
|
|
};
|
|
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 || deathSettlement), settlement: providerDeath ? "provider-death" : "stop", identityChanged: processError, processes, watcher: watch,
|
|
...(remote ? { environment: "daytona" as const, remote: { scope: scope(), observations: remoteObservations } } : { environment: "local" as const, samples }) });
|
|
await assertSettlement();
|
|
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, processErrorReasons: [...processErrorReasons], samples, remoteObservations, retirement, sealed, watcher: local?.watcher.finish(), checks: receipt });
|
|
} finally {
|
|
if (remote) await fixture?.close();
|
|
}
|
|
}
|
|
};
|
|
const timer = observer ? setInterval(() => { try { observeProcesses(); } catch (error) {
|
|
processError = true;
|
|
const code = (error as NodeJS.ErrnoException).code;
|
|
processErrorReasons.add(typeof code === "string" && /^[A-Z_]{1,32}$/u.test(code) ? `observation-${code}` : "process-observation-failed");
|
|
} }, 100) : undefined;
|
|
(remote ? input.registerBeforeEnvironmentTeardownAssertion : input.registerCleanupAssertion)(cleanup);
|
|
const prompt = () => `${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", timeoutSec: 120, lifecycleMode: "per_turn" } });
|
|
check("explicit-per-turn-policy", configured.adapterConfig?.acpxPermissionMode === "approve-reads" && configured.adapterConfig?.lifecycleMode === "per_turn", "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");
|
|
const createdTask = 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, requireExplicitTitle: true });
|
|
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.id === createdTask.issueId), accept: Boolean }))!;
|
|
await page.goto(`/${fixtures.company.issuePrefix}/issues/${issue.identifier ?? issue.id}`);
|
|
await prepareCopilotContext({
|
|
remoteSetup: remote ? async () => {
|
|
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;
|
|
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");
|
|
} : undefined,
|
|
approveContext: async () => {
|
|
await approveCopilotContextThroughUi({ page, companyId: fixtures.company.id, deadlineAt: input.deadlineAt, load, evidence: input.evidence });
|
|
},
|
|
});
|
|
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 = copilotPendingPermissionCard(page, target);
|
|
await expect(card).toHaveCount(1); await expect(card).toContainText(target); await expect(card.getByRole("button", { name: "Deny", exact: true })).toBeEnabled();
|
|
await input.capture("pending-permission", "Native permission left unanswered before Stop", "pending-permission.png"); await sample("pending");
|
|
if (providerDeath) {
|
|
deathPending = observeActiveStopPending({ ...await load(), scope: scope(), caller, cancellationRequestId: randomUUID(), bootstrap: bootstrap() });
|
|
await input.evidence("copilot-provider-death-pending.json", deathPending);
|
|
const fresh = observeActiveStopPending({ ...await load(), scope: scope(), caller, cancellationRequestId: deathPending.cancellationRequestId, bootstrap: bootstrap() });
|
|
if (fresh.requestRowSha256 !== deathPending.requestRowSha256 || fresh.toolStartedRowSha256 !== deathPending.toolStartedRowSha256) throw new Error("Provider death pending boundary changed");
|
|
const dispatch = remote ? await fixture!.killOwnedCopilot() : observer!.killOwnedCopilot();
|
|
await input.evidence("copilot-provider-death-dispatch.json", dispatch);
|
|
deathSettlement = await pollUntil({ label: "expired callback after owned Copilot death", deadlineAt: input.deadlineAt, intervalMs: 200, load: async () => {
|
|
const state = await load();
|
|
if (["succeeded", "cancelled", "timed_out"].includes(state.run.status)) throw new Error("Provider death produced an unexpected terminal run");
|
|
return assertCopilotProviderDeath({ ...state, pending: deathPending!, bootstrap: bootstrap() });
|
|
}, accept: Boolean });
|
|
check("provider-death-expires-pending", true, "The owned provider died and its unanswered callback expired without completing the task");
|
|
await input.evidence("copilot-provider-death-settlement.json", deathSettlement);
|
|
} else {
|
|
completed = await stopAtPendingPermission({ scope: scope(), caller, bootstrap: bootstrap(), deadlineAt: input.deadlineAt, load,
|
|
retain: proof => input.evidence("native-active-stop-pending.json", proof), retainAcknowledgement: proof => input.evidence("native-active-stop-acknowledgement.json", proof), stop: runId => api.post(`/api/heartbeat-runs/${runId}/cancel`) });
|
|
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);
|
|
}
|
|
// Only after confirmed cancellation: test the real public stale-response fence.
|
|
const response = await api.request.post(`/api/heartbeat-runs/${runs[0]!.id}/runtime-requests/${encodeURIComponent((deathPending ?? completed!.pending).requestId)}/resolve`, { data: { turnId: (deathPending ?? completed!.pending).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 assertSettlement();
|
|
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(providerDeath ? "after-provider-death" : "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.
|
|
await expect(page.getByTestId("issue-detail-header").getByRole("button", {
|
|
// Mainline includes the live blocker-attention explanation in a
|
|
// blocked status label. The API settlement still requires exact blocked.
|
|
name: providerDeath ? /^Change status \(current: Blocked(?: · [^)]+)?\)$/ : "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(providerDeath ? "Run failed" : "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 assertSettlement();
|
|
check("one-unfinished-cancelled-run", runs.length === 1 && issue.status === (providerDeath ? "blocked" : "in_progress") && runs[0]!.status === (providerDeath ? "failed" : "cancelled"), "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, providerDeath: deathSettlement });
|
|
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, deathPending, deathSettlement });
|
|
}
|
|
}
|