An annual report's questions live in a consultation conversation bound to the report by chat_sessions.report_id (one per report, guarded by a trigger); no settlement function is redefined. The consult route hands every turn of such a conversation to the annual handler, which reads only the saved report, checks dates and placements against what it read, and settles the fixed sentence and feedback-only turns free. The page has an entry per written section, a page-level entry in the title bar, passage selection and the shared panel or bottom sheet. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
105 lines
7.5 KiB
TypeScript
105 lines
7.5 KiB
TypeScript
import assert from "node:assert/strict";
|
||
import { readFileSync } from "node:fs";
|
||
import test from "node:test";
|
||
import { completeUsage } from "../src/lib/consultation-billing.ts";
|
||
|
||
const root = new URL("../", import.meta.url);
|
||
const consultRoute = readFileSync(new URL("src/app/api/consult/route.ts", root), "utf8");
|
||
const consultSettlement = readFileSync(new URL("src/lib/consult/settlement.ts", root), "utf8");
|
||
const packagesRoute = readFileSync(new URL("src/app/api/admin/packages/route.ts", root), "utf8");
|
||
|
||
test("standard consultation resolves and settles the session-pinned model version", () => {
|
||
assert.match(consultRoute, /sessionId: z\.string\(\)\.uuid\(\)/);
|
||
// Former value: select("id,model_id,model_config_version,session_type,messages").
|
||
// First-round session titles need the current title, theme, and chart role.
|
||
// 原值: select includes chart_profile_role but not chart_profile_id or chart_profile_name.
|
||
// 新值: the same select also reads chart_profile_id and chart_profile_name.
|
||
// 原因: ordinary chat resolves the subject from the stored binding, not from chart_profile_role alone.
|
||
// 原值: select 到 context_summary 结束
|
||
// 新值: 后面加上 synastry_report_id,synastry_section,synastry_partner_subject_id
|
||
// 原因: 合盘追问要在同一条会话读取里认出报告和节,普通咨询仍用原来的列
|
||
// 原值: 读会话时不取 report_id;新值: 多取 report_id;原因: BUG-2085,绑定了报告的对话一律交给报告的处理函数。
|
||
assert.match(consultRoute, /select\("id,model_id,model_config_version,session_type,messages,title,theme,chart_profile_id,chart_profile_name,chart_profile_role,context_summary,synastry_report_id,synastry_section,synastry_partner_subject_id,report_id"\)/);
|
||
assert.match(consultRoute, /resolveSessionLanguageModel\(\s*chatSession\.model_id,\s*chatSession\.model_config_version,?\s*\)/);
|
||
// 原值: route.ts 的 usagePayload 写 actualModelId 与 modelConfigVersion
|
||
// 新值: 这两字段在 settlement.ts 的 usagePayload
|
||
// 原因: 用量载荷搬进结算工厂
|
||
assert.match(consultSettlement, /actualModelId: selectedModel\.id/);
|
||
assert.match(consultSettlement, /modelConfigVersion: selectedModel\.configVersion/);
|
||
// 原值: 守卫 .eq("title", expectedTitle) 用 RPC 前快照,append_consultation_question 已改写标题,更新恒 0 行
|
||
// 新值: shouldGenerate 仍用 RPC 前标题;守卫比较 RPC 后再 select 到的 title
|
||
// 原因: BUG-557,模型标题必须能在刷新前落库
|
||
assert.match(consultRoute, /const expectedTitle = typeof chatSession\.title === "string" \? chatSession\.title : ""/);
|
||
assert.match(consultRoute, /shouldGenerateSessionTitle\(\{\s*title: expectedTitle,/);
|
||
assert.match(consultRoute, /expectedTitle: titleAfterRpc/);
|
||
assert.match(consultRoute, /persistGuardedSessionTitle/);
|
||
});
|
||
|
||
test("standard consultation awaits real usage before durable response settlement", () => {
|
||
assert.doesNotMatch(consultRoute, /recordActualUsage|void usage\.then/);
|
||
assert.doesNotMatch(consultRoute, /inputTokens: 0,[\s\S]*outputTokens: 0,[\s\S]*costMicrousd: 0/);
|
||
// 原值: route.ts 里 async function usagePayload 的函数体含 mergeUsage
|
||
// 新值: 函数体在 settlement.ts;route.ts 转调用 consultSettlement.usagePayload,完成回答仍 await usagePayload 再写入 p_actual_usage
|
||
// 原因: 用量载荷搬进结算工厂,完成回答留在 route
|
||
assert.match(consultRoute, /return consultSettlement\.usagePayload\(usage\)/);
|
||
assert.match(consultSettlement, /async function usagePayload\(usage: Promise<\{ inputTokens\?: number; outputTokens\?: number \}>\)/);
|
||
// 原值 await usage;新值等待咨询与分类 usage 合并;原因:分类成本也必须结算。
|
||
assert.match(consultSettlement, /const resolved = await mergeUsage\(\[usage, Promise\.resolve\(classificationUsage\)\]\);/);
|
||
assert.match(consultRoute, /const actualUsage = await usagePayload\(usage\);[\s\S]*p_actual_usage: actualUsage/);
|
||
assert.match(consultSettlement, /export function mergeUsage\(usages: Promise<Usage>\[\]\): Promise<Usage> \{[\s\S]*Promise\.all\(usages\)/);
|
||
// Former: three agentic first streams each had `usages.push(result.totalUsage)`.
|
||
// New: the three first streams share streamWithOverflowRetry, which pushes the
|
||
// successful first attempt (and the overflow retry under a different name).
|
||
// Reason: context overflow must retry once on the same request.
|
||
assert.equal(consultRoute.match(/usages\.push\(result\.totalUsage\)/g)?.length, 1);
|
||
assert.match(consultRoute, /streamWithOverflowRetry/);
|
||
assert.match(consultRoute, /isContextOverflowError/);
|
||
// Three agentic first streams: public/general, declared-window, and natal.
|
||
// Window and natal each have a contract retry plus an answer retry; general
|
||
// has only an answer retry. Every one of those model calls spends tokens.
|
||
assert.equal(consultRoute.match(/usages\.push\(retried\.totalUsage\)/g)?.length, 5);
|
||
// 原值: /const retryForAnswer = async \(\) => \{/ 三处
|
||
// 新值: /const retryForAnswer = async \(retryHint\?: string\) => \{/ 三处
|
||
// 原因: BUG-1053 删除 compose 后,Pass 4 整篇被拒的重写提示改由 answer retry 携带;三处回答重试仍各计一次 usage
|
||
assert.equal(consultRoute.match(/const retryForAnswer = async \(retryHint\?: string\) => \{/g)?.length, 3);
|
||
});
|
||
|
||
test("standard consultation forwards its stable reservation request as the usage event key", async () => {
|
||
const eventKey = "00000000-0000-4000-8000-000000000002";
|
||
const calls: Record<string, unknown>[] = [];
|
||
const accounting = {
|
||
async rpc(_rpcName: string, args: Record<string, unknown>) {
|
||
calls.push(args);
|
||
return {
|
||
data: { success: true, reservation_id: "00000000-0000-4000-8000-000000000003", credits: 9, error_code: null },
|
||
error: null,
|
||
};
|
||
},
|
||
};
|
||
const usage = { eventKey, actualModelId: "model", inputTokens: 1, outputTokens: 2, costMicrousd: 3, durationMs: 4 };
|
||
|
||
await completeUsage(accounting, "00000000-0000-4000-8000-000000000001", eventKey, usage);
|
||
await completeUsage(accounting, "00000000-0000-4000-8000-000000000001", eventKey, usage);
|
||
|
||
assert.deepEqual(calls.map((call) => (call.p_actual_usage as { eventKey: string }).eventKey), [eventKey, eventKey]);
|
||
// 原值: route.ts 含 eventKey: requestId
|
||
// 新值: settlement.ts 的 usagePayload 含 eventKey: requestId;route.ts 仍把 usagePayload 的结果写入 p_actual_usage
|
||
// 原因: 用量载荷搬进结算工厂,完成回答仍用这份载荷
|
||
assert.match(consultSettlement, /eventKey: requestId,/);
|
||
assert.match(consultRoute, /const actualUsage = await usagePayload\(usage\);[\s\S]*p_actual_usage: actualUsage/);
|
||
assert.doesNotMatch(consultSettlement, /eventKey:\s*(?:globalThis\.)?crypto\.randomUUID\(\)/);
|
||
assert.doesNotMatch(consultRoute, /eventKey:\s*(?:globalThis\.)?crypto\.randomUUID\(\)/);
|
||
});
|
||
|
||
test("legacy admin packages cannot mutate detached payment_packages", () => {
|
||
assert.doesNotMatch(packagesRoute, /payment_packages|queryAdminRows|insert into|update public/);
|
||
assert.match(packagesRoute, /export function GET\(request: Request\)/);
|
||
assert.match(packagesRoute, /const replacement = "\/api\/admin\/products"/);
|
||
assert.match(packagesRoute, /NextResponse\.redirect\(new URL\(replacement, request\.url\), 308\)/);
|
||
for (const method of ["POST", "PATCH", "DELETE"]) {
|
||
assert.match(packagesRoute, new RegExp(`export function ${method}\\(\\)`));
|
||
}
|
||
assert.match(packagesRoute, /status: 410/);
|
||
assert.match(packagesRoute, /error: "旧套餐写接口已停用,请使用统一商品管理。",[\s\S]*replacement,/);
|
||
});
|