Repository navigation
Description
Problem Statement
The chat composer is a plain textarea. Slash commands and @-mentions are implemented as string splices with hand-maintained cursor-offset bookkeeping: the trigger popovers detect a directive by scanning the string around the caret, and inserting a selection rewrites the whole draft string and repositions the cursor by numeric offset. For the user this means directives are just text — deleting a command means backspacing through its characters, copying a draft loses any structure, and nothing in the input can ever be richer than characters (no chips, no decorations, no structured payloads). For maintainers, every new trigger kind grows the offset-surgery machinery, which is a standing source of caret and undo bugs.
A spike (verdict recorded in this session; spike code deleted by request) proved a TipTap/ProseMirror input works as the composer input in our environment: ProseMirror is the only mainstream editor engine with shipped shadow-DOM selection support, autosize falls out of content-driven height for free, and the grow-to-cap-then-scroll behavior matches the shipped textarea exactly. It also proved the real cost: the editor stack is ~98 kB gzip, more than twice the entire published chat kit, so the dependency must not land in the chat kit itself.
Solution
Replace the composer's textarea with a TipTap-based rich composer field, delivered as a primitive owned by the rich-text package (ui-kit-tap) and injected into the chat kit through a composer input slot, so the published chat kit keeps zero editor dependency and its current bundle size. Rebuild the trigger system on ProseMirror suggestion nodes: slash commands and @-mentions become atomic inline nodes (chips) with typeahead popovers, atomic deletion, and correct undo — replacing the string-splice trigger machinery outright. The widget adopts the rich input; any consumer of the chat kit that does not inject it keeps a plain input with no editor payload.
The editor is a WYSIWYG skin over the existing string pipeline. The draft, the queue, the snapshots, and the submitted payload remain exactly the strings they are today: every chip lowers to the same directive text the current trigger menus splice in. No transport, protocol, store, or persistence format changes. This ships as one deliverable, not staged releases — feasibility was settled by the spike.
Sizing behavior is unchanged from the shipped composer: one row at rest, grows one row per line up to five rows, then freezes and scrolls internally inside the design system's ScrollArea.
User Stories
- As a widget user, I want to type multi-line prompts with Enter to send and Shift+Enter for a new line, so that composing behaves like every chat product I know.
- As a widget user, I want the composer to sit at one row when empty and grow with my content up to five rows then scroll, so that the input never wastes screen space or jumps unexpectedly.
- As a widget user, I want a placeholder hint when the composer is empty, so that I know where to type and what to do.
- As a widget user, I want every click anywhere inside the input box to focus the editor at a sensible caret position, so that there are no dead zones.
- As a widget user, I want to type "/" and get a typeahead of available slash commands filtered as I keep typing, so that I can discover and pick commands without memorizing them.
- As a widget user, I want a chosen slash command to appear as a single atomic chip in my draft, so that it reads as a command rather than loose text.
- As a widget user, I want backspace over a command chip to delete the whole chip at once, so that removing a command is one keystroke, not character surgery.
- As a widget user, I want to type "@" and get a typeahead of mentionable items (models, files, agents — whatever the host wires), so that I can reference things precisely.
- As a widget user, I want a chosen mention to render as an atomic chip with its label, so that references are visually distinct from prose.
- As a widget user, I want arrow keys and Enter to navigate and select inside a trigger typeahead without moving focus out of the editor, so that the flow never breaks my typing rhythm.
- As a widget user, I want Escape to dismiss an open typeahead and return me to plain typing, so that I can back out of a trigger.
- As a widget user, I want undo and redo to treat chip insertion and deletion as single steps, so that history behaves predictably.
- As a widget user, I want to paste text into the composer and have it appear at the caret, so that paste works like any input.
- As a widget user, I want to paste an image or file and have it attach through the existing attachment flow, so that rich pastes keep working.
- As a widget user, I want typing while the typeahead is open to keep filtering the list live, so that selection is fast.
- As a widget user, I want to keep typing and sending while a run is busy so my follow-ups queue and steer exactly as they do today, and I want the composer disabled only in the situations where today's composer is disabled, so that no queueing behavior regresses.
- As a widget user, I want my draft — including chips — to survive the trigger popover opening and closing, so that nothing I typed is lost.
- As a widget user on the live widget, I want all of this to work inside the widget's shadow DOM exactly as it does in a plain page, so that embedding context never degrades the composer.
- As a keyboard-only user, I want the editor, its typeahead listbox, and its options exposed with correct roles and labels, so that I can operate the composer without a pointer.
- As a screen-reader user, I want the input to announce itself with an accessible name and the typeahead to follow the combobox/listbox pattern, so that trigger selection is non-visual-friendly.
- As a host-app developer using the chat kit, I want the kit to keep working with the plain input when I inject nothing, so that I never pay the editor bundle cost for a plain chat.
- As a host-app developer, I want to opt into the rich input by injecting one component into the composer input slot, so that adoption is a one-line decision.
- As a host-app developer, I want to configure which slash commands and mention sources the typeaheads offer, so that triggers reflect my product.
- As the harness/server, I want the submitted draft to arrive as exactly the same string payload it does today — chips lowered to their directive text — so that nothing downstream of the composer changes.
- As a conciv maintainer, I want the string-splice trigger machinery deleted in the same change that replaces it, so that there is exactly one trigger model in the codebase.
- As a conciv maintainer, I want the chat kit to have no editor dependency, so that its published size stays where it is today.
- As a conciv maintainer, I want the rich-field primitive to live in the rich-text package beside the existing mention field, so that editor expertise and deps concentrate in one package.
- As a conciv maintainer, I want proper stories with play functions for every behavior above, so that the composer is regression-guarded at the seam users experience.
Implementation Decisions
- Ownership: the rich composer field is a new primitive in ui-kit-tap (beside MentionField, reusing its proven editor-lifecycle patterns: editor created once on mount, destroyed on cleanup, suggestion popover driven via signals so focus never leaves the editor, own placeholder overlay).
- The chat kit gains a composer input slot: the styled composer renders its current textarea input by default and accepts an injected input component satisfying the composer input contract. The chat kit takes NO dependency on the editor stack; only injectors (the widget) do. This is the bundle-cost firewall (~98 kB gzip stays out of the published kit).
- Input contract (spike shape plus review round-2 additions): value in/out as the composer store's controlled string; the replace/insert/append operations above;
getSelection/setSelectionin canonical-string offsets with a tested bidirectional mapping to document positions (offsets landing inside a chip's lowered text clamp to the chip boundary; out-of-range offsets clamp like a textarea) — the persisted selection columns keep their exact meaning and schema; anonSelectionChangesubscription and anisFocused()predicate (the host must never compare element identity against the shadow root's active element); key handling returning whether the event was consumed; a paste hook that runs inside the editor's paste handling and returns consumed (files-present consumes the event; pasted rich HTML lowers to plain text); ready callback exposing focus (with an end-of-document option), clear, and the editable element; trigger sources (live-query-backed command and mention items with option rendering); placeholder, accessible label, disabled — all reactive; row bounds as minRows/maxRows numbers (defaults 1 and 5, one cap owned by the primitive, replacing the current double cap of CSS max-height plus textarea maxRows); separate class slots for the scroll viewport and the editable element (a single class slot was proven to produce dead click zones). - Widget draft/snapshot persistence stops listening to input DOM events (a contenteditable fires neither
inputfor programmatic transactions norselectat all): persistence drives off the store draft reactively plus the contract'sonSelectionChange, wired from the input's ready callback so no mount-order race can silently disable it. - Editable fills the input box: padding lives on the ProseMirror element itself, never on a wrapper; no click-forwarding handlers (spike-proven: if a click shim seems needed, the sizing is wrong).
- Scrolling: the editor mounts inside the design system's ScrollArea; the row cap is a max-height on the ScrollArea viewport so it is the scrolling element. ProseMirror's caret scroll-into-view resolves it as the scrollable ancestor (spike-verified, including styled scrollbar on overflow).
- Sizing contract: content-driven height, one row empty, cap at five rows then internal scroll — identical to the shipped textarea composer (verified equivalent in the spike: both grow then clamp).
- Triggers become ProseMirror suggestion nodes: slash commands and mentions are atomic inline nodes inserted via the suggestion utility ("/" and "@" characters), each rendering as a chip. The typeahead popover reuses the existing trigger popover UI where feasible but is driven by the suggestion plugin's lifecycle, not by string scanning. The entire string-splice trigger layer (detection, directive formatting, selection/navigation/keyboard resources) is deleted with no compatibility path — one trigger model only.
- Both trigger kinds (slash commands and mentions) land in this change on shared node infrastructure; internal build order is the implementer's choice.
- State model: the composer store's draft string stays canonical for all product behavior and submission — emptiness, canSend, queueing, clearing, and snapshots keep reading the string exactly as they do now (emptiness computes from the text projection, never from the editor's own empty check). Every editor transaction immediately projects the document to text. Chips lower to
/or@followed by the item ID — the identical characters today's trigger menus serialize (IDs, not display labels, whose text already carries the sigil). The document additionally owns what a string cannot express — chip identity, selection, undo history — as session-local presentation state: hand-typed directive text and a chip lower identically, restored drafts render as plain directive text, and nothing re-chips text. The selection trailing space is a plain text node outside the chip, inserted only when the following character is not already a space, and trigger selection replaces exactly the trigger character plus the typed query (today's semantics). - External updates are two distinct contract operations with defined history semantics.
replaceText(text, selection?)rebuilds the document (may flatten chips — used by draft restoration, cross-view sync, and failed-send restore) and resets undo history.insertText/appendTextare editor transactions that preserve existing chips and undo as one undoable step — used by host append, panel-view insertion, and quote insertion. Trigger insertion is a node insert transaction, never set-content. Text-to-document building splits on newlines into explicit content JSON and never passes the string through an HTML parse (a draft containing markup must survive verbatim). The projection is idempotent: project(build(s)) equals s for every string, including blank lines, trailing spaces, tabs, and markup characters — this is the core lowering contract test. - Trigger grammar matches the current detection semantics (trigger character at start or after whitespace); selecting an item inserts the chip plus a trailing space. Command and mention sources are live queries: the typeahead handles loading, empty, and error states, and results that arrive after the suggestion closed or moved are discarded.
- Deleting the string-splice trigger layer is a deliberate public API removal, and the full removal set is larger than the trigger directory: the trigger popover primitives and their exports, the directive-formatter contract and its
:type[label]{...}grammar (one lowering grammar survives: sigil plus ID), the slash/mention adapter behaviors including the currently-unused action-command (onExecute), select-item override, and category drill-down surfaces, the styled composer'spopoverslot (the typeahead lives inside the field), and the textarea-typedinputRefpublic prop (retyped to the editor-neutral contract). Plain-input consumers keep plain typing with no trigger typeaheads. Acceptable under the v0 no-back-compat policy and stated here so nobody reads it as an oversight. Their unit tests and stories are deleted or replaced in the same cut so the dead-code audit stays clean. - Accessible label, disabled, and class surfaces on the editable stay reactive — dynamic changes go through the editor's update APIs rather than being frozen at creation. The editable keeps
role="textbox"with the popup ARIA attributes today's textarea carries (expanded state, listbox ownership, active-option tracking with stable unique option ids) — the same shape as the current composer and the existing mention field — so the dozens of existing textbox role queries across the embed, site, and e2e suites keep passing; promoting the editable to a full combobox role is an explicit follow-up with its own coordinated test migration. Chips are exposed to screen readers with their labels. - The widget adopts the rich input behind its existing composer wiring, and that wiring is de-textarea'd: the typed textarea ref, selection-offset snapshot/restore, and shadow-root focus checks move to an editor-neutral focus/selection surface provided by the input contract. Ark components inside the widget's shadow root keep the established environment-provider pattern.
- IME composition is guarded (composition events must not trigger submit); this was unverified in the spike and must be exercised for real.
- Widget embed bundle externalization rules extend to the rich-text package: the widget app and embed package take the new dependency, the embed's mount-externals guard gains the rich-text package's assertion (a second bundled Solid/Ark copy is the known popovers-at-0,0 landmine), the global widget bundle's size baseline is re-recorded (~+98 kB gzip is the accepted cost of this feature), and the committed copy of the widget bundle in the site's public assets is regenerated. The editor ships inside the widget bundle, never the chat kit.
- Story packaging: the rich-input stories live where the editor dependency is legal — the rich-text package owns the field's stories, and composer-with-rich-input stories run in the storybook app (which already depends on both packages) rather than inside the chat kit, so no package cycle and no editor dep leaks into the kit.
- The rich-text package gains a test setup (it currently has no test script), giving the lowering and selection-mapping contract tests a home in the standard turbo test graph.
Testing Decisions
- A good test here drives the composer the way a user does — real keyboard events, real browser, real focus — and asserts what a user or the server observes: visible text, roles and accessible names, chip presence, and the submitted payload. No DOM measurements, no computed-style assertions, no reaching into editor internals, no test ids. Layout claims are proven by screenshots, not numbers.
- Primary seam: chat kit Storybook stories with play functions (the established styled-story pattern: role-based queries, userEvent, waitFor, themed wrapper). Stories cover: plain typing and submit; Shift+Enter multi-line; placeholder; disabled; paste text; paste attachment; slash typeahead open/filter/arrow-navigate/select/escape; command chip atomic backspace; mention typeahead and chip; undo/redo across chip insertion; draft survival across popover open/close. Every story is also the a11y documentation of the behavior — queries only via roles and accessible names, so a11y regressions fail the tests.
- Secondary seam: one widget integration smoke on the prebuilt embed bundle in a real browser page: focus the composer inside the widget shadow root, type, open a slash typeahead, select, submit — covering shadow-DOM selection and environment wiring that Storybook cannot.
- Primitive seam: the new field primitive gets its own stories in the rich-text package following the existing mention-field stories' conventions.
- Prior art: the styled model-selector stories (play-function style), the mention-field stories (editor primitive style), and the existing widget integration suite (embed-bundle smoke style).
- Text-lowering round-trips are data-contract unit tests and are welcome: document-to-directive-text projection, the text-to-document builder, the idempotence property with adversarial strings (blank lines, markup characters, tabs, trailing spaces), selection-offset mapping across chips and line breaks, and the exact equality predicate the single-writer guard uses. These test our product semantics, not the editor library.
- Existing suites are part of the cut, not collateral: the embed integration tests asserting the composer via input value (queue-while-busy, clear-after-send, reload draft survival) are rewritten to visible-text assertions, and every external draft writer gets an owning test — quote insertion from the selection toolbar, suggestion prompts, thread prompt/clear, extension-driven insertion from the panel view, cross-view sync, and failed-send restore, each asserting chips-preserved or flattened per the replace/insert contract. A widget test types, waits for the persistence debounce, and asserts the stored draft and selection so silent persistence loss cannot ship.
- The widget shadow-DOM smoke includes IME: composing text, confirming composition, and pressing Enter immediately after composition ends, plus send-button submit during composition — composition inside the shadow root is the highest-risk untested surface.
- Explicitly rejected: transition-table unit tests for trigger state, schema-mirror tests, and any assertion on editor document internals beyond the lowering contract above.
- Additional behaviors the stories must cover (review findings): forward Delete as well as Backspace on both sides of a chip, range selection cut across text and chips, typeahead loading/empty/error states, Escape precedence with other widget overlays, Enter immediately after IME composition ends, submit via the send button (not only keyboard), and undo after paste and after external draft replacement.
- Bundle guard: an assertion that the chat kit has no transitive editor imports (package graph and built artifact), alongside the existing embed externalization guards.
Out of Scope
- Grab chips (element references as inline nodes), inline attachment chips at the caret, ghost-text completion via decorations, markdown input rules, typography transforms, character/token counting: all candidates for later, none in this change.
- Any rich rendering in the thread; this spec touches only the composer input.
- Per-thread draft persistence changes; chips are session-local rendering (the persisted string is the truth).
- Structured wire transport of directives (server keeps receiving the same string; a structured protocol is a possible future change).
- Collaborative editing.
- Removing or changing the plain textarea default in the chat kit — it remains the zero-dependency default for kit consumers.
Further Notes
- The spike branch and worktree were deleted at the user's request; this spec plus the session verdict are the surviving knowledge. Key spike numbers: editor stack ~370 kB raw / ~98 kB gzip for the minimal extension set, ~+12 kB gzip more with the mention extension; published chat kit today is ~44 kB gzip.
- The engine choice (TipTap v3 on ProseMirror, vanilla, no React) was settled by prior research: shipped shadow-DOM selection support is unique to ProseMirror and the composer lives in a shadow-DOM overlay.
- The trigger rewrite is the heart of the change, not an add-on: bolting the editor under the string-splice triggers was explicitly rejected as a caret/undo bug farm.
- Sizing behavior deliberately matches today's textarea (grow to five rows, then scroll); a fixed-height composer was discussed and rejected.
- Review round 2 (codex re-review plus two independent opus reviewers) confirmed the string-canonical direction and drove the contract additions above: selection offsets as a first-class contract (they live in the drafts schema and have two writers), replace-versus-insert external update semantics with defined undo behavior, lowering by ID not label (labels already carry the sigil — lowering labels would double it), one surviving grammar, textbox-role preservation to protect the existing cross-suite role queries, reactive persistence wiring, and the expanded blast-radius accounting (adapter behaviors, styled props, embed/site/e2e assertion rewrites, bundle artifacts, rich-text package test setup).
- This spec was externally reviewed (codex, gpt-5.6-sol). Its two "blocking" findings — no transport contract for structured parts, and a controlled-string/uncontrolled-editor conflict — were resolved by the string-canonical state model above (chips lower to directive text; nothing downstream changes). Its staged three-release plan was rejected in favor of one deliverable. Findings that were adopted: queue/steer sendable-while-busy preserved, widget de-textarea-ing in scope, trigger deletion stated as public API removal, reactive accessibility attributes, async source states, real combobox semantics, lowering round-trip unit tests, and the extra story list in Testing Decisions.
Amendment (2026-08-07): no composer input slot — zero new chat-kit API
This section supersedes every mention of a "composer input slot", "input contract", "injected input component", or contract-typed inputRef above (Implementation Decisions bullets 2–3 and the related user stories 21–22 wording).
Ruling: the chat kit gains no new API for this feature. No slot prop, no exported input contract types, no default/fallback component indirection. The composer's public surface stays exactly as it is.
The custom-input model is assistant-ui headless parity: assistant-ui's answer to a custom/rich input is a headless hook (unstable_useComposerInput returning value/setText/send/canSend) consumed by whatever component the app renders inside ComposerPrimitive.Root — never an injected component prop. Our kit already exposes the equivalent hooks publicly (useComposer, useComposerContext, useComposerHandlers), and the widget already composes ComposerPrimitive.* parts directly in its own markup rather than using the styled composer. Therefore:
- The rich field is a chat-agnostic component owned by ui-kit-tap (beside MentionField, following its conventions): controlled
value/onValueChange,onSubmit,onSelectionChange(canonical string offsets), trigger sources, placeholder/label/disabled, minRows/maxRows, class slots, plus an optional imperative handle per the tap package's own field conventions (focus/clear/insertText/appendText — replace semantics happen by reconciling a changedvalueprop: rebuild, flatten chips, reset undo; insert/append are chip-preserving single-undo transactions). That handle is tap API, never chat-kit API. No public name contains "TipTap". - The widget swaps inputs privately: a single widget-local adapter file renders the tap field in place of
ComposerPrimitive.Inputand binds it to the composer store via the existing public hooks. Widget persistence (draft + selection offsets) rides the store plus the field'sonSelectionChange. - The styled composer keeps its textarea untouched; kit consumers see zero difference. The trigger-layer deletion (stated public API removal above) still lands in the final cut.
User stories 21–23 are satisfied without a slot: consumers who do nothing keep the plain input (nothing changed for them); the widget adopts the rich input by composition; hosts configure triggers by the props they pass the field.
The bundle firewall is unchanged and stronger: the editor dependency exists only in ui-kit-tap and its widget/embed consumers; the chat kit's diff for this feature is the trigger-layer deletion only.
Activity
feat(composer)!: TipTap rich composer epic (#293) — stacked delivery …