2e3a7c0a7e
保留已有ui/chat场景与分组,支持命名、创建和停用;同一应用接入点实验互斥,保护历史场景类型与运行实验;增加自定义场景决策回归。
333 lines
8.8 KiB
TypeScript
333 lines
8.8 KiB
TypeScript
/** 数字人核心规则回归:分流域隔离、人群边界、世界书预算、SSE分片和鉴权。 */
|
|
import "./digital-env";
|
|
import test from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import { bucket, eligible } from "../src/modules/digital/digital.experiments";
|
|
import {
|
|
assemblePrompt,
|
|
selectLore,
|
|
} from "../src/modules/digital/digital.prompt";
|
|
import {
|
|
contentSchema,
|
|
entrySchema,
|
|
experimentSchema,
|
|
} from "../src/modules/digital/digital.schema";
|
|
import { completionDeltas } from "../src/modules/digital/digital.chat";
|
|
import { createApp } from "../src/app";
|
|
const config = experimentSchema.parse({
|
|
name: "test",
|
|
scope: "ui",
|
|
config: { audience: "all" },
|
|
}).config;
|
|
test("新老用户在注册分界精确互补,指定名单不能混入其他账号", () => {
|
|
const cutoff = "2026-10-26T00:00:00.000Z";
|
|
assert.equal(
|
|
eligible({ ...config, audience: "new", cutoff }, "employee:1", cutoff),
|
|
true,
|
|
);
|
|
assert.equal(
|
|
eligible({ ...config, audience: "existing", cutoff }, "employee:1", cutoff),
|
|
false,
|
|
);
|
|
assert.equal(
|
|
eligible(
|
|
{ ...config, audience: "existing", cutoff },
|
|
"employee:1",
|
|
"2026-10-25T23:59:59.999Z",
|
|
),
|
|
true,
|
|
);
|
|
assert.equal(
|
|
eligible({ ...config, audience: "new" }, "employee:1", cutoff),
|
|
false,
|
|
);
|
|
assert.equal(
|
|
eligible(
|
|
{ ...config, audience: "specified", accounts: ["employee:1"] },
|
|
"super_admin:1",
|
|
cutoff,
|
|
),
|
|
false,
|
|
);
|
|
});
|
|
test("独立流量和变体哈希在10%流量下仍覆盖两组且稳定", () => {
|
|
let enrolled = 0,
|
|
b = 0;
|
|
for (let i = 0; i < 20000; i++) {
|
|
const account = `employee:${i}`;
|
|
const n = bucket("exp", account, "traffic");
|
|
assert.equal(n, bucket("exp", account, "traffic"));
|
|
if (n < 1000) {
|
|
enrolled++;
|
|
if (bucket("exp", account, "variant") < 5000) b++;
|
|
}
|
|
}
|
|
assert.ok(enrolled > 1700 && enrolled < 2300);
|
|
assert.ok(b / enrolled > 0.45 && b / enrolled < 0.55);
|
|
assert.notEqual(
|
|
bucket("exp", "employee:1", "variant"),
|
|
bucket("exp", "super_admin:1", "variant"),
|
|
);
|
|
});
|
|
test("世界书按优先级入预算、支持次关键词、扫描深度和禁用", () => {
|
|
const entries = [
|
|
entrySchema.parse({
|
|
id: "a",
|
|
name: "高",
|
|
keys: ["灯塔"],
|
|
content: "蓝光",
|
|
priority: 200,
|
|
}),
|
|
entrySchema.parse({
|
|
id: "b",
|
|
name: "低",
|
|
keys: ["灯塔"],
|
|
content: "低优先级",
|
|
priority: 10,
|
|
}),
|
|
entrySchema.parse({
|
|
id: "c",
|
|
name: "次词",
|
|
keys: ["灯塔"],
|
|
secondaryKeys: ["口令"],
|
|
content: "秘密",
|
|
priority: 500,
|
|
}),
|
|
entrySchema.parse({
|
|
id: "d",
|
|
name: "禁用",
|
|
constant: true,
|
|
content: "不要出现",
|
|
enabled: false,
|
|
}),
|
|
];
|
|
assert.deepEqual(
|
|
selectLore(entries, [{ role: "user", content: "灯塔" }], 3).map(
|
|
(v) => v.id,
|
|
),
|
|
["a"],
|
|
);
|
|
assert.deepEqual(
|
|
selectLore(entries, [{ role: "user", content: "灯塔口令" }], 4).map(
|
|
(v) => v.id,
|
|
),
|
|
["c", "a"],
|
|
);
|
|
const recent = entrySchema.parse({
|
|
id: "last",
|
|
name: "近期",
|
|
keys: ["灯塔"],
|
|
content: "x",
|
|
scanDepth: 1,
|
|
});
|
|
assert.equal(
|
|
selectLore(
|
|
[recent],
|
|
[
|
|
{ role: "user", content: "灯塔" },
|
|
{ role: "assistant", content: "你好" },
|
|
],
|
|
100,
|
|
).length,
|
|
0,
|
|
);
|
|
});
|
|
test("超长角色不能突破上下文预算,最新用户输入保留", () => {
|
|
const card = {
|
|
...contentSchema.shape.body.parse({
|
|
cover: "",
|
|
description: "角".repeat(12000),
|
|
personality: "人".repeat(12000),
|
|
}),
|
|
name: "角色",
|
|
};
|
|
const preset = contentSchema.shape.body.parse({
|
|
cover: "",
|
|
contextBudget: 6000,
|
|
});
|
|
const latest = "用".repeat(4000);
|
|
const result = assemblePrompt(
|
|
card,
|
|
preset,
|
|
[],
|
|
[{ role: "user", content: latest }],
|
|
{ persona: "", userName: "旅人", memory: "" },
|
|
[],
|
|
);
|
|
assert.ok(result.characters <= 6000);
|
|
assert.equal(result.messages.at(-1)?.content, latest);
|
|
});
|
|
test("SSE中文跨字节分片仍只返回正文,不转发思考内容", async () => {
|
|
const raw = new TextEncoder().encode(
|
|
'data: {"choices":[{"delta":{"reasoning_content":"hidden"}}]}\n\ndata: {"choices":[{"delta":{"content":"你好🌙"}}]}\n\ndata: [DONE]\n\n',
|
|
);
|
|
const stream = new ReadableStream<Uint8Array>({
|
|
start(c) {
|
|
for (let i = 0; i < raw.length; i += 3) c.enqueue(raw.slice(i, i + 3));
|
|
c.close();
|
|
},
|
|
});
|
|
let text = "";
|
|
for await (const delta of completionDeltas(stream)) text += delta;
|
|
assert.equal(text, "你好🌙");
|
|
});
|
|
test("数字人及后台接口不接受匿名请求", async () => {
|
|
const app = createApp();
|
|
try {
|
|
for (const url of [
|
|
"/api/digital/bootstrap",
|
|
"/api/digital/conversations",
|
|
"/api/digital-admin/content",
|
|
"/api/digital-admin/experiments",
|
|
]) {
|
|
const r = await app.inject({ method: "GET", url });
|
|
assert.equal(r.statusCode, 401, url);
|
|
}
|
|
} finally {
|
|
await app.close();
|
|
}
|
|
});
|
|
|
|
test("上游未发送完成标记的断流不得误报成功", async () => {
|
|
const raw = new TextEncoder().encode(
|
|
'data: {"choices":[{"delta":{"content":"partial"}}]}\n\n',
|
|
);
|
|
const stream = new ReadableStream<Uint8Array>({
|
|
start(c) {
|
|
c.enqueue(raw);
|
|
c.close();
|
|
},
|
|
});
|
|
await assert.rejects(async () => {
|
|
for await (const _ of completionDeltas(stream)) {
|
|
}
|
|
}, /before completion/);
|
|
});
|
|
test("角色输入拒绝未成年和前台外部执行资源", () => {
|
|
assert.throws(() =>
|
|
contentSchema.parse({
|
|
kind: "character",
|
|
name: "test",
|
|
body: { cover: "", age: 17 },
|
|
}),
|
|
);
|
|
assert.throws(() =>
|
|
contentSchema.parse({
|
|
kind: "character",
|
|
name: "test",
|
|
body: { cover: "javascript:alert(1)" },
|
|
}),
|
|
);
|
|
const parsed = contentSchema.parse({
|
|
kind: "character",
|
|
name: "test",
|
|
body: { cover: "", experimentVariant: "B" },
|
|
});
|
|
assert.equal("experimentVariant" in parsed.body, false);
|
|
});
|
|
|
|
test("用户消息中的占位符保持原样,避免内容意外膨胀或被改写", () => {
|
|
const body = contentSchema.shape.body.parse({ cover: "" });
|
|
const latest = "{{user}}".repeat(500);
|
|
const result = assemblePrompt(
|
|
{ ...body, name: "角色" },
|
|
body,
|
|
[],
|
|
[{ role: "user", content: latest }],
|
|
{ persona: "", userName: "名".repeat(60), memory: "" },
|
|
[],
|
|
);
|
|
assert.equal(result.messages.at(-1)?.content, latest);
|
|
assert.ok(result.characters <= body.contextBudget);
|
|
});
|
|
test("空正文增量不触发前台打字", async () => {
|
|
const raw = new TextEncoder().encode(
|
|
'data: {"choices":[{"delta":{"content":""}}]}\n\ndata: [DONE]\n\n',
|
|
);
|
|
const stream = new ReadableStream<Uint8Array>({
|
|
start(c) {
|
|
c.enqueue(raw);
|
|
c.close();
|
|
},
|
|
});
|
|
const chunks = [];
|
|
for await (const text of completionDeltas(stream)) chunks.push(text);
|
|
assert.deepEqual(chunks, []);
|
|
});
|
|
test("员工即使持有旧管理员权限声明,也不能进入数字人运营接口", async () => {
|
|
const { authService } = await import("../src/modules/auth/auth.service");
|
|
const original = authService.getCurrentUser;
|
|
authService.getCurrentUser = async () => ({
|
|
id: 99,
|
|
username: "unit",
|
|
displayName: "unit",
|
|
accountType: "EMPLOYEE",
|
|
roles: [],
|
|
permissions: ["*"],
|
|
canManage: true,
|
|
});
|
|
const app = createApp();
|
|
try {
|
|
await app.ready();
|
|
const token = app.jwt.sign({
|
|
sub: "employee:99",
|
|
employeeId: 99,
|
|
accountType: "EMPLOYEE",
|
|
scene: "EMPLOYEE_APP",
|
|
username: "unit",
|
|
roleCodes: ["admin"],
|
|
permissions: ["*"],
|
|
canManage: true,
|
|
});
|
|
for (const url of [
|
|
"/api/digital-admin/content",
|
|
"/api/digital-admin/experiments",
|
|
])
|
|
assert.equal(
|
|
(
|
|
await app.inject({
|
|
method: "GET",
|
|
url,
|
|
headers: { authorization: `Bearer ${token}` },
|
|
})
|
|
).statusCode,
|
|
403,
|
|
);
|
|
} finally {
|
|
authService.getCurrentUser = original;
|
|
await app.close();
|
|
}
|
|
});
|
|
|
|
test("自定义场景按应用接入点生效,停用场景不再参与决策", async () => {
|
|
const { activeExperiment } = await import(
|
|
"../src/modules/digital/digital.experiments"
|
|
);
|
|
const custom = {
|
|
id: "e1",
|
|
scope: "my-ui-scene",
|
|
runtime: "ui",
|
|
sceneEnabled: 1,
|
|
state: "running",
|
|
};
|
|
const disabled = {
|
|
...custom,
|
|
id: "e2",
|
|
scope: "disabled-scene",
|
|
sceneEnabled: 0,
|
|
};
|
|
const chat = { ...custom, id: "e3", runtime: "chat" };
|
|
const list = [disabled, chat, custom] as Parameters<
|
|
typeof activeExperiment
|
|
>[0];
|
|
assert.equal(activeExperiment(list, "ui")?.id, "e1");
|
|
assert.equal(activeExperiment(list, "chat")?.id, "e3");
|
|
assert.equal(
|
|
activeExperiment(
|
|
[disabled] as Parameters<typeof activeExperiment>[0],
|
|
"ui",
|
|
),
|
|
undefined,
|
|
);
|
|
});
|