feat(runs): track each run's startup stage for the board (#22953)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - When a run starts, Core claims it, prepares the host, acquires and
prepares the execution environment, restores the saved session, sets up
tools, and starts the agent's runner.
> - The task view shows "Thinking" for all of that time, so a slow cold
start looks like a slow model.
> - Core already times each of these steps (`heartbeat.prepare.*`,
`native.controller.*` and the native run trace), but nothing tells the
board which step is running.
> - This pull request adds a closed list of startup stages and a
process-local tracker that follows those timed steps. It sends the
current stage to the board as a live event and adds it to active run
reads.
> - The benefit is that the board can say what a run is doing before the
agent's turn starts. The UI change comes in a stacked pull request.

## Linked Issues or Issue Description

No public issue exists.

**Subsystem affected**
Run execution status (`server/src/services/heartbeat*`, native runtime
trace) and the shared run types.

**Problem or motivation**
From the claim to the agent's first turn, the task view always says
"Thinking". On a test instance over 24 hours, the median time before the
first agent event was 10 to 50 seconds. Most of it was environment
setup, session migration (median 0.3 s, P90 14 s) and tool setup (median
8 s, P90 18 s), not model time. A user cannot tell a slow start from a
slow model.

**Proposed solution**
Name the startup steps that every execution environment goes through and
report the current one. Derive the stages from the steps Core already
times, so the stage and the trace spans cannot drift apart.

**Alternatives considered**
Free text from each environment, which gives inconsistent wording and
lets an environment show arbitrary text. Grouping by where the work
runs, which breaks the order because Core does host work both before and
after it acquires the environment.

## What Changed

- `packages/shared`: add `RUN_STARTUP_STAGES` (`getting_ready`,
`starting_environment`, `preparing_workspace`, `restoring_session`,
`connecting_tools`, `starting_agent`), the `heartbeat.run.startup_stage`
live event type and its payload type, and the `startupStage` and
`startupSessionResumed` run fields.
- `server/src/services/run-startup-stage.ts`: a process-local tracker.
One table maps timed step names to stages. A run only moves forward
within one execution attempt. Startup ends at the agent turn, turn
submission or first agent activity (native runs), or when the heartbeat
enters a direct adapter. When startup ends, the stage clears but the
attempt keeps its resumed-session flag until the attempt ends. The store
is bounded (512 runs, and a 1 hour TTL while a stage shows).
- The preparation timing helper (`measure`) and the native run trace
(`start`, which `record` also uses) report each step to the tracker. The
heartbeat starts tracking when a run starts executing and stops when the
execution ends. The native executor reports a resumed provider session.
- `tests/runner-e2e/source-sdk-public-inputs.json`: regenerated, because
the pinned shared SDK sources changed.
- `decorateHeartbeatRunRuntimeStatus` adds `startupStage` and
`startupSessionResumed` to active run reads and clears them for ended
runs.
- The native session executor ends startup when a run that reattached
after a restart sees its turn already under way: a replayed
`turn.submitted` or `turn.started`, or agent output, including output
that arrives before this attempt saw its own `turn.started`.

## Verification

- `npx vitest run src/services/run-startup-stage.test.ts` (13 tests):
stage order, the forward-only rule, skipped stages, the end of startup,
unknown runs, the resumed session (also after the turn starts), a new
attempt, company and agent checks, TTL and the size bound, the real
timing helper and native trace hooks, and active run reads.
- `npx vitest run
src/__tests__/heartbeat-execution-configuration.test.ts`: a new case
runs a registered direct adapter through real preparation on the test
Postgres. Each run publishes `getting_ready`, `starting_environment`,
`preparing_workspace`, then the end of startup, and no stage shows while
the adapter runs.
- `cd tests/runner-e2e && npx vitest run
source-sdk-public-inputs.test.mjs source-sdk-public-type.test.ts
source-sdk-evidence.test.ts` (59 tests) after the registry refresh.
- The CI failure in `adapter-utils` `run-fault-matrix.test.ts`
(`case_14c`) is in a package this change does not touch. It passed three
times locally.
- Existing tests near the change pass: `native-run-trace.test.ts`,
`native-run-trace-context.test.ts`,
`heartbeat/preparation-timing-context.test.ts`,
`heartbeat-run-runtime-status.test.ts`,
`realtime/live-event-delivery.test.ts` (108 tests).
- `npx vitest run
src/services/native-runtime/native-session-executor.test.ts -t "native
startup stage after a restart|native resumed preparation timing"` (16
tests): a reattached run leaves startup on a replayed turn start and on
new agent output. Both new cases fail without the fix.
- `pnpm --filter @paperclipai/shared typecheck` and `pnpm --filter
@paperclipai/server typecheck` pass.
- CI runs the full suite.

## Risks

- Low risk. The tracker is in memory only and is never persisted. A
server restart clears it, and the board then shows what it shows today.
No run, session or launch state changes shape, so no saved state needs a
migration.
- Every hook is wrapped so that a tracker error cannot fail a run or its
trace.
- The live event uses the existing `heartbeat.run.*` delivery rule: it
needs a `runId` and the viewer's run read access.
- One extra live event per stage change (at most about seven for each
run attempt).

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, Honeycomb trace queries for the timing data).

## 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:
Nicky LeachandClaude Opus 5.5 authored and GitHub committed 2026-11-30 16:22:07 +00:00
1 parent e7ed0c2f93
commit 76e3b7e172
14 files changed
+515 -4

No files matched your search

+17
View File
@@ -1117,10 +1117,27 @@ export const RUN_LIVENESS_STATES = [
] as const;
export type RunLivenessState = (typeof RUN_LIVENESS_STATES)[number];
/**
* Startup steps of a run between its claim and its first agent turn, in the
* order they happen on every execution environment. A run moves only forward
* through this list within one execution attempt. The board shows the current
* step instead of a generic "Thinking" until the agent's turn starts.
*/
export const RUN_STARTUP_STAGES = [
"getting_ready",
"starting_environment",
"preparing_workspace",
"restoring_session",
"connecting_tools",
"starting_agent",
] as const;
export type RunStartupStage = (typeof RUN_STARTUP_STAGES)[number];
export const LIVE_EVENT_TYPES = [
"heartbeat.run.queued",
"heartbeat.run.status",
"heartbeat.run.progress",
"heartbeat.run.startup_stage",
"heartbeat.run.event",
"heartbeat.run.log",
"heartbeat.run.activity",
+3
View File
@@ -577,6 +577,7 @@ export {
HEARTBEAT_INVOCATION_SOURCES,
HEARTBEAT_RUN_STATUSES,
RUN_LIVENESS_STATES,
RUN_STARTUP_STAGES,
WAKEUP_TRIGGER_DETAILS,
WAKEUP_REQUEST_STATUSES,
LIVE_EVENT_TYPES,
@@ -780,6 +781,7 @@ export {
type WakeupTriggerDetail,
type WakeupRequestStatus,
type LiveEventType,
type RunStartupStage,
type PrincipalType,
type MembershipStatus,
type CompanyMembershipRole,
@@ -1428,6 +1430,7 @@ export type {
HeartbeatRun,
HeartbeatRunEvent,
HeartbeatRunStatusPhase,
HeartbeatRunStartupStageEvent,
ProviderTraceDebugRequest,
ProviderTraceDirection,
ProviderTraceDisposition,
+20
View File
@@ -4,6 +4,7 @@ import type {
HeartbeatInvocationSource,
HeartbeatRunStatus,
RunLivenessState,
RunStartupStage,
WakeupTriggerDetail,
WakeupRequestStatus,
} from "../constants.js";
@@ -242,6 +243,25 @@ export interface HeartbeatRun {
currentToolName?: string | null;
lastAssistantSnippet?: string | null;
lastEventAt?: Date | string | null;
/**
* Ephemeral, process-local startup step of an active run that has not yet
* started its agent turn. Like `currentStatusMessage`, it is never persisted
* and is null once the turn starts, the run ends, or the server restarts.
*/
startupStage?: RunStartupStage | null;
/** True once the provider confirmed it resumed a saved session for this run. */
startupSessionResumed?: boolean;
}
/** Payload of the `heartbeat.run.startup_stage` live event. */
export interface HeartbeatRunStartupStageEvent {
runId: string;
agentId: string;
issueId: string | null;
/** Null once the agent's turn has started or the run ended. */
stage: RunStartupStage | null;
sessionResumed: boolean;
updatedAt: string;
}
/**
+1
View File
@@ -1038,6 +1038,7 @@ export type {
HeartbeatRun,
HeartbeatRunEvent,
HeartbeatRunStatusPhase,
HeartbeatRunStartupStageEvent,
ProviderTraceDebugRequest,
ProviderTraceDirection,
ProviderTraceDisposition,
@@ -13,6 +13,8 @@ import { skillVersionCachePaths, withSkillVersionCacheLock } from "../services/s
import { registerServerAdapter, unregisterServerAdapter, type AdapterExecutionContext } from "../adapters/index.js";
import { HttpError } from "../errors.js";
import { heartbeatService } from "../services/heartbeat.js";
import { subscribeCompanyLiveEvents } from "../services/live-events.js";
import { getRunStartupStage } from "../services/run-startup-stage.js";
import { bindHeartbeatRunnerHomeMode, prepareHeartbeatExecutionConfiguration, type HeartbeatExecutionConfigurationInput } from "../services/heartbeat/execution-configuration.js";
import { buildEffectiveRunSessionConfigMetadata, resolveTaskSessionConfigFreshness } from "../services/heartbeat/workspaces.js";
import { aiConnectionBindingSchema, type Environment } from "@paperclipai/shared";
@@ -203,6 +205,30 @@ describePostgres("heartbeat execution configuration through adapter dispatch", (
return { finished, input: captured.get(run!.id) };
}
it("ends a direct adapter's startup stage when the adapter takes over", async () => {
const f = await seed();
const stagesByRun = new Map<unknown, unknown[]>();
const unsubscribe = subscribeCompanyLiveEvents(f.companyId, event => {
if (event.type !== "heartbeat.run.startup_stage") return;
stagesByRun.set(event.payload.runId, [...stagesByRun.get(event.payload.runId) ?? [], event.payload.stage]);
});
let duringExecution: ReturnType<typeof getRunStartupStage> | undefined;
inspect.set(f.agentId, async input => { duringExecution = getRunStartupStage(input.runId); });
try {
await execute(f);
} finally {
unsubscribe();
inspect.delete(f.agentId);
}
// The adapter reports its own progress, so no startup stage covers its work.
expect(duringExecution).toEqual({ stage: null, sessionResumed: false });
// Each run (the wake and any follow-up it starts) moves forward once.
expect(stagesByRun.size).toBeGreaterThan(0);
for (const stages of stagesByRun.values()) {
expect(stages).toEqual(["getting_ready", "starting_environment", "preparing_workspace", null]);
}
});
it.each([
{ saved: "isolated", managed: true, failure: "saved managed login required" },
{ saved: "isolated", managed: false, failure: "saved isolated skills required" },
@@ -3,6 +3,7 @@ import { withDatabaseOperation } from "@paperclipai/db";
import { EXECUTION_PREPARATION_SPAN_ATTRS, getActiveStepContext, runWithRuntimeParent } from "@paperclipai/adapter-utils/acpx-engine/startup-timing";
import { createHash } from "node:crypto";
import { isSpanContextValid, ROOT_CONTEXT, SpanStatusCode, trace, type Context, type Span } from "@opentelemetry/api";
import { noteRunStartupStep } from "./run-startup-stage.js";
type PreparationPhase = "environment_selection" | "execution_configuration" | "session"
| "agent_read" | "chat_completion" | "conversation" | "runtime_state" | "issue_context"
@@ -214,6 +215,8 @@ export function drainRunPreparationPhases(runId: string): RecordedPreparationPha
function measure<T>(runId: string, name: string, work: () => T | Promise<T>, independent = false, counts: { fileCount?: number; bytes?: number } = {}, activeParent?: Context, recordRunId?: string): Promise<T> {
const startedAtMs = Date.now();
// The board's startup status follows the same timed steps (run-startup-stage).
try { noteRunStartupStep(runId, name); } catch { /* Status display never fails the work. */ }
const operation = measureTraced(runId, name, work, independent, counts, activeParent, recordRunId);
// Only pre-dispatch preparation reaches the run log here; execution attempts
// and runtime timings belong to the turn, not to the next attempt's prepare.
+8
View File
@@ -48,6 +48,7 @@ import { hasStoppedLocalProcessTree, legacyAdapterNeedsLocalProcessSettlement }
import { dotRunnerBroker } from "./dot-runner-broker.js";
import { withRunExecutionTiming, measureRunPhase, measureWorkspaceSyncPhase, isWorkspaceSyncDetailPhase } from "./execution-preparation-timing.js";
import { createHeartbeatPreparationTiming } from "./heartbeat/preparation-timing.js";
import { beginRunStartupStages, endRunStartup, finishRunStartupStages } from "./run-startup-stage.js";
import { createHeartbeatInstructionCopyRelease, createHeartbeatInstructionWorkingCopy } from "./heartbeat/instruction-working-copy.js";
import { AgentDirectoryPreparationDeferral, deferRunForBusyAgentDirectory, prepareWithAgentDirectoryDeferral, REATTACH_AGENT_DIRECTORY_WAIT_MS } from "./heartbeat/agent-directory-busy.js";
import { preparePredecessorRetirementFallback } from "./heartbeat/predecessor-retirement-fallback.js";
@@ -2129,6 +2130,10 @@ export function heartbeatService(
if (run.runtimeMode === "legacy" && run.controllerBootId &&
run.controllerBootId !== legacyControllerBootId) return;
activeRunExecutions.add(run.id);
try {
beginRunStartupStages({ id: run.id, companyId: run.companyId, agentId: run.agentId,
issueId: run.issueId ?? (typeof run.contextSnapshot?.issueId === "string" ? run.contextSnapshot.issueId : null) });
} catch (error) { logger.warn({ runId: run.id, error }, "Could not start run startup status"); }
const timePreparation = createHeartbeatPreparationTiming(run.id);
const executionControl = createAdapterExecutionControl();
endStorageOutageWaitOn(executionControl.controller.signal);
@@ -3836,6 +3841,8 @@ export function heartbeatService(
onNativeDispatchStarted: () => { nativeDispatchStarted = true; },
onLegacyAdapterEntered: () => {
legacyAdapterEntered = true;
// A direct adapter reports its own progress from here on.
try { endRunStartup(run.id); } catch { /* Status display never blocks dispatch. */ }
legacyLocalAdapterEntered = legacyAdapterNeedsLocalProcessSettlement({
adapterType: adapter.type, executionTargetKind: executionTarget?.kind,
});
@@ -4399,6 +4406,7 @@ export function heartbeatService(
} finally {
controllerLease.stop();
activeRunExecutions.delete(run.id);
try { finishRunStartupStages(run.id); } catch { /* Status display never blocks settlement. */ }
heartbeatQueue.releaseClaimBackoffsForTask(run);
if (restartClaimLapsed || detachedWithoutHandoff) scheduleNativeSessionResumeDispatch(run.id, new Date(), "restart");
// A failed owned Stop remains visible until this exact executor settles,
@@ -204,6 +204,8 @@ import {
MAX_HEARTBEAT_RUN_RUNTIME_TOOL_NAME_CHARS,
setHeartbeatRunRuntimeStatus,
} from "../heartbeat-run-runtime-status.js";
import { clearRunStartupStage, getRunStartupStage } from "../run-startup-stage.js";
import type { RunStartupStage } from "@paperclipai/shared";
import { readProcessStartedAt } from "../hot-restart.js";
import { currentProcessSpaceHash } from "../controller-process-identity.js";
@@ -361,9 +363,12 @@ export function decorateHeartbeatRunRuntimeStatus<
currentToolName: string | null;
lastAssistantSnippet: string | null;
lastEventAt: Date | null;
startupStage: RunStartupStage | null;
startupSessionResumed: boolean;
} {
if (isHeartbeatRunTerminalStatus(run.status)) {
clearHeartbeatRunRuntimeStatus(run.id);
clearRunStartupStage(run.id);
}
const companyId = expected.companyId ?? run.companyId ?? null;
@@ -380,6 +385,10 @@ export function decorateHeartbeatRunRuntimeStatus<
...(issueId !== undefined ? { issueId } : {}),
})
: null;
const startup =
isHeartbeatRunRuntimeStatusActive(run.status)
? getRunStartupStage(run.id, { companyId, agentId })
: null;
return {
...run,
@@ -390,6 +399,8 @@ export function decorateHeartbeatRunRuntimeStatus<
currentToolName: currentStatus?.currentToolName ?? null,
lastAssistantSnippet: currentStatus?.lastAssistantSnippet ?? null,
lastEventAt: currentStatus?.lastEventAt ?? null,
startupStage: startup?.stage ?? null,
startupSessionResumed: startup?.sessionResumed ?? false,
};
}
@@ -16,6 +16,7 @@ import {
type SpeedBudgetBreach,
type SpeedBudgetStart,
} from "./native-speed-budgets.js";
import { noteRunStartupStep } from "../run-startup-stage.js";
export const NATIVE_RUN_SPAN_EVENT_TYPE = "run.performance.span";
export const NATIVE_RUN_TRACE_SCHEMA_VERSION = 3;
@@ -463,6 +464,7 @@ export function createNativeRunTrace(input: {
} = {},
): NativeRunSpanScope => {
const startedAtMs = finiteMs(options.startedAtMs ?? Date.now());
try { noteRunStartupStep(input.runId, name); } catch { /* Status display never fails the trace. */ }
if (name === PROVIDER_SESSION_LOAD_SPAN) {
providerLoadStartsMs.push(startedAtMs);
// The measurement can arrive before its provider span is recorded; judge now.
@@ -22,6 +22,7 @@ import { trace } from "@opentelemetry/api";
import { InMemorySpanExporter, SimpleSpanProcessor, TracerProvider } from "@opentelemetry/sdk-trace";
import { configuredEnvironment, configuredEnvironmentProjection } from "../../vendor/paperclip-runner/index.js";
import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";
import { beginRunStartupStages, finishRunStartupStages, getRunStartupStage } from "../run-startup-stage.js";
import { TOOL_CALL_LOOP_REFUSAL_LIMIT, ToolCallLoopError, toolCallLoopContinuationKey } from "./repeated-tool-failure-guard.js";
import { enableReattachPhase, isReattachPhaseActive, joinReattachPhase, onReattachPhaseEnd, resetReattachPhaseForTests, type ReattachPhaseSummary } from "../heartbeat/run-admission.js";
import { createSystemRecovery, failSystemRecovery, reserveSystemRecoveryAttempt, SystemRecoveryFailure } from "../system-recovery-state.js";
@@ -10454,6 +10455,37 @@ describe("native terminal-turn accounting", () => {
});
});
describe("native startup stage after a restart", () => {
it.each(["a replayed turn start", "new agent output"] as const)("ends startup when a reattached run sees %s", async (mode) => {
const runId = execution.binding.runId;
const event = (eventType: string, payload: Record<string, unknown>) => ({
eventType, payload, itemId: "message", emittedAt: new Date().toISOString(),
}) as PrpEvent;
beginRunStartupStages({ id: runId, companyId: execution.binding.companyId, agentId: execution.binding.agentId, issueId: null });
let before: unknown, after: unknown;
state.execute.mockReset().mockImplementationOnce(async () => {
before = getRunStartupStage(runId)?.stage;
// The turn's start was saved before the restart, so this attempt sees it
// only as duplicates; new output arrives with no turn.started of its own.
if (mode === "a replayed turn start") {
await accountingEvents.duplicate!(event("turn.submitted", {}));
await accountingEvents.duplicate!(event("turn.started", {}));
} else {
await accountingEvents.committed!(event("item.delta", { kind: "agentMessage", text: "resumed text" }));
}
after = getRunStartupStage(runId);
return { result: { summary: "cancelled" }, terminal: { runTerminalState: "cancelled" },
turnId: "turn", normalizedSessionId: "session", providerSessionId: null,
driverKind: "test", driverVersion: "1", nativeEventCount: 1, highestContiguousSourceSeq: 1 };
});
try {
await executePaperclipNativeSession({ db: leaseDb(), execution, runnerInstanceId: "runner", onEvent: async () => {} });
} finally { finishRunStartupStages(runId); }
expect(before).not.toBeNull();
expect(after).toEqual({ stage: null, sessionResumed: false });
});
});
describe("native resumed preparation timing", () => {
it.each(["comment.to_run_created", "question_response.to_run_created", "heartbeat.queue", "native_dispatch"])(
"records first assistant text once from %s through Core preparation and event receipt",
@@ -101,6 +101,7 @@ import {
isKnownNativeSessionRootEntry,
} from "./native-session-root-entries.js";
import { createRunPreparationTiming } from "../execution-preparation-timing.js";
import { endRunStartup, noteRunStartupSessionResumed } from "../run-startup-stage.js";
import { CONFIGURED_ENVIRONMENT_KEYS, configuredEnvironment, PROVIDER_CREDENTIAL_ENVIRONMENT_KEYS } from "../../vendor/paperclip-runner/index.js";
import { parseProviderPerformanceSpans } from "../../vendor/paperclip-runner/index.js";
import { apiKeyBillingType } from "@paperclipai/adapter-utils/api-billing-type";
@@ -12065,6 +12066,7 @@ async function executePaperclipNativeSessionAttempt(
});
}
if (event.eventType === "session.resumed") {
noteRunStartupSessionResumed(input.execution.binding.runId);
await emitStartupReuse(input.onEvent, "provider_session", { state: "reused", reason: "verified_reuse" });
trace.setBudgetStart("warm");
}
@@ -12122,6 +12124,9 @@ async function executePaperclipNativeSessionAttempt(
endedAtMs: milestoneAtMs,
});
}
// Agent output means the turn is under way, even for an attempt that
// reattached to a turn whose start was saved before a restart.
if (firstMeaningfulAgentEventKind(event)) endRunStartup(input.execution.binding.runId);
if (!firstAgentEventRecorded && turnStartedAtMs !== null) {
const kind = firstMeaningfulAgentEventKind(event);
if (kind) {
@@ -12270,6 +12275,11 @@ async function executePaperclipNativeSessionAttempt(
);
},
onDuplicateEvent: async (event, cursor) => {
// A replayed turn start or agent output, after a restart, shows the
// turn was already under way, so the run is past startup.
if (event.eventType === "turn.submitted" || event.eventType === "turn.started" || firstMeaningfulAgentEventKind(event)) {
endRunStartup(input.execution.binding.runId);
}
await input.onPersistedNativeLog?.(cursor, formatNativeRunLogEvent(event));
if (!firstTokenRecorded) observeDeliverableText(event);
await observeAccountingEvent(event);
@@ -0,0 +1,215 @@
import { afterEach, describe, expect, it } from "vitest";
import type { LiveEvent } from "@paperclipai/shared";
import { createRunPreparationTiming } from "./execution-preparation-timing.js";
import { decorateHeartbeatRunRuntimeStatus } from "./heartbeat/run-lifecycle.js";
import { subscribeCompanyLiveEvents } from "./live-events.js";
import { createNativeRunTrace } from "./native-runtime/native-run-trace.js";
import {
beginRunStartupStages,
clearAllRunStartupStages,
endRunStartup,
finishRunStartupStages,
getRunStartupStage,
MAX_TRACKED_RUN_STARTUPS,
noteRunStartupSessionResumed,
noteRunStartupStep,
RUN_STARTUP_STAGE_TTL_MS,
runStartupStageForStep,
} from "./run-startup-stage.js";
const companyId = "company-startup-stage";
const run = { id: "run-1", companyId, agentId: "agent-1", issueId: "issue-1" };
function recordEvents() {
const events: LiveEvent[] = [];
const unsubscribe = subscribeCompanyLiveEvents(companyId, event => {
if (event.type === "heartbeat.run.startup_stage") events.push(event);
});
return { events, unsubscribe, stages: () => events.map(event => event.payload.stage) };
}
afterEach(() => clearAllRunStartupStages());
describe("run startup stages", () => {
it("maps Core's timed steps to stages", () => {
expect(runStartupStageForStep("heartbeat.prepare.agent_read")).toBe("getting_ready");
expect(runStartupStageForStep("heartbeat.prepare.workspace_environment_acquire")).toBe("starting_environment");
expect(runStartupStageForStep("heartbeat.prepare.workspace_environment_realize")).toBe("preparing_workspace");
expect(runStartupStageForStep("native.controller.state_migration")).toBe("restoring_session");
expect(runStartupStageForStep("native.controller.backend_setup")).toBe("connecting_tools");
expect(runStartupStageForStep("runner.session.startup")).toBe("starting_agent");
expect(runStartupStageForStep("agent.turn")).toBe("started");
expect(runStartupStageForStep("runner.turn.submit")).toBe("started");
expect(runStartupStageForStep("task.time_to_first_agent_activity")).toBe("started");
expect(runStartupStageForStep("native.controller.github_access")).toBeNull();
expect(runStartupStageForStep("workspace.checkout.git_clone")).toBeNull();
});
it("publishes each forward step and ignores steps that would move the run back", () => {
const recorder = recordEvents();
try {
beginRunStartupStages(run);
noteRunStartupStep(run.id, "heartbeat.prepare.workspace_environment_acquire");
noteRunStartupStep(run.id, "heartbeat.prepare.workspace_environment_realize");
// Host preparation after the environment keeps the later stage.
noteRunStartupStep(run.id, "heartbeat.prepare.instructions");
noteRunStartupStep(run.id, "native.controller.state_migration");
noteRunStartupStep(run.id, "native.controller.backend_setup");
noteRunStartupStep(run.id, "native.controller.github_access");
noteRunStartupStep(run.id, "runner.session.startup");
expect(recorder.stages()).toEqual([
"getting_ready", "starting_environment", "preparing_workspace",
"restoring_session", "connecting_tools", "starting_agent",
]);
expect(recorder.events[0]?.payload).toMatchObject({ runId: run.id, agentId: run.agentId, issueId: run.issueId });
expect(getRunStartupStage(run.id)).toEqual({ stage: "starting_agent", sessionResumed: false });
} finally {
recorder.unsubscribe();
}
});
it("skips stages that a run does not need", () => {
const recorder = recordEvents();
try {
beginRunStartupStages(run);
noteRunStartupStep(run.id, "runner.session.startup");
noteRunStartupStep(run.id, "native.controller.backend_setup");
expect(recorder.stages()).toEqual(["getting_ready", "starting_agent"]);
} finally {
recorder.unsubscribe();
}
});
it("ends startup when the agent turn starts", () => {
const recorder = recordEvents();
try {
beginRunStartupStages(run);
noteRunStartupStep(run.id, "agent.turn");
noteRunStartupStep(run.id, "runner.session.startup");
noteRunStartupStep(run.id, "agent.turn");
expect(recorder.stages()).toEqual(["getting_ready", null]);
expect(getRunStartupStage(run.id)).toEqual({ stage: null, sessionResumed: false });
finishRunStartupStages(run.id);
expect(recorder.stages()).toEqual(["getting_ready", null]);
expect(getRunStartupStage(run.id)).toBeNull();
} finally {
recorder.unsubscribe();
}
});
it("ignores runs that are not executing here", () => {
const recorder = recordEvents();
try {
noteRunStartupStep("other-run", "runner.session.startup");
noteRunStartupSessionResumed("other-run");
finishRunStartupStages("other-run");
expect(recorder.events).toEqual([]);
} finally {
recorder.unsubscribe();
}
});
it("publishes a resumed session once", () => {
const recorder = recordEvents();
try {
beginRunStartupStages(run);
noteRunStartupStep(run.id, "runner.session.startup");
noteRunStartupSessionResumed(run.id);
noteRunStartupSessionResumed(run.id);
expect(recorder.events.map(event => event.payload.sessionResumed)).toEqual([false, false, true]);
expect(getRunStartupStage(run.id)).toEqual({ stage: "starting_agent", sessionResumed: true });
} finally {
recorder.unsubscribe();
}
});
it("starts a new attempt over", () => {
beginRunStartupStages(run);
noteRunStartupStep(run.id, "runner.session.startup");
noteRunStartupSessionResumed(run.id);
beginRunStartupStages(run);
expect(getRunStartupStage(run.id)).toEqual({ stage: "getting_ready", sessionResumed: false });
});
it("reads only the expected company and agent, and expires stale entries", () => {
beginRunStartupStages(run);
expect(getRunStartupStage(run.id, { companyId: "other" })).toBeNull();
expect(getRunStartupStage(run.id, { agentId: "other" })).toBeNull();
expect(getRunStartupStage(run.id, { companyId, agentId: run.agentId })?.stage).toBe("getting_ready");
expect(getRunStartupStage(run.id, { now: new Date(Date.now() + RUN_STARTUP_STAGE_TTL_MS + 1) })).toBeNull();
expect(getRunStartupStage(run.id)).toBeNull();
});
it("keeps tracking when a live-event listener throws", () => {
const unsubscribe = subscribeCompanyLiveEvents(companyId, () => { throw new Error("listener failed"); });
try {
expect(() => beginRunStartupStages(run)).not.toThrow();
expect(() => noteRunStartupStep(run.id, "runner.session.startup")).not.toThrow();
expect(() => noteRunStartupSessionResumed(run.id)).not.toThrow();
expect(getRunStartupStage(run.id)).toEqual({ stage: "starting_agent", sessionResumed: true });
expect(() => endRunStartup(run.id)).not.toThrow();
expect(getRunStartupStage(run.id)).toEqual({ stage: null, sessionResumed: true });
beginRunStartupStages({ ...run, id: "run-2" });
expect(() => finishRunStartupStages("run-2")).not.toThrow();
expect(getRunStartupStage("run-2")).toBeNull();
} finally {
unsubscribe();
}
});
it("bounds the number of tracked runs", () => {
for (let index = 0; index <= MAX_TRACKED_RUN_STARTUPS; index += 1) {
beginRunStartupStages({ ...run, id: `run-${index}` });
}
expect(getRunStartupStage("run-0")).toBeNull();
expect(getRunStartupStage(`run-${MAX_TRACKED_RUN_STARTUPS}`)?.stage).toBe("getting_ready");
});
it("follows the steps Core times and the native trace", async () => {
beginRunStartupStages(run);
await createRunPreparationTiming(run.id)("workspace_environment_acquire", () => undefined);
expect(getRunStartupStage(run.id)?.stage).toBe("starting_environment");
await createRunPreparationTiming(run.id, "native.controller")("backend_setup", () => undefined);
expect(getRunStartupStage(run.id)?.stage).toBe("connecting_tools");
const trace = createNativeRunTrace({ runId: run.id });
trace.start("runner.session.startup");
expect(getRunStartupStage(run.id)?.stage).toBe("starting_agent");
trace.start("agent.turn");
expect(getRunStartupStage(run.id)?.stage).toBeNull();
});
it("ends startup on recorded first agent activity when no turn span starts", async () => {
beginRunStartupStages(run);
const trace = createNativeRunTrace({ runId: run.id });
trace.start("runner.session.startup");
const now = Date.now();
await trace.record({ name: "task.time_to_first_agent_activity", parentName: "task.provider_session",
startedAtMs: now - 1_000, endedAtMs: now });
expect(getRunStartupStage(run.id)?.stage).toBeNull();
});
it("keeps a confirmed resume for the attempt after its turn starts", () => {
beginRunStartupStages(run);
noteRunStartupStep(run.id, "runner.session.startup");
noteRunStartupSessionResumed(run.id);
endRunStartup(run.id);
const later = new Date(Date.now() + RUN_STARTUP_STAGE_TTL_MS + 1);
expect(getRunStartupStage(run.id, { now: later })).toEqual({ stage: null, sessionResumed: true });
finishRunStartupStages(run.id);
expect(getRunStartupStage(run.id)).toBeNull();
});
it("adds the stage to active run reads and drops it for ended runs", () => {
beginRunStartupStages(run);
noteRunStartupStep(run.id, "native.controller.backend_setup");
const base = { id: run.id, companyId, agentId: run.agentId, issueId: run.issueId };
expect(decorateHeartbeatRunRuntimeStatus({ ...base, status: "running" })).toMatchObject({
startupStage: "connecting_tools", startupSessionResumed: false,
});
expect(decorateHeartbeatRunRuntimeStatus({ ...base, status: "succeeded" })).toMatchObject({
startupStage: null, startupSessionResumed: false,
});
expect(getRunStartupStage(run.id)).toBeNull();
});
});
+163
View File
@@ -0,0 +1,163 @@
import { RUN_STARTUP_STAGES, type HeartbeatRunStartupStageEvent, type RunStartupStage } from "@paperclipai/shared";
import { logger } from "../middleware/logger.js";
import { publishLiveEvent } from "./live-events.js";
/**
* Process-local startup step of each executing run, for the board's live
* status line. Like the runtime status store it is never persisted: a server
* restart, the agent turn starting, or the run ending clears it.
*
* Stages come from the steps Core already times. One table maps step names to
* stages, so the timing spans and the stage the board shows cannot drift apart.
*/
const STAGE_BY_STEP: ReadonlyMap<string, RunStartupStage> = new Map([
["heartbeat.prepare.workspace_environment_acquire", "starting_environment"],
["heartbeat.prepare.workspace_environment_realize", "preparing_workspace"],
["native.controller.state_migration", "restoring_session"],
["native.controller.backend_setup", "connecting_tools"],
["runner.session.startup", "starting_agent"],
]);
/**
* Steps that end startup: the agent's turn has begun. The submit and
* first-activity spans back up `agent.turn` for a run that attaches to a turn
* already in flight, so a stale startup stage never covers agent work.
*/
const STARTUP_END_STEPS: ReadonlySet<string> = new Set([
"agent.turn",
"runner.turn.submit",
"provider.time_to_first_agent_event",
"task.time_to_first_agent_activity",
]);
const STAGE_ORDER = new Map(RUN_STARTUP_STAGES.map((stage, index) => [stage, index]));
/** Bounds a store that a crashed executor might never clear. */
export const MAX_TRACKED_RUN_STARTUPS = 512;
export const RUN_STARTUP_STAGE_TTL_MS = 60 * 60_000;
interface RunStartupEntry {
companyId: string;
agentId: string;
issueId: string | null;
/** Null once the agent's turn has started; the attempt keeps its resume flag. */
stage: RunStartupStage | null;
sessionResumed: boolean;
updatedAt: Date;
}
const entriesByRunId = new Map<string, RunStartupEntry>();
export function runStartupStageForStep(stepName: string): RunStartupStage | "started" | null {
const mapped = STAGE_BY_STEP.get(stepName);
if (mapped) return mapped;
if (STARTUP_END_STEPS.has(stepName)) return "started";
// Any other host preparation step is general setup. It never moves a run
// back, so the steps Core runs after the environment keep the later stage.
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) {
const payload: HeartbeatRunStartupStageEvent = {
runId, agentId: entry.agentId, issueId: entry.issueId, stage, 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.
try {
publishLiveEvent({ companyId: entry.companyId, type: "heartbeat.run.startup_stage", payload: { ...payload } });
} catch (err) {
logger.warn({ runId, stage, err }, "run startup stage notification failed");
}
}
/**
* Starts tracking one execution attempt of a run. A new attempt of the same
* run starts over, because its startup repeats every step.
*/
export function beginRunStartupStages(run: { id: string; companyId: string; agentId: string; issueId: string | null }) {
if (!entriesByRunId.has(run.id) && entriesByRunId.size >= MAX_TRACKED_RUN_STARTUPS) {
const oldest = entriesByRunId.keys().next().value;
if (oldest !== undefined) entriesByRunId.delete(oldest);
}
entriesByRunId.delete(run.id);
const entry: RunStartupEntry = {
companyId: run.companyId, agentId: run.agentId, issueId: run.issueId,
stage: "getting_ready", sessionResumed: false, updatedAt: new Date(),
};
entriesByRunId.set(run.id, entry);
publish(run.id, entry, entry.stage, false, entry.updatedAt);
}
/** Records that a timed step began. Unknown runs and earlier stages are ignored. */
export function noteRunStartupStep(runId: string, stepName: string) {
const entry = entriesByRunId.get(runId);
if (!entry || entry.stage === null) return;
const next = runStartupStageForStep(stepName);
if (next === null) return;
if (next === "started") {
endRunStartup(runId);
return;
}
if ((STAGE_ORDER.get(next) ?? -1) <= (STAGE_ORDER.get(entry.stage) ?? -1)) return;
entry.stage = next;
entry.updatedAt = new Date();
publish(runId, entry, entry.stage, entry.sessionResumed, entry.updatedAt);
}
/** The provider confirmed it resumed a saved session for this run. */
export function noteRunStartupSessionResumed(runId: string) {
const entry = entriesByRunId.get(runId);
if (!entry || entry.sessionResumed) return;
entry.sessionResumed = true;
entry.updatedAt = new Date();
publish(runId, entry, entry.stage, true, entry.updatedAt);
}
/**
* Ends startup because the agent is working: its turn started (native), or a
* direct adapter took over the execution. The attempt keeps its resume flag,
* so a later read still reports a confirmed resumed session.
*/
export function endRunStartup(runId: string) {
const entry = entriesByRunId.get(runId);
if (!entry || entry.stage === null) return;
entry.stage = null;
entry.updatedAt = new Date();
publish(runId, entry, null, entry.sessionResumed, entry.updatedAt);
}
/** Forgets the execution attempt once it ends. */
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());
}
export function getRunStartupStage(
runId: string,
expected: { companyId?: string | null; agentId?: string | null; now?: Date } = {},
): { stage: RunStartupStage | null; sessionResumed: boolean } | null {
const entry = entriesByRunId.get(runId);
if (!entry) return null;
const now = expected.now ?? new Date();
// Only a shown stage can go stale; a started attempt keeps its resume flag
// until the attempt ends (or the store's size bound evicts it).
if (entry.stage !== null && now.getTime() - entry.updatedAt.getTime() > RUN_STARTUP_STAGE_TTL_MS) {
entriesByRunId.delete(runId);
return null;
}
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 };
}
/** Forgets a run without publishing, e.g. once a terminal status is observed. */
export function clearRunStartupStage(runId: string) {
entriesByRunId.delete(runId);
}
export function clearAllRunStartupStages() {
entriesByRunId.clear();
}
@@ -237,7 +237,7 @@
"packages/shared/src/connector-availability.ts": "7797798bc989b774e8b6e62748ad689f66ab4193",
"packages/shared/src/connector-identity.test.ts": "d58357707faefa7c98bb906cdaeb4db39d31081a",
"packages/shared/src/connector-identity.ts": "5ede83c9c5225dbe8af9cf3a49c74e477ef5b955",
"packages/shared/src/constants.ts": "6204293794b5ef24159e1f0e01f686b6847ee6c2",
"packages/shared/src/constants.ts": "2ccbd70a01d76fec6233ec074256637554cca274",
"packages/shared/src/crash-point-registry.ts": "3cbf2d290bc111061376b43020848623e493737c",
"packages/shared/src/crash-points.test.ts": "3564a1f62d22f54a3c2fb0a72b3a6cde17c957d2",
"packages/shared/src/crash-points.ts": "c15259f39610e352eac5423a491548ec1bae94fe",
@@ -279,7 +279,7 @@
"packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d",
"packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca",
"packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699",
"packages/shared/src/index.ts": "03b2c7c74f56d9fcafcaf82b565ac07c8856ccd8",
"packages/shared/src/index.ts": "3ff15a1891c5d35043a58f3b2af4dece970fc8e6",
"packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca",
"packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075",
"packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9",
@@ -436,11 +436,11 @@
"packages/shared/src/types/folder.ts": "451856a6720f91525b846d91ec25f7eff110dba5",
"packages/shared/src/types/github-app-setup.ts": "d36e0b87233d662998c49d2a2d0709bb59bd97e8",
"packages/shared/src/types/goal.ts": "29100192bcc3e0c4c4904e59b5d84874952e67a2",
"packages/shared/src/types/heartbeat.ts": "e5449f8a58a79951cef909d8f4330fe27e29ae3b",
"packages/shared/src/types/heartbeat.ts": "68fed072e37ad155b22e3ddf03b6af60411aba24",
"packages/shared/src/types/inbox-agent-policy.ts": "cb9d41d9681e80b834889268ad96015a39df92f6",
"packages/shared/src/types/inbox-dismissal.ts": "58fb7013847396ac9971eb5799dd0bf0486e0371",
"packages/shared/src/types/inbox-mine.ts": "1d302b531d34842189704abd2f75f8743d09490d",
"packages/shared/src/types/index.ts": "44184c2badaf7cdf46ab5f574e85e0e3fa7a0b60",
"packages/shared/src/types/index.ts": "f8eedd126cf46462eed07976d2f9480ad9194428",
"packages/shared/src/types/instance.ts": "406736718fa7e8f788d4e963291943d38c16a368",
"packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df",
"packages/shared/src/types/issue.ts": "fe78765782a50faf24e91e76e39846a4ace2cfc5",