diff --git a/.changeset/34818-flow-checks-before-publish.md b/.changeset/34818-flow-checks-before-publish.md new file mode 100644 index 00000000000..144abb2417b --- /dev/null +++ b/.changeset/34818-flow-checks-before-publish.md @@ -0,0 +1,20 @@ +--- +'@objectstack/spec': minor +'@objectstack/lint': patch +'@objectstack/metadata-protocol': patch +'@objectstack/rest': patch +'@objectstack/runtime': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(flow designer): the publish checks show in the Problems tab and the publish drawer before the publish, worded for the builder + +Clause-②: yes (widening: optional userTextLocales on GetMetaItemRequestSchema) +Metadata-protocol: added + +Before, a flow's publish checks were seen only after the publish, as a toast that listed rule ids, machine names and English prose, and then disappeared. + +- **The draft read carries what the publish would still report.** A flow draft read (`state: 'draft'`) now adds the publish gate's advisory findings to `_diagnostics.warnings`, next to the refusals it already carried. Each warning has the finding's user sentence in the reader's language. The REST door and the runtime dispatcher pass the request's locales, through a new optional `userTextLocales` on `GetMetaItemRequestSchema`. With no locales the sentence is English. `valid` does not change, and the drafts of other types read as before. +- **The sentences name what the builder sees.** `flow-decision-unconditional-branch` has user text in all 11 platform locales. It names the flow, the branch step and the paths by their labels, and says what the shape does to a run and how to fix it. The `approval-approvers-*` sentences now name the flow and the approval step by their labels instead of the flow's machine name and the node id. A step or flow with no label falls back to its id or name. The findings' `message`, `where`, rules and severities do not change. +- **The console shows them before the publish.** The designer's Problems tab already lists a draft's warnings, so the checks now appear there after each save, and clicking one selects its step. The pending-changes drawer lists each flow draft's checks under the flow's label, above Publish. A publish from the drawer or the designer, made after the checks were listed, ends with the toast's title line only. A publish the author did not review, such as one an AI surface performs, keeps the full toast. diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index 3002e254152..7bb1d8372a9 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -698,6 +698,14 @@ refusal to a loud log for a migration window, so rows written before the gate existed stay re-savable; it converts refusals, and never promotes them into `advisories`. +A flow draft can be read before it is published. That read (`GET /api/v1/meta/flow/:name?state=draft`) +runs the publish's own judgement, so its `_diagnostics` say what the publish would answer. A refusal is +listed in `errors`. Each advisory is listed in `warnings`, at the flow-relative path of the step it is +about (`nodes.1`), as the finding's sentence for the builder in the language the request states +(`Accept-Language`, else the workspace default, else English). `valid` is not changed by an advisory. +The flow designer's Problems tab and the pending-changes drawer read these warnings, so an author sees +the publish checks before pressing Publish. A draft of any other type carries no advisories in its read. + So `os validate` is the fast inner-loop check (no artifact), `os build` is what you run when you need the deployable artifact, and `os lint` adds its own style rubric on top. **Any rule that can fail a build runs on all three**, so a green diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 3a46d4f7a23..dcadd71bd22 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -1504,6 +1504,7 @@ This schema accepts one of the following structures: | **member** | `string` | optional | Bundle member selector, for a metadata type whose identity is a pair (today only `email_template`, identified by `(name, locale)`): the member this request addresses, spelled as its discriminator value (`zh-CN`). Absent, the canonical member (`en-US` for `email_template`), which is what a bare-name read answers; naming the canonical value is the same request. It is not the response translation locale, which `?locale=` and `Accept-Language` choose. Refused with 400 `VALIDATION_ERROR` on a type that has no members, and for a blank value or one longer than a stored member can be (100 characters). A well-formed member with nothing stored or shipped answers as that door answers an absent item. | | **state** | `Enum<'active' \| 'draft'>` | optional | Draft-visibility switch — which lifecycle row to read (strict mode): `'draft'` opens the pending draft buffer (Studio's editor read) and fails when no draft exists; absent or `'active'` reads the live published row. Distinct from `previewDrafts`, which FALLS BACK to the active row when no draft exists. Declaration ≠ authorization: this member only selects which stored row is read — ADR-0106 masking is unaffected, and draft access is gated upstream, not by this schema. | | **previewDrafts** | `boolean` | optional | Draft-visibility switch (ADR-0033 draft-overlay preview, non-strict): when true and `state` is not `'draft'`, a pending draft row is preferred if one exists, else the read falls back to the active row — the render path degrades to the published value instead of erroring. A served draft is tagged `_draft: true` so UIs can badge it. Declaration ≠ authorization: this member only switches which row is read, and ADR-0106 masking is unaffected — draft preview is admin-gated upstream, not by this schema. | +| **userTextLocales** | `string[]` | optional | The locales the user-facing sentences of a served DRAFT's check findings are composed in, in ladder order: the locale the request names, then the workspace default — the save request's member of the same name, read the same way (each value against the platform locale table, whole and then one subtag shorter at a time; a value that names no table language is passed over; `en` is the last rung). Read only by the `state: 'draft'` read, which folds what publishing the draft would say into its `_diagnostics`: an advisory finding that carries a user sentence becomes a `_diagnostics.warnings[]` entry in that sentence. Stated by the door that holds the request (the REST door and the dispatcher state `[ExecutionContext.locale, ExecutionContext.workspaceLocale]`), never read from a query string. ABSENT ⇒ the sentences are composed in `en`. It selects a language only: which row is read, and what the verdict is, do not depend on it. | --- diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 55665132f78..592afe4a188 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -2059,9 +2059,15 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ severity: f.severity ?? 'warning', rule: f.rule, where: f.where, - path: f.where, + // [#34818] A finding placed on a node carries its document path, so a + // draft's `_diagnostics` entry resolves onto that node; the rest keep + // `where` as before. + path: f.path ?? f.where, message: f.message, hint: f.hint, + // The user sentence's names ride through the re-map, so the doors can + // render this finding in the request's language. + ...(f.userTextParams !== undefined ? { userTextParams: f.userTextParams } : {}), })), }, // A credential typed as a LITERAL into a flow position every flow reader is diff --git a/packages/lint/src/finding-user-text.test.ts b/packages/lint/src/finding-user-text.test.ts index 177a3ce4940..adf0c89f9e3 100644 --- a/packages/lint/src/finding-user-text.test.ts +++ b/packages/lint/src/finding-user-text.test.ts @@ -67,6 +67,8 @@ import { FLOW_UPDATE_READONLY_WHEN_FIELD, validateReadonlyFlowWrites } from './v import { READONLY_FLOW_WRITES_USER_TEXT } from './validate-readonly-flow-writes.user-text.js'; import { FLOW_CREDENTIAL_LITERAL, lintFlowCredentialLiterals } from './lint-flow-credential-literals.js'; import { FLOW_CREDENTIAL_LITERALS_USER_TEXT } from './lint-flow-credential-literals.user-text.js'; +import { FLOW_DECISION_UNCONDITIONAL_BRANCH, lintFlowPatterns } from './lint-flow-patterns.js'; +import { FLOW_PATTERNS_USER_TEXT } from './lint-flow-patterns.user-text.js'; describe('finding user text · the locale ladder (request locale, then workspace default, then en)', () => { /** A synthetic entry with two sentences: English and Simplified Chinese. */ @@ -479,12 +481,13 @@ interface AdvisoryCase { } /** Params that pick a sentence's arm rather than name something the sentence must show. */ -const ARM_PARAMS: ReadonlySet = new Set(['slate', 'locked', 'trigger', 'root', 'position']); +const ARM_PARAMS: ReadonlySet = new Set(['slate', 'locked', 'trigger', 'root', 'position', 'shape']); +/** A list param carries one name per line; each name must show. */ const shownNamesOf = (params: Record): string[] => Object.entries(params) .filter(([key, value]) => !ARM_PARAMS.has(key) && value !== '') - .map(([, value]) => value); + .flatMap(([, value]) => value.split('\n')); /** The catalog holds exactly `ids`, each in exactly the platform locales, and is the one the door renders from. */ function pinCatalog(name: string, catalog: UserTextCatalog, ids: readonly string[]): void { @@ -1012,3 +1015,94 @@ describe('flow credential literals user text · never the value', () => { expect(findingUserMessage(advisory, ['ja-JP'])).toContain('ヘッダー「Authorization」'); }); }); + +// ── lint-flow-patterns (#34818) ──────────────────────────────────────────── +// +// The flow designer's Problems tab shows the draft's check findings before +// publish, so the sentence names the flow and its steps by the labels the +// builder sees, never `node_2` or the rule id. + +/** A labelled decision flow; `edges` are the decision's out-edges. */ +const decisionStack = (edges: Array>) => ({ + flows: [{ + name: 'meeting_reminder', + label: 'Meeting reminder', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: {} }, + { id: 'node_2', type: 'decision', label: 'Check date', config: {} }, + { id: 'node_3', type: 'end', label: 'Remind owner', config: {} }, + { id: 'node_4', type: 'end', label: 'Skip', config: {} }, + ], + edges: [{ id: 'e0', source: 'start', target: 'node_2' }, ...edges], + }], +}); + +const FLOW_PATTERN_CASES: readonly AdvisoryCase[] = [ + { + label: 'a decision that gates on nothing', + rule: FLOW_DECISION_UNCONDITIONAL_BRANCH, + stack: decisionStack([ + { id: 'e1', source: 'node_2', target: 'node_3' }, + { id: 'e2', source: 'node_2', target: 'node_4' }, + ]), + params: { flow: 'Meeting reminder', node: 'Check date', shape: 'none', targets: 'Remind owner\nSkip' }, + }, + { + label: 'a decision with an ungated path beside a guarded one', + rule: FLOW_DECISION_UNCONDITIONAL_BRANCH, + stack: decisionStack([ + { id: 'e1', source: 'node_2', target: 'node_3', condition: 'record.amount > 10' }, + { id: 'e2', source: 'node_2', target: 'node_4' }, + ]), + params: { flow: 'Meeting reminder', node: 'Check date', shape: 'mixed', targets: 'Skip' }, + }, +]; + +pinCatalog('flow patterns', FLOW_PATTERNS_USER_TEXT, [FLOW_DECISION_UNCONDITIONAL_BRANCH]); +// The rule leaves `severity` unset for a warning, as the registry row reads it. +pinCases('flow patterns', (stack) => lintFlowPatterns(stack).map((f) => ({ ...f, severity: f.severity ?? 'warning' })), FLOW_PATTERN_CASES); + +describe('flow patterns user text · what the builder reads (#34818)', () => { + it('places the finding on the decision node by its document path, so the draft verdict resolves onto it', () => { + for (const c of FLOW_PATTERN_CASES) { + const [finding] = lintFlowPatterns(c.stack).filter((f) => f.rule === c.rule); + expect(finding!.path, c.label).toBe('flows[0].nodes[1]'); + const result = runRuntimeAuthoringRules({ type: 'flow', item: (c.stack.flows as unknown[])[0] }); + expect(result.advisories.find((f) => f.rule === c.rule)!.path, c.label).toBe('flows[0].nodes[1]'); + } + }); + + it('names no machine name and no rule id in any locale', () => { + for (const c of FLOW_PATTERN_CASES) { + const [finding] = lintFlowPatterns(c.stack).filter((f) => f.rule === c.rule); + for (const tag of PLATFORM_LOCALE_TAGS) { + const text = findingUserMessage(finding!, [tag])!; + expect(text, `${c.label} · ${tag}`).not.toMatch(/node_\d|meeting_reminder|flow-decision|config\./); + } + } + }); + + it('falls back to the machine names for a flow and nodes that declare no label', () => { + const stack = decisionStack([ + { id: 'e1', source: 'node_2', target: 'node_3' }, + { id: 'e2', source: 'node_2', target: 'node_4' }, + ]); + const flow = (stack.flows as Array>)[0]!; + delete flow.label; + for (const node of flow.nodes as Array>) delete node.label; + const [finding] = lintFlowPatterns(stack).filter((f) => f.rule === FLOW_DECISION_UNCONDITIONAL_BRANCH); + expect(finding!.userTextParams).toEqual({ flow: 'meeting_reminder', node: 'node_2', shape: 'none', targets: 'node_3\nnode_4' }); + }); + + it('names an approval node and its flow by their labels too', () => { + const stack = approvalStack([{ type: 'position', value: 'finance_manager' }]); + const flow = (stack.flows as Array>)[0]!; + flow.label = 'Expense approval'; + (flow.nodes as Array>)[1]!.label = 'Manager review'; + const finding = validateApprovalApprovers(stack).find((f) => f.rule === APPROVAL_APPROVERS_MAY_RESOLVE_EMPTY)!; + expect(finding.userTextParams).toEqual({ flow: 'Expense approval', node: 'Manager review', slate: 'group', locked: 'yes' }); + expect(findingUserMessage(finding, ['zh-CN'])).toContain('流程“Expense approval”的审批节点“Manager review”'); + // `where` keeps the machine names for `os validate` and logs. + expect(finding.where).toBe('flow "expense_approval" · node "manager_review"'); + }); +}); diff --git a/packages/lint/src/finding-user-text.ts b/packages/lint/src/finding-user-text.ts index 8f32f9227b5..31170ea309b 100644 --- a/packages/lint/src/finding-user-text.ts +++ b/packages/lint/src/finding-user-text.ts @@ -60,6 +60,7 @@ import { FLOW_TEMPLATE_PATHS_USER_TEXT } from './validate-flow-template-paths.us import { FLOW_NODE_WRITES_USER_TEXT } from './validate-flow-node-writes.user-text.js'; import { READONLY_FLOW_WRITES_USER_TEXT } from './validate-readonly-flow-writes.user-text.js'; import { FLOW_CREDENTIAL_LITERALS_USER_TEXT } from './lint-flow-credential-literals.user-text.js'; +import { FLOW_PATTERNS_USER_TEXT } from './lint-flow-patterns.user-text.js'; import { WIDGET_BINDINGS_USER_TEXT } from './validate-widget-bindings.user-text.js'; import { CHART_BINDINGS_USER_TEXT } from './validate-chart-bindings.user-text.js'; import { AUTONUMBER_FORMATS_USER_TEXT } from './lint-autonumber-formats.user-text.js'; @@ -180,6 +181,7 @@ export const FINDING_USER_TEXT_CATALOG: UserTextCatalog = mergeUserTextCatalogs( FLOW_NODE_WRITES_USER_TEXT, READONLY_FLOW_WRITES_USER_TEXT, FLOW_CREDENTIAL_LITERALS_USER_TEXT, + FLOW_PATTERNS_USER_TEXT, // The dashboard writes: widget and chart binding advisories. WIDGET_BINDINGS_USER_TEXT, CHART_BINDINGS_USER_TEXT, diff --git a/packages/lint/src/flow-walk.ts b/packages/lint/src/flow-walk.ts index 8544f912f9e..040b67d68a5 100644 --- a/packages/lint/src/flow-walk.ts +++ b/packages/lint/src/flow-walk.ts @@ -131,6 +131,16 @@ export function flowNodeLabel(node: AnyRec, index: number): string { return strName(node.label) ?? strName(node.id) ?? `#${index}`; } +/** + * A flow's name for a USER sentence (`userTextParams`): its `label`, then its + * machine `name`, then `(flow N)`. A builder reads a flow by the label Studio + * shows them; the machine name is the fallback for a flow that declares none, + * the way {@link flowNodeLabel} falls back to a node's `id`. + */ +export function flowDisplayLabel(flow: AnyRec, index: number): string { + return strName(flow.label) ?? strName(flow.name) ?? `(flow ${index})`; +} + const EMPTY_SLOTS: readonly string[] = []; /** The region slots a node type owns — empty for every non-container type. */ diff --git a/packages/lint/src/lint-flow-patterns.ts b/packages/lint/src/lint-flow-patterns.ts index e7ca060623b..a6f9efc50e0 100644 --- a/packages/lint/src/lint-flow-patterns.ts +++ b/packages/lint/src/lint-flow-patterns.ts @@ -177,7 +177,16 @@ import { reduceFilterVerdict } from '@objectstack/spec/data'; // pass names a row's inputs with (`storedExpressionReads`, objectql), so this // rule and the engine cannot disagree about which spellings read a field. import { analyzeRelationshipTraversals } from '@objectstack/formula'; -import { stripRegions, ownRegionKeys, REGION_SLOTS, MAX_REGION_DEPTH } from './flow-walk.js'; +import { + stripRegions, + ownRegionKeys, + REGION_SLOTS, + MAX_REGION_DEPTH, + walkFlowNodes, + flowNodeLabel, + flowDisplayLabel, +} from './flow-walk.js'; +import type { UserTextParams } from './finding-user-text.js'; import { objectsAsServed, recordsOf } from './object-graph.js'; export interface FlowLintFinding { @@ -197,10 +206,36 @@ export interface FlowLintFinding { * rejects the same stack (#3782). */ severity?: 'error' | 'warning'; + /** + * The finding's document path (`flows[0].nodes[2]`), when the rule placed it + * on a node. Absent, the runtime gate's row spells the path as `where`, as + * every finding here did before; present, a draft's `_diagnostics` entry + * resolves onto that node, so the flow designer's Problems row selects it. + */ + path?: string; + /** + * The names the finding's USER sentence interpolates, set only at push sites + * whose rule has an entry in `lint-flow-patterns.user-text.ts`; see + * `AuthoringFinding.userTextParams`. The builder-facing sentence names the + * flow and its nodes by their labels; `where`, `message` and `hint` keep the + * machine names for `os validate`, logs and AI authors. + */ + userTextParams?: UserTextParams; } type AnyRec = Record; +/** + * Where a flow's nodes sit, for the findings that name one in a user sentence + * and place it by path: the flow's display label, and each node's label and + * document path, keyed by the node RECORD (the graph walk and the document walk + * hand out the same objects). Built once per flow by {@link lintFlowPatterns}. + */ +interface FlowNodeSites { + flowLabel: string; + nodes: WeakMap; +} + /** Extract the raw predicate source from a `condition` (string or Expression envelope). */ function conditionSource(raw: unknown): string { if (typeof raw === 'string') return raw; @@ -1219,6 +1254,7 @@ function scanBranchRouting( nodes: AnyRec[], edges: AnyRec[], findings: FlowLintFinding[], + sites?: FlowNodeSites, ): void { const outEdgesBySource = new Map(); for (const e of edges) { @@ -1310,6 +1346,27 @@ function scanBranchRouting( if (!nid) continue; const outs = outEdgesBySource.get(nid) ?? []; if (outs.length === 0) continue; + // The user sentence's names and the node's path (#34818): the builder + // reads the decision and its successors by their labels. + const site = sites?.nodes.get(node); + const labelOfId = (id: unknown): string => { + const target = nodes.find((n) => n.id === id); + return target ? (sites?.nodes.get(target)?.label ?? flowNodeLabel(target, 0)) : String(id); + }; + const userSite = (shape: 'none' | 'mixed', targets: readonly AnyRec[]) => ({ + ...(site ? { path: site.path } : {}), + ...(sites + ? { + userTextParams: { + flow: sites.flowLabel, + node: site?.label ?? nid, + shape, + // One label per line: each locale's sentence quotes and joins them. + targets: targets.map((e) => labelOfId(e.target)).join('\n'), + }, + } + : {}), + }); const cfg = (node.config ?? {}) as AnyRec; const declaredLabels = new Set( @@ -1424,6 +1481,7 @@ function scanBranchRouting( `Gate the branches: a \`condition\` per out-edge plus \`isDefault: true\` on the fallback, or a ` + `\`config.conditions[]\` whose \`label\` matches an out-edge's.`, rule: FLOW_DECISION_UNCONDITIONAL_BRANCH, + ...userSite('none', outs), }); } // Either way no out-edge is gated, so the mixed-branch check below — an @@ -1447,6 +1505,7 @@ function scanBranchRouting( `Mark the fallback \`isDefault: true\` so it is taken only when no sibling condition matched ` + `(BPMN default flow), or give it its own \`condition\`.`, rule: FLOW_DECISION_UNCONDITIONAL_BRANCH, + ...userSite('mixed', ungated), }); } } @@ -2281,8 +2340,19 @@ export function lintFlowPatterns(stack: AnyRec): FlowLintFinding[] { const findings: FlowLintFinding[] = []; // Built once per stack, read by (f') below for every `multi` update. const storedInputs = storedInputsByObject(stack); + const flowList: readonly unknown[] = Array.isArray(stack.flows) ? stack.flows : []; for (const flow of recordsOf(stack.flows)) { const flowName = typeof flow.name === 'string' ? flow.name : '(unnamed flow)'; + // [#34818] Labels and document paths for the findings that carry a user + // sentence. A flow that is not an array member (a keyed map) has no + // `flows[N]` path, so its findings keep `where` as their path. + const flowIndex = flowList.indexOf(flow); + const sites: FlowNodeSites = { flowLabel: flowDisplayLabel(flow, Math.max(flowIndex, 0)), nodes: new WeakMap() }; + if (flowIndex >= 0) { + walkFlowNodes(flow, `flows[${flowIndex}]`).forEach(({ node, path }, i) => { + sites.nodes.set(node, { label: flowNodeLabel(node, i), path }); + }); + } // `Array.isArray` proves the LIST, never its MEMBERS. A YAML `nodes:` item // left empty deserialises to `null`, and `nodes.find(n => n.type === …)` // four lines down dereferenced it (#16751). Read through `recordsOf` — the @@ -2570,7 +2640,7 @@ export function lintFlowPatterns(stack: AnyRec): FlowLintFinding[] { // (e) #4414 — a decision that declares a branch it cannot route: an // unclaimable branch label, an unconditional sibling that runs anyway, // or a self-contradictory / duplicated `isDefault` marker. - scanBranchRouting(at, graphNodes, graphEdges, findings); + scanBranchRouting(at, graphNodes, graphEdges, findings, sites); // (f) #5482 — a `multi: true` write with nothing bounding it: the declared // whole-object delete/update. Scanned per graph like the rest, which is diff --git a/packages/lint/src/lint-flow-patterns.user-text.ts b/packages/lint/src/lint-flow-patterns.user-text.ts new file mode 100644 index 00000000000..c978ee1f291 --- /dev/null +++ b/packages/lint/src/lint-flow-patterns.user-text.ts @@ -0,0 +1,130 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The user-facing sentences of `lint-flow-patterns.ts`'s findings, in every + * platform locale (`PLATFORM_LOCALE_TAGS`, `@objectstack/spec/system`). The + * finding mechanism and the locale ladder are `finding-user-text.ts`'s; this + * file is the rule file's own half of it, kept beside the rules so their + * wording and their translations change together. + * + * Who reads these: the person building the flow in Studio, in their own + * language, in the flow designer's Problems tab and the publish drawer + * (#34818), once a door composes `RuntimeAuthoringIssueSchema.userMessage` from + * them. So each sentence names the flow and its steps by the labels the builder + * sees, says what the shape does to a run, and names the one change that fixes + * it. The developer-facing detail stays in the finding's `message`, `hint` and + * `os explain` entry. + * + * Each entry reads the `userTextParams` its finding carries, set at the push + * site in `lint-flow-patterns.ts`: + * + * | rule id | params | + * |---|---| + * | `flow-decision-unconditional-branch` | `flow`, `node` (labels), `shape` (`none`: no out-edge is gated · `mixed`: some are, these are not), `targets` (the successors' labels, one per line) | + * + * `finding-user-text.test.ts` renders every entry from the rule's real + * findings in every platform locale. + */ + +import type { UserTextCatalog, UserTextParams } from './finding-user-text.js'; +import { FLOW_DECISION_UNCONDITIONAL_BRANCH } from './lint-flow-patterns.js'; + +/** The successors' labels, quoted and joined the way one locale writes a list. */ +function targetList(p: UserTextParams, open: string, close: string, separator: string): string { + return (p.targets ?? '') + .split('\n') + .filter((label) => label !== '') + .map((label) => `${open}${label}${close}`) + .join(separator); +} + +export const FLOW_PATTERNS_USER_TEXT: UserTextCatalog = Object.freeze({ + [FLOW_DECISION_UNCONDITIONAL_BRANCH]: { + en: (p) => + p.shape === 'none' + ? `The branch step "${p.node}" in flow "${p.flow}" sets no condition on any of its paths ` + + `(${targetList(p, '"', '"', ', ')}), so every path runs every time and the step chooses nothing. ` + + `Give each path a condition, and mark one of them as the default path.` + : `The branch step "${p.node}" in flow "${p.flow}" has a path to ${targetList(p, '"', '"', ', ')} with ` + + `no condition, so that path runs every time, alongside whichever path matched. Give it a ` + + `condition, or mark it as the default path.`, + 'zh-Hans': (p) => + p.shape === 'none' + ? `流程“${p.flow}”中的条件分支“${p.node}”没有为任何一条连线(${targetList(p, '“', '”', '、')})设置条件,` + + `因此每次运行都会走所有连线,这个分支起不到选择作用。请为每条连线设置条件,并把其中一条设为默认分支。` + : `流程“${p.flow}”中的条件分支“${p.node}”通往${targetList(p, '“', '”', '、')}的连线没有设置条件,` + + `因此每次运行都会走这条连线,同时还会走条件成立的那一条。请为它设置条件,或把它设为默认分支。`, + 'zh-Hant': (p) => + p.shape === 'none' + ? `流程「${p.flow}」中的條件分支「${p.node}」沒有為任何一條連線(${targetList(p, '「', '」', '、')})設定條件,` + + `因此每次執行都會走所有連線,這個分支起不到選擇作用。請為每條連線設定條件,並把其中一條設為預設分支。` + : `流程「${p.flow}」中的條件分支「${p.node}」通往${targetList(p, '「', '」', '、')}的連線沒有設定條件,` + + `因此每次執行都會走這條連線,同時還會走條件成立的那一條。請為它設定條件,或把它設為預設分支。`, + es: (p) => + p.shape === 'none' + ? `El paso de bifurcación "${p.node}" del flujo "${p.flow}" no pone condición en ninguno de sus caminos ` + + `(${targetList(p, '"', '"', ', ')}), así que todos los caminos se recorren siempre y el paso no elige ` + + `nada. Ponga una condición a cada camino y marque uno de ellos como camino predeterminado.` + : `El paso de bifurcación "${p.node}" del flujo "${p.flow}" tiene un camino hacia ` + + `${targetList(p, '"', '"', ', ')} sin condición, así que ese camino se recorre siempre, junto con el ` + + `que haya coincidido. Póngale una condición o márquelo como camino predeterminado.`, + ar: (p) => + p.shape === 'none' + ? `خطوة التفرّع "${p.node}" في التدفق "${p.flow}" لا تضع شرطًا على أي من مساراتها ` + + `(${targetList(p, '"', '"', '، ')})، لذلك تُسلك كل المسارات في كل مرة ولا تختار الخطوة شيئًا. ` + + `ضع شرطًا لكل مسار، واجعل أحدها المسار الافتراضي.` + : `خطوة التفرّع "${p.node}" في التدفق "${p.flow}" لها مسار إلى ${targetList(p, '"', '"', '، ')} بلا ` + + `شرط، لذلك يُسلك هذا المسار في كل مرة إلى جانب المسار الذي تحقق شرطه. ضع له شرطًا، أو اجعله ` + + `المسار الافتراضي.`, + fr: (p) => + p.shape === 'none' + ? `L’étape d’embranchement « ${p.node} » du flux « ${p.flow} » ne pose de condition sur aucun de ses ` + + `chemins (${targetList(p, '« ', ' »', ', ')}) : tous les chemins sont suivis à chaque fois et l’étape ` + + `ne choisit rien. Donnez une condition à chaque chemin et marquez l’un d’eux comme chemin par défaut.` + : `L’étape d’embranchement « ${p.node} » du flux « ${p.flow} » a un chemin vers ` + + `${targetList(p, '« ', ' »', ', ')} sans condition : ce chemin est suivi à chaque fois, en plus de ` + + `celui dont la condition est vraie. Donnez-lui une condition, ou marquez-le comme chemin par défaut.`, + 'pt-BR': (p) => + p.shape === 'none' + ? `A etapa de ramificação "${p.node}" do fluxo "${p.flow}" não define condição em nenhum dos seus ` + + `caminhos (${targetList(p, '"', '"', ', ')}), então todos os caminhos são percorridos sempre e a ` + + `etapa não escolhe nada. Dê uma condição a cada caminho e marque um deles como caminho padrão.` + : `A etapa de ramificação "${p.node}" do fluxo "${p.flow}" tem um caminho para ` + + `${targetList(p, '"', '"', ', ')} sem condição, então esse caminho é percorrido sempre, junto com ` + + `aquele cuja condição foi atendida. Dê a ele uma condição ou marque-o como caminho padrão.`, + ru: (p) => + p.shape === 'none' + ? `Шаг ветвления «${p.node}» в потоке «${p.flow}» не задаёт условия ни для одного из своих путей ` + + `(${targetList(p, '«', '»', ', ')}), поэтому каждый раз выполняются все пути и шаг ничего не ` + + `выбирает. Задайте условие для каждого пути и отметьте один из них как путь по умолчанию.` + : `У шага ветвления «${p.node}» в потоке «${p.flow}» есть путь к ${targetList(p, '«', '»', ', ')} без ` + + `условия, поэтому этот путь выполняется каждый раз, вместе с тем, чьё условие выполнилось. Задайте ` + + `для него условие или отметьте его как путь по умолчанию.`, + de: (p) => + p.shape === 'none' + ? `Der Verzweigungsschritt „${p.node}“ im Flow „${p.flow}“ setzt auf keinem seiner Pfade ` + + `(${targetList(p, '„', '“', ', ')}) eine Bedingung, daher laufen bei jedem Durchlauf alle Pfade und ` + + `der Schritt wählt nichts aus. Geben Sie jedem Pfad eine Bedingung und markieren Sie einen davon als ` + + `Standardpfad.` + : `Der Verzweigungsschritt „${p.node}“ im Flow „${p.flow}“ hat einen Pfad zu ` + + `${targetList(p, '„', '“', ', ')} ohne Bedingung, daher läuft dieser Pfad jedes Mal, zusätzlich zu ` + + `dem Pfad, dessen Bedingung zutrifft. Geben Sie ihm eine Bedingung oder markieren Sie ihn als ` + + `Standardpfad.`, + ja: (p) => + p.shape === 'none' + ? `フロー「${p.flow}」の分岐ステップ「${p.node}」は、どの経路(${targetList(p, '「', '」', '、')})にも` + + `条件を設定していないため、毎回すべての経路が実行され、このステップは何も選択しません。` + + `各経路に条件を設定し、そのうち 1 つを既定の経路にしてください。` + : `フロー「${p.flow}」の分岐ステップ「${p.node}」には、条件のない${targetList(p, '「', '」', '、')}への` + + `経路があるため、その経路は条件が一致した経路と並んで毎回実行されます。条件を設定するか、既定の経路に` + + `してください。`, + ko: (p) => + p.shape === 'none' + ? `플로우 "${p.flow}"의 분기 단계 "${p.node}"는 어떤 경로(${targetList(p, '"', '"', ', ')})에도 조건을 ` + + `설정하지 않아 매번 모든 경로가 실행되고, 이 단계는 아무것도 선택하지 않습니다. 각 경로에 조건을 ` + + `설정하고 그중 하나를 기본 경로로 지정하세요.` + : `플로우 "${p.flow}"의 분기 단계 "${p.node}"에는 조건 없이 ${targetList(p, '"', '"', ', ')}(으)로 ` + + `가는 경로가 있어, 조건이 맞은 경로와 함께 매번 실행됩니다. 조건을 설정하거나 기본 경로로 ` + + `지정하세요.`, + }, +}); diff --git a/packages/lint/src/validate-approval-approvers.ts b/packages/lint/src/validate-approval-approvers.ts index 685b0a62615..625348a0e9f 100644 --- a/packages/lint/src/validate-approval-approvers.ts +++ b/packages/lint/src/validate-approval-approvers.ts @@ -52,7 +52,7 @@ import { } from '@objectstack/spec/automation'; import { BUILTIN_MEMBERSHIP_ROLES } from '@objectstack/spec'; import { collectCelRootIdentifiers } from '@objectstack/formula'; -import { walkFlowNodes } from './flow-walk.js'; +import { flowDisplayLabel, flowNodeLabel, walkFlowNodes } from './flow-walk.js'; import { recordsOf } from './object-graph.js'; import type { UserTextParams } from './finding-user-text.js'; @@ -401,6 +401,9 @@ export function validateApprovalApprovers( const flow = flows[fi]; if (!flow || typeof flow !== 'object') continue; const flowName = typeof flow.name === 'string' ? flow.name : `(flow ${fi})`; + // The user sentences name the flow and its nodes by the labels the builder + // sees in Studio; `where`, `message` and `path` keep the machine names. + const flowLabel = flowDisplayLabel(flow as AnyRec, fi); // Every node, INCLUDING those nested in try_catch / loop / parallel regions // — an approval inside a loop body is still an approval (#4380). const walked = walkFlowNodes(flow, `flows[${fi}]`); @@ -409,6 +412,7 @@ export function validateApprovalApprovers( const { node, path: nodePath } = walked[ni]; if (!node || node.type !== APPROVAL_NODE_TYPE) continue; const nodeId = typeof node.id === 'string' ? node.id : `(node ${ni})`; + const nodeLabel = flowNodeLabel(node as AnyRec, ni); const cfg = (node.config ?? {}) as AnyRec; const approvers = Array.isArray(cfg.approvers) ? (cfg.approvers as AnyRec[]) : []; const where = `flow "${flowName}" · node "${nodeId}"`; @@ -432,7 +436,7 @@ export function validateApprovalApprovers( hint: fix ? `Use the spec value: { type: '${fix}', value: '${value}' }.` : `Pick one of the spec values; unmapped types degrade to an inert '${type}:${value}' literal at runtime.`, - userTextParams: { flow: flowName, node: nodeId, type, suggested: fix ?? '' }, + userTextParams: { flow: flowLabel, node: nodeLabel, type, suggested: fix ?? '' }, }); continue; } @@ -525,7 +529,7 @@ export function validateApprovalApprovers( path: `${path}.resolveAs`, message: `resolveAs has no effect on a '${type}' approver — it only applies to type 'expression'.`, hint: `Remove it, or switch this approver to { type: 'expression', value: '', resolveAs: '${String(a.resolveAs)}' }.`, - userTextParams: { flow: flowName, node: nodeId, type }, + userTextParams: { flow: flowLabel, node: nodeLabel, type }, }); } @@ -551,7 +555,7 @@ export function validateApprovalApprovers( hint: `If it is an org position, author { type: 'position', value: '${value}' }; keep ` + `'org_membership_level' for the tiers the verdict lists`, - userTextParams: { flow: flowName, node: nodeId, value }, + userTextParams: { flow: flowLabel, node: nodeLabel, value }, }); } else if (type in DEPRECATED_APPROVER_TYPES) { const fix = canonicalApproverType(type); @@ -564,7 +568,7 @@ export function validateApprovalApprovers( `approver type '${type}' is the deprecated spelling of '${fix}' (ADR-0090 D3) and ` + `is removed in the next major.`, hint: `Author { type: '${fix}', value: '${value}' }. It resolves identically today.`, - userTextParams: { flow: flowName, node: nodeId, type, replacement: fix }, + userTextParams: { flow: flowLabel, node: nodeLabel, type, replacement: fix }, }); } else if ( (APPROVER_VALUE_BINDINGS as Record)[canonical]?.source === 'unsupported' @@ -588,7 +592,7 @@ export function validateApprovalApprovers( hint: `Route to people the engine can expand: ` + `{ type: ${EXPANDABLE_GROUP_TYPES.map((t) => `'${t}'`).join(' | ')}, ... }.`, - userTextParams: { flow: flowName, node: nodeId, type, routes: EXPANDABLE_GROUP_TYPES.join(', ') }, + userTextParams: { flow: flowLabel, node: nodeLabel, type, routes: EXPANDABLE_GROUP_TYPES.join(', ') }, }); } @@ -670,7 +674,7 @@ export function validateApprovalApprovers( `none is staffed the request opens on the organization's administrators` + (locks ? STAYS_LOCKED : ''), hint: GROUP_ONLY_FIX, - userTextParams: { flow: flowName, node: nodeId, slate: 'group', locked: locks ? 'yes' : 'no' }, + userTextParams: { flow: flowLabel, node: nodeLabel, slate: 'group', locked: locks ? 'yes' : 'no' }, }); } @@ -717,7 +721,7 @@ export function validateApprovalApprovers( `is unset the request opens on the organization's administrators` + (locks ? STAYS_LOCKED : ''), hint: MANAGER_ONLY_FIX, - userTextParams: { flow: flowName, node: nodeId, slate: 'manager', locked: locks ? 'yes' : 'no' }, + userTextParams: { flow: flowLabel, node: nodeLabel, slate: 'manager', locked: locks ? 'yes' : 'no' }, }); } @@ -745,7 +749,7 @@ export function validateApprovalApprovers( hint: `Declare onEmptyApprovers on the node: 'admin_rescue', 'fail', 'auto_approve', or 'fallback' ` + `with a fallbackApprovers list`, - userTextParams: { flow: flowName, node: nodeId }, + userTextParams: { flow: flowLabel, node: nodeLabel }, }); } @@ -787,7 +791,7 @@ export function validateApprovalApprovers( hint: `Set escalateTo to a position machine name (expanded via sys_user_position, ` + `ADR-0090 D3) or a specific user id, or change action to 'notify'.`, - userTextParams: { flow: flowName, node: nodeId }, + userTextParams: { flow: flowLabel, node: nodeLabel }, }); } } diff --git a/packages/metadata-protocol/src/metadata-diagnostics.publish-advisories.test.ts b/packages/metadata-protocol/src/metadata-diagnostics.publish-advisories.test.ts new file mode 100644 index 00000000000..e34097ddd2d --- /dev/null +++ b/packages/metadata-protocol/src/metadata-diagnostics.publish-advisories.test.ts @@ -0,0 +1,52 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34818] `withPublishAdvisories` — how the gate's advisories join a served + * draft's `_diagnostics`: as warnings, in their user sentence, item-relative, + * once, and only for a type whose editor shows them. + */ + +import { describe, expect, it } from 'vitest'; +import type { RuntimeAuthoringIssue } from '@objectstack/spec/api'; +import { withPublishAdvisories } from './metadata-diagnostics.js'; +// Paid during collection, not inside a case's clock: the module under test +// loads the lint package with a function-body import (check:test-source-alias). +import '@objectstack/lint'; + +const advisory = (over: Partial = {}): RuntimeAuthoringIssue => ({ + rule: 'flow-decision-unconditional-branch', + path: 'flows[0].nodes[1]', + where: "flow 'f' · decision 'node_2'", + message: 'gates on NOTHING', + hint: 'Gate the branches.', + severity: 'warning', + ...over, +}); + +describe('[#34818] withPublishAdvisories', () => { + it('adds each advisory as an item-relative warning in its user sentence, leaving valid as it was', () => { + const out = withPublishAdvisories('flow', 'f', { valid: true }, [advisory({ userMessage: '条件分支没有条件。' })]); + expect(out).toEqual({ valid: true, warnings: [{ path: 'nodes.1', message: '条件分支没有条件。' }] }); + const refused = withPublishAdvisories('flows', 'f', { valid: false, errors: [{ path: 'nodes.0', message: 'x' }] }, [advisory()]); + expect(refused).toEqual({ + valid: false, + errors: [{ path: 'nodes.0', message: 'x' }], + warnings: [{ path: 'nodes.1', message: 'gates on NOTHING' }], + }); + }); + + it('keeps the developer message for a finding with no user sentence, and repeats no warning already there', () => { + const prior = { valid: true, warnings: [{ path: 'nodes.1', message: 'gates on NOTHING' }] }; + expect(withPublishAdvisories('flow', 'f', prior, [advisory(), advisory()])).toBe(prior); + expect(withPublishAdvisories('flow', 'f', undefined, [advisory(), advisory()])).toEqual({ + valid: true, + warnings: [{ path: 'nodes.1', message: 'gates on NOTHING' }], + }); + }); + + it('returns the diagnostics untouched for another type, or with no advisories', () => { + const prior = { valid: true }; + expect(withPublishAdvisories('object', 'invoice', prior, [advisory({ path: 'objects.invoice.fields.x' })])).toBe(prior); + expect(withPublishAdvisories('flow', 'f', prior, [])).toBe(prior); + }); +}); diff --git a/packages/metadata-protocol/src/metadata-diagnostics.ts b/packages/metadata-protocol/src/metadata-diagnostics.ts index 0b635c90f78..30c81dde476 100644 --- a/packages/metadata-protocol/src/metadata-diagnostics.ts +++ b/packages/metadata-protocol/src/metadata-diagnostics.ts @@ -454,6 +454,53 @@ export function withPublishVerdict( return verdict; } +/** + * [#34818] The draft types whose served `_diagnostics.warnings` carry the gate's + * advisories ({@link withPublishAdvisories}). A type joins when its editor has a + * place that shows them on the element they name: the flow designer's Problems + * tab, its per-node badges and the publish drawer. Every other type's draft is + * served as before, its advisories still returned on the publish's 2xx. + */ +const DRAFT_ADVISORY_TYPES: ReadonlySet = new Set(['flow']); + +/** + * Fold what publishing a draft would still SAY into the draft's `_diagnostics`: + * the runtime gate's advisories for the draft body (the findings a publish that + * passes returns on its 2xx), each as one `warnings[]` entry. The entry's + * `message` is the finding's user sentence (`userMessage`, composed in the + * read's `userTextLocales`) when the finding has one, else its developer + * `message`; its `path` is item-relative as for {@link withPublishVerdict}. + * Warnings never change `valid`. An advisory whose path and words a warning + * already carries is not repeated. Only for {@link DRAFT_ADVISORY_TYPES}; any + * other type, and no advisories, return `diagnostics` itself. + */ +export function withPublishAdvisories( + type: string, + name: string, + diagnostics: MetadataDiagnostics | undefined, + advisories: readonly RuntimeAuthoringIssue[], +): MetadataDiagnostics | undefined { + if (advisories.length === 0 || !DRAFT_ADVISORY_TYPES.has(PLURAL_TO_SINGULAR[type] ?? type)) return diagnostics; + const findingKey = (entry: { path: string; message: string }) => JSON.stringify([entry.path, entry.message]); + const prior = diagnostics?.warnings ?? []; + const seen = new Set(prior.map(findingKey)); + const added: Array<{ path: string; message: string }> = []; + for (const advisory of advisories) { + const entry = { + path: itemRelativeIssuePath(type, name, advisory.path), + message: typeof advisory.userMessage === 'string' && advisory.userMessage.trim() !== '' + ? advisory.userMessage + : advisory.message, + }; + const key = findingKey(entry); + if (seen.has(key)) continue; + seen.add(key); + added.push(entry); + } + if (added.length === 0) return diagnostics; + return { ...diagnostics, valid: diagnostics?.valid ?? true, warnings: [...prior, ...added] }; +} + // --------------------------------------------------------------------------- // [#29196] The lint's `form-field-unknown` on a served view's `_diagnostics` // [#29309] …and its sibling `form-section-group-unknown` diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index 0a688cb1213..c05bab828be 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -710,11 +710,51 @@ function packagedRuleCopyRefusalOf( }; } +/** The members {@link draftPublishJudgement} and {@link draftPublishVerdict} read. */ +type DraftVerdictHost = RuntimeRulesHost & Pick; + +/** + * [#34818] What publishing a stored draft would answer: the refusal's issues + * ({@link draftPublishVerdict}'s answer) and, beside them, the gate's + * ADVISORIES — the findings a publish that passes returns on its 2xx, which the + * console otherwise sees only after the publish, in a toast. One judgement, so + * the two halves come from the same run of the same rules. + */ +export interface DraftPublishJudgement { + refusals: RuntimeAuthoringIssue[]; + advisories: RuntimeAuthoringIssue[]; +} + /** The body of `ObjectStackProtocolImplementation#draftPublishVerdict`; the method's docblock there is its contract. */ export async function draftPublishVerdict( - this: RuntimeRulesHost & Pick, + this: DraftVerdictHost, draft: { type: string; name: string; body: unknown; packageId: string | null }, ): Promise { + return (await draftPublishJudgement.call(this, draft)).refusals; +} + +/** + * The body of `ObjectStackProtocolImplementation#draftPublishJudgement` (#34818): + * {@link draftPublishVerdict}'s judgement with the gate's ADVISORIES beside its + * refusal — what a publish that passes would still say about the draft, which + * the publish returns on its 2xx and the draft read folds into + * `_diagnostics.warnings` (`withPublishAdvisories`), so a flow designer shows the + * publish checks before Publish is pressed. One run of the same rules; + * `userTextLocales` picks the language of the advisories' user sentences and + * nothing else. + */ +export async function draftPublishJudgement( + this: DraftVerdictHost, + draft: { + type: string; name: string; body: unknown; packageId: string | null; + /** + * [#34818] The locales the advisories' user sentences are composed in + * (`GetMetaItemRequestSchema.userTextLocales`, stated by the draft read + * doors). Absent ⇒ `en`. Selects a language, never a verdict. + */ + userTextLocales?: readonly (string | undefined)[]; + }, +): Promise { const singular = PLURAL_TO_SINGULAR[draft.type] ?? draft.type; // The closure "Publish all" judges this draft against: its package's other // drafts, collected by the batch door's own collector from the batch door's @@ -742,6 +782,7 @@ export async function draftPublishVerdict( ...(channel ? { restoredCredentialPaths: () => channel.heldPaths({ name: draft.name, state: 'draft', item: draft.body }) } : {}), + ...(draft.userTextLocales !== undefined ? { userTextLocales: draft.userTextLocales } : {}), }); const issues = (verdict.error as { issues?: RuntimeAuthoringIssue[] } | null)?.issues ?? []; // [#27444 · ADR-0129 D2] The namespace-prefix rule is not a gate rule: the @@ -778,5 +819,5 @@ export async function draftPublishVerdict( severity: 'error', }); } - return told.length > 0 ? [...told, ...issues] : issues; + return { refusals: told.length > 0 ? [...told, ...issues] : issues, advisories: verdict.advisories }; } diff --git a/packages/metadata-protocol/src/protocol-host.ts b/packages/metadata-protocol/src/protocol-host.ts index 7af6e930ed7..fdda2a1c1ad 100644 --- a/packages/metadata-protocol/src/protocol-host.ts +++ b/packages/metadata-protocol/src/protocol-host.ts @@ -101,6 +101,7 @@ export interface ProtocolHost { readonly diffMetaItem: ObjectStackProtocolImplementation['diffMetaItem']; readonly disabledActionsOf: ObjectStackProtocolImplementation['disabledActionsOf']; readonly discardDraftInItsScope: ObjectStackProtocolImplementation['discardDraftInItsScope']; + readonly draftPublishJudgement: ObjectStackProtocolImplementation['draftPublishJudgement']; readonly draftPublishVerdict: ObjectStackProtocolImplementation['draftPublishVerdict']; readonly dropObjectStorage: ObjectStackProtocolImplementation['dropObjectStorage']; readonly dropStorageRemainingRowsRefusal: (typeof ObjectStackProtocolImplementation)['dropStorageRemainingRowsRefusal']; diff --git a/packages/metadata-protocol/src/protocol-meta-item-face.ts b/packages/metadata-protocol/src/protocol-meta-item-face.ts index 404bc51e43d..3fd2c22513c 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-face.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-face.ts @@ -781,6 +781,8 @@ export async function readMetaItemFace( request: { type: string, name: string, packageId?: string, state?: 'active' | 'draft', previewDrafts?: boolean, member?: string, + /** [#34818] The draft read's user-sentence locales (`GetMetaItemRequestSchema.userTextLocales`). */ + userTextLocales?: readonly string[], }, face: 'served' | 'execution', ) { diff --git a/packages/metadata-protocol/src/protocol-meta-item-reads.ts b/packages/metadata-protocol/src/protocol-meta-item-reads.ts index 7454a58608f..18c5c38e4ee 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-reads.ts @@ -37,6 +37,7 @@ import { type MetadataDiagnostics, computeViewReferenceDiagnostics, decorateMetadataItem, + withPublishAdvisories, withPublishVerdict, withViewLintWarnings, } from './metadata-diagnostics.js'; @@ -565,6 +566,8 @@ export async function getMetaItem(host: Pick, request: { +export async function readMetaItem(host: Pick, request: { type: string, name: string, packageId?: string, state?: 'active' | 'draft', previewDrafts?: boolean, member?: string, + /** [#34818] The draft read's user-sentence locales (`GetMetaItemRequestSchema.userTextLocales`). */ + userTextLocales?: readonly string[], }, opts: { face?: 'served' | 'execution'; activeRows?: PrereadActiveRows } = {}) { // #4432 — CANONICAL TYPE KEY. See {@link canonicalMetaType}. request = canonicalizeMetaRequestType(request); @@ -761,17 +766,23 @@ export async function readMetaItem(host: Pick(resolved: T, row: { metadata?: unknown; package_id?: string | null }): Promise => { const served = await serveViewLint(serveItem(resolved)); if (execution || !served || typeof served !== 'object') return served; - const issues = await host.draftPublishVerdict({ + const judgement = await host.draftPublishJudgement({ type: request.type, name: request.name, body: storedRowDocument(row), packageId: row.package_id ?? null, + ...(request.userTextLocales !== undefined ? { userTextLocales: request.userTextLocales } : {}), }); const before = (served as { _diagnostics?: MetadataDiagnostics })._diagnostics; - const after = withPublishVerdict(request.type, request.name, before, issues); + const refused = withPublishVerdict(request.type, request.name, before, judgement.refusals); + const after = withPublishAdvisories(request.type, request.name, refused, judgement.advisories); return after === before ? served : { ...served, _diagnostics: after }; }; // ── [#20946, #20761 ruling rule 1, ADR-0126 §2 / §3] A shipped FLOW name ── diff --git a/packages/metadata-protocol/src/protocol.draft-publish-verdict.test.ts b/packages/metadata-protocol/src/protocol.draft-publish-verdict.test.ts index f644d18e002..6bc0e28e377 100644 --- a/packages/metadata-protocol/src/protocol.draft-publish-verdict.test.ts +++ b/packages/metadata-protocol/src/protocol.draft-publish-verdict.test.ts @@ -1286,3 +1286,100 @@ describe('[#29696] a flow read judges a stored legacy D2 row in its D2-converted expect(legacy.config.filters).toEqual({ name: 'Acme' }); }); }); + +// ── [#34818] What the publish would still SAY, on the flow draft read ──────── +// +// Measured on `origin/main` (3bbda33b) before this block: a flow draft whose +// decision gates on nothing read `_diagnostics: { valid: true }` with no +// warning, and its publish passed and returned the finding on the 2xx, so the +// flow designer's Problems tab said "no problems" until after the publish. + +/** A labelled flow whose decision gates on nothing: an advisory, never a refusal. */ +const ungatedDecisionFlow = { + name: 'meeting_reminder', + label: '会议提醒', + type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'node_2', type: 'decision', label: '检查日期', config: {} }, + { id: 'node_3', type: 'end', label: '提醒负责人' }, + { id: 'node_4', type: 'end', label: '跳过' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'node_2' }, + { id: 'e2', source: 'node_2', target: 'node_3' }, + { id: 'e3', source: 'node_2', target: 'node_4' }, + ], +}; + +async function draftRead(protocol: ObjectStackProtocolImplementation, type: string, name: string, userTextLocales?: string[]) { + const read: any = await protocol.getMetaItem({ + type, name, state: 'draft', packageId: PKG, ...(userTextLocales ? { userTextLocales } : {}), + } as any); + return read.item._diagnostics as { valid: boolean; errors?: unknown[]; warnings?: Array<{ path: string; message: string }> }; +} + +describe('[#34818] a flow draft read carries the advisories its publish would return', () => { + let warn: ReturnType; + beforeEach(() => { + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + delete process.env.OS_ALLOW_UNLINTED_METADATA_WRITES; + }); + afterEach(() => { + warn.mockRestore(); + }); + + it('as a warning on the decision node, in the request\'s language, naming steps by label', async () => { + const { engine } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(engine); + await stageDraft(protocol, 'flow', ungatedDecisionFlow); + + const diagnostics = await draftRead(protocol, 'flow', 'meeting_reminder', ['zh-CN', 'en']); + // An advisory is not a refusal: the draft still reads valid. + expect(diagnostics.valid).toBe(true); + expect(diagnostics.errors ?? []).toEqual([]); + const warning = (diagnostics.warnings ?? []).find((w) => w.path === 'nodes.1'); + expect(warning, JSON.stringify(diagnostics)).toBeDefined(); + expect(warning!.message).toContain('流程“会议提醒”中的条件分支“检查日期”'); + expect(warning!.message).toContain('“提醒负责人”、“跳过”'); + expect(warning!.message).not.toMatch(/node_\d|meeting_reminder|flow-decision-unconditional-branch/); + }); + + it('in English when the read states no locale', async () => { + const { engine } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(engine); + await stageDraft(protocol, 'flow', ungatedDecisionFlow); + + const warning = ((await draftRead(protocol, 'flow', 'meeting_reminder')).warnings ?? []) + .find((w) => w.path === 'nodes.1'); + expect(warning!.message).toContain('The branch step "检查日期" in flow "会议提醒"'); + }); + + it('with the words and path the publish returns for the same finding', async () => { + const { engine } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(engine); + await stageDraft(protocol, 'flow', ungatedDecisionFlow); + const judgement = await (protocol as any).draftPublishJudgement({ + type: 'flow', name: 'meeting_reminder', body: ungatedDecisionFlow, packageId: PKG, userTextLocales: ['zh-CN'], + }); + const advisory = judgement.advisories.find((a: any) => a.rule === 'flow-decision-unconditional-branch'); + expect(advisory.path).toBe('flows[0].nodes[1]'); + expect(judgement.refusals).toEqual([]); + + const warning = ((await draftRead(protocol, 'flow', 'meeting_reminder', ['zh-CN'])).warnings ?? []) + .find((w) => w.path === 'nodes.1'); + expect(warning!.message).toBe(advisory.userMessage); + }); + + it('a gated decision reads no such warning', async () => { + const { engine } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(engine); + const gated = structuredClone(ungatedDecisionFlow); + (gated.edges[1] as Record).condition = 'true'; + (gated.edges[2] as Record).isDefault = true; + await stageDraft(protocol, 'flow', gated); + + const warnings = (await draftRead(protocol, 'flow', 'meeting_reminder', ['zh-CN'])).warnings ?? []; + expect(warnings.filter((w) => w.path === 'nodes.1')).toEqual([]); + }); +}); diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 4187322317f..5d5946c4577 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -266,6 +266,8 @@ import type { ImportUnmanagedPackageAnswer } from './protocol-package-install.js // [#25467 cut 8] The runtime authoring gate and the restored-body doors. import { assertRuntimeAuthoringRules, + draftPublishJudgement, + type DraftPublishJudgement, draftPublishVerdict, refuseRestoredBodyTheSaveDoorRefuses, restoredBodyDerivation, @@ -1235,6 +1237,7 @@ export class ObjectStackProtocolImplementation implements diffMetaItem: (...a) => protocol.diffMetaItem(...a), disabledActionsOf: (...a) => protocol.disabledActionsOf(...a), discardDraftInItsScope: (...a) => protocol.discardDraftInItsScope(...a), + draftPublishJudgement: (...a) => protocol.draftPublishJudgement(...a), draftPublishVerdict: (...a) => protocol.draftPublishVerdict(...a), dropObjectStorage: (...a) => protocol.dropObjectStorage(...a), dropStorageRemainingRowsRefusal: (...a) => ObjectStackProtocolImplementation.dropStorageRemainingRowsRefusal(...a), @@ -1904,9 +1907,22 @@ export class ObjectStackProtocolImplementation implements private draftPublishVerdict(draft: { type: string; name: string; body: unknown; packageId: string | null; }): Promise { + return draftPublishVerdict.call(this.draftVerdictHost(), draft); + } + + /** [#34818] The same judgement with the gate's advisories beside its refusal (see `draftPublishJudgement`). */ + private draftPublishJudgement(draft: { + type: string; name: string; body: unknown; packageId: string | null; + userTextLocales?: readonly (string | undefined)[]; + }): Promise { + return draftPublishJudgement.call(this.draftVerdictHost(), draft); + } + + /** The host both draft verdict bodies read: the promotion's own collaborators. */ + private draftVerdictHost(): ThisParameterType { const readAuthoringChannel = () => this.authoringChannel; const readEngine = () => this.engine; - const host: ThisParameterType = { + const host: ThisParameterType = { get authoringChannel() { return readAuthoringChannel(); }, get engine() { return readEngine(); }, collectBatchPendingDeclarations: (...a) => this.collectBatchPendingDeclarations(...a), @@ -1922,7 +1938,7 @@ export class ObjectStackProtocolImplementation implements rlsMembershipResolverKeys: (...a) => this.rlsMembershipResolverKeys(...a), tenancyPostureInForce: (...a) => this.tenancyPostureInForce(...a), }; - return draftPublishVerdict.call(host, draft); + return host; } /** @@ -4103,6 +4119,8 @@ export class ObjectStackProtocolImplementation implements type: string, name: string, packageId?: string, state?: 'active' | 'draft', previewDrafts?: boolean, /** [#22877] The bundle member to read — {@link resolveBundleMemberSelector}; omitted, the canonical one. */ member?: string, + /** [#34818] The draft read's user-sentence locales (`GetMetaItemRequestSchema.userTextLocales`). */ + userTextLocales?: readonly string[], }) { // [#25467 E1] The body moved to `protocol-meta-item-reads.ts`; it reaches this class through `protocol-host.ts`. return getMetaItem(protocolHost(this), request); @@ -4156,7 +4174,7 @@ export class ObjectStackProtocolImplementation implements */ private async readMetaItemFace(request: { type: string, name: string, packageId?: string, state?: 'active' | 'draft', previewDrafts?: boolean, - member?: string, + member?: string, userTextLocales?: readonly string[], }, face: 'served' | 'execution') { // [#25467 cut 31] The body moved to `protocol-meta-item-face.ts` (see `MetaItemFaceHost`). const readEngine = () => this.engine; @@ -4195,7 +4213,7 @@ export class ObjectStackProtocolImplementation implements */ private async readMetaItem(request: { type: string, name: string, packageId?: string, state?: 'active' | 'draft', previewDrafts?: boolean, - member?: string, + member?: string, userTextLocales?: readonly string[], }, opts: { face?: 'served' | 'execution'; activeRows?: PrereadActiveRows } = {}) { // [#25467 E1] The body moved to `protocol-meta-item-reads.ts`; it reaches this class through `protocol-host.ts`. return readMetaItem(protocolHost(this), request, opts); diff --git a/packages/rest/src/meta-item-read-routes.ts b/packages/rest/src/meta-item-read-routes.ts index 356116bd6b7..067bcec13b4 100644 --- a/packages/rest/src/meta-item-read-routes.ts +++ b/packages/rest/src/meta-item-read-routes.ts @@ -102,7 +102,7 @@ * not move. */ -import { rethrowAuthzStoreUnavailable } from '@objectstack/core'; +import { rethrowAuthzStoreUnavailable, userTextLocalesOf } from '@objectstack/core'; // [ADR-0106 / #3682] Metadata-plane FLS — the item read's half of it; see // `rest-server.ts`' import of the same module for why the normalizer lives in // `@objectstack/metadata-core`. @@ -1085,6 +1085,12 @@ export function registerMetaItemReadRoutes(this: MetaItemReadRouteHost, scope: M ...(previewDrafts ? { previewDrafts: true } : {}), // [#22877] The member, read once above. ...memberSelector, + // [#34818] A draft read folds the publish's + // advisories into `_diagnostics.warnings` in their + // user sentence: the request's locale, then the + // workspace default, read off the resolved + // context, never the query. + ...(isDraftRead ? { userTextLocales: userTextLocalesOf(readCtx) } : {}), }; const envelope = await measureMetaRead(() => p.getMetaItem(itemRequest)) as Record; diff --git a/packages/runtime/src/domains/meta.ts b/packages/runtime/src/domains/meta.ts index 7054c60488a..f747a8d5aed 100644 --- a/packages/runtime/src/domains/meta.ts +++ b/packages/runtime/src/domains/meta.ts @@ -895,6 +895,11 @@ async function readPendingDraft( // [#23072] The member the item read's `?member=` named: its own // draft row, as `RestServer`'s draft read asks for it. ...item.memberSelector, + // [#34818] The languages the folded publish advisories' user + // sentences are composed in: the request's locale, then the + // workspace default, off the execution context, as `RestServer`'s + // draft read states them. + userTextLocales: userTextLocalesOf(context.executionContext), }); } catch (e: any) { return { handled: true, response: deps.errorFromThrown(e, 404) }; diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index a34eb2a38fa..00dc072a003 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -839,6 +839,7 @@ "api/GetMetaItemRequest:previewDrafts", "api/GetMetaItemRequest:state", "api/GetMetaItemRequest:type", + "api/GetMetaItemRequest:userTextLocales", "api/GetMetaItemResponse:cascadeDeleteObjects", "api/GetMetaItemResponse:deletable", "api/GetMetaItemResponse:disabledActions", diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index a0a50301714..ce2cedf4acb 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -442,6 +442,18 @@ export const GetMetaItemRequestSchema = lazySchema(() => z.object({ + 'ADR-0106 masking is unaffected — draft preview is admin-gated ' + 'upstream, not by this schema.', ), + userTextLocales: z.array(z.string()).max(2).optional().describe( + 'The locales the user-facing sentences of a served DRAFT\'s check findings are composed in, in ladder ' + + 'order: the locale the request names, then the workspace default — the save request\'s member of the ' + + 'same name, read the same way (each value against the platform locale table, whole and then one ' + + 'subtag shorter at a time; a value that names no table language is passed over; `en` is the last ' + + 'rung). Read only by the `state: \'draft\'` read, which folds what publishing the draft would say ' + + 'into its `_diagnostics`: an advisory finding that carries a user sentence becomes a ' + + '`_diagnostics.warnings[]` entry in that sentence. Stated by the door that holds the request (the ' + + 'REST door and the dispatcher state `[ExecutionContext.locale, ExecutionContext.workspaceLocale]`), ' + + 'never read from a query string. ABSENT ⇒ the sentences are composed in `en`. It selects a language ' + + 'only: which row is read, and what the verdict is, do not depend on it.', + ), })); /** diff --git a/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx b/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx index 11548ecb0f8..ce8607faefa 100644 --- a/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx +++ b/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx @@ -32,7 +32,7 @@ */ import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type ReactNode } from 'react'; -import { ChevronDown, ChevronRight, Equal, FilePlus2, FilePen, Loader2, Rocket, ShieldAlert } from 'lucide-react'; +import { ChevronDown, ChevronRight, Equal, FilePlus2, FilePen, ListChecks, Loader2, Rocket, ShieldAlert } from 'lucide-react'; import { toast } from 'sonner'; import { Badge, @@ -111,6 +111,11 @@ import { isStudioHiddenSystemField } from '../views/studio-design/studioHiddenSy // EAGER graph (see the `@objectstack/spec` note above for what that costs). import { useSurfaceNavigator } from '../views/studio-design/surfaceDeepLinkChannel.js'; import { lintDraftSecurityPosture, type DraftSecurityProblem } from './securityPostureLint.js'; +// objectstack#34818 — what a flow draft's publish would still say, read off +// the server's own draft read. React-free and import-light (no `@objectstack/*` +// runtime import), so it adds nothing else to the eager graph described above. +import { readDraftChecks, type DraftCheck } from './flowDraftChecks.js'; +import { clearPublishChecksShown, markPublishChecksShown } from './publishChecksShown.js'; // objectstack#27835 — a property by its label on the item type's form. import { formKeyLabel, labelSpellsKey } from './changeKeyLabels.js'; @@ -941,6 +946,20 @@ function securityProblemText(t: Translate, p: DraftSecurityProblem): string { return known ? known(t) : p.hint || p.message; } +/** objectstack#34818 — the checks grouped by the draft they are about, in first-seen order. */ +function draftChecksByItem( + checks: readonly DraftCheck[], +): Array<{ type: string; name: string; items: DraftCheck[] }> { + const groups = new Map(); + for (const c of checks) { + const key = JSON.stringify([c.type, c.name]); + const group = groups.get(key) ?? { type: c.type, name: c.name, items: [] }; + group.items.push(c); + groups.set(key, group); + } + return [...groups.values()]; +} + /** A backfill choice's identity: object and field, as a JSON tuple so no spelling collides. */ function backfillKey(entry: DraftBackfillEntry): string { return JSON.stringify([entry.object, entry.field]); @@ -1508,6 +1527,13 @@ export function DraftChangesPanel({ * arrives after the batch has already rolled back. */ const [problems, setProblems] = useState([]); + /** + * objectstack#34818 — what each flow draft's publish would still say: the + * gate's advisories (and any refusal) the server folds into the draft read, + * worded for the builder in the console's language. Listed beside the + * button so the author reads them before publishing, not in a toast after. + */ + const [checks, setChecks] = useState([]); /** * Null wherever no host listens for a surface request — the degradation this * panel owes its second home (Home / the draft-preview bar). Never a route @@ -1603,6 +1629,7 @@ export function DraftChangesPanel({ setEntries(null); setError(null); setProblems([]); + setChecks([]); setUnchanged(new Set()); setBackfill(new Map()); setNote(''); @@ -1624,6 +1651,18 @@ export function DraftChangesPanel({ }, drafts, ).then(setProblems, () => setProblems([])); + // objectstack#34818 — same stance: advisory, never awaited, and a failed + // read is "no checks". The read states the console's language, which is + // how the server picks the sentences' locale; this sheet's other reads + // state none. + void readDraftChecks(drafts, { + language: language || (typeof document !== 'undefined' ? document.documentElement.lang : '') || undefined, + }).then( + (found) => { + if (loadGenRef.current === gen) setChecks(found); + }, + () => undefined, + ); // Classify new-vs-update per TYPE: one published-list read covers every // draft of that type. A type whose read fails stays unclassified // (rendered neutrally) rather than failing the whole panel. @@ -1709,7 +1748,7 @@ export function DraftChangesPanel({ } finally { if (loadGenRef.current === gen) setClassifying(false); } - }, [packageId, include]); + }, [packageId, include, language]); useEffect(() => { if (open) void load(); @@ -1941,6 +1980,54 @@ export function DraftChangesPanel({ )) )} + {checks.length > 0 && !error && ( +
+

+ + {t('preview.changes.flowChecksTitle', { + defaultValue: 'Before you publish — the publish check will report these', + })} +

+
    + {draftChecksByItem(checks).map(({ type, name, items }) => { + const entry = entries?.find((e) => e.type === type && e.name === name); + const heading = resolveI18nLabel(entry?.label, language)?.trim() || name; + return ( +
  • + {/* The flow by the label its row shows, opening its designer + where a host publishes the surface channel (Studio), plain + text elsewhere — the security block's rule, below. */} + {openSurface ? ( + + ) : ( + {heading} + )} +
      + {items.map((c, i) => ( +
    • + {c.message} +
    • + ))} +
    +
  • + ); + })} +
+
+ )} {problems.length > 0 && !error && (
0 ? { backfill: [...backfill.values()] } : {}), ...(message ? { message } : {}), }; - void (Object.keys(options).length > 0 ? onPublish(options) : onPublish()); + // objectstack#34818 — the items whose publish checks this + // sheet just listed: their post-publish toast keeps its one + // title line (`publishChecksShown.ts`). Marked for the + // publish's flight only. + const reviewed = draftChecksByItem(checks); + for (const r of reviewed) markPublishChecksShown(r.type, r.name); + const clearReviewed = () => { + for (const r of reviewed) clearPublishChecksShown(r.type, r.name); + }; + try { + void Promise.resolve( + Object.keys(options).length > 0 ? onPublish(options) : onPublish(), + ).finally(clearReviewed); + } catch (e) { + clearReviewed(); + throw e; + } }} disabled={publishing} data-testid="draft-changes-publish" diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.flowChecks-34818.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.flowChecks-34818.test.tsx new file mode 100644 index 00000000000..d18e1ab4b0a --- /dev/null +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.flowChecks-34818.test.tsx @@ -0,0 +1,146 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The pending-changes sheet lists what a flow draft's publish will report, + * BEFORE the publish — objectstack#34818 item 1. + * + * The card's walk: a new flow with an unconfigured branch, 全部发布, and only + * then a toast carrying two findings that vanished on a timer. The server now + * folds the publish gate's advisories into the flow draft's read, worded for + * the builder; this suite pins that the sheet shows those sentences beside the + * Publish button, under the flow's label, as sent — that it stays silent when + * the draft has nothing to report — that it never takes the button away — and + * that a publish from here is marked as one whose checks the author reviewed, + * for its flight only (the toast then keeps its one title line). + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; + +// Same targeted override as the sibling security suite: `@object-ui/components` +// pulls `createSafeTranslation` from this module, so a bare object mock breaks +// at import time rather than at assert time. +vi.mock('@object-ui/i18n', async (importOriginal) => { + const mod = await importOriginal(); + return { + ...mod, + useObjectTranslation: () => ({ + t: (_k: string, o?: { defaultValue?: string; count?: number }) => + (o?.defaultValue ?? _k).replace('{{count}}', String(o?.count ?? '')), + language: 'zh-CN', + }), + }; +}); + +import { DraftChangesPanel } from '../DraftChangesPanel'; +import { werePublishChecksShown } from '../publishChecksShown'; +// Warm the lint package at module scope, as the sibling security suites do: +// the sheet's security lint loads it with a function-body import. +import '@objectstack/lint'; + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +const ADVISORY_ZH = + '流程“会议提醒”中的条件分支“检查日期”没有为任何一条连线(“提醒负责人”、“跳过”)设置条件,因此每次运行都会走所有连线,这个分支起不到选择作用。请为每条连线设置条件,并把其中一条设为默认分支。'; + +function mockRoutes(warnings: Array<{ path?: string; message: string }>) { + const fetchMock = vi.fn(async (input: RequestInfo | URL, _init?: RequestInit) => { + const url = String(input); + const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); + if (url.includes('/_drafts')) { + return ok([{ type: 'flow', name: 'xin_huiyi_tixing', packageId: 'app.minutes', label: '会议提醒' }]); + } + if (url.includes('state=draft')) { + return ok({ + type: 'flow', + name: 'xin_huiyi_tixing', + item: { + name: 'xin_huiyi_tixing', + label: '会议提醒', + nodes: [], + edges: [], + _diagnostics: { valid: true, errors: [], warnings }, + }, + }); + } + if (/\/meta\/flow(\?|$)/.test(url)) return ok([]); + return { ok: false, status: 404, json: async () => ({}) }; + }); + global.fetch = fetchMock as unknown as typeof fetch; + return fetchMock; +} + +const renderPanel = (onPublish: () => void | Promise = vi.fn()) => + render( {}} packageId="app.minutes" onPublish={onPublish} />); + +describe('DraftChangesPanel — the flow publish checks, before the publish (objectstack#34818)', () => { + it('lists the server sentence under the flow label, and asks in the console language', async () => { + const fetchMock = mockRoutes([{ path: 'nodes.1', message: ADVISORY_ZH }]); + renderPanel(); + const block = await screen.findByTestId('draft-flow-checks'); + const item = within(block).getByTestId('draft-flow-checks-item'); + expect(item.textContent).toContain('会议提醒'); + expect(item.textContent).toContain(ADVISORY_ZH); + // No rule id, no machine name of the flow in the row. + expect(block.textContent).not.toMatch(/flow-decision-unconditional-branch|xin_huiyi_tixing/); + // The read that fed it stated the console's language. + const draftCall = fetchMock.mock.calls.find( + ([u, init]) => String(u).includes('state=draft') && (init?.headers as Record | undefined)?.['Accept-Language'], + ); + expect((draftCall![1]!.headers as Record)['Accept-Language']).toBe('zh-CN'); + }); + + it('reports without blocking — the Publish button stays live', async () => { + mockRoutes([{ path: 'nodes.1', message: ADVISORY_ZH }]); + renderPanel(); + await screen.findByTestId('draft-flow-checks'); + expect(screen.getByTestId('draft-changes-publish')).not.toBeDisabled(); + }); + + it('says nothing for a flow draft whose publish has nothing to report', async () => { + mockRoutes([]); + renderPanel(); + await waitFor(() => expect(screen.getByTestId('draft-changes-publish')).toBeInTheDocument()); + await new Promise((r) => setTimeout(r, 150)); + expect(screen.queryByTestId('draft-flow-checks')).not.toBeInTheDocument(); + }); + + it('marks a publish from here as reviewed for its flight only', async () => { + mockRoutes([{ path: 'nodes.1', message: ADVISORY_ZH }]); + let release!: () => void; + let seenDuringPublish: boolean | undefined; + const onPublish = vi.fn( + () => + new Promise((resolve) => { + seenDuringPublish = werePublishChecksShown('flow', 'xin_huiyi_tixing'); + release = resolve; + }), + ); + renderPanel(onPublish); + await screen.findByTestId('draft-flow-checks'); + expect(werePublishChecksShown('flow', 'xin_huiyi_tixing')).toBe(false); + fireEvent.click(screen.getByTestId('draft-changes-publish')); + expect(onPublish).toHaveBeenCalledTimes(1); + expect(seenDuringPublish).toBe(true); + release(); + await waitFor(() => expect(werePublishChecksShown('flow', 'xin_huiyi_tixing')).toBe(false)); + }); + + it('CONTROL: a publish with nothing listed marks nothing', async () => { + mockRoutes([]); + let seenDuringPublish: boolean | undefined; + const onPublish = vi.fn(async () => { + seenDuringPublish = werePublishChecksShown('flow', 'xin_huiyi_tixing'); + }); + renderPanel(onPublish); + await waitFor(() => expect(screen.getByTestId('draft-changes-publish')).toBeInTheDocument()); + await new Promise((r) => setTimeout(r, 150)); + fireEvent.click(screen.getByTestId('draft-changes-publish')); + expect(seenDuringPublish).toBe(false); + }); +}); diff --git a/ui/packages/app-shell/src/preview/flowDraftChecks.test.ts b/ui/packages/app-shell/src/preview/flowDraftChecks.test.ts new file mode 100644 index 00000000000..2de0b631c8f --- /dev/null +++ b/ui/packages/app-shell/src/preview/flowDraftChecks.test.ts @@ -0,0 +1,104 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#34818 item 1 — the pending-changes sheet reads what a flow + * draft's publish would still say off the server's own draft read. + * + * Pinned: only flow drafts are read; the read states the console's language + * (the server picks the sentence's locale from it); the server's sentences come + * back as sent, refusals before advisories; a failed read is "no checks". + */ + +import { describe, expect, it, vi } from 'vitest'; +import { draftChecksOf, readDraftChecks } from './flowDraftChecks'; + +const ADVISORY_ZH = + '流程“会议提醒”中的条件分支“检查日期”没有为任何一条连线(“提醒负责人”、“跳过”)设置条件,因此每次运行都会走所有连线,这个分支起不到选择作用。请为每条连线设置条件,并把其中一条设为默认分支。'; + +const draftRead = (diagnostics: unknown) => ({ + type: 'flow', + name: 'xin_huiyi_tixing', + item: { name: 'xin_huiyi_tixing', label: '会议提醒', _diagnostics: diagnostics }, +}); + +function fetchReturning(payloadFor: (url: string) => unknown, status = 200) { + return vi.fn(async (input: RequestInfo | URL) => ({ + ok: status >= 200 && status < 300, + status, + json: async () => payloadFor(String(input)), + })) as unknown as typeof fetch & ReturnType; +} + +describe('draftChecksOf (objectstack#34818)', () => { + it('projects the served warnings, keeping the server sentence and the item-relative path', () => { + const checks = draftChecksOf( + { type: 'flow', name: 'xin_huiyi_tixing' }, + draftRead({ valid: true, errors: [], warnings: [{ path: 'nodes.1', message: ADVISORY_ZH }] }), + ); + expect(checks).toEqual([ + { type: 'flow', name: 'xin_huiyi_tixing', severity: 'warning', message: ADVISORY_ZH, path: 'nodes.1' }, + ]); + }); + + it('lists a refusal before an advisory', () => { + const checks = draftChecksOf( + { type: 'flow', name: 'f' }, + draftRead({ + valid: false, + errors: [{ path: 'nodes.0', message: 'refused' }], + warnings: [{ path: 'nodes.1', message: 'advised' }], + }), + ); + expect(checks.map((c) => [c.severity, c.message])).toEqual([ + ['error', 'refused'], + ['warning', 'advised'], + ]); + }); + + it('yields nothing for a body with no diagnostics, and skips a blank message', () => { + expect(draftChecksOf({ type: 'flow', name: 'f' }, { item: { name: 'f' } })).toEqual([]); + expect( + draftChecksOf({ type: 'flow', name: 'f' }, draftRead({ valid: true, errors: [], warnings: [{ message: ' ' }] })), + ).toEqual([]); + }); +}); + +describe('readDraftChecks (objectstack#34818)', () => { + it('reads only the flow drafts, as drafts, in their package, stating the console language', async () => { + const fetchImpl = fetchReturning(() => + draftRead({ valid: true, errors: [], warnings: [{ path: 'nodes.1', message: ADVISORY_ZH }] }), + ); + const checks = await readDraftChecks( + [ + { type: 'object', name: 'meeting', packageId: 'app.minutes' }, + { type: 'flow', name: 'xin_huiyi_tixing', packageId: 'app.minutes' }, + ], + { language: 'zh-CN', fetchImpl }, + ); + expect(fetchImpl).toHaveBeenCalledTimes(1); + const [url, init] = fetchImpl.mock.calls[0] as [string, RequestInit]; + expect(url).toBe('/api/v1/meta/flow/xin_huiyi_tixing?state=draft&package=app.minutes'); + expect((init.headers as Record)['Accept-Language']).toBe('zh-CN'); + expect(checks.map((c) => c.message)).toEqual([ADVISORY_ZH]); + }); + + it('states no language when the console has none to state', async () => { + const fetchImpl = fetchReturning(() => draftRead(undefined)); + await readDraftChecks([{ type: 'flow', name: 'f', packageId: null }], { fetchImpl }); + const [url, init] = fetchImpl.mock.calls[0] as [string, RequestInit]; + expect(url).toBe('/api/v1/meta/flow/f?state=draft'); + expect(init.headers as Record).not.toHaveProperty('Accept-Language'); + }); + + it('a failed or thrown read is "no checks", never a failure', async () => { + expect( + await readDraftChecks([{ type: 'flow', name: 'f', packageId: null }], { + fetchImpl: fetchReturning(() => ({}), 500), + }), + ).toEqual([]); + const throwing = vi.fn(async () => { + throw new Error('offline'); + }) as unknown as typeof fetch; + expect(await readDraftChecks([{ type: 'flow', name: 'f', packageId: null }], { fetchImpl: throwing })).toEqual([]); + }); +}); diff --git a/ui/packages/app-shell/src/preview/flowDraftChecks.ts b/ui/packages/app-shell/src/preview/flowDraftChecks.ts new file mode 100644 index 00000000000..c0de4e1eabd --- /dev/null +++ b/ui/packages/app-shell/src/preview/flowDraftChecks.ts @@ -0,0 +1,122 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * What a flow draft's publish would still say, read before the publish + * (objectstack#34818, item 1). + * + * The flow designer's Problems tab already lists a draft's `_diagnostics` + * (`ResourceEditPage` keeps them from each draft read). Since #34818 the + * server folds the publish gate's ADVISORIES into a flow draft's read too + * (`withPublishAdvisories`, `@objectstack/metadata-protocol`), each warning + * worded for the builder in the request's language. This module reads those + * same warnings for the pending-changes sheet, so the sheet names them beside + * the Publish button instead of a toast naming them after it. + * + * ## The server is the one author of the text + * + * Nothing here re-runs a rule or rewords a finding: the message is the + * server's, rendered as sent. The request states the console's language + * (`Accept-Language`), which is how the read door picks the sentence's locale + * (`userTextLocalesOf`); the sheet's other reads are plain `fetch` calls that + * state none, so this one says it itself. + * + * ## It reports; it never blocks + * + * Same stance as `securityPostureLint.ts`: a read that fails yields no checks, + * and nothing here touches the Publish button. + * + * Kept apart from the panel and free of React so the read and the projection + * can be exercised directly. + */ + +/** The draft types whose read carries the publish gate's advisories (the server's `DRAFT_ADVISORY_TYPES`). */ +export const DRAFT_CHECK_TYPES: ReadonlySet = new Set(['flow']); + +/** The part of a pending-changes entry this read needs. */ +export interface DraftCheckTarget { + type: string; + name: string; + packageId: string | null; + member?: string; +} + +/** One thing the publish would still say about one draft. */ +export interface DraftCheck { + type: string; + name: string; + /** `error` = the publish would refuse it; `warning` = an advisory it would report. */ + severity: 'error' | 'warning'; + /** The server's sentence, as sent. */ + message: string; + /** Item-relative path (`nodes.1`), when the server gave one. */ + path?: string; +} + +interface ServedIssue { + path?: unknown; + message?: unknown; +} + +function issuesOf(list: unknown): Array<{ message: string; path?: string }> { + if (!Array.isArray(list)) return []; + const out: Array<{ message: string; path?: string }> = []; + for (const raw of list as ServedIssue[]) { + if (!raw || typeof raw.message !== 'string' || raw.message.trim() === '') continue; + out.push({ + message: raw.message, + ...(typeof raw.path === 'string' && raw.path !== '' ? { path: raw.path } : {}), + }); + } + return out; +} + +/** + * The `_diagnostics` a draft read served, projected to checks: errors first, + * then warnings, each in the order served. A body with no `_diagnostics` + * yields none. + */ +export function draftChecksOf(target: Pick, payload: unknown): DraftCheck[] { + if (!payload || typeof payload !== 'object') return []; + const p = payload as Record; + const body = p.item && typeof p.item === 'object' ? (p.item as Record) : p; + const diagnostics = body._diagnostics; + if (!diagnostics || typeof diagnostics !== 'object') return []; + const d = diagnostics as { errors?: unknown; warnings?: unknown }; + const at = { type: target.type, name: target.name }; + return [ + ...issuesOf(d.errors).map((i) => ({ ...at, severity: 'error' as const, ...i })), + ...issuesOf(d.warnings).map((i) => ({ ...at, severity: 'warning' as const, ...i })), + ]; +} + +/** + * Read every flow draft among `drafts` and return what its publish would still + * say. One read per flow draft; a draft whose read fails contributes nothing. + */ +export async function readDraftChecks( + drafts: readonly DraftCheckTarget[], + opts: { language?: string; fetchImpl?: typeof fetch } = {}, +): Promise { + const doFetch = opts.fetchImpl ?? globalThis.fetch; + const targets = drafts.filter((d) => DRAFT_CHECK_TYPES.has(d.type)); + const perDraft = await Promise.all( + targets.map(async (target) => { + const params = ['state=draft']; + if (target.packageId) params.push(`package=${encodeURIComponent(target.packageId)}`); + if (target.member) params.push(`member=${encodeURIComponent(target.member)}`); + const headers: Record = { Accept: 'application/json' }; + if (opts.language) headers['Accept-Language'] = opts.language; + try { + const res = await doFetch( + `/api/v1/meta/${encodeURIComponent(target.type)}/${encodeURIComponent(target.name)}?${params.join('&')}`, + { credentials: 'include', headers, cache: 'no-store' }, + ); + if (!res.ok) return []; + return draftChecksOf(target, await res.json()); + } catch { + return []; + } + }), + ); + return perDraft.flat(); +} diff --git a/ui/packages/app-shell/src/preview/publishChecksShown.ts b/ui/packages/app-shell/src/preview/publishChecksShown.ts new file mode 100644 index 00000000000..cab382e0920 --- /dev/null +++ b/ui/packages/app-shell/src/preview/publishChecksShown.ts @@ -0,0 +1,43 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Which publishes the author reviewed the publish checks for, right before + * pressing Publish (objectstack#34818, item 1: 「发布抽屉里同样列出,用户确认后再 + * 发布。发布后的提示只留一句结果」). + * + * The pending-changes sheet (`flowDraftChecks.ts`) and the flow designer's + * Problems tab list what a flow draft's publish will report. When the author + * publishes from one of them, the post-publish advisory toast repeating those + * findings as a block of text says nothing new, so it keeps its one title line + * (`providers/saveAdvisoryToast.ts`). A publish the author did NOT review — + * one an AI surface performs, or a sheet that listed nothing for that item — + * keeps the full body, because that toast is then the only place the findings + * reach them. + * + * A surface marks an item while its publish is in flight and clears the mark + * when it is done, so a mark never outlives the publish it describes. + * Module state, because the toast is raised from the metadata client's + * advisory listener, which knows the item but not the surface that published + * it. + */ + +const shown = new Set(); + +function keyOf(type: string, name: string, member?: string): string { + return JSON.stringify([type, name, member ?? null]); +} + +/** Mark that the author has just been shown this item's publish checks. */ +export function markPublishChecksShown(type: string, name: string, member?: string): void { + shown.add(keyOf(type, name, member)); +} + +/** Clear the mark (the publish settled, or the surface closed). */ +export function clearPublishChecksShown(type: string, name: string, member?: string): void { + shown.delete(keyOf(type, name, member)); +} + +/** Whether the author was shown this item's publish checks before this publish. */ +export function werePublishChecksShown(type: string, name: string, member?: string): boolean { + return shown.has(keyOf(type, name, member)); +} diff --git a/ui/packages/app-shell/src/providers/saveAdvisoryToast.test.ts b/ui/packages/app-shell/src/providers/saveAdvisoryToast.test.ts index 4b2a338a5c6..85419650ecf 100644 --- a/ui/packages/app-shell/src/providers/saveAdvisoryToast.test.ts +++ b/ui/packages/app-shell/src/providers/saveAdvisoryToast.test.ts @@ -22,6 +22,7 @@ import { describe, it, expect, vi } from 'vitest'; import type { MetadataSaveAdvisoryEvent } from '@object-ui/data-objectstack'; import { emitSaveAdvisories, type TranslateFn } from './saveAdvisoryToast'; +import { clearPublishChecksShown, markPublishChecksShown } from '../preview/publishChecksShown'; /** i18next-shaped `t` that renders the inline default with its holes filled. */ const t: TranslateFn = (key, options) => { @@ -289,3 +290,50 @@ describe('emitSaveAdvisories — the door union is handled exhaustively', () => } }); }); + +/** + * objectstack#34818 item 1 — 「发布后的提示只留一句结果」. A publish whose + * checks the author just reviewed (the pending-changes sheet or the flow + * designer's Problems tab listed them) keeps the title line alone; every other + * publish keeps the body, because there the toast is the only place the + * findings reach the author. + */ +describe('emitSaveAdvisories — a publish whose checks were reviewed (objectstack#34818)', () => { + const reviewed = (run: () => void) => { + markPublishChecksShown('flow', 'nightly_purge'); + try { + run(); + } finally { + clearPublishChecksShown('flow', 'nightly_purge'); + } + }; + + it('keeps the one title line, on the same tier and duration', () => { + const sink = makeSink(); + reviewed(() => emitSaveAdvisories(event({ door: 'publish' }), t, sink)); + expect(sink.warning).toHaveBeenCalledTimes(1); + const [title, opts] = sink.warning.mock.calls[0]!; + expect(title).toContain('Published'); + expect(opts?.description).toBeUndefined(); + expect(opts!.duration).toBeGreaterThanOrEqual(10_000); + expect(sink.error).not.toHaveBeenCalled(); + }); + + it('CONTROL: the same publish, not reviewed, keeps the body', () => { + const sink = makeSink(); + emitSaveAdvisories(event({ door: 'publish' }), t, sink); + expect(sink.warning.mock.calls[0]![1]!.description).toContain(FINDING.message); + }); + + it('CONTROL: the save door keeps the body even for a reviewed item', () => { + const sink = makeSink(); + reviewed(() => emitSaveAdvisories(event({ door: 'save' }), t, sink)); + expect(sink.warning.mock.calls[0]![1]!.description).toContain(FINDING.message); + }); + + it('CONTROL: another item published alongside keeps its body', () => { + const sink = makeSink(); + reviewed(() => emitSaveAdvisories(event({ door: 'publish', name: 'other_flow' }), t, sink)); + expect(sink.warning.mock.calls[0]![1]!.description).toContain(FINDING.message); + }); +}); diff --git a/ui/packages/app-shell/src/providers/saveAdvisoryToast.ts b/ui/packages/app-shell/src/providers/saveAdvisoryToast.ts index d296f320745..6378163b6ff 100644 --- a/ui/packages/app-shell/src/providers/saveAdvisoryToast.ts +++ b/ui/packages/app-shell/src/providers/saveAdvisoryToast.ts @@ -47,6 +47,7 @@ import type { MetadataSaveAdvisoryEvent } from '@object-ui/data-objectstack'; import type { TranslateFn } from '@object-ui/i18n'; +import { werePublishChecksShown } from '../preview/publishChecksShown.js'; /** * i18next's `t`, narrowed to what this module uses — RE-EXPORTED from its one @@ -181,6 +182,10 @@ export function emitSaveAdvisories( ): void { if (!ev.advisories || ev.advisories.length === 0) return; + if (listedBeforePublish(ev)) { + sink.warning(advisoryTitle(ev, t), { duration: ADVISORY_TOAST_MS }); + return; + } sink.warning( advisoryTitle(ev, t), { @@ -189,3 +194,16 @@ export function emitSaveAdvisories( }, ); } + +/** + * Whether the author reviewed these findings right before this publish + * (objectstack#34818): the pending-changes sheet or the flow designer's + * Problems tab listed them, worded for the builder, and the author published + * from there (`preview/publishChecksShown.ts`). Repeating them as a block of + * text after the publish says nothing new, so the toast keeps its one title + * line. Every other publish, and the save door, keep the full body: there the + * toast is the only place the findings reach the author. + */ +function listedBeforePublish(ev: MetadataSaveAdvisoryEvent): boolean { + return ev.door === 'publish' && werePublishChecksShown(ev.type, ev.name, ev.member); +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx index ced68c5de4e..bc937a60f94 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx @@ -172,6 +172,7 @@ import { useRegisterUnsavedEdits } from '../../chrome/unsavedEdits.js'; import { useNavigationWrites } from '../../hooks/useNavigationSync.js'; import { RefusalMessage } from '../../components/RefusalMessage.js'; import { authoredBuffer, authoredPublished, editsAuthoredLayers, type AuthoredLayers } from './authoredObjectBuffer.js'; +import { clearPublishChecksShown, markPublishChecksShown } from '../../preview/publishChecksShown.js'; /** What an environment section is handed: the item's name and its definition on screen. */ interface EnvironmentSectionProps { @@ -2318,10 +2319,20 @@ function MetadataResourceEditPageImpl({ // objectstack#28680 — whether this publish is the item's first: before // it, the item held no layer at all (its body lived only in the draft). const firstPublish = holdsNoLayer(layered); - await client.publish(type, name, { - ...(activePackage ? { packageId: activePackage } : {}), - ...memberScope, - }); + // objectstack#34818 — a flow whose Problems tab is listing the draft's + // publish checks: the author has read them, so the post-publish toast + // keeps its one title line (`publishChecksShown.ts`). Marked for this + // publish's flight only. + const reviewedChecks = type === 'flow' && (draftDiagnostics?.warnings?.length ?? 0) > 0; + if (reviewedChecks) markPublishChecksShown(type, name); + try { + await client.publish(type, name, { + ...(activePackage ? { packageId: activePackage } : {}), + ...memberScope, + }); + } finally { + if (reviewedChecks) clearPublishChecksShown(type, name); + } // objectui#11773 — the draft is re-read at the address the next save // writes, so its answer pins that save (see the load effect). const [lay, draftRead] = await Promise.all([ diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 6c1b37e4d93..553ea9145a3 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -5255,6 +5255,7 @@ const ar = { securityBlockTitle_many: 'سيتم رفض النشر — {{count}} عنصرًا بحاجة إلى قرار أولاً', securityBlockTitle_other: 'سيتم رفض النشر — {{count}} عنصر بحاجة إلى قرار أولاً', securityBlockWhere: 'أصلحه في الكائن ضمن الإعدادات ← مشاركة السجلات، ثم انشر مرة أخرى.', + flowChecksTitle: 'قبل النشر: سيُبلغ فحص النشر عمّا يلي', securityRule: { owdUnset: 'لم يُعرَّف أساس مشاركة السجلات (sharingModel). يعود وقت التشغيل إلى private، لكن يجب أن يكون الأساس قرارًا صريحًا.', owdAlias: 'أساس مشاركة السجلات (sharingModel) ليس قيمة قياسية، لذا يعامل وقت التشغيل الكائن على أنه private.', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index e13a0334a49..b463eb9be16 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -4702,6 +4702,7 @@ const de = { securityBlockTitle_one: 'Veröffentlichen wird abgelehnt — {{count}} Element benötigt zuerst eine Entscheidung', securityBlockTitle_other: 'Veröffentlichen wird abgelehnt — {{count}} Elemente benötigen zuerst eine Entscheidung', securityBlockWhere: 'Korrigieren Sie es am Objekt unter Einstellungen → Datensatzfreigabe und veröffentlichen Sie erneut.', + flowChecksTitle: 'Vor dem Veröffentlichen: Die Veröffentlichungsprüfung meldet Folgendes', securityRule: { owdUnset: 'Es ist keine Basis für die Datensatzfreigabe (sharingModel) deklariert. Die Laufzeit greift auf private zurück, aber die Basis muss eine bewusste Entscheidung sein.', owdAlias: 'Die Basis für die Datensatzfreigabe (sharingModel) ist kein kanonischer Wert, daher behandelt die Laufzeit das Objekt als private.', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 05de0782a93..c58c27deaed 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -4298,6 +4298,7 @@ const en = { securityBlockTitle_one: 'Publishing will be refused — {{count}} item needs a decision first', securityBlockTitle_other: 'Publishing will be refused — {{count}} items need a decision first', securityBlockWhere: 'Fix it on the object under Settings → Record sharing, then publish again.', + flowChecksTitle: 'Before you publish — the publish check will report these', // The pre-publish security rows, by the rule id of the finding (DraftChangesPanel `SECURITY_RULE_TEXT`). securityRule: { owdUnset: 'No record-sharing baseline (sharingModel) is declared. The runtime falls back to private, but the baseline must be an authored decision.', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 29a924f63e9..1660b4088ec 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -4841,6 +4841,7 @@ const es = { securityBlockTitle_many: 'La publicación será rechazada: {{count}} de elementos necesitan una decisión primero', securityBlockTitle_other: 'La publicación será rechazada: {{count}} elementos necesitan una decisión primero', securityBlockWhere: 'Corríjalo en el objeto en Configuración → Uso compartido de registros y vuelva a publicar.', + flowChecksTitle: 'Antes de publicar: la comprobación de publicación señalará lo siguiente', securityRule: { owdUnset: 'No se ha declarado la base de uso compartido de registros (sharingModel). El entorno de ejecución usa private, pero la base debe ser una decisión explícita.', owdAlias: 'La base de uso compartido de registros (sharingModel) no es un valor canónico, así que el entorno de ejecución trata el objeto como private.', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index d8267583b7a..442411bf9ad 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -4837,6 +4837,7 @@ const fr = { securityBlockTitle_many: 'La publication sera refusée — {{count}} d’éléments nécessitent d’abord une décision', securityBlockTitle_other: 'La publication sera refusée — {{count}} éléments nécessitent d’abord une décision', securityBlockWhere: 'Corrigez-le sur l’objet dans Paramètres → Partage d’enregistrements, puis publiez à nouveau.', + flowChecksTitle: 'Avant de publier : la vérification de publication signalera ceci', securityRule: { owdUnset: 'Aucune base de partage des enregistrements (sharingModel) n’est déclarée. L’exécution se rabat sur private, mais la base doit être une décision explicite.', owdAlias: 'La base de partage des enregistrements (sharingModel) n’est pas une valeur canonique : l’exécution traite donc l’objet comme private.', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 69b4c36ae06..1d122fc6108 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -4704,6 +4704,7 @@ const ja = { securityBlockTitle_one: '公開は拒否されます — {{count}} 件の項目に先に決定が必要です', securityBlockTitle_other: '公開は拒否されます — {{count}} 件の項目に先に決定が必要です', securityBlockWhere: 'オブジェクトの「設定 → レコード共有」で修正してから、もう一度公開してください。', + flowChecksTitle: '公開する前に確認してください — 公開チェックが次の点を指摘します', securityRule: { owdUnset: 'レコード共有のベースライン(sharingModel)が宣言されていません。ランタイムは private として扱いますが、ベースラインは明示的に決める必要があります。', owdAlias: 'レコード共有のベースライン(sharingModel)が正規の値ではないため、ランタイムはこのオブジェクトを private として扱います。', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index a390244a8b2..c6fd6b84c6e 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -4701,6 +4701,7 @@ const ko = { securityBlockTitle_one: '게시가 거부됩니다 — {{count}}개 항목에 먼저 결정이 필요합니다', securityBlockTitle_other: '게시가 거부됩니다 — {{count}}개 항목에 먼저 결정이 필요합니다', securityBlockWhere: '객체의 설정 → 레코드 공유에서 수정한 후 다시 게시하세요.', + flowChecksTitle: '게시하기 전에 확인하세요 — 게시 검사에서 다음 사항을 알립니다', securityRule: { owdUnset: '레코드 공유 기준(sharingModel)이 선언되지 않았습니다. 런타임은 private로 처리하지만 기준은 명시적으로 결정해야 합니다.', owdAlias: '레코드 공유 기준(sharingModel)이 정식 값이 아니므로 런타임은 이 개체를 private로 처리합니다.', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index e229bb8cb57..3aa746e63db 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -4836,6 +4836,7 @@ const pt = { securityBlockTitle_many: 'A publicação será recusada — {{count}} de itens precisam de uma decisão primeiro', securityBlockTitle_other: 'A publicação será recusada — {{count}} itens precisam de uma decisão primeiro', securityBlockWhere: 'Corrija no objeto em Configurações → Compartilhamento de registros e publique novamente.', + flowChecksTitle: 'Antes de publicar: a verificação de publicação vai apontar o seguinte', securityRule: { owdUnset: 'Nenhuma base de compartilhamento de registros (sharingModel) foi declarada. O runtime usa private, mas a base precisa ser uma decisão explícita.', owdAlias: 'A base de compartilhamento de registros (sharingModel) não é um valor canônico, então o runtime trata o objeto como private.', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 2b96fe82ee3..08f313e4986 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -4989,6 +4989,7 @@ const ru = { securityBlockTitle_many: 'Публикация будет отклонена — {{count}} элементов требуют решения', securityBlockTitle_other: 'Публикация будет отклонена — {{count}} элемента требуют решения', securityBlockWhere: 'Исправьте это в объекте в разделе «Настройки → Общий доступ к записям» и опубликуйте снова.', + flowChecksTitle: 'Перед публикацией: проверка публикации сообщит следующее', securityRule: { owdUnset: 'Базовый уровень общего доступа к записям (sharingModel) не объявлен. Среда выполнения использует private, но базовый уровень должен быть осознанным решением.', owdAlias: 'Базовый уровень общего доступа к записям (sharingModel) — неканоническое значение, поэтому среда выполнения считает объект private.', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index f3936cb8be0..b79b1e0af07 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -3682,6 +3682,7 @@ const zh = { securityBlockTitle_one: '发布会被拒绝 —— 有 {{count}} 项需要先做出决定', securityBlockTitle_other: '发布会被拒绝 —— 有 {{count}} 项需要先做出决定', securityBlockWhere: '请在对象的“设置 → 记录共享模型”中修改后重新发布。', + flowChecksTitle: '发布前请先看 —— 发布检查会提出以下几点', securityRule: { owdUnset: '未声明记录共享模型(sharingModel)。运行时会按 private 处理,但这个基线必须是明确做出的决定。', owdAlias: '记录共享模型(sharingModel)不是规范取值,运行时会按 private 处理此对象。', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index bb963982c9f..12876cb0990 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -3682,6 +3682,7 @@ const zhHant = { securityBlockTitle_one: '釋出會被拒絕 —— 有 {{count}} 項需要先做出決定', securityBlockTitle_other: '釋出會被拒絕 —— 有 {{count}} 項需要先做出決定', securityBlockWhere: '請在物件的“設定 → 記錄共享模型”中修改後重新發布。', + flowChecksTitle: '釋出前請先看 —— 釋出檢查會提出以下幾點', securityRule: { owdUnset: '未宣告記錄共享模型(sharingModel)。執行環境會按 private 處理,但這個基線必須是明確做出的決定。', owdAlias: '記錄共享模型(sharingModel)不是規範取值,執行環境會按 private 處理此物件。',