---
url: /v7.0/en-us/copilot-sdk-js.md
---
# Complete UI SDK

Applies to HENGSHI SENSE 7.0. `hengshi-copilot@VERSION.js` exposes `window.Copilot` and mounts the complete conversation UI in an open Shadow DOM: input, answers, charts, history, and clarification. The customer owns the container, authentication, and business entry point. HENGSHI runs models and tools on the server.

Use the separate [data client SDK](copilot-sdk-client.md) to render your own UI. Complete [authentication and CORS prerequisites](copilot-sdk.md#Integration-prerequisites) first.

## Minimal integration

Replace the service URL, `VERSION`, and resource IDs with deployment values (see [Getting the SDK files and version](copilot-sdk.md#Getting-the-SDK-files-and-version) for the version lookup). This example uses an established browser login session; configure Cookie/CSRF and cross-origin policy first.

```html
<!doctype html>
<html lang="en-US">
<meta charset="utf-8">
<title>Data Agent</title>
<body>
  <button id="open">Open assistant</button>
  <div id="data-agent"></div>
  <script src="https://analytics.example.com/assets/hengshi-copilot@VERSION.js"></script>
  <script>
    const copilot = new window.Copilot(
      document.getElementById('data-agent'),
      {
        baseUrl: 'https://analytics.example.com',
        credentials: 'include',
        locale: 'en-US',
        executionMode: 'read_only',
        closable: true,
        userConfig: { dataSources: [{ dataAppId: 251, datasetId: 1 }] },
        style: { right: 20, bottom: 20, width: 440, height: 640 },
        onReady(instance) { instance.show(); },
      },
    );
    document.getElementById('open').onclick = () => copilot.show();
  </script>
</body>
</html>
```

`baseUrl` takes precedence over the compatibility global `window.__hs_sdk_base_url__`. With neither set, the host page origin is used. Loading a script from a CDN does not select the HENGSHI API host; set `baseUrl` explicitly. Keep associated deployment assets reachable rather than copying only the entry JS file.

For short-lived Bearer credentials, use `credentials: 'omit'` and `headers: async () => ({ Authorization: 'Bearer ' + await getUserAccessToken() })`. Implement `getUserAccessToken` to obtain a credential for the current user. Custom headers merge last. Do not embed administrator or client secrets in the frontend.

## Common configuration

| Option | Meaning |
| --- | --- |
| `baseUrl` / `apiPrefix` | HENGSHI service origin / API prefix; default prefix `/api` |
| `credentials` / `headers` | Cookie policy / custom headers; headers can be an object or async function |
| `locale` | `zh-CN` or `en-US` |
| `userConfig.dataSources` | Data sources within one application, or one measure subject |
| `executionMode` | Defaults to `read_only`; explicitly use `authoring` to expose authoring |
| `showModeSwitch` | Show Query/Authoring switch only when the host product allows it |
| `showHistory` | Show history entry |
| `conversationId` | Open a saved conversation owned by the current user |
| `resumeLastConversation` | Whether to open the most recent conversation on first mount; defaults to `true` |
| `tags` | Optional source tags; new conversations store them and history shows conversations containing every tag |
| `clientContext` | Bounded page hint, not scope or authorization |
| `closable` / `headless` | Close button / initially hidden; headless does not change execution |
| `style` / `stylesheet` | Root styles / custom CSS injected into Shadow DOM |
| `draggable` | Dragging/resizing options: `enable`, `bounds`, `position`, `size`, `minWidth`, `minHeight` |
| `onReady` / `onShow` / `onHide` / `onDestroy` | Ready, show, hide, and destroy callbacks |

Each instance owns its service client and conversation state without depending on a HENGSHI global store in the host page. Host CSS does not directly override Shadow DOM styles; use `stylesheet`.

When history is enabled, `resumeLastConversation` defaults to `true`, so the SDK opens the most recent conversation after its first mount. Set it to `false` to load the history list while starting a new conversation; users can still open older conversations from history. An explicit `conversationId` takes precedence and opens that conversation. The option applies when the instance mounts: `hide()` and `show()` preserve the current conversation, while destroying and recreating the instance applies the initialization option again.

Use `tags` to distinguish Data Agent conversations created from different business systems by the same user. A conversation created with its first turn stores the tags as immutable metadata; when multiple tags are configured, a history record must contain all of them to appear. An empty conversation shell created explicitly with `onCreateConversation` has no Data Agent context and is not included in source-tagged history. Pass at most five tags, each no longer than 64 characters, non-empty, and without leading or trailing whitespace. Omitting tags preserves existing history behavior. Tags do not change conversation or data permissions.

## Container embedding vs floating widget

The SDK resolves the root layout from the `style` the host passes; no extra switch is required:

| Host style | Layout | Root `position` | Shadow document |
| --- | --- | --- | --- |
| No `top`/`right`/`bottom`/`left` | Container embed | `relative` | Follows the container size |
| Any viewport anchor | Floating widget (same as 6.3) | `fixed` | `width/height: fit-content` |
| Explicit `style.position` | Explicit value wins | As passed | `fit-content` only for `fixed` |

Container embedding needs no extra options; the container just needs a size:

```html
<div id="data-agent" style="width: 420px; height: 100%"></div>
<script>
  new window.Copilot(document.getElementById('data-agent'), {
    baseUrl: 'https://analytics.example.com',
    dashboardContext: { appId: 251, dashboardId: 18 },
  });
</script>
```

For a bottom-right widget, keep the 6.3 pattern and pass viewport anchors such as `right`/`bottom` (see "Minimal integration"). In container-embed mode, if the container has no width, the SDK logs a console warning instead of rendering a blank panel silently.

## Data scope and page navigation

Application/data package example:

```js
userConfig: {
  dataSources: [
    { dataAppId: 251, datasetId: 1 },
    { dataAppId: 251, datasetId: 2 },
  ],
}
```

Subject example: `userConfig: { dataSources: [{ subjectId: 7 }] }`. Do not mix applications and subjects, select cross-application data, or combine independent subjects.

An SPA can update pending sources or page hints without destroying the UI:

```js
copilot.update({
  userConfig: { dataSources: [{ dataAppId: 252, datasetId: 1 }] },
});
```

Updating configuration does not change an existing conversation's fixed scope. Use the UI's new-conversation entry after changing scope. `update()` is not an API for changing a conversation's scope. Authoring also requires a new conversation.

## Embedded dashboard editor: page context

When the host page embeds the dashboard editor in an iframe, the SDK cannot read the cross-origin iframe. When the user says "the current dashboard", give the Data Agent the app and dashboard through `dashboardContext`; the SDK expands it into the full page context:

```js
const copilot = new window.Copilot(document.getElementById('data-agent'), {
  baseUrl: 'https://analytics.example.com',
  credentials: 'include',
  executionMode: 'authoring',
  dashboardContext: { appId: 251, dashboardId: 18, title: 'Operations overview' },
});
```

| Field | Meaning |
| --- | --- |
| `appId` / `dashboardId` | Current app and dashboard; `dashboardId` is required. |
| `title` | Optional dashboard title used when the answer refers to the resource. |
| `mode` | `edit` (default, `dashboard.editor`), `view` (`dashboard.viewer`), or `preview`. |
| `chartId` / `chartTitle` | Optional selected chart, sent as a `selected` resource. |
| `dirty` | Optional; whether edit mode has unsaved changes. A dirty context does not establish a dashboard scope automatically. |

* Call `update({ dashboardContext })` after the iframe navigates to another dashboard; it applies to later turns and does not rewrite the current conversation.
* A single turn may override it: `onCreateChat({ prompt, dashboardContext })`, or the payload of a bridged `conversation.turn.request`. That turn uses the request context first, and the SDK refreshes the timestamps.
* When `headlessScope` is not passed and the context is not dirty, the SDK uses `dashboardContext` to establish the dashboard question scope. It selects and locates the scope; it does not grant data permissions. Keep fixed data sources in `userConfig.dataSources`.
* Use `clientContext` (advanced) when you need custom filters or a full resource snapshot; a per-turn `dashboardContext` takes precedence when both are present.

Query scope and page context are separate: keep the fixed scope in `userConfig` / `scope`; in authoring mode (`executionMode: 'authoring'`) the server validates every write against the current user's permissions.

## Lifecycle and programmatic questions

| Method | Usage |
| --- | --- |
| `render(container?)` | Mount; call explicitly with `autoRender: false` |
| `update(patch)` | Update instance configuration |
| `show()` / `hide()` | Show/hide without deleting server history |
| `destroy()` | Unmount when the host component exits |
| `onCreateChat(body)` | Ask after ready, for example `{ prompt: 'Show sales quantity by region' }` |

Programmatic question:

```js
// Call inside onReady(instance), or after confirming readiness.
await copilot.onCreateChat({ prompt: 'Show 2025 sales quantity by region' });
```

Without an explicit conversation id, `onCreateChat` continues the conversation the panel currently shows (usually the newest one in history). Host-driven interactions that want each question to be its own thread pass `newConversation: true`:

```js
await copilot.onCreateChat({
  prompt: 'Interpret chart: Coffee monthly sales',
  dashboardContext: { appId: 251, dashboardId: 18, chartId: 42, mode: 'edit' },
  newConversation: true,
});
```

The SDK creates a new conversation and derives its scope from the turn context; the flag stays client-side and is never sent to the service.

A clarification renders as an in-conversation form: the service returns every unresolved `questions[]` item in one payload, and submitting the form starts a new turn carrying the confirmed choices in `runtimeContext.clarificationResolution`, and the service closes the original clarification when it creates the turn; the answered form stays visible but disabled. No host configuration is required. For a custom UI, read `questions[]` from `lui.clarification` and submit `answers[]` in the new turn through `runtimeContext.clarificationResolution` (see the [data client SDK](copilot-sdk-client.md)).

Only use `executionMode: 'authoring'` when the host intentionally provides authoring. Global authoring can start without selected data sources. Server ACL and high-risk confirmation still apply.

`Copilot.renderChat(container, chatConfig, copilotConfig)` remains a local-result display entry. Its second argument receives result configuration directly, not `{ chat: ... }`. It does not select or start a legacy runtime through `type: 'agent' | 'workflow'`. Use the [data client SDK](copilot-sdk-client.md) for custom-UI turns, recovery, and cancellation.

## Integration checks

Match script/backend versions, verify `baseUrl`, login, allowed preflight headers, and data permissions. Check permissions first on 403. A missing chart does not always mean failure: clarification or text-only answers can be valid. The UI SDK does not automatically take over iframe dashboards or execute a DOM/action bridge. See [iframe integration](copilot-sdk-iframe.md).

## Styling

The UI renders inside a Shadow DOM, so host-page CSS does not reach its elements. Inject styles through `stylesheet`:

```js
new Copilot(el, {
  stylesheet: `
    [data-test="answer"] { font-size: 14px; line-height: 1.7; }
    [data-test="chart"] { border-radius: 8px; }
  `,
});
```

Stable selectors for customization:

| Target | Selector |
| --- | --- |
| Answer container | `[data-test="answer"]` |
| Answer card | `[data-test="chatbi-answer-card"]` |
| Chart | `[data-test="chart"]` |
| Tool-call progress | `[data-test="headless-active-tool"]` |
| Processing status | `[data-test="headless-processing-status"]` |
| Add-to-dashboard entry | `[data-test="chatbi-add-to-dashboard"]` |
| Answer action menu | `[data-test="chatbi-answer-action-menu"]` |

The 6.3 practice of restyling tool calls and answer text with CSS still applies in 7.0; rely on `data-test` selectors, not internal class names.

## Answers only (EmbedCompletion)

For hosts that already own the conversation flow and only need HENGSHI to render answers and charts: no HENGSHI composer, product header, history entry, or mode switch. 6.3 provided the same behavior as `EmbedConversation`; 7.0 provides it as `EmbedCompletion`.

The difference from the full chat embed is the composer alone: same conversation service, same SSE events, same run and cancellation behavior. The SSE subscription lives in the SDK container, not the composer, so rendering answers only does not change stream consumption.

### Options

| Option | Meaning |
| --- | --- |
| `baseUrl` / `apiPrefix` / `credentials` / `headers` | Same as the service client |
| `render` | `answers`: answers only, no composer, header, history or mode switch |
| `conversationId` | Existing conversation; a new one is created when omitted |
| `prompt` | Optional; runs one turn in that conversation. `update({ conversationId, prompt })` runs the new prompt when the host opens another conversation |
| `chatUid` | Optional; render only that turn |
| `executionMode` | Defaults to `read_only`; with `authoring` it still renders answers only, and write operations are completed through the operation proposals and confirm button in the answer |
| `userConfig.dataSources` | Fixed query scope |
| `allowAddToDashboard` | Show the add-to-dashboard entry, default `false` |
| `dashboardTarget` | `{ window, origin, appId?, dashboardId? }` for an edit-mode dashboard iframed into the page; when set, insertion uses the message bridge and `appId` gates the entry on app write permission |
| `onBeforeAdd` / `onAfterAdd` | Notifications before and after insertion so the host can switch or refresh the iframe; callbacks do not gate insertion and their errors are ignored |
| `stylesheet` | Styles injected into the Shadow DOM for answers and tool calls |

### Basic usage

```html
<div id="answer"></div>
<script src="https://bi.example.com/assets/copilot-sdk.js"></script>
<script>
  const instance = new Copilot(document.getElementById('answer'), {
    baseUrl: 'https://bi.example.com',
    render: 'answers',
    conversationId: 1234,
    executionMode: 'read_only',
    userConfig: { dataSources: [{ dataAppId: 251 }] },
    allowAddToDashboard: true,
    stylesheet: '[data-test="answer"] { font-size: 14px; }',
  });
</script>
```

### Starting a turn

Two ways, depending on the host layout.

1. Pass `prompt` at mount; the SDK loads the conversation and runs one turn.

```js
new Copilot(document.getElementById('answer'), {
  baseUrl: 'https://bi.example.com',
  render: 'answers',
  conversationId: 1234,
  prompt: 'Sales by region for 2025',
});
```

2. Let the host's own input start turns through the instance method; follow-ups keep rendering in the same area.

```js
instance.onCreateChat({ prompt: question }, (chat) => {
  // chat.uid is available for readback, telemetry or later actions
});
```

When `conversationId` is omitted, the SDK creates a conversation; keep the instance or the conversation ID so follow-ups do not open a new conversation each time. Turns use the same `POST /api/conversations/{id}/chats/headless:stream` call and the same events as the full SDK. Clarifications render inside the answer area; the host does not implement them.

### Charts and add-to-dashboard

The SDK renders charts; the host does not handle chart configuration or data conversion. `allowAddToDashboard` is off by default; when enabled it works in this order.

**1. Message bridge (preferred)**

When the host page already iframes the dashboard editor, pass the target window:

```js
const dashboardFrame = document.getElementById('dashboard-frame');
const instance = new Copilot(el, {
  allowAddToDashboard: true,
  dashboardTarget: {
    window: dashboardFrame.contentWindow,
    origin: 'https://bi.example.com',
    appId: 251,        // editable (design) app id
    dashboardId: 18,   // shared by the published and edit states
  },
  onBeforeAdd: ({ chart, target }) => {
    // The host may switch the left iframe from published to edit mode here.
  },
  onAfterAdd: ({ chart, target, result, error }) => {
    // Insertion is done; refresh or navigate the iframe if needed.
  },
});
```

On click the SDK posts `dashboard.chart.insert.request` to that window; the dashboard inserts the chart into the **dashboard currently open in edit mode** and replies with `dashboard.chart.insert.result`. The chart lands in the live layout without a reload and without discarding unsaved edits.

`appId` is the edit-mode app id. When set, the SDK reads `GET /api/apps/{appId}` and checks whether `action` contains app-level write permission; without it the "+" entry stays hidden. The insert endpoint still validates permissions server-side. `appId` / `dashboardId` only pin the insertion target for the edit-mode iframe; they do not change the conversation `dashboardContext` or question scope.

Preconditions:

* The target iframe must be a HENGSHI dashboard page in **edit mode**; a published read-only dashboard cannot be written.
* Cross-origin embedding needs no extra parameter: the dashboard accepts messages only from its direct parent and replies to the origin the browser reports. If the iframe URL explicitly carries `parentOrigin=<host page origin>`, the dashboard enforces it as an allowlist; without it, the actual origin is used.
* The host supplies and keeps `window` and `origin` current; call `instance.update({ dashboardTarget })` after switching tabs or rebuilding the iframe.
* With a `dashboardTarget` the SDK **does not** fall back to the dashboard picker: the target is fixed, and choosing another dashboard would break it. Failures are reported through `onAfterAdd`'s `error`.
* The SDK and the dashboard come from the same 7.0 delivery batch. The bridge protocol is `1.0`; cross-version embedding is not supported.

**2. Built-in dialog (only without a fixed target)**

Without `dashboardTarget`, the SDK opens its own add-to-dashboard dialog: it lists dashboards the current user can edit and writes the chart into the chosen one. This is the same dialog the ChatBI page uses.

**3. Turning the entry off**

The entry is hidden when `allowAddToDashboard` is `false`. Without a `dashboardTarget`, enabling it opens the dialog; if the user has no writable dashboard, the list is empty.

The dialog renders inside the Shadow DOM; style it through `stylesheet` with the `add-to-dashboard` `data-test` selectors. Answer and tool-call styling is covered in the previous section.

### Embedding a published dashboard and republishing

The host first embeds the published dashboard; question scope and `dashboardContext` stay on the published app. When the user clicks "+", the SDK writes the chart into the fixed edit-mode target and the host can switch the iframe through the callbacks. To put republishing into the same flow:

1. Append `showRepublish=true` to the edit-mode iframe URL (default `false`; edit mode only). When the current user has app administrator permission, the dashboard top action bar shows a republish button; publish permission is still validated server-side.
2. Clicking it calls `POST /api/apps/{appId}/republish` with no body and reuses the previous publish configuration. The publish hash stays stable, so embedded publish links keep working.
3. The dashboard posts the result to the parent with the same message envelope as the chart bridge:

```json
{
  "type": "hengshi:dashboard-embed",
  "version": "1.0",
  "event": "publish.result",
  "payload": {
    "success": true,
    "originAppId": 251,
    "publishedAppId": 252,
    "publishHash": "<stable-hash>",
    "dashboardId": 18,
    "url": "https://bi.example.com/publish/<stable-hash>"
  }
}
```

On failure `success` is `false` and `error.code` / `error.message` are present. The parent refreshes or navigates the published iframe itself; how the iframe displays after publishing is up to the host.

Recommended flow:

* Embed the published URL first and keep `dashboardContext` on the published app id.
* Read `publishedBy` from the published app to get the edit-mode app id and put it in `dashboardTarget.appId` (the SDK checks write permission with it).
* On "+", switch the left iframe to edit mode in `onBeforeAdd` (keep `showRepublish=true`, `sidebar=false`, and other parameters), then decide whether to navigate in `onAfterAdd`.
* Refresh the published iframe after `publish.result`.

## Charts only: render a forwarded lui.chart

When your backend consumes the SSE stream and forwards only chart events to the browser, you do not need the conversation UI. Pass the complete `lui.chart` event to `Copilot.renderLuiChart`; the SDK reuses the same chart rendering as the conversation view and keeps the add-to-dashboard entry.

```js
const handle = window.Copilot.renderLuiChart(
  document.getElementById('chart'),
  luiChartEvent, // a complete lui.chart event, or an array of them
  {
    baseUrl: 'https://bi.example.com',
    dashboardTarget: {
      window: document.getElementById('dashboard-frame').contentWindow,
      origin: 'https://bi.example.com',
    },
  },
);

// Refresh in place when the server sends the next frame
handle.update(nextLuiChartEvent);
// Release when the page unloads
handle.destroy();
```

Accepted payloads:

| Payload | Description |
| --- | --- |
| Complete `lui.chart` event | The JSON object in the SSE `data:` line, for example `{"type":"lui.chart","data":{...}}` |
| `{ type: 'chart', data }` | A chart block already shaped like the chat data |
| Raw chart payload | `{ charts, chartsData, views }`, `{ chart, chartData }`, or `{ spec, chartData }` |
| Array | Any of the above, rendered in order |

Options:

| Option | Description |
| --- | --- |
| `baseUrl` / `credentials` / `headers` | Same as the data client; rendering reads dataset names and other display metadata |
| `dashboardTarget` | `{ window, origin, appId?, dashboardId? }`; the add-to-dashboard entry then posts into the edit-mode dashboard, forwarding `appId` / `dashboardId` with the request |
| `onAddToDashboard` | Host callback used when no `dashboardTarget` is configured |
| `onBeforeAdd` / `onAfterAdd` | Notifications around insertion; on failure `onAfterAdd` carries `error` |
| `allowAddToDashboard` | Set to `false` to hide the entry |

Notes:

* `renderLuiChart` does not create conversations, subscribe to SSE, or offer a "use in other dashboard" entry. The host owns turns, retries, and authentication.
* Chart rendering shares the same code and message bridge as the complete UI SDK, so the SDK build must come from the same 7.0 delivery batch as the server.
* To hand dashboard chart interpretation to the host page instead, append `interpret=parent` to the dashboard editor URL. See [iframe embedding](embed/iframe.md).

## Render only the clarification form: forward lui.clarification

When the host consumes SSE itself and wants the clarification form inside its own layout, pass the complete `lui.clarification` event to `Copilot.renderLuiClarification`. The SDK renders the form and selections only; it does not create conversations or submit answers. On submit it returns the structured selections and the next-turn prompt it composed to the host.

```js
const handle = window.Copilot.renderLuiClarification(
  document.getElementById('clarification'),
  luiClarificationEvent, // complete lui.clarification event, { data }, or the data itself
  {
    onClarificationSubmit: ({ clarificationId, questions, answers, prompt }) => {
      // Start the next turn with prompt or answers.
    },
  },
);

// Swap in the next clarification without remounting.
handle.update(nextLuiClarificationEvent);
// Tear down on page unload.
handle.destroy();
```

Callback context:

| Field | Description |
| --- | --- |
| `clarificationId` | Current clarification id |
| `questions` | Complete question list from the server |
| `answers` | `[{ questionId, slot?, selectedCandidateIds }]`, only answered questions |
| `prompt` | Next-turn prompt composed by the SDK, such as "继续上一个问题，已确认：…"; the host can use it as-is |

Configuration:

| Option | Description |
| --- | --- |
| `onClarificationSubmit` | Required for interactive forms; may be omitted with `clarificationInteractive: false`. Called on submit. Return `false` or throw to keep the form editable for a retry |
| `clarificationInteractive` | Defaults to `true`; set to `false` to render confirmed selections read-only. A payload with `status` `ANSWERED` / `ABANDONED` / `BLOCKED`, or `active: false`, is also read-only |

A throwing `onClarificationSubmit` does not lose user selections; the form stays interactive. The host only needs to create the next turn. **Do not call abandon afterward**: when any new turn is created in the conversation, the server automatically closes the clarification still waiting on the previous turn. Call `POST /api/conversations/{id}/chats/headless/clarifications/{clarificationId}:abandon` only when the user dismisses the clarification without starting a new turn.
