From c96bd2086e464b475435f303c8478bc6a808426e Mon Sep 17 00:00:00 2001 From: Hyo Date: Fri, 20 Nov 2026 17:04:11 +0900 Subject: [PATCH] feat: show own-key cost, active model and a priced model picker Owners running Gitdog on their own Anthropic or OpenAI key can now see what that usage costs and which model it runs on. - Usage page: the key, model and effort reviews run on, provider cost this period, average per run, a by-model table and recent runs with their cost; own-key cost per repository. - Profile: models as priced square choices, effort as a radio group, and a badge for the key that runs reviews and its backup. - Ticket page: each action shows its models and what it cost on the owner's key, or the Gitdog tokens it used. - New queries tokenUsage.getUserKeyUsage and getTicketUsage; model names and prices come from CHAT_MODELS in one place. getCurrentMonthUsage no longer returns the unused userKey totals. --- convex/_ai/config.ts | 69 ++--- convex/_generated/api.d.ts | 2 + convex/tokenUsage/query.ts | 139 ++++++---- convex/tokenUsage/usageSummary.ts | 135 ++++++++++ packages/cli/src/api-catalog.json | 10 + packages/cli/test/commands.test.mjs | 2 +- src/hooks/useRelativeTime.ts | 22 ++ src/i18n/locales/en.json | 50 +++- src/i18n/locales/ja.json | 48 +++- src/i18n/locales/ko.json | 48 +++- src/pages/profile/ProviderKeysSection.tsx | 219 +++++++++++----- src/pages/tickets/ActionUsageChip.tsx | 51 ++++ src/pages/tickets/[id].tsx | 28 +- src/pages/usage/UserKeyUsageSection.tsx | 271 ++++++++++++++++++++ src/pages/usage/index.tsx | 74 ++---- src/utils/actionTypes.ts | 12 + src/utils/providerKeyState.ts | 23 +- src/utils/usageFormat.ts | 16 ++ test/convex/tokenUsage/userKeyUsage.test.ts | 147 ++++++++++- test/pages/providerKeyState.test.ts | 37 ++- 20 files changed, 1156 insertions(+), 247 deletions(-) create mode 100644 convex/tokenUsage/usageSummary.ts create mode 100644 src/hooks/useRelativeTime.ts create mode 100644 src/pages/tickets/ActionUsageChip.tsx create mode 100644 src/pages/usage/UserKeyUsageSection.tsx create mode 100644 src/utils/actionTypes.ts create mode 100644 src/utils/usageFormat.ts diff --git a/convex/_ai/config.ts b/convex/_ai/config.ts index af08746..3b9f788 100644 --- a/convex/_ai/config.ts +++ b/convex/_ai/config.ts @@ -45,6 +45,7 @@ export const GENERATION_MODELS = { export const CHAT_MODELS: Record< string, { + name: string; provider: "anthropic" | "openai" | "google"; inputPer1M: number; outputPer1M: number; @@ -60,6 +61,7 @@ export const CHAT_MODELS: Record< } > = { "claude-opus-5-5": { + name: "Claude Opus 5.5", provider: "anthropic", inputPer1M: 4, outputPer1M: 20, @@ -68,18 +70,21 @@ export const CHAT_MODELS: Record< }, // Refusal fallback targets for Opus 5.5, priced only for recorded cost. "claude-opus-5": { + name: "Claude Opus 5", provider: "anthropic", inputPer1M: 5, outputPer1M: 25, quotaWeight: 2.5, }, "claude-opus-4-8": { + name: "Claude Opus 4.8", provider: "anthropic", inputPer1M: 5, outputPer1M: 25, quotaWeight: 2.5, }, "claude-sonnet-5-5": { + name: "Claude Sonnet 5.5", provider: "anthropic", inputPer1M: 2, outputPer1M: 10, @@ -87,6 +92,7 @@ export const CHAT_MODELS: Record< }, // Available on an owner's own key only; priced for recorded cost. "claude-haiku-5-5": { + name: "Claude Haiku 5.5", provider: "anthropic", inputPer1M: 0.1, outputPer1M: 0.5, @@ -98,6 +104,7 @@ export const CHAT_MODELS: Record< }, }, "gpt-6.2-sol": { + name: "GPT-6.2 Sol", provider: "openai", inputPer1M: 2, outputPer1M: 10, @@ -110,6 +117,7 @@ export const CHAT_MODELS: Record< }, }, "gpt-6.1-sol": { + name: "GPT-6.1 Sol", provider: "openai", inputPer1M: 2, outputPer1M: 10, @@ -121,6 +129,7 @@ export const CHAT_MODELS: Record< }, }, [LEGACY_GOOGLE_MODELS.chatModelId]: { + name: "Gemini 2.5 Flash", provider: LEGACY_GOOGLE_MODELS.provider, inputPer1M: LEGACY_GOOGLE_MODELS.chatInputPer1M, outputPer1M: LEGACY_GOOGLE_MODELS.chatOutputPer1M, @@ -173,10 +182,28 @@ export type UserKeyModel = { name: string; efforts: readonly ModelEffort[]; defaultEffort: ModelEffort; + // USD per 1M tokens, so owners can compare models before choosing one. + inputPer1M: number; + outputPer1M: number; }; const EFFORTS: readonly ModelEffort[] = ["low", "medium", "high"]; +function userKeyOption( + modelId: string, + defaultEffort: ModelEffort, +): UserKeyModel { + const { name, inputPer1M, outputPer1M } = CHAT_MODELS[modelId]; + return { + modelId, + name, + efforts: EFFORTS, + defaultEffort, + inputPer1M, + outputPer1M, + }; +} + /** * Models an owner can choose for their own provider key, the default first. * The provider bills that usage, so it never counts against Gitdog tokens. @@ -186,43 +213,25 @@ const EFFORTS: readonly ModelEffort[] = ["low", "medium", "high"]; */ export const USER_KEY_MODELS: Record<"anthropic" | "openai", UserKeyModel[]> = { anthropic: [ - { - modelId: "claude-opus-5-5", - name: "Claude Opus 5.5", - efforts: EFFORTS, - defaultEffort: "medium", - }, - { - modelId: "claude-sonnet-5-5", - name: "Claude Sonnet 5.5", - efforts: EFFORTS, - defaultEffort: "high", - }, - { - modelId: "claude-haiku-5-5", - name: "Claude Haiku 5.5", - efforts: EFFORTS, - defaultEffort: "medium", - }, + userKeyOption("claude-opus-5-5", "medium"), + userKeyOption("claude-sonnet-5-5", "high"), + userKeyOption("claude-haiku-5-5", "medium"), ], // Keys saved before GPT-6.2 Sol were checked against 6.1 and store no // model, so 6.1 stays the default they resolve to. openai: [ - { - modelId: "gpt-6.1-sol", - name: "GPT-6.1 Sol", - efforts: EFFORTS, - defaultEffort: "high", - }, - { - modelId: "gpt-6.2-sol", - name: "GPT-6.2 Sol", - efforts: EFFORTS, - defaultEffort: "high", - }, + userKeyOption("gpt-6.1-sol", "high"), + userKeyOption("gpt-6.2-sol", "high"), ], }; +/** A chat model's display name, or its id when Gitdog never priced it. */ +export function chatModelName(modelId: string): string { + return Object.hasOwn(CHAT_MODELS, modelId) + ? CHAT_MODELS[modelId].name + : modelId; +} + /** * The model and effort an owner's key runs with. A choice that is no longer * offered falls back to the default, so a key never stops working. diff --git a/convex/_generated/api.d.ts b/convex/_generated/api.d.ts index 34c2023..a8faa68 100644 --- a/convex/_generated/api.d.ts +++ b/convex/_generated/api.d.ts @@ -167,6 +167,7 @@ import type * as tokenUsage_periodTotals from "../tokenUsage/periodTotals.js"; import type * as tokenUsage_query from "../tokenUsage/query.js"; import type * as tokenUsage_quota from "../tokenUsage/quota.js"; import type * as tokenUsage_totals from "../tokenUsage/totals.js"; +import type * as tokenUsage_usageSummary from "../tokenUsage/usageSummary.js"; import type * as users_action from "../users/action.js"; import type * as users_internalQuery from "../users/internalQuery.js"; import type * as users_legal from "../users/legal.js"; @@ -339,6 +340,7 @@ declare const fullApi: ApiFromModules<{ "tokenUsage/query": typeof tokenUsage_query; "tokenUsage/quota": typeof tokenUsage_quota; "tokenUsage/totals": typeof tokenUsage_totals; + "tokenUsage/usageSummary": typeof tokenUsage_usageSummary; "users/action": typeof users_action; "users/internalQuery": typeof users_internalQuery; "users/legal": typeof users_legal; diff --git a/convex/tokenUsage/query.ts b/convex/tokenUsage/query.ts index 6bff008..afaa849 100644 --- a/convex/tokenUsage/query.ts +++ b/convex/tokenUsage/query.ts @@ -1,3 +1,4 @@ +import { v } from "convex/values"; import { query, type QueryCtx } from "../_generated/server"; import type { Doc, Id } from "../_generated/dataModel"; import { getAuthUserId } from "@convex-dev/auth/server"; @@ -5,6 +6,7 @@ import { MAX_COLLECT_LIMIT } from "../_utils/pagination"; import { getSubscriptionForEntitlement } from "../subscriptions/entitlement"; import { readEffectiveSubscriptionQuota } from "../subscriptions/quotaEntitlement"; import { readCompletePeriodTotals } from "./periodTotals"; +import { summarizeActionUsage, summarizeUserKeyUsage } from "./usageSummary"; export const MAX_TOKEN_USAGE_AGGREGATION_RECORDS = MAX_COLLECT_LIMIT; @@ -55,7 +57,8 @@ export function assertCompleteUsageAggregation(recordCount: number): void { /** * Usage on the user's own provider keys. It never counts toward quota, so a - * busy period is reported as a floor instead of failing the usage page. + * busy period is reported as a floor instead of failing the usage page. Rows + * come newest first, so a partial read still holds the latest actions. */ async function readUserKeyUsage( ctx: QueryCtx, @@ -72,6 +75,7 @@ async function readUserKeyUsage( .gte("createdAt", periodStart) .lt("createdAt", periodEnd), ) + .order("desc") .take(MAX_TOKEN_USAGE_AGGREGATION_RECORDS + 1); return { rows: rows.slice(0, MAX_TOKEN_USAGE_AGGREGATION_RECORDS), @@ -118,14 +122,6 @@ export const getCurrentMonthUsage = query({ totalCostCents: period.gitdog.totalCostCents, totalActions: period.gitdog.chatActions, totalEmbeddingTokens: period.gitdog.embeddingTokens, - userKey: { - inputTokens: period.userKey.inputTokens, - outputTokens: period.userKey.outputTokens, - totalTokens: period.userKey.totalTokens, - totalActions: period.userKey.rowCount, - estimatedProviderCostCents: period.userKey.baseCostCents, - isPartial: false, - }, paymentStatus: paymentStatus as "waived" | "pending" | "paid", }; } @@ -142,12 +138,6 @@ export const getCurrentMonthUsage = query({ ) .take(MAX_TOKEN_USAGE_AGGREGATION_RECORDS + 1); assertCompleteUsageAggregation(usageRecords.length); - const userKeyRecords = await readUserKeyUsage( - ctx, - userId, - periodStart, - periodEnd, - ); // `totalTokens` keeps cost-equivalent quota usage, while // `embeddingTokens` preserves the provider's actual embedding input count. @@ -198,38 +188,9 @@ export const getCurrentMonthUsage = query({ ); } - const userKey = { - inputTokens: 0, - outputTokens: 0, - totalTokens: 0, - totalActions: 0, - estimatedProviderCostCents: 0, - isPartial: userKeyRecords.isPartial, - }; - for (const record of userKeyRecords.rows) { - userKey.inputTokens = checkedTokenSum( - userKey.inputTokens, - record.inputTokens, - ); - userKey.outputTokens = checkedTokenSum( - userKey.outputTokens, - record.outputTokens, - ); - userKey.totalTokens = checkedTokenSum( - userKey.totalTokens, - record.totalTokens, - ); - userKey.totalActions = checkedTokenSum(userKey.totalActions, 1); - userKey.estimatedProviderCostCents = checkedCostSum( - userKey.estimatedProviderCostCents, - record.baseCostCents, - ); - } - return { yearMonth, ...totals, - userKey, paymentStatus: paymentStatus as "waived" | "pending" | "paid", }; }, @@ -375,3 +336,93 @@ export const getUsageByRepository = query({ return Array.from(usageByRepo.values()); }, }); + +const RECENT_USER_KEY_ACTIONS = 10; + +/** + * This period's usage on the owner's own keys, priced as the provider bills + * it: totals, each model, each repository and the most recent actions. + */ +export const getUserKeyUsage = query({ + args: {}, + handler: async (ctx) => { + const userId = await getAuthUserId(ctx); + if (!userId) return null; + + const subscription = await getSubscriptionForEntitlement(ctx, userId); + const quota = await readEffectiveSubscriptionQuota(ctx, subscription); + // Own-key usage never touches quota, so a quota problem only hides it; + // the keys page that shows it must keep working. + if (!quota.verified) return null; + const { periodStart, periodEnd } = quota.entitlement; + + const { rows, isPartial } = await readUserKeyUsage( + ctx, + userId, + periodStart, + periodEnd, + ); + const { actions, ...summary } = summarizeUserKeyUsage(rows); + + const recentActions = await Promise.all( + actions.slice(0, RECENT_USER_KEY_ACTIONS).map(async (usage) => { + const action = await ctx.db.get(usage.ticketActionId); + const ticket = action && (await ctx.db.get(action.ticketId)); + if (!action || !ticket || ticket.userId !== userId) return null; + return { + ...usage, + actionType: action.actionType, + // Deleted tickets keep their cost but no longer link anywhere. + ticketId: ticket.deletedAt ? null : ticket._id, + ticketType: ticket.ticketType, + githubRepo: ticket.githubRepo, + githubNumber: ticket.githubNumber, + githubTitle: ticket.githubTitle, + }; + }), + ); + + return { + isPartial, + ...summary, + recentActions: recentActions.filter((entry) => entry !== null), + }; + }, +}); + +// Bounded well under a query's read limit: the newest actions, and more rows +// per action than the largest batched review writes. +const MAX_TICKET_USAGE_ACTIONS = 40; +const MAX_ACTION_USAGE_ROWS = 300; + +/** What each action on a ticket used and whose key paid for it. */ +export const getTicketUsage = query({ + args: { ticketId: v.id("tickets") }, + handler: async (ctx, args) => { + const userId = await getAuthUserId(ctx); + if (!userId) return []; + const ticket = await ctx.db.get(args.ticketId); + if (!ticket || ticket.userId !== userId || ticket.deletedAt) return []; + + const actions = await ctx.db + .query("ticketActions") + .withIndex("by_ticket", (q) => q.eq("ticketId", ticket._id)) + .order("desc") + .take(MAX_TICKET_USAGE_ACTIONS); + return await Promise.all( + actions.map(async (action) => { + const rows = await ctx.db + .query("tokenUsage") + .withIndex("by_ticket_action", (q) => + q.eq("ticketActionId", action._id), + ) + .take(MAX_ACTION_USAGE_ROWS + 1); + return { + ticketActionId: action._id, + isPartial: rows.length > MAX_ACTION_USAGE_ROWS, + ...summarizeActionUsage(rows.slice(0, MAX_ACTION_USAGE_ROWS)), + }; + }), + ); + }, +}); diff --git a/convex/tokenUsage/usageSummary.ts b/convex/tokenUsage/usageSummary.ts new file mode 100644 index 0000000..1ae9ae7 --- /dev/null +++ b/convex/tokenUsage/usageSummary.ts @@ -0,0 +1,135 @@ +import type { Doc, Id } from "../_generated/dataModel"; +import { chatModelName } from "../_ai/config"; + +type UsageRow = Doc<"tokenUsage">; + +export type UsageSum = { + requests: number; + inputTokens: number; + outputTokens: number; + // What the provider billed for own-key rows; Gitdog's cost for the rest. + costCents: number; + // Gitdog tokens the rows counted against the owner's quota. + quotaTokens: number; +}; + +export type ModelUsage = UsageSum & { + provider: UsageRow["provider"]; + modelId: string; + name: string; + actions: number; +}; + +export type ActionUsage = UsageSum & { + ticketActionId: Id<"ticketActions">; + // A fallback may serve part of an action, so it can list several models. + models: string[]; + lastAt: number; +}; + +const emptySum = (): UsageSum => ({ + requests: 0, + inputTokens: 0, + outputTokens: 0, + costCents: 0, + quotaTokens: 0, +}); + +function addRow(sum: UsageSum, row: UsageRow): void { + sum.requests += 1; + sum.inputTokens += row.inputTokens; + sum.outputTokens += row.outputTokens; + sum.costCents += row.baseCostCents; + if (row.keySource !== "user") sum.quotaTokens += row.totalTokens; +} + +// A refusal fallback may serve a request; its cost is priced at that model. +const servedModelId = (row: UsageRow) => row.servedModel ?? row.model; + +/** + * Own-key usage by model, repository and action. Actions come newest first, + * so the first ones are what the owner ran most recently. + */ +export function summarizeUserKeyUsage(rows: UsageRow[]) { + const totals = emptySum(); + const models = new Map }>(); + const repositories = new Map< + string, + { + repositoryId?: Id<"repositories">; + costCents: number; + actionIds: Set; + } + >(); + const actions = new Map(); + + for (const row of rows) { + addRow(totals, row); + const modelId = servedModelId(row); + const modelKey = `${row.provider}/${modelId}`; + const model = models.get(modelKey) ?? { + ...emptySum(), + provider: row.provider, + modelId, + name: chatModelName(modelId), + actions: 0, + actionIds: new Set(), + }; + addRow(model, row); + if (row.ticketActionId) model.actionIds.add(row.ticketActionId); + models.set(modelKey, model); + + const repositoryKey = row.repositoryId ?? ""; + const repository = repositories.get(repositoryKey) ?? { + ...(row.repositoryId ? { repositoryId: row.repositoryId } : {}), + costCents: 0, + actionIds: new Set(), + }; + repository.costCents += row.baseCostCents; + if (row.ticketActionId) repository.actionIds.add(row.ticketActionId); + repositories.set(repositoryKey, repository); + + if (!row.ticketActionId) continue; + const action = actions.get(row.ticketActionId) ?? { + ...emptySum(), + ticketActionId: row.ticketActionId, + models: [], + lastAt: 0, + }; + addRow(action, row); + const name = chatModelName(modelId); + if (!action.models.includes(name)) action.models.push(name); + action.lastAt = Math.max(action.lastAt, row.createdAt); + actions.set(row.ticketActionId, action); + } + + return { + totals: { ...totals, actions: actions.size }, + models: [...models.values()] + .map(({ actionIds, ...model }) => ({ ...model, actions: actionIds.size })) + .sort((a, b) => b.costCents - a.costCents), + repositories: [...repositories.values()].map( + ({ actionIds, ...repository }) => ({ + ...repository, + actions: actionIds.size, + }), + ), + actions: [...actions.values()].sort((a, b) => b.lastAt - a.lastAt), + }; +} + +/** What one action used, split by whose key paid for it. */ +export function summarizeActionUsage(rows: UsageRow[]) { + const sides = { + userKey: null as (UsageSum & { models: string[] }) | null, + gitdog: null as (UsageSum & { models: string[] }) | null, + }; + for (const row of rows) { + const side = row.keySource === "user" ? "userKey" : "gitdog"; + const entry = (sides[side] ??= { ...emptySum(), models: [] }); + addRow(entry, row); + const name = chatModelName(servedModelId(row)); + if (!entry.models.includes(name)) entry.models.push(name); + } + return sides; +} diff --git a/packages/cli/src/api-catalog.json b/packages/cli/src/api-catalog.json index 8dae5e5..8e31575 100644 --- a/packages/cli/src/api-catalog.json +++ b/packages/cli/src/api-catalog.json @@ -444,11 +444,21 @@ "kind": "query", "args": "{}" }, + { + "path": "tokenUsage/query:getTicketUsage", + "kind": "query", + "args": "{ ticketId: v.id(\"tickets\") }" + }, { "path": "tokenUsage/query:getUsageByRepository", "kind": "query", "args": "{}" }, + { + "path": "tokenUsage/query:getUserKeyUsage", + "kind": "query", + "args": "{}" + }, { "path": "users/action:ensureProfile", "kind": "action", diff --git a/packages/cli/test/commands.test.mjs b/packages/cli/test/commands.test.mjs index 286406a..1f1fef1 100644 --- a/packages/cli/test/commands.test.mjs +++ b/packages/cli/test/commands.test.mjs @@ -418,7 +418,7 @@ test("all catalog paths are unique public functions and version matches the npm new Set(API_CATALOG.map((entry) => entry.path)).size, API_CATALOG.length, ); - assert.equal(API_CATALOG.length, 95); + assert.equal(API_CATALOG.length, 97); assert.equal( API_CATALOG.every( (entry) => diff --git a/src/hooks/useRelativeTime.ts b/src/hooks/useRelativeTime.ts new file mode 100644 index 0000000..8ffedd7 --- /dev/null +++ b/src/hooks/useRelativeTime.ts @@ -0,0 +1,22 @@ +import { useTranslation } from "react-i18next"; + +/** Formats a timestamp relative to now, such as "5 minutes ago". */ +export function useRelativeTime() { + const { i18n } = useTranslation(); + return (timestamp: number) => { + const format = new Intl.RelativeTimeFormat(i18n.language, { + numeric: "auto", + }); + const seconds = Math.round((timestamp - Date.now()) / 1000); + const units: Array<[Intl.RelativeTimeFormatUnit, number]> = [ + ["day", 86_400], + ["hour", 3_600], + ["minute", 60], + ]; + for (const [unit, size] of units) { + if (Math.abs(seconds) >= size) + return format.format(Math.round(seconds / size), unit); + } + return format.format(0, "minute"); + }; +} diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index 8b98505..c5c2178 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -501,7 +501,13 @@ "reviewExcluded": "Files without complete coverage", "reviewNotPublished": "Review completed without a GitHub post", "reviewFailureDetails": "Failure details", - "emptyBody": "(Empty)" + "emptyBody": "(Empty)", + "usage": { + "userKey": "{{cost}} on your API key", + "gitdog": "{{tokens}} Gitdog tokens", + "requests_one": "{{count}} AI request", + "requests_other": "{{count}} AI requests" + } } }, "usage": { @@ -552,8 +558,31 @@ }, "userKey": { "title": "Your API keys", - "description": "{{count}} requests on your own keys this period, about {{cost}} at provider prices. Not counted toward your quota.", - "repositoryTokens": "+ {{tokens}} on your API key" + "runsOn": "Reviews run on your {{provider}} key ••••{{last4}}", + "effort": "{{effort}} effort", + "backup": "If it runs out of credit, your {{provider}} key takes over with {{model}}.", + "noActiveKey": "No key is working right now, so reviews run on Gitdog tokens.", + "changeModel": "Change model", + "manageKeys": "Manage keys", + "costLabel": "Provider cost this period", + "costNote": "Estimated at list prices; your provider's bill is final.", + "runsLabel": "Reviews and replies", + "requests_one": "{{count}} AI request", + "requests_other": "{{count}} AI requests", + "averageLabel": "Average per run", + "tokens": "{{input}} in · {{output}} out", + "byModel": "By model", + "columns": { + "model": "Model", + "runs": "Runs using it", + "tokens": "Tokens", + "average": "Avg per run", + "cost": "Cost" + }, + "recent": "Recent runs on your keys", + "noRuns": "Nothing has run on your keys yet this period.", + "partial": "This period has more usage than can be shown, so totals are a lower bound.", + "repositoryUsage": "+ {{tokens}} on your API key ({{cost}})" } }, "profile": { @@ -621,7 +650,20 @@ "modelLabel": "Model", "effortLabel": "Effort", "modelHint": "Runs on this key and is billed by {{provider}}. It never uses Gitdog tokens.", - "modelSaved": "Saved" + "modelSaved": "Saved", + "role": { + "primary": "Runs reviews", + "backup": "Backup" + }, + "defaultModel": "Default", + "price": "{{input}} in · {{output}} out per 1M tokens", + "efforts": { + "low": "Low", + "medium": "Medium", + "high": "High" + }, + "effortHint": "Higher effort reads more and costs more per run.", + "thisPeriod": "This period: {{cost}} on this key" } }, "footer": { diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index 6ee1a70..63cfbf4 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -500,7 +500,12 @@ "reviewExcluded": "完全に確認できなかったファイル", "reviewNotPublished": "レビュー完了・GitHubへの投稿なし", "reviewFailureDetails": "失敗の詳細", - "emptyBody": "(空)" + "emptyBody": "(空)", + "usage": { + "userKey": "自分の API キーで {{cost}}", + "gitdog": "Gitdog トークン {{tokens}}", + "requests_other": "AI リクエスト {{count}} 件" + } } }, "usage": { @@ -551,8 +556,30 @@ }, "userKey": { "title": "自分の API キー", - "description": "今期間、自分のキーで {{count}} 件のリクエスト、プロバイダー価格で約 {{cost}}。上限には含まれません。", - "repositoryTokens": "+ 自分の API キーで {{tokens}}" + "runsOn": "レビューは {{provider}} キー ••••{{last4}} で実行されます", + "effort": "推論の強さ: {{effort}}", + "backup": "クレジットが切れると {{provider}} キーの {{model}} が引き継ぎます。", + "noActiveKey": "使えるキーがないため、レビューは Gitdog のトークンで実行されます。", + "changeModel": "モデルを変更", + "manageKeys": "キーを管理", + "costLabel": "今期間のプロバイダー費用", + "costNote": "定価での見積もりです。実際の金額はプロバイダーの請求に従います。", + "runsLabel": "レビューと回答", + "requests_other": "AI リクエスト {{count}} 件", + "averageLabel": "1 回あたりの平均", + "tokens": "入力 {{input}} · 出力 {{output}}", + "byModel": "モデル別", + "columns": { + "model": "モデル", + "runs": "使用した実行", + "tokens": "トークン", + "average": "1 回あたり", + "cost": "費用" + }, + "recent": "自分のキーで実行した最近の作業", + "noRuns": "今期間、自分のキーでの実行はまだありません。", + "partial": "今期間の利用が多く一部のみ表示しているため、合計は下限値です。", + "repositoryUsage": "+ 自分の API キーで {{tokens}}({{cost}})" } }, "profile": { @@ -620,7 +647,20 @@ "modelLabel": "モデル", "effortLabel": "推論の強さ", "modelHint": "このキーで実行され、{{provider}} から請求されます。Gitdog のトークンは使いません。", - "modelSaved": "保存しました" + "modelSaved": "保存しました", + "role": { + "primary": "レビューに使用中", + "backup": "予備" + }, + "defaultModel": "デフォルト", + "price": "100万トークンあたり 入力 {{input}} · 出力 {{output}}", + "efforts": { + "low": "低", + "medium": "中", + "high": "高" + }, + "effortHint": "強さを上げるほど多く読み、1 回あたりの費用が増えます。", + "thisPeriod": "今期間このキーで {{cost}}" } }, "footer": { diff --git a/src/i18n/locales/ko.json b/src/i18n/locales/ko.json index e23d09e..ec946bd 100644 --- a/src/i18n/locales/ko.json +++ b/src/i18n/locales/ko.json @@ -500,7 +500,12 @@ "reviewExcluded": "전체 검토하지 못한 파일", "reviewNotPublished": "검토 완료 · GitHub 게시 없음", "reviewFailureDetails": "실패 상세 정보", - "emptyBody": "(비어 있음)" + "emptyBody": "(비어 있음)", + "usage": { + "userKey": "내 API 키로 {{cost}}", + "gitdog": "Gitdog 토큰 {{tokens}}", + "requests_other": "AI 요청 {{count}}건" + } } }, "usage": { @@ -551,8 +556,30 @@ }, "userKey": { "title": "내 API 키", - "description": "이번 기간 내 키로 {{count}}건 요청, 제공자 가격 기준 약 {{cost}}. 한도에 포함되지 않습니다.", - "repositoryTokens": "+ 내 API 키 {{tokens}}" + "runsOn": "리뷰는 {{provider}} 키 ••••{{last4}}로 실행됩니다", + "effort": "추론 강도 {{effort}}", + "backup": "크레딧이 떨어지면 {{provider}} 키의 {{model}}이(가) 이어서 실행합니다.", + "noActiveKey": "지금 쓸 수 있는 키가 없어 리뷰는 Gitdog 토큰으로 실행됩니다.", + "changeModel": "모델 변경", + "manageKeys": "키 관리", + "costLabel": "이번 기간 제공자 비용", + "costNote": "정가 기준 추정치이며, 실제 금액은 제공자 청구서를 따릅니다.", + "runsLabel": "리뷰와 답변", + "requests_other": "AI 요청 {{count}}건", + "averageLabel": "실행당 평균", + "tokens": "입력 {{input}} · 출력 {{output}}", + "byModel": "모델별", + "columns": { + "model": "모델", + "runs": "사용한 실행", + "tokens": "토큰", + "average": "실행당 평균", + "cost": "비용" + }, + "recent": "내 키로 실행된 최근 작업", + "noRuns": "이번 기간에 내 키로 실행된 작업이 아직 없습니다.", + "partial": "이번 기간 사용량이 많아 일부만 표시되므로 합계는 최소값입니다.", + "repositoryUsage": "+ 내 API 키 {{tokens}} ({{cost}})" } }, "profile": { @@ -620,7 +647,20 @@ "modelLabel": "모델", "effortLabel": "추론 강도", "modelHint": "이 키로 실행되며 {{provider}}에서 청구됩니다. Gitdog 토큰은 사용하지 않습니다.", - "modelSaved": "저장됨" + "modelSaved": "저장됨", + "role": { + "primary": "리뷰 실행 중", + "backup": "예비" + }, + "defaultModel": "기본", + "price": "1M 토큰당 입력 {{input}} · 출력 {{output}}", + "efforts": { + "low": "낮음", + "medium": "중간", + "high": "높음" + }, + "effortHint": "강도가 높을수록 더 많이 읽고 실행당 비용이 커집니다.", + "thisPeriod": "이번 기간 이 키 사용액: {{cost}}" } }, "footer": { diff --git a/src/pages/profile/ProviderKeysSection.tsx b/src/pages/profile/ProviderKeysSection.tsx index dc7eca5..c70865e 100644 --- a/src/pages/profile/ProviderKeysSection.tsx +++ b/src/pages/profile/ProviderKeysSection.tsx @@ -7,6 +7,9 @@ import { AlertTriangle, Check, ExternalLink, KeyRound } from "lucide-react"; import { api } from "../../../convex/_generated/api"; import { LoadingIndicator } from "../../components/uis/LoadingIndicator"; import { cn } from "../../utils/cn"; +import { summarizeProviderKeys } from "../../utils/providerKeyState"; +import { useRelativeTime } from "../../hooks/useRelativeTime"; +import { formatPerMillion, formatUsdCents } from "../../utils/usageFormat"; export const PROVIDER_KEYS_ANCHOR = "ai-keys"; @@ -28,15 +31,12 @@ type ModelOption = { name: string; efforts: readonly string[]; defaultEffort: string; + inputPer1M: number; + outputPer1M: number; }; -const selectClass = cn( - "w-full px-3 py-2 text-sm", - "border border-gray-300 dark:border-gray-700", - "bg-white dark:bg-gray-900", - "focus:outline-hidden focus:border-black dark:focus:border-white", - "disabled:opacity-50", -); +// Which saved key reviews run on: Claude first, OpenAI when Claude cannot. +type KeyRole = "primary" | "backup"; const PROVIDERS: Record< KeyProvider, @@ -67,24 +67,26 @@ function serverReason(error: unknown): string | null { return typeof data?.reason === "string" ? data.reason : null; } -function useRelativeTime() { - const { i18n } = useTranslation(); - return (timestamp: number) => { - const format = new Intl.RelativeTimeFormat(i18n.language, { - numeric: "auto", - }); - const seconds = Math.round((timestamp - Date.now()) / 1000); - const units: Array<[Intl.RelativeTimeFormatUnit, number]> = [ - ["day", 86_400], - ["hour", 3_600], - ["minute", 60], - ]; - for (const [unit, size] of units) { - if (Math.abs(seconds) >= size) - return format.format(Math.round(seconds / size), unit); - } - return format.format(0, "minute"); - }; +// A labelled native radio drawn as a square choice, with a visible focus ring. +const choiceClass = cn( + "flex items-center text-sm cursor-pointer border", + "has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2", + "has-[:focus-visible]:outline-black dark:has-[:focus-visible]:outline-white", + "has-[:disabled]:cursor-not-allowed has-[:disabled]:opacity-50", +); + +function SquareMark({ checked }: { checked: boolean }) { + return ( +