feat: initialize experimental agent repo
This commit is contained in:
@@ -0,0 +1,280 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
|
||||
import {
|
||||
buildForkedSessionUiState,
|
||||
} from "../../src/routes/chat.js";
|
||||
import {
|
||||
buildPromptWithLearningContext,
|
||||
extractLatestFrontendTurn,
|
||||
generateSessionTitle,
|
||||
shouldRestoreConversationForRuntime,
|
||||
shouldGenerateSessionTitle,
|
||||
} from "../../src/routes/chatSession.js";
|
||||
import { type SessionTurnRecord } from "../../src/sessions/transcriptStore.js";
|
||||
import { type MemoryStore } from "../../src/memory/store.js";
|
||||
import { type OpencodeRuntimeAdapter } from "../../src/runtime/opencode.js";
|
||||
|
||||
describe("shouldGenerateSessionTitle", () => {
|
||||
it("allows auto-title generation for the first turn when the title was not edited", () => {
|
||||
expect(
|
||||
shouldGenerateSessionTitle({
|
||||
recentTurnCount: 0,
|
||||
isTitleManuallyEdited: false,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("blocks auto-title generation after the user edits the title manually", () => {
|
||||
expect(
|
||||
shouldGenerateSessionTitle({
|
||||
recentTurnCount: 0,
|
||||
isTitleManuallyEdited: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("only allows auto-title generation during the first two turns", () => {
|
||||
expect(
|
||||
shouldGenerateSessionTitle({
|
||||
recentTurnCount: 1,
|
||||
isTitleManuallyEdited: false,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldGenerateSessionTitle({
|
||||
recentTurnCount: 2,
|
||||
isTitleManuallyEdited: false,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("generateSessionTitle", () => {
|
||||
it("uses the current user and assistant turn instead of reading wrapped runtime context", async () => {
|
||||
let titlePrompt = "";
|
||||
const runtime = {
|
||||
createSession: async () => ({ id: "title-session" }),
|
||||
prompt: async (_sessionId: string, prompt: string) => {
|
||||
titlePrompt = prompt;
|
||||
},
|
||||
waitForSessionIdle: async () => undefined,
|
||||
messages: async () => [
|
||||
{
|
||||
info: { role: "assistant" },
|
||||
parts: [{ type: "text", text: "标题:泵站压力异常排查。" }],
|
||||
},
|
||||
],
|
||||
abortSession: async () => undefined,
|
||||
} as unknown as OpencodeRuntimeAdapter;
|
||||
|
||||
const title = await generateSessionTitle(runtime, {
|
||||
sessionId: "chat-session",
|
||||
latestUserMessage: "检查一下三号泵站最近压力波动的原因",
|
||||
latestAssistantMessage: "三号泵站压力波动主要与夜间阀门开度变化有关。",
|
||||
fallbackTitle: "新对话",
|
||||
});
|
||||
|
||||
expect(title).toBe("泵站压力异常排查");
|
||||
expect(titlePrompt).toContain("用户:检查一下三号泵站最近压力波动的原因");
|
||||
expect(titlePrompt).toContain("助手:三号泵站压力波动主要与夜间阀门开度变化有关。");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildPromptWithLearningContext", () => {
|
||||
const memoryStore = {
|
||||
buildPromptSnapshot: async () => "",
|
||||
} as unknown as MemoryStore;
|
||||
|
||||
it("prefers persisted frontend messages so aborted turns remain in restored context", async () => {
|
||||
const prompt = await buildPromptWithLearningContext(
|
||||
memoryStore,
|
||||
"actor-1",
|
||||
"project-1",
|
||||
{
|
||||
recentTurns: [],
|
||||
persistedMessages: [
|
||||
{ role: "user", content: "先分析 3 号泵站夜间压力波动" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: "已定位到夜间阀门开度变化与压力波动时间段重合,下一步准备对比相邻支路。",
|
||||
isError: true,
|
||||
},
|
||||
{ role: "assistant", content: "⚠️ **请求已中断**", isError: true },
|
||||
],
|
||||
message: "继续刚才的分析,并补充相邻支路影响",
|
||||
},
|
||||
);
|
||||
|
||||
expect(prompt).toContain("用户:先分析 3 号泵站夜间压力波动");
|
||||
expect(prompt).toContain(
|
||||
"助手:已定位到夜间阀门开度变化与压力波动时间段重合,下一步准备对比相邻支路。",
|
||||
);
|
||||
expect(prompt).not.toContain("⚠️ **请求已中断**");
|
||||
expect(prompt).toContain("[Current user request]\n继续刚才的分析,并补充相邻支路影响");
|
||||
});
|
||||
|
||||
it("falls back to history turns when frontend state is unavailable", async () => {
|
||||
const recentTurns: SessionTurnRecord[] = [
|
||||
{
|
||||
id: "turn-1",
|
||||
userMessage: "检查 DMA-2 夜间漏损异常",
|
||||
assistantMessage: "DMA-2 在 02:00-04:00 出现持续最小夜流抬升。",
|
||||
timestamp: new Date().toISOString(),
|
||||
toolCallCount: 1,
|
||||
},
|
||||
];
|
||||
|
||||
const prompt = await buildPromptWithLearningContext(
|
||||
memoryStore,
|
||||
"actor-1",
|
||||
"project-1",
|
||||
{
|
||||
recentTurns,
|
||||
message: "继续给出排查建议",
|
||||
},
|
||||
);
|
||||
|
||||
expect(prompt).toContain("用户:检查 DMA-2 夜间漏损异常");
|
||||
expect(prompt).toContain("助手:DMA-2 在 02:00-04:00 出现持续最小夜流抬升。");
|
||||
});
|
||||
|
||||
it("skips restored conversation injection when reusing an existing opencode session", async () => {
|
||||
const prompt = await buildPromptWithLearningContext(
|
||||
memoryStore,
|
||||
"actor-1",
|
||||
"project-1",
|
||||
{
|
||||
recentTurns: [
|
||||
{
|
||||
id: "turn-1",
|
||||
userMessage: "上一轮问题",
|
||||
assistantMessage: "上一轮回答",
|
||||
timestamp: new Date().toISOString(),
|
||||
toolCallCount: 0,
|
||||
},
|
||||
],
|
||||
persistedMessages: [
|
||||
{ role: "user", content: "旧问题" },
|
||||
{ role: "assistant", content: "旧回答" },
|
||||
],
|
||||
message: "基于刚才结果继续分析",
|
||||
restoreConversation: false,
|
||||
},
|
||||
);
|
||||
|
||||
expect(prompt).not.toContain("[Previous conversation context]");
|
||||
expect(prompt).toBe("基于刚才结果继续分析");
|
||||
});
|
||||
|
||||
it("restores copied fork context when metadata exists but runtime has no conversation", () => {
|
||||
expect(
|
||||
shouldRestoreConversationForRuntime({
|
||||
hadExistingSessionRecord: true,
|
||||
runtimeHasConversation: false,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldRestoreConversationForRuntime({
|
||||
hadExistingSessionRecord: true,
|
||||
runtimeHasConversation: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractLatestFrontendTurn", () => {
|
||||
it("extracts the latest valid frontend user and assistant turn", () => {
|
||||
const turn = extractLatestFrontendTurn([
|
||||
{ role: "user", content: "检查 DMA-2 漏损" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: "DMA-2 夜间最小流量持续抬升。",
|
||||
progress: [{ id: "tool-dma", phase: "tool" }],
|
||||
},
|
||||
{ role: "user", content: "继续分析相邻分区" },
|
||||
{ role: "assistant", content: "⚠️ **请求已中断**", isError: true },
|
||||
]);
|
||||
|
||||
expect(turn).toEqual({
|
||||
assistantMessage: "DMA-2 夜间最小流量持续抬升。",
|
||||
toolCallCount: 1,
|
||||
userMessage: "检查 DMA-2 漏损",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildForkedSessionUiState", () => {
|
||||
it("copies truncated source messages and preserves tool artifacts", () => {
|
||||
const forked = buildForkedSessionUiState(
|
||||
{
|
||||
messages: [
|
||||
{ role: "user", content: "画压力曲线" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: "已生成图表",
|
||||
artifacts: [
|
||||
{
|
||||
id: "chart-1",
|
||||
tool: "show_chart",
|
||||
kind: "chart",
|
||||
params: { chart_type: "line" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{ role: "user", content: "继续分析" },
|
||||
],
|
||||
},
|
||||
{
|
||||
keepMessageCount: 2,
|
||||
targetSessionId: "forked-session",
|
||||
},
|
||||
);
|
||||
|
||||
expect(forked).toEqual({
|
||||
sessionId: "forked-session",
|
||||
isTitleManuallyEdited: false,
|
||||
messages: [
|
||||
{ role: "user", content: "画压力曲线" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: "已生成图表",
|
||||
artifacts: [
|
||||
{
|
||||
id: "chart-1",
|
||||
tool: "show_chart",
|
||||
kind: "chart",
|
||||
params: { chart_type: "line" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("creates an empty branch state when source UI state is missing or keep count is zero", () => {
|
||||
expect(
|
||||
buildForkedSessionUiState(null, {
|
||||
keepMessageCount: 3,
|
||||
targetSessionId: "forked-without-source",
|
||||
}),
|
||||
).toEqual({
|
||||
sessionId: "forked-without-source",
|
||||
isTitleManuallyEdited: false,
|
||||
messages: [],
|
||||
});
|
||||
|
||||
expect(
|
||||
buildForkedSessionUiState(
|
||||
{ messages: [{ role: "user", content: "不保留" }] },
|
||||
{
|
||||
keepMessageCount: 0,
|
||||
targetSessionId: "forked-empty",
|
||||
},
|
||||
),
|
||||
).toEqual({
|
||||
sessionId: "forked-empty",
|
||||
isTitleManuallyEdited: false,
|
||||
messages: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,440 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
|
||||
import {
|
||||
streamPromptResponse,
|
||||
type PermissionRequestPayload,
|
||||
} from "../../src/routes/chatStream.js";
|
||||
import { type OpencodeRuntimeAdapter } from "../../src/runtime/opencode.js";
|
||||
|
||||
const createEventStream = (events: unknown[]) => ({
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const event of events) {
|
||||
yield event;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
describe("streamPromptResponse", () => {
|
||||
it("forwards opencode permission requests as SSE payloads", async () => {
|
||||
const runtime = {
|
||||
subscribeEvents: async () =>
|
||||
createEventStream([
|
||||
{
|
||||
type: "permission.asked",
|
||||
properties: {
|
||||
id: "perm-1",
|
||||
sessionID: "runtime-session-1",
|
||||
permission: "bash",
|
||||
patterns: ["rm *"],
|
||||
metadata: { command: "rm tmp.txt" },
|
||||
always: ["rm *"],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "session.idle",
|
||||
properties: {
|
||||
sessionID: "runtime-session-1",
|
||||
},
|
||||
},
|
||||
]),
|
||||
prompt: async () => undefined,
|
||||
messages: async () => [],
|
||||
} as unknown as OpencodeRuntimeAdapter;
|
||||
const events: Array<{ event: string; data: Record<string, unknown> }> = [];
|
||||
|
||||
await streamPromptResponse({
|
||||
runtime,
|
||||
sessionId: "runtime-session-1",
|
||||
clientSessionId: "client-session-1",
|
||||
message: "delete temp",
|
||||
write: (event, data) => events.push({ event, data }),
|
||||
});
|
||||
|
||||
const permissionEvent = events.find((item) => item.event === "permission_request");
|
||||
expect(permissionEvent?.data).toMatchObject({
|
||||
session_id: "client-session-1",
|
||||
request_id: "perm-1",
|
||||
permission: "bash",
|
||||
patterns: ["rm *"],
|
||||
target: "rm tmp.txt",
|
||||
always: ["rm *"],
|
||||
} satisfies Partial<PermissionRequestPayload>);
|
||||
});
|
||||
|
||||
it("auto replies always when approval mode is always", async () => {
|
||||
const replies: Array<Record<string, unknown>> = [];
|
||||
const runtime = {
|
||||
subscribeEvents: async () =>
|
||||
createEventStream([
|
||||
{
|
||||
type: "permission.asked",
|
||||
properties: {
|
||||
id: "perm-1",
|
||||
sessionID: "runtime-session-1",
|
||||
permission: "bash",
|
||||
patterns: ["npm test"],
|
||||
metadata: { command: "npm test" },
|
||||
always: ["npm test"],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "session.idle",
|
||||
properties: {
|
||||
sessionID: "runtime-session-1",
|
||||
},
|
||||
},
|
||||
]),
|
||||
prompt: async () => undefined,
|
||||
messages: async () => [],
|
||||
replyPermission: async (options: Record<string, unknown>) => {
|
||||
replies.push(options);
|
||||
},
|
||||
} as unknown as OpencodeRuntimeAdapter;
|
||||
const events: Array<{ event: string; data: Record<string, unknown> }> = [];
|
||||
|
||||
await streamPromptResponse({
|
||||
runtime,
|
||||
sessionId: "runtime-session-1",
|
||||
clientSessionId: "client-session-1",
|
||||
message: "run tests",
|
||||
approvalMode: "always",
|
||||
write: (event, data) => events.push({ event, data }),
|
||||
});
|
||||
|
||||
expect(replies).toEqual([
|
||||
{
|
||||
requestId: "perm-1",
|
||||
sessionId: "runtime-session-1",
|
||||
reply: "always",
|
||||
},
|
||||
]);
|
||||
expect(events.some((item) => item.event === "permission_request")).toBe(false);
|
||||
expect(events.find((item) => item.event === "permission_response")?.data).toEqual({
|
||||
session_id: "client-session-1",
|
||||
request_id: "perm-1",
|
||||
reply: "always",
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards opencode v2 permission requests as SSE payloads", async () => {
|
||||
const runtime = {
|
||||
subscribeEvents: async () =>
|
||||
createEventStream([
|
||||
{
|
||||
type: "permission.v2.asked",
|
||||
properties: {
|
||||
id: "perm-v2-1",
|
||||
sessionID: "runtime-session-1",
|
||||
action: "external_directory",
|
||||
resources: ["/tmp"],
|
||||
save: ["/tmp"],
|
||||
metadata: { path: "/tmp" },
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "session.idle",
|
||||
properties: {
|
||||
sessionID: "runtime-session-1",
|
||||
},
|
||||
},
|
||||
]),
|
||||
prompt: async () => undefined,
|
||||
messages: async () => [],
|
||||
} as unknown as OpencodeRuntimeAdapter;
|
||||
const events: Array<{ event: string; data: Record<string, unknown> }> = [];
|
||||
|
||||
await streamPromptResponse({
|
||||
runtime,
|
||||
sessionId: "runtime-session-1",
|
||||
clientSessionId: "client-session-1",
|
||||
message: "read /tmp",
|
||||
write: (event, data) => events.push({ event, data }),
|
||||
});
|
||||
|
||||
const permissionEvent = events.find((item) => item.event === "permission_request");
|
||||
expect(permissionEvent?.data).toMatchObject({
|
||||
session_id: "client-session-1",
|
||||
request_id: "perm-v2-1",
|
||||
permission: "external_directory",
|
||||
patterns: ["/tmp"],
|
||||
target: "/tmp",
|
||||
always: ["/tmp"],
|
||||
} satisfies Partial<PermissionRequestPayload>);
|
||||
});
|
||||
|
||||
it("forwards opencode question requests and replies as SSE payloads", async () => {
|
||||
const runtime = {
|
||||
subscribeEvents: async () =>
|
||||
createEventStream([
|
||||
{
|
||||
type: "question.asked",
|
||||
properties: {
|
||||
id: "question-1",
|
||||
sessionID: "runtime-session-1",
|
||||
questions: [
|
||||
{
|
||||
header: "范围",
|
||||
question: "选择分析范围",
|
||||
options: [{ label: "城区", description: "中心城区" }],
|
||||
multiple: false,
|
||||
custom: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "question.replied",
|
||||
properties: {
|
||||
sessionID: "runtime-session-1",
|
||||
requestID: "question-1",
|
||||
answers: [["城区", "补充说明"]],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "session.idle",
|
||||
properties: {
|
||||
sessionID: "runtime-session-1",
|
||||
},
|
||||
},
|
||||
]),
|
||||
prompt: async () => undefined,
|
||||
messages: async () => [],
|
||||
} as unknown as OpencodeRuntimeAdapter;
|
||||
const events: Array<{ event: string; data: Record<string, unknown> }> = [];
|
||||
|
||||
await streamPromptResponse({
|
||||
runtime,
|
||||
sessionId: "runtime-session-1",
|
||||
clientSessionId: "client-session-1",
|
||||
message: "ask",
|
||||
write: (event, data) => events.push({ event, data }),
|
||||
});
|
||||
|
||||
expect(events.find((item) => item.event === "question_request")?.data).toMatchObject({
|
||||
session_id: "client-session-1",
|
||||
request_id: "question-1",
|
||||
questions: [
|
||||
{
|
||||
header: "范围",
|
||||
question: "选择分析范围",
|
||||
options: [{ label: "城区", description: "中心城区" }],
|
||||
multiple: false,
|
||||
custom: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(events.find((item) => item.event === "question_response")?.data).toEqual({
|
||||
session_id: "client-session-1",
|
||||
request_id: "question-1",
|
||||
answers: [["城区", "补充说明"]],
|
||||
});
|
||||
});
|
||||
|
||||
it("converts question tool parts into question request SSE payloads", async () => {
|
||||
const runtime = {
|
||||
subscribeEvents: async () =>
|
||||
createEventStream([
|
||||
{
|
||||
type: "message.part.updated",
|
||||
properties: {
|
||||
sessionID: "runtime-session-1",
|
||||
part: {
|
||||
id: "tool-part-1",
|
||||
sessionID: "runtime-session-1",
|
||||
messageID: "message-1",
|
||||
type: "tool",
|
||||
callID: "call-1",
|
||||
tool: "question",
|
||||
state: {
|
||||
status: "running",
|
||||
input: {
|
||||
questions: [
|
||||
{
|
||||
question: "你觉得这个 question 工具好用吗?",
|
||||
header: "测试问题",
|
||||
options: [
|
||||
{
|
||||
label: "非常好用",
|
||||
description: "交互清晰,选项方便",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
time: { start: Date.now() },
|
||||
},
|
||||
},
|
||||
time: Date.now(),
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "session.idle",
|
||||
properties: {
|
||||
sessionID: "runtime-session-1",
|
||||
},
|
||||
},
|
||||
]),
|
||||
prompt: async () => undefined,
|
||||
messages: async () => [],
|
||||
} as unknown as OpencodeRuntimeAdapter;
|
||||
const events: Array<{ event: string; data: Record<string, unknown> }> = [];
|
||||
|
||||
await streamPromptResponse({
|
||||
runtime,
|
||||
sessionId: "runtime-session-1",
|
||||
clientSessionId: "client-session-1",
|
||||
message: "ask",
|
||||
write: (event, data) => events.push({ event, data }),
|
||||
});
|
||||
|
||||
expect(events.find((item) => item.event === "question_request")?.data).toMatchObject({
|
||||
session_id: "client-session-1",
|
||||
request_id: "call-1",
|
||||
questions: [
|
||||
{
|
||||
header: "测试问题",
|
||||
question: "你觉得这个 question 工具好用吗?",
|
||||
options: [
|
||||
{
|
||||
label: "非常好用",
|
||||
description: "交互清晰,选项方便",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
tool: {
|
||||
messageID: "message-1",
|
||||
callID: "call-1",
|
||||
},
|
||||
});
|
||||
expect(
|
||||
events.some(
|
||||
(item) => item.event === "tool_call" && item.data.tool === "question",
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("forwards todo updates as structured SSE payloads and progress", async () => {
|
||||
const runtime = {
|
||||
subscribeEvents: async () =>
|
||||
createEventStream([
|
||||
{
|
||||
type: "todo.updated",
|
||||
properties: {
|
||||
sessionID: "runtime-session-1",
|
||||
todos: [
|
||||
{ content: "分析水位", status: "completed", priority: "high" },
|
||||
{ content: "生成建议", status: "in_progress", priority: "medium" },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "session.idle",
|
||||
properties: {
|
||||
sessionID: "runtime-session-1",
|
||||
},
|
||||
},
|
||||
]),
|
||||
prompt: async () => undefined,
|
||||
messages: async () => [],
|
||||
} as unknown as OpencodeRuntimeAdapter;
|
||||
const events: Array<{ event: string; data: Record<string, unknown> }> = [];
|
||||
|
||||
await streamPromptResponse({
|
||||
runtime,
|
||||
sessionId: "runtime-session-1",
|
||||
clientSessionId: "client-session-1",
|
||||
message: "plan",
|
||||
write: (event, data) => events.push({ event, data }),
|
||||
});
|
||||
|
||||
expect(
|
||||
events.find(
|
||||
(item) => item.event === "progress" && item.data.id === "todo-progress",
|
||||
)?.data,
|
||||
).toMatchObject({
|
||||
id: "todo-progress",
|
||||
phase: "planning",
|
||||
title: "计划进度 1/2",
|
||||
});
|
||||
expect(events.find((item) => item.event === "todo_update")?.data).toMatchObject({
|
||||
session_id: "client-session-1",
|
||||
todos: [
|
||||
expect.objectContaining({
|
||||
content: "分析水位",
|
||||
status: "completed",
|
||||
priority: "high",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
content: "生成建议",
|
||||
status: "in_progress",
|
||||
priority: "medium",
|
||||
}),
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("maps visual tool calls to UIEnvelope SSE payloads", async () => {
|
||||
const runtime = {
|
||||
subscribeEvents: async () =>
|
||||
createEventStream([
|
||||
{
|
||||
type: "message.part.updated",
|
||||
properties: {
|
||||
sessionID: "runtime-session-1",
|
||||
part: {
|
||||
id: "tool-part-chart",
|
||||
sessionID: "runtime-session-1",
|
||||
messageID: "message-1",
|
||||
type: "tool",
|
||||
callID: "call-chart",
|
||||
tool: "show_chart",
|
||||
state: {
|
||||
status: "running",
|
||||
input: {
|
||||
reason: "展示压力趋势",
|
||||
title: "压力趋势",
|
||||
chart_type: "line",
|
||||
x_data: ["00:00", "01:00"],
|
||||
series: [{ name: "P-1", data: [0.4, 0.42] }],
|
||||
},
|
||||
time: { start: Date.now() },
|
||||
},
|
||||
},
|
||||
time: Date.now(),
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "session.idle",
|
||||
properties: {
|
||||
sessionID: "runtime-session-1",
|
||||
},
|
||||
},
|
||||
]),
|
||||
prompt: async () => undefined,
|
||||
messages: async () => [],
|
||||
} as unknown as OpencodeRuntimeAdapter;
|
||||
const events: Array<{ event: string; data: Record<string, unknown> }> = [];
|
||||
|
||||
await streamPromptResponse({
|
||||
runtime,
|
||||
sessionId: "runtime-session-1",
|
||||
clientSessionId: "client-session-1",
|
||||
message: "chart",
|
||||
write: (event, data) => events.push({ event, data }),
|
||||
});
|
||||
|
||||
expect(events.find((item) => item.event === "tool_call")?.data).toMatchObject({
|
||||
session_id: "client-session-1",
|
||||
tool: "show_chart",
|
||||
});
|
||||
expect(events.find((item) => item.event === "ui_envelope")?.data).toMatchObject({
|
||||
session_id: "client-session-1",
|
||||
envelope: {
|
||||
kind: "chart",
|
||||
schemaVersion: "agent-ui@1",
|
||||
grammar: "echarts-safe-subset",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,195 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
|
||||
import {
|
||||
appendBackendUiEnvelope,
|
||||
appendBackendToolArtifact,
|
||||
cancelBackendTodos,
|
||||
upsertBackendQuestion,
|
||||
} from "../../src/routes/chatUiState.js";
|
||||
|
||||
describe("appendBackendToolArtifact", () => {
|
||||
it("persists show_chart tool calls as chart artifacts", () => {
|
||||
const artifacts = appendBackendToolArtifact([], {
|
||||
session_id: "session-1",
|
||||
tool: "show_chart",
|
||||
reason: "测试折线图渲染",
|
||||
params: {
|
||||
title: "压力曲线",
|
||||
chart_type: "line",
|
||||
x_data: ["00:00", "01:00"],
|
||||
series: [{ name: "P-101", data: [0.42, 0.41] }],
|
||||
},
|
||||
}) as Array<Record<string, unknown>>;
|
||||
|
||||
expect(artifacts).toHaveLength(1);
|
||||
expect(artifacts[0]).toMatchObject({
|
||||
tool: "show_chart",
|
||||
kind: "chart",
|
||||
title: "压力曲线",
|
||||
description: "测试折线图渲染",
|
||||
params: {
|
||||
chart_type: "line",
|
||||
x_data: ["00:00", "01:00"],
|
||||
series: [{ name: "P-101", data: [0.42, 0.41] }],
|
||||
},
|
||||
});
|
||||
expect(artifacts[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: expect.stringMatching(/^show_chart-/),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("appendBackendUiEnvelope", () => {
|
||||
it("persists UIEnvelope payloads on assistant messages", () => {
|
||||
const uiEnvelopes = appendBackendUiEnvelope([], {
|
||||
session_id: "session-1",
|
||||
envelope_id: "env-1",
|
||||
created_at: 123,
|
||||
envelope: {
|
||||
kind: "map_action",
|
||||
schemaVersion: "agent-ui@1",
|
||||
action: "locate_features",
|
||||
surface: "map_overlay",
|
||||
params: { ids: ["J-1"], feature_type: "junction" },
|
||||
},
|
||||
});
|
||||
|
||||
expect(uiEnvelopes).toEqual([
|
||||
{
|
||||
envelopeId: "env-1",
|
||||
createdAt: 123,
|
||||
envelope: {
|
||||
kind: "map_action",
|
||||
schemaVersion: "agent-ui@1",
|
||||
action: "locate_features",
|
||||
surface: "map_overlay",
|
||||
params: { ids: ["J-1"], feature_type: "junction" },
|
||||
},
|
||||
renderStatus: "pending",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("upsertBackendQuestion", () => {
|
||||
it("replaces a tool-call placeholder with the actionable question request", () => {
|
||||
const questions = upsertBackendQuestion(
|
||||
[
|
||||
{
|
||||
requestId: "call-1",
|
||||
sessionId: "session-1",
|
||||
questions: [
|
||||
{
|
||||
header: "测试问题",
|
||||
question: "你觉得这个 question 工具好用吗?",
|
||||
options: [{ label: "非常好用", description: "交互清晰,选项方便" }],
|
||||
},
|
||||
],
|
||||
tool: { messageID: "message-1", callID: "call-1" },
|
||||
createdAt: 123,
|
||||
status: "pending",
|
||||
},
|
||||
],
|
||||
{
|
||||
session_id: "session-1",
|
||||
request_id: "question-1",
|
||||
questions: [
|
||||
{
|
||||
header: "测试问题",
|
||||
question: "你觉得这个 question 工具好用吗?",
|
||||
options: [{ label: "非常好用", description: "交互清晰,选项方便" }],
|
||||
},
|
||||
],
|
||||
tool: { messageID: "message-1", callID: "call-1" },
|
||||
created_at: 456,
|
||||
},
|
||||
);
|
||||
|
||||
expect(questions).toHaveLength(1);
|
||||
expect(questions[0]).toMatchObject({
|
||||
requestId: "question-1",
|
||||
tool: { callID: "call-1" },
|
||||
status: "pending",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not replace an actionable question request with a later tool-call placeholder", () => {
|
||||
const questions = upsertBackendQuestion(
|
||||
[
|
||||
{
|
||||
requestId: "question-1",
|
||||
sessionId: "session-1",
|
||||
questions: [
|
||||
{
|
||||
header: "测试问题",
|
||||
question: "你觉得这个 question 工具好用吗?",
|
||||
options: [{ label: "非常好用", description: "交互清晰,选项方便" }],
|
||||
},
|
||||
],
|
||||
tool: { messageID: "message-1", callID: "call-1" },
|
||||
createdAt: 123,
|
||||
status: "pending",
|
||||
},
|
||||
],
|
||||
{
|
||||
session_id: "session-1",
|
||||
request_id: "call-1",
|
||||
questions: [
|
||||
{
|
||||
header: "测试问题",
|
||||
question: "你觉得这个 question 工具好用吗?",
|
||||
options: [{ label: "非常好用", description: "交互清晰,选项方便" }],
|
||||
},
|
||||
],
|
||||
tool: { messageID: "message-1", callID: "call-1" },
|
||||
created_at: 456,
|
||||
},
|
||||
);
|
||||
|
||||
expect(questions).toHaveLength(1);
|
||||
expect(questions[0]).toMatchObject({
|
||||
requestId: "question-1",
|
||||
tool: { callID: "call-1" },
|
||||
status: "pending",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("cancelBackendTodos", () => {
|
||||
it("marks pending and in-progress todos as cancelled", () => {
|
||||
const cancelled = cancelBackendTodos([
|
||||
{
|
||||
sessionId: "session-1",
|
||||
todos: [
|
||||
{ id: "todo-1", content: "分析水位", status: "in_progress" },
|
||||
{ id: "todo-2", content: "生成建议", status: "pending" },
|
||||
{ id: "todo-3", content: "完成报告", status: "completed" },
|
||||
],
|
||||
createdAt: 123,
|
||||
},
|
||||
]);
|
||||
|
||||
expect(cancelled).toEqual([
|
||||
expect.objectContaining({
|
||||
todos: [
|
||||
expect.objectContaining({
|
||||
id: "todo-1",
|
||||
status: "cancelled",
|
||||
updatedAt: expect.any(Number),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
id: "todo-2",
|
||||
status: "cancelled",
|
||||
updatedAt: expect.any(Number),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
id: "todo-3",
|
||||
status: "completed",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user