* fix(web): sanitize custom footer HTML through HtmlContent
The footer was the only admin-configured HTML still injected with raw
dangerouslySetInnerHTML; it predates the shared HtmlContent hardening
(#5760, 626dadb55) and was never moved over, so inline handlers such as
<img onerror> ran on the home page.
Render it with the isolated HtmlContent variant used by the home, about
and legal pages: DOMPurify strips handlers, target=_blank links get
noopener noreferrer, and Shadow DOM keeps the footer's existing look.
sm:w-auto keeps the attribution column on one line beside it.
Also key the demo-site footer columns by title/href instead of array
index to clear the file's lint errors.
* fix(web): render sanitized footer HTML in the page DOM
The isolated variant put the footer in a Shadow DOM, which cut it off from
the page: in-page anchors to ids in the footer stopped resolving, a lone
badge lost its centering on mobile, theme presets no longer reached links
using the theme colors, and site CSS such as `.custom-footer a` stopped
applying.
Add an `embedded` HtmlContent variant that keeps the isolated variant's
sanitizing (handlers stripped, new-tab links get noopener noreferrer) but
renders into the page DOM, and use it for the footer. The footer no longer
needs the sm:w-auto width fix.
Treat Redis rate-limit failures as client-closed (HTTP 499, no error log) only when both the Redis error and request context report context.Canceled, while keeping deadline timeouts and Redis failures fail-closed with HTTP 500.
Closes#8462
Stop setting finish_reason=tool_calls unconditionally on every Gemini stream chunk containing a functionCall, omit empty content strings on non-text chunks, and strip upstream finish reasons from payload chunks so GeminiChatStreamHandler and GeminiToChatStreamState emit finish_reason once in an empty-delta terminal chunk.
Playground sends chat completions to /pg/chat/completions while GenRelayInfo maps info.RequestURLPath to /v1/chat/completions. Distributor path filters, per-route pass-through lookup in InitChannelMeta, and route resolution in the advanced custom and provider plugin adaptors still read raw c.Request.URL.Path, rejecting advanced custom, vLLM/SGLang preset, and provider plugin channels in Playground.
Add common.NormalizeRelayPath to map /pg/... paths onto /v1/... at the route matching and provider plugin hook boundaries while keeping c.Request.URL.Path unchanged for Playground detection, group selection, and request logs.
Closes#5966
* fix(billing): cap subscription usage at settlement instead of rejecting overrun
When a post-request settlement delta exceeds the remaining subscription quota,
PostConsumeUserSubscriptionDelta rejects the whole update and leaves
amount_used below amount_total. Subsequent requests with small pre-consume
estimates keep passing admission and become free, and secondary subscriptions
are never selected.
Add model.SettleUserSubscriptionDelta to cap positive settlement charges at
AmountTotal (or math.MaxInt64 for unlimited plans), log the uncovered
remainder, and return the applied delta. Route SubscriptionFunding.Settle and
async task settlement to it while keeping PostConsumeUserSubscriptionDelta
strict for reservations and Realtime in-session metering, and without changing
the FundingSource interface signature.
* test(billing): add regression coverage for capped subscription settlement
Consolidate regression cases in service/subscription_settle_test.go covering SettleUserSubscriptionDelta finite capping, unlimited MaxInt64 saturation, refund zero-flooring, BillingSession dual-subscription exhaustion and switching, strict PostConsumeQuota rejection for Realtime in-session metering, and async RecalculateTaskQuota overrun capping.
HasUnfinishedSyncTasks, GetAllUnFinishSyncTasks and GetTimedOutUnfinishedTasks
exclude the two terminal statuses with "status != ?" or "NOT IN". PostgreSQL
and SQLite cannot use idx_tasks_status for that filter, so every check reads
all finished tasks. The async_task_poll scheduler runs the existence check
every 15 seconds. On a PostgreSQL table with 1.4 million finished tasks, one
check took about 27 seconds, and the database kept scanning the table even
when no task was unfinished.
Write the filter as the key ranges around FAILURE and SUCCESS. It matches the
same rows, and all three databases answer it from the status index.
Closes#8528
- web/AGENTS.md: translation keys are English source strings, not
dotted paths; drop the E2E tools and 80% coverage target the project
does not use; drop the changelog section.
- vercel-react-best-practices: describe the Rsbuild SPA instead of
Next.js, Server Components and SWR.
- billing.md: Kling deduction field is final_unit_deduction in the
plugin.
- AGENTS.md: core maintainers write issues without the agent template,
as for PRs; replace the all-caps commentary line with a plain one.
- CLAUDE.md, i18n-translate, shadcn-ui: state each rule once and drop
copied upstream promo text.
Claude rejects tools whose input_schema has oneOf, anyOf or allOf at the
top level (400 "input_schema does not support oneOf, allOf, or anyOf at
the top level"). Codex Desktop's automation_update tool has such a schema,
so every Responses -> Claude turn that carried it failed.
FunctionParametersToInputSchema now merges the branches into one object
schema: properties are combined (differing same-name schemas go into a
nested anyOf), required is the intersection for oneOf/anyOf and the union
for allOf plus the top level's, and other top-level keywords are kept.
The tool conversion reports claude_top_level_schema_union_flattened.
Schemas without a top-level union are returned byte for byte.
* fix(gemini): bill audio inlineData by length, not as images, when usage is missing
When upstream reported no completion tokens (no usageMetadata, or
prompt-only usageMetadata), every inlineData part with a non-empty
mimeType was counted as an image and backfilled with 1400 completion
tokens. A relay that answered a text request with thousands of
audio/l16 TTS chunks was billed millions of output tokens.
Estimate inline output from the payload instead, on the stream and
non-stream paths alike:
- image* parts (case-insensitive) keep the 1400-token estimate;
- PCM audio (audio/l16 or audio/pcm with a rate) counts 25 tokens per
second, Gemini's audio token rate, measured from the decoded byte
count of valid base64 holding whole 16-bit samples, and is recorded
as audio output so tiered expressions price it with ao; on the
prompt-only path it replaces any upstream AUDIO candidate entry;
- audio without a measurable length and other media add nothing.
Responses that report completion tokens are unchanged.
* fix(gemini): harden inline media usage fallback and avoid redundant scan
- Parse inlineData MIME types once with mime.ParseMediaType and ignore empty image payloads
- Gate BillingUsage AUDIO detail replacement on inline fallback application so stale AUDIO entries are cleared when estimating images
- Defer inline media observation in buildUsageFromGeminiResponse until completion tokens are missing
- Saturate audio token conversion inside audioTokens via common.QuotaFromFloat without bare int casts
- Add regression cases for empty image payloads, stale AUDIO clearing on image fallback, and preserving upstream completion counts
---------
Co-authored-by: seefs001 <i@seefs.me>
* fix(claude): map output_tokens_details.thinking_tokens to reasoning_tokens
Anthropic reports thinking tokens in usage.output_tokens_details.thinking_tokens,
a subset of output_tokens. ClaudeUsage had no such field, so OpenAI-format
responses converted from a Claude channel always reported
completion_tokens_details.reasoning_tokens = 0.
Decode the field and carry it into CompletionTokenDetails.ReasoningTokens for
non-stream responses and stream message_start/message_delta usage, bounded by
output_tokens. completion_tokens and billing are unchanged.
* fix(claude): apply reported zero thinking_tokens on message_delta
message_delta usage is cumulative. When output_tokens_details is present, use its thinking_tokens even if zero; keep the earlier count only when the breakdown is absent.
* fix(claude): bound delta thinking_tokens by merged output and preserve on merge
- Clamp message_delta thinking_tokens against accumulated completion_tokens so deltas omitting output_tokens do not zero out reasoning_tokens.
- Copy incoming OutputTokensDetails in MergeClaudeUsageNonZero to preserve or replace the breakdown across usage merges.
---------
Co-authored-by: forgottener <8578113+forgottener@users.noreply.github.com>
Co-authored-by: seefs001 <i@seefs.me>
* fix(relaykit): report cached tokens in Gemini usageMetadata built from chat usage
Gemini promptTokenCount includes cached content, but responses converted
from chat usage (e.g. a Claude channel serving a Gemini-format request)
always reported cachedContentTokenCount as 0 while billing_usage carried
the cache read. Fill cachedContentTokenCount from the chat usage cache-read
count in the non-stream, stream chunk, and stream state converters.
* fix(relaykit): ignore non-positive cached token counts for Gemini usage
---------
Co-authored-by: seefs001 <i@seefs.me>
Verify that the callback pid matches the configured Epay PartnerID when RSA signing mode is enabled across EpayNotify, SubscriptionEpayNotify, and SubscriptionEpayReturn.
MD5 callbacks preserve existing behavior, and mismatched or missing RSA callback pid values are logged and rejected before settlement.
* fix(auth): reject API keys of deleted users with 401
Self-deleting an account soft-deletes the user but keeps its API keys.
TokenAuth and TokenAuthReadOnly treated the missing user as a database
failure and answered 500 "database error"; answer 401 invalid token
instead, the same as an unknown key.
* test(auth): cover deleted-user keys with a warm Redis user cache
Treat gemini-4-hydrogen as a thinkingLevel model so cross-protocol requests apply the requested strength. Pass xhigh and max through on hydrogen, pass max through on argon, and keep mapping minimal to low on both.
Closes#8364
Gemini may split one answer across several text parts. The Chat
converters inserted a newline between consecutive text parts and
dropped parts that were exactly "\n", so JSON split inside a key,
string, number or escape reached clients as invalid JSON, and other
text was silently altered.
Plain text parts are now written as-is and empty parts add nothing;
only rendered media, code and stream thought blocks keep their newline
separation. Grounding citations use the byte offsets recorded while
rendering instead of searching the output, so preserved newlines next
to those blocks are cited at their real position.
Share cache pricing labels across the editor, pricing pages, usage logs, and estimator. Distinguish GPT 30m/12h, Claude 5m/1h, generic cache reads, and custom configurations while preserving existing prices.
Add regression coverage and translations for all seven locales. Verified 832 related tests, focused final UI tests, type checking, lint, production build, and desktop/mobile browser checks.