@terreno/admin-frontend 0.20.2 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/.ai/guidelines/core.md +10 -0
  2. package/dist/AdminBreadcrumbs.d.ts +13 -0
  3. package/dist/AdminBreadcrumbs.js +22 -0
  4. package/dist/AdminBreadcrumbs.js.map +1 -0
  5. package/dist/AdminFieldRenderer.js +3 -3
  6. package/dist/AdminFieldRenderer.js.map +1 -1
  7. package/dist/AdminFieldRendererCore.d.ts +2 -0
  8. package/dist/AdminFieldRendererCore.js +28 -18
  9. package/dist/AdminFieldRendererCore.js.map +1 -1
  10. package/dist/AdminHome.d.ts +22 -0
  11. package/dist/AdminHome.js +189 -0
  12. package/dist/AdminHome.js.map +1 -0
  13. package/dist/AdminModelForm.d.ts +24 -1
  14. package/dist/AdminModelForm.js +185 -14
  15. package/dist/AdminModelForm.js.map +1 -1
  16. package/dist/AdminModelList.d.ts +4 -0
  17. package/dist/AdminModelList.js +19 -4
  18. package/dist/AdminModelList.js.map +1 -1
  19. package/dist/AdminModelTable.d.ts +2 -27
  20. package/dist/AdminModelTable.js +316 -60
  21. package/dist/AdminModelTable.js.map +1 -1
  22. package/dist/AdminNestedArrayField.d.ts +1 -0
  23. package/dist/AdminNestedArrayField.js +26 -6
  24. package/dist/AdminNestedArrayField.js.map +1 -1
  25. package/dist/AdminObjectPicker.d.ts +1 -0
  26. package/dist/AdminObjectPicker.js +6 -2
  27. package/dist/AdminObjectPicker.js.map +1 -1
  28. package/dist/AdminPrimitiveArrayField.d.ts +1 -0
  29. package/dist/AdminPrimitiveArrayField.js +9 -8
  30. package/dist/AdminPrimitiveArrayField.js.map +1 -1
  31. package/dist/AdminRefField.js +2 -2
  32. package/dist/AdminRefField.js.map +1 -1
  33. package/dist/AdminScriptList.js +114 -7
  34. package/dist/AdminScriptList.js.map +1 -1
  35. package/dist/AdminScriptRunModal.d.ts +5 -0
  36. package/dist/AdminScriptRunModal.js +136 -30
  37. package/dist/AdminScriptRunModal.js.map +1 -1
  38. package/dist/AdminShell.d.ts +39 -0
  39. package/dist/AdminShell.js +80 -0
  40. package/dist/AdminShell.js.map +1 -0
  41. package/dist/AdminShellLayout.d.ts +23 -0
  42. package/dist/AdminShellLayout.js +32 -0
  43. package/dist/AdminShellLayout.js.map +1 -0
  44. package/dist/AdminVersionConfig.d.ts +5 -0
  45. package/dist/AdminVersionConfig.js +15 -5
  46. package/dist/AdminVersionConfig.js.map +1 -1
  47. package/dist/ConfigurationScreen.js +3 -3
  48. package/dist/ConfigurationScreen.js.map +1 -1
  49. package/dist/ConsentFormEditor.js +2 -2
  50. package/dist/ConsentFormEditor.js.map +1 -1
  51. package/dist/ConsentFormList.js +1 -1
  52. package/dist/ConsentFormList.js.map +1 -1
  53. package/dist/ConsentResponseViewer.js +3 -3
  54. package/dist/ConsentResponseViewer.js.map +1 -1
  55. package/dist/DocumentStorageBrowser.js +1 -1
  56. package/dist/DocumentStorageBrowser.js.map +1 -1
  57. package/dist/adminModelListQueryParams.d.ts +14 -0
  58. package/dist/adminModelListQueryParams.js +51 -0
  59. package/dist/adminModelListQueryParams.js.map +1 -0
  60. package/dist/adminShellNav.d.ts +10 -0
  61. package/dist/adminShellNav.js +29 -0
  62. package/dist/adminShellNav.js.map +1 -0
  63. package/dist/index.d.ts +6 -1
  64. package/dist/index.js +5 -0
  65. package/dist/index.js.map +1 -1
  66. package/dist/scriptRunUtils.d.ts +36 -0
  67. package/dist/scriptRunUtils.js +121 -0
  68. package/dist/scriptRunUtils.js.map +1 -0
  69. package/dist/types.d.ts +70 -0
  70. package/dist/types.js.map +1 -1
  71. package/dist/useAdminApi.d.ts +1 -0
  72. package/dist/useAdminApi.js +11 -0
  73. package/dist/useAdminApi.js.map +1 -1
  74. package/dist/useAdminBackgroundTask.d.ts +12 -0
  75. package/dist/useAdminBackgroundTask.js +26 -0
  76. package/dist/useAdminBackgroundTask.js.map +1 -0
  77. package/dist/useAdminScripts.d.ts +19 -1
  78. package/dist/useAdminScripts.js +33 -4
  79. package/dist/useAdminScripts.js.map +1 -1
  80. package/package.json +4 -3
  81. package/src/AdminBreadcrumbs.test.tsx +27 -0
  82. package/src/AdminBreadcrumbs.tsx +63 -0
  83. package/src/AdminFieldRenderer.tsx +3 -0
  84. package/src/AdminFieldRendererCore.tsx +59 -1
  85. package/src/AdminHome.test.tsx +208 -0
  86. package/src/AdminHome.tsx +474 -0
  87. package/src/AdminModelForm.test.tsx +81 -1
  88. package/src/AdminModelForm.tsx +282 -34
  89. package/src/AdminModelList.test.tsx +1 -1
  90. package/src/AdminModelList.tsx +72 -39
  91. package/src/AdminModelTable.test.tsx +11 -0
  92. package/src/AdminModelTable.tsx +530 -92
  93. package/src/AdminNestedArrayField.tsx +59 -9
  94. package/src/AdminObjectPicker.tsx +19 -1
  95. package/src/AdminPrimitiveArrayField.tsx +30 -15
  96. package/src/AdminRefField.tsx +2 -0
  97. package/src/AdminScriptList.tsx +307 -30
  98. package/src/AdminScriptRunModal.tsx +410 -95
  99. package/src/AdminShell.tsx +296 -0
  100. package/src/AdminShellLayout.tsx +34 -0
  101. package/src/AdminVersionConfig.tsx +120 -76
  102. package/src/ConfigurationScreen.tsx +4 -2
  103. package/src/ConsentFormEditor.tsx +3 -1
  104. package/src/ConsentFormList.tsx +1 -1
  105. package/src/ConsentResponseViewer.tsx +3 -3
  106. package/src/DocumentStorageBrowser.tsx +1 -1
  107. package/src/adminModelListQueryParams.ts +61 -0
  108. package/src/adminShellNav.test.ts +29 -0
  109. package/src/adminShellNav.ts +33 -0
  110. package/src/index.tsx +6 -1
  111. package/src/isolated/AdminScriptRunModal.isolated.tsx +152 -1
  112. package/src/scriptRunUtils.test.ts +146 -0
  113. package/src/scriptRunUtils.ts +149 -0
  114. package/src/types.ts +69 -0
  115. package/src/useAdminApi.ts +11 -0
  116. package/src/useAdminBackgroundTask.ts +40 -0
  117. package/src/useAdminScripts.ts +56 -5
@@ -0,0 +1,61 @@
1
+ import type {AdminModelConfig} from "./types";
2
+
3
+ export const ADMIN_LIST_MAX_SELECTION = 1000;
4
+
5
+ export type AdminListFilterState = Record<string, string | boolean | undefined>;
6
+
7
+ /**
8
+ * Builds query params for `GET` admin modelRouter list routes from UI state.
9
+ */
10
+ export const buildAdminListQueryParams = (input: {
11
+ filterState: AdminListFilterState;
12
+ limit: number;
13
+ modelConfig: AdminModelConfig;
14
+ page: number;
15
+ searchDebounced: string;
16
+ sort?: string;
17
+ }): Record<string, unknown> => {
18
+ const out: Record<string, unknown> = {
19
+ limit: input.limit,
20
+ page: input.page,
21
+ };
22
+ if (input.sort) {
23
+ out.sort = input.sort;
24
+ }
25
+ const {filterState, modelConfig, searchDebounced} = input;
26
+ const filters = modelConfig.filters ?? [];
27
+ for (const f of filters) {
28
+ if (f.kind === "dateRange") {
29
+ const gteKey = `${f.field}_gte`;
30
+ const lteKey = `${f.field}_lte`;
31
+ const gteVal = filterState[gteKey];
32
+ const lteVal = filterState[lteKey];
33
+ if (gteVal !== undefined && String(gteVal).trim() !== "") {
34
+ out[gteKey] = String(gteVal).trim();
35
+ }
36
+ if (lteVal !== undefined && String(lteVal).trim() !== "") {
37
+ out[lteKey] = String(lteVal).trim();
38
+ }
39
+ continue;
40
+ }
41
+ const raw = filterState[f.field];
42
+ if (raw === undefined || raw === "") {
43
+ continue;
44
+ }
45
+ if (f.kind === "boolean") {
46
+ if (raw === "all") {
47
+ continue;
48
+ }
49
+ out[f.field] = raw === true || raw === "true";
50
+ continue;
51
+ }
52
+ if (f.kind === "choice" || f.kind === "text" || f.kind === "ref") {
53
+ out[f.field] = String(raw);
54
+ }
55
+ }
56
+ const firstSearchField = modelConfig.searchFields?.[0];
57
+ if (firstSearchField && searchDebounced.trim() !== "") {
58
+ out[firstSearchField] = searchDebounced.trim();
59
+ }
60
+ return out;
61
+ };
@@ -0,0 +1,29 @@
1
+ import {describe, expect, it} from "bun:test";
2
+
3
+ import {groupAdminModelsByGroup} from "./adminShellNav";
4
+ import type {AdminModelConfig} from "./types";
5
+
6
+ const stubModel = (name: string, displayName: string, group?: string): AdminModelConfig =>
7
+ ({
8
+ defaultSort: "-created",
9
+ displayName,
10
+ fields: {},
11
+ group,
12
+ listFields: ["_id"],
13
+ name,
14
+ routePath: `/${name}`,
15
+ }) as unknown as AdminModelConfig;
16
+
17
+ describe("groupAdminModelsByGroup", () => {
18
+ it("groups by model.group and places General last", () => {
19
+ const groups = groupAdminModelsByGroup([
20
+ stubModel("A", "A", "Zebra"),
21
+ stubModel("B", "B"),
22
+ stubModel("C", "C", "Alpha"),
23
+ ]);
24
+ expect(groups.map((g) => g.group)).toEqual(["Alpha", "Zebra", "General"]);
25
+ expect(groups[0]?.models.map((m) => m.name)).toEqual(["C"]);
26
+ expect(groups[1]?.models.map((m) => m.name)).toEqual(["A"]);
27
+ expect(groups[2]?.models.map((m) => m.name)).toEqual(["B"]);
28
+ });
29
+ });
@@ -0,0 +1,33 @@
1
+ import type {AdminModelConfig} from "./types";
2
+
3
+ export interface AdminModelGroup {
4
+ group: string;
5
+ models: AdminModelConfig[];
6
+ }
7
+
8
+ /**
9
+ * Groups admin models by {@link AdminModelConfig.group} for sidebar navigation.
10
+ * Models without a group go under "General", which is sorted last.
11
+ */
12
+ export const groupAdminModelsByGroup = (models: AdminModelConfig[]): AdminModelGroup[] => {
13
+ const map = new Map<string, AdminModelConfig[]>();
14
+ for (const model of models) {
15
+ const group = model.group?.trim() || "General";
16
+ const list = map.get(group);
17
+ if (list) {
18
+ list.push(model);
19
+ } else {
20
+ map.set(group, [model]);
21
+ }
22
+ }
23
+ const keys = [...map.keys()].sort((a, b) => {
24
+ if (a === "General") {
25
+ return 1;
26
+ }
27
+ if (b === "General") {
28
+ return -1;
29
+ }
30
+ return a.localeCompare(b);
31
+ });
32
+ return keys.map((group) => ({group, models: map.get(group) ?? []}));
33
+ };
package/src/index.tsx CHANGED
@@ -1,5 +1,7 @@
1
+ export {type AdminBreadcrumbSegment, AdminBreadcrumbs} from "./AdminBreadcrumbs";
1
2
  export {AdminFieldRenderer} from "./AdminFieldRenderer";
2
- export {AdminModelForm} from "./AdminModelForm";
3
+ export {AdminHome} from "./AdminHome";
4
+ export {AdminModelForm, type AdminModelFormScreenTitleParams} from "./AdminModelForm";
3
5
  export {AdminModelList} from "./AdminModelList";
4
6
  export {AdminModelTable} from "./AdminModelTable";
5
7
  export {AdminNestedArrayField} from "./AdminNestedArrayField";
@@ -8,7 +10,10 @@ export {AdminPrimitiveArrayField} from "./AdminPrimitiveArrayField";
8
10
  export {AdminRefField, type AdminRefFieldProps} from "./AdminRefField";
9
11
  export {AdminScriptList} from "./AdminScriptList";
10
12
  export {AdminScriptRunModal} from "./AdminScriptRunModal";
13
+ export {AdminShell, type AdminShellProps, type AdminShellSidebarVariant} from "./AdminShell";
14
+ export {AdminShellLayout, type AdminShellLayoutProps} from "./AdminShellLayout";
11
15
  export {AdminVersionConfig} from "./AdminVersionConfig";
16
+ export {groupAdminModelsByGroup} from "./adminShellNav";
12
17
  export {CheckboxListEditor} from "./CheckboxListEditor";
13
18
  export {ConfigurationScreen} from "./ConfigurationScreen";
14
19
  export {ConsentFormEditor} from "./ConsentFormEditor";
@@ -30,7 +30,13 @@ mock.module("@terreno/ui", () => {
30
30
  const Spinner = () => ReactMod.createElement(RN.View, {testID: "spinner"});
31
31
  const Text = ({children, ...rest}: Record<string, unknown>) =>
32
32
  ReactMod.createElement(RN.Text, rest, children);
33
- return {Box, Button, Heading, Icon, Modal, Spinner, Text};
33
+ const Badge = ({value}: Record<string, unknown>) =>
34
+ ReactMod.createElement(RN.Text, {}, value as string);
35
+ const Banner = ({text}: Record<string, unknown>) =>
36
+ ReactMod.createElement(RN.Text, {}, text as string);
37
+ const TextField = ({value, placeholder}: Record<string, unknown>) =>
38
+ ReactMod.createElement(RN.Text, {}, (value as string) || (placeholder as string) || "");
39
+ return {Badge, Banner, Box, Button, Heading, Icon, Modal, Spinner, Text, TextField};
34
40
  });
35
41
 
36
42
  interface TaskState {
@@ -329,6 +335,151 @@ describe("AdminScriptRunModal", () => {
329
335
  expect(toJSON()).toBeDefined();
330
336
  });
331
337
 
338
+ it("shows the done view (no stuck spinner) once the task reaches completed", async () => {
339
+ // Start in confirm with no task so the dry-run button is available.
340
+ state.task = {data: undefined, error: null, isLoading: false};
341
+ const {getByTestId, queryByTestId, rerender} = renderWithTheme(
342
+ <AdminScriptRunModal
343
+ api={mockApi}
344
+ baseUrl="/admin"
345
+ onDismiss={() => {}}
346
+ scriptName="wet-script"
347
+ visible={true}
348
+ />
349
+ );
350
+
351
+ await pressDryRun(getByTestId);
352
+ // While running with no terminal task yet, the spinner + cancel are shown.
353
+ expect(queryByTestId("spinner")).toBeTruthy();
354
+ expect(queryByTestId("admin-script-cancel-button")).toBeTruthy();
355
+
356
+ // Simulate the poll returning a completed task with the framework's 100% progress.
357
+ state.task = {
358
+ data: {
359
+ task: {
360
+ progress: {message: "Done", percentage: 100, stage: "Complete"},
361
+ result: ["ok"],
362
+ status: "completed",
363
+ },
364
+ },
365
+ error: null,
366
+ isLoading: false,
367
+ };
368
+ rerender(
369
+ <AdminScriptRunModal
370
+ api={mockApi}
371
+ baseUrl="/admin"
372
+ onDismiss={() => {}}
373
+ scriptName="wet-script"
374
+ visible={true}
375
+ />
376
+ );
377
+ await waitTicks();
378
+
379
+ // The done view must render — no lingering spinner or cancel button.
380
+ expect(queryByTestId("spinner")).toBeNull();
381
+ expect(queryByTestId("admin-script-cancel-button")).toBeNull();
382
+ });
383
+
384
+ it("offers a live run from the done view after a dry run completes", async () => {
385
+ state.task = {data: undefined, error: null, isLoading: false};
386
+ const {getByTestId, rerender} = renderWithTheme(
387
+ <AdminScriptRunModal
388
+ api={mockApi}
389
+ baseUrl="/admin"
390
+ onDismiss={() => {}}
391
+ scriptName="migrate"
392
+ visible={true}
393
+ />
394
+ );
395
+
396
+ await pressDryRun(getByTestId);
397
+
398
+ state.task = {
399
+ data: {task: {isDryRun: true, result: ["all good"], status: "completed"}},
400
+ error: null,
401
+ isLoading: false,
402
+ };
403
+ rerender(
404
+ <AdminScriptRunModal
405
+ api={mockApi}
406
+ baseUrl="/admin"
407
+ onDismiss={() => {}}
408
+ scriptName="migrate"
409
+ visible={true}
410
+ />
411
+ );
412
+ await waitTicks();
413
+
414
+ const wetButton = getByTestId("admin-script-done-wet-run-button");
415
+ expect(wetButton).toBeTruthy();
416
+
417
+ runCalls.length = 0;
418
+ await act(async () => {
419
+ fireEvent.press(wetButton);
420
+ });
421
+ await waitTicks();
422
+
423
+ const startedWet = runCalls.some((c) => {
424
+ const arg = c as {name?: string; wetRun?: boolean};
425
+ return arg?.name === "migrate" && arg?.wetRun === true;
426
+ });
427
+ expect(startedWet).toBe(true);
428
+ });
429
+
430
+ it("resets to the confirm step when reopened so a previous run does not linger", async () => {
431
+ // First open: complete a run so the done view is showing.
432
+ state.task = {
433
+ data: {task: {result: ["done"], status: "completed"}},
434
+ error: null,
435
+ isLoading: false,
436
+ };
437
+ const {getByTestId, queryByTestId, rerender} = renderWithTheme(
438
+ <AdminScriptRunModal
439
+ api={mockApi}
440
+ baseUrl="/admin"
441
+ onDismiss={() => {}}
442
+ scriptName="migrate"
443
+ visible={false}
444
+ />
445
+ );
446
+ rerender(
447
+ <AdminScriptRunModal
448
+ api={mockApi}
449
+ baseUrl="/admin"
450
+ onDismiss={() => {}}
451
+ scriptName="migrate"
452
+ visible={true}
453
+ />
454
+ );
455
+ await waitTicks();
456
+
457
+ // Close, then reopen: the confirm step (dry-run button) must be shown again, not
458
+ // the previous run's results.
459
+ rerender(
460
+ <AdminScriptRunModal
461
+ api={mockApi}
462
+ baseUrl="/admin"
463
+ onDismiss={() => {}}
464
+ scriptName="migrate"
465
+ visible={false}
466
+ />
467
+ );
468
+ rerender(
469
+ <AdminScriptRunModal
470
+ api={mockApi}
471
+ baseUrl="/admin"
472
+ onDismiss={() => {}}
473
+ scriptName="migrate"
474
+ visible={true}
475
+ />
476
+ );
477
+ await waitTicks();
478
+
479
+ expect(getByTestId("admin-script-dry-run-button")).toBeTruthy();
480
+ expect(queryByTestId("admin-script-done-wet-run-button")).toBeNull();
481
+ });
482
+
332
483
  it("early-returns when scriptName is null", async () => {
333
484
  const {getByTestId} = renderWithTheme(
334
485
  <AdminScriptRunModal
@@ -0,0 +1,146 @@
1
+ import {describe, expect, it} from "bun:test";
2
+ import {DateTime} from "luxon";
3
+ import {
4
+ buildExport,
5
+ formatDuration,
6
+ isErrorLine,
7
+ latestRunByScript,
8
+ relativeTime,
9
+ shortId,
10
+ statusMeta,
11
+ summarizeOutput,
12
+ } from "./scriptRunUtils";
13
+ import type {ScriptRun} from "./types";
14
+
15
+ const makeRun = (overrides: Partial<ScriptRun>): ScriptRun => ({
16
+ _id: "id",
17
+ created: DateTime.now().toISO() ?? "",
18
+ isDryRun: true,
19
+ logs: [],
20
+ status: "completed",
21
+ taskType: "demo",
22
+ updated: DateTime.now().toISO() ?? "",
23
+ ...overrides,
24
+ });
25
+
26
+ describe("scriptRunUtils", () => {
27
+ describe("statusMeta", () => {
28
+ it("maps each status to a badge style", () => {
29
+ expect(statusMeta("completed").badgeStatus).toBe("success");
30
+ expect(statusMeta("failed").badgeStatus).toBe("error");
31
+ expect(statusMeta("cancelled").badgeStatus).toBe("warning");
32
+ expect(statusMeta("running").badgeStatus).toBe("info");
33
+ expect(statusMeta("pending").badgeStatus).toBe("neutral");
34
+ expect(statusMeta(undefined).label).toBe("Pending");
35
+ });
36
+ });
37
+
38
+ describe("relativeTime", () => {
39
+ it("returns empty for missing or invalid input", () => {
40
+ expect(relativeTime(undefined)).toBe("");
41
+ expect(relativeTime("not-a-date")).toBe("");
42
+ });
43
+
44
+ it("formats recent times", () => {
45
+ expect(relativeTime(DateTime.now().toISO() ?? "")).toBe("just now");
46
+ expect(relativeTime(DateTime.now().minus({minutes: 5}).toISO() ?? "")).toBe("5m ago");
47
+ expect(relativeTime(DateTime.now().minus({hours: 3}).toISO() ?? "")).toBe("3h ago");
48
+ expect(relativeTime(DateTime.now().minus({days: 1}).toISO() ?? "")).toBe("yesterday");
49
+ expect(relativeTime(DateTime.now().minus({days: 3}).toISO() ?? "")).toBe("3d ago");
50
+ });
51
+ });
52
+
53
+ describe("formatDuration", () => {
54
+ it("returns empty when either timestamp is missing", () => {
55
+ expect(formatDuration(undefined, undefined)).toBe("");
56
+ expect(formatDuration("2026-01-01T00:00:00.000Z", undefined)).toBe("");
57
+ });
58
+
59
+ it("formats seconds and minutes", () => {
60
+ const start = "2026-01-01T00:00:00.000Z";
61
+ expect(formatDuration(start, "2026-01-01T00:00:08.000Z")).toBe("8s");
62
+ expect(formatDuration(start, "2026-01-01T00:03:04.000Z")).toBe("3m 4s");
63
+ });
64
+ });
65
+
66
+ describe("isErrorLine", () => {
67
+ it("detects error-ish output lines", () => {
68
+ expect(isErrorLine("Failed to update document abc")).toBe(true);
69
+ expect(isErrorLine("ValidationError: required field")).toBe(true);
70
+ expect(isErrorLine("Created 5 records")).toBe(false);
71
+ });
72
+ });
73
+
74
+ describe("summarizeOutput", () => {
75
+ it("counts errors from error-level logs", () => {
76
+ const summary = summarizeOutput({
77
+ logs: [
78
+ {level: "info", message: "ok", timestamp: ""},
79
+ {level: "error", message: "boom", timestamp: ""},
80
+ ],
81
+ result: ["one", "two", "three"],
82
+ });
83
+ expect(summary.total).toBe(3);
84
+ expect(summary.errorCount).toBe(1);
85
+ expect(summary.successCount).toBe(2);
86
+ });
87
+
88
+ it("falls back to a per-line heuristic when no error logs exist", () => {
89
+ const summary = summarizeOutput({
90
+ logs: [],
91
+ result: ["Created record", "Failed to migrate record"],
92
+ });
93
+ expect(summary.errorCount).toBe(1);
94
+ expect(summary.successCount).toBe(1);
95
+ });
96
+
97
+ it("handles empty/undefined tasks", () => {
98
+ expect(summarizeOutput(undefined).total).toBe(0);
99
+ expect(summarizeOutput(null).errorCount).toBe(0);
100
+ });
101
+ });
102
+
103
+ describe("shortId", () => {
104
+ it("returns the last 6 characters", () => {
105
+ expect(shortId("507f1f77bcf86cd799439011")).toBe("439011");
106
+ expect(shortId("abc")).toBe("abc");
107
+ expect(shortId(undefined)).toBe("");
108
+ });
109
+ });
110
+
111
+ describe("buildExport", () => {
112
+ it("builds JSON with status classification", () => {
113
+ const {content, mimeType} = buildExport(["ok line", "error line"], "json");
114
+ const parsed = JSON.parse(content) as {line: number; result: string; status: string}[];
115
+ expect(mimeType).toBe("application/json");
116
+ expect(parsed).toHaveLength(2);
117
+ expect(parsed[1].status).toBe("error");
118
+ });
119
+
120
+ it("builds CSV with a header and escaped quotes", () => {
121
+ const {content, mimeType} = buildExport(['has "quote"'], "csv");
122
+ expect(mimeType).toBe("text/csv");
123
+ expect(content.startsWith("line,status,result\n")).toBe(true);
124
+ expect(content).toContain('""quote""');
125
+ });
126
+ });
127
+
128
+ describe("latestRunByScript", () => {
129
+ it("keeps only the newest run per script", () => {
130
+ const older = makeRun({
131
+ _id: "1",
132
+ created: "2026-01-01T00:00:00.000Z",
133
+ taskType: "alpha",
134
+ });
135
+ const newer = makeRun({
136
+ _id: "2",
137
+ created: "2026-02-01T00:00:00.000Z",
138
+ taskType: "alpha",
139
+ });
140
+ const other = makeRun({_id: "3", taskType: "beta"});
141
+ const latest = latestRunByScript([older, newer, other]);
142
+ expect(latest.alpha._id).toBe("2");
143
+ expect(latest.beta._id).toBe("3");
144
+ });
145
+ });
146
+ });
@@ -0,0 +1,149 @@
1
+ import type {IconName} from "@terreno/ui";
2
+ import {DateTime} from "luxon";
3
+ import type {BackgroundTask, ScriptRun} from "./types";
4
+
5
+ export type TaskStatus = BackgroundTask["status"];
6
+
7
+ export interface StatusMeta {
8
+ badgeStatus: "info" | "error" | "warning" | "success" | "neutral";
9
+ iconName: IconName;
10
+ label: string;
11
+ }
12
+
13
+ /** Visual treatment for a task status, shared by the list, history, and modal. */
14
+ export const statusMeta = (status?: TaskStatus): StatusMeta => {
15
+ switch (status) {
16
+ case "completed":
17
+ return {badgeStatus: "success", iconName: "circle-check", label: "Completed"};
18
+ case "failed":
19
+ return {badgeStatus: "error", iconName: "circle-xmark", label: "Failed"};
20
+ case "cancelled":
21
+ return {badgeStatus: "warning", iconName: "circle-exclamation", label: "Cancelled"};
22
+ case "running":
23
+ return {badgeStatus: "info", iconName: "spinner", label: "Running"};
24
+ default:
25
+ return {badgeStatus: "neutral", iconName: "clock", label: "Pending"};
26
+ }
27
+ };
28
+
29
+ /** Compact relative time (e.g. "just now", "5m ago", "yesterday", "Jun 3"). */
30
+ export const relativeTime = (iso?: string): string => {
31
+ if (!iso) {
32
+ return "";
33
+ }
34
+ const then = DateTime.fromISO(iso);
35
+ if (!then.isValid) {
36
+ return "";
37
+ }
38
+ const totalSeconds = Math.max(1, Math.floor(DateTime.now().diff(then).as("seconds")));
39
+ if (totalSeconds < 90) {
40
+ return "just now";
41
+ }
42
+ const minutes = Math.floor(totalSeconds / 60);
43
+ if (minutes < 60) {
44
+ return `${minutes}m ago`;
45
+ }
46
+ const hours = Math.floor(minutes / 60);
47
+ if (hours < 24) {
48
+ return `${hours}h ago`;
49
+ }
50
+ const days = Math.floor(hours / 24);
51
+ if (days === 1) {
52
+ return "yesterday";
53
+ }
54
+ if (days < 7) {
55
+ return `${days}d ago`;
56
+ }
57
+ return then.toLocaleString({day: "numeric", month: "short"});
58
+ };
59
+
60
+ /** Human duration between two ISO timestamps (e.g. "8s", "3m 4s"). */
61
+ export const formatDuration = (startIso?: string, endIso?: string): string => {
62
+ if (!startIso || !endIso) {
63
+ return "";
64
+ }
65
+ const start = DateTime.fromISO(startIso);
66
+ const end = DateTime.fromISO(endIso);
67
+ if (!start.isValid || !end.isValid) {
68
+ return "";
69
+ }
70
+ const seconds = Math.max(0, Math.round(end.diff(start).as("seconds")));
71
+ if (seconds < 60) {
72
+ return `${seconds}s`;
73
+ }
74
+ const minutes = Math.floor(seconds / 60);
75
+ return `${minutes}m ${seconds % 60}s`;
76
+ };
77
+
78
+ const ERROR_PATTERN =
79
+ /(error|exception|❌)|\b(fail|failed|failure|cannot|unable|invalid|denied)\b/i;
80
+
81
+ /** Heuristic: does an output line read like an error? Used to color/filter result rows. */
82
+ export const isErrorLine = (line: string): boolean => ERROR_PATTERN.test(line);
83
+
84
+ export interface OutputSummary {
85
+ errorCount: number;
86
+ successCount: number;
87
+ total: number;
88
+ }
89
+
90
+ /**
91
+ * Derive success/error counts for a task. The backend returns `result: string[]`
92
+ * plus structured `logs`, so error count prefers `error`-level logs and falls back
93
+ * to a per-line heuristic over the result strings.
94
+ */
95
+ export const summarizeOutput = (task?: Partial<BackgroundTask> | null): OutputSummary => {
96
+ const result = task?.result ?? [];
97
+ const errorLogs = (task?.logs ?? []).filter((log) => log.level === "error").length;
98
+ const heuristicErrors = result.filter(isErrorLine).length;
99
+ const errorCount = Math.max(errorLogs, heuristicErrors);
100
+ const total = result.length;
101
+ return {
102
+ errorCount: Math.min(errorCount, total || errorCount),
103
+ successCount: Math.max(0, total - Math.min(errorCount, total)),
104
+ total,
105
+ };
106
+ };
107
+
108
+ /** Short, monospace-friendly id suffix for display (e.g. "…a1b2c3"). */
109
+ export const shortId = (id?: string): string => {
110
+ if (!id) {
111
+ return "";
112
+ }
113
+ return id.length <= 6 ? id : id.slice(-6);
114
+ };
115
+
116
+ /** Build the CSV/JSON payload for exporting a run's output lines. */
117
+ export const buildExport = (
118
+ lines: string[],
119
+ kind: "csv" | "json"
120
+ ): {content: string; mimeType: string} => {
121
+ if (kind === "json") {
122
+ const rows = lines.map((line, index) => ({
123
+ line: index + 1,
124
+ result: line,
125
+ status: isErrorLine(line) ? "error" : "success",
126
+ }));
127
+ return {content: JSON.stringify(rows, null, 2), mimeType: "application/json"};
128
+ }
129
+ const escapeCsv = (value: string): string => `"${String(value).replace(/"/g, '""')}"`;
130
+ const head = "line,status,result\n";
131
+ const body = lines
132
+ .map((line, index) =>
133
+ [String(index + 1), isErrorLine(line) ? "error" : "success", line].map(escapeCsv).join(",")
134
+ )
135
+ .join("\n");
136
+ return {content: head + body, mimeType: "text/csv"};
137
+ };
138
+
139
+ /** Most-recent run per script name, keyed by `taskType`. */
140
+ export const latestRunByScript = (runs: ScriptRun[]): Record<string, ScriptRun> => {
141
+ const latest: Record<string, ScriptRun> = {};
142
+ for (const run of runs) {
143
+ const existing = latest[run.taskType];
144
+ if (!existing || (run.created ?? "") > (existing.created ?? "")) {
145
+ latest[run.taskType] = run;
146
+ }
147
+ }
148
+ return latest;
149
+ };