feat(chat): 支持角色继续生成并保留前文
- 新增 continue 模式,不插入用户台词,沿用生成租约、限流和停止逻辑 - 重新生成仅替换末段,并补充真实路由回归和 README 接口说明
This commit is contained in:
@@ -0,0 +1,242 @@
|
||||
/** NPC 继续生成的真实路由回归:不插入用户台词、保留上一段,并沿用租约与鉴权。 */
|
||||
import "./digital-env";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { createApp } from "../src/app";
|
||||
import { pool } from "../src/db/pool";
|
||||
import { env } from "../src/config/env";
|
||||
import { authService } from "../src/modules/auth/auth.service";
|
||||
import type { PromptMessage } from "../src/modules/digital/digital.prompt";
|
||||
|
||||
type Last = {
|
||||
role: string;
|
||||
content: string;
|
||||
status: string;
|
||||
sequence_id: number;
|
||||
};
|
||||
/** 夹具只替换数据库和上游模型,路由校验、事务、提示词和 SSE 编排执行真实代码。 */
|
||||
async function exercise(
|
||||
t: TestContext,
|
||||
mode: "continue" | "regenerate",
|
||||
last: Last | null,
|
||||
lease = true,
|
||||
) {
|
||||
const original = env.DEEPSEEK_API_KEY;
|
||||
env.DEEPSEEK_API_KEY = "unit-test-no-network";
|
||||
t.after(() => {
|
||||
env.DEEPSEEK_API_KEY = original;
|
||||
});
|
||||
const writes: { sql: string; args: unknown[] }[] = [];
|
||||
let upstream: PromptMessage[] | undefined,
|
||||
rolledBack = false;
|
||||
const query = async (q: { sql: string }, args: unknown[]) => {
|
||||
const sql = q.sql;
|
||||
if (sql.startsWith("SELECT * FROM dh_conversations"))
|
||||
return [
|
||||
[
|
||||
{
|
||||
id: "continue-unit",
|
||||
account: "employee:1",
|
||||
character_id: "card",
|
||||
settings: {},
|
||||
},
|
||||
],
|
||||
[],
|
||||
];
|
||||
if (sql.startsWith("SELECT * FROM dh_content"))
|
||||
return [[{ id: "card", name: "验收角色", body: { cover: "" } }], []];
|
||||
if (sql.includes("FROM dh_scenes")) return [[], []];
|
||||
if (sql.includes("SELECT COUNT(*)")) return [[{ n: 0 }], []];
|
||||
if (
|
||||
sql.startsWith("SELECT role,content,status") ||
|
||||
sql.startsWith("SELECT role,sequence_id")
|
||||
)
|
||||
return [last ? [last] : [], []];
|
||||
if (
|
||||
sql.startsWith("SELECT id FROM dh_messages") &&
|
||||
sql.includes("role='user'")
|
||||
)
|
||||
return [[{ id: "previous-user" }], []];
|
||||
if (sql.startsWith("SELECT id FROM dh_messages")) return [[], []];
|
||||
if (sql.startsWith("SELECT role,content,pinned"))
|
||||
return [
|
||||
[
|
||||
{
|
||||
role: "assistant",
|
||||
content: "角色上一段,不能丢失或重述。",
|
||||
pinned: 0,
|
||||
sequence_id: 3,
|
||||
},
|
||||
],
|
||||
[],
|
||||
];
|
||||
if (sql.startsWith("SELECT content FROM dh_messages")) return [[], []];
|
||||
if (sql.startsWith("INSERT") || sql.startsWith("UPDATE")) {
|
||||
writes.push({ sql, args });
|
||||
return [
|
||||
{
|
||||
affectedRows:
|
||||
sql.startsWith("UPDATE dh_conversations SET lease_id=?") && !lease
|
||||
? 0
|
||||
: 1,
|
||||
},
|
||||
[],
|
||||
];
|
||||
}
|
||||
throw new Error("未覆盖 SQL:" + sql);
|
||||
};
|
||||
t.mock.method(pool, "query", query);
|
||||
t.mock.method(pool, "getConnection", async () => ({
|
||||
query,
|
||||
beginTransaction: async () => {},
|
||||
commit: async () => {},
|
||||
rollback: async () => {
|
||||
rolledBack = true;
|
||||
},
|
||||
release: () => {},
|
||||
}));
|
||||
t.mock.method(authService, "getCurrentUser", async () => ({
|
||||
accountType: "EMPLOYEE",
|
||||
}));
|
||||
t.mock.method(
|
||||
globalThis,
|
||||
"fetch",
|
||||
async (_url: unknown, init: RequestInit) => {
|
||||
upstream = JSON.parse(String(init.body)).messages;
|
||||
assert.ok(init.signal, "继续沿用取消/超时信号");
|
||||
return new Response(
|
||||
'data: {"choices":[{"delta":{"content":"角色接着说的新段落。"}}]}\n\ndata: [DONE]\n\n',
|
||||
{ headers: { "Content-Type": "text/event-stream" } },
|
||||
);
|
||||
},
|
||||
);
|
||||
const app = createApp();
|
||||
try {
|
||||
await app.ready();
|
||||
const token = app.jwt.sign({ sub: "employee:1", accountType: "EMPLOYEE" });
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/digital/conversations/continue-unit/stream",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { mode, content: "", requestId: randomUUID() },
|
||||
});
|
||||
return { response, writes, upstream, rolledBack };
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
}
|
||||
|
||||
test("未发送过用户台词也可接着角色问候继续,只新增 assistant 消息", async (t) => {
|
||||
const result = await exercise(t, "continue", {
|
||||
role: "assistant",
|
||||
content: "你好,我想告诉你一件事。",
|
||||
status: "complete",
|
||||
sequence_id: 1,
|
||||
});
|
||||
assert.equal(result.response.statusCode, 200);
|
||||
assert.match(result.response.body, /event: done/);
|
||||
assert.match(result.response.body, /角色接着说的新段落/);
|
||||
assert.equal(
|
||||
result.writes.filter((w) => w.sql.startsWith("INSERT INTO dh_messages"))
|
||||
.length,
|
||||
1,
|
||||
);
|
||||
assert.ok(
|
||||
result.writes.some((w) => w.sql.includes("'assistant','','generating'")),
|
||||
);
|
||||
assert.ok(
|
||||
!result.writes.some(
|
||||
(w) => w.sql.includes("'user'") || w.sql.includes("superseded"),
|
||||
),
|
||||
);
|
||||
assert.ok(
|
||||
result.upstream?.some(
|
||||
(m) => m.role === "assistant" && m.content.includes("上一段"),
|
||||
),
|
||||
);
|
||||
assert.match(result.upstream!.at(-1)!.content, /不是用户在故事中的发言/);
|
||||
assert.match(result.upstream!.at(-1)!.content, /不要替用户说话/);
|
||||
assert.ok(
|
||||
result.writes.some(
|
||||
(w) =>
|
||||
w.sql.startsWith("UPDATE dh_messages SET content") &&
|
||||
w.args[0] === "角色接着说的新段落。",
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test("停止后已有内容可以继续,原回复不被替换", async (t) => {
|
||||
const r = await exercise(t, "continue", {
|
||||
role: "assistant",
|
||||
content: "尚未说完的一段",
|
||||
status: "stopped",
|
||||
sequence_id: 9,
|
||||
});
|
||||
assert.equal(r.response.statusCode, 200);
|
||||
assert.ok(!r.writes.some((w) => w.sql.includes("superseded")));
|
||||
});
|
||||
|
||||
for (const last of [
|
||||
null,
|
||||
{ role: "user", content: "用户最后发言", status: "complete", sequence_id: 1 },
|
||||
{ role: "assistant", content: "", status: "failed", sequence_id: 2 },
|
||||
]) {
|
||||
test(`没有可接续的角色内容时拒绝继续:${last?.role ?? "空会话"}/${last?.status ?? "空"}`, async (t) => {
|
||||
const r = await exercise(t, "continue", last);
|
||||
assert.equal(r.response.statusCode, 400);
|
||||
assert.equal(r.upstream, undefined);
|
||||
assert.equal(r.rolledBack, true);
|
||||
assert.ok(
|
||||
!r.writes.some((w) => w.sql.startsWith("INSERT INTO dh_messages")),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
test("已有生成租约时继续被拒绝,不双发", async (t) => {
|
||||
const r = await exercise(
|
||||
t,
|
||||
"continue",
|
||||
{
|
||||
role: "assistant",
|
||||
content: "上一段",
|
||||
status: "complete",
|
||||
sequence_id: 3,
|
||||
},
|
||||
false,
|
||||
);
|
||||
assert.equal(r.response.statusCode, 409);
|
||||
assert.equal(r.upstream, undefined);
|
||||
});
|
||||
|
||||
test("重新生成最后一段,不清除此前继续生成的段落", async (t) => {
|
||||
const r = await exercise(t, "regenerate", {
|
||||
role: "assistant",
|
||||
content: "待替换的最后一段",
|
||||
status: "complete",
|
||||
sequence_id: 8,
|
||||
});
|
||||
assert.equal(r.response.statusCode, 200);
|
||||
const update = r.writes.find((w) => w.sql.includes("superseded"));
|
||||
assert.match(update!.sql, /sequence_id=\?/);
|
||||
assert.equal(update!.args[1], 8);
|
||||
assert.ok(
|
||||
r.upstream?.some(
|
||||
(m) => m.role === "assistant" && m.content.includes("上一段"),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test("匿名继续请求仍被拒绝", async () => {
|
||||
const app = createApp();
|
||||
try {
|
||||
const r = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/digital/conversations/continue-unit/stream",
|
||||
payload: { mode: "continue", requestId: randomUUID() },
|
||||
});
|
||||
assert.equal(r.statusCode, 401);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user