diff --git a/.changeset/34818-flow-designer-rest.md b/.changeset/34818-flow-designer-rest.md new file mode 100644 index 00000000000..b85667bc43c --- /dev/null +++ b/.changeset/34818-flow-designer-rest.md @@ -0,0 +1,15 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(flow designer): add variables, say why Runs is empty, Debug takes the side column, and autosave reads 已保存 in the header + +Clause-②: no +Metadata-protocol: none + +- **Variables can be added and edited.** The Variables tab says what variables are for and has an **Add variable** button. Each row edits its name, type, default value, input and output. A `$` name, a blank name or a duplicate is held with a note. A variable a step still reads cannot be renamed or removed until those steps change, and the note names them. A read-only package keeps the plain list. +- **Runs says why it is empty.** A flow that has never been published reads 「发布并启用后,这里显示每次运行的记录」 and fetches nothing. A published flow whose automation engine does not answer says so, and only that. +- **Debug takes the side column.** While Debug is open the simulator is drawn where the Configuration was: in Studio's right panel, or, where the page keeps its own side column, at that column's width beside the canvas. Leaving Debug brings the Configuration back with the same selection. +- **Autosave reads 已保存 in the header.** A landed flow autosave no longer raises a "Draft saved" toast. The header's 正在保存 settles into 已保存, which names the flow to screen readers and stays until the next edit. A failed save keeps its message and also raises one error toast. Other Studio editors keep their toast. +- **The node panel reads Chinese throughout.** The decision's branching mode, the approval's resolve-as, group and empty-approvers settings, the help the server sends for each approver column, exclude-submitter, backup approvers and the escalation settings, and the prose placeholders are translated, and quorum and per-group sign-off read 法定人数 and 分组会签. The approvers help says the approve and reject connections come with the node. diff --git a/ui/packages/app-shell/src/views/metadata-admin/i18n.ts b/ui/packages/app-shell/src/views/metadata-admin/i18n.ts index 983df23be2c..d2aa99cef88 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/i18n.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/i18n.ts @@ -210,12 +210,14 @@ export { isZhLocale, translateSchemaFieldLabel, translateSchemaFieldHelp } from interface FlowFieldZh { label?: string; help?: string; + /** objectstack#34818 — a PROSE placeholder only; example literals stay English. */ + placeholder?: string; /** The field's `unsetNotice` (objectui#11054). */ unsetNotice?: string; /** select option value → zh label. */ opts?: Record; - /** objectList column key → zh label (+ nested option labels). */ - cols?: Record }>; + /** objectList column key → zh label (+ help, prose placeholder, nested option labels). */ + cols?: Record }>; } /** @@ -227,6 +229,62 @@ interface FlowFieldZh { * to its English label, so plugin nodes stay readable. Placeholders (example * literals like cron strings / URLs) are intentionally left in English. */ +/** + * The approver row's columns, shared by an approval's `approvers` and its + * `fallbackApprovers` (the same `ApprovalNodeApproverSchema`). objectstack#34818: + * the column help the server serves (the spec's descriptions) read English in + * the zh panel; each is said here in the admin's words. + */ +const APPROVER_COLS_ZH: NonNullable = { + type: { + label: '类型', + help: + '这一步如何找到审批人。尽量选组织里的角色(上级、岗位、部门、团队),不要选某个具体的人 —— 人可能离职,换一个环境也可能不存在。' + + '「上级」要等管理员在用户目录里登记了每个人的上级才能找到人;在此之前找不到任何人,请求按本节点「没有解析出审批人时」的设置处理。' + + '「平台管理员」只用于部署自带的打包流程,这里保存的流程不能使用。', + opts: { + user: '用户', + position: '岗位', + org_membership_level: '组织成员(所有者 / 管理员 / 成员)', + team: '团队', + department: '部门', + manager: '上级', + field: '字段', + queue: '队列', + expression: '表达式(CEL)', + platform_admin: '平台管理员', + }, + }, + value: { + label: '值', + help: + '按所选类型填写具体是谁:用户、成员级别、岗位、团队、部门或队列,或保存审批人的记录字段。「上级」留空。' + + '「表达式」填写返回审批人的 CEL 表达式,可读取 `current.*`、`trigger.*` 和 `vars.*`。', + placeholder: '按“类型”填写:用户、组织成员级别、岗位、团队、部门或字段', + }, + resolveAs: { + label: '解析为', + help: '仅用于「表达式」:表达式的结果代表什么。默认每个结果是一个人;选部门、岗位或团队,则其全部成员都是审批人。', + opts: { + user: '用户 ID(默认)', + department: '部门 ID → 部门成员', + position: '岗位名称 → 任职人员', + team: '团队 ID → 团队成员', + }, + }, + group: { + label: '分组', + help: '分组会签的组名:同名的审批人为一组,这一步需要每一组都通过(如「法务」「财务」)。仅在审批方式为「分组会签」时读取。', + placeholder: '如 法务 / 财务 —— 用于分组会签', + }, + organization: { + label: '所属组织', + help: + '到同一集团的另一个组织里找这个审批人,而不是请求所在的组织,例如由集团 CFO 审批某个工厂的采购单。留空则用请求所在的组织。' + + '填 `$root` 表示集团顶层,`$parent` 表示上一级,或填写组织的标识。', + }, +}; + const FLOW_FIELD_ZH: Record> = { start: { triggerType: { @@ -293,9 +351,23 @@ const FLOW_FIELD_ZH: Record> = { conditions: { label: '分支', help: '每个分支包含标签、CEL 表达式和目标节点。表达式为 “true” 的分支即默认 / else 路径。选择目标会接线该分支的出边(创建或更新),清空则断开该边。', - cols: { label: { label: '标签' }, expression: { label: '表达式' }, target: { label: '目标节点' } }, + cols: { + label: { + label: '标签', + help: '分支的标签;成立的分支沿同名标签的出边继续(都不成立时走标为默认、或标签为 default 的出边)。', + placeholder: '如 有商机', + }, + expression: { label: '表达式', help: '决定是否走这个分支的 CEL 条件(不加 {{ }})。' }, + target: { label: '目标节点', placeholder: '下一个节点' }, + }, }, condition: { label: '单一条件', help: '旧的单分支条件(CEL)。建议使用上方“分支”;每条边的条件也可写在出边上。' }, + // objectstack#34818 — was English in the zh panel. + mode: { + label: '分支方式', + help: '按出边条件分支时:「只走一条」按连线顺序只走第一条成立的连线(不设置即为此方式);「走所有成立的」走每一条成立的连线。都不成立时走默认连线。不能与上方“分支”同时使用。', + opts: { exclusive: '只走一条', inclusive: '走所有成立的' }, + }, }, assignment: { assignments: { label: '赋值', help: '设置变量:每个键为一个变量,值为表达式或字面量。' }, @@ -391,24 +463,8 @@ const FLOW_FIELD_ZH: Record> = { approval: { approvers: { label: '审批人', - help: '谁可以处理此步骤。为节点的出边打上 “approve” 和 “reject” 标签。', - cols: { - type: { - label: '类型', - opts: { - user: '用户', - position: '岗位', - org_membership_level: '组织成员(所有者 / 管理员 / 成员)', - team: '团队', - department: '部门', - manager: '上级', - field: '字段', - queue: '队列', - }, - }, - value: { label: '值' }, - group: { label: '分组' }, - }, + help: '谁可以处理此步骤。插入审批节点时会自带「通过」和「驳回」两条连线;请保留这两条,缺任一条时「问题」页签会提示。', + cols: APPROVER_COLS_ZH, }, behavior: { label: '审批方式', @@ -420,23 +476,54 @@ const FLOW_FIELD_ZH: Record> = { per_group: '分组会签(每组签核)', }, }, - minApprovals: { label: '最少审批数', help: '所需审批数 —— quorum 为总数,per_group 为每组。服务端会做钳制以防死锁。' }, + minApprovals: { label: '最少审批数', help: '所需审批数 —— 「法定人数」方式下为总数,「分组会签」方式下为每组的数量。服务端会做钳制以防死锁。' }, lockRecord: { label: '锁定记录', help: '此节点待处理期间锁定触发记录,禁止编辑。' }, approvalStatusField: { label: '状态字段', help: '将请求状态(待审 / 通过 / 拒绝)镜像到的业务对象字段。应为只读。', }, 'escalation.enabled': { label: 'SLA 升级', help: '在超时内未做决策时升级。' }, - 'escalation.timeoutHours': { label: '超时(小时)' }, + 'escalation.timeoutHours': { + label: '超时(小时)', + help: '请求最多等多少小时后执行升级。按日历小时计算,夜间、周末和节假日都算在内;平台没有工作时间日历:周五 17:00 发起、设为 4 小时的请求会在当天 21:00 升级。', + }, 'escalation.action': { label: '超时动作', + help: '超过期限后怎么办:改派给其他人、自动通过、自动拒绝,或通知某人(默认)。', opts: { notify: '通知', reassign: '改派', auto_approve: '自动通过', auto_reject: '自动拒绝' }, }, - 'escalation.escalateTo': { label: '升级至' }, - 'escalation.notifySubmitter': { label: '通知提交人' }, + 'escalation.escalateTo': { + label: '升级至', + help: '超过期限后由谁接手或接到通知:通常是一个岗位,也可以是具体的人。填写岗位名称或 position:<名称>、用户 ID 或邮箱。不接受 team:、department:、org_membership_level: 或 role: 这类地址,因为没有审批人以它们的身份处理。', + placeholder: '岗位名称或用户 ID', + }, + 'escalation.notifySubmitter': { label: '通知提交人', help: '升级时通知提交请求的人。' }, maxRevisions: { label: '最多退回次数', - help: '请求自动拒绝前的最多退回修订次数(0 表示禁用退回)。需要一条 “revise” 出边才生效。', + help: '请求自动拒绝前的最多退回修订次数(0 表示禁用退回)。需要一条审批分支为「退回修改」的出边才生效。', + }, + // objectstack#34818 — was English in the zh panel. + onEmptyApprovers: { + label: '没有解析出审批人时', + help: '进入节点时解析出的审批人为空怎么办。「自动通过」会让记录直接放行,请确认确实需要再选。', + opts: { + admin_rescue: '等待管理员接手(默认)', + fail: '节点失败(配置有误)', + auto_approve: '自动通过(直接放行!)', + fallback: '交给备用审批人', + }, + }, + excludeSubmitter: { + label: '排除提交人', + help: + '防止自己审批自己的请求:开启后,不论审批人是怎样找到的,提交人都会从这一步的审批人中去掉。' + + '去掉后如果没人了,请求按「没有解析出审批人时」的设置处理(默认交给组织管理员,或交给你指定的备用审批人),绝不会自动通过,审批记录会写明原因。' + + '因此不能与「自动通过」同时选择。默认关闭。', + }, + fallbackApprovers: { + label: '备用审批人', + help: '这一步找不到其他审批人时,由这些人决定。仅在「没有解析出审批人时」选择「交给备用审批人」时读取。', + cols: APPROVER_COLS_ZH, }, }, wait: { diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-node-config.ts b/ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-node-config.ts index 5b743cf5596..6652bf1acdc 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-node-config.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-node-config.ts @@ -1004,7 +1004,9 @@ const FLOW_NODE_CONFIG: Record = { // nodes wired to its `approve` / `reject` out-edges). approval: [ cfg('approvers', 'Approvers', 'objectList', { - help: 'Who may act on this step. Wire the node’s out-edges with labels "approve" and "reject".', + // objectstack#34818 — the designer inserts the node with its `approve` + // and `reject` out-edges, and Problems names one that goes missing. + help: 'Who may act on this step. The node comes with an "approve" and a "reject" connection; keep both, or the Problems tab reports the missing one.', columns: [ { key: 'type', @@ -1508,14 +1510,19 @@ function withUnmappedDeclaredKeys( return out; } -/** Overlay a column's zh label / option labels (English is the fallback). */ +/** Overlay a column's zh label / help / option labels (English is the fallback). */ function localizeColumn( col: FlowConfigColumn, - cz: { label?: string; opts?: Record } | undefined, + cz: { label?: string; help?: string; placeholder?: string; opts?: Record } | undefined, ): FlowConfigColumn { if (!cz) return col; const out: FlowConfigColumn = { ...col }; if (cz.label) out.label = cz.label; + // objectstack#34818 — the served column help (the spec's description). + if (cz.help) out.help = cz.help; + // objectstack#34818 — only a column the zh table names a placeholder for: + // a prose hint, never an example literal. + if (col.placeholder && cz.placeholder) out.placeholder = cz.placeholder; if (col.options && cz.opts) { out.options = col.options.map((o) => ({ ...o, label: cz.opts![o.value] ?? o.label })); } @@ -1533,6 +1540,7 @@ function localizeField(rawType: string, canonicalType: string, field: FlowConfig if (z.label) out.label = z.label; if (z.help) out.help = z.help; if (field.unsetNotice && z.unsetNotice) out.unsetNotice = z.unsetNotice; + if (field.placeholder && z.placeholder) out.placeholder = z.placeholder; if (field.options && z.opts) { out.options = field.options.map((o) => ({ ...o, label: z.opts![o.value] ?? o.label })); } diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-node-config.zhPanel-34818.test.ts b/ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-node-config.zhPanel-34818.test.ts new file mode 100644 index 00000000000..d4b9d1585f0 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-node-config.zhPanel-34818.test.ts @@ -0,0 +1,83 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#34818 item 5 — the decision and approval panels read no English + * in zh-CN: every label, help, option and prose placeholder the inspector + * draws for them goes through the zh table, and the approval words + * `quorum` / `per_group` are said in Chinese. Example literals (a CEL + * expression, a number, a field name) stay as written. en-US is the control: + * the table is a no-op there. + */ + +import { describe, expect, it } from 'vitest'; +import { z } from 'zod'; +import { ApprovalNodeConfigSchema, DecisionConfigSchema } from '@objectstack/spec/automation'; +import { fieldsForNodeType, localizeFlowFields, type FlowConfigField } from './flow-node-config.js'; +import { jsonSchemaToFlowFields } from './json-schema-to-fields.js'; + +const CJK = /[㐀-鿿]/; + +/** Placeholders that are example literals, not prose: left as written on purpose. */ +const LITERAL_PLACEHOLDERS = new Set(['expiring_deals.length > 0', 'amount > 10000', '1', '3', '24', 'approval_status']); + +/** Every visible string of a field, with where it sits. */ +function strings(field: FlowConfigField): Array<[string, string]> { + const out: Array<[string, string]> = [[`${field.id}.label`, field.label]]; + if (field.help) out.push([`${field.id}.help`, field.help]); + if (field.placeholder && !LITERAL_PLACEHOLDERS.has(field.placeholder)) out.push([`${field.id}.placeholder`, field.placeholder]); + for (const o of field.options ?? []) out.push([`${field.id}.opt.${o.value}`, o.label]); + for (const c of field.columns ?? []) { + out.push([`${field.id}.col.${c.key}.label`, c.label]); + if (c.help) out.push([`${field.id}.col.${c.key}.help`, c.help]); + if (c.placeholder && !LITERAL_PLACEHOLDERS.has(c.placeholder)) out.push([`${field.id}.col.${c.key}.placeholder`, c.placeholder]); + for (const o of c.options ?? []) out.push([`${field.id}.col.${c.key}.opt.${o.value}`, o.label]); + } + return out; +} + +describe('zh-CN decision and approval panels (objectstack#34818 item 5)', () => { + it.each(['decision', 'approval'])('every %s string reads Chinese', (type) => { + const english = strings(fieldsForNodeType(type)[0]!).length; // the table is non-empty + expect(english).toBeGreaterThan(0); + const leftEnglish = localizeFlowFields(type, fieldsForNodeType(type), 'zh-CN') + .flatMap(strings) + .filter(([, text]) => !CJK.test(text)); + expect(leftEnglish).toEqual([]); + }); + + // The fields as the engine publishes them online: the installed contract's + // own JSON Schema, whose descriptions are the help (the live panel drew + // `excludeSubmitter`, `fallbackApprovers` and the approver columns' help in + // English before this pin). + it.each([ + ['approval', ApprovalNodeConfigSchema], + ['decision', DecisionConfigSchema], + ] as const)('every served %s string reads Chinese', (type, schema) => { + const served = jsonSchemaToFlowFields(z.toJSONSchema(schema, { io: 'input' }))!; + expect(served.length).toBeGreaterThan(0); + const leftEnglish = localizeFlowFields(type, served, 'zh-CN') + .flatMap(strings) + .filter(([, text]) => !CJK.test(text)); + expect(leftEnglish).toEqual([]); + }); + + it('the approval words are said in Chinese, not as `quorum` / `per_group`', () => { + const all = localizeFlowFields('approval', fieldsForNodeType('approval'), 'zh-CN').flatMap(strings); + expect(all.filter(([, text]) => /quorum|per_group/.test(text))).toEqual([]); + }); + + it('the approvers help says the node comes with both connections', () => { + const [approvers] = localizeFlowFields('approval', fieldsForNodeType('approval'), 'zh-CN'); + expect(approvers!.help).toContain('自带「通过」和「驳回」两条连线'); + const [en] = fieldsForNodeType('approval'); + expect(en!.help).toContain('comes with an "approve" and a "reject" connection'); + expect(en!.help).not.toMatch(/Wire the node/); + }); + + it('control: en-US draws the English table unchanged', () => { + const en = fieldsForNodeType('approval'); + expect(localizeFlowFields('approval', en, 'en-US')).toBe(en); + const mode = fieldsForNodeType('decision').find((f) => f.id === 'mode')!; + expect(mode.label).toBe('Branch mode'); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/FlowPreview.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/FlowPreview.tsx index 09c38b0bd69..59193e721c2 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/FlowPreview.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/FlowPreview.tsx @@ -21,6 +21,7 @@ */ import * as React from 'react'; +import { createPortal } from 'react-dom'; import { resolveFlowTriggerKind } from '@objectstack/spec/automation'; import { AlertCircle, @@ -34,7 +35,6 @@ import { Variable, Zap, } from 'lucide-react'; -import { EmptyDescription } from '@object-ui/components'; import type { MetadataPreviewProps, MetadataSelection } from '../preview-registry.js'; import { PreviewShell, PreviewMessage, PreviewErrorBoundary } from './PreviewShell.js'; import { appendArray } from '../inspectors/_shared.js'; @@ -46,6 +46,7 @@ import { edgeKey, type FlowDesignerEdge, type FlowDesignerNode } from './flow-ca import { NESTED_NODE_KIND, parseNestedNodeId, encodeNestedNodeId, locateFlowNode } from '../inspectors/flow-nested-selection.js'; import { FlowSimulatorPanel } from './FlowSimulatorPanel.js'; import { FlowRunsPanel } from './FlowRunsPanel.js'; +import { FlowVariablesPanel } from './FlowVariablesPanel.js'; import { ProblemsPanel } from './ProblemsPanel.js'; import { FlowRegistrationContext, @@ -109,6 +110,19 @@ export interface FlowPreviewChrome { * state setter (whose identity React keeps), never a fresh closure. */ onProblemsChange: (tally: FlowProblemTally) => void; + /** + * objectstack#34818 — whether the open flow has a published version, as the + * host read it; the Runs body says "publish to see runs" for `false` and + * names the engine alone for `true`. Absent: the host does not know. + */ + published?: boolean; + /** + * objectstack#34818 — where the Debug section's simulator goes when the host + * keeps its right column elsewhere (Studio's right slot): the simulator is + * drawn there, in the Configuration's place, and the section keeps the + * canvas alone. Absent or `null`: the simulator sits beside the canvas. + */ + debugTarget?: HTMLElement | null; } const FlowPreviewChromeContext = React.createContext(null); @@ -547,28 +561,44 @@ export function FlowPreview({ draft, editing, selection, onSelectionChange, onPa // objectui#12454 — the host's item header holds the meta and the tab row, // so the preview draws neither, and no frame: the section fills the body. const section = chrome.section; + const debugTarget = chrome.debugTarget ?? null; const panelBody = section === 'variables' || section === 'runs' || section === 'problems'; return (
{/* Kept mounted under a body section, so its pan, zoom and opened regions are where the author left them when the canvas returns. */}
{canvasEl}
- {section === 'debug' && ( -
- -
- )} + {section === 'debug' && + (debugTarget ? ( + createPortal( +
+ +
, + debugTarget, + ) + ) : ( +
+ +
+ ))} {section === 'variables' && (
- +
)} @@ -576,7 +606,7 @@ export function FlowPreview({ draft, editing, selection, onSelectionChange, onPa
{/* The engine keys runs by the flow's name; the host offers this section only with one. */} - {flowName && } + {flowName && }
)} @@ -718,7 +748,14 @@ export function FlowPreview({ draft, editing, selection, onSelectionChange, onPa
{tr('engine.flowPreview.variables', locale)}
- +
) : null} @@ -789,40 +826,3 @@ function useCutText(ref: React.RefObject, enabled: boolean): return cut; } -/** The flow's declared variables: the designer's side panel, and the Studio's Variables body (objectui#12454). */ -function FlowVariablesList({ variables, locale }: { variables: FlowVariable[]; locale?: string }) { - if (variables.length === 0) { - return {tr('engine.flowPreview.noVars', locale)}; - } - return ( -
    - {variables.map((v, i) => ( -
  • -
    - {v.name} - {v.type && ( - - {v.type} - - )} - {v.isInput && ( - - {tr('engine.flowPreview.varIn', locale)} - - )} - {v.isOutput && ( - - {tr('engine.flowPreview.varOut', locale)} - - )} -
    - {v.defaultValue !== undefined && ( -
    - = {String(v.defaultValue)} -
    - )} -
  • - ))} -
- ); -} diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/FlowRunsPanel.render.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/FlowRunsPanel.render.test.tsx index fa08b6478e1..0ce9f8f6fc4 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/FlowRunsPanel.render.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/FlowRunsPanel.render.test.tsx @@ -144,3 +144,39 @@ describe('FlowRunsPanel (render)', () => { expect(screen.queryByText('failure')).toBeNull(); }); }); + +// objectstack#34818 item 9 — the empty Runs tab says which of its two causes +// holds when the host knows: a flow never published says how runs come to be +// listed and asks the engine nothing; a published flow whose read fails names +// the engine alone. A host that does not know keeps the sentence naming both. +describe('FlowRunsPanel — why the list is empty (objectstack#34818)', () => { + it('an unpublished flow says to publish and turn it on, and fetches nothing', () => { + const fetchSpy = vi.fn(async () => new Response('{}', { status: 200 })); + vi.stubGlobal('fetch', fetchSpy); + render(); + expect(screen.getByTestId('flow-runs-unpublished').textContent).toBe( + 'Publish and turn on this flow, and each of its runs is listed here.', + ); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('a published flow whose read fails names the engine alone', async () => { + vi.stubGlobal('fetch', vi.fn(async () => new Response('down', { status: 503 }))); + render(); + const line = await screen.findByTestId('flow-runs-unavailable'); + expect(line.textContent).toMatch(/automation engine is not answering/); + expect(line.textContent).not.toMatch(/published/); + }); + + it('control: a host that does not know keeps the sentence naming both causes', async () => { + vi.stubGlobal('fetch', vi.fn(async () => new Response('down', { status: 503 }))); + render(); + expect((await screen.findByTestId('flow-runs-unavailable')).textContent).toMatch(/offline or this flow hasn’t been published/); + }); + + it('control: a published flow with no runs still says "No runs yet."', async () => { + vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ data: { runs: [] } }), { status: 200 }))); + render(); + expect(await screen.findByText('No runs yet.')).toBeTruthy(); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/FlowRunsPanel.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/FlowRunsPanel.tsx index c3deacaf7b5..b6a355c8c90 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/FlowRunsPanel.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/FlowRunsPanel.tsx @@ -451,11 +451,20 @@ export function FlowRunsPanel({ flowName, nodes, locale, + published, }: { flowName: string; /** The flow's `nodes`, so a step reads by its node's name (objectui#13143). */ nodes?: readonly unknown[]; locale?: string; + /** + * objectstack#34818 — whether the flow has a published version, as the host + * knows it. `false`: the flow never ran, so the panel says how runs come to + * be listed and asks the engine nothing. `true`: a failed read is the + * engine's alone. Absent (a host that does not know): the one sentence that + * names both causes, as before. + */ + published?: boolean; }) { const names = React.useMemo(() => flowNodeNames(nodes, locale), [nodes, locale]); const [runs, setRuns] = React.useState([]); @@ -463,6 +472,7 @@ export function FlowRunsPanel({ const [reloadKey, setReloadKey] = React.useState(0); React.useEffect(() => { + if (published === false) return; const controller = new AbortController(); let alive = true; setState('loading'); @@ -479,7 +489,20 @@ export function FlowRunsPanel({ alive = false; controller.abort(); }; - }, [flowName, reloadKey]); + }, [flowName, reloadKey, published]); + + if (published === false) { + return ( +
+
+ {tr('engine.flowRuns.title', locale)} +
+ + {tr('engine.flowRuns.unpublished', locale)} + +
+ ); + } return (
@@ -496,8 +519,8 @@ export function FlowRunsPanel({
{state === 'unavailable' ? ( -
- {tr('engine.flowRuns.unavailable', locale)} +
+ {tr(published ? 'engine.flowRuns.engineOffline' : 'engine.flowRuns.unavailable', locale)}
) : state === 'ready' && runs.length === 0 ? ( {tr('engine.flowRuns.empty', locale)} diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/FlowSimulatorPanel.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/FlowSimulatorPanel.tsx index fbbef114421..4442784c47c 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/FlowSimulatorPanel.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/FlowSimulatorPanel.tsx @@ -233,7 +233,9 @@ export function FlowSimulatorPanel({ nodes, edges, variables, locale, onRunState return (
-
+ {/* objectstack#34818 — wraps rather than clips: paused on an approval, + its decision buttons and the status pill outgrow a 300 px column. */} +
diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/FlowVariablesPanel-34818.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/FlowVariablesPanel-34818.test.tsx new file mode 100644 index 00000000000..b3978c1c3a0 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/FlowVariablesPanel-34818.test.tsx @@ -0,0 +1,193 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#34818 item 7 — "Add variable" on the flow's Variables tab. + * + * The panel replaces the read-only list. Every write is the whole + * `variables` array, parsed here with the spec's own `FlowVariableSchema`. + * A name the spec refuses (blank, `$`-led) or one another variable holds is + * held with a note; renaming or removing a variable a step still reads is + * refused with a note naming the steps. Control: without `onPatch` the panel + * is the read-only list, with no add button. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, fireEvent, cleanup, within } from '@testing-library/react'; +import { FlowVariableSchema } from '@objectstack/spec/automation'; +import { FlowVariablesPanel, flowVariableReaders, nextFlowVariableName, type FlowVariableRow } from './FlowVariablesPanel'; +import { t, tFormat } from '../i18n'; +import { loadStudioCatalogue } from '@object-ui/i18n/namespaces/studio'; + +await loadStudioCatalogue('zh'); + +afterEach(cleanup); + +const en = (key: string) => t(key, 'en'); + +const NODES = [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'notify', type: 'notify', label: 'Tell the owner', config: { message: 'Deal {{ amount }} closed' } }, + { id: 'route', type: 'decision', label: 'Big?', config: { conditions: [{ expression: 'amount > 1000' }] } }, + { id: 'end', type: 'end', label: 'End' }, +]; + +/** A host that applies each patch, as the designer's draft does. */ +function Host({ initial, onWrite, nodes = NODES }: { initial: FlowVariableRow[]; onWrite: (v: FlowVariableRow[]) => void; nodes?: typeof NODES }) { + const [variables, setVariables] = React.useState(initial); + return ( + { + onWrite(next); + setVariables(next); + }} + /> + ); +} + +/** Each write parses as the spec's variables. */ +function expectSpecShaped(rows: FlowVariableRow[]) { + for (const row of rows) expect(() => FlowVariableSchema.parse(row), JSON.stringify(row)).not.toThrow(); +} + +const rows = () => screen.queryAllByTestId('flow-variable-row'); +const nameBox = (row: HTMLElement) => within(row).getByRole('textbox', { name: en('engine.flowPreview.vars.name') }); +const note = (row: HTMLElement) => within(row).queryByTestId('flow-variable-note'); + +function rename(row: HTMLElement, value: string) { + const box = nameBox(row); + fireEvent.change(box, { target: { value } }); + fireEvent.blur(box); +} + +describe('the Variables panel adds and edits variables (#34818 item 7)', () => { + it('the empty state says what variables are for, and Add variable writes a spec-shaped text variable', () => { + const onWrite = vi.fn(); + render(); + expect(screen.getByTestId('flow-variables-empty')).toHaveTextContent(en('engine.flowPreview.noVars')); + expect(en('engine.flowPreview.noVars')).toContain('{{ name }}'); + + fireEvent.click(screen.getByRole('button', { name: en('engine.flowPreview.addVariable') })); + expect(onWrite).toHaveBeenLastCalledWith([{ name: 'variable_1', type: 'text' }]); + fireEvent.click(screen.getByRole('button', { name: en('engine.flowPreview.addVariable') })); + expect(onWrite.mock.calls.at(-1)![0].map((v: FlowVariableRow) => v.name)).toEqual(['variable_1', 'variable_2']); + expectSpecShaped(onWrite.mock.calls.at(-1)![0]); + expect(rows()).toHaveLength(2); + }); + + it('edits name, type, default, input and output into one spec-shaped row', () => { + const onWrite = vi.fn(); + render(); + const [row] = rows(); + rename(row, 'discount'); + fireEvent.change(within(row).getByRole('combobox', { name: en('engine.flowPreview.vars.type') }), { target: { value: 'number' } }); + const def = within(row).getByRole('textbox', { name: en('engine.flowPreview.vars.default') }); + fireEvent.change(def, { target: { value: '15' } }); + fireEvent.blur(def); + fireEvent.click(within(row).getByRole('checkbox', { name: en('engine.flowPreview.vars.input') })); + fireEvent.click(within(row).getByRole('checkbox', { name: en('engine.flowPreview.vars.output') })); + const last = onWrite.mock.calls.at(-1)![0] as FlowVariableRow[]; + expect(last).toEqual([{ name: 'discount', type: 'number', defaultValue: 15, isInput: true, isOutput: true }]); + expectSpecShaped(last); + expect(note(row)).toBeNull(); + }); + + it('a default the type cannot hold is held with a note, not written', () => { + const onWrite = vi.fn(); + render(); + const [row] = rows(); + const def = within(row).getByRole('textbox', { name: en('engine.flowPreview.vars.default') }); + fireEvent.change(def, { target: { value: 'many' } }); + fireEvent.blur(def); + expect(note(row)).toHaveTextContent(en('engine.flowPreview.vars.defaultNumber')); + expect(onWrite).not.toHaveBeenCalled(); + }); + + it('refuses a $ name, a blank name and a duplicate, holding the text and writing nothing', () => { + const onWrite = vi.fn(); + render(); + const second = rows()[1]; + rename(second, '$record'); + expect(note(second)).toHaveTextContent(en('engine.flowPreview.vars.nameDollar')); + expect(nameBox(second)).toHaveValue('$record'); + rename(second, ' '); + expect(note(second)).toHaveTextContent(en('engine.flowPreview.vars.nameBlank')); + rename(second, 'a'); + expect(note(second)).toHaveTextContent(tFormat('engine.flowPreview.vars.nameTaken', 'en', { name: 'a' })); + expect(onWrite).not.toHaveBeenCalled(); + // The spec agrees on the $ name. + expect(() => FlowVariableSchema.parse({ name: '$record', type: 'text' })).toThrow(); + }); + + it('refuses to rename or remove a variable a step still reads, naming the steps', () => { + const onWrite = vi.fn(); + render(); + const [amount, unused] = rows(); + rename(amount, 'total'); + expect(note(amount)).toHaveTextContent( + tFormat('engine.flowPreview.vars.renameRead', 'en', { name: 'amount', steps: 'Tell the owner, Big?' }), + ); + fireEvent.click(within(amount).getByRole('button', { name: tFormat('engine.flowPreview.vars.remove', 'en', { name: 'amount' }) })); + expect(note(amount)).toHaveTextContent( + tFormat('engine.flowPreview.vars.removeRead', 'en', { name: 'amount', steps: 'Tell the owner, Big?' }), + ); + expect(onWrite).not.toHaveBeenCalled(); + + // The control: a variable no step reads renames and removes. + rename(unused, 'spare'); + expect(onWrite).toHaveBeenLastCalledWith([{ name: 'amount', type: 'number' }, { name: 'spare', type: 'text' }]); + fireEvent.click(within(rows()[1]).getByRole('button', { name: tFormat('engine.flowPreview.vars.remove', 'en', { name: 'spare' }) })); + expect(onWrite).toHaveBeenLastCalledWith([{ name: 'amount', type: 'number' }]); + }); + + it('keeps an input that declares a record object an input, and its objectName rides along', () => { + const onWrite = vi.fn(); + const lead = { name: 'lead_id', type: 'text', isInput: true, objectName: 'crm_lead' }; + render(); + const [row] = rows(); + fireEvent.click(within(row).getByRole('checkbox', { name: en('engine.flowPreview.vars.input') })); + expect(note(row)).toHaveTextContent(tFormat('engine.flowPreview.vars.inputRecord', 'en', { object: 'crm_lead' })); + expect(onWrite).not.toHaveBeenCalled(); + fireEvent.click(within(row).getByRole('checkbox', { name: en('engine.flowPreview.vars.output') })); + expect(onWrite).toHaveBeenLastCalledWith([{ ...lead, isOutput: true }]); + expectSpecShaped(onWrite.mock.calls.at(-1)![0]); + }); + + it('the control: without onPatch the panel is the read-only list, with no add button', () => { + render(); + expect(screen.queryByRole('button', { name: en('engine.flowPreview.addVariable') })).toBeNull(); + expect(screen.queryByRole('textbox')).toBeNull(); + const [row] = rows(); + expect(row).toHaveTextContent('amount'); + expect(row).toHaveTextContent(en('engine.flowPreview.varIn')); + expect(row).toHaveTextContent('= 5'); + }); + + it('zh-CN: the panel reads its zh rows', () => { + render( {}} />); + expect(screen.getByTestId('flow-variables-empty')).toHaveTextContent(t('engine.flowPreview.noVars', 'zh-CN')); + expect(screen.getByRole('button', { name: '添加变量' })).toBeInTheDocument(); + }); +}); + +describe('flowVariableReaders and nextFlowVariableName', () => { + it('reads whole-word mentions only: not record.amount, not amounts', () => { + const nodes = [ + { id: 'a', type: 'update_record', label: 'A', config: { fields: { total: '{{ record.amount }}' } } }, + { id: 'b', type: 'notify', label: 'B', config: { message: 'amounts due' } }, + { id: 'c', type: 'assignment', label: 'C', config: { amount: '{{ 1 }}' } }, + { id: 'amount', type: 'end', label: 'amount' }, + ]; + expect(flowVariableReaders('amount', nodes)).toEqual(['C']); + expect(flowVariableReaders('amount', [], [{ condition: 'amount > 3' }], [], 'en')).toEqual([en('engine.flowPreview.vars.readerConnection')]); + expect(flowVariableReaders('amount', [], [], ['Closed {{ amount }}'], 'en')).toEqual([en('engine.flowPreview.vars.readerMessages')]); + }); + + it('names the first free variable_N', () => { + expect(nextFlowVariableName([{ name: 'variable_1' }, { name: 'variable_3' }])).toBe('variable_2'); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/FlowVariablesPanel.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/FlowVariablesPanel.tsx new file mode 100644 index 00000000000..346a09bd084 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/FlowVariablesPanel.tsx @@ -0,0 +1,410 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#34818 item 7 — the flow's Variables, editable. + * + * The Studio's Variables section (objectui#12454) and the designer's side + * panel used to list `variables` read-only, with "No variables declared." and + * no way to add one. This panel lists them and, where the flow is editable: + * + * - **Add variable** appends a uniquely named `text` variable; + * - each row edits its name, type, default value, input and output flags; + * - a name the spec refuses (blank, `$`-led — the engine's own namespace, see + * `flowBoundVariableNameSchema('variableName')` — or one another variable + * already holds) is held on screen with a note and not written; + * - renaming or removing a variable a step still reads is refused with a note + * naming those steps. References are not rewritten here: the author edits + * the steps first. The read is deliberately wide (a whole-word mention in + * any string of the step, `{{ name }}` holes and bare CEL alike, or a + * binding key that names it), so a refusal can be stricter than the + * engine, never looser. + * + * Every write is one `onPatch({ variables })` with the whole array, the shape + * `FlowVariableSchema` parses. A key this panel does not edit (`objectName`) + * rides along untouched. Without `onPatch` the panel is the + * read-only list it replaced, with no add button. + */ + +import * as React from 'react'; +import { Plus, Trash2 } from 'lucide-react'; +import { Button, EmptyDescription, Input, cn } from '@object-ui/components'; +import { t as tr, tFormat, tOptional } from '../i18n.js'; +import { flowNodeDisplayName } from './flow-canvas-parts.js'; + +export interface FlowVariableRow { + name: string; + type?: string; + defaultValue?: unknown; + isInput?: boolean; + isOutput?: boolean; + objectName?: string; +} + +interface FlowStepLike { + id: string; + type?: unknown; + label?: unknown; + [key: string]: unknown; +} + +export interface FlowVariablesPanelProps { + variables: FlowVariableRow[]; + /** The flow's steps and connections, read for the reference guard. */ + nodes: ReadonlyArray; + edges?: ReadonlyArray<{ condition?: unknown }>; + /** Flow-level text that reads variables (`successMessage`, `errorMessage`). */ + flowText?: ReadonlyArray; + /** Absent: the read-only list. */ + onPatch?: (patch: { variables: FlowVariableRow[] }) => void; + locale?: string; +} + +/** The data types the spec names (`FlowVariableSchema.type`'s description). */ +export const FLOW_VARIABLE_TYPES = ['text', 'number', 'boolean', 'object', 'list'] as const; + +const IDENT = /[A-Za-z0-9_$]/; + +/** Whether `text` mentions `name` as a whole word (not `record.name`, not `names`). */ +function mentions(text: string, name: string): boolean { + let from = 0; + for (;;) { + const at = text.indexOf(name, from); + if (at < 0) return false; + const before = at === 0 ? '' : text[at - 1]; + const after = text[at + name.length] ?? ''; + if (!(before && (IDENT.test(before) || before === '.')) && !(after && IDENT.test(after))) return true; + from = at + 1; + } +} + +/** Whether any string (or object key) in `value` mentions `name`. */ +function readsName(value: unknown, name: string, depth = 0): boolean { + if (depth > 32 || value === null || value === undefined) return false; + if (typeof value === 'string') return mentions(value, name); + if (Array.isArray(value)) return value.some((v) => readsName(v, name, depth + 1)); + if (typeof value === 'object') { + return Object.entries(value as Record).some( + ([k, v]) => mentions(k, name) || readsName(v, name, depth + 1), + ); + } + return false; +} + +/** + * The steps (by display name) that read `name`, plus "the flow's messages" + * and connection conditions. A step's own id, type and label are its + * identity, not a read, and are skipped. + */ +export function flowVariableReaders( + name: string, + nodes: ReadonlyArray, + edges: ReadonlyArray<{ condition?: unknown }> = [], + flowText: ReadonlyArray = [], + locale?: string, +): string[] { + if (!name.trim()) return []; + const out: string[] = []; + for (const node of nodes) { + const { id: _id, type: _type, label: _label, position: _position, description: _d, ...rest } = node; + if (readsName(rest, name)) out.push(flowNodeDisplayName(node, locale)); + } + if (edges.some((e) => readsName(e.condition, name))) out.push(tr('engine.flowPreview.vars.readerConnection', locale)); + if (flowText.some((v) => readsName(v, name))) out.push(tr('engine.flowPreview.vars.readerMessages', locale)); + return out; +} + +/** The first `variable_N` no variable holds. */ +export function nextFlowVariableName(variables: ReadonlyArray<{ name?: unknown }>): string { + const taken = new Set(variables.map((v) => (typeof v.name === 'string' ? v.name.trim() : ''))); + for (let n = 1; ; n++) { + const name = `variable_${n}`; + if (!taken.has(name)) return name; + } +} + +/** Why `name` cannot be variable `index`'s name, or null. */ +function nameRefusal(name: string, index: number, variables: ReadonlyArray, locale?: string): string | null { + if (!name) return tr('engine.flowPreview.vars.nameBlank', locale); + if (name.startsWith('$')) return tr('engine.flowPreview.vars.nameDollar', locale); + if (variables.some((v, i) => i !== index && v.name === name)) return tFormat('engine.flowPreview.vars.nameTaken', locale, { name }); + return null; +} + +function formatDefault(value: unknown): string { + if (value === undefined) return ''; + if (typeof value === 'string') return value; + try { + return JSON.stringify(value); + } catch { + return String(value); + } +} + +/** The default value `text` reads as for `type`, `undefined` to clear it, or a refusal. */ +function parseDefault(text: string, type: string | undefined): { value: unknown } | { refusal: string } { + if (text === '') return { value: undefined }; + switch (type) { + case 'number': { + const n = Number(text); + return Number.isFinite(n) ? { value: n } : { refusal: 'engine.flowPreview.vars.defaultNumber' }; + } + case 'boolean': + if (text === 'true') return { value: true }; + if (text === 'false') return { value: false }; + return { refusal: 'engine.flowPreview.vars.defaultBoolean' }; + case 'object': + case 'list': { + try { + const v = JSON.parse(text) as unknown; + if (type === 'list' ? Array.isArray(v) : v !== null && typeof v === 'object' && !Array.isArray(v)) return { value: v }; + } catch { + /* refused below */ + } + return { refusal: type === 'list' ? 'engine.flowPreview.vars.defaultList' : 'engine.flowPreview.vars.defaultObject' }; + } + default: + return { value: text }; + } +} + +export function FlowVariablesPanel({ variables, nodes, edges, flowText, onPatch, locale }: FlowVariablesPanelProps) { + const editable = !!onPatch; + const write = React.useCallback((next: FlowVariableRow[]) => onPatch?.({ variables: next }), [onPatch]); + + const add = () => { + write([...variables, { name: nextFlowVariableName(variables), type: 'text' }]); + }; + + return ( +
+ {variables.length === 0 ? ( + + {tr('engine.flowPreview.noVars', locale)} + + ) : ( +
    + {variables.map((v, i) => + editable ? ( + + ) : ( + + ), + )} +
+ )} + {editable && ( + + )} +
+ ); +} + +function Badges({ variable, locale }: { variable: FlowVariableRow; locale?: string }) { + return ( + <> + {variable.isInput && ( + {tr('engine.flowPreview.varIn', locale)} + )} + {variable.isOutput && ( + {tr('engine.flowPreview.varOut', locale)} + )} + + ); +} + +function ReadOnlyRow({ variable: v, locale }: { variable: FlowVariableRow; locale?: string }) { + return ( +
  • +
    + {v.name} + {v.type && {v.type}} + +
    + {v.defaultValue !== undefined && ( +
    = {formatDefault(v.defaultValue)}
    + )} +
  • + ); +} + +interface VariableRowProps { + index: number; + variable: FlowVariableRow; + variables: FlowVariableRow[]; + nodes: ReadonlyArray; + edges?: ReadonlyArray<{ condition?: unknown }>; + flowText?: ReadonlyArray; + write: (next: FlowVariableRow[]) => void; + locale?: string; +} + +function VariableRow({ index, variable: v, variables, nodes, edges, flowText, write, locale }: VariableRowProps) { + const [nameText, setNameText] = React.useState(v.name ?? ''); + const [defaultText, setDefaultText] = React.useState(formatDefault(v.defaultValue)); + const [note, setNote] = React.useState(null); + const label = (key: string) => tr(key, locale); + const typeLabel = (type: string) => tOptional(`engine.flowPreview.vars.type.${type}`, locale) ?? type; + // A write from elsewhere (undo, a reload) re-seeds the row's text. + React.useEffect(() => setNameText(v.name ?? ''), [v.name]); + React.useEffect(() => setDefaultText(formatDefault(v.defaultValue)), [v.defaultValue]); + + const put = (patch: Partial, drop: ReadonlyArray = []) => { + const row: FlowVariableRow = { ...v, ...patch }; + for (const k of drop) delete (row as unknown as Record)[k]; + write(variables.map((x, i) => (i === index ? row : x))); + }; + const readers = () => flowVariableReaders(v.name ?? '', nodes, edges, flowText, locale); + const readersNote = (key: string) => tFormat(key, locale, { name: v.name ?? '', steps: readers().join(tr('engine.flowPreview.vars.listSep', locale)) }); + + const commitName = () => { + const name = nameText.trim(); + if (name === v.name) { + setNameText(name); + setNote(null); + return; + } + const refusal = nameRefusal(name, index, variables, locale); + if (refusal) { + setNote(refusal); + return; + } + if (readers().length > 0) { + setNote(readersNote('engine.flowPreview.vars.renameRead')); + return; + } + setNote(null); + put({ name }); + }; + + const commitDefault = () => { + const parsed = parseDefault(defaultText, v.type); + if ('refusal' in parsed) { + setNote(tr(parsed.refusal, locale)); + return; + } + setNote(null); + if (parsed.value === undefined) { + if (v.defaultValue !== undefined) put({}, ['defaultValue']); + } else if (formatDefault(parsed.value) !== formatDefault(v.defaultValue)) { + put({ defaultValue: parsed.value }); + } + }; + + const changeType = (type: string) => { + if (defaultText === '') { + setNote(null); + put({ type }); + return; + } + // A default the new type cannot hold refuses the change: the author + // clears or rewrites the default first, and nothing is dropped silently. + const parsed = parseDefault(defaultText, type); + if ('refusal' in parsed) { + setNote(tFormat('engine.flowPreview.vars.typeHeld', locale, { type: typeLabel(type) })); + return; + } + setNote(null); + put({ type, defaultValue: parsed.value }); + }; + + const remove = () => { + if (readers().length > 0) { + setNote(readersNote('engine.flowPreview.vars.removeRead')); + return; + } + write(variables.filter((_, i) => i !== index)); + }; + + const toggleInput = (on: boolean) => { + // `objectName` declares an INPUT a record reference; the spec refuses it + // on a variable that is not one, so it cannot be unticked under it. + if (!on && v.objectName !== undefined) { + setNote(tFormat('engine.flowPreview.vars.inputRecord', locale, { object: String(v.objectName) })); + return; + } + setNote(null); + put({ isInput: on }); + }; + + const types: string[] = [...FLOW_VARIABLE_TYPES]; + if (v.type && !types.includes(v.type)) types.push(v.type); + + return ( +
  • +
    + setNameText(e.target.value)} + onBlur={commitName} + onKeyDown={(e) => { + if (e.key === 'Enter') commitName(); + }} + className={cn('h-7 min-w-0 flex-1 basis-32 font-mono text-xs', note && 'border-destructive')} + /> + + +
    +
    + setDefaultText(e.target.value)} + onBlur={commitDefault} + onKeyDown={(e) => { + if (e.key === 'Enter') commitDefault(); + }} + className="h-7 min-w-0 flex-1 basis-32 font-mono text-xs" + /> + + +
    + {note && ( +

    + {note} +

    + )} +
  • + ); +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/emptyCollection-8526.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/emptyCollection-8526.test.tsx index eabb6461a9f..cd07bee7d3c 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/emptyCollection-8526.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/emptyCollection-8526.test.tsx @@ -34,6 +34,9 @@ */ import { describe, it, expect, vi, afterEach } from 'vitest'; +// Paid at collection, not inside a clocked case (check:test-source-alias): +// the source under test loads `@objectstack/lint` lazily. +import '@objectstack/lint'; import { render, screen, within, cleanup, fireEvent } from '@testing-library/react'; // `ScreenPreview` reads both providers at its top level (`useAdapter()` / @@ -282,7 +285,9 @@ describe('EmailTemplatePreview — a template with no placeholders', () => { // ───────────────────────────── FlowPreview ───────────────────────────── describe('FlowPreview — the variables rail with no declared variables', () => { - const SENTENCE = 'No variables declared.'; + // objectstack#34818 — the sentence says what variables are for. + const SENTENCE = + 'No variables yet. A variable holds a value the steps read as {{ name }}. Mark it Input to take it from whoever starts the flow, or Output to hand it back when the flow ends.'; const FLOW = { name: 'ping_flow', nodes: [ diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/flowFieldChrome.i18n-10862-s4.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/flowFieldChrome.i18n-10862-s4.test.tsx index 9377175d79c..c51e66c7865 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/flowFieldChrome.i18n-10862-s4.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/flowFieldChrome.i18n-10862-s4.test.tsx @@ -38,6 +38,9 @@ import * as React from 'react'; import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; +// Paid at collection, not inside a clocked case (check:test-source-alias): +// the source under test loads `@objectstack/lint` lazily. +import '@objectstack/lint'; import { render, cleanup, act, fireEvent, screen } from '@testing-library/react'; import { I18nProvider, useObjectTranslation } from '@object-ui/i18n'; @@ -280,12 +283,19 @@ describe('FlowCanvas reads the locale FlowPreview hands it (objectui#10862, slic describe('FlowPreview and FlowRunsPanel read the designer locale (objectui#10862, slice 4)', () => { for (const lang of LANGS) { - pin(`${lang}: the variables panel's in / out tags`, async () => { + // objectstack#34818 — an editable flow's panel edits each variable: its + // in / out tags are the Input / Output boxes, and the names are values. + pin(`${lang}: the variables panel's input / output boxes`, async () => { await mountFlow(lang); fireEvent.click(buttonReading(lang, 'engine.flowPreview.variables')); await flush(); - expectSites(lang, [{ key: 'engine.flowPreview.varIn' }, { key: 'engine.flowPreview.varOut' }]); - expectAsWritten(['amount', 'verdict']); + expectSites(lang, [ + { key: 'engine.flowPreview.vars.input' }, + { key: 'engine.flowPreview.vars.output' }, + { key: 'engine.flowPreview.addVariable' }, + { key: 'engine.flowPreview.vars.defaultPlaceholder', in: 'placeholder' }, + ]); + for (const name of ['amount', 'verdict']) expect(screen.getByDisplayValue(name)).toBeTruthy(); }); pin(`${lang}: an expanded run's id line, with and without a trigger`, async () => { diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.flowAutosave-34818.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.flowAutosave-34818.test.tsx new file mode 100644 index 00000000000..778b8fc556c --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.flowAutosave-34818.test.tsx @@ -0,0 +1,339 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#34818 slice 3 — the Automations pillar's flow designer, on the + * REAL `AutomationsPillar` with the REAL registered `FlowPreview` and + * `FlowInspector` (the harness of `StudioDesignSurface.autosaveInFlight-11204`). + * + * Item 8 — a landed flow autosave settles the header's 正在保存 spinner into + * an 已保存 badge instead of raising a "Draft saved" toast. Seat ruling + * 6954475081 on #34818 holds the badge to ruling 6545938831 ② on #28345 (write + * feedback names the item): the badge sits in the flow header's own title row, + * beside the flow's title, and its accessible text names the flow. A refused + * save keeps its strip and raises one error toast. Controls: a second edit + * clears the badge, and an Interfaces page (a leaf) autosave still toasts. + * + * Item 6 — the Debug section takes the Configuration aside's place; leaving + * Debug brings the aside back with the selection kept. Control: Canvas keeps it. + * + * Item 9 — the Runs section says why it is empty: a flow the package does not + * serve yet (never published) reads "publish and turn on", and no run history + * is fetched; a served flow whose engine does not answer reads the + * engine-offline sentence. + */ + +import '@testing-library/jest-dom/vitest'; +// Paid at collection, not inside a clocked case (check:test-source-alias): +// the source under test loads `@objectstack/lint` lazily. +import '@objectstack/lint'; +import * as React from 'react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +// Module scope as well as in the `vi.mock` factory below: the cold transform is paid +// during collection, which no test or hook timeout clocks (AGENTS.md, flaky-test discipline). +import '@object-ui/components'; +import { render, screen, fireEvent, cleanup, waitFor, within } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; + +const PKG = 'com.acme.app'; + +const FLOW = { + name: 'notify_owner', + label: 'Notify owner', + type: 'autolaunched', + status: 'active', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'end' }], +}; + +const HOME = { + name: 'home', + label: 'Home', + type: 'app', + regions: [{ name: 'main', components: [{ id: 'hello', type: 'element:text', properties: { content: 'Hello' } }] }], +}; +const APP = { name: 'acme_app', label: 'Acme', navigation: [{ id: 'nav_home', type: 'page', label: 'Home menu', pageName: 'home' }] }; + +const server = vi.hoisted(() => ({ + active: new Map>(), + drafts: new Map>(), + saves: [] as Array<{ type: string; name: string }>, + /** While set, every save is refused with this message. */ + refuse: null as string | null, + /** The names `listResponse('flow')` serves: the published flows. */ + published: new Set(), +})); + +const mockClient = vi.hoisted(() => { + const k = (type: string, name: string) => `${type}/${name}`; + return { + list: vi.fn(async (type: string) => + [...server.active.entries()] + .filter(([key]) => key.startsWith(`${type}/`)) + .map(([, row]) => ({ name: row.name, label: row.label ?? row.name })), + ), + listResponse: vi.fn(async (type: string) => ({ + items: type === 'flow' ? [...server.published].map((name) => ({ name })) : [], + })), + listDrafts: vi.fn(async () => []), + listTypes: vi.fn(async () => ({ entries: [] })), + get: vi.fn(async () => null), + references: vi.fn(async () => []), + layered: vi.fn(async (type: string, name: string) => { + const eff = server.active.get(k(type, name)) ?? null; + const draft = server.drafts.get(k(type, name)) ?? null; + return { code: null, overlay: eff, overlayScope: eff ? 'env' : null, effective: eff, draft, editable: true, deletable: true, resettable: false, lock: 'none' }; + }), + getDraft: vi.fn(async (type: string, name: string) => { + const draft = server.drafts.get(k(type, name)); + if (draft) return { item: JSON.parse(JSON.stringify(draft)) as Record }; + throw Object.assign(new Error(`No pending draft exists for ${type}/${name}.`), { code: 'NO_DRAFT', status: 404 }); + }), + save: vi.fn(async (type: string, name: string, item: unknown) => { + server.saves.push({ type, name }); + if (server.refuse) throw Object.assign(new Error(server.refuse), { status: 422 }); + server.drafts.set(k(type, name), JSON.parse(JSON.stringify(item)) as Record); + return { type, name, item }; + }), + publish: vi.fn(async () => ({ success: true })), + reset: vi.fn(async () => ({})), + }; +}); + +vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; +}); + +vi.mock('./packages-io', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, fetchPackages: vi.fn(async () => []) }; +}); + +vi.mock('@object-ui/react', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, useAdapter: () => dataSource }; +}); + +vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), dismiss: vi.fn() } })); + +import { toast } from 'sonner'; +import { AutomationsPillar, InterfacesPillar } from './StudioDesignSurface'; +import { StudioRightSlotContext } from './studioRightSlotState'; +import { createEmptyDataSource } from './__tests__/emptyDataSource'; +import { registerMetadataPreview } from '../metadata-admin/preview-registry'; +import { registerMetadataInspector } from '../metadata-admin/inspector-registry'; +import { registerMetadataDefaultInspector } from '../metadata-admin/default-inspector-registry'; +import { FlowPreview } from '../metadata-admin/previews/FlowPreview'; +import { FlowInspector } from '../metadata-admin/inspectors/FlowInspector'; +import { PagePreview } from '../metadata-admin/previews/PagePreview'; +import { PageBlockInspector } from '../metadata-admin/inspectors/PageBlockInspector'; +import { PageDefaultInspector } from '../metadata-admin/inspectors/PageDefaultInspector'; +import { t, tFormat } from '../metadata-admin/i18n'; + +const dataSource = createEmptyDataSource(); + +registerMetadataPreview('flow', FlowPreview); +registerMetadataInspector('flow', FlowInspector); +registerMetadataPreview('page', PagePreview); +registerMetadataInspector('page', PageBlockInspector); +registerMetadataDefaultInspector('page', PageDefaultInspector); + +const en = (key: string) => t(key, 'en'); +const fetchSpy = vi.fn(async (_input: RequestInfo | URL) => new Response('null', { status: 404, headers: { 'content-type': 'application/json' } })); + +beforeEach(() => { + server.active.clear(); + server.drafts.clear(); + server.saves.length = 0; + server.refuse = null; + server.published = new Set([FLOW.name]); + for (const fn of Object.values(mockClient)) (fn as unknown as { mockClear: () => void }).mockClear(); + vi.mocked(toast.success).mockClear(); + vi.mocked(toast.error).mockClear(); + fetchSpy.mockClear(); + // The `/automation/_status` probe, the action catalog and the run history + // read all go through the global `fetch`; one double answers "absent". + vi.stubGlobal('fetch', fetchSpy); + server.active.set(`flow/${FLOW.name}`, JSON.parse(JSON.stringify(FLOW))); + server.active.set(`page/${HOME.name}`, JSON.parse(JSON.stringify(HOME))); + server.active.set(`app/${APP.name}`, JSON.parse(JSON.stringify(APP))); +}); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +function editText(el: HTMLElement, value: string): void { + fireEvent.change(el, { target: { value } }); + fireEvent.blur(el); +} + +async function renderOpenFlow(): Promise { + render( + + + , + ); + await screen.findByTestId('auto-tab-canvas', undefined, { timeout: 8000 }); + await waitFor(() => expect(screen.getByText('Status:').nextElementSibling).toHaveTextContent(en('engine.studio.auto.enabled')), { timeout: 8000 }); +} + +async function selectStart(): Promise { + fireEvent.click(document.querySelector('[data-node-id="start"] [role="button"]') as HTMLElement); + return within(screen.getByTestId('auto-config-aside')).findByLabelText('Label', undefined, { timeout: 8000 }); +} + +const flowToasts = () => + vi.mocked(toast.success).mock.calls.filter(([text]) => String(text).includes(FLOW.label) || String(text).includes(FLOW.name)); + +describe('a landed flow autosave says 已保存 in the header, not in a toast (#34818 item 8)', () => { + it('shows the badge in the flow header title row, naming the flow, and raises no toast', async () => { + await renderOpenFlow(); + editText(await selectStart(), 'Kick-off'); + const badge = await screen.findByTestId('auto-autosaved', undefined, { timeout: 8000 }); + expect(server.saves.filter((s) => s.type === 'flow')).toHaveLength(1); + + // Beside the flow's title: the header's own title row holds both. + const titleRow = screen.getByTestId('auto-flow-header').firstElementChild as HTMLElement; + expect(titleRow.contains(badge)).toBe(true); + expect(within(titleRow).getByRole('heading', { level: 1 })).toHaveTextContent(FLOW.label); + // Seen: "Saved". Heard: the sentence that names the flow. + expect(badge).toHaveAttribute('role', 'status'); + expect(badge).toHaveTextContent(en('engine.studio.autoSaved')); + expect(within(badge).getByText(tFormat('engine.studio.flowSavedNamed', 'en', { item: FLOW.label }))).toHaveClass('sr-only'); + + expect(flowToasts(), 'no "Draft saved" toast for a flow').toEqual([]); + expect(toast.error).not.toHaveBeenCalled(); + }); + + it('a second edit clears the badge until that edit lands', async () => { + await renderOpenFlow(); + const label = await selectStart(); + editText(label, 'Kick-off'); + await screen.findByTestId('auto-autosaved', undefined, { timeout: 8000 }); + editText(label, 'Kick-off two'); + expect(screen.queryByTestId('auto-autosaved')).toBeNull(); + await screen.findByTestId('auto-autosaved', undefined, { timeout: 8000 }); + expect(server.saves.filter((s) => s.type === 'flow')).toHaveLength(2); + }); + + it('a refused save keeps its strip, raises one error toast and shows no badge', async () => { + server.refuse = 'Flow "notify_owner" is invalid: label too long.'; + await renderOpenFlow(); + editText(await selectStart(), 'Kick-off'); + await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(1), { timeout: 8000 }); + expect(vi.mocked(toast.error).mock.calls[0][0]).toBe(tFormat('engine.studio.flowSaveFailed', 'en', { item: FLOW.label })); + expect(await screen.findByText(/label too long/, undefined, { timeout: 8000 })).toBeInTheDocument(); + expect(screen.queryByTestId('auto-autosaved')).toBeNull(); + expect(flowToasts()).toEqual([]); + }); + + it('the control: an Interfaces page (a leaf) autosave still toasts by its label', async () => { + render( + + + , + ); + await screen.findByRole('button', { name: 'Select hello' }, { timeout: 8000 }); + const label = await within(screen.getByRole('complementary')).findByLabelText(/^Label/, undefined, { timeout: 8000 }); + editText(label, 'Welcome'); + await waitFor(() => expect(toast.success).toHaveBeenCalled(), { timeout: 8000 }); + expect(vi.mocked(toast.success).mock.calls[0][0]).toBe(tFormat('engine.studio.draftSaved', 'en', { item: 'Home menu' })); + }); +}); + +describe('the Debug section takes the Configuration aside’s place (#34818 item 6)', () => { + it('hides the aside in Debug and brings it back, selection kept, on leaving', async () => { + await renderOpenFlow(); + await selectStart(); + fireEvent.click(screen.getByTestId('auto-tab-debug')); + await waitFor(() => expect(screen.getByTestId('flow-preview-section')).toHaveAttribute('data-section', 'debug')); + expect(screen.queryByTestId('auto-config-aside')).toBeNull(); + expect(screen.getByTestId('flow-preview-section').className).toContain('lg:grid-cols-[1fr_300px]'); + + fireEvent.click(screen.getByTestId('auto-tab-canvas')); + const aside = await screen.findByTestId('auto-config-aside'); + expect(within(aside).getByLabelText('Label')).toHaveValue('Start'); + }); + + it('in the right slot, Debug draws the simulator in the slot, in the Configuration’s place', async () => { + const showProps = vi.fn(); + function SlotHost({ children }: { children: React.ReactNode }) { + const [target, setTarget] = React.useState(null); + const handle = React.useMemo( + () => ({ propsTarget: target, mode: 'props' as const, claimProps: () => () => {}, showProps }), + [target], + ); + return ( + + {children} +
    + + ); + } + render( + + + + + , + ); + await screen.findByTestId('auto-tab-canvas', undefined, { timeout: 8000 }); + const slot = screen.getByTestId('slot-target'); + await waitFor(() => expect(within(slot).getByTestId('auto-config-aside')).toBeInTheDocument(), { timeout: 8000 }); + await selectStart(); + + showProps.mockClear(); + fireEvent.click(screen.getByTestId('auto-tab-debug')); + await waitFor(() => expect(within(slot).getByTestId('flow-debug-in-slot')).toBeInTheDocument()); + expect(within(slot).queryByTestId('auto-config-aside')).toBeNull(); + expect(showProps, 'opening Debug shows the slot’s properties half').toHaveBeenCalled(); + // The section keeps the canvas alone: no second simulator column beside it. + const sectionEl = screen.getByTestId('flow-preview-section'); + expect(sectionEl.className).toContain('grid-cols-1'); + expect(within(sectionEl).queryByRole('button', { name: en('engine.flowSim.run') })).toBeNull(); + expect(within(slot).getByRole('button', { name: en('engine.flowSim.run') })).toBeInTheDocument(); + + fireEvent.click(screen.getByTestId('auto-tab-canvas')); + const aside = await within(slot).findByTestId('auto-config-aside'); + expect(within(aside).getByLabelText('Label')).toHaveValue('Start'); + expect(within(slot).queryByTestId('flow-debug-in-slot')).toBeNull(); + }); + + it('the control: the Canvas section keeps the aside', async () => { + await renderOpenFlow(); + expect(screen.getByTestId('flow-preview-section')).toHaveAttribute('data-section', 'canvas'); + expect(screen.getByTestId('auto-config-aside')).toBeInTheDocument(); + }); +}); + +describe('the Runs section says why it is empty (#34818 item 9)', () => { + const runFetches = () => fetchSpy.mock.calls.filter(([input]) => String(input).includes('/runs')); + + it('a flow the package does not serve yet reads "publish and turn on", with no run fetch', async () => { + server.published = new Set(); + await renderOpenFlow(); + await waitFor(() => expect(mockClient.listResponse).toHaveBeenCalled()); + fireEvent.click(screen.getByTestId('auto-tab-runs')); + expect(await screen.findByTestId('flow-runs-unpublished', undefined, { timeout: 8000 })).toHaveTextContent( + en('engine.flowRuns.unpublished'), + ); + expect(runFetches()).toEqual([]); + }); + + it('a served flow whose engine does not answer reads the engine-offline sentence alone', async () => { + await renderOpenFlow(); + await waitFor(() => expect(mockClient.listResponse).toHaveBeenCalled()); + fireEvent.click(screen.getByTestId('auto-tab-runs')); + expect(await screen.findByTestId('flow-runs-unavailable', undefined, { timeout: 8000 })).toHaveTextContent( + en('engine.flowRuns.engineOffline'), + ); + expect(screen.queryByTestId('flow-runs-unpublished')).toBeNull(); + expect(runFetches().length).toBeGreaterThan(0); + }); +}); + diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx index 0df7e975b97..13180c382bb 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx @@ -8105,6 +8105,32 @@ export function DataPillar({ // objectstack#29988 — the Automations rail's flow helpers moved to their own module; re-exported for their pins. export { FlowStatusDot, type NewFlowTrigger }; +/** + * objectstack#34818 — the names of the flows that have a published version in + * these scopes: the published list (`list()` serves no drafts). Any failed read + * answers `null`, "unknown", so the Runs tab keeps its sentence that names both + * causes rather than claim the flow was never published. + */ +async function readPublishedFlowNames( + client: Pick, + scopes: ReadonlyArray, +): Promise | null> { + try { + const answers = await Promise.all( + scopes.map((packageId) => client.listResponse>('flow', packageId === null ? {} : { packageId })), + ); + const names = new Set(); + for (const answer of answers) { + for (const item of answer?.items ?? []) { + if (item && typeof item.name === 'string' && item.name) names.add(item.name); + } + } + return names; + } catch { + return null; + } +} + /** Automations pillar — flows: list → FlowPreview (default OFF / review-then-enable). */ export function AutomationsPillar({ packageId: railPackageId, @@ -8388,6 +8414,10 @@ export function AutomationsPillar({ // list's `registrations` (served beside the items, keyed by name). A flow // with no entry is one no engine judged, which reads as before. const [flowRegistrations, setFlowRegistrations] = React.useState>({}); + // objectstack#34818 — the flows of the rail's scope that have a published + // version, so the Runs tab can tell "not published yet" from "the engine is + // not answering". `null` until read, and after a failed read: unknown. + const [publishedFlowNames, setPublishedFlowNames] = React.useState | null>(null); // objectui#12454 — the rail groups flows by the object each is about and // marks each with its trigger kind, both read off the flow's definition as // served (`flowGrouping.ts`), with the scope's objects naming the groups. @@ -8456,7 +8486,7 @@ export function AutomationsPillar({ readFlowDefinitions(client, pairId), readObjectLabels(client, pairId, locale), ]); - const [baseItems, registrations, definitions, objects, pair] = await Promise.all([ + const [baseItems, registrations, definitions, objects, pair, publishedNames] = await Promise.all([ packageId === null ? loadPackageLessSurfaces(client, 'flow', locale) : loadPackageSurfaces(client, 'flow', packageId, locale), @@ -8464,10 +8494,12 @@ export function AutomationsPillar({ readFlowDefinitions(client, packageId), readObjectLabels(client, packageId, locale), readPair().catch(() => null), + readPublishedFlowNames(client, [packageId, ...(pairId === null ? [] : [pairId])]), ]); if (cancelled) return; const items: Surface[] = withPairItems(baseItems, pair?.[0] ?? [], pairId); setFlows(items); + setPublishedFlowNames(publishedNames); setFlowRegistrations(pair ? { ...pair[1], ...registrations } : registrations); setFlowDefinitions(pair ? new Map([...pair[2], ...definitions]) : definitions); setObjectLabels(pair ? new Map([...pair[3], ...objects]) : objects); @@ -8661,10 +8693,14 @@ export function AutomationsPillar({ // objectui#5813 — local dirty flag: auto-save arms only after a real edit. const [autoDirty, setAutoDirty] = React.useState(false); + // objectstack#34818 — the flow whose last autosave landed with nothing edited + // since: its header row says 已保存 in place of a toast. The next edit clears it. + const [flowSavedFor, setFlowSavedFor] = React.useState(null); const onPatch = React.useCallback( (patch: Record) => { setDraft((d) => ({ ...d, ...patch })); setAutoDirty(true); + setFlowSavedFor(null); }, [], ); @@ -8672,6 +8708,12 @@ export function AutomationsPillar({ if (!current) return; setSaving('draft'); setError(null); + // objectstack#34818 — a landed autosave raises no toast (the header says + // 已保存); a failed one does, once per flow, beside its refusal strip. + const announceFailed = () => + toast.error(tFormat('engine.studio.flowSaveFailed', locale, { item: current.label || current.name }), { + id: `studio-draft-failed:flow:${current.name}`, + }); try { // objectstack#28570 — a read-only base's flow is saved into the pair the // ensure door answers, under its own name, declaring the override. A @@ -8685,11 +8727,13 @@ export function AutomationsPillar({ pair = await pairForFlow(custom, current.name); } catch (e) { setError(plainRefusal(e)); + announceFailed(); return; } const declared = overrideDraftBody(draft, custom.base, custom.basedOn); if (declared === null) { setError({ message: tFormat('engine.studio.customize.noVersion', locale, { package: custom.baseLabel }) }); + announceFailed(); return; } // The buffer was read at another package (the base, before its pair @@ -8717,13 +8761,19 @@ export function AutomationsPillar({ // objectstack#26858 — the stored draft carries its own verdict now. rereadFlowVerdict(current.name, target.packageId); // objectui#11204 — clean only if nothing was edited while it was in flight. - if (sent.unmoved()) setAutoDirty(false); - // objectstack#28984 — named as the rail names the flow. - announceDraftSaved({ type: 'flow', name: current.name }, current.label, locale); + // objectstack#34818 — and only then does the header say 已保存: an edit + // made in flight is not saved yet. The header row names the flow, which + // is what ruling 6545938831 ② on #28345 asks of write feedback, so the + // flow pillar raises no "Draft of X saved" toast (seat ruling 6954475081). + if (sent.unmoved()) { + setAutoDirty(false); + setFlowSavedFor(current.name); + } onDraftSaved?.({ type: 'flow', name: current.name }); } catch (e) { // objectui#11785 — read against `draft`, the body this save sent. setError(flowSaveRefusal(e, draft, locale)); + announceFailed(); } finally { setSaving(false); } @@ -9009,6 +9059,12 @@ export function AutomationsPillar({ React.useEffect(() => { if (flowSelectionKey && showSlotProps) showSlotProps(); }, [flowSelectionKey, showSlotProps]); + // objectstack#34818 — Debug takes the Configuration's place in the slot, so + // opening it shows the properties half, where the simulator is drawn. + const flowDebugOpen = flowSection === 'debug'; + React.useEffect(() => { + if (flowDebugOpen && showSlotProps) showSlotProps(); + }, [flowDebugOpen, showSlotProps]); React.useEffect(() => { if (!inSlot || !flowSelectionKey) return; const onKey = (e: KeyboardEvent) => { @@ -9537,6 +9593,21 @@ export function AutomationsPillar({ {t('engine.studio.autoSaving', locale)} )} + {/* objectstack#34818 — the landed autosave, said in the flow's own + title row instead of a toast; read aloud with the flow's name. */} + {saving !== 'draft' && current && flowSavedFor === current.name && ( + + + )} {/* objectstack#28570 — Customize unlocks the flow's editors; nothing is saved until an edit. */} {current && flowLoaded && flowCustomizable && !flowUnlocked && !flowInPair && ( {React.createElement(Preview, { type: current.type, @@ -9749,7 +9827,12 @@ export function AutomationsPillar({
    - {flowsEmpty ? null : configFolded && !inSlot ? ( + {/* #34818 — Debug takes the Configuration's place, and the aside is + not drawn: in the classic row the simulator column widens to the + aside's width; in the right slot the simulator is drawn in the + slot itself (the chrome's `debugTarget`). The selection is kept, + so leaving Debug brings the aside back as it was. */} + {flowsEmpty || section === 'debug' ? null : configFolded && !inSlot ? ( // objectui#11795 — the folded row: no aside reserving width beside // the canvas; the selection's configuration opens over it, and // closing the drawer clears the selection, as the aside's ✕ does. diff --git a/ui/packages/app-shell/src/views/studio-design/StudioPillarKit.tsx b/ui/packages/app-shell/src/views/studio-design/StudioPillarKit.tsx index 7595997a5cf..ce4e88349e5 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioPillarKit.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioPillarKit.tsx @@ -273,6 +273,10 @@ export interface StudioSavedDraft { * saved meanwhile gets its own. Called only once the save has landed: a * refused save keeps its refusal strip and says nothing about saving, and a * conflict the author settled by reloading saved nothing. + * + * objectstack#34818 — the flow pillar no longer calls it: a flow's landed + * autosave says 已保存 in the flow's own title row, read aloud with the flow's + * name, and only a failed save raises a toast there (seat ruling 6954475081). */ export function announceDraftSaved(saved: StudioSavedDraft, label: string, locale: string): void { toast.success(tFormat('engine.studio.draftSaved', locale, { item: label || saved.name }), { diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 580098f8830..fdee97e9f53 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -3240,6 +3240,10 @@ const STUDIO_EN: Record = { 'engine.studio.createDraft': 'Save as draft', 'engine.studio.saveDraft': 'Save draft', 'engine.studio.autoSaving': 'Saving…', + // objectstack#34818 — the flow header's landed-autosave mark, its spoken form, and the one toast left (a failed save). + 'engine.studio.autoSaved': 'Saved', + 'engine.studio.flowSavedNamed': 'Flow "{item}" saved', + 'engine.studio.flowSaveFailed': 'The draft of "{item}" was not saved', // Standard create-dialog field labels (shared by object / app / flow / permission). 'engine.studio.app.nameLabel': 'App name', 'engine.studio.app.idLabel': 'Identifier', @@ -4071,7 +4075,34 @@ const STUDIO_EN: Record = { 'engine.flowPreview.showVars': 'Show variables panel', 'engine.flowPreview.hideVars': 'Hide variables panel', 'engine.flowPreview.variables': 'Variables', - 'engine.flowPreview.noVars': 'No variables declared.', + 'engine.flowPreview.noVars': 'No variables yet. A variable holds a value the steps read as {{ name }}. Mark it Input to take it from whoever starts the flow, or Output to hand it back when the flow ends.', + 'engine.flowPreview.addVariable': 'Add variable', + 'engine.flowPreview.vars.name': 'Variable name', + 'engine.flowPreview.vars.type': 'Type', + 'engine.flowPreview.vars.default': 'Default value', + 'engine.flowPreview.vars.defaultPlaceholder': 'Default value (optional)', + 'engine.flowPreview.vars.input': 'Input', + 'engine.flowPreview.vars.output': 'Output', + 'engine.flowPreview.vars.remove': 'Remove variable {name}', + 'engine.flowPreview.vars.type.text': 'Text', + 'engine.flowPreview.vars.type.number': 'Number', + 'engine.flowPreview.vars.type.boolean': 'True / false', + 'engine.flowPreview.vars.type.object': 'Object', + 'engine.flowPreview.vars.type.list': 'List', + 'engine.flowPreview.vars.nameBlank': 'A variable needs a name.', + 'engine.flowPreview.vars.nameDollar': 'A name may not start with $: those names belong to the flow engine.', + 'engine.flowPreview.vars.nameTaken': 'Another variable is already named {name}.', + 'engine.flowPreview.vars.renameRead': '{name} is still read by: {steps}. Change those steps first, then rename it.', + 'engine.flowPreview.vars.removeRead': '{name} is still read by: {steps}. Change those steps first, then remove it.', + 'engine.flowPreview.vars.listSep': ', ', + 'engine.flowPreview.vars.readerConnection': 'a connection condition', + 'engine.flowPreview.vars.readerMessages': 'the flow’s finish messages', + 'engine.flowPreview.vars.defaultNumber': 'The default of a number variable must be a number.', + 'engine.flowPreview.vars.defaultBoolean': 'The default of a true / false variable must be true or false.', + 'engine.flowPreview.vars.defaultObject': 'The default of an object variable must be a JSON object, such as {"key": "value"}.', + 'engine.flowPreview.vars.defaultList': 'The default of a list variable must be a JSON list, such as ["a", "b"].', + 'engine.flowPreview.vars.typeHeld': 'The default value does not fit {type}. Clear or rewrite it first, then change the type.', + 'engine.flowPreview.vars.inputRecord': 'This input is a record of {object}, so it stays an input.', 'engine.flowPreview.runsTitle': 'Run history from the automation engine', 'engine.flowPreview.runs': 'Runs', 'engine.flowPreview.problemsTitle': 'Validation problems', @@ -4086,6 +4117,9 @@ const STUDIO_EN: Record = { 'engine.flowRuns.unavailable': 'Run history unavailable — the automation engine is offline or this flow hasn’t been published.', 'engine.flowRuns.empty': 'No runs yet.', + // objectstack#34818 — the two causes the line above names, each said alone when the host knows which. + 'engine.flowRuns.unpublished': 'Publish and turn on this flow, and each of its runs is listed here.', + 'engine.flowRuns.engineOffline': 'Run history unavailable — the automation engine is not answering. Try again later.', 'engine.flowRuns.noSteps': 'No step log recorded.', 'engine.flowRuns.iteration': 'Iteration', 'engine.flowRuns.iterationN': 'Iteration {n}', diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index 7992ef84b4b..095b6588c0b 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -2883,6 +2883,10 @@ const STUDIO_ZH: Record = { 'engine.studio.createDraft': '存为草稿', 'engine.studio.saveDraft': '保存草稿', 'engine.studio.autoSaving': '保存中…', + // objectstack#34818 — 流程标题行的「已保存」、读屏时念出的完整说法,以及唯一保留的提示(保存失败)。 + 'engine.studio.autoSaved': '已保存', + 'engine.studio.flowSavedNamed': '流程「{item}」已保存', + 'engine.studio.flowSaveFailed': '「{item}」的草稿没有保存成功', // Standard create-dialog field labels (shared by object / app / flow / permission). 'engine.studio.app.nameLabel': '应用名称', 'engine.studio.app.idLabel': '标识', @@ -3670,7 +3674,34 @@ const STUDIO_ZH: Record = { 'engine.flowPreview.showVars': '显示变量面板', 'engine.flowPreview.hideVars': '隐藏变量面板', 'engine.flowPreview.variables': '变量', - 'engine.flowPreview.noVars': '未声明变量。', + 'engine.flowPreview.noVars': '还没有变量。变量保存一个值,步骤里用 {{ 名称 }} 读取。标为「输入」可由启动流程的一方传入,标为「输出」会在流程结束时返回。', + 'engine.flowPreview.addVariable': '添加变量', + 'engine.flowPreview.vars.name': '变量名', + 'engine.flowPreview.vars.type': '类型', + 'engine.flowPreview.vars.default': '默认值', + 'engine.flowPreview.vars.defaultPlaceholder': '默认值(可选)', + 'engine.flowPreview.vars.input': '输入', + 'engine.flowPreview.vars.output': '输出', + 'engine.flowPreview.vars.remove': '删除变量 {name}', + 'engine.flowPreview.vars.type.text': '文本', + 'engine.flowPreview.vars.type.number': '数字', + 'engine.flowPreview.vars.type.boolean': '是 / 否', + 'engine.flowPreview.vars.type.object': '对象', + 'engine.flowPreview.vars.type.list': '列表', + 'engine.flowPreview.vars.nameBlank': '变量需要一个名称。', + 'engine.flowPreview.vars.nameDollar': '名称不能以 $ 开头,这类名称归流程引擎所有。', + 'engine.flowPreview.vars.nameTaken': '已有另一个变量叫 {name}。', + 'engine.flowPreview.vars.renameRead': '{name} 仍被这些地方读取:{steps}。请先修改这些步骤,再重命名。', + 'engine.flowPreview.vars.removeRead': '{name} 仍被这些地方读取:{steps}。请先修改这些步骤,再删除。', + 'engine.flowPreview.vars.listSep': '、', + 'engine.flowPreview.vars.readerConnection': '某条连线的条件', + 'engine.flowPreview.vars.readerMessages': '流程的结束提示', + 'engine.flowPreview.vars.defaultNumber': '数字变量的默认值必须是数字。', + 'engine.flowPreview.vars.defaultBoolean': '是 / 否变量的默认值必须是 true 或 false。', + 'engine.flowPreview.vars.defaultObject': '对象变量的默认值必须是 JSON 对象,例如 {"key": "value"}。', + 'engine.flowPreview.vars.defaultList': '列表变量的默认值必须是 JSON 列表,例如 ["a", "b"]。', + 'engine.flowPreview.vars.typeHeld': '默认值不符合「{type}」。请先清空或改写默认值,再修改类型。', + 'engine.flowPreview.vars.inputRecord': '这个输入是 {object} 的记录,因此必须保持为输入。', 'engine.flowPreview.runsTitle': '来自自动化引擎的运行历史', 'engine.flowPreview.runs': '运行', 'engine.flowPreview.problemsTitle': '校验问题', @@ -3684,6 +3715,9 @@ const STUDIO_ZH: Record = { 'engine.flowRuns.refresh': '刷新运行历史', 'engine.flowRuns.unavailable': '运行历史不可用 —— 自动化引擎已离线,或此流程尚未发布。', 'engine.flowRuns.empty': '暂无运行记录。', + // objectstack#34818 — 上面那句里的两种原因,宿主知道是哪一种时各说各的。 + 'engine.flowRuns.unpublished': '发布并启用后,这里显示每次运行的记录。', + 'engine.flowRuns.engineOffline': '运行历史暂时不可用 —— 自动化引擎没有响应,请稍后再试。', 'engine.flowRuns.noSteps': '未记录步骤日志。', 'engine.flowRuns.iteration': '迭代', 'engine.flowRuns.iterationN': '第 {n} 次迭代',