@fractalsynapse/dsh-chapters 0.2.60 → 0.2.62
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.
- package/docs/project-state.md +8 -0
- package/lib/client.js +0 -184
- package/lib/client.js.map +1 -1
- package/lib/commands.js +8 -55
- package/lib/commands.js.map +1 -1
- package/lib/engine.js +8 -0
- package/lib/engine.js.map +1 -1
- package/lib/proxy-safe.d.ts +1 -0
- package/lib/proxy-safe.js +69 -0
- package/lib/proxy-safe.js.map +1 -0
- package/lib/version.d.ts +1 -1
- package/lib/version.js +1 -1
- package/package.json +1 -1
package/lib/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":["h","CSS","h","useReducer","useRef","useState","useCallback","useState","h","useState","useRef","useCallback","h"],"sources":["../src/client/tooltip.ts","../src/prompt-keys.ts","../src/client/prompt-bar.ts","../src/client/prompt-dock.ts","../src/preset-id.ts","../src/client/doors.ts","../src/client/command-reply.ts","../src/client/index.ts"],"sourcesContent":["/**\n * The host's Tooltip seat, resolved OPTIONALLY (#194-compat — measured on 0.2.1-rc.5, not guessed):\n *\n * `@deepseek-ai/dsh-client-ui-primitives` exists in the 0.2.0-rc.2 host tree and is ABSENT from the\n * entire 0.2.1-rc.5 install tree — no successor package exports `Tooltip`. Our bundle's static\n * import becomes a LAZY require in the built CJS: the bundle loads and components run, but the\n * first render that touches `Tooltip` throws, and React's error boundary swallows the subtree\n * silently. Measured symptoms on 0.2.1: door registration fully healthy (inject returned a\n * disposer; the factory ran; both register effects are functions) yet the assistant-actions region\n * renders ZERO entries, and the dock renders no row — because both wrap their buttons in Tooltip.\n *\n * The fix keeps one resolution point and one fallback (#59 — never per-component try/catch):\n * probe the module once; when it is absent, buttons carry the platform's own `title` tooltip, so\n * hover text survives on every host and the fancy tooltip survives where it exists.\n */\nimport { createElement as h, type ComponentType, type ReactElement } from 'react'\n\ndeclare const require: ((id: string) => Record<string, unknown>) | undefined\n\nexport type TooltipLike = ComponentType<{ label: string; side?: string; portal?: boolean; delayMs?: number; children: ReactElement<Record<string, unknown>> }>\n\n/**\n * The tooltip recipe, field for field the goal bar's own (GoalBar.tsx:101-142: `portal`,\n * `side=\"bottom\"`, `delayMs={500}`) — the shipped occupant of the same dock strip, whose tooltips\n * are NOT covered by the composer. `portal` is the load-bearing one: it renders the popup at\n * document level instead of inside our dock's stacking context, which is exactly the maintainer's\n * report (#210: \"the hoverover tooltips are covered by the main chat input container\"). Our old\n * compile-time types rejected portal/delayMs at the overload; the runtime host always accepted\n * them, and since the seat is typed by us, the recipe is pinned by a row instead of by luck.\n */\nexport function tooltipPropsFor(label: string): { label: string; side: 'bottom'; portal: true; delayMs: 500 } {\n return { label, side: 'bottom', portal: true, delayMs: 500 }\n}\n\nlet resolved: TooltipLike | null | undefined // undefined = not probed yet\n\nexport function resolveTooltip(): TooltipLike | null {\n if (resolved !== undefined) return resolved\n resolved = null\n try {\n if (typeof require === 'function') {\n const mod = require('@deepseek-ai/dsh-client-ui-primitives') as { Tooltip?: unknown } | undefined\n const T = mod?.Tooltip\n if (typeof T === 'function' || typeof T === 'object') resolved = T as TooltipLike\n }\n } catch {\n resolved = null // absent host: the native-title fallback stands\n }\n return resolved\n}\n\n/** Wrap in the host Tooltip when it exists; otherwise return the child (which must carry `title`). */\nexport function withTooltip(label: string, child: ReactElement<Record<string, unknown>>): ReactElement {\n const T = resolveTooltip()\n return T !== null ? h(T, { ...tooltipPropsFor(label), children: child }) : child\n}\n\n/** The native-tooltip attribute, present ONLY when the host seat is absent — no double tooltips. */\nexport function nativeTitle(label: string): { title: string } | Record<string, never> {\n return resolveTooltip() === null ? { title: label } : {}\n}\n","/**\n * Identifiers shared by BOTH planes of the push transport (#194). One module, one spelling: the\n * server registers the projection under this key and the client reads `useProjection(key)` — two\n * literals in two planes would be exactly the drift #59 forbids. No node imports (the client\n * compiles this), no DOM (the server imports this).\n */\nexport const PROMPT_PROJECTION_KEY = 'chaptersPrompt'\n","/**\n * The Suggested Next Step bar — every decision the row makes, kept out of React (#113).\n *\n * Deliberately shaped like the goal bar, because that implementation is tested, already fits, and gets the\n * split right: the **durable** facts (`status`, `text`, `turnSeq` — the server's one-generation-per-turn\n * identity) versus the **process-local** intent (`autorun`, `expanded` — the goal's `activation` in\n * everything but name). Nothing transient is persisted, and nothing persisted is guessed here.\n *\n * The failures the maintainer rejected are all decision bugs, not rendering bugs: firing while a turn is\n * running, shouting a refusal that should have been silence, an autorun that outlives the purpose that\n * justified it. Each has a row in `tests/unit/prompt-bar.test.ts`.\n */\n\nexport type PromptBarStatus = 'off' | 'idle' | 'analyzing' | 'ready' | 'failed'\nexport type PromptBarAutorun = 'armed' | 'disarmed'\n/** Mirrors the host's `GoalPhase` vocabulary (`dsh-goal` types) so goal composition needs no translation. */\nexport type GoalPhaseView = 'none' | 'active' | 'paused' | 'blocked' | 'complete'\n\nexport interface PromptBarState {\n status: PromptBarStatus\n /** The offer, verbatim. Never truncated — an over-cap answer is refused upstream. */\n text: string | null\n /** #113: what kind of step the server classified this as. `goal-edit` is held for the human's keystroke,\n * because goal edits require a direct human turn in the host and an autorun message is not one. */\n intent: 'worker-step' | 'goal-edit'\n /** The `turn/end` seq this offer belongs to; its identity, not a timestamp. */\n turnSeq: number | null\n /** Set only with `status: 'failed'`; rendered as `role=\"alert\"` (#61: delivered, not swallowed). */\n error: string | null\n /** Why an action did not happen, on the bar's face (#113). Empty when there is nothing to explain. */\n note: string\n autorun: PromptBarAutorun\n expanded: boolean\n running: boolean\n goalPhase: GoalPhaseView\n /** The offer a human dismissed or interrupted. A NEW `turnSeq` clears it; this one stays hidden. */\n hiddenTurnSeq: number | null\n /** Live goal facts, when the caller can read them (the goal driver owns the next turn when active+armed). */\n goal: { phase: string; activation: string; revision: number } | null\n}\n\nexport type PromptBarEvent =\n | { t: 'polled', status: PromptBarStatus, text?: string | null, turnSeq?: number | null, error?: string | null, intent?: 'worker-step' | 'goal-edit' }\n | { t: 'expand' } | { t: 'collapse' }\n /** Why an action did not happen, on the bar's own face (#113). Cleared when a new offer lands. */\n | { t: 'note'; note: string }\n | { t: 'autorun', on: boolean }\n | { t: 'human/prompt' }\n | { t: 'off' }\n | { t: 'goal', phase: GoalPhaseView }\n | { t: 'running', running: boolean }\n\nexport function initialBarState(autorun: PromptBarAutorun = 'disarmed'): PromptBarState {\n return { status: 'off', text: null, turnSeq: null, error: null, note: '', intent: 'worker-step', goalPhase: 'none', goal: null, autorun, expanded: false, running: false, hiddenTurnSeq: null }\n}\n\nexport function promptBarReducer(state: PromptBarState, ev: PromptBarEvent): PromptBarState {\n if (ev.t === 'note') return { ...state, note: ev.note }\n const next = baseBarReducer(state, ev)\n // A note is about the gesture that just failed, so a NEW offer retires it. A poll that repeats the same\n // offer (the bar re-reads every few seconds) does not — otherwise the explanation would blink out before\n // the human could read it.\n return ev.t === 'polled' && (next.turnSeq !== state.turnSeq || next.text !== state.text) ? { ...next, note: '' } : next\n}\n\nfunction baseBarReducer(state: PromptBarState, ev: PromptBarEvent): PromptBarState {\n switch (ev.t) {\n case 'polled': {\n // #285: the wire is the supreme authority on `running`. A local run-click folds `running: true`\n // honestly (the click authored the turn), but on hosts with no running edge (#221) nothing else\n // would ever retire that line — so any polled answer, whatever it carries, ends the local claim.\n // Wire-first, then the local fold: the order the #208/#221 lineage has always kept.\n if (ev.status === 'off') return { ...state, status: 'off', text: null, turnSeq: null, error: null, expanded: false, autorun: 'disarmed', running: false }\n // A fresh generation invalidates the previous offer: acting on a stale one is how a bar lies.\n if (ev.status === 'analyzing') return { ...state, status: 'analyzing', text: null, error: null, running: false }\n return {\n ...state,\n running: false,\n status: ev.status,\n text: ev.status === 'ready' ? (ev.text ?? null) : null,\n intent: ev.status === 'ready' ? (ev.intent ?? 'worker-step') : 'worker-step',\n turnSeq: ev.turnSeq ?? state.turnSeq,\n error: ev.status === 'failed' ? (ev.error ?? 'the suggestion call failed') : null,\n }\n }\n case 'expand': return { ...state, expanded: true }\n // Collapsing is a reading action. It keeps the offer — only a human prompt or `Off` dismisses it.\n case 'collapse': return { ...state, expanded: false }\n case 'autorun': return { ...state, autorun: ev.on ? 'armed' : 'disarmed' }\n // #282: a turn start makes every on-screen offer obsolete — Run could fire a stale step and the\n // human would watch the agent act on last cycle's question. The rising edge clears the offer,\n // collapses, and hands the row to the generic running line (barLabel/barVisible); the falling\n // edge shows nothing new — the post-turn pull lands the fresh state through the normal path.\n // Idempotent on repeats: same flag in, SAME object out — a re-delivered edge must not become\n // render-loop fuel. Unknown running folds as FALSE at the source (#221: unknown is not running).\n case 'running': {\n if (ev.running === state.running) return state\n return ev.running\n ? { ...state, running: true, text: null, error: null, expanded: false }\n : { ...state, running: false }\n }\n case 'human/prompt':\n // The human took the wheel: yield the loop, and drop the offer that was on screen. Generation itself\n // continues on the NEXT turn boundary — suspension is not disable.\n return { ...state, autorun: 'disarmed', hiddenTurnSeq: state.turnSeq, expanded: false }\n case 'off': return { ...state, status: 'off', text: null, turnSeq: null, error: null, expanded: false, autorun: 'disarmed' }\n case 'goal':\n // Per spec: autorun runs ALONGSIDE an active goal and disarms itself when the goal completes — the\n // suggestion loop exists to serve the session's purpose, and stops when that purpose stops.\n // #188: blocked joins complete — both planes stop together when the goal reaches a terminal\n // phase; a loop still firing offers at a blocked goal is the autorun that outlived its purpose.\n return { ...state, goalPhase: ev.phase, autorun: ev.phase === 'complete' || ev.phase === 'blocked' ? 'disarmed' : state.autorun }\n }\n // Exhaustive fallback: a new event without a case must return the state unchanged rather than\n // compile into `undefined` and blank the bar.\n return state\n}\n\n/** The status label. `failed` keeps the ready label so the error span is the delta, not a mystery row.\n * A goal-edit offer REPLACES the label text (#300): the row is one message tall, and the second-message\n * badge overflowed it and clipped the composer — so the protocol fact earns the slot or goes unsaid. */\nexport function barLabel(s: PromptBarState): string | null {\n // #282: running outranks everything shown — while the agent works, the bar says so and nothing\n // else. The wording is the §28 states-table row, kept identical (one predicate per decision, #59).\n if (s.running) return 'Agent is running — a fresh suggestion lands when the turn ends'\n if (s.status === 'analyzing') return 'Analyzing situation…'\n if (s.intent === 'goal-edit' && (s.status === 'ready' || s.status === 'failed')) return 'Goal edit — run it yourself'\n if (s.status === 'ready' || s.status === 'failed') return 'Recommended Next Step'\n return null\n}\n\n/**\n * #309: the row button's one sentence, as a pure function of what the click would DO —\n * collapsed invites the reading; expanded-into-an-empty-composer invites the handoff;\n * expanded-with-the-user-typing names the precondition instead of lying about the gesture.\n * One predicate per decision (#59): aria-label and the tooltip render this same string.\n */\nexport function rowTooltip(expanded: boolean, composerHasText: boolean): string {\n if (!expanded) return 'Click to expand the full suggested prompt'\n return composerHasText ? 'Clear existing prompt to send this prompt to chat input'\n : 'Click to send this prompt to the chat input for editing'\n}\n\n/**\n * #193: the pull cadence, as a decision instead of an interval constant. Every pull is two recorded\n * host lifecycle events (`command/run` + `command/done`) the UI renders as history nodes — cadence\n * IS the litter, so it belongs in this module with a row for every arm. Active = the state can\n * plausibly change on a short clock (generation in flight, an armed loop to fire, a turn running\n * that will end into an offer). Quiet = stable; one pull a minute is plenty for a state that only\n * changes at turn boundaries. Hidden-and-quiet = pull NOTHING (a background tab should write zero\n * history); hidden-and-active still pulls, because walking away from a running loop is the point of\n * autorun and pausing it silently would be the loop dying with nobody told.\n */\nexport const ACTIVE_POLL_MS = 10_000\n/**\n * #229: the quiet heartbeat is CONFIG-GATED (`promptQuietHeartbeatSec`) and defaults to ZERO.\n * Measured on the maintainer's live log after 0.2.11 installed correctly (gaps exactly 60.0s): every\n * pull is two durable nodes — a host `command/run` + `command/done` pair — and the user's rule is\n * absolute: never repeated chapters-prompt executions. The sanctioned moments (mount discovery once\n * per page load, the turn-end pulse, visibility return with an untrusted cache, forced confirms)\n * remain; the ambient drumbeat does not exist unless configured. This module is client-safe (no node\n * builtins), so the wiring injects the config value at boot via `configureQuietHeartbeat`.\n */\nexport let QUIET_POLL_MS = 0\nexport function configureQuietHeartbeat(seconds: number | undefined): void {\n QUIET_POLL_MS = typeof seconds === 'number' && Number.isFinite(seconds) && seconds > 0 ? Math.trunc(seconds * 1000) : 0\n}\n\n/**\n * #304: the analyzing belt backs off 10s → 20s → 40s → 60s (cap) while a generation is in\n * flight and nobody is armed. The first wait stays eager (short generations — every rig leg —\n * land in the old 10s rhythm); long and zombie generations stop paying 2 history nodes per\n * poll. The ARMED loop ignores the belt entirely: a stalled round is worse than any cadence.\n * streak counts consecutive analyzing OBSERVATIONS (undefined/0 = eager).\n */\nfunction analyzingBeltMs(streak: number | undefined): number {\n const n = streak === undefined || streak < 1 ? 0 : Math.min(streak, 3)\n return n === 0 ? ACTIVE_POLL_MS : n === 1 ? 20_000 : n === 2 ? 40_000 : 60_000\n}\n\n/** #429: attempts the mount may make before it gives up LOUDLY. Sized to the measured window:\n * loaded boots hydrate the composer's exec verb AFTER the dock's first effect (the two chain-context\n * failures vs 12 solo passes at the same head); 8x2s outlasts that without approaching any ceiling\n * that matters, and each attempt is COST-FREE until exec exists (refresh() still early-returns with\n * zero wire nodes) — the paid pulls begin only when the wire can answer. */\nexport const FIRST_PULL_RETRY_CEILING = 8\nexport const FIRST_PULL_RETRY_SPACING_MS = 2_000\n\n/**\n * THE ONE first-pull retry predicate (#429). The dock's mount pull no-ops silently while the host\n * has not yet handed `exec` — before #429 the retry lived only in two comments (the ceiling promise\n * above execWithTimeout, and 'retry until SOMETHING answers' in the mount effect) with no code\n * behind it, which is how the revival leg's mount pull could starve under boot load while solo\n * boots passed 10/10. The loop is due ONLY while no reply has arrived — any parseable answer, an\n * honest `off` included (#304's seam claim is THAT the wire answered, never that the feature is\n * on), the feature plane is present, and the ceiling has room.\n */\nexport function firstPullRetryDue(c: { answered: boolean, featureAbsent: boolean, attempts: number, owed: boolean, pushLive: boolean }): boolean {\n if (c.answered || c.featureAbsent) return false\n // #497 (third writer, finally named): the maintainer's reload pair at 2026-11-24T11:27:06Z was\n // NOT the mount tick — it was this retry. The mount tick correctly stayed silent (push mode),\n // but `answered` flips only on a WIRE reply, so the loop pulled `state` every 2s until exec\n // hydrated: a self-inflicted load-time pair on the exact hosts the #194 gate exists to protect.\n // Two truths the predicate now requires: the mount actually SANCTIONED a pull (owed) — silence\n // by design owes nothing — and the projection is NOT live (pushLive): a cell that answers is an\n // answer; retrying against it is the drumbeat the maintainer's rule forbids.\n if (c.pushLive || !c.owed) return false\n return c.attempts < FIRST_PULL_RETRY_CEILING\n}\n\nexport function pollSpacingFor(s: { status: PromptBarStatus; autorun: PromptBarAutorun; running: boolean; hidden: boolean; edges: boolean; turnEndPulse?: boolean; analyzingStreak?: number | undefined }): number | null {\n // #203: where the host publishes the running signal, the idle EDGE is the schedule — a turn ending\n // pulls, the bar's own actions pull, and a stable disarmed bar keeps NO clock at all, because a\n // timer there could only re-read truth into rendered history nodes. Analyzing stays on the fast\n // belt (a generation completing fires no edge), and an armed loop keeps it too (a missed edge must\n // not stall autorun). Hosts that publish no running prop get the #193 cadence, unchanged.\n // #221: a turn-end pulse from the host projection deserves an immediate follow-up — the offer\n // was just born. Applies in BOTH modes; it is the sanctioned moment, not a clock.\n if (s.turnEndPulse === true) return ACTIVE_POLL_MS\n if (s.edges) {\n if (s.autorun === 'armed') return ACTIVE_POLL_MS\n if (s.status === 'analyzing') return analyzingBeltMs(s.analyzingStreak)\n return null\n }\n // #221: unknown-running is UNKNOWN, not running. The maintainer's live host (0.2.0-rc.2) publishes\n // no usable running signal to docks; `running` defaulted to true and pinned this bar into the FAST\n // clock forever — measured 158 state pulls at exact 10.0s intervals across one session's log, even\n // while idle. Only two states justify a fast clock: generation in flight (analyzing) and an armed\n // loop that must see offers promptly. A KNOWN running turn (edges=false hosts that do supply the\n // signal... which by definition have edges=true) never needed the clock either way. So: analyzing\n // or armed ⇒ fast; otherwise quiet, hidden-quiet ⇒ silent.\n const active = s.status === 'analyzing' || s.autorun === 'armed'\n if (!active && s.hidden) return null\n if (!active) return QUIET_POLL_MS > 0 ? QUIET_POLL_MS : null\n // #304: armed keeps the 10s; analyzing alone rides the back-off (the 158-pull lesson was\n // about FOREVER; a real 90s generation deserves 3 polls, not 9).\n if (s.autorun === 'armed') return ACTIVE_POLL_MS\n return analyzingBeltMs(s.analyzingStreak)\n}\n\n/**\n * #203: whether a freshly mounted bar pulls, or renders its cache and stays silent. The maintainer's\n * rule: generate or read AFTER THE TURN ENDS, never when you activate a session. So a mount pulls\n * only when the cache cannot be trusted — absent (first mount after a page load), stale (a turn\n * could have ended since; this guarded pull is what keeps Run honest, because clicking a stale\n * offer would submit the row's newer text while showing the old), mid-generation, or armed. A\n * cached `off` never pulls WITHIN THE PAGE THAT SAW IT: off is a human/config switch, and only an\n * explicit `on` revisits it. #272 makes the page the discriminator the mirror erased — an off\n * RESTORED from localStorage after a reload was never observed by this page, and the reload pull\n * is the revival promise the enabling commands make, so disk-restored off pays it.\n */\nexport function mountPullDecision(c: { hasCache: boolean; ageMs: number; status: PromptBarStatus; autorun: PromptBarAutorun; cacheFromDisk?: boolean | undefined }): boolean {\n if (!c.hasCache) return true\n // #208, the maintainer's rule — NOT RELEVANT, NOT VISIBLE: `off` is terminal for the page\n // lifetime. The #203 staleness-revival arm cost one visible history node per reactivation of a\n // known-off session, for a feature that is not on; revival is a page reload, and the commands\n // that re-enable (`model`, `on`) say so in their replies. #251 then persisted the cache to disk,\n // which silently un-wrote that sentence — every reload restored the veto. The `cacheFromDisk`\n // input restores it exactly: an off THIS page observed stays terminal; an off carried across a\n // reload pulls once, and the server's answer (off stays hidden; idle/ready renders) decides.\n if (c.status === 'off') return c.cacheFromDisk === true\n if (c.autorun === 'armed' || c.status === 'analyzing') return true\n // #229: with no heartbeat configured, staleness alone never pulls — a tab left open for ten\n // minutes must not resurrect the drumbeat through the mount path. Freshness returns via the\n // turn-end pulse, visibility edges, and the confirm arms, all of which are real events.\n return QUIET_POLL_MS > 0 && c.ageMs > QUIET_POLL_MS\n}\n\n/**\n * #203: fold a cached wire event back into row state through the SAME reducer the live path uses —\n * one fold, no second implementation to drift (the #59 rule).\n */\nexport function stateFromCache(ev: PromptBarEvent, autorun: PromptBarAutorun | null): PromptBarState {\n const folded = promptBarReducer(initialBarState(), ev)\n return autorun === null ? folded : promptBarReducer(folded, { t: 'autorun', on: autorun === 'armed' })\n}\n\nexport function barVisible(s: PromptBarState): boolean {\n // Only `off` hides the row. `idle` is enabled-and-waiting, and showing it is the difference between\n // \"the feature is live, nothing to say yet\" and silence that reads as disabled (#113).\n if (s.status === 'off') return false\n // #282: the running line shows even with cleared text — the ready-empty rule below would otherwise\n // hide the bar exactly when it has the most important thing to say. `off` stays the first gate (#208).\n if (s.running) return true\n if (s.status === 'ready' && (s.text === null || s.text === '')) return false\n // The goal bar's `clearedGoalId` guard, in our terms: don't flicker back the offer just dismissed.\n if (s.hiddenTurnSeq !== null && s.hiddenTurnSeq === s.turnSeq) return false\n return true\n}\n\n/** May the bar submit its own offer? Armed, present, idle, not dismissed, and still serving a purpose. */\nexport function shouldAutoFire(s: PromptBarState): boolean {\n if (s.status !== 'ready') return false\n if (s.text === null || s.text === '') return false\n // #113: two host-imposed stops before anything else. A goal re-cut needs a human turn (dsh-tool-goal's\n // requireDirectHuman), and an armed goal driver already intends to start this turn — firing here would be\n // two turn-starters at one boundary, racing the driver's own reservation fence.\n if (s.intent === 'goal-edit') return false\n if (s.goal !== null && s.goal.phase === 'active' && s.goal.activation === 'armed') return false\n if (s.autorun !== 'armed') return false\n if (s.running) return false\n if (s.goalPhase === 'complete' || s.goalPhase === 'blocked') return false\n if (s.hiddenTurnSeq !== null && s.hiddenTurnSeq === s.turnSeq) return false\n return true\n}\n\n/** The command the bar pulls. One string, so the client and the command plane cannot drift silently. */\nexport const BAR_STATE_COMMAND = '/chapters-prompt state'\n/** The bar's Run button: the server submits the on-screen offer as the human's own turn. */\nexport const BAR_RUN_COMMAND = '/chapters-prompt run'\n\n/**\n * Parse the `state` verb's `k: v` lines into a pull event.\n *\n * One output serving the human and the component is the design (see `docs/contract.md`); this function is\n * the cost of that choice, and it is kept honest: an unrecognised line is IGNORED, not guessed at, and a\n * payload that yields no `status` is `null` so the caller keeps its last state rather than inventing `off`\n * (which would hide a bar that is merely mid-reply). Indentation and the prompt's own lines are the reason\n * the prompt is collected separately from the scalar fields — it is the only multi-line value.\n */\nexport function parseBarState(text: string): PromptBarEvent | null {\n const lines = text.split('\\n')\n const head = lines[0] ?? ''\n const statusWord = head.startsWith('suggested next step:') ? head.slice('suggested next step:'.length).trim() : ''\n const status = statusWord === 'off' ? 'off'\n : statusWord === 'idle' ? 'idle'\n : statusWord === 'analyzing' ? 'analyzing'\n : statusWord === 'ready' ? 'ready'\n : statusWord === 'failed' ? 'failed'\n : null\n if (status === null) return null\n const scalars: Record<string, string> = {}\n const prompt: string[] = []\n let inPrompt = false\n for (const line of lines.slice(1)) {\n if (inPrompt) { prompt.push(line.replace(/^ {4}/, '')); continue }\n const m = /^ {2}([a-z]+): ?(.*)$/.exec(line)\n if (m === null) continue\n const key = m[1]!, value = m[2]!.trim()\n if (key === 'prompt') { inPrompt = true; continue }\n scalars[key] !== undefined ? (scalars[key] += ` ${value}`) : (scalars[key] = value)\n }\n // #229: the server's configured ambient heartbeat rides every state reply; learn it here so the\n // module-level gate matches the operator's setting before any schedule decision reads it.\n configureQuietHeartbeat(Number.parseInt((scalars['heartbeat'] ?? '').trim(), 10) || 0)\n const turnRaw = scalars['turn'] ?? ''\n const turnSeq = /^\\d+$/.test(turnRaw) ? Number(turnRaw) : null\n const errorRaw = scalars['error'] ?? ''\n const intentWord = (scalars['intent'] ?? '').split(' ')[0] ?? ''\n return {\n t: 'polled',\n intent: intentWord === 'goal-edit' ? 'goal-edit' : 'worker-step',\n status,\n ...(status === 'ready' ? { text: prompt.join('\\n'), turnSeq } : {}),\n ...(status === 'failed' ? { error: errorRaw, turnSeq } : {}),\n }\n}\n\n/** The autorun flag, read from the same payload — the row is durable, the flag is not. */\nexport function parseBarAutorun(text: string): 'armed' | 'disarmed' | null {\n const m = /^ {2}autorun: (armed|disarmed)\\b/m.exec(text)\n return m === null ? null : (m[1] as 'armed' | 'disarmed')\n}\n\n/**\n * Does the host say this session is busy right now?\n *\n * The dock's props are HOOKS (`useSessionStatus`, `useChat`, `useInput`, …) — documented in\n * docs/contract.md § \"What a dock component is handed\" — so a component that waits for a scalar\n * `props.running` waits forever, which is precisely why Autorun declared itself unavailable while the host\n * was publishing the signal one field away. Shapes differ across hosts and versions, so every form is folded\n * here, in one pure function, with `undefined` (unknown) kept distinct from `false` (idle): the loop refuses\n * to start a turn on an unknown, and that distinction is the whole safety property.\n */\nexport function deriveRunning(status: unknown): boolean | undefined {\n if (status === undefined || status === null) return undefined\n if (typeof status === 'boolean') return status\n if (typeof status === 'string') {\n if (/^(running|streaming|busy|active)$/i.test(status)) return true\n if (/^(idle|done|stopped|finished|ready|waiting)$/i.test(status)) return false\n return undefined\n }\n if (typeof status === 'object') {\n const s = status as { status?: unknown, state?: unknown, running?: unknown, phase?: unknown }\n if (s.running !== undefined) return typeof s.running === 'boolean' ? s.running : undefined\n return deriveRunning(s.status ?? s.state ?? s.phase)\n }\n return undefined\n}\n\n\n/**\n * #208: the plane-wide relevance fact, read from the `state` block's own model line. `model: unset`\n * means the feature does not exist on this plane — one discovery reply carrying it silences EVERY\n * dock on the page (the pull transport cannot do better than one discovery; the push transport\n * (#194) removes even that). An unrecognised block is false, never a guess.\n */\nexport function parseModelAbsent(text: string): boolean {\n return /^\\s*model:\\s*unset\\b/m.test(text)\n}\n\n// ---------------------------------------------------------------- #194: the push half\n\n/** The pushed payload, as the client reads it from the standard `useProjection` seat. */\nexport interface PromptPushView {\n v: number\n status: PromptBarStatus\n text: string\n turnSeq: number | null\n error: string\n intent: 'worker-step' | 'goal-edit'\n autorun: 'armed' | 'disarmed'\n}\n\n/**\n * A pushed payload becomes the SAME events the pull path dispatches — one fold, one reducer, no\n * second implementation to drift (#59). Null when the payload is not ours or not trustworthy: an\n * unrecognised push is ignored, never guessed at, and the pull schedule underneath keeps running\n * until a payload this function accepts actually arrives.\n */\nexport function pushEventsOf(payload: unknown): { polled: PromptBarEvent; autorun: PromptBarEvent } | null {\n if (payload === null || payload === undefined || typeof payload !== 'object') return null\n const p = payload as Partial<PromptPushView>\n if (p.v !== 1 || typeof p.status !== 'string') return null\n // text is a ready-state fact, not a payload gate: an analyzing push without text is honest\n // progress, and rejecting it would blind the bar to the very transition it exists to show.\n const status = p.status as PromptBarStatus\n if (status !== 'off' && status !== 'idle' && status !== 'analyzing' && status !== 'ready' && status !== 'failed') return null\n return {\n polled: {\n t: 'polled', status,\n ...(status === 'ready' ? { text: typeof p.text === 'string' ? p.text : '', turnSeq: p.turnSeq ?? null, intent: p.intent ?? 'worker-step' } : {}),\n ...(status === 'failed' ? { error: p.error ?? 'the suggestion call failed' } : {}),\n },\n autorun: { t: 'autorun', on: p.autorun === 'armed' },\n }\n}\n\n/**\n * The running signal's resolution order (scalar prop → `useSession` snapshot via `deriveRunning` →\n * unknown) lives in the dock as `props.running ?? deriveRunning(sessionSnapshot)` — ONE expression,\n * pinned by a source-scan row, folded by the deriveRunning rows that already cover every shape.\n * A second pure helper for the same decision would be exactly the drift #59 forbids; the draft of\n * #194 shipped one and this comment is its headstone.\n */\n\n/** The staleness-confirm's one question: did a push arrive after the edge that scheduled it? */\nexport function pushIsFresher(lastPushAt: number | null, edgeAt: number): boolean {\n return lastPushAt !== null && lastPushAt > edgeAt\n}\n\n\n/** The projection key, from the ONE module both planes share (#194 — never retyped per plane). */\nexport { PROMPT_PROJECTION_KEY } from '../prompt-keys.ts'\n\n/**\n * #218: a DEAD-PUSH HEARTBEAT, not a staleness confirm — 20s fired mid-turn before the turn's\n * record could exist (turns outlast 20s), which was confirm spam wearing a safety hat. 5 minutes:\n * during normal work a record arrives every turn and the push effect retires the pending timer, so\n * a healthy push NEVER fires it; only a push silent for a whole 5 minutes pulls once — a frozen\n * bar is the failure this bounds, and it is worth one node every 5 minutes, not one every 20\n * seconds.\n * within moments (the runner writes it BEFORE calling the model). If no push arrived this long\n * after the edge, the push is presumed dead and ONE confirm pull runs — a silently dead push\n * degrades to one pull per turn, never to a frozen bar.\n */\nexport const PUSH_CONFIRM_GRACE_MS = 300_000\n\n/**\n * #211 — the edge kick's delay, measured on the maintainer's host the hard way: some hosts publish\n * `running` at STEP granularity (it flickers at every tool call and thinking block), and an\n * immediate kick per falling edge was a rendered `chapters-prompt` node per tool call — all waste,\n * because the server row changes ONLY at turn boundaries. So: a falling edge schedules its pull\n * after the debounce, a rising edge cancels it (step flicker coalesces to zero pulls), and the rate\n * floor bounds even a host that holds `running` low through long tool calls. A real turn end — a\n * falling edge with no rising edge after it — pulls exactly once.\n */\nexport const EDGE_DEBOUNCE_MS = 2_000\nexport const EDGE_FLOOR_MS = 15_000\n\nexport function edgeKickDelayMs(msSinceLastPull: number): number {\n return Math.max(EDGE_DEBOUNCE_MS, EDGE_FLOOR_MS - msSinceLastPull)\n}\n\n\n/**\n * #221: the turn-end pulse, derived from the host's own turn-boundary projection — no plugin\n * record API needed, so it works on 0.2.0 hosts (where appendPluginRecord is absent) exactly as\n * on newer ones. The host maintains a `turnBoundary` projection (the agent loop reads its\n * lastTurn for its own bookkeeping); reading what the host already folds costs zero writes and\n * delivers reactively through the same standard useProjection seat as any other projection.\n * Returns true when a NEW turn ended since the last observation; the dock calls it once per\n * render and stores the returned stamp back into `seen`.\n */\nexport function turnEndPulse(lastTurn: number | null | undefined, seen: number): { pulse: boolean, seen: number } {\n const cur = typeof lastTurn === 'number' && Number.isFinite(lastTurn) ? lastTurn : 0\n if (cur > seen) return { pulse: true, seen: cur }\n return { pulse: false, seen }\n}\n","/**\n * The Suggested Next Step dock row (#113) — thin by design.\n *\n * Every decision lives in `prompt-bar.ts` where a row can pin it; this file only moves pixels and bytes\n * between the host slot and that reducer. That split is the reason it exists: the ghost was rejected for\n * behaviour that had no home, and \"one turn, one offer\" cannot be tested in a component.\n *\n * Placement is measured, not styled: `conversation.input.dock` is the host's full-width stack rendered\n * ABOVE the composer card (todo `order: 0`, goal `10`, queue `20`), so `order: 30` puts this row under every\n * other dock entry and directly above the input — and because it is a docked row rather than an overlay, it\n * can neither cover the placeholder nor collide with the send buttons. The ghost's ugliest defect was\n * structural, and the structure fixes it.\n *\n * The bar is PUSH-SHAPED, PULL-FED. A registrant can own a reactive observable (`hooks: { x }` → prop\n * `useX`) — that is how the goal bar gets its `activation` — but a plugin cannot publish a projection, and\n * the only plugin-reachable call path is `remote.commands.execute`. So the component pulls the `state` verb\n * on edges it can actually observe. Stated here because the alternative is a reader assuming a subscription\n * that does not exist.\n *\n * @module dsh-chapters/src/client/prompt-dock\n */\n\nimport { createElement as h, useCallback, useEffect, useReducer, useRef, useState, type ReactElement } from 'react'\nimport { withTooltip, nativeTitle } from './tooltip.ts'\nimport {\n BAR_RUN_COMMAND,\n deriveRunning,\n BAR_STATE_COMMAND,\n pollSpacingFor, mountPullDecision, rowTooltip, stateFromCache, parseModelAbsent, edgeKickDelayMs,\n firstPullRetryDue, FIRST_PULL_RETRY_SPACING_MS, FIRST_PULL_RETRY_CEILING,\n pushEventsOf, pushIsFresher, PROMPT_PROJECTION_KEY, PUSH_CONFIRM_GRACE_MS, turnEndPulse, ACTIVE_POLL_MS, type PromptBarStatus,\n barLabel,\n barVisible,\n initialBarState,\n parseBarAutorun,\n parseBarState,\n promptBarReducer,\n shouldAutoFire,\n type PromptBarEvent,\n type PromptBarState,\n} from './prompt-bar.ts'\n\n/** The dock's owner + standard-kit props we read. Everything is optional-typed on purpose: this is a host\n * shape crossing a plugin boundary, and an absent field must degrade visibly, not throw at boot (#58). */\nexport interface DockProps {\n sessionId?: string\n // #243: the REAL contract shape (ui-conversation contract/input.ts): `insertText` takes the span\n // captured by `captureInsertion()` and returns whether it applied. Our old one-parameter guess is\n // what produced the `draftRev` throw we mis-blamed on the host.\n inputActions?: { captureInsertion?: () => unknown; insertText?: (text: string, span: unknown) => boolean; setDraft?: (text: string) => void; submit?: () => void }\n /** The host's session-status hook, when this build hands docks one (`useSessionStatus` is in the dock's\n * documented prop list). Folded through `deriveRunning` because its shape is not ours to assume. */\n useSessionStatus?: (selector?: unknown) => unknown\n /** The session snapshot hook; its snapshot carries `running`, which is Autorun's idle edge. */\n useSession?: (selector?: unknown) => unknown\n /** #194: the standard projection seat (SessionStandardProps, measured in ui-session). Where the\n * server registered the push projection, this returns its value reactively — zero commands.\n * Absent hook or undefined value ⇒ the pull schedule stands, unchanged. */\n useProjection?: (key: string) => unknown\n /** The host publishes running/idle through the composer kit on some builds; if it is absent, autorun\n * refuses to fire rather than guessing that the session is idle. Fail-safe, not fail-open. */\n running?: boolean\n /** Run a host command line for THIS session and return its text. One verb for every call the bar makes\n * (the `state` pull and the `off` write), because the bar is a mouth for the command plane — a second\n * private channel would be a second contract to keep in step, which is what `doors.ts` already avoids. */\n exec?: (line: string) => Promise<string>\n}\n\nconst CSS = [\n // Metrics copied from the goal bar's measured module so the two rows read as one family: a 36px card,\n // host elevation + radius tokens, and the host's own composer width vars so it tracks the card above it.\n '.dsh-chapters_promptDock{box-sizing:border-box;width:calc(100% - 2 * var(--dsh-composer-side-clearance) - 4 * var(--dsh-composer-dock-inset));max-width:calc(var(--dsh-composer-card-max-width) - 4 * var(--dsh-composer-dock-inset));margin:0 auto}',\n '.dsh-chapters_promptBar{isolation:isolate;box-sizing:border-box;width:100%;border-radius:var(--dsw-radius-md);height:36px;box-shadow:var(--dsw-elevation-panel);border:0;align-items:center;gap:10px;padding:4px 5px 4px 12px;display:flex;position:relative}',\n '.dsh-chapters_promptBar::before{z-index:-1;border-radius:inherit;background:var(--dsw-specific-menu);backdrop-filter:var(--dsw-menu-backdrop-filter);content:\"\";pointer-events:none;position:absolute;inset:0}',\n '.dsh-chapters_promptExpanded::before{align-items:flex-start;position:absolute;inset:0}',\n // #229: the EXPANDED bar is a solid card that grows with its content — the maintainer's report was\n // an offer opening \"on a transparent background right over the bar, impossible to read\". The ::before\n // paint layer (menu token) already backs the collapsed row; expansion now also lifts height:auto so\n // the whole text sits ON the card, in flow, not floating over anything.\n '.dsh-chapters_promptExpanded{height:auto;min-height:36px;padding-top:8px;padding-bottom:8px}',\n '.dsh-chapters_promptGlyph{color:var(--dsw-alias-label-tertiary);flex:none;display:inline-flex}',\n '.dsh-chapters_promptLabel{color:var(--dsw-alias-label-primary);flex:none;font-size:13px;font-weight:500;line-height:24px}',\n // #236: `flex:1` alone means flex-basis AUTO — sized from content. Collapsed (nowrap) that reads\n // fine; EXPANDED, a tall multi-line block drives the item toward its minimum width while the\n // glyph/label/actions keep flex:none, so the text column squeezed to ~one character per line (the\n // maintainer's \"illegible text that has one character and whitespace per line\"). The fix is the\n // basis: claim the full remaining card width in both states.\n '.dsh-chapters_promptText{min-width:0;color:var(--dsw-alias-label-primary-dimmed);font-size:13px;line-height:20px;cursor:pointer;border:0;background:0 0;padding:0;text-align:left;flex:1 1 100%}',\n '.dsh-chapters_promptEllipsis{white-space:nowrap;text-overflow:ellipsis;overflow:hidden;display:block}',\n // #236: the expanded offer is a bounded reading pane — max-height with an internal scrollbar, so\n // a long suggestion can never cover the screen (the maintainer asked for exactly this). Normal\n // wrapping (`break-word`, not `anywhere`) keeps words whole on full-width lines.\n '.dsh-chapters_promptFull{white-space:pre-wrap;overflow-wrap:break-word;word-break:normal;line-height:20px;font-size:13px;color:var(--dsw-alias-label-primary);display:block;max-height:9rem;overflow-y:auto}',\n '.dsh-chapters_promptError{color:var(--dsw-alias-state-error-primary);font-size:12px;line-height:20px;flex:none;max-width:34%}', '.dsh-chapters_promptNote{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:20px;min-width:0}',,\n\n '.dsh-chapters_promptActions{flex:none;align-items:center;gap:10px;display:flex}',\n '.dsh-chapters_promptBtn{corner-shape:round;width:28px;height:28px;color:var(--dsw-alias-label-tertiary);cursor:pointer;background:0 0;border:none;border-radius:999px;justify-content:center;align-items:center;padding:0;display:inline-flex;font-size:13px}',\n '.dsh-chapters_promptBtn:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary)}',\n '.dsh-chapters_promptBtn:disabled{opacity:.4;cursor:default}',\n].join('\\n')\nconst CSS_ID = 'dsh-chapters/prompt-dock.css'\n\nconst ensureCss = (): void => {\n if (typeof document === 'undefined') return\n if (document.getElementById(CSS_ID) !== null) return\n const style = document.createElement('style')\n style.id = CSS_ID\n style.setAttribute('data-plugin-css', CSS_ID)\n style.textContent = CSS\n document.head.appendChild(style)\n}\n\n/** The analysis glyph, drawn to the goal icon's metric (16 viewBox, stroke currentColor, width 1).\n * A prism-and-arrow: the feature reads the situation and points at the next move. */\nconst Glyph = (): ReactElement => h(\n 'svg', { viewBox: '0 0 16 16', width: 14, height: 14, fill: 'none', 'aria-hidden': 'true', 'stroke-width': '1' },\n h('path', { d: 'M2.5 3.5h11L8 9.5 2.5 3.5Z', stroke: 'currentColor' }),\n h('path', { d: 'M8 9.5V14', stroke: 'currentColor' }),\n h('path', { d: 'M6 12l2 2 2-2', stroke: 'currentColor' }),\n)\n\n/** One action button, labelled through the host tooltip exactly as the goal bar labels its own. */\nconst Action = (props: { label: string; glyph: string; onClick: () => void; disabled?: boolean; title?: string; className?: string | undefined }): ReactElement => {\n const button = h('button', {\n type: 'button', className: props.className === undefined ? 'dsh-chapters_promptBtn' : `dsh-chapters_promptBtn ${props.className}`, 'aria-label': props.label,\n ...(props.disabled === true ? { disabled: true } : {}),\n ...(props.title !== undefined ? { title: props.title } : nativeTitle(props.label)),\n onClick: props.onClick,\n }, props.glyph)\n // Props matched to the call `doors.ts` already makes successfully: the host Tooltip takes\n // { label, side, children } and nothing else that I have verified. Inventing extra props (portal, delayMs)\n // failed the overload on the first compile, which is the right way to learn it.\n return withTooltip(props.label, button as ReactElement<Record<string, unknown>>)\n}\n\n/** Run is allowed whenever there is an offer; AUTORUN is what the intent and the goal gate. Keeping the\n * human's own button enabled is deliberate — the point of the protocol is to route a goal edit to a keystroke,\n * never to disable the human's ability to send it. */\n/**\n * The words the collapsed row shows, per state. `idle` and `analyzing` must say something, because an empty\n * row is indistinguishable from a broken one — the whole reason this feature took a day to read: the bar was\n * live, enabled, and rendering nothing but whitespace.\n */\nfunction lineFor(state: PromptBarState): string {\n if (state.status === 'ready') return state.text ?? ''\n if (state.status === 'analyzing') return 'Analyzing the session…'\n if (state.status === 'failed') return state.error !== null && state.error !== '' ? `Cannot recommend: ${state.error}` : 'Cannot recommend a next step right now'\n return 'No suggestion yet — I will recommend one after your next turn'\n}\n\n// #243: the graceful fallback when even a correct composer write is refused — copy the offer so the\n// human CAN edit it (paste, tweak, send). navigator.clipboard needs a secure context; the harness GUI\n// is loopback-http, which browsers treat as secure, but the failure arm just says so instead of lying.\nconst copyToClipboard = (text: string): boolean => {\n try {\n void navigator.clipboard?.writeText(text)\n return true\n } catch { return false }\n}\n\nconst canRunHere = (state: PromptBarState): boolean => state.text !== null && state.text !== ''\n\n/** How long a state pull may take before we call it failed. Generous on purpose: this is a local RPC that\n * answers in milliseconds when the session is attachable, and the failure it guards against is a hang. */\nconst PULL_TIMEOUT_MS = 15_000\n\n/**\n * #203: the last known truth per session, outliving the component. SPA navigation remounts the\n * dock, and every pull is a rendered `command/run`+`command/done` history pair — so a remount\n * that re-pulled wrote a node per activation, the waste the maintainer named (\"every time I\n * navigate away and come back\"). The cache makes activation free: mount folds it through the SAME\n * reducer (stateFromCache), and only an untrustworthy cache pulls (mountPullDecision). A page\n * reload clears it and pays exactly one honest pull.\n */\ninterface CacheEntry { ev: import('./prompt-bar.ts').PromptBarEvent; autorun: 'armed' | 'disarmed' | null; at: number; /** #272: set while this entry came from localStorage and THIS page has not polled since — it predates whatever the server decided, including an enablement. */ fromDisk?: boolean | undefined }\nconst stateCache = new Map<string, CacheEntry>()\n\n/**\n * #251: the memory cache dies with the page, and the maintainer's rule is absolute — a reload must\n * cost ZERO chapters-prompt commands. Two page loads producing two visible `state` nodes still reads\n * as \"the same shit\" from the chair, sanctioned or not. So the last-known truth persists per session\n * in localStorage (the host's own convention for composer state — `dsh.sessions.current`, persisted\n * drafts), and activation reads memory first, then storage. A cold tab renders the last offer with\n * no command at all; turn boundaries refresh it through the pulse/confirm paths that already exist.\n */\nconst PERSIST_PREFIX = 'dsh.chapters.promptState.'\nconst PERSIST_MAX = 50\n\nconst persistKey = (sessionId: string): string => `${PERSIST_PREFIX}${sessionId}`\n\nfunction readPersisted(sessionId: string): CacheEntry | null {\n try {\n const raw = window.localStorage.getItem(persistKey(sessionId))\n if (raw === null) return null\n const p = JSON.parse(raw) as { ev?: unknown; autorun?: unknown; at?: unknown }\n if (typeof p.at !== 'number' || p.ev === null || typeof p.ev !== 'object') return null\n const t = (p.ev as { t?: unknown }).t\n if (t !== 'polled') return null\n const autorun = p.autorun === 'armed' || p.autorun === 'disarmed' ? p.autorun : null\n return { ev: p.ev as CacheEntry['ev'], autorun, at: p.at, fromDisk: true }\n } catch { return null }\n}\n\nfunction writePersisted(sessionId: string, entry: CacheEntry): void {\n try {\n window.localStorage.setItem(persistKey(sessionId), JSON.stringify(entry))\n // bounded: prune the oldest beyond PERSIST_MAX by their recorded time\n const keys: string[] = []\n for (let i = 0; i < window.localStorage.length; i++) {\n const k = window.localStorage.key(i)\n if (k !== null && k.startsWith(PERSIST_PREFIX)) keys.push(k)\n }\n if (keys.length <= PERSIST_MAX) return\n const aged = keys.map((k) => {\n let at = 0\n try { at = Number(((JSON.parse(window.localStorage.getItem(k) ?? '{}') as { at?: number }).at) ?? 0) } catch { at = 0 }\n return { k, at }\n }).sort((x, y) => x.at - y.at)\n for (const old of aged.slice(0, keys.length - PERSIST_MAX)) window.localStorage.removeItem(old.k)\n } catch { /* private mode / quota: the memory cache still does its job */ }\n}\n\n/** Memory first, then disk — one reader so every decision sees the same truth (#59). */\nfunction cachedState(sessionId: string | undefined): CacheEntry | undefined {\n if (sessionId === undefined) return undefined\n const mem = stateCache.get(sessionId)\n if (mem !== undefined) return mem\n const disk = readPersisted(sessionId)\n if (disk !== null) { stateCache.set(sessionId, disk); return disk }\n return undefined\n}\n\n/**\n * #208: set by the first reply reporting the plane-wide `model: unset` — the feature does not\n * exist here, so NO dock on this page pulls again for anything: not mounts, not idle edges, not\n * timers, not visibility. One discovery per page load is the pull transport's floor; a page reload\n * is the only revival, and the enabling commands say so.\n */\nlet featureAbsent = false\n\n/** Retry ceiling for the FIRST pull only, in attempts and spacing. A mount-time race must not be able to\n * starve the bar forever, and a real `off` answer stops the loop on the first reply either way. */\n\nfunction execWithTimeout(exec: (line: string) => Promise<string>, line: string, ms: number): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n const timer = setTimeout(() => { reject(new Error(`no answer within ${String(ms)}ms`)) }, ms)\n exec(line).then(\n (text) => { clearTimeout(timer); resolve(text) },\n (error: unknown) => { clearTimeout(timer); reject(error instanceof Error ? error : new Error(String(error))) },\n )\n })\n}\n\n/**\n * The composer, by the name the HOST gives it (placeholder \"Message or run a task, / commands, …\",\n * locales.ts:400) — NOT a bare `[contenteditable][role=textbox]` first(), which on this app matches\n * the sidebar's \"Search session names\" input (measured lesson, tests/e2e/prompt-bar.spec.ts:41: a\n * whole click-to-draft assertion was reading the wrong element). The host's own editable element\n * carries `data-composer-input` (measured: ComposerContentEditable.tsx:46) — stable across styles,\n * locales and restyles, so the probe matches THAT and never a first(). Shared by the three sites\n * that touch the editor: the #309 occupancy guard, the focus-before-insert, and the\n * write-verification — one probe, one truth. Absent attribute ⇒ null ⇒ the guard ALLOWS the\n * handoff (unknown is never a reason to block the feature; the post-write verify is the backstop).\n */\nconst composerBox = (): HTMLElement | null => {\n try { return document.querySelector<HTMLElement>('[data-composer-input]') } catch { return null }\n}\n\n/** #309: does the chat input hold the user's in-flight text? Whitespace-only counts as empty. */\nconst composerHasText = (): boolean => {\n const el = composerBox()\n if (el === null) return false\n const t = 'value' in el ? String((el as unknown as { value: string }).value ?? '') : (el.innerText ?? '')\n return t.trim() !== ''\n}\n\nexport function PromptDock(props: DockProps): ReactElement | null {\n const { sessionId, inputActions, exec } = props\n // #194 + the contract's running-signal lock: BOTH hook reads happen first, unconditionally,\n // above every other hook — hook order must not change between renders (the #310 lesson). The\n // measured seats: `useSession`'s snapshot carries `running` (deriveRunning folds whatever shape\n // arrives; a scalar `running` prop wins where a build supplies one), and `useProjection` is the\n // standard seat the push transport rides. Absent hooks degrade through stable fallbacks.\n const useSessionHook = props.useSession ?? (() => undefined)\n const sessionSnapshot = useSessionHook((snapshot: unknown) => snapshot)\n const running = props.running ?? deriveRunning(sessionSnapshot)\n const useProjectionHook = props.useProjection ?? (() => undefined)\n const pushed = useProjectionHook(PROMPT_PROJECTION_KEY)\n // #221: the host's OWN turn-boundary projection. Reading it costs nothing (the agent loop already\n // maintains it), works on EVERY host with projections including 0.2.0-rc.2 — where appendPluginRecord\n // is absent and the record transport cannot exist. A new turn end is the only moment our row can\n // change without a user action, so this pulse replaces the clock: one sanctioned follow-up pull per\n // boundary instead of a 10-second drumbeat (measured on the maintainer's live log: 158 pulls at exact\n // 10.0s intervals). Absent hook or projection ⇒ no pulse ⇒ the quiet heartbeat stands.\n const turnBoundary = useProjectionHook('turnBoundary') as { lastTurn?: number } | null | undefined\n const [state, dispatch] = useReducer(promptBarReducer, initialBarState(), (s) => {\n // #203: activation renders from the module cache — zero invocations — folded through the live\n // reducer path, so there is no second fold implementation to drift.\n const pushEvs = pushEventsOf(pushed)\n if (pushEvs !== null) {\n return { ...promptBarReducer(promptBarReducer(s, pushEvs.polled), pushEvs.autorun), running: running === true }\n }\n const c = cachedState(sessionId)\n const base = c !== undefined ? stateFromCache(c.ev, c.autorun) : s\n return { ...base, running: running === true }\n })\n // #79's discipline, kept because the failure it prevents was real: one pull per mount, then per edge.\n // A fetch in an effect with no such guard re-fires on every render.\n const pulling = useRef(false)\n // #304: consecutive analyzing OBSERVATIONS drive the belt back-off (10/20/40/60). It counts\n // what the wire SAID, not what we hope is happening — any non-analyzing answer resets it.\n const analyzingStreak = useRef(0)\n // TWO different facts, two different refs — conflating them is the bug I just shipped: `pulled` is the\n // once-per-mount pull guard, `alive` is \"may this component still call dispatch/setState\". Initializing the\n // pull guard to true made every mount skip its first pull, so the bar sat at its `off` default and rendered\n // nothing at all — a regression that looked, from outside, like the feature having stopped working.\n const probed = useRef(false)\n const pulled = useRef(false)\n const alive = useRef(true)\n useEffect(() => () => { alive.current = false }, [])\n const [busy, setBusy] = useState(false)\n void 0\n // #193: the mount effect's reschedule handle, so the idle edge and the visibility edge can pull NOW\n // instead of waiting out a possibly-quiet cadence. Undefined while the poll is not mounted.\n const kick = useRef<(() => void) | undefined>(undefined)\n // #211: when the last pull STARTED (a failed pull is still a rendered node — the floor counts it),\n // and the pending debounced edge pull, which a rising edge cancels.\n const lastPullAt = useRef<number | null>(null)\n const edgeTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n // #194: push-mode bookkeeping. A projection that existed and went silent is the confirm-pull's\n // job to police, not a reason to resurrect the clock — once live, live for the page lifetime.\n // #497: live is decided by the CELL, not by an arrival. The server registers this projection\n // only after the push transport resolved, and the seat read is a synchronous cut over the host's\n // watermark cache — so a cell that EXISTS on first render (payload or null: registered means the\n // records ride) can gain nothing from a mount pull except two durable command nodes. The old\n // latch-on-arrival always lost the race with the mount tick, so EVERY session load of EVERY\n // page paid the pull the maintainer's rule forbids. Absent cell (pre-projection host, or the\n // writer refused at boot) ⇒ undefined ⇒ the honest pull-first fallback stands, unchanged.\n const pushLiveRef = useRef<boolean>(pushed !== undefined)\n // #497: did the MOUNT tick sanction a pull? The retry loop may only chase a starved pull (exec\n // not hydrated yet, #429's whole point) — never invent one the silent-by-design mount skipped.\n const pullOwed = useRef<boolean>(false)\n // #221: the last turn-end seq observed; the pulse fires when the host advances past it.\n const seenTurnRef = useRef<number>(0)\n const lastPushAt = useRef<number | null>(null)\n const answered = useRef(false)\n const replyStatus = useRef<string>('unknown')\n const stateRef = useRef<PromptBarState>(initialBarState())\n stateRef.current = state\n // #203: does THIS host publish the running signal? Where it does, the idle edge is the schedule\n // and a stable bar keeps no clock; where it does not, the #193 cadence is the fallback.\n const edgesRef = useRef<boolean>(props.running !== undefined)\n edgesRef.current = props.running !== undefined\n if (!probed.current) {\n probed.current = true\n // One print, on the first mount: which composer verbs does THIS host actually hand a dock? The click-to-draft\n // requirement needs one, `setDraft` is accepted but never reaches the editor, and guessing at the surface\n // again would be a third wrong theory in a row.\n console.info(`[client:prompt] inputActions keys: ${Object.keys(inputActions ?? {}).join(',') || 'NONE'}`)\n }\n\n const refresh = useCallback(async (): Promise<void> => {\n if (exec === undefined || pulling.current) return\n pulling.current = true\n lastPullAt.current = Date.now()\n try {\n // Bounded, and loudly so. Tonight's whole diagnosis cost was paid because this await had no ceiling:\n // a wire that never answers produced no dispatch, no catch and no `finally`, which looked identical to\n // \"the feature is switched off\". A hung command is now a named failure with a number on it (#61).\n const text = await execWithTimeout(exec, BAR_STATE_COMMAND, PULL_TIMEOUT_MS)\n // Handed to the leg through the page, because the state block is the contract and I need to see the\n // bytes the browser parsed, not the bytes the server meant. Overwritten each pull; read on failure.\n try { (window as unknown as { __dshPromptReply?: string }).__dshPromptReply = text } catch { /* test seam only */ }\n const ev = parseBarState(text) as PromptBarEvent | null\n if (ev !== null) {\n answered.current = true\n const st = (ev as { status?: string }).status ?? replyStatus.current\n replyStatus.current = st\n analyzingStreak.current = st === 'analyzing' ? analyzingStreak.current + 1 : 0 // #304\n dispatch(ev)\n }\n const autorun = parseBarAutorun(text)\n if (autorun !== null) dispatch({ t: 'autorun', on: autorun === 'armed' })\n // #208: a reply naming the model unset silences the whole page — relevance is plane-wide.\n if (parseModelAbsent(text)) featureAbsent = true\n // #203: every honest reply feeds the cache the next activation renders from.\n if (ev !== null && sessionId !== undefined) {\n stateCache.set(sessionId, { ev, autorun: autorun === 'armed' || autorun === 'disarmed' ? autorun : null, at: Date.now() })\n // #251: write-through — this reply now outlives the page.\n writePersisted(sessionId, { ev, autorun: autorun === 'armed' || autorun === 'disarmed' ? autorun : null, at: Date.now() })\n }\n } catch (error) {\n // #61: a detected failure is a DELIVERED failure. Keeping the last known state is right; saying\n // nothing was not — with a bare `catch {}` a wire that never answers is indistinguishable from a\n // feature that is switched off, and that is exactly how this bar looked \"unverifiable\" in a browser\n // while the real fault was one line of swallowed output.\n // A failed pull is not a state: the bar keeps what it last knew rather than rendering `off`,\n // which would read as \"suggestions are disabled\" when the wire merely hiccoughed.\n console.warn(`[client:prompt] pull failed: ${String((error as Error)?.message ?? error).slice(0, 180)}`)\n } finally { pulling.current = false }\n }, [exec])\n\n // #194: the pushed value dispatches through the same reducer the pulls feed. The effect sits\n // ABOVE the mount poll so pushLive is set before the first tick decides anything. Any push also\n // retires a pending edge timer in push mode — the record IS the answer the confirm would fetch.\n useEffect(() => {\n // #497: a cell that EXISTS is an answer channel even before its first payload — retry pulls\n // are owed to exec, never to a projection that has not been given its chance to hydrate.\n if (pushed !== undefined) pushLiveRef.current = true\n const evs = pushEventsOf(pushed)\n if (evs === null) return\n pushLiveRef.current = true\n lastPushAt.current = Date.now()\n dispatch(evs.polled)\n dispatch(evs.autorun)\n if (edgeTimer.current !== undefined) { clearTimeout(edgeTimer.current); edgeTimer.current = undefined }\n }, [pushed])\n\n useEffect(() => {\n ensureCss()\n if (pulled.current) return\n pulled.current = true\n // Retry until SOMETHING answers. `answered` flips on any parseable reply, including an honest `off`, so\n // this loop cannot make a disabled session look enabled — it only closes the window where a pull fired\n // before the session could take a command and the bar then stayed blank for the rest of the session.\n // Keep reading while the feature is live, at a cadence that is a DECISION (#193): every pull is two\n // recorded host lifecycle events (`command/run` + `command/done`) the UI renders as history nodes, so\n // the old unconditional 10s poll wrote ~360 visible nodes an hour into every bar-enabled session —\n // the maintainer's \"littered with chapters-prompt runs, one right after another\". `pollSpacingFor`\n // paces it: fast while state can change (analyzing / armed / running), slow while stable, and NOTHING\n // in a hidden tab unless the loop is armed. On hosts that publish no running prop, `running` stays\n // conservatively true and the cadence stays active — the old behavior, unchanged. `off` still ends it.\n let timer: ReturnType<typeof setTimeout> | undefined\n // #203: one vocabulary for \"what the bar knows right now\" — a reply beats the cache-folded row\n // state, and every schedule decision reads THIS instead of keeping a fourth copy of the truth.\n const effectiveStatus = (): PromptBarStatus =>\n (replyStatus.current === 'unknown' ? stateRef.current.status : replyStatus.current) as PromptBarStatus\n const spacingNow = (): number | null => {\n // #229: an ARMED autorun loop is the one state that genuinely needs follow-up polling — after\n // a fired round the offer changes without a human action, and the turn-end pulse may already\n // have been consumed before generation finished. While armed, keep the old quiet floor (60s)\n // even when the ambient heartbeat is off; disarmed bars poll nothing.\n if (stateRef.current.autorun === 'armed') return ACTIVE_POLL_MS\n // #221: consume the pulse exactly once per boundary.\n const pe = turnEndPulse(turnBoundary?.lastTurn, seenTurnRef.current)\n if (pe.pulse) seenTurnRef.current = pe.seen\n return pollSpacingFor({\n status: effectiveStatus(),\n autorun: stateRef.current.autorun,\n running: stateRef.current.running,\n hidden: typeof document !== 'undefined' && document.hidden === true,\n edges: edgesRef.current,\n turnEndPulse: pe.pulse,\n analyzingStreak: analyzingStreak.current, // #304: arm the back-off with what we've OBSERVED\n })\n }\n const duePull = (): boolean => {\n const c = cachedState(sessionId)\n return mountPullDecision({\n hasCache: c !== undefined,\n ageMs: c !== undefined ? Date.now() - c.at : Number.MAX_SAFE_INTEGER,\n status: effectiveStatus(),\n autorun: stateRef.current.autorun,\n // #272: an off carried across the reload from localStorage must still pay this page's one\n // honest pull — the revival promise. Once this page polls, the replacing entry is untagged.\n cacheFromDisk: c?.fromDisk === true,\n })\n }\n const tick = async (opts?: { mount?: boolean; force?: boolean }): Promise<void> => {\n // #194: in push mode there is no clock and no mount pull — state arrives through the\n // projection. A FORCED tick still runs: that is the staleness confirm firing because the\n // push did NOT arrive, and the pull is then the honest fallback, not waste.\n if (pushLiveRef.current && opts?.force !== true) return\n // #208: not relevant, not visible — an unset-model plane spends nothing, ever.\n if (featureAbsent) return\n if (effectiveStatus() === 'off') {\n // A known `off` spends no clock and no edge — but a STALE cached off is untrustworthy:\n // `/chapters-prompt on` could have happened anywhere. The staleness guard on a mount is the\n // only revival path short of a page reload, and that matches the old within-mount rule.\n if (!(opts?.mount === true && duePull())) return\n }\n const spacing = spacingNow()\n // force = an edge the schedule sanctions (a turn ended): pull even where the steady cadence\n // says no timer is needed. mount = the guarded first look; a fresh cache renders for free.\n // #231: the MOUNT discovery is a sanctioned moment in its own right — it must NOT be gated on\n // `spacing`, or removing the ambient clock (the whole point of #231) removes the one pull that\n // tells the bar whether the feature exists at all. Measured cost of getting this wrong: the\n // rig's prompt leg failed four-for-four because no pull ever fired and the dock stayed hidden.\n const mountDiscovery = opts?.mount === true && duePull()\n if (opts?.force === true || mountDiscovery || (spacing !== null && opts?.mount !== true)) {\n if (opts?.mount === true) pullOwed.current = true // #497: the sanction IS the debt\n await refresh()\n }\n if (replyStatus.current === 'off') return\n // The reply, not the React state: the row is hidden while `off`, and a hidden row renders\n // nothing, so stateRef can lag. The schedule reads the wire truth whenever it exists.\n const next = spacingNow()\n if (next !== null) timer = setTimeout(() => { void tick() }, next)\n }\n // The idle edge IS the schedule (#203): a turn ending is the moment an offer is born, so it\n // pulls with force. The tab-foreground edge pulls ONLY when the cache can no longer be\n // trusted — flicking back to a tab you left a moment ago must not write a history node.\n kick.current = () => {\n if (timer !== undefined) clearTimeout(timer)\n void tick({ force: true })\n }\n const onVisible = (): void => {\n if (typeof document !== 'undefined' && !document.hidden && duePull()) kick.current?.()\n }\n if (typeof document !== 'undefined') document.addEventListener('visibilitychange', onVisible)\n // #429: THE FIRST-PULL BOUNDED RETRY, finally as code — both comments above promise it (:240's\n // ceiling, :410's 'retry until SOMETHING answers'), and its absence was the measured revival-leg\n // flake: the mount effect fires while a loaded boot is still hydrating the composer's exec verb,\n // refresh() returns at `exec === undefined` BEFORE pulling (no wire node, no answer), and under\n // the quiet cadence (#229) nothing ever asks the mount again. Samples: FAILED in two loaded\n // chains (local + CI), PASSED 10/10 solo on the same head + CI re-run + #427's CI. The loop is\n // due ONLY while owed and unanswered (firstPullRetryDue — any honest reply, `off` included, is an\n // answer, #304), and at the ceiling it gives up LOUDLY: a silent give-up is the mystery this\n // whole class of bug ships behind (#54, again).\n let firstPullRetries = 0\n let firstPullTimer: ReturnType<typeof setTimeout> | undefined = undefined\n const retryFirstPull = (): void => {\n if (!firstPullRetryDue({ answered: answered.current, featureAbsent, attempts: firstPullRetries, owed: pullOwed.current, pushLive: pushLiveRef.current })) {\n if (!answered.current && !featureAbsent && pullOwed.current && !pushLiveRef.current && firstPullRetries >= FIRST_PULL_RETRY_CEILING) {\n console.warn(`[client:prompt] first-pull retry ceiling (${String(FIRST_PULL_RETRY_CEILING)} x ${String(FIRST_PULL_RETRY_SPACING_MS)}ms) reached with NO wire answer — the mount pull remains owed; edges are the recovery path (#429)`)\n }\n return\n }\n firstPullRetries += 1\n firstPullTimer = setTimeout(() => {\n firstPullTimer = undefined\n void refresh().then(() => { retryFirstPull() })\n }, FIRST_PULL_RETRY_SPACING_MS)\n }\n void tick({ mount: true }).then(() => { retryFirstPull() })\n return () => {\n if (firstPullTimer !== undefined) clearTimeout(firstPullTimer)\n if (timer !== undefined) clearTimeout(timer)\n if (edgeTimer.current !== undefined) { clearTimeout(edgeTimer.current); edgeTimer.current = undefined }\n kick.current = undefined\n if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', onVisible)\n }\n }, [refresh])\n\n // Autorun fires off the IDLE edge, never off a render. `running` comes from the host when it publishes it;\n // absent means unknown, and unknown means do not start a turn the human cannot see coming.\n // #221/#282: unknown is NOT running. `?? true` here pinned a non-publishing host into a permanent\n // running edge — harmless while running only decorated the flag, fatal once a running edge CLEARS\n // the offer (#282): the bar would show \"Agent is running\" forever. Strict boolean at every fold.\n const prevRunning = useRef<boolean>(running === true)\n useEffect(() => {\n const next = running === true\n const prev = prevRunning.current\n prevRunning.current = next\n dispatch({ t: 'running', running: next })\n // #211 + #194, ONE schedule: a falling edge delays exactly one pull and a rising edge cancels\n // it (step-granular flicker coalesces to zero pulls). Pull mode: the debounced kick\n // (edgeKickDelayMs — 2s debounce, 15s floor). Push mode: the staleness CONFIRM at\n // max(grace, floor − since) — a record landing after the edge retires it via the push effect,\n // so a healthy push costs nothing and a dead one degrades to one pull per turn, never a\n // frozen bar. Hosts that publish no running signal never produce transitions and keep the\n // cadence fallback unchanged.\n if (prev && !next) {\n if (edgeTimer.current !== undefined) clearTimeout(edgeTimer.current)\n const since = lastPullAt.current === null ? Number.MAX_SAFE_INTEGER : Date.now() - lastPullAt.current\n const delay = pushLiveRef.current\n ? Math.max(PUSH_CONFIRM_GRACE_MS, edgeKickDelayMs(since))\n : edgeKickDelayMs(since)\n const edgeAt = Date.now()\n edgeTimer.current = setTimeout(() => {\n edgeTimer.current = undefined\n // A push that landed after the edge already answered the confirm's question.\n if (pushLiveRef.current && pushIsFresher(lastPushAt.current, edgeAt)) return\n kick.current?.()\n }, delay)\n } else if (!prev && next) {\n if (edgeTimer.current !== undefined) { clearTimeout(edgeTimer.current); edgeTimer.current = undefined }\n }\n }, [running])\n\n // Run is a COMMAND, not a keystroke. The composer-write path (`inputActions.setDraft` + `submit`) looked\n // like the obvious implementation and does not work on this host build: `setDraft` is accepted, and the\n // editor stays empty — measured, twice, after I had convinced myself it was the test's locator or a focus\n // ordering problem. The plugin already has a dependable wire to its own server plane, and the server has\n // exactly one human-authored submission path (the follow-up autorun uses), so Run rides that. The\n // consequence is also the point: what the human clicks and what the loop arms are the same code.\n const run = useCallback((): void => {\n if (state.text === null || state.text === '' || exec === undefined) return\n setBusy(true)\n void exec(BAR_RUN_COMMAND)\n .then((out) => {\n if (!alive.current) return\n if (/^cannot run:/i.test(out.trim())) dispatch({ t: 'polled', status: 'failed', text: state.text, error: out.trim().slice(0, 200), turnSeq: state.turnSeq } as PromptBarEvent)\n // #285: success means THIS click authored a turn — the dock knows that without any host\n // signal, so it folds `running: true` locally: the offer clears, Run disarms, and the\n // generic running line shows even on edgeless hosts (#221). The server consumed the row in\n // the same breath, so the next pull (any tab) confirms the truth, and polled retires the\n // flag wire-first. Replaces #282's collapse-only success fold, which left a just-run offer\n // sitting there re-runnable — the hole the maintainer's double-Click found.\n else dispatch({ t: 'running', running: true } as PromptBarEvent)\n // #518: the consumed state must OUTLIVE the reload. The disk cache kept the pre-run ready\n // entry, so a cold mount resurrected the executed offer with enabled buttons — the bar must\n // show the truth (nothing to run; next offer arrives at the next completed turn) everywhere.\n if (sessionId !== undefined) {\n const runEntry = { ev: { t: 'polled', status: 'off' } as CacheEntry['ev'], autorun: null, at: Date.now() }\n stateCache.set(sessionId, runEntry)\n writePersisted(sessionId, runEntry)\n }\n })\n .catch((error: unknown) => { console.warn(`[client:prompt] run failed: ${String((error as Error)?.message ?? error).slice(0, 160)}`) })\n .finally(() => { if (alive.current) setBusy(false) })\n }, [exec, state.text, state.turnSeq])\n\n useEffect(() => {\n if (!shouldAutoFire(state)) return\n run()\n }, [state, run])\n\n // Autorun's idle edge stays UNWIRED on this host, and that is now a measured fact rather than a guess:\n // `useSessionStatus` is in the dock's documented prop list, but calling it here threw twice — first a React\n // hook-order abort (#310, because it sat below the early return), then `TypeError: l is not a function` once\n // hoisted. Two blind attempts is the limit; the contract says which hooks exist, not their arity or context.\n // So the gate keeps its original, correct behavior: with no signal, `running` is undefined, Autorun is\n // visibly unavailable and says why, and `deriveRunning` (9 rows) stands ready for whichever shape the host\n // does publish. A loop that starts turns the human cannot foresee is the one failure mode not on offer.\n // `useSessionStatus` is `SnapshotSelectorHook<SessionStatusSnapshot>` — a SELECTOR hook (declared in\n // dsh-client-ui-session's client types), which is why calling it with a session id threw\n // `TypeError: l is not a function`: the host used my string as the selector. An identity selector takes\n // whatever the snapshot's shape happens to be, and `deriveRunning` folds it, so this code does not bet on\n // field names I have not read. Still hoisted above the early return: hook count must not change per render.\n // The idle signal IS published — on `useSession`, whose snapshot carries `running` (measured by printing the\n // hook surfaces once: `useSession=sessionId|pendingSubmissions|running|subagent|removed|openState`). My\n // first two attempts were wrong in different ways: a scalar `props.running` that no host supplies, then\n // `useSessionStatus`, which is provided but yields no readable keys under an identity selector. `deriveRunning`\n // folds `{running}`, so this is the last mile, and the hook is called unconditionally through a stable\n // fallback because hook order must not change between renders.\n const autorunDisabled = running === undefined\n\n if (sessionId === undefined || !barVisible(state as PromptBarState)) return null\n\n const populate = (): void => {\n // Collapsed: reading. Expanded: the maintainer's click-to-edit gesture — setDraft REPLACES the draft,\n // which is what they asked for (\"the prompt replaces the chat input contents so you can edit it\"), and\n // nothing is submitted. Run is a separate, deliberate button.\n // Printed on every branch, because \"the button did nothing\" and \"the button took the other path\" looked\n // identical from outside for three runs.\n console.info(`[client:prompt] populate expanded=${String(state.expanded)} hasInsertText=${String(typeof inputActions?.insertText)} hasSetDraft=${String(typeof inputActions?.setDraft)} textLen=${String(state.text?.length ?? -1)}`)\n if (!state.expanded) { dispatch({ t: 'expand' }); return }\n if (state.text === null || state.text === '') return\n // #309: hand off INTO AN EMPTY COMPOSER ONLY — never append to, never overwrite, text the user\n // is mid-typing. The refusal says itself on the bar (the tooltip already named the precondition).\n if (composerHasText()) { dispatch({ t: 'note', note: 'The chat input has text — clear it first, then this click hands the suggestion over.' }); return }\n // Delivered, not assumed. The click-to-draft gesture is the interaction the maintainer asked for, so a\n // silent no-op here is indistinguishable from \"the feature does not work\" — and that ambiguity cost the\n // rest of this leg's diagnosis. Absent verb, absent text: both say so.\n // The host's composer kit is `{ captureInsertion, insertText, setDraft, addAttachments, removeAttachment,\n // pruneAttachments, submit }` (measured on 0.2.0-rc.2). `setDraft` writes the STORE, and the store is\n // mirrored into the editor only at mount while the editor is empty — which is why a click that \"worked\"\n // (no refusal, no throw) left the box visibly empty. `insertText` is the verb that reaches the editor, so\n // click-to-draft uses it and keeps `setDraft` only as a fallback for builds that lack it.\n if (typeof inputActions?.insertText === 'function') {\n // `insertText` inserts AT THE CARET, and clicking this button moves the caret out of the editor — so the\n // call ran and put the words nowhere. Focusing the composer first is the whole difference, and it is done\n // with a tolerant query rather than a class name: the host's own module hashes (`wSkVaW_…`) are not mine\n // to depend on, and a bar that silently stops drafting after a host restyle is worse than one that tries.\n try { composerBox()?.focus() } catch { /* a host without the editor mounted: the insert below still records the intent */ }\n // Measured on host 0.2.0-rc.2: called from a dock this throws\n // `Cannot read properties of undefined (reading 'draftRev')`, and the kit's other verb (`setDraft`) writes\n // a store the editor mirrors only at mount. Neither reaches the composer. A silent no-op is what cost the\n // last six runs, so the refusal now appears on the bar and points at Run, which does work.\n // #243: THE BUG WAS OURS. The contract (ui-conversation contract/input.ts:249-256) requires\n // TWO steps: `captureInsertion()` returns the revision-guarded span, then `insertText(text, span)`\n // applies it. We called `insertText(text)` with NO span — facade.ts:128 reads `span.draftRev` off\n // `undefined` and throws. That throw, not any host defect, is what #126 recorded as \"the composer\n // refuses plugin writes\"; the API works exactly as documented once used correctly.\n const refuse = (why: string): void => {\n console.warn(`[client:prompt] click-to-draft refused: ${why}`)\n // Even the correct call can be refused honestly (phase guards). The fallback that always works:\n // put the offer on the CLIPBOARD and say so — the maintainer's own design — so the human pastes\n // into the composer, edits, sends.\n const copied = copyToClipboard(state.text ?? '')\n dispatch({ t: 'note', note: copied\n ? 'The composer refused this write (' + why.slice(0, 60) + ') — the prompt is COPIED: paste it into the input to edit, or press Run \\u25B6 to send as-is.'\n : 'The composer refused this write (' + why.slice(0, 60) + ') — press Run \\u25B6 to send the offer as-is, or copy the text above.' })\n }\n let wrote = false\n try {\n // The contract path first: captureInsertion() -> insertText(text, span). On hosts where the\n // two-argument call is unreachable from a dock (measured on 0.2.0-rc.2: the span guard sees\n // undefined even when we pass a real span), this throws or returns false and setDraft takes\n // over below — never a dead end.\n const span = typeof inputActions.captureInsertion === 'function' ? inputActions.captureInsertion() : null\n if (span !== null && span !== undefined) wrote = inputActions.insertText(state.text, span as never) === true\n } catch { wrote = false }\n if (!wrote && typeof inputActions.setDraft === 'function') {\n try { inputActions.setDraft(state.text); wrote = true } catch { wrote = false }\n }\n if (!wrote) { refuse('neither insertText nor setDraft was accepted'); return }\n // #295: the handoff SUCCEEDED — fold the bar back to its normal size. The gesture the\n // maintainer leans on ends tidy: the words are in the composer, the pane is closed, and\n // the offer stays in the row (Run still works; the next turn's pull refreshes it anyway).\n dispatch({ t: 'collapse' })\n // Verify what the human will SEE: the words in the editor, or in the persisted draft store\n // (setDraft writes the store; some builds mirror it into the editor only at mount). Neither?\n // say so plainly — Run still works, and silence is the one outcome never allowed.\n const head = state.text.slice(0, 24)\n setTimeout(() => {\n try {\n const el = composerBox()\n const dom = el === null ? false : (('value' in el ? String((el as unknown as { value: string }).value ?? '') : (el.innerText ?? '')).includes(head))\n const stored = Object.entries(localStorage).some(([, v]) => String(v).includes(head))\n if (!dom && !stored) refuse('the write was accepted but nothing holds the text')\n } catch { /* diagnostics never break the gesture */ }\n }, 400)\n return\n return\n }\n if (typeof inputActions?.setDraft === 'function') {\n inputActions.setDraft(state.text)\n dispatch({ t: 'collapse' }) // #295: same fold on the fallback write path\n return\n }\n console.warn('[client:prompt] click-to-draft refused: this host exposes neither insertText nor setDraft')\n }\n\n // Called unconditionally through a stable fallback, so the hook order cannot change between renders.\n return h('div', { className: 'dsh-chapters_promptDock', 'data-prompt-bar': 'true' },\n h('div', { className: `dsh-chapters_promptBar${state.expanded ? ' dsh-chapters_promptExpanded' : ''}` },\n h('span', { className: 'dsh-chapters_promptGlyph' }, h(Glyph)),\n h('span', { className: 'dsh-chapters_promptLabel' }, barLabel(state as PromptBarState) ?? ''),\n // #300: a goal re-cut still never auto-runs (the host reserves goal edits for a human turn), but the\n // fact now rides barLabel's REPLACEMENT text — the old second-message span overflowed the one-line\n // row and clipped the composer. Run's own tooltip (below) still explains the keystroke requirement.\n (() => {\n // #282+#309: one sentence (rowTooltip) for aria-label AND the bubble; the bubble rides the\n // HOST's themed tooltip seat (withTooltip) like the door buttons — the hard-coded native title\n // here was the black-bubble foreign style the maintainer flagged. nativeTitle appears only when\n // the host seat is absent; never both. Read per render, so the occupied-composer warning\n // tracks typing without a private clock.\n const rowTip = rowTooltip(state.expanded, composerHasText())\n return withTooltip(rowTip, h('button', {\n type: 'button', className: 'dsh-chapters_promptText',\n 'aria-label': rowTip,\n ...nativeTitle(rowTip),\n disabled: state.running,\n onClick: populate,\n }, state.expanded\n ? h('span', { className: 'dsh-chapters_promptFull' }, state.text ?? '')\n : h('span', { className: 'dsh-chapters_promptEllipsis' }, lineFor(state))) as ReactElement<Record<string, unknown>>)\n })(),\n ...(state.note === '' ? [] : [h('span', { key: 'note', className: 'dsh-chapters_promptNote', role: 'status' }, state.note)]),\n ...(state.error === '' ? [] : [h('span', { key: 'err', className: 'dsh-chapters_promptError', role: 'alert' }, state.error)]),\n h('div', { className: 'dsh-chapters_promptActions' },\n // #295: the collapse control lives in the ACTION row (right edge = top-right of the bar),\n // never floated over the prompt text — the pane-corner version made text and button fight\n // for the same pixel. The reducer's 'collapse' case keeps the offer; this is reading, not dismissal.\n ...(state.expanded ? [h(Action, {\n key: 'collapse',\n label: 'Collapse the suggested prompt', glyph: '▾', className: 'dsh-chapters_promptCollapse', // #309: it folds DOWN\n onClick: () => { dispatch({ t: 'collapse' }) },\n })] : []),\n h(Action, {\n label: 'Run the suggested next step', glyph: '▶', onClick: run, disabled: busy,\n ...(state.text === null || state.text === '' || !canRunHere(state) ? { disabled: true } : {}),\n ...(state.intent === 'goal-edit'\n ? { title: 'Goal edits need a human turn. Run still works; autorun will never do this one.' }\n : {}),\n }),\n h(Action, {\n label: state.autorun === 'armed' ? 'Autorun off' : 'Autorun',\n glyph: state.autorun === 'armed' ? '⟳' : '⟲',\n disabled: autorunDisabled,\n ...(autorunDisabled\n ? { title: 'Autorun needs the host to publish an idle signal; this build does not, so nothing would fire safely.' }\n : {}),\n // A SERVER write, like `off` below. Flipping local state alone was the defect: `refresh()` re-reads the\n // loop state (`:193`), the server still says `disarmed`, and the label snaps back — so the user watched\n // their own click be refused and the loop could never be started from the bar. The command surface is\n // `/chapters-prompt autorun on|off` (src/commands.ts:462-478), which also reports the goal displacement.\n onClick: () => {\n void (async () => {\n const arm = state.autorun !== 'armed'\n if (exec !== undefined) await exec(`/chapters-prompt autorun ${arm ? 'on' : 'off'}`)\n dispatch({ t: 'autorun', on: arm })\n // #194: in push mode the setAutorun append carries the truth back — a refresh here\n // would be a command run for a fact already in flight.\n if (!pushLiveRef.current) await refresh()\n })()\n },\n }),\n h(Action, {\n label: 'Turn prompt suggestions off for this session', glyph: '✕',\n // #291: off-SESSION — the scope this label has always promised. It used to execute the\n // plane-wide `off` verb (clears the model for EVERY session); one exploratory click here\n // silenced the whole plane while the row said \"for this session\". Generation stops for\n // this session, the model is kept, and the bar disappears instead of lingering stale.\n onClick: () => { void (async () => { if (exec !== undefined) await exec('/chapters-prompt off-session'); dispatch({ t: 'off' }); if (sessionId !== undefined) { const offEntry = { ev: { t: 'polled', status: 'off' } as CacheEntry['ev'], autorun: null, at: Date.now() }; stateCache.set(sessionId, offEntry); writePersisted(sessionId, offEntry) } })() },\n }),\n ),\n ),\n )\n}\n","/**\n * The chapters preset id — ONE source, client-safe.\n *\n * The literal 'chapters' had durable meaning in three places (the server's preset declaration, the\n * seventh archive moment's header gate, and the client's door visibility predicate per #372), and\n * #353 already caught a second literal copy drifting outside its predicate. `src/preset.ts` is the\n * declaration's home but imports cordis — the client bundle cannot load it — so the id lives HERE,\n * with zero imports, and preset.ts re-exports it so every existing server importer is unchanged.\n *\n * @module dsh-chapters/src/preset-id\n */\nexport const CHAPTERS_PRESET_ID = 'chapters'\n","/**\n * The client door runner: the two deterministic archive doors, executed over\n * `remote.commands` and followed by a SWITCH to the fresh child.\n *\n * ONE runner, two rows. The server side keeps the same discipline — both doors\n * come from `deterministicCommand(door)` in src/tools.ts, and a unit row pins\n * that they archive identically. Copy-pasting this body is how the two would\n * drift apart, so there is exactly one implementation and a table of rows.\n *\n * `chapters-continue` ships only as a composer command; without a button here\n * the child is created correctly and the UI shows nothing, which reads as\n * \"nothing happened\". The row is the missing affordance, not new logic.\n *\n * React-free on purpose: the primitives package pulls CSS modules the node\n * test runner cannot load, so the testable half lives here and index.ts is the\n * thin chrome that renders these rows as buttons (tests/unit/client-doors.test.ts).\n *\n * @module dsh-chapters/src/client/doors\n */\n\n/** Structural slice of the aggregated remote service (@deepseek-ai/dsh-api-remotes).\n * `remote.commands` must ALSO appear in inject — the federation gates each\n * sub-service individually (the live feedback package declares\n * remote.messageFeedback beside remote for exactly this reason). */\nimport { CHAPTERS_PRESET_ID } from '../preset-id.ts'\n\nexport interface ClientRemote {\n commands?: {\n execute(sessionId: string, line: string, attachments: readonly unknown[]): Promise<{\n ok?: boolean\n value?: { commandId?: string; result?: { kind?: string; text?: string } }\n error?: { code?: string; message?: string }\n }>\n }\n}\n\n/** The client sessions service (dsh-client-runtime): open() lives on the\n * prototype; everything else on the surface stays untrusted and unused. */\nexport interface ClientSessions {\n open(sessionId: string): unknown\n}\n\nexport interface DoorResult {\n ok: boolean\n message: string\n}\n\n/**\n * #372 — the host's OWN per-session preset fact. The shape is measured, not invented:\n * `dsh-client-ui-agent-preset/lib/client.js` resolves its label through\n * `session?.projectionValues?.agentPreset`, and `dsh-api-session-controller` documents the field as\n * \"current host-computed projection values retained by the object layer\". We read the SAME row the\n * list store already gives us (rosterIds' shape) — no inference, no hardcoded preset name.\n * null means the fact is NOT READABLE — which is UNKNOWN, never \"standard\" (#77's roster\n * discipline applied to the preset: absence invented from unreadability is the same lie).\n */\nexport function presetOfSession(sessions: ClientSessions | undefined, sessionId: string): string | null {\n try {\n const snap = (sessions as unknown as { list?: { getSnapshot?: () => unknown } } | undefined)?.list?.getSnapshot?.()\n const row = (snap as { byId?: Record<string, { projectionValues?: Record<string, unknown> }> } | undefined)?.byId?.[sessionId]\n const value = row?.projectionValues?.agentPreset\n return typeof value === 'string' && value !== '' ? value : null\n } catch { return null }\n}\n\n/**\n * The ONE visibility predicate for the realm-scoped door rows (#372). Unknown keeps the rows —\n * the click path answers with the named refusal, so fail-open is never fail-silent; a RESOLVED\n * foreign preset hides them, because those commands genuinely do not exist in that session.\n */\nexport function doorActionsVisibleFor(preset: string | null): boolean {\n return preset === null || preset === CHAPTERS_PRESET_ID\n}\n\n/**\n * One assistant-action row. `noun` is the server's own word for the child in\n * its success text (`branch` / `continuation`), so the fallback wording and the\n * title regex both track the door without a second implementation.\n */\nexport interface DoorAction {\n /** The slot registration id. */\n id: string\n /** Position in the assistant action row. */\n order: number\n /** Button + tooltip label, and the accessible name the e2e specs select on. */\n label: string\n /** The host command this row executes — the ONLY semantic difference at runtime. */\n command: string\n /** The noun in `${noun} “title” is session ch-…`. */\n noun: string\n /** The row's glyph (16×16 viewBox, single path). */\n iconPath: string\n}\n\nexport const DOOR_ACTIONS: readonly DoorAction[] = [\n {\n id: 'chapters-fork',\n order: 30,\n label: 'Fork with chapters',\n command: '/chapters-fork',\n noun: 'branch',\n iconPath: 'M5 3.25a2.25 2.25 0 1 0-1.5 2.12v5.26a2.25 2.25 0 1 0 1.5 0V9h5a2.25 2.25 0 0 0 2.25-2.25v-1.4a2.25 2.25 0 1 0-1.5 0v1.4A.75.75 0 0 1 10 7.5H5V5.37A2.25 2.25 0 0 0 5 3.25Z',\n },\n {\n id: 'chapters-continue',\n order: 31,\n label: 'Continue with chapters',\n command: '/chapters-continue',\n noun: 'continuation',\n iconPath: 'M1 8a.75.75 0 0 1 0-1.5h9.44L7.72 3.28a.75.75 0 1 1 1.06-1.06l3.5 3.5.53.53-.53.53-3.5 3.5a.75.75 0 1 1-1.06-1.06L10.44 9.5H1Zm13-5.25v10.5a.75.75 0 0 1-1.5 0v-10.5a.75.75 0 0 1 1.5 0Z',\n },\n]\n\n/** Pull the child id out of either door's durable success text — both end in\n * `… is session ch-…` (src/tools.ts), so this regex is door-agnostic. */\n/**\n * Which build of THIS file produced a door note (#77). When the live probe reported a roster\n * trace of `missing → missing → missing` — meaning adoption should have fired three times — while\n * showing no adoption outcome at all, the first question stopped being \"why did the client refuse\"\n * and became \"did the browser run the code I am reading?\". A note that names its own build makes\n * that a glance instead of an archaeology session into symlinked plugin trees.\n */\nexport const DOOR_BUILD = '2026-10-22T23:55 door-build-stamp'\n\nexport const CHILD_ID = /is session (ch-[\\w-]+)/\n\n/** The quoted title the door gave the child, matched by its OWN noun so a\n * refusal or an unrelated quote cannot pass for it. */\nexport const doorTitle = (noun: string): RegExp => new RegExp(`${noun} \\\\u201C([^\\\\u201D]+)\\\\u201D is session`)\n\n/**\n * A refusal reason that can never render as nothing. `String(err.message ?? err)` is `''` for a\n * host error built with an empty message, and an empty reason disappears from the note — the\n * reader then concludes \"no refusal happened\", which is the opposite of the truth (#77).\n */\nfunction refusalReason(error: unknown): string {\n const raw = error instanceof Error ? error.message : String(error)\n const trimmed = raw.trim()\n const named = trimmed === '' ? (error instanceof Error && error.name.trim() !== '' ? error.name : '') : trimmed\n const base = named === '' ? (error === null ? 'null thrown' : typeof error) : named\n return base.replace(/\\s+/g, ' ').slice(0, 90)\n}\n\n/**\n * Is the child in the client's OWN roster? This is the question that separates two very\n * different failures, and the door used to report the symptom without it:\n * - the client never learned the session exists (roster: missing) → the fix is server-side\n * publication, and no amount of clicking `open` will ever work;\n * - the client knows it and `open` still did nothing (roster: contains) → a navigation bug.\n * Measured host 0.2.0-rc.2: the sessions service exposes `projectList`, `refresh`, `retain`,\n * `handleSessionAdded` — the roster is a projection the client fills from control frames.\n */\n/**\n * The client's own session ids, or `null` when the store cannot be read. ONE reader for both\n * the note and the adoption decision, so the door never acts on a verdict it did not report.\n */\nfunction rosterIds(sessions: ClientSessions | undefined): Set<string> | null {\n const store = (sessions as unknown as { list?: { getSnapshot?: () => unknown } })?.list\n if (typeof store?.getSnapshot !== 'function') return null\n const snap = store.getSnapshot()\n const ids = new Set<string>()\n if (Array.isArray((snap as { ids?: unknown[] } | undefined)?.ids)) {\n for (const id of (snap as { ids: unknown[] }).ids) ids.add(String(id))\n } else if ((snap as { byId?: object } | undefined)?.byId !== undefined) {\n for (const k of Object.keys((snap as { byId: object }).byId)) ids.add(k)\n } else return null\n return ids\n}\n\nfunction rosterNote(sessions: ClientSessions | undefined, child: string): string {\n try {\n // The host's client store shape is `list.getSnapshot() → { ids, byId, phase }`.\n // `projectList()` turned out to be a MUTATOR that returns undefined (measured), so the first\n // version of this note printed \"0 sessions\" about a conversation that visibly had one — the\n // repo's own `listEvents` lesson (\"measure the SHAPE, not the presence\"), repeated by me in\n // the same week. Read the store; when it isn't reachable, presence is UNKNOWN and the note\n // says that rather than inventing an absence.\n const ids = rosterIds(sessions)\n if (ids === null) {\n const store = (sessions as unknown as { list?: { getSnapshot?: () => unknown } })?.list\n const shape = typeof store?.getSnapshot !== 'function' ? 'no list store on the service' : 'snapshot unreadable'\n return ` (roster: ${shape} — presence of ${child.slice(0, 11)}… is UNKNOWN, not absent)`\n }\n if (ids.size === 0) return ` (roster: empty — presence of ${child.slice(0, 11)}… is UNKNOWN, not absent)`\n const n = ids.size\n return ids.has(child)\n ? ` (roster: contains ${child.slice(0, 11)}…, ${String(n)} sessions — open() is the failure)`\n : ` (roster: MISSING, ${String(n)} sessions — the client never catalogued this session)`\n } catch { return '' }\n}\n\n/** The service's own method names, as a hint attached to a failure note (never a guess). */\nfunction verbsNote(sessions: ClientSessions | undefined): string {\n try {\n const svc = sessions as unknown as Record<string, unknown> | undefined\n if (svc === null || svc === undefined || typeof svc !== 'object') return ' (sessions service: absent)'\n // Measured: `Object.keys(svc)` returned NOTHING for the real service, because the host\n // puts its verbs on the PROTOTYPE (a class instance), not as own keys. A diagnostic that\n // reports \"no methods\" about a working service is worse than none — walk the chain.\n const found = new Set<string>()\n let node: unknown = svc\n // Stop at Object.prototype: its four legacy accessors are not service verbs, and listing\n // them pushed the real names past the cap on the first live run.\n for (let depth = 0; depth < 6 && node !== null && node !== undefined && node !== Object.prototype; depth++) {\n for (const key of Object.getOwnPropertyNames(node as object)) {\n if (key === 'constructor') continue\n try { if (typeof (svc as Record<string, unknown>)[key] === 'function') found.add(key) } catch { /* getter that throws — not a verb we can use either */ }\n }\n node = Object.getPrototypeOf(node)\n }\n const verbs = [...found].sort().slice(0, 24)\n return verbs.length === 0 ? ' (sessions service: no methods on the chain)' : ` (sessions verbs: ${verbs.join(', ')})`\n } catch { return ' (sessions service: unreadable)' }\n}\n\nfunction openByService(\n sessions: ClientSessions | undefined,\n sessionId: string,\n /** #77: adopt (and re-project) only when the client's own roster is missing this session.\n * `onAfter` reports the roster at the instant after adoption, before any later refresh can\n * discard the mutation — the difference between an ordering bug and a publication gap. */\n adopt?: { needed: boolean, onRefused: (reason: string) => void, onSubscribeRefused?: (reason: string) => void, onAfter: (seen: boolean | null) => void, onStep?: (step: string) => void },\n nav?: { openSession?: (id: string) => unknown },\n): Promise<boolean> {\n return (async () => {\n const svc = sessions as unknown as {\n open?: (id: string) => unknown; refresh?: () => unknown; projectList?: () => unknown\n create?: (opts: { sessionId?: string }) => unknown\n using?: (id: string, opts: { source: string }, fn: () => Promise<void>) => unknown\n } | undefined\n // #77, the actual root cause: `sessions.open` DOES NOT EXIST on this host. The sessions\n // service offers create/fork/using/retain/binding/refresh; the host's own fork button calls\n // `ctx.uiWorkspace.openSession(childId)` (`dsh-client-ui-chat/lib/client.js`). The line here\n // used to be `if (typeof svc?.open !== 'function') return false`, so every service attempt\n // since the door was written returned false on line one and the note blamed the client's\n // roster for a verb that was never there.\n if (svc === undefined) return false\n const navigate = typeof nav?.openSession === 'function'\n ? (id: string): unknown => nav.openSession!(id)\n : typeof svc?.open === 'function'\n ? (id: string): unknown => svc.open!(id)\n : null\n if (navigate === null) {\n adopt?.onStep?.('no-verb')\n return false\n }\n try { await svc.refresh?.() } catch { /* refresh best-effort */ }\n // #57: re-project the client's session catalog. The host does this ITSELF after every\n // create and fork — `dsh-api-session-controller/lib/client.js`, `create()` and `fork()`\n // both end in `this.projectList()` — because a session the client has never catalogued is\n // not addressable by `open()` no matter how often you call it. A plugin-created child is\n // exactly that case: durable, workspace-attached, absent from the client's roster. Measured\n // on 0.2.0-rc.2: without this the door created the child, `open` resolved, and the app\n // stayed on the parent (the door's own note now says `roster: …` so this is never a guess).\n try { svc.projectList?.() } catch { /* best-effort, like refresh */ }\n // #77: adopt-and-catalogue. `manager.create()` is documented \"on success merge into\n // summaries immediately (no wait for the next refresh)\" and forwards a caller-owned\n // `sessionId`, while the server ADOPTS a persisted id instead of authoring a second session\n // (`create(request)` → `ensureSession(sessionId, cwd, request.sessionId !== undefined, …)`).\n // Nothing about the child's content is authored here — the seed notice was committed\n // host-plane long before this call — this only lets the client see what the host already\n // knows. A refusal is reported to the caller, never swallowed.\n if (adopt?.needed === true && typeof svc.create === 'function') {\n // the block narrates itself: entry first, then whichever way it left. The live note once\n // said \"try\" from the runner and showed nothing downstream — with this line, an absent\n // `enter-create` IS the answer instead of a mystery.\n adopt.onStep?.('enter-create')\n try {\n await svc.create({ sessionId })\n adopt.onStep?.('settle-create')\n try { svc.projectList?.() } catch { /* re-project again, now that a mutation exists */ }\n // the momentary read is the whole point: a later `refreshList()` reassigns the manager's\n // mutations from the server result, so an adoption that DID land is invisible by the time\n // the last attempt fails. Report what was true at the instant it mattered.\n const after = rosterIds(sessions)\n adopt.onAfter?.(after === null ? null : after.has(sessionId))\n } catch (error) {\n adopt.onStep?.('refuse-create')\n adopt.onRefused(refusalReason(error))\n }\n }\n // #77, second candidate: if adoption left the child out of the roster, SUBSCRIBE to it.\n // `using(target, {source}, fn)` is the host's own way to address a session that is not\n // currently displayed (`sessions/service.js`: retain → `manager.get(id).open()`). A refusal is\n // reported exactly like adoption's. No URL route exists as an alternative — checked every\n // dsh-client-* bundle: the only `/session/` strings are resource addresses for files.\n if (adopt?.needed === true && typeof svc.using === 'function' && rosterIds(sessions)?.has(sessionId) === false) {\n adopt.onStep?.('enter-using')\n try {\n await svc.using(sessionId, { source: 'dsh-chapters-door' }, async () => undefined)\n adopt.onStep?.('settle-using')\n try { svc.projectList?.() } catch { /* best-effort, like the others */ }\n const seen = rosterIds(sessions)\n adopt.onAfter?.(seen === null ? null : seen.has(sessionId))\n } catch (error) {\n adopt.onStep?.('refuse-using')\n adopt.onSubscribeRefused?.(refusalReason(error))\n }\n }\n // The store must know the session before open() resolves it; a child\n // created seconds ago is only server-known until refresh lands. Retry\n // open briefly across that window.\n const started = Date.now()\n for (;;) {\n try { navigate(sessionId); return true } catch {\n if (Date.now() - started > 4_000) return false\n await new Promise((r) => setTimeout(r, 250))\n }\n }\n })()\n}\n\n/**\n * Fallback path: expand collapsed groups / show-more buttons, then click the\n * newest treeitem whose label contains the child title (newest-updated sorts\n * first, so the first match is the fresh child).\n */\nasync function openBranchRow(title: string, budgetMs = 4_000): Promise<boolean> {\n if (typeof document === 'undefined') return false\n const needle = title.toLowerCase()\n const tryClick = (): boolean => {\n const rows = Array.from(document.querySelectorAll<HTMLElement>('[role=\"treeitem\"]'))\n const hit = rows.find((row) => (row.textContent ?? '').toLowerCase().includes(needle))\n if (hit === undefined) return false\n hit.click()\n return true\n }\n const clickMore = (): number => {\n const buttons = Array.from(document.querySelectorAll<HTMLElement>('button'))\n .filter((b) => /more sessions|ungrouped/i.test(b.textContent ?? '') && b.getAttribute('aria-expanded') !== 'true')\n for (const b of buttons) b.click()\n return buttons.length\n }\n const started = Date.now()\n let expansions = 0\n while (Date.now() - started < budgetMs) {\n if (tryClick()) return true\n if (expansions < 4 && clickMore() > 0) { expansions += 1; await new Promise((r) => setTimeout(r, 250)); continue }\n await new Promise((resolve) => setTimeout(resolve, 150))\n }\n return tryClick()\n}\n\nexport function makeDoorRunner(\n remote: ClientRemote,\n sessions: ClientSessions | undefined,\n door: DoorAction,\n /**\n * \"Is THIS session the one the client is now showing?\" #54: `sessions.open()` returns\n * void, so a call that resolves proves the request was accepted, not that the app\n * switched. Measured on host 0.2.0-rc.2: no note element (open resolved), yet\n * `dsh.sessions.current` still named the parent and the child was absent from the\n * sidebar after a full reload — the user got silence and a missing session. Absent\n * (a client that cannot answer) the runner keeps the old behavior, and the wiring is\n * pinned by a row so production can never quietly drop it.\n */\n verifySwitched?: (childSessionId: string) => Promise<boolean>,\n /**\n * #77: how many times to re-pull the client's list, re-project and re-open. The session\n * manager documents `refreshList()` as \"single-flight within one Host generation\"\n * (`dsh-api-session-controller/lib/types/client/sessions/manager.js`), so a pull issued while\n * another is in flight can resolve from the STALE result — precisely the moment a session\n * created microseconds ago is missing. Retrying is both the fix candidate and the measurement:\n * which attempt lands tells us whether this is ordering (ours) or silence (host-side).\n * A client with no `refresh` verb gets exactly ONE attempt — re-asking `open` against a roster\n * we cannot re-pull would be theater.\n */\n opts?: { attempts?: number, attemptPauseMs?: number, navigator?: { openSession?: (id: string) => unknown } },\n): (sessionId: string, anchorSeq?: number | null) => Promise<DoorResult> {\n return async function run(sessionId: string, anchorSeq?: number | null): Promise<DoorResult> {\n try {\n if (remote.commands?.execute === undefined) return { ok: false, message: 'commands remote unavailable' }\n // #372: the gate runs BEFORE any wire call. A realm-scoped command asked of a session whose\n // preset RESOLVES to something else cannot resolve — answering with the host fact the dock\n // already reads is honest; firing into a guaranteed mystery is the dead button this issue was\n // filed for. UNKNOWN preset falls through: the named failure below still covers the wire.\n {\n const preset = presetOfSession(sessions, sessionId)\n if (preset !== null && !doorActionsVisibleFor(preset)) {\n return { ok: false, message: `Chapters ${door.noun} needs the chapters preset realm — this session composes \"${preset}\". Switch this session's preset or run the door from a chapters session.`.slice(0, 140) }\n }\n }\n // #221: the clicked message's seq rides the command as its first token — the server anchors\n // the archive at the last completed turn AT OR BEFORE it. Absent ⇒ today's behavior (the end\n // of the session), byte-identical to the pre-#221 line.\n const line = typeof anchorSeq === 'number' && Number.isFinite(anchorSeq) ? `${door.command} ${String(Math.trunc(anchorSeq))}` : door.command\n const res = await remote.commands.execute(sessionId, line, [])\n if (res.ok !== true) return { ok: false, message: (res.error?.message ?? `the ${door.noun} failed — its command lives in the chapters preset realm`).slice(0, 90) }\n const result = res.value?.result\n const text = typeof result?.text === 'string' ? result.text : ''\n if (result?.kind !== 'success') return { ok: false, message: (text || `the ${door.noun} was refused — see the command result`).slice(0, 90) }\n const child = CHILD_ID.exec(text)?.[1]\n if (child === undefined) return { ok: true, message: `${door.noun} created — appearing in the sidebar` }\n const switchedOnce = async (): Promise<boolean> => {\n if (verifySwitched === undefined) return true\n try { return await verifySwitched(child) } catch { return false }\n }\n const canRepull = typeof (sessions as unknown as { refresh?: unknown } | undefined)?.refresh === 'function'\n const maxAttempts = canRepull ? (opts?.attempts ?? 3) : 1\n let tried = 0\n let adoptRefusal = ''\n let subscribeRefusal = ''\n // #77: what the roster reader answered AT EACH DECISION, not only at the end. The live\n // probe reported MISSING after three attempts while neither candidate fired, which can\n // only mean the reader disagreed with itself over time — and a note that says one number\n // cannot show that.\n const rosterTrace: string[] = []\n const steps: string[] = []\n let adoptSaw: boolean | null | undefined\n for (let i = 0; i < maxAttempts; i++) {\n tried += 1\n // decide adoption from the SAME reader the note reports, so the door never acts on a\n // verdict it did not tell the user about; an unreadable roster is not \"missing\"\n const ids = rosterIds(sessions)\n // Loaded-but-empty is a DECISION (the child is not there → try the sanctioned paths);\n // unreadable is UNKNOWN and must not invent a session (#77: the strict form here meant\n // neither candidate ever ran in the live probe, and its silence looked like a result).\n const needed = ids !== null && !ids.has(child)\n // `+c` / `+u` = the candidate verbs are present on the injected service AT THAT MOMENT.\n // Without this, a note that says the roster was missing while no adoption outcome appears\n // is uninterpretable: either the code never ran, or the service has no create to call.\n const svcShape = sessions as unknown as { create?: unknown, using?: unknown, open?: unknown } | undefined\n // +c create, +u using, +o sessions.open, +w workspace navigator — the exact predicates\n // the door branches on, so a note can be read instead of re-derived from source\n rosterTrace.push(`${ids === null ? 'unknown' : ids.size === 0 ? 'empty' : ids.has(child) ? 'has' : 'missing'}${typeof svcShape?.create === 'function' ? '+c' : '-c'}${typeof svcShape?.using === 'function' ? '+u' : '-u'}${typeof svcShape?.open === 'function' ? '+o' : '-o'}${typeof opts?.navigator?.openSession === 'function' ? '+w' : '-w'}`)\n if (await openByService(sessions, child, {\n needed,\n onRefused: (reason) => { adoptRefusal = reason },\n onSubscribeRefused: (reason) => { subscribeRefusal = reason },\n onAfter: (seen) => { adoptSaw = seen },\n onStep: (step) => { if (!steps.includes(step)) steps.push(step) },\n }, opts?.navigator) && await switchedOnce()) return { ok: true, message: '' }\n // #358: NO `.unref()` on an awaited pause. The continuation depends on this very timer, so\n // releasing it from the event loop's refcount lets Node exit with the promise unresolved — the\n // door call never returns at all. Observed as 21 of 28 rows in client-doors.test.ts cancelled\n // by \"Promise resolution is still pending but the event loop has already resolved\" whenever the\n // retry path is the only pending work (Node 22; CI on the pinned Node 24 does not hit it, which\n // is precisely how it survived — an unobserved hang is not an absent one).\n // Browsers are unaffected either way: `setTimeout` returns a number there and `.unref` does not\n // exist, so the optional call was always a no-op in the only environment this ships to. The\n // three other waits in this file already do it correctly without one.\n if (i + 1 < maxAttempts) await new Promise((r) => { setTimeout(r, opts?.attemptPauseMs ?? 300) })\n }\n // the service path did not take — the sidebar row is the same affordance a human uses\n const title = doorTitle(door.noun).exec(text)?.[1]\n if (title !== undefined && await openBranchRow(title) && await switchedOnce()) return { ok: true, message: '' }\n // #54: a child that is created but not shown is a DIFFERENT fact from one the user\n // has to open by hand, and the message must not blur them.\n // #56/#57: the note must be ACTIONABLE. \"the app did not switch\" is true and useless;\n // naming the verbs the injected service actually exposes turns one failure into the\n // diagnosis (is there a refresh/reload to call, or is `open` the only verb and the\n // omission server-side?). A detected failure that isn't delivered is the same bug.\n return verifySwitched === undefined\n ? { ok: true, message: `${door.noun} created — open it in the sidebar` }\n : { ok: true, message: `${door.noun} created — the app did not switch after ${String(tried)} attempt${tried === 1 ? '' : 's'}; open it from the sidebar [roster per attempt: ${rosterTrace.join(' → ')}] [tried: ${steps.length === 0 ? 'none' : steps.includes('no-verb') ? 'no open or openSession verb on any injected service' : steps.join(', ')}] (build: ${DOOR_BUILD})${adoptRefusal === '' ? '' : ` (adoption refused: ${adoptRefusal})`}${subscribeRefusal === '' ? '' : ` (subscribe refused: ${subscribeRefusal})`}${adoptSaw === undefined ? '' : ` (right after adopt: ${adoptSaw ? 'contains' : 'missing'} ${child.slice(0, 15)})`}${rosterNote(sessions, child)}${verbsNote(sessions)}` }\n } catch (error) {\n return { ok: false, message: String((error as Error)?.message ?? error).slice(0, 90) }\n }\n }\n}\n\n/**\n * Execute a host command line for one session and return its text, or '' when the command plane is\n * unavailable. The bar's `state` pull and `off` write ride this, because it is the ONE place the client\n * talks to the wire: the guard row \"there is no second runner body in the client chrome\" exists to keep\n * `index.ts` as registration chrome, and a duplicated `commands.execute` in two files is how a wire\n * behaviour drifts from its own test (#59's one-predicate rule, applied to the transport).\n */\nexport async function runCommandText(remote: ClientRemote | undefined, sessionId: string, line: string): Promise<string> {\n const exec = remote?.commands?.execute\n if (exec === undefined) return ''\n const res = await exec(sessionId, line, [])\n if (res.ok !== true) return ''\n return res.value?.result?.text ?? ''\n}\n","/**\n * #590: THE COMMAND REPLY ROW. The maintainer's directive: \"I really don't want to suffer this\n * problem again\" — a typed /chapters-* command whose reply the timeline refuses to show (#545:\n * the host's SURFACE_EVENT_TYPES excludes command events from any rebuilt timeline) used to mean\n * invisible work and a wasted investigation. The reply is ALWAYS in the durable journal — the\n * host records command/run + command/done pairs faithfully; only its renderer filters them. So\n * this row reads the journal through the host's OWN session.follow stream (the same wire the\n * chat projector consumes, BEFORE its surface filter), renders the newest exchange above the\n * composer, and updates from the stream's live frames — zero polling, zero litter, zero model\n * calls, and no server-side state invented for it.\n *\n * Suppression, stated not assumed: when the host DOES render the reply as a timeline card\n * (healthy live sessions), the row steps aside — it probes the document for the reply excerpt\n * before mounting its own, so a visible card and a dock row never duplicate.\n */\nimport { createElement as h, useEffect, useState, type ReactElement } from 'react'\n\n/** The newest command exchange, shaped for the row. */\nexport interface CommandReply {\n line: string\n kind: 'success' | 'error' | 'running' | string\n text: string\n seq: number\n}\n\nexport const EXCERPT_CHARS = 200\n\nexport function excerptOf(text: string): string {\n const flat = text.replace(/\\s+/g, ' ').trim()\n return flat.length > EXCERPT_CHARS ? `${flat.slice(0, EXCERPT_CHARS)}…` : flat\n}\n\n/**\n * Does the host already render this reply? The probe runs BEFORE the row mounts (once per new\n * exchange), so an excerpt found in the document is the host's card, not our own echo. Absent\n * document (tests, odd hosts) reads as \"not shown\" — fail-visible, never fail-silent.\n */\nexport function hostCardShowsReply(excerpt: string, doc?: { body?: { innerText?: string } } | undefined): boolean {\n if (excerpt === '') return false\n const text = doc?.body?.innerText\n if (typeof text !== 'string') return false\n return text.includes(excerpt.slice(0, 80))\n}\n\n/**\n * #590, the channel as MEASURED: the host's follow wire filters command events before the\n * browser (reload-leg evidence 2026-11-27: snapshot 27 records, 0 command events), so the row\n * reads the server's reply record instead — `chapters-reply last` through the exec channel the\n * bar already owns. Pulls are human-driven only, and every one is named:\n * - mount (the restart+resume case: reload answers 'what did my last command say?'),\n * - visibility return (tab away, tab back),\n * - composer submit: a /chapters line that was in the composer and is now empty means the\n * host just dispatched it — one pull follows. Bounded by human action, never ambient\n * (#229's drumbeat ban stands: zero timers, zero polls).\n */\nexport interface CommandReplyRow { line?: string; kind?: string; text?: string; at?: string }\n\nexport function parseReplyRow(raw: string): CommandReply | null {\n if (raw.trim() === '') return null\n try {\n const p = JSON.parse(raw) as CommandReplyRow\n if (typeof p.line !== 'string' || p.line === '') return null\n // seq: the record's own timestamp — dismissal and 'newest wins' both ride it.\n return { line: p.line, kind: p.kind ?? 'success', text: p.text ?? '', seq: Number.isFinite(Date.parse(p.at ?? '')) ? Date.parse(p.at ?? '') : 1 }\n } catch { return null }\n}\n\nconst composerTextOf = (): string => {\n try {\n const el = document.querySelector<HTMLElement>('[data-composer-input]')\n if (el === null) return ''\n return ('value' in el ? String((el as unknown as { value: string }).value ?? '') : (el.innerText ?? ''))\n } catch { return '' }\n}\n\nexport function subscribeReply(exec: (line: string) => Promise<string>, onReply: (r: CommandReply | null) => void): () => void {\n let closed = false\n const pullOnce = async (): Promise<boolean> => {\n try {\n const raw = await exec('/chapters-reply last')\n const parsed = parseReplyRow(raw)\n if (closed) return true\n console.info(`[client:chapters] command reply pull: ${String(raw.length)} chars, parsed=${String(parsed !== null)}`)\n if (parsed === null) return false\n onReply(parsed)\n return true\n } catch { return false /* transport hiccup: the retry ladder decides */ }\n }\n // The composer empties at DISPATCH time; the handler writes the record asynchronously after.\n // A single submit-triggered pull races its own answer and reads empty (measured in the reload\n // leg: record present in the registry, every pull 0 chars). So the submit pull retries —\n // bounded, human-triggered, stops at the first parse: four tries, 500ms apart, then it waits\n // for the next sanctioned moment. Not a drumbeat: a doorbell that stops ringing.\n const pull = async (retry = false): Promise<void> => {\n if (await pullOnce()) return\n if (!retry) return\n for (let i = 0; i < 4; i += 1) {\n await new Promise((res) => setTimeout(res, 500))\n if (closed || await pullOnce()) return\n }\n }\n void pull()\n const onVis = (): void => { try { if (document.visibilityState === 'visible') void pull() } catch { /* no document: mount pull already ran */ } }\n try { document.addEventListener('visibilitychange', onVis) } catch { /* headless test env */ }\n let prior = composerTextOf()\n let observer: MutationObserver | undefined\n let attachTimer: ReturnType<typeof setTimeout> | undefined\n const onComposerMutate = (): void => {\n const now = composerTextOf()\n if (/^\\s*\\/chapters[-a-z]*/i.test(prior) && now.trim() === '') { console.info('[client:chapters] command reply submit detected'); void pull(true) }\n prior = now\n }\n const attachComposer = (): boolean => {\n try {\n const el = document.querySelector('[data-composer-input]')\n if (el === null) return false\n observer = new MutationObserver(onComposerMutate)\n observer.observe(el, { childList: true, subtree: true, characterData: true, attributes: true })\n console.info('[client:chapters] command reply composer observer attached')\n return true\n } catch { return true } // no MutationObserver at all: mount + visibility pulls remain; stop retrying\n }\n // #429's mount-retry shape, DOM-side: the dock mounts BEFORE the composer hydrates, so the\n // first probe can find nothing — and an observer attached to nothing silently never fires\n // (measured in the reload leg 2026-11-27: mounted, no row). 8x2s of querySelector costs zero\n // wire nodes; #229's ban is on command drumbeats, not DOM lookups.\n if (!attachComposer()) {\n let attempts = 0\n const retry = (): void => {\n if (closed || attempts >= 8 || attachComposer()) return\n attempts += 1\n attachTimer = setTimeout(retry, 2_000)\n }\n attachTimer = setTimeout(retry, 2_000)\n }\n return () => {\n closed = true\n if (attachTimer !== undefined) clearTimeout(attachTimer)\n try { document.removeEventListener('visibilitychange', onVis) } catch { /* paired with the guarded add */ }\n observer?.disconnect()\n }\n}\n\nexport interface CommandReplyProps {\n exec: (line: string) => Promise<string>\n}\n\nexport function CommandReplyRow(props: CommandReplyProps): ReactElement | null {\n // ALL hooks first, unconditionally (#310's hook-order rule — the early returns below must\n // never change how many hooks ran).\n const [reply, setReply] = useState<CommandReply | null>(null)\n const [expanded, setExpanded] = useState(false)\n const [dismissedSeq, setDismissedSeq] = useState<number | null>(null)\n useEffect(() => {\n // #590 triage breadcrumb: registered -> mounted -> pulls. A row that never appears is one\n // of these links, and the console names which. Silent is the failure mode this feature\n // exists to end.\n console.info('[client:chapters] command reply row mounted')\n return subscribeReply(props.exec, setReply)\n }, [props.exec])\n const excerpt = reply === null || reply.kind === 'running' ? '' : excerptOf(reply.text)\n const [suppressed, setSuppressed] = useState(false)\n // The host rendered it — no duplicate row. Re-decided per exchange, so a later command still\n // gets its own answer.\n useEffect(() => {\n setExpanded(false)\n const sup = reply !== null && excerpt !== '' && hostCardShowsReply(excerpt, document)\n if (reply !== null) console.info(`[client:chapters] command reply render decision: seq=${String(reply.seq)} suppressed=${String(sup)}`)\n setSuppressed(sup)\n }, [reply?.seq, excerpt])\n if (reply === null || reply.seq === dismissedSeq) return null\n if (suppressed) return null\n const color = reply.kind === 'error' ? 'var(--color-danger, #d33)' : reply.kind === 'running' ? 'var(--color-warning, #b80)' : 'var(--color-fg-dimmed, #888)'\n return h(\n 'div',\n {\n 'data-chapters-reply': 'true',\n style: { display: 'flex', gap: 8, alignItems: 'center', fontSize: 12, padding: '4px 10px', borderLeft: `3px solid ${color}`, opacity: 0.92 },\n title: reply.kind === 'running' ? `${reply.line} — running` : `${reply.line} — ${reply.kind}`,\n onClick: () => { if (excerpt !== '') setExpanded((e) => !e) },\n },\n h('span', { style: { fontFamily: 'monospace', color } }, reply.kind === 'running' ? `> ${reply.line} …` : `> ${reply.line}`),\n excerpt === '' ? null : h(\n 'span',\n { style: { color: 'var(--color-fg, #ccc)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: expanded ? 'pre-wrap' : 'nowrap', maxWidth: '60ch', flex: 1 } },\n expanded ? reply.text : excerpt,\n ),\n h(\n 'button',\n {\n type: 'button',\n 'aria-label': 'Dismiss command reply',\n style: { marginLeft: 'auto', border: 'none', background: 'none', color, cursor: 'pointer' },\n onClick: (ev: { stopPropagation(): void }) => { ev.stopPropagation(); setDismissedSeq(reply.seq) },\n },\n '×',\n ),\n )\n}\n","/**\n * dsh-chapters client entry: the per-message door buttons.\n *\n * Registers the two deterministic archive doors into the assistant action row\n * (`conversation.chat.assistant-actions` — the slot the official feedback\n * package populates beside copy/branch). Clicking one executes its host\n * command — `/chapters-fork`, `/chapters-continue` — through `remote.commands`,\n * the exact wire the composer's input line rides, then SWITCHES the app to the\n * fresh child:\n *\n * 1. `sessions.open(child)` — the client sessions service carries open() on\n * its prototype (Playwright-verified against this host; a keys-dump alone\n * hid it, which is why an earlier round wrongly gave up on this path);\n * 2. fallback: click the child's sidebar row after expanding collapsed\n * groups (plugin children can render under collapsed 'Ungrouped' heads);\n * 3. last resort: an inline note — the child is durable either way.\n *\n * There is deliberately NO second implementation of door logic here: the\n * buttons are mouths for the host commands (watermark, segmentation, budget,\n * titles, refusal-with-numbers all server-side, all tested), and the runner\n * they share is `src/client/doors.ts` — one body, one row per door. The purity\n * gate in tsdown.client.config.ts keeps this file cross-plugin-free.\n *\n * @module dsh-chapters/src/client\n */\n\nimport { createElement as h, useCallback, useEffect, useRef, useState, type ReactElement } from 'react'\n// The host's own tooltip bubble — a platform module served by the loader table,\n// external like react. Every action in this row labels through it.\nimport { withTooltip, nativeTitle } from './tooltip.ts'\nimport { PromptDock } from './prompt-dock.ts'\nimport { DOOR_ACTIONS, doorActionsVisibleFor, makeDoorRunner, presetOfSession, runCommandText, type ClientRemote, type ClientSessions, type DoorAction, type DoorResult } from './doors.ts'\nimport { CommandReplyRow } from './command-reply.ts'\n\ninterface ClientSlots {\n inject(name: string, factory: () => unknown): void\n register(registration: Record<string, unknown>, component: unknown): unknown\n}\n\ninterface Ctx {\n slots: ClientSlots\n get(name: string): unknown\n}\n\n// #77: `uiWorkspace` is not optional in practice — it owns `openSession(target)`, the verb the\n// host's own fork button uses (`ctx.uiWorkspace.openSession(childId)` in dsh-client-ui-chat).\n// `sessions` has no `open` at all, so without this row the door has never had a way to switch.\nexport const inject = ['slots', 'remote', 'remote.commands', 'sessions', 'uiWorkspace'] as const\n\n/** Props composed by the slot framework: owner (`messageId`) + our injected verb. */\ninterface DoorActionProps {\n messageId: string\n run: () => Promise<DoorResult>\n /** #372: the factory evaluates the host preset projection at render; false hides the row. */\n visible?: () => boolean\n}\n\n/**\n * Style parity with the native IconActions row: rules copied verbatim from the\n * host's MessageIconActions module (`._xzv4MW_action` in dsh-client-ui-chat's\n * compiled client + the feedback package's :disabled) — same metrics, tokens,\n * hover. Update this string if the host restyles its action row. Both doors\n * share these metrics.\n *\n * The final rule hides the native branch action IN THE MESSAGE ROW only\n * (user-approved cosmetic decision, docs/architecture.md): built-in chrome, so\n * the selector is its accessible label scoped to action-row buttons; both\n * locale spellings covered. If the host rewords the label the button simply\n * reappears — fails open, visibly.\n */\nconst CSS = [\n '.dsh-chapters_forkAction{width:calc(28px + var(--dsh-content-font-delta,0px));height:calc(28px + var(--dsh-content-font-delta,0px));color:var(--dsw-alias-label-tertiary);cursor:pointer;background:0 0;border:none;border-radius:28px;justify-content:center;align-items:center;padding:6px;display:inline-flex}',\n '.dsh-chapters_forkAction svg{width:calc(15px + var(--dsh-content-font-delta,0px));height:calc(15px + var(--dsh-content-font-delta,0px))}',\n '.dsh-chapters_forkAction:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary)}',\n '.dsh-chapters_forkAction:disabled{cursor:default;opacity:.4}',\n '.dsh-chapters_forkNote{color:var(--dsw-alias-label-tertiary);padding-left:4px;font-size:13px;line-height:20px}',\n 'button[class*=\"_action\"][aria-label=\"Branch into a new conversation\"],button[class*=\"_action\"][aria-label=\"\\u5728\\u65b0\\u5bf9\\u8bdd\\u4e2d\\u5206\\u652f\"]{display:none !important}',\n].join('\\n')\nconst CSS_TAG_ID = 'dsh-chapters/assistant-action.css'\n\nfunction injectStyles(): void {\n try {\n if (typeof document === 'undefined' || document.querySelector(`style[data-plugin-css=${JSON.stringify(CSS_TAG_ID)}]`) !== null) return\n const tag = document.createElement('style')\n tag.dataset.plugin = 'dsh-chapters'\n tag.dataset.pluginCss = CSS_TAG_ID\n tag.textContent = CSS\n document.head.appendChild(tag)\n } catch { /* styling is cosmetic; the action still works without it */ }\n}\n\n/** One component body for every door row; only the label and glyph differ. */\nfunction makeDoorAction(door: DoorAction) {\n return function ChaptersDoorAction({ run, visible }: DoorActionProps) {\n // #372: a RESOLVED foreign preset renders nothing at all — the command cannot exist in this\n // session's realm, and a button that resolves to nothing was the defect. UNKNOWN keeps the row\n // (the runner answers with the named refusal): fail-open VISIBLY is the contract, never a\n // silent disappearance on a host whose projection has not arrived yet.\n if (visible !== undefined && !visible()) return null\n const [busy, setBusy] = useState(false)\n const [note, setNote] = useState<string | null>(null)\n const alive = useRef(true)\n useEffect(() => () => { alive.current = false }, [])\n const onClick = useCallback(() => {\n if (busy) return\n setBusy(true)\n setNote(null)\n void run().then((result) => {\n if (!alive.current) return\n setBusy(false)\n setNote(result.message === '' ? null : result.message)\n setTimeout(() => { if (alive.current) setNote(null) }, 8000)\n })\n }, [busy, run])\n const button = h('button', {\n type: 'button',\n 'aria-label': door.label,\n ...nativeTitle(door.label),\n disabled: busy,\n onClick,\n className: 'dsh-chapters_forkAction',\n },\n h('svg', { viewBox: '0 0 16 16', width: '15', height: '15', fill: 'currentColor', 'aria-hidden': 'true' },\n h('path', { d: door.iconPath })))\n return h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: '4px' } },\n withTooltip(door.label, button as ReactElement<Record<string, unknown>>),\n note !== null\n ? h('span', { className: 'dsh-chapters_forkNote' }, note)\n : null)\n }\n}\n\nexport function apply(ctx: Ctx): void {\n injectStyles()\n const slots = ctx.slots\n const remote = (ctx.get('remote') ?? {}) as ClientRemote\n let sessions: ClientSessions | undefined\n try { sessions = ctx.get('sessions') as ClientSessions | undefined } catch { sessions = undefined }\n // Defensive: a host that cannot provide the navigator must leave the door registering and\n // reporting its own limitation, not failing at boot.\n let uiWorkspace: { openSession?: (id: string) => unknown } | undefined\n try { uiWorkspace = ctx.get('uiWorkspace') as { openSession?: (id: string) => unknown } | undefined } catch { uiWorkspace = undefined }\n // No early return on missing descriptors: the buttons register regardless\n // and the click reports the gap. A missing button is worse than a button\n // that explains itself. Components and runners are built ONCE here — slot\n // factories may re-run, and a fresh component identity per call would\n // remount the row.\n // #54: the switch verifier. `dsh.sessions.current` is published by the host's own\n // dsh-client-ui-workspace (grep-confirmed, not folklore) — the same key the e2e specs\n // read to name a session exactly, which is the point: the door now checks the fact the\n // user would notice, not whether a void call threw.\n const currentSessionId = (): string | null => {\n try {\n const raw = window.localStorage.getItem('dsh.sessions.current')\n if (raw === null) return null\n const parsed = JSON.parse(raw) as { sessionId?: string } | null\n return parsed?.sessionId ?? null\n } catch { return null }\n }\n const rows = DOOR_ACTIONS.map((door) => ({\n door,\n run: makeDoorRunner(remote, sessions, door, async (child) => {\n for (let i = 0; i < 8; i++) {\n if (currentSessionId() === child) return true\n await new Promise((r) => setTimeout(r, 250))\n }\n return currentSessionId() === child\n }, { ...(uiWorkspace !== undefined ? { navigator: uiWorkspace } : {} ) }),\n component: makeDoorAction(door),\n }))\n // Boot-witness instrumentation (#194's 0.2.1 compatibility hunt made this permanent): the door\n // registration is a two-step dance with the host's slot runtime, and a silent drop at either step\n // is indistinguishable from \"the region renders nothing\" — three console lines make the difference\n // one page reload away. Same discipline as the dock's inputActions witness.\n console.info(`[client:chapters] injecting ${String(rows.length)} assistant-actions door(s)`)\n const disposeDoors = slots.inject('conversation.chat.assistant-actions', () => {\n const effects = rows.map(({ door, run, component }) => slots.register({\n name: 'conversation.chat.assistant-actions',\n id: door.id,\n // #194-compat probe: the host's own entries in this region (feedback, goal's dock sibling)\n // all carry `label`/`locale`; 0.2.1-rc.5 renders NOTHING for entries without a label while\n // 0.2.0-rc.2 rendered them fine. Declaring the label is contract-blessed on BOTH (\"Register\n // options are id, order, and label\" — docs/contract.md) and costs nothing.\n label: door.label,\n // #221: the framework hands the action row its OWNER props — `{ messageId }`, the uuid of the\n // assistant message under the buttons (measured in dsh-client-ui-chat TurnTailNodeView). The\n // door resolves that uuid to its durable seq through the plugin's own RPC and passes it as the\n // anchor, so clicking Continue on an earlier message archives through THAT message's turn, not\n // the end of the session. Resolution failure falls back to no-anchor (old behavior) and says so\n // in the note — a door that silently ignores which row you clicked is the bug being fixed.\n inject: (sessionId: string, owner?: { messageId?: string }) => ({\n // #372: the factory re-runs per session render, so visibility reads the host projection AT\n // RENDER — resolved-foreign hides the row entirely, unknown keeps it for the named refusal.\n visible: () => doorActionsVisibleFor(presetOfSession(sessions, sessionId)),\n run: async () => {\n let anchor: number | null = null\n const mid = typeof owner?.messageId === 'string' ? owner.messageId : ''\n if (mid !== '') {\n try {\n const out = await runCommandText(remote, sessionId, `/chapters-anchor ${mid}`)\n const n = Number.parseInt(out.trim(), 10)\n if (Number.isFinite(n) && n > 0) anchor = n\n } catch { /* fall back to unanchored — old behavior */ }\n }\n return run(sessionId, anchor)\n },\n }),\n }, component))\n console.info(`[client:chapters] door factory ran: ${String(effects.length)} register effect(s), types: ${effects.map((e) => typeof e).join(',')}`)\n return effects\n })\n console.info(`[client:chapters] assistant-actions inject returned ${typeof disposeDoors}`)\n slots.inject('conversation.input.dock', () => slots.register({\n name: 'conversation.input.dock',\n id: 'chapters-prompt',\n // Under every other dock entry and directly above the composer card: todo 0, goal 10, queue 20, and the\n // host sorts ascending by priority then order (measured in dsh-client-ui-slots).\n order: 30,\n inject: (sessionId: string) => ({\n // The bar is a mouth for the command plane, and the ONE wire body in `doors.ts` carries it: a plugin has\n // no declarable RPC namespace, so this pull transport is why the bar is push-shaped and pull-fed.\n exec: (line: string) => runCommandText(remote, sessionId, line),\n }),\n }, PromptDock))\n // #590: the command reply row. Mounted beside the prompt bar (order 31 = between the bar and\n // the composer, because the reply to what you JUST typed belongs closest to where you typed\n // it). Data is the host's raw session journal via follow — snapshot plus live event frames —\n // so the row needs no exec pulls, no timers, and no server state of its own; and it\n // suppresses itself whenever the host renders the card. The inject face 'remote.session' is\n // listed above because the federation gates every face (#372: naming remote alone was once\n // not enough — the list is the contract).\n const disposeReplyRow = slots.inject('conversation.input.dock', () => slots.register({\n name: 'conversation.input.dock',\n id: 'chapters-command-reply',\n order: 31,\n inject: (sessionId: string) => ({\n exec: (line: string) => runCommandText(remote, sessionId, line),\n }),\n }, CommandReplyRow))\n console.info(`[client:chapters] command reply row registered: ${typeof disposeReplyRow}`)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA8BA,SAAgB,gBAAgB,OAA8E;GAC5G,OAAO;IAAE;IAAO,MAAM;IAAU,QAAQ;IAAM,SAAS;GAAI;EAC7D;EAEA,IAAI;EAEJ,SAAgB,iBAAqC;GACnD,IAAI,aAAa,KAAA,GAAW,OAAO;GACnC,WAAW;GACX,IAAI;IACF,IAAI,OAAO,YAAY,YAAY;KAEjC,MAAM,IADM,QAAQ,uCACR,CAAC,EAAE;KACf,IAAI,OAAO,MAAM,cAAc,OAAO,MAAM,UAAU,WAAW;IACnE;GACF,QAAQ;IACN,WAAW;GACb;GACA,OAAO;EACT;;EAGA,SAAgB,YAAY,OAAe,OAA4D;GACrG,MAAM,IAAI,eAAe;GACzB,OAAO,MAAM,QAAA,GAAOA,MAAAA,cAAAA,CAAE,GAAG;IAAE,GAAG,gBAAgB,KAAK;IAAG,UAAU;GAAM,CAAC,IAAI;EAC7E;;EAGA,SAAgB,YAAY,OAA0D;GACpF,OAAO,eAAe,MAAM,OAAO,EAAE,OAAO,MAAM,IAAI,CAAC;EACzD;;;;;;;;ECtDA,MAAa,wBAAwB;;EC8CrC,SAAgB,gBAAgB,UAA4B,YAA4B;GACtF,OAAO;IAAE,QAAQ;IAAO,MAAM;IAAM,SAAS;IAAM,OAAO;IAAM,MAAM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,OAAO,iCAAiC,MAAM,SAAS;IAC3D,MAAM;IACN,IAAI;IAGJ,OAAO;IACP,SAAS,eAAuB,EAG9B,OAAO,SAAiB,eAAe,QAAQ,WAAW,IAAI,EAChE;GACF,GAAG,UAAU,CAAC;GAQd,MAAM,kBAAkB,MAAM,OAAO,iCAAiC,MAAM,SAAS;IACnF,MAAM;IACN,IAAI;IACJ,OAAO;IACP,SAAS,eAAuB,EAC9B,OAAO,SAAiB,eAAe,QAAQ,WAAW,IAAI,EAChE;GACF,GAAG,eAAe,CAAC;GACnB,QAAQ,KAAK,mDAAmD,OAAO,iBAAiB;EAC1F"}
|
|
1
|
+
{"version":3,"file":"client.js","names":["h","CSS","h","useReducer","useRef","useState","useCallback","useState","useRef","useCallback","h"],"sources":["../src/client/tooltip.ts","../src/prompt-keys.ts","../src/client/prompt-bar.ts","../src/client/prompt-dock.ts","../src/preset-id.ts","../src/client/doors.ts","../src/client/index.ts"],"sourcesContent":["/**\n * The host's Tooltip seat, resolved OPTIONALLY (#194-compat — measured on 0.2.1-rc.5, not guessed):\n *\n * `@deepseek-ai/dsh-client-ui-primitives` exists in the 0.2.0-rc.2 host tree and is ABSENT from the\n * entire 0.2.1-rc.5 install tree — no successor package exports `Tooltip`. Our bundle's static\n * import becomes a LAZY require in the built CJS: the bundle loads and components run, but the\n * first render that touches `Tooltip` throws, and React's error boundary swallows the subtree\n * silently. Measured symptoms on 0.2.1: door registration fully healthy (inject returned a\n * disposer; the factory ran; both register effects are functions) yet the assistant-actions region\n * renders ZERO entries, and the dock renders no row — because both wrap their buttons in Tooltip.\n *\n * The fix keeps one resolution point and one fallback (#59 — never per-component try/catch):\n * probe the module once; when it is absent, buttons carry the platform's own `title` tooltip, so\n * hover text survives on every host and the fancy tooltip survives where it exists.\n */\nimport { createElement as h, type ComponentType, type ReactElement } from 'react'\n\ndeclare const require: ((id: string) => Record<string, unknown>) | undefined\n\nexport type TooltipLike = ComponentType<{ label: string; side?: string; portal?: boolean; delayMs?: number; children: ReactElement<Record<string, unknown>> }>\n\n/**\n * The tooltip recipe, field for field the goal bar's own (GoalBar.tsx:101-142: `portal`,\n * `side=\"bottom\"`, `delayMs={500}`) — the shipped occupant of the same dock strip, whose tooltips\n * are NOT covered by the composer. `portal` is the load-bearing one: it renders the popup at\n * document level instead of inside our dock's stacking context, which is exactly the maintainer's\n * report (#210: \"the hoverover tooltips are covered by the main chat input container\"). Our old\n * compile-time types rejected portal/delayMs at the overload; the runtime host always accepted\n * them, and since the seat is typed by us, the recipe is pinned by a row instead of by luck.\n */\nexport function tooltipPropsFor(label: string): { label: string; side: 'bottom'; portal: true; delayMs: 500 } {\n return { label, side: 'bottom', portal: true, delayMs: 500 }\n}\n\nlet resolved: TooltipLike | null | undefined // undefined = not probed yet\n\nexport function resolveTooltip(): TooltipLike | null {\n if (resolved !== undefined) return resolved\n resolved = null\n try {\n if (typeof require === 'function') {\n const mod = require('@deepseek-ai/dsh-client-ui-primitives') as { Tooltip?: unknown } | undefined\n const T = mod?.Tooltip\n if (typeof T === 'function' || typeof T === 'object') resolved = T as TooltipLike\n }\n } catch {\n resolved = null // absent host: the native-title fallback stands\n }\n return resolved\n}\n\n/** Wrap in the host Tooltip when it exists; otherwise return the child (which must carry `title`). */\nexport function withTooltip(label: string, child: ReactElement<Record<string, unknown>>): ReactElement {\n const T = resolveTooltip()\n return T !== null ? h(T, { ...tooltipPropsFor(label), children: child }) : child\n}\n\n/** The native-tooltip attribute, present ONLY when the host seat is absent — no double tooltips. */\nexport function nativeTitle(label: string): { title: string } | Record<string, never> {\n return resolveTooltip() === null ? { title: label } : {}\n}\n","/**\n * Identifiers shared by BOTH planes of the push transport (#194). One module, one spelling: the\n * server registers the projection under this key and the client reads `useProjection(key)` — two\n * literals in two planes would be exactly the drift #59 forbids. No node imports (the client\n * compiles this), no DOM (the server imports this).\n */\nexport const PROMPT_PROJECTION_KEY = 'chaptersPrompt'\n","/**\n * The Suggested Next Step bar — every decision the row makes, kept out of React (#113).\n *\n * Deliberately shaped like the goal bar, because that implementation is tested, already fits, and gets the\n * split right: the **durable** facts (`status`, `text`, `turnSeq` — the server's one-generation-per-turn\n * identity) versus the **process-local** intent (`autorun`, `expanded` — the goal's `activation` in\n * everything but name). Nothing transient is persisted, and nothing persisted is guessed here.\n *\n * The failures the maintainer rejected are all decision bugs, not rendering bugs: firing while a turn is\n * running, shouting a refusal that should have been silence, an autorun that outlives the purpose that\n * justified it. Each has a row in `tests/unit/prompt-bar.test.ts`.\n */\n\nexport type PromptBarStatus = 'off' | 'idle' | 'analyzing' | 'ready' | 'failed'\nexport type PromptBarAutorun = 'armed' | 'disarmed'\n/** Mirrors the host's `GoalPhase` vocabulary (`dsh-goal` types) so goal composition needs no translation. */\nexport type GoalPhaseView = 'none' | 'active' | 'paused' | 'blocked' | 'complete'\n\nexport interface PromptBarState {\n status: PromptBarStatus\n /** The offer, verbatim. Never truncated — an over-cap answer is refused upstream. */\n text: string | null\n /** #113: what kind of step the server classified this as. `goal-edit` is held for the human's keystroke,\n * because goal edits require a direct human turn in the host and an autorun message is not one. */\n intent: 'worker-step' | 'goal-edit'\n /** The `turn/end` seq this offer belongs to; its identity, not a timestamp. */\n turnSeq: number | null\n /** Set only with `status: 'failed'`; rendered as `role=\"alert\"` (#61: delivered, not swallowed). */\n error: string | null\n /** Why an action did not happen, on the bar's face (#113). Empty when there is nothing to explain. */\n note: string\n autorun: PromptBarAutorun\n expanded: boolean\n running: boolean\n goalPhase: GoalPhaseView\n /** The offer a human dismissed or interrupted. A NEW `turnSeq` clears it; this one stays hidden. */\n hiddenTurnSeq: number | null\n /** Live goal facts, when the caller can read them (the goal driver owns the next turn when active+armed). */\n goal: { phase: string; activation: string; revision: number } | null\n}\n\nexport type PromptBarEvent =\n | { t: 'polled', status: PromptBarStatus, text?: string | null, turnSeq?: number | null, error?: string | null, intent?: 'worker-step' | 'goal-edit' }\n | { t: 'expand' } | { t: 'collapse' }\n /** Why an action did not happen, on the bar's own face (#113). Cleared when a new offer lands. */\n | { t: 'note'; note: string }\n | { t: 'autorun', on: boolean }\n | { t: 'human/prompt' }\n | { t: 'off' }\n | { t: 'goal', phase: GoalPhaseView }\n | { t: 'running', running: boolean }\n\nexport function initialBarState(autorun: PromptBarAutorun = 'disarmed'): PromptBarState {\n return { status: 'off', text: null, turnSeq: null, error: null, note: '', intent: 'worker-step', goalPhase: 'none', goal: null, autorun, expanded: false, running: false, hiddenTurnSeq: null }\n}\n\nexport function promptBarReducer(state: PromptBarState, ev: PromptBarEvent): PromptBarState {\n if (ev.t === 'note') return { ...state, note: ev.note }\n const next = baseBarReducer(state, ev)\n // A note is about the gesture that just failed, so a NEW offer retires it. A poll that repeats the same\n // offer (the bar re-reads every few seconds) does not — otherwise the explanation would blink out before\n // the human could read it.\n return ev.t === 'polled' && (next.turnSeq !== state.turnSeq || next.text !== state.text) ? { ...next, note: '' } : next\n}\n\nfunction baseBarReducer(state: PromptBarState, ev: PromptBarEvent): PromptBarState {\n switch (ev.t) {\n case 'polled': {\n // #285: the wire is the supreme authority on `running`. A local run-click folds `running: true`\n // honestly (the click authored the turn), but on hosts with no running edge (#221) nothing else\n // would ever retire that line — so any polled answer, whatever it carries, ends the local claim.\n // Wire-first, then the local fold: the order the #208/#221 lineage has always kept.\n if (ev.status === 'off') return { ...state, status: 'off', text: null, turnSeq: null, error: null, expanded: false, autorun: 'disarmed', running: false }\n // A fresh generation invalidates the previous offer: acting on a stale one is how a bar lies.\n if (ev.status === 'analyzing') return { ...state, status: 'analyzing', text: null, error: null, running: false }\n return {\n ...state,\n running: false,\n status: ev.status,\n text: ev.status === 'ready' ? (ev.text ?? null) : null,\n intent: ev.status === 'ready' ? (ev.intent ?? 'worker-step') : 'worker-step',\n turnSeq: ev.turnSeq ?? state.turnSeq,\n error: ev.status === 'failed' ? (ev.error ?? 'the suggestion call failed') : null,\n }\n }\n case 'expand': return { ...state, expanded: true }\n // Collapsing is a reading action. It keeps the offer — only a human prompt or `Off` dismisses it.\n case 'collapse': return { ...state, expanded: false }\n case 'autorun': return { ...state, autorun: ev.on ? 'armed' : 'disarmed' }\n // #282: a turn start makes every on-screen offer obsolete — Run could fire a stale step and the\n // human would watch the agent act on last cycle's question. The rising edge clears the offer,\n // collapses, and hands the row to the generic running line (barLabel/barVisible); the falling\n // edge shows nothing new — the post-turn pull lands the fresh state through the normal path.\n // Idempotent on repeats: same flag in, SAME object out — a re-delivered edge must not become\n // render-loop fuel. Unknown running folds as FALSE at the source (#221: unknown is not running).\n case 'running': {\n if (ev.running === state.running) return state\n return ev.running\n ? { ...state, running: true, text: null, error: null, expanded: false }\n : { ...state, running: false }\n }\n case 'human/prompt':\n // The human took the wheel: yield the loop, and drop the offer that was on screen. Generation itself\n // continues on the NEXT turn boundary — suspension is not disable.\n return { ...state, autorun: 'disarmed', hiddenTurnSeq: state.turnSeq, expanded: false }\n case 'off': return { ...state, status: 'off', text: null, turnSeq: null, error: null, expanded: false, autorun: 'disarmed' }\n case 'goal':\n // Per spec: autorun runs ALONGSIDE an active goal and disarms itself when the goal completes — the\n // suggestion loop exists to serve the session's purpose, and stops when that purpose stops.\n // #188: blocked joins complete — both planes stop together when the goal reaches a terminal\n // phase; a loop still firing offers at a blocked goal is the autorun that outlived its purpose.\n return { ...state, goalPhase: ev.phase, autorun: ev.phase === 'complete' || ev.phase === 'blocked' ? 'disarmed' : state.autorun }\n }\n // Exhaustive fallback: a new event without a case must return the state unchanged rather than\n // compile into `undefined` and blank the bar.\n return state\n}\n\n/** The status label. `failed` keeps the ready label so the error span is the delta, not a mystery row.\n * A goal-edit offer REPLACES the label text (#300): the row is one message tall, and the second-message\n * badge overflowed it and clipped the composer — so the protocol fact earns the slot or goes unsaid. */\nexport function barLabel(s: PromptBarState): string | null {\n // #282: running outranks everything shown — while the agent works, the bar says so and nothing\n // else. The wording is the §28 states-table row, kept identical (one predicate per decision, #59).\n if (s.running) return 'Agent is running — a fresh suggestion lands when the turn ends'\n if (s.status === 'analyzing') return 'Analyzing situation…'\n if (s.intent === 'goal-edit' && (s.status === 'ready' || s.status === 'failed')) return 'Goal edit — run it yourself'\n if (s.status === 'ready' || s.status === 'failed') return 'Recommended Next Step'\n return null\n}\n\n/**\n * #309: the row button's one sentence, as a pure function of what the click would DO —\n * collapsed invites the reading; expanded-into-an-empty-composer invites the handoff;\n * expanded-with-the-user-typing names the precondition instead of lying about the gesture.\n * One predicate per decision (#59): aria-label and the tooltip render this same string.\n */\nexport function rowTooltip(expanded: boolean, composerHasText: boolean): string {\n if (!expanded) return 'Click to expand the full suggested prompt'\n return composerHasText ? 'Clear existing prompt to send this prompt to chat input'\n : 'Click to send this prompt to the chat input for editing'\n}\n\n/**\n * #193: the pull cadence, as a decision instead of an interval constant. Every pull is two recorded\n * host lifecycle events (`command/run` + `command/done`) the UI renders as history nodes — cadence\n * IS the litter, so it belongs in this module with a row for every arm. Active = the state can\n * plausibly change on a short clock (generation in flight, an armed loop to fire, a turn running\n * that will end into an offer). Quiet = stable; one pull a minute is plenty for a state that only\n * changes at turn boundaries. Hidden-and-quiet = pull NOTHING (a background tab should write zero\n * history); hidden-and-active still pulls, because walking away from a running loop is the point of\n * autorun and pausing it silently would be the loop dying with nobody told.\n */\nexport const ACTIVE_POLL_MS = 10_000\n/**\n * #229: the quiet heartbeat is CONFIG-GATED (`promptQuietHeartbeatSec`) and defaults to ZERO.\n * Measured on the maintainer's live log after 0.2.11 installed correctly (gaps exactly 60.0s): every\n * pull is two durable nodes — a host `command/run` + `command/done` pair — and the user's rule is\n * absolute: never repeated chapters-prompt executions. The sanctioned moments (mount discovery once\n * per page load, the turn-end pulse, visibility return with an untrusted cache, forced confirms)\n * remain; the ambient drumbeat does not exist unless configured. This module is client-safe (no node\n * builtins), so the wiring injects the config value at boot via `configureQuietHeartbeat`.\n */\nexport let QUIET_POLL_MS = 0\nexport function configureQuietHeartbeat(seconds: number | undefined): void {\n QUIET_POLL_MS = typeof seconds === 'number' && Number.isFinite(seconds) && seconds > 0 ? Math.trunc(seconds * 1000) : 0\n}\n\n/**\n * #304: the analyzing belt backs off 10s → 20s → 40s → 60s (cap) while a generation is in\n * flight and nobody is armed. The first wait stays eager (short generations — every rig leg —\n * land in the old 10s rhythm); long and zombie generations stop paying 2 history nodes per\n * poll. The ARMED loop ignores the belt entirely: a stalled round is worse than any cadence.\n * streak counts consecutive analyzing OBSERVATIONS (undefined/0 = eager).\n */\nfunction analyzingBeltMs(streak: number | undefined): number {\n const n = streak === undefined || streak < 1 ? 0 : Math.min(streak, 3)\n return n === 0 ? ACTIVE_POLL_MS : n === 1 ? 20_000 : n === 2 ? 40_000 : 60_000\n}\n\n/** #429: attempts the mount may make before it gives up LOUDLY. Sized to the measured window:\n * loaded boots hydrate the composer's exec verb AFTER the dock's first effect (the two chain-context\n * failures vs 12 solo passes at the same head); 8x2s outlasts that without approaching any ceiling\n * that matters, and each attempt is COST-FREE until exec exists (refresh() still early-returns with\n * zero wire nodes) — the paid pulls begin only when the wire can answer. */\nexport const FIRST_PULL_RETRY_CEILING = 8\nexport const FIRST_PULL_RETRY_SPACING_MS = 2_000\n\n/**\n * THE ONE first-pull retry predicate (#429). The dock's mount pull no-ops silently while the host\n * has not yet handed `exec` — before #429 the retry lived only in two comments (the ceiling promise\n * above execWithTimeout, and 'retry until SOMETHING answers' in the mount effect) with no code\n * behind it, which is how the revival leg's mount pull could starve under boot load while solo\n * boots passed 10/10. The loop is due ONLY while no reply has arrived — any parseable answer, an\n * honest `off` included (#304's seam claim is THAT the wire answered, never that the feature is\n * on), the feature plane is present, and the ceiling has room.\n */\nexport function firstPullRetryDue(c: { answered: boolean, featureAbsent: boolean, attempts: number, owed: boolean, pushLive: boolean }): boolean {\n if (c.answered || c.featureAbsent) return false\n // #497 (third writer, finally named): the maintainer's reload pair at 2026-11-24T11:27:06Z was\n // NOT the mount tick — it was this retry. The mount tick correctly stayed silent (push mode),\n // but `answered` flips only on a WIRE reply, so the loop pulled `state` every 2s until exec\n // hydrated: a self-inflicted load-time pair on the exact hosts the #194 gate exists to protect.\n // Two truths the predicate now requires: the mount actually SANCTIONED a pull (owed) — silence\n // by design owes nothing — and the projection is NOT live (pushLive): a cell that answers is an\n // answer; retrying against it is the drumbeat the maintainer's rule forbids.\n if (c.pushLive || !c.owed) return false\n return c.attempts < FIRST_PULL_RETRY_CEILING\n}\n\nexport function pollSpacingFor(s: { status: PromptBarStatus; autorun: PromptBarAutorun; running: boolean; hidden: boolean; edges: boolean; turnEndPulse?: boolean; analyzingStreak?: number | undefined }): number | null {\n // #203: where the host publishes the running signal, the idle EDGE is the schedule — a turn ending\n // pulls, the bar's own actions pull, and a stable disarmed bar keeps NO clock at all, because a\n // timer there could only re-read truth into rendered history nodes. Analyzing stays on the fast\n // belt (a generation completing fires no edge), and an armed loop keeps it too (a missed edge must\n // not stall autorun). Hosts that publish no running prop get the #193 cadence, unchanged.\n // #221: a turn-end pulse from the host projection deserves an immediate follow-up — the offer\n // was just born. Applies in BOTH modes; it is the sanctioned moment, not a clock.\n if (s.turnEndPulse === true) return ACTIVE_POLL_MS\n if (s.edges) {\n if (s.autorun === 'armed') return ACTIVE_POLL_MS\n if (s.status === 'analyzing') return analyzingBeltMs(s.analyzingStreak)\n return null\n }\n // #221: unknown-running is UNKNOWN, not running. The maintainer's live host (0.2.0-rc.2) publishes\n // no usable running signal to docks; `running` defaulted to true and pinned this bar into the FAST\n // clock forever — measured 158 state pulls at exact 10.0s intervals across one session's log, even\n // while idle. Only two states justify a fast clock: generation in flight (analyzing) and an armed\n // loop that must see offers promptly. A KNOWN running turn (edges=false hosts that do supply the\n // signal... which by definition have edges=true) never needed the clock either way. So: analyzing\n // or armed ⇒ fast; otherwise quiet, hidden-quiet ⇒ silent.\n const active = s.status === 'analyzing' || s.autorun === 'armed'\n if (!active && s.hidden) return null\n if (!active) return QUIET_POLL_MS > 0 ? QUIET_POLL_MS : null\n // #304: armed keeps the 10s; analyzing alone rides the back-off (the 158-pull lesson was\n // about FOREVER; a real 90s generation deserves 3 polls, not 9).\n if (s.autorun === 'armed') return ACTIVE_POLL_MS\n return analyzingBeltMs(s.analyzingStreak)\n}\n\n/**\n * #203: whether a freshly mounted bar pulls, or renders its cache and stays silent. The maintainer's\n * rule: generate or read AFTER THE TURN ENDS, never when you activate a session. So a mount pulls\n * only when the cache cannot be trusted — absent (first mount after a page load), stale (a turn\n * could have ended since; this guarded pull is what keeps Run honest, because clicking a stale\n * offer would submit the row's newer text while showing the old), mid-generation, or armed. A\n * cached `off` never pulls WITHIN THE PAGE THAT SAW IT: off is a human/config switch, and only an\n * explicit `on` revisits it. #272 makes the page the discriminator the mirror erased — an off\n * RESTORED from localStorage after a reload was never observed by this page, and the reload pull\n * is the revival promise the enabling commands make, so disk-restored off pays it.\n */\nexport function mountPullDecision(c: { hasCache: boolean; ageMs: number; status: PromptBarStatus; autorun: PromptBarAutorun; cacheFromDisk?: boolean | undefined }): boolean {\n if (!c.hasCache) return true\n // #208, the maintainer's rule — NOT RELEVANT, NOT VISIBLE: `off` is terminal for the page\n // lifetime. The #203 staleness-revival arm cost one visible history node per reactivation of a\n // known-off session, for a feature that is not on; revival is a page reload, and the commands\n // that re-enable (`model`, `on`) say so in their replies. #251 then persisted the cache to disk,\n // which silently un-wrote that sentence — every reload restored the veto. The `cacheFromDisk`\n // input restores it exactly: an off THIS page observed stays terminal; an off carried across a\n // reload pulls once, and the server's answer (off stays hidden; idle/ready renders) decides.\n if (c.status === 'off') return c.cacheFromDisk === true\n if (c.autorun === 'armed' || c.status === 'analyzing') return true\n // #229: with no heartbeat configured, staleness alone never pulls — a tab left open for ten\n // minutes must not resurrect the drumbeat through the mount path. Freshness returns via the\n // turn-end pulse, visibility edges, and the confirm arms, all of which are real events.\n return QUIET_POLL_MS > 0 && c.ageMs > QUIET_POLL_MS\n}\n\n/**\n * #203: fold a cached wire event back into row state through the SAME reducer the live path uses —\n * one fold, no second implementation to drift (the #59 rule).\n */\nexport function stateFromCache(ev: PromptBarEvent, autorun: PromptBarAutorun | null): PromptBarState {\n const folded = promptBarReducer(initialBarState(), ev)\n return autorun === null ? folded : promptBarReducer(folded, { t: 'autorun', on: autorun === 'armed' })\n}\n\nexport function barVisible(s: PromptBarState): boolean {\n // Only `off` hides the row. `idle` is enabled-and-waiting, and showing it is the difference between\n // \"the feature is live, nothing to say yet\" and silence that reads as disabled (#113).\n if (s.status === 'off') return false\n // #282: the running line shows even with cleared text — the ready-empty rule below would otherwise\n // hide the bar exactly when it has the most important thing to say. `off` stays the first gate (#208).\n if (s.running) return true\n if (s.status === 'ready' && (s.text === null || s.text === '')) return false\n // The goal bar's `clearedGoalId` guard, in our terms: don't flicker back the offer just dismissed.\n if (s.hiddenTurnSeq !== null && s.hiddenTurnSeq === s.turnSeq) return false\n return true\n}\n\n/** May the bar submit its own offer? Armed, present, idle, not dismissed, and still serving a purpose. */\nexport function shouldAutoFire(s: PromptBarState): boolean {\n if (s.status !== 'ready') return false\n if (s.text === null || s.text === '') return false\n // #113: two host-imposed stops before anything else. A goal re-cut needs a human turn (dsh-tool-goal's\n // requireDirectHuman), and an armed goal driver already intends to start this turn — firing here would be\n // two turn-starters at one boundary, racing the driver's own reservation fence.\n if (s.intent === 'goal-edit') return false\n if (s.goal !== null && s.goal.phase === 'active' && s.goal.activation === 'armed') return false\n if (s.autorun !== 'armed') return false\n if (s.running) return false\n if (s.goalPhase === 'complete' || s.goalPhase === 'blocked') return false\n if (s.hiddenTurnSeq !== null && s.hiddenTurnSeq === s.turnSeq) return false\n return true\n}\n\n/** The command the bar pulls. One string, so the client and the command plane cannot drift silently. */\nexport const BAR_STATE_COMMAND = '/chapters-prompt state'\n/** The bar's Run button: the server submits the on-screen offer as the human's own turn. */\nexport const BAR_RUN_COMMAND = '/chapters-prompt run'\n\n/**\n * Parse the `state` verb's `k: v` lines into a pull event.\n *\n * One output serving the human and the component is the design (see `docs/contract.md`); this function is\n * the cost of that choice, and it is kept honest: an unrecognised line is IGNORED, not guessed at, and a\n * payload that yields no `status` is `null` so the caller keeps its last state rather than inventing `off`\n * (which would hide a bar that is merely mid-reply). Indentation and the prompt's own lines are the reason\n * the prompt is collected separately from the scalar fields — it is the only multi-line value.\n */\nexport function parseBarState(text: string): PromptBarEvent | null {\n const lines = text.split('\\n')\n const head = lines[0] ?? ''\n const statusWord = head.startsWith('suggested next step:') ? head.slice('suggested next step:'.length).trim() : ''\n const status = statusWord === 'off' ? 'off'\n : statusWord === 'idle' ? 'idle'\n : statusWord === 'analyzing' ? 'analyzing'\n : statusWord === 'ready' ? 'ready'\n : statusWord === 'failed' ? 'failed'\n : null\n if (status === null) return null\n const scalars: Record<string, string> = {}\n const prompt: string[] = []\n let inPrompt = false\n for (const line of lines.slice(1)) {\n if (inPrompt) { prompt.push(line.replace(/^ {4}/, '')); continue }\n const m = /^ {2}([a-z]+): ?(.*)$/.exec(line)\n if (m === null) continue\n const key = m[1]!, value = m[2]!.trim()\n if (key === 'prompt') { inPrompt = true; continue }\n scalars[key] !== undefined ? (scalars[key] += ` ${value}`) : (scalars[key] = value)\n }\n // #229: the server's configured ambient heartbeat rides every state reply; learn it here so the\n // module-level gate matches the operator's setting before any schedule decision reads it.\n configureQuietHeartbeat(Number.parseInt((scalars['heartbeat'] ?? '').trim(), 10) || 0)\n const turnRaw = scalars['turn'] ?? ''\n const turnSeq = /^\\d+$/.test(turnRaw) ? Number(turnRaw) : null\n const errorRaw = scalars['error'] ?? ''\n const intentWord = (scalars['intent'] ?? '').split(' ')[0] ?? ''\n return {\n t: 'polled',\n intent: intentWord === 'goal-edit' ? 'goal-edit' : 'worker-step',\n status,\n ...(status === 'ready' ? { text: prompt.join('\\n'), turnSeq } : {}),\n ...(status === 'failed' ? { error: errorRaw, turnSeq } : {}),\n }\n}\n\n/** The autorun flag, read from the same payload — the row is durable, the flag is not. */\nexport function parseBarAutorun(text: string): 'armed' | 'disarmed' | null {\n const m = /^ {2}autorun: (armed|disarmed)\\b/m.exec(text)\n return m === null ? null : (m[1] as 'armed' | 'disarmed')\n}\n\n/**\n * Does the host say this session is busy right now?\n *\n * The dock's props are HOOKS (`useSessionStatus`, `useChat`, `useInput`, …) — documented in\n * docs/contract.md § \"What a dock component is handed\" — so a component that waits for a scalar\n * `props.running` waits forever, which is precisely why Autorun declared itself unavailable while the host\n * was publishing the signal one field away. Shapes differ across hosts and versions, so every form is folded\n * here, in one pure function, with `undefined` (unknown) kept distinct from `false` (idle): the loop refuses\n * to start a turn on an unknown, and that distinction is the whole safety property.\n */\nexport function deriveRunning(status: unknown): boolean | undefined {\n if (status === undefined || status === null) return undefined\n if (typeof status === 'boolean') return status\n if (typeof status === 'string') {\n if (/^(running|streaming|busy|active)$/i.test(status)) return true\n if (/^(idle|done|stopped|finished|ready|waiting)$/i.test(status)) return false\n return undefined\n }\n if (typeof status === 'object') {\n const s = status as { status?: unknown, state?: unknown, running?: unknown, phase?: unknown }\n if (s.running !== undefined) return typeof s.running === 'boolean' ? s.running : undefined\n return deriveRunning(s.status ?? s.state ?? s.phase)\n }\n return undefined\n}\n\n\n/**\n * #208: the plane-wide relevance fact, read from the `state` block's own model line. `model: unset`\n * means the feature does not exist on this plane — one discovery reply carrying it silences EVERY\n * dock on the page (the pull transport cannot do better than one discovery; the push transport\n * (#194) removes even that). An unrecognised block is false, never a guess.\n */\nexport function parseModelAbsent(text: string): boolean {\n return /^\\s*model:\\s*unset\\b/m.test(text)\n}\n\n// ---------------------------------------------------------------- #194: the push half\n\n/** The pushed payload, as the client reads it from the standard `useProjection` seat. */\nexport interface PromptPushView {\n v: number\n status: PromptBarStatus\n text: string\n turnSeq: number | null\n error: string\n intent: 'worker-step' | 'goal-edit'\n autorun: 'armed' | 'disarmed'\n}\n\n/**\n * A pushed payload becomes the SAME events the pull path dispatches — one fold, one reducer, no\n * second implementation to drift (#59). Null when the payload is not ours or not trustworthy: an\n * unrecognised push is ignored, never guessed at, and the pull schedule underneath keeps running\n * until a payload this function accepts actually arrives.\n */\nexport function pushEventsOf(payload: unknown): { polled: PromptBarEvent; autorun: PromptBarEvent } | null {\n if (payload === null || payload === undefined || typeof payload !== 'object') return null\n const p = payload as Partial<PromptPushView>\n if (p.v !== 1 || typeof p.status !== 'string') return null\n // text is a ready-state fact, not a payload gate: an analyzing push without text is honest\n // progress, and rejecting it would blind the bar to the very transition it exists to show.\n const status = p.status as PromptBarStatus\n if (status !== 'off' && status !== 'idle' && status !== 'analyzing' && status !== 'ready' && status !== 'failed') return null\n return {\n polled: {\n t: 'polled', status,\n ...(status === 'ready' ? { text: typeof p.text === 'string' ? p.text : '', turnSeq: p.turnSeq ?? null, intent: p.intent ?? 'worker-step' } : {}),\n ...(status === 'failed' ? { error: p.error ?? 'the suggestion call failed' } : {}),\n },\n autorun: { t: 'autorun', on: p.autorun === 'armed' },\n }\n}\n\n/**\n * The running signal's resolution order (scalar prop → `useSession` snapshot via `deriveRunning` →\n * unknown) lives in the dock as `props.running ?? deriveRunning(sessionSnapshot)` — ONE expression,\n * pinned by a source-scan row, folded by the deriveRunning rows that already cover every shape.\n * A second pure helper for the same decision would be exactly the drift #59 forbids; the draft of\n * #194 shipped one and this comment is its headstone.\n */\n\n/** The staleness-confirm's one question: did a push arrive after the edge that scheduled it? */\nexport function pushIsFresher(lastPushAt: number | null, edgeAt: number): boolean {\n return lastPushAt !== null && lastPushAt > edgeAt\n}\n\n\n/** The projection key, from the ONE module both planes share (#194 — never retyped per plane). */\nexport { PROMPT_PROJECTION_KEY } from '../prompt-keys.ts'\n\n/**\n * #218: a DEAD-PUSH HEARTBEAT, not a staleness confirm — 20s fired mid-turn before the turn's\n * record could exist (turns outlast 20s), which was confirm spam wearing a safety hat. 5 minutes:\n * during normal work a record arrives every turn and the push effect retires the pending timer, so\n * a healthy push NEVER fires it; only a push silent for a whole 5 minutes pulls once — a frozen\n * bar is the failure this bounds, and it is worth one node every 5 minutes, not one every 20\n * seconds.\n * within moments (the runner writes it BEFORE calling the model). If no push arrived this long\n * after the edge, the push is presumed dead and ONE confirm pull runs — a silently dead push\n * degrades to one pull per turn, never to a frozen bar.\n */\nexport const PUSH_CONFIRM_GRACE_MS = 300_000\n\n/**\n * #211 — the edge kick's delay, measured on the maintainer's host the hard way: some hosts publish\n * `running` at STEP granularity (it flickers at every tool call and thinking block), and an\n * immediate kick per falling edge was a rendered `chapters-prompt` node per tool call — all waste,\n * because the server row changes ONLY at turn boundaries. So: a falling edge schedules its pull\n * after the debounce, a rising edge cancels it (step flicker coalesces to zero pulls), and the rate\n * floor bounds even a host that holds `running` low through long tool calls. A real turn end — a\n * falling edge with no rising edge after it — pulls exactly once.\n */\nexport const EDGE_DEBOUNCE_MS = 2_000\nexport const EDGE_FLOOR_MS = 15_000\n\nexport function edgeKickDelayMs(msSinceLastPull: number): number {\n return Math.max(EDGE_DEBOUNCE_MS, EDGE_FLOOR_MS - msSinceLastPull)\n}\n\n\n/**\n * #221: the turn-end pulse, derived from the host's own turn-boundary projection — no plugin\n * record API needed, so it works on 0.2.0 hosts (where appendPluginRecord is absent) exactly as\n * on newer ones. The host maintains a `turnBoundary` projection (the agent loop reads its\n * lastTurn for its own bookkeeping); reading what the host already folds costs zero writes and\n * delivers reactively through the same standard useProjection seat as any other projection.\n * Returns true when a NEW turn ended since the last observation; the dock calls it once per\n * render and stores the returned stamp back into `seen`.\n */\nexport function turnEndPulse(lastTurn: number | null | undefined, seen: number): { pulse: boolean, seen: number } {\n const cur = typeof lastTurn === 'number' && Number.isFinite(lastTurn) ? lastTurn : 0\n if (cur > seen) return { pulse: true, seen: cur }\n return { pulse: false, seen }\n}\n","/**\n * The Suggested Next Step dock row (#113) — thin by design.\n *\n * Every decision lives in `prompt-bar.ts` where a row can pin it; this file only moves pixels and bytes\n * between the host slot and that reducer. That split is the reason it exists: the ghost was rejected for\n * behaviour that had no home, and \"one turn, one offer\" cannot be tested in a component.\n *\n * Placement is measured, not styled: `conversation.input.dock` is the host's full-width stack rendered\n * ABOVE the composer card (todo `order: 0`, goal `10`, queue `20`), so `order: 30` puts this row under every\n * other dock entry and directly above the input — and because it is a docked row rather than an overlay, it\n * can neither cover the placeholder nor collide with the send buttons. The ghost's ugliest defect was\n * structural, and the structure fixes it.\n *\n * The bar is PUSH-SHAPED, PULL-FED. A registrant can own a reactive observable (`hooks: { x }` → prop\n * `useX`) — that is how the goal bar gets its `activation` — but a plugin cannot publish a projection, and\n * the only plugin-reachable call path is `remote.commands.execute`. So the component pulls the `state` verb\n * on edges it can actually observe. Stated here because the alternative is a reader assuming a subscription\n * that does not exist.\n *\n * @module dsh-chapters/src/client/prompt-dock\n */\n\nimport { createElement as h, useCallback, useEffect, useReducer, useRef, useState, type ReactElement } from 'react'\nimport { withTooltip, nativeTitle } from './tooltip.ts'\nimport {\n BAR_RUN_COMMAND,\n deriveRunning,\n BAR_STATE_COMMAND,\n pollSpacingFor, mountPullDecision, rowTooltip, stateFromCache, parseModelAbsent, edgeKickDelayMs,\n firstPullRetryDue, FIRST_PULL_RETRY_SPACING_MS, FIRST_PULL_RETRY_CEILING,\n pushEventsOf, pushIsFresher, PROMPT_PROJECTION_KEY, PUSH_CONFIRM_GRACE_MS, turnEndPulse, ACTIVE_POLL_MS, type PromptBarStatus,\n barLabel,\n barVisible,\n initialBarState,\n parseBarAutorun,\n parseBarState,\n promptBarReducer,\n shouldAutoFire,\n type PromptBarEvent,\n type PromptBarState,\n} from './prompt-bar.ts'\n\n/** The dock's owner + standard-kit props we read. Everything is optional-typed on purpose: this is a host\n * shape crossing a plugin boundary, and an absent field must degrade visibly, not throw at boot (#58). */\nexport interface DockProps {\n sessionId?: string\n // #243: the REAL contract shape (ui-conversation contract/input.ts): `insertText` takes the span\n // captured by `captureInsertion()` and returns whether it applied. Our old one-parameter guess is\n // what produced the `draftRev` throw we mis-blamed on the host.\n inputActions?: { captureInsertion?: () => unknown; insertText?: (text: string, span: unknown) => boolean; setDraft?: (text: string) => void; submit?: () => void }\n /** The host's session-status hook, when this build hands docks one (`useSessionStatus` is in the dock's\n * documented prop list). Folded through `deriveRunning` because its shape is not ours to assume. */\n useSessionStatus?: (selector?: unknown) => unknown\n /** The session snapshot hook; its snapshot carries `running`, which is Autorun's idle edge. */\n useSession?: (selector?: unknown) => unknown\n /** #194: the standard projection seat (SessionStandardProps, measured in ui-session). Where the\n * server registered the push projection, this returns its value reactively — zero commands.\n * Absent hook or undefined value ⇒ the pull schedule stands, unchanged. */\n useProjection?: (key: string) => unknown\n /** The host publishes running/idle through the composer kit on some builds; if it is absent, autorun\n * refuses to fire rather than guessing that the session is idle. Fail-safe, not fail-open. */\n running?: boolean\n /** Run a host command line for THIS session and return its text. One verb for every call the bar makes\n * (the `state` pull and the `off` write), because the bar is a mouth for the command plane — a second\n * private channel would be a second contract to keep in step, which is what `doors.ts` already avoids. */\n exec?: (line: string) => Promise<string>\n}\n\nconst CSS = [\n // Metrics copied from the goal bar's measured module so the two rows read as one family: a 36px card,\n // host elevation + radius tokens, and the host's own composer width vars so it tracks the card above it.\n '.dsh-chapters_promptDock{box-sizing:border-box;width:calc(100% - 2 * var(--dsh-composer-side-clearance) - 4 * var(--dsh-composer-dock-inset));max-width:calc(var(--dsh-composer-card-max-width) - 4 * var(--dsh-composer-dock-inset));margin:0 auto}',\n '.dsh-chapters_promptBar{isolation:isolate;box-sizing:border-box;width:100%;border-radius:var(--dsw-radius-md);height:36px;box-shadow:var(--dsw-elevation-panel);border:0;align-items:center;gap:10px;padding:4px 5px 4px 12px;display:flex;position:relative}',\n '.dsh-chapters_promptBar::before{z-index:-1;border-radius:inherit;background:var(--dsw-specific-menu);backdrop-filter:var(--dsw-menu-backdrop-filter);content:\"\";pointer-events:none;position:absolute;inset:0}',\n '.dsh-chapters_promptExpanded::before{align-items:flex-start;position:absolute;inset:0}',\n // #229: the EXPANDED bar is a solid card that grows with its content — the maintainer's report was\n // an offer opening \"on a transparent background right over the bar, impossible to read\". The ::before\n // paint layer (menu token) already backs the collapsed row; expansion now also lifts height:auto so\n // the whole text sits ON the card, in flow, not floating over anything.\n '.dsh-chapters_promptExpanded{height:auto;min-height:36px;padding-top:8px;padding-bottom:8px}',\n '.dsh-chapters_promptGlyph{color:var(--dsw-alias-label-tertiary);flex:none;display:inline-flex}',\n '.dsh-chapters_promptLabel{color:var(--dsw-alias-label-primary);flex:none;font-size:13px;font-weight:500;line-height:24px}',\n // #236: `flex:1` alone means flex-basis AUTO — sized from content. Collapsed (nowrap) that reads\n // fine; EXPANDED, a tall multi-line block drives the item toward its minimum width while the\n // glyph/label/actions keep flex:none, so the text column squeezed to ~one character per line (the\n // maintainer's \"illegible text that has one character and whitespace per line\"). The fix is the\n // basis: claim the full remaining card width in both states.\n '.dsh-chapters_promptText{min-width:0;color:var(--dsw-alias-label-primary-dimmed);font-size:13px;line-height:20px;cursor:pointer;border:0;background:0 0;padding:0;text-align:left;flex:1 1 100%}',\n '.dsh-chapters_promptEllipsis{white-space:nowrap;text-overflow:ellipsis;overflow:hidden;display:block}',\n // #236: the expanded offer is a bounded reading pane — max-height with an internal scrollbar, so\n // a long suggestion can never cover the screen (the maintainer asked for exactly this). Normal\n // wrapping (`break-word`, not `anywhere`) keeps words whole on full-width lines.\n '.dsh-chapters_promptFull{white-space:pre-wrap;overflow-wrap:break-word;word-break:normal;line-height:20px;font-size:13px;color:var(--dsw-alias-label-primary);display:block;max-height:9rem;overflow-y:auto}',\n '.dsh-chapters_promptError{color:var(--dsw-alias-state-error-primary);font-size:12px;line-height:20px;flex:none;max-width:34%}', '.dsh-chapters_promptNote{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:20px;min-width:0}',,\n\n '.dsh-chapters_promptActions{flex:none;align-items:center;gap:10px;display:flex}',\n '.dsh-chapters_promptBtn{corner-shape:round;width:28px;height:28px;color:var(--dsw-alias-label-tertiary);cursor:pointer;background:0 0;border:none;border-radius:999px;justify-content:center;align-items:center;padding:0;display:inline-flex;font-size:13px}',\n '.dsh-chapters_promptBtn:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary)}',\n '.dsh-chapters_promptBtn:disabled{opacity:.4;cursor:default}',\n].join('\\n')\nconst CSS_ID = 'dsh-chapters/prompt-dock.css'\n\nconst ensureCss = (): void => {\n if (typeof document === 'undefined') return\n if (document.getElementById(CSS_ID) !== null) return\n const style = document.createElement('style')\n style.id = CSS_ID\n style.setAttribute('data-plugin-css', CSS_ID)\n style.textContent = CSS\n document.head.appendChild(style)\n}\n\n/** The analysis glyph, drawn to the goal icon's metric (16 viewBox, stroke currentColor, width 1).\n * A prism-and-arrow: the feature reads the situation and points at the next move. */\nconst Glyph = (): ReactElement => h(\n 'svg', { viewBox: '0 0 16 16', width: 14, height: 14, fill: 'none', 'aria-hidden': 'true', 'stroke-width': '1' },\n h('path', { d: 'M2.5 3.5h11L8 9.5 2.5 3.5Z', stroke: 'currentColor' }),\n h('path', { d: 'M8 9.5V14', stroke: 'currentColor' }),\n h('path', { d: 'M6 12l2 2 2-2', stroke: 'currentColor' }),\n)\n\n/** One action button, labelled through the host tooltip exactly as the goal bar labels its own. */\nconst Action = (props: { label: string; glyph: string; onClick: () => void; disabled?: boolean; title?: string; className?: string | undefined }): ReactElement => {\n const button = h('button', {\n type: 'button', className: props.className === undefined ? 'dsh-chapters_promptBtn' : `dsh-chapters_promptBtn ${props.className}`, 'aria-label': props.label,\n ...(props.disabled === true ? { disabled: true } : {}),\n ...(props.title !== undefined ? { title: props.title } : nativeTitle(props.label)),\n onClick: props.onClick,\n }, props.glyph)\n // Props matched to the call `doors.ts` already makes successfully: the host Tooltip takes\n // { label, side, children } and nothing else that I have verified. Inventing extra props (portal, delayMs)\n // failed the overload on the first compile, which is the right way to learn it.\n return withTooltip(props.label, button as ReactElement<Record<string, unknown>>)\n}\n\n/** Run is allowed whenever there is an offer; AUTORUN is what the intent and the goal gate. Keeping the\n * human's own button enabled is deliberate — the point of the protocol is to route a goal edit to a keystroke,\n * never to disable the human's ability to send it. */\n/**\n * The words the collapsed row shows, per state. `idle` and `analyzing` must say something, because an empty\n * row is indistinguishable from a broken one — the whole reason this feature took a day to read: the bar was\n * live, enabled, and rendering nothing but whitespace.\n */\nfunction lineFor(state: PromptBarState): string {\n if (state.status === 'ready') return state.text ?? ''\n if (state.status === 'analyzing') return 'Analyzing the session…'\n if (state.status === 'failed') return state.error !== null && state.error !== '' ? `Cannot recommend: ${state.error}` : 'Cannot recommend a next step right now'\n return 'No suggestion yet — I will recommend one after your next turn'\n}\n\n// #243: the graceful fallback when even a correct composer write is refused — copy the offer so the\n// human CAN edit it (paste, tweak, send). navigator.clipboard needs a secure context; the harness GUI\n// is loopback-http, which browsers treat as secure, but the failure arm just says so instead of lying.\nconst copyToClipboard = (text: string): boolean => {\n try {\n void navigator.clipboard?.writeText(text)\n return true\n } catch { return false }\n}\n\nconst canRunHere = (state: PromptBarState): boolean => state.text !== null && state.text !== ''\n\n/** How long a state pull may take before we call it failed. Generous on purpose: this is a local RPC that\n * answers in milliseconds when the session is attachable, and the failure it guards against is a hang. */\nconst PULL_TIMEOUT_MS = 15_000\n\n/**\n * #203: the last known truth per session, outliving the component. SPA navigation remounts the\n * dock, and every pull is a rendered `command/run`+`command/done` history pair — so a remount\n * that re-pulled wrote a node per activation, the waste the maintainer named (\"every time I\n * navigate away and come back\"). The cache makes activation free: mount folds it through the SAME\n * reducer (stateFromCache), and only an untrustworthy cache pulls (mountPullDecision). A page\n * reload clears it and pays exactly one honest pull.\n */\ninterface CacheEntry { ev: import('./prompt-bar.ts').PromptBarEvent; autorun: 'armed' | 'disarmed' | null; at: number; /** #272: set while this entry came from localStorage and THIS page has not polled since — it predates whatever the server decided, including an enablement. */ fromDisk?: boolean | undefined }\nconst stateCache = new Map<string, CacheEntry>()\n\n/**\n * #251: the memory cache dies with the page, and the maintainer's rule is absolute — a reload must\n * cost ZERO chapters-prompt commands. Two page loads producing two visible `state` nodes still reads\n * as \"the same shit\" from the chair, sanctioned or not. So the last-known truth persists per session\n * in localStorage (the host's own convention for composer state — `dsh.sessions.current`, persisted\n * drafts), and activation reads memory first, then storage. A cold tab renders the last offer with\n * no command at all; turn boundaries refresh it through the pulse/confirm paths that already exist.\n */\nconst PERSIST_PREFIX = 'dsh.chapters.promptState.'\nconst PERSIST_MAX = 50\n\nconst persistKey = (sessionId: string): string => `${PERSIST_PREFIX}${sessionId}`\n\nfunction readPersisted(sessionId: string): CacheEntry | null {\n try {\n const raw = window.localStorage.getItem(persistKey(sessionId))\n if (raw === null) return null\n const p = JSON.parse(raw) as { ev?: unknown; autorun?: unknown; at?: unknown }\n if (typeof p.at !== 'number' || p.ev === null || typeof p.ev !== 'object') return null\n const t = (p.ev as { t?: unknown }).t\n if (t !== 'polled') return null\n const autorun = p.autorun === 'armed' || p.autorun === 'disarmed' ? p.autorun : null\n return { ev: p.ev as CacheEntry['ev'], autorun, at: p.at, fromDisk: true }\n } catch { return null }\n}\n\nfunction writePersisted(sessionId: string, entry: CacheEntry): void {\n try {\n window.localStorage.setItem(persistKey(sessionId), JSON.stringify(entry))\n // bounded: prune the oldest beyond PERSIST_MAX by their recorded time\n const keys: string[] = []\n for (let i = 0; i < window.localStorage.length; i++) {\n const k = window.localStorage.key(i)\n if (k !== null && k.startsWith(PERSIST_PREFIX)) keys.push(k)\n }\n if (keys.length <= PERSIST_MAX) return\n const aged = keys.map((k) => {\n let at = 0\n try { at = Number(((JSON.parse(window.localStorage.getItem(k) ?? '{}') as { at?: number }).at) ?? 0) } catch { at = 0 }\n return { k, at }\n }).sort((x, y) => x.at - y.at)\n for (const old of aged.slice(0, keys.length - PERSIST_MAX)) window.localStorage.removeItem(old.k)\n } catch { /* private mode / quota: the memory cache still does its job */ }\n}\n\n/** Memory first, then disk — one reader so every decision sees the same truth (#59). */\nfunction cachedState(sessionId: string | undefined): CacheEntry | undefined {\n if (sessionId === undefined) return undefined\n const mem = stateCache.get(sessionId)\n if (mem !== undefined) return mem\n const disk = readPersisted(sessionId)\n if (disk !== null) { stateCache.set(sessionId, disk); return disk }\n return undefined\n}\n\n/**\n * #208: set by the first reply reporting the plane-wide `model: unset` — the feature does not\n * exist here, so NO dock on this page pulls again for anything: not mounts, not idle edges, not\n * timers, not visibility. One discovery per page load is the pull transport's floor; a page reload\n * is the only revival, and the enabling commands say so.\n */\nlet featureAbsent = false\n\n/** Retry ceiling for the FIRST pull only, in attempts and spacing. A mount-time race must not be able to\n * starve the bar forever, and a real `off` answer stops the loop on the first reply either way. */\n\nfunction execWithTimeout(exec: (line: string) => Promise<string>, line: string, ms: number): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n const timer = setTimeout(() => { reject(new Error(`no answer within ${String(ms)}ms`)) }, ms)\n exec(line).then(\n (text) => { clearTimeout(timer); resolve(text) },\n (error: unknown) => { clearTimeout(timer); reject(error instanceof Error ? error : new Error(String(error))) },\n )\n })\n}\n\n/**\n * The composer, by the name the HOST gives it (placeholder \"Message or run a task, / commands, …\",\n * locales.ts:400) — NOT a bare `[contenteditable][role=textbox]` first(), which on this app matches\n * the sidebar's \"Search session names\" input (measured lesson, tests/e2e/prompt-bar.spec.ts:41: a\n * whole click-to-draft assertion was reading the wrong element). The host's own editable element\n * carries `data-composer-input` (measured: ComposerContentEditable.tsx:46) — stable across styles,\n * locales and restyles, so the probe matches THAT and never a first(). Shared by the three sites\n * that touch the editor: the #309 occupancy guard, the focus-before-insert, and the\n * write-verification — one probe, one truth. Absent attribute ⇒ null ⇒ the guard ALLOWS the\n * handoff (unknown is never a reason to block the feature; the post-write verify is the backstop).\n */\nconst composerBox = (): HTMLElement | null => {\n try { return document.querySelector<HTMLElement>('[data-composer-input]') } catch { return null }\n}\n\n/** #309: does the chat input hold the user's in-flight text? Whitespace-only counts as empty. */\nconst composerHasText = (): boolean => {\n const el = composerBox()\n if (el === null) return false\n const t = 'value' in el ? String((el as unknown as { value: string }).value ?? '') : (el.innerText ?? '')\n return t.trim() !== ''\n}\n\nexport function PromptDock(props: DockProps): ReactElement | null {\n const { sessionId, inputActions, exec } = props\n // #194 + the contract's running-signal lock: BOTH hook reads happen first, unconditionally,\n // above every other hook — hook order must not change between renders (the #310 lesson). The\n // measured seats: `useSession`'s snapshot carries `running` (deriveRunning folds whatever shape\n // arrives; a scalar `running` prop wins where a build supplies one), and `useProjection` is the\n // standard seat the push transport rides. Absent hooks degrade through stable fallbacks.\n const useSessionHook = props.useSession ?? (() => undefined)\n const sessionSnapshot = useSessionHook((snapshot: unknown) => snapshot)\n const running = props.running ?? deriveRunning(sessionSnapshot)\n const useProjectionHook = props.useProjection ?? (() => undefined)\n const pushed = useProjectionHook(PROMPT_PROJECTION_KEY)\n // #221: the host's OWN turn-boundary projection. Reading it costs nothing (the agent loop already\n // maintains it), works on EVERY host with projections including 0.2.0-rc.2 — where appendPluginRecord\n // is absent and the record transport cannot exist. A new turn end is the only moment our row can\n // change without a user action, so this pulse replaces the clock: one sanctioned follow-up pull per\n // boundary instead of a 10-second drumbeat (measured on the maintainer's live log: 158 pulls at exact\n // 10.0s intervals). Absent hook or projection ⇒ no pulse ⇒ the quiet heartbeat stands.\n const turnBoundary = useProjectionHook('turnBoundary') as { lastTurn?: number } | null | undefined\n const [state, dispatch] = useReducer(promptBarReducer, initialBarState(), (s) => {\n // #203: activation renders from the module cache — zero invocations — folded through the live\n // reducer path, so there is no second fold implementation to drift.\n const pushEvs = pushEventsOf(pushed)\n if (pushEvs !== null) {\n return { ...promptBarReducer(promptBarReducer(s, pushEvs.polled), pushEvs.autorun), running: running === true }\n }\n const c = cachedState(sessionId)\n const base = c !== undefined ? stateFromCache(c.ev, c.autorun) : s\n return { ...base, running: running === true }\n })\n // #79's discipline, kept because the failure it prevents was real: one pull per mount, then per edge.\n // A fetch in an effect with no such guard re-fires on every render.\n const pulling = useRef(false)\n // #304: consecutive analyzing OBSERVATIONS drive the belt back-off (10/20/40/60). It counts\n // what the wire SAID, not what we hope is happening — any non-analyzing answer resets it.\n const analyzingStreak = useRef(0)\n // TWO different facts, two different refs — conflating them is the bug I just shipped: `pulled` is the\n // once-per-mount pull guard, `alive` is \"may this component still call dispatch/setState\". Initializing the\n // pull guard to true made every mount skip its first pull, so the bar sat at its `off` default and rendered\n // nothing at all — a regression that looked, from outside, like the feature having stopped working.\n const probed = useRef(false)\n const pulled = useRef(false)\n const alive = useRef(true)\n useEffect(() => () => { alive.current = false }, [])\n const [busy, setBusy] = useState(false)\n void 0\n // #193: the mount effect's reschedule handle, so the idle edge and the visibility edge can pull NOW\n // instead of waiting out a possibly-quiet cadence. Undefined while the poll is not mounted.\n const kick = useRef<(() => void) | undefined>(undefined)\n // #211: when the last pull STARTED (a failed pull is still a rendered node — the floor counts it),\n // and the pending debounced edge pull, which a rising edge cancels.\n const lastPullAt = useRef<number | null>(null)\n const edgeTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n // #194: push-mode bookkeeping. A projection that existed and went silent is the confirm-pull's\n // job to police, not a reason to resurrect the clock — once live, live for the page lifetime.\n // #497: live is decided by the CELL, not by an arrival. The server registers this projection\n // only after the push transport resolved, and the seat read is a synchronous cut over the host's\n // watermark cache — so a cell that EXISTS on first render (payload or null: registered means the\n // records ride) can gain nothing from a mount pull except two durable command nodes. The old\n // latch-on-arrival always lost the race with the mount tick, so EVERY session load of EVERY\n // page paid the pull the maintainer's rule forbids. Absent cell (pre-projection host, or the\n // writer refused at boot) ⇒ undefined ⇒ the honest pull-first fallback stands, unchanged.\n const pushLiveRef = useRef<boolean>(pushed !== undefined)\n // #497: did the MOUNT tick sanction a pull? The retry loop may only chase a starved pull (exec\n // not hydrated yet, #429's whole point) — never invent one the silent-by-design mount skipped.\n const pullOwed = useRef<boolean>(false)\n // #221: the last turn-end seq observed; the pulse fires when the host advances past it.\n const seenTurnRef = useRef<number>(0)\n const lastPushAt = useRef<number | null>(null)\n const answered = useRef(false)\n const replyStatus = useRef<string>('unknown')\n const stateRef = useRef<PromptBarState>(initialBarState())\n stateRef.current = state\n // #203: does THIS host publish the running signal? Where it does, the idle edge is the schedule\n // and a stable bar keeps no clock; where it does not, the #193 cadence is the fallback.\n const edgesRef = useRef<boolean>(props.running !== undefined)\n edgesRef.current = props.running !== undefined\n if (!probed.current) {\n probed.current = true\n // One print, on the first mount: which composer verbs does THIS host actually hand a dock? The click-to-draft\n // requirement needs one, `setDraft` is accepted but never reaches the editor, and guessing at the surface\n // again would be a third wrong theory in a row.\n console.info(`[client:prompt] inputActions keys: ${Object.keys(inputActions ?? {}).join(',') || 'NONE'}`)\n }\n\n const refresh = useCallback(async (): Promise<void> => {\n if (exec === undefined || pulling.current) return\n pulling.current = true\n lastPullAt.current = Date.now()\n try {\n // Bounded, and loudly so. Tonight's whole diagnosis cost was paid because this await had no ceiling:\n // a wire that never answers produced no dispatch, no catch and no `finally`, which looked identical to\n // \"the feature is switched off\". A hung command is now a named failure with a number on it (#61).\n const text = await execWithTimeout(exec, BAR_STATE_COMMAND, PULL_TIMEOUT_MS)\n // Handed to the leg through the page, because the state block is the contract and I need to see the\n // bytes the browser parsed, not the bytes the server meant. Overwritten each pull; read on failure.\n try { (window as unknown as { __dshPromptReply?: string }).__dshPromptReply = text } catch { /* test seam only */ }\n const ev = parseBarState(text) as PromptBarEvent | null\n if (ev !== null) {\n answered.current = true\n const st = (ev as { status?: string }).status ?? replyStatus.current\n replyStatus.current = st\n analyzingStreak.current = st === 'analyzing' ? analyzingStreak.current + 1 : 0 // #304\n dispatch(ev)\n }\n const autorun = parseBarAutorun(text)\n if (autorun !== null) dispatch({ t: 'autorun', on: autorun === 'armed' })\n // #208: a reply naming the model unset silences the whole page — relevance is plane-wide.\n if (parseModelAbsent(text)) featureAbsent = true\n // #203: every honest reply feeds the cache the next activation renders from.\n if (ev !== null && sessionId !== undefined) {\n stateCache.set(sessionId, { ev, autorun: autorun === 'armed' || autorun === 'disarmed' ? autorun : null, at: Date.now() })\n // #251: write-through — this reply now outlives the page.\n writePersisted(sessionId, { ev, autorun: autorun === 'armed' || autorun === 'disarmed' ? autorun : null, at: Date.now() })\n }\n } catch (error) {\n // #61: a detected failure is a DELIVERED failure. Keeping the last known state is right; saying\n // nothing was not — with a bare `catch {}` a wire that never answers is indistinguishable from a\n // feature that is switched off, and that is exactly how this bar looked \"unverifiable\" in a browser\n // while the real fault was one line of swallowed output.\n // A failed pull is not a state: the bar keeps what it last knew rather than rendering `off`,\n // which would read as \"suggestions are disabled\" when the wire merely hiccoughed.\n console.warn(`[client:prompt] pull failed: ${String((error as Error)?.message ?? error).slice(0, 180)}`)\n } finally { pulling.current = false }\n }, [exec])\n\n // #194: the pushed value dispatches through the same reducer the pulls feed. The effect sits\n // ABOVE the mount poll so pushLive is set before the first tick decides anything. Any push also\n // retires a pending edge timer in push mode — the record IS the answer the confirm would fetch.\n useEffect(() => {\n // #497: a cell that EXISTS is an answer channel even before its first payload — retry pulls\n // are owed to exec, never to a projection that has not been given its chance to hydrate.\n if (pushed !== undefined) pushLiveRef.current = true\n const evs = pushEventsOf(pushed)\n if (evs === null) return\n pushLiveRef.current = true\n lastPushAt.current = Date.now()\n dispatch(evs.polled)\n dispatch(evs.autorun)\n if (edgeTimer.current !== undefined) { clearTimeout(edgeTimer.current); edgeTimer.current = undefined }\n }, [pushed])\n\n useEffect(() => {\n ensureCss()\n if (pulled.current) return\n pulled.current = true\n // Retry until SOMETHING answers. `answered` flips on any parseable reply, including an honest `off`, so\n // this loop cannot make a disabled session look enabled — it only closes the window where a pull fired\n // before the session could take a command and the bar then stayed blank for the rest of the session.\n // Keep reading while the feature is live, at a cadence that is a DECISION (#193): every pull is two\n // recorded host lifecycle events (`command/run` + `command/done`) the UI renders as history nodes, so\n // the old unconditional 10s poll wrote ~360 visible nodes an hour into every bar-enabled session —\n // the maintainer's \"littered with chapters-prompt runs, one right after another\". `pollSpacingFor`\n // paces it: fast while state can change (analyzing / armed / running), slow while stable, and NOTHING\n // in a hidden tab unless the loop is armed. On hosts that publish no running prop, `running` stays\n // conservatively true and the cadence stays active — the old behavior, unchanged. `off` still ends it.\n let timer: ReturnType<typeof setTimeout> | undefined\n // #203: one vocabulary for \"what the bar knows right now\" — a reply beats the cache-folded row\n // state, and every schedule decision reads THIS instead of keeping a fourth copy of the truth.\n const effectiveStatus = (): PromptBarStatus =>\n (replyStatus.current === 'unknown' ? stateRef.current.status : replyStatus.current) as PromptBarStatus\n const spacingNow = (): number | null => {\n // #229: an ARMED autorun loop is the one state that genuinely needs follow-up polling — after\n // a fired round the offer changes without a human action, and the turn-end pulse may already\n // have been consumed before generation finished. While armed, keep the old quiet floor (60s)\n // even when the ambient heartbeat is off; disarmed bars poll nothing.\n if (stateRef.current.autorun === 'armed') return ACTIVE_POLL_MS\n // #221: consume the pulse exactly once per boundary.\n const pe = turnEndPulse(turnBoundary?.lastTurn, seenTurnRef.current)\n if (pe.pulse) seenTurnRef.current = pe.seen\n return pollSpacingFor({\n status: effectiveStatus(),\n autorun: stateRef.current.autorun,\n running: stateRef.current.running,\n hidden: typeof document !== 'undefined' && document.hidden === true,\n edges: edgesRef.current,\n turnEndPulse: pe.pulse,\n analyzingStreak: analyzingStreak.current, // #304: arm the back-off with what we've OBSERVED\n })\n }\n const duePull = (): boolean => {\n const c = cachedState(sessionId)\n return mountPullDecision({\n hasCache: c !== undefined,\n ageMs: c !== undefined ? Date.now() - c.at : Number.MAX_SAFE_INTEGER,\n status: effectiveStatus(),\n autorun: stateRef.current.autorun,\n // #272: an off carried across the reload from localStorage must still pay this page's one\n // honest pull — the revival promise. Once this page polls, the replacing entry is untagged.\n cacheFromDisk: c?.fromDisk === true,\n })\n }\n const tick = async (opts?: { mount?: boolean; force?: boolean }): Promise<void> => {\n // #194: in push mode there is no clock and no mount pull — state arrives through the\n // projection. A FORCED tick still runs: that is the staleness confirm firing because the\n // push did NOT arrive, and the pull is then the honest fallback, not waste.\n if (pushLiveRef.current && opts?.force !== true) return\n // #208: not relevant, not visible — an unset-model plane spends nothing, ever.\n if (featureAbsent) return\n if (effectiveStatus() === 'off') {\n // A known `off` spends no clock and no edge — but a STALE cached off is untrustworthy:\n // `/chapters-prompt on` could have happened anywhere. The staleness guard on a mount is the\n // only revival path short of a page reload, and that matches the old within-mount rule.\n if (!(opts?.mount === true && duePull())) return\n }\n const spacing = spacingNow()\n // force = an edge the schedule sanctions (a turn ended): pull even where the steady cadence\n // says no timer is needed. mount = the guarded first look; a fresh cache renders for free.\n // #231: the MOUNT discovery is a sanctioned moment in its own right — it must NOT be gated on\n // `spacing`, or removing the ambient clock (the whole point of #231) removes the one pull that\n // tells the bar whether the feature exists at all. Measured cost of getting this wrong: the\n // rig's prompt leg failed four-for-four because no pull ever fired and the dock stayed hidden.\n const mountDiscovery = opts?.mount === true && duePull()\n if (opts?.force === true || mountDiscovery || (spacing !== null && opts?.mount !== true)) {\n if (opts?.mount === true) pullOwed.current = true // #497: the sanction IS the debt\n await refresh()\n }\n if (replyStatus.current === 'off') return\n // The reply, not the React state: the row is hidden while `off`, and a hidden row renders\n // nothing, so stateRef can lag. The schedule reads the wire truth whenever it exists.\n const next = spacingNow()\n if (next !== null) timer = setTimeout(() => { void tick() }, next)\n }\n // The idle edge IS the schedule (#203): a turn ending is the moment an offer is born, so it\n // pulls with force. The tab-foreground edge pulls ONLY when the cache can no longer be\n // trusted — flicking back to a tab you left a moment ago must not write a history node.\n kick.current = () => {\n if (timer !== undefined) clearTimeout(timer)\n void tick({ force: true })\n }\n const onVisible = (): void => {\n if (typeof document !== 'undefined' && !document.hidden && duePull()) kick.current?.()\n }\n if (typeof document !== 'undefined') document.addEventListener('visibilitychange', onVisible)\n // #429: THE FIRST-PULL BOUNDED RETRY, finally as code — both comments above promise it (:240's\n // ceiling, :410's 'retry until SOMETHING answers'), and its absence was the measured revival-leg\n // flake: the mount effect fires while a loaded boot is still hydrating the composer's exec verb,\n // refresh() returns at `exec === undefined` BEFORE pulling (no wire node, no answer), and under\n // the quiet cadence (#229) nothing ever asks the mount again. Samples: FAILED in two loaded\n // chains (local + CI), PASSED 10/10 solo on the same head + CI re-run + #427's CI. The loop is\n // due ONLY while owed and unanswered (firstPullRetryDue — any honest reply, `off` included, is an\n // answer, #304), and at the ceiling it gives up LOUDLY: a silent give-up is the mystery this\n // whole class of bug ships behind (#54, again).\n let firstPullRetries = 0\n let firstPullTimer: ReturnType<typeof setTimeout> | undefined = undefined\n const retryFirstPull = (): void => {\n if (!firstPullRetryDue({ answered: answered.current, featureAbsent, attempts: firstPullRetries, owed: pullOwed.current, pushLive: pushLiveRef.current })) {\n if (!answered.current && !featureAbsent && pullOwed.current && !pushLiveRef.current && firstPullRetries >= FIRST_PULL_RETRY_CEILING) {\n console.warn(`[client:prompt] first-pull retry ceiling (${String(FIRST_PULL_RETRY_CEILING)} x ${String(FIRST_PULL_RETRY_SPACING_MS)}ms) reached with NO wire answer — the mount pull remains owed; edges are the recovery path (#429)`)\n }\n return\n }\n firstPullRetries += 1\n firstPullTimer = setTimeout(() => {\n firstPullTimer = undefined\n void refresh().then(() => { retryFirstPull() })\n }, FIRST_PULL_RETRY_SPACING_MS)\n }\n void tick({ mount: true }).then(() => { retryFirstPull() })\n return () => {\n if (firstPullTimer !== undefined) clearTimeout(firstPullTimer)\n if (timer !== undefined) clearTimeout(timer)\n if (edgeTimer.current !== undefined) { clearTimeout(edgeTimer.current); edgeTimer.current = undefined }\n kick.current = undefined\n if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', onVisible)\n }\n }, [refresh])\n\n // Autorun fires off the IDLE edge, never off a render. `running` comes from the host when it publishes it;\n // absent means unknown, and unknown means do not start a turn the human cannot see coming.\n // #221/#282: unknown is NOT running. `?? true` here pinned a non-publishing host into a permanent\n // running edge — harmless while running only decorated the flag, fatal once a running edge CLEARS\n // the offer (#282): the bar would show \"Agent is running\" forever. Strict boolean at every fold.\n const prevRunning = useRef<boolean>(running === true)\n useEffect(() => {\n const next = running === true\n const prev = prevRunning.current\n prevRunning.current = next\n dispatch({ t: 'running', running: next })\n // #211 + #194, ONE schedule: a falling edge delays exactly one pull and a rising edge cancels\n // it (step-granular flicker coalesces to zero pulls). Pull mode: the debounced kick\n // (edgeKickDelayMs — 2s debounce, 15s floor). Push mode: the staleness CONFIRM at\n // max(grace, floor − since) — a record landing after the edge retires it via the push effect,\n // so a healthy push costs nothing and a dead one degrades to one pull per turn, never a\n // frozen bar. Hosts that publish no running signal never produce transitions and keep the\n // cadence fallback unchanged.\n if (prev && !next) {\n if (edgeTimer.current !== undefined) clearTimeout(edgeTimer.current)\n const since = lastPullAt.current === null ? Number.MAX_SAFE_INTEGER : Date.now() - lastPullAt.current\n const delay = pushLiveRef.current\n ? Math.max(PUSH_CONFIRM_GRACE_MS, edgeKickDelayMs(since))\n : edgeKickDelayMs(since)\n const edgeAt = Date.now()\n edgeTimer.current = setTimeout(() => {\n edgeTimer.current = undefined\n // A push that landed after the edge already answered the confirm's question.\n if (pushLiveRef.current && pushIsFresher(lastPushAt.current, edgeAt)) return\n kick.current?.()\n }, delay)\n } else if (!prev && next) {\n if (edgeTimer.current !== undefined) { clearTimeout(edgeTimer.current); edgeTimer.current = undefined }\n }\n }, [running])\n\n // Run is a COMMAND, not a keystroke. The composer-write path (`inputActions.setDraft` + `submit`) looked\n // like the obvious implementation and does not work on this host build: `setDraft` is accepted, and the\n // editor stays empty — measured, twice, after I had convinced myself it was the test's locator or a focus\n // ordering problem. The plugin already has a dependable wire to its own server plane, and the server has\n // exactly one human-authored submission path (the follow-up autorun uses), so Run rides that. The\n // consequence is also the point: what the human clicks and what the loop arms are the same code.\n const run = useCallback((): void => {\n if (state.text === null || state.text === '' || exec === undefined) return\n setBusy(true)\n void exec(BAR_RUN_COMMAND)\n .then((out) => {\n if (!alive.current) return\n if (/^cannot run:/i.test(out.trim())) dispatch({ t: 'polled', status: 'failed', text: state.text, error: out.trim().slice(0, 200), turnSeq: state.turnSeq } as PromptBarEvent)\n // #285: success means THIS click authored a turn — the dock knows that without any host\n // signal, so it folds `running: true` locally: the offer clears, Run disarms, and the\n // generic running line shows even on edgeless hosts (#221). The server consumed the row in\n // the same breath, so the next pull (any tab) confirms the truth, and polled retires the\n // flag wire-first. Replaces #282's collapse-only success fold, which left a just-run offer\n // sitting there re-runnable — the hole the maintainer's double-Click found.\n else dispatch({ t: 'running', running: true } as PromptBarEvent)\n // #518: the consumed state must OUTLIVE the reload. The disk cache kept the pre-run ready\n // entry, so a cold mount resurrected the executed offer with enabled buttons — the bar must\n // show the truth (nothing to run; next offer arrives at the next completed turn) everywhere.\n if (sessionId !== undefined) {\n const runEntry = { ev: { t: 'polled', status: 'off' } as CacheEntry['ev'], autorun: null, at: Date.now() }\n stateCache.set(sessionId, runEntry)\n writePersisted(sessionId, runEntry)\n }\n })\n .catch((error: unknown) => { console.warn(`[client:prompt] run failed: ${String((error as Error)?.message ?? error).slice(0, 160)}`) })\n .finally(() => { if (alive.current) setBusy(false) })\n }, [exec, state.text, state.turnSeq])\n\n useEffect(() => {\n if (!shouldAutoFire(state)) return\n run()\n }, [state, run])\n\n // Autorun's idle edge stays UNWIRED on this host, and that is now a measured fact rather than a guess:\n // `useSessionStatus` is in the dock's documented prop list, but calling it here threw twice — first a React\n // hook-order abort (#310, because it sat below the early return), then `TypeError: l is not a function` once\n // hoisted. Two blind attempts is the limit; the contract says which hooks exist, not their arity or context.\n // So the gate keeps its original, correct behavior: with no signal, `running` is undefined, Autorun is\n // visibly unavailable and says why, and `deriveRunning` (9 rows) stands ready for whichever shape the host\n // does publish. A loop that starts turns the human cannot foresee is the one failure mode not on offer.\n // `useSessionStatus` is `SnapshotSelectorHook<SessionStatusSnapshot>` — a SELECTOR hook (declared in\n // dsh-client-ui-session's client types), which is why calling it with a session id threw\n // `TypeError: l is not a function`: the host used my string as the selector. An identity selector takes\n // whatever the snapshot's shape happens to be, and `deriveRunning` folds it, so this code does not bet on\n // field names I have not read. Still hoisted above the early return: hook count must not change per render.\n // The idle signal IS published — on `useSession`, whose snapshot carries `running` (measured by printing the\n // hook surfaces once: `useSession=sessionId|pendingSubmissions|running|subagent|removed|openState`). My\n // first two attempts were wrong in different ways: a scalar `props.running` that no host supplies, then\n // `useSessionStatus`, which is provided but yields no readable keys under an identity selector. `deriveRunning`\n // folds `{running}`, so this is the last mile, and the hook is called unconditionally through a stable\n // fallback because hook order must not change between renders.\n const autorunDisabled = running === undefined\n\n if (sessionId === undefined || !barVisible(state as PromptBarState)) return null\n\n const populate = (): void => {\n // Collapsed: reading. Expanded: the maintainer's click-to-edit gesture — setDraft REPLACES the draft,\n // which is what they asked for (\"the prompt replaces the chat input contents so you can edit it\"), and\n // nothing is submitted. Run is a separate, deliberate button.\n // Printed on every branch, because \"the button did nothing\" and \"the button took the other path\" looked\n // identical from outside for three runs.\n console.info(`[client:prompt] populate expanded=${String(state.expanded)} hasInsertText=${String(typeof inputActions?.insertText)} hasSetDraft=${String(typeof inputActions?.setDraft)} textLen=${String(state.text?.length ?? -1)}`)\n if (!state.expanded) { dispatch({ t: 'expand' }); return }\n if (state.text === null || state.text === '') return\n // #309: hand off INTO AN EMPTY COMPOSER ONLY — never append to, never overwrite, text the user\n // is mid-typing. The refusal says itself on the bar (the tooltip already named the precondition).\n if (composerHasText()) { dispatch({ t: 'note', note: 'The chat input has text — clear it first, then this click hands the suggestion over.' }); return }\n // Delivered, not assumed. The click-to-draft gesture is the interaction the maintainer asked for, so a\n // silent no-op here is indistinguishable from \"the feature does not work\" — and that ambiguity cost the\n // rest of this leg's diagnosis. Absent verb, absent text: both say so.\n // The host's composer kit is `{ captureInsertion, insertText, setDraft, addAttachments, removeAttachment,\n // pruneAttachments, submit }` (measured on 0.2.0-rc.2). `setDraft` writes the STORE, and the store is\n // mirrored into the editor only at mount while the editor is empty — which is why a click that \"worked\"\n // (no refusal, no throw) left the box visibly empty. `insertText` is the verb that reaches the editor, so\n // click-to-draft uses it and keeps `setDraft` only as a fallback for builds that lack it.\n if (typeof inputActions?.insertText === 'function') {\n // `insertText` inserts AT THE CARET, and clicking this button moves the caret out of the editor — so the\n // call ran and put the words nowhere. Focusing the composer first is the whole difference, and it is done\n // with a tolerant query rather than a class name: the host's own module hashes (`wSkVaW_…`) are not mine\n // to depend on, and a bar that silently stops drafting after a host restyle is worse than one that tries.\n try { composerBox()?.focus() } catch { /* a host without the editor mounted: the insert below still records the intent */ }\n // Measured on host 0.2.0-rc.2: called from a dock this throws\n // `Cannot read properties of undefined (reading 'draftRev')`, and the kit's other verb (`setDraft`) writes\n // a store the editor mirrors only at mount. Neither reaches the composer. A silent no-op is what cost the\n // last six runs, so the refusal now appears on the bar and points at Run, which does work.\n // #243: THE BUG WAS OURS. The contract (ui-conversation contract/input.ts:249-256) requires\n // TWO steps: `captureInsertion()` returns the revision-guarded span, then `insertText(text, span)`\n // applies it. We called `insertText(text)` with NO span — facade.ts:128 reads `span.draftRev` off\n // `undefined` and throws. That throw, not any host defect, is what #126 recorded as \"the composer\n // refuses plugin writes\"; the API works exactly as documented once used correctly.\n const refuse = (why: string): void => {\n console.warn(`[client:prompt] click-to-draft refused: ${why}`)\n // Even the correct call can be refused honestly (phase guards). The fallback that always works:\n // put the offer on the CLIPBOARD and say so — the maintainer's own design — so the human pastes\n // into the composer, edits, sends.\n const copied = copyToClipboard(state.text ?? '')\n dispatch({ t: 'note', note: copied\n ? 'The composer refused this write (' + why.slice(0, 60) + ') — the prompt is COPIED: paste it into the input to edit, or press Run \\u25B6 to send as-is.'\n : 'The composer refused this write (' + why.slice(0, 60) + ') — press Run \\u25B6 to send the offer as-is, or copy the text above.' })\n }\n let wrote = false\n try {\n // The contract path first: captureInsertion() -> insertText(text, span). On hosts where the\n // two-argument call is unreachable from a dock (measured on 0.2.0-rc.2: the span guard sees\n // undefined even when we pass a real span), this throws or returns false and setDraft takes\n // over below — never a dead end.\n const span = typeof inputActions.captureInsertion === 'function' ? inputActions.captureInsertion() : null\n if (span !== null && span !== undefined) wrote = inputActions.insertText(state.text, span as never) === true\n } catch { wrote = false }\n if (!wrote && typeof inputActions.setDraft === 'function') {\n try { inputActions.setDraft(state.text); wrote = true } catch { wrote = false }\n }\n if (!wrote) { refuse('neither insertText nor setDraft was accepted'); return }\n // #295: the handoff SUCCEEDED — fold the bar back to its normal size. The gesture the\n // maintainer leans on ends tidy: the words are in the composer, the pane is closed, and\n // the offer stays in the row (Run still works; the next turn's pull refreshes it anyway).\n dispatch({ t: 'collapse' })\n // Verify what the human will SEE: the words in the editor, or in the persisted draft store\n // (setDraft writes the store; some builds mirror it into the editor only at mount). Neither?\n // say so plainly — Run still works, and silence is the one outcome never allowed.\n const head = state.text.slice(0, 24)\n setTimeout(() => {\n try {\n const el = composerBox()\n const dom = el === null ? false : (('value' in el ? String((el as unknown as { value: string }).value ?? '') : (el.innerText ?? '')).includes(head))\n const stored = Object.entries(localStorage).some(([, v]) => String(v).includes(head))\n if (!dom && !stored) refuse('the write was accepted but nothing holds the text')\n } catch { /* diagnostics never break the gesture */ }\n }, 400)\n return\n return\n }\n if (typeof inputActions?.setDraft === 'function') {\n inputActions.setDraft(state.text)\n dispatch({ t: 'collapse' }) // #295: same fold on the fallback write path\n return\n }\n console.warn('[client:prompt] click-to-draft refused: this host exposes neither insertText nor setDraft')\n }\n\n // Called unconditionally through a stable fallback, so the hook order cannot change between renders.\n return h('div', { className: 'dsh-chapters_promptDock', 'data-prompt-bar': 'true' },\n h('div', { className: `dsh-chapters_promptBar${state.expanded ? ' dsh-chapters_promptExpanded' : ''}` },\n h('span', { className: 'dsh-chapters_promptGlyph' }, h(Glyph)),\n h('span', { className: 'dsh-chapters_promptLabel' }, barLabel(state as PromptBarState) ?? ''),\n // #300: a goal re-cut still never auto-runs (the host reserves goal edits for a human turn), but the\n // fact now rides barLabel's REPLACEMENT text — the old second-message span overflowed the one-line\n // row and clipped the composer. Run's own tooltip (below) still explains the keystroke requirement.\n (() => {\n // #282+#309: one sentence (rowTooltip) for aria-label AND the bubble; the bubble rides the\n // HOST's themed tooltip seat (withTooltip) like the door buttons — the hard-coded native title\n // here was the black-bubble foreign style the maintainer flagged. nativeTitle appears only when\n // the host seat is absent; never both. Read per render, so the occupied-composer warning\n // tracks typing without a private clock.\n const rowTip = rowTooltip(state.expanded, composerHasText())\n return withTooltip(rowTip, h('button', {\n type: 'button', className: 'dsh-chapters_promptText',\n 'aria-label': rowTip,\n ...nativeTitle(rowTip),\n disabled: state.running,\n onClick: populate,\n }, state.expanded\n ? h('span', { className: 'dsh-chapters_promptFull' }, state.text ?? '')\n : h('span', { className: 'dsh-chapters_promptEllipsis' }, lineFor(state))) as ReactElement<Record<string, unknown>>)\n })(),\n ...(state.note === '' ? [] : [h('span', { key: 'note', className: 'dsh-chapters_promptNote', role: 'status' }, state.note)]),\n ...(state.error === '' ? [] : [h('span', { key: 'err', className: 'dsh-chapters_promptError', role: 'alert' }, state.error)]),\n h('div', { className: 'dsh-chapters_promptActions' },\n // #295: the collapse control lives in the ACTION row (right edge = top-right of the bar),\n // never floated over the prompt text — the pane-corner version made text and button fight\n // for the same pixel. The reducer's 'collapse' case keeps the offer; this is reading, not dismissal.\n ...(state.expanded ? [h(Action, {\n key: 'collapse',\n label: 'Collapse the suggested prompt', glyph: '▾', className: 'dsh-chapters_promptCollapse', // #309: it folds DOWN\n onClick: () => { dispatch({ t: 'collapse' }) },\n })] : []),\n h(Action, {\n label: 'Run the suggested next step', glyph: '▶', onClick: run, disabled: busy,\n ...(state.text === null || state.text === '' || !canRunHere(state) ? { disabled: true } : {}),\n ...(state.intent === 'goal-edit'\n ? { title: 'Goal edits need a human turn. Run still works; autorun will never do this one.' }\n : {}),\n }),\n h(Action, {\n label: state.autorun === 'armed' ? 'Autorun off' : 'Autorun',\n glyph: state.autorun === 'armed' ? '⟳' : '⟲',\n disabled: autorunDisabled,\n ...(autorunDisabled\n ? { title: 'Autorun needs the host to publish an idle signal; this build does not, so nothing would fire safely.' }\n : {}),\n // A SERVER write, like `off` below. Flipping local state alone was the defect: `refresh()` re-reads the\n // loop state (`:193`), the server still says `disarmed`, and the label snaps back — so the user watched\n // their own click be refused and the loop could never be started from the bar. The command surface is\n // `/chapters-prompt autorun on|off` (src/commands.ts:462-478), which also reports the goal displacement.\n onClick: () => {\n void (async () => {\n const arm = state.autorun !== 'armed'\n if (exec !== undefined) await exec(`/chapters-prompt autorun ${arm ? 'on' : 'off'}`)\n dispatch({ t: 'autorun', on: arm })\n // #194: in push mode the setAutorun append carries the truth back — a refresh here\n // would be a command run for a fact already in flight.\n if (!pushLiveRef.current) await refresh()\n })()\n },\n }),\n h(Action, {\n label: 'Turn prompt suggestions off for this session', glyph: '✕',\n // #291: off-SESSION — the scope this label has always promised. It used to execute the\n // plane-wide `off` verb (clears the model for EVERY session); one exploratory click here\n // silenced the whole plane while the row said \"for this session\". Generation stops for\n // this session, the model is kept, and the bar disappears instead of lingering stale.\n onClick: () => { void (async () => { if (exec !== undefined) await exec('/chapters-prompt off-session'); dispatch({ t: 'off' }); if (sessionId !== undefined) { const offEntry = { ev: { t: 'polled', status: 'off' } as CacheEntry['ev'], autorun: null, at: Date.now() }; stateCache.set(sessionId, offEntry); writePersisted(sessionId, offEntry) } })() },\n }),\n ),\n ),\n )\n}\n","/**\n * The chapters preset id — ONE source, client-safe.\n *\n * The literal 'chapters' had durable meaning in three places (the server's preset declaration, the\n * seventh archive moment's header gate, and the client's door visibility predicate per #372), and\n * #353 already caught a second literal copy drifting outside its predicate. `src/preset.ts` is the\n * declaration's home but imports cordis — the client bundle cannot load it — so the id lives HERE,\n * with zero imports, and preset.ts re-exports it so every existing server importer is unchanged.\n *\n * @module dsh-chapters/src/preset-id\n */\nexport const CHAPTERS_PRESET_ID = 'chapters'\n","/**\n * The client door runner: the two deterministic archive doors, executed over\n * `remote.commands` and followed by a SWITCH to the fresh child.\n *\n * ONE runner, two rows. The server side keeps the same discipline — both doors\n * come from `deterministicCommand(door)` in src/tools.ts, and a unit row pins\n * that they archive identically. Copy-pasting this body is how the two would\n * drift apart, so there is exactly one implementation and a table of rows.\n *\n * `chapters-continue` ships only as a composer command; without a button here\n * the child is created correctly and the UI shows nothing, which reads as\n * \"nothing happened\". The row is the missing affordance, not new logic.\n *\n * React-free on purpose: the primitives package pulls CSS modules the node\n * test runner cannot load, so the testable half lives here and index.ts is the\n * thin chrome that renders these rows as buttons (tests/unit/client-doors.test.ts).\n *\n * @module dsh-chapters/src/client/doors\n */\n\n/** Structural slice of the aggregated remote service (@deepseek-ai/dsh-api-remotes).\n * `remote.commands` must ALSO appear in inject — the federation gates each\n * sub-service individually (the live feedback package declares\n * remote.messageFeedback beside remote for exactly this reason). */\nimport { CHAPTERS_PRESET_ID } from '../preset-id.ts'\n\nexport interface ClientRemote {\n commands?: {\n execute(sessionId: string, line: string, attachments: readonly unknown[]): Promise<{\n ok?: boolean\n value?: { commandId?: string; result?: { kind?: string; text?: string } }\n error?: { code?: string; message?: string }\n }>\n }\n}\n\n/** The client sessions service (dsh-client-runtime): open() lives on the\n * prototype; everything else on the surface stays untrusted and unused. */\nexport interface ClientSessions {\n open(sessionId: string): unknown\n}\n\nexport interface DoorResult {\n ok: boolean\n message: string\n}\n\n/**\n * #372 — the host's OWN per-session preset fact. The shape is measured, not invented:\n * `dsh-client-ui-agent-preset/lib/client.js` resolves its label through\n * `session?.projectionValues?.agentPreset`, and `dsh-api-session-controller` documents the field as\n * \"current host-computed projection values retained by the object layer\". We read the SAME row the\n * list store already gives us (rosterIds' shape) — no inference, no hardcoded preset name.\n * null means the fact is NOT READABLE — which is UNKNOWN, never \"standard\" (#77's roster\n * discipline applied to the preset: absence invented from unreadability is the same lie).\n */\nexport function presetOfSession(sessions: ClientSessions | undefined, sessionId: string): string | null {\n try {\n const snap = (sessions as unknown as { list?: { getSnapshot?: () => unknown } } | undefined)?.list?.getSnapshot?.()\n const row = (snap as { byId?: Record<string, { projectionValues?: Record<string, unknown> }> } | undefined)?.byId?.[sessionId]\n const value = row?.projectionValues?.agentPreset\n return typeof value === 'string' && value !== '' ? value : null\n } catch { return null }\n}\n\n/**\n * The ONE visibility predicate for the realm-scoped door rows (#372). Unknown keeps the rows —\n * the click path answers with the named refusal, so fail-open is never fail-silent; a RESOLVED\n * foreign preset hides them, because those commands genuinely do not exist in that session.\n */\nexport function doorActionsVisibleFor(preset: string | null): boolean {\n return preset === null || preset === CHAPTERS_PRESET_ID\n}\n\n/**\n * One assistant-action row. `noun` is the server's own word for the child in\n * its success text (`branch` / `continuation`), so the fallback wording and the\n * title regex both track the door without a second implementation.\n */\nexport interface DoorAction {\n /** The slot registration id. */\n id: string\n /** Position in the assistant action row. */\n order: number\n /** Button + tooltip label, and the accessible name the e2e specs select on. */\n label: string\n /** The host command this row executes — the ONLY semantic difference at runtime. */\n command: string\n /** The noun in `${noun} “title” is session ch-…`. */\n noun: string\n /** The row's glyph (16×16 viewBox, single path). */\n iconPath: string\n}\n\nexport const DOOR_ACTIONS: readonly DoorAction[] = [\n {\n id: 'chapters-fork',\n order: 30,\n label: 'Fork with chapters',\n command: '/chapters-fork',\n noun: 'branch',\n iconPath: 'M5 3.25a2.25 2.25 0 1 0-1.5 2.12v5.26a2.25 2.25 0 1 0 1.5 0V9h5a2.25 2.25 0 0 0 2.25-2.25v-1.4a2.25 2.25 0 1 0-1.5 0v1.4A.75.75 0 0 1 10 7.5H5V5.37A2.25 2.25 0 0 0 5 3.25Z',\n },\n {\n id: 'chapters-continue',\n order: 31,\n label: 'Continue with chapters',\n command: '/chapters-continue',\n noun: 'continuation',\n iconPath: 'M1 8a.75.75 0 0 1 0-1.5h9.44L7.72 3.28a.75.75 0 1 1 1.06-1.06l3.5 3.5.53.53-.53.53-3.5 3.5a.75.75 0 1 1-1.06-1.06L10.44 9.5H1Zm13-5.25v10.5a.75.75 0 0 1-1.5 0v-10.5a.75.75 0 0 1 1.5 0Z',\n },\n]\n\n/** Pull the child id out of either door's durable success text — both end in\n * `… is session ch-…` (src/tools.ts), so this regex is door-agnostic. */\n/**\n * Which build of THIS file produced a door note (#77). When the live probe reported a roster\n * trace of `missing → missing → missing` — meaning adoption should have fired three times — while\n * showing no adoption outcome at all, the first question stopped being \"why did the client refuse\"\n * and became \"did the browser run the code I am reading?\". A note that names its own build makes\n * that a glance instead of an archaeology session into symlinked plugin trees.\n */\nexport const DOOR_BUILD = '2026-10-22T23:55 door-build-stamp'\n\nexport const CHILD_ID = /is session (ch-[\\w-]+)/\n\n/** The quoted title the door gave the child, matched by its OWN noun so a\n * refusal or an unrelated quote cannot pass for it. */\nexport const doorTitle = (noun: string): RegExp => new RegExp(`${noun} \\\\u201C([^\\\\u201D]+)\\\\u201D is session`)\n\n/**\n * A refusal reason that can never render as nothing. `String(err.message ?? err)` is `''` for a\n * host error built with an empty message, and an empty reason disappears from the note — the\n * reader then concludes \"no refusal happened\", which is the opposite of the truth (#77).\n */\nfunction refusalReason(error: unknown): string {\n const raw = error instanceof Error ? error.message : String(error)\n const trimmed = raw.trim()\n const named = trimmed === '' ? (error instanceof Error && error.name.trim() !== '' ? error.name : '') : trimmed\n const base = named === '' ? (error === null ? 'null thrown' : typeof error) : named\n return base.replace(/\\s+/g, ' ').slice(0, 90)\n}\n\n/**\n * Is the child in the client's OWN roster? This is the question that separates two very\n * different failures, and the door used to report the symptom without it:\n * - the client never learned the session exists (roster: missing) → the fix is server-side\n * publication, and no amount of clicking `open` will ever work;\n * - the client knows it and `open` still did nothing (roster: contains) → a navigation bug.\n * Measured host 0.2.0-rc.2: the sessions service exposes `projectList`, `refresh`, `retain`,\n * `handleSessionAdded` — the roster is a projection the client fills from control frames.\n */\n/**\n * The client's own session ids, or `null` when the store cannot be read. ONE reader for both\n * the note and the adoption decision, so the door never acts on a verdict it did not report.\n */\nfunction rosterIds(sessions: ClientSessions | undefined): Set<string> | null {\n const store = (sessions as unknown as { list?: { getSnapshot?: () => unknown } })?.list\n if (typeof store?.getSnapshot !== 'function') return null\n const snap = store.getSnapshot()\n const ids = new Set<string>()\n if (Array.isArray((snap as { ids?: unknown[] } | undefined)?.ids)) {\n for (const id of (snap as { ids: unknown[] }).ids) ids.add(String(id))\n } else if ((snap as { byId?: object } | undefined)?.byId !== undefined) {\n for (const k of Object.keys((snap as { byId: object }).byId)) ids.add(k)\n } else return null\n return ids\n}\n\nfunction rosterNote(sessions: ClientSessions | undefined, child: string): string {\n try {\n // The host's client store shape is `list.getSnapshot() → { ids, byId, phase }`.\n // `projectList()` turned out to be a MUTATOR that returns undefined (measured), so the first\n // version of this note printed \"0 sessions\" about a conversation that visibly had one — the\n // repo's own `listEvents` lesson (\"measure the SHAPE, not the presence\"), repeated by me in\n // the same week. Read the store; when it isn't reachable, presence is UNKNOWN and the note\n // says that rather than inventing an absence.\n const ids = rosterIds(sessions)\n if (ids === null) {\n const store = (sessions as unknown as { list?: { getSnapshot?: () => unknown } })?.list\n const shape = typeof store?.getSnapshot !== 'function' ? 'no list store on the service' : 'snapshot unreadable'\n return ` (roster: ${shape} — presence of ${child.slice(0, 11)}… is UNKNOWN, not absent)`\n }\n if (ids.size === 0) return ` (roster: empty — presence of ${child.slice(0, 11)}… is UNKNOWN, not absent)`\n const n = ids.size\n return ids.has(child)\n ? ` (roster: contains ${child.slice(0, 11)}…, ${String(n)} sessions — open() is the failure)`\n : ` (roster: MISSING, ${String(n)} sessions — the client never catalogued this session)`\n } catch { return '' }\n}\n\n/** The service's own method names, as a hint attached to a failure note (never a guess). */\nfunction verbsNote(sessions: ClientSessions | undefined): string {\n try {\n const svc = sessions as unknown as Record<string, unknown> | undefined\n if (svc === null || svc === undefined || typeof svc !== 'object') return ' (sessions service: absent)'\n // Measured: `Object.keys(svc)` returned NOTHING for the real service, because the host\n // puts its verbs on the PROTOTYPE (a class instance), not as own keys. A diagnostic that\n // reports \"no methods\" about a working service is worse than none — walk the chain.\n const found = new Set<string>()\n let node: unknown = svc\n // Stop at Object.prototype: its four legacy accessors are not service verbs, and listing\n // them pushed the real names past the cap on the first live run.\n for (let depth = 0; depth < 6 && node !== null && node !== undefined && node !== Object.prototype; depth++) {\n for (const key of Object.getOwnPropertyNames(node as object)) {\n if (key === 'constructor') continue\n try { if (typeof (svc as Record<string, unknown>)[key] === 'function') found.add(key) } catch { /* getter that throws — not a verb we can use either */ }\n }\n node = Object.getPrototypeOf(node)\n }\n const verbs = [...found].sort().slice(0, 24)\n return verbs.length === 0 ? ' (sessions service: no methods on the chain)' : ` (sessions verbs: ${verbs.join(', ')})`\n } catch { return ' (sessions service: unreadable)' }\n}\n\nfunction openByService(\n sessions: ClientSessions | undefined,\n sessionId: string,\n /** #77: adopt (and re-project) only when the client's own roster is missing this session.\n * `onAfter` reports the roster at the instant after adoption, before any later refresh can\n * discard the mutation — the difference between an ordering bug and a publication gap. */\n adopt?: { needed: boolean, onRefused: (reason: string) => void, onSubscribeRefused?: (reason: string) => void, onAfter: (seen: boolean | null) => void, onStep?: (step: string) => void },\n nav?: { openSession?: (id: string) => unknown },\n): Promise<boolean> {\n return (async () => {\n const svc = sessions as unknown as {\n open?: (id: string) => unknown; refresh?: () => unknown; projectList?: () => unknown\n create?: (opts: { sessionId?: string }) => unknown\n using?: (id: string, opts: { source: string }, fn: () => Promise<void>) => unknown\n } | undefined\n // #77, the actual root cause: `sessions.open` DOES NOT EXIST on this host. The sessions\n // service offers create/fork/using/retain/binding/refresh; the host's own fork button calls\n // `ctx.uiWorkspace.openSession(childId)` (`dsh-client-ui-chat/lib/client.js`). The line here\n // used to be `if (typeof svc?.open !== 'function') return false`, so every service attempt\n // since the door was written returned false on line one and the note blamed the client's\n // roster for a verb that was never there.\n if (svc === undefined) return false\n const navigate = typeof nav?.openSession === 'function'\n ? (id: string): unknown => nav.openSession!(id)\n : typeof svc?.open === 'function'\n ? (id: string): unknown => svc.open!(id)\n : null\n if (navigate === null) {\n adopt?.onStep?.('no-verb')\n return false\n }\n try { await svc.refresh?.() } catch { /* refresh best-effort */ }\n // #57: re-project the client's session catalog. The host does this ITSELF after every\n // create and fork — `dsh-api-session-controller/lib/client.js`, `create()` and `fork()`\n // both end in `this.projectList()` — because a session the client has never catalogued is\n // not addressable by `open()` no matter how often you call it. A plugin-created child is\n // exactly that case: durable, workspace-attached, absent from the client's roster. Measured\n // on 0.2.0-rc.2: without this the door created the child, `open` resolved, and the app\n // stayed on the parent (the door's own note now says `roster: …` so this is never a guess).\n try { svc.projectList?.() } catch { /* best-effort, like refresh */ }\n // #77: adopt-and-catalogue. `manager.create()` is documented \"on success merge into\n // summaries immediately (no wait for the next refresh)\" and forwards a caller-owned\n // `sessionId`, while the server ADOPTS a persisted id instead of authoring a second session\n // (`create(request)` → `ensureSession(sessionId, cwd, request.sessionId !== undefined, …)`).\n // Nothing about the child's content is authored here — the seed notice was committed\n // host-plane long before this call — this only lets the client see what the host already\n // knows. A refusal is reported to the caller, never swallowed.\n if (adopt?.needed === true && typeof svc.create === 'function') {\n // the block narrates itself: entry first, then whichever way it left. The live note once\n // said \"try\" from the runner and showed nothing downstream — with this line, an absent\n // `enter-create` IS the answer instead of a mystery.\n adopt.onStep?.('enter-create')\n try {\n await svc.create({ sessionId })\n adopt.onStep?.('settle-create')\n try { svc.projectList?.() } catch { /* re-project again, now that a mutation exists */ }\n // the momentary read is the whole point: a later `refreshList()` reassigns the manager's\n // mutations from the server result, so an adoption that DID land is invisible by the time\n // the last attempt fails. Report what was true at the instant it mattered.\n const after = rosterIds(sessions)\n adopt.onAfter?.(after === null ? null : after.has(sessionId))\n } catch (error) {\n adopt.onStep?.('refuse-create')\n adopt.onRefused(refusalReason(error))\n }\n }\n // #77, second candidate: if adoption left the child out of the roster, SUBSCRIBE to it.\n // `using(target, {source}, fn)` is the host's own way to address a session that is not\n // currently displayed (`sessions/service.js`: retain → `manager.get(id).open()`). A refusal is\n // reported exactly like adoption's. No URL route exists as an alternative — checked every\n // dsh-client-* bundle: the only `/session/` strings are resource addresses for files.\n if (adopt?.needed === true && typeof svc.using === 'function' && rosterIds(sessions)?.has(sessionId) === false) {\n adopt.onStep?.('enter-using')\n try {\n await svc.using(sessionId, { source: 'dsh-chapters-door' }, async () => undefined)\n adopt.onStep?.('settle-using')\n try { svc.projectList?.() } catch { /* best-effort, like the others */ }\n const seen = rosterIds(sessions)\n adopt.onAfter?.(seen === null ? null : seen.has(sessionId))\n } catch (error) {\n adopt.onStep?.('refuse-using')\n adopt.onSubscribeRefused?.(refusalReason(error))\n }\n }\n // The store must know the session before open() resolves it; a child\n // created seconds ago is only server-known until refresh lands. Retry\n // open briefly across that window.\n const started = Date.now()\n for (;;) {\n try { navigate(sessionId); return true } catch {\n if (Date.now() - started > 4_000) return false\n await new Promise((r) => setTimeout(r, 250))\n }\n }\n })()\n}\n\n/**\n * Fallback path: expand collapsed groups / show-more buttons, then click the\n * newest treeitem whose label contains the child title (newest-updated sorts\n * first, so the first match is the fresh child).\n */\nasync function openBranchRow(title: string, budgetMs = 4_000): Promise<boolean> {\n if (typeof document === 'undefined') return false\n const needle = title.toLowerCase()\n const tryClick = (): boolean => {\n const rows = Array.from(document.querySelectorAll<HTMLElement>('[role=\"treeitem\"]'))\n const hit = rows.find((row) => (row.textContent ?? '').toLowerCase().includes(needle))\n if (hit === undefined) return false\n hit.click()\n return true\n }\n const clickMore = (): number => {\n const buttons = Array.from(document.querySelectorAll<HTMLElement>('button'))\n .filter((b) => /more sessions|ungrouped/i.test(b.textContent ?? '') && b.getAttribute('aria-expanded') !== 'true')\n for (const b of buttons) b.click()\n return buttons.length\n }\n const started = Date.now()\n let expansions = 0\n while (Date.now() - started < budgetMs) {\n if (tryClick()) return true\n if (expansions < 4 && clickMore() > 0) { expansions += 1; await new Promise((r) => setTimeout(r, 250)); continue }\n await new Promise((resolve) => setTimeout(resolve, 150))\n }\n return tryClick()\n}\n\nexport function makeDoorRunner(\n remote: ClientRemote,\n sessions: ClientSessions | undefined,\n door: DoorAction,\n /**\n * \"Is THIS session the one the client is now showing?\" #54: `sessions.open()` returns\n * void, so a call that resolves proves the request was accepted, not that the app\n * switched. Measured on host 0.2.0-rc.2: no note element (open resolved), yet\n * `dsh.sessions.current` still named the parent and the child was absent from the\n * sidebar after a full reload — the user got silence and a missing session. Absent\n * (a client that cannot answer) the runner keeps the old behavior, and the wiring is\n * pinned by a row so production can never quietly drop it.\n */\n verifySwitched?: (childSessionId: string) => Promise<boolean>,\n /**\n * #77: how many times to re-pull the client's list, re-project and re-open. The session\n * manager documents `refreshList()` as \"single-flight within one Host generation\"\n * (`dsh-api-session-controller/lib/types/client/sessions/manager.js`), so a pull issued while\n * another is in flight can resolve from the STALE result — precisely the moment a session\n * created microseconds ago is missing. Retrying is both the fix candidate and the measurement:\n * which attempt lands tells us whether this is ordering (ours) or silence (host-side).\n * A client with no `refresh` verb gets exactly ONE attempt — re-asking `open` against a roster\n * we cannot re-pull would be theater.\n */\n opts?: { attempts?: number, attemptPauseMs?: number, navigator?: { openSession?: (id: string) => unknown } },\n): (sessionId: string, anchorSeq?: number | null) => Promise<DoorResult> {\n return async function run(sessionId: string, anchorSeq?: number | null): Promise<DoorResult> {\n try {\n if (remote.commands?.execute === undefined) return { ok: false, message: 'commands remote unavailable' }\n // #372: the gate runs BEFORE any wire call. A realm-scoped command asked of a session whose\n // preset RESOLVES to something else cannot resolve — answering with the host fact the dock\n // already reads is honest; firing into a guaranteed mystery is the dead button this issue was\n // filed for. UNKNOWN preset falls through: the named failure below still covers the wire.\n {\n const preset = presetOfSession(sessions, sessionId)\n if (preset !== null && !doorActionsVisibleFor(preset)) {\n return { ok: false, message: `Chapters ${door.noun} needs the chapters preset realm — this session composes \"${preset}\". Switch this session's preset or run the door from a chapters session.`.slice(0, 140) }\n }\n }\n // #221: the clicked message's seq rides the command as its first token — the server anchors\n // the archive at the last completed turn AT OR BEFORE it. Absent ⇒ today's behavior (the end\n // of the session), byte-identical to the pre-#221 line.\n const line = typeof anchorSeq === 'number' && Number.isFinite(anchorSeq) ? `${door.command} ${String(Math.trunc(anchorSeq))}` : door.command\n const res = await remote.commands.execute(sessionId, line, [])\n if (res.ok !== true) return { ok: false, message: (res.error?.message ?? `the ${door.noun} failed — its command lives in the chapters preset realm`).slice(0, 90) }\n const result = res.value?.result\n const text = typeof result?.text === 'string' ? result.text : ''\n if (result?.kind !== 'success') return { ok: false, message: (text || `the ${door.noun} was refused — see the command result`).slice(0, 90) }\n const child = CHILD_ID.exec(text)?.[1]\n if (child === undefined) return { ok: true, message: `${door.noun} created — appearing in the sidebar` }\n const switchedOnce = async (): Promise<boolean> => {\n if (verifySwitched === undefined) return true\n try { return await verifySwitched(child) } catch { return false }\n }\n const canRepull = typeof (sessions as unknown as { refresh?: unknown } | undefined)?.refresh === 'function'\n const maxAttempts = canRepull ? (opts?.attempts ?? 3) : 1\n let tried = 0\n let adoptRefusal = ''\n let subscribeRefusal = ''\n // #77: what the roster reader answered AT EACH DECISION, not only at the end. The live\n // probe reported MISSING after three attempts while neither candidate fired, which can\n // only mean the reader disagreed with itself over time — and a note that says one number\n // cannot show that.\n const rosterTrace: string[] = []\n const steps: string[] = []\n let adoptSaw: boolean | null | undefined\n for (let i = 0; i < maxAttempts; i++) {\n tried += 1\n // decide adoption from the SAME reader the note reports, so the door never acts on a\n // verdict it did not tell the user about; an unreadable roster is not \"missing\"\n const ids = rosterIds(sessions)\n // Loaded-but-empty is a DECISION (the child is not there → try the sanctioned paths);\n // unreadable is UNKNOWN and must not invent a session (#77: the strict form here meant\n // neither candidate ever ran in the live probe, and its silence looked like a result).\n const needed = ids !== null && !ids.has(child)\n // `+c` / `+u` = the candidate verbs are present on the injected service AT THAT MOMENT.\n // Without this, a note that says the roster was missing while no adoption outcome appears\n // is uninterpretable: either the code never ran, or the service has no create to call.\n const svcShape = sessions as unknown as { create?: unknown, using?: unknown, open?: unknown } | undefined\n // +c create, +u using, +o sessions.open, +w workspace navigator — the exact predicates\n // the door branches on, so a note can be read instead of re-derived from source\n rosterTrace.push(`${ids === null ? 'unknown' : ids.size === 0 ? 'empty' : ids.has(child) ? 'has' : 'missing'}${typeof svcShape?.create === 'function' ? '+c' : '-c'}${typeof svcShape?.using === 'function' ? '+u' : '-u'}${typeof svcShape?.open === 'function' ? '+o' : '-o'}${typeof opts?.navigator?.openSession === 'function' ? '+w' : '-w'}`)\n if (await openByService(sessions, child, {\n needed,\n onRefused: (reason) => { adoptRefusal = reason },\n onSubscribeRefused: (reason) => { subscribeRefusal = reason },\n onAfter: (seen) => { adoptSaw = seen },\n onStep: (step) => { if (!steps.includes(step)) steps.push(step) },\n }, opts?.navigator) && await switchedOnce()) return { ok: true, message: '' }\n // #358: NO `.unref()` on an awaited pause. The continuation depends on this very timer, so\n // releasing it from the event loop's refcount lets Node exit with the promise unresolved — the\n // door call never returns at all. Observed as 21 of 28 rows in client-doors.test.ts cancelled\n // by \"Promise resolution is still pending but the event loop has already resolved\" whenever the\n // retry path is the only pending work (Node 22; CI on the pinned Node 24 does not hit it, which\n // is precisely how it survived — an unobserved hang is not an absent one).\n // Browsers are unaffected either way: `setTimeout` returns a number there and `.unref` does not\n // exist, so the optional call was always a no-op in the only environment this ships to. The\n // three other waits in this file already do it correctly without one.\n if (i + 1 < maxAttempts) await new Promise((r) => { setTimeout(r, opts?.attemptPauseMs ?? 300) })\n }\n // the service path did not take — the sidebar row is the same affordance a human uses\n const title = doorTitle(door.noun).exec(text)?.[1]\n if (title !== undefined && await openBranchRow(title) && await switchedOnce()) return { ok: true, message: '' }\n // #54: a child that is created but not shown is a DIFFERENT fact from one the user\n // has to open by hand, and the message must not blur them.\n // #56/#57: the note must be ACTIONABLE. \"the app did not switch\" is true and useless;\n // naming the verbs the injected service actually exposes turns one failure into the\n // diagnosis (is there a refresh/reload to call, or is `open` the only verb and the\n // omission server-side?). A detected failure that isn't delivered is the same bug.\n return verifySwitched === undefined\n ? { ok: true, message: `${door.noun} created — open it in the sidebar` }\n : { ok: true, message: `${door.noun} created — the app did not switch after ${String(tried)} attempt${tried === 1 ? '' : 's'}; open it from the sidebar [roster per attempt: ${rosterTrace.join(' → ')}] [tried: ${steps.length === 0 ? 'none' : steps.includes('no-verb') ? 'no open or openSession verb on any injected service' : steps.join(', ')}] (build: ${DOOR_BUILD})${adoptRefusal === '' ? '' : ` (adoption refused: ${adoptRefusal})`}${subscribeRefusal === '' ? '' : ` (subscribe refused: ${subscribeRefusal})`}${adoptSaw === undefined ? '' : ` (right after adopt: ${adoptSaw ? 'contains' : 'missing'} ${child.slice(0, 15)})`}${rosterNote(sessions, child)}${verbsNote(sessions)}` }\n } catch (error) {\n return { ok: false, message: String((error as Error)?.message ?? error).slice(0, 90) }\n }\n }\n}\n\n/**\n * Execute a host command line for one session and return its text, or '' when the command plane is\n * unavailable. The bar's `state` pull and `off` write ride this, because it is the ONE place the client\n * talks to the wire: the guard row \"there is no second runner body in the client chrome\" exists to keep\n * `index.ts` as registration chrome, and a duplicated `commands.execute` in two files is how a wire\n * behaviour drifts from its own test (#59's one-predicate rule, applied to the transport).\n */\nexport async function runCommandText(remote: ClientRemote | undefined, sessionId: string, line: string): Promise<string> {\n const exec = remote?.commands?.execute\n if (exec === undefined) return ''\n const res = await exec(sessionId, line, [])\n if (res.ok !== true) return ''\n return res.value?.result?.text ?? ''\n}\n","/**\n * dsh-chapters client entry: the per-message door buttons.\n *\n * Registers the two deterministic archive doors into the assistant action row\n * (`conversation.chat.assistant-actions` — the slot the official feedback\n * package populates beside copy/branch). Clicking one executes its host\n * command — `/chapters-fork`, `/chapters-continue` — through `remote.commands`,\n * the exact wire the composer's input line rides, then SWITCHES the app to the\n * fresh child:\n *\n * 1. `sessions.open(child)` — the client sessions service carries open() on\n * its prototype (Playwright-verified against this host; a keys-dump alone\n * hid it, which is why an earlier round wrongly gave up on this path);\n * 2. fallback: click the child's sidebar row after expanding collapsed\n * groups (plugin children can render under collapsed 'Ungrouped' heads);\n * 3. last resort: an inline note — the child is durable either way.\n *\n * There is deliberately NO second implementation of door logic here: the\n * buttons are mouths for the host commands (watermark, segmentation, budget,\n * titles, refusal-with-numbers all server-side, all tested), and the runner\n * they share is `src/client/doors.ts` — one body, one row per door. The purity\n * gate in tsdown.client.config.ts keeps this file cross-plugin-free.\n *\n * @module dsh-chapters/src/client\n */\n\nimport { createElement as h, useCallback, useEffect, useRef, useState, type ReactElement } from 'react'\n// The host's own tooltip bubble — a platform module served by the loader table,\n// external like react. Every action in this row labels through it.\nimport { withTooltip, nativeTitle } from './tooltip.ts'\nimport { PromptDock } from './prompt-dock.ts'\nimport { DOOR_ACTIONS, doorActionsVisibleFor, makeDoorRunner, presetOfSession, runCommandText, type ClientRemote, type ClientSessions, type DoorAction, type DoorResult } from './doors.ts'\n\ninterface ClientSlots {\n inject(name: string, factory: () => unknown): void\n register(registration: Record<string, unknown>, component: unknown): unknown\n}\n\ninterface Ctx {\n slots: ClientSlots\n get(name: string): unknown\n}\n\n// #77: `uiWorkspace` is not optional in practice — it owns `openSession(target)`, the verb the\n// host's own fork button uses (`ctx.uiWorkspace.openSession(childId)` in dsh-client-ui-chat).\n// `sessions` has no `open` at all, so without this row the door has never had a way to switch.\nexport const inject = ['slots', 'remote', 'remote.commands', 'sessions', 'uiWorkspace'] as const\n\n/** Props composed by the slot framework: owner (`messageId`) + our injected verb. */\ninterface DoorActionProps {\n messageId: string\n run: () => Promise<DoorResult>\n /** #372: the factory evaluates the host preset projection at render; false hides the row. */\n visible?: () => boolean\n}\n\n/**\n * Style parity with the native IconActions row: rules copied verbatim from the\n * host's MessageIconActions module (`._xzv4MW_action` in dsh-client-ui-chat's\n * compiled client + the feedback package's :disabled) — same metrics, tokens,\n * hover. Update this string if the host restyles its action row. Both doors\n * share these metrics.\n *\n * The final rule hides the native branch action IN THE MESSAGE ROW only\n * (user-approved cosmetic decision, docs/architecture.md): built-in chrome, so\n * the selector is its accessible label scoped to action-row buttons; both\n * locale spellings covered. If the host rewords the label the button simply\n * reappears — fails open, visibly.\n */\nconst CSS = [\n '.dsh-chapters_forkAction{width:calc(28px + var(--dsh-content-font-delta,0px));height:calc(28px + var(--dsh-content-font-delta,0px));color:var(--dsw-alias-label-tertiary);cursor:pointer;background:0 0;border:none;border-radius:28px;justify-content:center;align-items:center;padding:6px;display:inline-flex}',\n '.dsh-chapters_forkAction svg{width:calc(15px + var(--dsh-content-font-delta,0px));height:calc(15px + var(--dsh-content-font-delta,0px))}',\n '.dsh-chapters_forkAction:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary)}',\n '.dsh-chapters_forkAction:disabled{cursor:default;opacity:.4}',\n '.dsh-chapters_forkNote{color:var(--dsw-alias-label-tertiary);padding-left:4px;font-size:13px;line-height:20px}',\n 'button[class*=\"_action\"][aria-label=\"Branch into a new conversation\"],button[class*=\"_action\"][aria-label=\"\\u5728\\u65b0\\u5bf9\\u8bdd\\u4e2d\\u5206\\u652f\"]{display:none !important}',\n].join('\\n')\nconst CSS_TAG_ID = 'dsh-chapters/assistant-action.css'\n\nfunction injectStyles(): void {\n try {\n if (typeof document === 'undefined' || document.querySelector(`style[data-plugin-css=${JSON.stringify(CSS_TAG_ID)}]`) !== null) return\n const tag = document.createElement('style')\n tag.dataset.plugin = 'dsh-chapters'\n tag.dataset.pluginCss = CSS_TAG_ID\n tag.textContent = CSS\n document.head.appendChild(tag)\n } catch { /* styling is cosmetic; the action still works without it */ }\n}\n\n/** One component body for every door row; only the label and glyph differ. */\nfunction makeDoorAction(door: DoorAction) {\n return function ChaptersDoorAction({ run, visible }: DoorActionProps) {\n // #372: a RESOLVED foreign preset renders nothing at all — the command cannot exist in this\n // session's realm, and a button that resolves to nothing was the defect. UNKNOWN keeps the row\n // (the runner answers with the named refusal): fail-open VISIBLY is the contract, never a\n // silent disappearance on a host whose projection has not arrived yet.\n if (visible !== undefined && !visible()) return null\n const [busy, setBusy] = useState(false)\n const [note, setNote] = useState<string | null>(null)\n const alive = useRef(true)\n useEffect(() => () => { alive.current = false }, [])\n const onClick = useCallback(() => {\n if (busy) return\n setBusy(true)\n setNote(null)\n void run().then((result) => {\n if (!alive.current) return\n setBusy(false)\n setNote(result.message === '' ? null : result.message)\n setTimeout(() => { if (alive.current) setNote(null) }, 8000)\n })\n }, [busy, run])\n const button = h('button', {\n type: 'button',\n 'aria-label': door.label,\n ...nativeTitle(door.label),\n disabled: busy,\n onClick,\n className: 'dsh-chapters_forkAction',\n },\n h('svg', { viewBox: '0 0 16 16', width: '15', height: '15', fill: 'currentColor', 'aria-hidden': 'true' },\n h('path', { d: door.iconPath })))\n return h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: '4px' } },\n withTooltip(door.label, button as ReactElement<Record<string, unknown>>),\n note !== null\n ? h('span', { className: 'dsh-chapters_forkNote' }, note)\n : null)\n }\n}\n\nexport function apply(ctx: Ctx): void {\n injectStyles()\n const slots = ctx.slots\n const remote = (ctx.get('remote') ?? {}) as ClientRemote\n let sessions: ClientSessions | undefined\n try { sessions = ctx.get('sessions') as ClientSessions | undefined } catch { sessions = undefined }\n // Defensive: a host that cannot provide the navigator must leave the door registering and\n // reporting its own limitation, not failing at boot.\n let uiWorkspace: { openSession?: (id: string) => unknown } | undefined\n try { uiWorkspace = ctx.get('uiWorkspace') as { openSession?: (id: string) => unknown } | undefined } catch { uiWorkspace = undefined }\n // No early return on missing descriptors: the buttons register regardless\n // and the click reports the gap. A missing button is worse than a button\n // that explains itself. Components and runners are built ONCE here — slot\n // factories may re-run, and a fresh component identity per call would\n // remount the row.\n // #54: the switch verifier. `dsh.sessions.current` is published by the host's own\n // dsh-client-ui-workspace (grep-confirmed, not folklore) — the same key the e2e specs\n // read to name a session exactly, which is the point: the door now checks the fact the\n // user would notice, not whether a void call threw.\n const currentSessionId = (): string | null => {\n try {\n const raw = window.localStorage.getItem('dsh.sessions.current')\n if (raw === null) return null\n const parsed = JSON.parse(raw) as { sessionId?: string } | null\n return parsed?.sessionId ?? null\n } catch { return null }\n }\n const rows = DOOR_ACTIONS.map((door) => ({\n door,\n run: makeDoorRunner(remote, sessions, door, async (child) => {\n for (let i = 0; i < 8; i++) {\n if (currentSessionId() === child) return true\n await new Promise((r) => setTimeout(r, 250))\n }\n return currentSessionId() === child\n }, { ...(uiWorkspace !== undefined ? { navigator: uiWorkspace } : {} ) }),\n component: makeDoorAction(door),\n }))\n // Boot-witness instrumentation (#194's 0.2.1 compatibility hunt made this permanent): the door\n // registration is a two-step dance with the host's slot runtime, and a silent drop at either step\n // is indistinguishable from \"the region renders nothing\" — three console lines make the difference\n // one page reload away. Same discipline as the dock's inputActions witness.\n console.info(`[client:chapters] injecting ${String(rows.length)} assistant-actions door(s)`)\n const disposeDoors = slots.inject('conversation.chat.assistant-actions', () => {\n const effects = rows.map(({ door, run, component }) => slots.register({\n name: 'conversation.chat.assistant-actions',\n id: door.id,\n // #194-compat probe: the host's own entries in this region (feedback, goal's dock sibling)\n // all carry `label`/`locale`; 0.2.1-rc.5 renders NOTHING for entries without a label while\n // 0.2.0-rc.2 rendered them fine. Declaring the label is contract-blessed on BOTH (\"Register\n // options are id, order, and label\" — docs/contract.md) and costs nothing.\n label: door.label,\n // #221: the framework hands the action row its OWNER props — `{ messageId }`, the uuid of the\n // assistant message under the buttons (measured in dsh-client-ui-chat TurnTailNodeView). The\n // door resolves that uuid to its durable seq through the plugin's own RPC and passes it as the\n // anchor, so clicking Continue on an earlier message archives through THAT message's turn, not\n // the end of the session. Resolution failure falls back to no-anchor (old behavior) and says so\n // in the note — a door that silently ignores which row you clicked is the bug being fixed.\n inject: (sessionId: string, owner?: { messageId?: string }) => ({\n // #372: the factory re-runs per session render, so visibility reads the host projection AT\n // RENDER — resolved-foreign hides the row entirely, unknown keeps it for the named refusal.\n visible: () => doorActionsVisibleFor(presetOfSession(sessions, sessionId)),\n run: async () => {\n let anchor: number | null = null\n const mid = typeof owner?.messageId === 'string' ? owner.messageId : ''\n if (mid !== '') {\n try {\n const out = await runCommandText(remote, sessionId, `/chapters-anchor ${mid}`)\n const n = Number.parseInt(out.trim(), 10)\n if (Number.isFinite(n) && n > 0) anchor = n\n } catch { /* fall back to unanchored — old behavior */ }\n }\n return run(sessionId, anchor)\n },\n }),\n }, component))\n console.info(`[client:chapters] door factory ran: ${String(effects.length)} register effect(s), types: ${effects.map((e) => typeof e).join(',')}`)\n return effects\n })\n console.info(`[client:chapters] assistant-actions inject returned ${typeof disposeDoors}`)\n slots.inject('conversation.input.dock', () => slots.register({\n name: 'conversation.input.dock',\n id: 'chapters-prompt',\n // Under every other dock entry and directly above the composer card: todo 0, goal 10, queue 20, and the\n // host sorts ascending by priority then order (measured in dsh-client-ui-slots).\n order: 30,\n inject: (sessionId: string) => ({\n // The bar is a mouth for the command plane, and the ONE wire body in `doors.ts` carries it: a plugin has\n // no declarable RPC namespace, so this pull transport is why the bar is push-shaped and pull-fed.\n exec: (line: string) => runCommandText(remote, sessionId, line),\n }),\n }, PromptDock))\n}\n"],"mappings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