feat(roundtable): 增强多智能体 Step2 流式推理与产物展示

提交内容:将 roundtable 的流式消息拆分为文本与 think 推理,支持思考内容以 <think> 形式内联渲染,解决仅返回 reasoning token 时的内容空洞问题。新增 stream-reasoning 工具与单元测试,保证 reasoning 首包到正文的闭合行为稳定。

交互与预览修正:write_file/str_replace 工具的沙箱打开策略改为更接近实时席位行为,不再因为文件后缀限制阻塞临时脚本写入可视化;通过新增 streaming-artifacts 工具统一处理可预览路径、最终交付产物过滤与目录快照比对,支持 bash/脚本直接落盘场景在流式阶段自动发现新增文档。

体验细节:步骤面板文件卡片从工具路径与最终 artifact 统一收敛,避免 read_file 点击误触发;自动滚动逻辑新增布局高度抖动识别,防止模型推理渲染导致的误判向上滚动。
This commit is contained in:
董宏凯 committed 2026-08-31 16:45:01 +08:00
1 parent fbf9031e25
commit f0ddade8a7
9 files changed
+600 -106

No files matched your search

@@ -0,0 +1,21 @@
import assert from "node:assert/strict";
import test from "node:test";
import { createInlineReasoningDeltaFormatter } from "./stream-reasoning";
test("provider reasoning chunks form one live think block before answer content", () => {
const format = createInlineReasoningDeltaFormatter();
assert.equal(
format({ id: "msg-1", reasoning: "先检查约束", content: "" }),
"<think>先检查约束",
);
assert.equal(
format({ id: "msg-1", reasoning: ",再组织答案", content: "" }),
",再组织答案",
);
assert.equal(
format({ id: "msg-1", reasoning: "", content: "最终结论" }),
"</think>最终结论",
);
});
@@ -0,0 +1,30 @@
export type StreamedAiTextDelta = {
content: string;
reasoning: string;
id: string;
};
/**
* Preserve an open `<think>` block across provider reasoning-only chunks and
* close it exactly when visible content begins. The resulting text feeds the
* same Step2Message renderer used for literal `<think>` model output.
*/
export function createInlineReasoningDeltaFormatter(): (delta: StreamedAiTextDelta) => string {
const reasoningOpenByMessageId = new Set<string>();
return (delta) => {
const key = delta.id || "__roundtable-anonymous-reasoning__";
let text = "";
if (delta.reasoning) {
if (!reasoningOpenByMessageId.has(key)) {
reasoningOpenByMessageId.add(key);
text += "<think>";
}
text += delta.reasoning;
}
if (delta.content) {
if (reasoningOpenByMessageId.delete(key)) text += "</think>";
text += delta.content;
}
return text;
};
}
@@ -0,0 +1,107 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
collectRoundtableDeliverablePaths,
newestChangedRoundtableArtifact,
resolveRoundtableStreamingWritePreview,
roundtableArtifactDiskSnapshot,
} from "./streaming-artifacts";
test("roundtable opens a provisional Markdown preview when content arrives before path", () => {
assert.equal(
resolveRoundtableStreamingWritePreview("write_file", { content: "# 报告\n正文" }),
"未命名文件.md",
);
assert.equal(
resolveRoundtableStreamingWritePreview("write_file", { path: "/mnt/user-data/outputs/report.m", content: "# 报告" }),
"未命名文件.md",
);
});
test("roundtable live-previews every write_file type but filters final cards", () => {
assert.equal(
resolveRoundtableStreamingWritePreview("write_file", {
path: "/mnt/user-data/outputs/report.md",
content: "# 报告",
}),
"/mnt/user-data/outputs/report.md",
);
assert.equal(
resolveRoundtableStreamingWritePreview("write_file", {
path: "/mnt/user-data/workspace/fetch.py",
content: "print('fetch')",
}),
"/mnt/user-data/workspace/fetch.py",
);
assert.equal(
resolveRoundtableStreamingWritePreview("write_file", {
path: "/mnt/user-data/outputs/task-reports.json",
content: "[{}]",
}),
"/mnt/user-data/outputs/task-reports.json",
);
assert.equal(
resolveRoundtableStreamingWritePreview("str_replace", { content: "# 报告" }),
null,
);
assert.deepEqual(
collectRoundtableDeliverablePaths([
"/mnt/user-data/outputs/report.md",
"/mnt/user-data/outputs/report.md",
"/mnt/user-data/outputs/page.html",
"/mnt/user-data/outputs/chart.mermaid",
"/mnt/user-data/workspace/fetch.py",
"/mnt/user-data/workspace/notes.txt",
]),
[
"/mnt/user-data/outputs/report.md",
"/mnt/user-data/outputs/page.html",
"/mnt/user-data/outputs/chart.mermaid",
],
);
});
test("roundtable detects files created or overwritten by a skill without write_file SSE", () => {
const oldFile = {
path: "/mnt/user-data/outputs/report.md",
sizeBytes: 10,
modifiedAt: "2026-08-31T01:00:00.000Z",
};
const baseline = roundtableArtifactDiskSnapshot([oldFile]);
const overwritten = {
...oldFile,
sizeBytes: 20,
modifiedAt: "2026-08-31T01:00:05.000Z",
};
const generatedBySkill = {
path: "/mnt/user-data/outputs/chart.html",
sizeBytes: 30,
modifiedAt: "2026-08-31T01:00:06.000Z",
};
assert.deepEqual(
newestChangedRoundtableArtifact(
[overwritten, generatedBySkill],
baseline,
Date.parse("2026-08-31T01:00:04.000Z"),
),
generatedBySkill,
);
assert.equal(
newestChangedRoundtableArtifact(
[oldFile],
undefined,
Date.parse("2026-08-31T01:00:10.000Z"),
),
null,
);
assert.deepEqual(
newestChangedRoundtableArtifact(
[generatedBySkill],
undefined,
Date.parse("2026-08-31T01:00:07.000Z"),
),
generatedBySkill,
);
});
@@ -0,0 +1,113 @@
import {
hasCompleteArtifactExtension,
languageOfStreamingArtifact,
normalizeStreamingArtifactPath,
provisionalWriteFilePath,
} from "@/core/artifacts/streaming-write-preview";
/**
* Resolve the path that may be live-previewed while a roundtable tool call is
* still streaming.
*
* `write_file` is deliberately unrestricted here: the sandbox is a live tool
* activity view, not the final-deliverable list. Agents commonly write a
* temporary Python script before reading a skill or running it; suppressing
* that preview makes the page look stalled even though the backend is busy.
* The separate `collectRoundtableDeliverablePaths` gate remains responsible
* for limiting message-list file cards to Markdown, HTML, and Mermaid.
*
* `str_replace` retains its existing document-only behavior. It has no full
* content payload for a virtual preview, and is not a new-file write.
*/
export function resolveRoundtableStreamingWritePreview(
toolName: string | undefined,
args: Record<string, unknown> | undefined,
): string | null {
const rawPath = typeof args?.path === "string" ? args.path : "";
const path = normalizeStreamingArtifactPath(rawPath);
if (toolName === "write_file") {
// Weak models can emit content before the `path` JSON key. Give that same
// call a temporary name so the sandbox opens and continues receiving data.
const content = typeof args?.content === "string" ? args.content : "";
// A complete path of *any* file type is previewable. Keep an incomplete
// suffix such as `report.m` provisional while content is already flowing,
// so it upgrades cleanly to Markdown once the final `d` arrives.
if (path && (hasCompleteArtifactExtension(path) || !content.trim())) {
return path;
}
return content.trim() ? provisionalWriteFilePath(content) : null;
}
// Preserve the prior, conservative behavior for in-place replacement.
return languageOfStreamingArtifact(path) ? path : null;
}
/** Final artifact cards intentionally expose only user-facing deliverables. */
export function collectRoundtableDeliverablePaths(values: Iterable<unknown>): string[] {
const seen = new Set<string>();
const paths: string[] = [];
for (const value of values) {
if (typeof value !== "string") continue;
const path = normalizeStreamingArtifactPath(value);
if (!path || !languageOfStreamingArtifact(path) || seen.has(path)) continue;
seen.add(path);
paths.push(path);
}
return paths;
}
export interface RoundtableWatchedArtifact {
path: string;
sizeBytes: number;
modifiedAt: string;
}
/** Stable disk signature used to notice both newly created and overwritten files. */
export function roundtableArtifactDiskSnapshot(
files: Iterable<RoundtableWatchedArtifact>,
): Map<string, string> {
const snapshot = new Map<string, string>();
for (const file of files) {
const path = normalizeStreamingArtifactPath(file.path);
if (!path) continue;
snapshot.set(path, `${file.sizeBytes}:${file.modifiedAt}`);
}
return snapshot;
}
/**
* Pick the newest file created or changed since the prior directory poll.
*
* On the first poll there is no baseline yet. A small grace window catches a
* skill output that lands between mounting the streaming bubble and the first
* HTTP response, without reopening unrelated files from older roundtable runs.
*/
export function newestChangedRoundtableArtifact(
files: readonly RoundtableWatchedArtifact[],
previous: ReadonlyMap<string, string> | undefined,
watchStartedAtMs: number,
firstPollGraceMs = 2_000,
): RoundtableWatchedArtifact | null {
let newest: RoundtableWatchedArtifact | null = null;
let newestTime = Number.NEGATIVE_INFINITY;
for (const file of files) {
const path = normalizeStreamingArtifactPath(file.path);
if (!path) continue;
const signature = `${file.sizeBytes}:${file.modifiedAt}`;
const modifiedTime = Date.parse(file.modifiedAt);
const changed = previous
? previous.get(path) !== signature
: Number.isFinite(modifiedTime) &&
modifiedTime >= watchStartedAtMs - firstPollGraceMs;
if (!changed) continue;
const sortableTime = Number.isFinite(modifiedTime) ? modifiedTime : 0;
if (!newest || sortableTime > newestTime) {
newest = { ...file, path };
newestTime = sortableTime;
}
}
return newest;
}