File size: 12,965 Bytes
3144483 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 | import { createServer, type Server, type AddressInfo } from "node:net";
import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
import { FailoverError } from "../agents/failover-error.js";
import {
createAgentRunDirectAbortError,
createAgentRunRestartAbortError,
createAgentRunSupersededAbortError,
} from "../agents/run-termination.js";
import type { OpenClawConfig } from "../config/config.js";
import { createAgentRunStaleLifecycleError } from "../infra/agent-lifecycle-error.js";
import { resetTaskRegistryForTests } from "../tasks/task-runtime.test-helpers.js";
import { withOpenClawTestState } from "../test-utils/openclaw-test-state.js";
import {
loadRunCronIsolatedAgentTurn,
dispatchCronDeliveryMock,
mockRunCronFallbackPassthrough,
resetRunCronIsolatedAgentTurnHarness,
resolveAllowedModelRefMock,
resolveConfiguredModelRefMock,
runEmbeddedAgentMock,
runWithModelFallbackMock,
} from "./isolated-agent/run.test-harness.js";
import { CronService, type CronEvent } from "./service.js";
import { createNoopLogger } from "./service.test-harness.js";
import { cronStoreKey } from "./store/key.js";
import { readCronTaskRunHistoryPage } from "./task-run-history.js";
vi.doUnmock("./isolated-agent/model-preflight.runtime.js");
const runCronIsolatedAgentTurn = await loadRunCronIsolatedAgentTurn();
const { resetCronModelProviderPreflightCacheForTest } =
await import("./isolated-agent/model-preflight.runtime.js");
type ModelRef = { provider: string; model: string };
function makeCommandLaneTaskTimeoutError(lane: string, timeoutMs: number): Error {
const error = new Error(`Command lane "${lane}" task timed out after ${timeoutMs}ms`);
error.name = "CommandLaneTaskTimeoutError";
return error;
}
async function listenForBrokenHttpConnections(): Promise<{
baseUrl: string;
server: Server;
}> {
const server = createServer((socket) => socket.destroy());
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", resolve);
});
const address = server.address() as AddressInfo;
return { baseUrl: `http://127.0.0.1:${address.port}`, server };
}
async function closeServer(server: Server): Promise<void> {
await new Promise<void>((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
});
}
function configFor(modelRef: ModelRef, localBaseUrl?: string): OpenClawConfig {
return {
agents: {
defaults: {
model: `${modelRef.provider}/${modelRef.model}`,
},
},
...(localBaseUrl
? {
models: {
providers: {
[modelRef.provider]: {
api: "ollama",
baseUrl: localBaseUrl,
models: [],
},
},
},
}
: {}),
};
}
async function runPersistedDiagnosticCase(params: {
cfg: OpenClawConfig;
modelRef: ModelRef;
name: string;
}) {
return await withOpenClawTestState(
{ layout: "state-only", prefix: "openclaw-cron-execution-diagnostics-" },
async (state) => {
resetTaskRegistryForTests();
const events: CronEvent[] = [];
const storePath = state.path("cron", "jobs.json");
const cron = new CronService({
storePath,
cronEnabled: true,
cronConfig: { triggers: { enabled: true } },
log: createNoopLogger(),
enqueueSystemEvent: vi.fn(),
requestHeartbeat: vi.fn(),
onEvent: (event) => events.push(structuredClone(event)),
runIsolatedAgentJob: async (runParams) =>
await runCronIsolatedAgentTurn({
...runParams,
cfg: params.cfg,
deps: {},
sessionKey: `cron:${runParams.job.id}`,
}),
});
try {
await cron.start();
const job = await cron.add({
name: params.name,
enabled: true,
schedule: { kind: "every", everyMs: 60_000 },
sessionTarget: "isolated",
wakeMode: "next-heartbeat",
payload: {
kind: "agentTurn",
message: `run ${params.name}`,
model: `${params.modelRef.provider}/${params.modelRef.model}`,
},
delivery: { mode: "none" },
});
await expect(cron.run(job.id, "force")).resolves.toEqual({ ok: true, ran: true });
const finished = events.find(
(event) => event.action === "finished" && event.jobId === job.id,
);
const history = readCronTaskRunHistoryPage({
storeKey: cronStoreKey(storePath),
jobId: job.id,
limit: 1,
}).entries[0];
expect(finished).toBeDefined();
expect(history).toBeDefined();
return {
finished: finished!,
history: history!,
lastError: cron.getJob(job.id)?.state.lastError,
lastErrorReason: cron.getJob(job.id)?.state.lastErrorReason,
};
} finally {
cron.stop();
resetTaskRegistryForTests({ persist: false });
}
},
);
}
describe("cron execution diagnostics", { concurrent: false }, () => {
const servers: Server[] = [];
beforeEach(() => {
resetRunCronIsolatedAgentTurnHarness();
resetCronModelProviderPreflightCacheForTest();
});
afterAll(async () => {
await Promise.all(servers.map(closeServer));
});
it("persists and emits a real isolated-run local-provider preflight failure", async () => {
const endpoint = await listenForBrokenHttpConnections();
servers.push(endpoint.server);
const modelRef = { provider: "ollama", model: "diagnostic-model" };
resolveConfiguredModelRefMock.mockReturnValue(modelRef);
resolveAllowedModelRefMock.mockReturnValue({ ref: modelRef });
const { finished, history } = await runPersistedDiagnosticCase({
cfg: configFor(modelRef, endpoint.baseUrl),
modelRef,
name: "unreachable provider",
});
expect(runWithModelFallbackMock).not.toHaveBeenCalled();
expect(runEmbeddedAgentMock).not.toHaveBeenCalled();
for (const outcome of [finished, history]) {
expect(outcome).toMatchObject({
status: "skipped",
provider: "ollama",
model: "diagnostic-model",
error: expect.stringContaining("unavailable"),
diagnostics: {
entries: expect.arrayContaining([
expect.objectContaining({
source: "model-preflight",
severity: "warn",
message: expect.stringContaining("unavailable"),
}),
]),
},
});
}
});
it("persists and emits the canonical terminal timeout diagnostic", async () => {
const modelRef = { provider: "openai", model: "gpt-5.4" };
resolveConfiguredModelRefMock.mockReturnValue(modelRef);
runWithModelFallbackMock.mockRejectedValueOnce(
makeCommandLaneTaskTimeoutError("cron-nested", 330_000),
);
const { finished, history } = await runPersistedDiagnosticCase({
cfg: configFor(modelRef),
modelRef,
name: "nested lane timeout",
});
for (const outcome of [finished, history]) {
expect(outcome).toMatchObject({
status: "error",
provider: "openai",
model: "gpt-5.4",
error: "cron: job execution timed out",
diagnostics: {
entries: expect.arrayContaining([
expect.objectContaining({
source: "cron-setup",
severity: "error",
message: "cron: job execution timed out",
}),
]),
},
});
}
});
it("persists provider failures without internal class names", async () => {
const message = "Saved selection requires an update.";
const modelRef = { provider: "openai", model: "not-a-real-model" };
resolveConfiguredModelRefMock.mockReturnValue(modelRef);
resolveAllowedModelRefMock.mockReturnValue({ ref: modelRef });
runWithModelFallbackMock.mockRejectedValueOnce(
new FailoverError(message, {
reason: "model_not_found",
provider: modelRef.provider,
model: modelRef.model,
}),
);
const { finished, history, lastError, lastErrorReason } = await runPersistedDiagnosticCase({
cfg: configFor(modelRef),
modelRef,
name: "missing provider model",
});
for (const outcome of [finished, history]) {
expect(outcome).toMatchObject({
status: "error",
provider: modelRef.provider,
model: modelRef.model,
error: message,
diagnostics: { summary: message },
});
expect(outcome.error).not.toContain("FailoverError");
}
expect(lastError).toBe(message);
expect(lastErrorReason).toBe("model_not_found");
expect(history.errorReason).toBe("model_not_found");
});
it.each([
["direct abort", createAgentRunDirectAbortError],
["gateway restart", createAgentRunRestartAbortError],
["superseded run", createAgentRunSupersededAbortError],
["stale gateway lifecycle", createAgentRunStaleLifecycleError],
])("persists the coded %s reason instead of reporting a timeout", async (name, createError) => {
const modelRef = { provider: "openai", model: "gpt-5.4" };
resolveConfiguredModelRefMock.mockReturnValue(modelRef);
const rejection = createError() as Error & { code: string };
runWithModelFallbackMock.mockRejectedValueOnce(rejection);
const { finished, history, lastError } = await runPersistedDiagnosticCase({
cfg: configFor(modelRef),
modelRef,
name,
});
const expected = `${rejection.message} | ${rejection.code}`;
for (const outcome of [finished, history]) {
expect(outcome).toMatchObject({
status: "error",
error: expected,
});
expect(outcome.error).not.toContain("timed out");
}
expect(lastError).toBe(expected);
});
it("persists and emits a fatal execution-denial diagnostic", async () => {
const modelRef = { provider: "openai", model: "gpt-5.4" };
resolveConfiguredModelRefMock.mockReturnValue(modelRef);
mockRunCronFallbackPassthrough();
runEmbeddedAgentMock.mockResolvedValueOnce({
payloads: [],
meta: {
agentMeta: {},
failureSignal: {
kind: "execution_denied",
source: "tool",
toolName: "exec",
code: "SYSTEM_RUN_DENIED",
message: "SYSTEM_RUN_DENIED: approval required",
fatalForCron: true,
},
},
});
const { finished, history } = await runPersistedDiagnosticCase({
cfg: configFor(modelRef),
modelRef,
name: "execution denied",
});
for (const outcome of [finished, history]) {
expect(outcome).toMatchObject({
status: "error",
provider: "openai",
model: "gpt-5.4",
error: "SYSTEM_RUN_DENIED: approval required",
summary: "SYSTEM_RUN_DENIED: approval required",
diagnostics: {
entries: expect.arrayContaining([
expect.objectContaining({
source: "tool",
severity: "error",
message: "SYSTEM_RUN_DENIED: approval required",
}),
]),
},
});
}
});
it("persists and emits terminal tool detail while keeping the payload generic", async () => {
const modelRef = { provider: "openai", model: "gpt-5.4" };
resolveConfiguredModelRefMock.mockReturnValue(modelRef);
mockRunCronFallbackPassthrough();
runEmbeddedAgentMock.mockResolvedValueOnce({
payloads: [{ text: "⚠️ Exec failed", isError: true, toolName: "exec" }],
meta: {
agentMeta: {},
terminalToolFailure: {
source: "tool",
toolName: "exec",
code: "UNKNOWN_TOOL_ID",
},
},
});
const { finished, history } = await runPersistedDiagnosticCase({
cfg: configFor(modelRef),
modelRef,
name: "unknown tool id",
});
expect(dispatchCronDeliveryMock).toHaveBeenCalledWith(
expect.objectContaining({
deliveryPayloads: [{ text: "cron isolated run returned an error payload", isError: true }],
outputText: "cron isolated run returned an error payload",
summary: "Code Mode could not resolve a configured MCP tool.",
}),
);
for (const outcome of [finished, history]) {
expect(outcome).toMatchObject({
status: "error",
provider: "openai",
model: "gpt-5.4",
summary: "Code Mode could not resolve a configured MCP tool.",
diagnostics: {
summary: "Code Mode could not resolve a configured MCP tool.",
entries: expect.arrayContaining([
expect.objectContaining({
source: "tool",
severity: "error",
message: "Code Mode could not resolve a configured MCP tool.",
toolName: "exec",
}),
]),
},
});
}
});
});
|