From 9be8227535fc390df6d541e36808abacb0cea6cd Mon Sep 17 00:00:00 2001 From: Phantom-IN Date: Wed, 25 Nov 2026 20:58:18 +0530 Subject: [PATCH] feat(llm): set profile prices in the settings dialog The cost ledger (#70) stores four prices per profile and the usage API turns them into cost_eur, but the UI never got the follow-up: the profile list did not return the prices and the dialog had no inputs for them. That also made prices fragile. SaveProfile always rewrites the price columns, and the dialog's save payload had no price fields, so editing a profile in the UI reset prices set through the API to zero. Return the prices in LLMProfileDTO, add the four inputs to the dialog and send them on save. A negative price is stored as unset. --- CHANGELOG.md | 1 + server/cost_ledger_test.go | 53 ++++++++++++++++++++++++++ server/dto.go | 10 +++++ server/server_mgmt.go | 5 +++ web/src/app/(main)/system/llm/page.tsx | 37 ++++++++++++++++++ web/src/i18n/locales/tr.json | 7 +++- web/src/i18n/locales/zh-CN.json | 7 +++- web/src/lib/api.ts | 5 +++ 8 files changed, 123 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f46c990e..033a2e39f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project are documented in this file. The format is b ### Added +- **LLM profile prices in the settings dialog** (follow-up to #70): the profile dialog has inputs for the four cost-ledger prices (EUR per 1M tokens), and the profile list returns them. Before this, prices could only be set through the API, and saving the profile from the UI reset them to zero because the dialog never sent them. A negative price is stored as unset. - **Wildcard domains in asset scope**: a scope line such as `*.example.com`, the way bug bounty programs write a domain and its subdomains, is accepted in company and task asset scope and stored as the `example.com` domain rule, which already covers its subdomains. A URL form (`https://*.example.com/`) works too. The wildcard is accepted only on a registrable domain: `*.api.example.com`, `*.co.uk` and `*.` are still rejected, because no rule covers only a subdomain's subdomains (#519). - **Stream viewer direction filter** (follow-up to #380): the Traffic detail's Stream tab can show all messages, client-to-server messages or server-to-client messages. Pagination and refresh keep the selected direction, changing the filter resets the list, and opening another exchange resets the direction to all. Recording-limit warnings remain visible but are excluded from the displayed message counts. - **Security response headers on every response**: `X-Content-Type-Options: nosniff`, a same-origin referrer policy, `X-Frame-Options: SAMEORIGIN` and a `frame-ancestors 'self'` CSP are now set by one wrapper around the whole handler tree, so the JSON API carries them too; previously only the console route did. Console documents additionally get `Permissions-Policy` and COOP/CORP. `Strict-Transport-Security` is sent only when the request is known to be HTTPS: directly over TLS, or via `X-Forwarded-Proto: https` from a peer in `ARTEX_TRUSTED_PROXIES`, so a direct client cannot claim HTTPS on its own. The README reverse-proxy recipe now starts with an 80 to 443 redirect. diff --git a/server/cost_ledger_test.go b/server/cost_ledger_test.go index bfc73ad19..3605d2d73 100644 --- a/server/cost_ledger_test.go +++ b/server/cost_ledger_test.go @@ -1,6 +1,11 @@ package server import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" "testing" "github.com/Autumn-27/artex/db" @@ -60,3 +65,51 @@ func TestCostLedgerEurOnUsage(t *testing.T) { t.Fatalf("cost_eur = %v, want %v", *got, want) } } + +// Prices saved through the profile API come back in the profile list, so the +// settings dialog can show them and send them back unchanged on the next save. +// A negative price is stored as unset. +func TestProfilePricesThroughAPI(t *testing.T) { + skipWithoutDSN(t) + m, err := NewManager(t.TempDir(), "") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { m.Close() }) + if m.pg == nil { + db.SkipNoPG(t) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir()) + + body, _ := json.Marshal(map[string]any{ + "name": "price-api-test", "format": "openai", "model": "m", "api_key": "k", + "price_input_per_m": 2.5, "price_output_per_m": 10, "price_cache_read_per_m": -1, + }) + rec := httptest.NewRecorder() + s.pgSaveProfile(rec, httptest.NewRequest(http.MethodPost, "/api/llm/profiles", bytes.NewReader(body))) + if rec.Code != http.StatusOK { + t.Fatalf("save: HTTP %d %s", rec.Code, rec.Body.String()) + } + var saved struct{ ID int64 } + _ = json.Unmarshal(rec.Body.Bytes(), &saved) + t.Cleanup(func() { _, _ = m.pg.Exec("DELETE FROM llm_profiles WHERE id=$1", saved.ID) }) + + rec = httptest.NewRecorder() + s.pgListProfiles(rec, httptest.NewRequest(http.MethodGet, "/api/llm/profiles", nil)) + var list struct{ Profiles []LLMProfileDTO } + if err := json.Unmarshal(rec.Body.Bytes(), &list); err != nil { + t.Fatal(err) + } + for _, p := range list.Profiles { + if p.Name != "price-api-test" { + continue + } + if p.PriceInputPerM != 2.5 || p.PriceOutputPerM != 10 || p.PriceCacheReadPerM != 0 || p.PriceCacheWritePerM != 0 { + t.Fatalf("listed prices = %v %v %v %v; want 2.5 10 0 0", p.PriceInputPerM, p.PriceOutputPerM, p.PriceCacheReadPerM, p.PriceCacheWritePerM) + } + return + } + t.Fatal("saved profile missing from the list") +} diff --git a/server/dto.go b/server/dto.go index 3de6307c8..80efde658 100644 --- a/server/dto.go +++ b/server/dto.go @@ -650,6 +650,11 @@ type LLMProfileDTO struct { // window). Per item attempts: 0=inherit the global policy | -1=disable that retry // layer | >0=count; interval_ms: 0=default exponential backoff | >0=use that fixed millisecond interval. All zero = fully follow the global policy, i.e. the historical behavior. Retry db.RetryOverride `json:"retry"` + // Cost ledger prices, EUR per 1M tokens; 0 = unset. + PriceInputPerM float64 `json:"price_input_per_m"` + PriceOutputPerM float64 `json:"price_output_per_m"` + PriceCacheReadPerM float64 `json:"price_cache_read_per_m"` + PriceCacheWritePerM float64 `json:"price_cache_write_per_m"` } func llmProfileDTO(p *db.LLMProfile) LLMProfileDTO { @@ -677,6 +682,11 @@ func llmProfileDTO(p *db.LLMProfile) LLMProfileDTO { UserAgent: p.UserAgent, CustomHeadersSet: p.CustomHeaders != "", Retry: p.Retry, + + PriceInputPerM: p.PriceInputPerM, + PriceOutputPerM: p.PriceOutputPerM, + PriceCacheReadPerM: p.PriceCacheReadPerM, + PriceCacheWritePerM: p.PriceCacheWritePerM, } } diff --git a/server/server_mgmt.go b/server/server_mgmt.go index 701c7e80f..c357a28f2 100644 --- a/server/server_mgmt.go +++ b/server/server_mgmt.go @@ -2178,6 +2178,11 @@ func (s *Server) pgSaveProfile(w http.ResponseWriter, r *http.Request) { if p.MaxTokens < 0 { p.MaxTokens = 0 } + for _, price := range []*float64{&p.PriceInputPerM, &p.PriceOutputPerM, &p.PriceCacheReadPerM, &p.PriceCacheWritePerM} { + if *price < 0 { + *price = 0 + } + } if p.Format != "openai" || p.MaxTokensField != llm.MaxTokensFieldCompletion { p.MaxTokensField = "" } diff --git a/web/src/app/(main)/system/llm/page.tsx b/web/src/app/(main)/system/llm/page.tsx index 52ac7c9db..224dd66a8 100644 --- a/web/src/app/(main)/system/llm/page.tsx +++ b/web/src/app/(main)/system/llm/page.tsx @@ -345,6 +345,7 @@ function ProfileSheet({ const [rps, setRps] = React.useState("0"); const [rpm, setRpm] = React.useState("0"); const [cw, setCw] = React.useState("0"); // context window (K tokens); 0 = default 200K + const [prices, setPrices] = React.useState({ input: "0", output: "0", cacheRead: "0", cacheWrite: "0" }); // EUR per 1M tokens; 0 = unset const [thinkingType, setThinkingType] = React.useState(NONE); const [effort, setEffort] = React.useState(NONE); const [priority, setPriority] = React.useState("0"); // pool order; higher = tried earlier @@ -380,6 +381,12 @@ function ProfileSheet({ setRps(String(profile?.rate_per_second ?? 0)); setRpm(String(profile?.rate_per_minute ?? 0)); setCw(String(profile?.context_window_k ?? 0)); + setPrices({ + input: String(profile?.price_input_per_m ?? 0), + output: String(profile?.price_output_per_m ?? 0), + cacheRead: String(profile?.price_cache_read_per_m ?? 0), + cacheWrite: String(profile?.price_cache_write_per_m ?? 0), + }); setThinkingType(fromStore(profile?.thinking_type)); setEffort(fromStore(profile?.reasoning_effort)); setPriority(String(profile?.priority ?? 0)); @@ -482,6 +489,10 @@ function ProfileSheet({ rate_per_second: Number(rps) || 0, rate_per_minute: Number(rpm) || 0, context_window_k: Number(cw) || 0, + price_input_per_m: Math.max(0, Number(prices.input) || 0), + price_output_per_m: Math.max(0, Number(prices.output) || 0), + price_cache_read_per_m: Math.max(0, Number(prices.cacheRead) || 0), + price_cache_write_per_m: Math.max(0, Number(prices.cacheWrite) || 0), thinking_type: toStore(thinkingType), reasoning_effort: toStore(effort), priority: Number(priority) || 0, @@ -769,6 +780,32 @@ function ProfileSheet({ )}

+
+ {( + [ + ["input", t("Input price")], + ["output", t("Output price")], + ["cacheRead", t("Cache read price")], + ["cacheWrite", t("Cache write price")], + ] as const + ).map(([key, label]) => ( +
+ + setPrices((p) => ({ ...p, [key]: e.target.value }))} + /> +
+ ))} +
+

+ {t("Optional. EUR per 1M tokens, used to compute the cost of this profile's token usage. 0 = not priced.")} +

+
diff --git a/web/src/i18n/locales/tr.json b/web/src/i18n/locales/tr.json index 736aa13f3..6a09975db 100644 --- a/web/src/i18n/locales/tr.json +++ b/web/src/i18n/locales/tr.json @@ -2724,5 +2724,10 @@ "Search company…": "Şirket ara…", "Failed to load companies": "Şirketler yüklenemedi", "No company found": "Şirket bulunamadı", - "Manage companies": "Şirketleri yönet" + "Manage companies": "Şirketleri yönet", + "Input price": "Girdi fiyatı", + "Output price": "Çıktı fiyatı", + "Cache read price": "Önbellek okuma fiyatı", + "Cache write price": "Önbellek yazma fiyatı", + "Optional. EUR per 1M tokens, used to compute the cost of this profile's token usage. 0 = not priced.": "İsteğe bağlı. 1M token başına EUR; bu profilin token kullanımının maliyetini hesaplamak için kullanılır. 0 = fiyatlandırılmamış." } diff --git a/web/src/i18n/locales/zh-CN.json b/web/src/i18n/locales/zh-CN.json index fa7b58d56..a8c4bc3bd 100644 --- a/web/src/i18n/locales/zh-CN.json +++ b/web/src/i18n/locales/zh-CN.json @@ -2724,5 +2724,10 @@ "Search company…": "搜索企业…", "Failed to load companies": "加载企业失败", "No company found": "未找到企业", - "Manage companies": "管理企业" + "Manage companies": "管理企业", + "Input price": "输入价格", + "Output price": "输出价格", + "Cache read price": "缓存读取价格", + "Cache write price": "缓存写入价格", + "Optional. EUR per 1M tokens, used to compute the cost of this profile's token usage. 0 = not priced.": "可选。每 100 万 Token 的价格(欧元),用于计算该配置的 Token 用量费用。0 = 未定价。" } diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index 7a1035c04..94a53e987 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -1173,6 +1173,11 @@ export const api = { rate_per_second?: number; rate_per_minute?: number; context_window_k?: number; + // Cost ledger, EUR per 1M tokens; 0 = unset. Sent on every save, which rewrites all four. + price_input_per_m?: number; + price_output_per_m?: number; + price_cache_read_per_m?: number; + price_cache_write_per_m?: number; thinking_type?: string; // ""(not sent)|"disabled"|"enabled" reasoning_effort?: string; // ""(not sent)|"low"|"medium"|"high"|"xhigh"|"max" priority?: number; // pool order position; higher is used first