Skip to content

Commit a5b8b70

Browse files
authored
fix(ui): preserve advanced cron delivery settings when cloning (#117909)
* refactor(ui): consolidate task and log contracts * fix(cron): preserve advanced delivery routing * refactor(ui): share relative-time bucketing * fix(ui): retain narrow cron view types * fix(ui): keep cron form field keys total * style(ui): use narrowed task result boolean
1 parent c868805 commit a5b8b70

40 files changed

Lines changed: 405 additions & 472 deletions

‎packages/gateway-protocol/src/schema/cron.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,7 @@ const CronFailoverReasonSchema = Type.Union([
151151
Type.Literal("billing"),
152152
Type.Literal("server_error"),
153153
Type.Literal("timeout"),
154+
Type.Literal("tls_certificate"),
154155
Type.Literal("context_overflow"),
155156
Type.Literal("model_not_found"),
156157
Type.Literal("session_expired"),

‎packages/normalization-core/src/format.test.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,19 @@
11
import { describe, expect, it } from "vitest";
2-
import { formatByteSize } from "./format.js";
2+
import { bucketRelativeTimeMs, formatByteSize } from "./format.js";
3+
4+
describe("bucketRelativeTimeMs", () => {
5+
it.each([
6+
[0, { value: 0, unit: "second" }],
7+
[59_499, { value: 59, unit: "second" }],
8+
[59_500, { value: 1, unit: "minute" }],
9+
[59 * 60_000, { value: 59, unit: "minute" }],
10+
[60 * 60_000, { value: 1, unit: "hour" }],
11+
[47 * 3_600_000, { value: 47, unit: "hour" }],
12+
[48 * 3_600_000, { value: 2, unit: "day" }],
13+
] as const)("buckets %sms with nested rounding", (durationMs, expected) => {
14+
expect(bucketRelativeTimeMs(durationMs)).toEqual(expected);
15+
});
16+
});
317

418
describe("formatByteSize", () => {
519
it.each([

‎packages/normalization-core/src/format.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,27 @@ const BYTE_SIZE_STYLES = {
1717
"legacy-binary": { base: 1024, labels: ["B", "KB", "MB", "GB", "TB"] },
1818
} as const satisfies Record<ByteSizeStyle, { base: number; labels: readonly string[] }>;
1919

20+
export type RelativeTimeUnit = "second" | "minute" | "hour" | "day";
21+
22+
/** Buckets an absolute duration while preserving nested display rounding at unit boundaries. */
23+
export function bucketRelativeTimeMs(durationMs: number): {
24+
value: number;
25+
unit: RelativeTimeUnit;
26+
} {
27+
const seconds = Math.round(durationMs / 1000);
28+
if (seconds < 60) {
29+
return { value: seconds, unit: "second" };
30+
}
31+
const minutes = Math.round(seconds / 60);
32+
if (minutes < 60) {
33+
return { value: minutes, unit: "minute" };
34+
}
35+
const hours = Math.round(minutes / 60);
36+
return hours < 48
37+
? { value: hours, unit: "hour" }
38+
: { value: Math.round(hours / 24), unit: "day" };
39+
}
40+
2041
/** Formats a byte count with caller-explicit scale, labels, precision, and unit cap. */
2142
export function formatByteSize(bytes: number, options: ByteSizeFormatOptions): string {
2243
const { base, labels } = BYTE_SIZE_STYLES[options.style];
Lines changed: 61 additions & 116 deletions
Original file line numberDiff line numberDiff line change
@@ -1,131 +1,76 @@
11
// Cron protocol conformance tests cover schema compatibility for cron messages.
2-
import fs from "node:fs/promises";
3-
import path from "node:path";
4-
import { expectDefined } from "@openclaw/normalization-core";
2+
import { Value } from "typebox/value";
53
import { describe, expect, it } from "vitest";
64
import {
75
CronDeliverySchema,
86
CronJobStateSchema,
97
CronRunLogEntrySchema,
108
} from "../../packages/gateway-protocol/src/schema.js";
11-
12-
type SchemaLike = {
13-
anyOf?: Array<SchemaLike>;
14-
properties?: Record<string, unknown>;
15-
const?: unknown;
16-
};
17-
18-
function extractDeliveryModes(schema: SchemaLike): string[] {
19-
const modeSchema = schema.properties?.mode as SchemaLike | undefined;
20-
const directModes = (modeSchema?.anyOf ?? [])
21-
.map((entry) => entry?.const)
22-
.filter((value): value is string => typeof value === "string");
23-
if (directModes.length > 0) {
24-
return directModes;
25-
}
26-
27-
const unionModes = (schema.anyOf ?? [])
28-
.map((entry) => {
29-
const mode = entry.properties?.mode as SchemaLike | undefined;
30-
return mode?.const;
31-
})
32-
.filter((value): value is string => typeof value === "string");
33-
34-
return Array.from(new Set(unionModes));
35-
}
36-
37-
function extractConstUnionValues(schema: SchemaLike): string[] {
38-
return (schema.anyOf ?? [])
39-
.map((entry) => entry?.const)
40-
.filter((value): value is string => typeof value === "string");
41-
}
42-
43-
const UI_FILES = ["ui/src/api/types.ts", "ui/src/lib/cron/index.ts", "ui/src/pages/cron/view.ts"];
44-
45-
const MACOS_APP_SOURCES_DIR = "apps/macos/Sources/OpenClaw";
46-
const SWIFT_MODEL_CANDIDATES = [`${MACOS_APP_SOURCES_DIR}/CronModels.swift`];
47-
const SWIFT_STATUS_CANDIDATES = [`${MACOS_APP_SOURCES_DIR}/GatewayConnection.swift`];
48-
49-
async function resolveSwiftFiles(cwd: string, candidates: string[]): Promise<string[]> {
50-
const matches: string[] = [];
51-
for (const relPath of candidates) {
52-
try {
53-
await fs.access(path.join(cwd, relPath));
54-
matches.push(relPath);
55-
} catch {
56-
// ignore missing path
57-
}
58-
}
59-
if (matches.length === 0) {
60-
throw new Error(`Missing Swift cron definition. Tried: ${candidates.join(", ")}`);
61-
}
62-
return matches;
63-
}
9+
import type { CronJob } from "../../packages/gateway-protocol/src/schema/cron.types.js";
10+
import type { FailoverReason } from "../agents/embedded-agent-helpers/types.js";
11+
12+
type CronDelivery = NonNullable<CronJob["delivery"]>;
13+
14+
const DELIVERY_FIXTURES = {
15+
none: { mode: "none", threadId: 42 },
16+
announce: {
17+
mode: "announce",
18+
channel: "telegram",
19+
threadId: "topic-42",
20+
completionDestination: { mode: "webhook", to: "https://example.test/complete" },
21+
failureDestination: { mode: "announce", channel: "last", to: "ops" },
22+
},
23+
webhook: { mode: "webhook", to: "https://example.test/result" },
24+
} satisfies Record<CronDelivery["mode"], CronDelivery>;
25+
26+
const FAILOVER_REASONS = Object.keys({
27+
auth: true,
28+
auth_permanent: true,
29+
format: true,
30+
rate_limit: true,
31+
overloaded: true,
32+
billing: true,
33+
server_error: true,
34+
timeout: true,
35+
tls_certificate: true,
36+
context_overflow: true,
37+
model_not_found: true,
38+
session_expired: true,
39+
empty_response: true,
40+
no_error_details: true,
41+
unclassified: true,
42+
unknown: true,
43+
} satisfies Record<FailoverReason, true>) as FailoverReason[];
6444

6545
describe("cron protocol conformance", () => {
66-
it("ui + swift include all cron delivery modes from gateway schema", async () => {
67-
const modes = extractDeliveryModes(CronDeliverySchema as SchemaLike);
68-
expect(modes.length).toBeGreaterThan(0);
69-
70-
const cwd = process.cwd();
71-
for (const relPath of UI_FILES) {
72-
const content = await fs.readFile(path.join(cwd, relPath), "utf-8");
73-
for (const mode of modes) {
74-
expect(content, `${relPath} missing delivery mode ${mode}`).toContain(`"${mode}"`);
75-
}
76-
}
77-
78-
const swiftModelFiles = await resolveSwiftFiles(cwd, SWIFT_MODEL_CANDIDATES);
79-
for (const relPath of swiftModelFiles) {
80-
const content = await fs.readFile(path.join(cwd, relPath), "utf-8");
81-
for (const mode of modes) {
82-
const pattern = new RegExp(`\\bcase\\s+${mode}\\b`);
83-
expect(content, `${relPath} missing case ${mode}`).toMatch(pattern);
84-
}
46+
it("accepts every typed delivery mode and rejects unknown modes", () => {
47+
for (const delivery of Object.values(DELIVERY_FIXTURES)) {
48+
expect(Value.Check(CronDeliverySchema, delivery)).toBe(true);
8549
}
50+
expect(Value.Check(CronDeliverySchema, { mode: "email" })).toBe(false);
8651
});
8752

88-
it("cron status shape matches gateway fields in UI + Swift", async () => {
89-
const cwd = process.cwd();
90-
const uiTypes = await fs.readFile(path.join(cwd, "ui/src/api/types.ts"), "utf-8");
91-
expect(uiTypes).toContain("export type CronStatus");
92-
expect(uiTypes).toContain("jobs:");
93-
expect(uiTypes).not.toContain("jobCount");
94-
95-
const [swiftRelPath] = await resolveSwiftFiles(cwd, SWIFT_STATUS_CANDIDATES);
96-
const swiftPath = path.join(cwd, expectDefined(swiftRelPath, "swiftRelPath test invariant"));
97-
const swift = await fs.readFile(swiftPath, "utf-8");
98-
expect(swift).toContain("struct CronSchedulerStatus");
99-
expect(swift).toContain("let jobs:");
100-
});
101-
102-
it("cron public schemas keep the full failover reason set", () => {
103-
const expectedReasons = [
104-
"auth",
105-
"auth_permanent",
106-
"format",
107-
"rate_limit",
108-
"overloaded",
109-
"billing",
110-
"server_error",
111-
"timeout",
112-
"context_overflow",
113-
"model_not_found",
114-
"session_expired",
115-
"empty_response",
116-
"no_error_details",
117-
"unclassified",
118-
"unknown",
119-
];
120-
121-
const stateProperties = (CronJobStateSchema as SchemaLike).properties ?? {};
122-
const lastErrorReason = stateProperties.lastErrorReason as SchemaLike | undefined;
123-
expect(lastErrorReason).toBeDefined();
124-
expect(extractConstUnionValues(lastErrorReason ?? {})).toEqual(expectedReasons);
53+
it("accepts every core failover reason in state and run-history schemas", () => {
54+
for (const reason of FAILOVER_REASONS) {
55+
expect(Value.Check(CronJobStateSchema, { lastErrorReason: reason })).toBe(true);
56+
expect(
57+
Value.Check(CronRunLogEntrySchema, {
58+
ts: 1,
59+
jobId: "job-1",
60+
action: "finished",
61+
errorReason: reason,
62+
}),
63+
).toBe(true);
64+
}
12565

126-
const runLogProperties = (CronRunLogEntrySchema as SchemaLike).properties ?? {};
127-
const errorReason = runLogProperties.errorReason as SchemaLike | undefined;
128-
expect(errorReason).toBeDefined();
129-
expect(extractConstUnionValues(errorReason ?? {})).toEqual(expectedReasons);
66+
expect(Value.Check(CronJobStateSchema, { lastErrorReason: "not-a-reason" })).toBe(false);
67+
expect(
68+
Value.Check(CronRunLogEntrySchema, {
69+
ts: 1,
70+
jobId: "job-1",
71+
action: "finished",
72+
errorReason: "not-a-reason",
73+
}),
74+
).toBe(false);
13075
});
13176
});

‎src/cron/task-run-detail.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ const CRON_FAILOVER_REASONS = new Set<FailoverReason>([
2323
"billing",
2424
"server_error",
2525
"timeout",
26+
"tls_certificate",
2627
"model_not_found",
2728
"session_expired",
2829
"context_overflow",

‎src/cron/task-run-history.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -492,4 +492,16 @@ describe("cron task run history", () => {
492492
})?.errorReason,
493493
).toBeUndefined();
494494
});
495+
496+
it("preserves TLS certificate failures in stored run history", () => {
497+
const entry = {
498+
ts: 100,
499+
jobId: JOB_ID,
500+
action: "finished",
501+
status: "error",
502+
errorReason: "tls_certificate",
503+
} as const;
504+
505+
expect(parseCronRunLogEntryObject(entry)?.errorReason).toBe("tls_certificate");
506+
});
495507
});

‎src/infra/format-time/format-relative.ts‎

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
* - `formatTimeAgo(durationMs)` — format a duration as "5m ago" / "5m" (for known elapsed time)
88
* - `formatRelativeTimestamp(epochMs)` — format an epoch timestamp relative to now (handles future)
99
*/
10+
import { bucketRelativeTimeMs } from "@openclaw/normalization-core";
1011

1112
type FormatTimeAgoOptions = {
1213
/** Append "ago" suffix. Default: true. When false, returns bare unit: "5m", "2h" */
@@ -79,24 +80,18 @@ export function formatRelativeTimestamp(
7980
const absDiff = Math.abs(diff);
8081
const isPast = diff >= 0;
8182

82-
const sec = Math.round(absDiff / 1000);
83-
if (sec < 60) {
83+
const { value, unit } = bucketRelativeTimeMs(absDiff);
84+
if (unit === "second") {
8485
return isPast ? "just now" : "in <1m";
8586
}
86-
87-
const min = Math.round(sec / 60);
88-
if (min < 60) {
89-
return isPast ? `${min}m ago` : `in ${min}m`;
87+
if (unit === "minute") {
88+
return isPast ? `${value}m ago` : `in ${value}m`;
9089
}
91-
92-
const hr = Math.round(min / 60);
93-
if (hr < 48) {
94-
return isPast ? `${hr}h ago` : `in ${hr}h`;
90+
if (unit === "hour") {
91+
return isPast ? `${value}h ago` : `in ${value}h`;
9592
}
96-
97-
const day = Math.round(hr / 24);
98-
if (!options?.dateFallback || day <= 7) {
99-
return isPast ? `${day}d ago` : `in ${day}d`;
93+
if (!options?.dateFallback || value <= 7) {
94+
return isPast ? `${value}d ago` : `in ${value}d`;
10095
}
10196

10297
// Fall back to short date display for old timestamps
@@ -107,6 +102,6 @@ export function formatRelativeTimestamp(
107102
...(options.timezone ? { timeZone: options.timezone } : {}),
108103
}).format(new Date(timestampMs));
109104
} catch {
110-
return `${day}d ago`;
105+
return `${value}d ago`;
111106
}
112107
}

‎src/logging/parse-log-line.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,39 @@ describe("parseLogLine", () => {
2323
expect(parsed?.raw).toBe(line);
2424
});
2525

26+
it("prefers the complete persisted message while preserving numeric joining as fallback", () => {
27+
const persisted = parseLogLine(
28+
JSON.stringify({
29+
0: '{"subsystem":"gateway"}',
30+
1: "request failed",
31+
2: "retry later",
32+
message: "request failed retry later",
33+
}),
34+
);
35+
const positional = parseLogLine(
36+
JSON.stringify({ 0: "worker", 1: "request failed", 2: { retry: true } }),
37+
);
38+
39+
expect(persisted?.message).toBe("request failed retry later");
40+
expect(positional?.message).toBe('worker request failed {"retry":true}');
41+
});
42+
43+
it("uses structured metadata context before a structured positional fallback", () => {
44+
expect(
45+
parseLogLine(
46+
JSON.stringify({
47+
0: '{"subsystem":"legacy"}',
48+
1: "ready",
49+
_meta: { name: '{"module":"queue"}' },
50+
}),
51+
)?.module,
52+
).toBe("queue");
53+
expect(
54+
parseLogLine(JSON.stringify({ 0: '{"subsystem":"legacy"}', 1: "ready" }))?.subsystem,
55+
).toBe("legacy");
56+
expect(parseLogLine(JSON.stringify({ 0: "worker", 1: "ready" }))?.subsystem).toBeUndefined();
57+
});
58+
2659
it("falls back to meta timestamp when top-level time is missing", () => {
2760
const line = JSON.stringify({
2861
0: "hello",
@@ -41,5 +74,6 @@ describe("parseLogLine", () => {
4174

4275
it("returns null for invalid JSON", () => {
4376
expect(parseLogLine("not-json")).toBeNull();
77+
expect(parseLogLine("null")).toBeNull();
4478
});
4579
});

0 commit comments

Comments
 (0)