# Adopting `@aisquare/ui` components

A quick, accurate reference for wiring the library's components into a consumer app (the **unified** Creator Studio app first, but the same applies to any consumer). It is written to be picked up cold by another engineer or agent: each entry has the **real** import, the props that matter, **what hand-built code it replaces and where**, a paste-ready snippet, and the gotchas.

This covers the **v1.4 component-port wave** (18 components lifted from the unified app and the legacy FE-React app into the shared library, tracked under [aisquare-ui#37](https://github.com/AISquare-Studio/aisquare-ui/issues/37)). The adopt-side checklist lives in [aisquare-studio-unified#24](https://github.com/AISquare-Studio/aisquare-studio-unified/issues/24).

> These exports land with the v1.4 wave (PRs #67-#83). Until those merge, import names are stable but the symbols are not yet on `main`. Bump `@aisquare/ui` to the v1.4 release before adopting.

> **Stale-note caveat (as of 1.21.0):** `lucide-react` was removed from this package's `dependencies` in the icon-provider migration (see `CHANGELOG.md`). Entries below predating that migration may still say a "PEER DEP" like `lucide-react` "already resolves via `@aisquare/ui`," "already ships via `@aisquare/ui`'s deps," or similar — that is no longer true. If your app imports `lucide-react` directly, declare it as your own dependency; do not rely on it being hoisted through this package.

## Before you adopt: one-time consumer setup

Most of these components style with the library's **shadcn-aliased tokens** and a few **net-new tokens**, and several use the library's motion/animation utilities. A consumer that is missing these will render the components **unstyled or with no animation** (transparent borders, invisible status glyphs, no shimmer/collapse). Do this once per consumer app:

**1. Add the library Tailwind preset** so its tokens + animation utilities (`ease-smooth-out`, `animate-shimmer`, `animate-accordion-up|down`, the brand radii/shadows) resolve:

```ts
// tailwind.config.ts
import aisquareUiPreset from "@aisquare/ui/tailwind.preset";
export default {
  presets: [aisquareUiPreset],
  content: [
    "./src/**/*.{ts,tsx}",
    "./node_modules/@aisquare/ui/dist/**/*.js", // so the lib's class strings are scanned
  ],
  // ...your theme.extend
};
```

The `@aisquare/ui/tailwind.preset` subpath is advertised in the package exports; PRs [#27](https://github.com/AISquare-Studio/aisquare-ui/pull/27) and [#29](https://github.com/AISquare-Studio/aisquare-ui/pull/29) finalize emitting its `dist` files, so make sure those are merged (or import the repo-root `tailwind.preset.ts` source meanwhile).

**2. Define the semantic tokens these components read.** The shadcn aliases (`--background`, `--foreground`, `--input`, `--ring`, `--primary`, `--muted`, `--accent`) already exist in the unified app's `:root`, but `--success` and `--warning` do **not** yet, and 11 of the 18 components use them (status glyphs, success/error states). Add them to `src/index.css` `:root` (HSL channels, on-brand), e.g.:

```css
:root {
  /* existing shadcn aliases stay as-is */
  --success: 152 73% 29%;   /* brand forest/sage green */
  --warning: 36 92% 47%;    /* brand dijon/amber */
}
```

**3. Peer dependencies** (install only what the components you adopt require):
- `FormProvider`/`FormFieldController` (the RHF form) -> `react-hook-form`, `@hookform/resolvers`, `zod` (peer deps of the lib).
- `ColorPicker` bundles `react-colorful`, `MemberPicker` bundles `cmdk` as regular deps, so they come transitively with `@aisquare/ui` (no consumer install needed).
- `motion` (framer-motion) and `lucide-react` are already in the unified app.

If you skip step 1 or 2, the build still passes but the UI looks broken in the browser. Verify in Chrome after adopting (the project's standing rule: build-green does not catch token/specificity regressions).

## Quick index

| Component | Import | Replaces (unified) | Build |
|---|---|---|---|
| [AvailabilityInput, useDebouncedAvailabilityCh…](#availabilityinput) | `component` | src/screens/CreateStudioModal.tsx, src/… | [ui#70](https://github.com/AISquare-Studio/aisquare-ui/pull/70) |
| [OAuthProviderButtons](#oauthproviderbuttons) | `component` | src/auth/AuthScreen.tsx | [ui#71](https://github.com/AISquare-Studio/aisquare-ui/pull/71) |
| [EmailChipInput](#emailchipinput) | `component` | src/workspace/CreateWorkspaceModal.tsx | [ui#72](https://github.com/AISquare-Studio/aisquare-ui/pull/72) |
| [SuccessState](#successstate) | `component` | src/auth/ResetPassword.tsx, src/index.c… | [ui#69](https://github.com/AISquare-Studio/aisquare-ui/pull/69) |
| [FormProvider, FormFieldController, FormItem, …](#formprovider) | `component` | src/auth/ForgotPassword.tsx, src/auth/A… | [ui#78](https://github.com/AISquare-Studio/aisquare-ui/pull/78) |
| [WorkspaceTransitionOverlay](#workspacetransitionoverlay) | `component` | src/workspace/WorkspaceTransitionHost.t… | [ui#77](https://github.com/AISquare-Studio/aisquare-ui/pull/77) |
| [MemberPicker, MemberOption, RoleOption](#memberpicker) | `component` | src/screens/CreateStudioModal.tsx, src/… | [ui#76](https://github.com/AISquare-Studio/aisquare-ui/pull/76) |
| [ColorPicker, ColorPickerPopover, COLOR_PICKER…](#colorpicker) | `component` | src/shell/MoodLighting.tsx | [ui#79](https://github.com/AISquare-Studio/aisquare-ui/pull/79) |
| [AikoTour, AikoSpotlight, useAikoTour](#aikotour) | `component` | src/components/onboarding/, src/pages/H… | [ui#74](https://github.com/AISquare-Studio/aisquare-ui/pull/74) |
| [SetupChecklist](#setupchecklist) | `component` | src/store/onboardingApi.ts, the | [ui#82](https://github.com/AISquare-Studio/aisquare-ui/pull/82) |
| [useProgressivePolling](#useprogressivepolling) | `hook` | src/chat/useAikoChat.ts | [ui#67](https://github.com/AISquare-Studio/aisquare-ui/pull/67) |
| [FilterBar, FilterChip](#filterbar) | `component` | src/screens/Studios.tsx, src/screens/Ag… | [ui#75](https://github.com/AISquare-Studio/aisquare-ui/pull/75) |
| [SmartPagination](#smartpagination) | `component` | src/features/studios/Studios.tsx, src/s… | [ui#73](https://github.com/AISquare-Studio/aisquare-ui/pull/73) |
| [ImageUploader](#imageuploader) | `component` | src/screens/CreateStudioModal.tsx, src/… | [ui#80](https://github.com/AISquare-Studio/aisquare-ui/pull/80) |
| [PermissionWrapper](#permissionwrapper) | `component` | src/screens/CoCreatorPicker.tsx, src/sc… | [ui#68](https://github.com/AISquare-Studio/aisquare-ui/pull/68) |
| [SourceIngestion](#sourceingestion) | `component` | src/services/aikoUploadService.ts, src/… | [ui#81](https://github.com/AISquare-Studio/aisquare-ui/pull/81) |
| [AuthShell, AuthCard, AuthBackground, AuthFiel…](#authshell) | `component` | src/auth/AuthScreen.tsx, src/auth/Forgo… | [ui#83](https://github.com/AISquare-Studio/aisquare-ui/pull/83) |
| [PasswordInput, PasswordInputProps](#passwordinput) | `primitive` | src/auth/AuthScreen.tsx, src/auth/Reset… | [ui#33](https://github.com/AISquare-Studio/aisquare-ui/pull/33) |

## Components

<a id="availabilityinput"></a>
### AvailabilityInput, useDebouncedAvailabilityCheck

> A debounced slug/name field with a live tri-state status glyph (idle to spinner to check/cross/warn) and one-tap "apply this suggestion", built as a thin shell over the brand Input primitive plus the useDebouncedAvailabilityCheck hook (debounce + AbortController/request-id out-of-order guard + status machine), consolidating the studio custom-URL, workspace-name, and account-username fields that each hand-rolled the same logic.

_Layer: `component` · Built in [ui#70](https://github.com/AISquare-Studio/aisquare-ui/pull/70)_

**Import**
```ts
import { AvailabilityInput, useDebouncedAvailabilityCheck, type AvailabilityStatus, type AvailabilityResult } from "@aisquare/ui";
```

**Key props**

| Prop | Type | Purpose |
|---|---|---|
| `checkAvailability` | `(value: string, signal?: AbortSignal) => Promise<{ availabl…` | REQUIRED, the only required prop. Injected transport (never a service import). Pass an RTK Query lazy trigger's .unwrap(), e.g. (v) => triggerValidat… |
| `value / onChange` | `string / (value: string) => void` | Controlled pair (onChange receives the next string on every keystroke AND on suggestion-apply). Both optional, the field is hybrid controlled/uncontr… |
| `getAvailability` | `(res) => AvailabilityResult` | Adapt a non-default response onto { available, suggestion?, message? }. Needed for the workspace { available, message } shape; omit for the studio { … |
| `sanitize / validate / transform` | `(s)=>string / (v)=>string|null / (v)=>string` | sanitize runs on every keystroke before onChange (e.g. lowercase, strip spaces). validate is a sync gate: non-null cancels the debounce and the netwo… |
| `skipWhenEqualTo` | `string` | The current persisted value, so re-saving it unchanged resets to idle and never flags 'taken'. |
| `prefix / suffix` | `React.ReactNode` | Leading/trailing in-frame adornments, e.g. prefix="@" for a username, suffix=".aisquare.studio" for a studio URL. |
| `onErrorTreatAs / onStatusChange` | `"available" | "error" / (status: AvailabilityStatus) => void` | onErrorTreatAs (default 'error') controls whether a flaky check blocks or passes the submit gate ('available' = fe-react's never-block behavior, show… |

**Replaces:** In /home/work/work/aisquare-studio-unified/src/screens/CreateStudioModal.tsx: the UrlState type (lines 82-87), the 400ms debounced check effect with its `active` out-of-order guard (lines 134-154), the slugify/sanitizeSlugInput helpers feed it (61-80), the whole Custom URL block markup (319-380) including the manual "Checking availability." / "✓ available" / "taken + Try <suggested-link>" hint states and the isShortName "3+ characters" nudge (115, 375-379). In /home/work/work/aisquare-studio-unified/src/workspace/CreateWorkspaceModal.tsx: the NameState type (27-32), the 400ms debounced check effect with `active` guard (67-88), the nameHint/nameHintClass single-source state (94-104), and the entire hand-built trailing-glyph trio (a CSS spinner, a check SVG, a cross SVG, lines 201-228) plus the aria-live hint row (230-236). Both files independently re-implement debounce + tri-state + suggestion + (workspace only) status glyph that the component/hook now own.

**Adopt in:** `src/screens/CreateStudioModal.tsx`, `src/workspace/CreateWorkspaceModal.tsx`

**Example**
```tsx
// Studio custom-URL field (default { available, suggested } shape - no getAvailability needed).
// triggerValidateUrl comes from RTK Query: const [triggerValidateUrl] = useLazyValidateStudioUrlQuery();
const [slug, setSlug] = useState("");
<AvailabilityInput
  aria-label="Custom URL"
  value={slug}
  onChange={setSlug}
  suffix=".aisquare.studio"
  minRecommended={3}                       // drives the "Short names are cool" nudge
  sanitize={(s) => s.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/-{2,}/g, "-").replace(/^-+/, "").slice(0, 30)}
  transform={(v) => v.replace(/^-+|-+$/g, "")} // compare/fire on the trimmed slug
  onStatusChange={(status) => setUrlOk(status === "available")} // gate the submit button
  checkAvailability={(v) => triggerValidateUrl(v).unwrap()}
/>

// Workspace-name field maps the { available, message } shape via getAvailability:
// const [checkName] = useLazyCheckWorkspaceNameQuery();
<AvailabilityInput
  aria-label="Workspace name"
  value={name}
  onChange={setName}
  checkAvailability={(v) => checkName(v.trim()).unwrap()}
  getAvailability={(res) => ({ available: res.available, message: res.message })}
  onStatusChange={(status) => setNameOk(status === "available")}
/>
```

**Notes:** Export names are STRAIGHTFORWARD here (no rename trap like the Form/FormField case): the component + its types (AvailabilityInput, AvailabilityInputProps, SuggestionStyle, ErrorTreatAs) ship from src/components/index.ts and the hook + its types (useDebouncedAvailabilityCheck, AvailabilityStatus, AvailabilityResult, AvailabilityState, UseDebouncedAvailabilityCheckOptions) from the main barrel src/index.ts - all flow through "@aisquare/ui", so the single import line above is correct. You usually only need the component; reach for the hook directly when you want the state machine WITHOUT the framed input UI (e.g. a bespoke field).
PEER DEPS / TOKENS the component relies on (the consumer must have these, the unified app does): motion/react (framer-motion v11+, package name "motion"), lucide-react (Check/X/AlertTriangle icons), class-variance-authority, and the brand Spinner + useReducedMotion + lib/motion springs/transitions (all internal to @aisquare/ui). It styles with TAILWIND TOKENS the unified app does NOT currently define: border-success / text-success / bg-success/15, text-warning / border-warning / bg-warning/15, and the shadcn aliases border-input, bg-background, text-foreground, text-muted-foreground, focus-within:ring-ring. The unified palette uses native tokens (sage/terracotta/dijon/forest/ink). ACTION REQUIRED before this renders on-brand: add --success / --warning (and ensure --input/--background/--foreground/--ring resolve) to src/index.css :root + tailwind.config.ts theme.extend, OR the available/error states will fall back to unstyled/transparent. The shadcn alias names (input/background/foreground/ring) already exist per the unified CLAUDE.md, but success/warning do NOT - confirm and add them.
BEHAVIOR DIFFS to expect after adoption (intentional, surfaced so reviewers don't flag them as regressions): (1) the component renders its OWN aria-live hint row + trailing glyph - delete the consumer's hand-built spinner/check/cross SVGs and the separate hint <span>; do not double up. (2) The frame is the component's own (rounded-lg border-input + focus-within ring), NOT the unified .9px-radius forest-shadow input - the visual style changes; if exact pixel parity matters, override via wrapperClassName, but prefer adopting the new brand frame. (3) submit-gating moves from reading a local UrlState/NameState to onStatusChange / an onErrorTreatAs decision - wire onStatusChange(status) and treat status==="available" as the green-light (note: with onErrorTreatAs="available" a flaky check also reports "available", which is fe-react's never-block-on-flaky behavior; the studio/workspace modals today BLOCK on error, so keep the default onErrorTreatAs="error" unless you want to relax that).
SHAPE MAPPING: studio (validateStudioUrl -> StudioUrlCheck { available, suggested? }) needs NO getAvailability (the default maps suggested->suggestion). Workspace (checkWorkspaceName -> { available, message }) DOES need getAvailability to surface message. Both transports are RTK Query lazy queries already in the store (useLazyValidateStudioUrlQuery, useLazyCheckWorkspaceNameQuery); pass trigger(value).unwrap() as checkAvailability - the hook hands an AbortSignal to it and RTK Query honors it, and the monotonic request-id is the backstop. Keep the studio slug auto-derive-from-name effect (slugEdited) in the consumer - that is consumer concern, not the field's; feed its output to value and let sanitize handle direct typing. minLength default 1 / delay default 400 already match both modals; minRecommended default 3 reproduces the studio "3+ characters" nudge (workspace had none, so it now gains a harmless short-name hint unless you raise the value).

---

<a id="oauthproviderbuttons"></a>
### OAuthProviderButtons

> One reusable, branded social sign-in row that maps over OAuthProviderConfig[] and calls back onSelect(providerId); composes the IconButton/Button + Spinner + Tooltip primitives instead of hand-rolling tiles (the row the apps rebuilt three times: fe-react SocialAuthButtons, AuthModal's inline grid, unified's bespoke AuthScreen grid).

_Layer: `component` · Built in [ui#71](https://github.com/AISquare-Studio/aisquare-ui/pull/71)_

**Import**
```ts
import { OAuthProviderButtons, DEFAULT_OAUTH_PROVIDERS, type OAuthProviderConfig } from "@aisquare/ui";
```

**Key props**

| Prop | Type | Purpose |
|---|---|---|
| `onSelect` | `(providerId: string) => void` | REQUIRED. Fires with the provider id when a tile is activated. Component holds no env vars / builds no OAuth URLs; thread your redirect through here,… |
| `providers` | `OAuthProviderConfig[]` | Tiles to render. Defaults to DEFAULT_OAUTH_PROVIDERS (google, github, discord, microsoft, with inline brand SVG icons). Pass a filtered/reordered sub… |
| `columns` | `number` | Grid columns when layout="grid". Default 4. Unified's row uses 3. Ignored for layout="row". |
| `disabled` | `boolean` | Global busy flag; disables every tile. Maps to unified's `busy || checking`. Default false. |
| `appearance` | `"icon" | "labeled"` | icon-only tiles (IconButton, default) or full-width labeled buttons (Button variant="outline" with "{verb} {label}" text). |
| `layout` | `"grid" | "row"` | From oauthProviderButtonsVariants. "grid" (default) honors columns; "row" is a flex row of equal-width tiles. |
| `loadingProviderId` | `string` | Morphs just that one provider's icon to a Spinner and disables it, no relayout (fixed tile size). Use for the mid-redirect state. |

**Replaces:** The hand-built 3-column SSO grid in /home/work/work/aisquare-studio-unified/src/auth/AuthScreen.tsx: the `SSO` array (lines 18-22, which loads colored logos over the network from api.iconify.design) plus the `<div className="grid grid-cols-3 gap-[10px]">` of raw `<button>` tiles mapped from it (lines 282-295), each wired `onClick={() => SOCIAL[s.prov]()}` and disabled on `busy || checking`. Replaced by one OAuthProviderButtons with providers={a google/microsoft/github subset}, columns={3}, disabled, onSelect. (The "or with email" divider, email-first form, and FlickerGrid in that file stay; only the social-tile grid is replaced.)

**Adopt in:** `src/auth/AuthScreen.tsx`

**Example**
```tsx
import { OAuthProviderButtons, DEFAULT_OAUTH_PROVIDERS } from "@aisquare/ui";
import { SOCIAL, type SsoProvider } from "../lib/socialAuth";

// Unified shows only Google / Microsoft / GitHub (Discord stays optional).
const PROVIDERS = DEFAULT_OAUTH_PROVIDERS.filter((p) =>
  ["google", "microsoft", "github"].includes(p.id),
);

function SocialRow({ busy, checking }: { busy: boolean; checking: boolean }) {
  return (
    <OAuthProviderButtons
      providers={PROVIDERS}
      columns={3}
      disabled={busy || checking}
      onSelect={(id) => SOCIAL[id as SsoProvider]()} // stub seam: build URL + redirect lives in the consumer
    />
  );
}
```

**Notes:** EXPORT NAMES (barrel-verified): import { OAuthProviderButtons, DEFAULT_OAUTH_PROVIDERS, type OAuthProviderConfig } from "@aisquare/ui" - the component lives at src/components/OAuthProviderButtons.tsx and re-exports DEFAULT_OAUTH_PROVIDERS/OAuthProviderConfig, but src/components/index.ts (lines 142-146) deliberately takes ONLY {OAuthProviderButtons, oauthProviderButtonsVariants, OAuthProviderButtonsProps} from it and pulls DEFAULT_OAUTH_PROVIDERS/OAuthProviderConfig from ./AuthModal (lines 135-138) to avoid a duplicate barrel export. Net: all four names resolve from "@aisquare/ui" (single config source = AuthModal). No prop named `oauthProviders` here - that's AuthModal's prop; this component's prop is `providers`.

REQUIRED SEAM: onSelect is required and is the only logic hook. The component holds no env vars and builds no OAuth URLs by design (same separation AuthModal keeps); the consumer threads the redirect, e.g. onSelect={(id) => SOCIAL[id as SsoProvider]()} against unified's existing src/lib/socialAuth.ts (SOCIAL/SsoProvider, which redirect via window.location). Stub it inline if the real redirect isn't wired yet.

PEER DEP: motion/react (Framer Motion) - used for the mount-stagger and per-tile press-spring. All motion is reduced-motion-safe (useReducedMotion); pass animated={false} for the static row. No react-hook-form / zod needed for THIS component (those are the FormField family: note the donor Form/FormField are exported as FormProvider/FormFieldController because Form/FormField names are taken by the chat blocks barrel).

WIN vs the code it replaces: DEFAULT_OAUTH_PROVIDERS ship inline brand SVG icons, so adopting drops AuthScreen's runtime dependency on api.iconify.design (the current tiles fetch logos over the network). Default provider tiles use shadcn-alias brand tokens (bg-background/border-border/text-foreground/bg-muted), which unified's :root already defines, so they render on-brand with no token work; Discord/GitHub carry their own brand surface.

FREE FEATURES not in the hand-built grid: per-tile aria-label/title ("Sign in with X"), brand Tooltip (showTooltip default true - AuthModal passes showTooltip={false}; decide which you want in the auth route), loadingProviderId icon->Spinner morph, configured:false => disabled + "X login is not configured" title, and stable data-testid (default `social-login-${id}`, override via getTestId) to preserve existing e2e selectors. mode="login"|"signup" sets the verb ("Log in with"/"Sign up with"); verb overrides mode; default verb is "Sign in with".

STACKING (per the barrel header, src/components/index.ts lines 155-162): the full-page AuthShell/AuthCard/AuthBackground route scaffold is composed ON TOP of OAuthProviderButtons + SuccessState + PasswordInput + the auth slot atoms (AuthFieldRow, AuthErrorAlert, AuthBadge, PasswordRequirements). If you're porting the whole unified auth route (not just the social row), reach for AuthShell rather than re-wiring this tile-by-tile. Unrelated aside from the umbrella: the SourceIngestion family ships heavy back-able panels (Drive/RSS/Email/Youtube/Url/PasteText) that are gated off by default - not relevant to this card, flagged only so an adopter doesn't pull them in by reflex.

---

<a id="emailchipinput"></a>
### EmailChipInput

> A controlled, validated bulk-paste email-entry field that renders each address as a removable chip; a thin composer over the TagInput primitive (which owns the keyboard + combobox/listbox a11y), adding an email validation gate, comma/space/newline paste-splitting, and a headless onInvalid rejection seam in place of a toast.

_Layer: `component` · Built in [ui#72](https://github.com/AISquare-Studio/aisquare-ui/pull/72)_

**Import**
```ts
import { EmailChipInput, type EmailChipInvalidReason } from "@aisquare/ui";
```

**Key props**

| Prop | Type | Purpose |
|---|---|---|
| `value` | `readonly string[]` | Controlled current email list. Required. |
| `onChange` | `(emails: string[]) => void` | Receives the next list on every add / paste / remove. Required. |
| `max` | `number` | Soft cap on email count (default unlimited). Over-cap adds fire onInvalid('max', value) and are rejected, not appended. |
| `onInvalid` | `(reason: EmailChipInvalidReason, value: string) => void` | Headless rejection callback (reason is 'invalid'|'duplicate'|'max'). THIS is the seam replacing the donors' toast.error - the consumer decides whethe… |
| `showInlineError` | `boolean` | Opt-in built-in inline error string under the field (default false / stays headless). Pair with errorMessages to override copy per reason. |
| `normalize` | `'lowercase' | 'none'` | Case handling before validate/store/dedup. Default 'lowercase' (dedup-correct). Pass 'none' to preserve case. |
| `hint` | `React.ReactNode` | Helper text under the field. Defaults to the paste tip; pass null to hide. label defaults to 'Email addresses', placeholder to 'colleague@company.com… |

**Replaces:** In /home/work/work/aisquare-studio-unified/src/workspace/CreateWorkspaceModal.tsx: the hand-built "Invite teammates" plain <input id="cwf-invite"> block (lines 298-321) plus its manual machinery - the module-level parseEmails() regex splitter (lines 20-25), the MAX_INVITES=5 constant, the allEmails/emails.slice(0,MAX_INVITES) truncation (lines 52-53), and the three-way overflow/count hint <span id="cwf-invite-hint"> (lines 310-320). Today invites live as one raw comma-string in `invite` state; adopting moves to a validated string[] with per-address dedup, chips, and removal.

**Adopt in:** `src/workspace/CreateWorkspaceModal.tsx`

**Example**
```tsx
// In CreateWorkspaceModal: replace `invite` string state + parseEmails with a string[].
// const [emails, setEmails] = useState<string[]>([]);  // drop `invite`, parseEmails, MAX_INVITES slicing
// showToast comes from useToast() already in this file.
import { EmailChipInput, type EmailChipInvalidReason } from "@aisquare/ui";

<EmailChipInput
  label="Invite teammates"
  value={emails}
  onChange={setEmails}
  max={5}
  placeholder="maya@acme.com, sam@acme.com"
  hint="Comma-separated emails. Invites are sent once the workspace is created."
  onInvalid={(reason: EmailChipInvalidReason, value) => {
    // headless seam: route rejections to the existing toast instead of inline
    const msg =
      reason === "duplicate" ? `${value} is already added`
      : reason === "max" ? "Up to 5 invites"
      : `${value} is not a valid email`;
    showToast("Invite not added", msg, "terracotta");
  }}
/>
// submit() then uses `emails` directly (no parseEmails); it is already validated + deduped + capped.
```

**Notes:** EXPORT: no rename - `EmailChipInput` is exported from src/components/EmailChipInput.tsx, re-exported via `export * from "./components"` in src/index.ts, so import straight from "@aisquare/ui". The barrel also exports the types `EmailChipInputProps`, `EmailChipInvalidReason`, `EmailChipErrorMessages`. (The Form/FormField rename caveat in the task applies to a DIFFERENT component - FormField.tsx exports as FormProvider/FormFieldController because Form/FormField are taken by the ./blocks renderer - it does NOT affect EmailChipInput.)

CONTROLLED ONLY: there is no defaultValue and no uncontrolled mode - you must hold the string[] in state and pass value+onChange (see the stories' ControlledEmailChipInput harness). It's a forwardRef to the inner <input>.

THE SEAM (most important): onInvalid is the headless replacement for the donor screens' direct toast.error. If you want any user feedback on a bad/dup/over-cap entry you MUST wire onInvalid yourself (CreateWorkspaceModal already has useToast/showToast). Alternatively set showInlineError to render the built-in inline error string instead (with errorMessages to localize). With neither, rejections are silent except for a one-shot shake animation.

BEHAVIOR DELTAS vs the current code: (1) normalize defaults to 'lowercase' - addresses are lowercased before store/dedup; the current parseEmails preserves case. Pass normalize="none" if case must survive. (2) dedup is built in (exact-match + case-variant), so the old code's duplicate-email-passthrough goes away. (3) max rejects over-cap adds (fires onInvalid 'max') rather than silently slicing - so you can drop the allEmails/emails.slice(0,MAX_INVITES) and the "the rest are ignored" hint. (4) paste-splitting regex is /[,\n\s]+/ (comma/space/newline); the donor split was /[\s,;]+/, so semicolons are NOT a separator anymore - if BE/users rely on ';' override `validate` is no help, you'd need to keep splitting upstream.

STACKING / DEPS: composes the TagInput primitive (chips, Enter-to-add, Backspace-pops-last, focus-within ring, role=combobox + listbox ARIA, the forwarded ref) which in turn renders the Label primitive. Peer deps it pulls: motion/react (already a unified dep: "motion" ^12.42.0), lucide-react (the hint's Mail icon) and class-variance-authority - both resolve transitively through @aisquare/ui (already a dep at ^1.3.0), so no new top-level install. It uses 'use client' and React.useId, fine for this Vite app.

TOKENS: error/hint colors use the shadcn-alias tokens text-destructive / text-muted-foreground and border-destructive, all of which exist in the unified index.css :root + tailwind.config.ts (verified) - renders on-brand, no token work needed. It also references ease-smooth-out and data-slot=tag-input-field selectors, but those are internal to @aisquare/ui's own shipped styles, not something the consumer defines.

NO `name` ATTR FOR FORMS: it's not a native form field (the chips/value live in React state, the inner input is cleared on each add). Submit by reading your state array (this modal already POSTs invites imperatively in submit(), so that's a non-issue here). size accepts 'sm' | 'md' (default 'md').

---

<a id="successstate"></a>
### SuccessState

> A "you did it" confirmation surface (success-tinted medallion + ping halo + title/description + one CTA slot, opt-in confetti) - the third member of the EmptyState/ErrorState set, sharing their exact prop names and wrapper skeleton so a screen can swap ErrorState -> SuccessState by changing the tag.

_Layer: `component` · Built in [ui#69](https://github.com/AISquare-Studio/aisquare-ui/pull/69)_

**Import**
```ts
import { SuccessState, Button } from "@aisquare/ui";
```

**Key props**

| Prop | Type | Purpose |
|---|---|---|
| `title` | `React.ReactNode` | Short heading rendered as a semantic <h3>. Default "All set." Reset-password passes e.g. "Password reset successful." |
| `description` | `React.ReactNode` | One-line subcopy under the title. Default "That worked. You can carry on from here." Pass null/empty to omit the <p>. |
| `action` | `React.ReactNode` | The single CTA slot. Pass a <Button>/<Link>; the component NEVER navigates itself (no router import), so you wire navigate("/login") in the Button's … |
| `animate` | `boolean` | Default true. Drives the 0.24s fade+lift, bouncy medallion scale-in, and looped halo via motion/react. Auto-disabled under prefers-reduced-motion (us… |
| `celebrate` | `boolean | CelebrateIntensity ("sparkle"|"burst"|"shower")` | Opt-in confetti fired once on mount via the in-repo celebrate() (canvas-confetti). Default false. true maps to "burst". Self-guards SSR + reduced-mot… |
| `icon` | `React.ReactNode` | Override the medallion glyph. Defaults to lucide CheckCircle2 (h-6 w-6) inside the success-tinted medallion. |
| `tone` | `"success"` | cva tone seam; only "success" ships today (maps the medallion/halo to the --success token). Left open for a second tint without an API break - you al… |

**Replaces:** The hand-rolled "done" branch in /home/work/work/aisquare-studio-unified/src/auth/ResetPassword.tsx (the `if (done)` block, lines ~132-151): a <LockBadge sage /> medallion + bespoke <h2>/<p> copy + a hand-styled bg-ink "Go to sign in" <button> calling navigate("/login"). SuccessState replaces that success panel (medallion + heading + one CTA + the win-motion). Note: it does NOT replace the surrounding <Shell> (FlickerGrid + branded card) or the invalid-link / form branches - those are separate concerns (the full-page scaffold is AuthShell/AuthCard's job; the form fields are AuthFieldRow/PasswordInput/PasswordRequirements' job).

**Adopt in:** `src/auth/ResetPassword.tsx`, `src/index.css`, `tailwind.config.ts`

**Example**
```tsx
import { SuccessState, Button } from "@aisquare/ui";
import { useNavigate } from "react-router-dom";

function ResetPasswordDone() {
  const navigate = useNavigate();
  return (
    <SuccessState
      title="Password reset successful."
      description="You can now log in with your new password."
      // The component never navigates itself - wire it on the Button:
      action={<Button onClick={() => navigate("/login")}>Go to sign in</Button>}
    />
  );
}
// Big-moment variant (workspace created, invite accepted): add `celebrate`.
// <SuccessState title="You're in." description="Your workspace is ready."
//   action={<Button onClick={() => navigate("/")}>Open workspace</Button>} celebrate />

```

**Notes:** EXPORT NAMES (verified in barrels): `SuccessState` + type `SuccessStateProps` are exported from src/components/index.ts (line 175) and surface via `export * from "./components"` in the main src/index.ts - so import straight from "@aisquare/ui". No rename surprise on SuccessState itself. (Renames DO bite its neighbors: the RHF form wrapper exports as FormProvider/FormFieldController, NOT Form/FormField - those names are taken by the K2 chat block-renderer in ./blocks. Not needed here, but relevant if you also pull the form atoms.)

BLOCKER - missing `--success` token in unified. SuccessState's classes are ALL token-driven: `bg-success/10`, `text-success`, `border-success/30`, `bg-success/5`, `bg-success/20`. The unified app defines `--mint-success` (#4dffb5) but has NO `--success` token and NO `success` key in tailwind.config.ts (grep confirms only `mint-success`). Without it, every `*-success` utility resolves to an invalid color and the medallion/halo/border/wrapper-tint render broken. Before adopting, mirror the library: add to src/index.css `:root` (@layer base) `--success: 142 71% 45%;` and `--success-foreground: 0 0% 100%;` (the exact values in aisquare-ui src/tokens/tokens.template.css), then add to tailwind.config.ts theme.extend.colors a `success: { DEFAULT: "hsl(var(--success) / <alpha-value>)", foreground: "hsl(var(--success-foreground) / <alpha-value>)" }` entry (the `<alpha-value>` channel form is what makes the `/10`, `/5`, `/20`, `/30` opacity modifiers work - same pattern as the existing `destructive`/`muted`/`foreground` entries). The library wires it via tailwind.preset.ts; unified does not use that preset, so add it by hand. (Good news: `--foreground` and `--muted-foreground` already exist in unified, so the `text-foreground` / `text-muted-foreground` used for the title/description resolve fine.)

PEER DEPS - already satisfied in unified: `motion` (^12.42.0) and `canvas-confetti` (^1.9.4) are both present in package.json (canvas-confetti is only needed if you pass `celebrate`; the component lazy-guards it). `@aisquare/ui` ^1.3.0 is already a dep - confirm the published version actually contains SuccessState (it's a Phase-3 component on build PR ui#69; if the installed 1.3.0 predates it, bump the dep).

A11y / behavior: wrapper is `role="status" aria-live="polite"` (success is a status, not an alert), title is a real <h3>. Honors prefers-reduced-motion automatically (renders final state, drops halo loop, celebrate() no-ops). `null` reduced-motion (pre-resolve) is treated as allowed to avoid an animate-then-snap flash.

Adoption scope for ResetPassword.tsx: swap ONLY the `if (done)` success panel - keep the <Shell>, the invalid-link branch, and the form. The component family is stacked: AuthShell (full-page route scaffold) is composed FROM the auth slot atoms in src/primitives (AuthFieldRow, AuthErrorAlert, AuthBadge, PasswordRequirements) + PasswordInput + OAuthProviderButtons + SuccessState (see components/index.ts comment, lines 155-160). So a full auth migration is a multi-component job; SuccessState is just the confirmation leaf. (Aside: the SourceIngestion family from the same barrel ships heavy back-able panels - PasteText/Url/Youtube/Rss/Email/Drive - gated off by default; unrelated here, just don't get pulled into it.)

The `tone` cva currently has a single `success` variant - don't pass other tone values, they don't exist yet.

---

<a id="formprovider"></a>
### FormProvider, FormFieldController, FormItem, FormLabel, FormControl, FormDescription, FormMessage, useFormField, formItemVariants

> The canonical shadcn react-hook-form + zod a11y form anatomy ported into @aisquare/ui - a set of composable parts (provider, Controller wrapper, label/control/description/message) that collapse the per-field id / aria-describedby / aria-invalid / htmlFor wiring into one brand-themed unit, building on the brand Label + Input primitives and the text-destructive token.

_Layer: `component` · Built in [ui#78](https://github.com/AISquare-Studio/aisquare-ui/pull/78)_

**Import**
```ts
import { FormProvider, FormFieldController, FormItem, FormLabel, FormControl, FormDescription, FormMessage, useFormField, formItemVariants, type FormItemProps } from "@aisquare/ui";
```

**Key props**

| Prop | Type | Purpose |
|---|---|---|
| `FormFieldController: control` | `Control<TFieldValues> (RHF)` | RHF form control from useForm(). Passed straight through to Controller. Generic over <TFieldValues, TName> so render-prop field/fieldState are typed … |
| `FormFieldController: name` | `FieldPath<TFieldValues>` | The field name. Published on FormFieldContext so descendant parts (FormLabel/FormControl/FormMessage) resolve this field's state via useFormField. It… |
| `FormFieldController: render` | `({ field, fieldState }) => ReactElement` | RHF Controller render prop. Spread {...field} onto the wrapped control inside FormControl. This is the only required wiring the consumer writes per f… |
| `FormItem: spacing` | `"default" | "tight"` | VariantProps from formItemVariants. default=space-y-2 (roomy, e.g. auth); tight=space-y-1 (dense rows, e.g. settings). Mints a unique React.useId() i… |
| `FormControl: children` | `single control element (Slot)` | Slot-merges id={formItemId}, aria-describedby (description only when valid; description+message when errored) and aria-invalid onto exactly one child… |
| `FormMessage: children` | `ReactNode (optional)` | Validation text. error.message takes precedence over children; renders null when there is no body (no empty node). Fades/slides in via AnimatePresenc… |
| `FormProvider` | `{...useForm() return}` | Donor's Form = FormProvider re-export (a pass-through of RHF FormProvider). Spread the whole useForm() result so descendant parts read state via useF… |

**Replaces:** The hand-rolled, per-screen form plumbing repeated across /home/work/work/aisquare-studio-unified/src/auth/: ForgotPassword.tsx (lines 24-43, 80-103 - useState(email)/useState(err) + validEmail() guard + bespoke `<label htmlFor="fp-email">` / `<input>` / role="alert" error box), AuthScreen.tsx (useState for email/pw/pw2/emailErr/err + validEmail + passwordProblem manual checks, ~lines 80-207), and ResetPassword.tsx (useState pw/pw2/err + passwordProblem/passwordChecks at lines 68-100). None of these wire aria-invalid / aria-describedby / id-to-label association today, and each restates the same error-box and validation logic inline. FormFieldController + the parts + a zod schema replace all of that with typed validation and the a11y contract for free. Note: this anatomy does NOT replace the auth page chrome (stage, branded card, FlickerGrid, logo) - that is AuthShell/AuthCard/AuthBackground's job; FormField only owns the field-level form body.

**Adopt in:** `src/auth/ForgotPassword.tsx`, `src/auth/AuthScreen.tsx`, `src/auth/ResetPassword.tsx`, `src/auth/validation.ts`, `package.json`

**Example**
```tsx
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
  FormProvider,
  FormFieldController,
  FormItem,
  FormLabel,
  FormControl,
  FormDescription,
  FormMessage,
  Input,
  Button,
} from "@aisquare/ui";

const schema = z.object({
  email: z.string().min(1, "Email is required").email("Enter a valid email"),
});
type Values = z.infer<typeof schema>;

export function ForgotPasswordForm({
  // stub the real RTKQ trigger inline so this pastes + runs:
  onSubmit = async (v: Values) => { console.log("send reset to", v.email); },
}: { onSubmit?: (v: Values) => Promise<void> }) {
  const form = useForm<Values>({
    resolver: zodResolver(schema),
    defaultValues: { email: "" },
    mode: "onSubmit",
  });

  return (
    <FormProvider {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} noValidate className="space-y-4">
        <FormFieldController
          control={form.control}
          name="email"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Email</FormLabel>
              <FormControl>
                <Input type="email" placeholder="you@example.com" {...field} />
              </FormControl>
              <FormDescription>We never share it.</FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />
        <Button type="submit" disabled={form.formState.isSubmitting}>
          Send reset link
        </Button>
      </form>
    </FormProvider>
  );
}
```

**Notes:** RENAMED EXPORTS (the #1 gotcha): the donor's `Form` and `FormField` are NOT exported under those names - they collide with the K2 chat blocks barrel (src/components/blocks/Form.tsx). The barrel exports `FormProvider` (= donor Form) and `FormFieldController` (= donor FormField). FormItem/FormLabel/FormControl/FormDescription/FormMessage/useFormField/formItemVariants keep their names. If you want the donor names locally, alias on import: `import { FormProvider as Form, FormFieldController as FormField } from "@aisquare/ui"`. Do NOT import from "@aisquare/ui/stock" - these are composed components, not stock shadcn.

PEER DEPS (must install - verified the unified app has @aisquare/ui ^1.3.0 but NOT these): `react-hook-form` (>=7), `@hookform/resolvers` (>=3, for zodResolver), and `zod` (>=3). All three are OPTIONAL peers externalized from the bundle, so the consumer shares ONE RHF context and the lib never ships a second copy - but that means nothing renders until you `npm i react-hook-form @hookform/resolvers zod`.

REQUIRED SEAM / wiring contract: (1) FormControl must wrap exactly ONE control element and you must spread `{...field}` from the render prop onto it - that is how value/onChange/onBlur/ref connect. (2) useFormField throws "should be used within <FormField>" if any part renders outside a FormFieldController - keep the FormItem/parts inside the render prop. (3) The error styling is automatic only if the wrapped control honors `aria-invalid` - the brand `Input`/`Textarea`/`PasswordInput` do (aria-invalid:border-destructive); a raw `<input>` will get the aria attr but won't morph its border.

STACKING (per the barrel header at src/components/index.ts:155-160): the full-page auth scaffold is layered - AuthShell composes AuthCard + AuthBackground + the auth slot atoms in src/primitives (AuthFieldRow, AuthErrorAlert, AuthBadge, PasswordRequirements) + PasswordInput + OAuthProviderButtons + SuccessState. FormField is the field-body layer that drops INSIDE that card; for a full auth screen rebuild you typically adopt AuthShell for the chrome and FormField for the validated fields, not one instead of the other. (Separately, the SourceIngestion family ships heavy panels - Drive/Rss/Email/Youtube/Url/PasteText - that are gated off by default; unrelated to FormField but a known "heavy, opt-in" pattern in this barrel.)

OTHER: errors route through the `text-destructive` token (never a hex) and animate in/out, reduced-motion aware (instant when reduced). FormMessage returns null when there's no error AND no children - so no empty error node in the idle state. zod messages ARE the displayed error text (error.message wins over children), so write user-facing copy in the schema. This app is Tailwind v3 with Preflight OFF and the dual native/shadcn token system already resolves text-destructive/text-muted-foreground on-brand - no token work needed on intake.

---

<a id="workspacetransitionoverlay"></a>
### WorkspaceTransitionOverlay

> A full-bleed blocking overlay for must-finish async transitions (canonical case: switching workspaces) that runs a spinner -> success-check -> auto-dismiss phase machine; presentational only (props in, onComplete out), promoted and de-app-coupled from unified's WorkspaceTransitionToast and composing the library's Avatar + Spinner.

_Layer: `component` · Built in [ui#77](https://github.com/AISquare-Studio/aisquare-ui/pull/77)_

**Import**
```ts
import { WorkspaceTransitionOverlay, type WorkspaceTransitionOverlayProps, type WorkspaceTransitionTimings } from "@aisquare/ui";
```

**Key props**

| Prop | Type | Purpose |
|---|---|---|
| `open` | `boolean` | Controls visibility (renamed from the donor's `visible`; matches LogoutLoader's `open`). |
| `loading` | `boolean` | Whether the async work is still in flight. The phase machine flips spinner -> success once this goes false. |
| `onComplete` | `() => void` | REQUIRED seam. Fires once when the overlay should clear (after the ~1.5s success dwell, or immediately on the 10s hang fallback). Consumer unmounts/c… |
| `name` | `string` | Target name. Drives default copy, the Avatar initials fallback, and re-arms the machine if it changes mid-flight. |
| `type` | `"personal" | "team" | string` | Workspace kind (default "team"). Only "personal" is special-cased; drives the default pill + heading/sub copy. |
| `avatar` | `string | null` | Avatar image URL. Wins over `icon` and initials. |
| `icon` | `React.ReactNode` | Fallback figure in the tile when no `avatar` (e.g. the app's PersonalGlyph/TeamGlyph). The library imports NO app glyphs; you inject them here. Falls… |
| `timings` | `WorkspaceTransitionTimings` | Optional override of phase ms: { successDelay=100, dismiss=1500, fallback=10000 }. Donor hardcoded these exact values. |

**Replaces:** The entire presentational body of unified's /home/work/work/aisquare-studio-unified/src/workspace/WorkspaceTransitionToast.tsx (default-exported WorkspaceTransitionToast): the createPortal-to-document.body scrim+card, the hand-rolled tile/badge/copy/pill markup, the inline `usePhasedTransition`-equivalent effect machine (the 100/1500/10000ms timers are byte-identical to the library's defaults), and its app-glyph import (PersonalGlyph/TeamGlyph from ./workspaceGlyphs) plus the wsTransFade/wsTransPop/wsTransSpin @keyframes in index.css. The Redux host /home/work/work/aisquare-studio-unified/src/workspace/WorkspaceTransitionHost.tsx STAYS as the seam and just maps the workspaceUiSlice `transition` fields onto the new props.

**Adopt in:** `src/workspace/WorkspaceTransitionHost.tsx`, `src/workspace/WorkspaceTransitionToast.tsx`, `src/index.css`

**Example**
```tsx
// In WorkspaceTransitionHost.tsx - the Redux host stays, the toast body is replaced by the library overlay.
import { WorkspaceTransitionOverlay } from "@aisquare/ui";
import { useAppDispatch, useAppSelector } from "../store/hooks";
import { transitionCleared, selectWorkspaceTransition } from "../store/workspaceUiSlice";
import { PersonalGlyph, TeamGlyph } from "./workspaceGlyphs";

export default function WorkspaceTransitionHost() {
  const dispatch = useAppDispatch();
  const transition = useAppSelector(selectWorkspaceTransition);
  return (
    <WorkspaceTransitionOverlay
      open={!!transition}
      loading={transition?.loading ?? false}
      name={transition?.name ?? ""}
      type={transition?.type ?? "team"}
      avatar={transition?.avatar}
      icon={transition?.type === "personal" ? <PersonalGlyph /> : <TeamGlyph />}
      onComplete={() => dispatch(transitionCleared())}
    />
  );
}
```

**Notes:** No export rename here: the barrel exports the symbol verbatim as `WorkspaceTransitionOverlay` (src/components/index.ts L177-181, re-exported via `export * from "./components"` in src/index.ts), so import it by that name from "@aisquare/ui" (unlike the RHF FormField, which the barrel renames to FormProvider/FormFieldController because Form/FormField are claimed by the chat-blocks renderer). Prop rename to watch: the donor's `visible` is now `open`. REQUIRED seam: `onComplete` - without it the overlay never clears and the hang fallback can't fire; keep dispatching transitionCleared() from the existing host. Behavior parity is exact (same phase machine, same 100/1500/10000ms defaults) so no Redux/slice changes are needed. Two render differences to expect: (1) the library does NOT createPortal to document.body - it renders `fixed inset-0 z-[9999]` inline, so just mount the host high in the tree (App) as today; it's render-cheap (returns null/AnimatePresence-empty when closed); the old null-guard `if (!transition) return null` can be dropped since the component handles `open={false}` itself. (2) The app glyphs are NOT imported by the library - pass them through the `icon` slot (snippet does this); leave them out and it falls back to Avatar initials of `name`. On adoption, also delete the now-dead WorkspaceTransitionToast.tsx and the wsTransFade/wsTransPop/wsTransSpin @keyframes from src/index.css (this component animates via motion/react, not CSS keyframes). Tokens: the overlay uses shadcn-alias tokens (bg-card, border-border, bg-primary/text-primary-foreground, bg-secondary, text-muted-foreground, bg-success/text-success-foreground, hsl(var(--primary)/0.42)). Unified's :root defines the shadcn aliases, but verify a `--success`/`--success-foreground` pair exists (donor used `forest` for the check badge) - add it if missing or the success check will be unstyled. Peer deps the library already bundles: `motion` (motion/react) and `lucide-react`; this component does NOT pull in react-hook-form/zod (that peer-dep caveat belongs to the FormField/AuthShell family, not here). Stacking context: this overlay composes Avatar + Spinner (and is the sibling of LogoutLoader sharing the same fixed/z-[9999]/AnimatePresence shell + role=status aria-live=polite a11y posture) - adopt those primitives together. Variants available but optional: `scrim` ("navy" default == donor's rgba(10,37,64,.42) | "ink" denser), `size` ("default" | "sm"), `animate` (default true; false = static escape hatch), plus copy overrides title/description/pillLabel (pass pillLabel={null} to hide the pill) and loadingLabel/successLabel a11y strings.

---

<a id="memberpicker"></a>
### MemberPicker, MemberOption, RoleOption

> A searchable, keyboard-accessible multi-select for picking workspace members (co-creators / collaborators / share targets), built on cmdk inside the library Popover with chosen members surfaced as an AvatarGroup plus removable chips; fully controlled and data-agnostic (no service import).

_Layer: `component` · Built in [ui#76](https://github.com/AISquare-Studio/aisquare-ui/pull/76)_

**Import**
```ts
import { MemberPicker, type MemberOption, type RoleOption } from "@aisquare/ui";
```

**Key props**

| Prop | Type | Purpose |
|---|---|---|
| `members` | `MemberOption[]` | The full candidate list (the workspace's members). Data-agnostic; you map your DTO into MemberOption ({id,name,email,username?,role?,avatar?|avatarUr… |
| `value` | `MemberOption[]` | Currently-selected members (controlled). Dedupe + add/remove all key off the LOWERCASED email, not id. |
| `onChange` | `(next: MemberOption[]) => void` | Receives the next selection on every add/remove. The single required write seam. |
| `onInvite` | `(email: string, role: string) => void | Promise<void>` | Commit for inviting a brand-new email via the inline invite row. If it returns a promise it's awaited and rolled back on throw; synchronous otherwise… |
| `state` | `"idle" | "loading" | "error" | "ok"` | List lifecycle the caller drives from its query (default "ok"). loading => 3 skeleton rows; error => message + Retry; ok => rows/empty. |
| `onRetry` | `() => void` | Retry handler shown in the error state (wire to your query's refetch). |
| `canManage` | `boolean` | When false renders a "Limited access" lock panel instead of the picker (default true). |
| `onAdd` | `(member: MemberOption) => Promise<void>` | Optional async commit for adding an existing member; awaited + optimistically rolled back on throw. Without it, add is synchronous (just calls onChan… |

**Replaces:** The entire hand-built /home/work/work/aisquare-studio-unified/src/screens/CoCreatorPicker.tsx (387 lines): its custom RoleDropdown (incl. the capture-phase `mousedown`+deferred-bind outside-click workaround needed because the modal dialog stops mousedown in the bubble phase - Popover owns focus+dismiss now), the AddedButton hover-swap pill, the manual search-box + substring filter (cmdk does this + full keyboard nav + listbox/option a11y), the loading-skeleton / error+Retry / empty-vs-no-match states, and the ROLE_BADGE_BASE/ROLE_BADGE_TINT raw-rgba role-badge maps (library uses tinted brand-token Badges). The RTKQ fetch (useGetMembershipsListQuery) and the Membership->row mapping stay caller-side. Consumed once at /home/work/work/aisquare-studio-unified/src/screens/CreateStudioModal.tsx:492 (gated on isTeamWorkspace).

**Adopt in:** `src/screens/CreateStudioModal.tsx`, `src/screens/CoCreatorPicker.tsx`

**Example**
```tsx
// CoCreatorPicker.tsx becomes a thin adapter: keep the RTKQ fetch + the
// Membership->MemberOption mapping; let MemberPicker own search/keyboard/a11y/states.
import { MemberPicker, type MemberOption } from "@aisquare/ui";
import { useGetMembershipsListQuery } from "../store/membershipsApi";
import type { Membership } from "../services/membershipsService";

export interface CoCreator { email: string; name: string; role: string; id?: string | number; }

const toOption = (m: Membership): MemberOption => ({
  id: m.id ?? m.member ?? m.user_email ?? "",
  name: m.user_fullname || m.full_name || m.user_username || m.user_email || "",
  email: m.user_email || m.email || "",
  username: m.user_username || m.username,
  role: m.current_role || m.roles_list?.[0] || m.role || "",
  avatarUrl: m.profile_picture ?? undefined,
});

export default function CoCreatorPicker({ value, onChange }: { value: CoCreator[]; onChange: (n: CoCreator[]) => void }) {
  const { data, isError, isSuccess, isLoading, isFetching, refetch } =
    useGetMembershipsListQuery({ page_size: 100 });
  const members = (data?.results ?? []).map(toOption);
  const state = isError ? "error" : isSuccess ? "ok" : (isLoading || isFetching) ? "loading" : "idle";

  // MemberPicker speaks MemberOption[]; bridge to/from the CoCreator shape.
  const selected: MemberOption[] = value.map((c) => ({ id: c.id ?? c.email, name: c.name, email: c.email, role: c.role }));
  return (
    <MemberPicker
      members={members}
      value={selected}
      onChange={(next) => onChange(next.map((m) => ({ email: m.email, name: m.name, role: m.role ?? "editor", id: m.id })))}
      state={state}
      onRetry={() => { void refetch(); }}
      onInvite={(email, role) => { /* invite happens via the create-then-addCoCreator flow; local select only */ void email; void role; }}
    />
  );
}
```

**Notes:** EXPORT IS CLEAN - no rename trap here: `MemberPicker`, `MemberOption`, `RoleOption`, `MemberPickerProps` are exported under their own names from src/components/index.ts (lines 49-54) and flow through the main barrel via `export * from "./components"`, so import straight from "@aisquare/ui". (Contrast the RHF wrapper, where donor Form/FormField are re-exported as FormProvider/FormFieldController because the chat-block `./blocks` barrel owns Form/FormField - not relevant to MemberPicker.) IDENTITY IS LOWERCASED EMAIL, not id: a member with no/blank email can never be added and the same email can't be added twice; ensure your mapping always fills `email`. CONTROLLED ONLY: members/value/onChange are required; nothing fetches internally (the donor's useGetMembershipsListQuery + Membership mapping stay in your adapter). SEARCH SEAM: by default cmdk filters client-side over a name+username+email+role haystack; if you pass `onSearch` the component turns cmdk's own filter OFF (shouldFilter=false) and renders `members` as-is, so you must do the filtering server-side or rows won't narrow. ROLES: invite-role vocab defaults to Editor/Admin (`roles` prop to change); known role keys owner/admin/editor/viewer get tinted brand-token badges (warning/info/success/secondary), unknown roles fall back to a neutral "Member" badge; `normalizeRole` maps a raw codename onto the committed set (default: known-or-editor). PEER DEPS: pulls in cmdk (Command), motion/react, lucide-react, class-variance-authority, and Radix Popover/Select - all already transitive deps of @aisquare/ui, nothing extra to install. ANIMATION: every motion is gated on useReducedMotion() with a static fallback (Popover collapses to 0ms), so reduced-motion users keep state signals. ICONS: library uses lucide-react; the donor used react-icons/lu - do NOT carry react-icons in. canManage=false short-circuits to a lock panel (use it for non-owner/admin viewers). Browser-verify inside the CreateStudioModal: the donor's whole reason for the capture-phase mousedown hack was the modal swallowing bubble-phase mousedown; Popover should now dismiss correctly, but confirm in Chrome since build-green won't catch a focus/dismiss regression inside the dialog.

---

<a id="colorpicker"></a>
### ColorPicker, ColorPickerPopover, COLOR_PICKER_PRESETS

> One accessible HSV color picker (saturation square + hue strip via react-colorful, branded hex field, optional eyedropper + preset row, plus a controlled ColorPicker.Popover variant) that consolidates the three hand-rolled drag-loop pickers, riding on the canonical colorUtils hex/rgb/hsv math.

_Layer: `component` · Built in [ui#79](https://github.com/AISquare-Studio/aisquare-ui/pull/79)_

**Import**
```ts
import { ColorPicker, COLOR_PICKER_PRESETS, hexToHSV, hsvToHex, normalizeHex, readableTextColor } from "@aisquare/ui";
```

**Key props**

| Prop | Type | Purpose |
|---|---|---|
| `value / defaultValue` | `string (#rrggbb)` | Controlled (value, pair with onChange) vs uncontrolled (defaultValue, seeds internal state). Default falls back to brand gold #daa520. |
| `onChange` | `(hex: string) => void` | Fires with the next #rrggbb on every change (drag, hex field, preset, eyedropper). Required to read the value in controlled mode. |
| `presets` | `readonly string[]` | Swatch row under the picker. Defaults to COLOR_PICKER_PRESETS (the 7 MoodLighting colors). Pass [] to hide the row. |
| `showEyedropper` | `boolean | undefined` | undefined = auto (shown only where the native EyeDropper API exists); false forces it off. No callback needed - handled internally via useEyeDropper. |
| `size` | `"sm" | "md"` | Saturation-square size via --cp-square (sm=140px, md=180px). Default md. |
| `value + onChange + children (ColorPicker.Popover)` | `string + (hex)=>void + ReactNode` | Popover variant is controlled-ONLY (value/onChange required, no defaultValue); children is the trigger element (wrapped in Radix PopoverTrigger asChi… |

**Replaces:** The hand-rolled MoodLightingPalette (default export) in /home/work/work/aisquare-studio-unified/src/shell/MoodLighting.tsx - a 238-line HSV picker with its own window mousemove/mouseup drag loop (no touch/keyboard/a11y), manual hex regex (e.target.value.replace(/[^0-9a-fA-F]/g,"").slice(0,6)), an inline EyeDropper ctor, and a 7-swatch preset row. It already imports hexToHSV/hsvToHex from the unified src/lib/colorUtils.ts, which is the exact donor colorUtils was ported from, so the math is identical. The picker body (canvas + hue + hex + eyedropper + presets) maps 1:1 onto <ColorPicker>; the surrounding chrome it ships (header bar with Back + Reset-to-default buttons and the 40px swatch preview, driven by the onBack prop) is NOT part of <ColorPicker> and must be kept around it by the adopter.

**Adopt in:** `src/shell/MoodLighting.tsx`

**Example**
```tsx
import { useState } from "react";
import { ColorPicker, COLOR_PICKER_PRESETS } from "@aisquare/ui";

// Uncontrolled, with presets + auto eyedropper (the MoodLighting palette body):
function MoodLightingBody({ onChange }: { onChange?: (hex: string) => void }) {
  return (
    <ColorPicker
      defaultValue="#daa520"
      onChange={onChange}
      presets={COLOR_PICKER_PRESETS}
      size="md"
    />
  );
}

// Controlled, anchored to a trigger via the Popover variant:
function ColorField() {
  const [color, setColor] = useState("#daa520");
  return (
    <ColorPicker.Popover value={color} onChange={setColor} align="start" side="bottom">
      <button type="button" className="size-8 rounded-full border border-hairline" style={{ background: color }} />
    </ColorPicker.Popover>
  );
}
```

**Notes:** Exports verified in the real barrels - import from "@aisquare/ui" (NOT a subpath): ColorPicker, ColorPickerPopover, COLOR_PICKER_PRESETS + types ColorPickerProps/ColorPickerPopoverProps live in src/components/index.ts; the colorUtils functions (hexToRgb, rgbToHex, hexToHSV, hsvToHex, normalizeHex, readableTextColor) are exported from the MAIN barrel src/index.ts, not components. ColorPicker.Popover is the SAME component as the named ColorPickerPopover export, attached as a static member - either call shape works.

SCOPE / what does NOT come with it: <ColorPicker> is JUST the picker body (saturation square, hue strip, branded hex field, optional eyedropper, preset row). MoodLighting's header bar (Back arrow + Reset-to-default) and the 40px swatch preview are app chrome that <ColorPicker> does NOT render - the adopter keeps those around it, and the onBack prop has no equivalent. Migration is: drop the manual HSV state + drag effect + onHexInput + eyedropper, render <ColorPicker value/defaultValue onChange/>, keep the surrounding header.

Controlled-vs-uncontrolled asymmetry: <ColorPicker> supports both (value OR defaultValue). <ColorPicker.Popover> is controlled-ONLY - value AND onChange are REQUIRED, there is no defaultValue; children is the single trigger element (Radix asChild - pass exactly one element). Popover-only extras: align (default 'start'), side (default 'bottom'), className (on the content panel).

showEyedropper default is auto: the button renders only when the native EyeDropper API is supported (supported stays null during SSR/first paint so it never flashes); explicit false forces it off. No callback to wire - useEyeDropper handles open() internally.

Peer deps the build PR pulls in (must resolve in the consumer): react-colorful (the HexColorPicker/HexColorInput engine), motion (motion/react - preset ring + popover spring), lucide-react (Pipette icon). ColorPicker.Popover also transitively depends on the brand Popover (@radix-ui popover) and the lib's motion presets (springs.gentle / transitions.surface). It is light-theme only - all chrome resolves to shadcn-alias brand tokens (--card/--popover/--border/--muted/--accent/--ring), so unified's existing :root alias layer is required (it's already present per CLAUDE.md); do not paste any generated :root token block.

colorUtils null-handling contract: hexToRgb and normalizeHex return null on a malformed hex (callers MUST handle null); hexToHSV returns {h:0,s:0,v:0} (never NaN). readableTextColor returns "#000000"|"#ffffff" via WCAG luminance - handy if you build a swatch with an in-contrast check. Hex output is always lowercase 6-digit #-prefixed. These are the canonical copies; after adopting, delete unified's local src/lib/colorUtils.ts and re-point its importers (MoodLighting imports hexToHSV/hsvToHex from there today) at "@aisquare/ui".

react-colorful is re-skinned via a scoped <style> (ColorPickerSkin) keyed to [data-slot="color-picker"], so styling won't bleed across instances and it's SSR-safe.

---

<a id="aikotour"></a>
### AikoTour, AikoSpotlight, useAikoTour

> A multi-step product-tour engine (spotlight coach-marks + Radix Popover tooltips) built ON the lib's existing Aiko anchor layer (useAikoTarget + the AikoSurfaces virtualRef bridge), not on a third-party tour library.

_Layer: `component` · Built in [ui#74](https://github.com/AISquare-Studio/aisquare-ui/pull/74)_

**Import**
```ts
import { AikoTour, AikoAnchor, useAikoTour, type TourStep } from "@aisquare/ui";
```

**Key props**

| Prop | Type | Purpose |
|---|---|---|
| `steps` | `TourStep[]` | REQUIRED. Ordered steps; order is the nav order. Each: { anchorId: string, title: ReactNode, body?/bullets?/grid? (grid>bullets>body wins), side?: 't… |
| `storageKey` | `string` | localStorage key for the one-time 'seen' flag (uncontrolled open only). Set it so a first-run tour does not re-run after complete/skip; omit to run e… |
| `onComplete / onSkip` | `() => void` | Fire on finishing the last step (Done) / on early dismiss (step-0 X or Esc). Both also mark the tour seen. Wire to your onboarding flag (e.g. markOnb… |
| `open / onOpenChange (+ index / onIndexChange)` | `boolean / (b)=>void  (number / (n)=>void)` | Optional fully-controlled mode. defaultOpen defaults to true (a first-run tour opens on mount); defaultIndex defaults to 0. Use the controlled pair t… |
| `scrollOffset` | `number` | Px top clearance when scrolling a target into view. Default 120 (header clearance). Per-step scrollOffset overrides it. |
| `overlayOpacity / dismissOnStepZeroOnly / queueTimeoutMs` | `number / boolean / number` | Backdrop dim 0..1 (default 0.75); show the X only on step 0 (default true, set false for X on every step); ms a 'queue' step waits for its anchor bef… |
| `nextLabel / doneLabel / backLabel` | `string` | Button copy overrides. Defaults 'Next' / 'Done' / 'Back'. |

**Replaces:** No current consumer in the unified app. This is the reusable engine for a future in-app walkthrough / first-run coach-mark tour (Home composer + CREATE/CONNECT/GOVERN tiles + workspace switcher were the donor's highlighted surfaces). It ports the fe-react donor `WalkthroughTooltipSpotlight` (box-shadow cutout, scroll-into-view-then-lock, dashed arrow, progress dots, Back/Next/Done + step-0 dismiss), decoupled from that donor's app knowledge (no hardcoded #0A2540, no explore-studios/sidebar special-cases, no raw querySelector, no baked-in icon map). When unified adds onboarding coach-marks, build them on this instead of hand-rolling a tour.

**Adopt in:** `src/components/onboarding/ (new in-app walkthrough host - no existing file)`, `src/pages/Home.tsx (wrap the target surfaces in <AikoAnchor id> and mount <AikoTour>)`, `src/store/onboardingApi.ts (the onboarding flag drives onComplete/onSkip if not using storageKey)`

**Example**
```tsx
import { AikoTour, AikoAnchor, type TourStep } from "@aisquare/ui";
import { Sparkles, Workflow } from "lucide-react";

const STEPS: TourStep[] = [
  {
    anchorId: "home.composer",
    title: "Start in the composer",
    body: "Tell Aiko what you want to make and it drafts the studio for you.",
    side: "bottom",
  },
  {
    anchorId: "home.create",
    title: "Create, Connect, Govern",
    side: "bottom",
    grid: [
      { icon: <Sparkles aria-hidden />, heading: "Create", body: "Spin up a studio." },
      { icon: <Workflow aria-hidden />, heading: "Connect", body: "Wire your sources." },
    ],
  },
];

export function HomeTour() {
  return (
    <>
      {/* Mark the live targets the lib's normal way. */}
      <AikoAnchor id="home.composer">{/* composer element */}</AikoAnchor>
      <AikoAnchor id="home.create">{/* create tile */}</AikoAnchor>

      {/* storageKey => one-time, auto-opens on first mount, won't re-run after complete/skip. */}
      <AikoTour
        steps={STEPS}
        storageKey="home-first-run"
        onComplete={() => {/* markOnboarded() */}}
        onSkip={() => {/* markOnboarded() */}}
      />
    </>
  );
}
```

**Notes:** REQUIRED SEAM - anchors, not selectors: the tour resolves each step's anchorId via useAikoTarget against a <AikoAnchor id> (also barrel-exported from @aisquare/ui) or a raw data-aiko-anchor attribute. No anchors in the DOM = the spotlight has nothing to pin to and the step is unreachable; the onUnreachable policy then waits (queue, default, bounded by queueTimeoutMs=30s) or skips. So adopting AikoTour means also wrapping the target surfaces in AikoAnchor - it is stacked on the Aiko anchor layer, not standalone. Renders null while closed, while steps is empty, or while the current queue step's anchor is still unreachable. EXTRA EXPORTS in this same module: useAikoTour (a controller hook that owns the open + one-time-seen lifecycle via useLocalStorage and hands you tourProps to spread: const tour = useAikoTour({ storageKey:'x' }); <AikoTour steps={STEPS} {...tour.tourProps} /> - plus tour.reset()+tour.start() for a 'Replay tour' button), and AikoSpotlight (the single-step renderer, exported standalone for driving one coach-mark without the orchestrator). NAMING: the renderer is AikoSpotlight, NOT bare Spotlight - that name is deliberately avoided to not collide with the unrelated SpotlightCard component. PEER DEP: motion (motion/react, >=12.0.0) is an OPTIONAL peerDependency of @aisquare/ui - this component imports it at module load, so the unified app must have `motion` installed or the import throws. (@radix-ui/react-popover + lucide-react are regular deps of the lib, already present.) This component does NOT need react-hook-form/zod - those are FormField/AuthShell concerns, unrelated here. STYLING: light-theme tokens only (bg-popover/text-popover-foreground/bg-primary/border-border etc.) - all resolve to brand via the unified shadcn alias layer, no token work; z-index is hardcoded high (spotlight 9998, tooltip 9999). MOTION: every animation is gated on useReducedMotion() with a static fallback (reduced motion also switches scroll to behavior:'auto', which exercises the donor's 1s scroll-lock fallback). BEHAVIOR: while a step is active the engine LOCKS page scroll (sets body/scroll-container overflow:hidden after scroll settles) and stamps a data-aiko-tour-active attribute on the target (you may style it); Esc and outside-interaction both count as skip. The default X shows only on step 0 (dismissOnStepZeroOnly).

---

<a id="setupchecklist"></a>
### SetupChecklist

> A collapsible onboarding checklist card (animated Radix Progress bar + motion rows + two-tap dismiss guard + celebrate-on-100%), built on the library's own Progress/Collapsible/Tooltip primitives, consolidating Creator-Studio/FE-React's hand-built TeamSetupChecklist + StarterChecklist into one configurable component.

_Layer: `component` · Built in [ui#82](https://github.com/AISquare-Studio/aisquare-ui/pull/82)_

**Import**
```ts
import { SetupChecklist, type SetupChecklistTask } from "@aisquare/ui";
```

**Key props**

| Prop | Type | Purpose |
|---|---|---|
| `tasks` | `SetupChecklistTask[]` | REQUIRED. The rows, rendered in given order (sort upstream). Each task is { id: string; label: string; completed: boolean; href?: string; description… |
| `linkComponent` | `React.ElementType` | Your router Link, used to wrap incomplete rows that carry an href. Receives { to, href, className, children } so react-router (to) and anchor (href) … |
| `onDismiss` | `() => void` | Fired when dismiss is confirmed. OMIT to hide the dismiss button entirely. By default needs two taps (confirmDismiss). |
| `percentComplete` | `number (0-100)` | Override the derived completed/total percent with a server value (Starter's checklist_completion parity). Row checkmarks still come from each task.co… |
| `title / description` | `React.ReactNode` | title renders an <h2> above the card (omit for a heading-less embed); description is the muted sub-line inside the header. |
| `size` | `"compact" | "comfortable"` | CVA variant. compact = tighter padding for sidebars/dense surfaces; comfortable (default) matches the donor dashboard cards. |
| `renderRow` | `(ctx: { task, defaultContent }) => ReactNode` | Full row escape hatch; return any wrapper around defaultContent. OVERRIDES linkComponent. Also: confirmDismiss(true), dismissLabel("Dismiss Checklist… |

**Replaces:** A future team-setup surface in the unified app: there is NO SetupChecklist or any onboarding-checklist card in /home/work/work/aisquare-studio-unified/src today (grep for SetupChecklist/setup-checklist returns nothing; the only onboarding code is the multi-step Onboarding flow under src/screens/onboarding/ + src/store/onboardingApi.ts, which is a different concern). Per the component header it consolidates the two upstream copy-paste forks it is meant to replace: Creator-Studio/FE-React's hand-built `TeamSetupChecklist` and `StarterChecklist` (navy-to-blue gradient + text-gray washes, re-skinned here to brand tokens). When the unified team-setup card is built, render this instead of hand-rolling a progress bar + row list + dismiss.

**Adopt in:** `src/store/onboardingApi.ts (or a new membershipsApi/team-setup endpoint) to source the per-task completed flags or a server checklist_completion percent`, `the future team-setup screen component that will host the card (e.g. a new src/screens/onboarding/ or src/screens/team/ surface) - no such file exists yet`, `tailwind.config.ts - MUST add @aisquare/ui's tailwind.preset to presets so ease-smooth-out / animate-shimmer / animate-accordion-up|down resolve (the shimmer sweep + collapse animation no-op otherwise)`

**Example**
```tsx
import { SetupChecklist, type SetupChecklistTask } from "@aisquare/ui";
import { Link } from "react-router-dom"; // satisfies linkComponent's { to, ... } contract

const tasks: SetupChecklistTask[] = [
  { id: "profile", label: "Complete your profile", completed: true },
  { id: "studio", label: "Create your first Studio", completed: true },
  { id: "invite", label: "Invite a teammate", completed: false, href: "/team/invite" },
  {
    id: "publish",
    label: "Publish an experience",
    completed: false,
    href: "/studios/new",
    description: "Ship something your audience can open.",
  },
];

export function TeamSetupCard() {
  return (
    <SetupChecklist
      title="Jumpstart Your AISquare Journey"
      description="Complete this checklist to unlock the full AISquare experience"
      tasks={tasks}
      linkComponent={Link}          // incomplete rows with an href navigate via this
      onDismiss={() => {/* persist dismissal, e.g. an onboardingApi mutation */}}
    />
  );
}
```

**Notes:** EXPORT: this component keeps its own name - `SetupChecklist` is a clean named export from "@aisquare/ui" (verified src/components/index.ts:168 -> src/index.ts:166), plus setupChecklistVariants + types SetupChecklistProps/SetupChecklistTask/SetupChecklistRowContext. (The Form/FormField rename caveat in the task brief applies to the RHF form wrapper, NOT to this component - no alias needed here.)

REQUIRED SEAM - linkComponent: the library imports NO router. Incomplete rows that have an href only become navigable if you inject linkComponent; it is called as <LinkComp to={href} href={href} className=...>. react-router-dom v7's Link (already a dep, ^7.18.0, used in src/auth/AuthScreen.tsx) takes `to` and works as-is. Without linkComponent, href rows render as a plain non-navigating div. renderRow overrides linkComponent entirely.

TAILWIND PRESET IS A HARD REQUIREMENT: the card uses ease-smooth-out, animate-shimmer, and animate-accordion-up/down, which are defined in @aisquare/ui's tailwind.preset.ts (not in the unified config). The unified tailwind.config.ts must include that preset or the progress shimmer + collapse/expand animation silently no-op (build stays green - browser-verify). The shimmer also reads hsl(var(--primary-foreground)) - fine in this app, primary==ink.

celebrate / confetti: celebrateOnComplete (default true) fires celebrate({ intensity }) once on the transition into 100% (not on mount of an already-complete list). celebrate() is internal, SSR-safe, and no-ops under prefers-reduced-motion. canvas-confetti is an OPTIONAL peer dep - you do NOT need to install it just to use SetupChecklist (the burst is best-effort); pass celebrateOnComplete={false} to opt out. Note celebrate + CelebrateIntensity are intentionally NOT re-exported from the main barrel (src/index.ts:56-60), so don't try to import them.

BEHAVIORS to know: (1) completed rows show a filled circle + strike-through and are non-interactive even if they have an href. (2) On reaching 100% the list AUTO-COLLAPSES once (still re-openable); pass defaultCollapsed / track via onCollapseChange. (3) Dismiss defaults to a two-tap guard - first click shows "Click again to confirm", second fires onDismiss; set confirmDismiss={false} for one-click. (4) Omitting onDismiss hides the dismiss button. (5) tasks=[] returns null. (6) percentComplete only drives the bar + the 100% trigger; the "N of M complete" text and checkmarks always come from task.completed flags, so a server percent can disagree with the visible count.

PEER DEPS pulled in transitively: motion/react (AnimatePresence/motion), lucide-react (Check, ChevronDown), class-variance-authority, plus the library's Radix-backed Progress/Collapsible/Tooltip - all already part of @aisquare/ui's surface; no new direct installs for the adopter beyond consuming the library + its preset.

---

<a id="useprogressivepolling"></a>
### useProgressivePolling

> A headless, visibility-aware progressive-backoff polling engine (1s,2s,3s,5s,8s,10s then 15s forever) that drives status morphs in a consumer, composed on the library's own useInterval + useDocumentVisibility; it renders nothing.

_Layer: `hook` · Built in [ui#67](https://github.com/AISquare-Studio/aisquare-ui/pull/67)_

**Import**
```ts
import { useProgressivePolling, type UseProgressivePollingOptions, type UseProgressivePollingReturn } from "@aisquare/ui";
```

**Key props**

| Prop | Type | Purpose |
|---|---|---|
| `pollFn` | `() => void` | REQUIRED. The action run on each tick (an RTK Query refetch, a service call, a status GET). Captured in a ref by the underlying useInterval, so an in… |
| `isActive` | `boolean` | REQUIRED. Master gate. When false the timer is cleared and the schedule resets to step 0 (re-arms from the first/fast step next time it flips true). |
| `shouldStopPolling` | `() => boolean (optional)` | Terminal predicate, re-checked before AND at each tick. Returning true stops polling and resets the schedule. Read through a ref, so it need not be a… |
| `maxDurationMs` | `number (optional)` | Overall wall-clock cap. Once elapsed since polling (re)started, the timer stops and onTimeout fires once. Deliberately NOT extended by hidden-tab pau… |
| `onTimeout` | `() => void (optional)` | Fires once when maxDurationMs elapses before a terminal state. Typically marks the item 'still processing, try again'. |
| `resetDependencies` | `readonly unknown[] (optional, default [])` | Changing any entry auto-restarts the schedule from step 0 (fast feedback again). The array IS spread as the effect dep list, so pass filters/page/pag… |
| `pauseWhenHidden` | `boolean (optional, default true)` | Pause while the document is hidden (backgrounded tab), resuming from the same step when visible. Pass false only for the rare always-on case. schedul… |

**Replaces:** The hand-rolled fixed polling loop inside attachFile in /home/work/work/aisquare-studio-unified/src/chat/useAikoChat.ts (lines ~162-180): a `for (let i = 0; i < 40; i++) { await sleep(1500); ...getChatUploadStatus() }` loop that polls upload text-extraction status at a flat 1.5s with a hard 40-iteration (~60s) cap, hand-checks `attachmentsRef` membership as its stop condition, and emits the 'Still processing, try again' message on cap. The hook gives this progressive backoff (so a slow extraction does not hammer the BE), tab-visibility pausing, and a clean maxDurationMs/onTimeout cap.

**Adopt in:** `src/chat/useAikoChat.ts`

**Example**
```tsx
// Adopting in a component that polls one upload's extraction status.
// (The hook is headless; you own the status state + the poll call.)
import { useState } from "react";
import { useProgressivePolling } from "@aisquare/ui";
import { getChatUploadStatus } from "../services/aikoUploadService";

function useUploadStatus(documentId: number | null, workspaceId: string) {
  const [status, setStatus] = useState<"indexing" | "ready" | "error">("indexing");

  const { resetPollingSchedule, currentPollIndex } = useProgressivePolling({
    isActive: documentId != null && status === "indexing",
    pollFn: () => {
      // stub the real call inline; map result -> status
      void getChatUploadStatus(documentId!, { workspaceId })
        .then((st) => {
          if (st.textReady) setStatus("ready");
          else if (st.status?.toLowerCase().includes("fail")) setStatus("error");
        })
        .catch(() => {/* transient; next tick retries */});
    },
    shouldStopPolling: () => status === "ready" || status === "error",
    maxDurationMs: 60_000, // the old ~40 x 1.5s cap
    onTimeout: () => setStatus("error"), // "still processing, try again"
  });

  return { status, currentPollIndex, restart: resetPollingSchedule };
}
```

**Notes:** Export name is exactly `useProgressivePolling` (named export), surfaced ONLY from the main barrel `@aisquare/ui` (src/index.ts lines 105-109) - NOT from @aisquare/ui/stock and not re-exported from components/primitives. Already a live dep in unified (package.json `@aisquare/ui ^1.3.0`, already imported across src incl. the chat module), so no new dep wiring. NO peer deps: it is built entirely from the library's own useInterval + useDocumentVisibility (pure React, no canvas-confetti/RHF/zod/motion involvement). pollFn / isActive are the only required options; everything else defaults sanely. SSR-safe (no window/document read at module load; visibility via the SSR-safe hook), so safe to import server-side. REQUIRED SEAM: this is headless - it provides timing only, it does NOT hold your status/data state or do the fetch. You inject pollFn (your status call) and shouldStopPolling (your terminal predicate); the hook just decides WHEN to call them and pauses on hidden tabs. Gotchas when porting useAikoChat: (1) the current attachFile loop polls per-attachment inside an async IIFE and uses `attachmentsRef.current.some(a => a.id === id)` as an implicit stop - when you adopt, the hook's `isActive` (e.g. status === 'indexing' && still-present) plus `shouldStopPolling` replace BOTH the for-loop AND that membership check; do not keep the manual loop. (2) maxDurationMs is wall-clock and is intentionally NOT extended by hidden-tab pauses, so a 60s cap stays 60s even if the tab was backgrounded - same semantics as today's fixed loop. (3) call resetPollingSchedule() after a fresh upload to snap back to the fast (1s) step. (4) shouldStopPolling/onTimeout are read through refs, so they need not be memoized - but pollFn is fine as an inline closure too (useInterval captures the latest). (5) currentPollIndex is debug/telemetry only.

---

<a id="filterbar"></a>
### FilterBar, FilterChip

> A config-driven listing toolbar (optional search slot + a row of dropdown filter chips + a right-aligned sort chip + a consumer "right" actions slot), built on the library's Radix DropdownMenu primitive, that replaces the hand-rolled search/filter/sort toolbars duplicated across the listing surfaces.

_Layer: `component` · Built in [ui#75](https://github.com/AISquare-Studio/aisquare-ui/pull/75)_

**Import**
```ts
import { FilterBar, FilterChip, type FilterOption } from "@aisquare/ui";
```

**Key props**

| Prop | Type | Purpose |
|---|---|---|
| `FilterChip.label / options` | `string / FilterOption[]` | Required. label is the leading text (rendered as `Label: Value` when active); options is the menu list, each `{ value: string; label: string }`. |
| `FilterChip.value / defaultValue / onValueChange` | `string / string / (next:string)=>void` | Single-select (controlled). Chip is active when `value !== defaultValue` (defaultValue defaults to ""); the inline clear-X resets value to defaultVal… |
| `FilterChip.multi / values / onValuesChange` | `boolean / string[] / (next:string[])=>void` | Switches the chip to checkbox mode. Active when values is non-empty; chip then shows `N selected`. Menu stays open across toggles. |
| `FilterChip.tone / align` | `"sage"|"neutral" / "start"|"center"|"end"` | tone is the active-fill color (default "sage", the brand-positive sage wash matching the donor). align is the MENU alignment relative to the trigger … |
| `FilterBar.searchSlot / children / sort / right` | `ReactNode each` | searchSlot = a node above the chips (drop in <SmartSearch> or any input); children = the <FilterChip> filters; sort = the trailing sort chip (kept se… |
| `FilterBar.size` | `"md"|"sm"` | Spacing preset: "md" (Studios default, comfortable) or "sm" (Agents compact, tighter gaps). |
| `FilterBar.align / wrap` | `"start"|"spread" / boolean` | align="spread" (default) inserts a flex spacer so sort+right sit far-right (reproduces the donor's `flex-1` spacer); "start" left-packs everything. w… |

**Replaces:** In /home/work/work/aisquare-studio-unified/src/screens/Studios.tsx: the entire hand-rolled filter machine - `renderPill` / `setPill` / `clearPill` (lines 313-376), the `menu` open-state (line 292) + `useClickAway` ref (line 295, import line 2), and the search input + filter-bar JSX (lines 455-473), plus the `ROLE_OPTS`/`VIS_OPTS`/`STATUS_OPTS`/`SORT_OPTS` `[string,string][]` tuples (lines 240-265) which become `FilterOption[]`. In /home/work/work/aisquare-studio-unified/src/screens/Agents.tsx: the Fleet toolbar (lines 64-84) - the raw search div and the static "Saved view"/"Filters" buttons (which today don't even open menus); maps to a `size="sm"` FilterBar with a single-select "Saved view" chip + a `multi` "Filters" chip.

**Adopt in:** `src/screens/Studios.tsx`, `src/screens/Agents.tsx`

**Example**
```tsx
import { useState } from "react";
import { FilterBar, FilterChip, type FilterOption } from "@aisquare/ui";

const ROLE_OPTS: FilterOption[] = [
  { value: "all", label: "All roles" },
  { value: "owner", label: "Owner" },
  { value: "editor", label: "Editor" },
];
const SORT_OPTS: FilterOption[] = [
  { value: "recent", label: "Most recent" },
  { value: "name", label: "Name (A-Z)" },
];

function StudiosToolbar() {
  const [search, setSearch] = useState("");
  const [role, setRole] = useState("all");
  const [sort, setSort] = useState("recent");

  return (
    <FilterBar
      // searchSlot takes any node; drop in <SmartSearch> from @aisquare/ui, or a plain input.
      searchSlot={
        <input
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Search Studios..."
          className="h-9 w-full rounded-md border border-input bg-background px-3 text-sm outline-none"
        />
      }
      sort={
        <FilterChip
          label="Sort"
          value={sort}
          defaultValue="recent"
          onValueChange={setSort}
          options={SORT_OPTS}
          align="end"            // MENU alignment (per-chip), not row layout
        />
      }
    >
      <FilterChip
        label="Role"
        value={role}
        defaultValue="all"       // active = value !== defaultValue; clear-X resets to this
        onValueChange={setRole}
        options={ROLE_OPTS}
      />
    </FilterBar>
  );
}
```

**Notes:** Export names are clean: `FilterBar`, `FilterChip`, and types `FilterBarProps`/`FilterChipProps`/`FilterOption`/`FilterChipTone` are exported under their real names from src/components/index.ts (lines 41-48) and re-exported by the main barrel via `export * from "./components"` - import straight from "@aisquare/ui" (no rename trap like FormField's FormProvider/FormFieldController). REQUIRED SEAM: FilterChip is fully CONTROLLED - it holds no internal selection state, so you MUST wire value+onValueChange (or values+onValuesChange for multi); without the handler, picks/clear do nothing. searchSlot is an INJECTION SLOT, not a built-in search - FilterBar renders whatever node you pass (the stories pair it with @aisquare/ui's <SmartSearch>); to match the donor exactly you'd adopt SmartSearch too, but any input works. TWO `align` props that mean different things: FilterChip.align ("start"|"center"|"end") = Radix MENU placement; FilterBar.align ("start"|"spread") = chip-ROW layout (spread pushes sort+right far-right). Put the sort chip in the `sort` prop (not in children) so spread can right-align it; put view toggles / Create buttons / permission gating in `right` - the bar deliberately owns filtering only, not those. PEER DEPS (already in @aisquare/ui's tree): motion/react (the active morph + clear-X spring), lucide-react (ChevronDown, X icons), and the internal Radix DropdownMenu primitive (which provides focus trap, type-ahead, arrow-key nav, Esc-close, click-away for free - this is what lets you delete Studios' useClickAway + manual `menu` state). This component does NOT use react-hook-form/zod (that's the separate FormField family) - no extra peers needed. Reduced-motion aware: animations collapse to static under prefers-reduced-motion. Tone tokens map onto the lib's shadcn-aliased tokens (success/input/background/ring) which resolve on-brand in unified; the donor's raw `rgba(58,143,92,…)` sage wash becomes tone="sage" (the default). When porting Agents, its current "Saved view"/"Filters" buttons are non-functional placeholders - adopting gives them real menus; use `multi` for the "Filters" chip.

---

<a id="smartpagination"></a>
### SmartPagination

> A controlled, a11y-correct page navigator that wraps the stock @aisquare/ui Pagination primitives with the usePagination sliding-window math (first/last pin, gap-aware ellipses) plus a compact two-pill variant, so a caller passing only currentPage/totalPages/onPageChange gets a polished pager with animated active-marker motion.

_Layer: `component` · Built in [ui#73](https://github.com/AISquare-Studio/aisquare-ui/pull/73)_

**Import**
```ts
import { SmartPagination, type SmartPaginationProps } from "@aisquare/ui";
```

**Key props**

| Prop | Type | Purpose |
|---|---|---|
| `currentPage` | `number` | Active page, 1-based (controlled - you own the state). |
| `totalPages` | `number` | Total page count. The whole component self-hides (returns null) when totalPages <= 1. |
| `onPageChange` | `(page: number) => void` | Fired with the next page. Guarded: never fires for the already-active page or out-of-range; edges are no-ops. |
| `variant` | `"sliding" | "compact"` | Default "sliding" (full pinned-window pager + ellipses). "compact" is the two-page navy pill row. |
| `siblingCount` | `number` | Pages shown each side of current (sliding only). Default 1 (window of 3). |
| `boundaryCount` | `number` | Pages pinned at each end (sliding only). Default 1. |
| `renderLink` | `(page: number, children: React.ReactNode) => React.ReactNode` | Optional seam to render each page as a router <Link> (sliding only); cloned into the stock link styling via cloneElement. Omit for default <a href="#… |
| `scrollToTopOnChange` | `boolean` | Default false. SSR-safe opt-in window.scrollTo after a real navigation (behavior:auto under reduced-motion). |

**Replaces:** Nothing is rendered today: the unified app has no pagination UI component. Server-side pagination params live only in the data layer (/home/work/work/aisquare-studio-unified/src/store/workspaceApi.ts and /home/work/work/aisquare-studio-unified/src/services/workspacesService.ts), and current listing surfaces (Studios, the workspace switcher) consume paginated data via infinite-scroll merge with no page controls. This is the drop-in pager for FUTURE listing/table surfaces that adopt classic numbered paging, and it folds in the hand-built SlidingPagination + CompactPagination windowing logic (ported from FE-React, reimplemented by ~8 sites there) so a new surface never re-derives the window/ellipsis math.

**Adopt in:** `src/features/studios/Studios.tsx (or any new paged listing/table surface that needs numbered page controls)`, `src/store/studiosApi.ts / src/store/workspaceApi.ts (drive currentPage/totalPages from the RTK Query page arg + response total)`

**Example**
```tsx
import * as React from "react";
import { SmartPagination } from "@aisquare/ui";

export function PagedList() {
  const [page, setPage] = React.useState(1);
  const totalPages = 20; // derive from your RTK Query response total/pageSize

  return (
    <div className="flex flex-col items-center gap-4">
      {/* ...render the current page's rows for `page`... */}
      <SmartPagination
        currentPage={page}
        totalPages={totalPages}
        onPageChange={setPage}
      />
      {/* compact two-pill variant:
          <SmartPagination variant="compact" currentPage={page} totalPages={6} onPageChange={setPage} /> */}
    </div>
  );
}
```

**Notes:** - EXPORT NAME: exported as `SmartPagination` (verified in src/components/index.ts:40), deliberately NOT `Pagination` - the stock shadcn `Pagination` nav + its parts (PaginationContent/PaginationLink/PaginationPrevious/PaginationNext/PaginationEllipsis) are separately re-exported via `export * from "./ui/pagination"` (src/index.ts:146). Import SmartPagination for the smart pager; reach for stock `Pagination*` only if you want to hand-assemble. The bare math hook is also public: `usePagination` + types `UsePaginationItem` (aliased from PaginationItem) and `UsePaginationOptions` (src/index.ts:120-124).
- CONTROLLED ONLY: there is no internal page state and no defaultPage - you must own `currentPage` and update it in `onPageChange`, or the pager won't move. Re-clicking the active page and clicking past an edge are intentional no-ops (won't fire onPageChange).
- SELF-HIDES: renders `null` when totalPages <= 1 (both variants) - don't wrap it in chrome that assumes a node is always present.
- PEER DEPS (must be installed in the consumer): `motion` (>=12, used as motion/react for AnimatePresence + the shared-layout active marker) and `lucide-react` (compact variant's ChevronLeft/ChevronRight). Both already ship via @aisquare/ui deps; motion is a declared peerDependency so confirm it resolves in the unified app. No react-hook-form/zod needed for THIS component (those are peers for the RHF FormField family, not pagination).
- MOTION/A11Y: animation (sliding active-marker layoutId, AnimatePresence window fades, smooth scroll) is fully gated on useReducedMotion - degrades to a static render automatically. Renders a proper <nav role=\"navigation\" aria-label=\"pagination\"> with aria-current on the active page and disabled/aria-disabled prev-next at edges.
- renderLink is SLIDING-ONLY (ignored in compact) and is the seam for router links; it cloneElement-merges the stock link styling + a11y attrs onto your element, so pass a real React element (e.g. <Link to={...}/>), not a string. Without it the default page links are <a href=\"#\"> whose onClick preventDefaults and calls onPageChange - fine for SPA state-driven paging.
- `size` ('sm' | 'md', default 'md') visibly affects only the COMPACT pills; the sliding variant sizes via the stock button icon size. siblingCount/boundaryCount affect SLIDING only.
- Spreads remaining ...rest onto the root <nav> (it Omits the native `onChange`); `className` is cn-merged onto the nav (tailwind-merge), so safe to pass layout classes.
- TOKENS: styles use the shadcn-alias tokens (bg-primary/text-primary-foreground/border-border/bg-muted/ring-ring) which the unified :root already defines and which map to brand navy - so it renders on-brand with no token work. Don't paste a generated globals.css that redefines --primary.

---

<a id="imageuploader"></a>
### ImageUploader

> A drag-drop / click image input with internal object-URL preview, type+size validation, and a pixel-reveal transition, built on the Image + PixelCard + Spinner primitives; one variant ("avatar") is exactly the 44px logo well both unified create-modals hand-roll, the other ("dropzone") is a framed cover surface.

_Layer: `component` · Built in [ui#80](https://github.com/AISquare-Studio/aisquare-ui/pull/80)_

**Import**
```ts
import { ImageUploader, type ImageRejection } from "@aisquare/ui";
```

**Key props**

| Prop | Type | Purpose |
|---|---|---|
| `variant` | `"avatar" | "dropzone" (default "dropzone")` | "avatar" = small bordered well with an initial-letter fallback (use this to replace the modal logo wells); "dropzone" = min-h framed dashed surface w… |
| `value` | `File | string | null` | Controlled value. File = freshly picked; string = an existing remote URL shown as the initial preview; null = empty. Pair with onChange. Omit both va… |
| `onChange` | `(file: File | null) => void` | Fires with the next File on select/drop and null on Remove. This is the seam that replaces the modals' setLogo(e.target.files?.[0] ?? null). |
| `accept` | `readonly string[]` | Accepted MIME types. Default is the NO-SVG set [image/jpeg, image/png, image/webp]. Pass [...,"image/svg+xml"] to allow SVG. Drives both the <input a… |
| `maxSizeBytes` | `number (default 5*1024*1024)` | Max size in bytes; over-limit files are rejected via onReject, never committed. (The unified modals do NO size check today.) |
| `onReject` | `(rejections: ImageRejection[]) => void` | Called with every file that failed type/size validation. The component NEVER toasts internally - you decide what to surface (e.g. showToast(rejection… |
| `upload` | `(file: File) => Promise<string>` | Optional persistence seam. When provided, a picked file drives uploading->done and the resolved URL becomes the preview. OMIT it for the modal logo w… |
| `name` | `string` | Used for the avatar initial-letter fallback (first char, uppercased) and the preview alt. Pass the studio/workspace name being typed. |

**Replaces:** In BOTH /home/work/work/aisquare-studio-unified/src/screens/CreateStudioModal.tsx and /home/work/work/aisquare-studio-unified/src/workspace/CreateWorkspaceModal.tsx: the hand-rolled 44px logo well. Each modal carries (1) a `logo`/`logoUrl` state pair plus a `URL.createObjectURL` effect that creates AND revokes the object URL (CreateStudioModal lines 98-99, 122-131; CreateWorkspaceModal lines 39-40, 56-64), (2) the `<span className="w-11 h-11 ... rounded-[10px] ...">` well rendering either `<img src={logoUrl}>` or the name's initial letter (CreateStudioModal 386-389; CreateWorkspaceModal 262-269), (3) a hidden `<input type="file" accept="image/*" ref={fileRef}>` with a Upload/Change-image label and a Remove button that does `setLogo(null); fileRef.current.value=""` (CreateStudioModal 390-414; CreateWorkspaceModal 270-294). ImageUploader variant="avatar" collapses all three into one element and additionally gives type+size validation and drag-drop, which neither modal has today.

**Adopt in:** `src/screens/CreateStudioModal.tsx`, `src/workspace/CreateWorkspaceModal.tsx`

**Example**
```tsx
// CreateStudioModal / CreateWorkspaceModal - replace the logo well + its
// object-URL effect + hidden input + Remove button with one controlled avatar.
// Keep the existing `const [logo, setLogo] = useState<File | null>(null);`
// (it still feeds createPublicationMut({ ..., logo }) / create({ ..., logo })).
// DELETE the logoUrl state, the URL.createObjectURL effect, and fileRef - the
// component owns the object URL and revokes it for you.
import { ImageUploader, type ImageRejection } from "@aisquare/ui";

<ImageUploader
  variant="avatar"
  size="md"               // md == 44px (h-11 w-11), the existing well size
  shape="square"          // square == rounded-xl; logo wells were rounded-[10px]
  value={logo}
  onChange={setLogo}      // File on pick, null on remove
  name={name}             // first letter is the empty-state fallback + alt
  accept={["image/jpeg", "image/png", "image/webp", "image/svg+xml"]}
  onReject={(rejections: ImageRejection[]) =>
    showToast("Invalid image", rejections[0]?.message ?? "", "terracotta")
  }
  aria-label="Upload logo"
/>
// `logo` (a File) is still submitted as multipart at form submit. Do NOT pass
// `upload` here - there is no separate logo-upload endpoint; the File rides the
// create request. Pass `upload` only on a surface that persists eagerly.
```

**Notes:** Export names are clean - `ImageUploader` is exported under its own name from src/components/index.ts (lines 190-197) and re-exported via `export * from "./components"` in src/index.ts; NO rename trap like the FormField case (where the RHF Form/FormField are exported as FormProvider/FormFieldController because ./blocks owns Form/FormField). Import from the package root `@aisquare/ui`, not a subpath.

Stacking / transitive deps: this is a composed component, not a leaf. It internally pulls the Image, PixelCard, and Spinner primitives plus the useReducedMotion hook and the lib/motion presets - all already in @aisquare/ui, so no extra install. It does require `motion` (motion/react) and `lucide-react` as the package's own deps; the unified app already depends on both transitively via @aisquare/ui, so no new peer dep for the consumer (unlike the auth family, where AuthShell stacks on OAuthProviderButtons + SuccessState + PasswordInput, or SourceIngestion which ships heavy gated-off panels). The component itself adds ZERO new dependencies on top of those primitives - drag-drop is native, not react-dropzone.

Theme: light-theme tokens only; renders on-brand under the unified shadcn-alias layer (it styles via border-input/bg-muted/bg-background/ring-ring/text-destructive, all defined in unified's :root). No `dark:` work needed.

Behavioral deltas vs the code it replaces - call these out in the PR so reviewers expect them: (1) it ADDS type+size validation the modals never had (default 5MB, default NO-SVG). The modals use accept="image/*" today, so to preserve "any image" behavior either widen `accept` (e.g. add svg/gif as above) or accept the stricter policy deliberately. (2) it ADDS drag-drop + keyboard activation. (3) rejections fire `onReject` and set an inline error but are NOT toasted internally - wire onReject to the existing useToast or you silently swallow the reason. (4) the object URL is created AND revoked inside the component, so you MUST delete each modal's logoUrl state + URL.createObjectURL effect, or you double-manage and leak.

Controlled-value rule: `value` is hybrid File|string|null. Passing a `File` shows a live object-URL preview; passing a `string` treats it as an existing remote URL (handy if you later seed an already-saved logo). `value === undefined` flips it to uncontrolled (seeds from defaultValue) - so always pass `value={logo}` (a `File | null`) to stay controlled; don't pass `undefined`.

Size mapping for a faithful swap: variant=avatar size=md => h-11 w-11 (44px, matches the wells) rounded-xl; size=sm => h-11 w-11 rounded-lg; size=lg => h-24 w-24. shape=circle drops the radius classes for a round well (profile-picture read). The old wells were rounded-[10px]; size=md (rounded-xl ~12px) is the closest token - fine, or override via className if you must match 10px exactly.

`upload` is optional and orthogonal to these modals: both modals submit the File as multipart inside createPublicationMut / create at form-submit time, so leave `upload` unset and let ImageUploader stay a pure local preview. Only reach for `upload` on a surface that persists the image immediately and wants the built-in uploading->done scrim.

---

<a id="permissionwrapper"></a>
### PermissionWrapper

> A UX-only action gate that wraps a single control (usually a Button) and, when permission is off, disables it, swallows its click, dims it, and shows the reason in a Radix-backed Tooltip; built on the in-house Tooltip primitive.

_Layer: `component` · Built in [ui#68](https://github.com/AISquare-Studio/aisquare-ui/pull/68)_

**Import**
```ts
import { PermissionWrapper, type PermissionWrapperProps, type PermissionWrapperTone } from "@aisquare/ui";
```

**Key props**

| Prop | Type | Purpose |
|---|---|---|
| `hasPermission` | `boolean (required)` | Whether the action is allowed. Arbitrary boolean expression at the call site (e.g. !isViewer && !isEditor, canRemove). true -> child renders live; fa… |
| `children` | `React.ReactElement (required)` | The single child element to wrap (typically a Button). It is cloned, so it must accept ref, plus disabled and onClick (the wrapper injects disabled:t… |
| `deniedMessage` | `string (optional)` | Tooltip copy shown on hover/focus when denied. Defaults to "You do not have permission in this workspace for this action". Put role-specific copy her… |
| `hideOnDenied` | `boolean (optional, default false)` | When true and denied, render nothing instead of the dimmed control (drops it entirely, returns null). |
| `allowedTooltip` | `string (optional)` | Informational tooltip shown on the LIVE control when permission IS granted; the action stays interactive. Omit it for the zero-DOM hot path (child re… |
| `tone` | `PermissionWrapperTone = "muted" | "subtle" (optional, defau…` | Dim treatment for the denied state. muted = opacity-50 (donor default), subtle = opacity-60 for surfaces where fully-greyed reads as broken. |

**Replaces:** The unified app's future role-gated create/manage actions, today hand-built as bare disabled buttons with no reason-on-hover and ad-hoc dimming. Concretely it standardizes: /home/work/work/aisquare-studio-unified/src/screens/CoCreatorPicker.tsx:240 (invite button `disabled={!canInvite}`), /home/work/work/aisquare-studio-unified/src/screens/CreateStudioModal.tsx:209-269 (Next/Create buttons gated via `disabled={!step1Valid}` / `disabled={!canSubmit}` and an `aria-disabled` visibility-lock row at :441), and Studios/Agents/HomeEmpty action buttons that lean on plain `title=` attributes + `opacity-50` for feedback. There is no `Tooltip` primitive used for permission feedback anywhere in unified today (only HomeEmpty imports Tooltip), and no role-based gating is wired into these create/manage flows yet, so PermissionWrapper is the canonical seam for that gating as roles (owner/admin/member/reader, viewer/editor) land via membershipsApi + useWorkspace.

**Adopt in:** `src/screens/CoCreatorPicker.tsx`, `src/screens/CreateStudioModal.tsx`, `src/screens/Studios.tsx`, `src/screens/Agents.tsx`, `src/screens/HomeEmpty.tsx`

**Example**
```tsx
import { PermissionWrapper, Button } from "@aisquare/ui";

// Role flags would come from your workspace/membership selector, e.g.:
// const { role } = useWorkspace();  const isViewer = role === "reader";

function RemoveCoCreatorButton({ canRemove, onRemove }: { canRemove: boolean; onRemove: () => void }) {
  return (
    // Denied -> child is disabled, click is swallowed, dimmed (opacity-50),
    // and `deniedMessage` shows in a tooltip on hover/focus.
    <PermissionWrapper
      hasPermission={canRemove}
      deniedMessage="Only team owners and admins can remove Co-Creators."
    >
      <Button onClick={onRemove}>Remove</Button>
    </PermissionWrapper>
  );
}

// Drop the control entirely when denied:
// <PermissionWrapper hasPermission={canRemove} hideOnDenied><Button onClick={onRemove}>Remove</Button></PermissionWrapper>

// Informational hint on a LIVE control (stays clickable):
// <PermissionWrapper hasPermission allowedTooltip="Upload documents or connect sources to your Vault."><Button onClick={onUpload}>Upload</Button></PermissionWrapper>
```

**Notes:** - Export name is clean: barrel exports `PermissionWrapper` (+ types `PermissionWrapperProps`, `PermissionWrapperTone`) by that exact name from src/components/index.ts -> main barrel. No rename surprise (unlike the RHF form, which exports FormProvider/FormFieldController because Form/FormField are taken by the chat blocks barrel).
- SECURITY: UX/UI ONLY, NOT a security boundary. Users can bypass via DOM or direct API calls. ALL permission checks MUST be enforced on the backend; never rely on this for authorization.
- children must be a SINGLE ReactElement that forwards `ref` and accepts `disabled` + `onClick` (it is React.cloneElement-ed with disabled:true and a click-swallowing handler when denied). The library Button satisfies this. A plain DOM <button> works; a raw text node / Fragment / multiple children will not.
- Peer dep: pulls in the in-house Tooltip primitive which is `@radix-ui/react-tooltip`-backed (already a transitive dep of @aisquare/ui ^1.3.0, which unified already declares - no new install).
- TooltipProvider seam: requires a <TooltipProvider> mounted once at the app root. Per the component header unified already mounts one; the component also wraps its own local provider so it works in isolation (Storybook). Mounting a second nested provider is harmless.
- delayDuration is 0 on both branches (reason appears instantly on hover, no wait). Denied tooltip portals to document.body at z-50 (above app chrome) - do not add a magic z-index. In tests, query the tooltip via ownerDocument.body, not the local canvas.
- Three render branches: (1) allowed + no allowedTooltip -> returns the child untouched, zero wrapper DOM (hot path); (2) allowed + allowedTooltip -> wraps in an info Tooltip, stays live; (3) denied -> child wrapped in a live `relative inline-block` div (the Tooltip trigger) around the dimmed/disabled child. Do NOT collapse that wrapper div onto the child - a disabled native button does not reliably forward hover/focus, so Radix attaches to the div.
- Motion: on hasPermission false->true the child eases dimmed->live over durations.hover (0.18s), gated by useReducedMotion() (+ a motion-reduce: CSS fallback for first paint). Nothing for the adopter to wire.
- Brand-token note for unified: this ships from the library pre-styled (opacity-only dim + the primitive's tooltip). It uses no app `.css`; safe to drop in without the vanilla->Tailwind conversion playbook.

---

<a id="sourceingestion"></a>
### SourceIngestion

> The vault "add a source" flow as one app-decoupled unit: a Radix Dialog that opens on a data-driven source-picker grid (dropzone + live upload queue + tiles) and slides into back-able panels (paste text, URL, YouTube, RSS, email, Drive), built on @aisquare/ui's own Dialog/Button/Input/Textarea primitives + motion, with every app concern (Redux, WebSocket, sonner, env, signed URLs) lifted out behind props.

_Layer: `component` · Built in [ui#81](https://github.com/AISquare-Studio/aisquare-ui/pull/81)_

**Import**
```ts
import { AddSourceModal, type AddSourceModalProps, DEFAULT_SOURCES, DEFAULT_ACCEPT, createUploadFile, formatFileSize, type UploadFile, type SourceView, type SourceKind } from "@aisquare/ui";
```

**Key props**

| Prop | Type | Purpose |
|---|---|---|
| `open / onOpenChange` | `boolean / (open: boolean) => void` | Standard controlled-dialog pair. The modal self-blocks close while any queue row has status "uploading" (fires onNotify("info", "Please wait...") ins… |
| `queue` | `UploadFile[]` | Controlled upload list YOU own. The family never fetches: you push rows (use createUploadFile(file)) and mutate each row's status/progress/error as y… |
| `onAddFiles` | `(files: File[]) => void` | REQUIRED seam. Fires with files dropped/picked in the dropzone. You validate + start your upload here and append to `queue`. The component does no va… |
| `onSubmit` | `(kind: SourceKind, content: string) => void` | REQUIRED seam. Fires when the paste/url/youtube/rss panel submits. kind is "text"|"url"|"youtube"|"rss"|"email"; content is the panel's raw value (fo… |
| `view / onViewChange + values / onValueChange` | `SourceView / (v)=>void  +  Partial<Record<SourceView,string…` | Optional controlled state machine. Omit BOTH pairs to let the modal self-manage internally (it resets to the grid on close + auto-derives the paste f… |
| `sources` | `SourceDefinition[]` | Data-driven grid; defaults to DEFAULT_SOURCES where only paste + url are enabled and YouTube/Drive/Email/RSS render disabled "Soon". Pass your own ar… |
| `onRemoveFile / onRetryFile / onNotify / importProgress / isTransferring` | `(id)=>void / (id)=>void / (kind,msg)=>void / SourceImportPr…` | Optional: row remove/retry handlers (an X shows only when onRemoveFile is given); toast-replacement callback (no toaster is mounted); and the two ban… |

**Replaces:** The single-file chat-upload pathway in unified `src/services/aikoUploadService.ts` (uploadChatFile -> POST /api/v2/qllm/chat-upload/, getChatUploadStatus polling text_ready/vector_ready, plus ACCEPTED_UPLOAD_EXTENSIONS / UPLOAD_ACCEPT_ATTR / isAcceptedUpload / UPLOAD_UNSUPPORTED_MESSAGE). That service stays as the transport; this family replaces/becomes the future Studio vault "add a source" UI surface (today unified has no multi-file dropzone, queue, or non-file source panels - only the one-file chat attach). The component is purely presentational + controlled, so aikoUploadService's POST/poll calls are exactly what you wire into onAddFiles (per-file upload + status mutation) and onSubmit (non-file kinds).

**Adopt in:** `src/services/aikoUploadService.ts`, `src/store/baseApi.ts`, `package.json`

**Example**
```tsx
import * as React from "react";
import {
  AddSourceModal,
  createUploadFile,
  parseUrlLines,
  DEFAULT_SOURCES,
  type UploadFile,
  type SourceView,
  type SourceKind,
} from "@aisquare/ui";
import { uploadChatFile, getChatUploadStatus, isAcceptedUpload } from "@/services/aikoUploadService";

export function VaultAddSource() {
  const [open, setOpen] = React.useState(false);
  const [view, setView] = React.useState<SourceView>("main");
  const [values, setValues] = React.useState<Partial<Record<SourceView, string>>>({});
  const [queue, setQueue] = React.useState<UploadFile[]>([]);

  const patch = (id: string, p: Partial<UploadFile>) =>
    setQueue((q) => q.map((f) => (f.id === id ? { ...f, ...p } : f)));

  // onAddFiles owns validation + transport; the component does neither.
  const onAddFiles = (files: File[]) => {
    for (const file of files) {
      const row = createUploadFile(file); // {id, name, size, type, status:"uploading", progress:0, icon}
      if (!isAcceptedUpload(file.name)) {
        patch(row.id, { status: "error", error: "Unsupported format" });
        setQueue((q) => [...q, row]);
        continue;
      }
      setQueue((q) => [...q, row]);
      uploadChatFile(file, {})
        .then(() => patch(row.id, { status: "success", progress: 100 }))
        .catch((e) => patch(row.id, { status: "error", error: String(e?.message ?? e) }));
    }
  };

  const onSubmit = (kind: SourceKind, content: string) => {
    if (kind === "url") console.log("import urls", parseUrlLines(content));
    else console.log("import", kind, content);
    setView("main");
  };

  return (
    <AddSourceModal
      open={open}
      onOpenChange={setOpen}
      view={view}
      onViewChange={setView}
      values={values}
      onValueChange={(v, val) => setValues((s) => ({ ...s, [v]: val }))}
      queue={queue}
      onAddFiles={onAddFiles}
      onRemoveFile={(id) => setQueue((q) => q.filter((f) => f.id !== id))}
      onRetryFile={(id) => patch(id, { status: "uploading", progress: 0, error: undefined })}
      onSubmit={onSubmit}
      sources={DEFAULT_SOURCES}
      onNotify={(_kind, msg) => console.log(msg)}
    />
  );
}
```

**Notes:** EXPORT NAMES: no renames in THIS family - every symbol exports under its natural name from "@aisquare/ui" (re-barreled via src/components/index.ts -> ./source-ingestion). SourceIngestion is a literal alias of AddSourceModal (`export const SourceIngestion = AddSourceModal`); import either. Do NOT confuse with the FormField wrapper's rename table (donor Form/FormField are exported as FormProvider/FormFieldController there because Form/FormField names are taken by the blocks chat renderer) - that rename does NOT touch SourceIngestion, but an adopter scanning the barrel will see it nearby.

REQUIRED SEAMS (the whole point - it's presentational + controlled, never fetches): you MUST supply onAddFiles (file transport + validation) and onSubmit (non-file sources). The component mounts NO toaster, NO WebSocket, reads NO import.meta.env, dispatches NO Redux. Banners (isTransferring spinner, importProgress "current/total: file") are inputs you feed from your own socket. `queue` is yours to own and mutate - use the exported createUploadFile(file) (auto-sets status:"uploading", progress:0, icon) then patch status/progress/error as your upload resolves. formatFileSize + parseUrlLines + URL_PATTERN are exported for building rows / splitting the multi-URL blob.

HEAVY PANELS SHIP GATED OFF: DEFAULT_SOURCES marks YouTube/Drive/Email/RSS `enabled:false` so they render disabled "Soon" tiles; only Paste text + Webpage/GitHub URL are live. Flip `enabled:true` (pass your own SourceDefinition[]) only once you wire that source. Drive is shell-only - DrivePanel renders the logos/privacy/CTA but onConnect is YOUR OAuth dance (popup + postMessage GOOGLE_DRIVE_OAUTH_CODE was deliberately left in the consumer); appLogo/driveLogo are slots (no asset import). EmailPanel needs the per-user `emailAddress` prop (default placeholder otherwise).

PEER DEPS: uses `motion` (motion/react) + `lucide-react`. unified ALREADY has @aisquare/ui ^1.3.0 and motion ^12.42.0 - verify lucide-react is present (it's a hard runtime import). This family does NOT need react-hook-form/zod/@hookform/resolvers/canvas-confetti/gsap/lenis (those are optional peers for OTHER @aisquare/ui pieces). The Dialog is Radix-portaled to document.body (tests query the whole document, not the canvas).

TOKENS/STYLING: the family is written in shadcn-alias tokens (bg-primary, text-foreground, border-border, bg-muted, text-success/destructive/warning). Per unified CLAUDE.md those aliases already resolve to brand in src/index.css, so it renders on-brand with zero token work - but it is LIGHT-THEME ONLY (no dark: variants). The icon family is `size-5` lucide; SourceCard's connect/connected badge keeps a group-hover cross-fade.

This is the AddSourceModal/AddToVaultModal "add a source" flow, NOT the stored-vault listing - FilePreview is only the design-system shell of a single preview card; the full vault file grid (coupled to contentVaultSlice/documentUrlService/role gating) is a separate "VaultList" follow-up per the FilePreview header.

---

<a id="authshell"></a>
### AuthShell, AuthCard, AuthBackground, AuthFieldRow, AuthErrorAlert, AuthBadge, PasswordRequirements, validEmail/passwordChecks/passwordProblem/PASSWORD_REQUIREMENTS/PASSWORD_HINT/MAX_PASSWORD_LENGTH

> The full-page auth ROUTE scaffold (fixed-inset stage + logo-mask flickering backdrop + branded card) plus the auth body atoms (labeled field row, inline error alert, icon medallion, live password-rules checklist) and the shared email/password validation rule set, reusing the exact scaffold the unified login/signup/forgot/reset screens each copy-pasted.

_Layer: `component` · Built in [ui#83](https://github.com/AISquare-Studio/aisquare-ui/pull/83)_

**Import**
```ts
import { AuthShell, AuthCard, AuthFieldRow, AuthErrorAlert, AuthBadge, PasswordRequirements, validEmail, passwordChecks, passwordProblem, PASSWORD_REQUIREMENTS } from "@aisquare/ui";
```

**Key props**

| Prop | Type | Purpose |
|---|---|---|
| `AuthShell.background` | `"logo-mask" | "grid" | "none" | ReactNode` | Backdrop behind the centered column. Default "logo-mask" (the logo-clipped flickering diamond = the unified default). "grid" = full-area FlickeringGr… |
| `AuthShell.logoSrc` | `string` | Logo MARK url forwarded only to the "logo-mask" AuthBackground (the clip mask). Defaults to /logo-mark.png inside AuthBackground. Distinct from AuthC… |
| `AuthCard.logoSrc` | `string | null` | Logo shown in the card HEADER. Default "/logo-blue.png"; pass null to hide the header entirely (stories pass null). |
| `AuthCard.maxWidth / animate` | `number / boolean` | Card width px (default 460, the unified value) and whether to run the mount spring (default true; reduced-motion forces the static branch). |
| `AuthFieldRow {label, htmlFor, icon, error, inputProps, children}` | `ReactNode / string / ReactNode / ReactNode / InputProps / R…` | Labeled field. Omit children to render a built-in branded Input from inputProps; pass children (e.g. <PasswordInput/>) for a custom control. `error` … |
| `AuthBadge {tone, icon}` | `"accent" | "success" / ReactNode` | Icon medallion crowning a heading. tone="accent" (default, blue, was the forest MailBadge), tone="success" (green, was the sage LockBadge). `icon` is… |
| `PasswordRequirements {value | checks, requirements}` | `string | PasswordCheckResult / readonly PasswordRequirement…` | Live rules checklist. Pass `value` to compute checks from the shared passwordChecks, or pass pre-computed `checks`. Defaults to the shared PASSWORD_R… |

**Replaces:** All three unified auth screens hand-build the SAME scaffold this set provides: (1) the `fixed inset-0 z-[300] flex flex-col overflow-hidden bg-bg animate-[fadeIn_0.22s_ease]` stage + `<FlickerGrid/>` + safe-centered scroll column + `w-full max-w-[460px] bg-surface border border-hairline rounded-2xl shadow-lift px-7 pt-[26px] pb-6` card with the `/logo-blue.png` header - in AuthScreen.tsx lines 266-273, ForgotPassword.tsx 56-67, and ResetPassword.tsx's local `Shell` 20-38 (AuthShell+AuthCard, with FlickerGrid -> background=\"logo-mask\"/AuthBackground). (2) The repeated uppercase-micro-label + leading-icon-wrapper + hand-declared focus-ring field rows (AuthScreen 304-327/367-430, ForgotPassword 81-97, ResetPassword 161-226) -> AuthFieldRow (+ PasswordInput for the eye-toggle fields, replacing the hand-rolled EYE/EYE_OFF show/hide buttons). (3) The terracotta error box literal `bg-[rgba(192,87,70,0.10)] border border-[rgba(192,87,70,0.4)] text-[#a8482e]` duplicated 4x (AuthScreen 469-476, ForgotPassword `errorBoxClass` 7-8, ResetPassword 239-246) -> AuthErrorAlert. (4) ForgotPassword's `MailBadge` (10-17) and ResetPassword's `LockBadge` sage/forest variants (40-55) -> AuthBadge tone accent/success. (5) ResetPassword's inline `<ul>` requirement checklist (186-201) -> PasswordRequirements. The shared rule set in src/auth/validation.ts is the same logic as the lib's authValidation (the lib bundles MAX_PASSWORD_LENGTH internally; unified imports it from ../lib/passwordEncryption).

**Adopt in:** `src/auth/AuthScreen.tsx`, `src/auth/ForgotPassword.tsx`, `src/auth/ResetPassword.tsx`, `src/auth/validation.ts`, `src/auth/FlickerGrid.tsx`

**Example**
```tsx
import { useState } from "react";
import { Lock } from "lucide-react";
import {
  AuthShell, AuthCard, AuthFieldRow, AuthErrorAlert, AuthBadge,
  PasswordRequirements, PasswordInput, Button, passwordChecks,
} from "@aisquare/ui";

// Minimal reset-password screen, mirroring the lib's own AuthShell story.
export default function ResetPassword() {
  const [pw, setPw] = useState("");
  const [pw2, setPw2] = useState("");
  const [err, setErr] = useState("");           // set from your catch: error.data?.detail
  const checks = passwordChecks(pw);
  const allMet = Object.values(checks).every(Boolean);
  const match = pw.length > 0 && pw === pw2;

  return (
    // background defaults to "logo-mask"; pass logoSrc to point at your mark.
    <AuthShell background="logo-mask" logoSrc="/logo-mark.png">
      <AuthCard logoSrc="/logo-blue.png">
        <AuthBadge tone="success" icon={<Lock className="h-[22px] w-[22px]" />} />
        <h2 className="mb-4 mt-4 text-[27px] font-normal text-foreground">Reset your password</h2>
        <form onSubmit={(e) => { e.preventDefault(); /* call resetPassword, setErr on fail */ }} className="grid gap-3">
          <AuthFieldRow label="New password" htmlFor="rp-pw">
            <PasswordInput id="rp-pw" autoComplete="new-password" value={pw} onValueChange={setPw} valid={allMet} />
          </AuthFieldRow>
          <PasswordRequirements value={pw} />
          <AuthFieldRow label="Confirm password" htmlFor="rp-pw2">
            <PasswordInput id="rp-pw2" autoComplete="new-password" value={pw2} onValueChange={setPw2} valid={match} />
          </AuthFieldRow>
          {err && <AuthErrorAlert animate={false}>{err}</AuthErrorAlert>}
          <Button type="submit" className="w-full" disabled={!allMet || !match}>Reset password</Button>
        </form>
      </AuthCard>
    </AuthShell>
  );
}
```

**Notes:** Exports are clean - AuthShell/AuthCard/AuthBackground, AuthFieldRow/AuthErrorAlert/AuthBadge/PasswordRequirements, and validEmail/passwordChecks/passwordProblem/PASSWORD_REQUIREMENTS/PASSWORD_HINT/MAX_PASSWORD_LENGTH all re-export under their own names from "@aisquare/ui". The renamed-export gotcha does NOT apply to these; it applies to the SEPARATE RHF form component, whose donor `Form`/`FormField` are exported as `FormProvider`/`FormFieldController` (those names are taken by the chat-block renderer). Do not confuse the two - AuthShell is NOT a form library and does not need react-hook-form.\n\nSTACKING / COMPOSITION: AuthShell internally renders AuthBackground (for background=\"logo-mask\") and FlickeringGrid (for \"grid\"). A full auth route also composes OAuthProviderButtons (+ DEFAULT_OAUTH_PROVIDERS), SuccessState (reset-success), and PasswordInput (primitive, ships the eye-toggle + success check) - all already in @aisquare/ui; import them too rather than re-building. AuthFieldRow renders a branded Input when children is omitted, or your control (e.g. PasswordInput) when passed.\n\nREQUIRED SEAMS (logic stays in the consumer): AuthShell/AuthCard render only - they hold no auth state. Keep the RTK Query mutations (login/signup/socialLogin/forgotPassword/resetPassword), the email-existence/phase routing, and post-auth onboarding redirect in your screen. OAuthProviderButtons takes onSelect(id) - wire `onSelect={(id) => SOCIAL[id]()}`. AuthErrorAlert is render-only: decode the RTKQ error in your catch (toError puts the BE payload on `error.data.detail`, NOT error.response.data) and pass the string.\n\nPEER DEPS: `motion` (>=12) and `lucide-react` are required and used here (AuthCard/AuthErrorAlert mount-springs via motion/react; icons). react-hook-form/zod/@hookform/resolvers are peers of the lib but ONLY for the Form component - not needed to adopt AuthShell.\n\nGOTCHAS: (1) AuthShell.logoSrc (the logo-MASK for the canvas backdrop, default /logo-mark.png) is different from AuthCard.logoSrc (the header logo, default /logo-blue.png) - set both. (2) AuthBackground locks its diamond to the card via a `.gs-card` hook that AuthCard sets automatically and a `[data-auth-stage]` marker AuthShell sets - so use them together; a bare AuthCard outside AuthShell loses the backdrop centering. (3) Tokens are the shadcn/HSL alias layer (bg-card, border-border, text-foreground, --destructive, --accent, --success, --ring) - these resolve to brand in unified's :root, so no recolor, but note the visuals shift the error/badge hues from the old raw hex (#a8482e terracotta -> --destructive; #eaf1fe/forest + #e7f0e4/sage -> --accent/--success) to the themed tokens; expect a small palette change, not a regression. (4) Replace unified's src/auth/validation.ts imports with the lib's (same rules); the lib bundles MAX_PASSWORD_LENGTH itself, whereas unified pulls it from ../lib/passwordEncryption - keep the RSA cap in sync. (5) Unrelated: the same components barrel also ships the SourceIngestion family (AddSourceModal/SourceIngestion + heavy back-able panels: Url/Youtube/Rss/Email/Drive/PasteText) - heavy panels gated behind that flow, not pulled in by AuthShell; ignore for this adoption. (6) AuthCard/AuthErrorAlert honor prefers-reduced-motion (static branch); pass animate={false} on AuthErrorAlert inside AuthFieldRow (it already does) to avoid a per-keystroke fade.

---

<a id="passwordinput"></a>
### PasswordInput, PasswordInputProps

> A password field with a built-in reveal/hide toggle (and optional "all rules met" success check) that composes the base Input primitive, so it inherits every Input variant/size/token-color/focus-ring and drops straight into controlled, uncontrolled, or react-hook-form Controller use.

_Layer: `primitive` · Built in [ui#33](https://github.com/AISquare-Studio/aisquare-ui/pull/33)_

**Import**
```ts
import { PasswordInput, type PasswordInputProps } from "@aisquare/ui";
```

**Key props**

| Prop | Type | Purpose |
|---|---|---|
| `showToggle` | `boolean (default true)` | Render the eye reveal/hide button. Leave true for the standard auth field; set false for a plain masked input. |
| `valid` | `boolean` | When true AND the field is non-empty, shows a green Check left of the toggle. Wire to your 'password meets all rules' state (e.g. ResetPassword's all… |
| `onValueChange` | `(value: string) => void` | Convenience callback firing the raw string on every change (fires alongside the native onChange). Lets you write onValueChange={setPw} instead of onC… |
| `value / defaultValue` | `string` | Controlled (value) or uncontrolled (defaultValue) - passed straight through to the inner input; presence-tracking for the success check works in both… |
| `revealLabel / hideLabel` | `string (default "Show password" / "Hide password")` | aria-label for the toggle in each state; also exposes aria-pressed. Override for i18n. Replaces the old hardcoded 'Toggle password visibility'. |
| `size` | `"sm" | "default" | "lg" (inherited from InputProps)` | Field height/padding (h-9/h-10/h-12). 'variant' (default/ghost/chat/search) is also inherited. 'type' is the ONE Input prop omitted - the component o… |

**Replaces:** Both auth screens hand-roll an identical masked-input + eye-toggle block. In /home/work/work/aisquare-studio-unified/src/auth/AuthScreen.tsx: the inline EYE/EYE_OFF SVG consts (lines 54-65), the showPw useState (line 87), and the password <input> + toggle <button> at lines 408-429 (autoComplete current/new-password). In /home/work/work/aisquare-studio-unified/src/auth/ResetPassword.tsx: the EYE/EYE_OFF SVGs (lines 7-18), showPw/showPw2 useState (lines 70-71), and TWO copies of the input+toggle block (new password lines 165-183, confirm password lines 207-225). PasswordInput collapses each of these to one element and deletes the SVG consts + show-state booleans. (Note: AuthScreen's confirm-password input at 444-452 has no toggle today; adopting PasswordInput would give it one for free.)

**Adopt in:** `src/auth/AuthScreen.tsx`, `src/auth/ResetPassword.tsx`

**Example**
```tsx
import { useState } from "react";
import { PasswordInput } from "@aisquare/ui";
// uses the unified app's existing validation helper
import { passwordChecks } from "./validation";

function ResetPasswordFields() {
  const [pw, setPw] = useState("");
  const allMet = Object.values(passwordChecks(pw)).every(Boolean);

  return (
    <div className="flex flex-col gap-[6px] mb-3">
      <label htmlFor="rp-pw" className="text-[9.5px] font-medium text-ink-2 uppercase tracking-[0.13em]">
        New password
      </label>
      <PasswordInput
        id="rp-pw"
        aria-label="New password"
        placeholder="Create a password"
        autoComplete="new-password"
        value={pw}
        onValueChange={setPw}   // stub callback: replace with your form's setter
        valid={allMet}          // shows the success check once every rule passes
      />
    </div>
  );
}
```

**Notes:** IMPORT NAME: export is literally `PasswordInput` from the package root `@aisquare/ui` (primitives/index.ts L27 -> re-exported by src/index.ts L163 `export * from "./primitives"`). Not deep-imported. `@aisquare/ui` is already in unified package.json (^1.3.0). No RHF/zod peer dep for THIS primitive - it is framework-agnostic (forwards ref, passes value/onChange through); RHF/zod only matter for the separate Form* family (which the barrel renames to FormProvider/FormFieldController because Form/FormField are taken by the blocks chat-renderer - irrelevant here). peer deps actually pulled in: lucide-react (Eye/EyeOff/Check icons) and the cn util - both already transitive via @aisquare/ui. \n\nLOAD-BEARING GOTCHA (the `valid` prop): the success check is colored with the inline arbitrary class text-[hsl(var(--success))]. Unified's src/index.css defines --ring (L91) but NOT --success - I grepped, it is absent. So `valid` will render the check INVISIBLE (unresolved CSS var) until an adopter adds `--success: <H S% L%>;` to the :root block in src/index.css (use the brand sage/forest green, HSL channels only - it is hsl(var(--success)), matching the shadcn-alias HSL-channel convention). The toggle's focus-ring (focus-visible:ring-ring) is fine - --ring exists. \n\nTOKEN MAPPING: PasswordInput inherits Input's classes which use shadcn-alias tokens (bg-background, text-foreground, border-input, text-muted-foreground, ring-ring). Per the unified CLAUDE.md these aliases already resolve on-brand (background/card==surface, border==hairline, primary==ink), so it renders correctly without token work - it will NOT exactly match the auth screens' bespoke pixel styling (the current inputs use py-[11px] text-[14.5px] rounded-[10px] focus:shadow-[0_0_0_3px_rgba(10,37,64,0.15)] pl-[38px] for the left lock icon). To match: pass size + a className with the arbitrary values, and keep the left lock-icon <span> you already have (PasswordInput only owns the RIGHT side; it auto-sets pr-10 for the toggle, pr-16 when the check also shows). \n\nBEHAVIOR PARITY: toggle is type=\"button\" with tabIndex={-1} (stays out of Tab order, never submits) and aria-pressed - strictly better a11y than the current hardcoded aria-label=\"Toggle password visibility\". \n\nSTACKING / family context: PasswordInput is one atom of the full-page auth scaffold. AuthShell (components/index.ts L160) is explicitly built to compose AuthCard + AuthBackground + the primitives auth slot atoms (AuthFieldRow, AuthErrorAlert, AuthBadge, PasswordRequirements) + PasswordInput + OAuthProviderButtons + SuccessState. If you only want the field, adopt PasswordInput alone; if you later replace the whole AuthScreen/ResetPassword Shell, reach for AuthShell and that stack (PasswordRequirements would also replace ResetPassword's hand-rolled rules <ul> at L186-201, and validEmail/passwordChecks/passwordProblem/PASSWORD_REQUIREMENTS are ALSO exported from @aisquare/ui - same rule set as unified's local ./auth/validation, so the two can converge). Separately, the SourceIngestion family in this same barrel ships heavy panels (UrlPanel/YoutubePanel/RssPanel/EmailPanel/DrivePanel) that are app-decoupled and gated off by default - unrelated to auth, just noting the barrel is large.

---

## Merge & deploy order

1. [#85](https://github.com/AISquare-Studio/aisquare-ui/pull/85) - raise the worst-case `import *` size budget (lands the wave green).
2. The 14 independent component PRs (any order): #67, #68, #70, #72, #73, #74, #75, #76, #77, #78, #79, #80, #81, #82.
3. The auth stack **in order**: #33 -> #69 -> #71 -> #83 (AuthShell is built on the three before it).
4. [#84](https://github.com/AISquare-Studio/aisquare-ui/pull/84) - the playground showcase (collapses to just demos once the wave is in).
5. Trigger the **Playground Deploy to S3** workflow (`workflow_dispatch`) to publish [ui.aisquare.studio](https://ui.aisquare.studio).

See each component live on the playground after deploy, or run `pnpm storybook` in this repo for the Storybook surface.
