@alepha/ui 0.25.0 → 0.25.2

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 (104) hide show
  1. package/package.json +4 -5
  2. package/src/components/account/__tests__/account-router.spec.ts +201 -0
  3. package/src/components/account/account-connections.tsx +103 -0
  4. package/src/components/account/account-delete-dialog.tsx +184 -0
  5. package/src/components/account/account-header.tsx +57 -0
  6. package/src/components/account/account-keys.tsx +221 -0
  7. package/src/components/account/account-layout.tsx +63 -0
  8. package/src/components/account/account-password-dialog.tsx +152 -0
  9. package/src/components/account/account-profile.tsx +229 -0
  10. package/src/components/account/account-router-options.tsx +74 -0
  11. package/src/components/account/account-router-page.tsx +69 -0
  12. package/src/components/account/account-router.tsx +214 -0
  13. package/src/components/account/account-security.tsx +150 -0
  14. package/src/components/account/account-sessions.tsx +140 -0
  15. package/src/components/admin/__tests__/admin-keys-token-dialog.browser.spec.tsx +62 -0
  16. package/src/components/admin/__tests__/admin-layout.browser.spec.tsx +82 -0
  17. package/src/components/admin/__tests__/admin-router-page.spec.ts +54 -0
  18. package/src/components/admin/__tests__/admin-router.spec.ts +208 -0
  19. package/src/components/admin/__tests__/admin-user-cell.browser.spec.tsx +99 -0
  20. package/src/components/admin/__tests__/admin-user-detail.spec.ts +29 -0
  21. package/src/components/admin/admin-analytics-query-panel.tsx +149 -0
  22. package/src/components/admin/admin-analytics-results.tsx +95 -0
  23. package/src/components/admin/admin-analytics.tsx +104 -0
  24. package/src/components/admin/admin-audits.tsx +12 -15
  25. package/src/components/admin/admin-files.tsx +10 -18
  26. package/src/components/admin/admin-jobs-executions-panel.tsx +2 -1
  27. package/src/components/admin/admin-jobs.tsx +3 -1
  28. package/src/components/admin/admin-keys-token-dialog.tsx +123 -0
  29. package/src/components/admin/admin-keys.tsx +54 -3
  30. package/src/components/admin/admin-layout.tsx +107 -0
  31. package/src/components/admin/admin-payments.tsx +4 -5
  32. package/src/components/admin/admin-router-options.tsx +130 -0
  33. package/src/components/admin/admin-router-page.tsx +74 -0
  34. package/src/components/admin/admin-router.tsx +379 -0
  35. package/src/components/admin/admin-sessions.tsx +2 -16
  36. package/src/components/admin/admin-user-cell.tsx +70 -0
  37. package/src/components/admin/admin-user-detail-overview-tab.tsx +28 -0
  38. package/src/components/admin/admin-user-detail-profile-policy.spec.ts +146 -0
  39. package/src/components/admin/admin-user-detail-profile-policy.ts +147 -0
  40. package/src/components/admin/admin-user-detail-security-tab.tsx +1 -1
  41. package/src/components/admin/admin-user-detail.tsx +76 -32
  42. package/src/components/admin/admin-users-status-filter.tsx +2 -0
  43. package/src/components/admin/admin-workflows-execution-sheet.tsx +277 -0
  44. package/src/components/admin/admin-workflows-executions-panel.tsx +170 -0
  45. package/src/components/admin/admin-workflows-status-badge.tsx +40 -0
  46. package/src/components/admin/admin-workflows.tsx +207 -0
  47. package/src/components/alepha-table/alepha-table.tsx +73 -17
  48. package/src/components/app-actions/__tests__/app-actions.browser.spec.tsx +79 -0
  49. package/src/components/app-actions/app-actions.tsx +113 -0
  50. package/src/components/app-shell/app-shell.tsx +122 -0
  51. package/src/components/auth/auth-reset-password.tsx +81 -8
  52. package/src/components/button-user/button-user.tsx +58 -1
  53. package/src/components/control/control.tsx +14 -71
  54. package/src/components/control-password/control-password.tsx +87 -0
  55. package/src/components/control-select/__tests__/control-select-clear-label.browser.spec.tsx +101 -0
  56. package/src/components/control-select/__tests__/control-select-deselect.browser.spec.tsx +126 -0
  57. package/src/components/control-select/__tests__/control-select-searchable.browser.spec.tsx +142 -0
  58. package/src/components/control-select/control-select.tsx +133 -111
  59. package/src/components/control-upload/control-upload.tsx +27 -1
  60. package/src/components/markdown-view/markdown-view.tsx +6 -0
  61. package/src/components/nav-shell/nav-page.tsx +3 -3
  62. package/src/components/settings/__tests__/settings-nav.browser.spec.tsx +123 -0
  63. package/src/components/settings/__tests__/settings-section.browser.spec.tsx +130 -0
  64. package/src/components/settings/settings-danger-section.tsx +59 -0
  65. package/src/components/settings/settings-layout.tsx +56 -0
  66. package/src/components/settings/settings-nav.tsx +131 -0
  67. package/src/components/settings/settings-row.tsx +81 -0
  68. package/src/components/settings/settings-section.tsx +64 -0
  69. package/src/components/ui/alert-dialog.tsx +1 -1
  70. package/src/components/ui/avatar.tsx +2 -0
  71. package/src/components/ui/breadcrumb.tsx +1 -1
  72. package/src/components/ui/calendar.tsx +11 -6
  73. package/src/components/ui/card.tsx +5 -5
  74. package/src/components/ui/carousel.tsx +4 -4
  75. package/src/components/ui/chart.tsx +2 -0
  76. package/src/components/ui/collapsible.tsx +2 -0
  77. package/src/components/ui/combobox.tsx +3 -1
  78. package/src/components/ui/context-menu.tsx +3 -3
  79. package/src/components/ui/dialog.tsx +6 -1
  80. package/src/components/ui/direction.tsx +2 -0
  81. package/src/components/ui/drawer.tsx +134 -37
  82. package/src/components/ui/dropdown-menu.tsx +13 -3
  83. package/src/components/ui/empty.tsx +4 -1
  84. package/src/components/ui/input-otp.tsx +2 -0
  85. package/src/components/ui/menubar.tsx +2 -2
  86. package/src/components/ui/pagination.tsx +2 -2
  87. package/src/components/ui/popover.tsx +2 -0
  88. package/src/components/ui/radio-group.tsx +2 -0
  89. package/src/components/ui/scroll-area.tsx +2 -0
  90. package/src/components/ui/select.tsx +1 -1
  91. package/src/components/ui/separator.tsx +2 -0
  92. package/src/components/ui/sheet.tsx +4 -1
  93. package/src/components/ui/sidebar.tsx +1 -1
  94. package/src/components/ui/spinner.tsx +1 -0
  95. package/src/components/ui/switch.tsx +2 -0
  96. package/src/components/ui/tabs.tsx +2 -0
  97. package/src/components/ui/toggle-group.tsx +2 -0
  98. package/src/components/ui/tooltip.tsx +2 -0
  99. package/src/lib/__tests__/rehype-safe-img.spec.ts +121 -0
  100. package/src/lib/i18n-fr.ts +68 -0
  101. package/src/lib/rehype-safe-img.ts +150 -0
  102. package/src/lib/resize-image.ts +135 -0
  103. package/src/styles.css +126 -1
  104. /package/src/components/{admin/admin-user-detail-provider-labels.ts → auth/provider-labels.ts} +0 -0
@@ -0,0 +1,147 @@
1
+ import type {
2
+ FieldRequirement,
3
+ UpdateUser,
4
+ UsernameFieldRequirement,
5
+ } from "alepha/api/users";
6
+ import type { ProfileForm } from "./admin-user-detail-profile-schema.ts";
7
+
8
+ /**
9
+ * The realm settings the admin profile form cares about. A structural subset
10
+ * of the realm config's public settings, so `realmConfig.settings` can be
11
+ * passed straight in.
12
+ */
13
+ export interface ProfileRealmSettings {
14
+ username?: UsernameFieldRequirement;
15
+ email?: FieldRequirement;
16
+ }
17
+
18
+ export interface ProfileFieldPolicy {
19
+ visible: boolean;
20
+ required: boolean;
21
+ }
22
+
23
+ export interface ProfilePolicy {
24
+ username: ProfileFieldPolicy;
25
+ email: ProfileFieldPolicy;
26
+ }
27
+
28
+ /**
29
+ * The parts of the loaded user the policy reads: what the record already
30
+ * carries, as opposed to what the form currently holds.
31
+ */
32
+ export interface ProfileUser {
33
+ username?: string;
34
+ email?: string;
35
+ }
36
+
37
+ export type ProfileIssueReason = "required" | "cannot-clear";
38
+
39
+ export interface ProfileIssue {
40
+ field: "username" | "email";
41
+ reason: ProfileIssueReason;
42
+ }
43
+
44
+ /**
45
+ * Whether a single field is offered, and whether it must be filled.
46
+ */
47
+ const fieldPolicy = (
48
+ requirement: UsernameFieldRequirement | undefined,
49
+ current: string | undefined,
50
+ ): ProfileFieldPolicy => {
51
+ // No settings means the realm config could not be read. Inventing a
52
+ // requirement the realm may not have is what broke this form for
53
+ // username-only realms in the first place — and nothing server-side
54
+ // requires either field, so "optional" is both the safe default and the
55
+ // accurate one.
56
+ const req = requirement ?? "optional";
57
+ return {
58
+ // A realm that has stopped collecting a field can still have rows that
59
+ // carry one. Hide the input only when there is also nothing to show.
60
+ visible: req !== "none" || Boolean(current),
61
+ // `"email"` (username auto-derived from the email at signup) is not a
62
+ // requirement an admin has to satisfy by hand.
63
+ required: req === "required",
64
+ };
65
+ };
66
+
67
+ /**
68
+ * Derive which profile fields the admin form offers, and which of them the
69
+ * realm insists on.
70
+ *
71
+ * The form itself must not decide this: a realm configured for username-only
72
+ * sign-in (`email: "none"`) has users with no email at all, and demanding one
73
+ * makes every save fail — including a save that only touches roles.
74
+ */
75
+ export const profilePolicy = (
76
+ settings?: ProfileRealmSettings,
77
+ user?: ProfileUser,
78
+ ): ProfilePolicy => ({
79
+ username: fieldPolicy(settings?.username, user?.username),
80
+ email: fieldPolicy(settings?.email, user?.email),
81
+ });
82
+
83
+ /**
84
+ * Validate the submitted values against the realm policy. Returns every
85
+ * problem found; callers typically report the first.
86
+ */
87
+ export const profileIssues = (
88
+ values: ProfileForm,
89
+ policy: ProfilePolicy,
90
+ user?: ProfileUser,
91
+ ): ProfileIssue[] => {
92
+ const issues: ProfileIssue[] = [];
93
+ for (const field of ["username", "email"] as const) {
94
+ if (!policy[field].visible) continue;
95
+ if ((values[field] ?? "").trim()) continue;
96
+ if (policy[field].required) {
97
+ issues.push({ field, reason: "required" });
98
+ continue;
99
+ }
100
+ // Blanking a field that has a value is not a no-op the user should be
101
+ // left guessing about. `username` and `email` are both unique-indexed,
102
+ // so a blank cannot be written as `""` — the second user to try it
103
+ // collides with the first — and a partial PATCH has no way to spell
104
+ // "unset". Refuse it rather than drop the key and report success on a
105
+ // save that changed nothing.
106
+ if ((user?.[field] ?? "") !== "") {
107
+ issues.push({ field, reason: "cannot-clear" });
108
+ }
109
+ }
110
+ return issues;
111
+ };
112
+
113
+ /**
114
+ * Build the PATCH body from the form values.
115
+ *
116
+ * Fields the realm does not collect — and blank optional ones — are omitted
117
+ * entirely rather than sent as `""`: `users` is uniquely indexed on
118
+ * `(realm, username)` and `(realm, email)`, so an empty string is a value
119
+ * that collides, not an absence.
120
+ */
121
+ export const profileUpdateBody = (
122
+ values: ProfileForm,
123
+ policy: ProfilePolicy,
124
+ user?: ProfileUser,
125
+ ): UpdateUser => {
126
+ const body: UpdateUser = {
127
+ firstName: (values.firstName ?? "").trim(),
128
+ lastName: (values.lastName ?? "").trim(),
129
+ roles: values.roles ?? [],
130
+ };
131
+
132
+ const username = (values.username ?? "").trim();
133
+ if (policy.username.visible && username) {
134
+ body.username = username;
135
+ }
136
+
137
+ const email = (values.email ?? "").trim();
138
+ if (policy.email.visible && email) {
139
+ body.email = email;
140
+ // Changing the email invalidates the verified flag. The server enforces
141
+ // this as well; mirroring it keeps the UI consistent before the refetch.
142
+ body.emailVerified =
143
+ email === (user?.email ?? "") && Boolean(values.emailVerified);
144
+ }
145
+
146
+ return body;
147
+ };
@@ -16,7 +16,7 @@ import type { IdentityResource } from "alepha/api/users";
16
16
  import type { UseActionReturn } from "alepha/react";
17
17
  import { useI18n } from "alepha/react/i18n";
18
18
  import { KeyRound, Trash2 } from "lucide-react";
19
- import { PROVIDER_LABELS } from "./admin-user-detail-provider-labels.ts";
19
+ import { PROVIDER_LABELS } from "../auth/provider-labels.ts";
20
20
 
21
21
  export interface AdminUserDetailSecurityTabProps {
22
22
  /**
@@ -20,8 +20,8 @@ import type {
20
20
  AdminSessionController,
21
21
  AdminUserController,
22
22
  IdentityResource,
23
+ RealmController,
23
24
  SessionResource,
24
- UpdateUser,
25
25
  } from "alepha/api/users";
26
26
  import { useAction, useClient, useQuery } from "alepha/react";
27
27
  import { useAuth } from "alepha/react/auth";
@@ -40,12 +40,18 @@ import {
40
40
  UserX,
41
41
  } from "lucide-react";
42
42
  import { useCallback, useEffect, useState } from "react";
43
+ import { PROVIDER_LABELS } from "../auth/provider-labels.ts";
43
44
  import { passwordSchema } from "./admin-user-detail-password-schema.ts";
45
+ import {
46
+ type ProfileIssue,
47
+ profileIssues,
48
+ profilePolicy,
49
+ profileUpdateBody,
50
+ } from "./admin-user-detail-profile-policy.ts";
44
51
  import {
45
52
  type ProfileForm,
46
53
  profileSchema,
47
54
  } from "./admin-user-detail-profile-schema.ts";
48
- import { PROVIDER_LABELS } from "./admin-user-detail-provider-labels.ts";
49
55
 
50
56
  export interface AdminUserDetailProps {
51
57
  /**
@@ -63,6 +69,23 @@ export interface AdminUserDetailProps {
63
69
  type TabKey = "overview" | "security" | "sessions" | "audits";
64
70
  const tabSchema = z.object({ tab: z.string().optional() });
65
71
 
72
+ /**
73
+ * Resolves the id param for this page, preferring `:userId` (the param name
74
+ * `AdminRouter`'s own route declares) and falling back to `:id` (the name
75
+ * this component read exclusively before `AdminRouter` existed).
76
+ *
77
+ * The fallback exists for `~/git/club/apps/platform`, which vendors
78
+ * `@alepha/ui` and declares its own user-detail route as `/users/:id` against
79
+ * this same component. Without it, that application's next upgrade of
80
+ * `@alepha/ui` would resolve `userId` to `undefined`, fall through to the
81
+ * empty string, and load `AdminUserDetail` with no id at all instead of
82
+ * failing to build.
83
+ */
84
+ export const resolveUserDetailId = (params: {
85
+ userId?: string;
86
+ id?: string;
87
+ }): string => String(params.userId ?? params.id ?? "");
88
+
66
89
  /**
67
90
  * Composition root for the admin user detail page.
68
91
  *
@@ -73,11 +96,12 @@ const tabSchema = z.object({ tab: z.string().optional() });
73
96
  export const AdminUserDetail = (props: AdminUserDetailProps) => {
74
97
  const router = useRouter();
75
98
  const routerState = useRouterState();
76
- const userId = String(routerState.params.id ?? "");
99
+ const userId = resolveUserDetailId(routerState.params);
77
100
  const userClient = useClient<AdminUserController>();
78
101
  const sessionClient = useClient<AdminSessionController>();
79
102
  const identityClient = useClient<AdminIdentityController>();
80
103
  const auditClient = useClient<AdminAuditController>();
104
+ const realmClient = useClient<RealmController>();
81
105
  const { tr } = useI18n();
82
106
  const toast = useToast();
83
107
  const { user: currentUser } = useAuth();
@@ -151,8 +175,49 @@ export const AdminUserDetail = (props: AdminUserDetailProps) => {
151
175
  );
152
176
  const identities = identitiesQuery.data?.content ?? [];
153
177
 
178
+ const realmQuery = useQuery(
179
+ {
180
+ // The realm config query param is `realmName`; the admin endpoints
181
+ // spell the same thing `userRealmName`.
182
+ handler: ({ signal }) =>
183
+ realmClient.getRealmConfig(
184
+ { query: { realmName: props.userRealmName } },
185
+ { request: { signal } },
186
+ ),
187
+ // Realm settings only shape which profile fields are offered — a
188
+ // failure must not block the page. `profilePolicy` degrades to
189
+ // "everything optional" without them.
190
+ onError: () => {},
191
+ },
192
+ [realmClient, props.userRealmName],
193
+ );
194
+
195
+ // What the realm collects decides what this form offers and demands.
196
+ // Hardcoding "email is required" here made every save fail — a role change
197
+ // included — on a realm that signs users in by username alone.
198
+ const policy = profilePolicy(realmQuery.data?.settings, user);
199
+
154
200
  // -- Profile form ---------------------------------------------------------
155
201
 
202
+ const issueMessage = (issue: ProfileIssue): string => {
203
+ if (issue.field === "username") {
204
+ return issue.reason === "required"
205
+ ? tr("admin.userDetail.usernameRequired", {
206
+ default: "Username is required",
207
+ })
208
+ : tr("admin.userDetail.usernameCannotBeCleared", {
209
+ default: "Username cannot be removed once set",
210
+ });
211
+ }
212
+ return issue.reason === "required"
213
+ ? tr("admin.userDetail.emailRequired", {
214
+ default: "Email is required",
215
+ })
216
+ : tr("admin.userDetail.emailCannotBeCleared", {
217
+ default: "Email cannot be removed once set",
218
+ });
219
+ };
220
+
156
221
  const form = useForm({
157
222
  schema: profileSchema,
158
223
  initialValues: {
@@ -164,39 +229,17 @@ export const AdminUserDetail = (props: AdminUserDetailProps) => {
164
229
  roles: user?.roles ?? [],
165
230
  },
166
231
  handler: async (values: ProfileForm) => {
167
- // Required-field guards (kept in handler, not in schema, so
168
- // useForm's initial-decode doesn't crash on the empty mount).
169
- const username = (values.username ?? "").trim();
170
- const email = (values.email ?? "").trim();
171
- if (!username) {
232
+ // Field guards live in the handler, not in the schema, so useForm's
233
+ // initial decode doesn't crash on the empty mount.
234
+ const issue = profileIssues(values, policy, user)[0];
235
+ if (issue) {
172
236
  throw new FormValidationError({
173
- message: tr("admin.userDetail.usernameRequired", {
174
- default: "Username is required",
175
- }),
176
- path: "/username",
177
- });
178
- }
179
- if (!email) {
180
- throw new FormValidationError({
181
- message: tr("admin.userDetail.emailRequired", {
182
- default: "Email is required",
183
- }),
184
- path: "/email",
237
+ message: issueMessage(issue),
238
+ path: `/${issue.field}`,
185
239
  });
186
240
  }
187
241
 
188
- // Changing the email invalidates the verified flag — server-side
189
- // enforcement is also recommended, but mirror it client-side so
190
- // the UI is immediately consistent.
191
- const emailChanged = user && email !== (user.email ?? "");
192
- const body: UpdateUser = {
193
- username,
194
- email,
195
- firstName: (values.firstName ?? "").trim(),
196
- lastName: (values.lastName ?? "").trim(),
197
- roles: values.roles ?? [],
198
- emailVerified: emailChanged ? false : Boolean(values.emailVerified),
199
- };
242
+ const body = profileUpdateBody(values, policy, user);
200
243
 
201
244
  try {
202
245
  await userClient.updateUser({
@@ -567,6 +610,7 @@ export const AdminUserDetail = (props: AdminUserDetailProps) => {
567
610
  <AdminUserDetailOverviewTab
568
611
  form={form}
569
612
  availableRoles={availableRoles}
613
+ policy={policy}
570
614
  />
571
615
  )}
572
616
 
@@ -5,6 +5,7 @@ void React;
5
5
  import { Control } from "@alepha/ui/components/control/control";
6
6
  import type { useFieldValue } from "alepha/react/form";
7
7
  import { useI18n } from "alepha/react/i18n";
8
+ import { CircleDot } from "lucide-react";
8
9
 
9
10
  export interface AdminUsersStatusFilterProps {
10
11
  input: Parameters<typeof useFieldValue>[0];
@@ -24,6 +25,7 @@ export const AdminUsersStatusFilter = (props: AdminUsersStatusFilterProps) => {
24
25
  input={props.input}
25
26
  label=""
26
27
  clearable
28
+ icon={CircleDot}
27
29
  clearLabel={String(
28
30
  tr("admin.users.statusAll", { default: "All status" }),
29
31
  )}
@@ -0,0 +1,277 @@
1
+ import { WorkflowStatusBadge } from "@alepha/ui/components/admin/admin-workflows-status-badge";
2
+ import { useConfirmedAction } from "@alepha/ui/components/admin/use-confirmed-action";
3
+ import { Button } from "@alepha/ui/components/ui/button";
4
+ import {
5
+ Sheet,
6
+ SheetContent,
7
+ SheetDescription,
8
+ SheetHeader,
9
+ SheetTitle,
10
+ } from "@alepha/ui/components/ui/sheet";
11
+ import type { AdminWorkflowController } from "alepha/api/workflows";
12
+ import { useClient, useQuery } from "alepha/react";
13
+ import { useI18n } from "alepha/react/i18n";
14
+ import { Ban, Play, RotateCcw, Undo2 } from "lucide-react";
15
+ import { useState } from "react";
16
+
17
+ export interface WorkflowExecutionSheetProps {
18
+ executionId: string | null;
19
+ onClose: () => void;
20
+ }
21
+
22
+ /**
23
+ * Detail sheet for one workflow execution: status, admin actions gated by
24
+ * the server-computed `can`, and the step timeline with per-step attempts,
25
+ * durations, errors and results.
26
+ */
27
+ export const WorkflowExecutionSheet = (props: WorkflowExecutionSheetProps) => {
28
+ const client = useClient<AdminWorkflowController>();
29
+ const { l, tr } = useI18n();
30
+ const [refreshKey, setRefreshKey] = useState(0);
31
+
32
+ const { data: detail } = useQuery(
33
+ {
34
+ handler: ({ signal }) =>
35
+ props.executionId
36
+ ? client.getWorkflowExecution(
37
+ { params: { id: props.executionId } },
38
+ { request: { signal } },
39
+ )
40
+ : Promise.resolve(null),
41
+ onError: () => {},
42
+ },
43
+ [client, props.executionId, refreshKey],
44
+ );
45
+
46
+ const refresh = () => setRefreshKey((k) => k + 1);
47
+
48
+ const retry = useConfirmedAction<[string]>(
49
+ {
50
+ confirm: {
51
+ title: tr("admin.workflows.retryTitle", { default: "Retry workflow" }),
52
+ description: tr("admin.workflows.retryConfirm", {
53
+ default: "Resume this execution from its failed step?",
54
+ }),
55
+ },
56
+ handler: async (id) => {
57
+ await client.retryWorkflowExecution({ params: { id } });
58
+ refresh();
59
+ },
60
+ success: tr("admin.workflows.retried", { default: "Workflow resumed" }),
61
+ },
62
+ [client, tr],
63
+ );
64
+
65
+ const cancel = useConfirmedAction<[string]>(
66
+ {
67
+ confirm: {
68
+ title: tr("admin.workflows.cancelTitle", {
69
+ default: "Cancel workflow",
70
+ }),
71
+ description: tr("admin.workflows.cancelConfirm", {
72
+ default: "Stop this execution? Remaining steps will not run.",
73
+ }),
74
+ destructive: true,
75
+ },
76
+ handler: async (id) => {
77
+ await client.cancelWorkflowExecution({ params: { id } });
78
+ refresh();
79
+ },
80
+ success: tr("admin.workflows.cancelled", {
81
+ default: "Workflow cancelled",
82
+ }),
83
+ },
84
+ [client, tr],
85
+ );
86
+
87
+ const compensate = useConfirmedAction<[string]>(
88
+ {
89
+ confirm: {
90
+ title: tr("admin.workflows.compensateTitle", {
91
+ default: "Compensate workflow",
92
+ }),
93
+ description: tr("admin.workflows.compensateConfirm", {
94
+ default:
95
+ "Run the compensation functions of every completed step, in reverse order?",
96
+ }),
97
+ destructive: true,
98
+ },
99
+ handler: async (id) => {
100
+ await client.compensateWorkflowExecution({ params: { id } });
101
+ refresh();
102
+ },
103
+ success: tr("admin.workflows.compensated", {
104
+ default: "Compensation started",
105
+ }),
106
+ },
107
+ [client, tr],
108
+ );
109
+
110
+ const restart = useConfirmedAction<[string]>(
111
+ {
112
+ confirm: {
113
+ title: tr("admin.workflows.restartTitle", {
114
+ default: "Restart workflow",
115
+ }),
116
+ description: tr("admin.workflows.restartConfirm", {
117
+ default: "Start a new execution with the same payload?",
118
+ }),
119
+ },
120
+ handler: async (id) => {
121
+ await client.restartWorkflowExecution({ params: { id } });
122
+ refresh();
123
+ },
124
+ success: tr("admin.workflows.restarted", {
125
+ default: "Workflow restarted",
126
+ }),
127
+ },
128
+ [client, tr],
129
+ );
130
+
131
+ return (
132
+ <Sheet
133
+ open={props.executionId !== null}
134
+ onOpenChange={(open) => {
135
+ if (!open) props.onClose();
136
+ }}
137
+ >
138
+ <SheetContent
139
+ side="right"
140
+ className="flex w-full flex-col gap-0 data-[side=right]:sm:max-w-[42vw]"
141
+ >
142
+ {detail && (
143
+ <>
144
+ <SheetHeader>
145
+ <SheetTitle className="flex items-center gap-2">
146
+ <span className="truncate">{detail.workflowName}</span>
147
+ <WorkflowStatusBadge status={detail.status} />
148
+ </SheetTitle>
149
+ <SheetDescription className="font-mono text-xs">
150
+ {detail.id}
151
+ </SheetDescription>
152
+ </SheetHeader>
153
+
154
+ <div className="flex flex-wrap items-center gap-2 px-4 pb-2">
155
+ {detail.can.retry && (
156
+ <Button size="sm" onClick={() => retry.run(detail.id)}>
157
+ <Play />
158
+ {tr("admin.workflows.retry", { default: "Retry" })}
159
+ </Button>
160
+ )}
161
+ {detail.can.restart && (
162
+ <Button
163
+ size="sm"
164
+ variant="outline"
165
+ onClick={() => restart.run(detail.id)}
166
+ >
167
+ <RotateCcw />
168
+ {tr("admin.workflows.restart", { default: "Restart" })}
169
+ </Button>
170
+ )}
171
+ {detail.can.compensate && (
172
+ <Button
173
+ size="sm"
174
+ variant="outline"
175
+ onClick={() => compensate.run(detail.id)}
176
+ >
177
+ <Undo2 />
178
+ {tr("admin.workflows.compensate", { default: "Compensate" })}
179
+ </Button>
180
+ )}
181
+ {detail.can.cancel && (
182
+ <Button
183
+ size="sm"
184
+ variant="destructive"
185
+ onClick={() => cancel.run(detail.id)}
186
+ >
187
+ <Ban />
188
+ {tr("admin.workflows.cancel", { default: "Cancel" })}
189
+ </Button>
190
+ )}
191
+ </div>
192
+
193
+ {detail.error && (
194
+ <div className="text-destructive mx-4 mb-2 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs">
195
+ <span className="font-medium">
196
+ {detail.errorStep ? `${detail.errorStep}: ` : null}
197
+ </span>
198
+ {detail.error}
199
+ </div>
200
+ )}
201
+
202
+ <div className="min-h-0 flex-1 overflow-y-auto px-4 pb-4">
203
+ <ol className="flex flex-col gap-2">
204
+ {detail.steps.map((step) => (
205
+ <WorkflowExecutionSheetStep key={step.id} step={step} l={l} />
206
+ ))}
207
+ </ol>
208
+ </div>
209
+ </>
210
+ )}
211
+ </SheetContent>
212
+ </Sheet>
213
+ );
214
+ };
215
+
216
+ interface WorkflowExecutionSheetStepProps {
217
+ step: {
218
+ id: string;
219
+ stepName: string;
220
+ stepIndex: number;
221
+ status: string;
222
+ attempt: number;
223
+ maxAttempts: number;
224
+ iteration?: number;
225
+ error?: string;
226
+ result?: Record<string, unknown>;
227
+ startedAt?: string;
228
+ completedAt?: string;
229
+ scheduledAt?: string;
230
+ };
231
+ l: ReturnType<typeof useI18n>["l"];
232
+ }
233
+
234
+ const WorkflowExecutionSheetStep = (props: WorkflowExecutionSheetStepProps) => {
235
+ const { step, l } = props;
236
+ const durationMs =
237
+ step.startedAt && step.completedAt
238
+ ? new Date(step.completedAt).getTime() -
239
+ new Date(step.startedAt).getTime()
240
+ : null;
241
+
242
+ return (
243
+ <li className="rounded-md border px-3 py-2">
244
+ <div className="flex items-center gap-2">
245
+ <span className="text-muted-foreground w-5 text-right font-mono text-xs">
246
+ {step.stepIndex + 1}
247
+ </span>
248
+ <span className="truncate text-sm font-medium">{step.stepName}</span>
249
+ <WorkflowStatusBadge status={step.status} />
250
+ <span className="text-muted-foreground ml-auto text-xs">
251
+ {step.iteration && step.iteration > 0
252
+ ? `×${step.iteration + 1} `
253
+ : null}
254
+ {step.attempt > 0 ? `${step.attempt}/${step.maxAttempts}` : null}
255
+ {durationMs !== null
256
+ ? ` · ${durationMs < 1000 ? `${durationMs} ms` : `${(durationMs / 1000).toFixed(1)} s`}`
257
+ : null}
258
+ </span>
259
+ </div>
260
+ {step.status === "pending" && step.scheduledAt && (
261
+ <div className="text-muted-foreground mt-1 pl-7 text-xs">
262
+ {String(l(step.scheduledAt, { date: "fromNow" }))}
263
+ </div>
264
+ )}
265
+ {step.error && (
266
+ <div className="text-destructive mt-1 pl-7 text-xs" title={step.error}>
267
+ {step.error}
268
+ </div>
269
+ )}
270
+ {step.result && (
271
+ <pre className="text-muted-foreground mt-1 max-h-32 overflow-auto rounded bg-muted/50 p-2 pl-2 text-[11px] leading-snug">
272
+ {JSON.stringify(step.result, null, 2)}
273
+ </pre>
274
+ )}
275
+ </li>
276
+ );
277
+ };