Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 用量金额单位跟随 Gateway 来源,不再按构建区域写死 CNY (#488)

Chris Zhang7195b2fd390f
diff --git a/apps/desktop/drizzle/0081_preserve_gateway_currency.sql b/apps/desktop/drizzle/0081_preserve_gateway_currency.sql
new file mode 100644
index 0000000000..e0ac49d1ec
--- /dev/null
+++ b/apps/desktop/drizzle/0081_preserve_gateway_currency.sql
@@ -0,0 +1 @@
+SELECT 1;
diff --git a/apps/desktop/drizzle/meta/0081_snapshot.json b/apps/desktop/drizzle/meta/0081_snapshot.json
new file mode 100644
index 0000000000..5473ff5301
--- /dev/null
+++ b/apps/desktop/drizzle/meta/0081_snapshot.json
@@ -0,0 +1,3140 @@
+{
+ "id": "78f061ed-c715-452e-928f-33871745c4d4",
+ "prevId": "bc9927bd-878c-4d47-9840-d8c3db30a439",
+ "version": "6",
+ "dialect": "sqlite",
+ "tables": {
+ "account_usage_snapshots": {
+ "name": "account_usage_snapshots",
+ "columns": {
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "snapshot": {
+ "name": "snapshot",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "agent_input_queue_snapshots": {
+ "name": "agent_input_queue_snapshots",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "agent_input_queue_snapshots_session_id_sessions_id_fk": {
+ "name": "agent_input_queue_snapshots_session_id_sessions_id_fk",
+ "tableFrom": "agent_input_queue_snapshots",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "custom_mcp_servers": {
+ "name": "custom_mcp_servers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "transport": {
+ "name": "transport",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "headers": {
+ "name": "headers",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_custom_mcp_servers_sort_order": {
+ "name": "idx_custom_mcp_servers_sort_order",
+ "columns": [
+ "sort_order"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "custom_providers": {
+ "name": "custom_providers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "runtimes": {
+ "name": "runtimes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "auth": {
+ "name": "auth",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_custom_providers_sort_order": {
+ "name": "idx_custom_providers_sort_order",
+ "columns": [
+ "sort_order"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "daily_model_usage": {
+ "name": "daily_model_usage",
+ "columns": {
+ "day": {
+ "name": "day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_amount": {
+ "name": "cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_currency": {
+ "name": "cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_is_approximate": {
+ "name": "cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "input_tokens": {
+ "name": "input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "output_tokens": {
+ "name": "output_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cache_read_tokens": {
+ "name": "cache_read_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cache_create_tokens": {
+ "name": "cache_create_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "daily_model_usage_day_agent_kind_model_pk": {
+ "columns": [
+ "day",
+ "agent_kind",
+ "model"
+ ],
+ "name": "daily_model_usage_day_agent_kind_model_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "daily_spend": {
+ "name": "daily_spend",
+ "columns": {
+ "day": {
+ "name": "day",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_amount": {
+ "name": "cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_currency": {
+ "name": "cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_is_approximate": {
+ "name": "cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "device_link_ownership": {
+ "name": "device_link_ownership",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_pid": {
+ "name": "owner_pid",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_label": {
+ "name": "owner_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "heartbeat_at": {
+ "name": "heartbeat_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "embedding_jobs": {
+ "name": "embedding_jobs",
+ "columns": {
+ "rowid": {
+ "name": "rowid",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source_id": {
+ "name": "source_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chunk_index": {
+ "name": "chunk_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "vec_table": {
+ "name": "vec_table",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scheduled_at": {
+ "name": "scheduled_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "locked_at": {
+ "name": "locked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_embedding_jobs_natural": {
+ "name": "uniq_embedding_jobs_natural",
+ "columns": [
+ "source",
+ "source_id",
+ "chunk_index",
+ "model_id"
+ ],
+ "isUnique": true
+ },
+ "idx_embedding_jobs_status_scheduled": {
+ "name": "idx_embedding_jobs_status_scheduled",
+ "columns": [
+ "status",
+ "scheduled_at"
+ ],
+ "isUnique": false
+ },
+ "idx_embedding_jobs_source_id": {
+ "name": "idx_embedding_jobs_source_id",
+ "columns": [
+ "source",
+ "source_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "embedding_meta": {
+ "name": "embedding_meta",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "ghost_cards": {
+ "name": "ghost_cards",
+ "columns": {
+ "call_id": {
+ "name": "call_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ghost_id": {
+ "name": "ghost_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "html": {
+ "name": "html",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "height": {
+ "name": "height",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "v": {
+ "name": "v",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "ghost_cards_updated_at_idx": {
+ "name": "ghost_cards_updated_at_idx",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "im_bindings": {
+ "name": "im_bindings",
+ "columns": {
+ "channel": {
+ "name": "channel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_context_id": {
+ "name": "bot_context_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scope_key": {
+ "name": "scope_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "target_session_id": {
+ "name": "target_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attached_at": {
+ "name": "attached_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attached_via_card_message_id": {
+ "name": "attached_via_card_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_im_bindings_target": {
+ "name": "idx_im_bindings_target",
+ "columns": [
+ "target_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "im_bindings_target_session_id_sessions_id_fk": {
+ "name": "im_bindings_target_session_id_sessions_id_fk",
+ "tableFrom": "im_bindings",
+ "columnsFrom": [
+ "target_session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {
+ "im_bindings_channel_bot_context_id_user_id_scope_key_pk": {
+ "columns": [
+ "channel",
+ "bot_context_id",
+ "user_id",
+ "scope_key"
+ ],
+ "name": "im_bindings_channel_bot_context_id_user_id_scope_key_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "media_blobs": {
+ "name": "media_blobs",
+ "columns": {
+ "hash": {
+ "name": "hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ext": {
+ "name": "ext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mime_type": {
+ "name": "mime_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bytes": {
+ "name": "bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_cache": {
+ "name": "is_cache",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_access_at": {
+ "name": "last_access_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "media_refs": {
+ "name": "media_refs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "hash": {
+ "name": "hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ref_kind": {
+ "name": "ref_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ref_id": {
+ "name": "ref_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "origin_session_id": {
+ "name": "origin_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "origin_kind": {
+ "name": "origin_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "origin_id": {
+ "name": "origin_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "media_refs_hash_idx": {
+ "name": "media_refs_hash_idx",
+ "columns": [
+ "hash"
+ ],
+ "isUnique": false
+ },
+ "media_refs_ref_idx": {
+ "name": "media_refs_ref_idx",
+ "columns": [
+ "ref_kind",
+ "ref_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "media_refs_hash_media_blobs_hash_fk": {
+ "name": "media_refs_hash_media_blobs_hash_fk",
+ "tableFrom": "media_refs",
+ "columnsFrom": [
+ "hash"
+ ],
+ "tableTo": "media_blobs",
+ "columnsTo": [
+ "hash"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "messages": {
+ "name": "messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_use_id": {
+ "name": "tool_use_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_meta": {
+ "name": "agent_meta",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "rewind_at": {
+ "name": "rewind_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_messages_session_client": {
+ "name": "uniq_messages_session_client",
+ "columns": [
+ "session_id",
+ "client_id"
+ ],
+ "isUnique": true
+ },
+ "idx_messages_session_created": {
+ "name": "idx_messages_session_created",
+ "columns": [
+ "session_id",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "idx_messages_created_at": {
+ "name": "idx_messages_created_at",
+ "columns": [
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_messages_rewind_at": {
+ "name": "idx_messages_rewind_at",
+ "columns": [
+ "rewind_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "messages_session_id_sessions_id_fk": {
+ "name": "messages_session_id_sessions_id_fk",
+ "tableFrom": "messages",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "migration_history": {
+ "name": "migration_history",
+ "columns": {
+ "seq": {
+ "name": "seq",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "file_name": {
+ "name": "file_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content_hash": {
+ "name": "content_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "applied_at": {
+ "name": "applied_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "migration_meta": {
+ "name": "migration_meta",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_teams": {
+ "name": "orca_teams",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "lead_session_id": {
+ "name": "lead_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_active_team_per_lead": {
+ "name": "uniq_active_team_per_lead",
+ "columns": [
+ "lead_session_id"
+ ],
+ "where": "\"orca_teams\".\"status\" = 'active'",
+ "isUnique": true
+ },
+ "idx_orca_teams_status": {
+ "name": "idx_orca_teams_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_teams_lead_session_id_sessions_id_fk": {
+ "name": "orca_teams_lead_session_id_sessions_id_fk",
+ "tableFrom": "orca_teams",
+ "columnsFrom": [
+ "lead_session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_worker_creation_reservations": {
+ "name": "orca_worker_creation_reservations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_orca_worker_creation_reservations_team_label": {
+ "name": "uniq_orca_worker_creation_reservations_team_label",
+ "columns": [
+ "team_id",
+ "lower(\"label\")"
+ ],
+ "isUnique": true
+ },
+ "idx_orca_worker_creation_reservations_expires_at": {
+ "name": "idx_orca_worker_creation_reservations_expires_at",
+ "columns": [
+ "expires_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_worker_creation_reservations_team_id_orca_teams_id_fk": {
+ "name": "orca_worker_creation_reservations_team_id_orca_teams_id_fk",
+ "tableFrom": "orca_worker_creation_reservations",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "tableTo": "orca_teams",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_workers": {
+ "name": "orca_workers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'idle'"
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "worktree_branch": {
+ "name": "worktree_branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'developer'"
+ },
+ "focused": {
+ "name": "focused",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "idle_since": {
+ "name": "idle_since",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_orca_workers_session_id": {
+ "name": "uniq_orca_workers_session_id",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true
+ },
+ "uniq_orca_workers_team_label": {
+ "name": "uniq_orca_workers_team_label",
+ "columns": [
+ "team_id",
+ "lower(\"label\")"
+ ],
+ "isUnique": true
+ },
+ "uniq_orca_workers_focused_per_team": {
+ "name": "uniq_orca_workers_focused_per_team",
+ "columns": [
+ "team_id"
+ ],
+ "where": "\"orca_workers\".\"focused\" = true",
+ "isUnique": true
+ },
+ "idx_orca_workers_team_id": {
+ "name": "idx_orca_workers_team_id",
+ "columns": [
+ "team_id"
+ ],
+ "isUnique": false
+ },
+ "idx_orca_workers_status": {
+ "name": "idx_orca_workers_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_workers_team_id_orca_teams_id_fk": {
+ "name": "orca_workers_team_id_orca_teams_id_fk",
+ "tableFrom": "orca_workers",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "tableTo": "orca_teams",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "orca_workers_session_id_sessions_id_fk": {
+ "name": "orca_workers_session_id_sessions_id_fk",
+ "tableFrom": "orca_workers",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_aliases": {
+ "name": "project_aliases",
+ "columns": {
+ "project_key": {
+ "name": "project_key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "alias": {
+ "name": "alias",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_project_aliases_updated_at": {
+ "name": "idx_project_aliases_updated_at",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_automation_consents": {
+ "name": "project_automation_consents",
+ "columns": {
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "consented_at": {
+ "name": "consented_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "config_hash": {
+ "name": "config_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "recent_workdirs": {
+ "name": "recent_workdirs",
+ "columns": {
+ "path": {
+ "name": "path",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_recent_workdirs_last_used_at": {
+ "name": "idx_recent_workdirs_last_used_at",
+ "columns": [
+ "last_used_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "right_sidebar_tabs": {
+ "name": "right_sidebar_tabs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "right_sidebar_tabs_session_idx": {
+ "name": "right_sidebar_tabs_session_idx",
+ "columns": [
+ "session_id",
+ "position"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "right_sidebar_tabs_session_id_sessions_id_fk": {
+ "name": "right_sidebar_tabs_session_id_sessions_id_fk",
+ "tableFrom": "right_sidebar_tabs",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "schedule_runs": {
+ "name": "schedule_runs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "schedule_id": {
+ "name": "schedule_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fired_at": {
+ "name": "fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "error_msg": {
+ "name": "error_msg",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "estimated_value_usd": {
+ "name": "estimated_value_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_amount": {
+ "name": "cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "estimated_value_amount": {
+ "name": "estimated_value_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_currency": {
+ "name": "cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_is_approximate": {
+ "name": "cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "cost_attribution": {
+ "name": "cost_attribution",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'legacy'"
+ },
+ "result_text": {
+ "name": "result_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pre_run_hook_result": {
+ "name": "pre_run_hook_result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "read_at": {
+ "name": "read_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "heartbeat_at": {
+ "name": "heartbeat_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedule_runs_schedule": {
+ "name": "idx_schedule_runs_schedule",
+ "columns": [
+ "schedule_id",
+ "fired_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "schedule_runs_schedule_id_schedules_id_fk": {
+ "name": "schedule_runs_schedule_id_schedules_id_fk",
+ "tableFrom": "schedule_runs",
+ "columnsFrom": [
+ "schedule_id"
+ ],
+ "tableTo": "schedules",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "schedule_runs_session_id_sessions_id_fk": {
+ "name": "schedule_runs_session_id_sessions_id_fk",
+ "tableFrom": "schedule_runs",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "set null"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "schedules": {
+ "name": "schedules",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "job_type": {
+ "name": "job_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'prompt'"
+ },
+ "job_config": {
+ "name": "job_config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "execution_mode": {
+ "name": "execution_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'agent'"
+ },
+ "script_config": {
+ "name": "script_config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'user'"
+ },
+ "project_config_id": {
+ "name": "project_config_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "legacy_session_fallback": {
+ "name": "legacy_session_fallback",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'cron'"
+ },
+ "cron_expr": {
+ "name": "cron_expr",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "recurring": {
+ "name": "recurring",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "manual": {
+ "name": "manual",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "interval_ms": {
+ "name": "interval_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "effort": {
+ "name": "effort",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fast_mode": {
+ "name": "fast_mode",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_kind": {
+ "name": "workspace_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'project'"
+ },
+ "use_worktree": {
+ "name": "use_worktree",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "target_session_id": {
+ "name": "target_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "persistent_session": {
+ "name": "persistent_session",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "silent_when_idle": {
+ "name": "silent_when_idle",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "pre_run_hook_command": {
+ "name": "pre_run_hook_command",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pre_run_hook_timeout_ms": {
+ "name": "pre_run_hook_timeout_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "skip_log_session_id": {
+ "name": "skip_log_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "notify_desktop": {
+ "name": "notify_desktop",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "notify_feishu": {
+ "name": "notify_feishu",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_fired_at": {
+ "name": "last_fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_finished_at": {
+ "name": "last_finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "next_fire_at": {
+ "name": "next_fire_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expire_at": {
+ "name": "expire_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedules_active_next": {
+ "name": "idx_schedules_active_next",
+ "columns": [
+ "status",
+ "next_fire_at"
+ ],
+ "isUnique": false
+ },
+ "idx_schedules_target_session": {
+ "name": "idx_schedules_target_session",
+ "columns": [
+ "target_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "schedules_target_session_id_sessions_id_fk": {
+ "name": "schedules_target_session_id_sessions_id_fk",
+ "tableFrom": "schedules",
+ "columnsFrom": [
+ "target_session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "set null"
+ },
+ "schedules_skip_log_session_id_sessions_id_fk": {
+ "name": "schedules_skip_log_session_id_sessions_id_fk",
+ "tableFrom": "schedules",
+ "columnsFrom": [
+ "skip_log_session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "set null"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_goals": {
+ "name": "session_goals",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "objective": {
+ "name": "objective",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "budget_tokens": {
+ "name": "budget_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "max_turns": {
+ "name": "max_turns",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "no_progress_limit": {
+ "name": "no_progress_limit",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "turns_used": {
+ "name": "turns_used",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "tokens_used": {
+ "name": "tokens_used",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "no_progress_streak": {
+ "name": "no_progress_streak",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "usage_reset_at": {
+ "name": "usage_reset_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_reason": {
+ "name": "last_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_session_goals_status": {
+ "name": "idx_session_goals_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_goals_session_id_sessions_id_fk": {
+ "name": "session_goals_session_id_sessions_id_fk",
+ "tableFrom": "session_goals",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_pr_refs": {
+ "name": "session_pr_refs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner": {
+ "name": "owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "repo": {
+ "name": "repo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "first_seen_at": {
+ "name": "first_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_session_pr_refs": {
+ "name": "uniq_session_pr_refs",
+ "columns": [
+ "session_id",
+ "owner",
+ "repo",
+ "pr_number"
+ ],
+ "isUnique": true
+ },
+ "idx_session_pr_refs_session_last_seen": {
+ "name": "idx_session_pr_refs_session_last_seen",
+ "columns": [
+ "session_id",
+ "last_seen_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_pr_refs_session_id_sessions_id_fk": {
+ "name": "session_pr_refs_session_id_sessions_id_fk",
+ "tableFrom": "session_pr_refs",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'New Maker'"
+ },
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_kind": {
+ "name": "workspace_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'project'"
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'claude-sonnet-4-6'"
+ },
+ "effort": {
+ "name": "effort",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'high'"
+ },
+ "permission_mode": {
+ "name": "permission_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'ask'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "total_token_usage": {
+ "name": "total_token_usage",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_usd": {
+ "name": "total_cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_amount": {
+ "name": "total_cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_currency": {
+ "name": "total_cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "total_cost_is_approximate": {
+ "name": "total_cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "context_tokens": {
+ "name": "context_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "context_window": {
+ "name": "context_window",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "fast_mode": {
+ "name": "fast_mode",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "plan_mode_enabled": {
+ "name": "plan_mode_enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "cleared_at": {
+ "name": "cleared_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pinned_at": {
+ "name": "pinned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_send_at": {
+ "name": "user_send_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'cc'"
+ },
+ "orca_role": {
+ "name": "orca_role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "parent_session_id": {
+ "name": "parent_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "forked_at_message_id": {
+ "name": "forked_at_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "worktree_path": {
+ "name": "worktree_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'desktop'"
+ },
+ "feishu_open_id": {
+ "name": "feishu_open_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "feishu_bot_app_id": {
+ "name": "feishu_bot_app_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "im_bot_context_id": {
+ "name": "im_bot_context_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "im_user_id": {
+ "name": "im_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "used_project_context": {
+ "name": "used_project_context",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "codex_history_has_product_prompt": {
+ "name": "codex_history_has_product_prompt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "extra_dirs": {
+ "name": "extra_dirs",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "remote_host_id": {
+ "name": "remote_host_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "active_turn_started_at": {
+ "name": "active_turn_started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "active_turn_pid": {
+ "name": "active_turn_pid",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_turn_ended_at": {
+ "name": "last_turn_ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_sessions_updated_at": {
+ "name": "idx_sessions_updated_at",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_user_send_at": {
+ "name": "idx_sessions_user_send_at",
+ "columns": [
+ "user_send_at"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_sdk_session_id": {
+ "name": "idx_sessions_sdk_session_id",
+ "columns": [
+ "sdk_session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_workdir_created": {
+ "name": "idx_sessions_workdir_created",
+ "columns": [
+ "working_dir",
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_created_at": {
+ "name": "idx_sessions_created_at",
+ "columns": [
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_workspace_kind": {
+ "name": "idx_sessions_workspace_kind",
+ "columns": [
+ "workspace_kind"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_parent_session_id": {
+ "name": "idx_sessions_parent_session_id",
+ "columns": [
+ "parent_session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_orca_role": {
+ "name": "idx_sessions_orca_role",
+ "columns": [
+ "orca_role"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_worktree_path": {
+ "name": "idx_sessions_worktree_path",
+ "columns": [
+ "worktree_path"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_feishu_lookup": {
+ "name": "idx_sessions_feishu_lookup",
+ "columns": [
+ "source",
+ "feishu_bot_app_id",
+ "feishu_open_id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_im_lookup": {
+ "name": "idx_sessions_im_lookup",
+ "columns": [
+ "source",
+ "im_bot_context_id",
+ "im_user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "sessions_parent_session_id_sessions_id_fk": {
+ "name": "sessions_parent_session_id_sessions_id_fk",
+ "tableFrom": "sessions",
+ "columnsFrom": [
+ "parent_session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "set null"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "skill_usage_exposures": {
+ "name": "skill_usage_exposures",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "analyzer_version": {
+ "name": "analyzer_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'6'"
+ },
+ "raw_file_path": {
+ "name": "raw_file_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "raw_line_no": {
+ "name": "raw_line_no",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "skill_name": {
+ "name": "skill_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "skill_path": {
+ "name": "skill_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "skill_document_hash": {
+ "name": "skill_document_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "exposure_content_hash": {
+ "name": "exposure_content_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "document_hash_source": {
+ "name": "document_hash_source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_use_id": {
+ "name": "tool_use_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "seen_at": {
+ "name": "seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_call_count": {
+ "name": "tool_call_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "repeated_tool_call_count": {
+ "name": "repeated_tool_call_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "tool_error_count": {
+ "name": "tool_error_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "command_call_count": {
+ "name": "command_call_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "command_failure_count": {
+ "name": "command_failure_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ }
+ },
+ "indexes": {
+ "idx_skill_usage_exposures_skill_document_version": {
+ "name": "idx_skill_usage_exposures_skill_document_version",
+ "columns": [
+ "analyzer_version",
+ "skill_name",
+ "skill_document_hash"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_session": {
+ "name": "idx_skill_usage_exposures_session",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_raw_file": {
+ "name": "idx_skill_usage_exposures_raw_file",
+ "columns": [
+ "raw_file_path"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "skill_usage_exposures_raw_file_path_skill_usage_sources_raw_file_path_fk": {
+ "name": "skill_usage_exposures_raw_file_path_skill_usage_sources_raw_file_path_fk",
+ "tableFrom": "skill_usage_exposures",
+ "columnsFrom": [
+ "raw_file_path"
+ ],
+ "tableTo": "skill_usage_sources",
+ "columnsTo": [
+ "raw_file_path"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "skill_usage_sources": {
+ "name": "skill_usage_sources",
+ "columns": {
+ "raw_file_path": {
+ "name": "raw_file_path",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "analyzer_version": {
+ "name": "analyzer_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'6'"
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mtime_ms": {
+ "name": "mtime_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "size_bytes": {
+ "name": "size_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "last_scanned_at": {
+ "name": "last_scanned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'ok'"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_skill_usage_sources_session": {
+ "name": "idx_skill_usage_sources_session",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_sources_sdk_session": {
+ "name": "idx_skill_usage_sources_sdk_session",
+ "columns": [
+ "sdk_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "vec_table_meta": {
+ "name": "vec_table_meta",
+ "columns": {
+ "vec_table": {
+ "name": "vec_table",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "dim": {
+ "name": "dim",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "registered_at": {
+ "name": "registered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "notes": {
+ "name": "notes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ },
+ "internal": {
+ "indexes": {
+ "uniq_orca_worker_creation_reservations_team_label": {
+ "columns": {
+ "lower(\"label\")": {
+ "isExpression": true
+ }
+ }
+ },
+ "uniq_orca_workers_team_label": {
+ "columns": {
+ "lower(\"label\")": {
+ "isExpression": true
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/apps/desktop/drizzle/meta/_journal.json b/apps/desktop/drizzle/meta/_journal.json
index 8d4242f080..4e05bad07b 100644
--- a/apps/desktop/drizzle/meta/_journal.json
+++ b/apps/desktop/drizzle/meta/_journal.json
@@ -568,6 +568,13 @@
"when": 1784917033887,
"tag": "0080_regional_money",
"breakpoints": true
+ },
+ {
+ "idx": 81,
+ "version": "6",
+ "when": 1785037003169,
+ "tag": "0081_preserve_gateway_currency",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/apps/desktop/drizzle/scripts/0081_preserve_gateway_currency.ts b/apps/desktop/drizzle/scripts/0081_preserve_gateway_currency.ts
new file mode 100644
index 0000000000..4a8acf0d52
--- /dev/null
+++ b/apps/desktop/drizzle/scripts/0081_preserve_gateway_currency.ts
@@ -0,0 +1,170 @@
+import type Database from 'better-sqlite3';
+
+const USD_TO_CNY_FIXED_RATE = 6.7;
+
+interface TableInfoRow {
+ name: string;
+}
+
+function tableExists(db: Database.Database, tableName: string): boolean {
+ return (
+ db
+ .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1")
+ .get(tableName) !== undefined
+ );
+}
+
+function tableColumnNames(
+ db: Database.Database,
+ tableName: string,
+): Set<string> {
+ return new Set(
+ (db.prepare(`PRAGMA table_info('${tableName}')`).all() as TableInfoRow[]).map(
+ (row) => row.name,
+ ),
+ );
+}
+
+function relabelMoneyColumns(
+ db: Database.Database,
+ tableName: string,
+ amountColumn: string,
+ currencyColumn: string,
+ approximateColumn: string,
+ alwaysConvertedColumns: string[],
+): void {
+ if (!tableExists(db, tableName)) return;
+ const columns = tableColumnNames(db, tableName);
+ if (
+ !columns.has(amountColumn) ||
+ !columns.has(currencyColumn) ||
+ !columns.has(approximateColumn)
+ ) {
+ return;
+ }
+ for (const column of alwaysConvertedColumns) {
+ if (!columns.has(column)) continue;
+ db.prepare(
+ `UPDATE ${tableName} SET ${column} = ${column} / ${USD_TO_CNY_FIXED_RATE} WHERE ${currencyColumn} = 'CNY'`,
+ ).run();
+ }
+ db.prepare(
+ `UPDATE ${tableName} SET ${amountColumn} = ${amountColumn} / ${USD_TO_CNY_FIXED_RATE} WHERE ${currencyColumn} = 'CNY' AND ${approximateColumn} = 1`,
+ ).run();
+ db.prepare(
+ `UPDATE ${tableName} SET ${currencyColumn} = 'USD' WHERE ${currencyColumn} = 'CNY'`,
+ ).run();
+}
+
+interface MoneyLike {
+ amount?: unknown;
+ currency?: unknown;
+ approximate?: unknown;
+ estimateReasons?: unknown;
+}
+
+function relabelMoneyObject(value: unknown): boolean {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
+ const money = value as MoneyLike;
+ if (money.currency !== 'CNY') return false;
+ if (typeof money.amount !== 'number' || !Number.isFinite(money.amount)) {
+ return false;
+ }
+ if (money.approximate === true) {
+ money.amount = money.amount / USD_TO_CNY_FIXED_RATE;
+ }
+ money.currency = 'USD';
+ if (Array.isArray(money.estimateReasons)) {
+ const reasons = money.estimateReasons.filter(
+ (reason) => reason !== 'fixed-fx',
+ );
+ if (reasons.length > 0) {
+ money.estimateReasons = reasons;
+ } else {
+ delete money.estimateReasons;
+ }
+ }
+ return true;
+}
+
+function relabelMessageAgentMeta(db: Database.Database): void {
+ if (!tableExists(db, 'messages')) return;
+ const columns = tableColumnNames(db, 'messages');
+ if (!columns.has('id') || !columns.has('agent_meta')) return;
+ const rows = db
+ .prepare(
+ `SELECT id, agent_meta FROM messages WHERE agent_meta LIKE '%"currency":"CNY"%'`,
+ )
+ .all() as Array<{ id: string; agent_meta: string | null }>;
+ const update = db.prepare('UPDATE messages SET agent_meta = ? WHERE id = ?');
+ for (const row of rows) {
+ if (!row.agent_meta) continue;
+ let meta: Record<string, unknown>;
+ try {
+ const parsed = JSON.parse(row.agent_meta) as unknown;
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) continue;
+ meta = parsed as Record<string, unknown>;
+ } catch {
+ continue;
+ }
+ let changed = false;
+ changed = relabelMoneyObject(meta.turnCost) || changed;
+ changed = relabelMoneyObject(meta.userTurnCost) || changed;
+ const details = meta.turnUsageDetails;
+ if (details && typeof details === 'object' && !Array.isArray(details)) {
+ const perModelCost = (details as Record<string, unknown>).perModelCost;
+ if (Array.isArray(perModelCost)) {
+ for (const entry of perModelCost) {
+ if (entry && typeof entry === 'object' && !Array.isArray(entry)) {
+ changed =
+ relabelMoneyObject((entry as Record<string, unknown>).money) ||
+ changed;
+ }
+ }
+ }
+ }
+ if (changed) {
+ update.run(JSON.stringify(meta), row.id);
+ }
+ }
+}
+
+function run(db: Database.Database): void {
+ db.transaction(() => {
+ relabelMoneyColumns(
+ db,
+ 'daily_spend',
+ 'cost_amount',
+ 'cost_currency',
+ 'cost_is_approximate',
+ [],
+ );
+ relabelMoneyColumns(
+ db,
+ 'daily_model_usage',
+ 'cost_amount',
+ 'cost_currency',
+ 'cost_is_approximate',
+ [],
+ );
+ relabelMoneyColumns(
+ db,
+ 'sessions',
+ 'total_cost_amount',
+ 'total_cost_currency',
+ 'total_cost_is_approximate',
+ [],
+ );
+ relabelMoneyColumns(
+ db,
+ 'schedule_runs',
+ 'cost_amount',
+ 'cost_currency',
+ 'cost_is_approximate',
+ ['estimated_value_amount'],
+ );
+ relabelMessageAgentMeta(db);
+ })();
+}
+
+module.exports = { run };
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
index 5c19beda41..9599dded5d 100644
--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
@@ -291,7 +291,7 @@ describe('maker:event hot path ordering', () => {
expect(codexDoneSource).toContain('const pricing = isSubscriptionValue && !isCodexXaiProviderRoute');
expect(codexDoneSource).toContain('? await getModelPricing()');
expect(codexDoneSource).toContain(": await getModelPricingForModel('xd', pricingModel)");
- expect(codexDoneSource).toContain('regionalizeModelPriceQuote(price, CURRENT_CINDY_REGION)');
+ expect(codexDoneSource).toContain('price ?? undefined');
expect(codexDoneSource).toContain('if (!isSubscriptionValue && money)');
expect(codexDoneSource).toContain('void recordTurnSpend(money);');
expect(codexDoneSource).toContain('void recordSessionTurnSpend(session.id, money);');
@@ -336,7 +336,6 @@ describe('maker:event hot path ordering', () => {
expect(claudeDoneSource).toContain('const { turnMoney, perModel } = resolveClaudeTurnCostSinks(');
expect(claudeDoneSource).toContain('providerId: sessionProviderForBilling');
expect(claudeDoneSource).toContain('billingRoute,');
- expect(claudeDoneSource).toContain('region: CURRENT_CINDY_REGION');
expect(claudeDoneSource).toContain('recordTurnSpend(turnMoney);');
expect(claudeDoneSource).toContain('recordSessionTurnSpend(session.id, turnMoney);');
expect(claudeDoneSource).toContain('money: m.money,');
diff --git a/apps/desktop/src/main/__tests__/patchMessageAgentMeta.test.ts b/apps/desktop/src/main/__tests__/patchMessageAgentMeta.test.ts
index d763eb46c8..3e2ea01ec9 100644
--- a/apps/desktop/src/main/__tests__/patchMessageAgentMeta.test.ts
+++ b/apps/desktop/src/main/__tests__/patchMessageAgentMeta.test.ts
@@ -158,11 +158,11 @@ describe('extractEstimatedSessionValueEntries', () => {
const legacyEstimatedEntry = (clientId: string, costUsd: number) => ({
clientId,
money: {
- amount: expect.closeTo(costUsd * 6.7),
- currency: 'CNY',
+ amount: expect.closeTo(costUsd),
+ currency: 'USD',
approximate: true,
kind: 'value-estimate',
- estimateReasons: ['fixed-fx', 'legacy-usd', 'subscription-value'],
+ estimateReasons: ['legacy-usd', 'subscription-value'],
},
costUsd: expect.closeTo(costUsd),
});
diff --git a/apps/desktop/src/main/localDb/__tests__/dailyLedgerCurrencyConflict.test.ts b/apps/desktop/src/main/localDb/__tests__/dailyLedgerCurrencyConflict.test.ts
new file mode 100644
index 0000000000..2ff3035af0
--- /dev/null
+++ b/apps/desktop/src/main/localDb/__tests__/dailyLedgerCurrencyConflict.test.ts
@@ -0,0 +1,167 @@
+import Database from 'better-sqlite3';
+import { drizzle } from 'drizzle-orm/better-sqlite3';
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('../../logger', () => ({
+ createLogger: () => ({
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ debug: vi.fn(),
+ }),
+}));
+
+import * as schema from '../schema';
+import type { DbClient } from '../client/DbClient';
+import { clearCurrentDbClient, setCurrentDbClient } from '../client/current';
+import { incrementDailySpend, localDayKey } from '../dailySpend';
+import { incrementDailyModelUsage } from '../dailyModelUsage';
+
+const DDL = `
+ CREATE TABLE daily_spend (
+ day TEXT PRIMARY KEY NOT NULL,
+ cost_usd REAL NOT NULL DEFAULT 0,
+ cost_amount REAL NOT NULL DEFAULT 0,
+ cost_currency TEXT,
+ cost_is_approximate INTEGER NOT NULL DEFAULT 0,
+ updated_at INTEGER NOT NULL
+ );
+ CREATE TABLE daily_model_usage (
+ day TEXT NOT NULL,
+ agent_kind TEXT NOT NULL,
+ model TEXT NOT NULL,
+ cost_usd REAL NOT NULL DEFAULT 0,
+ cost_amount REAL NOT NULL DEFAULT 0,
+ cost_currency TEXT,
+ cost_is_approximate INTEGER NOT NULL DEFAULT 0,
+ input_tokens INTEGER NOT NULL DEFAULT 0,
+ output_tokens INTEGER NOT NULL DEFAULT 0,
+ cache_read_tokens INTEGER NOT NULL DEFAULT 0,
+ cache_create_tokens INTEGER NOT NULL DEFAULT 0,
+ updated_at INTEGER NOT NULL,
+ PRIMARY KEY (day, agent_kind, model)
+ );
+`;
+
+function createHarness() {
+ const sqlite = new Database(':memory:');
+ sqlite.exec(DDL);
+ const db = drizzle(sqlite, { schema });
+ const dbClient = { drizzle: db } as unknown as DbClient;
+ setCurrentDbClient(dbClient, 'test-user');
+ return {
+ sqlite,
+ dbClient,
+ close: () => {
+ clearCurrentDbClient(dbClient);
+ sqlite.close();
+ },
+ };
+}
+
+const usd = (amount: number) => ({
+ amount,
+ currency: 'USD' as const,
+ approximate: false,
+ kind: 'actual-cost' as const,
+});
+
+const cny = (amount: number) => ({
+ amount,
+ currency: 'CNY' as const,
+ approximate: false,
+ kind: 'actual-cost' as const,
+});
+
+describe('daily ledgers degrade gracefully on currency conflict', () => {
+ it('daily spend keeps the existing currency and drops the conflicting amount without throwing', async () => {
+ const harness = createHarness();
+ try {
+ await incrementDailySpend(usd(1.5));
+ const result = await incrementDailySpend(cny(10));
+ expect(result.money).toMatchObject({ amount: 1.5, currency: 'USD' });
+ const row = harness.sqlite
+ .prepare('SELECT cost_amount, cost_currency FROM daily_spend')
+ .get() as { cost_amount: number; cost_currency: string };
+ expect(row).toEqual({ cost_amount: 1.5, cost_currency: 'USD' });
+ } finally {
+ harness.close();
+ }
+ });
+
+ it('daily model usage still records token deltas when the money currency conflicts', async () => {
+ const harness = createHarness();
+ try {
+ await incrementDailyModelUsage({
+ agentKind: 'claude-code',
+ model: 'claude-opus-4-8',
+ money: usd(2),
+ inputTokensDelta: 100,
+ outputTokensDelta: 10,
+ cacheReadTokensDelta: 0,
+ cacheCreateTokensDelta: 0,
+ });
+ await expect(
+ incrementDailyModelUsage({
+ agentKind: 'claude-code',
+ model: 'claude-opus-4-8',
+ money: cny(13.4),
+ inputTokensDelta: 50,
+ outputTokensDelta: 5,
+ cacheReadTokensDelta: 7,
+ cacheCreateTokensDelta: 0,
+ }),
+ ).resolves.toBeUndefined();
+
+ const row = harness.sqlite
+ .prepare(
+ `SELECT cost_amount, cost_currency, input_tokens, output_tokens, cache_read_tokens
+ FROM daily_model_usage WHERE day = ?`,
+ )
+ .get(localDayKey()) as {
+ cost_amount: number;
+ cost_currency: string;
+ input_tokens: number;
+ output_tokens: number;
+ cache_read_tokens: number;
+ };
+ expect(row.cost_currency).toBe('USD');
+ expect(row.cost_amount).toBe(2);
+ expect(row.input_tokens).toBe(150);
+ expect(row.output_tokens).toBe(15);
+ expect(row.cache_read_tokens).toBe(7);
+ } finally {
+ harness.close();
+ }
+ });
+
+ it('daily model usage conflict with zero token deltas is a no-op', async () => {
+ const harness = createHarness();
+ try {
+ await incrementDailyModelUsage({
+ agentKind: 'codex',
+ model: 'gpt-5.5',
+ money: usd(1),
+ inputTokensDelta: 1,
+ outputTokensDelta: 0,
+ cacheReadTokensDelta: 0,
+ cacheCreateTokensDelta: 0,
+ });
+ await incrementDailyModelUsage({
+ agentKind: 'codex',
+ model: 'gpt-5.5',
+ money: cny(6.7),
+ inputTokensDelta: 0,
+ outputTokensDelta: 0,
+ cacheReadTokensDelta: 0,
+ cacheCreateTokensDelta: 0,
+ });
+ const row = harness.sqlite
+ .prepare('SELECT cost_amount, input_tokens FROM daily_model_usage')
+ .get() as { cost_amount: number; input_tokens: number };
+ expect(row).toEqual({ cost_amount: 1, input_tokens: 1 });
+ } finally {
+ harness.close();
+ }
+ });
+});
diff --git a/apps/desktop/src/main/localDb/__tests__/preserveGatewayCurrencyMigration.test.ts b/apps/desktop/src/main/localDb/__tests__/preserveGatewayCurrencyMigration.test.ts
new file mode 100644
index 0000000000..85c86b8079
--- /dev/null
+++ b/apps/desktop/src/main/localDb/__tests__/preserveGatewayCurrencyMigration.test.ts
@@ -0,0 +1,236 @@
+import Database from 'better-sqlite3';
+import { describe, expect, it } from 'vitest';
+
+// Migration companion scripts intentionally use CommonJS so the runtime loader can replay them.
+const migration0081 =
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ require('../../../../drizzle/scripts/0081_preserve_gateway_currency.ts') as {
+ run(db: Database.Database): void;
+ };
+
+const RATE = 6.7;
+
+function setupDb(): Database.Database {
+ const db = new Database(':memory:');
+ db.exec(`
+ CREATE TABLE daily_spend (
+ day TEXT PRIMARY KEY NOT NULL,
+ cost_usd REAL NOT NULL DEFAULT 0,
+ cost_amount REAL NOT NULL DEFAULT 0,
+ cost_currency TEXT,
+ cost_is_approximate INTEGER NOT NULL DEFAULT 0,
+ updated_at INTEGER NOT NULL DEFAULT 0
+ );
+ CREATE TABLE daily_model_usage (
+ day TEXT NOT NULL,
+ agent_kind TEXT NOT NULL,
+ model TEXT NOT NULL,
+ cost_amount REAL NOT NULL DEFAULT 0,
+ cost_currency TEXT,
+ cost_is_approximate INTEGER NOT NULL DEFAULT 0
+ );
+ CREATE TABLE sessions (
+ id TEXT PRIMARY KEY NOT NULL,
+ total_cost_amount REAL NOT NULL DEFAULT 0,
+ total_cost_currency TEXT,
+ total_cost_is_approximate INTEGER NOT NULL DEFAULT 0
+ );
+ CREATE TABLE schedule_runs (
+ id TEXT PRIMARY KEY NOT NULL,
+ cost_amount REAL NOT NULL DEFAULT 0,
+ estimated_value_amount REAL NOT NULL DEFAULT 0,
+ cost_currency TEXT,
+ cost_is_approximate INTEGER NOT NULL DEFAULT 0
+ );
+ CREATE TABLE messages (
+ id TEXT PRIMARY KEY NOT NULL,
+ agent_meta TEXT
+ );
+ `);
+ return db;
+}
+
+describe('0081 preserve gateway currency relabel', () => {
+ it('relabels exact CNY rows to USD without changing amounts (they were mislabeled gateway USD)', () => {
+ const db = setupDb();
+ try {
+ db.exec(`
+ INSERT INTO daily_spend (day, cost_amount, cost_currency, cost_is_approximate)
+ VALUES ('2026-07-25', 273.5, 'CNY', 0);
+ INSERT INTO sessions (id, total_cost_amount, total_cost_currency, total_cost_is_approximate)
+ VALUES ('s1', 3631.96, 'CNY', 0);
+ `);
+ migration0081.run(db);
+ expect(
+ db.prepare('SELECT cost_amount, cost_currency FROM daily_spend').get(),
+ ).toEqual({ cost_amount: 273.5, cost_currency: 'USD' });
+ expect(
+ db
+ .prepare('SELECT total_cost_amount, total_cost_currency FROM sessions')
+ .get(),
+ ).toEqual({ total_cost_amount: 3631.96, total_cost_currency: 'USD' });
+ } finally {
+ db.close();
+ }
+ });
+
+ it('inverts the fixed 6.7 conversion for approximate CNY rows and always for estimated values', () => {
+ const db = setupDb();
+ try {
+ db.exec(`
+ INSERT INTO daily_model_usage (day, agent_kind, model, cost_amount, cost_currency, cost_is_approximate)
+ VALUES ('2026-07-25', 'claude-code', 'claude-opus-4-8', 6.7, 'CNY', 1);
+ INSERT INTO schedule_runs (id, cost_amount, estimated_value_amount, cost_currency, cost_is_approximate)
+ VALUES ('r1', 13.4, 6.7, 'CNY', 0);
+ `);
+ migration0081.run(db);
+ const model = db
+ .prepare('SELECT cost_amount, cost_currency FROM daily_model_usage')
+ .get() as { cost_amount: number; cost_currency: string };
+ expect(model.cost_currency).toBe('USD');
+ expect(model.cost_amount).toBeCloseTo(1);
+ const run = db
+ .prepare(
+ 'SELECT cost_amount, estimated_value_amount, cost_currency FROM schedule_runs',
+ )
+ .get() as {
+ cost_amount: number;
+ estimated_value_amount: number;
+ cost_currency: string;
+ };
+ expect(run.cost_currency).toBe('USD');
+ expect(run.cost_amount).toBeCloseTo(13.4);
+ expect(run.estimated_value_amount).toBeCloseTo(1);
+ } finally {
+ db.close();
+ }
+ });
+
+ it('leaves USD rows and rows without currency untouched', () => {
+ const db = setupDb();
+ try {
+ db.exec(`
+ INSERT INTO daily_spend (day, cost_amount, cost_currency, cost_is_approximate)
+ VALUES ('2026-07-24', 12, 'USD', 0), ('2026-07-23', 0, NULL, 0);
+ `);
+ migration0081.run(db);
+ expect(
+ db
+ .prepare('SELECT cost_amount, cost_currency FROM daily_spend ORDER BY day')
+ .all(),
+ ).toEqual([
+ { cost_amount: 0, cost_currency: null },
+ { cost_amount: 12, cost_currency: 'USD' },
+ ]);
+ } finally {
+ db.close();
+ }
+ });
+
+ it('rewrites CNY money objects inside messages.agent_meta and drops the fixed-fx reason', () => {
+ const db = setupDb();
+ try {
+ const meta = JSON.stringify({
+ uuid: 'keep-me',
+ turnCost: {
+ amount: 11.17,
+ currency: 'CNY',
+ approximate: false,
+ kind: 'actual-cost',
+ },
+ userTurnCost: {
+ amount: 6.7,
+ currency: 'CNY',
+ approximate: true,
+ kind: 'actual-cost',
+ estimateReasons: ['fixed-fx', 'legacy-usd'],
+ },
+ turnUsageDetails: {
+ perModelCost: [
+ {
+ model: 'claude-opus-4-8',
+ money: {
+ amount: 13.4,
+ currency: 'CNY',
+ approximate: true,
+ kind: 'value-estimate',
+ estimateReasons: ['fixed-fx'],
+ },
+ },
+ ],
+ },
+ });
+ const untouched = JSON.stringify({
+ turnCost: {
+ amount: 2,
+ currency: 'USD',
+ approximate: false,
+ kind: 'actual-cost',
+ },
+ });
+ db.prepare('INSERT INTO messages (id, agent_meta) VALUES (?, ?)').run('m1', meta);
+ db.prepare('INSERT INTO messages (id, agent_meta) VALUES (?, ?)').run('m2', untouched);
+ db.prepare('INSERT INTO messages (id, agent_meta) VALUES (?, ?)').run('m3', 'not json {');
+
+ migration0081.run(db);
+
+ const rewritten = JSON.parse(
+ (db.prepare('SELECT agent_meta FROM messages WHERE id = ?').get('m1') as {
+ agent_meta: string;
+ }).agent_meta,
+ );
+ expect(rewritten.uuid).toBe('keep-me');
+ expect(rewritten.turnCost).toEqual({
+ amount: 11.17,
+ currency: 'USD',
+ approximate: false,
+ kind: 'actual-cost',
+ });
+ expect(rewritten.userTurnCost.currency).toBe('USD');
+ expect(rewritten.userTurnCost.amount).toBeCloseTo(6.7 / RATE);
+ expect(rewritten.userTurnCost.estimateReasons).toEqual(['legacy-usd']);
+ const perModel = rewritten.turnUsageDetails.perModelCost[0].money;
+ expect(perModel.currency).toBe('USD');
+ expect(perModel.amount).toBeCloseTo(2);
+ expect(perModel.estimateReasons).toBeUndefined();
+
+ expect(
+ (db.prepare('SELECT agent_meta FROM messages WHERE id = ?').get('m2') as {
+ agent_meta: string;
+ }).agent_meta,
+ ).toBe(untouched);
+ expect(
+ (db.prepare('SELECT agent_meta FROM messages WHERE id = ?').get('m3') as {
+ agent_meta: string;
+ }).agent_meta,
+ ).toBe('not json {');
+ } finally {
+ db.close();
+ }
+ });
+
+ it('is idempotent and tolerates missing tables or columns', () => {
+ const db = setupDb();
+ try {
+ db.exec(`
+ INSERT INTO daily_spend (day, cost_amount, cost_currency, cost_is_approximate)
+ VALUES ('2026-07-25', 100, 'CNY', 0);
+ `);
+ migration0081.run(db);
+ migration0081.run(db);
+ expect(
+ db.prepare('SELECT cost_amount, cost_currency FROM daily_spend').get(),
+ ).toEqual({ cost_amount: 100, cost_currency: 'USD' });
+ } finally {
+ db.close();
+ }
+
+ const partial = new Database(':memory:');
+ try {
+ partial.exec('CREATE TABLE daily_spend (day TEXT PRIMARY KEY NOT NULL)');
+ expect(() => migration0081.run(partial)).not.toThrow();
+ } finally {
+ partial.close();
+ }
+ });
+});
diff --git a/apps/desktop/src/main/localDb/dailyModelUsage.ts b/apps/desktop/src/main/localDb/dailyModelUsage.ts
index 4600245ba1..d1488d2d24 100644
--- a/apps/desktop/src/main/localDb/dailyModelUsage.ts
+++ b/apps/desktop/src/main/localDb/dailyModelUsage.ts
@@ -1,16 +1,17 @@
import { sql } from 'drizzle-orm';
-import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
import {
addRegionalMoney,
+ legacyUsdMoney,
normalizeRegionalMoney,
- regionalCurrencyForRegion,
- regionalizeLegacyUsd,
type RegionalMoney,
} from '../../shared/regionalMoney.js';
import { dailyModelUsage } from './schema.js';
import { localDayKey } from './dailySpend.js';
import { getDbClient } from './client/current.js';
+import { createLogger } from '../logger.js';
+
+const log = createLogger('localDb/dailyModelUsage');
export interface DailyModelUsageDelta {
agentKind: 'claude-code' | 'codex';
@@ -42,9 +43,6 @@ export async function incrementDailyModelUsage(
ts: number = Date.now(),
): Promise<void> {
const money = delta.money ? normalizeRegionalMoney(delta.money) : undefined;
- if (money && money.currency !== regionalCurrencyForRegion(CURRENT_CINDY_REGION)) {
- throw new Error('daily model usage currency mismatch');
- }
const inputTokens = sanitizeTokens(delta.inputTokensDelta);
const outputTokens = sanitizeTokens(delta.outputTokensDelta);
const cacheReadTokens = sanitizeTokens(delta.cacheReadTokensDelta);
@@ -62,22 +60,12 @@ export async function incrementDailyModelUsage(
const day = localDayKey(ts);
const model = delta.model || 'unknown';
const db = getDbClient().drizzle;
- const existing = await db
- .select({ costCurrency: dailyModelUsage.costCurrency })
- .from(dailyModelUsage)
- .where(
- sql`${dailyModelUsage.day} = ${day}
- AND ${dailyModelUsage.agentKind} = ${delta.agentKind}
- AND ${dailyModelUsage.model} = ${model}`,
- )
- .get();
- if (
- money &&
- existing?.costCurrency &&
- existing.costCurrency !== money.currency
- ) {
- throw new Error('daily model usage row has conflicting currency');
- }
+ // 单币种行:币种守卫必须在同一条 upsert 里用 CASE 表达 —— 先查再写有
+ // TOCTOU 窗口,并发首写会把不同币种的裸数字加进同一行。冲突时原子地只弃
+ // 金额,token 增量照记(throw 会连本轮 token 统计一起丢,损失更大)。
+ const sameCurrency = money
+ ? sql`(${dailyModelUsage.costCurrency} IS NULL OR ${dailyModelUsage.costCurrency} = ${money.currency})`
+ : sql`0`;
await db
.insert(dailyModelUsage)
.values({
@@ -100,9 +88,9 @@ export async function incrementDailyModelUsage(
dailyModelUsage.model,
],
set: {
- costAmount: sql`${dailyModelUsage.costAmount} + ${money?.amount ?? 0}`,
- ...(money ? { costCurrency: money.currency } : {}),
- costIsApproximate: sql`${dailyModelUsage.costIsApproximate} OR ${money?.approximate ? 1 : 0}`,
+ costAmount: sql`CASE WHEN ${sameCurrency} THEN ${dailyModelUsage.costAmount} + ${money?.amount ?? 0} ELSE ${dailyModelUsage.costAmount} END`,
+ costCurrency: sql`CASE WHEN ${sameCurrency} THEN ${money?.currency ?? null} ELSE ${dailyModelUsage.costCurrency} END`,
+ costIsApproximate: sql`CASE WHEN ${sameCurrency} THEN (${dailyModelUsage.costIsApproximate} OR ${money?.approximate ? 1 : 0}) ELSE ${dailyModelUsage.costIsApproximate} END`,
inputTokens: sql`${dailyModelUsage.inputTokens} + ${inputTokens}`,
outputTokens: sql`${dailyModelUsage.outputTokens} + ${outputTokens}`,
cacheReadTokens: sql`${dailyModelUsage.cacheReadTokens} + ${cacheReadTokens}`,
@@ -111,6 +99,23 @@ export async function incrementDailyModelUsage(
},
})
.run();
+ if (money) {
+ const row = await db
+ .select({ costCurrency: dailyModelUsage.costCurrency })
+ .from(dailyModelUsage)
+ .where(
+ sql`${dailyModelUsage.day} = ${day}
+ AND ${dailyModelUsage.agentKind} = ${delta.agentKind}
+ AND ${dailyModelUsage.model} = ${model}`,
+ )
+ .get();
+ if (row?.costCurrency && row.costCurrency !== money.currency) {
+ log.warn(
+ `daily model usage currency conflict on ${day}/${delta.agentKind}/${model}: ` +
+ `keeping ${row.costCurrency}, dropped ${money.currency} amount`,
+ );
+ }
+ }
}
export async function getModelUsageSince(
@@ -134,7 +139,7 @@ export async function getModelUsageSince(
.where(sql`${dailyModelUsage.day} >= ${sinceDayKey}`)
.all();
return rows.map((row) => {
- const legacy = regionalizeLegacyUsd(row.costUsd, CURRENT_CINDY_REGION);
+ const legacy = legacyUsdMoney(row.costUsd);
const current =
row.costCurrency && row.costAmount > 0
? normalizeRegionalMoney({
diff --git a/apps/desktop/src/main/localDb/dailySpend.ts b/apps/desktop/src/main/localDb/dailySpend.ts
index c7c9e35334..f9a55decf4 100644
--- a/apps/desktop/src/main/localDb/dailySpend.ts
+++ b/apps/desktop/src/main/localDb/dailySpend.ts
@@ -1,15 +1,16 @@
import { sql } from 'drizzle-orm';
-import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
import {
addRegionalMoney,
+ legacyUsdMoney,
normalizeRegionalMoney,
- regionalCurrencyForRegion,
- regionalizeLegacyUsd,
type RegionalMoney,
} from '../../shared/regionalMoney.js';
import { dailySpend } from './schema.js';
import { getDbClient } from './client/current.js';
+import { createLogger } from '../logger.js';
+
+const log = createLogger('localDb/dailySpend');
export function localDayKey(ts: number = Date.now()): string {
const date = new Date(ts);
@@ -25,7 +26,7 @@ function rowMoney(row: {
costCurrency: 'CNY' | 'USD' | null;
costIsApproximate: boolean;
} | undefined): RegionalMoney {
- const legacy = regionalizeLegacyUsd(row?.costUsd ?? 0, CURRENT_CINDY_REGION);
+ const legacy = legacyUsdMoney(row?.costUsd ?? 0);
const current =
row?.costCurrency && row.costAmount > 0
? normalizeRegionalMoney({
@@ -66,22 +67,11 @@ export async function incrementDailySpend(
if (!normalized || normalized.amount < 1e-10) {
return { day, money: await getSpendForDay(day) };
}
- const expectedCurrency = regionalCurrencyForRegion(CURRENT_CINDY_REGION);
- if (normalized.currency !== expectedCurrency) {
- throw new Error(
- `daily spend currency mismatch: ${normalized.currency} != ${expectedCurrency}`,
- );
- }
-
const db = getDbClient().drizzle;
- const existing = await db
- .select({ costCurrency: dailySpend.costCurrency })
- .from(dailySpend)
- .where(sql`${dailySpend.day} = ${day}`)
- .get();
- if (existing?.costCurrency && existing.costCurrency !== normalized.currency) {
- throw new Error('daily spend row has conflicting currency');
- }
+ // 单币种日账本:币种守卫必须在同一条 upsert 里用 CASE 表达 —— 先查再写有
+ // TOCTOU 窗口,并发首写会把不同币种的裸数字加进同一行。冲突段原子地弃掉
+ // (行保持原币种),绝不 throw:抛异常会打断 turn 收尾管道,损失更大。
+ const sameCurrency = sql`(${dailySpend.costCurrency} IS NULL OR ${dailySpend.costCurrency} = ${normalized.currency})`;
await db
.insert(dailySpend)
.values({
@@ -94,14 +84,20 @@ export async function incrementDailySpend(
.onConflictDoUpdate({
target: dailySpend.day,
set: {
- costAmount: sql`${dailySpend.costAmount} + ${normalized.amount}`,
- costCurrency: normalized.currency,
- costIsApproximate: sql`${dailySpend.costIsApproximate} OR ${normalized.approximate ? 1 : 0}`,
+ costAmount: sql`CASE WHEN ${sameCurrency} THEN ${dailySpend.costAmount} + ${normalized.amount} ELSE ${dailySpend.costAmount} END`,
+ costCurrency: sql`CASE WHEN ${sameCurrency} THEN ${normalized.currency} ELSE ${dailySpend.costCurrency} END`,
+ costIsApproximate: sql`CASE WHEN ${sameCurrency} THEN (${dailySpend.costIsApproximate} OR ${normalized.approximate ? 1 : 0}) ELSE ${dailySpend.costIsApproximate} END`,
updatedAt: ts,
},
})
.run();
- return { day, money: await getSpendForDay(day) };
+ const persisted = await getSpendForDay(day);
+ if (persisted.currency !== normalized.currency && persisted.amount > 0) {
+ log.warn(
+ `daily spend currency conflict on ${day}: keeping ${persisted.currency}, dropped ${normalized.currency} amount`,
+ );
+ }
+ return { day, money: persisted };
}
export function getTodaySpend(): Promise<RegionalMoney> {
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
index 3d5010aba4..3ddc30f74a 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
@@ -633,13 +633,13 @@ describe('readPriorUserRoundCost', () => {
await expect(readPriorUserRoundCost('s1', 'target')).resolves.toEqual({
money: {
- amount: expect.closeTo(18.934191 * 6.7, 10),
- currency: 'CNY',
+ amount: expect.closeTo(18.934191, 10),
+ currency: 'USD',
approximate: true,
kind: 'actual-cost',
- estimateReasons: ['fixed-fx', 'legacy-usd', 'subscription-value'],
+ estimateReasons: ['subscription-value'],
},
- costUsd: 0,
+ costUsd: 18.934191,
hasEstimatedValue: true,
});
});
@@ -672,13 +672,12 @@ describe('readPriorUserRoundCost', () => {
await expect(readPriorUserRoundCost('s1', 'target')).resolves.toEqual({
money: {
- amount: 3.35,
- currency: 'CNY',
- approximate: true,
+ amount: 0.5,
+ currency: 'USD',
+ approximate: false,
kind: 'actual-cost',
- estimateReasons: ['fixed-fx', 'legacy-usd'],
},
- costUsd: 0,
+ costUsd: 0.5,
hasEstimatedValue: false,
});
});
diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.ts
index 1be3c96cc8..cca04f3688 100644
--- a/apps/desktop/src/main/localDb/ipc/messages.ts
+++ b/apps/desktop/src/main/localDb/ipc/messages.ts
@@ -34,14 +34,12 @@ import {
} from '../../../shared/interruptedTurn.js';
import { resolveStaleCodexSubscriptionValueEstimate } from '../../../shared/codexSubscriptionValue.js';
import { normalizeTurnUsageDetails } from '../../../shared/turnUsageDetails.js';
-import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion.js';
import {
addCompatibleRegionalMoney,
asValueEstimateMoney,
+ legacyUsdMoney,
normalizeRegionalMoney,
- regionalCurrencyForRegion,
- regionalizeLegacyUsd,
- regionalizeUsd,
+ usdMoney,
type RegionalMoney,
} from '../../../shared/regionalMoney.js';
import { capReferenceMessageRows } from './history.js';
@@ -350,10 +348,7 @@ export function registerMessageIpc(): void {
);
const entries = extractEstimatedSessionValueEntries(rows);
const totalValueMoney =
- addCompatibleRegionalMoney(
- entries.map((entry) => entry.money),
- regionalCurrencyForRegion(CURRENT_CINDY_REGION),
- );
+ addCompatibleRegionalMoney(entries.map((entry) => entry.money));
const hasCompleteUsdProjection = entries.every((entry) => typeof entry.costUsd === 'number');
return {
totalValueMoney,
@@ -1101,7 +1096,7 @@ export function extractEstimatedSessionValueEntries(
const costUsd = recomputed ?? meta.turnCostUsd;
entries.push({
clientId: row.clientId,
- money: regionalizeUsd(costUsd, CURRENT_CINDY_REGION, 'legacy-usd', 'value-estimate'),
+ money: usdMoney(costUsd, 'value-estimate', 'legacy-usd'),
costUsd,
});
}
@@ -1257,7 +1252,7 @@ export async function readPriorUserRoundCost(
typeof meta?.turnCostUsd === 'number' &&
Number.isFinite(meta.turnCostUsd) &&
meta.turnCostUsd > 0
- ? regionalizeLegacyUsd(meta.turnCostUsd, CURRENT_CINDY_REGION)
+ ? legacyUsdMoney(meta.turnCostUsd)
: undefined;
const rawSegment = structured ?? legacy;
const isEstimate = rawSegment?.kind === 'value-estimate' || meta?.turnCostIsEstimate === true;
@@ -1266,10 +1261,7 @@ export async function readPriorUserRoundCost(
values.push(segment);
if (isEstimate) estimatedCurrencies.add(segment.currency);
}
- const money = addCompatibleRegionalMoney(
- values,
- regionalCurrencyForRegion(CURRENT_CINDY_REGION),
- );
+ const money = addCompatibleRegionalMoney(values);
const hasEstimatedValue =
money !== null && estimatedCurrencies.has(money.currency);
return {
@@ -1351,7 +1343,7 @@ async function hydrateLegacyUserTurnCosts(history: Message[]): Promise<Message[]
hasEstimatedValue ||= meta?.turnCostIsEstimate === true;
if (legacyClientIds.has(row.clientId)) {
totalsByClientId.set(row.clientId, {
- money: regionalizeLegacyUsd(costUsd, CURRENT_CINDY_REGION),
+ money: legacyUsdMoney(costUsd),
costUsd,
hasEstimatedValue,
});
diff --git a/apps/desktop/src/main/localDb/mapper.ts b/apps/desktop/src/main/localDb/mapper.ts
index c4f689c547..0c5243df73 100644
--- a/apps/desktop/src/main/localDb/mapper.ts
+++ b/apps/desktop/src/main/localDb/mapper.ts
@@ -41,13 +41,12 @@ import type {
import { normalizeSessionSource } from '../../shared/sessionSource.js';
import { normalizeWorkingDirForStorage } from '../../shared/workingDir.js';
import { isSyntheticTriggerText } from '../../shared/interruptedTurn.js';
-import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
import {
addRegionalMoney,
+ legacyUsdMoney,
normalizeRegionalMoney,
- regionalizeLegacyUsd,
- regionalizeUsd,
- zeroRegionalMoney,
+ usdMoney,
+ zeroUsageMoney,
} from '../../shared/regionalMoney.js';
type SessionRow = typeof sessions.$inferSelect;
@@ -126,7 +125,7 @@ export function extractMessagePreview(
*/
export function sessionToCamel(row: SessionRowWithCount): Session {
const legacyMoney =
- row.totalCostUsd > 0 ? regionalizeLegacyUsd(row.totalCostUsd, CURRENT_CINDY_REGION) : undefined;
+ row.totalCostUsd > 0 ? legacyUsdMoney(row.totalCostUsd) : undefined;
const currentMoney =
row.totalCostCurrency && row.totalCostAmount > 0
? normalizeRegionalMoney({
@@ -141,7 +140,7 @@ export function sessionToCamel(row: SessionRowWithCount): Session {
? legacyMoney.currency === currentMoney.currency
? addRegionalMoney([legacyMoney, currentMoney])
: currentMoney
- : (currentMoney ?? legacyMoney ?? zeroRegionalMoney(CURRENT_CINDY_REGION));
+ : (currentMoney ?? legacyMoney ?? zeroUsageMoney());
// 旧字段兼容投影,与 totalMoney 同一 combine 语义:结构化累计仍是 USD 时并入,
// 否则(CNY 无法表达进 USD 字段)保持冻结历史值。只消费 totalCostUsd 的读方
// (device-link v1 / 手机端)在全量 reseed 后才不会丢本构建新增的 USD 花费。
@@ -698,7 +697,7 @@ export function projectAutomationConsentToRow(
/** ScheduleRun 行 → 内存对象。 */
export function scheduleRunToCamel(row: ScheduleRunRow): ScheduleRun {
const legacyCost =
- row.costUsd > 0 ? regionalizeLegacyUsd(row.costUsd, CURRENT_CINDY_REGION) : undefined;
+ row.costUsd > 0 ? legacyUsdMoney(row.costUsd) : undefined;
const currentCost =
row.costCurrency && row.costAmount > 0
? normalizeRegionalMoney({
@@ -713,10 +712,10 @@ export function scheduleRunToCamel(row: ScheduleRunRow): ScheduleRun {
? legacyCost.currency === currentCost.currency
? addRegionalMoney([legacyCost, currentCost])
: currentCost
- : (currentCost ?? legacyCost ?? zeroRegionalMoney(CURRENT_CINDY_REGION));
+ : (currentCost ?? legacyCost ?? zeroUsageMoney());
const legacyEstimate =
row.estimatedValueUsd > 0
- ? regionalizeUsd(row.estimatedValueUsd, CURRENT_CINDY_REGION, 'legacy-usd', 'value-estimate')
+ ? usdMoney(row.estimatedValueUsd, 'value-estimate', 'legacy-usd')
: undefined;
const currentEstimate =
row.costCurrency && row.estimatedValueAmount > 0
@@ -735,7 +734,7 @@ export function scheduleRunToCamel(row: ScheduleRunRow): ScheduleRun {
: currentEstimate
: (currentEstimate ??
legacyEstimate ??
- zeroRegionalMoney(CURRENT_CINDY_REGION, 'value-estimate'));
+ zeroUsageMoney('value-estimate'));
return {
id: row.id,
scheduleId: row.scheduleId,
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts
index 12547627fb..9b8066ef26 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts
@@ -6,8 +6,7 @@ import { registerMakerStatusHandlers } from '../statusHandlers';
import { registerMakerUsageHandlers } from '../usageHandlers';
import { CodexRateLimitResetRejectedError } from '../../usage/codexRateLimitReset';
import { IpcHarness } from './helpers/ipcHarness';
-import { zeroRegionalMoney } from '../../../shared/regionalMoney';
-import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';
+import { zeroUsageMoney } from '../../../shared/regionalMoney';
function createMakerStub(methods: Partial<Maker>): Maker {
return methods as Maker;
@@ -329,13 +328,10 @@ describe('maker usage IPC handlers', () => {
models: [],
streak: { current: 0, longest: 0 },
totals: {
- today: zeroRegionalMoney(CURRENT_CINDY_REGION),
- last30Days: zeroRegionalMoney(CURRENT_CINDY_REGION),
- last30DaysWithEstimatedValue: zeroRegionalMoney(CURRENT_CINDY_REGION),
- last30DaysEstimatedValue: zeroRegionalMoney(
- CURRENT_CINDY_REGION,
- 'value-estimate',
- ),
+ today: zeroUsageMoney(),
+ last30Days: zeroUsageMoney(),
+ last30DaysWithEstimatedValue: zeroUsageMoney(),
+ last30DaysEstimatedValue: zeroUsageMoney('value-estimate'),
todayTokens: 0,
last30DaysTokens: 0,
},
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index c61fb84d59..1b4b6b46c3 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -266,9 +266,7 @@ import { computeModelUsageDeltas, type ModelUsageCumulative, type ModelUsageDelt
import { claudeSubscriptionUsageModelKey, codexApiUsageModelKey, codexSubscriptionUsageModelKey } from '../usage/usageHistory.js';
import { buildClaudeTurnUsageDetails, computePriceQuoteTurnMoney, estimateClaudeSubscriptionTurnValue, isAnthropicModel, normalizeModelIdForPricing, resolveClaudeTurnCostSinks, type BillingRoute } from '../usage/turnCostCalculator.js';
import { CHATGPT_MODEL_PREFIX, XAI_MODEL_PREFIX, isSubscriptionDirectModel } from '../../shared/subscriptionModels.js';
-import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
-import { regionalizeModelPriceQuote } from '../../shared/modelPriceQuote.js';
-import { addRegionalMoney, regionalizeUsd, type RegionalMoney } from '../../shared/regionalMoney.js';
+import { addRegionalMoney, usdMoney, type RegionalMoney } from '../../shared/regionalMoney.js';
import { triggerClaudeSubscriptionUsageRefresh, triggerCodexAccountUsageRefresh } from './usage.js';
import {
rebroadcastCodexTodayUsage,
@@ -2777,7 +2775,6 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
{
providerId: sessionProviderForBilling,
billingRoute,
- region: CURRENT_CINDY_REGION,
},
);
// 按模型记账 (首页仪表盘"按模型拆分"): 写归一化裸 id, 与 codex 行 / 价格表对齐。
@@ -2838,19 +2835,11 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
for (const m of perModel) {
if (m.source !== 'subscription') continue;
const quote = getSubscriptionDirectValuePrice(m.model);
- const value = computePriceQuoteTurnMoney(
- m.deltas,
- quote
- ? regionalizeModelPriceQuote(quote, CURRENT_CINDY_REGION)
- : undefined,
- );
+ const value = computePriceQuoteTurnMoney(m.deltas, quote ?? undefined);
if (value?.amount) estimatedValues.push(value);
}
if (isClaudeSubscriptionSession) {
- const claudeEstimated = estimateClaudeSubscriptionTurnValue(
- perModel,
- CURRENT_CINDY_REGION,
- );
+ const claudeEstimated = estimateClaudeSubscriptionTurnValue(perModel);
if (claudeEstimated?.amount) estimatedValues.push(claudeEstimated);
}
const turnEstimatedValue =
@@ -2898,10 +2887,8 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
? 'provider-api'
: 'unknown';
if (route === 'subscription' || route === 'xd-gateway') return;
- const money = regionalizeUsd(
+ const money = usdMoney(
rawDelta * getCodexBudgetEffectiveCostMultiplier(resolvedModel),
- CURRENT_CINDY_REGION,
- 'fixed-fx',
);
const turnUsageDetails = buildClaudeTurnUsageDetails(doneData?.usage, undefined, resolvedModel);
recordTurnSpend(money);
@@ -3019,9 +3006,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
: getModelPriceQuote(pricing, 'xd', pricingModel);
const money = computePriceQuoteTurnMoney(
codexUsageToTokens(u),
- price
- ? regionalizeModelPriceQuote(price, CURRENT_CINDY_REGION)
- : undefined,
+ price ?? undefined,
);
if (!isSubscriptionValue && money) {
await recordModelTurnUsage({
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runCostLedger.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runCostLedger.test.ts
index 908df50580..0e1708842c 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runCostLedger.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runCostLedger.test.ts
@@ -36,14 +36,14 @@ function structuredMeta(
}
describe('computeScheduleRunCostDeltas', () => {
- it('旧 USD 真实费用按当前 CN 区域投影后累计到对应 run', () => {
+ it('旧 USD 真实费用保持 USD 原值累计到对应 run', () => {
expect(computeScheduleRunCostDeltas({}, meta('run-1', 0.42))).toEqual([
{
runId: 'run-1',
- costAmountDelta: 2.814,
+ costAmountDelta: 0.42,
estimatedValueAmountDelta: 0,
- currency: 'CNY',
- approximate: true,
+ currency: 'USD',
+ approximate: false,
},
]);
});
@@ -57,28 +57,28 @@ describe('computeScheduleRunCostDeltas', () => {
const [delta] = computeScheduleRunCostDeltas(meta('run-1', 0.42, true), meta('run-1', 0.4));
expect(delta).toMatchObject({
runId: 'run-1',
- currency: 'CNY',
- approximate: true,
+ currency: 'USD',
+ approximate: false,
});
- expect(delta.costAmountDelta).toBeCloseTo(2.68);
- expect(delta.estimatedValueAmountDelta).toBeCloseTo(-2.814);
+ expect(delta.costAmountDelta).toBeCloseTo(0.4);
+ expect(delta.estimatedValueAmountDelta).toBeCloseTo(-0.42);
});
it('归因 runId 修正时从旧 run 扣除并写入新 run', () => {
expect(computeScheduleRunCostDeltas(meta('run-old', 0.42), meta('run-new', 0.42))).toEqual([
{
runId: 'run-old',
- costAmountDelta: -2.814,
+ costAmountDelta: -0.42,
estimatedValueAmountDelta: 0,
- currency: 'CNY',
+ currency: 'USD',
approximate: false,
},
{
runId: 'run-new',
- costAmountDelta: 2.814,
+ costAmountDelta: 0.42,
estimatedValueAmountDelta: 0,
- currency: 'CNY',
- approximate: true,
+ currency: 'USD',
+ approximate: false,
},
]);
});
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts
index 1ef403de5e..dfb5bee4aa 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts
@@ -19,34 +19,33 @@ import { DrizzleScheduleStorage, type SchedulerDrizzleDb } from '../storage';
function actualMoneyFromLegacyUsd(amountUsd: number) {
return {
- amount: expect.closeTo(amountUsd * 6.7, 10),
- currency: 'CNY' as const,
- approximate: true,
+ amount: expect.closeTo(amountUsd, 10),
+ currency: 'USD' as const,
+ approximate: false,
kind: 'actual-cost' as const,
- estimateReasons: ['fixed-fx', 'legacy-usd'] as const,
};
}
function estimatedMoneyFromLegacyUsd(amountUsd: number) {
return {
- amount: expect.closeTo(amountUsd * 6.7, 10),
- currency: 'CNY' as const,
+ amount: expect.closeTo(amountUsd, 10),
+ currency: 'USD' as const,
approximate: true,
kind: 'value-estimate' as const,
- estimateReasons: ['fixed-fx', 'legacy-usd', 'subscription-value'] as const,
+ estimateReasons: ['subscription-value'] as const,
};
}
const ZERO_ACTUAL_MONEY = {
amount: 0,
- currency: 'CNY' as const,
+ currency: 'USD' as const,
approximate: false,
kind: 'actual-cost' as const,
};
const ZERO_ESTIMATED_MONEY = {
amount: 0,
- currency: 'CNY' as const,
+ currency: 'USD' as const,
approximate: true,
kind: 'value-estimate' as const,
estimateReasons: ['subscription-value'] as const,
@@ -369,10 +368,14 @@ describe('DrizzleScheduleStorage (in-memory)', () => {
expect(summaries.get('sch-a')).toMatchObject({
totalMoney: actualMoneyFromLegacyUsd(0.4),
totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,
+ totalCostUsd: expect.closeTo(0.4, 10),
+ totalEstimatedValueUsd: 0,
});
expect(summaries.get('sch-b')).toMatchObject({
totalMoney: actualMoneyFromLegacyUsd(0.2),
totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,
+ totalCostUsd: expect.closeTo(0.2, 10),
+ totalEstimatedValueUsd: 0,
});
expect(await harness.storage.listRuns('sch-a')).toEqual([
expect.objectContaining({
@@ -698,12 +701,16 @@ describe('DrizzleScheduleStorage (in-memory)', () => {
scheduleId: schedule.id,
totalMoney: actualMoneyFromLegacyUsd(0.75),
totalEstimatedValueMoney: estimatedMoneyFromLegacyUsd(9.99),
+ totalCostUsd: expect.closeTo(0.75, 10),
+ totalEstimatedValueUsd: expect.closeTo(9.99, 10),
sessionCount: 1,
sessions: [
{
sessionId: 'sess-bound',
totalMoney: actualMoneyFromLegacyUsd(0.75),
totalEstimatedValueMoney: estimatedMoneyFromLegacyUsd(9.99),
+ totalCostUsd: expect.closeTo(0.75, 10),
+ totalEstimatedValueUsd: expect.closeTo(9.99, 10),
},
],
},
@@ -744,12 +751,16 @@ describe('DrizzleScheduleStorage (in-memory)', () => {
scheduleId: schedule.id,
totalMoney: ZERO_ACTUAL_MONEY,
totalEstimatedValueMoney: estimatedMoneyFromLegacyUsd(0.29),
+ totalCostUsd: 0,
+ totalEstimatedValueUsd: expect.closeTo(0.29, 10),
sessionCount: 1,
sessions: [
{
sessionId: 'sess-subscription',
totalMoney: ZERO_ACTUAL_MONEY,
totalEstimatedValueMoney: estimatedMoneyFromLegacyUsd(0.29),
+ totalCostUsd: 0,
+ totalEstimatedValueUsd: expect.closeTo(0.29, 10),
},
],
},
@@ -790,12 +801,16 @@ describe('DrizzleScheduleStorage (in-memory)', () => {
scheduleId: schedule.id,
totalMoney: actualMoneyFromLegacyUsd(0.42),
totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,
+ totalCostUsd: expect.closeTo(0.42, 10),
+ totalEstimatedValueUsd: 0,
sessionCount: 1,
sessions: [
{
sessionId: 'sess-api',
totalMoney: actualMoneyFromLegacyUsd(0.42),
totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,
+ totalCostUsd: expect.closeTo(0.42, 10),
+ totalEstimatedValueUsd: 0,
},
],
},
@@ -830,12 +845,16 @@ describe('DrizzleScheduleStorage (in-memory)', () => {
scheduleId: schedule.id,
totalMoney: actualMoneyFromLegacyUsd(0.42),
totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,
+ totalCostUsd: expect.closeTo(0.42, 10),
+ totalEstimatedValueUsd: 0,
sessionCount: 1,
sessions: [
{
sessionId: 'sess-direct',
totalMoney: actualMoneyFromLegacyUsd(0.42),
totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,
+ totalCostUsd: expect.closeTo(0.42, 10),
+ totalEstimatedValueUsd: 0,
},
],
},
@@ -925,12 +944,16 @@ describe('DrizzleScheduleStorage (in-memory)', () => {
scheduleId: schedule.id,
totalMoney: actualMoneyFromLegacyUsd(0.6),
totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,
+ totalCostUsd: expect.closeTo(0.6, 10),
+ totalEstimatedValueUsd: 0,
sessionCount: 1,
sessions: [
{
sessionId: 'sess-mixed-ledger',
totalMoney: actualMoneyFromLegacyUsd(0.6),
totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,
+ totalCostUsd: expect.closeTo(0.6, 10),
+ totalEstimatedValueUsd: 0,
},
],
},
@@ -963,11 +986,10 @@ describe('DrizzleScheduleStorage (in-memory)', () => {
await recordScheduleRunCostDirect({
runId: 'run-direct-only-snapshot',
money: {
- amount: 4.02,
- currency: 'CNY',
- approximate: true,
+ amount: 0.6,
+ currency: 'USD',
+ approximate: false,
kind: 'actual-cost',
- estimateReasons: ['fixed-fx'],
},
});
harness.db.run(sql`
@@ -991,12 +1013,16 @@ describe('DrizzleScheduleStorage (in-memory)', () => {
scheduleId: schedule.id,
totalMoney: actualMoneyFromLegacyUsd(1),
totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,
+ totalCostUsd: expect.closeTo(1, 10),
+ totalEstimatedValueUsd: 0,
sessionCount: 1,
sessions: [
{
sessionId: 'sess-direct-only',
totalMoney: actualMoneyFromLegacyUsd(1),
totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,
+ totalCostUsd: expect.closeTo(1, 10),
+ totalEstimatedValueUsd: 0,
},
],
},
@@ -1031,6 +1057,8 @@ describe('DrizzleScheduleStorage (in-memory)', () => {
scheduleId: schedule.id,
totalMoney: ZERO_ACTUAL_MONEY,
totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,
+ totalCostUsd: 0,
+ totalEstimatedValueUsd: 0,
hasUnavailableCost: true,
sessionCount: 1,
sessions: [
@@ -1038,6 +1066,8 @@ describe('DrizzleScheduleStorage (in-memory)', () => {
sessionId: 'sess-unavailable',
totalMoney: ZERO_ACTUAL_MONEY,
totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,
+ totalCostUsd: 0,
+ totalEstimatedValueUsd: 0,
},
],
},
@@ -1066,6 +1096,8 @@ describe('DrizzleScheduleStorage (in-memory)', () => {
scheduleId: schedule.id,
totalMoney: ZERO_ACTUAL_MONEY,
totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,
+ totalCostUsd: 0,
+ totalEstimatedValueUsd: 0,
sessionCount: 0,
sessions: [],
},
@@ -1098,7 +1130,7 @@ describe('DrizzleScheduleStorage (in-memory)', () => {
VALUES
('mixed-user', 'mixed-user', 'sess-legacy', 'user', '{}', '{"origin":{"kind":"scheduler","scheduleId":"sch-mixed","scheduleName":"legacy task"}}', 40),
('mixed-assistant', 'mixed-assistant', 'sess-legacy', 'assistant', '{}', '{"turnCostUsd":1.25}', 50),
- ('structured-assistant', 'structured-assistant', 'sess-legacy', 'assistant', '{}', '{"turnCost":{"amount":5,"currency":"CNY","approximate":false,"kind":"actual-cost"}}', 52),
+ ('structured-assistant', 'structured-assistant', 'sess-legacy', 'assistant', '{}', '{"turnCost":{"amount":5,"currency":"USD","approximate":false,"kind":"actual-cost"}}', 52),
('manual-user', 'manual-user', 'sess-legacy', 'user', '{}', NULL, 55),
('manual-assistant', 'manual-assistant', 'sess-legacy', 'assistant', '{}', '{"turnCostUsd":2}', 60)
`);
@@ -1108,18 +1140,22 @@ describe('DrizzleScheduleStorage (in-memory)', () => {
scheduleId: schedule.id,
totalMoney: {
...actualMoneyFromLegacyUsd(2.25),
- amount: expect.closeTo(2.25 * 6.7 + 5, 10),
+ amount: expect.closeTo(2.25 + 5, 10),
},
totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,
+ totalCostUsd: expect.closeTo(2.25 + 5, 10),
+ totalEstimatedValueUsd: 0,
sessionCount: 1,
sessions: [
{
sessionId: 'sess-legacy',
totalMoney: {
...actualMoneyFromLegacyUsd(2.25),
- amount: expect.closeTo(2.25 * 6.7 + 5, 10),
+ amount: expect.closeTo(2.25 + 5, 10),
},
totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,
+ totalCostUsd: expect.closeTo(2.25 + 5, 10),
+ totalEstimatedValueUsd: 0,
},
],
},
@@ -1159,12 +1195,16 @@ describe('DrizzleScheduleStorage (in-memory)', () => {
scheduleId: schedule.id,
totalMoney: actualMoneyFromLegacyUsd(1.5),
totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,
+ totalCostUsd: expect.closeTo(1.5, 10),
+ totalEstimatedValueUsd: 0,
sessionCount: 1,
sessions: [
{
sessionId: 'sess-unlinked',
totalMoney: actualMoneyFromLegacyUsd(1.5),
totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,
+ totalCostUsd: expect.closeTo(1.5, 10),
+ totalEstimatedValueUsd: 0,
},
],
},
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/storage.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/storage.test.ts
index 655376d8e3..db16fb9674 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/storage.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/storage.test.ts
@@ -302,18 +302,17 @@ describe('scheduleRunToCamel / scheduleRunCreateToRow', () => {
expect(back).toEqual({
...original,
costMoney: {
- amount: 2.814,
- currency: 'CNY',
- approximate: true,
+ amount: 0.42,
+ currency: 'USD',
+ approximate: false,
kind: 'actual-cost',
- estimateReasons: ['fixed-fx', 'legacy-usd'],
},
estimatedValueMoney: {
- amount: expect.closeTo(1.273, 10),
- currency: 'CNY',
+ amount: 0.19,
+ currency: 'USD',
approximate: true,
kind: 'value-estimate',
- estimateReasons: ['fixed-fx', 'legacy-usd', 'subscription-value'],
+ estimateReasons: ['legacy-usd', 'subscription-value'],
},
});
});
diff --git a/apps/desktop/src/main/scheduler-host/runCostLedger.ts b/apps/desktop/src/main/scheduler-host/runCostLedger.ts
index 4722db9e14..b7fc29190f 100644
--- a/apps/desktop/src/main/scheduler-host/runCostLedger.ts
+++ b/apps/desktop/src/main/scheduler-host/runCostLedger.ts
@@ -9,8 +9,10 @@ import { eq, sql } from 'drizzle-orm';
import { getDbClient } from '../localDb/client/current';
import { scheduleRuns } from '../localDb/schema';
-import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
-import { normalizeRegionalMoney, regionalizeLegacyUsd } from '../../shared/regionalMoney.js';
+import { createLogger } from '../logger';
+import { legacyUsdMoney, normalizeRegionalMoney } from '../../shared/regionalMoney.js';
+
+const log = createLogger('runCostLedger');
interface RunCostEntry {
runId: string;
@@ -47,7 +49,7 @@ function runCostEntry(meta: Record<string, unknown>): RunCostEntry | null {
const money =
normalizeRegionalMoney(meta.turnCost) ??
(finitePositive(meta.turnCostUsd) > 0
- ? regionalizeLegacyUsd(finitePositive(meta.turnCostUsd), CURRENT_CINDY_REGION)
+ ? legacyUsdMoney(finitePositive(meta.turnCostUsd))
: undefined);
if (!money || money.amount <= 0) return null;
const isEstimate = meta.turnCostIsEstimate === true || money.kind === 'value-estimate';
@@ -67,25 +69,26 @@ export function computeScheduleRunCostDeltas(
previous: Record<string, unknown>,
next: Record<string, unknown>,
): ScheduleRunCostDelta[] {
+ // 按 (runId, 币种) 分桶:同一 run 的消息在补丁前后换币种(device-link 旧对端 /
+ // 历史数据重写)时,旧币种减、新币种加各成一条 delta,由 SQL 侧的 CASE 币种
+ // 守卫逐条裁决——绝不 throw,抛异常会让整个差值应用被跳过。
const changes = new Map<string, ScheduleRunCostDelta>();
const apply = (entry: RunCostEntry | null, direction: 1 | -1) => {
if (!entry) return;
- const current = changes.get(entry.runId) ?? {
+ const key = `${entry.runId}\u0000${entry.currency}`;
+ const current = changes.get(key) ?? {
runId: entry.runId,
costAmountDelta: 0,
estimatedValueAmountDelta: 0,
currency: entry.currency,
approximate: false,
};
- if (current.currency !== entry.currency) {
- throw new Error('schedule run cost currency mismatch');
- }
current.costAmountDelta += direction * entry.costAmount;
current.estimatedValueAmountDelta += direction * entry.estimatedValueAmount;
// 这里是消息快照替换,不是新费用累加。只让 next 决定新的近似状态,
// 避免 approximate 消息被精确金额替换后永久保持 true。
if (direction === 1) current.approximate = entry.approximate;
- changes.set(entry.runId, current);
+ changes.set(key, current);
};
apply(runCostEntry(previous), -1);
apply(runCostEntry(next), 1);
@@ -105,6 +108,10 @@ export async function applyScheduleRunCostMetaChange(
if (changes.length === 0) return;
const db = getDbClient().drizzle;
for (const change of changes) {
+ // 单币种快照:币种守卫在同一条 UPDATE 里用 CASE 表达(先查再写有 TOCTOU
+ // 窗口)。币种冲突的 delta 原子地弃掉——金额、币种、约值标记全部保持原样,
+ // 绝不能只保金额却改写 costCurrency(那会把旧币种数值错标成新币种)。
+ const sameCurrency = sql`(${scheduleRuns.costCurrency} IS NULL OR ${scheduleRuns.costCurrency} = ${change.currency})`;
await db
.update(scheduleRuns)
.set({
@@ -113,22 +120,29 @@ export async function applyScheduleRunCostMetaChange(
// otherwise a successful message update would make a later read
// unable to tell whether the snapshot already contains that segment.
costAmount: sql<number>`CASE
+ WHEN NOT ${sameCurrency} THEN ${scheduleRuns.costAmount}
WHEN ${scheduleRuns.costAttribution} = 'direct'
THEN ${scheduleRuns.costAmount}
ELSE MAX(0, ${scheduleRuns.costAmount} + ${change.costAmountDelta})
END`,
estimatedValueAmount: sql<number>`CASE
+ WHEN NOT ${sameCurrency} THEN ${scheduleRuns.estimatedValueAmount}
WHEN ${scheduleRuns.costAttribution} = 'direct'
THEN ${scheduleRuns.estimatedValueAmount}
ELSE MAX(0, ${scheduleRuns.estimatedValueAmount} + ${change.estimatedValueAmountDelta})
END`,
- costCurrency: change.currency,
+ costCurrency: sql`CASE
+ WHEN NOT ${sameCurrency} THEN ${scheduleRuns.costCurrency}
+ ELSE ${change.currency}
+ END`,
costIsApproximate: sql`CASE
+ WHEN NOT ${sameCurrency} THEN ${scheduleRuns.costIsApproximate}
WHEN ${scheduleRuns.costAttribution} IN ('direct', 'mixed')
THEN ${scheduleRuns.costIsApproximate} OR ${change.approximate ? 1 : 0}
ELSE ${change.approximate ? 1 : 0}
END`,
costAttribution: sql<string>`CASE
+ WHEN NOT ${sameCurrency} THEN ${scheduleRuns.costAttribution}
WHEN ${scheduleRuns.costAttribution} IN ('direct', 'mixed')
THEN ${scheduleRuns.costAttribution}
ELSE 'exact'
@@ -169,24 +183,30 @@ export async function recordScheduleRunCostDirect(args: {
.limit(1);
if (!run) return null;
if (run.costCurrency && run.costCurrency !== money.currency) {
- throw new Error('schedule run cost currency mismatch');
+ // 观察到冲突只 warn 留痕;强制语义靠下方 UPDATE 内的 CASE 守卫(先查
+ // 再写有 TOCTOU 窗口),冲突段原子地弃掉,不 throw 打断调度记账管道。
+ log.warn(
+ `schedule run ${runId} currency conflict: keeping ${run.costCurrency}, dropping ${money.currency} segment`,
+ );
}
+ const sameCurrency = sql`(${scheduleRuns.costCurrency} IS NULL OR ${scheduleRuns.costCurrency} = ${money.currency})`;
const result = await db
.update(scheduleRuns)
.set({
- costAmount: sql<number>`MAX(0, ${scheduleRuns.costAmount} + ${isEstimate ? 0 : amount})`,
- estimatedValueAmount: sql<number>`MAX(0, ${scheduleRuns.estimatedValueAmount} + ${isEstimate ? amount : 0})`,
- costCurrency: money.currency,
- costIsApproximate: sql`${scheduleRuns.costIsApproximate} OR ${
+ costAmount: sql<number>`CASE WHEN ${sameCurrency} THEN MAX(0, ${scheduleRuns.costAmount} + ${isEstimate ? 0 : amount}) ELSE ${scheduleRuns.costAmount} END`,
+ estimatedValueAmount: sql<number>`CASE WHEN ${sameCurrency} THEN MAX(0, ${scheduleRuns.estimatedValueAmount} + ${isEstimate ? amount : 0}) ELSE ${scheduleRuns.estimatedValueAmount} END`,
+ costCurrency: sql`CASE WHEN ${sameCurrency} THEN ${money.currency} ELSE ${scheduleRuns.costCurrency} END`,
+ costIsApproximate: sql`CASE WHEN ${sameCurrency} THEN (${scheduleRuns.costIsApproximate} OR ${
!isEstimate && money.approximate ? 1 : 0
- }`,
+ }) ELSE ${scheduleRuns.costIsApproximate} END`,
// A confirmed zero-cost segment must not downgrade a run that already
// contains an exact segment; otherwise later summary reads lose the
// accumulated direct cost.
costAttribution:
isEstimate || amount > 0
? sql<string>`CASE
+ WHEN NOT ${sameCurrency} THEN ${scheduleRuns.costAttribution}
WHEN ${scheduleRuns.costAttribution} = 'mixed' THEN 'mixed'
WHEN ${scheduleRuns.costAttribution} = 'exact' THEN 'mixed'
ELSE 'direct'
diff --git a/apps/desktop/src/main/scheduler-host/storage.ts b/apps/desktop/src/main/scheduler-host/storage.ts
index be7b9284bc..69b92b07fb 100644
--- a/apps/desktop/src/main/scheduler-host/storage.ts
+++ b/apps/desktop/src/main/scheduler-host/storage.ts
@@ -30,15 +30,14 @@ import {
scheduleRunCreateToRow,
scheduleRunPatchToRow,
} from '../localDb/mapper';
-import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
import {
addRegionalMoney,
asValueEstimateMoney,
+ DEFAULT_USAGE_CURRENCY,
+ legacyUsdMoney,
normalizeRegionalMoney,
- regionalCurrencyForRegion,
- regionalizeLegacyUsd,
type RegionalMoney,
- zeroRegionalMoney,
+ zeroUsageMoney,
} from '../../shared/regionalMoney.js';
export type SchedulerDrizzleDb = BetterSQLite3Database<typeof schema>;
@@ -80,6 +79,25 @@ export interface ScheduleSessionCostSummary {
interface ScheduleMoneyValues {
costValues: RegionalMoney[];
estimatedValueValues: RegionalMoney[];
+ /** 最新一笔金额的币种(按时间戳取最大)——汇总聚合的偏好币种。 */
+ latestCurrency?: RegionalMoney['currency'];
+ latestCurrencyAt?: number;
+}
+
+/**
+ * 记录「当前账本币种」:跨币种切换的 schedule 汇总必须偏好最新片段的币种,
+ * 静态 USD 偏好会让任意历史 USD 片段把切换后的新币种 run 整段挤出汇总。
+ */
+function noteLatestCurrency(
+ values: ScheduleMoneyValues,
+ money: RegionalMoney | null | undefined,
+ at: number,
+): void {
+ if (!money || money.amount <= 0) return;
+ if (values.latestCurrencyAt === undefined || at >= values.latestCurrencyAt) {
+ values.latestCurrencyAt = at;
+ values.latestCurrency = money.currency;
+ }
}
interface ScheduleTurnCostState extends ScheduleMoneyValues {
@@ -104,11 +122,22 @@ function emptyScheduleTurnCostState(): ScheduleTurnCostState {
};
}
+/**
+ * 与 shared addCompatibleRegionalMoney 同语义的本地版(带显式 preferred 参数
+ * 的调用点较多故保留):preferred 币种没有任何值时回退第一个 actual-cost 值
+ * 的币种——全 CNY(来源真声明)账本绝不能被 USD 偏好清零。
+ */
function addCompatibleRegionalMoney(
values: readonly RegionalMoney[],
- currency: RegionalMoney['currency'] = regionalCurrencyForRegion(CURRENT_CINDY_REGION),
+ currency: RegionalMoney['currency'] = DEFAULT_USAGE_CURRENCY,
): RegionalMoney | null {
- const compatible = values.filter((value) => value.currency === currency);
+ if (values.length === 0) return null;
+ const actualValues = values.filter((value) => value.kind === 'actual-cost');
+ const candidates = actualValues.length > 0 ? actualValues : values;
+ const effective =
+ candidates.find((value) => value.currency === currency)?.currency ??
+ candidates[0].currency;
+ const compatible = values.filter((value) => value.currency === effective);
return compatible.length > 0 ? addRegionalMoney(compatible) : null;
}
@@ -224,7 +253,7 @@ function turnCostFromAgentMeta(agentMeta: string | null): {
typeof parsed.turnCostUsd === 'number' &&
Number.isFinite(parsed.turnCostUsd) &&
parsed.turnCostUsd > 0
- ? regionalizeLegacyUsd(parsed.turnCostUsd, CURRENT_CINDY_REGION)
+ ? legacyUsdMoney(parsed.turnCostUsd)
: undefined;
const money = structured ?? legacy;
if (!money || money.amount <= 0) {
@@ -526,12 +555,12 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
addCompatibleRegionalMoney(
costValues,
run.costMoney?.currency,
- ) ?? zeroRegionalMoney(CURRENT_CINDY_REGION),
+ ) ?? zeroUsageMoney(),
estimatedValueMoney:
addCompatibleRegionalMoney(
estimatedValues,
run.estimatedValueMoney?.currency,
- ) ?? zeroRegionalMoney(CURRENT_CINDY_REGION, 'value-estimate'),
+ ) ?? zeroUsageMoney('value-estimate'),
costAttribution: 'exact',
};
}
@@ -542,10 +571,10 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
...run,
costMoney:
addCompatibleRegionalMoney(persisted.costValues) ??
- zeroRegionalMoney(CURRENT_CINDY_REGION),
+ zeroUsageMoney(),
estimatedValueMoney:
addCompatibleRegionalMoney(persisted.estimatedValues) ??
- zeroRegionalMoney(CURRENT_CINDY_REGION, 'value-estimate'),
+ zeroUsageMoney('value-estimate'),
costAttribution: 'exact',
};
});
@@ -778,6 +807,8 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
if (turnCost.estimatedValueMoney) {
entry.estimatedValueValues.push(turnCost.estimatedValueMoney);
}
+ noteLatestCurrency(entry, turnCost.costMoney, row.createdAt);
+ noteLatestCurrency(entry, turnCost.estimatedValueMoney, row.createdAt);
const sessionCost = entry.sessionCosts.get(row.sessionId) ?? emptyScheduleMoneyValues();
if (turnCost.costMoney) {
sessionCost.costValues.push(turnCost.costMoney);
@@ -785,6 +816,8 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
if (turnCost.estimatedValueMoney) {
sessionCost.estimatedValueValues.push(turnCost.estimatedValueMoney);
}
+ noteLatestCurrency(sessionCost, turnCost.costMoney, row.createdAt);
+ noteLatestCurrency(sessionCost, turnCost.estimatedValueMoney, row.createdAt);
entry.sessionCosts.set(row.sessionId, sessionCost);
bySchedule.set(attributedScheduleId, entry);
}
@@ -797,11 +830,14 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
sessionId: string | undefined,
costMoney: RegionalMoney | null,
estimatedValueMoney: RegionalMoney | null,
+ at: number,
): void => {
if (costMoney && costMoney.amount > 0) entry.costValues.push(costMoney);
if (estimatedValueMoney && estimatedValueMoney.amount > 0) {
entry.estimatedValueValues.push(estimatedValueMoney);
}
+ noteLatestCurrency(entry, costMoney, at);
+ noteLatestCurrency(entry, estimatedValueMoney, at);
if (!sessionId) return;
entry.sessionIds.add(sessionId);
const sessionCost = entry.sessionCosts.get(sessionId) ?? emptyScheduleMoneyValues();
@@ -809,6 +845,8 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
if (estimatedValueMoney && estimatedValueMoney.amount > 0) {
sessionCost.estimatedValueValues.push(estimatedValueMoney);
}
+ noteLatestCurrency(sessionCost, costMoney, at);
+ noteLatestCurrency(sessionCost, estimatedValueMoney, at);
entry.sessionCosts.set(sessionId, sessionCost);
};
const remainingMoney = (
@@ -832,7 +870,7 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
if (messageCostRunIds.has(run.id)) continue;
const entry = bySchedule.get(run.scheduleId) ?? emptyScheduleTurnCostState();
entry.hasUnavailableCost = true;
- appendRunMoney(entry, run.sessionId, null, null);
+ appendRunMoney(entry, run.sessionId, null, null, run.firedAt);
bySchedule.set(run.scheduleId, entry);
continue;
}
@@ -842,7 +880,7 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
!messageCostRunIds.has(run.id)
) {
const entry = bySchedule.get(run.scheduleId) ?? emptyScheduleTurnCostState();
- appendRunMoney(entry, run.sessionId, null, null);
+ appendRunMoney(entry, run.sessionId, null, null, run.firedAt);
bySchedule.set(run.scheduleId, entry);
continue;
}
@@ -860,7 +898,7 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
messageCost?.estimatedValueValues ?? [],
);
const entry = bySchedule.get(run.scheduleId) ?? emptyScheduleTurnCostState();
- appendRunMoney(entry, run.sessionId, costMoney, estimatedValueMoney);
+ appendRunMoney(entry, run.sessionId, costMoney, estimatedValueMoney, run.firedAt);
bySchedule.set(run.scheduleId, entry);
continue;
}
@@ -873,6 +911,7 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
run.sessionId,
run.costMoney ?? null,
run.estimatedValueMoney ?? null,
+ run.firedAt,
);
bySchedule.set(run.scheduleId, entry);
}
@@ -885,7 +924,7 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
entry.sessionIds.add(session.id);
const cost = Number(session.totalCostUsd ?? 0);
if (Number.isFinite(cost) && cost > 0) {
- const projectedLegacyCost = regionalizeLegacyUsd(cost, CURRENT_CINDY_REGION);
+ const projectedLegacyCost = legacyUsdMoney(cost);
const alreadyCountedMessageCost = legacyMessageCostBySessionId.get(session.id) ?? 0;
const legacyCost = Math.max(0, projectedLegacyCost.amount - alreadyCountedMessageCost);
const legacyMoney: RegionalMoney = {
@@ -894,10 +933,12 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
};
if (legacyCost > 0) {
entry.costValues.push(legacyMoney);
+ noteLatestCurrency(entry, legacyMoney, 0);
}
const sessionCost = entry.sessionCosts.get(session.id) ?? emptyScheduleMoneyValues();
if (legacyCost > 0) {
sessionCost.costValues.push(legacyMoney);
+ noteLatestCurrency(sessionCost, legacyMoney, 0);
}
entry.sessionCosts.set(session.id, sessionCost);
}
@@ -906,11 +947,13 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
return [...bySchedule.entries()].map(([scheduleId, summary]) => {
const totalMoney =
- addCompatibleRegionalMoney(summary.costValues) ??
- zeroRegionalMoney(CURRENT_CINDY_REGION);
+ addCompatibleRegionalMoney(summary.costValues, summary.latestCurrency) ??
+ zeroUsageMoney();
const totalEstimatedValueMoney =
- addCompatibleRegionalMoney(summary.estimatedValueValues) ??
- zeroRegionalMoney(CURRENT_CINDY_REGION, 'value-estimate');
+ addCompatibleRegionalMoney(
+ summary.estimatedValueValues,
+ summary.latestCurrency,
+ ) ?? zeroUsageMoney('value-estimate');
return {
scheduleId,
totalMoney,
@@ -925,11 +968,13 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
sessionCount: summary.sessionIds.size,
sessions: [...summary.sessionCosts.entries()].map(([sessionId, costs]) => {
const money =
- addCompatibleRegionalMoney(costs.costValues) ??
- zeroRegionalMoney(CURRENT_CINDY_REGION);
+ addCompatibleRegionalMoney(costs.costValues, costs.latestCurrency) ??
+ zeroUsageMoney();
const estimatedMoney =
- addCompatibleRegionalMoney(costs.estimatedValueValues) ??
- zeroRegionalMoney(CURRENT_CINDY_REGION, 'value-estimate');
+ addCompatibleRegionalMoney(
+ costs.estimatedValueValues,
+ costs.latestCurrency,
+ ) ?? zeroUsageMoney('value-estimate');
return {
sessionId,
totalMoney: money,
diff --git a/apps/desktop/src/main/sessionSpendBroadcaster.ts b/apps/desktop/src/main/sessionSpendBroadcaster.ts
index 18a38cb381..38ede9f630 100644
--- a/apps/desktop/src/main/sessionSpendBroadcaster.ts
+++ b/apps/desktop/src/main/sessionSpendBroadcaster.ts
@@ -25,12 +25,10 @@ import { sessions } from './localDb/schema';
import { getDbClient } from './localDb/client/current';
import { createLogger } from './logger';
import { tapWindowBroadcast } from './device-link/broadcast-tap.js';
-import { CURRENT_CINDY_REGION } from '../shared/brandRegion.js';
import {
addRegionalMoney,
+ legacyUsdMoney,
normalizeRegionalMoney,
- regionalCurrencyForRegion,
- regionalizeLegacyUsd,
type RegionalMoney,
} from '../shared/regionalMoney.js';
@@ -82,29 +80,17 @@ export async function recordSessionTurnSpend(
if (!sessionId) return;
const normalized = normalizeRegionalMoney(money);
if (!normalized || normalized.amount < 1e-10) return;
- if (normalized.currency !== regionalCurrencyForRegion(CURRENT_CINDY_REGION)) {
- log.warn('recordSessionTurnSpend rejected currency mismatch');
- return;
- }
try {
const db = getDbClient().drizzle;
- const existing = await db
- .select({ totalCostCurrency: sessions.totalCostCurrency })
- .from(sessions)
- .where(sql`${sessions.id} = ${sessionId}`)
- .get();
- if (
- existing?.totalCostCurrency &&
- existing.totalCostCurrency !== normalized.currency
- ) {
- log.warn('recordSessionTurnSpend rejected persisted currency mismatch');
- return;
- }
+ // 单币种累计列:币种守卫必须在同一条 UPDATE 里用 CASE 表达 —— 先查再写
+ // 有 TOCTOU 窗口,并发首写会把不同币种的裸数字加进同一列。冲突段原子地
+ // 弃掉(列保持原币种),下方回读后 warn 留痕。
+ const sameCurrency = sql`(${sessions.totalCostCurrency} IS NULL OR ${sessions.totalCostCurrency} = ${normalized.currency})`;
await db.update(sessions)
.set({
- totalCostAmount: sql`${sessions.totalCostAmount} + ${normalized.amount}`,
- totalCostCurrency: normalized.currency,
- totalCostIsApproximate: sql`${sessions.totalCostIsApproximate} OR ${normalized.approximate ? 1 : 0}`,
+ totalCostAmount: sql`CASE WHEN ${sameCurrency} THEN ${sessions.totalCostAmount} + ${normalized.amount} ELSE ${sessions.totalCostAmount} END`,
+ totalCostCurrency: sql`CASE WHEN ${sameCurrency} THEN ${normalized.currency} ELSE ${sessions.totalCostCurrency} END`,
+ totalCostIsApproximate: sql`CASE WHEN ${sameCurrency} THEN (${sessions.totalCostIsApproximate} OR ${normalized.approximate ? 1 : 0}) ELSE ${sessions.totalCostIsApproximate} END`,
})
.where(sql`${sessions.id} = ${sessionId}`)
.run();
@@ -118,10 +104,13 @@ export async function recordSessionTurnSpend(
.from(sessions)
.where(sql`${sessions.id} = ${sessionId}`)
.get();
- const legacy = regionalizeLegacyUsd(
- row?.totalCostUsd ?? 0,
- CURRENT_CINDY_REGION,
- );
+ if (
+ row?.totalCostCurrency &&
+ row.totalCostCurrency !== normalized.currency
+ ) {
+ log.warn('recordSessionTurnSpend dropped a conflicting-currency segment');
+ }
+ const legacy = legacyUsdMoney(row?.totalCostUsd ?? 0);
const current = normalizeRegionalMoney({
amount: row?.totalCostAmount ?? 0,
currency: row?.totalCostCurrency ?? normalized.currency,
diff --git a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts b/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
index e75814400b..a6b41d80c1 100644
--- a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
@@ -54,7 +54,6 @@ vi.mock('../../secrets/providerSecretStore', () => ({
}));
import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';
-import { gatewayCurrencyForRegion } from '../../../shared/regionalMoney';
import {
__resetModelPricingCacheForTesting,
clearGatewayModelPricing,
@@ -133,7 +132,7 @@ describe('gateway model pricing projection', () => {
'claude-sonnet-4': {
providerId: 'xd',
modelId: 'claude-sonnet-4',
- currency: gatewayCurrencyForRegion(CURRENT_CINDY_REGION),
+ currency: 'USD',
source: 'gateway',
approximate: false,
inputPerMtok: 3,
@@ -144,7 +143,7 @@ describe('gateway model pricing projection', () => {
'codex/gpt-5.5': {
providerId: 'xd',
modelId: 'codex/gpt-5.5',
- currency: gatewayCurrencyForRegion(CURRENT_CINDY_REGION),
+ currency: 'USD',
source: 'gateway',
approximate: false,
inputPerMtok: 0.3,
@@ -239,7 +238,7 @@ describe('pricing cache lifecycle', () => {
await vi.waitFor(async () => {
const raw = JSON.parse(await readFile(userDataPath('cache', 'model-pricing.json'), 'utf8'));
expect(raw).toMatchObject({
- version: 3,
+ version: 4,
scope: expectedScope(),
pricing,
});
@@ -256,7 +255,7 @@ describe('pricing cache lifecycle', () => {
await writeFile(
userDataPath('cache', 'model-pricing.json'),
JSON.stringify({
- version: 3,
+ version: 4,
scope: expectedScope(),
fetchedAt: Date.now(),
pricing: {
@@ -264,7 +263,7 @@ describe('pricing cache lifecycle', () => {
secret: {
providerId: 'xd',
modelId: 'secret',
- currency: gatewayCurrencyForRegion(CURRENT_CINDY_REGION),
+ currency: 'USD',
source: 'gateway',
approximate: false,
inputPerMtok: 1,
@@ -311,7 +310,7 @@ describe('pricing cache lifecycle', () => {
await writeFile(
userDataPath('cache', 'model-pricing.json'),
JSON.stringify({
- version: 3,
+ version: 4,
scope: expectedScope(),
fetchedAt: Date.now(),
pricing: {
diff --git a/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts b/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts
index d14cd2e82c..d88226889a 100644
--- a/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts
@@ -19,20 +19,17 @@ import type {
RegionalMoney,
} from '../../../shared/regionalMoney';
-const XD_GLOBAL: TurnPricingContext = {
+const XD_GATEWAY: TurnPricingContext = {
providerId: 'xd',
billingRoute: 'xd-gateway',
- region: 'global',
};
-const PROVIDER_CN: TurnPricingContext = {
+const PROVIDER_API: TurnPricingContext = {
providerId: 'anthropic',
billingRoute: 'provider-api',
- region: 'cn',
};
-const SUBSCRIPTION_GLOBAL: TurnPricingContext = {
+const SUBSCRIPTION: TurnPricingContext = {
providerId: 'anthropic',
billingRoute: 'subscription',
- region: 'global',
};
function quote(
@@ -172,7 +169,7 @@ describe('resolveTurnCost', () => {
},
sdkCostDelta: 5.553085,
pricing,
- context: XD_GLOBAL,
+ context: XD_GATEWAY,
});
const claude = resolveTurnCost({
rawModel: 'claude-opus-4-8[1m]',
@@ -184,7 +181,7 @@ describe('resolveTurnCost', () => {
},
sdkCostDelta: 99,
pricing,
- context: XD_GLOBAL,
+ context: XD_GATEWAY,
});
expect(gpt.source).toBe('gateway');
@@ -204,7 +201,7 @@ describe('resolveTurnCost', () => {
},
sdkCostDelta: 1.23,
pricing: {},
- context: XD_GLOBAL,
+ context: XD_GATEWAY,
});
expect(result.source).toBe('sdk-fallback');
expect(result.money).toMatchObject({
@@ -214,7 +211,7 @@ describe('resolveTurnCost', () => {
});
});
- it('XD missing price fallback applies the codex budget multiplier and regionalizes CN', () => {
+ it('XD missing price fallback applies the codex budget multiplier and keeps USD', () => {
const zeroTokens = {
inputTokens: 0,
outputTokens: 0,
@@ -226,24 +223,15 @@ describe('resolveTurnCost', () => {
tokens: zeroTokens,
sdkCostDelta: 10,
pricing: null,
- context: XD_GLOBAL,
+ context: XD_GATEWAY,
});
expect(codexFallback.source).toBe('sdk-fallback');
- expect(codexFallback.money?.amount).toBe(1.5);
-
- const cnFallback = resolveTurnCost({
- rawModel: 'unknown-model',
- tokens: zeroTokens,
- sdkCostDelta: 1,
- pricing: {},
- context: { ...XD_GLOBAL, region: 'cn' },
- });
- expect(cnFallback.money).toMatchObject({
- amount: 6.7,
- currency: 'CNY',
- approximate: true,
+ expect(codexFallback.money).toMatchObject({
+ amount: 1.5,
+ currency: 'USD',
+ approximate: false,
+ kind: 'actual-cost',
});
- expect(cnFallback.money?.estimateReasons).toContain('fixed-fx');
});
it('XD missing price with no SDK cost still resolves to null money', () => {
@@ -256,13 +244,13 @@ describe('resolveTurnCost', () => {
cacheCreateTokens: 0,
},
pricing: {},
- context: XD_GLOBAL,
+ context: XD_GATEWAY,
});
expect(result.source).toBe('sdk-fallback');
expect(result.money).toBeNull();
});
- it('provider API route keeps SDK USD fact and regionalizes it for CN', () => {
+ it('provider API route keeps the SDK USD fact exact — no regional conversion', () => {
const result = resolveTurnCost({
rawModel: 'claude-opus-4-8',
tokens: {
@@ -273,16 +261,15 @@ describe('resolveTurnCost', () => {
},
sdkCostDelta: 3,
pricing: catalog(quote('claude-opus-4-8', 99, 99)),
- context: PROVIDER_CN,
+ context: PROVIDER_API,
});
expect(result.source).toBe('sdk');
- expect(result.money).toMatchObject({
- amount: 20.1,
- currency: 'CNY',
- approximate: true,
+ expect(result.money).toEqual({
+ amount: 3,
+ currency: 'USD',
+ approximate: false,
kind: 'actual-cost',
});
- expect(result.money?.estimateReasons).toContain('fixed-fx');
});
it('codex provider SDK fallback applies the 15% multiplier once', () => {
@@ -296,7 +283,7 @@ describe('resolveTurnCost', () => {
},
sdkCostDelta: 10,
pricing: null,
- context: { ...PROVIDER_CN, region: 'global' },
+ context: PROVIDER_API,
});
expect(result.money?.amount).toBe(1.5);
});
@@ -312,7 +299,7 @@ describe('resolveTurnCost', () => {
},
sdkCostDelta: 5,
pricing: null,
- context: SUBSCRIPTION_GLOBAL,
+ context: SUBSCRIPTION,
});
const byPrefix = resolveTurnCost({
rawModel: 'chatgpt/gpt-5.5',
@@ -324,7 +311,7 @@ describe('resolveTurnCost', () => {
},
sdkCostDelta: 5,
pricing: null,
- context: { ...PROVIDER_CN, region: 'global' },
+ context: PROVIDER_API,
});
expect(byRoute).toMatchObject({ source: 'subscription', money: null });
expect(byPrefix).toMatchObject({ source: 'subscription', money: null });
@@ -343,18 +330,45 @@ describe('resolveClaudeTurnCostSinks', () => {
delta('gpt-5.5[1m]', { inputTokensDelta: 1_000_000 }),
],
pricing,
- XD_GLOBAL,
+ XD_GATEWAY,
);
expect(result.turnMoney?.amount).toBe(7);
expect(result.perModel.map((item) => item.money?.amount)).toEqual([5, 2]);
expect(result.perModel.map((item) => item.source)).toEqual(['gateway', 'gateway']);
});
+ it('skips the USD SDK fallback under a non-USD catalog — no reliable price, no money', () => {
+ const pricing = catalog(
+ quote('claude-opus-4-8', 5, 25, { currency: 'CNY' }),
+ );
+ const result = resolveClaudeTurnCostSinks(
+ [
+ delta('claude-opus-4-8', { inputTokensDelta: 1_000_000 }),
+ delta('unquoted-model', { costUsdDelta: 2 }),
+ ],
+ pricing,
+ XD_GATEWAY,
+ );
+ expect(result.turnMoney).toMatchObject({
+ amount: 5,
+ currency: 'CNY',
+ kind: 'actual-cost',
+ });
+ expect(result.perModel.map((item) => item.money)).toEqual([
+ expect.objectContaining({ currency: 'CNY', amount: 5 }),
+ null,
+ ]);
+ expect(result.perModel.map((item) => item.source)).toEqual([
+ 'gateway',
+ 'sdk-fallback',
+ ]);
+ });
+
it('returns null total when the route is subscription-only', () => {
const result = resolveClaudeTurnCostSinks(
[delta('claude-opus-4-8', { costUsdDelta: 4 })],
null,
- SUBSCRIPTION_GLOBAL,
+ SUBSCRIPTION,
);
expect(result.turnMoney).toBeNull();
expect(result.perModel[0]).toMatchObject({
@@ -365,40 +379,33 @@ describe('resolveClaudeTurnCostSinks', () => {
});
describe('subscription value and usage details', () => {
- it('estimates Anthropic subscription value from reference pricing and regionalizes CN', () => {
- const value = estimateClaudeSubscriptionTurnValue(
- [
- resolvedModel('claude-opus-4-8', {
- inputTokens: 1_000_000,
- outputTokens: 200_000,
- }),
- ],
- 'cn',
- );
+ it('estimates Anthropic subscription value from USD reference pricing', () => {
+ const value = estimateClaudeSubscriptionTurnValue([
+ resolvedModel('claude-opus-4-8', {
+ inputTokens: 1_000_000,
+ outputTokens: 200_000,
+ }),
+ ]);
expect(value).toMatchObject({
- amount: 67,
- currency: 'CNY',
+ amount: 10,
+ currency: 'USD',
approximate: true,
kind: 'value-estimate',
});
});
it('does not estimate non-Anthropic, already-costed, unknown, or zero-token entries', () => {
- expect(estimateClaudeSubscriptionTurnValue(
- [
- resolvedModel('gpt-5.5', { inputTokens: 1_000_000 }),
- resolvedModel(
- 'claude-opus-4-8',
- { inputTokens: 1_000_000 },
- usdMoney(1),
- ),
- resolvedModel('claude-unknown-9', { inputTokens: 1_000_000 }),
- ],
- 'global',
- )).toBeNull();
+ expect(estimateClaudeSubscriptionTurnValue([
+ resolvedModel('gpt-5.5', { inputTokens: 1_000_000 }),
+ resolvedModel(
+ 'claude-opus-4-8',
+ { inputTokens: 1_000_000 },
+ usdMoney(1),
+ ),
+ resolvedModel('claude-unknown-9', { inputTokens: 1_000_000 }),
+ ])).toBeNull();
expect(estimateClaudeSubscriptionTurnValue(
[resolvedModel('claude-opus-4-8')],
- 'global',
)).toBeNull();
});
diff --git a/apps/desktop/src/main/usage/__tests__/turnCostRouting.test.ts b/apps/desktop/src/main/usage/__tests__/turnCostRouting.test.ts
index 34456fa4f2..4513c76e12 100644
--- a/apps/desktop/src/main/usage/__tests__/turnCostRouting.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/turnCostRouting.test.ts
@@ -59,7 +59,6 @@ describe('turn cost routing regression', () => {
{
providerId: 'xd',
billingRoute: 'xd-gateway',
- region: 'global',
},
);
@@ -76,7 +75,7 @@ describe('turn cost routing regression', () => {
expect(result.turnMoney?.amount).toBeCloseTo(7.216596, 5);
});
- it('provider API route uses SDK USD and CN marks the converted total approximate', () => {
+ it('provider API route keeps the SDK USD total exact in USD', () => {
const result = resolveClaudeTurnCostSinks(
[
delta({ model: 'claude-opus-4-8', costUsdDelta: 1.5 }),
@@ -86,15 +85,14 @@ describe('turn cost routing regression', () => {
{
providerId: 'anthropic',
billingRoute: 'provider-api',
- region: 'cn',
},
);
expect(result.turnMoney).toMatchObject({
- currency: 'CNY',
- approximate: true,
+ currency: 'USD',
+ approximate: false,
});
- expect(result.turnMoney?.amount).toBeCloseTo(23.45);
+ expect(result.turnMoney?.amount).toBeCloseTo(3.5);
expect(result.perModel.map((item) => item.source)).toEqual(['sdk', 'sdk']);
});
});
diff --git a/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts b/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
index b61e29feaa..f611a23bb3 100644
--- a/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
@@ -83,11 +83,8 @@ import {
import { getAllSpendDays } from '../../localDb/dailySpend';
import { getModelUsageSince } from '../../localDb/dailyModelUsage';
import { getModelPricing, isModelPricingRefreshInFlight } from '../modelPricing';
-import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';
import {
- gatewayCurrencyForRegion,
- regionalAmountFromUsdReference,
- zeroRegionalMoney,
+ zeroUsageMoney,
type ModelPriceQuote,
type RegionalMoney,
} from '../../../shared/regionalMoney';
@@ -97,7 +94,7 @@ const TODAY = '2026-06-11';
function actual(amount: number, approximate = false): RegionalMoney {
return {
amount,
- currency: gatewayCurrencyForRegion(CURRENT_CINDY_REGION),
+ currency: 'USD',
approximate,
kind: 'actual-cost',
...(approximate ? { estimateReasons: ['legacy-usd'] } : {}),
@@ -238,10 +235,7 @@ describe('billing model keys', () => {
describe('readUsageHistoryWith', () => {
it('aggregates actual money and subscription value without double counting', async () => {
- const estimateAmount = regionalAmountFromUsdReference(
- 2,
- CURRENT_CINDY_REGION,
- );
+ const estimateAmount = 2;
const result = await readUsageHistoryWith(makeDeps({
getAllSpendDays: async () => [
{ day: '2026-06-10', money: actual(3) },
@@ -310,7 +304,7 @@ describe('readUsageHistoryWith', () => {
});
it('uses provider-scoped Anthropic reference pricing for Claude subscription rows', async () => {
- const expected = regionalAmountFromUsdReference(5, CURRENT_CINDY_REGION);
+ const expected = 5;
const result = await readUsageHistoryWith(makeDeps({
getModelUsageSince: async () => [
modelRow(
@@ -402,7 +396,7 @@ describe('production cache and empty payload', () => {
),
);
expect(raw).toMatchObject({
- version: 2,
+ version: 3,
optsKey: 'user=user-a|days=30',
payload: {
totals: {
@@ -413,13 +407,11 @@ describe('production cache and empty payload', () => {
});
});
- it('returns region-correct structured zero money on fallback', () => {
+ it('returns structured USD zero money on fallback', () => {
const empty = emptyUsageHistoryPayload();
- expect(empty.totals.today).toEqual(
- zeroRegionalMoney(CURRENT_CINDY_REGION),
- );
+ expect(empty.totals.today).toEqual(zeroUsageMoney());
expect(empty.totals.last30DaysEstimatedValue).toEqual(
- zeroRegionalMoney(CURRENT_CINDY_REGION, 'value-estimate'),
+ zeroUsageMoney('value-estimate'),
);
});
});
diff --git a/apps/desktop/src/main/usage/claudeAccountUsage.ts b/apps/desktop/src/main/usage/claudeAccountUsage.ts
index 636f8fe04e..7e3c9b0e87 100644
--- a/apps/desktop/src/main/usage/claudeAccountUsage.ts
+++ b/apps/desktop/src/main/usage/claudeAccountUsage.ts
@@ -54,7 +54,8 @@ export const USAGE_CLAUDE_ACCOUNT_CHANGED = 'usage:claude-account-changed';
export interface ClaudeAccountUsageSnapshot {
/**
* 当前周期(网关部署为 30d / 月度) 跨所有客户端 + 所有 API key 的累计花费,
- * 来自 Gateway user.spend,数值保持部署区域原生金额。不只本机本壳。
+ * 来自 Gateway user.spend,数值保持 Gateway 原值(原生 USD 口径,展示层经
+ * gatewayMoney 标注单位,不按构建区域改标)。不只本机本壳。
*/
spend: number;
/** 周期内预算上限,保持 Gateway 原值 (来自 user.max_budget)。 */
diff --git a/apps/desktop/src/main/usage/modelPricing.ts b/apps/desktop/src/main/usage/modelPricing.ts
index 652c35587d..5e021d1ffe 100644
--- a/apps/desktop/src/main/usage/modelPricing.ts
+++ b/apps/desktop/src/main/usage/modelPricing.ts
@@ -32,7 +32,10 @@ export type {
} from '../../shared/regionalMoney.js';
const log = createLogger('modelPricing');
-const DISK_CACHE_VERSION = 3;
+// v4: 币种语义从「按构建区域标注」改为「跟随来源(默认 USD)」——旧缓存里
+// CN 构建的 quote 带错标 CNY,必须整体作废,否则升级后到下一次 /models 同步
+// 前仍会用旧币种折算单轮费用。
+const DISK_CACHE_VERSION = 4;
const DISK_CACHE_FILE = 'model-pricing.json';
export const MODEL_PRICING_CHANGED_CHANNEL = 'usage:model-pricing-changed';
@@ -221,7 +224,7 @@ export function replaceGatewayModelPricing(
models: readonly ModelAccessGatewayModel[],
): ModelPricingCatalog {
const scope = currentScope();
- const pricing = gatewayPricingCatalog(models, CURRENT_CINDY_REGION);
+ const pricing = gatewayPricingCatalog(models);
cache = pricing;
cacheScope = scope;
cacheAt = Date.now();
diff --git a/apps/desktop/src/main/usage/turnCostCalculator.ts b/apps/desktop/src/main/usage/turnCostCalculator.ts
index 3b296b1961..4d45f19d74 100644
--- a/apps/desktop/src/main/usage/turnCostCalculator.ts
+++ b/apps/desktop/src/main/usage/turnCostCalculator.ts
@@ -2,18 +2,17 @@
* 单轮费用计算。定价先看实际 billing route,再看模型;模型名不再决定来源。
*/
-import type { CindyRegion } from '@cindy/maker-shared/brand-identity';
-
import {
getModelPriceQuote,
providerReferencePriceQuote,
- regionalizeModelPriceQuote,
} from '../../shared/modelPriceQuote.js';
import {
+ addCompatibleRegionalMoney,
addRegionalMoney,
- regionalizeUsd,
+ usdMoney,
type ModelPriceQuote,
type ModelPricingCatalog,
+ type MoneyCurrency,
type RegionalMoney,
} from '../../shared/regionalMoney.js';
import { buildTurnUsageDetails, type TurnUsageDetails } from '../../shared/turnUsageDetails.js';
@@ -42,7 +41,6 @@ export type BillingRoute =
export interface TurnPricingContext {
providerId: string | null;
billingRoute: BillingRoute;
- region: CindyRegion;
}
export type TurnCostSource = 'sdk' | 'gateway' | 'sdk-fallback' | 'subscription';
@@ -140,15 +138,19 @@ export function resolveTurnCost(args: {
// quote 缺失(冷缓存 / /models 同步失败 / 目录无该模型价):回退 SDK 自报
// 数字,真实 gateway 计费不能整轮记 0。codex/ 预算路由的 SDK 数字未含 0.15
// 折扣,这里补乘一次 —— gateway 价路径的价表已折好,两路互斥不双重打折。
+ // 目录币种非 USD 时不回退:SDK 自报 USD 既不匹配网关价目、单位也对不上,
+ // 记入即错标——按「无可靠报价」语义返回无金额(token 照常统计),与 codex
+ // 无价条目的既有处理一致,也让单轮金额不可能混币种。
+ const xdQuotes = pricing?.xd ? Object.values(pricing.xd) : [];
+ if (xdQuotes.length > 0 && xdQuotes[0].currency !== 'USD') {
+ return { model, money: null, source: 'sdk-fallback' };
+ }
const fallbackUsd =
Math.max(0, sdkCostDelta ?? 0) *
getCodexBudgetEffectiveCostMultiplier(model);
return {
model,
- money:
- fallbackUsd > 0
- ? regionalizeUsd(fallbackUsd, context.region, 'fixed-fx')
- : null,
+ money: fallbackUsd > 0 ? usdMoney(fallbackUsd) : null,
source: 'sdk-fallback',
};
}
@@ -157,10 +159,7 @@ export function resolveTurnCost(args: {
0,
(sdkCostDelta ?? 0) * getCodexBudgetEffectiveCostMultiplier(model),
);
- const money =
- sdkAmount > 0
- ? regionalizeUsd(sdkAmount, context.region, 'fixed-fx')
- : null;
+ const money = sdkAmount > 0 ? usdMoney(sdkAmount) : null;
return {
model,
money,
@@ -210,23 +209,28 @@ export function resolveClaudeTurnCostSinks(
});
if (resolved.money && resolved.money.amount > 0) money.push(resolved.money);
}
+ if (money.length === 0) return { turnMoney: null, perModel };
+ // 非 USD 目录下若某模型缺报价,其 SDK fallback 段是 USD——同轮混币种时按
+ // gateway 报价段的币种聚合、弃掉冲突段(单币种账本约束),绝不能 throw
+ // 打断 turn 收尾管道。
+ const preferredCurrency: MoneyCurrency =
+ perModel.find((item) => item.source === 'gateway' && item.money)?.money
+ ?.currency ?? money[0].currency;
return {
- turnMoney: money.length > 0 ? addRegionalMoney(money) : null,
+ turnMoney: addCompatibleRegionalMoney(money, preferredCurrency),
perModel,
};
}
export function estimateClaudeSubscriptionTurnValue(
perModel: ResolvedModelCost[],
- region: CindyRegion,
): RegionalMoney | null {
const values: RegionalMoney[] = [];
for (const item of perModel) {
if (!isAnthropicModel(item.model) || item.money?.amount) continue;
const quote = providerReferencePriceQuote('anthropic', item.model);
if (!quote) continue;
- const regionalQuote = regionalizeModelPriceQuote(quote, region);
- const value = computePriceQuoteTurnMoney(item.deltas, regionalQuote);
+ const value = computePriceQuoteTurnMoney(item.deltas, quote);
if (value && value.amount > 0) values.push(value);
}
return values.length > 0 ? addRegionalMoney(values) : null;
diff --git a/apps/desktop/src/main/usage/usageHistory.ts b/apps/desktop/src/main/usage/usageHistory.ts
index 4b8b2a890c..0dd0a8a129 100644
--- a/apps/desktop/src/main/usage/usageHistory.ts
+++ b/apps/desktop/src/main/usage/usageHistory.ts
@@ -31,19 +31,18 @@ import {
type ModelPricingMap,
} from './modelPricing';
import { computePriceQuoteTurnMoney } from './turnCostCalculator';
-import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
import {
getModelPriceQuote,
- regionalizeModelPriceQuote,
} from '../../shared/modelPriceQuote.js';
import {
addCompatibleRegionalMoney,
+ DEFAULT_USAGE_CURRENCY,
normalizeRegionalMoney,
- regionalAmountFromUsdReference,
- regionalCurrencyForRegion,
+ USD_TO_CNY_FIXED_RATE,
type ModelPriceQuote,
+ type MoneyCurrency,
type RegionalMoney,
- zeroRegionalMoney,
+ zeroUsageMoney,
} from '../../shared/regionalMoney.js';
const log = createLogger('usageHistory');
@@ -59,7 +58,8 @@ const ANOMALY_MIN_ACTIVE_DAYS = 3;
const MODEL_WINDOW_DAYS = 30;
/** 等价格表的最长预算 (ms) — 缓存命中时是同步快返, 只有冷启动网络 fetch 会触及。 */
const PRICING_WAIT_BUDGET_MS = 200;
-const DISK_CACHE_VERSION = 2;
+// v3: 币种语义改为跟随来源(默认 USD),旧缓存里 CN 构建的金额带错标 CNY,整体作废。
+const DISK_CACHE_VERSION = 3;
const DISK_CACHE_FILE = 'usage-history.json';
/** 后台刷新完成后, renderer 的短轮询能拿到 fresh payload, 避免 stale 状态自循环。 */
const MEMORY_FRESH_MS = 10_000;
@@ -356,17 +356,12 @@ function getSubscriptionValuePriceFor(
pricing: ModelPricingMap | null,
): ModelPriceQuote | undefined {
if (agentKind === 'codex') {
- const quote =
+ return (
getSubscriptionDirectValuePrice(model) ??
- getCodexSubscriptionValuePrice(model, pricing);
- return quote
- ? regionalizeModelPriceQuote(quote, CURRENT_CINDY_REGION)
- : undefined;
+ getCodexSubscriptionValuePrice(model, pricing)
+ );
}
- const quote = getModelPriceQuote(pricing, 'anthropic', model);
- return quote
- ? regionalizeModelPriceQuote(quote, CURRENT_CINDY_REGION)
- : undefined;
+ return getModelPriceQuote(pricing, 'anthropic', model);
}
async function hydrateFromDisk(expectedOptsKey: string): Promise<UsageHistoryPayload | null> {
@@ -492,20 +487,38 @@ export async function readUsageHistoryWith(
const todayKey = deps.todayKey();
const allDays = await deps.getAllSpendDays();
+ // 阈值启发式(异常检测)使用的日金额表必须与账本币种同单位:币种切换过渡
+ // 期的异币种历史日不进表(按 0 计),避免拿一种币种的阈值去比另一种的数值。
+ const ledgerCurrency =
+ allDays.find((row) => row.day === todayKey)?.money.currency ??
+ allDays[allDays.length - 1]?.money.currency ??
+ DEFAULT_USAGE_CURRENCY;
const spendByDay = new Map(
- allDays.map((row) => [row.day, row.money.amount]),
+ allDays
+ .filter((row) => row.money.currency === ledgerCurrency)
+ .map((row) => [row.day, row.money.amount]),
);
- const zeroActual = () => zeroRegionalMoney(CURRENT_CINDY_REGION);
- const zeroEstimate = () =>
- zeroRegionalMoney(CURRENT_CINDY_REGION, 'value-estimate');
+ // 零值也用账本币种:无消费日的 today/空聚合不能把展示单位翻回默认币种。
+ const zeroActual = (): RegionalMoney => ({
+ amount: 0,
+ currency: ledgerCurrency,
+ approximate: false,
+ kind: 'actual-cost',
+ });
+ const zeroEstimate = (): RegionalMoney => ({
+ amount: 0,
+ currency: ledgerCurrency,
+ approximate: true,
+ kind: 'value-estimate',
+ estimateReasons: ['subscription-value'],
+ });
+ // 聚合偏好账本币种(今天/最新行的币种):默认 USD 偏好会在币种切换过渡期
+ // 把当前币种的日金额整段挤掉(窗口里残留任意旧 USD 行即触发)。
const addOrZero = (
values: RegionalMoney[],
kind: 'actual-cost' | 'value-estimate' = 'actual-cost',
): RegionalMoney =>
- addCompatibleRegionalMoney(
- values,
- regionalCurrencyForRegion(CURRENT_CINDY_REGION),
- ) ??
+ addCompatibleRegionalMoney(values, ledgerCurrency) ??
(kind === 'actual-cost' ? zeroActual() : zeroEstimate());
const heatmapCutoff = shiftDayKey(todayKey, -(windowDays - 1));
@@ -587,10 +600,7 @@ export async function readUsageHistoryWith(
if (row.money.amount > 0) {
agg.money =
agg.money.amount > 0
- ? (addCompatibleRegionalMoney(
- [agg.money, row.money],
- regionalCurrencyForRegion(CURRENT_CINDY_REGION),
- ) ?? row.money)
+ ? (addCompatibleRegionalMoney([agg.money, row.money], ledgerCurrency) ?? row.money)
: row.money;
}
agg.inputTokens += row.inputTokens;
@@ -645,16 +655,21 @@ export async function readUsageHistoryWith(
return tokens(b) - tokens(a);
});
- const activeDayMin = regionalAmountFromUsdReference(
- ACTIVE_DAY_MIN_USD,
- CURRENT_CINDY_REGION,
- );
- const anomalyMinToday = regionalAmountFromUsdReference(
+ // 活跃日/异常阈值常量是 USD 口径;历史 CNY 行(或来源真声明 CNY 的账本)按
+ // 固定汇率把阈值折到该行币种再比较。仅阈值启发式用,不产生任何展示金额。
+ const heuristicThreshold = (base: number, currency: MoneyCurrency): number =>
+ currency === 'CNY' ? base * USD_TO_CNY_FIXED_RATE : base;
+ const activeDayMin = heuristicThreshold(ACTIVE_DAY_MIN_USD, ledgerCurrency);
+ const anomalyMinToday = heuristicThreshold(
ANOMALY_MIN_TODAY_USD,
- CURRENT_CINDY_REGION,
+ ledgerCurrency,
);
const activeDays = allDays
- .filter((row) => row.money.amount >= activeDayMin)
+ .filter(
+ (row) =>
+ row.money.amount >=
+ heuristicThreshold(ACTIVE_DAY_MIN_USD, row.money.currency),
+ )
.map((row) => row.day);
const last30Cutoff = shiftDayKey(todayKey, -(MODEL_WINDOW_DAYS - 1));
const last30ActualByDay = new Map<string, RegionalMoney>();
@@ -677,11 +692,14 @@ export async function readUsageHistoryWith(
);
const last30WithEstimatedValue =
last30EstimatedValue.amount > 0
- ? (addCompatibleRegionalMoney(
- [last30, last30EstimatedValue],
- regionalCurrencyForRegion(CURRENT_CINDY_REGION),
- ) ?? last30)
+ ? (addCompatibleRegionalMoney([last30, last30EstimatedValue], ledgerCurrency) ?? last30)
: last30;
+ // 与合计口径一致:估算若因币种不兼容被聚合弃掉,就不能再单独外露非零值,
+ // 否则 UI 会声称「总额已含订阅估算」而实际未含。
+ const exposedLast30EstimatedValue =
+ last30EstimatedValue.currency === last30WithEstimatedValue.currency
+ ? last30EstimatedValue
+ : zeroEstimate();
const anomalyRaw = computeAnomaly(spendByDay, todayKey, {
activeDayMin,
anomalyMinToday,
@@ -707,7 +725,7 @@ export async function readUsageHistoryWith(
today,
last30Days: last30,
last30DaysWithEstimatedValue: last30WithEstimatedValue,
- last30DaysEstimatedValue: last30EstimatedValue,
+ last30DaysEstimatedValue: exposedLast30EstimatedValue,
todayTokens,
last30DaysTokens,
},
@@ -718,7 +736,7 @@ export async function readUsageHistoryWith(
? null
: {
amount: anomalyRaw.trailing7DayAvg,
- currency: today.currency,
+ currency: ledgerCurrency,
approximate: trailing7Approximate,
kind: 'actual-cost',
...(trailing7Approximate
@@ -768,15 +786,10 @@ export function emptyUsageHistoryPayload(): UsageHistoryPayload {
models: [],
streak: { current: 0, longest: 0 },
totals: {
- today: zeroRegionalMoney(CURRENT_CINDY_REGION),
- last30Days: zeroRegionalMoney(CURRENT_CINDY_REGION),
- last30DaysWithEstimatedValue: zeroRegionalMoney(
- CURRENT_CINDY_REGION,
- ),
- last30DaysEstimatedValue: zeroRegionalMoney(
- CURRENT_CINDY_REGION,
- 'value-estimate',
- ),
+ today: zeroUsageMoney(),
+ last30Days: zeroUsageMoney(),
+ last30DaysWithEstimatedValue: zeroUsageMoney(),
+ last30DaysEstimatedValue: zeroUsageMoney('value-estimate'),
todayTokens: 0,
last30DaysTokens: 0,
},
diff --git a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
index b77dc95e52..f291a398d0 100644
--- a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
+++ b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
@@ -934,7 +934,9 @@ describe('automation-generated sessions', () => {
expect(storageSource).toContain('SQLITE_IN_CHUNK_SIZE');
expect(storageSource).toContain("when 'user' then 0 else 1 end");
expect(storageSource).toContain('entry.costValues.push(turnCost.costMoney)');
- expect(storageSource).toContain('addCompatibleRegionalMoney(summary.costValues)');
+ expect(storageSource).toContain(
+ 'addCompatibleRegionalMoney(summary.costValues, summary.latestCurrency)',
+ );
expect(storageSource).toContain('totalMoney');
expect(storageSource).toContain('listLegacySessionRuns');
expect(storageSource).toContain("LEGACY_SCHEDULE_TITLE_PREFIX = '[Schedule] '");
diff --git a/apps/desktop/src/renderer/__tests__/homeUsageDashboardSource.test.ts b/apps/desktop/src/renderer/__tests__/homeUsageDashboardSource.test.ts
index e86274b55e..3d2845d366 100644
--- a/apps/desktop/src/renderer/__tests__/homeUsageDashboardSource.test.ts
+++ b/apps/desktop/src/renderer/__tests__/homeUsageDashboardSource.test.ts
@@ -19,7 +19,7 @@ const heatmapSource = readFileSync(
describe('HomeUsageDashboard source contract', () => {
it('uses the Claude account daily spend for the visible today amount when available', () => {
expect(source).toMatch(
- /const accountTodayMoney =\s+typeof claudeQuota\?\.todaySpend === 'number'\s+\? gatewayMoney\(claudeQuota\.todaySpend, CURRENT_CINDY_REGION\)\s+: null;/,
+ /const accountTodayMoney =\s+typeof claudeQuota\?\.todaySpend === 'number'\s+\? gatewayMoney\(claudeQuota\.todaySpend\)\s+: null;/,
);
expect(source).toContain('const hasAccountTodaySpend = accountTodayMoney !== null;');
expect(source).toContain('const layoutHistory = history ?? emptyLayoutHistory;');
@@ -60,13 +60,9 @@ describe('HomeUsageDashboard source contract', () => {
expect(source).not.toContain('history.days.length === 0 && history.models.length === 0');
});
- it('uses the build-region currency for empty chart cells', () => {
- expect(heatmapSource).toContain(
- 'regionalCurrencyForRegion(CURRENT_CINDY_REGION)',
- );
- expect(dailyBarsSource).toContain(
- 'regionalCurrencyForRegion(CURRENT_CINDY_REGION)',
- );
+ it('uses the default usage currency for empty chart cells', () => {
+ expect(heatmapSource).toContain('DEFAULT_USAGE_CURRENCY');
+ expect(dailyBarsSource).toContain('DEFAULT_USAGE_CURRENCY');
expect(heatmapSource).not.toContain("money.currency ?? 'USD'");
expect(dailyBarsSource).not.toContain("money.currency ?? 'USD'");
});
diff --git a/apps/desktop/src/renderer/__tests__/messageTurnCost.test.ts b/apps/desktop/src/renderer/__tests__/messageTurnCost.test.ts
index ea9d872bed..f2695cf9e6 100644
--- a/apps/desktop/src/renderer/__tests__/messageTurnCost.test.ts
+++ b/apps/desktop/src/renderer/__tests__/messageTurnCost.test.ts
@@ -50,8 +50,7 @@ vi.mock('@/lib/composerDraftStore', () => ({
}));
import { formatTurnCostUsd } from '@/lib/usageFormat';
-import { CURRENT_CINDY_REGION } from '../../shared/brandRegion';
-import { regionalizeLegacyUsd } from '../../shared/regionalMoney';
+import { legacyUsdMoney } from '../../shared/regionalMoney';
import { buildTurnUsageDetails } from '../../shared/turnUsageDetails';
import { makerChatStore } from '@/lib/makerChatStore';
import * as messageService from '@/lib/messageService';
@@ -124,8 +123,7 @@ function serverMessage(over: Partial<Message>): Message {
}
const flush = () => new Promise((r) => setTimeout(r, 0));
-const legacyMoney = (amountUsd: number) =>
- regionalizeLegacyUsd(amountUsd, CURRENT_CINDY_REGION);
+const legacyMoney = (amountUsd: number) => legacyUsdMoney(amountUsd);
const DETAILS = buildTurnUsageDetails({
inputTokens: 1200,
outputTokens: 300,
diff --git a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
index 4bfad77834..5700df7eec 100644
--- a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
+++ b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
@@ -150,12 +150,12 @@ describe('TodaySpendChip dashboard routing', () => {
expect(source).not.toContain('todaySpend.codex.creditsShort');
});
- it('formats gateway quota amounts with the build-region currency', () => {
+ it('formats gateway quota amounts with the gateway-native currency', () => {
expect(source).toContain(
- 'formatCompactMoney(gatewayMoney(claudeQuota.spend, CURRENT_CINDY_REGION))',
+ 'formatCompactMoney(gatewayMoney(claudeQuota.spend))',
);
expect(source).toContain(
- 'formatCompactMoney(gatewayMoney(claudeQuota.maxBudget, CURRENT_CINDY_REGION))',
+ 'formatCompactMoney(gatewayMoney(claudeQuota.maxBudget))',
);
expect(source).not.toContain('formatCompactUsd(claudeQuota.');
});
diff --git a/apps/desktop/src/renderer/components/chat/MessageActionBar.tsx b/apps/desktop/src/renderer/components/chat/MessageActionBar.tsx
index 22bbfaaf9e..76652b95cd 100644
--- a/apps/desktop/src/renderer/components/chat/MessageActionBar.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageActionBar.tsx
@@ -54,9 +54,8 @@ import { formatAbsolute, useRelativeTime } from '@/hooks/useRelativeTime';
import { formatTurnCostMoney } from '@/lib/usageFormat';
import { buildTurnUsageTooltipLines } from '@/lib/turnUsageTooltip';
import type { TurnUsageDetails } from '../../../shared/turnUsageDetails';
-import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';
import {
- regionalizeLegacyUsd,
+ legacyUsdMoney,
type RegionalMoney,
} from '../../../shared/regionalMoney';
@@ -309,12 +308,12 @@ export function MessageActionBar({
const effectiveTurnMoney =
turnMoney ??
(typeof turnCostUsd === 'number' && turnCostUsd > 0
- ? regionalizeLegacyUsd(turnCostUsd, CURRENT_CINDY_REGION)
+ ? legacyUsdMoney(turnCostUsd)
: undefined);
const effectiveUserTurnMoney =
userTurnMoney ??
(typeof userTurnCostUsd === 'number' && userTurnCostUsd > 0
- ? regionalizeLegacyUsd(userTurnCostUsd, CURRENT_CINDY_REGION)
+ ? legacyUsdMoney(userTurnCostUsd)
: undefined);
const displayedMoney = effectiveUserTurnMoney ?? effectiveTurnMoney;
const displayedCostIsEstimate = effectiveUserTurnMoney
diff --git a/apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx b/apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx
index b42cb42c53..2d076f4b16 100644
--- a/apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx
@@ -34,11 +34,10 @@ import { useAuth } from '@/contexts/AuthContext';
import { UsageDailyBars } from './UsageDailyBars';
import { UsageHeatmap } from './UsageHeatmap';
import { USAGE_TOP_MODELS, usageModelKey } from './usagePalette';
-import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';
import {
gatewayMoney,
type RegionalMoney,
- zeroRegionalMoney,
+ zeroUsageMoney,
} from '../../../shared/regionalMoney';
const COLLAPSED_STORAGE_KEY = 'homeUsageDashboard.collapsed';
@@ -49,7 +48,7 @@ const ACCOUNT_LOCAL_TODAY_MATCH_EPSILON = 0.01;
const UNKNOWN_VALUE = '—';
const TOKEN_DISTRIBUTION_TOP_MODELS = 5;
-const zeroMoney = () => zeroRegionalMoney(CURRENT_CINDY_REGION);
+const zeroMoney = () => zeroUsageMoney();
type TokenDistributionInput = {
model: string;
@@ -93,10 +92,7 @@ function createEmptyUsageHistoryPayload(): UsageHistoryPayload {
today: zeroMoney(),
last30Days: zeroMoney(),
last30DaysWithEstimatedValue: zeroMoney(),
- last30DaysEstimatedValue: zeroRegionalMoney(
- CURRENT_CINDY_REGION,
- 'value-estimate',
- ),
+ last30DaysEstimatedValue: zeroUsageMoney('value-estimate'),
todayTokens: 0,
last30DaysTokens: 0,
},
@@ -192,7 +188,7 @@ export function HomeUsageDashboard(): React.JSX.Element {
const accountTodayMoney =
typeof claudeQuota?.todaySpend === 'number'
- ? gatewayMoney(claudeQuota.todaySpend, CURRENT_CINDY_REGION)
+ ? gatewayMoney(claudeQuota.todaySpend)
: null;
const hasAccountTodaySpend = accountTodayMoney !== null;
@@ -205,7 +201,7 @@ export function HomeUsageDashboard(): React.JSX.Element {
const softDailyLimitMoney =
softDailyLimit === null
? null
- : gatewayMoney(softDailyLimit, CURRENT_CINDY_REGION);
+ : gatewayMoney(softDailyLimit);
const todayValue = !hasSpendValue
? UNKNOWN_VALUE
: softDailyLimitMoney
@@ -356,7 +352,7 @@ export function HomeUsageDashboard(): React.JSX.Element {
<StatCell
value={
hasMonthly
- ? `${formatCompactMoney(gatewayMoney(claudeQuota.spend, CURRENT_CINDY_REGION))} / ${formatCompactMoney(gatewayMoney(claudeQuota.maxBudget, CURRENT_CINDY_REGION))}`
+ ? `${formatCompactMoney(gatewayMoney(claudeQuota.spend))} / ${formatCompactMoney(gatewayMoney(claudeQuota.maxBudget))}`
: `${UNKNOWN_VALUE} / ${UNKNOWN_VALUE}`
}
label={t('usageDashboard.monthly')}
diff --git a/apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx b/apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx
index 0607cf7bf8..c3fbb10a6d 100644
--- a/apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx
@@ -20,9 +20,8 @@ import {
} from '@/lib/usageFormat';
import type { UsageHistoryModelDay } from '@/hooks/useUsageHistory';
import { usageModelKey, usageRankColor, usageRankOf } from './usagePalette';
-import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';
import {
- regionalCurrencyForRegion,
+ DEFAULT_USAGE_CURRENCY,
type MoneyCurrency,
type MoneyKind,
type RegionalMoney,
@@ -77,10 +76,25 @@ export function UsageDailyBars({
todayKey: string;
}): React.JSX.Element {
const { t } = useTranslation();
+ // chart currency 取窗口内**最近一个有金额的日子**的币种:取首行会在币种切换
+ // 过渡期选中旧币种(或 token-only 日合成的零额 USD),把当前币种的柱子全部
+ // 归零;金额为 0 的行不参与选取。
+ const latestPositiveCurrency = (
+ rows: ReadonlyArray<{ day: string; money: RegionalMoney }>,
+ ): MoneyCurrency | undefined => {
+ let best: { day: string; currency: MoneyCurrency } | undefined;
+ for (const row of rows) {
+ if (row.money.amount <= 0) continue;
+ if (!best || row.day > best.day) {
+ best = { day: row.day, currency: row.money.currency };
+ }
+ }
+ return best?.currency;
+ };
const currency: MoneyCurrency =
- days[0]?.money.currency ??
- modelDaily[0]?.money.currency ??
- regionalCurrencyForRegion(CURRENT_CINDY_REGION);
+ latestPositiveCurrency(days) ??
+ latestPositiveCurrency(modelDaily) ??
+ DEFAULT_USAGE_CURRENCY;
const money = (
amount: number,
approximate: boolean,
@@ -102,6 +116,10 @@ export function UsageDailyBars({
const bars = useMemo(() => {
const byDay = new Map(days.map((d) => [d.day, d]));
+ // 图表是单币种口径:与 chart currency 不同币种的金额不参与求和(裸数字
+ // 跨币种相加会产生错标总额),该行 token 仍照常进 tooltip 明细。
+ const amountIn = (m: RegionalMoney): number =>
+ m.currency === currency ? m.amount : 0;
// 按天聚出分段: 同 rank (含"其它"档) 合并金额与 token。
// 无价格的 codex 行 (amountUsd=0) 也收进来 — 画不了分段 (无金额占比),
// 但 tooltip 里要按 token 露出, 不能让它在明细里消失。
@@ -116,20 +134,18 @@ export function UsageDailyBars({
}
const seg = daySegs.get(rank);
if (seg) {
- seg.amount += row.money.amount;
- seg.apiAmount += row.apiMoney.amount;
- seg.subscriptionEstimateAmount +=
- row.subscriptionEstimateMoney.amount;
+ seg.amount += amountIn(row.money);
+ seg.apiAmount += amountIn(row.apiMoney);
+ seg.subscriptionEstimateAmount += amountIn(row.subscriptionEstimateMoney);
seg.tokens += row.tokens;
if (rank < colorOrder.length) seg.label = row.model;
} else {
daySegs.set(rank, {
rank,
label: rank < colorOrder.length ? row.model : t('usageDashboard.othersLegend'),
- amount: row.money.amount,
- apiAmount: row.apiMoney.amount,
- subscriptionEstimateAmount:
- row.subscriptionEstimateMoney.amount,
+ amount: amountIn(row.money),
+ apiAmount: amountIn(row.apiMoney),
+ subscriptionEstimateAmount: amountIn(row.subscriptionEstimateMoney),
tokens: row.tokens,
});
}
@@ -140,7 +156,7 @@ export function UsageDailyBars({
const day = shiftDayKeyLocal(todayKey, -i);
const row = byDay.get(day);
const segments = [...(segsByDay.get(day)?.values() ?? [])].sort((a, b) => a.rank - b.rank);
- const actualAmount = row?.money.amount ?? 0;
+ const actualAmount = row ? amountIn(row.money) : 0;
const segSum = segments.reduce((a, s) => a + s.amount, 0);
const subscriptionEstimateSum = segments.reduce(
(a, s) => a + s.subscriptionEstimateAmount,
diff --git a/apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx b/apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx
index 0925a01f5e..679ca7c64c 100644
--- a/apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx
@@ -13,15 +13,14 @@ import React, { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { formatCompactTokens, formatMoney } from '@/lib/usageFormat';
-import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';
import {
- regionalCurrencyForRegion,
+ DEFAULT_USAGE_CURRENCY,
type RegionalMoney,
} from '../../../shared/regionalMoney';
const CELL_PX = 12;
const GAP_PX = 3;
-const EMPTY_MONEY_CURRENCY = regionalCurrencyForRegion(CURRENT_CINDY_REGION);
+const EMPTY_MONEY_CURRENCY = DEFAULT_USAGE_CURRENCY;
/** 非零值分桶的 color-mix 浓度阶梯 (level 1..4)。 */
const LEVEL_MIX = [0.22, 0.42, 0.68, 1];
diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
index 1ca935777f..de067e6473 100644
--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
@@ -76,7 +76,6 @@ import { useXaiRateLimit, type XaiRateLimitSnapshot } from '@/hooks/useXaiRateLi
import { makerChatStore, type ChatMessage } from '@/lib/makerChatStore';
import { buildTurnUsageTooltipLines } from '@/lib/turnUsageTooltip';
import type { TurnUsageDetails } from '../../../shared/turnUsageDetails';
-import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';
import { gatewayMoney, type RegionalMoney } from '../../../shared/regionalMoney';
import { CHATGPT_MODEL_PREFIX, XAI_MODEL_PREFIX } from '../../../shared/subscriptionModels';
import {
@@ -152,8 +151,8 @@ function computeMetricSlots(
// monthly 永远跟 cycle 一起拿到; daily 走单独 endpoint 可能拉不到 (todaySpend=null) → 隐藏
slots.monthly = {
label: t('todaySpend.monthlyLimitLabel', {
- spend: formatCompactMoney(gatewayMoney(claudeQuota.spend, CURRENT_CINDY_REGION)),
- limit: formatCompactMoney(gatewayMoney(claudeQuota.maxBudget, CURRENT_CINDY_REGION)),
+ spend: formatCompactMoney(gatewayMoney(claudeQuota.spend)),
+ limit: formatCompactMoney(gatewayMoney(claudeQuota.maxBudget)),
}),
available: true,
};
@@ -162,9 +161,9 @@ function computeMetricSlots(
slots.daily = {
label: t('todaySpend.dailyLimitLabel', {
spend: formatCompactMoney(
- gatewayMoney(claudeQuota.todaySpend, CURRENT_CINDY_REGION),
+ gatewayMoney(claudeQuota.todaySpend),
),
- limit: formatCompactMoney(gatewayMoney(softLimit, CURRENT_CINDY_REGION)),
+ limit: formatCompactMoney(gatewayMoney(softLimit)),
}),
available: true,
};
diff --git a/apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsx b/apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsx
index 812cb6be03..c8b7b6110f 100644
--- a/apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsx
+++ b/apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsx
@@ -33,10 +33,9 @@ import { AgentMark } from './AgentMark';
import { AttentionDot } from '@/components/sidebar/AttentionDot';
import { formatDuration, formatRunTimestamp, formatStartedAgo } from '../lib/formatters';
import { formatTurnCostMoney } from '@/lib/usageFormat';
-import { CURRENT_CINDY_REGION } from '../../../../shared/brandRegion';
import {
- regionalizeLegacyUsd,
- regionalizeUsd,
+ legacyUsdMoney,
+ usdMoney,
} from '../../../../shared/regionalMoney';
import { isUnreadScheduleRun } from '../lib/runUnread';
import { markScheduleRunReadAndSync } from '../lib/scheduleRunReadSync';
@@ -171,18 +170,10 @@ export function RunHistoryCard({
? (() => {
const costMoney =
run.costMoney ??
- regionalizeLegacyUsd(
- run.costUsd ?? 0,
- CURRENT_CINDY_REGION,
- );
+ legacyUsdMoney(run.costUsd ?? 0);
const valueMoney =
run.estimatedValueMoney ??
- regionalizeUsd(
- run.estimatedValueUsd ?? 0,
- CURRENT_CINDY_REGION,
- 'legacy-usd',
- 'value-estimate',
- );
+ usdMoney(run.estimatedValueUsd ?? 0, 'value-estimate', 'legacy-usd');
return [
costMoney.amount > 0
? t('scheduler.runs.runCost', { cost: formatTurnCostMoney(costMoney) })
diff --git a/apps/desktop/src/renderer/hooks/useSessionEstimatedValue.ts b/apps/desktop/src/renderer/hooks/useSessionEstimatedValue.ts
index 63e22bee78..2406b48444 100644
--- a/apps/desktop/src/renderer/hooks/useSessionEstimatedValue.ts
+++ b/apps/desktop/src/renderer/hooks/useSessionEstimatedValue.ts
@@ -13,12 +13,10 @@ import { useChatDisplaySnapshot } from '@/components/chat/ChatDisplaySnapshotCon
import { makerChatStore, type ChatMessage } from '@/lib/makerChatStore';
import { estimatedSessionValueFor } from '@/lib/makerTransport';
import { resolveStaleCodexSubscriptionValueEstimate } from '../../shared/codexSubscriptionValue';
-import { CURRENT_CINDY_REGION } from '../../shared/brandRegion';
import {
addCompatibleRegionalMoney,
normalizeRegionalMoney,
- regionalCurrencyForRegion,
- regionalizeUsd,
+ usdMoney,
USD_TO_CNY_FIXED_RATE,
type MoneyEstimateReason,
type RegionalMoney,
@@ -87,12 +85,7 @@ function correctStaleUsdEstimate(
function legacyEstimateMoney(costUsd: number): RegionalMoney | null {
if (!Number.isFinite(costUsd) || costUsd <= 0) return null;
- return regionalizeUsd(
- costUsd,
- CURRENT_CINDY_REGION,
- 'legacy-usd',
- 'value-estimate',
- );
+ return usdMoney(costUsd, 'value-estimate', 'legacy-usd');
}
function estimateFromChatMessage(message: ChatMessage): { clientId: string; money: RegionalMoney } | null {
@@ -215,10 +208,7 @@ export function resolveEstimatedValueTurnCostEntry(
function sumCosts(costs: Map<string, RegionalMoney>): RegionalMoney | null {
const values = [...costs.values()];
if (values.length === 0) return null;
- const total = addCompatibleRegionalMoney(
- values,
- regionalCurrencyForRegion(CURRENT_CINDY_REGION),
- );
+ const total = addCompatibleRegionalMoney(values);
if (!total) return null;
return total.amount > 0 ? total : null;
}
diff --git a/apps/desktop/src/renderer/hooks/useSessionSpend.ts b/apps/desktop/src/renderer/hooks/useSessionSpend.ts
index 6ef721eacc..0340b28170 100644
--- a/apps/desktop/src/renderer/hooks/useSessionSpend.ts
+++ b/apps/desktop/src/renderer/hooks/useSessionSpend.ts
@@ -10,10 +10,9 @@
*/
import { useEffect, useState } from 'react';
-import { CURRENT_CINDY_REGION } from '../../shared/brandRegion';
import {
+ legacyUsdMoney,
normalizeRegionalMoney,
- regionalizeLegacyUsd,
type RegionalMoney,
} from '../../shared/regionalMoney';
@@ -25,7 +24,7 @@ export function useSessionSpend(
const initial =
normalizeRegionalMoney(initialMoney) ??
(typeof initialCostUsd === 'number'
- ? regionalizeLegacyUsd(initialCostUsd, CURRENT_CINDY_REGION)
+ ? legacyUsdMoney(initialCostUsd)
: null);
const [money, setMoney] = useState<RegionalMoney | null>(
initial,
@@ -36,7 +35,7 @@ export function useSessionSpend(
setMoney(
normalizeRegionalMoney(initialMoney) ??
(typeof initialCostUsd === 'number'
- ? regionalizeLegacyUsd(initialCostUsd, CURRENT_CINDY_REGION)
+ ? legacyUsdMoney(initialCostUsd)
: null),
);
}, [sessionId, initialMoney, initialCostUsd]);
@@ -48,10 +47,7 @@ export function useSessionSpend(
setMoney(
normalizeRegionalMoney(res.totalMoney) ??
(typeof res.totalCostUsd === 'number'
- ? regionalizeLegacyUsd(
- res.totalCostUsd,
- CURRENT_CINDY_REGION,
- )
+ ? legacyUsdMoney(res.totalCostUsd)
: null),
);
}
diff --git a/apps/desktop/src/renderer/hooks/useTodaySpend.ts b/apps/desktop/src/renderer/hooks/useTodaySpend.ts
index fe72e30d8e..6b749e5497 100644
--- a/apps/desktop/src/renderer/hooks/useTodaySpend.ts
+++ b/apps/desktop/src/renderer/hooks/useTodaySpend.ts
@@ -15,10 +15,9 @@
*/
import { useEffect, useState } from 'react';
-import { CURRENT_CINDY_REGION } from '../../shared/brandRegion';
import {
+ legacyUsdMoney,
normalizeRegionalMoney,
- regionalizeLegacyUsd,
type RegionalMoney,
} from '../../shared/regionalMoney';
@@ -54,10 +53,7 @@ export function useTodaySpend(): TodaySpendData {
const money =
normalizeRegionalMoney(res.money) ??
(typeof res.costUsd === 'number'
- ? regionalizeLegacyUsd(
- res.costUsd,
- CURRENT_CINDY_REGION,
- )
+ ? legacyUsdMoney(res.costUsd)
: null);
setData((prev) => ({
day: res.day,
@@ -90,10 +86,7 @@ export function useTodaySpend(): TodaySpendData {
const money =
normalizeRegionalMoney(res.money) ??
(typeof res.costUsd === 'number'
- ? regionalizeLegacyUsd(
- res.costUsd,
- CURRENT_CINDY_REGION,
- )
+ ? legacyUsdMoney(res.costUsd)
: null);
setData((prev) => ({
day: res.day,
diff --git a/apps/desktop/src/renderer/hooks/useUsageHistory.ts b/apps/desktop/src/renderer/hooks/useUsageHistory.ts
index 714b2880a6..413a91fd19 100644
--- a/apps/desktop/src/renderer/hooks/useUsageHistory.ts
+++ b/apps/desktop/src/renderer/hooks/useUsageHistory.ts
@@ -21,15 +21,13 @@
*/
import { useEffect, useState } from 'react';
-import { CURRENT_CINDY_REGION } from '../../shared/brandRegion';
import {
addCompatibleRegionalMoney,
+ legacyUsdMoney,
normalizeRegionalMoney,
- regionalCurrencyForRegion,
- regionalizeLegacyUsd,
- regionalizeUsd,
+ usdMoney,
+ zeroUsageMoney,
type RegionalMoney,
- zeroRegionalMoney,
} from '../../shared/regionalMoney';
export interface UsageHistoryModel {
@@ -83,7 +81,10 @@ const REFRESH_DEBOUNCE_MS = 2000;
const PRICING_RETRY_DELAY_MS = 6000;
/** main 返回 stale 磁盘快照时的补拉延迟: 让后台聚合先完成, 同时保持更新感知。 */
const STALE_RETRY_DELAY_MS = 800;
-const SNAPSHOT_STORAGE_KEY = 'homeUsageDashboard.lastPayload';
+// v2 后缀:币种语义改为跟随来源(默认 USD)后,旧构建快照里的金额可能带错标
+// CNY——直接换 key 让旧快照失效,首帧宁可空态也不闪现错单位;旧 key 顺手清理。
+const SNAPSHOT_STORAGE_KEY = 'homeUsageDashboard.lastPayload.v2';
+const LEGACY_SNAPSHOT_STORAGE_KEY = 'homeUsageDashboard.lastPayload';
const DEFAULT_SCOPE_KEY = 'anonymous';
function storageKeyForScope(scopeKey: string): string {
@@ -146,6 +147,9 @@ function isAgentKind(value: unknown): value is UsageHistoryModel['agentKind'] {
function readSnapshot(scopeKey: string): UsageHistoryPayload | null {
try {
+ localStorage.removeItem(
+ `${LEGACY_SNAPSHOT_STORAGE_KEY}.${encodeURIComponent(scopeKey)}`,
+ );
const raw = localStorage.getItem(storageKeyForScope(scopeKey));
if (!raw) return null;
const parsed = JSON.parse(raw) as StoredUsageHistoryPayload;
@@ -170,17 +174,12 @@ function readSnapshot(scopeKey: string): UsageHistoryPayload | null {
const anomaly = parsed.anomaly as Record<string, unknown>;
const legacyActual = (value: unknown): RegionalMoney =>
typeof value === 'number' && Number.isFinite(value) && value >= 0
- ? regionalizeLegacyUsd(value, CURRENT_CINDY_REGION)
- : zeroRegionalMoney(CURRENT_CINDY_REGION);
+ ? legacyUsdMoney(value)
+ : zeroUsageMoney();
const legacyEstimate = (value: unknown): RegionalMoney =>
typeof value === 'number' && Number.isFinite(value) && value >= 0
- ? regionalizeUsd(
- value,
- CURRENT_CINDY_REGION,
- 'subscription-value',
- 'value-estimate',
- )
- : zeroRegionalMoney(CURRENT_CINDY_REGION, 'value-estimate');
+ ? usdMoney(value, 'value-estimate', 'subscription-value')
+ : zeroUsageMoney('value-estimate');
const days = (parsed.days as StoredUsageHistoryDay[])
.filter((row) => typeof row?.day === 'string')
@@ -242,7 +241,6 @@ function readSnapshot(scopeKey: string): UsageHistoryPayload | null {
(last30DaysEstimatedValue.amount > 0
? (addCompatibleRegionalMoney(
[last30Days, last30DaysEstimatedValue],
- regionalCurrencyForRegion(CURRENT_CINDY_REGION),
) ?? last30Days)
: last30Days);
const trailing7DayAvg =
diff --git a/apps/desktop/src/renderer/lib/__tests__/turnUsageTooltip.test.ts b/apps/desktop/src/renderer/lib/__tests__/turnUsageTooltip.test.ts
index 365b7799df..eb4dcdff1f 100644
--- a/apps/desktop/src/renderer/lib/__tests__/turnUsageTooltip.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/turnUsageTooltip.test.ts
@@ -69,7 +69,7 @@ describe('buildTurnUsageTooltipLines — 按模型成本明细', () => {
(l) =>
l.startsWith('usageDetails.modelCostLine') &&
l.includes('Opus 4.8') &&
- l.includes('¥6.30'),
+ l.includes('$0.94'),
),
).toBe(true);
expect(
@@ -77,7 +77,7 @@ describe('buildTurnUsageTooltipLines — 按模型成本明细', () => {
(l) =>
l.startsWith('usageDetails.modelCostLine') &&
l.includes('Haiku 4.5') &&
- l.includes('¥5.36'),
+ l.includes('$0.80'),
),
).toBe(true);
expect(out.some((l) => l.startsWith('usageDetails.modelLine'))).toBe(false);
@@ -152,21 +152,19 @@ describe('normalizeTurnUsageDetails — perModelCost 往返 / 清洗', () => {
{
model: 'claude-opus-4-8',
money: {
- amount: expect.closeTo(6.298, 10),
- currency: 'CNY',
- approximate: true,
+ amount: expect.closeTo(0.94, 10),
+ currency: 'USD',
+ approximate: false,
kind: 'actual-cost',
- estimateReasons: ['fixed-fx', 'legacy-usd'],
},
},
{
model: 'claude-haiku-4-5',
money: {
- amount: expect.closeTo(5.36, 10),
- currency: 'CNY',
- approximate: true,
+ amount: expect.closeTo(0.8, 10),
+ currency: 'USD',
+ approximate: false,
kind: 'actual-cost',
- estimateReasons: ['fixed-fx', 'legacy-usd'],
},
},
]);
@@ -185,11 +183,10 @@ describe('normalizeTurnUsageDetails — perModelCost 往返 / 清洗', () => {
{
model: 'claude-opus-4-8',
money: {
- amount: expect.closeTo(6.03, 10),
- currency: 'CNY',
- approximate: true,
+ amount: expect.closeTo(0.9, 10),
+ currency: 'USD',
+ approximate: false,
kind: 'actual-cost',
- estimateReasons: ['fixed-fx', 'legacy-usd'],
},
},
]);
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 72a2f823d7..328fb87532 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -87,10 +87,9 @@ import {
} from '@/lib/issueConfirmPayload';
import { resolveStaleCodexSubscriptionValueEstimate } from '../../shared/codexSubscriptionValue';
import { normalizeTurnUsageDetails, type TurnUsageDetails } from '../../shared/turnUsageDetails';
-import { CURRENT_CINDY_REGION } from '../../shared/brandRegion';
import {
+ legacyUsdMoney,
normalizeRegionalMoney,
- regionalizeLegacyUsd,
type RegionalMoney,
} from '../../shared/regionalMoney';
import type { PersistedSessionReferenceMetadata } from '../../shared/sessionReferenceMetadata';
@@ -3945,14 +3944,14 @@ function initGlobalListeners(): void {
const turnMoney =
normalizedTurnMoney ??
(legacyTurnCostUsd !== undefined
- ? regionalizeLegacyUsd(legacyTurnCostUsd, CURRENT_CINDY_REGION)
+ ? legacyUsdMoney(legacyTurnCostUsd)
: undefined);
if (!turnMoney || !(turnMoney.amount > 0)) return;
const { sessionId, clientId } = p;
const userTurnMoney =
normalizeRegionalMoney(p.userTurnMoney) ??
(typeof p.userTurnCostUsd === 'number' && p.userTurnCostUsd > 0
- ? regionalizeLegacyUsd(p.userTurnCostUsd, CURRENT_CINDY_REGION)
+ ? legacyUsdMoney(p.userTurnCostUsd)
: undefined);
const userTurnCostUsd =
typeof p.userTurnCostUsd === 'number' && p.userTurnCostUsd > 0
@@ -4074,10 +4073,7 @@ function initGlobalListeners(): void {
(typeof p?.totalCostUsd === 'number' &&
Number.isFinite(p.totalCostUsd) &&
p.totalCostUsd >= 0
- ? regionalizeLegacyUsd(
- p.totalCostUsd,
- CURRENT_CINDY_REGION,
- )
+ ? legacyUsdMoney(p.totalCostUsd)
: undefined);
if (push.deviceId && p?.sessionId && totalMoney) {
remoteProjectsStore.applyPatch(push.deviceId, p.sessionId, {
@@ -8590,7 +8586,7 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {
m.role === 'assistant'
? normalizedTurnMoney ??
(legacyTurnCostUsd !== undefined
- ? regionalizeLegacyUsd(legacyTurnCostUsd, CURRENT_CINDY_REGION)
+ ? legacyUsdMoney(legacyTurnCostUsd)
: undefined)
: undefined;
return {
@@ -8623,10 +8619,7 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {
normalizeRegionalMoney(agentMeta.userTurnCost) ??
(typeof agentMeta.userTurnCostUsd === 'number' &&
agentMeta.userTurnCostUsd > 0
- ? regionalizeLegacyUsd(
- agentMeta.userTurnCostUsd,
- CURRENT_CINDY_REGION,
- )
+ ? legacyUsdMoney(agentMeta.userTurnCostUsd)
: undefined);
return {
turnMoney: persistedTurnMoney,
@@ -8742,7 +8735,7 @@ function projectLegacyUserTurnCosts(
(typeof meta.userTurnCostUsd !== 'number' || !(meta.userTurnCostUsd > 0))
) {
projected.set(message.clientId, {
- userTurnMoney: regionalizeLegacyUsd(costUsd, CURRENT_CINDY_REGION),
+ userTurnMoney: legacyUsdMoney(costUsd),
userTurnCostUsd: costUsd,
userTurnCostIsEstimate: hasEstimatedValue,
});
diff --git a/apps/desktop/src/shared/__tests__/modelPriceQuote.test.ts b/apps/desktop/src/shared/__tests__/modelPriceQuote.test.ts
new file mode 100644
index 0000000000..08b0f0df4f
--- /dev/null
+++ b/apps/desktop/src/shared/__tests__/modelPriceQuote.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ModelAccessGatewayModel } from '../modelAccess.js';
+import {
+ gatewayPricingCatalog,
+ resolveGatewayCatalogCurrency,
+} from '../modelPriceQuote.js';
+
+function model(
+ id: string,
+ overrides: Partial<ModelAccessGatewayModel> = {},
+): ModelAccessGatewayModel {
+ return {
+ id,
+ inputCostPerToken: 0.000002,
+ outputCostPerToken: 0.000008,
+ ...overrides,
+ };
+}
+
+describe('resolveGatewayCatalogCurrency', () => {
+ it('defaults to gateway-native USD when nothing is declared', () => {
+ expect(resolveGatewayCatalogCurrency([model('a'), model('b')])).toBe('USD');
+ expect(resolveGatewayCatalogCurrency([])).toBe('USD');
+ });
+
+ it('switches only when every entry explicitly declares the same non-USD currency', () => {
+ expect(
+ resolveGatewayCatalogCurrency([
+ model('a', { currency: 'CNY' }),
+ model('b', { currency: 'CNY' }),
+ ]),
+ ).toBe('CNY');
+ });
+
+ it('keeps undeclared entries USD — a partial CNY declaration never flips the catalog', () => {
+ expect(
+ resolveGatewayCatalogCurrency([
+ model('a', { currency: 'CNY' }),
+ model('b'),
+ ]),
+ ).toBe('USD');
+ });
+
+ it('treats mixed declarations as USD — local ledgers are single-currency', () => {
+ expect(
+ resolveGatewayCatalogCurrency([
+ model('a', { currency: 'CNY' }),
+ model('b', { currency: 'USD' }),
+ ]),
+ ).toBe('USD');
+ });
+
+ it('ignores invalid declaration values', () => {
+ expect(
+ resolveGatewayCatalogCurrency([
+ model('a', { currency: 'EUR' as unknown as 'USD' }),
+ ]),
+ ).toBe('USD');
+ });
+});
+
+describe('gatewayPricingCatalog currency', () => {
+ it('drops conflicting declared entries instead of relabeling their prices', () => {
+ const catalog = gatewayPricingCatalog([
+ model('a', { currency: 'CNY' }),
+ model('b', { currency: 'USD' }),
+ model('c'),
+ ]);
+ expect(Object.keys(catalog.xd)).toEqual(['b', 'c']);
+ expect(Object.values(catalog.xd).map((quote) => quote.currency)).toEqual([
+ 'USD',
+ 'USD',
+ ]);
+ });
+
+ it('labels every quote with the catalog currency when all entries declare it', () => {
+ const catalog = gatewayPricingCatalog([
+ model('a', { currency: 'CNY' }),
+ model('b', { currency: 'CNY' }),
+ ]);
+ expect(Object.values(catalog.xd).map((quote) => quote.currency)).toEqual([
+ 'CNY',
+ 'CNY',
+ ]);
+ });
+
+ it('never relabels undeclared entries when a sibling declares CNY', () => {
+ const catalog = gatewayPricingCatalog([
+ model('a', { currency: 'CNY' }),
+ model('b'),
+ ]);
+ expect(Object.keys(catalog.xd)).toEqual(['b']);
+ expect(catalog.xd.b.currency).toBe('USD');
+ });
+});
diff --git a/apps/desktop/src/shared/__tests__/regionalMoney.test.ts b/apps/desktop/src/shared/__tests__/regionalMoney.test.ts
index e763d90c12..0e9bd65e44 100644
--- a/apps/desktop/src/shared/__tests__/regionalMoney.test.ts
+++ b/apps/desktop/src/shared/__tests__/regionalMoney.test.ts
@@ -4,62 +4,68 @@ import {
addCompatibleRegionalMoney,
addRegionalMoney,
asValueEstimateMoney,
+ DEFAULT_USAGE_CURRENCY,
+ gatewayCurrency,
gatewayMoney,
- regionalizeLegacyUsd,
- regionalizeUsd,
+ legacyUsdMoney,
+ usdMoney,
+ type RegionalMoney,
} from '../regionalMoney.js';
+const cnyActual = (amount: number): RegionalMoney => ({
+ amount,
+ currency: 'CNY',
+ approximate: false,
+ kind: 'actual-cost',
+});
+
describe('regional money', () => {
- it('keeps Gateway values exact and assigns the build-region currency', () => {
- expect(gatewayMoney(3, 'cn')).toEqual({
- amount: 3,
- currency: 'CNY',
- approximate: false,
- kind: 'actual-cost',
- });
- expect(gatewayMoney(3, 'global')).toEqual({
+ it('keeps Gateway values exact in the gateway-native USD unit by default', () => {
+ expect(gatewayMoney(3)).toEqual({
amount: 3,
currency: 'USD',
approximate: false,
kind: 'actual-cost',
});
+ expect(DEFAULT_USAGE_CURRENCY).toBe('USD');
});
- it('converts non-Gateway USD to CN at the fixed 6.7 rate and marks it approximate', () => {
- expect(regionalizeUsd(3, 'cn', 'fixed-fx')).toEqual({
- amount: 20.1,
+ it('honors a server-declared gateway currency instead of any build-region guess', () => {
+ expect(gatewayCurrency()).toBe('USD');
+ expect(gatewayCurrency(null)).toBe('USD');
+ expect(gatewayCurrency('CNY')).toBe('CNY');
+ expect(gatewayMoney(3, 'actual-cost', 'CNY')).toEqual({
+ amount: 3,
currency: 'CNY',
- approximate: true,
+ approximate: false,
kind: 'actual-cost',
- estimateReasons: ['fixed-fx'],
});
});
- it('keeps actual zero exact while preserving value-estimate semantics', () => {
- expect(regionalizeLegacyUsd(0, 'cn')).toEqual({
- amount: 0,
- currency: 'CNY',
+ it('never converts USD amounts — the unit travels with the data', () => {
+ expect(usdMoney(3)).toEqual({
+ amount: 3,
+ currency: 'USD',
approximate: false,
kind: 'actual-cost',
});
- expect(regionalizeUsd(0, 'cn', 'subscription-value', 'value-estimate')).toEqual({
- amount: 0,
- currency: 'CNY',
- approximate: true,
- kind: 'value-estimate',
- estimateReasons: ['subscription-value'],
+ expect(legacyUsdMoney(1)).toEqual({
+ amount: 1,
+ currency: 'USD',
+ approximate: false,
+ kind: 'actual-cost',
});
});
- it('keeps global USD facts exact but marks subscription values as estimates', () => {
- expect(regionalizeUsd(3, 'global', 'reference-price')).toEqual({
- amount: 3,
+ it('keeps actual zero exact while preserving value-estimate semantics', () => {
+ expect(legacyUsdMoney(0)).toEqual({
+ amount: 0,
currency: 'USD',
approximate: false,
kind: 'actual-cost',
});
- expect(regionalizeUsd(3, 'global', 'subscription-value', 'value-estimate')).toEqual({
- amount: 3,
+ expect(usdMoney(0, 'value-estimate', 'subscription-value')).toEqual({
+ amount: 0,
currency: 'USD',
approximate: true,
kind: 'value-estimate',
@@ -67,65 +73,68 @@ describe('regional money', () => {
});
});
- it('preserves legacy USD as a fact and only marks CN conversion approximate', () => {
- expect(regionalizeLegacyUsd(1, 'global')).toMatchObject({
- amount: 1,
+ it('marks subscription values as estimates and records the reason chain', () => {
+ expect(usdMoney(3, 'value-estimate', 'legacy-usd')).toEqual({
+ amount: 3,
currency: 'USD',
- approximate: false,
- });
- expect(regionalizeLegacyUsd(1, 'cn')).toMatchObject({
- amount: 6.7,
- currency: 'CNY',
approximate: true,
- estimateReasons: expect.arrayContaining(['fixed-fx', 'legacy-usd']),
+ kind: 'value-estimate',
+ estimateReasons: ['legacy-usd', 'subscription-value'],
});
});
it('propagates approximation and reasons while adding same-currency values', () => {
- const total = addRegionalMoney([gatewayMoney(3, 'cn'), regionalizeLegacyUsd(1, 'cn')]);
+ const total = addRegionalMoney([
+ gatewayMoney(3),
+ usdMoney(1, 'value-estimate', 'legacy-usd'),
+ ]);
expect(total).toMatchObject({
- amount: 9.7,
- currency: 'CNY',
+ amount: 4,
+ currency: 'USD',
approximate: true,
kind: 'actual-cost',
- estimateReasons: expect.arrayContaining(['fixed-fx', 'legacy-usd']),
+ estimateReasons: expect.arrayContaining(['legacy-usd', 'subscription-value']),
});
});
it('rejects mixed currencies instead of silently combining them', () => {
- expect(() => addRegionalMoney([gatewayMoney(1, 'cn'), gatewayMoney(1, 'global')])).toThrow(
+ expect(() => addRegionalMoney([cnyActual(1), gatewayMoney(1)])).toThrow(
/different currencies/,
);
});
it('keeps actual cost when an incompatible estimate is present on read', () => {
- const total = addCompatibleRegionalMoney(
- [
- gatewayMoney(3, 'cn'),
- regionalizeUsd(2, 'global', 'subscription-value', 'value-estimate'),
- ],
- 'USD',
- );
+ const staleCnyEstimate: RegionalMoney = {
+ amount: 2,
+ currency: 'CNY',
+ approximate: true,
+ kind: 'value-estimate',
+ estimateReasons: ['subscription-value'],
+ };
+ const total = addCompatibleRegionalMoney([gatewayMoney(3), staleCnyEstimate]);
- expect(total).toEqual(gatewayMoney(3, 'cn'));
+ expect(total).toEqual(gatewayMoney(3));
});
- it('prefers the current regional currency for mixed historical actual costs', () => {
- const total = addCompatibleRegionalMoney(
- [gatewayMoney(3, 'cn'), gatewayMoney(2, 'global')],
- 'USD',
- );
+ it('prefers the default usage currency for mixed historical actual costs', () => {
+ const total = addCompatibleRegionalMoney([cnyActual(3), gatewayMoney(2)]);
+
+ expect(total).toEqual(gatewayMoney(2));
+ });
+
+ it('falls back to the first actual currency when nothing matches the preference', () => {
+ const total = addCompatibleRegionalMoney([cnyActual(3), cnyActual(2)]);
- expect(total).toEqual(gatewayMoney(2, 'global'));
+ expect(total).toEqual(cnyActual(5));
});
it('marks subscription value without changing amount or currency', () => {
- expect(asValueEstimateMoney(regionalizeLegacyUsd(1, 'cn'))).toEqual({
- amount: 6.7,
- currency: 'CNY',
+ expect(asValueEstimateMoney(legacyUsdMoney(1))).toEqual({
+ amount: 1,
+ currency: 'USD',
approximate: true,
kind: 'value-estimate',
- estimateReasons: ['fixed-fx', 'legacy-usd', 'subscription-value'],
+ estimateReasons: ['subscription-value'],
});
});
});
diff --git a/apps/desktop/src/shared/modelAccess.ts b/apps/desktop/src/shared/modelAccess.ts
index 9b290f9756..356b341bfa 100644
--- a/apps/desktop/src/shared/modelAccess.ts
+++ b/apps/desktop/src/shared/modelAccess.ts
@@ -108,8 +108,9 @@ export interface ModelGroupTieredPricing {
/**
* model-access-server 从 AIGateway /model-groups 白名单透传的价格字段。
- * 字段名和单位保持 Gateway 原样(per token);Desktop 在构建 quote 时才转
- * per-million-token,并按构建区域赋予币种。
+ * 字段名和数值保持 Gateway 原样(per token);Desktop 在构建 quote 时才转
+ * per-million-token。币种以条目声明的 currency 为准,未声明按 Gateway 原生
+ * USD——绝不按构建区域改标或折算。
*/
export interface ModelGroupPricing {
costDiscount?: number;
@@ -152,6 +153,14 @@ export interface ModelGroupPricing {
export interface ModelAccessGatewayModel extends ModelGroupPricing {
id: string;
+ /**
+ * 本条目价格字段的计费币种声明(透传 Gateway)。缺省表示 Gateway 原生口径
+ * USD;客户端不得按构建区域改标或折算——单位永远跟随下发数据。
+ * 注意:本地记账账本是单币种的,只有**每个**条目都显式声明同一非 USD 币种
+ * 时目录才整体切换;与目录币种冲突的声明条目不出报价(费用退回 SDK 实报
+ * USD 兜底),见 modelPriceQuote.resolveGatewayCatalogCurrency。
+ */
+ currency?: 'USD' | 'CNY';
/** 进哪些 runtime tab;缺省 = 仅 claude-code(网关 /v1/messages 翻译覆盖面最广)。 */
agents?: ('claude-code' | 'codex')[];
name?: string;
diff --git a/apps/desktop/src/shared/modelPriceQuote.ts b/apps/desktop/src/shared/modelPriceQuote.ts
index 413f24815c..d0d679e085 100644
--- a/apps/desktop/src/shared/modelPriceQuote.ts
+++ b/apps/desktop/src/shared/modelPriceQuote.ts
@@ -1,13 +1,11 @@
-import type { CindyRegion } from '@cindy/maker-shared/brand-identity';
-
import { getClaudeSubscriptionValueFallbackPrice } from './claudeSubscriptionValue.js';
import { CODEX_SUBSCRIPTION_VALUE_PRICING } from './codexSubscriptionValue.js';
import type { ModelAccessGatewayModel } from './modelAccess.js';
import {
- gatewayCurrencyForRegion,
- USD_TO_CNY_FIXED_RATE,
+ GATEWAY_NATIVE_CURRENCY,
type ModelPriceQuote,
type ModelPricingCatalog,
+ type MoneyCurrency,
} from './regionalMoney.js';
import { CHATGPT_MODEL_PREFIX, XAI_MODEL_PREFIX } from './subscriptionModels.js';
@@ -51,9 +49,36 @@ function applyCodexBudgetDiscount(quote: ModelPriceQuote): ModelPriceQuote {
};
}
+function declaredCurrency(
+ model: ModelAccessGatewayModel,
+): MoneyCurrency | undefined {
+ return model.currency === 'USD' || model.currency === 'CNY'
+ ? model.currency
+ : undefined;
+}
+
+/**
+ * 目录级币种:本地记账账本(daily / session / schedule)都是单币种,逐条目
+ * 混用币种会造成同端多币种金额被聚合层丢弃。规则:
+ * - 未声明条目恒为 Gateway 原生 USD(契约缺省),绝不被其它条目的声明改标;
+ * - 只有当**每个**条目都显式声明同一非 USD 币种时,目录才整体切换;
+ * - 与目录币种冲突的声明条目由 gatewayPricingCatalog 丢弃报价(退回 SDK
+ * 实报 USD 兜底),而不是改标币种——错标单位正是本模块要杜绝的事。
+ */
+export function resolveGatewayCatalogCurrency(
+ models: readonly ModelAccessGatewayModel[],
+): MoneyCurrency {
+ if (models.length === 0) return GATEWAY_NATIVE_CURRENCY;
+ const first = declaredCurrency(models[0]);
+ if (!first || first === GATEWAY_NATIVE_CURRENCY) return GATEWAY_NATIVE_CURRENCY;
+ return models.every((model) => declaredCurrency(model) === first)
+ ? first
+ : GATEWAY_NATIVE_CURRENCY;
+}
+
export function gatewayModelPriceQuote(
model: ModelAccessGatewayModel,
- region: CindyRegion,
+ currency: MoneyCurrency = GATEWAY_NATIVE_CURRENCY,
): ModelPriceQuote | undefined {
const modelId = model.id.trim();
const inputPerMtok = perMtok(model.inputCostPerToken);
@@ -73,10 +98,11 @@ export function gatewayModelPriceQuote(
}
// quote 是用量估算用的标准价;costDiscount 只在 effectiveGatewayModelCost 侧应用到
// cost,UI 展示价一致时取 cost(见 modelPriceFormat),不再并排展示标准价。
+ // 币种由 resolveGatewayCatalogCurrency 目录级统一解析后传入;不按构建区域改标。
return applyCodexBudgetDiscount({
providerId: 'xd',
modelId,
- currency: gatewayCurrencyForRegion(region),
+ currency,
source: 'gateway',
approximate: false,
inputPerMtok,
@@ -88,11 +114,15 @@ export function gatewayModelPriceQuote(
export function gatewayPricingCatalog(
models: readonly ModelAccessGatewayModel[],
- region: CindyRegion,
): ModelPricingCatalog {
+ const currency = resolveGatewayCatalogCurrency(models);
const xd: Record<string, ModelPriceQuote> = {};
for (const model of models) {
- const quote = gatewayModelPriceQuote(model, region);
+ // 声明与目录币种冲突的条目不出报价:宁可让该模型的单轮费用退回 SDK
+ // 实报 USD 兜底,也不给它标一个和价格数值不匹配的单位。
+ const declared = declaredCurrency(model);
+ if (declared && declared !== currency) continue;
+ const quote = gatewayModelPriceQuote(model, currency);
if (quote) xd[quote.modelId] = quote;
}
return Object.keys(xd).length > 0 ? { xd } : {};
@@ -189,28 +219,3 @@ export function subscriptionDirectPriceQuote(
return undefined;
}
-export function regionalizeModelPriceQuote(
- quote: ModelPriceQuote,
- region: CindyRegion,
-): ModelPriceQuote {
- if (region === 'global' || quote.currency === 'CNY') return quote;
- return {
- ...quote,
- currency: 'CNY',
- approximate: true,
- inputPerMtok: quote.inputPerMtok * USD_TO_CNY_FIXED_RATE,
- outputPerMtok: quote.outputPerMtok * USD_TO_CNY_FIXED_RATE,
- ...(quote.cacheReadPerMtok !== undefined
- ? {
- cacheReadPerMtok:
- quote.cacheReadPerMtok * USD_TO_CNY_FIXED_RATE,
- }
- : {}),
- ...(quote.cacheCreatePerMtok !== undefined
- ? {
- cacheCreatePerMtok:
- quote.cacheCreatePerMtok * USD_TO_CNY_FIXED_RATE,
- }
- : {}),
- };
-}
diff --git a/apps/desktop/src/shared/regionalMoney.ts b/apps/desktop/src/shared/regionalMoney.ts
index 8b5e0d987d..cfb26985c6 100644
--- a/apps/desktop/src/shared/regionalMoney.ts
+++ b/apps/desktop/src/shared/regionalMoney.ts
@@ -1,10 +1,16 @@
-import type { CindyRegion } from '@cindy/maker-shared/brand-identity';
-
export type MoneyCurrency = 'CNY' | 'USD';
export type MoneyKind = 'actual-cost' | 'value-estimate';
export type MoneyEstimateReason =
'fixed-fx' | 'legacy-usd' | 'subscription-value' | 'reference-price';
+/**
+ * 用量/费用金额永远携带自己的币种(单位跟随数据来源,构建区域不参与):
+ * - Gateway(LiteLLM)同步的 spend / 价格数值原生口径是 USD;服务端未声明币种时
+ * 一律按 USD 记账与展示,绝不按区域改标或按固定汇率折算。
+ * - 服务端将来在契约里声明币种(如 model-groups 条目的 currency 字段)时,以声明为准。
+ * - CNY 只会来自「来源本身就是 CNY」的金额;历史上被错标/折算的 CNY 数据由
+ * migration 0081 修复,读侧仍保留跨币种兼容(device-link 对端可能是旧版本)。
+ */
export interface RegionalMoney {
amount: number;
currency: MoneyCurrency;
@@ -27,8 +33,21 @@ export interface ModelPriceQuote {
export type ModelPricingCatalog = Record<string, Record<string, ModelPriceQuote>>;
+/**
+ * 仅供读取历史数据兼容用:2026-07 曾按此固定汇率把 USD 金额折算成 CNY 落盘/投影,
+ * 逆推这批历史数据时使用。禁止再用它产生新的折算金额。
+ */
export const USD_TO_CNY_FIXED_RATE = 6.7;
+/** Gateway 未声明币种时的原生记账单位(LiteLLM spend / per-token 价格口径)。 */
+export const GATEWAY_NATIVE_CURRENCY: MoneyCurrency = 'USD';
+
+/**
+ * 零值与读侧聚合 preferred 的默认币种。与 Gateway 原生单位一致;当前所有金额
+ * 来源(Gateway 价格、LiteLLM spend、订阅参考价)都是 USD。
+ */
+export const DEFAULT_USAGE_CURRENCY: MoneyCurrency = 'USD';
+
function assertAmount(amount: number): void {
if (!Number.isFinite(amount) || amount < 0) {
throw new Error(`invalid non-negative money amount: ${String(amount)}`);
@@ -42,63 +61,61 @@ function uniqueReasons(
return out.length > 0 ? out : undefined;
}
-export function gatewayCurrencyForRegion(region: CindyRegion): MoneyCurrency {
- return region === 'global' ? 'USD' : 'CNY';
+/** Gateway 金额的币种:以服务端声明为准,未声明按原生 USD。 */
+export function gatewayCurrency(
+ declared?: MoneyCurrency | null,
+): MoneyCurrency {
+ return declared ?? GATEWAY_NATIVE_CURRENCY;
}
-export function regionalCurrencyForRegion(region: CindyRegion): MoneyCurrency {
- return gatewayCurrencyForRegion(region);
-}
-
-export function zeroRegionalMoney(
- region: CindyRegion,
- kind: MoneyKind = 'actual-cost',
-): RegionalMoney {
+export function zeroUsageMoney(kind: MoneyKind = 'actual-cost'): RegionalMoney {
return {
amount: 0,
- currency: regionalCurrencyForRegion(region),
+ currency: DEFAULT_USAGE_CURRENCY,
approximate: kind === 'value-estimate',
kind,
...(kind === 'value-estimate' ? { estimateReasons: ['subscription-value'] } : {}),
};
}
-export function regionalizeUsd(
+/**
+ * 把一笔 USD 金额包成 RegionalMoney,单位保持 USD 不折算。
+ * actual-cost 是精确事实;value-estimate 按估算标记 approximate 并记录原因。
+ */
+export function usdMoney(
amountUsd: number,
- region: CindyRegion,
- reason: MoneyEstimateReason,
kind: MoneyKind = 'actual-cost',
+ reason?: MoneyEstimateReason,
): RegionalMoney {
assertAmount(amountUsd);
- const convert = region !== 'global';
- const approximateConversion = convert && amountUsd !== 0;
- const approximate = approximateConversion || kind === 'value-estimate';
+ const approximate = kind === 'value-estimate';
const estimateReasons = approximate
- ? uniqueReasons([
- approximateConversion ? 'fixed-fx' : undefined,
- reason,
- kind === 'value-estimate' ? 'subscription-value' : undefined,
- ])
+ ? uniqueReasons([reason, 'subscription-value'])
: undefined;
return {
- amount: convert ? amountUsd * USD_TO_CNY_FIXED_RATE : amountUsd,
- currency: convert ? 'CNY' : 'USD',
+ amount: amountUsd,
+ currency: 'USD',
approximate,
kind,
...(estimateReasons ? { estimateReasons } : {}),
};
}
+/** 旧 *_usd 列/字段(单位本来就是 USD)的读侧投影。 */
+export function legacyUsdMoney(amountUsd: number): RegionalMoney {
+ return usdMoney(amountUsd);
+}
+
export function gatewayMoney(
amount: number,
- region: CindyRegion,
kind: MoneyKind = 'actual-cost',
+ declaredCurrency?: MoneyCurrency | null,
): RegionalMoney {
assertAmount(amount);
const approximate = kind === 'value-estimate';
return {
amount,
- currency: gatewayCurrencyForRegion(region),
+ currency: gatewayCurrency(declaredCurrency),
approximate,
kind,
...(approximate ? { estimateReasons: ['subscription-value'] } : {}),
@@ -127,13 +144,14 @@ export function addRegionalMoney(values: readonly RegionalMoney[]): RegionalMone
* Read-side compatibility for persisted/history projections.
*
* Writers must keep using addRegionalMoney() so currency drift is rejected.
- * Readers may encounter stale mixed-currency data after a region change. In
- * that case actual cost determines the currency before estimates, and the
- * preferred regional currency wins when multiple actual currencies exist.
+ * Readers may encounter stale mixed-currency data (pre-0081 local rows or a
+ * device-link peer on an older build). In that case actual cost determines the
+ * currency before estimates, and the preferred currency wins when multiple
+ * actual currencies exist.
*/
export function addCompatibleRegionalMoney(
values: readonly RegionalMoney[],
- preferredCurrency: MoneyCurrency,
+ preferredCurrency: MoneyCurrency = DEFAULT_USAGE_CURRENCY,
): RegionalMoney | null {
if (values.length === 0) return null;
const actualValues = values.filter((value) => value.kind === 'actual-cost');
@@ -155,15 +173,6 @@ export function asValueEstimateMoney(money: RegionalMoney): RegionalMoney {
};
}
-export function regionalizeLegacyUsd(amountUsd: number, region: CindyRegion): RegionalMoney {
- return regionalizeUsd(amountUsd, region, 'legacy-usd');
-}
-
-export function regionalAmountFromUsdReference(amountUsd: number, region: CindyRegion): number {
- assertAmount(amountUsd);
- return region === 'global' ? amountUsd : amountUsd * USD_TO_CNY_FIXED_RATE;
-}
-
export function normalizeRegionalMoney(value: unknown): RegionalMoney | undefined {
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
const raw = value as Partial<RegionalMoney>;
diff --git a/apps/desktop/src/shared/turnUsageDetails.ts b/apps/desktop/src/shared/turnUsageDetails.ts
index 089b994135..972c949f54 100644
--- a/apps/desktop/src/shared/turnUsageDetails.ts
+++ b/apps/desktop/src/shared/turnUsageDetails.ts
@@ -3,12 +3,10 @@
* message. Stored in messages.agent_meta so old DB schema stays unchanged.
*/
-import { CURRENT_CINDY_REGION } from './brandRegion.js';
import {
addCompatibleRegionalMoney,
+ legacyUsdMoney,
normalizeRegionalMoney,
- regionalCurrencyForRegion,
- regionalizeLegacyUsd,
type RegionalMoney,
} from './regionalMoney.js';
@@ -89,7 +87,7 @@ function sanitizePerModelCost(
const structured = normalizeRegionalMoney(item.money);
const legacy =
typeof item.costUsd === 'number' && Number.isFinite(item.costUsd) && item.costUsd > 0
- ? regionalizeLegacyUsd(item.costUsd, CURRENT_CINDY_REGION)
+ ? legacyUsdMoney(item.costUsd)
: undefined;
const money = structured ?? legacy;
if (!model || !money || money.amount <= 0) continue;
@@ -97,10 +95,7 @@ function sanitizePerModelCost(
byModel.set(
model,
current
- ? (addCompatibleRegionalMoney(
- [current, money],
- regionalCurrencyForRegion(CURRENT_CINDY_REGION),
- ) ?? money)
+ ? (addCompatibleRegionalMoney([current, money]) ?? money)
: money,
);
}