# @nabeh/chat-widget-angular

## Release Notes

### Latest

- Adds document knowledge-graph support with built-in `Knowledge Graph` entry points and 2D/3D views.
- Shows source citation cards in both the embedded Knowledge Assistant and the floating widget.
- Keeps embedded suggestion chips clickable above the composer layer.
- Balances `Recent Activity` and `Pinned Collections` scroll areas when chat lists grow.
- Uses stream metadata IDs immediately, so feedback sends `message_id` without waiting for chat history reload.
- Sends feedback payloads as `{ "message_id": "...", "isLike": true }`.
- Shows user initials when no avatar URL is configured.
- Displays `No Content` when a completed assistant response has no answer text.
- Improves chat-list overflow handling and active like/dislike visual states.

## Install

```bash
npm install @nabeh/chat-widget-angular
```

Peer dependencies:

```json
{
  "@angular/common": ">=17.3.0",
  "@angular/core": ">=17.3.0",
  "rxjs": "6.6.7"
}
```

Import the module where the widget is used:

```ts
import { ChatWidgetModule } from '@nabeh/chat-widget-angular';
```

## Basic Usage

```html
<chat-widget [config]="chatConfig"></chat-widget>
```

```ts
import { ChatWidgetConfig } from '@nabeh/chat-widget-angular';

chatConfig: ChatWidgetConfig = {
  apiBaseUrl: 'https://customer-proxy.example.com',
  displayMode: 'widget',
  rag: {
    loadHistoryOnOpen: true
  }
};
```

By default the library uses these backend paths:

```ts
{
  ask: '/my-chats/:chatId/messages',
  askStream: '/my-chats/:chatId/messages/stream',
  history: '/my-chats/:chatId/messages/history',
  listChats: '/my-chats/list',
  createChat: '/my-chats',
  updateChat: '/my-chats/:chatId',
  deleteChat: '/my-chats/:chatId/delete',
  feedback: '/my-chats/:chatId/feedback',
  upload: '/my-chats/upload',
  docs: '/my-chats/docs/:filename',
  knowledgeGraph: '/my-chats/knowledge-graph/:docUuid'
}
```

## Knowledge Graph

The widget supports document-scoped knowledge graphs with both 2D and 3D views.
Enable the feature once; the document UUID is taken from the citation the user selects.

```ts
import { ChatWidgetConfig } from '@nabeh/chat-widget-angular';

chatConfig: ChatWidgetConfig = {
  apiBaseUrl: 'https://customer-proxy.example.com',
  displayMode: 'embedded',
  knowledgeGraph: {
    enabled: true,
    defaultViewMode: '2d',
    maxNodes: 500,
    maxEdges: 1000
  }
};
```

There is no global Knowledge Graph tab. Each citation containing a document UUID shows
a graph action next to its document-viewer action. Clicking the citation invokes
`onCitationClick`; clicking its graph action opens the graph inside the widget without
notifying the host application.

The AI citation contract must include the document UUID in streaming, non-streaming, and
chat-history responses:

```json
{
  "id": "c1",
  "document_uuid": "3c66197f-dbea-4889-9025-74849646c7fc",
  "page": 10,
  "text": "Relevant citation text"
}
```

The widget accepts `document_uuid`, `documentUuid`, `source_uuid`, or `sourceUuid` and
normalizes them to `citation.documentUuid`. The graph action is hidden when no UUID is
available, so citation/chunk IDs such as `c1` are never used as document identifiers.

The default endpoint is `/my-chats/knowledge-graph/:docUuid`, resolved against
`apiBaseUrl`. Customers using that proxy route do not need to configure an endpoint.
An endpoint override remains available for deployments with a different route.

Users can then switch between:

- `2D`: force-directed canvas view for fast exploration.
- `3D`: Three.js-powered force graph for spatial exploration.

Hovering a node temporarily highlights its immediate neighbors and connecting edges.
Clicking a node keeps that selection active and displays its details until it is reset.

For standalone document pages without citations, the existing `documentUuid` or
`documentUuidFactory` options remain supported for programmatic graph opening:

```ts
chatConfig: ChatWidgetConfig = {
  displayMode: 'embedded',
  knowledgeGraph: {
    enabled: true,
    documentUuidFactory: () => this.selectedDocument?.source_uuid ?? null
  }
};
```

The customer proxy route forwards to the AI graph API:

```http
GET /my-chats/knowledge-graph/{doc_uuid}?max_nodes=500&max_edges=1000
```

The widget expects:

- `kg_status`: `not_yet_started`, `processing`, `ready`, `failed`, or `disabled`
- `nodes`: entity nodes
- `edges`: relationships
- `node_count` / `edge_count`
- `is_truncated`

Recommended production flow:

```text
chat-widget -> client Angular app -> NestJS/customer proxy -> AI backend
```

Recommended NestJS proxy route:

```text
GET /my-chats/knowledge-graph/:docUuid
```

Example widget override:

```ts
endpoints: {
  knowledgeGraph: '/my-chats/knowledge-graph/:docUuid'
}
```

## Recommended Auth Architecture

For customer deployments, prefer a customer proxy backend:

```text
chat-widget -> customer proxy -> NestJS backend -> AI backend
```

The widget should call the customer proxy. The proxy can generate or refresh AI access tokens and forward requests to NestJS or AI services. In that setup, the widget does not need `getAccessToken`; auth stays server-side.

Use `getAccessToken` only for local testing or apps that intentionally attach a browser-side bearer token:

```ts
getAccessToken: () => localStorage.getItem('ACCESS_TOKEN')
```

The widget sends that value as:

```http
Authorization: Bearer <token>
```

## Streaming Responses

Streaming uses `fetch()` and `ReadableStream.getReader()` because Angular `HttpClient` does not expose token-by-token response chunks.

Streaming is enabled by default. Configure `endpoints.askStream` for the customer proxy or AI streaming route:

```ts
chatConfig: ChatWidgetConfig = {
  apiBaseUrl: 'https://customer-proxy.example.com',
  endpoints: {
    askStream: '/my-chats/:chatId/messages/stream'
  },
  rag: {
    enableThink: false
  }
};
```

`endpoints.askStream` should normally point to the customer proxy or NestJS backend. The backend should forward the request to the AI server stream endpoint. A full AI URL can be used only for isolated local testing when CORS and auth allow it:

```ts
endpoints: {
  askStream: 'http://183.82.145.33:7777/ai-server/smart_docs/ask_your_doc/stream'
}
```

The streaming request body is:

```json
{
  "message": "What are the key findings in this document?",
  "chat_id": "smart-docs-session-001",
  "query": "What are the key findings in this document?",
  "enable_think": false
}
```

The widget does not include `source_uuid` in streaming chat requests. If a deployment
requires document-scoped chat, the customer proxy or NestJS/AI API contract must add and
authorize that field explicitly; setting `rag.sourceUuid` alone does not send it.

The stream parser supports concatenated JSON objects and objects split across chunks:

```json
{"type":"metadata","content":""}
{"type":"answer","content":"The"}
{"type":"answer","content":" document"}
{"type":"references","content":{"citations":[]}}
```

`type: "answer"` appends content to the current assistant message in real time. `type: "references"` attaches citations to that assistant message and displays source cards.

## Document Preview

Citations are displayed below assistant answers:

- in the embedded Knowledge Assistant sources panel and inline source cards
- in the floating widget as inline source cards

Clicking a source opens a document preview overlay by default.

The preview uses:

```ts
endpoints: {
  docs: '/my-chats/docs/:filename'
}
```

For a citation with `knowledgeName: "labor-law"` and `pageNumber: 28`, the iframe opens:

```text
/my-chats/docs/labor-law#page=28
```

The backend can resolve the real file extension by matching files that start with the requested filename.

### Custom Citation Navigation

If the customer app wants to open its own document page instead of the built-in preview, use `onCitationClick`.

```ts
chatConfig: ChatWidgetConfig = {
  apiBaseUrl: 'https://customer-proxy.example.com',
  onCitationClick: async (event) => {
    console.log('Open customer document page', {
      documentId: event.documentId,
      pageNumber: event.pageNumber,
      text: event.text
    });
  }
};
```

The callback receives the requested navigation fields as guaranteed values:

- `documentId: string`
- `pageNumber: number` (defaults to `1` when the citation has no page)
- `text: string` (defaults to an empty string)

It also includes the full normalized `RagCitation` fields for compatibility:

- `documentUuid`
- `sourceDocument`
- `knowledgeName`
- `pageNumber`
- `text`
- `score`

## Chat Actions

The sidebar supports:

- `Edit`: calls `updateChat` with `{ title }`.
- `Pin Chat` / `Unpin Chat`: calls `updateChat` with `{ title, pinned }` and moves the chat between Recent Activity and Pinned Collections immediately.
- `Delete`: calls `deleteChat` and removes the chat from the UI.

## Configuration Reference

```ts
type ChatWidgetConfig = {
  apiBaseUrl: string;
  endpoints?: Partial<ChatWidgetEndpoints>;
  displayMode?: 'widget' | 'embedded';
  position?: 'bottom-right' | 'bottom-left';
  title?: string;
  subtitle?: string;
  welcomeMessage?: string;
  inputPlaceholder?: string;
  launcherAriaLabel?: string;
  closeAriaLabel?: string;
  initialSuggestions?: string[];
  sourceApp?: string;
  locale?: string;
  customHeaders?: Record<string, string>;
  rag?: KnowledgeRagConfig;
  knowledgeGraph?: KnowledgeGraphConfig;
  getAccessToken?: () => Promise<string | null> | string | null;
  userInfo?: () => Promise<UserInfo | null> | UserInfo | null;
  onOpen?: () => void;
  onClose?: () => void;
  onError?: (error: Error) => void;
  onOpenAssistantPage?: () => Promise<void> | void;
  assistantPageUrl?: string;
  assistantAvatarUrl?: string;
  embedded?: {
    showHeader?: boolean;
  };
};
```

### `apiBaseUrl`

Base URL for the customer proxy or backend.

### `endpoints`

Override any backend path. Relative paths are resolved against `apiBaseUrl`. Full URLs are supported for `askStream` and other endpoints.

### `customHeaders`

Static headers added to every request. Prefer proxy-side auth for production.

### `getAccessToken`

Optional browser-side bearer token provider. Useful for testing; not required when the customer proxy adds tokens server-side.

### `rag`

```ts
type KnowledgeRagConfig = {
  chatId?: string;
  chatIdFactory?: () => string;
  knowledgeNames?: string[];
  sourceUuid?: string;
  enableThink?: boolean;
  useStreaming?: boolean;
  enableReferences?: boolean;
  loadHistoryOnOpen?: boolean;
};
```

`sourceUuid` is retained for backward compatibility as a fallback document context when
Knowledge Graph is opened programmatically without a citation UUID. It is not included in
the `endpoints.askStream` request body. Citation-scoped graphs use the document UUID from
the AI citation response instead.
