# Browser SDK (`@aiui/sdk`)

> Every plugin ESM module running in the React app shell (style: app) can import directly from @aiui/sdk, react, react/jsx-runtime, react-dom, and react-dom/clien

Every plugin ESM module running in the React app shell (`style: app`) can import directly from `@aiui/sdk`, `react`, `react/jsx-runtime`, `react-dom`, and `react-dom/client`. The shell's import map binds all five specifiers to its own runtime instances so hooks work with zero duplicate React bundles.

See [Scaffolding & Types](https://ui.praison.ai/docs/features/plugins/scaffolding-and-types.md) to export the exact `aiui-sdk.d.ts` file for your installed version.

## Live data & SPA navigation (`useLiveData`, `pageLinkProps`)

Share the shell's built-in data-refresh lifecycle (abort on navigation, retain last good data on refresh failure, skip hidden tabs, exponential backoff, single read on tab return) and SPA navigation links (ordinary click stays in the shell with Back/Forward support; Cmd/Ctrl/middle-click opens a new tab):

```js
import { jsx, jsxs } from 'react/jsx-runtime'
import { fetchJson, pageLinkProps, useLiveData } from '@aiui/sdk'

const TABS = [
  { id: 'focus', label: 'Focus' },
  { id: 'revenue', label: 'Revenue' },
]

export default function OperatingPage() {
  const { data, error, refreshing, refresh } = useLiveData(
    'operating:summary',
    (signal) => fetchJson('/api/plugins/ops/summary', { signal }),
    { intervalMs: 30_000 },
  )

  return jsxs('div', {
    children: [
      jsx('nav', {
        style: { display: 'flex', gap: '12px', marginBottom: '16px' },
        children: TABS.map((t) =>
          jsx('a', { key: t.id, ...pageLinkProps(t.id), children: t.label }),
        ),
      }),
      error && jsx('p', { role: 'alert', children: `Refresh failed: ${error.message}` }),
      data && jsx('pre', { children: JSON.stringify(data, null, 2) }),
      jsx('button', { type: 'button', onClick: () => void refresh(), disabled: refreshing, children: 'Refresh' }),
    ],
  })
}
```

## Reuse native shell blocks (`<BlockTree>`)

Render any of PraisonAIUI's 73 native React blocks (`card`, `metric`, `table`, `chart`, `diff_viewer`, `tabs`, [`form`](https://ui.praison.ai/docs/components/form.md), [`rich_text_input`](https://ui.praison.ai/docs/components/rich-text-input.md), [`preview_frame`](https://ui.praison.ai/docs/components/preview-frame.md), `button_group`, `alert`, …) inside a React plugin page without writing custom CSS. `<BlockTree>` lazy-loads the blocks engine on demand (zero boot-bundle cost) and wraps rendering in an error boundary with Retry recovery:

```js
import { jsx } from 'react/jsx-runtime'
import { BlockTree, notify } from '@aiui/sdk'

export default function StatusPage({ page }) {
  const nodes = [
    {
      type: 'card',
      title: 'Pipeline Health',
      children: [
        { type: 'metric', label: 'Active Workers', value: '4' },
        { type: 'button_group', buttons: [{ label: 'Run sync', action: { op: 'sync' } }] },
      ],
    },
  ]

  return jsx(BlockTree, {
    node: nodes,
    page,
    onFormState: (state) => {
      // { action, values, dirty, busy, pendingAction } for native form blocks
      console.log('dirty?', state.dirty, 'pending:', state.pendingAction)
    },
    onAction: async (req) => {
      if (req.body?.op === 'sync') {
        notify({ title: 'Sync queued', description: 'Workers notified.' })
      }
    },
  })
}
```

`<BlockTree>` keeps its lazy `<Suspense>` wrapper identity stable across initial load and subsequent rerenders, so uncontrolled native inputs and textareas preserve their DOM node, value, focus, and text selection when surrounding plugin state updates.

## Authenticated WebSockets (`openWebSocket`, `getWsTicket`)

Plugin WebSocket routes mounted under `/api/plugins/<name>/*` can connect cleanly across open, session-cookie, and bearer-token auth modes without ever putting long-lived tokens in URLs:

```js
import { openWebSocket } from '@aiui/sdk'

// Exchanges any active bearer token for a single-use 60s ?ticket=... via POST /api/auth/ws-ticket.
// Refuses to attach credentials to cross-origin URLs (including //evil.example).
const ws = await openWebSocket('/api/plugins/my-plugin/ws/events')
ws.onmessage = (ev) => console.log('event:', ev.data)
```

## Notifications, toasts & shell chrome

```js
import { dismiss, notify, notifications, registerCommand, registerSlot } from '@aiui/sdk'

// Ephemeral toast
const id = notify({ title: 'Build started', description: 'Running tests…' })
dismiss(id)

// Persistent bell inbox item (works even in create_shell_app hosts)
notifications.push({ title: 'Deploy complete', type: 'success', category: 'deploy' })

// Command palette entry (Cmd/Ctrl+K)
registerCommand({
  id: 'my-plugin.sync',
  title: 'Sync workspace',
  group: 'My Plugin',
  run: () => notify({ title: 'Synced' }),
})
```

## Feature detection across shell versions

`SDK_VERSION` stays `1` while new exports are added monotonically to `SDK_EXPORTS` and `SDK_FEATURES`. Plugins that also target older shells can guard optional exports cleanly:

```js
import sdk from '@aiui/sdk'

if (sdk.SDK_FEATURES?.includes('block-tree')) {
  // BlockTree is available
}
if (sdk.SDK_FEATURES?.includes('ws-transport')) {
  // openWebSocket and getWsTicket are available
}
```

## Full export map

| Category | Exports |
|---|---|
| **Metadata** | `SDK_VERSION`, `SDK_FEATURES` |
| **Registries** | `registerPage`, `registerBlock`, `registerSlot`, `registerToolRenderer`, `registerView`, `getPage`, `getBlock`, `getSlot`, `getToolRenderers`, `subscribe`, `useRegistryVersion` |
| **Rendering** | `BlockTree`, `Markdown` |
| **Navigation & Live Data** | `navigate`, `pageHref`, `pageLinkProps`, `getPageId`, `usePageId`, `useLiveData`, `fetchJson`, `useManifest`, `useThemeMode` |
| **Realtime** | `getWsTicket`, `openWebSocket` |
| **Notifications & Commands** | `notify`, `dismiss`, `notifications`, `useNotifications`, `registerCommand`, `onActivate` |
| **Contributions & Layouts** | `registerSettingsSection`, `registerNavGroup`, `registerThemePreset`, `registerLayout`, `getLayouts`, `useLayout`, `setLayout`, `provideLayoutData`, `useLayoutData` |

## Related pages

- [UI Plugins](https://ui.praison.ai/docs/features/plugins.md)
- [Testing Plugins (`praisonaiui.testing`)](https://ui.praison.ai/docs/features/plugins/testing.md)
- [Notification Center](https://ui.praison.ai/docs/features/notifications.md)
