Skip to content

Commit bee48f7

Browse files
authored
fix: resume sessions with trusted runtime plugins absent at startup (#132804)
* fix(agents): prepare selected runtime generations before admission Carry the lease-selected immutable generation through Gateway, channel, embedded, and cron execution. Reuse only matching imported owners, preserve published metadata and inbound registries, and keep nested authority tied to the exact open parent lease. Consolidate cron preparation and execution on one selected lease using the same per-agent configuration projection, and remove the duplicate late acquisition and redundant scope wrapper. * fix(agents): prepare configured subagent fallback owners * fix(gateway): dispatch cancellation through its lazy owner * test: repair runtime owner integration fixtures * test(qa): assert Matrix proxy cleanup by owner
1 parent 9597c37 commit bee48f7

48 files changed

Lines changed: 1533 additions & 556 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,9 @@ Docs: https://docs.openclaw.ai
7272

7373
- **Browser extension relay:** route Runtime binding callbacks only to registered clients and preserve shared bindings during client cleanup, preventing raw callback payloads from reaching unrelated Playwright sessions.
7474
- **Control UI media playback:** restore inline audio and video rendition loading so readiness checks reach the Gateway instead of silently falling back to download cards. (#132832)
75+
- **Gateway cancellation:** route the first `chat.abort` directly to its cancellation handler without loading unrelated chat history and send workflows.
76+
- **Persisted agent runtimes:** prepare the trusted harness and provider selected by an existing session before Gateway, channel, and cron execution, while keeping plugin generations isolated and closed leases unusable.
77+
7578
- **Grok web search startup:** avoid loading the full agent runtime before the first search, while preserving agent-scoped credentials and OAuth fallback behavior.
7679
- Gateway/subagents: keep plugin completion turns bound to the owning Gateway runtime so successful native subagents can finish delivery without losing the published reply runtime.
7780
- **Upgrade config repair:** retain plugin-owned channel configuration migrations alongside core schemas so `doctor --fix` can repair older settings before an external plugin is installed or granted capabilities, while preserving installed-plugin ownership and state-migration boundaries.

‎extensions/qa-lab/src/live-transports/matrix/scenarios/scenario-runtime-e2ee-cli-account.test.ts‎

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,7 @@ import { startMatrixQaFaultProxy } from "../substrate/fault-proxy.js";
88
import type { MatrixQaCliSession } from "./scenario-runtime-cli.js";
99
import { runMatrixQaE2eeCliEncryptionSetupBootstrapFailureScenario } from "./scenario-runtime-e2ee-cli-account.js";
1010
import { MATRIX_QA_ROOM_KEY_BACKUP_VERSION_ENDPOINT } from "./scenario-runtime-e2ee-shared.js";
11-
import {
12-
assertMatrixQaTestPortClosed,
13-
createMatrixQaE2eeTestContext,
14-
} from "./scenario-runtime-e2ee.test-helpers.js";
11+
import { createMatrixQaE2eeTestContext } from "./scenario-runtime-e2ee.test-helpers.js";
1512

1613
const mocks = vi.hoisted(() => ({ createRuntime: vi.fn() }));
1714
vi.mock("./scenario-runtime-e2ee-cli-runtime.js", () => ({
@@ -65,6 +62,8 @@ describe("Matrix CLI bootstrap failure evidence and ownership", () => {
6562
stop: async () => {
6663
await beforeProxyStop?.();
6764
stopping = proxy.stop().then(() => {
65+
// The real stop joins this server's close event. Its released port may
66+
// already belong to another worker when the scenario settles.
6867
closed = true;
6968
});
7069
await stopping;
@@ -128,7 +127,7 @@ describe("Matrix CLI bootstrap failure evidence and ownership", () => {
128127
async ({ methods }) => {
129128
configureCli(methods);
130129
await expect(run()).rejects.toThrow("did not attempt faulted room-key backup creation");
131-
await assertMatrixQaTestPortClosed(proxy.baseUrl);
130+
expect(closed).toBe(true);
132131
expect(dispose).toHaveBeenCalledOnce();
133132
},
134133
);
@@ -138,19 +137,19 @@ describe("Matrix CLI bootstrap failure evidence and ownership", () => {
138137
await expect(run()).resolves.toMatchObject({
139138
artifacts: { bootstrapSuccess: false, faultHitCount: 2 },
140139
});
141-
await assertMatrixQaTestPortClosed(proxy.baseUrl);
140+
expect(closed).toBe(true);
142141
closed = false;
143142
configureCli(["POST"], "unrelated failure");
144143
await expect(run()).rejects.toThrow("unexpected reason");
145-
await assertMatrixQaTestPortClosed(proxy.baseUrl);
144+
expect(closed).toBe(true);
146145
});
147146

148147
it.each([new Error("runtime construction failed"), undefined, "construction rejected"])(
149148
"closes the already-acquired proxy and preserves construction rejection %s",
150149
async (failure) => {
151150
mocks.createRuntime.mockRejectedValueOnce(failure);
152151
await expect(run()).rejects.toBe(failure);
153-
await assertMatrixQaTestPortClosed(proxy.baseUrl);
152+
expect(closed).toBe(true);
154153
},
155154
);
156155

@@ -163,7 +162,7 @@ describe("Matrix CLI bootstrap failure evidence and ownership", () => {
163162
cause: failure,
164163
errors: [failure, proxyCleanupFailure],
165164
});
166-
await assertMatrixQaTestPortClosed(proxy.baseUrl);
165+
expect(closed).toBe(true);
167166
},
168167
);
169168

@@ -173,7 +172,7 @@ describe("Matrix CLI bootstrap failure evidence and ownership", () => {
173172
configureCli(["POST"]);
174173
dispose.mockRejectedValueOnce(failure);
175174
await expect(run()).rejects.toBe(failure);
176-
await assertMatrixQaTestPortClosed(proxy.baseUrl);
175+
expect(closed).toBe(true);
177176
},
178177
);
179178

@@ -186,7 +185,7 @@ describe("Matrix CLI bootstrap failure evidence and ownership", () => {
186185
cause: disposalFailure,
187186
errors: [disposalFailure, proxyCleanupFailure],
188187
});
189-
await assertMatrixQaTestPortClosed(proxy.baseUrl);
188+
expect(closed).toBe(true);
190189
});
191190

192191
it("joins proxy cleanup before returning a CLI disposal failure", async () => {
@@ -212,6 +211,6 @@ describe("Matrix CLI bootstrap failure evidence and ownership", () => {
212211
release.resolve();
213212
expect(await operation).toBe(disposalFailure);
214213
}
215-
await assertMatrixQaTestPortClosed(proxy.baseUrl);
214+
expect(closed).toBe(true);
216215
});
217216
});

‎extensions/qa-lab/src/live-transports/matrix/scenarios/scenario-runtime-e2ee.test-helpers.ts‎

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import { createServer } from "node:net";
21
import type { MatrixVerificationBootstrapResult } from "@openclaw/matrix/test-api.js";
32
import type { MatrixQaScenarioContext } from "./scenario-runtime-shared.js";
43

@@ -24,16 +23,6 @@ export function createMatrixQaE2eeTestContext(
2423
};
2524
}
2625

27-
export async function assertMatrixQaTestPortClosed(baseUrl: string) {
28-
const probe = createServer();
29-
await new Promise<void>((resolve, reject) => {
30-
probe.once("error", reject);
31-
probe.listen(Number(new URL(baseUrl).port), "127.0.0.1", () => {
32-
probe.close((error) => (error ? reject(error) : resolve()));
33-
});
34-
});
35-
}
36-
3726
export function createMatrixQaBootstrapFailure(): MatrixVerificationBootstrapResult {
3827
return {
3928
success: false,

‎src/agents/agent-scope.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,6 @@ export {
5555
tryResolveSoleAgentId,
5656
tryResolveDefaultAgentId,
5757
AgentSelectionRequiredError,
58-
type AgentSelectionContext,
59-
type AgentWorkspaceProvisioning,
60-
type ResolvedAgentConfig,
6158
} from "./agent-scope-config.js";
6259

6360
const AUTO_FALLBACK_PRIMARY_PROBE_INTERVAL_MS = 5 * 60 * 1000;
@@ -489,7 +486,7 @@ function resolveFirstModelFallbacksOverride(
489486
return undefined;
490487
}
491488

492-
export type SubagentModelConfigSelectionSource = "subagent" | "agent" | "default-subagent";
489+
type SubagentModelConfigSelectionSource = "subagent" | "agent" | "default-subagent";
493490

494491
export type SubagentModelConfigSelectionResult = {
495492
raw: AgentModelConfig;
@@ -542,7 +539,7 @@ export function resolveSubagentModelFallbacksOverride(
542539
return undefined;
543540
}
544541

545-
function resolveSubagentSpawnModelFallbacksOverride(
542+
export function resolveSubagentSpawnModelFallbacksOverride(
546543
cfg: OpenClawConfig,
547544
agentId: string,
548545
): string[] | undefined {

‎src/agents/command/cli-compaction.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,12 @@ function createPreparedRuntimeLease(input: {
127127
agentDir: input.agentDir,
128128
...(input.workspaceDir ? { workspaceDir: input.workspaceDir } : {}),
129129
},
130+
pluginGeneration: {
131+
configuredCatalogEntries: [],
132+
inlineProviderModels: [],
133+
pluginMetadataSnapshot: prepared.metadataSnapshot,
134+
pluginRegistry: prepared.pluginRegistry,
135+
},
130136
release: vi.fn(),
131137
};
132138
}

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,7 @@ async function runEmbeddedAgentInternal(
315315
);
316316
startupStages.mark("prepared-runtime");
317317
const preparedModelRuntimeOwnerSnapshot = preparedModelRuntimeLease.snapshot;
318+
let preparedLeaseActive = true;
318319
try {
319320
if (
320321
params.pluginGeneration &&
@@ -475,11 +476,13 @@ async function runEmbeddedAgentInternal(
475476
withPluginRuntimeGenerationScope(preparedModelRuntime, runPrepared);
476477
return params.pluginGeneration
477478
? await withPreparedModelRuntimePluginGenerationScope(
478-
params.pluginGeneration,
479+
preparedModelRuntimeLease.pluginGeneration,
479480
runWithPreparedRuntime,
481+
() => (preparedLeaseActive ? preparedModelRuntimeOwnerSnapshot : undefined),
480482
)
481483
: await runWithPreparedRuntime();
482484
} finally {
485+
preparedLeaseActive = false;
483486
preparedModelRuntimeLease.release();
484487
}
485488
});

‎src/agents/prepared-model-registry.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ function registryOwnerCandidates(
101101
async function loadReadSnapshot(
102102
input: PreparedModelRuntimeInput,
103103
allowConfiguredWorkspaceFallback: boolean,
104-
): Promise<PreparedModelRuntimeLease> {
104+
): Promise<Pick<PreparedModelRuntimeLease, "snapshot" | "release">> {
105105
for (const candidate of registryOwnerCandidates(input, allowConfiguredWorkspaceFallback)) {
106106
try {
107107
const prepared = await prepareModelRuntimeSnapshot(candidate);

‎src/agents/prepared-model-runtime-lease.ts‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ import {
2020
type PreparedModelRuntimeReplacement,
2121
type PreparedModelRuntimeSnapshot,
2222
} from "./prepared-model-runtime.owner.js";
23+
import {
24+
preparedPluginGenerationReusesBase,
25+
preparedPluginGenerationSupportsSelections,
26+
} from "./prepared-model-runtime.plugin-generation.js";
2327
import type { PreparedModelRuntimeCatalogMode } from "./prepared-model-runtime.types.js";
2428

2529
type PreparedModelRuntimeLeaseContext = {
@@ -120,12 +124,17 @@ export async function acquirePreparedModelRuntimeLeaseFromOwners(
120124
!input.readOnly &&
121125
!input.loadRuntimePlugins &&
122126
!input.skipCredentials &&
123-
!input.env
127+
!input.env &&
128+
preparedPluginGenerationSupportsSelections(options.pluginGeneration, input)
124129
) {
125130
// A turn may finish under its still-open parent lease after reload. Its historic
126131
// generation must never publish over the configured owner for newly admitted work.
127132
throwIfLeaseAdmissionAborted(options.abortSignal);
128-
return { snapshot: borrowed, release: () => {} };
133+
return {
134+
snapshot: borrowed,
135+
pluginGeneration: options.pluginGeneration,
136+
release: () => {},
137+
};
129138
}
130139
throw new PreparedModelRuntimeOwnerNotPublishedError(
131140
`prepared model runtime plugin generation was superseded for ${input.agentDir}`,
@@ -139,8 +148,10 @@ export async function acquirePreparedModelRuntimeLeaseFromOwners(
139148
(existing.provenance === "run" || existing.provenance === "ephemeral");
140149
const pluginGenerationChanged =
141150
options.pluginGeneration !== undefined &&
142-
(existing?.pending ? existing.pendingPluginGeneration : existing?.pluginGeneration) !==
143-
options.pluginGeneration;
151+
!preparedPluginGenerationReusesBase(
152+
existing?.pending ? existing.pendingPluginGeneration : existing?.pluginGeneration,
153+
options.pluginGeneration,
154+
);
144155
if (existing?.pending && pluginGenerationChanged) {
145156
// Do not supersede active discovery. Wait for its owner to settle, then retry against
146157
// the published identity so same-generation callers still coalesce.
@@ -241,8 +252,9 @@ export async function acquirePreparedModelRuntimeLeaseFromOwners(
241252
break;
242253
}
243254
throwIfLeaseAdmissionAborted(options.abortSignal);
255+
const pluginGeneration = owner.pluginGeneration!;
244256
if (owner.provenance !== provenance) {
245-
return { snapshot, release: () => {} };
257+
return { snapshot, pluginGeneration, release: () => {} };
246258
}
247259
throwIfLeaseAdmissionAborted(options.abortSignal);
248260
if (provenance === "run" && options.retainIdleRunOwner) {
@@ -254,6 +266,7 @@ export async function acquirePreparedModelRuntimeLeaseFromOwners(
254266
let released = false;
255267
return {
256268
snapshot,
269+
pluginGeneration,
257270
release: () => {
258271
if (released) {
259272
return;

‎src/agents/prepared-model-runtime.build.ts‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -301,17 +301,20 @@ async function buildSnapshotBatch(
301301
const freshGroups = new Map<string, PreparedModelRuntimeBuildCandidate[]>();
302302
const reusableGroups = new Map<
303303
PreparedModelRuntimePluginGeneration,
304-
PreparedModelRuntimeBuildCandidate[]
304+
Map<string, PreparedModelRuntimeBuildCandidate[]>
305305
>();
306306
for (const candidate of candidates) {
307307
const { input, pluginGeneration: reusablePluginGeneration } = candidate;
308308
if (reusablePluginGeneration) {
309-
const group = reusableGroups.get(reusablePluginGeneration);
309+
const workspaceGroups = reusableGroups.get(reusablePluginGeneration) ?? new Map();
310+
const key = preparedModelRuntimeWorkspaceFactsKey(input);
311+
const group = workspaceGroups.get(key);
310312
if (group) {
311313
group.push(candidate);
312314
} else {
313-
reusableGroups.set(reusablePluginGeneration, [candidate]);
315+
workspaceGroups.set(key, [candidate]);
314316
}
317+
reusableGroups.set(reusablePluginGeneration, workspaceGroups);
315318
continue;
316319
}
317320
const ownerKind = candidate.prepareInboundPluginRegistry ? "configured" : "dynamic";
@@ -327,10 +330,12 @@ async function buildSnapshotBatch(
327330
groupCandidates: PreparedModelRuntimeBuildCandidate[];
328331
pluginGeneration?: PreparedModelRuntimePluginGeneration;
329332
}> = [
330-
...[...reusableGroups].map(([pluginGeneration, groupCandidates]) => ({
331-
groupCandidates,
332-
pluginGeneration,
333-
})),
333+
...[...reusableGroups].flatMap(([pluginGeneration, workspaceGroups]) =>
334+
[...workspaceGroups.values()].map((groupCandidates) => ({
335+
groupCandidates,
336+
pluginGeneration,
337+
})),
338+
),
334339
...[...freshGroups.values()].map((groupCandidates) => ({ groupCandidates })),
335340
];
336341
const preparedInputs = new Map<PreparedModelRuntimeInput, PreparedModelRuntimeAgentFacts>();

0 commit comments

Comments
 (0)