From 63c20ab973edf4bb50fbf2cae4b9414ac0b413e1 Mon Sep 17 00:00:00 2001 From: Omri Katz <9701896+omridevk@users.noreply.github.com> Date: Sun, 16 Aug 2026 14:48:37 +0300 Subject: [PATCH 01/24] docs: composer actions collapse + refresh extraction design spec Co-Authored-By: Claude Fable 5 --- ...-08-16-composer-actions-collapse-design.md | 188 ++++++++++++++++++ 1 file changed, 188 insertions(+) create mode 100644 docs/superpowers/specs/2026-08-16-composer-actions-collapse-design.md diff --git a/docs/superpowers/specs/2026-08-16-composer-actions-collapse-design.md b/docs/superpowers/specs/2026-08-16-composer-actions-collapse-design.md new file mode 100644 index 0000000000..984e38f905 --- /dev/null +++ b/docs/superpowers/specs/2026-08-16-composer-actions-collapse-design.md @@ -0,0 +1,188 @@ +# Composer actions collapse & session refresh extraction + +Date: 2026-08-16 +Status: revised after codex (gpt-5.6-sol) adversarial review + +## Problem + +The widget composer toolbar row is saturated with icon buttons: attachment paperclip, grab +(select element), new session, compact, launch menu, extension-contributed buttons (whiteboard +canvas, whiteboard comment, tanstack), model selector, refresh, send/cancel. Every extension that +adds a composer button makes it worse, and nothing adapts to panel width. Additionally the +"Refresh the conversation" control (stream re-subscribe) is a session-level affordance that has no +business living in the composer. + +## Goals + +- Only a small number of action buttons visible inline in the composer; the rest live in a single + overflow dropdown menu. +- Extension authors keep authoring plain JSX: they declare *what* to show; the host decides *when + and how* (inline vs dropdown). +- Automatic collapse driven by measured container width, regardless of per-button config, so the + composer works at every panel size. +- Refresh removed from the composer contract entirely; standalone session-scoped `RefreshButton` + usable on any surface that has a chat context. + +## Non-goals + +- No declarative action-registry public API (rejected: extensions author JSX, not data). +- No `visible="menu"` state (dropdown-only expressed structurally: provide only `DropdownItem`s). +- No changes to attachment paperclip, model selector, or send/cancel — they are not "actions" and + stay outside the collapsible group (but their widths participate in the fit budget, see §2). +- No back-compat shims (v0). + +## Design + +### 1. `ComposerActions.*` compound primitives + +New public primitives, exported through the `@conciv/extension` surface (single import point for +extension authors). Authoring shape: + +```tsx +function MyExtensionButton() { + return ( + + + + + + + + + ) +} +``` + +- `Root` props: `id` (stable, unique), `priority` (higher = keeps inline slot longer; default 0), + `disabled?: () => boolean` — the single reactive disabled/pending source consumed by BOTH + renderings. Inline button and menu items can never disagree; disabled Ark items stay in the + collection but are skipped by arrow/typeahead navigation (Ark default). +- `Button` props: `visible?: 'auto' | 'always'` (default `'auto'`), `tooltip`, `onClick`. Renders + `TooltipIconButton`. +- `DropdownItem` props: `value` (required, stable; namespaced by the host as `${rootId}:${value}` + for Ark collection identity), `label`, `onSelect`, icon child. Renders an Ark `Menu.Item` + portaled into the host's shared overflow menu content node. +- A `Root` may contain MULTIPLE `DropdownItem`s, including conditional sets (`Show`/`Switch`). + When collapsed, all its items appear flattened in the overflow menu, grouped contiguously in + priority order. This is how the launch menu migrates (see §3). +- Semantics by structure: + - Button + item(s): inline when space, menu items when collapsed. + - Button only: inline when space, hidden when collapsed (`visible="always"` pins it inline). + - Item(s) only: menu-only. +- Extensions continue to gate on `useSlot() === 'composer'` exactly as today; only the JSX they + render inside that gate changes. +- Home: the primitives live with the widget UI kit surface (`packages/ui-kit-chat` or + `apps/conciv` + re-export via `@conciv/extension`); final placement decided at implementation by + where `TooltipIconButton`/`Menu` dependencies resolve without cycles. + +### 2. Host coordinator (invisible to extensions) + +**Ownership requirement:** the coordinator context AND the shared Ark `Menu.Root` must be +*logical Solid ancestors* (owner-tree, not merely DOM ancestors) of everything that renders +`ComposerActions.*` — the built-in actions and ``. Concretely: +`PaneComposer` hosts `ComposerActionsProvider` + `Menu.Root` above `props.children`. Solid +`Portal` preserves context, so extension `Menu.Item`s portaled into the shared `Menu.Content` +node resolve Ark context correctly. Items that register before the content mount node exists +(Suspense) queue and portal once it mounts. + +**Registration:** each `Root` registers `{id, priority, visible, hasButton, itemCount, disabled}` +into a reactive store on mount, unregisters on cleanup. Duplicate id: dev warning, last wins. +`Root` outside a coordinator renders nothing. + +**Fit algorithm (deterministic, no oscillation):** + +- One `ResizeObserver` on the stable outer toolbar row only (reuse `useSizeHandle`). +- Candidate button widths are measured once per registration-set change and cached (buttons are + uniform `TooltipIconButton` geometry; cache invalidates on register/unregister, not on resize). +- Budget = row width − widths of non-collapsible occupants (attachment control, model selector, + send/cancel at its widest state, gaps) − ALWAYS-reserved overflow-trigger width. Reserving the + trigger unconditionally removes the circular collapse condition (trigger appearing forces + another collapse). +- Fill: pinned (`visible="always"`) buttons first, then `auto` buttons in priority-desc order + while they fit; the rest collapse. Below a hard minimum budget all `auto` buttons collapse. +- Hysteresis margin on the threshold so drag-resizing across a boundary cannot flap. +- Reads batched before writes; visibility changes never feed back into the observed element's + height/width measurement path. +- Overflow trigger button: accessible name "More composer actions", rendered only when ≥1 item is + collapsed (space stays reserved regardless). Menu ordering: priority desc, then registration + order. + +### 3. Built-ins migrate to the same primitives + +`apps/conciv/src/composer/actions.tsx` (grab, new session, compact, launch menu) is rewritten on +`ComposerActions.*`: + +- Grab: `visible="always"` (primary, pinned) by default. +- New session, compact: `auto`, button + one dropdown item each. +- Launch: one `Root`; inline rendering keeps its own trigger + nested menu exactly as today; + collapsed rendering = its conditional item set (open-in-harness / copy-command / retry) + flattened into the shared overflow menu via multiple `DropdownItem`s. + +**Full migration surface (all authoring/guidance call sites):** + +- `packages/extensions/whiteboard/src/client.tsx`, `packages/extensions/tanstack/src/client.tsx`. +- `packages/extension/src/catalog.ts`: `composer-action` scaffold template, the `full` scaffold's + raw composer button, slot descriptions ("add buttons or actions"), and scaffold assertions in + `packages/extension/test/catalog.test.ts`. +- `packages/harness/plugins/claude/skills/conciv-extensions/SKILL.md` (teaches raw buttons today). +- `apps/site/content/docs/extending/widget-ui.mdx`. + +No authoring surface may keep demonstrating raw composer buttons — anything unmanaged bypasses +collapse. + +### 4. Refresh extracted from the composer + +- Delete `ComposerPrimitive.Refresh` (`packages/ui-kit-chat/src/primitives/composer/composer.tsx`) + and `onRefresh` from the composer handlers contract + (`packages/ui-kit-chat/src/primitives/composer/composer-handlers.tsx`); the composer no longer + knows refresh exists. +- New standalone self-contained `RefreshButton` in `apps/conciv`: internally calls + `useChatContext()`, runs `chat.refresh()` (stream re-subscribe), disabled while streaming. + Usable anywhere under a `ChatProvider`. +- Per-surface placement (`ChatProvider` stays where it is, inside `ChatPane`): + - **Panel:** header right cluster (`apps/conciv/src/routes/panel.$sessionId.tsx`). The header + renders above `ChatProvider`, so `ChatPane` relays a refresh command through `PaneContext` + (same pattern as the existing `newSession`); the header button consumes `pane.refresh`. + - **Quick mode:** per-pane placement (multiple sessions under one global header — a global + button has no target). Each pane's own chrome row hosts `RefreshButton` directly. + - **PiP:** no header exists; `RefreshButton` in pip chrome within the `ChatPane` region. +- ui-kit-chat's primitive-specific refresh browser tests are DELETED (not rewired — the header + button is an app component; ui-kit cannot depend on it). Refresh behavior + streaming-disable + coverage lives in the app-level browser suite. + +## Error handling + +- Duplicate `Root` id: dev-time warning, last registration wins. +- `Root` rendered outside a coordinator (e.g. non-composer slot): renders nothing. +- Zero collapsed items: no overflow trigger in the DOM (reserved space remains in the budget). +- Items registering before the shared menu content node mounts (Suspense): queued, portal on mount. + +## Testing + +Real-browser (Playwright/Chromium) tests against the prebuilt embed bundle, per repo rules: + +- Narrow panel: `auto` buttons leave the row, "More composer actions" trigger appears, menu items + present and fire the same actions; `visible="always"` button stays inline. +- Wide panel: all buttons inline, no trigger. +- Repeated resize across the exact threshold (drag back and forth): no oscillation, no + ResizeObserver loop errors. +- Button-only Root hidden when collapsed; item-only Root appears only in the menu; multi-item Root + (launch) shows its conditional set flattened. +- Disabled Root: inline button disabled AND menu item non-invocable, skipped by keyboard nav. +- Overflow menu keyboard lifecycle: `aria-haspopup`/expanded on trigger, arrow navigation, + typeahead, Escape dismissal, focus return to trigger, menu closes after selection, focus + behavior when a resize moves the focused action inline or unmounts an open menu. +- Extension-testkit: host runtime (`packages/extension-testkit/src/host/host-runtime.tsx`) gains + the coordinator + shared menu root + configurable width so fixtures can exercise the primitives; + fixture covering an extension using Button + DropdownItems. +- Refresh: re-subscribe + disabled-while-streaming tests move to the app-level suite against the + panel header button; per-surface presence checks for quick/pip. +- Assertions role/visibility-based; panel width driven through real resize affordances; no DOM + measurement assertions. + +## Open items (implementation-time) + +- Exact package placement of the primitives (dependency-cycle check). +- `ComposerActions.Button` needs an `asChild`-style escape for launch's inline rendering (the + inline control is itself a menu trigger, not a plain onClick button); follow the existing + `TooltipIconButtonSlot` + `Menu.Trigger asChild` pattern from `launch-menu.tsx`. From b43894cc650dde8d32232ecb3fe91f844f15f2c9 Mon Sep 17 00:00:00 2001 From: Omri Katz <9701896+omridevk@users.noreply.github.com> Date: Sun, 16 Aug 2026 14:52:43 +0300 Subject: [PATCH 02/24] docs: constant-slot-width fit arithmetic in composer actions spec Co-Authored-By: Claude Fable 5 --- ...-08-16-composer-actions-collapse-design.md | 33 +++++++++++-------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/docs/superpowers/specs/2026-08-16-composer-actions-collapse-design.md b/docs/superpowers/specs/2026-08-16-composer-actions-collapse-design.md index 984e38f905..436598e41f 100644 --- a/docs/superpowers/specs/2026-08-16-composer-actions-collapse-design.md +++ b/docs/superpowers/specs/2026-08-16-composer-actions-collapse-design.md @@ -89,20 +89,25 @@ node resolve Ark context correctly. Items that register before the content mount into a reactive store on mount, unregisters on cleanup. Duplicate id: dev warning, last wins. `Root` outside a coordinator renders nothing. -**Fit algorithm (deterministic, no oscillation):** - -- One `ResizeObserver` on the stable outer toolbar row only (reuse `useSizeHandle`). -- Candidate button widths are measured once per registration-set change and cached (buttons are - uniform `TooltipIconButton` geometry; cache invalidates on register/unregister, not on resize). -- Budget = row width − widths of non-collapsible occupants (attachment control, model selector, - send/cancel at its widest state, gaps) − ALWAYS-reserved overflow-trigger width. Reserving the - trigger unconditionally removes the circular collapse condition (trigger appearing forces - another collapse). -- Fill: pinned (`visible="always"`) buttons first, then `auto` buttons in priority-desc order - while they fit; the rest collapse. Below a hard minimum budget all `auto` buttons collapse. -- Hysteresis margin on the threshold so drag-resizing across a boundary cannot flap. -- Reads batched before writes; visibility changes never feed back into the observed element's - height/width measurement path. +**Fit algorithm (pure arithmetic, no DOM measurement of candidates):** + +- Action buttons are uniform `TooltipIconButton` geometry, so per-slot width is a design-token + CONSTANT (`SLOT` = button width + gap) — candidate widths are never read from the DOM. +- Two passive `ResizeObserver`s (reuse `useSizeHandle`): one on the stable outer toolbar row, one + on the trailing non-collapsible cluster (attachment control, model selector, send/cancel — + model selector is the only variable-width occupant). Observers report already-computed + geometry; no forced layout reads. +- `visibleAutoCount = floor((rowWidth − trailingWidth − reservedTriggerWidth − pinnedCount·SLOT) / SLOT)` + — one subtraction and a division per resize event. +- The overflow-trigger width is ALWAYS reserved, removing the circular collapse condition + (trigger appearing forces another collapse). +- Fill: pinned (`visible="always"`) buttons always inline, then the top `visibleAutoCount` `auto` + buttons in priority-desc order; the rest collapse. Below a hard minimum budget all `auto` + buttons collapse. +- Hysteresis margin on the count boundary so drag-resizing across a threshold cannot flap + (visual stability; the arithmetic itself is negligible). +- Visibility changes never alter the observed row/cluster widths (buttons collapse into the + portaled menu, the reserved trigger slot is constant), so no observer feedback loop exists. - Overflow trigger button: accessible name "More composer actions", rendered only when ≥1 item is collapsed (space stays reserved regardless). Menu ordering: priority desc, then registration order. From 686b5d1cf1a15994945f0eb2fed5c70d3c2eb03b Mon Sep 17 00:00:00 2001 From: Omri Katz <9701896+omridevk@users.noreply.github.com> Date: Sun, 16 Aug 2026 15:13:12 +0300 Subject: [PATCH 03/24] docs: composer actions collapse implementation plan Co-Authored-By: Claude Fable 5 --- .../2026-08-16-composer-actions-collapse.md | 568 ++++++++++++++++++ 1 file changed, 568 insertions(+) create mode 100644 docs/superpowers/plans/2026-08-16-composer-actions-collapse.md diff --git a/docs/superpowers/plans/2026-08-16-composer-actions-collapse.md b/docs/superpowers/plans/2026-08-16-composer-actions-collapse.md new file mode 100644 index 0000000000..d55ba68845 --- /dev/null +++ b/docs/superpowers/plans/2026-08-16-composer-actions-collapse.md @@ -0,0 +1,568 @@ +# Composer Actions Collapse & Refresh Extraction Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Replace the saturated composer button row with compound `ComposerActions.*` primitives whose host coordinator collapses lower-priority actions into one shared overflow menu by measured width, and extract the session refresh affordance out of the composer into per-surface chrome. + +**Architecture:** New `ComposerActions` compound components (Root/Button/DropdownItem) live in `@conciv/extension` (which already depends on `@conciv/ui-kit-system` for `TooltipIconButton`/`Menu`). A host-side `ComposerActionsProvider` + shared Ark `Menu.Root` wrap the composer toolbar row as logical Solid ancestors of both built-in actions and `ExtensionSurface name="composer"`. Fit is pure arithmetic over a constant slot width and two passive ResizeObservers. Refresh becomes a `RefreshButton` reading a refresh handle that `ChatPane` registers into `PaneContext` — one mechanism serving panel header, quick per-pane bar, and pip chrome. + +**Tech Stack:** SolidJS, Ark UI Menu (zag), UnoCSS utility classes, vitest browser (Playwright/Chromium), oxlint/oxfmt. + +**Spec:** `docs/superpowers/specs/2026-08-16-composer-actions-collapse-design.md` + +## Global Constraints + +- Functions only, no classes, no IIFEs, ZERO code comments (lint deletes them). +- Strict TS: no `any`, no `as` casts, no non-null assertions, `noUncheckedIndexedAccess`. +- oxfmt: no semicolons, single quotes, no bracket spacing, trailing commas, printWidth 120. +- Solid: use `splitProps` (never destructure props), `@solid-primitives` over raw signal glue, no hooks inside JSX attributes, `Show`/`For` over ternaries. +- Every Solid package `vitest.config.ts` pins `test: {environment: 'node'}`. +- Widget UI tests run in REAL Chromium (vitest browser), never jsdom. Web-first assertions only: no `poll`, no `querySelector`, no rect measurement, no sleeps, no test-ids. Locate by role/name. +- Never `newContext()` in widget ITs — `browser.newPage()` pattern; these tests use `@vitest/browser` page/userEvent. +- Whiteboard package test suite NEVER runs locally — local gates for whiteboard changes: typecheck/build/lint only. +- Package test gates: `pnpm turbo run test --filter=` (bare filter — NEVER trailing `...`). +- New UnoCSS utility classes in ui-kit src need an embed rebuild to appear: `pnpm turbo run build --filter=@conciv/embed`. +- Commit with pathspec (`git commit -- `); run `pnpm exec fallow audit --format json --quiet --explain --gate-marker agent` before each commit (JSON runtime errors non-blocking). +- All UI copy sentence-case, matches existing tone (`'More composer actions'`). + +## Layout constants (used across tasks) + +Action buttons are `size-8.5` (2.125rem = 34px) with row `gap-1` (4px): + +```ts +export const ACTION_SLOT_PX = 38 +export const FIT_HYSTERESIS_PX = 24 +``` + +The overflow trigger permanently occupies one slot in the row (visibility-hidden when no item is collapsed), so the arithmetic never feeds back into itself. + +--- + +### Task 1: Fit arithmetic (pure function) + +**Files:** +- Create: `packages/extension/src/composer-actions-fit.ts` +- Test: `packages/extension/test/composer-actions-fit.test.ts` + +**Interfaces:** +- Produces: `computeVisibleAutoCount(input: FitInput): number`, `type FitInput`, constants `ACTION_SLOT_PX`, `FIT_HYSTERESIS_PX`. Task 2 consumes all of these. + +- [ ] **Step 1: Write the failing test** + +```ts +import {describe, expect, it} from 'vitest' +import {ACTION_SLOT_PX, FIT_HYSTERESIS_PX, computeVisibleAutoCount} from '../src/composer-actions-fit.js' + +const base = { + slotWidth: ACTION_SLOT_PX, + hysteresisPx: FIT_HYSTERESIS_PX, + leadingWidth: 38, + trailingWidth: 120, + pinnedCount: 1, + autoCount: 4, + previousCount: null, +} + +describe('computeVisibleAutoCount', () => { + it('shows every auto action when the budget covers them', () => { + expect(computeVisibleAutoCount({...base, rowWidth: 600})).toBe(4) + }) + + it('clamps to the available whole slots', () => { + const rowWidth = 38 + 120 + 38 + 38 + 2 * 38 + 10 + expect(computeVisibleAutoCount({...base, rowWidth})).toBe(2) + }) + + it('never returns a negative count', () => { + expect(computeVisibleAutoCount({...base, rowWidth: 100})).toBe(0) + }) + + it('never exceeds the registered auto count', () => { + expect(computeVisibleAutoCount({...base, rowWidth: 5000})).toBe(4) + }) + + it('shrinks immediately when the row narrows', () => { + const rowWidth = 38 + 120 + 38 + 38 + 38 + expect(computeVisibleAutoCount({...base, rowWidth, previousCount: 4})).toBe(1) + }) + + it('expands only once the budget clears the hysteresis margin', () => { + const exact = 38 + 120 + 38 + 38 + 2 * 38 + expect(computeVisibleAutoCount({...base, rowWidth: exact + 4, previousCount: 1})).toBe(1) + expect(computeVisibleAutoCount({...base, rowWidth: exact + FIT_HYSTERESIS_PX, previousCount: 1})).toBe(2) + }) +}) +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `pnpm vitest run test/composer-actions-fit.test.ts` (cwd `packages/extension`) +Expected: FAIL — module not found. + +- [ ] **Step 3: Write the implementation** + +```ts +export const ACTION_SLOT_PX = 38 +export const FIT_HYSTERESIS_PX = 24 + +export type FitInput = { + rowWidth: number + leadingWidth: number + trailingWidth: number + slotWidth: number + pinnedCount: number + autoCount: number + previousCount: number | null + hysteresisPx: number +} + +export function computeVisibleAutoCount(input: FitInput): number { + const triggerWidth = input.slotWidth + const budget = + input.rowWidth - input.leadingWidth - input.trailingWidth - triggerWidth - input.pinnedCount * input.slotWidth + const fits = Math.max(0, Math.min(input.autoCount, Math.floor(budget / input.slotWidth))) + if (input.previousCount === null || fits <= input.previousCount) return fits + if (budget < fits * input.slotWidth + input.hysteresisPx) return input.previousCount + return fits +} +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run: `pnpm vitest run test/composer-actions-fit.test.ts` — Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add packages/extension/src/composer-actions-fit.ts packages/extension/test/composer-actions-fit.test.ts +git commit -m "feat(extension): composer actions fit arithmetic" -- packages/extension +``` + +--- + +### Task 2: `ComposerActions` primitives + host coordinator + +**Files:** +- Create: `packages/extension/src/composer-actions.tsx` +- Modify: `packages/extension/src/index.tsx` (export `ComposerActions`), `packages/extension/src/host.ts` (export `ComposerActionsHost`) + +**Interfaces:** +- Consumes: Task 1's `computeVisibleAutoCount`, `ACTION_SLOT_PX`, `FIT_HYSTERESIS_PX`; `Menu`, `TooltipIconButton` from `@conciv/ui-kit-system`. +- Produces (extension-author surface, exported from `@conciv/extension`): + - `ComposerActions.Root(props: {id: string; priority?: number; children: JSX.Element})` + - `ComposerActions.Button(props: {visible?: 'auto' | 'always'; tooltip: string; onClick: () => void; disabled?: boolean; children: JSX.Element})` + - `ComposerActions.DropdownItem(props: {value: string; label: string; onSelect: () => void; disabled?: boolean; children?: JSX.Element})` +- Produces (host surface, exported from `@conciv/extension/host`): + - `ComposerActionsHost(props: {leading?: JSX.Element; trailing: JSX.Element; children: JSX.Element})` — renders the toolbar row: leading region, managed children, permanent trigger slot, trailing region; owns provider, shared `Menu.Root`, both observers. + +**Implementation shape (write exactly this structure):** + +```tsx +import {For, Show, createContext, createMemo, createSignal, createUniqueId, onCleanup, onMount, splitProps, useContext, type Accessor, type JSX} from 'solid-js' +import {Portal} from 'solid-js/web' +import {createStore, produce} from 'solid-js/store' +import Ellipsis from 'lucide-solid/icons/ellipsis' +import {Menu, TooltipIconButton, TooltipIconButtonSlot} from '@conciv/ui-kit-system' +import {ACTION_SLOT_PX, FIT_HYSTERESIS_PX, computeVisibleAutoCount} from './composer-actions-fit.js' + +type Registration = {key: string; id: string; priority: number; pinned: boolean; hasButton: boolean} + +type Coordinator = { + register: (entry: Registration) => void + update: (key: string, patch: Partial) => void + unregister: (key: string) => void + inlineKeys: Accessor> + menuMount: Accessor +} + +const CoordinatorContext = createContext() +type RootState = {key: string; id: string; priority: number; inline: Accessor; setPinned: (pinned: boolean) => void; setHasButton: (has: boolean) => void} +const RootContext = createContext() +``` + +Coordinator internals (inside `ComposerActionsHost`): + +- `const [entries, setEntries] = createStore([])`; register appends, update patches by key, unregister filters. Duplicate `id`: `console.warn` in dev, keep both entries keyed by `key` (unique per mount) so last mount wins visually. +- `const [rowWidth, setRowWidth] = createSignal(0)` etc. for leading/trailing wrappers; one `ResizeObserver` per element via `createEffect` + `onCleanup` (same pattern as `useSizeHandle`). +- `const [previous, setPrevious] = createSignal(null)`; `visibleAutoCount` memo calls `computeVisibleAutoCount` with `pinnedCount = entries pinned+hasButton count`, `autoCount = entries auto+hasButton count`, then `setPrevious`. +- `inlineKeys` memo: all pinned keys, plus the first `visibleAutoCount()` auto entries sorted by priority desc then insertion order. +- Row JSX: `Menu.Root` (from ui-kit-system, `positioning={{placement: 'top-end'}}`) wrapping the whole row `div.pt-0.5.flex.gap-1.items-center`; inside: leading wrapper div (observer target), `{props.children}`, trigger slot, trailing wrapper div with `ml-auto` (observer target). Trigger slot: + +```tsx + + + + +``` + +`anyCollapsed()` = any entry with `hasDropdownItems` not in `inlineKeys()` — track item counts per key in the store (`items: number`, incremented/decremented by `DropdownItem` mount/cleanup through `RootContext`). + +Component behavior: + +- `Root`: `createUniqueId()` key; registers on mount, unregisters on cleanup; provides `RootContext` with `inline: () => coordinator.inlineKeys().has(key)`. Outside a coordinator (`useContext` undefined): render nothing (``). +- `Button`: on mount `root.setHasButton(true)` and `root.setPinned(props.visible === 'always')`; renders `` → `TooltipIconButton` with `class="size-8.5"`, `tooltip`, `onClick`, `disabled`. +- `DropdownItem`: increments the root's item count on mount; renders + +```tsx + + {(mount) => ( + + props.onSelect()} style={{order: String(-root.priority)}}> + {props.children} + {props.label} + + + )} + +``` + +Menu ordering uses flex `order: -priority` on the flex-col content (portal insertion order is mount order, which is not priority order). + +- [ ] **Step 1: Write `composer-actions.tsx` per the shape above; export `ComposerActions = {Root, Button, DropdownItem}` from `index.tsx` and `ComposerActionsHost` from `host.ts`** +- [ ] **Step 2: Typecheck + build gate** + +Run: `pnpm turbo run build --filter=@conciv/extension && pnpm turbo run typecheck --filter=@conciv/extension` +Expected: green. (Behavior coverage lands in Task 3's browser tests — primitives have no browser harness in this package.) + +- [ ] **Step 3: Commit** + +```bash +git add packages/extension/src +git commit -m "feat(extension): ComposerActions compound primitives with overflow coordinator" -- packages/extension +``` + +--- + +### Task 3: Wire the coordinator into `PaneComposer`, migrate grab/new-session/compact + +**Files:** +- Modify: `apps/conciv/src/pane/pane-composer.tsx` (toolbar row becomes `ComposerActionsHost`), `apps/conciv/src/composer/actions.tsx` (grab/new-session/compact on new primitives) +- Test: `apps/conciv/test/composer-overflow.browser.test.tsx` (new) + +**Interfaces:** +- Consumes: `ComposerActionsHost` from `@conciv/extension/host`, `ComposerActions` from `@conciv/extension`. +- Produces: the toolbar row DOM contract every later task tests against — leading = attachment button, managed = built-ins + `ExtensionSurface name="composer"`, trailing = model selector + send/cancel; trigger named `'More composer actions'`. + +**pane-composer.tsx** — replace the row `div` (currently lines 127-139) with: + +```tsx + + + + + } + trailing={ + }> + {props.busy} + + } +> + {props.children} + +``` + +`TrailingControls` loses the refresh slot in Task 7; until then keep `ComposerSendControl` only here and leave `TrailingControls` unused-free by deleting it in this task (send control is the only survivor; refresh temporarily stays where it is — do NOT touch it in this task). The model selector stays in `props.children` order-wise? No — move `SessionModelSelector` into `trailing` at the `chat-pane.tsx` call site: pass it via a new `PaneComposerProps.trailingExtras?: JSX.Element` rendered before the send control inside `trailing`. Keep the change minimal: `chat-pane.tsx` renders `` through that prop instead of as a child. + +**actions.tsx** — each button becomes a `Root`: + +```tsx + + void pick()} + > + + + + + props.onNewSession()}> + + + props.onNewSession()}> + + + + props.onCompact()}> + + + props.onCompact()}> + + +``` + +(Launch menu migrates in Task 4 — leave `LaunchMenu` rendered as-is inside the managed region for now.) + +- [ ] **Step 1: Write the failing browser test** (`composer-overflow.browser.test.tsx`, modeled on `chat-pane.browser.test.tsx` setup — same kit/mount helpers). Assertions: + +```tsx +test('wide panel keeps every action inline with no overflow trigger', async () => { + await mountPaneAtWidth(720) + await expect.element(page.getByRole('button', {name: 'Start a new session'})).toBeVisible() + await expect.element(page.getByRole('button', {name: 'Compress the conversation'})).toBeVisible() + await expect.element(page.getByRole('button', {name: 'More composer actions'})).not.toBeInTheDocument() +}) + +test('narrow panel collapses auto actions into the overflow menu and keeps the pinned grab inline', async () => { + await mountPaneAtWidth(360) + await expect.element(page.getByRole('button', {name: 'Select an element from the page'})).toBeVisible() + await expect.element(page.getByRole('button', {name: 'Start a new session'})).not.toBeInTheDocument() + await page.getByRole('button', {name: 'More composer actions'}).click() + await expect.element(page.getByRole('menuitem', {name: 'Start a new session'})).toBeVisible() +}) + +test('overflow menu items fire the same action', async () => { + await mountPaneAtWidth(360) + await page.getByRole('button', {name: 'More composer actions'}).click() + await page.getByRole('menuitem', {name: 'Start a new session'}).click() + // assert the same observable outcome the existing new-session test asserts (navigation/session creation via the kit) +}) + +test('keyboard lifecycle: open with keyboard, arrow to an item, Escape returns focus to the trigger', async () => { + await mountPaneAtWidth(360) + const trigger = page.getByRole('button', {name: 'More composer actions'}) + await trigger.click() + await userEvent.keyboard('{ArrowDown}') + await userEvent.keyboard('{Escape}') + await expect.element(page.getByRole('menu')).not.toBeVisible() + await expect.element(trigger).toHaveFocus() +}) + +test('disabled root is disabled in both renderings', async () => { + // mount with compacting=true fixture state + await mountPaneAtWidth(360) + await page.getByRole('button', {name: 'More composer actions'}).click() + await expect.element(page.getByRole('menuitem', {name: 'Compress the conversation'})).toHaveAttribute('data-disabled') +}) + +test('repeated resize across the collapse threshold settles without flapping', async () => { + const pane = await mountPaneAtWidth(720) + for (const width of [360, 720, 360, 720, 360]) await pane.setWidth(width) + await expect.element(page.getByRole('button', {name: 'More composer actions'})).toBeVisible() + await pane.setWidth(720) + await expect.element(page.getByRole('button', {name: 'Start a new session'})).toBeVisible() +}) +``` + +`mountPaneAtWidth` = existing pane mount helper wrapped in a fixed-width container div whose width the test controls through a style on the mount host (setting a container style is state the TEST owns, not app state — allowed). + +- [ ] **Step 2: Run to verify the new tests fail** — `pnpm vitest run test/composer-overflow.browser.test.tsx` (cwd `apps/conciv`). +- [ ] **Step 3: Implement pane-composer + actions migration per the code above.** +- [ ] **Step 4: Run the new suite AND the neighbors** — `pnpm vitest run test/composer-overflow.browser.test.tsx test/chat-pane.browser.test.tsx test/launch-menu.browser.test.tsx test/model-selector.browser.test.tsx` — Expected: PASS. +- [ ] **Step 5: Commit** + +```bash +git add apps/conciv/src apps/conciv/test/composer-overflow.browser.test.tsx +git commit -m "feat(conciv): collapse composer actions into overflow menu" -- apps/conciv +``` + +--- + +### Task 4: Migrate the launch menu (multi-item root) + +**Files:** +- Modify: `apps/conciv/src/composer/launch-menu.tsx`, `apps/conciv/src/composer/actions.tsx` +- Test: extend `apps/conciv/test/launch-menu.browser.test.tsx` + +**Interfaces:** +- Consumes: `ComposerActions` multi-`DropdownItem` support from Task 2. +- Produces: `LaunchMenu` keeps its exported props signature unchanged; gains collapsed rendering. + +`LaunchMenu` wraps itself in a `Root`; inline rendering is today's nested `Menu.Root` trigger placed inside `ComposerActions.Button`'s slot — use a `Button`-less root plus explicit inline JSX? No: keep it simple and faithful to the primitives — `Root id="conciv.launch" priority={10}` containing: + +- Inline: today's entire `Menu.Root` block wrapped in `` — expose this via a new primitive `ComposerActions.Inline(props: {children})` (added in this task to `composer-actions.tsx`: registers `hasButton` on the root, marks nothing pinned, renders children when inline). This is the `asChild` escape the spec's open item names. +- Collapsed: the same conditional item set as `DropdownItem`s: + +```tsx + + local.onOpen()}> + + local.onCopy()}> + + +}> + local.onRetry?.()}> + + +``` + +- [ ] **Step 1: Write failing test additions** — narrow pane: launch items appear flattened in the shared overflow menu (`menuitem` named `Open in `, `Copy command`); wide pane: launch trigger behaves exactly as the existing tests assert. +- [ ] **Step 2: Run to verify failure.** +- [ ] **Step 3: Add `ComposerActions.Inline` to `packages/extension/src/composer-actions.tsx`; migrate `LaunchMenu`.** +- [ ] **Step 4: Run** `pnpm vitest run test/launch-menu.browser.test.tsx test/launch-actions.browser.test.tsx test/composer-overflow.browser.test.tsx` — PASS. +- [ ] **Step 5: Commit** (`feat(conciv): launch menu flattens into composer overflow`, pathspec `packages/extension apps/conciv`). + +--- + +### Task 5: Migrate extension clients, scaffolds, and authoring docs + +**Files:** +- Modify: `packages/extensions/whiteboard/src/client.tsx`, `packages/extensions/tanstack/src/client.tsx`, `packages/extension/src/catalog.ts` (both `composer-action` and `full` templates + the composer slot description string), `packages/extension/test/catalog.test.ts`, `packages/harness/plugins/claude/skills/conciv-extensions/SKILL.md`, `apps/site/content/docs/extending/widget-ui.mdx` + +**Interfaces:** +- Consumes: `ComposerActions` from `@conciv/extension`. +- Produces: no authoring surface anywhere still demonstrates a raw composer button. + +Whiteboard `Component` becomes: + +```tsx + + + toggle()}> + + + toggle()}> + + + + + void pickComment()}> + + + void pickComment()}> + + + + +``` + +Tanstack client: same mechanical transform for its composer-gated buttons. Scaffold templates (`composer-action`, `full`) rewritten to author through `ComposerActions.Root/Button/DropdownItem`; composer slot catalog description updated to name the primitives; `catalog.test.ts` assertions updated to match verbatim template text. SKILL.md and `widget-ui.mdx` sections showing raw buttons rewritten around the same example. + +- [ ] **Step 1: Update `catalog.test.ts` expectations first (failing), run** `pnpm vitest run test/catalog.test.ts` (cwd `packages/extension`) — FAIL. +- [ ] **Step 2: Apply all migrations.** +- [ ] **Step 3: Gates** — `pnpm turbo run test --filter=@conciv/extension`, `pnpm turbo run test --filter=@conciv/extension-tanstack`, and for whiteboard typecheck/build/lint ONLY (suite is CI-only): `pnpm turbo run typecheck --filter=@conciv/extension-whiteboard && pnpm turbo run build --filter=@conciv/extension-whiteboard`. (Use the actual package names from each `package.json`.) +- [ ] **Step 4: Commit** (`feat(extensions): author composer buttons through ComposerActions`, pathspec the touched packages + site docs). + +--- + +### Task 6: Extension-testkit host support + fixture + +**Files:** +- Modify: `packages/extension-testkit/src/host/host-runtime.tsx` (wrap the composer-slot mount in `ComposerActionsHost` inside a width-controllable container) +- Test: the testkit's existing e2e app gains a fixture extension using Button + two DropdownItems (`packages/extension-testkit/e2e` — follow the existing fixture registration pattern there) + +**Interfaces:** +- Consumes: `ComposerActionsHost` from `@conciv/extension/host`. +- Produces: testkit hosts render extension `ComposerActions` exactly like the real app (coordinator + shared menu present). + +- [ ] **Step 1: Add a failing e2e asserting the fixture's button renders inline in a wide host and its items reach the shared overflow menu in a narrow host** (drive width through the testkit host page's own controls, same locator discipline as Task 3). +- [ ] **Step 2: Wrap the testkit composer mount in `ComposerActionsHost` (trailing can be an empty fragment).** +- [ ] **Step 3: Run the testkit suite** — `pnpm turbo run test --filter=@conciv/extension-testkit` — PASS. +- [ ] **Step 4: Commit** (`feat(extension-testkit): host composer actions coordinator`, pathspec `packages/extension-testkit`). + +--- + +### Task 7: Extract refresh from the composer + +**Files:** +- Modify: `packages/ui-kit-chat/src/primitives/composer/composer.tsx` (delete the `Refresh` action button + its export), `packages/ui-kit-chat/src/primitives/composer/composer-handlers.tsx` (delete `onRefresh`), `packages/ui-kit-chat/test/composer-completion.browser.test.tsx` (delete refresh-specific tests) +- Modify: `apps/conciv/src/app/pane-context.ts` + `apps/conciv/src/app/pane-provider.tsx` + `apps/conciv/src/routes/panel.$sessionId.tsx` (add refresh handle to `PaneContextValue`), `apps/conciv/src/pane/chat-pane.tsx` (register the handle, drop `onRefresh`), `apps/conciv/src/pane/pane-composer.tsx` (drop the refresh button) +- Create: `apps/conciv/src/shell/refresh-button.tsx` +- Modify: `apps/conciv/src/routes/panel.$sessionId.tsx` (header right cluster), `apps/conciv/src/routes/quick.tsx` (per-pane bar next to the pane's `SessionSelector`), `apps/conciv/src/routes/pip.$sessionId.tsx` (slim chrome row above `ChatPane`) +- Test: `apps/conciv/test/chat-pane.browser.test.tsx` (rewire the two refresh tests to the header button) + +**Interfaces:** +- Produces: `PaneContextValue` gains `refresh: Accessor` and `registerRefresh: (handle: RefreshHandle | null) => void` where `type RefreshHandle = {run: () => void; busy: () => boolean}`. `RefreshButton(props: {class?: string})` renders nothing while the handle is null. + +`pane-context.ts` additions and both `PaneContextValue` construction sites (`pane-provider.tsx`, `panel.$sessionId.tsx`): + +```tsx +const [refreshHandle, setRefreshHandle] = createSignal(null) +``` + +spread into the value as `refresh: refreshHandle, registerRefresh: setRefreshHandle`. + +`chat-pane.tsx`: replace the `onRefresh` handler entry with registration: + +```tsx +onMount(() => { + pane.registerRefresh({run: () => chat.refresh(), busy: () => chatBusy(chat)}) + onCleanup(() => pane.registerRefresh(null)) +}) +``` + +(`chatBusy` is exported by `@conciv/ui-kit-chat` — verify the export; if module-private, expose it or derive busy from the same chat state the deleted primitive used.) + +`refresh-button.tsx`: + +```tsx +import {Show, type JSX} from 'solid-js' +import RefreshCw from 'lucide-solid/icons/refresh-cw' +import {TooltipIconButton} from '@conciv/ui-kit-system' +import {usePane} from '../app/pane-context.js' + +export function RefreshButton(props: {class?: string}): JSX.Element { + const pane = usePane() + return ( + + {(handle) => ( + handle().run()} + > + + )} + + ) +} +``` + +Placements: panel header — before the close button (`panel.$sessionId.tsx` right cluster, reuse `CLOSE` class); quick — inside each pane's session bar (the `SessionSelector` row); pip — a `flex justify-end px-2 pt-1` row above `ChatPane`. + +- [ ] **Step 1: Rewrite the two refresh tests in `chat-pane.browser.test.tsx` against the header/pane-bar button (locator unchanged: role button name `'Refresh the conversation'`), run — FAIL.** +- [ ] **Step 2: Delete `Refresh` from ui-kit-chat composer + `onRefresh` from handlers + their ui-kit tests; implement PaneContext handle, `RefreshButton`, three placements.** +- [ ] **Step 3: Run** `pnpm turbo run test --filter=@conciv/ui-kit-chat` and `pnpm vitest run test/chat-pane.browser.test.tsx test/composer-overflow.browser.test.tsx` (cwd `apps/conciv`) — PASS. +- [ ] **Step 4: Fallow check for the deleted export** — `pnpm exec fallow dead-code --trace 'packages/ui-kit-chat/src/primitives/composer/composer.tsx:Refresh'` should report no remaining consumers before deletion lands. +- [ ] **Step 5: Commit** (`feat(conciv): session refresh moves to pane chrome, out of the composer`, pathspec `packages/ui-kit-chat apps/conciv`). + +--- + +### Task 8: Full gates, changeset, embed rebuild + +**Files:** +- Create: `.changeset/composer-actions-collapse.md` + +- [ ] **Step 1: Changeset** + +```md +--- +'@conciv/extension': patch +--- + +Composer actions collapse into a shared overflow menu; extensions author buttons through ComposerActions.Root/Button/DropdownItem. Session refresh moved out of the composer into pane chrome. +``` + +- [ ] **Step 2: Verify changeset coverage** — `pnpm exec conciv-publish check-changesets --require-coverage --base origin/main`. +- [ ] **Step 3: Embed rebuild + full gates** — `pnpm turbo run build --filter=@conciv/embed`, then `pnpm typecheck && pnpm test:affected`, then `pnpm exec fallow audit --changed-since main --format json` — fix anything INTRODUCED. +- [ ] **Step 4: Commit** (`chore: changeset for composer actions collapse`, pathspec `.changeset`). + +--- + +## Self-Review Notes + +- Spec §1 primitives → Tasks 1-2 (+`Inline` added in Task 4 per the spec's open item). §2 coordinator → Task 2-3. §3 built-ins + migration surfaces → Tasks 3-5. §4 refresh → Task 7. Testing section → Tasks 3, 4, 6, 7. Changeset/gates → Task 8. +- Deviation from spec, intentional: `RefreshButton` reads the handle from `PaneContext` on every surface (instead of `useChatContext` + a panel-only relay) because in quick mode and the panel the chrome sits above `ChatProvider`; one mechanism, three placements. +- Type names consistent across tasks: `FitInput`, `Registration`, `RefreshHandle`, `ComposerActionsHost`, `ComposerActions.{Root,Button,DropdownItem,Inline}`. From d96f5a1a05904c8b212b2071f0abe29531ba6202 Mon Sep 17 00:00:00 2001 From: Omri Katz <9701896+omridevk@users.noreply.github.com> Date: Sun, 16 Aug 2026 15:28:57 +0300 Subject: [PATCH 04/24] docs: fold codex + frontend review findings into composer actions plan Co-Authored-By: Claude Fable 5 --- .../2026-08-16-composer-actions-collapse.md | 498 ++++++++++-------- 1 file changed, 268 insertions(+), 230 deletions(-) diff --git a/docs/superpowers/plans/2026-08-16-composer-actions-collapse.md b/docs/superpowers/plans/2026-08-16-composer-actions-collapse.md index d55ba68845..3845cd0d40 100644 --- a/docs/superpowers/plans/2026-08-16-composer-actions-collapse.md +++ b/docs/superpowers/plans/2026-08-16-composer-actions-collapse.md @@ -4,37 +4,38 @@ **Goal:** Replace the saturated composer button row with compound `ComposerActions.*` primitives whose host coordinator collapses lower-priority actions into one shared overflow menu by measured width, and extract the session refresh affordance out of the composer into per-surface chrome. -**Architecture:** New `ComposerActions` compound components (Root/Button/DropdownItem) live in `@conciv/extension` (which already depends on `@conciv/ui-kit-system` for `TooltipIconButton`/`Menu`). A host-side `ComposerActionsProvider` + shared Ark `Menu.Root` wrap the composer toolbar row as logical Solid ancestors of both built-in actions and `ExtensionSurface name="composer"`. Fit is pure arithmetic over a constant slot width and two passive ResizeObservers. Refresh becomes a `RefreshButton` reading a refresh handle that `ChatPane` registers into `PaneContext` — one mechanism serving panel header, quick per-pane bar, and pip chrome. +**Architecture:** New `ComposerActions` compound components (Root/Button/DropdownItem/Inline) live in `@conciv/extension`. A host-side `ComposerActionsHost` (provider + shared Ark `Menu.Root`) wraps the composer toolbar row as a logical Solid ancestor of both built-in actions and `ExtensionSurface name="composer"`. Overflow-menu ordering is real DOM order: the host renders one group node per registered root sorted by priority, and each `DropdownItem` portals into its own root's group node (never CSS `order`). Fit is pure arithmetic over a constant slot width and passive resize observers. Refresh becomes a `RefreshButton` reading a refresh handle that `ChatPane` registers into `PaneContext`. **Tech Stack:** SolidJS, Ark UI Menu (zag), UnoCSS utility classes, vitest browser (Playwright/Chromium), oxlint/oxfmt. **Spec:** `docs/superpowers/specs/2026-08-16-composer-actions-collapse-design.md` +**Review inputs folded in:** codex plan review (`/tmp/codex-plan-review.md`) + frontend review — all HIGH/CRITICAL findings addressed inline below. + ## Global Constraints -- Functions only, no classes, no IIFEs, ZERO code comments (lint deletes them). +- Functions only, no classes, no IIFEs, ZERO code comments (lint deletes them) — including in test code. - Strict TS: no `any`, no `as` casts, no non-null assertions, `noUncheckedIndexedAccess`. - oxfmt: no semicolons, single quotes, no bracket spacing, trailing commas, printWidth 120. -- Solid: use `splitProps` (never destructure props), `@solid-primitives` over raw signal glue, no hooks inside JSX attributes, `Show`/`For` over ternaries. -- Every Solid package `vitest.config.ts` pins `test: {environment: 'node'}`. -- Widget UI tests run in REAL Chromium (vitest browser), never jsdom. Web-first assertions only: no `poll`, no `querySelector`, no rect measurement, no sleeps, no test-ids. Locate by role/name. -- Never `newContext()` in widget ITs — `browser.newPage()` pattern; these tests use `@vitest/browser` page/userEvent. -- Whiteboard package test suite NEVER runs locally — local gates for whiteboard changes: typecheck/build/lint only. -- Package test gates: `pnpm turbo run test --filter=` (bare filter — NEVER trailing `...`). -- New UnoCSS utility classes in ui-kit src need an embed rebuild to appear: `pnpm turbo run build --filter=@conciv/embed`. -- Commit with pathspec (`git commit -- `); run `pnpm exec fallow audit --format json --quiet --explain --gate-marker agent` before each commit (JSON runtime errors non-blocking). -- All UI copy sentence-case, matches existing tone (`'More composer actions'`). +- Solid: `splitProps` (never destructure props), `@solid-primitives` over raw observer glue, no hooks inside JSX attributes, register context state synchronously in component bodies (NOT `onMount`) with `onCleanup` — `Suspense`/lazy boundaries make mount-order assumptions fragile. +- Widget UI tests: REAL Chromium (vitest browser), never jsdom. Web-first assertions only; no `poll`, no `querySelector`, no rect measurement, no sleeps, no test-ids. Locate by role/name. Assert `aria-disabled`/`toBeDisabled()`, never zag styling hooks like `data-disabled`. +- Whiteboard package suite NEVER runs locally: whiteboard gates are typecheck + build + lint only. +- Package test gates finish with `pnpm turbo run test --filter=` (bare filter, NEVER trailing `...`); focused `pnpm vitest run` is for red/green iteration only. +- New UnoCSS classes need scanner coverage AND an embed rebuild (`pnpm turbo run build --filter=@conciv/embed`). +- Commit with pathspec; run `pnpm exec fallow audit --format json --quiet --explain --gate-marker agent` before each commit (JSON runtime errors non-blocking). `fallow dead-code --trace` runs BEFORE deleting an export, not after. +- **Dependency gate:** Task 2 adds `@solid-primitives/resize-observer` to `@conciv/extension` (already used by ui-kit-chat). This dependency addition has been approved by the user for this plan; add exactly this package, nothing else, no version pinning beyond the workspace convention. ## Layout constants (used across tasks) -Action buttons are `size-8.5` (2.125rem = 34px) with row `gap-1` (4px): +Action buttons are `size-8.5` (34px) in a `gap-1` (4px) row. Slot = width + one gap; the budget additionally charges one region gap on each side of the managed region: ```ts export const ACTION_SLOT_PX = 38 +export const REGION_GAP_PX = 4 export const FIT_HYSTERESIS_PX = 24 ``` -The overflow trigger permanently occupies one slot in the row (visibility-hidden when no item is collapsed), so the arithmetic never feeds back into itself. +The overflow trigger permanently occupies one slot (visibility-hidden placeholder when nothing is collapsed), so trigger appearance never feeds back into the fit input. --- @@ -45,32 +46,35 @@ The overflow trigger permanently occupies one slot in the row (visibility-hidden - Test: `packages/extension/test/composer-actions-fit.test.ts` **Interfaces:** -- Produces: `computeVisibleAutoCount(input: FitInput): number`, `type FitInput`, constants `ACTION_SLOT_PX`, `FIT_HYSTERESIS_PX`. Task 2 consumes all of these. +- Produces: `computeVisibleAutoCount(input: FitInput): number`, `type FitInput`, constants `ACTION_SLOT_PX`, `REGION_GAP_PX`, `FIT_HYSTERESIS_PX`. Task 2 consumes all of these. - [ ] **Step 1: Write the failing test** ```ts import {describe, expect, it} from 'vitest' -import {ACTION_SLOT_PX, FIT_HYSTERESIS_PX, computeVisibleAutoCount} from '../src/composer-actions-fit.js' +import {ACTION_SLOT_PX, FIT_HYSTERESIS_PX, REGION_GAP_PX, computeVisibleAutoCount} from '../src/composer-actions-fit.js' const base = { slotWidth: ACTION_SLOT_PX, + regionGapPx: REGION_GAP_PX, hysteresisPx: FIT_HYSTERESIS_PX, - leadingWidth: 38, + leadingWidth: 34, trailingWidth: 120, pinnedCount: 1, autoCount: 4, previousCount: null, } +const used = (autoSlots: number): number => + base.leadingWidth + base.trailingWidth + 2 * REGION_GAP_PX + ACTION_SLOT_PX + base.pinnedCount * ACTION_SLOT_PX + autoSlots * ACTION_SLOT_PX + describe('computeVisibleAutoCount', () => { it('shows every auto action when the budget covers them', () => { - expect(computeVisibleAutoCount({...base, rowWidth: 600})).toBe(4) + expect(computeVisibleAutoCount({...base, rowWidth: used(4) + 40})).toBe(4) }) it('clamps to the available whole slots', () => { - const rowWidth = 38 + 120 + 38 + 38 + 2 * 38 + 10 - expect(computeVisibleAutoCount({...base, rowWidth})).toBe(2) + expect(computeVisibleAutoCount({...base, rowWidth: used(2) + 10})).toBe(2) }) it('never returns a negative count', () => { @@ -82,27 +86,22 @@ describe('computeVisibleAutoCount', () => { }) it('shrinks immediately when the row narrows', () => { - const rowWidth = 38 + 120 + 38 + 38 + 38 - expect(computeVisibleAutoCount({...base, rowWidth, previousCount: 4})).toBe(1) + expect(computeVisibleAutoCount({...base, rowWidth: used(1) + 2, previousCount: 4})).toBe(1) }) it('expands only once the budget clears the hysteresis margin', () => { - const exact = 38 + 120 + 38 + 38 + 2 * 38 - expect(computeVisibleAutoCount({...base, rowWidth: exact + 4, previousCount: 1})).toBe(1) - expect(computeVisibleAutoCount({...base, rowWidth: exact + FIT_HYSTERESIS_PX, previousCount: 1})).toBe(2) + expect(computeVisibleAutoCount({...base, rowWidth: used(2) + 4, previousCount: 1})).toBe(1) + expect(computeVisibleAutoCount({...base, rowWidth: used(2) + FIT_HYSTERESIS_PX, previousCount: 1})).toBe(2) }) }) ``` -- [ ] **Step 2: Run test to verify it fails** - -Run: `pnpm vitest run test/composer-actions-fit.test.ts` (cwd `packages/extension`) -Expected: FAIL — module not found. - -- [ ] **Step 3: Write the implementation** +- [ ] **Step 2: Run to verify failure** — `pnpm vitest run test/composer-actions-fit.test.ts` (cwd `packages/extension`) — FAIL, module not found. +- [ ] **Step 3: Implement** ```ts export const ACTION_SLOT_PX = 38 +export const REGION_GAP_PX = 4 export const FIT_HYSTERESIS_PX = 24 export type FitInput = { @@ -110,6 +109,7 @@ export type FitInput = { leadingWidth: number trailingWidth: number slotWidth: number + regionGapPx: number pinnedCount: number autoCount: number previousCount: number | null @@ -117,9 +117,9 @@ export type FitInput = { } export function computeVisibleAutoCount(input: FitInput): number { - const triggerWidth = input.slotWidth - const budget = - input.rowWidth - input.leadingWidth - input.trailingWidth - triggerWidth - input.pinnedCount * input.slotWidth + const reserved = + input.leadingWidth + input.trailingWidth + 2 * input.regionGapPx + input.slotWidth + input.pinnedCount * input.slotWidth + const budget = input.rowWidth - reserved const fits = Math.max(0, Math.min(input.autoCount, Math.floor(budget / input.slotWidth))) if (input.previousCount === null || fits <= input.previousCount) return fits if (budget < fits * input.slotWidth + input.hysteresisPx) return input.previousCount @@ -127,16 +127,8 @@ export function computeVisibleAutoCount(input: FitInput): number { } ``` -- [ ] **Step 4: Run test to verify it passes** - -Run: `pnpm vitest run test/composer-actions-fit.test.ts` — Expected: PASS. - -- [ ] **Step 5: Commit** - -```bash -git add packages/extension/src/composer-actions-fit.ts packages/extension/test/composer-actions-fit.test.ts -git commit -m "feat(extension): composer actions fit arithmetic" -- packages/extension -``` +- [ ] **Step 4: Green + package gate** — focused run passes, then `pnpm turbo run test --filter=@conciv/extension`. +- [ ] **Step 5: Commit** (`feat(extension): composer actions fit arithmetic`, pathspec `packages/extension`). --- @@ -144,80 +136,102 @@ git commit -m "feat(extension): composer actions fit arithmetic" -- packages/ext **Files:** - Create: `packages/extension/src/composer-actions.tsx` -- Modify: `packages/extension/src/index.tsx` (export `ComposerActions`), `packages/extension/src/host.ts` (export `ComposerActionsHost`) +- Modify: `packages/extension/src/index.ts` (export `ComposerActions`), `packages/extension/src/host.ts` (export `ComposerActionsHost`), `packages/extension/package.json` (add `@solid-primitives/resize-observer` — approved, see Global Constraints), `packages/embed/uno.config.ts` + `apps/conciv/uno.config.ts` (add `../extension/src/**/*.{ts,tsx}` — relative to each config — to the scanned globs; without this the new utility classes never reach the built CSS) **Interfaces:** -- Consumes: Task 1's `computeVisibleAutoCount`, `ACTION_SLOT_PX`, `FIT_HYSTERESIS_PX`; `Menu`, `TooltipIconButton` from `@conciv/ui-kit-system`. -- Produces (extension-author surface, exported from `@conciv/extension`): - - `ComposerActions.Root(props: {id: string; priority?: number; children: JSX.Element})` - - `ComposerActions.Button(props: {visible?: 'auto' | 'always'; tooltip: string; onClick: () => void; disabled?: boolean; children: JSX.Element})` - - `ComposerActions.DropdownItem(props: {value: string; label: string; onSelect: () => void; disabled?: boolean; children?: JSX.Element})` -- Produces (host surface, exported from `@conciv/extension/host`): - - `ComposerActionsHost(props: {leading?: JSX.Element; trailing: JSX.Element; children: JSX.Element})` — renders the toolbar row: leading region, managed children, permanent trigger slot, trailing region; owns provider, shared `Menu.Root`, both observers. +- Consumes: Task 1's `computeVisibleAutoCount` + constants; `Menu`, `TooltipIconButton`, `TooltipIconButtonSlot` from `@conciv/ui-kit-system` (first RUNTIME import of ui-kit-system in this package — manifest dep already present); `createResizeObserver` from `@solid-primitives/resize-observer`. +- Produces (extension-author surface, from `@conciv/extension`): + - `ComposerActions.Root(props: {id: string; priority?: number; disabled?: () => boolean; children: JSX.Element})` — `disabled` is THE single reactive source; both renderings consume it (spec requirement; per-child disabled props do not exist). + - `ComposerActions.Button(props: {visible?: 'auto' | 'always'; tooltip: string; onClick: () => void; busy?: boolean; class?: string; variant?: 'ghost' | 'solid'; children: JSX.Element})` — `busy` renders `aria-busy` + progress styling, it does NOT disable. + - `ComposerActions.DropdownItem(props: {value: string; label: string; onSelect: () => void; children?: JSX.Element})` + - `ComposerActions.Inline(props: {children: JSX.Element})` — renders children only while the root is inline; counts as the root's button for fit purposes (the `asChild` escape for controls that are themselves triggers). +- Produces (host surface, from `@conciv/extension/host`): + - `ComposerActionsHost(props: {leading?: JSX.Element; trailing: JSX.Element; triggerContent: JSX.Element; children: JSX.Element})` — no icon-library dependency in this package; the app passes the ellipsis icon via `triggerContent`. -**Implementation shape (write exactly this structure):** +**Implementation contract (settled types — write exactly these):** ```tsx -import {For, Show, createContext, createMemo, createSignal, createUniqueId, onCleanup, onMount, splitProps, useContext, type Accessor, type JSX} from 'solid-js' -import {Portal} from 'solid-js/web' -import {createStore, produce} from 'solid-js/store' -import Ellipsis from 'lucide-solid/icons/ellipsis' -import {Menu, TooltipIconButton, TooltipIconButtonSlot} from '@conciv/ui-kit-system' -import {ACTION_SLOT_PX, FIT_HYSTERESIS_PX, computeVisibleAutoCount} from './composer-actions-fit.js' - -type Registration = {key: string; id: string; priority: number; pinned: boolean; hasButton: boolean} +type Registration = { + key: string + id: string + priority: number + pinned: boolean + hasButton: boolean + itemCount: number + disabled: () => boolean +} type Coordinator = { register: (entry: Registration) => void - update: (key: string, patch: Partial) => void + update: (key: string, patch: Partial>) => void unregister: (key: string) => void - inlineKeys: Accessor> - menuMount: Accessor + active: (key: string) => boolean + inline: (key: string) => boolean + groupMount: (key: string) => HTMLElement | undefined } -const CoordinatorContext = createContext() -type RootState = {key: string; id: string; priority: number; inline: Accessor; setPinned: (pinned: boolean) => void; setHasButton: (has: boolean) => void} -const RootContext = createContext() +type RootState = { + key: string + id: string + priority: number + disabled: () => boolean + inline: () => boolean + update: (patch: Partial>) => void +} ``` -Coordinator internals (inside `ComposerActionsHost`): +Coordinator rules (inside `ComposerActionsHost`): + +- Store: `createStore([])`. `Root` registers **synchronously in its component body** (`createUniqueId()` key), `onCleanup` unregisters. `priority`/`disabled` changes tracked with a `createEffect` that calls `update` (Solid props are getters; no stale metadata). +- Duplicate `id`: the LAST registration with that id is the active one — `active(key)` returns false for earlier holders, whose Roots render nothing (inline and menu). Warn unconditionally with `console.warn` once per collision. +- Widths: `createResizeObserver` on three refs — outer row, leading wrapper, trailing wrapper. Wrappers carry `class="empty:hidden flex gap-1 items-center"` so an empty region costs nothing. +- Count memo — hysteresis via the memo's OWN previous value, no extra signal: + +```tsx +const visibleAutoCount = createMemo( + (previous) => + computeVisibleAutoCount({ + rowWidth: rowWidth(), + leadingWidth: leadingWidth(), + trailingWidth: trailingWidth(), + slotWidth: ACTION_SLOT_PX, + regionGapPx: REGION_GAP_PX, + pinnedCount: pinnedCount(), + autoCount: autoCount(), + previousCount: previous, + hysteresisPx: FIT_HYSTERESIS_PX, + }), + null, +) +``` -- `const [entries, setEntries] = createStore([])`; register appends, update patches by key, unregister filters. Duplicate `id`: `console.warn` in dev, keep both entries keyed by `key` (unique per mount) so last mount wins visually. -- `const [rowWidth, setRowWidth] = createSignal(0)` etc. for leading/trailing wrappers; one `ResizeObserver` per element via `createEffect` + `onCleanup` (same pattern as `useSizeHandle`). -- `const [previous, setPrevious] = createSignal(null)`; `visibleAutoCount` memo calls `computeVisibleAutoCount` with `pinnedCount = entries pinned+hasButton count`, `autoCount = entries auto+hasButton count`, then `setPrevious`. -- `inlineKeys` memo: all pinned keys, plus the first `visibleAutoCount()` auto entries sorted by priority desc then insertion order. -- Row JSX: `Menu.Root` (from ui-kit-system, `positioning={{placement: 'top-end'}}`) wrapping the whole row `div.pt-0.5.flex.gap-1.items-center`; inside: leading wrapper div (observer target), `{props.children}`, trigger slot, trailing wrapper div with `ml-auto` (observer target). Trigger slot: +- `inline(key)`: pinned actives with a button always inline; auto actives with a button sorted priority desc then registration order, first `visibleAutoCount()` inline. +- **Menu ordering is DOM order, never CSS `order`:** inside `Menu.Content` the host renders `{(entry) =>
setGroupEl(entry.key, el)} />}` sorted priority desc then registration order. Each `DropdownItem` portals into ITS root's group node via `coordinator.groupMount(root.key)`. Visual order = DOM order = zag keyboard order; a root's items stay contiguous. `Menu.Content` keeps its default classes — no `flex` (its base is `hidden data-[state=open]:block`; adding `flex` creates a display conflict). +- Trigger slot (always occupies one slot): ```tsx - - - ``` -`anyCollapsed()` = any entry with `hasDropdownItems` not in `inlineKeys()` — track item counts per key in the store (`items: number`, incremented/decremented by `DropdownItem` mount/cleanup through `RootContext`). +`TRIGGER_CLASS` is defined locally in `composer-actions.tsx` on the `TooltipIconButton` ghost variant sizing (`'size-8.5'`) — `GHOST` from pane-composer is app-private and must not be referenced. -Component behavior: - -- `Root`: `createUniqueId()` key; registers on mount, unregisters on cleanup; provides `RootContext` with `inline: () => coordinator.inlineKeys().has(key)`. Outside a coordinator (`useContext` undefined): render nothing (``). -- `Button`: on mount `root.setHasButton(true)` and `root.setPinned(props.visible === 'always')`; renders `` → `TooltipIconButton` with `class="size-8.5"`, `tooltip`, `onClick`, `disabled`. -- `DropdownItem`: increments the root's item count on mount; renders +- `anyCollapsed()` = any active root with `itemCount > 0` not inline. +- **Menu-open collapse race:** control the menu (`Menu.Root open={menuOpen()} onOpenChange={...}` or `Menu.Context` api). A `createEffect` watching `anyCollapsed()`: on transition to false while open, close the menu and move focus to the trigger's nearest surviving focusable — the first inline action button if one exists, else the composer input (host prop `onOverflowDismissed?: () => void` lets the app focus the input). Without this, expanding while the menu is open strands focus on ``. +- `Button`: sets `hasButton` + pinned via `root.update` synchronously, `onCleanup` resets `hasButton: false`. Renders `` → `TooltipIconButton` with `class`/`variant` passthrough, `aria-busy={props.busy}`, `disabled={root.disabled()}`. +- `Inline`: same registration behavior as `Button` (`hasButton: true`, never pinned unless later needed), renders children when `root.inline()`. +- `DropdownItem`: `root.update` increments `itemCount` synchronously, `onCleanup` decrements. Renders ```tsx - + {(mount) => ( - props.onSelect()} style={{order: String(-root.priority)}}> + props.onSelect()}> {props.children} {props.label} @@ -226,37 +240,32 @@ Component behavior: ``` -Menu ordering uses flex `order: -priority` on the flex-col content (portal insertion order is mount order, which is not priority order). - -- [ ] **Step 1: Write `composer-actions.tsx` per the shape above; export `ComposerActions = {Root, Button, DropdownItem}` from `index.tsx` and `ComposerActionsHost` from `host.ts`** -- [ ] **Step 2: Typecheck + build gate** +- Root outside a coordinator: renders nothing. +- Row JSX: `Menu.Root` wraps `div class="pt-0.5 flex gap-1 items-center"` containing leading wrapper, `{props.children}`, trigger slot, trailing wrapper (`ml-auto` + `empty:hidden`), then `Menu.Positioner > Menu.Content` with the group `For`. -Run: `pnpm turbo run build --filter=@conciv/extension && pnpm turbo run typecheck --filter=@conciv/extension` -Expected: green. (Behavior coverage lands in Task 3's browser tests — primitives have no browser harness in this package.) - -- [ ] **Step 3: Commit** - -```bash -git add packages/extension/src -git commit -m "feat(extension): ComposerActions compound primitives with overflow coordinator" -- packages/extension -``` +- [ ] **Step 1: Add the dependency** — `@solid-primitives/resize-observer` to `packages/extension/package.json` (match the version ui-kit-chat uses), `pnpm install`. +- [ ] **Step 2: Write `composer-actions.tsx` per the contract; export `ComposerActions` from `index.ts`, `ComposerActionsHost` from `host.ts`; extend both uno configs.** +- [ ] **Step 3: Gates** — `pnpm turbo run build --filter=@conciv/extension && pnpm turbo run typecheck --filter=@conciv/extension && pnpm turbo run test --filter=@conciv/extension`, then the bundling guard NOW (not Task 8): `pnpm turbo run build --filter=@conciv/embed` and `pnpm turbo run test --filter=@conciv/embed` (mount-externals test must stay green — the extension contract now carries runtime Ark/tooltip imports). +- [ ] **Step 4: Commit** (`feat(extension): ComposerActions compound primitives with overflow coordinator`, pathspec `packages/extension packages/embed apps/conciv/uno.config.ts pnpm-lock.yaml`). --- -### Task 3: Wire the coordinator into `PaneComposer`, migrate grab/new-session/compact +### Task 3: Wire the coordinator into `PaneComposer`, migrate built-ins **Files:** -- Modify: `apps/conciv/src/pane/pane-composer.tsx` (toolbar row becomes `ComposerActionsHost`), `apps/conciv/src/composer/actions.tsx` (grab/new-session/compact on new primitives) +- Modify: `apps/conciv/src/pane/pane-composer.tsx`, `apps/conciv/src/composer/actions.tsx`, `apps/conciv/src/pane/chat-pane.tsx` +- Modify: `apps/conciv/test/helpers/pane-harness.tsx` (width control) - Test: `apps/conciv/test/composer-overflow.browser.test.tsx` (new) **Interfaces:** - Consumes: `ComposerActionsHost` from `@conciv/extension/host`, `ComposerActions` from `@conciv/extension`. -- Produces: the toolbar row DOM contract every later task tests against — leading = attachment button, managed = built-ins + `ExtensionSurface name="composer"`, trailing = model selector + send/cancel; trigger named `'More composer actions'`. +- Produces: toolbar row contract — leading = attachment button; managed = built-ins + `ExtensionSurface name="composer"`; trailing = `trailingExtras` (model selector, in its own `Suspense`) + refresh + send/cancel; trigger named `'More composer actions'`. Harness API: `mountPane(options & {width?: number})` returning `{setWidth(px: number): void}` alongside its existing returns (drives a reactive style width on the harness wrapper — the `w-100` hardcode becomes the 400px default). -**pane-composer.tsx** — replace the row `div` (currently lines 127-139) with: +**pane-composer.tsx** — replace the row div; REFRESH STAYS HERE UNTIL TASK 7 (do not delete it in this task): ```tsx ``` -`TrailingControls` loses the refresh slot in Task 7; until then keep `ComposerSendControl` only here and leave `TrailingControls` unused-free by deleting it in this task (send control is the only survivor; refresh temporarily stays where it is — do NOT touch it in this task). The model selector stays in `props.children` order-wise? No — move `SessionModelSelector` into `trailing` at the `chat-pane.tsx` call site: pass it via a new `PaneComposerProps.trailingExtras?: JSX.Element` rendered before the send control inside `trailing`. Keep the change minimal: `chat-pane.tsx` renders `` through that prop instead of as a child. +`TrailingControls` (refresh + send) is UNCHANGED in this task. `PaneComposerProps` gains `trailingExtras?: JSX.Element`; `chat-pane.tsx` moves `` out of children into `trailingExtras`. The slot-sized Suspense fallback keeps the trailing observer from jumping while models load. + +**actions.tsx** — the app component keeps its exported name; the primitives are imported under a non-colliding alias: + +```tsx +import {ComposerActions as Action} from '@conciv/extension' +``` -**actions.tsx** — each button becomes a `Root`: +(`ComposerActions` the app component at line 39 stays exported — chat-pane imports it by that name.) ```tsx - - + void pick()} > - - - - props.onNewSession()}> + + + + props.onNewSession()}> - - props.onNewSession()}> + + props.onNewSession()}> - - - props.onCompact()}> + + + props.compacting}> + props.onCompact()}> - - props.onCompact()}> + + props.onCompact()}> - + + + + + + + + + ``` -(Launch menu migrates in Task 4 — leave `LaunchMenu` rendered as-is inside the managed region for now.) +Grab keeps its ACT/busyClass styling contract and is NOT disabled while picking (`busy` only) — behavior preserved. Launch is coordinator-registered from day one via `Inline` so the fit budget counts it (its dropdown flattening lands in Task 4). -- [ ] **Step 1: Write the failing browser test** (`composer-overflow.browser.test.tsx`, modeled on `chat-pane.browser.test.tsx` setup — same kit/mount helpers). Assertions: +**pane-harness.tsx**: `w-100` becomes `style={{width: \`${width()}px\`}}` with `width` a signal defaulting to 400; `mountPane` accepts `width?` and returns `setWidth`. Before writing tests, verify with the fit constants that at 400px every built-in stays inline (leading 34 + 2 gaps + trigger 38 + grab 38 + 3 autos 114 + trailing ≈ 110 ≈ 342 < 400) so the neighbor suites (launch-menu, launch-actions, model-selector, chat-pane) keep their inline-button locators working; if the real trailing cluster measures wider, raise the harness default so they do, and say so in the commit. + +- [ ] **Step 1: Write the failing browser tests** (`composer-overflow.browser.test.tsx`, using the harness + kit helpers exactly as `chat-pane.browser.test.tsx` does): ```tsx test('wide panel keeps every action inline with no overflow trigger', async () => { - await mountPaneAtWidth(720) + await mountPane({width: 720}) await expect.element(page.getByRole('button', {name: 'Start a new session'})).toBeVisible() await expect.element(page.getByRole('button', {name: 'Compress the conversation'})).toBeVisible() await expect.element(page.getByRole('button', {name: 'More composer actions'})).not.toBeInTheDocument() }) -test('narrow panel collapses auto actions into the overflow menu and keeps the pinned grab inline', async () => { - await mountPaneAtWidth(360) +test('narrow panel collapses auto actions and keeps the pinned grab inline', async () => { + await mountPane({width: 320}) await expect.element(page.getByRole('button', {name: 'Select an element from the page'})).toBeVisible() await expect.element(page.getByRole('button', {name: 'Start a new session'})).not.toBeInTheDocument() - await page.getByRole('button', {name: 'More composer actions'}).click() + const trigger = page.getByRole('button', {name: 'More composer actions'}) + await expect.element(trigger).toHaveAttribute('aria-haspopup', 'menu') + await trigger.click() + await expect.element(trigger).toHaveAttribute('aria-expanded', 'true') await expect.element(page.getByRole('menuitem', {name: 'Start a new session'})).toBeVisible() }) -test('overflow menu items fire the same action', async () => { - await mountPaneAtWidth(360) +test('an overflow item fires its action and the menu closes', async () => { + const pane = await mountPane({width: 320}) await page.getByRole('button', {name: 'More composer actions'}).click() await page.getByRole('menuitem', {name: 'Start a new session'}).click() - // assert the same observable outcome the existing new-session test asserts (navigation/session creation via the kit) + await expect.element(page.getByRole('menu')).not.toBeVisible() + await pane.expectNewSessionRequested() }) -test('keyboard lifecycle: open with keyboard, arrow to an item, Escape returns focus to the trigger', async () => { - await mountPaneAtWidth(360) +test('keyboard lifecycle on the trigger', async () => { + await mountPane({width: 320}) const trigger = page.getByRole('button', {name: 'More composer actions'}) - await trigger.click() + await trigger.element().focus() + await userEvent.keyboard('{Enter}') + await expect.element(page.getByRole('menu')).toBeVisible() await userEvent.keyboard('{ArrowDown}') await userEvent.keyboard('{Escape}') await expect.element(page.getByRole('menu')).not.toBeVisible() await expect.element(trigger).toHaveFocus() }) -test('disabled root is disabled in both renderings', async () => { - // mount with compacting=true fixture state - await mountPaneAtWidth(360) +test('a disabled root cannot be invoked from the menu', async () => { + const pane = await mountPane({width: 320, compacting: true}) await page.getByRole('button', {name: 'More composer actions'}).click() - await expect.element(page.getByRole('menuitem', {name: 'Compress the conversation'})).toHaveAttribute('data-disabled') + const item = page.getByRole('menuitem', {name: 'Compress the conversation'}) + await expect.element(item).toHaveAttribute('aria-disabled', 'true') + await item.click({force: true}) + await pane.expectNoCompactRequested() }) -test('repeated resize across the collapse threshold settles without flapping', async () => { - const pane = await mountPaneAtWidth(720) - for (const width of [360, 720, 360, 720, 360]) await pane.setWidth(width) - await expect.element(page.getByRole('button', {name: 'More composer actions'})).toBeVisible() +test('expanding while the menu is open closes it without stranding focus', async () => { + const pane = await mountPane({width: 320}) + await page.getByRole('button', {name: 'More composer actions'}).click() await pane.setWidth(720) + await expect.element(page.getByRole('menu')).not.toBeVisible() await expect.element(page.getByRole('button', {name: 'Start a new session'})).toBeVisible() }) -``` -`mountPaneAtWidth` = existing pane mount helper wrapped in a fixed-width container div whose width the test controls through a style on the mount host (setting a container style is state the TEST owns, not app state — allowed). +test('repeated resize across the threshold settles without flapping', async () => { + const pane = await mountPane({width: 720}) + for (const width of [320, 720, 320, 720, 320]) pane.setWidth(width) + await expect.element(page.getByRole('button', {name: 'More composer actions'})).toBeVisible() + pane.setWidth(720) + await expect.element(page.getByRole('button', {name: 'Start a new session'})).toBeVisible() +}) +``` -- [ ] **Step 2: Run to verify the new tests fail** — `pnpm vitest run test/composer-overflow.browser.test.tsx` (cwd `apps/conciv`). -- [ ] **Step 3: Implement pane-composer + actions migration per the code above.** -- [ ] **Step 4: Run the new suite AND the neighbors** — `pnpm vitest run test/composer-overflow.browser.test.tsx test/chat-pane.browser.test.tsx test/launch-menu.browser.test.tsx test/model-selector.browser.test.tsx` — Expected: PASS. -- [ ] **Step 5: Commit** +`expectNewSessionRequested` / `expectNoCompactRequested` / `compacting` are harness options wired to the same fixture callbacks the existing suite passes to `ChatPane`/`PaneProvider` — extend the harness options, not app state. -```bash -git add apps/conciv/src apps/conciv/test/composer-overflow.browser.test.tsx -git commit -m "feat(conciv): collapse composer actions into overflow menu" -- apps/conciv -``` +- [ ] **Step 2: Run to verify failure** — `pnpm vitest run test/composer-overflow.browser.test.tsx` (cwd `apps/conciv`). +- [ ] **Step 3: Implement pane-composer + actions migration + harness width control per the blocks above.** +- [ ] **Step 4: Run the new suite AND neighbors** — `pnpm vitest run test/composer-overflow.browser.test.tsx test/chat-pane.browser.test.tsx test/launch-menu.browser.test.tsx test/launch-actions.browser.test.tsx test/model-selector.browser.test.tsx` — PASS (refresh tests still pass: refresh is untouched). +- [ ] **Step 5: Package gate + commit** — `pnpm turbo run test --filter=@conciv/conciv` (use the app's real package name from `apps/conciv/package.json`), then commit (`feat(conciv): collapse composer actions into overflow menu`, pathspec `apps/conciv`). --- -### Task 4: Migrate the launch menu (multi-item root) +### Task 4: Launch menu flattening (multi-item root) **Files:** -- Modify: `apps/conciv/src/composer/launch-menu.tsx`, `apps/conciv/src/composer/actions.tsx` +- Modify: `apps/conciv/src/composer/launch-menu.tsx` - Test: extend `apps/conciv/test/launch-menu.browser.test.tsx` **Interfaces:** -- Consumes: `ComposerActions` multi-`DropdownItem` support from Task 2. -- Produces: `LaunchMenu` keeps its exported props signature unchanged; gains collapsed rendering. - -`LaunchMenu` wraps itself in a `Root`; inline rendering is today's nested `Menu.Root` trigger placed inside `ComposerActions.Button`'s slot — use a `Button`-less root plus explicit inline JSX? No: keep it simple and faithful to the primitives — `Root id="conciv.launch" priority={10}` containing: +- Consumes: `Action.Inline` + multi-`DropdownItem` from Task 2/3; `LaunchMenu` props signature unchanged. -- Inline: today's entire `Menu.Root` block wrapped in `` — expose this via a new primitive `ComposerActions.Inline(props: {children})` (added in this task to `composer-actions.tsx`: registers `hasButton` on the root, marks nothing pinned, renders children when inline). This is the `asChild` escape the spec's open item names. -- Collapsed: the same conditional item set as `DropdownItem`s: +`LaunchMenu` gains collapsed items as siblings of the `Inline` block inside the Task 3 `Action.Root id="conciv.launch"` (move the `Root` wrapper from `actions.tsx` into `LaunchMenu` itself so the component owns both renderings; `actions.tsx` then renders bare ``): ```tsx - - local.onOpen()}> - - local.onCopy()}> - - -}> - local.onRetry?.()}> - - + local.pending === true}> + {existing Menu.Root block, unchanged} + + local.onOpen()}> + + local.onCopy()}> + + + } + > + local.onRetry?.()} + > + + + ``` -- [ ] **Step 1: Write failing test additions** — narrow pane: launch items appear flattened in the shared overflow menu (`menuitem` named `Open in `, `Copy command`); wide pane: launch trigger behaves exactly as the existing tests assert. +- [ ] **Step 1: Failing tests** — narrow pane: `menuitem` named `Open in ` and `Copy command` inside the shared overflow menu, contiguous; failure state shows the retry item instead. Wide pane: existing launch tests unchanged. - [ ] **Step 2: Run to verify failure.** -- [ ] **Step 3: Add `ComposerActions.Inline` to `packages/extension/src/composer-actions.tsx`; migrate `LaunchMenu`.** -- [ ] **Step 4: Run** `pnpm vitest run test/launch-menu.browser.test.tsx test/launch-actions.browser.test.tsx test/composer-overflow.browser.test.tsx` — PASS. -- [ ] **Step 5: Commit** (`feat(conciv): launch menu flattens into composer overflow`, pathspec `packages/extension apps/conciv`). +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run** launch + overflow + chat-pane suites — PASS; package gate. +- [ ] **Step 5: Commit** (`feat(conciv): launch menu flattens into composer overflow`, pathspec `apps/conciv`). --- -### Task 5: Migrate extension clients, scaffolds, and authoring docs +### Task 5: Migrate extension clients, scaffolds, authoring docs **Files:** -- Modify: `packages/extensions/whiteboard/src/client.tsx`, `packages/extensions/tanstack/src/client.tsx`, `packages/extension/src/catalog.ts` (both `composer-action` and `full` templates + the composer slot description string), `packages/extension/test/catalog.test.ts`, `packages/harness/plugins/claude/skills/conciv-extensions/SKILL.md`, `apps/site/content/docs/extending/widget-ui.mdx` +- Modify: `packages/extensions/whiteboard/src/client.tsx`, `packages/extensions/tanstack/src/client.tsx`, `packages/extension/src/catalog.ts` (`composer-action` AND `full` templates + the composer slot description), `packages/extension/test/catalog.test.ts`, `packages/harness/plugins/claude/skills/conciv-extensions/SKILL.md`, `apps/site/content/docs/extending/widget-ui.mdx` -**Interfaces:** -- Consumes: `ComposerActions` from `@conciv/extension`. -- Produces: no authoring surface anywhere still demonstrates a raw composer button. +**Interfaces:** no authoring surface anywhere still demonstrates a raw composer button. -Whiteboard `Component` becomes: +Whiteboard `Component` composer branch: ```tsx @@ -446,28 +489,26 @@ Whiteboard `Component` becomes: ``` -Tanstack client: same mechanical transform for its composer-gated buttons. Scaffold templates (`composer-action`, `full`) rewritten to author through `ComposerActions.Root/Button/DropdownItem`; composer slot catalog description updated to name the primitives; `catalog.test.ts` assertions updated to match verbatim template text. SKILL.md and `widget-ui.mdx` sections showing raw buttons rewritten around the same example. +Tanstack client: same transform. Templates/docs rewritten around the same example (scaffold templates must compile under the scaffold test's assertions — update `catalog.test.ts` expectations to the new verbatim template strings). -- [ ] **Step 1: Update `catalog.test.ts` expectations first (failing), run** `pnpm vitest run test/catalog.test.ts` (cwd `packages/extension`) — FAIL. +- [ ] **Step 1: Update `catalog.test.ts` expectations (failing)** — `pnpm vitest run test/catalog.test.ts` (cwd `packages/extension`) — FAIL. - [ ] **Step 2: Apply all migrations.** -- [ ] **Step 3: Gates** — `pnpm turbo run test --filter=@conciv/extension`, `pnpm turbo run test --filter=@conciv/extension-tanstack`, and for whiteboard typecheck/build/lint ONLY (suite is CI-only): `pnpm turbo run typecheck --filter=@conciv/extension-whiteboard && pnpm turbo run build --filter=@conciv/extension-whiteboard`. (Use the actual package names from each `package.json`.) -- [ ] **Step 4: Commit** (`feat(extensions): author composer buttons through ComposerActions`, pathspec the touched packages + site docs). +- [ ] **Step 3: Gates** — `pnpm turbo run test --filter=@conciv/extension`; tanstack package gate (its real name from `package.json`); whiteboard: `pnpm turbo run typecheck --filter= && pnpm turbo run build --filter= && pnpm turbo run lint --filter=` (suite is CI-only — lint IS part of the local gate). +- [ ] **Step 4: Commit** (`feat(extensions): author composer buttons through ComposerActions`, pathspec touched packages + site docs). --- ### Task 6: Extension-testkit host support + fixture **Files:** -- Modify: `packages/extension-testkit/src/host/host-runtime.tsx` (wrap the composer-slot mount in `ComposerActionsHost` inside a width-controllable container) -- Test: the testkit's existing e2e app gains a fixture extension using Button + two DropdownItems (`packages/extension-testkit/e2e` — follow the existing fixture registration pattern there) +- Modify: `packages/extension-testkit/src/host/host-runtime.tsx` (wrap the composer-slot mount in `ComposerActionsHost` inside a width-controllable container with an accessible width control), `packages/extension-testkit/fixtures/ping/client.tsx` (fixture gains a `ComposerActions` root: Button + two DropdownItems) +- Test: new `packages/extension-testkit/test/composer-actions.it.test.ts` following the existing `test/*.it.test.ts` + `fixtureHost` pattern (NOT `e2e/` — that directory holds websocket/RPC probes) -**Interfaces:** -- Consumes: `ComposerActionsHost` from `@conciv/extension/host`. -- Produces: testkit hosts render extension `ComposerActions` exactly like the real app (coordinator + shared menu present). +**Interfaces:** testkit hosts render extension `ComposerActions` with a real coordinator + shared menu, width driven through a labeled control on the host page (a range/number input the test sets via `userEvent` — no DOM measurement). -- [ ] **Step 1: Add a failing e2e asserting the fixture's button renders inline in a wide host and its items reach the shared overflow menu in a narrow host** (drive width through the testkit host page's own controls, same locator discipline as Task 3). -- [ ] **Step 2: Wrap the testkit composer mount in `ComposerActionsHost` (trailing can be an empty fragment).** -- [ ] **Step 3: Run the testkit suite** — `pnpm turbo run test --filter=@conciv/extension-testkit` — PASS. +- [ ] **Step 1: Failing test** — wide host: fixture button visible inline; narrow host (set via the width control): button gone, `More composer actions` opens, both fixture items present and fire (assert via the fixture's observable effect, same pattern the ping fixture already uses). +- [ ] **Step 2: Implement host wrap + width control + fixture root.** +- [ ] **Step 3: Run** — `pnpm turbo run test --filter=@conciv/extension-testkit` — PASS. - [ ] **Step 4: Commit** (`feat(extension-testkit): host composer actions coordinator`, pathspec `packages/extension-testkit`). --- @@ -475,35 +516,30 @@ Tanstack client: same mechanical transform for its composer-gated buttons. Scaff ### Task 7: Extract refresh from the composer **Files:** -- Modify: `packages/ui-kit-chat/src/primitives/composer/composer.tsx` (delete the `Refresh` action button + its export), `packages/ui-kit-chat/src/primitives/composer/composer-handlers.tsx` (delete `onRefresh`), `packages/ui-kit-chat/test/composer-completion.browser.test.tsx` (delete refresh-specific tests) -- Modify: `apps/conciv/src/app/pane-context.ts` + `apps/conciv/src/app/pane-provider.tsx` + `apps/conciv/src/routes/panel.$sessionId.tsx` (add refresh handle to `PaneContextValue`), `apps/conciv/src/pane/chat-pane.tsx` (register the handle, drop `onRefresh`), `apps/conciv/src/pane/pane-composer.tsx` (drop the refresh button) +- Modify (delete): `packages/ui-kit-chat/src/primitives/composer/composer.tsx` (`Refresh` action button + export), `packages/ui-kit-chat/src/primitives/composer/composer-handlers.tsx` (`onRefresh`), refresh-specific tests in `packages/ui-kit-chat/test/composer-completion.browser.test.tsx` (deleted, not rewired) +- Modify: `apps/conciv/src/app/pane-context.ts`, `apps/conciv/src/app/pane-provider.tsx`, `apps/conciv/src/routes/panel.$sessionId.tsx` (context value + header button), `apps/conciv/src/pane/chat-pane.tsx` (register handle, drop `onRefresh`), `apps/conciv/src/pane/pane-composer.tsx` (delete `TrailingControls`, trailing keeps only `ComposerSendControl`), `apps/conciv/src/routes/quick.tsx` (LIFT `PaneProvider` to wrap the whole `data-pw-qt-pane` div — the session bar currently sits outside it and `usePane()` would throw; button goes in that bar), `apps/conciv/src/routes/pip.$sessionId.tsx` (slim `flex justify-end px-2 pt-1` row above `ChatPane`) +- Modify: `apps/conciv/test/helpers/pane-harness.tsx` (THIRD `PaneContextValue` construction site — gains the signal pair; harness view renders `` alongside `ChatPane` so the suite has a target) - Create: `apps/conciv/src/shell/refresh-button.tsx` -- Modify: `apps/conciv/src/routes/panel.$sessionId.tsx` (header right cluster), `apps/conciv/src/routes/quick.tsx` (per-pane bar next to the pane's `SessionSelector`), `apps/conciv/src/routes/pip.$sessionId.tsx` (slim chrome row above `ChatPane`) -- Test: `apps/conciv/test/chat-pane.browser.test.tsx` (rewire the two refresh tests to the header button) +- Test: `apps/conciv/test/chat-pane.browser.test.tsx` (two refresh tests rewired against the harness-mounted `RefreshButton`), plus presence tests for the quick per-pane bar and pip chrome in those routes' existing suites (create `apps/conciv/test/quick-refresh.browser.test.tsx` / extend the pip suite if none exists — assert role button `'Refresh the conversation'` renders and is disabled while streaming, using each route's existing test scaffolding) **Interfaces:** -- Produces: `PaneContextValue` gains `refresh: Accessor` and `registerRefresh: (handle: RefreshHandle | null) => void` where `type RefreshHandle = {run: () => void; busy: () => boolean}`. `RefreshButton(props: {class?: string})` renders nothing while the handle is null. - -`pane-context.ts` additions and both `PaneContextValue` construction sites (`pane-provider.tsx`, `panel.$sessionId.tsx`): +- `type RefreshHandle = {run: () => void; busy: () => boolean}` in `pane-context.ts`. +- `PaneContextValue` gains `refresh: Accessor` and `registerRefresh: (handle: RefreshHandle | null) => void`. ALL THREE construction sites updated (pane-provider.tsx, panel.$sessionId.tsx, pane-harness.tsx), each via: ```tsx const [refreshHandle, setRefreshHandle] = createSignal(null) ``` -spread into the value as `refresh: refreshHandle, registerRefresh: setRefreshHandle`. - -`chat-pane.tsx`: replace the `onRefresh` handler entry with registration: +- `chat-pane.tsx` registers in the component body: ```tsx -onMount(() => { - pane.registerRefresh({run: () => chat.refresh(), busy: () => chatBusy(chat)}) - onCleanup(() => pane.registerRefresh(null)) -}) +pane.registerRefresh({run: () => chat.refresh(), busy: () => chatBusy(chat)}) +onCleanup(() => pane.registerRefresh(null)) ``` -(`chatBusy` is exported by `@conciv/ui-kit-chat` — verify the export; if module-private, expose it or derive busy from the same chat state the deleted primitive used.) +(`chatBusy` is exported from `@conciv/ui-kit-chat` — `src/index.tsx:49`.) -`refresh-button.tsx`: +- `refresh-button.tsx`: ```tsx import {Show, type JSX} from 'solid-js' @@ -530,17 +566,17 @@ export function RefreshButton(props: {class?: string}): JSX.Element { } ``` -Placements: panel header — before the close button (`panel.$sessionId.tsx` right cluster, reuse `CLOSE` class); quick — inside each pane's session bar (the `SessionSelector` row); pip — a `flex justify-end px-2 pt-1` row above `ChatPane`. +Placements: panel header right cluster before the close button (`CLOSE` class); quick per-pane session bar (inside the lifted provider); pip chrome row. -- [ ] **Step 1: Rewrite the two refresh tests in `chat-pane.browser.test.tsx` against the header/pane-bar button (locator unchanged: role button name `'Refresh the conversation'`), run — FAIL.** -- [ ] **Step 2: Delete `Refresh` from ui-kit-chat composer + `onRefresh` from handlers + their ui-kit tests; implement PaneContext handle, `RefreshButton`, three placements.** -- [ ] **Step 3: Run** `pnpm turbo run test --filter=@conciv/ui-kit-chat` and `pnpm vitest run test/chat-pane.browser.test.tsx test/composer-overflow.browser.test.tsx` (cwd `apps/conciv`) — PASS. -- [ ] **Step 4: Fallow check for the deleted export** — `pnpm exec fallow dead-code --trace 'packages/ui-kit-chat/src/primitives/composer/composer.tsx:Refresh'` should report no remaining consumers before deletion lands. +- [ ] **Step 1: Fallow trace BEFORE deleting** — `pnpm exec fallow dead-code --trace 'packages/ui-kit-chat/src/primitives/composer/composer.tsx:Refresh'` — confirm consumers are exactly `PaneComposer` + the ui-kit tests slated for deletion. +- [ ] **Step 2: Rewire the two refresh tests in `chat-pane.browser.test.tsx` to the harness-mounted `RefreshButton` (same role/name locator; disabled-while-streaming asserted with `toBeDisabled()`), add the quick/pip presence tests — run, FAIL.** +- [ ] **Step 3: Implement — deletions, context handle, `RefreshButton`, three placements, quick provider lift, harness update.** +- [ ] **Step 4: Run** — `pnpm turbo run test --filter=@conciv/ui-kit-chat`, then `pnpm vitest run test/chat-pane.browser.test.tsx test/composer-overflow.browser.test.tsx test/quick-refresh.browser.test.tsx` (cwd `apps/conciv`), then the app package gate — PASS. - [ ] **Step 5: Commit** (`feat(conciv): session refresh moves to pane chrome, out of the composer`, pathspec `packages/ui-kit-chat apps/conciv`). --- -### Task 8: Full gates, changeset, embed rebuild +### Task 8: Full gates + changeset **Files:** - Create: `.changeset/composer-actions-collapse.md` @@ -552,17 +588,19 @@ Placements: panel header — before the close button (`panel.$sessionId.tsx` rig '@conciv/extension': patch --- -Composer actions collapse into a shared overflow menu; extensions author buttons through ComposerActions.Root/Button/DropdownItem. Session refresh moved out of the composer into pane chrome. +Composer actions collapse into a shared overflow menu; extensions author buttons through ComposerActions.Root/Button/DropdownItem/Inline. Session refresh moved out of the composer into pane chrome. ``` -- [ ] **Step 2: Verify changeset coverage** — `pnpm exec conciv-publish check-changesets --require-coverage --base origin/main`. -- [ ] **Step 3: Embed rebuild + full gates** — `pnpm turbo run build --filter=@conciv/embed`, then `pnpm typecheck && pnpm test:affected`, then `pnpm exec fallow audit --changed-since main --format json` — fix anything INTRODUCED. +- [ ] **Step 2: Coverage check** — `pnpm exec conciv-publish check-changesets --require-coverage --base origin/main`. +- [ ] **Step 3: Final gates** — `pnpm turbo run build --filter=@conciv/embed`, `pnpm typecheck && pnpm test:affected`, `pnpm exec fallow audit --changed-since main --format json` — fix anything INTRODUCED. - [ ] **Step 4: Commit** (`chore: changeset for composer actions collapse`, pathspec `.changeset`). --- ## Self-Review Notes -- Spec §1 primitives → Tasks 1-2 (+`Inline` added in Task 4 per the spec's open item). §2 coordinator → Task 2-3. §3 built-ins + migration surfaces → Tasks 3-5. §4 refresh → Task 7. Testing section → Tasks 3, 4, 6, 7. Changeset/gates → Task 8. -- Deviation from spec, intentional: `RefreshButton` reads the handle from `PaneContext` on every surface (instead of `useChatContext` + a panel-only relay) because in quick mode and the panel the chrome sits above `ChatProvider`; one mechanism, three placements. -- Type names consistent across tasks: `FitInput`, `Registration`, `RefreshHandle`, `ComposerActionsHost`, `ComposerActions.{Root,Button,DropdownItem,Inline}`. +- Spec §1 → Tasks 1-2 (`Inline` lands in Task 2, used from Task 3 so launch is fit-counted from the first integration commit). §2 → Task 2-3. §3 → Tasks 3-5. §4 → Task 7. Testing → Tasks 3, 4, 6, 7. Gates → Task 8 (embed/mount-externals guard pulled forward into Task 2). +- Spec deviations, both intentional and recorded: (a) `RefreshButton` reads `PaneContext` on every surface instead of chat-context + panel-only relay — quick's bar and the panel header both sit above `ChatProvider`; quick's `PaneProvider` is lifted to make that true per-pane. (b) Menu ordering implemented as per-root group nodes in host-rendered DOM order, not portal order + CSS — zag walks DOM order, CSS `order` would desync keyboard from visuals. +- Root-level `disabled: () => boolean` is the ONLY disabled mechanism (spec requirement restored); `Button.busy` is styling-only. +- Type names consistent: `FitInput`, `Registration`, `Coordinator`, `RootState`, `RefreshHandle`, `ComposerActionsHost`, `ComposerActions.{Root,Button,DropdownItem,Inline}`. +- Entry file is `packages/extension/src/index.ts` (no `.tsx` rename needed — the file only re-exports). From 05c76f3d03830df7a82e599e24b32c3789a1b975 Mon Sep 17 00:00:00 2001 From: Omri Katz <9701896+omridevk@users.noreply.github.com> Date: Sun, 16 Aug 2026 15:56:05 +0300 Subject: [PATCH 05/24] docs: composer actions live in ui-kit-chat; extension package untouched by UI; storybook task added Co-Authored-By: Claude Fable 5 --- .../2026-08-16-composer-actions-collapse.md | 298 ++++++++---------- 1 file changed, 132 insertions(+), 166 deletions(-) diff --git a/docs/superpowers/plans/2026-08-16-composer-actions-collapse.md b/docs/superpowers/plans/2026-08-16-composer-actions-collapse.md index 3845cd0d40..2b0268d5f4 100644 --- a/docs/superpowers/plans/2026-08-16-composer-actions-collapse.md +++ b/docs/superpowers/plans/2026-08-16-composer-actions-collapse.md @@ -4,26 +4,30 @@ **Goal:** Replace the saturated composer button row with compound `ComposerActions.*` primitives whose host coordinator collapses lower-priority actions into one shared overflow menu by measured width, and extract the session refresh affordance out of the composer into per-surface chrome. -**Architecture:** New `ComposerActions` compound components (Root/Button/DropdownItem/Inline) live in `@conciv/extension`. A host-side `ComposerActionsHost` (provider + shared Ark `Menu.Root`) wraps the composer toolbar row as a logical Solid ancestor of both built-in actions and `ExtensionSurface name="composer"`. Overflow-menu ordering is real DOM order: the host renders one group node per registered root sorted by priority, and each `DropdownItem` portals into its own root's group node (never CSS `order`). Fit is pure arithmetic over a constant slot width and passive resize observers. Refresh becomes a `RefreshButton` reading a refresh handle that `ChatPane` registers into `PaneContext`. +**Architecture:** New `ComposerActions` compound components (Root/Button/DropdownItem/Inline) live in `@conciv/ui-kit-chat` under `src/primitives/composer/` — the package that already owns the composer primitives. EVERY consumer (apps/conciv, extension clients, testkit, scaffold templates, docs) imports them from `@conciv/ui-kit-chat`, the same way extensions import `TooltipIconButton` from `@conciv/ui-kit-system` today. `@conciv/extension` is NOT touched by UI work — it stays a lean contract package (its only edits in this plan are scaffold-template STRINGS in Task 5). A host-side `ComposerActionsHost` (provider + shared Ark `Menu.Root`) wraps the composer toolbar row as a logical Solid ancestor of both built-in actions and `ExtensionSurface name="composer"`. Overflow-menu ordering is real DOM order: the host renders one group node per registered root sorted by priority, and each `DropdownItem` portals into its own root's group node (never CSS `order`). Fit is pure arithmetic over a constant slot width and passive resize observers. Refresh becomes a `RefreshButton` reading a refresh handle that `ChatPane` registers into `PaneContext`. -**Tech Stack:** SolidJS, Ark UI Menu (zag), UnoCSS utility classes, vitest browser (Playwright/Chromium), oxlint/oxfmt. +**Tech Stack:** SolidJS, Ark UI Menu (zag), UnoCSS utility classes, vitest browser (Playwright/Chromium), storybook (consolidated `apps/storybook`), oxlint/oxfmt. -**Spec:** `docs/superpowers/specs/2026-08-16-composer-actions-collapse-design.md` +**Spec:** `docs/superpowers/specs/2026-08-16-composer-actions-collapse-design.md` (placement decision supersedes the spec's `@conciv/extension` export-surface line — recorded deviation, user-directed) -**Review inputs folded in:** codex plan review (`/tmp/codex-plan-review.md`) + frontend review — all HIGH/CRITICAL findings addressed inline below. +**Review inputs folded in:** codex plan review + Fable frontend review — all HIGH/CRITICAL findings addressed inline below. ## Global Constraints - Functions only, no classes, no IIFEs, ZERO code comments (lint deletes them) — including in test code. - Strict TS: no `any`, no `as` casts, no non-null assertions, `noUncheckedIndexedAccess`. - oxfmt: no semicolons, single quotes, no bracket spacing, trailing commas, printWidth 120. -- Solid: `splitProps` (never destructure props), `@solid-primitives` over raw observer glue, no hooks inside JSX attributes, register context state synchronously in component bodies (NOT `onMount`) with `onCleanup` — `Suspense`/lazy boundaries make mount-order assumptions fragile. -- Widget UI tests: REAL Chromium (vitest browser), never jsdom. Web-first assertions only; no `poll`, no `querySelector`, no rect measurement, no sleeps, no test-ids. Locate by role/name. Assert `aria-disabled`/`toBeDisabled()`, never zag styling hooks like `data-disabled`. +- Solid: `splitProps` (never destructure props), `@solid-primitives` over raw observer glue, no hooks inside JSX attributes, register context state synchronously in component bodies (NOT `onMount`) with `onCleanup`. +- NO hand-rolled components: every interactive element composes ui-kit primitives (`TooltipIconButton`/`TooltipIconButtonSlot`, `Menu.*` from `@conciv/ui-kit-system`). Raw elements allowed only for layout scaffolding (measurement wrappers, group nodes, invisible placeholder span). +- `ComposerActions` imports come from `@conciv/ui-kit-chat` EVERYWHERE. Adoption check at the end of every task that adds a consumer: `grep -rn "ComposerActions" --include="*.tsx" --include="*.ts" apps packages | grep "from '@conciv/extension'"` must return nothing. +- Widget UI tests: REAL Chromium (vitest browser), never jsdom. Web-first assertions only; no `poll`, no `querySelector`, no rect measurement, no sleeps, no test-ids. Locate by role/name. Assert `aria-disabled`/`toBeDisabled()`, never zag styling hooks. - Whiteboard package suite NEVER runs locally: whiteboard gates are typecheck + build + lint only. - Package test gates finish with `pnpm turbo run test --filter=` (bare filter, NEVER trailing `...`); focused `pnpm vitest run` is for red/green iteration only. -- New UnoCSS classes need scanner coverage AND an embed rebuild (`pnpm turbo run build --filter=@conciv/embed`). +- ui-kit-chat vitest projects: node project runs `test/**/*.test.ts`, browser project runs `test/**/*.browser.test.tsx` — name new files accordingly. +- New UnoCSS classes: `packages/ui-kit-chat/src` is already scanned by the embed uno config — no config change needed; embed rebuild (`pnpm turbo run build --filter=@conciv/embed`) still required before widget ITs. - Commit with pathspec; run `pnpm exec fallow audit --format json --quiet --explain --gate-marker agent` before each commit (JSON runtime errors non-blocking). `fallow dead-code --trace` runs BEFORE deleting an export, not after. -- **Dependency gate:** Task 2 adds `@solid-primitives/resize-observer` to `@conciv/extension` (already used by ui-kit-chat). This dependency addition has been approved by the user for this plan; add exactly this package, nothing else, no version pinning beyond the workspace convention. +- No new dependencies: `@solid-primitives/resize-observer` is ALREADY a ui-kit-chat dependency. +- All UI copy sentence-case (`'More composer actions'`). ## Layout constants (used across tasks) @@ -42,17 +46,24 @@ The overflow trigger permanently occupies one slot (visibility-hidden placeholde ### Task 1: Fit arithmetic (pure function) **Files:** -- Create: `packages/extension/src/composer-actions-fit.ts` -- Test: `packages/extension/test/composer-actions-fit.test.ts` +- Create: `packages/ui-kit-chat/src/primitives/composer/composer-actions-fit.ts` +- Test: `packages/ui-kit-chat/test/composer-actions-fit.test.ts` (node project) **Interfaces:** - Produces: `computeVisibleAutoCount(input: FitInput): number`, `type FitInput`, constants `ACTION_SLOT_PX`, `REGION_GAP_PX`, `FIT_HYSTERESIS_PX`. Task 2 consumes all of these. +The implementation and test bodies were already written and verified green on this branch's earlier revision (commit `7b550c1b`, since reset out of `packages/extension`) — recreate them VERBATIM at the new paths, only the test's import path changes: + - [ ] **Step 1: Write the failing test** ```ts import {describe, expect, it} from 'vitest' -import {ACTION_SLOT_PX, FIT_HYSTERESIS_PX, REGION_GAP_PX, computeVisibleAutoCount} from '../src/composer-actions-fit.js' +import { + ACTION_SLOT_PX, + computeVisibleAutoCount, + FIT_HYSTERESIS_PX, + REGION_GAP_PX, +} from '../src/primitives/composer/composer-actions-fit.js' const base = { slotWidth: ACTION_SLOT_PX, @@ -66,7 +77,12 @@ const base = { } const used = (autoSlots: number): number => - base.leadingWidth + base.trailingWidth + 2 * REGION_GAP_PX + ACTION_SLOT_PX + base.pinnedCount * ACTION_SLOT_PX + autoSlots * ACTION_SLOT_PX + base.leadingWidth + + base.trailingWidth + + 2 * REGION_GAP_PX + + ACTION_SLOT_PX + + base.pinnedCount * ACTION_SLOT_PX + + autoSlots * ACTION_SLOT_PX describe('computeVisibleAutoCount', () => { it('shows every auto action when the budget covers them', () => { @@ -96,7 +112,7 @@ describe('computeVisibleAutoCount', () => { }) ``` -- [ ] **Step 2: Run to verify failure** — `pnpm vitest run test/composer-actions-fit.test.ts` (cwd `packages/extension`) — FAIL, module not found. +- [ ] **Step 2: Run to verify failure** — `pnpm vitest run test/composer-actions-fit.test.ts` (cwd `packages/ui-kit-chat`) — FAIL, module not found. - [ ] **Step 3: Implement** ```ts @@ -118,7 +134,11 @@ export type FitInput = { export function computeVisibleAutoCount(input: FitInput): number { const reserved = - input.leadingWidth + input.trailingWidth + 2 * input.regionGapPx + input.slotWidth + input.pinnedCount * input.slotWidth + input.leadingWidth + + input.trailingWidth + + 2 * input.regionGapPx + + input.slotWidth + + input.pinnedCount * input.slotWidth const budget = input.rowWidth - reserved const fits = Math.max(0, Math.min(input.autoCount, Math.floor(budget / input.slotWidth))) if (input.previousCount === null || fits <= input.previousCount) return fits @@ -127,26 +147,26 @@ export function computeVisibleAutoCount(input: FitInput): number { } ``` -- [ ] **Step 4: Green + package gate** — focused run passes, then `pnpm turbo run test --filter=@conciv/extension`. -- [ ] **Step 5: Commit** (`feat(extension): composer actions fit arithmetic`, pathspec `packages/extension`). +- [ ] **Step 4: Green + package gate** — focused run passes, then `pnpm turbo run test --filter=@conciv/ui-kit-chat`. +- [ ] **Step 5: Commit** (`feat(ui-kit-chat): composer actions fit arithmetic`, pathspec `packages/ui-kit-chat`). --- ### Task 2: `ComposerActions` primitives + host coordinator **Files:** -- Create: `packages/extension/src/composer-actions.tsx` -- Modify: `packages/extension/src/index.ts` (export `ComposerActions`), `packages/extension/src/host.ts` (export `ComposerActionsHost`), `packages/extension/package.json` (add `@solid-primitives/resize-observer` — approved, see Global Constraints), `packages/embed/uno.config.ts` + `apps/conciv/uno.config.ts` (add `../extension/src/**/*.{ts,tsx}` — relative to each config — to the scanned globs; without this the new utility classes never reach the built CSS) +- Create: `packages/ui-kit-chat/src/primitives/composer/composer-actions.tsx` +- Modify: `packages/ui-kit-chat/src/index.tsx` (export `ComposerActions` and `ComposerActionsHost` alongside the existing `ComposerPrimitive` exports) +- Test: `packages/ui-kit-chat/test/composer-actions.browser.test.tsx` (component-level, in-package browser project) **Interfaces:** -- Consumes: Task 1's `computeVisibleAutoCount` + constants; `Menu`, `TooltipIconButton`, `TooltipIconButtonSlot` from `@conciv/ui-kit-system` (first RUNTIME import of ui-kit-system in this package — manifest dep already present); `createResizeObserver` from `@solid-primitives/resize-observer`. -- Produces (extension-author surface, from `@conciv/extension`): - - `ComposerActions.Root(props: {id: string; priority?: number; disabled?: () => boolean; children: JSX.Element})` — `disabled` is THE single reactive source; both renderings consume it (spec requirement; per-child disabled props do not exist). - - `ComposerActions.Button(props: {visible?: 'auto' | 'always'; tooltip: string; onClick: () => void; busy?: boolean; class?: string; variant?: 'ghost' | 'solid'; children: JSX.Element})` — `busy` renders `aria-busy` + progress styling, it does NOT disable. +- Consumes: Task 1's `computeVisibleAutoCount` + constants; `Menu`, `TooltipIconButton`, `TooltipIconButtonSlot` from `@conciv/ui-kit-system`; `createResizeObserver` from `@solid-primitives/resize-observer` (existing dep). +- Produces (from `@conciv/ui-kit-chat`): + - `ComposerActions.Root(props: {id: string; priority?: number; disabled?: () => boolean; children: JSX.Element})` — `disabled` is THE single reactive source; both renderings consume it. No per-child disabled props. + - `ComposerActions.Button(props: {visible?: 'auto' | 'always'; tooltip: string; onClick: () => void; busy?: boolean; class?: string; variant?: 'ghost' | 'solid'; children: JSX.Element})` — `busy` renders `aria-busy` + progress styling, never disables. - `ComposerActions.DropdownItem(props: {value: string; label: string; onSelect: () => void; children?: JSX.Element})` - - `ComposerActions.Inline(props: {children: JSX.Element})` — renders children only while the root is inline; counts as the root's button for fit purposes (the `asChild` escape for controls that are themselves triggers). -- Produces (host surface, from `@conciv/extension/host`): - - `ComposerActionsHost(props: {leading?: JSX.Element; trailing: JSX.Element; triggerContent: JSX.Element; children: JSX.Element})` — no icon-library dependency in this package; the app passes the ellipsis icon via `triggerContent`. + - `ComposerActions.Inline(props: {children: JSX.Element})` — renders children only while the root is inline; counts as the root's button for fit purposes (escape hatch for controls that are themselves triggers, e.g. the launch menu). + - `ComposerActionsHost(props: {leading?: JSX.Element; trailing: JSX.Element; triggerContent: JSX.Element; onOverflowDismissed?: () => void; children: JSX.Element})`. **Implementation contract (settled types — write exactly these):** @@ -182,8 +202,8 @@ type RootState = { Coordinator rules (inside `ComposerActionsHost`): -- Store: `createStore([])`. `Root` registers **synchronously in its component body** (`createUniqueId()` key), `onCleanup` unregisters. `priority`/`disabled` changes tracked with a `createEffect` that calls `update` (Solid props are getters; no stale metadata). -- Duplicate `id`: the LAST registration with that id is the active one — `active(key)` returns false for earlier holders, whose Roots render nothing (inline and menu). Warn unconditionally with `console.warn` once per collision. +- Store: `createStore([])`. `Root` registers **synchronously in its component body** (`createUniqueId()` key), `onCleanup` unregisters. `priority`/`disabled` changes tracked with a `createEffect` calling `update` (Solid props are getters; no stale metadata). +- Duplicate `id`: LAST registration with that id is active — `active(key)` false for earlier holders, whose Roots render nothing anywhere. `console.warn` once per collision, unconditional. - Widths: `createResizeObserver` on three refs — outer row, leading wrapper, trailing wrapper. Wrappers carry `class="empty:hidden flex gap-1 items-center"` so an empty region costs nothing. - Count memo — hysteresis via the memo's OWN previous value, no extra signal: @@ -206,7 +226,7 @@ const visibleAutoCount = createMemo( ``` - `inline(key)`: pinned actives with a button always inline; auto actives with a button sorted priority desc then registration order, first `visibleAutoCount()` inline. -- **Menu ordering is DOM order, never CSS `order`:** inside `Menu.Content` the host renders `{(entry) =>
setGroupEl(entry.key, el)} />}` sorted priority desc then registration order. Each `DropdownItem` portals into ITS root's group node via `coordinator.groupMount(root.key)`. Visual order = DOM order = zag keyboard order; a root's items stay contiguous. `Menu.Content` keeps its default classes — no `flex` (its base is `hidden data-[state=open]:block`; adding `flex` creates a display conflict). +- **Menu ordering is DOM order, never CSS `order`:** inside `Menu.Content` the host renders `{(entry) =>
setGroupEl(entry.key, el)} />}` sorted priority desc then registration order. Each `DropdownItem` portals into ITS root's group node via `coordinator.groupMount(root.key)`. Visual order = DOM order = zag keyboard order; a root's items stay contiguous. `Menu.Content` keeps its default classes — no `flex` (its base is `hidden data-[state=open]:block`; adding `flex` creates a display conflict). - Trigger slot (always occupies one slot): ```tsx @@ -219,12 +239,12 @@ const visibleAutoCount = createMemo( ``` -`TRIGGER_CLASS` is defined locally in `composer-actions.tsx` on the `TooltipIconButton` ghost variant sizing (`'size-8.5'`) — `GHOST` from pane-composer is app-private and must not be referenced. +`TRIGGER_CLASS` is a local constant on the `TooltipIconButton` ghost variant sizing (`'size-8.5'`); `triggerContent` keeps icon choice with the app (no lucide import here — this package's public API stays icon-agnostic like the rest of its primitives). - `anyCollapsed()` = any active root with `itemCount > 0` not inline. -- **Menu-open collapse race:** control the menu (`Menu.Root open={menuOpen()} onOpenChange={...}` or `Menu.Context` api). A `createEffect` watching `anyCollapsed()`: on transition to false while open, close the menu and move focus to the trigger's nearest surviving focusable — the first inline action button if one exists, else the composer input (host prop `onOverflowDismissed?: () => void` lets the app focus the input). Without this, expanding while the menu is open strands focus on ``. +- **Menu-open collapse race:** control the menu (`Menu.Root open={menuOpen()} onOpenChange={...}`). A `createEffect` watching `anyCollapsed()`: on transition to false while open, close the menu and call `props.onOverflowDismissed` (app focuses the composer input); default focus target is the first inline action button. - `Button`: sets `hasButton` + pinned via `root.update` synchronously, `onCleanup` resets `hasButton: false`. Renders `` → `TooltipIconButton` with `class`/`variant` passthrough, `aria-busy={props.busy}`, `disabled={root.disabled()}`. -- `Inline`: same registration behavior as `Button` (`hasButton: true`, never pinned unless later needed), renders children when `root.inline()`. +- `Inline`: same registration as `Button` (never pinned), renders children when `root.inline()`. - `DropdownItem`: `root.update` increments `itemCount` synchronously, `onCleanup` decrements. Renders ```tsx @@ -243,10 +263,41 @@ const visibleAutoCount = createMemo( - Root outside a coordinator: renders nothing. - Row JSX: `Menu.Root` wraps `div class="pt-0.5 flex gap-1 items-center"` containing leading wrapper, `{props.children}`, trigger slot, trailing wrapper (`ml-auto` + `empty:hidden`), then `Menu.Positioner > Menu.Content` with the group `For`. -- [ ] **Step 1: Add the dependency** — `@solid-primitives/resize-observer` to `packages/extension/package.json` (match the version ui-kit-chat uses), `pnpm install`. -- [ ] **Step 2: Write `composer-actions.tsx` per the contract; export `ComposerActions` from `index.ts`, `ComposerActionsHost` from `host.ts`; extend both uno configs.** -- [ ] **Step 3: Gates** — `pnpm turbo run build --filter=@conciv/extension && pnpm turbo run typecheck --filter=@conciv/extension && pnpm turbo run test --filter=@conciv/extension`, then the bundling guard NOW (not Task 8): `pnpm turbo run build --filter=@conciv/embed` and `pnpm turbo run test --filter=@conciv/embed` (mount-externals test must stay green — the extension contract now carries runtime Ark/tooltip imports). -- [ ] **Step 4: Commit** (`feat(extension): ComposerActions compound primitives with overflow coordinator`, pathspec `packages/extension packages/embed apps/conciv/uno.config.ts pnpm-lock.yaml`). +**Component-level browser tests** (`composer-actions.browser.test.tsx`, in-package — mount `ComposerActionsHost` directly with synthetic roots in a width-controlled container, following the package's existing browser-test mounting pattern): + +- wide: all buttons inline, no trigger; narrow: low-priority roots collapse, trigger appears with `aria-haspopup`/`aria-expanded`, items fire `onSelect` and the menu closes. +- pinned root stays inline at any width; button-only root hidden when collapsed; item-only root menu-only; multi-item root's items contiguous in priority order. +- Root `disabled` accessor disables inline button AND menu item (`aria-disabled`), item not invocable. +- duplicate id: only last root renders. +- widening while menu open closes it without stranding focus (assert menu hidden + `onOverflowDismissed` observable effect). +- keyboard: Enter opens, ArrowDown highlights, Escape closes and returns focus to trigger. + +- [ ] **Step 1: Write the failing browser tests.** +- [ ] **Step 2: Run to verify failure** — `pnpm vitest run test/composer-actions.browser.test.tsx` (cwd `packages/ui-kit-chat`). +- [ ] **Step 3: Implement `composer-actions.tsx` per the contract; export from `index.tsx`.** +- [ ] **Step 4: Gates** — focused browser suite green, then `pnpm turbo run typecheck --filter=@conciv/ui-kit-chat && pnpm turbo run build --filter=@conciv/ui-kit-chat && pnpm turbo run test --filter=@conciv/ui-kit-chat`, then the bundling guard: `pnpm turbo run build --filter=@conciv/embed && pnpm turbo run test --filter=@conciv/embed` (mount-externals stays green). +- [ ] **Step 5: Commit** (`feat(ui-kit-chat): ComposerActions compound primitives with overflow coordinator`, pathspec `packages/ui-kit-chat`). + +--- + +### Task 2b: Storybook coverage + +**Files:** +- Create: `packages/ui-kit-chat/src/primitives/composer/composer-actions.stories.tsx` (`apps/storybook` already globs `packages/ui-kit-chat/src/**/*.stories.*` — zero config) + +**Stories (rich, following `packages/ui-kit-system/src/menu.stories.tsx` conventions):** +- `AllInline` — wide fixed-width host, five mixed roots. +- `Collapsed` — narrow host, pinned + overflow trigger visible. +- `PinnedOnly` — `visible="always"` alongside collapsing autos. +- `MenuOnlyRoot` — item-only root. +- `MultiItemRoot` — launch-style root with conditional item set. +- `DisabledRoot` — disabled accessor live-toggled via story control. +- `ResizablePlayground` — host inside a CSS `resize: horizontal` container for manual dragging. +- Play functions (storybook vitest) on `Collapsed`, `DisabledRoot`, `MultiItemRoot`: open menu, assert menuitems by role/name, assert `aria-disabled`, select fires. + +- [ ] **Step 1: Write stories + play functions.** +- [ ] **Step 2: Gate** — the storybook test gate for this package's stories (`pnpm turbo run test --filter=conciv-storybook` — confirm the app's real package name from `apps/storybook/package.json`). +- [ ] **Step 3: Commit** (`feat(ui-kit-chat): ComposerActions stories`, pathspec `packages/ui-kit-chat apps/storybook`). --- @@ -255,17 +306,18 @@ const visibleAutoCount = createMemo( **Files:** - Modify: `apps/conciv/src/pane/pane-composer.tsx`, `apps/conciv/src/composer/actions.tsx`, `apps/conciv/src/pane/chat-pane.tsx` - Modify: `apps/conciv/test/helpers/pane-harness.tsx` (width control) -- Test: `apps/conciv/test/composer-overflow.browser.test.tsx` (new) +- Test: `apps/conciv/test/composer-overflow.browser.test.tsx` (new — app-level wiring: built-ins + extension surface through the real pane) **Interfaces:** -- Consumes: `ComposerActionsHost` from `@conciv/extension/host`, `ComposerActions` from `@conciv/extension`. -- Produces: toolbar row contract — leading = attachment button; managed = built-ins + `ExtensionSurface name="composer"`; trailing = `trailingExtras` (model selector, in its own `Suspense`) + refresh + send/cancel; trigger named `'More composer actions'`. Harness API: `mountPane(options & {width?: number})` returning `{setWidth(px: number): void}` alongside its existing returns (drives a reactive style width on the harness wrapper — the `w-100` hardcode becomes the 400px default). +- Consumes: `ComposerActionsHost`, `ComposerActions` from `@conciv/ui-kit-chat` (import alias `ComposerActions as Action` in `actions.tsx` — the app component of the same name keeps its export). +- Produces: toolbar row contract — leading = attachment button; managed = built-ins + `ExtensionSurface name="composer"`; trailing = `trailingExtras` (model selector, own `Suspense` with slot-sized fallback) + refresh + send/cancel; trigger named `'More composer actions'`. Harness API: `mountPane(options & {width?: number})` returning `setWidth(px: number)` (reactive style width; `w-100` hardcode becomes the 400px default). -**pane-composer.tsx** — replace the row div; REFRESH STAYS HERE UNTIL TASK 7 (do not delete it in this task): +**pane-composer.tsx** — REFRESH STAYS UNTIL TASK 7 (`TrailingControls` unchanged in this task): ```tsx ``` -`TrailingControls` (refresh + send) is UNCHANGED in this task. `PaneComposerProps` gains `trailingExtras?: JSX.Element`; `chat-pane.tsx` moves `` out of children into `trailingExtras`. The slot-sized Suspense fallback keeps the trailing observer from jumping while models load. +(`focusComposerInput` = whatever handle the composer input adapter already exposes — reuse `onInputReady`'s handle, don't invent focus plumbing.) `PaneComposerProps` gains `trailingExtras?: JSX.Element`; `chat-pane.tsx` moves `` into it. -**actions.tsx** — the app component keeps its exported name; the primitives are imported under a non-colliding alias: - -```tsx -import {ComposerActions as Action} from '@conciv/extension' -``` - -(`ComposerActions` the app component at line 39 stays exported — chat-pane imports it by that name.) +**actions.tsx** — built-ins on the primitives (grab pinned, launch coordinator-registered via `Inline` from day one so the fit budget counts it): ```tsx @@ -333,96 +379,33 @@ import {ComposerActions as Action} from '@conciv/extension' ``` -Grab keeps its ACT/busyClass styling contract and is NOT disabled while picking (`busy` only) — behavior preserved. Launch is coordinator-registered from day one via `Inline` so the fit budget counts it (its dropdown flattening lands in Task 4). - -**pane-harness.tsx**: `w-100` becomes `style={{width: \`${width()}px\`}}` with `width` a signal defaulting to 400; `mountPane` accepts `width?` and returns `setWidth`. Before writing tests, verify with the fit constants that at 400px every built-in stays inline (leading 34 + 2 gaps + trigger 38 + grab 38 + 3 autos 114 + trailing ≈ 110 ≈ 342 < 400) so the neighbor suites (launch-menu, launch-actions, model-selector, chat-pane) keep their inline-button locators working; if the real trailing cluster measures wider, raise the harness default so they do, and say so in the commit. - -- [ ] **Step 1: Write the failing browser tests** (`composer-overflow.browser.test.tsx`, using the harness + kit helpers exactly as `chat-pane.browser.test.tsx` does): - -```tsx -test('wide panel keeps every action inline with no overflow trigger', async () => { - await mountPane({width: 720}) - await expect.element(page.getByRole('button', {name: 'Start a new session'})).toBeVisible() - await expect.element(page.getByRole('button', {name: 'Compress the conversation'})).toBeVisible() - await expect.element(page.getByRole('button', {name: 'More composer actions'})).not.toBeInTheDocument() -}) +Grab keeps ACT/busyClass styling and is NOT disabled while picking (`busy` only). -test('narrow panel collapses auto actions and keeps the pinned grab inline', async () => { - await mountPane({width: 320}) - await expect.element(page.getByRole('button', {name: 'Select an element from the page'})).toBeVisible() - await expect.element(page.getByRole('button', {name: 'Start a new session'})).not.toBeInTheDocument() - const trigger = page.getByRole('button', {name: 'More composer actions'}) - await expect.element(trigger).toHaveAttribute('aria-haspopup', 'menu') - await trigger.click() - await expect.element(trigger).toHaveAttribute('aria-expanded', 'true') - await expect.element(page.getByRole('menuitem', {name: 'Start a new session'})).toBeVisible() -}) +**pane-harness.tsx**: `w-100` → `style={{width: \`${width()}px\`}}`, signal default 400; `mountPane` accepts `width?`, returns `setWidth`. Verify with the fit constants that 400px keeps every built-in inline (≈342px used) so neighbor suites keep their inline locators; raise the default if the real trailing cluster measures wider, and say so in the commit. -test('an overflow item fires its action and the menu closes', async () => { - const pane = await mountPane({width: 320}) - await page.getByRole('button', {name: 'More composer actions'}).click() - await page.getByRole('menuitem', {name: 'Start a new session'}).click() - await expect.element(page.getByRole('menu')).not.toBeVisible() - await pane.expectNewSessionRequested() -}) +**App-level tests** (`composer-overflow.browser.test.tsx`) — wiring-focused (primitives' own behavior is covered in-package by Task 2): -test('keyboard lifecycle on the trigger', async () => { - await mountPane({width: 320}) - const trigger = page.getByRole('button', {name: 'More composer actions'}) - await trigger.element().focus() - await userEvent.keyboard('{Enter}') - await expect.element(page.getByRole('menu')).toBeVisible() - await userEvent.keyboard('{ArrowDown}') - await userEvent.keyboard('{Escape}') - await expect.element(page.getByRole('menu')).not.toBeVisible() - await expect.element(trigger).toHaveFocus() -}) - -test('a disabled root cannot be invoked from the menu', async () => { - const pane = await mountPane({width: 320, compacting: true}) - await page.getByRole('button', {name: 'More composer actions'}).click() - const item = page.getByRole('menuitem', {name: 'Compress the conversation'}) - await expect.element(item).toHaveAttribute('aria-disabled', 'true') - await item.click({force: true}) - await pane.expectNoCompactRequested() -}) - -test('expanding while the menu is open closes it without stranding focus', async () => { - const pane = await mountPane({width: 320}) - await page.getByRole('button', {name: 'More composer actions'}).click() - await pane.setWidth(720) - await expect.element(page.getByRole('menu')).not.toBeVisible() - await expect.element(page.getByRole('button', {name: 'Start a new session'})).toBeVisible() -}) - -test('repeated resize across the threshold settles without flapping', async () => { - const pane = await mountPane({width: 720}) - for (const width of [320, 720, 320, 720, 320]) pane.setWidth(width) - await expect.element(page.getByRole('button', {name: 'More composer actions'})).toBeVisible() - pane.setWidth(720) - await expect.element(page.getByRole('button', {name: 'Start a new session'})).toBeVisible() -}) -``` - -`expectNewSessionRequested` / `expectNoCompactRequested` / `compacting` are harness options wired to the same fixture callbacks the existing suite passes to `ChatPane`/`PaneProvider` — extend the harness options, not app state. +- wide: all built-ins inline, no trigger. +- narrow: grab pinned inline, new-session/compact collapsed into the menu, menu item fires the real action (assert via harness fixture callbacks: `expectNewSessionRequested`). +- disabled compacting root not invocable from menu (`aria-disabled`, `expectNoCompactRequested`). +- resize back and forth settles; expanding with menu open closes it. +- (keyboard lifecycle already covered in-package; don't duplicate here.) +- [ ] **Step 1: Write failing tests** (harness options `compacting`, `expectNewSessionRequested`, `expectNoCompactRequested` wired to fixture callbacks — extend harness options, never app state). - [ ] **Step 2: Run to verify failure** — `pnpm vitest run test/composer-overflow.browser.test.tsx` (cwd `apps/conciv`). -- [ ] **Step 3: Implement pane-composer + actions migration + harness width control per the blocks above.** -- [ ] **Step 4: Run the new suite AND neighbors** — `pnpm vitest run test/composer-overflow.browser.test.tsx test/chat-pane.browser.test.tsx test/launch-menu.browser.test.tsx test/launch-actions.browser.test.tsx test/model-selector.browser.test.tsx` — PASS (refresh tests still pass: refresh is untouched). -- [ ] **Step 5: Package gate + commit** — `pnpm turbo run test --filter=@conciv/conciv` (use the app's real package name from `apps/conciv/package.json`), then commit (`feat(conciv): collapse composer actions into overflow menu`, pathspec `apps/conciv`). +- [ ] **Step 3: Implement pane-composer + actions migration + harness width control.** +- [ ] **Step 4: Run new suite AND neighbors** — `pnpm vitest run test/composer-overflow.browser.test.tsx test/chat-pane.browser.test.tsx test/launch-menu.browser.test.tsx test/launch-actions.browser.test.tsx test/model-selector.browser.test.tsx` — PASS (refresh untouched, its tests stay green). +- [ ] **Step 5: Package gate + adoption grep + commit** (`feat(conciv): collapse composer actions into overflow menu`, pathspec `apps/conciv`). --- ### Task 4: Launch menu flattening (multi-item root) **Files:** -- Modify: `apps/conciv/src/composer/launch-menu.tsx` +- Modify: `apps/conciv/src/composer/launch-menu.tsx`, `apps/conciv/src/composer/actions.tsx` - Test: extend `apps/conciv/test/launch-menu.browser.test.tsx` -**Interfaces:** -- Consumes: `Action.Inline` + multi-`DropdownItem` from Task 2/3; `LaunchMenu` props signature unchanged. - -`LaunchMenu` gains collapsed items as siblings of the `Inline` block inside the Task 3 `Action.Root id="conciv.launch"` (move the `Root` wrapper from `actions.tsx` into `LaunchMenu` itself so the component owns both renderings; `actions.tsx` then renders bare ``): +`LaunchMenu` owns both renderings — the `Action.Root id="conciv.launch"` moves from `actions.tsx` into `LaunchMenu` itself (`actions.tsx` renders bare ``): ```tsx local.pending === true}> @@ -451,10 +434,10 @@ test('repeated resize across the threshold settles without flapping', async () = ``` -- [ ] **Step 1: Failing tests** — narrow pane: `menuitem` named `Open in ` and `Copy command` inside the shared overflow menu, contiguous; failure state shows the retry item instead. Wide pane: existing launch tests unchanged. +- [ ] **Step 1: Failing tests** — narrow: `Open in ` + `Copy command` menuitems contiguous in the shared menu; failure state shows the retry item instead. Wide: existing launch tests unchanged. - [ ] **Step 2: Run to verify failure.** - [ ] **Step 3: Implement.** -- [ ] **Step 4: Run** launch + overflow + chat-pane suites — PASS; package gate. +- [ ] **Step 4: Run launch + overflow + chat-pane suites; package gate.** - [ ] **Step 5: Commit** (`feat(conciv): launch menu flattens into composer overflow`, pathspec `apps/conciv`). --- @@ -462,11 +445,11 @@ test('repeated resize across the threshold settles without flapping', async () = ### Task 5: Migrate extension clients, scaffolds, authoring docs **Files:** -- Modify: `packages/extensions/whiteboard/src/client.tsx`, `packages/extensions/tanstack/src/client.tsx`, `packages/extension/src/catalog.ts` (`composer-action` AND `full` templates + the composer slot description), `packages/extension/test/catalog.test.ts`, `packages/harness/plugins/claude/skills/conciv-extensions/SKILL.md`, `apps/site/content/docs/extending/widget-ui.mdx` - -**Interfaces:** no authoring surface anywhere still demonstrates a raw composer button. +- Modify: `packages/extensions/whiteboard/src/client.tsx`, `packages/extensions/tanstack/src/client.tsx` (both add `import {ComposerActions} from '@conciv/ui-kit-chat'` — check each package.json declares `@conciv/ui-kit-chat`; add the workspace dep if absent, it's an internal workspace ref, not a new third-party dep) +- Modify (TEMPLATE STRINGS ONLY — no runtime code in this package): `packages/extension/src/catalog.ts` (`composer-action` + `full` templates now emit `import {ComposerActions} from '@conciv/ui-kit-chat'` examples; composer slot description names the primitives), `packages/extension/test/catalog.test.ts` (assertions match new verbatim strings) +- Modify: `packages/harness/plugins/claude/skills/conciv-extensions/SKILL.md`, `apps/site/content/docs/extending/widget-ui.mdx` -Whiteboard `Component` composer branch: +Whiteboard composer branch: ```tsx @@ -489,11 +472,11 @@ Whiteboard `Component` composer branch: ``` -Tanstack client: same transform. Templates/docs rewritten around the same example (scaffold templates must compile under the scaffold test's assertions — update `catalog.test.ts` expectations to the new verbatim template strings). +Tanstack: same transform. No authoring surface anywhere still demonstrates a raw composer button. - [ ] **Step 1: Update `catalog.test.ts` expectations (failing)** — `pnpm vitest run test/catalog.test.ts` (cwd `packages/extension`) — FAIL. - [ ] **Step 2: Apply all migrations.** -- [ ] **Step 3: Gates** — `pnpm turbo run test --filter=@conciv/extension`; tanstack package gate (its real name from `package.json`); whiteboard: `pnpm turbo run typecheck --filter= && pnpm turbo run build --filter= && pnpm turbo run lint --filter=` (suite is CI-only — lint IS part of the local gate). +- [ ] **Step 3: Gates** — `pnpm turbo run test --filter=@conciv/extension`; tanstack package gate; whiteboard typecheck + build + lint ONLY; adoption grep. - [ ] **Step 4: Commit** (`feat(extensions): author composer buttons through ComposerActions`, pathspec touched packages + site docs). --- @@ -501,14 +484,12 @@ Tanstack client: same transform. Templates/docs rewritten around the same exampl ### Task 6: Extension-testkit host support + fixture **Files:** -- Modify: `packages/extension-testkit/src/host/host-runtime.tsx` (wrap the composer-slot mount in `ComposerActionsHost` inside a width-controllable container with an accessible width control), `packages/extension-testkit/fixtures/ping/client.tsx` (fixture gains a `ComposerActions` root: Button + two DropdownItems) -- Test: new `packages/extension-testkit/test/composer-actions.it.test.ts` following the existing `test/*.it.test.ts` + `fixtureHost` pattern (NOT `e2e/` — that directory holds websocket/RPC probes) +- Modify: `packages/extension-testkit/src/host/host-runtime.tsx` (wrap the composer-slot mount in `ComposerActionsHost` — testkit already depends on `@conciv/ui-kit-chat` — inside a width-controllable container with a labeled width control), `packages/extension-testkit/fixtures/ping/client.tsx` (fixture gains a `ComposerActions` root: Button + two DropdownItems) +- Test: new `packages/extension-testkit/test/composer-actions.it.test.ts` following the existing `test/*.it.test.ts` + `fixtureHost` pattern (NOT `e2e/` — that holds websocket/RPC probes) -**Interfaces:** testkit hosts render extension `ComposerActions` with a real coordinator + shared menu, width driven through a labeled control on the host page (a range/number input the test sets via `userEvent` — no DOM measurement). - -- [ ] **Step 1: Failing test** — wide host: fixture button visible inline; narrow host (set via the width control): button gone, `More composer actions` opens, both fixture items present and fire (assert via the fixture's observable effect, same pattern the ping fixture already uses). +- [ ] **Step 1: Failing test** — wide host: fixture button inline; narrow (set via the labeled width control with `userEvent`): button gone, `More composer actions` opens, both fixture items present and fire (assert via the fixture's observable effect). - [ ] **Step 2: Implement host wrap + width control + fixture root.** -- [ ] **Step 3: Run** — `pnpm turbo run test --filter=@conciv/extension-testkit` — PASS. +- [ ] **Step 3: Run** — `pnpm turbo run test --filter=@conciv/extension-testkit`. - [ ] **Step 4: Commit** (`feat(extension-testkit): host composer actions coordinator`, pathspec `packages/extension-testkit`). --- @@ -516,29 +497,15 @@ Tanstack client: same transform. Templates/docs rewritten around the same exampl ### Task 7: Extract refresh from the composer **Files:** -- Modify (delete): `packages/ui-kit-chat/src/primitives/composer/composer.tsx` (`Refresh` action button + export), `packages/ui-kit-chat/src/primitives/composer/composer-handlers.tsx` (`onRefresh`), refresh-specific tests in `packages/ui-kit-chat/test/composer-completion.browser.test.tsx` (deleted, not rewired) -- Modify: `apps/conciv/src/app/pane-context.ts`, `apps/conciv/src/app/pane-provider.tsx`, `apps/conciv/src/routes/panel.$sessionId.tsx` (context value + header button), `apps/conciv/src/pane/chat-pane.tsx` (register handle, drop `onRefresh`), `apps/conciv/src/pane/pane-composer.tsx` (delete `TrailingControls`, trailing keeps only `ComposerSendControl`), `apps/conciv/src/routes/quick.tsx` (LIFT `PaneProvider` to wrap the whole `data-pw-qt-pane` div — the session bar currently sits outside it and `usePane()` would throw; button goes in that bar), `apps/conciv/src/routes/pip.$sessionId.tsx` (slim `flex justify-end px-2 pt-1` row above `ChatPane`) -- Modify: `apps/conciv/test/helpers/pane-harness.tsx` (THIRD `PaneContextValue` construction site — gains the signal pair; harness view renders `` alongside `ChatPane` so the suite has a target) +- Modify (delete): `packages/ui-kit-chat/src/primitives/composer/composer.tsx` (`Refresh` + export), `composer-handlers.tsx` (`onRefresh`), refresh-specific tests in `packages/ui-kit-chat/test/composer-completion.browser.test.tsx` (deleted, not rewired) +- Modify: `apps/conciv/src/app/pane-context.ts`, `apps/conciv/src/app/pane-provider.tsx`, `apps/conciv/src/routes/panel.$sessionId.tsx` (context value + header button), `apps/conciv/src/pane/chat-pane.tsx` (register handle, drop `onRefresh`), `apps/conciv/src/pane/pane-composer.tsx` (delete `TrailingControls`, trailing keeps only `ComposerSendControl`), `apps/conciv/src/routes/quick.tsx` (LIFT `PaneProvider` to wrap the whole `data-pw-qt-pane` div — the session bar sits outside it and `usePane()` would throw; button goes in that bar), `apps/conciv/src/routes/pip.$sessionId.tsx` (slim `flex justify-end px-2 pt-1` row above `ChatPane`) +- Modify: `apps/conciv/test/helpers/pane-harness.tsx` (THIRD `PaneContextValue` construction site — gains the signal pair; harness view renders `` alongside `ChatPane`) - Create: `apps/conciv/src/shell/refresh-button.tsx` -- Test: `apps/conciv/test/chat-pane.browser.test.tsx` (two refresh tests rewired against the harness-mounted `RefreshButton`), plus presence tests for the quick per-pane bar and pip chrome in those routes' existing suites (create `apps/conciv/test/quick-refresh.browser.test.tsx` / extend the pip suite if none exists — assert role button `'Refresh the conversation'` renders and is disabled while streaming, using each route's existing test scaffolding) +- Test: `apps/conciv/test/chat-pane.browser.test.tsx` (two refresh tests rewired against the harness-mounted `RefreshButton`), `apps/conciv/test/quick-refresh.browser.test.tsx` (quick per-pane presence + disabled-while-streaming) + pip presence in the pip suite if one exists (else cover pip mounting in quick-refresh file via its route scaffolding) **Interfaces:** -- `type RefreshHandle = {run: () => void; busy: () => boolean}` in `pane-context.ts`. -- `PaneContextValue` gains `refresh: Accessor` and `registerRefresh: (handle: RefreshHandle | null) => void`. ALL THREE construction sites updated (pane-provider.tsx, panel.$sessionId.tsx, pane-harness.tsx), each via: - -```tsx -const [refreshHandle, setRefreshHandle] = createSignal(null) -``` - -- `chat-pane.tsx` registers in the component body: - -```tsx -pane.registerRefresh({run: () => chat.refresh(), busy: () => chatBusy(chat)}) -onCleanup(() => pane.registerRefresh(null)) -``` - -(`chatBusy` is exported from `@conciv/ui-kit-chat` — `src/index.tsx:49`.) - +- `type RefreshHandle = {run: () => void; busy: () => boolean}` in `pane-context.ts`; `PaneContextValue` gains `refresh: Accessor`, `registerRefresh: (handle: RefreshHandle | null) => void`. ALL THREE construction sites get `const [refreshHandle, setRefreshHandle] = createSignal(null)`. +- `chat-pane.tsx` registers in the component body: `pane.registerRefresh({run: () => chat.refresh(), busy: () => chatBusy(chat)})` + `onCleanup(() => pane.registerRefresh(null))` (`chatBusy` exported from `@conciv/ui-kit-chat`). - `refresh-button.tsx`: ```tsx @@ -569,9 +536,9 @@ export function RefreshButton(props: {class?: string}): JSX.Element { Placements: panel header right cluster before the close button (`CLOSE` class); quick per-pane session bar (inside the lifted provider); pip chrome row. - [ ] **Step 1: Fallow trace BEFORE deleting** — `pnpm exec fallow dead-code --trace 'packages/ui-kit-chat/src/primitives/composer/composer.tsx:Refresh'` — confirm consumers are exactly `PaneComposer` + the ui-kit tests slated for deletion. -- [ ] **Step 2: Rewire the two refresh tests in `chat-pane.browser.test.tsx` to the harness-mounted `RefreshButton` (same role/name locator; disabled-while-streaming asserted with `toBeDisabled()`), add the quick/pip presence tests — run, FAIL.** +- [ ] **Step 2: Rewire tests (FAIL first)** — refresh tests target the harness-mounted `RefreshButton` (role button `'Refresh the conversation'`, `toBeDisabled()` while streaming); quick/pip presence tests. - [ ] **Step 3: Implement — deletions, context handle, `RefreshButton`, three placements, quick provider lift, harness update.** -- [ ] **Step 4: Run** — `pnpm turbo run test --filter=@conciv/ui-kit-chat`, then `pnpm vitest run test/chat-pane.browser.test.tsx test/composer-overflow.browser.test.tsx test/quick-refresh.browser.test.tsx` (cwd `apps/conciv`), then the app package gate — PASS. +- [ ] **Step 4: Run** — `pnpm turbo run test --filter=@conciv/ui-kit-chat`, then `pnpm vitest run test/chat-pane.browser.test.tsx test/composer-overflow.browser.test.tsx test/quick-refresh.browser.test.tsx` (cwd `apps/conciv`), then the app package gate. - [ ] **Step 5: Commit** (`feat(conciv): session refresh moves to pane chrome, out of the composer`, pathspec `packages/ui-kit-chat apps/conciv`). --- @@ -585,10 +552,10 @@ Placements: panel header right cluster before the close button (`CLOSE` class); ```md --- -'@conciv/extension': patch +'@conciv/ui-kit-chat': patch --- -Composer actions collapse into a shared overflow menu; extensions author buttons through ComposerActions.Root/Button/DropdownItem/Inline. Session refresh moved out of the composer into pane chrome. +Composer actions collapse into a shared overflow menu; extensions author buttons through ComposerActions.Root/Button/DropdownItem/Inline from @conciv/ui-kit-chat. Session refresh moved out of the composer into pane chrome. ``` - [ ] **Step 2: Coverage check** — `pnpm exec conciv-publish check-changesets --require-coverage --base origin/main`. @@ -599,8 +566,7 @@ Composer actions collapse into a shared overflow menu; extensions author buttons ## Self-Review Notes -- Spec §1 → Tasks 1-2 (`Inline` lands in Task 2, used from Task 3 so launch is fit-counted from the first integration commit). §2 → Task 2-3. §3 → Tasks 3-5. §4 → Task 7. Testing → Tasks 3, 4, 6, 7. Gates → Task 8 (embed/mount-externals guard pulled forward into Task 2). -- Spec deviations, both intentional and recorded: (a) `RefreshButton` reads `PaneContext` on every surface instead of chat-context + panel-only relay — quick's bar and the panel header both sit above `ChatProvider`; quick's `PaneProvider` is lifted to make that true per-pane. (b) Menu ordering implemented as per-root group nodes in host-rendered DOM order, not portal order + CSS — zag walks DOM order, CSS `order` would desync keyboard from visuals. -- Root-level `disabled: () => boolean` is the ONLY disabled mechanism (spec requirement restored); `Button.busy` is styling-only. +- Placement: `@conciv/ui-kit-chat` per user direction (2026-08-16) — supersedes the spec's `@conciv/extension` export-surface line. `packages/extension` sees template-string edits only (Task 5). +- Spec deviations recorded: (a) `RefreshButton` reads `PaneContext` on every surface — quick's bar and panel header both sit above `ChatProvider`; quick's `PaneProvider` lifted per-pane. (b) Menu ordering = per-root group nodes in host DOM order — zag walks DOM order; CSS `order` desyncs keyboard from visuals. (c) Placement change above. +- Root-level `disabled: () => boolean` is the ONLY disabled mechanism; `Button.busy` styling-only. - Type names consistent: `FitInput`, `Registration`, `Coordinator`, `RootState`, `RefreshHandle`, `ComposerActionsHost`, `ComposerActions.{Root,Button,DropdownItem,Inline}`. -- Entry file is `packages/extension/src/index.ts` (no `.tsx` rename needed — the file only re-exports). From 73df597c0ce7ab845b75891c3ca230f42b6247c2 Mon Sep 17 00:00:00 2001 From: Omri Katz <9701896+omridevk@users.noreply.github.com> Date: Sun, 16 Aug 2026 16:43:23 +0300 Subject: [PATCH 06/24] feat(ui-kit-chat): ComposerActions compound primitives with overflow coordinator Co-Authored-By: Claude Fable 5 --- packages/ui-kit-chat/src/index.tsx | 9 + .../composer/composer-actions-fit.ts | 29 ++ .../primitives/composer/composer-actions.tsx | 336 +++++++++++++++++ .../test/composer-actions-fit.test.ts | 53 +++ .../test/composer-actions.browser.test.tsx | 338 ++++++++++++++++++ 5 files changed, 765 insertions(+) create mode 100644 packages/ui-kit-chat/src/primitives/composer/composer-actions-fit.ts create mode 100644 packages/ui-kit-chat/src/primitives/composer/composer-actions.tsx create mode 100644 packages/ui-kit-chat/test/composer-actions-fit.test.ts create mode 100644 packages/ui-kit-chat/test/composer-actions.browser.test.tsx diff --git a/packages/ui-kit-chat/src/index.tsx b/packages/ui-kit-chat/src/index.tsx index 8759abe720..9092f49e93 100644 --- a/packages/ui-kit-chat/src/index.tsx +++ b/packages/ui-kit-chat/src/index.tsx @@ -88,6 +88,15 @@ export { useComposerHandlers, type ComposerHandlers, } from './primitives/composer/composer-handlers.js' +export { + ComposerActions, + ComposerActionsHost, + type ComposerActionsButtonProps, + type ComposerActionsDropdownItemProps, + type ComposerActionsHostProps, + type ComposerActionsInlineProps, + type ComposerActionsRootProps, +} from './primitives/composer/composer-actions.js' export {ActionBar as ActionBarPrimitive, useCopied} from './primitives/action-bar/action-bar.js' export { ActionHandlersProvider, diff --git a/packages/ui-kit-chat/src/primitives/composer/composer-actions-fit.ts b/packages/ui-kit-chat/src/primitives/composer/composer-actions-fit.ts new file mode 100644 index 0000000000..0e95597283 --- /dev/null +++ b/packages/ui-kit-chat/src/primitives/composer/composer-actions-fit.ts @@ -0,0 +1,29 @@ +export const ACTION_SLOT_PX = 38 +export const REGION_GAP_PX = 4 +export const FIT_HYSTERESIS_PX = 24 + +export type FitInput = { + rowWidth: number + leadingWidth: number + trailingWidth: number + slotWidth: number + regionGapPx: number + pinnedCount: number + autoCount: number + previousCount: number | null + hysteresisPx: number +} + +export function computeVisibleAutoCount(input: FitInput): number { + const reserved = + input.leadingWidth + + input.trailingWidth + + 2 * input.regionGapPx + + input.slotWidth + + input.pinnedCount * input.slotWidth + const budget = input.rowWidth - reserved + const fits = Math.max(0, Math.min(input.autoCount, Math.floor(budget / input.slotWidth))) + if (input.previousCount === null || fits <= input.previousCount) return fits + if (budget < fits * input.slotWidth + input.hysteresisPx) return input.previousCount + return fits +} diff --git a/packages/ui-kit-chat/src/primitives/composer/composer-actions.tsx b/packages/ui-kit-chat/src/primitives/composer/composer-actions.tsx new file mode 100644 index 0000000000..777b9d48fe --- /dev/null +++ b/packages/ui-kit-chat/src/primitives/composer/composer-actions.tsx @@ -0,0 +1,336 @@ +import { + createContext, + createEffect, + createMemo, + createSignal, + createUniqueId, + For, + onCleanup, + Show, + splitProps, + untrack, + useContext, + type JSX, +} from 'solid-js' +import {createStore} from 'solid-js/store' +import {Portal} from 'solid-js/web' +import {createResizeObserver} from '@solid-primitives/resize-observer' +import {Menu, TooltipIconButton, TooltipIconButtonSlot} from '@conciv/ui-kit-system' +import {keyBy, orderBy} from 'es-toolkit' +import {ACTION_SLOT_PX, computeVisibleAutoCount, FIT_HYSTERESIS_PX, REGION_GAP_PX} from './composer-actions-fit.js' + +type Registration = { + key: string + id: string + priority: number + pinned: boolean + hasButton: boolean + itemCount: number + disabled: () => boolean +} + +type Coordinator = { + register: (entry: Registration) => void + update: (key: string, patch: Partial>) => void + adjustItemCount: (key: string, delta: number) => void + unregister: (key: string) => void + active: (key: string) => boolean + inline: (key: string) => boolean + groupMount: (key: string) => HTMLElement | undefined +} + +type RootState = { + key: string + id: string + priority: number + disabled: () => boolean + inline: () => boolean + update: (patch: Partial>) => void + adjustItemCount: (delta: number) => void +} + +const TRIGGER_TOOLTIP = 'More composer actions' +const TRIGGER_CLASS = 'size-8.5' +const ACTION_CLASS = 'size-8.5' +const REGION_CLASS = 'empty:hidden flex gap-1 items-center' + +const CoordinatorContext = createContext() +const RootContext = createContext() + +export type ComposerActionsHostProps = { + leading?: JSX.Element + trailing: JSX.Element + triggerContent: JSX.Element + onOverflowDismissed?: () => void + children: JSX.Element +} + +export function ComposerActionsHost(props: ComposerActionsHostProps): JSX.Element { + const [local] = splitProps(props, ['leading', 'trailing', 'triggerContent', 'onOverflowDismissed', 'children']) + const [registrations, setRegistrations] = createStore([]) + const [groupNodes, setGroupNodes] = createStore>({}) + const [rowElement, setRowElement] = createSignal() + const [leadingElement, setLeadingElement] = createSignal() + const [trailingElement, setTrailingElement] = createSignal() + const [rowWidth, setRowWidth] = createSignal(0) + const [leadingWidth, setLeadingWidth] = createSignal(0) + const [trailingWidth, setTrailingWidth] = createSignal(0) + const [menuOpen, setMenuOpen] = createSignal(false) + const warnedIds = new Set() + + createResizeObserver(rowElement, ({width}) => setRowWidth(width)) + createResizeObserver(leadingElement, ({width}) => setLeadingWidth(width)) + createResizeObserver(trailingElement, ({width}) => setTrailingWidth(width)) + + const indexOfKey = (key: string): number => registrations.findIndex((entry) => entry.key === key) + + const activeKeys = createMemo( + () => new Set(Object.values(keyBy([...registrations], (entry) => entry.id)).map((entry) => entry.key)), + ) + const activeRoots = createMemo(() => registrations.filter((entry) => activeKeys().has(entry.key))) + const sortedActiveRoots = createMemo(() => orderBy(activeRoots(), [(entry) => entry.priority], ['desc'])) + const pinnedRoots = createMemo(() => activeRoots().filter((entry) => entry.hasButton && entry.pinned)) + const autoRoots = createMemo(() => + orderBy( + activeRoots().filter((entry) => entry.hasButton && !entry.pinned), + [(entry) => entry.priority], + ['desc'], + ), + ) + + const visibleAutoCount = createMemo((previous) => { + const measuredRowWidth = rowWidth() + if (measuredRowWidth === 0) return previous + return computeVisibleAutoCount({ + rowWidth: measuredRowWidth, + leadingWidth: leadingWidth(), + trailingWidth: trailingWidth(), + slotWidth: ACTION_SLOT_PX, + regionGapPx: REGION_GAP_PX, + pinnedCount: pinnedRoots().length, + autoCount: autoRoots().length, + previousCount: previous, + hysteresisPx: FIT_HYSTERESIS_PX, + }) + }, null) + + const inlineKeys = createMemo( + () => + new Set([ + ...pinnedRoots().map((entry) => entry.key), + ...autoRoots() + .slice(0, visibleAutoCount() ?? 0) + .map((entry) => entry.key), + ]), + ) + + const anyCollapsed = createMemo(() => + activeRoots().some((entry) => entry.itemCount > 0 && !inlineKeys().has(entry.key)), + ) + + const coordinator: Coordinator = { + register: (entry) => { + if (registrations.some((existing) => existing.id === entry.id) && !warnedIds.has(entry.id)) { + warnedIds.add(entry.id) + console.warn(`ComposerActions: duplicate root id "${entry.id}" — the last registration wins`) + } + setRegistrations(registrations.length, entry) + }, + update: (key, patch) => { + const index = indexOfKey(key) + if (index < 0) return + setRegistrations(index, patch) + }, + adjustItemCount: (key, delta) => { + const index = indexOfKey(key) + if (index < 0) return + setRegistrations(index, 'itemCount', (previous) => previous + delta) + }, + unregister: (key) => setRegistrations((current) => current.filter((entry) => entry.key !== key)), + active: (key) => activeKeys().has(key), + inline: (key) => inlineKeys().has(key), + groupMount: (key) => groupNodes[key], + } + + createEffect(() => { + if (anyCollapsed()) return + if (!menuOpen()) return + setMenuOpen(false) + local.onOverflowDismissed?.() + }) + + return ( + + setMenuOpen(details.open)}> +
+
+ {local.leading} +
+ {local.children} + +
+ {local.trailing} +
+
+ + + + {(entry) => { + onCleanup(() => setGroupNodes(entry.key, undefined)) + return
setGroupNodes(entry.key, element)} /> + }} + + + + + + ) +} + +export type ComposerActionsRootProps = { + id: string + priority?: number + disabled?: () => boolean + children: JSX.Element +} + +function Root(props: ComposerActionsRootProps): JSX.Element { + const coordinator = useContext(CoordinatorContext) + if (coordinator === undefined) return null + const [local] = splitProps(props, ['id', 'priority', 'disabled', 'children']) + const key = createUniqueId() + const disabled = (): boolean => local.disabled?.() === true + const priority = (): number => local.priority ?? 0 + + coordinator.register( + untrack(() => ({ + key, + id: local.id, + priority: priority(), + pinned: false, + hasButton: false, + itemCount: 0, + disabled, + })), + ) + onCleanup(() => coordinator.unregister(key)) + createEffect(() => coordinator.update(key, {priority: priority(), disabled})) + + const state: RootState = { + key, + get id() { + return local.id + }, + get priority() { + return priority() + }, + disabled, + inline: () => coordinator.inline(key), + update: (patch) => coordinator.update(key, patch), + adjustItemCount: (delta) => coordinator.adjustItemCount(key, delta), + } + + return ( + + {local.children} + + ) +} + +export type ComposerActionsButtonProps = { + visible?: 'auto' | 'always' + tooltip: string + onClick: () => void + busy?: boolean + class?: string + variant?: 'ghost' | 'solid' + children: JSX.Element +} + +function Button(props: ComposerActionsButtonProps): JSX.Element { + const root = useContext(RootContext) + if (root === undefined) return null + const [local] = splitProps(props, ['visible', 'tooltip', 'onClick', 'busy', 'class', 'variant', 'children']) + const pinned = (): boolean => local.visible === 'always' + + root.update(untrack(() => ({hasButton: true, pinned: pinned()}))) + onCleanup(() => root.update({hasButton: false, pinned: false})) + createEffect(() => root.update({pinned: pinned()})) + + return ( + + local.onClick()} + > + {local.children} + + + ) +} + +export type ComposerActionsInlineProps = { + children: JSX.Element +} + +function Inline(props: ComposerActionsInlineProps): JSX.Element { + const root = useContext(RootContext) + if (root === undefined) return null + const [local] = splitProps(props, ['children']) + + root.update({hasButton: true}) + onCleanup(() => root.update({hasButton: false})) + + return {local.children} +} + +export type ComposerActionsDropdownItemProps = { + value: string + label: string + onSelect: () => void + children?: JSX.Element +} + +function DropdownItem(props: ComposerActionsDropdownItemProps): JSX.Element { + const root = useContext(RootContext) + const coordinator = useContext(CoordinatorContext) + if (root === undefined || coordinator === undefined) return null + const [local] = splitProps(props, ['value', 'label', 'onSelect', 'children']) + + root.adjustItemCount(1) + onCleanup(() => root.adjustItemCount(-1)) + + return ( + + {(mount) => ( + + local.onSelect()}> + {local.children} + {local.label} + + + )} + + ) +} + +export const ComposerActions = {Root, Button, DropdownItem, Inline} diff --git a/packages/ui-kit-chat/test/composer-actions-fit.test.ts b/packages/ui-kit-chat/test/composer-actions-fit.test.ts new file mode 100644 index 0000000000..90f9ab04d0 --- /dev/null +++ b/packages/ui-kit-chat/test/composer-actions-fit.test.ts @@ -0,0 +1,53 @@ +import {describe, expect, it} from 'vitest' +import { + ACTION_SLOT_PX, + computeVisibleAutoCount, + FIT_HYSTERESIS_PX, + REGION_GAP_PX, +} from '../src/primitives/composer/composer-actions-fit.js' + +const base = { + slotWidth: ACTION_SLOT_PX, + regionGapPx: REGION_GAP_PX, + hysteresisPx: FIT_HYSTERESIS_PX, + leadingWidth: 34, + trailingWidth: 120, + pinnedCount: 1, + autoCount: 4, + previousCount: null, +} + +const used = (autoSlots: number): number => + base.leadingWidth + + base.trailingWidth + + 2 * REGION_GAP_PX + + ACTION_SLOT_PX + + base.pinnedCount * ACTION_SLOT_PX + + autoSlots * ACTION_SLOT_PX + +describe('computeVisibleAutoCount', () => { + it('shows every auto action when the budget covers them', () => { + expect(computeVisibleAutoCount({...base, rowWidth: used(4) + 40})).toBe(4) + }) + + it('clamps to the available whole slots', () => { + expect(computeVisibleAutoCount({...base, rowWidth: used(2) + 10})).toBe(2) + }) + + it('never returns a negative count', () => { + expect(computeVisibleAutoCount({...base, rowWidth: 100})).toBe(0) + }) + + it('never exceeds the registered auto count', () => { + expect(computeVisibleAutoCount({...base, rowWidth: 5000})).toBe(4) + }) + + it('shrinks immediately when the row narrows', () => { + expect(computeVisibleAutoCount({...base, rowWidth: used(1) + 2, previousCount: 4})).toBe(1) + }) + + it('expands only once the budget clears the hysteresis margin', () => { + expect(computeVisibleAutoCount({...base, rowWidth: used(2) + 4, previousCount: 1})).toBe(1) + expect(computeVisibleAutoCount({...base, rowWidth: used(2) + FIT_HYSTERESIS_PX, previousCount: 1})).toBe(2) + }) +}) diff --git a/packages/ui-kit-chat/test/composer-actions.browser.test.tsx b/packages/ui-kit-chat/test/composer-actions.browser.test.tsx new file mode 100644 index 0000000000..63e948a082 --- /dev/null +++ b/packages/ui-kit-chat/test/composer-actions.browser.test.tsx @@ -0,0 +1,338 @@ +import 'virtual:uno.css' +import {createSignal, splitProps, type JSX} from 'solid-js' +import {expect, it} from 'vitest' +import {page, userEvent} from 'vitest/browser' +import {ComposerActions, ComposerActionsHost} from '../src/primitives/composer/composer-actions.js' +import {mountView} from './mount-view.js' + +const WIDE_PX = 400 +const ONE_SLOT_PX = 170 +const NO_SLOT_PX = 100 + +function Glyph(): JSX.Element { + return