停止、重新生成与消息分支:构建可控的生成交互

Agent 会犯错、会跑偏,用户需要「随时喊停」和「换个思路」。本文讲停止生成、重新生成、以及消息分支三套交互的状态设计。

一个只会「一路狂飙」的 Agent 是不可信的。好的 Agent 前端必须给用户三样东西:随时喊停的按钮、不满意就重来的入口、以及像 Git 分支一样的消息历史。

这篇文章把这三件事的状态模型一次讲清楚。

停止生成:AbortController 的一生

流式生成中,用户点「停止」要立即生效。核心是 AbortController:

class StreamController {
  private controller: AbortController | null = null;

  async start(messages: Message[]) {
    this.controller = new AbortController();
    const res = await fetch('/api/agent', {
      method: 'POST',
      body: JSON.stringify({ messages }),
      signal: this.controller.signal,
    });
    // ... 流式读取
  }

  stop() {
    this.controller?.abort(); // 触发 fetch 抛 AbortError
    this.controller = null;
  }
}

关键细节:abort() 之后,已收到的部分内容要定格成一条完整的 assistant 消息,而不是凭空消失:

try {
  await stream();
} catch (err) {
  if (err.name === 'AbortError') {
    finalizePartialMessage(); // 保存已生成的部分
  }
}

否则用户会看到「打了一半的字又缩回去了」的糟糕体验。

重新生成:回退到分叉点

用户对某条回复不满意,点「重新生成」。这意味着:

  1. 找到这条 assistant 消息在上下文里的位置。
  2. 把它(以及它之后的所有内容)从上下文里移除。
  3. 用同一份「之前的历史」重新发起请求。

这就用到了上一篇埋下的 ContextManager.snapshot():

function regenerate(msgId: string, ctx: ContextManager) {
  const snapshot = ctx.snapshot();
  const idx = snapshot.findIndex((m) => m.id === msgId);
  if (idx === -1) return;

  const branch = snapshot.slice(0, idx); // 去掉该消息及之后
  ctx.replace(branch); // 回退上下文
  streamController.start(branch); // 重新生成
}

消息分支:像 Git 一样的历史

真正的「分支」比「重新生成」更进一步——保留所有版本,用户可以在不同回复之间切换。数据结构上,把线性数组变成树:

interface MessageNode {
  id: string;
  message: Message;
  parentId: string | null; // 指向上一节点
  childrenIds: string[];   // 可能有多条「重新生成」的分支
}

interface Conversation {
  nodes: Record<string, MessageNode>;
  rootId: string;
  activeLeafId: string; // 当前展示的叶子
}

切换分支时,沿着 parentId 链回溯到根,就是一条完整的对话路径:

function pathTo(nodeId: string, nodes: Record<string, MessageNode>): Message[] {
  const path: Message[] = [];
  let cur = nodes[nodeId];
  while (cur) {
    path.unshift(cur.message);
    cur = cur.parentId ? nodes[cur.parentId] : null;
  }
  return path;
}

把交互落成 UI

三套交互,对应三个常见的 UI 元素:

  • 停止:生成中的消息旁,一个「■ 停止」按钮;生成结束后变成「↻ 重新生成」。
  • 重新生成:每条 assistant 消息 hover 时浮现的小按钮。
  • 分支切换:消息下方一排「版本 1 / 版本 2 / 版本 3」的切换点,当前高亮。

别忘了无障碍:这些操作要有明确的 aria-label,键盘也能触发,不能只靠 hover。

一个完整的状态机

把这些串起来,一条消息的生成状态机是:

idle → streaming → completed
              ↓
          stopped(定格部分内容)
completed → regenerating(进入新分支)

配合前一篇的 ContextManager 和后端的幂等设计,你就能构建出一个用户真正「可控」的 Agent 前端。

下一篇,我们换个视角——把 Agent 当作一个需要被监控的系统,搭一套可观察性仪表盘。