@w6w/embed 0.2.19 → 0.2.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"editor-tools-BR27RGto.js","sources":["../src/chrome/workspace.tsx","../src/chrome/RightRail.tsx","../src/rail/ExpressionScope.tsx","../src/rail/CodeTool.tsx","../src/rail/ConnectionsTool.tsx","../src/rail/rail-env.tsx","../src/rail/ErrorHandlingTool.tsx","../src/rail/HistoryTool.tsx","../src/lib/tag-editor.ts","../src/chrome/TagEditor.tsx","../src/chrome/CallableSettingsModal.tsx","../src/chrome/VersionHistoryModal.tsx","../src/chrome/DangerZone.tsx","../src/rail/settings-sections.tsx","../src/rail/SettingsTool.tsx","../src/editor/WorkflowVariablesEditor.tsx","../src/lib/state-panel.ts","../src/rail/StartingStateTool.tsx","../src/rail/editor-tools.ts"],"sourcesContent":["import type {\n CallablePolicy,\n SnippetInput,\n TriggerPreview,\n WorkflowVariableRow,\n} from \"@w6w/embed/lib\";\nimport type { WorkflowConnectionResources } from \"@w6w/ui/flow\";\n/**\n * `WorkspaceContext` — what resource (if any) the currently-viewed page has\n * open. The right rail (`chrome/RightRail.tsx`) and every registered\n * `RailTool`'s `Panel` read this via `useWorkspaceCallable`; a page publishes\n * into it via `useWorkspace`.\n *\n * Route-scoped, not root-scoped — mirrors `ProjectContext.tsx`'s precedent\n * (the only other context in this codebase deliberately scoped below the app\n * root): mounted around `Layout()`'s own returned tree (`components/Layout.tsx`),\n * next to its only reader, the rail.\n *\n * The publish idiom (compute a value during render, `useEffect` keyed on a\n * stable serialization of it, clear on unmount) mirrors the shape of the\n * human's uncommitted `src/ui/useDocumentTitle.ts` — copied here as a\n * PATTERN, never imported: that file is one of this project's 23 uncommitted\n * human files and a merged branch cannot depend on it.\n */\nimport { type ReactNode, createContext, useContext, useEffect, useMemo, useState } from \"react\";\n\n/**\n * T2.1.2: widened to a discriminated union, one arm per kind — every new\n * field OPTIONAL, no new required member, so every existing producer keeps\n * compiling and behaving identically (`{kind, id}` alone still satisfies any\n * arm). The extra fields are what `CodeTool`'s snippet panel needs per kind\n * (mirrors `lib/sdk-snippets.ts`'s `SnippetCallable`, field-for-field where\n * the names match — see `lib/code-rail.ts`'s `toSnippetCallable` for the one\n * field that doesn't, `label` -> `displayName`).\n */\nexport type WorkspaceCallable =\n | {\n kind: \"function\";\n id: string;\n label?: string;\n key?: string;\n inputs?: readonly SnippetInput[];\n alias?: string;\n /**\n * The Function's / Endpoint's run-level error policy and its writer, published by an\n * editor that owns the definition buffer (`useCallableDraft`) so the rail's Error handling\n * tool edits and saves THAT buffer (pending edits ride along) instead of racing it. Same\n * ⚠️ as the workflow arm: `onPolicyChange` MUST be referentially stable\n * (`useCallableDraft`'s is).\n */\n policy?: CallablePolicy;\n onPolicyChange?: (policy: CallablePolicy) => void;\n }\n | {\n kind: \"endpoint\";\n id: string;\n label?: string;\n key?: string;\n invokeUrl?: string;\n invokeUrlByKey?: string;\n urlForm?: \"id\" | \"key\";\n alias?: string;\n inputs?: readonly SnippetInput[];\n /**\n * The Function's / Endpoint's run-level error policy and its writer, published by an\n * editor that owns the definition buffer (`useCallableDraft`) so the rail's Error handling\n * tool edits and saves THAT buffer (pending edits ride along) instead of racing it. Same\n * ⚠️ as the workflow arm: `onPolicyChange` MUST be referentially stable\n * (`useCallableDraft`'s is).\n */\n policy?: CallablePolicy;\n onPolicyChange?: (policy: CallablePolicy) => void;\n }\n | {\n kind: \"workflow\";\n connectionResources?: WorkflowConnectionResources;\n id: string;\n label?: string;\n key?: string;\n triggers?: TriggerPreview[];\n /** Stable editor-owned actions serialize pending draft saves and refresh its buffer. */\n onRestoreVersion?: (versionNumber: number) => Promise<void>;\n /** Whether the editor buffer matches the published snapshot; absent while loading. */\n definitionStatus?: \"published\" | \"draft\" | \"unpublished\";\n /** Use the editor's save/publish guard from the sidebar too. Must be stable. */\n onPublish?: () => Promise<void>;\n publishDisabled?: boolean;\n authoringSettings?: { autoSave: boolean; savePosition: boolean };\n onAuthoringSettingChange?: (key: \"autoSave\" | \"savePosition\", value: boolean) => void;\n variables?: WorkflowVariableRow[];\n onVariablesChange?: (variables: WorkflowVariableRow[]) => void;\n onOpenHistory?: () => void;\n /**\n * The workflow's run-level error policy, and the writer that applies it\n * (core Workflow RFC — *Amendment — 2026-08-21: the run-level error\n * handler*). Published ONLY by the page that owns the definition buffer\n * — the canvas editor — so the rail's Error handling tool edits the same\n * text the editor is about to save instead of racing it over the wire.\n * `ErrorHandlingTool` is the only reader; see `lib/settings-rail.ts`'s\n * `isAvailable` for why the tool hides itself when they are absent.\n *\n * ⚠️ `onPolicyChange` MUST be referentially stable across renders (a\n * `useCallback` reading through a ref). `useWorkspace` keys its publish\n * effect on `JSON.stringify(resource)`, which drops functions — so the\n * stored callback is whichever one was current when some OTHER field\n * last changed, and a closure that captured stale editor state would\n * write stale bytes.\n */\n policy?: CallablePolicy;\n onPolicyChange?: (policy: CallablePolicy) => void;\n /** `Workflow.initialState` is a non-empty object: the rail State tool's dot. */\n hasStartingState?: boolean;\n /** `Workflow.initialState` as the editor holds it: the State panel's starting state preview. */\n startingState?: Record<string, unknown>;\n /**\n * Opens the canvas editor's starting state editor; the rail State tool shows only when it\n * is set. Same ⚠️ as `onPolicyChange`: it MUST be referentially stable.\n */\n onOpenStartingState?: () => void;\n /**\n * Opens one of this workflow's runs on the canvas (the History \"Open run\" path): the State\n * panel's link to the run its current state comes from. Same ⚠️: referentially stable.\n */\n onOpenRun?: (runId: string) => void;\n }\n | {\n kind: \"connection\";\n id: string;\n label?: string;\n /** Set by the connection ACTION page: the Code tool needs an action to show a snippet. */\n action?: string;\n /** Declared param keys of `action` (plain data — the registry keys on JSON). */\n params?: readonly SnippetInput[];\n }\n | null;\n\n/** Derived from {@link WorkspaceCallable}, never redeclared — the arm a\n * `RailTool.isAvailable`/route wrapper narrows on. */\nexport type WorkspaceKind = Exclude<WorkspaceCallable, null>[\"kind\"];\n\ninterface WorkspaceContextValue {\n resource: WorkspaceCallable;\n /** Publishes the OVERRIDE slot; `null` clears it, which restores the provider's `base`. */\n setCallable: (resource: WorkspaceCallable) => void;\n}\n\nconst WorkspaceContext = createContext<WorkspaceContextValue | null>(null);\n\n/**\n * Two layers: `base` (a prop — the host-owned `{kind, id}` a `<CallableWorkspace>` publishes) and\n * an override (what a mounted page publishes with `useWorkspace`). The override wins while it is\n * set; when its publisher unmounts it is cleared and the base is shown again — never empty. With no\n * `base` (Studio's layout, the editor's own nested provider) the behaviour is exactly the old\n * single-slot one: override or `null`.\n */\nexport function WorkspaceProvider({\n children,\n base = null,\n}: { children: ReactNode; base?: WorkspaceCallable }) {\n const [override, setCallable] = useState<WorkspaceCallable>(null);\n const resource = override ?? base;\n const value = useMemo(() => ({ resource, setCallable }), [resource]);\n return <WorkspaceContext.Provider value={value}>{children}</WorkspaceContext.Provider>;\n}\n\n/** Non-throwing probe: is there an enclosing {@link WorkspaceProvider}? */\nexport function useHasWorkspace(): boolean {\n return useContext(WorkspaceContext) !== null;\n}\n\n/** Publisher. Compute during render, effect-write, clear on unmount. */\nexport function useWorkspace(resource: WorkspaceCallable): void {\n const ctx = useContext(WorkspaceContext);\n if (!ctx) throw new Error(\"useWorkspace must be used within <WorkspaceProvider>\");\n const { setCallable } = ctx;\n // A stable serialization, not `resource` itself: a fresh object literal on\n // every render of the calling page (e.g. `{kind:\"workflow\", id}` rebuilt\n // each render) must not re-fire this effect every render — only a genuine\n // change to some field's VALUE should. T2.1.2: widened from a bespoke\n // `kind:id:label` template to a full `JSON.stringify` once the union grew\n // per-kind fields (`key`/`invokeUrl`/`invokeUrlByKey`/`urlForm`/`inputs`/\n // `triggers`) a caller can update after its first publish — e.g. the\n // Endpoint editor's id/key URL-form toggle or a picked tenant domain, both\n // of which change nothing about kind/id/label. A template keyed on\n // kind/id/label alone would miss those and leave `CodeTool`'s panel showing\n // the value from the FIRST render forever (same content -> same string ->\n // no re-fire, so this preserves the original's intent exactly, just over\n // every field instead of three of them).\n const key = resource ? JSON.stringify(resource) : \"\";\n // biome-ignore lint/correctness/useExhaustiveDependencies: keyed on the stable serialized `key`, not `resource`'s object identity — see the comment above.\n useEffect(() => {\n setCallable(resource);\n return () => setCallable(null);\n }, [key, setCallable]);\n}\n\n/** Reader — used by the rail and by every tool `Panel`. Throws outside the provider. */\nexport function useWorkspaceCallable(): WorkspaceCallable {\n const ctx = useContext(WorkspaceContext);\n if (!ctx) throw new Error(\"useWorkspaceCallable must be used within <WorkspaceProvider>\");\n return ctx.resource;\n}\n","import { restoreRailState } from \"@w6w/embed/lib\";\n/**\n * Third `.workspace` grid column: a 48px strip of the tools it is handed plus, when one is open,\n * its panel. Iterates `tools` with a single `.map` — never a per-tool JSX branch — so adding a\n * tool is a registry append in the host (Studio: `StudioRightRail`), nothing here changes.\n */\nimport { type ComponentType, useEffect, useState } from \"react\";\nimport { type WorkspaceCallable, useWorkspaceCallable } from \"./workspace.tsx\";\n\nexport interface RailTool {\n /** Stable; used as the persisted `activeTool`. */\n id: string;\n /** Strip tooltip + panel heading. */\n title: string;\n /** The strip glyph, as a component — built-in tools render a 16×16 `<Icon name=\"…\" />`\n * from `@w6w/ui`'s shared set; a tool may bring its own glyph instead. A component,\n * not an `IconName`, so this seam never narrows to the shared set. */\n Icon: ComponentType;\n isAvailable(ctx: WorkspaceCallable): boolean;\n /** Panel renders its own heading when it includes section actions. */\n rendersHeading?: boolean;\n /** Absent for an action tool: one with `onActivate` opens nothing in the rail. */\n Panel?: ComponentType<{ ctx: WorkspaceCallable }>;\n /** An action tool: the strip button calls this instead of toggling a panel (e.g. a modal). */\n onActivate?(ctx: WorkspaceCallable): void;\n /** A dot on the strip button: the tool has something set. */\n hasIndicator?(ctx: WorkspaceCallable): boolean;\n}\n\ninterface RailState {\n open: boolean;\n activeTool: string | null;\n}\n\nconst CLOSED: RailState = { open: false, activeTool: null };\n\n/**\n * T4.1.1/A2: every mount starts CLOSED, unconditionally — `open` is no\n * longer read out of storage at all (D-I0-2). `restoreRailState`\n * (`../lib/rail-settings.ts`) only ever returns `activeTool`; its return\n * type has no `open` member, so a pre-existing `{\"open\":true,…}` value\n * written before this task has nothing here to reopen the rail with.\n */\nfunction readStoredState(key: string): RailState {\n if (typeof localStorage === \"undefined\") return CLOSED;\n const raw = localStorage.getItem(key);\n const { activeTool } = restoreRailState(raw);\n return { open: false, activeTool };\n}\n\n/** Presentational: the strip + (when open) the active tool's panel. Shared by\n * the persisted and not-yet-persistable (pin 12) render paths below. */\nfunction RailShell({\n tools,\n ctx,\n state,\n onToggle,\n}: {\n tools: readonly RailTool[];\n ctx: WorkspaceCallable;\n state: RailState;\n onToggle: (id: string) => void;\n}) {\n const activeTool = state.open\n ? (tools.find((t) => t.id === state.activeTool && t.Panel) ?? null)\n : null;\n const ActivePanel = activeTool?.Panel;\n return (\n <aside className=\"right-rail\">\n <div className=\"right-rail-strip\">\n {tools.map((tool) => (\n <button\n key={tool.id}\n type=\"button\"\n data-testid={`rail-tool-${tool.id}`}\n className={`right-rail-tool-btn${activeTool?.id === tool.id ? \" active\" : \"\"}`}\n title={tool.title}\n aria-label={tool.title}\n aria-pressed={tool.onActivate ? undefined : activeTool?.id === tool.id}\n onClick={() => (tool.onActivate ? tool.onActivate(ctx) : onToggle(tool.id))}\n >\n <tool.Icon />\n {tool.hasIndicator?.(ctx) && (\n <span\n className=\"right-rail-tool-dot\"\n data-testid={`rail-tool-${tool.id}-dot`}\n aria-hidden=\"true\"\n />\n )}\n </button>\n ))}\n </div>\n {activeTool && ActivePanel && (\n <div className=\"right-rail-panel\" data-testid={`rail-panel-${activeTool.id}`}>\n {!activeTool.rendersHeading && (\n <div className=\"right-rail-panel-head\">\n <h3>{activeTool.title}</h3>\n </div>\n )}\n <ActivePanel ctx={ctx} />\n </div>\n )}\n </aside>\n );\n}\n\n/** Owns the persisted open/activeTool state. Split out from `RightRail` and\n * `key`ed on `storageKey` (pin 11/12): `currentProject` resolves from a\n * query, so a `useState` initializer that ran before it resolved would read\n * `w6w.rail.undefined.undefined`. `RightRail` renders this component only\n * once `storageKey` is non-null, and `key={storageKey}` forces a fresh\n * mount — and so a fresh synchronous read of the RESOLVED key — whenever the\n * account/project changes. */\nfunction PersistedRail({\n storageKey,\n tools,\n ctx,\n}: {\n storageKey: string;\n tools: readonly RailTool[];\n ctx: WorkspaceCallable;\n}) {\n const [state, setState] = useState<RailState>(() => readStoredState(storageKey));\n\n // A2: only `activeTool` is ever persisted — `open` is never written to\n // storage (D-I0-2), so a fresh mount always starts closed regardless of\n // whether the rail happened to be open when the tab last closed.\n useEffect(() => {\n if (typeof localStorage === \"undefined\") return;\n localStorage.setItem(storageKey, JSON.stringify({ activeTool: state.activeTool }));\n }, [storageKey, state.activeTool]);\n\n function onToggle(id: string) {\n setState((prev) =>\n prev.open && prev.activeTool === id\n ? { open: false, activeTool: id }\n : { open: true, activeTool: id },\n );\n }\n\n return <RailShell tools={tools} ctx={ctx} state={state} onToggle={onToggle} />;\n}\n\n/** `storageKey === null`: no key to persist under yet (pin 12) — the strip renders closed and\n * nothing is written to localStorage. No available tool ⇒ no rail element at all (C/D-C3). */\nexport function RightRail({\n tools,\n storageKey,\n}: {\n tools: readonly RailTool[];\n storageKey: string | null;\n}) {\n const ctx = useWorkspaceCallable();\n const available = tools.filter((t) => t.isAvailable(ctx));\n if (available.length === 0) return null;\n if (storageKey === null) {\n return <RailShell tools={available} ctx={ctx} state={CLOSED} onToggle={() => {}} />;\n }\n return <PersistedRail key={storageKey} storageKey={storageKey} tools={available} ctx={ctx} />;\n}\n","import { type ExpressionOptions, ExpressionOptionsProvider } from \"@w6w/ui\";\nimport type { ReactNode } from \"react\";\nimport { useMemo } from \"react\";\nimport { documentSampleValues, projectDocumentSources } from \"../lib/document-sources.ts\";\n/**\n * The APP-LEVEL contribution to the ƒx expression scope — the rail every\n * expression editor starts from (Studio binds `project` to its `ProjectContext`; an embedder\n * passes its own, `null` disabling the project-scoped queries), wherever it is opened.\n *\n * ## Why this is a provider and not a hook each page calls\n *\n * The scope used to travel as an `exprOptions` PROP: each page built the same\n * ~40-line object and handed it to the one or two components it happened to\n * think of. Two things went wrong with that, and both are user-visible:\n *\n * 1. **A field the prop had not reached opened an empty editor.** On a\n * Function's Implementation card, the `ƒx` toggle on a mapping row offered\n * no variables, no secrets and no inputs — while the very same editor,\n * reached through that card's \"Change\" button, offered all of them,\n * because only the modal had been wrapped in a provider.\n * 2. **Five pages carried a copy of the same object.** `FunctionsPage`,\n * `EndpointsPage`, `AliasesPage`, `WorkflowsPage` and the connection\n * tester each restated vars, secrets, documents, `sampleValues`,\n * `sealSecret`, `createVar` and `createSecret` — because the only way to\n * add one page-specific key (`inputs`) was to restate the rest alongside\n * it.\n *\n * Mounted ONCE, inside `ProjectProvider` and around `Layout`, this fixes both:\n * every route inherits it, and a page contributes only what is genuinely its\n * own by nesting a second `ExpressionOptionsProvider` (which LAYERS — see that\n * component's own doc). A page's `inputs` therefore cannot reach a sibling\n * route or a region above it; navigating away drops it with the subtree.\n *\n * ## What belongs here, and what does not\n *\n * Here: anything true for the whole **project** — its variables, its secret\n * NAMES, its document keys, the sample values the Result pane previews against,\n * and the three host callbacks the picker's \"+ Add\"/seal affordances need.\n *\n * Not here: anything that is only true inside one editor. A Function's declared\n * `inputs`, an Endpoint's declared `input`, the upstream `steps` leading to one\n * workflow node — those are contributed by the page or the region that knows\n * about them, and must not be visible anywhere else.\n *\n * `ui` components stay pure (they never fetch): this is the host side, and only\n * names/refs cross the boundary — secret plaintext never reaches the client.\n */\nimport {\n useConstantsQuery,\n useCreateSecretMutation,\n useCreateVarMutation,\n useDocumentsQuery,\n useSealSecret,\n useSecretsQuery,\n useVarsQuery,\n} from \"../repos/index.ts\";\n\n/**\n * The current project's expression sources, as an `ExpressionOptions`.\n *\n * Exported because a surface that renders OUTSIDE `ProjectExpressionScope` —\n * or one that needs the values themselves rather than the context — can still\n * build the same object. Inside the scope, prefer inheriting it.\n */\nexport function useProjectExpressionOptions(project: string | null): ExpressionOptions {\n const projectId = project;\n\n // Vars/secrets are subject-scoped (no project param on the secret list); the\n // vault list is masked name-only summaries, so nothing secret reaches the\n // client. Documents are project-scoped.\n const varsQuery = useVarsQuery(projectId ?? undefined, projectId != null);\n const secretsQuery = useSecretsQuery();\n const constantsQuery = useConstantsQuery();\n const documentsQuery = useDocumentsQuery(projectId ?? undefined, projectId != null);\n const sealSecretFn = useSealSecret();\n // \"+ Add\" (T1.2.4): both mutations already invalidate the exact key their\n // `useQuery` reads (repos/vars.ts, repos/vault.ts), so a create's success\n // alone refreshes the rail — no refetch(), no local list state.\n const createVarMut = useCreateVarMutation();\n const createSecretMut = useCreateSecretMutation();\n\n return useMemo(\n () => ({\n vars: (varsQuery.data ?? []).map((v) => v.name),\n constants: (constantsQuery.data ?? []).map((c) => c.name),\n secrets: (secretsQuery.data ?? []).map((s) => s.name),\n // `document-sources.ts` owns the `format === \"json\"` gate and the raw\n // field enumeration — no parsing, no gate logic, and no filtering here\n // (A5c); `isRefSafeKey` filtering happens once, downstream, at the\n // modal's render site.\n documents: projectDocumentSources(documentsQuery.data ?? []),\n // Real project values so the ƒx Result preview substitutes them for\n // `var.<name>` / `const.<name>` / `documents.<key>` / `documents.<key>.<field>` refs\n // instead of the raw template.\n sampleValues: {\n ...Object.fromEntries((varsQuery.data ?? []).map((v) => [`var.${v.name}`, v.value])),\n ...Object.fromEntries((constantsQuery.data ?? []).map((c) => [`const.${c.name}`, c.value])),\n ...documentSampleValues(documentsQuery.data ?? []),\n },\n sealSecret: sealSecretFn,\n // A created var carries the SAME project the read above carried (B3) —\n // it must land in the project whose rail asked for it. `type: \"string\"`\n // is pinned (a string type's `raw` passes through untouched) — the modal\n // has no type field.\n createVar: (input: { name: string; value: string; description?: string }) =>\n createVarMut\n .mutateAsync({\n input: {\n name: input.name,\n type: \"string\",\n value: input.value,\n description: input.description,\n },\n project: projectId ?? undefined,\n })\n .then(() => undefined),\n // Secrets carry NO project (B4) — `vault_secrets` has no `project`\n // column and the routes read no `?project=`. Plaintext in, the server\n // encrypts; the resolved value is referenced nowhere (B5).\n createSecret: (input: { name: string; value: string; description?: string }) =>\n createSecretMut\n .mutateAsync({ name: input.name, value: input.value, description: input.description })\n .then(() => undefined),\n }),\n [\n varsQuery.data,\n constantsQuery.data,\n secretsQuery.data,\n documentsQuery.data,\n sealSecretFn,\n createVarMut.mutateAsync,\n createSecretMut.mutateAsync,\n projectId,\n ],\n );\n}\n\n/**\n * Provide the current project's expression sources to every route below.\n *\n * Mount once, inside `ProjectProvider` (it reads the active project) and around\n * `Layout` (so every page inherits). It contributes no `inputs` and no `steps`\n * on purpose — see the module doc.\n */\nexport function ProjectExpressionScope({\n project,\n children,\n}: {\n project: string | null;\n children: ReactNode;\n}) {\n const options = useProjectExpressionOptions(project);\n return <ExpressionOptionsProvider value={options}>{children}</ExpressionOptionsProvider>;\n}\n","import { Icon } from \"@w6w/ui\";\nimport { useState } from \"react\";\nimport {\n CallFromCodeBody,\n type SnippetTabId,\n snippetTabsFor,\n} from \"../chrome/CallFromCodeButton.tsx\";\nimport { Modal } from \"../chrome/Modal.tsx\";\nimport type { RailTool } from \"../chrome/RightRail.tsx\";\nimport type { WorkspaceCallable } from \"../chrome/workspace.tsx\";\nimport { isAvailable, toSnippetCallable } from \"../lib/code-rail.ts\";\nimport { unavailableReason } from \"../lib/sdk-snippets.ts\";\n/**\n * The Code tool — the right rail's second registered client of T3.1.1's\n * registry seam (`src/ui/railTools.ts`), and T2.1.2's \"use code\" move: the\n * page-header \"Call from code\" button on Functions/Endpoints/Workflow-detail/\n * the flow-editor canvas becomes this strip icon + panel instead.\n *\n * The two pure decisions — is a snippet meaningful for this context, and\n * what `SnippetCallable` it converts to — live in `./../lib/code-rail.ts` so\n * `node --test` can gate them. This module owns presentation only.\n *\n * The panel is a LANGUAGE PICKER, not a snippet. It used to render\n * `CallFromCodeBody` inline, and a snippet is not readable in a ~395px\n * column: it scrolled sideways, and wrapping it (the first fix) turned the\n * CLI snippet's deliberate `\\`-continuations into what reads as separate\n * commands. Both are symptoms of the same thing — the snippet needs width the\n * rail does not have.\n *\n * So the rail shows one icon per language the resource can be called in, and\n * each opens the full-width modal ALREADY ON THAT LANGUAGE: one click to the\n * thing you came for, rather than open-then-hunt-for-the-tab. The set of\n * languages comes from `snippetTabsFor`, the same filter the modal's own tab\n * strip applies, so the rail can never offer a language the modal would not.\n */\n\nfunction CodePanel({ ctx }: { ctx: WorkspaceCallable }) {\n // Which language the modal opens on, or `null` for closed. ONE piece of\n // state, not an `open` flag beside a `tab`: the two can never disagree, and\n // \"closed\" cannot carry a stale language into the next open.\n const [openTab, setOpenTab] = useState<SnippetTabId | null>(null);\n const snippetCallable = toSnippetCallable(ctx);\n // Defensive: `isAvailable` already keeps this tool off the strip for a\n // `ctx` this can't build a snippet for — mirrors `SettingsTool.tsx`'s own\n // note about `Panel` still needing to handle a ctx `isAvailable` would\n // have excluded (a persisted `activeTool` plus an in-app transition to a\n // non-publishing route can still render this Panel).\n if (!snippetCallable) return null;\n const triggers = ctx?.kind === \"workflow\" ? ctx.triggers : undefined;\n const tabs = snippetTabsFor(snippetCallable);\n\n // No languages means no snippet at all — say why, rather than draw an empty\n // row of icons. Same sentence the body itself would have shown.\n if (tabs.length === 0) return <p className=\"muted\">{unavailableReason(snippetCallable)}</p>;\n\n return (\n <div>\n {/* A LANGUAGE PICKER, not a snippet.\n\n The rail's panel is ~395px wide, and a snippet rendered into it was\n unreadable at that width — first because it scrolled sideways, then,\n once wrapped, because a wrapped shell command reads as two commands.\n Neither is fixable in 395px: the snippet needs the room.\n\n So the panel stops trying to show one. It shows the languages this\n resource can be called in, and each opens the full-width modal\n ALREADY ON THAT LANGUAGE — one click to the thing you came for,\n instead of open-then-hunt-for-the-tab. The languages come from\n `snippetTabsFor`, so a resource with no public URL simply has no curl\n icon rather than an icon that opens an empty tab.\n\n Still not the double-chrome `CallFromCodeButton.tsx`'s header warns\n about: that trap was wrapping the rail's own panel in a modal by\n DEFAULT. The panel is its own content here; the modal is opt-in. */}\n <p className=\"muted small\" style={{ marginTop: 0 }}>\n Call this from:\n </p>\n <div className=\"rail-code-langs\">\n {tabs.map(({ id, label, icon }) => (\n <button\n key={id}\n type=\"button\"\n className=\"rail-code-lang\"\n data-testid={`rail-code-lang-${id}`}\n title={`Show the ${label} snippet`}\n aria-label={`Show the ${label} snippet`}\n onClick={() => setOpenTab(id)}\n >\n <Icon name={icon} size={20} />\n <span>{label}</span>\n </button>\n ))}\n </div>\n\n {/* Conditionally rendered, so each open MOUNTS the body afresh and\n `initialTab` seeds it again — picking Python, closing, then picking\n Node lands on Node. A body kept mounted would keep the first pick. */}\n {openTab !== null && (\n <Modal title=\"Call from code\" wide onClose={() => setOpenTab(null)}>\n <div style={{ height: 450 }}>\n <CallFromCodeBody resource={snippetCallable} triggers={triggers} initialTab={openTab} />\n </div>\n </Modal>\n )}\n </div>\n );\n}\n\nfunction CodeToolIcon() {\n return <Icon name=\"code\" />;\n}\n\nexport const codeTool: RailTool = {\n id: \"code\",\n title: \"Code\",\n Icon: CodeToolIcon,\n isAvailable: (ctx) => isAvailable(ctx),\n Panel: CodePanel,\n};\n","import { Icon } from \"@w6w/ui\";\nimport { WorkflowConnectionsPanel } from \"@w6w/ui/flow\";\nimport type { RailTool } from \"../chrome/RightRail.tsx\";\n\nexport const connectionsTool: RailTool = {\n id: \"connections\",\n title: \"Connections\",\n rendersHeading: true,\n Icon: () => <Icon name=\"plug\" />,\n isAvailable: (ctx) => ctx?.kind === \"workflow\" && !!ctx.connectionResources,\n hasIndicator: (ctx) =>\n ctx?.kind === \"workflow\" && Object.keys(ctx.connectionResources?.connections ?? {}).length > 0,\n Panel: ({ ctx }) =>\n ctx?.kind === \"workflow\" && ctx.connectionResources ? (\n <WorkflowConnectionsPanel key={ctx.id} resources={ctx.connectionResources} />\n ) : null,\n};\n","/**\n * The rail's host environment — the two things a rail tool needs from the host that it cannot\n * own: which project the surface is looking at, and how to move the host somewhere after a\n * rail action (archive / delete land on the list; an import opens the imported row).\n *\n * Studio binds both to its router and `ProjectContext`; an embedder binds them to its own. A\n * rail tool never imports a router: it calls `onNavigate` with a target and the host decides what\n * that means. The default (no provider mounted) is inert — no project, navigation ignored — so a\n * tool rendered outside a provider cannot save into the wrong project or throw.\n *\n * `project` is passed through to every write VERBATIM; `null` means \"no project\", on which the\n * package hooks refuse to save (never a fallback to the account default, C/D-C2).\n */\nimport { type ReactNode, createContext, useContext } from \"react\";\nimport type { SpecImportKind } from \"../lib/spec-import-invalidation.ts\";\n\n/** Where the host should go after a rail action. */\nexport type RailNavigation =\n | { type: \"list\" }\n | { type: \"imported\"; kind: SpecImportKind; id: string };\n\nexport interface RailEnv {\n project: string | null;\n onNavigate(to: RailNavigation): void;\n}\n\nconst DEFAULT_ENV: RailEnv = { project: null, onNavigate: () => {} };\n\nconst RailEnvContext = createContext<RailEnv>(DEFAULT_ENV);\n\nexport function RailEnvProvider({\n project,\n onNavigate,\n children,\n}: RailEnv & { children: ReactNode }) {\n return (\n <RailEnvContext.Provider value={{ project, onNavigate }}>{children}</RailEnvContext.Provider>\n );\n}\n\nexport function useRailEnv(): RailEnv {\n return useContext(RailEnvContext);\n}\n","import { ApiError } from \"@w6w/sdk\";\n/**\n * The Error handling tool — the right rail's tool for choosing **what runs when a call fails**.\n *\n * It is a BUTTON, not a form. Clicking it opens the F-2.0 picker modal (`StepBuilderModal`) with\n * its Functions and Workflows tabs, and the pick becomes the resource's `reroute.target`. All\n * three handler shapes are offered: an app Action, a Function, or a Workflow.\n *\n * This module owns two things:\n * - `ErrorHandlerSection` — the shared body (picker, handler label lookup, self-decision,\n * retry / reroute fields and the inline error). It calls no definition query and no save\n * mutation: the caller hands in the `policy` it read and an `onPersist` that writes.\n * - `errorHandlingTool` — the registry entry for all three kinds. A Workflow, and a Function /\n * Endpoint whose editor published `ctx.onPolicyChange`, hand the policy back to the surface\n * that owns the definition buffer, which folds it into the JSON it is already saving (the\n * rail makes zero writes — racing an editor's own save is not an option, see\n * `lib/settings-rail.ts`'s `isAvailable`). A Function / Endpoint with NO published writer\n * reads the cached record (`callableRecord`) and read-modify-writes the whole definition\n * (`definitionWithPolicy`) through the guarded save with that record's `updatedAt`.\n *\n * For a Workflow this is the handler for the RUN AS A WHOLE (core Workflow RFC — *Amendment —\n * 2026-08-21: the run-level error handler*), which is a different question from a step's own\n * `onError` on the canvas and from an `Edge.when: \"error\"`. `retry` IS authored here, through\n * `@w6w/ui`'s `RetryPolicyFields` (core Workflow RFC R-2, \"one retry shape everywhere\").\n */\nimport { type BuiltStep, Icon, RetryPolicyFields, StepBuilderModal } from \"@w6w/ui\";\nimport { useEffect, useState } from \"react\";\nimport type { RailTool } from \"../chrome/RightRail.tsx\";\nimport type { WorkspaceCallable } from \"../chrome/workspace.tsx\";\nimport { callableRecord } from \"../lib/callable-record.ts\";\nimport { errorHandlerSelfDecision } from \"../lib/error-handler-self.ts\";\nimport {\n type CallablePolicy,\n isAvailable as isSettingsRailAvailable,\n policyFromDefinition,\n} from \"../lib/settings-rail.ts\";\nimport { definitionWithPolicy } from \"../lib/settings-rail.ts\";\nimport { useEndpointQuery, useGuardedSaveEndpointMutation } from \"../repos/endpoints.ts\";\nimport {\n useFunctionQuery,\n useFunctionsQuery,\n useGuardedSaveFunctionMutation,\n} from \"../repos/functions.ts\";\nimport { useWorkflowsQuery } from \"../repos/workflows.ts\";\nimport { useRailEnv } from \"./rail-env.tsx\";\n\n/**\n * `@w6w/ui/flow`'s `CALL_APP`, restated: a VALUE import from the flow subpath would put the whole\n * canvas on the editor's eager path (the editor loads it with a dynamic `import()` only). A test\n * (`workflow-editor.test.ts`) pins the two spellings equal.\n */\nexport const CALL_APP = \"@w6w/call\";\n\ntype ErrorHandlerTarget = NonNullable<NonNullable<CallablePolicy[\"reroute\"]>[\"target\"]>;\n\nexport type ErrorHandlerKind = \"function\" | \"endpoint\" | \"workflow\";\n\n/** The id a handler target names, whichever of the three arms it is. */\nfunction refOf(target: ErrorHandlerTarget | undefined): string {\n if (!target) return \"\";\n if (target.kind === \"workflow\") return target.workflow;\n if (target.kind === \"function\") return target.function;\n return `${target.uses.app}/${target.uses.action}`;\n}\n\n/** The noun shown under a bound handler. */\nfunction nounOf(target: ErrorHandlerTarget | undefined): string {\n if (target?.kind === \"workflow\") return \"Workflow (asynchronous)\";\n if (target?.kind === \"function\") return \"Function (synchronous)\";\n return \"App action (synchronous)\";\n}\n\nexport interface ErrorHandlerSectionProps {\n kind: ErrorHandlerKind;\n id: string;\n /** The policy as currently stored (already read off the definition or buffer). */\n policy: CallablePolicy;\n /** The definition (or buffer) the policy was read from is present. */\n ready: boolean;\n saving: boolean;\n /** Write a whole new policy. `onError` shows a refusal inline. */\n onPersist(next: CallablePolicy, onError: (message: string) => void): void;\n}\n\nexport function ErrorHandlerSection({\n kind,\n id,\n policy,\n ready,\n saving,\n onPersist,\n}: ErrorHandlerSectionProps) {\n // Name the bound handler rather than showing a bare id. Both lists are already cached by the\n // picker itself, so this costs no extra round-trip in the common case.\n const functionsQuery = useFunctionsQuery(true);\n // The editor's project (RailEnv, as the Settings tool reads it), never the provider's default:\n // a project-less list would go out as the provider's project, not the one being edited.\n const { project } = useRailEnv();\n const workflowsQuery = useWorkflowsQuery(project ?? undefined, true);\n\n const [pickerOpen, setPickerOpen] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const target = policy.reroute?.target;\n const ref = refOf(target);\n const selfDecision = target\n ? errorHandlerSelfDecision({\n resource: { kind, id },\n target: { kind: target.kind, id: ref },\n hasAdapter: policy.reroute?.with !== undefined,\n })\n : \"allow\";\n const label =\n target?.kind === \"workflow\"\n ? (workflowsQuery.data?.find((w) => w.id === ref)?.displayName ?? undefined)\n : (() => {\n const fn = functionsQuery.data?.find((f) => f.id === ref);\n return fn ? fn.displayName || fn.key : undefined;\n })();\n\n // The rail remains mounted while its resource changes. A refusal belonging to the previous\n // resource must not obscure the current policy.\n useEffect(() => {\n if (id && kind) setError(null);\n }, [id, kind]);\n\n /** Persist a whole new policy — the one write path, shared by pick and clear. */\n function persist(next: CallablePolicy) {\n setError(null);\n onPersist(next, setError);\n }\n\n /**\n * The picker's `onAdd`. Two shapes reach here, because all three handler arms are offered:\n * - a callable → `{ uses: {app: \"@w6w/call\", …}, with: {targetKind, targetId} }`\n * - an action → `{ uses: {app, action, connection}, with }`\n * A graph-only internal node (`@w6w/script`, `@w6w/control`, …) is refused — `appsOnly` means no\n * such tab is rendered, but a `BuiltStep` is a wide type and a silent mis-write would be\n * invisible.\n */\n function pickHandler(built: BuiltStep) {\n let nextTarget: ErrorHandlerTarget;\n if (built.uses.app === CALL_APP) {\n const w = (built.with ?? {}) as { targetKind?: unknown; targetId?: unknown };\n const nextId = typeof w.targetId === \"string\" ? w.targetId : \"\";\n if (!nextId) return;\n nextTarget =\n w.targetKind === \"workflow\"\n ? { kind: \"workflow\", workflow: nextId }\n : { kind: \"function\", function: nextId };\n } else if (!built.uses.app.startsWith(\"@w6w/\")) {\n // The app arm. `with` is the action's own param map, straight from the picker's Configure\n // stage — it is `ActionTarget.with`, which `error-handler.ts` reads in preference to the\n // general `reroute.with`.\n nextTarget = {\n kind: \"action\",\n uses: {\n app: built.uses.app,\n action: built.uses.action,\n connection: built.uses.connection ?? undefined,\n },\n ...(built.with ? { with: built.with } : {}),\n };\n } else {\n return;\n }\n const nextDecision = errorHandlerSelfDecision({\n resource: { kind, id },\n target: { kind: nextTarget.kind, id: refOf(nextTarget) },\n hasAdapter: policy.reroute?.with !== undefined,\n });\n if (nextDecision === \"block\") {\n setError(\n \"This handler would call itself with the same inputs and can loop forever. Choose another handler or keep a differing imported adapter.\",\n );\n setPickerOpen(false);\n return;\n }\n // Preserve `reroute.with` if one was already authored elsewhere — this tool changes WHICH\n // handler runs, never the mapping onto it.\n persist({ ...policy, reroute: { ...policy.reroute, target: nextTarget } });\n setPickerOpen(false);\n }\n\n if (!ready && !saving) {\n return <p className=\"muted small\">Loading…</p>;\n }\n\n return (\n <div className=\"w6w-stack\" data-testid=\"rail-errorhandling-body\">\n {/* Retries run BEFORE the handler below, so the section renders first. */}\n <section data-testid=\"rail-retry-section\">\n <RetryPolicyFields\n value={policy.retry}\n onChange={(next) => persist({ ...policy, retry: next })}\n readOnly={saving}\n target={kind}\n />\n {kind === \"workflow\" && (\n <p className=\"muted small\" data-testid=\"rail-retry-run-warning\">\n Retrying re-runs the whole workflow from its first step, so steps that already succeeded\n run again. For a step that must not repeat (a send or a charge), set retry on that step\n instead.\n </p>\n )}\n </section>\n\n <p className=\"muted small\">\n {kind === \"workflow\"\n ? \"What runs when this workflow's run fails, after every node's own retry is spent.\"\n : \"What runs when this call fails, after retry (if any) is exhausted.\"}\n </p>\n\n {ref ? (\n <div className=\"row\" style={{ alignItems: \"center\", gap: 8 }}>\n <span className=\"list-main\">\n <strong>{label ?? ref}</strong> <code className=\"muted\">{ref}</code>\n <span className=\"muted small block\">{nounOf(target)}</span>\n </span>\n <button\n type=\"button\"\n className=\"btn ghost\"\n data-testid=\"rail-errorhandling-change\"\n disabled={saving}\n onClick={() => setPickerOpen(true)}\n >\n Change\n </button>\n </div>\n ) : (\n <button\n type=\"button\"\n className=\"btn\"\n data-testid=\"rail-errorhandling-choose\"\n disabled={saving}\n onClick={() => setPickerOpen(true)}\n >\n + Choose what runs on failure\n </button>\n )}\n\n {ref && (\n <button\n type=\"button\"\n className=\"btn ghost\"\n data-testid=\"rail-errorhandling-clear\"\n disabled={saving}\n onClick={() => persist({ ...policy, reroute: undefined })}\n >\n Remove handler\n </button>\n )}\n\n {selfDecision === \"warn\" && (\n <div className=\"result error\" data-testid=\"rail-errorhandling-self-caution\">\n This handler targets itself. Its imported input adapter is preserved; the server will\n refuse it if it resolves to the failed call's same inputs.\n </div>\n )}\n\n {error && (\n <div className=\"error\" data-testid=\"rail-errorhandling-error\">\n {error}\n </div>\n )}\n\n {pickerOpen && (\n <StepBuilderModal\n appsOnly\n callables={[\"function\", \"workflow\"] as const}\n title=\"Choose what runs on failure\"\n onClose={() => setPickerOpen(false)}\n onAdd={pickHandler}\n />\n )}\n </div>\n );\n}\n\n/**\n * The buffer arm: policy read off the host's buffer (`ctx.policy`), written back through\n * `ctx.onPolicyChange`. A workflow's only arm; a function / endpoint's when an editor owns the\n * buffer.\n */\nfunction BufferErrorHandlingPanel({ ctx }: { ctx: Exclude<WorkspaceCallable, null> }) {\n const policy = \"policy\" in ctx ? ctx.policy : undefined;\n const onPolicyChange = \"onPolicyChange\" in ctx ? ctx.onPolicyChange : undefined;\n return (\n <ErrorHandlerSection\n kind={ctx.kind as ErrorHandlerKind}\n id={ctx.id}\n policy={policy ? policyFromDefinition(policy) : {}}\n ready={Boolean(onPolicyChange)}\n saving={false}\n onPersist={(next) => onPolicyChange?.(next)}\n />\n );\n}\n\n/** The cache arm: a function / endpoint with no published writer saves from the cached record. */\nfunction CachedErrorHandlingPanel({ id, kind }: { id: string; kind: \"function\" | \"endpoint\" }) {\n const fnQuery = useFunctionQuery(id, kind === \"function\");\n const epQuery = useEndpointQuery(id, kind === \"endpoint\");\n const saveFnMut = useGuardedSaveFunctionMutation();\n const saveEpMut = useGuardedSaveEndpointMutation();\n\n const record = callableRecord(kind, kind === \"function\" ? fnQuery.data : epQuery.data);\n const saving = kind === \"function\" ? saveFnMut.isPending : saveEpMut.isPending;\n\n return (\n <ErrorHandlerSection\n kind={kind}\n id={id}\n policy={record ? policyFromDefinition(record.definition) : {}}\n ready={Boolean(record)}\n saving={saving}\n onPersist={(next, onError) => {\n if (!record) return;\n const vars = {\n definition: definitionWithPolicy(record.definition, next),\n ifUnmodifiedSince: record.updatedAt,\n };\n const settled = {\n onError: (e: unknown) => onError(e instanceof ApiError ? e.message : String(e)),\n };\n if (kind === \"function\") saveFnMut.mutate(vars, settled);\n else saveEpMut.mutate(vars, settled);\n }}\n />\n );\n}\n\nfunction ErrorHandlingPanel({ ctx }: { ctx: WorkspaceCallable }) {\n // Defensive: a persisted `activeTool` can render this Panel with a ctx this tool has no handler\n // for.\n if (ctx?.kind !== \"workflow\" && ctx?.kind !== \"function\" && ctx?.kind !== \"endpoint\") {\n return null;\n }\n if (ctx.kind === \"workflow\" || typeof ctx.onPolicyChange === \"function\") {\n return <BufferErrorHandlingPanel ctx={ctx} />;\n }\n return <CachedErrorHandlingPanel id={ctx.id} kind={ctx.kind} />;\n}\n\nfunction ErrorHandlingToolIcon() {\n return <Icon name=\"warning\" />;\n}\n\nexport const errorHandlingTool: RailTool = {\n id: \"error-handling\",\n title: \"Error handling\",\n Icon: ErrorHandlingToolIcon,\n isAvailable: (ctx) => isSettingsRailAvailable(ctx),\n Panel: ErrorHandlingPanel,\n};\n","import { Icon } from \"@w6w/ui\";\nimport type { RailTool } from \"../chrome/RightRail.tsx\";\n\nexport const historyTool: RailTool = {\n id: \"history\",\n title: \"Execution history\",\n Icon: () => <Icon name=\"history\" />,\n isAvailable: (ctx) => ctx?.kind === \"workflow\" && !!ctx.onOpenHistory,\n onActivate: (ctx) => {\n if (ctx?.kind === \"workflow\") ctx.onOpenHistory?.();\n },\n};\n","/**\n * Pure decision logic behind `../components/TagEditor.tsx` — kept out of the\n * component so `node --test` can exercise it directly\n * (`__tests__/tag-editor.test.ts`) without touching React, mirroring\n * `alias-rail.ts`/`rail-settings.ts`'s own split. Carries over the retiring\n * `WorkflowsPage.tsx`'s retired tags-editing modal's data contract verbatim:\n * `string[]`, trim, dedupe-on-add, drop empties.\n */\n\n/**\n * Applies a chip input's freeform text to the committed tag list. Called on\n * every change to the trailing, not-yet-committed input — `typed` is always\n * the FULL current value of just that one input, which resets to `\"\"` after\n * a commit, so a single keystroke never carries more than the one character\n * just typed.\n *\n * A comma anywhere in `typed` is the commit signal: every comma-delimited\n * segment is trimmed and, if non-empty and not already present, appended as\n * a chip — in order, regardless of whether it sits before or after the last\n * comma. That is what makes both shapes work from the one rule: typing\n * `\"alpha,\"` one character at a time commits `\"alpha\"` the moment the comma\n * lands, and pasting `\"a,b,c\"` in one go (no trailing comma at all) still\n * commits all three, because nothing here treats \"the last segment\" as\n * special. The returned `typed` is always `\"\"` once a comma triggered a\n * commit. With no comma present at all, nothing commits and `typed` passes\n * through unchanged, so the caller can just store it as the next draft.\n */\nexport function commitTag(tags: string[], typed: string): { tags: string[]; typed: string } {\n if (!typed.includes(\",\")) return { tags, typed };\n let next = tags;\n for (const raw of typed.split(\",\")) {\n const t = raw.trim();\n if (t && !next.includes(t)) next = [...next, t];\n }\n return { tags: next, typed: \"\" };\n}\n\n/**\n * Removes exactly one tag by VALUE, never by position — a list carrying both\n * a tag and a second tag that merely contains it as a prefix (`[\"ab\", \"b\"]`)\n * only ever loses the exact match.\n */\nexport function removeTag(tags: string[], tag: string): string[] {\n return tags.filter((t) => t !== tag);\n}\n","import { IconButton } from \"@w6w/ui\";\nimport { useState } from \"react\";\nimport { commitTag, removeTag } from \"../lib/tag-editor.ts\";\n\n/**\n * A chip input for a workflow's free-form tags: type text, `,` commits the\n * typed value as a chip (or paste a whole comma-separated list to commit\n * several at once — `../lib/tag-editor.ts`'s `commitTag`), each chip carries\n * an `×` to remove it, and a still-typable tail follows the chips — one\n * control, not a stacked input-above-list.\n *\n * Built fresh (T2.2.1) rather than extended from the retiring\n * `WorkflowsPage.tsx` tags-editing modal: that component was a submit-button\n * \"Add\" form with its own inline add/remove branching, a different\n * interaction shape from a comma-commits chip editor. The shared data\n * contract (trim, dedupe-on-add, drop empties) now lives in\n * `../lib/tag-editor.ts`'s\n * `commitTag`/`removeTag`, so this component holds no branching of its own —\n * it only calls them and renders the result. Controlled, mirroring\n * `InputListEditor.tsx`'s shape: the caller owns `tags`, this component owns\n * only the not-yet-committed typed tail.\n */\nexport interface TagEditorProps {\n tags: string[];\n onChange: (next: string[]) => void;\n}\n\nexport function TagEditor({ tags, onChange }: TagEditorProps) {\n const [typed, setTyped] = useState(\"\");\n\n function handleTypedChange(value: string) {\n const result = commitTag(tags, value);\n setTyped(result.typed);\n if (result.tags !== tags) onChange(result.tags);\n }\n\n return (\n <div className=\"tag-list\" data-testid=\"tag-editor\">\n {tags.map((t) => (\n <span key={t} className=\"tag removable\">\n {t}\n <IconButton\n danger\n icon=\"close\"\n label={`Remove tag ${t}`}\n title={`Remove ${t}`}\n onClick={() => onChange(removeTag(tags, t))}\n />\n </span>\n ))}\n <input\n type=\"text\"\n value={typed}\n placeholder=\"Add a tag…\"\n aria-label=\"New tag\"\n onChange={(e) => handleTypedChange(e.target.value)}\n />\n </div>\n );\n}\n","import { filterKeyInput, isEndpointKey } from \"@w6w/embed/lib\";\n/**\n * Unified settings modal for editing name, key, and tags (workflow only)\n * in a single dialog. Replaces separate Edit Key and Edit Tags modals.\n * Supports Function, Endpoint, and Workflow kinds.\n *\n * T4.2.1: every kind-shaped decision this component used to make inline — may\n * the key be typed at all, does this kind store tags, which placeholder goes in\n * which field — now comes from `CALLABLE_DESCRIPTORS[kind].settings`\n * (`lib/callable-descriptors.ts`). There is deliberately **no `kind ===` left in\n * this file**: a fourth kind, or a copy change, is an edit to the descriptor\n * table and to nothing else. The rendered output is byte-identical to before —\n * same labels, same placeholders, same hint sentence, same conditional Tags\n * section.\n */\nimport { descriptorFor } from \"@w6w/embed/repos\";\nimport { ApiError } from \"@w6w/sdk\";\nimport { useEnterSubmit } from \"@w6w/ui\";\nimport { useState } from \"react\";\nimport { Modal } from \"./Modal.tsx\";\nimport { TagEditor } from \"./TagEditor.tsx\";\n\ninterface CallableSettingsModalProps {\n kind: \"function\" | \"endpoint\" | \"workflow\";\n id: string;\n initial: {\n displayName: string;\n key: string | null;\n tags?: string[]; // workflow only\n };\n onSave: (data: {\n displayName: string;\n key: string | null;\n tags?: string[];\n }) => Promise<void>;\n onClose: () => void;\n}\n\nexport function CallableSettingsModal(props: CallableSettingsModalProps) {\n // The one kind lookup this component makes. `settings` then answers every\n // per-kind question below, including which of the three `initial` fields this\n // kind even has.\n const settings = descriptorFor(props.kind).settings;\n const { initial } = props;\n const [displayName, setDisplayName] = useState(initial.displayName);\n const [key, setKey] = useState(initial.key ?? \"\");\n const [tags, setTags] = useState<string[]>(initial.tags ?? []);\n const [isSaving, setIsSaving] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const displayNameChanged = displayName !== initial.displayName;\n const keyChanged = key !== (initial.key ?? \"\");\n const tagsChanged =\n settings.hasTags && JSON.stringify(tags) !== JSON.stringify(initial.tags ?? []);\n const isDirty = displayNameChanged || keyChanged || tagsChanged;\n\n // Key can be edited for function/workflow only (not endpoint)\n const canEditKey = settings.canEditKey;\n const keyGrammarOk = key === \"\" || isEndpointKey(key);\n const canSubmit = isDirty && keyGrammarOk && !isSaving;\n\n async function handleSave() {\n if (!canSubmit) return;\n setError(null);\n setIsSaving(true);\n try {\n await props.onSave({\n displayName: displayName.trim(),\n key: canEditKey && keyChanged ? key : initial.key,\n tags: settings.hasTags ? tags : undefined,\n });\n props.onClose();\n } catch (e) {\n setError(e instanceof ApiError ? e.message : String(e));\n } finally {\n setIsSaving(false);\n }\n }\n\n const enterSubmit = useEnterSubmit(handleSave, { enabled: canSubmit });\n\n return (\n <Modal title=\"Edit settings\" onClose={props.onClose}>\n <div className=\"modal-body\">\n <label className=\"field\">\n <span>Name</span>\n <input\n type=\"text\"\n value={displayName}\n onChange={(e) => setDisplayName(e.target.value)}\n placeholder={settings.namePlaceholder}\n autoFocus\n {...enterSubmit}\n />\n </label>\n\n {canEditKey && (\n <label className=\"field\">\n <span>Key</span>\n <input\n type=\"text\"\n value={key}\n onChange={(e) => setKey(filterKeyInput(e.target.value))}\n placeholder={settings.keyPlaceholder}\n {...enterSubmit}\n />\n <span className=\"muted small\">\n Lowercase, kebab-case, 3–39 characters.\n {settings.keyHintSuffix}\n </span>\n </label>\n )}\n\n {settings.hasTags && (\n <div>\n <p className=\"muted small\" style={{ marginBottom: \"8px\" }}>\n Tags\n </p>\n <TagEditor tags={tags} onChange={setTags} />\n </div>\n )}\n\n {error && <div className=\"error\">{error}</div>}\n </div>\n\n <div className=\"modal-actions\">\n <button type=\"button\" className=\"btn ghost\" onClick={props.onClose}>\n Cancel\n </button>\n <button type=\"button\" className=\"btn\" disabled={!canSubmit} onClick={handleSave}>\n {isSaving ? \"Saving…\" : \"Save\"}\n </button>\n </div>\n </Modal>\n );\n}\n","import {\n type VersionsKind,\n useInvokeVersionMutation,\n useRevertMutation,\n useVersionQuery,\n} from \"@w6w/embed/repos\";\nimport { ApiError } from \"@w6w/sdk\";\nimport { CodeBlock } from \"@w6w/ui\";\nimport { useState } from \"react\";\nimport { ConfirmModal } from \"./ConfirmModal.tsx\";\nimport { Modal } from \"./Modal.tsx\";\n\n/**\n * P2's `<collection>-version-*` testid scheme, spelled out literally per kind rather than built\n * by string interpolation — mirrors `ImportSpecModal.tsx`'s own `TESTIDS` reasoning: this file's\n * own kind arms stay the exact byte strings a page-guard suite would assert against, verifiable\n * by a plain substring search rather than only by running the browser suite.\n */\nconst TESTIDS: Record<\n VersionsKind,\n {\n json: string;\n error: string;\n revertButton: string;\n invokeButton: string;\n invokeJson: string;\n invokeError: string;\n }\n> = {\n function: {\n json: \"functions-version-json\",\n error: \"functions-version-error\",\n revertButton: \"functions-version-revert\",\n invokeButton: \"functions-version-invoke\",\n invokeJson: \"functions-version-invoke-json\",\n invokeError: \"functions-version-invoke-error\",\n },\n workflow: {\n json: \"workflows-version-json\",\n error: \"workflows-version-error\",\n revertButton: \"workflows-version-revert\",\n invokeButton: \"workflows-version-invoke\",\n invokeJson: \"workflows-version-invoke-json\",\n invokeError: \"workflows-version-invoke-error\",\n },\n endpoint: {\n json: \"endpoints-version-json\",\n error: \"endpoints-version-error\",\n revertButton: \"endpoints-version-revert\",\n invokeButton: \"endpoints-version-invoke\",\n invokeJson: \"endpoints-version-invoke-json\",\n invokeError: \"endpoints-version-invoke-error\",\n },\n};\n\n/**\n * Version viewer for Function/Workflow/Endpoint (T3.1.1, extended by T5.3.1): one\n * kind-parametrized component, mirroring `ImportSpecModal.tsx:12-46`'s established shape (a\n * `kind` prop plus per-kind `TESTIDS`, one component mounted from more than one place rather than\n * three near-copies). This project mounts it from `SettingsTool.tsx` only — the component\n * boundary exists so a second mount point later costs one line.\n *\n * Renders the version's own read-only definition through the same two primitives\n * `SettingsTool.tsx`'s existing Export modal already uses — the studio-local `Modal` and\n * `@w6w/ui`'s `CodeBlock` — plus, since T5.3.1, two live actions:\n *\n * - **\"Revert to this version\"** — confirmed via the studio-local `ConfirmModal` (P2-D4:\n * `./ConfirmModal.tsx`, never `@w6w/ui`'s), rendered as a SIBLING of `<Modal>` in\n * the returned fragment, never nested inside it. Overwrites the LIVE resource's `definition`\n * with this version's content, preserving its `key`/address (HITL-4's pinned default).\n * - **\"Invoke this version\"** — one click, NO confirm (ruling #12: an invoke is a call, not a\n * write to the resource, and the LIVE invoke action it mirrors carries no confirm either). Runs\n * this version's own archived definition, never the live one, and renders the response body\n * inline via `CodeBlock`, or a failure inline via the `ApiError` idiom (never a thrown error, a\n * blank modal, or a browser dialog).\n *\n * Both actions read `kind`/`id`/`versionNumber` from props, and both mutations are fresh\n * `useMutation` instances scoped to this component instance — since `SettingsTool.tsx`'s\n * `openVersion` gate fully unmounts/remounts this component per version rather than swapping\n * props on a surviving instance, any prior invoke result or error is gone the moment a different\n * version is opened.\n *\n * Amendments #5/#6 (project.md, Phase 2) supersede the earlier pin that made both of the above\n * out of scope (HITL-2's \"invocation always runs the live definition\"; Amendment #5's \"restore is\n * out of scope, not even a disabled button\").\n */\nexport function VersionHistoryModal(props: {\n kind: VersionsKind;\n id: string;\n versionNumber: number;\n onClose: () => void;\n /** Editor hosts serialize draft saves before restoring, then refresh their buffer. */\n onRestore?: (versionNumber: number) => Promise<void>;\n}) {\n const { kind, id, versionNumber } = props;\n const testids = TESTIDS[kind];\n // Always enabled: this component only ever mounts once a specific version has been picked\n // (the caller renders it conditionally), mirroring the Export modal's own \"mounted while open\"\n // gate rather than re-deriving a second `enabled` flag here.\n const versionQuery = useVersionQuery(kind, id, versionNumber, true);\n const revertMut = useRevertMutation(kind);\n const invokeMut = useInvokeVersionMutation(kind);\n const [confirmingRevert, setConfirmingRevert] = useState(false);\n const [restoreError, setRestoreError] = useState<string | null>(null);\n\n return (\n <>\n <Modal title={`Version ${versionNumber}`} onClose={props.onClose} wide>\n <div className=\"modal-body\">\n {versionQuery.isLoading ? (\n <p className=\"muted small\">Loading…</p>\n ) : versionQuery.isError ? (\n <div className=\"error\" data-testid={testids.error}>\n {versionQuery.error instanceof Error\n ? versionQuery.error.message\n : String(versionQuery.error)}\n </div>\n ) : versionQuery.data ? (\n <div data-testid={testids.json}>\n <CodeBlock\n code={JSON.stringify(versionQuery.data.definition, null, 2)}\n language=\"json\"\n maxHeight=\"420px\"\n copyable\n />\n </div>\n ) : null}\n\n {(restoreError || revertMut.isError) && (\n <div className=\"error\">{restoreError ?? String(revertMut.error)}</div>\n )}\n {invokeMut.data !== undefined && (\n <div data-testid={testids.invokeJson}>\n <CodeBlock\n code={JSON.stringify(invokeMut.data, null, 2)}\n language=\"json\"\n maxHeight=\"240px\"\n copyable\n />\n </div>\n )}\n {invokeMut.isError && (\n <div className=\"error\" data-testid={testids.invokeError}>\n {invokeMut.error instanceof ApiError\n ? invokeMut.error.message\n : String(invokeMut.error)}\n </div>\n )}\n </div>\n\n <div className=\"modal-actions\">\n <button\n type=\"button\"\n className=\"btn ghost\"\n data-testid={testids.invokeButton}\n disabled={invokeMut.isPending}\n onClick={() => invokeMut.mutate({ id, versionNumber })}\n >\n {invokeMut.isPending ? \"Invoking…\" : \"Invoke this version\"}\n </button>\n <button\n type=\"button\"\n className=\"btn danger\"\n data-testid={testids.revertButton}\n disabled={revertMut.isPending}\n onClick={() => setConfirmingRevert(true)}\n >\n {revertMut.isPending ? \"Reverting…\" : \"Revert to this version\"}\n </button>\n <button type=\"button\" className=\"btn ghost\" onClick={props.onClose}>\n Close\n </button>\n </div>\n </Modal>\n {confirmingRevert && (\n <ConfirmModal\n title=\"Revert to this version\"\n message={`Revert to version ${versionNumber}? This restores its content onto the resource's current draft; the resource's key and address stay unchanged.`}\n confirmLabel=\"Revert\"\n destructive\n onConfirm={() => {\n setConfirmingRevert(false);\n if (props.onRestore) {\n setRestoreError(null);\n void props\n .onRestore(versionNumber)\n .then(props.onClose, (e) => setRestoreError(String(e)));\n } else revertMut.mutate({ id, versionNumber });\n }}\n onClose={() => setConfirmingRevert(false)}\n />\n )}\n </>\n );\n}\n","/**\n * The rail Settings panel's bottom \"danger zone\" — Archive and optional direct\n * Delete, behind a visibly red confirmation panel — extracted\n * out of `src/ui/rail/SettingsTool.tsx` so Function, Endpoint and Workflow\n * render the EXACT same markup instead of three near-identical branches.\n * T1.3.1 had already moved all three kinds' Archive/Delete into one file, but\n * left them as three separate JSX arms that had drifted out of sync — only\n * Workflow's delete copy said the deletion was permanent (A5). This\n * extraction is what stops a fourth kind (or a future edit to one arm) from\n * silently reintroducing that gap: per-kind variance arrives entirely as\n * props. Callers opting into direct deletion handle the archive prerequisite.\n *\n * Presentational only, mirroring `@w6w/ui`'s own `DeleteButton` (HITL-1,\n * binding there): takes plain `onClick` callbacks, never an `onConfirm` and\n * never renders a confirm dialog itself — the caller (`SettingsTool.tsx`)\n * owns the `ConfirmModal`s and the archive/delete mutations, exactly as it\n * did before this extraction.\n *\n * A4: `DeleteButton`'s own `label` prop renders as `title`/`aria-label`\n * ONLY, never visible text (`packages/ui/src/components/IconButton.tsx`) —\n * so the visible word \"Delete\" here is this component's OWN sibling\n * `<span>`, not something passed through to `DeleteButton`.\n */\nimport { DeleteButton } from \"@w6w/ui\";\n\nexport interface DangerZoneProps {\n /** Archived resources offer Delete; other resources also offer Archive. */\n archived: boolean;\n /** Offer Delete before archiving when the caller handles both lifecycle operations. */\n allowDirectDelete?: boolean;\n pending?: boolean;\n /** Accessible name for the Delete icon button — `title`/`aria-label` only\n * (`IconButton.tsx`), e.g. \"Delete this function\". */\n deleteLabel: string;\n /** `data-testid` for the Delete control. Kind-specific — page guards key\n * on these directly (e.g. `delete-function`, `wf-settings-delete`). */\n deleteTestId: string;\n /** `data-testid` for the Archive control. Kind-specific. */\n archiveTestId: string;\n onRequestDelete: () => void;\n onRequestArchive: () => void;\n deleteError: string | null;\n archiveError: string | null;\n}\n\nexport function DangerZone(props: DangerZoneProps) {\n const {\n archived,\n deleteLabel,\n deleteTestId,\n archiveTestId,\n onRequestDelete,\n onRequestArchive,\n deleteError,\n archiveError,\n } = props;\n return (\n <div className=\"rail-danger-zone rail-danger-zone--panel\" data-testid=\"rail-danger-zone-panel\">\n <div className=\"rail-danger-zone-actions\">\n {!archived && (\n <button\n type=\"button\"\n className=\"btn danger\"\n data-testid={archiveTestId}\n onClick={onRequestArchive}\n disabled={props.pending}\n >\n Archive\n </button>\n )}\n {props.allowDirectDelete ? (\n <button\n type=\"button\"\n className=\"btn danger\"\n aria-label={deleteLabel}\n data-testid={deleteTestId}\n onClick={onRequestDelete}\n disabled={props.pending}\n >\n Delete\n </button>\n ) : archived ? (\n <span className=\"rail-danger-zone-delete\">\n <DeleteButton\n label={deleteLabel}\n data-testid={deleteTestId}\n onClick={onRequestDelete}\n disabled={props.pending}\n />\n <span>Delete</span>\n </span>\n ) : null}\n </div>\n {deleteError && (\n <div className=\"error\" data-testid=\"rail-delete-error\">\n {deleteError}\n </div>\n )}\n {archiveError && (\n <div className=\"error\" data-testid=\"rail-archive-error\">\n {archiveError}\n </div>\n )}\n </div>\n );\n}\n","/**\n * The presentational sections of the rail Settings panel, rendered by EVERY arm — the workflow\n * and function/endpoint arms in `./SettingsTool.tsx` — so the markup, test ids and copy exist\n * exactly once.\n *\n * Every section takes data and callbacks as props. There is no query or mutation hook in this\n * file: the arms own their data access (through `../repos/*`). `useState`-free too — open/close state lives in the arm, so a\n * section is a pure function of its props.\n *\n * Moved verbatim from the pre-split `SettingsPanel`: the `rail-meta` definition-list grid, the\n * version-history link + Publish/Enable block and its \"All versions\" list modal (kept as two\n * separate open states in the arm — see `SettingsTool.tsx`), the Export/Edit JSON/Import chooser\n * shell, and the Delete/Archive danger zone with its per-kind confirm copy.\n */\nimport { ConfirmModal, EditButton, Icon, IconButton } from \"@w6w/ui\";\nimport type { ReactNode } from \"react\";\nimport { DangerZone } from \"../chrome/DangerZone.tsx\";\nimport { Modal } from \"../chrome/Modal.tsx\";\nimport type { RailSettingsKind } from \"../lib/rail-settings.ts\";\nimport type { VersionSummary, VersionsEnvelope } from \"../repos/versions.ts\";\n\n/** The three kinds the Settings panel renders for. */\nexport type SettingsKind = Extract<RailSettingsKind, \"function\" | \"endpoint\" | \"workflow\">;\n\n/** Heading row: the title and the \"Edit settings\" trigger for the unified settings modal. */\nexport function SettingsHeading(props: { onEdit: () => void }) {\n return (\n <div className=\"right-rail-panel-head rail-settings-head\">\n <h3>Settings</h3>\n <EditButton label=\"Edit settings\" data-testid=\"rail-settings-edit\" onClick={props.onEdit} />\n </div>\n );\n}\n\n/**\n * id + key + updated (+ tags, workflow only) — and nothing else. No createdAt, ever. A two-column\n * label/value GRID (`dl`/`dt`/`dd`); `.rail-meta-list` is the rail-scoped grid and there is\n * deliberately no global `dl`/`dt`/`dd` rule.\n */\nexport function MetadataSection(props: {\n id: string;\n displayName: string;\n /** `metadataFieldsForKind(kind)`. */\n fields: ReadonlyArray<\"id\" | \"key\" | \"updatedAt\">;\n /** The already-cached list row (carries key/updatedAt); `undefined` until the list loads. */\n row: { key?: string | null; updatedAt: string } | undefined;\n /** Workflow only: the tag chips. `undefined` hides the row (function/endpoint). */\n tags?: readonly string[];\n}) {\n const { id, displayName, fields, row, tags } = props;\n return (\n <div className=\"rail-meta\">\n <div\n style={{\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"flex-start\",\n gap: \"8px\",\n }}\n >\n <dl className=\"rail-meta-list\">\n {displayName && (\n <>\n <dt>Name</dt>\n <dd data-testid=\"rail-meta-name\">\n <code>{displayName}</code>\n </dd>\n </>\n )}\n <dt>ID</dt>\n <dd data-testid=\"rail-meta-id\">\n <code>{id}</code>\n </dd>\n {fields.includes(\"key\") && row && (\n <>\n <dt>Key</dt>\n <dd data-testid=\"rail-meta-key\">\n <code>{row.key || \"unset\"}</code>\n </dd>\n </>\n )}\n {fields.includes(\"updatedAt\") && row && (\n <>\n <dt>Updated</dt>\n <dd data-testid=\"rail-meta-updated\" data-value={row.updatedAt}>\n {new Date(row.updatedAt).toLocaleString()}\n </dd>\n </>\n )}\n {tags !== undefined && row && (\n <>\n <dt>Tags</dt>\n <dd data-testid=\"rail-meta-tags\">\n {tags.length > 0\n ? tags.map((t) => (\n <span key={t} className=\"tag\">\n {t}\n </span>\n ))\n : \"No tags\"}\n </dd>\n </>\n )}\n </dl>\n </div>\n </div>\n );\n}\n\n/**\n * A5: one icon opens the combined Export/Edit JSON/Import chooser. Nothing here grows with the\n * size of the resource's definition — the definition renders in neither vessel here, only inside\n * a modal.\n */\nexport function SpecActionsTrigger(props: { onOpen: () => void }) {\n return (\n <div className=\"rail-spec-actions\">\n <IconButton\n icon=\"file-text\"\n label=\"Export, edit, or import\"\n data-testid=\"rail-spec-actions-open\"\n onClick={props.onOpen}\n />\n </div>\n );\n}\n\n/**\n * The chooser shell: Import always (it creates a NEW resource and navigates to it, never an\n * in-place replacement), plus a slot an arm fills with extra definition actions (the\n * function/endpoint arm adds Export + Edit JSON). Picking an item closes THIS modal and opens that\n * item's own — nothing is ever nested inside this one's body.\n */\nexport function SpecChooserModal(props: {\n kind: SettingsKind;\n /** Extra definition actions, rendered above the Import row. */\n children?: ReactNode;\n onImport: () => void;\n onClose: () => void;\n}) {\n const { kind, children, onImport, onClose } = props;\n return (\n <Modal title=\"Definition\" onClose={onClose}>\n <div className=\"modal-body\">\n {children}\n <p className=\"muted small\">\n Import a spec document to create a NEW {kind} and navigate to it — this does not replace\n the {kind} you have open.\n </p>\n <div className=\"rail-spec-menu-row\">\n <button\n type=\"button\"\n className=\"btn ghost\"\n data-testid=\"rail-spec-import\"\n onClick={onImport}\n >\n Import\n </button>\n </div>\n </div>\n <div className=\"modal-actions\">\n <button type=\"button\" className=\"btn ghost\" onClick={onClose}>\n Close\n </button>\n </div>\n </Modal>\n );\n}\n\n/**\n * Version history (A4): a link-styled icon, ALWAYS enabled (\"no earlier versions\" is an empty\n * state INSIDE the list modal, never a disabled control). Once opened (`open`), the un-carded\n * \"Published: vN\" line and Publish / Enable-Disable stay in the main panel.\n */\nexport function VersionSection(props: {\n definitionStatus?: \"published\" | \"draft\" | \"unpublished\";\n publishDisabled?: boolean;\n open: boolean;\n versions: VersionsEnvelope | undefined;\n publishing: boolean;\n togglingEnabled: boolean;\n publishError: string | null;\n enableError: string | null;\n onShow: () => void;\n onPublish: () => void;\n onToggleEnabled: () => void;\n}) {\n const { open, versions } = props;\n return (\n <div className=\"rail-version-section\">\n {props.definitionStatus && (\n <div aria-live=\"polite\" data-testid=\"rail-definition-status\">\n <span className={`badge wf-definition-status ${props.definitionStatus}`}>\n {props.definitionStatus === \"published\" ? \"Live\" : \"Draft\"}\n </span>\n <p className=\"muted small\">\n {props.definitionStatus === \"draft\"\n ? \"This definition has unpublished changes. Republish to update the live version.\"\n : props.definitionStatus === \"unpublished\"\n ? \"This definition has never been published.\"\n : \"This definition matches the published version.\"}\n </p>\n </div>\n )}\n <button\n type=\"button\"\n className=\"rail-link-icon\"\n data-testid=\"rail-history-show\"\n aria-label=\"Version history\"\n title=\"Version history\"\n onClick={props.onShow}\n >\n <Icon name=\"clock\" size={14} />\n <span>Version history</span>\n </button>\n {(open || props.definitionStatus) && (\n <p className=\"muted small\" data-testid=\"rail-version-published\">\n {versions?.currentPublishedVersion != null\n ? `Published: v${versions.currentPublishedVersion}`\n : \"Never published\"}\n </p>\n )}\n {open && (\n <>\n <div className=\"rail-version-actions\">\n <button\n type=\"button\"\n className=\"btn ghost\"\n data-testid=\"rail-publish\"\n disabled={\n props.publishing || props.publishDisabled || props.definitionStatus === \"published\"\n }\n onClick={props.onPublish}\n >\n {props.publishing\n ? versions?.currentPublishedVersion != null\n ? \"Republishing…\"\n : \"Publishing…\"\n : props.definitionStatus === \"published\" ||\n (props.publishDisabled !== undefined &&\n props.definitionStatus === undefined &&\n versions?.currentPublishedVersion != null)\n ? \"Published\"\n : versions?.currentPublishedVersion != null\n ? \"Republish\"\n : \"Publish\"}\n </button>{\" \"}\n <button\n type=\"button\"\n className=\"btn ghost\"\n data-testid=\"rail-enable-toggle\"\n disabled={props.togglingEnabled || versions === undefined}\n onClick={props.onToggleEnabled}\n >\n {props.togglingEnabled ? \"Saving…\" : versions?.enabled ? \"Disable\" : \"Enable\"}\n </button>\n </div>\n {props.publishError && (\n <div className=\"error\" data-testid=\"rail-publish-error\">\n {props.publishError}\n </div>\n )}\n {props.enableError && (\n <div className=\"error\" data-testid=\"rail-enable-error\">\n {props.enableError}\n </div>\n )}\n </>\n )}\n </div>\n );\n}\n\n/**\n * The \"All versions\" list modal — deliberately NOT titled \"Version history\" (which would share\n * the `Version …` aria-label prefix the per-version detail viewer's own dialogs use).\n */\nexport function VersionListModal(props: {\n loading: boolean;\n versions: readonly VersionSummary[] | undefined;\n onSelect: (versionNumber: number) => void;\n onClose: () => void;\n}) {\n const { loading, versions } = props;\n return (\n <Modal title=\"All versions\" onClose={props.onClose} wide>\n <div className=\"modal-body\">\n {loading && <p className=\"muted small\">Loading…</p>}\n {versions?.length === 0 && <p className=\"muted small\">No versions yet.</p>}\n {versions && versions.length > 0 && (\n <ul className=\"list\">\n {versions.map((v) => (\n <li key={v.versionNumber} className=\"selectable\">\n <button\n type=\"button\"\n className=\"row-select\"\n data-testid=\"rail-version-row\"\n onClick={() => props.onSelect(v.versionNumber)}\n >\n <div className=\"list-main\">\n <code>v{v.versionNumber}</code>{\" \"}\n {v.isCurrentPublished && (\n <span className=\"badge\" data-testid=\"rail-version-current\">\n Published\n </span>\n )}\n <div className=\"muted small\">{new Date(v.createdAt).toLocaleString()}</div>\n </div>\n </button>\n </li>\n ))}\n </ul>\n )}\n </div>\n <div className=\"modal-actions\">\n <button type=\"button\" className=\"btn ghost\" onClick={props.onClose}>\n Done\n </button>\n </div>\n </Modal>\n );\n}\n\nconst DANGER_COPY: Record<\n SettingsKind,\n {\n deleteTitle: string;\n deleteMessage: string;\n archiveTitle: string;\n archiveMessage: string;\n deleteLabel: string;\n deleteTestId: string;\n archiveTestId: string;\n }\n> = {\n function: {\n deleteTitle: \"Delete function\",\n deleteMessage:\n \"Delete this function permanently? Any endpoint, workflow, or call pointing to it will start failing with a not-found error the next time it runs, and this cannot be undone.\",\n archiveTitle: \"Archive function\",\n archiveMessage:\n \"Archive this function? It stops being invocable and can no longer be edited. Archiving is one-way — there is no unarchive — and only an archived function can be deleted.\",\n deleteLabel: \"Delete this function\",\n deleteTestId: \"delete-function\",\n archiveTestId: \"archive-function\",\n },\n endpoint: {\n deleteTitle: \"Delete endpoint\",\n deleteMessage:\n \"Delete this endpoint permanently? Any alias, workflow, or call pointing to it will start failing with a not-found error the next time it runs, and this cannot be undone.\",\n archiveTitle: \"Archive endpoint\",\n archiveMessage:\n \"Archive this endpoint? It stops being invocable and can no longer be edited. Archiving is one-way — there is no unarchive — and only an archived endpoint can be deleted.\",\n deleteLabel: \"Delete this endpoint\",\n deleteTestId: \"delete-endpoint\",\n archiveTestId: \"archive-endpoint\",\n },\n workflow: {\n deleteTitle: \"Delete workflow\",\n deleteMessage: \"Permanently delete this workflow and its run history? This cannot be undone.\",\n archiveTitle: \"Archive workflow\",\n archiveMessage:\n \"Archive this workflow? It stops running and can no longer be published. Archiving is one-way — there is no unarchive. Its run history is kept until you delete it.\",\n deleteLabel: \"Delete this workflow\",\n deleteTestId: \"wf-settings-delete\",\n archiveTestId: \"wf-settings-archive\",\n },\n};\n\n/**\n * The bottom \"danger zone\": Archive and Delete for workflows; Archive then Delete for other kinds.\n * Per-kind variance (copy, test ids) is the table above; the caller owns the mutations and the\n * confirm/error state, and renders this only when `hasDelete(kind)`.\n */\nexport function SettingsDangerZone(props: {\n kind: SettingsKind;\n archived: boolean;\n pending?: boolean;\n deleteConfirming: boolean;\n archiveConfirming: boolean;\n deleteError: string | null;\n archiveError: string | null;\n onRequestDelete: () => void;\n onRequestArchive: () => void;\n onConfirmDelete: () => void;\n onConfirmArchive: () => void;\n onCloseDelete: () => void;\n onCloseArchive: () => void;\n}) {\n const copy = DANGER_COPY[props.kind];\n return (\n <>\n <DangerZone\n archived={props.archived}\n allowDirectDelete={props.kind === \"workflow\"}\n pending={props.pending}\n deleteLabel={copy.deleteLabel}\n deleteTestId={copy.deleteTestId}\n archiveTestId={copy.archiveTestId}\n onRequestDelete={props.onRequestDelete}\n onRequestArchive={props.onRequestArchive}\n deleteError={props.deleteError}\n archiveError={props.archiveError}\n />\n {props.deleteConfirming && (\n <ConfirmModal\n title={copy.deleteTitle}\n message={copy.deleteMessage}\n confirmLabel=\"Delete\"\n pending={props.pending}\n onConfirm={props.onConfirmDelete}\n onClose={props.onCloseDelete}\n />\n )}\n {props.archiveConfirming && (\n <ConfirmModal\n title={copy.archiveTitle}\n message={copy.archiveMessage}\n confirmLabel=\"Archive\"\n pending={props.pending}\n onConfirm={props.onConfirmArchive}\n onClose={props.onCloseArchive}\n />\n )}\n </>\n );\n}\n","/**\n * The Settings rail tool — what a resource's right-rail Settings panel does, owned by the package\n * so `<WorkflowEditor>`, a host's `<CallableRail>` and Studio's own rail all render ONE tool:\n * `settingsTool` is a stateful shell (it owns the three open flags) that dispatches by kind to\n * `WorkflowSettingsPanel` or `CallableSettingsPanel` (function / endpoint). Both render the same\n * presentational sections (`./settings-sections.tsx`).\n *\n * Workflow arm, unchanged:\n * - metadata (name / id / key / tags) read off the cached workflow list row;\n * - the unified settings modal saves the WHOLE stored definition (`useWorkflowQuery`'s\n * `workflow`, `displayName` / `key` / `tags` replaced) with `ifUnmodifiedSince` from that\n * query's `updatedAt`, and `project` passed VERBATIM — `useSaveWorkflowMutation` refuses\n * without one, because an unscoped write would silently relocate the workflow into the\n * account's default project (C/D-C2). A 409/400 renders inline, never a thrown error;\n * - the Import chooser → `ImportSpecModal` (creates a NEW workflow and opens it);\n * - version history / Publish / Enable are gated on the section's OWN open state, so opening\n * the panel issues zero `/versions` requests;\n * - Archive or Delete directly. Both land on the list via `onNavigate({ type: \"list\" })`.\n *\n * Function / endpoint arm: the same sections over `../repos/functions.ts` / `endpoints.ts`, plus\n * Export (`useSpecQuery`, gated on the export modal being open) and Edit JSON. Every write built\n * from a cached definition takes the definition from `callableRecord(kind, query.data)` — the ONE\n * strip of `valid` / `updatedAt` — and saves through the guarded hook with the stale-write token\n * OF THE RECORD THE WRITTEN TEXT CAME FROM: the name/key modal uses the current record's\n * `updatedAt`; Edit JSON uses the token captured when its text was seeded (`openEdit`), never one\n * read at save time over older text (that would silently overwrite a write that landed meanwhile).\n * A refusal (409 `function_stale` / `endpoint_stale`, 400…) renders inline and is never retried.\n *\n * Host seams: `project` and `onNavigate` arrive as props on the arms, and the `settingsTool` Panel\n * reads them from `useRailEnv()` (`./rail-env.tsx`). Archive / delete land on the list through\n * `onNavigate({ type: \"list\" })`; an import opens `{ type: \"imported\", kind, id }`. No router, no\n * `client.console`, no module-scope browser globals.\n *\n * ⚠️ The strip id is `\"settings\"`; `activeTool` is persisted.\n */\nimport { ApiError } from \"@w6w/sdk\";\nimport { CodeBlock, Icon, JsonEditor } from \"@w6w/ui\";\nimport { useRef, useState } from \"react\";\nimport { CallableSettingsModal } from \"../chrome/CallableSettingsModal.tsx\";\nimport { ImportSpecModal } from \"../chrome/ImportSpecModal.tsx\";\nimport { Modal } from \"../chrome/Modal.tsx\";\nimport type { RailTool } from \"../chrome/RightRail.tsx\";\nimport { VersionHistoryModal } from \"../chrome/VersionHistoryModal.tsx\";\nimport type { WorkspaceCallable } from \"../chrome/workspace.tsx\";\nimport { callableRecord } from \"../lib/callable-record.ts\";\nimport {\n evaluateEdit,\n hasDefinitionActions,\n hasDelete,\n hasVersionHistory,\n metadataFieldsForKind,\n specCollectionForKind,\n} from \"../lib/rail-settings.ts\";\nimport {\n endpointsKey,\n useArchiveEndpointMutation,\n useDeleteEndpointMutation,\n useEndpointQuery,\n useEndpointsQuery,\n useGuardedSaveEndpointMutation,\n} from \"../repos/endpoints.ts\";\nimport {\n functionsKey,\n useArchiveFunctionMutation,\n useDeleteFunctionMutation,\n useFunctionQuery,\n useFunctionsQuery,\n useGuardedSaveFunctionMutation,\n} from \"../repos/functions.ts\";\nimport { useSpecQuery } from \"../repos/spec-export.ts\";\nimport {\n type VersionsKind,\n usePublishMutation,\n useSetEnabledMutation,\n useVersionsQuery,\n} from \"../repos/versions.ts\";\nimport {\n useArchiveWorkflowMutation,\n useDeleteWorkflowMutation,\n useSaveWorkflowMutation,\n useWorkflowQuery,\n useWorkflowsQuery,\n workflowsKey,\n} from \"../repos/workflows.ts\";\nimport { type RailNavigation, useRailEnv } from \"./rail-env.tsx\";\nimport {\n MetadataSection,\n SettingsDangerZone,\n SettingsHeading,\n SpecActionsTrigger,\n SpecChooserModal,\n VersionListModal,\n VersionSection,\n} from \"./settings-sections.tsx\";\n\n/** The Import modal's three list keys — the repos' own exports, never literals. */\nconst IMPORT_LIST_KEYS = { functionsKey, endpointsKey, workflowsKey };\n\n/**\n * The three open flags a Settings panel shows: the Name/Key/Tags modal, the history section, and\n * the version list modal. They are OWNED BY THE CALLER (a stateful shell above every kind's arm),\n * not by the arm: a rail that stays mounted across a kind change (function -> workflow ->\n * endpoint) swaps arm component types, and state held in the arm would be remounted away,\n * closing an open modal. Lifting them keeps the modal open exactly as the pre-split single\n * component did.\n */\nexport type SettingsOpenState = {\n editingSettings: boolean;\n setEditingSettings: (v: boolean) => void;\n historyOpen: boolean;\n setHistoryOpen: (v: boolean) => void;\n versionListOpen: boolean;\n setVersionListOpen: (v: boolean) => void;\n};\n\nexport function WorkflowSettingsPanel({\n ctx,\n project,\n onNavigate,\n open,\n}: {\n ctx: WorkspaceCallable;\n project: string | null;\n onNavigate: (to: RailNavigation) => void;\n open: SettingsOpenState;\n}) {\n const {\n editingSettings,\n setEditingSettings,\n historyOpen,\n setHistoryOpen,\n versionListOpen,\n setVersionListOpen,\n } = open;\n const workflowsQuery = useWorkflowsQuery(project ?? undefined);\n const isWorkflow = ctx?.kind === \"workflow\";\n const id = ctx?.id ?? \"\";\n\n // The Key / Tags / Name save needs the WHOLE stored definition (never a `{id,key}` stub) plus\n // the `updatedAt` precondition — both come from this query.\n const wfDefQuery = useWorkflowQuery(id, isWorkflow);\n // MUST carry the current project, verbatim: the hook refuses a missing one (no default).\n const saveWfMut = useSaveWorkflowMutation(project ?? undefined);\n const archiveWfMut = useArchiveWorkflowMutation();\n const deleteWfMut = useDeleteWorkflowMutation();\n const deleting = useRef(false);\n\n const [specMenuOpen, setSpecMenuOpen] = useState(false);\n const [importing, setImporting] = useState(false);\n const [exporting, setExporting] = useState(false);\n const [deleteConfirming, setDeleteConfirming] = useState(false);\n const [archiveConfirming, setArchiveConfirming] = useState(false);\n const [deleteError, setDeleteError] = useState<string | null>(null);\n const [archiveError, setArchiveError] = useState<string | null>(null);\n // Gated on the export modal's own open state: opening the panel issues zero `/spec` requests.\n const specQuery = useSpecQuery(specCollectionForKind(\"workflow\"), id, exporting);\n\n // `versionListOpen` is DELIBERATELY separate from `historyOpen` (both arrive via `open`): a\n // native `<dialog>` opened via `showModal()` makes the rest of the page inert, so sharing one\n // boolean would hide Publish/Enable-Disable the moment the list modal closes. The entry icon\n // sets both true; only the list modal's own close clears `versionListOpen`.\n // Gated on the section's OWN open state: opening this panel issues zero `/versions` requests.\n const versionsQuery = useVersionsQuery(\"workflow\", id, historyOpen && isWorkflow);\n const publishMut = usePublishMutation(\"workflow\");\n const setEnabledMut = useSetEnabledMutation(\"workflow\");\n const [publishError, setPublishError] = useState<string | null>(null);\n const [enableError, setEnableError] = useState<string | null>(null);\n // Keyed by resource id: falls back to closed the instant `ctx.id` no longer matches, so a\n // transition never carries a stale version from a DIFFERENT resource.\n const [openVersion, setOpenVersion] = useState<{ id: string; versionNumber: number } | null>(\n null,\n );\n\n if (!ctx || ctx.kind !== \"workflow\") {\n return <p className=\"muted small\">Open a workflow to see its settings.</p>;\n }\n\n const listRow = workflowsQuery.data?.find((w) => w.id === ctx.id);\n const displayName =\n listRow && typeof (listRow as { displayName?: unknown }).displayName === \"string\"\n ? (listRow as { displayName: string }).displayName\n : \"\";\n const tags = (listRow as { tags?: string[] } | undefined)?.tags ?? [];\n const archived = (listRow as { status?: string } | undefined)?.status === \"archived\";\n\n async function onDelete() {\n if (deleting.current) return;\n deleting.current = true;\n setDeleteError(null);\n try {\n // Preserve the API's lifecycle checks without requiring two user actions.\n if (!archived) await archiveWfMut.mutateAsync(id);\n await deleteWfMut.mutateAsync(id);\n setDeleteConfirming(false);\n onNavigate({ type: \"list\" });\n } catch (e) {\n setDeleteConfirming(false);\n setDeleteError(e instanceof ApiError ? e.message : String(e));\n } finally {\n deleting.current = false;\n }\n }\n\n function onArchive() {\n setArchiveError(null);\n archiveWfMut.mutate(id, {\n onSuccess: () => {\n setArchiveConfirming(false);\n onNavigate({ type: \"list\" });\n },\n onError: (e: unknown) => {\n setArchiveConfirming(false);\n setArchiveError(e instanceof ApiError ? e.message : String(e));\n },\n });\n }\n\n return (\n <div className=\"rail-settings-panel\">\n <SettingsHeading onEdit={() => setEditingSettings(true)} />\n {ctx.authoringSettings && ctx.onAuthoringSettingChange && (\n <section className=\"w6w-stack\" data-testid=\"rail-workflow-authoring\">\n <label>\n <input\n type=\"checkbox\"\n checked={ctx.authoringSettings.autoSave}\n onChange={(e) => ctx.onAuthoringSettingChange?.(\"autoSave\", e.target.checked)}\n />\n Auto-save edits\n </label>\n <label>\n <input\n type=\"checkbox\"\n checked={ctx.authoringSettings.savePosition}\n onChange={(e) => ctx.onAuthoringSettingChange?.(\"savePosition\", e.target.checked)}\n />\n Save node positions and canvas view\n </label>\n </section>\n )}\n <MetadataSection\n id={ctx.id}\n displayName={displayName}\n fields={metadataFieldsForKind(\"workflow\")}\n row={listRow}\n tags={tags}\n />\n\n <SpecActionsTrigger onOpen={() => setSpecMenuOpen(true)} />\n\n <VersionSection\n definitionStatus={ctx.definitionStatus}\n publishDisabled={ctx.publishDisabled}\n open={historyOpen}\n versions={versionsQuery.data}\n publishing={publishMut.isPending}\n togglingEnabled={setEnabledMut.isPending}\n publishError={publishError}\n enableError={enableError}\n onShow={() => {\n setHistoryOpen(true);\n setVersionListOpen(true);\n }}\n onPublish={() => {\n if (ctx.onPublish) {\n void ctx.onPublish();\n return;\n }\n setPublishError(null);\n publishMut.mutate(id, {\n onError: (e) => setPublishError(e instanceof ApiError ? e.message : String(e)),\n });\n }}\n onToggleEnabled={() => {\n setEnableError(null);\n setEnabledMut.mutate(\n { id, enabled: !versionsQuery.data?.enabled },\n { onError: (e) => setEnableError(e instanceof ApiError ? e.message : String(e)) },\n );\n }}\n />\n\n {versionListOpen && (\n <VersionListModal\n loading={versionsQuery.isLoading}\n versions={versionsQuery.data?.versions}\n onSelect={(versionNumber) => setOpenVersion({ id, versionNumber })}\n onClose={() => setVersionListOpen(false)}\n />\n )}\n\n {openVersion && openVersion.id === id && (\n <VersionHistoryModal\n kind=\"workflow\"\n id={id}\n onRestore={ctx.onRestoreVersion}\n versionNumber={openVersion.versionNumber}\n onClose={() => setOpenVersion(null)}\n />\n )}\n\n {specMenuOpen && (\n <SpecChooserModal\n kind=\"workflow\"\n onClose={() => setSpecMenuOpen(false)}\n onImport={() => {\n setSpecMenuOpen(false);\n setImporting(true);\n }}\n >\n <p className=\"muted small\">\n Export a portable definition — the same shape Import accepts.\n </p>\n <div className=\"rail-spec-menu-row\">\n <button\n type=\"button\"\n className=\"btn ghost\"\n data-testid=\"rail-spec-export\"\n onClick={() => {\n setSpecMenuOpen(false);\n setExporting(true);\n }}\n >\n Export\n </button>\n </div>\n </SpecChooserModal>\n )}\n\n {exporting && (\n <Modal title=\"Export spec document\" onClose={() => setExporting(false)} wide>\n <div className=\"modal-body\">\n {specQuery.isLoading ? (\n <p className=\"muted small\">Loading…</p>\n ) : specQuery.isError ? (\n <div className=\"error\" data-testid=\"rail-spec-error\">\n {specQuery.error instanceof Error\n ? specQuery.error.message\n : String(specQuery.error)}\n </div>\n ) : specQuery.data ? (\n <div data-testid=\"rail-spec-json\">\n <CodeBlock\n code={JSON.stringify(specQuery.data, null, 2)}\n language=\"json\"\n maxHeight=\"420px\"\n copyable\n />\n </div>\n ) : null}\n </div>\n <div className=\"modal-actions\">\n <button type=\"button\" className=\"btn ghost\" onClick={() => setExporting(false)}>\n Close\n </button>\n </div>\n </Modal>\n )}\n\n {/* Unified settings modal for name, key, and tags. */}\n {editingSettings && listRow && (\n <CallableSettingsModal\n // `key={id}` remounts (not merely re-renders) when an in-app navigation swaps the rail\n // to a different resource while this modal is open — the modal's `useState`\n // initializers never re-run on a prop change, so without it a save would mix the first\n // resource's stale fields with the new `id`.\n key={id}\n kind=\"workflow\"\n id={id}\n initial={{\n displayName,\n key: (listRow as { key?: string | null }).key ?? null,\n tags,\n }}\n onSave={async (data) => {\n if (!wfDefQuery.data) throw new Error(\"Unable to save settings\");\n const stored = wfDefQuery.data;\n return new Promise((resolve, reject) => {\n const updated: Record<string, unknown> = {\n ...stored.workflow,\n displayName: data.displayName,\n };\n if (data.key !== undefined) {\n updated.key = data.key;\n }\n if (data.tags !== undefined) {\n updated.tags = data.tags;\n }\n saveWfMut.mutate(\n { definition: updated, ifUnmodifiedSince: stored.updatedAt },\n { onSuccess: () => resolve(), onError: reject },\n );\n });\n }}\n onClose={() => setEditingSettings(false)}\n />\n )}\n\n <SettingsDangerZone\n kind=\"workflow\"\n archived={archived}\n pending={archiveWfMut.isPending || deleteWfMut.isPending}\n deleteConfirming={deleteConfirming}\n archiveConfirming={archiveConfirming}\n deleteError={deleteError}\n archiveError={archiveError}\n onRequestDelete={() => setDeleteConfirming(true)}\n onRequestArchive={() => setArchiveConfirming(true)}\n onConfirmDelete={onDelete}\n onConfirmArchive={onArchive}\n onCloseDelete={() => setDeleteConfirming(false)}\n onCloseArchive={() => setArchiveConfirming(false)}\n />\n\n {importing && (\n <ImportSpecModal\n kind=\"workflow\"\n project={project ?? undefined}\n listKeys={IMPORT_LIST_KEYS}\n onOpenImported={(kind, newId) => onNavigate({ type: \"imported\", kind, id: newId })}\n onClose={() => setImporting(false)}\n />\n )}\n </div>\n );\n}\n\n/**\n * Stateful shell: owns the three open flags ABOVE every arm and passes them down. The kind branch\n * picks a component TYPE (so each arm's data hooks stay per-kind), and an arm remounts on a kind\n * change — but the modal / version-list flags live here, so they survive the swap (rail guards\n * K6/V6).\n */\nfunction SettingsToolPanel({ ctx }: { ctx: WorkspaceCallable }) {\n const { project, onNavigate } = useRailEnv();\n const [editingSettings, setEditingSettings] = useState(false);\n const [historyOpen, setHistoryOpen] = useState(false);\n const [versionListOpen, setVersionListOpen] = useState(false);\n const open: SettingsOpenState = {\n editingSettings,\n setEditingSettings,\n historyOpen,\n setHistoryOpen,\n versionListOpen,\n setVersionListOpen,\n };\n return ctx?.kind === \"workflow\" ? (\n <WorkflowSettingsPanel ctx={ctx} project={project} onNavigate={onNavigate} open={open} />\n ) : (\n <CallableSettingsPanel ctx={ctx} project={project} onNavigate={onNavigate} open={open} />\n );\n}\n\nexport function CallableSettingsPanel({\n ctx,\n project,\n onNavigate,\n open,\n}: {\n ctx: WorkspaceCallable;\n project: string | null;\n onNavigate: (to: RailNavigation) => void;\n open: SettingsOpenState;\n}) {\n const {\n editingSettings,\n setEditingSettings,\n historyOpen,\n setHistoryOpen,\n versionListOpen,\n setVersionListOpen,\n } = open;\n const kind0 = ctx?.kind;\n const endpointsQuery = useEndpointsQuery(kind0 === \"endpoint\");\n const functionsQuery = useFunctionsQuery(kind0 === \"function\");\n\n const [editing, setEditing] = useState(false);\n const [editText, setEditText] = useState(\"\");\n const [editError, setEditError] = useState<string | null>(null);\n // The stale-write token of the record `editText` was seeded from (`openEdit`). Read at SAVE time\n // it would guard text seeded from an older copy with a newer token — a silent overwrite.\n const [editToken, setEditToken] = useState<string | null>(null);\n // A5: one chooser icon opens ONE combined Modal (Export + Edit JSON +\n // Import); picking an item there closes the chooser and opens THAT item's\n // own modal as a sibling — never nested inside the chooser's own body.\n const [specMenuOpen, setSpecMenuOpen] = useState(false);\n const [exporting, setExporting] = useState(false);\n const [importing, setImporting] = useState(false);\n const [deleteConfirming, setDeleteConfirming] = useState(false);\n const [archiveConfirming, setArchiveConfirming] = useState(false);\n const [deleteError, setDeleteError] = useState<string | null>(null);\n const [archiveError, setArchiveError] = useState<string | null>(null);\n\n // Gated on `ctx.kind` alone, never additionally on the edit modal being\n // open — ST6's post-save freshness proof needs the `[\"function\", id]` cache\n // entry to exist before the save happens.\n const fnDefQuery = useFunctionQuery(ctx?.id ?? \"\", ctx?.kind === \"function\");\n const epDefQuery = useEndpointQuery(ctx?.id ?? \"\", ctx?.kind === \"endpoint\");\n const saveFnMut = useGuardedSaveFunctionMutation();\n const saveEpMut = useGuardedSaveEndpointMutation();\n const deleteFnMut = useDeleteFunctionMutation();\n const deleteEpMut = useDeleteEndpointMutation();\n // A7: Function/Endpoint have the archive-before-delete step too.\n const archiveFnMut = useArchiveFunctionMutation();\n const archiveEpMut = useArchiveEndpointMutation();\n // Gated on the export modal's own open state, so opening this panel issues\n // zero `/spec` requests. `specCollectionForKind` returns `null` for\n // `workflow`/`connection`, which disables the query regardless of `exporting`.\n const specCollection = ctx ? specCollectionForKind(ctx.kind) : null;\n const specQuery = useSpecQuery(specCollection, ctx?.id ?? \"\", exporting);\n\n // ── The History section ─────────────────────────────────────────────────\n // `null` for a kind with no version history (`connection`).\n const versionsKind: VersionsKind | null =\n ctx && hasVersionHistory(ctx.kind) ? (ctx.kind as VersionsKind) : null;\n // Gated on the section's OWN open state (`historyOpen`): never fires on mount.\n const versionsQuery = useVersionsQuery(versionsKind, ctx?.id ?? \"\", historyOpen);\n // `usePublishMutation`/`useSetEnabledMutation` need a fixed, non-null kind\n // per hook instance; the fallback is never reached by an actual request —\n // the buttons that call `.mutate` only render inside the\n // `hasVersionHistory(ctx.kind)`-gated block.\n const publishMut = usePublishMutation(versionsKind ?? \"function\");\n const setEnabledMut = useSetEnabledMutation(versionsKind ?? \"function\");\n const [publishError, setPublishError] = useState<string | null>(null);\n const [enableError, setEnableError] = useState<string | null>(null);\n // Keyed by resource id: falls back to closed the instant `ctx.id` no longer\n // matches, so a kind/id transition (V6) never carries a stale version.\n const [openVersion, setOpenVersion] = useState<{ id: string; versionNumber: number } | null>(\n null,\n );\n\n // `isAvailable` already keeps this tool off the strip for a `ctx` this has\n // no settings for — but a persisted `activeTool` plus an in-app transition\n // to a non-publishing route can still render this Panel with `ctx === null`\n // (or a `connection`). The rail must never blank out or crash.\n if (!ctx || (ctx.kind !== \"function\" && ctx.kind !== \"endpoint\")) {\n return (\n <p className=\"muted small\">Open a workflow, function, or endpoint to see its settings.</p>\n );\n }\n\n const kind = ctx.kind;\n const id = ctx.id;\n const listRow =\n kind === \"function\"\n ? functionsQuery.data?.find((f) => f.id === id)\n : endpointsQuery.data?.find((e) => e.id === id);\n // The cached record split ONCE (`callableRecord`): the editable definition (no `valid` /\n // `updatedAt`) and the stale-write token it was read with.\n const record = callableRecord(kind, kind === \"function\" ? fnDefQuery.data : epDefQuery.data);\n const def = record?.definition ?? null;\n // Display name (the human-readable label shown in the list)\n const displayName = listRow\n ? typeof (listRow as { displayName?: unknown }).displayName === \"string\"\n ? (listRow as { displayName: string }).displayName\n : \"\"\n : \"\";\n\n const defJson = def ? JSON.stringify(def, null, 2) : \"\";\n\n function openEdit() {\n setEditError(null);\n setEditText(defJson);\n setEditToken(record?.updatedAt ?? null);\n setEditing(true);\n }\n\n const editEval = def\n ? evaluateEdit(editText, { id: String(def.id), key: String(def.key) })\n : { parsed: null, blockedReason: \"No definition loaded yet.\" };\n const savingDef = kind === \"function\" ? saveFnMut.isPending : saveEpMut.isPending;\n\n function onSaveEdit() {\n if (!editEval.parsed || editEval.blockedReason) return;\n setEditError(null);\n const onSettled = {\n onSuccess: () => setEditing(false),\n onError: (e: unknown) => setEditError(e instanceof ApiError ? e.message : String(e)),\n };\n const vars = { definition: editEval.parsed, ifUnmodifiedSince: editToken };\n if (kind === \"function\") {\n saveFnMut.mutate(vars, onSettled);\n } else {\n saveEpMut.mutate(vars, onSettled);\n }\n }\n\n // ── Delete/Archive — the bottom \"danger zone\" ────────────────────────────\n // Function/Endpoint signal \"already archived\" via the `archivedAt` column.\n const archived = (listRow as { archivedAt?: string | null } | undefined)?.archivedAt != null;\n\n function onDelete() {\n setDeleteError(null);\n const onSettled = {\n onSuccess: () => {\n setDeleteConfirming(false);\n onNavigate({ type: \"list\" });\n },\n onError: (e: unknown) => {\n setDeleteConfirming(false);\n setDeleteError(e instanceof ApiError ? e.message : String(e));\n },\n };\n if (kind === \"function\") deleteFnMut.mutate(id, onSettled);\n else deleteEpMut.mutate(id, onSettled);\n }\n\n // A1/D-I0-1: archive reuses `onDelete`'s land-on-the-list idiom.\n function onArchive() {\n setArchiveError(null);\n const onSettled = {\n onSuccess: () => {\n setArchiveConfirming(false);\n onNavigate({ type: \"list\" });\n },\n onError: (e: unknown) => {\n setArchiveConfirming(false);\n setArchiveError(e instanceof ApiError ? e.message : String(e));\n },\n };\n if (kind === \"function\") archiveFnMut.mutate(id, onSettled);\n else archiveEpMut.mutate(id, onSettled);\n }\n\n return (\n <div className=\"rail-settings-panel\">\n <SettingsHeading onEdit={() => setEditingSettings(true)} />\n <MetadataSection\n id={id}\n displayName={displayName}\n fields={metadataFieldsForKind(kind)}\n row={listRow}\n />\n\n {hasDefinitionActions(kind) && <SpecActionsTrigger onOpen={() => setSpecMenuOpen(true)} />}\n\n {hasVersionHistory(kind) && (\n <VersionSection\n open={historyOpen}\n versions={versionsQuery.data}\n publishing={publishMut.isPending}\n togglingEnabled={setEnabledMut.isPending}\n publishError={publishError}\n enableError={enableError}\n onShow={() => {\n setHistoryOpen(true);\n setVersionListOpen(true);\n }}\n onPublish={() => {\n setPublishError(null);\n publishMut.mutate(id, {\n onError: (e) => setPublishError(e instanceof ApiError ? e.message : String(e)),\n });\n }}\n onToggleEnabled={() => {\n setEnableError(null);\n setEnabledMut.mutate(\n { id, enabled: !versionsQuery.data?.enabled },\n { onError: (e) => setEnableError(e instanceof ApiError ? e.message : String(e)) },\n );\n }}\n />\n )}\n\n {versionListOpen && (\n <VersionListModal\n loading={versionsQuery.isLoading}\n versions={versionsQuery.data?.versions}\n onSelect={(versionNumber) => setOpenVersion({ id, versionNumber })}\n onClose={() => setVersionListOpen(false)}\n />\n )}\n\n {openVersion && openVersion.id === id && (\n <VersionHistoryModal\n kind={kind}\n id={id}\n versionNumber={openVersion.versionNumber}\n onClose={() => setOpenVersion(null)}\n />\n )}\n\n {/* The chooser — Export + Edit JSON (function/endpoint only, PL-2) fill\n the shell's slot; Import is the shell's own. */}\n {specMenuOpen && (\n <SpecChooserModal\n kind={kind}\n onClose={() => setSpecMenuOpen(false)}\n onImport={() => {\n setSpecMenuOpen(false);\n setImporting(true);\n }}\n >\n {hasDefinitionActions(kind) && (\n <>\n <p className=\"muted small\">\n Export a portable definition — the same shape Import accepts — or Edit JSON to\n change what's stored directly.\n </p>\n <div className=\"rail-spec-menu-row\">\n <button\n type=\"button\"\n className=\"btn ghost\"\n data-testid=\"rail-spec-export\"\n onClick={() => {\n setSpecMenuOpen(false);\n setExporting(true);\n }}\n >\n Export\n </button>{\" \"}\n <button\n type=\"button\"\n className=\"btn ghost\"\n disabled={!def}\n data-testid=\"rail-json-edit\"\n onClick={() => {\n setSpecMenuOpen(false);\n openEdit();\n }}\n >\n Edit JSON\n </button>\n </div>\n </>\n )}\n </SpecChooserModal>\n )}\n\n {/* Export — a read-only modal carrying the `/spec` route's `spec` field\n verbatim, via `@w6w/ui`'s `CodeBlock`, never a second editable text\n box. The request fires only while this modal is open. */}\n {exporting && (\n <Modal title=\"Export spec document\" onClose={() => setExporting(false)} wide>\n <div className=\"modal-body\">\n {specQuery.isLoading ? (\n <p className=\"muted small\">Loading…</p>\n ) : specQuery.isError ? (\n <div className=\"error\" data-testid=\"rail-spec-error\">\n {specQuery.error instanceof Error\n ? specQuery.error.message\n : String(specQuery.error)}\n </div>\n ) : specQuery.data ? (\n <div data-testid=\"rail-spec-json\">\n <CodeBlock\n code={JSON.stringify(specQuery.data, null, 2)}\n language=\"json\"\n maxHeight=\"420px\"\n copyable\n />\n </div>\n ) : null}\n </div>\n <div className=\"modal-actions\">\n <button type=\"button\" className=\"btn ghost\" onClick={() => setExporting(false)}>\n Close\n </button>\n </div>\n </Modal>\n )}\n\n {/* Self-contained — Save lives inside this modal, mirroring\n `WorkflowDetailPage.tsx`'s read-only card, never `WorkflowsPage.tsx`'s\n Save-less `showJson` modal. */}\n {editing && (\n <Modal title=\"Edit definition\" onClose={() => setEditing(false)} wide>\n <div className=\"modal-body\">\n <JsonEditor\n value={editText}\n onChange={setEditText}\n minHeight=\"320px\"\n aria-label=\"Edit definition JSON\"\n />\n {editEval.blockedReason && (\n <p className=\"muted small\" data-testid=\"rail-edit-reason\">\n {editEval.blockedReason}\n </p>\n )}\n {editError && <div className=\"error\">{editError}</div>}\n </div>\n <div className=\"modal-actions\">\n <button type=\"button\" className=\"btn ghost\" onClick={() => setEditing(false)}>\n Cancel\n </button>\n <button\n type=\"button\"\n className=\"btn\"\n disabled={editEval.blockedReason !== null || savingDef}\n data-testid=\"rail-json-save\"\n onClick={onSaveEdit}\n >\n {savingDef ? \"Saving…\" : \"Save\"}\n </button>\n </div>\n </Modal>\n )}\n\n {/* Unified settings modal for name and key. */}\n {editingSettings && listRow && (\n <CallableSettingsModal\n // `key={id}` forces a remount (not a re-render) when an in-app\n // navigation swaps the rail to a different resource while this modal\n // is open — the modal's `useState` initializers never re-run on a\n // prop change, so a save would mix stale fields with the new `id`.\n key={id}\n kind={kind}\n id={id}\n initial={{\n displayName,\n key: (listRow as { key?: string | null }).key ?? null,\n tags: [],\n }}\n onSave={async (data) => {\n if (!record) throw new Error(\"Unable to save settings\");\n // Definition AND token from the same record, read now: the text written is this\n // record's own fields plus the modal's edits.\n const base = record.definition;\n const edited =\n kind === \"function\"\n ? // `canEditKey: true` for function (`callable-descriptors.ts`): `data.key` must\n // reach the server (the modal falls back to `initial.key` when unchanged).\n { ...base, displayName: data.displayName, key: data.key ?? base.key }\n : { ...base, displayName: data.displayName };\n const vars = { definition: edited, ifUnmodifiedSince: record.updatedAt };\n return new Promise((resolve, reject) => {\n const settled = { onSuccess: () => resolve(), onError: reject };\n if (kind === \"function\") saveFnMut.mutate(vars, settled);\n else saveEpMut.mutate(vars, settled);\n });\n }}\n onClose={() => setEditingSettings(false)}\n />\n )}\n\n {hasDelete(kind) && (\n <SettingsDangerZone\n kind={kind}\n archived={archived}\n deleteConfirming={deleteConfirming}\n archiveConfirming={archiveConfirming}\n deleteError={deleteError}\n archiveError={archiveError}\n onRequestDelete={() => setDeleteConfirming(true)}\n onRequestArchive={() => setArchiveConfirming(true)}\n onConfirmDelete={onDelete}\n onConfirmArchive={onArchive}\n onCloseDelete={() => setDeleteConfirming(false)}\n onCloseArchive={() => setArchiveConfirming(false)}\n />\n )}\n\n {importing && (\n <ImportSpecModal\n kind={kind}\n project={project ?? undefined}\n listKeys={IMPORT_LIST_KEYS}\n onOpenImported={(k, newId) => onNavigate({ type: \"imported\", kind: k, id: newId })}\n onClose={() => setImporting(false)}\n />\n )}\n </div>\n );\n}\n\nfunction SettingsToolIcon() {\n return <Icon name=\"settings\" />;\n}\n\n/** The package's Settings tool — workflow, function and endpoint. */\nexport const settingsTool: RailTool = {\n id: \"settings\",\n title: \"Settings\",\n rendersHeading: true,\n Icon: SettingsToolIcon,\n isAvailable: (ctx) =>\n ctx?.kind === \"workflow\" || ctx?.kind === \"function\" || ctx?.kind === \"endpoint\",\n Panel: SettingsToolPanel,\n};\n","import {\n type ExprValue,\n ExpressionInput,\n ExpressionOptionsProvider,\n IconButton,\n type SecretValue,\n useExpressionOptions,\n} from \"@w6w/ui\";\nimport { type WorkflowVariableRow, duplicateKeyIndexes, varsRailFor } from \"../lib/index.ts\";\n\nconst VARIABLE_TYPES = [\"string\", \"number\", \"boolean\", \"object\", \"array\"] as const;\n\n/** Shared workflow input editor, used in the Data rail and the legacy settings dialog. */\nexport function WorkflowVariablesEditor({\n variables,\n onVariablesChange,\n}: {\n variables: WorkflowVariableRow[];\n onVariablesChange: (next: WorkflowVariableRow[]) => void;\n}) {\n const inheritedVars = useExpressionOptions().vars ?? [];\n function addVariable() {\n onVariablesChange([...variables, { key: \"\" }]);\n }\n function updateVariable(i: number, next: Partial<WorkflowVariableRow>) {\n onVariablesChange(variables.map((v, idx) => (idx === i ? { ...v, ...next } : v)));\n }\n function removeVariable(i: number) {\n onVariablesChange(variables.filter((_, idx) => idx !== i));\n }\n const dupIndexes = duplicateKeyIndexes(variables);\n return (\n <div className=\"workflow-variable-fields\">\n {/* HITL-5: declaring a variable flips this workflow's generated MCP\n tool from a pass-through schema to a declared one — say so. */}\n <p className=\"muted small\">\n Declaring variables here defines this workflow's <strong>public input schema</strong>: API\n and AI (MCP) callers then see exactly these inputs. With none declared, they may send\n anything.\n </p>\n <div className=\"row\" style={{ justifyContent: \"space-between\", alignItems: \"center\" }}>\n <span className=\"muted small\">\n {variables.length === 0\n ? \"No variables declared.\"\n : `${variables.length} variable${variables.length === 1 ? \"\" : \"s\"} declared.`}\n </span>\n <button type=\"button\" className=\"btn ghost\" onClick={addVariable}>\n + Add variable\n </button>\n </div>\n {variables.length > 0 && (\n <ul className=\"list\" data-testid=\"workflow-variables-list\">\n {variables.map((v, i) => (\n <li\n // biome-ignore lint/suspicious/noArrayIndexKey: rows are positional and reorderable\n key={i}\n style={{\n flexDirection: \"column\",\n alignItems: \"stretch\",\n gap: \"var(--w6w-sp-1)\",\n }}\n >\n <div className=\"workflow-variable-row\">\n <input\n type=\"text\"\n value={v.key}\n placeholder=\"key\"\n aria-label=\"Variable key\"\n onChange={(e) => updateVariable(i, { key: e.target.value })}\n />\n <select\n value={v.type ?? \"\"}\n aria-label=\"Variable type\"\n onChange={(e) =>\n updateVariable(i, {\n type: (e.target.value || undefined) as WorkflowVariableRow[\"type\"],\n })\n }\n >\n <option value=\"\">(unset)</option>\n {VARIABLE_TYPES.map((t) => (\n <option key={t} value={t}>\n {t}\n </option>\n ))}\n </select>\n <label className=\"row\" style={{ gap: \"var(--w6w-sp-1)\", alignItems: \"center\" }}>\n <input\n type=\"checkbox\"\n checked={v.required ?? false}\n onChange={(e) => updateVariable(i, { required: e.target.checked })}\n />\n <span className=\"muted small\">required</span>\n </label>\n {/* Narrow `vars` for THIS row only: a variable's default\n may reference the variables declared above it, never\n itself or the ones below. Only that one key is\n contributed — secrets, documents, sample values and the\n callbacks come through from the app shell untouched,\n because the provider layers rather than replaces. */}\n <ExpressionOptionsProvider\n value={{ vars: varsRailFor(variables, i, inheritedVars) }}\n >\n <ExpressionInput\n // Re-key on the list's shape (not just `i`): ExpressionInput\n // seeds its parts once on mount and never again, so when a\n // row is removed and later rows shift up an index, React\n // must remount the widget rather than reuse the instance —\n // otherwise the surviving cell keeps showing the previous\n // occupant's default (see ExpressionInput.tsx:56-57).\n key={`${variables.length}:${i}`}\n value={v.default as ExprValue | string | SecretValue | undefined}\n onChange={(next) => updateVariable(i, { default: next })}\n placeholder=\"default\"\n aria-label=\"Variable default\"\n />\n </ExpressionOptionsProvider>\n <IconButton\n danger\n icon=\"close\"\n label={`Remove variable ${v.key || i + 1}`}\n onClick={() => removeVariable(i)}\n />\n </div>\n {dupIndexes.includes(i) && (\n <span className=\"muted small\" data-testid=\"variable-duplicate\">\n Duplicate key — a later row with the same name wins.\n </span>\n )}\n </li>\n ))}\n </ul>\n )}\n </div>\n );\n}\n","/**\n * The pure decisions behind the workflow rail's State panel (`rail/StartingStateTool.tsx`):\n * which run's state it shows, which step last wrote each top-level key, and how the starting\n * state (`Workflow.initialState`) reads as a preview.\n *\n * Pure, React-free, `.ts`, **no value import of `@w6w/ui`** — the same header rule as\n * `starting-data.ts` (studio's `test:unit` has no jsx loader).\n */\nimport { type StateLogRow, foldStateLog } from \"@w6w/expr\";\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === \"object\" && !Array.isArray(v);\n}\n\n/**\n * The run's state tree: the snapshot `GET /runs/:id` serves when one was persisted, else the\n * state-write log folded by `@w6w/expr`'s `foldStateLog` (the same fold the run log's \"state\n * after this step\" uses). `undefined` when neither has anything.\n */\nexport function runStateTree(\n snapshot: unknown,\n writes: readonly StateLogRow[] | undefined,\n): Record<string, unknown> | undefined {\n if (isPlainObject(snapshot)) return snapshot;\n if (writes && writes.length > 0) return foldStateLog(writes);\n return undefined;\n}\n\n/**\n * Who last wrote each top-level state key, from the run's state-write log: the node id of the\n * last write under that key, or `null` for a key that came from the starting state (the seed row,\n * `seq 0` with no node). A warning row wrote nothing; a delete (`new` absent or `null`) forgets the\n * key; a whole-tree write (`path []`) hands every key it sets to its node. Read in `seq` order\n * whatever order the rows arrive in.\n */\nexport function stateKeyWriters(writes: readonly StateLogRow[]): Map<string, string | null> {\n const out = new Map<string, string | null>();\n const rows = [...writes].sort((a, b) => a.seq - b.seq);\n for (const row of rows) {\n if (row.warning !== undefined || !Array.isArray(row.path)) continue;\n const node = row.nodeId ?? null;\n const set = row.new !== undefined && row.new !== null;\n if (row.path.length === 0) {\n out.clear();\n if (set && isPlainObject(row.new)) for (const k of Object.keys(row.new)) out.set(k, node);\n continue;\n }\n const key = row.path[0];\n if (row.path.length === 1 && !set) out.delete(key);\n else out.set(key, node);\n }\n return out;\n}\n\n/** One line of the starting state preview: a leaf's dotted path and how it reads. */\nexport interface StartingStateRow {\n path: string;\n /** `reference`: a string carrying a `{{ }}` reference, resolved when a run starts. */\n kind: \"literal\" | \"reference\";\n /** The reference text verbatim, or the literal as JSON. */\n text: string;\n}\n\nconst REFERENCE = /\\{\\{[\\s\\S]*?\\}\\}/;\n\n/**\n * The starting state flattened to one row per leaf, in key order: nested objects descend\n * (`a.b`), arrays and empty objects stay one literal row. A string with a `{{ }}` reference is a\n * `reference` row shown as typed, never as a value: it only resolves when a run starts.\n */\nexport function startingStateRows(\n initial: Record<string, unknown> | undefined,\n): StartingStateRow[] {\n const out: StartingStateRow[] = [];\n const walk = (value: unknown, path: string) => {\n if (isPlainObject(value) && Object.keys(value).length > 0) {\n for (const [k, v] of Object.entries(value)) walk(v, path ? `${path}.${k}` : k);\n return;\n }\n if (typeof value === \"string\" && REFERENCE.test(value)) {\n out.push({ path, kind: \"reference\", text: value });\n return;\n }\n out.push({ path, kind: \"literal\", text: JSON.stringify(value) ?? String(value) });\n };\n if (initial) for (const [k, v] of Object.entries(initial)) walk(v, k);\n return out;\n}\n","import { useQueryClient } from \"@tanstack/react-query\";\n/**\n * The workflow rail's State tool: a panel with two sections, kept apart because they are two\n * different things.\n *\n * - **Current state** — the state tree of this workflow's latest run (any run: the header Run,\n * ▶ run-from-node, a schedule), as a collapsible JSON tree (`ResultViewer`), with the run's id\n * and start time, a link that opens that run on the canvas, and the step that last wrote each\n * top-level key (`GET /runs/:id/state-writes`). It follows the run while it is in flight\n * (`useLiveRunQuery` + `useRunStateWritesQuery`, the same queries — and so the same cache — the\n * editor's run log reads) and re-reads the run list once it finishes.\n * - **Starting state** — a read-only preview of `Workflow.initialState`, with `{{ }}` references\n * shown as references, and \"Edit starting state\", which opens the editor's starting state\n * editor (`StartingStateModal`) through the `onOpenStartingState` the canvas editor publishes.\n *\n * The strip dot still says the workflow has starting state. Hidden wherever no workflow editor\n * published that opener (Functions, Endpoints, a list).\n */\nimport type { StateLogRow } from \"@w6w/expr\";\nimport { Icon, ResultViewer } from \"@w6w/ui\";\nimport { useEffect, useRef } from \"react\";\nimport type { RailTool } from \"../chrome/RightRail.tsx\";\nimport type { WorkspaceCallable } from \"../chrome/workspace.tsx\";\nimport { WorkflowVariablesEditor } from \"../editor/WorkflowVariablesEditor.tsx\";\nimport { startingDataCollisions } from \"../lib/starting-data.ts\";\nimport { runStateTree, startingStateRows, stateKeyWriters } from \"../lib/state-panel.ts\";\nimport { shouldContinuePolling } from \"../lib/workflow-live-run.ts\";\nimport {\n runsKey,\n useLiveRunQuery,\n useRunStateWritesQuery,\n useRunsQuery,\n} from \"../repos/workflows.ts\";\n\ntype WorkflowCtx = Extract<WorkspaceCallable, { kind: \"workflow\" }>;\n\nfunction opener(ctx: WorkspaceCallable): (() => void) | undefined {\n return ctx?.kind === \"workflow\" ? ctx.onOpenStartingState : undefined;\n}\n\nfunction StartingStateToolIcon() {\n return <Icon name=\"database\" />;\n}\n\nfunction CurrentStateSection({ ctx }: { ctx: WorkflowCtx }) {\n const qc = useQueryClient();\n const runsQuery = useRunsQuery(ctx.id);\n const latest = runsQuery.data?.[0];\n const runQuery = useLiveRunQuery(latest?.runId ?? null);\n const status = runQuery.data?.status ?? latest?.status;\n const writesQuery = useRunStateWritesQuery(latest?.runId ?? null, status);\n const finished = status !== undefined && !shouldContinuePolling(status);\n\n // The list row was read while the run was in flight: once it finishes, read the list again\n // so the row (and a newer run, if one started meanwhile) is current. Once per run, so a row\n // the server still answers without `finishedAt` cannot loop the refetch.\n const refreshedFor = useRef<string | null>(null);\n useEffect(() => {\n if (!finished || !latest || latest.finishedAt !== null) return;\n if (refreshedFor.current === latest.runId) return;\n refreshedFor.current = latest.runId;\n void qc.invalidateQueries({ queryKey: runsKey(ctx.id) });\n }, [finished, latest, qc, ctx.id]);\n\n if (runsQuery.isLoading) return <p className=\"muted small\">Loading…</p>;\n if (!latest) {\n return (\n <p className=\"muted small\" data-testid=\"rail-state-current-empty\">\n No run yet. Run the workflow and the state it ends with shows here.\n </p>\n );\n }\n\n const writes: readonly StateLogRow[] = writesQuery.data?.writes ?? [];\n const snapshot = (runQuery.data as { state?: unknown } | undefined)?.state;\n const tree = runStateTree(snapshot, writes);\n const writers = stateKeyWriters(writes);\n const keys = tree ? Object.keys(tree) : [];\n\n return (\n <div className=\"w6w-stack\" data-testid=\"rail-state-current\">\n <dl className=\"rail-meta-list\">\n <dt>Run</dt>\n <dd>\n <code data-testid=\"rail-state-run-id\">{latest.runId}</code>\n </dd>\n <dt>Started</dt>\n <dd>{new Date(latest.startedAt).toLocaleString()}</dd>\n <dt>Status</dt>\n <dd data-testid=\"rail-state-run-status\">{status}</dd>\n </dl>\n {ctx.onOpenRun && (\n <button\n type=\"button\"\n className=\"btn ghost\"\n data-testid=\"rail-state-open-run\"\n onClick={() => ctx.onOpenRun?.(latest.runId)}\n >\n Open this run\n </button>\n )}\n {runQuery.isLoading ? (\n <p className=\"muted small\">Loading…</p>\n ) : keys.length === 0 || !tree ? (\n <p className=\"muted small\" data-testid=\"rail-state-current-none\">\n This run has no state.\n </p>\n ) : (\n <>\n <ResultViewer value={tree} />\n <ul className=\"list\" data-testid=\"rail-state-writers\">\n {keys.map((key) => {\n const node = writers.get(key);\n return (\n <li key={key} data-testid=\"rail-state-writer\">\n <span className=\"list-main\">\n <code>{key}</code>\n <span className=\"muted small block\">\n {node ? (\n <>\n Last written by <code>{node}</code>\n </>\n ) : writers.has(key) ? (\n \"From the starting state\"\n ) : (\n \"No step wrote it\"\n )}\n </span>\n </span>\n </li>\n );\n })}\n </ul>\n {writesQuery.data?.truncated && (\n <p className=\"muted small\">\n The run's state log reached its limit, so later writers aren't shown.\n </p>\n )}\n </>\n )}\n </div>\n );\n}\n\nfunction StartingStateSection({ ctx }: { ctx: WorkflowCtx }) {\n const rows = startingStateRows(ctx.startingState);\n const collisions = startingDataCollisions(ctx.startingState, ctx.variables ?? []);\n return (\n <div className=\"w6w-stack\" data-testid=\"rail-state-starting\">\n <p className=\"muted small\">\n Workflow inputs override starting state; starting state overrides project variables with the\n same name.\n </p>\n {collisions.length > 0 && (\n <p className=\"muted small\" data-testid=\"starting-data-collision\">\n Overridden by workflow inputs: {collisions.join(\", \")}.\n </p>\n )}\n <button\n type=\"button\"\n className=\"btn\"\n data-testid=\"rail-state-edit-starting\"\n onClick={() => ctx.onOpenStartingState?.()}\n >\n Edit starting state\n </button>\n {rows.length === 0 ? (\n <p className=\"muted small\" data-testid=\"rail-state-starting-empty\">\n No starting state. Every run begins with an empty state.\n </p>\n ) : (\n <ul className=\"list\">\n {rows.map((row) => (\n <li key={row.path} data-testid=\"rail-state-starting-row\" data-kind={row.kind}>\n <span className=\"list-main\">\n <code>{row.path}</code>\n <span className=\"muted small block\">\n {row.kind === \"reference\" ? (\n <>\n Reference <code>{row.text}</code>, resolved when a run starts\n </>\n ) : (\n <code>{row.text}</code>\n )}\n </span>\n </span>\n </li>\n ))}\n </ul>\n )}\n </div>\n );\n}\n\nfunction StatePanel({ ctx }: { ctx: WorkspaceCallable }) {\n // Defensive, as in the other tools: `isAvailable` keeps this off the strip for any other ctx.\n if (ctx?.kind !== \"workflow\" || !ctx.onOpenStartingState) return null;\n return (\n <div className=\"w6w-stack\" data-testid=\"rail-state-body\">\n <div className=\"right-rail-panel-head\">\n <h3>Data</h3>\n </div>\n {ctx.onVariablesChange && (\n <section data-testid=\"rail-workflow-variables\">\n <h4>Workflow inputs</h4>\n <WorkflowVariablesEditor\n variables={ctx.variables ?? []}\n onVariablesChange={ctx.onVariablesChange}\n />\n </section>\n )}\n <section data-testid=\"rail-state-current-section\">\n <h4>Current state</h4>\n <CurrentStateSection ctx={ctx} />\n </section>\n <hr />\n <section data-testid=\"rail-state-starting-section\">\n <h4>Starting state</h4>\n <StartingStateSection ctx={ctx} />\n </section>\n </div>\n );\n}\n\nexport const startingStateTool: RailTool = {\n id: \"starting-state\",\n title: \"Data\",\n rendersHeading: true,\n Icon: StartingStateToolIcon,\n isAvailable: (ctx) => opener(ctx) !== undefined,\n Panel: StatePanel,\n hasIndicator: (ctx) => ctx?.kind === \"workflow\" && ctx.hasStartingState === true,\n};\n","/**\n * The rail tools `<WorkflowEditor>`, `<CallableRail>` and Studio's rail mount, in display order.\n * Each serves workflow, function and endpoint resources (`isAvailable` decides per context); the\n * Aliases tool is deliberately absent (alias management is Studio-only). Reachable from the `chrome` subpath, never from the package root barrel — the\n * Error handling tool pulls in `@w6w/ui/flow`.\n */\nimport type { RailTool } from \"../chrome/RightRail.tsx\";\nimport { codeTool } from \"./CodeTool.tsx\";\nimport { connectionsTool } from \"./ConnectionsTool.tsx\";\nimport { errorHandlingTool } from \"./ErrorHandlingTool.tsx\";\nimport { historyTool } from \"./HistoryTool.tsx\";\nimport { settingsTool } from \"./SettingsTool.tsx\";\nimport { startingStateTool } from \"./StartingStateTool.tsx\";\n\nexport const editorRailTools: readonly RailTool[] = [\n settingsTool,\n codeTool,\n errorHandlingTool,\n startingStateTool,\n connectionsTool,\n historyTool,\n];\n"],"names":["WorkspaceContext","createContext","WorkspaceProvider","children","base","override","setCallable","useState","resource","value","useMemo","jsx","useHasWorkspace","useContext","useWorkspace","ctx","key","useEffect","useWorkspaceCallable","CLOSED","readStoredState","raw","activeTool","restoreRailState","RailShell","tools","state","onToggle","t","ActivePanel","jsxs","tool","_a","PersistedRail","storageKey","setState","id","prev","RightRail","available","useProjectExpressionOptions","project","projectId","varsQuery","useVarsQuery","secretsQuery","useSecretsQuery","constantsQuery","useConstantsQuery","documentsQuery","useDocumentsQuery","sealSecretFn","useSealSecret","createVarMut","useCreateVarMutation","createSecretMut","useCreateSecretMutation","v","c","s","projectDocumentSources","documentSampleValues","input","ProjectExpressionScope","options","ExpressionOptionsProvider","CodePanel","openTab","setOpenTab","snippetCallable","toSnippetCallable","triggers","tabs","snippetTabsFor","unavailableReason","label","icon","Icon","Modal","CallFromCodeBody","CodeToolIcon","codeTool","isAvailable","connectionsTool","WorkflowConnectionsPanel","DEFAULT_ENV","RailEnvContext","RailEnvProvider","onNavigate","useRailEnv","CALL_APP","refOf","target","nounOf","ErrorHandlerSection","kind","policy","ready","saving","onPersist","functionsQuery","useFunctionsQuery","workflowsQuery","useWorkflowsQuery","pickerOpen","setPickerOpen","error","setError","ref","selfDecision","errorHandlerSelfDecision","_b","_d","_c","w","fn","f","persist","next","pickHandler","built","nextTarget","nextId","RetryPolicyFields","StepBuilderModal","BufferErrorHandlingPanel","onPolicyChange","policyFromDefinition","CachedErrorHandlingPanel","fnQuery","useFunctionQuery","epQuery","useEndpointQuery","saveFnMut","useGuardedSaveFunctionMutation","saveEpMut","useGuardedSaveEndpointMutation","record","callableRecord","onError","vars","definitionWithPolicy","settled","e","ApiError","ErrorHandlingPanel","ErrorHandlingToolIcon","errorHandlingTool","isSettingsRailAvailable","historyTool","commitTag","tags","typed","removeTag","tag","TagEditor","onChange","setTyped","handleTypedChange","result","IconButton","CallableSettingsModal","props","settings","descriptorFor","initial","displayName","setDisplayName","setKey","setTags","isSaving","setIsSaving","displayNameChanged","keyChanged","tagsChanged","isDirty","canEditKey","keyGrammarOk","isEndpointKey","canSubmit","handleSave","enterSubmit","useEnterSubmit","filterKeyInput","TESTIDS","VersionHistoryModal","versionNumber","testids","versionQuery","useVersionQuery","revertMut","useRevertMutation","invokeMut","useInvokeVersionMutation","confirmingRevert","setConfirmingRevert","restoreError","setRestoreError","Fragment","CodeBlock","ConfirmModal","DangerZone","archived","deleteLabel","deleteTestId","archiveTestId","onRequestDelete","onRequestArchive","deleteError","archiveError","DeleteButton","SettingsHeading","EditButton","MetadataSection","fields","row","SpecActionsTrigger","SpecChooserModal","onImport","onClose","VersionSection","open","versions","VersionListModal","loading","DANGER_COPY","SettingsDangerZone","copy","IMPORT_LIST_KEYS","functionsKey","endpointsKey","workflowsKey","WorkflowSettingsPanel","editingSettings","setEditingSettings","historyOpen","setHistoryOpen","versionListOpen","setVersionListOpen","isWorkflow","wfDefQuery","useWorkflowQuery","saveWfMut","useSaveWorkflowMutation","archiveWfMut","useArchiveWorkflowMutation","deleteWfMut","useDeleteWorkflowMutation","deleting","useRef","specMenuOpen","setSpecMenuOpen","importing","setImporting","exporting","setExporting","deleteConfirming","setDeleteConfirming","archiveConfirming","setArchiveConfirming","setDeleteError","setArchiveError","specQuery","useSpecQuery","specCollectionForKind","versionsQuery","useVersionsQuery","publishMut","usePublishMutation","setEnabledMut","useSetEnabledMutation","publishError","setPublishError","enableError","setEnableError","openVersion","setOpenVersion","listRow","onDelete","onArchive","metadataFieldsForKind","data","stored","resolve","reject","updated","ImportSpecModal","newId","SettingsToolPanel","CallableSettingsPanel","kind0","endpointsQuery","useEndpointsQuery","editing","setEditing","editText","setEditText","editError","setEditError","editToken","setEditToken","fnDefQuery","epDefQuery","deleteFnMut","useDeleteFunctionMutation","deleteEpMut","useDeleteEndpointMutation","archiveFnMut","useArchiveFunctionMutation","archiveEpMut","useArchiveEndpointMutation","specCollection","versionsKind","hasVersionHistory","def","defJson","openEdit","editEval","evaluateEdit","savingDef","onSaveEdit","onSettled","hasDefinitionActions","JsonEditor","hasDelete","k","SettingsToolIcon","settingsTool","VARIABLE_TYPES","WorkflowVariablesEditor","variables","onVariablesChange","inheritedVars","useExpressionOptions","addVariable","updateVariable","i","idx","removeVariable","_","dupIndexes","duplicateKeyIndexes","varsRailFor","ExpressionInput","isPlainObject","runStateTree","snapshot","writes","foldStateLog","stateKeyWriters","out","rows","a","b","node","set","REFERENCE","startingStateRows","walk","path","opener","StartingStateToolIcon","CurrentStateSection","qc","useQueryClient","runsQuery","useRunsQuery","latest","runQuery","useLiveRunQuery","status","writesQuery","useRunStateWritesQuery","finished","shouldContinuePolling","refreshedFor","runsKey","tree","writers","keys","ResultViewer","_e","StartingStateSection","collisions","startingDataCollisions","StatePanel","startingStateTool","editorRailTools"],"mappings":";;;;;;;;;;;;;;;;;;AAkJA,MAAMA,KAAmBC,GAA4C,IAAI;AASlE,SAASC,GAAkB;AAAA,EAChC,UAAAC;AAAA,EACA,MAAAC,IAAO;AACT,GAAsD;AACpD,QAAM,CAACC,GAAUC,CAAW,IAAIC,EAA4B,IAAI,GAC1DC,IAAWH,KAAYD,GACvBK,IAAQC,GAAQ,OAAO,EAAE,UAAAF,GAAU,aAAAF,MAAgB,CAACE,CAAQ,CAAC;AACnE,SAAO,gBAAAG,EAACX,GAAiB,UAAjB,EAA0B,OAAAS,GAAe,UAAAN,EAAA,CAAS;AAC5D;AAGO,SAASS,KAA2B;AACzC,SAAOC,GAAWb,EAAgB,MAAM;AAC1C;AAGO,SAASc,GAAaN,GAAmC;AAC9D,QAAMO,IAAMF,GAAWb,EAAgB;AACvC,MAAI,CAACe,EAAK,OAAM,IAAI,MAAM,sDAAsD;AAChF,QAAM,EAAE,aAAAT,MAAgBS,GAclBC,IAAMR,IAAW,KAAK,UAAUA,CAAQ,IAAI;AAElD,EAAAS,GAAU,OACRX,EAAYE,CAAQ,GACb,MAAMF,EAAY,IAAI,IAC5B,CAACU,G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MAAA;AAAA,IACzB,GACF;AAAA,IAEF,gBAAAe,EAAC,WAAA,EAAQ,eAAY,8BACnB,UAAA;AAAA,MAAA,gBAAAnB,EAAC,QAAG,UAAA,gBAAA,CAAa;AAAA,MACjB,gBAAAA,EAAC+V,MAAoB,KAAA3V,EAAA,CAAU;AAAA,IAAA,GACjC;AAAA,sBACC,MAAA,EAAG;AAAA,IACJ,gBAAAe,EAAC,WAAA,EAAQ,eAAY,+BACnB,UAAA;AAAA,MAAA,gBAAAnB,EAAC,QAAG,UAAA,iBAAA,CAAc;AAAA,MAClB,gBAAAA,EAACmX,MAAqB,KAAA/W,EAAA,CAAU;AAAA,IAAA,EAAA,CAClC;AAAA,EAAA,GACF;AAEJ;AAEO,MAAMmX,KAA8B;AAAA,EACzC,IAAI;AAAA,EACJ,OAAO;AAAA,EACP,gBAAgB;AAAA,EAChB,MAAMzB;AAAA,EACN,aAAa,CAAC1V,MAAQyV,GAAOzV,CAAG,MAAM;AAAA,EACtC,OAAOkX;AAAA,EACP,cAAc,CAAClX,OAAQA,KAAA,gBAAAA,EAAK,UAAS,cAAcA,EAAI,qBAAqB;AAC9E,GC1NaoX,KAAuC;AAAA,EAClD5D;AAAA,EACAtP;AAAA,EACAkE;AAAA,EACA+O;AAAA,EACA/S;AAAA,EACAkE;AACF;"}
1
+ {"version":3,"file":"editor-tools-j3ThBY_4.js","sources":["../src/chrome/workspace.tsx","../src/chrome/RightRail.tsx","../src/rail/ExpressionScope.tsx","../src/rail/CodeTool.tsx","../src/rail/ConnectionsTool.tsx","../src/rail/rail-env.tsx","../src/rail/ErrorHandlingTool.tsx","../src/rail/HistoryTool.tsx","../src/lib/tag-editor.ts","../src/chrome/TagEditor.tsx","../src/chrome/CallableSettingsModal.tsx","../src/chrome/VersionHistoryModal.tsx","../src/chrome/DangerZone.tsx","../src/rail/settings-sections.tsx","../src/rail/SettingsTool.tsx","../src/editor/WorkflowVariablesEditor.tsx","../src/lib/state-panel.ts","../src/rail/StartingStateTool.tsx","../src/rail/editor-tools.ts"],"sourcesContent":["import type {\n CallablePolicy,\n SnippetInput,\n TriggerPreview,\n WorkflowVariableRow,\n} from \"@w6w/embed/lib\";\nimport type { WorkflowConnectionResources } from \"@w6w/ui/flow\";\n/**\n * `WorkspaceContext` — what resource (if any) the currently-viewed page has\n * open. The right rail (`chrome/RightRail.tsx`) and every registered\n * `RailTool`'s `Panel` read this via `useWorkspaceCallable`; a page publishes\n * into it via `useWorkspace`.\n *\n * Route-scoped, not root-scoped — mirrors `ProjectContext.tsx`'s precedent\n * (the only other context in this codebase deliberately scoped below the app\n * root): mounted around `Layout()`'s own returned tree (`components/Layout.tsx`),\n * next to its only reader, the rail.\n *\n * The publish idiom (compute a value during render, `useEffect` keyed on a\n * stable serialization of it, clear on unmount) mirrors the shape of the\n * human's uncommitted `src/ui/useDocumentTitle.ts` — copied here as a\n * PATTERN, never imported: that file is one of this project's 23 uncommitted\n * human files and a merged branch cannot depend on it.\n */\nimport { type ReactNode, createContext, useContext, useEffect, useMemo, useState } from \"react\";\n\n/**\n * T2.1.2: widened to a discriminated union, one arm per kind — every new\n * field OPTIONAL, no new required member, so every existing producer keeps\n * compiling and behaving identically (`{kind, id}` alone still satisfies any\n * arm). The extra fields are what `CodeTool`'s snippet panel needs per kind\n * (mirrors `lib/sdk-snippets.ts`'s `SnippetCallable`, field-for-field where\n * the names match — see `lib/code-rail.ts`'s `toSnippetCallable` for the one\n * field that doesn't, `label` -> `displayName`).\n */\nexport type WorkspaceCallable =\n | {\n kind: \"function\";\n id: string;\n label?: string;\n key?: string;\n inputs?: readonly SnippetInput[];\n alias?: string;\n /**\n * The Function's / Endpoint's run-level error policy and its writer, published by an\n * editor that owns the definition buffer (`useCallableDraft`) so the rail's Error handling\n * tool edits and saves THAT buffer (pending edits ride along) instead of racing it. Same\n * ⚠️ as the workflow arm: `onPolicyChange` MUST be referentially stable\n * (`useCallableDraft`'s is).\n */\n policy?: CallablePolicy;\n onPolicyChange?: (policy: CallablePolicy) => void;\n }\n | {\n kind: \"endpoint\";\n id: string;\n label?: string;\n key?: string;\n invokeUrl?: string;\n invokeUrlByKey?: string;\n urlForm?: \"id\" | \"key\";\n alias?: string;\n inputs?: readonly SnippetInput[];\n /**\n * The Function's / Endpoint's run-level error policy and its writer, published by an\n * editor that owns the definition buffer (`useCallableDraft`) so the rail's Error handling\n * tool edits and saves THAT buffer (pending edits ride along) instead of racing it. Same\n * ⚠️ as the workflow arm: `onPolicyChange` MUST be referentially stable\n * (`useCallableDraft`'s is).\n */\n policy?: CallablePolicy;\n onPolicyChange?: (policy: CallablePolicy) => void;\n }\n | {\n kind: \"workflow\";\n connectionResources?: WorkflowConnectionResources;\n id: string;\n label?: string;\n key?: string;\n triggers?: TriggerPreview[];\n /** Stable editor-owned actions serialize pending draft saves and refresh its buffer. */\n onRestoreVersion?: (versionNumber: number) => Promise<void>;\n /** Whether the editor buffer matches the published snapshot; absent while loading. */\n definitionStatus?: \"published\" | \"draft\" | \"unpublished\";\n /** Use the editor's save/publish guard from the sidebar too. Must be stable. */\n onPublish?: () => Promise<void>;\n publishDisabled?: boolean;\n authoringSettings?: { autoSave: boolean; savePosition: boolean };\n onAuthoringSettingChange?: (key: \"autoSave\" | \"savePosition\", value: boolean) => void;\n variables?: WorkflowVariableRow[];\n onVariablesChange?: (variables: WorkflowVariableRow[]) => void;\n onOpenHistory?: () => void;\n /**\n * The workflow's run-level error policy, and the writer that applies it\n * (core Workflow RFC — *Amendment — 2026-08-21: the run-level error\n * handler*). Published ONLY by the page that owns the definition buffer\n * — the canvas editor — so the rail's Error handling tool edits the same\n * text the editor is about to save instead of racing it over the wire.\n * `ErrorHandlingTool` is the only reader; see `lib/settings-rail.ts`'s\n * `isAvailable` for why the tool hides itself when they are absent.\n *\n * ⚠️ `onPolicyChange` MUST be referentially stable across renders (a\n * `useCallback` reading through a ref). `useWorkspace` keys its publish\n * effect on `JSON.stringify(resource)`, which drops functions — so the\n * stored callback is whichever one was current when some OTHER field\n * last changed, and a closure that captured stale editor state would\n * write stale bytes.\n */\n policy?: CallablePolicy;\n onPolicyChange?: (policy: CallablePolicy) => void;\n /** `Workflow.initialState` is a non-empty object: the rail State tool's dot. */\n hasStartingState?: boolean;\n /** `Workflow.initialState` as the editor holds it: the State panel's starting state preview. */\n startingState?: Record<string, unknown>;\n /**\n * Opens the canvas editor's starting state editor; the rail State tool shows only when it\n * is set. Same ⚠️ as `onPolicyChange`: it MUST be referentially stable.\n */\n onOpenStartingState?: () => void;\n /**\n * Opens one of this workflow's runs on the canvas (the History \"Open run\" path): the State\n * panel's link to the run its current state comes from. Same ⚠️: referentially stable.\n */\n onOpenRun?: (runId: string) => void;\n }\n | {\n kind: \"connection\";\n id: string;\n label?: string;\n /** Set by the connection ACTION page: the Code tool needs an action to show a snippet. */\n action?: string;\n /** Declared param keys of `action` (plain data — the registry keys on JSON). */\n params?: readonly SnippetInput[];\n }\n | null;\n\n/** Derived from {@link WorkspaceCallable}, never redeclared — the arm a\n * `RailTool.isAvailable`/route wrapper narrows on. */\nexport type WorkspaceKind = Exclude<WorkspaceCallable, null>[\"kind\"];\n\ninterface WorkspaceContextValue {\n resource: WorkspaceCallable;\n /** Publishes the OVERRIDE slot; `null` clears it, which restores the provider's `base`. */\n setCallable: (resource: WorkspaceCallable) => void;\n}\n\nconst WorkspaceContext = createContext<WorkspaceContextValue | null>(null);\n\n/**\n * Two layers: `base` (a prop — the host-owned `{kind, id}` a `<CallableWorkspace>` publishes) and\n * an override (what a mounted page publishes with `useWorkspace`). The override wins while it is\n * set; when its publisher unmounts it is cleared and the base is shown again — never empty. With no\n * `base` (Studio's layout, the editor's own nested provider) the behaviour is exactly the old\n * single-slot one: override or `null`.\n */\nexport function WorkspaceProvider({\n children,\n base = null,\n}: { children: ReactNode; base?: WorkspaceCallable }) {\n const [override, setCallable] = useState<WorkspaceCallable>(null);\n const resource = override ?? base;\n const value = useMemo(() => ({ resource, setCallable }), [resource]);\n return <WorkspaceContext.Provider value={value}>{children}</WorkspaceContext.Provider>;\n}\n\n/** Non-throwing probe: is there an enclosing {@link WorkspaceProvider}? */\nexport function useHasWorkspace(): boolean {\n return useContext(WorkspaceContext) !== null;\n}\n\n/** Publisher. Compute during render, effect-write, clear on unmount. */\nexport function useWorkspace(resource: WorkspaceCallable): void {\n const ctx = useContext(WorkspaceContext);\n if (!ctx) throw new Error(\"useWorkspace must be used within <WorkspaceProvider>\");\n const { setCallable } = ctx;\n // A stable serialization, not `resource` itself: a fresh object literal on\n // every render of the calling page (e.g. `{kind:\"workflow\", id}` rebuilt\n // each render) must not re-fire this effect every render — only a genuine\n // change to some field's VALUE should. T2.1.2: widened from a bespoke\n // `kind:id:label` template to a full `JSON.stringify` once the union grew\n // per-kind fields (`key`/`invokeUrl`/`invokeUrlByKey`/`urlForm`/`inputs`/\n // `triggers`) a caller can update after its first publish — e.g. the\n // Endpoint editor's id/key URL-form toggle or a picked tenant domain, both\n // of which change nothing about kind/id/label. A template keyed on\n // kind/id/label alone would miss those and leave `CodeTool`'s panel showing\n // the value from the FIRST render forever (same content -> same string ->\n // no re-fire, so this preserves the original's intent exactly, just over\n // every field instead of three of them).\n const key = resource ? JSON.stringify(resource) : \"\";\n // biome-ignore lint/correctness/useExhaustiveDependencies: keyed on the stable serialized `key`, not `resource`'s object identity — see the comment above.\n useEffect(() => {\n setCallable(resource);\n return () => setCallable(null);\n }, [key, setCallable]);\n}\n\n/** Reader — used by the rail and by every tool `Panel`. Throws outside the provider. */\nexport function useWorkspaceCallable(): WorkspaceCallable {\n const ctx = useContext(WorkspaceContext);\n if (!ctx) throw new Error(\"useWorkspaceCallable must be used within <WorkspaceProvider>\");\n return ctx.resource;\n}\n","import { restoreRailState } from \"@w6w/embed/lib\";\n/**\n * Third `.workspace` grid column: a 48px strip of the tools it is handed plus, when one is open,\n * its panel. Iterates `tools` with a single `.map` — never a per-tool JSX branch — so adding a\n * tool is a registry append in the host (Studio: `StudioRightRail`), nothing here changes.\n */\nimport { type ComponentType, useEffect, useState } from \"react\";\nimport { type WorkspaceCallable, useWorkspaceCallable } from \"./workspace.tsx\";\n\nexport interface RailTool {\n /** Stable; used as the persisted `activeTool`. */\n id: string;\n /** Strip tooltip + panel heading. */\n title: string;\n /** The strip glyph, as a component — built-in tools render a 16×16 `<Icon name=\"…\" />`\n * from `@w6w/ui`'s shared set; a tool may bring its own glyph instead. A component,\n * not an `IconName`, so this seam never narrows to the shared set. */\n Icon: ComponentType;\n isAvailable(ctx: WorkspaceCallable): boolean;\n /** Panel renders its own heading when it includes section actions. */\n rendersHeading?: boolean;\n /** Absent for an action tool: one with `onActivate` opens nothing in the rail. */\n Panel?: ComponentType<{ ctx: WorkspaceCallable }>;\n /** An action tool: the strip button calls this instead of toggling a panel (e.g. a modal). */\n onActivate?(ctx: WorkspaceCallable): void;\n /** A dot on the strip button: the tool has something set. */\n hasIndicator?(ctx: WorkspaceCallable): boolean;\n}\n\ninterface RailState {\n open: boolean;\n activeTool: string | null;\n}\n\nconst CLOSED: RailState = { open: false, activeTool: null };\n\n/**\n * T4.1.1/A2: every mount starts CLOSED, unconditionally — `open` is no\n * longer read out of storage at all (D-I0-2). `restoreRailState`\n * (`../lib/rail-settings.ts`) only ever returns `activeTool`; its return\n * type has no `open` member, so a pre-existing `{\"open\":true,…}` value\n * written before this task has nothing here to reopen the rail with.\n */\nfunction readStoredState(key: string): RailState {\n if (typeof localStorage === \"undefined\") return CLOSED;\n const raw = localStorage.getItem(key);\n const { activeTool } = restoreRailState(raw);\n return { open: false, activeTool };\n}\n\n/** Presentational: the strip + (when open) the active tool's panel. Shared by\n * the persisted and not-yet-persistable (pin 12) render paths below. */\nfunction RailShell({\n tools,\n ctx,\n state,\n onToggle,\n}: {\n tools: readonly RailTool[];\n ctx: WorkspaceCallable;\n state: RailState;\n onToggle: (id: string) => void;\n}) {\n const activeTool = state.open\n ? (tools.find((t) => t.id === state.activeTool && t.Panel) ?? null)\n : null;\n const ActivePanel = activeTool?.Panel;\n return (\n <aside className=\"right-rail\">\n <div className=\"right-rail-strip\">\n {tools.map((tool) => (\n <button\n key={tool.id}\n type=\"button\"\n data-testid={`rail-tool-${tool.id}`}\n className={`right-rail-tool-btn${activeTool?.id === tool.id ? \" active\" : \"\"}`}\n title={tool.title}\n aria-label={tool.title}\n aria-pressed={tool.onActivate ? undefined : activeTool?.id === tool.id}\n onClick={() => (tool.onActivate ? tool.onActivate(ctx) : onToggle(tool.id))}\n >\n <tool.Icon />\n {tool.hasIndicator?.(ctx) && (\n <span\n className=\"right-rail-tool-dot\"\n data-testid={`rail-tool-${tool.id}-dot`}\n aria-hidden=\"true\"\n />\n )}\n </button>\n ))}\n </div>\n {activeTool && ActivePanel && (\n <div className=\"right-rail-panel\" data-testid={`rail-panel-${activeTool.id}`}>\n {!activeTool.rendersHeading && (\n <div className=\"right-rail-panel-head\">\n <h3>{activeTool.title}</h3>\n </div>\n )}\n <ActivePanel ctx={ctx} />\n </div>\n )}\n </aside>\n );\n}\n\n/** Owns the persisted open/activeTool state. Split out from `RightRail` and\n * `key`ed on `storageKey` (pin 11/12): `currentProject` resolves from a\n * query, so a `useState` initializer that ran before it resolved would read\n * `w6w.rail.undefined.undefined`. `RightRail` renders this component only\n * once `storageKey` is non-null, and `key={storageKey}` forces a fresh\n * mount — and so a fresh synchronous read of the RESOLVED key — whenever the\n * account/project changes. */\nfunction PersistedRail({\n storageKey,\n tools,\n ctx,\n}: {\n storageKey: string;\n tools: readonly RailTool[];\n ctx: WorkspaceCallable;\n}) {\n const [state, setState] = useState<RailState>(() => readStoredState(storageKey));\n\n // A2: only `activeTool` is ever persisted — `open` is never written to\n // storage (D-I0-2), so a fresh mount always starts closed regardless of\n // whether the rail happened to be open when the tab last closed.\n useEffect(() => {\n if (typeof localStorage === \"undefined\") return;\n localStorage.setItem(storageKey, JSON.stringify({ activeTool: state.activeTool }));\n }, [storageKey, state.activeTool]);\n\n function onToggle(id: string) {\n setState((prev) =>\n prev.open && prev.activeTool === id\n ? { open: false, activeTool: id }\n : { open: true, activeTool: id },\n );\n }\n\n return <RailShell tools={tools} ctx={ctx} state={state} onToggle={onToggle} />;\n}\n\n/** `storageKey === null`: no key to persist under yet (pin 12) — the strip renders closed and\n * nothing is written to localStorage. No available tool ⇒ no rail element at all (C/D-C3). */\nexport function RightRail({\n tools,\n storageKey,\n}: {\n tools: readonly RailTool[];\n storageKey: string | null;\n}) {\n const ctx = useWorkspaceCallable();\n const available = tools.filter((t) => t.isAvailable(ctx));\n if (available.length === 0) return null;\n if (storageKey === null) {\n return <RailShell tools={available} ctx={ctx} state={CLOSED} onToggle={() => {}} />;\n }\n return <PersistedRail key={storageKey} storageKey={storageKey} tools={available} ctx={ctx} />;\n}\n","import { type ExpressionOptions, ExpressionOptionsProvider } from \"@w6w/ui\";\nimport type { ReactNode } from \"react\";\nimport { useMemo } from \"react\";\nimport { documentSampleValues, projectDocumentSources } from \"../lib/document-sources.ts\";\n/**\n * The APP-LEVEL contribution to the ƒx expression scope — the rail every\n * expression editor starts from (Studio binds `project` to its `ProjectContext`; an embedder\n * passes its own, `null` disabling the project-scoped queries), wherever it is opened.\n *\n * ## Why this is a provider and not a hook each page calls\n *\n * The scope used to travel as an `exprOptions` PROP: each page built the same\n * ~40-line object and handed it to the one or two components it happened to\n * think of. Two things went wrong with that, and both are user-visible:\n *\n * 1. **A field the prop had not reached opened an empty editor.** On a\n * Function's Implementation card, the `ƒx` toggle on a mapping row offered\n * no variables, no secrets and no inputs — while the very same editor,\n * reached through that card's \"Change\" button, offered all of them,\n * because only the modal had been wrapped in a provider.\n * 2. **Five pages carried a copy of the same object.** `FunctionsPage`,\n * `EndpointsPage`, `AliasesPage`, `WorkflowsPage` and the connection\n * tester each restated vars, secrets, documents, `sampleValues`,\n * `sealSecret`, `createVar` and `createSecret` — because the only way to\n * add one page-specific key (`inputs`) was to restate the rest alongside\n * it.\n *\n * Mounted ONCE, inside `ProjectProvider` and around `Layout`, this fixes both:\n * every route inherits it, and a page contributes only what is genuinely its\n * own by nesting a second `ExpressionOptionsProvider` (which LAYERS — see that\n * component's own doc). A page's `inputs` therefore cannot reach a sibling\n * route or a region above it; navigating away drops it with the subtree.\n *\n * ## What belongs here, and what does not\n *\n * Here: anything true for the whole **project** — its variables, its secret\n * NAMES, its document keys, the sample values the Result pane previews against,\n * and the three host callbacks the picker's \"+ Add\"/seal affordances need.\n *\n * Not here: anything that is only true inside one editor. A Function's declared\n * `inputs`, an Endpoint's declared `input`, the upstream `steps` leading to one\n * workflow node — those are contributed by the page or the region that knows\n * about them, and must not be visible anywhere else.\n *\n * `ui` components stay pure (they never fetch): this is the host side, and only\n * names/refs cross the boundary — secret plaintext never reaches the client.\n */\nimport {\n useConstantsQuery,\n useCreateSecretMutation,\n useCreateVarMutation,\n useDocumentsQuery,\n useSealSecret,\n useSecretsQuery,\n useVarsQuery,\n} from \"../repos/index.ts\";\n\n/**\n * The current project's expression sources, as an `ExpressionOptions`.\n *\n * Exported because a surface that renders OUTSIDE `ProjectExpressionScope` —\n * or one that needs the values themselves rather than the context — can still\n * build the same object. Inside the scope, prefer inheriting it.\n */\nexport function useProjectExpressionOptions(project: string | null): ExpressionOptions {\n const projectId = project;\n\n // Vars/secrets are subject-scoped (no project param on the secret list); the\n // vault list is masked name-only summaries, so nothing secret reaches the\n // client. Documents are project-scoped.\n const varsQuery = useVarsQuery(projectId ?? undefined, projectId != null);\n const secretsQuery = useSecretsQuery();\n const constantsQuery = useConstantsQuery();\n const documentsQuery = useDocumentsQuery(projectId ?? undefined, projectId != null);\n const sealSecretFn = useSealSecret();\n // \"+ Add\" (T1.2.4): both mutations already invalidate the exact key their\n // `useQuery` reads (repos/vars.ts, repos/vault.ts), so a create's success\n // alone refreshes the rail — no refetch(), no local list state.\n const createVarMut = useCreateVarMutation();\n const createSecretMut = useCreateSecretMutation();\n\n return useMemo(\n () => ({\n vars: (varsQuery.data ?? []).map((v) => v.name),\n constants: (constantsQuery.data ?? []).map((c) => c.name),\n secrets: (secretsQuery.data ?? []).map((s) => s.name),\n // `document-sources.ts` owns the `format === \"json\"` gate and the raw\n // field enumeration — no parsing, no gate logic, and no filtering here\n // (A5c); `isRefSafeKey` filtering happens once, downstream, at the\n // modal's render site.\n documents: projectDocumentSources(documentsQuery.data ?? []),\n // Real project values so the ƒx Result preview substitutes them for\n // `var.<name>` / `const.<name>` / `documents.<key>` / `documents.<key>.<field>` refs\n // instead of the raw template.\n sampleValues: {\n ...Object.fromEntries((varsQuery.data ?? []).map((v) => [`var.${v.name}`, v.value])),\n ...Object.fromEntries((constantsQuery.data ?? []).map((c) => [`const.${c.name}`, c.value])),\n ...documentSampleValues(documentsQuery.data ?? []),\n },\n sealSecret: sealSecretFn,\n // A created var carries the SAME project the read above carried (B3) —\n // it must land in the project whose rail asked for it. `type: \"string\"`\n // is pinned (a string type's `raw` passes through untouched) — the modal\n // has no type field.\n createVar: (input: { name: string; value: string; description?: string }) =>\n createVarMut\n .mutateAsync({\n input: {\n name: input.name,\n type: \"string\",\n value: input.value,\n description: input.description,\n },\n project: projectId ?? undefined,\n })\n .then(() => undefined),\n // Secrets carry NO project (B4) — `vault_secrets` has no `project`\n // column and the routes read no `?project=`. Plaintext in, the server\n // encrypts; the resolved value is referenced nowhere (B5).\n createSecret: (input: { name: string; value: string; description?: string }) =>\n createSecretMut\n .mutateAsync({ name: input.name, value: input.value, description: input.description })\n .then(() => undefined),\n }),\n [\n varsQuery.data,\n constantsQuery.data,\n secretsQuery.data,\n documentsQuery.data,\n sealSecretFn,\n createVarMut.mutateAsync,\n createSecretMut.mutateAsync,\n projectId,\n ],\n );\n}\n\n/**\n * Provide the current project's expression sources to every route below.\n *\n * Mount once, inside `ProjectProvider` (it reads the active project) and around\n * `Layout` (so every page inherits). It contributes no `inputs` and no `steps`\n * on purpose — see the module doc.\n */\nexport function ProjectExpressionScope({\n project,\n children,\n}: {\n project: string | null;\n children: ReactNode;\n}) {\n const options = useProjectExpressionOptions(project);\n return <ExpressionOptionsProvider value={options}>{children}</ExpressionOptionsProvider>;\n}\n","import { Icon } from \"@w6w/ui\";\nimport { useState } from \"react\";\nimport {\n CallFromCodeBody,\n type SnippetTabId,\n snippetTabsFor,\n} from \"../chrome/CallFromCodeButton.tsx\";\nimport { Modal } from \"../chrome/Modal.tsx\";\nimport type { RailTool } from \"../chrome/RightRail.tsx\";\nimport type { WorkspaceCallable } from \"../chrome/workspace.tsx\";\nimport { isAvailable, toSnippetCallable } from \"../lib/code-rail.ts\";\nimport { unavailableReason } from \"../lib/sdk-snippets.ts\";\n/**\n * The Code tool — the right rail's second registered client of T3.1.1's\n * registry seam (`src/ui/railTools.ts`), and T2.1.2's \"use code\" move: the\n * page-header \"Call from code\" button on Functions/Endpoints/Workflow-detail/\n * the flow-editor canvas becomes this strip icon + panel instead.\n *\n * The two pure decisions — is a snippet meaningful for this context, and\n * what `SnippetCallable` it converts to — live in `./../lib/code-rail.ts` so\n * `node --test` can gate them. This module owns presentation only.\n *\n * The panel is a LANGUAGE PICKER, not a snippet. It used to render\n * `CallFromCodeBody` inline, and a snippet is not readable in a ~395px\n * column: it scrolled sideways, and wrapping it (the first fix) turned the\n * CLI snippet's deliberate `\\`-continuations into what reads as separate\n * commands. Both are symptoms of the same thing — the snippet needs width the\n * rail does not have.\n *\n * So the rail shows one icon per language the resource can be called in, and\n * each opens the full-width modal ALREADY ON THAT LANGUAGE: one click to the\n * thing you came for, rather than open-then-hunt-for-the-tab. The set of\n * languages comes from `snippetTabsFor`, the same filter the modal's own tab\n * strip applies, so the rail can never offer a language the modal would not.\n */\n\nfunction CodePanel({ ctx }: { ctx: WorkspaceCallable }) {\n // Which language the modal opens on, or `null` for closed. ONE piece of\n // state, not an `open` flag beside a `tab`: the two can never disagree, and\n // \"closed\" cannot carry a stale language into the next open.\n const [openTab, setOpenTab] = useState<SnippetTabId | null>(null);\n const snippetCallable = toSnippetCallable(ctx);\n // Defensive: `isAvailable` already keeps this tool off the strip for a\n // `ctx` this can't build a snippet for — mirrors `SettingsTool.tsx`'s own\n // note about `Panel` still needing to handle a ctx `isAvailable` would\n // have excluded (a persisted `activeTool` plus an in-app transition to a\n // non-publishing route can still render this Panel).\n if (!snippetCallable) return null;\n const triggers = ctx?.kind === \"workflow\" ? ctx.triggers : undefined;\n const tabs = snippetTabsFor(snippetCallable);\n\n // No languages means no snippet at all — say why, rather than draw an empty\n // row of icons. Same sentence the body itself would have shown.\n if (tabs.length === 0) return <p className=\"muted\">{unavailableReason(snippetCallable)}</p>;\n\n return (\n <div>\n {/* A LANGUAGE PICKER, not a snippet.\n\n The rail's panel is ~395px wide, and a snippet rendered into it was\n unreadable at that width — first because it scrolled sideways, then,\n once wrapped, because a wrapped shell command reads as two commands.\n Neither is fixable in 395px: the snippet needs the room.\n\n So the panel stops trying to show one. It shows the languages this\n resource can be called in, and each opens the full-width modal\n ALREADY ON THAT LANGUAGE — one click to the thing you came for,\n instead of open-then-hunt-for-the-tab. The languages come from\n `snippetTabsFor`, so a resource with no public URL simply has no curl\n icon rather than an icon that opens an empty tab.\n\n Still not the double-chrome `CallFromCodeButton.tsx`'s header warns\n about: that trap was wrapping the rail's own panel in a modal by\n DEFAULT. The panel is its own content here; the modal is opt-in. */}\n <p className=\"muted small\" style={{ marginTop: 0 }}>\n Call this from:\n </p>\n <div className=\"rail-code-langs\">\n {tabs.map(({ id, label, icon }) => (\n <button\n key={id}\n type=\"button\"\n className=\"rail-code-lang\"\n data-testid={`rail-code-lang-${id}`}\n title={`Show the ${label} snippet`}\n aria-label={`Show the ${label} snippet`}\n onClick={() => setOpenTab(id)}\n >\n <Icon name={icon} size={20} />\n <span>{label}</span>\n </button>\n ))}\n </div>\n\n {/* Conditionally rendered, so each open MOUNTS the body afresh and\n `initialTab` seeds it again — picking Python, closing, then picking\n Node lands on Node. A body kept mounted would keep the first pick. */}\n {openTab !== null && (\n <Modal title=\"Call from code\" wide onClose={() => setOpenTab(null)}>\n <div style={{ height: 450 }}>\n <CallFromCodeBody resource={snippetCallable} triggers={triggers} initialTab={openTab} />\n </div>\n </Modal>\n )}\n </div>\n );\n}\n\nfunction CodeToolIcon() {\n return <Icon name=\"code\" />;\n}\n\nexport const codeTool: RailTool = {\n id: \"code\",\n title: \"Code\",\n Icon: CodeToolIcon,\n isAvailable: (ctx) => isAvailable(ctx),\n Panel: CodePanel,\n};\n","import { Icon } from \"@w6w/ui\";\nimport { WorkflowConnectionsPanel } from \"@w6w/ui/flow\";\nimport type { RailTool } from \"../chrome/RightRail.tsx\";\n\nexport const connectionsTool: RailTool = {\n id: \"connections\",\n title: \"Connections\",\n rendersHeading: true,\n Icon: () => <Icon name=\"plug\" />,\n isAvailable: (ctx) => ctx?.kind === \"workflow\" && !!ctx.connectionResources,\n hasIndicator: (ctx) =>\n ctx?.kind === \"workflow\" && Object.keys(ctx.connectionResources?.connections ?? {}).length > 0,\n Panel: ({ ctx }) =>\n ctx?.kind === \"workflow\" && ctx.connectionResources ? (\n <WorkflowConnectionsPanel key={ctx.id} resources={ctx.connectionResources} />\n ) : null,\n};\n","/**\n * The rail's host environment — the two things a rail tool needs from the host that it cannot\n * own: which project the surface is looking at, and how to move the host somewhere after a\n * rail action (archive / delete land on the list; an import opens the imported row).\n *\n * Studio binds both to its router and `ProjectContext`; an embedder binds them to its own. A\n * rail tool never imports a router: it calls `onNavigate` with a target and the host decides what\n * that means. The default (no provider mounted) is inert — no project, navigation ignored — so a\n * tool rendered outside a provider cannot save into the wrong project or throw.\n *\n * `project` is passed through to every write VERBATIM; `null` means \"no project\", on which the\n * package hooks refuse to save (never a fallback to the account default, C/D-C2).\n */\nimport { type ReactNode, createContext, useContext } from \"react\";\nimport type { SpecImportKind } from \"../lib/spec-import-invalidation.ts\";\n\n/** Where the host should go after a rail action. */\nexport type RailNavigation =\n | { type: \"list\" }\n | { type: \"imported\"; kind: SpecImportKind; id: string };\n\nexport interface RailEnv {\n project: string | null;\n onNavigate(to: RailNavigation): void;\n}\n\nconst DEFAULT_ENV: RailEnv = { project: null, onNavigate: () => {} };\n\nconst RailEnvContext = createContext<RailEnv>(DEFAULT_ENV);\n\nexport function RailEnvProvider({\n project,\n onNavigate,\n children,\n}: RailEnv & { children: ReactNode }) {\n return (\n <RailEnvContext.Provider value={{ project, onNavigate }}>{children}</RailEnvContext.Provider>\n );\n}\n\nexport function useRailEnv(): RailEnv {\n return useContext(RailEnvContext);\n}\n","import { ApiError } from \"@w6w/sdk\";\n/**\n * The Error handling tool — the right rail's tool for choosing **what runs when a call fails**.\n *\n * It is a BUTTON, not a form. Clicking it opens the F-2.0 picker modal (`StepBuilderModal`) with\n * its Functions and Workflows tabs, and the pick becomes the resource's `reroute.target`. All\n * three handler shapes are offered: an app Action, a Function, or a Workflow.\n *\n * This module owns two things:\n * - `ErrorHandlerSection` — the shared body (picker, handler label lookup, self-decision,\n * retry / reroute fields and the inline error). It calls no definition query and no save\n * mutation: the caller hands in the `policy` it read and an `onPersist` that writes.\n * - `errorHandlingTool` — the registry entry for all three kinds. A Workflow, and a Function /\n * Endpoint whose editor published `ctx.onPolicyChange`, hand the policy back to the surface\n * that owns the definition buffer, which folds it into the JSON it is already saving (the\n * rail makes zero writes — racing an editor's own save is not an option, see\n * `lib/settings-rail.ts`'s `isAvailable`). A Function / Endpoint with NO published writer\n * reads the cached record (`callableRecord`) and read-modify-writes the whole definition\n * (`definitionWithPolicy`) through the guarded save with that record's `updatedAt`.\n *\n * For a Workflow this is the handler for the RUN AS A WHOLE (core Workflow RFC — *Amendment —\n * 2026-08-21: the run-level error handler*), which is a different question from a step's own\n * `onError` on the canvas and from an `Edge.when: \"error\"`. `retry` IS authored here, through\n * `@w6w/ui`'s `RetryPolicyFields` (core Workflow RFC R-2, \"one retry shape everywhere\").\n */\nimport { type BuiltStep, Icon, RetryPolicyFields, StepBuilderModal } from \"@w6w/ui\";\nimport { useEffect, useState } from \"react\";\nimport type { RailTool } from \"../chrome/RightRail.tsx\";\nimport type { WorkspaceCallable } from \"../chrome/workspace.tsx\";\nimport { callableRecord } from \"../lib/callable-record.ts\";\nimport { errorHandlerSelfDecision } from \"../lib/error-handler-self.ts\";\nimport {\n type CallablePolicy,\n isAvailable as isSettingsRailAvailable,\n policyFromDefinition,\n} from \"../lib/settings-rail.ts\";\nimport { definitionWithPolicy } from \"../lib/settings-rail.ts\";\nimport { useEndpointQuery, useGuardedSaveEndpointMutation } from \"../repos/endpoints.ts\";\nimport {\n useFunctionQuery,\n useFunctionsQuery,\n useGuardedSaveFunctionMutation,\n} from \"../repos/functions.ts\";\nimport { useWorkflowsQuery } from \"../repos/workflows.ts\";\nimport { useRailEnv } from \"./rail-env.tsx\";\n\n/**\n * `@w6w/ui/flow`'s `CALL_APP`, restated: a VALUE import from the flow subpath would put the whole\n * canvas on the editor's eager path (the editor loads it with a dynamic `import()` only). A test\n * (`workflow-editor.test.ts`) pins the two spellings equal.\n */\nexport const CALL_APP = \"@w6w/call\";\n\ntype ErrorHandlerTarget = NonNullable<NonNullable<CallablePolicy[\"reroute\"]>[\"target\"]>;\n\nexport type ErrorHandlerKind = \"function\" | \"endpoint\" | \"workflow\";\n\n/** The id a handler target names, whichever of the three arms it is. */\nfunction refOf(target: ErrorHandlerTarget | undefined): string {\n if (!target) return \"\";\n if (target.kind === \"workflow\") return target.workflow;\n if (target.kind === \"function\") return target.function;\n return `${target.uses.app}/${target.uses.action}`;\n}\n\n/** The noun shown under a bound handler. */\nfunction nounOf(target: ErrorHandlerTarget | undefined): string {\n if (target?.kind === \"workflow\") return \"Workflow (asynchronous)\";\n if (target?.kind === \"function\") return \"Function (synchronous)\";\n return \"App action (synchronous)\";\n}\n\nexport interface ErrorHandlerSectionProps {\n kind: ErrorHandlerKind;\n id: string;\n /** The policy as currently stored (already read off the definition or buffer). */\n policy: CallablePolicy;\n /** The definition (or buffer) the policy was read from is present. */\n ready: boolean;\n saving: boolean;\n /** Write a whole new policy. `onError` shows a refusal inline. */\n onPersist(next: CallablePolicy, onError: (message: string) => void): void;\n}\n\nexport function ErrorHandlerSection({\n kind,\n id,\n policy,\n ready,\n saving,\n onPersist,\n}: ErrorHandlerSectionProps) {\n // Name the bound handler rather than showing a bare id. Both lists are already cached by the\n // picker itself, so this costs no extra round-trip in the common case.\n const functionsQuery = useFunctionsQuery(true);\n // The editor's project (RailEnv, as the Settings tool reads it), never the provider's default:\n // a project-less list would go out as the provider's project, not the one being edited.\n const { project } = useRailEnv();\n const workflowsQuery = useWorkflowsQuery(project ?? undefined, true);\n\n const [pickerOpen, setPickerOpen] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const target = policy.reroute?.target;\n const ref = refOf(target);\n const selfDecision = target\n ? errorHandlerSelfDecision({\n resource: { kind, id },\n target: { kind: target.kind, id: ref },\n hasAdapter: policy.reroute?.with !== undefined,\n })\n : \"allow\";\n const label =\n target?.kind === \"workflow\"\n ? (workflowsQuery.data?.find((w) => w.id === ref)?.displayName ?? undefined)\n : (() => {\n const fn = functionsQuery.data?.find((f) => f.id === ref);\n return fn ? fn.displayName || fn.key : undefined;\n })();\n\n // The rail remains mounted while its resource changes. A refusal belonging to the previous\n // resource must not obscure the current policy.\n useEffect(() => {\n if (id && kind) setError(null);\n }, [id, kind]);\n\n /** Persist a whole new policy — the one write path, shared by pick and clear. */\n function persist(next: CallablePolicy) {\n setError(null);\n onPersist(next, setError);\n }\n\n /**\n * The picker's `onAdd`. Two shapes reach here, because all three handler arms are offered:\n * - a callable → `{ uses: {app: \"@w6w/call\", …}, with: {targetKind, targetId} }`\n * - an action → `{ uses: {app, action, connection}, with }`\n * A graph-only internal node (`@w6w/script`, `@w6w/control`, …) is refused — `appsOnly` means no\n * such tab is rendered, but a `BuiltStep` is a wide type and a silent mis-write would be\n * invisible.\n */\n function pickHandler(built: BuiltStep) {\n let nextTarget: ErrorHandlerTarget;\n if (built.uses.app === CALL_APP) {\n const w = (built.with ?? {}) as { targetKind?: unknown; targetId?: unknown };\n const nextId = typeof w.targetId === \"string\" ? w.targetId : \"\";\n if (!nextId) return;\n nextTarget =\n w.targetKind === \"workflow\"\n ? { kind: \"workflow\", workflow: nextId }\n : { kind: \"function\", function: nextId };\n } else if (!built.uses.app.startsWith(\"@w6w/\")) {\n // The app arm. `with` is the action's own param map, straight from the picker's Configure\n // stage — it is `ActionTarget.with`, which `error-handler.ts` reads in preference to the\n // general `reroute.with`.\n nextTarget = {\n kind: \"action\",\n uses: {\n app: built.uses.app,\n action: built.uses.action,\n connection: built.uses.connection ?? undefined,\n },\n ...(built.with ? { with: built.with } : {}),\n };\n } else {\n return;\n }\n const nextDecision = errorHandlerSelfDecision({\n resource: { kind, id },\n target: { kind: nextTarget.kind, id: refOf(nextTarget) },\n hasAdapter: policy.reroute?.with !== undefined,\n });\n if (nextDecision === \"block\") {\n setError(\n \"This handler would call itself with the same inputs and can loop forever. Choose another handler or keep a differing imported adapter.\",\n );\n setPickerOpen(false);\n return;\n }\n // Preserve `reroute.with` if one was already authored elsewhere — this tool changes WHICH\n // handler runs, never the mapping onto it.\n persist({ ...policy, reroute: { ...policy.reroute, target: nextTarget } });\n setPickerOpen(false);\n }\n\n if (!ready && !saving) {\n return <p className=\"muted small\">Loading…</p>;\n }\n\n return (\n <div className=\"w6w-stack\" data-testid=\"rail-errorhandling-body\">\n {/* Retries run BEFORE the handler below, so the section renders first. */}\n <section data-testid=\"rail-retry-section\">\n <RetryPolicyFields\n value={policy.retry}\n onChange={(next) => persist({ ...policy, retry: next })}\n readOnly={saving}\n target={kind}\n />\n {kind === \"workflow\" && (\n <p className=\"muted small\" data-testid=\"rail-retry-run-warning\">\n Retrying re-runs the whole workflow from its first step, so steps that already succeeded\n run again. For a step that must not repeat (a send or a charge), set retry on that step\n instead.\n </p>\n )}\n </section>\n\n <p className=\"muted small\">\n {kind === \"workflow\"\n ? \"What runs when this workflow's run fails, after every node's own retry is spent.\"\n : \"What runs when this call fails, after retry (if any) is exhausted.\"}\n </p>\n\n {ref ? (\n <div className=\"row\" style={{ alignItems: \"center\", gap: 8 }}>\n <span className=\"list-main\">\n <strong>{label ?? ref}</strong> <code className=\"muted\">{ref}</code>\n <span className=\"muted small block\">{nounOf(target)}</span>\n </span>\n <button\n type=\"button\"\n className=\"btn ghost\"\n data-testid=\"rail-errorhandling-change\"\n disabled={saving}\n onClick={() => setPickerOpen(true)}\n >\n Change\n </button>\n </div>\n ) : (\n <button\n type=\"button\"\n className=\"btn\"\n data-testid=\"rail-errorhandling-choose\"\n disabled={saving}\n onClick={() => setPickerOpen(true)}\n >\n + Choose what runs on failure\n </button>\n )}\n\n {ref && (\n <button\n type=\"button\"\n className=\"btn ghost\"\n data-testid=\"rail-errorhandling-clear\"\n disabled={saving}\n onClick={() => persist({ ...policy, reroute: undefined })}\n >\n Remove handler\n </button>\n )}\n\n {selfDecision === \"warn\" && (\n <div className=\"result error\" data-testid=\"rail-errorhandling-self-caution\">\n This handler targets itself. Its imported input adapter is preserved; the server will\n refuse it if it resolves to the failed call's same inputs.\n </div>\n )}\n\n {error && (\n <div className=\"error\" data-testid=\"rail-errorhandling-error\">\n {error}\n </div>\n )}\n\n {pickerOpen && (\n <StepBuilderModal\n appsOnly\n callables={[\"function\", \"workflow\"] as const}\n title=\"Choose what runs on failure\"\n onClose={() => setPickerOpen(false)}\n onAdd={pickHandler}\n />\n )}\n </div>\n );\n}\n\n/**\n * The buffer arm: policy read off the host's buffer (`ctx.policy`), written back through\n * `ctx.onPolicyChange`. A workflow's only arm; a function / endpoint's when an editor owns the\n * buffer.\n */\nfunction BufferErrorHandlingPanel({ ctx }: { ctx: Exclude<WorkspaceCallable, null> }) {\n const policy = \"policy\" in ctx ? ctx.policy : undefined;\n const onPolicyChange = \"onPolicyChange\" in ctx ? ctx.onPolicyChange : undefined;\n return (\n <ErrorHandlerSection\n kind={ctx.kind as ErrorHandlerKind}\n id={ctx.id}\n policy={policy ? policyFromDefinition(policy) : {}}\n ready={Boolean(onPolicyChange)}\n saving={false}\n onPersist={(next) => onPolicyChange?.(next)}\n />\n );\n}\n\n/** The cache arm: a function / endpoint with no published writer saves from the cached record. */\nfunction CachedErrorHandlingPanel({ id, kind }: { id: string; kind: \"function\" | \"endpoint\" }) {\n const fnQuery = useFunctionQuery(id, kind === \"function\");\n const epQuery = useEndpointQuery(id, kind === \"endpoint\");\n const saveFnMut = useGuardedSaveFunctionMutation();\n const saveEpMut = useGuardedSaveEndpointMutation();\n\n const record = callableRecord(kind, kind === \"function\" ? fnQuery.data : epQuery.data);\n const saving = kind === \"function\" ? saveFnMut.isPending : saveEpMut.isPending;\n\n return (\n <ErrorHandlerSection\n kind={kind}\n id={id}\n policy={record ? policyFromDefinition(record.definition) : {}}\n ready={Boolean(record)}\n saving={saving}\n onPersist={(next, onError) => {\n if (!record) return;\n const vars = {\n definition: definitionWithPolicy(record.definition, next),\n ifUnmodifiedSince: record.updatedAt,\n };\n const settled = {\n onError: (e: unknown) => onError(e instanceof ApiError ? e.message : String(e)),\n };\n if (kind === \"function\") saveFnMut.mutate(vars, settled);\n else saveEpMut.mutate(vars, settled);\n }}\n />\n );\n}\n\nfunction ErrorHandlingPanel({ ctx }: { ctx: WorkspaceCallable }) {\n // Defensive: a persisted `activeTool` can render this Panel with a ctx this tool has no handler\n // for.\n if (ctx?.kind !== \"workflow\" && ctx?.kind !== \"function\" && ctx?.kind !== \"endpoint\") {\n return null;\n }\n if (ctx.kind === \"workflow\" || typeof ctx.onPolicyChange === \"function\") {\n return <BufferErrorHandlingPanel ctx={ctx} />;\n }\n return <CachedErrorHandlingPanel id={ctx.id} kind={ctx.kind} />;\n}\n\nfunction ErrorHandlingToolIcon() {\n return <Icon name=\"warning\" />;\n}\n\nexport const errorHandlingTool: RailTool = {\n id: \"error-handling\",\n title: \"Error handling\",\n Icon: ErrorHandlingToolIcon,\n isAvailable: (ctx) => isSettingsRailAvailable(ctx),\n Panel: ErrorHandlingPanel,\n};\n","import { Icon } from \"@w6w/ui\";\nimport type { RailTool } from \"../chrome/RightRail.tsx\";\n\nexport const historyTool: RailTool = {\n id: \"history\",\n title: \"Execution history\",\n Icon: () => <Icon name=\"history\" />,\n isAvailable: (ctx) => ctx?.kind === \"workflow\" && !!ctx.onOpenHistory,\n onActivate: (ctx) => {\n if (ctx?.kind === \"workflow\") ctx.onOpenHistory?.();\n },\n};\n","/**\n * Pure decision logic behind `../components/TagEditor.tsx` — kept out of the\n * component so `node --test` can exercise it directly\n * (`__tests__/tag-editor.test.ts`) without touching React, mirroring\n * `alias-rail.ts`/`rail-settings.ts`'s own split. Carries over the retiring\n * `WorkflowsPage.tsx`'s retired tags-editing modal's data contract verbatim:\n * `string[]`, trim, dedupe-on-add, drop empties.\n */\n\n/**\n * Applies a chip input's freeform text to the committed tag list. Called on\n * every change to the trailing, not-yet-committed input — `typed` is always\n * the FULL current value of just that one input, which resets to `\"\"` after\n * a commit, so a single keystroke never carries more than the one character\n * just typed.\n *\n * A comma anywhere in `typed` is the commit signal: every comma-delimited\n * segment is trimmed and, if non-empty and not already present, appended as\n * a chip — in order, regardless of whether it sits before or after the last\n * comma. That is what makes both shapes work from the one rule: typing\n * `\"alpha,\"` one character at a time commits `\"alpha\"` the moment the comma\n * lands, and pasting `\"a,b,c\"` in one go (no trailing comma at all) still\n * commits all three, because nothing here treats \"the last segment\" as\n * special. The returned `typed` is always `\"\"` once a comma triggered a\n * commit. With no comma present at all, nothing commits and `typed` passes\n * through unchanged, so the caller can just store it as the next draft.\n */\nexport function commitTag(tags: string[], typed: string): { tags: string[]; typed: string } {\n if (!typed.includes(\",\")) return { tags, typed };\n let next = tags;\n for (const raw of typed.split(\",\")) {\n const t = raw.trim();\n if (t && !next.includes(t)) next = [...next, t];\n }\n return { tags: next, typed: \"\" };\n}\n\n/**\n * Removes exactly one tag by VALUE, never by position — a list carrying both\n * a tag and a second tag that merely contains it as a prefix (`[\"ab\", \"b\"]`)\n * only ever loses the exact match.\n */\nexport function removeTag(tags: string[], tag: string): string[] {\n return tags.filter((t) => t !== tag);\n}\n","import { IconButton } from \"@w6w/ui\";\nimport { useState } from \"react\";\nimport { commitTag, removeTag } from \"../lib/tag-editor.ts\";\n\n/**\n * A chip input for a workflow's free-form tags: type text, `,` commits the\n * typed value as a chip (or paste a whole comma-separated list to commit\n * several at once — `../lib/tag-editor.ts`'s `commitTag`), each chip carries\n * an `×` to remove it, and a still-typable tail follows the chips — one\n * control, not a stacked input-above-list.\n *\n * Built fresh (T2.2.1) rather than extended from the retiring\n * `WorkflowsPage.tsx` tags-editing modal: that component was a submit-button\n * \"Add\" form with its own inline add/remove branching, a different\n * interaction shape from a comma-commits chip editor. The shared data\n * contract (trim, dedupe-on-add, drop empties) now lives in\n * `../lib/tag-editor.ts`'s\n * `commitTag`/`removeTag`, so this component holds no branching of its own —\n * it only calls them and renders the result. Controlled, mirroring\n * `InputListEditor.tsx`'s shape: the caller owns `tags`, this component owns\n * only the not-yet-committed typed tail.\n */\nexport interface TagEditorProps {\n tags: string[];\n onChange: (next: string[]) => void;\n}\n\nexport function TagEditor({ tags, onChange }: TagEditorProps) {\n const [typed, setTyped] = useState(\"\");\n\n function handleTypedChange(value: string) {\n const result = commitTag(tags, value);\n setTyped(result.typed);\n if (result.tags !== tags) onChange(result.tags);\n }\n\n return (\n <div className=\"tag-list\" data-testid=\"tag-editor\">\n {tags.map((t) => (\n <span key={t} className=\"tag removable\">\n {t}\n <IconButton\n danger\n icon=\"close\"\n label={`Remove tag ${t}`}\n title={`Remove ${t}`}\n onClick={() => onChange(removeTag(tags, t))}\n />\n </span>\n ))}\n <input\n type=\"text\"\n value={typed}\n placeholder=\"Add a tag…\"\n aria-label=\"New tag\"\n onChange={(e) => handleTypedChange(e.target.value)}\n />\n </div>\n );\n}\n","import { filterKeyInput, isEndpointKey } from \"@w6w/embed/lib\";\n/**\n * Unified settings modal for editing name, key, and tags (workflow only)\n * in a single dialog. Replaces separate Edit Key and Edit Tags modals.\n * Supports Function, Endpoint, and Workflow kinds.\n *\n * T4.2.1: every kind-shaped decision this component used to make inline — may\n * the key be typed at all, does this kind store tags, which placeholder goes in\n * which field — now comes from `CALLABLE_DESCRIPTORS[kind].settings`\n * (`lib/callable-descriptors.ts`). There is deliberately **no `kind ===` left in\n * this file**: a fourth kind, or a copy change, is an edit to the descriptor\n * table and to nothing else. The rendered output is byte-identical to before —\n * same labels, same placeholders, same hint sentence, same conditional Tags\n * section.\n */\nimport { descriptorFor } from \"@w6w/embed/repos\";\nimport { ApiError } from \"@w6w/sdk\";\nimport { useEnterSubmit } from \"@w6w/ui\";\nimport { useState } from \"react\";\nimport { Modal } from \"./Modal.tsx\";\nimport { TagEditor } from \"./TagEditor.tsx\";\n\ninterface CallableSettingsModalProps {\n kind: \"function\" | \"endpoint\" | \"workflow\";\n id: string;\n initial: {\n displayName: string;\n key: string | null;\n tags?: string[]; // workflow only\n };\n onSave: (data: {\n displayName: string;\n key: string | null;\n tags?: string[];\n }) => Promise<void>;\n onClose: () => void;\n}\n\nexport function CallableSettingsModal(props: CallableSettingsModalProps) {\n // The one kind lookup this component makes. `settings` then answers every\n // per-kind question below, including which of the three `initial` fields this\n // kind even has.\n const settings = descriptorFor(props.kind).settings;\n const { initial } = props;\n const [displayName, setDisplayName] = useState(initial.displayName);\n const [key, setKey] = useState(initial.key ?? \"\");\n const [tags, setTags] = useState<string[]>(initial.tags ?? []);\n const [isSaving, setIsSaving] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const displayNameChanged = displayName !== initial.displayName;\n const keyChanged = key !== (initial.key ?? \"\");\n const tagsChanged =\n settings.hasTags && JSON.stringify(tags) !== JSON.stringify(initial.tags ?? []);\n const isDirty = displayNameChanged || keyChanged || tagsChanged;\n\n // Key can be edited for function/workflow only (not endpoint)\n const canEditKey = settings.canEditKey;\n const keyGrammarOk = key === \"\" || isEndpointKey(key);\n const canSubmit = isDirty && keyGrammarOk && !isSaving;\n\n async function handleSave() {\n if (!canSubmit) return;\n setError(null);\n setIsSaving(true);\n try {\n await props.onSave({\n displayName: displayName.trim(),\n key: canEditKey && keyChanged ? key : initial.key,\n tags: settings.hasTags ? tags : undefined,\n });\n props.onClose();\n } catch (e) {\n setError(e instanceof ApiError ? e.message : String(e));\n } finally {\n setIsSaving(false);\n }\n }\n\n const enterSubmit = useEnterSubmit(handleSave, { enabled: canSubmit });\n\n return (\n <Modal title=\"Edit settings\" onClose={props.onClose}>\n <div className=\"modal-body\">\n <label className=\"field\">\n <span>Name</span>\n <input\n type=\"text\"\n value={displayName}\n onChange={(e) => setDisplayName(e.target.value)}\n placeholder={settings.namePlaceholder}\n autoFocus\n {...enterSubmit}\n />\n </label>\n\n {canEditKey && (\n <label className=\"field\">\n <span>Key</span>\n <input\n type=\"text\"\n value={key}\n onChange={(e) => setKey(filterKeyInput(e.target.value))}\n placeholder={settings.keyPlaceholder}\n {...enterSubmit}\n />\n <span className=\"muted small\">\n Lowercase, kebab-case, 3–39 characters.\n {settings.keyHintSuffix}\n </span>\n </label>\n )}\n\n {settings.hasTags && (\n <div>\n <p className=\"muted small\" style={{ marginBottom: \"8px\" }}>\n Tags\n </p>\n <TagEditor tags={tags} onChange={setTags} />\n </div>\n )}\n\n {error && <div className=\"error\">{error}</div>}\n </div>\n\n <div className=\"modal-actions\">\n <button type=\"button\" className=\"btn ghost\" onClick={props.onClose}>\n Cancel\n </button>\n <button type=\"button\" className=\"btn\" disabled={!canSubmit} onClick={handleSave}>\n {isSaving ? \"Saving…\" : \"Save\"}\n </button>\n </div>\n </Modal>\n );\n}\n","import {\n type VersionsKind,\n useInvokeVersionMutation,\n useRevertMutation,\n useVersionQuery,\n} from \"@w6w/embed/repos\";\nimport { ApiError } from \"@w6w/sdk\";\nimport { CodeBlock } from \"@w6w/ui\";\nimport { useState } from \"react\";\nimport { ConfirmModal } from \"./ConfirmModal.tsx\";\nimport { Modal } from \"./Modal.tsx\";\n\n/**\n * P2's `<collection>-version-*` testid scheme, spelled out literally per kind rather than built\n * by string interpolation — mirrors `ImportSpecModal.tsx`'s own `TESTIDS` reasoning: this file's\n * own kind arms stay the exact byte strings a page-guard suite would assert against, verifiable\n * by a plain substring search rather than only by running the browser suite.\n */\nconst TESTIDS: Record<\n VersionsKind,\n {\n json: string;\n error: string;\n revertButton: string;\n invokeButton: string;\n invokeJson: string;\n invokeError: string;\n }\n> = {\n function: {\n json: \"functions-version-json\",\n error: \"functions-version-error\",\n revertButton: \"functions-version-revert\",\n invokeButton: \"functions-version-invoke\",\n invokeJson: \"functions-version-invoke-json\",\n invokeError: \"functions-version-invoke-error\",\n },\n workflow: {\n json: \"workflows-version-json\",\n error: \"workflows-version-error\",\n revertButton: \"workflows-version-revert\",\n invokeButton: \"workflows-version-invoke\",\n invokeJson: \"workflows-version-invoke-json\",\n invokeError: \"workflows-version-invoke-error\",\n },\n endpoint: {\n json: \"endpoints-version-json\",\n error: \"endpoints-version-error\",\n revertButton: \"endpoints-version-revert\",\n invokeButton: \"endpoints-version-invoke\",\n invokeJson: \"endpoints-version-invoke-json\",\n invokeError: \"endpoints-version-invoke-error\",\n },\n};\n\n/**\n * Version viewer for Function/Workflow/Endpoint (T3.1.1, extended by T5.3.1): one\n * kind-parametrized component, mirroring `ImportSpecModal.tsx:12-46`'s established shape (a\n * `kind` prop plus per-kind `TESTIDS`, one component mounted from more than one place rather than\n * three near-copies). This project mounts it from `SettingsTool.tsx` only — the component\n * boundary exists so a second mount point later costs one line.\n *\n * Renders the version's own read-only definition through the same two primitives\n * `SettingsTool.tsx`'s existing Export modal already uses — the studio-local `Modal` and\n * `@w6w/ui`'s `CodeBlock` — plus, since T5.3.1, two live actions:\n *\n * - **\"Revert to this version\"** — confirmed via the studio-local `ConfirmModal` (P2-D4:\n * `./ConfirmModal.tsx`, never `@w6w/ui`'s), rendered as a SIBLING of `<Modal>` in\n * the returned fragment, never nested inside it. Overwrites the LIVE resource's `definition`\n * with this version's content, preserving its `key`/address (HITL-4's pinned default).\n * - **\"Invoke this version\"** — one click, NO confirm (ruling #12: an invoke is a call, not a\n * write to the resource, and the LIVE invoke action it mirrors carries no confirm either). Runs\n * this version's own archived definition, never the live one, and renders the response body\n * inline via `CodeBlock`, or a failure inline via the `ApiError` idiom (never a thrown error, a\n * blank modal, or a browser dialog).\n *\n * Both actions read `kind`/`id`/`versionNumber` from props, and both mutations are fresh\n * `useMutation` instances scoped to this component instance — since `SettingsTool.tsx`'s\n * `openVersion` gate fully unmounts/remounts this component per version rather than swapping\n * props on a surviving instance, any prior invoke result or error is gone the moment a different\n * version is opened.\n *\n * Amendments #5/#6 (project.md, Phase 2) supersede the earlier pin that made both of the above\n * out of scope (HITL-2's \"invocation always runs the live definition\"; Amendment #5's \"restore is\n * out of scope, not even a disabled button\").\n */\nexport function VersionHistoryModal(props: {\n kind: VersionsKind;\n id: string;\n versionNumber: number;\n onClose: () => void;\n /** Editor hosts serialize draft saves before restoring, then refresh their buffer. */\n onRestore?: (versionNumber: number) => Promise<void>;\n}) {\n const { kind, id, versionNumber } = props;\n const testids = TESTIDS[kind];\n // Always enabled: this component only ever mounts once a specific version has been picked\n // (the caller renders it conditionally), mirroring the Export modal's own \"mounted while open\"\n // gate rather than re-deriving a second `enabled` flag here.\n const versionQuery = useVersionQuery(kind, id, versionNumber, true);\n const revertMut = useRevertMutation(kind);\n const invokeMut = useInvokeVersionMutation(kind);\n const [confirmingRevert, setConfirmingRevert] = useState(false);\n const [restoreError, setRestoreError] = useState<string | null>(null);\n\n return (\n <>\n <Modal title={`Version ${versionNumber}`} onClose={props.onClose} wide>\n <div className=\"modal-body\">\n {versionQuery.isLoading ? (\n <p className=\"muted small\">Loading…</p>\n ) : versionQuery.isError ? (\n <div className=\"error\" data-testid={testids.error}>\n {versionQuery.error instanceof Error\n ? versionQuery.error.message\n : String(versionQuery.error)}\n </div>\n ) : versionQuery.data ? (\n <div data-testid={testids.json}>\n <CodeBlock\n code={JSON.stringify(versionQuery.data.definition, null, 2)}\n language=\"json\"\n maxHeight=\"420px\"\n copyable\n />\n </div>\n ) : null}\n\n {(restoreError || revertMut.isError) && (\n <div className=\"error\">{restoreError ?? String(revertMut.error)}</div>\n )}\n {invokeMut.data !== undefined && (\n <div data-testid={testids.invokeJson}>\n <CodeBlock\n code={JSON.stringify(invokeMut.data, null, 2)}\n language=\"json\"\n maxHeight=\"240px\"\n copyable\n />\n </div>\n )}\n {invokeMut.isError && (\n <div className=\"error\" data-testid={testids.invokeError}>\n {invokeMut.error instanceof ApiError\n ? invokeMut.error.message\n : String(invokeMut.error)}\n </div>\n )}\n </div>\n\n <div className=\"modal-actions\">\n <button\n type=\"button\"\n className=\"btn ghost\"\n data-testid={testids.invokeButton}\n disabled={invokeMut.isPending}\n onClick={() => invokeMut.mutate({ id, versionNumber })}\n >\n {invokeMut.isPending ? \"Invoking…\" : \"Invoke this version\"}\n </button>\n <button\n type=\"button\"\n className=\"btn danger\"\n data-testid={testids.revertButton}\n disabled={revertMut.isPending}\n onClick={() => setConfirmingRevert(true)}\n >\n {revertMut.isPending ? \"Reverting…\" : \"Revert to this version\"}\n </button>\n <button type=\"button\" className=\"btn ghost\" onClick={props.onClose}>\n Close\n </button>\n </div>\n </Modal>\n {confirmingRevert && (\n <ConfirmModal\n title=\"Revert to this version\"\n message={`Revert to version ${versionNumber}? This restores its content onto the resource's current draft; the resource's key and address stay unchanged.`}\n confirmLabel=\"Revert\"\n destructive\n onConfirm={() => {\n setConfirmingRevert(false);\n if (props.onRestore) {\n setRestoreError(null);\n void props\n .onRestore(versionNumber)\n .then(props.onClose, (e) => setRestoreError(String(e)));\n } else revertMut.mutate({ id, versionNumber });\n }}\n onClose={() => setConfirmingRevert(false)}\n />\n )}\n </>\n );\n}\n","/**\n * The rail Settings panel's bottom \"danger zone\" — Archive and optional direct\n * Delete, behind a visibly red confirmation panel — extracted\n * out of `src/ui/rail/SettingsTool.tsx` so Function, Endpoint and Workflow\n * render the EXACT same markup instead of three near-identical branches.\n * T1.3.1 had already moved all three kinds' Archive/Delete into one file, but\n * left them as three separate JSX arms that had drifted out of sync — only\n * Workflow's delete copy said the deletion was permanent (A5). This\n * extraction is what stops a fourth kind (or a future edit to one arm) from\n * silently reintroducing that gap: per-kind variance arrives entirely as\n * props. Callers opting into direct deletion handle the archive prerequisite.\n *\n * Presentational only, mirroring `@w6w/ui`'s own `DeleteButton` (HITL-1,\n * binding there): takes plain `onClick` callbacks, never an `onConfirm` and\n * never renders a confirm dialog itself — the caller (`SettingsTool.tsx`)\n * owns the `ConfirmModal`s and the archive/delete mutations, exactly as it\n * did before this extraction.\n *\n * A4: `DeleteButton`'s own `label` prop renders as `title`/`aria-label`\n * ONLY, never visible text (`packages/ui/src/components/IconButton.tsx`) —\n * so the visible word \"Delete\" here is this component's OWN sibling\n * `<span>`, not something passed through to `DeleteButton`.\n */\nimport { DeleteButton } from \"@w6w/ui\";\n\nexport interface DangerZoneProps {\n /** Archived resources offer Delete; other resources also offer Archive. */\n archived: boolean;\n /** Offer Delete before archiving when the caller handles both lifecycle operations. */\n allowDirectDelete?: boolean;\n pending?: boolean;\n /** Accessible name for the Delete icon button — `title`/`aria-label` only\n * (`IconButton.tsx`), e.g. \"Delete this function\". */\n deleteLabel: string;\n /** `data-testid` for the Delete control. Kind-specific — page guards key\n * on these directly (e.g. `delete-function`, `wf-settings-delete`). */\n deleteTestId: string;\n /** `data-testid` for the Archive control. Kind-specific. */\n archiveTestId: string;\n onRequestDelete: () => void;\n onRequestArchive: () => void;\n deleteError: string | null;\n archiveError: string | null;\n}\n\nexport function DangerZone(props: DangerZoneProps) {\n const {\n archived,\n deleteLabel,\n deleteTestId,\n archiveTestId,\n onRequestDelete,\n onRequestArchive,\n deleteError,\n archiveError,\n } = props;\n return (\n <div className=\"rail-danger-zone rail-danger-zone--panel\" data-testid=\"rail-danger-zone-panel\">\n <div className=\"rail-danger-zone-actions\">\n {!archived && (\n <button\n type=\"button\"\n className=\"btn danger\"\n data-testid={archiveTestId}\n onClick={onRequestArchive}\n disabled={props.pending}\n >\n Archive\n </button>\n )}\n {props.allowDirectDelete ? (\n <button\n type=\"button\"\n className=\"btn danger\"\n aria-label={deleteLabel}\n data-testid={deleteTestId}\n onClick={onRequestDelete}\n disabled={props.pending}\n >\n Delete\n </button>\n ) : archived ? (\n <span className=\"rail-danger-zone-delete\">\n <DeleteButton\n label={deleteLabel}\n data-testid={deleteTestId}\n onClick={onRequestDelete}\n disabled={props.pending}\n />\n <span>Delete</span>\n </span>\n ) : null}\n </div>\n {deleteError && (\n <div className=\"error\" data-testid=\"rail-delete-error\">\n {deleteError}\n </div>\n )}\n {archiveError && (\n <div className=\"error\" data-testid=\"rail-archive-error\">\n {archiveError}\n </div>\n )}\n </div>\n );\n}\n","/**\n * The presentational sections of the rail Settings panel, rendered by EVERY arm — the workflow\n * and function/endpoint arms in `./SettingsTool.tsx` — so the markup, test ids and copy exist\n * exactly once.\n *\n * Every section takes data and callbacks as props. There is no query or mutation hook in this\n * file: the arms own their data access (through `../repos/*`). `useState`-free too — open/close state lives in the arm, so a\n * section is a pure function of its props.\n *\n * Moved verbatim from the pre-split `SettingsPanel`: the `rail-meta` definition-list grid, the\n * version-history link + Publish/Enable block and its \"All versions\" list modal (kept as two\n * separate open states in the arm — see `SettingsTool.tsx`), the Export/Edit JSON/Import chooser\n * shell, and the Delete/Archive danger zone with its per-kind confirm copy.\n */\nimport { ConfirmModal, EditButton, Icon, IconButton } from \"@w6w/ui\";\nimport type { ReactNode } from \"react\";\nimport { DangerZone } from \"../chrome/DangerZone.tsx\";\nimport { Modal } from \"../chrome/Modal.tsx\";\nimport type { RailSettingsKind } from \"../lib/rail-settings.ts\";\nimport type { VersionSummary, VersionsEnvelope } from \"../repos/versions.ts\";\n\n/** The three kinds the Settings panel renders for. */\nexport type SettingsKind = Extract<RailSettingsKind, \"function\" | \"endpoint\" | \"workflow\">;\n\n/** Heading row: the title and the \"Edit settings\" trigger for the unified settings modal. */\nexport function SettingsHeading(props: { onEdit: () => void }) {\n return (\n <div className=\"right-rail-panel-head rail-settings-head\">\n <h3>Settings</h3>\n <EditButton label=\"Edit settings\" data-testid=\"rail-settings-edit\" onClick={props.onEdit} />\n </div>\n );\n}\n\n/**\n * id + key + updated (+ tags, workflow only) — and nothing else. No createdAt, ever. A two-column\n * label/value GRID (`dl`/`dt`/`dd`); `.rail-meta-list` is the rail-scoped grid and there is\n * deliberately no global `dl`/`dt`/`dd` rule.\n */\nexport function MetadataSection(props: {\n id: string;\n displayName: string;\n /** `metadataFieldsForKind(kind)`. */\n fields: ReadonlyArray<\"id\" | \"key\" | \"updatedAt\">;\n /** The already-cached list row (carries key/updatedAt); `undefined` until the list loads. */\n row: { key?: string | null; updatedAt: string } | undefined;\n /** Workflow only: the tag chips. `undefined` hides the row (function/endpoint). */\n tags?: readonly string[];\n}) {\n const { id, displayName, fields, row, tags } = props;\n return (\n <div className=\"rail-meta\">\n <div\n style={{\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"flex-start\",\n gap: \"8px\",\n }}\n >\n <dl className=\"rail-meta-list\">\n {displayName && (\n <>\n <dt>Name</dt>\n <dd data-testid=\"rail-meta-name\">\n <code>{displayName}</code>\n </dd>\n </>\n )}\n <dt>ID</dt>\n <dd data-testid=\"rail-meta-id\">\n <code>{id}</code>\n </dd>\n {fields.includes(\"key\") && row && (\n <>\n <dt>Key</dt>\n <dd data-testid=\"rail-meta-key\">\n <code>{row.key || \"unset\"}</code>\n </dd>\n </>\n )}\n {fields.includes(\"updatedAt\") && row && (\n <>\n <dt>Updated</dt>\n <dd data-testid=\"rail-meta-updated\" data-value={row.updatedAt}>\n {new Date(row.updatedAt).toLocaleString()}\n </dd>\n </>\n )}\n {tags !== undefined && row && (\n <>\n <dt>Tags</dt>\n <dd data-testid=\"rail-meta-tags\">\n {tags.length > 0\n ? tags.map((t) => (\n <span key={t} className=\"tag\">\n {t}\n </span>\n ))\n : \"No tags\"}\n </dd>\n </>\n )}\n </dl>\n </div>\n </div>\n );\n}\n\n/**\n * A5: one icon opens the combined Export/Edit JSON/Import chooser. Nothing here grows with the\n * size of the resource's definition — the definition renders in neither vessel here, only inside\n * a modal.\n */\nexport function SpecActionsTrigger(props: { onOpen: () => void }) {\n return (\n <div className=\"rail-spec-actions\">\n <IconButton\n icon=\"file-text\"\n label=\"Export, edit, or import\"\n data-testid=\"rail-spec-actions-open\"\n onClick={props.onOpen}\n />\n </div>\n );\n}\n\n/**\n * The chooser shell: Import always (it creates a NEW resource and navigates to it, never an\n * in-place replacement), plus a slot an arm fills with extra definition actions (the\n * function/endpoint arm adds Export + Edit JSON). Picking an item closes THIS modal and opens that\n * item's own — nothing is ever nested inside this one's body.\n */\nexport function SpecChooserModal(props: {\n kind: SettingsKind;\n /** Extra definition actions, rendered above the Import row. */\n children?: ReactNode;\n onImport: () => void;\n onClose: () => void;\n}) {\n const { kind, children, onImport, onClose } = props;\n return (\n <Modal title=\"Definition\" onClose={onClose}>\n <div className=\"modal-body\">\n {children}\n <p className=\"muted small\">\n Import a spec document to create a NEW {kind} and navigate to it — this does not replace\n the {kind} you have open.\n </p>\n <div className=\"rail-spec-menu-row\">\n <button\n type=\"button\"\n className=\"btn ghost\"\n data-testid=\"rail-spec-import\"\n onClick={onImport}\n >\n Import\n </button>\n </div>\n </div>\n <div className=\"modal-actions\">\n <button type=\"button\" className=\"btn ghost\" onClick={onClose}>\n Close\n </button>\n </div>\n </Modal>\n );\n}\n\n/**\n * Version history (A4): a link-styled icon, ALWAYS enabled (\"no earlier versions\" is an empty\n * state INSIDE the list modal, never a disabled control). Once opened (`open`), the un-carded\n * \"Published: vN\" line and Publish / Enable-Disable stay in the main panel.\n */\nexport function VersionSection(props: {\n definitionStatus?: \"published\" | \"draft\" | \"unpublished\";\n publishDisabled?: boolean;\n open: boolean;\n versions: VersionsEnvelope | undefined;\n publishing: boolean;\n togglingEnabled: boolean;\n publishError: string | null;\n enableError: string | null;\n onShow: () => void;\n onPublish: () => void;\n onToggleEnabled: () => void;\n}) {\n const { open, versions } = props;\n return (\n <div className=\"rail-version-section\">\n {props.definitionStatus && (\n <div aria-live=\"polite\" data-testid=\"rail-definition-status\">\n <span className={`badge wf-definition-status ${props.definitionStatus}`}>\n {props.definitionStatus === \"published\" ? \"Live\" : \"Draft\"}\n </span>\n <p className=\"muted small\">\n {props.definitionStatus === \"draft\"\n ? \"This definition has unpublished changes. Republish to update the live version.\"\n : props.definitionStatus === \"unpublished\"\n ? \"This definition has never been published.\"\n : \"This definition matches the published version.\"}\n </p>\n </div>\n )}\n <button\n type=\"button\"\n className=\"rail-link-icon\"\n data-testid=\"rail-history-show\"\n aria-label=\"Version history\"\n title=\"Version history\"\n onClick={props.onShow}\n >\n <Icon name=\"clock\" size={14} />\n <span>Version history</span>\n </button>\n {(open || props.definitionStatus) && (\n <p className=\"muted small\" data-testid=\"rail-version-published\">\n {versions?.currentPublishedVersion != null\n ? `Published: v${versions.currentPublishedVersion}`\n : \"Never published\"}\n </p>\n )}\n {open && (\n <>\n <div className=\"rail-version-actions\">\n <button\n type=\"button\"\n className=\"btn ghost\"\n data-testid=\"rail-publish\"\n disabled={\n props.publishing || props.publishDisabled || props.definitionStatus === \"published\"\n }\n onClick={props.onPublish}\n >\n {props.publishing\n ? versions?.currentPublishedVersion != null\n ? \"Republishing…\"\n : \"Publishing…\"\n : props.definitionStatus === \"published\" ||\n (props.publishDisabled !== undefined &&\n props.definitionStatus === undefined &&\n versions?.currentPublishedVersion != null)\n ? \"Published\"\n : versions?.currentPublishedVersion != null\n ? \"Republish\"\n : \"Publish\"}\n </button>{\" \"}\n <button\n type=\"button\"\n className=\"btn ghost\"\n data-testid=\"rail-enable-toggle\"\n disabled={props.togglingEnabled || versions === undefined}\n onClick={props.onToggleEnabled}\n >\n {props.togglingEnabled ? \"Saving…\" : versions?.enabled ? \"Disable\" : \"Enable\"}\n </button>\n </div>\n {props.publishError && (\n <div className=\"error\" data-testid=\"rail-publish-error\">\n {props.publishError}\n </div>\n )}\n {props.enableError && (\n <div className=\"error\" data-testid=\"rail-enable-error\">\n {props.enableError}\n </div>\n )}\n </>\n )}\n </div>\n );\n}\n\n/**\n * The \"All versions\" list modal — deliberately NOT titled \"Version history\" (which would share\n * the `Version …` aria-label prefix the per-version detail viewer's own dialogs use).\n */\nexport function VersionListModal(props: {\n loading: boolean;\n versions: readonly VersionSummary[] | undefined;\n onSelect: (versionNumber: number) => void;\n onClose: () => void;\n}) {\n const { loading, versions } = props;\n return (\n <Modal title=\"All versions\" onClose={props.onClose} wide>\n <div className=\"modal-body\">\n {loading && <p className=\"muted small\">Loading…</p>}\n {versions?.length === 0 && <p className=\"muted small\">No versions yet.</p>}\n {versions && versions.length > 0 && (\n <ul className=\"list\">\n {versions.map((v) => (\n <li key={v.versionNumber} className=\"selectable\">\n <button\n type=\"button\"\n className=\"row-select\"\n data-testid=\"rail-version-row\"\n onClick={() => props.onSelect(v.versionNumber)}\n >\n <div className=\"list-main\">\n <code>v{v.versionNumber}</code>{\" \"}\n {v.isCurrentPublished && (\n <span className=\"badge\" data-testid=\"rail-version-current\">\n Published\n </span>\n )}\n <div className=\"muted small\">{new Date(v.createdAt).toLocaleString()}</div>\n </div>\n </button>\n </li>\n ))}\n </ul>\n )}\n </div>\n <div className=\"modal-actions\">\n <button type=\"button\" className=\"btn ghost\" onClick={props.onClose}>\n Done\n </button>\n </div>\n </Modal>\n );\n}\n\nconst DANGER_COPY: Record<\n SettingsKind,\n {\n deleteTitle: string;\n deleteMessage: string;\n archiveTitle: string;\n archiveMessage: string;\n deleteLabel: string;\n deleteTestId: string;\n archiveTestId: string;\n }\n> = {\n function: {\n deleteTitle: \"Delete function\",\n deleteMessage:\n \"Delete this function permanently? Any endpoint, workflow, or call pointing to it will start failing with a not-found error the next time it runs, and this cannot be undone.\",\n archiveTitle: \"Archive function\",\n archiveMessage:\n \"Archive this function? It stops being invocable and can no longer be edited. Archiving is one-way — there is no unarchive — and only an archived function can be deleted.\",\n deleteLabel: \"Delete this function\",\n deleteTestId: \"delete-function\",\n archiveTestId: \"archive-function\",\n },\n endpoint: {\n deleteTitle: \"Delete endpoint\",\n deleteMessage:\n \"Delete this endpoint permanently? Any alias, workflow, or call pointing to it will start failing with a not-found error the next time it runs, and this cannot be undone.\",\n archiveTitle: \"Archive endpoint\",\n archiveMessage:\n \"Archive this endpoint? It stops being invocable and can no longer be edited. Archiving is one-way — there is no unarchive — and only an archived endpoint can be deleted.\",\n deleteLabel: \"Delete this endpoint\",\n deleteTestId: \"delete-endpoint\",\n archiveTestId: \"archive-endpoint\",\n },\n workflow: {\n deleteTitle: \"Delete workflow\",\n deleteMessage: \"Permanently delete this workflow and its run history? This cannot be undone.\",\n archiveTitle: \"Archive workflow\",\n archiveMessage:\n \"Archive this workflow? It stops running and can no longer be published. Archiving is one-way — there is no unarchive. Its run history is kept until you delete it.\",\n deleteLabel: \"Delete this workflow\",\n deleteTestId: \"wf-settings-delete\",\n archiveTestId: \"wf-settings-archive\",\n },\n};\n\n/**\n * The bottom \"danger zone\": Archive and Delete for workflows; Archive then Delete for other kinds.\n * Per-kind variance (copy, test ids) is the table above; the caller owns the mutations and the\n * confirm/error state, and renders this only when `hasDelete(kind)`.\n */\nexport function SettingsDangerZone(props: {\n kind: SettingsKind;\n archived: boolean;\n pending?: boolean;\n deleteConfirming: boolean;\n archiveConfirming: boolean;\n deleteError: string | null;\n archiveError: string | null;\n onRequestDelete: () => void;\n onRequestArchive: () => void;\n onConfirmDelete: () => void;\n onConfirmArchive: () => void;\n onCloseDelete: () => void;\n onCloseArchive: () => void;\n}) {\n const copy = DANGER_COPY[props.kind];\n return (\n <>\n <DangerZone\n archived={props.archived}\n allowDirectDelete={props.kind === \"workflow\"}\n pending={props.pending}\n deleteLabel={copy.deleteLabel}\n deleteTestId={copy.deleteTestId}\n archiveTestId={copy.archiveTestId}\n onRequestDelete={props.onRequestDelete}\n onRequestArchive={props.onRequestArchive}\n deleteError={props.deleteError}\n archiveError={props.archiveError}\n />\n {props.deleteConfirming && (\n <ConfirmModal\n title={copy.deleteTitle}\n message={copy.deleteMessage}\n confirmLabel=\"Delete\"\n pending={props.pending}\n onConfirm={props.onConfirmDelete}\n onClose={props.onCloseDelete}\n />\n )}\n {props.archiveConfirming && (\n <ConfirmModal\n title={copy.archiveTitle}\n message={copy.archiveMessage}\n confirmLabel=\"Archive\"\n pending={props.pending}\n onConfirm={props.onConfirmArchive}\n onClose={props.onCloseArchive}\n />\n )}\n </>\n );\n}\n","/**\n * The Settings rail tool — what a resource's right-rail Settings panel does, owned by the package\n * so `<WorkflowEditor>`, a host's `<CallableRail>` and Studio's own rail all render ONE tool:\n * `settingsTool` is a stateful shell (it owns the three open flags) that dispatches by kind to\n * `WorkflowSettingsPanel` or `CallableSettingsPanel` (function / endpoint). Both render the same\n * presentational sections (`./settings-sections.tsx`).\n *\n * Workflow arm, unchanged:\n * - metadata (name / id / key / tags) read off the cached workflow list row;\n * - the unified settings modal saves the WHOLE stored definition (`useWorkflowQuery`'s\n * `workflow`, `displayName` / `key` / `tags` replaced) with `ifUnmodifiedSince` from that\n * query's `updatedAt`, and `project` passed VERBATIM — `useSaveWorkflowMutation` refuses\n * without one, because an unscoped write would silently relocate the workflow into the\n * account's default project (C/D-C2). A 409/400 renders inline, never a thrown error;\n * - the Import chooser → `ImportSpecModal` (creates a NEW workflow and opens it);\n * - version history / Publish / Enable are gated on the section's OWN open state, so opening\n * the panel issues zero `/versions` requests;\n * - Archive or Delete directly. Both land on the list via `onNavigate({ type: \"list\" })`.\n *\n * Function / endpoint arm: the same sections over `../repos/functions.ts` / `endpoints.ts`, plus\n * Export (`useSpecQuery`, gated on the export modal being open) and Edit JSON. Every write built\n * from a cached definition takes the definition from `callableRecord(kind, query.data)` — the ONE\n * strip of `valid` / `updatedAt` — and saves through the guarded hook with the stale-write token\n * OF THE RECORD THE WRITTEN TEXT CAME FROM: the name/key modal uses the current record's\n * `updatedAt`; Edit JSON uses the token captured when its text was seeded (`openEdit`), never one\n * read at save time over older text (that would silently overwrite a write that landed meanwhile).\n * A refusal (409 `function_stale` / `endpoint_stale`, 400…) renders inline and is never retried.\n *\n * Host seams: `project` and `onNavigate` arrive as props on the arms, and the `settingsTool` Panel\n * reads them from `useRailEnv()` (`./rail-env.tsx`). Archive / delete land on the list through\n * `onNavigate({ type: \"list\" })`; an import opens `{ type: \"imported\", kind, id }`. No router, no\n * `client.console`, no module-scope browser globals.\n *\n * ⚠️ The strip id is `\"settings\"`; `activeTool` is persisted.\n */\nimport { ApiError } from \"@w6w/sdk\";\nimport { CodeBlock, Icon, JsonEditor } from \"@w6w/ui\";\nimport { useRef, useState } from \"react\";\nimport { CallableSettingsModal } from \"../chrome/CallableSettingsModal.tsx\";\nimport { ImportSpecModal } from \"../chrome/ImportSpecModal.tsx\";\nimport { Modal } from \"../chrome/Modal.tsx\";\nimport type { RailTool } from \"../chrome/RightRail.tsx\";\nimport { VersionHistoryModal } from \"../chrome/VersionHistoryModal.tsx\";\nimport type { WorkspaceCallable } from \"../chrome/workspace.tsx\";\nimport { callableRecord } from \"../lib/callable-record.ts\";\nimport {\n evaluateEdit,\n hasDefinitionActions,\n hasDelete,\n hasVersionHistory,\n metadataFieldsForKind,\n specCollectionForKind,\n} from \"../lib/rail-settings.ts\";\nimport {\n endpointsKey,\n useArchiveEndpointMutation,\n useDeleteEndpointMutation,\n useEndpointQuery,\n useEndpointsQuery,\n useGuardedSaveEndpointMutation,\n} from \"../repos/endpoints.ts\";\nimport {\n functionsKey,\n useArchiveFunctionMutation,\n useDeleteFunctionMutation,\n useFunctionQuery,\n useFunctionsQuery,\n useGuardedSaveFunctionMutation,\n} from \"../repos/functions.ts\";\nimport { useSpecQuery } from \"../repos/spec-export.ts\";\nimport {\n type VersionsKind,\n usePublishMutation,\n useSetEnabledMutation,\n useVersionsQuery,\n} from \"../repos/versions.ts\";\nimport {\n useArchiveWorkflowMutation,\n useDeleteWorkflowMutation,\n useSaveWorkflowMutation,\n useWorkflowQuery,\n useWorkflowsQuery,\n workflowsKey,\n} from \"../repos/workflows.ts\";\nimport { type RailNavigation, useRailEnv } from \"./rail-env.tsx\";\nimport {\n MetadataSection,\n SettingsDangerZone,\n SettingsHeading,\n SpecActionsTrigger,\n SpecChooserModal,\n VersionListModal,\n VersionSection,\n} from \"./settings-sections.tsx\";\n\n/** The Import modal's three list keys — the repos' own exports, never literals. */\nconst IMPORT_LIST_KEYS = { functionsKey, endpointsKey, workflowsKey };\n\n/**\n * The three open flags a Settings panel shows: the Name/Key/Tags modal, the history section, and\n * the version list modal. They are OWNED BY THE CALLER (a stateful shell above every kind's arm),\n * not by the arm: a rail that stays mounted across a kind change (function -> workflow ->\n * endpoint) swaps arm component types, and state held in the arm would be remounted away,\n * closing an open modal. Lifting them keeps the modal open exactly as the pre-split single\n * component did.\n */\nexport type SettingsOpenState = {\n editingSettings: boolean;\n setEditingSettings: (v: boolean) => void;\n historyOpen: boolean;\n setHistoryOpen: (v: boolean) => void;\n versionListOpen: boolean;\n setVersionListOpen: (v: boolean) => void;\n};\n\nexport function WorkflowSettingsPanel({\n ctx,\n project,\n onNavigate,\n open,\n}: {\n ctx: WorkspaceCallable;\n project: string | null;\n onNavigate: (to: RailNavigation) => void;\n open: SettingsOpenState;\n}) {\n const {\n editingSettings,\n setEditingSettings,\n historyOpen,\n setHistoryOpen,\n versionListOpen,\n setVersionListOpen,\n } = open;\n const workflowsQuery = useWorkflowsQuery(project ?? undefined);\n const isWorkflow = ctx?.kind === \"workflow\";\n const id = ctx?.id ?? \"\";\n\n // The Key / Tags / Name save needs the WHOLE stored definition (never a `{id,key}` stub) plus\n // the `updatedAt` precondition — both come from this query.\n const wfDefQuery = useWorkflowQuery(id, isWorkflow);\n // MUST carry the current project, verbatim: the hook refuses a missing one (no default).\n const saveWfMut = useSaveWorkflowMutation(project ?? undefined);\n const archiveWfMut = useArchiveWorkflowMutation();\n const deleteWfMut = useDeleteWorkflowMutation();\n const deleting = useRef(false);\n\n const [specMenuOpen, setSpecMenuOpen] = useState(false);\n const [importing, setImporting] = useState(false);\n const [exporting, setExporting] = useState(false);\n const [deleteConfirming, setDeleteConfirming] = useState(false);\n const [archiveConfirming, setArchiveConfirming] = useState(false);\n const [deleteError, setDeleteError] = useState<string | null>(null);\n const [archiveError, setArchiveError] = useState<string | null>(null);\n // Gated on the export modal's own open state: opening the panel issues zero `/spec` requests.\n const specQuery = useSpecQuery(specCollectionForKind(\"workflow\"), id, exporting);\n\n // `versionListOpen` is DELIBERATELY separate from `historyOpen` (both arrive via `open`): a\n // native `<dialog>` opened via `showModal()` makes the rest of the page inert, so sharing one\n // boolean would hide Publish/Enable-Disable the moment the list modal closes. The entry icon\n // sets both true; only the list modal's own close clears `versionListOpen`.\n // Gated on the section's OWN open state: opening this panel issues zero `/versions` requests.\n const versionsQuery = useVersionsQuery(\"workflow\", id, historyOpen && isWorkflow);\n const publishMut = usePublishMutation(\"workflow\");\n const setEnabledMut = useSetEnabledMutation(\"workflow\");\n const [publishError, setPublishError] = useState<string | null>(null);\n const [enableError, setEnableError] = useState<string | null>(null);\n // Keyed by resource id: falls back to closed the instant `ctx.id` no longer matches, so a\n // transition never carries a stale version from a DIFFERENT resource.\n const [openVersion, setOpenVersion] = useState<{ id: string; versionNumber: number } | null>(\n null,\n );\n\n if (!ctx || ctx.kind !== \"workflow\") {\n return <p className=\"muted small\">Open a workflow to see its settings.</p>;\n }\n\n const listRow = workflowsQuery.data?.find((w) => w.id === ctx.id);\n const displayName =\n listRow && typeof (listRow as { displayName?: unknown }).displayName === \"string\"\n ? (listRow as { displayName: string }).displayName\n : \"\";\n const tags = (listRow as { tags?: string[] } | undefined)?.tags ?? [];\n const archived = (listRow as { status?: string } | undefined)?.status === \"archived\";\n\n async function onDelete() {\n if (deleting.current) return;\n deleting.current = true;\n setDeleteError(null);\n try {\n // Preserve the API's lifecycle checks without requiring two user actions.\n if (!archived) await archiveWfMut.mutateAsync(id);\n await deleteWfMut.mutateAsync(id);\n setDeleteConfirming(false);\n onNavigate({ type: \"list\" });\n } catch (e) {\n setDeleteConfirming(false);\n setDeleteError(e instanceof ApiError ? e.message : String(e));\n } finally {\n deleting.current = false;\n }\n }\n\n function onArchive() {\n setArchiveError(null);\n archiveWfMut.mutate(id, {\n onSuccess: () => {\n setArchiveConfirming(false);\n onNavigate({ type: \"list\" });\n },\n onError: (e: unknown) => {\n setArchiveConfirming(false);\n setArchiveError(e instanceof ApiError ? e.message : String(e));\n },\n });\n }\n\n return (\n <div className=\"rail-settings-panel\">\n <SettingsHeading onEdit={() => setEditingSettings(true)} />\n {ctx.authoringSettings && ctx.onAuthoringSettingChange && (\n <section className=\"w6w-stack\" data-testid=\"rail-workflow-authoring\">\n <label>\n <input\n type=\"checkbox\"\n checked={ctx.authoringSettings.autoSave}\n onChange={(e) => ctx.onAuthoringSettingChange?.(\"autoSave\", e.target.checked)}\n />\n Auto-save edits\n </label>\n <label>\n <input\n type=\"checkbox\"\n checked={ctx.authoringSettings.savePosition}\n onChange={(e) => ctx.onAuthoringSettingChange?.(\"savePosition\", e.target.checked)}\n />\n Save node positions and canvas view\n </label>\n </section>\n )}\n <MetadataSection\n id={ctx.id}\n displayName={displayName}\n fields={metadataFieldsForKind(\"workflow\")}\n row={listRow}\n tags={tags}\n />\n\n <SpecActionsTrigger onOpen={() => setSpecMenuOpen(true)} />\n\n <VersionSection\n definitionStatus={ctx.definitionStatus}\n publishDisabled={ctx.publishDisabled}\n open={historyOpen}\n versions={versionsQuery.data}\n publishing={publishMut.isPending}\n togglingEnabled={setEnabledMut.isPending}\n publishError={publishError}\n enableError={enableError}\n onShow={() => {\n setHistoryOpen(true);\n setVersionListOpen(true);\n }}\n onPublish={() => {\n if (ctx.onPublish) {\n void ctx.onPublish();\n return;\n }\n setPublishError(null);\n publishMut.mutate(id, {\n onError: (e) => setPublishError(e instanceof ApiError ? e.message : String(e)),\n });\n }}\n onToggleEnabled={() => {\n setEnableError(null);\n setEnabledMut.mutate(\n { id, enabled: !versionsQuery.data?.enabled },\n { onError: (e) => setEnableError(e instanceof ApiError ? e.message : String(e)) },\n );\n }}\n />\n\n {versionListOpen && (\n <VersionListModal\n loading={versionsQuery.isLoading}\n versions={versionsQuery.data?.versions}\n onSelect={(versionNumber) => setOpenVersion({ id, versionNumber })}\n onClose={() => setVersionListOpen(false)}\n />\n )}\n\n {openVersion && openVersion.id === id && (\n <VersionHistoryModal\n kind=\"workflow\"\n id={id}\n onRestore={ctx.onRestoreVersion}\n versionNumber={openVersion.versionNumber}\n onClose={() => setOpenVersion(null)}\n />\n )}\n\n {specMenuOpen && (\n <SpecChooserModal\n kind=\"workflow\"\n onClose={() => setSpecMenuOpen(false)}\n onImport={() => {\n setSpecMenuOpen(false);\n setImporting(true);\n }}\n >\n <p className=\"muted small\">\n Export a portable definition — the same shape Import accepts.\n </p>\n <div className=\"rail-spec-menu-row\">\n <button\n type=\"button\"\n className=\"btn ghost\"\n data-testid=\"rail-spec-export\"\n onClick={() => {\n setSpecMenuOpen(false);\n setExporting(true);\n }}\n >\n Export\n </button>\n </div>\n </SpecChooserModal>\n )}\n\n {exporting && (\n <Modal title=\"Export spec document\" onClose={() => setExporting(false)} wide>\n <div className=\"modal-body\">\n {specQuery.isLoading ? (\n <p className=\"muted small\">Loading…</p>\n ) : specQuery.isError ? (\n <div className=\"error\" data-testid=\"rail-spec-error\">\n {specQuery.error instanceof Error\n ? specQuery.error.message\n : String(specQuery.error)}\n </div>\n ) : specQuery.data ? (\n <div data-testid=\"rail-spec-json\">\n <CodeBlock\n code={JSON.stringify(specQuery.data, null, 2)}\n language=\"json\"\n maxHeight=\"420px\"\n copyable\n />\n </div>\n ) : null}\n </div>\n <div className=\"modal-actions\">\n <button type=\"button\" className=\"btn ghost\" onClick={() => setExporting(false)}>\n Close\n </button>\n </div>\n </Modal>\n )}\n\n {/* Unified settings modal for name, key, and tags. */}\n {editingSettings && listRow && (\n <CallableSettingsModal\n // `key={id}` remounts (not merely re-renders) when an in-app navigation swaps the rail\n // to a different resource while this modal is open — the modal's `useState`\n // initializers never re-run on a prop change, so without it a save would mix the first\n // resource's stale fields with the new `id`.\n key={id}\n kind=\"workflow\"\n id={id}\n initial={{\n displayName,\n key: (listRow as { key?: string | null }).key ?? null,\n tags,\n }}\n onSave={async (data) => {\n if (!wfDefQuery.data) throw new Error(\"Unable to save settings\");\n const stored = wfDefQuery.data;\n return new Promise((resolve, reject) => {\n const updated: Record<string, unknown> = {\n ...stored.workflow,\n displayName: data.displayName,\n };\n if (data.key !== undefined) {\n updated.key = data.key;\n }\n if (data.tags !== undefined) {\n updated.tags = data.tags;\n }\n saveWfMut.mutate(\n { definition: updated, ifUnmodifiedSince: stored.updatedAt },\n { onSuccess: () => resolve(), onError: reject },\n );\n });\n }}\n onClose={() => setEditingSettings(false)}\n />\n )}\n\n <SettingsDangerZone\n kind=\"workflow\"\n archived={archived}\n pending={archiveWfMut.isPending || deleteWfMut.isPending}\n deleteConfirming={deleteConfirming}\n archiveConfirming={archiveConfirming}\n deleteError={deleteError}\n archiveError={archiveError}\n onRequestDelete={() => setDeleteConfirming(true)}\n onRequestArchive={() => setArchiveConfirming(true)}\n onConfirmDelete={onDelete}\n onConfirmArchive={onArchive}\n onCloseDelete={() => setDeleteConfirming(false)}\n onCloseArchive={() => setArchiveConfirming(false)}\n />\n\n {importing && (\n <ImportSpecModal\n kind=\"workflow\"\n project={project ?? undefined}\n listKeys={IMPORT_LIST_KEYS}\n onOpenImported={(kind, newId) => onNavigate({ type: \"imported\", kind, id: newId })}\n onClose={() => setImporting(false)}\n />\n )}\n </div>\n );\n}\n\n/**\n * Stateful shell: owns the three open flags ABOVE every arm and passes them down. The kind branch\n * picks a component TYPE (so each arm's data hooks stay per-kind), and an arm remounts on a kind\n * change — but the modal / version-list flags live here, so they survive the swap (rail guards\n * K6/V6).\n */\nfunction SettingsToolPanel({ ctx }: { ctx: WorkspaceCallable }) {\n const { project, onNavigate } = useRailEnv();\n const [editingSettings, setEditingSettings] = useState(false);\n const [historyOpen, setHistoryOpen] = useState(false);\n const [versionListOpen, setVersionListOpen] = useState(false);\n const open: SettingsOpenState = {\n editingSettings,\n setEditingSettings,\n historyOpen,\n setHistoryOpen,\n versionListOpen,\n setVersionListOpen,\n };\n return ctx?.kind === \"workflow\" ? (\n <WorkflowSettingsPanel ctx={ctx} project={project} onNavigate={onNavigate} open={open} />\n ) : (\n <CallableSettingsPanel ctx={ctx} project={project} onNavigate={onNavigate} open={open} />\n );\n}\n\nexport function CallableSettingsPanel({\n ctx,\n project,\n onNavigate,\n open,\n}: {\n ctx: WorkspaceCallable;\n project: string | null;\n onNavigate: (to: RailNavigation) => void;\n open: SettingsOpenState;\n}) {\n const {\n editingSettings,\n setEditingSettings,\n historyOpen,\n setHistoryOpen,\n versionListOpen,\n setVersionListOpen,\n } = open;\n const kind0 = ctx?.kind;\n const endpointsQuery = useEndpointsQuery(kind0 === \"endpoint\");\n const functionsQuery = useFunctionsQuery(kind0 === \"function\");\n\n const [editing, setEditing] = useState(false);\n const [editText, setEditText] = useState(\"\");\n const [editError, setEditError] = useState<string | null>(null);\n // The stale-write token of the record `editText` was seeded from (`openEdit`). Read at SAVE time\n // it would guard text seeded from an older copy with a newer token — a silent overwrite.\n const [editToken, setEditToken] = useState<string | null>(null);\n // A5: one chooser icon opens ONE combined Modal (Export + Edit JSON +\n // Import); picking an item there closes the chooser and opens THAT item's\n // own modal as a sibling — never nested inside the chooser's own body.\n const [specMenuOpen, setSpecMenuOpen] = useState(false);\n const [exporting, setExporting] = useState(false);\n const [importing, setImporting] = useState(false);\n const [deleteConfirming, setDeleteConfirming] = useState(false);\n const [archiveConfirming, setArchiveConfirming] = useState(false);\n const [deleteError, setDeleteError] = useState<string | null>(null);\n const [archiveError, setArchiveError] = useState<string | null>(null);\n\n // Gated on `ctx.kind` alone, never additionally on the edit modal being\n // open — ST6's post-save freshness proof needs the `[\"function\", id]` cache\n // entry to exist before the save happens.\n const fnDefQuery = useFunctionQuery(ctx?.id ?? \"\", ctx?.kind === \"function\");\n const epDefQuery = useEndpointQuery(ctx?.id ?? \"\", ctx?.kind === \"endpoint\");\n const saveFnMut = useGuardedSaveFunctionMutation();\n const saveEpMut = useGuardedSaveEndpointMutation();\n const deleteFnMut = useDeleteFunctionMutation();\n const deleteEpMut = useDeleteEndpointMutation();\n // A7: Function/Endpoint have the archive-before-delete step too.\n const archiveFnMut = useArchiveFunctionMutation();\n const archiveEpMut = useArchiveEndpointMutation();\n // Gated on the export modal's own open state, so opening this panel issues\n // zero `/spec` requests. `specCollectionForKind` returns `null` for\n // `workflow`/`connection`, which disables the query regardless of `exporting`.\n const specCollection = ctx ? specCollectionForKind(ctx.kind) : null;\n const specQuery = useSpecQuery(specCollection, ctx?.id ?? \"\", exporting);\n\n // ── The History section ─────────────────────────────────────────────────\n // `null` for a kind with no version history (`connection`).\n const versionsKind: VersionsKind | null =\n ctx && hasVersionHistory(ctx.kind) ? (ctx.kind as VersionsKind) : null;\n // Gated on the section's OWN open state (`historyOpen`): never fires on mount.\n const versionsQuery = useVersionsQuery(versionsKind, ctx?.id ?? \"\", historyOpen);\n // `usePublishMutation`/`useSetEnabledMutation` need a fixed, non-null kind\n // per hook instance; the fallback is never reached by an actual request —\n // the buttons that call `.mutate` only render inside the\n // `hasVersionHistory(ctx.kind)`-gated block.\n const publishMut = usePublishMutation(versionsKind ?? \"function\");\n const setEnabledMut = useSetEnabledMutation(versionsKind ?? \"function\");\n const [publishError, setPublishError] = useState<string | null>(null);\n const [enableError, setEnableError] = useState<string | null>(null);\n // Keyed by resource id: falls back to closed the instant `ctx.id` no longer\n // matches, so a kind/id transition (V6) never carries a stale version.\n const [openVersion, setOpenVersion] = useState<{ id: string; versionNumber: number } | null>(\n null,\n );\n\n // `isAvailable` already keeps this tool off the strip for a `ctx` this has\n // no settings for — but a persisted `activeTool` plus an in-app transition\n // to a non-publishing route can still render this Panel with `ctx === null`\n // (or a `connection`). The rail must never blank out or crash.\n if (!ctx || (ctx.kind !== \"function\" && ctx.kind !== \"endpoint\")) {\n return (\n <p className=\"muted small\">Open a workflow, function, or endpoint to see its settings.</p>\n );\n }\n\n const kind = ctx.kind;\n const id = ctx.id;\n const listRow =\n kind === \"function\"\n ? functionsQuery.data?.find((f) => f.id === id)\n : endpointsQuery.data?.find((e) => e.id === id);\n // The cached record split ONCE (`callableRecord`): the editable definition (no `valid` /\n // `updatedAt`) and the stale-write token it was read with.\n const record = callableRecord(kind, kind === \"function\" ? fnDefQuery.data : epDefQuery.data);\n const def = record?.definition ?? null;\n // Display name (the human-readable label shown in the list)\n const displayName = listRow\n ? typeof (listRow as { displayName?: unknown }).displayName === \"string\"\n ? (listRow as { displayName: string }).displayName\n : \"\"\n : \"\";\n\n const defJson = def ? JSON.stringify(def, null, 2) : \"\";\n\n function openEdit() {\n setEditError(null);\n setEditText(defJson);\n setEditToken(record?.updatedAt ?? null);\n setEditing(true);\n }\n\n const editEval = def\n ? evaluateEdit(editText, { id: String(def.id), key: String(def.key) })\n : { parsed: null, blockedReason: \"No definition loaded yet.\" };\n const savingDef = kind === \"function\" ? saveFnMut.isPending : saveEpMut.isPending;\n\n function onSaveEdit() {\n if (!editEval.parsed || editEval.blockedReason) return;\n setEditError(null);\n const onSettled = {\n onSuccess: () => setEditing(false),\n onError: (e: unknown) => setEditError(e instanceof ApiError ? e.message : String(e)),\n };\n const vars = { definition: editEval.parsed, ifUnmodifiedSince: editToken };\n if (kind === \"function\") {\n saveFnMut.mutate(vars, onSettled);\n } else {\n saveEpMut.mutate(vars, onSettled);\n }\n }\n\n // ── Delete/Archive — the bottom \"danger zone\" ────────────────────────────\n // Function/Endpoint signal \"already archived\" via the `archivedAt` column.\n const archived = (listRow as { archivedAt?: string | null } | undefined)?.archivedAt != null;\n\n function onDelete() {\n setDeleteError(null);\n const onSettled = {\n onSuccess: () => {\n setDeleteConfirming(false);\n onNavigate({ type: \"list\" });\n },\n onError: (e: unknown) => {\n setDeleteConfirming(false);\n setDeleteError(e instanceof ApiError ? e.message : String(e));\n },\n };\n if (kind === \"function\") deleteFnMut.mutate(id, onSettled);\n else deleteEpMut.mutate(id, onSettled);\n }\n\n // A1/D-I0-1: archive reuses `onDelete`'s land-on-the-list idiom.\n function onArchive() {\n setArchiveError(null);\n const onSettled = {\n onSuccess: () => {\n setArchiveConfirming(false);\n onNavigate({ type: \"list\" });\n },\n onError: (e: unknown) => {\n setArchiveConfirming(false);\n setArchiveError(e instanceof ApiError ? e.message : String(e));\n },\n };\n if (kind === \"function\") archiveFnMut.mutate(id, onSettled);\n else archiveEpMut.mutate(id, onSettled);\n }\n\n return (\n <div className=\"rail-settings-panel\">\n <SettingsHeading onEdit={() => setEditingSettings(true)} />\n <MetadataSection\n id={id}\n displayName={displayName}\n fields={metadataFieldsForKind(kind)}\n row={listRow}\n />\n\n {hasDefinitionActions(kind) && <SpecActionsTrigger onOpen={() => setSpecMenuOpen(true)} />}\n\n {hasVersionHistory(kind) && (\n <VersionSection\n open={historyOpen}\n versions={versionsQuery.data}\n publishing={publishMut.isPending}\n togglingEnabled={setEnabledMut.isPending}\n publishError={publishError}\n enableError={enableError}\n onShow={() => {\n setHistoryOpen(true);\n setVersionListOpen(true);\n }}\n onPublish={() => {\n setPublishError(null);\n publishMut.mutate(id, {\n onError: (e) => setPublishError(e instanceof ApiError ? e.message : String(e)),\n });\n }}\n onToggleEnabled={() => {\n setEnableError(null);\n setEnabledMut.mutate(\n { id, enabled: !versionsQuery.data?.enabled },\n { onError: (e) => setEnableError(e instanceof ApiError ? e.message : String(e)) },\n );\n }}\n />\n )}\n\n {versionListOpen && (\n <VersionListModal\n loading={versionsQuery.isLoading}\n versions={versionsQuery.data?.versions}\n onSelect={(versionNumber) => setOpenVersion({ id, versionNumber })}\n onClose={() => setVersionListOpen(false)}\n />\n )}\n\n {openVersion && openVersion.id === id && (\n <VersionHistoryModal\n kind={kind}\n id={id}\n versionNumber={openVersion.versionNumber}\n onClose={() => setOpenVersion(null)}\n />\n )}\n\n {/* The chooser — Export + Edit JSON (function/endpoint only, PL-2) fill\n the shell's slot; Import is the shell's own. */}\n {specMenuOpen && (\n <SpecChooserModal\n kind={kind}\n onClose={() => setSpecMenuOpen(false)}\n onImport={() => {\n setSpecMenuOpen(false);\n setImporting(true);\n }}\n >\n {hasDefinitionActions(kind) && (\n <>\n <p className=\"muted small\">\n Export a portable definition — the same shape Import accepts — or Edit JSON to\n change what's stored directly.\n </p>\n <div className=\"rail-spec-menu-row\">\n <button\n type=\"button\"\n className=\"btn ghost\"\n data-testid=\"rail-spec-export\"\n onClick={() => {\n setSpecMenuOpen(false);\n setExporting(true);\n }}\n >\n Export\n </button>{\" \"}\n <button\n type=\"button\"\n className=\"btn ghost\"\n disabled={!def}\n data-testid=\"rail-json-edit\"\n onClick={() => {\n setSpecMenuOpen(false);\n openEdit();\n }}\n >\n Edit JSON\n </button>\n </div>\n </>\n )}\n </SpecChooserModal>\n )}\n\n {/* Export — a read-only modal carrying the `/spec` route's `spec` field\n verbatim, via `@w6w/ui`'s `CodeBlock`, never a second editable text\n box. The request fires only while this modal is open. */}\n {exporting && (\n <Modal title=\"Export spec document\" onClose={() => setExporting(false)} wide>\n <div className=\"modal-body\">\n {specQuery.isLoading ? (\n <p className=\"muted small\">Loading…</p>\n ) : specQuery.isError ? (\n <div className=\"error\" data-testid=\"rail-spec-error\">\n {specQuery.error instanceof Error\n ? specQuery.error.message\n : String(specQuery.error)}\n </div>\n ) : specQuery.data ? (\n <div data-testid=\"rail-spec-json\">\n <CodeBlock\n code={JSON.stringify(specQuery.data, null, 2)}\n language=\"json\"\n maxHeight=\"420px\"\n copyable\n />\n </div>\n ) : null}\n </div>\n <div className=\"modal-actions\">\n <button type=\"button\" className=\"btn ghost\" onClick={() => setExporting(false)}>\n Close\n </button>\n </div>\n </Modal>\n )}\n\n {/* Self-contained — Save lives inside this modal, mirroring\n `WorkflowDetailPage.tsx`'s read-only card, never `WorkflowsPage.tsx`'s\n Save-less `showJson` modal. */}\n {editing && (\n <Modal title=\"Edit definition\" onClose={() => setEditing(false)} wide>\n <div className=\"modal-body\">\n <JsonEditor\n value={editText}\n onChange={setEditText}\n minHeight=\"320px\"\n aria-label=\"Edit definition JSON\"\n />\n {editEval.blockedReason && (\n <p className=\"muted small\" data-testid=\"rail-edit-reason\">\n {editEval.blockedReason}\n </p>\n )}\n {editError && <div className=\"error\">{editError}</div>}\n </div>\n <div className=\"modal-actions\">\n <button type=\"button\" className=\"btn ghost\" onClick={() => setEditing(false)}>\n Cancel\n </button>\n <button\n type=\"button\"\n className=\"btn\"\n disabled={editEval.blockedReason !== null || savingDef}\n data-testid=\"rail-json-save\"\n onClick={onSaveEdit}\n >\n {savingDef ? \"Saving…\" : \"Save\"}\n </button>\n </div>\n </Modal>\n )}\n\n {/* Unified settings modal for name and key. */}\n {editingSettings && listRow && (\n <CallableSettingsModal\n // `key={id}` forces a remount (not a re-render) when an in-app\n // navigation swaps the rail to a different resource while this modal\n // is open — the modal's `useState` initializers never re-run on a\n // prop change, so a save would mix stale fields with the new `id`.\n key={id}\n kind={kind}\n id={id}\n initial={{\n displayName,\n key: (listRow as { key?: string | null }).key ?? null,\n tags: [],\n }}\n onSave={async (data) => {\n if (!record) throw new Error(\"Unable to save settings\");\n // Definition AND token from the same record, read now: the text written is this\n // record's own fields plus the modal's edits.\n const base = record.definition;\n const edited =\n kind === \"function\"\n ? // `canEditKey: true` for function (`callable-descriptors.ts`): `data.key` must\n // reach the server (the modal falls back to `initial.key` when unchanged).\n { ...base, displayName: data.displayName, key: data.key ?? base.key }\n : { ...base, displayName: data.displayName };\n const vars = { definition: edited, ifUnmodifiedSince: record.updatedAt };\n return new Promise((resolve, reject) => {\n const settled = { onSuccess: () => resolve(), onError: reject };\n if (kind === \"function\") saveFnMut.mutate(vars, settled);\n else saveEpMut.mutate(vars, settled);\n });\n }}\n onClose={() => setEditingSettings(false)}\n />\n )}\n\n {hasDelete(kind) && (\n <SettingsDangerZone\n kind={kind}\n archived={archived}\n deleteConfirming={deleteConfirming}\n archiveConfirming={archiveConfirming}\n deleteError={deleteError}\n archiveError={archiveError}\n onRequestDelete={() => setDeleteConfirming(true)}\n onRequestArchive={() => setArchiveConfirming(true)}\n onConfirmDelete={onDelete}\n onConfirmArchive={onArchive}\n onCloseDelete={() => setDeleteConfirming(false)}\n onCloseArchive={() => setArchiveConfirming(false)}\n />\n )}\n\n {importing && (\n <ImportSpecModal\n kind={kind}\n project={project ?? undefined}\n listKeys={IMPORT_LIST_KEYS}\n onOpenImported={(k, newId) => onNavigate({ type: \"imported\", kind: k, id: newId })}\n onClose={() => setImporting(false)}\n />\n )}\n </div>\n );\n}\n\nfunction SettingsToolIcon() {\n return <Icon name=\"settings\" />;\n}\n\n/** The package's Settings tool — workflow, function and endpoint. */\nexport const settingsTool: RailTool = {\n id: \"settings\",\n title: \"Settings\",\n rendersHeading: true,\n Icon: SettingsToolIcon,\n isAvailable: (ctx) =>\n ctx?.kind === \"workflow\" || ctx?.kind === \"function\" || ctx?.kind === \"endpoint\",\n Panel: SettingsToolPanel,\n};\n","import {\n type ExprValue,\n ExpressionInput,\n ExpressionOptionsProvider,\n IconButton,\n type SecretValue,\n useExpressionOptions,\n} from \"@w6w/ui\";\nimport { type WorkflowVariableRow, duplicateKeyIndexes, varsRailFor } from \"../lib/index.ts\";\n\nconst VARIABLE_TYPES = [\"string\", \"number\", \"boolean\", \"object\", \"array\"] as const;\n\n/** Shared workflow input editor, used in the Data rail and the legacy settings dialog. */\nexport function WorkflowVariablesEditor({\n variables,\n onVariablesChange,\n}: {\n variables: WorkflowVariableRow[];\n onVariablesChange: (next: WorkflowVariableRow[]) => void;\n}) {\n const inheritedVars = useExpressionOptions().vars ?? [];\n function addVariable() {\n onVariablesChange([...variables, { key: \"\" }]);\n }\n function updateVariable(i: number, next: Partial<WorkflowVariableRow>) {\n onVariablesChange(variables.map((v, idx) => (idx === i ? { ...v, ...next } : v)));\n }\n function removeVariable(i: number) {\n onVariablesChange(variables.filter((_, idx) => idx !== i));\n }\n const dupIndexes = duplicateKeyIndexes(variables);\n return (\n <div className=\"workflow-variable-fields\">\n {/* HITL-5: declaring a variable flips this workflow's generated MCP\n tool from a pass-through schema to a declared one — say so. */}\n <p className=\"muted small\">\n Declaring variables here defines this workflow's <strong>public input schema</strong>: API\n and AI (MCP) callers then see exactly these inputs. With none declared, they may send\n anything.\n </p>\n <div className=\"row\" style={{ justifyContent: \"space-between\", alignItems: \"center\" }}>\n <span className=\"muted small\">\n {variables.length === 0\n ? \"No variables declared.\"\n : `${variables.length} variable${variables.length === 1 ? \"\" : \"s\"} declared.`}\n </span>\n <button type=\"button\" className=\"btn ghost\" onClick={addVariable}>\n + Add variable\n </button>\n </div>\n {variables.length > 0 && (\n <ul className=\"list\" data-testid=\"workflow-variables-list\">\n {variables.map((v, i) => (\n <li\n // biome-ignore lint/suspicious/noArrayIndexKey: rows are positional and reorderable\n key={i}\n style={{\n flexDirection: \"column\",\n alignItems: \"stretch\",\n gap: \"var(--w6w-sp-1)\",\n }}\n >\n <div className=\"workflow-variable-row\">\n <input\n type=\"text\"\n value={v.key}\n placeholder=\"key\"\n aria-label=\"Variable key\"\n onChange={(e) => updateVariable(i, { key: e.target.value })}\n />\n <select\n value={v.type ?? \"\"}\n aria-label=\"Variable type\"\n onChange={(e) =>\n updateVariable(i, {\n type: (e.target.value || undefined) as WorkflowVariableRow[\"type\"],\n })\n }\n >\n <option value=\"\">(unset)</option>\n {VARIABLE_TYPES.map((t) => (\n <option key={t} value={t}>\n {t}\n </option>\n ))}\n </select>\n <label className=\"row\" style={{ gap: \"var(--w6w-sp-1)\", alignItems: \"center\" }}>\n <input\n type=\"checkbox\"\n checked={v.required ?? false}\n onChange={(e) => updateVariable(i, { required: e.target.checked })}\n />\n <span className=\"muted small\">required</span>\n </label>\n {/* Narrow `vars` for THIS row only: a variable's default\n may reference the variables declared above it, never\n itself or the ones below. Only that one key is\n contributed — secrets, documents, sample values and the\n callbacks come through from the app shell untouched,\n because the provider layers rather than replaces. */}\n <ExpressionOptionsProvider\n value={{ vars: varsRailFor(variables, i, inheritedVars) }}\n >\n <ExpressionInput\n // Re-key on the list's shape (not just `i`): ExpressionInput\n // seeds its parts once on mount and never again, so when a\n // row is removed and later rows shift up an index, React\n // must remount the widget rather than reuse the instance —\n // otherwise the surviving cell keeps showing the previous\n // occupant's default (see ExpressionInput.tsx:56-57).\n key={`${variables.length}:${i}`}\n value={v.default as ExprValue | string | SecretValue | undefined}\n onChange={(next) => updateVariable(i, { default: next })}\n placeholder=\"default\"\n aria-label=\"Variable default\"\n />\n </ExpressionOptionsProvider>\n <IconButton\n danger\n icon=\"close\"\n label={`Remove variable ${v.key || i + 1}`}\n onClick={() => removeVariable(i)}\n />\n </div>\n {dupIndexes.includes(i) && (\n <span className=\"muted small\" data-testid=\"variable-duplicate\">\n Duplicate key — a later row with the same name wins.\n </span>\n )}\n </li>\n ))}\n </ul>\n )}\n </div>\n );\n}\n","/**\n * The pure decisions behind the workflow rail's State panel (`rail/StartingStateTool.tsx`):\n * which run's state it shows, which step last wrote each top-level key, and how the starting\n * state (`Workflow.initialState`) reads as a preview.\n *\n * Pure, React-free, `.ts`, **no value import of `@w6w/ui`** — the same header rule as\n * `starting-data.ts` (studio's `test:unit` has no jsx loader).\n */\nimport { type StateLogRow, foldStateLog } from \"@w6w/expr\";\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === \"object\" && !Array.isArray(v);\n}\n\n/**\n * The run's state tree: the snapshot `GET /runs/:id` serves when one was persisted, else the\n * state-write log folded by `@w6w/expr`'s `foldStateLog` (the same fold the run log's \"state\n * after this step\" uses). `undefined` when neither has anything.\n */\nexport function runStateTree(\n snapshot: unknown,\n writes: readonly StateLogRow[] | undefined,\n): Record<string, unknown> | undefined {\n if (isPlainObject(snapshot)) return snapshot;\n if (writes && writes.length > 0) return foldStateLog(writes);\n return undefined;\n}\n\n/**\n * Who last wrote each top-level state key, from the run's state-write log: the node id of the\n * last write under that key, or `null` for a key that came from the starting state (the seed row,\n * `seq 0` with no node). A warning row wrote nothing; a delete (`new` absent or `null`) forgets the\n * key; a whole-tree write (`path []`) hands every key it sets to its node. Read in `seq` order\n * whatever order the rows arrive in.\n */\nexport function stateKeyWriters(writes: readonly StateLogRow[]): Map<string, string | null> {\n const out = new Map<string, string | null>();\n const rows = [...writes].sort((a, b) => a.seq - b.seq);\n for (const row of rows) {\n if (row.warning !== undefined || !Array.isArray(row.path)) continue;\n const node = row.nodeId ?? null;\n const set = row.new !== undefined && row.new !== null;\n if (row.path.length === 0) {\n out.clear();\n if (set && isPlainObject(row.new)) for (const k of Object.keys(row.new)) out.set(k, node);\n continue;\n }\n const key = row.path[0];\n if (row.path.length === 1 && !set) out.delete(key);\n else out.set(key, node);\n }\n return out;\n}\n\n/** One line of the starting state preview: a leaf's dotted path and how it reads. */\nexport interface StartingStateRow {\n path: string;\n /** `reference`: a string carrying a `{{ }}` reference, resolved when a run starts. */\n kind: \"literal\" | \"reference\";\n /** The reference text verbatim, or the literal as JSON. */\n text: string;\n}\n\nconst REFERENCE = /\\{\\{[\\s\\S]*?\\}\\}/;\n\n/**\n * The starting state flattened to one row per leaf, in key order: nested objects descend\n * (`a.b`), arrays and empty objects stay one literal row. A string with a `{{ }}` reference is a\n * `reference` row shown as typed, never as a value: it only resolves when a run starts.\n */\nexport function startingStateRows(\n initial: Record<string, unknown> | undefined,\n): StartingStateRow[] {\n const out: StartingStateRow[] = [];\n const walk = (value: unknown, path: string) => {\n if (isPlainObject(value) && Object.keys(value).length > 0) {\n for (const [k, v] of Object.entries(value)) walk(v, path ? `${path}.${k}` : k);\n return;\n }\n if (typeof value === \"string\" && REFERENCE.test(value)) {\n out.push({ path, kind: \"reference\", text: value });\n return;\n }\n out.push({ path, kind: \"literal\", text: JSON.stringify(value) ?? String(value) });\n };\n if (initial) for (const [k, v] of Object.entries(initial)) walk(v, k);\n return out;\n}\n","import { useQueryClient } from \"@tanstack/react-query\";\n/**\n * The workflow rail's State tool: a panel with two sections, kept apart because they are two\n * different things.\n *\n * - **Current state** — the state tree of this workflow's latest run (any run: the header Run,\n * ▶ run-from-node, a schedule), as a collapsible JSON tree (`ResultViewer`), with the run's id\n * and start time, a link that opens that run on the canvas, and the step that last wrote each\n * top-level key (`GET /runs/:id/state-writes`). It follows the run while it is in flight\n * (`useLiveRunQuery` + `useRunStateWritesQuery`, the same queries — and so the same cache — the\n * editor's run log reads) and re-reads the run list once it finishes.\n * - **Starting state** — a read-only preview of `Workflow.initialState`, with `{{ }}` references\n * shown as references, and \"Edit starting state\", which opens the editor's starting state\n * editor (`StartingStateModal`) through the `onOpenStartingState` the canvas editor publishes.\n *\n * The strip dot still says the workflow has starting state. Hidden wherever no workflow editor\n * published that opener (Functions, Endpoints, a list).\n */\nimport type { StateLogRow } from \"@w6w/expr\";\nimport { Icon, ResultViewer } from \"@w6w/ui\";\nimport { useEffect, useRef } from \"react\";\nimport type { RailTool } from \"../chrome/RightRail.tsx\";\nimport type { WorkspaceCallable } from \"../chrome/workspace.tsx\";\nimport { WorkflowVariablesEditor } from \"../editor/WorkflowVariablesEditor.tsx\";\nimport { startingDataCollisions } from \"../lib/starting-data.ts\";\nimport { runStateTree, startingStateRows, stateKeyWriters } from \"../lib/state-panel.ts\";\nimport { shouldContinuePolling } from \"../lib/workflow-live-run.ts\";\nimport {\n runsKey,\n useLiveRunQuery,\n useRunStateWritesQuery,\n useRunsQuery,\n} from \"../repos/workflows.ts\";\n\ntype WorkflowCtx = Extract<WorkspaceCallable, { kind: \"workflow\" }>;\n\nfunction opener(ctx: WorkspaceCallable): (() => void) | undefined {\n return ctx?.kind === \"workflow\" ? ctx.onOpenStartingState : undefined;\n}\n\nfunction StartingStateToolIcon() {\n return <Icon name=\"database\" />;\n}\n\nfunction CurrentStateSection({ ctx }: { ctx: WorkflowCtx }) {\n const qc = useQueryClient();\n const runsQuery = useRunsQuery(ctx.id);\n const latest = runsQuery.data?.[0];\n const runQuery = useLiveRunQuery(latest?.runId ?? null);\n const status = runQuery.data?.status ?? latest?.status;\n const writesQuery = useRunStateWritesQuery(latest?.runId ?? null, status);\n const finished = status !== undefined && !shouldContinuePolling(status);\n\n // The list row was read while the run was in flight: once it finishes, read the list again\n // so the row (and a newer run, if one started meanwhile) is current. Once per run, so a row\n // the server still answers without `finishedAt` cannot loop the refetch.\n const refreshedFor = useRef<string | null>(null);\n useEffect(() => {\n if (!finished || !latest || latest.finishedAt !== null) return;\n if (refreshedFor.current === latest.runId) return;\n refreshedFor.current = latest.runId;\n void qc.invalidateQueries({ queryKey: runsKey(ctx.id) });\n }, [finished, latest, qc, ctx.id]);\n\n if (runsQuery.isLoading) return <p className=\"muted small\">Loading…</p>;\n if (!latest) {\n return (\n <p className=\"muted small\" data-testid=\"rail-state-current-empty\">\n No run yet. Run the workflow and the state it ends with shows here.\n </p>\n );\n }\n\n const writes: readonly StateLogRow[] = writesQuery.data?.writes ?? [];\n const snapshot = (runQuery.data as { state?: unknown } | undefined)?.state;\n const tree = runStateTree(snapshot, writes);\n const writers = stateKeyWriters(writes);\n const keys = tree ? Object.keys(tree) : [];\n\n return (\n <div className=\"w6w-stack\" data-testid=\"rail-state-current\">\n <dl className=\"rail-meta-list\">\n <dt>Run</dt>\n <dd>\n <code data-testid=\"rail-state-run-id\">{latest.runId}</code>\n </dd>\n <dt>Started</dt>\n <dd>{new Date(latest.startedAt).toLocaleString()}</dd>\n <dt>Status</dt>\n <dd data-testid=\"rail-state-run-status\">{status}</dd>\n </dl>\n {ctx.onOpenRun && (\n <button\n type=\"button\"\n className=\"btn ghost\"\n data-testid=\"rail-state-open-run\"\n onClick={() => ctx.onOpenRun?.(latest.runId)}\n >\n Open this run\n </button>\n )}\n {runQuery.isLoading ? (\n <p className=\"muted small\">Loading…</p>\n ) : keys.length === 0 || !tree ? (\n <p className=\"muted small\" data-testid=\"rail-state-current-none\">\n This run has no state.\n </p>\n ) : (\n <>\n <ResultViewer value={tree} />\n <ul className=\"list\" data-testid=\"rail-state-writers\">\n {keys.map((key) => {\n const node = writers.get(key);\n return (\n <li key={key} data-testid=\"rail-state-writer\">\n <span className=\"list-main\">\n <code>{key}</code>\n <span className=\"muted small block\">\n {node ? (\n <>\n Last written by <code>{node}</code>\n </>\n ) : writers.has(key) ? (\n \"From the starting state\"\n ) : (\n \"No step wrote it\"\n )}\n </span>\n </span>\n </li>\n );\n })}\n </ul>\n {writesQuery.data?.truncated && (\n <p className=\"muted small\">\n The run's state log reached its limit, so later writers aren't shown.\n </p>\n )}\n </>\n )}\n </div>\n );\n}\n\nfunction StartingStateSection({ ctx }: { ctx: WorkflowCtx }) {\n const rows = startingStateRows(ctx.startingState);\n const collisions = startingDataCollisions(ctx.startingState, ctx.variables ?? []);\n return (\n <div className=\"w6w-stack\" data-testid=\"rail-state-starting\">\n <p className=\"muted small\">\n Workflow inputs override starting state; starting state overrides project variables with the\n same name.\n </p>\n {collisions.length > 0 && (\n <p className=\"muted small\" data-testid=\"starting-data-collision\">\n Overridden by workflow inputs: {collisions.join(\", \")}.\n </p>\n )}\n <button\n type=\"button\"\n className=\"btn\"\n data-testid=\"rail-state-edit-starting\"\n onClick={() => ctx.onOpenStartingState?.()}\n >\n Edit starting state\n </button>\n {rows.length === 0 ? (\n <p className=\"muted small\" data-testid=\"rail-state-starting-empty\">\n No starting state. Every run begins with an empty state.\n </p>\n ) : (\n <ul className=\"list\">\n {rows.map((row) => (\n <li key={row.path} data-testid=\"rail-state-starting-row\" data-kind={row.kind}>\n <span className=\"list-main\">\n <code>{row.path}</code>\n <span className=\"muted small block\">\n {row.kind === \"reference\" ? (\n <>\n Reference <code>{row.text}</code>, resolved when a run starts\n </>\n ) : (\n <code>{row.text}</code>\n )}\n </span>\n </span>\n </li>\n ))}\n </ul>\n )}\n </div>\n );\n}\n\nfunction StatePanel({ ctx }: { ctx: WorkspaceCallable }) {\n // Defensive, as in the other tools: `isAvailable` keeps this off the strip for any other ctx.\n if (ctx?.kind !== \"workflow\" || !ctx.onOpenStartingState) return null;\n return (\n <div className=\"w6w-stack\" data-testid=\"rail-state-body\">\n <div className=\"right-rail-panel-head\">\n <h3>Data</h3>\n </div>\n {ctx.onVariablesChange && (\n <section data-testid=\"rail-workflow-variables\">\n <h4>Workflow inputs</h4>\n <WorkflowVariablesEditor\n variables={ctx.variables ?? []}\n onVariablesChange={ctx.onVariablesChange}\n />\n </section>\n )}\n <section data-testid=\"rail-state-current-section\">\n <h4>Current state</h4>\n <CurrentStateSection ctx={ctx} />\n </section>\n <hr />\n <section data-testid=\"rail-state-starting-section\">\n <h4>Starting state</h4>\n <StartingStateSection ctx={ctx} />\n </section>\n </div>\n );\n}\n\nexport const startingStateTool: RailTool = {\n id: \"starting-state\",\n title: \"Data\",\n rendersHeading: true,\n Icon: StartingStateToolIcon,\n isAvailable: (ctx) => opener(ctx) !== undefined,\n Panel: StatePanel,\n hasIndicator: (ctx) => ctx?.kind === \"workflow\" && ctx.hasStartingState === true,\n};\n","/**\n * The rail tools `<WorkflowEditor>`, `<CallableRail>` and Studio's rail mount, in display order.\n * Each serves workflow, function and endpoint resources (`isAvailable` decides per context); the\n * Aliases tool is deliberately absent (alias management is Studio-only). Reachable from the `chrome` subpath, never from the package root barrel — the\n * Error handling tool pulls in `@w6w/ui/flow`.\n */\nimport type { RailTool } from \"../chrome/RightRail.tsx\";\nimport { codeTool } from \"./CodeTool.tsx\";\nimport { connectionsTool } from \"./ConnectionsTool.tsx\";\nimport { errorHandlingTool } from \"./ErrorHandlingTool.tsx\";\nimport { historyTool } from \"./HistoryTool.tsx\";\nimport { settingsTool } from \"./SettingsTool.tsx\";\nimport { startingStateTool } from \"./StartingStateTool.tsx\";\n\nexport const editorRailTools: readonly RailTool[] = [\n settingsTool,\n codeTool,\n errorHandlingTool,\n startingStateTool,\n connectionsTool,\n historyTool,\n];\n"],"names":["WorkspaceContext","createContext","WorkspaceProvider","children","base","override","setCallable","useState","resource","value","useMemo","jsx","useHasWorkspace","useContext","useWorkspace","ctx","key","useEffect","useWorkspaceCallable","CLOSED","readStoredState","raw","activeTool","restoreRailState","RailShell","tools","state","onToggle","t","ActivePanel","jsxs","tool","_a","PersistedRail","storageKey","setState","id","prev","RightRail","available","useProjectExpressionOptions","project","projectId","varsQuery","useVarsQuery","secretsQuery","useSecretsQuery","constantsQuery","useConstantsQuery","documentsQuery","useDocumentsQuery","sealSecretFn","useSealSecret","createVarMut","useCreateVarMutation","createSecretMut","useCreateSecretMutation","v","c","s","projectDocumentSources","documentSampleValues","input","ProjectExpressionScope","options","ExpressionOptionsProvider","CodePanel","openTab","setOpenTab","snippetCallable","toSnippetCallable","triggers","tabs","snippetTabsFor","unavailableReason","label","icon","Icon","Modal","CallFromCodeBody","CodeToolIcon","codeTool","isAvailable","connectionsTool","WorkflowConnectionsPanel","DEFAULT_ENV","RailEnvContext","RailEnvProvider","onNavigate","useRailEnv","CALL_APP","refOf","target","nounOf","ErrorHandlerSection","kind","policy","ready","saving","onPersist","functionsQuery","useFunctionsQuery","workflowsQuery","useWorkflowsQuery","pickerOpen","setPickerOpen","error","setError","ref","selfDecision","errorHandlerSelfDecision","_b","_d","_c","w","fn","f","persist","next","pickHandler","built","nextTarget","nextId","RetryPolicyFields","StepBuilderModal","BufferErrorHandlingPanel","onPolicyChange","policyFromDefinition","CachedErrorHandlingPanel","fnQuery","useFunctionQuery","epQuery","useEndpointQuery","saveFnMut","useGuardedSaveFunctionMutation","saveEpMut","useGuardedSaveEndpointMutation","record","callableRecord","onError","vars","definitionWithPolicy","settled","e","ApiError","ErrorHandlingPanel","ErrorHandlingToolIcon","errorHandlingTool","isSettingsRailAvailable","historyTool","commitTag","tags","typed","removeTag","tag","TagEditor","onChange","setTyped","handleTypedChange","result","IconButton","CallableSettingsModal","props","settings","descriptorFor","initial","displayName","setDisplayName","setKey","setTags","isSaving","setIsSaving","displayNameChanged","keyChanged","tagsChanged","isDirty","canEditKey","keyGrammarOk","isEndpointKey","canSubmit","handleSave","enterSubmit","useEnterSubmit","filterKeyInput","TESTIDS","VersionHistoryModal","versionNumber","testids","versionQuery","useVersionQuery","revertMut","useRevertMutation","invokeMut","useInvokeVersionMutation","confirmingRevert","setConfirmingRevert","restoreError","setRestoreError","Fragment","CodeBlock","ConfirmModal","DangerZone","archived","deleteLabel","deleteTestId","archiveTestId","onRequestDelete","onRequestArchive","deleteError","archiveError","DeleteButton","SettingsHeading","EditButton","MetadataSection","fields","row","SpecActionsTrigger","SpecChooserModal","onImport","onClose","VersionSection","open","versions","VersionListModal","loading","DANGER_COPY","SettingsDangerZone","copy","IMPORT_LIST_KEYS","functionsKey","endpointsKey","workflowsKey","WorkflowSettingsPanel","editingSettings","setEditingSettings","historyOpen","setHistoryOpen","versionListOpen","setVersionListOpen","isWorkflow","wfDefQuery","useWorkflowQuery","saveWfMut","useSaveWorkflowMutation","archiveWfMut","useArchiveWorkflowMutation","deleteWfMut","useDeleteWorkflowMutation","deleting","useRef","specMenuOpen","setSpecMenuOpen","importing","setImporting","exporting","setExporting","deleteConfirming","setDeleteConfirming","archiveConfirming","setArchiveConfirming","setDeleteError","setArchiveError","specQuery","useSpecQuery","specCollectionForKind","versionsQuery","useVersionsQuery","publishMut","usePublishMutation","setEnabledMut","useSetEnabledMutation","publishError","setPublishError","enableError","setEnableError","openVersion","setOpenVersion","listRow","onDelete","onArchive","metadataFieldsForKind","data","stored","resolve","reject","updated","ImportSpecModal","newId","SettingsToolPanel","CallableSettingsPanel","kind0","endpointsQuery","useEndpointsQuery","editing","setEditing","editText","setEditText","editError","setEditError","editToken","setEditToken","fnDefQuery","epDefQuery","deleteFnMut","useDeleteFunctionMutation","deleteEpMut","useDeleteEndpointMutation","archiveFnMut","useArchiveFunctionMutation","archiveEpMut","useArchiveEndpointMutation","specCollection","versionsKind","hasVersionHistory","def","defJson","openEdit","editEval","evaluateEdit","savingDef","onSaveEdit","onSettled","hasDefinitionActions","JsonEditor","hasDelete","k","SettingsToolIcon","settingsTool","VARIABLE_TYPES","WorkflowVariablesEditor","variables","onVariablesChange","inheritedVars","useExpressionOptions","addVariable","updateVariable","i","idx","removeVariable","_","dupIndexes","duplicateKeyIndexes","varsRailFor","ExpressionInput","isPlainObject","runStateTree","snapshot","writes","foldStateLog","stateKeyWriters","out","rows","a","b","node","set","REFERENCE","startingStateRows","walk","path","opener","StartingStateToolIcon","CurrentStateSection","qc","useQueryClient","runsQuery","useRunsQuery","latest","runQuery","useLiveRunQuery","status","writesQuery","useRunStateWritesQuery","finished","shouldContinuePolling","refreshedFor","runsKey","tree","writers","keys","ResultViewer","_e","StartingStateSection","collisions","startingDataCollisions","StatePanel","startingStateTool","editorRailTools"],"mappings":";;;;;;;;;;;;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