| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947 |
- // @vitest-environment jsdom
- import { createElement, type ComponentProps } from "react";
- import { renderToStaticMarkup } from "react-dom/server";
- import { readFileSync } from "node:fs";
- import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
- import { afterEach, describe, expect, it, vi } from "vitest";
- import { BUILTIN_MODEL_PROVIDER_IDS } from "@zcode/shared";
- import {
- ChatCodingPlanUsageRemainingPanel,
- hasChatCodingPlanUsageRemaining,
- shouldShowContextQuotaResetTime,
- } from "../src/chat-input-toolbar/CodingPlanContextUsage.js";
- import { ChatCodingPlanMcpUsageMeter } from "../src/chat-input-toolbar/ChatCodingPlanMcpUsageMeter.js";
- import {
- ChatStartPlanBalancePanel,
- hasChatStartPlanBalance,
- } from "../src/chat-input-toolbar/StartPlanContextBalance.js";
- import {
- ChatContextUsage,
- buildContextUsageBreakdownSegments,
- buildContextUsageProgressSegments,
- formatContextCacheHitRateLabel,
- formatContextUsageSummary,
- formatContextUsageTokenCount,
- refreshContextUsageOnOpen,
- } from "../src/chat-input-toolbar/contextUsage.js";
- import {
- CodingPlanUsageRemainingPanel,
- type CodingPlanUsageAvailableProvider,
- hasCodingPlanUsageRemainingPanel,
- resolveCodingPlanUsageRemainingState,
- } from "../src/CodingPlanUsageRemainingPanel.js";
- import {
- resolveSidebarCodingPlanUpgradeFallbackProviderId,
- resolveSidebarCodingPlanUpgradeProviderId,
- } from "../src/lib/sidebarCodingPlanUpgrade.js";
- import { getContextQuotaMeterGridClass } from "../src/chat-input-toolbar/contextQuotaMeterGrid.js";
- import { resolveMcpQuotaLimit } from "../src/lib/codingPlanQuotaPresentation.js";
- import enMessages from "../src/i18n/locales/en-US.js";
- import zhMessages from "../src/i18n/locales/zh-CN.js";
- import { TooltipProvider } from "../src/components/ui/tooltip.js";
- const activeSubscription = {
- identityType: "unknown" as const,
- identityMasked: null,
- details: [{ productId: "coding-pro", productName: "Coding Pro" }],
- };
- const codingPlanQuotaResetUiMock = vi.hoisted(() => {
- const createController = () => ({
- entry: null,
- opportunityVisible: false,
- processing: false,
- done: false,
- statusVisible: false,
- reset: vi.fn(async () => undefined),
- });
- const createValue = () => ({
- enabled: false,
- ...createController(),
- week: createController(),
- reserveAutomaticCompletion: vi.fn(async () => ({ status: "blocked" })),
- commitAutomaticCompletion: vi.fn(() => false),
- releaseAutomaticCompletion: vi.fn(async () => undefined),
- });
- return { current: createValue() as unknown, createValue };
- });
- vi.mock("@/hooks/useCodingPlanQuotaResetUi.js", () => ({
- useCodingPlanQuotaResetUi: () => codingPlanQuotaResetUiMock.current,
- }));
- vi.mock("../src/CodingPlanBillingDiscount.js", () => ({
- CodingPlanBillingDiscountBadge: ({ size, variant }: { size?: string; variant?: string }) =>
- `billing-discount-badge:${variant ?? "gradient"}:${size ?? "default"}`,
- CodingPlanBillingDiscountBadgePill: ({ size, variant }: { size?: string; variant?: string }) =>
- `billing-discount-badge:${variant ?? "gradient"}:${size ?? "default"}`,
- CodingPlanBillingDiscountInfoDialog: () => "billing-discount-info",
- useCodingPlanBillingDiscount: () => ({ active: true, loading: false }),
- }));
- describe("context usage access refresh", () => {
- it("只在 Context 打开时触发后台额度刷新", () => {
- const onAccess = vi.fn();
- refreshContextUsageOnOpen(false, onAccess);
- refreshContextUsageOnOpen(true, onAccess);
- expect(onAccess).toHaveBeenCalledTimes(1);
- });
- it("无缓存快照时仍保留 hover 触发器", () => {
- expect(
- hasChatCodingPlanUsageRemaining({
- availableProviders: [],
- entitlements: [
- {
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- snapshot: null,
- loading: false,
- error: null,
- },
- ],
- modelProvidersLoading: false,
- onAccess: vi.fn(),
- }),
- ).toBe(true);
- });
- });
- vi.mock("../src/i18n/IntlProvider.js", () => ({
- useZCodeIntl: () => ({
- locale: "en-US",
- intl: {
- formatMessage: ({ id }: { id: string }) => id,
- },
- }),
- }));
- vi.mock("@/components/ai-elements/context.js", async () => {
- const React = await import("react");
- const passthrough =
- (tag: "button" | "div") =>
- ({ children, ...props }: { children?: React.ReactNode }) =>
- React.createElement(tag, props, children);
- return {
- Context: passthrough("div"),
- ContextContent: passthrough("div"),
- ContextContentBody: passthrough("div"),
- ContextTrigger: passthrough("button"),
- };
- });
- afterEach(() => {
- codingPlanQuotaResetUiMock.current = codingPlanQuotaResetUiMock.createValue();
- cleanup();
- vi.useRealTimers();
- });
- function createCodingPlanProvider(
- id:
- | typeof BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan
- | typeof BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- ): CodingPlanUsageAvailableProvider {
- return {
- providerId: id,
- label: id,
- };
- }
- function renderFiveHourResetPanel() {
- const availableProviders = [
- createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
- ];
- // 完成态会用 nextResetAt 兜底展示重置时间(带 Tooltip);真实应用中面板总在 TooltipProvider 下。
- render(
- createElement(
- TooltipProvider,
- null,
- createElement(ChatCodingPlanUsageRemainingPanel, {
- config: {
- availableProviders,
- entitlements: [
- {
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- loading: false,
- error: null,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- name: "Z.ai Coding Plan",
- },
- remaining: null,
- subscription: activeSubscription,
- quota: {
- level: "pro",
- limits: [
- {
- type: "TOKENS_LIMIT",
- unit: 3,
- number: 5,
- percentage: 35,
- usageDetails: [],
- },
- ],
- },
- },
- },
- ],
- modelProvidersLoading: false,
- },
- intl: {
- formatMessage: ({ id }: { id: string }) => id,
- } as never,
- locale: "en-US",
- }),
- ),
- );
- }
- describe("ChatCodingPlanUsageRemainingPanel reset action", () => {
- it("五小时有两次重置机会时仍在额度标题旁显示直接重置按钮", () => {
- const reset = vi.fn(async () => undefined);
- codingPlanQuotaResetUiMock.current = {
- ...codingPlanQuotaResetUiMock.createValue(),
- enabled: true,
- entry: {
- status: "available",
- opportunityCount: 2,
- opportunityExpiresAt: Date.now() + 60_000,
- startedAt: null,
- completedAt: null,
- observedAt: null,
- quotaOverridePending: false,
- nextResetAt: null,
- idempotencyKey: "five-hour-two-opportunities",
- error: null,
- },
- opportunityVisible: true,
- reset,
- };
- renderFiveHourResetPanel();
- expect(screen.getByRole("button", { name: "codingPlan.quotaReset.openDialog" })).toBeTruthy();
- expect(screen.getByRole("button", { name: "codingPlan.quotaReset.resetAria" })).toBeTruthy();
- });
- it("核销一张后同类型仍有余下机会时,额度标题旁保持可点击「重置」而非「已重置」", () => {
- const completedAt = Date.now() - 1_000;
- codingPlanQuotaResetUiMock.current = {
- ...codingPlanQuotaResetUiMock.createValue(),
- enabled: true,
- entry: {
- status: "completed",
- opportunityCount: 1,
- opportunityExpiresAt: Date.now() + 60_000,
- startedAt: completedAt - 1_000,
- completedAt,
- observedAt: completedAt,
- quotaOverridePending: false,
- nextResetAt: completedAt + 5 * 60 * 60 * 1_000,
- idempotencyKey: null,
- error: null,
- },
- opportunityVisible: true,
- done: true,
- };
- renderFiveHourResetPanel();
- expect(screen.getByRole("button", { name: "codingPlan.quotaReset.resetAria" })).toBeTruthy();
- expect(screen.queryByText("codingPlan.quotaReset.completed")).toBeNull();
- });
- });
- describe("ChatCodingPlanUsageRemainingPanel MCP 额度", () => {
- it("ZCode MCP tooltip 使用精简的每日合计额度说明", () => {
- expect(zhMessages["sidebar.usage.plan.zcodeMcpDescription"]).toBe(
- "ZCode 预置插件 MCP 每日合计额度",
- );
- expect(enMessages["sidebar.usage.plan.zcodeMcpDescription"]).toBe(
- "Daily aggregate quota for ZCode built-in plugin MCPs",
- );
- });
- it("ZCode MCP 文字保持普通前景色,进度条复用图表黄色", () => {
- const styles = readFileSync("packages/ui/src/styles.css", "utf8");
- expect(styles).toContain("--color-usage-chart-5: #e07b00;");
- expect(styles).toContain("--color-usage-chart-5: #ff8a30;");
- expect(styles).not.toContain("--zcode-mcp-progress");
- expect(styles).not.toContain("--zcode-mcp-gradient-");
- expect(styles).not.toContain("zcode-mcp-gradient-text");
- });
- it("三张主额度占满首行时,官方 Server MCP 在下一行横跨三列", () => {
- codingPlanQuotaResetUiMock.current = codingPlanQuotaResetUiMock.createValue();
- const html = renderToStaticMarkup(
- createElement(ChatCodingPlanUsageRemainingPanel, {
- config: {
- availableProviders: [
- createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
- ],
- entitlements: [
- {
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- loading: false,
- error: null,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- name: "Z.ai Coding Plan",
- },
- remaining: null,
- subscription: activeSubscription,
- quota: {
- level: "pro",
- limits: [
- { type: "TOKENS_LIMIT", unit: 3, number: 5, percentage: 2, usageDetails: [] },
- { type: "TOKENS_LIMIT", unit: 6, percentage: 1, usageDetails: [] },
- { type: "TIME_LIMIT", unit: 5, number: 1, percentage: 0, usageDetails: [] },
- ],
- },
- mcpQuota: {
- serverTime: 1_755_571_234_000,
- level: "pro",
- scope: { providerFamily: "zai", targetType: "PERSONAL" },
- buckets: [{ bucket: "search_image", used: 25, limit: 100, remaining: 75 }],
- aggregate: {
- type: "MCP_USAGE_LIMIT",
- percentage: 25,
- remaining: 75,
- nextResetTime: Date.UTC(2025, 7, 21),
- usageDetails: [],
- },
- },
- },
- },
- ],
- modelProvidersLoading: false,
- },
- intl: {
- formatMessage: ({ id }: { id: string }) => id,
- } as never,
- locale: "en-US",
- }),
- );
- expect(html).toContain("grid-cols-3");
- expect(html).toContain('data-context-mcp-usage="inline"');
- expect(html).toContain('data-context-mcp-layout="full-row"');
- expect(html).toContain('data-primary-quota-count="3"');
- expect(html).toContain("col-span-3");
- expect(html).toContain("width:calc((100% - 1rem) / 3)");
- expect(html).toContain("mt-1");
- expect(html).toContain("border-t border-border pt-1.5");
- expect(html).toContain(
- "ml-auto min-w-0 shrink overflow-hidden text-ellipsis whitespace-nowrap",
- );
- expect(html).not.toContain("rounded-lg bg-surface px-2 py-1.5");
- expect(html).toContain("sidebar.usage.plan.zcodeMcp");
- expect(html).toContain('data-context-mcp-info="true"');
- expect(html).toContain('aria-label="sidebar.usage.plan.zcodeMcpDescription"');
- expect(html).toContain(
- '<span class="min-w-0 truncate text-foreground-subtle">sidebar.usage.plan.zcodeMcp</span>',
- );
- expect(html).not.toContain(
- '<span class="font-medium text-foreground">sidebar.usage.plan.zcodeMcp</span>',
- );
- expect(html).not.toContain("zcode-mcp-gradient-text");
- expect(html).toContain("background-color:var(--color-usage-chart-5)");
- // percentage 是已使用占比,展示时反转成剩余。
- expect(html).toContain("75%");
- expect(html).toMatch(/>75%<\/span><span[^>]*> · Aug 21<\/span>/);
- expect(html).toContain("width:75%");
- });
- it("没有 MCP 额度时保持三列", () => {
- codingPlanQuotaResetUiMock.current = codingPlanQuotaResetUiMock.createValue();
- const html = renderToStaticMarkup(
- createElement(ChatCodingPlanUsageRemainingPanel, {
- config: {
- availableProviders: [
- createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
- ],
- entitlements: [
- {
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- loading: false,
- error: null,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- name: "Z.ai Coding Plan",
- },
- remaining: null,
- subscription: activeSubscription,
- quota: {
- level: "pro",
- limits: [
- { type: "TOKENS_LIMIT", unit: 3, number: 5, percentage: 2, usageDetails: [] },
- { type: "TOKENS_LIMIT", unit: 6, percentage: 1, usageDetails: [] },
- { type: "TIME_LIMIT", unit: 5, number: 1, percentage: 0, usageDetails: [] },
- ],
- },
- },
- },
- ],
- modelProvidersLoading: false,
- },
- intl: {
- formatMessage: ({ id }: { id: string }) => id,
- } as never,
- locale: "en-US",
- }),
- );
- expect(html).toContain("grid-cols-3");
- expect(html).not.toContain("sidebar.usage.plan.mcp");
- });
- it("两张主额度时 MCP 使用第三列的卡片布局", () => {
- const html = renderToStaticMarkup(
- createElement(ChatCodingPlanMcpUsageMeter, {
- color: "var(--color-usage-chart-5)",
- description: "description",
- label: "ZCode MCP",
- percentage: 75,
- primaryQuotaCount: 2,
- value: "75%",
- }),
- );
- expect(html).toContain('data-primary-quota-count="2"');
- expect(html).toContain('data-context-mcp-layout="card"');
- expect(html).toContain("space-y-1.5");
- expect(html).not.toContain("col-span-3");
- expect(html).not.toContain("border-t border-border");
- expect(html).not.toContain("width:calc(");
- });
- });
- describe("getContextQuotaMeterGridClass", () => {
- it("按非 MCP 额度条数选择一至三列", () => {
- expect(getContextQuotaMeterGridClass(1)).toBe("grid-cols-1");
- expect(getContextQuotaMeterGridClass(2)).toBe("grid-cols-2");
- expect(getContextQuotaMeterGridClass(3)).toBe("grid-cols-3");
- expect(getContextQuotaMeterGridClass(4)).toBe("grid-cols-3");
- });
- });
- describe("resolveMcpQuotaLimit", () => {
- it("缺少快照或 MCP 额度时返回 null", () => {
- expect(resolveMcpQuotaLimit(null)).toBeNull();
- expect(
- resolveMcpQuotaLimit({
- generatedAt: 1,
- authenticated: true,
- provider: null,
- remaining: null,
- subscription: null,
- quota: null,
- }),
- ).toBeNull();
- });
- it("有 MCP 额度时返回汇总额度条", () => {
- const aggregate = {
- type: "MCP_USAGE_LIMIT",
- percentage: 16,
- remaining: 1032,
- usageDetails: [],
- };
- expect(
- resolveMcpQuotaLimit({
- generatedAt: 1,
- authenticated: true,
- provider: null,
- remaining: null,
- subscription: null,
- quota: null,
- mcpQuota: {
- serverTime: 1,
- level: "pro",
- scope: { providerFamily: "bigmodel", targetType: "PERSONAL" },
- buckets: [],
- aggregate,
- },
- }),
- ).toBe(aggregate);
- });
- });
- describe("ChatCodingPlanUsageRemainingPanel refresh action", () => {
- it("远端刷新成功时用 loading 与成功勾临时代替详情入口", () => {
- vi.useFakeTimers();
- const availableProviders = [
- createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
- ];
- const entitlement = {
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- loading: true,
- error: null,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- name: "Z.ai Coding Plan",
- },
- remaining: null,
- subscription: activeSubscription,
- quota: {
- level: "pro",
- limits: [
- {
- type: "TOKENS_LIMIT",
- unit: 3,
- number: 5,
- percentage: 35,
- usageDetails: [],
- },
- ],
- },
- },
- } satisfies ComponentProps<
- typeof ChatCodingPlanUsageRemainingPanel
- >["config"]["entitlements"][number];
- const props = {
- config: {
- availableProviders,
- entitlements: [entitlement],
- modelProvidersLoading: false,
- onUsageClick: vi.fn(),
- },
- intl: {
- formatMessage: ({ id }: { id: string }) => id,
- } as never,
- locale: "en-US",
- } satisfies ComponentProps<typeof ChatCodingPlanUsageRemainingPanel>;
- const view = render(createElement(ChatCodingPlanUsageRemainingPanel, props));
- expect(screen.queryByRole("button", { name: "sidebar.usage.plan.open" })).toBeNull();
- expect(screen.getByRole("status", { name: "sidebar.usage.plan.refreshing" })).toBeTruthy();
- view.rerender(
- createElement(ChatCodingPlanUsageRemainingPanel, {
- ...props,
- config: {
- ...props.config,
- entitlements: [{ ...entitlement, loading: false }],
- },
- }),
- );
- expect(screen.queryByRole("button", { name: "sidebar.usage.plan.open" })).toBeNull();
- expect(screen.getByRole("status", { name: "sidebar.usage.plan.updated" })).toBeTruthy();
- act(() => vi.advanceTimersByTime(1_000));
- expect(screen.queryByRole("status", { name: "sidebar.usage.plan.updated" })).toBeNull();
- expect(screen.getByRole("button", { name: "sidebar.usage.plan.open" })).toBeTruthy();
- });
- it("静默 access 刷新中即使缓存快照不标记 loading 也显示 loading", () => {
- const availableProviders = [
- createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
- ];
- const entitlement = {
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- loading: false,
- error: null,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- name: "Z.ai Coding Plan",
- },
- remaining: null,
- subscription: activeSubscription,
- quota: {
- level: "pro",
- limits: [
- {
- type: "TOKENS_LIMIT",
- unit: 3,
- number: 5,
- percentage: 35,
- usageDetails: [],
- },
- ],
- },
- },
- } satisfies ComponentProps<
- typeof ChatCodingPlanUsageRemainingPanel
- >["config"]["entitlements"][number];
- render(
- createElement(ChatCodingPlanUsageRemainingPanel, {
- config: {
- availableProviders,
- entitlements: [entitlement],
- modelProvidersLoading: false,
- refreshing: true,
- onUsageClick: vi.fn(),
- },
- intl: {
- formatMessage: ({ id }: { id: string }) => id,
- } as never,
- locale: "en-US",
- }),
- );
- expect(screen.queryByRole("button", { name: "sidebar.usage.plan.open" })).toBeNull();
- expect(screen.getByRole("status", { name: "sidebar.usage.plan.refreshing" })).toBeTruthy();
- });
- it("有缓存快照刷新失败时在更多旁边显示 warning info tooltip", () => {
- const availableProviders = [
- createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
- ];
- const onEntitlementRefresh = vi.fn();
- const view = render(
- createElement(ChatCodingPlanUsageRemainingPanel, {
- config: {
- availableProviders,
- entitlements: [
- {
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- loading: false,
- error: "usage_entitlement_request_timeout:20000",
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- name: "Z.ai Coding Plan",
- },
- remaining: null,
- subscription: activeSubscription,
- quota: {
- level: "pro",
- limits: [
- {
- type: "TOKENS_LIMIT",
- unit: 3,
- number: 5,
- percentage: 35,
- usageDetails: [],
- },
- ],
- },
- },
- },
- ],
- modelProvidersLoading: false,
- onEntitlementRefresh,
- onUsageClick: vi.fn(),
- },
- intl: {
- formatMessage: ({ id }: { id: string }) => id,
- } as never,
- locale: "en-US",
- }),
- );
- expect(view.container.textContent).toContain("sidebar.usage.plan.fiveHour");
- expect(view.container.textContent).not.toContain("usage_entitlement_request_timeout");
- expect(view.container.innerHTML).not.toContain("border-destructive");
- expect(screen.getByLabelText("sidebar.usage.plan.updateFailed")).toBeTruthy();
- expect(screen.getByRole("button", { name: "sidebar.usage.plan.open" })).toBeTruthy();
- expect(screen.queryByRole("button", { name: "sidebar.usage.plan.refresh" })).toBeNull();
- });
- it("无可展示额度时复用 info notice 和刷新按钮", () => {
- const availableProviders = [
- createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
- ];
- const onEntitlementRefresh = vi.fn();
- const view = render(
- createElement(ChatCodingPlanUsageRemainingPanel, {
- config: {
- availableProviders,
- entitlements: [
- {
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- loading: false,
- error: null,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- name: "Z.ai Coding Plan",
- },
- remaining: null,
- subscription: activeSubscription,
- quota: {
- level: null,
- limits: [],
- },
- },
- },
- ],
- modelProvidersLoading: false,
- onEntitlementRefresh,
- },
- intl: {
- formatMessage: ({ id }: { id: string }) => id,
- } as never,
- locale: "en-US",
- }),
- );
- expect(view.container.textContent).toContain("sidebar.usage.plan.unavailable");
- expect(view.container.innerHTML).toContain("data-coding-plan-usage-notice");
- expect(screen.getByRole("button", { name: "sidebar.usage.plan.refresh" })).toBeTruthy();
- });
- });
- describe("buildContextUsageBreakdownSegments", () => {
- it("aggregates valid chars by source and sorts largest first", () => {
- expect(
- buildContextUsageBreakdownSegments([
- { source: "messages", chars: 700 },
- { source: "system_tool_schemas", chars: 200 },
- { source: "messages", chars: 100 },
- { source: "skills", chars: 0 },
- ]),
- ).toEqual([
- { source: "messages", chars: 800, percent: 0.8 },
- { source: "system_tool_schemas", chars: 200, percent: 0.2 },
- ]);
- });
- it("returns an empty list when no positive chars are available", () => {
- expect(
- buildContextUsageBreakdownSegments([
- { source: "messages", chars: 0 },
- { source: "skills", chars: -1 },
- ]),
- ).toEqual([]);
- });
- it("assigns the Coding Plan blue tone to the largest segment", () => {
- const segments = buildContextUsageBreakdownSegments([
- { source: "messages", chars: 100 },
- { source: "mcp_tool_schemas", chars: 900 },
- { source: "system_prompt", chars: 300 },
- ]);
- expect(buildContextUsageProgressSegments(segments)).toEqual([
- {
- id: "mcp_tool_schemas",
- percent: 0.6923076923076923,
- style: { backgroundColor: "var(--color-usage-chart-1)" },
- },
- {
- id: "system_prompt",
- percent: 0.23076923076923078,
- style: {
- backgroundColor:
- "color-mix(in oklab, var(--color-usage-chart-1) 78%, var(--color-surface))",
- },
- },
- {
- id: "messages",
- percent: 0.07692307692307693,
- style: {
- backgroundColor:
- "color-mix(in oklab, var(--color-usage-chart-1) 58%, var(--color-surface))",
- },
- },
- ]);
- });
- it("keeps later Coding Plan blue tones readable on the popover background", () => {
- const segments = buildContextUsageBreakdownSegments([
- { source: "messages", chars: 600 },
- { source: "system_prompt", chars: 500 },
- { source: "meta_user_context", chars: 400 },
- { source: "skills", chars: 300 },
- { source: "tool_prompt", chars: 200 },
- { source: "system_tool_schemas", chars: 100 },
- ]);
- expect(buildContextUsageProgressSegments(segments).at(-1)?.style).toEqual({
- backgroundColor: "color-mix(in oklab, var(--color-usage-chart-1) 28%, var(--color-surface))",
- });
- });
- });
- describe("formatContextUsageTokenCount", () => {
- it("uses uppercase compact suffixes for English context usage", () => {
- expect(formatContextUsageTokenCount(399_900, "en-US")).toBe("399.9K");
- expect(formatContextUsageTokenCount(200_000, "en-US")).toBe("200K");
- expect(formatContextUsageTokenCount(1_250_000, "en-US")).toBe("1.3M");
- });
- it("uses localized compact units for Chinese context usage", () => {
- expect(formatContextUsageTokenCount(399_900, "zh-CN")).toBe("40万");
- expect(formatContextUsageTokenCount(200_000, "zh-CN")).toBe("20万");
- expect(formatContextUsageTokenCount(120_000_000, "zh-CN")).toBe("1.2亿");
- });
- });
- describe("formatContextUsageSummary", () => {
- it("combines compact token values and usage percentage", () => {
- expect(
- formatContextUsageSummary({
- locale: "en-US",
- percent: 1,
- size: 200_000,
- used: 399_900,
- }),
- ).toBe("399.9K/200K (100%)");
- });
- });
- describe("formatContextCacheHitRateLabel", () => {
- it("keeps the production threshold for low cache hit rates", () => {
- expect(formatContextCacheHitRateLabel(0.048, "en-US")).toBeNull();
- });
- it("formats low cache hit rates when development diagnostics are enabled", () => {
- expect(
- formatContextCacheHitRateLabel(0.048, "en-US", {
- showBelowThreshold: true,
- }),
- ).toBe("4.8%");
- });
- it("does not invent a cache hit rate when the provider omits it", () => {
- expect(
- formatContextCacheHitRateLabel(null, "en-US", {
- showBelowThreshold: true,
- }),
- ).toBeNull();
- });
- });
- describe("ChatContextUsage", () => {
- it("在 Context 面板外点击时关闭额度重置提醒并清理监听器", async () => {
- codingPlanQuotaResetUiMock.current = {
- ...codingPlanQuotaResetUiMock.createValue(),
- enabled: true,
- entry: {
- status: "available",
- opportunityCount: 1,
- opportunityExpiresAt: Date.now() + 60_000,
- startedAt: null,
- completedAt: null,
- observedAt: null,
- quotaOverridePending: false,
- nextResetAt: null,
- idempotencyKey: "context-outside-dismiss",
- error: null,
- },
- opportunityVisible: true,
- };
- const provider = createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan);
- render(
- createElement(
- TooltipProvider,
- null,
- createElement(ChatContextUsage, {
- codingPlanUsageRemaining: {
- availableProviders: [provider],
- entitlements: [
- {
- providerId: provider.providerId,
- loading: false,
- error: null,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: { id: provider.providerId, name: provider.label },
- remaining: null,
- subscription: activeSubscription,
- quota: {
- level: "pro",
- limits: [
- {
- type: "TOKENS_LIMIT",
- unit: 3,
- number: 5,
- percentage: 35,
- usageDetails: [],
- },
- ],
- },
- },
- },
- ],
- modelProvidersLoading: false,
- },
- intl: {
- formatMessage: ({ id }: { id: string }) => id,
- } as never,
- locale: "en-US",
- selectedProvider: "glm",
- taskUsage: null,
- }),
- ),
- );
- expect(
- screen.getAllByText("codingPlan.quotaReset.contextReminder.expiresIn").length,
- ).toBeGreaterThan(0);
- fireEvent.pointerDown(document.body);
- await waitFor(() => {
- expect(screen.queryAllByText("codingPlan.quotaReset.contextReminder.expiresIn")).toEqual([]);
- });
- });
- it("does not render derived zero-usage capacity without task usage or plan data", () => {
- const html = renderToStaticMarkup(
- createElement(ChatContextUsage, {
- ...({
- contextCapacityTokens: 1_000_000,
- } as Partial<ComponentProps<typeof ChatContextUsage>>),
- intl: {
- formatMessage: ({ id }: { id: string }) => id,
- },
- locale: "en-US",
- selectedProvider: "glm",
- taskUsage: null,
- }),
- );
- expect(html).not.toContain("chat.contextUsage.title");
- expect(html).not.toContain("0/1M (0%)");
- });
- it("renders cache hit rate when the context usage reaches the display threshold", () => {
- const html = renderToStaticMarkup(
- createElement(ChatContextUsage, {
- intl: {
- formatMessage: ({ id }: { id: string }) => id,
- },
- locale: "en-US",
- selectedProvider: "glm",
- taskUsage: {
- used: 17_000,
- size: 1_000_000,
- cache: { hitRate: 0.8 },
- },
- }),
- );
- expect(html).toContain("chat.contextUsage.cacheHitRate");
- expect(html).toContain("80%");
- });
- it("renders a low cache hit rate in the development environment", () => {
- const html = renderToStaticMarkup(
- createElement(ChatContextUsage, {
- intl: {
- formatMessage: ({ id }: { id: string }) => id,
- },
- locale: "en-US",
- selectedProvider: "glm",
- taskUsage: {
- used: 17_000,
- size: 1_000_000,
- cache: { hitRate: 0.048 },
- },
- }),
- );
- expect(import.meta.env.DEV).toBe(true);
- expect(html).toContain("chat.contextUsage.cacheHitRate");
- expect(html).toContain("4.8%");
- });
- it("renders Coding Plan quota without real task context usage", () => {
- const availableProviders = [
- createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
- ];
- const html = renderToStaticMarkup(
- createElement(ChatContextUsage, {
- codingPlanUsageRemaining: {
- availableProviders,
- entitlements: [
- {
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- loading: false,
- error: null,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- name: "Z.ai Coding Plan",
- },
- remaining: null,
- subscription: activeSubscription,
- quota: {
- level: "pro",
- limits: [
- {
- type: "TOKENS_LIMIT",
- unit: 3,
- number: 5,
- percentage: 35,
- usageDetails: [],
- },
- ],
- },
- },
- },
- ],
- modelProvidersLoading: false,
- },
- intl: {
- formatMessage: ({ id }: { id: string }) => id,
- } as never,
- locale: "en-US",
- selectedProvider: "glm",
- taskUsage: null,
- }),
- );
- expect(html).toContain("sidebar.usage.plan.title");
- expect(html).toContain("sidebar.usage.plan.fiveHour");
- });
- it("does not render per-source token counts in the breakdown rows", () => {
- const html = renderToStaticMarkup(
- createElement(ChatContextUsage, {
- intl: {
- formatMessage: ({ id }: { id: string }) => id,
- },
- locale: "en-US",
- selectedProvider: "glm",
- taskUsage: {
- used: 17_000,
- size: 1_000_000,
- breakdown: [
- { source: "system_tool_schemas", chars: 52_000 },
- { source: "messages", chars: 38_000 },
- ],
- },
- }),
- );
- expect(html).toContain("chat.contextUsage.breakdown.systemTools");
- expect(html).toContain("chat.contextUsage.breakdown.messages");
- expect(html).toContain("57.8%");
- expect(html).toContain("42.2%");
- expect(html).not.toContain("52K");
- expect(html).not.toContain("38K");
- });
- });
- describe("Coding Plan usage remaining panel state", () => {
- it("does not show the billing discount badge in sidebar usage remaining", () => {
- const availableProviders = [
- createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
- ];
- const html = renderToStaticMarkup(
- createElement(CodingPlanUsageRemainingPanel, {
- availableProviders,
- entitlements: [
- {
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- loading: false,
- error: null,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- name: "Z.ai Coding Plan",
- },
- remaining: null,
- subscription: activeSubscription,
- quota: {
- level: "pro",
- limits: [],
- },
- },
- },
- ],
- modelProvidersLoading: false,
- }),
- );
- expect(html).toContain("sidebar.usage.plan.codingPlanTitle");
- expect(html).not.toContain("billing-discount-badge");
- });
- it("renders the sidebar usage details action as a link button with an arrow", () => {
- const availableProviders = [
- createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
- ];
- const html = renderToStaticMarkup(
- createElement(CodingPlanUsageRemainingPanel, {
- availableProviders,
- entitlements: [
- {
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- loading: false,
- error: null,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- name: "Z.ai Coding Plan",
- },
- remaining: null,
- subscription: activeSubscription,
- quota: {
- level: "pro",
- limits: [],
- },
- },
- },
- ],
- modelProvidersLoading: false,
- onUsageClick: vi.fn(),
- }),
- );
- expect(html).toContain('data-variant="link"');
- expect(html).toContain("sidebar.usage.plan.open");
- expect(html).toContain("lucide-chevron-right");
- });
- it("renders a single sidebar audience badge without source tabs", () => {
- const availableProviders = [
- createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan),
- ];
- const html = renderToStaticMarkup(
- createElement(CodingPlanUsageRemainingPanel, {
- audience: "team",
- availableProviders,
- entitlements: [
- {
- sourceId: "team:bigmodel:team-pro:project-a",
- providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- label: "BigModel - Project A",
- loading: false,
- error: null,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- name: "BigModel Coding Plan",
- },
- remaining: null,
- subscription: activeSubscription,
- quota: {
- level: "team",
- limits: [
- {
- type: "TOKENS_LIMIT",
- unit: 3,
- number: 5,
- percentage: 80,
- usageDetails: [],
- },
- ],
- },
- },
- },
- {
- providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- loading: false,
- error: null,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- name: "BigModel Coding Plan",
- },
- remaining: null,
- subscription: activeSubscription,
- quota: {
- level: "pro",
- limits: [
- {
- type: "TOKENS_LIMIT",
- unit: 6,
- percentage: 50,
- usageDetails: [],
- },
- ],
- },
- },
- },
- ],
- modelProvidersLoading: false,
- selectedProviderId: "team:bigmodel:team-pro:project-a",
- }),
- );
- expect(html).toContain("sidebar.usage.plan.codingPlanTitle");
- expect(html).toContain("sidebar.usage.plan.audienceTeam");
- expect(html).not.toContain("aria-pressed");
- });
- it("会话 Coding Plan 用量面板不显示 150% 活动徽标", () => {
- const availableProviders = [
- createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
- ];
- const html = renderToStaticMarkup(
- createElement(ChatCodingPlanUsageRemainingPanel, {
- config: {
- availableProviders,
- entitlements: [
- {
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- loading: false,
- error: null,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- name: "Z.ai Coding Plan",
- },
- remaining: null,
- subscription: activeSubscription,
- quota: {
- level: "pro",
- limits: [
- {
- type: "TOKENS_LIMIT",
- unit: 3,
- number: 5,
- percentage: 35,
- nextResetTime: Date.UTC(2026, 0, 2, 8, 30),
- usageDetails: [],
- },
- {
- type: "TOKENS_LIMIT",
- unit: 6,
- percentage: 45,
- nextResetTime: Date.UTC(2026, 0, 9, 0, 0),
- usageDetails: [],
- },
- {
- type: "TIME_LIMIT",
- unit: 5,
- number: 1,
- percentage: 55,
- nextResetTime: Date.UTC(2026, 0, 31, 0, 0),
- usageDetails: [],
- },
- ],
- },
- },
- },
- ],
- modelProvidersLoading: false,
- },
- intl: {
- formatMessage: ({ id }: { id: string }) => id,
- } as never,
- locale: "en-US",
- }),
- );
- expect(html).toContain("sidebar.usage.plan.title");
- expect(html).not.toContain("billing-discount-badge:gradient:compact");
- expect(html).toContain("grid-cols-3");
- expect(html).toContain("space-y-0.5");
- expect(html).toContain("h-1.5");
- expect(html).toContain("text-ui-xs text-foreground-subtle");
- expect(html).toContain("background-color:var(--color-usage-chart-1)");
- expect(html).toContain("background-color:var(--color-usage-chart-2)");
- expect(html).toContain("background-color:var(--color-usage-chart-3)");
- expect(html).toContain(" · ");
- expect(html).not.toContain('font-mono text-ui-sm tabular-nums"><span class="text-foreground');
- });
- it("hides a Coding Plan reset time when its full value exceeds the meter width", () => {
- expect(shouldShowContextQuotaResetTime({ availableWidth: 120, contentWidth: 119 })).toBe(true);
- expect(shouldShowContextQuotaResetTime({ availableWidth: 120, contentWidth: 121 })).toBe(false);
- });
- it("shows only time for non-today 5 hour Coding Plan reset in chat context usage", () => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date(2026, 0, 2, 7, 0));
- try {
- const availableProviders = [
- createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
- ];
- const html = renderToStaticMarkup(
- createElement(ChatCodingPlanUsageRemainingPanel, {
- config: {
- availableProviders,
- entitlements: [
- {
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- loading: false,
- error: null,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- name: "Z.ai Coding Plan",
- },
- remaining: null,
- subscription: activeSubscription,
- quota: {
- level: "pro",
- limits: [
- {
- type: "TOKENS_LIMIT",
- unit: 3,
- number: 5,
- percentage: 35,
- nextResetTime: new Date(2026, 0, 3, 8, 30).getTime(),
- usageDetails: [],
- },
- ],
- },
- },
- },
- ],
- modelProvidersLoading: false,
- },
- intl: {
- formatMessage: ({ id }: { id: string }) => id,
- } as never,
- locale: "en-US",
- }),
- );
- expect(html).toContain(" · 08:30");
- expect(html).not.toContain("Jan 3");
- } finally {
- vi.useRealTimers();
- }
- });
- it("uses two columns when only two Coding Plan meters are available", () => {
- const availableProviders = [
- createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
- ];
- const html = renderToStaticMarkup(
- createElement(ChatCodingPlanUsageRemainingPanel, {
- config: {
- availableProviders,
- entitlements: [
- {
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- loading: false,
- error: null,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- name: "Z.ai Coding Plan",
- },
- remaining: null,
- subscription: activeSubscription,
- quota: {
- level: "pro",
- limits: [
- {
- type: "TOKENS_LIMIT",
- unit: 3,
- number: 5,
- percentage: 35,
- usageDetails: [],
- },
- {
- type: "TOKENS_LIMIT",
- unit: 6,
- percentage: 45,
- usageDetails: [],
- },
- ],
- },
- },
- },
- ],
- modelProvidersLoading: false,
- },
- intl: {
- formatMessage: ({ id }: { id: string }) => id,
- } as never,
- locale: "en-US",
- }),
- );
- expect(html).toContain("grid-cols-2");
- expect(html).not.toContain("grid-cols-3");
- expect(html).toContain("background-color:var(--color-usage-chart-1)");
- expect(html).toContain("background-color:var(--color-usage-chart-2)");
- expect(html).not.toContain("background-color:var(--color-usage-chart-3)");
- });
- it("is renderable from entitlement data even without task context usage", () => {
- const availableProviders = [
- createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
- ];
- const entitlements = [
- {
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- loading: false,
- error: null,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- name: "Z.ai Coding Plan",
- },
- remaining: null,
- subscription: activeSubscription,
- quota: {
- level: "pro",
- limits: [],
- },
- },
- },
- ];
- expect(
- hasCodingPlanUsageRemainingPanel({
- availableProviders,
- entitlements,
- modelProvidersLoading: false,
- }),
- ).toBe(true);
- expect(
- resolveCodingPlanUsageRemainingState({
- availableProviders,
- entitlements,
- modelProvidersLoading: false,
- })?.activeProviderId,
- ).toBe(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan);
- });
- it("keeps Team Plan usage renderable without a personal Coding Plan provider", () => {
- const entitlements = [
- {
- sourceId: "team:bigmodel:team-pro:org-a:project-a",
- providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
- accountAccess: {
- type: "zhipu-account" as const,
- family: "bigmodel" as const,
- planKind: "team-coding-plan" as const,
- productId: "team-pro",
- organizationId: "org-a",
- projectId: "project-a",
- },
- label: "BigModel - Project A",
- loading: false,
- error: null,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
- name: "BigModel Coding Plan",
- },
- remaining: null,
- subscription: activeSubscription,
- quota: {
- level: "team",
- limits: [
- {
- type: "TOKENS_LIMIT",
- unit: 3,
- number: 5,
- percentage: 80,
- usageDetails: [],
- },
- ],
- },
- },
- },
- ];
- expect(
- hasCodingPlanUsageRemainingPanel({
- availableProviders: [],
- entitlements,
- modelProvidersLoading: false,
- selectedProviderId: "team:bigmodel:team-pro:org-a:project-a",
- }),
- ).toBe(true);
- expect(
- resolveCodingPlanUsageRemainingState({
- availableProviders: [],
- entitlements,
- modelProvidersLoading: false,
- selectedProviderId: "team:bigmodel:team-pro:org-a:project-a",
- })?.activeProviderId,
- ).toBe("team:bigmodel:team-pro:org-a:project-a");
- });
- it("shows the sidebar upgrade entry for authenticated users without an active plan", () => {
- const availableProviders = [
- createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
- ];
- const entitlements = [
- {
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- loading: false,
- error: null,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- unavailableReason: "no_plan" as const,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- name: "Z.ai Coding Plan",
- },
- remaining: null,
- subscription: null,
- quota: null,
- },
- },
- ];
- expect(
- resolveSidebarCodingPlanUpgradeProviderId({
- availableProviders,
- entitlements,
- modelProvidersLoading: false,
- }),
- ).toBe(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan);
- });
- it("falls back to the current provider family for the profile upgrade entry", () => {
- expect(resolveSidebarCodingPlanUpgradeFallbackProviderId("bigmodel")).toBe(
- BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
- );
- expect(resolveSidebarCodingPlanUpgradeFallbackProviderId("zai")).toBe(
- BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- );
- expect(resolveSidebarCodingPlanUpgradeFallbackProviderId(null)).toBe(
- BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- );
- });
- it("keeps the sidebar upgrade entry for max plan users", () => {
- const availableProviders = [
- createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
- ];
- const entitlements = [
- {
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- loading: false,
- error: null,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- name: "Z.ai Coding Plan",
- },
- remaining: null,
- subscription: {
- identityType: "unknown" as const,
- identityMasked: null,
- details: [{ productId: "coding-max", productName: "Coding Max" }],
- },
- quota: {
- level: "max",
- limits: [],
- },
- },
- },
- ];
- expect(
- resolveSidebarCodingPlanUpgradeProviderId({
- availableProviders,
- entitlements,
- modelProvidersLoading: false,
- }),
- ).toBe(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan);
- });
- it("hides the sidebar upgrade entry for team plan users", () => {
- const availableProviders = [
- createCodingPlanProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
- ];
- const entitlements = [
- {
- providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- loading: false,
- error: null,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
- name: "Z.ai Coding Plan",
- },
- remaining: null,
- subscription: {
- identityType: "unknown" as const,
- identityMasked: null,
- details: [
- {
- productId: "team-standard",
- productName: "Team Standard",
- },
- ],
- },
- quota: null,
- },
- },
- ];
- expect(
- resolveSidebarCodingPlanUpgradeProviderId({
- availableProviders,
- entitlements,
- modelProvidersLoading: false,
- }),
- ).toBeUndefined();
- });
- });
- describe("Start Plan context balance panel", () => {
- it("renders Today's balance meters with an upgrade action", () => {
- const html = renderToStaticMarkup(
- createElement(ChatStartPlanBalancePanel, {
- config: {
- loading: false,
- onUpgradeClick: vi.fn(),
- snapshot: {
- generatedAt: new Date(2026, 5, 13, 8, 15).getTime(),
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
- name: "Z.ai Start Plan",
- },
- remaining: null,
- subscription: {
- identityType: "unknown",
- identityMasked: null,
- details: [
- {
- productId: "zcode-v3-start-plan",
- productName: "ZCode Start Plan",
- purchaseTime: null,
- beginTime: null,
- renewTime: new Date(2026, 5, 13, 10, 0).toISOString(),
- expireTime: new Date(2026, 5, 20, 23, 59).toISOString(),
- },
- ],
- },
- quota: {
- level: "Start",
- limits: [
- {
- type: "TOKENS_LIMIT",
- number: 1_000_000,
- remaining: 750_000,
- usage: 250_000,
- nextResetTime: new Date(2026, 5, 14, 23, 2).getTime(),
- usageDetails: [
- {
- modelCode: "glm-5.2",
- displayName: "GLM-5.2",
- usage: 250_000,
- },
- ],
- },
- ],
- },
- },
- },
- intl: {
- formatMessage: ({ id }: { id: string }, values?: Record<string, string>) =>
- values?.value ? `${id}:${values.value}` : id,
- } as never,
- locale: "en-US",
- }),
- );
- expect(html).toContain("settings.modelProvider.startPlan.balance.title");
- expect(html).not.toContain("settings.modelProvider.codingPlan.expiresAt");
- expect(html).toContain("GLM-5.2");
- expect(html).toContain("75%");
- // 桶刷新时间只来自本桶 expires_at(nextResetTime),不再采用套餐级 renewTime;
- // 非当日与 Coding Plan 对齐只展示日期,不携带时间。
- expect(html).toContain("Jun 14");
- expect(html).not.toContain("Jun 14 23:02");
- expect(html).not.toContain("Jun 13 10:00");
- expect(html).not.toContain("750K");
- expect(html).not.toContain("1M");
- expect(html).not.toContain("settings.modelProvider.startPlan.balance.used");
- expect(html).toContain("chat.quota.action.upgrade");
- expect(html).toContain("button-gradient");
- expect(html).toContain("billing-discount-badge:surface:compact");
- expect(html).toContain("billing-discount-info");
- expect(html).toContain("grid-cols-1");
- expect(html).toContain("space-y-0.5");
- expect(html).toContain("h-1.5");
- expect(html).toContain("bg-success");
- // 修复原因:hover 静默刷新返回后今日余额进度条原先瞬间跳变,与 Coding Plan 额度条的
- // 500ms 宽度过渡不一致,导致"已刷新"完全无感;断言过渡与无障碍降级保持对齐。
- expect(html).toContain("transition-[width]");
- expect(html).toContain("duration-500");
- expect(html).toContain("motion-reduce:transition-none");
- expect(html).not.toContain("background-color");
- expect(html).toContain("lucide-rocket");
- });
- it("omits the date for today's Start Plan balance renew time", () => {
- vi.useFakeTimers();
- try {
- vi.setSystemTime(new Date(2026, 5, 15, 12, 0));
- const html = renderToStaticMarkup(
- createElement(ChatStartPlanBalancePanel, {
- config: {
- loading: false,
- snapshot: {
- generatedAt: new Date(2026, 5, 14, 8, 15).getTime(),
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
- name: "Z.ai Start Plan",
- },
- remaining: null,
- subscription: {
- identityType: "unknown",
- identityMasked: null,
- details: [
- {
- productId: "zcode-v3-start-plan",
- productName: "ZCode Start Plan",
- purchaseTime: null,
- beginTime: null,
- renewTime: null,
- expireTime: new Date(2026, 5, 20, 23, 59).toISOString(),
- },
- ],
- },
- quota: {
- level: "Start",
- limits: [
- {
- type: "TOKENS_LIMIT",
- number: 1_000_000,
- remaining: 990_000,
- nextResetTime: new Date(2026, 5, 15, 23, 2).getTime(),
- usageDetails: [
- {
- modelCode: "glm-5.2",
- displayName: "GLM-5.2",
- usage: 10_000,
- },
- ],
- },
- ],
- },
- },
- },
- intl: {
- formatMessage: ({ id }: { id: string }, values?: Record<string, string>) =>
- values?.value ? `${id}:${values.value}` : id,
- } as never,
- locale: "en-US",
- }),
- );
- expect(html).toContain("99%");
- expect(html).toContain("23:02");
- expect(html).not.toContain("Jun 15 23:02");
- } finally {
- vi.useRealTimers();
- }
- });
- it("renders each Start Plan bucket with its own reset time", () => {
- vi.useFakeTimers();
- try {
- vi.setSystemTime(new Date(2026, 5, 15, 12, 0));
- const html = renderToStaticMarkup(
- createElement(ChatStartPlanBalancePanel, {
- config: {
- loading: false,
- snapshot: {
- generatedAt: new Date(2026, 5, 15, 8, 15).getTime(),
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
- name: "Z.ai Start Plan",
- },
- remaining: {
- count: 1_750_000,
- isShow: true,
- // 全局聚合时间(最早桶时间)不得复制到每个桶。
- nextResetTime: new Date(2026, 5, 15, 20, 0).getTime(),
- },
- subscription: {
- identityType: "unknown",
- identityMasked: null,
- details: [
- {
- productId: "start-plan-welcome",
- productName: "Welcome Plan",
- purchaseTime: null,
- beginTime: null,
- renewTime: new Date(2026, 5, 13, 10, 0).toISOString(),
- expireTime: new Date(2026, 5, 20, 23, 59).toISOString(),
- },
- ],
- },
- quota: {
- level: "Start",
- limits: [
- {
- type: "welcome-glm-52",
- planId: "start-plan-welcome",
- number: 1_000_000,
- remaining: 750_000,
- nextResetTime: new Date(2026, 5, 15, 18, 45).getTime(),
- usageDetails: [
- {
- modelCode: "glm-5.2",
- displayName: "GLM-5.2",
- usage: 250_000,
- },
- ],
- },
- {
- type: "welcome-glm-5-turbo",
- planId: "start-plan-welcome",
- number: 1_000_000,
- remaining: 1_000_000,
- nextResetTime: new Date(2026, 5, 16, 9, 30).getTime(),
- usageDetails: [
- {
- modelCode: "glm-5-turbo",
- displayName: "GLM-5-Turbo",
- usage: 0,
- },
- ],
- },
- ],
- },
- },
- },
- intl: {
- formatMessage: ({ id }: { id: string }, values?: Record<string, string>) =>
- values?.value ? `${id}:${values.value}` : id,
- } as never,
- locale: "en-US",
- }),
- );
- // 每个 meter 只展示本桶的 expires_at:当日仅 HH:mm(对齐 Coding Plan 五小时窗口),
- // 非当日仅日期(对齐 Coding Plan 周/月重置),互不串用。
- expect(html).toContain("18:45");
- expect(html).toContain("Jun 16");
- expect(html).not.toContain("Jun 16 09:30");
- // 全局 remaining 聚合时间与套餐级 renewTime 不得串入任何桶。
- expect(html).not.toContain("20:00");
- expect(html).not.toContain("Jun 13 10:00");
- } finally {
- vi.useRealTimers();
- }
- });
- it("uses two columns when two Start Plan meters are available", () => {
- const html = renderToStaticMarkup(
- createElement(ChatStartPlanBalancePanel, {
- config: {
- loading: false,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
- name: "Z.ai Start Plan",
- },
- remaining: null,
- subscription: activeSubscription,
- quota: {
- level: "Start",
- limits: [
- {
- type: "TOKENS_LIMIT",
- number: 1_000_000,
- remaining: 750_000,
- usage: 250_000,
- usageDetails: [
- {
- modelCode: "glm-5.2",
- displayName: "GLM-5.2",
- usage: 250_000,
- },
- ],
- },
- {
- type: "TOKENS_LIMIT",
- number: 500_000,
- remaining: 250_000,
- usage: 250_000,
- usageDetails: [
- {
- modelCode: "glm-5.1",
- displayName: "GLM-5.1",
- usage: 250_000,
- },
- ],
- },
- ],
- },
- },
- },
- intl: {
- formatMessage: ({ id }: { id: string }, values?: Record<string, string>) =>
- values?.value ? `${id}:${values.value}` : id,
- } as never,
- locale: "en-US",
- }),
- );
- expect(html).toContain("grid-cols-2");
- expect(html).not.toContain("grid-cols-3");
- expect(html).toContain("GLM-5.2");
- expect(html).toContain("GLM-5.1");
- });
- it("is visible while loading or when displayable limits exist", () => {
- expect(hasChatStartPlanBalance({ loading: true, snapshot: null })).toBe(true);
- expect(
- hasChatStartPlanBalance({
- loading: false,
- snapshot: {
- generatedAt: 1,
- authenticated: true,
- provider: {
- id: BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan,
- name: "Z.ai Start Plan",
- },
- remaining: null,
- subscription: activeSubscription,
- quota: { level: "Start", limits: [] },
- },
- }),
- ).toBe(false);
- });
- });
|