mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 01:24:30 +01:00
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>
This commit is contained in:
1 parent
1a726eaccf
commit
fa283aeea2
16 files changed
+281
-17
No files matched your search
@@ -5,6 +5,7 @@ import { environmentTaskErrorCodeData, environmentTaskOperationSchema, parseEnvi
|
||||
readEnvironmentTaskErrorCode, readEnvironmentTaskErrorDiagnostic } from "@paperclipai/plugin-sdk";
|
||||
import { executeEnvironmentTask, isSettledReadyRunnerState, settleDispatchedEnvironmentTask } from "../services/environment-task-runtime.js";
|
||||
import { NativeExecutionContext } from "../services/native-runtime/native-execution-context.js";
|
||||
import { beginRunStartupStages, clearAllRunStartupStages, getRunStartupStage, reportPluginStartupStage } from "../services/run-startup-stage.js";
|
||||
import { createRunnerProviderLaunch, runnerLaunchPreparationDigest, runnerLaunchRunDigest, runnerProviderLaunchRequirements } from "../vendor/paperclip-runner/index.js";
|
||||
|
||||
const state = vi.hoisted(() => ({ plugin: {} as any, release: vi.fn(), identity: vi.fn(), config: vi.fn() }));
|
||||
@@ -129,6 +130,24 @@ describe("plugin-provided Runner execution", () => {
|
||||
await expect(settleDispatchedEnvironmentTask(fixture.db, workers as never, { companyId: "company", id: leaseId }, { executionStopObserved: true })).resolves.toBe("completed");
|
||||
expect(operations).toEqual(preparationStopped ? ["status", "complete"] : ["status", "stop", "status", "complete"]);
|
||||
});
|
||||
it("lets the task's plugin report a startup stage only while its operation runs", async () => {
|
||||
beginRunStartupStages({ id: "run", companyId: "company", agentId: "agent", issueId: "issue" });
|
||||
const workers = worker();
|
||||
let duringCall: ReturnType<typeof getRunStartupStage> = null;
|
||||
workers.call.mockImplementation(async () => {
|
||||
expect(reportPluginStartupStage("another-plugin", "attempt-1", "starting_environment")).toBe(false);
|
||||
expect(reportPluginStartupStage("original", "attempt-1", "starting_environment")).toBe(true);
|
||||
duringCall = getRunStartupStage("run");
|
||||
return { kind: "description", taskId: "attempt-1", runner: { version: "fixture", digest: `sha256:${"a".repeat(64)}` } };
|
||||
});
|
||||
try {
|
||||
await executeEnvironmentTask(database().db, workers as never, { companyId: "company", leaseId, operation: { kind: "describe" } });
|
||||
expect(duringCall).toMatchObject({ stage: "starting_environment" });
|
||||
expect(getRunStartupStage("run")).toMatchObject({ stage: "getting_ready" });
|
||||
expect(reportPluginStartupStage("original", "attempt-1", "starting_environment")).toBe(false);
|
||||
} finally { clearAllRunStartupStages(); }
|
||||
});
|
||||
|
||||
it("negotiates the transient context without reading transport for an older plugin", async () => {
|
||||
const context = new NativeExecutionContext({ binding: { companyId: "company", agentId: "agent", runId: "run" } } as never, 1_000);
|
||||
const workers = worker();
|
||||
|
||||
@@ -21,6 +21,7 @@ import { assertPluginTaskSourceAttachment, assertPluginTaskSourceRecovery } from
|
||||
import { pluginAgentRuntimeIdentity } from "./plugin-agent-runtime-state.js";
|
||||
import { runnerLaunchPreparationDigest, runnerLaunchRunDigest } from "../vendor/paperclip-runner/index.js";
|
||||
import { assertPluginTaskOwnershipDispatch, PluginTaskOwnershipPendingError, readyPortableTaskSource, reconcilePluginTaskAdmission } from "./plugin-task-ownership.js";
|
||||
import { openPluginStartupWindow } from "./run-startup-stage.js";
|
||||
|
||||
export type PluginTaskDescription = Extract<PluginEnvironmentTaskResult, { kind: "description" }>;
|
||||
|
||||
@@ -343,7 +344,13 @@ export async function executeEnvironmentTask(db: Db, workers: Pick<PluginWorkerM
|
||||
throw new Error("Plugin Runner credential handoff unavailable");
|
||||
}
|
||||
if (ownership && driver.sessionHandoffVersion !== 1) throw new Error("Plugin Runner ownership reconciliation unavailable");
|
||||
// While a task operation for a run is in flight, its plugin may report the
|
||||
// run's startup stage for display (run-startup-stage).
|
||||
const callWorker = async <M extends HostToWorkerMethodName>(method: M, params: HostToWorkerMethods[M][0], timeout?: number): Promise<HostToWorkerMethods[M][1]> => {
|
||||
const closeStartupWindow = method === "environmentTask" && run ? openPluginStartupWindow(plugin.id, taskId, run.id) : null;
|
||||
try { return await callPluginWorker(method, params, timeout); } finally { closeStartupWindow?.(); }
|
||||
};
|
||||
const callPluginWorker = async <M extends HostToWorkerMethodName>(method: M, params: HostToWorkerMethods[M][0], timeout?: number): Promise<HostToWorkerMethods[M][1]> => {
|
||||
if (!context) {
|
||||
const cleanup = metadata.runnerTaskStartupCleanup as { contextId?: unknown; requiresPreparationStop?: unknown } | undefined;
|
||||
if (["stop", "status", "complete", "credentials"].includes(operation.kind) && typeof cleanup?.contextId === "string" && typeof cleanup.requiresPreparationStop === "boolean") {
|
||||
|
||||
@@ -107,6 +107,7 @@ const OPERATION_CAPABILITIES: Record<string, readonly PluginCapability[]> = {
|
||||
"approvals.respond": ["approvals.respond"],
|
||||
"approvals.decide": ["approvals.respond"],
|
||||
"activity.log": ["activity.log.write"],
|
||||
"environmentTasks.reportStartupStage": ["environment.drivers.register"],
|
||||
"metrics.write": ["metrics.write"],
|
||||
"telemetry.track": ["telemetry.track"],
|
||||
"db.migrate": ["database.namespace.migrate"],
|
||||
|
||||
@@ -36,7 +36,8 @@ import type {
|
||||
PluginExecutionWorkspaceMetadata,
|
||||
} from "@paperclipai/plugin-sdk";
|
||||
import type { CreateIssueThreadInteraction, InviteJoinType, IssueDocumentSummary, IssueRelationIssueSummary, PermissionKey, PrincipalType } from "@paperclipai/shared";
|
||||
import { pluginOperationIssueOriginKind } from "@paperclipai/shared";
|
||||
import { pluginOperationIssueOriginKind, RUN_STARTUP_STAGES, type RunStartupStage } from "@paperclipai/shared";
|
||||
import { reportPluginStartupStage } from "./run-startup-stage.js";
|
||||
import { companyService } from "./companies.js";
|
||||
import { agentService } from "./agents.js";
|
||||
import { projectService } from "./projects.js";
|
||||
@@ -1811,6 +1812,17 @@ export function buildHostServices(
|
||||
},
|
||||
},
|
||||
|
||||
environmentTasks: {
|
||||
async reportStartupStage(params) {
|
||||
// Display only: the tracker accepts it during this plugin's own task operation.
|
||||
const stage = (params as { stage?: unknown } | undefined)?.stage;
|
||||
const taskId = (params as { taskId?: unknown } | undefined)?.taskId;
|
||||
if (typeof taskId !== "string" || !taskId || typeof stage !== "string"
|
||||
|| !(RUN_STARTUP_STAGES as readonly string[]).includes(stage)) return;
|
||||
reportPluginStartupStage(pluginId, taskId, stage as RunStartupStage);
|
||||
},
|
||||
},
|
||||
|
||||
activity: {
|
||||
async log(params) {
|
||||
const companyId = ensureCompanyId(params.companyId);
|
||||
|
||||
@@ -14,6 +14,8 @@ import {
|
||||
MAX_TRACKED_RUN_STARTUPS,
|
||||
noteRunStartupSessionResumed,
|
||||
noteRunStartupStep,
|
||||
openPluginStartupWindow,
|
||||
reportPluginStartupStage,
|
||||
RUN_STARTUP_STAGE_TTL_MS,
|
||||
runStartupStageForStep,
|
||||
} from "./run-startup-stage.js";
|
||||
@@ -200,6 +202,53 @@ describe("run startup stages", () => {
|
||||
expect(getRunStartupStage(run.id)).toBeNull();
|
||||
});
|
||||
|
||||
describe("plugin reports", () => {
|
||||
it("shows a plugin's stage only during its own task operation, even an earlier stage", () => {
|
||||
const recorder = recordEvents();
|
||||
try {
|
||||
beginRunStartupStages(run);
|
||||
noteRunStartupStep(run.id, "native.controller.backend_setup");
|
||||
expect(reportPluginStartupStage("plugin-a", "task-1", "starting_environment")).toBe(false);
|
||||
const close = openPluginStartupWindow("plugin-a", "task-1", run.id);
|
||||
expect(reportPluginStartupStage("plugin-b", "task-1", "starting_environment")).toBe(false);
|
||||
expect(reportPluginStartupStage("plugin-a", "task-2", "starting_environment")).toBe(false);
|
||||
expect(reportPluginStartupStage("plugin-a", "task-1", "starting_environment")).toBe(true);
|
||||
expect(getRunStartupStage(run.id)?.stage).toBe("starting_environment");
|
||||
// Core keeps moving underneath; the plugin's stage shows until the call returns.
|
||||
noteRunStartupStep(run.id, "runner.session.startup");
|
||||
expect(getRunStartupStage(run.id)?.stage).toBe("starting_environment");
|
||||
close();
|
||||
close();
|
||||
expect(getRunStartupStage(run.id)?.stage).toBe("starting_agent");
|
||||
expect(reportPluginStartupStage("plugin-a", "task-1", "preparing_workspace")).toBe(false);
|
||||
expect(recorder.stages()).toEqual(["getting_ready", "connecting_tools", "starting_environment", "starting_agent"]);
|
||||
} finally {
|
||||
recorder.unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the window open until every overlapping operation returns", () => {
|
||||
beginRunStartupStages(run);
|
||||
const first = openPluginStartupWindow("plugin-a", "task-1", run.id);
|
||||
const second = openPluginStartupWindow("plugin-a", "task-1", run.id);
|
||||
reportPluginStartupStage("plugin-a", "task-1", "starting_environment");
|
||||
first();
|
||||
expect(getRunStartupStage(run.id)?.stage).toBe("starting_environment");
|
||||
second();
|
||||
expect(getRunStartupStage(run.id)?.stage).toBe("getting_ready");
|
||||
});
|
||||
|
||||
it("ignores reports after the agent turn starts and unknown stages", () => {
|
||||
beginRunStartupStages(run);
|
||||
const close = openPluginStartupWindow("plugin-a", "task-1", run.id);
|
||||
expect(reportPluginStartupStage("plugin-a", "task-1", "made_up" as never)).toBe(false);
|
||||
noteRunStartupStep(run.id, "agent.turn");
|
||||
expect(reportPluginStartupStage("plugin-a", "task-1", "starting_environment")).toBe(false);
|
||||
expect(getRunStartupStage(run.id)?.stage).toBeNull();
|
||||
close();
|
||||
});
|
||||
});
|
||||
|
||||
it("adds the stage to active run reads and drops it for ended runs", () => {
|
||||
beginRunStartupStages(run);
|
||||
noteRunStartupStep(run.id, "native.controller.backend_setup");
|
||||
|
||||
@@ -42,12 +42,26 @@ interface RunStartupEntry {
|
||||
issueId: string | null;
|
||||
/** Null once the agent's turn has started; the attempt keeps its resume flag. */
|
||||
stage: RunStartupStage | null;
|
||||
/**
|
||||
* A stage the run's environment plugin reported during one of its task
|
||||
* operations. It shows instead of Core's stage until that operation returns,
|
||||
* and may name an earlier stage (a stopped machine starting during submit).
|
||||
*/
|
||||
pluginStage: RunStartupStage | null;
|
||||
sessionResumed: boolean;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
const entriesByRunId = new Map<string, RunStartupEntry>();
|
||||
|
||||
/** Plugin task operations in flight, by plugin and task: the only time a plugin may report. */
|
||||
const pluginWindows = new Map<string, { runId: string; open: number }>();
|
||||
const windowKey = (pluginId: string, taskId: string) => `${pluginId}\u0000${taskId}`;
|
||||
|
||||
function shownStage(entry: RunStartupEntry): RunStartupStage | null {
|
||||
return entry.stage === null ? null : entry.pluginStage ?? entry.stage;
|
||||
}
|
||||
|
||||
export function runStartupStageForStep(stepName: string): RunStartupStage | "started" | null {
|
||||
const mapped = STAGE_BY_STEP.get(stepName);
|
||||
if (mapped) return mapped;
|
||||
@@ -57,10 +71,11 @@ export function runStartupStageForStep(stepName: string): RunStartupStage | "sta
|
||||
return stepName.startsWith("heartbeat.prepare.") ? "getting_ready" : null;
|
||||
}
|
||||
|
||||
function publish(runId: string, entry: Pick<RunStartupEntry, "companyId" | "agentId" | "issueId">,
|
||||
stage: RunStartupStage | null, sessionResumed: boolean, updatedAt: Date) {
|
||||
function publish(runId: string, entry: RunStartupEntry, stage: RunStartupStage | null = shownStage(entry),
|
||||
updatedAt: Date = entry.updatedAt) {
|
||||
const payload: HeartbeatRunStartupStageEvent = {
|
||||
runId, agentId: entry.agentId, issueId: entry.issueId, stage, sessionResumed, updatedAt: updatedAt.toISOString(),
|
||||
runId, agentId: entry.agentId, issueId: entry.issueId, stage, sessionResumed: entry.sessionResumed,
|
||||
updatedAt: updatedAt.toISOString(),
|
||||
};
|
||||
// Listeners run synchronously. The stage is display only, so a failing
|
||||
// listener must never interrupt the run step or agent event that moved it.
|
||||
@@ -83,10 +98,10 @@ export function beginRunStartupStages(run: { id: string; companyId: string; agen
|
||||
entriesByRunId.delete(run.id);
|
||||
const entry: RunStartupEntry = {
|
||||
companyId: run.companyId, agentId: run.agentId, issueId: run.issueId,
|
||||
stage: "getting_ready", sessionResumed: false, updatedAt: new Date(),
|
||||
stage: "getting_ready", pluginStage: null, sessionResumed: false, updatedAt: new Date(),
|
||||
};
|
||||
entriesByRunId.set(run.id, entry);
|
||||
publish(run.id, entry, entry.stage, false, entry.updatedAt);
|
||||
publish(run.id, entry);
|
||||
}
|
||||
|
||||
/** Records that a timed step began. Unknown runs and earlier stages are ignored. */
|
||||
@@ -100,9 +115,10 @@ export function noteRunStartupStep(runId: string, stepName: string) {
|
||||
return;
|
||||
}
|
||||
if ((STAGE_ORDER.get(next) ?? -1) <= (STAGE_ORDER.get(entry.stage) ?? -1)) return;
|
||||
const shown = shownStage(entry);
|
||||
entry.stage = next;
|
||||
entry.updatedAt = new Date();
|
||||
publish(runId, entry, entry.stage, entry.sessionResumed, entry.updatedAt);
|
||||
if (shownStage(entry) !== shown) publish(runId, entry);
|
||||
}
|
||||
|
||||
/** The provider confirmed it resumed a saved session for this run. */
|
||||
@@ -111,7 +127,7 @@ export function noteRunStartupSessionResumed(runId: string) {
|
||||
if (!entry || entry.sessionResumed) return;
|
||||
entry.sessionResumed = true;
|
||||
entry.updatedAt = new Date();
|
||||
publish(runId, entry, entry.stage, true, entry.updatedAt);
|
||||
publish(runId, entry);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -123,8 +139,9 @@ export function endRunStartup(runId: string) {
|
||||
const entry = entriesByRunId.get(runId);
|
||||
if (!entry || entry.stage === null) return;
|
||||
entry.stage = null;
|
||||
entry.pluginStage = null;
|
||||
entry.updatedAt = new Date();
|
||||
publish(runId, entry, null, entry.sessionResumed, entry.updatedAt);
|
||||
publish(runId, entry);
|
||||
}
|
||||
|
||||
/** Forgets the execution attempt once it ends. */
|
||||
@@ -132,7 +149,52 @@ export function finishRunStartupStages(runId: string) {
|
||||
const entry = entriesByRunId.get(runId);
|
||||
if (!entry) return;
|
||||
entriesByRunId.delete(runId);
|
||||
if (entry.stage !== null) publish(runId, entry, null, entry.sessionResumed, new Date());
|
||||
if (entry.stage !== null) publish(runId, entry, null, new Date());
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the window in which a plugin may report a stage for one of its tasks:
|
||||
* the duration of one environment task operation for a run. Call the returned
|
||||
* function when the operation returns; the run's own stage then shows again.
|
||||
*/
|
||||
export function openPluginStartupWindow(pluginId: string, taskId: string, runId: string): () => void {
|
||||
const key = windowKey(pluginId, taskId);
|
||||
const slot = pluginWindows.get(key);
|
||||
if (slot && slot.runId === runId) slot.open += 1;
|
||||
else pluginWindows.set(key, { runId, open: 1 });
|
||||
let closed = false;
|
||||
return () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
const current = pluginWindows.get(key);
|
||||
if (!current || current.runId !== runId) return;
|
||||
current.open -= 1;
|
||||
if (current.open > 0) return;
|
||||
pluginWindows.delete(key);
|
||||
const entry = entriesByRunId.get(runId);
|
||||
if (!entry || entry.pluginStage === null) return;
|
||||
const shown = shownStage(entry);
|
||||
entry.pluginStage = null;
|
||||
entry.updatedAt = new Date();
|
||||
if (shownStage(entry) !== shown) publish(runId, entry);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A plugin reports the stage of its task. Accepted only inside an open window
|
||||
* for that plugin and task, and only before the run's agent turn starts.
|
||||
*/
|
||||
export function reportPluginStartupStage(pluginId: string, taskId: string, stage: RunStartupStage): boolean {
|
||||
if (!STAGE_ORDER.has(stage)) return false;
|
||||
const slot = pluginWindows.get(windowKey(pluginId, taskId));
|
||||
if (!slot) return false;
|
||||
const entry = entriesByRunId.get(slot.runId);
|
||||
if (!entry || entry.stage === null) return false;
|
||||
const shown = shownStage(entry);
|
||||
entry.pluginStage = stage;
|
||||
entry.updatedAt = new Date();
|
||||
if (shownStage(entry) !== shown) publish(slot.runId, entry);
|
||||
return true;
|
||||
}
|
||||
|
||||
export function getRunStartupStage(
|
||||
@@ -150,7 +212,7 @@ export function getRunStartupStage(
|
||||
}
|
||||
if (expected.companyId != null && entry.companyId !== expected.companyId) return null;
|
||||
if (expected.agentId != null && entry.agentId !== expected.agentId) return null;
|
||||
return { stage: entry.stage, sessionResumed: entry.sessionResumed };
|
||||
return { stage: shownStage(entry), sessionResumed: entry.sessionResumed };
|
||||
}
|
||||
|
||||
/** Forgets a run without publishing, e.g. once a terminal status is observed. */
|
||||
@@ -160,4 +222,5 @@ export function clearRunStartupStage(runId: string) {
|
||||
|
||||
export function clearAllRunStartupStages() {
|
||||
entriesByRunId.clear();
|
||||
pluginWindows.clear();
|
||||
}
|
||||
Reference in new issue
Block a user