mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 10:07:24 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Plugin environments (for example, an agent computer) run agents as plugin Runner tasks. Core sends each task one typed credential, and gets refreshed sign-ins back through the task's `credentials` snapshot. > - #22930 let a Google Antigravity task carry a Gemini API key. A Google subscription sign-in was still refused with "Google sign-in is not supported." > - The Cloud rollout plan (#22923) needs both routes. This is gaps G3 and G4 and work item 2: deliver the sign-in, and save a rotated refresh token safely, as Codex does. > - This pull request sends the saved, sanitized sign-in as the `antigravity` `provider-env` credential under `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`. It saves a refreshed token from the snapshot only after the generation, epoch and Google account checks. > - The benefit is that a plugin (for example, the Cloud agent computer) can run an Antigravity task with a person's Google sign-in, and token refreshes are not lost or saved to the wrong account. The picker, Test and save refusals for plugin targets (item 6) and the qualification flip (item 8) stay out of scope. ## Linked Issues or Issue Description Refs #22923 Refs #22930 **What problem does this solve?** A plugin Runner task cannot use a Google sign-in for Google Antigravity. Core refuses it at run start. There is also no path to save a refresh token that the Runner rotated on the plugin's computer. **Proposed solution** Add the sign-in variable as a second `antigravity` key set in `provider-env`. Core reads the sign-in from the run's private managed home, runs it through `sanitizeAntigravityCredential`, and sends that exact output. Core saves the write-back binding (grant, secret, session epoch, and a SHA-256 of the starting sign-in) on the lease. When the task stops, Core reads the snapshot and saves a new token only if all checks pass. **Alternatives considered** A new credential type for the sign-in. `provider-env` already has the exact-set check, the credential binding contract and the cross-check against the Runner's allowlists. The Cloud plan already describes the Launcher row as "`GEMINI_API_KEY` or the sign-in key". ## What Changed - `packages/plugins/sdk/src/environment-tasks.ts`: the `antigravity` key sets are now `GEMINI_API_KEY` or `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`. A mix of both stays rejected. - `server/src/services/native-runtime/plugin-runner-credentials.ts`: with no Gemini API key, Core reads `antigravity-acp/acp_token.json` from the selected managed home and sends the sanitizer's complete output (client ID, client secret, refresh token, token URI, `scopes`, and `project_id` when present). It never sends an access token or the account email. The task needs write-back authority. A sign-in supplied through the environment is refused. An unreadable or invalid saved sign-in fails with "The selected Google Antigravity account is unavailable. Reconnect the Google account, then retry." No error contains credential text. - `server/src/services/ai-connection-runtime.ts`: a Google subscription run now returns a write-back binding with `google.credentialSha256` of the starting sign-in. - `server/src/services/managed-ai-credential-writeback.ts`: new `syncManagedAntigravityCredential`. It requires an active grant, the same secret reference and session epoch, a Google subscription connection, and a saved sign-in that still hashes to the starting generation. It verifies a changed token with the existing account check (`prepareAntigravityCredentialWriteback`) in a private temporary home, then rechecks all of the above under the account lock before it rotates the secret. It writes `ai_connection.credential_refreshed` on save. For a different account, or a connection with no saved account, it saves nothing, writes `ai_connection.credential_refresh_refused` with a plain reason, and settles as `account_refused`. - `server/src/services/plugin-task-credential-writeback.ts`: a handoff with a Google binding takes the snapshot's `provider-env` `antigravity` sign-in and uses the Google write-back. Codex is unchanged. - `server/src/services/native-runtime/native-session-executor.ts`: a sign-in credential needs a Google write-back binding, and a Codex credential needs a non-Google one. - `server/src/services/native-runtime/antigravity-runner-credentials.ts`: the account mismatch is a typed error. The message is unchanged. - Docs: `doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md` and `doc/plugins/PLUGIN_RUNNER_EXECUTION.md` describe the sign-in credential, where the Runner stages it, and the snapshot that the plugin must return. - `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed for the changed SDK source. ## Verification - Red first: with the source changes removed, 22 of the new and updated tests failed (the refusal, no write-back binding, no Google write-back). - Green after the change: - `cd server && npx vitest run src/__tests__/antigravity-plugin-task-credential-writeback.test.ts` (11 passed, embedded PostgreSQL): delivery of the exact sanitized sign-in; same-account rotation saved and logged; a second rotation during the account check saved; a different account refused and recorded in plain words; unchanged token with no Google call; reconnect (new generation and epoch) and a revoked grant discard the write-back without an export; a Google outage keeps the handoff pending and the next cleanup saves it; Codex, API-key and invalid snapshots refused. No token, client secret or access token in lease metadata, activity rows or errors. - `cd server && npx vitest run src/services/native-runtime/plugin-runner-credentials.test.ts src/__tests__/plugin-runner-credential-names.test.ts` (39 passed). The names test checks that the Runner forwards the sign-in variable to the sidecar and keeps it out of the provider process. - `cd packages/plugins/sdk && npx vitest run tests/environment-task-release-resume.test.ts tests/environment-tasks.test.ts` (104 passed) - `cd server && pnpm typecheck` (clean) - `pnpm verify` (see the CI run for broad coverage) - No live run, no Google login and no real token was used. All Google calls are fixtures. ## Risks - Low for current users. Plugin targets still refuse Antigravity in the picker, Test and save (item 6), so no existing agent reaches this path until item 6 merges. - The lease now stores a SHA-256 of the starting sign-in. It is a one-way digest of a high-entropy token, and it is the same kind of generation value that Core already derives for the local route. - If Google rotates the token during the account check and the database save then fails, the cleanup retries from the plugin's snapshot. Google does not normally rotate these refresh tokens, so this matches the local route's exposure without its recovery journal. - The Launcher must return the Runner's `auth-refresh.json` (or `acp_token.json` before lease close) in the snapshot. A Launcher that returns the starting sign-in only records `unchanged`, so no token is lost on the Core side, but a rotation on the computer would not be saved. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use (shell, file edits, test runs). Standard context window, extended reasoning. ## 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
223 lines
16 KiB
TypeScript
223 lines
16 KiB
TypeScript
import { createInterface } from "node:readline";
|
|
import { PassThrough } from "node:stream";
|
|
import { describe, expect, it } from "vitest";
|
|
import { definePlugin } from "../src/define-plugin.js";
|
|
import {
|
|
environmentTaskOperationSchema,
|
|
environmentTaskResultSchema,
|
|
parseEnvironmentTaskResult,
|
|
type PluginEnvironmentTaskOperation,
|
|
type PluginEnvironmentTaskParams,
|
|
type PluginEnvironmentTaskResult,
|
|
} from "../src/environment-tasks.js";
|
|
import { createRequest, isJsonRpcResponse, parseMessage, serializeMessage, type JsonRpcResponse } from "../src/protocol.js";
|
|
import { startWorkerRpcHost } from "../src/worker-rpc-host.js";
|
|
|
|
const identity = { runnerInstanceId: "runner", environmentLeaseId: "lease", runId: "source-run",
|
|
normalizedSessionId: "session", turnId: "turn", itemId: "item" };
|
|
const release = { kind: "release", identity } as const;
|
|
const resume = { kind: "resume", identity, bootstrapTicket: "fixture-ticket" } as const;
|
|
const ownership = {
|
|
kind: "ensure_ownership", operationId: "9df4526f-36c5-4fba-9cf6-3c4fd317f531", identity,
|
|
sourceTaskId: "source-task", sourceGeneration: "source-generation", targetGeneration: "target-generation", policy: "reclaim_if_needed",
|
|
} as const;
|
|
const description = { kind: "description", taskId: "task", runner: { version: "fixture", digest: `sha256:${"a".repeat(64)}` } };
|
|
const submit = { kind: "submit", projectIds: [], bootstrapTicket: "fixture-ticket", runner: { harness: "claude", protocolMin: 1, protocolMax: 3,
|
|
runnerId: "runner", leaseId: "lease", runId: "run", sessionId: "session", turnId: "turn", itemId: "item" } } as const;
|
|
const credentials: [string, unknown, boolean][] = [
|
|
["a Claude OAuth token", { type: "claude-env", environment: { CLAUDE_CODE_OAUTH_TOKEN: "fixture-oauth" } }, true],
|
|
["a Claude API key", { type: "claude-env", environment: { ANTHROPIC_API_KEY: "fixture-key" } }, true],
|
|
["a Codex auth file", { type: "codex-auth-json", authJson: "{\"tokens\":{}}" }, true],
|
|
["two Claude credentials", { type: "claude-env", environment: { CLAUDE_CODE_OAUTH_TOKEN: "a", ANTHROPIC_API_KEY: "b" } }, false],
|
|
["no Claude credential", { type: "claude-env", environment: {} }, false],
|
|
["an unsupported Claude variable", { type: "claude-env", environment: { ANTHROPIC_BASE_URL: "https://example.test" } }, false],
|
|
["an empty value", { type: "claude-env", environment: { CLAUDE_CODE_OAUTH_TOKEN: "" } }, false],
|
|
["a NUL byte", { type: "claude-env", environment: { CLAUDE_CODE_OAUTH_TOKEN: "a\0b" } }, false],
|
|
["an oversized value", { type: "codex-auth-json", authJson: "x".repeat(65_537) }, false],
|
|
["an unknown type", { type: "gemini-env", environment: { GEMINI_API_KEY: "fixture" } }, false],
|
|
["an extra field", { type: "codex-auth-json", authJson: "{}", path: "/home/agent/.codex" }, false],
|
|
["an xAI API key for Grok", { type: "provider-env", provider: "grok", environment: { XAI_API_KEY: "fixture-xai" } }, true],
|
|
["a Copilot token", { type: "provider-env", provider: "copilot", environment: { COPILOT_GITHUB_TOKEN: "fixture-copilot" } }, true],
|
|
["an OpenRouter key for OpenCode", { type: "provider-env", provider: "opencode", environment: { OPENROUTER_API_KEY: "fixture-openrouter" } }, true],
|
|
["an OpenCode gateway", { type: "provider-env", provider: "opencode",
|
|
environment: { PAPERCLIP_AI_PROVIDER_URL: "https://gateway.example.test/v1", PAPERCLIP_AI_PROVIDER_KEY: "fixture-gateway" } }, true],
|
|
["half of an OpenCode gateway", { type: "provider-env", provider: "opencode", environment: { PAPERCLIP_AI_PROVIDER_URL: "https://gateway.example.test/v1" } }, false],
|
|
["a mixed OpenCode set", { type: "provider-env", provider: "opencode",
|
|
environment: { OPENROUTER_API_KEY: "fixture-openrouter", PAPERCLIP_AI_PROVIDER_KEY: "fixture-gateway" } }, false],
|
|
["two OpenCode sets", { type: "provider-env", provider: "opencode", environment: { OPENROUTER_API_KEY: "fixture-openrouter",
|
|
PAPERCLIP_AI_PROVIDER_URL: "https://gateway.example.test/v1", PAPERCLIP_AI_PROVIDER_KEY: "fixture-gateway" } }, false],
|
|
["another provider's variable", { type: "provider-env", provider: "grok", environment: { COPILOT_GITHUB_TOKEN: "fixture-copilot" } }, false],
|
|
["an extra provider variable", { type: "provider-env", provider: "grok", environment: { XAI_API_KEY: "fixture-xai", XAI_BASE_URL: "https://router.example.test" } }, false],
|
|
["no provider variable", { type: "provider-env", provider: "copilot", environment: {} }, false],
|
|
["an empty provider value", { type: "provider-env", provider: "copilot", environment: { COPILOT_GITHUB_TOKEN: "" } }, false],
|
|
["a NUL byte in a provider value", { type: "provider-env", provider: "grok", environment: { XAI_API_KEY: "a\0b" } }, false],
|
|
["an oversized provider value", { type: "provider-env", provider: "grok", environment: { XAI_API_KEY: "x".repeat(65_537) } }, false],
|
|
["an unsupported provider", { type: "provider-env", provider: "gemini", environment: { GEMINI_API_KEY: "fixture-gemini" } }, false],
|
|
["a provider credential without a provider", { type: "provider-env", environment: { XAI_API_KEY: "fixture-xai" } }, false],
|
|
["an extra provider credential field", { type: "provider-env", provider: "grok", environment: { XAI_API_KEY: "fixture-xai" }, home: "/home/agent" }, false],
|
|
["a Gemini API key for Antigravity", { type: "provider-env", provider: "antigravity", environment: { GEMINI_API_KEY: "fixture-gemini" } }, true],
|
|
["an Antigravity sign-in document", { type: "provider-env", provider: "antigravity",
|
|
environment: { PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "{\"refresh_token\":\"fixture\"}" } }, true],
|
|
["a Gemini API key mixed with a sign-in document", { type: "provider-env", provider: "antigravity",
|
|
environment: { GEMINI_API_KEY: "fixture-gemini", PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "{\"refresh_token\":\"fixture\"}" } }, false],
|
|
["a Google API key for Antigravity", { type: "provider-env", provider: "antigravity", environment: { GOOGLE_API_KEY: "fixture-google" } }, false],
|
|
["a Gemini API key with Google routing", { type: "provider-env", provider: "antigravity",
|
|
environment: { GEMINI_API_KEY: "fixture-gemini", GOOGLE_GEMINI_BASE_URL: "https://router.example.test" } }, false],
|
|
["no Antigravity variable", { type: "provider-env", provider: "antigravity", environment: {} }, false],
|
|
["an empty Gemini API key", { type: "provider-env", provider: "antigravity", environment: { GEMINI_API_KEY: "" } }, false],
|
|
["a Gemini API key for another provider", { type: "provider-env", provider: "copilot", environment: { GEMINI_API_KEY: "fixture-gemini" } }, false],
|
|
];
|
|
|
|
async function invoke(operation: unknown, handler: (params: PluginEnvironmentTaskParams) => Promise<PluginEnvironmentTaskResult>) {
|
|
const stdin = new PassThrough(), stdout = new PassThrough(), lines = createInterface({ input: stdout });
|
|
const worker = startWorkerRpcHost({ stdin, stdout, plugin: definePlugin({ async setup() {}, onEnvironmentTask: handler }) });
|
|
try {
|
|
const response = new Promise<JsonRpcResponse>(resolve => lines.on("line", line => {
|
|
const message = parseMessage(line);
|
|
if (isJsonRpcResponse(message)) resolve(message);
|
|
}));
|
|
stdin.write(serializeMessage(createRequest("environmentTask", { companyId: "company", taskId: "task",
|
|
runId: "claimant-run", lease: { providerLeaseId: "task" }, operation }, "lifecycle")));
|
|
return await response;
|
|
} finally { worker.stop(); lines.close(); stdin.destroy(); stdout.destroy(); }
|
|
}
|
|
|
|
describe("release and resume task contract", () => {
|
|
it("keeps the capability optional and independent of warm and source recovery support", () => {
|
|
for (const capabilities of [{}, { releaseResumeVersion: 1 }, { warmTaskVersion: 1 },
|
|
{ codexSourceRecoveryVersion: 1 }, { acpxSourceRecoveryVersion: 1 }]) {
|
|
expect(environmentTaskResultSchema.parse({ ...description, ...capabilities })).toEqual({ ...description, ...capabilities });
|
|
}
|
|
expect(environmentTaskResultSchema.safeParse({ ...description, releaseResumeVersion: 2 }).success).toBe(false);
|
|
expect(environmentTaskResultSchema.parse({ ...description, resumeLaunchInputsVersion: 1 })).toEqual({ ...description, resumeLaunchInputsVersion: 1 });
|
|
expect(environmentTaskResultSchema.safeParse({ ...description, resumeLaunchInputsVersion: 2 }).success).toBe(false);
|
|
expect(environmentTaskResultSchema.parse({ ...description, resumeRelaunchedRunnerVersion: 1 })).toEqual({ ...description, resumeRelaunchedRunnerVersion: 1 });
|
|
expect(environmentTaskResultSchema.safeParse({ ...description, resumeRelaunchedRunnerVersion: 2 }).success).toBe(false);
|
|
});
|
|
|
|
it("reports the Runner build a resume relaunched on only when asked", () => {
|
|
expect(environmentTaskOperationSchema.parse({ ...resume, relaunchedRunnerVersion: 1 })).toEqual({ ...resume, relaunchedRunnerVersion: 1 });
|
|
expect(environmentTaskOperationSchema.safeParse({ ...resume, relaunchedRunnerVersion: 2 }).success).toBe(false);
|
|
const runner = { version: "0.4.1", digest: `sha256:${"b".repeat(64)}` };
|
|
const result = { kind: "resume", taskId: "task", outcome: "resumed", runner };
|
|
expect(parseEnvironmentTaskResult(resume, "task", result)).toEqual(result);
|
|
expect(environmentTaskResultSchema.safeParse({ ...result, runner: { ...runner, digest: "sha256:short" } }).success).toBe(false);
|
|
expect(environmentTaskResultSchema.safeParse({ ...result, runner: { ...runner, extra: true } }).success).toBe(false);
|
|
});
|
|
|
|
it("relaunches as the claimant's identity only when asked, and reports the build", () => {
|
|
expect(environmentTaskResultSchema.parse({ ...description, resumeIdentityVersion: 1 })).toEqual({ ...description, resumeIdentityVersion: 1 });
|
|
expect(environmentTaskResultSchema.safeParse({ ...description, resumeIdentityVersion: 2 }).success).toBe(false);
|
|
const runner = { runId: "claimant-run", turnId: "turn-claimant-run", itemId: "item-claimant-run" };
|
|
const relaunch = { ...resume, runner };
|
|
expect(environmentTaskOperationSchema.parse(relaunch)).toEqual(relaunch);
|
|
for (const changed of [{ ...runner, sessionId: "other" }, { ...runner, runId: undefined }, { ...runner, turnId: "" }]) {
|
|
expect(environmentTaskOperationSchema.safeParse({ ...resume, runner: changed }).success).toBe(false);
|
|
}
|
|
const build = { version: "0.4.1", digest: `sha256:${"b".repeat(64)}` };
|
|
const resumed = { kind: "resume", taskId: "task", outcome: "resumed", runner: build };
|
|
expect(parseEnvironmentTaskResult(relaunch, "task", resumed)).toEqual(resumed);
|
|
const archivedState = { schema: "paperclip.runner.durable.state.v1", ...identity, lifecycle: "ready" };
|
|
expect(() => parseEnvironmentTaskResult(relaunch, "task", { ...resumed, archivedState })).toThrow();
|
|
expect(() => parseEnvironmentTaskResult(relaunch, "task", { ...resumed, runner: undefined })).toThrow();
|
|
expect(parseEnvironmentTaskResult(relaunch, "task", { kind: "resume", taskId: "task", outcome: "unavailable" }))
|
|
.toEqual({ kind: "resume", taskId: "task", outcome: "unavailable" });
|
|
});
|
|
|
|
it.each(credentials)("validates %s on resume as on submit", (_label, credential, valid) => {
|
|
expect(environmentTaskOperationSchema.safeParse({ ...submit, credential }).success).toBe(valid);
|
|
expect(environmentTaskOperationSchema.safeParse({ ...resume, credential }).success).toBe(valid);
|
|
});
|
|
|
|
it("dispatches a resume credential through the serialized worker RPC", async () => {
|
|
const operation = { ...resume, credential: { type: "claude-env", environment: { CLAUDE_CODE_OAUTH_TOKEN: "fixture-oauth" } } } as const;
|
|
const result = { kind: "resume", taskId: "task", outcome: "resumed" } as const;
|
|
expect(await invoke(operation, async params => {
|
|
expect(params.operation).toEqual(operation);
|
|
return result;
|
|
})).toMatchObject({ result });
|
|
});
|
|
|
|
it.each([release, resume])("requires the exact durable identity for $kind", operation => {
|
|
expect(environmentTaskOperationSchema.parse(operation)).toEqual(operation);
|
|
for (const field of Object.keys(identity)) {
|
|
expect(environmentTaskOperationSchema.safeParse({ ...operation, identity: { ...identity, [field]: undefined } }).success).toBe(false);
|
|
}
|
|
expect(environmentTaskOperationSchema.safeParse({ ...operation, identity: { ...identity, targetRunId: "other" } }).success).toBe(false);
|
|
expect(environmentTaskOperationSchema.safeParse({ ...operation, cancelActiveWork: true }).success).toBe(false);
|
|
});
|
|
|
|
it.each([undefined, "", "\0", "x".repeat(65_537)])("rejects a missing or invalid resume ticket", bootstrapTicket => {
|
|
expect(environmentTaskOperationSchema.safeParse({ ...resume, bootstrapTicket }).success).toBe(false);
|
|
});
|
|
|
|
it("matches each operation to its own closed result and task", () => {
|
|
const released = { kind: "released", taskId: "task" };
|
|
expect(parseEnvironmentTaskResult(release, "task", released)).toEqual(released);
|
|
for (const outcome of ["resumed", "unavailable"]) {
|
|
const result = { kind: "resume", taskId: "task", outcome };
|
|
expect(parseEnvironmentTaskResult(resume, "task", result)).toEqual(result);
|
|
expect(() => parseEnvironmentTaskResult(release, "task", result)).toThrow();
|
|
}
|
|
for (const operation of [release, resume]) {
|
|
expect(() => parseEnvironmentTaskResult(operation, "task", { kind: "accepted", taskId: "task" })).toThrow();
|
|
const result = operation.kind === "release" ? released : { kind: "resume", taskId: "task", outcome: "resumed" };
|
|
expect(() => parseEnvironmentTaskResult(operation, "other-task", result)).toThrow();
|
|
}
|
|
expect(() => parseEnvironmentTaskResult(resume, "task", { kind: "resume", taskId: "task", outcome: "unknown" })).toThrow();
|
|
expect(environmentTaskResultSchema.safeParse({ ...released, retained: true }).success).toBe(false);
|
|
expect(environmentTaskResultSchema.safeParse({ kind: "resume", taskId: "task", outcome: "resumed", bootstrapTicket: "fixture-ticket" }).success).toBe(false);
|
|
});
|
|
|
|
it.each([release, resume])("dispatches $kind through the serialized worker RPC", async operation => {
|
|
const result: PluginEnvironmentTaskResult = operation.kind === "release" ? { kind: "released", taskId: "task" }
|
|
: { kind: "resume", taskId: "task", outcome: "resumed" };
|
|
const response = await invoke(operation, async params => {
|
|
expect(params.operation).toEqual(operation);
|
|
expect(params.runId).toBe("claimant-run");
|
|
return result;
|
|
});
|
|
expect(response).toMatchObject({ result });
|
|
});
|
|
|
|
it("passes known absence through RPC without treating it as a successful reservation", async () => {
|
|
expect(await invoke(resume, async () => ({ kind: "resume", taskId: "task", outcome: "unavailable" })))
|
|
.toMatchObject({ result: { kind: "resume", taskId: "task", outcome: "unavailable" } });
|
|
});
|
|
|
|
it("binds a declarative ownership response to the exact worker request", async () => {
|
|
for (const status of ["pending", "ready"] as const) {
|
|
const result = { kind: "ownership", status, taskId: "task", operationId: ownership.operationId,
|
|
targetGeneration: ownership.targetGeneration } as const;
|
|
expect(await invoke(ownership, async params => {
|
|
expect(params.operation).toEqual(ownership);
|
|
return result;
|
|
})).toMatchObject({ result });
|
|
for (const changes of [
|
|
{ taskId: "another-task" },
|
|
{ operationId: "1f083ad0-a357-4f14-ad46-e9df981845b5" },
|
|
{ targetGeneration: "stale-generation" },
|
|
]) {
|
|
expect(await invoke(ownership, async () => ({ ...result, ...changes }))).toHaveProperty("error");
|
|
}
|
|
}
|
|
});
|
|
|
|
it.each(["source mismatch", "claim conflict", "authentication failed", "transport timeout"])("keeps %s as an RPC error", async message => {
|
|
expect(await invoke(resume, async () => { throw new Error(message); })).toHaveProperty("error");
|
|
});
|
|
|
|
it("rejects cross-task and wrong-kind replies at the worker boundary", async () => {
|
|
for (const result of [{ kind: "resume", taskId: "other", outcome: "resumed" }, { kind: "accepted", taskId: "task" }] as PluginEnvironmentTaskResult[]) {
|
|
expect(await invoke(resume, async () => result)).toHaveProperty("error");
|
|
}
|
|
});
|
|
|
|
it("preserves legacy describe and stop replies through RPC", async () => {
|
|
expect(await invoke({ kind: "describe" }, async () => description as PluginEnvironmentTaskResult)).toMatchObject({ result: description });
|
|
const operation: PluginEnvironmentTaskOperation = { kind: "stop" };
|
|
expect(await invoke(operation, async () => ({ kind: "accepted", taskId: "task" })))
|
|
.toMatchObject({ result: { kind: "accepted", taskId: "task" } });
|
|
});
|
|
});
|