@w6w/embed 0.2.34 → 0.2.35

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.
Files changed (74) hide show
  1. package/dist/{CreateFunctionModal-glk2zg1r.js → CreateFunctionModal-CYNHJUGJ.js} +3 -3
  2. package/dist/{CreateFunctionModal-glk2zg1r.js.map → CreateFunctionModal-CYNHJUGJ.js.map} +1 -1
  3. package/dist/{DocumentFormModal-B3OkvI5v.js → DocumentFormModal-CLmdGx34.js} +2 -2
  4. package/dist/{DocumentFormModal-B3OkvI5v.js.map → DocumentFormModal-CLmdGx34.js.map} +1 -1
  5. package/dist/ImportSpecModal-BzEyiNWD.js +378 -0
  6. package/dist/ImportSpecModal-BzEyiNWD.js.map +1 -0
  7. package/dist/WorkflowEditor-CxTuK8_d.js +1272 -0
  8. package/dist/WorkflowEditor-CxTuK8_d.js.map +1 -0
  9. package/dist/{apps-CFWdgGst.js → apps-CyEszfIu.js} +33 -33
  10. package/dist/{apps-CFWdgGst.js.map → apps-CyEszfIu.js.map} +1 -1
  11. package/dist/callable-row-actions-BPBPflMn.js +56 -0
  12. package/dist/callable-row-actions-BPBPflMn.js.map +1 -0
  13. package/dist/callables-dLF2IcwA.js +317 -0
  14. package/dist/callables-dLF2IcwA.js.map +1 -0
  15. package/dist/chrome/TagEditor.d.ts +6 -1
  16. package/dist/chrome/workspace.d.ts +16 -0
  17. package/dist/documents-hgltn0xe.js +1017 -0
  18. package/dist/documents-hgltn0xe.js.map +1 -0
  19. package/dist/draft.mjs +1 -1
  20. package/dist/editor/WaitingForm.d.ts +19 -0
  21. package/dist/{editor-apps-ShwCmvLY.js → editor-apps-DsGrGKfe.js} +3 -3
  22. package/dist/{editor-apps-ShwCmvLY.js.map → editor-apps-DsGrGKfe.js.map} +1 -1
  23. package/dist/{editor-tools-rY9nddqr.js → editor-tools-Ct7YPPj8.js} +682 -784
  24. package/dist/editor-tools-Ct7YPPj8.js.map +1 -0
  25. package/dist/editor.mjs +1 -1
  26. package/dist/editors.mjs +18 -18
  27. package/dist/{endpoints-zOuwci2U.js → endpoints-DJxXRh-I.js} +12 -12
  28. package/dist/{endpoints-zOuwci2U.js.map → endpoints-DJxXRh-I.js.map} +1 -1
  29. package/dist/forms.mjs +1 -1
  30. package/dist/index.mjs +140 -115
  31. package/dist/index.mjs.map +1 -1
  32. package/dist/lib/callable-row-actions.d.ts +17 -0
  33. package/dist/lib/index.d.ts +2 -0
  34. package/dist/lib/run-event-stream.d.ts +122 -0
  35. package/dist/lib/tag-editor.d.ts +6 -0
  36. package/dist/lib/workflow-live-run.d.ts +7 -0
  37. package/dist/lib/workflow-validity.d.ts +7 -1
  38. package/dist/lib.mjs +52 -47
  39. package/dist/lists/CallableKindList.d.ts +12 -0
  40. package/dist/lists/CallableRowParts.d.ts +8 -1
  41. package/dist/lists/EndpointList.d.ts +3 -0
  42. package/dist/lists/FunctionList.d.ts +3 -0
  43. package/dist/lists/WorkflowList.d.ts +3 -0
  44. package/dist/lists.d.ts +1 -0
  45. package/dist/lists.mjs +1589 -1513
  46. package/dist/lists.mjs.map +1 -1
  47. package/dist/rail.mjs +1 -1
  48. package/dist/repos/callables.d.ts +25 -0
  49. package/dist/repos/documents.d.ts +9 -1
  50. package/dist/repos/saved-file-names.d.ts +10 -0
  51. package/dist/repos/workflows.d.ts +19 -13
  52. package/dist/repos.mjs +333 -328
  53. package/dist/{setup-incomplete-BHs3Lpfy.js → setup-incomplete-6PAbN0EW.js} +50 -49
  54. package/dist/setup-incomplete-6PAbN0EW.js.map +1 -0
  55. package/dist/spec-import-BKyfhTYG.js +200 -0
  56. package/dist/spec-import-BKyfhTYG.js.map +1 -0
  57. package/dist/{use-callable-draft-w4tDTYcb.js → use-callable-draft-7HwfTuYQ.js} +3 -3
  58. package/dist/{use-callable-draft-w4tDTYcb.js.map → use-callable-draft-7HwfTuYQ.js.map} +1 -1
  59. package/package.json +3 -3
  60. package/src/styles.css +43 -0
  61. package/dist/ImportSpecModal-SQvTwtcX.js +0 -252
  62. package/dist/ImportSpecModal-SQvTwtcX.js.map +0 -1
  63. package/dist/WorkflowEditor-D2EfEP-U.js +0 -1201
  64. package/dist/WorkflowEditor-D2EfEP-U.js.map +0 -1
  65. package/dist/callable-record-Bhxim8C1.js +0 -14
  66. package/dist/callable-record-Bhxim8C1.js.map +0 -1
  67. package/dist/callables-B49tS2vv.js +0 -297
  68. package/dist/callables-B49tS2vv.js.map +0 -1
  69. package/dist/editor-tools-rY9nddqr.js.map +0 -1
  70. package/dist/setup-incomplete-BHs3Lpfy.js.map +0 -1
  71. package/dist/spec-import-CPbDnnuv.js +0 -272
  72. package/dist/spec-import-CPbDnnuv.js.map +0 -1
  73. package/dist/workflows-RhR8kwt7.js +0 -667
  74. package/dist/workflows-RhR8kwt7.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"documents-hgltn0xe.js","sources":["../src/lib/workflow-live-run.ts","../src/lib/workflow-poll.ts","../src/lib/history-query.ts","../src/lib/run-event-stream.ts","../src/repos/workflows.ts","../src/repos/documents.ts"],"sourcesContent":["/**\n * Pure decision layer for the visual editor's live Run/Stop feature (T2.1.1,\n * A7). Every judgment call this feature makes that is NOT layout — is a run\n * in flight? should polling continue? is the canvas editable right now? what\n * should the Run button say and is it disabled? how does a cancel failure\n * get handled? how does a `RunState`'s steps map to the execution log\n * panel's rows, and what error does each row and the run show? what `input`\n * does the header Run send? — lives here as plain functions of (run state) -> result,\n * with no `.tsx` import and no React import, so `node --test` can load this\n * module directly. Same mechanical reason `workflow-poll.ts` and\n * `repos/reliability-uptime.ts` exist as separate `.ts` modules — read\n * `workflow-poll.ts`'s own header. `WorkflowsPage.tsx` calls these functions\n * rather than restating the conditions inline.\n */\nimport { type StateLogRow, foldStateLog } from \"@w6w/expr\";\nimport { type RunStatus, isTerminalRunStatus } from \"@w6w/sdk\";\n\nexport type { RunStatus };\n\n/**\n * The five states a workflow step's execution can be in — a thin LOCAL copy\n * of `@w6w/ui`'s `StepStatus` (itself a thin local copy of the engine's\n * `StepStatus` — see `run-visuals.ts`'s own header in `packages/ui`, the\n * same house idiom). `@w6w/sdk/console`'s `RunState.steps` is deliberately\n * typed `Record<string, unknown>` — opaque pass-through, by that module's\n * own documented design — so the real per-step shape has to be re-stated\n * here rather than imported.\n */\nexport type StepStatus = \"pending\" | \"running\" | \"succeeded\" | \"failed\" | \"skipped\";\n\n/** The per-step metadata (which app/version/action/connection ran) — one\n * local structural copy of the pinned `StepMeta`. A `type` alias, not an\n * `interface`, so it stays assignable to index-signature types. */\nexport type StepMetaLike = {\n app: string;\n version: string;\n action: string;\n connectionId: string | null;\n};\n\n/** The slice of a `StepExecution` this module reads, to build one\n * `ExecutionLogPanel` row. */\nexport interface StepExecutionLike {\n status: StepStatus;\n /** Why a `skipped` step did not run (`NodeExecution.skipReason`); read as `unknown` (opaque\n * wire) and carried only when it is one of the four known reasons. */\n skipReason?: unknown;\n startedAt?: string;\n finishedAt?: string;\n input?: unknown;\n output?: unknown;\n logs?: string[];\n /** `StepExecution.error` — a `StepError` on `failed` per rfcs/workflow.md\n * §StepExecution, but read as `unknown` because `RunState.steps` is opaque\n * on the wire; {@link toLogError} normalises whatever actually arrives. */\n error?: unknown;\n /** Recorded metadata; absent (or null) for steps that recorded none. */\n meta?: StepMetaLike | null;\n /** `NodeExecution.usage` — the step's sandbox figures; read as `unknown` (opaque wire). */\n usage?: unknown;\n /** For each only (I3): per-iteration body records, read as `unknown` (opaque wire). */\n iterations?: unknown;\n iterationsTotal?: unknown;\n iterationsFailed?: unknown;\n iterationsTruncated?: unknown;\n}\n\n/** A step or run error, as the run log panel renders it — field-for-field\n * `@w6w/ui`'s `ExecutionLogError` (rfcs/workflow.md §StepError's\n * `code`/`message`/`phase`/`retryable`), restated locally for the same reason\n * as {@link ExecutionLogStepLike} below. `message` is never empty. */\nexport interface LogErrorLike {\n code?: string;\n message: string;\n phase?: string;\n retryable?: boolean;\n}\n\n/** One `RunState.stepErrors` entry the panel shows at run level — field-for-field\n * `@w6w/ui`'s `ExecutionLogRecordedError`, restated locally (see above). */\nexport interface RecordedLogErrorLike {\n stepId: string;\n label?: string;\n error: LogErrorLike;\n}\n\n/** The slice of a `RunState` {@link runLevelErrors} reads. */\nexport interface RunErrorSourceLike {\n status?: string;\n error?: unknown;\n stepErrors?: ReadonlyArray<{ nodeId?: string; stepId?: string; error: unknown }>;\n}\n\n/** The per-node execution map of a run record, in either shape — `nodes`\n * preferred, else the legacy `steps`. */\nexport function runNodeMap(\n run: { nodes?: unknown; steps?: unknown } | undefined | null,\n): Record<string, StepExecutionLike> | undefined {\n return (run?.nodes ?? run?.steps ?? undefined) as Record<string, StepExecutionLike> | undefined;\n}\n\n/** The slice of a saved step-test fixture (`StepTest`) {@link latestFixtureInput}\n * reads — `with` is what the trigger's Test tab invokes it with. */\nexport interface StepTestFixtureLike {\n with?: unknown;\n}\n\n/** The row-level fallback for a `failed` step that carries no `error` at all. */\nexport const STEP_FAILED_NO_REASON = \"Node failed without reporting a reason.\";\n\n/** The run-level fallback for a `failed` run where nothing carries a reason. */\nexport const RUN_FAILED_NO_REASON = \"Run failed without reporting a reason.\";\n\n/** One `ExecutionLogPanel` row — field-for-field `@w6w/ui`'s\n * `ExecutionLogStep`, restated locally for the same reason as\n * {@link StepExecutionLike} above (no runtime dependency on `@w6w/ui`,\n * which this module must not import — see the file header). */\nexport interface ExecutionLogStepLike {\n id: string;\n status: StepStatus;\n skipReason?: SkipReasonLike;\n startedAt?: string;\n finishedAt?: string;\n input?: unknown;\n output?: unknown;\n logs?: string[];\n error?: LogErrorLike;\n meta?: StepMetaLike;\n /** Peak memory and CPU time, the finite non-negative figures only (`@w6w/ui`'s `usage`). */\n usage?: { memoryBytes?: number; cpuMs?: number };\n /** For each only (I4) — field-for-field `@w6w/ui`'s `ExecutionLogStep`. */\n iterations?: ExecutionLogIterationLike[];\n iterationsTotal?: number;\n iterationsFailed?: number;\n iterationsTruncated?: boolean;\n /** This node's state writes (`GET /runs/:id/state-writes` rows, in `seq` order) —\n * field-for-field `@w6w/ui`'s `ExecutionLogStep.stateWrites` (plan §2.7). Absent → no State block. */\n stateWrites?: StateWriteEntryLike[] | null;\n /** The state tree right after this node's last write (`foldStateLog`). */\n stateAfter?: Record<string, unknown> | null;\n}\n\n/** One state-write entry on a run-log row — `@w6w/ui`'s `ExecutionLogStep.stateWrites[number]`. */\nexport type StateWriteEntryLike = {\n path: string[];\n item?: number;\n old?: unknown;\n new?: unknown;\n warning?: string;\n};\n\n/** One For each iteration row (I4) — mirrors `@w6w/ui`'s `ExecutionLogIteration`. */\nexport interface ExecutionLogIterationLike {\n index: number;\n status: \"succeeded\" | \"failed\" | \"running\";\n failedNodeId?: string;\n steps: ExecutionLogStepLike[];\n}\n\n/** How a cancel-request failure should be handled (A6). */\nexport type CancelErrorOutcome = \"reconcile\" | \"surface\";\n\n/**\n * A2/M1 — the `refetchInterval` decision: keep polling (`true`) until the\n * run's status is terminal (`false`), including while no run has answered\n * yet (`status === undefined` — the very first poll hasn't landed, or no run\n * is active at all).\n */\nexport function shouldContinuePolling(status: RunStatus | undefined): boolean {\n return status === undefined || !isTerminalRunStatus(status);\n}\n\n/**\n * A4/M2/M3 — is a run currently \"in flight\" from this page's point of view?\n * `true` only while the poll has a live, non-terminal status AND the poll\n * itself hasn't given up/errored — a failed poll unlocks the canvas exactly\n * like reaching a real terminal status does (A4's own named failure case: \"a\n * canvas that stays locked after a cancel\"). Drives the canvas's `readOnly`\n * prop, the Stop button's visibility, and the Run button's disabled state —\n * one function, three call sites, so they can never drift out of sync with\n * each other.\n */\nexport function isRunInFlight(status: RunStatus | undefined, pollFailed: boolean): boolean {\n if (pollFailed) return false;\n if (status === undefined) return false;\n return !isTerminalRunStatus(status);\n}\n\n/**\n * When a run turns terminal, how long after (ms) the editor re-reads the workflow's saved step\n * tests. The server books every step that succeeded in an editor run as its passing saved test\n * (`step-passes.ts`) — the record the publish gate reads — but only AFTER the engine has\n * checkpointed the run's terminal state, so the poll can see `succeeded` a few milliseconds before\n * the pass lands. The immediate read covers the usual case; the later one covers that window.\n */\nexport const STEP_PASS_REFRESH_DELAYS_MS: readonly number[] = [0, 1500];\n\n/**\n * Should the editor re-read this workflow's saved step tests now? Only once the run it polls is\n * terminal and belongs to the open workflow — a run's passes are booked as it finishes, and the\n * step-tests cache never refetches on its own (`refetchOnWindowFocus: false`), so without this\n * the publish gate keeps the pre-run list and a step that just passed still blocks Publish.\n */\nexport function stepPassRefreshDue(\n status: RunStatus | undefined,\n runWorkflowId: string | undefined,\n workflowId: string,\n): boolean {\n return status !== undefined && isTerminalRunStatus(status) && runWorkflowId === workflowId;\n}\n\n/** A1/A6 — what the Run button should read right now. */\nexport function runButtonLabel(status: RunStatus | undefined, pollFailed: boolean): string {\n if (!isRunInFlight(status, pollFailed)) return \"Run\";\n return status === \"queued\" ? \"Queued…\" : \"Running…\";\n}\n\n/**\n * A6/M6 — classify a `cancel()` failure. `run_not_cancelable` (409) means\n * the run already reached a terminal state before the cancel request landed\n * — not a user-facing error, just reconcile to whatever the next poll\n * reports. Everything else (`unknown_run`, a network failure, …) is a real\n * failure the page's existing error affordance must show.\n */\nexport function classifyCancelError(code: string): CancelErrorOutcome {\n return code === \"run_not_cancelable\" ? \"reconcile\" : \"surface\";\n}\n\n/**\n * G5 — map a `RunState`'s opaque `steps` record onto `ExecutionLogPanel`'s\n * row shape, preserving its keys and timestamps. Record key order is not\n * execution order; `ExecutionLogPanel` sorts the rows chronologically for\n * both live runs and saved history.\n */\nexport function mapRunStateToLogSteps(\n steps: Record<string, StepExecutionLike> | undefined,\n stateLog?: readonly StateLogRow[],\n): ExecutionLogStepLike[] {\n if (!steps) return [];\n const state = stateLog ? stateFieldsByNode(stateLog) : undefined;\n return Object.entries(steps).map(([id, step]) => ({\n ...mapStep(id, step),\n ...iterationFields(step),\n ...(state?.get(id) ?? {}),\n }));\n}\n\n/**\n * The run's state-write log (`GET /runs/:id/state-writes`) grouped by node, in `seq`\n * order whatever order the rows arrive in: each node's entries (only `path` plus the\n * `item`/`old`/`new`/`warning` a row has — never `seq`/`nodeId`/`step`) and the tree\n * right after its last row, folded by `@w6w/expr`'s `foldStateLog` (one fold for the\n * whole product, R18). Rows with a null `nodeId` (the base row) attach to no node but\n * still seed every fold.\n */\nfunction stateFieldsByNode(\n log: readonly StateLogRow[],\n): Map<string, Pick<ExecutionLogStepLike, \"stateWrites\" | \"stateAfter\">> {\n const rows = [...log].sort((a, b) => a.seq - b.seq);\n const byNode = new Map<string, { writes: StateWriteEntryLike[]; lastSeq: number }>();\n for (const row of rows) {\n if (row.nodeId === null || row.nodeId === undefined) continue;\n const entry: StateWriteEntryLike = { path: row.path };\n if (row.item !== undefined) entry.item = row.item;\n if (row.old !== undefined) entry.old = row.old;\n if (row.new !== undefined) entry.new = row.new;\n if (row.warning !== undefined) entry.warning = row.warning;\n const group = byNode.get(row.nodeId) ?? { writes: [], lastSeq: row.seq };\n group.writes.push(entry);\n group.lastSeq = row.seq;\n byNode.set(row.nodeId, group);\n }\n const out = new Map<string, Pick<ExecutionLogStepLike, \"stateWrites\" | \"stateAfter\">>();\n for (const [id, { writes, lastSeq }] of byNode) {\n out.set(id, { stateWrites: writes, stateAfter: foldStateLog(rows, lastSeq) });\n }\n return out;\n}\n\n/** `@w6w/ui`'s `SkipReason`, restated locally (see {@link ExecutionLogStepLike}). */\nexport type SkipReasonLike = \"not_on_path\" | \"condition\" | \"stopped\" | \"disabled\";\n\nconst SKIP_REASONS: ReadonlySet<unknown> = new Set([\n \"not_on_path\",\n \"condition\",\n \"stopped\",\n \"disabled\",\n]);\n\n/** One wire record -> one row (shared by top-level rows and iteration body steps). */\nfunction mapStep(id: string, step: StepExecutionLike): ExecutionLogStepLike {\n return {\n id,\n status: step.status,\n ...(step.status === \"skipped\" && SKIP_REASONS.has(step.skipReason)\n ? { skipReason: step.skipReason as SkipReasonLike }\n : {}),\n startedAt: step.startedAt,\n finishedAt: step.finishedAt,\n input: step.input,\n output: step.output,\n ...(Array.isArray(step.logs) && step.logs.length\n ? { logs: step.logs.filter((line): line is string => typeof line === \"string\") }\n : {}),\n ...(step.meta !== undefined && step.meta !== null ? { meta: step.meta } : {}),\n ...usageOf(step.usage),\n ...rowError(step),\n };\n}\n\n/** `{ usage }` holding only the finite, non-negative figures of a recorded `usage`; `{}` without any. */\nfunction usageOf(raw: unknown): Pick<ExecutionLogStepLike, \"usage\"> {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return {};\n const ok = (v: unknown): v is number => typeof v === \"number\" && Number.isFinite(v) && v >= 0;\n const { memoryBytes, cpuMs } = raw as Record<string, unknown>;\n const usage = {\n ...(ok(memoryBytes) ? { memoryBytes } : {}),\n ...(ok(cpuMs) ? { cpuMs } : {}),\n };\n return Object.keys(usage).length ? { usage } : {};\n}\n\nconst ITERATION_STATUSES: ReadonlySet<unknown> = new Set([\"succeeded\", \"failed\", \"running\"]);\n\n/** The I4 `iterations*` keys for a For each record (I3) — empty (no own keys) when\n * `iterations` is not an array. */\nfunction iterationFields(\n step: StepExecutionLike,\n): Pick<\n ExecutionLogStepLike,\n \"iterations\" | \"iterationsTotal\" | \"iterationsFailed\" | \"iterationsTruncated\"\n> {\n if (!step || !Array.isArray(step.iterations)) return {};\n const iterations = (step.iterations as Array<Record<string, unknown> | null>)\n .filter((it): it is Record<string, unknown> => it !== null && typeof it === \"object\")\n .map((it) => {\n const nodes =\n it.nodes !== null && typeof it.nodes === \"object\"\n ? (it.nodes as Record<string, StepExecutionLike>)\n : {};\n // An inner For each is a body step with iterations of its own: recurse (nested loops).\n const steps = Object.entries(nodes).map(([id, s]) => ({\n ...mapStep(id, s),\n ...iterationFields(s),\n }));\n const failedNodeId =\n typeof it.failedNodeId === \"string\" && it.failedNodeId !== \"\"\n ? it.failedNodeId\n : steps.find((s) => s.status === \"failed\")?.id;\n const status = ITERATION_STATUSES.has(it.status)\n ? (it.status as ExecutionLogIterationLike[\"status\"])\n : steps.some((s) => s.status === \"failed\")\n ? \"failed\"\n : steps.some((s) => s.status === \"running\")\n ? \"running\"\n : \"succeeded\";\n return {\n index: it.index as number,\n status,\n ...(failedNodeId !== undefined ? { failedNodeId } : {}),\n steps,\n };\n })\n .sort((a, b) => a.index - b.index);\n const finite = (n: unknown): n is number => typeof n === \"number\" && Number.isFinite(n);\n return {\n iterations,\n ...(finite(step.iterationsTotal) ? { iterationsTotal: step.iterationsTotal } : {}),\n ...(finite(step.iterationsFailed) ? { iterationsFailed: step.iterationsFailed } : {}),\n ...(typeof step.iterationsTruncated === \"boolean\"\n ? { iterationsTruncated: step.iterationsTruncated }\n : {}),\n };\n}\n\n/** The `error` key for one row — present ONLY when the step reports an error\n * or is `failed` (then with {@link STEP_FAILED_NO_REASON}), so a healthy row\n * keeps exactly the shape it had before errors were carried. */\nfunction rowError(step: StepExecutionLike): { error?: LogErrorLike } {\n const error = toLogError(step.error);\n if (error) return { error };\n if (step.status === \"failed\") return { error: { message: STEP_FAILED_NO_REASON } };\n return {};\n}\n\n/**\n * Normalise whatever a step or run reported as its error into the panel's\n * {@link LogErrorLike}. `null`/`undefined` mean \"no error\". A non-empty string\n * is the message. An object contributes `code` (string), `message` (its own\n * non-empty `message`, else a non-empty `code`, else its JSON), `phase`\n * (string) and `retryable` (boolean). Anything else is stringified. The\n * returned `message` is never empty.\n */\nexport function toLogError(raw: unknown): LogErrorLike | undefined {\n if (raw === null || raw === undefined) return undefined;\n if (typeof raw === \"string\" && raw !== \"\") return { message: raw };\n if (typeof raw === \"object\") {\n const o = raw as Record<string, unknown>;\n const code = typeof o.code === \"string\" ? o.code : undefined;\n const message =\n typeof o.message === \"string\" && o.message !== \"\" ? o.message : code || safeJson(raw);\n return {\n ...(code !== undefined ? { code } : {}),\n message: message || \"Unknown error.\",\n ...(typeof o.phase === \"string\" ? { phase: o.phase } : {}),\n ...(typeof o.retryable === \"boolean\" ? { retryable: o.retryable } : {}),\n };\n }\n return { message: String(raw) || \"Unknown error.\" };\n}\n\n/** `JSON.stringify` that answers `\"\"` instead of throwing (a cycle, a BigInt)\n * or returning `undefined` (a `toJSON` that yields nothing). */\nfunction safeJson(raw: unknown): string {\n try {\n return JSON.stringify(raw) ?? \"\";\n } catch {\n return \"\";\n }\n}\n\n/**\n * The run-level half of the run log: `RunState.error` as `runError`, plus the\n * `RunState.stepErrors` entries whose step has NO row already carrying an\n * error (a `continue-record` failure is usually also on its own row — showing\n * it twice would read as two failures), in their given order. A row showing\n * only {@link STEP_FAILED_NO_REASON} does not count as carrying an error here,\n * so the reason recorded for that step is still surfaced. A `failed` run where\n * nothing — run, rows or surfaced step errors — carries a reason gets\n * {@link RUN_FAILED_NO_REASON}. `runError` is omitted when it duplicates a\n * row's error (equal `message` and equal `code`), since the step failure that\n * stopped the run is already shown on its row. It is likewise omitted when it\n * duplicates a surfaced `stepErrors` entry's error, by the same equality.\n * Keys are omitted when empty.\n */\nexport function runLevelErrors(\n run: RunErrorSourceLike | undefined,\n rows: ReadonlyArray<ExecutionLogStepLike>,\n): { runError?: LogErrorLike; stepErrors?: RecordedLogErrorLike[] } {\n if (!run) return {};\n const carried = new Set(rows.filter((r) => r.error !== undefined).map((r) => r.id));\n const reasoned = new Set(\n rows\n .filter((r) => r.error !== undefined && r.error.message !== STEP_FAILED_NO_REASON)\n .map((r) => r.id),\n );\n const stepErrors = (run.stepErrors ?? [])\n .map((e) => ({ e, id: e.nodeId ?? e.stepId ?? \"\" }))\n .filter(({ id }) => !reasoned.has(id))\n .map(({ e, id }) => ({\n stepId: id,\n error: toLogError(e.error) ?? { message: STEP_FAILED_NO_REASON },\n }));\n const own = toLogError(run.error);\n const sameAsOwn = (e: LogErrorLike | undefined) =>\n own !== undefined && e?.message === own.message && e?.code === own.code;\n const shown = rows.some((r) => sameAsOwn(r.error)) || stepErrors.some((e) => sameAsOwn(e.error));\n let runError = shown ? undefined : own;\n if (!runError && run.status === \"failed\" && carried.size === 0 && stepErrors.length === 0) {\n runError = { message: RUN_FAILED_NO_REASON };\n }\n return {\n ...(runError ? { runError } : {}),\n ...(stepErrors.length > 0 ? { stepErrors } : {}),\n };\n}\n\n/**\n * The header Run's `input`: the LAST saved fixture's `with` (`listStepTests`\n * answers oldest-first — the same \"last is latest\" reading\n * `@w6w/ui`'s `TriggerFillForm` seeds from), when it is a plain object.\n * Sent verbatim — `{type:\"expr\",…}` values included.\n */\nexport function latestFixtureInput(\n tests: ReadonlyArray<StepTestFixtureLike> | undefined,\n): Record<string, unknown> | undefined {\n const last = tests?.[tests.length - 1]?.with;\n if (last === null || typeof last !== \"object\" || Array.isArray(last)) return undefined;\n return last as Record<string, unknown>;\n}\n\n/**\n * Resolve the header Run's `input` for the manual trigger `triggerStepId`.\n * No trigger id → `undefined` without fetching. A fetch that throws or\n * rejects → `undefined`: a missing fixture never blocks the run. Fetched at\n * click time on purpose — a cached `stepTestsKey` query can be stale, since\n * saving a fixture does not invalidate it.\n */\nexport async function resolveHeaderRunInput(\n triggerStepId: string | undefined,\n list: (stepId: string) => Promise<ReadonlyArray<StepTestFixtureLike> | undefined>,\n remembered?: () => Promise<ReadonlyArray<{ nodeId: string; input: unknown }> | undefined>,\n): Promise<Record<string, unknown> | undefined> {\n if (!triggerStepId) return undefined;\n // The REMEMBERED test input (`node_test_inputs`) is what the trigger last ran with on any\n // editor surface, so it wins; a `{}` row was cleared (no `input`, no fixture fallback). No row\n // (or a failed read) falls back to the latest fixture, exactly as before.\n if (remembered) {\n try {\n const row = (await remembered())?.find((r) => r.nodeId === triggerStepId);\n if (row) {\n const input = row.input;\n if (input === null || typeof input !== \"object\" || Array.isArray(input)) return undefined;\n return Object.keys(input).length > 0 ? (input as Record<string, unknown>) : undefined;\n }\n } catch {\n // fall through to the fixture\n }\n }\n try {\n return latestFixtureInput(await list(triggerStepId));\n } catch {\n return undefined;\n }\n}\n\n/** The trigger the header Run starts at, and whether it is the Manual trigger. */\nexport interface HeaderRunEntry {\n id: string;\n manual: boolean;\n}\n\n/**\n * The trigger the header Run starts at, and so whose remembered sample payload it runs with: the\n * FIRST Manual trigger (a run's own default entry), else the first other entry trigger — a\n * webhook, a schedule or an app trigger. Before, only a Manual trigger was looked up, so a\n * webhook-started workflow's header Run sent no payload at all. `undefined` when nothing in\n * `steps` is a trigger. The predicates are injected (`@w6w/ui/flow`), as in `trigger-preview.ts`.\n */\nexport function headerRunEntry(\n steps: ReadonlyArray<{ id: string; uses?: { app?: string; trigger?: unknown } }>,\n isManualTrigger: (app: string) => boolean,\n isEntryTrigger: (uses: { app: string; trigger?: true }) => boolean,\n): HeaderRunEntry | undefined {\n const manual = steps.find((s) => !!s.uses?.app && isManualTrigger(s.uses.app));\n if (manual) return { id: manual.id, manual: true };\n const other = steps.find(\n (s) =>\n !!s.uses?.app &&\n isEntryTrigger({ app: s.uses.app, ...(s.uses.trigger === true ? { trigger: true } : {}) }),\n );\n return other ? { id: other.id, manual: false } : undefined;\n}\n","/**\n * The run-polling loop, split out of `api/client.ts`'s original `runWorkflow`\n * into its own PURE module — for the SAME mechanical reason\n * `repos/reliability-uptime.ts` exists (read that file's own header comment in\n * full): a `.ts` module that would otherwise transitively import\n * `../api/apiClient.tsx` (a `.tsx` file Node's type-stripping cannot load at\n * all) must be split out to stay reachable by `node --test`.\n *\n * Ported field-for-field from `api/client.ts`'s original `runWorkflow` (same\n * 500 ms interval, same 600-iteration cap, same \"one more fetch after the\n * loop\" shape) — the ONLY change is the injected `getRun`/`sleep` parameters,\n * which is what makes this loop testable on a fake clock instead of a real\n * 5-minute wait. See `../repos/workflows.ts` for the caller.\n */\nimport type { RunState } from \"@w6w/sdk/console\";\n\nconst TERMINAL = new Set([\"succeeded\", \"failed\", \"canceled\"]);\n\nfunction realSleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Poll `getRun` until the run reaches a terminal status, or 600 polls (~5\n * minutes at the default 500ms interval) elapse — whichever comes first.\n * Ported verbatim from `api/client.ts`'s `runWorkflow`; see\n * `../repos/workflows.ts` for the caller.\n */\nexport async function pollRunToTerminal(\n getRun: () => Promise<RunState>,\n sleep: (ms: number) => Promise<void> = realSleep,\n): Promise<RunState> {\n for (let i = 0; i < 600; i++) {\n const run = await getRun();\n if (TERMINAL.has(run.status)) return run;\n await sleep(500);\n }\n return getRun();\n}\n","// Run: node --test src/lib/__tests__/history-query.test.ts (Node 24, type-stripped)\n//\n// T2.3.1 — the pure data layer behind the project-wide and per-callable\n// History page (T2.4.1) and the Function/Endpoint/Workflow header's History\n// button (T2.4.2). Everything that is a judgment call rather than React\n// plumbing lives here: how a URL's search string becomes a `HistoryFilters`\n// (and back), how a filter set becomes the wire's own query params, the\n// query keys every hook in `repos/history.ts` shares, and how a summary row\n// is expanded into a full detail view for one of the three callable kinds.\n//\n// Zero runtime imports other than `./workflow-live-run.ts` and\n// `./workflow-poll.ts` (A1) — every other import here is `import type`, erased\n// at build time, so `node --test` can load this module directly with no React,\n// no SDK runtime, no JSX. The first reuses `mapRunStateToLogSteps`, the same\n// step mapper the visual editor's live-run overlay already uses, so a\n// workflow's historical detail view renders steps identically to its live\n// one; the second is the same run-polling loop the editor's own Run uses, so a\n// re-run waits for its workflow exactly as a run started there does.\n//\n// The wire shape (`ExecutionKind`, `ExecutionStatus`, `ExecutionSummary`,\n// `ExecutionStats`) is pinned verbatim against T2.1.1's own contract — do not\n// drift it; T2.4.1/T2.4.2 are written against this file's exports exactly.\n\nimport type { W6WClient } from \"@w6w/sdk\";\nimport { mapRunStateToLogSteps, runNodeMap } from \"./workflow-live-run.ts\";\nimport { pollRunToTerminal } from \"./workflow-poll.ts\";\n\n// ── wire types (pinned, identical to T2.1.1 §Wire) ──────────────────────\n\nexport type ExecutionKind = \"function\" | \"endpoint\" | \"workflow\";\nexport type ExecutionStatus = \"queued\" | \"running\" | \"succeeded\" | \"failed\" | \"canceled\";\n\nexport interface ExecutionSummary {\n id: string;\n kind: ExecutionKind;\n callableId: string;\n callableName: string;\n status: ExecutionStatus;\n startedAt: string;\n finishedAt: string | null;\n durationMs: number | null;\n workflowRunId: string | null;\n /** The execution this one RE-RUNS (History's Re-run), or `null`. Absent from an older server. */\n rerunOf?: string | null;\n /** How a workflow run was started (manual, schedule, webhook, event, replay); `null` for a\n * Function/Endpoint call. Absent from an older server. */\n trigger?: string | null;\n /** The trigger node a workflow run entered through. Absent from an older server. */\n triggerNodeId?: string | null;\n /** The start of the input as JSON text. Absent from an older server. */\n inputPreview?: string | null;\n}\n\nexport interface ExecutionStats {\n total: number;\n succeeded: number;\n failed: number;\n canceled: number;\n inFlight: number;\n successRate: number | null;\n avgDurationMs: number | null;\n}\n\n// ── scope + filters ───────────────────────────────────────────────────────\n\n/** Either the project-wide view or one callable's own history — mutually\n * exclusive, never both, mirroring the wire's own `project`|`callable`\n * params (exactly one). */\nexport type HistoryScope = { project: string } | { callable: string };\n\n/** Everything the History page's filter chrome can set, already parsed out\n * of the URL. `status`/`kind` are `\"\"` for \"any\"; `from`/`to` are the\n * `YYYY-MM-DD` the date pickers hand back, or `\"\"` for unset; `offset` is\n * always a non-negative integer (0 for \"first page\"). */\nexport interface HistoryFilters {\n status: ExecutionStatus | \"\";\n kind: ExecutionKind | \"\";\n from: string;\n to: string;\n q: string;\n /** Which trigger started the run: `\"\"` (any), `entry:<trigger node id>` or `kind:<run trigger\n * kind>` (`kind:manual` — a manual run records no entry node). See `triggerFilterQuery`. */\n trigger: string;\n offset: number;\n}\n\nexport const EMPTY_HISTORY_FILTERS: HistoryFilters = {\n status: \"\",\n kind: \"\",\n from: \"\",\n to: \"\",\n q: \"\",\n trigger: \"\",\n offset: 0,\n};\n\nconst TRIGGER_FILTER_RE = /^(entry|kind):.{1,200}$/;\n\n/** A `HistoryFilters.trigger` value → the wire's own `entry` / `trigger` params. */\nexport function triggerFilterQuery(trigger: string): Record<string, string> {\n if (!TRIGGER_FILTER_RE.test(trigger)) return {};\n const value = trigger.slice(trigger.indexOf(\":\") + 1);\n return trigger.startsWith(\"entry:\") ? { entry: value } : { trigger: value };\n}\n\nexport const HISTORY_PAGE_SIZE = 25;\n\nconst VALID_STATUSES: ReadonlySet<string> = new Set([\n \"queued\",\n \"running\",\n \"succeeded\",\n \"failed\",\n \"canceled\",\n]);\nconst VALID_KINDS: ReadonlySet<string> = new Set([\"function\", \"endpoint\", \"workflow\"]);\nconst DATE_RE = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n/** True when `YYYY-MM-DD` names a real calendar day (`2026-02-30` rolls into\n * March through `new Date`, so a round-trip comparison rejects it). */\nfunction isRealDate(s: string): boolean {\n if (!DATE_RE.test(s)) return false;\n const { y, m, d } = dateParts(s);\n const dt = new Date(y, m - 1, d);\n return dt.getFullYear() === y && dt.getMonth() === m - 1 && dt.getDate() === d;\n}\n\n/** Parse a validated `YYYY-MM-DD` string into its three numeric parts. */\nfunction dateParts(value: string): { y: number; m: number; d: number } {\n const [y, m, d] = value.split(\"-\").map(Number);\n return { y, m, d };\n}\n\n/**\n * URL search string → `HistoryFilters`. An unrecognised `status`/`kind`, a\n * `from`/`to` not matching `YYYY-MM-DD`, or a non-integer/negative `offset`\n * all fall back to their empty/zero default rather than carrying a bogus\n * value forward into a request — a stale or hand-edited URL degrades to \"no\n * filter\" instead of erroring.\n */\nexport function filtersFromSearch(search: string): HistoryFilters {\n const params = new URLSearchParams(search);\n const status = params.get(\"status\") ?? \"\";\n const kind = params.get(\"kind\") ?? \"\";\n const from = params.get(\"from\") ?? \"\";\n const to = params.get(\"to\") ?? \"\";\n const q = params.get(\"q\") ?? \"\";\n const trigger = params.get(\"trigger\") ?? \"\";\n const offsetRaw = params.get(\"offset\");\n let offset = 0;\n if (offsetRaw !== null) {\n const n = Number(offsetRaw);\n if (Number.isInteger(n) && n >= 0) offset = n;\n }\n return {\n status: VALID_STATUSES.has(status) ? (status as ExecutionStatus) : \"\",\n kind: VALID_KINDS.has(kind) ? (kind as ExecutionKind) : \"\",\n from: isRealDate(from) ? from : \"\",\n to: isRealDate(to) ? to : \"\",\n q,\n trigger: TRIGGER_FILTER_RE.test(trigger) ? trigger : \"\",\n offset,\n };\n}\n\n/**\n * `HistoryFilters` → URL search string. `\"\"` when every field is at its\n * default, else a leading-`?` string with only the non-default fields, in\n * the pinned key order `status,kind,from,to,q,trigger,offset` (so two renders of the\n * same filters always produce byte-identical URLs — stable for bookmarking\n * and for `filtersFromSearch` round-tripping).\n */\nexport function filtersToSearch(f: HistoryFilters): string {\n const params = new URLSearchParams();\n if (f.status !== \"\") params.set(\"status\", f.status);\n if (f.kind !== \"\") params.set(\"kind\", f.kind);\n if (f.from !== \"\") params.set(\"from\", f.from);\n if (f.to !== \"\") params.set(\"to\", f.to);\n if (f.q !== \"\") params.set(\"q\", f.q);\n if (f.trigger) params.set(\"trigger\", f.trigger);\n if (f.offset > 0) params.set(\"offset\", String(f.offset));\n const s = params.toString();\n return s === \"\" ? \"\" : `?${s}`;\n}\n\n/**\n * `HistoryFilters` + a scope → the wire's own query params (D3/pinned rules).\n * `kind` is sent only for a project scope with a non-empty kind — a\n * per-callable view already knows its one kind, and the server's `kind`\n * param is project-mode-only. `from`/`to` are expanded from the picked\n * calendar day into the half-open `[from, to)` ISO instant range the wire\n * wants — `to` is the NEXT day's midnight so the picked day itself is fully\n * inclusive. `q` is trimmed and omitted when blank (server-side id/name\n * search, D3 — never a payload scan). Paging params are added only when\n * `opts.paged`: `limit` always (defaulting to `HISTORY_PAGE_SIZE`), `offset`\n * only when it would change anything (`> 0`).\n */\nexport function historyRequestQuery(\n scope: HistoryScope,\n f: HistoryFilters,\n opts: { paged: boolean; limit?: number },\n): Record<string, string> {\n const query: Record<string, string> = {};\n\n if (\"project\" in scope) {\n query.project = scope.project;\n if (f.kind !== \"\") query.kind = f.kind;\n } else {\n query.callable = scope.callable;\n }\n\n if (f.status !== \"\") query.status = f.status;\n\n if (f.from !== \"\" && isRealDate(f.from)) {\n const { y, m, d } = dateParts(f.from);\n query.from = new Date(y, m - 1, d).toISOString();\n }\n if (f.to !== \"\" && isRealDate(f.to)) {\n const { y, m, d } = dateParts(f.to);\n query.to = new Date(y, m - 1, d + 1).toISOString();\n }\n\n const q = f.q.trim();\n if (q !== \"\") query.q = q;\n if (f.trigger) Object.assign(query, triggerFilterQuery(f.trigger));\n\n if (opts.paged) {\n query.limit = String(opts.limit ?? HISTORY_PAGE_SIZE);\n if (f.offset > 0) query.offset = String(f.offset);\n }\n\n return query;\n}\n\n// ── cache keys (ship from here, never from a caller — mirrors `repos/dashboard.ts`) ──\n\n/**\n * Every key this domain reads or invalidates. `list`/`stats` carry the full\n * scope and filters object so two distinct filter sets never collide on the\n * same cache entry (and the identical pair always do) — react-query's own\n * structural key hashing does the rest.\n */\nexport const historyKeys = {\n root: [\"history\"] as const,\n list(scope: HistoryScope, f: HistoryFilters, limit: number): readonly unknown[] {\n return [\"history\", \"list\", scope, f, limit];\n },\n stats(scope: HistoryScope, f: HistoryFilters): readonly unknown[] {\n return [\"history\", \"stats\", scope, f];\n },\n exists(callableId: string): readonly [\"history\", \"exists\", string] {\n return [\"history\", \"exists\", callableId];\n },\n detail(kind: ExecutionKind, id: string): readonly [\"history\", \"detail\", ExecutionKind, string] {\n return [\"history\", \"detail\", kind, id];\n },\n triggers(workflowId: string): readonly [\"history\", \"triggers\", string] {\n return [\"history\", \"triggers\", workflowId];\n },\n};\n\n// ── fetchers ─────────────────────────────────────────────────────────────\n\n/** `GET /history` — paged. */\nexport function getHistory(\n client: W6WClient,\n scope: HistoryScope,\n f: HistoryFilters,\n limit: number = HISTORY_PAGE_SIZE,\n): Promise<{ executions: ExecutionSummary[]; hasMore: boolean }> {\n return client\n .request<{ executions: ExecutionSummary[]; hasMore: boolean }>({\n method: \"GET\",\n path: \"/history\",\n query: historyRequestQuery(scope, f, { paged: true, limit }),\n })\n .then((response) => response.body);\n}\n\n/** `GET /history/stats` — unpaged (no `limit`/`offset`). */\nexport function getHistoryStats(\n client: W6WClient,\n scope: HistoryScope,\n f: HistoryFilters,\n): Promise<ExecutionStats> {\n return client\n .request<{ stats: ExecutionStats }>({\n method: \"GET\",\n path: \"/history/stats\",\n query: historyRequestQuery(scope, f, { paged: false }),\n })\n .then((response) => response.body.stats);\n}\n\n/** One execution's full detail — the shape `ExecutionDetail` (`@w6w/ui`,\n * T2.2.2) renders. `steps` is present only for a workflow run; a\n * function/endpoint invocation has none. */\nexport interface ExecutionDetailData {\n id: string;\n kind: ExecutionKind;\n callableName: string;\n status: ExecutionStatus;\n startedAt: string;\n finishedAt: string | null;\n durationMs: number | null;\n input?: unknown;\n output?: unknown;\n error?: unknown;\n /** The execution this one re-runs, carried from its summary row. */\n rerunOf?: string | null;\n steps?: Array<{\n id: string;\n status: \"pending\" | \"running\" | \"succeeded\" | \"failed\" | \"skipped\";\n skipReason?: \"not_on_path\" | \"condition\" | \"stopped\" | \"disabled\";\n startedAt?: string;\n finishedAt?: string;\n input?: unknown;\n output?: unknown;\n node?: StepNode;\n }>;\n}\n\n/** What a workflow step IS (`@w6w/ui`'s `ExecutionLogNode`, restated locally — A1): the app and\n * action it uses, whether it is a trigger, and the app's display names when it is a registered app.\n * A built-in `@w6w/*` node carries ids only; the panel names those from its own catalog. */\nexport interface StepNode {\n app: string;\n action: string;\n trigger?: boolean;\n appName?: string;\n actionName?: string;\n}\n\n/** The slice of a definition node this module reads. */\ninterface DefinitionNode {\n id?: unknown;\n uses?: { app?: unknown; action?: unknown; trigger?: unknown };\n}\n\n/**\n * Every node of the workflow's CURRENT definition, keyed by id, as a {@link StepNode} — with the\n * display names of each registered app (`GET /apps/:id`'s `displayName` and action titles, plus\n * `GET /apps/:id/triggers` for an app a trigger node uses). Best-effort throughout: a definition\n * that cannot be read yields an empty map, and an app that cannot be read keeps its raw ids.\n */\nexport async function describeWorkflowNodes(\n client: W6WClient,\n workflowId: string,\n): Promise<Map<string, StepNode>> {\n const out = new Map<string, StepNode>();\n let nodes: DefinitionNode[];\n try {\n const { workflow } = await client.console.workflows.get(workflowId);\n nodes = Array.isArray(workflow.nodes) ? (workflow.nodes as DefinitionNode[]) : [];\n } catch {\n return out;\n }\n for (const n of nodes) {\n const app = n.uses?.app;\n const action = n.uses?.action;\n if (typeof n.id !== \"string\" || typeof app !== \"string\" || typeof action !== \"string\") continue;\n out.set(n.id, { app, action, ...(n.uses?.trigger === true ? { trigger: true } : {}) });\n }\n\n // Built-in `@w6w/*` ids are not served by `/apps/:id`; the panel names those itself.\n const registered = [...new Set([...out.values()].map((n) => n.app))].filter(\n (app) => !app.startsWith(\"@w6w/\"),\n );\n const names = await Promise.all(\n registered.map(async (app) => {\n const wantsTriggers = [...out.values()].some((n) => n.app === app && n.trigger);\n const [detail, triggers] = await Promise.all([\n client.console.apps.get(app).catch(() => null),\n wantsTriggers ? client.console.apps.getTriggers(app).catch(() => []) : Promise.resolve([]),\n ]);\n const titles = new Map<string, string>();\n for (const a of detail?.actions ?? []) titles.set(`a:${a.key}`, a.title);\n for (const t of triggers) titles.set(`t:${t.key}`, t.title);\n return { app, displayName: detail?.app.displayName, titles };\n }),\n );\n for (const node of out.values()) {\n const named = names.find((n) => n.app === node.app);\n if (!named) continue;\n if (named.displayName) node.appName = named.displayName;\n const title = named.titles.get(`${node.trigger ? \"t\" : \"a\"}:${node.action}`);\n if (title) node.actionName = title;\n }\n return out;\n}\n\n/** The built-in trigger nodes (`@w6w/ui`'s `isTriggerApp`), named as the canvas names them. */\nconst BUILT_IN_TRIGGERS: Record<string, string> = {\n \"@w6w/trigger\": \"Manual trigger\",\n \"@w6w/webhook\": \"Webhook\",\n \"@w6w/scheduler\": \"Schedule\",\n \"@w6w/form\": \"Form\",\n};\n\n/** One trigger a workflow run can enter through: its node id and display name. */\nexport interface WorkflowTrigger {\n nodeId: string;\n label: string;\n /** The node's app — `@w6w/trigger` for the Manual trigger. */\n app: string;\n}\n\n/**\n * The workflow's trigger nodes (built-in triggers and app trigger nodes), in definition order,\n * each named the way the canvas card names it — `Cohost · Channel Changed`, `Manual trigger`.\n * A label two triggers share gets its node id appended so the filter can tell them apart.\n */\nexport function workflowTriggers(nodes: Map<string, StepNode>): WorkflowTrigger[] {\n const out: WorkflowTrigger[] = [];\n for (const [nodeId, n] of nodes) {\n const builtIn = BUILT_IN_TRIGGERS[n.app];\n if (!builtIn && !n.trigger) continue;\n const label = builtIn ?? `${n.appName ?? n.app} · ${n.actionName ?? n.action}`;\n out.push({ nodeId, label, app: n.app });\n }\n const seen = new Map<string, number>();\n for (const t of out) seen.set(t.label, (seen.get(t.label) ?? 0) + 1);\n return out.map((t) =>\n (seen.get(t.label) ?? 0) > 1 ? { ...t, label: `${t.label} (${t.nodeId})` } : t,\n );\n}\n\n/** A run's trigger display name: its entry node's label, else the run kind (`Manual`). */\nexport function runTriggerLabel(\n summary: Pick<ExecutionSummary, \"trigger\" | \"triggerNodeId\">,\n triggers: WorkflowTrigger[],\n): string | null {\n if (summary.triggerNodeId) {\n const t = triggers.find((x) => x.nodeId === summary.triggerNodeId);\n if (t) return t.label;\n }\n if (!summary.trigger) return null;\n if (summary.trigger === \"manual\") return \"Manual run\";\n return summary.trigger.charAt(0).toUpperCase() + summary.trigger.slice(1);\n}\n\n/** The `GET /invocations/:id` response body's shape this module reads\n * (context notes: server `db/repos/invocations.ts` `InvocationRow`). */\ninterface InvocationDetailBody {\n status: ExecutionStatus;\n input?: unknown;\n output?: unknown;\n error?: unknown;\n durationMs: number | null;\n startedAt: string;\n finishedAt: string | null;\n}\n\n/**\n * Expand a list row into its full detail. Function/Endpoint invocations are\n * synchronous calls recorded one row per call (`.claude/docs/invocations.md`)\n * — `GET /invocations/:id` by the escape-hatch `client.request` (no typed SDK\n * method exists for this internal route, same reasoning as\n * `repos/callables.ts`'s `archiveCallable`/`deleteCallable` split; A1: no\n * other runtime import needed). A workflow run instead reuses\n * `client.console.workflows.getRun` (`repos/workflows.ts`'s own\n * `getRunState`) — its `variables` become the detail's `input`, and its\n * opaque `steps` map through the SAME `mapRunStateToLogSteps` the live-run\n * overlay uses, so a historical run's step list renders identically to a\n * live one. `callableName` always comes from the summary — neither read\n * carries a human-readable callable name of its own.\n */\nexport async function getExecutionDetail(\n client: W6WClient,\n summary: ExecutionSummary,\n): Promise<ExecutionDetailData> {\n if (summary.kind === \"workflow\") {\n const [run, described] = await Promise.all([\n client.console.workflows.getRun(summary.id),\n describeWorkflowNodes(client, summary.callableId),\n ]);\n // What STARTED the run: the start payload (`input`), else the trigger's delivered `event` —\n // both ride `GET /runs/:id` beside the SDK's typed fields — else, for a run that had\n // neither, its variables.\n const started = run as unknown as { input?: unknown; event?: unknown };\n return {\n id: summary.id,\n kind: \"workflow\",\n callableName: summary.callableName,\n status: run.status,\n startedAt: summary.startedAt,\n finishedAt: summary.finishedAt,\n durationMs: summary.durationMs,\n input: started.input ?? started.event ?? run.variables,\n output: run.output,\n error: run.error,\n rerunOf: summary.rerunOf ?? null,\n steps: mapRunStateToLogSteps(runNodeMap(run)).map((step) => {\n const node = described.get(step.id);\n return node ? { ...step, node } : step;\n }),\n };\n }\n\n const response = await client.request<{ invocation: InvocationDetailBody }>({\n method: \"GET\",\n path: `/invocations/${encodeURIComponent(summary.id)}`,\n });\n const invocation = response.body.invocation;\n return {\n id: summary.id,\n kind: summary.kind,\n callableName: summary.callableName,\n status: invocation.status,\n startedAt: invocation.startedAt,\n finishedAt: invocation.finishedAt,\n durationMs: invocation.durationMs,\n input: invocation.input,\n output: invocation.output,\n error: invocation.error,\n rerunOf: summary.rerunOf ?? null,\n };\n}\n\n// ── re-run ───────────────────────────────────────────────────────────────\n\n/** The invocation id a FAILED invoke still minted: the server stamps its frame\n * onto the error body (`withInvocationFrame`), and `@w6w/sdk`'s `ApiError`\n * keeps that body as `raw`. Duck-typed so this module stays SDK-runtime-free. */\nfunction invocationIdOf(err: unknown): string | undefined {\n const raw = (err as { raw?: unknown } | null)?.raw;\n const id = (raw as { invocationId?: unknown } | null)?.invocationId;\n return typeof id === \"string\" ? id : undefined;\n}\n\n/** A plain object, or `{}` — a stored input that is not an object (or is\n * absent) cannot be an invoke body. */\nfunction asRecord(value: unknown): Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n\n/** Start the new execution and return its id: the run id for a workflow (once\n * the run is terminal), the invocation id for a function/endpoint — also when\n * the call itself failed, since a failed call is still a recorded execution. */\nasync function startRerun(\n client: W6WClient,\n summary: ExecutionSummary,\n sleep?: (ms: number) => Promise<void>,\n): Promise<string> {\n const callable = encodeURIComponent(summary.callableId);\n\n if (summary.kind === \"workflow\") {\n // The SERVER replays the stored seed — trigger type, variables, start input, the trigger's\n // delivered `event`, entry node, partial-run spec. A client-side replay through\n // `POST /workflows/:id/run` cannot: that route has no slot for `event`, which is where an app\n // or webhook trigger's payload lives.\n const res = await client.request<{ runId: string }>({\n method: \"POST\",\n path: `/runs/${encodeURIComponent(summary.id)}/rerun`,\n body: { allowUnpublished: true },\n });\n const runId = res.body.runId;\n await pollRunToTerminal(() => client.console.workflows.getRun(runId), sleep);\n return runId;\n }\n\n const past = await client.request<{ invocation: InvocationDetailBody }>({\n method: \"GET\",\n path: `/invocations/${encodeURIComponent(summary.id)}`,\n });\n const input = asRecord(past.body.invocation.input);\n // `rerunOf` marks the new invocation as a re-run of this one (`invocations.rerun_of`).\n const body: Record<string, unknown> =\n summary.kind === \"function\"\n ? { inputs: input, allowUnpublished: true, rerunOf: summary.id }\n : { input, allowUnpublished: true, rerunOf: summary.id };\n try {\n const res = await client.request<{ invocationId?: string }>({\n method: \"POST\",\n path: `/${summary.kind === \"function\" ? \"functions\" : \"endpoints\"}/${callable}/invoke`,\n body,\n });\n const id = res.body.invocationId;\n if (typeof id !== \"string\") throw new Error(\"The server did not return an invocation id.\");\n return id;\n } catch (err) {\n const id = invocationIdOf(err);\n if (id === undefined) throw err;\n return id;\n }\n}\n\n/**\n * Run a past execution again with the input it had, against the callable's\n * CURRENT definition (the stored draft — `allowUnpublished`, as the editor's\n * own Run and Test do), and return the new execution's summary row so the\n * host can open it. A workflow is replayed by the server from its stored seed\n * (`POST /runs/:id/rerun`, trigger payload included); a function replays its\n * `inputs`; an endpoint its `input`. `null` when the new row is not yet listed (the host then just\n * shows the refreshed list).\n */\nexport async function rerunExecution(\n client: W6WClient,\n summary: ExecutionSummary,\n opts: { sleep?: (ms: number) => Promise<void> } = {},\n): Promise<ExecutionSummary | null> {\n const id = await startRerun(client, summary, opts.sleep);\n return findExecution(client, summary.callableId, id);\n}\n\n/** One callable's execution by id, as its summary row (`GET /history`'s id search), or `null`\n * when it is not listed — e.g. the original a re-run names, once retention removed it. */\nexport async function findExecution(\n client: W6WClient,\n callableId: string,\n id: string,\n): Promise<ExecutionSummary | null> {\n const found = await getHistory(\n client,\n { callable: callableId },\n { ...EMPTY_HISTORY_FILTERS, q: id },\n 1,\n );\n return found.executions.find((row) => row.id === id) ?? null;\n}\n","/**\n * The run-events stream client — PURE and Node-testable in full (no React, no runtime import):\n * the SSE frame parser, the per-run stream loop with its reconnect backoff and fallback decision,\n * and the refcounted registry that shares one stream per run between every component watching it.\n * `../repos/workflows.ts`'s `useLiveRunQuery` is the only React caller.\n *\n * WHY. The editor used to poll `GET /runs/:id` (and `GET /runs/:id/state-writes`) every 500 ms\n * for as long as a run was in flight. The server now pushes the run instead:\n *\n * GET /runs/:id/events\n * event: snapshot data = {\"run\": <exactly GET /runs/:id's `run`>} (full, replaces the last)\n * event: reconnect data = {} the server is ending the stream early: open a new one now\n * event: gone data = {} the run is no longer readable: stop streaming\n * : keep-alive heartbeat comment, about every 15 s\n *\n * Every `snapshot` is the same `RunState` a poll returned, so it goes straight into the query\n * cache and the canvas and the run log need no change.\n *\n * TRANSPORT. `fetch` + `ReadableStream` with the client's `Authorization: Bearer` HEADER, never\n * `EventSource` (it cannot send headers) and never a token in the URL (it would land in access\n * logs). The token, base URL and default headers are read off the caller's `W6WClient.config`, so\n * the public `@w6w/sdk` surface is unchanged.\n *\n * A RUN NEVER LOOKS FROZEN. The loop reports a {@link RunStreamMode}; the hook polls exactly as it\n * used to whenever the mode is `fallback`:\n * - a refusal (`401`/`403`/`404`, or a `2xx` that is not `text/event-stream`, e.g. an older\n * server without the route) is final: `fallback` for the rest of the run, no retry;\n * - a drop (a network error, any other status, the stream ending before a terminal snapshot, or\n * no byte at all for {@link RunStreamOptions.idleTimeoutMs}) is `fallback` WHILE the loop\n * reconnects with exponential backoff, and `live` again on the next snapshot;\n * - a stream that has not delivered its first snapshot within\n * {@link RunStreamOptions.firstSnapshotMs} (a buffering proxy) is `fallback` until it does;\n * - `reconnect` (the server's lifetime cap, or an instance shutting down) reconnects at once and\n * stays `live`: the new stream opens with a fresh snapshot, so nothing is lost.\n */\n\n/** One dispatched SSE event. Comment lines never become events. */\nexport interface SseEvent {\n event: string;\n data: string;\n}\n\n/**\n * Incremental SSE parser (the WHATWG event-stream rules this wire uses): feed it decoded text in\n * any chunking; it returns the events completed so far. `onActivity` is the caller's business —\n * every chunk, heartbeat comments included, counts as the connection being alive.\n */\nexport class SseParser {\n #buf = \"\";\n #event = \"\";\n #data: string[] = [];\n\n push(chunk: string): SseEvent[] {\n this.#buf += chunk;\n const out: SseEvent[] = [];\n for (;;) {\n const nl = this.#buf.search(/\\r\\n|\\r|\\n/);\n if (nl < 0) break;\n const line = this.#buf.slice(0, nl);\n this.#buf = this.#buf.slice(nl + (this.#buf.startsWith(\"\\r\\n\", nl) ? 2 : 1));\n if (line === \"\") {\n if (this.#data.length > 0) {\n out.push({ event: this.#event || \"message\", data: this.#data.join(\"\\n\") });\n }\n this.#event = \"\";\n this.#data = [];\n continue;\n }\n if (line.startsWith(\":\")) continue;\n const colon = line.indexOf(\":\");\n const field = colon < 0 ? line : line.slice(0, colon);\n let value = colon < 0 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) value = value.slice(1);\n if (field === \"event\") this.#event = value;\n else if (field === \"data\") this.#data.push(value);\n }\n return out;\n }\n}\n\n/** Where the stream lives, relative to the API base. */\nexport function runEventsPath(runId: string): string {\n return `/runs/${encodeURIComponent(runId)}/events`;\n}\n\n/**\n * - `connecting`: the first request is in flight and no snapshot has arrived yet;\n * - `live`: snapshots are arriving — the hook does not poll;\n * - `fallback`: the stream is refused or down — the hook polls `GET /runs/:id` as it used to;\n * - `done`: a terminal snapshot arrived (or the stream was stopped) — nothing more to fetch.\n */\nexport type RunStreamMode = \"connecting\" | \"live\" | \"fallback\" | \"done\";\n\n/** The run statuses after which nothing about a run changes again. */\nexport function isTerminalRunStatusLike(status: unknown): boolean {\n return status === \"succeeded\" || status === \"failed\" || status === \"canceled\";\n}\n\n/** The slice of a `@w6w/sdk` `W6WClient.config` the stream reads (structural, no import). */\nexport interface StreamClientConfig {\n baseUrl: string;\n token:\n | string\n | ((ctx?: { forceRefresh?: boolean }) =>\n | string\n | null\n | undefined\n | Promise<string | null | undefined>)\n | null;\n headers?: Record<string, string>;\n}\n\n/** The request headers for one stream attempt, or `null` when there is no token to send. */\nexport async function streamHeaders(\n config: StreamClientConfig,\n): Promise<Record<string, string> | null> {\n const raw = typeof config.token === \"function\" ? await config.token() : config.token;\n if (typeof raw !== \"string\" || raw.trim() === \"\") return null;\n return {\n ...(config.headers ?? {}),\n accept: \"text/event-stream\",\n authorization: `Bearer ${raw}`,\n };\n}\n\nexport type FetchLike = (url: string, init: RequestInit) => Promise<Response>;\n\nexport interface RunStreamOptions {\n config: StreamClientConfig;\n runId: string;\n fetchImpl: FetchLike;\n signal: AbortSignal;\n onSnapshot: (run: Record<string, unknown>) => void;\n onMode: (mode: RunStreamMode) => void;\n /** Injected for tests. Must settle early (resolve) when `signal` aborts. */\n sleep?: (ms: number, signal: AbortSignal) => Promise<void>;\n /** Fall back to polling if no snapshot arrived this long after a request started. */\n firstSnapshotMs?: number;\n /** Treat the connection as dead after this long without a byte (heartbeats included). */\n idleTimeoutMs?: number;\n /** Reconnect backoff after a drop: `retryMinMs` doubling up to `retryMaxMs`. */\n retryMinMs?: number;\n retryMaxMs?: number;\n}\n\n/** How one stream attempt ended. */\ntype AttemptEnd = \"terminal\" | \"refused\" | \"gone\" | \"reconnect\" | \"dropped\" | \"aborted\";\n\nexport function abortableSleep(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal.aborted) return resolve();\n const done = () => {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", done);\n resolve();\n };\n const timer = setTimeout(done, ms);\n signal.addEventListener(\"abort\", done);\n });\n}\n\n/**\n * Stream one run until a terminal snapshot, a refusal, `gone`, or `signal` aborts. Never rejects.\n * Resolves with the final mode it reported.\n */\nexport async function streamRun(opts: RunStreamOptions): Promise<RunStreamMode> {\n const sleep = opts.sleep ?? abortableSleep;\n const retryMin = opts.retryMinMs ?? 1_000;\n const retryMax = opts.retryMaxMs ?? 15_000;\n let retry = retryMin;\n let mode: RunStreamMode | null = null;\n const report = (next: RunStreamMode) => {\n if (next !== mode) {\n mode = next;\n opts.onMode(next);\n }\n };\n report(\"connecting\");\n for (;;) {\n if (opts.signal.aborted) return finish(\"done\");\n const end = await attempt(opts, (live) => {\n if (live) {\n retry = retryMin;\n report(\"live\");\n } else report(\"fallback\");\n });\n switch (end) {\n case \"terminal\":\n case \"aborted\":\n return finish(\"done\");\n case \"refused\":\n case \"gone\":\n return finish(\"fallback\");\n case \"reconnect\":\n continue;\n case \"dropped\":\n report(\"fallback\");\n await sleep(retry, opts.signal);\n retry = Math.min(retry * 2, retryMax);\n continue;\n }\n }\n function finish(final: RunStreamMode): RunStreamMode {\n report(final);\n return final;\n }\n}\n\nasync function attempt(\n opts: RunStreamOptions,\n setLive: (live: boolean) => void,\n): Promise<AttemptEnd> {\n const firstSnapshotMs = opts.firstSnapshotMs ?? 3_000;\n const idleTimeoutMs = opts.idleTimeoutMs ?? 45_000;\n const ctl = new AbortController();\n const onAbort = () => ctl.abort();\n opts.signal.addEventListener(\"abort\", onAbort);\n let sawSnapshot = false;\n const slow = setTimeout(() => {\n if (!sawSnapshot) setLive(false);\n }, firstSnapshotMs);\n let idleTimer: ReturnType<typeof setTimeout> | undefined;\n const touch = () => {\n clearTimeout(idleTimer);\n idleTimer = setTimeout(() => ctl.abort(), idleTimeoutMs);\n };\n try {\n const headers = await streamHeaders(opts.config);\n if (!headers) return \"refused\";\n touch();\n let res: Response;\n try {\n res = await opts.fetchImpl(`${opts.config.baseUrl}${runEventsPath(opts.runId)}`, {\n method: \"GET\",\n headers,\n signal: ctl.signal,\n cache: \"no-store\",\n });\n } catch {\n return opts.signal.aborted ? \"aborted\" : \"dropped\";\n }\n const type = res.headers.get(\"content-type\") ?? \"\";\n if (res.status === 401 || res.status === 403 || res.status === 404) {\n await res.body?.cancel().catch(() => {});\n return \"refused\";\n }\n if (!res.ok || !res.body) {\n await res.body?.cancel().catch(() => {});\n return \"dropped\";\n }\n if (!type.includes(\"text/event-stream\")) {\n await res.body.cancel().catch(() => {});\n return \"refused\";\n }\n const reader = res.body.getReader();\n // Cancel the read explicitly on abort (idle timeout or stop): not every `fetch` ties an\n // already-returned body to its signal.\n ctl.signal.addEventListener(\"abort\", () => {\n reader.cancel().catch(() => {});\n });\n const decoder = new TextDecoder();\n const parser = new SseParser();\n for (;;) {\n let chunk: ReadableStreamReadResult<Uint8Array>;\n try {\n chunk = await reader.read();\n } catch {\n return opts.signal.aborted ? \"aborted\" : \"dropped\";\n }\n if (chunk.done) return opts.signal.aborted ? \"aborted\" : \"dropped\";\n touch();\n for (const ev of parser.push(decoder.decode(chunk.value, { stream: true }))) {\n if (ev.event === \"snapshot\") {\n let run: unknown;\n try {\n run = (JSON.parse(ev.data) as { run?: unknown }).run;\n } catch {\n continue;\n }\n if (typeof run !== \"object\" || run === null) continue;\n sawSnapshot = true;\n opts.onSnapshot(run as Record<string, unknown>);\n setLive(true);\n if (isTerminalRunStatusLike((run as { status?: unknown }).status)) {\n await reader.cancel().catch(() => {});\n return \"terminal\";\n }\n } else if (ev.event === \"reconnect\") {\n await reader.cancel().catch(() => {});\n return \"reconnect\";\n } else if (ev.event === \"gone\") {\n await reader.cancel().catch(() => {});\n return \"gone\";\n }\n }\n }\n } finally {\n clearTimeout(slow);\n clearTimeout(idleTimer);\n opts.signal.removeEventListener(\"abort\", onAbort);\n ctl.abort();\n }\n}\n\n/**\n * One shared stream per run. Every component that watches a run (the editor canvas, the run log,\n * the starting-state rail) calls {@link RunStreamRegistry.acquire}; the first starts the stream,\n * the last release stops it. The release is deferred by a tick so React StrictMode's\n * unmount/remount in development reuses the stream instead of opening a second one.\n */\nexport class RunStreamRegistry {\n readonly #entries = new Map<\n string,\n {\n refs: number;\n ctl: AbortController;\n mode: RunStreamMode;\n stopTimer?: ReturnType<typeof setTimeout>;\n }\n >();\n readonly #modeListeners = new Map<string, Set<() => void>>();\n readonly #start: (\n runId: string,\n signal: AbortSignal,\n onMode: (mode: RunStreamMode) => void,\n ) => void;\n\n /** `start` opens the stream for a run (normally {@link streamRun}) and stops on `signal`. */\n constructor(\n start: (runId: string, signal: AbortSignal, onMode: (mode: RunStreamMode) => void) => void,\n ) {\n this.#start = start;\n }\n\n /** The run's current stream mode, or `null` when nothing streams it. */\n mode(runId: string): RunStreamMode | null {\n return this.#entries.get(runId)?.mode ?? null;\n }\n\n /** Subscribe to mode changes of one run (for `useSyncExternalStore`). */\n subscribe(runId: string, listener: () => void): () => void {\n let set = this.#modeListeners.get(runId);\n if (!set) {\n set = new Set();\n this.#modeListeners.set(runId, set);\n }\n set.add(listener);\n return () => {\n set.delete(listener);\n if (set.size === 0) this.#modeListeners.delete(runId);\n };\n }\n\n acquire(runId: string): () => void {\n let entry = this.#entries.get(runId);\n if (entry) {\n clearTimeout(entry.stopTimer);\n entry.stopTimer = undefined;\n entry.refs++;\n } else {\n const ctl = new AbortController();\n const created = {\n refs: 1,\n ctl,\n mode: \"connecting\" as RunStreamMode,\n };\n entry = created;\n this.#entries.set(runId, created);\n this.#start(runId, ctl.signal, (mode) => {\n if (this.#entries.get(runId) !== created) return;\n created.mode = mode;\n this.#notify(runId);\n });\n }\n const held = entry;\n let released = false;\n return () => {\n if (released) return;\n released = true;\n held.refs--;\n if (held.refs > 0) return;\n held.stopTimer = setTimeout(() => {\n if (held.refs > 0 || this.#entries.get(runId) !== held) return;\n this.#entries.delete(runId);\n held.ctl.abort();\n this.#notify(runId);\n }, 0);\n };\n }\n\n #notify(runId: string): void {\n for (const fn of [...(this.#modeListeners.get(runId) ?? [])]) fn();\n }\n}\n\n/**\n * Should the hook poll `GET /runs/:id` right now? Only when no stream carries the run (`null`:\n * none started, e.g. a run already known terminal or a host without a streaming client) or the\n * stream is down (`fallback`). While `connecting`, `live` or `done`, the stream owns the cache.\n */\nexport function pollWhileStreaming(mode: RunStreamMode | null): boolean {\n return mode === null || mode === \"fallback\";\n}\n\n/**\n * A signature of what the run's state-write log can depend on: the run status plus each node's\n * status. The hook re-reads `GET /runs/:id/state-writes` when it changes — once per step that\n * finishes — instead of polling that route every 500 ms.\n */\nexport function stateWritesSignature(run: Record<string, unknown>): string {\n const nodes = (run.nodes ?? run.steps ?? {}) as Record<string, { status?: unknown }>;\n const parts = Object.keys(nodes)\n .sort()\n .map((id) => `${id}=${String(nodes[id]?.status)}`);\n return `${String(run.status)}|${parts.join(\",\")}`;\n}\n","import {\n type QueryClient,\n type UseMutationResult,\n useMutation,\n useQuery,\n useQueryClient,\n} from \"@tanstack/react-query\";\nimport type { StateLogRow } from \"@w6w/expr\";\nimport { path } from \"@w6w/sdk\";\nimport type { RunStatus, W6WClient, WorkflowRunResult } from \"@w6w/sdk\";\nimport type { RunState } from \"@w6w/sdk/console\";\nimport { useCallback, useEffect, useSyncExternalStore } from \"react\";\nimport { useEmbedClient } from \"../draft/client-context.ts\";\nimport { historyKeys } from \"../lib/history-query.ts\";\nimport {\n type RunStreamMode,\n RunStreamRegistry,\n type StreamClientConfig,\n pollWhileStreaming,\n stateWritesSignature,\n streamRun,\n} from \"../lib/run-event-stream.ts\";\nimport { shouldContinuePolling } from \"../lib/workflow-live-run.ts\";\nimport { pollRunToTerminal } from \"../lib/workflow-poll.ts\";\n\nexport type { RunState, RunSummary } from \"@w6w/sdk/console\";\nexport type { WorkflowStatus, WorkflowSummary } from \"@w6w/sdk\";\n\n// `project` distinguishes a project-scoped entry (WorkflowsPage.tsx) from the\n// unscoped one (TargetSelector.tsx, SubscriptionsPage.tsx) — genuinely DIFFERENT\n// queries (not a spelling split to unify like T2.2.2's appActions fix). Keep them\n// as distinct cache entries.\nexport const workflowsKey = (project?: string) => [\"workflows\", project] as const;\n\nexport function listWorkflows(client: W6WClient, project?: string) {\n return client.workflows.list({ project });\n}\n\nexport function useWorkflowsQuery(project?: string, enabled = true) {\n const apiClient = useEmbedClient();\n return useQuery({\n queryKey: workflowsKey(project),\n queryFn: () => listWorkflows(apiClient, project),\n enabled,\n });\n}\n\nexport const workflowKey = (id: string) => [\"workflow\", id] as const;\n\nexport function getWorkflow(client: W6WClient, id: string) {\n return client.workflows.get(id);\n}\n\nexport function useWorkflowQuery(id: string, enabled = true) {\n const apiClient = useEmbedClient();\n return useQuery({\n queryKey: workflowKey(id),\n queryFn: () => getWorkflow(apiClient, id),\n enabled,\n });\n}\n\n/**\n * A missing `project` here is not \"unscoped\" the way a read can legitimately\n * be — the write would silently land in the account's default project\n * instead of the one the caller is looking at. Both mutations refuse rather\n * than risk that; `WorkflowsPage.tsx`'s own `projectId != null` gate on\n * `useWorkflowsQuery` should mean `project` is always set by the time either\n * of these can actually be invoked from the UI, but the guard costs nothing.\n */\nexport function useCreateWorkflowMutation(project?: string) {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: (definition: unknown) => {\n if (!project) return Promise.reject(new Error(\"No project selected yet.\"));\n return apiClient.console.workflows.upsert(definition, { project });\n },\n onSuccess: () => qc.invalidateQueries({ queryKey: [\"workflows\"] }),\n });\n}\n\nexport function useSaveWorkflowMutation(project?: string) {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: (vars: { definition: unknown; ifUnmodifiedSince: string | null }) => {\n if (!project) return Promise.reject(new Error(\"No project selected yet.\"));\n return apiClient.console.workflows.upsert(vars.definition, {\n project,\n ifUnmodifiedSince: vars.ifUnmodifiedSince,\n });\n },\n // The single-workflow cache too: its `updatedAt` is the next save's precondition, so leaving\n // it stale makes the very next save from the same panel a 409. Awaited, so a caller's own\n // `onSuccess` (the modal closing) runs only once the fresh token is in.\n onSuccess: () =>\n Promise.all([\n qc.invalidateQueries({ queryKey: [\"workflows\"] }),\n qc.invalidateQueries({ queryKey: [\"workflow\"] }),\n ]),\n });\n}\n\nexport function useArchiveWorkflowMutation() {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: (id: string) => apiClient.workflows.archive(id),\n onSuccess: () => qc.invalidateQueries({ queryKey: [\"workflows\"] }),\n });\n}\n\nexport function useDeleteWorkflowMutation() {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: (id: string) => apiClient.workflows.delete(id),\n onSuccess: () => qc.invalidateQueries({ queryKey: [\"workflows\"] }),\n });\n}\n\nexport const runsKey = (workflowId: string) => [\"runs\", workflowId] as const;\n\nexport function useRunsQuery(workflowId: string) {\n const apiClient = useEmbedClient();\n return useQuery({\n queryKey: runsKey(workflowId),\n queryFn: () => apiClient.console.workflows.listRuns(workflowId),\n });\n}\n\n/**\n * Start a run and poll it to a terminal state.\n *\n * `input` is the run's START PAYLOAD, and it is a different thing from\n * `variables`: the server hands it to the entry `@w6w/trigger` node as that\n * node's own output, which is what makes `{{ steps.<trigger>.output.<field> }}`\n * resolve in a real run. Omitted, that node outputs `{}` and every reference to\n * a trigger field resolves to the empty string — the failure mode filed as\n * `.ai/projects/backlog/26-07-29-01-trigger-run-payload.md`, where a step tests\n * green and then does nothing in production. `variables` seeds `var.*` and\n * reaches the trigger node not at all.\n *\n * Goes through the typed `client.workflows.run()` with\n * `allowUnpublished: true`: this call site always runs the STORED draft, and\n * the server exempts a caller that sets the flag from the publish gate\n * (`packages/api/run-workflow.ts`'s `enqueueRun`). The SDK's result is the flat\n * run body, so the `runId` used to poll comes off `res.runId`.\n */\nexport function runWorkflow(\n client: W6WClient,\n id: string,\n variables: Record<string, unknown>,\n input?: Record<string, unknown>,\n): Promise<RunState> {\n return client.workflows\n .run(id, { variables, input, allowUnpublished: true })\n .then((res) => pollRunToTerminal(() => client.console.workflows.getRun(res.runId)));\n}\n\nexport function useRunWorkflowMutation() {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: (vars: {\n id: string;\n variables: Record<string, unknown>;\n input?: Record<string, unknown>;\n }) => runWorkflow(apiClient, vars.id, vars.variables, vars.input),\n onSuccess: (_res, vars) => qc.invalidateQueries({ queryKey: runsKey(vars.id) }),\n onSettled: () => qc.invalidateQueries({ queryKey: historyKeys.root }),\n });\n}\n\n/**\n * Run a Workflow SYNCHRONOUSLY — the `W6WApi.runWorkflow` facade member's\n * backing function (the Workflows tab's Test stage, D-11/D-15(c)). A sibling\n * of {@link runWorkflow}, NOT a replacement: that function's enqueue-then-poll\n * shape is the studio-wide \"Run this workflow\" action and stays exactly as it\n * is. This one instead sends `wait: true` on the SAME base `client.workflows\n * .run` call already published (`?wait=true` — the server polls internally,\n * up to its own timeout) — zero new server code, and no second poll loop:\n * there is no `pollRunToTerminal` here at all. `terminal`/`httpStatus` on the\n * result distinguish \"finished in time\" (`200`) from \"still going when the\n * server's own wait timed out\" (`202`, a legitimate outcome, not an error).\n */\nexport function runWorkflowSync(\n client: W6WClient,\n id: string,\n variables: Record<string, unknown>,\n input?: Record<string, unknown>,\n entry?: string,\n): Promise<WorkflowRunResult> {\n return client.workflows.run(id, { variables, input, entry, wait: true });\n}\n\n/**\n * T2.1.1 — the ENQUEUE half only: starts a run and returns its handle\n * immediately, without polling it to terminal. A genuine sibling of\n * {@link runWorkflow}, NOT a replacement — that function's \"enqueue, then\n * block to a terminal result\" shape is what `WorkflowDetailPage.tsx`'s \"Run\n * now\" panel is built on and stays exactly as it is. This one is for a host\n * that wants the `runId` right away so it can poll it live itself (the\n * visual editor's canvas + execution log panel) — see {@link useLiveRunQuery}.\n *\n * Like {@link runWorkflow}, this calls `client.workflows.run()` with\n * `allowUnpublished: true` unconditionally. Only `{ runId }` is returned, so\n * callers keep reading `runId` off the resolved value exactly as before.\n */\nexport function startWorkflowRun(\n client: W6WClient,\n id: string,\n variables: Record<string, unknown>,\n input?: Record<string, unknown>,\n) {\n return client.workflows\n .run(id, { variables, input, allowUnpublished: true })\n .then((res) => ({ runId: res.runId }));\n}\n\n/** What {@link startRunFromNode} sends: the paused nodes to stop before, and the start seed. */\nexport interface RunFromNodeBody {\n /** Node ids the run stops BEFORE (they do not execute) — the editor's paused nodes. */\n stopAt: string[];\n /** Upstream outputs keyed by node id, seeded from saved step tests / the last run. */\n nodes?: Record<string, { output?: unknown; meta?: unknown }>;\n /** The trigger's filled values, when the run starts at a trigger node. */\n input?: Record<string, unknown>;\n}\n\n/**\n * Run from a node — `POST /workflows/:id/nodes/:nodeId/run` with `continue: true`: a REAL run\n * that executes `nodeId`, continues through every node downstream of it the way a run follows\n * its edges, and stops before each `stopAt` node. Answers `202 { runId }` at once, like\n * {@link startWorkflowRun}, so the caller polls it live ({@link useLiveRunQuery}). The run\n * executes the STORED definition, so a caller flushes its draft first.\n *\n * The plain `client.request()` escape hatch, not a typed `@w6w/sdk` method: the route is a\n * console authoring aid, and a typed method would pull `packages/wrappers` (every language, in\n * lockstep) into an editor-only change.\n */\nexport async function startRunFromNode(\n client: W6WClient,\n id: string,\n nodeId: string,\n body: RunFromNodeBody,\n): Promise<{ runId: string }> {\n const res = await client.request<{ runId: string }>({\n method: \"POST\",\n path: path`/workflows/${id}/nodes/${nodeId}/run`,\n body: {\n continue: true,\n stopAt: body.stopAt,\n ...(body.nodes ? { state: { nodes: body.nodes } } : {}),\n ...(body.input ? { input: body.input } : {}),\n },\n });\n return { runId: res.body.runId };\n}\n\n/** A node output's structural shape, as the server records it (structural mirror of `@w6w/ui`'s). */\nexport type NodeSampleShape =\n | { type: \"string\" | \"number\" | \"boolean\" | \"null\" | \"unknown\" }\n | { type: \"object\"; fields: Record<string, NodeSampleShape> }\n | { type: \"array\"; items?: NodeSampleShape };\n\n/**\n * One persisted node sample — structural mirror of `@w6w/ui`'s `NodeSample` (this barrel may not\n * import `@w6w/ui`; the facade/UiBridge assignment typechecks against `W6WApi` structurally).\n */\nexport interface NodeSample {\n nodeId: string;\n shape: NodeSampleShape;\n sample?: unknown;\n sampleOmitted?: true;\n source: \"step_test\" | \"node_run\" | \"run\";\n runId?: string;\n updatedAt: string;\n}\n\n/**\n * The workflow's persisted node samples — `GET /workflows/:id/node-samples` → `{ nodeSamples }`:\n * each node's last output shape (and value, when kept), written server-side on every Test, node\n * run and run. Backs `W6WApi.loadNodeSamples`, so the editor's picker keeps upstream keys across a\n * reload. The plain `client.request()` escape hatch, for the same reason as {@link startRunFromNode}.\n */\nexport function listNodeSamples(client: W6WClient, id: string): Promise<NodeSample[]> {\n return client\n .request<{ nodeSamples?: NodeSample[] }>({\n method: \"GET\",\n path: path`/workflows/${id}/node-samples`,\n })\n .then((res) => res.body.nodeSamples ?? []);\n}\n\n/** One remembered node test input — structural mirror of `@w6w/ui`'s `NodeTestInput`. */\nexport interface NodeTestInput {\n nodeId: string;\n input: Record<string, unknown>;\n updatedAt: string;\n}\n\n/**\n * The test input each node of the workflow last ran with in the editor —\n * `GET /workflows/:id/test-inputs` → `{ testInputs }` (`node_test_inputs`, 0160). Backs\n * `W6WApi.loadTestInputs`, so the Run node modal, the Test tabs and the header Run reopen\n * prefilled. The plain `client.request()` escape hatch, for the same reason as {@link startRunFromNode}.\n */\nexport function listTestInputs(client: W6WClient, id: string): Promise<NodeTestInput[]> {\n return client\n .request<{ testInputs?: NodeTestInput[] }>({\n method: \"GET\",\n path: path`/workflows/${id}/test-inputs`,\n })\n .then((res) => res.body.testInputs ?? []);\n}\n\n/**\n * Remember a node's test input (`{}` clears it) — `PUT /workflows/:id/nodes/:nodeId/test-input`.\n * Backs `W6WApi.saveTestInput`; the server drops sealed envelopes before the write.\n */\nexport function saveTestInput(\n client: W6WClient,\n id: string,\n nodeId: string,\n input: Record<string, unknown>,\n): Promise<void> {\n return client\n .request<{ ok: boolean }>({\n method: \"PUT\",\n path: path`/workflows/${id}/nodes/${nodeId}/test-input`,\n body: { input },\n })\n .then(() => undefined);\n}\n\nexport function useRunFromNodeMutation() {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: (vars: { id: string; nodeId: string; body: RunFromNodeBody }) =>\n startRunFromNode(apiClient, vars.id, vars.nodeId, vars.body),\n onSuccess: (_res, vars) => qc.invalidateQueries({ queryKey: runsKey(vars.id) }),\n onSettled: () => qc.invalidateQueries({ queryKey: historyKeys.root }),\n });\n}\n\nexport function useStartRunMutation() {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: (vars: {\n id: string;\n variables: Record<string, unknown>;\n input?: Record<string, unknown>;\n }) => startWorkflowRun(apiClient, vars.id, vars.variables, vars.input),\n onSuccess: (_res, vars) => qc.invalidateQueries({ queryKey: runsKey(vars.id) }),\n onSettled: () => qc.invalidateQueries({ queryKey: historyKeys.root }),\n });\n}\n\n/** What `client.workflows.cancel` resolves to. Named here because the SDK's root entry does not\n * export its `WorkflowCancelResult`: an inferred return type would name it and `vite-plugin-dts`\n * would skip this whole file (TS2742), leaving every `./repos` declaration out of the tarball. */\nexport type WorkflowCancelResult = Awaited<ReturnType<W6WClient[\"workflows\"][\"cancel\"]>>;\n\n/**\n * T2.1.1/A6 — cancel a queued or running run. `client.workflows.cancel`\n * itself never claims the run has stopped (its own doc comment: a `202`\n * means the request was RECORDED, not that the run finished) — the caller\n * keeps polling {@link useLiveRunQuery} until the run actually reaches a\n * terminal status. See `../lib/workflow-live-run.ts`'s `classifyCancelError`\n * for how a `409 run_not_cancelable` (the run beat the cancel to the finish\n * line) is told apart from a real failure.\n */\nexport function cancelWorkflowRun(client: W6WClient, runId: string): Promise<WorkflowCancelResult> {\n return client.workflows.cancel(runId);\n}\n\nexport function useCancelRunMutation(): UseMutationResult<WorkflowCancelResult, Error, string> {\n const apiClient = useEmbedClient();\n return useMutation({\n mutationFn: (runId: string) => cancelWorkflowRun(apiClient, runId),\n });\n}\n\n/** The single-shot half of {@link useLiveRunQuery} — a thin, directly\n * testable wrapper around `client.console.workflows.getRun`, so the polling\n * config below can be pinned without needing to render a hook. */\nexport function getRunState(client: W6WClient, runId: string): Promise<RunState> {\n return client.console.workflows.getRun(runId);\n}\n\n/** Query key for one run's live state — distinct from {@link runsKey}, which\n * is the workflow's run LIST. */\nexport const runStateKey = (runId: string) => [\"run\", runId] as const;\n\n/** The client's base URL, token and default headers, or `null` when it has none to stream with\n * (a test double, or a runtime without `fetch`) — the hooks then poll exactly as before. */\nfunction streamConfigOf(client: W6WClient): StreamClientConfig | null {\n const config = (client as { config?: Partial<StreamClientConfig> }).config;\n if (!config || typeof config.baseUrl !== \"string\") return null;\n if (typeof globalThis.fetch !== \"function\") return null;\n return { baseUrl: config.baseUrl, token: config.token ?? null, headers: config.headers };\n}\n\nconst streamRegistries = new WeakMap<W6WClient, WeakMap<QueryClient, RunStreamRegistry | null>>();\n\n/**\n * The run-stream registry for this client and query cache — one stream per run, shared by every\n * hook watching it (`../lib/run-event-stream.ts`). Each `snapshot` the server pushes is written\n * straight into {@link runStateKey}'s cache entry (it is the same `RunState` a poll returns), and\n * when a step's status changes the run's state-write log is re-read once, instead of on a timer.\n */\nfunction runStreamRegistry(client: W6WClient, qc: QueryClient): RunStreamRegistry | null {\n let byCache = streamRegistries.get(client);\n if (!byCache) {\n byCache = new WeakMap();\n streamRegistries.set(client, byCache);\n }\n if (byCache.has(qc)) return byCache.get(qc) ?? null;\n const config = streamConfigOf(client);\n const registry = config\n ? new RunStreamRegistry((runId, signal, onMode) => {\n let signature: string | null = null;\n void streamRun({\n config,\n runId,\n signal,\n onMode,\n fetchImpl: (url, init) => globalThis.fetch(url, init),\n onSnapshot: (run) => {\n qc.setQueryData(runStateKey(runId), run as unknown as RunState);\n const next = stateWritesSignature(run);\n if (signature !== null && next !== signature) {\n void qc.invalidateQueries({\n queryKey: [...runStateKey(runId), \"state-writes\", \"live\"],\n });\n }\n signature = next;\n },\n });\n })\n : null;\n byCache.set(qc, registry);\n return registry;\n}\n\n/** The run's stream mode (`null`: nothing streams it), re-rendering on every change. */\nfunction useRunStreamMode(registry: RunStreamRegistry | null, runId: string | null) {\n const subscribe = useCallback(\n (onChange: () => void) =>\n registry && runId != null ? registry.subscribe(runId, onChange) : () => {},\n [registry, runId],\n );\n const read = (): RunStreamMode | null =>\n registry && runId != null ? registry.mode(runId) : null;\n return useSyncExternalStore(subscribe, read, () => null);\n}\n\n/**\n * One run's live state, PUSHED by the server while it is in flight: the hook opens\n * `GET /runs/:id/events` (one stream per run, shared — {@link runStreamRegistry}) and every\n * snapshot lands in this query's cache, so `data` updates the moment a step starts or finishes and\n * nothing is fetched while the run is idle. The stream ends at a terminal status.\n *\n * POLLING IS THE FALLBACK, NEVER GONE. Whenever the stream is refused (an older server, an auth\n * refusal, a buffering proxy that holds the first snapshot past 3 s) or down (reconnecting with\n * backoff), the query polls exactly as it used to — every 500 ms until a terminal status\n * ({@link shouldContinuePolling}, `../lib/workflow-live-run.ts`) — so a run never looks frozen;\n * it stops polling again as soon as the stream is back. A client with nothing to stream with (a\n * test double) only polls. `runId === null` disables the query entirely (no run started yet, or\n * the page navigated to a different workflow). A run already cached as terminal is neither\n * streamed nor refetched: nothing about it changes again.\n */\nexport function useLiveRunQuery(runId: string | null) {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n const registry = runStreamRegistry(apiClient, qc);\n const mode = useRunStreamMode(registry, runId);\n const cached = runId != null ? qc.getQueryData<RunState>(runStateKey(runId)) : undefined;\n const settled = cached !== undefined && !shouldContinuePolling(cached.status);\n const streaming = registry !== null && runId != null && !settled;\n // Before the effect below has opened the stream (`mode === null` on the first render), the\n // stream is about to own the cache: count it as connecting so no poll races the first snapshot.\n const poll = streaming ? pollWhileStreaming(mode ?? \"connecting\") : !settled;\n useEffect(() => {\n if (!streaming || registry === null || runId == null) return;\n return registry.acquire(runId);\n }, [registry, runId, streaming]);\n return useQuery({\n queryKey: runStateKey(runId ?? \"\"),\n queryFn: () => getRunState(apiClient, runId as string),\n enabled: runId != null && poll,\n refetchInterval: (query) =>\n poll && shouldContinuePolling(query.state.data?.status) ? 500 : false,\n });\n}\n\n/** `GET /runs/:id/state-writes` — the run's state-write log (plan §2.4). */\nexport interface RunStateWrites {\n writes: StateLogRow[];\n truncated: boolean;\n}\n\n/**\n * One run's state-write log, read for the run log's State block (\"state after this\n * step\"). The plain `client.request()` escape hatch, for the same reason as\n * {@link listNodeSamples}: the route has no typed `@w6w/sdk` method.\n */\nexport function getRunStateWrites(client: W6WClient, runId: string): Promise<RunStateWrites> {\n return client\n .request<{ writes?: StateLogRow[]; truncated?: boolean }>({\n method: \"GET\",\n path: path`/runs/${runId}/state-writes`,\n })\n .then((res) => ({ writes: res.body.writes ?? [], truncated: res.body.truncated === true }));\n}\n\n/** Query key for one run's state-write log. The last segment flips from `\"live\"` to\n * `\"final\"` when the run turns terminal, so the final log is fetched exactly once more. */\nexport function runStateWritesKey(runId: string, status: RunStatus | undefined) {\n return [\"run\", runId, \"state-writes\", shouldContinuePolling(status) ? \"live\" : \"final\"] as const;\n}\n\n/**\n * One run's state-write log beside {@link useLiveRunQuery}. While the run streams, it is re-read\n * when a step's status changes ({@link runStreamRegistry} invalidates it) rather than on a timer;\n * while the run polls instead (stream refused or down, or no stream at all), it polls on the same\n * 500 ms cadence. Read once more, under the `\"final\"` key, when the run turns terminal. `retry:\n * false` — a failed read only leaves the run log without its State block; it never touches the\n * run read.\n */\nexport function useRunStateWritesQuery(runId: string | null, status: RunStatus | undefined) {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n const registry = runStreamRegistry(apiClient, qc);\n const mode = useRunStreamMode(registry, runId);\n const live = shouldContinuePolling(status);\n const streamed = registry !== null && runId != null && mode !== \"fallback\";\n return useQuery({\n queryKey: runStateWritesKey(runId ?? \"\", status),\n queryFn: () => getRunStateWrites(apiClient, runId as string),\n enabled: runId != null,\n refetchInterval: live && !streamed ? 500 : false,\n retry: false,\n });\n}\n","/**\n * The `documents` domain repo — wraps `@w6w/sdk`'s `client.documents.*` in\n * react-query (HITL-6). `QueryClientProvider` (`main.tsx`) stays the actual\n * cache; this module only centralizes the query-key factory and the\n * `queryFn`/`mutationFn` pairs so every page reads documents the same way.\n *\n * Documents are project-scoped (`documents.ts`'s `DocumentOptions.project`);\n * every mutation here invalidates the unscoped `[\"documents\"]` key, which\n * prefix-matches every project-scoped query key produced by\n * {@linkcode documentsKey} — the same invalidation shape `DocumentsPage.tsx`\n * used before this migration.\n */\nimport { useMutation, useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport {\n path,\n type Doc,\n type DocumentCreateInput,\n type DocumentPatch,\n type W6WClient,\n} from \"@w6w/sdk\";\nimport { useEmbedClient } from \"../draft/client-context.ts\";\n\n/**\n * T1.1.1's wire shape for one document, pinned here ahead of that node\n * merging (this node is dispatched speculatively against it — see this\n * task's contract). `shared` and the six `source*`/`syncedAt` fields are all\n * additive over the SDK's own `Doc`, so a locally-created document simply\n * carries them as `null` (or `false` for `shared`) rather than omitting\n * them. Do not rename a field — the server produces these names verbatim.\n */\nexport interface DocWithProvenance extends Doc {\n shared: boolean;\n /** \"owner/name\" of the bound repository this document was pulled from. */\n sourceRepo: string | null;\n /** Repo-relative file path the document was pulled from. */\n sourcePath: string | null;\n /** The pulled file's content hash — NOT a commit SHA. */\n sourceSha: string | null;\n /** The repository's HEAD commit SHA at pull time — NOT a content hash. */\n sourceRefSha: string | null;\n /** Web link to the file; may be absent even when the rest of provenance is set. */\n sourceUrl: string | null;\n /** ISO-8601. Stamped at the document's last actual change, not at every sync. */\n syncedAt: string | null;\n}\n\n/**\n * Which provenance state `DocumentDetailPage.tsx`'s \"Source\" card should\n * render for `doc`. `shared` (not `sourceRepo`) is the gate: a shared\n * document whose provenance columns haven't been stamped yet (any document\n * synced before this feature shipped, until its next real-content sync —\n * tier-1 \"unchanged\" syncs never restamp provenance) is still shared, and\n * must say so, distinct from a genuinely private document.\n *\n * - `\"private\"` — `doc.shared` is false. No card.\n * - `\"pending\"` — shared, but `sourceRepo` hasn't been stamped yet.\n * - `\"synced\"` — shared, with full provenance available.\n */\nexport function documentProvenanceState(doc: DocWithProvenance): \"private\" | \"pending\" | \"synced\" {\n if (!doc.shared) return \"private\";\n return doc.sourceRepo == null ? \"pending\" : \"synced\";\n}\n\n/** Query key for a documents list, optionally scoped to a project. */\nexport function documentsKey(projectId?: string) {\n return [\"documents\", projectId] as const;\n}\n\n/**\n * Query key for a single document, scoped to a project (mirrors\n * {@linkcode useDocumentsQuery}'s fix at :72-79/:80-87 below — `projectId`\n * belongs in the key itself, not just the `queryFn`, so a render where the\n * key was cached under `projectId === undefined` genuinely changes key once\n * `ProjectContext` resolves the real one, instead of reusing the same cache\n * entry — and its `retry: false` wrong-project 404 — forever). Still sits\n * under the bare `[\"documents\"]` prefix every mutation below invalidates, so\n * an edit/delete refreshes this page too — `\"detail\"` keeps it from\n * colliding with {@linkcode documentsKey}'s own `[\"documents\", projectId]`\n * shape.\n */\nexport function documentKey(id: string, projectId?: string) {\n return [\"documents\", \"detail\", id, projectId] as const;\n}\n\n/**\n * A single document by id, cast to {@link DocWithProvenance} (D-5): the SDK's\n * `Doc` doesn't model T1.1.1's provenance fields yet, and this repo is not\n * the place to fork or extend `@w6w/sdk` (D-4). The `project` option is\n * passed exactly as {@linkcode useDocumentsQuery} passes it — a document in a\n * non-default project 404s without it. `enabled` defaults `true` to preserve\n * that unscoped fallback for a caller that genuinely wants it — same as\n * {@linkcode useDocumentsQuery}'s own `enabled` doc comment below — a\n * project-scoped page should instead pass `enabled: projectId != null` so it\n * never queries (and never renders) against the wrong project while\n * `ProjectContext`'s own project list is still resolving.\n */\nexport function useDocumentQuery(id: string, projectId?: string, enabled = true) {\n const apiClient = useEmbedClient();\n return useQuery({\n queryKey: documentKey(id, projectId),\n queryFn: async () =>\n (await apiClient.documents.get(id, { project: projectId })) as DocWithProvenance,\n enabled,\n });\n}\n\n/**\n * The current project's documents (or the tenant default when unscoped).\n * `enabled` defaults `true` to preserve that unscoped fallback for a caller\n * that genuinely wants it — a project-scoped page should instead pass\n * `enabled: projectId != null` so it never queries (and never renders)\n * against the wrong project while `ProjectContext`'s own project list is\n * still resolving.\n */\nexport function useDocumentsQuery(projectId?: string, enabled = true) {\n const apiClient = useEmbedClient();\n return useQuery({\n queryKey: documentsKey(projectId),\n // Cast to DocWithProvenance[], same as useDocumentQuery above: the wire\n // response already carries `shared`/`source*`/`syncedAt` (repo.list()\n // serializes every document the same way repo.get() does), but the SDK's\n // own `Doc` type doesn't declare them yet (D-5). Without this cast,\n // DocumentsPage.tsx's list rows have no type-visible way to branch on\n // `d.shared` the way DocumentDetailPage.tsx already does.\n queryFn: async () =>\n (await apiClient.documents.list({ project: projectId })) as DocWithProvenance[],\n enabled,\n });\n}\n\nexport function useCreateDocumentMutation() {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: (vars: { input: DocumentCreateInput; project?: string }) =>\n apiClient.documents.create(vars.input, { project: vars.project }),\n onSuccess: () => qc.invalidateQueries({ queryKey: [\"documents\"] }),\n });\n}\n\nexport function useUpdateDocumentMutation() {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: (vars: { id: string; patch: DocumentPatch; project?: string }) =>\n apiClient.documents.update(vars.id, vars.patch, { project: vars.project }),\n onSuccess: () => qc.invalidateQueries({ queryKey: [\"documents\"] }),\n });\n}\n\nexport function useDeleteDocumentMutation() {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: (vars: { id: string; project?: string }) =>\n apiClient.documents.delete(vars.id, { project: vars.project }),\n onSuccess: () => qc.invalidateQueries({ queryKey: [\"documents\"] }),\n });\n}\n\n/**\n * Re-pulls a shared document from its bound repository (\"Sync\" button, T2.1.4)\n * — `POST /documents/:id/sync` (T3.1.1). No SDK method exists for this route\n * yet (D-4/D-5), so this goes through `apiClient.request()` directly, same\n * escape hatch `repo-sync.ts`'s `useSyncRepoNowMutation` uses. The document\n * routes are project-scoped by QUERY param, not a path segment (unlike\n * `repo-binding`'s `/projects/:id/...` shape), so `project` travels in\n * `query`, mirroring {@linkcode useDocumentQuery}'s own `{ project: … }` use.\n */\nexport function useSyncDocumentMutation() {\n const apiClient = useEmbedClient();\n const qc = useQueryClient();\n return useMutation({\n mutationFn: (vars: { id: string; project?: string }) =>\n apiClient.request<{ document: DocWithProvenance }>({\n method: \"POST\",\n path: path`/documents/${vars.id}/sync`,\n query: { project: vars.project },\n }),\n onSuccess: () => qc.invalidateQueries({ queryKey: [\"documents\"] }),\n });\n}\n\n/**\n * The project's document keys and formats, for the ui's `document` step-param picker\n * (`W6WApi.listDocuments`, `@w6w/document · get`). Hook-less so that seam can call it.\n */\nexport async function listDocumentKeys(\n client: W6WClient,\n project: string,\n): Promise<{ key: string; format: string }[]> {\n const docs = await client.documents.list({ project });\n return docs.map((d) => ({ key: d.key, format: d.format }));\n}\n"],"names":["runNodeMap","run","STEP_FAILED_NO_REASON","RUN_FAILED_NO_REASON","shouldContinuePolling","status","isTerminalRunStatus","isRunInFlight","pollFailed","STEP_PASS_REFRESH_DELAYS_MS","stepPassRefreshDue","runWorkflowId","workflowId","runButtonLabel","classifyCancelError","code","mapRunStateToLogSteps","steps","stateLog","state","stateFieldsByNode","id","step","mapStep","iterationFields","log","rows","a","b","byNode","row","entry","group","out","writes","lastSeq","foldStateLog","SKIP_REASONS","line","usageOf","rowError","raw","ok","v","memoryBytes","cpuMs","usage","ITERATION_STATUSES","iterations","it","nodes","s","failedNodeId","_a","finite","n","error","toLogError","o","message","safeJson","runLevelErrors","carried","r","reasoned","stepErrors","e","own","sameAsOwn","runError","latestFixtureInput","tests","last","resolveHeaderRunInput","triggerStepId","list","remembered","input","headerRunEntry","isManualTrigger","isEntryTrigger","manual","other","TERMINAL","realSleep","ms","resolve","pollRunToTerminal","getRun","sleep","i","EMPTY_HISTORY_FILTERS","TRIGGER_FILTER_RE","triggerFilterQuery","trigger","value","HISTORY_PAGE_SIZE","VALID_STATUSES","VALID_KINDS","DATE_RE","isRealDate","y","m","d","dateParts","dt","filtersFromSearch","search","params","kind","from","to","q","offsetRaw","offset","filtersToSearch","f","historyRequestQuery","scope","opts","query","historyKeys","limit","callableId","getHistory","client","response","getHistoryStats","describeWorkflowNodes","workflow","app","action","_b","_c","registered","names","wantsTriggers","detail","triggers","titles","t","node","named","title","BUILT_IN_TRIGGERS","workflowTriggers","nodeId","builtIn","label","seen","runTriggerLabel","summary","x","getExecutionDetail","described","started","invocation","invocationIdOf","err","asRecord","startRerun","callable","runId","past","body","rerunExecution","findExecution","SseParser","__privateAdd","_buf","_event","_data","chunk","__privateSet","__privateGet","nl","colon","field","runEventsPath","isTerminalRunStatusLike","streamHeaders","config","abortableSleep","signal","done","timer","streamRun","retryMin","retryMax","retry","mode","report","next","finish","attempt","live","final","setLive","firstSnapshotMs","idleTimeoutMs","ctl","onAbort","sawSnapshot","slow","idleTimer","touch","headers","res","type","reader","decoder","parser","ev","RunStreamRegistry","start","_RunStreamRegistry_instances","_entries","_modeListeners","_start","listener","set","created","__privateMethod","notify_fn","held","released","fn","pollWhileStreaming","stateWritesSignature","parts","workflowsKey","project","listWorkflows","useWorkflowsQuery","enabled","apiClient","useEmbedClient","useQuery","workflowKey","getWorkflow","useWorkflowQuery","useCreateWorkflowMutation","qc","useQueryClient","useMutation","definition","useSaveWorkflowMutation","vars","useArchiveWorkflowMutation","useDeleteWorkflowMutation","runsKey","useRunsQuery","runWorkflow","variables","useRunWorkflowMutation","_res","runWorkflowSync","startWorkflowRun","startRunFromNode","path","listNodeSamples","listTestInputs","saveTestInput","useRunFromNodeMutation","useStartRunMutation","cancelWorkflowRun","useCancelRunMutation","getRunState","runStateKey","streamConfigOf","streamRegistries","runStreamRegistry","byCache","registry","onMode","signature","url","init","useRunStreamMode","subscribe","useCallback","onChange","useSyncExternalStore","useLiveRunQuery","cached","settled","streaming","poll","useEffect","getRunStateWrites","runStateWritesKey","useRunStateWritesQuery","streamed","documentProvenanceState","doc","documentsKey","projectId","documentKey","useDocumentQuery","useDocumentsQuery","useCreateDocumentMutation","useUpdateDocumentMutation","useDeleteDocumentMutation","useSyncDocumentMutation","listDocumentKeys"],"mappings":";;;;;;;;;;AA+FO,SAASA,GACdC,GAC+C;AAC/C,UAAQA,KAAA,gBAAAA,EAAK,WAASA,KAAA,gBAAAA,EAAK,UAAS;AACtC;AASO,MAAMC,IAAwB,2CAGxBC,KAAuB;AAyD7B,SAASC,EAAsBC,GAAwC;AAC5E,SAAOA,MAAW,UAAa,CAACC,EAAoBD,CAAM;AAC5D;AAYO,SAASE,GAAcF,GAA+BG,GAA8B;AAEzF,SADIA,KACAH,MAAW,SAAkB,KAC1B,CAACC,EAAoBD,CAAM;AACpC;AASO,MAAMI,KAAiD,CAAC,GAAG,IAAI;AAQ/D,SAASC,GACdL,GACAM,GACAC,GACS;AACT,SAAOP,MAAW,UAAaC,EAAoBD,CAAM,KAAKM,MAAkBC;AAClF;AAGO,SAASC,GAAeR,GAA+BG,GAA6B;AACzF,SAAKD,GAAcF,GAAQG,CAAU,IAC9BH,MAAW,WAAW,YAAY,aADM;AAEjD;AASO,SAASS,GAAoBC,GAAkC;AACpE,SAAOA,MAAS,uBAAuB,cAAc;AACvD;AAQO,SAASC,GACdC,GACAC,GACwB;AACxB,MAAI,CAACD,EAAO,QAAO,CAAA;AACnB,QAAME,IAAQD,IAAWE,GAAkBF,CAAQ,IAAI;AACvD,SAAO,OAAO,QAAQD,CAAK,EAAE,IAAI,CAAC,CAACI,GAAIC,CAAI,OAAO;AAAA,IAChD,GAAGC,EAAQF,GAAIC,CAAI;AAAA,IACnB,GAAGE,EAAgBF,CAAI;AAAA,IACvB,IAAIH,KAAA,gBAAAA,EAAO,IAAIE,OAAO,CAAA;AAAA,EAAC,EACvB;AACJ;AAUA,SAASD,GACPK,GACuE;AACvE,QAAMC,IAAO,CAAC,GAAGD,CAAG,EAAE,KAAK,CAACE,GAAGC,MAAM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EAAK,QAAA,CAAS;AAAA,IAC/D,WAAW,MAAML,EAAG,kBAAkB,EAAE,UAAU,CAAC,WAAW,EAAA,CAAG;AAAA,EAAA,CAClE;AACH;AAWO,SAAS6D,KAA0B;AACxC,QAAMpE,IAAYC,EAAA,GACZM,IAAKC,EAAA;AACX,SAAOC,EAAY;AAAA,IACjB,YAAY,CAACG,MACXZ,EAAU,QAAyC;AAAA,MACjD,QAAQ;AAAA,MACR,MAAMwB,eAAkBZ,EAAK,EAAE;AAAA,MAC/B,OAAO,EAAE,SAASA,EAAK,QAAA;AAAA,IAAQ,CAChC;AAAA,IACH,WAAW,MAAML,EAAG,kBAAkB,EAAE,UAAU,CAAC,WAAW,EAAA,CAAG;AAAA,EAAA,CAClE;AACH;AAMA,eAAsB8D,GACpBnL,GACA0G,GAC4C;AAE5C,UADa,MAAM1G,EAAO,UAAU,KAAK,EAAE,SAAA0G,GAAS,GACxC,IAAI,CAAChI,OAAO,EAAE,KAAKA,EAAE,KAAK,QAAQA,EAAE,OAAA,EAAS;AAC3D;"}
package/dist/draft.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  import { A as a, c as s, i as t, n as o, r as i, u } from "./use-workflow-draft-l3P5KZzw.js";
3
3
  import { E as n, u as l } from "./client-context-CX61Bgw-.js";
4
4
  import { D as E, c, u as d } from "./draft-registry-YF0tqNN0.js";
5
- import { u as p, a as x, b as S } from "./use-callable-draft-w4tDTYcb.js";
5
+ import { u as p, a as x, b as S } from "./use-callable-draft-7HwfTuYQ.js";
6
6
  export {
7
7
  a as AUTOSAVE_DEBOUNCE_MS,
8
8
  E as DraftRegistryProvider,
@@ -0,0 +1,19 @@
1
+ import { ReactNode } from 'react';
2
+ /** A form a run is waiting on: the step it belongs to and its private link (`GET /runs/:id`). */
3
+ export interface WaitingForm {
4
+ stepId: string;
5
+ url: string;
6
+ }
7
+ /** The run's `waitingForms`, read defensively off the polled run record (absent when none). */
8
+ export declare function waitingFormsOf(run: unknown): WaitingForm[];
9
+ export interface WaitingFormPanelProps {
10
+ forms: WaitingForm[];
11
+ /** The step's display name, when the workflow gives it one. */
12
+ labelOf?: (stepId: string) => string | undefined;
13
+ }
14
+ /**
15
+ * A run paused at a form reached mid-run: the form itself, inline, so the author answers it and the
16
+ * run continues in place, plus "Open form" for the same page in its own tab (the link works for
17
+ * anyone it is shared with). Answering it wakes the run; the next poll drops the panel.
18
+ */
19
+ export declare function WaitingFormPanel({ forms, labelOf }: WaitingFormPanelProps): ReactNode;
@@ -1,6 +1,6 @@
1
1
  import { jsxs as C, jsx as u } from "react/jsx-runtime";
2
- import { u as oe, a as se, b as ie, c as le, d as ce, e as ae } from "./apps-CFWdgGst.js";
3
- import { r as ue, H as j, t as de } from "./workflows-RhR8kwt7.js";
2
+ import { u as oe, a as se, b as ie, c as le, d as ce, e as ae } from "./apps-CyEszfIu.js";
3
+ import { r as ue, H as j, t as de } from "./documents-hgltn0xe.js";
4
4
  import { ExecutionDetail as fe, ExecutionStats as ge, ExecutionFilters as pe, ExecutionList as me, useW6WApi as we } from "@w6w/ui";
5
5
  import { useRef as w, useState as R, useEffect as W, useLayoutEffect as ye, useCallback as Y, useMemo as V } from "react";
6
6
  import { useQuery as Ee } from "@tanstack/react-query";
@@ -175,4 +175,4 @@ export {
175
175
  ke as a,
176
176
  He as u
177
177
  };
178
- //# sourceMappingURL=editor-apps-ShwCmvLY.js.map
178
+ //# sourceMappingURL=editor-apps-DsGrGKfe.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"editor-apps-ShwCmvLY.js","sources":["../src/chrome/HistoryView.tsx","../src/editor/editor-apps.ts"],"sourcesContent":["/**\n * `HistoryView` — the execution-history view body (T3.2.1, extracted from\n * `HistoryPage.tsx`'s T2.4.1 shape): stats + filters + paged list, OR the\n * selected execution's detail — never both. Opening a row swaps the list for\n * that execution (with a Back control to return to the list where it was\n * left); it does not stack the detail under a long list, where it lands\n * off-screen. Two hosts mount it — `HistoryPage` (the\n * project-wide and per-callable routes, filters URL-backed) and\n * `HistoryModal` (R-2's in-place modal, filters kept in local state) — so\n * this component owns every judgment call about HOW the view behaves, and\n * takes no position on WHERE its filters live: the host hands down\n * `filters` and gets every change back through `onFiltersChange`, exactly\n * the controlled-value shape `filtersToSearch`/`filtersFromSearch` already\n * assume on the URL-backed side.\n *\n * What stays here, same as it was in `HistoryPage` before the extraction:\n * - the search box's text, debounced, so a keystroke does not re-key and\n * re-issue both queries on every character (`onFiltersChange` — and so\n * the host's own write, URL or local state — fires only once typing\n * settles);\n * - which list row is selected, which is not shareable state and resets on\n * every mount;\n * - re-running an execution (a control on every row and in the detail): the\n * same input, against the callable's current definition. The view then\n * opens the NEW execution, so the outcome is what the author sees next;\n * - every filter change but paging snapping the page back to the first\n * (`offset` 0), because a narrowed result set has no meaningful \"page 3\".\n *\n * `onOpenInEditor`, when given, is called with the selected execution ONLY\n * while it is a workflow run (a function/endpoint invocation has no visual\n * editor to open) — the same gate `HistoryPage.tsx` applied inline before\n * this extraction. A host that never passes it (none of today's two do)\n * simply never sees the call.\n */\nimport {\n type ExecutionSummary,\n HISTORY_PAGE_SIZE,\n type HistoryFilters,\n type HistoryScope,\n runTriggerLabel,\n triggerFilterQuery,\n useExecutionDetailQuery,\n useFindExecution,\n useHistoryQuery,\n useHistoryStatsQuery,\n useRerunExecutionMutation,\n useWorkflowTriggers,\n} from \"@w6w/embed/repos\";\nimport {\n ExecutionDetail,\n type ExecutionFilterValue,\n ExecutionFilters,\n ExecutionList,\n ExecutionStats,\n} from \"@w6w/ui\";\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from \"react\";\n\n/** How long to wait after the last keystroke before `onFiltersChange` fires\n * with the new `q` (and so before either query re-issues with it). */\nconst SEARCH_DEBOUNCE_MS = 300;\n\n/** The nearest ancestor that actually scrolls (the modal body, the app's main\n * pane), or `null` when the document itself does. */\nfunction scrollParent(el: HTMLElement | null): HTMLElement | null {\n for (let p = el?.parentElement ?? null; p; p = p.parentElement) {\n const overflowY = getComputedStyle(p).overflowY;\n if ((overflowY === \"auto\" || overflowY === \"scroll\") && p.scrollHeight > p.clientHeight) {\n return p;\n }\n }\n return null;\n}\n\nexport interface HistoryViewProps {\n /** `null` ⇒ no scope known yet (the project-wide host, before its project\n * resolves) — both queries stay disabled, mirroring `repos/history.ts`'s\n * own `enabled: scope !== null`. */\n scope: HistoryScope | null;\n /** Project-wide chrome: the Kind filter, and the Callable column on every\n * row. A per-callable host (every callable already knows its own kind)\n * passes `false`. */\n showKind: boolean;\n filters: HistoryFilters;\n onFiltersChange: (next: HistoryFilters) => void;\n onOpenInEditor?: (execution: ExecutionSummary) => void;\n /** The scope is this one workflow: offer its triggers as a filter (\"which trigger started the\n * run\"), so one trigger's runs and stats can be reviewed on their own. */\n workflowId?: string;\n}\n\nexport function HistoryView(props: HistoryViewProps) {\n const { scope, showKind, filters, onFiltersChange, onOpenInEditor, workflowId } = props;\n\n // The debounce below fires outside any render, so it needs the LATEST\n // filters (a status picked while a `q` write was still pending must\n // survive it) rather than the ones captured when typing started.\n const filtersRef = useRef(filters);\n filtersRef.current = filters;\n\n const [q, setQ] = useState(filters.q);\n const searchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n const [selected, setSelected] = useState<ExecutionSummary | null>(null);\n\n // Keep the search box in step with `filters.q` when IT moves from outside\n // (Back/Forward or a shared link on the URL-backed host). This never\n // fights a keystroke: an outside `q` only changes once typing has\n // settled, by which point `q` already equals it.\n useEffect(() => {\n setQ(filters.q);\n }, [filters.q]);\n\n // Drop a pending debounce on unmount.\n useEffect(\n () => () => {\n if (searchTimer.current) clearTimeout(searchTimer.current);\n },\n [],\n );\n\n const listQuery = useHistoryQuery(scope, filters);\n const statsQuery = useHistoryStatsQuery(scope, filters);\n const detailQuery = useExecutionDetailQuery(selected);\n const rerun = useRerunExecutionMutation();\n const findExecution = useFindExecution();\n const [findError, setFindError] = useState<string | null>(null);\n\n // Swapping list ⇄ detail keeps the scroll offset of whatever scrolls around\n // this view, which would open a detail scrolled past its own top (the row\n // was clicked far down the list). So: remember the list's offset on the\n // way in, show the detail from its top, and put the list back on the way out.\n const viewRef = useRef<HTMLDivElement>(null);\n const listScroll = useRef<{ parent: HTMLElement | null; top: number } | null>(null);\n const selectedId = selected?.id ?? null;\n useLayoutEffect(() => {\n const el = viewRef.current;\n if (!el) return;\n if (selectedId !== null) {\n const parent = scrollParent(el);\n if (parent) parent.scrollTop = 0;\n else if (el.getBoundingClientRect().top < 0) el.scrollIntoView?.({ block: \"start\" });\n } else if (listScroll.current) {\n const { parent, top } = listScroll.current;\n listScroll.current = null;\n if (parent) parent.scrollTop = top;\n else window.scrollTo(0, top);\n }\n }, [selectedId]);\n\n const selectedRef = useRef(selected);\n selectedRef.current = selected;\n const open = useCallback((next: ExecutionSummary) => {\n // Leaving the LIST (not one detail for another, as a re-run from the detail does).\n if (selectedRef.current === null) {\n const parent = scrollParent(viewRef.current);\n listScroll.current = { parent, top: parent ? parent.scrollTop : window.scrollY };\n }\n setSelected(next);\n }, []);\n\n const rows = listQuery.data?.executions ?? [];\n // Every listed workflow's triggers, so each row names the trigger that started it — a run list\n // mixing three triggers is unreadable as `Event · <node id>` until each row is opened.\n const triggersByWorkflow = useWorkflowTriggers([\n ...(workflowId ? [workflowId] : []),\n ...rows.filter((r) => r.kind === \"workflow\").map((r) => r.callableId),\n ]);\n const executions = useMemo(\n () =>\n rows.map((r) =>\n r.kind === \"workflow\"\n ? { ...r, triggerLabel: runTriggerLabel(r, triggersByWorkflow.get(r.callableId) ?? []) }\n : r,\n ),\n [rows, triggersByWorkflow],\n );\n const ownTriggers = workflowId ? (triggersByWorkflow.get(workflowId) ?? []) : [];\n const triggerOptions = ownTriggers.map((t) => ({\n // A manual run records no entry node, so the Manual trigger filters by run kind instead.\n value: t.app === \"@w6w/trigger\" ? \"kind:manual\" : `entry:${t.nodeId}`,\n label: t.label,\n }));\n const offset = filters.offset;\n const hasMore = listQuery.data?.hasMore ?? false;\n\n /** Every filter change but paging reports a fresh filter set and resets\n * the page to the first. */\n const applyFilters = (next: ExecutionFilterValue) => {\n const trigger = next.trigger ?? \"\";\n onFiltersChange({\n ...next,\n trigger: Object.keys(triggerFilterQuery(trigger)).length > 0 ? trigger : \"\",\n offset: 0,\n });\n };\n\n const onChange = (next: ExecutionFilterValue) => {\n if (next.q === q) {\n applyFilters(next);\n return;\n }\n setQ(next.q);\n if (searchTimer.current) clearTimeout(searchTimer.current);\n searchTimer.current = setTimeout(() => {\n searchTimer.current = null;\n onFiltersChange({ ...filtersRef.current, q: next.q, offset: 0 });\n }, SEARCH_DEBOUNCE_MS);\n };\n\n const onPrev = () =>\n onFiltersChange({ ...filters, q, offset: Math.max(0, offset - HISTORY_PAGE_SIZE) });\n const onNext = () => onFiltersChange({ ...filters, q, offset: offset + HISTORY_PAGE_SIZE });\n\n const onSelect = useCallback(\n (executionId: string) => {\n const row = executions.find((r) => r.id === executionId);\n if (row) open(row);\n },\n [executions, open],\n );\n\n /** Re-run one execution, then open the new one — or, when it is not listed\n * yet, fall back to the (refreshed) list. */\n const startRerun = (summary: ExecutionSummary) => {\n rerun.mutate(summary, {\n onSuccess: (next) => {\n if (next) open(next);\n else setSelected(null);\n },\n });\n };\n const rerunningId = rerun.isPending ? (rerun.variables?.id ?? null) : null;\n\n /** \"Re-run of <id>\": open the original, from the callable this one belongs to. */\n const openOriginal = (callableId: string, id: string) => {\n setFindError(null);\n findExecution(callableId, id)\n .then((row) => {\n if (row) open(row);\n else setFindError(`${id} is no longer available.`);\n })\n .catch(() => setFindError(`Couldn't open ${id}.`));\n };\n const rerunError = rerun.isError ? (\n <p className=\"error\" data-testid=\"history-rerun-error\">\n Couldn't re-run: {rerun.error instanceof Error ? rerun.error.message : String(rerun.error)}\n </p>\n ) : null;\n\n const filterValue: ExecutionFilterValue = {\n status: filters.status,\n kind: filters.kind,\n from: filters.from,\n to: filters.to,\n q,\n trigger: filters.trigger,\n };\n\n // A workflow run is the only execution with a visual editor to jump into\n // — a function/endpoint invocation has no such surface.\n const openInEditor =\n selected?.kind === \"workflow\" && onOpenInEditor ? () => onOpenInEditor(selected) : undefined;\n\n if (selected) {\n return (\n <div ref={viewRef}>\n {rerunError}\n {findError && (\n <p className=\"error\" data-testid=\"history-find-error\">\n {findError}\n </p>\n )}\n <ExecutionDetail\n execution={detailQuery.data ?? null}\n loading={detailQuery.isLoading}\n errorMessage={detailQuery.isError ? \"This execution is no longer available.\" : undefined}\n onBack={() => {\n rerun.reset();\n setFindError(null);\n setSelected(null);\n }}\n onOpenExecution={(id) => openOriginal(selected.callableId, id)}\n onRerun={() => startRerun(selected)}\n rerunning={rerunningId !== null}\n onOpenInEditor={openInEditor}\n />\n </div>\n );\n }\n\n // `.w6w-card-stack` spaces stats → filters → list. A bare fragment left them touching: every host\n // wraps this view in one element (`RunHistory`'s embed root, `HistoryModal`'s body), so the\n // page's own flex gap never reached these siblings.\n return (\n <div className=\"w6w-card-stack\" data-testid=\"history-view\">\n <ExecutionStats stats={statsQuery.data ?? null} />\n\n <ExecutionFilters\n showKind={showKind}\n value={filterValue}\n onChange={onChange}\n triggerOptions={triggerOptions}\n />\n\n {listQuery.isError && (\n <p className=\"error\" data-testid=\"history-error\">\n Couldn't load execution history.\n </p>\n )}\n\n {rerunError}\n\n <div ref={viewRef}>\n <ExecutionList\n items={executions}\n showCallable={showKind}\n loading={listQuery.isLoading}\n hasPrev={offset > 0}\n hasNext={hasMore}\n onPrev={onPrev}\n onNext={onNext}\n onSelect={onSelect}\n onRerun={(id) => {\n const row = executions.find((r) => r.id === id);\n if (row) startRerun(row);\n }}\n rerunningId={rerunningId}\n />\n </div>\n </div>\n );\n}\n","/**\n * The canvas's app lookups, through the host-provided `W6WApi` (`useW6WApi()` — in an embed that\n * is `createW6WUiAdapter`'s, in Studio the facade, which delegates to the same store/repo).\n */\nimport { useQuery } from \"@tanstack/react-query\";\nimport { type AppSummary, useW6WApi } from \"@w6w/ui\";\nimport { useMemo } from \"react\";\n\n/** The per-app actions query key — the repos export itself (one declaration, no copy). */\nexport { appActionsKey } from \"../repos/apps.ts\";\n\nconst NO_APPS: ReadonlyMap<string, AppSummary> = new Map();\n\n/** A bounded set of app records by id. Empty when the host's API has no `listAppsByIds`. */\nexport function useEditorApps(ids: readonly string[]): { byId: ReadonlyMap<string, AppSummary> } {\n const api = useW6WApi();\n const list = api.listAppsByIds?.bind(api);\n const key = [...ids].sort().join(\",\");\n const q = useQuery({\n queryKey: [\"editor-apps\", key],\n queryFn: ({ signal }) => (list ? list(ids, { signal }) : Promise.resolve([] as AppSummary[])),\n enabled: ids.length > 0 && typeof list === \"function\",\n });\n const data = q.data;\n const byId = useMemo(\n () => (data ? new Map(data.map((a) => [a.id, a] as const)) : NO_APPS),\n [data],\n );\n return { byId };\n}\n\n/**\n * One app record by id, over {@link useEditorApps} (same `/apps` request, same cache entry as the\n * canvas's batch lookup). `undefined` while loading, for an empty id (which issues no request),\n * or when the host's API cannot look apps up by id.\n */\nexport function useEditorApp(id: string): AppSummary | undefined {\n const { byId } = useEditorApps(id ? [id] : []);\n return id ? byId.get(id) : undefined;\n}\n"],"names":["SEARCH_DEBOUNCE_MS","scrollParent","el","p","overflowY","HistoryView","props","scope","showKind","filters","onFiltersChange","onOpenInEditor","workflowId","filtersRef","useRef","q","setQ","useState","searchTimer","selected","setSelected","useEffect","listQuery","useHistoryQuery","statsQuery","useHistoryStatsQuery","detailQuery","useExecutionDetailQuery","rerun","useRerunExecutionMutation","findExecution","useFindExecution","findError","setFindError","viewRef","listScroll","selectedId","useLayoutEffect","parent","top","selectedRef","open","useCallback","next","rows","_a","triggersByWorkflow","useWorkflowTriggers","r","executions","useMemo","runTriggerLabel","triggerOptions","t","offset","hasMore","_b","applyFilters","trigger","triggerFilterQuery","onChange","onPrev","HISTORY_PAGE_SIZE","onNext","onSelect","executionId","row","startRerun","summary","rerunningId","_c","openOriginal","callableId","id","rerunError","jsxs","filterValue","openInEditor","jsx","ExecutionDetail","ExecutionStats","ExecutionFilters","ExecutionList","NO_APPS","useEditorApps","ids","api","useW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AAcC,GAAmE;;AAC/F,QAAMC,IAAMC,GAAA,GACNC,KAAO3C,IAAAyC,EAAI,kBAAJ,gBAAAzC,EAAmB,KAAKyC,IAC/BG,IAAM,CAAC,GAAGJ,CAAG,EAAE,KAAA,EAAO,KAAK,GAAG,GAM9BK,IALIC,GAAS;AAAA,IACjB,UAAU,CAAC,eAAeF,CAAG;AAAA,IAC7B,SAAS,CAAC,EAAE,QAAAG,EAAA,MAAcJ,IAAOA,EAAKH,GAAK,EAAE,QAAAO,GAAQ,IAAI,QAAQ,QAAQ,CAAA,CAAkB;AAAA,IAC3F,SAASP,EAAI,SAAS,KAAK,OAAOG,KAAS;AAAA,EAAA,CAC5C,EACc;AAKf,SAAO,EAAE,MAJItC;AAAA,IACX,MAAOwC,IAAO,IAAI,IAAIA,EAAK,IAAI,CAACG,MAAM,CAACA,EAAE,IAAIA,CAAC,CAAU,CAAC,IAAIV;AAAA,IAC7D,CAACO,CAAI;AAAA,EAAA,EAEE;AACX;AAOO,SAASI,GAAarB,GAAoC;AAC/D,QAAM,EAAE,MAAAsB,MAASX,GAAcX,IAAK,CAACA,CAAE,IAAI,EAAE;AAC7C,SAAOA,IAAKsB,EAAK,IAAItB,CAAE,IAAI;AAC7B;"}
1
+ {"version":3,"file":"editor-apps-DsGrGKfe.js","sources":["../src/chrome/HistoryView.tsx","../src/editor/editor-apps.ts"],"sourcesContent":["/**\n * `HistoryView` — the execution-history view body (T3.2.1, extracted from\n * `HistoryPage.tsx`'s T2.4.1 shape): stats + filters + paged list, OR the\n * selected execution's detail — never both. Opening a row swaps the list for\n * that execution (with a Back control to return to the list where it was\n * left); it does not stack the detail under a long list, where it lands\n * off-screen. Two hosts mount it — `HistoryPage` (the\n * project-wide and per-callable routes, filters URL-backed) and\n * `HistoryModal` (R-2's in-place modal, filters kept in local state) — so\n * this component owns every judgment call about HOW the view behaves, and\n * takes no position on WHERE its filters live: the host hands down\n * `filters` and gets every change back through `onFiltersChange`, exactly\n * the controlled-value shape `filtersToSearch`/`filtersFromSearch` already\n * assume on the URL-backed side.\n *\n * What stays here, same as it was in `HistoryPage` before the extraction:\n * - the search box's text, debounced, so a keystroke does not re-key and\n * re-issue both queries on every character (`onFiltersChange` — and so\n * the host's own write, URL or local state — fires only once typing\n * settles);\n * - which list row is selected, which is not shareable state and resets on\n * every mount;\n * - re-running an execution (a control on every row and in the detail): the\n * same input, against the callable's current definition. The view then\n * opens the NEW execution, so the outcome is what the author sees next;\n * - every filter change but paging snapping the page back to the first\n * (`offset` 0), because a narrowed result set has no meaningful \"page 3\".\n *\n * `onOpenInEditor`, when given, is called with the selected execution ONLY\n * while it is a workflow run (a function/endpoint invocation has no visual\n * editor to open) — the same gate `HistoryPage.tsx` applied inline before\n * this extraction. A host that never passes it (none of today's two do)\n * simply never sees the call.\n */\nimport {\n type ExecutionSummary,\n HISTORY_PAGE_SIZE,\n type HistoryFilters,\n type HistoryScope,\n runTriggerLabel,\n triggerFilterQuery,\n useExecutionDetailQuery,\n useFindExecution,\n useHistoryQuery,\n useHistoryStatsQuery,\n useRerunExecutionMutation,\n useWorkflowTriggers,\n} from \"@w6w/embed/repos\";\nimport {\n ExecutionDetail,\n type ExecutionFilterValue,\n ExecutionFilters,\n ExecutionList,\n ExecutionStats,\n} from \"@w6w/ui\";\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from \"react\";\n\n/** How long to wait after the last keystroke before `onFiltersChange` fires\n * with the new `q` (and so before either query re-issues with it). */\nconst SEARCH_DEBOUNCE_MS = 300;\n\n/** The nearest ancestor that actually scrolls (the modal body, the app's main\n * pane), or `null` when the document itself does. */\nfunction scrollParent(el: HTMLElement | null): HTMLElement | null {\n for (let p = el?.parentElement ?? null; p; p = p.parentElement) {\n const overflowY = getComputedStyle(p).overflowY;\n if ((overflowY === \"auto\" || overflowY === \"scroll\") && p.scrollHeight > p.clientHeight) {\n return p;\n }\n }\n return null;\n}\n\nexport interface HistoryViewProps {\n /** `null` ⇒ no scope known yet (the project-wide host, before its project\n * resolves) — both queries stay disabled, mirroring `repos/history.ts`'s\n * own `enabled: scope !== null`. */\n scope: HistoryScope | null;\n /** Project-wide chrome: the Kind filter, and the Callable column on every\n * row. A per-callable host (every callable already knows its own kind)\n * passes `false`. */\n showKind: boolean;\n filters: HistoryFilters;\n onFiltersChange: (next: HistoryFilters) => void;\n onOpenInEditor?: (execution: ExecutionSummary) => void;\n /** The scope is this one workflow: offer its triggers as a filter (\"which trigger started the\n * run\"), so one trigger's runs and stats can be reviewed on their own. */\n workflowId?: string;\n}\n\nexport function HistoryView(props: HistoryViewProps) {\n const { scope, showKind, filters, onFiltersChange, onOpenInEditor, workflowId } = props;\n\n // The debounce below fires outside any render, so it needs the LATEST\n // filters (a status picked while a `q` write was still pending must\n // survive it) rather than the ones captured when typing started.\n const filtersRef = useRef(filters);\n filtersRef.current = filters;\n\n const [q, setQ] = useState(filters.q);\n const searchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n const [selected, setSelected] = useState<ExecutionSummary | null>(null);\n\n // Keep the search box in step with `filters.q` when IT moves from outside\n // (Back/Forward or a shared link on the URL-backed host). This never\n // fights a keystroke: an outside `q` only changes once typing has\n // settled, by which point `q` already equals it.\n useEffect(() => {\n setQ(filters.q);\n }, [filters.q]);\n\n // Drop a pending debounce on unmount.\n useEffect(\n () => () => {\n if (searchTimer.current) clearTimeout(searchTimer.current);\n },\n [],\n );\n\n const listQuery = useHistoryQuery(scope, filters);\n const statsQuery = useHistoryStatsQuery(scope, filters);\n const detailQuery = useExecutionDetailQuery(selected);\n const rerun = useRerunExecutionMutation();\n const findExecution = useFindExecution();\n const [findError, setFindError] = useState<string | null>(null);\n\n // Swapping list ⇄ detail keeps the scroll offset of whatever scrolls around\n // this view, which would open a detail scrolled past its own top (the row\n // was clicked far down the list). So: remember the list's offset on the\n // way in, show the detail from its top, and put the list back on the way out.\n const viewRef = useRef<HTMLDivElement>(null);\n const listScroll = useRef<{ parent: HTMLElement | null; top: number } | null>(null);\n const selectedId = selected?.id ?? null;\n useLayoutEffect(() => {\n const el = viewRef.current;\n if (!el) return;\n if (selectedId !== null) {\n const parent = scrollParent(el);\n if (parent) parent.scrollTop = 0;\n else if (el.getBoundingClientRect().top < 0) el.scrollIntoView?.({ block: \"start\" });\n } else if (listScroll.current) {\n const { parent, top } = listScroll.current;\n listScroll.current = null;\n if (parent) parent.scrollTop = top;\n else window.scrollTo(0, top);\n }\n }, [selectedId]);\n\n const selectedRef = useRef(selected);\n selectedRef.current = selected;\n const open = useCallback((next: ExecutionSummary) => {\n // Leaving the LIST (not one detail for another, as a re-run from the detail does).\n if (selectedRef.current === null) {\n const parent = scrollParent(viewRef.current);\n listScroll.current = { parent, top: parent ? parent.scrollTop : window.scrollY };\n }\n setSelected(next);\n }, []);\n\n const rows = listQuery.data?.executions ?? [];\n // Every listed workflow's triggers, so each row names the trigger that started it — a run list\n // mixing three triggers is unreadable as `Event · <node id>` until each row is opened.\n const triggersByWorkflow = useWorkflowTriggers([\n ...(workflowId ? [workflowId] : []),\n ...rows.filter((r) => r.kind === \"workflow\").map((r) => r.callableId),\n ]);\n const executions = useMemo(\n () =>\n rows.map((r) =>\n r.kind === \"workflow\"\n ? { ...r, triggerLabel: runTriggerLabel(r, triggersByWorkflow.get(r.callableId) ?? []) }\n : r,\n ),\n [rows, triggersByWorkflow],\n );\n const ownTriggers = workflowId ? (triggersByWorkflow.get(workflowId) ?? []) : [];\n const triggerOptions = ownTriggers.map((t) => ({\n // A manual run records no entry node, so the Manual trigger filters by run kind instead.\n value: t.app === \"@w6w/trigger\" ? \"kind:manual\" : `entry:${t.nodeId}`,\n label: t.label,\n }));\n const offset = filters.offset;\n const hasMore = listQuery.data?.hasMore ?? false;\n\n /** Every filter change but paging reports a fresh filter set and resets\n * the page to the first. */\n const applyFilters = (next: ExecutionFilterValue) => {\n const trigger = next.trigger ?? \"\";\n onFiltersChange({\n ...next,\n trigger: Object.keys(triggerFilterQuery(trigger)).length > 0 ? trigger : \"\",\n offset: 0,\n });\n };\n\n const onChange = (next: ExecutionFilterValue) => {\n if (next.q === q) {\n applyFilters(next);\n return;\n }\n setQ(next.q);\n if (searchTimer.current) clearTimeout(searchTimer.current);\n searchTimer.current = setTimeout(() => {\n searchTimer.current = null;\n onFiltersChange({ ...filtersRef.current, q: next.q, offset: 0 });\n }, SEARCH_DEBOUNCE_MS);\n };\n\n const onPrev = () =>\n onFiltersChange({ ...filters, q, offset: Math.max(0, offset - HISTORY_PAGE_SIZE) });\n const onNext = () => onFiltersChange({ ...filters, q, offset: offset + HISTORY_PAGE_SIZE });\n\n const onSelect = useCallback(\n (executionId: string) => {\n const row = executions.find((r) => r.id === executionId);\n if (row) open(row);\n },\n [executions, open],\n );\n\n /** Re-run one execution, then open the new one — or, when it is not listed\n * yet, fall back to the (refreshed) list. */\n const startRerun = (summary: ExecutionSummary) => {\n rerun.mutate(summary, {\n onSuccess: (next) => {\n if (next) open(next);\n else setSelected(null);\n },\n });\n };\n const rerunningId = rerun.isPending ? (rerun.variables?.id ?? null) : null;\n\n /** \"Re-run of <id>\": open the original, from the callable this one belongs to. */\n const openOriginal = (callableId: string, id: string) => {\n setFindError(null);\n findExecution(callableId, id)\n .then((row) => {\n if (row) open(row);\n else setFindError(`${id} is no longer available.`);\n })\n .catch(() => setFindError(`Couldn't open ${id}.`));\n };\n const rerunError = rerun.isError ? (\n <p className=\"error\" data-testid=\"history-rerun-error\">\n Couldn't re-run: {rerun.error instanceof Error ? rerun.error.message : String(rerun.error)}\n </p>\n ) : null;\n\n const filterValue: ExecutionFilterValue = {\n status: filters.status,\n kind: filters.kind,\n from: filters.from,\n to: filters.to,\n q,\n trigger: filters.trigger,\n };\n\n // A workflow run is the only execution with a visual editor to jump into\n // — a function/endpoint invocation has no such surface.\n const openInEditor =\n selected?.kind === \"workflow\" && onOpenInEditor ? () => onOpenInEditor(selected) : undefined;\n\n if (selected) {\n return (\n <div ref={viewRef}>\n {rerunError}\n {findError && (\n <p className=\"error\" data-testid=\"history-find-error\">\n {findError}\n </p>\n )}\n <ExecutionDetail\n execution={detailQuery.data ?? null}\n loading={detailQuery.isLoading}\n errorMessage={detailQuery.isError ? \"This execution is no longer available.\" : undefined}\n onBack={() => {\n rerun.reset();\n setFindError(null);\n setSelected(null);\n }}\n onOpenExecution={(id) => openOriginal(selected.callableId, id)}\n onRerun={() => startRerun(selected)}\n rerunning={rerunningId !== null}\n onOpenInEditor={openInEditor}\n />\n </div>\n );\n }\n\n // `.w6w-card-stack` spaces stats → filters → list. A bare fragment left them touching: every host\n // wraps this view in one element (`RunHistory`'s embed root, `HistoryModal`'s body), so the\n // page's own flex gap never reached these siblings.\n return (\n <div className=\"w6w-card-stack\" data-testid=\"history-view\">\n <ExecutionStats stats={statsQuery.data ?? null} />\n\n <ExecutionFilters\n showKind={showKind}\n value={filterValue}\n onChange={onChange}\n triggerOptions={triggerOptions}\n />\n\n {listQuery.isError && (\n <p className=\"error\" data-testid=\"history-error\">\n Couldn't load execution history.\n </p>\n )}\n\n {rerunError}\n\n <div ref={viewRef}>\n <ExecutionList\n items={executions}\n showCallable={showKind}\n loading={listQuery.isLoading}\n hasPrev={offset > 0}\n hasNext={hasMore}\n onPrev={onPrev}\n onNext={onNext}\n onSelect={onSelect}\n onRerun={(id) => {\n const row = executions.find((r) => r.id === id);\n if (row) startRerun(row);\n }}\n rerunningId={rerunningId}\n />\n </div>\n </div>\n );\n}\n","/**\n * The canvas's app lookups, through the host-provided `W6WApi` (`useW6WApi()` — in an embed that\n * is `createW6WUiAdapter`'s, in Studio the facade, which delegates to the same store/repo).\n */\nimport { useQuery } from \"@tanstack/react-query\";\nimport { type AppSummary, useW6WApi } from \"@w6w/ui\";\nimport { useMemo } from \"react\";\n\n/** The per-app actions query key — the repos export itself (one declaration, no copy). */\nexport { appActionsKey } from \"../repos/apps.ts\";\n\nconst NO_APPS: ReadonlyMap<string, AppSummary> = new Map();\n\n/** A bounded set of app records by id. Empty when the host's API has no `listAppsByIds`. */\nexport function useEditorApps(ids: readonly string[]): { byId: ReadonlyMap<string, AppSummary> } {\n const api = useW6WApi();\n const list = api.listAppsByIds?.bind(api);\n const key = [...ids].sort().join(\",\");\n const q = useQuery({\n queryKey: [\"editor-apps\", key],\n queryFn: ({ signal }) => (list ? list(ids, { signal }) : Promise.resolve([] as AppSummary[])),\n enabled: ids.length > 0 && typeof list === \"function\",\n });\n const data = q.data;\n const byId = useMemo(\n () => (data ? new Map(data.map((a) => [a.id, a] as const)) : NO_APPS),\n [data],\n );\n return { byId };\n}\n\n/**\n * One app record by id, over {@link useEditorApps} (same `/apps` request, same cache entry as the\n * canvas's batch lookup). `undefined` while loading, for an empty id (which issues no request),\n * or when the host's API cannot look apps up by id.\n */\nexport function useEditorApp(id: string): AppSummary | undefined {\n const { byId } = useEditorApps(id ? [id] : []);\n return id ? byId.get(id) : undefined;\n}\n"],"names":["SEARCH_DEBOUNCE_MS","scrollParent","el","p","overflowY","HistoryView","props","scope","showKind","filters","onFiltersChange","onOpenInEditor","workflowId","filtersRef","useRef","q","setQ","useState","searchTimer","selected","setSelected","useEffect","listQuery","useHistoryQuery","statsQuery","useHistoryStatsQuery","detailQuery","useExecutionDetailQuery","rerun","useRerunExecutionMutation","findExecution","useFindExecution","findError","setFindError","viewRef","listScroll","selectedId","useLayoutEffect","parent","top","selectedRef","open","useCallback","next","rows","_a","triggersByWorkflow","useWorkflowTriggers","r","executions","useMemo","runTriggerLabel","triggerOptions","t","offset","hasMore","_b","applyFilters","trigger","triggerFilterQuery","onChange","onPrev","HISTORY_PAGE_SIZE","onNext","onSelect","executionId","row","startRerun","summary","rerunningId","_c","openOriginal","callableId","id","rerunError","jsxs","filterValue","openInEditor","jsx","ExecutionDetail","ExecutionStats","ExecutionFilters","ExecutionList","NO_APPS","useEditorApps","ids","api","useW6WApi","list","key","data","useQuery","signal","a","useEditorApp","byId"],"mappings":";;;;;;AA2DA,MAAMA,KAAqB;AAI3B,SAASC,EAAaC,GAA4C;AAChE,WAASC,KAAID,KAAA,gBAAAA,EAAI,kB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