From 96b76ac4c6acd043cd3fafadc44834425c53d2d8 Mon Sep 17 00:00:00 2001 From: kapla73 Date: Tue, 17 Nov 2026 21:19:55 +0800 Subject: [PATCH 01/10] =?UTF-8?q?feat(repo):=20=E7=94=A8=E9=87=8F=E6=B1=87?= =?UTF-8?q?=E6=80=BB=E4=B8=8E=E8=B6=8B=E5=8A=BF=E8=BF=81=E7=A7=BB=E5=88=B0?= =?UTF-8?q?=20Provider=20usage=20API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - server:新增 usage.summary 与 usage.trend 端点(workspace/agent/session 维度,UTC+8 分桶),mock 网关按账本生成演示数据,上游 SDK 钉 beta 版 - console:用量页统一统计时间选择器,趋势卡与模型/工具明细改读 Provider 口径,成员筛选展示 display_name - sdk:session-usage 合同扩展 usage 类型;openapi、生成物、skills 参考与接口文档同步 --- .../catalog/remote-resource-picker.tsx | 17 +- .../features/members/member-usage-page.tsx | 115 +- .../src/features/usage/session-usage-page.tsx | 22 +- .../features/usage/template-usage-panel.tsx | 349 ++-- .../features/usage/template-usage-trend.tsx | 382 ++++- .../src/features/usage/usage.module.less | 75 +- apps/console/src/lib/admin/client.ts | 62 +- apps/console/src/lib/admin/index.ts | 2 - .../src/lib/admin/member-usage.test.ts | 14 +- apps/console/src/lib/admin/member-usage.ts | 2 +- apps/server/openapi.json | 1459 ++++++++++++++--- apps/server/package.json | 2 +- apps/server/src/gateway/mock.ts | 343 ++-- apps/server/src/gateway/sdk.ts | 12 +- apps/server/src/gateway/types.ts | 15 +- apps/server/src/routes/admin.ts | 187 ++- apps/server/src/services/index.ts | 1 + apps/server/src/services/member-usage.ts | 2 +- apps/server/src/store/session-usage.ts | 35 +- apps/server/tests/member-usage.test.ts | 232 ++- apps/server/tests/sdk-session-usage.test.ts | 89 +- apps/storybook/next-env.d.ts | 4 +- apps/web/e2e/member-usage.spec.ts | 67 +- .../kit-chat-provider/references/api.md | 6 +- assets/skills/use-kit-chat/references/api.md | 12 +- docs/interfaces.md | 9 +- .../src/protocol/generated/openapi-types.ts | 347 +++- packages/sdk/src/protocol/session-usage.ts | 164 +- pnpm-lock.yaml | 131 +- 29 files changed, 3058 insertions(+), 1099 deletions(-) diff --git a/apps/console/src/features/catalog/remote-resource-picker.tsx b/apps/console/src/features/catalog/remote-resource-picker.tsx index e09ccb9..db511f4 100644 --- a/apps/console/src/features/catalog/remote-resource-picker.tsx +++ b/apps/console/src/features/catalog/remote-resource-picker.tsx @@ -30,6 +30,8 @@ type RemoteResourcePickerProps = { triggerRef?: Ref<{ focus: () => void }>; showId?: boolean; emptyText?: string; + /** 展开时是否重拉远端候选(数据与页面主内容同源时关闭,避免展开触发整页刷新)。 */ + refreshOnOpen?: boolean; } & ( | { multiple?: false; @@ -101,7 +103,18 @@ function sourceOf(option: DefaultOptionType | undefined, byId: Map>(null); useImperativeHandle(triggerRef, () => ({ focus: () => selectRef.current?.focus() }), []); const [search, setSearch] = useState(""); @@ -123,7 +136,7 @@ export function RemoteResourcePicker(props: RemoteResourcePickerProps) { if (disabled) return; if (next) { setSearch(""); - void remote.refresh(); + if (refreshOnOpen) void remote.refresh(); } }; diff --git a/apps/console/src/features/members/member-usage-page.tsx b/apps/console/src/features/members/member-usage-page.tsx index d449536..81b06ac 100644 --- a/apps/console/src/features/members/member-usage-page.tsx +++ b/apps/console/src/features/members/member-usage-page.tsx @@ -2,8 +2,9 @@ import type { MemberSessionUsage, MemberUsageSummary, MemberView, - ModelUsagePage, - ToolUsagePage, + UsageModelRow, + UsageSummary, + UsageToolRow, } from "@openagentpack/kit-sdk/protocol"; import type { TableColumnsType } from "antd"; import { Button, Empty, Result, Select, Spin, Table } from "antd"; @@ -25,56 +26,52 @@ function captureTime(value?: string) { const SESSION_TELEMETRY_PAGE_SIZE = 20; -function usageTotalText(page?: ModelUsagePage | ToolUsagePage) { - return page ? page.total_call_count.toLocaleString("zh-CN") : "—"; +/** 指标值可能为 null(上游未知指标),统一显示破折号而不是 0。 */ +function countText(value: number | null) { + return value === null ? "—" : value.toLocaleString("zh-CN"); } -type TelemetryQueryState = { loading: boolean; data?: unknown; error?: string | null }; - -function telemetryLoading(...queries: TelemetryQueryState[]) { - return queries.some((query) => query.loading || (!query.data && !query.error)); -} - -function telemetryHasNext(page: { total: number } | undefined, pageNo: number, pageSize: number) { - return page ? pageNo * pageSize < page.total : false; +/** 本地分页:上游一次返回全量明细,分页只在展示层切片。 */ +function slicePage(rows: T[], pageNo: number) { + return rows.slice((pageNo - 1) * SESSION_TELEMETRY_PAGE_SIZE, pageNo * SESSION_TELEMETRY_PAGE_SIZE); } -type ModelRow = ModelUsagePage["items"][number]; - -function countText(value: number) { - return value.toLocaleString("zh-CN"); +/** 任一明细长度超过单页即仍有下一页。 */ +function telemetryHasNext(summary: UsageSummary | undefined, pageNo: number) { + const longest = Math.max(summary?.usage.models.length ?? 0, summary?.usage.tools.length ?? 0); + return pageNo * SESSION_TELEMETRY_PAGE_SIZE < longest; } -const modelColumns: TableColumnsType = [ - { title: "模型名", dataIndex: "model_name" }, - { title: "调用次数", dataIndex: "call_count", align: "right", render: (value: number) => countText(value) }, - { title: "失败次数", dataIndex: "failed_count", align: "right", render: (value: number) => countText(value) }, +const modelColumns: TableColumnsType = [ + { title: "模型名", dataIndex: "model_name", render: (value: string | null) => value ?? "未归因" }, + { title: "调用次数", align: "right", render: (_, row) => countText(row.usage.call_count.value) }, + { title: "失败次数", align: "right", render: (_, row) => countText(row.usage.failed_count.value) }, { title: "输入", align: "right", - render: (_, row) => {countText(row.tokens.input_tokens)}, + render: (_, row) => {countText(row.usage.input_tokens.value)}, }, { title: "输出", align: "right", - render: (_, row) => {countText(row.tokens.output_tokens)}, + render: (_, row) => {countText(row.usage.output_tokens.value)}, }, { title: "缓存读取", align: "right", - render: (_, row) => {countText(row.tokens.cache_read_tokens)}, + render: (_, row) => {countText(row.usage.cache_read_tokens.value)}, }, { title: "缓存创建", align: "right", - render: (_, row) => {countText(row.tokens.cache_creation_tokens)}, + render: (_, row) => {countText(row.usage.cache_creation_tokens.value)}, }, ]; -function SessionModelTable({ rows, loading }: { rows: ModelUsagePage["items"]; loading?: boolean }) { +function SessionModelTable({ rows, loading }: { rows: UsageModelRow[]; loading?: boolean }) { return ( row.model_name ?? "unknown"} size="small" loading={loading} columns={modelColumns} @@ -86,19 +83,17 @@ function SessionModelTable({ rows, loading }: { rows: ModelUsagePage["items"]; l ); } -type ToolRow = ToolUsagePage["items"][number]; - -const toolColumns: TableColumnsType = [ - { title: "工具名", dataIndex: "tool_name" }, - { title: "来源", dataIndex: "source" }, - { title: "调用次数", dataIndex: "call_count", align: "right", render: (value: number) => countText(value) }, - { title: "失败次数", dataIndex: "failed_count", align: "right", render: (value: number) => countText(value) }, +const toolColumns: TableColumnsType = [ + { title: "工具名", dataIndex: "tool_name", render: (value: string | null) => value ?? "未知" }, + { title: "来源", dataIndex: "source", render: (value: string | null) => value ?? "未知" }, + { title: "调用次数", align: "right", render: (_, row) => countText(row.usage.call_count.value) }, + { title: "失败次数", align: "right", render: (_, row) => countText(row.usage.failed_count.value) }, ]; -function SessionToolTable({ rows, loading }: { rows: ToolUsagePage["items"]; loading?: boolean }) { +function SessionToolTable({ rows, loading }: { rows: UsageToolRow[]; loading?: boolean }) { return (
`${row.source}/${row.tool_name}`} + rowKey={(row) => `${row.source ?? "unknown"}/${row.tool_name ?? "unknown"}`} size="small" loading={loading} columns={toolColumns} @@ -118,7 +113,7 @@ function SessionTelemetryView({ hasNext, onPage, }: { - shown: { models: ModelUsagePage; tools: ToolUsagePage }; + shown: UsageSummary; loading: boolean; pageNo: number; hasNext: boolean; @@ -132,12 +127,16 @@ function SessionTelemetryView({

) : null}
-

模型调用明细 · 全部模型调用 {usageTotalText(shown.models)} 次

- +

+ 模型调用明细 · 全部模型调用 {countText(shown.usage.total.model_call_count.value)} 次 +

+
-

工具调用明细 · 全部工具调用 {usageTotalText(shown.tools)} 次

- +

+ 工具调用明细 · 全部工具调用 {countText(shown.usage.total.tool_call_count.value)} 次 +

+
{hasNext || pageNo > 1 ? (
`${row.workspace_id}/${row.model_name}`} + rowKey={(row) => row.model_name ?? "unknown"} size="small" loading={loading} columns={modelTelemetryColumns} @@ -624,7 +666,7 @@ function ModelUsageSection({ }} /> )} - {page && (page.total > TELEMETRY_PAGE_SIZE || filters.page_no > 1) ? ( + {filtered.length > TELEMETRY_PAGE_SIZE || filters.page_no > 1 ? ( ({ scope: scopeKeyOf(templateId, agentId), - start: toLocalMinuteInput(Date.now() - 7 * 24 * 60 * 60 * 1000), - end: toLocalMinuteInput(Date.now()), source: "", tool_name: "", page_no: 1, })); - /** 切换选中模版(含进入/离开「全部」)即归位分页与来源/工具筛选,保留时间区间。 */ + /** 切换选中模版(含进入/离开「全部」)即归位分页与来源/工具筛选。 */ useEffect(() => { const scope = scopeKeyOf(templateId, agentId); setFilters((current) => @@ -664,74 +709,30 @@ function ToolUsageSection({ : { ...current, scope, page_no: 1, source: "", tool_name: "" }, ); }, [templateId, agentId]); - /** 工具名下拉选项:按当前模版绑定智能体、时间区间与来源拉一页全量去重聚合;工具种类超过 100 时选项可能不全。 */ - const optionsQuery = useAdminQuery( - `usage:tool-options:${scopeKeyOf(templateId, agentId)}:${filters.start}:${filters.end}:${filters.source}`, - (signal) => - client.usage.toolUsage( - { - ...telemetryQuery(filters, agentId), - ...(filters.source ? { source: filters.source as ToolUsageQuery["source"] } : {}), - page_no: 1, - page_size: 100, - }, - signal, - ), - ); - const toolOptions = [...new Set((optionsQuery.data?.items ?? []).map((row) => row.tool_name))]; - const list = useAdminQuery( - `usage:tool-usage:${scopeKeyOf(templateId, agentId)}:${JSON.stringify(filters)}`, - (signal) => - client.usage.toolUsage( - { - ...telemetryQuery(filters, agentId), - ...(filters.source ? { source: filters.source as ToolUsageQuery["source"] } : {}), - ...(filters.tool_name ? { tool_name: filters.tool_name } : {}), - page_no: filters.page_no, - page_size: TELEMETRY_PAGE_SIZE, - }, - signal, - ), - ); - const page: ToolUsagePage | undefined = list.data; - const rows: ToolUsageItem[] = page?.items ?? []; - const hasNext = page ? filters.page_no * TELEMETRY_PAGE_SIZE < page.total : false; - const loading = list.loading || (!list.data && !list.error); + const allTools = summary?.usage.tools ?? []; + const bySource = filters.source ? allTools.filter((row) => row.source === filters.source) : allTools; + const toolOptions = [ + ...new Set(bySource.map((row) => row.tool_name).filter((name): name is string => Boolean(name))), + ]; + const filtered = filters.tool_name ? bySource.filter((row) => row.tool_name === filters.tool_name) : bySource; + const rows = filtered.slice((filters.page_no - 1) * TELEMETRY_PAGE_SIZE, filters.page_no * TELEMETRY_PAGE_SIZE); + const hasNext = filters.page_no * TELEMETRY_PAGE_SIZE < filtered.length; return (

工具调用

- {page ? ( + {summary ? ( - 全部工具调用 {usageNumber(page.total_call_count)} 次 · 共 {usageNumber(page.total)} 行 + 全部工具调用 {usageNumber(summary.usage.total.tool_call_count.value)} 次 + {toolSourceSuffix(summary.usage.total)} + {failedSuffix(summary.usage.total.tool_failed_count.value)} · 共 {usageNumber(filtered.length)} 行 ) : null}
- { - if (value) setFilters({ ...filters, start: value.format("YYYY-MM-DDTHH:mm"), page_no: 1 }); - }} - /> - 至 - { - if (value) setFilters({ ...filters, end: value.format("YYYY-MM-DDTHH:mm"), page_no: 1 }); - }} - />
`${row.workspace_id}/${row.source}/${row.tool_name}`} + rowKey={(row) => `${row.source ?? "unknown"}/${row.tool_name ?? "unknown"}`} size="small" loading={loading} columns={toolTelemetryColumns} @@ -768,7 +769,7 @@ function ToolUsageSection({ }} /> )} - {page && (page.total > TELEMETRY_PAGE_SIZE || filters.page_no > 1) ? ( + {filtered.length > TELEMETRY_PAGE_SIZE || filters.page_no > 1 ? ( number | null; +} + +/** 趋势指标视图:Token 消耗 / 调用次数 / 失败次数(模型+工具失败,不含中断)/ 运行时长(runtime_ms 换算成秒展示)。 */ +const TREND_METRICS = { + tokens: { + label: "Token 消耗", + unit: "", + legendHint: "输入+输出", + decimals: 0, + pick: (total: UsageTrendPoint["usage"]["total"]) => total.total_tokens.value, + }, + calls: { + label: "调用次数", + unit: " 次", + decimals: 0, + pick: (total: UsageTrendPoint["usage"]["total"]) => total.model_call_count.value, + }, + failures: { + label: "失败次数", + unit: " 次", + decimals: 0, + pick: (total: UsageTrendPoint["usage"]["total"]) => + (total.model_failed_count.value ?? 0) + (total.tool_failed_count.value ?? 0), + }, + runtime: { + label: "运行时长", + unit: " 秒", + decimals: 1, + pick: (total: UsageTrendPoint["usage"]["total"]) => (total.runtime_ms.value ?? 0) / 1000, + }, +} as const; +type TrendMetric = keyof typeof TREND_METRICS; + +/** 缓存 Token = 缓存读取 + 缓存写入;与总 Token 构成 Token 消耗视图的同桶双柱。 */ +const CACHE_TOKEN_META: TrendChartMeta = { + label: "缓存 Token", + unit: "", + legendHint: "缓存读取+缓存写入", + decimals: 0, + pick: (total) => (total.cache_read_tokens.value ?? 0) + (total.cache_creation_tokens.value ?? 0), +}; + +/** 系列 → 柱色:accent 为主系列(主题蓝),secondary 为次系列(--kit-success 绿)。 */ +const BAR_CLASSES = { + accent: { today: styles.barAccentToday, past: styles.barAccentPast }, + secondary: { today: styles.barSecondaryToday, past: styles.barSecondaryPast }, +} as const; + +/** 任意时间窗的隐含分桶粒度:≤24h 按小时、≤120 天按天、更长按月(对齐原时间窗预设的口径)。 */ +function granularityOf(spanMs: number): UsageGranularity { + if (spanMs <= 24 * HOUR_MS) return "hour"; + if (spanMs <= 120 * DAY_MS) return "day"; + return "month"; +} + +/** Provider 省略无数据的桶;按响应粒度逐桶补 0 得到稳定柱位(仅展示口径)。 */ +function filledBuckets( + trend: UsageTrend, + pick: (total: UsageTrendPoint["usage"]["total"]) => number | null, +): { key: string; value: number }[] { + const length = BUCKET_KEY_LENGTH[trend.granularity]; + const byKey = new Map( + trend.points.map((point): [string, number] => [point.start_time.slice(0, length), pick(point.usage.total) ?? 0]), + ); + const end = Date.parse(trend.query_range.end_time) - 1; + const buckets: { key: string; value: number }[] = []; + for ( + let ms = bucketStart(trend.granularity, Date.parse(trend.query_range.start_time)); + ms <= end; + ms = nextBucketStart(trend.granularity, ms) + ) { + const key = bucketKey(trend.granularity, ms); + buckets.push({ key, value: byKey.get(key) ?? 0 }); + } + return buckets; +} /** 单个汇总数字:小标签 + 大号数字(与统计卡同款结构,趋势卡内独立声明避免跨文件导出私有组件)。 */ function TrendTotal({ label, value, unit }: { label: string; value: number; unit?: string }) { @@ -25,92 +151,192 @@ function TrendTotal({ label, value, unit }: { label: string; value: number; unit ); } -/** 指标切换:Token 消耗 / 运行时长(两者量级悬殊,图内一次展示一个,汇总行始终同时给出两个总数)。 */ +/** 指标切换:Token 消耗 / 调用次数 / 失败次数 / 运行时长(量级悬殊,图内一次展示一个,汇总行始终同时给出五个总数)。 */ function TrendMetricToggle({ value, onChange }: { value: TrendMetric; onChange: (metric: TrendMetric) => void }) { return ( onChange(next as TrendMetric)} - options={[ - { label: "Token 消耗", value: "tokens" }, - { label: "运行时长", value: "active_seconds" }, - ]} + options={(Object.keys(TREND_METRICS) as TrendMetric[]).map((value) => ({ + value, + label: TREND_METRICS[value].label, + }))} /> ); } -/** 每日单指标柱状图:div 柱 + 三档虚线刻度 + 底部日期;今天(to_day)用实色强调,柱高变化走冻结动效 token。 */ +/** 柱状图:div 柱 + 三档虚线刻度 + 底部时间;同桶可并排多系列柱,当前桶(小时/日/月)实色强调,柱高变化走冻结动效 token。 + * 小时粒度每 4 桶出一个 x 刻度(占位保留柱位对齐),日/月逐桶出刻度。 */ function TrendChart({ - points, - metric, - toDay, + series, + granularity, + currentKey, }: { - points: TemplateUsageTrendPoint[]; - metric: TrendMetric; - toDay: string; + series: TrendChartSeries[]; + granularity: UsageGranularity; + currentKey: string; }) { - const max = Math.max(...points.map((point) => point[metric]), 0); - const unit = metric === "tokens" ? " Token" : " 秒"; - const fmt = (value: number) => value.toLocaleString("zh-CN", { maximumFractionDigits: metric === "tokens" ? 0 : 1 }); + const [primary] = series; + if (!primary) return null; + const max = Math.max(...series.flatMap((s) => s.points.map((point) => point.value)), 0) || 1; + const fmtFor = (meta: TrendChartMeta) => (value: number) => + value.toLocaleString("zh-CN", { maximumFractionDigits: meta.decimals }); + const axisFmt = fmtFor(primary.meta); + const buckets = primary.points.map((point) => ({ + key: point.key, + current: point.key === currentKey, + label: bucketLabel(granularity, point.key), + bars: series.map((s) => ({ + meta: s.meta, + variant: s.variant, + value: s.points.find((candidate) => candidate.key === point.key)?.value ?? 0, + })), + })); return ( -
- {/* pt-3 给 y 轴最上方的 max 刻度留出上溢空间(-translate-y-1/2 会探出容器半行),避免与汇总行重叠。 */} -
- {[0, 1, 2, 3].map((step) => ( - - {fmt((max * step) / 3)} - - ))} -
-
-
+ <> +
+ {/* pt-3 给 y 轴最上方的 max 刻度留出上溢空间(-translate-y-1/2 会探出容器半行),避免与汇总行重叠。 */} +
{[0, 1, 2, 3].map((step) => ( -
+ + {axisFmt((max * step) / 3)} + ))} -
- {points.map((point) => ( +
+
+
+ {[0, 1, 2, 3].map((step) => (
+ key={step} + className={step === 0 ? styles.gridLine : `${styles.gridLine} ${styles.gridLineDashed}`} + style={{ bottom: `${(step * 100) / 3}%` }} + /> + ))} +
+ {buckets.map((bucket) => (
-
+ key={bucket.key} + className={styles.barSlot} + title={`${bucket.label} · ${bucket.bars + .map((bar) => `${bar.meta.label} ${fmtFor(bar.meta)(bar.value)}${bar.meta.unit}`) + .join(" · ")}`} + > + {bucket.bars.map((bar) => ( +
+ ))} +
+ ))} +
+
+
+ {primary.points.map((point) => ( + + {granularity === "hour" && Number(point.key.slice(11, 13)) % 4 !== 0 + ? "" + : bucketLabel(granularity, point.key)} + ))}
-
- {points.map((point) => ( - - {shortDay(point.day)} +
+ {series.length > 1 ? ( +
+ {series.map((s) => ( + +