Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): 稳定账本币种并停止用量记账丢数据 (#1302)

Dash7792cebd66b0
diff --git a/apps/desktop/drizzle/0085_skinny_iron_man.sql b/apps/desktop/drizzle/0085_skinny_iron_man.sql
new file mode 100644
index 0000000000..213b92c3f5
--- /dev/null
+++ b/apps/desktop/drizzle/0085_skinny_iron_man.sql
@@ -0,0 +1,59 @@
+PRAGMA foreign_keys=OFF;--> statement-breakpoint
+CREATE TABLE IF NOT EXISTS `daily_model_usage` (
+ `day` text NOT NULL,
+ `agent_kind` text NOT NULL,
+ `model` text NOT NULL,
+ `cost_usd` real DEFAULT 0 NOT NULL,
+ `cost_amount` real DEFAULT 0 NOT NULL,
+ `cost_currency` text,
+ `cost_is_approximate` integer DEFAULT false NOT NULL,
+ `input_tokens` integer DEFAULT 0 NOT NULL,
+ `output_tokens` integer DEFAULT 0 NOT NULL,
+ `cache_read_tokens` integer DEFAULT 0 NOT NULL,
+ `cache_create_tokens` integer DEFAULT 0 NOT NULL,
+ `updated_at` integer NOT NULL,
+ PRIMARY KEY(`day`, `agent_kind`, `model`)
+);
+--> statement-breakpoint
+CREATE TABLE IF NOT EXISTS `daily_spend` (
+ `day` text PRIMARY KEY NOT NULL,
+ `cost_usd` real DEFAULT 0 NOT NULL,
+ `cost_amount` real DEFAULT 0 NOT NULL,
+ `cost_currency` text,
+ `cost_is_approximate` integer DEFAULT false NOT NULL,
+ `updated_at` integer NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE `__new_daily_model_usage` (
+ `day` text NOT NULL,
+ `agent_kind` text NOT NULL,
+ `model` text NOT NULL,
+ `cost_usd` real DEFAULT 0 NOT NULL,
+ `cost_amount` real DEFAULT 0 NOT NULL,
+ `cost_currency` text DEFAULT 'USD' NOT NULL,
+ `cost_is_approximate` integer DEFAULT false NOT NULL,
+ `input_tokens` integer DEFAULT 0 NOT NULL,
+ `output_tokens` integer DEFAULT 0 NOT NULL,
+ `cache_read_tokens` integer DEFAULT 0 NOT NULL,
+ `cache_create_tokens` integer DEFAULT 0 NOT NULL,
+ `updated_at` integer NOT NULL,
+ PRIMARY KEY(`day`, `agent_kind`, `model`, `cost_currency`)
+);
+--> statement-breakpoint
+INSERT INTO `__new_daily_model_usage`("day", "agent_kind", "model", "cost_usd", "cost_amount", "cost_currency", "cost_is_approximate", "input_tokens", "output_tokens", "cache_read_tokens", "cache_create_tokens", "updated_at") SELECT "day", "agent_kind", "model", "cost_usd", "cost_amount", COALESCE("cost_currency", 'USD'), "cost_is_approximate", "input_tokens", "output_tokens", "cache_read_tokens", "cache_create_tokens", "updated_at" FROM `daily_model_usage`;--> statement-breakpoint
+DROP TABLE `daily_model_usage`;--> statement-breakpoint
+ALTER TABLE `__new_daily_model_usage` RENAME TO `daily_model_usage`;--> statement-breakpoint
+PRAGMA foreign_keys=ON;--> statement-breakpoint
+CREATE TABLE `__new_daily_spend` (
+ `day` text NOT NULL,
+ `cost_usd` real DEFAULT 0 NOT NULL,
+ `cost_amount` real DEFAULT 0 NOT NULL,
+ `cost_currency` text DEFAULT 'USD' NOT NULL,
+ `cost_is_approximate` integer DEFAULT false NOT NULL,
+ `updated_at` integer NOT NULL,
+ PRIMARY KEY(`day`, `cost_currency`)
+);
+--> statement-breakpoint
+INSERT INTO `__new_daily_spend`("day", "cost_usd", "cost_amount", "cost_currency", "cost_is_approximate", "updated_at") SELECT "day", "cost_usd", "cost_amount", COALESCE("cost_currency", 'USD'), "cost_is_approximate", "updated_at" FROM `daily_spend`;--> statement-breakpoint
+DROP TABLE `daily_spend`;--> statement-breakpoint
+ALTER TABLE `__new_daily_spend` RENAME TO `daily_spend`;
\ No newline at end of file
diff --git a/apps/desktop/drizzle/meta/0085_snapshot.json b/apps/desktop/drizzle/meta/0085_snapshot.json
new file mode 100644
index 0000000000..e12956f150
--- /dev/null
+++ b/apps/desktop/drizzle/meta/0085_snapshot.json
@@ -0,0 +1,3844 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "daddbf8c-2d5f-48e4-8f12-f760511b47fa",
+ "prevId": "8344fb86-a506-45c9-bb6c-552a2482afa5",
+ "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": true,
+ "autoincrement": false,
+ "default": "'USD'"
+ },
+ "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_cost_currency_pk": {
+ "columns": [
+ "day",
+ "agent_kind",
+ "model",
+ "cost_currency"
+ ],
+ "name": "daily_model_usage_day_agent_kind_model_cost_currency_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "daily_spend": {
+ "name": "daily_spend",
+ "columns": {
+ "day": {
+ "name": "day",
+ "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": true,
+ "autoincrement": false,
+ "default": "'USD'"
+ },
+ "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": {
+ "daily_spend_day_cost_currency_pk": {
+ "columns": [
+ "day",
+ "cost_currency"
+ ],
+ "name": "daily_spend_day_cost_currency_pk"
+ }
+ },
+ "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": {}
+ },
+ "hook_group_messages": {
+ "name": "hook_group_messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "thread_id": {
+ "name": "thread_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_name": {
+ "name": "chat_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "author": {
+ "name": "author",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_bot": {
+ "name": "is_bot",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "file_names": {
+ "name": "file_names",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "hook_group_messages_msg_idx": {
+ "name": "hook_group_messages_msg_idx",
+ "columns": [
+ "provider",
+ "chat_id",
+ "thread_id",
+ "message_id"
+ ],
+ "isUnique": true
+ },
+ "hook_group_messages_window_idx": {
+ "name": "hook_group_messages_window_idx",
+ "columns": [
+ "provider",
+ "chat_id",
+ "thread_id",
+ "id"
+ ],
+ "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
+ },
+ "notify_wecom_group": {
+ "name": "notify_wecom_group",
+ "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": {}
+ },
+ "wechat_file_attachments": {
+ "name": "wechat_file_attachments",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "abs_path": {
+ "name": "abs_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "original_name": {
+ "name": "original_name",
+ "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
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'staged'"
+ },
+ "promoted_at": {
+ "name": "promoted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_wechat_file_attachments_task": {
+ "name": "idx_wechat_file_attachments_task",
+ "columns": [
+ "binding_epoch",
+ "task_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "wechat_file_attachments_binding_epoch_wechat_sync_state_binding_epoch_fk": {
+ "name": "wechat_file_attachments_binding_epoch_wechat_sync_state_binding_epoch_fk",
+ "tableFrom": "wechat_file_attachments",
+ "tableTo": "wechat_sync_state",
+ "columnsFrom": [
+ "binding_epoch"
+ ],
+ "columnsTo": [
+ "binding_epoch"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wechat_file_attachments_task_id_wechat_inbox_id_fk": {
+ "name": "wechat_file_attachments_task_id_wechat_inbox_id_fk",
+ "tableFrom": "wechat_file_attachments",
+ "tableTo": "wechat_inbox",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wechat_file_attachments_session_id_sessions_id_fk": {
+ "name": "wechat_file_attachments_session_id_sessions_id_fk",
+ "tableFrom": "wechat_file_attachments",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_inbox": {
+ "name": "wechat_inbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "platform_message_id": {
+ "name": "platform_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "platform_seq": {
+ "name": "platform_seq",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "peer_id": {
+ "name": "peer_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "received_at": {
+ "name": "received_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "platform_created_at": {
+ "name": "platform_created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "lease_until": {
+ "name": "lease_until",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "conversation_epoch": {
+ "name": "conversation_epoch",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "payload_json": {
+ "name": "payload_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_nonce": {
+ "name": "context_nonce",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_ciphertext": {
+ "name": "context_ciphertext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_tag": {
+ "name": "context_tag",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "last_error_code": {
+ "name": "last_error_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_wechat_inbox_platform_message": {
+ "name": "uniq_wechat_inbox_platform_message",
+ "columns": [
+ "binding_epoch",
+ "platform_message_id"
+ ],
+ "isUnique": true
+ },
+ "idx_wechat_inbox_queue": {
+ "name": "idx_wechat_inbox_queue",
+ "columns": [
+ "binding_epoch",
+ "status",
+ "received_at"
+ ],
+ "isUnique": false
+ },
+ "idx_wechat_inbox_lease": {
+ "name": "idx_wechat_inbox_lease",
+ "columns": [
+ "binding_epoch",
+ "lease_until"
+ ],
+ "isUnique": false
+ },
+ "idx_wechat_inbox_conversation": {
+ "name": "idx_wechat_inbox_conversation",
+ "columns": [
+ "binding_epoch",
+ "peer_id",
+ "conversation_epoch"
+ ],
+ "isUnique": false
+ },
+ "uniq_wechat_inbox_running_session": {
+ "name": "uniq_wechat_inbox_running_session",
+ "columns": [
+ "binding_epoch",
+ "session_id"
+ ],
+ "isUnique": true,
+ "where": "\"wechat_inbox\".\"session_id\" IS NOT NULL AND \"wechat_inbox\".\"status\" IN ('dispatching', 'accepted_running', 'waiting_desktop', 'delivery_pending')"
+ }
+ },
+ "foreignKeys": {
+ "wechat_inbox_binding_epoch_wechat_sync_state_binding_epoch_fk": {
+ "name": "wechat_inbox_binding_epoch_wechat_sync_state_binding_epoch_fk",
+ "tableFrom": "wechat_inbox",
+ "tableTo": "wechat_sync_state",
+ "columnsFrom": [
+ "binding_epoch"
+ ],
+ "columnsTo": [
+ "binding_epoch"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wechat_inbox_session_id_sessions_id_fk": {
+ "name": "wechat_inbox_session_id_sessions_id_fk",
+ "tableFrom": "wechat_inbox",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_outbox": {
+ "name": "wechat_outbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chunk_index": {
+ "name": "chunk_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "media_json": {
+ "name": "media_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "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
+ },
+ "next_retry_at": {
+ "name": "next_retry_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "delivered_at": {
+ "name": "delivered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_wechat_outbox_client_id": {
+ "name": "uniq_wechat_outbox_client_id",
+ "columns": [
+ "binding_epoch",
+ "client_id"
+ ],
+ "isUnique": true
+ },
+ "idx_wechat_outbox_delivery": {
+ "name": "idx_wechat_outbox_delivery",
+ "columns": [
+ "binding_epoch",
+ "status",
+ "next_retry_at"
+ ],
+ "isUnique": false
+ },
+ "idx_wechat_outbox_task": {
+ "name": "idx_wechat_outbox_task",
+ "columns": [
+ "binding_epoch",
+ "task_id",
+ "chunk_index"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "wechat_outbox_binding_epoch_wechat_sync_state_binding_epoch_fk": {
+ "name": "wechat_outbox_binding_epoch_wechat_sync_state_binding_epoch_fk",
+ "tableFrom": "wechat_outbox",
+ "tableTo": "wechat_sync_state",
+ "columnsFrom": [
+ "binding_epoch"
+ ],
+ "columnsTo": [
+ "binding_epoch"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wechat_outbox_task_id_wechat_inbox_id_fk": {
+ "name": "wechat_outbox_task_id_wechat_inbox_id_fk",
+ "tableFrom": "wechat_outbox",
+ "tableTo": "wechat_inbox",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_sync_state": {
+ "name": "wechat_sync_state",
+ "columns": {
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "sync_cursor": {
+ "name": "sync_cursor",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "last_poll_at": {
+ "name": "last_poll_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_error_code": {
+ "name": "last_error_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_wechat_sync_active": {
+ "name": "uniq_wechat_sync_active",
+ "columns": [
+ "is_active"
+ ],
+ "isUnique": true,
+ "where": "\"wechat_sync_state\".\"is_active\" = 1"
+ }
+ },
+ "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 file
diff --git a/apps/desktop/drizzle/meta/_journal.json b/apps/desktop/drizzle/meta/_journal.json
index 533cc26e30..7930194420 100644
--- a/apps/desktop/drizzle/meta/_journal.json
+++ b/apps/desktop/drizzle/meta/_journal.json
@@ -596,6 +596,13 @@
"when": 1785428363998,
"tag": "0084_small_gwen_stacy",
"breakpoints": true
+ },
+ {
+ "idx": 85,
+ "version": "6",
+ "when": 1785574922980,
+ "tag": "0085_skinny_iron_man",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/apps/desktop/drizzle/scripts/0085_skinny_iron_man.ts b/apps/desktop/drizzle/scripts/0085_skinny_iron_man.ts
new file mode 100644
index 0000000000..67afd1a5d7
Binary files /dev/null and b/apps/desktop/drizzle/scripts/0085_skinny_iron_man.ts differ
diff --git a/apps/desktop/src/main/localDb/__tests__/dailyLedgerCurrencyConflict.test.ts b/apps/desktop/src/main/localDb/__tests__/dailyLedgerCurrencyConflict.test.ts
index 894c72f96a..70c6eedcde 100644
--- a/apps/desktop/src/main/localDb/__tests__/dailyLedgerCurrencyConflict.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/dailyLedgerCurrencyConflict.test.ts
@@ -14,9 +14,14 @@ vi.mock('../../logger', () => ({
import * as schema from '../schema';
import type { DbClient } from '../client/DbClient';
import { clearCurrentDbClient, setCurrentDbClient } from '../client/current';
-import { incrementDailySpend, localDayKey } from '../dailySpend';
+import {
+ collapseDayMonies,
+ getAllSpendDays,
+ getTodaySpend,
+ incrementDailySpend,
+ localDayKey,
+} from '../dailySpend';
import { incrementDailyModelUsage } from '../dailyModelUsage';
-import { DEFAULT_USAGE_CURRENCY } from '../../../shared/regionalMoney';
import {
__resetActiveLedgerCurrencyForTesting,
setActiveLedgerCurrency,
@@ -24,12 +29,13 @@ import {
const DDL = `
CREATE TABLE daily_spend (
- day TEXT PRIMARY KEY NOT NULL,
+ day TEXT NOT NULL,
cost_usd REAL NOT NULL DEFAULT 0,
cost_amount REAL NOT NULL DEFAULT 0,
- cost_currency TEXT,
+ cost_currency TEXT NOT NULL DEFAULT 'USD',
cost_is_approximate INTEGER NOT NULL DEFAULT 0,
- updated_at INTEGER NOT NULL
+ updated_at INTEGER NOT NULL,
+ PRIMARY KEY (day, cost_currency)
);
CREATE TABLE daily_model_usage (
day TEXT NOT NULL,
@@ -37,14 +43,14 @@ const DDL = `
model TEXT NOT NULL,
cost_usd REAL NOT NULL DEFAULT 0,
cost_amount REAL NOT NULL DEFAULT 0,
- cost_currency TEXT,
+ cost_currency TEXT NOT NULL DEFAULT 'USD',
cost_is_approximate INTEGER NOT NULL DEFAULT 0,
input_tokens INTEGER NOT NULL DEFAULT 0,
output_tokens INTEGER NOT NULL DEFAULT 0,
cache_read_tokens INTEGER NOT NULL DEFAULT 0,
cache_create_tokens INTEGER NOT NULL DEFAULT 0,
updated_at INTEGER NOT NULL,
- PRIMARY KEY (day, agent_kind, model)
+ PRIMARY KEY (day, agent_kind, model, cost_currency)
);
`;
@@ -58,6 +64,7 @@ function createHarness() {
sqlite,
dbClient,
close: () => {
+ __resetActiveLedgerCurrencyForTesting();
clearCurrentDbClient(dbClient);
sqlite.close();
},
@@ -78,126 +85,104 @@ const cny = (amount: number) => ({
kind: 'actual-cost' as const,
});
-const currentMoney = DEFAULT_USAGE_CURRENCY === 'CNY' ? cny : usd;
-const conflictingMoney = DEFAULT_USAGE_CURRENCY === 'CNY' ? usd : cny;
+describe('daily ledger multi-currency rows', () => {
+ it('never overwrites an existing day total when the ledger currency flips', async () => {
+ // 回归护栏。此前 daily_spend 一天只有一行、币种冲突时直接用新金额覆盖旧累计,
+ // 于是账本币种每翻转一次(换号、跨租户、上游漏发 currency)就静默丢掉当天已记的
+ // 全部花费 —— 实测一天内翻转多次,首页"今日花费"被反复清零。
+ const harness = createHarness();
+ try {
+ setActiveLedgerCurrency('CNY');
+ await incrementDailySpend(cny(149.13));
+ setActiveLedgerCurrency('USD');
+ await incrementDailySpend(usd(15.44));
-describe('daily ledger currency invariant', () => {
- it('daily spend ignores a non-regional currency without replacing the total', async () => {
+ const rows = harness.sqlite
+ .prepare('SELECT cost_currency, cost_amount FROM daily_spend ORDER BY cost_currency')
+ .all() as Array<{ cost_currency: string; cost_amount: number }>;
+ expect(rows).toEqual([
+ { cost_currency: 'CNY', cost_amount: 149.13 },
+ { cost_currency: 'USD', cost_amount: 15.44 },
+ ]);
+ } finally {
+ harness.close();
+ }
+ });
+
+ it('keeps accumulating within each currency instead of restarting', async () => {
const harness = createHarness();
try {
- await incrementDailySpend(currentMoney(1.5));
- await expect(incrementDailySpend(conflictingMoney(10))).resolves.toMatchObject({
- money: currentMoney(1.5),
- });
- const row = harness.sqlite
- .prepare('SELECT cost_amount, cost_currency FROM daily_spend')
- .get() as { cost_amount: number; cost_currency: string };
- expect(row).toEqual({
- cost_amount: 1.5,
- cost_currency: DEFAULT_USAGE_CURRENCY,
- });
+ setActiveLedgerCurrency('USD');
+ await incrementDailySpend(usd(1.5));
+ setActiveLedgerCurrency('CNY');
+ await incrementDailySpend(cny(10));
+ setActiveLedgerCurrency('USD');
+ await incrementDailySpend(usd(2.5));
+
+ const rows = harness.sqlite
+ .prepare('SELECT cost_currency, cost_amount FROM daily_spend ORDER BY cost_currency')
+ .all() as Array<{ cost_currency: string; cost_amount: number }>;
+ expect(rows).toEqual([
+ { cost_currency: 'CNY', cost_amount: 10 },
+ { cost_currency: 'USD', cost_amount: 4 },
+ ]);
} finally {
harness.close();
}
});
- it('daily model usage ignores non-regional money but still records tokens', async () => {
+ it('reads back the row matching the active ledger currency', async () => {
const harness = createHarness();
try {
- await incrementDailyModelUsage({
- agentKind: 'claude-code',
- model: 'claude-opus-4-8',
- money: currentMoney(2),
- inputTokensDelta: 100,
- outputTokensDelta: 10,
- cacheReadTokensDelta: 0,
- cacheCreateTokensDelta: 0,
+ setActiveLedgerCurrency('CNY');
+ await incrementDailySpend(cny(149.13));
+ setActiveLedgerCurrency('USD');
+ await incrementDailySpend(usd(15.44));
+
+ // 展示侧仍是单币种:不跨币种求和(汇率是估算,混加会把两笔精确账单变成谁也对不上
+ // 的数),按当前账本币种挑那一行。
+ await expect(getTodaySpend()).resolves.toMatchObject({
+ amount: 15.44,
+ currency: 'USD',
});
- await incrementDailyModelUsage({
- agentKind: 'claude-code',
- model: 'claude-opus-4-8',
- money: conflictingMoney(13.4),
- inputTokensDelta: 50,
- outputTokensDelta: 5,
- cacheReadTokensDelta: 7,
- cacheCreateTokensDelta: 0,
+ setActiveLedgerCurrency('CNY');
+ await expect(getTodaySpend()).resolves.toMatchObject({
+ amount: 149.13,
+ currency: 'CNY',
});
-
- const row = harness.sqlite
- .prepare(
- `SELECT cost_amount, cost_currency, input_tokens, output_tokens, cache_read_tokens
- FROM daily_model_usage WHERE day = ?`,
- )
- .get(localDayKey()) as {
- cost_amount: number;
- cost_currency: string;
- input_tokens: number;
- output_tokens: number;
- cache_read_tokens: number;
- };
- expect(row.cost_currency).toBe(DEFAULT_USAGE_CURRENCY);
- expect(row.cost_amount).toBe(2);
- expect(row.input_tokens).toBe(150);
- expect(row.output_tokens).toBe(15);
- expect(row.cache_read_tokens).toBe(7);
} finally {
harness.close();
}
});
- it('rolls active old-currency rows forward on the first regional write', async () => {
+ it('returns per-day rows unfolded so the caller collapses after the currency is known', async () => {
+ // 回归护栏。折叠是一个依赖账本币种的决定,而账本币种要等报价快照恢复才确定。
+ // 若在 getAllSpendDays 内部折叠,冷启动时(usageHistory 与 getModelPricing 并发)
+ // 会先按兜底币种把本账号那一行丢掉,调用方再怎么等也拿不回来。
const harness = createHarness();
try {
- const day = localDayKey();
- const oldCurrency = conflictingMoney(1).currency;
- harness.sqlite
- .prepare(
- `INSERT INTO daily_spend
- (day, cost_amount, cost_currency, cost_is_approximate, updated_at)
- VALUES (?, 99, ?, 0, 1)`,
- )
- .run(day, oldCurrency);
- harness.sqlite
- .prepare(
- `INSERT INTO daily_model_usage
- (day, agent_kind, model, cost_amount, cost_currency, cost_is_approximate,
- input_tokens, output_tokens, cache_read_tokens, cache_create_tokens, updated_at)
- VALUES (?, 'claude-code', 'claude-opus-4-8', 88, ?, 0, 25, 3, 0, 0, 1)`,
- )
- .run(day, oldCurrency);
+ setActiveLedgerCurrency('CNY');
+ await incrementDailySpend(cny(149.13));
+ setActiveLedgerCurrency('USD');
+ await incrementDailySpend(usd(15.44));
- await incrementDailySpend(currentMoney(1.5));
- await incrementDailyModelUsage({
- agentKind: 'claude-code',
- model: 'claude-opus-4-8',
- money: currentMoney(2),
- inputTokensDelta: 50,
- outputTokensDelta: 5,
- cacheReadTokensDelta: 7,
- cacheCreateTokensDelta: 0,
- });
+ // 读侧不折叠:两个币种都原样返回,与当前账本币种无关。
+ const days = await getAllSpendDays();
+ expect(days).toHaveLength(1);
+ const monies = [...days[0].monies].sort((a, b) => a.currency.localeCompare(b.currency));
+ expect(monies.map((m) => [m.currency, m.amount])).toEqual([
+ ['CNY', 149.13],
+ ['USD', 15.44],
+ ]);
- expect(
- harness.sqlite
- .prepare('SELECT cost_amount, cost_currency FROM daily_spend WHERE day = ?')
- .get(day),
- ).toEqual({
- cost_amount: 1.5,
- cost_currency: DEFAULT_USAGE_CURRENCY,
+ // 折叠由调用方在币种确定后做,两个方向都能取到自己那一行。
+ expect(collapseDayMonies(days[0].monies, 'USD')).toMatchObject({
+ amount: 15.44,
+ currency: 'USD',
});
- expect(
- harness.sqlite
- .prepare(
- `SELECT cost_amount, cost_currency, input_tokens, output_tokens, cache_read_tokens
- FROM daily_model_usage WHERE day = ?`,
- )
- .get(day),
- ).toEqual({
- cost_amount: 2,
- cost_currency: DEFAULT_USAGE_CURRENCY,
- input_tokens: 75,
- output_tokens: 8,
- cache_read_tokens: 7,
+ expect(collapseDayMonies(days[0].monies, 'CNY')).toMatchObject({
+ amount: 149.13,
+ currency: 'CNY',
});
} finally {
harness.close();
@@ -206,17 +191,15 @@ describe('daily ledger currency invariant', () => {
it('accepts the account settlement currency even when it differs from the build region', async () => {
// 结算币种由服务端按账号所属租户下发,不是构建区域:CN 构建 + USD 结算账号是正常
- // 组合。基准若取构建区域,这些账号的每一笔都会被拒收 —— 等于完全不计费。
- // setActiveLedgerCurrency 由模型目录同步时写入(见 usage/modelPricing)。
+ // 组合。按区域判会把这些账号的每一笔都拒收 —— 等于完全不计费。
const harness = createHarness();
- const settlement = conflictingMoney(1).currency;
- setActiveLedgerCurrency(settlement);
try {
- await incrementDailySpend(conflictingMoney(1.5));
+ setActiveLedgerCurrency('USD');
+ await incrementDailySpend(usd(1.5));
await incrementDailyModelUsage({
agentKind: 'claude-code',
model: 'claude-opus-4-8',
- money: conflictingMoney(2),
+ money: usd(2),
inputTokensDelta: 100,
outputTokensDelta: 10,
cacheReadTokensDelta: 0,
@@ -225,20 +208,65 @@ describe('daily ledger currency invariant', () => {
expect(
harness.sqlite.prepare('SELECT cost_amount, cost_currency FROM daily_spend').get(),
- ).toEqual({ cost_amount: 1.5, cost_currency: settlement });
+ ).toEqual({ cost_amount: 1.5, cost_currency: 'USD' });
expect(
harness.sqlite
.prepare('SELECT cost_amount, cost_currency FROM daily_model_usage WHERE day = ?')
.get(localDayKey()),
- ).toMatchObject({ cost_amount: 2, cost_currency: settlement });
+ ).toMatchObject({ cost_amount: 2, cost_currency: 'USD' });
+ } finally {
+ harness.close();
+ }
+ });
- // 反向:此时构建默认币种才是异币种,仍应被拒收以保护已有账本。
- await incrementDailySpend(currentMoney(10));
- expect(
- harness.sqlite.prepare('SELECT cost_amount, cost_currency FROM daily_spend').get(),
- ).toEqual({ cost_amount: 1.5, cost_currency: settlement });
+ it('splits model usage rows per currency without dropping tokens', async () => {
+ const harness = createHarness();
+ try {
+ setActiveLedgerCurrency('USD');
+ await incrementDailyModelUsage({
+ agentKind: 'claude-code',
+ model: 'claude-opus-4-8',
+ money: usd(2),
+ inputTokensDelta: 100,
+ outputTokensDelta: 10,
+ cacheReadTokensDelta: 0,
+ cacheCreateTokensDelta: 0,
+ });
+ setActiveLedgerCurrency('CNY');
+ await incrementDailyModelUsage({
+ agentKind: 'claude-code',
+ model: 'claude-opus-4-8',
+ money: cny(13.4),
+ inputTokensDelta: 50,
+ outputTokensDelta: 5,
+ cacheReadTokensDelta: 7,
+ cacheCreateTokensDelta: 0,
+ });
+
+ const rows = harness.sqlite
+ .prepare(
+ `SELECT cost_currency, cost_amount, input_tokens, output_tokens, cache_read_tokens
+ FROM daily_model_usage WHERE day = ? ORDER BY cost_currency`,
+ )
+ .all(localDayKey()) as Array<Record<string, number | string>>;
+ // 金额分行互不覆盖;token 各自留在自己那行,合计仍是 150 / 15 / 7。
+ expect(rows).toEqual([
+ {
+ cost_currency: 'CNY',
+ cost_amount: 13.4,
+ input_tokens: 50,
+ output_tokens: 5,
+ cache_read_tokens: 7,
+ },
+ {
+ cost_currency: 'USD',
+ cost_amount: 2,
+ input_tokens: 100,
+ output_tokens: 10,
+ cache_read_tokens: 0,
+ },
+ ]);
} finally {
- __resetActiveLedgerCurrencyForTesting();
harness.close();
}
});
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.ts
index 4b158beb11..7c96583a78 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
@@ -601,10 +601,11 @@ function buildDailySpendUpsertQuery(
.values({
day,
costUsd: costUsdDelta,
+ costCurrency: 'USD',
updatedAt: ts,
})
.onConflictDoUpdate({
- target: dailySpend.day,
+ target: [dailySpend.day, dailySpend.costCurrency],
set: {
costUsd: sql`${dailySpend.costUsd} + ${costUsdDelta}`,
updatedAt: ts,
diff --git a/apps/desktop/src/main/localDb/__tests__/rebuildDailySpendMigration.test.ts b/apps/desktop/src/main/localDb/__tests__/rebuildDailySpendMigration.test.ts
new file mode 100644
index 0000000000..3d3902ebf8
--- /dev/null
+++ b/apps/desktop/src/main/localDb/__tests__/rebuildDailySpendMigration.test.ts
@@ -0,0 +1,165 @@
+import Database from 'better-sqlite3';
+import { describe, expect, it } from 'vitest';
+
+// Migration companion scripts intentionally use CommonJS so the runtime loader can replay them.
+const migration0085 =
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ require('../../../../drizzle/scripts/0085_skinny_iron_man.ts') as {
+ run(db: Database.Database): void;
+ };
+
+function setupDb(): Database.Database {
+ const db = new Database(':memory:');
+ db.exec(`
+ CREATE TABLE daily_spend (
+ day TEXT NOT NULL,
+ cost_usd REAL NOT NULL DEFAULT 0,
+ cost_amount REAL NOT NULL DEFAULT 0,
+ cost_currency TEXT NOT NULL DEFAULT 'USD',
+ cost_is_approximate INTEGER NOT NULL DEFAULT 0,
+ updated_at INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY (day, cost_currency)
+ );
+ CREATE TABLE messages (
+ id TEXT PRIMARY KEY NOT NULL,
+ created_at INTEGER,
+ rewind_at INTEGER,
+ agent_meta TEXT
+ );
+ `);
+ return db;
+}
+
+function dayTs(day: string, hour: number): number {
+ const [year, month, date] = day.split('-').map(Number);
+ return new Date(year, month - 1, date, hour, 0, 0, 0).getTime();
+}
+
+function insertMessage(
+ db: Database.Database,
+ id: string,
+ ts: number,
+ turnCost: unknown,
+ rewindAt: number | null = null,
+): void {
+ db.prepare('INSERT INTO messages (id, created_at, rewind_at, agent_meta) VALUES (?, ?, ?, ?)').run(
+ id,
+ ts,
+ rewindAt,
+ JSON.stringify({ turnCost }),
+ );
+}
+
+const usd = (amount: number) => ({
+ amount,
+ currency: 'USD',
+ approximate: false,
+ kind: 'actual-cost',
+});
+
+const cny = (amount: number) => ({
+ amount,
+ currency: 'CNY',
+ approximate: false,
+ kind: 'actual-cost',
+});
+
+function spendRows(db: Database.Database): Array<Record<string, unknown>> {
+ return db
+ .prepare('SELECT day, cost_currency, cost_amount FROM daily_spend ORDER BY day, cost_currency')
+ .all() as Array<Record<string, unknown>>;
+}
+
+describe('0085 daily_spend rebuild from message ledger', () => {
+ it('restores a day total that the old single-row schema had overwritten', () => {
+ // 复现真实事故:当天先累计了 CNY,账本币种翻成 USD 后旧写入路径用新金额覆盖整行,
+ // 149.13 永久消失、只剩 15.44。消息级 turnCost 从未丢过,据此重建。
+ const db = setupDb();
+ db.prepare(
+ `INSERT INTO daily_spend (day, cost_amount, cost_currency, updated_at) VALUES (?, ?, ?, ?)`,
+ ).run('2026-07-31', 15.44, 'USD', 1);
+
+ insertMessage(db, 'm1', dayTs('2026-07-31', 9), cny(100));
+ insertMessage(db, 'm2', dayTs('2026-07-31', 10), cny(49.13));
+ insertMessage(db, 'm3', dayTs('2026-07-31', 20), usd(15.44));
+
+ migration0085.run(db);
+
+ expect(spendRows(db)).toEqual([
+ { day: '2026-07-31', cost_currency: 'CNY', cost_amount: 149.13 },
+ { day: '2026-07-31', cost_currency: 'USD', cost_amount: 15.44 },
+ ]);
+ });
+
+ it('never lowers an existing total', () => {
+ // 有些费用不挂在消息上(scheduler 直接归因、历史 legacy 列),重建拿不到它们。
+ // 单调不减:重建只补齐被覆盖掉的部分,不会因为消息侧看不见就抹掉已记的账。
+ const db = setupDb();
+ db.prepare(
+ `INSERT INTO daily_spend (day, cost_amount, cost_currency, updated_at) VALUES (?, ?, ?, ?)`,
+ ).run('2026-07-30', 500, 'USD', 1);
+ insertMessage(db, 'm1', dayTs('2026-07-30', 9), usd(12));
+
+ migration0085.run(db);
+
+ expect(spendRows(db)).toEqual([
+ { day: '2026-07-30', cost_currency: 'USD', cost_amount: 500 },
+ ]);
+ });
+
+ it('skips rewound messages', () => {
+ const db = setupDb();
+ insertMessage(db, 'm1', dayTs('2026-07-29', 9), usd(10));
+ insertMessage(db, 'm2', dayTs('2026-07-29', 10), usd(99), 123);
+
+ migration0085.run(db);
+
+ expect(spendRows(db)).toEqual([
+ { day: '2026-07-29', cost_currency: 'USD', cost_amount: 10 },
+ ]);
+ });
+
+ it('is idempotent', () => {
+ const db = setupDb();
+ insertMessage(db, 'm1', dayTs('2026-07-28', 9), usd(3));
+ insertMessage(db, 'm2', dayTs('2026-07-28', 11), usd(4));
+
+ migration0085.run(db);
+ const first = spendRows(db);
+ migration0085.run(db);
+
+ expect(spendRows(db)).toEqual(first);
+ expect(first).toEqual([{ day: '2026-07-28', cost_currency: 'USD', cost_amount: 7 }]);
+ });
+
+ it('ignores malformed or zero money without throwing', () => {
+ const db = setupDb();
+ insertMessage(db, 'm1', dayTs('2026-07-27', 9), { amount: 0, currency: 'USD' });
+ insertMessage(db, 'm2', dayTs('2026-07-27', 10), { amount: 'nope', currency: 'USD' });
+ insertMessage(db, 'm3', dayTs('2026-07-27', 11), { amount: 5, currency: 'JPY' });
+ insertMessage(db, 'm4', dayTs('2026-07-27', 12), usd(2));
+ db.prepare('INSERT INTO messages (id, created_at, agent_meta) VALUES (?, ?, ?)').run(
+ 'm5',
+ dayTs('2026-07-27', 13),
+ '{"turnCost": not json',
+ );
+
+ expect(() => migration0085.run(db)).not.toThrow();
+ expect(spendRows(db)).toEqual([
+ { day: '2026-07-27', cost_currency: 'USD', cost_amount: 2 },
+ ]);
+ });
+
+ it('does nothing when the messages table has no cost data', () => {
+ const db = setupDb();
+ db.prepare(
+ `INSERT INTO daily_spend (day, cost_amount, cost_currency, updated_at) VALUES (?, ?, ?, ?)`,
+ ).run('2026-07-26', 42, 'USD', 1);
+
+ migration0085.run(db);
+
+ expect(spendRows(db)).toEqual([
+ { day: '2026-07-26', cost_currency: 'USD', cost_amount: 42 },
+ ]);
+ });
+});
diff --git a/apps/desktop/src/main/localDb/dailyModelUsage.ts b/apps/desktop/src/main/localDb/dailyModelUsage.ts
index c02ad6fdce..65020ea2e6 100644
--- a/apps/desktop/src/main/localDb/dailyModelUsage.ts
+++ b/apps/desktop/src/main/localDb/dailyModelUsage.ts
@@ -44,18 +44,19 @@ export async function incrementDailyModelUsage(
delta: DailyModelUsageDelta,
ts: number = Date.now(),
): Promise<void> {
- // 单币种行:只接受本账号的结算币种,基准取 currentLedgerCurrency() 而不是构建区域 ——
- // 结算币种由服务端按账号所属租户下发,不保证等于发行区域;按区域判会让以 USD 结算的
- // 账号每一行都只剩 token、金额永远是 0。
- // 异币种金额被忽略但 token 仍累计。
- const normalizedMoney = delta.money ? normalizeRegionalMoney(delta.money) : undefined;
+ // 每 (天, agent, 模型, 币种) 一行,各币种各自累加。异币种金额不再被丢弃,也不再覆盖
+ // 当天该模型的已有累计 —— 账本币种会因为换号、跨租户、上游漏发币种而切换,那两种
+ // 做法都会静默丢账。
+ const money = delta.money ? normalizeRegionalMoney(delta.money) : undefined;
const ledgerCurrency = currentLedgerCurrency();
- const money = normalizedMoney?.currency === ledgerCurrency ? normalizedMoney : undefined;
- if (normalizedMoney && !money) {
+ if (money && money.currency !== ledgerCurrency) {
log.warn(
- `daily model usage rejected currency mismatch: ${normalizedMoney.currency} != ${ledgerCurrency}`,
+ `daily model usage currency differs from ledger: ${money.currency} != ${ledgerCurrency}; ` +
+ 'recording into its own currency row',
);
}
+ // 纯 token 行(无金额)归到当前账本币种,让它和同轮的金额落在同一行。
+ const rowCurrency = money?.currency ?? ledgerCurrency;
const inputTokens = sanitizeTokens(delta.inputTokensDelta);
const outputTokens = sanitizeTokens(delta.outputTokensDelta);
const cacheReadTokens = sanitizeTokens(delta.cacheReadTokensDelta);
@@ -73,11 +74,6 @@ export async function incrementDailyModelUsage(
const day = localDayKey(ts);
const model = delta.model || 'unknown';
const db = getDbClient().drizzle;
- // 单币种行:错误币种金额被忽略但 token 仍累计。升级前当天若仍是旧币种,
- // 首笔当前币种费用重新起算该金额列;历史 token 不受币种影响继续累计。
- const sameCurrency = money
- ? sql`(${dailyModelUsage.costCurrency} IS NULL OR ${dailyModelUsage.costCurrency} = ${money.currency})`
- : sql`0`;
await db
.insert(dailyModelUsage)
.values({
@@ -85,7 +81,7 @@ export async function incrementDailyModelUsage(
agentKind: delta.agentKind,
model,
costAmount: money?.amount ?? 0,
- costCurrency: money?.currency ?? null,
+ costCurrency: rowCurrency,
costIsApproximate: money?.approximate ?? false,
inputTokens,
outputTokens,
@@ -94,15 +90,15 @@ export async function incrementDailyModelUsage(
updatedAt: ts,
})
.onConflictDoUpdate({
- target: [dailyModelUsage.day, dailyModelUsage.agentKind, dailyModelUsage.model],
+ target: [
+ dailyModelUsage.day,
+ dailyModelUsage.agentKind,
+ dailyModelUsage.model,
+ dailyModelUsage.costCurrency,
+ ],
set: {
- costAmount: money
- ? sql`CASE WHEN ${sameCurrency} THEN ${dailyModelUsage.costAmount} + ${money.amount} ELSE ${money.amount} END`
- : sql`${dailyModelUsage.costAmount}`,
- costCurrency: money?.currency ?? sql`${dailyModelUsage.costCurrency}`,
- costIsApproximate: money
- ? sql`CASE WHEN ${sameCurrency} THEN (${dailyModelUsage.costIsApproximate} OR ${money.approximate ? 1 : 0}) ELSE ${money.approximate ? 1 : 0} END`
- : sql`${dailyModelUsage.costIsApproximate}`,
+ costAmount: sql`${dailyModelUsage.costAmount} + ${money?.amount ?? 0}`,
+ costIsApproximate: sql`(${dailyModelUsage.costIsApproximate} OR ${money?.approximate ? 1 : 0})`,
inputTokens: sql`${dailyModelUsage.inputTokens} + ${inputTokens}`,
outputTokens: sql`${dailyModelUsage.outputTokens} + ${outputTokens}`,
cacheReadTokens: sql`${dailyModelUsage.cacheReadTokens} + ${cacheReadTokens}`,
diff --git a/apps/desktop/src/main/localDb/dailySpend.ts b/apps/desktop/src/main/localDb/dailySpend.ts
index 47b1b2dbef..33acad00c9 100644
--- a/apps/desktop/src/main/localDb/dailySpend.ts
+++ b/apps/desktop/src/main/localDb/dailySpend.ts
@@ -1,10 +1,12 @@
import { sql } from 'drizzle-orm';
import {
+ addCompatibleRegionalMoney,
addRegionalMoney,
legacyUsdMoney,
normalizeRegionalMoney,
zeroUsageMoney,
+ type MoneyCurrency,
type RegionalMoney,
} from '../../shared/regionalMoney.js';
import { dailySpend } from './schema.js';
@@ -22,16 +24,14 @@ export function localDayKey(ts: number = Date.now()): string {
return `${year}-${month}-${day}`;
}
-function rowMoney(
- row:
- | {
- costUsd: number;
- costAmount: number;
- costCurrency: 'CNY' | 'USD' | null;
- costIsApproximate: boolean;
- }
- | undefined,
-): RegionalMoney {
+interface SpendRow {
+ costUsd: number;
+ costAmount: number;
+ costCurrency: 'CNY' | 'USD' | null;
+ costIsApproximate: boolean;
+}
+
+function rowMoney(row: SpendRow | undefined): RegionalMoney {
const legacy = legacyUsdMoney(row?.costUsd ?? 0);
const current =
row?.costCurrency && row.costAmount > 0
@@ -48,8 +48,41 @@ function rowMoney(
return current ?? (legacy.amount > 0 ? legacy : zeroUsageMoney());
}
-async function getSpendForDay(day: string): Promise<RegionalMoney> {
- const row = await getDbClient()
+/** 一天里各币种各自的金额(每币种一行,故至多一种币出现一次)。 */
+function dayMonies(rows: readonly SpendRow[]): RegionalMoney[] {
+ return rows.map(rowMoney).filter((money) => money.amount > 0);
+}
+
+/**
+ * 把一天的多币种金额折叠成展示用的单值。
+ *
+ * 一天可能有多个币种行(换号 / 跨租户 / 上游漏发币种)。展示侧仍是单币种,按账本币种
+ * 挑那一行;账本币种缺席时 addCompatibleRegionalMoney 会挑真实计费里的第一种。
+ *
+ * 不做跨币种求和 —— 汇率是估算,混加会把两笔精确账单变成一个谁也对不上的数。挑不中的
+ * 行留在库里,账本币种切回去时自然重新可见。
+ *
+ * **币种参数必须由调用方显式传入**:折叠是一个依赖账本币种的决定,而账本币种在冷启动
+ * 期间要等报价快照恢复才确定。此前这里直接读 currentLedgerCurrency(),于是
+ * getAllSpendDays() 与 getModelPricing() 并发时会先按兜底币种把 CNY 行全丢掉,
+ * 调用方拿到的已经是折叠过的错值,首页整段历史短暂显示为 0。
+ */
+export function collapseDayMonies(
+ monies: readonly RegionalMoney[],
+ ledgerCurrency: MoneyCurrency,
+): RegionalMoney {
+ const zero = (): RegionalMoney => ({
+ amount: 0,
+ currency: ledgerCurrency,
+ approximate: false,
+ kind: 'actual-cost',
+ });
+ if (monies.length === 0) return zero();
+ return addCompatibleRegionalMoney(monies, ledgerCurrency) ?? zero();
+}
+
+async function getSpendMoniesForDay(day: string): Promise<RegionalMoney[]> {
+ const rows = await getDbClient()
.drizzle.select({
costUsd: dailySpend.costUsd,
costAmount: dailySpend.costAmount,
@@ -58,8 +91,16 @@ async function getSpendForDay(day: string): Promise<RegionalMoney> {
})
.from(dailySpend)
.where(sql`${dailySpend.day} = ${day}`)
- .get();
- return rowMoney(row);
+ .all();
+ return dayMonies(rows);
+}
+
+/**
+ * 写入路径专用:此处账本币种必然已就绪(记账链路在算钱之前就 await 过报价快照),
+ * 读侧的冷启动竞态在这里不成立。
+ */
+async function getSpendForDay(day: string): Promise<RegionalMoney> {
+ return collapseDayMonies(await getSpendMoniesForDay(day), currentLedgerCurrency());
}
export async function incrementDailySpend(
@@ -71,21 +112,18 @@ export async function incrementDailySpend(
if (!normalized || normalized.amount < 1e-10) {
return { day, money: await getSpendForDay(day) };
}
- // 单币种日账本:入口只接受本账号的结算币种。基准取 currentLedgerCurrency() 而不是
- // 构建区域 —— 结算币种由服务端按账号所属租户下发,不保证等于发行区域;按区域判会把
- // 以 USD 结算的账号在 CN 构建上的每一笔都拒收成不计费。
- // 异币种(脏数据 / 上游 bug)仍然拒收,避免污染已有账本。
+ // 每天每币种一行,各自累加。异币种不再拒收,也不再覆盖当天累计 —— 那两种做法一个
+ // 丢当笔、一个丢全天,而账本币种会因为完全正常的原因(换号、跨租户、上游漏发币种)
+ // 发生切换。如实入到它自己的币种行,展示侧再按当前账本币种挑。
const ledgerCurrency = currentLedgerCurrency();
if (normalized.currency !== ledgerCurrency) {
+ // 不是错误,但值得留痕:出现异币种通常意味着账本币种刚切换过,或上游报价口径变了。
log.warn(
- `daily spend rejected currency mismatch: ${normalized.currency} != ${ledgerCurrency}`,
+ `daily spend currency differs from ledger: ${normalized.currency} != ${ledgerCurrency}; ` +
+ 'recording into its own currency row',
);
- return { day, money: await getSpendForDay(day) };
}
const db = getDbClient().drizzle;
- // 升级前 / 换号前当天若仍是旧币种,首笔新费用从当前账本币种重新起算;不猜测或换算
- // 旧聚合值,也不让当天后续费用永久停记。CASE 与写入保持原子,避免并发混加不同单位。
- const sameCurrency = sql`(${dailySpend.costCurrency} IS NULL OR ${dailySpend.costCurrency} = ${normalized.currency})`;
await db
.insert(dailySpend)
.values({
@@ -96,11 +134,10 @@ export async function incrementDailySpend(
updatedAt: ts,
})
.onConflictDoUpdate({
- target: dailySpend.day,
+ target: [dailySpend.day, dailySpend.costCurrency],
set: {
- costAmount: sql`CASE WHEN ${sameCurrency} THEN ${dailySpend.costAmount} + ${normalized.amount} ELSE ${normalized.amount} END`,
- costCurrency: normalized.currency,
- costIsApproximate: sql`CASE WHEN ${sameCurrency} THEN (${dailySpend.costIsApproximate} OR ${normalized.approximate ? 1 : 0}) ELSE ${normalized.approximate ? 1 : 0} END`,
+ costAmount: sql`${dailySpend.costAmount} + ${normalized.amount}`,
+ costIsApproximate: sql`(${dailySpend.costIsApproximate} OR ${normalized.approximate ? 1 : 0})`,
updatedAt: ts,
},
})
@@ -109,11 +146,23 @@ export async function incrementDailySpend(
return { day, money: persisted };
}
+/**
+ * 今日金额。调用方须保证账本币种已就绪(见 usageBroadcaster.readTodaySpend),
+ * 否则冷启动首帧会按兜底币种折叠掉其它币种行。
+ */
export function getTodaySpend(): Promise<RegionalMoney> {
return getSpendForDay(localDayKey());
}
-export async function getAllSpendDays(): Promise<Array<{ day: string; money: RegionalMoney }>> {
+/**
+ * 每日金额,**按币种拆开不折叠**。
+ *
+ * 与 getModelUsageSince 同口径:读侧只负责把事实取出来,「按哪个币种展示」交给调用方在
+ * 账本币种确定之后决定。折叠用 collapseDayMonies。
+ */
+export async function getAllSpendDays(): Promise<
+ Array<{ day: string; monies: RegionalMoney[] }>
+> {
const rows = await getDbClient()
.drizzle.select({
day: dailySpend.day,
@@ -125,5 +174,11 @@ export async function getAllSpendDays(): Promise<Array<{ day: string; money: Reg
.from(dailySpend)
.orderBy(dailySpend.day)
.all();
- return rows.map((row) => ({ day: row.day, money: rowMoney(row) }));
+ const byDay = new Map<string, SpendRow[]>();
+ for (const row of rows) {
+ const bucket = byDay.get(row.day);
+ if (bucket) bucket.push(row);
+ else byDay.set(row.day, [row]);
+ }
+ return [...byDay.entries()].map(([day, dayRows]) => ({ day, monies: dayMonies(dayRows) }));
}
diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.ts
index 671a37f008..220ac9824b 100644
--- a/apps/desktop/src/main/localDb/schema.ts
+++ b/apps/desktop/src/main/localDb/schema.ts
@@ -1060,20 +1060,32 @@ export const embeddingMeta = sqliteTable('embedding_meta', {
* - 同账号用多设备时本表数字会不一致 — 设计取舍, chip 点击跳 web 看完整账。
*
* 历史数据: 不 backfill — 安装迁移后从 0 开始累计 (用户明确接受)。
+ *
+ * 主键含币种: 一天一行放不下两种币种。此前主键只有 day, 账本币种切换时写入侧只能
+ * 二选一 —— 实现选择了"用新币种的金额覆盖当天累计", 于是每翻转一次就静默丢掉当天
+ * 已记的全部花费。按 (day, currency) 分行后两种币种各自累加, 读侧再按当前账本币种
+ * 取用; 换号、跨租户、上游漏发币种都不再造成数据丢失。
*/
-export const dailySpend = sqliteTable('daily_spend', {
- /** 本地时区 YYYY-MM-DD 字符串。 */
- 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(),
-});
+export const dailySpend = sqliteTable(
+ 'daily_spend',
+ {
+ /** 本地时区 YYYY-MM-DD 字符串。 */
+ day: text('day').notNull(),
+ /** 当日累计 USD (real)。SDK 单 turn 的 cost 通常是小数 (如 0.0391)。 */
+ costUsd: real('cost_usd').notNull().default(0),
+ costAmount: real('cost_amount').notNull().default(0),
+ /** 该行金额的币种。历史 NULL 行在迁移时按其 USD 口径填为 'USD'。 */
+ costCurrency: text('cost_currency', { enum: ['CNY', 'USD'] }).notNull().default('USD'),
+ costIsApproximate: integer('cost_is_approximate', { mode: 'boolean' })
+ .notNull()
+ .default(false),
+ /** 最后一次更新的 unix ms。 */
+ updatedAt: integer('updated_at').notNull(),
+ },
+ (t) => ({
+ pk: primaryKey({ columns: [t.day, t.costCurrency] }),
+ }),
+);
/**
* 每日按模型用量聚合表 (daily_model_usage) — 支撑首页用量仪表盘的"按模型拆分"。
@@ -1088,6 +1100,9 @@ export const dailySpend = sqliteTable('daily_spend', {
* 本表只做按模型的拆分展示, 两边求和因舍入可能有微小差异 — 设计取舍。
*
* 历史数据: 不 backfill — 上线后从 0 开始积累。
+ *
+ * 主键含币种: 理由同 daily_spend —— 单行单币种会在账本币种切换时把当天该模型已累计
+ * 的金额覆盖掉。
*/
export const dailyModelUsage = sqliteTable(
'daily_model_usage',
@@ -1101,7 +1116,8 @@ export const dailyModelUsage = sqliteTable(
/** 当日该模型累计 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'] }),
+ /** 该行金额的币种。无金额的纯 token 行与历史 NULL 行迁移时填为 'USD'。 */
+ costCurrency: text('cost_currency', { enum: ['CNY', 'USD'] }).notNull().default('USD'),
costIsApproximate: integer('cost_is_approximate', { mode: 'boolean' })
.notNull()
.default(false),
@@ -1114,7 +1130,7 @@ export const dailyModelUsage = sqliteTable(
},
(t) => ({
// day 开头 → 近 N 天范围扫描直接走 PK 索引, 无需额外 index。
- pk: primaryKey({ columns: [t.day, t.agentKind, t.model] }),
+ pk: primaryKey({ columns: [t.day, t.agentKind, t.model, t.costCurrency] }),
}),
);
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 61fa31e406..feae5347b7 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -298,7 +298,7 @@ import { detectClaudeModelMismatch } from '../../shared/modelMismatch.js';
import { triggerClaudeAccountUsageRefresh } from '../usage/claudeAccountUsage.js';
import { broadcastEffectiveModelPricing, getCodexProviderSubscriptionValuePrice, getGatewayAccountCurrency, getModelPriceQuote, getModelPricing, getModelPricingForModel, getSubscriptionDirectValuePrice } from '../usage/modelPricing.js';
import { clearModelPriceOverride, stageProviderModelPriceOverridesClear, readModelPriceOverrideView, setModelPriceOverride } from '../usage/modelPriceOverrideStore.js';
-import { computeModelUsageDeltas, type ModelUsageCumulative, type ModelUsageDeltaEntry } from '../usage/modelUsageDelta.js';
+import { computeModelUsageDeltas, detectOutputLag, type ModelUsageCumulative, type ModelUsageDeltaEntry } from '../usage/modelUsageDelta.js';
import { claudeSubscriptionUsageModelKey, codexApiUsageModelKey, codexSubscriptionUsageModelKey } from '../usage/usageHistory.js';
import { billingRouteForExplicitProvider, buildClaudeTurnUsageDetails, computePriceQuoteTurnMoney, estimateClaudeSubscriptionTurnValue, isAnthropicModel, normalizeModelIdForPricing, resolveClaudeTurnCostSinks, type BillingRoute } from '../usage/turnCostCalculator.js';
import { CHATGPT_MODEL_PREFIX, XAI_MODEL_PREFIX, isSubscriptionDirectModel } from '../../shared/subscriptionModels.js';
@@ -3222,6 +3222,20 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
// 判定主线被上游静默替换(如 fable-5 高负载被路由到 opus-4-8),把标记挂到本轮
// 收尾 assistant 的 agent_meta 上(AssistantMessage 渲染降级提示行)。
// fire-and-forget,与记账 sink 互不阻塞;判定纯函数见 shared/modelMismatch.ts。
+ if (modelUsageDeltas && detectOutputLag(modelUsageDeltas)) {
+ // 上游在 done 时点还没结算本轮输出(实测 Vertex),这一轮的费用会偏低、下一轮偏高。
+ // 总量不丢,只是归属错位;不做纠正的理由见 usage/modelUsageDelta 文件头。
+ log.warn(
+ `turn output likely lagging upstream settlement (session=${session.id}): ` +
+ modelUsageDeltas
+ .map(
+ (d) =>
+ `${d.model} out=${d.outputTokensDelta} in=${d.inputTokensDelta} ` +
+ `cacheRead=${d.cacheReadTokensDelta} cacheCreate=${d.cacheCreateTokensDelta}`,
+ )
+ .join('; '),
+ );
+ }
if (turnAssistantPersistId && modelUsageDeltas && modelUsageDeltas.length > 0) {
const mismatchClientId = turnAssistantPersistId;
const actualEntries = modelUsageDeltas.map((d) => ({
diff --git a/apps/desktop/src/main/usage/__tests__/accountCurrencyStore.test.ts b/apps/desktop/src/main/usage/__tests__/accountCurrencyStore.test.ts
new file mode 100644
index 0000000000..6066f8bc64
--- /dev/null
+++ b/apps/desktop/src/main/usage/__tests__/accountCurrencyStore.test.ts
@@ -0,0 +1,202 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtemp, readdir, readFile, rm, writeFile, mkdir } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+const mocks = vi.hoisted(() => ({
+ getCurrentDbClientUserId: vi.fn(() => 'user-a' as string | null),
+ electronAppGetPath: vi.fn(() => ''),
+}));
+
+vi.mock('electron', () => ({
+ app: { getPath: mocks.electronAppGetPath },
+}));
+vi.mock('../../logger', () => ({
+ createLogger: () => ({
+ info: vi.fn(),
+ debug: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ }),
+}));
+vi.mock('../../localDb/client/current', () => ({
+ getCurrentDbClientUserId: mocks.getCurrentDbClientUserId,
+}));
+
+import {
+ __resetAccountCurrencyStoreForTesting,
+ hydrateAccountCurrency,
+ noteActiveAccount,
+ rememberAccountCurrency,
+} from '../accountCurrencyStore';
+import {
+ __resetActiveLedgerCurrencyForTesting,
+ currentLedgerCurrency,
+ isLedgerCurrencyKnown,
+} from '../ledgerCurrency';
+
+let tempUserDataDir: string | null = null;
+
+function storeFile(): string {
+ if (!tempUserDataDir) throw new Error('temp userData is not initialized');
+ return path.join(tempUserDataDir, 'cache', 'ledger-currency.json');
+}
+
+async function writeStore(entries: Record<string, string>): Promise<void> {
+ const file = storeFile();
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, JSON.stringify({ version: 1, entries }), 'utf8');
+}
+
+/** 等 rememberAccountCurrency 的串行写链跑完(它是 fire-and-forget)。 */
+async function flushWrites(): Promise<void> {
+ for (let i = 0; i < 20; i += 1) await Promise.resolve();
+ await new Promise((resolve) => setTimeout(resolve, 10));
+}
+
+beforeEach(async () => {
+ tempUserDataDir = await mkdtemp(path.join(os.tmpdir(), 'cindy-ledger-currency-'));
+ mocks.electronAppGetPath.mockReturnValue(tempUserDataDir);
+ mocks.getCurrentDbClientUserId.mockReturnValue('user-a');
+ __resetAccountCurrencyStoreForTesting();
+ __resetActiveLedgerCurrencyForTesting();
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ if (tempUserDataDir) {
+ await rm(tempUserDataDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
+ tempUserDataDir = null;
+ }
+});
+
+describe('hydrate across an account switch', () => {
+ // 不变量:跨越 await 的账号相关写入,只有在这段 await 期间**账号身份一次都没变过**
+ // 时才允许提交。
+ //
+ // 判据必须是账号代际号而不是「当前 userId 是否还等于发起时的 userId」——后者挡得住
+ // A→B,挡不住 A→B→A:切回来之后 userId 重新相等,一份在 B 期间就已过期的读取结果
+ // 会被当成有效值写进 lastKnown。
+ //
+ // 表驱动交错序列而不是逐条孤立用例:ABA 与 ABCA 两行对「只比 userId」的实现必然
+ // 失败,「期间重复 note 同一账号」一行则对「每次 note 都递增代际」的实现失败 ——
+ // 两个方向都能把错误修法区分出来。
+ const interleavings: Array<{ name: string; during: string[]; committed: boolean }> = [
+ { name: '期间无任何账号事件', during: [], committed: true },
+ { name: '期间重复 note 同一账号', during: ['user-a', 'user-a'], committed: true },
+ { name: '切走未回 (A→B)', during: ['user-b'], committed: false },
+ { name: '切走又切回 (A→B→A)', during: ['user-b', 'user-a'], committed: false },
+ { name: '绕一圈再回 (A→B→C→A)', during: ['user-b', 'user-c', 'user-a'], committed: false },
+ ];
+
+ for (const { name, during, committed } of interleavings) {
+ it(`${committed ? 'commits' : 'discards'} the hydrate — ${name}`, async () => {
+ await writeStore({ 'user-a': 'CNY', 'user-b': 'USD', 'user-c': 'USD' });
+
+ const pending = hydrateAccountCurrency('user-a');
+ // await 期间的账号事件(真实链路里是 replaceGatewayModelPricing 的同步 noteActiveAccount)。
+ for (const userId of during) noteActiveAccount(userId);
+
+ await expect(pending).resolves.toBe(committed ? 'CNY' : null);
+ if (committed) {
+ expect(currentLedgerCurrency()).toBe('CNY');
+ } else {
+ // 丢弃时绝不能把 A 的币种留在账本上,回退链要回到「上次已知 → USD」。
+ expect(isLedgerCurrencyKnown()).toBe(false);
+ expect(currentLedgerCurrency()).toBe('USD');
+ }
+ });
+ }
+
+ it('hydrates normally when the account stays put', async () => {
+ await writeStore({ 'user-a': 'CNY' });
+ await expect(hydrateAccountCurrency('user-a')).resolves.toBe('CNY');
+ expect(currentLedgerCurrency()).toBe('CNY');
+ });
+
+ it('drops the previous account currency on switch', async () => {
+ await writeStore({ 'user-a': 'CNY' });
+ await hydrateAccountCurrency('user-a');
+ expect(currentLedgerCurrency()).toBe('CNY');
+
+ noteActiveAccount('user-b');
+ expect(isLedgerCurrencyKnown()).toBe(false);
+ expect(currentLedgerCurrency()).toBe('USD');
+ });
+
+ it('returns null without touching the ledger when no user is known', async () => {
+ mocks.getCurrentDbClientUserId.mockReturnValue(null);
+ await expect(hydrateAccountCurrency()).resolves.toBeNull();
+ expect(isLedgerCurrencyKnown()).toBe(false);
+ });
+});
+
+describe('persistence durability', () => {
+ it('writes atomically and leaves no temp file behind', async () => {
+ // 直接覆盖写会在崩溃 / 断电时留下截断 JSON,readEntries 解析失败后把 entries 当空,
+ // 整份币种快照丢失 —— 冷启动退回兜底币种,正是本 PR 要修的那类错账。
+ rememberAccountCurrency('user-a', 'CNY');
+ await flushWrites();
+
+ const raw = await readFile(storeFile(), 'utf8');
+ expect(JSON.parse(raw)).toEqual({ version: 1, entries: { 'user-a': 'CNY' } });
+
+ const leftovers = (await readdir(path.dirname(storeFile()))).filter((name) =>
+ name.endsWith('.tmp'),
+ );
+ expect(leftovers).toEqual([]);
+ });
+
+ it('retries after a transient write failure instead of giving up for the process', async () => {
+ // memo 表示「磁盘上是什么」。抢在落位前更新它,会让同值短路把后续同步一并跳过 ——
+ // 一次瞬时写失败就变成本进程再也不重试,重启后报价缓存又恰好失效时,CNY 账号会
+ // 丢掉这份独立快照并回落 USD。
+ const fsp = await import('node:fs/promises');
+ const renameSpy = vi
+ .spyOn(fsp.default, 'rename')
+ .mockRejectedValueOnce(new Error('EBUSY: transient'));
+
+ rememberAccountCurrency('user-a', 'CNY');
+ await flushWrites();
+ expect(renameSpy).toHaveBeenCalledTimes(1);
+ await expect(readFile(storeFile(), 'utf8').catch(() => null)).resolves.toBeNull();
+
+ // 同一账号同一币种再来一次:不能被同值短路吃掉。
+ renameSpy.mockRestore();
+ rememberAccountCurrency('user-a', 'CNY');
+ await flushWrites();
+ expect(JSON.parse(await readFile(storeFile(), 'utf8')).entries).toEqual({
+ 'user-a': 'CNY',
+ });
+ });
+
+ it('keeps other accounts when appending a new one', async () => {
+ await writeStore({ 'user-b': 'USD' });
+ rememberAccountCurrency('user-a', 'CNY');
+ await flushWrites();
+
+ expect(JSON.parse(await readFile(storeFile(), 'utf8')).entries).toEqual({
+ 'user-b': 'USD',
+ 'user-a': 'CNY',
+ });
+ });
+
+ it('treats a truncated store as empty instead of throwing', async () => {
+ const file = storeFile();
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, '{"version":1,"entr', 'utf8');
+
+ await expect(hydrateAccountCurrency('user-a')).resolves.toBeNull();
+ expect(isLedgerCurrencyKnown()).toBe(false);
+ });
+
+ it('ignores a store written by a future version', async () => {
+ await mkdir(path.dirname(storeFile()), { recursive: true });
+ await writeFile(
+ storeFile(),
+ JSON.stringify({ version: 99, entries: { 'user-a': 'CNY' } }),
+ 'utf8',
+ );
+ await expect(hydrateAccountCurrency('user-a')).resolves.toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/usage/__tests__/ledgerCurrency.test.ts b/apps/desktop/src/main/usage/__tests__/ledgerCurrency.test.ts
new file mode 100644
index 0000000000..e36d36eb5b
--- /dev/null
+++ b/apps/desktop/src/main/usage/__tests__/ledgerCurrency.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it, beforeEach } from 'vitest';
+
+import { DEFAULT_USAGE_CURRENCY } from '../../../shared/regionalMoney';
+import {
+ LEDGER_CURRENCY_FALLBACK,
+ __resetActiveLedgerCurrencyForTesting,
+ currentLedgerCurrency,
+ hydrateLastKnownLedgerCurrency,
+ isLedgerCurrencyKnown,
+ resetLedgerCurrencyForAccountSwitch,
+ setActiveLedgerCurrency,
+} from '../ledgerCurrency';
+
+describe('ledger currency fallback chain', () => {
+ beforeEach(() => {
+ __resetActiveLedgerCurrencyForTesting();
+ });
+
+ it('falls back to USD rather than the build region when nothing is known', () => {
+ // 这是整组修复的核心不变量。此前兜底取构建区域币种(CN 构建 = CNY),而报价数值
+ // 由服务端给定、恒为 USD 口径 —— 服务端某次漏发 currency 就会把 USD 数字盖上 CNY
+ // 戳,既不换算也不拒收,产生 6.7 倍量级的错账。USD 是 SDK 自报费用与全部参考价表
+ // 的原生口径,兜底成它最多是符号显示得保守,不会算错。
+ expect(isLedgerCurrencyKnown()).toBe(false);
+ expect(currentLedgerCurrency()).toBe('USD');
+ expect(LEDGER_CURRENCY_FALLBACK).toBe('USD');
+ });
+
+ it('keeps the last known currency when a sync fails to confirm one', () => {
+ // active 会因为完全正常的原因变成未知:目录同步在途、缓存 scope 失效、登出重登。
+ // 若这些瞬时状态回落到兜底值,账本币种就会在两种币种之间来回翻,而下游账本按币种
+ // 分行/取用,翻转会让展示值忽大忽小。
+ setActiveLedgerCurrency('CNY');
+ expect(currentLedgerCurrency()).toBe('CNY');
+
+ setActiveLedgerCurrency(null);
+ expect(currentLedgerCurrency()).toBe('CNY');
+ expect(isLedgerCurrencyKnown()).toBe(true);
+ });
+
+ it('lets a newly confirmed currency win over the last known one', () => {
+ setActiveLedgerCurrency('CNY');
+ setActiveLedgerCurrency('USD');
+ expect(currentLedgerCurrency()).toBe('USD');
+ });
+
+ it('hydrates a persisted currency only while nothing is known yet', () => {
+ hydrateLastKnownLedgerCurrency('CNY');
+ expect(currentLedgerCurrency()).toBe('CNY');
+
+ // 磁盘快照可能比当前登录账号旧,绝不能覆盖本进程已经确认过的币种。
+ setActiveLedgerCurrency('USD');
+ hydrateLastKnownLedgerCurrency('CNY');
+ setActiveLedgerCurrency(null);
+ expect(currentLedgerCurrency()).toBe('USD');
+ });
+
+ it('ignores a null hydrate', () => {
+ hydrateLastKnownLedgerCurrency(null);
+ expect(isLedgerCurrencyKnown()).toBe(false);
+ expect(currentLedgerCurrency()).toBe('USD');
+ });
+
+ it('drops the last known currency at an account boundary', () => {
+ // lastKnown 的作用是熬过同一账号的瞬时未知。跨账号沿用就成了记错账:新账号的目录
+ // 若恰好没声明币种,会静默继承上一个账号的结算币种。
+ setActiveLedgerCurrency('CNY');
+ resetLedgerCurrencyForAccountSwitch();
+ expect(isLedgerCurrencyKnown()).toBe(false);
+ expect(currentLedgerCurrency()).toBe('USD');
+ });
+
+ it('does not read the build region at all', () => {
+ // 回归护栏:构建区域一旦重新参与回退,CN 构建就会再次把 USD 口径数值记成 CNY。
+ // 这条断言在 global 构建上恒真,在 cn 构建上才有区分度 —— 后者正是出过事的组合。
+ if (DEFAULT_USAGE_CURRENCY === 'CNY') {
+ expect(currentLedgerCurrency()).not.toBe(DEFAULT_USAGE_CURRENCY);
+ }
+ expect(currentLedgerCurrency()).toBe('USD');
+ });
+});
diff --git a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts b/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
index 429420eb9c..311490c95e 100644
--- a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
@@ -83,8 +83,10 @@ import {
} from '../modelPricing';
let tempUserDataDir: string | null = null;
-const EXPECTED_GATEWAY_CURRENCY =
- CURRENT_CINDY_REGION === 'global' ? 'USD' : 'CNY';
+// 目录整份没声明 currency 时的回落值。不再按构建区域推断 —— 服务端漏发 currency 时
+// 按区域猜会把 USD 口径的报价数值盖上 CNY 戳,产生 6.7 倍量级的错账。回落链是
+// 「上次已知 → USD」(见 usage/ledgerCurrency),测试从干净状态起跑,所以是 USD。
+const EXPECTED_GATEWAY_CURRENCY = 'USD';
function userDataPath(...segments: string[]): string {
if (!tempUserDataDir) throw new Error('temp userData is not initialized');
@@ -157,6 +159,8 @@ describe('gateway model pricing projection', () => {
cacheReadPerMtok: 0.3,
cacheCreatePerMtok: 3.75,
costDiscount: 0.4,
+ // 这批 model 都没声明 currency,回落值是本地推断的 —— 下游据此把金额标成估算。
+ currencyInferred: true,
},
'codex/gpt-5.5': {
providerId: 'xd',
@@ -167,6 +171,7 @@ describe('gateway model pricing projection', () => {
inputPerMtok: 2,
outputPerMtok: 8,
cacheReadPerMtok: expect.closeTo(0.2),
+ currencyInferred: true,
},
},
});
@@ -300,9 +305,10 @@ describe('pricing cache lifecycle', () => {
await vi.waitFor(async () => {
const raw = JSON.parse(await readFile(userDataPath('cache', 'model-pricing.json'), 'utf8'));
expect(raw).toMatchObject({
- // 账号币种与报价同快照持久化后升到 8:旧缓存缺少账号币种,
- // 必须靠版本号失效掉。改缓存结构时同步这里。
- version: 8,
+ // 币种回落不再按构建区域猜之后升到 9:v8 快照里那些按区域兜底写入的
+ // accountCurrency 与 quote 没有 currencyInferred 标记,复用会让猜出来的币种
+ // 重新冒充精确报价。改缓存结构或币种语义时同步这里。
+ version: 9,
scope: expectedScope(),
pricing,
});
@@ -402,6 +408,44 @@ describe('pricing cache lifecycle', () => {
});
});
+ it('discards a v8 snapshot whose currency was guessed by build region', async () => {
+ // 回归护栏。v8 快照里的 accountCurrency 与 quote 币种可能是旧版本按构建区域兜底
+ // 写进去的,而那一版还没有 currencyInferred 字段 —— 无从分辨「服务端声明的」与
+ // 「本地猜的」。若继续复用,离线或 /models 失败时猜出来的币种会重新冒充精确报价,
+ // 正好绕过本次修复。只能靠版本号整份作废。
+ await mkdir(userDataPath('cache'), { recursive: true });
+ await writeFile(
+ userDataPath('cache', 'model-pricing.json'),
+ JSON.stringify({
+ version: 8,
+ scope: expectedScope(),
+ fetchedAt: Date.now(),
+ accountCurrency: 'CNY',
+ pricing: {
+ xd: {
+ 'gpt-5.5': {
+ providerId: 'xd',
+ modelId: 'gpt-5.5',
+ currency: 'CNY',
+ source: 'gateway',
+ approximate: false,
+ inputPerMtok: 5,
+ outputPerMtok: 30,
+ },
+ },
+ },
+ }),
+ 'utf8',
+ );
+
+ __resetActiveLedgerCurrencyForTesting();
+ const hydrated = await getModelPricing();
+ // 那份 v8 的 xd 报价一条都不能进来(registry 参考价不受影响,另有来源)。
+ expect(hydrated?.xd).toBeUndefined();
+ // 账本币种也不能被它带偏,回退链重新从「上次已知 → USD」起算。
+ expect(currentLedgerCurrency()).toBe('USD');
+ });
+
it('does not hydrate pricing written for an older gateway key identity', async () => {
replaceGatewayModelPricing([
{
diff --git a/apps/desktop/src/main/usage/__tests__/turnCostCurrencyTrust.test.ts b/apps/desktop/src/main/usage/__tests__/turnCostCurrencyTrust.test.ts
new file mode 100644
index 0000000000..21efe297be
--- /dev/null
+++ b/apps/desktop/src/main/usage/__tests__/turnCostCurrencyTrust.test.ts
@@ -0,0 +1,154 @@
+import { describe, expect, it, afterEach } from 'vitest';
+
+import { __resetActiveLedgerCurrencyForTesting } from '../ledgerCurrency';
+import { detectOutputLag, type ModelUsageDeltaEntry } from '../modelUsageDelta';
+import {
+ computePriceQuoteTurnMoney,
+ normalizeModelIdForPricing,
+ resolveTurnCost,
+ type TurnPricingContext,
+} from '../turnCostCalculator';
+import type { ModelPriceQuote, ModelPricingCatalog } from '../../../shared/regionalMoney';
+
+const XD_GATEWAY: TurnPricingContext = {
+ providerId: 'xd',
+ billingRoute: 'xd-gateway',
+ region: 'global',
+};
+
+const TOKENS = {
+ inputTokens: 1_000,
+ outputTokens: 1_000,
+ cacheReadTokens: 0,
+ cacheCreateTokens: 0,
+};
+
+function gatewayQuote(modelId: string, overrides: Partial<ModelPriceQuote> = {}): ModelPriceQuote {
+ return {
+ providerId: 'xd',
+ modelId,
+ currency: 'USD',
+ source: 'gateway',
+ approximate: false,
+ inputPerMtok: 10,
+ outputPerMtok: 50,
+ ...overrides,
+ };
+}
+
+function catalog(...quotes: ModelPriceQuote[]): ModelPricingCatalog {
+ const xd: Record<string, ModelPriceQuote> = {};
+ for (const quote of quotes) xd[quote.modelId] = quote;
+ return { xd };
+}
+
+afterEach(() => {
+ __resetActiveLedgerCurrencyForTesting();
+});
+
+describe('inferred currency downgrades the money to an estimate', () => {
+ it('marks money approximate when the quote currency was guessed locally', () => {
+ // 报价数值来自服务端、币种由本地推断时,这一笔能不能和账单对上取决于猜得对不对。
+ // 金额仍是真实计费(kind 保持 actual-cost,否则会被并进订阅价值统计),但不能再
+ // 自称精确。
+ const money = computePriceQuoteTurnMoney(
+ TOKENS,
+ gatewayQuote('claude-fable-5', { currencyInferred: true }),
+ 'USD',
+ );
+ expect(money).toMatchObject({
+ currency: 'USD',
+ approximate: true,
+ kind: 'actual-cost',
+ });
+ expect(money?.estimateReasons).toContain('inferred-currency');
+ });
+
+ it('keeps a server-declared currency exact', () => {
+ const money = computePriceQuoteTurnMoney(TOKENS, gatewayQuote('claude-fable-5'), 'USD');
+ expect(money).toMatchObject({ approximate: false, kind: 'actual-cost' });
+ expect(money?.estimateReasons).toBeUndefined();
+ });
+});
+
+describe('long-context turns pick the right pricing band', () => {
+ // 定档只看本轮实际 input token 落进哪个 band,不看模型 id 的 `[1m]` 后缀 ——
+ // 后缀只说明会话开了大窗口,不代表这一轮真的超过阈值。
+ const BANDED = gatewayQuote('claude-fable-5', {
+ inputTokenPriceBands: [
+ { minInputTokens: 200_001, inputPerMtok: 20, outputPerMtok: 75, cacheReadPerMtok: 2 },
+ ],
+ });
+
+ it('charges the long-context band once the turn crosses the threshold', () => {
+ // 实测形态:40 万 token 上下文的轮次此前一律按 200K 档标准价记账。
+ const resolved = resolveTurnCost({
+ rawModel: 'claude-fable-5[1m]',
+ tokens: {
+ inputTokens: 1_000,
+ outputTokens: 1_000,
+ cacheReadTokens: 400_000,
+ cacheCreateTokens: 0,
+ },
+ pricing: catalog(BANDED),
+ context: XD_GATEWAY,
+ });
+ // 1000*20 + 1000*75 + 400000*2 = 895_000 → 0.895
+ expect(resolved.money?.amount).toBeCloseTo(0.895, 10);
+ });
+
+ it('stays on the baseline for a short turn of the same model', () => {
+ const resolved = resolveTurnCost({
+ rawModel: 'claude-fable-5[1m]',
+ tokens: TOKENS,
+ pricing: catalog(BANDED),
+ context: XD_GATEWAY,
+ });
+ // 1000*10 + 1000*50 = 60_000 → 0.06,与不带后缀的同轮一致。
+ expect(resolved.money?.amount).toBeCloseTo(0.06, 10);
+ });
+
+ it('normalizes the variant suffix away for catalog lookup', () => {
+ const resolved = resolveTurnCost({
+ rawModel: 'claude-fable-5[1m]',
+ tokens: TOKENS,
+ pricing: catalog(gatewayQuote('claude-fable-5')),
+ context: XD_GATEWAY,
+ });
+ expect(resolved.model).toBe('claude-fable-5');
+ expect(resolved.money?.approximate).toBe(false);
+ expect(normalizeModelIdForPricing('claude-fable-5[1m]')).toBe('claude-fable-5');
+ });
+});
+
+describe('output lag detection', () => {
+ function delta(overrides: Partial<ModelUsageDeltaEntry>): ModelUsageDeltaEntry {
+ return {
+ model: 'claude-fable-5[1m]',
+ costUsdDelta: 0,
+ inputTokensDelta: 0,
+ outputTokensDelta: 0,
+ cacheReadTokensDelta: 0,
+ cacheCreateTokensDelta: 0,
+ ...overrides,
+ };
+ }
+
+ it('flags a huge input turn that reports almost no output', () => {
+ // 实测形态:40 万 token 的上下文写进 cache,output 只报 7 —— 真实的长回复被上游
+ // 结算延后到了下一轮。
+ expect(
+ detectOutputLag([delta({ inputTokensDelta: 131, cacheCreateTokensDelta: 404_534, outputTokensDelta: 7 })]),
+ ).toBe(true);
+ });
+
+ it('does not flag a normal turn', () => {
+ expect(
+ detectOutputLag([delta({ cacheReadTokensDelta: 404_771, outputTokensDelta: 3_202 })]),
+ ).toBe(false);
+ });
+
+ it('does not flag a genuinely tiny turn', () => {
+ expect(detectOutputLag([delta({ inputTokensDelta: 120, outputTokensDelta: 4 })])).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts b/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
index a96be1e68e..286c25a348 100644
--- a/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
@@ -286,8 +286,8 @@ describe('readUsageHistoryWith', () => {
const estimateAmount = regionalUsdAmount(2);
const result = await readUsageHistoryWith(makeDeps({
getAllSpendDays: async () => [
- { day: '2026-06-10', money: actual(3) },
- { day: TODAY, money: actual(5) },
+ { day: '2026-06-10', monies: [actual(3)] },
+ { day: TODAY, monies: [actual(5)] },
],
getModelUsageSince: async () => [
modelRow(
@@ -390,12 +390,12 @@ describe('readUsageHistoryWith', () => {
getAllSpendDays: async () => [
{
day: TODAY,
- money: {
+ monies: [{
amount: 5,
currency: historicalCurrency,
approximate: false,
kind: 'actual-cost',
- },
+ }],
},
],
getModelUsageSince: async () => [
@@ -471,8 +471,8 @@ describe('readUsageHistoryWith', () => {
const result = await readUsageHistoryWith(
makeDeps({
getAllSpendDays: async () => [
- { day: '2026-06-10', money: usdRow(3) },
- { day: TODAY, money: usdRow(5) },
+ { day: '2026-06-10', monies: [usdRow(3)] },
+ { day: TODAY, monies: [usdRow(5)] },
],
getModelUsageSince: async () => [],
getModelPricing: async () => ({
@@ -550,12 +550,12 @@ describe('readUsageHistoryWith', () => {
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),
+ monies: [actual(1, true)],
}));
const result = await readUsageHistoryWith(makeDeps({
getAllSpendDays: async () => [
...trailing,
- { day: TODAY, money: actual(7, true) },
+ { day: TODAY, monies: [actual(7, true)] },
],
}));
expect(result.anomaly).toMatchObject({
@@ -572,7 +572,7 @@ describe('readUsageHistoryWith', () => {
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) },
+ { day: TODAY, monies: [actual(2)] },
]);
const first = await readUsageHistory({ days: 30 });
const second = await readUsageHistory({ days: 30 });
@@ -588,7 +588,9 @@ describe('production cache and empty payload', () => {
),
);
expect(raw).toMatchObject({
- version: 4,
+ // 日账改为按币种分行、折叠推迟到读侧之后升到 5:v4 快照是用「按区域猜出来的
+ // 账本币种」折叠出来的聚合值,不能沿用。改折叠口径时同步这里。
+ version: 5,
optsKey: 'user=user-a|days=30',
payload: {
totals: {
diff --git a/apps/desktop/src/main/usage/accountCurrencyStore.ts b/apps/desktop/src/main/usage/accountCurrencyStore.ts
new file mode 100644
index 0000000000..f3311c1d4e
--- /dev/null
+++ b/apps/desktop/src/main/usage/accountCurrencyStore.ts
@@ -0,0 +1,189 @@
+/**
+ * accountCurrencyStore — 账号结算币种的独立持久化。
+ *
+ * ## 为什么不跟着报价缓存走
+ *
+ * 结算币种和价格表的稳定性差了一个数量级:价格表随时可能改、随时可能拉不到,
+ * 而一个账号的结算币种基本不变。可它此前被塞在 model-pricing.json 的同一份快照里,
+ * 于是共享了那份快照的全部失效条件 —— 报价缓存的 scope 含 endpoint 与凭证文件的
+ * inode/mtime,凭证轮换、端点切换、冷启动期 userId 尚未就绪都会让整份快照作废,
+ * 币种跟着一起变成未知,账本随即回落兜底值。实测这会让同一账号的账本币种一天内
+ * 翻转多次。
+ *
+ * 所以这里单独存一份,scope 只认 userId:凭证轮换与端点变化都不影响它。
+ *
+ * 按 userId 分桶而不是只存一个值,是因为切号后必须立刻停止沿用上一个账号的币种;
+ * userId 未知(冷启动尚未接管、未登录)时既不读也不写 —— 宁可让 ledgerCurrency 走
+ * 兜底,也不能把 A 账号的币种记到 B 账号头上。
+ */
+
+import { promises as fs } from 'node:fs';
+import path from 'node:path';
+import { app } from 'electron';
+
+import type { MoneyCurrency } from '../../shared/regionalMoney.js';
+import { getCurrentDbClientUserId } from '../localDb/client/current.js';
+import { createLogger } from '../logger.js';
+import {
+ hydrateLastKnownLedgerCurrency,
+ resetLedgerCurrencyForAccountSwitch,
+} from './ledgerCurrency.js';
+
+const log = createLogger('accountCurrencyStore');
+
+const STORE_VERSION = 1;
+const STORE_FILE = 'ledger-currency.json';
+
+interface StorePayload {
+ version: number;
+ entries: Record<string, MoneyCurrency>;
+}
+
+let memo: Record<string, MoneyCurrency> | null = null;
+let writeChain: Promise<void> = Promise.resolve();
+let hydratedUserId: string | null = null;
+/**
+ * 账号代际。每次活跃账号真正发生变化时 +1,唯一写入者是 noteActiveAccount。
+ *
+ * 存在的理由是 A→B→A:跨 await 的写入只比较「当前 userId 是否还等于发起时的 userId」
+ * 不足以判定期间没换过人 —— 切走又切回会让这个比较重新相等,于是一份在 B 期间就已
+ * 过期的读取结果被当成有效值提交。代际号单调递增,切回来也不会复用旧值。
+ */
+let accountGeneration = 0;
+
+function storePath(): string {
+ return path.join(app.getPath('userData'), 'cache', STORE_FILE);
+}
+
+function isCurrency(value: unknown): value is MoneyCurrency {
+ return value === 'CNY' || value === 'USD';
+}
+
+function parseEntries(raw: unknown): Record<string, MoneyCurrency> {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
+ const payload = raw as Partial<StorePayload>;
+ if (payload.version !== STORE_VERSION) return {};
+ if (!payload.entries || typeof payload.entries !== 'object' || Array.isArray(payload.entries)) {
+ return {};
+ }
+ const out: Record<string, MoneyCurrency> = {};
+ for (const [userId, currency] of Object.entries(payload.entries)) {
+ if (userId && isCurrency(currency)) out[userId] = currency;
+ }
+ return out;
+}
+
+async function readEntries(): Promise<Record<string, MoneyCurrency>> {
+ if (memo) return memo;
+ try {
+ memo = parseEntries(JSON.parse(await fs.readFile(storePath(), 'utf8')));
+ } catch (err) {
+ const code =
+ typeof err === 'object' && err && 'code' in err ? String((err as { code?: unknown }).code) : '';
+ if (code !== 'ENOENT') {
+ log.debug('read ledger currency store failed:', err instanceof Error ? err.message : String(err));
+ }
+ memo = {};
+ }
+ return memo;
+}
+
+/**
+ * 记住某账号的结算币种。同值重复写会被跳过,避免每次目录同步都碰盘。
+ *
+ * 写入串行化:目录同步与登录接管可能几乎同时触发,并发 readEntries + writeFile 会让
+ * 后写的整份覆盖先写的,丢掉另一个账号的条目。
+ */
+export function rememberAccountCurrency(
+ userId: string | null | undefined,
+ currency: MoneyCurrency | null,
+): void {
+ if (!userId || !currency) return;
+ writeChain = writeChain.then(async () => {
+ const entries = await readEntries();
+ if (entries[userId] === currency) return;
+ const next = { ...entries, [userId]: currency };
+ const file = storePath();
+ // 写临时文件 + rename 原子落位(同 learn-host/runStore)。直接覆盖写会在崩溃或断电时
+ // 留下截断的 JSON,readEntries 解析失败后把 entries 当空 —— 整份币种快照丢失,冷启动
+ // 回退链退到 USD 兜底,对 CNY 结算账号就是本 PR 要修的那个错账。
+ // tmp 名带 pid + 随机串,避免多进程残留碰撞。
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2, 8)}.tmp`;
+ try {
+ await fs.mkdir(path.dirname(file), { recursive: true });
+ const payload: StorePayload = { version: STORE_VERSION, entries: next };
+ await fs.writeFile(tmp, JSON.stringify(payload), 'utf8');
+ await fs.rename(tmp, file);
+ // memo 表示「磁盘上是什么」,只在落位成功后才提交。抢先更新会让上面第 96 行的
+ // 同值短路把后续同步一并跳过 —— 一次瞬时写失败就变成本进程再也不重试,重启后
+ // 报价缓存又恰好失效时,CNY 账号会丢掉这份独立快照并回落 USD。
+ memo = next;
+ log.info(`ledger currency remembered: user=${userId} currency=${currency}`);
+ } catch (err) {
+ log.warn(
+ 'persist ledger currency failed:',
+ err instanceof Error ? err.message : String(err),
+ );
+ await fs.rm(tmp, { force: true }).catch(() => undefined);
+ }
+ });
+}
+
+/**
+ * 记录「当前是哪个账号在记账」,账号变了就丢掉内存里的「上次已知」币种。
+ *
+ * 同步实现,因为目录同步(replaceGatewayModelPricing)是同步路径,必须在它写入
+ * setActiveLedgerCurrency 之前就完成账号边界判定 —— 否则新账号目录没声明币种的那一轮
+ * 会先按上一个账号的口径记完账。
+ */
+export function noteActiveAccount(userId: string | null | undefined): void {
+ if (!userId) return;
+ if (hydratedUserId === userId) return;
+ if (hydratedUserId) {
+ resetLedgerCurrencyForAccountSwitch();
+ log.info(`ledger currency reset for account switch: ${hydratedUserId} -> ${userId}`);
+ }
+ hydratedUserId = userId;
+ accountGeneration += 1;
+}
+
+/**
+ * 启动时把当前账号上次已知的结算币种恢复给 ledgerCurrency。
+ *
+ * 必须在任何记账路径之前跑(prewarm 阶段):否则 /models 回来之前的那几轮会按兜底
+ * 币种入账,而那正是币种翻转的主要来源之一。
+ *
+ * ## 不变量
+ *
+ * 跨越 await 的账号相关写入,只有在这段 await 期间**账号身份一次都没变过**时才允许
+ * 提交。判据是账号代际号,不是 userId 相等 —— 后者挡得住 A→B,挡不住 A→B→A:切回来
+ * 之后 userId 重新相等,一份在 B 期间就已过期的读取结果会被当成有效值写进 lastKnown。
+ */
+export async function hydrateAccountCurrency(userId?: string): Promise<MoneyCurrency | null> {
+ const resolved = userId ?? getCurrentDbClientUserId();
+ if (!resolved) return null;
+ noteActiveAccount(resolved);
+ const generation = accountGeneration;
+ const entries = await readEntries();
+ if (accountGeneration !== generation) {
+ log.info(
+ `ledger currency hydrate discarded: account changed during read (user=${resolved}, ` +
+ `generation ${generation} -> ${accountGeneration})`,
+ );
+ return null;
+ }
+ const currency = entries[resolved] ?? null;
+ if (currency) {
+ hydrateLastKnownLedgerCurrency(currency);
+ log.info(`ledger currency hydrated: user=${resolved} currency=${currency}`);
+ }
+ return currency;
+}
+
+/** 仅测试:丢掉内存快照,强制下次重读磁盘。 */
+export function __resetAccountCurrencyStoreForTesting(): void {
+ accountGeneration = 0;
+ memo = null;
+ writeChain = Promise.resolve();
+ hydratedUserId = null;
+}
diff --git a/apps/desktop/src/main/usage/ledgerCurrency.ts b/apps/desktop/src/main/usage/ledgerCurrency.ts
index bd20206760..750423a353 100644
--- a/apps/desktop/src/main/usage/ledgerCurrency.ts
+++ b/apps/desktop/src/main/usage/ledgerCurrency.ts
@@ -7,34 +7,83 @@
* 等于这些用户完全不计费。
*
* 值由模型目录同步时写入(见 usage/modelPricing.replaceGatewayModelPricing)——报价币种
- * 就是该账号的结算币种。登出 / 切号 / 清空报价时置为未知,读侧回落构建默认值。
+ * 就是该账号的结算币种。
*
- * 本模块刻意零依赖(只引 shared 常量):账本写入层(localDb/dailySpend、
+ * ## 三级回退,且绝不按区域猜
+ *
+ * active(本次同步刚确认) → lastKnown(本进程或磁盘上见过的最后一次) → USD
+ *
+ * `active` 会因为完全正常的原因反复变成未知:目录同步在途、缓存 scope 失效、登出重登。
+ * 一旦这些瞬时状态回落到构建区域,同一账号的账本币种就会在 USD / CNY 之间来回翻 ——
+ * 而下游账本是单币种的,翻转会让金额被拒收或让当天累计被覆盖。所以未知时优先沿用
+ * 已知过的值:币种是账号属性,比任何一次同步都稳定。
+ *
+ * 最终兜底取 USD 而不是构建区域币种:USD 是 SDK 自报费用与全部参考价表的原生口径,
+ * 兜底成 USD 最多是币种符号显示得不合预期,兜底成 CNY 却会把 USD 数值原样盖上 CNY 戳
+ * (既不换算也不拒收),产生 6.7 倍量级的错账。宁可显示得保守,不可记错。
+ *
+ * 本模块刻意零依赖(只引 shared 类型):账本写入层(localDb/dailySpend、
* localDb/dailyModelUsage、sessionSpendBroadcaster)和报价层都要用它,
- * 走这里可以避免两边互相 import 成环。
+ * 走这里可以避免两边互相 import 成环。持久化由 usage/accountCurrencyStore 负责,
+ * 它在启动时把上次已知值 hydrate 回来。
*/
-import { DEFAULT_USAGE_CURRENCY, type MoneyCurrency } from '../../shared/regionalMoney.js';
+import type { MoneyCurrency } from '../../shared/regionalMoney.js';
+
+/**
+ * 三级回退的最后一档。取 USD 的理由见文件头 —— 不要改成 DEFAULT_USAGE_CURRENCY,
+ * 那正是本次修复要消灭的「按区域猜」。
+ */
+export const LEDGER_CURRENCY_FALLBACK: MoneyCurrency = 'USD';
let active: MoneyCurrency | null = null;
+let lastKnown: MoneyCurrency | null = null;
/**
- * 记录当前账号的账本币种。传 null 表示未知(登出、切号、目录尚未同步,
- * 或目录出现混合币种因而不可信),此时读侧回落构建默认值。
+ * 记录当前账号的账本币种。传 null 表示本次同步没能确认(登出、切号、目录尚未同步,
+ * 或目录出现混合币种因而不可信)—— 只清 active,不清 lastKnown。
*/
export function setActiveLedgerCurrency(currency: MoneyCurrency | null): void {
active = currency;
+ if (currency) lastKnown = currency;
+}
+
+/**
+ * 启动时从磁盘快照恢复「上次已知」。只在尚无已知值时生效,绝不覆盖本进程已经确认过的
+ * 币种 —— 磁盘快照可能比当前登录账号旧。
+ */
+export function hydrateLastKnownLedgerCurrency(currency: MoneyCurrency | null): void {
+ if (currency && !lastKnown) lastKnown = currency;
}
/**
- * 账本写入与聚合应当使用的币种。未知时回落构建默认值 —— 冷启动首帧、纯订阅账号
- * (没有 Gateway 报价)都走这条,与历史行为一致。
+ * 切号时丢掉「上次已知」。
+ *
+ * lastKnown 的作用是熬过同一账号的瞬时未知,跨账号沿用就变成了记错账:新账号的目录
+ * 若恰好没声明币种,会静默继承上一个账号的结算币种。账号边界一到就必须清零,让回退
+ * 链重新从这个账号自己的持久化值开始。
*/
+export function resetLedgerCurrencyForAccountSwitch(): void {
+ active = null;
+ lastKnown = null;
+}
+
+/** 账本写入与聚合应当使用的币种。回退链见文件头。 */
export function currentLedgerCurrency(): MoneyCurrency {
- return active ?? DEFAULT_USAGE_CURRENCY;
+ return active ?? lastKnown ?? LEDGER_CURRENCY_FALLBACK;
+}
+
+/**
+ * 账本币种是否有据可依(而非落到最后一档兜底)。
+ *
+ * 调用方据此决定「这一笔要不要标成估算」:兜底值是猜的,按它记的账不该冒充精确账单。
+ */
+export function isLedgerCurrencyKnown(): boolean {
+ return active !== null || lastKnown !== null;
}
/** 仅测试:重置为未知。 */
export function __resetActiveLedgerCurrencyForTesting(): void {
active = null;
+ lastKnown = null;
}
diff --git a/apps/desktop/src/main/usage/modelPricing.ts b/apps/desktop/src/main/usage/modelPricing.ts
index f77d198f8a..c4c433eee2 100644
--- a/apps/desktop/src/main/usage/modelPricing.ts
+++ b/apps/desktop/src/main/usage/modelPricing.ts
@@ -23,13 +23,17 @@ import {
import type { ModelAccessGatewayModel } from '../../shared/modelAccess.js';
import { providerSecretStorageKey } from '../../shared/providerSecrets.js';
import {
- gatewayCurrencyForRegion,
type ModelPriceQuote,
type ModelPricingCatalog,
type MoneyCurrency,
} from '../../shared/regionalMoney.js';
import { getCurrentDbClientUserId } from '../localDb/client/current.js';
-import { setActiveLedgerCurrency } from './ledgerCurrency.js';
+import {
+ hydrateAccountCurrency,
+ noteActiveAccount,
+ rememberAccountCurrency,
+} from './accountCurrencyStore.js';
+import { currentLedgerCurrency, setActiveLedgerCurrency } from './ledgerCurrency.js';
import { createLogger } from '../logger.js';
import { getClientEndpoint } from '../clientEndpointsService.js';
import { resolveOwnerScopedSecretStorageKey } from '../secrets/providerSecretStore.js';
@@ -50,11 +54,14 @@ export type {
} from '../../shared/regionalMoney.js';
const log = createLogger('modelPricing');
+// v9:币种回落不再按构建区域猜,且猜出来的报价会带 currencyInferred。v8 快照里那些
+// 按区域兜底写入的 accountCurrency 与 quote 没有这个标记,复用它们会让「猜的币种」
+// 重新冒充精确报价 —— 离线或 /models 失败时正好绕过本次修复,必须整份作废重取。
// v8:账号币种与报价同快照持久化;无报价模型也可能明确声明结算币种。
// v7:币种改为优先使用 Model Access 明确声明,不能复用按 region 猜测的旧 quote。
// v6:所有 Gateway 模型统一按服务端 costDiscount 计费。v5 的 codex/ quote 已
// 硬编码乘过 0.15 且丢弃 costDiscount,不能继续复用。
-const DISK_CACHE_VERSION = 8;
+const DISK_CACHE_VERSION = 9;
const DISK_CACHE_FILE = 'model-pricing.json';
export const MODEL_PRICING_CHANGED_CHANNEL = 'usage:model-pricing-changed';
@@ -73,9 +80,19 @@ let cacheAt = 0;
let modelSyncInflight: Promise<unknown> | null = null;
let gatewayAccountCurrency: MoneyCurrency | null = null;
let gatewayAccountCurrencyScope: string | null = null;
+/** 上一次观察到的**生效**账本币种(含回退结果),只用于把切换打进日志。 */
+let activeLedgerCurrencySnapshot: MoneyCurrency | null = null;
const hydratedScopes = new Set<string>();
const hydrateInflightByScope = new Map<string, Promise<ModelPricingCatalog | null>>();
+/**
+ * 目录**显式声明**的结算币种;没声明就返回 null,由 ledgerCurrency 的回退链接手。
+ *
+ * 这里曾经在没声明时回落 `gatewayCurrencyForRegion(CURRENT_CINDY_REGION)`。那是把
+ * 「服务端这次没告诉我」翻译成了「那按发行区域算」,而报价数值仍是服务端给的原口径 ——
+ * 一旦某次 /models 漏发 currency,整份目录的 USD 数值就会被盖上 CNY 戳。实测这让同一
+ * 账号的账本币种在一天内翻转多次,并连带把当天已累计的花费覆盖掉。
+ */
function resolveGatewayAccountCurrency(
models: readonly ModelAccessGatewayModel[],
): MoneyCurrency | null {
@@ -89,7 +106,14 @@ function resolveGatewayAccountCurrency(
log.warn('xd gateway models returned mixed currencies; account quota currency unavailable');
return null;
}
- return currencies.values().next().value ?? gatewayCurrencyForRegion(CURRENT_CINDY_REGION);
+ const declared = currencies.values().next().value ?? null;
+ if (!declared) {
+ log.warn(
+ `xd gateway models declared no currency (${models.length} models); ` +
+ 'keeping last known ledger currency instead of guessing by region',
+ );
+ }
+ return declared;
}
function currentKeyCacheIdentity(): string {
@@ -206,6 +230,10 @@ function validateQuote(
) {
next.costDiscount = quote.costDiscount;
}
+ // 必须跨磁盘往返保留:丢了它,重启后用同一份缓存算出的金额会重新冒充精确账单。
+ if (quote.currencyInferred === true) {
+ next.currencyInferred = true;
+ }
return next;
}
@@ -287,6 +315,8 @@ async function hydrateFromDisk(scope: string): Promise<ModelPricingCatalog | nul
gatewayAccountCurrency = raw.accountCurrency;
gatewayAccountCurrencyScope = scope;
setActiveLedgerCurrency(raw.accountCurrency);
+ activeLedgerCurrencySnapshot = currentLedgerCurrency();
+ rememberAccountCurrency(getCurrentDbClientUserId(), raw.accountCurrency);
log.debug(`hydrated model pricing cache: ${Object.keys(pricing.xd ?? {}).length} XD quotes`);
return pricing;
} catch (err) {
@@ -348,15 +378,35 @@ export function replaceGatewayModelPricing(
// therefore passes the authenticated user captured when the request starts,
// so a valid startup snapshot is never persisted under `anonymous`.
const scope = currentScope(authenticatedUserId);
- const pricing = gatewayPricingCatalog(models, CURRENT_CINDY_REGION);
- cache = pricing;
- cacheScope = scope;
- cacheAt = Date.now();
+ // 账号边界判定必须先于下面的 setActiveLedgerCurrency:切号后新账号的目录若没声明
+ // 币种,回退链不能继续沿用上一个账号的结算币种。
+ noteActiveAccount(authenticatedUserId ?? getCurrentDbClientUserId());
gatewayAccountCurrency = resolveGatewayAccountCurrency(models);
gatewayAccountCurrencyScope = scope;
// 账本写入层据此判断"这一笔是不是本账号的结算币种"。目录为空(登出 / clear)或混合
- // 币种时 resolveGatewayAccountCurrency 返回 null,账本随之回落构建默认值。
+ // 币种时返回 null,账本回退到「上次已知 → USD」,绝不按区域猜。
+ //
+ // 顺序要紧:先落 active,下面的 catalog 兜底才能读到本次刚确认的币种;本次没确认时
+ // currentLedgerCurrency() 给出的也是上次已知值,而不是区域默认值。
setActiveLedgerCurrency(gatewayAccountCurrency);
+ const previousLedgerCurrency = activeLedgerCurrencySnapshot;
+ activeLedgerCurrencySnapshot = currentLedgerCurrency();
+ if (previousLedgerCurrency && previousLedgerCurrency !== activeLedgerCurrencySnapshot) {
+ // 账本币种切换会改变后续每一笔的记账口径,也是历史上账本被覆盖的触发点。
+ // 它必须在默认日志级别可见 —— 此前只有 debug,10 次翻转在日志里一个字都没留下。
+ log.warn(
+ `ledger currency changed: ${previousLedgerCurrency} -> ${activeLedgerCurrencySnapshot}` +
+ `${gatewayAccountCurrency ? '' : ' (gateway declared none; using last known)'}`,
+ );
+ }
+ rememberAccountCurrency(
+ authenticatedUserId ?? getCurrentDbClientUserId(),
+ gatewayAccountCurrency,
+ );
+ const pricing = gatewayPricingCatalog(models, activeLedgerCurrencySnapshot);
+ cache = pricing;
+ cacheScope = scope;
+ cacheAt = Date.now();
hydratedScopes.add(scope);
void writeDiskCache(scope, pricing, gatewayAccountCurrency, cacheAt);
broadcastPricing(effectivePricingCatalog(pricing));
@@ -564,13 +614,28 @@ export function getSubscriptionDirectValuePrice(
};
}
-/** 启动只读磁盘快照;真正的新价格仍由 /models 同步整体替换。 */
+/**
+ * 启动只读磁盘快照;真正的新价格仍由 /models 同步整体替换。
+ *
+ * 先恢复账号币种再读报价快照:币种的持久化不跟报价缓存共享 scope(见
+ * accountCurrencyStore),凭证轮换或端点变化让报价快照作废时,币种仍然取得回来 ——
+ * 这样 /models 回来之前的那几轮记账不会落到兜底币种上。
+ */
export async function prewarmModelPricing(): Promise<void> {
+ try {
+ await hydrateAccountCurrency();
+ } catch (err) {
+ log.debug(
+ 'hydrate account currency failed:',
+ err instanceof Error ? err.message : String(err),
+ );
+ }
try {
await getModelPricing();
} catch (err) {
log.debug('prewarm model pricing failed:', err instanceof Error ? err.message : String(err));
}
+ activeLedgerCurrencySnapshot = currentLedgerCurrency();
}
export function __resetModelPricingCacheForTesting(): void {
@@ -580,6 +645,7 @@ export function __resetModelPricingCacheForTesting(): void {
modelSyncInflight = null;
gatewayAccountCurrency = null;
gatewayAccountCurrencyScope = null;
+ activeLedgerCurrencySnapshot = null;
hydratedScopes.clear();
hydrateInflightByScope.clear();
}
diff --git a/apps/desktop/src/main/usage/modelUsageDelta.ts b/apps/desktop/src/main/usage/modelUsageDelta.ts
index a4d86142d4..7e1462aad1 100644
--- a/apps/desktop/src/main/usage/modelUsageDelta.ts
+++ b/apps/desktop/src/main/usage/modelUsageDelta.ts
@@ -9,6 +9,18 @@
* 钳制: 子进程重 spawn (resume / 崩溃重启) 后累计值归零, delta 会算出负数 —
* 一律 Math.max(0, ...) 钳到 0 (接受少记一个 turn 的取舍, 与 total_cost_usd 一致)。
*
+ * ## 已知上游行为: output 归属可能滞后一轮
+ *
+ * 部分路由(实测 Vertex, requestId 前缀 msg_vrtx_)在 done 事件时点报出的 modelUsage
+ * 尚未结算本轮的输出 token: 一条几千 token 的长回复只报个位数 output, 差额在下一轮的
+ * delta 里补上。result.usage 与 modelUsage 两个源同时滞后, 所以客户端在 done 时刻拿
+ * 不到正确值 —— 总量不丢, 但**归属会错位一轮**, 表现为某条消息的费用明显偏低、下一条
+ * 明显偏高。
+ *
+ * 这里不做纠正: 把 output 挪到别处需要知道"本轮真实输出是多少", 而两个可用数据源都
+ * 还没结算; 猜一个值会把"归属错位"升级成"金额算错"。detectOutputLag 只把可疑轮次标出
+ * 来供日志定位, 不参与任何计费。
+ *
* 纯函数、零 Electron 依赖 — 可直接单测。
*/
@@ -109,3 +121,22 @@ export function computeModelUsageDeltas(
return { next, deltas };
}
+
+/**
+ * 本轮 output 归属是否可疑(见文件头「已知上游行为」)。
+ *
+ * 判据:这一轮明明送进去了实质性的输入(input + cache 合计过万 token,说明不是空转),
+ * 报回来的 output 却只有个位到几十 —— 真实回复不可能这么短。阈值取得很松,只求把
+ * "长回复被记成 7 个 token" 这种量级的异常捞出来,不追求精确。
+ *
+ * 纯诊断:调用方只应拿它打日志。不参与计费,也不改任何金额。
+ */
+export function detectOutputLag(deltas: readonly ModelUsageDeltaEntry[]): boolean {
+ const OUTPUT_FLOOR = 64;
+ const INPUT_SIGNIFICANT = 10_000;
+ return deltas.some((delta) => {
+ const inputSide =
+ delta.inputTokensDelta + delta.cacheReadTokensDelta + delta.cacheCreateTokensDelta;
+ return inputSide >= INPUT_SIGNIFICANT && delta.outputTokensDelta < OUTPUT_FLOOR;
+ });
+}
diff --git a/apps/desktop/src/main/usage/turnCostCalculator.ts b/apps/desktop/src/main/usage/turnCostCalculator.ts
index a05cbfed3d..f589090327 100644
--- a/apps/desktop/src/main/usage/turnCostCalculator.ts
+++ b/apps/desktop/src/main/usage/turnCostCalculator.ts
@@ -16,6 +16,7 @@ import {
type ModelPriceQuote,
type ModelPricingCatalog,
type MoneyCurrency,
+ type MoneyEstimateReason,
type RegionalMoney,
} from '../../shared/regionalMoney.js';
import { buildTurnUsageDetails, type TurnUsageDetails } from '../../shared/turnUsageDetails.js';
@@ -145,18 +146,26 @@ export function computePriceQuoteTurnMoney(
price.source === 'subscription-reference' ||
price.source === 'provider-reference' ||
price.source === 'user-override';
- const estimateReasons =
+ // 币种是本地推断出来的时候,金额仍是真实计费(kind 保持 actual-cost,否则会被并进
+ // 订阅价值统计),但不能再自称精确:报价数值来自服务端、币种却是猜的,这一笔与账单
+ // 能不能对上取决于猜得对不对。标 approximate + 原因,让 UI 与对账口径看得见。
+ const currencyInferred = price.currencyInferred === true;
+ const baseReasons =
price.source === 'subscription-reference'
? (['subscription-value', 'reference-price'] as const)
: valueEstimate || price.approximate
? (['reference-price'] as const)
: undefined;
+ const estimateReasons: MoneyEstimateReason[] = [
+ ...(baseReasons ?? []),
+ ...(currencyInferred ? (['inferred-currency'] as const) : []),
+ ];
const money: RegionalMoney = {
amount: Math.max(0, amount),
currency: price.currency,
- approximate: price.approximate || valueEstimate,
+ approximate: price.approximate || valueEstimate || currencyInferred,
kind: valueEstimate ? 'value-estimate' : 'actual-cost',
- ...(estimateReasons ? { estimateReasons: [...estimateReasons] } : {}),
+ ...(estimateReasons.length > 0 ? { estimateReasons } : {}),
};
// Gateway 报价的币种就是该账号的实际结算币种,原样记账才能与账单对账 —— 不做任何换算。
// 否则以 USD 结算的账号在 CN 构建上,turn 会被 USD_TO_CNY_FIXED_RATE 折成 CNY,而同一
@@ -197,6 +206,9 @@ export function resolveTurnCost(args: {
const ledgerCurrency = gatewayLedgerCurrency(pricing) ?? currentLedgerCurrency();
if (context.billingRoute === 'xd-gateway') {
+ // 长上下文档不看模型 id 后缀:computeGatewayTurnCost 按本轮实际 input token 落进
+ // quote 的 inputTokenPriceBands,比 `[1m]` 这类后缀更权威(后缀只表示会话开了大
+ // 窗口,不代表这一轮真的超过阈值)。
const quote = getModelPriceQuote(pricing, 'xd', model);
if (!quote) {
// 该模型没有报价(上游未登记,或目录还没同步下来)。SDK 的 costDelta 是 USD,
diff --git a/apps/desktop/src/main/usage/usageHistory.ts b/apps/desktop/src/main/usage/usageHistory.ts
index 0adeeb1836..2450e385b4 100644
--- a/apps/desktop/src/main/usage/usageHistory.ts
+++ b/apps/desktop/src/main/usage/usageHistory.ts
@@ -58,8 +58,10 @@ const ANOMALY_MIN_TODAY_USD = 1;
const ANOMALY_MIN_ACTIVE_DAYS = 3;
/** 模型拆分统计窗口 (天)。 */
const MODEL_WINDOW_DAYS = 30;
+// v5:日账改为按币种分行后折叠口径变了;v4 快照是用「按区域猜出来的账本币种」折叠出来
+// 的聚合值,直接沿用会让升级后的首页继续显示按错币种算出的历史。整份作废重算。
// v4:恢复 CN usage 的 CNY 账本口径,并让订阅 USD 估值按 6.7 投影到 CNY。
-const DISK_CACHE_VERSION = 4;
+const DISK_CACHE_VERSION = 5;
const DISK_CACHE_FILE = 'usage-history.json';
/** 后台刷新完成后, renderer 的短轮询能拿到 fresh payload, 避免 stale 状态自循环。 */
const MEMORY_FRESH_MS = 10_000;
@@ -223,7 +225,7 @@ export function computeAnomaly(
/** 测试注入用的数据读取依赖。 */
export interface UsageHistoryDeps {
- getAllSpendDays(): Promise<Array<{ day: string; money: RegionalMoney }>>;
+ getAllSpendDays(): Promise<Array<{ day: string; monies: RegionalMoney[] }>>;
getModelUsageSince(sinceDayKey: string): Promise<DailyModelUsageRow[]>;
getModelPricing(): Promise<ModelPricingMap | null>;
/** 覆盖记录快照,一次聚合读一份——历史重合并逐行读文件会在慢盘上拖垮 Main 线程。 */
@@ -526,13 +528,6 @@ export async function readUsageHistoryWith(
});
const keepCompatibleMoney = (money: RegionalMoney): RegionalMoney =>
money.currency === ledgerCurrency ? money : zeroActual();
- const allDays = spendDayRows.map((row) => ({
- ...row,
- money: keepCompatibleMoney(row.money),
- }));
- const spendByDay = new Map(
- allDays.map((row) => [row.day, row.money.amount]),
- );
const addOrZero = (
values: RegionalMoney[],
kind: 'actual-cost' | 'value-estimate' = 'actual-cost',
@@ -541,6 +536,17 @@ export async function readUsageHistoryWith(
values.filter((value) => value.currency === ledgerCurrency),
ledgerCurrency,
) ?? (kind === 'actual-cost' ? zeroActual() : zeroEstimate());
+ // 日账按币种拆开取回,折叠推迟到这里 —— 与上面等 pricing 是同一个理由:折叠依赖账本
+ // 币种,而它要等报价快照恢复才确定。若在 getAllSpendDays 内部折叠,冷启动时会先按
+ // 兜底币种把本账号那一行丢掉,等到这里再怎么等也拿不回来。
+ // 与 model 行共用 addOrZero,异币种同样归零,两条链路口径一致。
+ const allDays = spendDayRows.map((row) => ({
+ day: row.day,
+ money: addOrZero(row.monies),
+ }));
+ const spendByDay = new Map(
+ allDays.map((row) => [row.day, row.money.amount]),
+ );
const heatmapCutoff = shiftDayKey(todayKey, -(windowDays - 1));
const modelCutoff = shiftDayKey(todayKey, -(MODEL_WINDOW_DAYS - 1));
diff --git a/apps/desktop/src/main/usageBroadcaster.ts b/apps/desktop/src/main/usageBroadcaster.ts
index d82915bb7d..9755376ef7 100644
--- a/apps/desktop/src/main/usageBroadcaster.ts
+++ b/apps/desktop/src/main/usageBroadcaster.ts
@@ -23,6 +23,7 @@
import { BrowserWindow } from 'electron';
import { incrementDailySpend, getTodaySpend, localDayKey } from './localDb/dailySpend';
+import { getModelPricing } from './usage/modelPricing';
import type { XaiRateLimitSnapshot } from '../shared/xaiRateLimit';
import { incrementDailyModelUsage, type DailyModelUsageDelta } from './localDb/dailyModelUsage';
import { getDbClient } from './localDb/client/current';
@@ -134,6 +135,10 @@ export async function recordTurnSpend(
/** Claude 今日 USD 累计 (供 IPC handler / 内部消费)。 */
export async function readTodaySpend(): Promise<TodaySpendPayload> {
+ // getTodaySpend 要按账本币种从多币种日账里挑行,而账本币种由报价快照恢复。
+ // getModelPricing 只读内存或磁盘快照、不发网络请求,等它一下就能避免冷启动首帧
+ // 按兜底币种折叠掉本账号真正的那一行(与 usageHistory 里同一个理由)。
+ await getModelPricing().catch(() => null);
const money = await getTodaySpend();
return {
day: localDayKey(),
diff --git a/apps/desktop/src/shared/__tests__/modelPriceQuote.test.ts b/apps/desktop/src/shared/__tests__/modelPriceQuote.test.ts
index fb37670994..fdf8794427 100644
--- a/apps/desktop/src/shared/__tests__/modelPriceQuote.test.ts
+++ b/apps/desktop/src/shared/__tests__/modelPriceQuote.test.ts
@@ -28,37 +28,53 @@ describe('gatewayPricingCatalog', () => {
expect(
gatewayPricingCatalog(
[model('a', { currency: 'CNY' }), model('b', { currency: 'USD' }), model('c')],
- 'cn',
+ 'CNY',
),
).toEqual({});
});
it('lets a single declared currency cover the models that omit it', () => {
// 同一账号的目录币种是统一的:省略 currency 的条目跟随同目录已声明的币种,
- // 而不是各自回落构建区域(那会产出跨币种目录)。
+ // 而不是各自回落账本币种(那会产出跨币种目录)。
const catalog = gatewayPricingCatalog(
[model('a', { currency: 'USD' }), model('b')],
- 'cn',
+ 'CNY',
);
expect(Object.keys(catalog.xd ?? {})).toEqual(['a', 'b']);
expect(Object.values(catalog.xd ?? {}).map((quote) => quote.currency)).toEqual([
'USD',
'USD',
]);
+ // 目录声明了币种,不是猜的 —— 下游金额仍按精确账单记。
+ expect(
+ Object.values(catalog.xd ?? {}).every((quote) => quote.currencyInferred === undefined),
+ ).toBe(true);
});
- it('falls back to the build region only when no model declares a currency', () => {
- const catalog = gatewayPricingCatalog([model('a'), model('b')], 'cn');
+ it('falls back to the ledger currency and marks it inferred when no model declares one', () => {
+ // 服务端漏发 currency 时只能回落账本币种,但必须留下"这是猜的"的痕迹:报价数值来自
+ // 服务端、币种由本地推断,猜错就是把一个口径的数字盖上另一个口径的戳。
+ const catalog = gatewayPricingCatalog([model('a'), model('b')], 'USD');
expect(Object.values(catalog.xd ?? {}).map((quote) => quote.currency)).toEqual([
- 'CNY',
- 'CNY',
+ 'USD',
+ 'USD',
]);
+ expect(
+ Object.values(catalog.xd ?? {}).every((quote) => quote.currencyInferred === true),
+ ).toBe(true);
+ });
+
+ it('never guesses the currency by build region', () => {
+ // 回归护栏:此前整份目录没声明 currency 时按构建区域猜 CNY,把 USD 口径的报价数值
+ // 盖上 CNY 戳,产生 6.7 倍量级的错账。回落值只能来自调用方给的账本币种。
+ const catalog = gatewayPricingCatalog([model('a')], 'USD');
+ expect(catalog.xd?.a?.currency).toBe('USD');
});
it('carries Gateway costDiscount uniformly for ordinary and codex models', () => {
const catalog = gatewayPricingCatalog(
[model('a', { costDiscount: 0.4 }), model('codex/gpt-5.5', { costDiscount: 0.4 })],
- 'cn',
+ 'CNY',
);
expect(catalog.xd.a).toMatchObject({
inputPerMtok: 2,
diff --git a/apps/desktop/src/shared/modelPriceQuote.ts b/apps/desktop/src/shared/modelPriceQuote.ts
index a73855d10e..2c9bb4292a 100644
--- a/apps/desktop/src/shared/modelPriceQuote.ts
+++ b/apps/desktop/src/shared/modelPriceQuote.ts
@@ -1,4 +1,3 @@
-import type { CindyRegion } from '@cindy/maker-shared/brand-identity';
import {
resolveModelReferencePrice,
type AgentKind,
@@ -7,7 +6,6 @@ import {
import type { ModelAccessGatewayModel } from './modelAccess.js';
import {
- gatewayCurrencyForRegion,
type ModelPriceQuote,
type ModelPricingCatalog,
type MoneyCurrency,
@@ -79,21 +77,22 @@ function gatewayInputTokenPriceBands(
return thresholdBands.length > 0 ? thresholdBands : undefined;
}
-/** Gateway 原生币种优先;旧服务端未声明时才按构建 region 回退。 */
/** 该条目是否会产生报价(与币种无关;目录币种裁决与覆盖率统计共用此判定)。 */
export function isPricedGatewayModel(model: ModelAccessGatewayModel): boolean {
- // 币种不影响“是否有价格”的判断,这里显式传值,避免计费 API 隐式回落 Global。
- return gatewayModelPriceQuote(model, 'global') !== undefined;
+ // 币种不影响“是否有价格”的判断,随便传一个具体币种即可。
+ return gatewayModelPriceQuote(model, 'USD') !== undefined;
}
/**
* @param fallbackCurrency 该模型未声明 currency 时的回落币种。调用方(gatewayPricingCatalog)
- * 会传同一目录里已声明的币种,让整份目录保持单一币种;缺省才按区域回落。
+ * 先传同一目录里已声明的币种,让整份目录保持单一币种;整份都没声明时才传账本币种。
+ * @param fallbackIsInferred fallbackCurrency 本身是否是猜出来的。为 true 时产出的报价带
+ * currencyInferred 标记,让下游金额降级成估算而不是冒充精确账单。
*/
export function gatewayModelPriceQuote(
model: ModelAccessGatewayModel,
- region: CindyRegion,
- fallbackCurrency?: MoneyCurrency,
+ fallbackCurrency: MoneyCurrency,
+ fallbackIsInferred = false,
): ModelPriceQuote | undefined {
const modelId = model.id.trim();
const inputPerMtok = perMtok(model.inputCostPerToken);
@@ -115,10 +114,11 @@ export function gatewayModelPriceQuote(
// costDiscount 带入计费计算,CatalogModel.cost 继续承载折后展示价。
const costDiscount = normalizedCostDiscount(model.costDiscount);
const inputTokenPriceBands = gatewayInputTokenPriceBands(model);
+ const declaredCurrency = model.currency;
return {
providerId: 'xd',
modelId,
- currency: model.currency ?? fallbackCurrency ?? gatewayCurrencyForRegion(region),
+ currency: declaredCurrency ?? fallbackCurrency,
source: 'gateway',
approximate: false,
inputPerMtok,
@@ -127,12 +127,19 @@ export function gatewayModelPriceQuote(
...(cacheCreatePerMtok !== undefined ? { cacheCreatePerMtok } : {}),
...(inputTokenPriceBands ? { inputTokenPriceBands } : {}),
...(costDiscount !== undefined ? { costDiscount } : {}),
+ ...(!declaredCurrency && fallbackIsInferred ? { currencyInferred: true } : {}),
};
}
+/**
+ * @param ledgerCurrency 整份目录都没声明币种时的回落值。传本账号的账本币种(见
+ * main/usage/ledgerCurrency),**不要**传按区域推出来的值:服务端漏发 currency 时
+ * 按区域猜会把 USD 口径的报价数值盖上 CNY 戳,产生 6.7 倍量级的错账。这种回落出来的
+ * 报价一律带 currencyInferred 标记。
+ */
export function gatewayPricingCatalog(
models: readonly ModelAccessGatewayModel[],
- region: CindyRegion,
+ ledgerCurrency: MoneyCurrency,
): ModelPricingCatalog {
// 整份目录必须是单一币种。
//
@@ -149,10 +156,11 @@ export function gatewayPricingCatalog(
.filter((currency): currency is MoneyCurrency => currency === 'CNY' || currency === 'USD'),
);
if (declared.size > 1) return {};
- const fallbackCurrency = declared.values().next().value ?? gatewayCurrencyForRegion(region);
+ const declaredCurrency = declared.values().next().value;
+ const fallbackCurrency = declaredCurrency ?? ledgerCurrency;
const xd: Record<string, ModelPriceQuote> = {};
for (const model of models) {
- const quote = gatewayModelPriceQuote(model, region, fallbackCurrency);
+ const quote = gatewayModelPriceQuote(model, fallbackCurrency, declaredCurrency === undefined);
if (quote) xd[quote.modelId] = quote;
}
return Object.keys(xd).length > 0 ? { xd } : {};
diff --git a/apps/desktop/src/shared/regionalMoney.ts b/apps/desktop/src/shared/regionalMoney.ts
index 2da306eb81..2b6cedf8c6 100644
--- a/apps/desktop/src/shared/regionalMoney.ts
+++ b/apps/desktop/src/shared/regionalMoney.ts
@@ -5,7 +5,7 @@ import { CURRENT_CINDY_REGION } from './brandRegion.js';
export type MoneyCurrency = 'CNY' | 'USD';
export type MoneyKind = 'actual-cost' | 'value-estimate';
export type MoneyEstimateReason =
- 'fixed-fx' | 'legacy-usd' | 'subscription-value' | 'reference-price';
+ 'fixed-fx' | 'legacy-usd' | 'subscription-value' | 'reference-price' | 'inferred-currency';
/**
* 用量/费用金额始终携带币种。当前构建的本地账本使用区域币种:
@@ -49,6 +49,14 @@ export interface ModelPriceQuote {
}>;
/** Gateway 声明的折扣比例;计费金额按原价 × (1 - costDiscount)。 */
costDiscount?: number;
+ /**
+ * 该报价的币种不是上游声明的,而是本地按兜底链推断出来的。
+ *
+ * 报价数值由服务端给定、币种却由客户端猜,猜错就会把一个口径的数字盖上另一个口径的
+ * 戳(既不换算也不拒收),下游账本按它记账后无从分辨。带上这个标记,金额侧才能降级
+ * 成估算而不是继续冒充精确账单。
+ */
+ currencyInferred?: boolean;
}
export type ModelPricingCatalog = Record<string, Record<string, ModelPriceQuote>>;
@@ -261,7 +269,8 @@ export function normalizeRegionalMoney(value: unknown): RegionalMoney | undefine
reason === 'fixed-fx' ||
reason === 'legacy-usd' ||
reason === 'subscription-value' ||
- reason === 'reference-price',
+ reason === 'reference-price' ||
+ reason === 'inferred-currency',
),
)
: undefined;
diff --git a/packages/maker-scheduler/src/types.ts b/packages/maker-scheduler/src/types.ts
index 1de5a3467b..04c88d102f 100644
--- a/packages/maker-scheduler/src/types.ts
+++ b/packages/maker-scheduler/src/types.ts
@@ -304,7 +304,7 @@ export interface ScheduleRunMoney {
approximate: boolean;
kind: 'actual-cost' | 'value-estimate';
estimateReasons?: Array<
- 'fixed-fx' | 'legacy-usd' | 'subscription-value' | 'reference-price'
+ 'fixed-fx' | 'legacy-usd' | 'subscription-value' | 'reference-price' | 'inferred-currency'
>;
}
diff --git a/packages/maker-shared/src/scheduleTypes.ts b/packages/maker-shared/src/scheduleTypes.ts
index 75f2d7a247..1859814da5 100644
--- a/packages/maker-shared/src/scheduleTypes.ts
+++ b/packages/maker-shared/src/scheduleTypes.ts
@@ -132,7 +132,7 @@ export interface RemoteScheduleRunMoney {
approximate: boolean;
kind: 'actual-cost' | 'value-estimate';
estimateReasons?: Array<
- 'fixed-fx' | 'legacy-usd' | 'subscription-value' | 'reference-price'
+ 'fixed-fx' | 'legacy-usd' | 'subscription-value' | 'reference-price' | 'inferred-currency'
>;
}