> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# 从回答分叉会话

从一条已结束的回答创建新会话，保留该轮及之前的上下文。新建、复制上下文与导航由业务后端和应用完成。

## 接入 SOP

1. 配置 `features.fork.onFork(message, run)`，由回调拿到目标消息与运行信息。
2. 调业务 fork 接口，以当前 sessionId 和目标消息为依据复制上下文，返回新会话 ID。
3. 接口成功后更新会话目录，并切换 `activeSessionId`。
4. 让新运行时通过适配器历史读取复制后的对话；不要仅复制前端数组冒充后端分叉。

## 验证结果

在完整历史中选择一个较早的回答分叉。新会话应只包含截至目标轮的上下文；后续发送不改变原会话。验证失败回调经 onError 处理，重复点击受到等待状态约束。

## 常见调整与排错

按钮只在已结束且带运行信息的回答上出现。没有按钮检查 `onFork` 和消息的运行关联。复制范围错误检查后端 fork 语义。`SessionList.onFork` 是目录上的操作入口，应复用同一业务服务。

## 示例与 API


### 后端职责的内存演示：分叉后在新目录项继续对话

Mock 演示；业务函数需要替换为真实实现。

#### src/demos/fork-session.tsx


````
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
// SPDX-License-Identifier: MIT
import '@volcengine/chatkit/styles.css';

import { Chatkit, SessionList, useChatSessions } from '@volcengine/chatkit';
import { createMockAdapter } from '@volcengine/chatkit/adapters/mock';
import type { ChatInput, ChatRuntimeAdapter, RuntimeMessage } from '@volcengine/chatkit/core';
import { useState } from 'react';

const mock = createMockAdapter({ pace: 1.5, getScenarioId: () => 'product-tools' });
const forks = new Map<string, readonly RuntimeMessage[]>();
const adapter: ChatRuntimeAdapter<ChatInput> = {
  start: ingress => mock.start(ingress),
  run: (request, context) => mock.run(request, context),
  history: async ({ sessionId }) => {
    const own = await mock.history!({ sessionId }, { signal: new AbortController().signal });
    return { ...own, messages: [...(forks.get(sessionId) ?? []), ...own.messages] };
  },
};
export default function ForkSession() {
  const [items, setItems] = useState([{ id: 'fork-original', title: '原会话' }]);
  const [active, setActive] = useState('fork-original');
  const [notice, setNotice] = useState('完成一次回答后，从回答下方分叉。');
  const sessions = useChatSessions({ adapter, activeSessionId: active });
  return (
    <div className="demo-column">
      <div className="demo-bar" role="status">
        {notice}
      </div>
      <div className="demo-row">
        <SessionList sessions={items} activeSessionId={active} onSelect={setActive} style={{ width: 160 }} />
        <div className="demo-main">
          <Chatkit
            sessions={sessions}
            settings={{ recommendations: ['帮我查询接入方法'] }}
            features={{
              fork: {
                onFork: async (message, run) => {
                  const history = await adapter.history!(
                    { sessionId: active },
                    { signal: new AbortController().signal }
                  );
                  const target = history.messages.reduce(
                    (last, item, index) => (item.runId === run.id ? index : last),
                    -1
                  );
                  if (target < 0) {
                    setNotice('尚未取得目标轮次的后端历史，请稍后重试。');
                    return;
                  }
                  const id = crypto.randomUUID();
                  forks.set(
                    id,
                    history.messages.slice(0, target + 1).map(item => ({ ...item }))
                  );
                  setItems(old => [...old, { id, title: `分叉 ${items.length}` }]);
                  setActive(id);
                  setNotice(`已从消息 ${message.id} 分叉；仅演示内存后端。`);
                },
              },
            }}
          />
        </div>
      </div>
    </div>
  );
}

````

#### src/main.css


````
/*
 * Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
 * SPDX-License-Identifier: MIT
 */

/* 示例页只给一个铺满的容器；chatkit 自己渲染 .chatkit-wrapper，接入方不用再包一层。 */
html,
body,
#root {
  height: 100%;
  margin: 0;
}

body {
  color: var(--chatkit-color-text, #0b0b0f);
  font-family: 'PingFang SC', system-ui, -apple-system, 'Microsoft YaHei', sans-serif;
  font-size: 13px;
}

/* 示例的 iframe 不宽，输入框左右留一点边距，不贴着边。 */
.chatkit-composer-wrapper {
  width: calc(100% - 24px);
  margin-bottom: 12px;
}

.demo-missing {
  padding: 24px;
  color: var(--chatkit-color-text-tertiary, #7a7880);
}

/*
 * 下面是示例页面自己的外观（页面布局、示例里的业务按钮和卡片），代表接入方页面上自己的样式，
 * 和 chatkit 无关。示例代码里以 demo- 开头的类名都在这里。
 */

/* 页面布局：上下排、左右排、聊天区占剩下的空间 */
.demo-column {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.demo-row {
  position: relative;
  display: flex;
  flex: 1;
  min-height: 0;
  height: 100%;
}

.demo-main {
  flex: 1;
  min-width: 0;
  min-height: 0;
}

/* 页面顶部的一条：开关、单选、页面自己的头部 */
.demo-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 6px 12px;
  align-items: center;
  padding: 8px 12px;
  background: var(--chatkit-color-bg-subtle, #fafafb);
  border-bottom: 1px solid var(--chatkit-color-border, #e8e8ec);
}

.demo-bar strong {
  margin-right: auto;
  font-size: 14px;
}

.demo-bar label {
  display: inline-flex;
  gap: 4px;
  align-items: center;
  cursor: pointer;
}

/* 页面侧边的一栏：后端收到的内容、事件列表 */
.demo-side {
  box-sizing: border-box;
  flex-shrink: 0;
  width: 190px;
  padding: 12px;
  overflow: auto;
  font-size: 12px;
  line-height: 1.6;
  background: var(--chatkit-color-bg-subtle, #fafafb);
  border-left: 1px solid var(--chatkit-color-border, #e8e8ec);
}

.demo-side h4 {
  margin: 0 0 8px;
  font-size: 12px;
}

.demo-side pre {
  margin: 0 0 8px;
  padding: 8px;
  font-size: 11px;
  font-family: ui-monospace, Menlo, monospace;
  white-space: pre-wrap;
  word-break: break-all;
  background: var(--chatkit-color-bg, #fff);
  border: 1px solid var(--chatkit-color-border, #e8e8ec);
  border-radius: 6px;
}

.demo-muted {
  color: var(--chatkit-color-text-tertiary, #8f959e);
}

/* 抽屉：盖在聊天区上面的会话列表 */
.demo-drawer {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  z-index: 20;
  box-shadow: 8px 0 24px rgb(0 0 0 / 12%);
}

/* 两个会话示例：宽屏保留左右侧栏，窄屏用按钮展开列表，不挤占聊天区。 */
.demo-session-sidebar {
  flex-shrink: 0;
  width: 200px;
  max-width: 100%;
}

.demo-session-layout[data-placement='right'] .demo-session-sidebar {
  order: 1;
}

.demo-session-layout .demo-session-toggle,
.demo-session-toggle-bar {
  display: none;
}

.demo-session-layout[data-placement='drawer'] .demo-session-toggle {
  display: inline-flex;
}

.demo-session-layout[data-placement='drawer'] .demo-session-sidebar {
  position: absolute;
  inset: 0 auto 0 0;
  z-index: 20;
  display: none;
  box-shadow: 8px 0 24px rgb(0 0 0 / 12%);
}

.demo-session-layout[data-placement='drawer'][data-open='true'] .demo-session-sidebar {
  display: block;
}

@media (width <= 520px) {
  .demo-session-layout .demo-session-placement {
    display: none;
  }

  .demo-session-layout .demo-session-toggle,
  .demo-session-toggle-bar {
    display: flex;
  }

  .demo-session-layout .demo-session-sidebar {
    position: absolute;
    inset: 0 auto 0 0;
    z-index: 20;
    display: none;
    box-shadow: 8px 0 24px rgb(0 0 0 / 12%);
  }

  .demo-session-layout[data-open='true'] .demo-session-sidebar {
    display: block;
  }
}

/* 业务按钮：工具栏、操作栏、顶栏里的小按钮 */
.demo-chip {
  display: inline-flex;
  gap: 4px;
  align-items: center;
  height: 28px;
  padding: 0 10px;
  color: inherit;
  font-size: 12px;
  font-family: inherit;
  white-space: nowrap;
  background: var(--chatkit-color-bg, #fff);
  border: 0.5px solid #b8b7c3;
  border-radius: 14px;
  cursor: pointer;
}

.demo-chip:hover {
  background: var(--chatkit-color-bg-hover, #f2f3f5);
}

.demo-chip[aria-pressed='true'] {
  color: var(--chatkit-color-bg, #fff);
  background: var(--chatkit-color-text, #0b0b0f);
  border-color: var(--chatkit-color-text, #0b0b0f);
}

.demo-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
  padding: 6px 0;
  font-size: 12px;
}

/* 标出插槽位置的色块 */
.demo-slot {
  display: inline-block;
  box-sizing: border-box;
  padding: 1px 6px;
  color: #ad4e00;
  font-size: 10.5px;
  line-height: 18px;
  white-space: nowrap;
  background: #fff3e0;
  border: 1px dashed #ffab40;
  border-radius: 4px;
}

/* 业务卡片 */
.demo-card {
  box-sizing: border-box;
  max-width: 360px;
  margin: 8px 0;
  padding: 12px 14px;
  font-size: 13px;
  line-height: 1.6;
  background: var(--chatkit-color-bg, #fff);
  border: 0.5px solid #d2d1e0;
  border-radius: 16px;
}

.demo-card header {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 4px;
  font-weight: 600;
}

.demo-card footer {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

.demo-badge {
  padding: 0 8px;
  color: var(--chatkit-color-text-secondary, #3f3f51);
  font-weight: 400;
  font-size: 11px;
  line-height: 20px;
  background: #ebebf5;
  border-radius: 10px;
}

/* 右侧面板里的内容 */
.demo-panel {
  padding: 16px;
  font-size: 13px;
  line-height: 1.7;
}

.demo-panel header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
  font-weight: 600;
  font-size: 15px;
}

/* 菜单：点按钮展开的列表 */
.demo-menu {
  position: relative;
  display: inline-block;
}

.demo-menu ul {
  position: absolute;
  bottom: 34px;
  left: 0;
  z-index: 30;
  min-width: 180px;
  margin: 0;
  padding: 4px;
  list-style: none;
  background: var(--chatkit-color-bg, #fff);
  border: 1px solid #e1e3e8;
  border-radius: 8px;
  box-shadow: 0 8px 24px rgb(0 0 0 / 12%);
}

.demo-menu li button {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 6px 10px;
  color: inherit;
  font-size: 13px;
  font-family: inherit;
  text-align: left;
  background: none;
  border: 0;
  border-radius: 6px;
  cursor: pointer;
}

.demo-menu li button:hover {
  background: var(--chatkit-color-bg-hover, #f2f3f5);
}

/* 顶栏、公告这类占一整行的内容 */
.demo-line {
  display: flex;
  gap: 8px;
  align-items: center;
  padding: 6px 14px;
  font-size: 12px;
}

.demo-line--notice {
  margin: 0 16px 8px;
  padding: 8px 12px;
  color: var(--chatkit-color-text-secondary, #3f3f51);
  background: var(--chatkit-color-bg-subtle, #f6f6fc);
  border-radius: 8px;
}

/* 完整应用：左边会话列表，中间顶栏加聊天区，右边一栏卡片 */
.demo-app {
  display: flex;
  height: 100%;
  color: var(--chatkit-color-text, #0b0b0f);
  background: var(--chatkit-color-bg, #fff);
}

.demo-app .chatkit-session-list {
  border-right: 1px solid #ececf0;
}

.demo-app-main {
  display: flex;
  flex: 1;
  flex-direction: column;
  min-width: 0;
}

.demo-app-header {
  display: flex;
  flex-shrink: 0;
  gap: 12px;
  align-items: center;
  justify-content: space-between;
  height: 56px;
  padding: 0 24px 0 16px;
  font-size: 12px;
}

.demo-app-header strong {
  overflow: hidden;
  font-weight: 500;
  font-size: 16px;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.demo-app-body {
  display: flex;
  flex: 1;
  min-height: 0;
}

.demo-app-rail {
  display: flex;
  flex-shrink: 0;
  flex-direction: column;
  gap: 12px;
  box-sizing: border-box;
  width: 280px;
  padding: 4px 24px 24px 0;
  overflow: auto;
}

.demo-rail-card {
  display: flex;
  flex-direction: column;
  gap: 2px;
  padding: 8px;
  border: 1px solid #e6e6ea;
  border-radius: 16px;
}

.demo-rail-card h4 {
  margin: 0;
  padding: 8px;
  color: var(--chatkit-color-text-tertiary, #7a7880);
  font-weight: 500;
  font-size: 14px;
  line-height: 22px;
}

.demo-rail-row {
  display: flex;
  gap: 10px;
  align-items: center;
  min-height: 38px;
  padding: 0 8px;
  color: inherit;
  font-size: 13px;
  font-family: inherit;
  line-height: 22px;
  text-align: left;
  background: none;
  border: 0;
  border-radius: 10px;
}

button.demo-rail-row {
  cursor: pointer;
}

button.demo-rail-row:hover {
  background: #f3f3f5;
}

.demo-rail-row span {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

/* 状态圆点：没开始是虚线圈，进行中转圈，结束是绿色 */
.demo-rail-row i {
  box-sizing: border-box;
  flex-shrink: 0;
  width: 16px;
  height: 16px;
  margin: 0 3px;
  border: 1.5px dashed #b8b7c3;
  border-radius: 50%;
}

.demo-rail-row[data-status='running'] i,
.demo-rail-row[data-status='queued'] i {
  border-color: #e6e6ea;
  border-top-color: var(--chatkit-color-text, #0b0b0f);
  border-style: solid;
  animation: demo-spin 0.9s linear infinite;
}

.demo-rail-row[data-status='completed'] i {
  background: #2db55d;
  border-color: #2db55d;
  border-style: solid;
  box-shadow: inset 0 0 0 3px var(--chatkit-color-bg, #fff);
}

.demo-rail-row[data-status='failed'] i,
.demo-rail-row[data-status='interrupted'] i {
  background: #ec4e6d;
  border-color: #ec4e6d;
  border-style: solid;
  box-shadow: inset 0 0 0 3px var(--chatkit-color-bg, #fff);
}

@keyframes demo-spin {
  to {
    transform: rotate(360deg);
  }
}

/* 会话列表上方的产品名、下方的用户 */
.demo-brand,
.demo-user {
  display: flex;
  gap: 8px;
  align-items: center;
  padding: 4px;
  font-weight: 600;
  font-size: 16px;
}

.demo-user {
  font-weight: 400;
  font-size: 13px;
}

.demo-brand::before,
.demo-user::before {
  width: 20px;
  height: 20px;
  background: var(--chatkit-color-text, #0b0b0f);
  border-radius: 6px;
  content: '';
}

.demo-user::before {
  background: linear-gradient(135deg, #2f79ff, #ec4e6d);
  border-radius: 50%;
}

.demo-legal {
  padding: 6px 0 2px;
  color: #6e718c;
  font-size: 11px;
  line-height: 20px;
  text-align: center;
  opacity: 0.6;
}

/* 窄的时候先收起右边一栏，再收起会话列表 */
@media (width <= 1080px) {
  .demo-app-rail {
    display: none;
  }
}

@media (width <= 760px) {
  .demo-app .chatkit-session-list {
    width: 180px;
  }
}

@media (width <= 520px) {
  .demo-app .chatkit-session-list {
    display: none;
  }
}

.studio-session-picker {
  display: none;
}

@media (width <= 560px) {
  .studio-session-list {
    display: none;
  }

  .studio-session-picker {
    display: block;
    max-width: 140px;
  }
}

/* Demo host status, driven by the runtime's public lifecycle events. */
.demo-stream-status {
  display: flex;
  align-items: center;
  gap: 7px;
  padding: 9px 14px;
  border-bottom: 1px solid var(--chatkit-color-border, #e5e6eb);
  font-size: 10px;
  color: var(--chatkit-color-text-secondary, #6e6e78);
}

.demo-stream-status > span {
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background: currentcolor;
}

.demo-stream-status > span[data-active='true'] {
  animation: demo-live-pulse 1.2s ease-in-out infinite;
}

.demo-stream-status small {
  margin-left: auto;
  font-size: 9px;
}

@keyframes demo-live-pulse {
  50% {
    opacity: 0.25;
  }
}

@media (prefers-reduced-motion: reduce) {
  .demo-stream-status > span[data-active='true'] {
    animation: none;
  }
}

.demo-theme-sample {
  padding: 4px 7px;
  border: 1px solid var(--chatkit-color-border);
  border-radius: var(--chatkit-radius-md);
  background: var(--chatkit-color-bg);
  color: var(--chatkit-color-link);
  font: inherit;
  font-size: 11px;
  white-space: nowrap;
  cursor: pointer;
}

.demo-theme-sample:focus-visible {
  outline: 2px solid var(--chatkit-color-primary);
  outline-offset: 2px;
}

````

#### src/main.tsx


````
import './main.css';
import '@volcengine/chatkit/styles.css';
import { createRoot } from 'react-dom/client';
import Demo from './demos/fork-session';
createRoot(document.getElementById('root')!).render(<Demo />);

````

#### index.html


````
<!doctype html><html lang="zh"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><div id="root"></div><script type="module" src="/src/main.tsx"></script></html>
````

#### package.json


````
{
  "name": "chatkit-example-fork-session",
  "private": true,
  "type": "module",
  "packageManager": "pnpm@10.20.0",
  "scripts": {
    "dev": "vite --host 127.0.0.1",
    "build": "vite build"
  },
  "dependencies": {
    "@volcengine/chatkit": "file:../chatkit.tgz",
    "react": "18.3.1",
    "react-dom": "18.3.1"
  },
  "devDependencies": {
    "vite": "^6.4.1",
    "typescript": "5.9.3",
    "@vitejs/plugin-react": "^4.0.0"
  }
}
````

#### vite.config.ts


````
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({plugins:[react()]});

````

#### README.md


````
# fork-session

本示例与本站预览来自同一份本地代码。

1. 下载页面提供的本地 SDK chatkit.tgz，放在本示例目录的上一级。
2. corepack enable；pnpm install；pnpm dev。
3. 开发真实业务时替换 Mock、上传、语音等演示实现。数据不构成真实业务服务。

````

示例只模拟创建与历史复制；生产环境使用真实后端事务。见[会话列表](/features/sessions.md)、[Hook 参考](/reference/hooks.md)与[配置参考](/reference/config.md)。
