# Hooks

> SDK 的 React Hooks：指挥中心及其注册类 Hooks、任务收件箱、实时任务事件、期限监控、运行控制台以及通知偏好。

Source: https://docs.sommatic.ai/zh/sdks/react/hooks/ (updated 2026-11-26)

这些 Hooks 把你的组件与指挥中心以及用户的工作连接起来。大多数 Hooks 需要 Veripass 的 `AuthProvider` 提供当前登录用户；
指挥中心相关 Hooks 还需要 `CommandCenterProvider`。

## 指挥中心

| Hook                                     | 作用                                                                                                                                                         |
| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `useCommandCenter()`                     | 返回指挥中心：`registerCommands`、`getContext`、`registry`、`executeIntent`、`allCommands`、`providers`、`isThinking`、`error` 等。未挂载 Provider 时返回 `null`，因此共享组件可以回退为空对象。 |
| `useSommaticContextSource(source, deps)` | 发布模型可读取的快照：`{ id, description, getData, ttl_ms? }`。快照默认缓存 30 秒。                                                                                            |
| `useSommaticSurface(surface, deps)`      | 发布界面区域及其处理函数和目标：`{ id, type, label, description?, targets?, handlers? }`。                                                                                  |
| `useSommaticSelection(selection, deps)`  | 发布当前选择：`{ type, content, surface_id }`。                                                                                                                    |
| `useSommaticFocus(focus, deps)`          | 发布当前焦点实体：`{ entity_type, entity_id, label, metadata }`。                                                                                                    |
| `useCommandCenterAgent(options)`         | 单独使用的推理循环：`classifyIntent` 把请求转换为计划，`executePlan` 执行计划。面板已经在使用它；只有构建自己的界面时才需要直接调用。                                                                         |

所有注册类 Hooks 都会在卸载时自动注销，并在 `deps` 变化时重新注册。在页面中的用法见[接入](https://docs.sommatic.ai/zh/command-center/integration.md)。

## 任务

### `useTaskInbox(options)`

当前登录用户的收件箱，按紧急程度排序，定时刷新，并在收到任务事件时立即刷新。

```javascript
import { useTaskInbox } from '@sommatic/react-sdk';

function InboxBadge() {
  const { counts, badgeSeverity, groups, isLoading, refresh } = useTaskInbox({ pollIntervalMs: 60000, pageSize: 10 });
  return <span data-severity={badgeSeverity}>{counts.total}</span>;
}
```

| 选项                   | 默认值       |                        |
| -------------------- | --------- | ---------------------- |
| `enabled`            | `true`    | 关闭该 Hook。              |
| `pollIntervalMs`     | `60000`   | 刷新间隔。                  |
| `dueSoonThresholdMs` | `1800000` | 期限在多近时算作“即将到期”（30 分钟）。 |
| `pageSize`           | `10`      | 加载的任务数量。               |

返回 `tasks`、`groups`（`overdue`、`dueSoon`、`critical`、`normal`）、`counts`、`badgeSeverity`、`isLoading` 和 `refresh`。

### `useEventStream({ userIdentity, enabled, baseUrl })`

为某个用户打开任务事件流，把每个 `task-assigned` 事件转换为 DOM 事件 `sommatic::task-notification`：
`TaskNotificationToast` 会显示它，`useTaskInbox` 会据此刷新。在布局中挂载一次即可：

```javascript
const { user } = useAuth();
useEventStream({ userIdentity: user?.identity, enabled: Boolean(user?.identity) });
```

### `useTaskSLAMonitor(fetchActiveTasks, options)`

定时检查用户的进行中任务，对即将到期或已逾期的任务发出 `sommatic::task-notification`。`fetchActiveTasks`
是你提供的异步函数，返回任务列表。选项：`enabled`、`onLoad`（挂载时检查，默认 `true`）、`repeat`（默认 `true`）、
`intervalMs`（默认 15 分钟）和 `dueSoonThresholdMs`（默认 30 分钟）。

### 通知偏好

`useNotificationPreferences()` 从浏览器本地存储读取用户的偏好（暂停、免打扰时段、最低优先级、静音类型以及按应用的开关），
并在多个标签页之间保持同步。`readNotificationPreferences`、`writeNotificationPreferences`、`isQuietNow` 和
`shouldNotify` 可在 React 之外处理同样的数据。存储键为 `NOTIFICATION_PREFS_KEY`，偏好变化时触发的事件为
`NOTIFICATION_PREFS_EVENT`。

## 工作流与应用

| Hook                                         | 作用                                                                                                                                                                   |
| -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `useSseConsole()`                            | `FlowsSseConsole` 的控制器：以稳定的 id 收集运行事件，并可通过 `$('evt-3')`、`$events`、`$last` 对事件执行 JavaScript。返回 `items`、`events`、`commandHistory`、`push`、`clear`、`reset` 和 `evaluate`。 |
| `useAppStateSync(sdk, state, deps, options)` | 用于 App Engine 应用：通过运行时 `sdk` 保存应用的视图状态（防抖，默认 5 秒），并在应用重新打开时通过 `options.onRestore` 恢复。                                                                                |
| `useLocalStorage(key, defaultValue)`         | 保存在本地存储中的值。                                                                                                                                                          |

> **注意: 不要在本地存储中保存敏感信息**
>
> 通知偏好和 `useLocalStorage` 都会写入浏览器。不要在其中保存令牌或个人数据。

## 下一步

- [组件](https://docs.sommatic.ai/zh/sdks/react/components.md): 基于这些 Hooks 构建的视图。
- [任务通知](https://docs.sommatic.ai/zh/human-in-the-loop/notifications.md): 任务事件如何触达用户。
