Skip to content

Commit 26e7738

Browse files
committed
refactor(gateway): unify embedded run recovery
1 parent 70db766 commit 26e7738

26 files changed

Lines changed: 818 additions & 1377 deletions

‎extensions/codex/src/app-server/run-attempt-active-turn.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,6 @@ export async function activateCodexAttemptTurn(
5858
sandboxSessionKey,
5959
contextSessionKey,
6060
effectiveCwd,
61-
attemptStartedAt,
6261
} = connection;
6362
const { dynamicToolParams, compactionPlanState, computerContextEpoch, toolBridge } = attemptTools;
6463
const { state, userInputBridgeRef, steeringQueueRef, turnWatches, completeTurn, interruptTurn } =
@@ -335,7 +334,7 @@ export async function activateCodexAttemptTurn(
335334
const handle = {
336335
kind: "embedded" as const,
337336
runId: params.runId,
338-
startedAtMs: attemptStartedAt,
337+
startedAtMs: params.startedAtMs,
339338
toolAuthorityFingerprint: params.toolAuthorityFingerprint,
340339
claimPendingUserInputAnswer,
341340
cancelPendingUserInput,

‎extensions/codex/src/app-server/run-attempt.steering.test.ts‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -151,11 +151,11 @@ describe("runCodexAppServerAttempt steering", () => {
151151
});
152152
});
153153

154-
it("threads the attempt start time onto the active-turn handle for recovery", async () => {
154+
it("threads the core run start time onto the active-turn handle", async () => {
155155
const { waitForMethod, completeTurn } = createStartedThreadHarness();
156-
const params = createSteeringParams();
156+
const startedAtMs = 1_750_000_000_000;
157+
const params = { ...createSteeringParams(), startedAtMs };
157158
activeRunRegistrationMocks.setActiveEmbeddedRun.mockClear();
158-
const beforeStart = Date.now();
159159
const run = runCodexAppServerAttempt(params);
160160
await waitForMethod("turn/start");
161161

@@ -166,11 +166,7 @@ describe("runCodexAppServerAttempt steering", () => {
166166
)?.[1] as typeof handle;
167167
expect(handle).toBeDefined();
168168
}, fastWait);
169-
const afterStart = Date.now();
170-
171-
expect(handle?.startedAtMs).toBeTypeOf("number");
172-
expect(handle!.startedAtMs!).toBeGreaterThanOrEqual(beforeStart);
173-
expect(handle!.startedAtMs!).toBeLessThanOrEqual(afterStart);
169+
expect(handle?.startedAtMs).toBe(startedAtMs);
174170

175171
await completeTurn({ threadId: "thread-1", turnId: "turn-1" });
176172
await run;

‎extensions/copilot/src/attempt-active-run.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ export function registerCopilotActiveRun(params: {
1717
abortActiveSession: () => void;
1818
bridge: ReturnType<typeof attachEventBridge> | undefined;
1919
canAcceptSteering: () => boolean;
20-
startedAtMs: number;
20+
startedAtMs?: number;
2121
input: AttemptParamsLike;
2222
isAborted: () => boolean;
2323
isSettled: () => boolean;

‎extensions/copilot/src/attempt-execution.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -474,7 +474,7 @@ export async function runCopilotExecution(context: {
474474
abortActiveSession,
475475
bridge,
476476
canAcceptSteering: () => initialSdkUserValidated,
477-
startedAtMs: attemptStartedAt,
477+
startedAtMs: input.startedAtMs,
478478
input,
479479
isAborted: () => aborted,
480480
isSettled: () => settled,

‎packages/gateway-protocol/src/schema/logs-chat.ts‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,17 +38,14 @@ export const ChatHistoryParamsSchema = closedObject({
3838
* Bounded forward catch-up response. Clients replay `messages` as `session.message`
3939
* payloads. There is no continuation loop: more than 200 raw events or the byte
4040
* budget returns `reset`, and the client fetches a fresh tail page.
41-
*
42-
* `inFlightRun` carries the same bounded recovery snapshot as the full response
43-
* when an embedded run is still live, so cached-cursor reloads can adopt it.
4441
*/
4542
export const ChatHistoryDeltaResultSchema = closedObject({
4643
kind: Type.Literal("delta"),
4744
messages: Type.Array(Type.Unknown()),
4845
deltaCursor: Type.String(),
4946
sessionInfo: Type.Unknown(),
50-
inFlightRun: Type.Optional(Type.Unknown()),
5147
agentsList: Type.Optional(Type.Unknown()),
48+
inFlightRun: Type.Optional(Type.Unknown()),
5249
metadata: Type.Optional(Type.Unknown()),
5350
});
5451

‎src/agents/embedded-agent-runner/run-state.ts‎

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,9 @@ import {
1414
type ReplyBackendQueueMessageResult,
1515
type ReplyBackendMessageInjection,
1616
} from "../../auto-reply/reply/reply-run-registry.js";
17-
import type { ChatRunPlanSnapshot } from "../../gateway/server-chat-state.js";
1817
import {
1918
isAgentEventLifecycleGenerationCurrent,
2019
registerAgentEventLifecycleRotationHandler,
21-
type AgentEventPayload,
2220
} from "../../infra/agent-events.js";
2321
import type { DiagnosticEmbeddedRunOwner } from "../../logging/diagnostic-run-activity.js";
2422
import { resolveGlobalSingleton } from "../../shared/global-singleton.js";
@@ -36,7 +34,7 @@ export type EmbeddedAgentQueueHandle = {
3634
readonly diagnosticOwner?: DiagnosticEmbeddedRunOwner;
3735
/** Synchronously closes diagnostic authority before this handle is evicted. */
3836
readonly closeDiagnostics?: () => void;
39-
/** Epoch ms when the embedded run started (authoritative, vs SessionEntry.startedAt which is the subagent first-run time). */
37+
/** Core run start time used by live recovery projections. */
4038
startedAtMs?: number;
4139
/** Exact authority of the concrete provider/model attempt behind this handle. */
4240
toolAuthorityFingerprint?: string;
@@ -77,12 +75,11 @@ export type ActiveEmbeddedRunSnapshot = {
7775
transcriptLeafId: string | null;
7876
messages?: unknown[];
7977
inFlightPrompt?: string;
80-
/** Bounded agent events for Control UI replay after reload. */
81-
events?: AgentEventPayload[];
82-
/** Running byte size of `events`; trims oldest entries to stay within budget. */
83-
byteLength?: number;
84-
/** Latest plan snapshot for Control UI recovery after reload. */
85-
plan?: ChatRunPlanSnapshot;
78+
};
79+
80+
export type EmbeddedRunRegistration = {
81+
sessionId: string;
82+
sessionKey?: string;
8683
};
8784

8885
export type EmbeddedRunWaiter = {
@@ -104,10 +101,10 @@ const EMBEDDED_RUN_STATE_KEY = Symbol.for("openclaw.embeddedRunState");
104101
const embeddedRunState = resolveGlobalSingleton(EMBEDDED_RUN_STATE_KEY, () => ({
105102
activeRuns: new Map<string, EmbeddedAgentQueueHandle>(),
106103
activeRunsByRunId: new Map<string, EmbeddedAgentQueueHandle>(),
104+
activeRunRegistrations: new WeakMap<EmbeddedAgentQueueHandle, EmbeddedRunRegistration>(),
107105
activeRunLifecycleGenerations: new WeakMap<EmbeddedAgentQueueHandle, string>(),
108106
retainedAbortabilityRunIds: new Set<string>(),
109107
snapshots: new Map<string, ActiveEmbeddedRunSnapshot>(),
110-
eventSubscriptionsByRunId: new Map<string, () => void>(),
111108
sessionIdsByKey: new Map<string, string>(),
112109
sessionIdsByFile: new Map<string, string>(),
113110
abandonedRunsBySessionId: new Map<string, AbandonedEmbeddedRun>(),
@@ -124,6 +121,12 @@ export const ACTIVE_EMBEDDED_RUNS =
124121
export const ACTIVE_EMBEDDED_RUNS_BY_RUN_ID =
125122
embeddedRunState.activeRunsByRunId ??
126123
(embeddedRunState.activeRunsByRunId = new Map<string, EmbeddedAgentQueueHandle>());
124+
export const ACTIVE_EMBEDDED_RUN_REGISTRATIONS =
125+
embeddedRunState.activeRunRegistrations ??
126+
(embeddedRunState.activeRunRegistrations = new WeakMap<
127+
EmbeddedAgentQueueHandle,
128+
EmbeddedRunRegistration
129+
>());
127130
const ACTIVE_EMBEDDED_RUN_LIFECYCLE_GENERATIONS =
128131
embeddedRunState.activeRunLifecycleGenerations ??
129132
(embeddedRunState.activeRunLifecycleGenerations = new WeakMap<
@@ -136,9 +139,6 @@ export const RETAINED_EMBEDDED_RUN_ABORTABILITY_RUN_IDS =
136139
export const ACTIVE_EMBEDDED_RUN_SNAPSHOTS =
137140
embeddedRunState.snapshots ??
138141
(embeddedRunState.snapshots = new Map<string, ActiveEmbeddedRunSnapshot>());
139-
export const EMBEDDED_RUN_EVENT_SUBSCRIPTIONS_BY_RUN_ID =
140-
embeddedRunState.eventSubscriptionsByRunId ??
141-
(embeddedRunState.eventSubscriptionsByRunId = new Map<string, () => void>());
142142
export const ACTIVE_EMBEDDED_RUN_SESSION_IDS_BY_KEY =
143143
embeddedRunState.sessionIdsByKey ??
144144
(embeddedRunState.sessionIdsByKey = new Map<string, string>());
@@ -190,10 +190,6 @@ function evictPriorLifecycleEmbeddedRuns(): void {
190190
if (ACTIVE_EMBEDDED_RUNS_BY_RUN_ID.get(runId) === handle) {
191191
ACTIVE_EMBEDDED_RUNS_BY_RUN_ID.delete(runId);
192192
RETAINED_EMBEDDED_RUN_ABORTABILITY_RUN_IDS.delete(runId);
193-
// Release the stale run's event subscription so its listener does not
194-
// survive lifecycle rotation for the process lifetime.
195-
EMBEDDED_RUN_EVENT_SUBSCRIPTIONS_BY_RUN_ID.get(runId)?.();
196-
EMBEDDED_RUN_EVENT_SUBSCRIPTIONS_BY_RUN_ID.delete(runId);
197193
}
198194
}
199195
for (const [sessionKey, sessionId] of ACTIVE_EMBEDDED_RUN_SESSION_IDS_BY_KEY) {

0 commit comments

Comments
 (0)