From ed6613073af35b31e058f3437b62246f14ce3663 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 03:59:10 +0000 Subject: [PATCH 01/11] =?UTF-8?q?feat(automation):=20record-update=20previ?= =?UTF-8?q?ew=20read=20=E2=80=94=20which=20flows=20a=20proposed=20update?= =?UTF-8?q?=20starts=20(#35928)=20[wip]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude-Session: https://claude.ai/code/session_01FEkQ5keqTTiV8ptWFNc6ZF Co-authored-by: Claude --- packages/client/src/index.ts | 20 ++++ packages/runtime/src/dispatcher-plugin.ts | 12 +++ packages/runtime/src/domains/automation.ts | 73 ++++++++++++++- packages/runtime/src/route-ledger.ts | 5 + .../services/service-automation/src/engine.ts | 26 +++++- .../src/record-update-starts.ts | 92 +++++++++++++++++++ .../spec/src/api/automation-api.zod.test.ts | 49 +++++++++- packages/spec/src/api/automation-api.zod.ts | 72 +++++++++++++++ packages/spec/src/automation/index.ts | 3 + .../record-change-trigger-events.ts | 47 ++++++++++ .../spec/src/contracts/automation-service.ts | 48 +++++++++- packages/spec/src/kernel/address-grammar.ts | 2 +- .../src/record-change-trigger.ts | 29 ++---- 13 files changed, 450 insertions(+), 28 deletions(-) create mode 100644 packages/services/service-automation/src/record-update-starts.ts create mode 100644 packages/spec/src/automation/record-change-trigger-events.ts diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index a12d08bc583..4183e63a4c6 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -140,6 +140,9 @@ import { EnsureCustomizationPackageResponse, CloneFlowRequest, CloneFlowResponse, + // [#35928] The record-update preview's request and its payload. + RecordUpdateStartsRequest, + RecordUpdateStartsResponse, ValidateDataIssue, } from '@objectstack/spec/api'; // [#17536] The element the two `/packages` READ doors are declared to serve. @@ -6379,6 +6382,23 @@ export class ObjectStackClient { return this.unwrapResponse(res); }, + /** + * [#35928] Which flows a proposed update of one record would start — + * `POST /automation/_record-starts`, the preview a stage-change confirm + * shows before the reader confirms the save. Answered to a caller who + * can read the record (an unreadable or absent record is 404 + * `RECORD_NOT_FOUND`); each flow is its name, authored label and + * whether it starts an approval. Nothing runs and nothing is written. + */ + listRecordUpdateStarts: async (request: RecordUpdateStartsRequest): Promise => { + const route = this.getRoute('automation'); + const res = await this.fetch(`${this.baseUrl}${route}/_record-starts`, { + method: 'POST', + body: JSON.stringify(request), + }); + return this.unwrapResponse(res); + }, + /** * Enable or disable a PACKAGED flow — one a code package ships. * diff --git a/packages/runtime/src/dispatcher-plugin.ts b/packages/runtime/src/dispatcher-plugin.ts index 47139ceb23f..d3dc598525c 100644 --- a/packages/runtime/src/dispatcher-plugin.ts +++ b/packages/runtime/src/dispatcher-plugin.ts @@ -1894,6 +1894,18 @@ export function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plu } }); + // [#35928] The record-update preview the stage-change confirms + // read; a literal, registered with `/_status` ahead of + // `/automation/:name` for the reason above. + server!.post(`${base}/automation/_record-starts`, async (req: any, res: any) => { + try { + const result = await dispatcher.dispatch('POST', '/automation/_record-starts', deferRequestBody(req), req.query, { request: req }); + sendResult(result, res); + } catch (err: any) { + errorResponse(err, res); + } + }); + server!.get(`${base}/automation/:name`, async (req: any, res: any) => { try { const result = await dispatcher.dispatch('GET', `/automation/${req.params.name}`, undefined, req.query, { request: req }); diff --git a/packages/runtime/src/domains/automation.ts b/packages/runtime/src/domains/automation.ts index 65e6a60badd..1b1b7a4d4b9 100644 --- a/packages/runtime/src/domains/automation.ts +++ b/packages/runtime/src/domains/automation.ts @@ -58,7 +58,7 @@ import { } from '../validation-failure.js'; import { ExecutionStatus, collectFlowGraphs, type FlowNodeParsed } from '@objectstack/spec/automation'; import { nearestName } from '@objectstack/formula'; -import { ListRunsRequestSchema, standardErrorCodeForHttpStatus } from '@objectstack/spec/api'; +import { ListRunsRequestSchema, RecordUpdateStartsRequestSchema, standardErrorCodeForHttpStatus } from '@objectstack/spec/api'; import type { ResumeFailureDetails } from '@objectstack/spec/api'; import { parseEnumParam, parseIntegerParam, parseStringParam } from '../query-param.js'; import { capabilityUnavailable } from './unavailable.js'; @@ -3719,6 +3719,70 @@ export async function classifyResumeResult( }; } +/** [#35928] The record-update preview's literal segment (`NAMESPACE_POSITION_LITERALS.automation`). */ +const RECORD_UPDATE_STARTS_SEGMENT = '_record-starts'; + +/** [#35928] The preview's closed query set: it reads none, so any parameter is refused. */ +const RECORD_UPDATE_STARTS_QUERY_PARAMS: readonly string[] = []; + +/** + * [#35928] `POST /automation/_record-starts` — which flows a proposed update of + * one record would start, for the stage-change confirms (ruling record + * 7073655354: a caller who can read the record sees the flows' labels; hooks + * are never listed; no new capability). + * + * Order: the closed query set, the body (`RecordUpdateStartsRequestSchema`, + * `400 VALIDATION_FAILED` located on the member), then the record, read AS + * THE CALLER through the `/data` door's own read (`callData` `get`): an object + * the caller may not address, or a record they cannot read, answers that + * read's refusal (`404 RECORD_NOT_FOUND` for an unreadable or absent record), + * so this door tells a caller nothing the record read would not. Only then the + * engine, handed the record as read (`previous`) and with the proposed fields + * applied (`record`), and the caller as the writer. An engine without the + * optional member answers 501, never a guess. + */ +async function respondToRecordUpdateStarts( + deps: DomainHandlerDeps, + automationService: unknown, + body: unknown, + query: unknown, + context: HttpProtocolContext, +): Promise { + const queryRefusal = unknownQueryParamRefusalMessage(query, RECORD_UPDATE_STARTS_QUERY_PARAMS); + if (queryRefusal !== undefined) { + return { handled: true, response: deps.error(queryRefusal, 400, { code: 'VALIDATION_ERROR' }) }; + } + const parsed = RecordUpdateStartsRequestSchema.safeParse(body); + if (!parsed.success) { + const fields = fieldsFromZodIssues(parsed.error.issues, body); + const message = `Invalid record-update preview request: ${fields.map((f) => `${f.field}: ${f.message}`).join('; ')}`; + return { handled: true, response: deps.errorFromThrown(validationFailure(message, fields), VALIDATION_FAILED_STATUS) }; + } + const { object, recordId, changes } = parsed.data; + const svc = automationService as Pick; + if (typeof svc.listRecordUpdateStarts !== 'function') return capabilityUnavailable(deps, 'automation'); + let stored: Record; + try { + const read = await callData( + deps, context, 'get', { object, id: recordId }, + context?.dataDriver, context?.environmentId, context?.executionContext, + ); + const row = (read as { record?: unknown } | null | undefined)?.record; + stored = row && typeof row === 'object' ? (row as Record) : {}; + } catch (err) { + return { handled: true, response: deps.errorFromThrown(err, 500) }; + } + const ec: any = (context as any)?.executionContext; + const flows = svc.listRecordUpdateStarts({ + object, + previous: stored, + record: { ...stored, ...changes }, + ...(typeof ec?.userId === 'string' ? { userId: ec.userId } : {}), + ...(typeof ec?.tenantId === 'string' ? { tenantId: ec.tenantId } : {}), + }); + return { handled: true, response: deps.success({ flows }) }; +} + /** * Handles Automation requests * path: sub-path after /automation/ @@ -4346,6 +4410,13 @@ export async function handleAutomationRequest(deps: DomainHandlerDeps, path: str return { handled: true, response: deps.success({ flows: [], total: 0 }) }; } + // [#35928] POST /_record-starts → which flows a proposed update of one + // record would start (`listRecordUpdateStarts`). Underscore-prefixed so no + // flow name can shadow it; ahead of the `/:name` arms for that reason. + if (parts[0] === RECORD_UPDATE_STARTS_SEGMENT && parts.length === 1 && m === 'POST') { + return respondToRecordUpdateStarts(deps, automationService, body, query, context); + } + // Routes with :name if (parts.length >= 1) { const name = parts[0]; diff --git a/packages/runtime/src/route-ledger.ts b/packages/runtime/src/route-ledger.ts index f7f59c8677f..46fc72f4360 100644 --- a/packages/runtime/src/route-ledger.ts +++ b/packages/runtime/src/route-ledger.ts @@ -628,6 +628,11 @@ export const ROUTE_LEDGER: readonly RouteLedgerEntry[] = [ { route: 'GET /automation/connectors/oauth/callback', domain: '/automation', disposition: 'server-only', note: "The authorization server's redirect (ADR-0143 D5). Closed query set: `code`, `state`, `error`, `error_description`, `error_uri`, `iss`; an unknown or repeated one is 400 `VALIDATION_ERROR`. The `state` is taken once and must have been begun by the same user in the same organization, else 400 before any code is exchanged; an `error` answer is 400 naming its registered code only. The code is exchanged with the PKCE verifier and the connection stored; answers the connection's status. 503 when the token endpoint cannot be reached. Same capability gate as the rows above (`manage_connector_connections`): the browser landing here is the administrator's. Pinned in `domains/automation-connector-connection-door.test.ts`" }, { route: 'GET /automation/_status', domain: '/automation', disposition: 'sdk', client: 'automation.getRuntimeStatus' }, + // [#35928] The record-update preview: which flows a proposed update of one record would start. + { route: 'POST /automation/_record-starts', domain: '/automation', disposition: 'sdk', client: 'automation.listRecordUpdateStarts', + requestSchema: 'RecordUpdateStartsRequestSchema', + responseSchema: 'RecordUpdateStartsResponseSchema', + note: "Ruling record 7073655354: a caller who can READ the record is answered the flows the proposed update would start, each as `{ name, label, startsApproval }` — no description, condition, node or link; hooks are never listed (ADR-0077 §2); no new capability. Body `RecordUpdateStartsRequestSchema` (`{ object, recordId, changes }`, closed; 400 `VALIDATION_FAILED` on the member). No query parameter is read, so any is refused 400 `VALIDATION_ERROR`. The record is read AS THE CALLER through the `/data` door's own `get` (`callData`), so an object the caller may not address or a record they cannot read answers that read's refusal (404 `RECORD_NOT_FOUND`, the same as an absent id) and the engine is never asked. The engine (`IAutomationService.listRecordUpdateStarts`) lists enabled flows armed on a record-change trigger of the object whose token binds an update (the spec's `recordChangeTriggerFiresOnUpdate`) and whose start condition holds — the ONE start-condition gate a run passes — for the stored row with `changes` applied against the stored row; a condition it cannot evaluate is not listed; nothing runs or is written. An engine without the optional member answers 501. The domain-wide anonymous floor answers 401 first. Pinned in `domains/automation-record-update-starts.test.ts`" }, { route: 'POST /automation/:name/trigger', domain: '/automation', disposition: 'sdk', client: 'automation.execute' }, { route: 'POST /automation/:name/toggle', domain: '/automation', disposition: 'sdk', client: 'automation.toggle', note: "enablement, and since the 2026-08-23 ruling that enablement is an authoring write, `manage_metadata` gates it — the same `isFlowAuthoringWrite` door as `POST /automation` above, NOT a fourth copy of the policy. The definition-write gate deliberately left this one out as engine state and filed the question; the measurement is what settled it. No organization wall scopes the enabled bit: `toggleFlow` writes the ADR-0126 §7.2 activation ledger first — one deployment-wide `sys_metadata_activation` row per flow, keyed by `(metadata_type, name)`, carrying the flow's package id and no organization column — and only then updates the engine's in-process projection, which `getFlowRuntimeStates()` reads with no caller and no organization; the automation service is ONE instance per environment — so an unentitled tenant org owner switched a shipped flow off and an unrelated tenant in a different organization, plus the platform admin, read it off, in both directions. Disabling a shipped flow is equivalent to deleting it for as long as it stays off, and DELETE was already gated. ⚠️ BREAKING: 200 → 403 for callers without the capability. Fail-closed on an absent executionContext, an absent `systemPermissions` or an empty one, refusing 403 `PERMISSION_DENIED`, with only `isSystem` bypassing; the domain-wide anonymous floor still answers 401 first. The predicate excludes `POST /automation/trigger/:name` so a flow literally NAMED `toggle` keeps its execution door. Pinned in `domains/automation-write-capability-gate.test.ts` and `qa/dogfood/test/automation-toggle-tenant-scope.dogfood.test.ts`" }, diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 87dca9ae423..a8aa97f8a7e 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -10,9 +10,9 @@ import type { FlowFunctionEffect, FlowRunSummary, } from '@objectstack/spec/automation'; -import type { AutomationContext, AutomationResult, ResumeSignal, IAutomationService, RunListResult, ScreenSpec, ScreenFieldSpec, ConnectorSourcePullRequest, ConnectorSourcePullResult, ConnectorCredentialRef, ConnectorCredentialSetRequest, ConnectorCredentialClearRequest, ConnectorConnectionState, ConnectorConnectionRequest, ConnectorConnectionBegin, ConnectorConnectionCallbackRequest, FlowDryRunOptions, FlowDryRunResult } from '@objectstack/spec/contracts'; +import type { AutomationContext, AutomationResult, ResumeSignal, IAutomationService, RunListResult, ScreenSpec, ScreenFieldSpec, ConnectorSourcePullRequest, ConnectorSourcePullResult, ConnectorCredentialRef, ConnectorCredentialSetRequest, ConnectorCredentialClearRequest, ConnectorConnectionState, ConnectorConnectionRequest, ConnectorConnectionBegin, ConnectorConnectionCallbackRequest, FlowDryRunOptions, FlowDryRunResult, RecordUpdateStartsInput } from '@objectstack/spec/contracts'; import type { MetadataActivationWriteOptions } from '@objectstack/core'; -import type { FlowRegistration, FlowRegistrationRefusal, FlowInnerRefusal } from '@objectstack/spec/api'; +import type { FlowRegistration, FlowRegistrationRefusal, FlowInnerRefusal, RecordUpdateStart } from '@objectstack/spec/api'; import { RESUME_AUTHORITY_SERVICE } from '@objectstack/spec/contracts'; import { validateScreenInputs, @@ -132,6 +132,8 @@ import { type ValueEnvelopeRefusal, } from './dag-traversal.js'; import { activeDryRunExecuteNode, dryRun as dryRunBody, type DryRunHost } from './dry-run.js'; +// [#35928] The record-update preview's body. +import { listRecordUpdateStarts, type RecordUpdateStartsHost } from './record-update-starts.js'; // [#25222] The run history's bodies: recording a run's log entry, finishing a // refused run, and reading runs and suspended runs back. Each // `AutomationEngine` method of the same name calls its body. @@ -5964,6 +5966,26 @@ export class AutomationEngine implements IAutomationService { return getFlowRuntimeStates.call(host); } + /** + * [#35928] Which flows a proposed update of one record would start — the + * preview the stage-change confirms show. The contract is + * `IAutomationService.listRecordUpdateStarts`; the body lives in + * ./record-update-starts.ts, over this engine's own arming state and its + * one start-condition gate. + */ + listRecordUpdateStarts(input: RecordUpdateStartsInput): RecordUpdateStart[] { + const host: RecordUpdateStartsHost = { + flows: this.flows, + boundFlowTriggers: this.boundFlowTriggers, + isFlowEnabled: (...a) => this.isFlowEnabled(...a), + resolveTriggerBinding: (...a) => this.resolveTriggerBinding(...a), + seedRunVariables: (...a) => this.seedRunVariables(...a), + evaluateCondition: (...a) => this.evaluateCondition(...a), + flowSlotName: (...a) => this.flowSlotName(...a), + }; + return listRecordUpdateStarts.call(host, input); + } + /** * [#17396 ruled item 6, #18235] The ONE place that decides why a registered * flow is not armed — both the status door ({@link getFlowRuntimeStates}) diff --git a/packages/services/service-automation/src/record-update-starts.ts b/packages/services/service-automation/src/record-update-starts.ts new file mode 100644 index 00000000000..7c9512dce02 --- /dev/null +++ b/packages/services/service-automation/src/record-update-starts.ts @@ -0,0 +1,92 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35928] {@link AutomationEngine.listRecordUpdateStarts}: which flows a + * proposed update of one record would start. The contract is + * `IAutomationService.listRecordUpdateStarts`'s docblock + * (`@objectstack/spec/contracts`); ruling record 7073655354 decided what is + * served and to whom. + * + * Nothing here is a second reading of a live run's rules: + * + * - WHICH flows can start on the write is the engine's own arming state: a + * flow is asked only when it is enabled and armed on a trigger + * (`isFlowEnabled`, `boundFlowTriggers`), of the record-change kind, on + * this object (`resolveTriggerBinding`, the binding the trigger was handed). + * - WHICH writes bind it is the spec's `recordChangeTriggerFiresOnUpdate`, + * the token grammar `@objectstack/trigger-record-change` binds hooks by. + * - WHETHER it starts is `startConditionHolds`, the ONE start-condition gate + * every run attempt passes, over the variables `seedRunVariables` seeds for + * a run (`record`, its flattened fields, `previous`). + * - WHETHER it starts an approval is the presence of an approval node + * (`APPROVAL_NODE_TYPE`, ADR-0019: an approval is a node inside a flow). + * + * A condition that throws (one that reads a field the record does not carry) + * is not listed: the preview names only what it could judge to start, and the + * confirm keeps its generic sentence beside any list it shows. + */ + +import type { FlowParsed } from '@objectstack/spec/automation'; +import { APPROVAL_NODE_TYPE, recordChangeTriggerFiresOnUpdate } from '@objectstack/spec/automation'; +import type { AutomationContext, RecordUpdateStartsInput } from '@objectstack/spec/contracts'; +import type { RecordUpdateStart } from '@objectstack/spec/api'; +import { startConditionHolds } from './dag-traversal.js'; +import type { AutomationEngine, FlowTriggerBinding } from './engine.js'; + +/** The `AutomationEngine` members the preview reads, each typed as the member itself. */ +export interface RecordUpdateStartsHost { + readonly flows: ReadonlyMap; + readonly boundFlowTriggers: ReadonlyMap; + isFlowEnabled(name: string): boolean; + resolveTriggerBinding(name: string): { triggerType: string; binding: FlowTriggerBinding } | undefined; + seedRunVariables(flow: FlowParsed, flowName: string, context: AutomationContext | undefined, runId: string): Map; + evaluateCondition: AutomationEngine['evaluateCondition']; + flowSlotName(key: string): string; +} + +/** The run id a preview's variables carry: no run exists, and none is recorded. */ +const PREVIEW_RUN_ID = 'record-update-preview'; + +/** Whether `flow` holds an approval node, so a run of it starts an approval (ADR-0019). */ +export function flowStartsApproval(flow: FlowParsed): boolean { + return flow.nodes.some((node) => node.type === APPROVAL_NODE_TYPE); +} + +/** The body of {@link AutomationEngine.listRecordUpdateStarts}; the contract's docblock is its contract. */ +export function listRecordUpdateStarts( + this: RecordUpdateStartsHost, + input: RecordUpdateStartsInput, +): RecordUpdateStart[] { + const context: AutomationContext = { + record: input.record, + previous: input.previous, + object: input.object, + event: 'afterUpdate', + ...(typeof input.userId === 'string' && input.userId !== '' ? { userId: input.userId } : {}), + ...(typeof input.tenantId === 'string' && input.tenantId !== '' ? { tenantId: input.tenantId } : {}), + }; + const starts: RecordUpdateStart[] = []; + for (const [key, flow] of this.flows) { + if (!this.isFlowEnabled(key) || !this.boundFlowTriggers.has(key)) continue; + const resolved = this.resolveTriggerBinding(key); + if (resolved?.triggerType !== 'record_change') continue; + if (resolved.binding.object !== input.object) continue; + if (!recordChangeTriggerFiresOnUpdate(resolved.binding.event)) continue; + const startNode = flow.nodes.find((node) => node.type === 'start'); + if (!startNode) continue; + let holds: boolean; + try { + const variables = this.seedRunVariables(flow, key, context, PREVIEW_RUN_ID); + holds = startConditionHolds.call(this, startNode, variables, context); + } catch { + // Not judged: a condition that cannot be evaluated against this + // record is not named as starting (see the module note). + holds = false; + } + if (!holds) continue; + const name = this.flowSlotName(key); + const label = typeof flow.label === 'string' && flow.label.trim() !== '' ? flow.label : name; + starts.push({ name, label, startsApproval: flowStartsApproval(flow) }); + } + return starts; +} diff --git a/packages/spec/src/api/automation-api.zod.test.ts b/packages/spec/src/api/automation-api.zod.test.ts index 45e2bf710c0..1cdb58b37b1 100644 --- a/packages/spec/src/api/automation-api.zod.test.ts +++ b/packages/spec/src/api/automation-api.zod.test.ts @@ -962,13 +962,16 @@ describe('AutomationApiErrorCode', () => { // ========================================== describe('AutomationApiContracts', () => { - it('should define all 9 contract endpoints', () => { + it('should define all 10 contract endpoints', () => { // 9 -> 8: `listFlows` (`GET /api/v1/automation`) retired with its route // (#19543) — flows are listed through `GET /api/v1/meta/flow`. // 8 -> 9: `cloneFlow` (`POST /api/v1/automation/:name/clone`) gained its // request/response schemas (#28149, ADR-0146 D4 "new similar"). - expect(Object.keys(AutomationApiContracts)).toHaveLength(9); + // 9 -> 10: `listRecordUpdateStarts` (`POST /api/v1/automation/_record-starts`), + // the record-update preview the stage-change confirms read (#35928). + expect(Object.keys(AutomationApiContracts)).toHaveLength(10); expect(AutomationApiContracts).toHaveProperty('cloneFlow'); + expect(AutomationApiContracts).toHaveProperty('listRecordUpdateStarts'); }); it('declares no flow-list entry and no GET at the bare /api/v1/automation path', () => { @@ -1000,6 +1003,8 @@ describe('AutomationApiContracts', () => { expect(AutomationApiContracts.toggleFlow.path).toBe('/api/v1/automation/:name/toggle'); expect(AutomationApiContracts.listRuns.path).toBe('/api/v1/automation/:name/runs'); expect(AutomationApiContracts.getRun.path).toBe('/api/v1/automation/:name/runs/:runId'); + expect(AutomationApiContracts.listRecordUpdateStarts.method).toBe('POST'); + expect(AutomationApiContracts.listRecordUpdateStarts.path).toBe('/api/v1/automation/_record-starts'); }); it('should have input and output schemas for all endpoints', () => { @@ -1009,3 +1014,43 @@ describe('AutomationApiContracts', () => { } }); }); + +// ========================================== +// Record Update Starts (#35928) +// ========================================== + +describe('RecordUpdateStarts schemas (#35928)', () => { + it('accepts the proposed update of one record', () => { + const parsed = AutomationApiModule.RecordUpdateStartsRequestSchema.safeParse({ + object: 'showcase_project', + recordId: 'p_1', + changes: { status: 'completed' }, + }); + expect(parsed.success).toBe(true); + }); + + it('refuses a key the request does not declare, and a request without changes', () => { + const extra = AutomationApiModule.RecordUpdateStartsRequestSchema.safeParse({ + object: 'showcase_project', recordId: 'p_1', changes: {}, nodes: true, + }); + expect(extra.success).toBe(false); + expect(extra.error?.issues.map((i) => i.code)).toContain('unrecognized_keys'); + const bare = AutomationApiModule.RecordUpdateStartsRequestSchema.safeParse({ object: 'showcase_project', recordId: 'p_1' }); + expect(bare.success).toBe(false); + }); + + it('answers flows by name, label and approval mark only', () => { + const answer = { + success: true, + data: { flows: [{ name: 'showcase_project_closure', label: 'Project Closure', startsApproval: true }] }, + }; + const parsed = AutomationApiModule.RecordUpdateStartsResponseSchema.parse(answer); + expect(parsed.data.flows[0]).toEqual({ name: 'showcase_project_closure', label: 'Project Closure', startsApproval: true }); + // A served condition or node list is not part of the answer: the parse drops it. + const leaked = AutomationApiModule.RecordUpdateStartsResponseSchema.parse({ + success: true, + data: { flows: [{ name: 'f', label: 'F', startsApproval: false, condition: 'status == "x"', nodes: [] }] }, + }); + expect(Object.keys(leaked.data.flows[0]).sort()).toEqual(['label', 'name', 'startsApproval']); + }); +}); diff --git a/packages/spec/src/api/automation-api.zod.ts b/packages/spec/src/api/automation-api.zod.ts index d1a044400d7..2c098fb3565 100644 --- a/packages/spec/src/api/automation-api.zod.ts +++ b/packages/spec/src/api/automation-api.zod.ts @@ -51,6 +51,7 @@ import { DroppedFieldsEventSchema } from '../data/data-engine.zod'; * POST /api/v1/automation/:name/clone — Copy a flow, switched off, into a package * GET /api/v1/automation/:name/runs — List execution runs * GET /api/v1/automation/:name/runs/:runId — Get single execution run + * POST /api/v1/automation/_record-starts — Flows a proposed record update would start * ``` */ @@ -884,6 +885,71 @@ export type GetRunResponse = z.input; /** Post-parse shape of {@link GetRunResponse} — defaults applied, transforms run (ADR-0122). */ export type GetRunResponseParsed = z.infer; +// ========================================== +// 10a. Record Update Starts (POST /api/v1/automation/_record-starts) +// ========================================== + +/** + * Request of the record-update preview: which flows a proposed update of ONE + * record would start (#35928, ruling record 7073655354). + * + * Read by the stage-change confirms (the list cell's and the record page's), + * which show the reader the flows their save will start before they confirm + * it. `changes` is the proposed write as the confirm would send it — the + * fields it sets and their new values; the record's other fields are read as + * stored. Nothing is written and no flow runs. + * + * Answered to a caller who can read the record: the record is read AS THE + * CALLER, and one the caller cannot read answers `404 RECORD_NOT_FOUND`, the + * same answer as a record id that does not exist. + * + * @example POST /api/v1/automation/_record-starts + * { object: 'showcase_project', recordId: 'p_1', changes: { status: 'completed' } } + */ +export const RecordUpdateStartsRequestSchema = lazySchema(() => z.object({ + object: z.string().min(1).describe('Machine name of the record\'s object.'), + recordId: z.string().min(1).describe('Id of the record the update would write.'), + changes: z.record(z.string(), z.unknown()).describe( + 'The proposed update: each field it sets and its new value. The record\'s other fields are read as stored.', + ), +}).strict()); +export type RecordUpdateStartsRequest = z.input; +export type RecordUpdateStartsRequestParsed = z.infer; + +/** + * One flow the proposed update would start, as an ordinary reader may see it: + * the flow's machine name and display label, and whether it starts an + * approval (the flow holds an approval node, ADR-0019). No description, + * condition or node is served (ruling record 7073655354). Hooks are never + * listed: they are not the business-facing tier (ADR-0077 §2). + */ +export const RecordUpdateStartSchema = lazySchema(() => z.object({ + name: z.string().describe('The flow\'s machine name — the key a client translates its label by (`flows..label`).'), + label: z.string().describe('The flow\'s display label as authored; the flow\'s name when it declares none.'), + startsApproval: z.boolean().describe('Whether the flow contains an approval node, so the update starts an approval.'), +})); +export type RecordUpdateStart = z.input; +export type RecordUpdateStartParsed = z.infer; + +/** + * Response of the record-update preview. + * + * `data.flows` lists the ENABLED flows, armed on a record-update trigger of + * the record's object, whose start condition holds for the record with + * `changes` applied (`record`) against the record as read (`previous`) — + * evaluated by the engine's own start-condition gate, the one a live run + * passes. A flow whose condition cannot be evaluated against that record is + * not listed. Empty when the update starts nothing. + */ +export const RecordUpdateStartsResponseSchema = lazySchema(() => BaseResponseSchema.extend({ + data: z.object({ + flows: z.array(RecordUpdateStartSchema).describe('The flows the update would start, in no promised order.'), + }), +})); +export type RecordUpdateStartsResponse = z.input; +/** Post-parse shape of {@link RecordUpdateStartsResponse} — defaults applied, transforms run (ADR-0122). */ +export type RecordUpdateStartsResponseParsed = z.infer; + // ========================================== // 11. Automation API Error Codes // ========================================== @@ -958,6 +1024,12 @@ export const AutomationApiContracts = { input: CloneFlowRequestSchema, output: CloneFlowResponseSchema, }, + listRecordUpdateStarts: { + method: 'POST' as const, + path: '/api/v1/automation/_record-starts', + input: RecordUpdateStartsRequestSchema, + output: RecordUpdateStartsResponseSchema, + }, listRuns: { method: 'GET' as const, path: '/api/v1/automation/:name/runs', diff --git a/packages/spec/src/automation/index.ts b/packages/spec/src/automation/index.ts index d4033e6e477..2fb5e80cb5f 100644 --- a/packages/spec/src/automation/index.ts +++ b/packages/spec/src/automation/index.ts @@ -98,5 +98,8 @@ export * from './flow-text-slot-template'; // option-collision parse refusal, `translateFlow`, the reference lint and the // i18n extractor alike. export * from './flow-screen-option-key'; +// [#35928] The record-change trigger's token grammar — the one reading of a +// `triggerType` the trigger binds by and the record-update preview asks. +export * from './record-change-trigger-events'; export * from './bpmn-interop.zod'; export * from './bpmn-mapping'; diff --git a/packages/spec/src/automation/record-change-trigger-events.ts b/packages/spec/src/automation/record-change-trigger-events.ts new file mode 100644 index 00000000000..fa905cb0b60 --- /dev/null +++ b/packages/spec/src/automation/record-change-trigger-events.ts @@ -0,0 +1,47 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The record-change trigger's token grammar — which ObjectQL hook events a + * flow start node's `triggerType` binds (#35928). + * + * One reading of the token, read by every party that asks "does this flow + * start on this kind of write": `@objectstack/trigger-record-change` binds the + * hooks it names (`triggerTypeToHookEvents` there delegates here), and the + * automation engine's record-update preview + * (`IAutomationService.listRecordUpdateStarts`) asks it which bound flows a + * proposed update would start. Declared in the spec because neither package + * depends on the other; ⛔ never a second copy of the pattern in either. + */ + +/** The `triggerType` tokens a record-change trigger binds: phase, then operation. */ +const RECORD_CHANGE_TRIGGER_TOKEN = /^record-(before|after)-(create|insert|update|delete|write)$/; + +/** + * Map a flow start node's `triggerType` (e.g. `record-after-update`) to the + * ObjectQL `HookEvent`(s) it binds. Returns a list because one token can bind + * more than one lifecycle event: + * + * - Single ops (`create`/`insert`/`update`/`delete`) → one event, e.g. + * `record-after-update` → `['afterUpdate']`. + * - `write` is the **create-OR-update union** — the two mutations that + * persist field data (delete is deliberately excluded) — so + * `record-after-write` → `['afterInsert', 'afterUpdate']`. + * + * The token is trimmed. Returns `[]` for anything that isn't a + * `record-(before|after)-(create|insert|update|delete|write)` token. + */ +export function recordChangeTriggerHookEvents(triggerType: string | undefined): string[] { + if (!triggerType) return []; + const m = RECORD_CHANGE_TRIGGER_TOKEN.exec(triggerType.trim()); + if (!m) return []; + const phase = m[1]; // 'before' | 'after' + const op = m[2]; // create|insert|update|delete|write + if (op === 'write') return [`${phase}Insert`, `${phase}Update`]; // create OR update + const verb = op === 'create' || op === 'insert' ? 'Insert' : op.charAt(0).toUpperCase() + op.slice(1); + return [`${phase}${verb}`]; // e.g. 'afterUpdate', 'beforeDelete' +} + +/** Whether a `triggerType` token starts its flow on a record UPDATE (`beforeUpdate` or `afterUpdate`). */ +export function recordChangeTriggerFiresOnUpdate(triggerType: string | undefined): boolean { + return recordChangeTriggerHookEvents(triggerType).some((event) => event === 'beforeUpdate' || event === 'afterUpdate'); +} diff --git a/packages/spec/src/contracts/automation-service.ts b/packages/spec/src/contracts/automation-service.ts index 40b387602a9..671c0d9f77c 100644 --- a/packages/spec/src/contracts/automation-service.ts +++ b/packages/spec/src/contracts/automation-service.ts @@ -21,7 +21,7 @@ import type { ConversionNotice, ConversionTodoNotice } from '../conversions/type import type { ExecutionContext } from '../kernel/execution-context.zod'; import type { JobRunTrigger } from './job-service'; import type { FlowRegistration } from '../api/protocol.zod'; -import type { FlowInnerRefusal } from '../api/automation-api.zod'; +import type { FlowInnerRefusal, RecordUpdateStart } from '../api/automation-api.zod'; import type { DroppedFieldsEvent } from '../data/data-engine.zod'; /** @@ -948,6 +948,29 @@ export interface ResumeSignal { [RESUME_AUTHORITY_SERVICE]?: true; } +/** + * [#35928] The input of {@link IAutomationService.listRecordUpdateStarts}: one + * record of `object` as it stands (`previous`) and as the proposed update + * would leave it (`record`, the stored fields with the update's fields + * applied). The caller reads the record; the engine reads nothing. + */ +export interface RecordUpdateStartsInput { + /** Machine name of the record's object. */ + object: string; + /** The record as the proposed update would leave it. */ + record: Record; + /** The record as it stands before the update. */ + previous: Record; + /** + * The user who would write the update — `current_user` in a start + * condition, as the record-change trigger forwards the writer on a live + * save. Absent, `current_user` is `null`. + */ + userId?: string; + /** The writer's active organization, as the trigger forwards it (`current_user.organizationId`). */ + tenantId?: string; +} + /** * One flow's deployment + trigger-binding state, as * {@link IAutomationService.getFlowRuntimeStates} reports it (#4127). @@ -2248,6 +2271,29 @@ export interface IAutomationService { */ getFlowRuntimeStates?(): FlowRuntimeState[]; + /** + * [#35928] Which flows a proposed update of one record would start — the + * preview the stage-change confirms show before the reader confirms the + * save (ruling record 7073655354). + * + * A flow is listed when it is enabled, armed on a record-change trigger of + * `input.object` whose token binds an update (the spec's + * `recordChangeTriggerFiresOnUpdate`, the grammar the trigger binds by), + * and its start condition holds for `input.record` against + * `input.previous`, evaluated by the ONE start-condition gate a live run + * passes. A condition that cannot be evaluated against the record is not + * listed; nothing runs and nothing is written. Each entry carries the + * flow's name, its authored label and whether it holds an approval node + * (ADR-0019); hooks are not flows and are never listed (ADR-0077 §2). + * + * Who may ask is the caller's question, not this method's: the dispatcher + * door reads the record as its caller first. + * + * Optional: an automation implementation without it leaves the door + * answering 501, never a guess. + */ + listRecordUpdateStarts?(input: RecordUpdateStartsInput): RecordUpdateStart[]; + /** * This engine's verdict on ONE flow name — whether it holds a registration * under it, refused the stored flow, or holds nothing (`FlowRegistration`, diff --git a/packages/spec/src/kernel/address-grammar.ts b/packages/spec/src/kernel/address-grammar.ts index 0de2e4c2c58..acfe719f816 100644 --- a/packages/spec/src/kernel/address-grammar.ts +++ b/packages/spec/src/kernel/address-grammar.ts @@ -139,7 +139,7 @@ export interface NamespacePosition { export const NAMESPACE_POSITION_LITERALS: Readonly> = Object.freeze({ automation: Object.freeze({ prefix: '/automation', - literals: Object.freeze(['_status', 'actions', 'connectors', 'hooks', 'trigger']), + literals: Object.freeze(['_record-starts', '_status', 'actions', 'connectors', 'hooks', 'trigger']), }), automationTrigger: Object.freeze({ prefix: '/automation/trigger', literals: Object.freeze([]) }), inboundHook: Object.freeze({ prefix: '/automation/hooks', literals: Object.freeze(['runs']) }), diff --git a/packages/triggers/trigger-record-change/src/record-change-trigger.ts b/packages/triggers/trigger-record-change/src/record-change-trigger.ts index 00f0a8f3bf5..df128f2d852 100644 --- a/packages/triggers/trigger-record-change/src/record-change-trigger.ts +++ b/packages/triggers/trigger-record-change/src/record-change-trigger.ts @@ -2,6 +2,7 @@ import type { AutomationContext } from '@objectstack/spec/contracts'; import type { HookContext } from '@objectstack/spec/data'; +import { recordChangeTriggerHookEvents } from '@objectstack/spec/automation'; import { omitInternalFieldsFromWriteResponse } from '@objectstack/core'; import { decoupleFromEngineState } from './decouple-flow-record.js'; @@ -205,30 +206,16 @@ export function closeSaveNoticeChannel(context: AutomationContext): void { /** * Map a flow start node's `triggerType` (e.g. `record-after-update`) to the - * ObjectQL `HookEvent`(s) it binds. Returns a list because one token can bind - * more than one lifecycle event: + * ObjectQL `HookEvent`(s) it binds — `['afterUpdate']`, or for the + * create-OR-update union `record-after-write` `['afterInsert', 'afterUpdate']`; + * `[]` for any other token. * - * - Single ops (`create`/`insert`/`update`/`delete`) → one event, e.g. - * `record-after-update` → `['afterUpdate']`. - * - `write` is the **create-OR-update union** (#3427) — the two mutations that - * persist field data (delete is deliberately excluded) — so - * `record-after-write` → `['afterInsert', 'afterUpdate']`. This is what lets a - * single flow react to "record created or updated" without duplicating the - * whole definition, mirroring Salesforce's "created or updated" record-trigger - * option and Rails' `after_save`. - * - * Returns `[]` for anything that isn't a - * `record-(before|after)-(create|insert|update|delete|write)` token. + * [#35928] The grammar is the spec's `recordChangeTriggerHookEvents`, the one + * reading the automation engine's record-update preview asks too, so what + * this trigger binds and what the preview lists cannot disagree. */ export function triggerTypeToHookEvents(triggerType: string | undefined): string[] { - if (!triggerType) return []; - const m = /^record-(before|after)-(create|insert|update|delete|write)$/.exec(triggerType.trim()); - if (!m) return []; - const phase = m[1]; // 'before' | 'after' - const op = m[2]; // create|insert|update|delete|write - if (op === 'write') return [`${phase}Insert`, `${phase}Update`]; // create OR update - const verb = op === 'create' || op === 'insert' ? 'Insert' : op.charAt(0).toUpperCase() + op.slice(1); - return [`${phase}${verb}`]; // e.g. 'afterUpdate', 'beforeDelete' + return recordChangeTriggerHookEvents(triggerType); } /** From 4097c6d1abb70311481b4e8ca52a5754a3b8f649 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 04:05:25 +0000 Subject: [PATCH 02/11] test(automation): pin the record-update preview's engine and door (#35928) [wip] Claude-Session: https://claude.ai/code/session_01FEkQ5keqTTiV8ptWFNc6ZF Co-authored-by: Claude --- .../runtime/src/domains/automation-address.ts | 2 + .../automation-record-update-starts.test.ts | 143 ++++++++++++++++++ .../src/record-update-starts.test.ts | 113 ++++++++++++++ .../src/record-update-starts.ts | 5 +- packages/spec/authorable-surface/api.json | 10 ++ packages/spec/json-schema.manifest/api.json | 3 + packages/spec/src/api/automation-api.zod.ts | 2 +- 7 files changed, 274 insertions(+), 4 deletions(-) create mode 100644 packages/runtime/src/domains/automation-record-update-starts.test.ts create mode 100644 packages/services/service-automation/src/record-update-starts.test.ts diff --git a/packages/runtime/src/domains/automation-address.ts b/packages/runtime/src/domains/automation-address.ts index 5269b173f68..fb4f44264fb 100644 --- a/packages/runtime/src/domains/automation-address.ts +++ b/packages/runtime/src/domains/automation-address.ts @@ -399,6 +399,8 @@ export function automationRouteAllow(parts: readonly string[]): string[] { switch (parts.length) { case 1: for (const verb of ['GET', 'PUT', 'DELETE']) allow.add(verb); + // [#35928] The record-update preview, a literal a flow name never spells. + if (a === '_record-starts') allow.add('POST'); break; case 2: if (a === 'trigger') allow.add('POST'); diff --git a/packages/runtime/src/domains/automation-record-update-starts.test.ts b/packages/runtime/src/domains/automation-record-update-starts.test.ts new file mode 100644 index 00000000000..8cca9afdd91 --- /dev/null +++ b/packages/runtime/src/domains/automation-record-update-starts.test.ts @@ -0,0 +1,143 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35928] `POST /automation/_record-starts` — the record-update preview the + * stage-change confirms read (ruling record 7073655354). + * + * The door is answered to a caller who can READ the record: the record is read + * as the caller through the `/data` door's own `get` (`callData`), so a record + * the caller cannot read answers that read's `404 RECORD_NOT_FOUND` and the + * engine is never asked. The engine is handed the record as read (`previous`), + * the record with the proposed fields applied (`record`) and the caller as the + * writer; its answer is served as `data.flows`, parsed through the declared + * response schema. Pinned both ways: refusals never reach the engine, and an + * admitted call hands the engine exactly the record it read. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { recordNotFoundError } from '@objectstack/core'; +import { RecordUpdateStartsResponseSchema } from '@objectstack/spec/api'; +import type { RecordUpdateStartsInput } from '@objectstack/spec/contracts'; + +import { HttpDispatcher } from '../http-dispatcher.js'; + +const STORED = { id: 'p1', status: 'active', name: 'Apollo' }; +const CLOSURE = { name: 'project_closure', label: 'Project Closure', startsApproval: true }; + +function makeDispatcher(opts: { withPreview?: boolean; readable?: boolean } = {}) { + const listRecordUpdateStarts = vi.fn((input: RecordUpdateStartsInput) => + input.record.status === 'completed' ? [CLOSURE] : []); + // The caller-scoped read the `/data` door makes. An id the caller cannot + // read is refused as an id naming no row (the protocol's own error). + const getData = vi.fn(async ({ object, id }: any) => { + if (opts.readable === false || id !== STORED.id) throw recordNotFoundError(object, id); + return { object, id, record: { ...STORED } }; + }); + const automation: Record = { handlerReady: true, execute: vi.fn(), getFlow: vi.fn() }; + if (opts.withPreview !== false) automation.listRecordUpdateStarts = listRecordUpdateStarts; + const services: Record = { automation, protocol: { getData } }; + const resolve = (name: string) => services[name]; + const kernel: any = { getService: resolve, getServiceAsync: async (name: string) => resolve(name), context: { getService: resolve } }; + return { dispatcher: new HttpDispatcher(kernel), listRecordUpdateStarts, getData }; +} + +const MEMBER = () => ({ request: {}, executionContext: { userId: 'u_member', tenantId: 'org_1', systemPermissions: [] } }) as any; +const ANONYMOUS = () => ({ request: {}, executionContext: {} }) as any; +const BODY = { object: 'project', recordId: 'p1', changes: { status: 'completed' } }; + +describe('POST /automation/_record-starts (#35928)', () => { + it('answers a member who can read the record the flows the change would start', async () => { + const { dispatcher, listRecordUpdateStarts, getData } = makeDispatcher(); + + const result = await dispatcher.handleAutomation('/_record-starts', 'POST', BODY, MEMBER()); + + expect(result.response?.status).toBe(200); + const parsed = RecordUpdateStartsResponseSchema.parse(result.response?.body); + expect(parsed.data.flows).toEqual([CLOSURE]); + // The record was read as the caller, and the engine handed exactly that read. + expect(getData).toHaveBeenCalledWith(expect.objectContaining({ object: 'project', id: 'p1', context: expect.objectContaining({ userId: 'u_member' }) })); + expect(listRecordUpdateStarts).toHaveBeenCalledWith({ + object: 'project', + previous: STORED, + record: { ...STORED, status: 'completed' }, + userId: 'u_member', + tenantId: 'org_1', + }); + }); + + it('answers an empty list for a change that starts nothing', async () => { + const { dispatcher } = makeDispatcher(); + + const result = await dispatcher.handleAutomation('/_record-starts', 'POST', { ...BODY, changes: { status: 'on_hold' } }, MEMBER()); + + expect(result.response?.status).toBe(200); + expect(result.response?.body?.data).toEqual({ flows: [] }); + }); + + it('refuses a caller who cannot read the record 404 RECORD_NOT_FOUND, and never asks the engine', async () => { + const { dispatcher, listRecordUpdateStarts } = makeDispatcher({ readable: false }); + + const result = await dispatcher.handleAutomation('/_record-starts', 'POST', BODY, MEMBER()); + + expect(result.response?.status).toBe(404); + expect(result.response?.body?.error?.code).toBe('RECORD_NOT_FOUND'); + expect(listRecordUpdateStarts).not.toHaveBeenCalled(); + }); + + it('answers an unreadable record and an absent one alike', async () => { + const unreadable = await makeDispatcher({ readable: false }).dispatcher.handleAutomation('/_record-starts', 'POST', BODY, MEMBER()); + const absent = await makeDispatcher().dispatcher.handleAutomation('/_record-starts', 'POST', { ...BODY, recordId: 'p_absent' }, MEMBER()); + const shape = (r: any) => ({ status: r.response?.status, code: r.response?.body?.error?.code }); + expect(shape(unreadable)).toEqual(shape(absent)); + }); + + it('refuses an anonymous caller 401 before any read', async () => { + const { dispatcher, getData, listRecordUpdateStarts } = makeDispatcher(); + + const result = await dispatcher.handleAutomation('/_record-starts', 'POST', BODY, ANONYMOUS()); + + expect(result.response?.status).toBe(401); + expect(getData).not.toHaveBeenCalled(); + expect(listRecordUpdateStarts).not.toHaveBeenCalled(); + }); + + it('refuses a malformed body 400 VALIDATION_FAILED on the member, before any read', async () => { + const { dispatcher, getData } = makeDispatcher(); + + const missing = await dispatcher.handleAutomation('/_record-starts', 'POST', { object: 'project', recordId: 'p1' }, MEMBER()); + expect(missing.response?.status).toBe(400); + expect(missing.response?.body?.error?.code).toBe('VALIDATION_FAILED'); + expect(JSON.stringify(missing.response?.body)).toContain('changes'); + + const extra = await dispatcher.handleAutomation('/_record-starts', 'POST', { ...BODY, nodes: true }, MEMBER()); + expect(extra.response?.status).toBe(400); + expect(extra.response?.body?.error?.code).toBe('VALIDATION_FAILED'); + expect(getData).not.toHaveBeenCalled(); + }); + + it('refuses any query parameter 400 VALIDATION_ERROR, before any read', async () => { + const { dispatcher, getData } = makeDispatcher(); + + const result = await dispatcher.handleAutomation('/_record-starts', 'POST', BODY, MEMBER(), { debug: '1' }); + + expect(result.response?.status).toBe(400); + expect(result.response?.body?.error?.code).toBe('VALIDATION_ERROR'); + expect(getData).not.toHaveBeenCalled(); + }); + + it('answers 501 on an engine without the preview, never a guessed empty list', async () => { + const { dispatcher } = makeDispatcher({ withPreview: false }); + + const result = await dispatcher.handleAutomation('/_record-starts', 'POST', BODY, MEMBER()); + + expect(result.response?.status).toBe(501); + }); + + it('is not read as a flow name: a GET of the literal is not this door', async () => { + const { dispatcher, listRecordUpdateStarts } = makeDispatcher(); + + await dispatcher.handleAutomation('/_record-starts', 'GET', undefined, MEMBER()); + + expect(listRecordUpdateStarts).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/services/service-automation/src/record-update-starts.test.ts b/packages/services/service-automation/src/record-update-starts.test.ts new file mode 100644 index 00000000000..4dddaeb5440 --- /dev/null +++ b/packages/services/service-automation/src/record-update-starts.test.ts @@ -0,0 +1,113 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// [#35928] `AutomationEngine.listRecordUpdateStarts` — which flows a proposed +// update of one record would start (ruling record 7073655354): enabled, +// armed record-change flows of the object whose token binds an update and +// whose start condition holds, through the engine's one start-condition gate; +// each served as `{ name, label, startsApproval }`. + +import { describe, it, expect, beforeEach } from 'vitest'; +import { AutomationEngine } from './engine.js'; +import type { FlowTrigger } from './engine.js'; +import { withLoaderSetFromPull } from './loader-set.test-support.js'; + +function createTestLogger() { + return { + info: () => {}, + warn: () => {}, + error: () => {}, + debug: () => {}, + child: () => createTestLogger(), + } as any; +} + +const recordChangeTrigger: FlowTrigger = { type: 'record_change', start() {}, stop() {} }; + +function updateFlow( + name: string, + start: Record, + options: { label?: string; approval?: boolean } = {}, +) { + const middle = options.approval + ? [{ id: 'review', type: 'approval' as const, label: 'Review', config: { approvers: [{ type: 'user', value: 'u1' }] } }] + : []; + const chain = ['start', ...middle.map((n) => n.id), 'end']; + return { + name, + label: options.label ?? name, + type: 'autolaunched' as const, + nodes: [ + { id: 'start', type: 'start' as const, label: 'Start', config: { objectName: 'project', triggerType: 'record-after-update', ...start } }, + ...middle, + { id: 'end', type: 'end' as const, label: 'End' }, + ], + edges: chain.slice(1).map((target, i) => ({ id: `e${i}`, source: chain[i], target })), + }; +} + +const STORED = { id: 'p1', status: 'active', health: 'green' }; + +describe('AutomationEngine.listRecordUpdateStarts (#35928)', () => { + let engine: AutomationEngine; + + beforeEach(() => { + engine = withLoaderSetFromPull(new AutomationEngine(createTestLogger())); + // The approval node's executor stands in for plugin-approvals' own. + engine.registerNodeExecutor({ type: 'approval', async execute() { return { success: true }; } }); + engine.registerTrigger(recordChangeTrigger); + }); + + const ask = (changes: Record) => + engine.listRecordUpdateStarts({ object: 'project', previous: { ...STORED }, record: { ...STORED, ...changes } }); + + it('names a flow whose start condition holds for the proposed change, by name and label', async () => { + engine.registerFlow('closure', updateFlow('closure', { condition: 'status == "completed" && previous.status != "completed"' }, { label: 'Project Closure' })); + expect(ask({ status: 'completed' })).toEqual([{ name: 'closure', label: 'Project Closure', startsApproval: false }]); + }); + + it('does not name a flow whose start condition does not hold', async () => { + engine.registerFlow('closure', updateFlow('closure', { condition: 'status == "completed" && previous.status != "completed"' })); + expect(ask({ status: 'on_hold' })).toEqual([]); + }); + + it('marks a flow holding an approval node as starting an approval — and only that one (CONTROL)', async () => { + engine.registerFlow('signoff', updateFlow('signoff', { condition: 'status == "completed"' }, { approval: true })); + engine.registerFlow('notify', updateFlow('notify', { condition: 'status == "completed"' })); + const starts = ask({ status: 'completed' }); + expect(starts.find((s) => s.name === 'signoff')?.startsApproval).toBe(true); + expect(starts.find((s) => s.name === 'notify')?.startsApproval).toBe(false); + }); + + it('names a flow with no condition on every update', async () => { + engine.registerFlow('every_update', updateFlow('every_update', {}, { label: 'Every Update' })); + expect(ask({ health: 'red' })).toEqual([{ name: 'every_update', label: 'Every Update', startsApproval: false }]); + }); + + it('binds update tokens only: a create, a delete, another object or a disabled flow is never named', async () => { + engine.registerFlow('on_create', updateFlow('on_create', { triggerType: 'record-after-create' })); + engine.registerFlow('on_delete', updateFlow('on_delete', { triggerType: 'record-before-delete' })); + engine.registerFlow('other_object', updateFlow('other_object', { objectName: 'task' })); + engine.registerFlow('switched_off', { ...updateFlow('switched_off', {}), status: 'obsolete' } as any); + engine.registerFlow('on_write', updateFlow('on_write', { triggerType: 'record-before-write' })); + expect(ask({ status: 'completed' }).map((s) => s.name)).toEqual(['on_write']); + }); + + it('does not name a flow whose condition cannot be evaluated against the record', async () => { + engine.registerFlow('reads_missing', updateFlow('reads_missing', { condition: 'record.no_such_field == "x"' })); + expect(ask({ status: 'completed' })).toEqual([]); + }); + + it('answers nothing for a flow the engine holds but has not armed (no record-change trigger)', async () => { + const bare = withLoaderSetFromPull(new AutomationEngine(createTestLogger())); + bare.registerFlow('closure', updateFlow('closure', {})); + expect(bare.listRecordUpdateStarts({ object: 'project', previous: STORED, record: STORED })).toEqual([]); + }); + + it('evaluates `current_user` as the writer the caller names', async () => { + engine.registerFlow('mine', updateFlow('mine', { condition: 'current_user.id == "u_writer"' })); + const asWriter = engine.listRecordUpdateStarts({ object: 'project', previous: STORED, record: STORED, userId: 'u_writer' }); + const asOther = engine.listRecordUpdateStarts({ object: 'project', previous: STORED, record: STORED, userId: 'u_other' }); + expect(asWriter.map((s) => s.name)).toEqual(['mine']); + expect(asOther).toEqual([]); + }); +}); diff --git a/packages/services/service-automation/src/record-update-starts.ts b/packages/services/service-automation/src/record-update-starts.ts index 7c9512dce02..a79899bdd3e 100644 --- a/packages/services/service-automation/src/record-update-starts.ts +++ b/packages/services/service-automation/src/record-update-starts.ts @@ -84,9 +84,8 @@ export function listRecordUpdateStarts( holds = false; } if (!holds) continue; - const name = this.flowSlotName(key); - const label = typeof flow.label === 'string' && flow.label.trim() !== '' ? flow.label : name; - starts.push({ name, label, startsApproval: flowStartsApproval(flow) }); + // `label` is required by `FlowSchema`, so every registered flow carries one. + starts.push({ name: this.flowSlotName(key), label: flow.label, startsApproval: flowStartsApproval(flow) }); } return starts; } diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index 7859f267dd9..62d0f32951b 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -1658,6 +1658,16 @@ "api/RecordPageTimelineRequest:activity", "api/RecordPageTimelineRequest:discussion", "api/RecordPageTimelineRequest:fieldChanges", + "api/RecordUpdateStart:label", + "api/RecordUpdateStart:name", + "api/RecordUpdateStart:startsApproval", + "api/RecordUpdateStartsRequest:changes", + "api/RecordUpdateStartsRequest:object", + "api/RecordUpdateStartsRequest:recordId", + "api/RecordUpdateStartsResponse:data", + "api/RecordUpdateStartsResponse:error", + "api/RecordUpdateStartsResponse:meta", + "api/RecordUpdateStartsResponse:success", "api/RefreshTokenRequest:refreshToken", "api/RegisterDeviceRequest:appId", "api/RegisterDeviceRequest:deviceId", diff --git a/packages/spec/json-schema.manifest/api.json b/packages/spec/json-schema.manifest/api.json index 71466d7487f..50b66c14438 100644 --- a/packages/spec/json-schema.manifest/api.json +++ b/packages/spec/json-schema.manifest/api.json @@ -415,6 +415,9 @@ "api/RecordPageStreamRows", "api/RecordPageTimelineCount", "api/RecordPageTimelineRequest", + "api/RecordUpdateStart", + "api/RecordUpdateStartsRequest", + "api/RecordUpdateStartsResponse", "api/RefreshTokenRequest", "api/RegisterDeviceRequest", "api/RegisterDeviceResponse", diff --git a/packages/spec/src/api/automation-api.zod.ts b/packages/spec/src/api/automation-api.zod.ts index 2c098fb3565..cb78c5341f5 100644 --- a/packages/spec/src/api/automation-api.zod.ts +++ b/packages/spec/src/api/automation-api.zod.ts @@ -925,7 +925,7 @@ export type RecordUpdateStartsRequestParsed = z.infer z.object({ name: z.string().describe('The flow\'s machine name — the key a client translates its label by (`flows..label`).'), - label: z.string().describe('The flow\'s display label as authored; the flow\'s name when it declares none.'), + label: z.string().describe('The flow\'s display label as authored (a client translates it by `name`).'), startsApproval: z.boolean().describe('Whether the flow contains an approval node, so the update starts an approval.'), })); export type RecordUpdateStart = z.input; From f71ac223349bbecd8138290bdd54019bc1a89140 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 04:31:11 +0000 Subject: [PATCH 03/11] feat(console): the stage confirms name the flows a move would start (#35928) The list cell's state-machine confirm and the record page's stage confirm (path press and header stage menu) read one shared hook in plugin-detail, useRecordUpdateStarts, and draw StageChangeStarts under their sentence. activeFlowsBundle moves from app-shell into @object-ui/i18n so the confirms translate flow labels as the flow runner does. Changesets and docs. Claude-Session: https://claude.ai/code/session_01FEkQ5keqTTiV8ptWFNc6ZF Co-authored-by: Claude --- .changeset/35928-record-update-starts-read.md | 20 ++ .changeset/35928-stage-confirm-names-flows.md | 20 ++ content/docs/automation/flows.mdx | 38 ++++ content/docs/frontend/plugins/plugin-grid.mdx | 10 +- .../app-shell/src/views/FlowRunner.tsx | 4 +- .../previews/FlowCanvas.test.tsx | 2 +- .../previews/flow-label-translations.tsx | 2 +- .../fields/src/RequiredFieldsDialog.tsx | 9 + .../src/utils => i18n/src}/flowsBundle.ts | 19 +- ui/packages/i18n/src/index.ts | 10 + ui/packages/i18n/src/locales/ar.ts | 2 + ui/packages/i18n/src/locales/de.ts | 2 + ui/packages/i18n/src/locales/en.ts | 2 + ui/packages/i18n/src/locales/es.ts | 2 + ui/packages/i18n/src/locales/fr.ts | 2 + ui/packages/i18n/src/locales/ja.ts | 2 + ui/packages/i18n/src/locales/ko.ts | 2 + ui/packages/i18n/src/locales/pt-BR.ts | 2 + ui/packages/i18n/src/locales/ru.ts | 2 + ui/packages/i18n/src/locales/zh-Hans.ts | 2 + ui/packages/i18n/src/locales/zh-Hant.ts | 2 + .../__tests__/RecordStageMenu-35891.test.tsx | 12 +- .../stageChangeStarts-35928.test.tsx | 203 +++++++++++++++++ .../stageChangeStarts-label-35928.test.tsx | 60 +++++ ui/packages/plugin-detail/src/index.tsx | 4 + .../record-path.stageChange-28199.test.tsx | 12 +- .../src/renderers/recordPathStageChange.tsx | 18 ++ .../plugin-detail/src/stageChangeStarts.tsx | 127 +++++++++++ .../plugin-detail/src/useDetailTranslation.ts | 4 + ui/packages/plugin-grid/src/ObjectGrid.tsx | 10 + .../ObjectGrid.stageStarts-35928.test.tsx | 207 ++++++++++++++++++ .../plugin-grid/src/objectGridStateConfirm.ts | 9 +- 32 files changed, 804 insertions(+), 18 deletions(-) create mode 100644 .changeset/35928-record-update-starts-read.md create mode 100644 .changeset/35928-stage-confirm-names-flows.md rename ui/packages/{app-shell/src/utils => i18n/src}/flowsBundle.ts (77%) create mode 100644 ui/packages/plugin-detail/src/__tests__/stageChangeStarts-35928.test.tsx create mode 100644 ui/packages/plugin-detail/src/__tests__/stageChangeStarts-label-35928.test.tsx create mode 100644 ui/packages/plugin-detail/src/stageChangeStarts.tsx create mode 100644 ui/packages/plugin-grid/src/__tests__/ObjectGrid.stageStarts-35928.test.tsx diff --git a/.changeset/35928-record-update-starts-read.md b/.changeset/35928-record-update-starts-read.md new file mode 100644 index 00000000000..fe05ae61fd5 --- /dev/null +++ b/.changeset/35928-record-update-starts-read.md @@ -0,0 +1,20 @@ +--- +'@objectstack/spec': patch +'@objectstack/service-automation': patch +'@objectstack/trigger-record-change': patch +'@objectstack/runtime': patch +'@objectstack/client': patch +--- + +feat(automation): `POST /api/v1/automation/_record-starts` answers which flows a proposed update of one record would start + +Clause-②: yes (widening) — one new public read: the route `POST /api/v1/automation/_record-starts` (`automation.listRecordUpdateStarts` in the API contract and in `@objectstack/client`); `@objectstack/spec/api` adds `RecordUpdateStartsRequestSchema`, `RecordUpdateStartSchema`, `RecordUpdateStartsResponseSchema` and their types; `@objectstack/spec/contracts` adds `RecordUpdateStartsInput` and the optional `IAutomationService.listRecordUpdateStarts`; `@objectstack/spec/automation` adds `recordChangeTriggerHookEvents` and `recordChangeTriggerFiresOnUpdate`; `_record-starts` joins the `/automation` domain's reserved position literals. Nothing existing is removed or re-typed. +Metadata-protocol: none +Skills-docs: none — no skill under `skills/**` teaches the console's stage confirms; `content/docs/automation/flows.mdx` gains the read in this change. + +The console's stage confirms now name the flows a move would start (objectstack#35928, ruling record 7073655354). They ask the server: + +- **Request** `{ object, recordId, changes }`; **response** `{ success, data: { flows: [{ name, label, startsApproval }] } }`. +- **Who is answered:** a signed-in caller who can read the record. The record is read as the caller through the `/data` door's own `get`, so a record they cannot read answers `404 RECORD_NOT_FOUND` exactly as an absent one, and the engine is never asked. Anonymous `401`; a malformed body `400 VALIDATION_FAILED`; any query parameter `400 VALIDATION_ERROR`; an engine without the read `501`. +- **Which flows:** enabled `record_change` flows of the object, armed on their trigger, whose `triggerType` binds an update, and whose start condition holds for the record read with `changes` applied (`previous` is the record read). The condition goes through the engine's one start-condition gate, the one every run passes; the token grammar `@objectstack/trigger-record-change` binds hooks by moved into the spec (`recordChangeTriggerHookEvents`) so the preview reads the same rule, with no second copy. A condition that cannot be evaluated against the record is not listed. Hooks are never listed. +- **Per flow:** `name`, the authored `label` (a client translates it by name) and `startsApproval`, true for a flow holding an `approval` node (ADR-0019). No description, condition or nodes. diff --git a/.changeset/35928-stage-confirm-names-flows.md b/.changeset/35928-stage-confirm-names-flows.md new file mode 100644 index 00000000000..735e46ee1c7 --- /dev/null +++ b/.changeset/35928-stage-confirm-names-flows.md @@ -0,0 +1,20 @@ +--- +'@object-ui/plugin-detail': patch +'@object-ui/plugin-grid': patch +'@object-ui/fields': patch +'@object-ui/i18n': patch +'@object-ui/app-shell': patch +--- + +feat(console): a stage confirm names the flows the move would start, in the list cell and on the record page + +Clause-②: yes (widening) — `@object-ui/plugin-detail` adds the exports `useRecordUpdateStarts`, `StageChangeStarts`, `RECORD_UPDATE_STARTS_PATH` and the type `RecordUpdateStartsAsk`; `@object-ui/fields`' `RequiredFieldsDialog` takes an optional `notice`; `@object-ui/i18n` adds the export `activeFlowsBundle` (with the types `FlowsTranslation` and `TranslationResourceReader`, moved from `@object-ui/app-shell`'s internal `utils/flowsBundle`) and two keys to every pack: `detail.stageChangeStartsHeading`, `detail.stageChangeStartsApproval`. `@object-ui/plugin-grid`'s `StateChangeConfirm` gains an optional `ask`. Nothing existing is removed or re-typed. +Metadata-protocol: none +Skills-docs: none — no skill under `skills/**` teaches the console's stage confirms; `content/docs/frontend/plugins/plugin-grid.mdx` names the list in this change. + +When a stage move would start a flow, its confirm now says so (objectstack#35928, ruling record 7073655354): + +- The list cell's state-machine confirm and the record page's stage confirm (the path's press and the header's stage menu) keep their sentence and add, under it, 「保存后将启动以下流程:」 ("Saving this change starts these flows:") and each flow by its label in the reader's language. A flow that starts an approval is marked 「发起审批」 ("starts an approval"). +- Both confirms ask one read, `POST /api/v1/automation/_record-starts`, through one shared hook, so the two surfaces cannot disagree. The server decides which flows start; nothing is judged in the browser. +- A move that starts nothing shows no list, and a read that fails or is refused leaves the confirm exactly as it was. +- A flow label is translated as the flow runner translates it: the app's `flows` translations, read through `activeFlowsBundle`, which now lives in `@object-ui/i18n` so the confirms' packages can read it; the console's flow runner and designer import it from there. diff --git a/content/docs/automation/flows.mdx b/content/docs/automation/flows.mdx index 47eb58a851d..f03767f184a 100644 --- a/content/docs/automation/flows.mdx +++ b/content/docs/automation/flows.mdx @@ -2586,6 +2586,44 @@ uncached one: it is read live on every call and kept out of the ETag, so a read that carries it is always answered in full, never with `304 Not Modified`. It is the verdict of the engine in the process that answered. +### Which flows a record update would start + +`POST /api/v1/automation/_record-starts` answers, before anything is written, +which flows a proposed update of one record would start. The console's stage +confirms read it: the list cell's state-machine confirm and the record page's +stage confirm name those flows under their sentence (objectstack#35928). + +```json +// request +{ "object": "project", "recordId": "p1", "changes": { "status": "completed" } } +// response +{ "success": true, "data": { "flows": [ + { "name": "project_closure", "label": "Project Closure", "startsApproval": true } +] } } +``` + +- **Who is answered:** any signed-in caller who can read the record. The + record is read as the caller, through the `/data` door's own `get`, so a + record they cannot read answers `404 RECORD_NOT_FOUND` exactly as one that + does not exist. An anonymous call is refused `401`, a malformed body `400 + VALIDATION_FAILED`, any query parameter `400 VALIDATION_ERROR`, and an engine + without the read `501`. +- **Which flows:** enabled `record_change` flows of that object, armed on their + trigger, whose `triggerType` binds an update (`record-…-update` or + `record-…-write`), and whose start `condition` holds for the record with + `changes` applied, with `previous` as the record read. The condition is judged + by the same gate every run passes, on the record as the caller reads it. A + condition that cannot be evaluated against it is not listed. Hooks are never + listed. +- **What is served per flow:** its `name`, its authored `label` (a client + translates it by `name`, as it translates any flow label) and + `startsApproval`, true when the flow holds an `approval` node. No + description, condition or nodes. + +The answer is a preview, not a promise: the write itself is judged when it +happens, and a condition that reads a field the caller cannot see is judged +here on what the caller sees. + ## Expressions in flows A flow computes with **one expression dialect, CEL**: every condition is bare diff --git a/content/docs/frontend/plugins/plugin-grid.mdx b/content/docs/frontend/plugins/plugin-grid.mdx index 8db647681dd..b7f6d186f56 100644 --- a/content/docs/frontend/plugins/plugin-grid.mdx +++ b/content/docs/frontend/plugins/plugin-grid.mdx @@ -479,8 +479,14 @@ row whose new value would sort it elsewhere stays in place until the next load confirm that names the field and both values and says saving may trigger related automation ("Status changes from On Hold to Active. Saving may trigger related automation."). Cancel writes nothing and the cell keeps the - value it had; Change saves it as any commit is saved. The confirm does not - list the flows. A host asks this through `GridCellSelection.confirmCommit`. + value it had; Change saves it as any commit is saved. Under that sentence the + confirm names the flows the move would start, each by its label in the + reader's language and a flow that starts an approval marked so, as the + server's `POST /api/v1/automation/_record-starts` answers them (the record + page's stage confirm reads the same answer, through `@object-ui/plugin-detail`'s + `useRecordUpdateStarts`). A read that fails or names no flow leaves the + sentence alone (objectstack#35928). A host asks this through + `GridCellSelection.confirmCommit`. - **A change that makes other fields required asks for them** (objectstack#35956). When the new value makes a field's `requiredWhen` true while that field is still empty (a win reason on "Won", say), nothing is written yet: a dialog diff --git a/ui/packages/app-shell/src/views/FlowRunner.tsx b/ui/packages/app-shell/src/views/FlowRunner.tsx index c22bcf22da4..5d844bb5346 100644 --- a/ui/packages/app-shell/src/views/FlowRunner.tsx +++ b/ui/packages/app-shell/src/views/FlowRunner.tsx @@ -158,7 +158,7 @@ * launch hosts alike. * * WHERE the bundle comes from is the channel the console already has: - * `activeFlowsBundle` (`utils/flowsBundle`) reads the `flows` group back out + * `activeFlowsBundle` (`@object-ui/i18n`) reads the `flows` group back out * of the i18next resource tree the provider loaded, for the active language. * There is no second loader. * @@ -349,7 +349,7 @@ import { } from './ScreenView.js'; import { flowSuccessCopy, interpretFlowResponse } from '../utils/flowResponse.js'; import { announceFlowDroppedFields } from '../utils/flowLaunch.js'; -import { activeFlowsBundle, type FlowsTranslation } from '../utils/flowsBundle.js'; +import { activeFlowsBundle, type FlowsTranslation } from '@object-ui/i18n'; export type { ScreenSpec, ScreenFieldSpec } from './ScreenView.js'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/FlowCanvas.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/FlowCanvas.test.tsx index 9bfdf5792a1..26193c3f6c8 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/FlowCanvas.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/FlowCanvas.test.tsx @@ -19,7 +19,7 @@ import { useFlowLabelTranslations, type FlowLabelTranslations, } from './flow-label-translations'; -import { activeFlowsBundle } from '../../../utils/flowsBundle'; +import { activeFlowsBundle } from '@object-ui/i18n'; afterEach(cleanup); diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/flow-label-translations.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/flow-label-translations.tsx index ea76d0119e6..7ff49a1498e 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/flow-label-translations.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/flow-label-translations.tsx @@ -24,7 +24,7 @@ import * as React from 'react'; import { useObjectTranslation } from '@object-ui/react'; import { translateFlow, type TranslationBundle } from '@objectstack/spec/system'; -import { activeFlowsBundle } from '../../../utils/flowsBundle.js'; +import { activeFlowsBundle } from '@object-ui/i18n'; /** A flow's translated labels in one language. Every member answers `undefined` where the bundle carries nothing. */ export interface FlowLabelTranslations { diff --git a/ui/packages/fields/src/RequiredFieldsDialog.tsx b/ui/packages/fields/src/RequiredFieldsDialog.tsx index 9886a78ba2f..41411824a26 100644 --- a/ui/packages/fields/src/RequiredFieldsDialog.tsx +++ b/ui/packages/fields/src/RequiredFieldsDialog.tsx @@ -129,6 +129,12 @@ export interface RequiredFieldsDialogProps { labelOf?: (name: string) => string | undefined; title?: string; description?: string; + /** + * What the host adds about the change under the change block, read-only — + * the record header's stage menu names the flows the move would start there + * (objectstack#35928). Nothing is drawn for none. + */ + notice?: React.ReactNode; submitLabel?: string; } @@ -153,6 +159,7 @@ export function RequiredFieldsDialog({ labelOf, title, description, + notice, submitLabel, }: RequiredFieldsDialogProps): React.ReactElement { const tt = useSafeTranslate(); @@ -274,6 +281,8 @@ export function RequiredFieldsDialog({ )} + {notice} +
{shown.map((f) => { const isMissing = isMissingForRequired(values[f.name]); diff --git a/ui/packages/app-shell/src/utils/flowsBundle.ts b/ui/packages/i18n/src/flowsBundle.ts similarity index 77% rename from ui/packages/app-shell/src/utils/flowsBundle.ts rename to ui/packages/i18n/src/flowsBundle.ts index 9961cd10307..ab417002b3c 100644 --- a/ui/packages/app-shell/src/utils/flowsBundle.ts +++ b/ui/packages/i18n/src/flowsBundle.ts @@ -8,16 +8,17 @@ /** * The app's `flows` translation group, read back out of the i18next resource - * tree the console already loaded — the ONE reader of that group in the - * console. Module-internal (not re-exported from `utils/index` or the package - * entry). + * tree the host already loaded — the ONE reader of that group in the UI. * - * Three surfaces read it, all for the flow a run belongs to: `FlowRunner` - * (the paused screen's field copy and option labels, the flow's label, the - * resume's terminal toasts) and the two flow-LAUNCH hosts through - * `launchConsoleFlow` (a straight-through run's terminal toasts, - * objectui#12075). They read it through this module so the three cannot - * disagree about where the bundle lives. + * Every surface that names a flow in the reader's language reads it through + * this module, so none can disagree about where the bundle lives: the + * console's `FlowRunner` (the paused screen's field copy and option labels, + * the flow's label, the resume's terminal toasts), the two flow-LAUNCH hosts + * through `launchConsoleFlow` (objectui#12075), the flow designer's label + * translations, and the stage-change confirms of the list cell and the record + * page, which name the flows a move would start (objectstack#35928). It lives + * here rather than in `@object-ui/app-shell` because the confirms' packages + * do not depend on the console. * * The provider's `loadLanguage` hands the app's translation payload to * i18next (`transformSpecTranslations` forwards `flows` verbatim under the app diff --git a/ui/packages/i18n/src/index.ts b/ui/packages/i18n/src/index.ts index d700130912c..d84cd8c8ed8 100644 --- a/ui/packages/i18n/src/index.ts +++ b/ui/packages/i18n/src/index.ts @@ -191,3 +191,13 @@ export { // grids and the timeline's week buckets read it from the tag they format with, // so the week starts where the locale says and never on a hard-coded day. export { firstDayOfWeek, type WeekdayIndex } from './utils/index.js'; + +// The app's `flows` translation group, read back out of the loaded resource +// tree: the ONE reader every surface that names a flow goes through — the +// console's flow runner and designer, and the stage-change confirms that name +// the flows a move would start (objectstack#35928). +export { + activeFlowsBundle, + type FlowsTranslation, + type TranslationResourceReader, +} from './flowsBundle.js'; diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 266d2ced82a..90f8c410cc4 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1695,6 +1695,8 @@ const ar = { pathStageChangeConflict: 'قام شخص آخر بتغيير هذا السجل، ويتم الآن عرض أحدث إصدار. اضغط على المرحلة مرة أخرى إذا كان النقل لا يزال مطلوبًا.', pathStageChangeDenied: 'ليس لديك إذن لتغيير مرحلة هذا السجل.', pathStageChangeFailed: 'تعذر تغيير المرحلة.', + stageChangeStartsHeading: 'يؤدي حفظ هذا التغيير إلى بدء هذه التدفقات:', + stageChangeStartsApproval: 'يبدأ موافقة', inlineEditRecordChanged: "تم تغيير هذا السجل في مكان آخر أثناء التحرير. يتم الاحتفاظ بتغييراتك غير المحفوظة، ويكتبها الحفظ فوق أحدث إصدار.", stageMenuTrigger: 'المرحلة: {{stage}}. تغيير المرحلة', stageMenuCurrent: 'المرحلة الحالية', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 403ca6ae1bb..b7fa37c9f1d 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1517,6 +1517,8 @@ const de = { pathStageChangeConflict: 'Jemand anderes hat diesen Datensatz geändert; die aktuelle Version wird jetzt angezeigt. Klicken Sie erneut auf die Phase, wenn die Verschiebung weiterhin gilt.', pathStageChangeDenied: 'Sie sind nicht berechtigt, die Phase dieses Datensatzes zu ändern.', pathStageChangeFailed: 'Die Phase konnte nicht geändert werden.', + stageChangeStartsHeading: 'Beim Speichern dieser Änderung starten diese Flows:', + stageChangeStartsApproval: 'startet eine Genehmigung', inlineEditRecordChanged: "Dieser Datensatz wurde während Ihrer Bearbeitung an anderer Stelle geändert. Ihre ungespeicherten Änderungen bleiben erhalten, und Speichern schreibt sie über die neueste Version.", stageMenuTrigger: 'Phase: {{stage}}. Phase ändern', stageMenuCurrent: 'aktuelle Phase', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 9ff4af973f9..37d5ac488af 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1644,6 +1644,8 @@ const en = { pathStageChangeConflict: 'Someone else changed this record, and the latest version is now shown. Press the stage again if the move still applies.', pathStageChangeDenied: "You don't have permission to change this record's stage.", pathStageChangeFailed: 'The stage could not be changed.', + stageChangeStartsHeading: 'Saving this change starts these flows:', + stageChangeStartsApproval: 'starts an approval', inlineEditRecordChanged: 'This record was changed elsewhere while you were editing. Your unsaved changes are kept, and Save writes them over the latest version.', stageMenuTrigger: 'Stage: {{stage}}. Change stage', stageMenuCurrent: 'current stage', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 96159fc8ce3..37d4613bf87 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1563,6 +1563,8 @@ const es = { pathStageChangeConflict: 'Otra persona ha modificado este registro y ahora se muestra la versión más reciente. Vuelve a pulsar la etapa si el cambio sigue siendo válido.', pathStageChangeDenied: 'No tienes permiso para cambiar la etapa de este registro.', pathStageChangeFailed: 'No se ha podido cambiar la etapa.', + stageChangeStartsHeading: 'Al guardar este cambio se inician estos flujos:', + stageChangeStartsApproval: 'inicia una aprobación', inlineEditRecordChanged: "Este registro se modificó en otro lugar mientras lo editaba. Sus cambios sin guardar se conservan, y Guardar los escribe sobre la versión más reciente.", stageMenuTrigger: 'Etapa: {{stage}}. Cambiar etapa', stageMenuCurrent: 'etapa actual', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 2134308f32e..dd2080db018 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1560,6 +1560,8 @@ const fr = { pathStageChangeConflict: "Quelqu'un d'autre a modifié cet enregistrement ; la dernière version est maintenant affichée. Cliquez à nouveau sur l'étape si le changement s'applique toujours.", pathStageChangeDenied: "Vous n'avez pas l'autorisation de modifier l'étape de cet enregistrement.", pathStageChangeFailed: "L'étape n'a pas pu être modifiée.", + stageChangeStartsHeading: "L'enregistrement de cette modification démarre ces flux :", + stageChangeStartsApproval: 'démarre une approbation', inlineEditRecordChanged: "Cet enregistrement a été modifié ailleurs pendant votre modification. Vos modifications non enregistrées sont conservées, et Enregistrer les écrit sur la dernière version.", stageMenuTrigger: "Étape : {{stage}}. Changer d'étape", stageMenuCurrent: 'étape actuelle', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 63cd1c97184..3d8377be2d3 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1601,6 +1601,8 @@ const ja = { pathStageChangeConflict: '他のユーザーがこのレコードを変更したため、最新の内容を表示しています。移動が必要な場合は、もう一度ステージを押してください。', pathStageChangeDenied: 'このレコードのステージを変更する権限がありません。', pathStageChangeFailed: 'ステージを変更できませんでした。', + stageChangeStartsHeading: '保存すると次のフローが開始されます:', + stageChangeStartsApproval: '承認を開始', inlineEditRecordChanged: "編集中にこのレコードが別の場所で変更されました。未保存の変更はそのまま残り、保存すると最新版に上書きされます。", stageMenuTrigger: 'ステージ:{{stage}}。ステージを変更', stageMenuCurrent: '現在のステージ', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index ff3406710af..f8502d4109f 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1517,6 +1517,8 @@ const ko = { pathStageChangeConflict: '다른 사용자가 이 레코드를 변경하여 최신 버전을 표시합니다. 이동이 여전히 필요하면 단계를 다시 누르세요.', pathStageChangeDenied: '이 레코드의 단계를 변경할 권한이 없습니다.', pathStageChangeFailed: '단계를 변경할 수 없습니다.', + stageChangeStartsHeading: '저장하면 다음 플로가 시작됩니다:', + stageChangeStartsApproval: '승인 시작', inlineEditRecordChanged: "편집하는 동안 이 레코드가 다른 곳에서 변경되었습니다. 저장하지 않은 변경 사항은 유지되며, 저장하면 최신 버전에 덮어씁니다.", stageMenuTrigger: '단계: {{stage}}. 단계 변경', stageMenuCurrent: '현재 단계', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 5ac02b304b5..dc000767a1f 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1560,6 +1560,8 @@ const pt = { pathStageChangeConflict: 'Outra pessoa alterou este registro, e a versão mais recente está sendo exibida. Pressione a etapa novamente se a mudança ainda se aplicar.', pathStageChangeDenied: 'Você não tem permissão para alterar a etapa deste registro.', pathStageChangeFailed: 'Não foi possível alterar a etapa.', + stageChangeStartsHeading: 'Salvar esta alteração inicia estes fluxos:', + stageChangeStartsApproval: 'inicia uma aprovação', inlineEditRecordChanged: "Este registro foi alterado em outro lugar enquanto você editava. Suas alterações não salvas são mantidas, e Salvar as grava sobre a versão mais recente.", stageMenuTrigger: 'Etapa: {{stage}}. Alterar etapa', stageMenuCurrent: 'etapa atual', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index d3ea838ac67..9fcbdb9334f 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1708,6 +1708,8 @@ const ru = { pathStageChangeConflict: 'Запись изменил другой пользователь, теперь показана последняя версия. Нажмите на этап ещё раз, если перевод всё ещё нужен.', pathStageChangeDenied: 'У вас нет прав на смену этапа этой записи.', pathStageChangeFailed: 'Не удалось сменить этап.', + stageChangeStartsHeading: 'При сохранении этого изменения запустятся процессы:', + stageChangeStartsApproval: 'запускает согласование', inlineEditRecordChanged: "Пока вы редактировали, эту запись изменили в другом месте. Несохранённые изменения сохранены, и при сохранении они будут записаны поверх последней версии.", stageMenuTrigger: 'Этап: «{{stage}}». Сменить этап', stageMenuCurrent: 'текущий этап', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 9b480b27879..641cd77a8c6 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1365,6 +1365,8 @@ const zh = { pathStageChangeConflict: '其他人已修改此记录,现已显示最新版本。如仍需移动,请再次点击该阶段。', pathStageChangeDenied: '你没有更改此记录阶段的权限。', pathStageChangeFailed: '无法更改阶段。', + stageChangeStartsHeading: '保存后将启动以下流程:', + stageChangeStartsApproval: '发起审批', inlineEditRecordChanged: '编辑期间,此记录已在别处被修改。你未保存的修改会保留,保存时以你的修改为准,写到最新版本上。', stageMenuTrigger: '阶段:{{stage}},更改阶段', stageMenuCurrent: '当前阶段', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 459582fd35b..9f515721bc3 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1365,6 +1365,8 @@ const zhHant = { pathStageChangeConflict: '其他人已修改此記錄,現已顯示最新版本。如仍需移動,請再次點選該階段。', pathStageChangeDenied: '你沒有更改此記錄階段的權限。', pathStageChangeFailed: '無法更改階段。', + stageChangeStartsHeading: '儲存後將啟動以下流程:', + stageChangeStartsApproval: '發起審批', inlineEditRecordChanged: '編輯期間,此記錄已在別處被修改。你未儲存的修改會保留,儲存時以你的修改為準,寫到最新版本上。', stageMenuTrigger: '階段:{{stage}},更改階段', stageMenuCurrent: '當前階段', diff --git a/ui/packages/plugin-detail/src/__tests__/RecordStageMenu-35891.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordStageMenu-35891.test.tsx index c023b071e35..7c37df4ff85 100644 --- a/ui/packages/plugin-detail/src/__tests__/RecordStageMenu-35891.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RecordStageMenu-35891.test.tsx @@ -143,7 +143,17 @@ beforeEach(() => { perms.writeDenied = []; }); -afterEach(() => cleanup()); +// objectstack#35928 — the stage confirm asks which flows the move would start. +// Answered here as a deployment without that read (501), so the confirm reads as +// it does without it and no request leaves for the network. +beforeEach(() => { + vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 501, json: async () => ({}) }))); +}); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); describe('#35891 the stage tag opens a menu of every stage', () => { it('lists every stage in order, the current one checked', () => { diff --git a/ui/packages/plugin-detail/src/__tests__/stageChangeStarts-35928.test.tsx b/ui/packages/plugin-detail/src/__tests__/stageChangeStarts-35928.test.tsx new file mode 100644 index 00000000000..f372f8ea478 --- /dev/null +++ b/ui/packages/plugin-detail/src/__tests__/stageChangeStarts-35928.test.tsx @@ -0,0 +1,203 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * objectstack#35928 — the record page's stage confirm names the flows the + * move would start (ruling record 7073655354), through `../stageChangeStarts`, + * the reader the list cell's confirm shares. Both of the page's confirms are + * pinned: `record:path`'s plain confirmation and the header stage menu's + * dialog (`RecordStageMenu`, the shared `RequiredFieldsDialog`). + * + * 1. List: the confirm asks `POST /api/v1/automation/_record-starts` for the + * record and the move, and names each flow by label under today's + * sentence, a flow holding an approval marked as such. + * 2. Empty: an answer of no flows draws no list; the sentence stands alone. + * 3. Failure: a refused read draws no list; the sentence stands alone, and + * the move still writes on Move. + * + * `@object-ui/*` resolves to source through the root vitest alias table. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; +import { render, cleanup, fireEvent, screen, waitFor, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { InlineEditProvider, RecordContextProvider } from '@object-ui/react'; + +vi.mock('@object-ui/permissions', async (importOriginal) => { + const actual = await importOriginal(); + const stub = { + isLoaded: true, + checkField: () => true, + check: () => ({ allowed: true }), + getFieldPermissions: () => [], + getRowFilter: () => undefined, + getObjectApiOperations: () => undefined, + roles: [], + userId: null, + systemPermissions: undefined, + hasCapabilities: () => true, + can: () => true, + cannot: () => false, + }; + return { ...actual, usePermissions: () => stub as any }; +}); + +import { RecordPathRenderer } from '../renderers/record-path'; +import { RecordStageMenu } from '../RecordStageMenu'; + +const VERSION = '2026-11-20T12:00:00.000Z'; +const CLOSURE = { name: 'project_closure', label: 'Project Closure', startsApproval: true }; +const NOTIFY = { name: 'notify_owner', label: 'Notify Owner', startsApproval: false }; + +const PROJECT = { + name: 'project', + fields: { + name: { type: 'text', label: 'Name' }, + status: { + type: 'select', + label: 'Status', + options: [ + { value: 'active', label: 'Active' }, + { value: 'completed', label: 'Completed' }, + ], + }, + }, +}; + +type StartsAnswer = { status: number; body: unknown } | 'network-error'; + +/** The global `fetch`, answering `_record-starts` with `answer` and recording every request. */ +function installFetch(answer: StartsAnswer) { + const calls: Array<{ url: string; body: any }> = []; + vi.stubGlobal('fetch', vi.fn(async (url: unknown, init?: { body?: unknown }) => { + calls.push({ url: String(url), body: init?.body ? JSON.parse(String(init.body)) : undefined }); + if (answer === 'network-error') throw new TypeError('Failed to fetch'); + return { ok: answer.status < 400, status: answer.status, json: async () => answer.body }; + })); + return calls; +} + +const listed = (flows: unknown[]): StartsAnswer => ({ status: 200, body: { success: true, data: { flows } } }); + +function Host({ children }: { children: React.ReactNode }) { + const [dataSource] = React.useState(() => ({ update: vi.fn(async () => ({})) })); + return ( + {}} + > + {children} + + ); +} + +/** `record:path`'s confirmation, opened on Completed. */ +async function openPathConfirm(): Promise { + const { container } = render( + + + , + ); + const rail = container.querySelector('[role="list"]') as HTMLElement; + fireEvent.click(within(rail).getByRole('button', { name: 'Move to Completed' })); + return screen.findByRole('alertdialog'); +} + +/** The header stage menu's dialog, opened on Completed. */ +async function openMenuConfirm(): Promise { + render( + + Active} /> + , + ); + fireEvent.pointerDown(screen.getByRole('button', { name: /^Stage: / }), { button: 0, ctrlKey: false, pointerType: 'mouse' }); + const item = within(screen.getByRole('menu')).getAllByRole('menuitem').find((el) => el.textContent?.startsWith('Completed'))!; + fireEvent.click(item); + return screen.findByRole('dialog'); +} + +const startsCalls = (calls: Array<{ url: string; body: any }>) => + calls.filter((c) => c.url === '/api/v1/automation/_record-starts'); + +const CONFIRMS: Array<[string, () => Promise]> = [ + ['record:path confirmation', openPathConfirm], + ['header stage menu dialog', openMenuConfirm], +]; + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +describe.each(CONFIRMS)('#35928 the %s names the flows the move starts', (_name, open) => { + let calls: Array<{ url: string; body: any }>; + beforeEach(() => { + calls = []; + }); + + it('list: asks for the record and the move, and names each flow under the sentence, approval marked', async () => { + calls = installFetch(listed([CLOSURE, NOTIFY])); + const dialog = await open(); + const list = await within(dialog).findByTestId('stage-change-starts'); + expect(within(dialog).getByText('Move this record to Completed?')).toBeInTheDocument(); + expect(list).toHaveTextContent('Saving this change starts these flows:'); + const closure = list.querySelector('[data-stage-change-start="project_closure"]')!; + const notify = list.querySelector('[data-stage-change-start="notify_owner"]')!; + expect(closure).toHaveTextContent('Project Closure'); + expect(closure.querySelector('[data-stage-change-start-approval]')).toHaveTextContent('starts an approval'); + expect(notify).toHaveTextContent('Notify Owner'); + expect(notify.querySelector('[data-stage-change-start-approval]')).toBeNull(); + expect(startsCalls(calls).map((c) => c.body)).toEqual([ + { object: 'project', recordId: 'p1', changes: { status: 'completed' } }, + ]); + }); + + it('empty: no flows answered draws no list, and the sentence stands alone', async () => { + calls = installFetch(listed([])); + const dialog = await open(); + await waitFor(() => expect(startsCalls(calls)).toHaveLength(1)); + await new Promise((r) => setTimeout(r, 0)); + expect(within(dialog).queryByTestId('stage-change-starts')).toBeNull(); + expect(within(dialog).getByText('Move this record to Completed?')).toBeInTheDocument(); + }); + + it('failure: a refused read and a network error draw no list, and the sentence stands alone', async () => { + calls = installFetch({ status: 404, body: { success: false, error: { code: 'RECORD_NOT_FOUND', message: 'no' } } }); + const refused = await open(); + await waitFor(() => expect(startsCalls(calls)).toHaveLength(1)); + await new Promise((r) => setTimeout(r, 0)); + expect(within(refused).queryByTestId('stage-change-starts')).toBeNull(); + expect(within(refused).getByText('Move this record to Completed?')).toBeInTheDocument(); + cleanup(); + vi.unstubAllGlobals(); + + calls = installFetch('network-error'); + const failed = await open(); + await waitFor(() => expect(startsCalls(calls)).toHaveLength(1)); + await new Promise((r) => setTimeout(r, 0)); + expect(within(failed).queryByTestId('stage-change-starts')).toBeNull(); + expect(within(failed).getByText('Move this record to Completed?')).toBeInTheDocument(); + }); + + it('a malformed answer (not the declared envelope) draws no list', async () => { + calls = installFetch({ status: 200, body: { flows: [CLOSURE] } }); + const dialog = await open(); + await waitFor(() => expect(startsCalls(calls)).toHaveLength(1)); + await new Promise((r) => setTimeout(r, 0)); + expect(within(dialog).queryByTestId('stage-change-starts')).toBeNull(); + }); +}); diff --git a/ui/packages/plugin-detail/src/__tests__/stageChangeStarts-label-35928.test.tsx b/ui/packages/plugin-detail/src/__tests__/stageChangeStarts-label-35928.test.tsx new file mode 100644 index 00000000000..b5ccdfdf3f3 --- /dev/null +++ b/ui/packages/plugin-detail/src/__tests__/stageChangeStarts-label-35928.test.tsx @@ -0,0 +1,60 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * objectstack#35928 — a flow the stage confirm names is named by its label in + * the reader's language: the app's `flows` translation, read through + * `activeFlowsBundle` and the spec's `translateFlow` (the flow runner's + * reading), and the authored label where the app translates none. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, cleanup } from '@testing-library/react'; +import '@testing-library/jest-dom'; + +// The active language's resource tree, as the provider loads an app's +// translations into i18next (the `flows` group under the app namespace). +const tree = { + app: { flows: { project_closure: { label: '项目结项' } } }, +}; + +vi.mock('@object-ui/i18n', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + useObjectTranslation: () => ({ + ...actual.useObjectTranslation(), + language: 'zh-Hans', + i18n: { getResourceBundle: (lng: string) => (lng === 'zh-Hans' ? tree : undefined) }, + }), + }; +}); + +import { StageChangeStarts } from '../stageChangeStarts'; + +afterEach(() => cleanup()); + +describe('#35928 StageChangeStarts names a flow in the reader\'s language', () => { + it('a translated flow reads its translation; an untranslated one its authored label', () => { + const { container } = render( + , + ); + expect(container.querySelector('[data-stage-change-start="project_closure"]')).toHaveTextContent('项目结项'); + expect(container.querySelector('[data-stage-change-start="project_closure"]')).not.toHaveTextContent('Project Closure'); + expect(container.querySelector('[data-stage-change-start="notify_owner"]')).toHaveTextContent('Notify Owner'); + }); + + it('draws nothing for no flows', () => { + const { container } = render(); + expect(container.firstChild).toBeNull(); + }); +}); diff --git a/ui/packages/plugin-detail/src/index.tsx b/ui/packages/plugin-detail/src/index.tsx index 8d4bea4c086..60ad61f3ae6 100644 --- a/ui/packages/plugin-detail/src/index.tsx +++ b/ui/packages/plugin-detail/src/index.tsx @@ -142,6 +142,10 @@ export type { RecordOperation } from './useRecordEditable'; // claim is `{ owner_id: }` through the normal update. export { recordSitsInQueue, useQueueClaimOffered, claimQueuedRecord, seedQueueClaimDecision } from './queueClaim'; export type { QueueClaimOutcome, ClaimWriter } from './queueClaim'; +// objectstack#35928 — the flows a stage change would start, named in both +// stage confirms: the record page's and the list cell's (`@object-ui/plugin-grid`). +export { useRecordUpdateStarts, StageChangeStarts, RECORD_UPDATE_STARTS_PATH } from './stageChangeStarts'; +export type { RecordUpdateStartsAsk } from './stageChangeStarts'; export { SectionGroup } from './SectionGroup'; export { HeaderHighlight } from './HeaderHighlight'; export { InlineFieldInput } from './InlineFieldInput'; diff --git a/ui/packages/plugin-detail/src/renderers/__tests__/record-path.stageChange-28199.test.tsx b/ui/packages/plugin-detail/src/renderers/__tests__/record-path.stageChange-28199.test.tsx index 542ab1f0ecc..656e4cb0d35 100644 --- a/ui/packages/plugin-detail/src/renderers/__tests__/record-path.stageChange-28199.test.tsx +++ b/ui/packages/plugin-detail/src/renderers/__tests__/record-path.stageChange-28199.test.tsx @@ -138,7 +138,17 @@ beforeEach(() => { perms.writeDenied = []; }); -afterEach(() => cleanup()); +// objectstack#35928 — the stage confirm asks which flows the move would start. +// Answered here as a deployment without that read (501), so the confirm reads as +// it does without it and no request leaves for the network. +beforeEach(() => { + vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 501, json: async () => ({}) }))); +}); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); describe('record:path allowStageChange — a press writes the stage', () => { it('every stage but the current one is a button, on both rows', () => { diff --git a/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx b/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx index 5d599d0d453..6740af8b6d9 100644 --- a/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx +++ b/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx @@ -55,6 +55,13 @@ * the reader may fill adds that field, any other reads at the dialog's foot. * A stage that needs nothing opens the same dialog as the move's confirmation. * `record:path` leaves the option off and keeps its plain confirmation. + * + * ## The flows a move starts (objectstack#35928) + * + * Both confirmations name the flows the move would start, under their + * sentence, through `../stageChangeStarts` — the reader the list cell's + * confirm shares, so the two surfaces cannot disagree. The server judges which + * flows start; a read that fails or answers none leaves the sentence alone. */ import React from 'react'; @@ -98,6 +105,7 @@ import { NON_EDITABLE_SYSTEM_FIELDS } from '../systemFields'; import { updateVia } from '../InlineEditSaveBar'; import { isConcurrentUpdateError } from '../ConcurrentUpdateDialog'; import { useDetailTranslation } from '../useDetailTranslation'; +import { StageChangeStarts, useRecordUpdateStarts } from '../stageChangeStarts'; /** The field a server refusal names when its rule declares no field. */ const RECORD_LEVEL_FIELD = '_record'; @@ -256,6 +264,14 @@ export function useStageChange( setTarget({ value: stage.value, label: stage.label, fields: fieldsNeededAt(stage.value) }); }; + // objectstack#35928 — the flows the pending move would start, named under + // the confirm's sentence by the shared reader the list cell's confirm uses. + const starts = useRecordUpdateStarts( + target && pressable && statusField && objectName + ? { object: objectName, recordId: String(recordId), changes: { [statusField]: target.value } } + : null, + ); + const labelOf = (field: string): string => { const declared = fieldDefOf(objectSchema, field)?.label; const fallback = declared == null ? field : String(pickLocalized(declared as Parameters[0], language) ?? field); @@ -324,6 +340,7 @@ export function useStageChange( {t('detail.pathStageChangeDescription', { stage: target?.label ?? '' })} + {t('detail.cancel')} { void confirm(); }}> @@ -379,6 +396,7 @@ export function useStageChange( description={stage.fields.length > 0 ? t('detail.stageMenuFieldsDescription', { stage: stage.label }) : t('detail.pathStageChangeDescription', { stage: stage.label })} + notice={} submitLabel={t('detail.pathStageChangeConfirm')} onCancel={() => setTarget(null)} onSubmit={(values) => submitWithFields(stage, values)} diff --git a/ui/packages/plugin-detail/src/stageChangeStarts.tsx b/ui/packages/plugin-detail/src/stageChangeStarts.tsx new file mode 100644 index 00000000000..053c0a8b46f --- /dev/null +++ b/ui/packages/plugin-detail/src/stageChangeStarts.tsx @@ -0,0 +1,127 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35928 — the flows a stage change would start, named in the + * change's confirm (ruling record 7073655354 on objectstack#35928). + * + * Two confirms ask before a stage moves: the list cell's state-machine confirm + * (`@object-ui/plugin-grid`, objectstack#35685) and the record page's stage + * confirm (`renderers/recordPathStageChange`). Both read this module, so they + * cannot disagree about what a move starts or how it is named: + * + * - {@link useRecordUpdateStarts} asks the server once per pending move + * (`POST /api/v1/automation/_record-starts`, the declared + * `listRecordUpdateStarts` contract of `@objectstack/spec/api`). Which flows + * start is the SERVER's call — the engine's own start-condition gate over + * the record as the caller reads it, with the proposed fields applied. ⛔ No + * condition is judged here. + * - {@link StageChangeStarts} draws the answer under the confirm's sentence: + * each flow by its label in the reader's language (the app's `flows` + * translations, read through `activeFlowsBundle` and the spec's + * `translateFlow`, as the flow runner names a flow), and a flow holding an + * approval node marked as starting one (ADR-0019). Nothing else about a flow + * is shown: no description, condition, nodes or link. + * + * The confirm's own sentence stays as it is and is never replaced: a hook the + * object runs is not listed (ADR-0077 §2), so "may trigger related automation" + * stays true beside any list. A read in flight, refused or failing, and an + * empty answer, draw nothing — the confirm reads as it did before this card. + */ + +import * as React from 'react'; +import { SchemaRendererContext } from '@object-ui/react'; +import { activeFlowsBundle, useObjectTranslation } from '@object-ui/i18n'; +import { RecordUpdateStartsResponseSchema, type RecordUpdateStart } from '@objectstack/spec/api'; +import { translateFlow } from '@objectstack/spec/system'; +import { useDetailTranslation } from './useDetailTranslation'; + +/** The route of the declared `listRecordUpdateStarts` contract. */ +export const RECORD_UPDATE_STARTS_PATH = '/api/v1/automation/_record-starts'; + +/** One pending move: the record, and the fields it would write. */ +export interface RecordUpdateStartsAsk { + object: string; + recordId: string; + changes: Record; +} + +/** + * The flows the pending move `ask` would start, as the server answers them; + * `[]` while no move is pending, while the read is in flight, and when it is + * refused, fails or answers nothing. Asked again whenever the move changes. + */ +export function useRecordUpdateStarts(ask: RecordUpdateStartsAsk | null): RecordUpdateStart[] { + const apiFetch = React.useContext(SchemaRendererContext)?.apiFetch; + const key = ask ? JSON.stringify([ask.object, ask.recordId, ask.changes]) : null; + const [answer, setAnswer] = React.useState<{ key: string; flows: RecordUpdateStart[] } | null>(null); + + React.useEffect(() => { + if (key === null) return; + const [object, recordId, changes] = JSON.parse(key) as [string, string, Record]; + let cancelled = false; + void (async () => { + try { + const doFetch = apiFetch ?? fetch; + const res = await doFetch(RECORD_UPDATE_STARTS_PATH, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify({ object, recordId, changes }), + }); + if (!res.ok) return; + const parsed = RecordUpdateStartsResponseSchema.safeParse(await res.json()); + if (!cancelled && parsed.success) setAnswer({ key, flows: parsed.data.data.flows }); + } catch { + // No answer names no flow: the confirm keeps its sentence alone. + } + })(); + return () => { + cancelled = true; + }; + }, [key, apiFetch]); + + // An answer is read only for the move it was asked for, so a confirm never + // shows the flows of the move before it. + return answer !== null && answer.key === key ? answer.flows : []; +} + +/** + * The list a confirm draws under its sentence, or nothing for no flows. Each + * flow is named by its label in the reader's language, the authored label + * where the app translates none. + */ +export function StageChangeStarts({ flows }: { flows: readonly RecordUpdateStart[] }): React.ReactElement | null { + const { t } = useDetailTranslation(); + const { i18n, language } = useObjectTranslation(); + if (flows.length === 0) return null; + const labelOf = (flow: RecordUpdateStart): string => { + const bundle = activeFlowsBundle(i18n, language, flow.name); + if (!bundle) return flow.label; + const translated = translateFlow({ name: flow.name, label: flow.label }, bundle, { locale: language }).label; + return typeof translated === 'string' && translated ? translated : flow.label; + }; + return ( +
+

{t('detail.stageChangeStartsHeading')}

+
    + {flows.map((flow) => ( +
  • + {labelOf(flow)} + {flow.startsApproval && ( + + {' · '} + {t('detail.stageChangeStartsApproval')} + + )} +
  • + ))} +
+
+ ); +} diff --git a/ui/packages/plugin-detail/src/useDetailTranslation.ts b/ui/packages/plugin-detail/src/useDetailTranslation.ts index 756c569300a..f7865120bb5 100644 --- a/ui/packages/plugin-detail/src/useDetailTranslation.ts +++ b/ui/packages/plugin-detail/src/useDetailTranslation.ts @@ -360,6 +360,10 @@ export const DETAIL_DEFAULT_TRANSLATIONS: Record = { 'detail.pathStageChangeConflict': 'Someone else changed this record, and the latest version is now shown. Press the stage again if the move still applies.', 'detail.pathStageChangeDenied': "You don't have permission to change this record's stage.", 'detail.pathStageChangeFailed': 'The stage could not be changed.', + // objectstack#35928 — the flows a stage change would start, listed under + // the confirm's sentence (`stageChangeStarts`); byte-identical to the `en` pack. + 'detail.stageChangeStartsHeading': 'Saving this change starts these flows:', + 'detail.stageChangeStartsApproval': 'starts an approval', // objectstack#35685 — the save bar's note when the record changed elsewhere // during the edit session (`InlineEditSaveBar`). Byte-identical to the `en` pack. 'detail.inlineEditRecordChanged': 'This record was changed elsewhere while you were editing. Your unsaved changes are kept, and Save writes them over the latest version.', diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 5be74cc0aab..33109f08aac 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -79,6 +79,8 @@ import { ConcurrentUpdateDialog, isConcurrentUpdateError, useDetailTranslation, + StageChangeStarts, + useRecordUpdateStarts, type ConcurrentUpdateConflict, } from '@object-ui/plugin-detail'; import { ChevronRight, ChevronLeft, ChevronsLeft, ChevronsRight, Download, Rows2, Rows3, Rows4, AlignJustify, Loader2, Check } from 'lucide-react'; @@ -935,6 +937,9 @@ export const ObjectGrid: React.FC = ({ const [stateChange, setStateChange] = useState(null); const stateChangeDecisionRef = React.useRef<((confirmed: boolean) => void) | null>(null); useEffect(() => () => stateChangeDecisionRef.current?.(false), []); + // objectstack#35928 — the flows the pending move would start, named under + // the confirm's sentence by the reader the record page's confirm shares. + const stateChangeStarts = useRecordUpdateStarts(stateChange?.ask ?? null); // objectstack#35685 — the rows a select-first save redrew in place, per // record id. Each applies while the grid still holds the row object it was // saved from (`RowPatch.base`); the next load's rows replace them. @@ -1435,10 +1440,14 @@ export const ObjectGrid: React.FC = ({ ); const declared = objectFields?.[columnKey]?.label; const fallback = typeof declared === 'string' && declared.length > 0 ? declared : columnKey; + const recordId = resolveRecordId(row); return askStateChange({ field: columnHeaderOf(columnKey) ?? (objectName ? resolveFieldLabel(objectName, columnKey, fallback) : fallback), from: labelOf(row?.[columnKey]), to: labelOf(value), + ...(objectName && recordId != null && recordId !== '' + ? { ask: { object: objectName, recordId: String(recordId), changes: { [columnKey]: value } } } + : {}), }); } @@ -4989,6 +4998,7 @@ export const ObjectGrid: React.FC = ({ })} + {t('grid.stateChange.cancel')} settleStateChange(true)}>{t('grid.stateChange.confirm')} diff --git a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.stageStarts-35928.test.tsx b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.stageStarts-35928.test.tsx new file mode 100644 index 00000000000..886af519439 --- /dev/null +++ b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.stageStarts-35928.test.tsx @@ -0,0 +1,207 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The list cell's state-machine confirm names the flows the move would start + * (objectstack#35928, ruling record 7073655354), read through + * `@object-ui/plugin-detail`'s `useRecordUpdateStarts` — the reader the record + * page's stage confirm shares. + * + * 1. List: the confirm asks `POST /api/v1/automation/_record-starts` for + * the row's record and the move, and names each flow it answers by label + * under today's sentence, a flow holding an approval marked as such. + * 2. Empty: an answer of no flows draws no list; the sentence stands alone. + * 3. Failure: a refused read draws no list; the sentence stands alone, and + * the move still saves on Change. + */ +import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; +import { render, screen, waitFor, fireEvent, cleanup, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; + +import { ObjectGrid } from '../ObjectGrid'; +import { registerAllFields } from '@object-ui/fields'; +import { ActionProvider } from '@object-ui/react'; +import { __clearRecordCrudVerdictCache } from '../hooks/useRecordCrudVerdicts'; +import { __resetApprovalsServiceLatch } from '../hooks/useRowApprovalLocks'; + +registerAllFields(); + +beforeAll(() => { + if (!Element.prototype.scrollIntoView) { + Element.prototype.scrollIntoView = vi.fn() as any; + } +}); + +const OBJECT = 'deal'; +const SENTENCE = 'Stage changes from New to Won. Saving may trigger related automation.'; +const CLOSURE = { name: 'deal_won', label: 'Deal Won Sign-off', startsApproval: true }; +const NOTIFY = { name: 'deal_notify', label: 'Notify Owner', startsApproval: false }; + +type StartsAnswer = { status: number; body: unknown }; + +/** + * The global `fetch`: the explain probe answers permissively (as + * `explainDouble` does), `_record-starts` answers `starts`; every call is + * recorded so the request the confirm sends can be read back. + */ +function installFetch(starts: StartsAnswer) { + const calls: Array<{ url: string; body: any }> = []; + vi.stubGlobal('fetch', vi.fn(async (url: unknown, init?: { body?: unknown }) => { + const body = init?.body ? JSON.parse(String(init.body)) : undefined; + calls.push({ url: String(url), body }); + if (String(url).endsWith('/automation/_record-starts')) { + return { ok: starts.status < 400, status: starts.status, json: async () => starts.body }; + } + const recordIds = Array.isArray(body?.recordIds) ? body.recordIds : undefined; + return { + ok: true, + status: 200, + json: async () => ({ + allowed: true, + layers: [], + ...(recordIds ? { records: recordIds.map((id: string) => ({ recordId: id, visible: true })) } : {}), + ...(typeof body?.recordId === 'string' ? { record: { visible: true } } : {}), + }), + }; + })); + return calls; +} + +function makeDataSource() { + const store: Record = { + d1: { id: 'd1', name: 'alpha', stage: 'new', updated_at: '2026-11-20T10:00:00.000Z' }, + d2: { id: 'd2', name: 'beta', stage: 'qualified', updated_at: '2026-11-20T10:00:00.000Z' }, + }; + return { + store, + find: vi.fn(async () => { + const data = Object.values(store).map((r) => ({ ...r })); + return { data, total: data.length, hasMore: false, pageSize: 50 }; + }), + update: vi.fn(async (_object: string, id: string, changes: Record) => { + store[id] = { ...store[id], ...changes, updated_at: '2026-11-20T11:00:00.000Z' }; + return { ...store[id] }; + }), + getObjectSchema: async (name: string) => ({ + name, + fields: { + id: { type: 'text' }, + name: { type: 'text', label: 'Name' }, + stage: { + type: 'select', + label: 'Stage', + options: [ + { value: 'new', label: 'New' }, + { value: 'qualified', label: 'Qualified' }, + { value: 'won', label: 'Won' }, + ], + }, + updated_at: { type: 'datetime' }, + }, + validations: [{ + name: 'stage_flow', + type: 'state_machine', + field: 'stage', + transitions: { new: ['qualified', 'won'], qualified: ['won'] }, + }], + }), + } as any; +} + +function renderGrid(ds: any) { + const schema: any = { + type: 'object-grid', + objectName: OBJECT, + editable: true, + columns: [ + { field: 'name', label: 'Name' }, + { field: 'stage', label: 'Stage' }, + ], + pagination: { pageSize: 50 }, + }; + return render( + + + , + ); +} + +const dataCell = (container: HTMLElement, row: number, text: string) => + Array.from(container.querySelectorAll('tbody tr')[row].querySelectorAll('td')) + .find((td) => td.textContent === text)!; + +/** Paste `Won` into the first row's stage cell and wait for the confirm. */ +async function moveFirstRowToWon(container: HTMLElement): Promise { + fireEvent.click(dataCell(container, 0, 'New')); + const catcher = container.querySelector('[data-slot="cell-type-catcher"]')!; + fireEvent.paste(catcher, { clipboardData: { getData: () => 'Won' } }); + return screen.findByRole('alertdialog'); +} + +const startsCalls = (calls: Array<{ url: string; body: any }>) => + calls.filter((c) => c.url.endsWith('/automation/_record-starts')); + +beforeEach(() => { + __clearRecordCrudVerdictCache(); + __resetApprovalsServiceLatch(); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +describe('ObjectGrid — the state-machine confirm names the flows the move starts (objectstack#35928)', () => { + it('list: asks for the row and the move, and names each flow under the sentence, approval marked', async () => { + const calls = installFetch({ status: 200, body: { success: true, data: { flows: [CLOSURE, NOTIFY] } } }); + const ds = makeDataSource(); + const { container } = renderGrid(ds); + await screen.findByText('beta'); + const dialog = await moveFirstRowToWon(container); + + const list = await within(dialog).findByTestId('stage-change-starts'); + expect(dialog).toHaveTextContent(SENTENCE); + expect(list).toHaveTextContent('Saving this change starts these flows:'); + const closure = list.querySelector('[data-stage-change-start="deal_won"]')!; + const notify = list.querySelector('[data-stage-change-start="deal_notify"]')!; + expect(closure).toHaveTextContent('Deal Won Sign-off'); + expect(closure.querySelector('[data-stage-change-start-approval]')).toHaveTextContent('starts an approval'); + expect(notify).toHaveTextContent('Notify Owner'); + expect(notify.querySelector('[data-stage-change-start-approval]')).toBeNull(); + expect(startsCalls(calls).map((c) => c.body)).toEqual([ + { object: OBJECT, recordId: 'd1', changes: { stage: 'won' } }, + ]); + }); + + it('empty: no flows answered draws no list, and the sentence stands alone', async () => { + const calls = installFetch({ status: 200, body: { success: true, data: { flows: [] } } }); + const { container } = renderGrid(makeDataSource()); + await screen.findByText('beta'); + const dialog = await moveFirstRowToWon(container); + await waitFor(() => expect(startsCalls(calls)).toHaveLength(1)); + // Let the answer land before reading that nothing was drawn for it. + await new Promise((r) => setTimeout(r, 0)); + expect(within(dialog).queryByTestId('stage-change-starts')).toBeNull(); + expect(dialog).toHaveTextContent(SENTENCE); + }); + + it('failure: a refused read draws no list, the sentence stands, and Change still saves the move', async () => { + const calls = installFetch({ status: 500, body: { success: false, error: { code: 'INTERNAL_ERROR', message: 'boom' } } }); + const ds = makeDataSource(); + const { container } = renderGrid(ds); + await screen.findByText('beta'); + const dialog = await moveFirstRowToWon(container); + await waitFor(() => expect(startsCalls(calls)).toHaveLength(1)); + await new Promise((r) => setTimeout(r, 0)); + expect(within(dialog).queryByTestId('stage-change-starts')).toBeNull(); + expect(dialog).toHaveTextContent(SENTENCE); + fireEvent.click(within(dialog).getByRole('button', { name: 'Change' })); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); + expect(ds.update.mock.calls[0][2]).toEqual({ stage: 'won' }); + }); +}); diff --git a/ui/packages/plugin-grid/src/objectGridStateConfirm.ts b/ui/packages/plugin-grid/src/objectGridStateConfirm.ts index ae23a348c95..0ed01026280 100644 --- a/ui/packages/plugin-grid/src/objectGridStateConfirm.ts +++ b/ui/packages/plugin-grid/src/objectGridStateConfirm.ts @@ -17,9 +17,14 @@ * * The confirm names the field and its old and new value and says saving may * trigger related automation, as the maintainer ruled (ruling record - * 7039615827 on objectstack#35685); it does not list the flows. + * 7039615827 on objectstack#35685). Under that sentence it names the flows the + * move would start (objectstack#35928, ruling record 7073655354), read through + * `@object-ui/plugin-detail`'s `useRecordUpdateStarts`, the reader the record + * page's stage confirm shares; no answer leaves the sentence alone. */ +import type { RecordUpdateStartsAsk } from '@object-ui/plugin-detail'; + /** The spec's `events` default for a validation rule. */ const DEFAULT_EVENTS: readonly string[] = ['insert', 'update']; @@ -41,6 +46,8 @@ export interface StateChangeConfirm { field: string; from: string; to: string; + /** The move as the server is asked which flows it starts; absent for a row with no record id. */ + ask?: RecordUpdateStartsAsk; } type OptionLike = { value?: unknown; label?: unknown } | string | number; From 5416066604d603424e31f75a8e28950ba8c366b4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 05:38:37 +0000 Subject: [PATCH 04/11] chore(spec): regenerate the surfaces the record-update preview moves (#35928) api-surface, export-origins, declaration-map, the strictness-ledger api count and the automation-api reference page; the route-ledger census sentence; the trigger package's spec/automation test alias; the door test pays its metadata load at collection. Claude-Session: https://claude.ai/code/session_01FEkQ5keqTTiV8ptWFNc6ZF Co-authored-by: Claude --- .../docs/references/api/automation-api.mdx | 74 ++++++++++++++++++- content/docs/references/index.mdx | 10 +-- .../api.md | 2 +- .../automation-record-update-starts.test.ts | 3 + packages/runtime/src/route-ledger.ts | 2 +- packages/spec/api-surface/api.json | 9 +++ packages/spec/api-surface/automation.json | 2 + packages/spec/api-surface/contracts.json | 1 + packages/spec/declaration-map/api.json | 6 ++ packages/spec/export-origins/api.json | 9 +++ packages/spec/export-origins/automation.json | 2 + packages/spec/export-origins/contracts.json | 1 + .../trigger-record-change/vitest.config.ts | 3 + 13 files changed, 115 insertions(+), 9 deletions(-) diff --git a/content/docs/references/api/automation-api.mdx b/content/docs/references/api/automation-api.mdx index 4ec1efe1712..f6b2f519cd4 100644 --- a/content/docs/references/api/automation-api.mdx +++ b/content/docs/references/api/automation-api.mdx @@ -49,6 +49,7 @@ POST /api/v1/automation/:name/toggle — Enable/disable a packaged flo POST /api/v1/automation/:name/clone — Copy a flow, switched off, into a package GET /api/v1/automation/:name/runs — List execution runs GET /api/v1/automation/:name/runs/:runId — Get single execution run +POST /api/v1/automation/_record-starts — Flows a proposed record update would start ``` @@ -58,8 +59,8 @@ GET /api/v1/automation/:name/runs/:runId — Get single execution run ## TypeScript Usage ```typescript -import { AutomationApiErrorCode, AutomationFlowPathParamsSchema, AutomationRunPathParamsSchema, CloneFlowRequestSchema, CloneFlowResponseSchema, CreateFlowRequestSchema, CreateFlowResponseSchema, DeleteFlowRequestSchema, DeleteFlowResponseSchema, FlowFailureDetailsSchema, FlowInnerRefusalSchema, GetFlowRequestSchema, GetFlowResponseSchema, GetRunRequestSchema, GetRunResponseSchema, ListRunsRequestSchema, ListRunsResponseSchema, ResumeFailureDetailsSchema, ToggleFlowRequestSchema, ToggleFlowResponseSchema, TriggerFlowRequestSchema, TriggerFlowResponseSchema, UpdateFlowRequestSchema, UpdateFlowResponseSchema } from '@objectstack/spec/api'; -import type { AutomationApiErrorCode, AutomationFlowPathParams, AutomationRunPathParams, CloneFlowRequest, CloneFlowResponse, CreateFlowRequest, CreateFlowResponse, DeleteFlowRequest, DeleteFlowResponse, FlowFailureDetails, FlowInnerRefusal, GetFlowRequest, GetFlowResponse, GetRunRequest, GetRunResponse, ListRunsRequest, ListRunsResponse, ResumeFailureDetails, ToggleFlowRequest, ToggleFlowResponse, TriggerFlowRequest, TriggerFlowResponse, UpdateFlowRequest, UpdateFlowResponse } from '@objectstack/spec/api'; +import { AutomationApiErrorCode, AutomationFlowPathParamsSchema, AutomationRunPathParamsSchema, CloneFlowRequestSchema, CloneFlowResponseSchema, CreateFlowRequestSchema, CreateFlowResponseSchema, DeleteFlowRequestSchema, DeleteFlowResponseSchema, FlowFailureDetailsSchema, FlowInnerRefusalSchema, GetFlowRequestSchema, GetFlowResponseSchema, GetRunRequestSchema, GetRunResponseSchema, ListRunsRequestSchema, ListRunsResponseSchema, RecordUpdateStartSchema, RecordUpdateStartsRequestSchema, RecordUpdateStartsResponseSchema, ResumeFailureDetailsSchema, ToggleFlowRequestSchema, ToggleFlowResponseSchema, TriggerFlowRequestSchema, TriggerFlowResponseSchema, UpdateFlowRequestSchema, UpdateFlowResponseSchema } from '@objectstack/spec/api'; +import type { AutomationApiErrorCode, AutomationFlowPathParams, AutomationRunPathParams, CloneFlowRequest, CloneFlowResponse, CreateFlowRequest, CreateFlowResponse, DeleteFlowRequest, DeleteFlowResponse, FlowFailureDetails, FlowInnerRefusal, GetFlowRequest, GetFlowResponse, GetRunRequest, GetRunResponse, ListRunsRequest, ListRunsResponse, RecordUpdateStart, RecordUpdateStartsRequest, RecordUpdateStartsResponse, ResumeFailureDetails, ToggleFlowRequest, ToggleFlowResponse, TriggerFlowRequest, TriggerFlowResponse, UpdateFlowRequest, UpdateFlowResponse } from '@objectstack/spec/api'; // Validate data const result = AutomationApiErrorCode.parse(data); @@ -1022,6 +1023,75 @@ const result = AutomationApiErrorCode.parse(data); | **hasMore** | `boolean` | ✅ | Whether more runs matched than this response carries — widen `limit` to see them. Under `status`, `false` means no further match within the scanned window rather than none at all: the window is taken before the filter is applied. | +--- + +## RecordUpdateStart + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **name** | `string` | ✅ | The flow's machine name — the key a client translates its label by (`flows..label`). | +| **label** | `string` | ✅ | The flow's display label as authored (a client translates it by `name`). | +| **startsApproval** | `boolean` | ✅ | Whether the flow contains an approval node, so the update starts an approval. | + + +--- + +## RecordUpdateStartsRequest + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **object** | `string` | ✅ | Machine name of the record's object. | +| **recordId** | `string` | ✅ | Id of the record the update would write. | +| **changes** | `Record` | ✅ | The proposed update: each field it sets and its new value. The record's other fields are read as stored. | + + +--- + +## RecordUpdateStartsResponse + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **success** | `boolean` | ✅ | Operation success status | +| **error** | `{ code: Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| …>; declaredCode?: string; message: string; userMessage?: string; … }` | optional | Error details if success is false | +| **meta** | `{ timestamp: string; duration?: integer; requestId?: string; traceId?: string }` | optional | Response metadata | +| **data** | `{ flows: object[] }` | ✅ | | + +### Nested Shape: `RecordUpdateStartsResponse.error` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| …>` | ✅ | Error code (e.g. VALIDATION_ERROR; StandardErrorCode ∪ the ledger the serving side registers — ERROR_CODE_LEDGER for framework packages) | +| **declaredCode** | `string` | optional | The producer-declared code, verbatim, when it is not a member of the closed `code` vocabulary — the open, author-authored channel (app-specific spellings; ADR-0112) | +| **message** | `string` | ✅ | Readable error message | +| **userMessage** | `string` | optional | Producer-marked user-facing refusal text, verbatim, in the request's locale: platform-composed text falls back to the workspace default locale, then `en`; an app-authored refusal falls back to its declared wording. Present exactly when the producer opted in at throw time; consumers render it to end users as received and keep their generic substitution for anything unmarked. Status-agnostic; never replaces `message`. | +| **refusal** | `true` | optional | Producer-declared: the 5xx this envelope carries is a deliberate refusal whose `message` is authored for the caller, so a boundary that reads the declaration keeps it verbatim (until the withhold arms read it, a declared refusal is still withheld). Absent (the default) on a declared fault, whose `message` is withheld from the body and logged for the operator; redundant on a 4xx. Presence is the declaration — `true` is the only value. | +| **category** | `string` | optional | Error category (e.g. validation, authorization) | +| **httpStatus** | `integer` | optional | HTTP status of the response carrying this error | +| **details** | `any` | optional | Additional error context (e.g. field validation errors) | +| **requestId** | `string` | optional | Request ID for tracking | + +### Nested Shape: `RecordUpdateStartsResponse.meta` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **timestamp** | `string` | ✅ | | +| **duration** | `integer` | optional | Server-side processing duration in milliseconds | +| **requestId** | `string` | optional | | +| **traceId** | `string` | optional | | + +### Nested Shape: `RecordUpdateStartsResponse.data` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **flows** | `{ name: string; label: string; startsApproval: boolean }[]` | ✅ | The flows the update would start, in no promised order. | + + --- ## ResumeFailureDetails diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 9e4d718f8e7..b9d802633e2 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1703 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1706 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -21,7 +21,7 @@ counts are sums of the rows they head. Regenerate with | Module | Pages | Schemas | Description | | :--- | ---: | ---: | :--- | | [AI Protocol](/docs/references/ai) | 14 | 84 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | -| [API Protocol](/docs/references/api) | 37 | 521 | REST contracts, endpoints, routing, realtime, batch, discovery. | +| [API Protocol](/docs/references/api) | 37 | 524 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | | [Data Protocol](/docs/references/data) | 35 | 191 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | | [Identity Protocol](/docs/references/identity) | 5 | 27 | Users and accounts, organizations, positions, SCIM provisioning. | @@ -34,7 +34,7 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 297 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 16 | 180 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **219** | **1703** | 14 protocol modules | +| **Total** | **219** | **1706** | 14 protocol modules | --- @@ -65,7 +65,7 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. ## API Protocol -**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **37 pages, 521 schemas** +**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **37 pages, 524 schemas** REST contracts, endpoints, routing, realtime, batch, discovery. @@ -76,7 +76,7 @@ REST contracts, endpoints, routing, realtime, batch, discovery. | [`app-bundle.zod.ts`](/docs/references/api/app-bundle) | `AppMetadataBundleResponse` | | [`auth.zod.ts`](/docs/references/api/auth) | `AuthProvider`, `LoginRequest`, `LoginType`, `MePermissionsAnonymousResponse`, `MePermissionsAuthenticatedResponse`, `MePermissionsResponse`, `RefreshTokenRequest`, `RegisterRequest`, `Session`, `SessionResponse`, `SessionUser`, `UserProfileResponse` | | [`auth-endpoints.zod.ts`](/docs/references/api/auth-endpoints) | `AuthEndpoint`, `AuthFeaturesConfig`, `AuthProviderInfo`, `DeviceRequestResponse`, `DeviceTokenResponse`, `EmailPasswordConfigPublic`, `GetAuthConfigResponse`, `OneTimeTokenHandoffQuery`, `OneTimeTokenVerifyRequest`, `OneTimeTokenVerifyResponse`, `OrganizationEditionChoice` | -| [`automation-api.zod.ts`](/docs/references/api/automation-api) | `AutomationApiErrorCode`, `AutomationFlowPathParams`, `AutomationRunPathParams`, `CloneFlowRequest`, `CloneFlowResponse`, `CreateFlowRequest`, `CreateFlowResponse`, `DeleteFlowRequest`, `DeleteFlowResponse`, `FlowFailureDetails`, `FlowInnerRefusal`, `GetFlowRequest`, `GetFlowResponse`, `GetRunRequest`, `GetRunResponse`, `ListRunsRequest`, `ListRunsResponse`, `ResumeFailureDetails`, `ToggleFlowRequest`, `ToggleFlowResponse`, `TriggerFlowRequest`, `TriggerFlowResponse`, `UpdateFlowRequest`, `UpdateFlowResponse` | +| [`automation-api.zod.ts`](/docs/references/api/automation-api) | `AutomationApiErrorCode`, `AutomationFlowPathParams`, `AutomationRunPathParams`, `CloneFlowRequest`, `CloneFlowResponse`, `CreateFlowRequest`, `CreateFlowResponse`, `DeleteFlowRequest`, `DeleteFlowResponse`, `FlowFailureDetails`, `FlowInnerRefusal`, `GetFlowRequest`, `GetFlowResponse`, `GetRunRequest`, `GetRunResponse`, `ListRunsRequest`, `ListRunsResponse`, `RecordUpdateStart`, `RecordUpdateStartsRequest`, `RecordUpdateStartsResponse`, `ResumeFailureDetails`, `ToggleFlowRequest`, `ToggleFlowResponse`, `TriggerFlowRequest`, `TriggerFlowResponse`, `UpdateFlowRequest`, `UpdateFlowResponse` | | [`batch.zod.ts`](/docs/references/api/batch) | `BatchConfig`, `BatchOperationResult`, `BatchOperationType`, `BatchOptions`, `BatchRecord`, `BatchUpdateRequest`, `BatchUpdateResponse`, `CrossObjectBatchDroppedFields`, `CrossObjectBatchOperation`, `CrossObjectBatchRequest`, `CrossObjectBatchResponse`, `DeleteManyRequest`, `UpdateManyRecord`, `UpdateManyRequest` | | [`contract.zod.ts`](/docs/references/api/contract) | `ApiError`, `BaseResponse`, `BatchLoadingStrategy`, `BulkRequest`, `BulkResponse`, `CreateRequest`, `DataLoaderConfig`, `DeleteResponse`, `ExportRequest`, `IdRequest`, `ListRecordResponse`, `ModificationResult`, `QueryOptimizationConfig`, `RecordData`, `SingleRecordResponse`, `UpdateRequest` | | [`discovery.zod.ts`](/docs/references/api/discovery) | `ApiRoutes`, `AuthFamilies`, `CapabilityDescriptor`, `Discovery`, `DiscoveryEnvironment`, `EnvironmentType`, `RouteHealthEntry`, `RouteHealthReport`, `ServiceInfo`, `ServiceSelfInfo`, `ServiceStatus`, `WellKnownCapabilities` | diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md index d7957730d2b..9dae95346fe 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `api/` | 533 | +| `api/` | 536 | diff --git a/packages/runtime/src/domains/automation-record-update-starts.test.ts b/packages/runtime/src/domains/automation-record-update-starts.test.ts index 8cca9afdd91..34dfff5f436 100644 --- a/packages/runtime/src/domains/automation-record-update-starts.test.ts +++ b/packages/runtime/src/domains/automation-record-update-starts.test.ts @@ -19,6 +19,9 @@ import { recordNotFoundError } from '@objectstack/core'; import { RecordUpdateStartsResponseSchema } from '@objectstack/spec/api'; import type { RecordUpdateStartsInput } from '@objectstack/spec/contracts'; +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/metadata'; + import { HttpDispatcher } from '../http-dispatcher.js'; const STORED = { id: 'p1', status: 'active', name: 'Apollo' }; diff --git a/packages/runtime/src/route-ledger.ts b/packages/runtime/src/route-ledger.ts index 46fc72f4360..ffe7ce3ef41 100644 --- a/packages/runtime/src/route-ledger.ts +++ b/packages/runtime/src/route-ledger.ts @@ -301,7 +301,7 @@ export const NON_DISPATCH_MOUNT_PREFIXES = [ /** * The ledger. * - * CENSUS (generated): this list holds 149 rows. + * CENSUS (generated): this list holds 150 rows. * * ⛔ THAT NUMBER IS WRITTEN BY A TOOL — never by hand. * `pnpm check:route-ledger-census` counts the rows below and fails when the two diff --git a/packages/spec/api-surface/api.json b/packages/spec/api-surface/api.json index 6d2c04ef346..9cd4209fd06 100644 --- a/packages/spec/api-surface/api.json +++ b/packages/spec/api-surface/api.json @@ -1047,6 +1047,15 @@ "RecordPageTimelineRequest (type)", "RecordPageTimelineRequestParsed (type)", "RecordPageTimelineRequestSchema (const)", + "RecordUpdateStart (type)", + "RecordUpdateStartParsed (type)", + "RecordUpdateStartSchema (const)", + "RecordUpdateStartsRequest (type)", + "RecordUpdateStartsRequestParsed (type)", + "RecordUpdateStartsRequestSchema (const)", + "RecordUpdateStartsResponse (type)", + "RecordUpdateStartsResponseParsed (type)", + "RecordUpdateStartsResponseSchema (const)", "RefreshTokenRequest (type)", "RefreshTokenRequestSchema (const)", "RegisterDeviceRequest (type)", diff --git a/packages/spec/api-surface/automation.json b/packages/spec/api-surface/automation.json index fcc0ddd2bbd..88a17850582 100644 --- a/packages/spec/api-surface/automation.json +++ b/packages/spec/api-surface/automation.json @@ -365,6 +365,8 @@ "normalizeFlowFunctionEntry (function)", "parseFlowNodeRegions (function)", "predicateSlotRefusal (function)", + "recordChangeTriggerFiresOnUpdate (function)", + "recordChangeTriggerHookEvents (function)", "reservedFlowNodeTypeRefusal (function)", "resolveFlowNodeExpressions (function)", "resolveFlowNodeValueSlots (function)", diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index 7f8acd80673..b5a95b593d5 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -322,6 +322,7 @@ "RealtimeSubscriptionOptions (interface)", "RecordShare (interface)", "RecordShareRecipientType (type)", + "RecordUpdateStartsInput (interface)", "RemoteTable (interface)", "RenderTemplateInput (interface)", "RenderTemplateResult (interface)", diff --git a/packages/spec/declaration-map/api.json b/packages/spec/declaration-map/api.json index 85c5d2b94de..9c5d1d9e019 100644 --- a/packages/spec/declaration-map/api.json +++ b/packages/spec/declaration-map/api.json @@ -773,6 +773,12 @@ "RecordPageTimelineCountSchema": "api/RecordPageTimelineCount", "RecordPageTimelineRequest": "api/RecordPageTimelineRequest", "RecordPageTimelineRequestSchema": "api/RecordPageTimelineRequest", + "RecordUpdateStart": "api/RecordUpdateStart", + "RecordUpdateStartSchema": "api/RecordUpdateStart", + "RecordUpdateStartsRequest": "api/RecordUpdateStartsRequest", + "RecordUpdateStartsRequestSchema": "api/RecordUpdateStartsRequest", + "RecordUpdateStartsResponse": "api/RecordUpdateStartsResponse", + "RecordUpdateStartsResponseSchema": "api/RecordUpdateStartsResponse", "RefreshTokenRequest": "api/RefreshTokenRequest", "RefreshTokenRequestSchema": "api/RefreshTokenRequest", "RegisterDeviceRequest": "api/RegisterDeviceRequest", diff --git a/packages/spec/export-origins/api.json b/packages/spec/export-origins/api.json index 7663e6efaed..dc220eb046e 100644 --- a/packages/spec/export-origins/api.json +++ b/packages/spec/export-origins/api.json @@ -1016,6 +1016,15 @@ "RecordPageTimelineRequest": "src/api/record-page.zod.ts#RecordPageTimelineRequest (type)", "RecordPageTimelineRequestParsed": "src/api/record-page.zod.ts#RecordPageTimelineRequestParsed (type)", "RecordPageTimelineRequestSchema": "src/api/record-page.zod.ts#RecordPageTimelineRequestSchema (const)", + "RecordUpdateStart": "src/api/automation-api.zod.ts#RecordUpdateStart (type)", + "RecordUpdateStartParsed": "src/api/automation-api.zod.ts#RecordUpdateStartParsed (type)", + "RecordUpdateStartSchema": "src/api/automation-api.zod.ts#RecordUpdateStartSchema (const)", + "RecordUpdateStartsRequest": "src/api/automation-api.zod.ts#RecordUpdateStartsRequest (type)", + "RecordUpdateStartsRequestParsed": "src/api/automation-api.zod.ts#RecordUpdateStartsRequestParsed (type)", + "RecordUpdateStartsRequestSchema": "src/api/automation-api.zod.ts#RecordUpdateStartsRequestSchema (const)", + "RecordUpdateStartsResponse": "src/api/automation-api.zod.ts#RecordUpdateStartsResponse (type)", + "RecordUpdateStartsResponseParsed": "src/api/automation-api.zod.ts#RecordUpdateStartsResponseParsed (type)", + "RecordUpdateStartsResponseSchema": "src/api/automation-api.zod.ts#RecordUpdateStartsResponseSchema (const)", "RefreshTokenRequest": "src/api/auth.zod.ts#RefreshTokenRequest (type)", "RefreshTokenRequestSchema": "src/api/auth.zod.ts#RefreshTokenRequestSchema (const)", "RegisterDeviceRequest": "src/api/protocol.zod.ts#RegisterDeviceRequest (type)", diff --git a/packages/spec/export-origins/automation.json b/packages/spec/export-origins/automation.json index cc4e09f0d43..4514964427b 100644 --- a/packages/spec/export-origins/automation.json +++ b/packages/spec/export-origins/automation.json @@ -358,6 +358,8 @@ "normalizeFlowFunctionEntry": "src/automation/flow-function.zod.ts#normalizeFlowFunctionEntry (function)", "parseFlowNodeRegions": "src/automation/control-flow.zod.ts#parseFlowNodeRegions (function)", "predicateSlotRefusal": "src/automation/flow-node-expression-paths.ts#predicateSlotRefusal (function)", + "recordChangeTriggerFiresOnUpdate": "src/automation/record-change-trigger-events.ts#recordChangeTriggerFiresOnUpdate (function)", + "recordChangeTriggerHookEvents": "src/automation/record-change-trigger-events.ts#recordChangeTriggerHookEvents (function)", "reservedFlowNodeTypeRefusal": "src/automation/flow-reserved-node-types.ts#reservedFlowNodeTypeRefusal (function)", "resolveFlowNodeExpressions": "src/automation/flow-node-expression-paths.ts#resolveFlowNodeExpressions (function)", "resolveFlowNodeValueSlots": "src/automation/flow-node-expression-paths.ts#resolveFlowNodeValueSlots (function)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index e7fd61240ad..5161d5f6af9 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -322,6 +322,7 @@ "RealtimeSubscriptionOptions": "src/contracts/realtime-service.ts#RealtimeSubscriptionOptions (interface)", "RecordShare": "src/contracts/sharing-service.ts#RecordShare (interface)", "RecordShareRecipientType": "src/contracts/sharing-service.ts#RecordShareRecipientType (type)", + "RecordUpdateStartsInput": "src/contracts/automation-service.ts#RecordUpdateStartsInput (interface)", "RemoteTable": "src/contracts/external-datasource-service.ts#RemoteTable (interface)", "RenderTemplateInput": "src/contracts/email-service.ts#RenderTemplateInput (interface)", "RenderTemplateResult": "src/contracts/email-service.ts#RenderTemplateResult (interface)", diff --git a/packages/triggers/trigger-record-change/vitest.config.ts b/packages/triggers/trigger-record-change/vitest.config.ts index b095a97a8b6..7385df8cdfb 100644 --- a/packages/triggers/trigger-record-change/vitest.config.ts +++ b/packages/triggers/trigger-record-change/vitest.config.ts @@ -39,6 +39,9 @@ export default defineConfig({ alias: [ { find: /^@objectstack\/formula$/, replacement: path.resolve(__dirname, '../../formula/src/index.ts') }, { find: /^@objectstack\/spec\/data$/, replacement: path.resolve(__dirname, '../../spec/src/data/index.ts') }, + // `@objectstack/spec/automation` carries `recordChangeTriggerHookEvents`, the + // token grammar `triggerTypeToHookEvents` delegates to (#35928). + { find: /^@objectstack\/spec\/automation$/, replacement: path.resolve(__dirname, '../../spec/src/automation/index.ts') }, // `@objectstack/core` carries `omitInternalFieldsFromWriteResponse`, the // ADR-0100 mask helper `record-change-trigger.ts` applies, so the mask // pins read it from source rather than from core's `dist/`. From 0658fbc5e7807b52cd07263a7eac5e27ad1919cb Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 05:44:21 +0000 Subject: [PATCH 05/11] test(console): fold the #35928 confirm pins into each confirm's harness file Per the shared-harness rule (ruling record 6583487846): the list cell's pins join ObjectGrid.autosave-35685, the record page's join record-path.stageChange-28199 and RecordStageMenu-35891, each as a top-level describe. Claude-Session: https://claude.ai/code/session_01FEkQ5keqTTiV8ptWFNc6ZF Co-authored-by: Claude --- .../__tests__/RecordStageMenu-35891.test.tsx | 72 ++++++ .../stageChangeStarts-35928.test.tsx | 203 ----------------- .../record-path.stageChange-28199.test.tsx | 72 ++++++ .../ObjectGrid.autosave-35685.test.tsx | 160 +++++++++++++- .../ObjectGrid.stageStarts-35928.test.tsx | 207 ------------------ 5 files changed, 303 insertions(+), 411 deletions(-) delete mode 100644 ui/packages/plugin-detail/src/__tests__/stageChangeStarts-35928.test.tsx delete mode 100644 ui/packages/plugin-grid/src/__tests__/ObjectGrid.stageStarts-35928.test.tsx diff --git a/ui/packages/plugin-detail/src/__tests__/RecordStageMenu-35891.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordStageMenu-35891.test.tsx index 7c37df4ff85..25ed861e926 100644 --- a/ui/packages/plugin-detail/src/__tests__/RecordStageMenu-35891.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RecordStageMenu-35891.test.tsx @@ -489,3 +489,75 @@ describe('#35891 the keyboard', () => { await waitFor(() => expect(within(dialog).getByRole('button', { name: 'Cancel' })).toHaveFocus()); }); }); + +// objectstack#35928 — under its sentence the confirm names the flows the move +// would start (`POST /api/v1/automation/_record-starts`, read through +// `../stageChangeStarts`, the reader the list cell's confirm shares); no flows, +// a refused read and a malformed answer leave the sentence alone. +describe('#35928 the stage menu\'s dialog names the flows the move starts', () => { + const CLOSURE = { name: 'closure', label: 'Closure Sign-off', startsApproval: true }; + const NOTIFY = { name: 'notify_owner', label: 'Notify Owner', startsApproval: false }; + type StartsAnswer = { status: number; body: unknown } | 'network-error'; + + /** The global `fetch`, answering the read with `answer` and recording every request. */ + function installStartsFetch(answer: StartsAnswer) { + const calls: Array<{ url: string; body: any }> = []; + vi.stubGlobal('fetch', vi.fn(async (url: unknown, init?: { body?: unknown }) => { + calls.push({ url: String(url), body: init?.body ? JSON.parse(String(init.body)) : undefined }); + if (answer === 'network-error') throw new TypeError('Failed to fetch'); + return { ok: answer.status < 400, status: answer.status, json: async () => answer.body }; + })); + return calls; + } + const listed = (flows: unknown[]): StartsAnswer => ({ status: 200, body: { success: true, data: { flows } } }); + const startsCalls = (calls: Array<{ url: string }>) => calls.filter((c) => c.url === '/api/v1/automation/_record-starts'); + /** Let an answer that arrived land before reading that nothing was drawn for it. */ + const settle = () => new Promise((r) => setTimeout(r, 0)); + + async function openConfirm(): Promise { + mount(); + fireEvent.click(item(openMenu(), 'Negotiation')); + return screen.findByRole('dialog'); + } + + it('list: asks for the record and the move, and names each flow under the sentence, approval marked', async () => { + const calls = installStartsFetch(listed([CLOSURE, NOTIFY])); + const dialog = await openConfirm(); + const list = await within(dialog).findByTestId('stage-change-starts'); + expect(within(dialog).getByText('Move this record to Negotiation?')).toBeInTheDocument(); + expect(list).toHaveTextContent('Saving this change starts these flows:'); + const closure = list.querySelector('[data-stage-change-start="closure"]')!; + const notify = list.querySelector('[data-stage-change-start="notify_owner"]')!; + expect(closure).toHaveTextContent('Closure Sign-off'); + expect(closure.querySelector('[data-stage-change-start-approval]')).toHaveTextContent('starts an approval'); + expect(notify).toHaveTextContent('Notify Owner'); + expect(notify.querySelector('[data-stage-change-start-approval]')).toBeNull(); + expect(startsCalls(calls).map((c: any) => c.body)).toEqual([{ object: 'crm_opportunity', recordId: 'o1', changes: { stage: 'negotiation' } }]); + }); + + it('empty: no flows answered draws no list, and the sentence stands alone', async () => { + const calls = installStartsFetch(listed([])); + const dialog = await openConfirm(); + await waitFor(() => expect(startsCalls(calls)).toHaveLength(1)); + await settle(); + expect(within(dialog).queryByTestId('stage-change-starts')).toBeNull(); + expect(within(dialog).getByText('Move this record to Negotiation?')).toBeInTheDocument(); + }); + + it('failure: a refused read, a network error and a malformed answer each draw no list', async () => { + const answers: StartsAnswer[] = [ + { status: 404, body: { success: false, error: { code: 'RECORD_NOT_FOUND', message: 'no' } } }, + 'network-error', + { status: 200, body: { flows: [CLOSURE] } }, + ]; + for (const answer of answers) { + const calls = installStartsFetch(answer); + const dialog = await openConfirm(); + await waitFor(() => expect(startsCalls(calls)).toHaveLength(1)); + await settle(); + expect(within(dialog).queryByTestId('stage-change-starts')).toBeNull(); + expect(within(dialog).getByText('Move this record to Negotiation?')).toBeInTheDocument(); + cleanup(); + } + }); +}); diff --git a/ui/packages/plugin-detail/src/__tests__/stageChangeStarts-35928.test.tsx b/ui/packages/plugin-detail/src/__tests__/stageChangeStarts-35928.test.tsx deleted file mode 100644 index f372f8ea478..00000000000 --- a/ui/packages/plugin-detail/src/__tests__/stageChangeStarts-35928.test.tsx +++ /dev/null @@ -1,203 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * objectstack#35928 — the record page's stage confirm names the flows the - * move would start (ruling record 7073655354), through `../stageChangeStarts`, - * the reader the list cell's confirm shares. Both of the page's confirms are - * pinned: `record:path`'s plain confirmation and the header stage menu's - * dialog (`RecordStageMenu`, the shared `RequiredFieldsDialog`). - * - * 1. List: the confirm asks `POST /api/v1/automation/_record-starts` for the - * record and the move, and names each flow by label under today's - * sentence, a flow holding an approval marked as such. - * 2. Empty: an answer of no flows draws no list; the sentence stands alone. - * 3. Failure: a refused read draws no list; the sentence stands alone, and - * the move still writes on Move. - * - * `@object-ui/*` resolves to source through the root vitest alias table. - */ - -import * as React from 'react'; -import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; -import { render, cleanup, fireEvent, screen, waitFor, within } from '@testing-library/react'; -import '@testing-library/jest-dom'; -import { InlineEditProvider, RecordContextProvider } from '@object-ui/react'; - -vi.mock('@object-ui/permissions', async (importOriginal) => { - const actual = await importOriginal(); - const stub = { - isLoaded: true, - checkField: () => true, - check: () => ({ allowed: true }), - getFieldPermissions: () => [], - getRowFilter: () => undefined, - getObjectApiOperations: () => undefined, - roles: [], - userId: null, - systemPermissions: undefined, - hasCapabilities: () => true, - can: () => true, - cannot: () => false, - }; - return { ...actual, usePermissions: () => stub as any }; -}); - -import { RecordPathRenderer } from '../renderers/record-path'; -import { RecordStageMenu } from '../RecordStageMenu'; - -const VERSION = '2026-11-20T12:00:00.000Z'; -const CLOSURE = { name: 'project_closure', label: 'Project Closure', startsApproval: true }; -const NOTIFY = { name: 'notify_owner', label: 'Notify Owner', startsApproval: false }; - -const PROJECT = { - name: 'project', - fields: { - name: { type: 'text', label: 'Name' }, - status: { - type: 'select', - label: 'Status', - options: [ - { value: 'active', label: 'Active' }, - { value: 'completed', label: 'Completed' }, - ], - }, - }, -}; - -type StartsAnswer = { status: number; body: unknown } | 'network-error'; - -/** The global `fetch`, answering `_record-starts` with `answer` and recording every request. */ -function installFetch(answer: StartsAnswer) { - const calls: Array<{ url: string; body: any }> = []; - vi.stubGlobal('fetch', vi.fn(async (url: unknown, init?: { body?: unknown }) => { - calls.push({ url: String(url), body: init?.body ? JSON.parse(String(init.body)) : undefined }); - if (answer === 'network-error') throw new TypeError('Failed to fetch'); - return { ok: answer.status < 400, status: answer.status, json: async () => answer.body }; - })); - return calls; -} - -const listed = (flows: unknown[]): StartsAnswer => ({ status: 200, body: { success: true, data: { flows } } }); - -function Host({ children }: { children: React.ReactNode }) { - const [dataSource] = React.useState(() => ({ update: vi.fn(async () => ({})) })); - return ( - {}} - > - {children} - - ); -} - -/** `record:path`'s confirmation, opened on Completed. */ -async function openPathConfirm(): Promise { - const { container } = render( - - - , - ); - const rail = container.querySelector('[role="list"]') as HTMLElement; - fireEvent.click(within(rail).getByRole('button', { name: 'Move to Completed' })); - return screen.findByRole('alertdialog'); -} - -/** The header stage menu's dialog, opened on Completed. */ -async function openMenuConfirm(): Promise { - render( - - Active} /> - , - ); - fireEvent.pointerDown(screen.getByRole('button', { name: /^Stage: / }), { button: 0, ctrlKey: false, pointerType: 'mouse' }); - const item = within(screen.getByRole('menu')).getAllByRole('menuitem').find((el) => el.textContent?.startsWith('Completed'))!; - fireEvent.click(item); - return screen.findByRole('dialog'); -} - -const startsCalls = (calls: Array<{ url: string; body: any }>) => - calls.filter((c) => c.url === '/api/v1/automation/_record-starts'); - -const CONFIRMS: Array<[string, () => Promise]> = [ - ['record:path confirmation', openPathConfirm], - ['header stage menu dialog', openMenuConfirm], -]; - -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -describe.each(CONFIRMS)('#35928 the %s names the flows the move starts', (_name, open) => { - let calls: Array<{ url: string; body: any }>; - beforeEach(() => { - calls = []; - }); - - it('list: asks for the record and the move, and names each flow under the sentence, approval marked', async () => { - calls = installFetch(listed([CLOSURE, NOTIFY])); - const dialog = await open(); - const list = await within(dialog).findByTestId('stage-change-starts'); - expect(within(dialog).getByText('Move this record to Completed?')).toBeInTheDocument(); - expect(list).toHaveTextContent('Saving this change starts these flows:'); - const closure = list.querySelector('[data-stage-change-start="project_closure"]')!; - const notify = list.querySelector('[data-stage-change-start="notify_owner"]')!; - expect(closure).toHaveTextContent('Project Closure'); - expect(closure.querySelector('[data-stage-change-start-approval]')).toHaveTextContent('starts an approval'); - expect(notify).toHaveTextContent('Notify Owner'); - expect(notify.querySelector('[data-stage-change-start-approval]')).toBeNull(); - expect(startsCalls(calls).map((c) => c.body)).toEqual([ - { object: 'project', recordId: 'p1', changes: { status: 'completed' } }, - ]); - }); - - it('empty: no flows answered draws no list, and the sentence stands alone', async () => { - calls = installFetch(listed([])); - const dialog = await open(); - await waitFor(() => expect(startsCalls(calls)).toHaveLength(1)); - await new Promise((r) => setTimeout(r, 0)); - expect(within(dialog).queryByTestId('stage-change-starts')).toBeNull(); - expect(within(dialog).getByText('Move this record to Completed?')).toBeInTheDocument(); - }); - - it('failure: a refused read and a network error draw no list, and the sentence stands alone', async () => { - calls = installFetch({ status: 404, body: { success: false, error: { code: 'RECORD_NOT_FOUND', message: 'no' } } }); - const refused = await open(); - await waitFor(() => expect(startsCalls(calls)).toHaveLength(1)); - await new Promise((r) => setTimeout(r, 0)); - expect(within(refused).queryByTestId('stage-change-starts')).toBeNull(); - expect(within(refused).getByText('Move this record to Completed?')).toBeInTheDocument(); - cleanup(); - vi.unstubAllGlobals(); - - calls = installFetch('network-error'); - const failed = await open(); - await waitFor(() => expect(startsCalls(calls)).toHaveLength(1)); - await new Promise((r) => setTimeout(r, 0)); - expect(within(failed).queryByTestId('stage-change-starts')).toBeNull(); - expect(within(failed).getByText('Move this record to Completed?')).toBeInTheDocument(); - }); - - it('a malformed answer (not the declared envelope) draws no list', async () => { - calls = installFetch({ status: 200, body: { flows: [CLOSURE] } }); - const dialog = await open(); - await waitFor(() => expect(startsCalls(calls)).toHaveLength(1)); - await new Promise((r) => setTimeout(r, 0)); - expect(within(dialog).queryByTestId('stage-change-starts')).toBeNull(); - }); -}); diff --git a/ui/packages/plugin-detail/src/renderers/__tests__/record-path.stageChange-28199.test.tsx b/ui/packages/plugin-detail/src/renderers/__tests__/record-path.stageChange-28199.test.tsx index 656e4cb0d35..d327b0fb086 100644 --- a/ui/packages/plugin-detail/src/renderers/__tests__/record-path.stageChange-28199.test.tsx +++ b/ui/packages/plugin-detail/src/renderers/__tests__/record-path.stageChange-28199.test.tsx @@ -466,3 +466,75 @@ describe('record:path allowStageChange — a status field carrying an expression ); }); }); + +// objectstack#35928 — under its sentence the confirm names the flows the move +// would start (`POST /api/v1/automation/_record-starts`, read through +// `../stageChangeStarts`, the reader the list cell's confirm shares); no flows, +// a refused read and a malformed answer leave the sentence alone. +describe('record:path allowStageChange — the confirmation names the flows the move starts (objectstack#35928)', () => { + const CLOSURE = { name: 'closure', label: 'Closure Sign-off', startsApproval: true }; + const NOTIFY = { name: 'notify_owner', label: 'Notify Owner', startsApproval: false }; + type StartsAnswer = { status: number; body: unknown } | 'network-error'; + + /** The global `fetch`, answering the read with `answer` and recording every request. */ + function installStartsFetch(answer: StartsAnswer) { + const calls: Array<{ url: string; body: any }> = []; + vi.stubGlobal('fetch', vi.fn(async (url: unknown, init?: { body?: unknown }) => { + calls.push({ url: String(url), body: init?.body ? JSON.parse(String(init.body)) : undefined }); + if (answer === 'network-error') throw new TypeError('Failed to fetch'); + return { ok: answer.status < 400, status: answer.status, json: async () => answer.body }; + })); + return calls; + } + const listed = (flows: unknown[]): StartsAnswer => ({ status: 200, body: { success: true, data: { flows } } }); + const startsCalls = (calls: Array<{ url: string }>) => calls.filter((c) => c.url === '/api/v1/automation/_record-starts'); + /** Let an answer that arrived land before reading that nothing was drawn for it. */ + const settle = () => new Promise((r) => setTimeout(r, 0)); + + async function openConfirm(): Promise { + const { container } = mount({ allowStageChange: true }); + fireEvent.click(within(rows(container)[0]).getByRole('button', { name: 'Move to Accepted' })); + return screen.findByRole('alertdialog'); + } + + it('list: asks for the record and the move, and names each flow under the sentence, approval marked', async () => { + const calls = installStartsFetch(listed([CLOSURE, NOTIFY])); + const dialog = await openConfirm(); + const list = await within(dialog).findByTestId('stage-change-starts'); + expect(within(dialog).getByText('Move this record to Accepted?')).toBeInTheDocument(); + expect(list).toHaveTextContent('Saving this change starts these flows:'); + const closure = list.querySelector('[data-stage-change-start="closure"]')!; + const notify = list.querySelector('[data-stage-change-start="notify_owner"]')!; + expect(closure).toHaveTextContent('Closure Sign-off'); + expect(closure.querySelector('[data-stage-change-start-approval]')).toHaveTextContent('starts an approval'); + expect(notify).toHaveTextContent('Notify Owner'); + expect(notify.querySelector('[data-stage-change-start-approval]')).toBeNull(); + expect(startsCalls(calls).map((c: any) => c.body)).toEqual([{ object: 'crm_quote', recordId: 'q1', changes: { status: 'accepted' } }]); + }); + + it('empty: no flows answered draws no list, and the sentence stands alone', async () => { + const calls = installStartsFetch(listed([])); + const dialog = await openConfirm(); + await waitFor(() => expect(startsCalls(calls)).toHaveLength(1)); + await settle(); + expect(within(dialog).queryByTestId('stage-change-starts')).toBeNull(); + expect(within(dialog).getByText('Move this record to Accepted?')).toBeInTheDocument(); + }); + + it('failure: a refused read, a network error and a malformed answer each draw no list', async () => { + const answers: StartsAnswer[] = [ + { status: 404, body: { success: false, error: { code: 'RECORD_NOT_FOUND', message: 'no' } } }, + 'network-error', + { status: 200, body: { flows: [CLOSURE] } }, + ]; + for (const answer of answers) { + const calls = installStartsFetch(answer); + const dialog = await openConfirm(); + await waitFor(() => expect(startsCalls(calls)).toHaveLength(1)); + await settle(); + expect(within(dialog).queryByTestId('stage-change-starts')).toBeNull(); + expect(within(dialog).getByText('Move this record to Accepted?')).toBeInTheDocument(); + cleanup(); + } + }); +}); diff --git a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx index 723abb30640..cd6f90bf035 100644 --- a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx @@ -33,9 +33,13 @@ * field and both values and saying automation may run; Cancel writes * nothing, Change writes the move. A field no active machine governs * saves without asking. + * 8. objectstack#35928: under its sentence that confirm names the flows the + * move would start (`POST /api/v1/automation/_record-starts`, read + * through `@object-ui/plugin-detail`'s `useRecordUpdateStarts`), an + * approval flow marked; no flows or a refused read leave the sentence alone. */ import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; -import { render, screen, waitFor, fireEvent, cleanup, act } from '@testing-library/react'; +import { render, screen, waitFor, fireEvent, cleanup, act, within } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; @@ -606,3 +610,157 @@ describe('ObjectGrid — a state-machine field is confirmed before a list cell s expect(ds.update).not.toHaveBeenCalled(); }); }); + +describe('ObjectGrid — the state-machine confirm names the flows the move starts (objectstack#35928)', () => { + const SENTENCE = 'Stage changes from New to Won. Saving may trigger related automation.'; + const CLOSURE = { name: 'deal_won', label: 'Deal Won Sign-off', startsApproval: true }; + const NOTIFY = { name: 'deal_notify', label: 'Notify Owner', startsApproval: false }; + + type StartsAnswer = { status: number; body: unknown }; + + /** + * The global `fetch`: the explain probe answers permissively (as + * `explainDouble` does), `_record-starts` answers `starts`; every call is + * recorded so the request the confirm sends can be read back. + */ + function installFetch(starts: StartsAnswer) { + const calls: Array<{ url: string; body: any }> = []; + vi.stubGlobal('fetch', vi.fn(async (url: unknown, init?: { body?: unknown }) => { + const body = init?.body ? JSON.parse(String(init.body)) : undefined; + calls.push({ url: String(url), body }); + if (String(url).endsWith('/automation/_record-starts')) { + return { ok: starts.status < 400, status: starts.status, json: async () => starts.body }; + } + const recordIds = Array.isArray(body?.recordIds) ? body.recordIds : undefined; + return { + ok: true, + status: 200, + json: async () => ({ + allowed: true, + layers: [], + ...(recordIds ? { records: recordIds.map((id: string) => ({ recordId: id, visible: true })) } : {}), + ...(typeof body?.recordId === 'string' ? { record: { visible: true } } : {}), + }), + }; + })); + return calls; + } + + function makeStartsDataSource() { + const store: Record = { + d1: { id: 'd1', name: 'alpha', stage: 'new', updated_at: '2026-11-20T10:00:00.000Z' }, + d2: { id: 'd2', name: 'beta', stage: 'qualified', updated_at: '2026-11-20T10:00:00.000Z' }, + }; + return { + store, + find: vi.fn(async () => { + const data = Object.values(store).map((r) => ({ ...r })); + return { data, total: data.length, hasMore: false, pageSize: 50 }; + }), + update: vi.fn(async (_object: string, id: string, changes: Record) => { + store[id] = { ...store[id], ...changes, updated_at: '2026-11-20T11:00:00.000Z' }; + return { ...store[id] }; + }), + getObjectSchema: async (name: string) => ({ + name, + fields: { + id: { type: 'text' }, + name: { type: 'text', label: 'Name' }, + stage: { + type: 'select', + label: 'Stage', + options: [ + { value: 'new', label: 'New' }, + { value: 'qualified', label: 'Qualified' }, + { value: 'won', label: 'Won' }, + ], + }, + updated_at: { type: 'datetime' }, + }, + validations: [{ + name: 'stage_flow', + type: 'state_machine', + field: 'stage', + transitions: { new: ['qualified', 'won'], qualified: ['won'] }, + }], + }), + } as any; + } + + function renderStartsGrid(ds: any) { + const schema: any = { + type: 'object-grid', + objectName: OBJECT, + editable: true, + columns: [ + { field: 'name', label: 'Name' }, + { field: 'stage', label: 'Stage' }, + ], + pagination: { pageSize: 50 }, + }; + return render( + + + , + ); + } + + /** Paste `Won` into the first row's stage cell and wait for the confirm. */ + async function moveFirstRowToWon(container: HTMLElement): Promise { + fireEvent.click(dataCell(container, 0, 'New')); + const catcher = container.querySelector('[data-slot="cell-type-catcher"]')!; + fireEvent.paste(catcher, { clipboardData: { getData: () => 'Won' } }); + return screen.findByRole('alertdialog'); + } + + const startsCalls = (calls: Array<{ url: string; body: any }>) => + calls.filter((c) => c.url.endsWith('/automation/_record-starts')); + + it('list: asks for the row and the move, and names each flow under the sentence, approval marked', async () => { + const calls = installFetch({ status: 200, body: { success: true, data: { flows: [CLOSURE, NOTIFY] } } }); + const ds = makeStartsDataSource(); + const { container } = renderStartsGrid(ds); + await screen.findByText('beta'); + const dialog = await moveFirstRowToWon(container); + + const list = await within(dialog).findByTestId('stage-change-starts'); + expect(dialog).toHaveTextContent(SENTENCE); + expect(list).toHaveTextContent('Saving this change starts these flows:'); + const closure = list.querySelector('[data-stage-change-start="deal_won"]')!; + const notify = list.querySelector('[data-stage-change-start="deal_notify"]')!; + expect(closure).toHaveTextContent('Deal Won Sign-off'); + expect(closure.querySelector('[data-stage-change-start-approval]')).toHaveTextContent('starts an approval'); + expect(notify).toHaveTextContent('Notify Owner'); + expect(notify.querySelector('[data-stage-change-start-approval]')).toBeNull(); + expect(startsCalls(calls).map((c) => c.body)).toEqual([ + { object: OBJECT, recordId: 'd1', changes: { stage: 'won' } }, + ]); + }); + + it('empty: no flows answered draws no list, and the sentence stands alone', async () => { + const calls = installFetch({ status: 200, body: { success: true, data: { flows: [] } } }); + const { container } = renderStartsGrid(makeStartsDataSource()); + await screen.findByText('beta'); + const dialog = await moveFirstRowToWon(container); + await waitFor(() => expect(startsCalls(calls)).toHaveLength(1)); + // Let the answer land before reading that nothing was drawn for it. + await new Promise((r) => setTimeout(r, 0)); + expect(within(dialog).queryByTestId('stage-change-starts')).toBeNull(); + expect(dialog).toHaveTextContent(SENTENCE); + }); + + it('failure: a refused read draws no list, the sentence stands, and Change still saves the move', async () => { + const calls = installFetch({ status: 500, body: { success: false, error: { code: 'INTERNAL_ERROR', message: 'boom' } } }); + const ds = makeStartsDataSource(); + const { container } = renderStartsGrid(ds); + await screen.findByText('beta'); + const dialog = await moveFirstRowToWon(container); + await waitFor(() => expect(startsCalls(calls)).toHaveLength(1)); + await new Promise((r) => setTimeout(r, 0)); + expect(within(dialog).queryByTestId('stage-change-starts')).toBeNull(); + expect(dialog).toHaveTextContent(SENTENCE); + fireEvent.click(within(dialog).getByRole('button', { name: 'Change' })); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); + expect(ds.update.mock.calls[0][2]).toEqual({ stage: 'won' }); + }); +}); diff --git a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.stageStarts-35928.test.tsx b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.stageStarts-35928.test.tsx deleted file mode 100644 index 886af519439..00000000000 --- a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.stageStarts-35928.test.tsx +++ /dev/null @@ -1,207 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * The list cell's state-machine confirm names the flows the move would start - * (objectstack#35928, ruling record 7073655354), read through - * `@object-ui/plugin-detail`'s `useRecordUpdateStarts` — the reader the record - * page's stage confirm shares. - * - * 1. List: the confirm asks `POST /api/v1/automation/_record-starts` for - * the row's record and the move, and names each flow it answers by label - * under today's sentence, a flow holding an approval marked as such. - * 2. Empty: an answer of no flows draws no list; the sentence stands alone. - * 3. Failure: a refused read draws no list; the sentence stands alone, and - * the move still saves on Change. - */ -import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; -import { render, screen, waitFor, fireEvent, cleanup, within } from '@testing-library/react'; -import '@testing-library/jest-dom'; -import React from 'react'; - -import { ObjectGrid } from '../ObjectGrid'; -import { registerAllFields } from '@object-ui/fields'; -import { ActionProvider } from '@object-ui/react'; -import { __clearRecordCrudVerdictCache } from '../hooks/useRecordCrudVerdicts'; -import { __resetApprovalsServiceLatch } from '../hooks/useRowApprovalLocks'; - -registerAllFields(); - -beforeAll(() => { - if (!Element.prototype.scrollIntoView) { - Element.prototype.scrollIntoView = vi.fn() as any; - } -}); - -const OBJECT = 'deal'; -const SENTENCE = 'Stage changes from New to Won. Saving may trigger related automation.'; -const CLOSURE = { name: 'deal_won', label: 'Deal Won Sign-off', startsApproval: true }; -const NOTIFY = { name: 'deal_notify', label: 'Notify Owner', startsApproval: false }; - -type StartsAnswer = { status: number; body: unknown }; - -/** - * The global `fetch`: the explain probe answers permissively (as - * `explainDouble` does), `_record-starts` answers `starts`; every call is - * recorded so the request the confirm sends can be read back. - */ -function installFetch(starts: StartsAnswer) { - const calls: Array<{ url: string; body: any }> = []; - vi.stubGlobal('fetch', vi.fn(async (url: unknown, init?: { body?: unknown }) => { - const body = init?.body ? JSON.parse(String(init.body)) : undefined; - calls.push({ url: String(url), body }); - if (String(url).endsWith('/automation/_record-starts')) { - return { ok: starts.status < 400, status: starts.status, json: async () => starts.body }; - } - const recordIds = Array.isArray(body?.recordIds) ? body.recordIds : undefined; - return { - ok: true, - status: 200, - json: async () => ({ - allowed: true, - layers: [], - ...(recordIds ? { records: recordIds.map((id: string) => ({ recordId: id, visible: true })) } : {}), - ...(typeof body?.recordId === 'string' ? { record: { visible: true } } : {}), - }), - }; - })); - return calls; -} - -function makeDataSource() { - const store: Record = { - d1: { id: 'd1', name: 'alpha', stage: 'new', updated_at: '2026-11-20T10:00:00.000Z' }, - d2: { id: 'd2', name: 'beta', stage: 'qualified', updated_at: '2026-11-20T10:00:00.000Z' }, - }; - return { - store, - find: vi.fn(async () => { - const data = Object.values(store).map((r) => ({ ...r })); - return { data, total: data.length, hasMore: false, pageSize: 50 }; - }), - update: vi.fn(async (_object: string, id: string, changes: Record) => { - store[id] = { ...store[id], ...changes, updated_at: '2026-11-20T11:00:00.000Z' }; - return { ...store[id] }; - }), - getObjectSchema: async (name: string) => ({ - name, - fields: { - id: { type: 'text' }, - name: { type: 'text', label: 'Name' }, - stage: { - type: 'select', - label: 'Stage', - options: [ - { value: 'new', label: 'New' }, - { value: 'qualified', label: 'Qualified' }, - { value: 'won', label: 'Won' }, - ], - }, - updated_at: { type: 'datetime' }, - }, - validations: [{ - name: 'stage_flow', - type: 'state_machine', - field: 'stage', - transitions: { new: ['qualified', 'won'], qualified: ['won'] }, - }], - }), - } as any; -} - -function renderGrid(ds: any) { - const schema: any = { - type: 'object-grid', - objectName: OBJECT, - editable: true, - columns: [ - { field: 'name', label: 'Name' }, - { field: 'stage', label: 'Stage' }, - ], - pagination: { pageSize: 50 }, - }; - return render( - - - , - ); -} - -const dataCell = (container: HTMLElement, row: number, text: string) => - Array.from(container.querySelectorAll('tbody tr')[row].querySelectorAll('td')) - .find((td) => td.textContent === text)!; - -/** Paste `Won` into the first row's stage cell and wait for the confirm. */ -async function moveFirstRowToWon(container: HTMLElement): Promise { - fireEvent.click(dataCell(container, 0, 'New')); - const catcher = container.querySelector('[data-slot="cell-type-catcher"]')!; - fireEvent.paste(catcher, { clipboardData: { getData: () => 'Won' } }); - return screen.findByRole('alertdialog'); -} - -const startsCalls = (calls: Array<{ url: string; body: any }>) => - calls.filter((c) => c.url.endsWith('/automation/_record-starts')); - -beforeEach(() => { - __clearRecordCrudVerdictCache(); - __resetApprovalsServiceLatch(); -}); -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -describe('ObjectGrid — the state-machine confirm names the flows the move starts (objectstack#35928)', () => { - it('list: asks for the row and the move, and names each flow under the sentence, approval marked', async () => { - const calls = installFetch({ status: 200, body: { success: true, data: { flows: [CLOSURE, NOTIFY] } } }); - const ds = makeDataSource(); - const { container } = renderGrid(ds); - await screen.findByText('beta'); - const dialog = await moveFirstRowToWon(container); - - const list = await within(dialog).findByTestId('stage-change-starts'); - expect(dialog).toHaveTextContent(SENTENCE); - expect(list).toHaveTextContent('Saving this change starts these flows:'); - const closure = list.querySelector('[data-stage-change-start="deal_won"]')!; - const notify = list.querySelector('[data-stage-change-start="deal_notify"]')!; - expect(closure).toHaveTextContent('Deal Won Sign-off'); - expect(closure.querySelector('[data-stage-change-start-approval]')).toHaveTextContent('starts an approval'); - expect(notify).toHaveTextContent('Notify Owner'); - expect(notify.querySelector('[data-stage-change-start-approval]')).toBeNull(); - expect(startsCalls(calls).map((c) => c.body)).toEqual([ - { object: OBJECT, recordId: 'd1', changes: { stage: 'won' } }, - ]); - }); - - it('empty: no flows answered draws no list, and the sentence stands alone', async () => { - const calls = installFetch({ status: 200, body: { success: true, data: { flows: [] } } }); - const { container } = renderGrid(makeDataSource()); - await screen.findByText('beta'); - const dialog = await moveFirstRowToWon(container); - await waitFor(() => expect(startsCalls(calls)).toHaveLength(1)); - // Let the answer land before reading that nothing was drawn for it. - await new Promise((r) => setTimeout(r, 0)); - expect(within(dialog).queryByTestId('stage-change-starts')).toBeNull(); - expect(dialog).toHaveTextContent(SENTENCE); - }); - - it('failure: a refused read draws no list, the sentence stands, and Change still saves the move', async () => { - const calls = installFetch({ status: 500, body: { success: false, error: { code: 'INTERNAL_ERROR', message: 'boom' } } }); - const ds = makeDataSource(); - const { container } = renderGrid(ds); - await screen.findByText('beta'); - const dialog = await moveFirstRowToWon(container); - await waitFor(() => expect(startsCalls(calls)).toHaveLength(1)); - await new Promise((r) => setTimeout(r, 0)); - expect(within(dialog).queryByTestId('stage-change-starts')).toBeNull(); - expect(dialog).toHaveTextContent(SENTENCE); - fireEvent.click(within(dialog).getByRole('button', { name: 'Change' })); - await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); - expect(ds.update.mock.calls[0][2]).toEqual({ stage: 'won' }); - }); -}); From 3019d630a2762773232c4b81a161443d730ec366 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 06:29:25 +0000 Subject: [PATCH 06/11] chore(spec): regenerate the reference index on the merged tree (#35928) Claude-Session: https://claude.ai/code/session_01FEkQ5keqTTiV8ptWFNc6ZF Co-authored-by: Claude --- content/docs/references/index.mdx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index b9d802633e2..86e4a59a333 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1706 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1707 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -32,9 +32,9 @@ counts are sums of the rows they head. Regenerate with | [Security Protocol](/docs/references/security) | 6 | 37 | Permission sets, row-level security, sharing rules, tenancy posture. | | [Shared Protocol](/docs/references/shared) | 10 | 31 | Primitives used across every protocol — identifiers, HTTP, expressions, error maps, enums. | | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | -| [System Protocol](/docs/references/system) | 40 | 297 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | +| [System Protocol](/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 16 | 180 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **219** | **1706** | 14 protocol modules | +| **Total** | **219** | **1707** | 14 protocol modules | --- @@ -335,7 +335,7 @@ Studio designer metadata — the authoring surfaces for the protocols above. ## System Protocol -**Source:** `packages/spec/src/system/` · **Import:** `@objectstack/spec/system` · **40 pages, 297 schemas** +**Source:** `packages/spec/src/system/` · **Import:** `@objectstack/spec/system` · **40 pages, 298 schemas** The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. @@ -375,7 +375,7 @@ The runtime environment — logging, jobs, cache, metrics, notifications, i18n a | [`settings-client.zod.ts`](/docs/references/system/settings-client) | `SettingsChangeEvent` | | [`settings-manifest.zod.ts`](/docs/references/system/settings-manifest) | `ResolvedSettingValue`, `SettingsActionResult`, `SettingsManifest`, `SettingsNamespacePayload`, `Specifier`, `SpecifierHandler`, `SpecifierOption`, `SpecifierScope`, `SpecifierType`, `SpecifierValueDomain` | | [`sms-config.zod.ts`](/docs/references/system/sms-config) | `StackSmsConfig` | -| [`stack-server.zod.ts`](/docs/references/system/stack-server) | `ServerRateLimitConfig`, `StackServerConfig`, `StackServerSecurity` | +| [`stack-server.zod.ts`](/docs/references/system/stack-server) | `ServerRateLimitConfig`, `StackServerConfig`, `StackServerSecurity`, `TrustedProxyNetworks` | | [`supplier-security.zod.ts`](/docs/references/system/supplier-security) | `SupplierAssessmentStatus`, `SupplierRiskLevel`, `SupplierSecurityAssessment`, `SupplierSecurityPolicy`, `SupplierSecurityRequirement` | | [`tenant.zod.ts`](/docs/references/system/tenant) | `DatabaseLevelIsolationStrategy`, `DatabaseProvider`, `QuotaEnforcementResult`, `RowLevelIsolationStrategy`, `SchemaLevelIsolationStrategy`, `Tenant`, `TenantConnectionConfig`, `TenantIsolationConfig`, `TenantIsolationLevel`, `TenantQuota`, `TenantSecurityPolicy`, `TenantUsage` | | [`tracing.zod.ts`](/docs/references/system/tracing) | `OpenTelemetryCompatibility`, `OtelExporterType`, `SamplingDecision`, `SamplingStrategyType`, `Span`, `SpanAttributeValue`, `SpanAttributes`, `SpanEvent`, `SpanKind`, `SpanLink`, `SpanStatus`, `TraceContext`, `TraceContextPropagation`, `TraceFlags`, `TracePropagationFormat`, `TraceSamplingConfig`, `TraceState`, `TracingConfig` | From 6bd111ff7a061a05ea2de739bbc23274bf949b69 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 07:25:17 +0000 Subject: [PATCH 07/11] chore(spec): regenerate the generated surfaces on the merged tree Claude-Session: https://claude.ai/code/session_01QsR2jVTYADzVWfarACx5j3 Co-authored-by: Claude --- content/docs/references/index.mdx | 10 +++++----- packages/spec/api-surface/contracts.json | 1 + packages/spec/export-origins/contracts.json | 1 + 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 86e4a59a333..20e02b73e95 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1707 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1711 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -23,7 +23,7 @@ counts are sums of the rows they head. Regenerate with | [AI Protocol](/docs/references/ai) | 14 | 84 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | | [API Protocol](/docs/references/api) | 37 | 524 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | -| [Data Protocol](/docs/references/data) | 35 | 191 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | +| [Data Protocol](/docs/references/data) | 35 | 195 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | | [Identity Protocol](/docs/references/identity) | 5 | 27 | Users and accounts, organizations, positions, SCIM provisioning. | | [Integration Protocol](/docs/references/integration) | 1 | 23 | The single connector protocol (ADR-0097) — catalog descriptors and provider-bound instances. | | [Kernel Protocol](/docs/references/kernel) | 30 | 153 | Plugin lifecycle and manifests, capabilities and security, metadata loading, service registry. | @@ -34,7 +34,7 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 16 | 180 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **219** | **1707** | 14 protocol modules | +| **Total** | **219** | **1711** | 14 protocol modules | --- @@ -140,7 +140,7 @@ Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execu ## Data Protocol -**Source:** `packages/spec/src/data/` · **Import:** `@objectstack/spec/data` · **35 pages, 191 schemas** +**Source:** `packages/spec/src/data/` · **Import:** `@objectstack/spec/data` · **35 pages, 195 schemas** Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. @@ -173,7 +173,7 @@ Objects, fields, queries, filters, datasources and drivers — the ObjectQL laye | [`hook-body.zod.ts`](/docs/references/data/hook-body) | `ExpressionBody`, `HookBody`, `HookBodyCapability`, `ScriptBody` | | [`hook-body-doors.zod.ts`](/docs/references/data/hook-body-doors) | `BodyActivityAppendInput`, `BodyDoorRecordRef`, `BodyMailSendInput` | | [`mapping.zod.ts`](/docs/references/data/mapping) | `ImportFieldMapping`, `Mapping`, `TransformType` | -| [`object.zod.ts`](/docs/references/data/object) | `ApiMethod`, `ApiOperation`, `Index`, `Lifecycle`, `LifecycleClass`, `Object`, `ObjectAccessConfig`, `ObjectCapabilities`, `ObjectExtension`, `ObjectExternalBinding`, `ObjectFieldGroup`, `ObjectOwnershipEnum`, `ObjectRequiredPermissions`, `PerOperationRequiredPermissions`, `RelatedListEntry`, `RelatedListEntryObject`, `RowCrudActionOverride`, `TenancyConfig` | +| [`object.zod.ts`](/docs/references/data/object) | `ApiMethod`, `ApiOperation`, `Index`, `Lifecycle`, `LifecycleClass`, `Object`, `ObjectAccessConfig`, `ObjectCapabilities`, `ObjectExtension`, `ObjectExtensionFieldPlacement`, `ObjectExtensionGroupPlacement`, `ObjectExtensionListPlacement`, `ObjectExtensionPlacement`, `ObjectExternalBinding`, `ObjectFieldGroup`, `ObjectOwnershipEnum`, `ObjectRequiredPermissions`, `PerOperationRequiredPermissions`, `RelatedListEntry`, `RelatedListEntryObject`, `RowCrudActionOverride`, `TenancyConfig` | | [`picklist.zod.ts`](/docs/references/data/picklist) | `Picklist`, `PicklistExtension`, `PicklistServedField` | | [`query.zod.ts`](/docs/references/data/query) | `AggregationFunction`, `AggregationNode`, `DateGranularity`, `FieldNode`, `FullTextSearch`, `GroupByNode`, `Query`, `SortNode` | | [`recycle-bin.zod.ts`](/docs/references/data/recycle-bin) | `RecycleBinClearedReference`, `RecycleBinEntry`, `RecycleBinRetentionDays`, `RecycleBinRetentionDaysEnv`, `RecycleBinSnapshot`, `RecycleBinSnapshotRow` | diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index b5a95b593d5..d33bacc4712 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -25,6 +25,7 @@ "APPROVAL_ACTION_KIND_LABELS (const)", "APPROVAL_CANCEL_REASONS (const)", "APPROVAL_CANCEL_REASON_LABELS (const)", + "APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS (const)", "APPROVAL_STATUSES (const)", "APPROVAL_STATUS_LABELS (const)", "AUDIT_CHECKPOINT_SIGNER_SERVICE (const)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index 5161d5f6af9..b44cd720196 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -25,6 +25,7 @@ "APPROVAL_ACTION_KIND_LABELS": "src/contracts/approval-service.ts#APPROVAL_ACTION_KIND_LABELS (const)", "APPROVAL_CANCEL_REASONS": "src/contracts/approval-service.ts#APPROVAL_CANCEL_REASONS (const)", "APPROVAL_CANCEL_REASON_LABELS": "src/contracts/approval-service.ts#APPROVAL_CANCEL_REASON_LABELS (const)", + "APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS": "src/contracts/approval-service.ts#APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS (const)", "APPROVAL_STATUSES": "src/contracts/approval-service.ts#APPROVAL_STATUSES (const)", "APPROVAL_STATUS_LABELS": "src/contracts/approval-service.ts#APPROVAL_STATUS_LABELS (const)", "AUDIT_CHECKPOINT_SIGNER_SERVICE": "src/contracts/audit-checkpoint.ts#AUDIT_CHECKPOINT_SIGNER_SERVICE (const)", From 99bfd857eb823d672ab57e10b0c7d916d2064a27 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 09:05:50 +0000 Subject: [PATCH 08/11] chore(changeset): the record-update preview read declares the api shard keys it adds Claude-Session: https://claude.ai/code/session_01QsR2jVTYADzVWfarACx5j3 Co-authored-by: Claude --- .changeset/35928-record-update-starts-read.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/35928-record-update-starts-read.md b/.changeset/35928-record-update-starts-read.md index fe05ae61fd5..8b8aca4af77 100644 --- a/.changeset/35928-record-update-starts-read.md +++ b/.changeset/35928-record-update-starts-read.md @@ -1,5 +1,5 @@ --- -'@objectstack/spec': patch +'@objectstack/spec': minor '@objectstack/service-automation': patch '@objectstack/trigger-record-change': patch '@objectstack/runtime': patch @@ -9,7 +9,7 @@ feat(automation): `POST /api/v1/automation/_record-starts` answers which flows a proposed update of one record would start Clause-②: yes (widening) — one new public read: the route `POST /api/v1/automation/_record-starts` (`automation.listRecordUpdateStarts` in the API contract and in `@objectstack/client`); `@objectstack/spec/api` adds `RecordUpdateStartsRequestSchema`, `RecordUpdateStartSchema`, `RecordUpdateStartsResponseSchema` and their types; `@objectstack/spec/contracts` adds `RecordUpdateStartsInput` and the optional `IAutomationService.listRecordUpdateStarts`; `@objectstack/spec/automation` adds `recordChangeTriggerHookEvents` and `recordChangeTriggerFiresOnUpdate`; `_record-starts` joins the `/automation` domain's reserved position literals. Nothing existing is removed or re-typed. -Metadata-protocol: none +Metadata-protocol: added — the three new `@objectstack/spec/api` schemas enter the `api` authorable-surface shard (10 keys: `RecordUpdateStart:name/label/startsApproval`, `RecordUpdateStartsRequest:object/recordId/changes`, `RecordUpdateStartsResponse:success/data/error/meta`); no flow or other metadata key is added Skills-docs: none — no skill under `skills/**` teaches the console's stage confirms; `content/docs/automation/flows.mdx` gains the read in this change. The console's stage confirms now name the flows a move would start (objectstack#35928, ruling record 7073655354). They ask the server: From 3ba211dc4a52c9e5fb164dfe7e9b9b1cd5bb3a7a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 10:13:36 +0000 Subject: [PATCH 09/11] fix(automation): the record-update preview reads only declared fields of the object The door refuses a change key that is not a declared field of the object, and a read that answers no record, before the engine is asked; the request schema holds each change key to the field-name grammar. The ledger row is pinned to the schemas the suite parses with, and the preview's binding of the caller (user and tenant only) is stated in the contract and the docs. Claude-Session: https://claude.ai/code/session_01QsR2jVTYADzVWfarACx5j3 Co-authored-by: Claude --- content/docs/automation/flows.mdx | 10 +++- .../docs/references/api/automation-api.mdx | 2 +- .../runtime/src/domains/automation-address.ts | 2 +- .../automation-record-update-starts.test.ts | 60 ++++++++++++++++++- packages/runtime/src/domains/automation.ts | 52 ++++++++++++++-- packages/runtime/src/route-ledger.ts | 2 +- .../spec/src/api/automation-api.zod.test.ts | 13 ++++ packages/spec/src/api/automation-api.zod.ts | 18 +++++- .../spec/src/contracts/automation-service.ts | 5 ++ 9 files changed, 148 insertions(+), 16 deletions(-) diff --git a/content/docs/automation/flows.mdx b/content/docs/automation/flows.mdx index f03767f184a..87a29ecdd3b 100644 --- a/content/docs/automation/flows.mdx +++ b/content/docs/automation/flows.mdx @@ -2606,8 +2606,9 @@ stage confirm name those flows under their sentence (objectstack#35928). record is read as the caller, through the `/data` door's own `get`, so a record they cannot read answers `404 RECORD_NOT_FOUND` exactly as one that does not exist. An anonymous call is refused `401`, a malformed body `400 - VALIDATION_FAILED`, any query parameter `400 VALIDATION_ERROR`, and an engine - without the read `501`. + VALIDATION_FAILED`, a `changes` key that is not a declared field of the + object `400 VALIDATION_FAILED`, any query parameter `400 VALIDATION_ERROR`, + and an engine without the read `501`. - **Which flows:** enabled `record_change` flows of that object, armed on their trigger, whose `triggerType` binds an update (`record-…-update` or `record-…-write`), and whose start `condition` holds for the record with @@ -2622,7 +2623,10 @@ stage confirm name those flows under their sentence (objectstack#35928). The answer is a preview, not a promise: the write itself is judged when it happens, and a condition that reads a field the caller cannot see is judged -here on what the caller sees. +here on what the caller sees. Of the caller, the preview binds the user id and +the tenant only. A live save also binds the writer's positions, the request's +params and its expand, so a condition that reads those is judged here without +them and the preview can list fewer flows than the save starts. ## Expressions in flows diff --git a/content/docs/references/api/automation-api.mdx b/content/docs/references/api/automation-api.mdx index f6b2f519cd4..9919b9d777a 100644 --- a/content/docs/references/api/automation-api.mdx +++ b/content/docs/references/api/automation-api.mdx @@ -1046,7 +1046,7 @@ const result = AutomationApiErrorCode.parse(data); | :--- | :--- | :--- | :--- | | **object** | `string` | ✅ | Machine name of the record's object. | | **recordId** | `string` | ✅ | Id of the record the update would write. | -| **changes** | `Record` | ✅ | The proposed update: each field it sets and its new value. The record's other fields are read as stored. | +| **changes** | `Record` | ✅ | The proposed update: each field it sets and its new value, keyed by the field's machine name. Every key must be a declared field of `object`; the door refuses any other key `400 VALIDATION_FAILED` before the engine is asked. The record's other fields are read as stored. | --- diff --git a/packages/runtime/src/domains/automation-address.ts b/packages/runtime/src/domains/automation-address.ts index fb4f44264fb..c453a4c1375 100644 --- a/packages/runtime/src/domains/automation-address.ts +++ b/packages/runtime/src/domains/automation-address.ts @@ -16,7 +16,7 @@ * {@link readAutomationAddress} reads the namespace position in the router's * documented order (`readNamespacePositionSegment`, `@objectstack/spec/kernel`): * the grammar's literals (`trigger`, `hooks`, `connectors`, `actions`, - * `_status`; `credential-refs` and `oauth` under `connectors`) first, then + * `_status`, `_record-starts`; `credential-refs` and `oauth` under `connectors`) first, then * `_env`, then an installed namespace (the registry's `getNamespaceOwners`, * G2's mapping, never a second one), else the bare grammar. An addressed path * comes back as the bare path after its qualifier, so every gate of the domain, diff --git a/packages/runtime/src/domains/automation-record-update-starts.test.ts b/packages/runtime/src/domains/automation-record-update-starts.test.ts index 34dfff5f436..4a5ae8806a6 100644 --- a/packages/runtime/src/domains/automation-record-update-starts.test.ts +++ b/packages/runtime/src/domains/automation-record-update-starts.test.ts @@ -17,6 +17,7 @@ import { describe, it, expect, vi } from 'vitest'; import { recordNotFoundError } from '@objectstack/core'; import { RecordUpdateStartsResponseSchema } from '@objectstack/spec/api'; +import { ROUTE_LEDGER } from '../route-ledger.js'; import type { RecordUpdateStartsInput } from '@objectstack/spec/contracts'; // Paid at collection, not inside a case's clock (check:test-source-alias). @@ -27,18 +28,21 @@ import { HttpDispatcher } from '../http-dispatcher.js'; const STORED = { id: 'p1', status: 'active', name: 'Apollo' }; const CLOSURE = { name: 'project_closure', label: 'Project Closure', startsApproval: true }; -function makeDispatcher(opts: { withPreview?: boolean; readable?: boolean } = {}) { +function makeDispatcher(opts: { withPreview?: boolean; readable?: boolean; answersNoRecord?: boolean } = {}) { const listRecordUpdateStarts = vi.fn((input: RecordUpdateStartsInput) => input.record.status === 'completed' ? [CLOSURE] : []); // The caller-scoped read the `/data` door makes. An id the caller cannot // read is refused as an id naming no row (the protocol's own error). const getData = vi.fn(async ({ object, id }: any) => { if (opts.readable === false || id !== STORED.id) throw recordNotFoundError(object, id); + if (opts.answersNoRecord) return { object, id }; return { object, id, record: { ...STORED } }; }); const automation: Record = { handlerReady: true, execute: vi.fn(), getFlow: vi.fn() }; if (opts.withPreview !== false) automation.listRecordUpdateStarts = listRecordUpdateStarts; - const services: Record = { automation, protocol: { getData } }; + // The object the record belongs to, as the registry declares it. + const objectql = { registry: { getObject: (name: string) => (name === 'project' ? { name, fields: { name: {}, status: {}, budget: {} } } : undefined) } }; + const services: Record = { automation, protocol: { getData }, objectql }; const resolve = (name: string) => services[name]; const kernel: any = { getService: resolve, getServiceAsync: async (name: string) => resolve(name), context: { getService: resolve } }; return { dispatcher: new HttpDispatcher(kernel), listRecordUpdateStarts, getData }; @@ -143,4 +147,56 @@ describe('POST /automation/_record-starts (#35928)', () => { expect(listRecordUpdateStarts).not.toHaveBeenCalled(); }); + + it('refuses a change key that is not a field 400 VALIDATION_FAILED on that key, and never asks the engine', async () => { + const { dispatcher, listRecordUpdateStarts } = makeDispatcher(); + + const undeclared = await dispatcher.handleAutomation('/_record-starts', 'POST', { ...BODY, changes: { status: 'completed', stage_typo: 'x' } }, MEMBER()); + expect(undeclared.response?.status).toBe(400); + expect(undeclared.response?.body?.error?.code).toBe('VALIDATION_FAILED'); + expect(JSON.stringify(undeclared.response?.body)).toContain('changes.stage_typo'); + + const offGrammar = await dispatcher.handleAutomation('/_record-starts', 'POST', { ...BODY, changes: { '__proto__.x': 1 } }, MEMBER()); + expect(offGrammar.response?.status).toBe(400); + expect(offGrammar.response?.body?.error?.code).toBe('VALIDATION_FAILED'); + + const inherited = await dispatcher.handleAutomation('/_record-starts', 'POST', { ...BODY, changes: { constructor: 1 } }, MEMBER()); + expect(inherited.response?.status).toBe(400); + expect(inherited.response?.body?.error?.code).toBe('VALIDATION_FAILED'); + + expect(listRecordUpdateStarts).not.toHaveBeenCalled(); + expect(({} as Record).x).toBeUndefined(); + }); + + it('refuses a change on an object the registry does not declare, and never asks the engine', async () => { + const { dispatcher, listRecordUpdateStarts, getData } = makeDispatcher(); + getData.mockImplementationOnce(async ({ object, id }: any) => ({ object, id, record: { id } })); + + const result = await dispatcher.handleAutomation('/_record-starts', 'POST', { ...BODY, object: 'unregistered' }, MEMBER()); + + expect(result.response?.status).toBe(400); + expect(result.response?.body?.error?.code).toBe('VALIDATION_FAILED'); + expect(listRecordUpdateStarts).not.toHaveBeenCalled(); + }); + + it('refuses a read that answers no record 404 RECORD_NOT_FOUND, never previewing an empty row', async () => { + const { dispatcher, listRecordUpdateStarts } = makeDispatcher({ answersNoRecord: true }); + + const result = await dispatcher.handleAutomation('/_record-starts', 'POST', BODY, MEMBER()); + + expect(result.response?.status).toBe(404); + expect(result.response?.body?.error?.code).toBe('RECORD_NOT_FOUND'); + expect(listRecordUpdateStarts).not.toHaveBeenCalled(); + }); +}); + +describe('[#35928] the contract: the ledger row names the schemas this suite parses with', () => { + it('the record-starts row is SDK surface and names RecordUpdateStartsRequestSchema / RecordUpdateStartsResponseSchema', () => { + const row = ROUTE_LEDGER.find((e) => e.route === 'POST /automation/_record-starts'); + expect(row, 'the record-starts row must exist in ROUTE_LEDGER').toBeDefined(); + expect(row!.disposition).toBe('sdk'); + expect(row!.client).toBe('automation.listRecordUpdateStarts'); + expect(row!.requestSchema).toBe('RecordUpdateStartsRequestSchema'); + expect(row!.responseSchema).toBe('RecordUpdateStartsResponseSchema'); + }); }); diff --git a/packages/runtime/src/domains/automation.ts b/packages/runtime/src/domains/automation.ts index 1b1b7a4d4b9..6ab0661a7f5 100644 --- a/packages/runtime/src/domains/automation.ts +++ b/packages/runtime/src/domains/automation.ts @@ -59,6 +59,7 @@ import { import { ExecutionStatus, collectFlowGraphs, type FlowNodeParsed } from '@objectstack/spec/automation'; import { nearestName } from '@objectstack/formula'; import { ListRunsRequestSchema, RecordUpdateStartsRequestSchema, standardErrorCodeForHttpStatus } from '@objectstack/spec/api'; +import { recordNotFoundError } from '@objectstack/metadata-protocol'; import type { ResumeFailureDetails } from '@objectstack/spec/api'; import { parseEnumParam, parseIntegerParam, parseStringParam } from '../query-param.js'; import { capabilityUnavailable } from './unavailable.js'; @@ -3736,11 +3737,39 @@ const RECORD_UPDATE_STARTS_QUERY_PARAMS: readonly string[] = []; * THE CALLER through the `/data` door's own read (`callData` `get`): an object * the caller may not address, or a record they cannot read, answers that * read's refusal (`404 RECORD_NOT_FOUND` for an unreadable or absent record), - * so this door tells a caller nothing the record read would not. Only then the - * engine, handed the record as read (`previous`) and with the proposed fields - * applied (`record`), and the caller as the writer. An engine without the - * optional member answers 501, never a guess. + * so this door tells a caller nothing the record read would not. A read that + * answers no record is refused the same `404`, never previewed over an empty + * row. Then every `changes` key must be a declared field of `object` (its own + * key in the registry's `fields`); any other key is refused + * `400 VALIDATION_FAILED`, located on the key, and the engine is not asked. + * Only then the engine, handed the record as read (`previous`) and with the + * proposed fields applied (`record`), and the caller as the writer. An engine + * without the optional member answers 501, never a guess. */ +/** + * [#35928] The `changes` keys of a record-update preview that are not declared + * fields of `object`: an own key of the registry object's `fields` map is + * declared, anything else is not. With no registry, or no object under the + * name, nothing is declared and every key is answered back, so the door + * refuses rather than previews. + */ +async function undeclaredChangeKeys( + deps: DomainHandlerDeps, + context: HttpProtocolContext, + object: string, + changes: Record, +): Promise { + let fields: unknown; + try { + const ql: any = typeof deps.getObjectQL === 'function' ? await deps.getObjectQL(context) : undefined; + fields = ql?.registry?.getObject?.(object)?.fields; + } catch { + fields = undefined; + } + const declared = fields && typeof fields === 'object' && !Array.isArray(fields) ? fields : undefined; + return Object.keys(changes).filter((key) => !(declared && Object.prototype.hasOwnProperty.call(declared, key))); +} + async function respondToRecordUpdateStarts( deps: DomainHandlerDeps, automationService: unknown, @@ -3768,10 +3797,23 @@ async function respondToRecordUpdateStarts( context?.dataDriver, context?.environmentId, context?.executionContext, ); const row = (read as { record?: unknown } | null | undefined)?.record; - stored = row && typeof row === 'object' ? (row as Record) : {}; + if (!row || typeof row !== 'object' || Array.isArray(row)) { + return { handled: true, response: deps.errorFromThrown(recordNotFoundError(object, recordId), 404) }; + } + stored = row as Record; } catch (err) { return { handled: true, response: deps.errorFromThrown(err, 500) }; } + const undeclared = await undeclaredChangeKeys(deps, context, object, changes); + if (undeclared.length > 0) { + const fields = undeclared.map((key) => ({ + field: `changes.${key}`, + code: 'unknown_field', + message: `not a field of \`${object}\``, + })); + const message = `Invalid record-update preview request: ${undeclared.map((key) => `\`${key}\``).join(', ')} ${undeclared.length > 1 ? 'are not fields' : 'is not a field'} of \`${object}\``; + return { handled: true, response: deps.errorFromThrown(validationFailure(message, fields), VALIDATION_FAILED_STATUS) }; + } const ec: any = (context as any)?.executionContext; const flows = svc.listRecordUpdateStarts({ object, diff --git a/packages/runtime/src/route-ledger.ts b/packages/runtime/src/route-ledger.ts index ffe7ce3ef41..995026f9ee5 100644 --- a/packages/runtime/src/route-ledger.ts +++ b/packages/runtime/src/route-ledger.ts @@ -632,7 +632,7 @@ export const ROUTE_LEDGER: readonly RouteLedgerEntry[] = [ { route: 'POST /automation/_record-starts', domain: '/automation', disposition: 'sdk', client: 'automation.listRecordUpdateStarts', requestSchema: 'RecordUpdateStartsRequestSchema', responseSchema: 'RecordUpdateStartsResponseSchema', - note: "Ruling record 7073655354: a caller who can READ the record is answered the flows the proposed update would start, each as `{ name, label, startsApproval }` — no description, condition, node or link; hooks are never listed (ADR-0077 §2); no new capability. Body `RecordUpdateStartsRequestSchema` (`{ object, recordId, changes }`, closed; 400 `VALIDATION_FAILED` on the member). No query parameter is read, so any is refused 400 `VALIDATION_ERROR`. The record is read AS THE CALLER through the `/data` door's own `get` (`callData`), so an object the caller may not address or a record they cannot read answers that read's refusal (404 `RECORD_NOT_FOUND`, the same as an absent id) and the engine is never asked. The engine (`IAutomationService.listRecordUpdateStarts`) lists enabled flows armed on a record-change trigger of the object whose token binds an update (the spec's `recordChangeTriggerFiresOnUpdate`) and whose start condition holds — the ONE start-condition gate a run passes — for the stored row with `changes` applied against the stored row; a condition it cannot evaluate is not listed; nothing runs or is written. An engine without the optional member answers 501. The domain-wide anonymous floor answers 401 first. Pinned in `domains/automation-record-update-starts.test.ts`" }, + note: "Ruling record 7073655354: a caller who can READ the record is answered the flows the proposed update would start, each as `{ name, label, startsApproval }` — no description, condition, node or link; hooks are never listed (ADR-0077 §2); no new capability. Body `RecordUpdateStartsRequestSchema` (`{ object, recordId, changes }`, closed; 400 `VALIDATION_FAILED` on the member). No query parameter is read, so any is refused 400 `VALIDATION_ERROR`. The record is read AS THE CALLER through the `/data` door's own `get` (`callData`), so an object the caller may not address or a record they cannot read answers that read's refusal (404 `RECORD_NOT_FOUND`, the same as an absent id) and the engine is never asked; a read that answers no record is refused the same 404. Every `changes` key must be a declared field of the object (the registry object's own `fields` key; the request schema also holds each key to the field-name grammar), else 400 `VALIDATION_FAILED` on `changes.KEY` and the engine is never asked. The engine (`IAutomationService.listRecordUpdateStarts`) lists enabled flows armed on a record-change trigger of the object whose token binds an update (the spec's `recordChangeTriggerFiresOnUpdate`) and whose start condition holds — the ONE start-condition gate a run passes — for the stored row with `changes` applied against the stored row; a condition it cannot evaluate is not listed; nothing runs or is written. An engine without the optional member answers 501. The domain-wide anonymous floor answers 401 first. Pinned in `domains/automation-record-update-starts.test.ts`" }, { route: 'POST /automation/:name/trigger', domain: '/automation', disposition: 'sdk', client: 'automation.execute' }, { route: 'POST /automation/:name/toggle', domain: '/automation', disposition: 'sdk', client: 'automation.toggle', note: "enablement, and since the 2026-08-23 ruling that enablement is an authoring write, `manage_metadata` gates it — the same `isFlowAuthoringWrite` door as `POST /automation` above, NOT a fourth copy of the policy. The definition-write gate deliberately left this one out as engine state and filed the question; the measurement is what settled it. No organization wall scopes the enabled bit: `toggleFlow` writes the ADR-0126 §7.2 activation ledger first — one deployment-wide `sys_metadata_activation` row per flow, keyed by `(metadata_type, name)`, carrying the flow's package id and no organization column — and only then updates the engine's in-process projection, which `getFlowRuntimeStates()` reads with no caller and no organization; the automation service is ONE instance per environment — so an unentitled tenant org owner switched a shipped flow off and an unrelated tenant in a different organization, plus the platform admin, read it off, in both directions. Disabling a shipped flow is equivalent to deleting it for as long as it stays off, and DELETE was already gated. ⚠️ BREAKING: 200 → 403 for callers without the capability. Fail-closed on an absent executionContext, an absent `systemPermissions` or an empty one, refusing 403 `PERMISSION_DENIED`, with only `isSystem` bypassing; the domain-wide anonymous floor still answers 401 first. The predicate excludes `POST /automation/trigger/:name` so a flow literally NAMED `toggle` keeps its execution door. Pinned in `domains/automation-write-capability-gate.test.ts` and `qa/dogfood/test/automation-toggle-tenant-scope.dogfood.test.ts`" }, diff --git a/packages/spec/src/api/automation-api.zod.test.ts b/packages/spec/src/api/automation-api.zod.test.ts index 1cdb58b37b1..e7cb5e9ea48 100644 --- a/packages/spec/src/api/automation-api.zod.test.ts +++ b/packages/spec/src/api/automation-api.zod.test.ts @@ -1039,6 +1039,19 @@ describe('RecordUpdateStarts schemas (#35928)', () => { expect(bare.success).toBe(false); }); + it('holds each change key to the field-name grammar', () => { + for (const key of ['a.b', 'Status', '1st', 'has space', '']) { + const parsed = AutomationApiModule.RecordUpdateStartsRequestSchema.safeParse({ + object: 'showcase_project', recordId: 'p_1', changes: { [key]: 1 }, + }); + expect(parsed.success, key).toBe(false); + } + const ok = AutomationApiModule.RecordUpdateStartsRequestSchema.safeParse({ + object: 'showcase_project', recordId: 'p_1', changes: { status: 'completed', _internal_note: 'x' }, + }); + expect(ok.success).toBe(true); + }); + it('answers flows by name, label and approval mark only', () => { const answer = { success: true, diff --git a/packages/spec/src/api/automation-api.zod.ts b/packages/spec/src/api/automation-api.zod.ts index cb78c5341f5..0da9a3f9836 100644 --- a/packages/spec/src/api/automation-api.zod.ts +++ b/packages/spec/src/api/automation-api.zod.ts @@ -901,7 +901,14 @@ export type GetRunResponseParsed = z.infer; * * Answered to a caller who can read the record: the record is read AS THE * CALLER, and one the caller cannot read answers `404 RECORD_NOT_FOUND`, the - * same answer as a record id that does not exist. + * same answer as a record id that does not exist. Every `changes` key must be + * a declared field of `object`; any other key is refused + * `400 VALIDATION_FAILED` and the engine is not asked. + * + * What the preview binds of the caller: their user id and tenant only. A live + * run also binds the writer's positions, request params and expand, so a + * start condition that reads those is judged without them here and the + * preview can under-list (it never runs a flow). * * @example POST /api/v1/automation/_record-starts * { object: 'showcase_project', recordId: 'p_1', changes: { status: 'completed' } } @@ -909,8 +916,13 @@ export type GetRunResponseParsed = z.infer; export const RecordUpdateStartsRequestSchema = lazySchema(() => z.object({ object: z.string().min(1).describe('Machine name of the record\'s object.'), recordId: z.string().min(1).describe('Id of the record the update would write.'), - changes: z.record(z.string(), z.unknown()).describe( - 'The proposed update: each field it sets and its new value. The record\'s other fields are read as stored.', + changes: z.record( + z.string().regex(/^[a-z_][a-z0-9_]*$/, { + message: 'A change key is a field machine name (snake_case, the field-name grammar of `data/field.zod.ts`).', + }), + z.unknown(), + ).describe( + 'The proposed update: each field it sets and its new value, keyed by the field\'s machine name. Every key must be a declared field of `object`; the door refuses any other key `400 VALIDATION_FAILED` before the engine is asked. The record\'s other fields are read as stored.', ), }).strict()); export type RecordUpdateStartsRequest = z.input; diff --git a/packages/spec/src/contracts/automation-service.ts b/packages/spec/src/contracts/automation-service.ts index 671c0d9f77c..96362d28bc5 100644 --- a/packages/spec/src/contracts/automation-service.ts +++ b/packages/spec/src/contracts/automation-service.ts @@ -953,6 +953,11 @@ export interface ResumeSignal { * record of `object` as it stands (`previous`) and as the proposed update * would leave it (`record`, the stored fields with the update's fields * applied). The caller reads the record; the engine reads nothing. + * + * Of the writer it carries the user id and tenant only. A live save also + * binds the writer's positions, request params and expand into the run, so a + * start condition reading those is judged here without them and the preview + * can under-list. */ export interface RecordUpdateStartsInput { /** Machine name of the record's object. */ From d2279e6cc647e310bf98c7aa2b98498acea8db96 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 11:17:21 +0000 Subject: [PATCH 10/11] test(runtime): the unregistered-object pin's read answers the stored row Claude-Session: https://claude.ai/code/session_01QsR2jVTYADzVWfarACx5j3 Co-authored-by: Claude --- .../runtime/src/domains/automation-record-update-starts.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/runtime/src/domains/automation-record-update-starts.test.ts b/packages/runtime/src/domains/automation-record-update-starts.test.ts index 4a5ae8806a6..69f8396a420 100644 --- a/packages/runtime/src/domains/automation-record-update-starts.test.ts +++ b/packages/runtime/src/domains/automation-record-update-starts.test.ts @@ -170,7 +170,7 @@ describe('POST /automation/_record-starts (#35928)', () => { it('refuses a change on an object the registry does not declare, and never asks the engine', async () => { const { dispatcher, listRecordUpdateStarts, getData } = makeDispatcher(); - getData.mockImplementationOnce(async ({ object, id }: any) => ({ object, id, record: { id } })); + getData.mockImplementationOnce(async ({ object, id }: any) => ({ object, id, record: { ...STORED } })); const result = await dispatcher.handleAutomation('/_record-starts', 'POST', { ...BODY, object: 'unregistered' }, MEMBER()); From 41487226fa0c4be52fa3085a09e0cd806434b563 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 12:09:19 +0000 Subject: [PATCH 11/11] fix(automation): the preview's refusals are named in full, and its caller limit reads both ways Claude-Session: https://claude.ai/code/session_01QsR2jVTYADzVWfarACx5j3 Co-authored-by: Claude --- .changeset/35928-record-update-starts-read.md | 2 +- content/docs/automation/flows.mdx | 4 +++- .../src/domains/automation-record-update-starts.test.ts | 2 ++ packages/spec/src/api/automation-api.zod.ts | 4 ++-- packages/spec/src/contracts/automation-service.ts | 4 ++-- 5 files changed, 10 insertions(+), 6 deletions(-) diff --git a/.changeset/35928-record-update-starts-read.md b/.changeset/35928-record-update-starts-read.md index 8b8aca4af77..e96759dd4fd 100644 --- a/.changeset/35928-record-update-starts-read.md +++ b/.changeset/35928-record-update-starts-read.md @@ -15,6 +15,6 @@ Skills-docs: none — no skill under `skills/**` teaches the console's stage con The console's stage confirms now name the flows a move would start (objectstack#35928, ruling record 7073655354). They ask the server: - **Request** `{ object, recordId, changes }`; **response** `{ success, data: { flows: [{ name, label, startsApproval }] } }`. -- **Who is answered:** a signed-in caller who can read the record. The record is read as the caller through the `/data` door's own `get`, so a record they cannot read answers `404 RECORD_NOT_FOUND` exactly as an absent one, and the engine is never asked. Anonymous `401`; a malformed body `400 VALIDATION_FAILED`; any query parameter `400 VALIDATION_ERROR`; an engine without the read `501`. +- **Who is answered:** a signed-in caller who can read the record. The record is read as the caller through the `/data` door's own `get`, so a record they cannot read answers `404 RECORD_NOT_FOUND` exactly as an absent one, and the engine is never asked. Anonymous `401`; a malformed body `400 VALIDATION_FAILED`; a `changes` key that is not a declared field of the object `400 VALIDATION_FAILED` on that key, the engine never asked; a read that answers no record `404 RECORD_NOT_FOUND`; any query parameter `400 VALIDATION_ERROR`; an engine without the read `501`. - **Which flows:** enabled `record_change` flows of the object, armed on their trigger, whose `triggerType` binds an update, and whose start condition holds for the record read with `changes` applied (`previous` is the record read). The condition goes through the engine's one start-condition gate, the one every run passes; the token grammar `@objectstack/trigger-record-change` binds hooks by moved into the spec (`recordChangeTriggerHookEvents`) so the preview reads the same rule, with no second copy. A condition that cannot be evaluated against the record is not listed. Hooks are never listed. - **Per flow:** `name`, the authored `label` (a client translates it by name) and `startsApproval`, true for a flow holding an `approval` node (ADR-0019). No description, condition or nodes. diff --git a/content/docs/automation/flows.mdx b/content/docs/automation/flows.mdx index 87a29ecdd3b..b5ece39bc0b 100644 --- a/content/docs/automation/flows.mdx +++ b/content/docs/automation/flows.mdx @@ -2626,7 +2626,9 @@ happens, and a condition that reads a field the caller cannot see is judged here on what the caller sees. Of the caller, the preview binds the user id and the tenant only. A live save also binds the writer's positions, the request's params and its expand, so a condition that reads those is judged here without -them and the preview can list fewer flows than the save starts. +them, and the preview can differ from the save in either direction: it can miss +a flow the save starts, or list one the save does not (a negated test of the +writer reads true here). ## Expressions in flows diff --git a/packages/runtime/src/domains/automation-record-update-starts.test.ts b/packages/runtime/src/domains/automation-record-update-starts.test.ts index 69f8396a420..e4d3c99319f 100644 --- a/packages/runtime/src/domains/automation-record-update-starts.test.ts +++ b/packages/runtime/src/domains/automation-record-update-starts.test.ts @@ -104,6 +104,7 @@ describe('POST /automation/_record-starts (#35928)', () => { const result = await dispatcher.handleAutomation('/_record-starts', 'POST', BODY, ANONYMOUS()); expect(result.response?.status).toBe(401); + expect(result.response?.body?.error?.code).toBe('UNAUTHENTICATED'); expect(getData).not.toHaveBeenCalled(); expect(listRecordUpdateStarts).not.toHaveBeenCalled(); }); @@ -138,6 +139,7 @@ describe('POST /automation/_record-starts (#35928)', () => { const result = await dispatcher.handleAutomation('/_record-starts', 'POST', BODY, MEMBER()); expect(result.response?.status).toBe(501); + expect(result.response?.body?.error?.code).toBe('NOT_IMPLEMENTED'); }); it('is not read as a flow name: a GET of the literal is not this door', async () => { diff --git a/packages/spec/src/api/automation-api.zod.ts b/packages/spec/src/api/automation-api.zod.ts index 0da9a3f9836..9ffdde43526 100644 --- a/packages/spec/src/api/automation-api.zod.ts +++ b/packages/spec/src/api/automation-api.zod.ts @@ -907,8 +907,8 @@ export type GetRunResponseParsed = z.infer; * * What the preview binds of the caller: their user id and tenant only. A live * run also binds the writer's positions, request params and expand, so a - * start condition that reads those is judged without them here and the - * preview can under-list (it never runs a flow). + * start condition that reads those is judged without them here, and the + * preview can differ from the save in either direction (it never runs a flow). * * @example POST /api/v1/automation/_record-starts * { object: 'showcase_project', recordId: 'p_1', changes: { status: 'completed' } } diff --git a/packages/spec/src/contracts/automation-service.ts b/packages/spec/src/contracts/automation-service.ts index 96362d28bc5..d8a732f5ad8 100644 --- a/packages/spec/src/contracts/automation-service.ts +++ b/packages/spec/src/contracts/automation-service.ts @@ -956,8 +956,8 @@ export interface ResumeSignal { * * Of the writer it carries the user id and tenant only. A live save also * binds the writer's positions, request params and expand into the run, so a - * start condition reading those is judged here without them and the preview - * can under-list. + * start condition reading those is judged here without them, and the preview + * can differ from the save in either direction. */ export interface RecordUpdateStartsInput { /** Machine name of the record's object. */