Compare commits

..
Author SHA1 Message Date
ClaudeandClaude Fable 5.2 a63d85f279 fix: admin shows estimated cost before usage exists, lists only real feature flags (BUG-1937)
Independent Staging Quality Gate / validate-frontend (push) Successful in 5m53s
Independent Staging Quality Gate / validate-python (push) Successful in 7m36s
Independent Staging Quality Gate / publish (push) Successful in 3m2s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXp2Vp62Ur3C7yRWQdSq
2026-11-16 16:30:27 +08:00
ClaudeandClaude Fable 5.2 a814661ddb fix: admin role could not read usage tables behind row-level security (BUG-1935)
Independent Staging Quality Gate / validate-frontend (push) Successful in 5m32s
Independent Staging Quality Gate / validate-python (push) Successful in 6m54s
Independent Staging Quality Gate / publish (push) Successful in 3m8s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXp2Vp62Ur3C7yRWQdSq
2026-11-16 16:18:09 +08:00
10 changed files with 316 additions and 207 deletions
+24
View File
@@ -26035,3 +26035,27 @@
- 验证与防复发:公开测试盘父母题本地样本(DeepSeek):改前 3 份每份 2 处「这条线」,改后 4 份合计 1 处;「底色」和补充套话改后 0 处。相关断言随新字句更新(原值 / 新值 / 原因写在测试注释里),问答测试 808 通过。未解决:「判断依据」里仍会出现 Narayana 的内部状态用语(该句受占星师裁定约束,未动)。Gemini 中转当天在本地只返回几百字的短答案(未改动的代码同样如此),因此没有 Gemini 的改后样本。
- 关联记录:BUG-1929、BUG-1928、BUG-1920。
- 修复版本:`claude/echo-words-1930`,待 staging 实测。
## BUG-1935 | 后台「用量和成本」、上线配置的实测成本和毛利、订阅列表一直是空的
- 状态:fixed-pending-verify(待 staging 实测)。
- 首次发现 / 最近更新:2026-11-16 / 2026-11-16。
- 触发与现象:产品负责人在 staging 后台填好模型输入、输出单价后,上线配置页四项功能的实测成本都显示「还没有数据」、毛利「算不出」;用量和成本页也没有记录。当天他在同一环境完成过多次聊天。用量聚合接口返回八项功能 runs 全为 0。
- 触发条件:self-hosted 环境(后台用 `admin_runtime` 角色读库)下,后台读取 `usage_ledger`、`usage_reservations`、`usage_events`、`user_subscriptions`、`user_product_redemptions`、`notification_templates`、`pricing_experiment_events`。
- 根因:这些表启用了行级安全,迁移只给 `admin_runtime` 授了 SELECT,没有建它的 SELECT 策略;读取不报错,只是被静默过滤成 0 行。与 BUG-147 同一根因;当时只补了出问题的那几张表,没有检查其余授权表,之后 `feature_pricing`、`feature_flags` 又各补过一次,仍没有全量核对。
- 修复:新迁移给上述七张表各建 `<表名>_admin_read` 策略(`for select to admin_runtime using (true)`)。
- 验证与防复发:新增 `frontend/tests/admin-runtime-read-policies-20261116.test.ts`,扫描全部迁移:凡启用行级安全且授予 `admin_runtime` SELECT 的表都必须有它的策略,否则失败。线上效果待部署后由产品负责人在后台确认(本会话没有后台和数据库权限)。
- 关联记录:BUG-147、BUG-135。
- 修复版本:`claude/admin-usage-rls-1935`,待 staging 实测。
## BUG-1937 | 后台上线配置的成本和毛利在没有用量时是空的;功能开关页可以新增没人读的开关;对话质量页不说明何时有记录
- 状态:fixed-pending-verify(待 staging 实测)。
- 首次发现 / 最近更新:2026-11-16 / 2026-11-16。
- 触发与现象:产品负责人填好模型单价后,上线配置页成本显示「还没有数据」、毛利「算不出」(读不到用量是 BUG-1935;这里是页面本身在没有用量时不给任何数)。功能开关页有新增、编辑草稿、灰度百分比、配置 JSON 和发布,他不知道怎么用;对话质量记录页是空的,也没有说明。
- 触发条件:上线前(没有实测用量)定价;任何管理员打开功能开关页或对话质量页。
- 根因:上线配置页只在有结算记录时显示成本,而定价恰恰发生在没有记录的时候;单价填好之前结算的请求成本为 0,也被当成实测。功能开关页是通用编辑器,产品实际只读四个开关键,新增的键没有代码读取,且开关要「启用且灰度 100% 且已发布」才算开,页面没有说明。对话质量记录只在用户点踩时写入,页面没有说明。
- 修复:上线配置页的成本改为「有带价格的实测用实测,否则按默认模型单价乘以一次成功生成的典型字数估算」,分别标(实测)(估算);实测为 0 时不采用。功能开关页改为固定列出产品实际读取的四个开关,每个一个开关按钮和一句「关掉会怎样」,拨动即保存并发布(开 = 启用且 100%);去掉新增、灰度和配置 JSON。对话质量页加一句说明。
- 验证与防复发:`frontend/tests/admin-clarity-20261116.test.ts`:估算与实测的取舍;开关清单必须与代码里实际读取的开关键一致(以后新增读取点而不加到清单会失败);页面不再出现新增和配置 JSON。典型字数是 2026-11-16 本地各一份样本的量(聊天 10 万入 / 1.3 万出,个人报告 12.6 万 / 3.3 万,年运 10.8 万 / 8.6 万,合盘 36 万 / 10.2 万),不含失败重试,只作估算。后台页面本会话无登录权限,未在真实页面上操作过。
- 关联记录:BUG-1935、BUG-1922。
- 修复版本:`claude/admin-clarity-1936`(分支名沿用旧编号),待 staging 实测。
@@ -1,80 +0,0 @@
# 生时纠正页面:讲清哪些方面受影响,并让用户自己选线前线后(2026-11-16,Claude)
Bug 编号:BUG-1936。关联 BUG-1890(#279)、BUG-1896(#292)、BUG-1925(#294)。
## 背景
#292 停掉问答后,生时纠正页面只剩「显示时间、选范围、看六张盘、用这个时间」,用户进来没有任何结果。产品负责人 11-16 的决定:
1. 页面要直接讲清:哪些方面不受时间范围影响,哪些方面会因为差几分钟而不同,分别差在哪条线上、线前线后各是什么。
2. **允许用户自己选线前还是线后。** 这是用户自己的选择(按自己的做事风格判断),不是系统验证出来的结果。选了,报告和聊天就按那一边写;不确定,受影响的方面两版都读。
3. 系统不推荐任何一边,不打分,不问事件题。
这是对 #279/#292「停用选边」的**有意调整**,只恢复「用户自选」这一条路;问答、事件打分、答题得出的时间范围继续停用。
## 不做的事
- 不改 `RECT_QUESTIONNAIRE_ENABLED`,不恢复问答(`questionnaire`、`adaptive`、`chart_answers`、`resumeRecordId`)和事件证据输入。`useAnswerWindow` 继续被拒绝。
- 不调用 `scripts/chart_choice/astrologer.py`、`adaptive.py`、`interview.py`、`chart_questions.py` 的任何打分或选题。
- 不显示票数、推荐、把握、概率、「更可能」「系统判断」之类的任何措辞;不显示「已纠正」「已校正」「已确认」。
- 不改报告、年运的渲染代码(`scripts/report_render/` 不动)。聊天侧只复用已有的「两版都读」(`frontend/src/lib/chart-choice-both-versions.ts`),不新写提示词。
- 不删除、不改写历史记录;不改 `references/real_case_calibration/`。
- 不新造按钮、卡片样式:沿用页面现有的 `Card`、`Primary`、范围按钮、六张盘条形图、`ChooseStep` 的选项样式。不加提示性的小字副标题。
## 一、结果页讲清结论
在现有「按你填的 HH:MM」这一步(`defaultOnly` 的 `FinalStep`)和「当前使用」首页,把「现有信息不足以确认更准确的出生时间。」这句换成由数据生成的结论,放在六张盘上方:
- 范围内没有任何盘换座:`这个时间范围内六张盘都不变,可以直接用。`(已有的 `certain` 步骤保持不变。)
- 有换座:分两行。
- `不受影响:主盘。`(列出范围内不换座的那些盘的名称,用页面已有的盘名:主盘、婚恋、事业、钱财、日常、突变。)
- `差几分钟就不同:婚恋、事业、钱财、日常、突变。`(列出会换座的。)
- 六张盘每行现有文案 `狮子上升,范围内会换座(04:59:43 换)` 改成把两边都写出来:`04:59:43 之前巨蟹上升,之后狮子上升`。一个盘在范围内换座多于一次时,只写离所填时间最近的那一次,后面加 `等 N 处`。星座名用现有的中文映射,时刻格式沿用现有的。
- 所填时间离最近的线不到 2 分钟时,在结论下加一行:`你填的 05:00 离 04:59:43 这条线只有 17 秒。`(秒数、分钟数按实际计算;1 分钟以上写「X 分 Y 秒」。)
所有句子由后端 packet 里已有的线和分盘星座生成;packet 缺「线前星座」时在 `scripts/chart_choice/service.py` 的线视图里补上(`Line.flips` 已有前后星座)。不改任何计算。
## 二、用户自选
在结果页「用 05:00」按钮旁加一个次级按钮 `自己选线前线后`(范围内没有换座线时不显示)。
流程复用已有的逐条线选边步骤(`ChooseStep` / v1 的 `runDecision` + `overrideSide`,或 v2 的 `RoundStep`,以哪个更容易去掉打分为准,在 PROGRESS 写明选了哪个):
1. 从离所填时间最近的线开始,一次一条线。每条线列出在这条线上换座的方面,每个方面给线前、线后两段说明(用 `scripts/chart_choice/readings.py` 现有的文字,不新写)。
2. 每条线一个三选一:`线前`、`线后`、`不确定`。整条线选一次,不是每个方面各选一次(同一条线上的各方面在同一时刻一起换,分开选会自相矛盾)。
3. 选了线前或线后:范围收到那一侧,继续问这一侧里剩下的线(如果有),直到这一段里没有线或用户选了「不确定」或点了 `就到这里`。
4. 选「不确定」:这条线不收范围,这条线上换座的方面记入「两版都读」(现有 `both_versions` 字段),流程结束。
5. 结束后到确认页:写明最终用的时间、选过的每条线和选的哪一边,以及 `这是你自己选的,可以随时改。`。保存按钮文案 `用 HH:MM`。
保存规则:
- 采用时刻:选定的那一段里的代表时刻,沿用现有 `representative_minute` 规则;所填时间本来就在选定段内时保持所填时间不变。
- 来源链写明是用户自选:`source = user_choice`、`rule = user_override`,并新增 `declared_by_user: true` 和 `basis: self_choice_20261116`,与旧问答、旧事件采纳区分开。不写 `votes`,不写任何打分回执。
- **原始填写的时间和原范围必须原样保留**在记录里(现有的申报字段不动);首页「当前使用」显示采用时刻、选定的范围,以及一行 `按你自己的选择`。提供 `改回我填的时间`(复用现有的恢复默认 `restore_default`)。
- 出生时间状态不得升级为「已确认」一类;沿用现有 `accepted`。
- 服务器重新计算线和代表时刻,不信任客户端传来的时刻或范围。
- 接口:在 `/api/chart-choice/adopt` 现有 schema 上加一个明确的入口字段(建议 `selfChoice: true` + 每条线的选择列表),只有带这个字段的请求才走自选;不带的旧载荷(`overrideSide`、非空 `resolved`、`answers`、`chart_answers`、`resumeRecordId`、`useAnswerWindow`)继续按 #279/#292/#294 的方式被拒绝或走默认。**不要靠放开旧字段来实现。**
## 三、下游
- 聊天:采用时刻变了,照常按采用时刻排盘;`both_versions` 非空时现有「两版都读」逻辑照常生效。确认 `chartChoiceBothVersionsFromProvenance` 认得本单写出的来源(它要求 `source === "user_choice"`、`chosen_side`、`other_saved_at`);「不确定」发生在第一条线、没有选定任何一侧时,`chosen_side` 怎么写、`other_saved_at` 取哪一侧,按现有字段约束给出一个能让两版都读生效的写法,并写测试。
- 报告、年运:不改代码。它们读采用时刻,本单后自然按用户选的那边生成。旧报告不重算、不标记;这一点写进 PROGRESS 的「已知边界」。
## 四、测试
- `frontend/tests/chart-choice-self-choice-20261116.test.tsx`:结论两行的生成(全不变、部分换座、多次换座、离线不到 2 分钟);自选按钮只在有线时出现;三选一流程(线前→下一条线、线后、不确定结束、就到这里);确认页文案;页面任何位置不出现「推荐」「更可能」「把握」「已纠正」「已校正」「已确认」和票数。
- 接口测试:带 `selfChoice` 的请求保存后读回,原始时间和原范围未变、来源字段齐全、无 `votes`;不带 `selfChoice` 的旧载荷行为与现在完全一致(#294 的 `rectification-p0-evidence-20261116.test.ts` 与 `chart-choice-pause-20261115.test.tsx` 不删断言、照旧通过;确需调整的断言逐条在 PROGRESS 说明原因);客户端伪造时刻被服务器重算覆盖;重复提交两次结果相同。
- `改回我填的时间` 后读回等于原始申报。
- 「两版都读」:不确定的线上换座的方面进入 `both_versions`,聊天侧读取函数返回非空。
- Python:`service.py` 线视图补字段的测试;既有 `tests/` 里 chart_choice 相关测试照旧通过。
## 五、文档
- `docs/BUG_HISTORY.md` 新增 BUG-1936,关联 BUG-1890、BUG-1896、BUG-1925,写明这是产品负责人对「停用选边」的有意调整及其范围(只在自己那一节内编辑;不写姓名、出生资料、邮箱、ID)。
- `CHANGELOG.md` 一行;`docs/tasks/PROGRESS-rect-self-choice-20261116.md`。
- `docs/research/rect-p0-evidence-20261116.md` 末尾追加一段「11-16 之后的变更」,说明用户自选入口的恢复及其来源标记,不改原有内容。
## 验收
- Python quick gate 通过;`cd frontend && npx eslint .` 0 错误;`npx tsc --noEmit` 通过;前端全量测试不新增失败。
- 验收时会用测试账号在 staging 之前的本地构建上走一遍:结论两行、自选三条路径、改回原时间。
@@ -1,155 +1,108 @@
"use client";
import { PlusOutlined } from "@ant-design/icons";
import { useGetIdentity } from "@refinedev/core";
import { useTable } from "@refinedev/antd";
import { List } from "@refinedev/antd";
import { App, Button, Form, Input, InputNumber, Modal, Select, Space, Switch, Table, Typography, type TableColumnsType } from "antd";
import { useState } from "react";
import { Alert, App, Space, Switch, Table, Typography } from "antd";
import { useCallback, useEffect, useState } from "react";
import { flagIsOn, KNOWN_FEATURE_FLAGS, publishedFlag, type FeatureFlagVersion } from "@/lib/admin/known-feature-flags";
import { adminRequestJson, type AdminIdentity } from "@/lib/admin/providers";
import { formatAdminDate } from "./resource-table";
const { Text } = Typography;
type FeatureFlag = {
id: string;
flagKey: string;
version: number;
enabled: boolean;
rolloutPercentage: number;
config: Record<string, unknown>;
status: string;
createdAt: string;
publishedAt: string | null;
};
type FlagFilters = { q?: string; status?: string };
type FlagForm = {
flagKey: string;
enabled: boolean;
rolloutPercentage: number;
configJson: string;
};
type Row = (typeof KNOWN_FEATURE_FLAGS)[number];
/**
* BUG-1937: the page used to be a free-form editor (new key, rollout percent,
* config JSON, draft then publish). Only four keys are read by the product, so
* it now lists those four with one switch each; flipping it saves and publishes.
*/
export default function FeatureFlagsManagement() {
const { message } = App.useApp();
const { data: identity } = useGetIdentity<AdminIdentity>();
const table = useTable<FeatureFlag, { message: string; statusCode: number }, FlagFilters>({
resource: "feature-flags",
syncWithLocation: true,
pagination: { pageSize: 20 },
onSearch: ({ q, status }) => [
{ field: "q", operator: "contains", value: q },
{ field: "status", operator: "eq", value: status },
],
});
const [form] = Form.useForm<FlagForm>();
const [editing, setEditing] = useState<FeatureFlag | null>(null);
const [open, setOpen] = useState(false);
const [saving, setSaving] = useState(false);
const [publishingId, setPublishingId] = useState<string | null>(null);
const [rows, setRows] = useState<FeatureFlagVersion[]>([]);
const [loadError, setLoadError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [savingKey, setSavingKey] = useState<string | null>(null);
const canWrite = Boolean(identity?.permissions.includes("ops.flags.write"));
function edit(item?: FeatureFlag) {
setEditing(item ?? null);
form.setFieldsValue(item ? {
flagKey: item.flagKey,
enabled: item.enabled,
rolloutPercentage: item.rolloutPercentage,
configJson: JSON.stringify(item.config, null, 2),
} : {
flagKey: "",
enabled: false,
rolloutPercentage: 0,
configJson: "{}",
});
setOpen(true);
}
async function save(values: FlagForm) {
setSaving(true);
const load = useCallback(async () => {
try {
let config: unknown;
try {
config = JSON.parse(values.configJson);
} catch {
throw new Error("配置 JSON 格式不正确");
}
await adminRequestJson("/api/admin/feature-flags", {
const payload = await adminRequestJson<{ data: FeatureFlagVersion[] }>("/api/admin/feature-flags?pageSize=100");
setRows(payload.data);
setLoadError(null);
return payload.data;
} catch (error) {
setLoadError(error instanceof Error ? error.message : "读取失败");
return null;
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
const timer = window.setTimeout(() => void load(), 0);
return () => window.clearTimeout(timer);
}, [load]);
async function toggle(row: Row, on: boolean) {
setSavingKey(row.key);
try {
const saved = await adminRequestJson<{ data: { id: string } }>("/api/admin/feature-flags", {
method: "POST",
body: JSON.stringify({
action: "save",
id: editing?.id ?? null,
flagKey: values.flagKey.trim(),
enabled: values.enabled,
rolloutPercentage: values.rolloutPercentage,
config,
expectedVersion: editing?.version ?? null,
id: null,
flagKey: row.key,
enabled: on,
rolloutPercentage: on ? 100 : 0,
config: publishedFlag(rows, row.key)?.config ?? {},
expectedVersion: null,
}),
});
message.success("功能开关草稿已保存");
setOpen(false);
await table.tableQuery.refetch();
} catch (error) {
message.error(error instanceof Error ? error.message : "保存失败");
} finally {
setSaving(false);
}
}
async function publish(item: FeatureFlag) {
setPublishingId(item.id);
try {
const draft = (await load())?.find((item) => item.id === saved.data.id);
if (!draft) throw new Error("已保存,但没有读到新版本,请刷新后再试");
await adminRequestJson("/api/admin/feature-flags", {
method: "POST",
body: JSON.stringify({ action: "publish", id: item.id, expectedVersion: item.version }),
body: JSON.stringify({ action: "publish", id: draft.id, expectedVersion: draft.version }),
});
message.success("功能开关已发布");
await table.tableQuery.refetch();
await load();
message.success(`${row.label}已${on ? "打开" : "关闭"},大约 15 秒后对用户生效`);
} catch (error) {
message.error(error instanceof Error ? error.message : "发布失败");
message.error(`${row.label}没有改成:${error instanceof Error ? error.message : "请求失败"}`);
await load();
} finally {
setPublishingId(null);
setSavingKey(null);
}
}
const columns: TableColumnsType<FeatureFlag> = [
{ title: "开关", render: (_, item) => <Space direction="vertical" size={0}><Text strong>{item.flagKey}</Text><Text type="secondary">v{item.version}</Text></Space> },
{ title: "状态", render: (_, item) => <Text>{item.status === "published" ? "已发布" : item.status === "draft" ? "草稿" : item.status} · {item.enabled ? "已开启" : "已关闭"}</Text> },
{ title: "灰度", dataIndex: "rolloutPercentage", render: (value) => `${value}%` },
{ title: "配置", dataIndex: "config", render: (value) => <Text code>{JSON.stringify(value)}</Text> },
{ title: "发布时间", dataIndex: "publishedAt", render: formatAdminDate },
{
title: "操作",
fixed: "right",
render: (_, item) => <Space>{canWrite && <Button type="link" onClick={() => edit(item)}>编辑草稿</Button>}{canWrite && item.status !== "published" && <Button type="link" loading={publishingId === item.id} onClick={() => void publish(item)}>发布</Button>}</Space>,
},
];
return <List title="功能开关" headerButtons={canWrite ? <Button type="primary" icon={<PlusOutlined />} onClick={() => edit()}>新增开关</Button> : null}>
return <List title="功能开关" headerButtons={null}>
<Space direction="vertical" size="middle" style={{ width: "100%" }}>
<Form {...table.searchFormProps} layout="inline" style={{ rowGap: 8 }}>
<Form.Item name="q" label="搜索"><Input.Search allowClear placeholder="开关键" /></Form.Item>
<Form.Item name="status" label="状态">
<Select
allowClear
placeholder="全部状态"
style={{ minWidth: 140 }}
options={["draft", "published", "retired"].map((value) => ({ value, label: value }))}
/>
</Form.Item>
</Form>
<Table {...table.tableProps} columns={columns} rowKey="id" scroll={{ x: "max-content" }} />
<Text type="secondary">这里列的是产品里真正会生效的全部开关。拨一下就直接生效,不需要另外发布。</Text>
{loadError && <Alert type="error" showIcon message={`开关状态没有读出来:${loadError}`} />}
<Table<Row>
rowKey="key"
loading={loading}
pagination={false}
dataSource={[...KNOWN_FEATURE_FLAGS]}
columns={[
{ title: "功能", render: (_, row) => <Text strong>{row.label}</Text> },
{
title: "现在",
render: (_, row) => (
<Switch
checked={flagIsOn(rows, row.key)}
checkedChildren="开"
unCheckedChildren="关"
disabled={!canWrite || loading || Boolean(loadError) || (savingKey !== null && savingKey !== row.key)}
loading={savingKey === row.key}
onChange={(on) => void toggle(row, on)}
/>
),
},
{ title: "关掉会怎样", render: (_, row) => row.off.replace(/^关掉后:/, "") },
]}
/>
</Space>
<Modal title={editing ? `编辑 ${editing.flagKey}` : "新增功能开关"} open={open} okText="保存草稿" cancelText="取消" confirmLoading={saving} onOk={() => form.submit()} onCancel={() => setOpen(false)} destroyOnHidden>
<Form<FlagForm> form={form} layout="vertical" onFinish={save}>
<Form.Item name="flagKey" label="开关键" rules={[{ required: true }, { pattern: /^[a-z][a-z0-9._-]{1,99}$/ }]}><Input disabled={Boolean(editing)} /></Form.Item>
<Form.Item name="rolloutPercentage" label="灰度百分比" rules={[{ required: true }]}><InputNumber min={0} max={100} precision={0} style={{ width: "100%" }} /></Form.Item>
<Form.Item name="enabled" label="启用" valuePropName="checked"><Switch /></Form.Item>
<Form.Item name="configJson" label="配置 JSON" rules={[{ required: true }]}><Input.TextArea rows={6} spellCheck={false} /></Form.Item>
</Form>
</Modal>
</List>;
}
+17 -5
View File
@@ -37,6 +37,7 @@ import {
launchCnyPerCredit,
launchDefaultModel,
launchFeaturePrice,
launchFeatureCost,
launchMargin,
microusdToCny,
microusdToCnyPerMillion,
@@ -281,9 +282,10 @@ export default function LaunchSetup() {
const edited = priceEdits[feature.key];
const credits = edited ?? current?.creditCost ?? null;
const metrics = usageByFeature.get(feature.key)?.metrics.costMicrousd;
const cost = microusdToCny(metrics?.p95 ?? null, usdToCny);
const picked = launchFeatureCost({ runs: metrics?.runs ?? 0, p95Microusd: metrics?.p95 ?? null, model: launchDefaultModel(models), featureKey: feature.key });
const cost = microusdToCny(picked?.microusd ?? null, usdToCny);
const sale = credits !== null && cnyPerCredit ? credits * cnyPerCredit.low : null;
return { ...feature, current, credits, runs: metrics?.runs ?? 0, cost, sale, margin: launchMargin(sale, cost) };
return { ...feature, current, credits, runs: metrics?.runs ?? 0, cost, costSource: picked?.source ?? null, sale, margin: launchMargin(sale, cost) };
});
const changedPrices = featureRows.filter((row) => row.credits !== null && row.credits !== row.current?.creditCost);
@@ -505,8 +507,18 @@ export default function LaunchSetup() {
},
{ title: "现在生效的", render: (_, row) => (row.current ? `${row.current.creditCost} 积分` : <Tag color="warning">还没有价格</Tag>) },
{ title: "折合售价", render: (_, row) => yuan(row.sale) },
{ title: "实测成本(近 30 天,95% 的请求不超过)", render: (_, row) => (row.runs ? yuan(row.cost, 3) : "还没有数据") },
{ title: "毛利", render: (_, row) => (row.margin === null ? "算不出" : `${(row.margin * 100).toFixed(0)}%`) },
{
title: "每次成本",
render: (_, row) => (row.cost === null
? "先填模型单价"
: row.costSource === "measured" ? `${row.cost.toFixed(3)} 元(实测)` : `约 ${row.cost.toFixed(2)} 元(估算)`),
},
{
title: "毛利",
render: (_, row) => (row.margin === null
? (row.sale === null ? "先上架积分包" : "先填模型单价")
: `${row.costSource === "estimate" ? "约 " : ""}${(row.margin * 100).toFixed(0)}%`),
},
]}
/>
<Space style={{ marginTop: 16 }} wrap>
@@ -517,7 +529,7 @@ export default function LaunchSetup() {
{cnyPerCredit
? `折合售价按最划算的积分包算(每积分 ${cnyPerCredit.low.toFixed(3)} 元)。`
: "还没有在售的积分包,折合售价和毛利暂时算不出。"}
模型单价填好之前产生的请求,成本记的是 0。
实测:近 30 天里 95% 的请求不超过这个数,只算填好模型单价之后的请求。估算:还没有实测时,按模型单价乘以一次成功生成通常用掉的字数算,失败重试不算在内。
</Text>
</Space>
</Card>
@@ -181,6 +181,7 @@ export function ReplyQualityResource() {
return (
<Space direction="vertical" size="middle" style={{ width: "100%" }}>
<StatsPanel />
<Alert type="info" showIcon message="用户给某条回答点了「踩」,这里才会多一条记录,里面有那一轮的问题、回答和模型当时读到的内容。没人点踩时,下面的列表是空的。" />
<ResourceTable<Record_>
resource="reply-quality"
title="对话质量记录"
@@ -0,0 +1,35 @@
/**
* The feature flags the product actually reads (BUG-1937). The admin page lists
* exactly these: a flag with any other key is read by no code, so creating one
* changed nothing. A flag counts as on only when its published version is
* enabled at 100% (src/lib/feature-flags.ts).
*/
export const KNOWN_FEATURE_FLAGS = [
{ key: "product.report_center", label: "报告", off: "关掉后:用户不能生成个人报告和年运报告,合盘报告也不能新建。已生成的报告不受影响。" },
{ key: "product.compatibility", label: "婚恋合盘", off: "关掉后:合盘入口隐藏,不能新建合盘报告,也不能生成合盘英文版。" },
{ key: "product.rectification", label: "生时纠正", off: "关掉后:生时纠正入口隐藏,聊天里也不再引导纠正出生时间。" },
{ key: "billing.subscriptions", label: "订阅套餐", off: "关掉后:购买页不显示订阅套餐,也不能下订阅订单;积分包照常卖。" },
] as const;
export type KnownFeatureFlagKey = (typeof KNOWN_FEATURE_FLAGS)[number]["key"];
export type FeatureFlagVersion = Readonly<{
id: string;
flagKey: string;
version: number;
enabled: boolean;
rolloutPercentage: number;
config: Record<string, unknown>;
status: string;
}>;
/** The published version of one flag, or null when it was never published (the product then treats it as off). */
export function publishedFlag(rows: readonly FeatureFlagVersion[], key: string): FeatureFlagVersion | null {
return rows.find((row) => row.flagKey === key && row.status === "published") ?? null;
}
/** Whether the product sees this flag as on: published, enabled, and rolled out to everyone. */
export function flagIsOn(rows: readonly FeatureFlagVersion[], key: string): boolean {
const flag = publishedFlag(rows, key);
return Boolean(flag && flag.enabled && flag.rolloutPercentage === 100);
}
+38
View File
@@ -194,3 +194,41 @@ export function launchMargin(saleCny: number | null, costCny: number | null): nu
if (saleCny === null || costCny === null || saleCny <= 0) return null;
return (saleCny - costCny) / saleCny;
}
/**
* Tokens one successful run typically uses, measured locally on 2026-11-16
* (one sample each, DeepSeek flash). Used only for the estimate the launch page
* shows while a feature has no settled usage with a price yet (BUG-1937).
*/
export const LAUNCH_TYPICAL_TOKENS: Readonly<Record<LaunchFeatureKey, { input: number; output: number }>> = {
"chat.standard": { input: 100_000, output: 13_000 },
"report.full": { input: 126_000, output: 33_000 },
"annual.full": { input: 108_000, output: 86_000 },
"synastry.full": { input: 360_000, output: 102_000 },
};
/** Estimated cost of one run from the default model's unit prices. Null until both prices are filled. */
export function launchEstimatedCostMicrousd(
model: Pick<LaunchModel, "inputCostMicrousdPerMillion" | "outputCostMicrousdPerMillion"> | null,
featureKey: LaunchFeatureKey,
): number | null {
if (!model || !(model.inputCostMicrousdPerMillion > 0) || !(model.outputCostMicrousdPerMillion > 0)) return null;
const tokens = LAUNCH_TYPICAL_TOKENS[featureKey];
return (tokens.input * model.inputCostMicrousdPerMillion + tokens.output * model.outputCostMicrousdPerMillion) / 1_000_000;
}
/**
* The cost the launch page shows for one feature: the measured 95th percentile
* when the ledger has priced runs, otherwise the estimate. A measured value of 0
* means the runs settled before the unit prices were filled, so it is not used.
*/
export function launchFeatureCost(input: Readonly<{
runs: number;
p95Microusd: number | null;
model: Pick<LaunchModel, "inputCostMicrousdPerMillion" | "outputCostMicrousdPerMillion"> | null;
featureKey: LaunchFeatureKey;
}>): { microusd: number; source: "measured" | "estimate" } | null {
if (input.runs > 0 && input.p95Microusd !== null && input.p95Microusd > 0) return { microusd: input.p95Microusd, source: "measured" };
const estimate = launchEstimatedCostMicrousd(input.model, input.featureKey);
return estimate === null ? null : { microusd: estimate, source: "estimate" };
}
@@ -0,0 +1,26 @@
-- BUG-1935: the admin role had SELECT grants on these tables but no row-level
-- security policy, so every admin read returned zero rows without an error
-- (用量和成本、上线配置里的实测成本、订阅列表都是空的). Same cause as BUG-147.
begin;
do $$
declare
t text;
begin
if exists (select 1 from pg_roles where rolname = 'admin_runtime') then
foreach t in array array[
'usage_ledger', 'usage_reservations', 'usage_events',
'user_subscriptions', 'user_product_redemptions',
'notification_templates', 'pricing_experiment_events'
] loop
if to_regclass('public.' || t) is not null then
execute format('grant select on table public.%I to admin_runtime', t);
execute format('drop policy if exists %I on public.%I', t || '_admin_read', t);
execute format('create policy %I on public.%I for select to admin_runtime using (true)', t || '_admin_read', t);
end if;
end loop;
end if;
end;
$$;
commit;
@@ -0,0 +1,64 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { fileURLToPath } from "node:url";
import { flagIsOn, KNOWN_FEATURE_FLAGS, publishedFlag, type FeatureFlagVersion } from "../src/lib/admin/known-feature-flags.ts";
import { LAUNCH_FEATURES, launchEstimatedCostMicrousd, launchFeatureCost } from "../src/lib/admin/launch-setup.ts";
const source = (path: string) => readFileSync(fileURLToPath(new URL(`../${path}`, import.meta.url)), "utf8");
const model = { inputCostMicrousdPerMillion: 100_000, outputCostMicrousdPerMillion: 400_000 };
test("the launch page estimates a cost while a feature has no priced usage (BUG-1937)", () => {
// chat: 100k in × $0.10/M + 13k out × $0.40/M = 10,000 + 5,200 microusd
assert.equal(launchEstimatedCostMicrousd(model, "chat.standard"), 15_200);
assert.equal(launchEstimatedCostMicrousd(null, "chat.standard"), null);
assert.equal(launchEstimatedCostMicrousd({ inputCostMicrousdPerMillion: 0, outputCostMicrousdPerMillion: 400_000 }, "chat.standard"), null);
for (const feature of LAUNCH_FEATURES) assert.ok((launchEstimatedCostMicrousd(model, feature.key) ?? 0) > 0, feature.key);
assert.deepEqual(launchFeatureCost({ runs: 0, p95Microusd: null, model, featureKey: "chat.standard" }), { microusd: 15_200, source: "estimate" });
assert.deepEqual(launchFeatureCost({ runs: 12, p95Microusd: 9_000, model, featureKey: "chat.standard" }), { microusd: 9_000, source: "measured" });
// Runs settled before the unit prices were filled carry cost 0: not a measurement.
assert.deepEqual(launchFeatureCost({ runs: 12, p95Microusd: 0, model, featureKey: "chat.standard" }), { microusd: 15_200, source: "estimate" });
assert.equal(launchFeatureCost({ runs: 0, p95Microusd: null, model: null, featureKey: "chat.standard" }), null);
const page = source("src/components/admin/launch-setup.tsx");
assert.match(page, /(估算)/);
assert.match(page, /(实测)/);
assert.doesNotMatch(page, /row\.runs \? yuan\(row\.cost, 3\) : "还没有数据"/);
});
test("the flags page lists exactly the flags the product reads, one switch each (BUG-1937)", () => {
const read = new Set<string>();
for (const file of ["src/app/api/payment/packages/route.ts", "src/app/api/payment/epay/create/route.ts"]) {
for (const match of source(file).matchAll(/loadRuntimeFeatureFlags\(\["([a-z._]+)"\]\)/g)) read.add(match[1]!);
}
const used = new Set<string>();
for (const file of [
"src/app/api/reports/route.ts", "src/app/api/account/route.ts", "src/app/api/synastry-reports/route.ts", "src/app/api/product-access/route.ts",
"src/lib/annual-report-server.ts", "src/lib/synastry-full-create.ts", "src/lib/rectification-in-chat-server.ts", "src/lib/chart-choice/route-support.ts",
]) {
for (const match of source(file).matchAll(/isProductEnabled\("([a-z_]+)"\)/g)) used.add(`product.${match[1]}`);
}
assert.deepEqual([...KNOWN_FEATURE_FLAGS.map((flag) => flag.key)].sort(), [...read, ...used].sort());
const page = source("src/components/admin/feature-flags-management.tsx");
assert.doesNotMatch(page, /新增开关|配置 JSON|灰度百分比|编辑草稿/);
assert.match(page, /rolloutPercentage: on \? 100 : 0/);
const rows: FeatureFlagVersion[] = [
{ id: "a", flagKey: "product.compatibility", version: 1, enabled: true, rolloutPercentage: 100, config: {}, status: "retired" },
{ id: "b", flagKey: "product.compatibility", version: 2, enabled: true, rolloutPercentage: 50, config: { x: 1 }, status: "published" },
{ id: "c", flagKey: "product.report_center", version: 1, enabled: true, rolloutPercentage: 100, config: {}, status: "published" },
{ id: "d", flagKey: "billing.subscriptions", version: 1, enabled: true, rolloutPercentage: 100, config: {}, status: "draft" },
];
assert.equal(publishedFlag(rows, "product.compatibility")?.id, "b");
assert.equal(flagIsOn(rows, "product.compatibility"), false);
assert.equal(flagIsOn(rows, "product.report_center"), true);
assert.equal(flagIsOn(rows, "billing.subscriptions"), false);
assert.equal(flagIsOn(rows, "product.rectification"), false);
});
test("the quality records page says when a record appears (BUG-1937)", () => {
assert.match(source("src/components/admin/reply-quality-resource.tsx"), /点了「踩」,这里才会多一条记录/);
});
@@ -0,0 +1,36 @@
import assert from "node:assert/strict";
import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
const MIGRATIONS = fileURLToPath(new URL("../supabase/migrations/", import.meta.url));
const NEW_MIGRATION = "20261116040000_admin_runtime_usage_read_policies.sql";
// BUG-1935: a table with row-level security and a SELECT grant to admin_runtime
// but no admin_runtime policy reads as empty, with no error. Every such table
// must have a policy, either written out or listed in the BUG-1935 migration.
test("every RLS table the admin role may read has an admin read policy (BUG-1935)", () => {
const granted = new Set<string>();
const withPolicy = new Set<string>();
const rls = new Set<string>();
for (const file of readdirSync(MIGRATIONS).filter((name) => name.endsWith(".sql")).sort()) {
const sql = readFileSync(join(MIGRATIONS, file), "utf8");
for (const match of sql.matchAll(/grant\s+([a-z, ]+?)\s+on\s+(?:table\s+)?([a-z_.,\s]+?)\s+to\s+([a-z_, ]+);/gi)) {
if (!match[3]!.includes("admin_runtime") || !/select/i.test(match[1]!)) continue;
for (const table of match[2]!.split(",").map((name) => name.trim())) if (table.startsWith("public.")) granted.add(table);
}
for (const match of sql.matchAll(/create policy\s+\S+\s+on\s+(public\.[a-z_]+)([\s\S]*?);/gi)) {
if (match[2]!.includes("admin_runtime")) withPolicy.add(match[1]!);
}
for (const match of sql.matchAll(/alter table\s+(?:if exists\s+)?(public\.[a-z_]+)\s+enable row level security/gi)) rls.add(match[1]!);
}
const listed = readFileSync(join(MIGRATIONS, NEW_MIGRATION), "utf8");
for (const match of listed.matchAll(/'([a-z_]+)'/g)) withPolicy.add(`public.${match[1]}`);
assert.match(listed, /create policy %I on public\.%I for select to admin_runtime using \(true\)/);
const missing = [...granted].filter((table) => rls.has(table) && !withPolicy.has(table)).sort();
assert.deepEqual(missing, []);
for (const table of ["usage_ledger", "usage_reservations", "usage_events", "user_subscriptions"]) {
assert.ok(listed.includes(`'${table}'`), table);
}
});