|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * The Automations pillar's flow rail helpers: the runtime and rail states, the |
| 5 | + * status dot and its glyph tables, the flow, definition and object-label reads, |
| 6 | + * the new-flow trigger helpers, `pairIdOf` and the copied-flow arrival reader, |
| 7 | + * moved out of `StudioDesignSurface.tsx` unchanged by objectstack#29988 (slice 4 |
| 8 | + * of the move-only split). |
| 9 | + */ |
| 10 | + |
| 11 | +import * as React from 'react'; |
| 12 | +import type { MetadataClient } from '@object-ui/data-objectstack'; |
| 13 | +import type { FlowRuntimeState as SpecFlowRuntimeState } from '@objectstack/spec/contracts'; |
| 14 | +import { resolveI18nLabel, type I18nLabel } from '@objectstack/spec/ui'; |
| 15 | +import { customizationPackageId } from '@objectstack/spec/kernel'; |
| 16 | +import type { FlowTriggerGlyph } from './flowGrouping.js'; |
| 17 | +import { |
| 18 | + Zap, |
| 19 | + Clock, |
| 20 | + MousePointerClick, |
| 21 | + CornerDownRight, |
| 22 | + type LucideIcon, |
| 23 | +} from 'lucide-react'; |
| 24 | +import { |
| 25 | + fieldsForNodeType, |
| 26 | + localizeFlowFields, |
| 27 | + type FlowConfigField, |
| 28 | +} from '../metadata-admin/inspectors/flow-node-config.js'; |
| 29 | +import { |
| 30 | + deriveFlowRunStatus, |
| 31 | + describeFlowRunStatus, |
| 32 | + type FlowRunStatus, |
| 33 | + type FlowRunStatusView, |
| 34 | + type FlowRuntimeRow, |
| 35 | +} from '../metadata-admin/previews/flow-problems.js'; |
| 36 | +import type { FlowRegistration } from '@objectstack/spec/api'; |
| 37 | + |
| 38 | +/** |
| 39 | + * One flow's runtime enable/bound state, as `GET /automation/_status` puts it on |
| 40 | + * the wire — the same report `IAutomationService.getFlowRuntimeStates` produces, |
| 41 | + * so the shape is the spec's and is TAKEN from it rather than restated |
| 42 | + * (objectui#7265; this used to be a module-local copy under the spec's own name, |
| 43 | + * already three keys behind it). |
| 44 | + * |
| 45 | + * `Partial<>` is the one deliberate divergence, and it is about the READER, not |
| 46 | + * the contract: this types a JSON body that has not been validated and may come |
| 47 | + * from an older backend that sends neither `enabled` nor `bound` — the effect |
| 48 | + * hard-codes the degraded case (`if (!res.ok) return`, "dots just don't |
| 49 | + * render"). Every member is therefore optional HERE while the contract keeps |
| 50 | + * `name` / `enabled` / `bound` required, and the reads below narrow each one |
| 51 | + * explicitly (`if (s?.name)`, then `s.enabled !== false`, `!!s.bound` and the |
| 52 | + * two string checks in `flowRailState`) instead of trusting the type. Pinned in |
| 53 | + * `spec-symbol-parity.test.ts`: if the spec ever |
| 54 | + * relaxes those three itself, the pin fails and this alias should collapse to a |
| 55 | + * plain re-export. |
| 56 | + */ |
| 57 | +export type FlowRuntimeState = Partial<SpecFlowRuntimeState>; |
| 58 | + |
| 59 | +/** |
| 60 | + * What the Automations rail keeps from one flow's runtime row (objectui#11281). |
| 61 | + * |
| 62 | + * `bound` alone cannot say why an enabled flow is unbound. The contract's |
| 63 | + * `FlowRuntimeState.bound` is false both for a flow that declares no trigger |
| 64 | + * and for one whose declared trigger the engine has not armed, and "`triggerType` |
| 65 | + * distinguishes the two". `reason` is the platform's one sentence for why such a |
| 66 | + * flow is not armed: a deployment policy and a binding failure each arrive in |
| 67 | + * the platform's own words. So the rail keeps both beside `enabled` / `bound`. |
| 68 | + * |
| 69 | + * The shape is `flow-problems`' `FlowRuntimeRow` (objectui#11779): the rail, |
| 70 | + * the flow header and the Problems panel derive one run status from it |
| 71 | + * (`deriveFlowRunStatus`), so it is declared once, where that derivation is. |
| 72 | + * |
| 73 | + * `unboundCause` is the one member kept beside it, for the ledger switch on a |
| 74 | + * read-only package's flow (ADR-0146 D4): `activationReading` reads it for its |
| 75 | + * presence, the same reading Setup › Packaged automation shows. |
| 76 | + */ |
| 77 | +export type FlowRailState = FlowRuntimeRow & { unboundCause?: string }; |
| 78 | + |
| 79 | +/** |
| 80 | + * Narrow one unvalidated runtime row into the rail's state. `triggerType`, |
| 81 | + * `reason` and `unboundCause` are kept only as non-empty strings and are |
| 82 | + * otherwise absent, the way the engine omits them, so a row without them, and |
| 83 | + * every older backend, reads exactly as it did before they existed. |
| 84 | + */ |
| 85 | +export function flowRailState(s: FlowRuntimeState): FlowRailState { |
| 86 | + const { triggerType, reason, unboundCause } = s; |
| 87 | + return { |
| 88 | + enabled: s.enabled !== false, |
| 89 | + bound: !!s.bound, |
| 90 | + ...(typeof triggerType === 'string' && triggerType.length > 0 ? { triggerType } : {}), |
| 91 | + ...(typeof reason === 'string' && reason.length > 0 ? { reason } : {}), |
| 92 | + ...(typeof unboundCause === 'string' && unboundCause.length > 0 ? { unboundCause } : {}), |
| 93 | + }; |
| 94 | +} |
| 95 | + |
| 96 | +/** |
| 97 | + * A flow's live status in the Automations rail, from the engine's runtime state |
| 98 | + * (persisted `status` is intent; this is what's actually live). Renders nothing |
| 99 | + * for a flow the engine doesn't know yet (never published) — the amber |
| 100 | + * "unpublished draft" chip already covers that case. |
| 101 | + * |
| 102 | + * objectui#12349 — and from the engine's registration verdict, which the flow |
| 103 | + * list serves beside its items. A flow the engine REFUSED has no runtime row, |
| 104 | + * so it used to render nothing here; it now reads "Refused by the engine", |
| 105 | + * titled with the engine's `reason.message`, as sent and never parsed. An |
| 106 | + * `unregistered` flow reads "Not running here". A `registered` verdict, and |
| 107 | + * none at all, leave the row's reading below. |
| 108 | + * |
| 109 | + * The state is the run status `deriveFlowRunStatus` derives, worded by |
| 110 | + * `describeFlowRunStatus` — the derivation the flow header's Status pill and the |
| 111 | + * Problems panel read too (objectui#11779), so the three cannot disagree: |
| 112 | + * - enabled and bound, or enabled with no declared trigger: "On", titled |
| 113 | + * "bound to its trigger" / "no trigger (run manually)" — a flow that runs |
| 114 | + * when invoked is never called "not running"; |
| 115 | + * - enabled, with a declared trigger the engine has not armed: "Not running |
| 116 | + * here". Its title is the platform's `reason`, verbatim (objectui#11281), |
| 117 | + * or, from a backend that predates the field, the contract's own reading of |
| 118 | + * the row: its trigger is not armed here; |
| 119 | + * - disabled: "Off". |
| 120 | + * |
| 121 | + * objectui#12454 — drawn as a 6 px dot, as the redesign's rail draws it: green |
| 122 | + * for On, grey for Not running here, amber for Refused, a hollow ring for Off |
| 123 | + * (`flowDotClass`). The words are the element's visually hidden text and the |
| 124 | + * row's title (the dot no longer prints them), and the dot's own title is the |
| 125 | + * reason it always carried. The rail's legend names each look. |
| 126 | + * Nothing here is styled as an error: a deployment policy is not a defect. |
| 127 | + */ |
| 128 | +export function FlowStatusDot({ |
| 129 | + state, |
| 130 | + registration, |
| 131 | + locale, |
| 132 | +}: { |
| 133 | + state?: FlowRailState; |
| 134 | + /** The engine's verdict on this flow, from the list's `registrations`; absent when none was served. */ |
| 135 | + registration?: FlowRegistration; |
| 136 | + locale: string; |
| 137 | +}): React.ReactElement | null { |
| 138 | + const reading = flowRailStatus(state, registration, locale); |
| 139 | + if (!reading) return null; |
| 140 | + const { status, view } = reading; |
| 141 | + // objectui#12454 — a 6 px dot; the status words stay the element's text |
| 142 | + // (visually hidden, so a reader and a search still find them) and the hover |
| 143 | + // text stays the reason as it was. |
| 144 | + return ( |
| 145 | + <span title={view.title} data-status={status.kind} className="inline-flex h-4 w-3 shrink-0 items-center justify-center"> |
| 146 | + <span aria-hidden className={'h-1.5 w-1.5 rounded-full ' + flowDotClass(status)} /> |
| 147 | + <span className="sr-only">{view.label}</span> |
| 148 | + </span> |
| 149 | + ); |
| 150 | +} |
| 151 | + |
| 152 | +/** |
| 153 | + * The rail's reading of one flow: the run status `FlowStatusDot` draws and the |
| 154 | + * row's title names, or `null` when there is nothing to say — a flow the engine |
| 155 | + * does not know yet and holds no verdict on (the amber "unpublished draft" chip |
| 156 | + * already covers that case). |
| 157 | + */ |
| 158 | +export function flowRailStatus( |
| 159 | + state: FlowRailState | undefined, |
| 160 | + registration: FlowRegistration | undefined, |
| 161 | + locale: string, |
| 162 | +): { status: FlowRunStatus; view: FlowRunStatusView } | null { |
| 163 | + const decides = registration?.state === 'refused' || registration?.state === 'unregistered'; |
| 164 | + if (!state && !decides) return null; |
| 165 | + const status = deriveFlowRunStatus(state, undefined, registration); |
| 166 | + return { status, view: describeFlowRunStatus(status, locale) }; |
| 167 | +} |
| 168 | + |
| 169 | +/** |
| 170 | + * The dot's look per run status (objectui#12454): green when the flow runs |
| 171 | + * (bound, or run by hand), grey when this deployment does not run it, amber |
| 172 | + * when the engine refused it, and a hollow ring when it is switched off. |
| 173 | + * Nothing here is styled as an error: a deployment policy is not a defect. |
| 174 | + */ |
| 175 | +export function flowDotClass(status: FlowRunStatus): string { |
| 176 | + switch (status.kind) { |
| 177 | + case 'on': |
| 178 | + case 'manual': |
| 179 | + return 'bg-emerald-500'; |
| 180 | + case 'refused': |
| 181 | + return 'bg-amber-500'; |
| 182 | + case 'off': |
| 183 | + return 'border border-muted-foreground/70'; |
| 184 | + default: |
| 185 | + return 'bg-muted-foreground/50'; |
| 186 | + } |
| 187 | +} |
| 188 | + |
| 189 | +/** Each trigger kind's 14 px glyph and its words, in the rail rows and the legend (objectui#12454). */ |
| 190 | +export const FLOW_GLYPH_ICON: Record<FlowTriggerGlyph, LucideIcon> = { |
| 191 | + record: Zap, |
| 192 | + scheduled: Clock, |
| 193 | + screen: MousePointerClick, |
| 194 | + autolaunched: CornerDownRight, |
| 195 | +}; |
| 196 | +export const FLOW_GLYPH_LABEL_KEY: Record<FlowTriggerGlyph, string> = { |
| 197 | + record: 'engine.studio.auto.kind.record', |
| 198 | + scheduled: 'engine.studio.auto.kind.scheduled', |
| 199 | + screen: 'engine.studio.auto.kind.screen', |
| 200 | + autolaunched: 'engine.studio.auto.kind.autolaunched', |
| 201 | +}; |
| 202 | + |
| 203 | +/** The React key of the trailing group, whose grouping key is the empty string. */ |
| 204 | +export const NO_OBJECT_GROUP_KEY = '__no_object__'; |
| 205 | + |
| 206 | +/** |
| 207 | + * The engine's registration verdict on each flow of the rail's scope |
| 208 | + * (objectui#12349): the flow list's `registrations`, which the server serves |
| 209 | + * beside the items, read through the same list read the rail's own loader |
| 210 | + * makes (one request when both are in flight). Every entry is parsed with the |
| 211 | + * spec's `FlowRegistrationSchema` at the client. |
| 212 | + * |
| 213 | + * A read that fails leaves every flow unjudged — what an absent |
| 214 | + * `registrations` already means — so the rail reads as it did before the |
| 215 | + * verdict existed; the rail's own list read reports a failing list. |
| 216 | + */ |
| 217 | +export async function readFlowRegistrations( |
| 218 | + client: { listResponse: MetadataClient['listResponse'] }, |
| 219 | + packageId: string | null, |
| 220 | +): Promise<Record<string, FlowRegistration>> { |
| 221 | + try { |
| 222 | + const answer = await client.listResponse('flow', packageId === null ? {} : { packageId }); |
| 223 | + return answer.registrations ?? {}; |
| 224 | + } catch { |
| 225 | + return {}; |
| 226 | + } |
| 227 | +} |
| 228 | + |
| 229 | +/** |
| 230 | + * Each flow's definition in the rail's scope, by name (objectui#12454): what |
| 231 | + * the rail's grouping and trigger glyphs read. Read with the drafts overlaid, |
| 232 | + * so a draft-only flow, and a published one whose draft moved its trigger, |
| 233 | + * group as the author's draft has them; a server that refuses that read gives |
| 234 | + * the published list, and a failing list gives none, which groups every flow |
| 235 | + * under "No object" rather than failing the rail. |
| 236 | + */ |
| 237 | +export async function readFlowDefinitions(client: MetadataClient, packageId: string | null): Promise<Map<string, unknown>> { |
| 238 | + const scope = packageId === null ? {} : { packageId }; |
| 239 | + const read = async (): Promise<Array<Record<string, unknown>> | null | undefined> => { |
| 240 | + try { |
| 241 | + return await client.withPreviewDrafts(true).list<Record<string, unknown>>('flow', scope); |
| 242 | + } catch { |
| 243 | + return await client.list<Record<string, unknown>>('flow', scope); |
| 244 | + } |
| 245 | + }; |
| 246 | + const definitions = new Map<string, unknown>(); |
| 247 | + try { |
| 248 | + for (const flow of (await read()) ?? []) { |
| 249 | + if (flow && typeof flow.name === 'string' && flow.name) definitions.set(flow.name, flow); |
| 250 | + } |
| 251 | + } catch { |
| 252 | + /* no definitions: every flow groups under "No object" */ |
| 253 | + } |
| 254 | + return definitions; |
| 255 | +} |
| 256 | + |
| 257 | +/** |
| 258 | + * The scope's objects, name → label in the designer locale (objectui#12454): |
| 259 | + * the rail's group headers and their order, and which objects count as the |
| 260 | + * scope's own when a flow is grouped by the data it touches. The package's |
| 261 | + * object list, as the Data rail reads it; unscoped in the package-less scope. |
| 262 | + * A failing read gives an empty index, which `groupFlowsByObject` reads as |
| 263 | + * "every object is the scope's". |
| 264 | + */ |
| 265 | +export async function readObjectLabels(client: MetadataClient, packageId: string | null, locale: string): Promise<Map<string, string>> { |
| 266 | + const labels = new Map<string, string>(); |
| 267 | + try { |
| 268 | + // The package's pending object drafts too, as the Data rail lists them: a |
| 269 | + // flow on an object not published yet is grouped under it, and the header |
| 270 | + // reads its label (the `_drafts` row carries one), not its name. A |
| 271 | + // published object keeps its published label; a failed draft read adds |
| 272 | + // none and leaves the published index whole (an async function, so even |
| 273 | + // a throw before the read is sent rejects into the catch). |
| 274 | + const readDrafts = async (): Promise<Array<{ name?: string | null; label?: I18nLabel | null }>> => |
| 275 | + (await client.listDrafts(packageId === null ? { type: 'object' } : { packageId, type: 'object' })) ?? []; |
| 276 | + const [objects, drafts] = await Promise.all([ |
| 277 | + client.list<Record<string, unknown>>('object', packageId === null ? {} : { packageId }), |
| 278 | + readDrafts().catch(() => []), |
| 279 | + ]); |
| 280 | + for (const object of objects ?? []) { |
| 281 | + if (!object || typeof object.name !== 'string' || !object.name) continue; |
| 282 | + const label = resolveI18nLabel(object.label as I18nLabel | undefined, locale)?.trim(); |
| 283 | + labels.set(object.name, label || object.name); |
| 284 | + } |
| 285 | + for (const draft of drafts) { |
| 286 | + if (!draft || typeof draft.name !== 'string' || !draft.name || labels.has(draft.name)) continue; |
| 287 | + labels.set(draft.name, resolveI18nLabel(draft.label ?? undefined, locale)?.trim() || draft.name); |
| 288 | + } |
| 289 | + } catch { |
| 290 | + /* an empty index */ |
| 291 | + } |
| 292 | + return labels; |
| 293 | +} |
| 294 | + |
| 295 | +/** The trigger the New automation dialog chose (objectui#11788). */ |
| 296 | +export interface NewFlowTrigger { |
| 297 | + triggerType: string; |
| 298 | + /** The object a record trigger watches, when the author named one. */ |
| 299 | + objectName?: string; |
| 300 | +} |
| 301 | + |
| 302 | +/** |
| 303 | + * The Start node's own trigger and object fields, localized — the source of the |
| 304 | + * New automation dialog's choices (objectui#11788), so the dialog offers what |
| 305 | + * the Start node offers, under the same labels, and shows the object picker for |
| 306 | + * exactly the triggers the Start node shows it for (`objectName`'s `showWhen`). |
| 307 | + */ |
| 308 | +export function newFlowTriggerFields(locale: string): { trigger?: FlowConfigField; object?: FlowConfigField } { |
| 309 | + const start = localizeFlowFields('start', fieldsForNodeType('start'), locale); |
| 310 | + return { |
| 311 | + trigger: start.find((f) => f.id === 'triggerType'), |
| 312 | + object: start.find((f) => f.id === 'objectName'), |
| 313 | + }; |
| 314 | +} |
| 315 | + |
| 316 | +/** |
| 317 | + * `flow` with the chosen trigger written on its Start node, where the Start |
| 318 | + * node's trigger field writes it (`config.triggerType`, and `config.objectName` |
| 319 | + * for the object) — objectui#11788. No choice leaves the skeleton as it was. |
| 320 | + */ |
| 321 | +export function withStartTrigger( |
| 322 | + flow: Record<string, unknown>, |
| 323 | + trigger: NewFlowTrigger | null, |
| 324 | +): Record<string, unknown> { |
| 325 | + if (!trigger) return flow; |
| 326 | + const nodes = Array.isArray(flow.nodes) ? (flow.nodes as Array<Record<string, unknown>>) : []; |
| 327 | + return { |
| 328 | + ...flow, |
| 329 | + nodes: nodes.map((n) => { |
| 330 | + if (n.type !== 'start') return n; |
| 331 | + const config = n.config && typeof n.config === 'object' && !Array.isArray(n.config) ? (n.config as Record<string, unknown>) : {}; |
| 332 | + return { |
| 333 | + ...n, |
| 334 | + config: { |
| 335 | + ...config, |
| 336 | + triggerType: trigger.triggerType, |
| 337 | + ...(trigger.objectName ? { objectName: trigger.objectName } : {}), |
| 338 | + }, |
| 339 | + }; |
| 340 | + }), |
| 341 | + }; |
| 342 | +} |
| 343 | + |
| 344 | +/** No navigation order: one shared empty list, so the rail's memo holds across renders. */ |
| 345 | +export const NO_OBJECT_ORDER: readonly string[] = []; |
| 346 | + |
| 347 | +/** |
| 348 | + * objectstack#28567 — what the Automations pillar's "New similar" strip says: |
| 349 | + * the copy the clone door saved, shown on that copy in the package the answer |
| 350 | + * named, or an answer that named no package (nothing opened). `notice` is the |
| 351 | + * door's sentence, and `noticeCode` the code it names it by (objectstack#29727): |
| 352 | + * shown in the console's language for a known code, as sent otherwise. |
| 353 | + */ |
| 354 | +export type FlowCopiedStrip = |
| 355 | + | { kind: 'landed'; name: string; packageId: string; notice: string; noticeCode?: string } |
| 356 | + | { kind: 'noPackage'; name: string; notice: string; noticeCode?: string }; |
| 357 | + |
| 358 | +/** The navigation-state key the copy's landing rides to the copy's pillar on. */ |
| 359 | +export const FLOW_COPIED_ARRIVAL_STATE = 'flowNewSimilar'; |
| 360 | + |
| 361 | +/** |
| 362 | + * The landing a "New similar" navigation carried, kept only when it names |
| 363 | + * THIS package, so a stale history entry of another package shows nothing. |
| 364 | + */ |
| 365 | +/** objectstack#28572 — `base`'s paired customization package id by the spec's pairing rule, or `null`. For READS only. */ |
| 366 | +export function pairIdOf(base: string): string | null { |
| 367 | + const pair = customizationPackageId(base); |
| 368 | + return pair.ok ? pair.value : null; |
| 369 | +} |
| 370 | + |
| 371 | +export function readFlowCopiedArrival(state: unknown, packageId: string | null): FlowCopiedStrip | null { |
| 372 | + const arrival = (state as Record<string, unknown> | null | undefined)?.[FLOW_COPIED_ARRIVAL_STATE] as |
| 373 | + | Partial<Extract<FlowCopiedStrip, { kind: 'landed' }>> |
| 374 | + | undefined; |
| 375 | + if (!arrival || arrival.kind !== 'landed' || packageId === null || arrival.packageId !== packageId) return null; |
| 376 | + if (typeof arrival.name !== 'string' || arrival.name === '') return null; |
| 377 | + return { |
| 378 | + kind: 'landed', |
| 379 | + name: arrival.name, |
| 380 | + packageId, |
| 381 | + notice: typeof arrival.notice === 'string' ? arrival.notice : '', |
| 382 | + ...(typeof arrival.noticeCode === 'string' ? { noticeCode: arrival.noticeCode } : {}), |
| 383 | + }; |
| 384 | +} |
0 commit comments