Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 统一模型价格源与区域金额展示 (#353)
GaoWei Liu5b71e8b25074
diff --git a/apps/desktop/drizzle/0080_regional_money.sql b/apps/desktop/drizzle/0080_regional_money.sqlnew file mode 100644index 0000000000..e0ac49d1ec--- /dev/null+++ b/apps/desktop/drizzle/0080_regional_money.sql@@ -0,0 +1 @@+SELECT 1;diff --git a/apps/desktop/drizzle/meta/0080_snapshot.json b/apps/desktop/drizzle/meta/0080_snapshot.jsonnew file mode 100644index 0000000000..2e79c6590a--- /dev/null+++ b/apps/desktop/drizzle/meta/0080_snapshot.json@@ -0,0 +1,3140 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "bc9927bd-878c-4d47-9840-d8c3db30a439",+ "prevId": "a3e0f0f5-f96d-49f7-a1cb-b5dbce2b2324",+ "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",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "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",+ "tableTo": "sessions",+ "columnsFrom": [+ "target_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "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",+ "tableTo": "media_blobs",+ "columnsFrom": [+ "hash"+ ],+ "columnsTo": [+ "hash"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "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",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "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"+ ],+ "isUnique": true,+ "where": "\"orca_teams\".\"status\" = 'active'"+ },+ "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",+ "tableTo": "sessions",+ "columnsFrom": [+ "lead_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "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",+ "tableTo": "orca_teams",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "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"+ ],+ "isUnique": true,+ "where": "\"orca_workers\".\"focused\" = 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",+ "tableTo": "orca_teams",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "orca_workers_session_id_sessions_id_fk": {+ "name": "orca_workers_session_id_sessions_id_fk",+ "tableFrom": "orca_workers",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "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",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "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",+ "tableTo": "schedules",+ "columnsFrom": [+ "schedule_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "schedule_runs_session_id_sessions_id_fk": {+ "name": "schedule_runs_session_id_sessions_id_fk",+ "tableFrom": "schedule_runs",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "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",+ "tableTo": "sessions",+ "columnsFrom": [+ "target_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "schedules_skip_log_session_id_sessions_id_fk": {+ "name": "schedules_skip_log_session_id_sessions_id_fk",+ "tableFrom": "schedules",+ "tableTo": "sessions",+ "columnsFrom": [+ "skip_log_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "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",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "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",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "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",+ "tableTo": "sessions",+ "columnsFrom": [+ "parent_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "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",+ "tableTo": "skill_usage_sources",+ "columnsFrom": [+ "raw_file_path"+ ],+ "columnsTo": [+ "raw_file_path"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "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": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "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 filediff --git a/apps/desktop/drizzle/meta/_journal.json b/apps/desktop/drizzle/meta/_journal.jsonindex dc42f5c405..8d4242f080 100644--- a/apps/desktop/drizzle/meta/_journal.json+++ b/apps/desktop/drizzle/meta/_journal.json@@ -561,6 +561,13 @@"when": 1784689259586,"tag": "0079_futuristic_hercules","breakpoints": true+ },+ {+ "idx": 80,+ "version": "6",+ "when": 1784917033887,+ "tag": "0080_regional_money",+ "breakpoints": true}]}\ No newline at end of filediff --git a/apps/desktop/drizzle/scripts/0080_regional_money.ts b/apps/desktop/drizzle/scripts/0080_regional_money.tsnew file mode 100644index 0000000000..3414cb47e8--- /dev/null+++ b/apps/desktop/drizzle/scripts/0080_regional_money.ts@@ -0,0 +1,103 @@+import type Database from 'better-sqlite3';++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 addColumnIfMissing(+ db: Database.Database,+ tableName: string,+ columnName: string,+ definition: string,+): void {+ if (!tableExists(db, tableName)) return;+ const columns = tableColumnNames(db, tableName);+ if (!columns.has(columnName)) {+ db.exec(`ALTER TABLE ${tableName} ADD COLUMN ${columnName} ${definition}`);+ }+}++function run(db: Database.Database): void {+ addColumnIfMissing(+ db,+ 'sessions',+ 'total_cost_amount',+ 'real DEFAULT 0 NOT NULL',+ );+ addColumnIfMissing(db, 'sessions', 'total_cost_currency', 'text');+ addColumnIfMissing(+ db,+ 'sessions',+ 'total_cost_is_approximate',+ 'integer DEFAULT 0 NOT NULL',+ );++ addColumnIfMissing(+ db,+ 'daily_spend',+ 'cost_amount',+ 'real DEFAULT 0 NOT NULL',+ );+ addColumnIfMissing(db, 'daily_spend', 'cost_currency', 'text');+ addColumnIfMissing(+ db,+ 'daily_spend',+ 'cost_is_approximate',+ 'integer DEFAULT 0 NOT NULL',+ );++ addColumnIfMissing(+ db,+ 'daily_model_usage',+ 'cost_amount',+ 'real DEFAULT 0 NOT NULL',+ );+ addColumnIfMissing(db, 'daily_model_usage', 'cost_currency', 'text');+ addColumnIfMissing(+ db,+ 'daily_model_usage',+ 'cost_is_approximate',+ 'integer DEFAULT 0 NOT NULL',+ );++ addColumnIfMissing(+ db,+ 'schedule_runs',+ 'cost_amount',+ 'real DEFAULT 0 NOT NULL',+ );+ addColumnIfMissing(+ db,+ 'schedule_runs',+ 'estimated_value_amount',+ 'real DEFAULT 0 NOT NULL',+ );+ addColumnIfMissing(db, 'schedule_runs', 'cost_currency', 'text');+ addColumnIfMissing(+ db,+ 'schedule_runs',+ 'cost_is_approximate',+ 'integer DEFAULT 0 NOT NULL',+ );+}++module.exports = { run };diff --git a/apps/desktop/src/main/__tests__/claudeLocalSessions.test.ts b/apps/desktop/src/main/__tests__/claudeLocalSessions.test.tsindex 07d06dbaf9..0e69e9aaad 100644--- a/apps/desktop/src/main/__tests__/claudeLocalSessions.test.ts+++ b/apps/desktop/src/main/__tests__/claudeLocalSessions.test.ts@@ -67,6 +67,9 @@ function createLocalDb(): Database.Database {sdk_session_id TEXT,total_token_usage INTEGER NOT NULL DEFAULT 0,total_cost_usd REAL NOT NULL DEFAULT 0,+ total_cost_amount REAL NOT NULL DEFAULT 0,+ total_cost_currency TEXT,+ total_cost_is_approximate INTEGER NOT NULL DEFAULT 0,context_tokens INTEGER NOT NULL DEFAULT 0,context_window INTEGER NOT NULL DEFAULT 0,fast_mode INTEGER NOT NULL DEFAULT 0,@@ -120,8 +123,13 @@ function setLocalDb(db: Database.Database, userId = 'test-user'): void {setCurrentDbClient(makeTestDbClient(db), userId);}-function insertImportedClaudeSession(db: Database.Database, sessionId: string, sdkSessionId: string): void {- db.prepare(`+function insertImportedClaudeSession(+ db: Database.Database,+ sessionId: string,+ sdkSessionId: string,+): void {+ db.prepare(+ `INSERT INTO sessions (id, title, working_dir, model, effort, permission_mode, status,sdk_session_id, total_token_usage, total_cost_usd, context_tokens,@@ -135,7 +143,8 @@ function insertImportedClaudeSession(db: Database.Database, sessionId: string, s?, 0, 0, 0, 0, 0, NULL, NULL, 1,'cc', NULL, NULL, NULL, 'desktop', NULL, NULL, 0, '[]', 1, 1)- `).run(sessionId, sdkSessionId);+ `,+ ).run(sessionId, sdkSessionId);}function resetLocalDb(): void {@@ -145,12 +154,17 @@ function resetLocalDb(): void {describe('parseClaudeCodeMessageLine', () => {it('maps plain user text into XD user messages', () => {- const rows = parseClaudeCodeMessageLine(line({- type: 'user',- uuid: 'user-1',- parentUuid: null,- message: { role: 'user', content: '继续对战斗系统模拟器和文档的事情吧' },- }), 7, sdkSessionId, 'claude-sonnet-4-6');+ const rows = parseClaudeCodeMessageLine(+ line({+ type: 'user',+ uuid: 'user-1',+ parentUuid: null,+ message: { role: 'user', content: '继续对战斗系统模拟器和文档的事情吧' },+ }),+ 7,+ sdkSessionId,+ 'claude-sonnet-4-6',+ );expect(rows).toHaveLength(1);expect(rows[0]).toMatchObject({@@ -166,18 +180,23 @@ describe('parseClaudeCodeMessageLine', () => {it('removes complete IDE opened-file context blocks from imported user text', () => {const ideContextA = '<ide_opened_file>The user opened /tmp/a.ts in the IDE.</ide_opened_file>';const ideContextB = '<ide_opened_file>The user opened /tmp/b.ts in the IDE.</ide_opened_file>';- const rows = parseClaudeCodeMessageLine(line({- type: 'user',- uuid: 'user-ide-context',- message: {- role: 'user',- content: [- { type: 'text', text: `${ideContextA}\n${ideContextB}` },- { type: 'text', text: 'Please fix the parser' },- { type: 'text', text: ideContextA },- ],- },- }), 8, sdkSessionId, 'claude-sonnet-4-6');+ const rows = parseClaudeCodeMessageLine(+ line({+ type: 'user',+ uuid: 'user-ide-context',+ message: {+ role: 'user',+ content: [+ { type: 'text', text: `${ideContextA}\n${ideContextB}` },+ { type: 'text', text: 'Please fix the parser' },+ { type: 'text', text: ideContextA },+ ],+ },+ }),+ 8,+ sdkSessionId,+ 'claude-sonnet-4-6',+ );expect(rows).toHaveLength(1);expect(rows[0]).toMatchObject({@@ -187,20 +206,30 @@ describe('parseClaudeCodeMessageLine', () => {});it('skips IDE-only user messages but preserves malformed IDE tags', () => {- const ideOnly = parseClaudeCodeMessageLine(line({- type: 'user',- message: {- role: 'user',- content: '<ide_opened_file>The user opened /tmp/a.ts in the IDE.</ide_opened_file>',- },- }), 9, sdkSessionId, 'claude-sonnet-4-6');- const malformed = parseClaudeCodeMessageLine(line({- type: 'user',- message: {- role: 'user',- content: 'Keep this <ide_opened_file>unfinished context',- },- }), 10, sdkSessionId, 'claude-sonnet-4-6');+ const ideOnly = parseClaudeCodeMessageLine(+ line({+ type: 'user',+ message: {+ role: 'user',+ content: '<ide_opened_file>The user opened /tmp/a.ts in the IDE.</ide_opened_file>',+ },+ }),+ 9,+ sdkSessionId,+ 'claude-sonnet-4-6',+ );+ const malformed = parseClaudeCodeMessageLine(+ line({+ type: 'user',+ message: {+ role: 'user',+ content: 'Keep this <ide_opened_file>unfinished context',+ },+ }),+ 10,+ sdkSessionId,+ 'claude-sonnet-4-6',+ );expect(ideOnly).toEqual([]);expect(malformed).toHaveLength(1);@@ -208,21 +237,26 @@ describe('parseClaudeCodeMessageLine', () => {});it('maps assistant text, tool use, and thinking blocks into XD roles', () => {- const rows = parseClaudeCodeMessageLine(line({- type: 'assistant',- uuid: 'assistant-1',- message: {- id: 'msg_1',- model: 'claude-opus-4-7-20260501',- stop_reason: 'tool_use',- usage: { input_tokens: 10, output_tokens: 5, cache_read_input_tokens: 2 },- content: [- { type: 'thinking', thinking: 'check files' },- { type: 'tool_use', id: 'toolu_1', name: 'Read', input: { file_path: '/tmp/a.md' } },- { type: 'text', text: 'Done' },- ],- },- }), 8, sdkSessionId, 'claude-sonnet-4-6');+ const rows = parseClaudeCodeMessageLine(+ line({+ type: 'assistant',+ uuid: 'assistant-1',+ message: {+ id: 'msg_1',+ model: 'claude-opus-4-7-20260501',+ stop_reason: 'tool_use',+ usage: { input_tokens: 10, output_tokens: 5, cache_read_input_tokens: 2 },+ content: [+ { type: 'thinking', thinking: 'check files' },+ { type: 'tool_use', id: 'toolu_1', name: 'Read', input: { file_path: '/tmp/a.md' } },+ { type: 'text', text: 'Done' },+ ],+ },+ }),+ 8,+ sdkSessionId,+ 'claude-sonnet-4-6',+ );expect(rows.map((row) => row.role)).toEqual(['thinking', 'tool_use', 'assistant']);expect(rows[0].content).toEqual({ text: 'check files', durationMs: 0, isRedacted: false });@@ -242,16 +276,21 @@ describe('parseClaudeCodeMessageLine', () => {});it('keeps transcript parentage separate from tool/subagent parentage', () => {- const rows = parseClaudeCodeMessageLine(line({- type: 'assistant',- uuid: 'assistant-imported',- parentUuid: 'preceding-user-record',- message: {- id: 'msg_imported',- model: 'claude-sonnet-4-6',- content: [{ type: 'text', text: 'Imported answer' }],- },- }), 10, sdkSessionId, 'claude-sonnet-4-6');+ const rows = parseClaudeCodeMessageLine(+ line({+ type: 'assistant',+ uuid: 'assistant-imported',+ parentUuid: 'preceding-user-record',+ message: {+ id: 'msg_imported',+ model: 'claude-sonnet-4-6',+ content: [{ type: 'text', text: 'Imported answer' }],+ },+ }),+ 10,+ sdkSessionId,+ 'claude-sonnet-4-6',+ );expect(rows).toHaveLength(1);expect(rows[0].agentMeta).toMatchObject({@@ -263,17 +302,22 @@ describe('parseClaudeCodeMessageLine', () => {});it('preserves real tool parent metadata while also recording the transcript parent', () => {- const rows = parseClaudeCodeMessageLine(line({- type: 'assistant',- uuid: 'assistant-tool-owned',- parent_uuid: 'preceding-tool-result-record',- parent_tool_use_id: 'toolu_agent_1',- message: {- id: 'msg_tool_owned',- model: 'claude-sonnet-4-6',- content: [{ type: 'text', text: 'Subagent answer' }],- },- }), 11, sdkSessionId, 'claude-sonnet-4-6');+ const rows = parseClaudeCodeMessageLine(+ line({+ type: 'assistant',+ uuid: 'assistant-tool-owned',+ parent_uuid: 'preceding-tool-result-record',+ parent_tool_use_id: 'toolu_agent_1',+ message: {+ id: 'msg_tool_owned',+ model: 'claude-sonnet-4-6',+ content: [{ type: 'text', text: 'Subagent answer' }],+ },+ }),+ 11,+ sdkSessionId,+ 'claude-sonnet-4-6',+ );expect(rows).toHaveLength(1);expect(rows[0].agentMeta).toMatchObject({@@ -285,12 +329,17 @@ describe('parseClaudeCodeMessageLine', () => {});it('stores sourceToolAssistantUUID as transcript parent on user/tool records', () => {- const rows = parseClaudeCodeMessageLine(line({- type: 'user',- uuid: 'user-tool-result',- sourceToolAssistantUUID: 'source-assistant-uuid',- message: { content: [{ type: 'tool_result', tool_use_id: 'toolu_1', content: 'done' }] },- }), 12, sdkSessionId, 'claude-sonnet-4-6');+ const rows = parseClaudeCodeMessageLine(+ line({+ type: 'user',+ uuid: 'user-tool-result',+ sourceToolAssistantUUID: 'source-assistant-uuid',+ message: { content: [{ type: 'tool_result', tool_use_id: 'toolu_1', content: 'done' }] },+ }),+ 12,+ sdkSessionId,+ 'claude-sonnet-4-6',+ );expect(rows).toHaveLength(1);expect(rows[0].agentMeta).toMatchObject({@@ -302,37 +351,47 @@ describe('parseClaudeCodeMessageLine', () => {});it('normalizes opus-4-8 full model id to short form', () => {- const rows = parseClaudeCodeMessageLine(line({- type: 'assistant',- uuid: 'assistant-opus48',- message: {- id: 'msg_opus48',- model: 'claude-opus-4-8-20260601',- stop_reason: 'end_turn',- usage: { input_tokens: 1, output_tokens: 1 },- content: [{ type: 'text', text: 'ok' }],- },- }), 10, sdkSessionId, 'claude-sonnet-4-6');+ const rows = parseClaudeCodeMessageLine(+ line({+ type: 'assistant',+ uuid: 'assistant-opus48',+ message: {+ id: 'msg_opus48',+ model: 'claude-opus-4-8-20260601',+ stop_reason: 'end_turn',+ usage: { input_tokens: 1, output_tokens: 1 },+ content: [{ type: 'text', text: 'ok' }],+ },+ }),+ 10,+ sdkSessionId,+ 'claude-sonnet-4-6',+ );expect(rows).toHaveLength(1);expect(rows[0].agentMeta).toMatchObject({ model: 'claude-opus-4-8' });});it('maps Claude task notifications back to tool_result instead of user text', () => {- const rows = parseClaudeCodeMessageLine(line({- type: 'user',- uuid: 'task-result-1',- message: {- role: 'user',- content: [- '<task-notification>',- '<tool-use-id>toolu_task</tool-use-id>',- '<summary>Agent completed</summary>',- '<result>Subtask output</result>',- '</task-notification>',- ].join('\n'),- },- }), 9, sdkSessionId, 'claude-sonnet-4-6');+ const rows = parseClaudeCodeMessageLine(+ line({+ type: 'user',+ uuid: 'task-result-1',+ message: {+ role: 'user',+ content: [+ '<task-notification>',+ '<tool-use-id>toolu_task</tool-use-id>',+ '<summary>Agent completed</summary>',+ '<result>Subtask output</result>',+ '</task-notification>',+ ].join('\n'),+ },+ }),+ 9,+ sdkSessionId,+ 'claude-sonnet-4-6',+ );expect(rows).toHaveLength(1);expect(rows[0]).toMatchObject({@@ -343,18 +402,29 @@ describe('parseClaudeCodeMessageLine', () => {});it('skips subagent sidechains and local command synthetic user messages', () => {- const sidechain = parseClaudeCodeMessageLine(line({- type: 'user',- isSidechain: true,- message: { role: 'user', content: 'sidechain prompt' },- }), 10, sdkSessionId, 'claude-sonnet-4-6');- const command = parseClaudeCodeMessageLine(line({- type: 'user',- message: {- role: 'user',- content: '<command-name>/effort</command-name>\n<command-message>effort</command-message>',- },- }), 11, sdkSessionId, 'claude-sonnet-4-6');+ const sidechain = parseClaudeCodeMessageLine(+ line({+ type: 'user',+ isSidechain: true,+ message: { role: 'user', content: 'sidechain prompt' },+ }),+ 10,+ sdkSessionId,+ 'claude-sonnet-4-6',+ );+ const command = parseClaudeCodeMessageLine(+ line({+ type: 'user',+ message: {+ role: 'user',+ content:+ '<command-name>/effort</command-name>\n<command-message>effort</command-message>',+ },+ }),+ 11,+ sdkSessionId,+ 'claude-sonnet-4-6',+ );expect(sidechain).toEqual([]);expect(command).toEqual([]);@@ -365,25 +435,28 @@ describe('parseClaudeCodeMessageLine', () => {const projectDir = path.join(dir, '-Users-carol');fs.mkdirSync(projectDir, { recursive: true });const file = path.join(projectDir, `${sdkSessionId}.jsonl`);- fs.writeFileSync(file, [- line({- type: 'user',- uuid: 'user-home',- cwd: '/Users/carol',- message: { role: 'user', content: '<local-command-caveat>ignore</local-command-caveat>' },- }),- line({- type: 'system',- cwd: '/Users/carol/Projects/Github/ExampleOrg/cli-app',- subtype: 'turn_duration',- }),- line({- type: 'user',- uuid: 'user-project',- cwd: '/Users/carol/Projects/Github/ExampleOrg/cli-app',- message: { role: 'user', content: '继续写 V4 文档' },- }),- ].join('\n'));+ fs.writeFileSync(+ file,+ [+ line({+ type: 'user',+ uuid: 'user-home',+ cwd: '/Users/carol',+ message: { role: 'user', content: '<local-command-caveat>ignore</local-command-caveat>' },+ }),+ line({+ type: 'system',+ cwd: '/Users/carol/Projects/Github/ExampleOrg/cli-app',+ subtype: 'turn_duration',+ }),+ line({+ type: 'user',+ uuid: 'user-project',+ cwd: '/Users/carol/Projects/Github/ExampleOrg/cli-app',+ message: { role: 'user', content: '继续写 V4 文档' },+ }),+ ].join('\n'),+ );try {const summary = await readClaudeCodeSessionSummary(file);@@ -402,20 +475,23 @@ describe('parseClaudeCodeMessageLine', () => {const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'claude-ide-title-'));const file = path.join(dir, `${sdkSessionId}.jsonl`);const ideContext = '<ide_opened_file>The user opened /tmp/a.ts in the IDE.</ide_opened_file>';- fs.writeFileSync(file, [- line({- type: 'user',- uuid: 'user-ide-only',- cwd: '/tmp/project',- message: { role: 'user', content: ideContext },- }),- line({- type: 'user',- uuid: 'user-real-input',- cwd: '/tmp/project',- message: { role: 'user', content: `${ideContext}\nPlease fix the parser` },- }),- ].join('\n'));+ fs.writeFileSync(+ file,+ [+ line({+ type: 'user',+ uuid: 'user-ide-only',+ cwd: '/tmp/project',+ message: { role: 'user', content: ideContext },+ }),+ line({+ type: 'user',+ uuid: 'user-real-input',+ cwd: '/tmp/project',+ message: { role: 'user', content: `${ideContext}\nPlease fix the parser` },+ }),+ ].join('\n'),+ );try {const summary = await readClaudeCodeSessionSummary(file);@@ -433,18 +509,23 @@ describe('parseClaudeCodeMessageLine', () => {const projectsDir = path.join(home, '.claude', 'projects', '-tmp-project');fs.mkdirSync(projectsDir, { recursive: true });const file = path.join(projectsDir, `${sdkSessionId}.jsonl`);- fs.writeFileSync(file, `${line({- type: 'user',- uuid: 'user-1',- cwd: '/tmp/project',- message: { role: 'user', content: 'hello' },- })}\n`);+ fs.writeFileSync(+ file,+ `${line({+ type: 'user',+ uuid: 'user-1',+ cwd: '/tmp/project',+ message: { role: 'user', content: 'hello' },+ })}\n`,+ );const db = createLocalDb();insertImportedClaudeSession(db, `claude-${sdkSessionId}`, sdkSessionId);const homedir = vi.spyOn(os, 'homedir').mockReturnValue(home);- const tx = vi.fn(async (name: string, args: unknown) => runInprocTx(db, { name, args }) as never);+ const tx = vi.fn(+ async (name: string, args: unknown) => runInprocTx(db, { name, args }) as never,+ );vi.mocked(getRawDb).mockReturnValue(db);setCurrentDbClient({ ...makeTestDbClient(db), tx }, 'test-user');@@ -468,12 +549,15 @@ describe('parseClaudeCodeMessageLine', () => {const projectsDir = path.join(home, '.claude', 'projects', '-tmp-project');fs.mkdirSync(projectsDir, { recursive: true });const file = path.join(projectsDir, `${sdkSessionId}.jsonl`);- fs.writeFileSync(file, `${line({- type: 'user',- uuid: 'user-1',- cwd: '/tmp/project',- message: { role: 'user', content: 'hello' },- })}\n`);+ fs.writeFileSync(+ file,+ `${line({+ type: 'user',+ uuid: 'user-1',+ cwd: '/tmp/project',+ message: { role: 'user', content: 'hello' },+ })}\n`,+ );const dbA = createLocalDb();const dbB = createLocalDb();@@ -481,8 +565,12 @@ describe('parseClaudeCodeMessageLine', () => {insertImportedClaudeSession(dbB, `claude-${sdkSessionId}`, sdkSessionId);const homedir = vi.spyOn(os, 'homedir').mockReturnValue(home);- const txA = vi.fn(async (name: string, args: unknown) => runInprocTx(dbA, { name, args }) as never);- const txB = vi.fn(async (name: string, args: unknown) => runInprocTx(dbB, { name, args }) as never);+ const txA = vi.fn(+ async (name: string, args: unknown) => runInprocTx(dbA, { name, args }) as never,+ );+ const txB = vi.fn(+ async (name: string, args: unknown) => runInprocTx(dbB, { name, args }) as never,+ );try {vi.mocked(getRawDb).mockReturnValue(dbA);@@ -495,7 +583,9 @@ describe('parseClaudeCodeMessageLine', () => {await importExternalClaudeCodeMessagesForSession(`claude-${sdkSessionId}`);expect(txB).toHaveBeenCalledTimes(1);- const count = dbB.prepare('SELECT COUNT(*) AS count FROM messages').get() as { count: number };+ const count = dbB.prepare('SELECT COUNT(*) AS count FROM messages').get() as {+ count: number;+ };expect(count.count).toBe(1);} finally {homedir.mockRestore();@@ -511,15 +601,19 @@ describe('parseClaudeCodeMessageLine', () => {const projectsDir = path.join(home, '.claude', 'projects', '-tmp-project');fs.mkdirSync(projectsDir, { recursive: true });const file = path.join(projectsDir, `${sdkSessionId}.jsonl`);- fs.writeFileSync(file, `${line({- type: 'user',- uuid: 'user-1',- cwd: '/tmp/project',- message: { role: 'user', content: 'hello' },- })}\n`);+ fs.writeFileSync(+ file,+ `${line({+ type: 'user',+ uuid: 'user-1',+ cwd: '/tmp/project',+ message: { role: 'user', content: 'hello' },+ })}\n`,+ );const db = createLocalDb();- db.prepare(`+ db.prepare(+ `INSERT INTO sessions (id, title, working_dir, model, effort, permission_mode, status,sdk_session_id, total_token_usage, total_cost_usd, context_tokens,@@ -533,23 +627,27 @@ describe('parseClaudeCodeMessageLine', () => {?, 0, 0, 0, 0, 0, NULL, NULL, 1,'cc', NULL, NULL, NULL, 'desktop', NULL, NULL, 0, '[]', 1, 1)- `).run(`claude-${sdkSessionId}`, sdkSessionId);+ `,+ ).run(`claude-${sdkSessionId}`, sdkSessionId);const homedir = vi.spyOn(os, 'homedir').mockReturnValue(home);setLocalDb(db);try {await importExternalClaudeCodeMessagesForSession(`claude-${sdkSessionId}`);- fs.appendFileSync(file, `${line({- type: 'assistant',- uuid: 'assistant-1',- cwd: '/tmp/project',- message: {- role: 'assistant',- model: 'claude-sonnet-4-6',- content: [{ type: 'text', text: 'world' }],- },- })}\n`);+ fs.appendFileSync(+ file,+ `${line({+ type: 'assistant',+ uuid: 'assistant-1',+ cwd: '/tmp/project',+ message: {+ role: 'assistant',+ model: 'claude-sonnet-4-6',+ content: [{ type: 'text', text: 'world' }],+ },+ })}\n`,+ );await importExternalClaudeCodeMessagesForSession(`claude-${sdkSessionId}`);const count = db.prepare('SELECT COUNT(*) AS count FROM messages').get() as { count: number };@@ -570,29 +668,33 @@ describe('parseClaudeCodeMessageLine', () => {fs.mkdirSync(userData, { recursive: true });electronMock.userData = userData;const file = path.join(projectsDir, `${sdkSessionId}.jsonl`);- fs.writeFileSync(file, `${line({- type: 'user',- uuid: 'user-1',- cwd: '/tmp/project',- message: {- role: 'user',- content: [- { type: 'text', text: 'look at this' },- {- type: 'image',- source: {- type: 'base64',- media_type: 'image/png',- data: pngBase64,+ fs.writeFileSync(+ file,+ `${line({+ type: 'user',+ uuid: 'user-1',+ cwd: '/tmp/project',+ message: {+ role: 'user',+ content: [+ { type: 'text', text: 'look at this' },+ {+ type: 'image',+ source: {+ type: 'base64',+ media_type: 'image/png',+ data: pngBase64,+ },},- },- ],- },- })}\n`);+ ],+ },+ })}\n`,+ );const sessionId = `claude-${sdkSessionId}`;const db = createLocalDb();- db.prepare(`+ db.prepare(+ `INSERT INTO sessions (id, title, working_dir, model, effort, permission_mode, status,sdk_session_id, total_token_usage, total_cost_usd, context_tokens,@@ -606,15 +708,18 @@ describe('parseClaudeCodeMessageLine', () => {?, 0, 0, 0, 0, 0, NULL, NULL, 1,'cc', NULL, NULL, NULL, 'desktop', NULL, NULL, 0, '[]', 1, 1)- `).run(sessionId, sdkSessionId);- db.prepare(`+ `,+ ).run(sessionId, sdkSessionId);+ db.prepare(+ `INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, agent_meta, created_at, rewind_at)VALUES ('old-imported-user', ?, ?, 'user', ?, NULL, NULL, 1, NULL)- `).run(`claude-import:${sdkSessionId}:1-0`, sessionId, JSON.stringify('look at this'));+ `,+ ).run(`claude-import:${sdkSessionId}:1-0`, sessionId, JSON.stringify('look at this'));const homedir = vi.spyOn(os, 'homedir').mockReturnValue(home);setLocalDb(db);@@ -622,7 +727,8 @@ describe('parseClaudeCodeMessageLine', () => {try {await importExternalClaudeCodeMessagesForSession(sessionId);- const row = db.prepare('SELECT content FROM messages WHERE client_id = ?')+ const row = db+ .prepare('SELECT content FROM messages WHERE client_id = ?').get(`claude-import:${sdkSessionId}:1-0`) as { content: string } | undefined;const parsed = JSON.parse(row?.content ?? 'null') as {text: string;@@ -637,7 +743,9 @@ describe('parseClaudeCodeMessageLine', () => {originalName: 'claude-import-1-0-0.png',});const filename = decodeURIComponent(new URL(parsed.images[0].url).pathname.slice(1));- expect(fs.existsSync(path.join(userData, 'cc-agent', 'images', sessionId, filename))).toBe(true);+ expect(fs.existsSync(path.join(userData, 'cc-agent', 'images', sessionId, filename))).toBe(+ true,+ );} finally {homedir.mockRestore();resetLocalDb();@@ -651,21 +759,27 @@ describe('parseClaudeCodeMessageLine', () => {const projectsDir = path.join(home, '.claude', 'projects', '-tmp-project');fs.mkdirSync(projectsDir, { recursive: true });const olderValidFile = path.join(projectsDir, `${sdkSessionId}.jsonl`);- fs.writeFileSync(olderValidFile, `${line({- type: 'user',- uuid: 'user-1',- cwd: '/tmp/project',- message: { role: 'user', content: 'hello' },- })}\n`);+ fs.writeFileSync(+ olderValidFile,+ `${line({+ type: 'user',+ uuid: 'user-1',+ cwd: '/tmp/project',+ message: { role: 'user', content: 'hello' },+ })}\n`,+ );fs.utimesSync(olderValidFile, new Date(1_000), new Date(1_000));const newerValidFile = path.join(projectsDir, `${sdkSessionId2}.jsonl`);- fs.writeFileSync(newerValidFile, `${line({- sessionId: sdkSessionId2,- type: 'user',- uuid: 'user-2',- cwd: '/tmp/project-newer',- message: { role: 'user', content: 'newer' },- })}\n`);+ fs.writeFileSync(+ newerValidFile,+ `${line({+ sessionId: sdkSessionId2,+ type: 'user',+ uuid: 'user-2',+ cwd: '/tmp/project-newer',+ message: { role: 'user', content: 'newer' },+ })}\n`,+ );fs.utimesSync(newerValidFile, new Date(2_000), new Date(2_000));const invalidFile = path.join(projectsDir, 'invalid-newest.jsonl');fs.writeFileSync(invalidFile, 'not json\n');@@ -698,19 +812,25 @@ describe('parseClaudeCodeMessageLine', () => {fs.mkdirSync(projectsDir, { recursive: true });const firstFile = path.join(projectsDir, `${sdkSessionId}.jsonl`);const secondFile = path.join(projectsDir, `${sdkSessionId2}.jsonl`);- fs.writeFileSync(firstFile, `${line({- type: 'user',- uuid: 'user-1',- cwd: '/tmp/project',- message: { role: 'user', content: 'import me' },- })}\n`);- fs.writeFileSync(secondFile, `${line({- sessionId: sdkSessionId2,- type: 'user',- uuid: 'user-2',- cwd: '/tmp/project',- message: { role: 'user', content: 'leave me' },- })}\n`);+ fs.writeFileSync(+ firstFile,+ `${line({+ type: 'user',+ uuid: 'user-1',+ cwd: '/tmp/project',+ message: { role: 'user', content: 'import me' },+ })}\n`,+ );+ fs.writeFileSync(+ secondFile,+ `${line({+ sessionId: sdkSessionId2,+ type: 'user',+ uuid: 'user-2',+ cwd: '/tmp/project',+ message: { role: 'user', content: 'leave me' },+ })}\n`,+ );const db = createLocalDb();const homedir = vi.spyOn(os, 'homedir').mockReturnValue(home);@@ -719,8 +839,12 @@ describe('parseClaudeCodeMessageLine', () => {try {const scan = await scanExternalClaudeCodeSessions();- expect(scan.candidates.map((item) => item.id).sort()).toEqual([sdkSessionId, sdkSessionId2].sort());- const countBefore = db.prepare('SELECT COUNT(*) AS count FROM sessions').get() as { count: number };+ expect(scan.candidates.map((item) => item.id).sort()).toEqual(+ [sdkSessionId, sdkSessionId2].sort(),+ );+ const countBefore = db.prepare('SELECT COUNT(*) AS count FROM sessions').get() as {+ count: number;+ };expect(countBefore.count).toBe(0);const result = await importExternalClaudeCodeSessions([sdkSessionId]);@@ -741,12 +865,15 @@ describe('parseClaudeCodeMessageLine', () => {const projectsDir = path.join(home, '.claude', 'projects', 'D--Project-001');fs.mkdirSync(projectsDir, { recursive: true });const file = path.join(projectsDir, `${sdkSessionId}.jsonl`);- fs.writeFileSync(file, `${line({- type: 'user',- uuid: 'user-1',- cwd: 'D:\\Project-001\\',- message: { role: 'user', content: 'windows session' },- })}\n`);+ fs.writeFileSync(+ file,+ `${line({+ type: 'user',+ uuid: 'user-1',+ cwd: 'D:\\Project-001\\',+ message: { role: 'user', content: 'windows session' },+ })}\n`,+ );const db = createLocalDb();const homedir = vi.spyOn(os, 'homedir').mockReturnValue(home);@@ -774,17 +901,22 @@ describe('parseClaudeCodeMessageLine', () => {const projectsDir = path.join(home, '.claude', 'projects', '-tmp-project');fs.mkdirSync(projectsDir, { recursive: true });const file = path.join(projectsDir, `${sdkSessionId}.jsonl`);- fs.writeFileSync(file, `${line({- type: 'user',- uuid: 'user-1',- cwd: '/tmp/project',- message: { role: 'user', content: 'hello' },- })}\n`);+ fs.writeFileSync(+ file,+ `${line({+ type: 'user',+ uuid: 'user-1',+ cwd: '/tmp/project',+ message: { role: 'user', content: 'hello' },+ })}\n`,+ );const db = createLocalDb();// 模拟分享导入后被软删的会话行:UUID id(非 claude- 前缀)+ status deletedinsertImportedClaudeSession(db, 'aaaa1111-dead-beef-0000-000000000001', sdkSessionId);- db.prepare(`UPDATE sessions SET status = 'deleted' WHERE id = ?`).run('aaaa1111-dead-beef-0000-000000000001');+ db.prepare(`UPDATE sessions SET status = 'deleted' WHERE id = ?`).run(+ 'aaaa1111-dead-beef-0000-000000000001',+ );const homedir = vi.spyOn(os, 'homedir').mockReturnValue(home);setLocalDb(db);@@ -811,21 +943,26 @@ describe('parseClaudeCodeMessageLine', () => {// 之后的内容不再读——大转录文件不会在扫描期被全文 JSON.parse。const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'claude-scan-head-'));const file = path.join(dir, `${sdkSessionId}.jsonl`);- const filler = Array.from({ length: 500 }, (_, i) => line({- type: 'system',- subtype: 'noise',- cwd: '/tmp/tail-project',- seq: i,- }));- fs.writeFileSync(file, [+ const filler = Array.from({ length: 500 }, (_, i) =>line({- type: 'user',- uuid: 'user-1',- cwd: '/tmp/head-project',- message: { role: 'user', content: 'head title' },+ type: 'system',+ subtype: 'noise',+ cwd: '/tmp/tail-project',+ seq: i,}),- ...filler,- ].join('\n'));+ );+ fs.writeFileSync(+ file,+ [+ line({+ type: 'user',+ uuid: 'user-1',+ cwd: '/tmp/head-project',+ message: { role: 'user', content: 'head title' },+ }),+ ...filler,+ ].join('\n'),+ );fs.utimesSync(file, new Date(5_000_000), new Date(5_000_000));try {@@ -845,21 +982,26 @@ describe('parseClaudeCodeMessageLine', () => {const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'claude-scan-ide-extension-'));const file = path.join(dir, `${sdkSessionId}.jsonl`);const ideContext = '<ide_opened_file>The user opened /tmp/a.ts in the IDE.</ide_opened_file>';- const ideOnlyRows = Array.from({ length: 401 }, (_, index) => line({- type: 'user',- uuid: `user-ide-${index}`,- cwd: '/tmp/project',- message: { role: 'user', content: ideContext },- }));- fs.writeFileSync(file, [- ...ideOnlyRows,+ const ideOnlyRows = Array.from({ length: 401 }, (_, index) =>line({type: 'user',- uuid: 'user-real-after-cap',+ uuid: `user-ide-${index}`,cwd: '/tmp/project',- message: { role: 'user', content: 'Please fix the parser after the normal line cap' },+ message: { role: 'user', content: ideContext },}),- ].join('\n'));+ );+ fs.writeFileSync(+ file,+ [+ ...ideOnlyRows,+ line({+ type: 'user',+ uuid: 'user-real-after-cap',+ cwd: '/tmp/project',+ message: { role: 'user', content: 'Please fix the parser after the normal line cap' },+ }),+ ].join('\n'),+ );try {const summary = await readClaudeCodeSessionScanSummary(file);@@ -873,30 +1015,35 @@ describe('parseClaudeCodeMessageLine', () => {it('inspects an IDE-only first overflow row before deciding whether to extend the scan', async () => {const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'claude-scan-ide-boundary-'));const file = path.join(dir, `${sdkSessionId}.jsonl`);- const noiseRows = Array.from({ length: 400 }, (_, index) => line({- type: 'system',- subtype: 'noise',- cwd: '/tmp/project',- seq: index,- }));- fs.writeFileSync(file, [- ...noiseRows,- line({- type: 'user',- uuid: 'user-ide-at-boundary',- cwd: '/tmp/project',- message: {- role: 'user',- content: '<ide_opened_file>The user opened /tmp/a.ts in the IDE.</ide_opened_file>',- },- }),+ const noiseRows = Array.from({ length: 400 }, (_, index) =>line({- type: 'user',- uuid: 'user-real-after-boundary',+ type: 'system',+ subtype: 'noise',cwd: '/tmp/project',- message: { role: 'user', content: 'Please use the input after the boundary row' },+ seq: index,}),- ].join('\n'));+ );+ fs.writeFileSync(+ file,+ [+ ...noiseRows,+ line({+ type: 'user',+ uuid: 'user-ide-at-boundary',+ cwd: '/tmp/project',+ message: {+ role: 'user',+ content: '<ide_opened_file>The user opened /tmp/a.ts in the IDE.</ide_opened_file>',+ },+ }),+ line({+ type: 'user',+ uuid: 'user-real-after-boundary',+ cwd: '/tmp/project',+ message: { role: 'user', content: 'Please use the input after the boundary row' },+ }),+ ].join('\n'),+ );try {const summary = await readClaudeCodeSessionScanSummary(file);@@ -910,12 +1057,13 @@ describe('parseClaudeCodeMessageLine', () => {it('scan summary is cached by (mtime, size) and re-parsed when the file changes', async () => {const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'claude-scan-cache-'));const file = path.join(dir, `${sdkSessionId}.jsonl`);- const makeContent = (title: string) => `${line({- type: 'user',- uuid: 'user-1',- cwd: '/tmp/project',- message: { role: 'user', content: title },- })}\n`;+ const makeContent = (title: string) =>+ `${line({+ type: 'user',+ uuid: 'user-1',+ cwd: '/tmp/project',+ message: { role: 'user', content: title },+ })}\n`;fs.writeFileSync(file, makeContent('AAAA'));fs.utimesSync(file, new Date(5_000_000), new Date(5_000_000));@@ -942,10 +1090,13 @@ describe('parseClaudeCodeMessageLine', () => {it('scan summary rejects files without top-level events in the head window', async () => {const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'claude-scan-reject-'));const file = path.join(dir, `${sdkSessionId}.jsonl`);- fs.writeFileSync(file, [- line({ type: 'system', subtype: 'noise', cwd: '/tmp/project' }),- line({ type: 'user', isSidechain: true, message: { role: 'user', content: 'sidechain' } }),- ].join('\n'));+ fs.writeFileSync(+ file,+ [+ line({ type: 'system', subtype: 'noise', cwd: '/tmp/project' }),+ line({ type: 'user', isSidechain: true, message: { role: 'user', content: 'sidechain' } }),+ ].join('\n'),+ );try {expect(await readClaudeCodeSessionScanSummary(file)).toBeNull();@@ -959,15 +1110,19 @@ describe('parseClaudeCodeMessageLine', () => {const projectsDir = path.join(home, '.claude', 'projects', '-tmp-project');fs.mkdirSync(projectsDir, { recursive: true });const file = path.join(projectsDir, `${sdkSessionId}.jsonl`);- fs.writeFileSync(file, `${line({- type: 'user',- uuid: 'user-1',- cwd: '/tmp/project',- message: { role: 'user', content: 'hello' },- })}\n`);+ fs.writeFileSync(+ file,+ `${line({+ type: 'user',+ uuid: 'user-1',+ cwd: '/tmp/project',+ message: { role: 'user', content: 'hello' },+ })}\n`,+ );const db = createLocalDb();- db.prepare(`+ db.prepare(+ `INSERT INTO sessions (id, title, working_dir, model, effort, permission_mode, status,sdk_session_id, total_token_usage, total_cost_usd, context_tokens,@@ -981,7 +1136,8 @@ describe('parseClaudeCodeMessageLine', () => {?, 0, 0, 0, 0, 0, NULL, NULL, 1,'cc', NULL, NULL, NULL, 'desktop', NULL, NULL, 0, '[]', 1, 1)- `).run(sdkSessionId);+ `,+ ).run(sdkSessionId);const homedir = vi.spyOn(os, 'homedir').mockReturnValue(home);setLocalDb(db);diff --git a/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts b/apps/desktop/src/main/__tests__/codexLocalSessions.test.tsindex 2c4741efad..5bb9831d36 100644--- a/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts+++ b/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts@@ -67,6 +67,9 @@ function createLocalDb(): Database.Database {sdk_session_id TEXT,total_token_usage INTEGER NOT NULL DEFAULT 0,total_cost_usd REAL NOT NULL DEFAULT 0,+ total_cost_amount REAL NOT NULL DEFAULT 0,+ total_cost_currency TEXT,+ total_cost_is_approximate INTEGER NOT NULL DEFAULT 0,context_tokens INTEGER NOT NULL DEFAULT 0,context_window INTEGER NOT NULL DEFAULT 0,fast_mode INTEGER NOT NULL DEFAULT 0,@@ -120,8 +123,13 @@ function currentTestDb(): Database.Database {return dbMock.current;}-function insertImportedCodexSession(db: Database.Database, sessionId: string, sdkSessionId: string): void {- db.prepare(`+function insertImportedCodexSession(+ db: Database.Database,+ sessionId: string,+ sdkSessionId: string,+): void {+ db.prepare(+ `INSERT INTO sessions (id, title, working_dir, model, effort, permission_mode, status,sdk_session_id, total_token_usage, total_cost_usd, context_tokens,@@ -135,7 +143,8 @@ function insertImportedCodexSession(db: Database.Database, sessionId: string, sd?, 0, 0, 0, 0, 0, NULL, NULL, 1,'codex', NULL, NULL, NULL, 'desktop', NULL, NULL, 0, '[]', 1, 1)- `).run(sessionId, sdkSessionId);+ `,+ ).run(sessionId, sdkSessionId);}function createStateDb(home: string, withThreads = true): string {@@ -166,24 +175,31 @@ function createStateDb(home: string, withThreads = true): string {return dbPath;}-function insertThread(dbPath: string, id: string, rolloutPath: string, opts: {- updatedAt: number;- threadSource?: string;- source?: string;- title?: string;- archived?: boolean;- archivedAt?: number | null;- cwd?: string;-}): void {+function insertThread(+ dbPath: string,+ id: string,+ rolloutPath: string,+ opts: {+ updatedAt: number;+ threadSource?: string;+ source?: string;+ title?: string;+ archived?: boolean;+ archivedAt?: number | null;+ cwd?: string;+ },+): void {const db = new Database(dbPath);- db.prepare(`+ db.prepare(+ `INSERT INTO threads (id, rollout_path, created_at, updated_at, source, cwd, title,approval_mode, tokens_used, archived, archived_at, model,reasoning_effort, thread_source)VALUES (?, ?, ?, ?, ?, ?, ?, 'on-request', 0, ?, ?, 'gpt-5.5', 'high', ?)- `).run(+ `,+ ).run(id,rolloutPath,opts.updatedAt - 10,@@ -198,7 +214,12 @@ function insertThread(dbPath: string, id: string, rolloutPath: string, opts: {db.close();}-function rolloutLine(id: string, role: 'user' | 'assistant', text: string, timestamp: string): string {+function rolloutLine(+ id: string,+ role: 'user' | 'assistant',+ text: string,+ timestamp: string,+): string {return JSON.stringify({timestamp,type: 'response_item',@@ -268,7 +289,12 @@ describe('Codex local session import', () => {2,);const malformed = parseCodexRolloutMessageLine(- rolloutLine('m3', 'user', 'Keep <ide_opened_file>unfinished context', '2026-05-13T00:00:03.000Z'),+ rolloutLine(+ 'm3',+ 'user',+ 'Keep <ide_opened_file>unfinished context',+ '2026-05-13T00:00:03.000Z',+ ),3,);@@ -288,21 +314,25 @@ describe('Codex local session import', () => {fs.writeFileSync(rolloutPath, '');for (let i = 0; i < 1000; i += 1) {- insertThread(- dbPath,- `019dcd5a-6e54-7960-95e0-${String(i).padStart(12, '0')}`,- rolloutPath,- { updatedAt: 10_000 + i, threadSource: 'subagent' },- );+ insertThread(dbPath, `019dcd5a-6e54-7960-95e0-${String(i).padStart(12, '0')}`, rolloutPath, {+ updatedAt: 10_000 + i,+ threadSource: 'subagent',+ });}- insertThread(dbPath, threadId, rolloutPath, { updatedAt: 1_000, title: 'Top Level Codex Session' });+ insertThread(dbPath, threadId, rolloutPath, {+ updatedAt: 1_000,+ title: 'Top Level Codex Session',+ });const scan = await scanExternalCodexSessions();expect(scan.candidates.map((item) => item.id)).toEqual([threadId]);const result = await importExternalCodexSessions([threadId]);expect(result).toMatchObject({ scanned: 1, inserted: 1, updated: 0 });- const rows = currentTestDb().prepare('SELECT id, title FROM sessions').all() as Array<{ id: string; title: string }>;+ const rows = currentTestDb().prepare('SELECT id, title FROM sessions').all() as Array<{+ id: string;+ title: string;+ }>;expect(rows).toEqual([{ id: `codex-${threadId}`, title: 'Top Level Codex Session' }]);}, 15_000);@@ -320,15 +350,24 @@ describe('Codex local session import', () => {const scan = await scanExternalCodexSessions();expect(scan.candidates).toEqual([]);- const count = currentTestDb().prepare('SELECT COUNT(*) AS count FROM sessions')- .get() as { count: number };+ const count = currentTestDb().prepare('SELECT COUNT(*) AS count FROM sessions').get() as {+ count: number;+ };expect(count.count).toBe(0);});it('scans without writing and imports only explicitly selected Codex sessions', async () => {const dbPath = createStateDb(externalHome);- const firstRolloutPath = path.join(externalHome, 'sessions', `rollout-2026-05-13-${threadId}.jsonl`);- const secondRolloutPath = path.join(externalHome, 'sessions', `rollout-2026-05-13-${execThreadId}.jsonl`);+ const firstRolloutPath = path.join(+ externalHome,+ 'sessions',+ `rollout-2026-05-13-${threadId}.jsonl`,+ );+ const secondRolloutPath = path.join(+ externalHome,+ 'sessions',+ `rollout-2026-05-13-${execThreadId}.jsonl`,+ );fs.mkdirSync(path.dirname(firstRolloutPath), { recursive: true });fs.writeFileSync(firstRolloutPath, '');fs.writeFileSync(secondRolloutPath, '');@@ -338,8 +377,9 @@ describe('Codex local session import', () => {const scan = await scanExternalCodexSessions();expect(scan.candidates.map((item) => item.id).sort()).toEqual([execThreadId, threadId].sort());- const countBefore = currentTestDb().prepare('SELECT COUNT(*) AS count FROM sessions')- .get() as { count: number };+ const countBefore = currentTestDb().prepare('SELECT COUNT(*) AS count FROM sessions').get() as {+ count: number;+ };expect(countBefore.count).toBe(0);const result = await importExternalCodexSessions([threadId]);@@ -371,17 +411,31 @@ describe('Codex local session import', () => {it('imports the same latest Codex thread version shown by scan when defaults contain duplicates', async () => {const olderDbPath = createStateDb(externalHome);- const olderRolloutPath = path.join(externalHome, 'sessions', `rollout-2026-05-13-${threadId}.jsonl`);+ const olderRolloutPath = path.join(+ externalHome,+ 'sessions',+ `rollout-2026-05-13-${threadId}.jsonl`,+ );fs.mkdirSync(path.dirname(olderRolloutPath), { recursive: true });fs.writeFileSync(olderRolloutPath, '');- insertThread(olderDbPath, threadId, olderRolloutPath, { updatedAt: 1_000, title: 'Older Copy' });+ insertThread(olderDbPath, threadId, olderRolloutPath, {+ updatedAt: 1_000,+ title: 'Older Copy',+ });const defaultHome = path.join(rootDir, 'home', '.codex');const newerDbPath = createStateDb(defaultHome);- const newerRolloutPath = path.join(defaultHome, 'sessions', `rollout-2026-05-15-${threadId}.jsonl`);+ const newerRolloutPath = path.join(+ defaultHome,+ 'sessions',+ `rollout-2026-05-15-${threadId}.jsonl`,+ );fs.mkdirSync(path.dirname(newerRolloutPath), { recursive: true });fs.writeFileSync(newerRolloutPath, '');- insertThread(newerDbPath, threadId, newerRolloutPath, { updatedAt: 3_000, title: 'Newest Copy' });+ insertThread(newerDbPath, threadId, newerRolloutPath, {+ updatedAt: 3_000,+ title: 'Newest Copy',+ });const scan = await scanExternalCodexSessions();@@ -397,26 +451,30 @@ describe('Codex local session import', () => {createStateDb(externalHome, false);const rolloutPath = path.join(externalHome, 'sessions', `rollout-2026-05-13-${threadId}.jsonl`);fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });- fs.writeFileSync(rolloutPath, `${JSON.stringify({- timestamp: '2026-05-13T00:00:00.000Z',- type: 'session_meta',- payload: {- id: threadId,+ fs.writeFileSync(+ rolloutPath,+ `${JSON.stringify({timestamp: '2026-05-13T00:00:00.000Z',- cwd: '/tmp/project',- source: 'cli',- model: 'gpt-5.5',- reasoning_effort: 'high',- approval_mode: 'on-request',- },- })}\n`);+ type: 'session_meta',+ payload: {+ id: threadId,+ timestamp: '2026-05-13T00:00:00.000Z',+ cwd: '/tmp/project',+ source: 'cli',+ model: 'gpt-5.5',+ reasoning_effort: 'high',+ approval_mode: 'on-request',+ },+ })}\n`,+ );const scan = await scanExternalCodexSessions();expect(scan.candidates.map((item) => item.id)).toEqual([threadId]);const result = await importExternalCodexSessions([threadId]);expect(result).toMatchObject({ scanned: 1, inserted: 1, updated: 0 });- const row = currentTestDb().prepare('SELECT id, working_dir AS workingDir FROM sessions LIMIT 1')+ const row = currentTestDb()+ .prepare('SELECT id, working_dir AS workingDir FROM sessions LIMIT 1').get() as { id: string; workingDir: string } | undefined;expect(row).toEqual({ id: `codex-${threadId}`, workingDir: '/tmp/project' });});@@ -426,9 +484,12 @@ describe('Codex local session import', () => {const rolloutPath = path.join(externalHome, 'sessions', `rollout-2026-05-13-${threadId}.jsonl`);fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });fs.writeFileSync(rolloutPath, '');- fs.writeFileSync(path.join(externalHome, '.codex-global-state.json'), JSON.stringify({- 'projectless-thread-ids': [threadId],- }));+ fs.writeFileSync(+ path.join(externalHome, '.codex-global-state.json'),+ JSON.stringify({+ 'projectless-thread-ids': [threadId],+ }),+ );insertThread(dbPath, threadId, rolloutPath, { updatedAt: 1_000, title: 'Standalone Dialogue' });const scan = await scanExternalCodexSessions();@@ -438,11 +499,15 @@ describe('Codex local session import', () => {]);const result = await importExternalCodexSessions([threadId]);expect(result).toMatchObject({ scanned: 1, inserted: 1, updated: 0 });- const row = currentTestDb().prepare(`+ const row = currentTestDb()+ .prepare(+ `SELECT id, working_dir AS workingDir, workspace_kind AS workspaceKindFROM sessionsLIMIT 1- `).get() as { id: string; workingDir: string; workspaceKind: string } | undefined;+ `,+ )+ .get() as { id: string; workingDir: string; workspaceKind: string } | undefined;expect(row).toEqual({id: `codex-${threadId}`,workingDir: '/tmp/project',@@ -455,12 +520,17 @@ describe('Codex local session import', () => {const rolloutPath = path.join(externalHome, 'sessions', `rollout-2026-05-13-${threadId}.jsonl`);fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });fs.writeFileSync(rolloutPath, '');- fs.writeFileSync(path.join(externalHome, '.codex-global-state.json'), JSON.stringify({- 'projectless-thread-ids': [threadId],- }));+ fs.writeFileSync(+ path.join(externalHome, '.codex-global-state.json'),+ JSON.stringify({+ 'projectless-thread-ids': [threadId],+ }),+ );insertThread(dbPath, threadId, rolloutPath, { updatedAt: 1_000, title: 'External Dialogue' });- currentTestDb().prepare(`+ currentTestDb()+ .prepare(+ `INSERT INTO sessions (id, title, working_dir, workspace_kind, model, effort, permission_mode, status,sdk_session_id, total_token_usage, total_cost_usd, context_tokens,@@ -474,16 +544,23 @@ describe('Codex local session import', () => {?, 0, 0, 0, 0, 0, NULL, NULL, 2000000,'codex', NULL, NULL, NULL, 'desktop', NULL, NULL, 0, '[]', 2000000, 2000000)- `).run(`codex-${threadId}`, threadId);+ `,+ )+ .run(`codex-${threadId}`, threadId);const result = await importExternalCodexSessions([threadId]);expect(result).toMatchObject({ scanned: 1, inserted: 0, updated: 1 });- const row = currentTestDb().prepare(`+ const row = currentTestDb()+ .prepare(+ `SELECT title, workspace_kind AS workspaceKind, updated_at AS updatedAtFROM sessionsWHERE id = ?- `).get(`codex-${threadId}`) as { title: string; workspaceKind: string; updatedAt: number } | undefined;+ `,+ )+ .get(`codex-${threadId}`) as+ { title: string; workspaceKind: string; updatedAt: number } | undefined;expect(row).toEqual({title: 'Local Rename',workspaceKind: 'dialogue',@@ -493,7 +570,11 @@ describe('Codex local session import', () => {it('maps external Codex archived state while preserving the project working dir', async () => {const dbPath = createStateDb(externalHome);- const rolloutPath = path.join(externalHome, 'archived_sessions', `rollout-2026-05-13-${threadId}.jsonl`);+ const rolloutPath = path.join(+ externalHome,+ 'archived_sessions',+ `rollout-2026-05-13-${threadId}.jsonl`,+ );fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });fs.writeFileSync(rolloutPath, '');insertThread(dbPath, threadId, rolloutPath, {@@ -507,11 +588,15 @@ describe('Codex local session import', () => {expect(scan.candidates.map((item) => item.id)).toEqual([threadId]);const result = await importExternalCodexSessions([threadId]);expect(result).toMatchObject({ scanned: 1, inserted: 1, updated: 0 });- const row = currentTestDb().prepare(`+ const row = currentTestDb()+ .prepare(+ `SELECT id, status, working_dir AS workingDir, user_send_at AS userSendAtFROM sessionsLIMIT 1- `).get() as { id: string; status: string; workingDir: string; userSendAt: number } | undefined;+ `,+ )+ .get() as { id: string; status: string; workingDir: string; userSendAt: number } | undefined;expect(row).toEqual({id: `codex-${threadId}`,status: 'archived',@@ -527,7 +612,9 @@ describe('Codex local session import', () => {fs.writeFileSync(rolloutPath, '');insertThread(dbPath, threadId, rolloutPath, { updatedAt: 1_000, title: 'External Duplicate' });- currentTestDb().prepare(`+ currentTestDb()+ .prepare(+ `INSERT INTO sessions (id, title, working_dir, model, effort, permission_mode, status,sdk_session_id, total_token_usage, total_cost_usd, context_tokens,@@ -541,7 +628,9 @@ describe('Codex local session import', () => {?, 0, 0, 0, 0, 0, NULL, NULL, 1,'codex', NULL, NULL, NULL, 'desktop', NULL, NULL, 0, '[]', 1, 1)- `).run(threadId);+ `,+ )+ .run(threadId);const result = await importExternalCodexSessions([threadId]);@@ -552,12 +641,23 @@ describe('Codex local session import', () => {it('filters Codex exec sessions from scan and explicit import', async () => {const dbPath = createStateDb(externalHome);- const normalRolloutPath = path.join(externalHome, 'sessions', `rollout-2026-05-13-${threadId}.jsonl`);- const execRolloutPath = path.join(externalHome, 'sessions', `rollout-2026-05-13-${execThreadId}.jsonl`);+ const normalRolloutPath = path.join(+ externalHome,+ 'sessions',+ `rollout-2026-05-13-${threadId}.jsonl`,+ );+ const execRolloutPath = path.join(+ externalHome,+ 'sessions',+ `rollout-2026-05-13-${execThreadId}.jsonl`,+ );fs.mkdirSync(path.dirname(normalRolloutPath), { recursive: true });fs.writeFileSync(normalRolloutPath, '');fs.writeFileSync(execRolloutPath, '');- insertThread(dbPath, threadId, normalRolloutPath, { updatedAt: 2_000, title: 'Top Level Codex Session' });+ insertThread(dbPath, threadId, normalRolloutPath, {+ updatedAt: 2_000,+ title: 'Top Level Codex Session',+ });insertThread(dbPath, execThreadId, execRolloutPath, {updatedAt: 1_000,source: 'exec',@@ -605,23 +705,32 @@ describe('Codex local session import', () => {// archived_sessions/ 拷贝 mtime 更老,sessions/ 拷贝 mtime 更新 →// 期望合并时 archived=true(archived 标志 sticky,不会被较新的 sessions/ 拷贝覆盖)。createStateDb(externalHome, false);- const archivedRollout = path.join(externalHome, 'archived_sessions', `rollout-2026-05-12-${threadId}.jsonl`);- const activeRollout = path.join(externalHome, 'sessions', `rollout-2026-05-13-${threadId}.jsonl`);+ const archivedRollout = path.join(+ externalHome,+ 'archived_sessions',+ `rollout-2026-05-12-${threadId}.jsonl`,+ );+ const activeRollout = path.join(+ externalHome,+ 'sessions',+ `rollout-2026-05-13-${threadId}.jsonl`,+ );fs.mkdirSync(path.dirname(archivedRollout), { recursive: true });fs.mkdirSync(path.dirname(activeRollout), { recursive: true });- const meta = (timestamp: string) => `${JSON.stringify({- timestamp,- type: 'session_meta',- payload: {- id: threadId,+ const meta = (timestamp: string) =>+ `${JSON.stringify({timestamp,- cwd: '/tmp/project',- source: 'cli',- model: 'gpt-5.5',- reasoning_effort: 'high',- approval_mode: 'on-request',- },- })}\n`;+ type: 'session_meta',+ payload: {+ id: threadId,+ timestamp,+ cwd: '/tmp/project',+ source: 'cli',+ model: 'gpt-5.5',+ reasoning_effort: 'high',+ approval_mode: 'on-request',+ },+ })}\n`;fs.writeFileSync(archivedRollout, meta('2026-05-12T00:00:00.000Z'));fs.writeFileSync(activeRollout, meta('2026-05-13T00:00:00.000Z'));fs.utimesSync(archivedRollout, new Date(1_000), new Date(1_000));@@ -663,7 +772,9 @@ describe('Codex local session import', () => {insertThread(dbPath, threadId, rolloutPath, { updatedAt: 1_000, title: 'Still Present' });const staleThreadId = '019dcd5a-6e54-7960-95e0-aa68117a28ff';- currentTestDb().prepare(`+ currentTestDb()+ .prepare(+ `INSERT INTO sessions (id, title, working_dir, model, effort, permission_mode, status,sdk_session_id, total_token_usage, total_cost_usd, context_tokens,@@ -677,7 +788,9 @@ describe('Codex local session import', () => {?, 0, 0, 0, 0, 0, NULL, NULL, 1,'codex', NULL, NULL, NULL, 'desktop', NULL, NULL, 0, '[]', 1, 1)- `).run(`codex-${staleThreadId}`, staleThreadId);+ `,+ )+ .run(`codex-${staleThreadId}`, staleThreadId);const scan = await scanExternalCodexSessions();@@ -692,21 +805,25 @@ describe('importExternalCodexMessagesForSession', () => {const dbPath = createStateDb(externalHome);const rolloutPath = path.join(externalHome, 'sessions', `rollout-2026-05-13-${threadId}.jsonl`);fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });- fs.writeFileSync(rolloutPath, `${rolloutLine('m1', 'user', 'hello', '2026-05-13T00:00:01.000Z')}\n`);+ fs.writeFileSync(+ rolloutPath,+ `${rolloutLine('m1', 'user', 'hello', '2026-05-13T00:00:01.000Z')}\n`,+ );insertThread(dbPath, threadId, rolloutPath, { updatedAt: 1_000 });const db = currentTestDb();insertImportedCodexSession(db, `codex-${threadId}`, threadId);- const tx = vi.fn(async (name: string, args: unknown) => runInprocTx(db, { name, args }) as never);+ const tx = vi.fn(+ async (name: string, args: unknown) => runInprocTx(db, { name, args }) as never,+ );setCurrentDbClient({ ...makeTestDbClient(db), tx }, 'test-user');await importExternalCodexMessagesForSession(`codex-${threadId}`);await importExternalCodexMessagesForSession(`codex-${threadId}`);expect(tx).toHaveBeenCalledTimes(1);- const count = db.prepare('SELECT COUNT(*) AS count FROM messages')- .get() as { count: number };+ const count = db.prepare('SELECT COUNT(*) AS count FROM messages').get() as { count: number };expect(count.count).toBe(1);});@@ -714,12 +831,17 @@ describe('importExternalCodexMessagesForSession', () => {const dbPath = createStateDb(externalHome);const rolloutPath = path.join(externalHome, 'sessions', `rollout-2026-05-13-${threadId}.jsonl`);fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });- fs.writeFileSync(rolloutPath, `${rolloutLine('m1', 'user', 'hello', '2026-05-13T00:00:01.000Z')}\n`);+ fs.writeFileSync(+ rolloutPath,+ `${rolloutLine('m1', 'user', 'hello', '2026-05-13T00:00:01.000Z')}\n`,+ );insertThread(dbPath, threadId, rolloutPath, { updatedAt: 1_000 });const dbA = currentTestDb();insertImportedCodexSession(dbA, `codex-${threadId}`, threadId);- const txA = vi.fn(async (name: string, args: unknown) => runInprocTx(dbA, { name, args }) as never);+ const txA = vi.fn(+ async (name: string, args: unknown) => runInprocTx(dbA, { name, args }) as never,+ );setCurrentDbClient({ ...makeTestDbClient(dbA), tx: txA }, 'user-a');await importExternalCodexMessagesForSession(`codex-${threadId}`);expect(txA).toHaveBeenCalledTimes(1);@@ -728,14 +850,17 @@ describe('importExternalCodexMessagesForSession', () => {try {dbMock.current = dbB;insertImportedCodexSession(dbB, `codex-${threadId}`, threadId);- const txB = vi.fn(async (name: string, args: unknown) => runInprocTx(dbB, { name, args }) as never);+ const txB = vi.fn(+ async (name: string, args: unknown) => runInprocTx(dbB, { name, args }) as never,+ );setCurrentDbClient({ ...makeTestDbClient(dbB), tx: txB }, 'user-b');await importExternalCodexMessagesForSession(`codex-${threadId}`);expect(txB).toHaveBeenCalledTimes(1);- const count = dbB.prepare('SELECT COUNT(*) AS count FROM messages')- .get() as { count: number };+ const count = dbB.prepare('SELECT COUNT(*) AS count FROM messages').get() as {+ count: number;+ };expect(count.count).toBe(1);} finally {dbA.close();@@ -746,10 +871,15 @@ describe('importExternalCodexMessagesForSession', () => {const dbPath = createStateDb(externalHome);const rolloutPath = path.join(externalHome, 'sessions', `rollout-2026-05-13-${threadId}.jsonl`);fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });- fs.writeFileSync(rolloutPath, `${rolloutLine('m1', 'user', 'hello', '2026-05-13T00:00:01.000Z')}\n`);+ fs.writeFileSync(+ rolloutPath,+ `${rolloutLine('m1', 'user', 'hello', '2026-05-13T00:00:01.000Z')}\n`,+ );insertThread(dbPath, threadId, rolloutPath, { updatedAt: 1_000 });- currentTestDb().prepare(`+ currentTestDb()+ .prepare(+ `INSERT INTO sessions (id, title, working_dir, model, effort, permission_mode, status,sdk_session_id, total_token_usage, total_cost_usd, context_tokens,@@ -763,14 +893,20 @@ describe('importExternalCodexMessagesForSession', () => {?, 0, 0, 0, 0, 0, NULL, NULL, 1,'codex', NULL, NULL, NULL, 'desktop', NULL, NULL, 0, '[]', 1, 1)- `).run(`codex-${threadId}`, threadId);+ `,+ )+ .run(`codex-${threadId}`, threadId);await importExternalCodexMessagesForSession(`codex-${threadId}`);- fs.appendFileSync(rolloutPath, `${rolloutLine('m2', 'assistant', 'world', '2026-05-13T00:00:02.000Z')}\n`);+ fs.appendFileSync(+ rolloutPath,+ `${rolloutLine('m2', 'assistant', 'world', '2026-05-13T00:00:02.000Z')}\n`,+ );await importExternalCodexMessagesForSession(`codex-${threadId}`);- const count = currentTestDb().prepare('SELECT COUNT(*) AS count FROM messages')- .get() as { count: number };+ const count = currentTestDb().prepare('SELECT COUNT(*) AS count FROM messages').get() as {+ count: number;+ };expect(count.count).toBe(2);});@@ -778,11 +914,16 @@ describe('importExternalCodexMessagesForSession', () => {const dbPath = createStateDb(externalHome);const rolloutPath = path.join(externalHome, 'sessions', `rollout-2026-05-13-${threadId}.jsonl`);fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });- fs.writeFileSync(rolloutPath, `${rolloutLineWithImage('m1', 'look at this', '2026-05-13T00:00:01.000Z')}\n`);+ fs.writeFileSync(+ rolloutPath,+ `${rolloutLineWithImage('m1', 'look at this', '2026-05-13T00:00:01.000Z')}\n`,+ );insertThread(dbPath, threadId, rolloutPath, { updatedAt: 1_000 });const sessionId = `codex-${threadId}`;- currentTestDb().prepare(`+ currentTestDb()+ .prepare(+ `INSERT INTO sessions (id, title, working_dir, model, effort, permission_mode, status,sdk_session_id, total_token_usage, total_cost_usd, context_tokens,@@ -796,19 +937,26 @@ describe('importExternalCodexMessagesForSession', () => {?, 0, 0, 0, 0, 0, NULL, NULL, 1,'codex', NULL, NULL, NULL, 'desktop', NULL, NULL, 0, '[]', 1, 1)- `).run(sessionId, threadId);- currentTestDb().prepare(`+ `,+ )+ .run(sessionId, threadId);+ currentTestDb()+ .prepare(+ `INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, agent_meta, created_at, rewind_at)VALUES ('old-imported-user', ?, ?, 'user', ?, NULL, NULL, 1, NULL)- `).run(`codex-import:${threadId}:1`, sessionId, JSON.stringify('look at this'));+ `,+ )+ .run(`codex-import:${threadId}:1`, sessionId, JSON.stringify('look at this'));await importExternalCodexMessagesForSession(sessionId);- const row = currentTestDb().prepare('SELECT content FROM messages WHERE client_id = ?')+ const row = currentTestDb()+ .prepare('SELECT content FROM messages WHERE client_id = ?').get(`codex-import:${threadId}:1`) as { content: string } | undefined;const parsed = JSON.parse(row?.content ?? 'null') as {text: string;@@ -823,7 +971,9 @@ describe('importExternalCodexMessagesForSession', () => {originalName: 'codex-import-1-0-0.png',});const filename = decodeURIComponent(new URL(parsed.images[0].url).pathname.slice(1));- expect(fs.existsSync(path.join(targetUserData, 'cc-agent', 'images', sessionId, filename))).toBe(true);+ expect(+ fs.existsSync(path.join(targetUserData, 'cc-agent', 'images', sessionId, filename)),+ ).toBe(true);});it('skips a truncated jsonl line in the middle without failing the whole import', async () => {@@ -841,7 +991,9 @@ describe('importExternalCodexMessagesForSession', () => {);insertThread(dbPath, threadId, rolloutPath, { updatedAt: 1_000 });- currentTestDb().prepare(`+ currentTestDb()+ .prepare(+ `INSERT INTO sessions (id, title, working_dir, model, effort, permission_mode, status,sdk_session_id, total_token_usage, total_cost_usd, context_tokens,@@ -855,13 +1007,19 @@ describe('importExternalCodexMessagesForSession', () => {?, 0, 0, 0, 0, 0, NULL, NULL, 1,'codex', NULL, NULL, NULL, 'desktop', NULL, NULL, 0, '[]', 1, 1)- `).run(`codex-${threadId}`, threadId);+ `,+ )+ .run(`codex-${threadId}`, threadId);await importExternalCodexMessagesForSession(`codex-${threadId}`);- const rows = currentTestDb().prepare(`+ const rows = currentTestDb()+ .prepare(+ `SELECT role, content FROM messages ORDER BY id- `).all() as Array<{ role: string; content: string }>;+ `,+ )+ .all() as Array<{ role: string; content: string }>;// 损坏的中间行被跳过,前后两条有效行仍应入库。expect(rows.map((r) => r.role)).toEqual(['user', 'assistant']);expect(rows.map((r) => JSON.parse(r.content))).toEqual(['first', 'third']);@@ -871,10 +1029,15 @@ describe('importExternalCodexMessagesForSession', () => {const dbPath = createStateDb(externalHome);const rolloutPath = path.join(externalHome, 'sessions', `rollout-2026-05-13-${threadId}.jsonl`);fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });- fs.writeFileSync(rolloutPath, `${rolloutLine('m1', 'user', 'hello', '2026-05-13T00:00:01.000Z')}\n`);+ fs.writeFileSync(+ rolloutPath,+ `${rolloutLine('m1', 'user', 'hello', '2026-05-13T00:00:01.000Z')}\n`,+ );insertThread(dbPath, threadId, rolloutPath, { updatedAt: 1_000 });- currentTestDb().prepare(`+ currentTestDb()+ .prepare(+ `INSERT INTO sessions (id, title, working_dir, model, effort, permission_mode, status,sdk_session_id, total_token_usage, total_cost_usd, context_tokens,@@ -888,33 +1051,53 @@ describe('importExternalCodexMessagesForSession', () => {?, 0, 0, 0, 0, 0, NULL, NULL, 1,'codex', NULL, NULL, NULL, 'desktop', NULL, NULL, 0, '[]', 1, 1)- `).run(`codex-${threadId}`, threadId);+ `,+ )+ .run(`codex-${threadId}`, threadId);await importExternalCodexMessagesForSession(`codex-${threadId}`);- currentTestDb().prepare(`+ currentTestDb()+ .prepare(+ `INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, agent_meta, created_at, rewind_at)VALUES ('local-user', 'local-user-client', ?, 'user', 'continue', NULL, NULL, ?, NULL)- `).run(`codex-${threadId}`, Date.parse('2026-05-13T00:00:02.000Z') + 2);+ `,+ )+ .run(`codex-${threadId}`, Date.parse('2026-05-13T00:00:02.000Z') + 2);- fs.appendFileSync(rolloutPath, `${rolloutLine('m2', 'user', 'continue', '2026-05-13T00:00:02.000Z')}\n`);- fs.appendFileSync(rolloutPath, `${rolloutLine('m3', 'assistant', 'external update', '2026-05-13T00:00:03.000Z')}\n`);+ fs.appendFileSync(+ rolloutPath,+ `${rolloutLine('m2', 'user', 'continue', '2026-05-13T00:00:02.000Z')}\n`,+ );+ fs.appendFileSync(+ rolloutPath,+ `${rolloutLine('m3', 'assistant', 'external update', '2026-05-13T00:00:03.000Z')}\n`,+ );await importExternalCodexMessagesForSession(`codex-${threadId}`);- const rows = currentTestDb().prepare(`+ const rows = currentTestDb()+ .prepare(+ `SELECT client_id AS clientId, role, contentFROM messagesORDER BY created_at- `).all() as Array<{ clientId: string; role: string; content: string }>;+ `,+ )+ .all() as Array<{ clientId: string; role: string; content: string }>;expect(rows).toEqual([{ clientId: `codex-import:${threadId}:1`, role: 'user', content: JSON.stringify('hello') },{ clientId: 'local-user-client', role: 'user', content: 'continue' },- { clientId: `codex-import:${threadId}:3`, role: 'assistant', content: JSON.stringify('external update') },+ {+ clientId: `codex-import:${threadId}:3`,+ role: 'assistant',+ content: JSON.stringify('external update'),+ },]);});});@@ -929,7 +1112,9 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>sdkSessionId: string,opts: { createdAt?: number; updatedAt?: number } = {},): void {- currentTestDb().prepare(`+ currentTestDb()+ .prepare(+ `INSERT INTO sessions (id, title, working_dir, model, effort, permission_mode, status,sdk_session_id, total_token_usage, total_cost_usd, context_tokens,@@ -943,7 +1128,9 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>?, 0, 0, 0, 0, 0, NULL, NULL, 1,'codex', NULL, NULL, NULL, 'desktop', NULL, NULL, 0, '[]', ?, ?)- `).run(sessionId, sdkSessionId, opts.createdAt ?? 1_000, opts.updatedAt ?? 2_000);+ `,+ )+ .run(sessionId, sdkSessionId, opts.createdAt ?? 1_000, opts.updatedAt ?? 2_000);}function insertLocalMessage(@@ -953,10 +1140,14 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>content: string,createdAt: number,): void {- currentTestDb().prepare(`+ currentTestDb()+ .prepare(+ `INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, agent_meta, created_at, rewind_at)VALUES (?, ?, ?, ?, ?, NULL, NULL, ?, NULL)- `).run(`${clientId}-id`, clientId, sessionId, role, content, createdAt);+ `,+ )+ .run(`${clientId}-id`, clientId, sessionId, role, content, createdAt);}it('adopts a legacy branded Codex HOME and remains resumable after the old directory is removed', async () => {@@ -988,7 +1179,8 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>await prepareExternalCodexSessionForResume(threadId);const targetRow = new Database(targetDbPath, { readonly: true });- const adopted = targetRow.prepare('SELECT rollout_path AS rolloutPath, title FROM threads WHERE id = ?')+ const adopted = targetRow+ .prepare('SELECT rollout_path AS rolloutPath, title FROM threads WHERE id = ?').get(threadId) as { rolloutPath: string; title: string };targetRow.close();expect(adopted.title).toBe('Legacy branded session');@@ -1022,7 +1214,8 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>await prepareExternalCodexSessionForResume(threadId);const targetDb = new Database(targetDbPath, { readonly: true });- const targetRow = targetDb.prepare('SELECT rollout_path AS rolloutPath, title FROM threads WHERE id = ?')+ const targetRow = targetDb+ .prepare('SELECT rollout_path AS rolloutPath, title FROM threads WHERE id = ?').get(threadId) as { rolloutPath: string; title: string };targetDb.close();expect(targetRow.title).toBe('Current Cindy title');@@ -1041,7 +1234,11 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>title: 'Legacy source title',});- const linkedRollout = path.join(externalHome, 'sessions', `rollout-2026-07-15-${threadId}.jsonl`);+ const linkedRollout = path.join(+ externalHome,+ 'sessions',+ `rollout-2026-07-15-${threadId}.jsonl`,+ );fs.mkdirSync(path.dirname(linkedRollout), { recursive: true });fs.writeFileSync(linkedRollout, 'NEWER_LINKED_ROLLOUT');const linkedDbPath = createStateDb(externalHome);@@ -1059,7 +1256,8 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>await prepareExternalCodexSessionForResume(threadId);const targetDb = new Database(targetDbPath, { readonly: true });- const targetRow = targetDb.prepare('SELECT rollout_path AS rolloutPath, title FROM threads WHERE id = ?')+ const targetRow = targetDb+ .prepare('SELECT rollout_path AS rolloutPath, title FROM threads WHERE id = ?').get(threadId) as { rolloutPath: string; title: string };targetDb.close();expect(targetRow.title).toBe('Current Cindy title');@@ -1068,7 +1266,11 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>});it('keeps an explicitly configured external CODEX_HOME linked instead of adopting it', async () => {- const sourceRollout = path.join(externalHome, 'sessions', `rollout-2026-07-14-${threadId}.jsonl`);+ const sourceRollout = path.join(+ externalHome,+ 'sessions',+ `rollout-2026-07-14-${threadId}.jsonl`,+ );const sourceDbPath = createStateDb(externalHome);fs.mkdirSync(path.dirname(sourceRollout), { recursive: true });fs.writeFileSync(sourceRollout, 'LINKED_EXTERNAL_ROLLOUT');@@ -1078,11 +1280,14 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>await prepareExternalCodexSessionForResume(threadId);const targetDb = new Database(targetDbPath, { readonly: true });- const targetRow = targetDb.prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')+ const targetRow = targetDb+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?').get(threadId) as { rolloutPath: string };targetDb.close();expect(targetRow.rolloutPath).toBe(sourceRollout);- expect(fs.existsSync(path.join(desktopHome(), 'sessions', path.basename(sourceRollout)))).toBe(false);+ expect(fs.existsSync(path.join(desktopHome(), 'sessions', path.basename(sourceRollout)))).toBe(+ false,+ );});it('synthesizes into the current HOME when legacy state survives but its rollout is missing', async () => {@@ -1107,7 +1312,8 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>await prepareExternalCodexSessionForResume(threadId);const targetDb = new Database(targetDbPath, { readonly: true });- const targetRow = targetDb.prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?')+ const targetRow = targetDb+ .prepare('SELECT rollout_path AS rolloutPath FROM threads WHERE id = ?').get(threadId) as { rolloutPath: string };targetDb.close();expect(targetRow.rolloutPath.startsWith(desktopHome())).toBe(true);@@ -1120,7 +1326,13 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>const dbPath = createStateDb(desktopHome());const sessionId = `local-missing-state-${threadId}`;insertLocalCodexSession(sessionId, threadId);- insertLocalMessage(sessionId, 'c1', 'user', JSON.stringify({ text: 'recover without state' }), 1_000);+ insertLocalMessage(+ sessionId,+ 'c1',+ 'user',+ JSON.stringify({ text: 'recover without state' }),+ 1_000,+ );insertLocalMessage(sessionId, 'c2', 'assistant', 'state will hydrate on resume', 1_100);await prepareExternalCodexSessionForResume(threadId);@@ -1134,7 +1346,11 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>`rollout-1970-01-01T00-00-01-${threadId}.jsonl`,);expect(fs.existsSync(rolloutPath)).toBe(true);- const lines = fs.readFileSync(rolloutPath, 'utf-8').trim().split('\n').map((line) => JSON.parse(line));+ const lines = fs+ .readFileSync(rolloutPath, 'utf-8')+ .trim()+ .split('\n')+ .map((line) => JSON.parse(line));expect(lines[0]).toMatchObject({type: 'session_meta',payload: {@@ -1155,7 +1371,8 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>// Cindy 不伪造版本敏感的 threads 行;它由随后的 app-server thread/resume hydrate。const stateDb = new Database(dbPath, { readonly: true });- const stateCount = stateDb.prepare('SELECT count(*) AS count FROM threads WHERE id = ?')+ const stateCount = stateDb+ .prepare('SELECT count(*) AS count FROM threads WHERE id = ?').get(threadId) as { count: number };stateDb.close();expect(stateCount.count).toBe(0);@@ -1172,10 +1389,28 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>const partialSessionId = `local-partial-${threadId}`;insertLocalCodexSession(fullerSessionId, threadId, { createdAt: 1_000, updatedAt: 2_000 });insertLocalCodexSession(partialSessionId, threadId, { createdAt: 1_500, updatedAt: 3_000 });- insertLocalMessage(fullerSessionId, 'full-1', 'user', JSON.stringify({ text: 'full start' }), 1_000);+ insertLocalMessage(+ fullerSessionId,+ 'full-1',+ 'user',+ JSON.stringify({ text: 'full start' }),+ 1_000,+ );insertLocalMessage(fullerSessionId, 'full-2', 'assistant', 'full answer', 1_100);- insertLocalMessage(fullerSessionId, 'full-3', 'user', JSON.stringify({ text: 'full continuation' }), 1_200);- insertLocalMessage(partialSessionId, 'partial-1', 'user', JSON.stringify({ text: 'partial only' }), 1_500);+ insertLocalMessage(+ fullerSessionId,+ 'full-3',+ 'user',+ JSON.stringify({ text: 'full continuation' }),+ 1_200,+ );+ insertLocalMessage(+ partialSessionId,+ 'partial-1',+ 'user',+ JSON.stringify({ text: 'partial only' }),+ 1_500,+ );await prepareExternalCodexSessionForResume(threadId);@@ -1187,7 +1422,11 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>'01',`rollout-1970-01-01T00-00-01-${threadId}.jsonl`,);- const lines = fs.readFileSync(rolloutPath, 'utf-8').trim().split('\n').map((line) => JSON.parse(line));+ const lines = fs+ .readFileSync(rolloutPath, 'utf-8')+ .trim()+ .split('\n')+ .map((line) => JSON.parse(line));expect(lines.slice(1).map((line) => line.payload.content[0].text)).toEqual(['full start','full answer',@@ -1226,8 +1465,16 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>createStateDb(desktopHome());const sessionId = `local-deleted-${threadId}`;insertLocalCodexSession(sessionId, threadId);- currentTestDb().prepare('UPDATE sessions SET status = ? WHERE id = ?').run('deleted', sessionId);- insertLocalMessage(sessionId, 'c1', 'user', JSON.stringify({ text: 'do not resurrect' }), 1_000);+ currentTestDb()+ .prepare('UPDATE sessions SET status = ? WHERE id = ?')+ .run('deleted', sessionId);+ insertLocalMessage(+ sessionId,+ 'c1',+ 'user',+ JSON.stringify({ text: 'do not resurrect' }),+ 1_000,+ );await prepareExternalCodexSessionForResume(threadId);@@ -1236,18 +1483,46 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>it('synthesizes a rollout from localDb when the DB row exists but the file is missing', async () => {const dbPath = createStateDb(desktopHome());- const missingRollout = path.join(desktopHome(), 'sessions', '2026', '06', '15', `rollout-2026-06-15-${threadId}.jsonl`);+ const missingRollout = path.join(+ desktopHome(),+ 'sessions',+ '2026',+ '06',+ '15',+ `rollout-2026-06-15-${threadId}.jsonl`,+ );// threads 行存在、但 rollout 文件不写(孤儿)。insertThread(dbPath, threadId, missingRollout, { updatedAt: 2_000 });const sessionId = `local-orphan-${threadId}`;insertLocalCodexSession(sessionId, threadId);- insertLocalMessage(sessionId, 'c1', 'user', JSON.stringify({ text: '123312', images: [], files: [] }), 1000);- insertLocalMessage(sessionId, 'c2', 'thinking', JSON.stringify({ kind: 'thinking', text: 'internal' }), 1500);+ insertLocalMessage(+ sessionId,+ 'c1',+ 'user',+ JSON.stringify({ text: '123312', images: [], files: [] }),+ 1000,+ );+ insertLocalMessage(+ sessionId,+ 'c2',+ 'thinking',+ JSON.stringify({ kind: 'thinking', text: 'internal' }),+ 1500,+ );insertLocalMessage(sessionId, 'c3', 'assistant', '我没看懂你的意思。', 1600);- insertLocalMessage(sessionId, 'c4', 'user', JSON.stringify({ text: '444', images: [], files: [] }), 1700);+ insertLocalMessage(+ sessionId,+ 'c4',+ 'user',+ JSON.stringify({ text: '444', images: [], files: [] }),+ 1700,+ );const newerPartialSessionId = `local-orphan-partial-${threadId}`;- insertLocalCodexSession(newerPartialSessionId, threadId, { createdAt: 1_500, updatedAt: 3_000 });+ insertLocalCodexSession(newerPartialSessionId, threadId, {+ createdAt: 1_500,+ updatedAt: 3_000,+ });insertLocalMessage(newerPartialSessionId,'partial-1',@@ -1260,14 +1535,24 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>await prepareExternalCodexSessionForResume(threadId);expect(fs.existsSync(missingRollout)).toBe(true);- const lines = fs.readFileSync(missingRollout, 'utf-8').trim().split('\n').map((l) => JSON.parse(l));+ const lines = fs+ .readFileSync(missingRollout, 'utf-8')+ .trim()+ .split('\n')+ .map((l) => JSON.parse(l));// 第一行 session_meta,id 正确。expect(lines[0]).toMatchObject({ type: 'session_meta', payload: { id: threadId } });// 后续仅 user/assistant 的 response_item(thinking 被跳过)。const items = lines.slice(1);- expect(items.every((l) => l.type === 'response_item' && l.payload.type === 'message')).toBe(true);+ expect(items.every((l) => l.type === 'response_item' && l.payload.type === 'message')).toBe(+ true,+ );expect(items.map((l) => l.payload.role)).toEqual(['user', 'assistant', 'user']);- expect(items.map((l) => l.payload.content[0].text)).toEqual(['123312', '我没看懂你的意思。', '444']);+ expect(items.map((l) => l.payload.content[0].text)).toEqual([+ '123312',+ '我没看懂你的意思。',+ '444',+ ]);// user 用 input_text、assistant 用 output_text。expect(items[0].payload.content[0].type).toBe('input_text');expect(items[1].payload.content[0].type).toBe('output_text');@@ -1275,14 +1560,24 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>it('does not overwrite an existing rollout file (happy path short-circuit)', async () => {const dbPath = createStateDb(desktopHome());- const rolloutPath = path.join(desktopHome(), 'sessions', `rollout-2026-06-15-${threadId}.jsonl`);+ const rolloutPath = path.join(+ desktopHome(),+ 'sessions',+ `rollout-2026-06-15-${threadId}.jsonl`,+ );fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });fs.writeFileSync(rolloutPath, 'ORIGINAL_CONTENT');insertThread(dbPath, threadId, rolloutPath, { updatedAt: 2_000 });const sessionId = `local-orphan-${threadId}`;insertLocalCodexSession(sessionId, threadId);- insertLocalMessage(sessionId, 'c1', 'user', JSON.stringify({ text: 'hi', images: [], files: [] }), 1000);+ insertLocalMessage(+ sessionId,+ 'c1',+ 'user',+ JSON.stringify({ text: 'hi', images: [], files: [] }),+ 1000,+ );await prepareExternalCodexSessionForResume(threadId);@@ -1291,7 +1586,11 @@ describe('prepareExternalCodexSessionForResume orphan rollout synthesis', () =>it('does not synthesize when there is no readable localDb history', async () => {const dbPath = createStateDb(desktopHome());- const missingRollout = path.join(desktopHome(), 'sessions', `rollout-2026-06-15-${threadId}.jsonl`);+ const missingRollout = path.join(+ desktopHome(),+ 'sessions',+ `rollout-2026-06-15-${threadId}.jsonl`,+ );insertThread(dbPath, threadId, missingRollout, { updatedAt: 2_000 });// 有 threads 行,但 localDb 里没有对应会话/消息。diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.tsindex f29df9e9bb..5c19beda41 100644--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts@@ -287,28 +287,29 @@ describe('maker:event hot path ordering', () => {expect(codexDoneSource).toContain('const price = isCodexXaiProviderRoute');expect(codexDoneSource).toContain('? getSubscriptionDirectValuePrice(pricingModel)');expect(codexDoneSource).toContain('? getCodexSubscriptionValuePrice(pricingModel, pricing)');- expect(codexDoneSource).toContain(': pricing?.[pricingModel]');+ expect(codexDoneSource).toContain(": getModelPriceQuote(pricing, 'xd', pricingModel)");expect(codexDoneSource).toContain('const pricing = isSubscriptionValue && !isCodexXaiProviderRoute');expect(codexDoneSource).toContain('? await getModelPricing()');- expect(codexDoneSource).toContain(': await getModelPricingForModel(pricingModel)');+ expect(codexDoneSource).toContain(": await getModelPricingForModel('xd', pricingModel)");+ expect(codexDoneSource).toContain('regionalizeModelPriceQuote(price, CURRENT_CINDY_REGION)');+ expect(codexDoneSource).toContain('if (!isSubscriptionValue && money)');+ expect(codexDoneSource).toContain('void recordTurnSpend(money);');+ expect(codexDoneSource).toContain('void recordSessionTurnSpend(session.id, money);');expect(codexDoneSource).toMatch(- /if \(!isSubscriptionValue\) \{\s*void recordTurnSpend\(cost\);\s*void recordSessionTurnSpend\(session\.id, cost\);/,+ /await recordModelTurnUsage\(\{\s*agentKind: 'codex',\s*model: modelUsageKey,\s*inputTokensDelta: promptTokens,\s*outputTokensDelta: completionTokens,\s*cacheReadTokensDelta: cachedTokens,\s*cacheCreateTokensDelta: 0,\s*\}\)\.finally\(\(\) => rebroadcastCodexTodayUsage\(\)\);[\s\S]*?const pricing = isSubscriptionValue && !isCodexXaiProviderRoute/,);expect(codexDoneSource).toMatch(- /await recordModelTurnUsage\(\{\s*agentKind: 'codex',\s*model: modelUsageKey,\s*costUsdDelta: 0,\s*inputTokensDelta: promptTokens,\s*outputTokensDelta: completionTokens,\s*cacheReadTokensDelta: cachedTokens,\s*cacheCreateTokensDelta: 0,\s*\}\)\.finally\(\(\) => rebroadcastCodexTodayUsage\(\)\);[\s\S]*?const pricing = isSubscriptionValue && !isCodexXaiProviderRoute/,+ /await recordModelTurnUsage\(\{\s*agentKind: 'codex',\s*model: modelUsageKey,\s*money,\s*inputTokensDelta: 0,\s*outputTokensDelta: 0,\s*cacheReadTokensDelta: 0,\s*cacheCreateTokensDelta: 0,\s*\}\);/,);- expect(codexDoneSource).toMatch(- /await recordModelTurnUsage\(\{\s*agentKind: 'codex',\s*model: modelUsageKey,\s*costUsdDelta: cost,\s*inputTokensDelta: 0,\s*outputTokensDelta: 0,\s*cacheReadTokensDelta: 0,\s*cacheCreateTokensDelta: 0,\s*\}\);/,- );- const costRecordIndex = codexDoneSource.indexOf('void recordTurnSpend(cost);');- const modelCostRecordIndex = codexDoneSource.indexOf('costUsdDelta: cost,');+ const costRecordIndex = codexDoneSource.indexOf('void recordTurnSpend(money);');+ const modelCostRecordIndex = codexDoneSource.indexOf('if (!isSubscriptionValue && money)');const schedulerCostRecordIndex = codexDoneSource.indexOf('await recordSchedulerTurnCost({');expect(costRecordIndex).toBeGreaterThanOrEqual(0);expect(modelCostRecordIndex).toBeGreaterThanOrEqual(0);expect(modelCostRecordIndex).toBeGreaterThan(codexDoneSource.indexOf('const pricing = isSubscriptionValue && !isCodexXaiProviderRoute'));expect(schedulerCostRecordIndex).toBeGreaterThan(costRecordIndex);expect(codexDoneSource).toContain('clientId: turnAssistantPersistId');- expect(codexDoneSource).toContain('isEstimate: isSubscriptionValue');+ expect(codexDoneSource).toContain('money,');expect(codexDoneSource).toContain('if (!isRemoteCodexSession &&');expect(codexDoneSource).toContain("!model.startsWith(XAI_MODEL_PREFIX) &&");expect(codexDoneSource).toContain("(codexAuthInjection === 'env-key' || model.startsWith('codex/') || (sessionProvider === 'xd' && hasGatewayKey))");@@ -325,24 +326,27 @@ describe('maker:event hot path ordering', () => {// 仅取 claude-code 块 (到 codex 块前)。const claudeDoneSource = wireSessionSource.slice(claudeDoneIndex, codexDoneIndex);- // 主路径: 逐模型 HYBRID 定价 (Anthropic→SDK, 非 Anthropic→gateway), 四个 sink 同源同值。- expect(claudeDoneSource).toContain('const gatewayPricingModels = Array.from(new Set(');- expect(claudeDoneSource).toContain('.filter((model) => !isAnthropicModel(model) && !isSubscriptionDirectModel(model))');- expect(claudeDoneSource).toContain('for (const model of gatewayPricingModels) {');- expect(claudeDoneSource).toContain('pricing = await getModelPricingForModel(model);');- expect(claudeDoneSource).not.toContain('const gatewayPricingModel = deltas');- expect(claudeDoneSource).not.toContain('const pricing = needsPricing ? await getModelPricing() : null;');- expect(claudeDoneSource).toContain('const { turnTotalUsd, perModel } = resolveClaudeTurnCostSinks(deltas, pricing);');- expect(claudeDoneSource).toContain('recordTurnSpend(turnTotalUsd);');- expect(claudeDoneSource).toContain('recordSessionTurnSpend(session.id, turnTotalUsd);');- expect(claudeDoneSource).toContain('costUsdDelta: m.costUsd,');+ // 主路径:按真实 provider / billing route 取价,所有 sink 共用区域金额结果。+ expect(claudeDoneSource).toContain('const billingRoute: BillingRoute = session.remoteHostId');+ expect(claudeDoneSource).toContain("billingRoute === 'xd-gateway'");+ expect(claudeDoneSource).toContain("await getModelPricingForModel(");+ expect(claudeDoneSource).toContain("'xd',");+ expect(claudeDoneSource).toContain('normalizeModelIdForPricing(deltas[0]?.model)');+ expect(claudeDoneSource).toContain(': await getModelPricing();');+ 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,');// 订阅轮 (Claude Anthropic 订阅或 bridge 订阅直连) 打 #billing=subscription 标记,// 仪表盘按订阅估算价折算; 其余轮仍写归一化裸 id。expect(claudeDoneSource).toContain('model: isClaudeSubscriptionValueRow ? claudeSubscriptionUsageModelKey(m.model) : m.model,',);expect(claudeDoneSource).toContain(- "isClaudeSubscriptionSession && m.costUsd === 0 && isAnthropicModel(m.model)",+ "isClaudeSubscriptionSession && !m.money && isAnthropicModel(m.model)",);expect(claudeDoneSource).toContain("m.source === 'subscription' && isSubscriptionDirectModel(m.model)",diff --git a/apps/desktop/src/main/__tests__/patchMessageAgentMeta.test.ts b/apps/desktop/src/main/__tests__/patchMessageAgentMeta.test.tsindex 6271a6bda6..9f9cd1e77e 100644--- a/apps/desktop/src/main/__tests__/patchMessageAgentMeta.test.ts+++ b/apps/desktop/src/main/__tests__/patchMessageAgentMeta.test.ts@@ -83,9 +83,7 @@ beforeEach(() => {describe('patchMessageAgentMeta', () => {it('merge:保留已有 meta 字段(uuid 等 fork/rewind 锚点),合并 patch 字段', async () => {- selectQueue.push([- { agentMeta: JSON.stringify({ uuid: 'sdk-u1', model: 'claude-fable-5' }) },- ]);+ selectQueue.push([{ agentMeta: JSON.stringify({ uuid: 'sdk-u1', model: 'claude-fable-5' }) }]);const ok = await patchMessageAgentMeta('s1', 'm1', {turnCostUsd: 0.05,turnCostIsEstimate: false,@@ -122,18 +120,20 @@ describe('patchMessageAgentMeta', () => {});it('元数据更新复用 messages:created 广播权威完整行', async () => {- selectQueue.push([{- id: 'row-1',- sessionId: 's1',- clientId: 'm1',- role: 'assistant',- content: JSON.stringify('正式总结'),- toolUseId: null,- agentMeta: JSON.stringify({ turnCompleted: true }),- agentKind: 'cc',- createdAt: 1,- rewindAt: null,- }]);+ selectQueue.push([+ {+ id: 'row-1',+ sessionId: 's1',+ clientId: 'm1',+ role: 'assistant',+ content: JSON.stringify('正式总结'),+ toolUseId: null,+ agentMeta: JSON.stringify({ turnCompleted: true }),+ agentKind: 'cc',+ createdAt: 1,+ rewindAt: null,+ },+ ]);await expect(broadcastMessageAgentMetaUpdate('s1', 'm1')).resolves.toBe(true);expect(mockSend).toHaveBeenCalledWith(@@ -151,102 +151,115 @@ describe('patchMessageAgentMeta', () => {describe('extractEstimatedSessionValueEntries', () => {it('只汇总订阅模式估算价值,忽略真实 API cost / 非法 meta', () => {- expect(extractEstimatedSessionValueEntries([- {- clientId: 'estimate-1',- agentMeta: JSON.stringify({ turnCostUsd: 0.12, turnCostIsEstimate: true }),+ const legacyEstimatedEntry = (clientId: string, costUsd: number) => ({+ clientId,+ money: {+ amount: expect.closeTo(costUsd * 6.7),+ currency: 'CNY',+ approximate: true,+ kind: 'value-estimate',+ estimateReasons: ['fixed-fx', 'legacy-usd', 'subscription-value'],},- {- clientId: 'api-cost',- agentMeta: JSON.stringify({ turnCostUsd: 0.34, turnCostIsEstimate: false }),- },- {- clientId: 'missing-flag',- agentMeta: JSON.stringify({ turnCostUsd: 0.56 }),- },- {- clientId: 'zero',- agentMeta: JSON.stringify({ turnCostUsd: 0, turnCostIsEstimate: true }),- },- {- clientId: 'broken',- agentMeta: '{broken',- },- {- clientId: 'estimate-2',- agentMeta: JSON.stringify({ uuid: 'u2', turnCostUsd: 0.03, turnCostIsEstimate: true }),- },- {- clientId: 'estimate-recomputed',- agentMeta: JSON.stringify({- turnCostUsd: 8.76,- turnCostIsEstimate: true,- turnUsageDetails: {- inputTokens: 213_800,- outputTokens: 6_400,- cacheReadTokens: 1_500_000,- cacheCreateTokens: 0,- totalTokens: 1_720_200,- cacheHitRate: 0.875,+ costUsd: expect.closeTo(costUsd),+ });+ expect(+ extractEstimatedSessionValueEntries([+ {+ clientId: 'estimate-1',+ agentMeta: JSON.stringify({ turnCostUsd: 0.12, turnCostIsEstimate: true }),+ },+ {+ clientId: 'api-cost',+ agentMeta: JSON.stringify({ turnCostUsd: 0.34, turnCostIsEstimate: false }),+ },+ {+ clientId: 'missing-flag',+ agentMeta: JSON.stringify({ turnCostUsd: 0.56 }),+ },+ {+ clientId: 'zero',+ agentMeta: JSON.stringify({ turnCostUsd: 0, turnCostIsEstimate: true }),+ },+ {+ clientId: 'broken',+ agentMeta: '{broken',+ },+ {+ clientId: 'estimate-2',+ agentMeta: JSON.stringify({ uuid: 'u2', turnCostUsd: 0.03, turnCostIsEstimate: true }),+ },+ {+ clientId: 'estimate-recomputed',+ agentMeta: JSON.stringify({+ turnCostUsd: 8.76,+ turnCostIsEstimate: true,+ turnUsageDetails: {+ inputTokens: 213_800,+ outputTokens: 6_400,+ cacheReadTokens: 1_500_000,+ cacheCreateTokens: 0,+ totalTokens: 1_720_200,+ cacheHitRate: 0.875,+ model: 'gpt-5.5',+ },+ }),+ },+ {+ clientId: 'estimate-recomputed-meta-model',+ agentMeta: JSON.stringify({model: 'gpt-5.5',- },- }),- },- {- clientId: 'estimate-recomputed-meta-model',- agentMeta: JSON.stringify({- model: 'gpt-5.5',- turnCostUsd: 8.76,- turnCostIsEstimate: true,- turnUsageDetails: {- inputTokens: 213_800,- outputTokens: 6_400,- cacheReadTokens: 1_500_000,- cacheCreateTokens: 0,- totalTokens: 1_720_200,- cacheHitRate: 0.875,- },- }),- },- {- clientId: 'estimate-legacy-fallback-recomputed',- agentMeta: JSON.stringify({- model: 'gpt-5.5',- turnCostUsd: 3.4788,- turnCostIsEstimate: true,- turnUsageDetails: {- inputTokens: 213_800,- outputTokens: 6_400,- cacheReadTokens: 1_500_000,- cacheCreateTokens: 0,- totalTokens: 1_720_200,- cacheHitRate: 0.875,- },- }),- },- {- clientId: 'estimate-live-pricing-preserved',- agentMeta: JSON.stringify({- model: 'gpt-5.5',- turnCostUsd: 3.14,- turnCostIsEstimate: true,- turnUsageDetails: {- inputTokens: 213_800,- outputTokens: 6_400,- cacheReadTokens: 1_500_000,- cacheCreateTokens: 0,- totalTokens: 1_720_200,- cacheHitRate: 0.875,- },- }),- },- ])).toEqual([- { clientId: 'estimate-1', costUsd: 0.12 },- { clientId: 'estimate-2', costUsd: 0.03 },- { clientId: 'estimate-recomputed', costUsd: expect.closeTo(2.011) },- { clientId: 'estimate-recomputed-meta-model', costUsd: expect.closeTo(2.011) },- { clientId: 'estimate-legacy-fallback-recomputed', costUsd: expect.closeTo(2.011) },- { clientId: 'estimate-live-pricing-preserved', costUsd: 3.14 },+ turnCostUsd: 8.76,+ turnCostIsEstimate: true,+ turnUsageDetails: {+ inputTokens: 213_800,+ outputTokens: 6_400,+ cacheReadTokens: 1_500_000,+ cacheCreateTokens: 0,+ totalTokens: 1_720_200,+ cacheHitRate: 0.875,+ },+ }),+ },+ {+ clientId: 'estimate-legacy-fallback-recomputed',+ agentMeta: JSON.stringify({+ model: 'gpt-5.5',+ turnCostUsd: 3.4788,+ turnCostIsEstimate: true,+ turnUsageDetails: {+ inputTokens: 213_800,+ outputTokens: 6_400,+ cacheReadTokens: 1_500_000,+ cacheCreateTokens: 0,+ totalTokens: 1_720_200,+ cacheHitRate: 0.875,+ },+ }),+ },+ {+ clientId: 'estimate-live-pricing-preserved',+ agentMeta: JSON.stringify({+ model: 'gpt-5.5',+ turnCostUsd: 3.14,+ turnCostIsEstimate: true,+ turnUsageDetails: {+ inputTokens: 213_800,+ outputTokens: 6_400,+ cacheReadTokens: 1_500_000,+ cacheCreateTokens: 0,+ totalTokens: 1_720_200,+ cacheHitRate: 0.875,+ },+ }),+ },+ ]),+ ).toEqual([+ legacyEstimatedEntry('estimate-1', 0.12),+ legacyEstimatedEntry('estimate-2', 0.03),+ legacyEstimatedEntry('estimate-recomputed', 2.011),+ legacyEstimatedEntry('estimate-recomputed-meta-model', 2.011),+ legacyEstimatedEntry('estimate-legacy-fallback-recomputed', 2.011),+ legacyEstimatedEntry('estimate-live-pricing-preserved', 3.14),]);});});diff --git a/apps/desktop/src/main/__tests__/turnCostBroadcaster.test.ts b/apps/desktop/src/main/__tests__/turnCostBroadcaster.test.tsindex f5e631973d..752eb0f62e 100644--- a/apps/desktop/src/main/__tests__/turnCostBroadcaster.test.ts+++ b/apps/desktop/src/main/__tests__/turnCostBroadcaster.test.ts@@ -24,7 +24,7 @@ vi.mock('../localDb/ipc/messages.js', () => ({previous: {},next: patch,})),- readPriorUserRoundCost: vi.fn(async () => ({ costUsd: 0, hasEstimatedValue: false })),+ readPriorUserRoundCost: vi.fn(async () => ({ money: null, costUsd: 0, hasEstimatedValue: false })),}));vi.mock('../scheduler-host/runCostLedger.js', () => ({applyScheduleRunCostMetaChange: vi.fn(async () => undefined),@@ -45,10 +45,40 @@ import {buildTurnUsageDetails,type TurnUsageDetails,} from '../../shared/turnUsageDetails.js';+import type { RegionalMoney } from '../../shared/regionalMoney.js';++function usdMoney(+ amount: number,+ kind: RegionalMoney['kind'] = 'actual-cost',+): RegionalMoney {+ return {+ amount,+ currency: 'USD',+ approximate: kind === 'value-estimate',+ kind,+ ...(kind === 'value-estimate'+ ? { estimateReasons: ['subscription-value'] }+ : {}),+ };+}++function cnyMoney(amount: number): RegionalMoney {+ return {+ amount,+ currency: 'CNY',+ approximate: false,+ kind: 'actual-cost',+ };+}function makeDeps(patchResult: boolean | Error = true,- prior: { costUsd: number; hasEstimatedValue: boolean } | Error = {+ prior: {+ money: RegionalMoney | null;+ costUsd: number;+ hasEstimatedValue: boolean;+ } | Error = {+ money: null,costUsd: 0,hasEstimatedValue: false,},@@ -83,7 +113,7 @@ function makeDeps(return { deps, broadcasts, patchCalls, runCostCalls };}-const ARGS = { sessionId: 's1', clientId: 'm1', costUsd: 0.042, isEstimate: false };+const ARGS = { sessionId: 's1', clientId: 'm1', money: usdMoney(0.042) };const DETAILS = buildTurnUsageDetails({inputTokens: 1000,outputTokens: 200,@@ -105,8 +135,10 @@ describe('recordTurnCostOnMessage', () => {sessionId: 's1',clientId: 'm1',patch: {+ turnCost: usdMoney(0.042),turnCostUsd: 0.042,turnCostIsEstimate: false,+ userTurnCost: usdMoney(0.042),userTurnCostUsd: 0.042,userTurnCostIsEstimate: false,},@@ -116,8 +148,10 @@ describe('recordTurnCostOnMessage', () => {{sessionId: 's1',clientId: 'm1',+ turnMoney: usdMoney(0.042),turnCostUsd: 0.042,turnCostIsEstimate: false,+ userTurnMoney: usdMoney(0.042),userTurnCostUsd: 0.042,userTurnCostIsEstimate: false,},@@ -128,8 +162,10 @@ describe('recordTurnCostOnMessage', () => {const { deps, broadcasts, patchCalls } = makeDeps(true);await recordTurnCostOnMessage({ ...ARGS, turnUsageDetails: DETAILS }, deps);expect(patchCalls[0]?.patch).toEqual({+ turnCost: usdMoney(0.042),turnCostUsd: 0.042,turnCostIsEstimate: false,+ userTurnCost: usdMoney(0.042),userTurnCostUsd: 0.042,userTurnCostIsEstimate: false,turnUsageDetails: DETAILS,@@ -137,8 +173,10 @@ describe('recordTurnCostOnMessage', () => {expect(broadcasts[0]).toEqual({sessionId: 's1',clientId: 'm1',+ turnMoney: usdMoney(0.042),turnCostUsd: 0.042,turnCostIsEstimate: false,+ userTurnMoney: usdMoney(0.042),userTurnCostUsd: 0.042,userTurnCostIsEstimate: false,turnUsageDetails: DETAILS,@@ -147,7 +185,10 @@ describe('recordTurnCostOnMessage', () => {it('订阅模式 token 价值标记(isEstimate=true)原样透传', async () => {const { deps, broadcasts } = makeDeps(true);- await recordTurnCostOnMessage({ ...ARGS, isEstimate: true }, deps);+ await recordTurnCostOnMessage(+ { ...ARGS, money: usdMoney(0.042, 'value-estimate') },+ deps,+ );expect(broadcasts[0]?.turnCostIsEstimate).toBe(true);expect(broadcasts[0]?.userTurnCostIsEstimate).toBe(true);});@@ -168,6 +209,7 @@ describe('recordTurnCostOnMessage', () => {previous: {},next: expect.objectContaining({origin: turnOrigin,+ turnCost: usdMoney(0.042),turnCostUsd: 0.042,turnCostIsEstimate: false,}),@@ -176,14 +218,17 @@ describe('recordTurnCostOnMessage', () => {it('多段 SDK done 的展示累计完整,但原始分段成本不变', async () => {const { deps, broadcasts, patchCalls } = makeDeps(true, {+ money: usdMoney(51.452182),costUsd: 51.452182,hasEstimatedValue: false,});- await recordTurnCostOnMessage({ ...ARGS, costUsd: 0.777042 }, deps);+ await recordTurnCostOnMessage({ ...ARGS, money: usdMoney(0.777042) }, deps);expect(patchCalls[0]?.patch).toEqual({+ turnCost: usdMoney(0.777042),turnCostUsd: 0.777042,turnCostIsEstimate: false,+ userTurnCost: usdMoney(52.229224),userTurnCostUsd: 52.229224,userTurnCostIsEstimate: false,});@@ -195,6 +240,7 @@ describe('recordTurnCostOnMessage', () => {it('先前任一分段为估算值时,累计展示也标为估算', async () => {const { deps, broadcasts } = makeDeps(true, {+ money: usdMoney(1.2, 'value-estimate'),costUsd: 1.2,hasEstimatedValue: true,});@@ -205,6 +251,46 @@ describe('recordTurnCostOnMessage', () => {});});+ it('CNY 只写结构化金额,不伪造 legacy USD 投影', async () => {+ const { deps, broadcasts, patchCalls } = makeDeps(true);+ await recordTurnCostOnMessage(+ { ...ARGS, money: cnyMoney(3) },+ deps,+ );++ expect(patchCalls[0]?.patch).toEqual({+ turnCost: cnyMoney(3),+ turnCostIsEstimate: false,+ userTurnCost: cnyMoney(3),+ userTurnCostIsEstimate: false,+ });+ expect(broadcasts[0]).toEqual({+ sessionId: 's1',+ clientId: 'm1',+ turnMoney: cnyMoney(3),+ turnCostIsEstimate: false,+ userTurnMoney: cnyMoney(3),+ userTurnCostIsEstimate: false,+ });+ });++ it('混币历史估值不污染当前实际金额', async () => {+ const { deps, broadcasts } = makeDeps(true, {+ money: usdMoney(1.2, 'value-estimate'),+ costUsd: 1.2,+ hasEstimatedValue: true,+ });+ await recordTurnCostOnMessage(+ { ...ARGS, money: cnyMoney(3) },+ deps,+ );++ expect(broadcasts[0]).toMatchObject({+ userTurnMoney: cnyMoney(3),+ userTurnCostIsEstimate: false,+ });+ });+it('patch 返回 false(行不存在,典型 rewind 已删)→ 不广播', async () => {const { deps, broadcasts, patchCalls } = makeDeps(false);await expect(recordTurnCostOnMessage(ARGS, deps)).resolves.toBe(false);@@ -212,10 +298,13 @@ describe('recordTurnCostOnMessage', () => {expect(broadcasts).toHaveLength(0);});- it('costUsd ≤ 0 / NaN / Infinity → 跳过(不 patch 不广播)', async () => {+ it('金额 ≤ 0 / NaN / Infinity → 跳过(不 patch 不广播)', async () => {const { deps, broadcasts, patchCalls } = makeDeps(true);for (const bad of [0, -1, NaN, Infinity, 1e-12]) {- await recordTurnCostOnMessage({ ...ARGS, costUsd: bad }, deps);+ await recordTurnCostOnMessage({+ ...ARGS,+ money: { ...usdMoney(0), amount: bad },+ }, deps);}expect(patchCalls).toHaveLength(0);expect(broadcasts).toHaveLength(0);@@ -272,8 +361,7 @@ describe('recordSchedulerTurnCost', () => {await expect(recordSchedulerTurnCost({sessionId: 's1',- costUsd: 0.42,- isEstimate: false,+ money: usdMoney(0.42),turnOrigin: schedulerOrigin,},{ recordOnMessage, recordDirect },@@ -282,8 +370,7 @@ describe('recordSchedulerTurnCost', () => {expect(recordOnMessage).not.toHaveBeenCalled();expect(recordDirect).toHaveBeenCalledWith({runId: 'run-1',- costUsd: 0.42,- isEstimate: false,+ money: usdMoney(0.42),});});@@ -329,8 +416,7 @@ describe('recordSchedulerTurnCost', () => {await expect(recordSchedulerTurnCost({sessionId: 's1',- costUsd: 0,- isEstimate: false,+ money: usdMoney(0),turnOrigin: schedulerOrigin,},{ recordOnMessage, recordDirect },@@ -338,8 +424,7 @@ describe('recordSchedulerTurnCost', () => {expect(recordDirect).toHaveBeenCalledWith({runId: 'run-1',- costUsd: 0,- isEstimate: false,+ money: usdMoney(0),});});});diff --git a/apps/desktop/src/main/localDb/__tests__/drizzle-proxy-perf.bench.ts b/apps/desktop/src/main/localDb/__tests__/drizzle-proxy-perf.bench.tsindex 237f378ac0..a998b7d3f0 100644--- a/apps/desktop/src/main/localDb/__tests__/drizzle-proxy-perf.bench.ts+++ b/apps/desktop/src/main/localDb/__tests__/drizzle-proxy-perf.bench.ts@@ -40,6 +40,9 @@ const CREATE_TABLES = [sdk_session_id TEXT,total_token_usage INTEGER NOT NULL DEFAULT 0,total_cost_usd REAL NOT NULL DEFAULT 0,+ total_cost_amount REAL NOT NULL DEFAULT 0,+ total_cost_currency TEXT,+ total_cost_is_approximate INTEGER NOT NULL DEFAULT 0,context_tokens INTEGER NOT NULL DEFAULT 0,context_window INTEGER NOT NULL DEFAULT 0,fast_mode INTEGER NOT NULL DEFAULT 0,diff --git a/apps/desktop/src/main/localDb/__tests__/drizzle-split.spike.test.ts b/apps/desktop/src/main/localDb/__tests__/drizzle-split.spike.test.tsindex e39e7332a0..4b158beb11 100644--- a/apps/desktop/src/main/localDb/__tests__/drizzle-split.spike.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/drizzle-split.spike.test.ts@@ -156,6 +156,52 @@ function applyMigrationScriptSync(db: Sqlite, fileName: string): void {if (fileName === '0065_equal_shinobi_shaw.sql') {ensureColumnSync(db, 'sessions', 'last_turn_ended_at', 'integer');}+ if (fileName === '0080_regional_money.sql') {+ ensureColumnSync(db, 'sessions', 'total_cost_amount', 'real DEFAULT 0 NOT NULL');+ ensureColumnSync(db, 'sessions', 'total_cost_currency', 'text');+ ensureColumnSync(+ db,+ 'sessions',+ 'total_cost_is_approximate',+ 'integer DEFAULT 0 NOT NULL',+ );+ ensureColumnSync(db, 'daily_spend', 'cost_amount', 'real DEFAULT 0 NOT NULL');+ ensureColumnSync(db, 'daily_spend', 'cost_currency', 'text');+ ensureColumnSync(+ db,+ 'daily_spend',+ 'cost_is_approximate',+ 'integer DEFAULT 0 NOT NULL',+ );+ ensureColumnSync(+ db,+ 'daily_model_usage',+ 'cost_amount',+ 'real DEFAULT 0 NOT NULL',+ );+ ensureColumnSync(db, 'daily_model_usage', 'cost_currency', 'text');+ ensureColumnSync(+ db,+ 'daily_model_usage',+ 'cost_is_approximate',+ 'integer DEFAULT 0 NOT NULL',+ );+ ensureColumnSync(db, 'schedule_runs', 'cost_amount', 'real DEFAULT 0 NOT NULL');+ ensureColumnSync(+ db,+ 'schedule_runs',+ 'estimated_value_amount',+ 'real DEFAULT 0 NOT NULL',+ );+ ensureColumnSync(db, 'schedule_runs', 'cost_currency', 'text');+ ensureColumnSync(+ db,+ 'schedule_runs',+ 'cost_is_approximate',+ 'integer DEFAULT 0 NOT NULL',+ );+ return;+ }}async function applyMigrationScript(target: DbClient, fileName: string): Promise<void> {@@ -190,6 +236,52 @@ async function applyMigrationScript(target: DbClient, fileName: string): Promiseif (fileName === '0065_equal_shinobi_shaw.sql') {await ensureColumn(target, 'sessions', 'last_turn_ended_at', 'integer');}+ if (fileName === '0080_regional_money.sql') {+ await ensureColumn(target, 'sessions', 'total_cost_amount', 'real DEFAULT 0 NOT NULL');+ await ensureColumn(target, 'sessions', 'total_cost_currency', 'text');+ await ensureColumn(+ target,+ 'sessions',+ 'total_cost_is_approximate',+ 'integer DEFAULT 0 NOT NULL',+ );+ await ensureColumn(target, 'daily_spend', 'cost_amount', 'real DEFAULT 0 NOT NULL');+ await ensureColumn(target, 'daily_spend', 'cost_currency', 'text');+ await ensureColumn(+ target,+ 'daily_spend',+ 'cost_is_approximate',+ 'integer DEFAULT 0 NOT NULL',+ );+ await ensureColumn(+ target,+ 'daily_model_usage',+ 'cost_amount',+ 'real DEFAULT 0 NOT NULL',+ );+ await ensureColumn(target, 'daily_model_usage', 'cost_currency', 'text');+ await ensureColumn(+ target,+ 'daily_model_usage',+ 'cost_is_approximate',+ 'integer DEFAULT 0 NOT NULL',+ );+ await ensureColumn(target, 'schedule_runs', 'cost_amount', 'real DEFAULT 0 NOT NULL');+ await ensureColumn(+ target,+ 'schedule_runs',+ 'estimated_value_amount',+ 'real DEFAULT 0 NOT NULL',+ );+ await ensureColumn(target, 'schedule_runs', 'cost_currency', 'text');+ await ensureColumn(+ target,+ 'schedule_runs',+ 'cost_is_approximate',+ 'integer DEFAULT 0 NOT NULL',+ );+ return;+ }}function applyOrcaMultiWorkerPhase1Sync(db: Sqlite): void {diff --git a/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts b/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.tsindex 33859868ca..9fd3ad2a47 100644--- a/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts@@ -44,15 +44,19 @@ describe('orcaTeamStore', () => {await seedOrcaWorkers(client);- await expect(getWorkerLink({- workerId: 'worker-1',- workerSessionId: 'worker-session-2',- })).resolves.toBeNull();+ await expect(+ getWorkerLink({+ workerId: 'worker-1',+ workerSessionId: 'worker-session-2',+ }),+ ).resolves.toBeNull();- await expect(getWorkerLink({- workerId: 'worker-1',- workerSessionId: 'worker-session-1',- })).resolves.toMatchObject({+ await expect(+ getWorkerLink({+ workerId: 'worker-1',+ workerSessionId: 'worker-session-1',+ }),+ ).resolves.toMatchObject({workerId: 'worker-1',workerSessionId: 'worker-session-1',leadSessionId: 'lead-session-1',@@ -74,10 +78,12 @@ describe('orcaTeamStore', () => {'worker-session-2',]);- expect(await client.query<{ id: string; status: string }>(- 'SELECT id, status FROM sessions WHERE id IN (?, ?) ORDER BY id',- ['worker-session-1', 'worker-session-2'],- )).toEqual([+ expect(+ await client.query<{ id: string; status: string }>(+ 'SELECT id, status FROM sessions WHERE id IN (?, ?) ORDER BY id',+ ['worker-session-1', 'worker-session-2'],+ ),+ ).toEqual([{ id: 'worker-session-1', status: 'archived' },{ id: 'worker-session-2', status: 'archived' },]);@@ -99,8 +105,7 @@ describe('orcaTeamStore', () => {});it('executes worker status CAS updates and only rolls back idle acknowledgements', async () => {- const { markWorkerIdleIfStatus, restoreWorkerDoneIfIdle } =- await import('../orcaTeamStore.js');+ const { markWorkerIdleIfStatus, restoreWorkerDoneIfIdle } = await import('../orcaTeamStore.js');const client = createTestDbClient();setCurrentDbClient(client, 'test-user');@@ -140,6 +145,9 @@ describe('orcaTeamStore', () => {sdk_session_id TEXT,total_token_usage INTEGER NOT NULL DEFAULT 0,total_cost_usd REAL NOT NULL DEFAULT 0,+ total_cost_amount REAL NOT NULL DEFAULT 0,+ total_cost_currency TEXT,+ total_cost_is_approximate INTEGER NOT NULL DEFAULT 0,context_tokens INTEGER NOT NULL DEFAULT 0,context_window INTEGER NOT NULL DEFAULT 0,fast_mode INTEGER NOT NULL DEFAULT 0,diff --git a/apps/desktop/src/main/localDb/__tests__/workingDirHistoryFilter.test.ts b/apps/desktop/src/main/localDb/__tests__/workingDirHistoryFilter.test.tsindex 31ef4c8588..07e35534f1 100644--- a/apps/desktop/src/main/localDb/__tests__/workingDirHistoryFilter.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/workingDirHistoryFilter.test.ts@@ -9,8 +9,7 @@ vi.mock('electron', () => ({}));vi.mock('../../appSessionState.js', () => ({- ownerScopedUserDataPath: (...parts: string[]) =>- ['/tmp/xdt-test-user-data', ...parts].join('/'),+ ownerScopedUserDataPath: (...parts: string[]) => ['/tmp/xdt-test-user-data', ...parts].join('/'),}));import {@@ -42,6 +41,9 @@ function createLocalDb(): Database.Database {sdk_session_id TEXT,total_token_usage INTEGER NOT NULL DEFAULT 0,total_cost_usd REAL NOT NULL DEFAULT 0,+ total_cost_amount REAL NOT NULL DEFAULT 0,+ total_cost_currency TEXT,+ total_cost_is_approximate INTEGER NOT NULL DEFAULT 0,context_tokens INTEGER NOT NULL DEFAULT 0,context_window INTEGER NOT NULL DEFAULT 0,fast_mode INTEGER NOT NULL DEFAULT 0,@@ -126,7 +128,9 @@ afterEach(() => {describe('normalizeHistoryWorkingDir', () => {it('normalizes legacy Windows drive and UNC spellings', () => {expect(normalizeHistoryWorkingDir('D:\\repo\\project')).toBe('D:/repo/project');- expect(normalizeHistoryWorkingDir('\\\\?\\UNC\\server\\share\\repo')).toBe('//server/share/repo');+ expect(normalizeHistoryWorkingDir('\\\\?\\UNC\\server\\share\\repo')).toBe(+ '//server/share/repo',+ );});});@@ -162,7 +166,11 @@ describe('resolveStoredWorkingDirCandidates', () => {insertSession(db, 'p1', '/repo/project', 2_000);expect(await resolveStoredWorkingDirCandidates(dialogueDir)).toEqual([dialogueDir]);- expect(await resolveStoredWorkingDirCandidates('/tmp/xdt-test-user-data/dialogues/2026-07-04/absent')).toEqual([]);+ expect(+ await resolveStoredWorkingDirCandidates(+ '/tmp/xdt-test-user-data/dialogues/2026-07-04/absent',+ ),+ ).toEqual([]);});it('still resolves project dirs when the DB is dominated by managed dialogue rows', async () => {@@ -215,7 +223,11 @@ describe('listWorkdirsForHistory managed dialogue exclusion', () => {const page = await listWorkdirsForHistory({ limit: 10, cursor: null, order: 'desc' });expect(page.items.map((w) => w.workingDir).sort()).toEqual(- ['/repo/dialogue-target', '/repo/project', '/tmp/xdt-test-user-data/dialogues-project'].sort(),+ [+ '/repo/dialogue-target',+ '/repo/project',+ '/tmp/xdt-test-user-data/dialogues-project',+ ].sort(),);});});diff --git a/apps/desktop/src/main/localDb/client/__tests__/WorkerThreadTransport.test.ts b/apps/desktop/src/main/localDb/client/__tests__/WorkerThreadTransport.test.tsindex 3689a7d41b..9e455891e1 100644--- a/apps/desktop/src/main/localDb/client/__tests__/WorkerThreadTransport.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/WorkerThreadTransport.test.ts@@ -3,10 +3,7 @@ import os from 'node:os';import path from 'node:path';import { describe, expect, it } from 'vitest';-import {- buildDbWorkerBundle,- createMigratedSmokeDb,-} from '../../__tests__/dbWorkerTestUtils.js';+import { buildDbWorkerBundle, createMigratedSmokeDb } from '../../__tests__/dbWorkerTestUtils.js';import type { LogEvent, VecStatusEvent } from '../DbTransport.js';import { WorkerThreadTransport } from '../WorkerThreadTransport.js';@@ -21,9 +18,11 @@ describe('WorkerThreadTransport', () => {sql: 'INSERT INTO t (name) VALUES (?)',params: ['alice'],});- await expect(transport.send('query', {- sql: 'SELECT id, name FROM t',- })).resolves.toEqual([{ id: 1, name: 'alice' }]);+ await expect(+ transport.send('query', {+ sql: 'SELECT id, name FROM t',+ }),+ ).resolves.toEqual([{ id: 1, name: 'alice' }]);} finally {await transport.close();}@@ -45,9 +44,9 @@ describe('WorkerThreadTransport', () => {try {const active = transport.send('sleep', { ms: 30 });const queued = transport.send('echoTransfer', { buffer: new ArrayBuffer(4) });- await expect(- transport.send('query', { sql: 'SELECT 1' }),- ).rejects.toThrow(/RPC queue overloaded/);+ await expect(transport.send('query', { sql: 'SELECT 1' })).rejects.toThrow(+ /RPC queue overloaded/,+ );await expect(active).resolves.toEqual({ slept: 30 });await expect(queued).resolves.toEqual({ byteLength: 4 });@@ -122,6 +121,9 @@ describe('WorkerThreadTransport', () => {sdk_session_id TEXT,total_token_usage INTEGER NOT NULL,total_cost_usd REAL NOT NULL,+ total_cost_amount REAL NOT NULL DEFAULT 0,+ total_cost_currency TEXT,+ total_cost_is_approximate INTEGER NOT NULL DEFAULT 0,context_tokens INTEGER NOT NULL,context_window INTEGER NOT NULL,fast_mode INTEGER NOT NULL,@@ -202,10 +204,12 @@ describe('WorkerThreadTransport', () => {},});- await expect(transport.send('queryOne', {- sql: 'SELECT working_dir FROM sessions WHERE id = ?',- params: ['forked'],- })).resolves.toEqual({ working_dir: 'D:/repo/project' });+ await expect(+ transport.send('queryOne', {+ sql: 'SELECT working_dir FROM sessions WHERE id = ?',+ params: ['forked'],+ }),+ ).resolves.toEqual({ working_dir: 'D:/repo/project' });const copiedSwitch = await transport.send<{ content: string }>('queryOne', {sql: 'SELECT content FROM messages WHERE id = ?',params: ['forked-switch'],@@ -240,13 +244,17 @@ describe('WorkerThreadTransport', () => {useInlineWorker: true,});try {- await expect(transport.send('query', {- sql: 'SELECT name FROM sqlite_master WHERE type = ? AND name = ?',- params: ['table', 'worker_smoke'],- })).resolves.toEqual([{ name: 'worker_smoke' }]);- await expect(transport.send('queryOne', {- sql: "SELECT value FROM migration_meta WHERE key='schema_version'",- })).resolves.toEqual({ value: '0' });+ await expect(+ transport.send('query', {+ sql: 'SELECT name FROM sqlite_master WHERE type = ? AND name = ?',+ params: ['table', 'worker_smoke'],+ }),+ ).resolves.toEqual([{ name: 'worker_smoke' }]);+ await expect(+ transport.send('queryOne', {+ sql: "SELECT value FROM migration_meta WHERE key='schema_version'",+ }),+ ).resolves.toEqual({ value: '0' });} finally {await transport.close();fs.rmSync(dir, { recursive: true, force: true });@@ -276,13 +284,17 @@ describe('WorkerThreadTransport', () => {useInlineWorker: true,});try {- await expect(transport.send('query', {- sql: 'SELECT name FROM sqlite_master WHERE type = ? AND name = ?',- params: ['table', 'worker_smoke'],- })).resolves.toEqual([{ name: 'worker_smoke' }]);- await expect(transport.send('queryOne', {- sql: "SELECT value FROM migration_meta WHERE key='schema_version'",- })).resolves.toEqual({ value: '0' });+ await expect(+ transport.send('query', {+ sql: 'SELECT name FROM sqlite_master WHERE type = ? AND name = ?',+ params: ['table', 'worker_smoke'],+ }),+ ).resolves.toEqual([{ name: 'worker_smoke' }]);+ await expect(+ transport.send('queryOne', {+ sql: "SELECT value FROM migration_meta WHERE key='schema_version'",+ }),+ ).resolves.toEqual({ value: '0' });} finally {await transport.close();fs.rmSync(dir, { recursive: true, force: true });@@ -290,14 +302,14 @@ describe('WorkerThreadTransport', () => {});it('fails fast when the real worker script is missing', () => {- const missingWorkerPath = path.join(- os.tmpdir(),- `xdt-missing-db-worker-${Date.now()}.js`,- );+ const missingWorkerPath = path.join(os.tmpdir(), `xdt-missing-db-worker-${Date.now()}.js`);- expect(() => new WorkerThreadTransport({- workerScriptPath: missingWorkerPath,- })).toThrow(/db worker script not found/i);+ expect(+ () =>+ new WorkerThreadTransport({+ workerScriptPath: missingWorkerPath,+ }),+ ).toThrow(/db worker script not found/i);});it('runs queries through a real worker bundle', async () => {@@ -329,18 +341,22 @@ describe('WorkerThreadTransport', () => {});transport.on('log', (event) => logs.push(event));- await expect(transport.send('query', {- sql: 'SELECT name FROM worker_smoke',- })).resolves.toEqual([{ name: 'file-worker' }]);+ await expect(+ transport.send('query', {+ sql: 'SELECT name FROM worker_smoke',+ }),+ ).resolves.toEqual([{ name: 'file-worker' }]);expect(logs.map((event) => event.payload)).toEqual(expect.arrayContaining([expect.objectContaining({ event: 'dbWorker.init.ok', runtimeMode: 'file' }),]),);await expect(transport.send('closeDb')).resolves.toBeUndefined();- await expect(transport.send('query', {- sql: 'SELECT name FROM worker_smoke',- })).rejects.toMatchObject({ code: 'INIT_FAILED' });+ await expect(+ transport.send('query', {+ sql: 'SELECT name FROM worker_smoke',+ }),+ ).rejects.toMatchObject({ code: 'INIT_FAILED' });} finally {if (transport) await transport.close();fs.rmSync(dir, { recursive: true, force: true });@@ -377,9 +393,11 @@ describe('WorkerThreadTransport', () => {});transport.on('log', (event) => logs.push(event));- await expect(transport.send('query', {- sql: 'SELECT name FROM worker_smoke',- })).resolves.toEqual([{ name: 'alice' }]);+ await expect(+ transport.send('query', {+ sql: 'SELECT name FROM worker_smoke',+ }),+ ).resolves.toEqual([{ name: 'alice' }]);expect(logs.map((event) => event.payload)).toEqual(expect.arrayContaining([expect.objectContaining({ event: 'dbWorker.init.ok', runtimeMode: 'file' }),@@ -421,9 +439,11 @@ describe('WorkerThreadTransport', () => {workerScriptPath,});- await expect(transport.send('query', {- sql: 'SELECT name FROM worker_smoke',- })).rejects.toMatchObject({ code: 'MIGRATION_REQUIRED' });+ await expect(+ transport.send('query', {+ sql: 'SELECT name FROM worker_smoke',+ }),+ ).rejects.toMatchObject({ code: 'MIGRATION_REQUIRED' });} finally {if (transport) await transport.close();fs.rmSync(dir, { recursive: true, force: true });@@ -460,9 +480,11 @@ describe('WorkerThreadTransport', () => {});transport.on('vec-status', (event) => vecStatus.push(event));- await expect(transport.send('query', {- sql: 'SELECT name FROM worker_smoke',- })).resolves.toEqual([{ name: 'alice' }]);+ await expect(+ transport.send('query', {+ sql: 'SELECT name FROM worker_smoke',+ }),+ ).resolves.toEqual([{ name: 'alice' }]);expect(vecStatus).toContainEqual({loaded: false,error: 'sqlite-vec binary not found at expected path',@@ -505,9 +527,11 @@ describe('WorkerThreadTransport', () => {});transport.on('vec-status', (event) => vecStatus.push(event));- await expect(transport.send('query', {- sql: 'SELECT name FROM worker_smoke',- })).resolves.toEqual([{ name: 'alice' }]);+ await expect(+ transport.send('query', {+ sql: 'SELECT name FROM worker_smoke',+ }),+ ).resolves.toEqual([{ name: 'alice' }]);expect(vecStatus).toEqual([expect.objectContaining({loaded: false,@@ -550,9 +574,11 @@ describe('WorkerThreadTransport', () => {});transport.on('log', (event) => logs.push(event));- await expect(transport.send('query', {- sql: 'SELECT name FROM worker_smoke',- })).resolves.toEqual([{ name: 'alice' }]);+ await expect(+ transport.send('query', {+ sql: 'SELECT name FROM worker_smoke',+ }),+ ).resolves.toEqual([{ name: 'alice' }]);expect(logs.map((event) => event.payload)).toEqual(expect.arrayContaining([expect.objectContaining({ event: 'dbWorker.schemaDrift.queryFailed' }),diff --git a/apps/desktop/src/main/localDb/client/__tests__/drizzleProxy.test.ts b/apps/desktop/src/main/localDb/client/__tests__/drizzleProxy.test.tsindex 55f6f93797..75067d6eb8 100644--- a/apps/desktop/src/main/localDb/client/__tests__/drizzleProxy.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/drizzleProxy.test.ts@@ -27,6 +27,9 @@ const DRIZZLE_PROXY_SCHEMA = [sdk_session_id TEXT,total_token_usage INTEGER NOT NULL DEFAULT 0,total_cost_usd REAL NOT NULL DEFAULT 0,+ total_cost_amount REAL NOT NULL DEFAULT 0,+ total_cost_currency TEXT,+ total_cost_is_approximate INTEGER NOT NULL DEFAULT 0,context_tokens INTEGER NOT NULL DEFAULT 0,context_window INTEGER NOT NULL DEFAULT 0,fast_mode INTEGER NOT NULL DEFAULT 0,@@ -80,12 +83,14 @@ describe('drizzle proxy', () => {await applyDrizzleProxySchema(client);for (const target of [inProc, client] as const) {if ('prepare' in target) {- target.prepare(- 'INSERT INTO sessions (id, title, created_at, updated_at) VALUES (?, ?, ?, ?)',- ).run('s1', 'Session 1', 1, 2);- target.prepare(- 'INSERT INTO messages (id, client_id, session_id, role, content, created_at) VALUES (?, ?, ?, ?, ?, ?)',- ).run('m1', 'c1', 's1', 'user', '"hello"', 3);+ target+ .prepare('INSERT INTO sessions (id, title, created_at, updated_at) VALUES (?, ?, ?, ?)')+ .run('s1', 'Session 1', 1, 2);+ target+ .prepare(+ 'INSERT INTO messages (id, client_id, session_id, role, content, created_at) VALUES (?, ?, ?, ?, ?, ?)',+ )+ .run('m1', 'c1', 's1', 'user', '"hello"', 3);} else {await target.exec('INSERT INTO sessions (id, title, created_at, updated_at) VALUES (?, ?, ?, ?)',@@ -134,10 +139,7 @@ describe('drizzle proxy', () => {.values({ id: 's2', title: 'b', createdAt: 2, updatedAt: 2 } as never);// UPDATE- await client.drizzle- .update(sessions)- .set({ title: 'updated' })- .where(eq(sessions.id, 's1'));+ await client.drizzle.update(sessions).set({ title: 'updated' }).where(eq(sessions.id, 's1'));// DELETEawait client.drizzle.delete(sessions).where(eq(sessions.id, 's2'));diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.tsindex bec6f012ab..58673d3d33 100644--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts@@ -29,6 +29,9 @@ CREATE TABLE sessions (sdk_session_id TEXT,total_token_usage INTEGER NOT NULL DEFAULT 0,total_cost_usd REAL NOT NULL DEFAULT 0,+ total_cost_amount REAL NOT NULL DEFAULT 0,+ total_cost_currency TEXT,+ total_cost_is_approximate INTEGER NOT NULL DEFAULT 0,context_tokens INTEGER NOT NULL DEFAULT 0,context_window INTEGER NOT NULL DEFAULT 0,fast_mode INTEGER NOT NULL DEFAULT 0,@@ -179,7 +182,11 @@ describe('db worker tx handlers', () => {});expect(result).toEqual({ changed: 1 });- await expect(client.query('SELECT client_id, agent_meta FROM messages WHERE client_id LIKE ?', ['codex-import:%'])).resolves.toEqual([+ await expect(+ client.query('SELECT client_id, agent_meta FROM messages WHERE client_id LIKE ?', [+ 'codex-import:%',+ ]),+ ).resolves.toEqual([{client_id: 'codex-import:2',agent_meta: JSON.stringify({ sdkSessionId: 'thread-1', model: 'gpt-5' }),@@ -202,7 +209,13 @@ describe('db worker tx handlers', () => {sdkSessionId: 'thread-1',model: 'gpt-5',rows: [- { lineNo: 2, role: 'assistant', text: 'secret body', content: 'secret body', createdAt: 2000 },+ {+ lineNo: 2,+ role: 'assistant',+ text: 'secret body',+ content: 'secret body',+ createdAt: 2000,+ },],});@@ -241,7 +254,9 @@ describe('db worker tx handlers', () => {});expect(result).toEqual({ changed: 1 });- await expect(client.queryOne('SELECT id, client_id, tool_use_id, agent_meta FROM messages')).resolves.toEqual({+ await expect(+ client.queryOne('SELECT id, client_id, tool_use_id, agent_meta FROM messages'),+ ).resolves.toEqual({id: 'claude-import-sdk-1-7-0',client_id: 'claude-import:7-0',tool_use_id: 'tool-1',@@ -306,11 +321,18 @@ describe('db worker tx handlers', () => {now: 999,});- await expect(client.query('SELECT id, rewind_at FROM messages ORDER BY id')).resolves.toEqual([- { id: 'm1', rewind_at: null },- { id: 'm2', rewind_at: 999 },- ]);- await expect(client.queryOne('SELECT user_send_at, context_tokens, context_window, sdk_session_id FROM sessions WHERE id = ?', ['s1'])).resolves.toEqual({+ await expect(client.query('SELECT id, rewind_at FROM messages ORDER BY id')).resolves.toEqual(+ [+ { id: 'm1', rewind_at: null },+ { id: 'm2', rewind_at: 999 },+ ],+ );+ await expect(+ client.queryOne(+ 'SELECT user_send_at, context_tokens, context_window, sdk_session_id FROM sessions WHERE id = ?',+ ['s1'],+ ),+ ).resolves.toEqual({user_send_at: 999,context_tokens: 0,context_window: 0,@@ -355,11 +377,13 @@ describe('db worker tx handlers', () => {now: 999,});- await expect(client.query('SELECT id, rewind_at FROM messages ORDER BY id')).resolves.toEqual([- { id: 'aaa-before-target', rewind_at: null },- { id: 'target', rewind_at: 999 },- { id: 'zzz-after-target', rewind_at: 999 },- ]);+ await expect(client.query('SELECT id, rewind_at FROM messages ORDER BY id')).resolves.toEqual(+ [+ { id: 'aaa-before-target', rewind_at: null },+ { id: 'target', rewind_at: 999 },+ { id: 'zzz-after-target', rewind_at: 999 },+ ],+ );});});@@ -391,7 +415,9 @@ describe('db worker tx handlers', () => {updatedAt: expect.stringMatching(/^20\d{2}-\d{2}-\d{2}T/),},]);- await expect(client.queryOne('SELECT title FROM sessions WHERE id = ?', ['s1'])).resolves.toEqual({+ await expect(+ client.queryOne('SELECT title FROM sessions WHERE id = ?', ['s1']),+ ).resolves.toEqual({title: 'New title',});@@ -406,7 +432,9 @@ describe('db worker tx handlers', () => {],}),).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });- await expect(client.queryOne('SELECT title FROM sessions WHERE id = ?', ['s1'])).resolves.toEqual({+ await expect(+ client.queryOne('SELECT title FROM sessions WHERE id = ?', ['s1']),+ ).resolves.toEqual({title: 'New title',});});@@ -459,12 +487,14 @@ describe('db worker tx handlers', () => {now: 999,});- await expect(client.query('SELECT id, rewind_at FROM messages ORDER BY id')).resolves.toEqual([- { id: 'child', rewind_at: 999 },- { id: 'prior', rewind_at: null },- { id: 'target', rewind_at: 999 },- { id: 'unrelated', rewind_at: null },- ]);+ await expect(client.query('SELECT id, rewind_at FROM messages ORDER BY id')).resolves.toEqual(+ [+ { id: 'child', rewind_at: 999 },+ { id: 'prior', rewind_at: null },+ { id: 'target', rewind_at: 999 },+ { id: 'unrelated', rewind_at: null },+ ],+ );});});@@ -507,11 +537,13 @@ describe('db worker tx handlers', () => {now: 999,});- await expect(client.query('SELECT id, rewind_at FROM messages ORDER BY id')).resolves.toEqual([- { id: 'child', rewind_at: 999 },- { id: 'prior', rewind_at: null },- { id: 'target', rewind_at: 999 },- ]);+ await expect(client.query('SELECT id, rewind_at FROM messages ORDER BY id')).resolves.toEqual(+ [+ { id: 'child', rewind_at: 999 },+ { id: 'prior', rewind_at: null },+ { id: 'target', rewind_at: 999 },+ ],+ );});});@@ -550,21 +582,34 @@ describe('db worker tx handlers', () => {forkedAtMessageId: 'c2',providerId: 'xd',}),- uuidMap: [['old', 'new'], ['parent', 'new-parent-tool'], ['old-parent', 'new-parent']],+ uuidMap: [+ ['old', 'new'],+ ['parent', 'new-parent-tool'],+ ['old-parent', 'new-parent'],+ ],newMessageIds: [{ id: 'copy-id-1', clientId: 'copy-client-1' }],});expect(result).toEqual({ messageCount: 1 });- await expect(client.queryOne('SELECT working_dir, parent_session_id, forked_at_message_id, provider_id FROM sessions WHERE id = ?', ['forked'])).resolves.toEqual({+ await expect(+ client.queryOne(+ 'SELECT working_dir, parent_session_id, forked_at_message_id, provider_id FROM sessions WHERE id = ?',+ ['forked'],+ ),+ ).resolves.toEqual({working_dir: 'D:/repo/project',parent_session_id: 'src',forked_at_message_id: 'c2',provider_id: 'xd',});- const copied = await client.queryOne<{ id: string; client_id: string; agent_meta: string; agent_kind: string }>(- 'SELECT id, client_id, agent_meta, agent_kind FROM messages WHERE session_id = ?',- ['forked'],- );+ const copied = await client.queryOne<{+ id: string;+ client_id: string;+ agent_meta: string;+ agent_kind: string;+ }>('SELECT id, client_id, agent_meta, agent_kind FROM messages WHERE session_id = ?', [+ 'forked',+ ]);expect(copied?.id).toBe('copy-id-1');expect(copied?.client_id).toBe('copy-client-1');expect(copied?.agent_kind).toBe('cc');@@ -593,11 +638,36 @@ describe('db worker tx handlers', () => {VALUES (?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?),(?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?)`,[- 'pre-clear', 'pre-clear-client', 'src', 'user', 'old', 50,- 'switch', 'switch-client', 'src', 'agent_switch', switchContent, 100,- 'same-before', 'same-before-client', 'src', 'assistant', 'keep', 200,- 'target', 'target-client', 'src', 'user', 'exclude target', 200,- 'same-after', 'same-after-client', 'src', 'assistant', 'exclude tail', 200,+ 'pre-clear',+ 'pre-clear-client',+ 'src',+ 'user',+ 'old',+ 50,+ 'switch',+ 'switch-client',+ 'src',+ 'agent_switch',+ switchContent,+ 100,+ 'same-before',+ 'same-before-client',+ 'src',+ 'assistant',+ 'keep',+ 200,+ 'target',+ 'target-client',+ 'src',+ 'user',+ 'exclude target',+ 200,+ 'same-after',+ 'same-after-client',+ 'src',+ 'assistant',+ 'exclude tail',+ 200,],);const target = await client.queryOne<{ rowid: number }>(@@ -625,10 +695,9 @@ describe('db worker tx handlers', () => {id: string;role: string;content: string;- }>(- 'SELECT id, role, content FROM messages WHERE session_id = ? ORDER BY created_at, rowid',- ['forked'],- );+ }>('SELECT id, role, content FROM messages WHERE session_id = ? ORDER BY created_at, rowid', [+ 'forked',+ ]);expect(copied.map((row) => row.id)).toEqual(['copy-switch', 'copy-same-before']);expect(JSON.parse(copied[0].content)).toMatchObject({fromSdkSessionId: null,@@ -659,7 +728,10 @@ describe('db worker tx handlers', () => {sourceSessionId: 'src',targetCreatedAt: 200,newSession: sessionRow('forked', { parentSessionId: 'src' }),- uuidMap: [['legacy-asst', 'new-asst'], ['legacy-user', 'new-user']],+ uuidMap: [+ ['legacy-asst', 'new-asst'],+ ['legacy-user', 'new-user'],+ ],legacyTranscriptParentUuids: ['legacy-asst'],newMessageIds: [{ id: 'copy-id', clientId: 'copy-client' }],});@@ -720,13 +792,15 @@ describe('db worker tx handlers', () => {['m1', 'c1', 'src', 'assistant', 'copy', 100],);- await expect(client.tx('fork.session', {- sourceSessionId: 'src',- targetCreatedAt: 200,- newSession: sessionRow('forked', { parentSessionId: 'src', forkedAtMessageId: 'c1' }),- uuidMap: [],- newMessageIds: [],- })).rejects.toMatchObject({ code: 'INVALID_ARGS' });+ await expect(+ client.tx('fork.session', {+ sourceSessionId: 'src',+ targetCreatedAt: 200,+ newSession: sessionRow('forked', { parentSessionId: 'src', forkedAtMessageId: 'c1' }),+ uuidMap: [],+ newMessageIds: [],+ }),+ ).rejects.toMatchObject({ code: 'INVALID_ARGS' });});});@@ -744,14 +818,15 @@ describe('db worker tx handlers', () => {boundaryContent: '{"handoff":"full","resumed":false}',updatedAt: 500,});- await expect(client.queryOne(- 'SELECT sdk_session_id, updated_at FROM sessions WHERE id = ?',- ['s1'],- )).resolves.toEqual({ sdk_session_id: null, updated_at: 500 });- await expect(client.queryOne(- 'SELECT content FROM messages WHERE session_id = ? AND client_id = ?',- ['s1', 'sw-client'],- )).resolves.toEqual({ content: '{"handoff":"full","resumed":false}' });+ await expect(+ client.queryOne('SELECT sdk_session_id, updated_at FROM sessions WHERE id = ?', ['s1']),+ ).resolves.toEqual({ sdk_session_id: null, updated_at: 500 });+ await expect(+ client.queryOne('SELECT content FROM messages WHERE session_id = ? AND client_id = ?', [+ 's1',+ 'sw-client',+ ]),+ ).resolves.toEqual({ content: '{"handoff":"full","resumed":false}' });});});@@ -759,23 +834,27 @@ describe('db worker tx handlers', () => {await withClient(async (client) => {await seedSession(client, 's1');await client.exec('UPDATE sessions SET sdk_session_id = ? WHERE id = ?', ['stale-sdk', 's1']);- await expect(client.tx('session.agentSwitchFallback', {- sessionId: 's1',- boundaryClientId: 'missing',- boundaryContent: '{}',- updatedAt: 500,- })).rejects.toMatchObject({ code: 'NOT_FOUND' });- await expect(client.queryOne(- 'SELECT sdk_session_id FROM sessions WHERE id = ?',- ['s1'],- )).resolves.toEqual({ sdk_session_id: 'stale-sdk' });+ await expect(+ client.tx('session.agentSwitchFallback', {+ sessionId: 's1',+ boundaryClientId: 'missing',+ boundaryContent: '{}',+ updatedAt: 500,+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ await expect(+ client.queryOne('SELECT sdk_session_id FROM sessions WHERE id = ?', ['s1']),+ ).resolves.toEqual({ sdk_session_id: 'stale-sdk' });});});it('message.delete scrubs the selected AI round and invalidates native context atomically', async () => {await withClient(async (client) => {await seedSession(client, 's1');- await client.exec('UPDATE sessions SET sdk_session_id = ? WHERE id = ?', ['old-native', 's1']);+ await client.exec('UPDATE sessions SET sdk_session_id = ? WHERE id = ?', [+ 'old-native',+ 's1',+ ]);for (const [id, role, createdAt] of [['before', 'user', 100],['target', 'assistant', 200],@@ -793,19 +872,24 @@ describe('db worker tx handlers', () => {"INSERT INTO embedding_jobs (source, source_id, model_id, vec_table, scheduled_at) VALUES ('chat', ?, 'test', 'chat_vec', 0)",['target'],);- await client.exec('INSERT INTO chat_vec (rowid, embedding) VALUES (?, ?)', [job.lastInsertRowid, Buffer.from([1, 2, 3])]);+ await client.exec('INSERT INTO chat_vec (rowid, embedding) VALUES (?, ?)', [+ job.lastInsertRowid,+ Buffer.from([1, 2, 3]),+ ]);- await expect(client.tx('message.delete', {- sessionId: 's1',- clientIds: ['target', 'thinking', 'auto-resume', 'tool'],- contextMarker: {- id: 'ctx-id',- clientId: 'ctx-client',- content: '{"handoff":"before + after","consumed":false}',- createdAt: 400,- },- updatedAt: 500,- })).resolves.toEqual({+ await expect(+ client.tx('message.delete', {+ sessionId: 's1',+ clientIds: ['target', 'thinking', 'auto-resume', 'tool'],+ contextMarker: {+ id: 'ctx-id',+ clientId: 'ctx-client',+ content: '{"handoff":"before + after","consumed":false}',+ createdAt: 400,+ },+ updatedAt: 500,+ }),+ ).resolves.toEqual({messages: [{ messageId: 'target', clientId: 'target' },{ messageId: 'thinking', clientId: 'thinking' },@@ -814,21 +898,47 @@ describe('db worker tx handlers', () => {],});- await expect(client.query<{- id: string;- role: string;- content: string;- agent_meta: string | null;- rewind_at: number | null;- }>(- 'SELECT id, role, content, agent_meta, rewind_at FROM messages WHERE session_id = ? ORDER BY created_at',- ['s1'],- )).resolves.toEqual([+ await expect(+ client.query<{+ id: string;+ role: string;+ content: string;+ agent_meta: string | null;+ rewind_at: number | null;+ }>(+ 'SELECT id, role, content, agent_meta, rewind_at FROM messages WHERE session_id = ? ORDER BY created_at',+ ['s1'],+ ),+ ).resolves.toEqual([{ id: 'before', role: 'user', content: '"before"', agent_meta: null, rewind_at: null },- { id: 'target', role: 'message_tombstone', content: 'null', agent_meta: null, rewind_at: 500 },- { id: 'thinking', role: 'message_tombstone', content: 'null', agent_meta: null, rewind_at: 500 },- { id: 'auto-resume', role: 'message_tombstone', content: 'null', agent_meta: null, rewind_at: 500 },- { id: 'tool', role: 'message_tombstone', content: 'null', agent_meta: null, rewind_at: 500 },+ {+ id: 'target',+ role: 'message_tombstone',+ content: 'null',+ agent_meta: null,+ rewind_at: 500,+ },+ {+ id: 'thinking',+ role: 'message_tombstone',+ content: 'null',+ agent_meta: null,+ rewind_at: 500,+ },+ {+ id: 'auto-resume',+ role: 'message_tombstone',+ content: 'null',+ agent_meta: null,+ rewind_at: 500,+ },+ {+ id: 'tool',+ role: 'message_tombstone',+ content: 'null',+ agent_meta: null,+ rewind_at: 500,+ },{ id: 'after', role: 'user', content: '"after"', agent_meta: null, rewind_at: null },{id: 'ctx-id',@@ -838,11 +948,12 @@ describe('db worker tx handlers', () => {rewind_at: 400,},]);- await expect(client.queryOne(- 'SELECT sdk_session_id, updated_at FROM sessions WHERE id = ?',- ['s1'],- )).resolves.toEqual({ sdk_session_id: null, updated_at: 500 });- await expect(client.query('SELECT rowid FROM embedding_jobs WHERE source_id = ?', ['target'])).resolves.toEqual([]);+ await expect(+ client.queryOne('SELECT sdk_session_id, updated_at FROM sessions WHERE id = ?', ['s1']),+ ).resolves.toEqual({ sdk_session_id: null, updated_at: 500 });+ await expect(+ client.query('SELECT rowid FROM embedding_jobs WHERE source_id = ?', ['target']),+ ).resolves.toEqual([]);await expect(client.query('SELECT rowid FROM chat_vec')).resolves.toEqual([]);});});@@ -850,24 +961,30 @@ describe('db worker tx handlers', () => {it('message.delete rejects non-deletable rows without clearing the sdk binding', async () => {await withClient(async (client) => {await seedSession(client, 's1');- await client.exec('UPDATE sessions SET sdk_session_id = ? WHERE id = ?', ['old-native', 's1']);+ await client.exec('UPDATE sessions SET sdk_session_id = ? WHERE id = ?', [+ 'old-native',+ 's1',+ ]);await client.exec('INSERT INTO messages (id, client_id, session_id, role, content, created_at) VALUES (?, ?, ?, ?, ?, ?)',['switch', 'switch', 's1', 'agent_switch', '{}', 100],);- await expect(client.tx('message.delete', {- sessionId: 's1',- clientIds: ['switch'],- contextMarker: {- id: 'ctx-id',- clientId: 'ctx-client',- content: '{"handoff":"empty","consumed":false}',- createdAt: 400,- },- updatedAt: 500,- })).rejects.toMatchObject({ code: 'NOT_FOUND' });- await expect(client.queryOne('SELECT sdk_session_id FROM sessions WHERE id = ?', ['s1']))- .resolves.toEqual({ sdk_session_id: 'old-native' });+ await expect(+ client.tx('message.delete', {+ sessionId: 's1',+ clientIds: ['switch'],+ contextMarker: {+ id: 'ctx-id',+ clientId: 'ctx-client',+ content: '{"handoff":"empty","consumed":false}',+ createdAt: 400,+ },+ updatedAt: 500,+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ await expect(+ client.queryOne('SELECT sdk_session_id FROM sessions WHERE id = ?', ['s1']),+ ).resolves.toEqual({ sdk_session_id: 'old-native' });});});@@ -1066,7 +1183,9 @@ describe('db worker tx handlers', () => {await withClient(async (client) => {const rowid = await insertJob(client, { sourceId: 'm1' });await client.tx('embedding.markDone', { rowids: [rowid] });- await expect(client.queryOne('SELECT status, last_error FROM embedding_jobs WHERE rowid = ?', [rowid])).resolves.toEqual({+ await expect(+ client.queryOne('SELECT status, last_error FROM embedding_jobs WHERE rowid = ?', [rowid]),+ ).resolves.toEqual({status: 'done',last_error: null,});@@ -1077,16 +1196,18 @@ describe('db worker tx handlers', () => {await withClient(async (client) => {const rowid = await insertJob(client, { sourceId: 'm1' });const embedding = new Float32Array([1, 2, 3, 4]);- await client.tx(- 'embedding.commit',- { items: [{ rowid, vecTable: 'chat_vec', embedding }] },- [embedding.buffer],- );+ await client.tx('embedding.commit', { items: [{ rowid, vecTable: 'chat_vec', embedding }] }, [+ embedding.buffer,+ ]);- await expect(client.queryOne('SELECT status FROM embedding_jobs WHERE rowid = ?', [rowid])).resolves.toEqual({+ await expect(+ client.queryOne('SELECT status FROM embedding_jobs WHERE rowid = ?', [rowid]),+ ).resolves.toEqual({status: 'done',});- await expect(client.queryOne('SELECT rowid, length(embedding) AS len FROM chat_vec')).resolves.toEqual({+ await expect(+ client.queryOne('SELECT rowid, length(embedding) AS len FROM chat_vec'),+ ).resolves.toEqual({rowid,len: 16,});@@ -1136,13 +1257,19 @@ describe('db worker tx handlers', () => {[second.buffer],);- await expect(client.queryOne('SELECT status FROM embedding_jobs WHERE rowid = ?', [rowid])).resolves.toEqual({+ await expect(+ client.queryOne('SELECT status FROM embedding_jobs WHERE rowid = ?', [rowid]),+ ).resolves.toEqual({status: 'done',});- await expect(client.queryOne('SELECT COUNT(*) AS n FROM chat_vec WHERE rowid = ?', [rowid])).resolves.toEqual({+ await expect(+ client.queryOne('SELECT COUNT(*) AS n FROM chat_vec WHERE rowid = ?', [rowid]),+ ).resolves.toEqual({n: 1,});- await expect(client.queryOne('SELECT rowid, length(embedding) AS len FROM chat_vec')).resolves.toEqual({+ await expect(+ client.queryOne('SELECT rowid, length(embedding) AS len FROM chat_vec'),+ ).resolves.toEqual({rowid,len: 32,});@@ -1163,7 +1290,11 @@ describe('db worker tx handlers', () => {});expect(result).toEqual({ failCount: 1 });- await expect(client.query('SELECT rowid, status, attempts, scheduled_at FROM embedding_jobs ORDER BY rowid')).resolves.toEqual([+ await expect(+ client.query(+ 'SELECT rowid, status, attempts, scheduled_at FROM embedding_jobs ORDER BY rowid',+ ),+ ).resolves.toEqual([{ rowid: retryRowid, status: 'pending', attempts: 1, scheduled_at: 11_000 },{ rowid: failRowid, status: 'failed', attempts: 5, scheduled_at: 0 },]);@@ -1183,7 +1314,11 @@ describe('db worker tx handlers', () => {});expect(result).toEqual({ inserted: 2, skipped: 1 });- await expect(client.query('SELECT source_id, chunk_index, scheduled_at FROM embedding_jobs ORDER BY rowid')).resolves.toEqual([+ await expect(+ client.query(+ 'SELECT source_id, chunk_index, scheduled_at FROM embedding_jobs ORDER BY rowid',+ ),+ ).resolves.toEqual([{ source_id: 'm1', chunk_index: 0, scheduled_at: 123 },{ source_id: 'm2', chunk_index: 1, scheduled_at: 123 },]);@@ -1214,8 +1349,14 @@ describe('db worker tx handlers', () => {expect(archivedSessionId).toBe('worker');expect(missingSessionId).toBeNull();- await expect(client.queryOne('SELECT id FROM orca_workers WHERE id = ?', ['worker-1'])).resolves.toBeUndefined();- await expect(client.queryOne('SELECT status, orca_role, updated_at FROM sessions WHERE id = ?', ['worker'])).resolves.toEqual({+ await expect(+ client.queryOne('SELECT id FROM orca_workers WHERE id = ?', ['worker-1']),+ ).resolves.toBeUndefined();+ await expect(+ client.queryOne('SELECT status, orca_role, updated_at FROM sessions WHERE id = ?', [+ 'worker',+ ]),+ ).resolves.toEqual({status: 'archived',orca_role: null,updated_at: 999,@@ -1232,10 +1373,20 @@ describe('db worker tx handlers', () => {);const results = await Promise.all([first.tx('orca.reserveWorkerCreation', {- reservationId: 'first', teamId: 'team-1', label: 'tester', hardLimit: 5, now: 100, expiresAt: 200,+ reservationId: 'first',+ teamId: 'team-1',+ label: 'tester',+ hardLimit: 5,+ now: 100,+ expiresAt: 200,}),second.tx('orca.reserveWorkerCreation', {- reservationId: 'second', teamId: 'team-1', label: 'TESTER', hardLimit: 5, now: 100, expiresAt: 200,+ reservationId: 'second',+ teamId: 'team-1',+ label: 'TESTER',+ hardLimit: 5,+ now: 100,+ expiresAt: 200,}),]);expect(results).toContainEqual({ ok: true, occupiedSlotsBefore: 0 });@@ -1265,15 +1416,29 @@ describe('db worker tx handlers', () => {['worker-2', 'team-1', 'errored-worker', 'error', 'errored', 'reviewer', 1, 1],);- await expect(client.tx('orca.reserveWorkerCreation', {- reservationId: 'blocked', teamId: 'team-1', label: 'blocked', hardLimit: 2, now: 100, expiresAt: 200,- })).resolves.toEqual({ ok: false, errorCode: 'WORKER_LIMIT_HARD_EXCEEDED' });+ await expect(+ client.tx('orca.reserveWorkerCreation', {+ reservationId: 'blocked',+ teamId: 'team-1',+ label: 'blocked',+ hardLimit: 2,+ now: 100,+ expiresAt: 200,+ }),+ ).resolves.toEqual({ ok: false, errorCode: 'WORKER_LIMIT_HARD_EXCEEDED' });await client.exec("UPDATE sessions SET status = 'archived' WHERE id = ?", ['done-worker']);- await expect(client.tx('orca.reserveWorkerCreation', {- reservationId: 'replacement', teamId: 'team-1', label: 'replacement', hardLimit: 2, now: 100, expiresAt: 200,- })).resolves.toEqual({ ok: true, occupiedSlotsBefore: 1 });+ await expect(+ client.tx('orca.reserveWorkerCreation', {+ reservationId: 'replacement',+ teamId: 'team-1',+ label: 'replacement',+ hardLimit: 2,+ now: 100,+ expiresAt: 200,+ }),+ ).resolves.toEqual({ ok: true, occupiedSlotsBefore: 1 });});});});@@ -1313,13 +1478,15 @@ async function withTwoClients(fn: (clients: [DbClient, DbClient]) => Promise<voiconst clients: DbClient[] = [];try {for (let index = 0; index < 2; index += 1) {- clients.push(await createDbClient({- userId: `test-user-${index}`,- dbPath,- drizzleDir,- betterSqliteModulePath: require.resolve('better-sqlite3'),- workerScriptPath,- }));+ clients.push(+ await createDbClient({+ userId: `test-user-${index}`,+ dbPath,+ drizzleDir,+ betterSqliteModulePath: require.resolve('better-sqlite3'),+ workerScriptPath,+ }),+ );}await fn(clients as [DbClient, DbClient]);} finally {@@ -1380,10 +1547,7 @@ async function seedSession();}-function sessionRow(- id: string,- overrides: Partial<TestSessionRow> = {},-): TestSessionRow {+function sessionRow(id: string, overrides: Partial<TestSessionRow> = {}): TestSessionRow {return {id,title: `Session ${id}`,diff --git a/apps/desktop/src/main/localDb/dailyModelUsage.ts b/apps/desktop/src/main/localDb/dailyModelUsage.tsindex fedddbf329..4600245ba1 100644--- a/apps/desktop/src/main/localDb/dailyModelUsage.ts+++ b/apps/desktop/src/main/localDb/dailyModelUsage.ts@@ -1,81 +1,92 @@-/**- * dailyModelUsage — 每日按模型用量聚合 CRUD。- *- * 数据流:- * - register.ts 在每个 turn done 后调用 incrementDailyModelUsage(deltas, ts)- * - claude-code: SDK modelUsage 累计值经 modelUsageDelta.ts delta 化后的 per-turn 增量- * - codex: done.data.usage 的 per-turn token 数 (costUsdDelta 恒 0, 美元读取时估算)- *- * 与 dailySpend 的关系: daily_spend 仍是日总额 canonical 来源;- * 本表只做按模型拆分展示, 两边求和因舍入可能有微小差异 — 设计取舍。- *- * 时区: day key 与 dailySpend 同口径, 用 localDayKey (本地时区 YYYY-MM-DD)。- */-import { sql } from 'drizzle-orm';-import { dailyModelUsage } from './schema';-import { localDayKey } from './dailySpend';-import { getDbClient } from './client/current';+import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';+import {+ addRegionalMoney,+ 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';-/** 一笔 per-turn 增量 (全部字段为本 turn 的 delta, 不是累计)。 */export interface DailyModelUsageDelta {agentKind: 'claude-code' | 'codex';model: string;- costUsdDelta: number;+ money?: RegionalMoney | null;inputTokensDelta: number;outputTokensDelta: number;cacheReadTokensDelta: number;cacheCreateTokensDelta: number;}-/** 近 N 天按模型聚合读出的原始行。 */export interface DailyModelUsageRow {day: string;agentKind: string;model: string;- costUsd: number;+ money: RegionalMoney;inputTokens: number;outputTokens: number;cacheReadTokens: number;cacheCreateTokens: number;}-/** 非有限值 / 负数一律归 0; cost 沿用 dailySpend 的 1e-10 浮点噪声守卫。 */-function sanitizeCost(v: number): number {- return Number.isFinite(v) && v >= 1e-10 ? v : 0;-}--function sanitizeTokens(v: number): number {- return Number.isFinite(v) && v > 0 ? Math.round(v) : 0;+function sanitizeTokens(value: number): number {+ return Number.isFinite(value) && value > 0 ? Math.round(value) : 0;}-/**- * 累加一笔 per-turn 用量到 (day, agentKind, model) 聚合行 (upsert)。- * 全部 delta 清洗后均为 0 时跳过写库 (防止空 turn 刷 updatedAt)。- */export async function incrementDailyModelUsage(delta: DailyModelUsageDelta,ts: number = Date.now(),): Promise<void> {- const costUsd = sanitizeCost(delta.costUsdDelta);+ 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);const cacheCreateTokens = sanitizeTokens(delta.cacheCreateTokensDelta);- if (costUsd === 0 && inputTokens === 0 && outputTokens === 0 && cacheReadTokens === 0 && cacheCreateTokens === 0) {+ if (+ !money?.amount &&+ inputTokens === 0 &&+ outputTokens === 0 &&+ cacheReadTokens === 0 &&+ cacheCreateTokens === 0+ ) {return;}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');+ }await db.insert(dailyModelUsage).values({day,agentKind: delta.agentKind,- model: delta.model || 'unknown',- costUsd,+ model,+ costAmount: money?.amount ?? 0,+ costCurrency: money?.currency ?? null,+ costIsApproximate: money?.approximate ?? false,inputTokens,outputTokens,cacheReadTokens,@@ -83,9 +94,15 @@ export async function incrementDailyModelUsage(updatedAt: ts,}).onConflictDoUpdate({- target: [dailyModelUsage.day, dailyModelUsage.agentKind, dailyModelUsage.model],+ target: [+ dailyModelUsage.day,+ dailyModelUsage.agentKind,+ dailyModelUsage.model,+ ],set: {- costUsd: sql`${dailyModelUsage.costUsd} + ${costUsd}`,+ costAmount: sql`${dailyModelUsage.costAmount} + ${money?.amount ?? 0}`,+ ...(money ? { costCurrency: money.currency } : {}),+ costIsApproximate: sql`${dailyModelUsage.costIsApproximate} OR ${money?.approximate ? 1 : 0}`,inputTokens: sql`${dailyModelUsage.inputTokens} + ${inputTokens}`,outputTokens: sql`${dailyModelUsage.outputTokens} + ${outputTokens}`,cacheReadTokens: sql`${dailyModelUsage.cacheReadTokens} + ${cacheReadTokens}`,@@ -96,15 +113,18 @@ export async function incrementDailyModelUsage(.run();}-/** 读出 day >= sinceDayKey 的全部原始行 (按模型聚合在 usageHistory.ts 做)。 */-export async function getModelUsageSince(sinceDayKey: string): Promise<DailyModelUsageRow[]> {- const db = getDbClient().drizzle;- return db+export async function getModelUsageSince(+ sinceDayKey: string,+): Promise<DailyModelUsageRow[]> {+ const rows = await getDbClient().drizzle.select({day: dailyModelUsage.day,agentKind: dailyModelUsage.agentKind,model: dailyModelUsage.model,costUsd: dailyModelUsage.costUsd,+ costAmount: dailyModelUsage.costAmount,+ costCurrency: dailyModelUsage.costCurrency,+ costIsApproximate: dailyModelUsage.costIsApproximate,inputTokens: dailyModelUsage.inputTokens,outputTokens: dailyModelUsage.outputTokens,cacheReadTokens: dailyModelUsage.cacheReadTokens,@@ -113,4 +133,31 @@ export async function getModelUsageSince(sinceDayKey: string): Promise<DailyMode.from(dailyModelUsage).where(sql`${dailyModelUsage.day} >= ${sinceDayKey}`).all();+ return rows.map((row) => {+ const legacy = regionalizeLegacyUsd(row.costUsd, CURRENT_CINDY_REGION);+ const current =+ row.costCurrency && row.costAmount > 0+ ? normalizeRegionalMoney({+ amount: row.costAmount,+ currency: row.costCurrency,+ approximate: row.costIsApproximate,+ kind: 'actual-cost',+ })+ : undefined;+ return {+ day: row.day,+ agentKind: row.agentKind,+ model: row.model,+ money:+ legacy.amount > 0 && current+ ? legacy.currency === current.currency+ ? addRegionalMoney([legacy, current])+ : current+ : current ?? legacy,+ inputTokens: row.inputTokens,+ outputTokens: row.outputTokens,+ cacheReadTokens: row.cacheReadTokens,+ cacheCreateTokens: row.cacheCreateTokens,+ };+ });}diff --git a/apps/desktop/src/main/localDb/dailySpend.ts b/apps/desktop/src/main/localDb/dailySpend.tsindex 3dc113154c..c7c9e35334 100644--- a/apps/desktop/src/main/localDb/dailySpend.ts+++ b/apps/desktop/src/main/localDb/dailySpend.ts@@ -1,100 +1,126 @@-/**- * dailySpend — 每日花费聚合 CRUD。- *- * 数据流:- * - agentManager.ts 在每个 turn 的 `result` 事件后调用 incrementDailySpend(costUsd, ts)- * - costUsd 是 SDK 给的 total_cost_usd (per-turn delta, 不是累计)- * - 用户右下角 chip 通过 IPC `usage:get-today-spend` 拉当日值- *- * 时区处理:- * - day key 用**用户本地时区** YYYY-MM-DD (避免 UTC 跨日错配)- * - localDayKey(ts) 把 unix ms 转成本地日期串- */-import { sql } from 'drizzle-orm';-import { dailySpend } from './schema';-import { getDbClient } from './client/current';+import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';+import {+ addRegionalMoney,+ normalizeRegionalMoney,+ regionalCurrencyForRegion,+ regionalizeLegacyUsd,+ type RegionalMoney,+} from '../../shared/regionalMoney.js';+import { dailySpend } from './schema.js';+import { getDbClient } from './client/current.js';-/**- * 把 unix ms 时间戳转成**本地时区**的 YYYY-MM-DD 字符串。- * 避开 ISO 字符串的 UTC 偏移问题(toISOString 会返回 UTC 日期,跨午夜会错)。- */export function localDayKey(ts: number = Date.now()): string {- const d = new Date(ts);- const y = d.getFullYear();- const m = String(d.getMonth() + 1).padStart(2, '0');- const day = String(d.getDate()).padStart(2, '0');- return `${y}-${m}-${day}`;+ const date = new Date(ts);+ const year = date.getFullYear();+ const month = String(date.getMonth() + 1).padStart(2, '0');+ const day = String(date.getDate()).padStart(2, '0');+ return `${year}-${month}-${day}`;+}++function rowMoney(row: {+ costUsd: number;+ costAmount: number;+ costCurrency: 'CNY' | 'USD' | null;+ costIsApproximate: boolean;+} | undefined): RegionalMoney {+ const legacy = regionalizeLegacyUsd(row?.costUsd ?? 0, CURRENT_CINDY_REGION);+ const current =+ row?.costCurrency && row.costAmount > 0+ ? normalizeRegionalMoney({+ amount: row.costAmount,+ currency: row.costCurrency,+ approximate: row.costIsApproximate,+ kind: 'actual-cost',+ })+ : undefined;+ if (legacy.amount > 0 && current) {+ return legacy.currency === current.currency+ ? addRegionalMoney([legacy, current])+ : current;+ }+ return current ?? legacy;+}++async function getSpendForDay(day: string): Promise<RegionalMoney> {+ const row = await getDbClient().drizzle+ .select({+ costUsd: dailySpend.costUsd,+ costAmount: dailySpend.costAmount,+ costCurrency: dailySpend.costCurrency,+ costIsApproximate: dailySpend.costIsApproximate,+ })+ .from(dailySpend)+ .where(sql`${dailySpend.day} = ${day}`)+ .get();+ return rowMoney(row);}-/**- * 累加一笔花费到对应日期的聚合行(upsert)。- * 不存在 → INSERT;存在 → UPDATE cost_usd += delta + 刷 updated_at。- *- * 返回累加后该日期的最新累计值(供 main 直接广播给 renderer)。- *- * 注意:极小金额(< 1e-10)跳过 — 防止脏数据 / 浮点噪声写库。- */export async function incrementDailySpend(- costUsdDelta: number,+ money: RegionalMoney,ts: number = Date.now(),-): Promise<{ day: string; costUsd: number }> {+): Promise<{ day: string; money: RegionalMoney }> {const day = localDayKey(ts);- if (!Number.isFinite(costUsdDelta) || costUsdDelta < 1e-10) {- // 0 或负数或 NaN/Infinity — 不写,但仍返回当前值供调用方用- return { day, costUsd: await getSpendForDay(day) };+ const normalized = normalizeRegionalMoney(money);+ 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;-- // SQLite UPSERT:INSERT ... ON CONFLICT(day) DO UPDATE SET cost_usd = cost_usd + excluded.cost_usd- await db.insert(dailySpend)+ 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');+ }+ await db+ .insert(dailySpend).values({day,- costUsd: costUsdDelta,+ costAmount: normalized.amount,+ costCurrency: normalized.currency,+ costIsApproximate: normalized.approximate,updatedAt: ts,}).onConflictDoUpdate({target: dailySpend.day,set: {- costUsd: sql`${dailySpend.costUsd} + ${costUsdDelta}`,+ costAmount: sql`${dailySpend.costAmount} + ${normalized.amount}`,+ costCurrency: normalized.currency,+ costIsApproximate: sql`${dailySpend.costIsApproximate} OR ${normalized.approximate ? 1 : 0}`,updatedAt: ts,},}).run();-- return { day, costUsd: await getSpendForDay(day) };+ return { day, money: await getSpendForDay(day) };}-/**- * 拿"今天"的累计花费(USD)。- * 没记录 → 返回 0(不是 null —— 调用方判 0 vs > 0 来决定 UI 显示)。- */-export function getTodaySpend(): Promise<number> {+export function getTodaySpend(): Promise<RegionalMoney> {return getSpendForDay(localDayKey());}-/**- * 读出全部日花费行 (day 升序)。- * 表每天最多 1 行, 体量极小 — 首页仪表盘的 streak / 热力图直接全量读。- */-export async function getAllSpendDays(): Promise<Array<{ day: string; costUsd: number }>> {- const db = getDbClient().drizzle;- return db- .select({ day: dailySpend.day, costUsd: dailySpend.costUsd })+export async function getAllSpendDays(): Promise<+ Array<{ day: string; money: RegionalMoney }>+> {+ const rows = await getDbClient().drizzle+ .select({+ day: dailySpend.day,+ costUsd: dailySpend.costUsd,+ costAmount: dailySpend.costAmount,+ costCurrency: dailySpend.costCurrency,+ costIsApproximate: dailySpend.costIsApproximate,+ }).from(dailySpend).orderBy(dailySpend.day).all();-}--/** 内部:按指定 day key 查累计值。 */-async function getSpendForDay(day: string): Promise<number> {- const db = getDbClient().drizzle;- const row = await db- .select({ costUsd: dailySpend.costUsd })- .from(dailySpend)- .where(sql`${dailySpend.day} = ${day}`)- .get();- return row?.costUsd ?? 0;+ return rows.map((row) => ({ day: row.day, money: rowMoney(row) }));}diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.tsindex ee5f96c03a..3d5010aba4 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts@@ -73,15 +73,20 @@ function createDb(): Database.Database {return sqlite;}-function insertMessage(sqlite: Database.Database, input: { id: string; createdAt: number; content: string }): void {+function insertMessage(+ sqlite: Database.Database,+ input: { id: string; createdAt: number; content: string },+): void {sqlite- .prepare(`+ .prepare(+ `INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, agent_meta, created_at, rewind_at) VALUES (@id, @clientId, 's1', 'assistant', @content, NULL, NULL, @createdAt, NULL)- `)+ `,+ ).run({id: input.id,clientId: input.id,@@ -101,13 +106,15 @@ function insertCostMessage(},): void {sqlite- .prepare(`+ .prepare(+ `INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, agent_meta, created_at, rewind_at) VALUES (@id, @id, 's1', @role, '""', NULL, @agentMeta, @createdAt, @rewindAt)- `)+ `,+ ).run({...input,agentMeta: input.agentMeta ? JSON.stringify(input.agentMeta) : null,@@ -139,10 +146,7 @@ describe('local-db:messages:list cursor', () => {'row-z','row-old',]);- expect((rows as Array<{ id: string; rowid: number }>).map((row) => row.rowid)).toEqual([- 1,- 4,- ]);+ expect((rows as Array<{ id: string; rowid: number }>).map((row) => row.rowid)).toEqual([1, 4]);});it('keeps around windows stable for same timestamp rows', async () => {@@ -164,9 +168,7 @@ describe('local-db:messages:list cursor', () => {'row-m',]);expect((rows as Array<{ id: string; rowid: number }>).map((row) => row.rowid)).toEqual([- 1,- 2,- 3,+ 1, 2, 3,]);});@@ -189,9 +191,7 @@ describe('local-db:messages:list cursor', () => {'row-m',]);expect((rows as Array<{ id: string; rowid: number }>).map((row) => row.rowid)).toEqual([- 1,- 2,- 3,+ 1, 2, 3,]);});@@ -202,7 +202,10 @@ describe('local-db:messages:list cursor', () => {registerMessageIpc();const handler = h.handlers.get('local-db:messages:around-client-id');- const rows = await handler?.({}, 's1', 'anchor', { radius: 0, contentCharLimit: 5 }) as Array<{+ const rows = (await handler?.({}, 's1', 'anchor', {+ radius: 0,+ contentCharLimit: 5,+ })) as Array<{id: string;content: string;agentMeta: Record<string, unknown>;@@ -248,7 +251,7 @@ describe('local-db:messages:list cursor', () => {registerMessageIpc();const prepareSpy = vi.spyOn(sqlite, 'prepare');const listHandler = h.handlers.get('local-db:messages:list');- const rows = await listHandler?.({}, 's1', { limit: 10 }) as Array<{+ const rows = (await listHandler?.({}, 's1', { limit: 10 })) as Array<{id: string;agentMeta: Record<string, unknown> | null;}>;@@ -258,7 +261,9 @@ describe('local-db:messages:list cursor', () => {userTurnCostUsd: 52.229224,userTurnCostIsEstimate: false,});- const stored = sqlite.prepare('SELECT agent_meta FROM messages WHERE id = ?').get('final') as { agent_meta: string };+ const stored = sqlite.prepare('SELECT agent_meta FROM messages WHERE id = ?').get('final') as {+ agent_meta: string;+ };expect(JSON.parse(stored.agent_meta)).toEqual({turnCostUsd: 0.777042,});@@ -274,21 +279,29 @@ describe('findPendingAgentHandoff 持久消费位', () => {content: Record<string, unknown>,createdAt = 1_000,): void {- sqlite.prepare(`+ sqlite+ .prepare(+ `INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, agent_meta,agent_kind, created_at, rewind_at) VALUES ('sw', 'sw', 's1', 'agent_switch', ?, NULL, NULL, 'cc', ?, NULL)- `).run(JSON.stringify(content), createdAt);+ `,+ )+ .run(JSON.stringify(content), createdAt);}function insertUser(sqlite: Database.Database, createdAt = 2_000): void {- sqlite.prepare(`+ sqlite+ .prepare(+ `INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, agent_meta,agent_kind, created_at, rewind_at) VALUES ('user-after', 'user-after', 's1', 'user', '"失败首发"', NULL, NULL, 'codex', ?, NULL)- `).run(createdAt);+ `,+ )+ .run(createdAt);}it('失败首发已落 user 行但 consumed=false,重启重建仍返回 handoff', async () => {@@ -317,16 +330,22 @@ describe('findPendingAgentHandoff 持久消费位', () => {it('restores a hidden context rebuild marker after app restart', async () => {const sqlite = createDb();sqlite.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');- sqlite.prepare(`+ sqlite+ .prepare(+ `INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, agent_meta,agent_kind, created_at, rewind_at) VALUES ('ctx', 'ctx', 's1', 'context_rebuild', ?, NULL, NULL, 'cc', 3000, 3000)- `).run(JSON.stringify({ handoff: 'FILTERED-HISTORY', consumed: false }));+ `,+ )+ .run(JSON.stringify({ handoff: 'FILTERED-HISTORY', consumed: false }));await expect(findPendingAgentHandoff('s1')).resolves.toBe('FILTERED-HISTORY');await markLatestAgentHandoffConsumed('s1');await expect(findPendingAgentHandoff('s1')).resolves.toBeNull();- const stored = sqlite.prepare('SELECT content, rewind_at FROM messages WHERE id = ?').get('ctx') as {+ const stored = sqlite+ .prepare('SELECT content, rewind_at FROM messages WHERE id = ?')+ .get('ctx') as {content: string;rewind_at: number;};@@ -342,17 +361,21 @@ describe('findParkedEngineSession context rebuild boundary', () => {it('does not resume a parked native session from before message deletion', async () => {const sqlite = createDb();sqlite.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');- sqlite.prepare(`+ sqlite+ .prepare(+ `INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, agent_meta,agent_kind, created_at, rewind_at) VALUES('sw', 'sw', 's1', 'agent_switch', ?, NULL, NULL, 'codex', 1000, NULL),('ctx', 'ctx', 's1', 'context_rebuild', ?, NULL, NULL, NULL, 2000, 2000)- `).run(- JSON.stringify({ fromAgentKind: 'codex', fromSdkSessionId: 'parked-codex' }),- JSON.stringify({ handoff: 'filtered', consumed: true }),- );+ `,+ )+ .run(+ JSON.stringify({ fromAgentKind: 'codex', fromSdkSessionId: 'parked-codex' }),+ JSON.stringify({ handoff: 'filtered', consumed: true }),+ );await expect(findParkedEngineSession('s1', 'codex')).resolves.toBeNull();});@@ -375,8 +398,20 @@ describe('getMessageDeletionTarget', () => {`);for (const row of [{ id: 'user', role: 'user', content: '"diagnose"', agentMeta: null, createdAt: 1_000 },- { id: 'progress', role: 'assistant', content: '"checking"', agentMeta: null, createdAt: 1_100 },- { id: 'thinking', role: 'thinking', content: '"analysis"', agentMeta: null, createdAt: 1_200 },+ {+ id: 'progress',+ role: 'assistant',+ content: '"checking"',+ agentMeta: null,+ createdAt: 1_100,+ },+ {+ id: 'thinking',+ role: 'thinking',+ content: '"analysis"',+ agentMeta: null,+ createdAt: 1_200,+ },{id: 'auto-resume',role: 'user',@@ -389,7 +424,13 @@ describe('getMessageDeletionTarget', () => {{ id: 'error', role: 'error', content: '"late error"', agentMeta: null, createdAt: 1_600 },{ id: 'switch', role: 'agent_switch', content: '{}', agentMeta: null, createdAt: 1_700 },{ id: 'next-user', role: 'user', content: '"thanks"', agentMeta: null, createdAt: 1_800 },- { id: 'next-answer', role: 'assistant', content: '"welcome"', agentMeta: null, createdAt: 1_900 },+ {+ id: 'next-answer',+ role: 'assistant',+ content: '"welcome"',+ agentMeta: null,+ createdAt: 1_900,+ },]) {insert.run(row);}@@ -397,14 +438,7 @@ describe('getMessageDeletionTarget', () => {await expect(getMessageDeletionTarget('s1', 'progress')).resolves.toEqual({id: 'progress',role: 'assistant',- deletedClientIds: [- 'progress',- 'thinking',- 'auto-resume',- 'tool',- 'final',- 'error',- ],+ deletedClientIds: ['progress', 'thinking', 'auto-resume', 'tool', 'final', 'error'],});});@@ -523,7 +557,9 @@ describe('getMessageDeletionTarget', () => {it('keeps a blank real user message as a deletion boundary', async () => {const sqlite = createDb();sqlite.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');- sqlite.prepare(`+ sqlite+ .prepare(+ `INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, agent_meta, created_at, rewind_at) VALUES@@ -531,7 +567,9 @@ describe('getMessageDeletionTarget', () => {('before', 'before', 's1', 'assistant', '"before"', NULL, NULL, 1100, NULL),('blank-user', 'blank-user', 's1', 'user', '""', NULL, NULL, 1200, NULL),('target', 'target', 's1', 'assistant', '"target"', NULL, NULL, 1300, NULL)- `).run();+ `,+ )+ .run();await expect(getMessageDeletionTarget('s1', 'target')).resolves.toEqual({id: 'target',@@ -543,13 +581,17 @@ describe('getMessageDeletionTarget', () => {it('keeps user-message deletion scoped to the selected row', async () => {const sqlite = createDb();sqlite.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');- sqlite.prepare(`+ sqlite+ .prepare(+ `INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, agent_meta, created_at, rewind_at) VALUES('user', 'user', 's1', 'user', '"question"', NULL, NULL, 1000, NULL),('answer', 'answer', 's1', 'assistant', '"answer"', NULL, NULL, 1100, NULL)- `).run();+ `,+ )+ .run();await expect(getMessageDeletionTarget('s1', 'user')).resolves.toEqual({id: 'user',@@ -590,7 +632,14 @@ describe('readPriorUserRoundCost', () => {insertCostMessage(sqlite, { id: 'target', role: 'assistant', createdAt: 1_300 });await expect(readPriorUserRoundCost('s1', 'target')).resolves.toEqual({- costUsd: 18.934191,+ money: {+ amount: expect.closeTo(18.934191 * 6.7, 10),+ currency: 'CNY',+ approximate: true,+ kind: 'actual-cost',+ estimateReasons: ['fixed-fx', 'legacy-usd', 'subscription-value'],+ },+ costUsd: 0,hasEstimatedValue: true,});});@@ -622,7 +671,14 @@ describe('readPriorUserRoundCost', () => {insertCostMessage(sqlite, { id: 'target', role: 'assistant', createdAt: 1_500 });await expect(readPriorUserRoundCost('s1', 'target')).resolves.toEqual({- costUsd: 0.5,+ money: {+ amount: 3.35,+ currency: 'CNY',+ approximate: true,+ kind: 'actual-cost',+ estimateReasons: ['fixed-fx', 'legacy-usd'],+ },+ costUsd: 0,hasEstimatedValue: false,});});diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.tsindex 745c4d4de3..d1f420d375 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts@@ -73,6 +73,9 @@ function createDb(): void {sdk_session_id TEXT,total_token_usage INTEGER NOT NULL DEFAULT 0,total_cost_usd REAL NOT NULL DEFAULT 0,+ total_cost_amount REAL NOT NULL DEFAULT 0,+ total_cost_currency TEXT,+ total_cost_is_approximate INTEGER NOT NULL DEFAULT 0,context_tokens INTEGER NOT NULL DEFAULT 0,context_window INTEGER NOT NULL DEFAULT 0,fast_mode INTEGER NOT NULL DEFAULT 0,diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.tsindex 6040523ebc..e2836461f7 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts@@ -44,7 +44,9 @@ vi.mock('../../../git-context/prRefsStore', () => ({}));vi.mock('../../../imageCacheStore', () => ({ removeSession: vi.fn(async () => undefined) }));vi.mock('../recentWorkdirs', () => ({ upsertRecentWorkdir: vi.fn(async () => undefined) }));-vi.mock('../../../device-link/broadcast-tap.js', () => ({ tapWindowBroadcast: h.tapWindowBroadcast }));+vi.mock('../../../device-link/broadcast-tap.js', () => ({+ tapWindowBroadcast: h.tapWindowBroadcast,+}));vi.mock('../../agentIslandSessionPatch', () => ({ notifyAgentIslandSessionPatch: vi.fn() }));vi.mock('../../../messagePersistBroadcaster', () => ({ noteSessionClearBoundary: vi.fn() }));vi.mock('../../../sessionIds', () => ({ resolveBusinessSessionId: (id: string) => id }));@@ -69,6 +71,9 @@ function createDb(): void {sdk_session_id TEXT,total_token_usage INTEGER NOT NULL DEFAULT 0,total_cost_usd REAL NOT NULL DEFAULT 0,+ total_cost_amount REAL NOT NULL DEFAULT 0,+ total_cost_currency TEXT,+ total_cost_is_approximate INTEGER NOT NULL DEFAULT 0,context_tokens INTEGER NOT NULL DEFAULT 0,context_window INTEGER NOT NULL DEFAULT 0,fast_mode INTEGER NOT NULL DEFAULT 0,@@ -141,8 +146,8 @@ describe('local-db:sessions:update handler wiring', () => {it('persists and broadcasts title-only patches to device-link subscribers', async () => {await invokeUpdate('codex-local', { title: '排查远程标题同步' });- const persisted = h.sqlite!- .prepare('SELECT title FROM sessions WHERE id = ?')+ const persisted = h+ .sqlite!.prepare('SELECT title FROM sessions WHERE id = ?').get('codex-local') as { title: string };expect(persisted.title).toBe('排查远程标题同步');expect(h.tapWindowBroadcast).toHaveBeenCalledWith(@@ -178,7 +183,10 @@ describe('local-db:sessions:update handler wiring', () => {// 模拟真实编排:迁移把内存 id 持久化进 DB 并上报;handler 必须在迁移后才查// 返回行,并把该 id 并入广播 patch,renderer 才不会留着旧 resume id。h.relocate.mockImplementation(async () => {- h.sqlite!.prepare('UPDATE sessions SET sdk_session_id = ? WHERE id = ?').run(liveId, 'cc-local');+ h.sqlite!.prepare('UPDATE sessions SET sdk_session_id = ? WHERE id = ?').run(+ liveId,+ 'cc-local',+ );return { persistedSdkSessionId: liveId };});diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.tsindex fa79523362..1be3c96cc8 100644--- a/apps/desktop/src/main/localDb/ipc/messages.ts+++ b/apps/desktop/src/main/localDb/ipc/messages.ts@@ -34,12 +34,18 @@ 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,+ normalizeRegionalMoney,+ regionalCurrencyForRegion,+ regionalizeLegacyUsd,+ regionalizeUsd,+ type RegionalMoney,+} from '../../../shared/regionalMoney.js';import { capReferenceMessageRows } from './history.js';-import type {- Message,- MessageRole,- AgentMeta,-} from '../../../renderer/lib/ccAgent.types';+import type { Message, MessageRole, AgentMeta } from '../../../renderer/lib/ccAgent.types';const log = createLogger('localDb/messages');@@ -52,7 +58,8 @@ type MessageRowWithRowid = MessageRow & { rowid: number };export interface EstimatedSessionValueEntry {clientId: string;- costUsd: number;+ money: RegionalMoney;+ costUsd?: number;}/**@@ -61,6 +68,7 @@ export interface EstimatedSessionValueEntry {* scoped; callers use this value only to produce a user-facing round total.*/export interface PriorUserRoundCost {+ money: RegionalMoney | null;costUsd: number;hasEstimatedValue: boolean;}@@ -76,77 +84,76 @@ const VALID_ROLES: ReadonlySet<MessageRole> = new Set([] as const);export function registerMessageIpc(): void {- ipcMain.handle(- 'local-db:messages:list',- async (_e, sessionId: unknown, opts: unknown) => {- const sid = requireString(sessionId, 'sessionId');- const limit = clampLimit(- (opts as { limit?: number } | undefined)?.limit,- );- const before = (opts as { before?: string } | undefined)?.before;- const beforeTs = (opts as { beforeTs?: number } | undefined)?.beforeTs;- const db = getDbClient().drizzle;+ ipcMain.handle('local-db:messages:list', async (_e, sessionId: unknown, opts: unknown) => {+ const sid = requireString(sessionId, 'sessionId');+ const limit = clampLimit((opts as { limit?: number } | undefined)?.limit);+ const before = (opts as { before?: string } | undefined)?.before;+ const beforeTs = (opts as { beforeTs?: number } | undefined)?.beforeTs;+ const db = getDbClient().drizzle;- // 外部历史导入(Codex rollout / Claude transcript):device-link 隧道调用- // 只在首页请求跑(分页跳过,#318 性能语义;首页判定 = 无任何分页游标),- // 覆盖「被控端从未本机打开该会话」的导入缺口。- await runMessagesListImportSideEffects(sid, {}, {+ // 外部历史导入(Codex rollout / Claude transcript):device-link 隧道调用+ // 只在首页请求跑(分页跳过,#318 性能语义;首页判定 = 无任何分页游标),+ // 覆盖「被控端从未本机打开该会话」的导入缺口。+ await runMessagesListImportSideEffects(+ sid,+ {},+ {deviceLinkFirstPage: !before && beforeTs == null,- });-- let beforeCursor: { createdAt: number; rowid: number } | null = null;- let beforeMs: number | null = null;- if (typeof before === 'string' && before) {- const beforeRow = await db- .select({ createdAt: messages.createdAt, rowid: messageRowid })- .from(messages)- .where(eq(messages.id, before))- .limit(1);- if (beforeRow.length > 0) {- beforeCursor = beforeRow[0];- }- } else if (typeof beforeTs === 'number' && Number.isFinite(beforeTs)) {- beforeMs = beforeTs;- }+ },+ );- // /clear:过滤 createdAt > session.clearedAt,本地 DB 旧消息也遵守 clearedAt 边界- const sessionRow = await db- .select({ clearedAt: sessions.clearedAt })- .from(sessions)- .where(eq(sessions.id, sid))+ let beforeCursor: { createdAt: number; rowid: number } | null = null;+ let beforeMs: number | null = null;+ if (typeof before === 'string' && before) {+ const beforeRow = await db+ .select({ createdAt: messages.createdAt, rowid: messageRowid })+ .from(messages)+ .where(eq(messages.id, before)).limit(1);- const clearedAtMs = sessionRow[0]?.clearedAt ?? null;-- // rewind-session:list 永远过滤 rewind_at IS NULL —— 被 rewind 软删的消息在 UI 上不可见- const conds: (SQL<unknown> | undefined)[] = [eq(messages.sessionId, sid), isNull(messages.rewindAt)];- if (beforeCursor) {- conds.push(- or(- lt(messages.createdAt, beforeCursor.createdAt),- and(- eq(messages.createdAt, beforeCursor.createdAt),- lt(messageRowid, beforeCursor.rowid),- ),- ),- );- } else if (beforeMs !== null) {- conds.push(lt(messages.createdAt, beforeMs));+ if (beforeRow.length > 0) {+ beforeCursor = beforeRow[0];}- if (clearedAtMs !== null) conds.push(gt(messages.createdAt, clearedAtMs));- const whereExpr = and(...conds);+ } else if (typeof beforeTs === 'number' && Number.isFinite(beforeTs)) {+ beforeMs = beforeTs;+ }- const rows = await db- .select({- ...getMessageSelectFields(),- rowid: messageRowid,- })- .from(messages)- .where(whereExpr)- .orderBy(desc(messages.createdAt), desc(messageRowid))- .limit(limit);- return hydrateLegacyUserTurnCosts(rows.map(messageToCamelWithRowid));- },- );+ // /clear:过滤 createdAt > session.clearedAt,本地 DB 旧消息也遵守 clearedAt 边界+ const sessionRow = await db+ .select({ clearedAt: sessions.clearedAt })+ .from(sessions)+ .where(eq(sessions.id, sid))+ .limit(1);+ const clearedAtMs = sessionRow[0]?.clearedAt ?? null;++ // rewind-session:list 永远过滤 rewind_at IS NULL —— 被 rewind 软删的消息在 UI 上不可见+ const conds: (SQL<unknown> | undefined)[] = [+ eq(messages.sessionId, sid),+ isNull(messages.rewindAt),+ ];+ if (beforeCursor) {+ conds.push(+ or(+ lt(messages.createdAt, beforeCursor.createdAt),+ and(eq(messages.createdAt, beforeCursor.createdAt), lt(messageRowid, beforeCursor.rowid)),+ ),+ );+ } else if (beforeMs !== null) {+ conds.push(lt(messages.createdAt, beforeMs));+ }+ if (clearedAtMs !== null) conds.push(gt(messages.createdAt, clearedAtMs));+ const whereExpr = and(...conds);++ const rows = await db+ .select({+ ...getMessageSelectFields(),+ rowid: messageRowid,+ })+ .from(messages)+ .where(whereExpr)+ .orderBy(desc(messages.createdAt), desc(messageRowid))+ .limit(limit);+ return hydrateLegacyUserTurnCosts(rows.map(messageToCamelWithRowid));+ });ipcMain.handle('local-db:messages:around',@@ -224,7 +231,9 @@ export function registerMessageIpc(): void {.orderBy(asc(messages.createdAt), asc(messageRowid)).limit(radius);- return hydrateLegacyUserTurnCosts([...before.reverse(), anchor, ...after].map(messageToCamelWithRowid));+ return hydrateLegacyUserTurnCosts(+ [...before.reverse(), anchor, ...after].map(messageToCamelWithRowid),+ );},);@@ -306,127 +315,122 @@ export function registerMessageIpc(): void {.orderBy(asc(messages.createdAt), asc(messageRowid)).limit(radius);- const rows = await hydrateLegacyUserTurnCosts([...before.reverse(), anchor, ...after].map(messageToCamelWithRowid));+ const rows = await hydrateLegacyUserTurnCosts(+ [...before.reverse(), anchor, ...after].map(messageToCamelWithRowid),+ );return capReferenceMessageRows(rows, contentCharLimit);},);- ipcMain.handle(- 'local-db:messages:estimatedSessionValue',- async (_e, sessionId: unknown) => {- const sid = requireString(sessionId, 'sessionId');- const db = getDbClient().drizzle;-- const [sessionRow] = await db- .select({ clearedAt: sessions.clearedAt })- .from(sessions)- .where(eq(sessions.id, sid))- .limit(1);- const clearedAtMs = sessionRow?.clearedAt ?? null;+ ipcMain.handle('local-db:messages:estimatedSessionValue', async (_e, sessionId: unknown) => {+ const sid = requireString(sessionId, 'sessionId');+ const db = getDbClient().drizzle;- const visibleConds = clearedAtMs === null ? [] : [gt(messages.createdAt, clearedAtMs)];- const rows = await db- .select({- clientId: messages.clientId,- agentMeta: messages.agentMeta,- })- .from(messages)- .where(and(+ const [sessionRow] = await db+ .select({ clearedAt: sessions.clearedAt })+ .from(sessions)+ .where(eq(sessions.id, sid))+ .limit(1);+ const clearedAtMs = sessionRow?.clearedAt ?? null;++ const visibleConds = clearedAtMs === null ? [] : [gt(messages.createdAt, clearedAtMs)];+ const rows = await db+ .select({+ clientId: messages.clientId,+ agentMeta: messages.agentMeta,+ })+ .from(messages)+ .where(+ and(eq(messages.sessionId, sid),eq(messages.role, 'assistant'),isNull(messages.rewindAt),...visibleConds,- ));- const entries = extractEstimatedSessionValueEntries(rows);- return {- totalValueUsd: entries.reduce((sum, item) => sum + item.costUsd, 0),- entries,- };- },- );+ ),+ );+ const entries = extractEstimatedSessionValueEntries(rows);+ const totalValueMoney =+ addCompatibleRegionalMoney(+ entries.map((entry) => entry.money),+ regionalCurrencyForRegion(CURRENT_CINDY_REGION),+ );+ const hasCompleteUsdProjection = entries.every((entry) => typeof entry.costUsd === 'number');+ return {+ totalValueMoney,+ ...(hasCompleteUsdProjection+ ? {+ totalValueUsd: entries.reduce((sum, item) => sum + (item.costUsd ?? 0), 0),+ }+ : {}),+ entries,+ };+ });- ipcMain.handle(- 'local-db:messages:create',- async (_e, sessionId: unknown, body: unknown) => {- const sid = requireString(sessionId, 'sessionId');- if (!body || typeof body !== 'object') {- throwIpcError('INVALID_PARAMS', 'body 必须是对象');- }- const b = body as {- clientId?: unknown;- role?: unknown;- content?: unknown;- toolUseId?: unknown;- agentMeta?: unknown;- createdAt?: unknown;- };- const cid = requireString(b.clientId, 'clientId');- if (typeof b.role !== 'string' || !VALID_ROLES.has(b.role as MessageRole)) {- throwIpcError('INVALID_PARAMS', 'role 不合法');- }- if (- b.agentMeta !== undefined &&- b.agentMeta !== null &&- (typeof b.agentMeta !== 'object' || Array.isArray(b.agentMeta))- ) {- throwIpcError('INVALID_PARAMS', 'agentMeta 必须是对象或 null');- }- let createdAt: number | undefined;- if (b.createdAt !== undefined) {- const parsed = typeof b.createdAt === 'number'+ ipcMain.handle('local-db:messages:create', async (_e, sessionId: unknown, body: unknown) => {+ const sid = requireString(sessionId, 'sessionId');+ if (!body || typeof body !== 'object') {+ throwIpcError('INVALID_PARAMS', 'body 必须是对象');+ }+ const b = body as {+ clientId?: unknown;+ role?: unknown;+ content?: unknown;+ toolUseId?: unknown;+ agentMeta?: unknown;+ createdAt?: unknown;+ };+ const cid = requireString(b.clientId, 'clientId');+ if (typeof b.role !== 'string' || !VALID_ROLES.has(b.role as MessageRole)) {+ throwIpcError('INVALID_PARAMS', 'role 不合法');+ }+ if (+ b.agentMeta !== undefined &&+ b.agentMeta !== null &&+ (typeof b.agentMeta !== 'object' || Array.isArray(b.agentMeta))+ ) {+ throwIpcError('INVALID_PARAMS', 'agentMeta 必须是对象或 null');+ }+ let createdAt: number | undefined;+ if (b.createdAt !== undefined) {+ const parsed =+ typeof b.createdAt === 'number'? b.createdAt- : (typeof b.createdAt === 'string' ? Date.parse(b.createdAt) : Number.NaN);- if (!Number.isFinite(parsed)) {- throwIpcError('INVALID_PARAMS', 'createdAt 必须是合法时间');- }- createdAt = parsed;+ : typeof b.createdAt === 'string'+ ? Date.parse(b.createdAt)+ : Number.NaN;+ if (!Number.isFinite(parsed)) {+ throwIpcError('INVALID_PARAMS', 'createdAt 必须是合法时间');}+ createdAt = parsed;+ }- return createMessage(sid, {- clientId: cid,- role: b.role as MessageRole,- content: b.content,- toolUseId: typeof b.toolUseId === 'string' ? b.toolUseId : undefined,- agentMeta: (b.agentMeta as AgentMeta | null | undefined) ?? null,- createdAt,- });- },- );+ return createMessage(sid, {+ clientId: cid,+ role: b.role as MessageRole,+ content: b.content,+ toolUseId: typeof b.toolUseId === 'string' ? b.toolUseId : undefined,+ agentMeta: (b.agentMeta as AgentMeta | null | undefined) ?? null,+ createdAt,+ });+ });// rewind-session:把 SDK echo 出的 user 消息 cc 元信息(uuid / sdkSessionId)// 回写到那条已存在的 user 消息。renderer 暂时用不到,注册 IPC 仅为对称完整性。ipcMain.handle('local-db:messages:updateAgentMeta',- async (- _e,- sessionId: unknown,- clientId: unknown,- agentMeta: unknown,- ) => {+ async (_e, sessionId: unknown, clientId: unknown, agentMeta: unknown) => {const sid = requireString(sessionId, 'sessionId');const cid = requireString(clientId, 'clientId');- if (- agentMeta !== null &&- (typeof agentMeta !== 'object' || Array.isArray(agentMeta))- ) {+ if (agentMeta !== null && (typeof agentMeta !== 'object' || Array.isArray(agentMeta))) {throwIpcError('INVALID_PARAMS', 'agentMeta 必须是对象或 null');}- await updateAgentMeta(- sid,- cid,- agentMeta === null ? null : JSON.stringify(agentMeta),- );+ await updateAgentMeta(sid, cid, agentMeta === null ? null : JSON.stringify(agentMeta));},);ipcMain.handle('local-db:messages:updateContent',- async (- _e,- sessionId: unknown,- clientId: unknown,- content: unknown,- ) => {+ async (_e, sessionId: unknown, clientId: unknown, content: unknown) => {const sid = requireString(sessionId, 'sessionId');const cid = requireString(clientId, 'clientId');const msg = await updateMessageContent(sid, cid, content);@@ -568,9 +572,8 @@ export async function getMessageDeletionTarget(.where(eq(sessions.id, sessionId)).limit(1);if (!session) return null;- const afterClear = session.clearedAt === null- ? undefined- : gt(messages.createdAt, session.clearedAt);+ const afterClear =+ session.clearedAt === null ? undefined : gt(messages.createdAt, session.clearedAt);const [row] = await db.select({id: messages.id,@@ -616,9 +619,7 @@ export async function getMessageDeletionTarget(const scanRealUserBoundary = async (direction: 'prior' | 'next',): Promise<UserBoundaryRow | undefined> => {- let cursor: SQL<unknown> | undefined = direction === 'prior'- ? beforeTarget- : afterTarget;+ let cursor: SQL<unknown> | undefined = direction === 'prior' ? beforeTarget : afterTarget;while (cursor) {const candidates = await db.select({@@ -634,21 +635,22 @@ export async function getMessageDeletionTarget(direction === 'prior' ? desc(messageRowid) : asc(messageRowid),).limit(MESSAGE_DELETION_USER_BOUNDARY_PAGE_SIZE);- const boundary = candidates.find((candidate) =>- !isHiddenContinuationUserMessage(candidate.agentMeta, candidate.content),+ const boundary = candidates.find(+ (candidate) => !isHiddenContinuationUserMessage(candidate.agentMeta, candidate.content),);if (boundary) return boundary;const last = candidates.at(-1);if (!last || candidates.length < MESSAGE_DELETION_USER_BOUNDARY_PAGE_SIZE) return undefined;- cursor = direction === 'prior'- ? or(- lt(messages.createdAt, last.createdAt),- and(eq(messages.createdAt, last.createdAt), lt(messageRowid, last.rowid)),- )- : or(- gt(messages.createdAt, last.createdAt),- and(eq(messages.createdAt, last.createdAt), gt(messageRowid, last.rowid)),- );+ cursor =+ direction === 'prior'+ ? or(+ lt(messages.createdAt, last.createdAt),+ and(eq(messages.createdAt, last.createdAt), lt(messageRowid, last.rowid)),+ )+ : or(+ gt(messages.createdAt, last.createdAt),+ and(eq(messages.createdAt, last.createdAt), gt(messageRowid, last.rowid)),+ );}return undefined;};@@ -733,9 +735,9 @@ export async function commitMessageDeletion(// 当前生产聊天附件主要是 session-attachment 粗粒度引用,不能因删除一轮// 误删同 session 其它气泡仍在用的 blob。这里只释放明确以消息 id/clientId// 登记的 message refs;零引用 blob 由 recycler 统一回收。- const mediaRefIds = [...new Set(- result.messages.flatMap((message) => [message.messageId, message.clientId]),- )];+ const mediaRefIds = [+ ...new Set(result.messages.flatMap((message) => [message.messageId, message.clientId])),+ ];const mediaCleanup = await Promise.allSettled(mediaRefIds.map((refId) => removeMediaRefs({ refKind: 'message', refId })),);@@ -762,9 +764,8 @@ export async function commitMessageDeletion(.from(sessions).where(eq(sessions.id, sessionId)).limit(1);- const visibleAfterClear = sessionRow?.clearedAt == null- ? undefined- : gt(messages.createdAt, sessionRow.clearedAt);+ const visibleAfterClear =+ sessionRow?.clearedAt == null ? undefined : gt(messages.createdAt, sessionRow.clearedAt);const visibleMessageProjection = and(eq(messages.sessionId, sessionId),sql`${messages.role} IN ('user', 'assistant')`,@@ -824,15 +825,14 @@ export async function dismissErrorMessage(const [row] = await db.select().from(messages)- .where(- and(- eq(messages.sessionId, sessionId),- eq(messages.clientId, clientId),- ),- )+ .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, clientId))).limit(1);if (!row || row.role !== 'error') return null;- const updated = await updateMessageContent(sessionId, clientId, mergeDismissedIntoErrorContent(row.content));+ const updated = await updateMessageContent(+ sessionId,+ clientId,+ mergeDismissedIntoErrorContent(row.content),+ );// 广播更新行(review P2):dismiss 若只写 DB,同会话开在其它窗口/被控端本机// 窗口的内存 errorDismissed 仍为 false,stale 尾部 banner 留着还能对已忽略的// 错误重复 enqueue 续跑。peer 端 handleMessageCreatedRaw 按 clientId merge,@@ -850,21 +850,11 @@ export async function updateMessageContent(await db.update(messages).set({ content: safeStringify(content) })- .where(- and(- eq(messages.sessionId, sessionId),- eq(messages.clientId, clientId),- ),- );+ .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, clientId)));const [row] = await db.select().from(messages)- .where(- and(- eq(messages.sessionId, sessionId),- eq(messages.clientId, clientId),- ),- )+ .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, clientId))).limit(1);if (row) {// 挂账钩子同样覆盖"先摘要 create、后全文 update"的 tool_result 顺序@@ -900,7 +890,10 @@ function clampAroundRadius(raw: unknown): number {function requireReferenceContentCharLimit(raw: unknown): number | null {if (raw === undefined || raw === null) return null;if (typeof raw !== 'number' || !Number.isInteger(raw) || raw < 1 || raw > 8_000) {- throwIpcError('INVALID_PARAMS', 'contentCharLimit must be an integer between 1 and 8000 or null');+ throwIpcError(+ 'INVALID_PARAMS',+ 'contentCharLimit must be an integer between 1 and 8000 or null',+ );}return raw;}@@ -975,12 +968,7 @@ export async function createMessage(const existing = await db.select().from(messages)- .where(- and(- eq(messages.sessionId, sessionId),- eq(messages.clientId, body.clientId),- ),- )+ .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, body.clientId))).limit(1);if (existing.length > 0) {return messageToCamel(existing[0]);@@ -995,12 +983,7 @@ export async function createMessage(const after = await db.select().from(messages)- .where(- and(- eq(messages.sessionId, sessionId),- eq(messages.clientId, body.clientId),- ),- )+ .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, body.clientId))).limit(1);if (after.length > 0) return messageToCamel(after[0]);throw err;@@ -1063,9 +1046,7 @@ export async function updateAgentMeta(await db.update(messages).set({ agentMeta: agentMetaJson })- .where(- and(eq(messages.sessionId, sessionId), eq(messages.clientId, clientId)),- );+ .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, clientId)));}export function extractEstimatedSessionValueEntries(@@ -1084,7 +1065,32 @@ export function extractEstimatedSessionValueEntries(continue;}if (meta?.turnCostIsEstimate !== true) continue;- if (typeof meta.turnCostUsd !== 'number' || !Number.isFinite(meta.turnCostUsd) || meta.turnCostUsd <= 0) {+ const structured = normalizeRegionalMoney(meta.turnCost);+ if (structured && structured.amount > 0) {+ const recomputed =+ structured.currency === 'USD'+ ? resolveStaleCodexSubscriptionValueEstimate(+ structured.amount,+ normalizeTurnUsageDetails(meta.turnUsageDetails),+ meta.model,+ )+ : null;+ const money = asValueEstimateMoney({+ ...structured,+ amount: recomputed ?? structured.amount,+ });+ entries.push({+ clientId: row.clientId,+ money,+ ...(money.currency === 'USD' ? { costUsd: money.amount } : {}),+ });+ continue;+ }+ if (+ typeof meta.turnCostUsd !== 'number' ||+ !Number.isFinite(meta.turnCostUsd) ||+ meta.turnCostUsd <= 0+ ) {continue;}const recomputed = resolveStaleCodexSubscriptionValueEstimate(@@ -1092,11 +1098,12 @@ export function extractEstimatedSessionValueEntries(normalizeTurnUsageDetails(meta.turnUsageDetails),meta.model,);- if (typeof recomputed === 'number' && Number.isFinite(recomputed) && recomputed > 0) {- entries.push({ clientId: row.clientId, costUsd: recomputed });- continue;- }- entries.push({ clientId: row.clientId, costUsd: meta.turnCostUsd });+ const costUsd = recomputed ?? meta.turnCostUsd;+ entries.push({+ clientId: row.clientId,+ money: regionalizeUsd(costUsd, CURRENT_CINDY_REGION, 'legacy-usd', 'value-estimate'),+ costUsd,+ });}return entries;}@@ -1123,9 +1130,7 @@ export async function patchMessageAgentMetaWithResult(const rows = await db.select({ agentMeta: messages.agentMeta }).from(messages)- .where(- and(eq(messages.sessionId, sessionId), eq(messages.clientId, clientId)),- )+ .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, clientId))).limit(1);if (rows.length === 0) return null;// 损坏的 JSON 以 {} 为底重建(补丁字段仍写入,旧字段无法挽救)。@@ -1155,11 +1160,13 @@ export async function broadcastMessageAgentMetaUpdate(const [row] = await db.select().from(messages)- .where(and(- eq(messages.sessionId, sessionId),- eq(messages.clientId, clientId),- isNull(messages.rewindAt),- ))+ .where(+ and(+ eq(messages.sessionId, sessionId),+ eq(messages.clientId, clientId),+ isNull(messages.rewindAt),+ ),+ ).limit(1);if (!row) return false;broadcastMessageRow(sessionId, messageToCamel(row));@@ -1184,21 +1191,24 @@ export async function readPriorUserRoundCost(const [target] = await db.select({ createdAt: messages.createdAt, rowid: messageRowid }).from(messages)- .where(and(- eq(messages.sessionId, sessionId),- eq(messages.clientId, assistantClientId),- eq(messages.role, 'assistant'),- isNull(messages.rewindAt),- ))+ .where(+ and(+ eq(messages.sessionId, sessionId),+ eq(messages.clientId, assistantClientId),+ eq(messages.role, 'assistant'),+ isNull(messages.rewindAt),+ ),+ ).limit(1);- if (!target) return { costUsd: 0, hasEstimatedValue: false };+ if (!target) return { money: null, costUsd: 0, hasEstimatedValue: false };const [session] = await db.select({ clearedAt: sessions.clearedAt }).from(sessions).where(eq(sessions.id, sessionId)).limit(1);- const visibleAfterClear = session?.clearedAt == null ? [] : [gt(messages.createdAt, session.clearedAt)];+ const visibleAfterClear =+ session?.clearedAt == null ? [] : [gt(messages.createdAt, session.clearedAt)];const beforeTarget = or(lt(messages.createdAt, target.createdAt),and(eq(messages.createdAt, target.createdAt), lt(messageRowid, target.rowid)),@@ -1207,16 +1217,18 @@ export async function readPriorUserRoundCost(const userRows = await db.select({ createdAt: messages.createdAt, rowid: messageRowid, agentMeta: messages.agentMeta }).from(messages)- .where(and(- eq(messages.sessionId, sessionId),- eq(messages.role, 'user'),- isNull(messages.rewindAt),- beforeTarget,- ...visibleAfterClear,- ))+ .where(+ and(+ eq(messages.sessionId, sessionId),+ eq(messages.role, 'user'),+ isNull(messages.rewindAt),+ beforeTarget,+ ...visibleAfterClear,+ ),+ ).orderBy(desc(messages.createdAt), desc(messageRowid));const boundary = userRows.find((row) => !isAutoResumeUserMessage(row.agentMeta));- if (!boundary) return { costUsd: 0, hasEstimatedValue: false };+ if (!boundary) return { money: null, costUsd: 0, hasEstimatedValue: false };const afterBoundary = or(gt(messages.createdAt, boundary.createdAt),@@ -1225,25 +1237,46 @@ export async function readPriorUserRoundCost(const assistantRows = await db.select({ agentMeta: messages.agentMeta }).from(messages)- .where(and(- eq(messages.sessionId, sessionId),- eq(messages.role, 'assistant'),- isNull(messages.rewindAt),- afterBoundary,- beforeTarget,- ...visibleAfterClear,- ));+ .where(+ and(+ eq(messages.sessionId, sessionId),+ eq(messages.role, 'assistant'),+ isNull(messages.rewindAt),+ afterBoundary,+ beforeTarget,+ ...visibleAfterClear,+ ),+ );- let costUsd = 0;- let hasEstimatedValue = false;+ const values: RegionalMoney[] = [];+ const estimatedCurrencies = new Set<RegionalMoney['currency']>();for (const row of assistantRows) {const meta = parseAgentMetaRecord(row.agentMeta);- const segmentCost = meta?.turnCostUsd;- if (typeof segmentCost !== 'number' || !Number.isFinite(segmentCost) || segmentCost <= 0) continue;- costUsd += segmentCost;- hasEstimatedValue ||= meta?.turnCostIsEstimate === true;+ const structured = normalizeRegionalMoney(meta?.turnCost);+ const legacy =+ typeof meta?.turnCostUsd === 'number' &&+ Number.isFinite(meta.turnCostUsd) &&+ meta.turnCostUsd > 0+ ? regionalizeLegacyUsd(meta.turnCostUsd, CURRENT_CINDY_REGION)+ : undefined;+ const rawSegment = structured ?? legacy;+ const isEstimate = rawSegment?.kind === 'value-estimate' || meta?.turnCostIsEstimate === true;+ const segment = rawSegment && isEstimate ? asValueEstimateMoney(rawSegment) : rawSegment;+ if (!segment || segment.amount <= 0) continue;+ values.push(segment);+ if (isEstimate) estimatedCurrencies.add(segment.currency);}- return { costUsd, hasEstimatedValue };+ const money = addCompatibleRegionalMoney(+ values,+ regionalCurrencyForRegion(CURRENT_CINDY_REGION),+ );+ const hasEstimatedValue =+ money !== null && estimatedCurrencies.has(money.currency);+ return {+ money,+ costUsd: money?.currency === 'USD' ? money.amount : 0,+ hasEstimatedValue,+ };}/**@@ -1280,7 +1313,8 @@ async function hydrateLegacyUserTurnCosts(history: Message[]): Promise<Message[].from(sessions).where(eq(sessions.id, sessionId)).limit(1);- const visibleAfterClear = session?.clearedAt == null ? [] : [gt(messages.createdAt, session.clearedAt)];+ const visibleAfterClear =+ session?.clearedAt == null ? [] : [gt(messages.createdAt, session.clearedAt)];const rows = await db.select({clientId: messages.clientId,@@ -1288,11 +1322,7 @@ async function hydrateLegacyUserTurnCosts(history: Message[]): Promise<Message[]agentMeta: messages.agentMeta,}).from(messages)- .where(and(- eq(messages.sessionId, sessionId),- isNull(messages.rewindAt),- ...visibleAfterClear,- ))+ .where(and(eq(messages.sessionId, sessionId), isNull(messages.rewindAt), ...visibleAfterClear)).orderBy(asc(messages.createdAt), asc(messageRowid));const totalsByClientId = new Map<string, PriorUserRoundCost>();@@ -1309,16 +1339,22 @@ async function hydrateLegacyUserTurnCosts(history: Message[]): Promise<Message[]if (row.role !== 'assistant') continue;const meta = parseAgentMetaRecord(row.agentMeta);const segmentCost = meta?.turnCostUsd;- if (!hasRealUserBoundary ||+ if (+ !hasRealUserBoundary ||typeof segmentCost !== 'number' ||!Number.isFinite(segmentCost) ||- segmentCost <= 0) {+ segmentCost <= 0+ ) {continue;}costUsd += segmentCost;hasEstimatedValue ||= meta?.turnCostIsEstimate === true;if (legacyClientIds.has(row.clientId)) {- totalsByClientId.set(row.clientId, { costUsd, hasEstimatedValue });+ totalsByClientId.set(row.clientId, {+ money: regionalizeLegacyUsd(costUsd, CURRENT_CINDY_REGION),+ costUsd,+ hasEstimatedValue,+ });}}@@ -1345,6 +1381,7 @@ async function hydrateLegacyUserTurnCosts(history: Message[]): Promise<Message[]...message,agentMeta: {...agentMeta,+ ...(total.money ? { userTurnCost: total.money } : {}),userTurnCostUsd: total.costUsd,userTurnCostIsEstimate: total.hasEstimatedValue,},@@ -1377,10 +1414,7 @@ function readMessageText(content: string): string {}function isHiddenContinuationUserMessage(agentMeta: string | null, content: string): boolean {- return (- isAutoResumeUserMessage(agentMeta) ||- isSyntheticTriggerText(readMessageText(content))- );+ return isAutoResumeUserMessage(agentMeta) || isSyntheticTriggerText(readMessageText(content));}function parseAgentMetaRecord(agentMeta: string | null): Record<string, unknown> | null {@@ -1388,7 +1422,7 @@ function parseAgentMetaRecord(agentMeta: string | null): Record<string, unknown>try {const parsed = JSON.parse(agentMeta);return parsed && typeof parsed === 'object' && !Array.isArray(parsed)- ? parsed as Record<string, unknown>+ ? (parsed as Record<string, unknown>): null;} catch {return null;@@ -1404,9 +1438,7 @@ function parseAgentMetaRecord(agentMeta: string | null): Record<string, unknown>* 字段的 v1 agent_switch 老行才回落“边界后是否已有 user 行”的启发式。* 同毫秒并列用 rowid 决序(与 messages list 的 tie-break 口径一致)。*/-export async function findPendingAgentHandoff(- sessionId: string,-): Promise<string | null> {+export async function findPendingAgentHandoff(sessionId: string): Promise<string | null> {const db = getDbClient().drizzle;const [sessRow] = await db.select({ clearedAt: sessions.clearedAt })@@ -1442,9 +1474,8 @@ export async function findPendingAgentHandoff(} catch {return null;}- const handoff = typeof parsed.handoff === 'string' && parsed.handoff.length > 0- ? parsed.handoff- : null;+ const handoff =+ typeof parsed.handoff === 'string' && parsed.handoff.length > 0 ? parsed.handoff : null;if (!handoff || parsed.consumed === true) return null;// v2 边界以持久消费位为真源:失败首发可能已先落 user 行;只要 vendor 尚未// accepted,重启后仍必须恢复交接。缺字段的 v1 老行才走 user-row 启发式。@@ -1562,11 +1593,7 @@ export async function findParkedEngineSession(const [contextRebuild] = await db.select({ rowid: messageRowid, createdAt: messages.createdAt }).from(messages)- .where(and(- eq(messages.sessionId, sessionId),- eq(messages.role, 'context_rebuild'),- afterClear,- ))+ .where(and(eq(messages.sessionId, sessionId), eq(messages.role, 'context_rebuild'), afterClear)).orderBy(desc(messages.createdAt), desc(messageRowid)).limit(1);const rows = await db@@ -1643,14 +1670,16 @@ export async function markLatestAgentHandoffConsumed(sessionId: string): Promiseconst [boundary] = await db.select({ clientId: messages.clientId, role: messages.role, content: messages.content }).from(messages)- .where(and(- eq(messages.sessionId, sessionId),- or(- and(eq(messages.role, 'agent_switch'), isNull(messages.rewindAt)),- eq(messages.role, 'context_rebuild'),+ .where(+ and(+ eq(messages.sessionId, sessionId),+ or(+ and(eq(messages.role, 'agent_switch'), isNull(messages.rewindAt)),+ eq(messages.role, 'context_rebuild'),+ ),+ afterClear,),- afterClear,- ))+ ).orderBy(desc(messages.createdAt), desc(messageRowid)).limit(1);if (!boundary) return;@@ -1668,14 +1697,16 @@ export async function markLatestAgentHandoffConsumed(sessionId: string): Promiseawait updateAgentSwitchBoundaryContent(sessionId, boundary.clientId, nextContent);return;}- await getDbClient().drizzle- .update(messages)+ await getDbClient()+ .drizzle.update(messages).set({ content: safeStringify(nextContent) })- .where(and(- eq(messages.sessionId, sessionId),- eq(messages.clientId, boundary.clientId),- eq(messages.role, 'context_rebuild'),- ));+ .where(+ and(+ eq(messages.sessionId, sessionId),+ eq(messages.clientId, boundary.clientId),+ eq(messages.role, 'context_rebuild'),+ ),+ );}/** 原子事务提交后只读并广播边界新行,不做第二次写入。 */@@ -1687,10 +1718,7 @@ export async function rebroadcastAgentSwitchBoundary(const [row] = await db.select().from(messages)- .where(and(- eq(messages.sessionId, sessionId),- eq(messages.clientId, boundaryClientId),- ))+ .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, boundaryClientId))).limit(1);if (row) broadcastMessageRow(sessionId, messageToCamel(row));}diff --git a/apps/desktop/src/main/localDb/mapper.ts b/apps/desktop/src/main/localDb/mapper.tsindex ef3b234698..9662fc9140 100644--- a/apps/desktop/src/main/localDb/mapper.ts+++ b/apps/desktop/src/main/localDb/mapper.ts@@ -15,7 +15,16 @@ import type {scheduleRuns,} from './schema';// 类型从 renderer 共享(仅 type-only import,运行时无 import 副作用)-import type { Session, SessionStatus, Message, MessageRole, AgentKind, AgentMeta, OrcaRole, WorkspaceKind } from '../../renderer/lib/ccAgent.types';+import type {+ Session,+ SessionStatus,+ Message,+ MessageRole,+ AgentKind,+ AgentMeta,+ OrcaRole,+ WorkspaceKind,+} from '../../renderer/lib/ccAgent.types';import type { Effort, PermissionMode } from '../../renderer/lib/userPreferences.types';// scheduler 模块的纯类型/接口契约——零运行时依赖(package main 是 src/index.ts,// type-only import 编译期消除)。@@ -32,6 +41,14 @@ 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,+ normalizeRegionalMoney,+ regionalizeLegacyUsd,+ regionalizeUsd,+ zeroRegionalMoney,+} from '../../shared/regionalMoney.js';type SessionRow = typeof sessions.$inferSelect;type SessionInsert = typeof sessions.$inferInsert;@@ -98,9 +115,7 @@ export function extractMessagePreview(if (isSyntheticTriggerText(text)) return null;const collapsed = text.replace(/\s+/g, ' ').trim();if (!collapsed) return null;- return collapsed.length > PREVIEW_MAX_CHARS- ? collapsed.slice(0, PREVIEW_MAX_CHARS)- : collapsed;+ return collapsed.length > PREVIEW_MAX_CHARS ? collapsed.slice(0, PREVIEW_MAX_CHARS) : collapsed;}/**@@ -110,6 +125,23 @@ export function extractMessagePreview(* 出口处补一个空字符串 `userId: ''`,避免类型缺失;上层消费如果需要用户 id 应该读 AuthContext。*/export function sessionToCamel(row: SessionRowWithCount): Session {+ const legacyMoney =+ row.totalCostUsd > 0 ? regionalizeLegacyUsd(row.totalCostUsd, CURRENT_CINDY_REGION) : undefined;+ const currentMoney =+ row.totalCostCurrency && row.totalCostAmount > 0+ ? normalizeRegionalMoney({+ amount: row.totalCostAmount,+ currency: row.totalCostCurrency,+ approximate: row.totalCostIsApproximate,+ kind: 'actual-cost',+ })+ : undefined;+ const totalMoney =+ legacyMoney && currentMoney+ ? legacyMoney.currency === currentMoney.currency+ ? addRegionalMoney([legacyMoney, currentMoney])+ : currentMoney+ : (currentMoney ?? legacyMoney ?? zeroRegionalMoney(CURRENT_CINDY_REGION));return {id: row.id,userId: '', // 本地 db 已按 user 隔离,无需冗余存储@@ -124,6 +156,7 @@ export function sessionToCamel(row: SessionRowWithCount): Session {sdkSessionId: row.sdkSessionId,totalTokenUsage: row.totalTokenUsage,totalCostUsd: row.totalCostUsd,+ totalMoney,contextTokens: row.contextTokens,contextWindow: row.contextWindow,fastMode: !!row.fastMode,@@ -201,29 +234,31 @@ export function normalizeRemoteHostId(raw: string | null | undefined): string |/** Session create 入口字段映射。生成 timestamps + 默认值由调用方保证必填。 */export function sessionCreateToRow(id: string,- body: {- id?: string;- workingDir?: string;- workspaceKind?: WorkspaceKind;- model?: string;- effort?: string;- permissionMode?: string;- fastMode?: boolean;- planModeEnabled?: boolean;- agentKind?: AgentKind;- orcaRole?: OrcaRole | null;- parentSessionId?: string | null;- forkedAtMessageId?: string | null;- extraDirs?: string[];- /** Remote codex (P2): 远端 SSH host alias; null/undefined = 本地。 */- remoteHostId?: string | null;- /**- * per-session 来源(供应商)显式选择,落盘 sessions.provider_id(与 update 同列)。- * null/undefined = 不显式选,跟随该 agent 的原生默认路由(no-break)。草稿态首次- * create 由 renderer 透传用户在草稿里选定的来源,使新会话首个请求就走对供应商。- */- providerId?: string | null;- } | undefined,+ body:+ | {+ id?: string;+ workingDir?: string;+ workspaceKind?: WorkspaceKind;+ model?: string;+ effort?: string;+ permissionMode?: string;+ fastMode?: boolean;+ planModeEnabled?: boolean;+ agentKind?: AgentKind;+ orcaRole?: OrcaRole | null;+ parentSessionId?: string | null;+ forkedAtMessageId?: string | null;+ extraDirs?: string[];+ /** Remote codex (P2): 远端 SSH host alias; null/undefined = 本地。 */+ remoteHostId?: string | null;+ /**+ * per-session 来源(供应商)显式选择,落盘 sessions.provider_id(与 update 同列)。+ * null/undefined = 不显式选,跟随该 agent 的原生默认路由(no-break)。草稿态首次+ * create 由 renderer 透传用户在草稿里选定的来源,使新会话首个请求就走对供应商。+ */+ providerId?: string | null;+ }+ | undefined,now: number,): SessionInsert {return {@@ -233,8 +268,7 @@ export function sessionCreateToRow(workspaceKind: body?.workspaceKind ?? 'project',model: body?.model ?? 'claude-sonnet-4-6',effort: (body?.effort as SessionInsert['effort']) ?? 'high',- permissionMode:- (body?.permissionMode as SessionInsert['permissionMode']) ?? 'ask',+ permissionMode: (body?.permissionMode as SessionInsert['permissionMode']) ?? 'ask',status: 'active',sdkSessionId: null,totalTokenUsage: 0,@@ -298,7 +332,8 @@ export function sessionPatchToRow(): Partial<SessionInsert> {const out: Partial<SessionInsert> = {};if (patch.title !== undefined) out.title = patch.title;- if (patch.workingDir !== undefined) out.workingDir = normalizeWorkingDirForStorage(patch.workingDir);+ if (patch.workingDir !== undefined)+ out.workingDir = normalizeWorkingDirForStorage(patch.workingDir);if (patch.workspaceKind !== undefined) out.workspaceKind = patch.workspaceKind;if (patch.model !== undefined) out.model = patch.model;if (patch.effort !== undefined) out.effort = patch.effort as SessionInsert['effort'];@@ -440,13 +475,7 @@ function parseScriptConfig(raw: string | null): ScriptExecutionConfig | undefine}}-const PRE_RUN_HOOK_STATUSES = new Set([- 'passed',- 'skipped',- 'failed',- 'timed_out',- 'aborted',-]);+const PRE_RUN_HOOK_STATUSES = new Set(['passed', 'skipped', 'failed', 'timed_out', 'aborted']);const PRE_RUN_HOOK_DECISIONS = new Set(['run', 'skip', 'block']);/** 兼容损坏/手工写入的 JSON:非法结果不应让整个运行历史加载失败。 */@@ -457,7 +486,8 @@ function parsePreRunHookResult(raw: string | null): PreRunHookRunResult | undefiif (!PRE_RUN_HOOK_STATUSES.has(String(value.status))) return undefined;if (!PRE_RUN_HOOK_DECISIONS.has(String(value.decision))) return undefined;if (value.exitCode !== null && typeof value.exitCode !== 'number') return undefined;- if (typeof value.durationMs !== 'number' || !Number.isFinite(value.durationMs)) return undefined;+ if (typeof value.durationMs !== 'number' || !Number.isFinite(value.durationMs))+ return undefined;if (typeof value.stdout !== 'string' || typeof value.stderr !== 'string') return undefined;if (typeof value.stdoutTruncated !== 'boolean' ||@@ -592,8 +622,7 @@ export function schedulePatchToRow(patch: Partial<Schedule>): Partial<ScheduleInif (hasKey(patch, 'executionMode')) out.executionMode = patch.executionMode ?? 'agent';if (hasKey(patch, 'scriptConfig')) out.scriptConfig = serializeScriptConfig(patch.scriptConfig);if (hasKey(patch, 'source')) out.source = patch.source ?? 'user';- if (hasKey(patch, 'projectConfigId'))- out.projectConfigId = patch.projectConfigId ?? null;+ if (hasKey(patch, 'projectConfigId')) out.projectConfigId = patch.projectConfigId ?? null;if (hasKey(patch, 'kind')) out.kind = patch.kind as ScheduleInsert['kind'];if (hasKey(patch, 'cronExpr')) out.cronExpr = patch.cronExpr as string;if (hasKey(patch, 'timezone')) out.timezone = patch.timezone as string;@@ -601,22 +630,17 @@ export function schedulePatchToRow(patch: Partial<Schedule>): Partial<ScheduleInif (hasKey(patch, 'manual')) out.manual = patch.manual as boolean;// intervalMs:undefined → null(清空,回退到 cron 槽位语义);数字原样写if (hasKey(patch, 'intervalMs')) out.intervalMs = patch.intervalMs ?? null;- if (hasKey(patch, 'agentKind'))- out.agentKind = patch.agentKind as ScheduleInsert['agentKind'];+ if (hasKey(patch, 'agentKind')) out.agentKind = patch.agentKind as ScheduleInsert['agentKind'];if (hasKey(patch, 'model')) out.model = patch.model ?? null;if (hasKey(patch, 'providerId')) out.providerId = patch.providerId ?? null;- if (hasKey(patch, 'effort'))- out.effort = (patch.effort as ScheduleInsert['effort']) ?? null;+ if (hasKey(patch, 'effort')) out.effort = (patch.effort as ScheduleInsert['effort']) ?? null;if (hasKey(patch, 'fastMode')) out.fastMode = !!patch.fastMode;if (hasKey(patch, 'workspaceKind')) out.workspaceKind = patch.workspaceKind ?? 'project';if (hasKey(patch, 'workingDir')) out.workingDir = patch.workingDir ?? null;if (hasKey(patch, 'useWorktree')) out.useWorktree = patch.useWorktree as boolean;- if (hasKey(patch, 'targetSessionId'))- out.targetSessionId = patch.targetSessionId ?? null;- if (hasKey(patch, 'persistentSession'))- out.persistentSession = !!patch.persistentSession;- if (hasKey(patch, 'silentWhenIdle'))- out.silentWhenIdle = !!patch.silentWhenIdle;+ if (hasKey(patch, 'targetSessionId')) out.targetSessionId = patch.targetSessionId ?? null;+ if (hasKey(patch, 'persistentSession')) out.persistentSession = !!patch.persistentSession;+ if (hasKey(patch, 'silentWhenIdle')) out.silentWhenIdle = !!patch.silentWhenIdle;if (hasKey(patch, 'preRunHook')) {// 嵌套对象整体替换(同 notify):出现即两列同写;undefined = 关闭 hook,双列清 NULLout.preRunHookCommand = patch.preRunHook?.command ?? null;@@ -633,8 +657,7 @@ export function schedulePatchToRow(patch: Partial<Schedule>): Partial<ScheduleInif (hasKey(patch, 'updatedAt')) out.updatedAt = patch.updatedAt as number;// 三个可空时间戳:undefined 也要写成 null(业务语义"清空 nextFireAt")if (hasKey(patch, 'lastFiredAt')) out.lastFiredAt = patch.lastFiredAt ?? null;- if (hasKey(patch, 'lastFinishedAt'))- out.lastFinishedAt = patch.lastFinishedAt ?? null;+ if (hasKey(patch, 'lastFinishedAt')) out.lastFinishedAt = patch.lastFinishedAt ?? null;if (hasKey(patch, 'nextFireAt')) out.nextFireAt = patch.nextFireAt ?? null;if (hasKey(patch, 'expireAt')) out.expireAt = patch.expireAt ?? null;return out;@@ -668,6 +691,45 @@ export function projectAutomationConsentToRow(/** ScheduleRun 行 → 内存对象。 */export function scheduleRunToCamel(row: ScheduleRunRow): ScheduleRun {+ const legacyCost =+ row.costUsd > 0 ? regionalizeLegacyUsd(row.costUsd, CURRENT_CINDY_REGION) : undefined;+ const currentCost =+ row.costCurrency && row.costAmount > 0+ ? normalizeRegionalMoney({+ amount: row.costAmount,+ currency: row.costCurrency,+ approximate: row.costIsApproximate,+ kind: 'actual-cost',+ })+ : undefined;+ const costMoney =+ legacyCost && currentCost+ ? legacyCost.currency === currentCost.currency+ ? addRegionalMoney([legacyCost, currentCost])+ : currentCost+ : (currentCost ?? legacyCost ?? zeroRegionalMoney(CURRENT_CINDY_REGION));+ const legacyEstimate =+ row.estimatedValueUsd > 0+ ? regionalizeUsd(row.estimatedValueUsd, CURRENT_CINDY_REGION, 'legacy-usd', 'value-estimate')+ : undefined;+ const currentEstimate =+ row.costCurrency && row.estimatedValueAmount > 0+ ? normalizeRegionalMoney({+ amount: row.estimatedValueAmount,+ currency: row.costCurrency,+ approximate: true,+ kind: 'value-estimate',+ estimateReasons: ['subscription-value'],+ })+ : undefined;+ const estimatedValueMoney =+ legacyEstimate && currentEstimate+ ? legacyEstimate.currency === currentEstimate.currency+ ? addRegionalMoney([legacyEstimate, currentEstimate])+ : currentEstimate+ : (currentEstimate ??+ legacyEstimate ??+ zeroRegionalMoney(CURRENT_CINDY_REGION, 'value-estimate'));return {id: row.id,scheduleId: row.scheduleId,@@ -678,6 +740,8 @@ export function scheduleRunToCamel(row: ScheduleRunRow): ScheduleRun {errorMsg: row.errorMsg ?? undefined,costUsd: row.costUsd,estimatedValueUsd: row.estimatedValueUsd,+ costMoney,+ estimatedValueMoney,costAttribution: row.costAttribution,resultText: row.resultText ?? undefined,preRunHookResult: parsePreRunHookResult(row.preRunHookResult),@@ -698,6 +762,10 @@ export function scheduleRunCreateToRow(r: ScheduleRun): ScheduleRunInsert {errorMsg: r.errorMsg ?? null,costUsd: r.costUsd ?? 0,estimatedValueUsd: r.estimatedValueUsd ?? 0,+ costAmount: r.costMoney?.amount ?? 0,+ estimatedValueAmount: r.estimatedValueMoney?.amount ?? 0,+ costCurrency: r.costMoney?.currency ?? r.estimatedValueMoney?.currency ?? null,+ costIsApproximate: r.costMoney?.approximate ?? false,// 新写入的 run 从创建起就带 runId origin;迁移前旧行由列默认值标为 legacy。costAttribution: r.costAttribution ?? 'exact',resultText: r.resultText ?? null,@@ -712,9 +780,7 @@ export function scheduleRunCreateToRow(r: ScheduleRun): ScheduleRunInsert {* 与 schedulePatchToRow 同样的 hasOwn 语义:key 不存在 = 不更新;* key 存在但 undefined = 写 NULL。*/-export function scheduleRunPatchToRow(- patch: Partial<ScheduleRun>,-): Partial<ScheduleRunInsert> {+export function scheduleRunPatchToRow(patch: Partial<ScheduleRun>): Partial<ScheduleRunInsert> {const out: Partial<ScheduleRunInsert> = {};if (hasKey(patch, 'scheduleId')) out.scheduleId = patch.scheduleId as string;// 空字符串等同 null:FireResult.sessionId 是 required string,但 runner@@ -722,21 +788,27 @@ export function scheduleRunPatchToRow(if (hasKey(patch, 'sessionId')) out.sessionId = patch.sessionId || null;if (hasKey(patch, 'firedAt')) out.firedAt = patch.firedAt as number;if (hasKey(patch, 'finishedAt')) out.finishedAt = patch.finishedAt ?? null;- if (hasKey(patch, 'status'))- out.status = patch.status as ScheduleRunInsert['status'];+ if (hasKey(patch, 'status')) out.status = patch.status as ScheduleRunInsert['status'];if (hasKey(patch, 'errorMsg')) out.errorMsg = patch.errorMsg ?? null;if (hasKey(patch, 'costUsd')) out.costUsd = patch.costUsd ?? 0;if (hasKey(patch, 'estimatedValueUsd')) {out.estimatedValueUsd = patch.estimatedValueUsd ?? 0;}+ if (hasKey(patch, 'costMoney')) {+ out.costAmount = patch.costMoney?.amount ?? 0;+ out.costCurrency = patch.costMoney?.currency ?? null;+ out.costIsApproximate = patch.costMoney?.approximate ?? false;+ }+ if (hasKey(patch, 'estimatedValueMoney')) {+ out.estimatedValueAmount = patch.estimatedValueMoney?.amount ?? 0;+ out.costCurrency = patch.estimatedValueMoney?.currency ?? out.costCurrency ?? null;+ }if (hasKey(patch, 'costAttribution')) {out.costAttribution = patch.costAttribution ?? 'legacy';}if (hasKey(patch, 'resultText')) out.resultText = patch.resultText ?? null;if (hasKey(patch, 'preRunHookResult')) {- out.preRunHookResult = patch.preRunHookResult- ? JSON.stringify(patch.preRunHookResult)- : null;+ out.preRunHookResult = patch.preRunHookResult ? JSON.stringify(patch.preRunHookResult) : null;}if (hasKey(patch, 'readAt')) out.readAt = patch.readAt ?? null;if (hasKey(patch, 'heartbeatAt')) out.heartbeatAt = patch.heartbeatAt ?? null;diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.tsindex d56289c114..703686b96c 100644--- a/apps/desktop/src/main/localDb/schema.ts+++ b/apps/desktop/src/main/localDb/schema.ts@@ -62,6 +62,14 @@ export const sessions = sqliteTable(sdkSessionId: text('sdk_session_id'),totalTokenUsage: integer('total_token_usage').notNull().default(0),totalCostUsd: real('total_cost_usd').notNull().default(0),+ /** 新版区域金额;legacy total_cost_usd 仍保留为历史 USD 事实。 */+ totalCostAmount: real('total_cost_amount').notNull().default(0),+ totalCostCurrency: text('total_cost_currency', { enum: ['CNY', 'USD'] }),+ totalCostIsApproximate: integer('total_cost_is_approximate', {+ mode: 'boolean',+ })+ .notNull()+ .default(false),contextTokens: integer('context_tokens').notNull().default(0),contextWindow: integer('context_window').notNull().default(0),fastMode: integer('fast_mode', { mode: 'boolean' }).notNull().default(false),@@ -764,6 +772,13 @@ export const scheduleRuns = sqliteTable(costUsd: real('cost_usd').notNull().default(0),/** 单次 run 的订阅 token 估算价值,不计入真实账单。 */estimatedValueUsd: real('estimated_value_usd').notNull().default(0),+ /** 新版区域真实费用与订阅价值;旧 USD 列只做历史兼容。 */+ costAmount: real('cost_amount').notNull().default(0),+ estimatedValueAmount: real('estimated_value_amount').notNull().default(0),+ costCurrency: text('cost_currency', { enum: ['CNY', 'USD'] }),+ costIsApproximate: integer('cost_is_approximate', { mode: 'boolean' })+ .notNull()+ .default(false),/*** zero 表示已确认零费用;unavailable 表示 agent run 尚无可靠计价;legacy* 表示迁移前数据缺少 runId,不能精确拆分。SQLite 无 CHECK,无需 migration。@@ -902,6 +917,11 @@ export const dailySpend = sqliteTable('daily_spend', {day: text('day').primaryKey(),/** 当日累计 USD (real)。SDK 单 turn 的 cost 通常是小数 (如 0.0391)。 */costUsd: real('cost_usd').notNull().default(0),+ costAmount: real('cost_amount').notNull().default(0),+ costCurrency: text('cost_currency', { enum: ['CNY', 'USD'] }),+ costIsApproximate: integer('cost_is_approximate', { mode: 'boolean' })+ .notNull()+ .default(false),/** 最后一次更新的 unix ms。 */updatedAt: integer('updated_at').notNull(),});@@ -931,6 +951,11 @@ export const dailyModelUsage = sqliteTable(model: text('model').notNull(),/** 当日该模型累计 USD (仅 claude-code 实报; codex 恒 0)。 */costUsd: real('cost_usd').notNull().default(0),+ costAmount: real('cost_amount').notNull().default(0),+ costCurrency: text('cost_currency', { enum: ['CNY', 'USD'] }),+ costIsApproximate: integer('cost_is_approximate', { mode: 'boolean' })+ .notNull()+ .default(false),inputTokens: integer('input_tokens').notNull().default(0),outputTokens: integer('output_tokens').notNull().default(0),cacheReadTokens: integer('cache_read_tokens').notNull().default(0),diff --git a/apps/desktop/src/main/localDb/worker/__tests__/sessionImportShareTx.test.ts b/apps/desktop/src/main/localDb/worker/__tests__/sessionImportShareTx.test.tsindex 502c8f23b4..9746fa2de8 100644--- a/apps/desktop/src/main/localDb/worker/__tests__/sessionImportShareTx.test.ts+++ b/apps/desktop/src/main/localDb/worker/__tests__/sessionImportShareTx.test.ts@@ -20,6 +20,9 @@ function createTables(db: Database.Database): void {sdk_session_id TEXT,total_token_usage INTEGER NOT NULL DEFAULT 0,total_cost_usd REAL NOT NULL DEFAULT 0,+ total_cost_amount REAL NOT NULL DEFAULT 0,+ total_cost_currency TEXT,+ total_cost_is_approximate INTEGER NOT NULL DEFAULT 0,context_tokens INTEGER NOT NULL DEFAULT 0,context_window INTEGER NOT NULL DEFAULT 0,fast_mode INTEGER NOT NULL DEFAULT 0,@@ -133,7 +136,9 @@ describe('tx session.importShare', () => {it('inserts session and all messages (including rewound rows) atomically', () => {const result = tx(db, validArgs());expect(result).toEqual({ messageCount: 3 });- const session = db.prepare('SELECT * FROM sessions WHERE id = ?').get('new-session-1') as Record<string, unknown>;+ const session = db+ .prepare('SELECT * FROM sessions WHERE id = ?')+ .get('new-session-1') as Record<string, unknown>;expect(session.source).toBe('shared');expect(session.sdk_session_id).toBe('sdk-abc');expect(session.provider_id).toBe('prov-1');@@ -141,8 +146,14 @@ describe('tx session.importShare', () => {expect(session.fast_mode).toBe(0);expect(session.cleared_at).toBe(1700000000050);const messages = db- .prepare('SELECT id, rewind_at, agent_kind FROM messages WHERE session_id = ? ORDER BY created_at')- .all('new-session-1') as Array<{ id: string; rewind_at: number | null; agent_kind: string | null }>;+ .prepare(+ 'SELECT id, rewind_at, agent_kind FROM messages WHERE session_id = ? ORDER BY created_at',+ )+ .all('new-session-1') as Array<{+ id: string;+ rewind_at: number | null;+ agent_kind: string | null;+ }>;expect(messages.map((m) => m.id)).toEqual(['m1', 'm2', 'm3']);expect(messages.map((m) => m.agent_kind)).toEqual(['cc', 'codex', null]);expect(messages[2].rewind_at).toBe(1700000000400);diff --git a/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.tsindex ac01405646..12547627fb 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts@@ -6,6 +6,8 @@ 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';function createMakerStub(methods: Partial<Maker>): Maker {return methods as Maker;@@ -327,10 +329,13 @@ describe('maker usage IPC handlers', () => {models: [],streak: { current: 0, longest: 0 },totals: {- today: 0,- last30Days: 0,- last30DaysWithEstimatedValue: 0,- last30DaysEstimatedValue: 0,+ today: zeroRegionalMoney(CURRENT_CINDY_REGION),+ last30Days: zeroRegionalMoney(CURRENT_CINDY_REGION),+ last30DaysWithEstimatedValue: zeroRegionalMoney(CURRENT_CINDY_REGION),+ last30DaysEstimatedValue: zeroRegionalMoney(+ CURRENT_CINDY_REGION,+ 'value-estimate',+ ),todayTokens: 0,last30DaysTokens: 0,},@@ -382,17 +387,44 @@ describe('maker usage IPC handlers', () => {expect(triggerClaudeAccountUsageRefresh).toHaveBeenCalledWith(true);});- it('reads model pricing through injected host dependency', async () => {+ it('keeps the legacy device-link pricing channel flat and USD-only', async () => {const harness = new IpcHarness();const pricing = {- 'claude-sonnet-4-6': { inputUsdPerMtok: 3, outputUsdPerMtok: 15 },+ xd: {+ 'claude-sonnet-4-6': {+ providerId: 'xd',+ modelId: 'claude-sonnet-4-6',+ currency: 'USD',+ source: 'gateway',+ approximate: false,+ inputPerMtok: 3,+ outputPerMtok: 15,+ cacheReadPerMtok: 0.3,+ },+ 'claude-opus-4-6': {+ providerId: 'xd',+ modelId: 'claude-opus-4-6',+ currency: 'CNY',+ source: 'gateway',+ approximate: false,+ inputPerMtok: 5,+ outputPerMtok: 25,+ },+ },};const readModelPricing = vi.fn().mockResolvedValue(pricing);registerMakerUsageHandlers(harness, makeUsageDeps({ readModelPricing }));- await expect(harness.invoke(MAKER_INVOKE.USAGE_MODEL_PRICING)).resolves.toEqual(pricing);- expect(readModelPricing).toHaveBeenCalledTimes(1);+ await expect(harness.invoke(MAKER_INVOKE.USAGE_MODEL_PRICING)).resolves.toEqual({+ 'claude-sonnet-4-6': {+ inputUsdPerMtok: 3,+ outputUsdPerMtok: 15,+ cacheReadUsdPerMtok: 0.3,+ },+ });+ await expect(harness.invoke(MAKER_INVOKE.USAGE_MODEL_PRICING_V2)).resolves.toEqual(pricing);+ expect(readModelPricing).toHaveBeenCalledTimes(2);});it('reads Codex reset credits and consumes only a UUID offer key', async () => {diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.tsindex cebaa78f27..3072d47d5c 100644--- a/apps/desktop/src/main/maker-ipc/channels.ts+++ b/apps/desktop/src/main/maker-ipc/channels.ts@@ -226,8 +226,10 @@ export const MAKER_INVOKE = {USAGE_CODEX_RATE_LIMIT_RESET: 'maker:usage:codex-rate-limit-reset',// Claude 订阅账号余量 (oauth/usage 端点 + unified headers 双源, cached-first) — 状态栏 chip 用USAGE_CLAUDE_SUBSCRIPTION: 'maker:usage:claude-subscription',- // 模型单价表 (LiteLLM /model_group/info, main 端内存 + 磁盘缓存, 启动预热) — 模型选择器 hover tooltip 用+ // device-link v1 模型单价表:保留 modelId → USD/Mtok 扁平形状,旧控制端继续可读。USAGE_MODEL_PRICING: 'maker:usage:model-pricing',+ // Desktop renderer v2:provider-scoped + currency-aware 模型单价表。+ USAGE_MODEL_PRICING_V2: 'maker:usage:model-pricing-v2',// 用量历史聚合 (daily_spend + daily_model_usage, main 侧算好 streak/异常/估算) — 首页仪表盘用USAGE_HISTORY: 'maker:usage:history',// Memory 控制 — 走 Maker.{getAgentMemoryStatus/setAgentMemory/resetAgentMemory},diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex f07655367c..0af623fd75 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -224,11 +224,14 @@ import {import { recordModelMismatchOnMessage } from '../modelMismatchBroadcaster.js';import { detectClaudeModelMismatch } from '../../shared/modelMismatch.js';import { triggerClaudeAccountUsageRefresh } from '../usage/claudeAccountUsage.js';-import { getCodexBudgetEffectiveCostMultiplier, getCodexSubscriptionValuePrice, getModelPricing, getModelPricingForModel, getSubscriptionDirectValuePrice } from '../usage/modelPricing.js';+import { getCodexBudgetEffectiveCostMultiplier, getCodexSubscriptionValuePrice, getModelPriceQuote, getModelPricing, getModelPricingForModel, getSubscriptionDirectValuePrice } from '../usage/modelPricing.js';import { computeModelUsageDeltas, type ModelUsageCumulative, type ModelUsageDeltaEntry } from '../usage/modelUsageDelta.js';import { claudeSubscriptionUsageModelKey, codexApiUsageModelKey, codexSubscriptionUsageModelKey } from '../usage/usageHistory.js';-import { buildClaudeTurnUsageDetails, computeGatewayTurnCost, estimateClaudeSubscriptionTurnValue, isAnthropicModel, normalizeModelIdForPricing, resolveClaudeTurnCostSinks } from '../usage/turnCostCalculator.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 { triggerClaudeSubscriptionUsageRefresh, triggerCodexAccountUsageRefresh } from './usage.js';import {rebroadcastCodexTodayUsage,@@ -2569,27 +2572,6 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// 由同一份解析结果驱动。价格表走 main 端内存 + 磁盘缓存, stale 快返并后台刷新。const deltas = modelUsageDeltas;void (async () => {- // 纯 Anthropic 轮 (绝大多数 Claude Code 会话) resolveTurnCost 一律信任 SDK、- // 不看 gateway 价 —— 此时跳过 getModelPricing() 的网络往返, 避免冷缓存 / 离线- // 时把 cost 记账拖到 fetch 超时 (最长 5s), 甚至在等待期间 app 退出而丢整轮账- // (rule 10: 不在记账热路径加阻塞)。只要有一个非 Anthropic 模型就照常拉价。- // 订阅直连模型(chatgpt/ / xai/)同样跳过 —— resolveTurnCost 对它们恒 cost 0 不查价,- // 价值估算走静态参考表;带前缀 id 也不可能出现在 gateway 价表里,拉了纯属白等超时。- const gatewayPricingModels = Array.from(new Set(- deltas- .map((d) => normalizeModelIdForPricing(d.model))- .filter((model) => !isAnthropicModel(model) && !isSubscriptionDirectModel(model)),- ));- let pricing = null;- for (const model of gatewayPricingModels) {- pricing = await getModelPricingForModel(model);- }- const { turnTotalUsd, perModel } = resolveClaudeTurnCostSinks(deltas, pricing);- // 订阅轮判定对齐 proxy 实际路由(远端恒走网关, 排除):- // - 显式选 Anthropic 供应商 → 订阅直连;- // - 默认路由 (providerId=null) → 优先使用 proxy 按请求记录的会话实际路由;- // 未观察到时再回落到「当前无网关 key」启发式。显式选了其它自定义供应商- // 的会话不打订阅标记(cost 语义未知)。const sessionProviderForBilling = getSessionProvider(session.id);const observedClaudeRoute =sessionProviderForBilling == null ? readClaudeSessionRoute(session.id) : null;@@ -2602,6 +2584,31 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void: !readClaudeApiKey())));+ const billingRoute: BillingRoute = session.remoteHostId+ ? 'unknown'+ : isClaudeSubscriptionSession+ ? 'subscription'+ : sessionProviderForBilling === 'xd' || observedClaudeRoute === 'gateway'+ ? 'xd-gateway'+ : sessionProviderForBilling+ ? 'provider-api'+ : 'unknown';+ const pricing =+ billingRoute === 'xd-gateway'+ ? await getModelPricingForModel(+ 'xd',+ normalizeModelIdForPricing(deltas[0]?.model),+ )+ : await getModelPricing();+ const { turnMoney, perModel } = resolveClaudeTurnCostSinks(+ deltas,+ pricing,+ {+ providerId: sessionProviderForBilling,+ billingRoute,+ region: CURRENT_CINDY_REGION,+ },+ );// 按模型记账 (首页仪表盘"按模型拆分"): 写归一化裸 id, 与 codex 行 / 价格表对齐。// 订阅轮打 #billing=subscription 标记(Claude 订阅:Anthropic 模型 + cost=0),// 或 bridge 订阅轮(chatgpt// xai/ 前缀,source==='subscription');两类均需触发@@ -2610,14 +2617,14 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidlet hasSubscriptionValueRow = false;for (const m of perModel) {const isClaudeSubscriptionValueRow =- isClaudeSubscriptionSession && m.costUsd === 0 && isAnthropicModel(m.model);+ isClaudeSubscriptionSession && !m.money && isAnthropicModel(m.model);const isBridgeSubscriptionRow =m.source === 'subscription' && isSubscriptionDirectModel(m.model);if (isClaudeSubscriptionValueRow || isBridgeSubscriptionRow) hasSubscriptionValueRow = true;modelUsageWrites.push(recordModelTurnUsage({agentKind: 'claude-code',model: isClaudeSubscriptionValueRow ? claudeSubscriptionUsageModelKey(m.model) : m.model,- costUsdDelta: m.costUsd,+ money: m.money,inputTokensDelta: m.deltas.inputTokens,outputTokensDelta: m.deltas.outputTokens,cacheReadTokensDelta: m.deltas.cacheReadTokens,@@ -2627,28 +2634,25 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// 纯订阅轮 (turnTotalUsd=0) 不走 recordTurnSpend, 没有任何 usage push ——// 等模型行落库后重广播今日 spend 快照, 通知已打开的首页仪表盘刷新// (对齐 codex 订阅轮的 rebroadcastCodexTodayUsage)。- if (hasSubscriptionValueRow && turnTotalUsd === 0) {+ if (hasSubscriptionValueRow && !turnMoney) {void Promise.allSettled(modelUsageWrites).then(() => rebroadcastTodaySpend());}- if (turnTotalUsd > 0) {+ if (turnMoney && turnMoney.amount > 0) {// 保留 #216 的 token/cache 明细随费用落库 (MessageActionBar tooltip)。// deltas 非空 → buildClaudeTurnUsageDetails 用 deltas 里的 model, fallbackModel 不取用。// 传 perModel → 落「按模型成本明细」(含 subagent 跑的模型, 如 Haiku)。const turnUsageDetails = buildClaudeTurnUsageDetails(doneData?.usage, deltas, 'unknown', perModel);- recordTurnSpend(turnTotalUsd);- // session 级别的"终身 cost"持久化到 sessions.total_cost_usd 并广播。- recordSessionTurnSpend(session.id, turnTotalUsd);- // per-message 维度: 把本 turn 费用 + 明细挂到该轮最后一条 assistant 的 agent_meta。- if (turnAssistantPersistId) {- void recordTurnCostOnMessage({- sessionId: session.id,- clientId: turnAssistantPersistId,- costUsd: turnTotalUsd,- isEstimate: false,- turnUsageDetails,- turnOrigin: event.turnOrigin,- });- }+ recordTurnSpend(turnMoney);+ recordSessionTurnSpend(session.id, turnMoney);+ // per-message 维度优先挂 assistant;纯 tool turn 则按 scheduler runId 直接归因。+ const changedScheduleId = await recordSchedulerTurnCost({+ sessionId: session.id,+ clientId: turnAssistantPersistId,+ money: turnMoney,+ turnUsageDetails,+ turnOrigin: event.turnOrigin,+ });+ if (changedScheduleId) broadcastSchedulerChanged(changedScheduleId);} else if (turnAssistantPersistId) {// 纯订阅轮(无真实计费)的「本轮价值」估算,挂到消息(isEstimate:true,chip 的// "本会话价值"由 useSessionEstimatedValue 汇总),不进 daily_spend /@@ -2659,26 +2663,39 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// (纯 Anthropic 轮 pricing 为 null → 家族牌价兜底表,不为估值发起网络请求)。// 混合轮(真实计费 > 0)走上面的真实分支,订阅部分不另挂估算 —— 一条消息只有一个// cost 字段,真实计费优先;订阅 token 明细仍在 turnUsageDetails.perModelCost 里。- let turnEstimatedValueUsd = 0;+ const estimatedValues: RegionalMoney[] = [];for (const m of perModel) {if (m.source !== 'subscription') continue;- const value = computeGatewayTurnCost(m.deltas, getSubscriptionDirectValuePrice(m.model));- if (value != null) turnEstimatedValueUsd += value;+ const quote = getSubscriptionDirectValuePrice(m.model);+ const value = computePriceQuoteTurnMoney(+ m.deltas,+ quote+ ? regionalizeModelPriceQuote(quote, CURRENT_CINDY_REGION)+ : undefined,+ );+ if (value?.amount) estimatedValues.push(value);}if (isClaudeSubscriptionSession) {- const claudeEstimated = estimateClaudeSubscriptionTurnValue(perModel, pricing);- if (claudeEstimated != null && claudeEstimated > 0) turnEstimatedValueUsd += claudeEstimated;+ const claudeEstimated = estimateClaudeSubscriptionTurnValue(+ perModel,+ CURRENT_CINDY_REGION,+ );+ if (claudeEstimated?.amount) estimatedValues.push(claudeEstimated);}- if (turnEstimatedValueUsd > 0) {+ const turnEstimatedValue =+ estimatedValues.length > 0+ ? addRegionalMoney(estimatedValues)+ : null;+ if (turnEstimatedValue && turnEstimatedValue.amount > 0) {const turnUsageDetails = buildClaudeTurnUsageDetails(doneData?.usage, deltas, 'unknown', perModel);- void recordTurnCostOnMessage({+ const changedScheduleId = await recordSchedulerTurnCost({sessionId: session.id,clientId: turnAssistantPersistId,- costUsd: turnEstimatedValueUsd,- isEstimate: true,+ money: turnEstimatedValue,turnUsageDetails,turnOrigin: event.turnOrigin,});+ if (changedScheduleId) broadcastSchedulerChanged(changedScheduleId);}}})();@@ -2688,31 +2705,44 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidconst rawDelta = Math.max(0, cumulative - prevReportedCost);if (rawDelta > 0) {void (async () => {- let multiplier = 1;let resolvedModel = 'unknown';try {const model = await modelPromise;resolvedModel = model;- multiplier = getCodexBudgetEffectiveCostMultiplier(model);} catch { /* non-fatal: 保留 SDK 原始 cost */ }// 订阅直连轮(chatgpt/ / xai/)走窄兜底时: 真实计费恒 0, 不写 daily_spend /// sessions.total_cost_usd(与主路径 resolveTurnCost 的 subscription gate 同口径,// 避免把订阅 SDK 自报 cost 误记进计费)。if (isSubscriptionDirectModel(resolvedModel)) return;- const delta = rawDelta * multiplier;+ const providerId = getSessionProvider(session.id);+ const observedRoute =+ providerId == null ? readClaudeSessionRoute(session.id) : null;+ const route: BillingRoute = session.remoteHostId+ ? 'unknown'+ : providerId === 'anthropic' || observedRoute === 'subscription'+ ? 'subscription'+ : providerId === 'xd' || observedRoute === 'gateway'+ ? 'xd-gateway'+ : providerId+ ? 'provider-api'+ : 'unknown';+ if (route === 'subscription' || route === 'xd-gateway') return;+ const money = regionalizeUsd(+ rawDelta * getCodexBudgetEffectiveCostMultiplier(resolvedModel),+ CURRENT_CINDY_REGION,+ 'fixed-fx',+ );const turnUsageDetails = buildClaudeTurnUsageDetails(doneData?.usage, undefined, resolvedModel);- recordTurnSpend(delta);- recordSessionTurnSpend(session.id, delta);- if (turnAssistantPersistId) {- void recordTurnCostOnMessage({- sessionId: session.id,- clientId: turnAssistantPersistId,- costUsd: delta,- isEstimate: false,- turnUsageDetails,- turnOrigin: event.turnOrigin,- });- }+ recordTurnSpend(money);+ recordSessionTurnSpend(session.id, money);+ const changedScheduleId = await recordSchedulerTurnCost({+ sessionId: session.id,+ clientId: turnAssistantPersistId,+ money,+ turnUsageDetails,+ turnOrigin: event.turnOrigin,+ });+ if (changedScheduleId) broadcastSchedulerChanged(changedScheduleId);})();}}@@ -2791,7 +2821,6 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidawait recordModelTurnUsage({agentKind: 'codex',model: modelUsageKey,- costUsdDelta: 0,inputTokensDelta: promptTokens,outputTokensDelta: completionTokens,cacheReadTokensDelta: cachedTokens,@@ -2811,18 +2840,23 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void? await getModelPricing(): isSubscriptionValue? null- : await getModelPricingForModel(pricingModel);+ : await getModelPricingForModel('xd', pricingModel);const price = isCodexXaiProviderRoute? getSubscriptionDirectValuePrice(pricingModel): isSubscriptionValue? getCodexSubscriptionValuePrice(pricingModel, pricing)- : pricing?.[pricingModel];- const cost = computeGatewayTurnCost(codexUsageToTokens(u), price);- if (!isSubscriptionValue && cost != null) {+ : getModelPriceQuote(pricing, 'xd', pricingModel);+ const money = computePriceQuoteTurnMoney(+ codexUsageToTokens(u),+ price+ ? regionalizeModelPriceQuote(price, CURRENT_CINDY_REGION)+ : undefined,+ );+ if (!isSubscriptionValue && money) {await recordModelTurnUsage({agentKind: 'codex',model: modelUsageKey,- costUsdDelta: cost,+ money,inputTokensDelta: 0,outputTokensDelta: 0,cacheReadTokensDelta: 0,@@ -2836,18 +2870,15 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidcacheCreateTokens: 0,model: turnModel,});- if (cost != null && cost > 0) {+ if (money && money.amount > 0) {if (!isSubscriptionValue) {- void recordTurnSpend(cost);- void recordSessionTurnSpend(session.id, cost);+ void recordTurnSpend(money);+ void recordSessionTurnSpend(session.id, money);}- }- if (cost != null) {const changedScheduleId = await recordSchedulerTurnCost({sessionId: session.id,clientId: turnAssistantPersistId,- costUsd: cost,- isEstimate: isSubscriptionValue,+ money,turnUsageDetails,turnOrigin: event.turnOrigin,});diff --git a/apps/desktop/src/main/maker-ipc/usageHandlers.ts b/apps/desktop/src/main/maker-ipc/usageHandlers.tsindex 8d79402243..aa9e465841 100644--- a/apps/desktop/src/main/maker-ipc/usageHandlers.ts+++ b/apps/desktop/src/main/maker-ipc/usageHandlers.ts@@ -20,6 +20,39 @@ import { requireString, throwIpcError } from '../utils/ipcValidate.js';import { MAKER_INVOKE } from './channels.js';import type { IpcHandlerRegistry } from './ipcHandlerRegistry.js';+export interface LegacyUsdModelPrice {+ inputUsdPerMtok: number;+ outputUsdPerMtok: number;+ cacheReadUsdPerMtok?: number;+ cacheCreateUsdPerMtok?: number;+}++export type LegacyUsdModelPricingMap = Record<string, LegacyUsdModelPrice>;++/**+ * device-link v1 兼容投影。旧控制端只能表达扁平 USD 价格,因此只投影真实 USD quote;+ * CNY 不能反算或写进 *Usd,旧端按既有“无价隐藏”语义降级。+ */+export function toLegacyUsdModelPricing(+ pricing: ModelPricingMap | null,+): LegacyUsdModelPricingMap | null {+ const out: LegacyUsdModelPricingMap = {};+ for (const [modelId, quote] of Object.entries(pricing?.xd ?? {})) {+ if (quote.currency !== 'USD') continue;+ out[modelId] = {+ inputUsdPerMtok: quote.inputPerMtok,+ outputUsdPerMtok: quote.outputPerMtok,+ ...(quote.cacheReadPerMtok !== undefined+ ? { cacheReadUsdPerMtok: quote.cacheReadPerMtok }+ : {}),+ ...(quote.cacheCreatePerMtok !== undefined+ ? { cacheCreateUsdPerMtok: quote.cacheCreatePerMtok }+ : {}),+ };+ }+ return Object.keys(out).length > 0 ? out : null;+}+/** usage handler 需要的 host-level 查询与刷新能力。 */export interface MakerUsageHandlerDeps {readAgentTodayUsage(agentKind: AgentKind): Promise<AgentTodayUsage>;@@ -89,8 +122,13 @@ export function registerMakerUsageHandlers(return await deps.readClaudeSubscriptionUsageSnapshot();});- // 模型单价表 — 失败时 null, renderer 据此隐藏价格 tooltip。+ // device-link v1:保留旧扁平 USD 形状,不能把 CNY 伪装成 *Usd。registry.handle(MAKER_INVOKE.USAGE_MODEL_PRICING, async () => {+ return toLegacyUsdModelPricing(await deps.readModelPricing());+ });++ // Desktop renderer v2:provider-scoped、带币种和约值语义的完整价格目录。+ registry.handle(MAKER_INVOKE.USAGE_MODEL_PRICING_V2, async () => {return await deps.readModelPricing();});diff --git a/apps/desktop/src/main/model-access/__tests__/devMetaOverlay.test.ts b/apps/desktop/src/main/model-access/__tests__/devMetaOverlay.test.tsindex d89ff0e1a6..e3a47e5e96 100644--- a/apps/desktop/src/main/model-access/__tests__/devMetaOverlay.test.ts+++ b/apps/desktop/src/main/model-access/__tests__/devMetaOverlay.test.ts@@ -61,6 +61,45 @@ describe('overlayCindyModelMeta', () => {expect(m.contextWindow).toBe(999_000);});+ it('本地元数据覆盖和撤销都保留 Gateway 价格字段', () => {+ const priced: ModelAccessGatewayModel = {+ ...SERVER_MODEL,+ costDiscount: 0.2,+ inputCostPerToken: 0.000003,+ outputCostPerToken: 0.000015,+ tieredPricing: [+ {+ range: [0, 200_000],+ inputCostPerToken: 0.000003,+ outputCostPerToken: 0.000015,+ },+ ],+ };+ const [overridden] = overlayCindyModelMeta(+ [priced],+ envelope({ 'gpt-5.5': LOCAL_ENTRY }),+ );+ const [revoked] = overlayCindyModelMeta(+ [priced],+ envelope({ 'gpt-5.5': null }),+ );++ for (const model of [overridden, revoked]) {+ expect(model).toMatchObject({+ costDiscount: 0.2,+ inputCostPerToken: 0.000003,+ outputCostPerToken: 0.000015,+ tieredPricing: [+ {+ range: [0, 200_000],+ inputCostPerToken: 0.000003,+ outputCostPerToken: 0.000015,+ },+ ],+ });+ }+ });+it('icon(展示图标)可经本地条目覆盖 / 撤销:字符串透传,非字符串条目整条拒绝', () => {const [withIcon] = overlayCindyModelMeta([SERVER_MODEL],diff --git a/apps/desktop/src/main/model-access/devMetaOverlay.ts b/apps/desktop/src/main/model-access/devMetaOverlay.tsindex c2eb06b5cd..2d6e58b4c8 100644--- a/apps/desktop/src/main/model-access/devMetaOverlay.ts+++ b/apps/desktop/src/main/model-access/devMetaOverlay.ts@@ -57,6 +57,28 @@ function isPlainObject(v: unknown): v is Record<string, unknown> {return typeof v === 'object' && v !== null && !Array.isArray(v);}+/**+ * 去掉可由 dev 元数据覆盖的展示、归属和能力字段,保留 token 上限和全部+ * Gateway 价格。这样本地 overlay 或 null 撤销登记都不会把同快照里的价格静默丢掉。+ */+function gatewayFields(m: ModelAccessGatewayModel): ModelAccessGatewayModel {+ const {+ agents: _agents,+ name: _name,+ group: _group,+ description: _description,+ icon: _icon,+ efforts: _efforts,+ defaultEffort: _defaultEffort,+ sortOrder: _sortOrder,+ supportsFastMode: _supportsFastMode,+ defaultEnabled: _defaultEnabled,+ perAgent: _perAgent,+ ...fields+ } = m;+ return fields;+}+/** 校验并拷贝 override 形态的能力字段(基线与 perAgent 共用);非法返回原因。 */function readOverrideFields(o: Record<string, unknown>,@@ -141,14 +163,11 @@ function parseEntry(raw: unknown): { meta: MetaEntry } | { reason: string } {/** 以本地条目重建服务端下发条目(网关权威字段保留,元数据字段整体替换)。 */function rebuildModel(m: ModelAccessGatewayModel, meta: MetaEntry): ModelAccessGatewayModel {return {- id: m.id,+ ...gatewayFields(m),// 网关上报的 token 上限权威;本地 contextWindow 仅在服务端条目缺失时兜底(同服务端规则)。- ...(m.contextWindow !== undefined- ? { contextWindow: m.contextWindow }- : meta.contextWindow !== undefined- ? { contextWindow: meta.contextWindow }- : {}),- ...(m.maxOutputTokens !== undefined ? { maxOutputTokens: m.maxOutputTokens } : {}),+ ...(m.contextWindow === undefined && meta.contextWindow !== undefined+ ? { contextWindow: meta.contextWindow }+ : {}),agents: meta.agents,name: meta.name,...(meta.group ? { group: meta.group } : {}),@@ -187,11 +206,7 @@ export function overlayCindyModelMeta(if (raw === null) {// 撤销登记:剥掉全部元数据,只留网关权威字段(客户端回落确定性默认)。revoked += 1;- return {- id: m.id,- ...(m.contextWindow !== undefined ? { contextWindow: m.contextWindow } : {}),- ...(m.maxOutputTokens !== undefined ? { maxOutputTokens: m.maxOutputTokens } : {}),- };+ return gatewayFields(m);}const parsed = parseEntry(raw);if ('reason' in parsed) {diff --git a/apps/desktop/src/main/model-access/index.ts b/apps/desktop/src/main/model-access/index.tsindex 6132fbf3fe..c6a1188993 100644--- a/apps/desktop/src/main/model-access/index.ts+++ b/apps/desktop/src/main/model-access/index.ts@@ -14,6 +14,10 @@ import {import { getActiveCatalog, setXdGatewayModels } from '../maker-host/active-catalog.js';import { isDev } from '../manifestService.js';import { overlayCindyModelMeta } from './devMetaOverlay.js';+import {+ replaceGatewayModelPricing,+ trackGatewayModelPricingSync,+} from '../usage/modelPricing.js';import { throwIpcError } from '../utils/ipcValidate.js';import {MODEL_ACCESS_STATUS_CHANNEL,@@ -108,8 +112,7 @@ function broadcastStatus(status: ModelAccessStatus): void {// ─── XD 网关模型目录同步(网关为准,目录仅补元数据)────────────────────// 凭据同步成功后从 model-access-server 拉 GET /models(AIGateway /model-groups// 的 mode=chat 投影),整体重建 xd 供应商的模型列表(active-catalog-// setXdGatewayModels)。拉取失败或返回空列表时立即清空 XD 模型:产品目录与历史快照-// 都不能证明模型当前可用,不得继续显示。+// setXdGatewayModels)。拉取失败保留最后一次完整成功快照;成功空列表同时清空模型和价格。let modelsSyncInflight: Promise<void> | null = null;/** 在途目录请求所属的认证世代。 */@@ -125,6 +128,10 @@ let authGeneration = 0;let lastAuthUserId: string | null = null;function applyGatewayModels(models: ModelAccessGatewayModel[]): void {+ // 同一次 /models 响应先建立 provider-scoped 价格投影,再做仅影响展示元数据的+ // dev overlay。空成功响应会同时清空模型和价格;请求失败不会调用本函数,+ // 因而保留上一份完整成功快照。+ replaceGatewayModelPricing(models);// dev:本地目录文件(catalog/providers.json)的 cindyModelMeta 段覆盖服务端下发的// 元数据,改本地 json + 重启即可自测,无需发 OSS / 等服务端热加载;只覆盖同 id,// 清单成员资格仍以网关为准。packaged 不走此分支(语义见 devMetaOverlay.ts)。@@ -184,6 +191,7 @@ function scheduleModelsSync(): void {.finally(() => {modelsSyncInflight = null;});+ trackGatewayModelPricingSync(modelsSyncInflight);}let syncInstance: CredentialsSync | null = null;@@ -299,5 +307,5 @@ export function resetModelAccessForTest(): void {modelsSyncRerunQueued = false;authGeneration = 0;lastAuthUserId = null;- setXdGatewayModels([]);+ applyGatewayModels([]);}diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runCostLedger.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runCostLedger.test.tsindex 6a8821e215..2b522196d8 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/runCostLedger.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/runCostLedger.test.ts@@ -12,13 +12,35 @@ function meta(runId: string, costUsd: number, isEstimate = false): Record<string};}+function structuredMeta(+ runId: string,+ amount: number,+ isEstimate = false,+): Record<string, unknown> {+ return {+ origin: { kind: 'scheduler', scheduleId: 'schedule-1', runId },+ turnCost: {+ amount,+ currency: 'CNY',+ approximate: isEstimate,+ kind: isEstimate ? 'value-estimate' : 'actual-cost',+ ...(isEstimate ? { estimateReasons: ['subscription-value'] } : {}),+ },+ turnCostIsEstimate: isEstimate,+ };+}+describe('computeScheduleRunCostDeltas', () => {- it('首次写入真实费用时累计到对应 run', () => {- expect(computeScheduleRunCostDeltas({}, meta('run-1', 0.42))).toEqual([{- runId: 'run-1',- costUsdDelta: 0.42,- estimatedValueUsdDelta: 0,- }]);+ it('旧 USD 真实费用按当前 CN 区域投影后累计到对应 run', () => {+ expect(computeScheduleRunCostDeltas({}, meta('run-1', 0.42))).toEqual([+ {+ runId: 'run-1',+ costAmountDelta: 2.814,+ estimatedValueAmountDelta: 0,+ currency: 'CNY',+ approximate: true,+ },+ ]);});it('相同消息重放时不重复累计', () => {@@ -27,17 +49,49 @@ describe('computeScheduleRunCostDeltas', () => {});it('估算值转为真实费用时在两栏之间搬移', () => {- expect(computeScheduleRunCostDeltas(meta('run-1', 0.42, true), meta('run-1', 0.4))).toEqual([{+ const [delta] = computeScheduleRunCostDeltas(meta('run-1', 0.42, true), meta('run-1', 0.4));+ expect(delta).toMatchObject({runId: 'run-1',- costUsdDelta: 0.4,- estimatedValueUsdDelta: -0.42,- }]);+ currency: 'CNY',+ approximate: true,+ });+ expect(delta.costAmountDelta).toBeCloseTo(2.68);+ expect(delta.estimatedValueAmountDelta).toBeCloseTo(-2.814);});it('归因 runId 修正时从旧 run 扣除并写入新 run', () => {expect(computeScheduleRunCostDeltas(meta('run-old', 0.42), meta('run-new', 0.42))).toEqual([- { runId: 'run-old', costUsdDelta: -0.42, estimatedValueUsdDelta: 0 },- { runId: 'run-new', costUsdDelta: 0.42, estimatedValueUsdDelta: 0 },+ {+ runId: 'run-old',+ costAmountDelta: -2.814,+ estimatedValueAmountDelta: 0,+ currency: 'CNY',+ approximate: false,+ },+ {+ runId: 'run-new',+ costAmountDelta: 2.814,+ estimatedValueAmountDelta: 0,+ currency: 'CNY',+ approximate: true,+ },+ ]);+ });++ it('结构化 CN 金额原样累计,订阅估值不污染真实费用约值标记', () => {+ expect(+ computeScheduleRunCostDeltas(+ structuredMeta('run-1', 0.29, true),+ structuredMeta('run-1', 0.42),+ ),+ ).toEqual([+ {+ runId: 'run-1',+ costAmountDelta: 0.42,+ estimatedValueAmountDelta: -0.29,+ currency: 'CNY',+ approximate: false,+ },]);});});@@ -46,8 +100,12 @@ describe('recordScheduleRunCostDirect', () => {it('忽略低于消息账本阈值的正费用', async () => {await expect(recordScheduleRunCostDirect({runId: 'run-near-zero',- costUsd: 1e-12,- isEstimate: false,+ money: {+ amount: 1e-12,+ currency: 'USD',+ approximate: false,+ kind: 'actual-cost',+ },})).resolves.toBeNull();});@@ -84,8 +142,12 @@ describe('recordScheduleRunCostDirect', () => {try {await expect(recordScheduleRunCostDirect({runId: 'run-raced-delete',- costUsd: 0.42,- isEstimate: false,+ money: {+ amount: 0.42,+ currency: 'USD',+ approximate: false,+ kind: 'actual-cost',+ },})).resolves.toBeNull();} finally {clearCurrentDbClient(dbClient);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.tsindex 90544bbd40..1ef403de5e 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@@ -17,6 +17,41 @@ import { clearCurrentDbClient, setCurrentDbClient } from '../../localDb/client/cimport { recordScheduleRunCostDirect } from '../runCostLedger';import { DrizzleScheduleStorage, type SchedulerDrizzleDb } from '../storage';+function actualMoneyFromLegacyUsd(amountUsd: number) {+ return {+ amount: expect.closeTo(amountUsd * 6.7, 10),+ currency: 'CNY' as const,+ approximate: true,+ 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,+ approximate: true,+ kind: 'value-estimate' as const,+ estimateReasons: ['fixed-fx', 'legacy-usd', 'subscription-value'] as const,+ };+}++const ZERO_ACTUAL_MONEY = {+ amount: 0,+ currency: 'CNY' as const,+ approximate: false,+ kind: 'actual-cost' as const,+};++const ZERO_ESTIMATED_MONEY = {+ amount: 0,+ currency: 'CNY' as const,+ approximate: true,+ kind: 'value-estimate' as const,+ estimateReasons: ['subscription-value'] as const,+};+function baseSchedule(overrides: Partial<Schedule> = {}): Schedule {return {id: 'sch-1',@@ -66,7 +101,10 @@ const SCHEDULER_DDL = [user_send_at INTEGER,created_at INTEGER NOT NULL DEFAULT 0,updated_at INTEGER NOT NULL DEFAULT 0,- total_cost_usd REAL+ total_cost_usd REAL,+ total_cost_amount REAL NOT NULL DEFAULT 0,+ total_cost_currency TEXT,+ total_cost_is_approximate INTEGER NOT NULL DEFAULT 0)`,`@@ -138,6 +176,10 @@ const SCHEDULER_DDL = [error_msg TEXT,cost_usd REAL NOT NULL DEFAULT 0,estimated_value_usd REAL NOT NULL DEFAULT 0,+ 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,cost_attribution TEXT NOT NULL DEFAULT 'legacy',result_text TEXT,pre_run_hook_result TEXT,@@ -209,6 +251,8 @@ describe('DrizzleScheduleStorage (in-memory)', () => {...run,costUsd: 0,estimatedValueUsd: 0,+ costMoney: ZERO_ACTUAL_MONEY,+ estimatedValueMoney: ZERO_ESTIMATED_MONEY,costAttribution: 'exact',});const completed = await harness.storage.updateRun(run.id, {@@ -264,8 +308,10 @@ describe('DrizzleScheduleStorage (in-memory)', () => {await expect(harness.storage.listRuns(schedule.id)).resolves.toEqual([expect.objectContaining({id: 'run-exact',- costUsd: 0.42,- estimatedValueUsd: 0.29,+ costUsd: 0,+ estimatedValueUsd: 0,+ costMoney: actualMoneyFromLegacyUsd(0.42),+ estimatedValueMoney: estimatedMoneyFromLegacyUsd(0.29),costAttribution: 'exact',}),]);@@ -321,19 +367,28 @@ describe('DrizzleScheduleStorage (in-memory)', () => {(await harness.storage.listCostSummaries()).map((summary) => [summary.scheduleId, summary]),);expect(summaries.get('sch-a')).toMatchObject({- totalCostUsd: 0.4,- totalEstimatedValueUsd: 0,+ totalMoney: actualMoneyFromLegacyUsd(0.4),+ totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,});expect(summaries.get('sch-b')).toMatchObject({- totalCostUsd: 0.2,- totalEstimatedValueUsd: 0,+ totalMoney: actualMoneyFromLegacyUsd(0.2),+ totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,});expect(await harness.storage.listRuns('sch-a')).toEqual([- expect.objectContaining({ id: 'run-a2', costUsd: 0.3 }),- expect.objectContaining({ id: 'run-a1', costUsd: 0.1 }),+ expect.objectContaining({+ id: 'run-a2',+ costMoney: actualMoneyFromLegacyUsd(0.3),+ }),+ expect.objectContaining({+ id: 'run-a1',+ costMoney: actualMoneyFromLegacyUsd(0.1),+ }),]);expect(await harness.storage.listRuns('sch-b')).toEqual([- expect.objectContaining({ id: 'run-b1', costUsd: 0.2 }),+ expect.objectContaining({+ id: 'run-b1',+ costMoney: actualMoneyFromLegacyUsd(0.2),+ }),]);} finally {harness.close();@@ -641,14 +696,14 @@ describe('DrizzleScheduleStorage (in-memory)', () => {await expect(harness.storage.listCostSummaries()).resolves.toEqual([{scheduleId: schedule.id,- totalCostUsd: 0.75,- totalEstimatedValueUsd: 9.99,+ totalMoney: actualMoneyFromLegacyUsd(0.75),+ totalEstimatedValueMoney: estimatedMoneyFromLegacyUsd(9.99),sessionCount: 1,sessions: [{sessionId: 'sess-bound',- totalCostUsd: 0.75,- totalEstimatedValueUsd: 9.99,+ totalMoney: actualMoneyFromLegacyUsd(0.75),+ totalEstimatedValueMoney: estimatedMoneyFromLegacyUsd(9.99),},],},@@ -687,14 +742,14 @@ describe('DrizzleScheduleStorage (in-memory)', () => {await expect(harness.storage.listCostSummaries()).resolves.toEqual([{scheduleId: schedule.id,- totalCostUsd: 0,- totalEstimatedValueUsd: 0.29,+ totalMoney: ZERO_ACTUAL_MONEY,+ totalEstimatedValueMoney: estimatedMoneyFromLegacyUsd(0.29),sessionCount: 1,sessions: [{sessionId: 'sess-subscription',- totalCostUsd: 0,- totalEstimatedValueUsd: 0.29,+ totalMoney: ZERO_ACTUAL_MONEY,+ totalEstimatedValueMoney: estimatedMoneyFromLegacyUsd(0.29),},],},@@ -733,14 +788,14 @@ describe('DrizzleScheduleStorage (in-memory)', () => {await expect(harness.storage.listCostSummaries()).resolves.toEqual([{scheduleId: schedule.id,- totalCostUsd: 0.42,- totalEstimatedValueUsd: 0,+ totalMoney: actualMoneyFromLegacyUsd(0.42),+ totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,sessionCount: 1,sessions: [{sessionId: 'sess-api',- totalCostUsd: 0.42,- totalEstimatedValueUsd: 0,+ totalMoney: actualMoneyFromLegacyUsd(0.42),+ totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,},],},@@ -773,14 +828,14 @@ describe('DrizzleScheduleStorage (in-memory)', () => {await expect(harness.storage.listCostSummaries()).resolves.toEqual([{scheduleId: schedule.id,- totalCostUsd: 0.42,- totalEstimatedValueUsd: 0,+ totalMoney: actualMoneyFromLegacyUsd(0.42),+ totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,sessionCount: 1,sessions: [{sessionId: 'sess-direct',- totalCostUsd: 0.42,- totalEstimatedValueUsd: 0,+ totalMoney: actualMoneyFromLegacyUsd(0.42),+ totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,},],},@@ -808,26 +863,27 @@ describe('DrizzleScheduleStorage (in-memory)', () => {await recordScheduleRunCostDirect({runId: 'run-direct-segments',- costUsd: 0.42,- isEstimate: false,+ money: { amount: 0.42, currency: 'CNY', approximate: false, kind: 'actual-cost' },});await recordScheduleRunCostDirect({runId: 'run-direct-segments',- costUsd: 0.18,- isEstimate: false,+ money: { amount: 0.18, currency: 'CNY', approximate: false, kind: 'actual-cost' },});await recordScheduleRunCostDirect({runId: 'run-direct-segments',- costUsd: 0,- isEstimate: false,+ money: { amount: 0, currency: 'CNY', approximate: false, kind: 'actual-cost' },});await expect(harness.storage.listRuns(schedule.id)).resolves.toEqual([expect.objectContaining({id: 'run-direct-segments',- costUsd: 0.6,- estimatedValueUsd: 0,- costAttribution: 'exact',+ costMoney: {+ amount: expect.closeTo(0.6, 10),+ currency: 'CNY',+ approximate: false,+ kind: 'actual-cost',+ },+ costAttribution: 'direct',}),]);} finally {@@ -867,14 +923,14 @@ describe('DrizzleScheduleStorage (in-memory)', () => {await expect(harness.storage.listCostSummaries()).resolves.toEqual([{scheduleId: schedule.id,- totalCostUsd: 0.6,- totalEstimatedValueUsd: 0,+ totalMoney: actualMoneyFromLegacyUsd(0.6),+ totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,sessionCount: 1,sessions: [{sessionId: 'sess-mixed-ledger',- totalCostUsd: 0.6,- totalEstimatedValueUsd: 0,+ totalMoney: actualMoneyFromLegacyUsd(0.6),+ totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,},],},@@ -906,8 +962,13 @@ describe('DrizzleScheduleStorage (in-memory)', () => {setCurrentDbClient(dbClient, 'test-user');await recordScheduleRunCostDirect({runId: 'run-direct-only-snapshot',- costUsd: 0.6,- isEstimate: false,+ money: {+ amount: 4.02,+ currency: 'CNY',+ approximate: true,+ kind: 'actual-cost',+ estimateReasons: ['fixed-fx'],+ },});harness.db.run(sql`INSERT INTO messages (id, client_id, session_id, role, content, agent_meta, created_at)@@ -921,22 +982,21 @@ describe('DrizzleScheduleStorage (in-memory)', () => {await expect(harness.storage.listRuns(schedule.id)).resolves.toEqual([expect.objectContaining({id: 'run-direct-only-snapshot',- costUsd: 1,- estimatedValueUsd: 0,+ costMoney: actualMoneyFromLegacyUsd(1),costAttribution: 'exact',}),]);await expect(harness.storage.listCostSummaries()).resolves.toEqual([{scheduleId: schedule.id,- totalCostUsd: 1,- totalEstimatedValueUsd: 0,+ totalMoney: actualMoneyFromLegacyUsd(1),+ totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,sessionCount: 1,sessions: [{sessionId: 'sess-direct-only',- totalCostUsd: 1,- totalEstimatedValueUsd: 0,+ totalMoney: actualMoneyFromLegacyUsd(1),+ totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,},],},@@ -969,15 +1029,15 @@ describe('DrizzleScheduleStorage (in-memory)', () => {await expect(harness.storage.listCostSummaries()).resolves.toEqual([{scheduleId: schedule.id,- totalCostUsd: 0,- totalEstimatedValueUsd: 0,+ totalMoney: ZERO_ACTUAL_MONEY,+ totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,hasUnavailableCost: true,sessionCount: 1,sessions: [{sessionId: 'sess-unavailable',- totalCostUsd: 0,- totalEstimatedValueUsd: 0,+ totalMoney: ZERO_ACTUAL_MONEY,+ totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,},],},@@ -1004,8 +1064,8 @@ describe('DrizzleScheduleStorage (in-memory)', () => {await expect(harness.storage.listCostSummaries()).resolves.toEqual([{scheduleId: schedule.id,- totalCostUsd: 0,- totalEstimatedValueUsd: 0,+ totalMoney: ZERO_ACTUAL_MONEY,+ totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,sessionCount: 0,sessions: [],},@@ -1038,6 +1098,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),('manual-user', 'manual-user', 'sess-legacy', 'user', '{}', NULL, 55),('manual-assistant', 'manual-assistant', 'sess-legacy', 'assistant', '{}', '{"turnCostUsd":2}', 60)`);@@ -1045,14 +1106,20 @@ describe('DrizzleScheduleStorage (in-memory)', () => {await expect(harness.storage.listCostSummaries()).resolves.toEqual([{scheduleId: schedule.id,- totalCostUsd: 2.25,- totalEstimatedValueUsd: 0,+ totalMoney: {+ ...actualMoneyFromLegacyUsd(2.25),+ amount: expect.closeTo(2.25 * 6.7 + 5, 10),+ },+ totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,sessionCount: 1,sessions: [{sessionId: 'sess-legacy',- totalCostUsd: 2.25,- totalEstimatedValueUsd: 0,+ totalMoney: {+ ...actualMoneyFromLegacyUsd(2.25),+ amount: expect.closeTo(2.25 * 6.7 + 5, 10),+ },+ totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,},],},@@ -1090,14 +1157,14 @@ describe('DrizzleScheduleStorage (in-memory)', () => {await expect(harness.storage.listCostSummaries()).resolves.toEqual([{scheduleId: schedule.id,- totalCostUsd: 1.5,- totalEstimatedValueUsd: 0,+ totalMoney: actualMoneyFromLegacyUsd(1.5),+ totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,sessionCount: 1,sessions: [{sessionId: 'sess-unlinked',- totalCostUsd: 1.5,- totalEstimatedValueUsd: 0,+ totalMoney: actualMoneyFromLegacyUsd(1.5),+ totalEstimatedValueMoney: ZERO_ESTIMATED_MONEY,},],},@@ -1144,9 +1211,7 @@ describe('DrizzleScheduleStorage (in-memory)', () => {)`);- expect(- (await harness.storage.listRuns(oldSchedule.id)).map((run) => run.sessionId),- ).toEqual(+ expect((await harness.storage.listRuns(oldSchedule.id)).map((run) => run.sessionId)).toEqual(expect.arrayContaining(['sess-old-retained', 'sess-old-archived', 'sess-old-deleted']),);diff --git a/apps/desktop/src/main/scheduler-host/__tests__/storage.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/storage.test.tsindex 8326cd612e..97614fd542 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/storage.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/storage.test.ts@@ -141,9 +141,7 @@ describe('scheduleToCamel', () => {describe('scheduleCreateToRow', () => {it('拆 notify 为两列', () => {- const row = scheduleCreateToRow(- baseSchedule({ notify: { desktop: false, feishu: true } }),- );+ const row = scheduleCreateToRow(baseSchedule({ notify: { desktop: false, feishu: true } }));expect(row.notifyDesktop).toBe(false);expect(row.notifyFeishu).toBe(true);// 嵌套字段不直接出现在行里@@ -232,9 +230,7 @@ describe('schedulePatchToRow — patch 清空语义', () => {// 2. ScheduleRun mapper// ============================================================================-function baseRunRow(- overrides: Partial<ScheduleRunRowLike> = {},-): ScheduleRunRowLike {+function baseRunRow(overrides: Partial<ScheduleRunRowLike> = {}): ScheduleRunRowLike {return {id: 'run-1',scheduleId: 'sch-1',@@ -245,6 +241,10 @@ function baseRunRow(errorMsg: null,costUsd: 0,estimatedValueUsd: 0,+ costAmount: 0,+ estimatedValueAmount: 0,+ costCurrency: null,+ costIsApproximate: false,costAttribution: 'legacy',resultText: null,preRunHookResult: null,@@ -293,7 +293,52 @@ describe('scheduleRunToCamel / scheduleRunCreateToRow', () => {};const row = scheduleRunCreateToRow(original);const back = scheduleRunToCamel(row as ScheduleRunRowLike);- expect(back).toEqual(original);+ expect(back).toEqual({+ ...original,+ costMoney: {+ amount: 2.814,+ currency: 'CNY',+ approximate: true,+ kind: 'actual-cost',+ estimateReasons: ['fixed-fx', 'legacy-usd'],+ },+ estimatedValueMoney: {+ amount: expect.closeTo(1.273, 10),+ currency: 'CNY',+ approximate: true,+ kind: 'value-estimate',+ estimateReasons: ['fixed-fx', 'legacy-usd', 'subscription-value'],+ },+ });+ });++ it('订阅估值不写入真实费用的约值标记', () => {+ const run: ScheduleRun = {+ id: 'run-money',+ scheduleId: 'sch-1',+ firedAt: 1,+ status: 'success',+ costMoney: {+ amount: 0.42,+ currency: 'CNY',+ approximate: false,+ kind: 'actual-cost',+ },+ estimatedValueMoney: {+ amount: 0.19,+ currency: 'CNY',+ approximate: true,+ kind: 'value-estimate',+ estimateReasons: ['subscription-value'],+ },+ };+ expect(scheduleRunCreateToRow(run).costIsApproximate).toBe(false);+ expect(+ 'costIsApproximate' in+ scheduleRunPatchToRow({+ estimatedValueMoney: run.estimatedValueMoney,+ }),+ ).toBe(false);});it('可选字段 undefined → null 写入', () => {diff --git a/apps/desktop/src/main/scheduler-host/runCostLedger.ts b/apps/desktop/src/main/scheduler-host/runCostLedger.tsindex ea59a289ba..4722db9e14 100644--- a/apps/desktop/src/main/scheduler-host/runCostLedger.ts+++ b/apps/desktop/src/main/scheduler-host/runCostLedger.ts@@ -9,19 +9,25 @@ 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';interface RunCostEntry {runId: string;- costUsd: number;- estimatedValueUsd: number;+ costAmount: number;+ estimatedValueAmount: number;+ currency: 'CNY' | 'USD';+ approximate: boolean;}const MIN_RECORDED_COST_USD = 1e-10;export interface ScheduleRunCostDelta {runId: string;- costUsdDelta: number;- estimatedValueUsdDelta: number;+ costAmountDelta: number;+ estimatedValueAmountDelta: number;+ currency: 'CNY' | 'USD';+ approximate: boolean;}function finitePositive(value: unknown): number {@@ -38,10 +44,22 @@ function runCostEntry(meta: Record<string, unknown>): RunCostEntry | null {const runId = parsedOrigin.runId;if (typeof runId !== 'string' || runId.length === 0) return null;- const amount = finitePositive(meta.turnCostUsd);- return meta.turnCostIsEstimate === true- ? { runId, costUsd: 0, estimatedValueUsd: amount }- : { runId, costUsd: amount, estimatedValueUsd: 0 };+ const money =+ normalizeRegionalMoney(meta.turnCost) ??+ (finitePositive(meta.turnCostUsd) > 0+ ? regionalizeLegacyUsd(finitePositive(meta.turnCostUsd), CURRENT_CINDY_REGION)+ : undefined);+ if (!money || money.amount <= 0) return null;+ const isEstimate = meta.turnCostIsEstimate === true || money.kind === 'value-estimate';+ return {+ runId,+ costAmount: isEstimate ? 0 : money.amount,+ estimatedValueAmount: isEstimate ? money.amount : 0,+ currency: money.currency,+ // cost_is_approximate 只描述真实费用;订阅价值本身始终由+ // estimatedValueMoney 标成 value-estimate,不能污染真实费用。+ approximate: !isEstimate && money.approximate,+ };}/** 计算消息元数据变化对 run 聚合的幂等差值,最多影响旧/新两个 run。 */@@ -54,19 +72,27 @@ export function computeScheduleRunCostDeltas(if (!entry) return;const current = changes.get(entry.runId) ?? {runId: entry.runId,- costUsdDelta: 0,- estimatedValueUsdDelta: 0,+ costAmountDelta: 0,+ estimatedValueAmountDelta: 0,+ currency: entry.currency,+ approximate: false,};- current.costUsdDelta += direction * entry.costUsd;- current.estimatedValueUsdDelta += direction * entry.estimatedValueUsd;+ 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);};apply(runCostEntry(previous), -1);apply(runCostEntry(next), 1);return [...changes.values()].filter((change) =>- Math.abs(change.costUsdDelta) >= MIN_RECORDED_COST_USD ||- Math.abs(change.estimatedValueUsdDelta) >= MIN_RECORDED_COST_USD,+ Math.abs(change.costAmountDelta) >= MIN_RECORDED_COST_USD ||+ Math.abs(change.estimatedValueAmountDelta) >= MIN_RECORDED_COST_USD,);}@@ -86,15 +112,21 @@ export async function applyScheduleRunCostMetaChange(// keep the message ledger in agent_meta and let read paths add it;// otherwise a successful message update would make a later read// unable to tell whether the snapshot already contains that segment.- costUsd: sql<number>`CASE+ costAmount: sql<number>`CASEWHEN ${scheduleRuns.costAttribution} = 'direct'- THEN ${scheduleRuns.costUsd}- ELSE MAX(0, ${scheduleRuns.costUsd} + ${change.costUsdDelta})+ THEN ${scheduleRuns.costAmount}+ ELSE MAX(0, ${scheduleRuns.costAmount} + ${change.costAmountDelta})END`,- estimatedValueUsd: sql<number>`CASE+ estimatedValueAmount: sql<number>`CASEWHEN ${scheduleRuns.costAttribution} = 'direct'- THEN ${scheduleRuns.estimatedValueUsd}- ELSE MAX(0, ${scheduleRuns.estimatedValueUsd} + ${change.estimatedValueUsdDelta})+ THEN ${scheduleRuns.estimatedValueAmount}+ ELSE MAX(0, ${scheduleRuns.estimatedValueAmount} + ${change.estimatedValueAmountDelta})+ END`,+ costCurrency: change.currency,+ costIsApproximate: sql`CASE+ WHEN ${scheduleRuns.costAttribution} IN ('direct', 'mixed')+ THEN ${scheduleRuns.costIsApproximate} OR ${change.approximate ? 1 : 0}+ ELSE ${change.approximate ? 1 : 0}END`,costAttribution: sql<string>`CASEWHEN ${scheduleRuns.costAttribution} IN ('direct', 'mixed')@@ -115,31 +147,40 @@ export async function applyScheduleRunCostMetaChange(*/export async function recordScheduleRunCostDirect(args: {runId: string;- costUsd: number;- isEstimate: boolean;+ money: import('../../shared/regionalMoney.js').RegionalMoney;}): Promise<string | null> {- const { runId, costUsd, isEstimate } = args;- if (!runId || typeof costUsd !== 'number' || !Number.isFinite(costUsd) || costUsd < 0) {- return null;- }- const amount = finitePositive(costUsd);+ const { runId } = args;+ const money = normalizeRegionalMoney(args.money);+ if (!runId || !money) return null;+ const amount = finitePositive(money.amount);// Match the message ledger's delta threshold; a tiny positive residue must// not create a direct-only run segment or a misleading changed broadcast.- if (costUsd > 0 && amount === 0) return null;+ if (money.amount > 0 && amount === 0) return null;+ const isEstimate = money.kind === 'value-estimate';const db = getDbClient().drizzle;const [run] = await db- .select({ scheduleId: scheduleRuns.scheduleId })+ .select({+ scheduleId: scheduleRuns.scheduleId,+ costCurrency: scheduleRuns.costCurrency,+ }).from(scheduleRuns).where(eq(scheduleRuns.id, runId)).limit(1);if (!run) return null;+ if (run.costCurrency && run.costCurrency !== money.currency) {+ throw new Error('schedule run cost currency mismatch');+ }const result = await db.update(scheduleRuns).set({- costUsd: sql<number>`MAX(0, ${scheduleRuns.costUsd} + ${isEstimate ? 0 : amount})`,- estimatedValueUsd: sql<number>`MAX(0, ${scheduleRuns.estimatedValueUsd} + ${isEstimate ? amount : 0})`,+ 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 ${+ !isEstimate && money.approximate ? 1 : 0+ }`,// 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.diff --git a/apps/desktop/src/main/scheduler-host/storage.ts b/apps/desktop/src/main/scheduler-host/storage.tsindex 6bee2ae506..be7b9284bc 100644--- a/apps/desktop/src/main/scheduler-host/storage.ts+++ b/apps/desktop/src/main/scheduler-host/storage.ts@@ -30,6 +30,16 @@ import {scheduleRunCreateToRow,scheduleRunPatchToRow,} from '../localDb/mapper';+import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';+import {+ addRegionalMoney,+ asValueEstimateMoney,+ normalizeRegionalMoney,+ regionalCurrencyForRegion,+ regionalizeLegacyUsd,+ type RegionalMoney,+ zeroRegionalMoney,+} from '../../shared/regionalMoney.js';export type SchedulerDrizzleDb = BetterSQLite3Database<typeof schema>;@@ -49,8 +59,10 @@ export interface ScheduleSidebarIndexRun {export interface ScheduleCostSummary {scheduleId: string;- totalCostUsd: number;- totalEstimatedValueUsd: number;+ totalMoney: RegionalMoney;+ totalEstimatedValueMoney: RegionalMoney;+ totalCostUsd?: number;+ totalEstimatedValueUsd?: number;/** 至少一轮 agent run 无法得到可靠费用。 */hasUnavailableCost?: boolean;sessionCount: number;@@ -59,16 +71,45 @@ export interface ScheduleCostSummary {export interface ScheduleSessionCostSummary {sessionId: string;- totalCostUsd: number;- totalEstimatedValueUsd: number;+ totalMoney: RegionalMoney;+ totalEstimatedValueMoney: RegionalMoney;+ totalCostUsd?: number;+ totalEstimatedValueUsd?: number;+}++interface ScheduleMoneyValues {+ costValues: RegionalMoney[];+ estimatedValueValues: RegionalMoney[];}-interface ScheduleTurnCostState {- totalCostUsd: number;- totalEstimatedValueUsd: number;+interface ScheduleTurnCostState extends ScheduleMoneyValues {hasUnavailableCost: boolean;sessionIds: Set<string>;- sessionCosts: Map<string, { totalCostUsd: number; totalEstimatedValueUsd: number }>;+ sessionCosts: Map<string, ScheduleMoneyValues>;+}++function emptyScheduleMoneyValues(): ScheduleMoneyValues {+ return {+ costValues: [],+ estimatedValueValues: [],+ };+}++function emptyScheduleTurnCostState(): ScheduleTurnCostState {+ return {+ ...emptyScheduleMoneyValues(),+ hasUnavailableCost: false,+ sessionIds: new Set<string>(),+ sessionCosts: new Map<string, ScheduleMoneyValues>(),+ };+}++function addCompatibleRegionalMoney(+ values: readonly RegionalMoney[],+ currency: RegionalMoney['currency'] = regionalCurrencyForRegion(CURRENT_CINDY_REGION),+): RegionalMoney | null {+ const compatible = values.filter((value) => value.currency === currency);+ return compatible.length > 0 ? addRegionalMoney(compatible) : null;}// Keep IN (...) bind counts well below SQLite's historical 999 variable limit.@@ -161,24 +202,50 @@ function scheduleOriginFromAgentMeta(agentMeta: string | null): PersistedSchedul}function turnCostFromAgentMeta(agentMeta: string | null): {- costUsd: number;- estimatedValueUsd: number;+ costMoney: RegionalMoney | null;+ estimatedValueMoney: RegionalMoney | null;+ legacyProjectedActualAmount: number;} {- if (!agentMeta) return { costUsd: 0, estimatedValueUsd: 0 };+ if (!agentMeta) {+ return {+ costMoney: null,+ estimatedValueMoney: null,+ legacyProjectedActualAmount: 0,+ };+ }try {const parsed = JSON.parse(agentMeta) as {+ turnCost?: unknown;turnCostUsd?: unknown;turnCostIsEstimate?: unknown;};- const cost = parsed.turnCostUsd;- if (typeof cost !== 'number' || !Number.isFinite(cost) || cost <= 0) {- return { costUsd: 0, estimatedValueUsd: 0 };+ const structured = normalizeRegionalMoney(parsed.turnCost);+ const legacy =+ typeof parsed.turnCostUsd === 'number' &&+ Number.isFinite(parsed.turnCostUsd) &&+ parsed.turnCostUsd > 0+ ? regionalizeLegacyUsd(parsed.turnCostUsd, CURRENT_CINDY_REGION)+ : undefined;+ const money = structured ?? legacy;+ if (!money || money.amount <= 0) {+ return {+ costMoney: null,+ estimatedValueMoney: null,+ legacyProjectedActualAmount: 0,+ };}- return parsed.turnCostIsEstimate === true- ? { costUsd: 0, estimatedValueUsd: cost }- : { costUsd: cost, estimatedValueUsd: 0 };+ const isEstimate = parsed.turnCostIsEstimate === true || money.kind === 'value-estimate';+ return {+ costMoney: isEstimate ? null : money,+ estimatedValueMoney: isEstimate ? asValueEstimateMoney(money) : null,+ legacyProjectedActualAmount: !structured && !isEstimate ? money.amount : 0,+ };} catch {- return { costUsd: 0, estimatedValueUsd: 0 };+ return {+ costMoney: null,+ estimatedValueMoney: null,+ legacyProjectedActualAmount: 0,+ };}}@@ -395,10 +462,6 @@ export class DrizzleScheduleStorage implements ScheduleStorage {db: SchedulerDrizzleDb,runs: ScheduleRun[],): Promise<ScheduleRun[]> {- const normalizeAttribution = (run: ScheduleRun): ScheduleRun =>- run.costAttribution === 'direct' || run.costAttribution === 'mixed'- ? { ...run, costAttribution: 'exact' }- : run;const attributableRunIds = new Set(runs.filter((run) => run.costAttribution !== 'legacy').map((run) => run.id),);@@ -409,7 +472,7 @@ export class DrizzleScheduleStorage implements ScheduleStorage {.filter((id): id is string => Boolean(id)),);if (attributableRunIds.size === 0 || sessionIds.size === 0) {- return runs.map(normalizeAttribution);+ return runs;}const rows = (@@ -419,35 +482,56 @@ export class DrizzleScheduleStorage implements ScheduleStorage {.select({ agentMeta: messages.agentMeta }).from(messages).where(- and(- inArray(messages.sessionId, sessionIdChunk),- eq(messages.role, 'assistant'),- ),+ and(inArray(messages.sessionId, sessionIdChunk), eq(messages.role, 'assistant')),),),)).flat();- const ledger = new Map<string, { costUsd: number; estimatedValueUsd: number }>();+ const ledger = new Map<+ string,+ { costValues: RegionalMoney[]; estimatedValues: RegionalMoney[] }+ >();for (const row of rows) {const origin = scheduleOriginFromAgentMeta(row.agentMeta);if (!origin?.runId || !attributableRunIds.has(origin.runId)) continue;const cost = turnCostFromAgentMeta(row.agentMeta);- if (cost.costUsd <= 0 && cost.estimatedValueUsd <= 0) continue;- const current = ledger.get(origin.runId) ?? { costUsd: 0, estimatedValueUsd: 0 };- current.costUsd += cost.costUsd;- current.estimatedValueUsd += cost.estimatedValueUsd;+ const current = ledger.get(origin.runId) ?? {+ costValues: [],+ estimatedValues: [],+ };+ if (cost.costMoney) current.costValues.push(cost.costMoney);+ if (cost.estimatedValueMoney) {+ current.estimatedValues.push(cost.estimatedValueMoney);+ }ledger.set(origin.runId, current);}return runs.map((run) => {const persisted = ledger.get(run.id);- if (!persisted) return normalizeAttribution(run);+ if (!persisted) return run;if (run.costAttribution === 'direct') {+ const costValues = [+ ...(run.costMoney && run.costMoney.amount > 0 ? [run.costMoney] : []),+ ...persisted.costValues,+ ];+ const estimatedValues = [+ ...(run.estimatedValueMoney && run.estimatedValueMoney.amount > 0+ ? [run.estimatedValueMoney]+ : []),+ ...persisted.estimatedValues,+ ];return {...run,- costUsd: finitePositiveNumber(run.costUsd) + persisted.costUsd,- estimatedValueUsd:- finitePositiveNumber(run.estimatedValueUsd) + persisted.estimatedValueUsd,+ costMoney:+ addCompatibleRegionalMoney(+ costValues,+ run.costMoney?.currency,+ ) ?? zeroRegionalMoney(CURRENT_CINDY_REGION),+ estimatedValueMoney:+ addCompatibleRegionalMoney(+ estimatedValues,+ run.estimatedValueMoney?.currency,+ ) ?? zeroRegionalMoney(CURRENT_CINDY_REGION, 'value-estimate'),costAttribution: 'exact',};}@@ -456,7 +540,12 @@ export class DrizzleScheduleStorage implements ScheduleStorage {}return {...run,- ...persisted,+ costMoney:+ addCompatibleRegionalMoney(persisted.costValues) ??+ zeroRegionalMoney(CURRENT_CINDY_REGION),+ estimatedValueMoney:+ addCompatibleRegionalMoney(persisted.estimatedValues) ??+ zeroRegionalMoney(CURRENT_CINDY_REGION, 'value-estimate'),costAttribution: 'exact',};});@@ -565,17 +654,7 @@ export class DrizzleScheduleStorage implements ScheduleStorage {*/async listCostSummaries(): Promise<ScheduleCostSummary[]> {const db = this.getDb();- const runCostRows = await db- .select({- runId: scheduleRuns.id,- scheduleId: scheduleRuns.scheduleId,- sessionId: scheduleRuns.sessionId,- status: scheduleRuns.status,- costUsd: scheduleRuns.costUsd,- estimatedValueUsd: scheduleRuns.estimatedValueUsd,- costAttribution: scheduleRuns.costAttribution,- })- .from(scheduleRuns);+ const runCostRows = (await db.select().from(scheduleRuns)).map(scheduleRunToCamel);const bySchedule = new Map<string, ScheduleTurnCostState>();const linkedSessionIds = new Set<string>();@@ -651,12 +730,9 @@ export class DrizzleScheduleStorage implements ScheduleStorage {let activeSessionId: string | null = null;let activeScheduleId: string | null = null;- const billableMessageCostBySessionId = new Map<string, number>();const messageCostRunIds = new Set<string>();- const messageCostByRunId = new Map<- string,- { costUsd: number; estimatedValueUsd: number }- >();+ const messageCostByRunId = new Map<string, ScheduleMoneyValues>();+ const legacyMessageCostBySessionId = new Map<string, number>();for (const row of messageRows) {if (row.sessionId !== activeSessionId) {activeSessionId = row.sessionId;@@ -668,12 +744,14 @@ export class DrizzleScheduleStorage implements ScheduleStorage {}if (row.role !== 'assistant') continue;const turnCost = turnCostFromAgentMeta(row.agentMeta);- const cost = turnCost.costUsd;- if (cost <= 0 && turnCost.estimatedValueUsd <= 0) continue;- if (cost > 0) {- billableMessageCostBySessionId.set(+ const cost = turnCost.costMoney?.amount ?? 0;+ const estimatedValue = turnCost.estimatedValueMoney?.amount ?? 0;+ if (cost <= 0 && estimatedValue <= 0) continue;+ if (turnCost.legacyProjectedActualAmount > 0) {+ legacyMessageCostBySessionId.set(row.sessionId,- (billableMessageCostBySessionId.get(row.sessionId) ?? 0) + cost,+ (legacyMessageCostBySessionId.get(row.sessionId) ?? 0) ++ turnCost.legacyProjectedActualAmount,);}const assistantOrigin = scheduleOriginFromAgentMeta(row.agentMeta);@@ -683,32 +761,30 @@ export class DrizzleScheduleStorage implements ScheduleStorage {if (!attributedScheduleId || !linkedScheduleIds.has(attributedScheduleId)) {continue;}- const entry = bySchedule.get(attributedScheduleId) ?? {- totalCostUsd: 0,- totalEstimatedValueUsd: 0,- hasUnavailableCost: false,- sessionIds: new Set<string>(),- sessionCosts: new Map(),- };if (assistantRunId) {messageCostRunIds.add(assistantRunId);- const runCost = messageCostByRunId.get(assistantRunId) ?? {- costUsd: 0,- estimatedValueUsd: 0,- };- runCost.costUsd += cost;- runCost.estimatedValueUsd += turnCost.estimatedValueUsd;+ const runCost = messageCostByRunId.get(assistantRunId) ?? emptyScheduleMoneyValues();+ if (turnCost.costMoney) runCost.costValues.push(turnCost.costMoney);+ if (turnCost.estimatedValueMoney) {+ runCost.estimatedValueValues.push(turnCost.estimatedValueMoney);+ }messageCostByRunId.set(assistantRunId, runCost);}+ const entry = bySchedule.get(attributedScheduleId) ?? emptyScheduleTurnCostState();entry.sessionIds.add(row.sessionId);- entry.totalCostUsd += cost;- entry.totalEstimatedValueUsd += turnCost.estimatedValueUsd;- const sessionCost = entry.sessionCosts.get(row.sessionId) ?? {- totalCostUsd: 0,- totalEstimatedValueUsd: 0,- };- sessionCost.totalCostUsd += cost;- sessionCost.totalEstimatedValueUsd += turnCost.estimatedValueUsd;+ if (turnCost.costMoney) {+ entry.costValues.push(turnCost.costMoney);+ }+ if (turnCost.estimatedValueMoney) {+ entry.estimatedValueValues.push(turnCost.estimatedValueMoney);+ }+ const sessionCost = entry.sessionCosts.get(row.sessionId) ?? emptyScheduleMoneyValues();+ if (turnCost.costMoney) {+ sessionCost.costValues.push(turnCost.costMoney);+ }+ if (turnCost.estimatedValueMoney) {+ sessionCost.estimatedValueValues.push(turnCost.estimatedValueMoney);+ }entry.sessionCosts.set(row.sessionId, sessionCost);bySchedule.set(attributedScheduleId, entry);}@@ -716,132 +792,88 @@ export class DrizzleScheduleStorage implements ScheduleStorage {// 纯 tool turn 没有 assistant message 可挂账,费用会直接写在 schedule_runs。// 正常消息费用已经进入 message ledger;混合 run 则只补 schedule_runs 快照中// 尚未被消息账本覆盖的余量,避免漏记 direct segment 或双计。+ const appendRunMoney = (+ entry: ScheduleTurnCostState,+ sessionId: string | undefined,+ costMoney: RegionalMoney | null,+ estimatedValueMoney: RegionalMoney | null,+ ): void => {+ if (costMoney && costMoney.amount > 0) entry.costValues.push(costMoney);+ if (estimatedValueMoney && estimatedValueMoney.amount > 0) {+ entry.estimatedValueValues.push(estimatedValueMoney);+ }+ if (!sessionId) return;+ entry.sessionIds.add(sessionId);+ const sessionCost = entry.sessionCosts.get(sessionId) ?? emptyScheduleMoneyValues();+ if (costMoney && costMoney.amount > 0) sessionCost.costValues.push(costMoney);+ if (estimatedValueMoney && estimatedValueMoney.amount > 0) {+ sessionCost.estimatedValueValues.push(estimatedValueMoney);+ }+ entry.sessionCosts.set(sessionId, sessionCost);+ };+ const remainingMoney = (+ total: RegionalMoney | undefined,+ messageValues: readonly RegionalMoney[],+ ): RegionalMoney | null => {+ if (!total || total.amount <= 0) return null;+ if (messageValues.length === 0) return total;+ const messageTotal = addCompatibleRegionalMoney(messageValues, total.currency);+ if (!messageTotal) return total;+ // 历史脏数据的币种不一致时保留持久化实际金额,不能让整个 dashboard 抛错。+ if (messageTotal.currency !== total.currency) return total;+ const amount = Math.max(0, total.amount - messageTotal.amount);+ return amount > 0 ? { ...total, amount } : null;+ };+for (const run of runCostRows) {if (run.costAttribution === 'unavailable' && run.status !== 'running') {// 消息账本已经给出该 run 的费用时,以账本为准;schedule_runs 快照可由// listRuns 的 hydrate 路径自愈,不应把任务误标成“部分费用不可用”。- if (messageCostRunIds.has(run.runId)) continue;- const entry = bySchedule.get(run.scheduleId) ?? {- totalCostUsd: 0,- totalEstimatedValueUsd: 0,- hasUnavailableCost: false,- sessionIds: new Set<string>(),- sessionCosts: new Map(),- };+ if (messageCostRunIds.has(run.id)) continue;+ const entry = bySchedule.get(run.scheduleId) ?? emptyScheduleTurnCostState();entry.hasUnavailableCost = true;- if (run.sessionId) {- entry.sessionIds.add(run.sessionId);- if (!entry.sessionCosts.has(run.sessionId)) {- entry.sessionCosts.set(run.sessionId, {- totalCostUsd: 0,- totalEstimatedValueUsd: 0,- });- }- }+ appendRunMoney(entry, run.sessionId, null, null);bySchedule.set(run.scheduleId, entry);continue;}if (run.costAttribution === 'zero' &&run.status !== 'running' &&- !messageCostRunIds.has(run.runId)+ !messageCostRunIds.has(run.id)) {- const entry = bySchedule.get(run.scheduleId) ?? {- totalCostUsd: 0,- totalEstimatedValueUsd: 0,- hasUnavailableCost: false,- sessionIds: new Set<string>(),- sessionCosts: new Map(),- };- if (run.sessionId) {- entry.sessionIds.add(run.sessionId);- if (!entry.sessionCosts.has(run.sessionId)) {- entry.sessionCosts.set(run.sessionId, {- totalCostUsd: 0,- totalEstimatedValueUsd: 0,- });- }- }+ const entry = bySchedule.get(run.scheduleId) ?? emptyScheduleTurnCostState();+ appendRunMoney(entry, run.sessionId, null, null);bySchedule.set(run.scheduleId, entry);continue;}if (run.costAttribution === 'direct' || run.costAttribution === 'mixed') {- const messageCost = messageCostByRunId.get(run.runId);- const costUsd =+ const messageCost = messageCostByRunId.get(run.id);+ const costMoney =run.costAttribution === 'direct'- ? finitePositiveNumber(run.costUsd)- : Math.max(- 0,- finitePositiveNumber(run.costUsd) - (messageCost?.costUsd ?? 0),- );- const estimatedValueUsd =+ ? (run.costMoney ?? null)+ : remainingMoney(run.costMoney, messageCost?.costValues ?? []);+ const estimatedValueMoney =run.costAttribution === 'direct'- ? finitePositiveNumber(run.estimatedValueUsd)- : Math.max(- 0,- finitePositiveNumber(run.estimatedValueUsd) -- (messageCost?.estimatedValueUsd ?? 0),+ ? (run.estimatedValueMoney ?? null)+ : remainingMoney(+ run.estimatedValueMoney,+ messageCost?.estimatedValueValues ?? [],);- if (costUsd === 0 && estimatedValueUsd === 0) continue;- const entry = bySchedule.get(run.scheduleId) ?? {- totalCostUsd: 0,- totalEstimatedValueUsd: 0,- hasUnavailableCost: false,- sessionIds: new Set<string>(),- sessionCosts: new Map(),- };- entry.totalCostUsd += costUsd;- entry.totalEstimatedValueUsd += estimatedValueUsd;- if (run.sessionId) {- entry.sessionIds.add(run.sessionId);- const sessionCost = entry.sessionCosts.get(run.sessionId) ?? {- totalCostUsd: 0,- totalEstimatedValueUsd: 0,- };- sessionCost.totalCostUsd += costUsd;- sessionCost.totalEstimatedValueUsd += estimatedValueUsd;- entry.sessionCosts.set(run.sessionId, sessionCost);- if (costUsd > 0) {- billableMessageCostBySessionId.set(- run.sessionId,- (billableMessageCostBySessionId.get(run.sessionId) ?? 0) + costUsd,- );- }- }+ const entry = bySchedule.get(run.scheduleId) ?? emptyScheduleTurnCostState();+ appendRunMoney(entry, run.sessionId, costMoney, estimatedValueMoney);bySchedule.set(run.scheduleId, entry);continue;}if (run.costAttribution !== 'exact') continue;- const messageCost = messageCostByRunId.get(run.runId);+ const messageCost = messageCostByRunId.get(run.id);if (messageCost) continue;- const costUsd = finitePositiveNumber(run.costUsd);- const estimatedValueUsd = finitePositiveNumber(run.estimatedValueUsd);- if (costUsd === 0 && estimatedValueUsd === 0) continue;- const entry = bySchedule.get(run.scheduleId) ?? {- totalCostUsd: 0,- totalEstimatedValueUsd: 0,- hasUnavailableCost: false,- sessionIds: new Set<string>(),- sessionCosts: new Map(),- };- entry.totalCostUsd += costUsd;- entry.totalEstimatedValueUsd += estimatedValueUsd;- if (run.sessionId) {- entry.sessionIds.add(run.sessionId);- const sessionCost = entry.sessionCosts.get(run.sessionId) ?? {- totalCostUsd: 0,- totalEstimatedValueUsd: 0,- };- sessionCost.totalCostUsd += costUsd;- sessionCost.totalEstimatedValueUsd += estimatedValueUsd;- entry.sessionCosts.set(run.sessionId, sessionCost);- if (costUsd > 0) {- billableMessageCostBySessionId.set(- run.sessionId,- (billableMessageCostBySessionId.get(run.sessionId) ?? 0) + costUsd,- );- }- }+ const entry = bySchedule.get(run.scheduleId) ?? emptyScheduleTurnCostState();+ appendRunMoney(+ entry,+ run.sessionId,+ run.costMoney ?? null,+ run.estimatedValueMoney ?? null,+ );bySchedule.set(run.scheduleId, entry);}@@ -849,40 +881,69 @@ export class DrizzleScheduleStorage implements ScheduleStorage {const scheduleId = legacySessionScheduleIds.get(session.id);if (!scheduleId) continue;- const entry = bySchedule.get(scheduleId) ?? {- totalCostUsd: 0,- totalEstimatedValueUsd: 0,- hasUnavailableCost: false,- sessionIds: new Set<string>(),- sessionCosts: new Map(),- };+ const entry = bySchedule.get(scheduleId) ?? emptyScheduleTurnCostState();entry.sessionIds.add(session.id);const cost = Number(session.totalCostUsd ?? 0);if (Number.isFinite(cost) && cost > 0) {- const alreadyCountedMessageCost = billableMessageCostBySessionId.get(session.id) ?? 0;- const legacyCost = Math.max(0, cost - alreadyCountedMessageCost);- entry.totalCostUsd += legacyCost;- const sessionCost = entry.sessionCosts.get(session.id) ?? {- totalCostUsd: 0,- totalEstimatedValueUsd: 0,+ const projectedLegacyCost = regionalizeLegacyUsd(cost, CURRENT_CINDY_REGION);+ const alreadyCountedMessageCost = legacyMessageCostBySessionId.get(session.id) ?? 0;+ const legacyCost = Math.max(0, projectedLegacyCost.amount - alreadyCountedMessageCost);+ const legacyMoney: RegionalMoney = {+ ...projectedLegacyCost,+ amount: legacyCost,};- sessionCost.totalCostUsd += legacyCost;+ if (legacyCost > 0) {+ entry.costValues.push(legacyMoney);+ }+ const sessionCost = entry.sessionCosts.get(session.id) ?? emptyScheduleMoneyValues();+ if (legacyCost > 0) {+ sessionCost.costValues.push(legacyMoney);+ }entry.sessionCosts.set(session.id, sessionCost);}bySchedule.set(scheduleId, entry);}- return [...bySchedule.entries()].map(([scheduleId, summary]) => ({- scheduleId,- totalCostUsd: summary.totalCostUsd,- totalEstimatedValueUsd: summary.totalEstimatedValueUsd,- ...(summary.hasUnavailableCost ? { hasUnavailableCost: true } : {}),- sessionCount: summary.sessionIds.size,- sessions: [...summary.sessionCosts.entries()].map(([sessionId, costs]) => ({- sessionId,- ...costs,- })),- }));+ return [...bySchedule.entries()].map(([scheduleId, summary]) => {+ const totalMoney =+ addCompatibleRegionalMoney(summary.costValues) ??+ zeroRegionalMoney(CURRENT_CINDY_REGION);+ const totalEstimatedValueMoney =+ addCompatibleRegionalMoney(summary.estimatedValueValues) ??+ zeroRegionalMoney(CURRENT_CINDY_REGION, 'value-estimate');+ return {+ scheduleId,+ totalMoney,+ totalEstimatedValueMoney,+ ...(totalMoney.currency === 'USD'+ ? {+ totalCostUsd: totalMoney.amount,+ totalEstimatedValueUsd: totalEstimatedValueMoney.amount,+ }+ : {}),+ ...(summary.hasUnavailableCost ? { hasUnavailableCost: true } : {}),+ sessionCount: summary.sessionIds.size,+ sessions: [...summary.sessionCosts.entries()].map(([sessionId, costs]) => {+ const money =+ addCompatibleRegionalMoney(costs.costValues) ??+ zeroRegionalMoney(CURRENT_CINDY_REGION);+ const estimatedMoney =+ addCompatibleRegionalMoney(costs.estimatedValueValues) ??+ zeroRegionalMoney(CURRENT_CINDY_REGION, 'value-estimate');+ return {+ sessionId,+ totalMoney: money,+ totalEstimatedValueMoney: estimatedMoney,+ ...(money.currency === 'USD'+ ? {+ totalCostUsd: money.amount,+ totalEstimatedValueUsd: estimatedMoney.amount,+ }+ : {}),+ };+ }),+ };+ });}async deleteRun(id: string): Promise<ScheduleRun | null> {diff --git a/apps/desktop/src/main/sessionSpendBroadcaster.ts b/apps/desktop/src/main/sessionSpendBroadcaster.tsindex 89e8cc6eba..18a38cb381 100644--- a/apps/desktop/src/main/sessionSpendBroadcaster.ts+++ b/apps/desktop/src/main/sessionSpendBroadcaster.ts@@ -25,6 +25,14 @@ 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,+ normalizeRegionalMoney,+ regionalCurrencyForRegion,+ regionalizeLegacyUsd,+ type RegionalMoney,+} from '../shared/regionalMoney.js';const log = createLogger('sessionSpendBroadcaster');@@ -44,8 +52,9 @@ export const USAGE_SESSION_CONTEXT_CHANGED = 'usage:session-context-changed';export interface SessionSpendPayload {sessionId: string;- /** session 终身累计 USD(已持久化到 sessions.total_cost_usd)。 */- totalCostUsd: number;+ totalMoney: RegionalMoney;+ /** 仅当累计金额仍是 USD 时给旧 renderer 的兼容投影。 */+ totalCostUsd?: number;}export interface SessionTokensPayload {@@ -66,22 +75,72 @@ export interface SessionContextPayload {** 极小 / 非法 delta 跳过(与 dailySpend 同阈值)。*/-export async function recordSessionTurnSpend(sessionId: string, costUsdDelta: number): Promise<void> {+export async function recordSessionTurnSpend(+ sessionId: string,+ money: RegionalMoney,+): Promise<void> {if (!sessionId) return;- if (!Number.isFinite(costUsdDelta) || costUsdDelta < 1e-10) 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;+ }await db.update(sessions)- .set({ totalCostUsd: sql`${sessions.totalCostUsd} + ${costUsdDelta}` })+ .set({+ totalCostAmount: sql`${sessions.totalCostAmount} + ${normalized.amount}`,+ totalCostCurrency: normalized.currency,+ totalCostIsApproximate: sql`${sessions.totalCostIsApproximate} OR ${normalized.approximate ? 1 : 0}`,+ }).where(sql`${sessions.id} = ${sessionId}`).run();const row = await db- .select({ totalCostUsd: sessions.totalCostUsd })+ .select({+ totalCostUsd: sessions.totalCostUsd,+ totalCostAmount: sessions.totalCostAmount,+ totalCostCurrency: sessions.totalCostCurrency,+ totalCostIsApproximate: sessions.totalCostIsApproximate,+ }).from(sessions).where(sql`${sessions.id} = ${sessionId}`).get();- const totalCostUsd = row?.totalCostUsd ?? 0;- broadcast({ sessionId, totalCostUsd });+ const legacy = regionalizeLegacyUsd(+ row?.totalCostUsd ?? 0,+ CURRENT_CINDY_REGION,+ );+ const current = normalizeRegionalMoney({+ amount: row?.totalCostAmount ?? 0,+ currency: row?.totalCostCurrency ?? normalized.currency,+ approximate: row?.totalCostIsApproximate ?? false,+ kind: 'actual-cost',+ });+ const totalMoney =+ legacy.amount > 0 && current+ ? legacy.currency === current.currency+ ? addRegionalMoney([legacy, current])+ : current+ : current ?? legacy;+ broadcast({+ sessionId,+ totalMoney,+ ...(totalMoney.currency === 'USD'+ ? { totalCostUsd: totalMoney.amount }+ : {}),+ });} catch (err) {log.warn('recordSessionTurnSpend failed:',diff --git a/apps/desktop/src/main/turnCostBroadcaster.ts b/apps/desktop/src/main/turnCostBroadcaster.tsindex 01d14c2005..a2e41f209e 100644--- a/apps/desktop/src/main/turnCostBroadcaster.ts+++ b/apps/desktop/src/main/turnCostBroadcaster.ts@@ -29,6 +29,11 @@ import {applyScheduleRunCostMetaChange,recordScheduleRunCostDirect,} from './scheduler-host/runCostLedger.js';+import {+ addCompatibleRegionalMoney,+ normalizeRegionalMoney,+ type RegionalMoney,+} from '../shared/regionalMoney.js';const log = createLogger('turnCostBroadcaster');@@ -39,11 +44,12 @@ export interface MessageTurnCostPayload {sessionId: string;/** 该轮最后一条 assistant 的 messages.client_id。 */clientId: string;- turnCostUsd: number;- /** true = 订阅模式下的 token 价值;false = API 账单 cost / API 单价折算 cost。 */+ turnMoney: RegionalMoney;+ turnCostUsd?: number;turnCostIsEstimate: boolean;/** User-visible cumulative cost from the latest real user prompt through this message. */- userTurnCostUsd: number;+ userTurnMoney: RegionalMoney;+ userTurnCostUsd?: number;/** True when any segment in userTurnCostUsd is a subscription-value estimate. */userTurnCostIsEstimate: boolean;/** 本轮 token/cache 明细;旧消息或取不到 usage 时缺省。 */@@ -62,6 +68,7 @@ export interface TurnCostDeps {next: Record<string, unknown>,): Promise<void>;readPriorUserRoundCost(sessionId: string, clientId: string): Promise<{+ money: RegionalMoney | null;costUsd: number;hasEstimatedValue: boolean;}>;@@ -95,34 +102,47 @@ export async function recordTurnCostOnMessage(args: {sessionId: string;clientId: string;- costUsd: number;- isEstimate: boolean;+ money: RegionalMoney;turnUsageDetails?: TurnUsageDetails | null;turnOrigin?: SendOrigin;},deps: TurnCostDeps = defaultDeps,): Promise<boolean> {- const { sessionId, clientId, costUsd, isEstimate, turnUsageDetails, turnOrigin } = args;+ const { sessionId, clientId, money, turnUsageDetails, turnOrigin } = args;if (!sessionId || !clientId) return false;- if (!Number.isFinite(costUsd) || costUsd < 1e-10) return false;+ const normalized = normalizeRegionalMoney(money);+ if (!normalized || normalized.amount < 1e-10) return false;try {- let userTurnCostUsd = costUsd;- let userTurnCostIsEstimate = isEstimate;+ let userTurnMoney = normalized;+ let userTurnCostIsEstimate = normalized.kind === 'value-estimate';const patched = await deps.enqueue(`turn-cost:${sessionId}:${clientId}`, async () => {// This runs in the durable FIFO after prior assistant cost patches, so// the query sees every earlier segment of this user round.const prior = await deps.readPriorUserRoundCost(sessionId, clientId);- userTurnCostUsd = prior.costUsd + costUsd;- userTurnCostIsEstimate = prior.hasEstimatedValue || isEstimate;+ userTurnMoney = prior.money+ ? (addCompatibleRegionalMoney([prior.money, normalized], normalized.currency) ??+ normalized)+ : normalized;+ userTurnCostIsEstimate =+ (prior.money?.currency === userTurnMoney.currency &&+ prior.hasEstimatedValue) ||+ (normalized.currency === userTurnMoney.currency &&+ normalized.kind === 'value-estimate');const patch: Record<string, unknown> = {// Keep the raw segment immutable: daily/session/model accounting and// scheduler summaries consume this field and must never see a running// user-round total.- turnCostUsd: costUsd,- turnCostIsEstimate: isEstimate,- userTurnCostUsd,+ turnCost: normalized,+ turnCostIsEstimate: normalized.kind === 'value-estimate',+ userTurnCost: userTurnMoney,userTurnCostIsEstimate,};+ if (normalized.currency === 'USD') {+ patch.turnCostUsd = normalized.amount;+ }+ if (userTurnMoney.currency === 'USD') {+ patch.userTurnCostUsd = userTurnMoney.amount;+ }if (turnOrigin?.kind === 'scheduler' && typeof turnOrigin.runId === 'string' && turnOrigin.runId) {patch.origin = turnOrigin;}@@ -142,9 +162,15 @@ export async function recordTurnCostOnMessage(deps.broadcast({sessionId,clientId,- turnCostUsd: costUsd,- turnCostIsEstimate: isEstimate,- userTurnCostUsd,+ turnMoney: normalized,+ ...(normalized.currency === 'USD'+ ? { turnCostUsd: normalized.amount }+ : {}),+ turnCostIsEstimate: normalized.kind === 'value-estimate',+ userTurnMoney,+ ...(userTurnMoney.currency === 'USD'+ ? { userTurnCostUsd: userTurnMoney.amount }+ : {}),userTurnCostIsEstimate,...(turnUsageDetails ? { turnUsageDetails } : {}),});@@ -178,8 +204,7 @@ export async function recordSchedulerTurnCost(args: {sessionId: string;clientId?: string;- costUsd: number;- isEstimate: boolean;+ money: RegionalMoney;turnUsageDetails?: TurnUsageDetails | null;turnOrigin?: SendOrigin;},@@ -203,8 +228,7 @@ export async function recordSchedulerTurnCost(try {return await deps.recordDirect({runId: turnOrigin.runId,- costUsd: args.costUsd,- isEstimate: args.isEstimate,+ money: args.money,});} catch (err) {log.warn('recordSchedulerTurnCost fallback failed:', err instanceof Error ? err.message : String(err));diff --git a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts b/apps/desktop/src/main/usage/__tests__/modelPricing.test.tsindex 96b4e3f347..3253803d59 100644--- a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts+++ b/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts@@ -1,876 +1,370 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';+import { mkdtemp, readFile, rm, writeFile, mkdir } from 'node:fs/promises';import os from 'node:os';import path from 'node:path';-// modelPricing 顶层 import 了 host / Electron 依赖; 单测 mock 掉这些边界,-// 只覆盖价格解析、缓存和 gateway 刷新语义。-vi.mock('../../logger', () => ({- createLogger: () => ({- info: vi.fn(),- debug: vi.fn(),- warn: vi.fn(),- error: vi.fn(),- }),-}));const mocks = vi.hoisted(() => ({- readClaudeApiKey: vi.fn(() => null as string | null),getCurrentDbClientUserId: vi.fn(() => 'user-a' as string | null),electronAppGetPath: vi.fn(() => ''),+ getClientEndpoint: vi.fn(() => 'https://model-access.example.test'),+ resolveOwnerScopedSecretStorageKey: vi.fn(() => 'provider-xd'),+ statSync: vi.fn(() => ({+ dev: 1n,+ ino: 2n,+ size: 3n,+ mtimeNs: 4n,+ ctimeNs: 5n,+ })),+ send: vi.fn(),}));+vi.mock('node:fs', async (importOriginal) => ({+ ...(await importOriginal<typeof import('node:fs')>()),+ statSync: mocks.statSync,+}));vi.mock('electron', () => ({app: {getPath: mocks.electronAppGetPath,},+ BrowserWindow: {+ getAllWindows: () => [{+ isDestroyed: () => false,+ webContents: { send: mocks.send },+ }],+ },}));-vi.mock('../../maker-host/auth-adapters', () => ({- readClaudeApiKey: mocks.readClaudeApiKey,+vi.mock('../../logger', () => ({+ createLogger: () => ({+ info: vi.fn(),+ debug: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ }),}));vi.mock('../../localDb/client/current', () => ({getCurrentDbClientUserId: mocks.getCurrentDbClientUserId,}));-vi.mock('../../appSessionState', () => ({- getActiveAppSession: () => ({- mode: 'cloud',- dataOwnerId: mocks.getCurrentDbClientUserId(),- generation: 0,- }),- dataOwnerStorageKey: (ownerId: string) => ownerId,- LOCAL_DATA_OWNER_ID: 'local-v1',+vi.mock('../../clientEndpointsService', () => ({+ getClientEndpoint: mocks.getClientEndpoint,}));-vi.mock('../../maker-host/runtime-configs', () => ({- claudeUpstreamEndpoint: () => 'https://example.invalid',+vi.mock('../../secrets/providerSecretStore', () => ({+ resolveOwnerScopedSecretStorageKey:+ mocks.resolveOwnerScopedSecretStorageKey,}));+import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';+import { gatewayCurrencyForRegion } from '../../../shared/regionalMoney';import {__resetModelPricingCacheForTesting,+ clearGatewayModelPricing,getCodexBudgetEffectiveCostMultiplier,getCodexSubscriptionValuePrice,getModelPricing,getModelPricingForModel,- parseModelGroupInfo,+ getSubscriptionDirectValuePrice,+ MODEL_PRICING_CHANGED_CHANNEL,prewarmModelPricing,+ replaceGatewayModelPricing,} from '../modelPricing';let tempUserDataDir: string | null = null;function userDataPath(...segments: string[]): string {- if (!tempUserDataDir) throw new Error('tempUserDataDir 未初始化');+ if (!tempUserDataDir) throw new Error('temp userData is not initialized');return path.join(tempUserDataDir, ...segments);}-async function writeTestKeyFile(value = 'encrypted-test-key'): Promise<void> {- await mkdir(userDataPath('safe-storage'), { recursive: true });- const ownerId = mocks.getCurrentDbClientUserId();- if (!ownerId) throw new Error('test owner is not initialized');- await writeFile(userDataPath('safe-storage', `owner_${ownerId}_api_key.enc`), value, 'utf8');-}--async function testCacheScope(userId = 'user-a'): Promise<string> {- const ownerId = mocks.getCurrentDbClientUserId();- if (!ownerId) throw new Error('test owner is not initialized');- const keyFileStat = await stat(- userDataPath('safe-storage', `owner_${ownerId}_api_key.enc`),- { bigint: true },- );- return `v1|base=https://example.invalid|user=${userId}|key=file=${keyFileStat.dev}:${keyFileStat.ino}:${keyFileStat.size}:${keyFileStat.mtimeNs}:${keyFileStat.ctimeNs}`;+function expectedScope(userId = 'user-a'): string {+ return `v1|region=${CURRENT_CINDY_REGION}|base=https://model-access.example.test|user=${userId}|key=1:2:3:4:5`;}beforeEach(async () => {- tempUserDataDir = await mkdtemp(path.join(os.tmpdir(), 'xdt-maker-model-pricing-'));+ tempUserDataDir = await mkdtemp(path.join(os.tmpdir(), 'cindy-model-pricing-'));mocks.electronAppGetPath.mockReturnValue(tempUserDataDir);- __resetModelPricingCacheForTesting();- mocks.readClaudeApiKey.mockReturnValue(null);mocks.getCurrentDbClientUserId.mockReturnValue('user-a');+ mocks.getClientEndpoint.mockReturnValue(+ 'https://model-access.example.test',+ );+ mocks.resolveOwnerScopedSecretStorageKey.mockReturnValue('provider-xd');+ mocks.statSync.mockReturnValue({+ dev: 1n,+ ino: 2n,+ size: 3n,+ mtimeNs: 4n,+ ctimeNs: 5n,+ });+ mocks.send.mockClear();+ __resetModelPricingCacheForTesting();});afterEach(async () => {- vi.useRealTimers();- vi.unstubAllGlobals();vi.restoreAllMocks();if (tempUserDataDir) {- await rm(tempUserDataDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });+ await rm(tempUserDataDir, {+ recursive: true,+ force: true,+ maxRetries: 5,+ retryDelay: 100,+ });tempUserDataDir = null;}});-describe('parseModelGroupInfo', () => {- it('converts per-token costs to USD per Mtok', () => {- const out = parseModelGroupInfo({- data: [- {- model_group: 'claude-sonnet-4-6',- input_cost_per_token: 0.000003,- output_cost_per_token: 0.000015,- },- {- model_group: 'gpt-5.4-mini',- input_cost_per_token: 7.5e-7,- output_cost_per_token: 0.0000045,- },- ],- });- expect(out['claude-sonnet-4-6']).toEqual({- inputUsdPerMtok: 3,- outputUsdPerMtok: 15,- });- expect(out['gpt-5.4-mini']?.inputUsdPerMtok).toBeCloseTo(0.75);- expect(out['gpt-5.4-mini']?.outputUsdPerMtok).toBeCloseTo(4.5);- });-- it('applies the 15% budget discount to codex/ model pricing', () => {- const out = parseModelGroupInfo({- data: [- { model_group: 'gpt-5.5', input_cost_per_token: 0.000002, output_cost_per_token: 0.000008 },- { model_group: 'codex/gpt-5.5', input_cost_per_token: 0.000002, output_cost_per_token: 0.000008 },- { model_group: 'codex/qwen3.7-max', input_cost_per_token: 0.000001, output_cost_per_token: 0.000002 },- ],- });- expect(out['gpt-5.5']).toEqual({ inputUsdPerMtok: 2, outputUsdPerMtok: 8, cacheReadUsdPerMtok: 0.2 });- expect(out['codex/gpt-5.5']?.inputUsdPerMtok).toBeCloseTo(0.3);- expect(out['codex/gpt-5.5']?.outputUsdPerMtok).toBeCloseTo(1.2);- expect(out['codex/qwen3.7-max']?.inputUsdPerMtok).toBeCloseTo(0.15);- expect(out['codex/qwen3.7-max']?.outputUsdPerMtok).toBeCloseTo(0.3);- });-- it('parses optional cache_read / cache_creation 档价 when present, 非 OpenAI 缺失则不挂', () => {- const out = parseModelGroupInfo({- data: [- {- model_group: 'claude-opus-4-8',- input_cost_per_token: 0.000005,- output_cost_per_token: 0.000025,- cache_read_input_token_cost: 5e-7,- cache_creation_input_token_cost: 0.00000625,- },- { model_group: 'qwen/qwen3.7-max', input_cost_per_token: 0.000002, output_cost_per_token: 0.000008 },- ],- });- expect(out['claude-opus-4-8']).toEqual({- inputUsdPerMtok: 5,- outputUsdPerMtok: 25,- cacheReadUsdPerMtok: 0.5,- cacheCreateUsdPerMtok: 6.25,- });- expect(out['qwen/qwen3.7-max']?.cacheReadUsdPerMtok).toBeUndefined();- expect(out['qwen/qwen3.7-max']?.cacheCreateUsdPerMtok).toBeUndefined();- });-- it('fills missing cache_read for known OpenAI/Codex GPT models', () => {- const out = parseModelGroupInfo({- data: [- { model_group: 'gpt-5.5', input_cost_per_token: 0.000005, output_cost_per_token: 0.00003 },- { model_group: 'codex/gpt-5.5', input_cost_per_token: 0.000005, output_cost_per_token: 0.00003 },- ],- });- expect(out['gpt-5.5']).toEqual({- inputUsdPerMtok: 5,- outputUsdPerMtok: 30,- cacheReadUsdPerMtok: 0.5,- });- expect(out['codex/gpt-5.5']).toEqual({- inputUsdPerMtok: 0.75,- outputUsdPerMtok: 4.5,- cacheReadUsdPerMtok: 0.075,- });- });-- it('fills missing cache_read (10%) and cache_creation (1.25x) for GPT-5.6 models', () => {- const out = parseModelGroupInfo({- data: [- { model_group: 'gpt-5.6-sol', input_cost_per_token: 0.000005, output_cost_per_token: 0.00003 },- { model_group: 'gpt-5.6-luna', input_cost_per_token: 0.000001, output_cost_per_token: 0.000006 },- { model_group: 'codex/gpt-5.6-sol', input_cost_per_token: 0.000005, output_cost_per_token: 0.00003 },- ],- });- expect(out['gpt-5.6-sol']).toEqual({- inputUsdPerMtok: 5,- outputUsdPerMtok: 30,- cacheReadUsdPerMtok: 0.5,- cacheCreateUsdPerMtok: 6.25,- });- expect(out['gpt-5.6-luna']).toEqual({- inputUsdPerMtok: 1,- outputUsdPerMtok: 6,- cacheReadUsdPerMtok: 0.1,- cacheCreateUsdPerMtok: 1.25,- });- // 骨折路由: 兜底档价同样吃 0.15 折扣 (先补价后打折)- expect(out['codex/gpt-5.6-sol']?.inputUsdPerMtok).toBeCloseTo(0.75);- expect(out['codex/gpt-5.6-sol']?.cacheReadUsdPerMtok).toBeCloseTo(0.075);- expect(out['codex/gpt-5.6-sol']?.cacheCreateUsdPerMtok).toBeCloseTo(0.9375);- });-- it('fills only the missing cache tier when gateway provides the other one', () => {- const out = parseModelGroupInfo({- data: [- {- model_group: 'gpt-5.6-terra',- input_cost_per_token: 0.0000025,- output_cost_per_token: 0.000015,- cache_read_input_token_cost: 2.5e-7,- },- // 老 GPT 模型缺 cache_creation 不兜底 (官方 write 不加价, 消费方回退 input 价即正确)- { model_group: 'gpt-5.5', input_cost_per_token: 0.000005, output_cost_per_token: 0.00003, cache_read_input_token_cost: 5e-7 },- ],- });- expect(out['gpt-5.6-terra']).toEqual({- inputUsdPerMtok: 2.5,- outputUsdPerMtok: 15,- cacheReadUsdPerMtok: 0.25,- cacheCreateUsdPerMtok: 3.125,- });- expect(out['gpt-5.5']?.cacheCreateUsdPerMtok).toBeUndefined();- });-- it('parses numeric-string cache 档价 (与 base 价同口径, gateway 偶尔序列化成字符串)', () => {- const out = parseModelGroupInfo({- data: [- {- model_group: 'gpt-5.5',- input_cost_per_token: '0.000002',- output_cost_per_token: '0.000008',- cache_read_input_token_cost: '0.0000005',- cache_creation_input_token_cost: '0.0000025',- },- ],- } as unknown);- // base 价本就走 Number() 接受字符串; cache 档价现在对齐同口径, 不再被静默丢弃。- expect(out['gpt-5.5']).toEqual({- inputUsdPerMtok: 2,- outputUsdPerMtok: 8,- cacheReadUsdPerMtok: 0.5,- cacheCreateUsdPerMtok: 2.5,- });- });-- it('treats null / 非数值 cache 字段为未提供 (不挂成 0)', () => {- const out = parseModelGroupInfo({- data: [- {- model_group: 'claude-opus-4-8',- input_cost_per_token: 0.000005,- output_cost_per_token: 0.000025,- cache_read_input_token_cost: null,- cache_creation_input_token_cost: 'x',+describe('gateway model pricing projection', () => {+ it('converts model-groups per-token values to provider-scoped per-Mtok quotes', () => {+ const pricing = replaceGatewayModelPricing([+ {+ id: 'claude-sonnet-4',+ inputCostPerToken: 0.000003,+ outputCostPerToken: 0.000015,+ cacheReadInputTokenCost: 0.0000003,+ cacheCreationInputTokenCost: 0.00000375,+ },+ {+ id: 'codex/gpt-5.5',+ inputCostPerToken: 0.000002,+ outputCostPerToken: 0.000008,+ cacheReadInputTokenCost: 0.0000002,+ },+ ]);++ expect(pricing).toEqual({+ xd: {+ 'claude-sonnet-4': {+ providerId: 'xd',+ modelId: 'claude-sonnet-4',+ currency: gatewayCurrencyForRegion(CURRENT_CINDY_REGION),+ source: 'gateway',+ approximate: false,+ inputPerMtok: 3,+ outputPerMtok: 15,+ cacheReadPerMtok: 0.3,+ cacheCreatePerMtok: 3.75,},- // 数值 0 是合法的"免费缓存读", 应挂成 0- { model_group: 'free-cache-model', input_cost_per_token: 0.000002, output_cost_per_token: 0.000008, cache_read_input_token_cost: 0 },- ],- } as unknown);- expect(out['claude-opus-4-8']?.cacheReadUsdPerMtok).toBeUndefined();- expect(out['claude-opus-4-8']?.cacheCreateUsdPerMtok).toBeUndefined();- expect(out['free-cache-model']?.cacheReadUsdPerMtok).toBe(0);- });-- it('scales cache 档价 by the codex budget discount too', () => {- const out = parseModelGroupInfo({- data: [- {- model_group: 'codex/gpt-5.5',- input_cost_per_token: 0.000002,- output_cost_per_token: 0.000008,- cache_read_input_token_cost: 2e-7,- cache_creation_input_token_cost: 0.0000025,+ 'codex/gpt-5.5': {+ providerId: 'xd',+ modelId: 'codex/gpt-5.5',+ currency: gatewayCurrencyForRegion(CURRENT_CINDY_REGION),+ source: 'gateway',+ approximate: false,+ inputPerMtok: 0.3,+ outputPerMtok: 1.2,+ cacheReadPerMtok: expect.closeTo(0.03),},- ],- });- expect(out['codex/gpt-5.5']?.cacheReadUsdPerMtok).toBeCloseTo(0.03); // 0.2 × 0.15- expect(out['codex/gpt-5.5']?.cacheCreateUsdPerMtok).toBeCloseTo(0.375); // 2.5 × 0.15- });-- it('drops 0/0 entries — LiteLLM 未配价不是免费, 不能展示成 $0', () => {- const out = parseModelGroupInfo({- data: [- { model_group: 'claude-fable-5', input_cost_per_token: 0, output_cost_per_token: 0 },- { model_group: 'claude-opus-4-8', input_cost_per_token: 0.000005, output_cost_per_token: 0.000025 },- ],- });- expect(out['claude-fable-5']).toBeUndefined();- expect(out['claude-opus-4-8']).toBeDefined();- });-- it('keeps single-sided pricing (embedding 类 output=0)', () => {- const out = parseModelGroupInfo({- data: [- { model_group: 'gemini-embedding-2-preview', input_cost_per_token: 2e-7, output_cost_per_token: 0 },- ],+ },});- expect(out['gemini-embedding-2-preview']?.inputUsdPerMtok).toBeCloseTo(0.2);- expect(out['gemini-embedding-2-preview']?.outputUsdPerMtok).toBe(0);- });-- it('drops malformed entries (缺名 / 非数值 / 负数) without throwing', () => {- const out = parseModelGroupInfo({- data: [- { input_cost_per_token: 0.000001, output_cost_per_token: 0.000002 },- { model_group: '', input_cost_per_token: 0.000001, output_cost_per_token: 0.000002 },- { model_group: 'bad-string', input_cost_per_token: 'x', output_cost_per_token: 0.000002 },- { model_group: 'bad-missing' },- { model_group: 'bad-negative', input_cost_per_token: -1e-6, output_cost_per_token: 1e-6 },- null,- { model_group: 'ok', input_cost_per_token: 1e-6, output_cost_per_token: 2e-6 },- ],- } as unknown);- expect(Object.keys(out)).toEqual(['ok']);+ expect(mocks.send).toHaveBeenCalledWith(+ MODEL_PRICING_CHANGED_CHANNEL,+ pricing,+ );});- it('returns empty map for non-object / missing data payloads', () => {- expect(parseModelGroupInfo(null)).toEqual({});- expect(parseModelGroupInfo(undefined)).toEqual({});- expect(parseModelGroupInfo('nope')).toEqual({});- expect(parseModelGroupInfo({})).toEqual({});- expect(parseModelGroupInfo({ data: 'nope' })).toEqual({});- });-});+ it('keeps legal zero tiers but drops missing, invalid and 0/0 standard prices', () => {+ const pricing = replaceGatewayModelPricing([+ {+ id: 'free-output',+ inputCostPerToken: 0.000001,+ outputCostPerToken: 0,+ cacheReadInputTokenCost: 0,+ },+ {+ id: 'missing-output',+ inputCostPerToken: 0.000001,+ },+ {+ id: 'zero-both',+ inputCostPerToken: 0,+ outputCostPerToken: 0,+ },+ {+ id: 'negative',+ inputCostPerToken: -1,+ outputCostPerToken: 1,+ },+ ]);-describe('getCodexSubscriptionValuePrice', () => {- it('falls back to embedded display pricing for official Codex subscription models', () => {- expect(getCodexSubscriptionValuePrice('gpt-5.5', null)).toEqual({- inputUsdPerMtok: 5,- cacheReadUsdPerMtok: 0.5,- outputUsdPerMtok: 30,- });- expect(getCodexSubscriptionValuePrice('gpt-5.4-mini', undefined)).toEqual({- inputUsdPerMtok: 0.75,- cacheReadUsdPerMtok: 0.075,- outputUsdPerMtok: 4.5,- });- expect(getCodexSubscriptionValuePrice('gpt-5.6-sol', null)).toEqual({- inputUsdPerMtok: 5,- cacheReadUsdPerMtok: 0.5,- cacheCreateUsdPerMtok: 6.25,- outputUsdPerMtok: 30,- });- expect(getCodexSubscriptionValuePrice('gpt-5.6-luna', null)).toEqual({- inputUsdPerMtok: 1,- cacheReadUsdPerMtok: 0.1,- cacheCreateUsdPerMtok: 1.25,- outputUsdPerMtok: 6,+ expect(pricing?.xd?.['free-output']).toMatchObject({+ inputPerMtok: 1,+ outputPerMtok: 0,+ cacheReadPerMtok: 0,});+ expect(Object.keys(pricing?.xd ?? {})).toEqual(['free-output']);});- it('prefers live gateway pricing when available', () => {- expect(getCodexSubscriptionValuePrice('gpt-5.5', {- 'gpt-5.5': { inputUsdPerMtok: 3, outputUsdPerMtok: 9 },- })).toMatchObject({ inputUsdPerMtok: 3, cacheReadUsdPerMtok: expect.closeTo(0.3), outputUsdPerMtok: 9 });- });-- it('does not invent pricing for budget API routes or unknown models', () => {- expect(getCodexSubscriptionValuePrice('codex/gpt-5.5', null)).toBeUndefined();- expect(getCodexSubscriptionValuePrice('unknown-model', null)).toBeUndefined();- });-});--describe('getCodexBudgetEffectiveCostMultiplier', () => {- it('returns the fixed budget multiplier for codex budget routes', () => {- expect(getCodexBudgetEffectiveCostMultiplier('codex/gpt-5.5')).toBeCloseTo(0.15);- });+ it('successful empty or unpriced snapshots clear the old quote instead of reviving it', async () => {+ replaceGatewayModelPricing([+ {+ id: 'priced',+ inputCostPerToken: 0.000001,+ outputCostPerToken: 0.000002,+ },+ ]);+ expect(await getModelPricing()).not.toBeNull();++ expect(replaceGatewayModelPricing([+ { id: 'unpriced' },+ ])).toBeNull();+ expect(await getModelPricing()).toBeNull();+ expect(mocks.send).toHaveBeenLastCalledWith(+ MODEL_PRICING_CHANGED_CHANNEL,+ null,+ );- it('returns 1 for regular models', () => {- expect(getCodexBudgetEffectiveCostMultiplier('gpt-5.5')).toBe(1);+ clearGatewayModelPricing();+ expect(await getModelPricing()).toBeNull();});});-describe('getModelPricing', () => {- it('keeps stale gateway pricing and short retry window when refresh fails', async () => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-06-16T00:00:00.000Z'));- mocks.readClaudeApiKey.mockReturnValue('test-key');- await writeTestKeyFile();- const fetchMock = vi.fn()- .mockResolvedValueOnce({- ok: true,- json: async () => ({- data: [- {- model_group: 'claude-opus-4-8',- input_cost_per_token: 0.000005,- output_cost_per_token: 0.000025,- },- {- model_group: 'gpt-5.5',- input_cost_per_token: 0.000005,- output_cost_per_token: 0.00003,- },- {- model_group: 'codex/gpt-5.5',- input_cost_per_token: 0.000005,- output_cost_per_token: 0.00003,- },- ],- }),- })- .mockResolvedValueOnce({ ok: false, status: 500 })- .mockResolvedValueOnce({- ok: true,- json: async () => ({- data: [- {- model_group: 'claude-opus-4-8',- input_cost_per_token: 0.000006,- output_cost_per_token: 0.00003,- },- {- model_group: 'codex/gpt-5.5',- input_cost_per_token: 0.000006,- output_cost_per_token: 0.000036,- },- ],- }),- });- vi.stubGlobal('fetch', fetchMock);-- await expect(getModelPricing()).resolves.toMatchObject({- 'claude-opus-4-8': { inputUsdPerMtok: 5, outputUsdPerMtok: 25 },- 'codex/gpt-5.5': { inputUsdPerMtok: expect.closeTo(0.75), outputUsdPerMtok: expect.closeTo(4.5) },- });-- vi.setSystemTime(new Date('2026-06-16T07:00:00.000Z'));- await expect(getModelPricing()).resolves.toMatchObject({- 'claude-opus-4-8': { inputUsdPerMtok: 5, outputUsdPerMtok: 25 },- 'gpt-5.5': { inputUsdPerMtok: 5, outputUsdPerMtok: 30 },- 'codex/gpt-5.5': { inputUsdPerMtok: expect.closeTo(0.75), outputUsdPerMtok: expect.closeTo(4.5) },- });- await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));-- vi.setSystemTime(new Date('2026-06-16T07:00:30.000Z'));- await expect(getModelPricing()).resolves.toMatchObject({- 'claude-opus-4-8': { inputUsdPerMtok: 5, outputUsdPerMtok: 25 },- });- expect(fetchMock).toHaveBeenCalledTimes(2);-- vi.setSystemTime(new Date('2026-06-16T07:01:01.000Z'));- await expect(getModelPricing()).resolves.toMatchObject({- 'claude-opus-4-8': { inputUsdPerMtok: 5, outputUsdPerMtok: 25 },- 'codex/gpt-5.5': { inputUsdPerMtok: expect.closeTo(0.75), outputUsdPerMtok: expect.closeTo(4.5) },- });- await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(3));- await expect(getModelPricing()).resolves.toMatchObject({- 'claude-opus-4-8': { inputUsdPerMtok: 6, outputUsdPerMtok: 30 },- 'codex/gpt-5.5': { inputUsdPerMtok: expect.closeTo(0.9), outputUsdPerMtok: expect.closeTo(5.4) },- });- });-- it('persists successful gateway pricing and hydrates it after process cache reset', async () => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-06-16T00:00:00.000Z'));- mocks.readClaudeApiKey.mockReturnValue('test-key');- await writeTestKeyFile();- const fetchMock = vi.fn().mockResolvedValueOnce({- ok: true,- json: async () => ({- data: [- {- model_group: 'claude-opus-4-8',- input_cost_per_token: 0.000005,- output_cost_per_token: 0.000025,- cache_read_input_token_cost: 5e-7,- },- ],- }),- });+describe('pricing cache lifecycle', () => {+ it('persists the model-sync projection and hydrates it without any network request', async () => {+ const fetchMock = vi.fn();vi.stubGlobal('fetch', fetchMock);-- await expect(getModelPricing()).resolves.toMatchObject({- 'claude-opus-4-8': {- inputUsdPerMtok: 5,- outputUsdPerMtok: 25,- cacheReadUsdPerMtok: 0.5,+ const pricing = replaceGatewayModelPricing([+ {+ id: 'gpt-5.5',+ inputCostPerToken: 0.000005,+ outputCostPerToken: 0.00003,},- });+ ]);+await vi.waitFor(async () => {- const raw = await readFile(userDataPath('cache', 'model-pricing.json'), 'utf8');- expect(JSON.parse(raw)).toMatchObject({- version: 2,- fetchedAt: Date.parse('2026-06-16T00:00:00.000Z'),- baseUrl: 'https://example.invalid',- cacheScope: await testCacheScope('user-a'),- pricing: {- 'claude-opus-4-8': {- inputUsdPerMtok: 5,- outputUsdPerMtok: 25,- cacheReadUsdPerMtok: 0.5,- },- },+ const raw = JSON.parse(+ await readFile(userDataPath('cache', 'model-pricing.json'), 'utf8'),+ );+ expect(raw).toMatchObject({+ version: 3,+ scope: expectedScope(),+ pricing,});});__resetModelPricingCacheForTesting();- fetchMock.mockReset();-- await expect(getModelPricing()).resolves.toMatchObject({- 'claude-opus-4-8': {- inputUsdPerMtok: 5,- outputUsdPerMtok: 25,- cacheReadUsdPerMtok: 0.5,- },- });+ await expect(getModelPricing()).resolves.toEqual(pricing);+ await prewarmModelPricing();expect(fetchMock).not.toHaveBeenCalled();});- it('fills known OpenAI cache pricing when hydrating an older disk cache', async () => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-06-16T00:30:00.000Z'));- mocks.readClaudeApiKey.mockReturnValue('test-key');- await writeTestKeyFile();+ it('does not hydrate another account pricing snapshot', async () => {await mkdir(userDataPath('cache'), { recursive: true });await writeFile(userDataPath('cache', 'model-pricing.json'),JSON.stringify({- version: 2,- fetchedAt: Date.parse('2026-06-16T00:00:00.000Z'),- baseUrl: 'https://example.invalid',- cacheScope: await testCacheScope('user-a'),+ version: 3,+ scope: expectedScope(),+ fetchedAt: Date.now(),pricing: {- 'gpt-5.5': { inputUsdPerMtok: 5, outputUsdPerMtok: 30 },+ xd: {+ secret: {+ providerId: 'xd',+ modelId: 'secret',+ currency: gatewayCurrencyForRegion(CURRENT_CINDY_REGION),+ source: 'gateway',+ approximate: false,+ inputPerMtok: 1,+ outputPerMtok: 2,+ },+ },},}),'utf8',);- const fetchMock = vi.fn();- vi.stubGlobal('fetch', fetchMock);-- await expect(getModelPricing()).resolves.toMatchObject({- 'gpt-5.5': {- inputUsdPerMtok: 5,- outputUsdPerMtok: 30,- cacheReadUsdPerMtok: 0.5,- },- });- expect(fetchMock).not.toHaveBeenCalled();- });-- it('does not hydrate another account or key pricing cache from disk', async () => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-06-16T00:30:00.000Z'));mocks.getCurrentDbClientUserId.mockReturnValue('user-b');- mocks.readClaudeApiKey.mockReturnValue('key-b');- await writeTestKeyFile('encrypted-key-b');- const staleScope = await testCacheScope('user-a');- await mkdir(userDataPath('cache'), { recursive: true });- await writeFile(- userDataPath('cache', 'model-pricing.json'),- JSON.stringify({- version: 2,- fetchedAt: Date.parse('2026-06-16T00:00:00.000Z'),- baseUrl: 'https://example.invalid',- cacheScope: staleScope,- pricing: {- 'gpt-5.5': { inputUsdPerMtok: 99, outputUsdPerMtok: 199 },- },- }),- 'utf8',- );- const fetchMock = vi.fn().mockResolvedValueOnce({- ok: true,- json: async () => ({- data: [- {- model_group: 'gpt-5.5',- input_cost_per_token: 0.000002,- output_cost_per_token: 0.000008,- },- ],- }),- });- vi.stubGlobal('fetch', fetchMock);- await expect(getModelPricingForModel('gpt-5.5')).resolves.toMatchObject({- 'gpt-5.5': { inputUsdPerMtok: 2, outputUsdPerMtok: 8 },- });- expect(fetchMock).toHaveBeenCalledTimes(1);+ await expect(getModelPricing()).resolves.toBeNull();});- it('does not reuse fresh in-memory pricing after the XD key changes', async () => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-06-16T00:00:00.000Z'));- mocks.readClaudeApiKey.mockReturnValue('key-a');- await writeTestKeyFile('encrypted-key-a');- const fetchMock = vi.fn()- .mockResolvedValueOnce({- ok: true,- json: async () => ({- data: [- {- model_group: 'gpt-5.5',- input_cost_per_token: 0.000002,- output_cost_per_token: 0.000008,- },- ],- }),- })- .mockResolvedValueOnce({- ok: true,- json: async () => ({- data: [- {- model_group: 'gpt-5.5',- input_cost_per_token: 0.000003,- output_cost_per_token: 0.000009,- },- ],- }),- });- vi.stubGlobal('fetch', fetchMock);-- await expect(getModelPricingForModel('gpt-5.5')).resolves.toMatchObject({- 'gpt-5.5': { inputUsdPerMtok: 2, outputUsdPerMtok: 8 },- });-- vi.setSystemTime(new Date('2026-06-16T00:01:00.000Z'));- mocks.readClaudeApiKey.mockReturnValue('key-b');- await writeTestKeyFile('encrypted-key-b-with-different-size');- await expect(getModelPricingForModel('gpt-5.5')).resolves.toMatchObject({- 'gpt-5.5': { inputUsdPerMtok: 3, outputUsdPerMtok: 9 },+ it('does not hydrate pricing written for an older gateway key identity', async () => {+ replaceGatewayModelPricing([+ {+ id: 'gpt-5.5',+ inputCostPerToken: 0.000005,+ outputCostPerToken: 0.00003,+ },+ ]);+ await vi.waitFor(async () => {+ await expect(+ readFile(userDataPath('cache', 'model-pricing.json'), 'utf8'),+ ).resolves.toContain(expectedScope());});- expect(fetchMock).toHaveBeenCalledTimes(2);- });- it('refreshes pricing synchronously when an accounting model is missing', async () => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-06-16T00:30:00.000Z'));- mocks.readClaudeApiKey.mockReturnValue('test-key');- await writeTestKeyFile();- await mkdir(userDataPath('cache'), { recursive: true });- await writeFile(- userDataPath('cache', 'model-pricing.json'),- JSON.stringify({- version: 2,- fetchedAt: Date.parse('2026-06-16T00:00:00.000Z'),- baseUrl: 'https://example.invalid',- cacheScope: await testCacheScope('user-a'),- pricing: {- 'gpt-5.5': { inputUsdPerMtok: 5, outputUsdPerMtok: 30 },- },- }),- 'utf8',- );- const fetchMock = vi.fn().mockResolvedValueOnce({- ok: true,- json: async () => ({- data: [- {- model_group: 'gpt-5.5',- input_cost_per_token: 0.000005,- output_cost_per_token: 0.00003,- },- {- model_group: 'gpt-5.6',- input_cost_per_token: 0.000006,- output_cost_per_token: 0.000036,- },- ],- }),+ __resetModelPricingCacheForTesting();+ mocks.statSync.mockReturnValue({+ dev: 1n,+ ino: 2n,+ size: 3n,+ mtimeNs: 6n,+ ctimeNs: 7n,});- vi.stubGlobal('fetch', fetchMock);- await expect(getModelPricingForModel('gpt-5.6')).resolves.toMatchObject({- 'gpt-5.6': { inputUsdPerMtok: 6, outputUsdPerMtok: 36 },- });- expect(fetchMock).toHaveBeenCalledTimes(1);+ await expect(getModelPricing()).resolves.toBeNull();});- it('refreshes expired accounting prices even when the target model is already cached', async () => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-06-16T07:00:00.000Z'));- mocks.readClaudeApiKey.mockReturnValue('test-key');- await writeTestKeyFile();+ it('rejects malformed or non-gateway disk quotes', async () => {await mkdir(userDataPath('cache'), { recursive: true });await writeFile(userDataPath('cache', 'model-pricing.json'),JSON.stringify({- version: 2,- fetchedAt: Date.parse('2026-06-16T00:00:00.000Z'),- baseUrl: 'https://example.invalid',- cacheScope: await testCacheScope('user-a'),+ version: 3,+ scope: expectedScope(),+ fetchedAt: Date.now(),pricing: {- 'gpt-5.5': { inputUsdPerMtok: 5, outputUsdPerMtok: 30 },- },- }),- 'utf8',- );- const fetchMock = vi.fn().mockResolvedValueOnce({- ok: true,- json: async () => ({- data: [- {- model_group: 'gpt-5.5',- input_cost_per_token: 0.000006,- output_cost_per_token: 0.000036,+ xd: {+ bad: {+ providerId: 'xd',+ modelId: 'bad',+ currency: 'USD',+ source: 'subscription-reference',+ approximate: true,+ inputPerMtok: -1,+ outputPerMtok: 2,+ },},- ],- }),- });- vi.stubGlobal('fetch', fetchMock);-- await expect(getModelPricingForModel('gpt-5.5')).resolves.toMatchObject({- 'gpt-5.5': { inputUsdPerMtok: 6, outputUsdPerMtok: 36 },- });- expect(fetchMock).toHaveBeenCalledTimes(1);- });-- it('bypasses the generic failure cooldown when an accounting model is missing', async () => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-06-16T07:00:00.000Z'));- mocks.readClaudeApiKey.mockReturnValue('test-key');- await writeTestKeyFile();- await mkdir(userDataPath('cache'), { recursive: true });- await writeFile(- userDataPath('cache', 'model-pricing.json'),- JSON.stringify({- version: 2,- fetchedAt: Date.parse('2026-06-16T00:00:00.000Z'),- baseUrl: 'https://example.invalid',- cacheScope: await testCacheScope('user-a'),- pricing: {- 'gpt-5.5': { inputUsdPerMtok: 5, outputUsdPerMtok: 30 },},}),'utf8',);- const fetchMock = vi.fn()- .mockResolvedValueOnce({ ok: false, status: 502 })- .mockResolvedValueOnce({- ok: true,- json: async () => ({- data: [- {- model_group: 'gpt-5.6',- input_cost_per_token: 0.000006,- output_cost_per_token: 0.000036,- },- ],- }),- });- vi.stubGlobal('fetch', fetchMock);-- await prewarmModelPricing();- expect(fetchMock).toHaveBeenCalledTimes(1);-- vi.setSystemTime(new Date('2026-06-16T07:00:10.000Z'));- await expect(getModelPricingForModel('gpt-5.6')).resolves.toMatchObject({- 'gpt-5.6': { inputUsdPerMtok: 6, outputUsdPerMtok: 36 },- });- expect(fetchMock).toHaveBeenCalledTimes(2);+ await expect(getModelPricing()).resolves.toBeNull();});- it('does not cooldown accounting misses caused by transient refresh failures', async () => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-06-16T07:00:00.000Z'));- mocks.readClaudeApiKey.mockReturnValue('test-key');- await writeTestKeyFile();- await mkdir(userDataPath('cache'), { recursive: true });- await writeFile(- userDataPath('cache', 'model-pricing.json'),- JSON.stringify({- version: 2,- fetchedAt: Date.parse('2026-06-16T00:00:00.000Z'),- baseUrl: 'https://example.invalid',- cacheScope: await testCacheScope('user-a'),- pricing: {- 'gpt-5.5': { inputUsdPerMtok: 5, outputUsdPerMtok: 30 },- },- }),- 'utf8',- );- const fetchMock = vi.fn()- .mockResolvedValueOnce({ ok: false, status: 502 })- .mockResolvedValueOnce({- ok: true,- json: async () => ({- data: [- {- model_group: 'gpt-5.6',- input_cost_per_token: 0.000006,- output_cost_per_token: 0.000036,- },- ],- }),- });- vi.stubGlobal('fetch', fetchMock);-- await expect(getModelPricingForModel('gpt-5.6')).resolves.toMatchObject({- 'gpt-5.5': { inputUsdPerMtok: 5, outputUsdPerMtok: 30 },+ it('requires provider identity on accounting lookups', async () => {+ replaceGatewayModelPricing([+ {+ id: 'same-id',+ inputCostPerToken: 0.000001,+ outputCostPerToken: 0.000002,+ },+ ]);+ await expect(getModelPricingForModel('xd', 'same-id')).resolves.toMatchObject({+ xd: { 'same-id': { inputPerMtok: 1, outputPerMtok: 2 } },});- vi.setSystemTime(new Date('2026-06-16T07:00:10.000Z'));- await expect(getModelPricingForModel('gpt-5.6')).resolves.toMatchObject({- 'gpt-5.6': { inputUsdPerMtok: 6, outputUsdPerMtok: 36 },+ await expect(getModelPricingForModel('openai', 'same-id')).resolves.toMatchObject({+ xd: { 'same-id': { inputPerMtok: 1, outputPerMtok: 2 } },});- expect(fetchMock).toHaveBeenCalledTimes(2);});+});- it('does not apply retry cooldown when prewarm is skipped without a key', async () => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-06-16T00:00:00.000Z'));- mocks.readClaudeApiKey.mockReturnValue(null);- const fetchMock = vi.fn();- vi.stubGlobal('fetch', fetchMock);-- await prewarmModelPricing();- expect(fetchMock).not.toHaveBeenCalled();-- vi.setSystemTime(new Date('2026-06-16T00:00:10.000Z'));- mocks.readClaudeApiKey.mockReturnValue('test-key');- await writeTestKeyFile();- fetchMock.mockResolvedValueOnce({- ok: true,- json: async () => ({- data: [- {- model_group: 'gpt-5.6',- input_cost_per_token: 0.000006,- output_cost_per_token: 0.000036,- },- ],- }),- });-- await expect(getModelPricingForModel('gpt-5.6')).resolves.toMatchObject({- 'gpt-5.6': { inputUsdPerMtok: 6, outputUsdPerMtok: 36 },- });- expect(fetchMock).toHaveBeenCalledTimes(1);+describe('reference pricing helpers', () => {+ it('returns subscription reference quotes separately from the XD cache', () => {+ expect(getCodexSubscriptionValuePrice('gpt-5.5', null)).toMatchObject({+ providerId: 'openai',+ modelId: 'gpt-5.5',+ currency: 'USD',+ source: 'subscription-reference',+ approximate: true,+ inputPerMtok: 5,+ outputPerMtok: 30,+ cacheReadPerMtok: 0.5,+ });+ expect(getSubscriptionDirectValuePrice('chatgpt/gpt-5.5')).toMatchObject({+ providerId: 'openai',+ modelId: 'chatgpt/gpt-5.5',+ source: 'subscription-reference',+ });+ expect(getSubscriptionDirectValuePrice('unknown')).toBeUndefined();});- it('prewarms stale disk cache and refreshes it in the background startup path', async () => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-06-16T07:00:00.000Z'));- mocks.readClaudeApiKey.mockReturnValue('test-key');- await writeTestKeyFile();- await mkdir(userDataPath('cache'), { recursive: true });- await writeFile(- userDataPath('cache', 'model-pricing.json'),- JSON.stringify({- version: 2,- fetchedAt: Date.parse('2026-06-16T00:00:00.000Z'),- baseUrl: 'https://example.invalid',- cacheScope: await testCacheScope('user-a'),- pricing: {- 'claude-opus-4-8': { inputUsdPerMtok: 5, outputUsdPerMtok: 25 },- },- }),- 'utf8',- );- const fetchMock = vi.fn().mockResolvedValueOnce({- ok: true,- json: async () => ({- data: [- {- model_group: 'claude-opus-4-8',- input_cost_per_token: 0.000006,- output_cost_per_token: 0.00003,- },- ],- }),- });- vi.stubGlobal('fetch', fetchMock);-- await prewarmModelPricing();-- expect(fetchMock).toHaveBeenCalledTimes(1);- await expect(getModelPricing()).resolves.toMatchObject({- 'claude-opus-4-8': { inputUsdPerMtok: 6, outputUsdPerMtok: 30 },- });+ it('keeps codex budget multiplier isolated to codex/ routes', () => {+ expect(getCodexBudgetEffectiveCostMultiplier('codex/gpt-5.5')).toBe(0.15);+ expect(getCodexBudgetEffectiveCostMultiplier('gpt-5.5')).toBe(1);});});diff --git a/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts b/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.tsindex 904aa043ad..eaf1a75965 100644--- a/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts+++ b/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts@@ -1,30 +1,85 @@-/**- * turnCostCalculator.test.ts- * ---------------------------------------------------------------------------- * 单轮费用计算共享模块的纯函数单测 (HYBRID 策略):- * - normalizeModelIdForPricing: 剥 [1m]/变体后缀 → 与 gateway 价表对齐的裸 key- * - isAnthropicModel: claude-* / sonnet / haiku / opus- * - computeGatewayTurnCost: cache-aware; 无 cache 档价时锁旧 estimateCodexCost 算式- * - resolveTurnCost: Anthropic→一律信任 SDK; 非 Anthropic→gateway 价 (查不到→SDK 兜底); codex/ 不二次折扣- */-import { describe, expect, it } from 'vitest';-// turnCostCalculator 是零 host 依赖的纯模块 (codex/ 折扣常量也定义在本模块内),-// 无需 mock logger / auth-adapters / runtime-configs。+import type { ModelUsageDeltaEntry } from '../modelUsageDelta';import {buildClaudeTurnUsageDetails,computeGatewayTurnCost,estimateClaudeSubscriptionTurnValue,+ getCodexBudgetEffectiveCostMultiplier,isAnthropicModel,normalizeModelIdForPricing,resolveClaudeTurnCostSinks,resolveTurnCost,type ResolvedModelCost,+ type TurnPricingContext,} from '../turnCostCalculator';-import type { ModelUsageDeltaEntry } from '../modelUsageDelta';+import type {+ ModelPriceQuote,+ ModelPricingCatalog,+ RegionalMoney,+} from '../../../shared/regionalMoney';++const XD_GLOBAL: TurnPricingContext = {+ providerId: 'xd',+ billingRoute: 'xd-gateway',+ region: 'global',+};+const PROVIDER_CN: TurnPricingContext = {+ providerId: 'anthropic',+ billingRoute: 'provider-api',+ region: 'cn',+};+const SUBSCRIPTION_GLOBAL: TurnPricingContext = {+ providerId: 'anthropic',+ billingRoute: 'subscription',+ region: 'global',+};++function quote(+ modelId: string,+ inputPerMtok: number,+ outputPerMtok: number,+ overrides: Partial<ModelPriceQuote> = {},+): ModelPriceQuote {+ return {+ providerId: 'xd',+ modelId,+ currency: 'USD',+ source: 'gateway',+ approximate: false,+ inputPerMtok,+ outputPerMtok,+ ...overrides,+ };+}++function catalog(...quotes: ModelPriceQuote[]): ModelPricingCatalog {+ const result: ModelPricingCatalog = {};+ for (const item of quotes) {+ (result[item.providerId] ??= {})[item.modelId] = item;+ }+ return result;+}-function delta(model: string, p: Partial<ModelUsageDeltaEntry> = {}): ModelUsageDeltaEntry {+function usdMoney(+ amount: number,+ kind: RegionalMoney['kind'] = 'actual-cost',+): RegionalMoney {+ return {+ amount,+ currency: 'USD',+ approximate: kind === 'value-estimate',+ kind,+ ...(kind === 'value-estimate'+ ? { estimateReasons: ['subscription-value'] }+ : {}),+ };+}++function delta(+ model: string,+ values: Partial<ModelUsageDeltaEntry> = {},+): ModelUsageDeltaEntry {return {model,costUsdDelta: 0,@@ -32,358 +87,301 @@ function delta(model: string, p: Partial<ModelUsageDeltaEntry> = {}): ModelUsageoutputTokensDelta: 0,cacheReadTokensDelta: 0,cacheCreateTokensDelta: 0,- ...p,+ ...values,};}-function modelCost(model: string, costUsd: number): ResolvedModelCost {- return { model, costUsd, source: 'sdk', deltas: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0 } };+function resolvedModel(+ model: string,+ deltas: Partial<ResolvedModelCost['deltas']> = {},+ money: RegionalMoney | null = null,+): ResolvedModelCost {+ return {+ model,+ money,+ source: 'subscription',+ deltas: {+ inputTokens: 0,+ outputTokens: 0,+ cacheReadTokens: 0,+ cacheCreateTokens: 0,+ ...deltas,+ },+ };}-describe('normalizeModelIdForPricing', () => {- it('剥掉尾部 [1m]/变体后缀, 保留 codex/ 前缀', () => {+describe('model id and route helpers', () => {+ it('normalizes model suffixes without dropping provider prefixes', () => {expect(normalizeModelIdForPricing('gpt-5.5[1m]')).toBe('gpt-5.5');expect(normalizeModelIdForPricing('codex/gpt-5.5[1m]')).toBe('codex/gpt-5.5');- expect(normalizeModelIdForPricing('claude-opus-4-8[1m]')).toBe('claude-opus-4-8');- expect(normalizeModelIdForPricing('sonnet[1m]')).toBe('sonnet');- expect(normalizeModelIdForPricing('z-ai/glm-5.2[1m]')).toBe('z-ai/glm-5.2');- });-- it('无后缀原样返回; 空 / nullish → unknown', () => {- expect(normalizeModelIdForPricing('gpt-5.5')).toBe('gpt-5.5');expect(normalizeModelIdForPricing(' claude-opus-4-8 ')).toBe('claude-opus-4-8');expect(normalizeModelIdForPricing('')).toBe('unknown');expect(normalizeModelIdForPricing(null)).toBe('unknown');- expect(normalizeModelIdForPricing(undefined)).toBe('unknown');});-});-describe('isAnthropicModel', () => {- it('claude-* / sonnet / haiku / opus → true', () => {- expect(isAnthropicModel('claude-opus-4-8')).toBe(true);- expect(isAnthropicModel('claude-fable-5')).toBe(true);+ it('recognizes Anthropic families and applies codex budget discount exactly once', () => {+ expect(isAnthropicModel('claude-sonnet-4-6')).toBe(true);expect(isAnthropicModel('sonnet')).toBe(true);- expect(isAnthropicModel('haiku')).toBe(true);- });- it('gateway-routed 非 Anthropic → false', () => {expect(isAnthropicModel('gpt-5.5')).toBe(false);- expect(isAnthropicModel('codex/gpt-5.5')).toBe(false);- expect(isAnthropicModel('qwen/qwen3.7-max')).toBe(false);- expect(isAnthropicModel('z-ai/glm-5.2')).toBe(false);+ expect(getCodexBudgetEffectiveCostMultiplier('codex/gpt-5.5')).toBe(0.15);+ expect(getCodexBudgetEffectiveCostMultiplier('gpt-5.5')).toBe(1);});});describe('computeGatewayTurnCost', () => {- const zero = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0 };-- it('无 price → null (绝不返 0)', () => {- expect(computeGatewayTurnCost({ ...zero, inputTokens: 1000 }, undefined)).toBeNull();- });-- it('纯 input/output 折算', () => {- const cost = computeGatewayTurnCost(- { ...zero, inputTokens: 1_099_022, outputTokens: 2_319 },- { inputUsdPerMtok: 2, outputUsdPerMtok: 8 },- );- expect(cost).toBeCloseTo((1_099_022 * 2 + 2_319 * 8) / 1e6, 6);- });-- it('无 cache 档价时 cacheRead 按 input 价计 (锁旧 estimateCodexCost 算式)', () => {- const cost = computeGatewayTurnCost(- { inputTokens: 1_000_000, outputTokens: 1_000_000, cacheReadTokens: 1_000_000, cacheCreateTokens: 0 },- { inputUsdPerMtok: 2, outputUsdPerMtok: 8 },- );- // (1M + 1M)*2 + 1M*8 = 12- expect(cost).toBeCloseTo(12, 6);+ it('returns null without a quote and uses input price for missing cache tiers', () => {+ const tokens = {+ inputTokens: 1_000_000,+ outputTokens: 1_000_000,+ cacheReadTokens: 1_000_000,+ cacheCreateTokens: 1_000_000,+ };+ expect(computeGatewayTurnCost(tokens, undefined)).toBeNull();+ expect(computeGatewayTurnCost(tokens, quote('m', 2, 8))).toBe(14);});- it('有 cache 档价时按档价计', () => {- const cost = computeGatewayTurnCost(- { inputTokens: 1_000_000, outputTokens: 1_000_000, cacheReadTokens: 1_000_000, cacheCreateTokens: 1_000_000 },- { inputUsdPerMtok: 2, outputUsdPerMtok: 8, cacheReadUsdPerMtok: 0.2, cacheCreateUsdPerMtok: 2.5 },- );- // 2 + 8 + 0.2 + 2.5- expect(cost).toBeCloseTo(12.7, 6);+ it('uses explicit cache read/write prices when present', () => {+ expect(computeGatewayTurnCost(+ {+ inputTokens: 1_000_000,+ outputTokens: 1_000_000,+ cacheReadTokens: 1_000_000,+ cacheCreateTokens: 1_000_000,+ },+ quote('m', 2, 8, {+ cacheReadPerMtok: 0.2,+ cacheCreatePerMtok: 2.5,+ }),+ )).toBeCloseTo(12.7);});});describe('resolveTurnCost', () => {- it('非 Anthropic + 有 gateway 价 → 用 gateway 价, 丢弃 SDK 数字; 返回归一化 id', () => {- const res = resolveTurnCost({+ it('XD route uses provider-scoped gateway pricing for every model family', () => {+ const pricing = catalog(+ quote('gpt-5.5', 2, 8),+ quote('claude-opus-4-8', 5, 25),+ );+ const gpt = resolveTurnCost({rawModel: 'gpt-5.5[1m]',- tokens: { inputTokens: 1_099_022, outputTokens: 2_319, cacheReadTokens: 0, cacheCreateTokens: 0 },- sdkCostDelta: 5.553085, // SDK 按 Opus 误算- pricing: { 'gpt-5.5': { inputUsdPerMtok: 2, outputUsdPerMtok: 8 } },- });- expect(res.source).toBe('gateway');- expect(res.model).toBe('gpt-5.5');- expect(res.costUsd).toBeCloseTo(2.216596, 5);- expect(res.costUsd).not.toBeCloseTo(5.553085, 2);- });-- it('codex/ 已折价的 map 不再二次打折', () => {- const res = resolveTurnCost({- rawModel: 'codex/gpt-5.5',- tokens: { inputTokens: 1_000_000, outputTokens: 1_000_000, cacheReadTokens: 0, cacheCreateTokens: 0 },- pricing: { 'codex/gpt-5.5': { inputUsdPerMtok: 0.3, outputUsdPerMtok: 1.2 } },+ tokens: {+ inputTokens: 1_099_022,+ outputTokens: 2_319,+ cacheReadTokens: 0,+ cacheCreateTokens: 0,+ },+ sdkCostDelta: 5.553085,+ pricing,+ context: XD_GLOBAL,});- // 0.3 + 1.2 = 1.5, 不是再 ×0.15 的 0.225- expect(res.costUsd).toBeCloseTo(1.5, 6);- });-- it('Anthropic → 一律信任 SDK, 忽略 gateway 价 (即便价表里有)', () => {- const res = resolveTurnCost({+ const claude = resolveTurnCost({rawModel: 'claude-opus-4-8[1m]',- tokens: { inputTokens: 100, outputTokens: 200, cacheReadTokens: 844_436, cacheCreateTokens: 5_000 },- sdkCostDelta: 3.08,- pricing: { 'claude-opus-4-8': { inputUsdPerMtok: 5, outputUsdPerMtok: 25 } },+ tokens: {+ inputTokens: 1_000_000,+ outputTokens: 0,+ cacheReadTokens: 0,+ cacheCreateTokens: 0,+ },+ sdkCostDelta: 99,+ pricing,+ context: XD_GLOBAL,});- expect(res.source).toBe('sdk');- expect(res.model).toBe('claude-opus-4-8');- expect(res.costUsd).toBeCloseTo(3.08, 6);- // 若误用 gateway input 价计 cacheRead 会 >$4, 远高于真实 $3.08。- expect(res.costUsd).toBeLessThan(4);- });- it('Anthropic + OAuth (SDK cost=0) → 记 0, 不把订阅价值混进 daily_spend', () => {- const res = resolveTurnCost({- rawModel: 'claude-opus-4-8[1m]',- tokens: { inputTokens: 1_000_000, outputTokens: 2_000, cacheReadTokens: 0, cacheCreateTokens: 0 },- sdkCostDelta: 0, // OAuth 订阅模式下 SDK 不报 API cost- pricing: { 'claude-opus-4-8': { inputUsdPerMtok: 5, outputUsdPerMtok: 25 } },- });- expect(res.source).toBe('sdk');- expect(res.costUsd).toBe(0);+ expect(gpt.source).toBe('gateway');+ expect(gpt.money?.amount).toBeCloseTo(2.216596, 5);+ expect(claude.source).toBe('gateway');+ expect(claude.money?.amount).toBe(5);});- it('非 Anthropic 查不到价 → 回退 SDK 数字 (别丢账); 非 codex/ 不打折', () => {- const res = resolveTurnCost({- rawModel: 'mystery-model[1m]',- tokens: { inputTokens: 1000, outputTokens: 100, cacheReadTokens: 0, cacheCreateTokens: 0 },+ it('XD missing price does not revive an SDK guess', () => {+ const result = resolveTurnCost({+ rawModel: 'unknown-model',+ tokens: {+ inputTokens: 1_000,+ outputTokens: 100,+ cacheReadTokens: 0,+ cacheCreateTokens: 0,+ },sdkCostDelta: 1.23,pricing: {},+ context: XD_GLOBAL,});- expect(res.source).toBe('sdk-fallback');- expect(res.costUsd).toBeCloseTo(1.23, 6);+ expect(result.source).toBe('sdk-fallback');+ expect(result.money).toBeNull();});- it('codex/ 预算模型查不到 gateway 价 → SDK 兜底仍补 0.15 折扣 (与窄兜底口径一致)', () => {- const res = resolveTurnCost({- rawModel: 'codex/gpt-5.5[1m]',- tokens: { inputTokens: 1_000_000, outputTokens: 2_000, cacheReadTokens: 0, cacheCreateTokens: 0 },- sdkCostDelta: 5.05, // SDK 按 Anthropic Opus 误算, 且未含 codex/ 0.15 折扣- pricing: {}, // gateway 冷启动 / 缺该行+ it('provider API route keeps SDK USD fact and regionalizes it for CN', () => {+ const result = resolveTurnCost({+ rawModel: 'claude-opus-4-8',+ tokens: {+ inputTokens: 0,+ outputTokens: 0,+ cacheReadTokens: 0,+ cacheCreateTokens: 0,+ },+ sdkCostDelta: 3,+ pricing: catalog(quote('claude-opus-4-8', 99, 99)),+ context: PROVIDER_CN,});- expect(res.source).toBe('sdk-fallback');- expect(res.model).toBe('codex/gpt-5.5');- // gateway 价路径已折好 0.15、SDK 兜底路径补乘一次 —— 二者口径对齐, 不双重打折。- expect(res.costUsd).toBeCloseTo(5.05 * 0.15, 6);- });-- it('非 Anthropic 查不到价且无 SDK 数字 → 0 (调用方据阈值跳过)', () => {- const res = resolveTurnCost({- rawModel: 'mystery-model',- tokens: { inputTokens: 1000, outputTokens: 100, cacheReadTokens: 0, cacheCreateTokens: 0 },- pricing: null,+ expect(result.source).toBe('sdk');+ expect(result.money).toMatchObject({+ amount: 20.1,+ currency: 'CNY',+ approximate: true,+ kind: 'actual-cost',});- expect(res.costUsd).toBe(0);- expect(res.source).toBe('sdk-fallback');+ expect(result.money?.estimateReasons).toContain('fixed-fx');});- it('订阅直连 chatgpt/ → cost 0, source subscription (不进真实计费), 无视 SDK 误算', () => {- const res = resolveTurnCost({- rawModel: 'chatgpt/gpt-5.5[1m]',- tokens: { inputTokens: 1_000_000, outputTokens: 5_000, cacheReadTokens: 0, cacheCreateTokens: 0 },- sdkCostDelta: 5.0, // SDK 按 Anthropic 误算, 但订阅轮不计费- pricing: { 'gpt-5.5': { inputUsdPerMtok: 2, outputUsdPerMtok: 8 } }, // 即便有裸 gpt-5.5 价也不采用+ it('codex provider SDK fallback applies the 15% multiplier once', () => {+ const result = resolveTurnCost({+ rawModel: 'codex/gpt-5.5',+ tokens: {+ inputTokens: 0,+ outputTokens: 0,+ cacheReadTokens: 0,+ cacheCreateTokens: 0,+ },+ sdkCostDelta: 10,+ pricing: null,+ context: { ...PROVIDER_CN, region: 'global' },});- expect(res.source).toBe('subscription');- expect(res.model).toBe('chatgpt/gpt-5.5');- expect(res.costUsd).toBe(0);+ expect(result.money?.amount).toBe(1.5);});- it('订阅直连 xai/ → cost 0, source subscription', () => {- const res = resolveTurnCost({- rawModel: 'xai/grok-4.3',- tokens: { inputTokens: 500_000, outputTokens: 3_000, cacheReadTokens: 0, cacheCreateTokens: 0 },- sdkCostDelta: 2.5,- pricing: {},+ it('subscription routes and explicit subscription model prefixes never become actual cost', () => {+ const byRoute = resolveTurnCost({+ rawModel: 'claude-opus-4-8',+ tokens: {+ inputTokens: 1_000_000,+ outputTokens: 0,+ cacheReadTokens: 0,+ cacheCreateTokens: 0,+ },+ sdkCostDelta: 5,+ pricing: null,+ context: SUBSCRIPTION_GLOBAL,});- expect(res.source).toBe('subscription');- expect(res.costUsd).toBe(0);- });-- it('真网关裸 gpt-5.5(无前缀)不被订阅 gate 误伤, 照常按 gateway 价计费', () => {- const res = resolveTurnCost({- rawModel: 'gpt-5.5',- tokens: { inputTokens: 1_000_000, outputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0 },- sdkCostDelta: 5.0,- pricing: { 'gpt-5.5': { inputUsdPerMtok: 2, outputUsdPerMtok: 8 } },+ const byPrefix = resolveTurnCost({+ rawModel: 'chatgpt/gpt-5.5',+ tokens: {+ inputTokens: 1_000_000,+ outputTokens: 0,+ cacheReadTokens: 0,+ cacheCreateTokens: 0,+ },+ sdkCostDelta: 5,+ pricing: null,+ context: { ...PROVIDER_CN, region: 'global' },});- expect(res.source).toBe('gateway');- expect(res.costUsd).toBeCloseTo(2, 6);+ expect(byRoute).toMatchObject({ source: 'subscription', money: null });+ expect(byPrefix).toMatchObject({ source: 'subscription', money: null });});});-describe('resolveClaudeTurnCostSinks — 订阅轮排除', () => {- it('同一 done 的主 agent 与付费 subagent 一并计入消息分段成本', () => {- const { turnTotalUsd, perModel } = resolveClaudeTurnCostSinks(- [- // 真实 Claude modelUsage 会同时带主模型与 Task/subagent 模型。- delta('claude-fable-5', { costUsdDelta: 14.226789 }),- delta('claude-opus-4-8[1m]', { costUsdDelta: 0.57519775 }),- ],- null,+describe('resolveClaudeTurnCostSinks', () => {+ it('sums structured per-model money using one billing route', () => {+ const pricing = catalog(+ quote('claude-opus-4-8', 5, 25),+ quote('gpt-5.5', 2, 8),);- expect(turnTotalUsd).toBeCloseTo(14.80198675, 8);- expect(perModel).toMatchObject([- { model: 'claude-fable-5', costUsd: 14.226789 },- { model: 'claude-opus-4-8', costUsd: 0.57519775 },- ]);- });-- it('主 Anthropic + 子 agent 走 bridge(chatgpt/): turnTotal 只含 Anthropic, 订阅轮 cost 0', () => {- const { turnTotalUsd, perModel } = resolveClaudeTurnCostSinks(+ const result = resolveClaudeTurnCostSinks([- // 主会话 opus: 信任 SDK cost- delta('claude-opus-4-8[1m]', { inputTokensDelta: 100, outputTokensDelta: 800, costUsdDelta: 0.94 }),- // 子 agent 走订阅 grok: 不计费- delta('xai/grok-4.3', { inputTokensDelta: 500_000, outputTokensDelta: 3_000, costUsdDelta: 2.5 }),- // 子 agent 走订阅 gpt-5.5(带前缀): 不计费- delta('chatgpt/gpt-5.5', { inputTokensDelta: 1_000_000, outputTokensDelta: 5_000, costUsdDelta: 5.0 }),+ delta('claude-opus-4-8[1m]', { inputTokensDelta: 1_000_000 }),+ delta('gpt-5.5[1m]', { inputTokensDelta: 1_000_000 }),],- { 'gpt-5.5': { inputUsdPerMtok: 2, outputUsdPerMtok: 8 } },+ pricing,+ XD_GLOBAL,);- // 总额只含 opus 的 SDK cost, 订阅轮 0- expect(turnTotalUsd).toBeCloseTo(0.94, 6);- const bySource = Object.fromEntries(perModel.map((m) => [m.model, m]));- expect(bySource['xai/grok-4.3'].costUsd).toBe(0);- expect(bySource['xai/grok-4.3'].source).toBe('subscription');- expect(bySource['chatgpt/gpt-5.5'].costUsd).toBe(0);- expect(bySource['chatgpt/gpt-5.5'].source).toBe('subscription');- expect(bySource['claude-opus-4-8'].costUsd).toBeCloseTo(0.94, 6);- });-});--describe('buildClaudeTurnUsageDetails', () => {- // 主 agent (opus) + subagent (haiku) 一轮, 顶层 usage 只反映主线程。- const usage = { input_tokens: 2, output_tokens: 28, cache_read_input_tokens: 152_730, cache_creation_input_tokens: 1_149 };- const deltas: ModelUsageDeltaEntry[] = [- delta('claude-opus-4-8[1m]', { inputTokensDelta: 100, outputTokensDelta: 800, cacheReadTokensDelta: 150_000, cacheCreateTokensDelta: 1_000, costUsdDelta: 0.94 }),- delta('claude-haiku-4-5-20251001', { inputTokensDelta: 33, outputTokensDelta: 9_099, cacheReadTokensDelta: 5_139_380, cacheCreateTokensDelta: 250_573, costUsdDelta: 0.80 }),- ];-- it('Part A: 有 deltas 时 input/output/cache 全部从 delta 求和 (含 subagent), 不取顶层 usage', () => {- const d = buildClaudeTurnUsageDetails(usage, deltas, 'unknown');- expect(d).not.toBeNull();- // 顶层 usage.output=28 被忽略, 用 delta 求和 800+9099 (含 haiku subagent 输出)。- expect(d!.inputTokens).toBe(133);- expect(d!.outputTokens).toBe(9_899);- expect(d!.cacheReadTokens).toBe(5_289_380);- expect(d!.cacheCreateTokens).toBe(251_573);- expect(d!.models).toEqual(['claude-opus-4-8[1m]', 'claude-haiku-4-5-20251001']);- });-- it('Part B: perModel → perModelCost (保留 cost>0, 含 subagent 模型)', () => {- const perModel = [modelCost('claude-opus-4-8', 0.94), modelCost('claude-haiku-4-5-20251001', 0.80)];- const d = buildClaudeTurnUsageDetails(usage, deltas, 'unknown', perModel);- expect(d!.perModelCost).toEqual([- { model: 'claude-opus-4-8', costUsd: 0.94 },- { model: 'claude-haiku-4-5-20251001', costUsd: 0.80 },- ]);- });-- it('Part B: 过滤掉 cost<=0 的模型项', () => {- const perModel = [modelCost('claude-opus-4-8', 0.94), modelCost('claude-haiku-4-5-20251001', 0)];- const d = buildClaudeTurnUsageDetails(usage, deltas, 'unknown', perModel);- expect(d!.perModelCost).toEqual([{ model: 'claude-opus-4-8', costUsd: 0.94 }]);- });-- it('未传 perModel → 无 perModelCost', () => {- const d = buildClaudeTurnUsageDetails(usage, deltas, 'unknown');- expect(d!.perModelCost).toBeUndefined();- });-- it('窄兜底 (无 deltas) → input/output/cache 回退顶层 usage, model 用 fallback, 无 perModelCost', () => {- const d = buildClaudeTurnUsageDetails(usage, undefined, 'claude-opus-4-8');- expect(d!.inputTokens).toBe(2);- expect(d!.outputTokens).toBe(28);- expect(d!.cacheReadTokens).toBe(152_730);- expect(d!.model).toBe('claude-opus-4-8');- expect(d!.perModelCost).toBeUndefined();+ 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('单模型轮 → model 取该模型, models 仍为单元素', () => {- const single = [delta('claude-opus-4-8[1m]', { inputTokensDelta: 10, outputTokensDelta: 20, costUsdDelta: 0.1 })];- const d = buildClaudeTurnUsageDetails(usage, single, 'unknown', [modelCost('claude-opus-4-8', 0.1)]);- expect(d!.model).toBe('claude-opus-4-8[1m]');- expect(d!.perModelCost).toEqual([{ model: 'claude-opus-4-8', costUsd: 0.1 }]);- });-});--describe('estimateClaudeSubscriptionTurnValue (Claude 订阅"本轮价值"估算)', () => {- function subscriptionModel(- model: string,- deltas: Partial<ResolvedModelCost['deltas']> = {},- costUsd = 0,- ): ResolvedModelCost {- return {- model,- costUsd,- source: 'sdk',- deltas: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0, ...deltas },- };- }-- it('用网关价表精确条目估值 (cache-aware)', () => {- const pricing = {- 'claude-fable-5': {- inputUsdPerMtok: 10, outputUsdPerMtok: 50,- cacheReadUsdPerMtok: 1, cacheCreateUsdPerMtok: 12.5,- },- };- const value = estimateClaudeSubscriptionTurnValue(- [subscriptionModel('claude-fable-5', { inputTokens: 1_000_000, outputTokens: 100_000, cacheReadTokens: 2_000_000 })],- pricing,+ it('returns null total when the route is subscription-only', () => {+ const result = resolveClaudeTurnCostSinks(+ [delta('claude-opus-4-8', { costUsdDelta: 4 })],+ null,+ SUBSCRIPTION_GLOBAL,);- // 1M×$10 + 0.1M×$50 + 2M×$1 = 10 + 5 + 2 = 17- expect(value).toBeCloseTo(17, 6);+ expect(result.turnMoney).toBeNull();+ expect(result.perModel[0]).toMatchObject({+ source: 'subscription',+ money: null,+ });});+});- it('网关价表缺失时回退家族牌价 (纯 Anthropic 轮 pricing=null 不发网络请求的路径)', () => {+describe('subscription value and usage details', () => {+ it('estimates Anthropic subscription value from reference pricing and regionalizes CN', () => {const value = estimateClaudeSubscriptionTurnValue(- [subscriptionModel('claude-opus-4-8', { inputTokens: 1_000_000, outputTokens: 200_000 })],- null,+ [+ resolvedModel('claude-opus-4-8', {+ inputTokens: 1_000_000,+ outputTokens: 200_000,+ }),+ ],+ 'cn',);- // Opus 家族牌价: 1M×$5 + 0.2M×$25 = 5 + 5 = 10- expect(value).toBeCloseTo(10, 6);+ expect(value).toMatchObject({+ amount: 67,+ currency: 'CNY',+ approximate: true,+ kind: 'value-estimate',+ });});- it('只对 SDK cost=0 的 Anthropic 模型估值; 真实计费 / 非 Anthropic / 未知家族跳过', () => {+ it('does not estimate non-Anthropic, already-costed, unknown, or zero-token entries', () => {expect(estimateClaudeSubscriptionTurnValue([- subscriptionModel('claude-opus-4-8', { inputTokens: 1_000_000 }, 0.5), // 真实 API 账单, 跳过- subscriptionModel('gpt-5.5', { inputTokens: 1_000_000 }), // 非 Anthropic, 跳过- subscriptionModel('claude-unknown-model-9', { inputTokens: 1_000_000 }),// 无家族牌价, 跳过+ 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 }),],- null,+ 'global',+ )).toBeNull();+ expect(estimateClaudeSubscriptionTurnValue(+ [resolvedModel('claude-opus-4-8')],+ 'global',)).toBeNull();});- it('多模型订阅轮 (主线程 Fable + subagent Haiku) 求和', () => {- const value = estimateClaudeSubscriptionTurnValue(+ it('builds token totals and structured per-model costs from model deltas', () => {+ const deltas = [+ delta('claude-opus-4-8', {+ inputTokensDelta: 100,+ outputTokensDelta: 800,+ cacheReadTokensDelta: 1_000,+ }),+ delta('claude-haiku-4-5', {+ inputTokensDelta: 33,+ outputTokensDelta: 9_099,+ cacheCreateTokensDelta: 250,+ }),+ ];+ const details = buildClaudeTurnUsageDetails(+ { input_tokens: 1, output_tokens: 2 },+ deltas,+ 'fallback',[- subscriptionModel('claude-fable-5', { outputTokens: 100_000 }),- subscriptionModel('claude-haiku-4-5-20251001', { inputTokens: 1_000_000 }),+ resolvedModel('claude-opus-4-8', {}, usdMoney(0.94)),+ resolvedModel('claude-haiku-4-5', {}, usdMoney(0.8)),],- null,);- // Fable: 0.1M×$50 = 5; Haiku: 1M×$1 = 1- expect(value).toBeCloseTo(6, 6);- });-- it('零 token 轮 → null (不显示 $0.00)', () => {- expect(estimateClaudeSubscriptionTurnValue([subscriptionModel('claude-fable-5')], null)).toBeNull();- expect(estimateClaudeSubscriptionTurnValue([], null)).toBeNull();+ expect(details).toMatchObject({+ inputTokens: 133,+ outputTokens: 9_899,+ cacheReadTokens: 1_000,+ cacheCreateTokens: 250,+ models: ['claude-opus-4-8', 'claude-haiku-4-5'],+ });+ expect(details?.perModelCost).toEqual([+ { model: 'claude-opus-4-8', money: usdMoney(0.94) },+ { model: 'claude-haiku-4-5', money: usdMoney(0.8) },+ ]);});});diff --git a/apps/desktop/src/main/usage/__tests__/turnCostRouting.test.ts b/apps/desktop/src/main/usage/__tests__/turnCostRouting.test.tsindex 23193d69d0..34456fa4f2 100644--- a/apps/desktop/src/main/usage/__tests__/turnCostRouting.test.ts+++ b/apps/desktop/src/main/usage/__tests__/turnCostRouting.test.ts@@ -1,100 +1,100 @@-/**- * turnCostRouting.test.ts- * ---------------------------------------------------------------------------- * 回归: claude-code done 的整段费用推导 (resolveClaudeTurnCostSinks)。- *- * 头号 bug: gpt-5.5 走 claude-code 时 SDK 的 total_cost_usd 按 Anthropic Opus- * ($5/$25) 误算 (实测 1,099,022 in + 2,319 out 报 $5.553085)。HYBRID 修复后:- * 非 Anthropic 用 gateway 价 ($2/$8) ≈ $2.22; Anthropic 一律信任 SDK- * (OAuth=0 / API=真实), daily_model_usage 的 key 写归一化裸 id。- */-import { describe, expect, it } from 'vitest';import type { ModelUsageDeltaEntry } from '../modelUsageDelta';import { resolveClaudeTurnCostSinks } from '../turnCostCalculator';+import type {+ ModelPriceQuote,+ ModelPricingCatalog,+} from '../../../shared/regionalMoney';-function delta(over: Partial<ModelUsageDeltaEntry> & { model: string }): ModelUsageDeltaEntry {+function delta(values: Partial<ModelUsageDeltaEntry> & { model: string }): ModelUsageDeltaEntry {return {costUsdDelta: 0,inputTokensDelta: 0,outputTokensDelta: 0,cacheReadTokensDelta: 0,cacheCreateTokensDelta: 0,- ...over,+ ...values,};}-describe('resolveClaudeTurnCostSinks — gpt-5.5 错价回归', () => {- it('用 gateway 价重算 ($2/$8), 丢弃 SDK 的 Opus 价 ($5.55); key 归一化', () => {- const deltas = [- delta({- model: 'gpt-5.5[1m]',- costUsdDelta: 5.553085, // SDK 按 Opus 误算- inputTokensDelta: 1_099_022,- outputTokensDelta: 2_319,- }),- ];- const pricing = { 'gpt-5.5': { inputUsdPerMtok: 2, outputUsdPerMtok: 8 } };-- const { turnTotalUsd, perModel } = resolveClaudeTurnCostSinks(deltas, pricing);-- expect(turnTotalUsd).toBeCloseTo(2.216596, 5);- expect(turnTotalUsd).not.toBeCloseTo(5.553085, 2);- expect(perModel).toHaveLength(1);- expect(perModel[0].model).toBe('gpt-5.5'); // daily_model_usage 写裸 id- expect(perModel[0].costUsd).toBeCloseTo(2.216596, 5);- expect(perModel[0].source).toBe('gateway');- });-});--describe('resolveClaudeTurnCostSinks — Anthropic 信任 SDK (不高估、OAuth 安全)', () => {- it('Opus 缓存重的轮次直接用 SDK cost, 不被 gateway input 价高估', () => {- const deltas = [- delta({- model: 'claude-opus-4-8[1m]',- costUsdDelta: 3.08, // SDK cache-correct- inputTokensDelta: 100,- outputTokensDelta: 200,- cacheReadTokensDelta: 844_436,- cacheCreateTokensDelta: 5_000,- }),- ];- const pricing = { 'claude-opus-4-8': { inputUsdPerMtok: 5, outputUsdPerMtok: 25 } };+function quote(modelId: string, inputPerMtok: number, outputPerMtok: number): ModelPriceQuote {+ return {+ providerId: 'xd',+ modelId,+ currency: 'USD',+ source: 'gateway',+ approximate: false,+ inputPerMtok,+ outputPerMtok,+ };+}- const { turnTotalUsd, perModel } = resolveClaudeTurnCostSinks(deltas, pricing);+function pricing(...values: ModelPriceQuote[]): ModelPricingCatalog {+ return {+ xd: Object.fromEntries(values.map((value) => [value.modelId, value])),+ };+}- expect(turnTotalUsd).toBeCloseTo(3.08, 6);- expect(turnTotalUsd).toBeLessThan(4);- expect(perModel[0].model).toBe('claude-opus-4-8');- expect(perModel[0].source).toBe('sdk');- });+describe('turn cost routing regression', () => {+ it('XD route ignores the SDK model-family guess and prices every model from its gateway quote', () => {+ const result = resolveClaudeTurnCostSinks(+ [+ delta({+ model: 'gpt-5.5[1m]',+ costUsdDelta: 5.553085,+ inputTokensDelta: 1_099_022,+ outputTokensDelta: 2_319,+ }),+ delta({+ model: 'claude-opus-4-8[1m]',+ costUsdDelta: 99,+ inputTokensDelta: 1_000_000,+ }),+ ],+ pricing(+ quote('gpt-5.5', 2, 8),+ quote('claude-opus-4-8', 5, 25),+ ),+ {+ providerId: 'xd',+ billingRoute: 'xd-gateway',+ region: 'global',+ },+ );- it('OAuth 订阅 (SDK cost=0) → Anthropic 记 0, 不混进真实 spend', () => {- const deltas = [- delta({ model: 'claude-opus-4-8[1m]', costUsdDelta: 0, inputTokensDelta: 1_000_000, outputTokensDelta: 2_000 }),- ];- const pricing = { 'claude-opus-4-8': { inputUsdPerMtok: 5, outputUsdPerMtok: 25 } };- const { turnTotalUsd } = resolveClaudeTurnCostSinks(deltas, pricing);- expect(turnTotalUsd).toBe(0);+ expect(result.perModel[0]).toMatchObject({+ model: 'gpt-5.5',+ source: 'gateway',+ });+ expect(result.perModel[0].money?.amount).toBeCloseTo(2.216596, 5);+ expect(result.perModel[1]).toMatchObject({+ model: 'claude-opus-4-8',+ source: 'gateway',+ });+ expect(result.perModel[1].money?.amount).toBe(5);+ expect(result.turnMoney?.amount).toBeCloseTo(7.216596, 5);});-});--describe('resolveClaudeTurnCostSinks — 多模型加总', () => {- it('turnTotal = 各模型加总; Anthropic 走 SDK, 非 Anthropic 走 gateway', () => {- const deltas = [- delta({ model: 'claude-opus-4-8[1m]', costUsdDelta: 1.5, inputTokensDelta: 10, cacheReadTokensDelta: 100_000 }),- delta({ model: 'gpt-5.5[1m]', costUsdDelta: 9.99, inputTokensDelta: 1_000_000, outputTokensDelta: 0 }),- ];- const pricing = {- 'claude-opus-4-8': { inputUsdPerMtok: 5, outputUsdPerMtok: 25 },- 'gpt-5.5': { inputUsdPerMtok: 2, outputUsdPerMtok: 8 },- };- const { turnTotalUsd, perModel } = resolveClaudeTurnCostSinks(deltas, pricing);+ it('provider API route uses SDK USD and CN marks the converted total approximate', () => {+ const result = resolveClaudeTurnCostSinks(+ [+ delta({ model: 'claude-opus-4-8', costUsdDelta: 1.5 }),+ delta({ model: 'mystery-model', costUsdDelta: 2 }),+ ],+ null,+ {+ providerId: 'anthropic',+ billingRoute: 'provider-api',+ region: 'cn',+ },+ );- expect(perModel[0].costUsd).toBeCloseTo(1.5, 6); // opus SDK- expect(perModel[1].costUsd).toBeCloseTo(2.0, 6); // gpt-5.5 gateway 1M*2/1e6- expect(turnTotalUsd).toBeCloseTo(3.5, 6);+ expect(result.turnMoney).toMatchObject({+ currency: 'CNY',+ approximate: true,+ });+ expect(result.turnMoney?.amount).toBeCloseTo(23.45);+ 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.tsindex 04d0dc822b..b61e29feaa 100644--- a/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts+++ b/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts@@ -1,10 +1,15 @@-import { describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { mkdtemp, readFile, rm } from 'node:fs/promises';import os from 'node:os';import path from 'node:path';-// usageHistory 经由 localDb/dailySpend → client/current 间接触达 better-sqlite3 /-// modelPricing 触达 host 依赖 — 这里只测纯函数 + deps 注入版聚合, 全部 mock 掉。+const currentDbClient = vi.hoisted(() => ({+ userId: 'user-a' as string | null,+}));+const mocks = vi.hoisted(() => ({+ electronAppGetPath: vi.fn(() => ''),+}));+vi.mock('../../localDb/dailySpend', () => ({getAllSpendDays: vi.fn(),localDayKey: () => '2026-06-11',@@ -12,9 +17,6 @@ vi.mock('../../localDb/dailySpend', () => ({vi.mock('../../localDb/dailyModelUsage', () => ({getModelUsageSince: vi.fn(),}));-const currentDbClient = vi.hoisted(() => ({- userId: 'user-a' as string | null,-}));vi.mock('../../localDb/client/current', () => ({getCurrentDbClientUserId: () => currentDbClient.userId,}));@@ -23,27 +25,55 @@ vi.mock('../modelPricing', () => ({isModelPricingRefreshInFlight: vi.fn(() => false),getCodexSubscriptionValuePrice: (model: string,- pricing: Record<string, { inputUsdPerMtok: number; outputUsdPerMtok: number }> | null | undefined,- ) => pricing?.[model] ?? (model === 'gpt-5.5' ? { inputUsdPerMtok: 2, outputUsdPerMtok: 8 } : undefined),+ pricing: Record<string, Record<string, unknown>> | null | undefined,+ ) =>+ pricing?.openai?.[model] ??+ (model === 'gpt-5.5'+ ? {+ providerId: 'openai',+ modelId: model,+ currency: 'USD',+ source: 'subscription-reference',+ approximate: true,+ inputPerMtok: 2,+ outputPerMtok: 8,+ }+ : undefined),getSubscriptionDirectValuePrice: (model: string) =>- model === 'xai/grok-4.3' ? { inputUsdPerMtok: 3, outputUsdPerMtok: 15 } : undefined,-}));-const mocks = vi.hoisted(() => ({- electronAppGetPath: vi.fn(() => ''),+ model === 'xai/grok-4.3'+ ? {+ providerId: 'xai',+ modelId: model,+ currency: 'USD',+ source: 'subscription-reference',+ approximate: true,+ inputPerMtok: 3,+ outputPerMtok: 15,+ }+ : undefined,}));vi.mock('electron', () => ({app: {getPath: mocks.electronAppGetPath,},}));+vi.mock('../../logger', () => ({+ createLogger: () => ({+ info: vi.fn(),+ debug: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ }),+}));import {+ __resetUsageHistoryCacheForTesting,claudeSubscriptionUsageModelKey,codexApiUsageModelKey,codexSubscriptionUsageModelKey,computeAnomaly,computeStreaks,- __resetUsageHistoryCacheForTesting,+ emptyUsageHistoryPayload,prevDayKey,readUsageHistory,readUsageHistoryWith,@@ -53,685 +83,343 @@ 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,+ type ModelPriceQuote,+ type RegionalMoney,+} from '../../../shared/regionalMoney';++const TODAY = '2026-06-11';++function actual(amount: number, approximate = false): RegionalMoney {+ return {+ amount,+ currency: gatewayCurrencyForRegion(CURRENT_CINDY_REGION),+ approximate,+ kind: 'actual-cost',+ ...(approximate ? { estimateReasons: ['legacy-usd'] } : {}),+ };+}++function subscriptionQuote(+ providerId: string,+ modelId: string,+ inputPerMtok: number,+ outputPerMtok: number,+): ModelPriceQuote {+ return {+ providerId,+ modelId,+ currency: 'USD',+ source: 'subscription-reference',+ approximate: true,+ inputPerMtok,+ outputPerMtok,+ };+}++function modelRow(+ day: string,+ agentKind: 'claude-code' | 'codex',+ model: string,+ money: RegionalMoney,+ tokens: {+ inputTokens?: number;+ outputTokens?: number;+ cacheReadTokens?: number;+ cacheCreateTokens?: number;+ } = {},+) {+ return {+ day,+ agentKind,+ model,+ money,+ inputTokens: tokens.inputTokens ?? 0,+ outputTokens: tokens.outputTokens ?? 0,+ cacheReadTokens: tokens.cacheReadTokens ?? 0,+ cacheCreateTokens: tokens.cacheCreateTokens ?? 0,+ };+}++function makeDeps(overrides: Partial<UsageHistoryDeps> = {}): UsageHistoryDeps {+ return {+ getAllSpendDays: async () => [],+ getModelUsageSince: async () => [],+ getModelPricing: async () => null,+ isModelPricingRefreshInFlight: () => false,+ todayKey: () => TODAY,+ ...overrides,+ };+}++beforeEach(async () => {+ mocks.electronAppGetPath.mockReturnValue(+ await mkdtemp(path.join(os.tmpdir(), 'cindy-usage-history-')),+ );+ currentDbClient.userId = 'user-a';+ __resetUsageHistoryCacheForTesting();+ vi.mocked(getAllSpendDays).mockResolvedValue([]);+ vi.mocked(getModelUsageSince).mockResolvedValue([]);+ vi.mocked(getModelPricing).mockResolvedValue(null);+ vi.mocked(isModelPricingRefreshInFlight).mockReturnValue(false);+});-describe('day key arithmetic', () => {- it('prevDayKey crosses month/year boundaries', () => {- expect(prevDayKey('2026-06-01')).toBe('2026-05-31');+afterEach(async () => {+ const dir = mocks.electronAppGetPath();+ vi.useRealTimers();+ vi.restoreAllMocks();+ if (dir) {+ await rm(dir, {+ recursive: true,+ force: true,+ maxRetries: 5,+ retryDelay: 100,+ });+ }+});++describe('day arithmetic and streaks', () => {+ it('crosses month/year boundaries and shifts arbitrary deltas', () => {expect(prevDayKey('2026-01-01')).toBe('2025-12-31');expect(prevDayKey('2026-03-01')).toBe('2026-02-28');- });-- it('shiftDayKey shifts by arbitrary deltas', () => {- expect(shiftDayKey('2026-06-11', -1)).toBe('2026-06-10');expect(shiftDayKey('2026-06-11', -30)).toBe('2026-05-12');- expect(shiftDayKey('2026-06-11', 0)).toBe('2026-06-11');});-});-describe('computeStreaks', () => {- it('empty input → zero streaks', () => {- expect(computeStreaks([], '2026-06-11')).toEqual({ current: 0, longest: 0 });- });-- it('counts current streak ending today', () => {- const days = ['2026-06-09', '2026-06-10', '2026-06-11'];- expect(computeStreaks(days, '2026-06-11')).toEqual({ current: 3, longest: 3 });- });-- it('today not yet active does not break the streak (grace from yesterday)', () => {- const days = ['2026-06-09', '2026-06-10'];- expect(computeStreaks(days, '2026-06-11')).toEqual({ current: 2, longest: 2 });- });-- it('gap before yesterday → current 0, longest preserved', () => {- const days = ['2026-06-05', '2026-06-06', '2026-06-07'];- expect(computeStreaks(days, '2026-06-11')).toEqual({ current: 0, longest: 3 });- });-- it('longest picks the biggest historical run across gaps', () => {- const days = ['2026-05-01', '2026-05-02', '2026-05-03', '2026-05-04', '2026-06-10', '2026-06-11'];- expect(computeStreaks(days, '2026-06-11')).toEqual({ current: 2, longest: 4 });+ it('keeps today grace while preserving the longest historical run', () => {+ expect(computeStreaks(+ ['2026-05-01', '2026-05-02', '2026-05-03', '2026-06-09', '2026-06-10'],+ TODAY,+ )).toEqual({ current: 2, longest: 3 });+ expect(computeStreaks([], TODAY)).toEqual({ current: 0, longest: 0 });});});-describe('computeAnomaly', () => {- const today = '2026-06-11';-- function spendMap(trailing: number[], todayVal: number): Map<string, number> {- const m = new Map<string, number>();- trailing.forEach((v, i) => m.set(shiftDayKey(today, -(i + 1)), v));- m.set(today, todayVal);- return m;+describe('anomaly detection', () => {+ function spendMap(trailing: number[], todayValue: number): Map<string, number> {+ const values = new Map<string, number>();+ trailing.forEach((value, index) => {+ values.set(shiftDayKey(TODAY, -(index + 1)), value);+ });+ values.set(TODAY, todayValue);+ return values;}- it('fewer than 3 active trailing days → null baseline, never anomalous', () => {- const m = spendMap([5, 0, 0, 0, 0, 0, 0], 100);- expect(computeAnomaly(m, today)).toEqual({ isAnomalous: false, trailing7DayAvg: null });- });-- it('today below $1 floor is never anomalous even at huge multiples', () => {- const m = spendMap([0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05], 0.9);- expect(computeAnomaly(m, today)).toEqual({ isAnomalous: false, trailing7DayAvg: expect.closeTo(0.05) });- });-- it('exactly 2x average is NOT anomalous (strict greater-than)', () => {- const m = spendMap([7, 7, 7, 7, 7, 7, 7], 14);- expect(computeAnomaly(m, today)).toEqual({ isAnomalous: false, trailing7DayAvg: 7 });+ it('requires three active baseline days and a strict two-times increase', () => {+ expect(computeAnomaly(+ spendMap([5, 0, 0, 0, 0, 0, 0], 100),+ TODAY,+ )).toEqual({ isAnomalous: false, trailing7DayAvg: null });+ expect(computeAnomaly(+ spendMap([7, 7, 7, 0, 0, 0, 0], 7),+ TODAY,+ )).toEqual({ isAnomalous: true, trailing7DayAvg: 3 });+ expect(computeAnomaly(+ spendMap([7, 7, 7, 7, 7, 7, 7], 14),+ TODAY,+ )).toEqual({ isAnomalous: false, trailing7DayAvg: 7 });});+});- it('above 2x average and >= $1 is anomalous; missing days count as zero', () => {- // 3 active days of 7, sum=21 → avg=3; today 7 > 6- const m = spendMap([7, 7, 7, 0, 0, 0, 0], 7);- expect(computeAnomaly(m, today)).toEqual({ isAnomalous: true, trailing7DayAvg: 3 });+describe('billing model keys', () => {+ it('keeps API and subscription accounting rows distinct', () => {+ expect(codexApiUsageModelKey('gpt-5.5')).toBe('gpt-5.5#billing=api');+ expect(codexSubscriptionUsageModelKey('gpt-5.5')).toBe(+ 'gpt-5.5#billing=subscription',+ );+ expect(claudeSubscriptionUsageModelKey('claude-opus-4-8')).toBe(+ 'claude-opus-4-8#billing=subscription',+ );});});-// Codex 费用折算的纯函数已迁到 turnCostCalculator.computeGatewayTurnCost,-// 其单测见 turnCostCalculator.test.ts。-describe('readUsageHistoryWith', () => {- const today = '2026-06-11';-- function makeDeps(over: Partial<UsageHistoryDeps> = {}): UsageHistoryDeps {- return {- getAllSpendDays: async () => [],- getModelUsageSince: async () => [],- getModelPricing: async () => null,- isModelPricingRefreshInFlight: () => false,- todayKey: () => today,- ...over,- };- }-- it('aggregates models across days, estimates codex cost, sorts by comparable amount', async () => {- const deps = makeDeps({+ it('aggregates actual money and subscription value without double counting', async () => {+ const estimateAmount = regionalAmountFromUsdReference(+ 2,+ CURRENT_CINDY_REGION,+ );+ const result = await readUsageHistoryWith(makeDeps({getAllSpendDays: async () => [- { day: '2026-06-10', costUsd: 3 },- { day: '2026-06-11', costUsd: 5 },- ],- getModelUsageSince: async () => [- { day: '2026-06-10', agentKind: 'claude-code', model: 'claude-opus-4-8', costUsd: 2, inputTokens: 10, outputTokens: 20, cacheReadTokens: 0, cacheCreateTokens: 0 },- { day: '2026-06-11', agentKind: 'claude-code', model: 'claude-opus-4-8', costUsd: 4, inputTokens: 10, outputTokens: 20, cacheReadTokens: 0, cacheCreateTokens: 0 },- { day: '2026-06-11', agentKind: 'codex', model: codexSubscriptionUsageModelKey('gpt-5.5'), costUsd: 0, inputTokens: 1_000_000, outputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0 },- { day: '2026-06-11', agentKind: 'codex', model: 'mystery-model', costUsd: 0, inputTokens: 500, outputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0 },- ],- getModelPricing: async () => ({ 'gpt-5.5': { inputUsdPerMtok: 2, outputUsdPerMtok: 8 } }),- });- const out = await readUsageHistoryWith(deps);-- expect(out.todayKey).toBe(today);- expect(out.estimatesPending).toBe(false);- expect(out.models.map((m) => m.model)).toEqual(['claude-opus-4-8', 'gpt-5.5', 'mystery-model']);- const [claude, gpt, mystery] = out.models;- expect(claude).toMatchObject({ agentKind: 'claude-code', costUsd: 6, estimatedCostUsd: null, inputTokens: 20 });- expect(gpt).toMatchObject({ agentKind: 'codex', costUsd: 0, estimatedCostUsd: 2 });- expect(mystery).toMatchObject({ agentKind: 'codex', estimatedCostUsd: null });- // token 合计: claude 两天 (10+20)*2=60 + gpt 今日 1M + mystery 今日 500- expect(out.totals).toEqual({- today: 5,- last30Days: 8,- last30DaysWithEstimatedValue: 10,- last30DaysEstimatedValue: 2,- todayTokens: 30 + 1_000_000 + 500,- last30DaysTokens: 60 + 1_000_000 + 500,- });- expect(out.streak).toEqual({ current: 2, longest: 2 });- // days 带每日 token 合计 (热力图/柱状图 tooltip 用)- expect(out.days).toEqual([- { day: '2026-06-10', costUsd: 3, tokens: 30 },- { day: '2026-06-11', costUsd: 5, tokens: 30 + 1_000_000 + 500 },- ]);- // modelDaily: 每日 × 模型分段; Claude 实报 $, codex 有价折算、无价 amountUsd=0- expect(out.modelDaily).toEqual([- { day: '2026-06-10', agentKind: 'claude-code', model: 'claude-opus-4-8', amountUsd: 2, apiCostUsd: 2, subscriptionEstimateUsd: 0, tokens: 30 },- { day: '2026-06-11', agentKind: 'claude-code', model: 'claude-opus-4-8', amountUsd: 4, apiCostUsd: 4, subscriptionEstimateUsd: 0, tokens: 30 },- { day: '2026-06-11', agentKind: 'codex', model: 'gpt-5.5', amountUsd: 2, apiCostUsd: 0, subscriptionEstimateUsd: 2, tokens: 1_000_000 },- { day: '2026-06-11', agentKind: 'codex', model: 'mystery-model', amountUsd: 0, apiCostUsd: 0, subscriptionEstimateUsd: 0, tokens: 500 },- ]);- });-- it('includes codex-only days (tokens without spend) in days', async () => {- const deps = makeDeps({- getAllSpendDays: async () => [{ day: '2026-06-11', costUsd: 2 }],- getModelUsageSince: async () => [- { day: '2026-06-10', agentKind: 'codex', model: 'gpt-5.5', costUsd: 0, inputTokens: 7000, outputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0 },+ { day: '2026-06-10', money: actual(3) },+ { day: TODAY, money: actual(5) },],- });- const out = await readUsageHistoryWith(deps);- expect(out.days).toEqual([- { day: '2026-06-10', costUsd: 0, tokens: 7000 },- { day: '2026-06-11', costUsd: 2, tokens: 0 },- ]);- });-- it('estimates claude subscription rows (#billing=subscription) like codex ones', async () => {- const deps = makeDeps({- getAllSpendDays: async () => [],- getModelUsageSince: async () => [- // Claude 订阅轮: cost=0 的订阅标记行 → 按 Anthropic 价折算估算价值- { day: '2026-06-11', agentKind: 'claude-code', model: claudeSubscriptionUsageModelKey('claude-fable-5'), costUsd: 0, inputTokens: 1_000_000, outputTokens: 100_000, cacheReadTokens: 0, cacheCreateTokens: 0 },- // Claude API 轮: 实报 $, 不受订阅折算影响- { day: '2026-06-11', agentKind: 'claude-code', model: 'claude-opus-4-8', costUsd: 3, inputTokens: 10, outputTokens: 20, cacheReadTokens: 0, cacheCreateTokens: 0 },- ],- // 网关无 claude-fable-5 行 → 走家族牌价兜底 ($10/$50): 1M×10 + 0.1M×50 = 15- getModelPricing: async () => null,- });- const out = await readUsageHistoryWith(deps);-- expect(out.estimatesPending).toBe(false);- const fable = out.models.find((m) => m.model === 'claude-fable-5');- expect(fable).toMatchObject({ agentKind: 'claude-code', costUsd: 0, estimatedCostUsd: 15 });- const fableDaily = out.modelDaily.find((r) => r.model === 'claude-fable-5');- expect(fableDaily).toMatchObject({ amountUsd: 15, apiCostUsd: 0, subscriptionEstimateUsd: 15 });- // 30 天含估算 = 实报 0 (daily_spend 空) + 订阅估算 15- expect(out.totals).toMatchObject({- last30Days: 0,- last30DaysWithEstimatedValue: 15,- last30DaysEstimatedValue: 15,- });- });-- it('prefers gateway pricing (cache-aware) for claude subscription rows when available', async () => {- const deps = makeDeps({- getAllSpendDays: async () => [],getModelUsageSince: async () => [- { day: '2026-06-11', agentKind: 'claude-code', model: claudeSubscriptionUsageModelKey('claude-fable-5'), costUsd: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 1_000_000, cacheCreateTokens: 0 },+ modelRow(+ '2026-06-10',+ 'claude-code',+ 'claude-opus-4-8',+ actual(2),+ { inputTokens: 10, outputTokens: 20 },+ ),+ modelRow(+ TODAY,+ 'claude-code',+ 'claude-opus-4-8',+ actual(4),+ { inputTokens: 10, outputTokens: 20 },+ ),+ modelRow(+ TODAY,+ 'codex',+ codexSubscriptionUsageModelKey('gpt-5.5'),+ actual(0),+ { inputTokens: 1_000_000 },+ ),+ modelRow(+ TODAY,+ 'codex',+ codexApiUsageModelKey('gpt-5.5'),+ actual(1),+ { outputTokens: 100 },+ ),],getModelPricing: async () => ({- 'claude-fable-5': { inputUsdPerMtok: 10, outputUsdPerMtok: 50, cacheReadUsdPerMtok: 1 },+ openai: {+ 'gpt-5.5': subscriptionQuote('openai', 'gpt-5.5', 2, 8),+ },}),+ }));++ expect(result.estimatesPending).toBe(false);+ expect(result.totals.today).toEqual(actual(5));+ expect(result.totals.last30Days).toEqual(actual(8));+ expect(result.totals.last30DaysEstimatedValue).toMatchObject({+ amount: estimateAmount,+ kind: 'value-estimate',+ approximate: true,});- const out = await readUsageHistoryWith(deps);- // cacheRead 1M × $1 (网关 cache 档价) = 1, 而非按 input 价折算的 10- expect(out.models[0]).toMatchObject({ model: 'claude-fable-5', estimatedCostUsd: 1 });- });-- it('uses built-in subscription value pricing when gateway pricing is unavailable', async () => {- const deps = makeDeps({+ expect(result.totals.last30DaysWithEstimatedValue.amount).toBeCloseTo(+ 8 + estimateAmount,+ );+ expect(result.totals.last30DaysWithEstimatedValue.approximate).toBe(true);+ expect(result.totals.todayTokens).toBe(1_000_130);+ expect(result.totals.last30DaysTokens).toBe(1_000_160);++ const subscription = result.models.find(+ (row) => row.agentKind === 'codex' && row.estimatedMoney,+ );+ expect(subscription?.estimatedMoney?.amount).toBeCloseTo(estimateAmount);+ const api = result.modelDaily.find(+ (row) => row.apiMoney.amount === 1,+ );+ expect(api?.subscriptionEstimateMoney.amount).toBe(0);+ });++ it('uses provider-scoped Anthropic reference pricing for Claude subscription rows', async () => {+ const expected = regionalAmountFromUsdReference(5, CURRENT_CINDY_REGION);+ const result = await readUsageHistoryWith(makeDeps({getModelUsageSince: async () => [- { day: '2026-06-11', agentKind: 'codex', model: codexSubscriptionUsageModelKey('gpt-5.5'), costUsd: 0, inputTokens: 1_000_000, outputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0 },+ modelRow(+ TODAY,+ 'claude-code',+ claudeSubscriptionUsageModelKey('claude-opus-4-8'),+ actual(0),+ { inputTokens: 1_000_000 },+ ),],- getModelPricing: async () => null,- });- const out = await readUsageHistoryWith(deps);- expect(out.estimatesPending).toBe(false);- expect(out.models[0]).toMatchObject({ model: 'gpt-5.5', estimatedCostUsd: 2 });- expect(out.modelDaily[0]).toMatchObject({ amountUsd: 2, subscriptionEstimateUsd: 2 });- expect(out.totals).toMatchObject({- last30Days: 0,- last30DaysWithEstimatedValue: 2,- last30DaysEstimatedValue: 2,- });- });-- it('uses xAI direct subscription pricing for Codex xAI subscription rows', async () => {- const deps = makeDeps({- getModelUsageSince: async () => [- { day: '2026-06-11', agentKind: 'codex', model: codexSubscriptionUsageModelKey('xai/grok-4.3'), costUsd: 0, inputTokens: 1_000_000, outputTokens: 100_000, cacheReadTokens: 0, cacheCreateTokens: 0 },- ],- getModelPricing: async () => null,- });- const out = await readUsageHistoryWith(deps);- expect(out.estimatesPending).toBe(false);- expect(out.models[0]).toMatchObject({ model: 'xai/grok-4.3', estimatedCostUsd: 4.5 });- expect(out.modelDaily[0]).toMatchObject({ amountUsd: 4.5, subscriptionEstimateUsd: 4.5 });- expect(out.totals).toMatchObject({- last30Days: 0,- last30DaysWithEstimatedValue: 4.5,- last30DaysEstimatedValue: 4.5,- });- });-- it('does not mark API-billed Codex rows as pending subscription estimates', async () => {- const deps = makeDeps({- getModelUsageSince: async () => [- { day: '2026-06-11', agentKind: 'codex', model: codexApiUsageModelKey('unknown-model'), costUsd: 3, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0 },- ],- getModelPricing: async () => null,- });- const out = await readUsageHistoryWith(deps);- expect(out.estimatesPending).toBe(false);- expect(out.modelDaily[0]).toMatchObject({- model: 'unknown-model',- amountUsd: 3,- apiCostUsd: 3,- subscriptionEstimateUsd: 0,- });- });+ getModelPricing: async () => ({+ anthropic: {+ 'claude-opus-4-8': subscriptionQuote(+ 'anthropic',+ 'claude-opus-4-8',+ 5,+ 25,+ ),+ },+ }),+ }));- it('renders token-only usage when missing subscription pricing cannot refresh', async () => {- const deps = makeDeps({- getModelUsageSince: async () => [- { day: '2026-06-11', agentKind: 'codex', model: codexSubscriptionUsageModelKey('mystery-model'), costUsd: 0, inputTokens: 7000, outputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0 },- ],- getModelPricing: async () => null,- isModelPricingRefreshInFlight: () => false,+ expect(result.models[0]).toMatchObject({+ agentKind: 'claude-code',+ model: 'claude-opus-4-8',});- const out = await readUsageHistoryWith(deps);- expect(out.estimatesPending).toBe(false);- expect(out.modelDaily[0]).toMatchObject({ amountUsd: 0, subscriptionEstimateUsd: 0 });- });-- it('marks missing subscription estimates pending while stale pricing refresh is in flight', async () => {- const deps = makeDeps({- getModelUsageSince: async () => [- { day: '2026-06-11', agentKind: 'codex', model: codexSubscriptionUsageModelKey('future-model'), costUsd: 0, inputTokens: 7000, outputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0 },- ],- getModelPricing: async () => ({ 'gpt-5.5': { inputUsdPerMtok: 2, outputUsdPerMtok: 8 } }),+ expect(result.models[0].estimatedMoney?.amount).toBe(expected);+ });++ it('marks estimates pending only when a subscription price is missing during refresh', async () => {+ const row = modelRow(+ TODAY,+ 'codex',+ codexSubscriptionUsageModelKey('unknown-model'),+ actual(0),+ { inputTokens: 1_000 },+ );+ const pending = await readUsageHistoryWith(makeDeps({+ getModelUsageSince: async () => [row],isModelPricingRefreshInFlight: () => true,- });- const out = await readUsageHistoryWith(deps);- expect(out.estimatesPending).toBe(true);- expect(out.modelDaily[0]).toMatchObject({ amountUsd: 0, subscriptionEstimateUsd: 0 });- });-- it('does not keep missing subscription estimates pending after stale pricing refresh settles', async () => {- const deps = makeDeps({- getModelUsageSince: async () => [- { day: '2026-06-11', agentKind: 'codex', model: codexSubscriptionUsageModelKey('future-model'), costUsd: 0, inputTokens: 7000, outputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0 },- ],- getModelPricing: async () => ({ 'gpt-5.5': { inputUsdPerMtok: 2, outputUsdPerMtok: 8 } }),+ }));+ const settled = await readUsageHistoryWith(makeDeps({+ getModelUsageSince: async () => [row],isModelPricingRefreshInFlight: () => false,- });- const out = await readUsageHistoryWith(deps);- expect(out.estimatesPending).toBe(false);- expect(out.modelDaily[0]).toMatchObject({ amountUsd: 0, subscriptionEstimateUsd: 0 });- });-- it('adds subscription estimates on top of unclassified actual daily spend', async () => {- const deps = makeDeps({- getAllSpendDays: async () => [{ day: '2026-06-11', costUsd: 10 }],- getModelUsageSince: async () => [- { day: '2026-06-11', agentKind: 'codex', model: codexSubscriptionUsageModelKey('gpt-5.5'), costUsd: 0, inputTokens: 1_000_000, outputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0 },- ],- getModelPricing: async () => null,- });- const out = await readUsageHistoryWith(deps);- expect(out.estimatesPending).toBe(false);- expect(out.totals).toMatchObject({- last30Days: 10,- last30DaysWithEstimatedValue: 12,- last30DaysEstimatedValue: 2,- });- });-- it('keeps Codex API cost and subscription value separate for the same model and day', async () => {- const deps = makeDeps({- getAllSpendDays: async () => [{ day: '2026-06-11', costUsd: 10 }],- getModelUsageSince: async () => [- { day: '2026-06-11', agentKind: 'codex', model: codexSubscriptionUsageModelKey('gpt-5.5'), costUsd: 0, inputTokens: 1_000_000, outputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0 },- { day: '2026-06-11', agentKind: 'codex', model: codexApiUsageModelKey('gpt-5.5'), costUsd: 3, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0 },- ],- getModelPricing: async () => null,- });- const out = await readUsageHistoryWith(deps);-- expect(out.models).toEqual([- expect.objectContaining({ agentKind: 'codex', model: 'gpt-5.5', costUsd: 3, estimatedCostUsd: null }),- expect.objectContaining({ agentKind: 'codex', model: 'gpt-5.5', costUsd: 0, estimatedCostUsd: 2 }),- ]);- expect(out.modelDaily).toEqual([- { day: '2026-06-11', agentKind: 'codex', model: 'gpt-5.5', amountUsd: 2, apiCostUsd: 0, subscriptionEstimateUsd: 2, tokens: 1_000_000 },- { day: '2026-06-11', agentKind: 'codex', model: 'gpt-5.5', amountUsd: 3, apiCostUsd: 3, subscriptionEstimateUsd: 0, tokens: 0 },- ]);- expect(out.totals).toMatchObject({- last30Days: 10,- last30DaysWithEstimatedValue: 12,- last30DaysEstimatedValue: 2,- });- });-- it('does not add subscription estimates for legacy unsuffixed Codex rows', async () => {- const deps = makeDeps({- getAllSpendDays: async () => [{ day: '2026-06-11', costUsd: 10 }],- getModelUsageSince: async () => [- { day: '2026-06-11', agentKind: 'codex', model: 'gpt-5.5', costUsd: 0, inputTokens: 1_000_000, outputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0 },- ],- getModelPricing: async () => null,- });- const out = await readUsageHistoryWith(deps);-- expect(out.estimatesPending).toBe(false);- expect(out.models[0]).toMatchObject({ agentKind: 'codex', model: 'gpt-5.5', costUsd: 0, estimatedCostUsd: null });- expect(out.modelDaily[0]).toMatchObject({- amountUsd: 0,- apiCostUsd: 0,- subscriptionEstimateUsd: 0,- tokens: 1_000_000,- });- expect(out.totals).toMatchObject({- last30Days: 10,- last30DaysWithEstimatedValue: 10,- last30DaysEstimatedValue: 0,- });- });-- it('clamps heatmap window and filters zero-cost days', async () => {- const deps = makeDeps({+ }));+ expect(pending.estimatesPending).toBe(true);+ expect(settled.estimatesPending).toBe(false);+ expect(settled.models[0].estimatedMoney).toBeNull();+ });++ it('propagates approximate legacy history into anomaly and totals', async () => {+ const trailing = Array.from({ length: 7 }, (_, index) => ({+ day: shiftDayKey(TODAY, -(index + 1)),+ money: actual(1, true),+ }));+ const result = await readUsageHistoryWith(makeDeps({getAllSpendDays: async () => [- { day: '2020-01-01', costUsd: 9 },- { day: '2026-06-10', costUsd: 0 },- { day: '2026-06-11', costUsd: 1 },+ ...trailing,+ { day: TODAY, money: actual(7, true) },],+ }));+ expect(result.anomaly).toMatchObject({+ isAnomalous: true,+ trailing7DayAvg: {+ amount: 1,+ approximate: true,+ },});- const out = await readUsageHistoryWith(deps, { days: 7 });- expect(out.days).toEqual([{ day: '2026-06-11', costUsd: 1, tokens: 0 }]);- });-- it('empty database → empty payload shape', async () => {- const out = await readUsageHistoryWith(makeDeps());- expect(out.days).toEqual([]);- expect(out.models).toEqual([]);- expect(out.streak).toEqual({ current: 0, longest: 0 });- expect(out.anomaly).toEqual({ isAnomalous: false, trailing7DayAvg: null });+ expect(result.totals.last30Days.approximate).toBe(true);});});-describe('readUsageHistory persistent cache', () => {- async function withTempUserData<T>(fn: (dir: string) => Promise<T>): Promise<T> {- const dir = await mkdtemp(path.join(os.tmpdir(), 'xdt-maker-usage-history-'));- mocks.electronAppGetPath.mockReturnValue(dir);- currentDbClient.userId = 'user-a';- try {- return await fn(dir);- } finally {- await rm(dir, { recursive: true, force: true });- __resetUsageHistoryCacheForTesting();- vi.useRealTimers();- vi.restoreAllMocks();- }- }-- it('returns the previous disk snapshot first, then a fresh memory snapshot after background refresh', async () => {- await withTempUserData(async (dir) => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-06-11T00:00:00.000Z'));- vi.mocked(getAllSpendDays).mockResolvedValueOnce([{ day: '2026-06-11', costUsd: 1 }]);- vi.mocked(getModelUsageSince).mockResolvedValueOnce([]);- vi.mocked(getModelPricing).mockResolvedValueOnce(null);-- await expect(readUsageHistory()).resolves.toMatchObject({- stale: false,- totals: { today: 1, last30Days: 1 },- });- await vi.waitFor(async () => {- const raw = await readFile(path.join(dir, 'cache', 'usage-history.json'), 'utf8');- expect(JSON.parse(raw)).toMatchObject({- version: 1,- optsKey: 'user=user-a|days=140',- payload: { totals: { today: 1, last30Days: 1 } },- });- });-- __resetUsageHistoryCacheForTesting();- vi.setSystemTime(new Date('2026-06-11T00:00:01.000Z'));- vi.mocked(getAllSpendDays).mockResolvedValueOnce([{ day: '2026-06-11', costUsd: 2 }]);- vi.mocked(getModelUsageSince).mockResolvedValueOnce([]);- vi.mocked(getModelPricing).mockResolvedValueOnce(null);-- await expect(readUsageHistory()).resolves.toMatchObject({- stale: true,- totals: { today: 1, last30Days: 1 },- });- await vi.waitFor(() => expect(getAllSpendDays).toHaveBeenCalledTimes(2));-- await vi.waitFor(async () => {- await expect(readUsageHistory()).resolves.toMatchObject({- stale: false,- totals: { today: 2, last30Days: 2 },- });- });- });- });-- it('scopes fresh memory cache by current user', async () => {- await withTempUserData(async () => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-06-11T00:00:00.000Z'));- currentDbClient.userId = 'user-a';- vi.mocked(getAllSpendDays).mockResolvedValueOnce([{ day: '2026-06-11', costUsd: 1 }]);- vi.mocked(getModelUsageSince).mockResolvedValueOnce([]);- vi.mocked(getModelPricing).mockResolvedValueOnce(null);-- await expect(readUsageHistory()).resolves.toMatchObject({- stale: false,- totals: { today: 1, last30Days: 1 },- });-- vi.setSystemTime(new Date('2026-06-11T00:00:01.000Z'));- currentDbClient.userId = 'user-b';- vi.mocked(getAllSpendDays).mockResolvedValueOnce([{ day: '2026-06-11', costUsd: 9 }]);- vi.mocked(getModelUsageSince).mockResolvedValueOnce([]);- vi.mocked(getModelPricing).mockResolvedValueOnce(null);-- await expect(readUsageHistory()).resolves.toMatchObject({- stale: false,- totals: { today: 9, last30Days: 9 },- });- expect(getAllSpendDays).toHaveBeenCalledTimes(2);- });- });-- it('does not reuse an in-flight refresh across users', async () => {- await withTempUserData(async () => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-06-11T00:00:00.000Z'));- currentDbClient.userId = 'user-a';- let resolveUserASpendDays: (rows: Array<{ day: string; costUsd: number }>) => void = () => {};- vi.mocked(getAllSpendDays).mockImplementationOnce(- () => new Promise((resolve) => {- resolveUserASpendDays = resolve;- }),- );-- const userARead = readUsageHistory();- await vi.waitFor(() => expect(getAllSpendDays).toHaveBeenCalledTimes(1));-- vi.setSystemTime(new Date('2026-06-11T00:00:01.000Z'));- currentDbClient.userId = 'user-b';- vi.mocked(getAllSpendDays).mockResolvedValueOnce([{ day: '2026-06-11', costUsd: 9 }]);- vi.mocked(getModelUsageSince).mockResolvedValueOnce([]);- vi.mocked(getModelPricing).mockResolvedValueOnce(null);-- await expect(readUsageHistory()).resolves.toMatchObject({- stale: false,- totals: { today: 9, last30Days: 9 },- });- expect(getAllSpendDays).toHaveBeenCalledTimes(2);-- currentDbClient.userId = 'user-a';- vi.mocked(getModelUsageSince).mockResolvedValueOnce([]);- vi.mocked(getModelPricing).mockResolvedValueOnce(null);- resolveUserASpendDays([{ day: '2026-06-11', costUsd: 1 }]);- await vi.runAllTimersAsync();- await expect(userARead).resolves.toMatchObject({- stale: false,- totals: { today: 1, last30Days: 1 },- });- });- });-- it('keeps disk snapshots stale while the background refresh is still in flight', async () => {- await withTempUserData(async (dir) => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-06-11T00:00:00.000Z'));- vi.mocked(getAllSpendDays).mockResolvedValueOnce([{ day: '2026-06-11', costUsd: 1 }]);- vi.mocked(getModelUsageSince).mockResolvedValueOnce([]);- vi.mocked(getModelPricing).mockResolvedValueOnce(null);-- await expect(readUsageHistory()).resolves.toMatchObject({- stale: false,- totals: { today: 1, last30Days: 1 },- });- await vi.waitFor(async () => {- const raw = await readFile(path.join(dir, 'cache', 'usage-history.json'), 'utf8');- expect(JSON.parse(raw)).toMatchObject({- payload: { totals: { today: 1, last30Days: 1 } },- });- });-- __resetUsageHistoryCacheForTesting();- vi.setSystemTime(new Date('2026-06-11T00:00:01.000Z'));- let resolveSpendDays: (rows: Array<{ day: string; costUsd: number }>) => void = () => {};- vi.mocked(getAllSpendDays).mockImplementationOnce(- () => new Promise((resolve) => {- resolveSpendDays = resolve;- }),- );- vi.mocked(getModelUsageSince).mockResolvedValueOnce([]);- vi.mocked(getModelPricing).mockResolvedValueOnce(null);-- await expect(readUsageHistory()).resolves.toMatchObject({- stale: true,- totals: { today: 1, last30Days: 1 },- });-- await expect(readUsageHistory()).resolves.toMatchObject({- stale: true,- totals: { today: 1, last30Days: 1 },- });-- resolveSpendDays([{ day: '2026-06-11', costUsd: 2 }]);- await vi.runAllTimersAsync();- await vi.waitFor(() => expect(getAllSpendDays).toHaveBeenCalledTimes(2));- await vi.waitFor(() => expect(getModelUsageSince).toHaveBeenCalledTimes(2));- await vi.waitFor(() => expect(getModelPricing).toHaveBeenCalledTimes(2));-- await expect(readUsageHistory()).resolves.toMatchObject({- stale: false,- totals: { today: 2, last30Days: 2 },- });- });- });-- it('force refresh bypasses the fresh in-memory shortcut after a usage push', async () => {- await withTempUserData(async () => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-06-11T00:00:00.000Z'));- vi.mocked(getAllSpendDays).mockResolvedValueOnce([{ day: '2026-06-11', costUsd: 1 }]);- vi.mocked(getModelUsageSince).mockResolvedValueOnce([]);- vi.mocked(getModelPricing).mockResolvedValueOnce(null);-- await expect(readUsageHistory()).resolves.toMatchObject({- stale: false,- totals: { today: 1, last30Days: 1 },- });-- vi.setSystemTime(new Date('2026-06-11T00:00:01.000Z'));- await expect(readUsageHistory()).resolves.toMatchObject({- stale: false,- totals: { today: 1, last30Days: 1 },- });- expect(getAllSpendDays).toHaveBeenCalledTimes(1);-- vi.mocked(getAllSpendDays).mockResolvedValueOnce([{ day: '2026-06-11', costUsd: 2 }]);- vi.mocked(getModelUsageSince).mockResolvedValueOnce([]);- vi.mocked(getModelPricing).mockResolvedValueOnce(null);-- await expect(readUsageHistory({ forceRefresh: true })).resolves.toMatchObject({- stale: false,- totals: { today: 2, last30Days: 2 },- });- expect(getAllSpendDays).toHaveBeenCalledTimes(2);- });- });-- it('does not let an older stale-while-refresh overwrite a newer forced refresh', async () => {- await withTempUserData(async () => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-06-11T00:00:00.000Z'));- vi.mocked(getAllSpendDays).mockResolvedValueOnce([{ day: '2026-06-11', costUsd: 1 }]);- vi.mocked(getModelUsageSince).mockResolvedValueOnce([]);- vi.mocked(getModelPricing).mockResolvedValueOnce(null);-- await expect(readUsageHistory()).resolves.toMatchObject({- stale: false,- totals: { today: 1, last30Days: 1 },- });-- vi.setSystemTime(new Date('2026-06-11T00:00:11.000Z'));- let resolveOldSpendDays: (rows: Array<{ day: string; costUsd: number }>) => void = () => {};- vi.mocked(getAllSpendDays).mockImplementationOnce(- () => new Promise((resolve) => {- resolveOldSpendDays = resolve;- }),+describe('production cache and empty payload', () => {+ it('writes a structured fresh payload and serves it from memory', async () => {+ vi.mocked(getAllSpendDays).mockResolvedValue([+ { day: TODAY, money: actual(2) },+ ]);+ const first = await readUsageHistory({ days: 30 });+ const second = await readUsageHistory({ days: 30 });+ expect(first.stale).toBe(false);+ expect(second.stale).toBe(false);+ expect(second.totals.today).toEqual(actual(2));++ await vi.waitFor(async () => {+ const raw = JSON.parse(+ await readFile(+ path.join(mocks.electronAppGetPath(), 'cache', 'usage-history.json'),+ 'utf8',+ ),);- vi.mocked(getModelUsageSince).mockResolvedValueOnce([]);- vi.mocked(getModelPricing).mockResolvedValueOnce(null);-- await expect(readUsageHistory()).resolves.toMatchObject({- stale: true,- totals: { today: 1, last30Days: 1 },- });- await vi.waitFor(() => expect(getAllSpendDays).toHaveBeenCalledTimes(2));-- vi.mocked(getAllSpendDays).mockResolvedValueOnce([{ day: '2026-06-11', costUsd: 3 }]);- vi.mocked(getModelUsageSince).mockResolvedValueOnce([]);- vi.mocked(getModelPricing).mockResolvedValueOnce(null);-- await expect(readUsageHistory({ forceRefresh: true })).resolves.toMatchObject({- stale: false,- totals: { today: 3, last30Days: 3 },+ expect(raw).toMatchObject({+ version: 2,+ optsKey: 'user=user-a|days=30',+ payload: {+ totals: {+ today: actual(2),+ },+ },});-- resolveOldSpendDays([{ day: '2026-06-11', costUsd: 2 }]);- await vi.runAllTimersAsync();-- await expect(readUsageHistory()).resolves.toMatchObject({- stale: false,- totals: { today: 3, last30Days: 3 },- });- expect(getAllSpendDays).toHaveBeenCalledTimes(3);});});- it('keeps estimates-pending refreshes in memory without overwriting the disk cache', async () => {- await withTempUserData(async (dir) => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-06-11T00:00:00.000Z'));- vi.mocked(getAllSpendDays).mockResolvedValueOnce([{ day: '2026-06-11', costUsd: 1 }]);- vi.mocked(getModelUsageSince).mockResolvedValueOnce([]);- vi.mocked(getModelPricing).mockResolvedValueOnce(null);-- await expect(readUsageHistory()).resolves.toMatchObject({- stale: false,- estimatesPending: false,- totals: { today: 1, last30Days: 1 },- });- await vi.waitFor(async () => {- const raw = await readFile(path.join(dir, 'cache', 'usage-history.json'), 'utf8');- expect(JSON.parse(raw)).toMatchObject({- payload: { estimatesPending: false, totals: { today: 1, last30Days: 1 } },- });- });-- __resetUsageHistoryCacheForTesting();- vi.setSystemTime(new Date('2026-06-11T00:00:01.000Z'));- vi.mocked(getAllSpendDays).mockResolvedValueOnce([{ day: '2026-06-11', costUsd: 2 }]);- vi.mocked(getModelUsageSince).mockResolvedValueOnce([- { day: '2026-06-11', agentKind: 'codex', model: codexSubscriptionUsageModelKey('mystery-model'), costUsd: 0, inputTokens: 7000, outputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0 },- ]);- vi.mocked(getModelPricing).mockResolvedValueOnce(null);- vi.mocked(isModelPricingRefreshInFlight).mockReturnValueOnce(true);-- await expect(readUsageHistory()).resolves.toMatchObject({- stale: true,- estimatesPending: false,- totals: { today: 1, last30Days: 1 },- });- await vi.waitFor(() => expect(getAllSpendDays).toHaveBeenCalledTimes(2));-- await expect(readUsageHistory()).resolves.toMatchObject({- stale: false,- estimatesPending: true,- totals: { today: 2, last30Days: 2 },- });-- const diskPayload = JSON.parse(await readFile(path.join(dir, 'cache', 'usage-history.json'), 'utf8'));- expect(diskPayload).toMatchObject({- payload: { estimatesPending: false, totals: { today: 1, last30Days: 1 } },- });- expect(getAllSpendDays).toHaveBeenCalledTimes(2);- });+ it('returns region-correct structured zero money on fallback', () => {+ const empty = emptyUsageHistoryPayload();+ expect(empty.totals.today).toEqual(+ zeroRegionalMoney(CURRENT_CINDY_REGION),+ );+ expect(empty.totals.last30DaysEstimatedValue).toEqual(+ zeroRegionalMoney(CURRENT_CINDY_REGION, 'value-estimate'),+ );});});diff --git a/apps/desktop/src/main/usage/claudeAccountUsage.ts b/apps/desktop/src/main/usage/claudeAccountUsage.tsindex b5c9f2bc9b..636f8fe04e 100644--- a/apps/desktop/src/main/usage/claudeAccountUsage.ts+++ b/apps/desktop/src/main/usage/claudeAccountUsage.ts@@ -17,7 +17,7 @@* 且 todaySpend 已是本 user 当日全部用量, 该指标冗余, 2026-06-21 移除。** 设计取舍 (与 usageBroadcaster.ts 拆开的理由):- * - usageBroadcaster.ts 原本职责 = 本机 SQLite 累加的"今日 USD" + Codex token, 是+ * - usageBroadcaster.ts 原本职责 = 本机 SQLite 累加的"今日金额" + Codex token, 是* turn 收尾的"记账"层。账号配额是"账号画像"层, 来源是 HTTP API 而非 SDK turn delta —* 两件事不同步 (前者写 SQLite + 同步广播, 后者 fire-and-forget + 节流), 强行混在* 一个文件里会让 broadcaster 的 turn-done 路径多一个 IO side-effect。@@ -53,16 +53,17 @@ export const USAGE_CLAUDE_ACCOUNT_CHANGED = 'usage:claude-account-changed';export interface ClaudeAccountUsageSnapshot {/**- * 当前周期(网关部署为 30d / 月度) 跨所有客户端 + 所有 API key 的累计花费 USD,- * 来自 LiteLLM user.spend。不只本机本壳。+ * 当前周期(网关部署为 30d / 月度) 跨所有客户端 + 所有 API key 的累计花费,+ * 来自 Gateway user.spend,数值保持部署区域原生金额。不只本机本壳。*/spend: number;- /** 周期内预算上限 USD (来自 LiteLLM user.max_budget)。 */+ /** 周期内预算上限,保持 Gateway 原值 (来自 user.max_budget)。 */maxBudget: number;/** 下次重置时间 ISO8601 (来自 user.budget_reset_at)。 */budgetResetAt?: string | null;/**- * 今日 (UTC 日) 跨所有客户端累计 USD, 来自 LiteLLM /user/daily/activity 的+ * 今日 (UTC 日) 跨所有客户端累计金额,保持 Gateway 原值,来自+ * LiteLLM /user/daily/activity 的* results[0].metrics.spend。null = 端点暂时拉不到 (跟 cycle 是两个独立 fetch,* 任一可能失败); chip 的 daily 段会因此变 unavailable。*/@@ -194,7 +195,7 @@ async function fetchOnce(): Promise<ClaudeAccountUsageSnapshot | null> {if (!cycle) return null;const todaySpend = dailyActivity ? resolveDailyActivitySpend(dailyActivity).todaySpend : null;log.info(- `refreshed cycle=$${cycle.spend.toFixed(2)}/$${cycle.maxBudget.toFixed(2)} today=${todaySpend == null ? 'n/a' : `$${todaySpend.toFixed(2)}`} resetAt=${cycle.budgetResetAt ?? 'n/a'}`,+ `refreshed cycle=${cycle.spend.toFixed(2)}/${cycle.maxBudget.toFixed(2)} today=${todaySpend == null ? 'n/a' : todaySpend.toFixed(2)} resetAt=${cycle.budgetResetAt ?? 'n/a'}`,);return {spend: cycle.spend,diff --git a/apps/desktop/src/main/usage/modelPricing.ts b/apps/desktop/src/main/usage/modelPricing.tsindex 6301465f6a..3b05879ec7 100644--- a/apps/desktop/src/main/usage/modelPricing.ts+++ b/apps/desktop/src/main/usage/modelPricing.ts@@ -1,532 +1,308 @@/**- * modelPricing — 模型单价拉取与缓存。+ * modelPricing — Desktop 的 provider-scoped 价格投影。*- * 数据语义:- * LiteLLM gateway 的 /model_group/info 返回每个 model group 的- * input_cost_per_token / output_cost_per_token (USD per token), ×1e6 即- * UI 展示用的 "$X / Mtok"。codex/ 骨折路由目前由 gateway 暴露同底座原价,- * 客户端只对这些路由应用固定 15% 有效价折扣。- *- * 映射约定:- * model_group 名与 maker-core ModelDescriptor.id 一致 (claude-opus-4-8 /- * gpt-5.5 / codex/gpt-5.5 / qwen/qwen3.7-max ...), renderer 直接按 id 查表。- *- * 无价格条目:- * LiteLLM 配置里没填价的 group 返回 0/0 (如部分实验模型), **不是真免费**。- * 解析时直接丢弃, renderer 查不到则不显示价格行, 绝不能展示成 $0。- *- * 缓存与失败语义 (对齐 claudeAccountUsage.ts 的取舍):- * - 价格变化频率极低 → 成功结果缓存 6h, 并落盘到 userData/cache;- * 启动期预热, 前台读取优先返回内存 / 磁盘 stale 快照, 后台刷新- * - 失败 (网络 / 非 2xx) → 返当前 scope 的 stale 快照 (若有) 或 null;- * 60s 内不重试; key 缺失直接跳过, 不写失败冷却- * - in-flight 去重 — 多窗口同时首开下拉只发一次请求+ * XD 模型与价格只来自 model-access-server 的同一次 GET /models 响应。这里不再+ * 直接请求 LiteLLM;模型同步成功时整体替换 XD quote,失败时保留上一份成功快照。+ * Gateway per-token 数值在这里转换为 per-Mtok,币种只由构建区域决定。*/import { promises as fs, statSync } from 'node:fs';import path from 'node:path';-import { app } from 'electron';-import { createLogger } from '../logger';-import { getCurrentDbClientUserId } from '../localDb/client/current';-import { readClaudeApiKey } from '../maker-host/auth-adapters';-import { claudeUpstreamEndpoint } from '../maker-host/runtime-configs';-import { CODEX_SUBSCRIPTION_VALUE_PRICING } from '../../shared/codexSubscriptionValue.js';-import { providerSecretStorageKey } from '../../shared/providerSecrets';+import { app, BrowserWindow } from 'electron';++import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';+import {+ gatewayPricingCatalog,+ getModelPriceQuote,+ subscriptionDirectPriceQuote,+} from '../../shared/modelPriceQuote.js';+import type { ModelAccessGatewayModel } from '../../shared/modelAccess.js';+import { providerSecretStorageKey } from '../../shared/providerSecrets.js';+import {+ type ModelPriceQuote,+ type ModelPricingCatalog,+} from '../../shared/regionalMoney.js';+import { getCurrentDbClientUserId } from '../localDb/client/current.js';+import { createLogger } from '../logger.js';+import { getClientEndpoint } from '../clientEndpointsService.js';import { resolveOwnerScopedSecretStorageKey } from '../secrets/providerSecretStore.js';-import { CHATGPT_MODEL_PREFIX } from '../../shared/subscriptionModels';-// codex/ 预算折扣系数与判据归一在 turnCostCalculator (零 host 依赖纯模块), 这里-// import 用于把折扣折进价表, 并 re-export 维持既有 import 路径 ('../modelPricing')。-import { getCodexBudgetEffectiveCostMultiplier } from './turnCostCalculator';+import { getCodexBudgetEffectiveCostMultiplier } from './turnCostCalculator.js';-export { getCodexBudgetEffectiveCostMultiplier } from './turnCostCalculator';+export { getCodexBudgetEffectiveCostMultiplier } from './turnCostCalculator.js';+export { getModelPriceQuote } from '../../shared/modelPriceQuote.js';+export type {+ ModelPriceQuote as ModelPrice,+ ModelPricingCatalog as ModelPricingMap,+} from '../../shared/regionalMoney.js';const log = createLogger('modelPricing');--/** 单模型价格, USD per million tokens。 */-export interface ModelPrice {- inputUsdPerMtok: number;- outputUsdPerMtok: number;- /**- * 缓存读取 / 写入单价 (USD per Mtok), 来自 gateway 的- * cache_read_input_token_cost / cache_creation_input_token_cost。- * gateway 未暴露时为 undefined —— 消费方 (turnCostCalculator) 回退到 input 价。- */- cacheReadUsdPerMtok?: number;- cacheCreateUsdPerMtok?: number;-}--/** model id (= LiteLLM model_group 名) → 价格。 */-export type ModelPricingMap = Record<string, ModelPrice>;--/**- * 「订阅直连」bridge 模型(chatgpt/ / xai/)的价值估算展示价 —— 与 CODEX_SUBSCRIPTION_VALUE_PRICING- * (shared/codexSubscriptionValue)同语义:真实计费恒 0(经用户个人订阅额度),这张表只给- * 「本会话价值估算」用(tooltip 明确标注不代表真实账单)。key = 带前缀的 catalog model id。- * - chatgpt/*:与 codex 同底座 —— 程序化镜像 CODEX_SUBSCRIPTION_VALUE_PRICING(单一维护点,- * 调价 / codex 侧加模型只改那张表,这里自动跟上,杜绝两表漂移)。- * - xai/*:xAI 官网参考价(估算用,非真实账单;以官网为准)。- * 查不到的模型(如 discovery 未来新 slug 尚未进 codex 表)→ undefined → 不显示价值估算;- * 真实计费仍恒 0(subscription gate 不依赖本表),记账正确性不受影响。- */-const SUBSCRIPTION_DIRECT_VALUE_PRICING: ModelPricingMap = {- ...Object.fromEntries(- Object.entries(CODEX_SUBSCRIPTION_VALUE_PRICING).map(([m, p]) => [`${CHATGPT_MODEL_PREFIX}${m}`, p]),- ),- 'xai/grok-4.5': { inputUsdPerMtok: 2, outputUsdPerMtok: 6, cacheReadUsdPerMtok: 0.5 },- 'xai/grok-4.3': { inputUsdPerMtok: 3, outputUsdPerMtok: 15 },- 'xai/grok-4.20': { inputUsdPerMtok: 3, outputUsdPerMtok: 15 },- 'xai/grok-code-fast': { inputUsdPerMtok: 0.2, outputUsdPerMtok: 1.5 },-};--const FETCH_TIMEOUT_MS = 5000;-/** 成功结果缓存时长 — 价格日级变化, 6h 足够新鲜。 */-const CACHE_TTL_MS = 6 * 60 * 60 * 1000;-/** 失败后的重试冷却 — 防离线时反复打 gateway。 */-const FAILURE_RETRY_MS = 60_000;-const DISK_CACHE_VERSION = 2;+const DISK_CACHE_VERSION = 3;const DISK_CACHE_FILE = 'model-pricing.json';-const FETCH_SKIPPED_MISSING_KEY = Symbol('fetch-skipped-missing-key');-type FetchModelPricingResult = ModelPricingMap | null | typeof FETCH_SKIPPED_MISSING_KEY;-let cache: ModelPricingMap | null = null;-let cacheScope: string | null = null;-let cacheAt = 0;-const lastFailureAtByScope = new Map<string, number>();-const inflightByScope = new Map<string, Promise<ModelPricingMap | null>>();-const hydratedScopes = new Set<string>();-const hydrateInFlightByScope = new Map<string, Promise<ModelPricingMap | null>>();-const missingModelRefreshAt = new Map<string, number>();--interface LiteLlmModelGroupInfo {- data?: Array<{- model_group?: string;- input_cost_per_token?: number;- output_cost_per_token?: number;- cache_read_input_token_cost?: number;- cache_creation_input_token_cost?: number;- }>;-}+export const MODEL_PRICING_CHANGED_CHANNEL = 'usage:model-pricing-changed';interface DiskCachePayload {- version?: number;- fetchedAt?: number;- baseUrl?: string;- cacheScope?: string;- pricing?: unknown;-}--interface PricingScope {- identity: string;- apiKey: string;- baseUrl: string;+ version: number;+ scope: string;+ fetchedAt: number;+ pricing: ModelPricingCatalog;}-function currentBaseUrl(): string {- return claudeUpstreamEndpoint().trim();-}+let cache: ModelPricingCatalog | null = null;+let cacheScope: string | null = null;+let cacheAt = 0;+let modelSyncInflight: Promise<unknown> | null = null;+const hydratedScopes = new Set<string>();+const hydrateInflightByScope = new Map<+ string,+ Promise<ModelPricingCatalog | null>+>();-function currentKeyCacheIdentity(): string | null {+function currentKeyCacheIdentity(): string {try {- const physicalKey = resolveOwnerScopedSecretStorageKey(providerSecretStorageKey('xd'));- if (!physicalKey) return null;- const file = path.join(app.getPath('userData'), 'safe-storage', `${physicalKey}.enc`);+ const physicalKey = resolveOwnerScopedSecretStorageKey(+ providerSecretStorageKey('xd'),+ );+ if (!physicalKey) return 'key=missing';+ const file = path.join(+ app.getPath('userData'),+ 'safe-storage',+ `${physicalKey}.enc`,+ );const stat = statSync(file, { bigint: true });- return `file=${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;+ return `key=${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;} catch {- return null;+ return 'key=missing';}}-function currentPricingScope(): PricingScope | null {- const apiKey = readClaudeApiKey();- const baseUrl = currentBaseUrl();- if (!apiKey || !baseUrl) return null;- const userId = getCurrentDbClientUserId() ?? 'anonymous';- const keyIdentity = currentKeyCacheIdentity();- if (!keyIdentity) return null;- return {- identity: `v1|base=${baseUrl}|user=${userId}|key=${keyIdentity}`,- apiKey,- baseUrl,- };+function currentScope(): string {+ return [+ 'v1',+ `region=${CURRENT_CINDY_REGION}`,+ `base=${getClientEndpoint('modelAccessApiBaseUrl').trim()}`,+ `user=${getCurrentDbClientUserId() ?? 'anonymous'}`,+ currentKeyCacheIdentity(),+ ].join('|');}function diskCachePath(): string {return path.join(app.getPath('userData'), 'cache', DISK_CACHE_FILE);}-function isValidUsdPerMtok(value: unknown): value is number {+function isNonNegativeFinite(value: unknown): value is number {return typeof value === 'number' && Number.isFinite(value) && value >= 0;}-function validateDiskPricing(value: unknown): ModelPricingMap | null {- if (!value || typeof value !== 'object' || Array.isArray(value)) return null;- const out: ModelPricingMap = {};- for (const [rawModel, rawPrice] of Object.entries(value as Record<string, unknown>)) {- const model = rawModel.trim();- if (!model || !rawPrice || typeof rawPrice !== 'object' || Array.isArray(rawPrice)) continue;- const price = rawPrice as Partial<ModelPrice>;- if (!isValidUsdPerMtok(price.inputUsdPerMtok) || !isValidUsdPerMtok(price.outputUsdPerMtok)) continue;- let next: ModelPrice = {- inputUsdPerMtok: price.inputUsdPerMtok,- outputUsdPerMtok: price.outputUsdPerMtok,- };- if (isValidUsdPerMtok(price.cacheReadUsdPerMtok)) next.cacheReadUsdPerMtok = price.cacheReadUsdPerMtok;- if (isValidUsdPerMtok(price.cacheCreateUsdPerMtok)) next.cacheCreateUsdPerMtok = price.cacheCreateUsdPerMtok;- next = applyKnownOpenAiCachePricing(model, next);- out[model] = next;+function validateQuote(+ value: unknown,+ providerId: string,+ modelId: string,+): ModelPriceQuote | undefined {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;+ const quote = value as Partial<ModelPriceQuote>;+ if (+ quote.providerId !== providerId ||+ quote.modelId !== modelId ||+ (quote.currency !== 'CNY' && quote.currency !== 'USD') ||+ quote.source !== 'gateway' ||+ quote.approximate !== false ||+ !isNonNegativeFinite(quote.inputPerMtok) ||+ !isNonNegativeFinite(quote.outputPerMtok)+ ) {+ return undefined;}- return Object.keys(out).length > 0 ? out : null;-}--function validateDiskPayload(value: unknown, scopeIdentity: string): { pricing: ModelPricingMap; fetchedAt: number } | null {- if (!value || typeof value !== 'object') return null;- const payload = value as DiskCachePayload;- if (payload.version !== DISK_CACHE_VERSION) return null;- if (payload.baseUrl !== currentBaseUrl()) return null;- if (payload.cacheScope !== scopeIdentity) return null;- if (!Number.isFinite(payload.fetchedAt) || Number(payload.fetchedAt) <= 0) return null;- const pricing = validateDiskPricing(payload.pricing);- if (!pricing) return null;- return { pricing, fetchedAt: Number(payload.fetchedAt) };+ const next: ModelPriceQuote = {+ providerId,+ modelId,+ currency: quote.currency,+ source: 'gateway',+ approximate: false,+ inputPerMtok: quote.inputPerMtok,+ outputPerMtok: quote.outputPerMtok,+ };+ if (isNonNegativeFinite(quote.cacheReadPerMtok)) {+ next.cacheReadPerMtok = quote.cacheReadPerMtok;+ }+ if (isNonNegativeFinite(quote.cacheCreatePerMtok)) {+ next.cacheCreatePerMtok = quote.cacheCreatePerMtok;+ }+ return next;}-async function hydrateFromDisk(scopeIdentity: string): Promise<ModelPricingMap | null> {- if (hydratedScopes.has(scopeIdentity)) return cacheScope === scopeIdentity ? cache : null;- let hydrateInFlight = hydrateInFlightByScope.get(scopeIdentity);- if (!hydrateInFlight) {- hydrateInFlight = (async () => {- try {- const raw = await fs.readFile(diskCachePath(), 'utf8');- const parsed = validateDiskPayload(JSON.parse(raw), scopeIdentity);- if (!parsed) return cacheScope === scopeIdentity ? cache : null;- cache = parsed.pricing;- cacheScope = scopeIdentity;- cacheAt = parsed.fetchedAt;- log.debug(`hydrated model pricing cache: ${Object.keys(cache).length} priced groups`);- return cache;- } catch (err) {- const code = typeof err === 'object' && err && 'code' in err ? String((err as { code?: unknown }).code) : '';- if (code !== 'ENOENT') {- log.debug('hydrate model pricing cache failed:', err instanceof Error ? err.message : String(err));- }- return cacheScope === scopeIdentity ? cache : null;- } finally {- hydratedScopes.add(scopeIdentity);- hydrateInFlightByScope.delete(scopeIdentity);- }- })();- hydrateInFlightByScope.set(scopeIdentity, hydrateInFlight);+function validateCatalog(value: unknown): ModelPricingCatalog | null {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ const xdValue = (value as Record<string, unknown>).xd;+ if (!xdValue || typeof xdValue !== 'object' || Array.isArray(xdValue)) return null;+ const xd: Record<string, ModelPriceQuote> = {};+ for (const [rawModelId, rawQuote] of Object.entries(xdValue)) {+ const modelId = rawModelId.trim();+ if (!modelId) continue;+ const quote = validateQuote(rawQuote, 'xd', modelId);+ if (quote) xd[modelId] = quote;}- return hydrateInFlight;+ return Object.keys(xd).length > 0 ? { xd } : null;}-async function writeDiskCache(scopeIdentity: string, pricing: ModelPricingMap, fetchedAt: number): Promise<void> {- const file = diskCachePath();+async function writeDiskCache(+ scope: string,+ pricing: ModelPricingCatalog,+ fetchedAt: number,+): Promise<void> {try {+ const file = diskCachePath();await fs.mkdir(path.dirname(file), { recursive: true });const payload: DiskCachePayload = {version: DISK_CACHE_VERSION,+ scope,fetchedAt,- baseUrl: currentBaseUrl(),- cacheScope: scopeIdentity,pricing,};await fs.writeFile(file, JSON.stringify(payload), 'utf8');- hydratedScopes.add(scopeIdentity);+ hydratedScopes.add(scope);} catch (err) {- log.debug('write model pricing cache failed:', err instanceof Error ? err.message : String(err));+ log.debug(+ 'write model pricing cache failed:',+ err instanceof Error ? err.message : String(err),+ );}}-function scopedCache(scopeIdentity: string): ModelPricingMap | null {- return cacheScope === scopeIdentity ? cache : null;-}--function hasFreshCache(scopeIdentity: string, now = Date.now()): boolean {- return Boolean(scopedCache(scopeIdentity) && now - cacheAt < CACHE_TTL_MS);-}--function toUsdPerMtok(value: unknown): number | null {- const n = Number(value);- if (!Number.isFinite(n) || n < 0) return null;- return n * 1e6;-}--/**- * 解析可选 cache 档价: 与 base 价同口径走 toUsdPerMtok (接受数值或数值字符串,- * gateway 偶尔把价格序列化成字符串), 但把 null / undefined / 空串视为"未提供"- * → 返回 undefined (不挂), 区别于数值 0 (= gateway 明确的免费缓存读, 合法挂成 0)。- * 不能直接复用 toUsdPerMtok: Number(null)=0 / Number('')=0 会把"未提供"误挂成- * "免费", 让 resolveTurnCost 误以为有 cache 档价而绕过 SDK 兜底, 把缓存重轮次少算。- */-function toOptionalCacheUsdPerMtok(value: unknown): number | undefined {- if (value == null || value === '') return undefined;- const n = toUsdPerMtok(value);- return n == null ? undefined : n;-}--function applyCodexBudgetDiscount(model: string, price: ModelPrice): ModelPrice {- const multiplier = getCodexBudgetEffectiveCostMultiplier(model);- if (multiplier === 1) return price;- // 折所有档价 (含可选 cache 档), 保持 codex/ 各档一致折扣。- const scaled: ModelPrice = {- inputUsdPerMtok: price.inputUsdPerMtok * multiplier,- outputUsdPerMtok: price.outputUsdPerMtok * multiplier,- };- if (price.cacheReadUsdPerMtok != null) scaled.cacheReadUsdPerMtok = price.cacheReadUsdPerMtok * multiplier;- if (price.cacheCreateUsdPerMtok != null) scaled.cacheCreateUsdPerMtok = price.cacheCreateUsdPerMtok * multiplier;- return scaled;-}--function getOpenAiCachedInputPriceRatio(model: string): number | null {- const bareModel = model.startsWith('codex/') ? model.slice('codex/'.length) : model;- switch (bareModel) {- case 'gpt-5.5':- case 'gpt-5.4':- case 'gpt-5.4-mini':- case 'gpt-5.4-nano':- case 'gpt-5.3-codex':- case 'gpt-5.6-sol':- case 'gpt-5.6-terra':- case 'gpt-5.6-luna':- return 0.1;- default:- return null;- }-}--/**- * GPT-5.6 起官方对 cache write 按 1.25x uncached input 计费; 此前 GPT 系列- * 自动缓存写入不加价 (write token 走正常 input 价), 消费方回退 input 价即为- * 正确口径, 故老模型不进此清单、不兜底。- */-function getOpenAiCacheWriteInputPriceRatio(model: string): number | null {- const bareModel = model.startsWith('codex/') ? model.slice('codex/'.length) : model;- switch (bareModel) {- case 'gpt-5.6-sol':- case 'gpt-5.6-terra':- case 'gpt-5.6-luna':- return 1.25;- default:+async function hydrateFromDisk(scope: string): Promise<ModelPricingCatalog | null> {+ if (hydratedScopes.has(scope)) return cacheScope === scope ? cache : null;+ const existing = hydrateInflightByScope.get(scope);+ if (existing) return existing;+ const hydrateInflight = (async () => {+ try {+ const raw = JSON.parse(await fs.readFile(diskCachePath(), 'utf8')) as Partial<DiskCachePayload>;+ if (+ raw.version !== DISK_CACHE_VERSION ||+ raw.scope !== scope ||+ !Number.isFinite(raw.fetchedAt) ||+ Number(raw.fetchedAt) <= 0+ ) {+ return null;+ }+ const pricing = validateCatalog(raw.pricing);+ if (!pricing) return null;+ if (currentScope() !== scope) return null;+ cache = pricing;+ cacheScope = scope;+ cacheAt = Number(raw.fetchedAt);+ log.debug(+ `hydrated model pricing cache: ${Object.keys(pricing.xd ?? {}).length} XD quotes`,+ );+ return pricing;+ } catch (err) {+ const code =+ typeof err === 'object' && err && 'code' in err+ ? String((err as { code?: unknown }).code)+ : '';+ if (code !== 'ENOENT') {+ log.debug(+ 'hydrate model pricing cache failed:',+ err instanceof Error ? err.message : String(err),+ );+ }return null;- }-}--function applyKnownOpenAiCachePricing(model: string, price: ModelPrice): ModelPrice {- // read / write 两档独立兜底: gateway 只给了其中一档时, 另一档仍按官方口径补齐。- const readRatio = price.cacheReadUsdPerMtok == null ? getOpenAiCachedInputPriceRatio(model) : null;- const writeRatio = price.cacheCreateUsdPerMtok == null ? getOpenAiCacheWriteInputPriceRatio(model) : null;- if (readRatio == null && writeRatio == null) return price;- const next: ModelPrice = { ...price };- if (readRatio != null) next.cacheReadUsdPerMtok = price.inputUsdPerMtok * readRatio;- if (writeRatio != null) next.cacheCreateUsdPerMtok = price.inputUsdPerMtok * writeRatio;- return next;+ } finally {+ hydratedScopes.add(scope);+ hydrateInflightByScope.delete(scope);+ }+ })();+ hydrateInflightByScope.set(scope, hydrateInflight);+ return hydrateInflight;}-/**- * 解析 /model_group/info 响应为价格表 (纯函数, 单测覆盖)。- * - per-token → per-Mtok (×1e6)- * - 0/0 (未配置价) / 非有限数 / 缺 model_group 的条目丢弃- * - cache_read / cache_creation 档价为可选: 与 base 价同口径 (数值或数值字符串都收,- * 含数值 0 = 免费缓存读); null / 缺失 / 空串 / 非数值不挂 —— 消费方回退到 input 价计。- * - 已知 OpenAI/Codex GPT 模型若 gateway 未给 cache_read,按官方 cached input- * 10% input 口径补齐;GPT-5.6 系列若未给 cache_creation,按官方 cache write- * 1.25x input 口径补齐;其它模型仍不臆测。- */-export function parseModelGroupInfo(json: unknown): ModelPricingMap {- const out: ModelPricingMap = {};- const data = (json as LiteLlmModelGroupInfo | null)?.data;- if (!Array.isArray(data)) return out;- for (const entry of data) {- if (!entry || typeof entry !== 'object') continue;- const name = typeof entry.model_group === 'string' ? entry.model_group.trim() : '';- if (!name) continue;- const input = toUsdPerMtok(entry.input_cost_per_token);- const output = toUsdPerMtok(entry.output_cost_per_token);- if (input == null || output == null) continue;- // 0/0 = LiteLLM 没配价, 不是免费 — 丢弃, UI 隐藏价格行。- if (input === 0 && output === 0) continue;- const price: ModelPrice = { inputUsdPerMtok: input, outputUsdPerMtok: output };- // cache 档价可选: 与 base 价同口径解析 (数值或数值字符串都收), null / 缺失 /- // 非数值视为"未提供"→ 消费方回退 input 价; 数值 0 = 免费缓存读, 合法挂成 0。- const cacheRead = toOptionalCacheUsdPerMtok(entry.cache_read_input_token_cost);- if (cacheRead !== undefined) price.cacheReadUsdPerMtok = cacheRead;- const cacheCreate = toOptionalCacheUsdPerMtok(entry.cache_creation_input_token_cost);- if (cacheCreate !== undefined) price.cacheCreateUsdPerMtok = cacheCreate;- out[name] = applyCodexBudgetDiscount(name, applyKnownOpenAiCachePricing(name, price));+function broadcastPricing(pricing: ModelPricingCatalog | null): void {+ for (const win of BrowserWindow.getAllWindows()) {+ if (!win.isDestroyed()) {+ win.webContents.send(MODEL_PRICING_CHANGED_CHANNEL, pricing);+ }}- return out;}/**- * Codex 订阅价值估算用单价。- * - 优先使用 gateway 价格, 覆盖 API key 用户的真实计费路径。- * - 官方订阅模型缺少价格表条目时, 回退到内置展示价。- * - codex/ 骨折路由只使用 gateway 价格。+ * 与模型同步同快照更新 XD quote。models 非空但没有标准 input/output 价格时,+ * 价格投影会被清空,不复活旧模型价格。*/-export function getCodexSubscriptionValuePrice(- model: string,- pricing: ModelPricingMap | null | undefined,-): ModelPrice | undefined {- const livePrice = pricing?.[model];- return livePrice ? applyKnownOpenAiCachePricing(model, livePrice) : CODEX_SUBSCRIPTION_VALUE_PRICING[model];+export function replaceGatewayModelPricing(+ models: readonly ModelAccessGatewayModel[],+): ModelPricingCatalog | null {+ const scope = currentScope();+ const next = gatewayPricingCatalog(models, CURRENT_CINDY_REGION);+ const pricing = Object.keys(next.xd ?? {}).length > 0 ? next : null;+ cache = pricing;+ cacheScope = scope;+ cacheAt = Date.now();+ hydratedScopes.add(scope);+ void writeDiskCache(scope, next, cacheAt);+ broadcastPricing(pricing);+ return pricing;+}++export function clearGatewayModelPricing(): void {+ replaceGatewayModelPricing([]);+}++export function trackGatewayModelPricingSync(sync: Promise<unknown>): void {+ modelSyncInflight = sync;+ void sync.then(+ () => {+ if (modelSyncInflight === sync) modelSyncInflight = null;+ },+ () => {+ if (modelSyncInflight === sync) modelSyncInflight = null;+ },+ );}-/**- * 「订阅直连」bridge 模型(chatgpt/ / xai/)的价值估算单价。- * 内置参考表(SUBSCRIPTION_DIRECT_VALUE_PRICING)为主 —— gateway 价表按裸 id 索引、- * 不含带前缀的订阅模型,故这里不查 gateway,直接用内置表。查不到 → undefined(不显示价值)。- */-export function getSubscriptionDirectValuePrice(model: string): ModelPrice | undefined {- return SUBSCRIPTION_DIRECT_VALUE_PRICING[model];-}--async function fetchOnce(scope: PricingScope): Promise<FetchModelPricingResult> {- const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);- try {- const res = await fetch(`${scope.baseUrl.replace(/\/+$/, '')}/model_group/info`, {- headers: { Authorization: `Bearer ${scope.apiKey}` },- signal: controller.signal,- });- if (!res.ok) {- log.debug(`model_group/info non-2xx: ${res.status}`);- return null;- }- const parsed = parseModelGroupInfo(await res.json());- const count = Object.keys(parsed).length;- if (count === 0) {- // 端点通了但一条价格都没有 — 视为失败, 保留 stale 缓存。- log.debug('model_group/info returned no priced entries');- return null;- }- log.info(`refreshed model pricing: ${count} priced groups`);- return parsed;- } catch (err) {- log.debug('model_group/info failed:', err instanceof Error ? err.message : String(err));- return null;- } finally {- clearTimeout(timer);- }-}--async function refreshModelPricing(): Promise<ModelPricingMap | null> {- const scope = currentPricingScope();- if (!scope) return null;- const existing = inflightByScope.get(scope.identity);- if (existing) return existing;- const inflight = fetchOnce(scope)- .then((next) => {- if (next === FETCH_SKIPPED_MISSING_KEY) return scopedCache(scope.identity);- if (next) {- if (currentPricingScope()?.identity !== scope.identity) return scopedCache(scope.identity);- const fetchedAt = Date.now();- cache = next;- cacheScope = scope.identity;- cacheAt = fetchedAt;- lastFailureAtByScope.delete(scope.identity);- void writeDiskCache(scope.identity, next, fetchedAt);- } else {- lastFailureAtByScope.set(scope.identity, Date.now());- }- return scopedCache(scope.identity);- })- .finally(() => {- inflightByScope.delete(scope.identity);- });- inflightByScope.set(scope.identity, inflight);- return inflight;-}--function refreshModelPricingInBackground(): void {- void refreshModelPricing().catch((err) => {- log.debug('background model pricing refresh failed:', err instanceof Error ? err.message : String(err));- });-}--/** 当前 scope 是否正在刷新价格表。用于 UI 聚合判断缺价是否仍可能补齐。 */export function isModelPricingRefreshInFlight(): boolean {- const scope = currentPricingScope();- return Boolean(scope && inflightByScope.has(scope.identity));+ return modelSyncInflight !== null;}-/**- * 读取模型价格表 (启动预热 + lazy fetch + 内存 / 磁盘缓存)。- * 失败时回退 stale 缓存 (若有), 都没有则 null — renderer 据此隐藏价格 tooltip。- */-export async function getModelPricing(): Promise<ModelPricingMap | null> {- const scope = currentPricingScope();- if (!scope) return null;- const now = Date.now();- if (hasFreshCache(scope.identity, now)) return cache;-- await hydrateFromDisk(scope.identity);- const afterHydrate = Date.now();- if (hasFreshCache(scope.identity, afterHydrate)) return cache;- if (afterHydrate - (lastFailureAtByScope.get(scope.identity) ?? 0) < FAILURE_RETRY_MS) return scopedCache(scope.identity);-- if (scopedCache(scope.identity)) {- refreshModelPricingInBackground();- return scopedCache(scope.identity);- }-- return refreshModelPricing();+export async function getModelPricing(): Promise<ModelPricingCatalog | null> {+ const scope = currentScope();+ if (cacheScope === scope) return cache;+ return hydrateFromDisk(scope);}/**- * 真实计费路径用的价格查询。- *- * 普通 UI 读取可以接受 stale 快返; 但 API/gateway 记账如果目标模型缺价格,- * 不能因为过期缓存缺项就永久丢本轮费用。这里仅在“缓存已过期且缺目标模型”- * 时等待一次刷新, 其它情况保持与 getModelPricing 相同的快路径。+ * 计费热路径等待模型同步已经落下的本地投影,不再自己联网。providerId 是必需的,+ * 同模型从 XD/OpenAI/订阅来源进入时不会串价。*/-export async function getModelPricingForModel(model: string): Promise<ModelPricingMap | null> {- const normalized = model.trim();- if (!normalized) return getModelPricing();- const scope = currentPricingScope();- if (!scope) return null;- const refreshForMissingModel = async (): Promise<ModelPricingMap | null> => {- const missKey = `${scope.identity}\0${normalized}`;- const lastMissRefreshAt = missingModelRefreshAt.get(missKey) ?? 0;- if (Date.now() - lastMissRefreshAt < FAILURE_RETRY_MS) return scopedCache(scope.identity);- const beforeCacheAt = cacheScope === scope.identity ? cacheAt : 0;- const next = await refreshModelPricing();- if (next?.[normalized]) missingModelRefreshAt.delete(missKey);- else if (cacheScope === scope.identity && cacheAt > beforeCacheAt) {- missingModelRefreshAt.set(missKey, Date.now());- }- return next;- };-- const now = Date.now();- if (hasFreshCache(scope.identity, now)) {- return scopedCache(scope.identity)?.[normalized] ? cache : refreshForMissingModel();- }+export async function getModelPricingForModel(+ providerId: string | null | undefined,+ modelId: string,+): Promise<ModelPricingCatalog | null> {+ if (modelSyncInflight) await modelSyncInflight;+ const pricing = await getModelPricing();+ void getModelPriceQuote(pricing, providerId, modelId);+ return pricing;+}- await hydrateFromDisk(scope.identity);- const afterHydrate = Date.now();- if (hasFreshCache(scope.identity, afterHydrate)) {- return scopedCache(scope.identity)?.[normalized] ? cache : refreshForMissingModel();- }+export function getCodexSubscriptionValuePrice(+ modelId: string,+ pricing: ModelPricingCatalog | null | undefined,+): ModelPriceQuote | undefined {+ return getModelPriceQuote(pricing, 'openai', modelId);+}- return refreshForMissingModel();+export function getSubscriptionDirectValuePrice(+ modelId: string,+): ModelPriceQuote | undefined {+ return subscriptionDirectPriceQuote(modelId);}-/**- * 启动期预热价格表: 先把磁盘缓存放进内存, 再按 TTL 后台刷新。- * 调用方不需要 await; 返回 Promise 只方便单测精确等待。- */+/** 启动只读磁盘快照;真正的新价格仍由 /models 同步整体替换。 */export async function prewarmModelPricing(): Promise<void> {try {- const scope = currentPricingScope();- if (!scope) return;- await hydrateFromDisk(scope.identity);- const now = Date.now();- if (hasFreshCache(scope.identity, now) || now - (lastFailureAtByScope.get(scope.identity) ?? 0) < FAILURE_RETRY_MS) return;- await refreshModelPricing();+ await getModelPricing();} catch (err) {- log.debug('prewarm model pricing failed:', err instanceof Error ? err.message : String(err));+ log.debug(+ 'prewarm model pricing failed:',+ err instanceof Error ? err.message : String(err),+ );}}@@ -534,9 +310,7 @@ export function __resetModelPricingCacheForTesting(): void {cache = null;cacheScope = null;cacheAt = 0;- lastFailureAtByScope.clear();- inflightByScope.clear();+ modelSyncInflight = null;hydratedScopes.clear();- hydrateInFlightByScope.clear();- missingModelRefreshAt.clear();+ hydrateInflightByScope.clear();}diff --git a/apps/desktop/src/main/usage/turnCostCalculator.ts b/apps/desktop/src/main/usage/turnCostCalculator.tsindex 9d267a8b26..a8b442ed08 100644--- a/apps/desktop/src/main/usage/turnCostCalculator.ts+++ b/apps/desktop/src/main/usage/turnCostCalculator.ts@@ -1,48 +1,31 @@/**- * turnCostCalculator — 单轮费用计算的共享纯函数 (无 Electron / DB)。- *- * 背景 bug: 非 Anthropic 模型 (gpt-5.5 / deepseek / glm / qwen) 走 claude-code SDK- * 时, SDK 的 total_cost_usd 是按 Anthropic 单价算的 (实测 gpt-5.5 被按 Opus $5/$25- * 计, 真实网关价 $2/$8, 高估 ~2.5x)。- *- * 策略 = HYBRID:- * - Anthropic 模型 (claude-*): **一律信任 SDK 自报 cost**。理由: SDK 对自家模型- * cache-correct (cacheRead ~0.1x / cacheWrite ~1.25x, 网关价表没这两档);且- * OAuth 订阅模式下 SDK cost 为 0、API 模式下为真实花费 —— 直接复用 SDK 数字- * 就天然分清"订阅价值 vs 真实 spend", 不会把订阅价值混进 daily_spend。- * - 非 Anthropic / provider-routed 模型: 用远端 gateway 价 × token 重算, 丢弃 SDK- * 的 Anthropic 错价。- *- * 关键不变量: codex/ 0.15 折扣按"价格来源"恰好应用一次 —— gateway 价路径已在- * modelPricing.applyCodexBudgetDiscount 里折进价表, 消费方不得再乘; SDK 兜底路径- * (gateway 价缺失) 用的是未折扣的 SDK 数字, 由 resolveTurnCost 在那一处补乘一次。- * 两路互斥, 永不双重打折。+ * 单轮费用计算。定价先看实际 billing route,再看模型;模型名不再决定来源。*/-import { getClaudeSubscriptionValueFallbackPrice } from '../../shared/claudeSubscriptionValue.js';+import type { CindyRegion } from '@cindy/maker-shared/brand-identity';++import {+ getModelPriceQuote,+ providerReferencePriceQuote,+ regionalizeModelPriceQuote,+} from '../../shared/modelPriceQuote.js';+import {+ addRegionalMoney,+ regionalizeUsd,+ type ModelPriceQuote,+ type ModelPricingCatalog,+ type RegionalMoney,+} from '../../shared/regionalMoney.js';import { buildTurnUsageDetails, type TurnUsageDetails } from '../../shared/turnUsageDetails.js';import { isSubscriptionDirectModel } from '../../shared/subscriptionModels.js';-import type { ModelUsageDeltaEntry } from './modelUsageDelta';-import type { ModelPrice, ModelPricingMap } from './modelPricing';+import type { ModelUsageDeltaEntry } from './modelUsageDelta.js';-/**- * codex/ 「骨折」预算路由的统一折扣系数 —— **全局唯一来源**。- * 既被 modelPricing.applyCodexBudgetDiscount 折进 gateway 价表, 也被本模块- * resolveTurnCost 的 SDK 兜底分支用。放在这个零依赖纯模块里 (而非 modelPricing,- * 它顶层 import 了 Electron host 依赖), 让消费方无需为一个常量拖进 host 副作用。- */const CODEX_BUDGET_PRICE_MULTIPLIER = 0.15;-/**- * codex/ 预算模型的有效成本系数: codex/ 前缀 → 0.15, 其余 → 1 (无影响)。- * 唯一折扣应用判据, 他处不得再硬编码 0.15 / 再判 startsWith('codex/')。- */export function getCodexBudgetEffectiveCostMultiplier(model: string): number {- if (!model.startsWith('codex/')) return 1;- return CODEX_BUDGET_PRICE_MULTIPLIER;+ return model.startsWith('codex/') ? CODEX_BUDGET_PRICE_MULTIPLIER : 1;}-/** 单轮各类 token 增量 (per-turn, 非累计)。 */export interface TurnTokenDeltas {inputTokens: number;outputTokens: number;@@ -50,34 +33,35 @@ export interface TurnTokenDeltas {cacheCreateTokens: number;}+export type BillingRoute =+ | 'xd-gateway'+ | 'provider-api'+ | 'subscription'+ | 'unknown';++export interface TurnPricingContext {+ providerId: string | null;+ billingRoute: BillingRoute;+ region: CindyRegion;+}+export type TurnCostSource = 'sdk' | 'gateway' | 'sdk-fallback' | 'subscription';export interface TurnCostResolution {- /** 归一化后的裸 model id (供调用方写 daily_model_usage, 免重复归一化)。 */model: string;- costUsd: number;+ money: RegionalMoney | null;source: TurnCostSource;}-/**- * 剥掉 SDK 路由后缀, 得到与 gateway 价格表对齐的裸 key。- * 'gpt-5.5[1m]' → 'gpt-5.5'; 'codex/gpt-5.5[1m]' → 'codex/gpt-5.5'- * 'claude-opus-4-8[1m]' → 'claude-opus-4-8'; 'claude-sonnet-5[1m]' → 'claude-sonnet-5'- * 'sonnet[1m]' → 'sonnet'(历史裸别名产物,仅存量数据;见 isAnthropicModel 的兼容分支)- * '' / null / undefined → 'unknown'- * 这是全局**唯一**的归一化入口。- */-export function normalizeModelIdForPricing(model: string | null | undefined): string {+export function normalizeModelIdForPricing(+ model: string | null | undefined,+): string {const trimmed = (model ?? '').trim();if (!trimmed) return 'unknown';- // 去掉尾部 [..] 段 (SDK 1M beta 通道后缀 / 变体)。codex/ 等前缀保留。const stripped = trimmed.replace(/\[[^\]]*\]\s*$/, '').trim();return stripped || 'unknown';}-/**- * Anthropic 自家模型 —— 这些一律信任 claude-code SDK 自报 cost。传入归一化后的 id。- */export function isAnthropicModel(normalizedModel: string): boolean {return (normalizedModel.startsWith('claude-') ||@@ -88,155 +72,150 @@ export function isAnthropicModel(normalizedModel: string): boolean {}/**- * token × gateway 价 → USD, cache-aware。无 price → null (绝不返 0 误导)。- *- * cacheRead / cacheCreate 优先用 gateway 的 cache 档价 (cacheReadUsdPerMtok /- * cacheCreateUsdPerMtok), 缺失时回退 input 价。当 cache 档价缺失且 cacheCreate=0- * 时, 算式与历史 estimateCodexCost 逐字节一致 —— 保证 Codex 现有数字不漂。+ * token × quote → quote 币种金额。cache 价缺失时按输入价计,和详情文案一致。*/export function computeGatewayTurnCost(tokens: TurnTokenDeltas,- price: ModelPrice | undefined,+ price: ModelPriceQuote | undefined,): number | null {if (!price) return null;- const cacheReadPrice = price.cacheReadUsdPerMtok ?? price.inputUsdPerMtok;- const cacheCreatePrice = price.cacheCreateUsdPerMtok ?? price.inputUsdPerMtok;+ const cacheReadPrice = price.cacheReadPerMtok ?? price.inputPerMtok;+ const cacheCreatePrice = price.cacheCreatePerMtok ?? price.inputPerMtok;return (- (tokens.inputTokens * price.inputUsdPerMtok +- tokens.outputTokens * price.outputUsdPerMtok ++ (tokens.inputTokens * price.inputPerMtok ++ tokens.outputTokens * price.outputPerMtok +tokens.cacheReadTokens * cacheReadPrice +tokens.cacheCreateTokens * cacheCreatePrice) /- 1e6+ 1_000_000);}-/**- * 单个 (模型, token 增量) → 本轮该模型的 USD, 实现 HYBRID 策略。- *- * @param sdkCostDelta claude-code 该模型 SDK 自报的 per-turn cost delta; codex 无 (undefined)。- */+export function computePriceQuoteTurnMoney(+ tokens: TurnTokenDeltas,+ price: ModelPriceQuote | undefined,+): RegionalMoney | null {+ if (!price) return null;+ const amount = computeGatewayTurnCost(tokens, price);+ if (amount == null) return null;+ const valueEstimate = price.source === 'subscription-reference';+ return {+ amount: Math.max(0, amount),+ currency: price.currency,+ approximate: price.approximate || valueEstimate,+ kind: valueEstimate ? 'value-estimate' : 'actual-cost',+ ...(valueEstimate+ ? { estimateReasons: ['subscription-value', 'reference-price'] }+ : price.approximate+ ? { estimateReasons: ['reference-price'] }+ : {}),+ };+}+export function resolveTurnCost(args: {rawModel: string;tokens: TurnTokenDeltas;sdkCostDelta?: number;- pricing: ModelPricingMap | null | undefined;+ pricing: ModelPricingCatalog | null | undefined;+ context: TurnPricingContext;}): TurnCostResolution {- const { rawModel, tokens, sdkCostDelta, pricing } = args;- const id = normalizeModelIdForPricing(rawModel);-- // Anthropic: 一律信任 SDK (OAuth 下=0、API 下=真实、cache-correct)。- if (isAnthropicModel(id)) {- return { model: id, costUsd: Math.max(0, sdkCostDelta ?? 0), source: 'sdk' };- }+ const { rawModel, tokens, sdkCostDelta, pricing, context } = args;+ const model = normalizeModelIdForPricing(rawModel);- // 订阅直连 (chatgpt/ / xai/): 经 bridge 走用户**个人订阅**额度, 不产生公司网关真实计费 →- // cost 恒 0, 不进 daily_spend / sessions.total_cost_usd。子 agent 走 bridge 模型同理天然排除- // (per-model 逐个 resolve)。「订阅价值估算」另走展示路 (getSubscriptionDirectValuePrice), 不入此账。- // 注意判据用带前缀的归一化 id, 与真网关同名裸模型 (如 gateway 的 gpt-5.5) 天然区分, 不误伤。- if (isSubscriptionDirectModel(id)) {- return { model: id, costUsd: 0, source: 'subscription' };+ if (+ context.billingRoute === 'subscription' ||+ isSubscriptionDirectModel(model)+ ) {+ return { model, money: null, source: 'subscription' };}- // 非 Anthropic: 用 gateway 价重算, 丢弃 SDK 的 Anthropic 错价。- const price = pricing?.[id];- if (price) {- const computed = computeGatewayTurnCost(tokens, price);- if (computed != null) return { model: id, costUsd: Math.max(0, computed), source: 'gateway' };+ if (context.billingRoute === 'xd-gateway') {+ const quote = getModelPriceQuote(pricing, 'xd', model);+ return {+ model,+ money: computePriceQuoteTurnMoney(tokens, quote),+ source: quote ? 'gateway' : 'sdk-fallback',+ };}- // 非 Anthropic 但查不到价 → 回退 SDK 数字 (claude-code 真实 API 计费别丢账)。- // codex/ 预算路由特例: gateway 价缺失 (冷启动 / 无该行) 时, SDK 自报数字按- // Anthropic 误算且**未含** 0.15 折扣, 这里补乘一次 —— gateway 路径的价表已折好- // (applyCodexBudgetDiscount), 两路互斥, 不会双重打折; 与 register.ts 的 total_cost_usd- // 窄兜底口径一致。非 codex/ 模型 multiplier=1, 等价于直接透传 SDK 数字。- const budgetMultiplier = getCodexBudgetEffectiveCostMultiplier(id);- return { model: id, costUsd: Math.max(0, (sdkCostDelta ?? 0) * budgetMultiplier), source: 'sdk-fallback' };+ const sdkAmount = Math.max(+ 0,+ (sdkCostDelta ?? 0) * getCodexBudgetEffectiveCostMultiplier(model),+ );+ const money =+ sdkAmount > 0+ ? regionalizeUsd(sdkAmount, context.region, 'fixed-fx')+ : null;+ return {+ model,+ money,+ source:+ context.billingRoute === 'provider-api' ? 'sdk' : 'sdk-fallback',+ };}-/** 单模型解析结果, model 已归一化 (写 daily_model_usage 用)。 */export interface ResolvedModelCost {model: string;- costUsd: number;+ money: RegionalMoney | null;source: TurnCostSource;deltas: TurnTokenDeltas;}export interface ClaudeTurnCostResolution {- /** 本轮总额, 喂 daily_spend / sessions / per-message 三个 sink。 */- turnTotalUsd: number;- /** 按模型拆分, 喂 daily_model_usage (model 已归一化为裸 id)。 */+ turnMoney: RegionalMoney | null;perModel: ResolvedModelCost[];}-/**- * claude-code done 的整段费用推导 (纯函数, 把 register.ts 的逻辑抽出来便于单测)。- * 逐模型走 resolveTurnCost (Anthropic→SDK, 非 Anthropic→gateway), 总额 = 各模型加总- * —— 四个 sink 由此天然一致。- */export function resolveClaudeTurnCostSinks(modelDeltas: ModelUsageDeltaEntry[],- pricing: ModelPricingMap | null | undefined,+ pricing: ModelPricingCatalog | null | undefined,+ context: TurnPricingContext,): ClaudeTurnCostResolution {const perModel: ResolvedModelCost[] = [];- let turnTotalUsd = 0;- for (const d of modelDeltas) {+ const money: RegionalMoney[] = [];+ for (const delta of modelDeltas) {const tokens: TurnTokenDeltas = {- inputTokens: d.inputTokensDelta,- outputTokens: d.outputTokensDelta,- cacheReadTokens: d.cacheReadTokensDelta,- cacheCreateTokens: d.cacheCreateTokensDelta,+ inputTokens: delta.inputTokensDelta,+ outputTokens: delta.outputTokensDelta,+ cacheReadTokens: delta.cacheReadTokensDelta,+ cacheCreateTokens: delta.cacheCreateTokensDelta,};- const res = resolveTurnCost({- rawModel: d.model,+ const resolved = resolveTurnCost({+ rawModel: delta.model,tokens,- sdkCostDelta: d.costUsdDelta,+ sdkCostDelta: delta.costUsdDelta,pricing,+ context,+ });+ perModel.push({+ model: resolved.model,+ money: resolved.money,+ source: resolved.source,+ deltas: tokens,});- perModel.push({ model: res.model, costUsd: res.costUsd, source: res.source, deltas: tokens });- turnTotalUsd += res.costUsd;+ if (resolved.money && resolved.money.amount > 0) money.push(resolved.money);}- return { turnTotalUsd, perModel };+ return {+ turnMoney: money.length > 0 ? addRegionalMoney(money) : null,+ perModel,+ };}-/**- * Claude 订阅(Anthropic OAuth)轮的「本轮价值」估算 —— 订阅会话 SDK 自报 cost=0,- * chip 上的 $ 用 token × Anthropic 牌价折算参考价值(与 Codex 订阅估值同口径,- * 只挂 per-message isEstimate,绝不进 daily_spend / sessions.total_cost_usd)。- *- * 只对「Anthropic 模型且本轮解析 cost 为 0」的条目估值(cost>0 说明 SDK 报了真实- * API 账单,或非 Anthropic 模型走了网关真实计费 —— 都不属于订阅价值)。选价顺序:- * 网关价表精确条目(带 cache 档价)→ 家族牌价兜底表;两级都 miss 的模型跳过。- * 全部跳过 / 加总为 0 → null(本轮不显示估值,绝不用 0 误导)。- */export function estimateClaudeSubscriptionTurnValue(perModel: ResolvedModelCost[],- pricing: ModelPricingMap | null | undefined,-): number | null {- let total = 0;- for (const m of perModel) {- if (!isAnthropicModel(m.model)) continue;- if (m.costUsd > 0) continue;- const price = pricing?.[m.model] ?? getClaudeSubscriptionValueFallbackPrice(m.model);- if (!price) continue;- const value = computeGatewayTurnCost(m.deltas, price);- if (value != null && value > 0) total += value;+ 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);+ if (value && value.amount > 0) values.push(value);}- return total > 0 ? total : null;+ return values.length > 0 ? addRegionalMoney(values) : null;}-/**- * 由 claude-code done 事件构造挂在消息上的 token/cache/费用明细 (MessageActionBar tooltip)。- *- * 口径 (rule: 与总额 `$` 同源):- * - 有 modelUsage deltas 时, input/output/cacheRead/cacheCreate **全部**从 deltas 求和 ——- * deltas 是 SDK modelUsage 的 per-turn 增量、按模型分桶, 含 subagent (如 Task 工具跑的- * Haiku)。早期版本 input/output 取自顶层 `usage` (基本只反映主线程, 漏 subagent output),- * 与 cacheRead 口径不一致, 这里统一掉。- * - 无 deltas 的窄兜底路径 (done 只带 total_cost_usd) 回退顶层 `usage`。- *- * perModel (来自 resolveClaudeTurnCostSinks) 传入时, 产出按模型费用明细 perModelCost ——- * 仅保留 cost>0 的模型, tooltip 据此展示「Opus $x / Haiku(subagent) $y」。- */export function buildClaudeTurnUsageDetails(usage: {input_tokens?: number;@@ -250,23 +229,29 @@ export function buildClaudeTurnUsageDetails(): TurnUsageDetails | null {const hasModelUsageDeltas = Boolean(deltas && deltas.length > 0);const perModelCost = perModel- ?.filter((m) => Number.isFinite(m.costUsd) && m.costUsd > 0)- .map((m) => ({ model: m.model, costUsd: m.costUsd }));+ ?.filter((item) => item.money && item.money.amount > 0)+ .map((item) => ({ model: item.model, money: item.money! }));return buildTurnUsageDetails({inputTokens: hasModelUsageDeltas- ? deltas?.reduce((sum, d) => sum + d.inputTokensDelta, 0)+ ? deltas?.reduce((sum, delta) => sum + delta.inputTokensDelta, 0): usage?.input_tokens,outputTokens: hasModelUsageDeltas- ? deltas?.reduce((sum, d) => sum + d.outputTokensDelta, 0)+ ? deltas?.reduce((sum, delta) => sum + delta.outputTokensDelta, 0): usage?.output_tokens,cacheReadTokens: hasModelUsageDeltas- ? deltas?.reduce((sum, d) => sum + d.cacheReadTokensDelta, 0)+ ? deltas?.reduce((sum, delta) => sum + delta.cacheReadTokensDelta, 0): usage?.cache_read_input_tokens,cacheCreateTokens: hasModelUsageDeltas- ? deltas?.reduce((sum, d) => sum + d.cacheCreateTokensDelta, 0)+ ? deltas?.reduce((sum, delta) => sum + delta.cacheCreateTokensDelta, 0): usage?.cache_creation_input_tokens,- model: deltas?.length === 1 ? deltas[0].model : (hasModelUsageDeltas ? undefined : fallbackModel),- models: hasModelUsageDeltas ? deltas?.map((d) => d.model) : undefined,- perModelCost: perModelCost && perModelCost.length > 0 ? perModelCost : undefined,+ model:+ deltas?.length === 1+ ? deltas[0].model+ : hasModelUsageDeltas+ ? undefined+ : fallbackModel,+ models: hasModelUsageDeltas ? deltas?.map((delta) => delta.model) : undefined,+ perModelCost:+ perModelCost && perModelCost.length > 0 ? perModelCost : undefined,});}diff --git a/apps/desktop/src/main/usage/usageHistory.ts b/apps/desktop/src/main/usage/usageHistory.tsindex 96725d7248..4b8b2a890c 100644--- a/apps/desktop/src/main/usage/usageHistory.ts+++ b/apps/desktop/src/main/usage/usageHistory.ts@@ -23,16 +23,28 @@ import { getAllSpendDays, localDayKey } from '../localDb/dailySpend';import { getModelUsageSince, type DailyModelUsageRow } from '../localDb/dailyModelUsage';import { getCurrentDbClientUserId } from '../localDb/client/current';import { createLogger } from '../logger';-import { getClaudeSubscriptionValueFallbackPrice } from '../../shared/claudeSubscriptionValue';import {getCodexSubscriptionValuePrice,getModelPricing,getSubscriptionDirectValuePrice,isModelPricingRefreshInFlight,- type ModelPrice,type ModelPricingMap,} from './modelPricing';-import { computeGatewayTurnCost } from './turnCostCalculator';+import { computePriceQuoteTurnMoney } from './turnCostCalculator';+import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';+import {+ getModelPriceQuote,+ regionalizeModelPriceQuote,+} from '../../shared/modelPriceQuote.js';+import {+ addCompatibleRegionalMoney,+ normalizeRegionalMoney,+ regionalAmountFromUsdReference,+ regionalCurrencyForRegion,+ type ModelPriceQuote,+ type RegionalMoney,+ zeroRegionalMoney,+} from '../../shared/regionalMoney.js';const log = createLogger('usageHistory');@@ -47,7 +59,7 @@ const ANOMALY_MIN_ACTIVE_DAYS = 3;const MODEL_WINDOW_DAYS = 30;/** 等价格表的最长预算 (ms) — 缓存命中时是同步快返, 只有冷启动网络 fetch 会触及。 */const PRICING_WAIT_BUDGET_MS = 200;-const DISK_CACHE_VERSION = 1;+const DISK_CACHE_VERSION = 2;const DISK_CACHE_FILE = 'usage-history.json';/** 后台刷新完成后, renderer 的短轮询能拿到 fresh payload, 避免 stale 状态自循环。 */const MEMORY_FRESH_MS = 10_000;@@ -55,7 +67,7 @@ const CODEX_BILLING_MODEL_SUFFIX_RE = /#billing=(api|subscription)$/;export interface UsageHistoryDay {day: string;- costUsd: number;+ money: RegionalMoney;/** 当日 token 合计 (daily_model_usage 口径, 表上线前的历史日为 0)。 */tokens: number;}@@ -64,9 +76,9 @@ export interface UsageHistoryModel {agentKind: 'claude-code' | 'codex';model: string;/** SDK 实报美元 (Claude); Codex 恒 0。 */- costUsd: number;+ money: RegionalMoney;/** Codex: token × 价格表估算; 模型无价格条目或价格表不可用时 null。Claude 恒 null。 */- estimatedCostUsd: number | null;+ estimatedMoney: RegionalMoney | null;inputTokens: number;outputTokens: number;cacheReadTokens: number;@@ -79,11 +91,11 @@ export interface UsageHistoryModelDay {agentKind: 'claude-code' | 'codex';model: string;/** 可比金额: Claude 实报 $; Codex 为价格表估算 (无价格 → 0, 只出现在图例 token 行)。 */- amountUsd: number;+ money: RegionalMoney;/** 实际 API / gateway 计费金额。 */- apiCostUsd: number;+ apiMoney: RegionalMoney;/** 订阅 token 价值估算金额。 */- subscriptionEstimateUsd: number;+ subscriptionEstimateMoney: RegionalMoney;tokens: number;}@@ -109,21 +121,21 @@ export interface UsageHistoryPayload {models: UsageHistoryModel[];streak: { current: number; longest: number };totals: {- today: number;- last30Days: number;+ today: RegionalMoney;+ last30Days: RegionalMoney;/*** 近 30 天展示口径: 实际 API / gateway spend + Codex OAuth 订阅 token 价值估算。* 订阅估算按模型明细单独叠加, 不会把已计入 API spend 的模型行重复算入。*/- last30DaysWithEstimatedValue: number;+ last30DaysWithEstimatedValue: RegionalMoney;/** last30DaysWithEstimatedValue - last30Days, 用于 UI 标注"含估算"。 */- last30DaysEstimatedValue: number;+ last30DaysEstimatedValue: RegionalMoney;/** 今日 token 合计 (input+output+cacheRead+cacheCreate, daily_model_usage 口径; 表上线后才有)。 */todayTokens: number;/** 近 30 天 token 合计 (同上口径; 0 = 还没积累出数据, renderer 据此隐藏 token 段)。 */last30DaysTokens: number;};- anomaly: { isAnomalous: boolean; trailing7DayAvg: number | null };+ anomaly: { isAnomalous: boolean; trailing7DayAvg: RegionalMoney | null };}/** YYYY-MM-DD → 前一天 (本地时区语义, 纯字符串进出)。 */@@ -183,13 +195,20 @@ export function computeStreaks(export function computeAnomaly(spendByDay: ReadonlyMap<string, number>,todayKey: string,+ thresholds: {+ activeDayMin?: number;+ anomalyMinToday?: number;+ } = {},): { isAnomalous: boolean; trailing7DayAvg: number | null } {+ const activeDayMin = thresholds.activeDayMin ?? ACTIVE_DAY_MIN_USD;+ const anomalyMinToday =+ thresholds.anomalyMinToday ?? ANOMALY_MIN_TODAY_USD;let sum = 0;let activeCount = 0;for (let i = 1; i <= 7; i++) {const v = spendByDay.get(shiftDayKey(todayKey, -i)) ?? 0;sum += v;- if (v >= ACTIVE_DAY_MIN_USD) activeCount += 1;+ if (v >= activeDayMin) activeCount += 1;}if (activeCount < ANOMALY_MIN_ACTIVE_DAYS) {return { isAnomalous: false, trailing7DayAvg: null };@@ -197,14 +216,14 @@ export function computeAnomaly(const avg = sum / 7;const today = spendByDay.get(todayKey) ?? 0;return {- isAnomalous: today >= ANOMALY_MIN_TODAY_USD && today > ANOMALY_FACTOR * avg,+ isAnomalous: today >= anomalyMinToday && today > ANOMALY_FACTOR * avg,trailing7DayAvg: avg,};}/** 测试注入用的数据读取依赖。 */export interface UsageHistoryDeps {- getAllSpendDays(): Promise<Array<{ day: string; costUsd: number }>>;+ getAllSpendDays(): Promise<Array<{ day: string; money: RegionalMoney }>>;getModelUsageSince(sinceDayKey: string): Promise<DailyModelUsageRow[]>;getModelPricing(): Promise<ModelPricingMap | null>;isModelPricingRefreshInFlight(): boolean;@@ -258,10 +277,10 @@ function validateUsageHistoryPayload(value: unknown): UsageHistoryPayload | nullif (!payload.streak || !payload.totals || !payload.anomaly) return null;if (!isFiniteNumber(payload.streak.current) || !isFiniteNumber(payload.streak.longest)) return null;if (- !isFiniteNumber(payload.totals.today) ||- !isFiniteNumber(payload.totals.last30Days) ||- !isFiniteNumber(payload.totals.last30DaysWithEstimatedValue) ||- !isFiniteNumber(payload.totals.last30DaysEstimatedValue) ||+ !normalizeRegionalMoney(payload.totals.today) ||+ !normalizeRegionalMoney(payload.totals.last30Days) ||+ !normalizeRegionalMoney(payload.totals.last30DaysWithEstimatedValue) ||+ !normalizeRegionalMoney(payload.totals.last30DaysEstimatedValue) ||!isFiniteNumber(payload.totals.todayTokens) ||!isFiniteNumber(payload.totals.last30DaysTokens)) {@@ -269,7 +288,10 @@ function validateUsageHistoryPayload(value: unknown): UsageHistoryPayload | null}if (typeof payload.anomaly.isAnomalous !== 'boolean' ||- !(isFiniteNumber(payload.anomaly.trailing7DayAvg) || payload.anomaly.trailing7DayAvg === null)+ !(+ normalizeRegionalMoney(payload.anomaly.trailing7DayAvg) ||+ payload.anomaly.trailing7DayAvg === null+ )) {return null;}@@ -332,11 +354,19 @@ function getSubscriptionValuePriceFor(agentKind: 'claude-code' | 'codex',model: string,pricing: ModelPricingMap | null,-): ModelPrice | undefined {+): ModelPriceQuote | undefined {if (agentKind === 'codex') {- return getSubscriptionDirectValuePrice(model) ?? getCodexSubscriptionValuePrice(model, pricing);+ const quote =+ getSubscriptionDirectValuePrice(model) ??+ getCodexSubscriptionValuePrice(model, pricing);+ return quote+ ? regionalizeModelPriceQuote(quote, CURRENT_CINDY_REGION)+ : undefined;}- return pricing?.[model] ?? getClaudeSubscriptionValueFallbackPrice(model);+ const quote = getModelPriceQuote(pricing, 'anthropic', model);+ return quote+ ? regionalizeModelPriceQuote(quote, CURRENT_CINDY_REGION)+ : undefined;}async function hydrateFromDisk(expectedOptsKey: string): Promise<UsageHistoryPayload | null> {@@ -462,7 +492,21 @@ export async function readUsageHistoryWith(const todayKey = deps.todayKey();const allDays = await deps.getAllSpendDays();- const spendByDay = new Map(allDays.map((r) => [r.day, r.costUsd]));+ const spendByDay = new Map(+ allDays.map((row) => [row.day, row.money.amount]),+ );+ const zeroActual = () => zeroRegionalMoney(CURRENT_CINDY_REGION);+ const zeroEstimate = () =>+ zeroRegionalMoney(CURRENT_CINDY_REGION, 'value-estimate');+ const addOrZero = (+ values: RegionalMoney[],+ kind: 'actual-cost' | 'value-estimate' = 'actual-cost',+ ): RegionalMoney =>+ addCompatibleRegionalMoney(+ values,+ regionalCurrencyForRegion(CURRENT_CINDY_REGION),+ ) ??+ (kind === 'actual-cost' ? zeroActual() : zeroEstimate());const heatmapCutoff = shiftDayKey(todayKey, -(windowDays - 1));const modelCutoff = shiftDayKey(todayKey, -(MODEL_WINDOW_DAYS - 1));@@ -482,13 +526,15 @@ export async function readUsageHistoryWith(}const daysMap = new Map<string, UsageHistoryDay>();for (const r of allDays) {- if (r.day >= heatmapCutoff && r.costUsd > 0) daysMap.set(r.day, { day: r.day, costUsd: r.costUsd, tokens: 0 });+ if (r.day >= heatmapCutoff && r.money.amount > 0) {+ daysMap.set(r.day, { day: r.day, money: r.money, tokens: 0 });+ }}for (const [day, tokens] of tokensByDay) {if (tokens <= 0) continue;const existing = daysMap.get(day);if (existing) existing.tokens = tokens;- else daysMap.set(day, { day, costUsd: 0, tokens });+ else daysMap.set(day, { day, money: zeroActual(), tokens });}const days = [...daysMap.values()].sort((a, b) => (a.day < b.day ? -1 : 1));// pricing 不许阻塞首页首帧: 冷启动时 getModelPricing 是一次最长 5s 的网络请求,@@ -529,8 +575,8 @@ export async function readUsageHistoryWith(agg = {agentKind,model,- costUsd: 0,- estimatedCostUsd: null,+ money: zeroActual(),+ estimatedMoney: null,inputTokens: 0,outputTokens: 0,cacheReadTokens: 0,@@ -538,7 +584,15 @@ export async function readUsageHistoryWith(};byKey.set(key, agg);}- agg.costUsd += row.costUsd;+ if (row.money.amount > 0) {+ agg.money =+ agg.money.amount > 0+ ? (addCompatibleRegionalMoney(+ [agg.money, row.money],+ regionalCurrencyForRegion(CURRENT_CINDY_REGION),+ ) ?? row.money)+ : row.money;+ }agg.inputTokens += row.inputTokens;agg.outputTokens += row.outputTokens;agg.cacheReadTokens += row.cacheReadTokens;@@ -546,8 +600,8 @@ export async function readUsageHistoryWith(}for (const [key, m] of byKey) {const modelKey = key.slice(key.indexOf('\u0000') + 1);- if (m.costUsd === 0 && isSubscriptionUsageModel(modelKey)) {- m.estimatedCostUsd = computeGatewayTurnCost(+ if (m.money.amount === 0 && isSubscriptionUsageModel(modelKey)) {+ m.estimatedMoney = computePriceQuoteTurnMoney(m,getSubscriptionValuePriceFor(m.agentKind, m.model, pricing),);@@ -560,23 +614,29 @@ export async function readUsageHistoryWith(const modelDaily: UsageHistoryModelDay[] = modelRows.map((row) => {const agentKind = row.agentKind === 'codex' ? ('codex' as const) : ('claude-code' as const);const model = displayModelName(row.model);- const apiCostUsd = row.costUsd > 0 ? row.costUsd : 0;- const subscriptionEstimateUsd = apiCostUsd === 0 && isSubscriptionUsageModel(row.model)- ? (computeGatewayTurnCost(row, getSubscriptionValuePriceFor(agentKind, model, pricing)) ?? 0)- : 0;- const amountUsd = apiCostUsd > 0 ? apiCostUsd : subscriptionEstimateUsd;+ const apiMoney = row.money;+ const subscriptionEstimateMoney =+ apiMoney.amount === 0 && isSubscriptionUsageModel(row.model)+ ? (computePriceQuoteTurnMoney(+ row,+ getSubscriptionValuePriceFor(agentKind, model, pricing),+ ) ?? zeroEstimate())+ : zeroEstimate();+ const money =+ apiMoney.amount > 0 ? apiMoney : subscriptionEstimateMoney;return {day: row.day,agentKind,model,- amountUsd,- apiCostUsd,- subscriptionEstimateUsd,+ money,+ apiMoney,+ subscriptionEstimateMoney,tokens: row.inputTokens + row.outputTokens + row.cacheReadTokens + row.cacheCreateTokens,};});// 可比金额 (实报或估算) 降序; 无金额的 token-only 行排最后 (按 token 量降序)- const comparable = (m: UsageHistoryModel) => (m.costUsd > 0 ? m.costUsd : (m.estimatedCostUsd ?? -1));+ const comparable = (m: UsageHistoryModel) =>+ m.money.amount > 0 ? m.money.amount : (m.estimatedMoney?.amount ?? -1);models.sort((a, b) => {const diff = comparable(b) - comparable(a);if (diff !== 0) return diff;@@ -585,30 +645,55 @@ export async function readUsageHistoryWith(return tokens(b) - tokens(a);});- const activeDays = allDays.filter((r) => r.costUsd >= ACTIVE_DAY_MIN_USD).map((r) => r.day);+ const activeDayMin = regionalAmountFromUsdReference(+ ACTIVE_DAY_MIN_USD,+ CURRENT_CINDY_REGION,+ );+ const anomalyMinToday = regionalAmountFromUsdReference(+ ANOMALY_MIN_TODAY_USD,+ CURRENT_CINDY_REGION,+ );+ const activeDays = allDays+ .filter((row) => row.money.amount >= activeDayMin)+ .map((row) => row.day);const last30Cutoff = shiftDayKey(todayKey, -(MODEL_WINDOW_DAYS - 1));- let last30 = 0;- for (const r of allDays) {- if (r.day >= last30Cutoff) last30 += r.costUsd;- }- const last30ActualByDay = new Map<string, number>();- for (const r of allDays) {- if (r.day >= last30Cutoff) last30ActualByDay.set(r.day, r.costUsd);+ const last30ActualByDay = new Map<string, RegionalMoney>();+ for (const row of allDays) {+ if (row.day >= last30Cutoff) {+ last30ActualByDay.set(row.day, row.money);+ }}- const last30SubscriptionEstimateByDay = new Map<string, number>();+ const last30SubscriptionEstimateByDay = new Map<string, RegionalMoney[]>();for (const row of modelDaily) {- last30SubscriptionEstimateByDay.set(- row.day,- (last30SubscriptionEstimateByDay.get(row.day) ?? 0) + row.subscriptionEstimateUsd,- );- }- const last30DisplayDays = new Set([...last30ActualByDay.keys(), ...last30SubscriptionEstimateByDay.keys()]);- let last30WithEstimatedValue = 0;- for (const day of last30DisplayDays) {- last30WithEstimatedValue +=- (last30ActualByDay.get(day) ?? 0) + (last30SubscriptionEstimateByDay.get(day) ?? 0);+ if (row.subscriptionEstimateMoney.amount <= 0) continue;+ const values = last30SubscriptionEstimateByDay.get(row.day) ?? [];+ values.push(row.subscriptionEstimateMoney);+ last30SubscriptionEstimateByDay.set(row.day, values);}- const last30EstimatedValue = Math.max(0, last30WithEstimatedValue - last30);+ const last30 = addOrZero([...last30ActualByDay.values()]);+ const last30EstimatedValue = addOrZero(+ [...last30SubscriptionEstimateByDay.values()].flat(),+ 'value-estimate',+ );+ const last30WithEstimatedValue =+ last30EstimatedValue.amount > 0+ ? (addCompatibleRegionalMoney(+ [last30, last30EstimatedValue],+ regionalCurrencyForRegion(CURRENT_CINDY_REGION),+ ) ?? last30)+ : last30;+ const anomalyRaw = computeAnomaly(spendByDay, todayKey, {+ activeDayMin,+ anomalyMinToday,+ });+ const trailing7Approximate = allDays.some(+ (row) =>+ row.day >= shiftDayKey(todayKey, -7) &&+ row.day < todayKey &&+ row.money.approximate,+ );+ const today =+ allDays.find((row) => row.day === todayKey)?.money ?? zeroActual();return {generatedAt: Date.now(),@@ -619,14 +704,28 @@ export async function readUsageHistoryWith(models,streak: computeStreaks(activeDays, todayKey),totals: {- today: spendByDay.get(todayKey) ?? 0,+ today,last30Days: last30,last30DaysWithEstimatedValue: last30WithEstimatedValue,last30DaysEstimatedValue: last30EstimatedValue,todayTokens,last30DaysTokens,},- anomaly: computeAnomaly(spendByDay, todayKey),+ anomaly: {+ isAnomalous: anomalyRaw.isAnomalous,+ trailing7DayAvg:+ anomalyRaw.trailing7DayAvg === null+ ? null+ : {+ amount: anomalyRaw.trailing7DayAvg,+ currency: today.currency,+ approximate: trailing7Approximate,+ kind: 'actual-cost',+ ...(trailing7Approximate+ ? { estimateReasons: ['legacy-usd'] }+ : {}),+ },+ },};}@@ -669,10 +768,15 @@ export function emptyUsageHistoryPayload(): UsageHistoryPayload {models: [],streak: { current: 0, longest: 0 },totals: {- today: 0,- last30Days: 0,- last30DaysWithEstimatedValue: 0,- last30DaysEstimatedValue: 0,+ today: zeroRegionalMoney(CURRENT_CINDY_REGION),+ last30Days: zeroRegionalMoney(CURRENT_CINDY_REGION),+ last30DaysWithEstimatedValue: zeroRegionalMoney(+ CURRENT_CINDY_REGION,+ ),+ last30DaysEstimatedValue: zeroRegionalMoney(+ CURRENT_CINDY_REGION,+ 'value-estimate',+ ),todayTokens: 0,last30DaysTokens: 0,},diff --git a/apps/desktop/src/main/usageBroadcaster.ts b/apps/desktop/src/main/usageBroadcaster.tsindex 404d55fab6..b2d602accd 100644--- a/apps/desktop/src/main/usageBroadcaster.ts+++ b/apps/desktop/src/main/usageBroadcaster.ts@@ -34,6 +34,7 @@ import {import type { AgentKind } from '@cindy/maker-core';import { createLogger } from './logger';+import type { RegionalMoney } from '../shared/regionalMoney.js';const log = createLogger('usageBroadcaster');@@ -51,14 +52,16 @@ export const USAGE_CLAUDE_SUBSCRIPTION_CHANGED = 'usage:claude-subscription-chanexport interface TodaySpendPayload {/** 本地时区 YYYY-MM-DD。 */day: string;- /** 当日累计 USD。 */- costUsd: number;+ money: RegionalMoney;+ /** Global/旧客户端兼容;CN 新金额绝不伪装为 USD。 */+ costUsd?: number;}/** 跨 agent 统一的 today usage 形状 —— maker:usage:today(agentKind) 返回值。 */export interface AgentTodayUsage {day: string;- /** Claude 有值, Codex undefined (SDK 不报 cost)。 */+ money?: RegionalMoney;+ /** 仅 USD 时的旧客户端兼容投影。 */costUsd?: number;/** Codex 有值, Claude undefined (Claude 链路走 cost 不走 token)。 */totalTokens?: number;@@ -101,10 +104,19 @@ export interface RateLimitSnapshot {* - costUsd 是 per-turn delta (cumulative - lastReported, 在 register.ts 里算好)* - 写库 + 广播是同步调用,不阻塞 turn 收尾 (SQLite better-sqlite3 是同步的, O(1) upsert)*/-export async function recordTurnSpend(costUsd: number, ts: number = Date.now()): Promise<void> {+export async function recordTurnSpend(+ money: RegionalMoney,+ ts: number = Date.now(),+): Promise<void> {try {- const result = await incrementDailySpend(costUsd, ts);- broadcastTodaySpend({ day: result.day, costUsd: result.costUsd });+ const result = await incrementDailySpend(money, ts);+ broadcastTodaySpend({+ day: result.day,+ money: result.money,+ ...(result.money.currency === 'USD'+ ? { costUsd: result.money.amount }+ : {}),+ });} catch (err) {// 写库失败不应阻塞主流程 —— 仅日志log.warn(@@ -116,9 +128,11 @@ export async function recordTurnSpend(costUsd: number, ts: number = Date.now()):/** Claude 今日 USD 累计 (供 IPC handler / 内部消费)。 */export async function readTodaySpend(): Promise<TodaySpendPayload> {+ const money = await getTodaySpend();return {day: localDayKey(),- costUsd: await getTodaySpend(),+ money,+ ...(money.currency === 'USD' ? { costUsd: money.amount } : {}),};}@@ -244,7 +258,11 @@ function readCodexTodaySnapshot(): CodexTokenSnapshot {export async function readAgentTodayUsage(agentKind: AgentKind): Promise<AgentTodayUsage> {if (agentKind === 'claude-code') {const s = await readTodaySpend();- return { day: s.day, costUsd: s.costUsd };+ return {+ day: s.day,+ money: s.money,+ ...(s.costUsd !== undefined ? { costUsd: s.costUsd } : {}),+ };}if (agentKind === 'codex') {const s = readCodexTodaySnapshot();diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 96e25e69a0..da59262341 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -411,6 +411,7 @@ const fanOutMakerClaudeSessionRouteChanged = createIpcFanOut('maker:claude-sessiconst fanOutMakerSessionBackgroundActivityChanged = createIpcFanOut('maker:session-background-activity-changed');const fanOutMakerUsageTodaySpend = createIpcFanOut('usage:today-spend-changed'); // Claude USDconst fanOutMakerUsageTodayTokens = createIpcFanOut('usage:today-tokens-changed'); // Codex token+const fanOutMakerUsageModelPricing = createIpcFanOut('usage:model-pricing-changed');const fanOutMakerUsageClaudeAccount = createIpcFanOut('usage:claude-account-changed'); // Claude 月度配额const fanOutMakerUsageCodexAccount = createIpcFanOut('usage:codex-account-changed'); // Codex 订阅用量const fanOutMakerUsageXaiRateLimit = createIpcFanOut('usage:xai-rate-limit-changed'); // xAI bridge 限流快照@@ -4310,9 +4311,10 @@ contextBridge.exposeInMainWorld('electronAPI', {/** Claude 订阅账号余量 (5h/周/分模型窗口, cached-first, main 侧按需后台刷新)。 */getClaudeSubscription: (): Promise<unknown | null> =>ipcRenderer.invoke('maker:usage:claude-subscription'),- /** 模型单价表 (LiteLLM /model_group/info, main 端内存 + 磁盘缓存)。失败时 null。 */+ /** provider-scoped 模型单价表,由 model-access /models 同次快照更新。 */getModelPricing: (): Promise<unknown | null> =>- ipcRenderer.invoke('maker:usage:model-pricing'),+ ipcRenderer.invoke('maker:usage:model-pricing-v2'),+ onModelPricingChanged: fanOutMakerUsageModelPricing,/** 用量历史聚合 (首页仪表盘: 热力图 + streak + 按模型拆分, main 侧算好)。 */getHistory: (opts?: { days?: number; forceRefresh?: boolean }): Promise<unknown> =>ipcRenderer.invoke('maker:usage:history', opts),diff --git a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.tsindex 39414b064f..a11d69fd9a 100644--- a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts+++ b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts@@ -930,7 +930,9 @@ describe('automation-generated sessions', () => {expect(storageSource).toContain('turnCostIsEstimate === true');expect(storageSource).toContain('SQLITE_IN_CHUNK_SIZE');expect(storageSource).toContain("when 'user' then 0 else 1 end");- expect(storageSource).toContain('entry.totalCostUsd += cost');+ expect(storageSource).toContain('entry.costValues.push(turnCost.costMoney)');+ expect(storageSource).toContain('addCompatibleRegionalMoney(summary.costValues)');+ expect(storageSource).toContain('totalMoney');expect(storageSource).toContain('listLegacySessionRuns');expect(storageSource).toContain("LEGACY_SCHEDULE_TITLE_PREFIX = '[Schedule] '");expect(storageSource).toContain("LEGACY_SESSION_RUN_ID_PREFIX = 'legacy-session:'");@@ -946,7 +948,7 @@ describe('automation-generated sessions', () => {expect(schedulePageSource).toContain('useScheduleCostSummaries(sorted)');expect(taskListPaneSource).toContain('costSummariesLoaded');expect(taskListCellSource).toContain('scheduler.cell.totalCost');- expect(taskListCellSource).toContain('formatUsd(totalCostUsd ?? 0)');+ expect(taskListCellSource).toContain('formatTurnCostMoney(totalMoney)');expect(runHistoryPaneSource).toContain('groupRunsForHistory');expect(runHistoryPaneSource).toContain('PERSISTENT_SESSION_PREVIEW_LIMIT = 3');expect(runHistoryPaneSource).toContain('expandRemainingRuns');diff --git a/apps/desktop/src/renderer/__tests__/homeUsageDashboardSource.test.ts b/apps/desktop/src/renderer/__tests__/homeUsageDashboardSource.test.tsindex 6b2e4913f0..e86274b55e 100644--- a/apps/desktop/src/renderer/__tests__/homeUsageDashboardSource.test.ts+++ b/apps/desktop/src/renderer/__tests__/homeUsageDashboardSource.test.ts@@ -11,28 +11,34 @@ const dailyBarsSource = readFileSync(resolve(__dirname, '../components/new-chat/UsageDailyBars.tsx'),'utf8',);+const heatmapSource = readFileSync(+ resolve(__dirname, '../components/new-chat/UsageHeatmap.tsx'),+ 'utf8',+);describe('HomeUsageDashboard source contract', () => {it('uses the Claude account daily spend for the visible today amount when available', () => {expect(source).toMatch(- /const accountTodaySpend =\s+typeof claudeQuota\?\.todaySpend === 'number' \? claudeQuota\.todaySpend : null;/,+ /const accountTodayMoney =\s+typeof claudeQuota\?\.todaySpend === 'number'\s+\? gatewayMoney\(claudeQuota\.todaySpend, CURRENT_CINDY_REGION\)\s+: null;/,);- expect(source).toContain('const hasAccountTodaySpend = accountTodaySpend !== null;');+ expect(source).toContain('const hasAccountTodaySpend = accountTodayMoney !== null;');expect(source).toContain('const layoutHistory = history ?? emptyLayoutHistory;');expect(source).toContain(- 'const displayTodaySpend = accountTodaySpend ?? layoutHistory.totals.today;',+ 'const displayTodaySpend = accountTodayMoney ?? layoutHistory.totals.today;',);expect(source).toContain('const ACCOUNT_LOCAL_TODAY_MATCH_EPSILON = 0.01;');expect(source).toMatch(- /function isSameDisplayedTodaySpend\(\s+accountTodaySpend: number \| null,\s+localTodaySpend: number,\s+\): boolean/,+ /function isSameDisplayedTodaySpend\(\s+accountTodaySpend: RegionalMoney \| null,\s+localTodaySpend: RegionalMoney,\s+\): boolean/,);expect(source).toMatch(- /layoutHistory\.anomaly\.isAnomalous &&\s+isSameDisplayedTodaySpend\(accountTodaySpend, layoutHistory\.totals\.today\);/,+ /layoutHistory\.anomaly\.isAnomalous &&\s+isSameDisplayedTodaySpend\(accountTodayMoney, layoutHistory\.totals\.today\);/,);expect(source).toContain(- '`${formatUsd(displayTodaySpend)} / ${formatCompactUsd(softDailyLimit)}`',+ '`${formatMoney(displayTodaySpend)} / ${formatCompactMoney(softDailyLimitMoney)}`',+ );+ expect(source).toMatch(+ /hasSpendValue \?\s+formatMoney\(displayTodaySpend\)\s+:\s+UNKNOWN_VALUE/,);- expect(source).toMatch(/hasSpendValue \?\s+formatUsd\(displayTodaySpend\)\s+:\s+UNKNOWN_VALUE/);expect(source).toContain('warning={showLocalSpendAnomaly}');});@@ -54,6 +60,17 @@ 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)',+ );+ expect(heatmapSource).not.toContain("money.currency ?? 'USD'");+ expect(dailyBarsSource).not.toContain("money.currency ?? 'USD'");+ });+it('shows cached usage immediately while marking background refresh', () => {expect(source).toContain('const { history, refreshing: usageRefreshing } = useUsageHistory({ paused: collapsed, userId: user?.id });',@@ -73,14 +90,13 @@ describe('HomeUsageDashboard source contract', () => {it('loads once while collapsed but skips usage push subscriptions', () => {expect(source).toContain('useUsageHistory({ paused: collapsed, userId: user?.id })');- const hookSource = readFileSync(- resolve(__dirname, '../hooks/useUsageHistory.ts'),- 'utf8',- );+ const hookSource = readFileSync(resolve(__dirname, '../hooks/useUsageHistory.ts'), 'utf8');const loadIndex = hookSource.indexOf('void load(scopeKey);');const pausedIndex = hookSource.indexOf('if (paused) {');const pushIndex = hookSource.indexOf('window.electronAPI.maker.usage.onTodaySpendChanged');- const tokenPushIndex = hookSource.indexOf('window.electronAPI.maker.usage.onTodayTokensChanged');+ const tokenPushIndex = hookSource.indexOf(+ 'window.electronAPI.maker.usage.onTodayTokensChanged',+ );expect(loadIndex).toBeGreaterThan(0);expect(pausedIndex).toBeGreaterThan(0);expect(loadIndex).toBeLessThan(pausedIndex);@@ -89,78 +105,72 @@ describe('HomeUsageDashboard source contract', () => {});it('scopes renderer usage-history snapshots by account', () => {- const hookSource = readFileSync(- resolve(__dirname, '../hooks/useUsageHistory.ts'),- 'utf8',- );+ const hookSource = readFileSync(resolve(__dirname, '../hooks/useUsageHistory.ts'), 'utf8');expect(hookSource).toContain('function storageKeyForScope(scopeKey: string): string');expect(hookSource).toContain('localStorage.getItem(storageKeyForScope(scopeKey))');- expect(hookSource).toContain('localStorage.setItem(storageKeyForScope(scopeKey), JSON.stringify(p))');+ expect(hookSource).toContain(+ 'localStorage.setItem(storageKeyForScope(scopeKey), JSON.stringify(p))',+ );expect(hookSource).toContain('const scopes = new Map<string, UsageHistoryScopeState>();');expect(hookSource).toContain('const scopeKey = normalizeScopeKey(opts?.userId);');});it('does not render the previous account history after the scope changes', () => {- const hookSource = readFileSync(- resolve(__dirname, '../hooks/useUsageHistory.ts'),- 'utf8',+ const hookSource = readFileSync(resolve(__dirname, '../hooks/useUsageHistory.ts'), 'utf8');+ expect(hookSource).toContain(+ 'const [historyState, setHistoryState] = useState<{ scopeKey: string; value: UsageHistoryPayload | null }>',);- expect(hookSource).toContain('const [historyState, setHistoryState] = useState<{ scopeKey: string; value: UsageHistoryPayload | null }>');expect(hookSource).toContain('setHistoryState({ scopeKey, value });');- expect(hookSource).toContain('history: historyState.scopeKey === scopeKey ? historyState.value : scope.cache,');+ expect(hookSource).toContain(+ 'history: historyState.scopeKey === scopeKey ? historyState.value : scope.cache,',+ );});it('adds subscription estimates to mixed actual daily bars', () => {+ expect(dailyBarsSource).toContain('const subscriptionEstimateSum = segments.reduce(');+ expect(dailyBarsSource).toContain('actualAmount + subscriptionEstimateSum,');expect(dailyBarsSource).toContain(- 'const subscriptionEstimateSum = segments.reduce((a, s) => a + s.subscriptionEstimateUsd, 0);',- );- expect(dailyBarsSource).toContain(- 'const effectiveUsd = Math.max(costUsd + subscriptionEstimateSum, segSum);',+ 'segments.some((segment) => segment.subscriptionEstimateAmount > 0)',);- expect(dailyBarsSource).toContain('estimated: subscriptionEstimateSum > 0,');- expect(dailyBarsSource).toContain('subscription: formatUsd(subscriptionEstimateSum)');+ expect(dailyBarsSource).toContain("money(subscriptionEstimateSum, true, 'value-estimate')");});it('force-refreshes delayed pricing retries instead of reusing pending memory cache', () => {- const hookSource = readFileSync(- resolve(__dirname, '../hooks/useUsageHistory.ts'),- 'utf8',- );+ const hookSource = readFileSync(resolve(__dirname, '../hooks/useUsageHistory.ts'), 'utf8');expect(hookSource).toContain('scope.pricingRetryTimer = setTimeout(() => {');expect(hookSource).toContain('void load(scopeKey, { forceRefresh: true });');expect(hookSource).not.toContain('setTimeout(() => void load(), PRICING_RETRY_DELAY_MS);');});it('cancels delayed retries when a usage scope is no longer active', () => {- const hookSource = readFileSync(- resolve(__dirname, '../hooks/useUsageHistory.ts'),- 'utf8',- );+ const hookSource = readFileSync(resolve(__dirname, '../hooks/useUsageHistory.ts'), 'utf8');expect(hookSource).toContain('pricingRetryTimer: ReturnType<typeof setTimeout> | null;');- expect(hookSource).toContain('function deactivateScopeIfUnused(scope: UsageHistoryScopeState): void');+ expect(hookSource).toContain(+ 'function deactivateScopeIfUnused(scope: UsageHistoryScopeState): void',+ );expect(hookSource).toContain('cancelScopeTimers(scope);');expect(hookSource).toContain('scope.loadSeq += 1;');expect(hookSource).toContain('deactivateScopeIfUnused(activeScope);');- expect(hookSource).toContain('if (scope.listeners.size === 0 && scope.statusListeners.size === 0) return;');+ expect(hookSource).toContain(+ 'if (scope.listeners.size === 0 && scope.statusListeners.size === 0) return;',+ );});it('resets the pricing retry gate after successful loads and usage-push refreshes', () => {- const hookSource = readFileSync(- resolve(__dirname, '../hooks/useUsageHistory.ts'),- 'utf8',- );+ const hookSource = readFileSync(resolve(__dirname, '../hooks/useUsageHistory.ts'), 'utf8');expect(hookSource).toContain('opts?: { forceRefresh?: boolean; resetPricingRetry?: boolean }');expect(hookSource).toContain('if (opts?.resetPricingRetry) scope.pricingRetryDone = false;');expect(hookSource).toContain('scope.pricingRetryDone = false;');- expect(hookSource).toContain('void load(scopeKey, { forceRefresh: true, resetPricingRetry: true });');+ expect(hookSource).toContain(+ 'void load(scopeKey, { forceRefresh: true, resetPricingRetry: true });',+ );});it('does not retry forever for permanent Codex null estimates', () => {- const hookSource = readFileSync(- resolve(__dirname, '../hooks/useUsageHistory.ts'),- 'utf8',- );+ const hookSource = readFileSync(resolve(__dirname, '../hooks/useUsageHistory.ts'), 'utf8');expect(hookSource).toContain('if (next.estimatesPending) {');- expect(hookSource).not.toContain("next.models.some((m) => m.agentKind === 'codex' && m.estimatedCostUsd === null)");+ expect(hookSource).not.toContain(+ "next.models.some((m) => m.agentKind === 'codex' && m.estimatedCostUsd === null)",+ );});});diff --git a/apps/desktop/src/renderer/__tests__/messageTurnCost.test.ts b/apps/desktop/src/renderer/__tests__/messageTurnCost.test.tsindex d75b314e01..ea9d872bed 100644--- a/apps/desktop/src/renderer/__tests__/messageTurnCost.test.ts+++ b/apps/desktop/src/renderer/__tests__/messageTurnCost.test.ts@@ -3,7 +3,7 @@* ---------------------------------------------------------------------------* per-turn 费用展示(MessageActionBar"本轮消耗")的 renderer 侧:* - formatTurnCostUsd:用户可见费用统一保留两位小数。- * - makerChatStore:历史加载从 agentMeta 提取 turnCostUsd;本机 IPC 与 device-link+ * - makerChatStore:历史 USD 会投影为区域金额;本机 IPC 与 device-link* remote push 都按 clientId 命中消息补字段;clientId 不存在 → state 引用不变(no-op)。*/@@ -50,6 +50,8 @@ vi.mock('@/lib/composerDraftStore', () => ({}));import { formatTurnCostUsd } from '@/lib/usageFormat';+import { CURRENT_CINDY_REGION } from '../../shared/brandRegion';+import { regionalizeLegacyUsd } from '../../shared/regionalMoney';import { buildTurnUsageDetails } from '../../shared/turnUsageDetails';import { makerChatStore } from '@/lib/makerChatStore';import * as messageService from '@/lib/messageService';@@ -122,6 +124,8 @@ function serverMessage(over: Partial<Message>): Message {}const flush = () => new Promise((r) => setTimeout(r, 0));+const legacyMoney = (amountUsd: number) =>+ regionalizeLegacyUsd(amountUsd, CURRENT_CINDY_REGION);const DETAILS = buildTurnUsageDetails({inputTokens: 1200,outputTokens: 300,@@ -218,17 +222,18 @@ describe('makerChatStore per-turn 费用', () => {const staleEstimateMetaModel = snap.messages.find((m) => m.clientId === 'a-stale-estimate-meta-model');const livePricingPreserved = snap.messages.find((m) => m.clientId === 'a-live-pricing-preserved');const noCost = snap.messages.find((m) => m.clientId === 'a-no-cost');- expect(withCost?.turnCostUsd).toBe(0.05);+ expect(withCost?.turnMoney).toEqual(legacyMoney(0.05));expect(withCost?.turnCostIsEstimate).toBe(true);+ expect(withCost?.userTurnMoney).toEqual(legacyMoney(12.34));expect(withCost?.userTurnCostUsd).toBe(12.34);expect(withCost?.userTurnCostIsEstimate).toBe(true);expect(withCost?.turnUsageDetails).toEqual(DETAILS);- expect(staleEstimate?.turnCostUsd).toBeCloseTo(2.011);+ expect(staleEstimate?.turnMoney).toEqual(legacyMoney(2.011));expect(staleEstimate?.turnCostIsEstimate).toBe(true);expect(staleEstimate?.turnUsageDetails).toEqual(GPT_DETAILS);- expect(staleEstimateMetaModel?.turnCostUsd).toBeCloseTo(2.011);- expect(livePricingPreserved?.turnCostUsd).toBe(3.14);- expect(noCost?.turnCostUsd).toBeUndefined();+ expect(staleEstimateMetaModel?.turnMoney).toEqual(legacyMoney(2.011));+ expect(livePricingPreserved?.turnMoney).toEqual(legacyMoney(3.14));+ expect(noCost?.turnMoney).toBeUndefined();});it('device-link 旧历史:缺少持久化累计值时按完整用户轮投影', async () => {@@ -260,8 +265,12 @@ describe('makerChatStore per-turn 费用', () => {await flush();const messages = makerChatStore.getSnapshot(SID).messages;+ expect(messages.find((m) => m.clientId === 'segment-1')?.userTurnMoney).toEqual(+ legacyMoney(14.8),+ );expect(messages.find((m) => m.clientId === 'segment-1')?.userTurnCostUsd).toBe(14.8);const final = messages.find((m) => m.clientId === 'final');+ expect(final?.userTurnMoney).toEqual(legacyMoney(15.5));expect(final?.userTurnCostUsd).toBe(15.5);expect(final?.userTurnCostIsEstimate).toBe(true);});@@ -288,8 +297,9 @@ describe('makerChatStore per-turn 费用', () => {const snap = makerChatStore.getSnapshot(SID);const msg = snap.messages.find((m) => m.clientId === 'a-live');- expect(msg?.turnCostUsd).toBe(0.042);+ expect(msg?.turnMoney).toEqual(legacyMoney(0.042));expect(msg?.turnCostIsEstimate).toBe(false);+ expect(msg?.userTurnMoney).toEqual(legacyMoney(52.229224));expect(msg?.userTurnCostUsd).toBe(52.229224);expect(msg?.userTurnCostIsEstimate).toBe(false);expect(msg?.turnUsageDetails).toEqual(DETAILS);@@ -318,7 +328,7 @@ describe('makerChatStore per-turn 费用', () => {});const msg = makerChatStore.getSnapshot(SID).messages.find((m) => m.clientId === 'a-live-estimate');- expect(msg?.turnCostUsd).toBeCloseTo(2.011);+ expect(msg?.turnMoney).toEqual(legacyMoney(2.011));expect(msg?.turnCostIsEstimate).toBe(true);});@@ -340,7 +350,7 @@ describe('makerChatStore per-turn 费用', () => {});const msg = makerChatStore.getSnapshot(SID).messages.find((m) => m.clientId === 'a-live-pricing-preserved');- expect(msg?.turnCostUsd).toBe(3.14);+ expect(msg?.turnMoney).toEqual(legacyMoney(3.14));expect(msg?.turnCostIsEstimate).toBe(true);});@@ -368,8 +378,9 @@ describe('makerChatStore per-turn 费用', () => {});const msg = makerChatStore.getSnapshot(SID).messages.find((m) => m.clientId === 'a-remote');- expect(msg?.turnCostUsd).toBe(0.08);+ expect(msg?.turnMoney).toEqual(legacyMoney(0.08));expect(msg?.turnCostIsEstimate).toBe(true);+ expect(msg?.userTurnMoney).toEqual(legacyMoney(2.08));expect(msg?.userTurnCostUsd).toBe(2.08);expect(msg?.userTurnCostIsEstimate).toBe(true);});diff --git a/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts b/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.tsindex 9e851788fc..c0b867e6af 100644--- a/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts+++ b/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts@@ -19,6 +19,7 @@ vi.mock('react-i18next', async (importOriginal) => ({value?: string;model?: string;effort?: string;+ price?: string;},) => {const translations: Record<string, string> = {@@ -176,9 +177,18 @@ vi.mock('@/hooks/useConnectedSource', () => ({vi.mock('@/hooks/useModelPricing', () => ({useModelPricing: () => ({- 'claude-opus-4-8': {- inputUsdPerMtok: 3,- outputUsdPerMtok: 15,+ anthropic: {+ 'claude-opus-4-8': {+ providerId: 'anthropic',+ modelId: 'claude-opus-4-8',+ currency: 'USD',+ source: 'subscription-reference',+ approximate: true,+ inputPerMtok: 3,+ outputPerMtok: 15,+ cacheReadPerMtok: 0.3,+ cacheCreatePerMtok: 3.75,+ },},}),}));@@ -552,13 +562,20 @@ describe('ModelSelector trigger variants', () => {expect(within(options).getByText('Most capable for ambitious work')).toBeTruthy();expect(within(options).getByText('Source: Anthropic')).toBeTruthy();expect(within(options).getByText('200K context')).toBeTruthy();- const price = within(options).getByText('Input $3 · Output $15 per 1M tokens');+ const priceTitle = within(options).getByText('newChat.modelSelector.pricing.title');+ expect(within(options).getByText('≈¥20.1')).toBeTruthy();+ expect(within(options).getByText('≈¥100.5')).toBeTruthy();+ expect(within(options).getByText('≈¥2.01')).toBeTruthy();+ expect(within(options).getByText('≈¥25.13')).toBeTruthy();+ expect(+ within(options).getByText('newChat.modelSelector.pricing.subscriptionEstimate'),+ ).toBeTruthy();const firstChoice = within(options).getByRole('option', { name: 'low' });const description = within(options).getByText('Most capable for ambitious work');expect(description.compareDocumentPosition(firstChoice) & Node.DOCUMENT_POSITION_FOLLOWING,).toBe(Node.DOCUMENT_POSITION_FOLLOWING);- expect(firstChoice.compareDocumentPosition(price) & Node.DOCUMENT_POSITION_FOLLOWING).toBe(+ expect(firstChoice.compareDocumentPosition(priceTitle) & Node.DOCUMENT_POSITION_FOLLOWING).toBe(Node.DOCUMENT_POSITION_FOLLOWING,);expect(row.getAttribute('data-model-options-active')).toBe('true');diff --git a/apps/desktop/src/renderer/__tests__/sessionsStoreAccountBoundary.test.tsx b/apps/desktop/src/renderer/__tests__/sessionsStoreAccountBoundary.test.tsxindex 09d577ce96..31146cf1c2 100644--- a/apps/desktop/src/renderer/__tests__/sessionsStoreAccountBoundary.test.tsx+++ b/apps/desktop/src/renderer/__tests__/sessionsStoreAccountBoundary.test.tsx@@ -4,12 +4,18 @@ import { act, cleanup, renderHook, waitFor } from '@testing-library/react';import type { Session } from '@/lib/ccAgent.types';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+type SpendPayload = {+ sessionId: string;+ totalMoney?: Session['totalMoney'];+ totalCostUsd?: number;+};+const mocks = vi.hoisted(() => {let spendListener:- | ((payload: { sessionId: string; totalCostUsd: number }) => void)+ | ((payload: SpendPayload) => void)| undefined;const onUsageSessionSpendChanged = vi.fn(- (listener: (payload: { sessionId: string; totalCostUsd: number }) => void) => {+ (listener: (payload: SpendPayload) => void) => {spendListener = listener;return vi.fn();},@@ -20,7 +26,7 @@ const mocks = vi.hoisted(() => {});return {list: vi.fn(),- emitSessionSpend(payload: { sessionId: string; totalCostUsd: number }): void {+ emitSessionSpend(payload: SpendPayload): void {spendListener?.(payload);},};@@ -162,6 +168,38 @@ describe('sessionsStore account boundaries', () => {unsubscribe();});+ it('patches structured CNY spend without fabricating a USD projection', async () => {+ mocks.list.mockResolvedValueOnce([+ session('target', { totalCostUsd: 1 }),+ ]);+ await sessionsStore.ensureByFilter('active');++ act(() => {+ mocks.emitSessionSpend({+ sessionId: 'target',+ totalMoney: {+ amount: 3,+ currency: 'CNY',+ approximate: false,+ kind: 'actual-cost',+ },+ });+ });++ expect(sessionsStore.getByFilter('active')).toEqual([+ expect.objectContaining({+ id: 'target',+ totalCostUsd: 1,+ totalMoney: {+ amount: 3,+ currency: 'CNY',+ approximate: false,+ kind: 'actual-cost',+ },+ }),+ ]);+ });+it('preserves spend received while a stale session list response is in flight', async () => {const staleRequest = deferred<Session[]>();mocks.list.mockImplementationOnce(() => staleRequest.promise);diff --git a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.tsindex c67ff6dad4..e30ab11141 100644--- a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts+++ b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts@@ -15,12 +15,14 @@ const source = readFileSync(sourcePath, 'utf8').replace(/\r\n/g, '\n');describe('TodaySpendChip dashboard routing', () => {it('separates the latest user-round total from final-segment token details', () => {+ expect(source).toContain('message.userTurnMoney?.amount');expect(source).toContain('const userTurnCostUsd = typeof message.userTurnCostUsd');- expect(source).toContain('? { costUsd: userTurnCostUsd }');- expect(source).toContain('isUserTurnTotal: userTurnCostUsd != null');+ expect(source).toContain('? { money: userTurnMoney }');+ expect(source).toContain('isUserTurnTotal: Boolean(userTurnMoney || userTurnCostUsd != null)');expect(source).toContain("'todaySpend.tooltip.latestUserTurnTitle'");+ expect(source).toContain('segmentMoney: message.turnMoney');expect(source).toContain('segmentCostUsd: message.turnCostUsd');- expect(source).toContain('costUsd: summary.isUserTurnTotal ? summary.segmentCostUsd : summary.costUsd');+ expect(source).toContain('money: summary.isUserTurnTotal ? summary.segmentMoney : summary.money');expect(source).toContain("'chat.messageActionBar.userTurnCostDetailsTitle'");});@@ -111,7 +113,7 @@ describe('TodaySpendChip dashboard routing', () => {expect(source).not.toContain('CODEX_CREDIT_USD_RATE');expect(source).not.toContain('usdFormatted');expect(source).not.toContain('function getSessionCostSegment(');- expect(source).toContain("t('todaySpend.sessionCostLabel', { cost: `$${sessionCostUsd.toFixed(2)}` })");+ expect(source).toContain('const cost = formatTurnCostMoney(sessionMoney)');expect(source).toContain("tooltipLabel: t('todaySpend.tooltip.sessionUsed'");expect(source).toContain("session: { label: t('todaySpend.sessionCostLabel', { cost: '$—' })");// spend hook 对 device-link 远程会话无条件启用(形态未知,累计 cost 镜像不可丢)@@ -132,7 +134,7 @@ describe('TodaySpendChip dashboard routing', () => {"chipSegments.push(t('todaySpend.codex.sessionValueLabel'",);expect(source).toContain('tooltipNode = buildCodexTooltipNode(');- expect(source).toContain('sessionEstimatedValueUsd,');+ expect(source).toContain('sessionEstimatedValueMoney,');expect(source).toContain("t('todaySpend.codex.sessionValueLabel'");expect(source).toContain('getCodexWindowUsages(snapshot, t, nowMs)');expect(source).toContain('todaySpend.codex.planCreditsLine');@@ -148,6 +150,16 @@ describe('TodaySpendChip dashboard routing', () => {expect(source).not.toContain('todaySpend.codex.creditsShort');});+ it('formats gateway quota amounts with the build-region currency', () => {+ expect(source).toContain(+ 'formatCompactMoney(gatewayMoney(claudeQuota.spend, CURRENT_CINDY_REGION))',+ );+ expect(source).toContain(+ 'formatCompactMoney(gatewayMoney(claudeQuota.maxBudget, CURRENT_CINDY_REGION))',+ );+ expect(source).not.toContain('formatCompactUsd(claudeQuota.');+ });+it('uses token and explicit empty-state fallbacks for Codex API sessions', () => {expect(source).toContain('isCodexApi || isCodexSubscription || isSubscriptionBridge || isDeviceLinkRemote',diff --git a/apps/desktop/src/renderer/__tests__/usageFormat.test.ts b/apps/desktop/src/renderer/__tests__/usageFormat.test.tsindex f07fa10c51..da66d9b1a8 100644--- a/apps/desktop/src/renderer/__tests__/usageFormat.test.ts+++ b/apps/desktop/src/renderer/__tests__/usageFormat.test.ts@@ -1,6 +1,9 @@import { describe, expect, it } from 'vitest';-import { formatCompactTokens } from '@/lib/usageFormat';+import {+ formatCompactTokens,+ formatTurnCostMoney,+} from '@/lib/usageFormat';describe('formatCompactTokens', () => {it('uses B for billion-scale token counts', () => {@@ -14,3 +17,24 @@ describe('formatCompactTokens', () => {expect(formatCompactTokens(2_000_000)).toBe('2.0M');});});++describe('formatTurnCostMoney', () => {+ it('renders a true zero without a less-than label', () => {+ expect(+ formatTurnCostMoney({+ amount: 0,+ currency: 'CNY',+ approximate: false,+ kind: 'actual-cost',+ }),+ ).toBe('¥0.00');+ expect(+ formatTurnCostMoney({+ amount: 0,+ currency: 'USD',+ approximate: true,+ kind: 'value-estimate',+ }),+ ).toBe('≈$0.00');+ });+});diff --git a/apps/desktop/src/renderer/__tests__/useSessionEstimatedValue.test.ts b/apps/desktop/src/renderer/__tests__/useSessionEstimatedValue.test.tsindex a9bdf11338..f789079a88 100644--- a/apps/desktop/src/renderer/__tests__/useSessionEstimatedValue.test.ts+++ b/apps/desktop/src/renderer/__tests__/useSessionEstimatedValue.test.ts@@ -7,6 +7,27 @@ import {} from '@/hooks/useSessionEstimatedValue';import type { ChatMessage } from '@/lib/makerChatStore';import { buildTurnUsageDetails } from '../../shared/turnUsageDetails';+import type { RegionalMoney } from '../../shared/regionalMoney';++function usdEstimate(amount: number): RegionalMoney {+ return {+ amount,+ currency: 'USD',+ approximate: true,+ kind: 'value-estimate',+ estimateReasons: ['subscription-value'],+ };+}++function legacyCnyEstimate(amount: number): RegionalMoney {+ return {+ amount,+ currency: 'CNY',+ approximate: true,+ kind: 'value-estimate',+ estimateReasons: ['fixed-fx', 'legacy-usd', 'subscription-value'],+ };+}function assistantMessage(clientId: string,@@ -18,7 +39,7 @@ function assistantMessage(content: 'ok',createdAt: new Date(0).toISOString(),...(typeof costUsd === 'number'- ? { turnCostUsd: costUsd, turnCostIsEstimate: true }+ ? { turnMoney: usdEstimate(costUsd), turnCostIsEstimate: true }: {}),} as ChatMessage;}@@ -36,7 +57,7 @@ if (!GPT_DETAILS) {describe('syncEstimatedValueCostsFromStoreSnapshot', () => {it('preserves DB-backed costs before chat history has loaded', () => {- const current = new Map([['persisted', 0.12]]);+ const current = new Map([['persisted', usdEstimate(0.12)]]);const result = syncEstimatedValueCostsFromStoreSnapshot(current,new Set(),@@ -48,7 +69,10 @@ describe('syncEstimatedValueCostsFromStoreSnapshot', () => {it('clears all costs when /clear leaves an authoritative empty transcript', () => {const result = syncEstimatedValueCostsFromStoreSnapshot(- new Map([['persisted', 0.12], ['visible', 0.03]]),+ new Map([+ ['persisted', usdEstimate(0.12)],+ ['visible', usdEstimate(0.03)],+ ]),new Set(['visible']),{ messages: [], historyLoaded: true, hasMoreMessages: false },);@@ -59,7 +83,10 @@ describe('syncEstimatedValueCostsFromStoreSnapshot', () => {it('removes stale visible ids while keeping DB-only hidden history costs', () => {const result = syncEstimatedValueCostsFromStoreSnapshot(- new Map([['hidden-history', 0.12], ['old-visible', 0.03]]),+ new Map([+ ['hidden-history', usdEstimate(0.12)],+ ['old-visible', usdEstimate(0.03)],+ ]),new Set(['old-visible']),{messages: [@@ -71,8 +98,8 @@ describe('syncEstimatedValueCostsFromStoreSnapshot', () => {},);- expect(result?.costs.get('hidden-history')).toBe(0.12);- expect(result?.costs.get('new-visible')).toBe(0.04);+ expect(result?.costs.get('hidden-history')?.amount).toBe(0.12);+ expect(result?.costs.get('new-visible')?.amount).toBe(0.04);expect(result?.costs.has('old-visible')).toBe(false);expect(result?.costs.has('visible-no-cost')).toBe(false);});@@ -82,19 +109,28 @@ describe('resolveEstimatedValueTurnCostEntry', () => {it('corrects realtime stale full-cache estimates before merging session value', () => {expect(resolveEstimatedValueTurnCostEntry({clientId: 'stale',- turnCostUsd: 8.76,+ turnMoney: usdEstimate(8.76),+ turnCostIsEstimate: true,+ turnUsageDetails: GPT_DETAILS,+ })?.money.amount).toBeCloseTo(2.011);+ });++ it('corrects stale legacy estimates after their CN fixed-FX projection', () => {+ expect(resolveEstimatedValueTurnCostEntry({+ clientId: 'stale-cn',+ turnMoney: legacyCnyEstimate(8.76 * 6.7),turnCostIsEstimate: true,turnUsageDetails: GPT_DETAILS,- })?.costUsd).toBeCloseTo(2.011);+ })?.money.amount).toBeCloseTo(2.011 * 6.7);});it('preserves realtime live pricing estimates that do not match stale full-cache formulas', () => {expect(resolveEstimatedValueTurnCostEntry({clientId: 'live',- turnCostUsd: 3.14,+ turnMoney: usdEstimate(3.14),turnCostIsEstimate: true,turnUsageDetails: GPT_DETAILS,- })?.costUsd).toBe(3.14);+ })?.money.amount).toBe(3.14);});it('ignores non-estimate realtime entries', () => {diff --git a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsxindex d75a796510..ae801da12c 100644--- a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx+++ b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx@@ -47,6 +47,7 @@ import { GhostToolCard } from './GhostToolCard';import type { KnownLocalFileRef } from '@/lib/localPathResolver';import type { AgentKind as RendererAgentKind } from '@/lib/ccAgent.types';import type { TurnUsageDetails } from '../../../shared/turnUsageDetails';+import type { RegionalMoney } from '../../../shared/regionalMoney';import { useAgentCapabilities, type AgentKind as MakerAgentKind } from '@/hooks/useAgentCapabilities';import { useSessionFileOrigin } from './ChatSessionFileContext';import { originDeviceId } from '@/lib/sessionFileOrigin';@@ -172,9 +173,11 @@ interface AssistantMessageProps {* opacity-0 也占 24px 布局高度,每句都挂会拉散消息流)。默认 false。 */showActionBar?: boolean;/** Per-turn 费用 (USD) — 仅该轮最后一条 assistant 有值, action bar 时间旁显示。 */+ turnMoney?: RegionalMoney;turnCostUsd?: number;/** true = 订阅模式下的 token 价值;false = API 账单 cost / API 单价折算 cost。 */turnCostIsEstimate?: boolean;+ userTurnMoney?: RegionalMoney;userTurnCostUsd?: number;userTurnCostIsEstimate?: boolean;/** Per-turn token/cache 明细。 */@@ -201,8 +204,10 @@ export const AssistantMessage = memo(function AssistantMessage({forkBlocked,sessionRunning,showActionBar = false,+ turnMoney,turnCostUsd,turnCostIsEstimate,+ userTurnMoney,userTurnCostUsd,userTurnCostIsEstimate,turnUsageDetails,@@ -365,8 +370,10 @@ export const AssistantMessage = memo(function AssistantMessage({onFork={canFork ? handleFork : undefined}onAddToChat={messageDeepLink ? handleAddToChat : undefined}onDelete={currentSessionId && messageClientId ? handleDelete : undefined}+ turnMoney={turnMoney}turnCostUsd={turnCostUsd}turnCostIsEstimate={turnCostIsEstimate}+ userTurnMoney={userTurnMoney}userTurnCostUsd={userTurnCostUsd}userTurnCostIsEstimate={userTurnCostIsEstimate}turnUsageDetails={turnUsageDetails}diff --git a/apps/desktop/src/renderer/components/chat/MessageActionBar.tsx b/apps/desktop/src/renderer/components/chat/MessageActionBar.tsxindex 330fe8521a..974456b94d 100644--- a/apps/desktop/src/renderer/components/chat/MessageActionBar.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageActionBar.tsx@@ -51,9 +51,14 @@ import {} from '@/components/ui/dropdown-menu';import { toast } from '@/lib/toast';import { formatAbsolute, useRelativeTime } from '@/hooks/useRelativeTime';-import { formatTurnCostUsd } from '@/lib/usageFormat';+import { formatTurnCostMoney, formatTurnCostUsd } from '@/lib/usageFormat';import { buildTurnUsageTooltipLines } from '@/lib/turnUsageTooltip';import type { TurnUsageDetails } from '../../../shared/turnUsageDetails';+import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';+import {+ regionalizeLegacyUsd,+ type RegionalMoney,+} from '../../../shared/regionalMoney';interface MessageActionBarProps {createdAt?: string;@@ -92,9 +97,11 @@ interface MessageActionBarProps {* Preview Dialog's open lifetime + commit, which the bar doesn't manage. */rewindInFlight?: boolean;/** Per-turn 费用 (USD) — 仅该轮最后一条 assistant 有值, 时间旁显示。 */+ turnMoney?: RegionalMoney;turnCostUsd?: number;turnCostIsEstimate?: boolean;/** User-visible cumulative cost for the surrounding user round. */+ userTurnMoney?: RegionalMoney;userTurnCostUsd?: number;userTurnCostIsEstimate?: boolean;/** Per-turn token/cache 明细。旧消息没有时 tooltip 保持旧文案。 */@@ -118,8 +125,10 @@ export function MessageActionBar({onEdit,onRewind,rewindInFlight = false,+ turnMoney,turnCostUsd,turnCostIsEstimate = false,+ userTurnMoney,userTurnCostUsd,userTurnCostIsEstimate = false,turnUsageDetails,@@ -297,20 +306,30 @@ export function MessageActionBar({);// 用户轮累计优先;没有新字段的历史消息继续显示原始 SDK 分段成本。- const displayedCostUsd = userTurnCostUsd ?? turnCostUsd;- const displayedCostIsEstimate = userTurnCostUsd != null+ const effectiveTurnMoney =+ turnMoney ??+ (typeof turnCostUsd === 'number' && turnCostUsd > 0+ ? regionalizeLegacyUsd(turnCostUsd, CURRENT_CINDY_REGION)+ : undefined);+ const effectiveUserTurnMoney =+ userTurnMoney ??+ (typeof userTurnCostUsd === 'number' && userTurnCostUsd > 0+ ? regionalizeLegacyUsd(userTurnCostUsd, CURRENT_CINDY_REGION)+ : undefined);+ const displayedMoney = effectiveUserTurnMoney ?? effectiveTurnMoney;+ const displayedCostIsEstimate = effectiveUserTurnMoney? userTurnCostIsEstimate: turnCostIsEstimate;- const isUserTurnTotal = userTurnCostUsd != null;+ const isUserTurnTotal = effectiveUserTurnMoney != null;// 费用 — 样式与 timeText 完全一致(12px + 同色 + 0.5px 光学修正)。// 仅 assistant(align='left')会拿到值;估算值(Codex 折算)表达为 token 价值。const turnCostTooltipNode =- displayedCostUsd != null && displayedCostUsd > 0 && turnUsageDetails ? (+ displayedMoney && displayedMoney.amount > 0 && turnUsageDetails ? (<span className="whitespace-pre-line">{isUserTurnTotal && (<>{t('chat.messageActionBar.userTurnCostTotalLine', {- cost: formatTurnCostUsd(displayedCostUsd),+ cost: formatTurnCostMoney(displayedMoney),})}\n</>)}{buildTurnUsageTooltipLines({@@ -318,7 +337,7 @@ export function MessageActionBar({t,// Token / model detail is currently scoped to this final SDK segment;// never pair it with the user-turn cumulative total above.- costUsd: isUserTurnTotal ? turnCostUsd : displayedCostUsd,+ money: isUserTurnTotal ? effectiveTurnMoney : displayedMoney,isEstimate: isUserTurnTotal ? turnCostIsEstimate : displayedCostIsEstimate,...(isUserTurnTotal ? { title: t('chat.messageActionBar.userTurnCostDetailsTitle') } : {}),}).join('\n')}@@ -331,7 +350,7 @@ export function MessageActionBar({));- const costText = displayedCostUsd != null && displayedCostUsd > 0 && (+ const costText = displayedMoney && displayedMoney.amount > 0 && (<Tooltip.Root key="cost"><Tooltip.Trigger asChild><span@@ -346,9 +365,9 @@ export function MessageActionBar({>{displayedCostIsEstimate? t('chat.messageActionBar.turnCostEstimatedValue', {- cost: formatTurnCostUsd(displayedCostUsd),+ cost: formatTurnCostMoney(displayedMoney),})- : formatTurnCostUsd(displayedCostUsd)}+ : formatTurnCostMoney(displayedMoney)}</span></Tooltip.Trigger><Tooltip.Content>diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex 18b8c10408..d64ccab26a 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -553,6 +553,7 @@ export function shouldBlockAssistantFork(*/function isCompletedAssistantMessage(message: ChatMessage): boolean {return message.turnCompleted === true ||+ (message.turnMoney?.amount ?? 0) > 0 ||(typeof message.turnCostUsd === 'number' && message.turnCostUsd > 0);}@@ -3416,8 +3417,10 @@ const MessageItem = memo(function MessageItem({// 任务执行过程中(尾部 turn 流式中,forkBlocked=true)不出现操作行;// turn 结束后只有收尾正文出现 —— 中间句彻底不挂 bar。showActionBar={Boolean(assistantIsTurnFinal) && !assistantForkBlocked}+ turnMoney={message.turnMoney}turnCostUsd={message.turnCostUsd}turnCostIsEstimate={message.turnCostIsEstimate}+ userTurnMoney={message.userTurnMoney}userTurnCostUsd={message.userTurnCostUsd}userTurnCostIsEstimate={message.userTurnCostIsEstimate}turnUsageDetails={message.turnUsageDetails}diff --git a/apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx b/apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsxindex ff335ccdab..b42cb42c53 100644--- a/apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx+++ b/apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx@@ -25,8 +25,8 @@ import { Tip } from '@/components/ui/tooltip';import {DAILY_SOFT_LIMIT_FACTOR,formatCompactTokens,- formatCompactUsd,- formatUsd,+ formatCompactMoney,+ formatMoney,} from '@/lib/usageFormat';import { useClaudeAccountUsage } from '@/hooks/useClaudeAccountUsage';import { useUsageHistory, type UsageHistoryPayload } from '@/hooks/useUsageHistory';@@ -34,6 +34,12 @@ 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,+} from '../../../shared/regionalMoney';const COLLAPSED_STORAGE_KEY = 'homeUsageDashboard.collapsed';/** 与 useUsageHistory 的拉取窗口一致 (20 周)。 */@@ -43,6 +49,8 @@ const ACCOUNT_LOCAL_TODAY_MATCH_EPSILON = 0.01;const UNKNOWN_VALUE = '—';const TOKEN_DISTRIBUTION_TOP_MODELS = 5;+const zeroMoney = () => zeroRegionalMoney(CURRENT_CINDY_REGION);+type TokenDistributionInput = {model: string;tokens: number;@@ -82,10 +90,13 @@ function createEmptyUsageHistoryPayload(): UsageHistoryPayload {models: [],streak: { current: 0, longest: 0 },totals: {- today: 0,- last30Days: 0,- last30DaysWithEstimatedValue: 0,- last30DaysEstimatedValue: 0,+ today: zeroMoney(),+ last30Days: zeroMoney(),+ last30DaysWithEstimatedValue: zeroMoney(),+ last30DaysEstimatedValue: zeroRegionalMoney(+ CURRENT_CINDY_REGION,+ 'value-estimate',+ ),todayTokens: 0,last30DaysTokens: 0,},@@ -110,11 +121,15 @@ function writeCollapsedFlag(value: boolean): void {}function isSameDisplayedTodaySpend(- accountTodaySpend: number | null,- localTodaySpend: number,+ accountTodaySpend: RegionalMoney | null,+ localTodaySpend: RegionalMoney,): boolean {if (accountTodaySpend === null) return true;- return Math.abs(accountTodaySpend - localTodaySpend) <= ACCOUNT_LOCAL_TODAY_MATCH_EPSILON;+ return (+ accountTodaySpend.currency === localTodaySpend.currency &&+ Math.abs(accountTodaySpend.amount - localTodaySpend.amount) <=+ ACCOUNT_LOCAL_TODAY_MATCH_EPSILON+ );}function modelTokenTotal(model: UsageHistoryPayload['models'][number]): number {@@ -175,24 +190,30 @@ export function HomeUsageDashboard(): React.JSX.Element {});}, []);- const accountTodaySpend =- typeof claudeQuota?.todaySpend === 'number' ? claudeQuota.todaySpend : null;- const hasAccountTodaySpend = accountTodaySpend !== null;+ const accountTodayMoney =+ typeof claudeQuota?.todaySpend === 'number'+ ? gatewayMoney(claudeQuota.todaySpend, CURRENT_CINDY_REGION)+ : null;+ const hasAccountTodaySpend = accountTodayMoney !== null;- const displayTodaySpend = accountTodaySpend ?? layoutHistory.totals.today;+ const displayTodaySpend = accountTodayMoney ?? layoutHistory.totals.today;const hasSpendValue = hasHistoryData || hasAccountTodaySpend;const showLocalSpendAnomaly =layoutHistory.anomaly.isAnomalous &&- isSameDisplayedTodaySpend(accountTodaySpend, layoutHistory.totals.today);+ isSameDisplayedTodaySpend(accountTodayMoney, layoutHistory.totals.today);const softDailyLimit = hasMonthly ? (claudeQuota.maxBudget / 30) * DAILY_SOFT_LIMIT_FACTOR : null;+ const softDailyLimitMoney =+ softDailyLimit === null+ ? null+ : gatewayMoney(softDailyLimit, CURRENT_CINDY_REGION);const todayValue = !hasSpendValue? UNKNOWN_VALUE- : softDailyLimit !== null- ? `${formatUsd(displayTodaySpend)} / ${formatCompactUsd(softDailyLimit)}`- : formatUsd(displayTodaySpend);+ : softDailyLimitMoney+ ? `${formatMoney(displayTodaySpend)} / ${formatCompactMoney(softDailyLimitMoney)}`+ : formatMoney(displayTodaySpend);const anomalyTip = showLocalSpendAnomaly? t('usageDashboard.anomalyTooltip', {- avg: formatUsd(layoutHistory.anomaly.trailing7DayAvg ?? 0),+ avg: formatMoney(layoutHistory.anomaly.trailing7DayAvg ?? zeroMoney()),}): null;@@ -241,13 +262,13 @@ export function HomeUsageDashboard(): React.JSX.Element {}): `${UNKNOWN_VALUE} / ${UNKNOWN_VALUE}`;const last30DaysValue = hasHistoryData- ? `${layoutHistory.totals.last30DaysEstimatedValue > 0 ? '≈' : ''}${formatUsd(layoutHistory.totals.last30DaysWithEstimatedValue)}`+ ? formatMoney(layoutHistory.totals.last30DaysWithEstimatedValue): UNKNOWN_VALUE;- const last30DaysTip = hasHistoryData && layoutHistory.totals.last30DaysEstimatedValue > 0+ const last30DaysTip = hasHistoryData && layoutHistory.totals.last30DaysEstimatedValue.amount > 0? t('usageDashboard.last30dTooltip', {- api: formatUsd(layoutHistory.totals.last30Days),- subscription: formatUsd(layoutHistory.totals.last30DaysEstimatedValue),- total: formatUsd(layoutHistory.totals.last30DaysWithEstimatedValue),+ api: formatMoney(layoutHistory.totals.last30Days),+ subscription: formatMoney(layoutHistory.totals.last30DaysEstimatedValue),+ total: formatMoney(layoutHistory.totals.last30DaysWithEstimatedValue),}): null;@@ -256,7 +277,7 @@ export function HomeUsageDashboard(): React.JSX.Element {<span className="min-w-0 flex-1 truncate text-right text-[11px] leading-[18px] tabular-nums text-[var(--text-tertiary)]"><span className={cn(showLocalSpendAnomaly && 'font-medium text-[var(--warning-accent)]')}>{t('usageDashboard.collapsedToday', {- v: hasSpendValue ? formatUsd(displayTodaySpend) : UNKNOWN_VALUE,+ v: hasSpendValue ? formatMoney(displayTodaySpend) : UNKNOWN_VALUE,})}</span>{' · '}@@ -335,7 +356,7 @@ export function HomeUsageDashboard(): React.JSX.Element {<StatCellvalue={hasMonthly- ? `${formatCompactUsd(claudeQuota.spend)} / ${formatCompactUsd(claudeQuota.maxBudget)}`+ ? `${formatCompactMoney(gatewayMoney(claudeQuota.spend, CURRENT_CINDY_REGION))} / ${formatCompactMoney(gatewayMoney(claudeQuota.maxBudget, CURRENT_CINDY_REGION))}`: `${UNKNOWN_VALUE} / ${UNKNOWN_VALUE}`}label={t('usageDashboard.monthly')}@@ -344,7 +365,7 @@ export function HomeUsageDashboard(): React.JSX.Element {<StatCellvalue={last30DaysValue}label={- layoutHistory.totals.last30DaysEstimatedValue > 0+ layoutHistory.totals.last30DaysEstimatedValue.amount > 0? t('usageDashboard.last30dWithEstimate'): t('usageDashboard.last30d')}diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsxindex 57f89ae899..d3c5e097c5 100644--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx@@ -25,6 +25,10 @@ import { useConnectedSource } from '@/hooks/useConnectedSource';import { useModelPricing } from '@/hooks/useModelPricing';import { useProviders } from '@/hooks/useProviders';import { useDeviceProviders } from '@/hooks/useDeviceProviders';+import {+ formatModelPricePair,+ modelPriceDetailRows,+} from '@/lib/modelPriceFormat';import {filterChatBridgedCodexProviders,providerMonogram,@@ -46,6 +50,12 @@ import {visibleModelUnion,type ProviderView,} from '@cindy/model-providers';+import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';+import {+ getModelPriceQuote,+ regionalizeModelPriceQuote,+} from '../../../shared/modelPriceQuote';+import type { ModelPriceQuote } from '../../../shared/regionalMoney';import { buildProviderSections } from './sourceSwitch';// 厂商分类 / 分组标题 key 表的纯逻辑在 ./sourceSwitch。这里 re-export 给 ChatInput@@ -622,14 +632,26 @@ export function ModelSelectorContent({};// ── 模型单价 ─────────────────────────────────────────────────────────────- const priceTipOf = (id: string): string | null => {- const p = pricing?.[id];- if (!p) return null;- const fmt = (v: number) => `$${Number(v.toFixed(2))}`;- return t('newChat.modelSelector.priceTip', {- input: fmt(p.inputUsdPerMtok),- output: fmt(p.outputUsdPerMtok),- });+ // providerId 是价格索引的一部分。同模型经 XD / OpenAI / Anthropic 等来源出现时,+ // 必须按实际行来源查价,不能退化为 pricing[modelId]。+ const priceQuoteOf = (+ providerId: string | null,+ id: string,+ ): ModelPriceQuote | null => {+ const effectiveProviderId =+ providerId ??+ (currentAgentKind+ ? effectiveSourceIdForModel(+ providers,+ currentProviderId,+ id,+ currentAgentKind,+ )+ : null);+ const quote = getModelPriceQuote(pricing, effectiveProviderId, id);+ return quote+ ? regionalizeModelPriceQuote(quote, CURRENT_CINDY_REGION)+ : null;};const modelDisabledOf = (id: string): boolean => {if (!deviceId) return id.startsWith('codex/') && !hasSavedKey;@@ -870,7 +892,9 @@ export function ModelSelectorContent({effectiveSourceIdForModel(providers, currentProviderId, editingModel.id, currentAgentKind);return providerId ? providers.find((provider) => provider.id === providerId) : undefined;}, [editingModel, currentAgentKind, editingProviderId, providers, currentProviderId]);- const editingPrice = editingModel ? priceTipOf(editingModel.id) : null;+ const editingPrice = editingModel+ ? priceQuoteOf(editingProvider?.id ?? editingProviderId, editingModel.id)+ : null;// 每个模型行的信息 / 配置内容由一个独立的 portaled Popover 承载,而不是拼进主菜单宽度。// 这样浮层会像 Hermes 的 Radix submenu 一样贴着当前行移动,切行不触发主菜单重排。@@ -953,6 +977,36 @@ export function ModelSelectorContent({{(editShowFast || editHasEfforts) && (<div className="mx-1 my-1 h-px bg-[var(--model-dropdown-border)]" />)}+ {editingPrice && (+ <>+ <div className="px-2 pb-1 pt-1">+ <div className="mb-1.5 text-11 font-medium text-[var(--text-tertiary)]">+ {t('newChat.modelSelector.pricing.title')}+ </div>+ <div className="grid grid-cols-[1fr_auto] gap-x-3 gap-y-1 text-12 leading-[1.4]">+ {modelPriceDetailRows(editingPrice).map((row) => (+ <div key={row.kind} className="contents">+ <span className="text-[var(--text-secondary)]">+ {t(`newChat.modelSelector.pricing.${row.kind}`)}+ </span>+ <span className="tabular-nums text-[var(--model-item-text)]">+ {editingPrice.approximate ? '≈' : ''}+ {row.value}+ </span>+ </div>+ ))}+ </div>+ <div className="mt-1.5 text-11 leading-[1.4] text-[var(--text-tertiary)]">+ {editingPrice.source === 'subscription-reference'+ ? t('newChat.modelSelector.pricing.subscriptionEstimate')+ : editingPrice.approximate+ ? t('newChat.modelSelector.pricing.fixedFx')+ : t('newChat.modelSelector.pricing.perMillion')}+ </div>+ </div>+ <div className="mx-1 my-1 h-px bg-[var(--model-dropdown-border)]" />+ </>+ )}<div className="px-2 py-1.5"><div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-11 font-normal leading-[1.4] text-[var(--text-tertiary)]">{editingProvider && (@@ -972,7 +1026,6 @@ export function ModelSelectorContent({{editingModel.supportsFastMode && (<span>{t('newChat.modelSelector.meta.fastBadge')}</span>)}- {editingPrice && <span>{editingPrice}</span>}</div></div></div>@@ -988,6 +1041,7 @@ export function ModelSelectorContent({const disabled = modelDisabledOf(model.id);const rowEffort = rowEffortOf(providerId, model);const rowFastOn = fastOnOf(providerId, model);+ const rowPrice = priceQuoteOf(providerId, model.id);// 信息面板对所有可用模型开放;能否编辑 effort / Fast 在面板内部另行判定。// session-agent-switch 浏览目标引擎态同样开放:选模型前正需要看描述/上下文/价格/来源;// 面板内配置写的是**目标引擎**的 per-(来源,模型) 全局预设(currentAgentKind 已随浏览态@@ -1109,8 +1163,17 @@ export function ModelSelectorContent({)}</span></span>- {isSelected && (- <Check size={15} className="ml-2 shrink-0 text-[var(--model-item-check)]" />+ {(rowPrice || isSelected) && (+ <span className="ml-2 flex shrink-0 items-center gap-1.5">+ {rowPrice && (+ <span className="tabular-nums text-11 font-normal text-[var(--text-tertiary)]">+ {formatModelPricePair(rowPrice)}+ </span>+ )}+ {isSelected && (+ <Check size={15} className="shrink-0 text-[var(--model-item-check)]" />+ )}+ </span>)}</div></PopoverAnchor>diff --git a/apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx b/apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsxindex 13dc7c8d8e..78b9109e28 100644--- a/apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx+++ b/apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx@@ -13,9 +13,20 @@import React, { useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { formatCompactTokens, formatCompactUsd, formatUsd } from '@/lib/usageFormat';+import {+ formatCompactMoney,+ formatCompactTokens,+ formatMoney,+} from '@/lib/usageFormat';import type { UsageHistoryModelDay } from '@/hooks/useUsageHistory';import { usageModelKey, usageRankColor, usageRankOf } from './usagePalette';+import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';+import {+ regionalCurrencyForRegion,+ type MoneyCurrency,+ type MoneyKind,+ type RegionalMoney,+} from '../../../shared/regionalMoney';const WINDOW_DAYS = 30;const CHART_HEIGHT_PX = 96;@@ -31,16 +42,16 @@ function shiftDayKeyLocal(dayKey: string, deltaDays: number): string {interface DaySegment {rank: number;label: string;- amountUsd: number;- apiCostUsd: number;- subscriptionEstimateUsd: number;+ amount: number;+ apiAmount: number;+ subscriptionEstimateAmount: number;tokens: number;}interface DayBar {day: string;/** daily_spend 实报日总额 (仅 Claude 计入 $; Codex 不写 $ 入账)。 */- costUsd: number;+ actualAmount: number;tokens: number;/** rank 升序 (rank 0 = 最大头模型, 渲染在柱子底部)。 */segments: DaySegment[];@@ -48,9 +59,9 @@ interface DayBar {* 柱高/总额显示值 = daily_spend 实报 + Codex 订阅价值估算。* 纯 Codex 订阅日 costUsd 为 0, 仍按估算分段撑起柱子。*/- effectiveUsd: number;+ effectiveAmount: number;/** 总额包含 Codex 订阅价值估算 → 总额前缀 ≈ 并展示 tooltip 解释。 */- estimated: boolean;+ approximate: boolean;}export function UsageDailyBars({@@ -59,13 +70,35 @@ export function UsageDailyBars({colorOrder,todayKey,}: {- days: Array<{ day: string; costUsd: number; tokens?: number }>;+ days: Array<{ day: string; money: RegionalMoney; tokens?: number }>;modelDaily: UsageHistoryModelDay[];/** 前 N 名模型 key (payload.models 排序), 决定分段/图例配色。 */colorOrder: string[];todayKey: string;}): React.JSX.Element {const { t } = useTranslation();+ const currency: MoneyCurrency =+ days[0]?.money.currency ??+ modelDaily[0]?.money.currency ??+ regionalCurrencyForRegion(CURRENT_CINDY_REGION);+ const money = (+ amount: number,+ approximate: boolean,+ kind: MoneyKind = 'actual-cost',+ ): RegionalMoney => ({+ amount,+ currency,+ approximate,+ kind,+ ...(approximate+ ? {+ estimateReasons:+ kind === 'value-estimate'+ ? (['subscription-value'] as const)+ : (['reference-price'] as const),+ }+ : {}),+ });const bars = useMemo(() => {const byDay = new Map(days.map((d) => [d.day, d]));@@ -74,7 +107,7 @@ export function UsageDailyBars({// 但 tooltip 里要按 token 露出, 不能让它在明细里消失。const segsByDay = new Map<string, Map<number, DaySegment>>();for (const row of modelDaily) {- if (row.amountUsd <= 0 && row.tokens <= 0) continue;+ if (row.money.amount <= 0 && row.tokens <= 0) continue;const rank = usageRankOf(colorOrder, usageModelKey(row.agentKind, row.model));let daySegs = segsByDay.get(row.day);if (!daySegs) {@@ -83,18 +116,20 @@ export function UsageDailyBars({}const seg = daySegs.get(rank);if (seg) {- seg.amountUsd += row.amountUsd;- seg.apiCostUsd += row.apiCostUsd;- seg.subscriptionEstimateUsd += row.subscriptionEstimateUsd;+ seg.amount += row.money.amount;+ seg.apiAmount += row.apiMoney.amount;+ seg.subscriptionEstimateAmount +=+ row.subscriptionEstimateMoney.amount;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'),- amountUsd: row.amountUsd,- apiCostUsd: row.apiCostUsd,- subscriptionEstimateUsd: row.subscriptionEstimateUsd,+ amount: row.money.amount,+ apiAmount: row.apiMoney.amount,+ subscriptionEstimateAmount:+ row.subscriptionEstimateMoney.amount,tokens: row.tokens,});}@@ -105,20 +140,28 @@ 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 costUsd = row?.costUsd ?? 0;- const segSum = segments.reduce((a, s) => a + s.amountUsd, 0);- const subscriptionEstimateSum = segments.reduce((a, s) => a + s.subscriptionEstimateUsd, 0);- const effectiveUsd = Math.max(costUsd + subscriptionEstimateSum, segSum);+ const actualAmount = row?.money.amount ?? 0;+ const segSum = segments.reduce((a, s) => a + s.amount, 0);+ const subscriptionEstimateSum = segments.reduce(+ (a, s) => a + s.subscriptionEstimateAmount,+ 0,+ );+ const effectiveAmount = Math.max(+ actualAmount + subscriptionEstimateSum,+ segSum,+ );list.push({day,- costUsd,+ actualAmount,tokens: row?.tokens ?? 0,segments,- effectiveUsd,- estimated: subscriptionEstimateSum > 0,+ effectiveAmount,+ approximate:+ Boolean(row?.money.approximate) ||+ segments.some((segment) => segment.subscriptionEstimateAmount > 0),});}- const max = Math.max(...list.map((b) => b.effectiveUsd), 0);+ const max = Math.max(...list.map((b) => b.effectiveAmount), 0);return { list, max };}, [days, modelDaily, colorOrder, todayKey, t]);@@ -135,7 +178,7 @@ export function UsageDailyBars({className="absolute right-0 translate-y-1/2 text-[9px] leading-none tabular-nums text-[var(--text-tertiary)]"style={{ bottom: (v / bars.max) * CHART_HEIGHT_PX }}>- {tickLabel(v)}+ {tickLabel(v, currency)}</span>))}</div>@@ -151,36 +194,47 @@ export function UsageDailyBars({))}<div className="absolute inset-0 flex items-end gap-[3px]">{bars.list.map((b) => {- const ratio = bars.max > 0 ? b.effectiveUsd / bars.max : 0;- const h = b.effectiveUsd > 0 ? Math.max(3, Math.round(ratio * CHART_HEIGHT_PX)) : 2;+ const ratio = bars.max > 0 ? b.effectiveAmount / bars.max : 0;+ const h = b.effectiveAmount > 0 ? Math.max(3, Math.round(ratio * CHART_HEIGHT_PX)) : 2;// 画分段只看有金额的行; tooltip 明细全量列出 (无价格模型按 token 露出)- const drawSegs = b.segments.filter((s) => s.amountUsd > 0);- const segSum = drawSegs.reduce((a, s) => a + s.amountUsd, 0);- const subscriptionEstimateSum = b.segments.reduce((a, s) => a + s.subscriptionEstimateUsd, 0);+ const drawSegs = b.segments.filter((s) => s.amount > 0);+ const segSum = drawSegs.reduce((a, s) => a + s.amount, 0);+ const subscriptionEstimateSum = b.segments.reduce(+ (a, s) => a + s.subscriptionEstimateAmount,+ 0,+ );// 未分类差额: 日总额里没被任何模型行覆盖的部分 (升级日早段消费 / 未计价行)。// 分段必须按 effectiveUsd 定比例 + 差额画中性段, 否则已知模型会撑满整根柱,// 视觉上把未分类的钱也算到它们头上 (>1% 才画, 吸收舍入噪声)。- const remainder = Math.max(0, b.effectiveUsd - segSum);- const showRemainder = segSum > 0 && remainder > b.effectiveUsd * 0.01;+ const remainder = Math.max(0, b.effectiveAmount - segSum);+ const showRemainder = segSum > 0 && remainder > b.effectiveAmount * 0.01;const titleLines = [- `${b.day} · ${b.estimated ? '≈' : ''}$${b.effectiveUsd.toFixed(2)}${+ `${b.day} · ${formatMoney(money(b.effectiveAmount, b.approximate))}${b.tokens > 0 ? ` · ${t('usageDashboard.tokensOnly', { tokens: formatCompactTokens(b.tokens) })}` : ''}`,- ...(b.estimated+ ...(subscriptionEstimateSum > 0? [t('usageDashboard.dailyEstimatedTooltip', {- api: formatUsd(b.costUsd),- subscription: formatUsd(subscriptionEstimateSum),+ api: formatMoney(money(b.actualAmount, false)),+ subscription: formatMoney(+ money(subscriptionEstimateSum, true, 'value-estimate'),+ ),}),]: []),...b.segments.map((s) => {const tokensPart = t('usageDashboard.tokensOnly', { tokens: formatCompactTokens(s.tokens) });- return s.amountUsd > 0- ? `${s.label}: ${formatUsd(s.amountUsd)} · ${tokensPart}`+ return s.amount > 0+ ? `${s.label}: ${formatMoney(money(s.amount, s.subscriptionEstimateAmount > 0))} · ${tokensPart}`: `${s.label}: ${tokensPart}`;}),- ...(showRemainder ? [`${t('usageDashboard.unclassified')}: ${formatUsd(remainder)}`] : []),+ ...(showRemainder+ ? [+ `${t('usageDashboard.unclassified')}: ${formatMoney(+ money(remainder, b.approximate),+ )}`,+ ]+ : []),];return (<div@@ -188,13 +242,13 @@ export function UsageDailyBars({title={titleLines.join('\n')}// 列容器只负责高度与圆角裁切; 分段自上而下 = rank 降序 ("其它"在顶, 大头在底)className="flex min-w-0 flex-1 flex-col justify-end overflow-hidden rounded-[2px]"- style={{ height: h, backgroundColor: segSum > 0 ? undefined : barFallbackColor(b.effectiveUsd, ratio) }}+ style={{ height: h, backgroundColor: segSum > 0 ? undefined : barFallbackColor(b.effectiveAmount, ratio) }}>{showRemainder && (// 未分类差额: 中性色顶段 (与零消费日同色, 区别于所有模型档)<divstyle={{- height: `${(remainder / b.effectiveUsd) * 100}%`,+ height: `${(remainder / b.effectiveAmount) * 100}%`,backgroundColor: 'var(--surface-chip)',}}/>@@ -204,7 +258,7 @@ export function UsageDailyBars({<divkey={s.rank}style={{- height: `${(s.amountUsd / b.effectiveUsd) * 100}%`,+ height: `${(s.amount / b.effectiveAmount) * 100}%`,backgroundColor: usageRankColor(s.rank),}}/>@@ -219,8 +273,8 @@ export function UsageDailyBars({}/** 无分段数据 (历史日 / 无消费日) 的整根柱颜色 — 与旧版纯总额柱一致。 */-function barFallbackColor(costUsd: number, ratio: number): string {- return costUsd > 0+function barFallbackColor(amount: number, ratio: number): string {+ return amount > 0? `color-mix(in srgb, var(--accent-emphasis) ${Math.round(35 + ratio * 55)}%, var(--surface-chip))`: 'var(--surface-chip)';}@@ -230,9 +284,15 @@ function barFallbackColor(costUsd: number, ratio: number): string {* 会把它们全部四舍五入成 "$0" (重复且误导), 这里 < $10 保留小数位。* Number() 去掉尾零: $0.2 而不是 $0.20。*/-function tickLabel(v: number): string {- if (v >= 10) return formatCompactUsd(v);- return `$${Number(v.toFixed(2))}`;+function tickLabel(v: number, currency: MoneyCurrency): string {+ const money: RegionalMoney = {+ amount: v,+ currency,+ approximate: false,+ kind: 'actual-cost',+ };+ if (v >= 10) return formatCompactMoney(money);+ return `${currency === 'CNY' ? '¥' : '$'}${Number(v.toFixed(2))}`;}/**diff --git a/apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx b/apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsxindex ce449b4965..0925a01f5e 100644--- a/apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx+++ b/apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx@@ -12,16 +12,22 @@import React, { useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { formatCompactTokens } from '@/lib/usageFormat';+import { formatCompactTokens, formatMoney } from '@/lib/usageFormat';+import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';+import {+ regionalCurrencyForRegion,+ type RegionalMoney,+} from '../../../shared/regionalMoney';const CELL_PX = 12;const GAP_PX = 3;+const EMPTY_MONEY_CURRENCY = regionalCurrencyForRegion(CURRENT_CINDY_REGION);/** 非零值分桶的 color-mix 浓度阶梯 (level 1..4)。 */const LEVEL_MIX = [0.22, 0.42, 0.68, 1];interface HeatCell {day: string;- costUsd: number;+ money: RegionalMoney;/** 当日 token 合计 (daily_model_usage 上线前的历史日为 0 → tooltip 不显示)。 */tokens: number;/** 0 = 无消费, 1..4 = 分位桶。 */@@ -55,16 +61,16 @@ export function UsageHeatmap({todayKey,windowDays,}: {- days: Array<{ day: string; costUsd: number; tokens?: number }>;+ days: Array<{ day: string; money: RegionalMoney; tokens?: number }>;todayKey: string;windowDays: number;}): React.JSX.Element {const { t, i18n } = useTranslation();const { columns, monthLabels } = useMemo(() => {- const spendByDay = new Map(days.map((d) => [d.day, d.costUsd]));+ const spendByDay = new Map(days.map((d) => [d.day, d.money]));const tokensByDay = new Map(days.map((d) => [d.day, d.tokens ?? 0]));- const nonZero = days.map((d) => d.costUsd).filter((v) => v > 0).sort((a, b) => a - b);+ const nonZero = days.map((d) => d.money.amount).filter((v) => v > 0).sort((a, b) => a - b);const q = (p: number): number => (nonZero.length ? nonZero[Math.min(nonZero.length - 1, Math.floor(p * nonZero.length))] : 0);const thresholds: [number, number, number] = [q(0.25), q(0.5), q(0.75)];@@ -77,19 +83,35 @@ export function UsageHeatmap({const cursor = new Date(start);while (cursor <= today) {const key = toDayKey(cursor);- const cost = spendByDay.get(key) ?? 0;+ const money = spendByDay.get(key) ?? {+ amount: 0,+ currency: days[0]?.money.currency ?? EMPTY_MONEY_CURRENCY,+ approximate: false,+ kind: 'actual-cost' as const,+ };cells.push({day: key,- costUsd: cost,+ money,tokens: tokensByDay.get(key) ?? 0,- level: levelFor(cost, thresholds),+ level: levelFor(money.amount, thresholds),placeholder: false,});cursor.setDate(cursor.getDate() + 1);}// 末列补满 7 行 (未来日占位, 保持网格矩形)while (cells.length % 7 !== 0) {- cells.push({ day: '', costUsd: 0, tokens: 0, level: 0, placeholder: true });+ cells.push({+ day: '',+ money: {+ amount: 0,+ currency: days[0]?.money.currency ?? EMPTY_MONEY_CURRENCY,+ approximate: false,+ kind: 'actual-cost',+ },+ tokens: 0,+ level: 0,+ placeholder: true,+ });}const cols: HeatCell[][] = [];@@ -134,7 +156,7 @@ export function UsageHeatmap({) : (<divkey={ri}- title={`${cell.day} · $${cell.costUsd.toFixed(2)}${+ title={`${cell.day} · ${formatMoney(cell.money)}${cell.tokens > 0? ` · ${t('usageDashboard.tokensOnly', { tokens: formatCompactTokens(cell.tokens) })}`: ''diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsxindex 2fe656522b..bf8edb2303 100644--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx@@ -36,7 +36,13 @@ import { useTranslation } from 'react-i18next';import type { TFunction } from 'i18next';import { cn } from '@/lib/utils';-import { DAILY_SOFT_LIMIT_FACTOR, formatCompactTokens, formatCompactUsd, formatTurnCostUsd } from '@/lib/usageFormat';+import {+ DAILY_SOFT_LIMIT_FACTOR,+ formatCompactMoney,+ formatCompactTokens,+ formatTurnCostMoney,+ formatTurnCostUsd,+} from '@/lib/usageFormat';import { Tip } from '@/components/ui/tooltip';import { useApiKey } from '@/hooks/useApiKey';import { useClaudeOAuthConnected } from '@/hooks/useClaudeOAuthConnected';@@ -68,6 +74,8 @@ import { useXaiRateLimit, type XaiRateLimitSnapshot } from '@/hooks/useXaiRateLiimport { 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 {RESET_PENDING_MAX_MS,@@ -129,7 +137,7 @@ interface MetricSlot {*/function computeMetricSlots(claudeQuota: ClaudeAccountUsageSnapshot | null,- sessionCostUsd: number | null,+ sessionMoney: RegionalMoney | null,t: TFunction,): Record<MetricKey, MetricSlot> {const slots: Record<MetricKey, MetricSlot> = {@@ -142,8 +150,8 @@ function computeMetricSlots(// monthly 永远跟 cycle 一起拿到; daily 走单独 endpoint 可能拉不到 (todaySpend=null) → 隐藏slots.monthly = {label: t('todaySpend.monthlyLimitLabel', {- spend: formatCompactUsd(claudeQuota.spend),- limit: formatCompactUsd(claudeQuota.maxBudget),+ spend: formatCompactMoney(gatewayMoney(claudeQuota.spend, CURRENT_CINDY_REGION)),+ limit: formatCompactMoney(gatewayMoney(claudeQuota.maxBudget, CURRENT_CINDY_REGION)),}),available: true,};@@ -151,18 +159,21 @@ function computeMetricSlots(const softLimit = (claudeQuota.maxBudget / 30) * DAILY_SOFT_LIMIT_FACTOR;slots.daily = {label: t('todaySpend.dailyLimitLabel', {- spend: formatCompactUsd(claudeQuota.todaySpend),- limit: formatCompactUsd(softLimit),+ spend: formatCompactMoney(+ gatewayMoney(claudeQuota.todaySpend, CURRENT_CINDY_REGION),+ ),+ limit: formatCompactMoney(gatewayMoney(softLimit, CURRENT_CINDY_REGION)),}),available: true,};}}- if (typeof sessionCostUsd === 'number' && sessionCostUsd > 0) {+ if (sessionMoney && sessionMoney.amount > 0) {+ const cost = formatTurnCostMoney(sessionMoney);slots.session = {- label: t('todaySpend.sessionCostLabel', { cost: `$${sessionCostUsd.toFixed(2)}` }),- tooltipLabel: t('todaySpend.tooltip.sessionUsed', { cost: `$${sessionCostUsd.toFixed(2)}` }),+ label: t('todaySpend.sessionCostLabel', { cost }),+ tooltipLabel: t('todaySpend.tooltip.sessionUsed', { cost }),available: true,};}@@ -439,7 +450,7 @@ function getCodexApiEmptyState(function buildCodexTooltipNode(snapshot: RateLimitSnapshot | null,sessionTokens: number | null,- sessionValueUsd: number | null,+ sessionValueMoney: RegionalMoney | null,t: TFunction,usageDashboardLabel: string | null,nowMs: number,@@ -477,7 +488,7 @@ function buildCodexTooltipNode(} else if (credits?.hasCredits && !parsedCredits) {lines.push(t('todaySpend.codex.balanceAvailable'));}- pushSessionValueLines(lines, sessionValueUsd, sessionTokens, t);+ pushSessionValueLines(lines, sessionValueMoney, sessionTokens, t);for (const window of getCodexWindowUsages(snapshot, t, nowMs)) {const base = t('todaySpend.codex.windowLine', {@@ -645,7 +656,7 @@ function isClaudeSubscriptionAlerting(function buildClaudeSubscriptionTooltipNode(snapshot: ClaudeSubscriptionUsageSnapshot | null,modelId: string | null | undefined,- sessionValueUsd: number | null,+ sessionValueMoney: RegionalMoney | null,t: TFunction,usageDashboardLabel: string | null,latestTurnUsage: LatestTurnUsageSummary | null,@@ -662,9 +673,9 @@ function buildClaudeSubscriptionTooltipNode(if (planLabel) {lines.push(t('todaySpend.claude.planLine', { plan: planLabel }));}- if (typeof sessionValueUsd === 'number' && Number.isFinite(sessionValueUsd) && sessionValueUsd > 0) {+ if (sessionValueMoney?.amount) {lines.push(t('todaySpend.claude.sessionValueLabel', {- cost: `$${sessionValueUsd.toFixed(2)}`,+ cost: formatTurnCostMoney(sessionValueMoney),}));}@@ -718,8 +729,10 @@ function buildClaudeSubscriptionTooltipNode(/** 最近一轮 tooltip 使用的 assistant 消息明细。 */interface LatestTurnUsageSummary {+ money?: RegionalMoney;costUsd?: number;isEstimate?: boolean;+ segmentMoney?: RegionalMoney;segmentCostUsd?: number;segmentIsEstimate?: boolean;isUserTurnTotal: boolean;@@ -730,25 +743,38 @@ function findLatestTurnUsageSummary(messages: ChatMessage[]): LatestTurnUsageSumfor (let i = messages.length - 1; i >= 0; i--) {const message = messages[i];if (message.role !== 'assistant' || !message.turnUsageDetails) continue;+ const userTurnMoney =+ message.userTurnMoney?.amount+ ? message.userTurnMoney+ : undefined;const userTurnCostUsd = typeof message.userTurnCostUsd === 'number' && message.userTurnCostUsd > 0? message.userTurnCostUsd: undefined;return {- ...(userTurnCostUsd != null- ? { costUsd: userTurnCostUsd }+ ...(userTurnMoney+ ? { money: userTurnMoney }+ : userTurnCostUsd != null+ ? { costUsd: userTurnCostUsd }+ : message.turnMoney?.amount+ ? { money: message.turnMoney }: typeof message.turnCostUsd === 'number' && message.turnCostUsd > 0? { costUsd: message.turnCostUsd }: {}),- ...((userTurnCostUsd != null+ ...((userTurnMoney || userTurnCostUsd != null? message.userTurnCostIsEstimate: message.turnCostIsEstimate) === true ? { isEstimate: true } : {}),- ...(userTurnCostUsd != null && typeof message.turnCostUsd === 'number' && message.turnCostUsd > 0+ ...((userTurnMoney || userTurnCostUsd != null) && message.turnMoney?.amount+ ? {+ segmentMoney: message.turnMoney,+ segmentIsEstimate: message.turnCostIsEstimate === true,+ }+ : userTurnCostUsd != null && typeof message.turnCostUsd === 'number' && message.turnCostUsd > 0? {segmentCostUsd: message.turnCostUsd,segmentIsEstimate: message.turnCostIsEstimate === true,}: {}),- isUserTurnTotal: userTurnCostUsd != null,+ isUserTurnTotal: Boolean(userTurnMoney || userTurnCostUsd != null),details: message.turnUsageDetails,};}@@ -789,10 +815,15 @@ function appendLatestTurnUsageLines(): void {if (!summary) return;if (lines.length > 0) lines.push('');- if (summary.isUserTurnTotal && summary.costUsd != null) {+ if (+ summary.isUserTurnTotal &&+ (summary.money?.amount || summary.costUsd != null)+ ) {lines.push(t('todaySpend.tooltip.latestUserTurnTitle'));lines.push(t(summary.isEstimate ? 'usageDetails.valueLine' : 'usageDetails.costLine', {- cost: formatTurnCostUsd(summary.costUsd),+ cost: summary.money+ ? formatTurnCostMoney(summary.money)+ : formatTurnCostUsd(summary.costUsd ?? 0),}));}lines.push(...buildTurnUsageTooltipLines({@@ -800,6 +831,7 @@ function appendLatestTurnUsageLines(t,// Token / model detail remains scoped to the final SDK segment. Keep its// cost line separate from the user-turn total shown above.+ money: summary.isUserTurnTotal ? summary.segmentMoney : summary.money,costUsd: summary.isUserTurnTotal ? summary.segmentCostUsd : summary.costUsd,isEstimate: summary.isUserTurnTotal ? summary.segmentIsEstimate : summary.isEstimate,title: t(summary.isUserTurnTotal@@ -825,12 +857,14 @@ function pushDashboardLinkLine(lines: string[], label: string | null): void {/** 「本会话价值 / token 累计」两行 —— codex 订阅与 xai bridge tooltip 共用(同 i18n key 同格式)。 */function pushSessionValueLines(lines: string[],- sessionValueUsd: number | null,+ sessionValueMoney: RegionalMoney | null,sessionTokens: number | null,t: TFunction,): void {- if (typeof sessionValueUsd === 'number' && Number.isFinite(sessionValueUsd) && sessionValueUsd > 0) {- lines.push(t('todaySpend.codex.sessionValueLabel', { cost: `$${sessionValueUsd.toFixed(2)}` }));+ if (sessionValueMoney?.amount) {+ lines.push(t('todaySpend.codex.sessionValueLabel', {+ cost: formatTurnCostMoney(sessionValueMoney),+ }));}if (typeof sessionTokens === 'number' && Number.isFinite(sessionTokens) && sessionTokens > 0) {lines.push(t('todaySpend.codex.sessionTokensLine', {@@ -846,13 +880,13 @@ function pushSessionValueLines(function buildXaiTooltipNode(rateLimit: XaiRateLimitSnapshot | null,sessionTokens: number | null,- sessionValueUsd: number | null,+ sessionValueMoney: RegionalMoney | null,t: TFunction,usageDashboardLabel: string | null,latestTurnUsage: LatestTurnUsageSummary | null,): React.ReactNode {const lines: string[] = [];- pushSessionValueLines(lines, sessionValueUsd, sessionTokens, t);+ pushSessionValueLines(lines, sessionValueMoney, sessionTokens, t);if (rateLimit && typeof rateLimit.remainingRequests === 'number' && typeof rateLimit.limitRequests === 'number') {lines.push(t('todaySpend.xai.requestsLine', {remaining: rateLimit.remainingRequests.toLocaleString(),@@ -901,6 +935,7 @@ interface TodaySpendChipProps {/** session 累计需要 sessionId + 初始值。Claude / Codex API 显示真实 USD cost。 */sessionId?: string;/** 来自 session.totalCostUsd(sessionService.get 拿到)— mount 后由 IPC push 更新。 */+ sessionInitialMoney?: RegionalMoney | null;sessionInitialCostUsd?: number | null;/** 来自 session.totalTokenUsage(sessionService.get 拿到)— mount 后由 IPC push 更新。 */sessionInitialTokens?: number | null;@@ -919,6 +954,7 @@ export function TodaySpendChip({modelId,providerId,sessionId,+ sessionInitialMoney,sessionInitialCostUsd,sessionInitialTokens,remoteHostId,@@ -1004,10 +1040,13 @@ export function TodaySpendChip({// 订阅直连 bridge 轮真实计费恒 0(不写 sessions.total_cost_usd),spend hook 无意义 → 关。// device-link 远程会话形态未知 → 无条件启用(与 tokens / 估算价值同口径),否则被控端// 若是本机判不出的形态(如 codex+xai)累计 cost 镜像永远不展示。- const sessionCostUsd = useSessionSpend(+ const sessionMoney = useSessionSpend((vendorKey === 'cc' && !isSubscriptionBridge) || isCodexApi || isDeviceLinkRemote? sessionId: undefined,+ (vendorKey === 'cc' && !isSubscriptionBridge) || isCodexApi || isDeviceLinkRemote+ ? sessionInitialMoney+ : null,(vendorKey === 'cc' && !isSubscriptionBridge) || isCodexApi || isDeviceLinkRemote? sessionInitialCostUsd: null,@@ -1020,7 +1059,7 @@ export function TodaySpendChip({);// 订阅会话的"本会话价值"估算 (isEstimate 消息汇总): Codex OAuth / Claude 订阅 / bridge 订阅同管道。// device-link 远程会话形态未知(被控端账号事实拿不到)→ 无条件启用,有估算数据就显示。- const sessionEstimatedValueUsd = useSessionEstimatedValue(+ const sessionEstimatedValueMoney = useSessionEstimatedValue(sessionId,isCodexSubscription || isClaudeSubscription || isSubscriptionBridge || isDeviceLinkRemote,);@@ -1201,30 +1240,34 @@ export function TodaySpendChip({// turn-cost 推送)与真实累计 cost(usage:session-spend-changed 镜像)有哪个显哪个;// 被控端账号的限额窗口本机拿不到,不显示、不猜。const chipSegments: string[] = [];- if (typeof sessionEstimatedValueUsd === 'number' && sessionEstimatedValueUsd > 0) {+ if (sessionEstimatedValueMoney) {chipSegments.push(t('todaySpend.codex.sessionValueLabel', {- cost: `$${sessionEstimatedValueUsd.toFixed(2)}`,+ cost: formatTurnCostMoney(sessionEstimatedValueMoney),}));}- if (typeof sessionCostUsd === 'number' && sessionCostUsd > 0) {- chipSegments.push(t('todaySpend.sessionCostLabel', { cost: `$${sessionCostUsd.toFixed(2)}` }));+ if (sessionMoney?.amount) {+ chipSegments.push(t('todaySpend.sessionCostLabel', {+ cost: formatTurnCostMoney(sessionMoney),+ }));}labelNode = chipSegments.length > 0? renderSegmentedLabel(chipSegments): <span className="tabular-nums opacity-60">$</span>;const tooltipLines: string[] = [];- pushSessionValueLines(tooltipLines, sessionEstimatedValueUsd, sessionTokens, t);- if (typeof sessionCostUsd === 'number' && sessionCostUsd > 0) {- tooltipLines.push(t('todaySpend.tooltip.sessionUsed', { cost: `$${sessionCostUsd.toFixed(2)}` }));+ pushSessionValueLines(tooltipLines, sessionEstimatedValueMoney, sessionTokens, t);+ if (sessionMoney?.amount) {+ tooltipLines.push(t('todaySpend.tooltip.sessionUsed', {+ cost: formatTurnCostMoney(sessionMoney),+ }));}appendLatestTurnUsageLines(tooltipLines, latestTurnUsage, t);tooltipNode = tooltipLines.length > 0 ? buildTooltipNode(tooltipLines) : null;} else if (usesCodexQuotaForm) {// codex-oauth 与 cc+chatgpt/ bridge 共用同一 ChatGPT 账户,复用同一套限额窗口 + 价值估算渲染。const chipSegments = [...windowSegments];- if (typeof sessionEstimatedValueUsd === 'number' && sessionEstimatedValueUsd > 0) {+ if (sessionEstimatedValueMoney) {chipSegments.push(t('todaySpend.codex.sessionValueLabel', {- cost: `$${sessionEstimatedValueUsd.toFixed(2)}`,+ cost: formatTurnCostMoney(sessionEstimatedValueMoney),}));}labelNode = chipSegments.length > 0@@ -1233,7 +1276,7 @@ export function TodaySpendChip({tooltipNode = buildCodexTooltipNode(accountUsage,sessionTokens,- sessionEstimatedValueUsd,+ sessionEstimatedValueMoney,t,usageDashboardLabel,windowLabelNowMs,@@ -1242,9 +1285,9 @@ export function TodaySpendChip({} else if (usesXaiQuotaForm) {// xAI 无订阅窗口数据源:主 chip 只显示本会话价值估算,限流细节(若 bridge 抓到)进 tooltip。const chipSegments: string[] = [];- if (typeof sessionEstimatedValueUsd === 'number' && sessionEstimatedValueUsd > 0) {+ if (sessionEstimatedValueMoney) {chipSegments.push(t('todaySpend.codex.sessionValueLabel', {- cost: `$${sessionEstimatedValueUsd.toFixed(2)}`,+ cost: formatTurnCostMoney(sessionEstimatedValueMoney),}));}labelNode = chipSegments.length > 0@@ -1253,7 +1296,7 @@ export function TodaySpendChip({tooltipNode = buildXaiTooltipNode(xaiRateLimit,sessionTokens,- sessionEstimatedValueUsd,+ sessionEstimatedValueMoney,t,usageDashboardLabel,latestTurnUsage,@@ -1262,9 +1305,9 @@ export function TodaySpendChip({// Claude 订阅形态 (方案 B): chip 显示「剩余时长 剩余%」倒计时段 + 本会话价值,// 倒计时由 windowLabelNowMs 驱动 (常态 60s tick, 最后一分钟逐秒); tooltip 保留精确时间。const chipSegments = [...windowSegments];- if (typeof sessionEstimatedValueUsd === 'number' && sessionEstimatedValueUsd > 0) {+ if (sessionEstimatedValueMoney) {chipSegments.push(t('todaySpend.claude.sessionValueLabel', {- cost: `$${sessionEstimatedValueUsd.toFixed(2)}`,+ cost: formatTurnCostMoney(sessionEstimatedValueMoney),}));}labelNode = chipSegments.length > 0@@ -1273,13 +1316,13 @@ export function TodaySpendChip({tooltipNode = buildClaudeSubscriptionTooltipNode(claudeSubscriptionUsage,modelId,- sessionEstimatedValueUsd,+ sessionEstimatedValueMoney,t,usageDashboardLabel,latestTurnUsage,);} else {- const slots = computeMetricSlots(claudeQuota, sessionCostUsd, t);+ const slots = computeMetricSlots(claudeQuota, sessionMoney, t);const chipSegments = getGatewayChipSegments(slots);const codexApiHasTokenFallback = isCodexApi&& !slots.session.availablediff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex 711c4d5448..48be9f4cb4 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -3300,6 +3300,7 @@ export function CCAgentSessionView({: (session?.providerId ?? null)}sessionId={sessionId}+ sessionInitialMoney={session?.totalMoney ?? null}sessionInitialCostUsd={session?.totalCostUsd ?? null}sessionInitialTokens={session?.totalTokenUsage ?? null}remoteHostId={session?.remoteHostId ?? null}diff --git a/apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsx b/apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsxindex c12a67f7c8..812cb6be03 100644--- a/apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsx+++ b/apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsx@@ -31,7 +31,13 @@ import {import { AgentMark } from './AgentMark';import { AttentionDot } from '@/components/sidebar/AttentionDot';-import { formatDuration, formatRunTimestamp, formatStartedAgo, formatUsd } from '../lib/formatters';+import { formatDuration, formatRunTimestamp, formatStartedAgo } from '../lib/formatters';+import { formatTurnCostMoney } from '@/lib/usageFormat';+import { CURRENT_CINDY_REGION } from '../../../../shared/brandRegion';+import {+ regionalizeLegacyUsd,+ regionalizeUsd,+} from '../../../../shared/regionalMoney';import { isUnreadScheduleRun } from '../lib/runUnread';import { markScheduleRunReadAndSync } from '../lib/scheduleRunReadSync';@@ -162,16 +168,35 @@ export function RunHistoryCard({run.costAttribution === 'direct' ||run.costAttribution === 'mixed' ||run.costAttribution === 'zero'- ? [- (run.costUsd ?? 0) > 0- ? t('scheduler.runs.runCost', { cost: formatUsd(run.costUsd ?? 0) })- : null,- (run.estimatedValueUsd ?? 0) > 0- ? t('scheduler.runs.runValue', { value: formatUsd(run.estimatedValueUsd ?? 0) })- : null,- ]- .filter(Boolean)- .join(' · ') || t('scheduler.runs.runCost', { cost: formatUsd(0) })+ ? (() => {+ const costMoney =+ run.costMoney ??+ regionalizeLegacyUsd(+ run.costUsd ?? 0,+ CURRENT_CINDY_REGION,+ );+ const valueMoney =+ run.estimatedValueMoney ??+ regionalizeUsd(+ run.estimatedValueUsd ?? 0,+ CURRENT_CINDY_REGION,+ 'legacy-usd',+ 'value-estimate',+ );+ return [+ costMoney.amount > 0+ ? t('scheduler.runs.runCost', { cost: formatTurnCostMoney(costMoney) })+ : null,+ valueMoney.amount > 0+ ? t('scheduler.runs.runValue', { value: formatTurnCostMoney(valueMoney) })+ : null,+ ]+ .filter(Boolean)+ .join(' · ') ||+ t('scheduler.runs.runCost', {+ cost: formatTurnCostMoney(costMoney),+ });+ })(): null;// 终态且未读 → 在 agent 图标右上角点一个状态点(全端统一色表:失败结局红 / 成功绿)。diff --git a/apps/desktop/src/renderer/features/scheduler/components/TaskListCell.tsx b/apps/desktop/src/renderer/features/scheduler/components/TaskListCell.tsxindex fc40e4a48a..f3bc9417da 100644--- a/apps/desktop/src/renderer/features/scheduler/components/TaskListCell.tsx+++ b/apps/desktop/src/renderer/features/scheduler/components/TaskListCell.tsx@@ -29,6 +29,7 @@ import { useTranslation } from 'react-i18next';import { cn } from '@/lib/utils';import { AttentionDot } from '@/components/sidebar/AttentionDot';import type { Schedule } from '@cindy/maker-scheduler';+import type { RegionalMoney } from '../../../../shared/regionalMoney';import {DropdownMenu,DropdownMenuContent,@@ -37,14 +38,15 @@ import {DropdownMenuTrigger,} from '@/components/ui/dropdown-menu';-import { formatLastRun, formatNextRun, formatUsd } from '../lib/formatters';+import { formatLastRun, formatNextRun } from '../lib/formatters';+import { formatTurnCostMoney } from '@/lib/usageFormat';interface Props {schedule: Schedule;selected: boolean;unreadCount?: number;- totalCostUsd?: number;- totalEstimatedValueUsd?: number;+ totalMoney?: RegionalMoney;+ totalEstimatedValueMoney?: RegionalMoney;hasUnavailableCost?: boolean;onSelect: (s: Schedule) => void;/** 右键菜单的 Pause/Resume 动作;与 RunHistoryPane ⋯ 菜单同行为。 */@@ -80,8 +82,8 @@ export function TaskListCell({schedule: s,selected,unreadCount = 0,- totalCostUsd,- totalEstimatedValueUsd = 0,+ totalMoney,+ totalEstimatedValueMoney,hasUnavailableCost = false,onSelect,onTogglePause,@@ -166,19 +168,28 @@ export function TaskListCell({subtitle = lastText ?? nextText;}const costText =- totalCostUsd == null && !hasUnavailableCost+ totalMoney == null && !hasUnavailableCost? null: [- (totalCostUsd ?? 0) > 0- ? t('scheduler.cell.totalCost', { cost: formatUsd(totalCostUsd ?? 0) })+ totalMoney && totalMoney.amount > 0+ ? t('scheduler.cell.totalCost', {+ cost: formatTurnCostMoney(totalMoney),+ }): null,- totalEstimatedValueUsd > 0- ? t('scheduler.cell.totalValue', { value: formatUsd(totalEstimatedValueUsd) })+ (totalEstimatedValueMoney?.amount ?? 0) > 0+ ? t('scheduler.cell.totalValue', {+ value: formatTurnCostMoney(totalEstimatedValueMoney!),+ }): null,hasUnavailableCost ? t('scheduler.cell.costUnavailable') : null,].filter(Boolean)- .join(' · ') || t('scheduler.cell.totalCost', { cost: formatUsd(0) });+ .join(' · ') ||+ (totalMoney+ ? t('scheduler.cell.totalCost', {+ cost: formatTurnCostMoney(totalMoney),+ })+ : t('scheduler.cell.costUnavailable'));// 副标题行是否渲染:决定右下角 Run 按钮的"预留位"落在哪一行(见下方两处 pr-3.5)。const hasMetaRow = Boolean(subtitle || costText);diff --git a/apps/desktop/src/renderer/features/scheduler/components/TaskListPane.tsx b/apps/desktop/src/renderer/features/scheduler/components/TaskListPane.tsxindex 002ff1933e..9a1cd37d6b 100644--- a/apps/desktop/src/renderer/features/scheduler/components/TaskListPane.tsx+++ b/apps/desktop/src/renderer/features/scheduler/components/TaskListPane.tsx@@ -225,14 +225,14 @@ export function TaskListPane({schedule={s}selected={s.id === selectedId}unreadCount={unreadRunCounts.get(s.id) ?? 0}- totalCostUsd={+ totalMoney={costSummariesLoaded- ? costSummaries.get(s.id)?.totalCostUsd+ ? costSummaries.get(s.id)?.totalMoney: undefined}- totalEstimatedValueUsd={+ totalEstimatedValueMoney={costSummariesLoaded- ? costSummaries.get(s.id)?.totalEstimatedValueUsd+ ? costSummaries.get(s.id)?.totalEstimatedValueMoney: undefined}hasUnavailableCost={diff --git a/apps/desktop/src/renderer/features/scheduler/components/__tests__/TaskListCell.test.tsx b/apps/desktop/src/renderer/features/scheduler/components/__tests__/TaskListCell.test.tsxindex 30cd5ec3da..3fcf711d31 100644--- a/apps/desktop/src/renderer/features/scheduler/components/__tests__/TaskListCell.test.tsx+++ b/apps/desktop/src/renderer/features/scheduler/components/__tests__/TaskListCell.test.tsx@@ -112,7 +112,12 @@ describe('TaskListCell 费用展示', () => {schedule,selected: false,onSelect: vi.fn(),- totalCostUsd: 0,+ totalMoney: {+ amount: 0,+ currency: 'USD',+ approximate: false,+ kind: 'actual-cost',+ },hasUnavailableCost: true,}),);@@ -127,7 +132,12 @@ describe('TaskListCell 费用展示', () => {schedule,selected: false,onSelect: vi.fn(),- totalCostUsd: 0,+ totalMoney: {+ amount: 0,+ currency: 'USD',+ approximate: false,+ kind: 'actual-cost',+ },hasUnavailableCost: false,}),);diff --git a/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleCostSummaries.ts b/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleCostSummaries.tsindex 0d572388bb..450ef4c365 100644--- a/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleCostSummaries.ts+++ b/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleCostSummaries.ts@@ -2,25 +2,30 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import type { Schedule, SchedulerEvent } from '@cindy/maker-scheduler';import { createLogger } from '@/lib/logger';+import type { RegionalMoney } from '../../../../shared/regionalMoney';const log = createLogger('ScheduleCostSummaries');/** 单个自动化任务按自动化触发的 turn 汇总出的累计开销。 */export interface ScheduleCostSummary {scheduleId: string;- totalCostUsd: number;- totalEstimatedValueUsd: number;+ totalMoney: RegionalMoney;+ totalEstimatedValueMoney: RegionalMoney;+ totalCostUsd?: number;+ totalEstimatedValueUsd?: number;/** 至少一轮自动化无法取得可靠费用。 */hasUnavailableCost?: boolean;- /** 产生过自动化 run 的去重 session 数;费用不可用或确认为零的 run 也会计入。 */+ /** 产生过自动化 turn cost 的去重 session 数;legacy 会话兜底同样计入。 */sessionCount: number;sessions?: readonly ScheduleSessionCostSummary[];}export interface ScheduleSessionCostSummary {sessionId: string;- totalCostUsd: number;- totalEstimatedValueUsd: number;+ totalMoney: RegionalMoney;+ totalEstimatedValueMoney: RegionalMoney;+ totalCostUsd?: number;+ totalEstimatedValueUsd?: number;}/** Automation 任务列表的 cost summary 状态;loaded=false 时 UI 不显示占位金额。 */diff --git a/apps/desktop/src/renderer/hooks/__tests__/useCCAgentChatHiddenFreeze.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/useCCAgentChatHiddenFreeze.test.tsxindex b09d310093..a6630e37a6 100644--- a/apps/desktop/src/renderer/hooks/__tests__/useCCAgentChatHiddenFreeze.test.tsx+++ b/apps/desktop/src/renderer/hooks/__tests__/useCCAgentChatHiddenFreeze.test.tsx@@ -116,10 +116,12 @@ import { ChatDisplaySnapshotProvider, type ChatDisplaySnapshot } from '@/componeimport { makerChatStore, type ChatMessage } from '@/lib/makerChatStore';import * as messageService from '@/lib/messageService';import { buildTurnUsageDetails } from '../../../shared/turnUsageDetails';+import type { RegionalMoney } from '../../../shared/regionalMoney';type TurnCostListener = (payload: {sessionId: string;clientId: string;+ turnMoney?: RegionalMoney;turnCostUsd: number;turnCostIsEstimate: boolean;turnUsageDetails?: unknown;@@ -138,6 +140,16 @@ if (!TURN_USAGE_DETAILS) {throw new Error('expected test turn usage details to be buildable');}+function usdEstimate(amount: number): RegionalMoney {+ return {+ amount,+ currency: 'USD',+ approximate: true,+ kind: 'value-estimate',+ estimateReasons: ['subscription-value'],+ };+}+function sid(label: string): string {return `${label}-${Math.random().toString(36).slice(2, 8)}`;}@@ -152,6 +164,7 @@ function assistantCostMessage(clientId: string, costUsd: number): ChatMessage {role: 'assistant',content: `cost ${costUsd}`,createdAt: new Date(0).toISOString(),+ turnMoney: usdEstimate(costUsd),turnCostUsd: costUsd,turnCostIsEstimate: true,turnUsageDetails: TURN_USAGE_DETAILS,@@ -278,7 +291,7 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {function EstimatedValueProbe() {renderCounts.estimated += 1;const value = useSessionEstimatedValue(sessionId, true);- return <div data-testid="estimated-value">{value == null ? '' : value.toFixed(2)}</div>;+ return <div data-testid="estimated-value">{value == null ? '' : value.amount.toFixed(2)}</div>;}function TestTree({ snapshot }: { snapshot: ChatDisplaySnapshot }) {@@ -297,6 +310,7 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {turnCostListener?.({sessionId,clientId: 'hidden-cost',+ turnMoney: usdEstimate(9.99),turnCostUsd: 9.99,turnCostIsEstimate: true,turnUsageDetails: TURN_USAGE_DETAILS,@@ -330,7 +344,7 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {function EstimatedValueProbe() {const value = useSessionEstimatedValue(sessionId, true);- return <div data-testid="estimated-value">{value == null ? '' : value.toFixed(2)}</div>;+ return <div data-testid="estimated-value">{value == null ? '' : value.amount.toFixed(2)}</div>;}render(@@ -351,6 +365,7 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {turnCostListener?.({sessionId,clientId: 'unknown-live-client',+ turnMoney: usdEstimate(2.5),turnCostUsd: 2.5,turnCostIsEstimate: true,turnUsageDetails: TURN_USAGE_DETAILS,@@ -377,12 +392,20 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {};const renderCounts = { estimated: 0 };vi.mocked(messageService.estimatedSessionValue)- .mockResolvedValueOnce({ totalValueUsd: 4.56, entries: [{ clientId: 'hidden-cost', costUsd: 4.56 }] });+ .mockResolvedValueOnce({+ totalValueMoney: usdEstimate(4.56),+ totalValueUsd: 4.56,+ entries: [{+ clientId: 'hidden-cost',+ money: usdEstimate(4.56),+ costUsd: 4.56,+ }],+ });function EstimatedValueProbe({ sessionId: currentSessionId }: { sessionId: string }) {renderCounts.estimated += 1;const value = useSessionEstimatedValue(currentSessionId, true);- return <div data-testid="estimated-value">{value == null ? '' : value.toFixed(2)}</div>;+ return <div data-testid="estimated-value">{value == null ? '' : value.amount.toFixed(2)}</div>;}const { rerender } = render(@@ -403,6 +426,7 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {turnCostListener?.({sessionId,clientId: 'hidden-cost',+ turnMoney: usdEstimate(9.99),turnCostUsd: 9.99,turnCostIsEstimate: true,turnUsageDetails: TURN_USAGE_DETAILS,@@ -429,6 +453,7 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {turnCostListener?.({sessionId,clientId: 'hidden-cost',+ turnMoney: usdEstimate(4.56),turnCostUsd: 4.56,turnCostIsEstimate: true,turnUsageDetails: TURN_USAGE_DETAILS,@@ -464,7 +489,7 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {function EstimatedValueProbe({ sessionId: currentSessionId }: { sessionId: string }) {const value = useSessionEstimatedValue(currentSessionId, true);- return <div data-testid="estimated-value">{value == null ? '' : value.toFixed(2)}</div>;+ return <div data-testid="estimated-value">{value == null ? '' : value.amount.toFixed(2)}</div>;}const { rerender } = render(@@ -480,6 +505,7 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {turnCostListener?.({sessionId: clearedSessionId,clientId: 'stale-before-clear',+ turnMoney: usdEstimate(6.66),turnCostUsd: 6.66,turnCostIsEstimate: true,turnUsageDetails: TURN_USAGE_DETAILS,@@ -515,12 +541,28 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {await waitFor(() => expect(pendingQueries.has(nextSessionId)).toBe(true));act(() => {- pendingQueries.get(staleSessionId)?.({ totalValueUsd: 7.77, entries: [{ clientId: 'stale-entry', costUsd: 7.77 }] });+ pendingQueries.get(staleSessionId)?.({+ totalValueMoney: usdEstimate(7.77),+ totalValueUsd: 7.77,+ entries: [{+ clientId: 'stale-entry',+ money: usdEstimate(7.77),+ costUsd: 7.77,+ }],+ });});expect(screen.getByTestId('estimated-value').textContent).toBe('');act(() => {- pendingQueries.get(nextSessionId)?.({ totalValueUsd: 3.21, entries: [{ clientId: 'next-entry', costUsd: 3.21 }] });+ pendingQueries.get(nextSessionId)?.({+ totalValueMoney: usdEstimate(3.21),+ totalValueUsd: 3.21,+ entries: [{+ clientId: 'next-entry',+ money: usdEstimate(3.21),+ costUsd: 3.21,+ }],+ });});await waitFor(() => expect(screen.getByTestId('estimated-value').textContent).toBe('3.21'));diff --git a/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts b/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.tsindex 9cad391587..ff32743f2b 100644--- a/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts+++ b/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts@@ -28,14 +28,15 @@import { useEffect, useState } from 'react';export interface ClaudeAccountUsageSnapshot {- /** 月度周期跨客户端累计 USD。 */+ /** 月度周期跨客户端累计,保持 Gateway 部署区域的原生金额。 */spend: number;- /** 月度周期上限 USD。 */+ /** 月度周期上限,保持 Gateway 部署区域的原生金额。 */maxBudget: number;/** 下次月度 reset 时间 ISO8601。 */budgetResetAt?: string | null;/**- * 今日 (UTC 日) 跨客户端累计 USD, 来自 LiteLLM /user/daily/activity 的+ * 今日 (UTC 日) 跨客户端累计,保持 Gateway 部署区域的原生金额,来自+ * LiteLLM /user/daily/activity 的* results[0].metrics.spend。null 表示该端点暂时不可用 (跟 cycle 是独立 fetch),* 此时消费方应隐藏 daily 段。*/diff --git a/apps/desktop/src/renderer/hooks/useModelPricing.ts b/apps/desktop/src/renderer/hooks/useModelPricing.tsindex 48cf8c4a9a..1e4bc98f1f 100644--- a/apps/desktop/src/renderer/hooks/useModelPricing.ts+++ b/apps/desktop/src/renderer/hooks/useModelPricing.ts@@ -1,50 +1,71 @@-/**- * useModelPricing — 模型单价表 (model id → USD/Mtok) 的 renderer 侧只读缓存。- *- * 数据通道: main usage/modelPricing.ts (LiteLLM /model_group/info, 内存 + 磁盘缓存, 启动预热)- * → IPC maker:usage:model-pricing → 本 hook。- *- * 语义:- * - 价格是账号级静态数据, main 端全局缓存; renderer module-local 只保留一份只读快照,- * in-flight 共享 Promise, 后挂载者复用结果 (避免多个 ModelSelector 同开时重复 IPC)- * - 返回 null = 还没拉到 / 拉取失败 — 消费方隐藏价格展示, 不出 loading 态- * (符合设计规范: 数据未到时界面不变化)- * - 查不到某个 model id = 该模型无定价 (LiteLLM 未配价, 不是免费), 同样隐藏- */+/** renderer 侧 provider-scoped 模型价格快照。 */import { useEffect, useState } from 'react';-export interface ModelPrice {- inputUsdPerMtok: number;- outputUsdPerMtok: number;-}+import type {+ ModelPriceQuote,+ ModelPricingCatalog,+} from '../../shared/regionalMoney';-export type ModelPricingMap = Record<string, ModelPrice>;+let cache: ModelPricingCatalog | null = null;+let cacheLoaded = false;+let inflight: Promise<ModelPricingCatalog | null> | null = null;-let cache: ModelPricingMap | null = null;-let inflight: Promise<ModelPricingMap | null> | null = null;+function isNonNegativeFinite(value: unknown): value is number {+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;+}-function isValidMap(v: unknown): v is ModelPricingMap {+function isValidQuote(+ value: unknown,+ providerId: string,+ modelId: string,+): value is ModelPriceQuote {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;+ const quote = value as Partial<ModelPriceQuote>;+ return (+ quote.providerId === providerId &&+ quote.modelId === modelId &&+ (quote.currency === 'CNY' || quote.currency === 'USD') &&+ quote.source === 'gateway' &&+ quote.approximate === false &&+ isNonNegativeFinite(quote.inputPerMtok) &&+ isNonNegativeFinite(quote.outputPerMtok) &&+ (quote.cacheReadPerMtok === undefined ||+ isNonNegativeFinite(quote.cacheReadPerMtok)) &&+ (quote.cacheCreatePerMtok === undefined ||+ isNonNegativeFinite(quote.cacheCreatePerMtok))+ );+}++function isValidCatalog(v: unknown): v is ModelPricingCatalog {if (!v || typeof v !== 'object' || Array.isArray(v)) return false;- return Object.values(v as Record<string, unknown>).every(- (p) =>- !!p &&- typeof p === 'object' &&- typeof (p as ModelPrice).inputUsdPerMtok === 'number' &&- typeof (p as ModelPrice).outputUsdPerMtok === 'number',+ return Object.entries(v as Record<string, unknown>).every(+ ([providerId, rawModels]) =>+ !!providerId &&+ !!rawModels &&+ typeof rawModels === 'object' &&+ !Array.isArray(rawModels) &&+ Object.entries(rawModels as Record<string, unknown>).every(+ ([modelId, quote]) => isValidQuote(quote, providerId, modelId),+ ),);}-function load(): Promise<ModelPricingMap | null> {- if (cache) return Promise.resolve(cache);+function load(): Promise<ModelPricingCatalog | null> {+ if (cacheLoaded) return Promise.resolve(cache);if (!inflight) {inflight = window.electronAPI.maker.usage.getModelPricing().then((res) => {- if (isValidMap(res) && Object.keys(res).length > 0) cache = res;+ cacheLoaded = true;+ cache = isValidCatalog(res) ? res : null;return cache;})- .catch(() => null)+ .catch(() => {+ cacheLoaded = true;+ cache = null;+ return null;+ }).finally(() => {inflight = null;});@@ -52,17 +73,23 @@ function load(): Promise<ModelPricingMap | null> {return inflight;}-export function useModelPricing(): ModelPricingMap | null {- const [pricing, setPricing] = useState<ModelPricingMap | null>(cache);+export function useModelPricing(): ModelPricingCatalog | null {+ const [pricing, setPricing] = useState<ModelPricingCatalog | null>(cache);useEffect(() => {- if (cache) return;let active = true;+ const unsubscribe =+ window.electronAPI.maker.usage.onModelPricingChanged((next) => {+ cacheLoaded = true;+ cache = isValidCatalog(next) ? next : null;+ if (active) setPricing(cache);+ });void load().then((res) => {- if (active && res) setPricing(res);+ if (active) setPricing(res);});return () => {active = false;+ unsubscribe();};}, []);diff --git a/apps/desktop/src/renderer/hooks/useSessionEstimatedValue.ts b/apps/desktop/src/renderer/hooks/useSessionEstimatedValue.tsindex be8cec7865..63e22bee78 100644--- a/apps/desktop/src/renderer/hooks/useSessionEstimatedValue.ts+++ b/apps/desktop/src/renderer/hooks/useSessionEstimatedValue.ts@@ -2,8 +2,9 @@* useSessionEstimatedValue — 订阅当前 Codex 订阅会话的"本会话价值"。** 订阅价值不能写入 sessions.total_cost_usd(那是 scheduler / API 账单的真实 cost)。- * 这里从 assistant message 的 agentMeta.turnCostUsd 估算值汇总,历史初值走 main- * 侧 SQLite 汇总,实时增量走 usage:message-turn-cost。+ * 这里从 assistant message 的结构化 turnMoney 估算值汇总,历史初值走 main+ * 侧 SQLite 汇总,实时增量走 usage:message-turn-cost。旧 turnCostUsd 只作为+ * 历史 USD 事实投影到当前区域金额。*/import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';@@ -12,6 +13,16 @@ import { useChatDisplaySnapshot } from '@/components/chat/ChatDisplaySnapshotConimport { 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,+ USD_TO_CNY_FIXED_RATE,+ type MoneyEstimateReason,+ type RegionalMoney,+} from '../../shared/regionalMoney';import { normalizeTurnUsageDetails } from '../../shared/turnUsageDetails';interface EstimatedValueStoreSnapshot {@@ -21,30 +32,111 @@ interface EstimatedValueStoreSnapshot {}interface EstimatedValueStoreSyncResult {- costs: Map<string, number>;+ costs: Map<string, RegionalMoney>;storeClientIds: Set<string>;}interface EstimatedValueTurnCostPayload {clientId: string;- turnCostUsd: number;+ turnMoney?: unknown;+ turnCostUsd?: number;turnCostIsEstimate: boolean;turnUsageDetails?: unknown;}-function estimateFromChatMessage(message: ChatMessage): { clientId: string; costUsd: number } | null {+function asValueEstimate(+ money: RegionalMoney,+ reason: MoneyEstimateReason = 'subscription-value',+): RegionalMoney {+ const estimateReasons = [...new Set([...(money.estimateReasons ?? []), reason])];+ return {+ ...money,+ approximate: true,+ kind: 'value-estimate',+ estimateReasons,+ };+}++function correctStaleUsdEstimate(+ money: RegionalMoney,+ turnUsageDetails: unknown,+ model?: string,+): RegionalMoney {+ const reasons = money.estimateReasons ?? [];+ const isLegacyCnyProjection =+ money.currency === 'CNY' &&+ reasons.includes('legacy-usd') &&+ reasons.includes('fixed-fx');+ if (money.currency !== 'USD' && !isLegacyCnyProjection) return money;+ const amountUsd = isLegacyCnyProjection+ ? money.amount / USD_TO_CNY_FIXED_RATE+ : money.amount;+ const corrected = resolveStaleCodexSubscriptionValueEstimate(+ amountUsd,+ normalizeTurnUsageDetails(turnUsageDetails),+ model,+ );+ if (corrected == null) return money;+ return {+ ...money,+ amount: isLegacyCnyProjection+ ? corrected * USD_TO_CNY_FIXED_RATE+ : corrected,+ };+}++function legacyEstimateMoney(costUsd: number): RegionalMoney | null {+ if (!Number.isFinite(costUsd) || costUsd <= 0) return null;+ return regionalizeUsd(+ costUsd,+ CURRENT_CINDY_REGION,+ 'legacy-usd',+ 'value-estimate',+ );+}++function estimateFromChatMessage(message: ChatMessage): { clientId: string; money: RegionalMoney } | null {if (message.role !== 'assistant') return null;if (message.turnCostIsEstimate !== true) return null;- if (typeof message.turnCostUsd !== 'number' || !Number.isFinite(message.turnCostUsd) || message.turnCostUsd <= 0) {- return null;+ const normalized =+ normalizeRegionalMoney(message.turnMoney) ??+ (typeof message.turnCostUsd === 'number'+ ? legacyEstimateMoney(message.turnCostUsd)+ : null);+ if (!normalized || normalized.amount <= 0) return null;+ return {+ clientId: message.clientId,+ money: correctStaleUsdEstimate(+ asValueEstimate(normalized),+ message.turnUsageDetails,+ message.model,+ ),+ };+}++function areMoneyEqual(a: RegionalMoney, b: RegionalMoney): boolean {+ if (+ a.amount !== b.amount ||+ a.currency !== b.currency ||+ a.approximate !== b.approximate ||+ a.kind !== b.kind+ ) {+ return false;}- return { clientId: message.clientId, costUsd: message.turnCostUsd };+ const aReasons = a.estimateReasons ?? [];+ const bReasons = b.estimateReasons ?? [];+ return aReasons.length === bReasons.length &&+ aReasons.every((reason, index) => reason === bReasons[index]);}-function areCostMapsEqual(a: ReadonlyMap<string, number>, b: ReadonlyMap<string, number>): boolean {+function areCostMapsEqual(+ a: ReadonlyMap<string, RegionalMoney>,+ b: ReadonlyMap<string, RegionalMoney>,+): boolean {if (a.size !== b.size) return false;for (const [key, value] of a) {- if (b.get(key) !== value) return false;+ const other = b.get(key);+ if (!other || !areMoneyEqual(value, other)) return false;}return true;}@@ -67,7 +159,7 @@ export function shouldApplyEstimatedValueEntry(}export function syncEstimatedValueCostsFromStoreSnapshot(- currentCosts: ReadonlyMap<string, number>,+ currentCosts: ReadonlyMap<string, RegionalMoney>,previousStoreClientIds: ReadonlySet<string>,snapshot: EstimatedValueStoreSnapshot,): EstimatedValueStoreSyncResult | null {@@ -89,7 +181,7 @@ export function syncEstimatedValueCostsFromStoreSnapshot(if (!message.clientId) continue;const entry = estimateFromChatMessage(message);if (entry) {- next.set(entry.clientId, entry.costUsd);+ next.set(entry.clientId, entry.money);} else {next.delete(message.clientId);}@@ -102,24 +194,33 @@ export function syncEstimatedValueCostsFromStoreSnapshot(export function resolveEstimatedValueTurnCostEntry(payload: EstimatedValueTurnCostPayload,-): { clientId: string; costUsd: number } | null {+): { clientId: string; money: RegionalMoney } | null {if (payload.turnCostIsEstimate !== true) return null;if (!payload.clientId) return null;- if (!Number.isFinite(payload.turnCostUsd) || payload.turnCostUsd <= 0) return null;- const corrected = resolveStaleCodexSubscriptionValueEstimate(- payload.turnCostUsd,- normalizeTurnUsageDetails(payload.turnUsageDetails),- );+ const normalized =+ normalizeRegionalMoney(payload.turnMoney) ??+ (typeof payload.turnCostUsd === 'number'+ ? legacyEstimateMoney(payload.turnCostUsd)+ : null);+ if (!normalized || normalized.amount <= 0) return null;return {clientId: payload.clientId,- costUsd: corrected ?? payload.turnCostUsd,+ money: correctStaleUsdEstimate(+ asValueEstimate(normalized),+ payload.turnUsageDetails,+ ),};}-function sumCosts(costs: Map<string, number>): number | null {- let total = 0;- for (const cost of costs.values()) total += cost;- return total > 0 ? total : null;+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),+ );+ if (!total) return null;+ return total.amount > 0 ? total : null;}const NOOP_UNSUBSCRIBE = () => {};@@ -127,14 +228,14 @@ const NOOP_UNSUBSCRIBE = () => {};export function useSessionEstimatedValue(sessionId: string | undefined,enabled: boolean,-): number | null {+): RegionalMoney | null {const displaySnapshot = useChatDisplaySnapshot(sessionId);const displaySnapshotRef = useRef(displaySnapshot);const shouldListenForDirectTurnCost = !displaySnapshot || displaySnapshot.chatRealtime;- const costsRef = useRef<Map<string, number>>(new Map());+ const costsRef = useRef<Map<string, RegionalMoney>>(new Map());const storeClientIdsRef = useRef<Set<string>>(new Set());const transcriptClearedRef = useRef(false);- const [valueUsd, setValueUsd] = useState<number | null>(null);+ const [valueMoney, setValueMoney] = useState<RegionalMoney | null>(null);const subscribeSnapshot = useCallback((cb: () => void) =>!enabled || !sessionId || displaySnapshot@@ -156,7 +257,7 @@ export function useSessionEstimatedValue(costsRef.current = new Map();storeClientIdsRef.current = new Set();transcriptClearedRef.current = false;- setValueUsd(null);+ setValueMoney(null);}, [enabled, sessionId]);useEffect(() => {@@ -173,19 +274,19 @@ export function useSessionEstimatedValue(storeClientIdsRef.current = result.storeClientIds;if (areCostMapsEqual(costsRef.current, result.costs)) return;costsRef.current = result.costs;- setValueUsd(sumCosts(result.costs));+ setValueMoney(sumCosts(result.costs));}, [enabled, sessionId, storeSnapshot]);useEffect(() => {if (!enabled || !sessionId) return undefined;let cancelled = false;- const applyCosts = (next: Map<string, number>): void => {+ const applyCosts = (next: Map<string, RegionalMoney>): void => {if (cancelled || areCostMapsEqual(costsRef.current, next)) return;costsRef.current = next;- setValueUsd(sumCosts(next));+ setValueMoney(sumCosts(next));};- const mergeEntry = (entry: { clientId: string; costUsd: number } | null): void => {- if (cancelled || !entry || !entry.clientId || !Number.isFinite(entry.costUsd) || entry.costUsd <= 0) return;+ const mergeEntry = (entry: { clientId: string; money: RegionalMoney } | null): void => {+ if (cancelled || !entry || !entry.clientId || entry.money.amount <= 0) return;const snapshot = displaySnapshotRef.current ?? makerChatStore.getSnapshot(sessionId);if (!shouldApplyEstimatedValueEntry(snapshot,@@ -193,9 +294,9 @@ export function useSessionEstimatedValue(transcriptClearedRef.current,)) return;const prev = costsRef.current.get(entry.clientId);- if (prev === entry.costUsd) return;+ if (prev && areMoneyEqual(prev, entry.money)) return;const next = new Map(costsRef.current);- next.set(entry.clientId, entry.costUsd);+ next.set(entry.clientId, entry.money);applyCosts(next);};@@ -213,7 +314,21 @@ export function useSessionEstimatedValue(void estimatedSessionValueFor(sessionId).then((snapshot) => {if (cancelled) return;- for (const entry of snapshot.entries) mergeEntry(entry);+ for (const entry of snapshot.entries) {+ const normalized =+ normalizeRegionalMoney(entry.money) ??+ (typeof entry.costUsd === 'number'+ ? legacyEstimateMoney(entry.costUsd)+ : null);+ if (!normalized) continue;+ mergeEntry({+ clientId: entry.clientId,+ money: correctStaleUsdEstimate(+ asValueEstimate(normalized),+ entry.turnUsageDetails,+ ),+ });+ }}).catch(() => {// 历史汇总失败不影响实时增量;本 hook 只是展示辅助信息。@@ -225,5 +340,5 @@ export function useSessionEstimatedValue(};}, [enabled, sessionId, shouldListenForDirectTurnCost]);- return valueUsd;+ return valueMoney;}diff --git a/apps/desktop/src/renderer/hooks/useSessionSpend.ts b/apps/desktop/src/renderer/hooks/useSessionSpend.tsindex c6f931dfb7..6ef721eacc 100644--- a/apps/desktop/src/renderer/hooks/useSessionSpend.ts+++ b/apps/desktop/src/renderer/hooks/useSessionSpend.ts@@ -10,29 +10,54 @@*/import { useEffect, useState } from 'react';+import { CURRENT_CINDY_REGION } from '../../shared/brandRegion';+import {+ normalizeRegionalMoney,+ regionalizeLegacyUsd,+ type RegionalMoney,+} from '../../shared/regionalMoney';export function useSessionSpend(sessionId: string | undefined,+ initialMoney: RegionalMoney | null | undefined,initialCostUsd: number | null | undefined,-): number | null {- const [costUsd, setCostUsd] = useState<number | null>(- typeof initialCostUsd === 'number' ? initialCostUsd : null,+): RegionalMoney | null {+ const initial =+ normalizeRegionalMoney(initialMoney) ??+ (typeof initialCostUsd === 'number'+ ? regionalizeLegacyUsd(initialCostUsd, CURRENT_CINDY_REGION)+ : null);+ const [money, setMoney] = useState<RegionalMoney | null>(+ initial,);// sessionId 切换时, 用新初始值复位 —— 否则会带着上一个 session 的累计串台useEffect(() => {- setCostUsd(typeof initialCostUsd === 'number' ? initialCostUsd : null);- }, [sessionId, initialCostUsd]);+ setMoney(+ normalizeRegionalMoney(initialMoney) ??+ (typeof initialCostUsd === 'number'+ ? regionalizeLegacyUsd(initialCostUsd, CURRENT_CINDY_REGION)+ : null),+ );+ }, [sessionId, initialMoney, initialCostUsd]);useEffect(() => {if (!sessionId) return;const unsubscribe = window.electronAPI.onUsageSessionSpendChanged((res) => {if (res.sessionId === sessionId) {- setCostUsd(res.totalCostUsd);+ setMoney(+ normalizeRegionalMoney(res.totalMoney) ??+ (typeof res.totalCostUsd === 'number'+ ? regionalizeLegacyUsd(+ res.totalCostUsd,+ CURRENT_CINDY_REGION,+ )+ : null),+ );}});return unsubscribe;}, [sessionId]);- return costUsd;+ return money;}diff --git a/apps/desktop/src/renderer/hooks/useTodaySpend.ts b/apps/desktop/src/renderer/hooks/useTodaySpend.tsindex 54d4e2a846..fe72e30d8e 100644--- a/apps/desktop/src/renderer/hooks/useTodaySpend.ts+++ b/apps/desktop/src/renderer/hooks/useTodaySpend.ts@@ -15,10 +15,16 @@*/import { useEffect, useState } from 'react';+import { CURRENT_CINDY_REGION } from '../../shared/brandRegion';+import {+ normalizeRegionalMoney,+ regionalizeLegacyUsd,+ type RegionalMoney,+} from '../../shared/regionalMoney';export interface TodaySpendData {day: string;- costUsd: number | null;+ money: RegionalMoney | null;codexTokens: number | null;}@@ -33,7 +39,7 @@ function localDayKey(): string {export function useTodaySpend(): TodaySpendData {const [data, setData] = useState<TodaySpendData>({day: localDayKey(),- costUsd: null,+ money: null,codexTokens: null,});@@ -45,9 +51,17 @@ export function useTodaySpend(): TodaySpendData {void window.electronAPI.maker.usage.getToday('claude-code').then((res) => {if (cancelled) return;currentDay = res.day;+ const money =+ normalizeRegionalMoney(res.money) ??+ (typeof res.costUsd === 'number'+ ? regionalizeLegacyUsd(+ res.costUsd,+ CURRENT_CINDY_REGION,+ )+ : null);setData((prev) => ({day: res.day,- costUsd: res.costUsd ?? prev.costUsd,+ money: money ?? prev.money,codexTokens: prev.codexTokens,}));});@@ -73,9 +87,17 @@ export function useTodaySpend(): TodaySpendData {// 只接受"今天"的更新(防御 main 在跨日缝隙推的延迟数据)if (res.day === localDayKey()) {currentDay = res.day;+ const money =+ normalizeRegionalMoney(res.money) ??+ (typeof res.costUsd === 'number'+ ? regionalizeLegacyUsd(+ res.costUsd,+ CURRENT_CINDY_REGION,+ )+ : null);setData((prev) => ({day: res.day,- costUsd: res.costUsd,+ money,codexTokens: prev.codexTokens,}));}diff --git a/apps/desktop/src/renderer/hooks/useUsageHistory.ts b/apps/desktop/src/renderer/hooks/useUsageHistory.tsindex 8f063ea43f..714b2880a6 100644--- a/apps/desktop/src/renderer/hooks/useUsageHistory.ts+++ b/apps/desktop/src/renderer/hooks/useUsageHistory.ts@@ -21,12 +21,22 @@*/import { useEffect, useState } from 'react';+import { CURRENT_CINDY_REGION } from '../../shared/brandRegion';+import {+ addCompatibleRegionalMoney,+ normalizeRegionalMoney,+ regionalCurrencyForRegion,+ regionalizeLegacyUsd,+ regionalizeUsd,+ type RegionalMoney,+ zeroRegionalMoney,+} from '../../shared/regionalMoney';export interface UsageHistoryModel {agentKind: 'claude-code' | 'codex';model: string;- costUsd: number;- estimatedCostUsd: number | null;+ money: RegionalMoney;+ estimatedMoney: RegionalMoney | null;inputTokens: number;outputTokens: number;cacheReadTokens: number;@@ -38,9 +48,9 @@ export interface UsageHistoryModelDay {day: string;agentKind: 'claude-code' | 'codex';model: string;- amountUsd: number;- apiCostUsd: number;- subscriptionEstimateUsd: number;+ money: RegionalMoney;+ apiMoney: RegionalMoney;+ subscriptionEstimateMoney: RegionalMoney;tokens: number;}@@ -50,20 +60,20 @@ export interface UsageHistoryPayload {stale?: boolean;estimatesPending?: boolean;/** tokens: 当日合计 (旧快照可能缺该字段, 消费端用 ?? 0 兜底)。 */- days: Array<{ day: string; costUsd: number; tokens?: number }>;+ days: Array<{ day: string; money: RegionalMoney; tokens?: number }>;/** 近 30 天每日 × 模型明细 (旧快照缺该字段时补 [])。 */modelDaily: UsageHistoryModelDay[];models: UsageHistoryModel[];streak: { current: number; longest: number };totals: {- today: number;- last30Days: number;- last30DaysWithEstimatedValue: number;- last30DaysEstimatedValue: number;+ today: RegionalMoney;+ last30Days: RegionalMoney;+ last30DaysWithEstimatedValue: RegionalMoney;+ last30DaysEstimatedValue: RegionalMoney;todayTokens: number;last30DaysTokens: number;};- anomaly: { isAnomalous: boolean; trailing7DayAvg: number | null };+ anomaly: { isAnomalous: boolean; trailing7DayAvg: RegionalMoney | null };}/** 热力图窗口: 20 周 = 140 天。 */@@ -80,38 +90,192 @@ function storageKeyForScope(scopeKey: string): string {return `${SNAPSHOT_STORAGE_KEY}.${encodeURIComponent(scopeKey)}`;}+interface StoredUsageHistoryDay {+ day?: unknown;+ money?: unknown;+ costUsd?: unknown;+ tokens?: unknown;+}++interface StoredUsageHistoryModelDay {+ day?: unknown;+ agentKind?: unknown;+ model?: unknown;+ money?: unknown;+ amountUsd?: unknown;+ apiMoney?: unknown;+ apiCostUsd?: unknown;+ subscriptionEstimateMoney?: unknown;+ subscriptionEstimateUsd?: unknown;+ tokens?: unknown;+}++interface StoredUsageHistoryModel {+ agentKind?: unknown;+ model?: unknown;+ money?: unknown;+ costUsd?: unknown;+ estimatedMoney?: unknown;+ estimatedCostUsd?: unknown;+ inputTokens?: unknown;+ outputTokens?: unknown;+ cacheReadTokens?: unknown;+ cacheCreateTokens?: unknown;+}++interface StoredUsageHistoryPayload {+ generatedAt?: unknown;+ todayKey?: unknown;+ stale?: unknown;+ estimatesPending?: unknown;+ days?: unknown;+ modelDaily?: unknown;+ models?: unknown;+ streak?: unknown;+ totals?: unknown;+ anomaly?: unknown;+}++function finiteNumber(value: unknown, fallback = 0): number {+ return typeof value === 'number' && Number.isFinite(value) ? value : fallback;+}++function isAgentKind(value: unknown): value is UsageHistoryModel['agentKind'] {+ return value === 'claude-code' || value === 'codex';+}+function readSnapshot(scopeKey: string): UsageHistoryPayload | null {try {const raw = localStorage.getItem(storageKeyForScope(scopeKey));if (!raw) return null;- const parsed = JSON.parse(raw) as UsageHistoryPayload;+ const parsed = JSON.parse(raw) as StoredUsageHistoryPayload;// 最小结构校验 — 大结构对不上才丢弃; 旧版快照缺 token 字段时补 0 继续用,// 避免升级后首启空一帧 (首帧照常渲染, ~200ms 后真实数据静默覆盖)。if (!Array.isArray(parsed.days) || !Array.isArray(parsed.models)) return null;- if (!parsed.totals || !parsed.streak || !parsed.anomaly) return null;- if (typeof parsed.stale !== 'boolean') parsed.stale = false;- if (typeof parsed.estimatesPending !== 'boolean') parsed.estimatesPending = false;- if (typeof parsed.totals.last30DaysWithEstimatedValue !== 'number') {- parsed.totals.last30DaysWithEstimatedValue = parsed.totals.last30Days;- }- if (typeof parsed.totals.last30DaysEstimatedValue !== 'number') {- parsed.totals.last30DaysEstimatedValue = Math.max(- 0,- parsed.totals.last30DaysWithEstimatedValue - parsed.totals.last30Days,- );- }- if (typeof parsed.totals.todayTokens !== 'number') parsed.totals.todayTokens = 0;- if (typeof parsed.totals.last30DaysTokens !== 'number') parsed.totals.last30DaysTokens = 0;- if (!Array.isArray(parsed.modelDaily)) parsed.modelDaily = [];- for (const row of parsed.modelDaily) {- if (typeof row.apiCostUsd !== 'number') {- row.apiCostUsd = row.agentKind === 'codex' ? 0 : row.amountUsd;- }- if (typeof row.subscriptionEstimateUsd !== 'number') {- row.subscriptionEstimateUsd = row.agentKind === 'codex' ? row.amountUsd : 0;- }+ if (+ !parsed.totals ||+ typeof parsed.totals !== 'object' ||+ Array.isArray(parsed.totals) ||+ !parsed.streak ||+ typeof parsed.streak !== 'object' ||+ Array.isArray(parsed.streak) ||+ !parsed.anomaly ||+ typeof parsed.anomaly !== 'object' ||+ Array.isArray(parsed.anomaly)+ ) {+ return null;}- return parsed;+ const totals = parsed.totals as Record<string, unknown>;+ const streak = parsed.streak as Record<string, unknown>;+ 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);+ 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');++ const days = (parsed.days as StoredUsageHistoryDay[])+ .filter((row) => typeof row?.day === 'string')+ .map((row) => ({+ day: row.day as string,+ money: normalizeRegionalMoney(row.money) ?? legacyActual(row.costUsd),+ tokens: finiteNumber(row.tokens),+ }));+ const modelDaily = (Array.isArray(parsed.modelDaily) ? parsed.modelDaily : [])+ .filter(+ (row: StoredUsageHistoryModelDay) =>+ typeof row?.day === 'string' &&+ typeof row.model === 'string' &&+ isAgentKind(row.agentKind),+ )+ .map((row: StoredUsageHistoryModelDay): UsageHistoryModelDay => ({+ day: row.day as string,+ agentKind: row.agentKind as UsageHistoryModelDay['agentKind'],+ model: row.model as string,+ money:+ normalizeRegionalMoney(row.money) ??+ (row.agentKind === 'codex'+ ? legacyEstimate(row.amountUsd)+ : legacyActual(row.amountUsd)),+ apiMoney: normalizeRegionalMoney(row.apiMoney) ?? legacyActual(row.apiCostUsd),+ subscriptionEstimateMoney:+ normalizeRegionalMoney(row.subscriptionEstimateMoney) ??+ legacyEstimate(row.subscriptionEstimateUsd),+ tokens: finiteNumber(row.tokens),+ }));+ const models = (parsed.models as StoredUsageHistoryModel[])+ .filter(+ (row) =>+ typeof row?.model === 'string' &&+ isAgentKind(row.agentKind),+ )+ .map((row): UsageHistoryModel => ({+ agentKind: row.agentKind as UsageHistoryModel['agentKind'],+ model: row.model as string,+ money: normalizeRegionalMoney(row.money) ?? legacyActual(row.costUsd),+ estimatedMoney:+ normalizeRegionalMoney(row.estimatedMoney) ??+ (typeof row.estimatedCostUsd === 'number'+ ? legacyEstimate(row.estimatedCostUsd)+ : null),+ inputTokens: finiteNumber(row.inputTokens),+ outputTokens: finiteNumber(row.outputTokens),+ cacheReadTokens: finiteNumber(row.cacheReadTokens),+ cacheCreateTokens: finiteNumber(row.cacheCreateTokens),+ }));+ const today = normalizeRegionalMoney(totals.today) ?? legacyActual(totals.today);+ const last30Days =+ normalizeRegionalMoney(totals.last30Days) ?? legacyActual(totals.last30Days);+ const last30DaysEstimatedValue =+ normalizeRegionalMoney(totals.last30DaysEstimatedValue) ??+ legacyEstimate(totals.last30DaysEstimatedValue);+ const last30DaysWithEstimatedValue =+ normalizeRegionalMoney(totals.last30DaysWithEstimatedValue) ??+ (last30DaysEstimatedValue.amount > 0+ ? (addCompatibleRegionalMoney(+ [last30Days, last30DaysEstimatedValue],+ regionalCurrencyForRegion(CURRENT_CINDY_REGION),+ ) ?? last30Days)+ : last30Days);+ const trailing7DayAvg =+ anomaly.trailing7DayAvg === null+ ? null+ : normalizeRegionalMoney(anomaly.trailing7DayAvg) ??+ legacyActual(anomaly.trailing7DayAvg);++ return {+ generatedAt: finiteNumber(parsed.generatedAt, Date.now()),+ todayKey: typeof parsed.todayKey === 'string' ? parsed.todayKey : '',+ stale: parsed.stale === true,+ estimatesPending: parsed.estimatesPending === true,+ days,+ modelDaily,+ models,+ streak: {+ current: finiteNumber(streak.current),+ longest: finiteNumber(streak.longest),+ },+ totals: {+ today,+ last30Days,+ last30DaysWithEstimatedValue,+ last30DaysEstimatedValue,+ todayTokens: finiteNumber(totals.todayTokens),+ last30DaysTokens: finiteNumber(totals.last30DaysTokens),+ },+ anomaly: {+ isAnomalous: anomaly.isAnomalous === true,+ trailing7DayAvg,+ },+ };} catch {return null;}@@ -309,6 +473,7 @@ export function useUsageHistory(opts?: { paused?: boolean; userId?: string | nul};const offSpend = window.electronAPI.maker.usage.onTodaySpendChanged(scheduleRefresh);const offTokens = window.electronAPI.maker.usage.onTodayTokensChanged(scheduleRefresh);+ const offPricing = window.electronAPI.maker.usage.onModelPricingChanged(scheduleRefresh);return () => {activeScope.listeners.delete(setScopedHistory);@@ -317,6 +482,7 @@ export function useUsageHistory(opts?: { paused?: boolean; userId?: string | nulif (timer) clearTimeout(timer);offSpend();offTokens();+ offPricing();};}, [paused, scopeKey]);diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 2e33bf760c..ea1163df56 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -3669,6 +3669,16 @@"edit": "Edit","options": "Options","priceTip": "Input {{input}} · Output {{output}} per 1M tokens",+ "pricing": {+ "title": "Per 1M tokens",+ "input": "Input",+ "output": "Output",+ "cacheRead": "Cache read",+ "cacheCreate": "Cache write",+ "perMillion": "Standard model pricing",+ "fixedFx": "Estimated at the fixed rate of 1 USD = 6.7 CNY",+ "subscriptionEstimate": "Value estimate, not an actual bill"+ },"trigger": {"placeholder": "Select model","aria": "Select model. Current: {{model}}",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 401b781aa5..c9c3d075f8 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -3668,6 +3668,16 @@"edit": "編集","options": "オプション","priceTip": "入力 {{input}} · 出力 {{output}} / 100万トークン",+ "pricing": {+ "title": "100万トークンあたり",+ "input": "入力",+ "output": "出力",+ "cacheRead": "キャッシュ読み取り",+ "cacheCreate": "キャッシュ書き込み",+ "perMillion": "モデル標準価格",+ "fixedFx": "固定レート 1 USD = 6.7 CNY による概算",+ "subscriptionEstimate": "価値の推定であり、実際の請求額ではありません"+ },"trigger": {"placeholder": "モデルを選択","aria": "モデルを選択。現在:{{model}}",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex db206e20cf..7918203de5 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -3668,6 +3668,16 @@"edit": "편집","options": "옵션","priceTip": "입력 {{input}} · 출력 {{output}} / 100만 토큰",+ "pricing": {+ "title": "100만 토큰당",+ "input": "입력",+ "output": "출력",+ "cacheRead": "캐시 읽기",+ "cacheCreate": "캐시 쓰기",+ "perMillion": "모델 표준 가격",+ "fixedFx": "고정 환율 1 USD = 6.7 CNY 기준 추정",+ "subscriptionEstimate": "가치 추정치이며 실제 청구 금액이 아닙니다"+ },"trigger": {"placeholder": "모델 선택","aria": "모델 선택. 현재: {{model}}",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 0db4520e37..345d573430 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -3668,6 +3668,16 @@"edit": "编辑","options": "选项","priceTip": "输入 {{input}} · 输出 {{output}} / 百万 token",+ "pricing": {+ "title": "每百万 token",+ "input": "输入",+ "output": "输出",+ "cacheRead": "缓存读取",+ "cacheCreate": "缓存写入",+ "perMillion": "模型标准价格",+ "fixedFx": "按固定汇率 1 USD = 6.7 CNY 约算",+ "subscriptionEstimate": "价值估算,不代表实际账单"+ },"trigger": {"placeholder": "选择模型","aria": "选择模型。当前:{{model}}",diff --git a/apps/desktop/src/renderer/lib/__tests__/modelPriceFormat.test.ts b/apps/desktop/src/renderer/lib/__tests__/modelPriceFormat.test.tsnew file mode 100644index 0000000000..4ff062307e--- /dev/null+++ b/apps/desktop/src/renderer/lib/__tests__/modelPriceFormat.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from 'vitest';++import type { ModelPriceQuote } from '../../../shared/regionalMoney';+import {+ formatModelPricePair,+ modelPriceDetailRows,+} from '../modelPriceFormat';++function quote(overrides: Partial<ModelPriceQuote> = {}): ModelPriceQuote {+ return {+ providerId: 'xd',+ modelId: 'claude-sonnet-4',+ currency: 'CNY',+ source: 'gateway',+ approximate: false,+ inputPerMtok: 3,+ outputPerMtok: 15,+ ...overrides,+ };+}++describe('modelPriceFormat', () => {+ it('formats gateway CNY input/output as a compact pair', () => {+ expect(formatModelPricePair(quote())).toBe('¥3 / ¥15');+ });++ it('adds the approximate marker only once', () => {+ expect(+ formatModelPricePair(+ quote({+ source: 'subscription-reference',+ approximate: true,+ inputPerMtok: 20.1,+ outputPerMtok: 100.5,+ }),+ ),+ ).toBe('≈¥20.1 / ¥100.5');+ });++ it('includes configured cache prices in details', () => {+ expect(+ modelPriceDetailRows(+ quote({ cacheReadPerMtok: 0.3, cacheCreatePerMtok: 3.75 }),+ ),+ ).toEqual([+ { kind: 'input', value: '¥3' },+ { kind: 'output', value: '¥15' },+ { kind: 'cacheRead', value: '¥0.3' },+ { kind: 'cacheCreate', value: '¥3.75' },+ ]);+ });+});diff --git a/apps/desktop/src/renderer/lib/__tests__/turnUsageTooltip.test.ts b/apps/desktop/src/renderer/lib/__tests__/turnUsageTooltip.test.tsindex 4daa3d91d1..5ea43eabeb 100644--- a/apps/desktop/src/renderer/lib/__tests__/turnUsageTooltip.test.ts+++ b/apps/desktop/src/renderer/lib/__tests__/turnUsageTooltip.test.ts@@ -38,7 +38,10 @@ describe('formatModelShort', () => {});describe('buildTurnUsageTooltipLines — 按模型成本明细', () => {- function lines(perModelCost?: Array<{ model: string; costUsd: number }>, costUsd = 1.74): string[] {+ function lines(+ perModelCost?: Array<{ model: string; costUsd: number }>,+ costUsd = 1.74,+ ): string[] {const details = buildTurnUsageDetails({inputTokens: 133,outputTokens: 9_899,@@ -56,8 +59,22 @@ describe('buildTurnUsageTooltipLines — 按模型成本明细', () => {{ model: 'claude-haiku-4-5-20251001', costUsd: 0.8 },]);expect(out).toContain('usageDetails.costBreakdownHeader');- expect(out.some((l) => l.startsWith('usageDetails.modelCostLine') && l.includes('Opus 4.8') && l.includes('$0.94'))).toBe(true);- expect(out.some((l) => l.startsWith('usageDetails.modelCostLine') && l.includes('Haiku 4.5') && l.includes('$0.80'))).toBe(true);+ expect(+ out.some(+ (l) =>+ l.startsWith('usageDetails.modelCostLine') &&+ l.includes('Opus 4.8') &&+ l.includes('≈¥6.30'),+ ),+ ).toBe(true);+ expect(+ out.some(+ (l) =>+ l.startsWith('usageDetails.modelCostLine') &&+ l.includes('Haiku 4.5') &&+ l.includes('≈¥5.36'),+ ),+ ).toBe(true);expect(out.some((l) => l.startsWith('usageDetails.modelLine'))).toBe(false);});@@ -81,8 +98,9 @@ describe('buildTurnUsageTooltipLines — 建议行 (只在真正有价值时出cacheCreateTokens?: number;}): string[] {const details = buildTurnUsageDetails({ outputTokens: 100, ...tokens })!;- return buildTurnUsageTooltipLines({ details, t, costUsd: 1 })- .filter((l) => l.startsWith('usageDetails.suggestionLine'));+ return buildTurnUsageTooltipLines({ details, t, costUsd: 1 }).filter((l) =>+ l.startsWith('usageDetails.suggestionLine'),+ );}it('总量大但缓存命中率高 (健康长会话) → 无建议', () => {@@ -126,8 +144,26 @@ describe('normalizeTurnUsageDetails — perModelCost 往返 / 清洗', () => {],});expect(d!.perModelCost).toEqual([- { model: 'claude-opus-4-8', costUsd: 0.94 },- { model: 'claude-haiku-4-5', costUsd: 0.8 },+ {+ model: 'claude-opus-4-8',+ money: {+ amount: expect.closeTo(6.298, 10),+ currency: 'CNY',+ approximate: true,+ kind: 'actual-cost',+ estimateReasons: ['fixed-fx', 'legacy-usd'],+ },+ },+ {+ model: 'claude-haiku-4-5',+ money: {+ amount: expect.closeTo(5.36, 10),+ currency: 'CNY',+ approximate: true,+ kind: 'actual-cost',+ estimateReasons: ['fixed-fx', 'legacy-usd'],+ },+ },]);});@@ -140,7 +176,18 @@ describe('normalizeTurnUsageDetails — perModelCost 往返 / 清洗', () => {{ model: 'claude-opus-4-8', costUsd: 0.4 },],});- expect(d!.perModelCost).toEqual([{ model: 'claude-opus-4-8', costUsd: 0.9 }]);+ expect(d!.perModelCost).toEqual([+ {+ model: 'claude-opus-4-8',+ money: {+ amount: expect.closeTo(6.03, 10),+ currency: 'CNY',+ approximate: true,+ kind: 'actual-cost',+ estimateReasons: ['fixed-fx', 'legacy-usd'],+ },+ },+ ]);});it('缺 perModelCost 字段 → undefined, 其它明细仍构建', () => {diff --git a/apps/desktop/src/renderer/lib/ccAgent.types.ts b/apps/desktop/src/renderer/lib/ccAgent.types.tsindex 4733d795f5..9b4aec11e3 100644--- a/apps/desktop/src/renderer/lib/ccAgent.types.ts+++ b/apps/desktop/src/renderer/lib/ccAgent.types.ts@@ -1,6 +1,7 @@import type { Effort, PermissionMode } from '@/lib/userPreferences.types';import type { SessionSource } from '../../shared/sessionSource';import type { TurnUsageDetails } from '../../shared/turnUsageDetails';+import type { RegionalMoney } from '../../shared/regionalMoney';export type SessionStatus = 'active' | 'archived' | 'deleted';export type WorkspaceKind = 'project' | 'dialogue';@@ -92,15 +93,14 @@ export interface CcMeta {*/hookSource?: { im: string; channelName?: string | null; userText?: string; threadContext?: Array<{ author: string; text: string; isBot?: boolean }> };- /**- * Per-turn 费用 (USD), main 在 turn 结束时 patch 到该轮最后一条 assistant 上- * (turnCostBroadcaster)。MessageActionBar 据此显示"本轮消耗"。- */+ /** 历史 per-turn USD;新数据以 turnCost 为区域金额事实。 */turnCostUsd?: number;+ turnCost?: RegionalMoney;/** true = Codex token × 价格表折算的估算值; false / 缺省 = SDK 实报。 */turnCostIsEstimate?: boolean;- /** 用户从最近一条真实输入至本消息的累计成本(用于展示,不参与账单汇总)。 */+ /** 历史用户轮累计 USD;新数据以 userTurnCost 为区域金额事实。 */userTurnCostUsd?: number;+ userTurnCost?: RegionalMoney;/** 累计值含订阅 token 价值估算时为 true。 */userTurnCostIsEstimate?: boolean;/** Per-turn token/cache 明细,与 turnCostUsd 同时由 main patch 到 agent_meta。 */@@ -191,6 +191,8 @@ export interface Session {sdkSessionId: string | null;totalTokenUsage: number;totalCostUsd: number;+ /** 新版区域累计金额;旧会话仍只带 totalCostUsd。 */+ totalMoney?: RegionalMoney;contextTokens: number;contextWindow: number;fastMode: boolean;diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex d5ed36c17e..c237c0b0fa 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -79,6 +79,12 @@ import {} from '@/lib/issueConfirmPayload';import { resolveStaleCodexSubscriptionValueEstimate } from '../../shared/codexSubscriptionValue';import { normalizeTurnUsageDetails, type TurnUsageDetails } from '../../shared/turnUsageDetails';+import { CURRENT_CINDY_REGION } from '../../shared/brandRegion';+import {+ normalizeRegionalMoney,+ regionalizeLegacyUsd,+ type RegionalMoney,+} from '../../shared/regionalMoney';import type { PersistedSessionReferenceMetadata } from '../../shared/sessionReferenceMetadata';import { isSessionUpgrading } from '@/state/ccMgrUpgradeStore';import { i18n } from '@/i18n';@@ -375,10 +381,12 @@ export interface ChatMessage {* 仅 assistant 消息可能有值;MessageActionBar 据此显示"本轮消耗"。*/turnCostUsd?: number;+ turnMoney?: RegionalMoney;/** true = 订阅模式下的 token 价值;false = API 账单 cost / API 单价折算 cost。 */turnCostIsEstimate?: boolean;/** 用户从最近一条真实输入至本消息的累计成本;只用于消息旁展示。 */userTurnCostUsd?: number;+ userTurnMoney?: RegionalMoney;userTurnCostIsEstimate?: boolean;/** 本轮 token/cache 明细;旧消息或未拿到 usage 时缺省。 */turnUsageDetails?: TurnUsageDetails;@@ -3519,37 +3527,61 @@ function initGlobalListeners(): void {const p = raw as {sessionId?: string;clientId?: string;+ turnMoney?: unknown;turnCostUsd?: number;turnCostIsEstimate?: boolean;+ userTurnMoney?: unknown;userTurnCostUsd?: number;userTurnCostIsEstimate?: boolean;turnUsageDetails?: unknown;} | null;if (!p?.sessionId || !p.clientId) return;- if (typeof p.turnCostUsd !== 'number' || !(p.turnCostUsd > 0)) return;- const { sessionId, clientId, turnCostUsd } = p;const turnCostIsEstimate = p.turnCostIsEstimate === true;+ const turnUsageDetails = normalizeTurnUsageDetails(p.turnUsageDetails);+ const normalizedTurnMoney = normalizeRegionalMoney(p.turnMoney);+ const legacyTurnCostUsd =+ typeof p.turnCostUsd === 'number' && p.turnCostUsd > 0+ ? resolveEstimatedTurnCostUsd(+ p.turnCostUsd,+ turnCostIsEstimate,+ turnUsageDetails,+ )+ : undefined;+ const turnMoney =+ normalizedTurnMoney ??+ (legacyTurnCostUsd !== undefined+ ? regionalizeLegacyUsd(legacyTurnCostUsd, CURRENT_CINDY_REGION)+ : 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)+ : undefined);const userTurnCostUsd =typeof p.userTurnCostUsd === 'number' && p.userTurnCostUsd > 0? p.userTurnCostUsd: undefined;- const turnUsageDetails = normalizeTurnUsageDetails(p.turnUsageDetails);- const resolvedTurnCostUsd = resolveEstimatedTurnCostUsd(- turnCostUsd,- turnCostIsEstimate,- turnUsageDetails,- );+ const resolvedTurnCostUsd =+ turnMoney.currency === 'USD'+ ? turnMoney.amount+ : undefined;setState(sessionId, (s) => {const idx = s.messages.findIndex((m) => m.clientId === clientId);if (idx < 0) return s;const msgs = s.messages.slice();msgs[idx] = {...msgs[idx],- turnCostUsd: resolvedTurnCostUsd,+ turnMoney,+ ...(resolvedTurnCostUsd !== undefined+ ? { turnCostUsd: resolvedTurnCostUsd }+ : {}),turnCostIsEstimate,- ...(userTurnCostUsd+ ...(userTurnMoney? {- userTurnCostUsd,+ userTurnMoney,+ ...(userTurnCostUsd ? { userTurnCostUsd } : {}),userTurnCostIsEstimate: p.userTurnCostIsEstimate === true,}: {}),@@ -3637,15 +3669,27 @@ function initGlobalListeners(): void {// 被控端 session 终身累计 cost 落库推送(sessionSpendBroadcaster 走裸 UPDATE、// 不发 sessions:patched)→ 镜像进远程项目分片;打开中的远程会话底部 $ chip 经// session.totalCostUsd → useSessionSpend 初值重置显示最新值。- const p = push.payload as { sessionId?: string; totalCostUsd?: number } | null;- // 跨设备 payload 防御:NaN / 负数不入镜像(否则 chip 显示 $NaN / 污染后续计算)。- if (- push.deviceId && p?.sessionId- && typeof p.totalCostUsd === 'number'- && Number.isFinite(p.totalCostUsd) && p.totalCostUsd >= 0- ) {+ const p = push.payload as {+ sessionId?: string;+ totalMoney?: unknown;+ totalCostUsd?: number;+ } | null;+ const totalMoney =+ normalizeRegionalMoney(p?.totalMoney) ??+ (typeof p?.totalCostUsd === 'number' &&+ Number.isFinite(p.totalCostUsd) &&+ p.totalCostUsd >= 0+ ? regionalizeLegacyUsd(+ p.totalCostUsd,+ CURRENT_CINDY_REGION,+ )+ : undefined);+ if (push.deviceId && p?.sessionId && totalMoney) {remoteProjectsStore.applyPatch(push.deviceId, p.sessionId, {- totalCostUsd: p.totalCostUsd,+ totalMoney,+ ...(typeof p.totalCostUsd === 'number'+ ? { totalCostUsd: p.totalCostUsd }+ : {}),});}break;@@ -7956,6 +8000,33 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {systemCardData: { kind: m.agentMeta.goalNotice },};}+ const agentMeta = m.agentMeta;+ const turnUsageDetails =+ m.role === 'assistant'+ ? normalizeTurnUsageDetails(agentMeta?.turnUsageDetails)+ : undefined;+ const normalizedTurnMoney =+ m.role === 'assistant'+ ? normalizeRegionalMoney(agentMeta?.turnCost)+ : undefined;+ const legacyTurnCostUsd =+ m.role === 'assistant' &&+ typeof agentMeta?.turnCostUsd === 'number' &&+ agentMeta.turnCostUsd > 0+ ? resolveEstimatedTurnCostUsd(+ agentMeta.turnCostUsd,+ agentMeta.turnCostIsEstimate === true,+ turnUsageDetails,+ agentMeta.model,+ )+ : undefined;+ const persistedTurnMoney =+ m.role === 'assistant'+ ? normalizedTurnMoney ??+ (legacyTurnCostUsd !== undefined+ ? regionalizeLegacyUsd(legacyTurnCostUsd, CURRENT_CINDY_REGION)+ : undefined)+ : undefined;return {clientId: m.clientId,role: m.role,@@ -7967,30 +8038,42 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {// SDK done turn seal:新数据用 turnCompleted;存量会话已有 turnCostUsd 的收尾// assistant 等价可推导,直接补投影让本修复对历史复现会话立即生效。...(m.role === 'assistant' && (- m.agentMeta?.turnCompleted === true ||- (typeof m.agentMeta?.turnCostUsd === 'number' && m.agentMeta.turnCostUsd > 0)+ agentMeta?.turnCompleted === true ||+ (persistedTurnMoney?.amount ?? 0) > 0)? { turnCompleted: true }: {}),// assistant 上挂的 per-turn 费用(main turn 结束时 patch 进 agent_meta)...(m.role === 'assistant' &&- typeof m.agentMeta?.turnCostUsd === 'number' &&- m.agentMeta.turnCostUsd > 0+ agentMeta &&+ persistedTurnMoney &&+ persistedTurnMoney.amount > 0? (() => {- const turnUsageDetails = normalizeTurnUsageDetails(m.agentMeta.turnUsageDetails);- const turnCostUsd = resolveEstimatedTurnCostUsd(- m.agentMeta.turnCostUsd,- m.agentMeta.turnCostIsEstimate === true,- turnUsageDetails,- m.agentMeta.model,- );+ const turnCostUsd =+ persistedTurnMoney.currency === 'USD'+ ? persistedTurnMoney.amount+ : undefined;+ const persistedUserTurnMoney =+ normalizeRegionalMoney(agentMeta.userTurnCost) ??+ (typeof agentMeta.userTurnCostUsd === 'number' &&+ agentMeta.userTurnCostUsd > 0+ ? regionalizeLegacyUsd(+ agentMeta.userTurnCostUsd,+ CURRENT_CINDY_REGION,+ )+ : undefined);return {- turnCostUsd,- turnCostIsEstimate: m.agentMeta.turnCostIsEstimate === true,- ...(typeof m.agentMeta.userTurnCostUsd === 'number' && m.agentMeta.userTurnCostUsd > 0+ turnMoney: persistedTurnMoney,+ ...(turnCostUsd !== undefined ? { turnCostUsd } : {}),+ turnCostIsEstimate: agentMeta.turnCostIsEstimate === true,+ ...(persistedUserTurnMoney? {- userTurnCostUsd: m.agentMeta.userTurnCostUsd,- userTurnCostIsEstimate: m.agentMeta.userTurnCostIsEstimate === true,+ userTurnMoney: persistedUserTurnMoney,+ ...(typeof agentMeta.userTurnCostUsd === 'number' &&+ agentMeta.userTurnCostUsd > 0+ ? { userTurnCostUsd: agentMeta.userTurnCostUsd }+ : {}),+ userTurnCostIsEstimate: agentMeta.userTurnCostIsEstimate === true,}: {}),...(turnUsageDetails ? { turnUsageDetails } : {}),@@ -8048,15 +8131,24 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {/*** Device-link can load history from a peer that predates persisted- * userTurnCostUsd. Rebuild only those missing display totals from the ordered+ * userTurnCost. Rebuild only those missing display totals from the ordered* rows returned by that peer; raw per-segment values remain untouched.*/function projectLegacyUserTurnCosts(serverMsgs: Message[],-): Map<string, Pick<ChatMessage, 'userTurnCostUsd' | 'userTurnCostIsEstimate'>> {+): Map<+ string,+ Pick<+ ChatMessage,+ 'userTurnMoney' | 'userTurnCostUsd' | 'userTurnCostIsEstimate'+ >+> {const projected = new Map<string,- Pick<ChatMessage, 'userTurnCostUsd' | 'userTurnCostIsEstimate'>+ Pick<+ ChatMessage,+ 'userTurnMoney' | 'userTurnCostUsd' | 'userTurnCostIsEstimate'+ >>();let hasRealUserBoundary = false;let costUsd = 0;@@ -8079,8 +8171,12 @@ function projectLegacyUserTurnCosts(}costUsd += meta.turnCostUsd;hasEstimatedValue ||= meta.turnCostIsEstimate === true;- if (typeof meta.userTurnCostUsd !== 'number' || !(meta.userTurnCostUsd > 0)) {+ if (+ !normalizeRegionalMoney(meta.userTurnCost) &&+ (typeof meta.userTurnCostUsd !== 'number' || !(meta.userTurnCostUsd > 0))+ ) {projected.set(message.clientId, {+ userTurnMoney: regionalizeLegacyUsd(costUsd, CURRENT_CINDY_REGION),userTurnCostUsd: costUsd,userTurnCostIsEstimate: hasEstimatedValue,});diff --git a/apps/desktop/src/renderer/lib/makerTransport.ts b/apps/desktop/src/renderer/lib/makerTransport.tsindex f20401b339..d2a26c1756 100644--- a/apps/desktop/src/renderer/lib/makerTransport.ts+++ b/apps/desktop/src/renderer/lib/makerTransport.ts@@ -199,14 +199,20 @@ export function listMessagesFor(* 后退化为只显示已加载消息 + 实时推送的部分值。*/export function estimatedSessionValueFor(sessionId: string): Promise<{- totalValueUsd: number;- entries: Array<{ clientId: string; costUsd: number }>;+ totalValueMoney?: import('../../shared/regionalMoney').RegionalMoney | null;+ totalValueUsd?: number;+ entries: Array<{+ clientId: string;+ money?: import('../../shared/regionalMoney').RegionalMoney;+ costUsd?: number;+ turnUsageDetails?: unknown;+ }>;}> {const deviceId = getStickySessionDeviceId(sessionId);if (!deviceId) return messageService.estimatedSessionValue(sessionId);return invokeRemote(deviceId, 'local-db:messages:estimatedSessionValue', [sessionId,- ]) as Promise<{ totalValueUsd: number; entries: Array<{ clientId: string; costUsd: number }> }>;+ ]) as ReturnType<typeof estimatedSessionValueFor>;}/** 会话内搜索跳转定位:远程走隧道 local-db:messages:around(否则查控制端空库,跳转必失败)。 */diff --git a/apps/desktop/src/renderer/lib/messageService.ts b/apps/desktop/src/renderer/lib/messageService.tsindex 5fabaf21b7..a89dcebc90 100644--- a/apps/desktop/src/renderer/lib/messageService.ts+++ b/apps/desktop/src/renderer/lib/messageService.ts@@ -7,6 +7,7 @@import type { AgentMeta, Message, MessageRole } from '@/lib/ccAgent.types';import { ApiError } from '@/lib/httpClient';import { extractIpcError } from '@/utils/ipcError';+import type { RegionalMoney } from '../../shared/regionalMoney';function wrap<T>(p: Promise<T>): Promise<T> {return p.catch((err: unknown) => {@@ -31,8 +32,14 @@ export async function list(export async function estimatedSessionValue(sessionId: string,): Promise<{- totalValueUsd: number;- entries: Array<{ clientId: string; costUsd: number }>;+ totalValueMoney?: RegionalMoney | null;+ totalValueUsd?: number;+ entries: Array<{+ clientId: string;+ money?: RegionalMoney;+ costUsd?: number;+ turnUsageDetails?: unknown;+ }>;}> {return wrap(window.electronAPI.localDb.messages.estimatedSessionValue(sessionId));}diff --git a/apps/desktop/src/renderer/lib/modelPriceFormat.ts b/apps/desktop/src/renderer/lib/modelPriceFormat.tsnew file mode 100644index 0000000000..5a0d2e6a9d--- /dev/null+++ b/apps/desktop/src/renderer/lib/modelPriceFormat.ts@@ -0,0 +1,64 @@+import type {+ ModelPriceQuote,+ MoneyCurrency,+} from '../../shared/regionalMoney';++function compactNumber(value: number): string {+ return new Intl.NumberFormat('en-US', {+ maximumFractionDigits: value > 0 && value < 0.01 ? 4 : 2,+ useGrouping: false,+ }).format(value);+}++export function formatModelPriceAmount(+ amount: number,+ currency: MoneyCurrency,+): string {+ return `${currency === 'CNY' ? '¥' : '$'}${compactNumber(amount)}`;+}++export function formatModelPricePair(quote: ModelPriceQuote): string {+ const input = formatModelPriceAmount(quote.inputPerMtok, quote.currency);+ const output = formatModelPriceAmount(quote.outputPerMtok, quote.currency);+ return `${quote.approximate ? '≈' : ''}${input} / ${output}`;+}++export function modelPriceDetailRows(+ quote: ModelPriceQuote,+): Array<{+ kind: 'input' | 'output' | 'cacheRead' | 'cacheCreate';+ value: string;+}> {+ return [+ {+ kind: 'input' as const,+ value: formatModelPriceAmount(quote.inputPerMtok, quote.currency),+ },+ {+ kind: 'output' as const,+ value: formatModelPriceAmount(quote.outputPerMtok, quote.currency),+ },+ ...(quote.cacheReadPerMtok === undefined+ ? []+ : [+ {+ kind: 'cacheRead' as const,+ value: formatModelPriceAmount(+ quote.cacheReadPerMtok,+ quote.currency,+ ),+ },+ ]),+ ...(quote.cacheCreatePerMtok === undefined+ ? []+ : [+ {+ kind: 'cacheCreate' as const,+ value: formatModelPriceAmount(+ quote.cacheCreatePerMtok,+ quote.currency,+ ),+ },+ ]),+ ];+}diff --git a/apps/desktop/src/renderer/lib/sessionsStore.ts b/apps/desktop/src/renderer/lib/sessionsStore.tsindex dedca70c04..ee177382ba 100644--- a/apps/desktop/src/renderer/lib/sessionsStore.ts+++ b/apps/desktop/src/renderer/lib/sessionsStore.ts@@ -285,9 +285,14 @@ if (typeof window !== 'undefined') {void sessionsStore.forceRefreshAll();});- window.electronAPI?.onUsageSessionSpendChanged?.(({ sessionId, totalCostUsd }) => {- sessionsStore.patchLocal(sessionId, { totalCostUsd });- });+ window.electronAPI?.onUsageSessionSpendChanged?.(+ ({ sessionId, totalMoney, totalCostUsd }) => {+ sessionsStore.patchLocal(sessionId, {+ ...(totalMoney ? { totalMoney } : {}),+ ...(typeof totalCostUsd === 'number' ? { totalCostUsd } : {}),+ });+ },+ );const sessionsPush = window.electronAPI?.localDb?.sessionsPush;if (sessionsPush) {diff --git a/apps/desktop/src/renderer/lib/turnUsageTooltip.ts b/apps/desktop/src/renderer/lib/turnUsageTooltip.tsindex 3862be68ba..264e8183b4 100644--- a/apps/desktop/src/renderer/lib/turnUsageTooltip.ts+++ b/apps/desktop/src/renderer/lib/turnUsageTooltip.ts@@ -1,11 +1,19 @@import type { TFunction } from 'i18next';import type { TurnUsageDetails } from '../../shared/turnUsageDetails';-import { formatCompactTokens, formatModelShort, formatTurnCostUsd } from '@/lib/usageFormat';+import type { RegionalMoney } from '../../shared/regionalMoney';+import {+ formatCompactTokens,+ formatModelShort,+ formatTurnCostMoney,+ formatTurnCostUsd,+} from '@/lib/usageFormat';export interface TurnUsageTooltipInput {details: TurnUsageDetails;t: TFunction;+ money?: RegionalMoney;+ /** 旧消息兼容;新链路使用 money。 */costUsd?: number;isEstimate?: boolean;title?: string;@@ -54,15 +62,21 @@ function suggestion(details: TurnUsageDetails, t: TFunction): string | null {export function buildTurnUsageTooltipLines({details,t,+ money,costUsd,isEstimate = false,title,}: TurnUsageTooltipInput): string[] {const lines: string[] = [];if (title) lines.push(title);- if (typeof costUsd === 'number' && Number.isFinite(costUsd) && costUsd > 0) {+ const formattedCost = money && money.amount > 0+ ? formatTurnCostMoney(money)+ : typeof costUsd === 'number' && Number.isFinite(costUsd) && costUsd > 0+ ? formatTurnCostUsd(costUsd)+ : null;+ if (formattedCost) {lines.push(t(isEstimate ? 'usageDetails.valueLine' : 'usageDetails.costLine', {- cost: formatTurnCostUsd(costUsd),+ cost: formattedCost,}));}// 按模型成本明细: 仅在 ≥2 个模型时展开 (单模型已由下方 modelLine 表达)。@@ -74,7 +88,7 @@ export function buildTurnUsageTooltipLines({for (const m of perModelCost) {lines.push(t('usageDetails.modelCostLine', {model: formatModelShort(m.model),- cost: formatTurnCostUsd(m.costUsd),+ cost: formatTurnCostMoney(m.money),}));}}diff --git a/apps/desktop/src/renderer/lib/usageFormat.ts b/apps/desktop/src/renderer/lib/usageFormat.tsindex c633b10fea..6f53ddb09f 100644--- a/apps/desktop/src/renderer/lib/usageFormat.ts+++ b/apps/desktop/src/renderer/lib/usageFormat.ts@@ -4,6 +4,8 @@* 保证两处金额口径 / 文案形态一致。*/+import type { RegionalMoney } from '../../shared/regionalMoney';+/*** 软日限额系数: 月度配额 / 30 * 4.5 = 月度配额 * 0.15。* 给重度使用的"忙日"留 buffer (即把月配额视作可在 1/4.5 ≈ 6.67 个高强度日内集中消耗)。@@ -34,6 +36,36 @@ export function formatTurnCostUsd(n: number): string {return '<$0.01';}+function moneyPrefix(money: RegionalMoney): string {+ return `${money.approximate ? '≈' : ''}${money.currency === 'CNY' ? '¥' : '$'}`;+}++/** 区域金额的紧凑展示;币种与约值语义来自金额本身。 */+export function formatCompactMoney(money: RegionalMoney): string {+ const prefix = moneyPrefix(money);+ if (money.amount >= 1000) return `${prefix}${(money.amount / 1000).toFixed(1)}k`;+ return `${prefix}${Math.round(money.amount)}`;+}++/** 区域金额的常规展示。 */+export function formatMoney(money: RegionalMoney): string {+ if (money.amount < 10) return `${moneyPrefix(money)}${money.amount.toFixed(2)}`;+ return formatCompactMoney(money);+}++/** 每轮 / 每模型金额:固定两位;小于最小货币展示单位时显示下界。 */+export function formatTurnCostMoney(money: RegionalMoney): string {+ const symbol = money.currency === 'CNY' ? '¥' : '$';+ const approximate = money.approximate ? '≈' : '';+ if (money.amount === 0) {+ return `${approximate}${symbol}0.00`;+ }+ if (money.amount >= 0.01) {+ return `${approximate}${symbol}${money.amount.toFixed(2)}`;+ }+ return `${approximate}<${symbol}0.01`;+}+/*** 把 SDK / 网关 model id 收成简短可读标签, 供 tooltip「按模型成本明细」展示。* 依次剥掉 SDK 路由后缀 `[..]`、尾部日期 `-YYYYMMDD`、`codex/` 预算前缀, 再美化家族名。diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 2380ae6438..6c63a300be 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -2911,7 +2911,11 @@ interface ElectronAPI {// ── session 级"终身累计 cost"变化 (per-session, 不是 today-aggregate) ──// today aggregate 已搬到 electronAPI.maker.usage.* (Claude USD + Codex token 统一)。onUsageSessionSpendChanged: (- cb: (data: { sessionId: string; totalCostUsd: number }) => void,+ cb: (data: {+ sessionId: string;+ totalMoney: import('../shared/regionalMoney').RegionalMoney;+ totalCostUsd?: number;+ }) => void,) => () => void;onUsageSessionTokensChanged: (cb: (data: { sessionId: string; totalTokens: number }) => void,@@ -2922,9 +2926,11 @@ interface ElectronAPI {cb: (data: {sessionId: string;clientId: string;- turnCostUsd: number;+ turnMoney: import('../shared/regionalMoney').RegionalMoney;+ turnCostUsd?: number;turnCostIsEstimate: boolean;- userTurnCostUsd: number;+ userTurnMoney: import('../shared/regionalMoney').RegionalMoney;+ userTurnCostUsd?: number;userTurnCostIsEstimate: boolean;turnUsageDetails?: import('../shared/turnUsageDetails').TurnUsageDetails;}) => void,@@ -3195,8 +3201,14 @@ interface ElectronAPI {estimatedSessionValue: (sessionId: string,) => Promise<{- totalValueUsd: number;- entries: Array<{ clientId: string; costUsd: number }>;+ totalValueMoney?: import('../shared/regionalMoney').RegionalMoney | null;+ totalValueUsd?: number;+ entries: Array<{+ clientId: string;+ money?: import('../shared/regionalMoney').RegionalMoney;+ costUsd?: number;+ turnUsageDetails?: unknown;+ }>;}>;around: (sessionId: string,@@ -4118,6 +4130,7 @@ interface ElectronAPI {usage: {getToday: (agentKind: 'claude-code' | 'codex') => Promise<{day: string;+ money?: import('../shared/regionalMoney').RegionalMoney;costUsd?: number;totalTokens?: number;promptTokens?: number;@@ -4126,52 +4139,24 @@ interface ElectronAPI {cachedTokens?: number;}>;getAccount: (agentKind: 'claude-code' | 'codex') => Promise<unknown | null>;- /** 模型单价表 (model id → USD/Mtok), main 端内存 + 磁盘缓存, 拉取失败时 null。 */- getModelPricing: () => Promise<Record<- string,- {- inputUsdPerMtok: number;- outputUsdPerMtok: number;- }- > | null>;+ /** provider-scoped 模型单价表;XD 价格与 model-access /models 同快照更新。 */+ getModelPricing: () => Promise<+ import('../shared/regionalMoney').ModelPricingCatalog | null+ >;+ onModelPricingChanged: (+ cb: (+ pricing: import('../shared/regionalMoney').ModelPricingCatalog | null,+ ) => void,+ ) => () => void;/** 用量历史聚合 (首页仪表盘)。wire 形态与 main/usage/usageHistory.ts 的 UsageHistoryPayload 同形。 */- getHistory: (opts?: { days?: number; forceRefresh?: boolean }) => Promise<{- generatedAt: number;- todayKey: string;- stale?: boolean;- estimatesPending?: boolean;- days: Array<{ day: string; costUsd: number; tokens: number }>;- modelDaily: Array<{- day: string;- agentKind: 'claude-code' | 'codex';- model: string;- amountUsd: number;- apiCostUsd: number;- subscriptionEstimateUsd: number;- tokens: number;- }>;- models: Array<{- agentKind: 'claude-code' | 'codex';- model: string;- costUsd: number;- estimatedCostUsd: number | null;- inputTokens: number;- outputTokens: number;- cacheReadTokens: number;- cacheCreateTokens: number;- }>;- streak: { current: number; longest: number };- totals: {- today: number;- last30Days: number;- last30DaysWithEstimatedValue: number;- last30DaysEstimatedValue: number;- todayTokens: number;- last30DaysTokens: number;- };- anomaly: { isAnomalous: boolean; trailing7DayAvg: number | null };- }>;- onTodaySpendChanged: (cb: (p: { day: string; costUsd: number }) => void) => () => void;+ getHistory: (+ opts?: { days?: number; forceRefresh?: boolean },+ ) => Promise<import('../main/usage/usageHistory').UsageHistoryPayload>;+ onTodaySpendChanged: (cb: (p: {+ day: string;+ money: import('../shared/regionalMoney').RegionalMoney;+ costUsd?: number;+ }) => void) => () => void;onTodayTokensChanged: (cb: (p: CodexUsageSnapshot) => void) => () => void;onClaudeAccountChanged: (cb: (p: {diff --git a/apps/desktop/src/shared/__tests__/regionalMoney.test.ts b/apps/desktop/src/shared/__tests__/regionalMoney.test.tsnew file mode 100644index 0000000000..e763d90c12--- /dev/null+++ b/apps/desktop/src/shared/__tests__/regionalMoney.test.ts@@ -0,0 +1,131 @@+import { describe, expect, it } from 'vitest';++import {+ addCompatibleRegionalMoney,+ addRegionalMoney,+ asValueEstimateMoney,+ gatewayMoney,+ regionalizeLegacyUsd,+ regionalizeUsd,+} from '../regionalMoney.js';++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({+ amount: 3,+ currency: 'USD',+ approximate: false,+ kind: 'actual-cost',+ });+ });++ 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,+ currency: 'CNY',+ approximate: true,+ 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',+ 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'],+ });+ });++ it('keeps global USD facts exact but marks subscription values as estimates', () => {+ expect(regionalizeUsd(3, 'global', 'reference-price')).toEqual({+ amount: 3,+ currency: 'USD',+ approximate: false,+ kind: 'actual-cost',+ });+ expect(regionalizeUsd(3, 'global', 'subscription-value', 'value-estimate')).toEqual({+ amount: 3,+ currency: 'USD',+ approximate: true,+ kind: 'value-estimate',+ estimateReasons: ['subscription-value'],+ });+ });++ it('preserves legacy USD as a fact and only marks CN conversion approximate', () => {+ expect(regionalizeLegacyUsd(1, 'global')).toMatchObject({+ amount: 1,+ currency: 'USD',+ approximate: false,+ });+ expect(regionalizeLegacyUsd(1, 'cn')).toMatchObject({+ amount: 6.7,+ currency: 'CNY',+ approximate: true,+ estimateReasons: expect.arrayContaining(['fixed-fx', 'legacy-usd']),+ });+ });++ it('propagates approximation and reasons while adding same-currency values', () => {+ const total = addRegionalMoney([gatewayMoney(3, 'cn'), regionalizeLegacyUsd(1, 'cn')]);+ expect(total).toMatchObject({+ amount: 9.7,+ currency: 'CNY',+ approximate: true,+ kind: 'actual-cost',+ estimateReasons: expect.arrayContaining(['fixed-fx', 'legacy-usd']),+ });+ });++ it('rejects mixed currencies instead of silently combining them', () => {+ expect(() => addRegionalMoney([gatewayMoney(1, 'cn'), gatewayMoney(1, 'global')])).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',+ );++ expect(total).toEqual(gatewayMoney(3, 'cn'));+ });++ it('prefers the current regional currency for mixed historical actual costs', () => {+ const total = addCompatibleRegionalMoney(+ [gatewayMoney(3, 'cn'), gatewayMoney(2, 'global')],+ 'USD',+ );++ expect(total).toEqual(gatewayMoney(2, 'global'));+ });++ it('marks subscription value without changing amount or currency', () => {+ expect(asValueEstimateMoney(regionalizeLegacyUsd(1, 'cn'))).toEqual({+ amount: 6.7,+ currency: 'CNY',+ approximate: true,+ kind: 'value-estimate',+ estimateReasons: ['fixed-fx', 'legacy-usd', 'subscription-value'],+ });+ });+});diff --git a/apps/desktop/src/shared/modelAccess.ts b/apps/desktop/src/shared/modelAccess.tsindex 0f338fef6d..53b5d42812 100644--- a/apps/desktop/src/shared/modelAccess.ts+++ b/apps/desktop/src/shared/modelAccess.ts@@ -99,7 +99,59 @@ export interface ModelAccessAgentOverride {defaultEnabled?: boolean;}-export interface ModelAccessGatewayModel {+export interface ModelGroupTieredPricing {+ range: [number, number];+ inputCostPerToken?: number;+ outputCostPerToken?: number;+ cacheReadInputTokenCost?: number;+ cacheCreationInputTokenCost?: number;+}++/**+ * model-access-server 从 AIGateway /model-groups 白名单透传的价格字段。+ * 字段名和单位保持 Gateway 原样(per token);Desktop 在构建 quote 时才转+ * per-million-token,并按构建区域赋予币种。+ */+export interface ModelGroupPricing {+ costDiscount?: number;+ inputCostPerToken?: number;+ outputCostPerToken?: number;+ inputCostPerTokenPriority?: number;+ outputCostPerTokenPriority?: number;+ cacheReadInputTokenCost?: number;+ cacheReadInputTokenCostPriority?: number;+ cacheCreationInputTokenCost?: number;+ inputCostPerTokenAbove200kTokens?: number;+ outputCostPerTokenAbove200kTokens?: number;+ cacheReadInputTokenCostAbove200kTokens?: number;+ inputCostPerTokenAbove200kTokensPriority?: number;+ outputCostPerTokenAbove200kTokensPriority?: number;+ cacheReadInputTokenCostAbove200kTokensPriority?: number;+ inputCostPerTokenAbove272kTokens?: number;+ outputCostPerTokenAbove272kTokens?: number;+ cacheReadInputTokenCostAbove272kTokens?: number;+ inputCostPerTokenAbove272kTokensPriority?: number;+ outputCostPerTokenAbove272kTokensPriority?: number;+ cacheReadInputTokenCostAbove272kTokensPriority?: number;+ inputCostPerCharacter?: number;+ outputCostPerCharacter?: number;+ inputCostPerSecond?: number;+ outputCostPerSecond?: number;+ inputCostPerAudioToken?: number;+ outputCostPerAudioToken?: number;+ inputCostPerAudioPerSecond?: number;+ outputCostPerAudioPerSecond?: number;+ inputCostPerImage?: number;+ outputCostPerImage?: number;+ inputCostPerImageToken?: number;+ outputCostPerImageToken?: number;+ cacheReadInputImageTokenCost?: number;+ inputCostPerVideoPerSecond?: number;+ outputCostPerVideoPerSecond?: number;+ tieredPricing?: ModelGroupTieredPricing[];+}++export interface ModelAccessGatewayModel extends ModelGroupPricing {id: string;/** 进哪些 runtime tab;缺省 = 仅 claude-code(网关 /v1/messages 翻译覆盖面最广)。 */agents?: ('claude-code' | 'codex')[];diff --git a/apps/desktop/src/shared/modelPriceQuote.ts b/apps/desktop/src/shared/modelPriceQuote.tsnew file mode 100644index 0000000000..1dee64c9ab--- /dev/null+++ b/apps/desktop/src/shared/modelPriceQuote.ts@@ -0,0 +1,207 @@+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,+ type ModelPriceQuote,+ type ModelPricingCatalog,+} from './regionalMoney.js';+import { CHATGPT_MODEL_PREFIX, XAI_MODEL_PREFIX } from './subscriptionModels.js';++const CODEX_BUDGET_PRICE_MULTIPLIER = 0.15;++const XAI_SUBSCRIPTION_VALUE_PRICING: Record<+ string,+ {+ inputPerMtok: number;+ outputPerMtok: number;+ cacheReadPerMtok?: number;+ cacheCreatePerMtok?: number;+ }+> = {+ 'grok-4.5': { inputPerMtok: 2, outputPerMtok: 6, cacheReadPerMtok: 0.5 },+ 'grok-4.3': { inputPerMtok: 3, outputPerMtok: 15 },+ 'grok-4.20': { inputPerMtok: 3, outputPerMtok: 15 },+ 'grok-code-fast': { inputPerMtok: 0.2, outputPerMtok: 1.5 },+};++function isNonNegativeFinite(value: unknown): value is number {+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;+}++function perMtok(value: unknown): number | undefined {+ return isNonNegativeFinite(value) ? value * 1_000_000 : undefined;+}++function applyCodexBudgetDiscount(quote: ModelPriceQuote): ModelPriceQuote {+ if (!quote.modelId.startsWith('codex/')) return quote;+ return {+ ...quote,+ inputPerMtok: quote.inputPerMtok * CODEX_BUDGET_PRICE_MULTIPLIER,+ outputPerMtok: quote.outputPerMtok * CODEX_BUDGET_PRICE_MULTIPLIER,+ ...(quote.cacheReadPerMtok !== undefined+ ? { cacheReadPerMtok: quote.cacheReadPerMtok * CODEX_BUDGET_PRICE_MULTIPLIER }+ : {}),+ ...(quote.cacheCreatePerMtok !== undefined+ ? { cacheCreatePerMtok: quote.cacheCreatePerMtok * CODEX_BUDGET_PRICE_MULTIPLIER }+ : {}),+ };+}++export function gatewayModelPriceQuote(+ model: ModelAccessGatewayModel,+ region: CindyRegion,+): ModelPriceQuote | undefined {+ const modelId = model.id.trim();+ const inputPerMtok = perMtok(model.inputCostPerToken);+ const outputPerMtok = perMtok(model.outputCostPerToken);+ if (!modelId || inputPerMtok === undefined || outputPerMtok === undefined) {+ return undefined;+ }+ if (inputPerMtok === 0 && outputPerMtok === 0) return undefined;+ const cacheReadPerMtok = perMtok(model.cacheReadInputTokenCost);+ const cacheCreatePerMtok = perMtok(model.cacheCreationInputTokenCost);+ return applyCodexBudgetDiscount({+ providerId: 'xd',+ modelId,+ currency: gatewayCurrencyForRegion(region),+ source: 'gateway',+ approximate: false,+ inputPerMtok,+ outputPerMtok,+ ...(cacheReadPerMtok !== undefined ? { cacheReadPerMtok } : {}),+ ...(cacheCreatePerMtok !== undefined ? { cacheCreatePerMtok } : {}),+ });+}++export function gatewayPricingCatalog(+ models: readonly ModelAccessGatewayModel[],+ region: CindyRegion,+): ModelPricingCatalog {+ const xd: Record<string, ModelPriceQuote> = {};+ for (const model of models) {+ const quote = gatewayModelPriceQuote(model, region);+ if (quote) xd[quote.modelId] = quote;+ }+ return Object.keys(xd).length > 0 ? { xd } : {};+}++function subscriptionQuote(+ providerId: string,+ modelId: string,+ price: {+ inputPerMtok: number;+ outputPerMtok: number;+ cacheReadPerMtok?: number;+ cacheCreatePerMtok?: number;+ },+): ModelPriceQuote {+ return {+ providerId,+ modelId,+ currency: 'USD',+ source: 'subscription-reference',+ approximate: true,+ ...price,+ };+}++export function providerReferencePriceQuote(+ providerId: string,+ modelId: string,+): ModelPriceQuote | undefined {+ if (providerId === 'anthropic') {+ const price = getClaudeSubscriptionValueFallbackPrice(modelId);+ if (!price) return undefined;+ return subscriptionQuote(providerId, modelId, {+ inputPerMtok: price.inputUsdPerMtok,+ outputPerMtok: price.outputUsdPerMtok,+ ...(price.cacheReadUsdPerMtok !== undefined+ ? { cacheReadPerMtok: price.cacheReadUsdPerMtok }+ : {}),+ ...(price.cacheCreateUsdPerMtok !== undefined+ ? { cacheCreatePerMtok: price.cacheCreateUsdPerMtok }+ : {}),+ });+ }+ if (providerId === 'openai') {+ const bareModel = modelId.startsWith(CHATGPT_MODEL_PREFIX)+ ? modelId.slice(CHATGPT_MODEL_PREFIX.length)+ : modelId;+ const price = CODEX_SUBSCRIPTION_VALUE_PRICING[bareModel];+ if (!price) return undefined;+ return subscriptionQuote(providerId, modelId, {+ inputPerMtok: price.inputUsdPerMtok,+ outputPerMtok: price.outputUsdPerMtok,+ ...(price.cacheReadUsdPerMtok !== undefined+ ? { cacheReadPerMtok: price.cacheReadUsdPerMtok }+ : {}),+ ...(price.cacheCreateUsdPerMtok !== undefined+ ? { cacheCreatePerMtok: price.cacheCreateUsdPerMtok }+ : {}),+ });+ }+ if (providerId === 'xai') {+ const bareModel = modelId.startsWith(XAI_MODEL_PREFIX)+ ? modelId.slice(XAI_MODEL_PREFIX.length)+ : modelId;+ const price = XAI_SUBSCRIPTION_VALUE_PRICING[bareModel];+ return price ? subscriptionQuote(providerId, modelId, price) : undefined;+ }+ return undefined;+}++export function getModelPriceQuote(+ pricing: ModelPricingCatalog | null | undefined,+ providerId: string | null | undefined,+ modelId: string,+): ModelPriceQuote | undefined {+ const normalizedProvider = providerId?.trim();+ const normalizedModel = modelId.trim();+ if (!normalizedProvider || !normalizedModel) return undefined;+ return (+ pricing?.[normalizedProvider]?.[normalizedModel] ??+ providerReferencePriceQuote(normalizedProvider, normalizedModel)+ );+}++export function subscriptionDirectPriceQuote(+ modelId: string,+): ModelPriceQuote | undefined {+ if (modelId.startsWith(CHATGPT_MODEL_PREFIX)) {+ return providerReferencePriceQuote('openai', modelId);+ }+ if (modelId.startsWith(XAI_MODEL_PREFIX)) {+ return providerReferencePriceQuote('xai', modelId);+ }+ 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.tsnew file mode 100644index 0000000000..8b5e0d987d--- /dev/null+++ b/apps/desktop/src/shared/regionalMoney.ts@@ -0,0 +1,200 @@+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';++export interface RegionalMoney {+ amount: number;+ currency: MoneyCurrency;+ approximate: boolean;+ kind: MoneyKind;+ estimateReasons?: MoneyEstimateReason[];+}++export interface ModelPriceQuote {+ providerId: string;+ modelId: string;+ currency: MoneyCurrency;+ source: 'gateway' | 'provider-reference' | 'subscription-reference';+ approximate: boolean;+ inputPerMtok: number;+ outputPerMtok: number;+ cacheReadPerMtok?: number;+ cacheCreatePerMtok?: number;+}++export type ModelPricingCatalog = Record<string, Record<string, ModelPriceQuote>>;++export const USD_TO_CNY_FIXED_RATE = 6.7;++function assertAmount(amount: number): void {+ if (!Number.isFinite(amount) || amount < 0) {+ throw new Error(`invalid non-negative money amount: ${String(amount)}`);+ }+}++function uniqueReasons(+ reasons: ReadonlyArray<MoneyEstimateReason | undefined>,+): MoneyEstimateReason[] | undefined {+ const out = [...new Set(reasons.filter((reason): reason is MoneyEstimateReason => !!reason))];+ return out.length > 0 ? out : undefined;+}++export function gatewayCurrencyForRegion(region: CindyRegion): MoneyCurrency {+ return region === 'global' ? 'USD' : 'CNY';+}++export function regionalCurrencyForRegion(region: CindyRegion): MoneyCurrency {+ return gatewayCurrencyForRegion(region);+}++export function zeroRegionalMoney(+ region: CindyRegion,+ kind: MoneyKind = 'actual-cost',+): RegionalMoney {+ return {+ amount: 0,+ currency: regionalCurrencyForRegion(region),+ approximate: kind === 'value-estimate',+ kind,+ ...(kind === 'value-estimate' ? { estimateReasons: ['subscription-value'] } : {}),+ };+}++export function regionalizeUsd(+ amountUsd: number,+ region: CindyRegion,+ reason: MoneyEstimateReason,+ kind: MoneyKind = 'actual-cost',+): RegionalMoney {+ assertAmount(amountUsd);+ const convert = region !== 'global';+ const approximateConversion = convert && amountUsd !== 0;+ const approximate = approximateConversion || kind === 'value-estimate';+ const estimateReasons = approximate+ ? uniqueReasons([+ approximateConversion ? 'fixed-fx' : undefined,+ reason,+ kind === 'value-estimate' ? 'subscription-value' : undefined,+ ])+ : undefined;+ return {+ amount: convert ? amountUsd * USD_TO_CNY_FIXED_RATE : amountUsd,+ currency: convert ? 'CNY' : 'USD',+ approximate,+ kind,+ ...(estimateReasons ? { estimateReasons } : {}),+ };+}++export function gatewayMoney(+ amount: number,+ region: CindyRegion,+ kind: MoneyKind = 'actual-cost',+): RegionalMoney {+ assertAmount(amount);+ const approximate = kind === 'value-estimate';+ return {+ amount,+ currency: gatewayCurrencyForRegion(region),+ approximate,+ kind,+ ...(approximate ? { estimateReasons: ['subscription-value'] } : {}),+ };+}++export function addRegionalMoney(values: readonly RegionalMoney[]): RegionalMoney {+ if (values.length === 0) throw new Error('cannot add an empty money list');+ const currency = values[0].currency;+ if (values.some((value) => value.currency !== currency)) {+ throw new Error('cannot add money with different currencies');+ }+ for (const value of values) assertAmount(value.amount);+ const approximate = values.some((value) => value.approximate);+ const estimateReasons = uniqueReasons(values.flatMap((value) => value.estimateReasons ?? []));+ return {+ amount: values.reduce((sum, value) => sum + value.amount, 0),+ currency,+ approximate,+ kind: values.some((value) => value.kind === 'actual-cost') ? 'actual-cost' : 'value-estimate',+ ...(estimateReasons ? { estimateReasons } : {}),+ };+}++/**+ * 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.+ */+export function addCompatibleRegionalMoney(+ values: readonly RegionalMoney[],+ preferredCurrency: MoneyCurrency,+): RegionalMoney | null {+ if (values.length === 0) return null;+ const actualValues = values.filter((value) => value.kind === 'actual-cost');+ const currencyCandidates = actualValues.length > 0 ? actualValues : values;+ const currency =+ currencyCandidates.find((value) => value.currency === preferredCurrency)?.currency ??+ currencyCandidates[0].currency;+ const compatible = values.filter((value) => value.currency === currency);+ return compatible.length > 0 ? addRegionalMoney(compatible) : null;+}++export function asValueEstimateMoney(money: RegionalMoney): RegionalMoney {+ assertAmount(money.amount);+ return {+ ...money,+ approximate: true,+ kind: 'value-estimate',+ estimateReasons: uniqueReasons([...(money.estimateReasons ?? []), 'subscription-value']),+ };+}++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>;+ if (+ !isNonNegativeAmount(raw.amount) ||+ (raw.currency !== 'CNY' && raw.currency !== 'USD') ||+ typeof raw.approximate !== 'boolean' ||+ (raw.kind !== 'actual-cost' && raw.kind !== 'value-estimate')+ ) {+ return undefined;+ }+ const estimateReasons = Array.isArray(raw.estimateReasons)+ ? uniqueReasons(+ raw.estimateReasons.filter(+ (reason): reason is MoneyEstimateReason =>+ reason === 'fixed-fx' ||+ reason === 'legacy-usd' ||+ reason === 'subscription-value' ||+ reason === 'reference-price',+ ),+ )+ : undefined;+ return {+ amount: raw.amount,+ currency: raw.currency,+ approximate: raw.approximate,+ kind: raw.kind,+ ...(estimateReasons ? { estimateReasons } : {}),+ };+}++function isNonNegativeAmount(value: unknown): value is number {+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;+}diff --git a/apps/desktop/src/shared/turnUsageDetails.ts b/apps/desktop/src/shared/turnUsageDetails.tsindex 8375e52906..089b994135 100644--- a/apps/desktop/src/shared/turnUsageDetails.ts+++ b/apps/desktop/src/shared/turnUsageDetails.ts@@ -3,6 +3,15 @@* message. Stored in messages.agent_meta so old DB schema stays unchanged.*/+import { CURRENT_CINDY_REGION } from './brandRegion.js';+import {+ addCompatibleRegionalMoney,+ normalizeRegionalMoney,+ regionalCurrencyForRegion,+ regionalizeLegacyUsd,+ type RegionalMoney,+} from './regionalMoney.js';+export interface TurnUsageDetails {/** 新输入 token:未命中缓存、按输入价计费的部分。 */inputTokens: number;@@ -25,7 +34,7 @@ export interface TurnUsageDetails {* (来自 resolveClaudeTurnCostSinks 的 perModel),含 subagent (如 Task 工具* 跑的 Haiku) —— tooltip 据此展示「按模型成本明细」。老消息无此字段。*/- perModelCost?: Array<{ model: string; costUsd: number }>;+ perModelCost?: Array<{ model: string; money: RegionalMoney }>;}export interface BuildTurnUsageDetailsInput {@@ -35,13 +44,20 @@ export interface BuildTurnUsageDetailsInput {cacheCreateTokens?: number;model?: string | null;models?: Array<string | null | undefined> | readonly (string | null | undefined)[];- perModelCost?: ReadonlyArray<{ model?: string | null; costUsd?: number | null } | null | undefined>;+ perModelCost?: ReadonlyArray<+ | {+ model?: string | null;+ money?: RegionalMoney | null;+ /** 旧消息兼容:历史事实始终是 USD。 */+ costUsd?: number | null;+ }+ | null+ | undefined+ >;}function sanitizeToken(value: unknown): number {- return typeof value === 'number' && Number.isFinite(value) && value > 0- ? Math.floor(value)- : 0;+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;}function sanitizeModel(value: unknown): string | undefined {@@ -64,18 +80,36 @@ function uniqueModels(models: BuildTurnUsageDetailsInput['models']): string[] |*/function sanitizePerModelCost(list: BuildTurnUsageDetailsInput['perModelCost'],-): Array<{ model: string; costUsd: number }> | undefined {+): Array<{ model: string; money: RegionalMoney }> | undefined {if (!list || !Array.isArray(list)) return undefined;- const byModel = new Map<string, number>();+ const byModel = new Map<string, RegionalMoney>();for (const item of list) {if (!item || typeof item !== 'object') continue;const model = sanitizeModel(item.model);- const cost = item.costUsd;- if (!model || typeof cost !== 'number' || !Number.isFinite(cost) || cost <= 0) continue;- byModel.set(model, (byModel.get(model) ?? 0) + cost);+ const structured = normalizeRegionalMoney(item.money);+ const legacy =+ typeof item.costUsd === 'number' && Number.isFinite(item.costUsd) && item.costUsd > 0+ ? regionalizeLegacyUsd(item.costUsd, CURRENT_CINDY_REGION)+ : undefined;+ const money = structured ?? legacy;+ if (!model || !money || money.amount <= 0) continue;+ const current = byModel.get(model);+ byModel.set(+ model,+ current+ ? (addCompatibleRegionalMoney(+ [current, money],+ regionalCurrencyForRegion(CURRENT_CINDY_REGION),+ ) ?? money)+ : money,+ );}- if (byModel.size === 0) return undefined;- return Array.from(byModel, ([model, costUsd]) => ({ model, costUsd }));+ return byModel.size > 0+ ? [...byModel.entries()].map(([model, money]) => ({+ model,+ money,+ }))+ : undefined;}/** Build a normalized usage detail object. Returns null when all token counts are 0. */@@ -110,19 +144,28 @@ export function buildTurnUsageDetails(input: BuildTurnUsageDetailsInput): TurnUsexport function normalizeTurnUsageDetails(value: unknown): TurnUsageDetails | undefined {if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;const raw = value as Record<string, unknown>;- return buildTurnUsageDetails({- inputTokens: typeof raw.inputTokens === 'number' ? raw.inputTokens : undefined,- outputTokens: typeof raw.outputTokens === 'number' ? raw.outputTokens : undefined,- cacheReadTokens: typeof raw.cacheReadTokens === 'number' ? raw.cacheReadTokens : undefined,- cacheCreateTokens: typeof raw.cacheCreateTokens === 'number' ? raw.cacheCreateTokens : undefined,- model: typeof raw.model === 'string' ? raw.model : undefined,- models: Array.isArray(raw.models) ? raw.models.filter((m): m is string => typeof m === 'string') : undefined,- perModelCost: Array.isArray(raw.perModelCost)- ? raw.perModelCost.map((e) =>- e && typeof e === 'object'- ? { model: (e as Record<string, unknown>).model as string | null | undefined, costUsd: (e as Record<string, unknown>).costUsd as number | null | undefined }- : null,- )- : undefined,- }) ?? undefined;+ return (+ buildTurnUsageDetails({+ inputTokens: typeof raw.inputTokens === 'number' ? raw.inputTokens : undefined,+ outputTokens: typeof raw.outputTokens === 'number' ? raw.outputTokens : undefined,+ cacheReadTokens: typeof raw.cacheReadTokens === 'number' ? raw.cacheReadTokens : undefined,+ cacheCreateTokens:+ typeof raw.cacheCreateTokens === 'number' ? raw.cacheCreateTokens : undefined,+ model: typeof raw.model === 'string' ? raw.model : undefined,+ models: Array.isArray(raw.models)+ ? raw.models.filter((m): m is string => typeof m === 'string')+ : undefined,+ perModelCost: Array.isArray(raw.perModelCost)+ ? raw.perModelCost.map((e) =>+ e && typeof e === 'object'+ ? {+ model: (e as Record<string, unknown>).model as string | null | undefined,+ money: (e as Record<string, unknown>).money as RegionalMoney | null | undefined,+ costUsd: (e as Record<string, unknown>).costUsd as number | null | undefined,+ }+ : null,+ )+ : undefined,+ }) ?? undefined+ );}diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex 08cf28c6f2..a656b10fdb 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -293,8 +293,8 @@ const EXTENDED_INVOKE_CHANNELS: readonly string[] = [// 人工 reset。mutation 不接收 creditId,不能泛化成任意账号/凭证控制入口。'maker:usage:codex-rate-limits','maker:usage:codex-rate-limit-reset',- // 模型单价表(只读,main 侧 LiteLLM /model_group/info 缓存):控制端模型选择器展示被控端- // 视角的单价(与被控端桌面 tooltip 同源)。无 sender 依赖、无副作用;老被控端无此 channel+ // 模型单价表(只读,main 侧 Model Access model-groups 投影缓存):控制端模型选择器展示+ // 被控端视角的单价(与被控端桌面 tooltip 同源)。无 sender 依赖、无副作用;老被控端无此 channel// → CHANNEL_NOT_ALLOWED → 控制端隐藏价格(与桌面「无价不显示」口径一致)。'maker:usage:model-pricing',// 网关 API key **presence-only** 探测:只回 { present: boolean },不回、也永不扩展为读取diff --git a/packages/maker-scheduler/src/types.ts b/packages/maker-scheduler/src/types.tsindex 7e03efea7b..9a1528db15 100644--- a/packages/maker-scheduler/src/types.ts+++ b/packages/maker-scheduler/src/types.ts@@ -241,6 +241,10 @@ export interface ScheduleRun {costUsd?: number;/** 本次 run 的订阅 token 估算价值,不计入真实账单。 */estimatedValueUsd?: number;+ /** 新版区域真实费用;旧 costUsd 仅作历史 USD 兼容。 */+ costMoney?: ScheduleRunMoney;+ /** 新版区域订阅价值估算;不代表实际账单。 */+ estimatedValueMoney?: ScheduleRunMoney;/*** exact = 已确认费用(可能是实际账单,也可能是 estimate-only);direct = 费用仅来自* 无法挂载消息的直接账本;mixed = 快照同时包含直接账本和消息账本;zero = 已确认零费用;@@ -266,6 +270,16 @@ export interface ScheduleRun {heartbeatAt?: number;}+export interface ScheduleRunMoney {+ amount: number;+ currency: 'CNY' | 'USD';+ approximate: boolean;+ kind: 'actual-cost' | 'value-estimate';+ estimateReasons?: Array<+ 'fixed-fx' | 'legacy-usd' | 'subscription-value' | 'reference-price'+ >;+}+export interface CreateScheduleInput {name: string;prompt: string;diff --git a/packages/maker-shared/src/scheduleTypes.ts b/packages/maker-shared/src/scheduleTypes.tsindex 8617a09b6f..2b7af63920 100644--- a/packages/maker-shared/src/scheduleTypes.ts+++ b/packages/maker-shared/src/scheduleTypes.ts@@ -119,10 +119,22 @@ export interface RemoteScheduleRun {resultText?: string;costUsd?: number;estimatedValueUsd?: number;+ costMoney?: RemoteScheduleRunMoney;+ estimatedValueMoney?: RemoteScheduleRunMoney;costAttribution?: 'exact' | 'direct' | 'mixed' | 'zero' | 'unavailable' | 'legacy';readAt?: RemoteTimestamp;}+export interface RemoteScheduleRunMoney {+ amount: number;+ currency: 'CNY' | 'USD';+ approximate: boolean;+ kind: 'actual-cost' | 'value-estimate';+ estimateReasons?: Array<+ 'fixed-fx' | 'legacy-usd' | 'subscription-value' | 'reference-price'+ >;+}+export interface ScheduleListFilter {status?: RemoteScheduleStatus;}