Skip to content

Commit 77902b1

Browse files
authored
fix(tasks): validate filter flags before querying (#124520)
1 parent 46f5951 commit 77902b1

24 files changed

Lines changed: 549 additions & 181 deletions
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Browser tests cover Playwright observation filtering behavior.
2+
import { describe, expect, it } from "vitest";
3+
import {
4+
getPwToolsCoreSessionMocks,
5+
installPwToolsCoreTestHooks,
6+
setPwToolsCoreCurrentPage,
7+
} from "./pw-tools-core.test-harness.js";
8+
9+
installPwToolsCoreTestHooks();
10+
const { getConsoleMessagesViaPlaywright } = await import("./pw-tools-core.activity.js");
11+
12+
describe("getConsoleMessagesViaPlaywright", () => {
13+
it("treats the documented warn filter as warning priority", async () => {
14+
setPwToolsCoreCurrentPage({});
15+
getPwToolsCoreSessionMocks().ensurePageState.mockReturnValueOnce({
16+
console: [
17+
{ type: "error", text: "error", timestamp: "1" },
18+
{ type: "warning", text: "warning", timestamp: "2" },
19+
{ type: "info", text: "info", timestamp: "3" },
20+
],
21+
armIdUpload: 0,
22+
armIdDownload: 0,
23+
downloadWaiterDepth: 0,
24+
});
25+
26+
const messages = await getConsoleMessagesViaPlaywright({
27+
cdpUrl: "http://127.0.0.1:18792",
28+
targetId: "T1",
29+
level: "warn",
30+
});
31+
32+
expect(messages.map((message) => message.type)).toEqual(["error", "warning"]);
33+
});
34+
});

‎extensions/browser/src/browser/pw-tools-core.activity.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ function consolePriority(level: string) {
4747
switch (level) {
4848
case "error":
4949
return 3;
50+
case "warn":
5051
case "warning":
5152
return 2;
5253
case "info":

‎extensions/browser/src/cli/browser-cli-actions-observe.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,15 @@ describe("browser action observe commands", () => {
5858
expect(mocks.callBrowserRequest).not.toHaveBeenCalled();
5959
});
6060

61+
it("rejects unknown console levels before dispatch", async () => {
62+
const program = createActionObserveProgram();
63+
64+
await expect(
65+
program.parseAsync(["browser", "console", "--level", "bogus"], { from: "user" }),
66+
).rejects.toThrow(/error.*warn.*info/u);
67+
expect(mocks.callBrowserRequest).not.toHaveBeenCalled();
68+
});
69+
6170
it("passes responsebody limits through to the request and outer timeout", async () => {
6271
const program = createActionObserveProgram();
6372

‎extensions/browser/src/cli/browser-cli-actions-observe.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,18 @@ import {
1313
} from "./browser-cli-shared.js";
1414
import { defaultRuntime, shortenHomePath } from "./core-api.js";
1515

16+
const BROWSER_CONSOLE_LEVELS = ["error", "warn", "info"] as const;
17+
18+
function parseBrowserConsoleLevel(value: string): (typeof BROWSER_CONSOLE_LEVELS)[number] {
19+
const level = BROWSER_CONSOLE_LEVELS.find((candidate) => candidate === value);
20+
if (!level) {
21+
throw new Error(
22+
`--level must be ${BROWSER_CONSOLE_LEVELS.slice(0, -1).join(", ")}, or ${BROWSER_CONSOLE_LEVELS.at(-1)}.`,
23+
);
24+
}
25+
return level;
26+
}
27+
1628
/** Registers Browser commands that observe current page state without direct input. */
1729
export function registerBrowserActionObserveCommands(
1830
browser: Command,
@@ -21,7 +33,11 @@ export function registerBrowserActionObserveCommands(
2133
browser
2234
.command("console")
2335
.description("Get recent console messages")
24-
.option("--level <level>", "Filter by level (error, warn, info)")
36+
.option(
37+
"--level <level>",
38+
`Filter by level (${BROWSER_CONSOLE_LEVELS.join(", ")})`,
39+
parseBrowserConsoleLevel,
40+
)
2541
.option("--target-id <id>", BROWSER_TAB_REFERENCE_HELP)
2642
.action(async (opts, cmd) => {
2743
const parent = parentOpts(cmd);

‎src/cli/enum-filter.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
2+
import { formatHumanList } from "../shared/human-list.js";
3+
4+
/** Parses an optional exact-match CLI enum before command-owned work begins. */
5+
export function parseCliEnumFilter<T extends string>(
6+
raw: string | undefined,
7+
flag: string,
8+
values: readonly T[],
9+
): T | undefined {
10+
const normalized = normalizeOptionalString(raw);
11+
if (normalized === undefined) {
12+
return undefined;
13+
}
14+
const match = values.find((value) => value === normalized);
15+
if (!match) {
16+
throw new Error(`${flag} must be ${formatHumanList(values)}.`);
17+
}
18+
return match;
19+
}

‎src/cli/program/register.status-health-sessions.ts‎

Lines changed: 17 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,14 @@ import { formatDocsLink } from "../../../packages/terminal-core/src/links.js";
55
import { theme } from "../../../packages/terminal-core/src/theme.js";
66
import { setVerbose } from "../../globals.js";
77
import { defaultRuntime } from "../../runtime.js";
8+
import { TASK_FLOW_STATUSES } from "../../tasks/task-flow-registry.types.js";
9+
import { TASK_RUNTIMES, TASK_STATUSES } from "../../tasks/task-registry.types.js";
10+
import {
11+
TASK_SYSTEM_AUDIT_CODES,
12+
TASK_SYSTEM_AUDIT_SEVERITIES,
13+
type TaskSystemAuditCode,
14+
type TaskSystemAuditSeverity,
15+
} from "../../tasks/task-system-audit.types.js";
816
import { runCommandWithRuntime } from "../cli-utils.js";
917
import { formatHelpExamples } from "../help-format.js";
1018

@@ -591,11 +599,8 @@ export function registerStatusHealthSessionsCommands(program: Command) {
591599
.command("tasks")
592600
.description("Inspect durable background tasks and TaskFlow state")
593601
.option("--json", "Output as JSON", false)
594-
.option("--runtime <name>", "Filter by kind (subagent, acp, cron, cli)")
595-
.option(
596-
"--status <name>",
597-
"Filter by status (queued, running, succeeded, failed, timed_out, cancelled, lost)",
598-
)
602+
.option("--runtime <name>", `Filter by kind (${TASK_RUNTIMES.join(", ")})`)
603+
.option("--status <name>", `Filter by status (${TASK_STATUSES.join(", ")})`)
599604
.action(async (opts) => {
600605
await runCommandWithRuntime(defaultRuntime, async () => {
601606
const { tasksListCommand } = await loadTasksCommands();
@@ -615,11 +620,8 @@ export function registerStatusHealthSessionsCommands(program: Command) {
615620
.command("list")
616621
.description("List tracked background tasks")
617622
.option("--json", "Output as JSON", false)
618-
.option("--runtime <name>", "Filter by kind (subagent, acp, cron, cli)")
619-
.option(
620-
"--status <name>",
621-
"Filter by status (queued, running, succeeded, failed, timed_out, cancelled, lost)",
622-
)
623+
.option("--runtime <name>", `Filter by kind (${TASK_RUNTIMES.join(", ")})`)
624+
.option("--status <name>", `Filter by status (${TASK_STATUSES.join(", ")})`)
623625
.action(async (opts, command) => {
624626
const parentOpts = command.parent?.opts() as
625627
| {
@@ -645,11 +647,8 @@ export function registerStatusHealthSessionsCommands(program: Command) {
645647
.command("audit")
646648
.description("Show stale or broken background tasks and TaskFlows")
647649
.option("--json", "Output as JSON", false)
648-
.option("--severity <level>", "Filter by severity (warn, error)")
649-
.option(
650-
"--code <name>",
651-
"Filter by finding code (stale_queued, stale_running, lost, delivery_failed, missing_cleanup, inconsistent_timestamps, restore_failed, stale_waiting, stale_blocked, cancel_stuck, missing_linked_tasks, blocked_task_missing)",
652-
)
650+
.option("--severity <level>", `Filter by severity (${TASK_SYSTEM_AUDIT_SEVERITIES.join(", ")})`)
651+
.option("--code <name>", `Filter by finding code (${TASK_SYSTEM_AUDIT_CODES.join(", ")})`)
653652
.option("--limit <n>", "Limit displayed findings")
654653
.action(async (opts, command) => {
655654
const parentOpts = command.parent?.opts() as { json?: boolean } | undefined;
@@ -662,21 +661,8 @@ export function registerStatusHealthSessionsCommands(program: Command) {
662661
await tasksAuditCommand(
663662
{
664663
json: Boolean(opts.json || parentOpts?.json),
665-
severity: opts.severity as "warn" | "error" | undefined,
666-
code: opts.code as
667-
| "stale_queued"
668-
| "stale_running"
669-
| "lost"
670-
| "delivery_failed"
671-
| "missing_cleanup"
672-
| "inconsistent_timestamps"
673-
| "restore_failed"
674-
| "stale_waiting"
675-
| "stale_blocked"
676-
| "cancel_stuck"
677-
| "missing_linked_tasks"
678-
| "blocked_task_missing"
679-
| undefined,
664+
severity: opts.severity as TaskSystemAuditSeverity | undefined,
665+
code: opts.code as TaskSystemAuditCode | undefined,
680666
limit,
681667
},
682668
defaultRuntime,
@@ -784,10 +770,7 @@ export function registerStatusHealthSessionsCommands(program: Command) {
784770
.command("list")
785771
.description("List tracked TaskFlows")
786772
.option("--json", "Output as JSON", false)
787-
.option(
788-
"--status <name>",
789-
"Filter by status (queued, running, waiting, blocked, succeeded, failed, cancelled, lost)",
790-
)
773+
.option("--status <name>", `Filter by status (${TASK_FLOW_STATUSES.join(", ")})`)
791774
.action(async (opts) => {
792775
await runCommandWithRuntime(defaultRuntime, async () => {
793776
const { flowsListCommand } = await loadFlowsCommands();

‎src/commands/flows.test.ts‎

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
// Flows command tests cover task creation, task execution, and runtime command output.
22
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
33
import { visibleWidth } from "../../packages/terminal-core/src/ansi.js";
4+
import { runCommandWithRuntime } from "../cli/cli-utils.js";
45
import type { RuntimeEnv } from "../runtime.js";
56
import { createRunningTaskRunCore as createRunningTaskRunOrNull } from "../tasks/task-executor.js";
67
import { createManagedTaskFlow as createManagedTaskFlowOrNull } from "../tasks/task-flow-registry.js";
78
import type { TaskFlowRecord } from "../tasks/task-flow-registry.types.js";
9+
import * as taskFlowRuntime from "../tasks/task-flow-runtime-internal.js";
810
import { markTaskLostById, markTaskTerminalById } from "../tasks/task-registry.js";
911
import type { TaskRecord } from "../tasks/task-registry.types.js";
1012
import {
@@ -159,6 +161,14 @@ describe("flows commands", () => {
159161
},
160162
],
161163
});
164+
165+
const emptyRuntime = createRuntime();
166+
await flowsListCommand({ json: true, status: "waiting" }, emptyRuntime);
167+
expect(jsonRoundTrip(emptyRuntime.writeJson.mock.calls[0]?.[0])).toStrictEqual({
168+
count: 0,
169+
status: "waiting",
170+
flows: [],
171+
});
162172
});
163173
});
164174

@@ -185,6 +195,25 @@ describe("flows commands", () => {
185195
});
186196
});
187197

198+
it("rejects invalid TaskFlow status filters before querying", async () => {
199+
const query = vi.spyOn(taskFlowRuntime, "listTaskFlowRecords").mockImplementation(() => {
200+
throw new Error("TaskFlow query performed");
201+
});
202+
const runtime = createRuntime();
203+
204+
try {
205+
await runCommandWithRuntime(runtime, () => flowsListCommand({ status: "bogus" }, runtime));
206+
207+
expect(runtime.error).toHaveBeenCalledWith(
208+
"--status must be queued, running, waiting, blocked, succeeded, failed, cancelled, or lost.",
209+
);
210+
expect(runtime.exit).toHaveBeenCalledWith(1);
211+
expect(query).not.toHaveBeenCalled();
212+
} finally {
213+
query.mockRestore();
214+
}
215+
});
216+
188217
it("counts pending cancellation intent in TaskFlow pressure", async () => {
189218
await withTaskFlowCommandStateDir(async () => {
190219
createManagedTaskFlow({
@@ -549,16 +578,19 @@ describe("flows commands", () => {
549578
await withTaskFlowCommandStateDir(async () => {
550579
const unsafe = "\u001b]52;c;Zm9yZ2Vk\u0007\nforged: yes";
551580
const filterRuntime = createRuntime();
552-
await flowsListCommand({ status: `running${unsafe}` }, filterRuntime);
581+
await runCommandWithRuntime(filterRuntime, () =>
582+
flowsListCommand({ status: `running${unsafe}` }, filterRuntime),
583+
);
553584

554585
const lookupRuntime = createRuntime();
555586
await flowsShowCommand({ lookup: `missing${unsafe}` }, lookupRuntime);
556587

557588
const lines = [
558589
...vi.mocked(filterRuntime.log).mock.calls.map(([line]) => String(line)),
590+
...vi.mocked(filterRuntime.error).mock.calls.map(([line]) => String(line)),
559591
...vi.mocked(lookupRuntime.error).mock.calls.map(([line]) => String(line)),
560592
];
561-
expect(lines.some((line) => line.includes("Status filter: running"))).toBe(true);
593+
expect(lines.some((line) => line.includes("--status must be queued"))).toBe(true);
562594
expect(lines.some((line) => line.includes("TaskFlow not found: missing"))).toBe(true);
563595
for (const line of lines) {
564596
expect(line).not.toContain("\u001b");

‎src/commands/flows.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,18 @@ import { truncateToVisibleWidth, visibleWidth } from "../../packages/terminal-co
66
import { sanitizeTerminalText } from "../../packages/terminal-core/src/safe-text.js";
77
import { isRich, theme } from "../../packages/terminal-core/src/theme.js";
88
import { formatCliCommand } from "../cli/command-format.js";
9+
import { parseCliEnumFilter } from "../cli/enum-filter.js";
910
import { getRuntimeConfig } from "../config/config.js";
1011
import { info } from "../globals.js";
1112
import type { RuntimeEnv } from "../runtime.js";
1213
import { writeRuntimeJson } from "../runtime.js";
1314
import { listTasksForFlowId } from "../tasks/runtime-internal.js";
1415
import { cancelFlowById, getFlowTaskSummary } from "../tasks/task-executor.js";
15-
import type { TaskFlowRecord, TaskFlowStatus } from "../tasks/task-flow-registry.types.js";
16+
import {
17+
TASK_FLOW_STATUSES,
18+
type TaskFlowRecord,
19+
type TaskFlowStatus,
20+
} from "../tasks/task-flow-registry.types.js";
1621
import {
1722
getTaskFlowById,
1823
listTaskFlowRecords,
@@ -161,7 +166,7 @@ export async function flowsListCommand(
161166
opts: { json?: boolean; status?: string },
162167
runtime: RuntimeEnv,
163168
) {
164-
const statusFilter = normalizeOptionalString(opts.status);
169+
const statusFilter = parseCliEnumFilter(opts.status, "--status", TASK_FLOW_STATUSES);
165170
const flows = listTaskFlowRecords().filter((flow) => {
166171
if (statusFilter && flow.status !== statusFilter) {
167172
return false;

‎src/commands/models/list.list-command.forward-compat.test.ts‎

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,19 @@ const mocks = vi.hoisted(() => {
3232
plugins: [],
3333
diagnostics: [],
3434
};
35+
const knownModelProviderOwners = new Map(
36+
[
37+
"anthropic",
38+
"azure-openai-responses",
39+
"codex",
40+
"google",
41+
"moonshot",
42+
"openai",
43+
"opencode-go",
44+
"xiaomi",
45+
"z.ai",
46+
].map((providerId) => [providerId, ["test-provider-plugin"]]),
47+
);
3548
const emptyPluginMetadataSnapshot = {
3649
policyHash: "models-list-command-forward-compat-test",
3750
configFingerprint: "models-list-command-forward-compat-test",
@@ -45,7 +58,7 @@ const mocks = vi.hoisted(() => {
4558
owners: {
4659
channels: new Map(),
4760
channelConfigs: new Map(),
48-
providers: new Map(),
61+
providers: knownModelProviderOwners,
4962
modelCatalogProviders: new Map(),
5063
cliBackends: new Map(),
5164
setupProviders: new Map(),
@@ -150,7 +163,7 @@ function resetMocks() {
150163
}
151164

152165
function createRuntime() {
153-
return { log: vi.fn(), error: vi.fn() };
166+
return { log: vi.fn(), error: vi.fn(), exit: vi.fn() };
154167
}
155168

156169
function primeModelRegistry(
@@ -416,14 +429,39 @@ describe("modelsListCommand forward-compat", () => {
416429
expect(mocks.ensureAuthProfileStore).toHaveBeenCalledWith("/tmp/openclaw-agent-research");
417430
});
418431

432+
it("rejects unknown provider filters before loading the model registry", async () => {
433+
const runtime = createRuntime();
434+
const previousExitCode = process.exitCode;
435+
process.exitCode = undefined;
436+
let observedExitCode: number | undefined;
437+
438+
try {
439+
await modelsListCommand(
440+
{ provider: "autoqa-no-such-provider", json: true },
441+
runtime as never,
442+
);
443+
observedExitCode = process.exitCode;
444+
} finally {
445+
process.exitCode = previousExitCode;
446+
}
447+
448+
expect(runtime.error).toHaveBeenCalledWith(
449+
expect.stringContaining('Unknown provider filter "autoqa-no-such-provider"'),
450+
);
451+
expect(observedExitCode).toBe(1);
452+
expect(mocks.loadModelRegistry).not.toHaveBeenCalled();
453+
expect(mocks.loadModelCatalog).not.toHaveBeenCalled();
454+
expect(mocks.printModelTable).not.toHaveBeenCalled();
455+
});
456+
419457
describe("empty model lists", () => {
420458
it.each([
421459
{ name: "JSON", options: { json: true } },
422460
{ name: "plain text", options: { plain: true } },
423461
])("renders empty $name output through the canonical model table", async ({ options }) => {
424462
mocks.resolveConfiguredEntries.mockReturnValueOnce({ entries: [] });
425463
const runtime = createRuntime();
426-
const opts = { ...options, provider: "autoqa-no-such-provider" };
464+
const opts = { ...options, provider: "openai" };
427465

428466
await modelsListCommand(opts, runtime as never);
429467

@@ -438,7 +476,7 @@ describe("modelsListCommand forward-compat", () => {
438476
mocks.startPromotionsFeedRefresh.mockReturnValueOnce(refreshToken);
439477
const runtime = createRuntime();
440478

441-
await modelsListCommand({ provider: "autoqa-no-such-provider" }, runtime as never);
479+
await modelsListCommand({ provider: "openai" }, runtime as never);
442480

443481
expect(runtime.log).toHaveBeenCalledWith("No models found.");
444482
expect(mocks.printModelTable).not.toHaveBeenCalled();

0 commit comments

Comments
 (0)