diff --git a/.changeset/36893-sds-pillar-split.md b/.changeset/36893-sds-pillar-split.md
new file mode 100644
index 00000000000..e34efd95b34
--- /dev/null
+++ b/.changeset/36893-sds-pillar-split.md
@@ -0,0 +1,10 @@
+---
+'@object-ui/app-shell': patch
+---
+
+internal: move-only — Studio's Data, Automations and Access pillars move out of `StudioDesignSurface.tsx` into their own modules, taking it from 8,010 to 1,715 lines
+
+Clause-②: no
+Metadata-protocol: none
+
+No behaviour change. Under `views/studio-design/`, `DataPillar.tsx` holds the Data pillar with its records-grid slot (`renderStudioGridList`) and its object draft-save shape. `AutomationsPillar.tsx` holds the Automations pillar and the published-flow-names read only it makes. `AccessPillar.tsx` holds the Access pillar with its "New similar" arrival reader and the list-row name label only it draws. The moved code is byte-identical apart from its imports. `StudioDesignSurface.tsx` imports the three pillars from there and re-exports them, with `renderStudioGridList`, so every import of them keeps working. The package's public exports are unchanged.
diff --git a/ui/packages/app-shell/src/__tests__/homeRecoveryRedirectsFollowDeclaration-7373.test.ts b/ui/packages/app-shell/src/__tests__/homeRecoveryRedirectsFollowDeclaration-7373.test.ts
index 52b9c018a79..14f506ae2cf 100644
--- a/ui/packages/app-shell/src/__tests__/homeRecoveryRedirectsFollowDeclaration-7373.test.ts
+++ b/ui/packages/app-shell/src/__tests__/homeRecoveryRedirectsFollowDeclaration-7373.test.ts
@@ -142,6 +142,9 @@ const RECOVERY_SITES: ReadonlyArray<{
'packages/app-shell/src/views/studio-design/AutomationsFlowRail.tsx',
'packages/app-shell/src/views/studio-design/StudioPillarKit.tsx',
'packages/app-shell/src/views/studio-design/DataPillarHelpers.tsx',
+ 'packages/app-shell/src/views/studio-design/AutomationsPillar.tsx',
+ 'packages/app-shell/src/views/studio-design/AccessPillar.tsx',
+ 'packages/app-shell/src/views/studio-design/DataPillar.tsx',
],
site: 'Studio: the header Back to app, with no app to name',
expression: /const homePath = useHomePath\(\)/,
diff --git a/ui/packages/app-shell/src/views/studio-design/AccessPillar.tsx b/ui/packages/app-shell/src/views/studio-design/AccessPillar.tsx
new file mode 100644
index 00000000000..364777d4e56
--- /dev/null
+++ b/ui/packages/app-shell/src/views/studio-design/AccessPillar.tsx
@@ -0,0 +1,1115 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+/**
+ * The Access pillar — the permission-set rail and the embedded permission
+ * workbench — with its "New similar" arrival reader and the list-row name
+ * label only it draws, moved out of `StudioDesignSurface.tsx` unchanged by
+ * objectstack#36893 (the move-only split's pillar slice; the surface
+ * re-exports it).
+ */
+
+import * as React from 'react';
+import { useNavigate, useLocation } from 'react-router-dom';
+import { formatMetadataError } from '@object-ui/data-objectstack';
+import { type I18nLabel } from '@objectstack/spec/ui';
+import { type StudioSurfaceLabel } from './StudioAiCopilot.js';
+import { StudioItemHeader, StudioStatusChip, type StudioItemStatus } from './StudioItemHeader.js';
+import { StudioRail, StudioRailRow } from './StudioRail.js';
+import { StudioEmptyState, StudioEmptyStateAction } from './StudioEmptyState.js';
+import { pairIdOf } from './AutomationsFlowRail.js';
+import {
+ confirmDropUnsavedWork,
+ CreateTakenNotice,
+ findTakenIdentifier,
+ type StudioBaseCustomization,
+ StudioReadOnlyLink,
+} from './StudioPillarKit.js';
+import { useIsMobile } from '@object-ui/components';
+import { Copy, Shield, ShieldCheck, ShieldQuestion, Menu, Undo2 } from 'lucide-react';
+import { PermissionMatrixEditPage, type PermissionStudioTab } from '../metadata-admin/PermissionMatrixEditor.js';
+import { AccessExplainPanel } from '../metadata-admin/AccessExplainPanel.js';
+import { useMetadataClient } from '../metadata-admin/useMetadata.js';
+import { publishSavedItem } from './studioSaveBar.js';
+import { studioPillarItemPath } from './metadataArea.js';
+import { PermissionSetCloneDialog } from '../metadata-admin/PermissionSetCloneDialog.js';
+import { permissionSetCloneNoticeText, type PermissionSetCloned } from '../metadata-admin/permission-set-clone.js';
+import { useWalledCatalogReadOnly } from '../metadata-admin/catalog-scope.js';
+import { useCanAuthorMetadata } from '../../hooks/useCanAuthorMetadata.js';
+import { useMetadataRefreshNonce } from './useMetadataRefreshNonce.js';
+import { useSurfaceDeepLink, resolveSurfaceDeepLink } from './useSurfaceDeepLink.js';
+import { buildPermissionSkeleton } from './skeletons.js';
+import { t, tFormat, translateMetadataType, useMetadataLocale } from '../metadata-admin/i18n.js';
+import { SuggestedBindingsPanel } from '../../components/SuggestedBindingsPanel.js';
+import type { SuggestedBinding } from '../../services/suggestedBindingsApi.js';
+import { suggestedSetLabel as suggestedSetLabelOf } from '../../components/suggestedSetLabel.js';
+import {
+ navItemLabelText,
+} from '../metadata-admin/previews/navItemLabel.js';
+import { errorCodeIs } from '@object-ui/types';
+import { CreateItemDialog } from './CreateItemDialog.js';
+import { PackageOwdOverviewPanel } from './PackageOwdOverviewPanel.js';
+import {
+ RailCustomizationFilter,
+ RailCustomizationMark,
+ StudioPairItemChip,
+ railCustomizationsOf,
+ useDeepLinkFallback,
+ useRailCustomizationsOnly,
+} from './StudioRailCustomizations.js';
+import { toast } from 'sonner';
+
+/**
+ * A Studio list row's name (objectui#11862, on the maintainer's word
+ * 「所有地方以标签为主,机器名只作为次要信息」): the label as the primary text, and
+ * the machine name beneath it as secondary text — smaller and monospace — when
+ * it differs from the label. With no label the name alone is the text.
+ *
+ * Display only: it reads what the row already holds and writes nothing. The
+ * secondary name is `aria-hidden`, so a row's accessible name stays the label
+ * it was; the nav rail carries the machine name for assistive tech on the
+ * row's `title` (`type · name`), as it did before.
+ */
+function StudioNameLabel({ label, name }: { label: string; name?: string }): React.ReactElement {
+ const primary = label.trim() ? label : (name ?? '');
+ const secondary = name && name !== primary ? name : '';
+ return (
+
+ {primary}
+ {secondary ? (
+
+ {secondary}
+
+ ) : null}
+
+ );
+}
+
+/**
+ * objectstack#28573 — what the Access pillar's "New similar" strip says: the
+ * copy the clone door saved (shown on that copy, in the package the answer
+ * named), or an answer the pillar could not open (no copy named, or no
+ * package). `notice` is the server's sentence, and `noticeCode` the code it
+ * names it by (objectstack#29727): shown in the console's language for a known
+ * code, as sent otherwise.
+ */
+type NewSimilarStrip =
+ | { kind: 'landed'; name: string; package: string; notice: string; noticeCode?: string }
+ | { kind: 'noPackage'; name: string; notice: string; noticeCode?: string }
+ | { kind: 'noName'; notice: string; noticeCode?: string };
+
+/** The navigation-state key the copy's landing rides to the copy's pillar on. */
+const NEW_SIMILAR_ARRIVAL_STATE = 'accessNewSimilar';
+
+/**
+ * The landing a "New similar" navigation carried, for the pillar it opened:
+ * kept only when it names THIS package, so a stale history entry of another
+ * package's pillar shows nothing.
+ */
+function readNewSimilarArrival(state: unknown, packageId: string): NewSimilarStrip | null {
+ const arrival = (state as Record | null | undefined)?.[NEW_SIMILAR_ARRIVAL_STATE] as
+ | Partial>
+ | undefined;
+ if (!arrival || arrival.kind !== 'landed' || arrival.package !== packageId || typeof arrival.name !== 'string') {
+ return null;
+ }
+ return {
+ kind: 'landed',
+ name: arrival.name,
+ package: packageId,
+ notice: typeof arrival.notice === 'string' ? arrival.notice : '',
+ ...(typeof arrival.noticeCode === 'string' ? { noticeCode: arrival.noticeCode } : {}),
+ };
+}
+
+/**
+ * Access pillar — the permission workbench (builder-ui §7, ADR-0084's fourth
+ * content pillar). Left rail: the environment's permission sets / profiles;
+ * main: the Salesforce-style PermissionMatrixEditPage (objects × CRUD/VAMA +
+ * field-level R/W).
+ *
+ * Scope note (ADR-0086 P0/P1/P2): the pillar is scoped to the current package.
+ * The left rail lists only permission sets this package owns — the metadata API
+ * filters `permission` by the record-level `package_id` provenance server-side
+ * (P1), so environment-owned platform defaults (`admin_full_access`,
+ * `member_default`, …) are excluded by the backend. The object MATRIX lists only
+ * the objects this package declares, and Save merges just that slice back,
+ * leaving other packages' contributed rows untouched (P0). Save writes a package
+ * DRAFT and publishes with the whole package via the top-bar Publish (P2, D6).
+ */
+// Exported for tests — routed only through StudioDesignSurface in production.
+export function AccessPillar({
+ packageId: railPackageId,
+ publishNonce,
+ onDraftSaved,
+ readOnly: packageReadOnly = false,
+ customization = null,
+ onDirtyChange,
+ onSurfaceLabelChange,
+}: {
+ packageId: string;
+ publishNonce?: number;
+ onDraftSaved?: () => void;
+ /** Courtesy gate: hide/disable permission-authoring affordances. */
+ readOnly?: boolean;
+ /** objectstack#28572 — on a read-only base, its pair: the rail lists the pair's sets too, and New lands there. */
+ customization?: StudioBaseCustomization | null;
+ /** objectui#2600 — mirrors the pillar's unsaved-edit state (permission
+ * matrix or OWD overview rows) up to the Studio header, whose
+ * pillar/Home/package navigation unmounts this whole pillar (SPA nav, so no
+ * beforeunload). Reports `false` when the pillar unmounts, same contract as
+ * PermissionMatrixEditPage's own onDirtyChange. */
+ onDirtyChange?: (dirty: boolean) => void;
+ /**
+ * objectstack#35018 — the open set's label (or the record-visibility
+ * overview's title) for the copilot's chip: 「正在看:权限 · 组织成员」,
+ * never the type word and machine name. Same seam as the Data and
+ * Interfaces pillars' reports.
+ */
+ onSurfaceLabelChange?: (surface: StudioSurfaceLabel | null) => void;
+}): React.ReactElement {
+ const client = useMetadataClient();
+ const locale = useMetadataLocale();
+ // See DataPillar's rail — same mobile-overlay treatment for the permission-set list.
+ const isMobile = useIsMobile();
+ const [railOpen, setRailOpen] = React.useState(false);
+ // objectui#7255 — same live-pulse subscription as the sibling rails; this
+ // one only replaces the permission-set LIST, so no edit-buffer hold.
+ const metadataRefreshNonce = useMetadataRefreshNonce();
+ const [perms, setPerms] = React.useState<
+ Array<{ name: string; label: string; isDefault?: boolean; addedIn?: string }>
+ >([]);
+ const [loaded, setLoaded] = React.useState(false);
+ const [error, setError] = React.useState(null);
+ const [current, setCurrent] = React.useState(null);
+ // objectstack#28572 (ADR-0146 D3) — the rail is the base's; on a read-only
+ // base it lists the sets its pair adds too, and New lands in the pair. A set
+ // the pair adds opens writable, read and saved at the pair: the open set's
+ // matrix names `packageId` and asks `readOnly`, the open set's own. The
+ // package-wide surfaces (the OWD overview, suggested bindings, Explain)
+ // stay the base's.
+ const railPairId = packageReadOnly && customization ? customization.pairId : null;
+ const railMarks = railCustomizationsOf(customization?.marks, railPackageId);
+ const [onlyCustomized, toggleOnlyCustomized] = useRailCustomizationsOnly();
+ const newInPair = packageReadOnly && customization !== null && !customization.walled;
+ const currentAddedIn = perms.find((p) => p.name === current)?.addedIn;
+ const packageId = currentAddedIn ?? railPackageId;
+ const readOnly = packageReadOnly && !currentAddedIn;
+ // The Record Sharing Baseline (OWD) overview is a sibling surface to the
+ // permission-set matrix (objectui#2505) — same package-author ownership
+ // boundary, no principal dimension. `owdOpen` swaps the main panel to it;
+ // `owdHighlight` carries the object a permission-matrix badge deep-linked to.
+ const [owdOpen, setOwdOpen] = React.useState(false);
+ const [owdHighlight, setOwdHighlight] = React.useState(null);
+ const appliedOwdDeepLink = React.useRef(false);
+ // `?surface=permission:` / `?surface=owd:overview` capture + mirror —
+ // shared plumbing (see useSurfaceDeepLink). This rail keys `current` by name,
+ // so wrap the open surface in the identity the param carries.
+ const currentSurface = React.useMemo(
+ () =>
+ owdOpen
+ ? { type: 'owd', name: 'overview' }
+ : current
+ ? { type: 'permission', name: current }
+ : null,
+ [owdOpen, current],
+ );
+ const initialSurface = useSurfaceDeepLink(currentSurface);
+ // objectstack#28572 — see `useDeepLinkFallback`.
+ const deepLinkUpgrade = useDeepLinkFallback();
+ // objectstack#35018 — lift the open set's label to the copilot's chip, the
+ // pillar's word first: 「正在看:权限 · 组织成员」. Keyed on primitives, the
+ // callback read through a ref (the Data pillar's report).
+ const onSurfaceLabelChangeRef = React.useRef(onSurfaceLabelChange);
+ React.useEffect(() => {
+ onSurfaceLabelChangeRef.current = onSurfaceLabelChange;
+ });
+ const accessSubject = t('engine.studio.copilot.subject.access', locale);
+ const currentSetLabel = current ? perms.find((p) => p.name === current)?.label : undefined;
+ const surfaceReportLabel = owdOpen
+ ? `${accessSubject} · ${t('engine.studio.owd.title', locale)}`
+ : current && currentSetLabel
+ ? `${accessSubject} · ${currentSetLabel}`
+ : undefined;
+ const surfaceReportType = currentSurface?.type;
+ const surfaceReportName = currentSurface?.name;
+ React.useEffect(() => {
+ onSurfaceLabelChangeRef.current?.(
+ surfaceReportType && surfaceReportName && surfaceReportLabel
+ ? { type: surfaceReportType, name: surfaceReportName, label: surfaceReportLabel }
+ : null,
+ );
+ }, [surfaceReportType, surfaceReportName, surfaceReportLabel]);
+ React.useEffect(
+ () => () => {
+ onSurfaceLabelChangeRef.current?.(null);
+ },
+ [],
+ );
+ const currentRef = React.useRef(current);
+ React.useLayoutEffect(() => {
+ currentRef.current = current;
+ });
+ const [query, setQuery] = React.useState('');
+ // inline creator (same rail pattern as the Data pillar's object creator)
+ const [creating, setCreating] = React.useState(false);
+ const [createErr, setCreateErr] = React.useState(null);
+ const [busy, setBusy] = React.useState(false);
+ // objectstack#26836 — a create refused because the name is taken: which set
+ // holds it, and whether it is this package's, so the dialog can open it.
+ const [createTaken, setCreateTaken] = React.useState<{ name: string; label: string; here: boolean } | null>(null);
+ // Which of the rail's sets are published, and which hold a pending draft:
+ // the draft discard's two inputs, read by `load` with the rail.
+ const [publishedNames, setPublishedNames] = React.useState>(() => new Set());
+ const [draftNames, setDraftNames] = React.useState>(() => new Set());
+ const [discarding, setDiscarding] = React.useState(false);
+ // Bumped by a discard: the open matrix re-reads as it does after a publish,
+ // since in both its draft is gone (added to `publishNonce` below).
+ const [draftGoneNonce, setDraftGoneNonce] = React.useState(0);
+ // [ADR-0090 D6] "why can this user access?" — right-side explain sheet.
+ const [explainOpen, setExplainOpen] = React.useState(false);
+ // objectstack#28573 (ADR-0146 D6) — "New similar" on a read-only base's set:
+ // whether its dialog is open, and what the strip above the matrix says. A
+ // `landed` strip is the copy the clone door saved, shown on that copy; a
+ // `noPackage` / `noName` strip is an answer this pillar cannot open, shown
+ // on the base. The copy usually opens in ANOTHER package, which remounts
+ // this pillar (keyed by package), so the strip rides the navigation's state
+ // and is read once here.
+ const navigate = useNavigate();
+ const location = useLocation();
+ const [newSimilarOpen, setNewSimilarOpen] = React.useState(false);
+ // objectstack#32774 — the package "New similar" clones the open set from,
+ // as the matrix read it: named only where the set's name has more than one
+ // holder (`onCloneSourceRead`), so a name with one holder is cloned by name.
+ const [newSimilarSource, setNewSimilarSource] = React.useState<{ name: string; sourcePackage: string | undefined } | null>(
+ null,
+ );
+ const onCloneSourceRead = React.useCallback((name: string, sourcePackage: string | undefined) => {
+ setNewSimilarSource((prev) =>
+ prev && prev.name === name && prev.sourcePackage === sourcePackage ? prev : { name, sourcePackage },
+ );
+ }, []);
+ const [newSimilarStrip, setNewSimilarStrip] = React.useState(() => {
+ // objectstack#28572 — a copy that landed in the base's pair arrives on
+ // the base's surface; matched by the spec's pairing rule (a read).
+ const pair = pairIdOf(railPackageId);
+ return readNewSimilarArrival(location.state, railPackageId) ?? (pair ? readNewSimilarArrival(location.state, pair) : null);
+ });
+ // Who may press it: the clone door asks the metadata door's verdict
+ // (`manage_metadata`), and under a wall the catalog is the platform
+ // operator's (ADR-0131 D3), refused whatever the capability. Either way the
+ // action draws disabled, with the console's own sentence for why.
+ const canAuthorSets = useCanAuthorMetadata();
+ const walledSets = useWalledCatalogReadOnly('permission');
+ // objectui#12456 — the open set's tab (epic objectui#12446, decision C):
+ // Objects, System capabilities, Row-level security, Tab visibility,
+ // Delegated admin. Objects is the landing; the choice holds across sets.
+ const [accessTab, setAccessTab] = React.useState('objects');
+ // Both main-panel surfaces hold unsaved edits and unmount on a rail-driven
+ // swap: the matrix page is keyed by `current` (and unmounts entirely when
+ // the OWD overview swaps in), and the OWD overview batch-editor unmounts
+ // when a set swaps back in. Each editor reports its dirty state up
+ // (`onDirtyChange` — the two never coexist, so at most one bit is set), and
+ // every swap is gated on this confirm — same native prompt as the metadata
+ // editor's leave guard. Each editor resets its report on unmount, so a
+ // confirmed discard clears its bit by itself.
+ const [matrixDirty, setMatrixDirty] = React.useState(false);
+ const [owdDirty, setOwdDirty] = React.useState(false);
+ const pillarDirty = matrixDirty || owdDirty;
+ // The combined bit also gates the Studio header's pillar/Home/package
+ // navigation, which unmounts this whole pillar (objectui#2600) — mirror it
+ // up alongside the local rail guard. Ref-stabilized like the editors' own
+ // reports; the unmount cleanup reports `false` so a discarded pillar clears
+ // the surface's guard state.
+ const onDirtyChangeRef = React.useRef(onDirtyChange);
+ React.useEffect(() => {
+ onDirtyChangeRef.current = onDirtyChange;
+ });
+ React.useEffect(() => {
+ onDirtyChangeRef.current?.(pillarDirty);
+ }, [pillarDirty]);
+ React.useEffect(
+ () => () => {
+ onDirtyChangeRef.current?.(false);
+ },
+ [],
+ );
+ const confirmDiscardEdits = React.useCallback(
+ () => confirmDropUnsavedWork(pillarDirty, locale),
+ [pillarDirty, locale],
+ );
+
+ // objectstack#28572 — the latest rail read wins: a read the pair's arrival
+ // re-ran can finish before or after one a New in the pair asked for.
+ const loadSeqRef = React.useRef(0);
+ const load = React.useCallback(async (pairOverride?: string) => {
+ const seq = ++loadSeqRef.current;
+ const railPair = pairOverride ?? railPairId;
+ try {
+ // Scope the rail to this package server-side (ADR-0086 P1): the metadata
+ // API filters `permission` by the record-level `package_id` provenance, so
+ // it returns only the sets this package owns — environment-owned platform
+ // defaults (`admin_full_access`, `member_default`, …) are excluded by the
+ // backend, not the client. (The `?package=` list rows don't echo the
+ // provenance columns, so a client-side filter can't do this.)
+ //
+ // ADR-0086 P2 (D6): a package permission set is draft/published metadata,
+ // so the rail shows published ∪ pending-draft sets — a set created (or
+ // renamed) as a draft but not yet published must still appear, just like
+ // the Data/Interfaces pillars merge their drafts. Draft headers are
+ // already package-scoped by `listDrafts({ packageId })`.
+ const packageId = railPackageId;
+ // objectstack#28572 — and, on a read-only base with a pair, the pair's
+ // published and draft sets: those the base's list does not hold are the
+ // sets the pair adds. A failed pair read lists none of them.
+ const readPair = async () =>
+ railPair === null
+ ? null
+ : Promise.all([
+ client.list('permission', { packageId: railPair }) as Promise>>,
+ client.listDrafts({ packageId: railPair, type: 'permission' }).catch(() => []),
+ ]);
+ const [list, drafts, pair] = await Promise.all([
+ client.list('permission', { packageId }) as Promise>>,
+ client.listDrafts({ packageId, type: 'permission' }).catch(() => []),
+ readPair().catch(() => null),
+ ]);
+ if (seq !== loadSeqRef.current) return;
+ const byName = new Map();
+ for (const p of list || []) {
+ const name = String(p.name ?? (p as Record).id ?? '');
+ if (!name) continue;
+ byName.set(name, {
+ name,
+ label: String(p.label ?? p.name ?? ''),
+ isDefault: !!(p as Record).isDefault,
+ });
+ }
+ // objectui#11862 — a draft-only set reads as the label its `_drafts` row
+ // carries (objectstack-ai/objectstack#22200), in the designer locale; the
+ // set is not read for it (ruling `6053526025`, question 1). A row with
+ // no label leaves `label` empty, and the rail shows the name alone.
+ for (const d of (drafts as Array<{ name?: string; label?: I18nLabel | null }>) || []) {
+ const name = String(d?.name ?? '');
+ if (!name || byName.has(name)) continue;
+ byName.set(name, { name, label: navItemLabelText(d?.label ?? undefined, locale).trim() });
+ }
+ const [pairList, pairDrafts] = pair ?? [[], []];
+ if (railPair !== null) {
+ for (const p of pairList || []) {
+ const name = String(p.name ?? (p as Record).id ?? '');
+ if (!name || byName.has(name)) continue;
+ byName.set(name, { name, label: String(p.label ?? p.name ?? ''), addedIn: railPair });
+ }
+ for (const d of (pairDrafts as Array<{ name?: string; label?: I18nLabel | null }>) || []) {
+ const name = String(d?.name ?? '');
+ if (!name || byName.has(name)) continue;
+ byName.set(name, { name, label: navItemLabelText(d?.label ?? undefined, locale).trim(), addedIn: railPair });
+ }
+ }
+ const scoped = [...byName.values()];
+ setPerms(scoped);
+ const nameOf = (p: Record) => String(p.name ?? p.id ?? '');
+ setPublishedNames(new Set([...(list || []), ...(pairList || [])].map(nameOf)));
+ setDraftNames(
+ new Set(
+ [...((drafts as Array<{ name?: string }>) || []), ...((pairDrafts as Array<{ name?: string }>) || [])]
+ .map((d) => String(d?.name ?? ''))
+ .filter(Boolean),
+ ),
+ );
+ // A `?surface=owd:overview` deep-link opens the OWD overview instead of a
+ // permission set; `current` still defaults to the first set so switching
+ // back to the matrix has a target. Applied once — a later publish re-runs
+ // `load`, and we must not yank the user back to OWD then.
+ if (!appliedOwdDeepLink.current && initialSurface?.type === 'owd') {
+ appliedOwdDeepLink.current = true;
+ setOwdOpen(true);
+ }
+ const deepLinked = resolveSurfaceDeepLink(scoped, initialSurface, 'permission');
+ // objectstack#28572 — a set the pair adds is listed once the pair is
+ // known (`useDeepLinkFallback`).
+ if (deepLinked && deepLinkUpgrade.take(currentRef.current, deepLinked.name)) {
+ setCurrent(deepLinked.name);
+ } else {
+ if (!deepLinked && initialSurface?.type === 'permission' && currentRef.current === null) {
+ deepLinkUpgrade.note(scoped[0]?.name ?? null);
+ }
+ setCurrent((c) => c ?? deepLinked?.name ?? scoped[0]?.name ?? null);
+ }
+ } catch (e) {
+ if (seq === loadSeqRef.current) setError(formatMetadataError(e));
+ } finally {
+ if (seq === loadSeqRef.current) setLoaded(true);
+ }
+ }, [client, railPackageId, railPairId, locale]);
+
+ React.useEffect(() => {
+ void load();
+ // Re-read after a package publish so drafts that went live collapse into
+ // the published rail (ADR-0086 P2), and on the live-metadata pulse so a
+ // copilot turn's permission set appears without a page reload (#7255).
+ }, [load, publishNonce, metadataRefreshNonce]);
+
+ const doCreate = React.useCallback(
+ async (label: string, name: string) => {
+ setBusy(true);
+ setCreateErr(null);
+ setCreateTaken(null);
+ try {
+ // A name a permission set already holds, published or as a draft, in
+ // this package or any other, is refused here and nothing is written:
+ // over a published set the first-write pin below would write this
+ // blank skeleton as its pending draft (`findTakenIdentifier`).
+ const taken = await findTakenIdentifier(client, 'permission', name, locale);
+ if (taken) {
+ setCreateTaken({ ...taken, here: perms.some((p) => p.name === name) });
+ return;
+ }
+ // objectstack#28572 (ADR-0146 D3) — on a read-only base the set is
+ // created in its pair, which the ensure door answers (creating it on
+ // first use, without a prompt).
+ const target =
+ packageReadOnly && customization ? (await customization.ensurePackage()).packageId : railPackageId;
+ // Package door → a DRAFT stamped with this package (D6/D7).
+ // objectui#11773 — and the door refuses a draft row too (the
+ // first-write pin), for one that lands between the check above and
+ // this save. A set published in that window is not refused by it.
+ await client.save('permission', name, buildPermissionSkeleton(name, label), {
+ mode: 'draft',
+ packageId: target,
+ ifNoneMatch: '*',
+ surface: 'studio',
+ });
+ // objectstack#36511 — then that one set is published, so it is live at
+ // once like every Save in Studio. A refused publish takes back the
+ // draft it wrote, so nothing is created, and says why.
+ const live = await publishSavedItem(client, { type: 'permission', name, packageId: target }, false);
+ if (!live.ok) {
+ setCreateErr(formatMetadataError(live.error));
+ return;
+ }
+ toast.success(tFormat('engine.studio.access.created', locale, { label }));
+ setCreating(false);
+ // A set made in the pair is read back from the pair the door named.
+ await load(target === railPackageId ? undefined : target);
+ // Land on the new set's matrix — also from the OWD overview, whose
+ // discard the "+ New" gate already confirmed up front.
+ setOwdOpen(false);
+ setCurrent(name);
+ } catch (e) {
+ // objectstack#26846 — the first-write pin's refusal, for a draft that
+ // landed after the check above, read by its code: this create sent
+ // the pin, so a conflict means the identifier holds a draft. The
+ // door's sentence speaks of the pin itself and is not shown.
+ setCreateErr(
+ errorCodeIs(e, 'METADATA_CONFLICT')
+ ? tFormat('engine.studio.access.createDraftTaken', locale, { name })
+ : formatMetadataError(e),
+ );
+ } finally {
+ setBusy(false);
+ }
+ },
+ [client, load, railPackageId, packageReadOnly, customization, locale, perms],
+ );
+
+ // The refusal's way out: the taken set is this package's, so it opens in
+ // the matrix instead of a second one being made. The "+ New" gate already
+ // confirmed any discard of unsaved edits.
+ const openTakenSet = React.useCallback((name: string) => {
+ setCreating(false);
+ setCreateTaken(null);
+ setOwdOpen(false);
+ setCurrent(name);
+ }, []);
+
+ // objectstack#28573 — the clone door saved a copy of the open set. It opens
+ // only where the answer says it landed: that package's Access pillar with
+ // the copy selected. An answer that names no copy, or no package, is said
+ // so and opens nothing; the landing is never derived from the base.
+ const onNewSimilarSaved = React.useCallback(
+ (copy: PermissionSetCloned) => {
+ setNewSimilarOpen(false);
+ if (!copy.name) {
+ setNewSimilarStrip({ kind: 'noName', notice: copy.notice, noticeCode: copy.noticeCode });
+ return;
+ }
+ if (typeof copy.package !== 'string') {
+ setNewSimilarStrip({ kind: 'noPackage', name: copy.name, notice: copy.notice, noticeCode: copy.noticeCode });
+ return;
+ }
+ const landed: NewSimilarStrip = {
+ kind: 'landed',
+ name: copy.name,
+ package: copy.package,
+ notice: copy.notice,
+ noticeCode: copy.noticeCode,
+ };
+ // objectstack#28572 — the pair's sets are this surface's too.
+ if (copy.package === railPackageId || (railPairId !== null && copy.package === railPairId)) {
+ setNewSimilarStrip(landed);
+ setOwdOpen(false);
+ setCurrent(copy.name);
+ void load();
+ return;
+ }
+ navigate(studioPillarItemPath(copy.package, 'access', { type: 'permission', name: copy.name }), {
+ state: { [NEW_SIMILAR_ARRIVAL_STATE]: landed },
+ });
+ },
+ [railPackageId, railPairId, navigate, load],
+ );
+
+ // Discard the open set's pending draft (`DELETE ?state=draft` at this
+ // package's address, the door the metadata editor's "Discard draft" uses).
+ // A published set goes back to its live body; a set that was never
+ // published has nothing left, so it leaves the rail.
+ const discardDraft = React.useCallback(
+ async (name: string) => {
+ const row = perms.find((p) => p.name === name);
+ const item = row?.label || name;
+ const neverPublished = !publishedNames.has(name);
+ // One confirm: an unsaved edit on the open matrix is an unpublished
+ // change of this same set, and the discard removes it with the rest.
+ if (
+ !window.confirm(
+ tFormat(
+ neverPublished ? 'engine.studio.access.discardConfirmUnpublished' : 'engine.studio.access.discardConfirm',
+ locale,
+ { item },
+ ),
+ )
+ ) {
+ return;
+ }
+ setDiscarding(true);
+ try {
+ await client.reset('permission', name, { state: 'draft', packageId });
+ toast.success(tFormat('engine.edit.draftDiscarded', locale, { item }));
+ if (neverPublished) setCurrent((c) => (c === name ? null : c));
+ // The open matrix holds the discarded draft and the pin it was read
+ // with: read it again, as after a publish (its draft is gone).
+ setDraftGoneNonce((n) => n + 1);
+ onDraftSaved?.();
+ await load();
+ } catch (e) {
+ toast.error(t('engine.studio.access.discardFailed', locale), {
+ description: formatMetadataError(e),
+ classNames: { description: 'whitespace-pre-line' },
+ });
+ } finally {
+ setDiscarding(false);
+ }
+ },
+ [perms, publishedNames, locale, client, packageId, onDraftSaved, load],
+ );
+
+ const filtered = perms.filter(
+ (p) =>
+ (!query.trim() ||
+ p.label.toLowerCase().includes(query.trim().toLowerCase()) ||
+ p.name.toLowerCase().includes(query.trim().toLowerCase())) &&
+ // objectstack#28572 — "only customizations" keeps the marked rows.
+ (!onlyCustomized || railMarks?.markOf({ type: 'permission', ...p }) != null),
+ );
+ const markedSets = railMarks ? perms.filter((p) => railMarks.markOf({ type: 'permission', ...p }) !== null).length : 0;
+
+ // objectui#12459 — the item header inside the content column. The
+ // "Permission matrix" band above the rail retires. objectui#12456 — an
+ // open set's header is the matrix page's own (its label, api name, Package
+ // chip, granted / override counts, History, the tab row), fed the three
+ // pieces below; this pillar draws the header for the OWD overview and for
+ // the empty states.
+ const accessRailToggleEl = (
+
+ );
+ // objectui#11781 — "saved as draft" is what an editable package does. A
+ // read-only one saves nothing: objectui#12453 puts the read-only link where
+ // the note was, and the link's title carries the note's sentence. An open
+ // set's header draws it at the tab row's right end (objectui#12456: the
+ // title row truncated the set's label at the 1280 px design width).
+ // objectui#12524 — the writable note is this pillar's draft status: the
+ // header draws it in the status place every pillar shares. The read-only
+ // link is an action, so it stays in the actions slot.
+ // The note speaks for what the main panel shows: the open set, or the
+ // package-wide OWD overview and empty header, which are the base's.
+ const noteReadOnly = owdOpen || current === null ? packageReadOnly : readOnly;
+ // objectstack#29674 — an open set the pair adds lists its base's objects
+ // too (`permissionObjectScopePackages`), so its note names the base instead
+ // of claiming "this package's objects" only.
+ const notePairBase = !owdOpen && current !== null && currentAddedIn ? (customization?.baseLabel ?? railPackageId) : null;
+ const accessStatus: StudioItemStatus | undefined = noteReadOnly
+ ? undefined
+ : notePairBase !== null
+ ? {
+ label: tFormat('engine.studio.access.bannerPair', locale, { package: notePairBase }),
+ title: tFormat('engine.studio.access.bannerTitlePair', locale, { package: notePairBase }),
+ }
+ : { label: t('engine.studio.access.banner', locale), title: t('engine.studio.access.bannerTitle', locale) };
+ const accessNoteEl = accessStatus ? (
+
+ ) : (
+
+ );
+ const accessExplainEl = (
+
+ );
+ // The rail's "+" — and the empty block's button, which runs this same
+ // handler (objectui#12514). Creating a set lands on the new set's matrix — a
+ // remount of the open matrix, or a swap out of the OWD overview — so gate
+ // the flow up front.
+ const openCreateSet = packageReadOnly && !newInPair
+ ? undefined
+ : () => {
+ if (!confirmDiscardEdits()) return;
+ setCreateErr(null);
+ setCreateTaken(null);
+ setCreating(true);
+ };
+ // objectstack#26836 — the open set's pending draft can be discarded where
+ // the set is edited; nothing in Studio offered it, so a blank draft over a
+ // live set could only be published.
+ const accessDiscardEl =
+ !readOnly && current && !owdOpen && draftNames.has(current) ? (
+
+ ) : null;
+ // objectstack#28573 (ADR-0146 D6) — a read-only base's set offers "New
+ // similar", never an override: the copy is a NEW set, in the package the
+ // clone door chooses. Disabled, it says why in the console's words.
+ const newSimilarBlocked = walledSets
+ ? tFormat('engine.catalog.readOnly.walled', locale, { type: translateMetadataType('permission', locale) })
+ : canAuthorSets
+ ? null
+ : t('engine.edit.capabilityReadOnly', locale);
+ const accessNewSimilarEl =
+ readOnly && current && !owdOpen ? (
+
+
+ {newSimilarBlocked !== null && (
+
+ {newSimilarBlocked}
+
+ )}
+
+ ) : null;
+ const newSimilarStripEl =
+ newSimilarStrip && !owdOpen && (newSimilarStrip.kind !== 'landed' || newSimilarStrip.name === current) ? (
+
+ ) : null;
+ const accessHeaderEl = (
+
+ {noteReadOnly && accessNoteEl}
+ {accessExplainEl}
+ >
+ }
+ />
+ );
+
+ // A suggestion names its set by machine name only; the banner, its toasts
+ // and its state lines name it by the label the rail shows for that set
+ // (`ux-conventions.labels-over-machine-names`). The suggestions listed here
+ // are this package's own sets, which the rail read; a set the rail does not
+ // hold, or one with no label, is named by its machine name.
+ const suggestedSetLabel = (s: SuggestedBinding): string => suggestedSetLabelOf(s, perms);
+
+ return (
+
+ {/* ADR-0090 D5/D9 — this package's suggested audience bindings
+ (isDefault sets shipped by the package) and the deployment's
+ decision on each. Renders nothing when there are none or for a
+ caller without manage_metadata (the list answers 403); accept and
+ revoke are enforced server-side by the anchor gates. Drawn on a
+ read-only package too: accepting or dismissing a suggestion is a
+ deployment decision about the package, not an edit of it, and a
+ marketplace-installed package — read-only here — is the one that
+ ships an isDefault set. Only this strip ignores `packageReadOnly`;
+ every affordance that edits the package keeps its gate. */}
+
+ tFormat(
+ s.anchor === 'guest'
+ ? 'engine.studio.access.suggestPromptGuest'
+ : 'engine.studio.access.suggestPromptEveryone',
+ locale,
+ { set: suggestedSetLabel(s) },
+ ),
+ confirm: t('engine.studio.access.suggestConfirm', locale),
+ confirming: t('engine.studio.access.suggestConfirming', locale),
+ dismiss: t('engine.studio.access.suggestDismiss', locale),
+ confirmedToast: (s) =>
+ tFormat('engine.studio.access.suggestConfirmedToast', locale, {
+ set: suggestedSetLabel(s),
+ anchor: s.anchor,
+ }),
+ dismissedToast: (s) =>
+ tFormat('engine.studio.access.suggestDismissedToast', locale, { set: suggestedSetLabel(s) }),
+ guestUnsupported: t('engine.studio.access.suggestGuestUnsupported', locale),
+ acceptedState: (s) =>
+ tFormat('engine.studio.access.suggestAcceptedState', locale, { set: suggestedSetLabel(s) }),
+ notInForceState: (s) =>
+ tFormat('engine.studio.access.suggestNotInForceState', locale, { set: suggestedSetLabel(s) }),
+ dismissedState: (s) =>
+ tFormat('engine.studio.access.suggestDismissedState', locale, { set: suggestedSetLabel(s) }),
+ revoke: t('engine.studio.access.suggestRevoke', locale),
+ revoking: t('engine.studio.access.suggestRevoking', locale),
+ revokedToast: (s) =>
+ tFormat('engine.studio.access.suggestRevokedToast', locale, { set: suggestedSetLabel(s) }),
+ reopen: t('engine.studio.access.suggestReopen', locale),
+ reopening: t('engine.studio.access.suggestReopening', locale),
+ reopenedToast: (s) =>
+ tFormat('engine.studio.access.suggestReopenedToast', locale, { set: suggestedSetLabel(s) }),
+ }}
+ />
+
+
+ {isMobile && railOpen && (
+
setRailOpen(false)}
+ aria-hidden="true"
+ />
+ )}
+
+ }
+ pinned={
+ // Pinned sibling surface: the package-wide Record Sharing Baseline
+ // (OWD) overview (objectui#2505). Same package-author ownership as
+ // the sets below, but a distinct surface — not a permission set.
+
+ {
+ // Re-clicking the open overview is a no-op — nothing
+ // remounts, so no confirm (mirrors the set re-click below).
+ if (owdOpen) {
+ setOwdHighlight(null);
+ if (isMobile) setRailOpen(false);
+ return;
+ }
+ if (!confirmDiscardEdits()) return;
+ setOwdOpen(true);
+ setOwdHighlight(null);
+ if (isMobile) setRailOpen(false);
+ }}
+ icon={}
+ className="font-medium"
+ >
+ {t('engine.studio.owd.railLabel', locale)}
+
+
+ }
+ isMobile={isMobile}
+ open={railOpen}
+ >
+ {/* objectui#12514 — the empty sentence names the "+" it points at;
+ without one, the content column's block speaks alone. */}
+ {perms.length === 0 && (error || !loaded || openCreateSet) && (
+
+ )}
+ {filtered.map((p) => (
+ {
+ if (!owdOpen && current === p.name) {
+ if (isMobile) setRailOpen(false);
+ return;
+ }
+ if (!confirmDiscardEdits()) return;
+ setOwdOpen(false);
+ setCurrent(p.name);
+ if (isMobile) setRailOpen(false);
+ }}
+ icon={}
+ name={p.label.trim() ? p.label : p.name}
+ trailing={
+ <>
+
+ {p.isDefault ? (
+ {t('perm.badge.default', locale)}
+ ) : null}
+ >
+ }
+ >
+ {/* objectui#11862 — the set's label. objectstack#34795: the
+ machine name is no longer drawn as secondary text; it is the
+ row's tooltip. A set listed from its draft header alone has
+ no label in hand (the header carries none), so its name is
+ the text, as before. */}
+
+
+
+
+ ))}
+
+
+
+ {(owdOpen || !current) && accessHeaderEl}
+ {newSimilarStripEl}
+
+ {owdOpen ? (
+ /* Sibling surface: the package-wide OWD baseline overview
+ * (objectui#2505) — object × sharingModel,
+ * batch-edited as per-object drafts. */
+
+ ) : current ? (
+ /* The existing Salesforce-style matrix page in its Studio
+ * presentation (objectui#12456): the item header and five tabs
+ * are the page's own, its autosave + destructive-change guard
+ * included. The OWD chip deep-links to the overview above. */
+ {
+ // The set now holds a pending draft, so its discard shows.
+ setDraftNames((names) => (names.has(current) ? names : new Set(names).add(current)));
+ onDraftSaved?.();
+ // objectstack#26846 — and the rail reads the sets again, so a
+ // label this save changed shows there without a publish or a
+ // reload.
+ void load();
+ }}
+ onSaved={() => {
+ // objectstack#36511 — the top bar's Save published the set: no
+ // draft of it is left, and the rail reads its label again.
+ setDraftNames((names) => {
+ if (!names.has(current)) return names;
+ const next = new Set(names);
+ next.delete(current);
+ return next;
+ });
+ void load();
+ }}
+ readOnly={readOnly}
+ onDirtyChange={setMatrixDirty}
+ embedded
+ // objectstack#29809 — the header's provenance chip reads the
+ // mark this set's rail row draws, so the two tell one story.
+ customizationMark={railMarks?.markOf({ type: 'permission', name: current, addedIn: currentAddedIn }) ?? null}
+ studio={{
+ tab: accessTab,
+ onTabChange: setAccessTab,
+ onCloneSourceRead,
+ leading: accessRailToggleEl,
+ chips: currentAddedIn ? (
+ <>
+
+ {accessNoteEl}
+ >
+ ) : (
+ accessNoteEl
+ ),
+ actions: (
+ <>
+ {accessNewSimilarEl}
+ {accessDiscardEl}
+ {accessExplainEl}
+ >
+ ),
+ }}
+ onOpenOwd={(objectName) => {
+ // The badge deep-link swaps this page out for the OWD
+ // overview — same remount, same guard.
+ if (!confirmDiscardEdits()) return;
+ setOwdHighlight(objectName || null);
+ setOwdOpen(true);
+ }}
+ />
+ ) : loaded && !error && perms.length === 0 ? (
+ // objectui#12514 — one centered block whose button runs the rail's "+".
+
+
+ )
+ }
+ />
+
+ ) : null}
+
+
+
+
+
+
+ {/* objectstack#28573 — the clone door's dialog, shared with Setup's
+ catalog: a name and a label, nothing else, refusals verbatim. */}
+ {newSimilarOpen && current && (
+ setNewSimilarOpen(false)}
+ onCloned={onNewSimilarSaved}
+ />
+ )}
+
+ openTakenSet(createTaken.name) : undefined}
+ />
+ )
+ }
+ onSubmit={({ label, name }) => void doCreate(label, name)}
+ />
+
+ );
+}
diff --git a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.tsx b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.tsx
new file mode 100644
index 00000000000..a2d33fe0d4a
--- /dev/null
+++ b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.tsx
@@ -0,0 +1,2236 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+/**
+ * The Automations pillar — the flow rail, the flow canvas and its inspectors,
+ * the New automation dialog — with the published-flow-names read only it makes,
+ * moved out of `StudioDesignSurface.tsx` unchanged by objectstack#36893 (the
+ * move-only split's pillar slice; the surface re-exports it).
+ */
+
+import * as React from 'react';
+import { createPortal } from 'react-dom';
+import { useNavigate, useLocation } from 'react-router-dom';
+import { extractDraftBody, formatMetadataError, readDraftChanges, type DraftChange } from '@object-ui/data-objectstack';
+import type { MetadataClient } from '@object-ui/data-objectstack';
+import { type StudioSurfaceLabel } from './StudioAiCopilot.js';
+import { isSlotEscapeExempt, useStudioRightSlot } from './studioRightSlotState.js';
+import { AUTOMATIONS_CONFIG_FOLD_WIDTH, useIsNarrowerThan } from './wideViewport.js';
+import { STUDIO_FOLD_LABEL } from './studio-tokens.js';
+import { StudioInspector } from './StudioInspector.js';
+import { isAgentDraftSurface } from './StudioDraftMark.js';
+import { StudioAiDraftNotice } from './StudioAiDraftNotice.js';
+import { StudioItemHeader, StudioTab } from './StudioItemHeader.js';
+import { StudioItemTools } from '../item-tools/StudioItemTools.js';
+import { useStudioItemDraftStatus } from './studioItemDraftStatus.js';
+import { FlowItemMoreMenu, flowCloneNoticeText, type FlowCopied } from './FlowItemMoreMenu.js';
+import { FlowLedgerSwitch } from './FlowLedgerSwitch.js';
+import { requestFlowToggle, useFlowLedgerWalledReadOnly } from '../setup/packagedFlowLedger.js';
+import { activationReading } from '../setup/packagedFlows.js';
+import { StudioRail, StudioRailGroup, StudioRailRow } from './StudioRail.js';
+import { StudioEmptyState, StudioEmptyStateAction } from './StudioEmptyState.js';
+import { FLOW_TRIGGER_GLYPHS, flowTriggerGlyph, groupFlowsByObject } from './flowGrouping.js';
+import { StudioRefusalStrip } from './StudioRefusalStrip.js';
+import { StudioPicker } from './StudioPicker.js';
+import {
+ FLOW_COPIED_ARRIVAL_STATE,
+ FLOW_GLYPH_ICON,
+ FLOW_GLYPH_LABEL_KEY,
+ type FlowCopiedStrip,
+ flowDotClass,
+ type FlowRailState,
+ flowRailState,
+ flowRailStatus,
+ type FlowRuntimeState,
+ FlowStatusDot,
+ type NewFlowTrigger,
+ newFlowTriggerFields,
+ NO_OBJECT_GROUP_KEY,
+ NO_OBJECT_ORDER,
+ pairIdOf,
+ readFlowCopiedArrival,
+ readFlowDefinitions,
+ readFlowRegistrations,
+ readObjectLabels,
+ withStartTrigger,
+} from './AutomationsFlowRail.js';
+import {
+ confirmDropUnsavedWork,
+ CreateTakenNotice,
+ findTakenIdentifier,
+ type StudioBaseCustomization,
+ StudioHeldNotice,
+ StudioReadOnlyLink,
+ type StudioSavedDraft,
+ useHeldEditReport,
+ useShowInputFocus,
+} from './StudioPillarKit.js';
+import {
+ useIsMobile,
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from '@object-ui/components';
+import { Ban, Workflow, SlidersHorizontal, MousePointer2, Loader2, Lock, Menu } from 'lucide-react';
+import {
+ useRegisteredMetadataPreview,
+ useRegisteredMetadataPreviewTypes,
+ type MetadataSelection,
+} from '../metadata-admin/preview-registry.js';
+import {
+ useRegisteredMetadataInspector,
+ useRegisteredMetadataInspectorTypes,
+} from '../metadata-admin/inspector-registry.js';
+import { useMetadataClient } from '../metadata-admin/useMetadata.js';
+import { readDraftForSave, useDraftSaveGuard } from '../metadata-admin/DraftConflictDialog.js';
+import {
+ DraftVerdictContext,
+ draftEnvelopeDiagnostics,
+ editedItemDiagnostics,
+ verdictPreviewEntries,
+ type ServerDiagnostics,
+} from '../metadata-admin/draftVerdict.js';
+import { emitMetadataRefresh } from '../../assistant/assistantBus.js';
+import { publishSavedItem, STUDIO_SAVE_TOAST_ID, useStudioSaveEntry, type StudioSaveResult } from './studioSaveBar.js';
+import {
+ flowHeldEdit,
+ flowSaveRefusal,
+ plainRefusal,
+ publishFailureOf,
+ publishRefusal,
+ type StudioRefusal,
+} from './metadataError.js';
+import {
+ loadPackageLessSurfaces,
+ loadPackageSurfaces,
+} from './packageSurfaces.js';
+import { studioOrgScopePath } from './studioScope.js';
+import { studioPillarItemPath } from './metadataArea.js';
+import { useCanAuthorMetadata } from '../../hooks/useCanAuthorMetadata.js';
+import { useMetadataRefreshNonce } from './useMetadataRefreshNonce.js';
+import { type Surface } from './navSurface.js';
+import { useSurfaceDeepLink, resolveSurfaceDeepLink } from './useSurfaceDeepLink.js';
+import { buildFlowSkeleton } from './skeletons.js';
+import { t, tFormat, translateValidationMessage, useMetadataLocale } from '../metadata-admin/i18n.js';
+import { ObjectPicker } from '../metadata-admin/inspectors/ObjectPicker.js';
+import {
+ FlowRegistrationContext,
+ FlowRuntimeContext,
+ deriveFlowRunStatus,
+ type FlowRunStatus,
+} from '../metadata-admin/previews/flow-problems.js';
+import {
+ FlowMetaPills,
+ FlowPreviewChromeProvider,
+ FlowSelectionTitle,
+ flowSelectionHeading,
+ type FlowPreviewSection,
+ type FlowProblemTally,
+} from '../metadata-admin/previews/FlowPreview.js';
+import { InspectorShellHostProvider } from '../metadata-admin/inspectors/_shared.js';
+import { useFlowLabelOf, useFlowLabelTranslations } from '../metadata-admin/previews/flow-label-translations.js';
+import type { FlowRegistration } from '@objectstack/spec/api';
+import { CreateItemDialog } from './CreateItemDialog.js';
+import { FLOW_PRESETS, flowPresetTrigger, type FlowPreset } from './flowPresets.js';
+import {
+ ContributedRailRow,
+ RailCustomizationFilter,
+ RailCustomizationMark,
+ StudioPairItemChip,
+ contributedItemTitle,
+ railCustomizationsOf,
+ useOpenContributor,
+ useRailCustomizationsOnly,
+ withPairItems,
+} from './StudioRailCustomizations.js';
+import { baseContributionsOf, withContributedFlowGroups, type ContributedOnObject } from './contributionRows.js';
+import {
+ StudioCustomizeButton,
+ StudioOverrideChip,
+ StudioRestoreOriginalDialog,
+ overrideDraftBody,
+ useServedOverride,
+ type CustomizeBlock,
+} from './StudioCustomizeControls.js';
+import { SavedToCustomizationNote } from '../../preview/savedToCustomization.js';
+import { toast } from 'sonner';
+
+/**
+ * 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,
+ objectOrder = NO_OBJECT_ORDER,
+ publishNonce = 0,
+ onDraftSaved,
+ readOnly: packageReadOnly = false,
+ customization = null,
+ onHeldEditChange,
+ onSurfaceLabelChange,
+}: {
+ /**
+ * The package whose flows the rail lists, or `null` for the package-less
+ * scope (objectui#11553, `studioScope.ts`): every flow that belongs to no
+ * package, saved as package-less drafts.
+ */
+ packageId: string | null;
+ /**
+ * objectui#12612 — the objects the package app's navigation lists, in its
+ * order (`navigationObjectOrder`): the rail's groups follow it. The shell
+ * reads it with the package's app; none (the package-less scope, a package
+ * without an app) leaves every group ordered by its flow count.
+ */
+ objectOrder?: readonly string[];
+ publishNonce?: number;
+ onDraftSaved?: (saved?: StudioSavedDraft) => void;
+ /** Courtesy gate: hide/disable flow-authoring affordances. */
+ readOnly?: boolean;
+ /** objectstack#28572 — on a read-only base, its pair: the rail lists the pair's flows too, and New lands there. */
+ customization?: StudioBaseCustomization | null;
+ /** objectui#11786 — the clause of the edit the autosave holds unsent, for the surface's Publish. */
+ onHeldEditChange?: (clause: string | null) => void;
+ /**
+ * objectstack#35018 — the open flow's label for the copilot's chip:
+ * 「正在看:流程 · 新会议提醒」, never the type word and machine name.
+ */
+ onSurfaceLabelChange?: (surface: StudioSurfaceLabel | null) => void;
+}): React.ReactElement {
+ const client = useMetadataClient();
+ const locale = useMetadataLocale();
+ const navigate = useNavigate();
+ const location = useLocation();
+ // objectstack#28572 (ADR-0146 D3) — the rail is the base's; on a read-only
+ // base it lists the flows its pair adds too, and New lands in the pair.
+ const railPairId = packageReadOnly && railPackageId !== null && customization ? customization.pairId : null;
+ const railMarks = railPackageId === null ? null : railCustomizationsOf(customization?.marks, railPackageId);
+ const [onlyCustomized, toggleOnlyCustomized] = useRailCustomizationsOnly();
+ const newInPair = packageReadOnly && railPackageId !== null && customization !== null && !customization.walled;
+ // objectstack#28567 — "New similar" (`FlowItemMoreMenu`): the strip that
+ // shows the copy the clone door saved, with the door's sentence that it is
+ // switched off, as sent. The copy usually opens in ANOTHER package (a
+ // read-only base's pair), which remounts this pillar (keyed by package), so
+ // the landing rides the navigation's state and is read once here.
+ const [flowCopied, setFlowCopied] = React.useState(
+ () =>
+ readFlowCopiedArrival(location.state, railPackageId) ??
+ // objectstack#28572 — a copy that landed in the base's pair arrives on
+ // the base's surface (the pair's URL lands there). Matched by the spec's
+ // pairing rule: a read of where the copy went, never a write target.
+ (railPackageId !== null ? readFlowCopiedArrival(location.state, pairIdOf(railPackageId)) : null),
+ );
+ // The copy to open once the rail re-reads, when it landed in THIS package.
+ const openAfterListRef = React.useRef(null);
+ const canAuthorFlows = useCanAuthorMetadata();
+ // See DataPillar's rail — same mobile-overlay treatment for the flow list.
+ const isMobile = useIsMobile();
+ const [railOpen, setRailOpen] = React.useState(false);
+ // objectui#11795 — on a row too narrow for the Configuration aside to sit
+ // beside the canvas (`AUTOMATIONS_CONFIG_FOLD_WIDTH`), the aside folds away
+ // and a selection opens the same configuration as a drawer over the canvas,
+ // so the canvas keeps the row's width. Wider rows keep the aside as it was.
+ const layoutRowRef = React.useRef(null);
+ const configFolded = useIsNarrowerThan(layoutRowRef, AUTOMATIONS_CONFIG_FOLD_WIDTH);
+ const [flows, setFlows] = React.useState([]);
+ // objectui#11794 — the rail's search: a case-insensitive match on the label
+ // or the machine name. Ephemeral (AGENTS.md #8): nobody expects it back.
+ const [railQuery, setRailQuery] = React.useState('');
+ const railNeedle = railQuery.trim().toLowerCase();
+ // objectstack#35319 — a row names its flow as the open flow's header does:
+ // the package's `flows.NAME.label` in the console's language, else the
+ // authored label. The search matches that name, the authored label and the
+ // machine name, so what the row shows is always searchable.
+ const flowLabelOf = useFlowLabelOf();
+ const railLabel = (f: Surface) => flowLabelOf(f.name) || f.label;
+ const flowMatches = (f: Surface) =>
+ [railLabel(f), f.label, f.name].some((text) => text.toLowerCase().includes(railNeedle));
+ // objectstack#28572 — "only customizations" keeps the marked rows.
+ const flowShown = (f: Surface) =>
+ (!railNeedle || flowMatches(f)) && (!onlyCustomized || railMarks?.markOf(f) != null);
+ const shownFlows = flows.filter(flowShown);
+ const markedFlows = railMarks ? flows.filter((f) => railMarks.markOf(f) !== null).length : 0;
+ // objectui#7255 — same live-pulse subscription as the sibling rails; this
+ // one only replaces the flow LIST, so it needs no edit-buffer hold either.
+ const metadataRefreshNonce = useMetadataRefreshNonce();
+ const [current, setCurrent] = React.useState(null);
+ // objectstack#28572 — a flow the pair adds (`current.addedIn`) opens
+ // writable, read and saved at the pair: every read and write of the OPEN
+ // flow below names `packageId` and asks `readOnly`, the open flow's own.
+ const packageId: string | null = current?.addedIn ?? railPackageId;
+ const readOnly = packageReadOnly && !current?.addedIn;
+ // The draft writes' package binding (objectui#11553): none in the
+ // package-less scope, so the draft row stays as package-less as the flow it
+ // edits. The client sends no `package=` for an absent id.
+ const draftPackageId = packageId ?? undefined;
+ // objectstack#28570 (ADR-0146 D9 items 1–3, D2) — Customize a flow. On a
+ // read-only base its flow is edited in the base's paired customization
+ // package under the flow's own name, as a declared override of the base's
+ // flow, with N-17's control and ensure door. Its editors stay read-only
+ // until Customize is pressed, or while the server serves no override of
+ // it; nothing is written until an edit is saved. ⛔ The pair a write names
+ // is the door's answer; the pair a READ names is the surface's, read
+ // through this ref, so a pair the first save creates never reloads the
+ // buffer it saved. Whether the flow is overridden is the declared
+ // override's own row as served (`useServedOverride`: the pair's draft, else
+ // the layered read's `overlay`), ⛔ never the served envelope's
+ // `deletable`, which follows the base's seal.
+ const customizationRef = React.useRef(customization);
+ React.useLayoutEffect(() => {
+ customizationRef.current = customization;
+ });
+ const flowCustomizing = packageReadOnly && railPackageId !== null && customization !== null;
+ const customizeBase = flowCustomizing && customization ? customization.base : null;
+ const customizePair = flowCustomizing && customization ? customization.pairId : null;
+ const customizeBaseLabel = customization?.baseLabel ?? railPackageId ?? '';
+ // objectstack#30436 — the pair the "saved to" note names.
+ const customizeNotePair = customization ? (customization.pairId ?? pairIdOf(customization.base)) : null;
+ const customizeWalled = flowCustomizing && customization?.walled === true;
+ const customizeBlock: CustomizeBlock = customizeWalled
+ ? 'walled'
+ : flowCustomizing && !customization?.basedOn
+ ? 'noVersion'
+ : null;
+ const flowCustomizable = flowCustomizing && !!current && !current.addedIn;
+ // The flows Customize was pressed on, by name: unlocked, nothing saved yet.
+ const [customizeAsked, setCustomizeAsked] = React.useState>(() => new Set());
+ // The ensure door's answer for each flow's first saved edit: asked once per
+ // flow, and again only after a refusal.
+ const pairsByFlowRef = React.useRef(new Map>());
+ const pairForFlow = React.useCallback((custom: StudioBaseCustomization, name: string): Promise => {
+ const held = pairsByFlowRef.current.get(name);
+ if (held) return held;
+ const asked = custom.ensure();
+ pairsByFlowRef.current.set(name, asked);
+ asked.catch(() => {
+ if (pairsByFlowRef.current.get(name) === asked) pairsByFlowRef.current.delete(name);
+ });
+ return asked;
+ }, []);
+ // Re-reads the served declaration: a flow's first save into the pair, a restore.
+ const [servedNonce, setServedNonce] = React.useState(0);
+ const flowServed = useServedOverride(
+ client,
+ flowCustomizable && current ? { type: 'flow', name: current.name } : null,
+ customizeBase,
+ customizePair,
+ `${publishNonce}:${servedNonce}`,
+ );
+ const flowInPair = flowCustomizable && flowServed.declaration !== null;
+ const flowUnlocked =
+ flowCustomizable &&
+ !customizeWalled &&
+ (flowInPair || (customizeBlock === null && !!current && customizeAsked.has(current.name)));
+ // The open flow's editors: locked on a read-only package's flow unless it is customized.
+ const editLocked = readOnly && !flowUnlocked;
+ const flowInPairRef = React.useRef(flowInPair);
+ React.useLayoutEffect(() => {
+ flowInPairRef.current = flowInPair;
+ });
+ // A restore in flight: no save is sent beside it.
+ const [restoring, setRestoring] = React.useState(false);
+ const [restoreOpen, setRestoreOpen] = React.useState(false);
+ // The package the open flow's draft read was asked at (`flow:NAME`): the
+ // address the pin it recorded describes.
+ const flowReadAtRef = React.useRef<{ key: string; at: string | undefined } | null>(null);
+ // `?surface=flow:` capture + mirror — shared plumbing (see
+ // useSurfaceDeepLink). No producer emits this link yet; honoring it keeps
+ // the pillars uniform so a future "design this flow" bridge just works.
+ const initialSurface = useSurfaceDeepLink(current);
+ // objectui#11553 — the package-less probe for a deep-linked flow this
+ // package does not hold runs once per mount, not on every list re-read.
+ const deepLinkProbedRef = React.useRef(false);
+ const [draft, setDraft] = React.useState>({});
+ // objectui#11272 — the flow `draft` was loaded for, `flow:NAME`: written
+ // where the load below installs it, and nowhere else.
+ const [draftFor, setDraftFor] = React.useState('');
+ // objectui#11773 — the version `draft` was saved at, sent as `If-Match` by
+ // every save of this buffer (the autosave and the enable switch). A
+ // conflict's "reload" re-runs the flow load below.
+ const [flowReloadNonce, setFlowReloadNonce] = React.useState(0);
+ const reloadFlowDraft = React.useCallback(() => setFlowReloadNonce((n) => n + 1), []);
+ const {
+ save: saveFlowDraft,
+ recordRead: recordFlowRead,
+ dialog: flowConflictDialog,
+ } = useDraftSaveGuard(client, reloadFlowDraft);
+ const [selection, setSelection] = React.useState(null);
+ // The package's translations of the flow label and its approval-step labels (flow-label-translations.tsx).
+ const flowLabels = useFlowLabelTranslations(current?.name ?? '');
+ // objectstack#35018 — lift the open flow's label to the copilot's chip, the
+ // pillar's word first: 「正在看:流程 · 新会议提醒」 — the label the canvas
+ // header reads. Keyed on primitives, the callback read through a ref.
+ const onSurfaceLabelChangeRef = React.useRef(onSurfaceLabelChange);
+ React.useEffect(() => {
+ onSurfaceLabelChangeRef.current = onSurfaceLabelChange;
+ });
+ const currentFlowType = current?.type;
+ const currentFlowName = current?.name;
+ const currentFlowLabel = current ? flowLabels?.flowLabel || current.label : undefined;
+ const flowSubject = t('engine.studio.copilot.subject.flow', locale);
+ React.useEffect(() => {
+ onSurfaceLabelChangeRef.current?.(
+ currentFlowType && currentFlowName && currentFlowLabel
+ ? { type: currentFlowType, name: currentFlowName, label: `${flowSubject} · ${currentFlowLabel}` }
+ : null,
+ );
+ }, [currentFlowType, currentFlowName, currentFlowLabel, flowSubject]);
+ React.useEffect(
+ () => () => {
+ onSurfaceLabelChangeRef.current?.(null);
+ },
+ [],
+ );
+ const [loading, setLoading] = React.useState(false);
+ const [saving, setSaving] = React.useState(false);
+ const [hasDraft, setHasDraft] = React.useState(false);
+ // objectstack#36511 item 6 — the per-key provenance the flow's draft read
+ // served (`draftChanges`), `null` with no draft: whether the AI assistant
+ // wrote the pending draft the page opened on.
+ const [flowDraftChanges, setFlowDraftChanges] = React.useState(null);
+ // The aside header's slot for the hosted inspector's header actions (the
+ // flow node's "···" menu), so they sit in the title bar (`InspectorShellHost`).
+ const [configHeaderSlot, setConfigHeaderSlot] = React.useState(null);
+ // objectstack#26858 — the server's verdict on the flow on screen: the pending
+ // draft's (what its publish will refuse), else the layered read's. Taken off
+ // each read, never computed here; the inspectors read it at their paths.
+ const [flowVerdict, setFlowVerdict] = React.useState(undefined);
+ // objectstack#27799 — and the flow's Problems list reads that same verdict,
+ // so it never calls a flow valid that its publish refuses.
+ const flowPreviewDiagnostics = React.useMemo(
+ () =>
+ verdictPreviewEntries(flowVerdict).map((entry) => ({
+ ...entry,
+ message: translateValidationMessage(entry.message, locale),
+ })),
+ [flowVerdict, locale],
+ );
+ const flowVerdictSeq = React.useRef(0);
+ // objectstack#28570 — read at the package the draft was saved at (a customized flow's pair).
+ const rereadFlowVerdict = React.useCallback(
+ (flowName: string, at: string | undefined) => {
+ const seq = ++flowVerdictSeq.current;
+ void readDraftForSave(client, 'flow', flowName, at).then((read) => {
+ if (seq === flowVerdictSeq.current) setFlowVerdict(draftEnvelopeDiagnostics(read.answer));
+ });
+ },
+ [client],
+ );
+ // objectui#11785 — a load failure as it was (`plainRefusal`), a refused save
+ // as an author sentence naming the step and its input, raw text behind Details.
+ const [error, setError] = React.useState(null);
+ // Tells "still fetching the list" apart from "fetched, package has no flows"
+ // — without it the empty rail showed an endless "Loading…" for a fresh package.
+ const [listed, setListed] = React.useState(false);
+ // The flow a deep link named that this rail, once listed, does not hold.
+ const missingFlow =
+ listed && initialSurface?.type === 'flow' && !flows.some((f) => f.name === initialSurface.name)
+ ? initialSurface.name
+ : null;
+ // Inline create — a fresh package starts with zero flows, so the pillar must
+ // offer a way to author the first one (mirrors the object/app creators).
+ const [creating, setCreating] = React.useState(false);
+ const [createBusy, setCreateBusy] = React.useState(false);
+ // objectui#11788 — the trigger the New dialog asks for (unset = choose it
+ // later on the Start node), and the object a record trigger watches. The
+ // New button empties both each time it opens the dialog, as the dialog
+ // empties its own inputs.
+ const [newTrigger, setNewTrigger] = React.useState('');
+ const [newTriggerObject, setNewTriggerObject] = React.useState('');
+ const startTrigger = React.useMemo(() => newFlowTriggerFields(locale), [locale]);
+ // objectui#11861 — the dialog opens on the starting points of
+ // `flowPresets.ts`; the trigger form above is the *Advanced* choice. A
+ // record preset waits for its object: `newNeeds` is the line the dialog
+ // shows while Create holds it.
+ const [newChoice, setNewChoice] = React.useState(FLOW_PRESETS[0]);
+ const [newNeeds, setNewNeeds] = React.useState(null);
+ // objectstack#26917 — a create refused because the identifier is taken:
+ // which flow holds it, and whether it is on this rail, so it can be opened.
+ const [createTaken, setCreateTaken] = React.useState<{ name: string; label: string; here: boolean } | null>(null);
+ const newChoiceGroup = React.useId();
+ // objectui#12303 — the read-only reason the header's status switch is described by.
+ const toggleReadOnlyReasonId = React.useId();
+ // objectui#12454 — the canvas hint the header used to print describes the Canvas tab.
+ const canvasHintId = React.useId();
+ // objectui#11591 — keyed on the pillar's one type, as the inspector beside
+ // it is, never on the open flow's: with no flow open (a deep link naming one
+ // this rail does not hold, or an empty rail) a selection-keyed read found no
+ // designer and the canvas chip below said none were registered, on a page
+ // whose designers are.
+ const Preview = useRegisteredMetadataPreview('flow');
+ const inspector = useRegisteredMetadataInspector('flow');
+ const isEditable = !!Preview;
+ // objectui#6795 part C — the FOURTH site, found by sweeping past the three the
+ // ruling named. Same class as the Interfaces rail: with the registries
+ // unpopulated the canvas below degrades to a raw JSON dump, and both the
+ // header chip ("click a node to configure") and the rail ("Click a node on the
+ // canvas, and its configuration appears here") went on instructing the author
+ // to click nodes that are not rendered. Same constraint on the wording — ⛔ no
+ // "loading…"/"try again": the reads are observed (objectui#11939), so a late
+ // registration does bring the canvas back, but nothing here knows one is on
+ // its way. Both type lists are read unconditionally (no hook behind `&&`).
+ const registeredPreviewTypes = useRegisteredMetadataPreviewTypes();
+ const registeredInspectorTypes = useRegisteredMetadataInspectorTypes();
+ const designersUnregistered =
+ registeredPreviewTypes.length === 0 && registeredInspectorTypes.length === 0;
+
+ // Runtime enable/bound state per flow (GET /automation/_status). Persisted
+ // `status` is intent; this is what's actually live in the engine — the truth
+ // behind the rail's status dots. Refetched after a publish (publishNonce);
+ // degrades silently on an older backend / offline (dots just don't render).
+ const [flowStatus, setFlowStatus] = React.useState>({});
+ // objectui#11779 — whether `flowStatus` holds an answer from the engine. With
+ // one, a flow the map has no row for is a flow the engine does not have
+ // (nothing of it is deployed); without one, there is nothing to say about any
+ // flow's live state, and the header reads the draft's own switch instead.
+ const [flowStatusRead, setFlowStatusRead] = React.useState(false);
+ // objectui#12349 — the engine's registration verdict per flow, from the flow
+ // 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.
+ const [flowDefinitions, setFlowDefinitions] = React.useState>(() => new Map());
+ const [objectLabels, setObjectLabels] = React.useState>(() => new Map());
+ // Which groups the author folded. Ephemeral (AGENTS.md #8), as the search is.
+ const [foldedGroups, setFoldedGroups] = React.useState>(() => new Set());
+ // objectui#12454 — the tab the item header's tab row has open over the flow,
+ // and the problem tally its Problems tab carries (reported by the preview).
+ const [flowSection, setFlowSection] = React.useState('canvas');
+ const [problemTally, setProblemTally] = React.useState({ count: 0, errors: 0 });
+ // ADR-0146 D4 — bumped after a ledger toggle the server accepted: its answer
+ // carries the flag alone, and the flip can move what the engine armed.
+ const [statusNonce, setStatusNonce] = React.useState(0);
+ React.useEffect(() => {
+ let cancelled = false;
+ (async () => {
+ try {
+ const res = await fetch('/api/v1/automation/_status', { credentials: 'include', headers: { Accept: 'application/json' } });
+ if (!res.ok) return;
+ const payload = (await res.json().catch(() => null)) as { data?: { flows?: FlowRuntimeState[] }; flows?: FlowRuntimeState[] } | null;
+ const list = payload?.data?.flows ?? payload?.flows ?? [];
+ if (cancelled || !Array.isArray(list)) return;
+ const map: Record = {};
+ for (const s of list) if (s?.name) map[s.name] = flowRailState(s);
+ setFlowStatus(map);
+ setFlowStatusRead(true);
+ } catch {
+ /* offline / older backend → no dots */
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [publishNonce, statusNonce]);
+
+ // #27356 row 19 — a delete re-reads the rail (`flowListNonce`) and leaves
+ // the pillar on its empty state: that one re-read opens no other flow.
+ const [flowListNonce, setFlowListNonce] = React.useState(0);
+ const keepEmptyAfterDeleteRef = React.useRef(false);
+ React.useEffect(() => {
+ let cancelled = false;
+ (async () => {
+ try {
+ // Published flows ∪ pending DRAFT flows — `list()` only sees
+ // published/active metadata, so a just-authored flow that hasn't been
+ // published yet (or a fresh writable-base package whose flows are all
+ // drafts) would render an empty rail even though "Changes · N" shows the
+ // draft exists. Mirrors the Data / Interfaces / Access pillars, which all
+ // merge their drafts. Keyed on `publishNonce` too so drafts that go live
+ // collapse back into the published rail after a package publish.
+ // objectui#11862 — a draft-only flow reads as the label its `_drafts`
+ // row carries, resolved in the designer locale.
+ const packageId = railPackageId;
+ // objectstack#28572 — on a read-only base with a pair, the pair's
+ // flows too: the ones the base's list does not hold are the flows the
+ // pair adds, grouped and dotted from the pair's own reads. A failed
+ // pair read lists none of them.
+ const pairId = railPairId;
+ const readPair = async () =>
+ pairId === null
+ ? null
+ : Promise.all([
+ loadPackageSurfaces(client, 'flow', pairId, locale),
+ readFlowRegistrations(client, pairId),
+ readFlowDefinitions(client, pairId),
+ readObjectLabels(client, pairId, locale),
+ ]);
+ const [baseItems, registrations, definitions, objects, pair, publishedNames] = await Promise.all([
+ packageId === null
+ ? loadPackageLessSurfaces(client, 'flow', locale)
+ : loadPackageSurfaces(client, 'flow', packageId, locale),
+ readFlowRegistrations(client, packageId),
+ 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);
+ const deepLinked = resolveSurfaceDeepLink(items, initialSurface, 'flow');
+ // objectui#11553 — a deep link that NAMES a flow this rail does not
+ // hold opens no other flow in its place: the first flow under the name
+ // of the one asked for is how the clone's link "redirected to another
+ // flow". A package-less flow named from a package's pillar is found in
+ // the package-less scope and opened there, once per mount.
+ const named = initialSurface?.type === 'flow' ? initialSurface.name : null;
+ if (named && !deepLinked && packageId !== null && !deepLinkProbedRef.current) {
+ deepLinkProbedRef.current = true;
+ const packageLess = await loadPackageLessSurfaces(client, 'flow', locale).catch(() => []);
+ if (cancelled) return;
+ if (packageLess.some((f) => f.name === named)) {
+ navigate(studioOrgScopePath({ type: 'flow', name: named }), { replace: true });
+ return;
+ }
+ }
+ const keepEmpty = keepEmptyAfterDeleteRef.current;
+ keepEmptyAfterDeleteRef.current = false;
+ // objectstack#28567 — a copy "New similar" saved in this package opens.
+ const copied = openAfterListRef.current;
+ openAfterListRef.current = null;
+ const copiedFlow = copied ? items.find((f) => f.name === copied) : undefined;
+ if (copiedFlow) {
+ setCurrent(copiedFlow);
+ return;
+ }
+ setCurrent((c) => (keepEmpty ? c : (c ?? deepLinked ?? (named ? null : items[0]) ?? null)));
+ } catch (e) {
+ if (!cancelled) setError(plainRefusal(e));
+ } finally {
+ if (!cancelled) setListed(true);
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [client, railPackageId, railPairId, publishNonce, metadataRefreshNonce, locale, flowListNonce]);
+
+ const doCreateFlow = React.useCallback(
+ async (label: string, name: string, trigger: NewFlowTrigger | null) => {
+ setCreateBusy(true);
+ setError(null);
+ setCreateTaken(null);
+ try {
+ // A name a flow already holds, published or as a draft, in this
+ // package or any other, is refused here and nothing is written: over
+ // a published flow the first-write pin below would write this blank
+ // skeleton as its pending draft (`findTakenIdentifier`).
+ const taken = await findTakenIdentifier(client, 'flow', name, locale);
+ if (taken) {
+ setCreateTaken({ ...taken, here: flows.some((f) => f.name === name) });
+ return;
+ }
+ // Minimal valid, autolaunched skeleton: start → end. The designer fills in
+ // the trigger + nodes; publishing it is a separate, user-initiated step.
+ //
+ // objectui#11779 — and it is born switched OFF, as the bar above the
+ // rail promises ("Off by default · review before enabling"). With no
+ // `status` the spec's default is `draft`, which the engine arms like
+ // `active`: the switch read "Enabled" on a flow nobody had reviewed, and
+ // a package publish armed it as soon as it had a trigger. `obsolete` is
+ // what the switch itself writes for Off; enabling it is the author's
+ // own flip.
+ const skeleton = withStartTrigger(
+ {
+ ...buildFlowSkeleton(
+ name,
+ label,
+ t('engine.studio.auto.nodeStart', locale),
+ t('engine.studio.auto.nodeEnd', locale),
+ ),
+ status: 'obsolete',
+ },
+ trigger,
+ );
+ // objectstack#28572 (ADR-0146 D3) — on a read-only base the flow is
+ // created in its pair, which the ensure door answers (creating it on
+ // first use, without a prompt).
+ const target = packageReadOnly && customization ? (await customization.ensurePackage()).packageId : null;
+ // objectui#11773 — and the door refuses a draft row too (the
+ // first-write pin), for one that lands between the check above and
+ // this save.
+ await client.save('flow', name, skeleton, {
+ mode: 'draft',
+ packageId: target ?? railPackageId ?? undefined,
+ ifNoneMatch: '*',
+ surface: 'studio',
+ });
+ // objectstack#36511 — and published at once, switched off as it was
+ // born: no draft is left for a package publish, and the switch arms it.
+ const live = await publishSavedItem(client, { type: 'flow', name, packageId: target ?? railPackageId }, false);
+ if (!live.ok) {
+ setError(plainRefusal(live.error));
+ return;
+ }
+ const item: Surface = target === null ? { type: 'flow', name, label } : { type: 'flow', name, label, addedIn: target };
+ setFlows((fs) => [...fs.filter((f) => f.name !== name), item]);
+ // objectstack#36742 — the engine's row for the new flow is read, as
+ // after a Save: the snapshot held was taken before the flow existed,
+ // and its missing row read as 「未发布草稿」 over a published flow.
+ setStatusNonce((n) => n + 1);
+ // objectstack#28572 — the rail reads again after the save, so the
+ // pair's list it reads holds the new flow.
+ if (target !== null) setFlowListNonce((n) => n + 1);
+ // objectui#12454 — and groups by what it was born with.
+ setFlowDefinitions((m) => new Map([...m, [name, skeleton]]));
+ setCurrent(item);
+ setHasDraft(false);
+ setCreating(false);
+ // objectstack#36742 — its own words: the flow is published, but born
+ // switched off, so 「已保存并生效」 would promise a run it will not do.
+ toast.success(tFormat('engine.studio.auto.createdOff', locale, { name: label }), { id: STUDIO_SAVE_TOAST_ID });
+ } catch (e) {
+ // Shown in the create dialog, which prints the message only: kept whole.
+ setError(plainRefusal(e));
+ } finally {
+ setCreateBusy(false);
+ }
+ },
+ [client, railPackageId, packageReadOnly, customization, locale, flows],
+ );
+
+ React.useEffect(() => {
+ if (!current) return;
+ let cancelled = false;
+ // objectui#11331 — whether this run's load has settled (see the cleanup).
+ let settled = false;
+ setLoading(true);
+ setError(null);
+ setSelection(null);
+ (async () => {
+ try {
+ // objectui#11773 — read at the address the flow saves write, so the
+ // version it serves pins the first of them. objectstack#28570 — a
+ // read-only base's flow: its pair, when one is listed.
+ const pair = flowCustomizing && !current.addedIn ? (customizationRef.current?.pairId ?? null) : null;
+ const readAt = pair ?? draftPackageId;
+ const draftRead = await readDraftForSave>(client, 'flow', current.name, readAt);
+ if (cancelled) return;
+ // objectstack#29148 — a flow draft the server refused to read is no
+ // absence: no buffer is installed over it (see InterfacesPillar's leaf
+ // load), so nothing is shown to edit and the autosave has nothing to send.
+ if ('refused' in draftRead) {
+ setDraftFor('');
+ setError({
+ message: t('engine.studio.refusal.draftUnreadable', locale),
+ detail: formatMetadataError(draftRead.refused),
+ });
+ return;
+ }
+ const draftBody = extractDraftBody(draftRead.answer);
+ // objectui#11799 — the baseline is read only for a flow with no
+ // pending draft, the one case it is used. An unsaved flow always has
+ // one, so it never asks `/layers`, which answers 404 for it.
+ // ADR-0048 — at the package the flow saves write, its owner here; with
+ // none, the read names none, and a name two packages hold is refused
+ // with the server's own sentence, shown as the load's error.
+ const layRaw = draftBody
+ ? null
+ : await client.layered>(
+ 'flow',
+ current.name,
+ draftPackageId ? { packageId: draftPackageId } : {},
+ );
+ if (cancelled) return;
+ const lay = layRaw as { effective?: Record; code?: Record } | null;
+ const baseline = (lay?.effective ?? lay?.code ?? {}) as Record;
+ // Served draft as-is, baseline only without one (objectui#10765).
+ setDraft(draftBody ?? baseline);
+ flowStoredRef.current = draftBody ?? baseline;
+ setDraftFor(`flow:${current.name}`);
+ flowVerdictSeq.current += 1;
+ setFlowVerdict(
+ editedItemDiagnostics({
+ hasDraft: !!draftBody,
+ draftDiagnostics: draftEnvelopeDiagnostics(draftRead.answer),
+ layered: layRaw,
+ }),
+ );
+ // objectui#11773 — the next save is pinned to what the draft read served.
+ recordFlowRead('flow', current.name, readAt, draftRead.pin);
+ flowReadAtRef.current = { key: `flow:${current.name}`, at: readAt };
+ setHasDraft(!!draftBody);
+ setFlowDraftChanges(draftBody ? readDraftChanges(draftRead.answer) : null);
+ } catch (e) {
+ if (!cancelled) setError(plainRefusal(e));
+ } finally {
+ settled = true;
+ if (!cancelled) {
+ setLoading(false);
+ setAutoDirty(false);
+ }
+ }
+ })();
+ return () => {
+ cancelled = true;
+ // objectui#11331 — a load cancelled before it settled lowers the
+ // `loading` it raised, as in InterfacesPillar's draft load.
+ if (!settled) setLoading(false);
+ };
+ }, [client, current, draftPackageId, publishNonce, flowReloadNonce, recordFlowRead, flowCustomizing]);
+
+ // objectui#5813 — local dirty flag: auto-save arms only after a real edit.
+ const [autoDirty, setAutoDirty] = React.useState(false);
+ const onPatch = React.useCallback(
+ (patch: Record) => {
+ setDraft((d) => ({ ...d, ...patch }));
+ setAutoDirty(true);
+ },
+ [],
+ );
+ // objectstack#36511 — the flow as the server holds it (as loaded, or as last
+ // saved): what the enable switch writes its status onto, so a flip never
+ // carries an edit Save has not sent.
+ const flowStoredRef = React.useRef>({});
+ const flowDraftRef = React.useRef(draft);
+ React.useLayoutEffect(() => {
+ flowDraftRef.current = draft;
+ });
+ // objectstack#36511 — the top bar's Save for the open flow (canvas and
+ // properties): its draft, then that flow's own publish, so it is live at
+ // once. A refused publish keeps the edits on the page with the reason.
+ const doSave = React.useCallback(async (): Promise => {
+ if (!current) return { kind: 'declined' };
+ setSaving('draft');
+ setError(null);
+ const body = draft;
+ const hadDraft = hasDraft;
+ 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
+ // refused door is shown as it was sent, and nothing is saved.
+ const custom = readOnly ? customizationRef.current : null;
+ let target: { packageId: string | undefined; body: Record } = { packageId: draftPackageId, body };
+ let entering = false;
+ if (custom) {
+ let pair: string;
+ try {
+ pair = await pairForFlow(custom, current.name);
+ } catch (e) {
+ const refusal = plainRefusal(e);
+ setError(refusal);
+ return { kind: 'refused', reason: refusal.message };
+ }
+ const declared = overrideDraftBody(body, custom.base, custom.basedOn);
+ if (declared === null) {
+ const refusal = { message: tFormat('engine.studio.customize.noVersion', locale, { package: custom.baseLabel }) };
+ setError(refusal);
+ return { kind: 'refused', reason: refusal.message };
+ }
+ // The buffer was read at another package (the base, before its pair
+ // was listed): the pair is taken to hold no draft of the flow, so a
+ // draft there is a conflict the author is asked about, never one this
+ // save overwrites. Its receipt pins the saves after it.
+ const key = `flow:${current.name}`;
+ if (!(flowReadAtRef.current?.key === key && flowReadAtRef.current.at === pair)) {
+ recordFlowRead('flow', current.name, pair, { ifNoneMatch: '*' });
+ flowReadAtRef.current = { key, at: pair };
+ }
+ entering = !flowInPairRef.current;
+ target = { packageId: pair, body: declared };
+ }
+ const outcome = await saveFlowDraft('flow', current.name, target.body, {
+ mode: 'draft',
+ packageId: target.packageId,
+ surface: 'studio',
+ });
+ // objectui#11773 — the author chose the saved version; the load replaces the buffer.
+ if (outcome === 'reloaded') return { kind: 'declined' };
+ // The badge reads the declaration the server now serves.
+ if (entering) setServedNonce((n) => n + 1);
+ setSaving('publish');
+ const live = await publishSavedItem(
+ client,
+ { type: 'flow', name: current.name, packageId: target.packageId ?? null },
+ hadDraft,
+ );
+ if (!live.ok) {
+ setHasDraft(!live.draftDiscarded);
+ if (live.draftDiscarded) recordFlowRead('flow', current.name, target.packageId, { ifNoneMatch: '*' });
+ // objectstack#26858 — what the pending draft now says, or the live flow's verdict.
+ rereadFlowVerdict(current.name, target.packageId);
+ const refusal = publishRefusal(publishFailureOf('flow', current.name, live.error), 'flow', target.body, locale);
+ setError(refusal);
+ return { kind: 'refused', reason: refusal.message };
+ }
+ // Live: no draft is left, so the next save asserts none.
+ setHasDraft(false);
+ recordFlowRead('flow', current.name, target.packageId, { ifNoneMatch: '*' });
+ flowStoredRef.current = body;
+ // The engine's row for the flow is read again: the publish armed or disarmed it.
+ setStatusNonce((n) => n + 1);
+ // objectstack#26858 — and the verdict: the one held described the body before this Save.
+ rereadFlowVerdict(current.name, target.packageId);
+ // objectstack#36511 — clean once nothing was edited since; the top bar's
+ // toast says the flow is saved (the header's 已保存 badge retired with it).
+ if (JSON.stringify(flowDraftRef.current) === JSON.stringify(body)) setAutoDirty(false);
+ return { kind: 'saved' };
+ } catch (e) {
+ // objectui#11785 — read against `body`, the body this save sent.
+ const refusal = flowSaveRefusal(e, body, locale);
+ setError(refusal);
+ return { kind: 'refused', reason: refusal.message };
+ } finally {
+ setSaving(false);
+ }
+ }, [saveFlowDraft, client, current, draft, hasDraft, draftPackageId, locale, rereadFlowVerdict, readOnly, pairForFlow, recordFlowRead]);
+ // objectui#11786 — an edit that leaves a step's required input out (a step
+ // just added, before it is filled in) is held, not sent: the server would
+ // refuse the flow with a 422 naming that input. The step's inspector hints the
+ // input, and the line below names it. Asked of the spec's own flow judges
+ // (`specRequiresField`) over the inputs each step's inspector offers.
+ const flowIncomplete = React.useMemo(
+ () => (autoDirty ? flowHeldEdit(draft, locale) : null),
+ [autoDirty, draft, locale],
+ );
+ // objectui#11272 — the buffer is the open flow's own once its load installed it.
+ const flowLoaded = current !== null && draftFor === `flow:${current.name}`;
+ // Only the open flow's own buffer is held (objectui#11272).
+ const flowHeld = flowLoaded ? flowIncomplete : null;
+ // objectstack#36511 — what opening another flow (or a new one) would drop.
+ const flowUnsaved = flowLoaded && autoDirty;
+ useStudioSaveEntry(
+ current && flowLoaded && isEditable && !editLocked && !restoring
+ ? {
+ label: current.label || current.name,
+ order: 0,
+ dirty: autoDirty,
+ held: flowHeld?.clause ?? null,
+ save: () => doSave(),
+ cancel: () => {
+ setAutoDirty(false);
+ setError(null);
+ reloadFlowDraft();
+ },
+ }
+ : null,
+ );
+ useHeldEditReport(onHeldEditChange, flowHeld?.clause ?? null);
+ // objectstack#36511 item 6 — the AI assistant's unpublished draft is the
+ // version on screen: say Save makes it live too, and offer to drop that one
+ // flow's draft (`DELETE /meta/flow/NAME?state=draft`, at the package it was
+ // read at), back to the live version. Edits not yet saved go with it, asked first.
+ const flowAiDraft =
+ flowLoaded && hasDraft && (flowDraftChanges ?? []).some((change) => isAgentDraftSurface(change.by));
+ const [discardingFlowDraft, setDiscardingFlowDraft] = React.useState(false);
+ const discardFlowDraft = React.useCallback(async () => {
+ if (!current) return;
+ if (autoDirty && !window.confirm(t('engine.studio.aiDraft.discardConfirmUnsaved', locale))) return;
+ const at = flowReadAtRef.current?.key === `flow:${current.name}` ? flowReadAtRef.current.at : draftPackageId;
+ setDiscardingFlowDraft(true);
+ setError(null);
+ try {
+ await client.reset('flow', current.name, { state: 'draft', ...(at ? { packageId: at } : {}) });
+ setHasDraft(false);
+ setFlowDraftChanges(null);
+ setAutoDirty(false);
+ // The load installs the live version and pins the next save to it.
+ reloadFlowDraft();
+ // The ledger behind Changes re-reads on the pulse, one item fewer.
+ emitMetadataRefresh();
+ } catch (e) {
+ const refusal = plainRefusal(e);
+ setError({ ...refusal, message: tFormat('engine.studio.aiDraft.discardFailed', locale, { reason: refusal.message }) });
+ } finally {
+ setDiscardingFlowDraft(false);
+ }
+ }, [autoDirty, client, current, draftPackageId, locale, reloadFlowDraft]);
+ // objectui#12725 — the header's draft line reads the badge's ledger.
+ const flowDraftStatus = useStudioItemDraftStatus(
+ current ? { type: 'flow', name: current.name } : null,
+ hasDraft && flowLoaded,
+ locale,
+ );
+
+ // Enable/disable persists via the flow's deployment `status` (active = on,
+ // obsolete = off). objectstack#36511 — the switch is live at once, as an
+ // installed app's ledger switch is: it writes the status onto the flow as
+ // the server holds it, never onto an edit Save has not sent, and publishes
+ // that one flow. The edits on the page keep the new status and stay unsaved.
+ const flowEnabled = draft.status !== 'obsolete' && draft.status !== 'invalid';
+ // The flow the draft on screen belongs to — read by the toggle's rollback
+ // below, so a refusal that lands after the author opened another flow never
+ // rewrites that other flow's draft.
+ const draftFlowRef = React.useRef(null);
+ React.useEffect(() => {
+ draftFlowRef.current = current?.name ?? null;
+ }, [current]);
+ const toggleEnabled = React.useCallback(async () => {
+ // Guarded in addition to being disabled (objectui#11124): a read-only
+ // package refuses the save, so the flip would only be rolled back.
+ if (!current || readOnly) return;
+ // objectui#11272 — refused on a buffer that is not this flow's document
+ // (its load is not in yet): the switch is not offered then either.
+ if (draftFor !== `flow:${current.name}`) return;
+ const flowName = current.name;
+ const prevStatus = draft.status;
+ const next = !(draft.status !== 'obsolete' && draft.status !== 'invalid');
+ const nextStatus = next ? 'active' : 'obsolete';
+ const stored = { ...flowStoredRef.current, status: nextStatus };
+ const hadDraft = hasDraft;
+ setDraft((d) => ({ ...d, status: nextStatus }));
+ setSaving('draft');
+ setError(null);
+ // objectui#11124 — the switch and the canvas status (both read
+ // `draft.status`) never show a status the server refused. Only `status`
+ // is put back, and only on the same flow, still holding the refused one.
+ const rollBack = () =>
+ setDraft((d) => {
+ if (draftFlowRef.current !== flowName || d.status !== nextStatus) return d;
+ const { status: _refused, ...rest } = d;
+ return prevStatus !== undefined ? { ...rest, status: prevStatus } : rest;
+ });
+ try {
+ // objectui#11773 — a reload replaced the buffer the flip was taken on.
+ if ((await saveFlowDraft('flow', flowName, stored, { mode: 'draft', packageId: draftPackageId, surface: 'studio' })) === 'reloaded') return;
+ setSaving('publish');
+ const live = await publishSavedItem(client, { type: 'flow', name: flowName, packageId: draftPackageId ?? null }, hadDraft);
+ if (!live.ok) {
+ setHasDraft(!live.draftDiscarded);
+ if (live.draftDiscarded) recordFlowRead('flow', flowName, draftPackageId, { ifNoneMatch: '*' });
+ rollBack();
+ setError(publishRefusal(publishFailureOf('flow', flowName, live.error), 'flow', stored, locale));
+ return;
+ }
+ setHasDraft(false);
+ recordFlowRead('flow', flowName, draftPackageId, { ifNoneMatch: '*' });
+ if (draftFlowRef.current === flowName) flowStoredRef.current = stored;
+ setStatusNonce((n) => n + 1);
+ rereadFlowVerdict(flowName, draftPackageId);
+ toast.success(next ? t('engine.studio.auto.enabledToast', locale) : t('engine.studio.auto.disabledToast', locale));
+ } catch (e) {
+ rollBack();
+ setError(flowSaveRefusal(e, stored, locale));
+ } finally {
+ setSaving(false);
+ }
+ }, [saveFlowDraft, client, current, draft, draftFor, hasDraft, draftPackageId, locale, readOnly, recordFlowRead, rereadFlowVerdict]);
+
+ // The rail's "+" — and the empty block's button, which runs this same
+ // handler (objectui#12514). objectui#11553 — no "New" in the package-less
+ // scope: new authoring stays package-first, and this scope reaches flows
+ // that already exist without a package.
+ const openCreateFlow =
+ (!packageReadOnly || newInPair) && railPackageId !== null
+ ? () => {
+ // objectstack#26845 — the created flow opens at once, and its load
+ // replaces the buffer a held step lives in: asked before the dialog
+ // opens, so Cancel costs nothing and the create itself asks nothing.
+ if (!confirmDropUnsavedWork(flowUnsaved, locale)) return;
+ setError(null);
+ setNewTrigger('');
+ setNewTriggerObject('');
+ setNewChoice(FLOW_PRESETS[0]);
+ setNewNeeds(null);
+ setCreateTaken(null);
+ setCreating(true);
+ }
+ : undefined;
+ // #27356 row 19 — Delete flow (`FlowItemMoreMenu`): the autosave disarmed,
+ // the draft (so none is left to publish the flow back) and then the flow
+ // deleted at the drafts' package, then the empty state over a re-read rail.
+ // A refusal shows the door's sentence and keeps the flow open.
+ const deleteOpenFlow = React.useCallback(async () => {
+ if (!current || packageId === null) return;
+ const flow = current;
+ setAutoDirty(false);
+ setError(null);
+ try {
+ if (hasDraft) {
+ await client.reset('flow', flow.name, { state: 'draft', packageId });
+ setHasDraft(false);
+ }
+ await client.reset('flow', flow.name, { packageId });
+ } catch (e) {
+ setError(plainRefusal(e));
+ return;
+ }
+ keepEmptyAfterDeleteRef.current = true;
+ setCurrent(null);
+ setFlows((fs) => fs.filter((f) => f.name !== flow.name));
+ setFlowListNonce((n) => n + 1);
+ onDraftSaved?.({ type: 'flow', name: flow.name });
+ toast.success(tFormat('engine.studio.auto.flowDeleted', locale, { item: flow.label || flow.name }));
+ }, [client, current, packageId, hasDraft, onDraftSaved, locale]);
+ // objectstack#28570 (ADR-0146 D2) — "Restore package original" on a flow
+ // the pair overrides: the pair's draft of the flow, then its row, deleted
+ // at the pair. The pair is the door's answer this flow's saves named, else
+ // the surface's; never asked of the door again. The base's flow reads back
+ // and runs again under the same ledger row, and the server's refusal is
+ // shown as it is sent.
+ const restoreFlow = React.useCallback(async () => {
+ const custom = customizationRef.current;
+ if (!current || !custom) return;
+ const flow = current;
+ const held = pairsByFlowRef.current.get(flow.name);
+ const pair = (held ? await held.catch(() => null) : null) ?? custom.pairId;
+ if (!pair) return;
+ setRestoring(true);
+ setAutoDirty(false);
+ setError(null);
+ try {
+ await client.reset('flow', flow.name, { state: 'draft', packageId: pair });
+ await client.reset('flow', flow.name, { packageId: pair });
+ } catch (e) {
+ setError(plainRefusal(e));
+ return;
+ } finally {
+ setRestoring(false);
+ }
+ pairsByFlowRef.current.delete(flow.name);
+ setCustomizeAsked((prev) => {
+ if (!prev.has(flow.name)) return prev;
+ const next = new Set(prev);
+ next.delete(flow.name);
+ return next;
+ });
+ reloadFlowDraft();
+ setServedNonce((n) => n + 1);
+ // The base's flow is armed again: the engine's rows are read again.
+ setStatusNonce((n) => n + 1);
+ emitMetadataRefresh();
+ onDraftSaved?.({ type: 'flow', name: flow.name });
+ toast.success(
+ tFormat('engine.studio.customize.restoreDone', locale, { item: flow.label || flow.name, package: custom.baseLabel }),
+ );
+ }, [client, current, reloadFlowDraft, onDraftSaved, locale]);
+ // objectstack#28567 (ADR-0146 D4) — "New similar" saved a copy. It opens
+ // only where the door's answer says it landed: in this pillar after a
+ // re-read when that is this package, else that package's Automations pillar
+ // on the copy (a read-only base's pair, `.custom`). An answer naming
+ // no package opens nothing and says so; the landing is never derived here.
+ const onFlowCopied = React.useCallback(
+ (copy: FlowCopied) => {
+ setError(null);
+ if (copy.packageId === null) {
+ setFlowCopied({ kind: 'noPackage', name: copy.name, notice: copy.notice, noticeCode: copy.noticeCode });
+ return;
+ }
+ const landed: FlowCopiedStrip = {
+ kind: 'landed',
+ name: copy.name,
+ packageId: copy.packageId,
+ notice: copy.notice,
+ noticeCode: copy.noticeCode,
+ };
+ onDraftSaved?.({ type: 'flow', name: copy.name });
+ // objectstack#28572 — the pair's flows are this surface's too.
+ if (copy.packageId === railPackageId || (railPairId !== null && copy.packageId === railPairId)) {
+ setFlowCopied(landed);
+ openAfterListRef.current = copy.name;
+ setFlowListNonce((n) => n + 1);
+ // The door stored the copy live and the engine already holds its row;
+ // the `_status` snapshot this pillar holds predates it, so it is read
+ // once more, or the copy's header reads the row it lacks as an
+ // unpublished draft. The other landing remounts the pillar keyed by
+ // package, and that mount reads `_status` itself.
+ setStatusNonce((n) => n + 1);
+ return;
+ }
+ navigate(studioPillarItemPath(copy.packageId, 'automations', { type: 'flow', name: copy.name }), {
+ state: { [FLOW_COPIED_ARRIVAL_STATE]: landed },
+ });
+ },
+ [railPackageId, railPairId, navigate, onDraftSaved],
+ );
+ // A landing is shown on its copy; an answer that names no package, on any flow.
+ const flowCopiedShown =
+ flowCopied && (flowCopied.kind === 'noPackage' || flowCopied.name === current?.name) ? flowCopied : null;
+ // ADR-0146 D4 — a read-only package's open flow offers the activation-ledger
+ // switch (`FlowLedgerSwitch`). It reads the engine's `_status` row for the
+ // flow, never the draft's `status`, in `activationReading`'s three readings,
+ // the ones Setup › Packaged automation shows. With no row served there is
+ // nothing to bind and the read-only definition switch stays as it was. The
+ // door is pre-judged from the served posture facts; after any attempt the
+ // server's refusal is shown as sent.
+ const ledgerRow =
+ readOnly && packageId !== null && current && flowStatusRead ? flowStatus[current.name] : undefined;
+ const ledgerOn = ledgerRow?.enabled;
+ const ledgerWalled = useFlowLedgerWalledReadOnly();
+ const ledgerWalledReason = ledgerWalled ? t('engine.studio.auto.ledger.walled', locale) : undefined;
+ const [ledgerBusy, setLedgerBusy] = React.useState(false);
+ const toggleLedger = React.useCallback(async () => {
+ if (!current || ledgerOn === undefined || ledgerWalled) return;
+ const flow = current;
+ setError(null);
+ setLedgerBusy(true);
+ // Never throws: a failed request comes back as an outcome.
+ const outcome = await requestFlowToggle(flow.name, !ledgerOn, {
+ http: (status) => tFormat('engine.studio.auto.ledger.toggleFailedHttp', locale, { status }),
+ network: t('engine.studio.auto.ledger.toggleFailed', locale),
+ });
+ setLedgerBusy(false);
+ // VERBATIM: the posture gate's 403 names the sanctioned path, the subflow
+ // guard's 409 names the callers that would break.
+ if (!outcome.ok) {
+ setError({ message: outcome.message });
+ return;
+ }
+ const enabled = outcome.enabled;
+ setFlowStatus((m) => (m[flow.name] ? { ...m, [flow.name]: { ...m[flow.name], enabled } } : m));
+ setStatusNonce((n) => n + 1);
+ toast.success(
+ tFormat(enabled ? 'engine.studio.auto.ledger.switchedOn' : 'engine.studio.auto.ledger.switchedOff', locale, {
+ label: flow.label || flow.name,
+ }),
+ );
+ }, [current, ledgerOn, ledgerWalled, locale]);
+ // objectstack#26917 — the refusal's way out: the flow holding the identifier
+ // is on this rail, so it opens instead of a second one being made. The New
+ // button already asked about a held step (objectstack#26845).
+ const openTakenFlow = (name: string) => {
+ const flow = flows.find((f) => f.name === name);
+ if (!flow) return;
+ setCreating(false);
+ setCreateTaken(null);
+ setCurrent(flow);
+ };
+ // objectui#12514 — a listed package with no flow: one centered block in the
+ // content column, and no aside while there is nothing to select.
+ const flowsEmpty = listed && !error && flows.length === 0;
+
+ // objectui#12725 — the surface's right slot hosts the Configuration
+ // (`useStudioRightSlot`); `null` in the package-less scope and under an
+ // injected `aiSlot`, where the aside beside the canvas (or, on a folded
+ // row, the drawer over it) stays. Held while there is a flow to select, as
+ // the aside is drawn. A selection asks for the properties, keyed on its
+ // identity; Esc drops it (the canvas's own background press already does),
+ // so the slot returns to the flow's Configuration.
+ const slot = useStudioRightSlot();
+ const inSlot = slot !== null;
+ const claimSlotProps = slot?.claimProps;
+ React.useEffect(
+ () => (claimSlotProps && !flowsEmpty ? claimSlotProps() : undefined),
+ [claimSlotProps, flowsEmpty],
+ );
+ const flowSelectionKey = selection ? `${selection.kind}:${selection.id}` : '';
+ const showSlotProps = slot?.showProps;
+ 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) => {
+ if (e.key !== 'Escape' || e.defaultPrevented || isSlotEscapeExempt(e.target)) return;
+ setSelection(null);
+ };
+ document.addEventListener('keydown', onKey);
+ return () => document.removeEventListener('keydown', onKey);
+ }, [inSlot, flowSelectionKey]);
+
+ // The Configuration's body, in the aside beside the canvas or, on a folded
+ // row, in the drawer over it (objectui#11795). objectstack#26730 — the ref
+ // is where a refusal's "Show me" looks for the input it names.
+ const configBodyRef = React.useRef(null);
+ const focusConfigInput = useShowInputFocus(configBodyRef);
+ const configBodyEl =
+ selection && inspector && current && flowLoaded ? (
+ // objectstack#26858 — the inspectors read the served verdict at their paths.
+
+