[codex] Polish routine layout follow-ups (#7858)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Routines are the recurring-work surface that lets a company keep operating without a human manually kicking off every task > - The base routine detail Variation C shell already landed in #7848, but the follow-up branch still had polish work for scheduling, section ergonomics, and the list layout > - Operators need routine edit screens to explain trigger behavior clearly, keep long detail pages usable on mobile/touch devices, and make grouped routine lists easier to scan > - This pull request rebases the remaining branch work onto current `master`, drops the duplicate commits already merged through #7848, and keeps only the new routine UI follow-ups > - The benefit is a cleaner routines workflow without reopening the already-merged shell work or carrying unrelated lockfile, workflow, or screenshot changes ## Linked Issues or Issue Description Refs #7848 Feature follow-up: polish the routines UI after the Variation C routine-detail shell landed. Problem / motivation: - Routine trigger configuration needs clearer previews for manual, schedule, API, and webhook execution modes. - Routine detail sections need better responsive spacing and touch ergonomics. - The routines list grouping should scan like grouped records instead of a table with heavy row dividers. - The routine tests need a React 19-compatible render helper so the focused routine suite can run in this workspace. Proposed solution: - Add cron-fire preview helpers and routine-run display helpers with focused tests. - Expand the routine editable and operate sections with richer trigger, variable, run, activity, and history presentation. - Adjust the routine detail shell and sub-sidebar spacing for mobile/touch layout. - Update grouped routine list presentation to use bordered group headers with borderless rows. - Switch affected routine tests to the repo's `flushSync` render-helper pattern. Alternatives considered: - Leaving the duplicate pre-#7848 commits in the branch would recreate conflicts and make the PR review much larger than the remaining change. - Keeping grouped routine rows inside one bordered table was simpler, but made the grouping hierarchy less legible. Roadmap alignment: - ROADMAP.md lists Scheduled Routines as a core shipped capability and Output/Enforced Outcomes as ongoing priorities. This is polish on that existing routines capability, not a new roadmap-level feature. ## What Changed - Added routine scheduling preview helpers and tests for cron/manual/API/webhook fire-policy display. - Added routine run display helpers and tests for deduped trigger labels and run-row subtitles. - Polished routine detail sections, including trigger summaries, operate views, and env/variable editing ergonomics. - Adjusted routine detail page and sub-sidebar spacing so the title/header area is less pinned and touch layouts center better. - Reworked the routines list grouped layout so group headers are bordered cards and routine rows are borderless inside each group. - Added Storybook coverage for the routines list grouped layout and updated the existing routine detail story. - Repaired routine tests to use `flushSync` helpers compatible with the installed React 19 runtime. ## Verification - `pnpm exec vitest run ui/src/lib/cron-fires.test.ts ui/src/lib/routine-run-display.test.ts ui/src/pages/Routines.test.tsx ui/src/components/RoutineSubSidebar.test.tsx ui/src/components/RoutineSaveBar.test.tsx` - Result: 5 test files passed, 37 tests passed. - Confirmed the rebased PR diff does not include `pnpm-lock.yaml`, `.github/workflows/*`, or committed screenshots. - Confirmed `origin/master` is an ancestor of the pushed branch head after rebase. ## Risks - Medium UI risk: this touches the routine detail and routine list surfaces, so visual regressions are possible in edge cases not covered by the focused tests. - Low data risk: no schema, migration, server API, or lockfile changes are included. - Review note: the branch intentionally force-pushed after rebasing because the original first three commits were already merged through #7848. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used OpenAI Codex, GPT-5-based coding agent runtime, with repository shell/tool access. Exact hosted runtime model identifier and context-window size were not exposed in the execution environment. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] If this change affects the UI, I have included before/after screenshots - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { nextCronFires, parseCronExpression, previewFirePolicies } from "./cron-fires";
|
||||
|
||||
describe("parseCronExpression", () => {
|
||||
it("parses a standard 5-field expression", () => {
|
||||
const parsed = parseCronExpression("0 14 * * 1-5");
|
||||
expect(parsed).not.toBeNull();
|
||||
expect(parsed?.minutes).toEqual([0]);
|
||||
expect(parsed?.hours).toEqual([14]);
|
||||
expect(parsed?.daysOfWeek).toEqual([1, 2, 3, 4, 5]);
|
||||
});
|
||||
|
||||
it("returns null for malformed expressions", () => {
|
||||
expect(parseCronExpression("not a cron")).toBeNull();
|
||||
expect(parseCronExpression("0 14 * *")).toBeNull();
|
||||
expect(parseCronExpression("")).toBeNull();
|
||||
expect(parseCronExpression(null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("nextCronFires", () => {
|
||||
it("computes the next N daily fires in UTC", () => {
|
||||
const after = new Date("2026-06-09T10:00:00Z");
|
||||
const fires = nextCronFires("0 14 * * *", 3, { after, timeZone: "UTC" });
|
||||
expect(fires.map((d) => d.toISOString())).toEqual([
|
||||
"2026-06-09T14:00:00.000Z",
|
||||
"2026-06-10T14:00:00.000Z",
|
||||
"2026-06-11T14:00:00.000Z",
|
||||
]);
|
||||
});
|
||||
|
||||
it("skips weekends for a weekday schedule", () => {
|
||||
// 2026-06-12 is a Friday; the next weekday fire after Fri is Mon 2026-06-15.
|
||||
const after = new Date("2026-06-12T15:00:00Z");
|
||||
const fires = nextCronFires("0 14 * * 1-5", 2, { after, timeZone: "UTC" });
|
||||
expect(fires.map((d) => d.toISOString())).toEqual([
|
||||
"2026-06-15T14:00:00.000Z",
|
||||
"2026-06-16T14:00:00.000Z",
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses OR semantics when day-of-month and day-of-week are both restricted", () => {
|
||||
const after = new Date("2026-06-09T10:00:00Z");
|
||||
const fires = nextCronFires("0 9 15 * 5", 3, { after, timeZone: "UTC" });
|
||||
expect(fires.map((d) => d.toISOString())).toEqual([
|
||||
"2026-06-12T09:00:00.000Z",
|
||||
"2026-06-15T09:00:00.000Z",
|
||||
"2026-06-19T09:00:00.000Z",
|
||||
]);
|
||||
});
|
||||
|
||||
it("interprets cron fields in the trigger timezone", () => {
|
||||
// 14:00 in New York (EDT, UTC-4 in June) is 18:00 UTC.
|
||||
const after = new Date("2026-06-09T10:00:00Z");
|
||||
const fires = nextCronFires("0 14 * * *", 1, { after, timeZone: "America/New_York" });
|
||||
expect(fires[0]?.toISOString()).toBe("2026-06-09T18:00:00.000Z");
|
||||
});
|
||||
|
||||
it("returns an empty list for an unparseable expression", () => {
|
||||
expect(nextCronFires("garbage", 5)).toEqual([]);
|
||||
expect(nextCronFires("0 14 * * *", 0)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("previewFirePolicies", () => {
|
||||
const fires = [
|
||||
new Date("2026-06-09T14:00:00Z"),
|
||||
new Date("2026-06-10T14:00:00Z"),
|
||||
new Date("2026-06-11T14:00:00Z"),
|
||||
];
|
||||
|
||||
it("always queues the first fire regardless of policy", () => {
|
||||
for (const policy of ["coalesce_if_active", "always_enqueue", "skip_if_active"]) {
|
||||
expect(previewFirePolicies(fires, policy)[0]?.disposition).toBe("queued");
|
||||
}
|
||||
});
|
||||
|
||||
it("coalesces subsequent fires under coalesce_if_active", () => {
|
||||
const preview = previewFirePolicies(fires, "coalesce_if_active");
|
||||
expect(preview.map((e) => e.disposition)).toEqual(["queued", "coalesced", "coalesced"]);
|
||||
expect(preview[1]?.label).toBe("would be coalesced");
|
||||
});
|
||||
|
||||
it("skips subsequent fires under skip_if_active", () => {
|
||||
const preview = previewFirePolicies(fires, "skip_if_active");
|
||||
expect(preview.map((e) => e.disposition)).toEqual(["queued", "skipped", "skipped"]);
|
||||
});
|
||||
|
||||
it("queues every fire under always_enqueue", () => {
|
||||
const preview = previewFirePolicies(fires, "always_enqueue");
|
||||
expect(preview.every((e) => e.disposition === "queued")).toBe(true);
|
||||
});
|
||||
|
||||
it("defaults unknown policies to coalesce", () => {
|
||||
const preview = previewFirePolicies(fires, "mystery");
|
||||
expect(preview[1]?.disposition).toBe("coalesced");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,272 @@
|
||||
/**
|
||||
* Client-side "next N schedule fires" helper for the routine Delivery preview (§3.5).
|
||||
*
|
||||
* Mirrors the server's timezone-aware cron tick (server/src/services/routines.ts
|
||||
* `nextCronTickInTimeZone`) closely enough for an illustrative preview: it parses
|
||||
* the same 5-field cron grammar and walks minute-by-minute, matching the cron
|
||||
* fields against wall-clock parts in the trigger's timezone via `Intl.DateTimeFormat`.
|
||||
*
|
||||
* This is preview-only — the authoritative `nextRunAt` is still computed server-side.
|
||||
*/
|
||||
|
||||
const WEEKDAY_INDEX: Record<string, number> = {
|
||||
Sun: 0,
|
||||
Mon: 1,
|
||||
Tue: 2,
|
||||
Wed: 3,
|
||||
Thu: 4,
|
||||
Fri: 5,
|
||||
Sat: 6,
|
||||
};
|
||||
|
||||
interface ParsedCron {
|
||||
minutes: number[];
|
||||
hours: number[];
|
||||
daysOfMonth: number[];
|
||||
months: number[];
|
||||
daysOfWeek: number[];
|
||||
daysOfMonthWildcard: boolean;
|
||||
daysOfWeekWildcard: boolean;
|
||||
}
|
||||
|
||||
interface FieldSpec {
|
||||
min: number;
|
||||
max: number;
|
||||
}
|
||||
|
||||
const FIELD_SPECS: FieldSpec[] = [
|
||||
{ min: 0, max: 59 }, // minute
|
||||
{ min: 0, max: 23 }, // hour
|
||||
{ min: 1, max: 31 }, // day of month
|
||||
{ min: 1, max: 12 }, // month
|
||||
{ min: 0, max: 6 }, // day of week (Sun = 0)
|
||||
];
|
||||
|
||||
function parseField(token: string, spec: FieldSpec): number[] {
|
||||
const values = new Set<number>();
|
||||
for (const rawPart of token.split(",")) {
|
||||
const part = rawPart.trim();
|
||||
if (part === "") throw new Error("Empty cron field element");
|
||||
|
||||
const slashIdx = part.indexOf("/");
|
||||
if (slashIdx !== -1) {
|
||||
const base = part.slice(0, slashIdx);
|
||||
const step = Number.parseInt(part.slice(slashIdx + 1), 10);
|
||||
if (!Number.isInteger(step) || step <= 0) throw new Error("Invalid cron step");
|
||||
let start = spec.min;
|
||||
let end = spec.max;
|
||||
if (base === "*") {
|
||||
// every `step` from min
|
||||
} else if (base.includes("-")) {
|
||||
const [a, b] = base.split("-").map((s) => Number.parseInt(s, 10));
|
||||
if (!Number.isInteger(a) || !Number.isInteger(b)) throw new Error("Invalid cron range");
|
||||
start = a;
|
||||
end = b;
|
||||
} else {
|
||||
const s = Number.parseInt(base, 10);
|
||||
if (!Number.isInteger(s)) throw new Error("Invalid cron start");
|
||||
start = s;
|
||||
}
|
||||
assertBounds(start, spec);
|
||||
assertBounds(end, spec);
|
||||
for (let i = start; i <= end; i += step) values.add(i);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (part.includes("-")) {
|
||||
const [a, b] = part.split("-").map((s) => Number.parseInt(s, 10));
|
||||
if (!Number.isInteger(a) || !Number.isInteger(b)) throw new Error("Invalid cron range");
|
||||
assertBounds(a, spec);
|
||||
assertBounds(b, spec);
|
||||
if (a > b) throw new Error("Invalid cron range (start > end)");
|
||||
for (let i = a; i <= b; i++) values.add(i);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (part === "*" || part === "?") {
|
||||
for (let i = spec.min; i <= spec.max; i++) values.add(i);
|
||||
continue;
|
||||
}
|
||||
|
||||
const val = Number.parseInt(part, 10);
|
||||
if (!Number.isInteger(val)) throw new Error("Invalid cron value");
|
||||
assertBounds(val, spec);
|
||||
values.add(val);
|
||||
}
|
||||
if (values.size === 0) throw new Error("Empty cron field");
|
||||
return [...values].sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
function assertBounds(value: number, spec: FieldSpec): void {
|
||||
if (value < spec.min || value > spec.max) {
|
||||
throw new Error(`Cron value ${value} out of range`);
|
||||
}
|
||||
}
|
||||
|
||||
function coversEntireField(values: number[], spec: FieldSpec): boolean {
|
||||
return values.length === spec.max - spec.min + 1 && values[0] === spec.min && values.at(-1) === spec.max;
|
||||
}
|
||||
|
||||
/** Parse a 5-field cron expression. Returns null when it can't be parsed. */
|
||||
export function parseCronExpression(expression: string | null | undefined): ParsedCron | null {
|
||||
if (!expression) return null;
|
||||
const tokens = expression.trim().split(/\s+/);
|
||||
if (tokens.length !== 5) return null;
|
||||
try {
|
||||
const daysOfMonth = parseField(tokens[2]!, FIELD_SPECS[2]!);
|
||||
const daysOfWeek = parseField(tokens[4]!, FIELD_SPECS[4]!);
|
||||
return {
|
||||
minutes: parseField(tokens[0]!, FIELD_SPECS[0]!),
|
||||
hours: parseField(tokens[1]!, FIELD_SPECS[1]!),
|
||||
daysOfMonth,
|
||||
months: parseField(tokens[3]!, FIELD_SPECS[3]!),
|
||||
daysOfWeek,
|
||||
daysOfMonthWildcard: coversEntireField(daysOfMonth, FIELD_SPECS[2]!),
|
||||
daysOfWeekWildcard: coversEntireField(daysOfWeek, FIELD_SPECS[4]!),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
interface ZonedParts {
|
||||
month: number;
|
||||
day: number;
|
||||
hour: number;
|
||||
minute: number;
|
||||
weekday: number;
|
||||
}
|
||||
|
||||
function getZonedMinuteParts(date: Date, timeZone: string): ZonedParts {
|
||||
const formatter = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone,
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
weekday: "short",
|
||||
hourCycle: "h23",
|
||||
});
|
||||
const map: Record<string, string> = {};
|
||||
for (const part of formatter.formatToParts(date)) {
|
||||
if (part.type !== "literal") map[part.type] = part.value;
|
||||
}
|
||||
const weekday = WEEKDAY_INDEX[map.weekday ?? ""];
|
||||
if (weekday === undefined) throw new Error(`Unable to resolve weekday for ${timeZone}`);
|
||||
return {
|
||||
month: Number(map.month),
|
||||
day: Number(map.day),
|
||||
hour: Number(map.hour),
|
||||
minute: Number(map.minute),
|
||||
weekday,
|
||||
};
|
||||
}
|
||||
|
||||
function matches(cron: ParsedCron, parts: ZonedParts): boolean {
|
||||
const dayOfMonthMatches = cron.daysOfMonth.includes(parts.day);
|
||||
const dayOfWeekMatches = cron.daysOfWeek.includes(parts.weekday);
|
||||
const dayMatches =
|
||||
!cron.daysOfMonthWildcard && !cron.daysOfWeekWildcard
|
||||
? dayOfMonthMatches || dayOfWeekMatches
|
||||
: dayOfMonthMatches && dayOfWeekMatches;
|
||||
|
||||
return (
|
||||
cron.minutes.includes(parts.minute) &&
|
||||
cron.hours.includes(parts.hour) &&
|
||||
cron.months.includes(parts.month) &&
|
||||
dayMatches
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute up to `count` upcoming fire instants for a cron expression, strictly
|
||||
* after `after`, interpreting the cron fields in `timeZone`.
|
||||
*/
|
||||
export function nextCronFires(
|
||||
expression: string | null | undefined,
|
||||
count: number,
|
||||
options: { after?: Date; timeZone?: string } = {},
|
||||
): Date[] {
|
||||
const cron = parseCronExpression(expression);
|
||||
if (!cron || count <= 0) return [];
|
||||
const timeZone = options.timeZone ?? "UTC";
|
||||
const after = options.after ?? new Date();
|
||||
|
||||
const cursor = new Date(after.getTime());
|
||||
cursor.setUTCSeconds(0, 0);
|
||||
cursor.setUTCMinutes(cursor.getUTCMinutes() + 1);
|
||||
|
||||
const fires: Date[] = [];
|
||||
// Preview-only bound: cap sparse or impossible schedules before they can stall the UI.
|
||||
const maxIterations = 2 * 366 * 24 * 60;
|
||||
for (let i = 0; i < maxIterations && fires.length < count; i++) {
|
||||
let parts: ZonedParts;
|
||||
try {
|
||||
parts = getZonedMinuteParts(cursor, timeZone);
|
||||
} catch {
|
||||
return fires;
|
||||
}
|
||||
if (matches(cron, parts)) fires.push(new Date(cursor.getTime()));
|
||||
cursor.setUTCMinutes(cursor.getUTCMinutes() + 1);
|
||||
}
|
||||
return fires;
|
||||
}
|
||||
|
||||
export type FireDisposition = "queued" | "coalesced" | "skipped";
|
||||
|
||||
export interface FirePreviewEntry {
|
||||
at: Date;
|
||||
disposition: FireDisposition;
|
||||
/** Short human label for the disposition (e.g. "queued", "would be coalesced"). */
|
||||
label: string;
|
||||
note: string | null;
|
||||
}
|
||||
|
||||
const DISPOSITION_LABEL: Record<FireDisposition, string> = {
|
||||
queued: "queued",
|
||||
coalesced: "would be coalesced",
|
||||
skipped: "would be skipped",
|
||||
};
|
||||
|
||||
/**
|
||||
* Annotate a list of upcoming fires with how the chosen concurrency policy would
|
||||
* treat each, assuming the previous run is still in flight when the next fires —
|
||||
* the worst case that makes the policy's behaviour legible (§3.5).
|
||||
*
|
||||
* Pure + deterministic so it can be unit-tested without a clock.
|
||||
*/
|
||||
export function previewFirePolicies(
|
||||
fires: Date[],
|
||||
concurrencyPolicy: string,
|
||||
): FirePreviewEntry[] {
|
||||
return fires.map((at, index) => {
|
||||
if (index === 0) {
|
||||
return {
|
||||
at,
|
||||
disposition: "queued",
|
||||
label: DISPOSITION_LABEL.queued,
|
||||
note: "runs immediately",
|
||||
};
|
||||
}
|
||||
let disposition: FireDisposition;
|
||||
switch (concurrencyPolicy) {
|
||||
case "always_enqueue":
|
||||
disposition = "queued";
|
||||
break;
|
||||
case "skip_if_active":
|
||||
disposition = "skipped";
|
||||
break;
|
||||
case "coalesce_if_active":
|
||||
default:
|
||||
disposition = "coalesced";
|
||||
break;
|
||||
}
|
||||
return {
|
||||
at,
|
||||
disposition,
|
||||
label: DISPOSITION_LABEL[disposition],
|
||||
note: disposition === "queued" ? null : "if the previous run is still active",
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { RoutineVariable } from "@paperclipai/shared";
|
||||
import { dedupedTriggerLabel, runRowSubtitle } from "./routine-run-display";
|
||||
|
||||
const variables: RoutineVariable[] = [
|
||||
{ name: "customer", label: null, type: "text", defaultValue: null, required: true, options: [] },
|
||||
{ name: "retries", label: null, type: "number", defaultValue: null, required: false, options: [] },
|
||||
];
|
||||
|
||||
describe("runRowSubtitle", () => {
|
||||
it("shows inline variable values for successful runs", () => {
|
||||
const subtitle = runRowSubtitle(
|
||||
{
|
||||
status: "succeeded",
|
||||
failureReason: null,
|
||||
triggerPayload: { customer: "Acme", retries: 3, PAPERCLIP_RUN_ID: "ignored" },
|
||||
},
|
||||
variables,
|
||||
);
|
||||
expect(subtitle).toBe('customer="Acme", retries=3');
|
||||
});
|
||||
|
||||
it("only includes declared routine variables, not builtin payload keys", () => {
|
||||
const subtitle = runRowSubtitle(
|
||||
{ status: "succeeded", failureReason: null, triggerPayload: { PAPERCLIP_RUN_ID: "x" } },
|
||||
variables,
|
||||
);
|
||||
expect(subtitle).toBe("");
|
||||
});
|
||||
|
||||
it("shows the failure reason for failed runs", () => {
|
||||
const subtitle = runRowSubtitle(
|
||||
{ status: "failed", failureReason: "Cron timed out", triggerPayload: { customer: "Acme" } },
|
||||
variables,
|
||||
);
|
||||
expect(subtitle).toBe("Cron timed out");
|
||||
});
|
||||
|
||||
it("falls back to a generic label when a failed run has no reason", () => {
|
||||
const subtitle = runRowSubtitle(
|
||||
{ status: "failed", failureReason: null, triggerPayload: null },
|
||||
variables,
|
||||
);
|
||||
expect(subtitle).toBe("Run failed");
|
||||
});
|
||||
|
||||
it("returns empty when there is no payload", () => {
|
||||
expect(
|
||||
runRowSubtitle({ status: "succeeded", failureReason: null, triggerPayload: null }, variables),
|
||||
).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("dedupedTriggerLabel", () => {
|
||||
it("drops the label when it merely restates the kind", () => {
|
||||
expect(dedupedTriggerLabel({ kind: "schedule", label: "schedule" })).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps a meaningful custom label", () => {
|
||||
expect(dedupedTriggerLabel({ kind: "schedule", label: "Nightly sync" })).toBe("Nightly sync");
|
||||
});
|
||||
|
||||
it("returns null for missing labels or triggers", () => {
|
||||
expect(dedupedTriggerLabel({ kind: "webhook", label: null })).toBeNull();
|
||||
expect(dedupedTriggerLabel({ kind: "webhook", label: " " })).toBeNull();
|
||||
expect(dedupedTriggerLabel(null)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { RoutineRunSummary, RoutineVariable } from "@paperclipai/shared";
|
||||
|
||||
/**
|
||||
* Format a single resolved variable value for the runs-row subtitle (§3.6).
|
||||
* Strings are quoted (`customer="Acme"`); numbers/booleans rendered bare.
|
||||
*/
|
||||
function formatVariableValue(value: unknown): string {
|
||||
if (typeof value === "string") return `"${value}"`;
|
||||
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
||||
if (value == null) return "—";
|
||||
try {
|
||||
return JSON.stringify(value);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The de-duped trigger label for a run. The kind chip already states the kind,
|
||||
* so when a trigger has no custom label (`label` falls back to `kind`) we drop
|
||||
* the redundant text rather than re-stating it.
|
||||
*/
|
||||
export function dedupedTriggerLabel(
|
||||
trigger: Pick<RoutineRunSummary["trigger"] & object, "kind" | "label"> | null | undefined,
|
||||
): string | null {
|
||||
if (!trigger) return null;
|
||||
const label = trigger.label?.trim();
|
||||
if (!label) return null;
|
||||
if (label === trigger.kind) return null;
|
||||
return label;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subtitle line for a run row (§3.6):
|
||||
* - failed runs show the failure reason ("why" without clicking through);
|
||||
* - other runs show the inline resolved variable values (e.g. `customer="Acme"`).
|
||||
* Returns an empty string when there is nothing meaningful to show.
|
||||
*/
|
||||
export function runRowSubtitle(
|
||||
run: Pick<RoutineRunSummary, "status" | "failureReason" | "triggerPayload">,
|
||||
variables: readonly RoutineVariable[] | null | undefined,
|
||||
): string {
|
||||
if (run.status === "failed") {
|
||||
return run.failureReason?.trim() || "Run failed";
|
||||
}
|
||||
const payload = run.triggerPayload;
|
||||
if (!payload || typeof payload !== "object") return "";
|
||||
const parts: string[] = [];
|
||||
for (const variable of variables ?? []) {
|
||||
if (!(variable.name in payload)) continue;
|
||||
parts.push(`${variable.name}=${formatVariableValue((payload as Record<string, unknown>)[variable.name])}`);
|
||||
}
|
||||
return parts.join(", ");
|
||||
}
|
||||
Reference in New Issue
Block a user