Files
PaperClipAI/packages/plugins/sdk/tests/host-client-factory.test.ts
T
Nicky LeachandClaude Opus 5.5 fa283aeea2 feat(plugins): let an environment plugin report its task's startup stage (#22970)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A run's environment can come from a plugin, which runs the agent's
task through environment task operations such as prepare and submit.
> - The stacked pull requests below this one make Core publish each
run's startup stage from the steps it times, and show that stage in the
task view.
> - Core cannot see inside a plugin's task operation. A slow step there,
such as a stopped machine starting, shows as whatever stage Core was in
when it called the plugin.
> - This pull request lets an environment plugin report its task's
stage, from the same closed list Core uses, while one of its task
operations runs.
> - The benefit is that the task view names the real reason a
plugin-backed turn has not started yet, with no stages only plugins know
about.

## Linked Issues or Issue Description

No public issue exists. Stacked on #22956 (UI), which is stacked on
#22953 (server).

**Subsystem affected**
Plugin SDK (`packages/plugins/sdk`), plugin host services and
environment task runtime (`server/src/services`), and the plugin docs.

**Problem or motivation**
A plugin's environment task operation can take many seconds, for example
when it starts a stopped machine. The task view keeps the stage Core
showed when it called the plugin, so the wait has the wrong name.

**Proposed solution**
Add `ctx.environmentTasks.reportStartupStage({ taskId, stage })`. Core
accepts a report only while one of that plugin's task operations for a
run is in flight. The reported stage shows instead of Core's stage until
the operation returns.

**Alternatives considered**
- Free-form status text from the plugin. It would not match Core's
stages, and each plugin would word the same step in a different way.
- Stages that only plugins can report. One shared list keeps Core and
plugins aligned, so the task view needs no plugin-specific labels.

## What Changed

- SDK: `ctx.environmentTasks.reportStartupStage({ taskId, stage })` and
the `environmentTasks.reportStartupStage` host method. The call needs
the existing `environment.drivers.register` capability. The test harness
records reports in `startupStageReports`.
- Server: the environment task runtime opens a reporting window for the
plugin and task while each task operation for a run is in flight. Inside
the window, the plugin's stage shows instead of Core's stage, and may be
an earlier stage (for example `starting_environment` during submit).
When the last operation returns, Core's stage shows again.
- Server: Core ignores a report outside a window, for another plugin's
task, with an unknown stage, or after the agent's turn starts. A report
never fails the task operation.
- Docs: `PLUGIN_ENVIRONMENT_TASKS.md` has a "Startup stages" section,
and `PLUGIN_SPEC.md` lists `ctx.environmentTasks`.
- `tests/runner-e2e/source-sdk-public-inputs.json`: regenerated for the
changed SDK sources.

## Verification

- `npx vitest run tests/host-client-factory.test.ts
tests/testing-environment-tasks.test.ts` in `packages/plugins/sdk`: the
capability gate and the harness record (26 tests pass).
- `npx vitest run src/services/run-startup-stage.test.ts
src/__tests__/environment-task-runtime.test.ts` in `server`: windows
open and close per operation, overlapping operations, reports outside a
window or after the turn starts are ignored, an earlier stage shows
during the window, and a report from inside a real task operation
reaches the run (78 tests pass).
- `node tests/runner-e2e/source-sdk-public-inputs.mjs <head> --write`
reports no changes.
- `pnpm --filter @paperclipai/plugin-sdk typecheck` and `pnpm --filter
@paperclipai/server typecheck` pass.
- CI runs the full suite.

## Risks

- Low risk. The call is new and optional. Plugins that do not call it
see no change.
- A plugin can only report for its own task, only while Core waits on
one of its operations, and only from the shared stage list. It cannot
change the stage after the agent's turn starts.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits).

## 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 Opus 5.5 <noreply@anthropic.com>
2026-11-30 16:22:09 +00:00

489 lines
20 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import type { HostServices } from "../src/host-client-factory.js";
import {
CapabilityDeniedError,
createHostClientHandlers,
InvocationScopeDeniedError,
} from "../src/host-client-factory.js";
import { PLUGIN_RPC_ERROR_CODES } from "../src/protocol.js";
describe("createHostClientHandlers invocation company scope", () => {
it("rejects worker-selected config and secret company ids without a host invocation scope", async () => {
const configGet = vi.fn(async () => ({ apiKeyRef: "unreachable" }));
const secretsResolve = vi.fn(async () => "unreachable");
const services = {
config: { get: configGet },
secrets: { resolve: secretsResolve },
} as unknown as HostServices;
const handlers = createHostClientHandlers({
pluginId: "paperclip.test",
capabilities: ["secrets.read-ref"],
services,
});
await expect(
handlers["config.get"]({ companyId: "company-a" }),
).rejects.toBeInstanceOf(InvocationScopeDeniedError);
await expect(
handlers["secrets.resolve"]({
companyId: "company-a",
secretRef: { type: "secret_ref", secretId: "secret-a" },
}),
).rejects.toBeInstanceOf(InvocationScopeDeniedError);
expect(configGet).not.toHaveBeenCalled();
expect(secretsResolve).not.toHaveBeenCalled();
});
it("allows explicit config and secret company ids only when they match the host invocation scope", async () => {
const configGet = vi.fn(async () => ({ apiKeyRef: "ref" }));
const secretsResolve = vi.fn(async () => "resolved");
const services = {
config: { get: configGet },
secrets: { resolve: secretsResolve },
} as unknown as HostServices;
const handlers = createHostClientHandlers({
pluginId: "paperclip.test",
capabilities: ["secrets.read-ref"],
services,
});
const context = { invocationScope: { companyId: "company-a" } };
await expect(
handlers["config.get"]({ companyId: "company-a" }, context),
).resolves.toEqual({ apiKeyRef: "ref" });
await expect(
handlers["secrets.resolve"]({
companyId: "company-a",
secretRef: { type: "secret_ref", secretId: "secret-a" },
}, context),
).resolves.toBe("resolved");
expect(configGet).toHaveBeenCalledWith({ companyId: "company-a" }, context);
expect(secretsResolve).toHaveBeenCalledWith({
companyId: "company-a",
secretRef: { type: "secret_ref", secretId: "secret-a" },
}, context);
});
it("rejects company-scoped host calls outside the current invocation company", async () => {
const projectsList = vi.fn(async () => []);
const services = {
projects: {
list: projectsList,
},
} as unknown as HostServices;
const handlers = createHostClientHandlers({
pluginId: "paperclip.test",
capabilities: ["projects.read"],
services,
});
await expect(
handlers["projects.list"](
{ companyId: "company-b" },
{ invocationScope: { companyId: "company-a" } },
),
).rejects.toBeInstanceOf(InvocationScopeDeniedError);
await expect(
handlers["projects.list"](
{ companyId: "company-b" },
{ invocationScope: { companyId: "company-a" } },
),
).rejects.toMatchObject({
code: PLUGIN_RPC_ERROR_CODES.INVOCATION_SCOPE_DENIED,
});
expect(projectsList).not.toHaveBeenCalled();
});
it("filters companies.list to the current invocation company", async () => {
const services = {
companies: {
list: vi.fn(async () => [
{ id: "company-a", name: "Company A" },
{ id: "company-b", name: "Company B" },
]),
},
} as unknown as HostServices;
const handlers = createHostClientHandlers({
pluginId: "paperclip.test",
capabilities: ["companies.read"],
services,
});
await expect(
handlers["companies.list"](
{},
{ invocationScope: { companyId: "company-a" } },
),
).resolves.toEqual([{ id: "company-a", name: "Company A" }]);
});
it("rejects company-scope store access for a different company", async () => {
const stateGet = vi.fn(async () => null);
const services = {
state: {
get: stateGet,
},
} as unknown as HostServices;
const handlers = createHostClientHandlers({
pluginId: "paperclip.test",
capabilities: ["plugin.state.read"],
services,
});
await expect(
handlers["state.get"](
{ scopeKind: "company", scopeId: "company-b", stateKey: "settings" },
{ invocationScope: { companyId: "company-a" } },
),
).rejects.toBeInstanceOf(InvocationScopeDeniedError);
expect(stateGet).not.toHaveBeenCalled();
});
it.each([
[
"access.members.list",
"access.members.read",
{ companyId: "company-a" },
(services: HostServices) => vi.mocked(services.access.listMembers),
],
[
"access.members.update",
"access.members.write",
{ companyId: "company-a", memberId: "member-a", patch: { status: "active" } },
(services: HostServices) => vi.mocked(services.access.updateMember),
],
[
"authorization.grants.set",
"authorization.grants.write",
{ companyId: "company-a", principalType: "agent", principalId: "agent-a", grants: [] },
(services: HostServices) => vi.mocked(services.authorization.setGrants),
],
[
"authorization.policies.update",
"authorization.policies.write",
{ companyId: "company-a", resourceType: "agent", resourceId: "agent-a", policy: null },
(services: HostServices) => vi.mocked(services.authorization.updatePolicy),
],
[
"authorization.audit.search",
"authorization.audit.read",
{ companyId: "company-a" },
(services: HostServices) => vi.mocked(services.authorization.searchAudit),
],
] as const)(
"rejects %s when the plugin lacks %s",
async (method, capability, params, getDelegate) => {
const services = {
access: {
listMembers: vi.fn(async () => []),
updateMember: vi.fn(async () => ({ id: "member-a" })),
},
authorization: {
setGrants: vi.fn(async () => []),
updatePolicy: vi.fn(async () => ({ policy: null })),
searchAudit: vi.fn(async () => []),
},
} as unknown as HostServices;
const handlers = createHostClientHandlers({
pluginId: "paperclip.test",
capabilities: [],
services,
});
await expect(
(handlers as Record<string, (input: unknown) => Promise<unknown>>)[method](params),
).rejects.toMatchObject({
name: "CapabilityDeniedError",
message: expect.stringContaining(capability),
});
await expect(
(handlers as Record<string, (input: unknown) => Promise<unknown>>)[method](params),
).rejects.toBeInstanceOf(CapabilityDeniedError);
expect(getDelegate(services)).not.toHaveBeenCalled();
},
);
it("checks invocation company scope before exposing authorization data", async () => {
const searchAudit = vi.fn(async () => []);
const services = {
authorization: {
searchAudit,
},
} as unknown as HostServices;
const handlers = createHostClientHandlers({
pluginId: "paperclip.test",
capabilities: ["authorization.audit.read"],
services,
});
await expect(
handlers["authorization.audit.search"](
{ companyId: "company-b" },
{ invocationScope: { companyId: "company-a" } },
),
).rejects.toBeInstanceOf(InvocationScopeDeniedError);
expect(searchAudit).not.toHaveBeenCalled();
});
it("rejects a human-attributed createComment call when only issue.comments.create is granted", async () => {
const createComment = vi.fn(async () => ({ id: "comment-1" }));
const services = {
issues: { createComment },
} as unknown as HostServices;
const handlers = createHostClientHandlers({
pluginId: "paperclip.test",
capabilities: ["issue.comments.create"],
services,
});
const context = { invocationScope: { companyId: "company-a" } };
await expect(
handlers["issues.createComment"]({
issueId: "issue-a",
body: "hello",
companyId: "company-a",
actorUserId: "user-a",
}, context),
).rejects.toBeInstanceOf(CapabilityDeniedError);
expect(createComment).not.toHaveBeenCalled();
});
it("allows a human-attributed createComment call once issue.comments.create_human_attributed is also granted", async () => {
const createComment = vi.fn(async () => ({ id: "comment-1" }));
const services = {
issues: { createComment },
} as unknown as HostServices;
const handlers = createHostClientHandlers({
pluginId: "paperclip.test",
capabilities: ["issue.comments.create", "issue.comments.create_human_attributed"],
services,
});
const context = { invocationScope: { companyId: "company-a" } };
await expect(
handlers["issues.createComment"]({
issueId: "issue-a",
body: "hello",
companyId: "company-a",
actorUserId: "user-a",
}, context),
).resolves.toEqual({ id: "comment-1" });
expect(createComment).toHaveBeenCalledWith({
issueId: "issue-a",
body: "hello",
companyId: "company-a",
actorUserId: "user-a",
});
});
it("still allows a plain agent-attributed createComment call without the human-attribution capability", async () => {
const createComment = vi.fn(async () => ({ id: "comment-2" }));
const services = {
issues: { createComment },
} as unknown as HostServices;
const handlers = createHostClientHandlers({
pluginId: "paperclip.test",
capabilities: ["issue.comments.create"],
services,
});
const context = { invocationScope: { companyId: "company-a" } };
await expect(
handlers["issues.createComment"]({
issueId: "issue-a",
body: "hello",
companyId: "company-a",
authorAgentId: "agent-a",
}, context),
).resolves.toEqual({ id: "comment-2" });
expect(createComment).toHaveBeenCalled();
});
});
describe("createHostClientHandlers capability gating for LOOA-641 methods", () => {
const context = { invocationScope: { companyId: "company-a" } };
it("denies issues.respondInteraction without issue.interactions.respond", async () => {
const respondInteraction = vi.fn(async () => ({ interaction: { id: "i" }, applied: true }));
const services = { issues: { respondInteraction } } as unknown as HostServices;
const handlers = createHostClientHandlers({
pluginId: "paperclip.test",
// A read grant must not confer the ability to respond.
capabilities: ["issue.interactions.read"],
services,
});
await expect(
handlers["issues.respondInteraction"]({
issueId: "issue-a", interactionId: "int-a", companyId: "company-a", action: "accept", actorUserId: "user-a",
}, context),
).rejects.toBeInstanceOf(CapabilityDeniedError);
expect(respondInteraction).not.toHaveBeenCalled();
});
it("allows issues.respondInteraction with issue.interactions.respond", async () => {
const respondInteraction = vi.fn(async () => ({ interaction: { id: "i" }, applied: true }));
const services = { issues: { respondInteraction } } as unknown as HostServices;
const handlers = createHostClientHandlers({
pluginId: "paperclip.test",
capabilities: ["issue.interactions.respond"],
services,
});
await expect(
handlers["issues.respondInteraction"]({
issueId: "issue-a", interactionId: "int-a", companyId: "company-a", action: "accept", actorUserId: "user-a",
}, context),
).resolves.toEqual({ interaction: { id: "i" }, applied: true });
expect(respondInteraction).toHaveBeenCalledOnce();
});
it("gates startup stage reports on environment.drivers.register", async () => {
const reportStartupStage = vi.fn(async () => undefined);
const services = { environmentTasks: { reportStartupStage } } as unknown as HostServices;
const params = { taskId: "task-a", stage: "starting_environment" as const };
const denied = createHostClientHandlers({ pluginId: "paperclip.test", capabilities: ["issues.read"], services });
await expect(denied["environmentTasks.reportStartupStage"](params, context)).rejects.toBeInstanceOf(CapabilityDeniedError);
expect(reportStartupStage).not.toHaveBeenCalled();
const allowed = createHostClientHandlers({ pluginId: "paperclip.test", capabilities: ["environment.drivers.register"], services });
await expect(allowed["environmentTasks.reportStartupStage"](params, context)).resolves.toBeUndefined();
expect(reportStartupStage).toHaveBeenCalledExactlyOnceWith(params);
});
it("denies approvals.decide without approvals.respond", async () => {
const decide = vi.fn(async () => ({ approval: { id: "a" }, applied: true }));
const services = { approvals: { decide } } as unknown as HostServices;
const handlers = createHostClientHandlers({
pluginId: "paperclip.test",
// A read grant must not confer the ability to decide.
capabilities: ["approvals.read"],
services,
});
await expect(
handlers["approvals.decide"]({
approvalId: "a", companyId: "company-a", action: "approve", actorUserId: "user-a",
}, context),
).rejects.toBeInstanceOf(CapabilityDeniedError);
expect(decide).not.toHaveBeenCalled();
});
it("allows approvals.decide with approvals.respond", async () => {
const decide = vi.fn(async () => ({ approval: { id: "a" }, applied: true }));
const services = { approvals: { decide } } as unknown as HostServices;
const handlers = createHostClientHandlers({
pluginId: "paperclip.test",
capabilities: ["approvals.respond"],
services,
});
await expect(
handlers["approvals.decide"]({
approvalId: "a", companyId: "company-a", action: "approve", actorUserId: "user-a",
}, context),
).resolves.toEqual({ approval: { id: "a" }, applied: true });
expect(decide).toHaveBeenCalledOnce();
});
it("denies read methods without their read capability", async () => {
const listInteractions = vi.fn(async () => []);
const list = vi.fn(async () => []);
const getAttachmentContent = vi.fn(async () => null);
const services = {
issues: { listInteractions, getAttachmentContent },
approvals: { list },
} as unknown as HostServices;
const handlers = createHostClientHandlers({
pluginId: "paperclip.test",
capabilities: [],
services,
});
await expect(
handlers["issues.listInteractions"]({ issueId: "i", companyId: "company-a" }, context),
).rejects.toBeInstanceOf(CapabilityDeniedError);
await expect(
handlers["approvals.list"]({ companyId: "company-a" }, context),
).rejects.toBeInstanceOf(CapabilityDeniedError);
await expect(
handlers["issues.getAttachmentContent"]({ attachmentId: "at", companyId: "company-a" }, context),
).rejects.toBeInstanceOf(CapabilityDeniedError);
expect(listInteractions).not.toHaveBeenCalled();
expect(list).not.toHaveBeenCalled();
expect(getAttachmentContent).not.toHaveBeenCalled();
});
it("enforces invocation company scope on the new methods", async () => {
const list = vi.fn(async () => []);
const services = { approvals: { list } } as unknown as HostServices;
const handlers = createHostClientHandlers({
pluginId: "paperclip.test",
capabilities: ["approvals.read"],
services,
});
// Requesting company-b while scoped to company-a must be denied.
await expect(
handlers["approvals.list"]({ companyId: "company-b" }, context),
).rejects.toBeInstanceOf(InvocationScopeDeniedError);
expect(list).not.toHaveBeenCalled();
});
});
describe("agent runtime reader", () => {
it.each(["getRuntime", "getRuntimeIdentity"] as const)("requires lifecycle capability and invocation company for %s", async method => {
const getRuntime = vi.fn(async () => null);
const services = { agents: { [method]: getRuntime } } as unknown as HostServices;
const params = { companyId: "company-a", agentId: "agent-a" };
const context = { invocationScope: { companyId: "company-a" } };
const denied = createHostClientHandlers({ pluginId: "runtime", capabilities: ["agents.read"], services });
await expect(denied[`agents.${method}`](params, context)).rejects.toBeInstanceOf(CapabilityDeniedError);
const allowed = createHostClientHandlers({ pluginId: "runtime", capabilities: ["agents.lifecycle.manage"], services });
await expect(allowed[`agents.${method}`](params, { invocationScope: { companyId: "other" } })).rejects.toBeInstanceOf(InvocationScopeDeniedError);
expect(getRuntime).not.toHaveBeenCalled();
await expect(allowed[`agents.${method}`](params, context)).resolves.toBeNull();
expect(getRuntime).toHaveBeenCalledOnce();
});
});
describe("project instance secrets", () => {
it("requires the capability and host-authorized company scope", async () => {
const getInstanceSecrets = vi.fn(async () => ({ mount_grants: "fixture" }));
const services = { projects: { getInstanceSecrets } } as unknown as HostServices;
const params = { companyId: "company-a", projectId: "project-a" };
const context = { invocationScope: { companyId: "company-a" } };
const denied = createHostClientHandlers({ pluginId: "fixture", capabilities: [], services });
await expect(denied["projects.getInstanceSecrets"](params, context)).rejects.toBeInstanceOf(CapabilityDeniedError);
const allowed = createHostClientHandlers({ pluginId: "fixture", capabilities: ["projects.instance-secrets"], services });
await expect(allowed["projects.getInstanceSecrets"](params)).rejects.toBeInstanceOf(InvocationScopeDeniedError);
await expect(allowed["projects.getInstanceSecrets"](params, { invocationScope: { companyId: "other" } })).rejects.toBeInstanceOf(InvocationScopeDeniedError);
expect(getInstanceSecrets).not.toHaveBeenCalled();
await expect(allowed["projects.getInstanceSecrets"](params, context)).resolves.toEqual({ mount_grants: "fixture" });
expect(getInstanceSecrets).toHaveBeenCalledWith(params);
});
});
describe("project Git credentials", () => {
it("requires capability, company, project and repository scope before calling credential services", async () => {
const resolveGitCredential = vi.fn(async () => "transient-token");
const services = { projects: { resolveGitCredential } } as unknown as HostServices;
const params = { companyId: "company-a", projectId: "project-a", workspaceId: "workspace-a" };
const context = { invocationScope: { companyId: "company-a", projectGit: { projectId: "project-a", workspaceId: "workspace-a", runId: "run-a", agentId: "agent-a" } } };
const denied = createHostClientHandlers({ pluginId: "fixture", capabilities: [], services });
await expect(denied["projects.resolveGitCredential"](params, context)).rejects.toBeInstanceOf(CapabilityDeniedError);
const allowed = createHostClientHandlers({ pluginId: "fixture", capabilities: ["projects.git-credentials"], services });
for (const invalid of [undefined, { invocationScope: { companyId: "other" } },
{ invocationScope: { companyId: "company-a" } },
{ invocationScope: { companyId: "company-a", projectGit: { projectId: "other" } } },
{ invocationScope: { companyId: "company-a", projectGit: { projectId: "project-a", workspaceId: "other" } } },
{ ...context, invalidInvocationScope: true }]) {
await expect(allowed["projects.resolveGitCredential"](params, invalid)).rejects.toThrow();
}
expect(resolveGitCredential).not.toHaveBeenCalled();
await expect(allowed["projects.resolveGitCredential"](params, context)).resolves.toBe("transient-token");
expect(resolveGitCredential).toHaveBeenCalledWith(params, context);
});
});