diff --git a/.changeset/35863-decided-route-outcome.md b/.changeset/35863-decided-route-outcome.md new file mode 100644 index 00000000000..a58af72e7e7 --- /dev/null +++ b/.changeset/35863-decided-route-outcome.md @@ -0,0 +1,24 @@ +--- +'@objectstack/spec': patch +'@objectstack/plugin-approvals': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +'@object-ui/console': patch +--- + +feat(approvals): a decided request's step line says where the record's approval went next: on to a later step, or ended + +Clause-②: yes +Metadata-protocol: none + +The single approval request read (`GET /api/v1/approvals/requests/ID`) serves one more fact on a decided request's own route: `flow_route.outcome`, beside `ahead: 'decided'`. Before, a decided route stopped at the request's own step, so an approver reopening a request they had decided could not tell whether the record's approval went on to a later step or ended. + +- `outcome.step` is the run's latest request when it is a later one than this request (a request of the same flow run opened after it, on any node, a later round of the same node included; a pending one wins over a decided one). It is absent when no later request was opened in that run; a request a child run opened is not among them. +- `outcome.status` is that latest request's status, or this request's own when `step` is absent. `pending` with a `step` means the approval went on to that step and waits on its decision. +- `outcome.ended` is `true` only when the record's approval is known to have stopped: the request's run is a root run (not a `subflow` body or a `map` item, whose end is not the approval's), the flow body the run ran holds no `subflow` or `map` node anywhere, regions included (a child run files its requests under its own run, so this run's requests cannot show what it decided, before or after this request), and the run reports it stopped for good, with the same terminal set the dead-run sweep uses. The body the run ran is known only when the body armed now is the flow's newest registration and was registered before the run started, so a flow edited, rolled back or re-registered after a run started is never judged by its current body for that run. `false` means not known to have stopped: the run goes on, is a child run, ran a body that can start a child run, ran a body that is not known, cannot be read, or was opened before this release (the approval node now records on each new request whether its run is a root run). + +`outcome` is absent when nothing past the request is known: no later request was opened and the approval is not known to have ended, or several later requests are pending at once (parallel steps). A pending request's route never carries it. It is served to every reader of the request and says only where the same approval went: the later step's node id and label and that request's status, never the later request's id, approvers, comments or field values. The `ApprovalRequestRow.flow_route` contract type in `@objectstack/spec/contracts` gains the optional member, and `routeOutcome` in `@objectstack/plugin-approvals` is the rule. + +The approval request page (`@object-ui/app-shell`) draws one line under the decided step: "Went on to STEP, waiting for a decision", "Went on to STEP: DECISION", "Went on to STEP, then ended: DECISION", or "The approval ended here". No line is drawn when no outcome is served. `@object-ui/i18n` carries the four new `approvalsInbox` rows in every built-in locale, and the console's request type (`@object-ui/console`) mirrors the new member. + +Nothing to migrate: a caller that does not read `outcome` is unaffected. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index b07bd02a01a..a32d4bbcbaa 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -1199,6 +1199,41 @@ out-edges, a loop back or a `subflow` / `map` / `loop` node, and `ahead` reads `decided` for a request already decided. The older `flow_steps` member is the graph's first branch at every decision, not the route; nothing draws it. +A decided request's route also says where the record's approval stands now, +in `outcome`, so its step line can answer "what happened next": + +```jsonc +// getRequest, for the manager's request after the manager approved: +"flow_route": { + "steps": [{ "id": "manager_review", "label": "Manager", "state": "done" }], + "ahead": "decided", + "outcome": { + "step": { "id": "finance_only", "label": "Finance" }, // the run's latest, later request + "status": "pending", // it waits on its decision + "ended": false // the run goes on + } +} +``` + +`step` is the run's latest request opened after this one (a pending one first), +and is absent when none was opened; `status` is that request's status, or this +request's own without a `step`; `ended` is `true` only when the record's +approval is known to have stopped: the request's run is a root run (an approval +inside a `subflow` or a `map` item runs in a child run, whose end is not the +approval's), the flow body the run ran holds no `subflow` or `map` node +anywhere (a child run files its requests under its own run, so the root run's +requests cannot show what it decided), and the run has stopped for good. The +body the run ran is known only while the flow has not been registered again +since the run started: after an edit, a rollback or a restart, older runs are +not judged by today's body, and their requests are not served "ended". `false` +means not known to have stopped, including a run that cannot be read. So on a +flow that starts a child run, a decided request's line names the later steps of +its own run but never says the approval ended. `outcome` is left out when nothing past +the request is known: no later request and the approval not known to have +ended, or several later requests pending at once. Every reader of the request +gets it; it names only the later step and its status, never that request's +approvers, comments or field values. + Approval **notifications deep-link into the request**: `notify()` rewrites the inbox action URL to `/system/approvals?request=`, so clicking the bell opens that request's drawer directly instead of a generic list. diff --git a/packages/plugins/plugin-approvals/src/approval-node.ts b/packages/plugins/plugin-approvals/src/approval-node.ts index 6b852081006..5809ba7e878 100644 --- a/packages/plugins/plugin-approvals/src/approval-node.ts +++ b/packages/plugins/plugin-approvals/src/approval-node.ts @@ -209,6 +209,12 @@ export function registerApprovalNode( // The node object this run executes: a step naming the platform // administrators opens only when it belongs to the armed body. node, + // [#35863] Whether this run is the record's whole approval run or a + // child of another (a `subflow` body or a `map` item: the engine + // links those upward by `$parentRunId`). A child run's end is not + // the end of the record's approval, so a decided route may say + // "ended" only for a root run's request. + runRoot: !hasParentRun(context), }, { ...SYSTEM_CTX, userId: context?.userId, @@ -256,3 +262,13 @@ export function registerApprovalNode( logger?.info?.('[approvals] approval node executor registered'); } + +/** + * [#35863] Whether `context` is a child run's: the engine starts a `subflow` + * body or a `map` item with the parent's run id as `$parentRunId`. Read the + * way the engine's own readers read it (a non-empty string). + */ +function hasParentRun(context: unknown): boolean { + const parent = (context as { $parentRunId?: unknown } | undefined)?.$parentRunId; + return typeof parent === 'string' && parent !== ''; +} diff --git a/packages/plugins/plugin-approvals/src/approval-route.test.ts b/packages/plugins/plugin-approvals/src/approval-route.test.ts index 082b35c5f48..3f8973f1f4c 100644 --- a/packages/plugins/plugin-approvals/src/approval-route.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-route.test.ts @@ -5,11 +5,14 @@ * the real engine and a real run, is pinned in `flow-route.integration.test.ts`; * these are the cases a real run reaches rarely or slowly: rounds, other runs, * outcomes that are not a pass, and each kind of branch the walk refuses to - * decide. + * decide. [#35863] Then where a decided request's approval stands now + * (`routeOutcome`): what the run's later rows and its end say, and the cases + * where they say nothing; and which flows can start a child run, whose + * requests those rows never hold (`flowHostsChildRuns`). */ import { describe, it, expect } from 'vitest'; -import { flowRoute, passedSteps, stepsAhead, type RouteFlowGraph } from './approval-route.js'; +import { flowHostsChildRuns, flowRoute, passedSteps, routeOutcome, stepsAhead, type RouteFlowGraph } from './approval-route.js'; const label = (id: string) => id.toUpperCase(); const row = (flow_node_id: string, status: string, created_at: string, id = `${flow_node_id}@${created_at}`) => @@ -146,3 +149,101 @@ describe('flowRoute — the whole route', () => { expect(flowRoute({ id: 'x', status: 'pending' }, LINE, runRows, label)).toBeUndefined(); }); }); + +describe('[#35863] routeOutcome — where the record\'s approval stands after a decided request', () => { + const decided = (status: string, created_at = at(2)) => ({ id: `a@${created_at}`, status, created_at }); + + it('a later request pending: the approval went on to that step and waits, whatever the run says', () => { + const rows = [row('a', 'approved', at(2)), row('b', 'pending', at(3))]; + expect(routeOutcome(decided('approved'), rows, false, label)).toEqual({ + step: { id: 'b', label: 'B' }, status: 'pending', ended: false, + }); + }); + + it('the last step decided and the run ended: the approval ended with that step\'s decision', () => { + for (const status of ['approved', 'rejected'] as const) { + const rows = [row('a', 'approved', at(2)), row('b', status, at(3))]; + expect(routeOutcome(decided('approved'), rows, true, label), status).toEqual({ + step: { id: 'b', label: 'B' }, status, ended: true, + }); + } + }); + + it('no later request and the run ended: the approval ended at this request, with its own decision', () => { + for (const status of ['approved', 'rejected', 'recalled', 'cancelled'] as const) { + expect(routeOutcome(decided(status), [row('a', status, at(2))], true, label), status).toEqual({ status, ended: true }); + } + }); + + it('no later request and the run not ended: nothing is known past this request, so no outcome', () => { + expect(routeOutcome(decided('returned'), [row('a', 'returned', at(2))], false, label)).toBeUndefined(); + expect(routeOutcome(decided('approved'), [], false, label)).toBeUndefined(); + }); + + it('a later round of the same node counts: a returned request resubmitted waits at its own step again', () => { + const rows = [row('a', 'returned', at(2)), row('a', 'pending', at(3))]; + expect(routeOutcome(decided('returned'), rows, false, label)).toEqual({ + step: { id: 'a', label: 'A' }, status: 'pending', ended: false, + }); + }); + + it('a pending later request wins over a decided one opened after it; else the latest decided one', () => { + const rows = [row('b', 'pending', at(3)), row('c', 'rejected', at(4))]; + expect(routeOutcome(decided('approved'), rows, false, label)?.step?.id).toBe('b'); + const decidedOnly = [row('c', 'approved', at(4)), row('b', 'approved', at(3))]; + expect(routeOutcome(decided('approved'), decidedOnly, true, label)?.step?.id).toBe('c'); + }); + + it('several later requests pending at once (parallel steps): no single step, no outcome', () => { + const rows = [row('b', 'pending', at(3)), row('c', 'pending', at(3))]; + expect(routeOutcome(decided('approved'), rows, false, label)).toBeUndefined(); + }); + + it('earlier rows, the request itself, and rows with no node, time or status are not later requests', () => { + const rows = [ + row('z', 'pending', at(1)), + { id: 'a@' + at(2), flow_node_id: 'a', status: 'pending', created_at: at(5) }, + { id: 'n1', status: 'pending', created_at: at(3) }, + { id: 'n2', flow_node_id: 'b', status: 'pending' }, + { id: 'n3', flow_node_id: 'b', created_at: at(3) }, + ]; + expect(routeOutcome(decided('approved'), rows, false, label)).toBeUndefined(); + expect(routeOutcome({ id: 'x', status: 'approved' }, [row('b', 'pending', at(3))], false, label)).toBeUndefined(); + }); + + it('flowRoute carries it on a decided request only, and only when one is known', () => { + const rows = [row('a', 'approved', at(2)), row('b', 'pending', at(3))]; + expect(flowRoute({ id: 'a@' + at(2), flow_node_id: 'a', created_at: at(2), status: 'approved' }, LINE, rows, label)).toEqual({ + steps: [{ id: 'a', label: 'A', state: 'done' }], + ahead: 'decided', + outcome: { step: { id: 'b', label: 'B' }, status: 'pending', ended: false }, + }); + // A pending request is never handed an outcome, even with the run's rows and an ended run. + const pending = flowRoute({ id: 'b@' + at(3), flow_node_id: 'b', created_at: at(3), status: 'pending' }, LINE, rows, label, true); + expect(pending && 'outcome' in pending).toBe(false); + }); +}); + +describe('[#35863] flowHostsChildRuns — a flow whose run may file requests under a child run', () => { + const node = (id: string, type: string, config?: Record) => ({ id, type, label: id, ...(config ? { config } : {}) }); + const region = (...nodes: unknown[]) => ({ nodes, edges: [] }); + + it('a subflow or a map node at the top level', () => { + expect(flowHostsChildRuns({ nodes: [node('s', 'start'), node('legal', 'subflow'), node('e', 'end')] })).toBe(true); + expect(flowHostsChildRuns({ nodes: [node('s', 'start'), node('each', 'map'), node('e', 'end')] })).toBe(true); + }); + + it('a subflow or a map node inside a container\'s region, at any depth', () => { + const inLoop = { nodes: [node('l', 'loop', { body: region(node('legal', 'subflow')) })] } as RouteFlowGraph; + const inBranch = { nodes: [node('p', 'parallel', { branches: [region(node('a', 'approval')), region(node('each', 'map'))] })] } as RouteFlowGraph; + const inCatch = { nodes: [node('t', 'try_catch', { try: region(node('a', 'approval')), catch: region(node('legal', 'subflow')) })] } as RouteFlowGraph; + const nested = { nodes: [node('l', 'loop', { body: region(node('t', 'try_catch', { try: region(node('legal', 'subflow')) })) })] } as RouteFlowGraph; + for (const flow of [inLoop, inBranch, inCatch, nested]) expect(flowHostsChildRuns(flow)).toBe(true); + }); + + it('no such node anywhere: approvals, gateways and in-run containers only', () => { + expect(flowHostsChildRuns({ nodes: [node('s', 'start'), node('a', 'approval'), node('d', 'decision'), node('e', 'end')] })).toBe(false); + expect(flowHostsChildRuns({ nodes: [node('l', 'loop', { body: region(node('a', 'approval')) })] } as RouteFlowGraph)).toBe(false); + expect(flowHostsChildRuns({})).toBe(false); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-route.ts b/packages/plugins/plugin-approvals/src/approval-route.ts index c46897e7c55..dbab7a74fea 100644 --- a/packages/plugins/plugin-approvals/src/approval-route.ts +++ b/packages/plugins/plugin-approvals/src/approval-route.ts @@ -11,14 +11,20 @@ * it cannot decide; it never takes the trunk's branch in its place, which is * what `flow_steps` does. * + * [#35863] A decided request's route also says where the record's approval + * stands now, {@link routeOutcome}: the run's latest request past this one, + * and whether the run has ended. History again, never the graph. + * * Pure functions over the flow and the rows: the service reads both and * attaches the result (`ApprovalService.attachFlowRoute`). */ +import { collectFlowGraphs } from '@objectstack/spec/automation'; import type { ApprovalRequestRow } from '@objectstack/spec/contracts'; export type FlowRoute = NonNullable; type RouteStep = FlowRoute['steps'][number]; +type RouteOutcome = NonNullable; /** The parts of a flow graph the route reads. */ export interface RouteFlowGraph { @@ -43,6 +49,41 @@ export type RouteStepLabel = (nodeId: string) => string; */ const OPAQUE_NODE_TYPES = new Set(['subflow', 'map', 'loop']); +/** + * [#35863] Node types that start a CHILD run: a `subflow` body or a `map` + * item runs under its own run id, linked upward by `$parentRunId`. A request + * a child run opens is filed under that child's `flow_run_id`, so it is not + * among the run rows the route reads. + * + * ⚠️ A hand list of the engine's child-run starters: the only executors that + * set `$parentRunId` on a context are `subflow` + * (`service-automation/src/builtin/subflow-node.ts`) and `map` + * (`builtin/map-node.ts`); `loop`, `parallel` and `try_catch` run their + * regions inside the same run. A node kind that starts a child run joins this + * set in the same change, or {@link flowHostsChildRuns} under-reports it and + * "ended" is claimed past that child's requests. + */ +const CHILD_RUN_NODE_TYPES = new Set(['subflow', 'map']); + +/** + * [#35863] Whether `flow` holds a node that starts a child run + * ({@link CHILD_RUN_NODE_TYPES}), anywhere: at the top level or inside a + * container's region (`loop` body, `parallel` branch, `try_catch`), every + * graph {@link collectFlowGraphs} walks. + * + * Read off the definition, not off the run's step log: a run's persisted step + * log is compacted to a bounded number of steps and may drop a body step, so + * "the run never ran one" cannot be proven from it. The definition can say + * "it never could". The caller uses it to refuse "ended": a run of such a flow + * may have opened requests in a child run that the run's own rows do not hold, + * so neither "the approval ended here" nor "the last decision was this one" + * can be known. + */ +export function flowHostsChildRuns(flow: RouteFlowGraph): boolean { + return collectFlowGraphs(flow as Parameters[0]) + .some((graph) => graph.nodes.some((node) => CHILD_RUN_NODE_TYPES.has(String(node.type)))); +} + /** * The approval steps `current`'s run passed before `current`, oldest first: * a row of the same run, on another node, `approved`, opened before @@ -110,9 +151,60 @@ export function stepsAhead( return { steps, ahead: 'undecided' }; } +/** + * [#35863] Where the record's approval stands after the decided request + * `current` (`flow_route.outcome`, the contract doc is the rule): the run's + * latest request opened after `current`, on any node, a pending one first; + * else, once the run has ended, `current` itself. `undefined` when neither + * says anything, and when several later requests are pending at once: no one + * step is where a parallel approval stands, and none is picked. + * + * `runRows` is the run's own request rows, as for {@link passedSteps}; + * `runEnded` is whether the record's approval is KNOWN to have stopped: the + * caller answers `true` only for a root run (never a `subflow` or `map` + * child, whose end is not the approval's) whose flow starts no child run + * ({@link flowHostsChildRuns}: a child run's requests are not in `runRows`) + * and that the run itself reports stopped for good, and `false` for anything + * it cannot tell. + */ +export function routeOutcome( + current: { id: string; status?: string; created_at?: string }, + runRows: ReadonlyArray, + runEnded: boolean, + label: RouteStepLabel, +): RouteOutcome | undefined { + const openedAt = current.created_at; + const later: Array<{ node: string; status: string; at: string }> = []; + if (openedAt) { + for (const r of runRows) { + const node = typeof r.flow_node_id === 'string' ? r.flow_node_id : undefined; + const at = typeof r.created_at === 'string' ? r.created_at : undefined; + const status = typeof r.status === 'string' ? r.status : undefined; + if (!node || !at || !status || String(r.id) === current.id || at <= openedAt) continue; + later.push({ node, status, at }); + } + } + const pending = later.filter((r) => r.status === 'pending'); + if (pending.length > 1) return undefined; + const latest = pending[0] ?? later.reduce<(typeof later)[number] | undefined>( + (best, r) => (!best || best.at < r.at ? r : best), + undefined, + ); + if (latest) { + return { + step: { id: latest.node, label: label(latest.node) }, + status: latest.status as RouteOutcome['status'], + ended: runEnded, + }; + } + if (!runEnded || !current.status) return undefined; + return { status: current.status as RouteOutcome['status'], ended: true }; +} + /** * The whole route of `row`: {@link passedSteps}, then `row`'s own node, then - * — for a pending row only — {@link stepsAhead}. `undefined` when the row + * — for a pending row only — {@link stepsAhead}; for a decided row, the + * {@link routeOutcome} past it when one is known. `undefined` when the row * names no node. */ export function flowRoute( @@ -120,12 +212,16 @@ export function flowRoute( flow: RouteFlowGraph, runRows: ReadonlyArray, label: RouteStepLabel, + runEnded = false, ): FlowRoute | undefined { const nodeId = row.flow_node_id; if (!nodeId) return undefined; const own: RouteStep = { id: nodeId, label: label(nodeId), state: row.status === 'approved' ? 'done' : 'current' }; const before = passedSteps(row, runRows, label); - if (row.status !== 'pending') return { steps: [...before, own], ahead: 'decided' }; + if (row.status !== 'pending') { + const outcome = routeOutcome(row, runRows, runEnded, label); + return outcome ? { steps: [...before, own], ahead: 'decided', outcome } : { steps: [...before, own], ahead: 'decided' }; + } const after = stepsAhead(flow, nodeId, label); return { steps: [...before, own, ...after.steps], ahead: after.ahead }; } diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 50e23203422..a9a04b2b7c0 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -123,7 +123,7 @@ import { type ActingCaller, } from './approver-address.js'; import { labelOrMachineName, requestDisplayLabels, slateLabelOf } from './display-labels.js'; -import { flowRoute, type RouteFlowGraph } from './approval-route.js'; +import { flowHostsChildRuns, flowRoute, type RouteFlowGraph } from './approval-route.js'; import { ADMIN_RESCUE_NOTE_SNAPSHOT_KEY, adminRescueNoteOf, @@ -314,6 +314,15 @@ export interface ApprovalResumeSurface { flowSlotKey?(packageId: string | null, name: string): string | undefined; getFlowSlot?(packageId: string | null, name: string): any | null; getRunFlow?(run: { flowName: string }): any | null; + /** + * [#35863] A flow name's registrations, oldest first: each body and when it + * was registered. Read by {@link ApprovalService.attachFlowRoute} to tell + * whether a run ran the body armed now (`ranArmedBody`). ⚠️ Declares a + * method `AutomationEngine` ALREADY implements publicly + * (`getFlowVersionHistory`); it widens no engine surface. Optional: absent, + * no request is served "ended". + */ + getFlowVersionHistory?(name: string): ReadonlyArray<{ version?: number; definition: unknown; createdAt: string }>; /** * Terminally cancel a suspended run (ADR-0044). Used when a recall lands * during a revision window — the run is paused at the revise-window node, @@ -332,7 +341,7 @@ export interface ApprovalResumeSurface { * `null` — unknown run, evicted log, no durable store, no automation engine — * as "still alive". */ - getRun?(runId: string): Promise<{ status?: string; flowName?: string } | null>; + getRun?(runId: string): Promise<{ status?: string; flowName?: string; startedAt?: string } | null>; /** * Whether a suspension still exists for `runId` — the pre-flight that keeps * a decision from being recorded against a run that can never advance @@ -5126,6 +5135,16 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * the flow's key, the body whose origin {@link flowPackageOf} answers. */ node?: unknown; + /** + * [#35863] Whether `runId` is a root run (`true`) or a child of another + * run, a `subflow` body or a `map` item (`false`), as the approval + * executor reads the run's context. Stamped on the config snapshot + * (`__runRoot`, precedent: `__round`) for {@link attachFlowRoute}: only + * a root run's end is the end of the record's approval. Absent (a + * caller that does not say) stamps nothing, which reads as "not known + * to be a root run". + */ + runRoot?: boolean; }, context: ExecutionContext, ): Promise { @@ -5493,6 +5512,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega : undefined; if (exclusionNote) configSnapshot[SUBMITTER_EXCLUSION_NOTE_SNAPSHOT_KEY] = exclusionNote; if (noApproverNote) configSnapshot[NO_APPROVER_NOTE_SNAPSHOT_KEY] = noApproverNote; + // [#35863] Root run or child run, as the executor said; nothing when it + // did not say ({@link attachFlowRoute} reads absence as "not known"). + if (typeof input.runRoot === 'boolean') configSnapshot.__runRoot = input.runRoot; // ADR-0044 round numbering: rounds of a revise loop share the run — count // this (run, node)'s prior requests; the new one is round N+1. Stamped on // the snapshot (precedent: __flowLabel), so no schema migration. @@ -11623,7 +11645,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const flow: any = await this.requestFlow(raw, flowName); if (!flow?.nodes?.length) return; const nodesById = new Map(flow.nodes.map((n: any) => [n.id, n])); - await this.attachFlowRoute(row, flowName, flow, nodesById, labels); + await this.attachFlowRoute(row, flowName, flow, nodesById, labels, raw); const steps: Array<{ id: string; label: string }> = []; const seen = new Set(); let cur: any = flow.nodes.find((n: any) => n.type === 'start'); @@ -11663,6 +11685,34 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * A step is named as `flow_steps` names it ([#24863]): the reader's label, * else the node's authored label; a node no longer in the graph by the * label its request stored. Display-only and best-effort. + * + * [#35863] A decided request's route carries `outcome`, where the record's + * approval stands now, off the same system read. So that read now serves + * more than the step labels `flow_steps` serves: for the run's latest later + * request, its step (node id and label) and its status, and whether the + * record's approval has ended. It serves that to every reader of THIS + * request, including one who cannot read the later request: within the + * request-visibility bound of ruling record 5299823744 (request content + * stays behind the read-visibility tier), as the seat ruled on PR #37148, + * because it tells only where the same approval went. The later request's + * id, approvers, comments and field values are never served here; a reader + * gets those only through that request's own read gate. + * + * "Ended" is asked of the run itself ({@link runHasEnded}, the dead-run + * sweep's {@link TERMINAL_RUN_STATUSES}), and only for a request its + * snapshot names a root run's (`__runRoot`, stamped at open): a `subflow` + * body or a `map` item is a child run, and its end is not the end of the + * record's approval, since the parent run goes on. Nor for a root run whose + * flow starts a child run anywhere ({@link flowHostsChildRuns}): a request + * a child run opened, after this one included, is filed under the child's + * run id and is not among the rows read here, so neither "ended here" nor + * "the last decision" can be known. "Its flow" is the body the run ran, + * and the read holds only the body armed NOW, so "ended" is also refused + * unless the run provably ran that body ({@link ranArmedBody}): a flow + * edited after the run, to drop its `subflow` say, is not judged by the + * edit. A request opened before the stamp, a child run's, a run of such a + * flow, a run not known to have run the armed body, or a run that cannot be + * read is never "ended": `ended: false` means "not known to have stopped". */ private async attachFlowRoute( row: ApprovalRequestRow, @@ -11670,6 +11720,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega flow: RouteFlowGraph, nodesById: Map, labels: ReaderLabels | undefined, + raw: any, ): Promise { try { if (!row.flow_run_id || !row.flow_node_id) return; @@ -11688,11 +11739,57 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } const label = (nodeId: string): string => labels?.stepLabel(flowName, nodeId) ?? (nodesById.get(nodeId)?.label || stored.get(nodeId) || nodeId); - const route = flowRoute(row, flow, rows, label); + const runRoot = parseJson(raw?.node_config_json, undefined)?.__runRoot === true; + const ended = row.status !== 'pending' && runRoot && !flowHostsChildRuns(flow) + && await this.runHasEnded(row.flow_run_id, flowName, flow); + const route = flowRoute(row, flow, rows, label, ended); if (route) (row as any).flow_route = route; } catch { /* display-only — never fail the read */ } } + /** + * [#35863] Whether the flow run `runId` has stopped for good, having run + * `flow`: its status is one of {@link TERMINAL_RUN_STATUSES} and + * {@link ranArmedBody} holds for it. `false` when there is no `getRun`, no + * such run, or a read throws: display-only, so an unreadable run is only + * ever "not known to have ended", never a failed read. + */ + private async runHasEnded(runId: string, flowName: string, flow: unknown): Promise { + if (typeof this.automation?.getRun !== 'function') return false; + try { + const run = await this.automation.getRun(runId); + const status = run?.status; + return !!status && TERMINAL_RUN_STATUSES.has(status) && this.ranArmedBody(run?.startedAt, flowName, flow); + } catch { + return false; + } + } + + /** + * [#35863] Whether a run that started at `startedAt` provably ran `flow`, + * the body of `flowName` armed now: `flow` is the engine's NEWEST + * registration of the name (`getFlowVersionHistory`, the very object), and + * was registered strictly before the run started. A run starts on the body + * armed at its start and resumes pinned to it, so with nothing registered + * since, that body is `flow`. + * + * Every other case is "not known", never a guess: a body registered after + * the run started (an edit, or the registration a restart makes), a body + * armed without being the newest registration (a rollback re-arms an older + * one), no history for the name, or no start time. The run's `flowVersion` + * is not the witness: it is the author's number and an edit need not change + * it. + */ + private ranArmedBody(startedAt: unknown, flowName: string, flow: unknown): boolean { + if (typeof startedAt !== 'string' || typeof this.automation?.getFlowVersionHistory !== 'function') return false; + const history = this.automation.getFlowVersionHistory(flowName); + const newest = Array.isArray(history) && history.length > 0 ? history[history.length - 1] : undefined; + if (!newest || newest.definition !== flow) return false; + const registered = Date.parse(newest.createdAt); + const started = Date.parse(startedAt); + return Number.isFinite(registered) && Number.isFinite(started) && registered < started; + } + async listActions(requestId: string, context: ExecutionContext): Promise { if (!requestId) return []; // Tenant gate: ensure the caller can see the parent request before diff --git a/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts b/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts index fadea8e1714..b9b8f4b88d2 100644 --- a/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts @@ -33,7 +33,12 @@ * - a gateway right after the current step is served `undecided`, never the * trunk's branch, and a gateway ahead of a step the graph decides lets that * step through; - * - a decided request ends its route at itself, `decided`. + * - a decided request ends its route at itself, `decided`; + * - [#35863] and carries `outcome`: a later request pending (step 2 of a + * two-step route), the approval ended with a later step's decision, or + * ended at the request itself; a pending request carries none; an + * approval inside a subflow is never served its child run's end, nor is a + * request whose snapshot does not say its run is a root run. * * ⚠️ Direction, predicted before running: every `flow_route` pin is RED on the * unfixed door (it served no such member); the `flow_steps` pins are green on @@ -43,7 +48,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; -import { AutomationEngine, registerLogicNodes } from '@objectstack/service-automation'; +import { AutomationEngine, installBuiltinNodes } from '@objectstack/service-automation'; import type { EngineQueryOptions } from '@objectstack/spec/data'; import { ApprovalService } from './approval-service.js'; import { ApprovalsServicePlugin } from './approvals-plugin.js'; @@ -166,6 +171,58 @@ const LINEAR = { ], }; +/** [#35863] One approval, run as another flow's `subflow` body: a child run. */ +const CHILD = { + name: 'contract_child', label: 'Contract Child', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + step('legal_review', 'Legal', 'u_legal'), + { id: 'ok', type: 'end', label: 'Approved' }, + { id: 'no', type: 'end', label: 'Rejected' }, + ], + edges: [ + { id: 'c1', source: 'start', target: 'legal_review' }, + { id: 'c2', source: 'legal_review', target: 'ok', label: 'approve' }, + { id: 'c3', source: 'legal_review', target: 'no', label: 'reject' }, + ], +}; + +/** [#35863] The legal step in a child run, then the general manager in the root run. */ +const HOSTED = { + name: 'contract_hosted', label: 'Contract Hosted', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'legal', type: 'subflow', label: 'Legal subflow', config: { flowName: CHILD.name } }, + step('gm_signoff', 'General Manager', 'u_gm'), + { id: 'ok', type: 'end', label: 'Approved' }, + { id: 'no', type: 'end', label: 'Rejected' }, + ], + edges: [ + { id: 'h1', source: 'start', target: 'legal' }, + { id: 'h2', source: 'legal', target: 'gm_signoff' }, + { id: 'h3', source: 'gm_signoff', target: 'ok', label: 'approve' }, + { id: 'h4', source: 'gm_signoff', target: 'no', label: 'reject' }, + ], +}; + +/** [#35863] The manager in the root run, then the legal step in a child run, then the end. */ +const REVIEWED_THEN_LEGAL = { + name: 'contract_reviewed_then_legal', label: 'Contract Reviewed Then Legal', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + step('manager_review', 'Manager', 'u_mgr'), + { id: 'legal', type: 'subflow', label: 'Legal subflow', config: { flowName: CHILD.name } }, + { id: 'done', type: 'end', label: 'Done' }, + { id: 'no', type: 'end', label: 'Rejected' }, + ], + edges: [ + { id: 'r1', source: 'start', target: 'manager_review' }, + { id: 'r2', source: 'manager_review', target: 'legal', label: 'approve' }, + { id: 'r3', source: 'manager_review', target: 'no', label: 'reject' }, + { id: 'r4', source: 'legal', target: 'done' }, + ], +}; + /** What `flow_steps` serves for every `contract_approval` request: its trunk. */ const CONTRACT_TRUNK = ['manager_review', 'legal_finance_joint', 'executive_signoff', 'gm_signoff']; @@ -198,6 +255,12 @@ describe('[#26668] the approvals get serves the route a request takes, not the f expect([out.finalized, out.resumed], `${decider} approved ${req.flow_node_id}`).toEqual([true, true]); return pendingOn(req.record_id); }; + /** `decider` rejects `req`; the run walks the `reject` edge to its end. */ + const reject = async (req: any, decider: string): Promise => { + const out = await svc.decide(req.id, { decision: 'reject', actorId: decider, comment: 'Not this quarter' }, asUser(decider)); + expect([out.finalized, out.resumed], `${decider} rejected ${req.flow_node_id}`).toEqual([true, true]); + expect(await pendingOn(req.record_id), 'nothing pending after the rejection').toBeUndefined(); + }; /** The get, as the submitter reads it. */ const get = async (req: any): Promise => svc.getRequest(req.id, asUser(SUBMITTER)); const states = (steps: any[] | undefined) => (steps ?? []).map((s) => [s.id, s.state]); @@ -218,8 +281,9 @@ describe('[#26668] the approvals get serves the route a request takes, not the f for (const u of USERS) await engine.insert('sys_user', u, { context: SYSTEM } as any); automation = new AutomationEngine(silent); - // The gateways are `decision` nodes, built-ins a bare engine starts without. - registerLogicNodes(automation, { logger: silent } as any); + // The gateways are `decision` nodes and the hosted case a `subflow`, built-ins + // a bare engine starts without. + installBuiltinNodes(automation, { logger: silent, getService() { throw new Error('none'); } } as any); svc = new ApprovalService({ engine: engine as any, clock: { now: () => new Date(now += 1000) }, @@ -229,6 +293,9 @@ describe('[#26668] the approvals get serves the route a request takes, not the f registerApprovalNode(automation as any, svc, silent); automation.registerFlow(CONTRACT.name, CONTRACT as any); automation.registerFlow(LINEAR.name, LINEAR as any); + automation.registerFlow(CHILD.name, CHILD as any); + automation.registerFlow(HOSTED.name, HOSTED as any); + automation.registerFlow(REVIEWED_THEN_LEGAL.name, REVIEWED_THEN_LEGAL as any); }); afterAll(async () => { @@ -280,7 +347,7 @@ describe('[#26668] the approvals get serves the route a request takes, not the f expect(row.flow_route.ahead).toBe('undecided'); }); - it('a decided request ends its route at itself', async () => { + it('a decided request ends its route at itself; at the last step, the outcome says the approval ended', async () => { const manager = await submit(CONTRACT.name, { amount: 250000, route_finance: true }); const finance = await approve(manager, 'u_mgr'); await approve(finance, 'u_fin'); @@ -293,9 +360,158 @@ describe('[#26668] the approvals get serves the route a request takes, not the f { id: 'finance_only', label: 'Finance', state: 'done' }, ], ahead: 'decided', + // [#35863] Both gateways past the finance rung fall through to the end: no later request. + outcome: { status: 'approved', ended: true }, + }); + }); + + it('[#35863] a request decided at step 1 of a two-step route: the outcome says step 2 is pending, then that the approval ended there', async () => { + const manager = await submit(CONTRACT.name, { amount: 250000, route_finance: true }); + const finance = await approve(manager, 'u_mgr'); + + const before = await get(manager); + expect(before.flow_route).toEqual({ + steps: [{ id: 'manager_review', label: 'Manager', state: 'done' }], + ahead: 'decided', + outcome: { step: { id: 'finance_only', label: 'Finance' }, status: 'pending', ended: false }, + }); + + await reject(finance, 'u_fin'); + const after = await get(manager); + expect(after.flow_route.outcome).toEqual({ step: { id: 'finance_only', label: 'Finance' }, status: 'rejected', ended: true }); + }); + + it('[#35863] a request rejected at the first step: the outcome says the approval ended there, rejected', async () => { + const manager = await submit(CONTRACT.name, { amount: 250000, route_finance: true }); + await reject(manager, 'u_mgr'); + + const row = await get(manager); + expect(row.flow_route).toEqual({ + steps: [{ id: 'manager_review', label: 'Manager', state: 'current' }], + ahead: 'decided', + outcome: { status: 'rejected', ended: true }, }); }); + it('[#35863] an approval inside a subflow: its child run\'s end is not served as the end of the record\'s approval', async () => { + const legal = await submit(HOSTED.name, {}); + expect(legal?.flow_node_id).toBe('legal_review'); + expect(legal.flow_run_id, 'the legal step runs in a child run').toBeTruthy(); + const gm = await approve(legal, 'u_legal'); + // The child run completed; the root run went on to the general manager under its own run id. + expect(gm?.flow_node_id).toBe('gm_signoff'); + expect(gm.flow_run_id).not.toBe(legal.flow_run_id); + expect((await automation.getRun(legal.flow_run_id))?.status, 'the child run itself has ended').toBe('completed'); + + const row = await get(legal); + expect(row.status).toBe('approved'); + expect(row.flow_route.ahead).toBe('decided'); + // Nothing later in the child run, and the child's end is not the approval's: no outcome. + expect('outcome' in row.flow_route).toBe(false); + + // The root run's own last request: the run completed, but its flow starts a child run, whose + // requests are not among this run's rows, so the approval is not known to have ended here. + await approve(gm, 'u_gm'); + expect((await automation.getRun(gm.flow_run_id))?.status, 'the root run itself has ended').toBe('completed'); + expect('outcome' in (await get(gm)).flow_route).toBe(false); + }); + + it('[#35863] a later step in a child run: the root run\'s end is not served as "ended here" for the request before it', async () => { + const manager = await submit(REVIEWED_THEN_LEGAL.name, {}); + expect(manager?.flow_node_id).toBe('manager_review'); + const legal = await approve(manager, 'u_mgr'); + expect(legal?.flow_node_id).toBe('legal_review'); + expect(legal.flow_run_id, 'the legal step runs in a child run').not.toBe(manager.flow_run_id); + + // Legal rejects; the child run ends and the root run walks on to its end. + await reject(legal, 'u_legal'); + expect((await automation.getRun(manager.flow_run_id))?.status, 'the root run has ended').toBe('completed'); + + // The root run's rows hold only the manager's request. "The approval ended here, approved" + // would be wrong twice: it went on to legal, and legal's rejection was the last decision. + const row = await get(manager); + expect(row.status).toBe('approved'); + expect(row.flow_route).toEqual({ + steps: [{ id: 'manager_review', label: 'Manager', state: 'done' }], + ahead: 'decided', + }); + }); + + it('[#35863] a flow edited after the run is not judged by the edit: the run\'s own body hosted a subflow', async () => { + // The run's body: the manager, then legal in a child run. Registered under its own name so the edit below touches no other pin. + const name = 'contract_edited_after_run'; + automation.registerFlow(name, { ...REVIEWED_THEN_LEGAL, name } as any); + await new Promise((r) => setTimeout(r, 5)); // registered strictly before the run starts + const manager = await submit(name, {}); + const legal = await approve(manager, 'u_mgr'); + expect(legal.flow_run_id, 'the legal step runs in a child run').not.toBe(manager.flow_run_id); + await reject(legal, 'u_legal'); + expect((await automation.getRun(manager.flow_run_id))?.status, 'the root run has ended').toBe('completed'); + expect('outcome' in (await get(manager)).flow_route).toBe(false); + + // The flow is edited to drop its subflow, under the SAME version number: the body armed now hosts no child run. + const { nodes, edges } = REVIEWED_THEN_LEGAL; + automation.registerFlow(name, { + ...REVIEWED_THEN_LEGAL, name, + nodes: nodes.filter((n) => n.id !== 'legal'), + edges: [...edges.filter((e) => e.source !== 'legal' && e.target !== 'legal'), { id: 'r5', source: 'manager_review', target: 'done', label: 'approve' }], + } as any); + // Still no outcome: the run ran the body with the subflow, and legal's rejection was the last decision. + const row = await get(manager); + expect(row.flow_route).toEqual({ steps: [{ id: 'manager_review', label: 'Manager', state: 'done' }], ahead: 'decided' }); + + // A run started on the edited body does end at the manager: "ended" is judged by the body a run ran. + await new Promise((r) => setTimeout(r, 5)); + const next = await submit(name, {}); + await approve(next, 'u_mgr'); + expect((await get(next)).flow_route.outcome).toEqual({ status: 'approved', ended: true }); + }); + + it('[#35863] a rollback re-arms an older body: a run of the newer one is not judged by it', async () => { + const name = 'contract_rolled_back'; + const { nodes, edges } = REVIEWED_THEN_LEGAL; + // Version 1 has no subflow; version 2, the one the run runs, adds legal in a child run. + automation.registerFlow(name, { + ...REVIEWED_THEN_LEGAL, name, version: 1, + nodes: nodes.filter((n) => n.id !== 'legal'), + edges: [...edges.filter((e) => e.source !== 'legal' && e.target !== 'legal'), { id: 'r5', source: 'manager_review', target: 'done', label: 'approve' }], + } as any); + automation.registerFlow(name, { ...REVIEWED_THEN_LEGAL, name, version: 2 } as any); + await new Promise((r) => setTimeout(r, 5)); + const manager = await submit(name, {}); + const legal = await approve(manager, 'u_mgr'); + await reject(legal, 'u_legal'); + expect((await automation.getRun(manager.flow_run_id))?.status, 'the root run has ended').toBe('completed'); + + // Version 1 armed again: a body with no subflow, registered before the run started, but not the body it ran. + automation.rollbackFlow(name, 1); + expect('outcome' in (await get(manager)).flow_route).toBe(false); + }); + + it('[#35863] a request whose snapshot does not say its run is a root run is never served "ended"', async () => { + const manager = await submit(LINEAR.name, {}); + const director = await approve(manager, 'u_mgr'); + const gm = await approve(director, 'u_dir'); + await approve(gm, 'u_gm'); + expect((await get(gm)).flow_route.outcome).toEqual({ status: 'approved', ended: true }); + + // As a request opened before the stamp reads: the run ended, but it is not known to be the root run. + const [stored]: any[] = await engine.find('sys_approval_request', { where: { id: gm.id }, context: SYSTEM } satisfies EngineQueryOptions); + const cfg = JSON.parse(stored.node_config_json); + expect(cfg.__runRoot, 'the approval node stamps a root run').toBe(true); + delete cfg.__runRoot; + await engine.update('sys_approval_request', { id: gm.id, node_config_json: JSON.stringify(cfg) }, { context: SYSTEM } as any); + expect('outcome' in (await get(gm)).flow_route).toBe(false); + // An earlier request of the same run keeps its own stamp: it still says the approval went on and ended. + expect((await get(manager)).flow_route.outcome).toEqual({ step: { id: 'gm_signoff', label: 'General Manager' }, status: 'approved', ended: true }); + }); + + it('[#35863] a pending request is never served an outcome', async () => { + const manager = await submit(CONTRACT.name, { amount: 250000, route_finance: true }); + const row = await get(manager); + expect('outcome' in row.flow_route).toBe(false); + }); + it('on a linear flow the trunk is the route: at every step the route equals flow_steps, ending at the flow\'s end', async () => { let req = await submit(LINEAR.name, {}); for (const [node, decider] of [['manager_review', 'u_mgr'], ['director_review', 'u_dir'], ['gm_signoff', 'u_gm']] as const) { diff --git a/packages/spec/src/contracts/approval-service.ts b/packages/spec/src/contracts/approval-service.ts index a929ddb6a48..01bbc8efd83 100644 --- a/packages/spec/src/contracts/approval-service.ts +++ b/packages/spec/src/contracts/approval-service.ts @@ -384,11 +384,64 @@ export interface ApprovalRequestRow { * yet. Steps past it are not listed, and the trunk is never listed in * their place. * - `decided` — the request is decided, so nothing past it is walked. The - * steps its run reached next are the later requests' own routes. + * steps its run reached next are the later requests' own routes; + * `outcome` says where the record's approval stands now. */ flow_route?: { steps: Array<{ id: string; label: string; state: 'done' | 'current' | 'upcoming' }>; ahead: 'end' | 'undecided' | 'decided'; + /** + * Where the record's approval stands after this request, on a decided + * request only (`ahead: 'decided'`), read off the request's flow run and + * never guessed: + * + * - `step` — the run's latest request, when that is a later one than + * this request: a request of the same `flow_run_id` opened after this + * one, on any node (a later round of this request's own node too). A + * pending one wins over a decided one. Absent when no later request was + * opened in that run, so the approval stands at this request as far as + * the run's own requests tell. A request a `subflow` body or a `map` + * item opens belongs to a child run (its own `flow_run_id`) and is not + * among them; see `ended`. + * - `status` — that latest request's status (this request's own when + * `step` is absent). `pending` with a `step`: the approval went on to + * that step and waits on its decision. + * - `ended` — `true` only when the record's approval is known to have + * stopped: the request's run is a root run (not a `subflow` body or a + * `map` item, whose end is not the approval's: the parent run goes on), + * the flow body the run ran holds no `subflow` or `map` node anywhere, + * its regions included (a child run started from it may have opened + * requests, after this one too, that the run's own requests do not + * show), and the run has stopped for good. The body the run ran is + * known only when the body armed now is the flow's newest registration + * and was registered before the run started; a flow edited, rolled back + * or re-registered since the run started is not judged by its current + * body. When `status` is not `pending`, it is then the last decision the + * record's approval took. `false` means "not known to have stopped": + * the run is still going, is a child run, ran a body that can start a + * child run, ran a body that is not known (its flow was registered + * again since it started), was opened before the platform recorded + * which runs are root runs, or cannot be read. + * + * Absent when nothing past this request is known: no later request was + * opened and the approval is not known to have ended, or several later + * requests are pending at once (parallel steps), which no single step + * answers. With a later request it is served even when the run cannot be + * read, with `ended: false`. + * + * Audience: every reader of this request, whether or not they can read + * the later request. It says only where the same approval went: the later + * step's node id and label, which the route already names for the steps + * it lists, and that request's status. It never carries the later + * request's id, its approvers, its comments or its field values; those + * stay behind that request's own read gate (the read-visibility tier of + * ruling record 5299823744). + */ + outcome?: { + step?: { id: string; label: string }; + status: ApprovalStatus; + ended: boolean; + }; }; /** * ADR-0044 revision round of this request on its (run, node): 1 (or absent) diff --git a/ui/apps/console/src/services/approvalsApi.ts b/ui/apps/console/src/services/approvalsApi.ts index 8a723da4458..1334cd8451b 100644 --- a/ui/apps/console/src/services/approvalsApi.ts +++ b/ui/apps/console/src/services/approvalsApi.ts @@ -125,11 +125,18 @@ export interface ApprovalRequestRow { * This request's own route (single reads only, objectstack#26668): the steps * its run passed, its own, and while pending the steps ahead the graph alone * decides; `ahead` says whether the route ends, waits on an undecided branch, - * or stops at a decided request. + * or stops at a decided request; on a decided one, `outcome` says where the + * record's approval stands now (objectstack#35863). */ flow_route?: { steps: Array<{ id: string; label: string; state: 'done' | 'current' | 'upcoming' }>; ahead: 'end' | 'undecided' | 'decided'; + outcome?: { + step?: { id: string; label: string }; + /** A request status, typed as this row's own `status`. */ + status: ApprovalRequestRow['status']; + ended: boolean; + }; }; /** * Server-computed aggregation progress (#3266) for pending multi-approver diff --git a/ui/packages/app-shell/src/hooks/useRecordApprovals.ts b/ui/packages/app-shell/src/hooks/useRecordApprovals.ts index 8f1f195e286..f167e819d97 100644 --- a/ui/packages/app-shell/src/hooks/useRecordApprovals.ts +++ b/ui/packages/app-shell/src/hooks/useRecordApprovals.ts @@ -129,6 +129,20 @@ export interface ApprovalRequestLite { flow_route?: { steps: Array<{ id: string; label: string; state: 'done' | 'current' | 'upcoming' }>; ahead: 'end' | 'undecided' | 'decided'; + /** + * On a decided route only (objectstack#35863): where the record's + * approval stands now. `step` is the run's latest request when it is a + * later one (absent: the approval stands at this request), `status` that + * request's status (`pending`: waiting on that step), `ended` whether the + * record's approval is known to have stopped (`false`: not known, never + * "still going"). Absent when the server knows nothing past this request. + */ + outcome?: { + step?: { id: string; label: string }; + /** A request status, typed as this row's own `status`. */ + status: ApprovalRequestLite['status']; + ended: boolean; + }; }; /** The flow run that opened this request; every request of one run shares it. */ flow_run_id?: string; diff --git a/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.stepLine-12491.test.tsx b/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.stepLine-12491.test.tsx index dfc09daba0d..c4525702328 100644 --- a/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.stepLine-12491.test.tsx +++ b/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.stepLine-12491.test.tsx @@ -30,6 +30,10 @@ * connector tint) is pinned over the same `ApprovalStepLine` markup in * `RecordApprovalsPanel.stepProgressVertical.test.tsx`. The declared actions * bar is doubled. + * + * objectstack#35863: a decided request's route carries `outcome`, where the + * record's approval stands now; one line under the decided step says it, and + * nothing is drawn when no outcome is served. */ import * as React from 'react'; @@ -40,6 +44,9 @@ vi.mock('../DeclaredActionsBar.js', () => ({ DeclaredActionsBar: () =>
, })); +// The submitted-record card's lazy detail surface: loaded here, at collection, +// so no clocked case pays its first transform. +import '@object-ui/plugin-detail'; import { RecordContextProvider } from '@object-ui/react'; import { builtInLocales } from '@object-ui/i18n/locales'; import { ApprovalDecisionRenderer } from './ApprovalDecisionPanel'; @@ -232,3 +239,80 @@ describe('ApprovalDecisionPanel — a decided request draws its own step and its expect(within(decidedNoRoute).queryByTestId('approval-decision-progress')).toBeNull(); }); }); + +describe('ApprovalDecisionPanel — a decided request says where the approval stands now (objectstack#35863)', () => { + const EN = (builtInLocales as unknown as { en: { approvalsInbox: Record } }).en.approvalsInbox; + const fill = (key: string, vars: Record) => + EN[key].replace(/\{\{(\w+)\}\}/g, (_, name: string) => vars[name] ?? ''); + /** The manager's request, decided at the first step of the reported route. */ + const decidedAtManager = (status: string, outcome: Route['outcome']) => requestRow({ + id: 'areq_mgr', + status, + flow_node_id: 'manager_review', + current_step: 'manager_review', + step_label: MANAGER, + flow_route: { + steps: [{ id: 'manager_review', label: MANAGER, state: status === 'approved' ? 'done' : 'current' }], + ahead: 'decided', + ...(outcome ? { outcome } : {}), + }, + }); + const outcomeLine = (panel: HTMLElement) => within(panel).queryByTestId('approval-step-outcome'); + + it('decided at step 1 while step 2 is pending: the line names step 2 and that it waits on a decision', () => { + const panel = mount(decidedAtManager('approved', { + step: { id: 'finance_only', label: FINANCE }, status: 'pending', ended: false, + })); + const line = outcomeLine(panel); + expect(line).toHaveTextContent(fill('outcomeWaiting', { step: FINANCE })); + // Under the step line, and never one of its steps. + const steps = within(panel).getByLabelText(STEP_LINE_NAME); + expect(steps.compareDocumentPosition(line!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + expect(within(steps).getAllByRole('listitem')).toHaveLength(1); + }); + + it('decided at the last step and the run ended: the line says the approval ended here', () => { + const panel = mount(decidedAtManager('approved', { status: 'approved', ended: true })); + expect(outcomeLine(panel)).toHaveTextContent(EN.outcomeEndedHere); + }); + + it('went on and ended at a later step: the line names that step and its decision', () => { + const panel = mount(decidedAtManager('approved', { + step: { id: 'finance_only', label: FINANCE }, status: 'rejected', ended: true, + })); + expect(outcomeLine(panel)).toHaveTextContent(fill('outcomeEndedAt', { step: FINANCE, decision: EN.statusRejected })); + }); + + it('went on and a later step stands decided while the run goes on: the line names that step and its decision', () => { + const panel = mount(decidedAtManager('approved', { + step: { id: 'finance_only', label: FINANCE }, status: 'returned', ended: false, + })); + expect(outcomeLine(panel)).toHaveTextContent(fill('outcomeNow', { step: FINANCE, decision: EN.statusReturned })); + }); + + it('no outcome served, or an outcome with nothing to say: no line, and the step line as before', () => { + const none = mount(decidedAtManager('approved', undefined)); + expect(outcomeLine(none)).toBeNull(); + expect(within(none).getByLabelText(STEP_LINE_NAME)).toBeTruthy(); + cleanup(); + const notEnded = mount(decidedAtManager('rejected', { status: 'rejected', ended: false })); + expect(outcomeLine(notEnded)).toBeNull(); + }); + + it('a pending route never draws the line, even if an outcome were served', () => { + const panel = mount(requestRow({ + flow_route: { ...SERVED_ROUTE, outcome: { step: { id: 'x', label: 'X' }, status: 'pending', ended: false } }, + })); + expect(within(panel).getByLabelText(STEP_LINE_NAME)).toBeTruthy(); + expect(outcomeLine(panel)).toBeNull(); + }); + + it('every locale pack carries the four outcome rows', () => { + const packs = builtInLocales as unknown as Record }>; + for (const [locale, pack] of Object.entries(packs)) { + for (const key of ['outcomeWaiting', 'outcomeNow', 'outcomeEndedAt', 'outcomeEndedHere']) { + expect(pack.approvalsInbox?.[key], `${locale} approvalsInbox.${key}`).toBeTruthy(); + } + } + }); +}); diff --git a/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.tsx b/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.tsx index b5b68516c52..860f736425c 100644 --- a/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.tsx +++ b/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.tsx @@ -442,6 +442,7 @@ export function ApprovalDecisionPanel({ request, className }: ApprovalDecisionPa const line = { steps: request.flow_route?.steps, decided: request.flow_route?.ahead === 'decided' ? request.status : undefined, + outcome: request.flow_route?.ahead === 'decided' ? request.flow_route.outcome : undefined, }; const hasProgress = stepLineDraws(line) || !!progress || waitsOnAnyone(request); diff --git a/ui/packages/app-shell/src/views/approval-progress/ApprovalStepLine.tsx b/ui/packages/app-shell/src/views/approval-progress/ApprovalStepLine.tsx index 96d67063972..0b248599f88 100644 --- a/ui/packages/app-shell/src/views/approval-progress/ApprovalStepLine.tsx +++ b/ui/packages/app-shell/src/views/approval-progress/ApprovalStepLine.tsx @@ -8,7 +8,7 @@ import * as React from 'react'; import { cn } from '@object-ui/components'; -import { Check, Minus, Undo2, X } from 'lucide-react'; +import { Check, CornerDownRight, Minus, Undo2, X } from 'lucide-react'; import { useObjectTranslation } from '@object-ui/react'; import type { ApprovalRequestLite } from '../../hooks/useRecordApprovals.js'; @@ -37,6 +37,15 @@ import type { ApprovalRequestLite } from '../../hooks/useRecordApprovals.js'; * step in progress. One step is then enough to draw: the first step of a flow, * or a one-step flow, decided, is still the answer to "where did it stop". * + * ## Where the approval stands after it (objectstack#35863) + * + * The decided route stops at the request's own step, so the server adds + * `flow_route.outcome`: the run's latest request past this one and whether the + * run has ended. The caller hands it in as `outcome`, and one line under the + * decided step says it: went on to a later step and waits there, went on and + * stands at that step's decision, went on and ended with it, or ended here. + * Nothing is drawn when the server serves no outcome: the line never guesses. + * * ## Vertical, at every step count (objectui#5554) * * The strip used to be a horizontal row. A row's intrinsic width grows without @@ -58,11 +67,16 @@ import type { ApprovalRequestLite } from '../../hooks/useRecordApprovals.js'; /** One approval step of a request's route: its node id, its label and where it stands. */ export type ApprovalFlowStep = NonNullable['steps'][number]; +/** Where the record's approval stands after a decided request (`flow_route.outcome`). */ +export type ApprovalRouteOutcome = NonNullable['outcome']>; + export interface ApprovalStepLineProps { /** The served route's steps (`flow_route.steps`), in route order. Fewer than two draws nothing, unless `decided`. */ steps: ReadonlyArray | null | undefined; /** The request's status when its route is decided (`flow_route.ahead === 'decided'`); else absent. */ decided?: string; + /** The served outcome past a decided request (`flow_route.outcome`); drawn only with `decided`. */ + outcome?: ApprovalRouteOutcome; } /** Whether {@link ApprovalStepLine} draws anything for these props: the one gate on step count. */ @@ -79,7 +93,7 @@ const DECISION_MARKER: Readonly = ({ steps, decided }) => { +export const ApprovalStepLine: React.FC = ({ steps, decided, outcome }) => { const { t } = useObjectTranslation(); if (!steps || !stepLineDraws({ steps, decided })) return null; // Literal keys, so the call-site i18n gate checks every one. @@ -93,7 +107,24 @@ export const ApprovalStepLine: React.FC = ({ steps, decid default: return null; } }; - return ( + // The line under the decided step, or null when there is nothing to say. + const outcomeText = (o: ApprovalRouteOutcome | undefined): string | null => { + if (!decided || !o) return null; + const decision = decisionWord(o.status); + if (!o.step) { + return o.ended ? String(t('approvalsInbox.outcomeEndedHere', { defaultValue: 'The approval ended here' })) : null; + } + const step = o.step.label; + if (o.status === 'pending') { + return String(t('approvalsInbox.outcomeWaiting', { step, defaultValue: 'Went on to {{step}}, waiting for a decision' })); + } + if (!decision) return null; + return o.ended + ? String(t('approvalsInbox.outcomeEndedAt', { step, decision, defaultValue: 'Went on to {{step}}, then ended: {{decision}}' })) + : String(t('approvalsInbox.outcomeNow', { step, decision, defaultValue: 'Went on to {{step}}: {{decision}}' })); + }; + const after = outcomeText(outcome); + const list = (
    = ({ steps, decid })}
); + if (!after) return list; + // Outside the list, so assistive tech never counts it as a step. + return ( +
+ {list} +

+ + + + {after} +

+
+ ); }; diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index a570d169563..98b7563b35f 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -5427,6 +5427,10 @@ const ar = { actComment: 'تعليق', actSystemNote: 'ملاحظة من النظام', stepProgress: 'خطوات الموافقة', + outcomeWaiting: 'انتقلت إلى {{step}}، بانتظار قرار', + outcomeNow: 'انتقلت إلى {{step}}: {{decision}}', + outcomeEndedAt: 'انتقلت إلى {{step}} ثم انتهت: {{decision}}', + outcomeEndedHere: 'انتهت الموافقة هنا', prevRequest: 'السابق', nextRequest: 'التالي', positionOf: 'الطلب {{index}} من {{total}}', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index bbdddfb1524..526d637a43f 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -4989,6 +4989,10 @@ const de = { actComment: 'Kommentiert', actSystemNote: 'Systemhinweis', stepProgress: 'Genehmigungsschritte', + outcomeWaiting: 'Weiter an {{step}}, wartet auf eine Entscheidung', + outcomeNow: 'Weiter an {{step}}: {{decision}}', + outcomeEndedAt: 'Weiter an {{step}}, dann beendet: {{decision}}', + outcomeEndedHere: 'Die Genehmigung endete hier', prevRequest: 'Zurück', nextRequest: 'Weiter', positionOf: 'Anfrage {{index}} von {{total}}', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 213556e881d..a55b72512b1 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -5965,6 +5965,10 @@ const en = { actComment: 'Commented', actSystemNote: 'System note', stepProgress: 'Approval steps', + outcomeWaiting: 'Went on to {{step}}, waiting for a decision', + outcomeNow: 'Went on to {{step}}: {{decision}}', + outcomeEndedAt: 'Went on to {{step}}, then ended: {{decision}}', + outcomeEndedHere: 'The approval ended here', prevRequest: 'Previous', nextRequest: 'Next', positionOf: 'Request {{index}} of {{total}}', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 02593fd2e78..b4b7f69770b 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -5099,6 +5099,10 @@ const es = { actComment: 'Comentó', actSystemNote: 'Nota del sistema', stepProgress: 'Pasos de aprobación', + outcomeWaiting: 'Pasó a {{step}}, a la espera de una decisión', + outcomeNow: 'Pasó a {{step}}: {{decision}}', + outcomeEndedAt: 'Pasó a {{step}} y terminó: {{decision}}', + outcomeEndedHere: 'La aprobación terminó aquí', prevRequest: 'Anterior', nextRequest: 'Siguiente', positionOf: 'Solicitud {{index}} de {{total}}', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 454eed991ec..8db238ee123 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -5095,6 +5095,10 @@ const fr = { actComment: 'Commentaire', actSystemNote: 'Note du système', stepProgress: 'Étapes d\'approbation', + outcomeWaiting: 'Passée à {{step}}, en attente d\'une décision', + outcomeNow: 'Passée à {{step}} : {{decision}}', + outcomeEndedAt: 'Passée à {{step}}, puis terminée : {{decision}}', + outcomeEndedHere: 'L\'approbation s\'est terminée ici', prevRequest: 'Précédente', nextRequest: 'Suivante', positionOf: 'Demande {{index}} sur {{total}}', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index c30c66763b6..7900bf77b44 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -4991,6 +4991,10 @@ const ja = { actComment: 'コメント', actSystemNote: 'システムからのお知らせ', stepProgress: '承認ステップ', + outcomeWaiting: '「{{step}}」に進み、判断待ちです', + outcomeNow: '「{{step}}」に進みました:{{decision}}', + outcomeEndedAt: '「{{step}}」に進み、承認は終了しました:{{decision}}', + outcomeEndedHere: '承認はここで終了しました', prevRequest: '前へ', nextRequest: '次へ', positionOf: 'リクエスト {{index}} / {{total}} 件', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index a87cf7ba6f5..854f6c1bbdb 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -4988,6 +4988,10 @@ const ko = { actComment: '댓글', actSystemNote: '시스템 안내', stepProgress: '승인 단계', + outcomeWaiting: '{{step}}(으)로 넘어가 결정을 기다리는 중', + outcomeNow: '{{step}}(으)로 넘어감: {{decision}}', + outcomeEndedAt: '{{step}}(으)로 넘어간 뒤 종료됨: {{decision}}', + outcomeEndedHere: '승인이 여기서 종료되었습니다', prevRequest: '이전', nextRequest: '다음', positionOf: '요청 {{total}}개 중 {{index}}번째', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 09d94b638b4..2237161b73f 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -5094,6 +5094,10 @@ const pt = { actComment: 'Comentou', actSystemNote: 'Nota do sistema', stepProgress: 'Etapas de aprovação', + outcomeWaiting: 'Seguiu para {{step}}, aguardando uma decisão', + outcomeNow: 'Seguiu para {{step}}: {{decision}}', + outcomeEndedAt: 'Seguiu para {{step}} e terminou: {{decision}}', + outcomeEndedHere: 'A aprovação terminou aqui', prevRequest: 'Anterior', nextRequest: 'Próxima', positionOf: 'Solicitação {{index}} de {{total}}', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index bbe3e564474..973cd7afb5a 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -5218,6 +5218,10 @@ const ru = { actComment: 'Комментарий', actSystemNote: 'Системное сообщение', stepProgress: 'Шаги согласования', + outcomeWaiting: 'Передано на шаг «{{step}}», ожидает решения', + outcomeNow: 'Передано на шаг «{{step}}»: {{decision}}', + outcomeEndedAt: 'Передано на шаг «{{step}}», затем завершено: {{decision}}', + outcomeEndedHere: 'Согласование завершилось здесь', prevRequest: 'Назад', nextRequest: 'Далее', positionOf: 'Запрос {{index}} из {{total}}', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 97ea9b36f2c..52bffa25ffa 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -5251,6 +5251,10 @@ const zh = { actComment: '评论', actSystemNote: '系统说明', stepProgress: '审批步骤', + outcomeWaiting: '已流转到「{{step}}」,等待审批', + outcomeNow: '已流转到「{{step}}」:{{decision}}', + outcomeEndedAt: '已流转到「{{step}}」,审批结束:{{decision}}', + outcomeEndedHere: '审批在此结束', prevRequest: '上一条', nextRequest: '下一条', positionOf: '第 {{index}} / {{total}} 条请求', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index c16ecda97c7..e4a7ead6eec 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -5251,6 +5251,10 @@ const zhHant = { actComment: '評論', actSystemNote: '系統說明', stepProgress: '審批步驟', + outcomeWaiting: '已流轉到「{{step}}」,等待審批', + outcomeNow: '已流轉到「{{step}}」:{{decision}}', + outcomeEndedAt: '已流轉到「{{step}}」,審批結束:{{decision}}', + outcomeEndedHere: '審批在此結束', prevRequest: '上一條', nextRequest: '下一條', positionOf: '第 {{index}} / {{total}} 條請求',