diff --git a/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md b/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md index 8c463eb0fef..fa265db1d43 100644 --- a/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md +++ b/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md @@ -321,6 +321,25 @@ Provider recovery, bounded host retention and deployment qualification are still required before activation. Recovery from a Core crash between claim and source authentication is not qualified by this integration. +## Startup stages + +While the host waits for one of your task operations for a run (for example +`prepare` or `submit`), your worker can tell the board which startup stage the +task is on: + +```ts +await ctx.environmentTasks.reportStartupStage({ taskId, stage: "starting_environment" }); +``` + +The stages are the shared `RUN_STARTUP_STAGES`. The host also tracks the run's +stage from its own steps. Your report shows instead of the host's stage until +the operation returns, and it may name an earlier stage, such as a stopped +machine starting during `submit`. The host ignores a report outside such an +operation, for a task your plugin does not own, or after the agent turn has +started. A report never fails the operation, so call it best effort. It +requires `environment.drivers.register`. An older host does not have the +method, so catch and ignore its error. + ## Error codes Core does not read the text of a task error. To report a failure that Core can diff --git a/doc/plugins/PLUGIN_SPEC.md b/doc/plugins/PLUGIN_SPEC.md index b76769096ac..01dbef2cfb3 100644 --- a/doc/plugins/PLUGIN_SPEC.md +++ b/doc/plugins/PLUGIN_SPEC.md @@ -792,6 +792,7 @@ Required SDK clients: - `ctx.secrets` - `ctx.assets` - `ctx.activity` +- `ctx.environmentTasks` - `ctx.state` - `ctx.entities` - `ctx.projects` diff --git a/packages/plugins/sdk/src/host-client-factory.ts b/packages/plugins/sdk/src/host-client-factory.ts index e0301c390ea..8f76d518b4b 100644 --- a/packages/plugins/sdk/src/host-client-factory.ts +++ b/packages/plugins/sdk/src/host-client-factory.ts @@ -159,6 +159,11 @@ export interface HostServices { ): Promise; }; + /** Provides `environmentTasks.reportStartupStage`. */ + environmentTasks: { + reportStartupStage(params: WorkerToHostMethods["environmentTasks.reportStartupStage"][0]): Promise; + }; + /** Provides `activity.log`. */ activity: { log(params: { @@ -424,6 +429,9 @@ const METHOD_CAPABILITY_MAP: Record { + return services.environmentTasks.reportStartupStage(params); + }), + // Metrics "metrics.write": gated("metrics.write", async (params) => { return services.metrics.write(params); diff --git a/packages/plugins/sdk/src/protocol.ts b/packages/plugins/sdk/src/protocol.ts index 4861d78f1c5..a540b56dee3 100644 --- a/packages/plugins/sdk/src/protocol.ts +++ b/packages/plugins/sdk/src/protocol.ts @@ -1,7 +1,7 @@ import type { PluginWorkspaceParams, PluginWorkspacePrepareParams, PluginWorkspacePrepareResult, PluginWorkspaceResult } from "./workspace-provider.js"; import type { PluginEnvironmentTaskParams, PluginEnvironmentTaskResult } from "./environment-tasks.js"; import type { PluginAgentRuntimeState, PluginAgentRuntimeIdentity } from "./types.js"; -import type { AgentLifecycleRequest, AgentLifecycleResult } from "@paperclipai/shared"; +import type { AgentLifecycleRequest, AgentLifecycleResult, RunStartupStage } from "@paperclipai/shared"; import type { AiConnectionRouterRequest, AiConnectionRouterResult } from "@paperclipai/shared"; /** * JSON-RPC 2.0 message types and protocol helpers for the host ↔ worker IPC @@ -1818,6 +1818,12 @@ export interface WorkerToHostMethods { result: void, ]; + // Environment tasks + "environmentTasks.reportStartupStage": [ + params: { taskId: string; stage: RunStartupStage }, + result: void, + ]; + // Metrics "metrics.write": [ params: { diff --git a/packages/plugins/sdk/src/testing.ts b/packages/plugins/sdk/src/testing.ts index 5a3994447fd..d40b4c1cada 100644 --- a/packages/plugins/sdk/src/testing.ts +++ b/packages/plugins/sdk/src/testing.ts @@ -1,6 +1,7 @@ import { randomUUID } from "node:crypto"; import { createIssueThreadInteractionSchema, pluginOperationIssueOriginKind } from "@paperclipai/shared"; import type { + RunStartupStage, PaperclipPluginManifestV1, PluginCapability, PluginEventType, @@ -162,6 +163,8 @@ export interface TestHarness { simulateSessionEvent(sessionId: string, event: Omit): void; logs: TestHarnessLogEntry[]; activity: Array<{ message: string; entityType?: string; entityId?: string; metadata?: Record }>; + /** Startup stages reported through `ctx.environmentTasks.reportStartupStage`, in order. */ + startupStageReports: Array<{ taskId: string; stage: RunStartupStage }>; metrics: Array<{ name: string; value: number; tags?: Record }>; telemetry: Array<{ eventName: string; dimensions?: Record }>; dbQueries: Array<{ sql: string; params?: unknown[] }>; @@ -510,6 +513,7 @@ export function createTestHarness(options: TestHarnessOptions): TestHarness { const logs: TestHarnessLogEntry[] = []; const activity: TestHarness["activity"] = []; + const startupStageReports: TestHarness["startupStageReports"] = []; const metrics: TestHarness["metrics"] = []; const telemetry: TestHarness["telemetry"] = []; const dbQueries: TestHarness["dbQueries"] = []; @@ -981,6 +985,12 @@ export function createTestHarness(options: TestHarnessOptions): TestHarness { activity.push(entry); }, }, + environmentTasks: { + async reportStartupStage(input) { + requireCapability(manifest, capabilitySet, "environment.drivers.register"); + startupStageReports.push({ ...input }); + }, + }, state: { async get(input) { requireCapability(manifest, capabilitySet, "plugin.state.read"); @@ -2793,6 +2803,7 @@ export function createTestHarness(options: TestHarnessOptions): TestHarness { }, logs, activity, + startupStageReports, metrics, telemetry, dbQueries, diff --git a/packages/plugins/sdk/src/types.ts b/packages/plugins/sdk/src/types.ts index e3532de0e13..1391d1599de 100644 --- a/packages/plugins/sdk/src/types.ts +++ b/packages/plugins/sdk/src/types.ts @@ -10,6 +10,7 @@ */ import type { + RunStartupStage, PaperclipPluginManifestV1, PluginStateScopeKind, PluginEventType, @@ -790,6 +791,25 @@ export interface PluginActivityClient { log(entry: PluginActivityLogEntry): Promise; } +/** + * `ctx.environmentTasks` — status reporting for this plugin's Runner tasks. + * + * Requires `environment.drivers.register`. + */ +export interface PluginEnvironmentTasksClient { + /** + * Report the startup stage of one of this plugin's Runner tasks while the + * host waits for an environment task operation on that task (for example + * `starting_environment` while a stopped machine starts during `submit`). + * + * The board shows the reported stage only for the rest of that operation. + * When it returns, the host's own stage for the run shows again. The host + * ignores a report outside such an operation, for another plugin's task, or + * after the run's agent turn has started. It never fails the operation. + */ + reportStartupStage(input: { taskId: string; stage: RunStartupStage }): Promise; +} + /** * `ctx.state` — read and write plugin-scoped key-value state. * @@ -2321,6 +2341,9 @@ export interface PluginContext { /** Write activity log entries. Requires `activity.log.write`. */ activity: PluginActivityClient; + /** Report Runner task startup stages. Requires `environment.drivers.register`. */ + environmentTasks: PluginEnvironmentTasksClient; + /** Read and write scoped plugin state. Requires `plugin.state.read` / `plugin.state.write`. */ state: PluginStateClient; diff --git a/packages/plugins/sdk/src/worker-rpc-host.ts b/packages/plugins/sdk/src/worker-rpc-host.ts index 820c73c7d4c..1fe5ce2c813 100644 --- a/packages/plugins/sdk/src/worker-rpc-host.ts +++ b/packages/plugins/sdk/src/worker-rpc-host.ts @@ -682,6 +682,12 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost }, }, + environmentTasks: { + async reportStartupStage(input): Promise { + await callHost("environmentTasks.reportStartupStage", { taskId: input.taskId, stage: input.stage }); + }, + }, + activity: { async log(entry): Promise { await callHost("activity.log", { diff --git a/packages/plugins/sdk/tests/host-client-factory.test.ts b/packages/plugins/sdk/tests/host-client-factory.test.ts index b30ffebefc7..54862fa3b38 100644 --- a/packages/plugins/sdk/tests/host-client-factory.test.ts +++ b/packages/plugins/sdk/tests/host-client-factory.test.ts @@ -343,6 +343,18 @@ describe("createHostClientHandlers capability gating for LOOA-641 methods", () = 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; diff --git a/packages/plugins/sdk/tests/testing-environment-tasks.test.ts b/packages/plugins/sdk/tests/testing-environment-tasks.test.ts new file mode 100644 index 00000000000..c29d72fca7b --- /dev/null +++ b/packages/plugins/sdk/tests/testing-environment-tasks.test.ts @@ -0,0 +1,22 @@ +import { expect, it } from "vitest"; +import { createTestHarness } from "../src/testing.js"; +import type { PaperclipPluginManifestV1 } from "../src/types.js"; + +const manifest: PaperclipPluginManifestV1 = { + id: "fixture.environment-tasks", apiVersion: 1, version: "1.0.0", displayName: "Environment tasks", + description: "Fixture", author: "Tests", categories: ["automation"], + capabilities: ["environment.drivers.register"], entrypoints: { worker: "./worker.js" }, +}; + +it("records startup stage reports for a driver plugin and requires its capability", async () => { + const harness = createTestHarness({ manifest }); + await harness.ctx.environmentTasks.reportStartupStage({ taskId: "task-1", stage: "starting_environment" }); + await harness.ctx.environmentTasks.reportStartupStage({ taskId: "task-1", stage: "preparing_workspace" }); + expect(harness.startupStageReports).toEqual([ + { taskId: "task-1", stage: "starting_environment" }, + { taskId: "task-1", stage: "preparing_workspace" }, + ]); + const denied = createTestHarness({ manifest, capabilities: [] }); + await expect(denied.ctx.environmentTasks.reportStartupStage({ taskId: "task-1", stage: "starting_agent" })) + .rejects.toThrow("environment.drivers.register"); +}); diff --git a/server/src/__tests__/environment-task-runtime.test.ts b/server/src/__tests__/environment-task-runtime.test.ts index 6fc30c805d0..26234253815 100644 --- a/server/src/__tests__/environment-task-runtime.test.ts +++ b/server/src/__tests__/environment-task-runtime.test.ts @@ -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 = 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(); diff --git a/server/src/services/environment-task-runtime.ts b/server/src/services/environment-task-runtime.ts index b96851f50dd..0d0616a13f4 100644 --- a/server/src/services/environment-task-runtime.ts +++ b/server/src/services/environment-task-runtime.ts @@ -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; @@ -343,7 +344,13 @@ export async function executeEnvironmentTask(db: Db, workers: Pick(method: M, params: HostToWorkerMethods[M][0], timeout?: number): Promise => { + const closeStartupWindow = method === "environmentTask" && run ? openPluginStartupWindow(plugin.id, taskId, run.id) : null; + try { return await callPluginWorker(method, params, timeout); } finally { closeStartupWindow?.(); } + }; + const callPluginWorker = async (method: M, params: HostToWorkerMethods[M][0], timeout?: number): Promise => { 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") { diff --git a/server/src/services/plugin-capability-validator.ts b/server/src/services/plugin-capability-validator.ts index 20819b57925..3b341a25b6e 100644 --- a/server/src/services/plugin-capability-validator.ts +++ b/server/src/services/plugin-capability-validator.ts @@ -107,6 +107,7 @@ const OPERATION_CAPABILITIES: Record = { "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"], diff --git a/server/src/services/plugin-host-services.ts b/server/src/services/plugin-host-services.ts index 6c92987f5d9..14f98e953c6 100644 --- a/server/src/services/plugin-host-services.ts +++ b/server/src/services/plugin-host-services.ts @@ -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); diff --git a/server/src/services/run-startup-stage.test.ts b/server/src/services/run-startup-stage.test.ts index 9a7afdb2e82..881ea306fa7 100644 --- a/server/src/services/run-startup-stage.test.ts +++ b/server/src/services/run-startup-stage.test.ts @@ -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"); diff --git a/server/src/services/run-startup-stage.ts b/server/src/services/run-startup-stage.ts index 24ac17fc9c8..078da7d9c3e 100644 --- a/server/src/services/run-startup-stage.ts +++ b/server/src/services/run-startup-stage.ts @@ -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(); +/** Plugin task operations in flight, by plugin and task: the only time a plugin may report. */ +const pluginWindows = new Map(); +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, - 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(); } diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 435019760d8..ad1efd30ed0 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -14,22 +14,22 @@ "packages/plugins/sdk/src/environment-sync-error.ts": "7d6a51a95da49a7da4525aebbab6382dc5c44ae8", "packages/plugins/sdk/src/environment-task-error.ts": "98aae8a06743b38884b68cb9a3ec44c57b34c0e4", "packages/plugins/sdk/src/environment-tasks.ts": "ebdf0950379645dda416300acaa65718daf2795e", - "packages/plugins/sdk/src/host-client-factory.ts": "e0301c390ea13f2340b669383f07af2455e48c8a", + "packages/plugins/sdk/src/host-client-factory.ts": "8f76d518b4b43a41436b516cb2929165611bd483", "packages/plugins/sdk/src/idle-drain.test.ts": "cc59f7881e7d46c89395a1d93d74f6c6b9b0a64a", "packages/plugins/sdk/src/idle-drain.ts": "ae6e4c6be4657a3d541396922b3bc551b8db557f", "packages/plugins/sdk/src/index.ts": "686c87d177f180a05e4162dd762fd0447572956f", "packages/plugins/sdk/src/invocation-tracer.ts": "b28ac4aa4bc3e82658abac4a8081ed4508008696", "packages/plugins/sdk/src/protocol.duplex-channel.test.ts": "18255eb3d63038dc459240c111cbcb29fcba25cc", - "packages/plugins/sdk/src/protocol.ts": "4861d78f1c57f1485a79e037932f39e8c91446b8", - "packages/plugins/sdk/src/testing.ts": "5a3994447fd84ce176978fa8bc3548c14c37b189", - "packages/plugins/sdk/src/types.ts": "e3532de0e1341dae241a44e6b6e5419bd0645687", + "packages/plugins/sdk/src/protocol.ts": "a540b56dee310bfacc0d9100a795d12dfbc9396a", + "packages/plugins/sdk/src/testing.ts": "d40b4c1cada40a3a371085612774b64aa1b984a0", + "packages/plugins/sdk/src/types.ts": "1391d1599de9da2c0a3e7c9cacaf1448cedf6dac", "packages/plugins/sdk/src/ui/clipboard.ts": "1f42069c97d731e636a6ad5481dad22d20c0ed63", "packages/plugins/sdk/src/ui/components.ts": "3f0594408a1bb5ac3a8d00e709f91877dd260359", "packages/plugins/sdk/src/ui/hooks.ts": "686d02cf4b35f1cddb79a83a4c4d81fd52f0100e", "packages/plugins/sdk/src/ui/index.ts": "f7d1cee64a8f0c924bd10a1bd20745a52fe2060e", "packages/plugins/sdk/src/ui/runtime.ts": "998428e9701eba3b762d3417236d32c2d0d5763d", "packages/plugins/sdk/src/ui/types.ts": "5a5644acf6554d2e5e1d000bfd03b97d57001eb2", - "packages/plugins/sdk/src/worker-rpc-host.ts": "820c73c7d4c681296ef8c813a68ab2bd9901d339", + "packages/plugins/sdk/src/worker-rpc-host.ts": "1fe5ce2c81362af765db249a4c804dfd04688683", "packages/plugins/sdk/src/workspace-operation-error.ts": "2cd247d002d83b163239229e631bca4e519e5075", "packages/plugins/sdk/src/workspace-provider.ts": "38e945b807f22150710c11b136af0a28aab2cb7c", "packages/plugins/sdk/tsconfig.json": "d62ebdff94bc4b75dabf1fcad187e1e7a90fc794",