diff --git a/packages/shared/src/constants.ts b/packages/shared/src/constants.ts index 6204293794b..2ccbd70a01d 100644 --- a/packages/shared/src/constants.ts +++ b/packages/shared/src/constants.ts @@ -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", diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 03b2c7c74f5..3ff15a1891c 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -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, diff --git a/packages/shared/src/types/heartbeat.ts b/packages/shared/src/types/heartbeat.ts index e5449f8a58a..68fed072e37 100644 --- a/packages/shared/src/types/heartbeat.ts +++ b/packages/shared/src/types/heartbeat.ts @@ -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; } /** diff --git a/packages/shared/src/types/index.ts b/packages/shared/src/types/index.ts index 44184c2bada..f8eedd126cf 100644 --- a/packages/shared/src/types/index.ts +++ b/packages/shared/src/types/index.ts @@ -1038,6 +1038,7 @@ export type { HeartbeatRun, HeartbeatRunEvent, HeartbeatRunStatusPhase, + HeartbeatRunStartupStageEvent, ProviderTraceDebugRequest, ProviderTraceDirection, ProviderTraceDisposition, diff --git a/server/src/__tests__/heartbeat-execution-configuration.test.ts b/server/src/__tests__/heartbeat-execution-configuration.test.ts index 85ea381f2fe..ae185685bd6 100644 --- a/server/src/__tests__/heartbeat-execution-configuration.test.ts +++ b/server/src/__tests__/heartbeat-execution-configuration.test.ts @@ -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(); + 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 | 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" }, diff --git a/server/src/services/execution-preparation-timing.ts b/server/src/services/execution-preparation-timing.ts index 33f09ee7207..a8c7e27f07e 100644 --- a/server/src/services/execution-preparation-timing.ts +++ b/server/src/services/execution-preparation-timing.ts @@ -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(runId: string, name: string, work: () => T | Promise, independent = false, counts: { fileCount?: number; bytes?: number } = {}, activeParent?: Context, recordRunId?: string): Promise { 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. diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 3bdd1d4453c..57de23a915b 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -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, diff --git a/server/src/services/heartbeat/run-lifecycle.ts b/server/src/services/heartbeat/run-lifecycle.ts index d41ab0b41f4..87eca2e4730 100644 --- a/server/src/services/heartbeat/run-lifecycle.ts +++ b/server/src/services/heartbeat/run-lifecycle.ts @@ -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, }; } diff --git a/server/src/services/native-runtime/native-run-trace.ts b/server/src/services/native-runtime/native-run-trace.ts index 2e8f5c54676..b833f315c35 100644 --- a/server/src/services/native-runtime/native-run-trace.ts +++ b/server/src/services/native-runtime/native-run-trace.ts @@ -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. diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index 03e8819f295..518e3d7ac65 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -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) => ({ + 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", diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 6a010df0d3c..6ca4d9d40e8 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -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); diff --git a/server/src/services/run-startup-stage.test.ts b/server/src/services/run-startup-stage.test.ts new file mode 100644 index 00000000000..9a7afdb2e82 --- /dev/null +++ b/server/src/services/run-startup-stage.test.ts @@ -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(); + }); +}); diff --git a/server/src/services/run-startup-stage.ts b/server/src/services/run-startup-stage.ts new file mode 100644 index 00000000000..24ac17fc9c8 --- /dev/null +++ b/server/src/services/run-startup-stage.ts @@ -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 = 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 = 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(); + +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, + 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(); +} diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 10fd54bd3e3..435019760d8 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -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",