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。

feat(desktop): 用量历史默认合并所有设备并支持按设备查看 (#5116)

Dashd25a0eaf3b8d
diff --git a/apps/desktop/drizzle/0115_silky_power_man.sql b/apps/desktop/drizzle/0115_silky_power_man.sql
new file mode 100644
index 0000000000..270d7279e2
--- /dev/null
+++ b/apps/desktop/drizzle/0115_silky_power_man.sql
@@ -0,0 +1,7 @@
+CREATE TABLE `daily_session_usage` (
+ `day` text NOT NULL,
+ `session_id` text NOT NULL,
+ `tokens` integer DEFAULT 0 NOT NULL,
+ `updated_at` integer NOT NULL,
+ PRIMARY KEY(`day`, `session_id`)
+);
diff --git a/apps/desktop/drizzle/meta/0115_snapshot.json b/apps/desktop/drizzle/meta/0115_snapshot.json
new file mode 100644
index 0000000000..38b1cb960d
--- /dev/null
+++ b/apps/desktop/drizzle/meta/0115_snapshot.json
@@ -0,0 +1,6113 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "5d2dd28a-3d32-448d-8bbb-000d29541d1e",
+ "prevId": "c5d29ae9-c017-4e7f-ba01-9e305d7b4cb8",
+ "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": {}
+ },
+ "bot_delegations": {
+ "name": "bot_delegations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "requesting_bot_id": {
+ "name": "requesting_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "target_bot_id": {
+ "name": "target_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "parent_session_id": {
+ "name": "parent_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "child_session_id": {
+ "name": "child_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "objective": {
+ "name": "objective",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_refs_json": {
+ "name": "context_refs_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "artifact_refs_json": {
+ "name": "artifact_refs_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "permission_snapshot_json": {
+ "name": "permission_snapshot_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "lineage_json": {
+ "name": "lineage_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "target_profile_version": {
+ "name": "target_profile_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "depth": {
+ "name": "depth",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "budget_tokens": {
+ "name": "budget_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tokens_used": {
+ "name": "tokens_used",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "result_summary": {
+ "name": "result_summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "output_artifacts_json": {
+ "name": "output_artifacts_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "pending_interaction_json": {
+ "name": "pending_interaction_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "run_sequence": {
+ "name": "run_sequence",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "accepted_at": {
+ "name": "accepted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "completion_delivered_at": {
+ "name": "completion_delivered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_delegations_requester_status": {
+ "name": "idx_bot_delegations_requester_status",
+ "columns": [
+ "requesting_bot_id",
+ "status"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_delegations_target_status": {
+ "name": "idx_bot_delegations_target_status",
+ "columns": [
+ "target_bot_id",
+ "status"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_delegations_parent_session": {
+ "name": "idx_bot_delegations_parent_session",
+ "columns": [
+ "parent_session_id"
+ ],
+ "isUnique": false
+ },
+ "uniq_bot_delegations_child_session": {
+ "name": "uniq_bot_delegations_child_session",
+ "columns": [
+ "child_session_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "bot_delegations_requesting_bot_id_bot_profiles_id_fk": {
+ "name": "bot_delegations_requesting_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_delegations",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "requesting_bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_delegations_target_bot_id_bot_profiles_id_fk": {
+ "name": "bot_delegations_target_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_delegations",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "target_bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_delegations_parent_session_id_sessions_id_fk": {
+ "name": "bot_delegations_parent_session_id_sessions_id_fk",
+ "tableFrom": "bot_delegations",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "parent_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "bot_delegations_child_session_id_sessions_id_fk": {
+ "name": "bot_delegations_child_session_id_sessions_id_fk",
+ "tableFrom": "bot_delegations",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "child_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_direct_message_threads": {
+ "name": "bot_direct_message_threads",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_a_id": {
+ "name": "bot_a_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_b_id": {
+ "name": "bot_b_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "close_reason": {
+ "name": "close_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "message_count": {
+ "name": "message_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "max_messages": {
+ "name": "max_messages",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "blocked_until": {
+ "name": "blocked_until",
+ "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
+ },
+ "closed_at": {
+ "name": "closed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_bot_dm_threads_active_pair": {
+ "name": "uniq_bot_dm_threads_active_pair",
+ "columns": [
+ "bot_a_id",
+ "bot_b_id"
+ ],
+ "isUnique": true,
+ "where": "\"bot_direct_message_threads\".\"status\" = 'active'"
+ },
+ "idx_bot_dm_threads_pair_updated": {
+ "name": "idx_bot_dm_threads_pair_updated",
+ "columns": [
+ "bot_a_id",
+ "bot_b_id",
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_direct_messages": {
+ "name": "bot_direct_messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "thread_id": {
+ "name": "thread_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sequence": {
+ "name": "sequence",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sender_bot_id": {
+ "name": "sender_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "recipient_bot_id": {
+ "name": "recipient_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sender_session_id": {
+ "name": "sender_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "recipient_session_id": {
+ "name": "recipient_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "delivery_status": {
+ "name": "delivery_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "sender_name": {
+ "name": "sender_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "recipient_name": {
+ "name": "recipient_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "bridge_session_id": {
+ "name": "bridge_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_bot_direct_messages_thread_sequence": {
+ "name": "uniq_bot_direct_messages_thread_sequence",
+ "columns": [
+ "thread_id",
+ "sequence"
+ ],
+ "isUnique": true
+ },
+ "idx_bot_direct_messages_thread_created": {
+ "name": "idx_bot_direct_messages_thread_created",
+ "columns": [
+ "thread_id",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_direct_messages_thread_id_bot_direct_message_threads_id_fk": {
+ "name": "bot_direct_messages_thread_id_bot_direct_message_threads_id_fk",
+ "tableFrom": "bot_direct_messages",
+ "tableTo": "bot_direct_message_threads",
+ "columnsFrom": [
+ "thread_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_direct_messages_sender_session_id_sessions_id_fk": {
+ "name": "bot_direct_messages_sender_session_id_sessions_id_fk",
+ "tableFrom": "bot_direct_messages",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "sender_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "bot_direct_messages_recipient_session_id_sessions_id_fk": {
+ "name": "bot_direct_messages_recipient_session_id_sessions_id_fk",
+ "tableFrom": "bot_direct_messages",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "recipient_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_lifecycle_events": {
+ "name": "bot_lifecycle_events",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "event_type": {
+ "name": "event_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload_json": {
+ "name": "payload_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_lifecycle_events_bot_created": {
+ "name": "idx_bot_lifecycle_events_bot_created",
+ "columns": [
+ "bot_id",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_lifecycle_events_session_created": {
+ "name": "idx_bot_lifecycle_events_session_created",
+ "columns": [
+ "session_id",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_lifecycle_events_bot_id_bot_profiles_id_fk": {
+ "name": "bot_lifecycle_events_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_lifecycle_events",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_lifecycle_events_session_id_sessions_id_fk": {
+ "name": "bot_lifecycle_events_session_id_sessions_id_fk",
+ "tableFrom": "bot_lifecycle_events",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_profile_versions": {
+ "name": "bot_profile_versions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "version": {
+ "name": "version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "identity_source": {
+ "name": "identity_source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "capabilities_json": {
+ "name": "capabilities_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_bot_profile_versions_bot_version": {
+ "name": "uniq_bot_profile_versions_bot_version",
+ "columns": [
+ "bot_id",
+ "version"
+ ],
+ "isUnique": true
+ },
+ "idx_bot_profile_versions_bot_created": {
+ "name": "idx_bot_profile_versions_bot_created",
+ "columns": [
+ "bot_id",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_profile_versions_bot_id_bot_profiles_id_fk": {
+ "name": "bot_profile_versions_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_profile_versions",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_profiles": {
+ "name": "bot_profiles",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "display_name": {
+ "name": "display_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "avatar": {
+ "name": "avatar",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'🤖'"
+ },
+ "avatar_color": {
+ "name": "avatar_color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'violet'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "hidden_at": {
+ "name": "hidden_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pinned_at": {
+ "name": "pinned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "attention_reason": {
+ "name": "attention_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "attention_at": {
+ "name": "attention_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "current_version": {
+ "name": "current_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "canonical_session_id": {
+ "name": "canonical_session_id",
+ "type": "text",
+ "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_bot_profiles_status_updated": {
+ "name": "idx_bot_profiles_status_updated",
+ "columns": [
+ "status",
+ "updated_at"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_profiles_canonical_session": {
+ "name": "idx_bot_profiles_canonical_session",
+ "columns": [
+ "canonical_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_profiles_canonical_session_id_sessions_id_fk": {
+ "name": "bot_profiles_canonical_session_id_sessions_id_fk",
+ "tableFrom": "bot_profiles",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "canonical_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_runtime_snapshots": {
+ "name": "bot_runtime_snapshots",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "profile_version": {
+ "name": "profile_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "memory_scope_key": {
+ "name": "memory_scope_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "configured_json": {
+ "name": "configured_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "resolved_json": {
+ "name": "resolved_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "prepared_at": {
+ "name": "prepared_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "applied_at": {
+ "name": "applied_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "failed_at": {
+ "name": "failed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "failure_json": {
+ "name": "failure_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_runtime_snapshots_bot_prepared": {
+ "name": "idx_bot_runtime_snapshots_bot_prepared",
+ "columns": [
+ "bot_id",
+ "prepared_at"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_runtime_snapshots_session_prepared": {
+ "name": "idx_bot_runtime_snapshots_session_prepared",
+ "columns": [
+ "session_id",
+ "prepared_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_runtime_snapshots_bot_id_bot_profiles_id_fk": {
+ "name": "bot_runtime_snapshots_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_runtime_snapshots",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_runtime_snapshots_session_id_sessions_id_fk": {
+ "name": "bot_runtime_snapshots_session_id_sessions_id_fk",
+ "tableFrom": "bot_runtime_snapshots",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_session_links": {
+ "name": "bot_session_links",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "profile_version": {
+ "name": "profile_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "route_key": {
+ "name": "route_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_bot_session_links_session": {
+ "name": "uniq_bot_session_links_session",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true
+ },
+ "uniq_bot_session_links_canonical_per_bot": {
+ "name": "uniq_bot_session_links_canonical_per_bot",
+ "columns": [
+ "bot_id"
+ ],
+ "isUnique": true,
+ "where": "\"bot_session_links\".\"role\" = 'canonical'"
+ },
+ "idx_bot_session_links_bot_role": {
+ "name": "idx_bot_session_links_bot_role",
+ "columns": [
+ "bot_id",
+ "role"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_session_links_bot_id_bot_profiles_id_fk": {
+ "name": "bot_session_links_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_session_links",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_session_links_session_id_sessions_id_fk": {
+ "name": "bot_session_links_session_id_sessions_id_fk",
+ "tableFrom": "bot_session_links",
+ "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_session_usage": {
+ "name": "daily_session_usage",
+ "columns": {
+ "day": {
+ "name": "day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tokens": {
+ "name": "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_session_usage_day_session_id_pk": {
+ "columns": [
+ "day",
+ "session_id"
+ ],
+ "name": "daily_session_usage_day_session_id_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_context_cursors": {
+ "name": "hook_group_context_cursors",
+ "columns": {
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cursor_key": {
+ "name": "cursor_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cursor_id": {
+ "name": "cursor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "hook_group_context_cursors_updated_at_idx": {
+ "name": "hook_group_context_cursors_updated_at_idx",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "hook_group_context_cursors_provider_cursor_key_pk": {
+ "columns": [
+ "provider",
+ "cursor_key"
+ ],
+ "name": "hook_group_context_cursors_provider_cursor_key_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "hook_group_message_stats": {
+ "name": "hook_group_message_stats",
+ "columns": {
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "row_count": {
+ "name": "row_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text_bytes": {
+ "name": "text_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "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": {}
+ },
+ "im_notification_origins": {
+ "name": "im_notification_origins",
+ "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
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "im_notification_origins_channel_bot_context_id_user_id_message_id_pk": {
+ "columns": [
+ "channel",
+ "bot_context_id",
+ "user_id",
+ "message_id"
+ ],
+ "name": "im_notification_origins_channel_bot_context_id_user_id_message_id_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_invocations": {
+ "name": "media_invocations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner": {
+ "name": "owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "capability": {
+ "name": "capability",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "guide_revision": {
+ "name": "guide_revision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "guide_json": {
+ "name": "guide_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "response_json": {
+ "name": "response_json",
+ "type": "text",
+ "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": {
+ "media_invocations_owner_created_at_idx": {
+ "name": "media_invocations_owner_created_at_idx",
+ "columns": [
+ "owner",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "media_invocations_owner_state_idx": {
+ "name": "media_invocations_owner_state_idx",
+ "columns": [
+ "owner",
+ "state"
+ ],
+ "isUnique": false
+ }
+ },
+ "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
+ },
+ "idx_messages_active_error_tail": {
+ "name": "idx_messages_active_error_tail",
+ "columns": [
+ "session_id",
+ "created_at"
+ ],
+ "isUnique": false,
+ "where": "\"messages\".\"role\" = 'error' AND \"messages\".\"rewind_at\" IS NULL"
+ }
+ },
+ "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": {}
+ },
+ "messages_fts_rows": {
+ "name": "messages_fts_rows",
+ "columns": {
+ "fts_rowid": {
+ "name": "fts_rowid",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "messages_fts_rows_message_id_idx": {
+ "name": "messages_fts_rows_message_id_idx",
+ "columns": [
+ "message_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "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
+ },
+ "right_sidebar_tabs_subagents_singleton_idx": {
+ "name": "right_sidebar_tabs_subagents_singleton_idx",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true,
+ "where": "\"right_sidebar_tabs\".\"kind\" = 'subagents'"
+ },
+ "right_sidebar_tabs_bot_artifacts_singleton_idx": {
+ "name": "right_sidebar_tabs_bot_artifacts_singleton_idx",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true,
+ "where": "\"right_sidebar_tabs\".\"kind\" = 'bot-artifacts'"
+ }
+ },
+ "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
+ },
+ "idx_schedule_runs_running_schedule": {
+ "name": "idx_schedule_runs_running_schedule",
+ "columns": [
+ "schedule_id"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"status\" = 'running'"
+ },
+ "idx_schedule_runs_running_heartbeat": {
+ "name": "idx_schedule_runs_running_heartbeat",
+ "columns": [
+ "heartbeat_at"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"status\" = 'running' AND \"schedule_runs\".\"heartbeat_at\" IS NOT NULL"
+ },
+ "idx_schedule_runs_running_legacy": {
+ "name": "idx_schedule_runs_running_legacy",
+ "columns": [
+ "fired_at"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"status\" = 'running' AND \"schedule_runs\".\"heartbeat_at\" IS NULL"
+ },
+ "idx_schedule_runs_unread_terminal": {
+ "name": "idx_schedule_runs_unread_terminal",
+ "columns": [
+ "schedule_id",
+ "status",
+ "fired_at"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"read_at\" IS NULL AND \"schedule_runs\".\"status\" IN ('success', 'failed', 'aborted', 'interrupted')"
+ },
+ "idx_schedule_runs_session_latest": {
+ "name": "idx_schedule_runs_session_latest",
+ "columns": [
+ "session_id",
+ "fired_at",
+ "id"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"session_id\" IS NOT NULL"
+ }
+ },
+ "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": {}
+ },
+ "schedule_session_latest_runs": {
+ "name": "schedule_session_latest_runs",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "fired_at": {
+ "name": "fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedule_session_latest_runs_run": {
+ "name": "idx_schedule_session_latest_runs_run",
+ "columns": [
+ "run_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "schedule_session_latest_runs_session_id_sessions_id_fk": {
+ "name": "schedule_session_latest_runs_session_id_sessions_id_fk",
+ "tableFrom": "schedule_session_latest_runs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "schedule_session_latest_runs_run_id_schedule_runs_id_fk": {
+ "name": "schedule_session_latest_runs_run_id_schedule_runs_id_fk",
+ "tableFrom": "schedule_session_latest_runs",
+ "tableTo": "schedule_runs",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "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_agent_kind": {
+ "name": "model_agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "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": {}
+ },
+ "session_task_tags": {
+ "name": "session_task_tags",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tag_id": {
+ "name": "tag_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "session_task_tags_tag_idx": {
+ "name": "session_task_tags_tag_idx",
+ "columns": [
+ "tag_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_task_tags_session_id_sessions_id_fk": {
+ "name": "session_task_tags_session_id_sessions_id_fk",
+ "tableFrom": "session_task_tags",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "session_task_tags_tag_id_task_tags_id_fk": {
+ "name": "session_task_tags_tag_id_task_tags_id_fk",
+ "tableFrom": "session_task_tags",
+ "tableTo": "task_tags",
+ "columnsFrom": [
+ "tag_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "session_task_tags_session_id_tag_id_pk": {
+ "columns": [
+ "session_id",
+ "tag_id"
+ ],
+ "name": "session_task_tags_session_id_tag_id_pk"
+ }
+ },
+ "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
+ },
+ "context_window_runtime": {
+ "name": "context_window_runtime",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "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
+ },
+ "codex_plan_json": {
+ "name": "codex_plan_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "extra_dirs": {
+ "name": "extra_dirs",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "writable_dirs": {
+ "name": "writable_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
+ },
+ "list_preview": {
+ "name": "list_preview",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "list_preview_role": {
+ "name": "list_preview_role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "list_message_count": {
+ "name": "list_message_count",
+ "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": {}
+ },
+ "shared_task_events": {
+ "name": "shared_task_events",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "shared_task_id": {
+ "name": "shared_task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "revision": {
+ "name": "revision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "terminal": {
+ "name": "terminal",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "snapshot": {
+ "name": "snapshot",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "recorded_at": {
+ "name": "recorded_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "shared_task_events_revision_idx": {
+ "name": "shared_task_events_revision_idx",
+ "columns": [
+ "shared_task_id",
+ "kind",
+ "revision"
+ ],
+ "isUnique": true
+ },
+ "shared_task_events_session_idx": {
+ "name": "shared_task_events_session_idx",
+ "columns": [
+ "session_id",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "shared_task_events_session_id_sessions_id_fk": {
+ "name": "shared_task_events_session_id_sessions_id_fk",
+ "tableFrom": "shared_task_events",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "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_skill_recent": {
+ "name": "idx_skill_usage_exposures_skill_recent",
+ "columns": [
+ "skill_name",
+ "analyzer_version",
+ "seen_at"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_skill_recent_any_version": {
+ "name": "idx_skill_usage_exposures_skill_recent_any_version",
+ "columns": [
+ "skill_name",
+ "seen_at"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_analyzer_recent_source": {
+ "name": "idx_skill_usage_exposures_analyzer_recent_source",
+ "columns": [
+ "analyzer_version",
+ "seen_at",
+ "raw_file_path"
+ ],
+ "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": {}
+ },
+ "subagent_run_aliases": {
+ "name": "subagent_run_aliases",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "alias": {
+ "name": "alias",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "subagent_run_aliases_lookup_idx": {
+ "name": "subagent_run_aliases_lookup_idx",
+ "columns": [
+ "session_id",
+ "provider",
+ "alias",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "subagent_run_aliases_session_id_sessions_id_fk": {
+ "name": "subagent_run_aliases_session_id_sessions_id_fk",
+ "tableFrom": "subagent_run_aliases",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "subagent_run_aliases_run_id_subagent_runs_id_fk": {
+ "name": "subagent_run_aliases_run_id_subagent_runs_id_fk",
+ "tableFrom": "subagent_run_aliases",
+ "tableTo": "subagent_runs",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "subagent_run_aliases_run_id_alias_pk": {
+ "columns": [
+ "run_id",
+ "alias"
+ ],
+ "name": "subagent_run_aliases_run_id_alias_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subagent_runs": {
+ "name": "subagent_runs",
+ "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
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "logical_agent_id": {
+ "name": "logical_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "parent_tool_use_id": {
+ "name": "parent_tool_use_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "aliases": {
+ "name": "aliases",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "provider_run_ids": {
+ "name": "provider_run_ids",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'running'"
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "returned_result": {
+ "name": "returned_result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "returned_result_empty": {
+ "name": "returned_result_empty",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "returned_result_truncated": {
+ "name": "returned_result_truncated",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "reasoning_effort": {
+ "name": "reasoning_effort",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "total_tokens": {
+ "name": "total_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tool_uses": {
+ "name": "tool_uses",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "duration_ms": {
+ "name": "duration_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "capabilities": {
+ "name": "capabilities",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "activity": {
+ "name": "activity",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "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
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "rewind_at": {
+ "name": "rewind_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "subagent_runs_logical_idx": {
+ "name": "subagent_runs_logical_idx",
+ "columns": [
+ "session_id",
+ "provider",
+ "logical_agent_id"
+ ],
+ "isUnique": false
+ },
+ "subagent_runs_session_idx": {
+ "name": "subagent_runs_session_idx",
+ "columns": [
+ "session_id",
+ "rewind_at",
+ "deleted_at",
+ "started_at"
+ ],
+ "isUnique": false
+ },
+ "subagent_runs_parent_tool_use_idx": {
+ "name": "subagent_runs_parent_tool_use_idx",
+ "columns": [
+ "session_id",
+ "parent_tool_use_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "subagent_runs_session_id_sessions_id_fk": {
+ "name": "subagent_runs_session_id_sessions_id_fk",
+ "tableFrom": "subagent_runs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "task_tags": {
+ "name": "task_tags",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name_customized": {
+ "name": "name_customized",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "favorite_order": {
+ "name": "favorite_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "revision": {
+ "name": "revision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ }
+ },
+ "indexes": {
+ "task_tags_name_idx": {
+ "name": "task_tags_name_idx",
+ "columns": [
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "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 e0598f0814..b574885fb8 100644
--- a/apps/desktop/drizzle/meta/_journal.json
+++ b/apps/desktop/drizzle/meta/_journal.json
@@ -806,6 +806,13 @@
"when": 1789905526324,
"tag": "0114_shared_task_events",
"breakpoints": true
+ },
+ {
+ "idx": 115,
+ "version": "6",
+ "when": 1790421361685,
+ "tag": "0115_silky_power_man",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
index 3d7e184560..d292643172 100644
--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
@@ -939,10 +939,10 @@ describe('maker:event hot path ordering', () => {
expect(codexDoneSource).toContain('void recordTurnSpend(money);');
expect(codexDoneSource).toContain('void recordSessionTurnSpend(session.id, money);');
expect(codexDoneSource).toMatch(
- /await recordModelTurnUsage\(\{\s*agentKind: 'codex',\s*model: modelUsageKey,\s*money: isSubscriptionValue \? unpricedSubscriptionValueMarker\(\) : undefined,\s*inputTokensDelta: promptTokens,\s*outputTokensDelta: completionTokens,\s*cacheReadTokensDelta: cachedTokens,\s*cacheCreateTokensDelta: cacheCreationTokens,\s*\}\)\.finally\(\(\) => rebroadcastCodexTodayUsage\(\)\);[\s\S]*?const pricing = isSubscriptionValue/,
+ /await recordModelTurnUsage\(\{\s*sessionId: session\.id,\s*agentKind: 'codex',\s*model: modelUsageKey,\s*money: isSubscriptionValue \? unpricedSubscriptionValueMarker\(\) : undefined,\s*inputTokensDelta: promptTokens,\s*outputTokensDelta: completionTokens,\s*cacheReadTokensDelta: cachedTokens,\s*cacheCreateTokensDelta: cacheCreationTokens,\s*\}\)\.finally\(\(\) => rebroadcastCodexTodayUsage\(\)\);[\s\S]*?const pricing = isSubscriptionValue/,
);
expect(codexDoneSource).toMatch(
- /await recordModelTurnUsage\(\{\s*agentKind: 'codex',\s*model: modelUsageKey,\s*money,\s*inputTokensDelta: 0,\s*outputTokensDelta: 0,\s*cacheReadTokensDelta: 0,\s*cacheCreateTokensDelta: 0,\s*\}\);/,
+ /await recordModelTurnUsage\(\{\s*sessionId: session\.id,\s*agentKind: 'codex',\s*model: modelUsageKey,\s*money,\s*inputTokensDelta: 0,\s*outputTokensDelta: 0,\s*cacheReadTokensDelta: 0,\s*cacheCreateTokensDelta: 0,\s*\}\);/,
);
const costRecordIndex = codexDoneSource.indexOf('void recordTurnSpend(money);');
const modelCostRecordIndex = codexDoneSource.indexOf(
@@ -1058,6 +1058,12 @@ describe('maker:event hot path ordering', () => {
expect(piDoneSource).toContain('money: modelRowMoney,');
expect(piDoneSource).toContain('if (actualMoney)');
expect(piDoneSource).toContain('await recordSchedulerTurnCost({');
+ // 消息 / 调度落库失败同样落进 catch:兜底只补写正常分支尚未发起的模型组,
+ // 不重放已写过的用量(否则任务与模型用量翻倍)。
+ expectOrder(piDoneSource, 'recordedModels.add(model);', 'modelWrites.push(');
+ expect(piDoneSource).toMatch(
+ /\[\.\.\.groupedSegments\]\s*\.filter\(\(\[model\]\) => !recordedModels\.has\(model\)\)\s*\.map\(/,
+ );
});
it('records Claude subscription quota events only while the native login is connected', () => {
diff --git a/apps/desktop/src/main/__tests__/usageBroadcasterTurnUsage.test.ts b/apps/desktop/src/main/__tests__/usageBroadcasterTurnUsage.test.ts
new file mode 100644
index 0000000000..651d9f2b5c
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/usageBroadcasterTurnUsage.test.ts
@@ -0,0 +1,62 @@
+/**
+ * 每轮用量:任务用量是模型用量的细分,模型行没记上时不能单独计入任务排行。
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ incrementDailyModelUsage: vi.fn(async () => undefined),
+ incrementDailySessionUsage: vi.fn(async () => undefined),
+}));
+
+vi.mock('electron', () => ({
+ BrowserWindow: { getAllWindows: () => [] },
+}));
+vi.mock('../logger', () => ({
+ createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
+}));
+vi.mock('../localDb/dailySpend', () => ({
+ incrementDailySpend: vi.fn(),
+ getTodaySpend: vi.fn(async () => 0),
+ localDayKey: () => '2026-09-27',
+}));
+vi.mock('../localDb/dailyModelUsage', () => ({
+ incrementDailyModelUsage: mocks.incrementDailyModelUsage,
+}));
+vi.mock('../localDb/dailySessionUsage', () => ({
+ incrementDailySessionUsage: mocks.incrementDailySessionUsage,
+}));
+vi.mock('../localDb/client/current', () => ({
+ getDbClient: () => ({ queryOne: vi.fn(), exec: vi.fn(), drizzle: {} }),
+ getCurrentDbClientUserId: () => 'user-1',
+}));
+
+import { recordModelTurnUsage } from '../usageBroadcaster';
+
+const delta = {
+ sessionId: 's1',
+ agentKind: 'pi' as const,
+ model: 'gpt-5.5',
+ inputTokensDelta: 10,
+ outputTokensDelta: 5,
+ cacheReadTokensDelta: 2,
+ cacheCreateTokensDelta: 0,
+};
+
+describe('recordModelTurnUsage', () => {
+ beforeEach(() => {
+ mocks.incrementDailyModelUsage.mockReset().mockResolvedValue(undefined);
+ mocks.incrementDailySessionUsage.mockReset().mockResolvedValue(undefined);
+ });
+
+ it('adds the turn tokens to the task after the model row is recorded', async () => {
+ await recordModelTurnUsage(delta, 1);
+ expect(mocks.incrementDailySessionUsage).toHaveBeenCalledWith('s1', 17, 1);
+ });
+
+ it('does not count the task when the model row failed', async () => {
+ mocks.incrementDailyModelUsage.mockRejectedValue(new Error('worker restarted'));
+ await expect(recordModelTurnUsage(delta, 1)).resolves.toBeUndefined();
+ expect(mocks.incrementDailySessionUsage).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/device-link/__tests__/backgroundLink.test.ts b/apps/desktop/src/main/device-link/__tests__/backgroundLink.test.ts
new file mode 100644
index 0000000000..cceb25bfd0
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/backgroundLink.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it, vi } from 'vitest';
+import { DEVICE_LINK_CAPABILITY_BACKGROUND_LINK_V1 } from '@cindy/device-link';
+
+import { assertBackgroundLinkAccepted, linkOpenCapabilities } from '../backgroundLink';
+
+describe('background link capability', () => {
+ it('declares a background link only while this computer controls nothing on the peer', () => {
+ expect(linkOpenCapabilities(['base'], false)).toEqual([
+ 'base',
+ DEVICE_LINK_CAPABILITY_BACKGROUND_LINK_V1,
+ ]);
+ expect(linkOpenCapabilities(['base'], true)).toEqual(['base']);
+ });
+
+ it('accepts a peer that declares background support without closing the link', () => {
+ const closeLink = vi.fn();
+ assertBackgroundLinkAccepted(
+ { capabilities: ['history-view-v1', DEVICE_LINK_CAPABILITY_BACKGROUND_LINK_V1] },
+ { hasOutboundSubscriptions: () => false, closeLink },
+ );
+ expect(closeLink).not.toHaveBeenCalled();
+ });
+
+ it('closes the link it opened on an old peer and fails as unsupported', () => {
+ const closeLink = vi.fn();
+ expect(() =>
+ assertBackgroundLinkAccepted(
+ { capabilities: ['history-view-v1'] },
+ { hasOutboundSubscriptions: () => false, closeLink },
+ ),
+ ).toThrow(/^\[UNSUPPORTED_CAPABILITY\]/);
+ expect(closeLink).toHaveBeenCalledOnce();
+ });
+
+ it('keeps the link when the user started controlling the peer meanwhile', () => {
+ const closeLink = vi.fn();
+ expect(() =>
+ assertBackgroundLinkAccepted({}, { hasOutboundSubscriptions: () => true, closeLink }),
+ ).toThrow(/UNSUPPORTED_CAPABILITY/);
+ expect(closeLink).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
index fd543797d6..a6347ebaf1 100644
--- a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
@@ -13,6 +13,7 @@ import {
DeviceLinkError,
DEVICE_LINK_CAPABILITY_COMPACT_MESSAGE_HISTORY_V1,
CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1,
+ DEVICE_LINK_CAPABILITY_BACKGROUND_LINK_V1,
DL_SUBSCRIBE_CHANNEL,
MAX_FRAME_BYTES,
PROTOCOL_VERSION,
@@ -783,6 +784,44 @@ describe('[13] forwardPush — 转发失败 best-effort,不冒泡', () => {
expect(subscriptions.__testing.topicsOf('ctrl-legacy')).toEqual(['*']);
});
+ it('background link-open never installs the legacy wildcard or lights the controlled banner', () => {
+ const client = mkClient();
+ __testing.setActiveClient(client as never);
+
+ __testing.handleLinkOpen(client as never, 'ctrl-background', 'open-1', {
+ controllerName: 'Desktop',
+ protocolVersion: 1,
+ appVersion: '1.0.0',
+ capabilities: [DEVICE_LINK_CAPABILITY_BACKGROUND_LINK_V1],
+ });
+
+ expect(client.sendLinkAccept).toHaveBeenCalledWith(
+ 'ctrl-background',
+ 'open-1',
+ expect.objectContaining({
+ capabilities: expect.arrayContaining([DEVICE_LINK_CAPABILITY_BACKGROUND_LINK_V1]),
+ }),
+ );
+ expect(subscriptions.__testing.topicsOf('ctrl-background')).toEqual([]);
+ expect(subscriptions.getControlControllers()).toEqual([]);
+ expect(subscriptions.getUpdateRelaunchControllers()).toEqual([]);
+ __testing.forwardPush('local-db:messages:created', { sessionId: 's1', id: 'm1' });
+ expect(client.sendPush).not.toHaveBeenCalled();
+
+ // 之后用户真正开始控制:显式 subscribe 照常生效。
+ const result = __testing.handleSubscriptionFrame('ctrl-background', {
+ channel: DL_SUBSCRIBE_CHANNEL,
+ args: [{ topics: ['session:s1'] }],
+ });
+ expect(result).toEqual({ ok: true, result: { ok: true } });
+ __testing.forwardPush('local-db:messages:created', { sessionId: 's1', id: 'm1' });
+ expect(client.sendPush).toHaveBeenCalledWith(
+ 'ctrl-background',
+ 'local-db:messages:created',
+ { sessionId: 's1', id: 'm1' },
+ );
+ });
+
it('remembered modern link-open waits for an explicit subscribe frame', () => {
const client = mkClient();
__testing.setActiveClient(client as never);
@@ -969,6 +1008,19 @@ describe('background database admission covers the complete remote list lifecycl
},
);
+ it('runs cross-device usage row reads under background admission', async () => {
+ const admissions: string[] = [];
+ registry.register('maker:usage:device-rows', () => {
+ admissions.push(currentDbRpcAdmissionClass());
+ return { format: 'usage-device-rows-v1', oversize: true };
+ });
+ expect(
+ await runInvoke('ctrl-1', { channel: 'maker:usage:device-rows', args: [{ sinceDay: '2026-09-25' }] }),
+ ).toMatchObject({ ok: true });
+ expect(admissions).toEqual(['background']);
+ expect(currentDbRpcAdmissionClass()).toBe('interactive');
+ });
+
it('keeps sending interactive while an unrelated background list is awaiting permission checks', async () => {
let finish!: () => void;
const pending = new Promise<void>((resolve) => { finish = resolve; });
diff --git a/apps/desktop/src/main/device-link/backgroundLink.ts b/apps/desktop/src/main/device-link/backgroundLink.ts
new file mode 100644
index 0000000000..d83bb4049e
--- /dev/null
+++ b/apps/desktop/src/main/device-link/backgroundLink.ts
@@ -0,0 +1,34 @@
+/**
+ * 后台链路(DEVICE_LINK_CAPABILITY_BACKGROUND_LINK_V1)的控制端判据。
+ *
+ * 唯一判据:本机没有订阅对端任何 topic = 不在控制它。此时建的链路声明后台能力,新被控端
+ * 不装 legacy `'*'`(横幅 / 全量推送 / 挡无人值守更新)。openRemoteLink 的所有入口(用户打开、
+ * 订阅前建链、transport-timeout 重开、熔断恢复、后台读取)共用这一处判据。
+ */
+import {
+ DEVICE_LINK_CAPABILITY_BACKGROUND_LINK_V1,
+ type LinkAcceptPayload,
+} from '@cindy/device-link';
+
+export function linkOpenCapabilities(
+ base: readonly string[],
+ hasOutboundSubscriptions: boolean,
+): string[] {
+ return hasOutboundSubscriptions
+ ? [...base]
+ : [...base, DEVICE_LINK_CAPABILITY_BACKGROUND_LINK_V1];
+}
+
+/**
+ * 后台只读请求新建链路后的确认:旧被控端不认后台能力、已装上 legacy `'*'`。本机仍无控制
+ * 意图时关掉这条链路(撤掉对方的受控状态),并以 UNSUPPORTED_CAPABILITY 失败,不发请求;
+ * 期间用户已开始控制(有了订阅)时保留链路,只让这次后台请求失败。
+ */
+export function assertBackgroundLinkAccepted(
+ accepted: Pick<LinkAcceptPayload, 'capabilities'>,
+ deps: { hasOutboundSubscriptions(): boolean; closeLink(): void },
+): void {
+ if (accepted.capabilities?.includes(DEVICE_LINK_CAPABILITY_BACKGROUND_LINK_V1)) return;
+ if (!deps.hasOutboundSubscriptions()) deps.closeLink();
+ throw new Error('[UNSUPPORTED_CAPABILITY] remote device does not support background links');
+}
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index c49264cfcf..9dc08da84e 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -56,6 +56,7 @@ import {
CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1,
DEVICE_LINK_CAPABILITY_COMPACT_MESSAGE_HISTORY_V1,
DEVICE_LINK_CAPABILITY_HISTORY_VIEW_V1,
+ DEVICE_LINK_CAPABILITY_BACKGROUND_LINK_V1,
byteLength,
DeviceLinkError,
parseFsWatchTopic,
@@ -696,6 +697,8 @@ const BACKGROUND_REMOTE_INVOKE_CHANNELS: ReadonlySet<string> = new Set([
'maker:provider:list',
'maker:git-safety:get',
'maker:schedule:list-sidebar-index-runs',
+ // 用量历史跨设备合并:其它电脑周期性增量拉取本机全量用量行,属后台同步。
+ 'maker:usage:device-rows',
]);
/** Include pre/post authorization and cached delivery, not only the IPC handler. */
function withRemoteDbAdmission<T>(channel: string | undefined, fn: () => T): T {
@@ -2469,16 +2472,18 @@ function handleLinkOpen(
// 已在当前 link 上证明支持 topic 的客户端可能重复 open;不能重新装回兼容 wildcard。
const capabilities = sanitizeControllerCapabilities(payload?.capabilities);
const rememberedModernTopics = subscriptions.hasRememberedModernTopics(src);
+ // 后台链路:控制端声明本机未订阅任何 topic(如用量读取),同样不装 legacy '*'。
const knownModernController =
topicSubscriptionControllers.has(src)
- || rememberedModernTopics;
+ || rememberedModernTopics
+ || capabilities.includes(DEVICE_LINK_CAPABILITY_BACKGROUND_LINK_V1);
// 先确认 link-accept 已经进入 socket/可靠层,再提交本地订阅状态。弱网背压下
// accept 发送失败时不能留下“控制端未连上、被控端却显示已受控”的幽灵订阅。
try {
client.sendLinkAccept(src, requestId, {
appVersion: app.getVersion(),
allowlistHash: computeAllowlistHash(),
- capabilities: [DEVICE_LINK_CAPABILITY_HISTORY_VIEW_V1],
+ capabilities: [DEVICE_LINK_CAPABILITY_HISTORY_VIEW_V1, DEVICE_LINK_CAPABILITY_BACKGROUND_LINK_V1],
});
} catch (err) {
// 背压等瞬时失败:短退避重试(见 LINK_ACCEPT_RETRY_DELAYS_MS 注释),
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index 857254fd8d..c0d97a1cff 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -12,6 +12,7 @@
import os from 'node:os';
import { tryPeerInvoke } from './filePeer';
+import { assertBackgroundLinkAccepted, linkOpenCapabilities } from './backgroundLink';
import { deviceName, initializeDeviceName } from './deviceName';
import { watchNetworkChanges } from './networkChanges';
import path from 'node:path';
@@ -1670,7 +1671,11 @@ export async function openRemoteLink(
controllerName: deviceName(),
protocolVersion: 1,
appVersion: app.getVersion(),
- capabilities: [...CONTROLLER_CAPABILITIES],
+ // 本机不在控制对端(无订阅)时声明后台链路,对端不进入受控状态(见 backgroundLink)。
+ capabilities: linkOpenCapabilities(
+ CONTROLLER_CAPABILITIES,
+ snapshotSubscriptions(deviceId).length > 0,
+ ),
});
revokedByRemote.delete(deviceId);
return accepted;
@@ -1796,6 +1801,26 @@ export async function remoteInvoke(
return responsivenessTracker.guardInvoke(deviceId, channel, run);
}
+/**
+ * 控制端:后台只读请求(如用量历史读取其它电脑)。本机不在控制对端时,建的链路声明后台能力,
+ * 对端不进入受控状态。旧被控端不认该能力、仍会装 legacy '*':需要新建链路且对端未声明支持时,
+ * 若本机仍无控制意图(无订阅)就立即关闭本次建的链路,以 UNSUPPORTED_CAPABILITY 失败,不发请求。
+ * 链路已就绪(用户正在控制对端)时直接复用,不产生新的 link-open。
+ */
+export async function remoteBackgroundInvoke(
+ deviceId: string,
+ channel: string,
+ args: unknown[],
+): Promise<InvokeResultPayload> {
+ if (!client?.isLinkReady(deviceId)) {
+ assertBackgroundLinkAccepted(await openRemoteLink(deviceId), {
+ hasOutboundSubscriptions: () => snapshotSubscriptions(deviceId).length > 0,
+ closeLink: () => closeRemoteLink(deviceId),
+ });
+ }
+ return remoteInvoke(deviceId, channel, args);
+}
+
/**
* 控制端:订阅被控端某 topic 的变更推送(push 驱动)。走 invoke 帧承载,被控端 dispatch
* 拦截执行。带上本机设备名,供被控端横幅展示「正在被 X 控制」(与 openRemoteLink 同款)。
diff --git a/apps/desktop/src/main/localDb/__tests__/dailySessionUsage.db.test.ts b/apps/desktop/src/main/localDb/__tests__/dailySessionUsage.db.test.ts
new file mode 100644
index 0000000000..a15291cab0
--- /dev/null
+++ b/apps/desktop/src/main/localDb/__tests__/dailySessionUsage.db.test.ts
@@ -0,0 +1,69 @@
+import Database from 'better-sqlite3';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createDrizzleProxy } from '../client/drizzleProxy';
+import type { DbTransport } from '../client/DbTransport';
+
+const state = vi.hoisted(() => ({ db: null as unknown }));
+vi.mock('../client/current.js', () => ({ getDbClient: () => ({ drizzle: state.db }) }));
+import { getSessionUsageSince, getUsageTaskMeta } from '../dailySessionUsage';
+
+let sqlite: Database.Database;
+
+beforeEach(() => {
+ sqlite = new Database(':memory:');
+ sqlite.exec(`
+ CREATE TABLE sessions (
+ id TEXT PRIMARY KEY, title TEXT NOT NULL, model TEXT NOT NULL, provider_id TEXT,
+ status TEXT NOT NULL, context_tokens INTEGER NOT NULL DEFAULT 0,
+ context_window INTEGER NOT NULL DEFAULT 0, user_send_at INTEGER, updated_at INTEGER NOT NULL
+ );
+ CREATE TABLE daily_session_usage (
+ day TEXT NOT NULL, session_id TEXT NOT NULL, tokens INTEGER NOT NULL DEFAULT 0,
+ updated_at INTEGER NOT NULL, PRIMARY KEY (day, session_id)
+ );
+ INSERT INTO sessions VALUES
+ ('old', 'Renamed later', 'gpt-5.5', 'openai', 'active', 10, 100, 50, 40),
+ ('recent', 'Recent', 'claude', NULL, 'archived', 0, 0, NULL, 70),
+ ('gone', 'Deleted', 'gpt-5.5', NULL, 'deleted', 0, 0, NULL, 80),
+ ('unused', 'No usage', 'gpt-5.5', NULL, 'active', 0, 0, NULL, 90);
+ INSERT INTO daily_session_usage VALUES
+ ('2026-09-01', 'old', 5, 1), ('2026-09-01', 'gone', 6, 1),
+ ('2026-09-25', 'recent', 7, 1), ('2026-09-25', 'gone', 8, 1);
+ `);
+ const transport: DbTransport = {
+ async send<R>(_op: string, args: unknown): Promise<R> {
+ const { sql, params } = args as { sql: string; params: unknown[] };
+ return sqlite
+ .prepare(sql)
+ .raw()
+ .all(...params) as R;
+ },
+ on() {},
+ onTerminated() {},
+ async close() {},
+ };
+ state.db = createDrizzleProxy(transport);
+});
+afterEach(() => sqlite.close());
+
+describe('daily session usage SQL', () => {
+ it('returns current metadata for every non-deleted task with usage, regardless of window', async () => {
+ const meta = await getUsageTaskMeta();
+ expect(meta.map((task) => task.sessionId).sort()).toEqual(['old', 'recent']);
+ expect(meta.find((task) => task.sessionId === 'old')).toEqual({
+ sessionId: 'old',
+ title: 'Renamed later',
+ model: 'gpt-5.5',
+ providerId: 'openai',
+ contextTokens: 10,
+ contextWindow: 100,
+ lastActiveAt: 50,
+ });
+ });
+
+ it('limits rows to the window but keeps the full task set', async () => {
+ const usage = await getSessionUsageSince('2026-09-20');
+ expect(usage.rows).toEqual([{ day: '2026-09-25', sessionId: 'recent', tokens: 7 }]);
+ expect(usage.tasks.map((task) => task.sessionId).sort()).toEqual(['old', 'recent']);
+ });
+});
diff --git a/apps/desktop/src/main/localDb/dailySessionUsage.ts b/apps/desktop/src/main/localDb/dailySessionUsage.ts
new file mode 100644
index 0000000000..dfc11492b9
--- /dev/null
+++ b/apps/desktop/src/main/localDb/dailySessionUsage.ts
@@ -0,0 +1,105 @@
+import { and, gte, inArray, ne, sql } from 'drizzle-orm';
+
+import { dailySessionUsage, sessions } from './schema.js';
+import { localDayKey } from './dailySpend.js';
+import { getDbClient } from './client/current.js';
+
+/** 每日 × 任务的 token 行 (daily_session_usage)。 */
+export interface DailySessionUsageRow {
+ day: string;
+ sessionId: string;
+ tokens: number;
+}
+
+/** 用量历史展示任务所需的元数据 (取任务当前值, 不是每轮事实)。 */
+export interface UsageTaskMeta {
+ sessionId: string;
+ title: string;
+ model: string;
+ providerId: string | null;
+ contextTokens: number;
+ contextWindow: number;
+ /** userSendAt 与 updatedAt 中较新者 (unix ms)。 */
+ lastActiveAt: number;
+}
+
+/** 给某任务当天累加一笔 turn token(与 daily_model_usage 同一处调用)。 */
+export async function incrementDailySessionUsage(
+ sessionId: string,
+ tokens: number,
+ ts: number = Date.now(),
+): Promise<void> {
+ const delta = Number.isFinite(tokens) && tokens > 0 ? Math.round(tokens) : 0;
+ if (!sessionId || delta === 0) return;
+ await getDbClient()
+ .drizzle.insert(dailySessionUsage)
+ .values({ day: localDayKey(ts), sessionId, tokens: delta, updatedAt: ts })
+ .onConflictDoUpdate({
+ target: [dailySessionUsage.day, dailySessionUsage.sessionId],
+ set: { tokens: sql`${dailySessionUsage.tokens} + ${delta}`, updatedAt: ts },
+ })
+ .run();
+}
+
+/**
+ * 所有记过用量、且仍存在(未删除)的任务的当前元数据。
+ * 这是任务元数据的完整集合:调用方据此覆盖旧元数据,不在集合里的任务视为已删除。
+ */
+export async function getUsageTaskMeta(): Promise<UsageTaskMeta[]> {
+ const db = getDbClient().drizzle;
+ const rows = await db
+ .select({
+ sessionId: sessions.id,
+ title: sessions.title,
+ model: sessions.model,
+ providerId: sessions.providerId,
+ contextTokens: sessions.contextTokens,
+ contextWindow: sessions.contextWindow,
+ userSendAt: sessions.userSendAt,
+ updatedAt: sessions.updatedAt,
+ })
+ .from(sessions)
+ .where(
+ and(
+ ne(sessions.status, 'deleted'),
+ inArray(
+ sessions.id,
+ db.selectDistinct({ id: dailySessionUsage.sessionId }).from(dailySessionUsage),
+ ),
+ ),
+ )
+ .all();
+ return rows.map((row) => ({
+ sessionId: row.sessionId,
+ title: row.title,
+ model: row.model,
+ providerId: row.providerId ?? null,
+ contextTokens: row.contextTokens ?? 0,
+ contextWindow: row.contextWindow ?? 0,
+ lastActiveAt: Math.max(row.userSendAt ?? 0, row.updatedAt),
+ }));
+}
+
+/**
+ * 读取 sinceDay(含)之后的每日 × 任务行,并附上全部任务的当前元数据(getUsageTaskMeta)。
+ * 已删除任务的行不返回 —— 与侧栏一致, 删掉的任务不再出现在排行里。
+ */
+export async function getSessionUsageSince(
+ sinceDay: string,
+): Promise<{ rows: DailySessionUsageRow[]; tasks: UsageTaskMeta[] }> {
+ const db = getDbClient().drizzle;
+ const rows = await db
+ .select({
+ day: dailySessionUsage.day,
+ sessionId: dailySessionUsage.sessionId,
+ tokens: dailySessionUsage.tokens,
+ })
+ .from(dailySessionUsage)
+ .innerJoin(sessions, sql`${sessions.id} = ${dailySessionUsage.sessionId}`)
+ .where(and(gte(dailySessionUsage.day, sinceDay), ne(sessions.status, 'deleted')))
+ .all();
+ return {
+ rows: rows.filter((row) => row.tokens > 0),
+ tasks: await getUsageTaskMeta(),
+ };
+}
diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.ts
index 9c82faee0a..9b05b2cbbd 100644
--- a/apps/desktop/src/main/localDb/schema.ts
+++ b/apps/desktop/src/main/localDb/schema.ts
@@ -1619,6 +1619,26 @@ export const dailyModelUsage = sqliteTable(
}),
);
+/**
+ * 每日按任务 token 用量 (daily_session_usage) — 支撑用量历史「最耗 token 的任务」按所选
+ * 时间范围统计。与 daily_model_usage 同一处写入 (每个 turn done 后, 三个 harness 共用),
+ * 只记 token 合计。历史数据不 backfill: 上线后从 0 开始积累。
+ */
+export const dailySessionUsage = sqliteTable(
+ 'daily_session_usage',
+ {
+ /** 本地时区 YYYY-MM-DD 字符串 (localDayKey)。 */
+ day: text('day').notNull(),
+ sessionId: text('session_id').notNull(),
+ tokens: integer('tokens').notNull().default(0),
+ /** 最后一次更新的 unix ms。 */
+ updatedAt: integer('updated_at').notNull(),
+ },
+ (t) => ({
+ pk: primaryKey({ columns: [t.day, t.sessionId] }),
+ }),
+);
+
/** Skill 使用分析的原始 transcript 扫描缓存。 */
export const skillUsageSources = sqliteTable(
'skill_usage_sources',
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts
index 4b124536cd..2a8743f5eb 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts
@@ -1237,6 +1237,7 @@ describe('maker usage IPC handlers', () => {
assertTrustedSender: vi.fn(),
readUsageHistory: vi.fn().mockResolvedValue(emptyHistory),
emptyUsageHistory: vi.fn(() => emptyHistory),
+ readUsageDeviceRows: vi.fn(),
...over,
};
}
@@ -1554,6 +1555,51 @@ describe('maker usage IPC handlers', () => {
expect(readUsageHistory).toHaveBeenLastCalledWith(undefined);
});
+ it('passes the device scope through and drops malformed values', async () => {
+ const harness = new IpcHarness();
+ const readUsageHistory = vi.fn().mockResolvedValue(emptyHistory);
+
+ registerMakerUsageHandlers(harness, makeUsageDeps({ readUsageHistory }));
+
+ await harness.invoke(MAKER_INVOKE.USAGE_HISTORY, { days: 'all', device: 'all' });
+ expect(readUsageHistory).toHaveBeenLastCalledWith({ days: 'all', device: 'all' });
+
+ await harness.invoke(MAKER_INVOKE.USAGE_HISTORY, { device: 'device-b' });
+ expect(readUsageHistory).toHaveBeenLastCalledWith({ device: 'device-b' });
+
+ await harness.invoke(MAKER_INVOKE.USAGE_HISTORY, { device: 42 });
+ expect(readUsageHistory).toHaveBeenLastCalledWith(undefined);
+
+ await harness.invoke(MAKER_INVOKE.USAGE_HISTORY, { includeTasks: true });
+ expect(readUsageHistory).toHaveBeenLastCalledWith({ includeTasks: true });
+ await harness.invoke(MAKER_INVOKE.USAGE_HISTORY, { includeTasks: 'yes' });
+ expect(readUsageHistory).toHaveBeenLastCalledWith(undefined);
+
+ await harness.invoke(MAKER_INVOKE.USAGE_HISTORY, { device: 'x'.repeat(200) });
+ expect(readUsageHistory).toHaveBeenLastCalledWith(undefined);
+ });
+
+ it('serves raw device rows to device-link peers without a trusted-sender check', async () => {
+ const harness = new IpcHarness();
+ const response = { format: 'usage-device-rows-v1', todayKey: '2026-09-26', sinceDay: null, rowsGz: '' };
+ const readUsageDeviceRows = vi.fn().mockResolvedValue(response);
+ const assertTrustedSender = vi.fn(() => {
+ throw new Error('[PERMISSION_DENIED] untrusted');
+ });
+
+ registerMakerUsageHandlers(harness, makeUsageDeps({ readUsageDeviceRows, assertTrustedSender }));
+
+ await expect(harness.invoke(MAKER_INVOKE.USAGE_DEVICE_ROWS, {})).resolves.toEqual(response);
+ expect(readUsageDeviceRows).toHaveBeenLastCalledWith({ sinceDay: null });
+ await harness.invoke(MAKER_INVOKE.USAGE_DEVICE_ROWS, { sinceDay: '2026-09-25' });
+ expect(readUsageDeviceRows).toHaveBeenLastCalledWith({ sinceDay: '2026-09-25' });
+ await expect(
+ harness.invoke(MAKER_INVOKE.USAGE_DEVICE_ROWS, { sinceDay: '../etc' }),
+ ).rejects.toThrow(/INVALID_PARAMS/);
+ expect(readUsageDeviceRows).toHaveBeenCalledTimes(2);
+ expect(assertTrustedSender).not.toHaveBeenCalled();
+ });
+
it('rejects usage-history reads from an untrusted sender before parsing or querying', async () => {
const harness = new IpcHarness();
const readUsageHistory = vi.fn().mockResolvedValue(emptyHistory);
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index 889feb2ca9..6a2b79032c 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -351,6 +351,9 @@ export const MAKER_INVOKE = {
USAGE_REFERENCE_MODEL_PRICING: 'maker:usage:reference-model-pricing',
// 用量历史聚合 (daily_spend + daily_model_usage, main 侧算好 streak/异常/估算) — 首页仪表盘用
USAGE_HISTORY: 'maker:usage:history',
+ // 本机原始用量行 (daily_spend + daily_model_usage) — 仅供同账号其它电脑经 device-link
+ // 拉取后合并进它们的用量历史; 本机 renderer 不调用。wire 契约见 usage/usageDeviceRows.ts
+ USAGE_DEVICE_ROWS: 'maker:usage:device-rows',
// Memory 控制 — 走 Maker.{getAgentMemoryStatus/setAgentMemory/resetAgentMemory},
// 各 agent 子类落地 (Claude 改 SDK Settings.autoMemoryEnabled, Codex 调 app-server
// experimentalFeature/enablement/set + memory/reset RPC)。
diff --git a/apps/desktop/src/main/maker-ipc/sessionClaudeTurnUsage.ts b/apps/desktop/src/main/maker-ipc/sessionClaudeTurnUsage.ts
index f8e1a6acb2..a9621fd9ce 100644
--- a/apps/desktop/src/main/maker-ipc/sessionClaudeTurnUsage.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionClaudeTurnUsage.ts
@@ -302,6 +302,7 @@ export function recordSessionClaudeTurnUsage(
: null;
modelUsageWrites.push(
recordModelTurnUsage({
+ sessionId: session.id,
agentKind: 'claude-code',
model:
isSubscriptionValueRow
diff --git a/apps/desktop/src/main/maker-ipc/sessionCodexTurnUsage.ts b/apps/desktop/src/main/maker-ipc/sessionCodexTurnUsage.ts
index 052f3982fa..c7140f5e72 100644
--- a/apps/desktop/src/main/maker-ipc/sessionCodexTurnUsage.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionCodexTurnUsage.ts
@@ -152,6 +152,7 @@ export function recordSessionCodexTurnUsage(
? codexSubscriptionUsageModelKey(pricingModel)
: codexApiUsageModelKey(pricingModel);
await recordModelTurnUsage({
+ sessionId: session.id,
agentKind: 'codex',
model: modelUsageKey,
money: isSubscriptionValue ? deps.unpricedSubscriptionValueMarker() : undefined,
@@ -223,6 +224,7 @@ export function recordSessionCodexTurnUsage(
// writing them into #billing=api would later reconstruct an estimate as actual cost.
if (money && (isSubscriptionValue || price?.source === 'gateway')) {
await recordModelTurnUsage({
+ sessionId: session.id,
agentKind: 'codex',
model: modelUsageKey,
money,
diff --git a/apps/desktop/src/main/maker-ipc/sessionPiTurnUsage.ts b/apps/desktop/src/main/maker-ipc/sessionPiTurnUsage.ts
index 0e4ac00a68..61edc776b4 100644
--- a/apps/desktop/src/main/maker-ipc/sessionPiTurnUsage.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionPiTurnUsage.ts
@@ -184,6 +184,9 @@ export function recordSessionPiTurnUsage(
turnDurationMs,
});
+ // 每个模型组的用量行只写一次:catch 只补写正常分支尚未发起的组。后续消息 /
+ // 调度落库失败也会落进 catch,不能再重放已写过的组(会让任务与模型用量翻倍)。
+ const recordedModels = new Set<string>();
try {
const pricing =
billingRoute === 'xd-gateway'
@@ -239,8 +242,10 @@ export function recordSessionPiTurnUsage(
: isSubscriptionValue
? (money ?? deps.unpricedSubscriptionValueMarker())
: null;
+ recordedModels.add(model);
modelWrites.push(
recordModelTurnUsage({
+ sessionId: session.id,
agentKind: 'pi',
model: modelUsageKey,
// daily_model_usage has no money-kind column. Subscription
@@ -291,17 +296,20 @@ export function recordSessionPiTurnUsage(
}
} catch {
// Price/catalog failure must not lose token/cache facts.
- const writes = [...groupedSegments].map(([model, group]) =>
- recordModelTurnUsage({
- agentKind: 'pi',
- model: isSubscriptionValue ? piSubscriptionUsageModelKey(model) : model,
- money: isSubscriptionValue ? deps.unpricedSubscriptionValueMarker() : undefined,
- inputTokensDelta: group.tokens.inputTokens,
- outputTokensDelta: group.tokens.outputTokens,
- cacheReadTokensDelta: group.tokens.cacheReadTokens,
- cacheCreateTokensDelta: group.tokens.cacheCreateTokens,
- }),
- );
+ const writes = [...groupedSegments]
+ .filter(([model]) => !recordedModels.has(model))
+ .map(([model, group]) =>
+ recordModelTurnUsage({
+ sessionId: session.id,
+ agentKind: 'pi',
+ model: isSubscriptionValue ? piSubscriptionUsageModelKey(model) : model,
+ money: isSubscriptionValue ? deps.unpricedSubscriptionValueMarker() : undefined,
+ inputTokensDelta: group.tokens.inputTokens,
+ outputTokensDelta: group.tokens.outputTokens,
+ cacheReadTokensDelta: group.tokens.cacheReadTokens,
+ cacheCreateTokensDelta: group.tokens.cacheCreateTokens,
+ }),
+ );
await Promise.allSettled(writes);
void rebroadcastTodaySpend();
if (turnAssistantPersistId && usageOnlyDetails) {
diff --git a/apps/desktop/src/main/maker-ipc/usage.ts b/apps/desktop/src/main/maker-ipc/usage.ts
index 5a3b08eed8..aafa882d21 100644
--- a/apps/desktop/src/main/maker-ipc/usage.ts
+++ b/apps/desktop/src/main/maker-ipc/usage.ts
@@ -35,7 +35,24 @@ import {
CodexWebUsageUnauthorizedError,
fetchCodexWebUsageSnapshot,
} from '../usage/codexWebUsage.js';
+import { app } from 'electron';
+import { requireAppCapability } from '../appCapabilities.js';
import { emptyUsageHistoryPayload, readUsageHistory } from '../usage/usageHistory.js';
+import { readUsageDeviceRows } from '../usage/usageDeviceRows.js';
+import {
+ configurePeerUsageSync,
+ peerUsageCacheFilePath,
+ withPeerUsageAccessGate,
+ readPeerUsageCacheFile,
+ writePeerUsageCacheFile,
+} from '../usage/peerUsageSync.js';
+import { getAllSpendDays, localDayKey } from '../localDb/dailySpend.js';
+import { getModelUsageSince } from '../localDb/dailyModelUsage.js';
+import { getSessionUsageSince } from '../localDb/dailySessionUsage.js';
+import { readRemoteBotSessionAccessBatch } from '../localDb/ipc/botRemoteSessionAccess.js';
+import { getCurrentDbClientUserId } from '../localDb/client/current.js';
+import { getSelfDeviceId, remoteBackgroundInvoke } from '../device-link/index.js';
+import { handleListDevices, defaultDeps as deviceDirectoryDeps } from '../device-link/ipc.js';
import {
clearClaudeSubscriptionUsageSnapshot,
clearCodexAccountUsageSnapshot,
@@ -309,8 +326,38 @@ export function registerMakerUsageIpc(maker: Maker): void {
readReferenceModelPricing: getReferenceModelPricing,
readUsageHistory,
emptyUsageHistory: emptyUsageHistoryPayload,
+ readUsageDeviceRows: (request) =>
+ readUsageDeviceRows(
+ {
+ getAllSpendDays,
+ getModelUsageSince,
+ getSessionUsageSince,
+ // 与 local-db:sessions:list 的远端投影同一判据:hidden(含账号切换中的全拒)不外发。
+ remoteVisibleTaskIds: async (ids) => {
+ const access = await readRemoteBotSessionAccessBatch(ids, 'session');
+ return new Set(ids.filter((id) => (access.get(id) ?? 'hidden') !== 'hidden'));
+ },
+ todayKey: () => localDayKey(),
+ },
+ request,
+ ),
});
+ // 用量历史「所有设备」范围:经 device-link 拉同账号其它电脑的原始用量行并按账号缓存。
+ // 与设备互联 IPC 入口同一道能力门:未登录或账号切换进行中时,不读设备目录、不开 peer 链路。
+ configurePeerUsageSync(withPeerUsageAccessGate(() =>
+ requireAppCapability('canUseDeviceLink', 'Device Link requires a Cindy account.'), {
+ userId: getCurrentDbClientUserId,
+ selfDeviceId: getSelfDeviceId,
+ listDevices: () => handleListDevices(deviceDirectoryDeps()),
+ // 后台链路:不让被读取的电脑进入受控状态;旧版本在建链后确认不支持时即关闭链路。
+ invoke: (deviceId, channel, args) => remoteBackgroundInvoke(deviceId, channel, args),
+ readCache: (userId) => readPeerUsageCacheFile(peerUsageCacheFilePath(app.getPath('userData'), userId)),
+ writeCache: (userId, contents) =>
+ writePeerUsageCacheFile(peerUsageCacheFilePath(app.getPath('userData'), userId), contents),
+ now: () => Date.now(),
+ }));
+
// 订阅会话的 CLI 在会话里上报 SDK rate_limit_event → 落库 + 广播(maker-core 只对本机
// Claude 订阅会话转发)。事件晚于登出 / 断开到达时丢弃,不复活刚清掉的快照。
setClaudeRateLimitInfoListener((info) => {
diff --git a/apps/desktop/src/main/maker-ipc/usageHandlers.ts b/apps/desktop/src/main/maker-ipc/usageHandlers.ts
index 3e9c1e14e7..e5d732851d 100644
--- a/apps/desktop/src/main/maker-ipc/usageHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/usageHandlers.ts
@@ -15,6 +15,10 @@ import type { XaiSubscriptionUsageSnapshot } from '../../shared/xaiSubscriptionU
import type { ClaudeAccountUsageSnapshot } from '../usage/claudeAccountUsage.js';
import type { ModelPricingMap } from '../usage/modelPricing.js';
import type { UsageHistoryPayload, UsageHistoryReadOptions } from '../usage/usageHistory.js';
+import {
+ parseUsageDeviceRowsRequest,
+ type UsageDeviceRowsResponse,
+} from '../usage/usageDeviceRows.js';
import type { AgentTodayUsage, RateLimitSnapshot } from '../usageBroadcaster.js';
import { CodexRateLimitResetRejectedError } from '../usage/codexRateLimitReset.js';
import { requireString, throwIpcError } from '../utils/ipcValidate.js';
@@ -84,6 +88,7 @@ export interface MakerUsageHandlerDeps {
readReferenceModelPricing(): ModelPricingMap;
readUsageHistory(opts?: UsageHistoryReadOptions): Promise<UsageHistoryPayload>;
emptyUsageHistory(): UsageHistoryPayload;
+ readUsageDeviceRows(request: { sinceDay: string | null }): Promise<UsageDeviceRowsResponse>;
}
export function registerMakerUsageHandlers(
@@ -168,7 +173,13 @@ export function registerMakerUsageHandlers(
// renderer 正常渲染空态 (与同文件其它 usage 读取的 fallback-data 口径一致)。
registry.handle(MAKER_INVOKE.USAGE_HISTORY, async (event, opts: unknown) => {
deps.assertTrustedSender(event);
- const raw = (opts ?? {}) as { days?: unknown; modelDays?: unknown; forceRefresh?: unknown };
+ const raw = (opts ?? {}) as {
+ days?: unknown;
+ modelDays?: unknown;
+ device?: unknown;
+ includeTasks?: unknown;
+ forceRefresh?: unknown;
+ };
const days =
raw.days === 'all'
? ('all' as const)
@@ -182,9 +193,17 @@ export function registerMakerUsageHandlers(
? raw.modelDays
: undefined;
const forceRefresh = raw.forceRefresh === true;
+ const device =
+ raw.device === 'all' || raw.device === 'local'
+ ? raw.device
+ : typeof raw.device === 'string' && raw.device.length > 0 && raw.device.length <= 128
+ ? raw.device
+ : undefined;
const readOpts = {
...(days === undefined ? {} : { days }),
...(modelDays === undefined ? {} : { modelDays }),
+ ...(device === undefined ? {} : { device }),
+ ...(raw.includeTasks === true ? { includeTasks: true } : {}),
...(forceRefresh ? { forceRefresh: true } : {}),
};
try {
@@ -193,4 +212,12 @@ export function registerMakerUsageHandlers(
return deps.emptyUsageHistory();
}
});
+
+ // 跨设备用量合并的被控端读取 (只读, 无 sender 依赖、无 UI 副作用):
+ // 数据真相在本机库里, 由同账号其它电脑经 device-link allowlist 调用。
+ registry.handle(MAKER_INVOKE.USAGE_DEVICE_ROWS, async (_e, request: unknown) => {
+ const parsed = parseUsageDeviceRowsRequest(request);
+ if (!parsed) throwIpcError('INVALID_PARAMS', 'sinceDay must be YYYY-MM-DD');
+ return await deps.readUsageDeviceRows(parsed);
+ });
}
diff --git a/apps/desktop/src/main/usage/__tests__/peerUsageSync.test.ts b/apps/desktop/src/main/usage/__tests__/peerUsageSync.test.ts
new file mode 100644
index 0000000000..0ebf42d1dc
--- /dev/null
+++ b/apps/desktop/src/main/usage/__tests__/peerUsageSync.test.ts
@@ -0,0 +1,588 @@
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('../../logger', () => ({
+ createLogger: () => ({ info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() }),
+}));
+
+import type { DeviceLinkDeviceView } from '../../../shared/deviceLinkIpc';
+import type { RegionalMoney } from '../../../shared/regionalMoney';
+import {
+ createPeerUsageSync,
+ mayServeBackgroundRead,
+ mergeIncrementalRows,
+ withPeerUsageAccessGate,
+ type PeerUsageSyncDeps,
+} from '../peerUsageSync';
+import {
+ decodeUsageDeviceRowsResponse,
+ isUnixMs,
+ parseUsageDeviceRowsRequest,
+ readUsageDeviceRows,
+ sanitizeUsageDeviceRows,
+ type UsageDeviceRows,
+} from '../usageDeviceRows';
+
+const usd = (amount: number): RegionalMoney => ({
+ amount,
+ currency: 'USD',
+ approximate: false,
+ kind: 'actual-cost',
+});
+
+function rowsFor(days: string[], tokens = 10): UsageDeviceRows {
+ return {
+ spendDays: days.map((day) => ({ day, monies: [usd(1)] })),
+ modelRows: days.map((day) => ({
+ day,
+ agentKind: 'codex' as const,
+ model: 'gpt-5.5',
+ money: usd(1),
+ inputTokens: tokens,
+ outputTokens: 0,
+ cacheReadTokens: 0,
+ cacheCreateTokens: 0,
+ })),
+ sessionRows: [],
+ tasks: [],
+ };
+}
+
+function device(over: Partial<DeviceLinkDeviceView> & { deviceId: string }): DeviceLinkDeviceView {
+ return {
+ name: over.deviceId,
+ platform: 'darwin',
+ appVersion: '0.1.94',
+ lastSeenAt: null,
+ online: true,
+ busy: false,
+ remoteControlEnabled: true,
+ controlEnabled: true,
+ isSelf: false,
+ ...over,
+ };
+}
+
+async function hostResponse(rows: UsageDeviceRows, todayKey: string, sinceDay: string | null) {
+ return readUsageDeviceRows(
+ {
+ getAllSpendDays: async () => rows.spendDays,
+ getModelUsageSince: async (since) => rows.modelRows.filter((row) => row.day >= since),
+ getSessionUsageSince: async () => ({ rows: [], tasks: [] }),
+ remoteVisibleTaskIds: async (ids) => new Set(ids),
+ todayKey: () => todayKey,
+ },
+ { sinceDay },
+ );
+}
+
+function harness(over: Partial<PeerUsageSyncDeps> = {}) {
+ let now = 1_000_000;
+ let userId: string | null = 'user-a';
+ const written = new Map<string, string>();
+ const deps: PeerUsageSyncDeps = {
+ userId: () => userId,
+ selfDeviceId: () => 'self',
+ listDevices: async () => ({ devices: [device({ deviceId: 'self', isSelf: true })] }),
+ invoke: vi.fn(async () => ({ ok: false as const, error: { code: 'TIMEOUT', message: 'x' } })),
+ readCache: async (id) => written.get(id) ?? null,
+ writeCache: async (id, contents) => {
+ written.set(id, contents);
+ },
+ now: () => now,
+ ...over,
+ };
+ return {
+ deps,
+ written,
+ advance: (ms: number) => {
+ now += ms;
+ },
+ setUser: (id: string | null) => {
+ userId = id;
+ },
+ };
+}
+
+describe('usage device rows wire format', () => {
+ it('round-trips rows, filters by sinceDay and validates requests', async () => {
+ const rows = rowsFor(['2026-09-24', '2026-09-25', '2026-09-26']);
+ const decoded = await decodeUsageDeviceRowsResponse(
+ await hostResponse(rows, '2026-09-26', '2026-09-25'),
+ );
+ expect(decoded).toMatchObject({ kind: 'rows', todayKey: '2026-09-26', sinceDay: '2026-09-25' });
+ if (decoded?.kind !== 'rows') throw new Error('expected rows');
+ expect(decoded.rows.spendDays.map((row) => row.day)).toEqual(['2026-09-25', '2026-09-26']);
+ expect(decoded.rows.modelRows.map((row) => row.day)).toEqual(['2026-09-25', '2026-09-26']);
+
+ expect(parseUsageDeviceRowsRequest(undefined)).toEqual({ sinceDay: null });
+ expect(parseUsageDeviceRowsRequest({ sinceDay: '2026-09-25' })).toEqual({
+ sinceDay: '2026-09-25',
+ });
+ expect(parseUsageDeviceRowsRequest({ sinceDay: 'yesterday' })).toBeNull();
+ expect(parseUsageDeviceRowsRequest('2026-09-25')).toBeNull();
+ });
+
+ it('rejects malformed responses and drops malformed rows', async () => {
+ expect(await decodeUsageDeviceRowsResponse(null)).toBeNull();
+ expect(await decodeUsageDeviceRowsResponse({ format: 'other' })).toBeNull();
+ expect(
+ await decodeUsageDeviceRowsResponse({
+ format: 'usage-device-rows-v1',
+ todayKey: '2026-09-26',
+ sinceDay: null,
+ rowsGz: 'not-gzip',
+ }),
+ ).toBeNull();
+ expect(
+ await decodeUsageDeviceRowsResponse({ format: 'usage-device-rows-v1', oversize: true }),
+ ).toEqual({
+ kind: 'oversize',
+ });
+
+ const bad = {
+ spendDays: [{ day: 'bad', monies: [usd(1)] }],
+ modelRows: [
+ { ...rowsFor(['2026-09-26']).modelRows[0], agentKind: 'other' },
+ { ...rowsFor(['2026-09-26']).modelRows[0], inputTokens: -5 },
+ ],
+ };
+ const decoded = await decodeUsageDeviceRowsResponse(
+ await readUsageDeviceRows(
+ {
+ getAllSpendDays: async () => bad.spendDays,
+ getModelUsageSince: async () => bad.modelRows as never,
+ getSessionUsageSince: async () => ({ rows: [], tasks: [] }),
+ remoteVisibleTaskIds: async (ids) => new Set(ids),
+ todayKey: () => '2026-09-26',
+ },
+ { sinceDay: null },
+ ),
+ );
+ if (decoded?.kind !== 'rows') throw new Error('expected rows');
+ expect(decoded.rows.spendDays).toEqual([]);
+ expect(decoded.rows.modelRows).toHaveLength(1);
+ expect(decoded.rows.modelRows[0].inputTokens).toBe(0);
+ });
+
+ it('rejects timestamps outside the Date range from peers and the disk cache', () => {
+ const rows = sanitizeUsageDeviceRows({
+ spendDays: [],
+ modelRows: [],
+ sessionRows: [],
+ tasks: [
+ { sessionId: 'far', title: 't', model: 'm', lastActiveAt: 1e17 },
+ { sessionId: 'ok', title: 't', model: 'm', lastActiveAt: 1_790_000_000_000 },
+ ],
+ });
+ expect(rows?.tasks.map((task) => [task.sessionId, task.lastActiveAt])).toEqual([
+ ['far', 0],
+ ['ok', 1_790_000_000_000],
+ ]);
+ expect(isUnixMs(8.64e15)).toBe(true);
+ expect(isUnixMs(8.64e15 + 1)).toBe(false);
+ });
+
+ it('drops a cached peer whose sync time is outside the Date range', async () => {
+ const h = harness({
+ readCache: async () =>
+ JSON.stringify({
+ version: 2,
+ peers: {
+ laptop: {
+ name: 'L',
+ platform: 'darwin',
+ syncedAt: 1e17,
+ todayKey: '2026-09-26',
+ rows: rowsFor(['2026-09-26']),
+ },
+ },
+ }),
+ });
+ expect((await createPeerUsageSync(h.deps).snapshot()).peerRows.size).toBe(0);
+ });
+
+ it('sends only remotely visible tasks and their rows', async () => {
+ const task = (sessionId: string) => ({
+ sessionId,
+ title: sessionId,
+ model: 'm',
+ providerId: null,
+ contextTokens: 0,
+ contextWindow: 0,
+ lastActiveAt: 1,
+ });
+ const decoded = await decodeUsageDeviceRowsResponse(
+ await readUsageDeviceRows(
+ {
+ getAllSpendDays: async () => [],
+ getModelUsageSince: async () => [],
+ getSessionUsageSince: async () => ({
+ rows: [
+ { day: '2026-09-26', sessionId: 'ordinary', tokens: 3 },
+ { day: '2026-09-26', sessionId: 'hidden-bot', tokens: 4 },
+ ],
+ tasks: [task('ordinary'), task('hidden-bot')],
+ }),
+ remoteVisibleTaskIds: async () => new Set(['ordinary']),
+ todayKey: () => '2026-09-26',
+ },
+ { sinceDay: null },
+ ),
+ );
+ if (decoded?.kind !== 'rows') throw new Error('expected rows');
+ expect(decoded.rows.tasks.map((row) => row.sessionId)).toEqual(['ordinary']);
+ expect(decoded.rows.sessionRows.map((row) => row.sessionId)).toEqual(['ordinary']);
+ });
+
+ it('replaces task metadata wholesale and drops rows of tasks that disappeared', () => {
+ const task = (sessionId: string, title: string) => ({
+ sessionId,
+ title,
+ model: 'm',
+ providerId: null,
+ contextTokens: 0,
+ contextWindow: 0,
+ lastActiveAt: 1,
+ });
+ const cached: UsageDeviceRows = {
+ ...rowsFor(['2026-09-20']),
+ sessionRows: [
+ { day: '2026-09-20', sessionId: 'renamed', tokens: 1 },
+ { day: '2026-09-20', sessionId: 'deleted', tokens: 2 },
+ ],
+ tasks: [task('renamed', 'Old'), task('deleted', 'Gone')],
+ };
+ // 两个任务在增量区间内都没有新用量;被控端返回的是全部任务的当前元数据。
+ const merged = mergeIncrementalRows(cached, '2026-09-25', {
+ ...rowsFor(['2026-09-25']),
+ tasks: [task('renamed', 'New')],
+ });
+ expect(merged.tasks.map((row) => [row.sessionId, row.title])).toEqual([['renamed', 'New']]);
+ expect(merged.sessionRows.map((row) => row.sessionId)).toEqual(['renamed']);
+ });
+
+ it('replaces only the incremental window when merging', () => {
+ const cached = rowsFor(['2026-09-24', '2026-09-25'], 1);
+ const merged = mergeIncrementalRows(
+ cached,
+ '2026-09-25',
+ rowsFor(['2026-09-25', '2026-09-26'], 9),
+ );
+ expect(merged.modelRows.map((row) => [row.day, row.inputTokens])).toEqual([
+ ['2026-09-24', 1],
+ ['2026-09-25', 9],
+ ['2026-09-26', 9],
+ ]);
+ expect(mergeIncrementalRows(cached, null, rowsFor(['2026-09-26']))).toEqual(
+ rowsFor(['2026-09-26']),
+ );
+ });
+});
+
+describe('createPeerUsageSync', () => {
+ it('reads online permitted computers, skips phones and reports why others are missing', async () => {
+ const invoke = vi.fn(async (deviceId: string) => {
+ if (deviceId === 'old')
+ return { ok: false as const, error: { code: 'CHANNEL_NOT_ALLOWED', message: 'x' } };
+ return {
+ ok: true as const,
+ result: await hostResponse(rowsFor(['2026-09-26']), '2026-09-26', null),
+ };
+ });
+ const h = harness({
+ invoke,
+ listDevices: async () => ({
+ devices: [
+ device({ deviceId: 'self', isSelf: true, name: 'Studio' }),
+ device({ deviceId: 'laptop', name: 'Laptop' }),
+ device({ deviceId: 'phone', platform: 'ios' }),
+ device({ deviceId: 'sleeping', online: false }),
+ device({ deviceId: 'locked', remoteControlEnabled: false }),
+ device({ deviceId: 'old' }),
+ ],
+ }),
+ });
+ const sync = createPeerUsageSync(h.deps);
+
+ await sync.sync();
+
+ expect(invoke.mock.calls.map((call) => call[0]).sort()).toEqual(['laptop', 'old']);
+ expect(invoke).toHaveBeenCalledWith('laptop', 'maker:usage:device-rows', [{}]);
+ const snapshot = await sync.snapshot();
+ expect(snapshot.devices.map((d) => [d.deviceId, d.status])).toEqual([
+ ['self', 'ok'],
+ ['laptop', 'ok'],
+ ['sleeping', 'offline'],
+ ['locked', 'remote-disabled'],
+ ['old', 'unsupported'],
+ ]);
+ expect([...snapshot.peerRows.keys()]).toEqual(['laptop']);
+ expect(JSON.parse(h.written.get('user-a') ?? '{}').peers.laptop.name).toBe('Laptop');
+ });
+
+ it('never connects released versions without background links and retries unsupported ones only after an update', async () => {
+ const invoke = vi.fn<PeerUsageSyncDeps['invoke']>(async () => ({
+ ok: false as const,
+ error: { code: 'UNSUPPORTED_CAPABILITY', message: 'x' },
+ }));
+ let candidateVersion = '0.1.94';
+ const h = harness({
+ invoke,
+ listDevices: async () => ({
+ devices: [
+ device({ deviceId: 'self', isSelf: true }),
+ device({ deviceId: 'released', appVersion: '0.1.93' }),
+ device({ deviceId: 'beta', appVersion: '0.1.93-beta' }),
+ device({ deviceId: 'unknown', appVersion: null }),
+ device({ deviceId: 'candidate', appVersion: candidateVersion }),
+ ],
+ }),
+ });
+ const sync = createPeerUsageSync(h.deps);
+
+ await sync.sync();
+ // 旧正式版 / 版本未知:连都不连(建链就会让对方显示受控);只尝试更新的版本。
+ expect(invoke.mock.calls.map((call) => call[0])).toEqual(['candidate']);
+ expect((await sync.snapshot()).devices.map((d) => [d.deviceId, d.status])).toEqual([
+ ['self', 'ok'],
+ ['released', 'unsupported'],
+ ['beta', 'unsupported'],
+ ['unknown', 'unsupported'],
+ ['candidate', 'unsupported'],
+ ]);
+
+ // 同一版本不再重试;对方更新后再试一次。
+ h.advance(61_000);
+ await sync.sync();
+ expect(invoke).toHaveBeenCalledTimes(1);
+ candidateVersion = '0.1.95';
+ h.advance(61_000);
+ await sync.sync();
+ expect(invoke).toHaveBeenCalledTimes(2);
+ });
+
+ it('allows local development builds through to the link capability check', () => {
+ expect(mayServeBackgroundRead('0.0.0')).toBe(true);
+ expect(mayServeBackgroundRead('0.1.94')).toBe(true);
+ expect(mayServeBackgroundRead('0.1.93')).toBe(false);
+ expect(mayServeBackgroundRead(null)).toBe(false);
+ });
+
+ it('throttles, then syncs incrementally from the day before the cached day', async () => {
+ const invoke = vi.fn(async (_id: string, _channel: string, args: unknown[]) => {
+ const sinceDay = (args[0] as { sinceDay?: string }).sinceDay ?? null;
+ const rows = sinceDay
+ ? rowsFor(['2026-09-26', '2026-09-27'], 5)
+ : rowsFor(['2026-09-25', '2026-09-26'], 1);
+ return {
+ ok: true as const,
+ result: await hostResponse(rows, sinceDay ? '2026-09-27' : '2026-09-26', sinceDay),
+ };
+ });
+ const h = harness({
+ invoke,
+ listDevices: async () => ({ devices: [device({ deviceId: 'laptop' })] }),
+ });
+ const sync = createPeerUsageSync(h.deps);
+
+ await sync.sync();
+ await sync.sync();
+ expect(invoke).toHaveBeenCalledTimes(1);
+
+ h.advance(61_000);
+ await sync.sync();
+ expect(invoke).toHaveBeenLastCalledWith('laptop', 'maker:usage:device-rows', [
+ { sinceDay: '2026-09-25' },
+ ]);
+ const rows = (await sync.snapshot()).peerRows.get('laptop');
+ expect(rows?.modelRows.map((row) => [row.day, row.inputTokens])).toEqual([
+ ['2026-09-26', 5],
+ ['2026-09-27', 5],
+ ]);
+ });
+
+ it('keeps cached rows when a later read fails, and forgets removed devices', async () => {
+ let fail = false;
+ let listed = true;
+ const h = harness({
+ invoke: async () =>
+ fail
+ ? { ok: false as const, error: { code: 'TIMEOUT', message: 'x' } }
+ : {
+ ok: true as const,
+ result: await hostResponse(rowsFor(['2026-09-26']), '2026-09-26', null),
+ },
+ listDevices: async () => ({ devices: listed ? [device({ deviceId: 'laptop' })] : [] }),
+ });
+ const sync = createPeerUsageSync(h.deps);
+ await sync.sync();
+
+ fail = true;
+ h.advance(61_000);
+ await sync.sync();
+ let snapshot = await sync.snapshot();
+ expect(snapshot.devices[0]).toMatchObject({
+ deviceId: 'laptop',
+ status: 'offline',
+ syncedAt: 1_000_000,
+ });
+ expect(snapshot.peerRows.has('laptop')).toBe(true);
+
+ // 新进程从磁盘缓存恢复, 目录读到之前照常参与合并。
+ const restored = createPeerUsageSync({
+ ...h.deps,
+ listDevices: async () => Promise.reject(new Error('offline')),
+ });
+ expect((await restored.snapshot()).peerRows.has('laptop')).toBe(true);
+
+ listed = false;
+ h.advance(61_000);
+ await sync.sync();
+ snapshot = await sync.snapshot();
+ expect(snapshot.devices).toEqual([]);
+ expect(snapshot.peerRows.size).toBe(0);
+ });
+
+ it('marks previously read computers unreadable when the device directory fails', async () => {
+ let directoryFails = false;
+ const h = harness({
+ invoke: async () => ({
+ ok: true as const,
+ result: await hostResponse(rowsFor(['2026-09-26']), '2026-09-26', null),
+ }),
+ listDevices: async () => {
+ if (directoryFails) throw new Error('offline');
+ return { devices: [device({ deviceId: 'laptop' })] };
+ },
+ });
+ const sync = createPeerUsageSync(h.deps);
+ await sync.sync();
+ expect((await sync.snapshot()).devices[0].status).toBe('ok');
+
+ directoryFails = true;
+ h.advance(61_000);
+ const before = sync.version();
+ await sync.sync();
+ const snapshot = await sync.snapshot();
+ expect(snapshot.devices[0]).toMatchObject({
+ deviceId: 'laptop',
+ status: 'error',
+ syncedAt: 1_000_000,
+ });
+ expect(snapshot.peerRows.has('laptop')).toBe(true);
+ // 用量行没变:聚合版本不动,读取失败的状态作为展示元数据在读取时附上。
+ expect(sync.version()).toBe(before);
+ });
+
+ it('starts a fresh sync for a new account instead of waiting on the old one, and drops late old writes', async () => {
+ let releaseOld!: () => void;
+ const oldGate = new Promise<void>((resolve) => {
+ releaseOld = resolve;
+ });
+ let userForListing = 'user-a';
+ const invoked: string[] = [];
+ const h = harness({
+ invoke: async (deviceId) => {
+ invoked.push(deviceId);
+ if (deviceId === 'laptop-a') {
+ await oldGate;
+ return { ok: false as const, error: { code: 'TIMEOUT', message: 'late' } };
+ }
+ return {
+ ok: true as const,
+ result: await hostResponse(rowsFor(['2026-09-26']), '2026-09-26', null),
+ };
+ },
+ listDevices: async () => ({
+ devices: [device({ deviceId: userForListing === 'user-a' ? 'laptop-a' : 'laptop-b' })],
+ }),
+ });
+ const sync = createPeerUsageSync(h.deps);
+ const oldRun = sync.sync();
+ await vi.waitFor(() => expect(invoked).toContain('laptop-a'));
+
+ h.setUser('user-b');
+ userForListing = 'user-b';
+ await sync.sync();
+ expect(invoked).toContain('laptop-b');
+ expect([...(await sync.snapshot()).peerRows.keys()]).toEqual(['laptop-b']);
+
+ releaseOld();
+ await oldRun;
+ const snapshot = await sync.snapshot();
+ expect(snapshot.devices.map((d) => [d.deviceId, d.status])).toEqual([['laptop-b', 'ok']]);
+ expect(h.written.has('user-a')).toBe(false);
+ });
+
+ it('keeps the data version stable when a sync changes nothing (no other computers)', async () => {
+ const h = harness({
+ listDevices: async () => ({ devices: [device({ deviceId: 'self', isSelf: true })] }),
+ });
+ const sync = createPeerUsageSync(h.deps);
+ await sync.sync();
+ const settled = sync.version();
+ for (let i = 0; i < 3; i += 1) {
+ h.advance(61_000);
+ await sync.sync();
+ }
+ expect(sync.version()).toBe(settled);
+ });
+
+ it('does not list devices or invoke peers while Device Link access is denied', async () => {
+ let allowed = true;
+ const listDevices = vi.fn(async () => ({ devices: [device({ deviceId: 'laptop' })] }));
+ const invoke = vi.fn(async () => ({
+ ok: true as const,
+ result: await hostResponse(rowsFor(['2026-09-26']), '2026-09-26', null),
+ }));
+ const h = harness({ listDevices, invoke });
+ const sync = createPeerUsageSync(
+ withPeerUsageAccessGate(() => {
+ if (!allowed) throw new Error('[PERMISSION_DENIED] Device Link requires a Cindy account.');
+ }, h.deps),
+ );
+ await sync.sync();
+ expect(invoke).toHaveBeenCalledTimes(1);
+
+ allowed = false;
+ h.advance(61_000);
+ await sync.sync();
+ expect(listDevices).toHaveBeenCalledTimes(1);
+ expect(invoke).toHaveBeenCalledTimes(1);
+ const snapshot = await sync.snapshot();
+ expect(snapshot.devices[0]).toMatchObject({ deviceId: 'laptop', status: 'error' });
+ expect(snapshot.peerRows.has('laptop')).toBe(true);
+ });
+
+ it('drops a disk cache that finishes loading after the account changed', async () => {
+ let releaseCache!: (raw: string) => void;
+ const cacheGate = new Promise<string>((resolve) => {
+ releaseCache = resolve;
+ });
+ const h = harness();
+ const oldCache = JSON.stringify({
+ version: 2,
+ peers: {
+ laptop: {
+ name: 'Old account laptop',
+ platform: 'darwin',
+ syncedAt: 1,
+ todayKey: '2026-09-26',
+ rows: rowsFor(['2026-09-26']),
+ },
+ },
+ });
+ const sync = createPeerUsageSync({
+ ...h.deps,
+ readCache: (id) => (id === 'user-a' ? cacheGate : Promise.resolve(null)),
+ });
+ const pending = sync.snapshot();
+ // 读缓存期间切换账号,且在缓存返回前没有其它调用触发 reset。
+ h.setUser('user-b');
+ releaseCache(oldCache);
+ const snapshot = await pending;
+ expect(snapshot.peerRows.size).toBe(0);
+ expect(snapshot.devices).toEqual([]);
+ expect((await sync.snapshot()).peerRows.size).toBe(0);
+ });
+});
diff --git a/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts b/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
index 93145653bd..428959fb1e 100644
--- a/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
@@ -17,6 +17,10 @@ vi.mock('../../localDb/dailySpend', () => ({
vi.mock('../../localDb/dailyModelUsage', () => ({
getModelUsageSince: vi.fn(),
}));
+vi.mock('../../localDb/dailySessionUsage', () => ({
+ getSessionUsageSince: vi.fn(async () => ({ rows: [], tasks: [] })),
+ getUsageTaskMeta: vi.fn(async () => []),
+}));
vi.mock('../../localDb/client/current', () => ({
getCurrentDbClientUserId: () => currentDbClient.userId,
}));
@@ -102,6 +106,7 @@ vi.mock('../../logger', () => ({
}),
}));
+import { getSessionUsageSince, getUsageTaskMeta } from '../../localDb/dailySessionUsage';
import {
__resetUsageHistoryCacheForTesting,
claudeSubscriptionUsageModelKey,
@@ -116,8 +121,17 @@ import {
readUsageHistory,
readUsageHistoryWith,
shiftDayKey,
+ combineUsageDeviceRows,
+ usageHistoryDepsForScope,
+ clampPeerRowsToToday,
type UsageHistoryDeps,
} from '../usageHistory';
+import {
+ __resetPeerUsageSyncForTesting,
+ configurePeerUsageSync,
+ type PeerUsageSyncDeps,
+} from '../peerUsageSync';
+import { readUsageDeviceRows } from '../usageDeviceRows';
import { getAllSpendDays } from '../../localDb/dailySpend';
import { getModelUsageSince } from '../../localDb/dailyModelUsage';
import { getGatewayModelPricing, isModelPricingRefreshInFlight } from '../modelPricing';
@@ -212,6 +226,7 @@ beforeEach(async () => {
);
currentDbClient.userId = 'user-a';
__resetUsageHistoryCacheForTesting();
+ __resetPeerUsageSyncForTesting();
// 账本币种是跨用例的模块级状态,逐例重置,不受前一例显式设定的账号币种影响。
// 重置后必须再显式落一次账号币种:生产里由 modelPricing(报价目录同步/磁盘快照
// 恢复)写入,而本文件把它整体 mock 掉了;不落这一笔,回退链会落到与构建区域
@@ -223,6 +238,8 @@ beforeEach(async () => {
setActiveLedgerCurrency(DEFAULT_USAGE_CURRENCY);
vi.mocked(getAllSpendDays).mockResolvedValue([]);
vi.mocked(getModelUsageSince).mockResolvedValue([]);
+ vi.mocked(getSessionUsageSince).mockResolvedValue({ rows: [], tasks: [] });
+ vi.mocked(getUsageTaskMeta).mockResolvedValue([]);
vi.mocked(getGatewayModelPricing).mockResolvedValue(null);
vi.mocked(getReferenceModelPricing).mockReturnValue({});
vi.mocked(isModelPricingRefreshInFlight).mockReturnValue(false);
@@ -817,6 +834,41 @@ describe('readUsageHistoryWith', () => {
});
describe('production cache and empty payload', () => {
+ it('overlays current local task metadata on a cached aggregate', async () => {
+ const meta = (sessionId: string, title: string) => ({
+ sessionId,
+ title,
+ model: 'gpt-5.5',
+ providerId: null,
+ contextTokens: 0,
+ contextWindow: 0,
+ lastActiveAt: 1,
+ });
+ vi.mocked(getSessionUsageSince).mockResolvedValue({
+ rows: [
+ { day: TODAY, sessionId: 's1', tokens: 5 },
+ { day: TODAY, sessionId: 's2', tokens: 7 },
+ ],
+ tasks: [meta('s1', 'Old title'), meta('s2', 'Doomed')],
+ });
+ vi.mocked(getUsageTaskMeta).mockResolvedValue([meta('s1', 'Old title'), meta('s2', 'Doomed')]);
+ const first = await readUsageHistory({ days: 30, includeTasks: true });
+ expect(first.tasks?.map((task) => task.title)).toEqual(['Old title', 'Doomed']);
+ // 重命名 s1、删除 s2:不产生用量,聚合缓存照常复用,但出口的任务元数据必须是当前值。
+ vi.mocked(getUsageTaskMeta).mockResolvedValue([meta('s1', 'New title')]);
+ const second = await readUsageHistory({ days: 30, includeTasks: true });
+ expect(second.tasks?.map((task) => [task.sessionId, task.title])).toEqual([['s1', 'New title']]);
+ expect(getSessionUsageSince).toHaveBeenCalledTimes(1);
+ });
+
+ it('skips task data unless the caller asks for it (home dashboard reads)', async () => {
+ const payload = await readUsageHistory({ days: 30 });
+ expect(payload.tasks).toBeUndefined();
+ expect(payload.taskDaily).toBeUndefined();
+ expect(getSessionUsageSince).not.toHaveBeenCalled();
+ expect(getUsageTaskMeta).not.toHaveBeenCalled();
+ });
+
it('writes a structured fresh payload and serves it from memory', async () => {
vi.mocked(getAllSpendDays).mockResolvedValue([
{ day: TODAY, monies: [actual(2)] },
@@ -856,3 +908,337 @@ describe('production cache and empty payload', () => {
);
});
});
+
+describe('multi-device scope', () => {
+ const peerRows = {
+ sessionRows: [],
+ tasks: [],
+ spendDays: [
+ { day: '2026-06-10', monies: [actual(3)] },
+ { day: TODAY, monies: [actual(3)] },
+ ],
+ modelRows: [
+ modelRow(TODAY, 'codex', 'gpt-5.5', actual(0), { inputTokens: 100 }),
+ modelRow('2026-06-10', 'claude-code', 'claude-sonnet-5', actual(3), { outputTokens: 50 }),
+ ],
+ };
+
+ it('merges identical model keys from different devices into one row', () => {
+ const combined = combineUsageDeviceRows([
+ {
+ sessionRows: [],
+ tasks: [],
+ spendDays: [{ day: TODAY, monies: [actual(1)] }],
+ modelRows: [modelRow(TODAY, 'codex', 'gpt-5.5', actual(1), { inputTokens: 10 })],
+ },
+ {
+ sessionRows: [],
+ tasks: [],
+ spendDays: [{ day: TODAY, monies: [actual(2)] }],
+ modelRows: [modelRow(TODAY, 'codex', 'gpt-5.5', actual(2), { inputTokens: 5, outputTokens: 7 })],
+ },
+ ]);
+ expect(combined.spendDays).toEqual([{ day: TODAY, monies: [actual(1), actual(2)] }]);
+ expect(combined.modelRows).toHaveLength(1);
+ expect(combined.modelRows[0]).toMatchObject({
+ money: actual(3),
+ inputTokens: 15,
+ outputTokens: 7,
+ });
+ });
+
+ it('aggregates local plus peer rows for all devices, and only the peer for a device scope', async () => {
+ const base = makeDeps({
+ getAllSpendDays: async () => [{ day: TODAY, monies: [actual(2)] }],
+ getModelUsageSince: async () => [
+ modelRow(TODAY, 'codex', 'gpt-5.5', actual(0), { inputTokens: 40 }),
+ ],
+ });
+ const snapshot = { peerRows: new Map([['device-b', peerRows]]) };
+
+ const all = await readUsageHistoryWith(usageHistoryDepsForScope(base, 'all', snapshot), {
+ days: 'all',
+ modelDays: 'all',
+ });
+ expect(all.totals.today).toEqual(actual(5));
+ expect(all.totals.todayTokens).toBe(140);
+ expect(all.modelDaily.filter((row) => row.day === TODAY)).toHaveLength(1);
+ expect(all.streak.current).toBe(2);
+
+ const peerOnly = await readUsageHistoryWith(usageHistoryDepsForScope(base, 'device-b', snapshot), {
+ days: 'all',
+ modelDays: 'all',
+ });
+ expect(peerOnly.totals.today).toEqual(actual(3));
+ expect(peerOnly.totals.todayTokens).toBe(100);
+
+ const unknown = await readUsageHistoryWith(usageHistoryDepsForScope(base, 'device-x', snapshot));
+ expect(unknown.days).toEqual([]);
+
+ expect(usageHistoryDepsForScope(base, 'local', snapshot)).toBe(base);
+ });
+
+ it('counts a peer that is already on tomorrow into the controller today', async () => {
+ const tomorrow = shiftDayKey(TODAY, 1);
+ const ahead = {
+ sessionRows: [],
+ tasks: [],
+ spendDays: [{ day: tomorrow, monies: [actual(4)] }],
+ modelRows: [modelRow(tomorrow, 'codex', 'gpt-5.5', actual(0), { inputTokens: 70 })],
+ };
+ expect(clampPeerRowsToToday(ahead, TODAY).modelRows[0].day).toBe(TODAY);
+
+ const base = makeDeps({
+ getAllSpendDays: async () => [{ day: TODAY, monies: [actual(2)] }],
+ getModelUsageSince: async () => [
+ modelRow(TODAY, 'codex', 'gpt-5.5', actual(0), { inputTokens: 30 }),
+ ],
+ });
+ const snapshot = { peerRows: new Map([['device-b', ahead]]) };
+ const all = await readUsageHistoryWith(usageHistoryDepsForScope(base, 'all', snapshot), {
+ days: 'all',
+ modelDays: 'all',
+ });
+ expect(all.totals.today).toEqual(actual(6));
+ expect(all.totals.todayTokens).toBe(100);
+ expect(all.days.map((d) => d.day)).toEqual([TODAY]);
+
+ const peerOnly = await readUsageHistoryWith(
+ usageHistoryDepsForScope(base, 'device-b', snapshot),
+ { days: 'all', modelDays: 'all' },
+ );
+ expect(peerOnly.totals.todayTokens).toBe(70);
+ });
+
+ it('round-trips a peer through the device-rows wire format into the all-devices payload', async () => {
+ vi.mocked(getAllSpendDays).mockResolvedValue([{ day: TODAY, monies: [actual(2)] }]);
+ const response = await readUsageDeviceRows(
+ {
+ getAllSpendDays: async () => peerRows.spendDays,
+ getModelUsageSince: async () => peerRows.modelRows,
+ getSessionUsageSince: async () => ({ rows: [], tasks: [] }),
+ remoteVisibleTaskIds: async (ids) => new Set(ids),
+todayKey: () => TODAY,
+ },
+ { sinceDay: null },
+ );
+ let resolveInvoke!: () => void;
+ const invokeGate = new Promise<void>((resolve) => {
+ resolveInvoke = resolve;
+ });
+ const deps: PeerUsageSyncDeps = {
+ userId: () => 'user-a',
+ selfDeviceId: () => 'device-a',
+ listDevices: async () => ({
+ devices: [
+ {
+ deviceId: 'device-a', name: 'Studio', platform: 'darwin', appVersion: null, lastSeenAt: null,
+ online: true, busy: false, remoteControlEnabled: true, controlEnabled: true, isSelf: true,
+ },
+ {
+ deviceId: 'device-b', name: 'Laptop', platform: 'darwin', appVersion: '0.1.94', lastSeenAt: null,
+ online: true, busy: false, remoteControlEnabled: true, controlEnabled: true, isSelf: false,
+ },
+ ],
+ }),
+ invoke: async () => {
+ await invokeGate;
+ return { ok: true, result: response };
+ },
+ readCache: async () => null,
+ writeCache: async () => undefined,
+ now: () => Date.now(),
+ };
+ configurePeerUsageSync(deps);
+
+ const first = await readUsageHistory({ days: 'all', modelDays: 'all', device: 'all' });
+ expect(first.stale).toBe(true);
+ expect(first.devicesSyncing).toBe(true);
+ expect(first.totals.today).toEqual(actual(2));
+
+ resolveInvoke();
+ await vi.waitFor(async () => {
+ const next = await readUsageHistory({ days: 'all', modelDays: 'all', device: 'all' });
+ expect(next.stale).toBe(false);
+ expect(next.totals.today).toEqual(actual(5));
+ expect(next.devices?.map((device) => [device.name, device.isSelf, device.status])).toEqual([
+ ['Studio', true, 'ok'],
+ ['Laptop', false, 'ok'],
+ ]);
+ });
+
+ // 本机范围不受跨设备数据影响, 也不带设备列表。
+ const local = await readUsageHistory({ days: 'all', modelDays: 'all' });
+ expect(local.totals.today).toEqual(actual(2));
+ expect(local.devices).toBeUndefined();
+ });
+
+ it('does not mark an aggregate fresh when the peer sync finished while it was being computed', async () => {
+ const response = await readUsageDeviceRows(
+ {
+ getAllSpendDays: async () => peerRows.spendDays,
+ getModelUsageSince: async () => peerRows.modelRows,
+ getSessionUsageSince: async () => ({ rows: [], tasks: [] }),
+ remoteVisibleTaskIds: async (ids) => new Set(ids),
+todayKey: () => TODAY,
+ },
+ { sinceDay: null },
+ );
+ let releaseInvoke!: () => void;
+ const invokeGate = new Promise<void>((resolve) => {
+ releaseInvoke = resolve;
+ });
+ let releaseLocal!: () => void;
+ const localGate = new Promise<void>((resolve) => {
+ releaseLocal = resolve;
+ });
+ let localReads = 0;
+ vi.mocked(getAllSpendDays).mockImplementation(async () => {
+ localReads += 1;
+ if (localReads === 1) await localGate;
+ return [{ day: TODAY, monies: [actual(2)] }];
+ });
+ configurePeerUsageSync({
+ userId: () => 'user-a',
+ selfDeviceId: () => 'device-a',
+ listDevices: async () => ({
+ devices: [
+ {
+ deviceId: 'device-b', name: 'Laptop', platform: 'darwin', appVersion: '0.1.94', lastSeenAt: null,
+ online: true, busy: false, remoteControlEnabled: true, controlEnabled: true, isSelf: false,
+ },
+ ],
+ }),
+ invoke: async () => {
+ await invokeGate;
+ return { ok: true, result: response };
+ },
+ readCache: async () => null,
+ writeCache: async () => undefined,
+ now: () => Date.now(),
+ });
+
+ const opts = { days: 'all' as const, modelDays: 'all' as const, device: 'all' };
+ const first = readUsageHistory(opts);
+ // 聚合已拿到旧快照并卡在读本机日账时, 让跨设备同步完成。
+ await vi.waitFor(() => expect(localReads).toBe(1));
+ releaseInvoke();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ releaseLocal();
+ const settled = await first;
+ expect(settled.stale).toBe(true);
+ expect(settled.totals.today).toEqual(actual(2));
+
+ await vi.waitFor(async () => {
+ const next = await readUsageHistory(opts);
+ expect(next.stale).toBe(false);
+ expect(next.totals.today).toEqual(actual(5));
+ });
+ });
+
+ it('does not re-aggregate the full history on periodic re-reads when nothing changed', async () => {
+ let now = 1_800_000_000_000;
+ vi.spyOn(Date, 'now').mockImplementation(() => now);
+ vi.mocked(getAllSpendDays).mockResolvedValue([{ day: TODAY, monies: [actual(2)] }]);
+ configurePeerUsageSync({
+ userId: () => 'user-a',
+ selfDeviceId: () => 'device-a',
+ listDevices: async () => ({
+ devices: [
+ {
+ deviceId: 'device-a', name: 'Studio', platform: 'darwin', appVersion: null, lastSeenAt: null,
+ online: true, busy: false, remoteControlEnabled: true, controlEnabled: true, isSelf: true,
+ },
+ ],
+ }),
+ invoke: async () => ({ ok: false, error: { code: 'TIMEOUT', message: 'unused' } }),
+ readCache: async () => null,
+ writeCache: async () => undefined,
+ now: () => now,
+ });
+ const opts = { days: 'all' as const, modelDays: 'all' as const, device: 'all' };
+ await vi.waitFor(async () => expect((await readUsageHistory(opts)).stale).toBe(false));
+ const readsAfterSettle = vi.mocked(getAllSpendDays).mock.calls.length;
+
+ // 设置页每分钟一次的定时重读:没有其它电脑、本机也没有新用量。
+ // 每次重读会触发一轮(节流的)设备同步,同步期间如实标为更新中;同步结束后结果即为最新。
+ for (let i = 0; i < 3; i += 1) {
+ now += 61_000;
+ await readUsageHistory(opts);
+ await vi.waitFor(async () => expect((await readUsageHistory(opts)).stale).toBe(false));
+ }
+ expect(vi.mocked(getAllSpendDays).mock.calls.length).toBe(readsAfterSettle);
+
+ // 本机有新用量时照常经 forceRefresh 重聚合。
+ now += 1_000;
+ await readUsageHistory({ ...opts, forceRefresh: true });
+ expect(vi.mocked(getAllSpendDays).mock.calls.length).toBeGreaterThan(readsAfterSettle);
+ });
+
+ it('refreshes peer sync time without re-aggregating until peer rows actually change', async () => {
+ let now = 1_800_000_000_000;
+ vi.spyOn(Date, 'now').mockImplementation(() => now);
+ vi.mocked(getAllSpendDays).mockResolvedValue([{ day: TODAY, monies: [actual(2)] }]);
+ let peerTokens = 10;
+ configurePeerUsageSync({
+ userId: () => 'user-a',
+ selfDeviceId: () => 'device-a',
+ listDevices: async () => ({
+ devices: [
+ {
+ deviceId: 'device-b', name: 'Laptop', platform: 'darwin', appVersion: '0.1.94', lastSeenAt: null,
+ online: true, busy: false, remoteControlEnabled: true, controlEnabled: true, isSelf: false,
+ },
+ ],
+ }),
+ invoke: async () => ({
+ ok: true,
+ result: await readUsageDeviceRows(
+ {
+ getAllSpendDays: async () => [],
+ getModelUsageSince: async () => [
+ modelRow(TODAY, 'codex', 'gpt-5.5', actual(0), { inputTokens: peerTokens }),
+ ],
+ getSessionUsageSince: async () => ({ rows: [], tasks: [] }),
+ remoteVisibleTaskIds: async (ids) => new Set(ids),
+todayKey: () => TODAY,
+ },
+ { sinceDay: null },
+ ),
+ }),
+ readCache: async () => null,
+ writeCache: async () => undefined,
+ now: () => now,
+ });
+ const opts = { days: 'all' as const, modelDays: 'all' as const, device: 'all' };
+ const settled = async () => {
+ let last!: Awaited<ReturnType<typeof readUsageHistory>>;
+ await vi.waitFor(async () => {
+ last = await readUsageHistory(opts);
+ expect(last.stale).toBe(false);
+ });
+ return last;
+ };
+ const first = await settled();
+ expect(first.totals.todayTokens).toBe(10);
+ const aggregations = vi.mocked(getAllSpendDays).mock.calls.length;
+ const firstSyncedAt = first.devices?.find((d) => d.deviceId === 'device-b')?.syncedAt;
+
+ // 60 秒后的定时重读:对方成功同步但行没变 —— 同步时间更新,不重聚合全量历史。
+ now += 61_000;
+ await readUsageHistory(opts);
+ const second = await settled();
+ expect(vi.mocked(getAllSpendDays).mock.calls.length).toBe(aggregations);
+ expect(second.devices?.find((d) => d.deviceId === 'device-b')?.syncedAt).toBeGreaterThan(
+ firstSyncedAt ?? 0,
+ );
+
+ // 对方有新用量:行变化 → 重聚合一次。
+ peerTokens = 25;
+ now += 61_000;
+ await readUsageHistory(opts);
+ const third = await settled();
+ expect(third.totals.todayTokens).toBe(25);
+ expect(vi.mocked(getAllSpendDays).mock.calls.length).toBeGreaterThan(aggregations);
+ });
+});
diff --git a/apps/desktop/src/main/usage/peerUsageSync.ts b/apps/desktop/src/main/usage/peerUsageSync.ts
new file mode 100644
index 0000000000..80fd979b82
--- /dev/null
+++ b/apps/desktop/src/main/usage/peerUsageSync.ts
@@ -0,0 +1,547 @@
+/**
+ * peerUsageSync — 用量历史的跨设备拉取与本机缓存 (控制端)。
+ *
+ * 数据来源:同账号其它电脑经 device-link 的 `maker:usage:device-rows`(见
+ * usageDeviceRows.ts)。只能拉到**在线、对方开启远程控制、本机允许控制它**的电脑;
+ * 因此每台设备最近一次拿到的原始行按账号落盘缓存,设备离线时仍按上次数据合并,并在
+ * 设备列表里带上 syncedAt 让界面标注「数据截至」。
+ *
+ * 同步节奏:
+ * - 读取多设备范围的用量历史时触发(含本机 turn 结束后的刷新),统一按
+ * SYNC_MIN_INTERVAL_MS 节流;页面不打开就不会读其它设备。
+ * - 增量:已有缓存时从缓存 todayKey 的前一天起拉(对方当天、跨午夜前一天的行仍在变),
+ * 返回区间内的行整体替换缓存里同区间的行。
+ * - 并发上限 PEER_FANOUT,与伙伴跨设备目录同口径,不随设备数放大 relay 负载。
+ * - 单台失败只更新该设备状态,不清掉它的缓存,不影响其它设备,也不重试。
+ *
+ * 缓存只存按天聚合的 token / 金额行,不含会话、消息或任何凭证。
+ */
+
+import { compareAppUpdateVersions } from '../updateVersionPolicy.js';
+import { promises as fs } from 'node:fs';
+import path from 'node:path';
+
+import type { DeviceLinkDeviceView } from '../../shared/deviceLinkIpc.js';
+import { createLogger } from '../logger.js';
+import { MAKER_INVOKE } from '../maker-ipc/channels.js';
+import {
+ decodeUsageDeviceRowsResponse,
+ isDayKey,
+ isUnixMs,
+ sanitizeUsageDeviceRows,
+ type UsageDeviceRows,
+} from './usageDeviceRows.js';
+
+const log = createLogger('peerUsageSync');
+
+const USAGE_DEVICE_ROWS_CHANNEL = MAKER_INVOKE.USAGE_DEVICE_ROWS;
+const SYNC_MIN_INTERVAL_MS = 60_000;
+const PEER_FANOUT = 3;
+// v2:缓存行追加每日 × 任务用量;v1 缓存没有这部分,整份作废后全量重拉。
+const CACHE_VERSION = 2;
+const MOBILE_PLATFORMS = new Set(['ios', 'android']);
+
+export type UsageDeviceStatus =
+ /** 本次或最近一次已成功读取。 */
+ | 'ok'
+ /** 正在读取。 */
+ | 'syncing'
+ | 'offline'
+ /** 对方未开启远程控制,或本机关闭了对它的控制。 */
+ | 'remote-disabled'
+ /** 对方版本不支持读取用量。 */
+ | 'unsupported'
+ | 'error';
+
+export interface UsageDeviceSummary {
+ deviceId: string;
+ name: string;
+ platform: string | null;
+ isSelf: boolean;
+ /** 最近一次成功读取的时间;本机与从未读到的设备为 null。 */
+ syncedAt: number | null;
+ status: UsageDeviceStatus;
+}
+
+interface CachedPeer {
+ name: string;
+ platform: string | null;
+ syncedAt: number;
+ /** 对方读取时的本地 todayKey,作为下一次增量的锚点。 */
+ todayKey: string;
+ rows: UsageDeviceRows;
+}
+
+interface CacheFile {
+ version: number;
+ peers: Record<string, CachedPeer>;
+}
+
+export interface PeerUsageSyncDeps {
+ userId(): string | null;
+ selfDeviceId(): string | null;
+ listDevices(): Promise<{ devices: DeviceLinkDeviceView[] }>;
+ invoke(
+ deviceId: string,
+ channel: string,
+ args: unknown[],
+ ): Promise<
+ { ok: true; result: unknown } | { ok: false; error: { code: string; message: string } }
+ >;
+ readCache(userId: string): Promise<string | null>;
+ writeCache(userId: string, contents: string): Promise<void>;
+ now(): number;
+}
+
+export interface PeerUsageSnapshot {
+ /** 聚合版本:参与聚合的用量行变化时 +1(设备状态 / 目录 / 同步时间不影响)。 */
+ version: number;
+ selfDeviceId: string | null;
+ devices: UsageDeviceSummary[];
+ peerRows: ReadonlyMap<string, UsageDeviceRows>;
+}
+
+export interface PeerUsageSync {
+ /** 读当前已知的设备与缓存行(不发网络请求;首次调用会先读磁盘缓存)。 */
+ snapshot(): Promise<PeerUsageSnapshot>;
+ /** 节流地触发一次同步;返回本次(或在途)同步的 promise。 */
+ sync(): Promise<void>;
+ isSyncing(): boolean;
+ /** 当前数据版本(同 snapshot().version),同步读取供缓存新鲜度判断。 */
+ version(): number;
+}
+
+function dayBefore(dayKey: string): string {
+ const [y, m, d] = dayKey.split('-').map(Number);
+ const date = new Date(y, (m ?? 1) - 1, (d ?? 1) - 1);
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
+}
+
+/**
+ * 用增量结果替换缓存中 sinceDay(含)之后的行;sinceDay 为 null 时整体替换。
+ * 任务元数据不分区间:被控端每次都返回全部任务的当前元数据,整体覆盖缓存;不在其中的
+ * 任务(已删除 / 不对远端可见)连同区间外的旧行一起丢弃。
+ */
+export function mergeIncrementalRows(
+ cached: UsageDeviceRows | null,
+ sinceDay: string | null,
+ incoming: UsageDeviceRows,
+): UsageDeviceRows {
+ const taskIds = new Set(incoming.tasks.map((task) => task.sessionId));
+ const merged =
+ !cached || sinceDay === null
+ ? incoming
+ : {
+ spendDays: [
+ ...cached.spendDays.filter((row) => row.day < sinceDay),
+ ...incoming.spendDays,
+ ],
+ modelRows: [
+ ...cached.modelRows.filter((row) => row.day < sinceDay),
+ ...incoming.modelRows,
+ ],
+ sessionRows: [
+ ...cached.sessionRows.filter((row) => row.day < sinceDay),
+ ...incoming.sessionRows,
+ ],
+ tasks: incoming.tasks,
+ };
+ return {
+ ...merged,
+ sessionRows: merged.sessionRows.filter((row) => taskIds.has(row.sessionId)),
+ };
+}
+
+function parseCacheFile(raw: string | null): Record<string, CachedPeer> {
+ if (!raw) return {};
+ try {
+ const parsed = JSON.parse(raw) as Partial<CacheFile>;
+ if (parsed.version !== CACHE_VERSION || !parsed.peers || typeof parsed.peers !== 'object')
+ return {};
+ const peers: Record<string, CachedPeer> = {};
+ for (const [deviceId, value] of Object.entries(parsed.peers)) {
+ const peer = value as Partial<CachedPeer> | null;
+ if (!peer || typeof peer.name !== 'string' || !isDayKey(peer.todayKey)) continue;
+ if (!isUnixMs(peer.syncedAt)) continue;
+ const rows = sanitizeUsageDeviceRows(peer.rows);
+ if (!rows) continue;
+ peers[deviceId] = {
+ name: peer.name,
+ platform: typeof peer.platform === 'string' ? peer.platform : null,
+ syncedAt: peer.syncedAt,
+ todayKey: peer.todayKey,
+ rows,
+ };
+ }
+ return peers;
+ } catch {
+ return {};
+ }
+}
+
+function errorStatus(code: string): UsageDeviceStatus {
+ if (
+ code === 'CHANNEL_NOT_ALLOWED' ||
+ code === 'NO_HANDLER' ||
+ code === 'UNSUPPORTED_CAPABILITY'
+ ) {
+ return 'unsupported';
+ }
+ if (code === 'DEVICE_OFFLINE' || code === 'PEER_OFFLINE' || code === 'TIMEOUT') return 'offline';
+ if (
+ code === 'REMOTE_DISABLED' ||
+ code === 'CONTROL_TARGET_DISABLED' ||
+ code === 'PERMISSION_DENIED' ||
+ code === 'ACCESS_REVOKED'
+ ) {
+ return 'remote-disabled';
+ }
+ return 'error';
+}
+
+function errorCodeOf(error: unknown): string {
+ if (error && typeof error === 'object' && 'code' in error && typeof error.code === 'string') {
+ return error.code;
+ }
+ const message = error instanceof Error ? error.message : String(error);
+ return /^\[([A-Z_]+)\]/.exec(message)?.[1] ?? 'REMOTE_UNAVAILABLE';
+}
+
+/** 0.1.93 及更早的正式版既没有用量读取通道,也不认后台链路:连它们只会让对方进入受控状态。 */
+const LAST_VERSION_WITHOUT_BACKGROUND_READ = '0.1.93';
+
+/**
+ * 按设备目录里的版本判断能否后台读取。本地开发构建(0.0.0)无法按版本判断,放行给
+ * 建链后的能力确认(remoteBackgroundInvoke)。
+ */
+export function mayServeBackgroundRead(appVersion: string | null): boolean {
+ if (appVersion === '0.0.0') return true;
+ return compareAppUpdateVersions(appVersion, LAST_VERSION_WITHOUT_BACKGROUND_READ) === 'newer';
+}
+
+export function createPeerUsageSync(deps: PeerUsageSyncDeps): PeerUsageSync {
+ let loadedUserId: string | null = null;
+ let loadPromise: Promise<void> | null = null;
+ let peers: Record<string, CachedPeer> = {};
+ /** 最近一次设备目录(含本机);目录读取失败时沿用上次结果。 */
+ let directory: DeviceLinkDeviceView[] | null = null;
+ const statuses = new Map<string, UsageDeviceStatus>();
+ /** 判定为不支持时对方的版本:版本不变就不再建链重试(旧被控端每次建链都会闪一下受控横幅)。 */
+ const unsupportedVersions = new Map<string, string | null>();
+ let version = 0;
+ /**
+ * 账号代次:切换账号时 +1。一次同步开始时记下代次,之后对状态 / 缓存 / 目录 / 落盘的
+ * 每一次写入都先经 isCurrent 判定 —— 旧账号的在途请求迟到或失败都不能写进新账号的状态。
+ */
+ let epoch = 0;
+ let inflight: Promise<void> | null = null;
+ let lastSyncStartedAt = 0;
+
+ /**
+ * 聚合版本:只在参与聚合的用量行真的变化时前进(唯一写入点是下面几处对 peers 的修改)。
+ * 设备目录、状态、同步时间是展示元数据,由用量历史在每次读取时从快照附上,不影响版本 ——
+ * 否则每分钟一次的成功同步都会让全量历史重新聚合。
+ */
+ const bumpRows = (): void => {
+ version += 1;
+ };
+ const sameRows = (a: UsageDeviceRows | undefined, b: UsageDeviceRows): boolean =>
+ a !== undefined && JSON.stringify(a) === JSON.stringify(b);
+
+ const resetForUser = (userId: string | null): void => {
+ epoch += 1;
+ // 旧账号的在途同步不再代表当前账号:新账号立即发起自己的同步,不等它超时。
+ inflight = null;
+ loadedUserId = userId;
+ loadPromise = null;
+ peers = {};
+ directory = null;
+ statuses.clear();
+ unsupportedVersions.clear();
+ lastSyncStartedAt = 0;
+ bumpRows();
+ };
+
+ const ensureLoaded = async (): Promise<string | null> => {
+ const userId = deps.userId();
+ if (userId !== loadedUserId) resetForUser(userId);
+ if (!userId) return null;
+ if (!loadPromise) {
+ // I4 账号代次同样约束磁盘缓存:读缓存期间账号变了(哪怕还没有调用触发 reset),
+ // 旧账号的行不得装进内存。
+ const loadEpoch = epoch;
+ loadPromise = deps
+ .readCache(userId)
+ .catch(() => null)
+ .then((raw) => {
+ if (loadEpoch !== epoch || loadedUserId !== userId || deps.userId() !== userId) return;
+ const cached = parseCacheFile(raw);
+ peers = { ...cached, ...peers };
+ if (Object.keys(cached).length > 0) bumpRows();
+ });
+ }
+ await loadPromise;
+ return deps.userId() === userId ? userId : null;
+ };
+
+ const persist = async (userId: string, isCurrent: () => boolean): Promise<void> => {
+ if (!isCurrent()) return;
+ const file: CacheFile = { version: CACHE_VERSION, peers };
+ try {
+ await deps.writeCache(userId, JSON.stringify(file));
+ } catch (err) {
+ log.debug('write peer usage cache failed:', err instanceof Error ? err.message : String(err));
+ }
+ };
+
+ const syncPeer = async (
+ device: DeviceLinkDeviceView,
+ isCurrent: () => boolean,
+ ): Promise<void> => {
+ const setStatus = (status: UsageDeviceStatus): void => {
+ if (isCurrent()) statuses.set(device.deviceId, status);
+ };
+ if (!device.online) {
+ setStatus('offline');
+ return;
+ }
+ if (!device.remoteControlEnabled || !device.controlEnabled) {
+ setStatus('remote-disabled');
+ return;
+ }
+ if (
+ !mayServeBackgroundRead(device.appVersion) ||
+ (unsupportedVersions.has(device.deviceId) &&
+ unsupportedVersions.get(device.deviceId) === device.appVersion)
+ ) {
+ setStatus('unsupported');
+ return;
+ }
+ const markFailed = (code: string): void => {
+ const status = errorStatus(code);
+ if (status === 'unsupported' && isCurrent()) {
+ unsupportedVersions.set(device.deviceId, device.appVersion);
+ }
+ setStatus(status);
+ };
+ const cached = peers[device.deviceId] ?? null;
+ const sinceDay = cached ? dayBefore(cached.todayKey) : null;
+ setStatus('syncing');
+ try {
+ const response = await deps.invoke(device.deviceId, USAGE_DEVICE_ROWS_CHANNEL, [
+ sinceDay ? { sinceDay } : {},
+ ]);
+ if (!response.ok) {
+ markFailed(errorCodeOf(response.error));
+ return;
+ }
+ const decoded = await decodeUsageDeviceRowsResponse(response.result);
+ if (!decoded || decoded.kind === 'oversize') {
+ setStatus('error');
+ return;
+ }
+ // 账号在请求期间切换:结果属于旧账号,丢弃。
+ if (!isCurrent()) return;
+ // 对方回的区间与请求不一致(旧实现忽略参数等)时按全量处理,不能拼出重复行。
+ const effectiveSince = decoded.sinceDay === sinceDay ? sinceDay : null;
+ const rows = mergeIncrementalRows(cached?.rows ?? null, effectiveSince, decoded.rows);
+ const rowsChanged = !sameRows(cached?.rows, rows);
+ peers[device.deviceId] = {
+ name: device.name,
+ platform: device.platform,
+ syncedAt: deps.now(),
+ todayKey: decoded.todayKey,
+ rows,
+ };
+ if (rowsChanged) bumpRows();
+ setStatus('ok');
+ } catch (error) {
+ markFailed(errorCodeOf(error));
+ }
+ };
+
+ /** 设备目录读不到:在线状态未知,上次的「ok」不能再代表最新,统一标为读取失败(保留缓存行)。 */
+ const markPeersUnreadable = (): void => {
+ const selfDeviceId = deps.selfDeviceId();
+ const ids = new Set([
+ ...(directory ?? [])
+ .filter((device) => !device.isSelf && !MOBILE_PLATFORMS.has(device.platform ?? ''))
+ .map((device) => device.deviceId),
+ ...Object.keys(peers),
+ ]);
+ for (const deviceId of ids) {
+ if (deviceId !== selfDeviceId) statuses.set(deviceId, 'error');
+ }
+ };
+
+ const runSync = async (): Promise<void> => {
+ const userId = await ensureLoaded();
+ if (!userId) return;
+ const runEpoch = epoch;
+ const isCurrent = (): boolean =>
+ runEpoch === epoch && loadedUserId === userId && deps.userId() === userId;
+ let devices: DeviceLinkDeviceView[];
+ try {
+ devices = (await deps.listDevices()).devices;
+ } catch (err) {
+ log.debug(
+ 'list devices for usage sync failed:',
+ err instanceof Error ? err.message : String(err),
+ );
+ if (isCurrent()) markPeersUnreadable();
+ return;
+ }
+ if (!isCurrent()) return;
+ directory = devices;
+ // 已从账号移除的设备不再出现在选择器里,缓存一并清掉。
+ const known = new Set(devices.map((device) => device.deviceId));
+ for (const deviceId of Object.keys(peers)) {
+ if (known.has(deviceId)) continue;
+ delete peers[deviceId];
+ bumpRows();
+ }
+ const targets = devices.filter(
+ (device) => !device.isSelf && !MOBILE_PLATFORMS.has(device.platform ?? ''),
+ );
+ for (const device of targets) {
+ if (
+ device.online &&
+ device.remoteControlEnabled &&
+ device.controlEnabled &&
+ mayServeBackgroundRead(device.appVersion)
+ ) {
+ statuses.set(device.deviceId, 'syncing');
+ }
+ }
+ for (let offset = 0; offset < targets.length; offset += PEER_FANOUT) {
+ await Promise.all(
+ targets.slice(offset, offset + PEER_FANOUT).map((device) => syncPeer(device, isCurrent)),
+ );
+ }
+ if (!isCurrent()) return;
+ await persist(userId, isCurrent);
+ };
+
+ const snapshot = async (): Promise<PeerUsageSnapshot> => {
+ await ensureLoaded();
+ const selfDeviceId = deps.selfDeviceId();
+ // 加载期间账号变了:按当前账号重置并返回空快照,不带出旧账号的设备或行。
+ if (deps.userId() !== loadedUserId) {
+ resetForUser(deps.userId());
+ return { version, selfDeviceId, devices: [], peerRows: new Map() };
+ }
+ const devices: UsageDeviceSummary[] = [];
+ const listed = new Set<string>();
+ for (const device of directory ?? []) {
+ if (MOBILE_PLATFORMS.has(device.platform ?? '')) continue;
+ const isSelf = device.isSelf || device.deviceId === selfDeviceId;
+ listed.add(device.deviceId);
+ devices.push({
+ deviceId: device.deviceId,
+ name: device.name,
+ platform: device.platform,
+ isSelf,
+ syncedAt: isSelf ? null : (peers[device.deviceId]?.syncedAt ?? null),
+ status: isSelf
+ ? 'ok'
+ : (statuses.get(device.deviceId) ??
+ (peers[device.deviceId] ? 'ok' : device.online ? 'syncing' : 'offline')),
+ });
+ }
+ // 目录尚未读到(冷启动 / 未连接)时,缓存里的设备照常参与合并。
+ for (const [deviceId, peer] of Object.entries(peers)) {
+ if (listed.has(deviceId) || deviceId === selfDeviceId) continue;
+ devices.push({
+ deviceId,
+ name: peer.name,
+ platform: peer.platform,
+ isSelf: false,
+ syncedAt: peer.syncedAt,
+ status: statuses.get(deviceId) ?? 'offline',
+ });
+ }
+ const peerRows = new Map<string, UsageDeviceRows>();
+ for (const [deviceId, peer] of Object.entries(peers)) {
+ if (deviceId !== selfDeviceId) peerRows.set(deviceId, peer.rows);
+ }
+ return { version, selfDeviceId, devices, peerRows };
+ };
+
+ return {
+ snapshot,
+ sync() {
+ const userId = deps.userId();
+ // 先按当前账号重置(会丢弃旧账号的在途同步),再判断是否复用在途请求。
+ if (userId !== loadedUserId) resetForUser(userId);
+ if (inflight) return inflight;
+ if (deps.now() - lastSyncStartedAt < SYNC_MIN_INTERVAL_MS) return Promise.resolve();
+ lastSyncStartedAt = deps.now();
+ const run: Promise<void> = runSync()
+ .catch((err) => {
+ log.debug('peer usage sync failed:', err instanceof Error ? err.message : String(err));
+ })
+ .finally(() => {
+ if (inflight === run) inflight = null;
+ });
+ inflight = run;
+ return run;
+ },
+ isSyncing: () => inflight !== null,
+ version: () => version,
+ };
+}
+
+/**
+ * 读设备目录与远程读取都先过访问门(生产里是设备互联能力:已登录且不在账号切换中)。
+ * 门拒绝时视同目录读取失败 —— 设备标为读取失败、保留缓存,不发请求也不开 peer 链路。
+ */
+export function withPeerUsageAccessGate(
+ assertAllowed: () => void,
+ deps: PeerUsageSyncDeps,
+): PeerUsageSyncDeps {
+ return {
+ ...deps,
+ listDevices: async () => {
+ assertAllowed();
+ return deps.listDevices();
+ },
+ invoke: async (deviceId, channel, args) => {
+ assertAllowed();
+ return deps.invoke(deviceId, channel, args);
+ },
+ };
+}
+
+let defaultSync: PeerUsageSync | null = null;
+
+export function peerUsageCacheFilePath(userDataDir: string, userId: string): string {
+ return path.join(userDataDir, 'cache', `usage-peer-rows.${encodeURIComponent(userId)}.json`);
+}
+
+/** 由 maker-ipc/usage.ts 注入生产依赖(device-link、userData 路径);未注入时只看本机。 */
+export function configurePeerUsageSync(deps: PeerUsageSyncDeps): void {
+ defaultSync = createPeerUsageSync(deps);
+}
+
+export function getPeerUsageSync(): PeerUsageSync | null {
+ return defaultSync;
+}
+
+export async function readPeerUsageCacheFile(file: string): Promise<string | null> {
+ try {
+ return await fs.readFile(file, 'utf8');
+ } catch {
+ return null;
+ }
+}
+
+export async function writePeerUsageCacheFile(file: string, contents: string): Promise<void> {
+ await fs.mkdir(path.dirname(file), { recursive: true });
+ const tmp = `${file}.${process.pid}.tmp`;
+ await fs.writeFile(tmp, contents, 'utf8');
+ await fs.rename(tmp, file);
+}
+
+export function __resetPeerUsageSyncForTesting(): void {
+ defaultSync = null;
+}
diff --git a/apps/desktop/src/main/usage/usageDeviceRows.ts b/apps/desktop/src/main/usage/usageDeviceRows.ts
new file mode 100644
index 0000000000..e8c0412475
--- /dev/null
+++ b/apps/desktop/src/main/usage/usageDeviceRows.ts
@@ -0,0 +1,215 @@
+/**
+ * usageDeviceRows — 用量历史跨设备合并的 wire 契约与被控端读取。
+ *
+ * 设置 → 用量历史默认合并同账号所有电脑的用量。每台电脑的真相只在它自己的
+ * daily_spend / daily_model_usage 里,控制端经 device-link 调用
+ * `maker:usage:device-rows` 拉取**原始行**(不是聚合后的 payload),在本机与
+ * 自己的行合并后重新聚合 —— streak / 订阅估算 / 币种折叠全部沿用本机同一条链路,
+ * 不需要拼接两份已聚合的结果。
+ *
+ * 请求:`[{ sinceDay?: 'YYYY-MM-DD' }]`。给出 sinceDay 时只回该日(含)之后的行,
+ * 控制端据此增量同步;缺省回全部历史。
+ * 响应:`{ format: 'usage-device-rows-v1', todayKey, sinceDay, rowsGz }`,
+ * rowsGz = gzip(JSON({ spendDays, modelRows })) 的 base64 —— 新 channel 两端同代次,
+ * 控制端恒可解 gzip(同 git-review:remote-op 的超帧预判口径);压缩后仍超预算回
+ * `{ format, oversize: true }`,不裸炸 FRAME_TOO_LARGE。
+ * 老被控端没有该 channel → CHANNEL_NOT_ALLOWED,控制端标记「版本过旧」。
+ */
+
+import { gzip as gzipCb, gunzip as gunzipCb } from 'node:zlib';
+import { promisify } from 'node:util';
+
+import { normalizeRegionalMoney, type RegionalMoney } from '../../shared/regionalMoney.js';
+import type { DailyModelUsageRow } from '../localDb/dailyModelUsage.js';
+import type { DailySessionUsageRow, UsageTaskMeta } from '../localDb/dailySessionUsage.js';
+
+const gzipAsync = promisify(gzipCb);
+const gunzipAsync = promisify(gunzipCb);
+
+export const USAGE_DEVICE_ROWS_FORMAT = 'usage-device-rows-v1';
+/** relay 单帧 2MiB;留出信封与 base64 膨胀余量。 */
+const MAX_ROWS_GZ_BASE64_BYTES = 1_500_000;
+/** 解压后上限:防止损坏或恶意回复在控制端撑爆内存。 */
+const MAX_ROWS_JSON_BYTES = 32 * 1024 * 1024;
+const DAY_KEY_RE = /^\d{4}-\d{2}-\d{2}$/;
+
+export interface UsageSpendDayRow {
+ day: string;
+ monies: RegionalMoney[];
+}
+
+export interface UsageDeviceRows {
+ spendDays: UsageSpendDayRow[];
+ modelRows: DailyModelUsageRow[];
+ /** 每日 × 任务 token(「最耗 token 的任务」按范围统计用)。 */
+ sessionRows: DailySessionUsageRow[];
+ /** sessionRows 涉及任务的元数据(标题 / 模型等取任务当前值)。 */
+ tasks: UsageTaskMeta[];
+}
+
+export type UsageDeviceRowsResponse =
+ | {
+ format: typeof USAGE_DEVICE_ROWS_FORMAT;
+ todayKey: string;
+ sinceDay: string | null;
+ rowsGz: string;
+ }
+ | { format: typeof USAGE_DEVICE_ROWS_FORMAT; oversize: true };
+
+export interface UsageDeviceRowsReaderDeps {
+ getAllSpendDays(): Promise<UsageSpendDayRow[]>;
+ getModelUsageSince(sinceDayKey: string): Promise<DailyModelUsageRow[]>;
+ getSessionUsageSince(
+ sinceDayKey: string,
+ ): Promise<{ rows: DailySessionUsageRow[]; tasks: UsageTaskMeta[] }>;
+ /**
+ * 远端可见的任务 id。任务标题等元数据要离开本机,必须经过与会话列表相同的
+ * 远端 Bot 可见性边界(隐藏 / 已停用伙伴的任务不外发)。
+ */
+ remoteVisibleTaskIds(sessionIds: readonly string[]): Promise<ReadonlySet<string>>;
+ todayKey(): string;
+}
+
+export function isDayKey(value: unknown): value is string {
+ return typeof value === 'string' && DAY_KEY_RE.test(value);
+}
+
+/** 解析被控端请求参数;非法时返回 null(由 IPC handler 转成 INVALID_PARAMS)。 */
+export function parseUsageDeviceRowsRequest(arg: unknown): { sinceDay: string | null } | null {
+ if (arg === undefined || arg === null) return { sinceDay: null };
+ if (typeof arg !== 'object' || Array.isArray(arg)) return null;
+ const sinceDay = (arg as { sinceDay?: unknown }).sinceDay;
+ if (sinceDay === undefined || sinceDay === null) return { sinceDay: null };
+ return isDayKey(sinceDay) ? { sinceDay } : null;
+}
+
+/** 被控端:读本机原始用量行并编码成 wire 响应。 */
+export async function readUsageDeviceRows(
+ deps: UsageDeviceRowsReaderDeps,
+ request: { sinceDay: string | null },
+): Promise<UsageDeviceRowsResponse> {
+ const todayKey = deps.todayKey();
+ const sinceDay = request.sinceDay;
+ const [spendDays, modelRows, sessionUsage] = await Promise.all([
+ deps.getAllSpendDays(),
+ deps.getModelUsageSince(sinceDay ?? '0000-01-01'),
+ deps.getSessionUsageSince(sinceDay ?? '0000-01-01'),
+ ]);
+ const visible = await deps.remoteVisibleTaskIds(sessionUsage.tasks.map((task) => task.sessionId));
+ const rows: UsageDeviceRows = {
+ spendDays: sinceDay ? spendDays.filter((row) => row.day >= sinceDay) : spendDays,
+ modelRows,
+ sessionRows: sessionUsage.rows.filter((row) => visible.has(row.sessionId)),
+ tasks: sessionUsage.tasks.filter((task) => visible.has(task.sessionId)),
+ };
+ const rowsGz = (await gzipAsync(Buffer.from(JSON.stringify(rows), 'utf8'))).toString('base64');
+ if (Buffer.byteLength(rowsGz, 'utf8') > MAX_ROWS_GZ_BASE64_BYTES) {
+ return { format: USAGE_DEVICE_ROWS_FORMAT, oversize: true };
+ }
+ return { format: USAGE_DEVICE_ROWS_FORMAT, todayKey, sinceDay, rowsGz };
+}
+
+/** JavaScript Date 能表示的最大 Unix 毫秒;超出时 toISOString / Intl 格式化会抛 RangeError。 */
+const MAX_DATE_MS = 8.64e15;
+
+/** 跨设备 / 磁盘来的时间戳:只接受 Date 能表示的正 Unix 毫秒。 */
+export function isUnixMs(value: unknown): value is number {
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 && value <= MAX_DATE_MS;
+}
+
+function finiteNonNegative(value: unknown): number {
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
+}
+
+function isAgentKind(value: unknown): value is DailyModelUsageRow['agentKind'] {
+ return value === 'claude-code' || value === 'codex' || value === 'pi';
+}
+
+/** 控制端和缓存共用的逐行校验:远端 / 磁盘数据一律当不可信输入。 */
+export function sanitizeUsageDeviceRows(value: unknown): UsageDeviceRows | null {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ const raw = value as {
+ spendDays?: unknown;
+ modelRows?: unknown;
+ sessionRows?: unknown;
+ tasks?: unknown;
+ };
+ if (!Array.isArray(raw.spendDays) || !Array.isArray(raw.modelRows)) return null;
+ const spendDays: UsageSpendDayRow[] = [];
+ for (const row of raw.spendDays as Array<{ day?: unknown; monies?: unknown }>) {
+ if (!row || !isDayKey(row.day) || !Array.isArray(row.monies)) continue;
+ const monies = row.monies
+ .map((money) => normalizeRegionalMoney(money))
+ .filter((money): money is RegionalMoney => Boolean(money && money.amount > 0));
+ if (monies.length > 0) spendDays.push({ day: row.day, monies });
+ }
+ const modelRows: DailyModelUsageRow[] = [];
+ for (const row of raw.modelRows as Array<Partial<DailyModelUsageRow>>) {
+ if (!row || !isDayKey(row.day) || !isAgentKind(row.agentKind)) continue;
+ if (typeof row.model !== 'string' || row.model.length === 0 || row.model.length > 256) continue;
+ const money = normalizeRegionalMoney(row.money);
+ if (!money) continue;
+ modelRows.push({
+ day: row.day,
+ agentKind: row.agentKind,
+ model: row.model,
+ money,
+ inputTokens: finiteNonNegative(row.inputTokens),
+ outputTokens: finiteNonNegative(row.outputTokens),
+ cacheReadTokens: finiteNonNegative(row.cacheReadTokens),
+ cacheCreateTokens: finiteNonNegative(row.cacheCreateTokens),
+ });
+ }
+ const sessionRows: DailySessionUsageRow[] = [];
+ for (const row of (Array.isArray(raw.sessionRows) ? raw.sessionRows : []) as Array<
+ Partial<DailySessionUsageRow>
+ >) {
+ if (!row || !isDayKey(row.day) || !isShortString(row.sessionId)) continue;
+ const tokens = finiteNonNegative(row.tokens);
+ if (tokens > 0) sessionRows.push({ day: row.day, sessionId: row.sessionId, tokens });
+ }
+ const tasks: UsageTaskMeta[] = [];
+ for (const task of (Array.isArray(raw.tasks) ? raw.tasks : []) as Array<Partial<UsageTaskMeta>>) {
+ if (!task || !isShortString(task.sessionId)) continue;
+ tasks.push({
+ sessionId: task.sessionId,
+ title: typeof task.title === 'string' ? task.title.slice(0, 500) : '',
+ model: typeof task.model === 'string' ? task.model.slice(0, 256) : '',
+ providerId: isShortString(task.providerId) ? task.providerId : null,
+ contextTokens: finiteNonNegative(task.contextTokens),
+ contextWindow: finiteNonNegative(task.contextWindow),
+ lastActiveAt: isUnixMs(task.lastActiveAt) ? task.lastActiveAt : 0,
+ });
+ }
+ return { spendDays, modelRows, sessionRows, tasks };
+}
+
+function isShortString(value: unknown): value is string {
+ return typeof value === 'string' && value.length > 0 && value.length <= 256;
+}
+
+/** 控制端:解码并校验 wire 响应。oversize 返回 'oversize';格式不对返回 null。 */
+export async function decodeUsageDeviceRowsResponse(
+ value: unknown,
+): Promise<
+ | { kind: 'rows'; todayKey: string; sinceDay: string | null; rows: UsageDeviceRows }
+ | { kind: 'oversize' }
+ | null
+> {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ const response = value as Record<string, unknown>;
+ if (response.format !== USAGE_DEVICE_ROWS_FORMAT) return null;
+ if (response.oversize === true) return { kind: 'oversize' };
+ if (!isDayKey(response.todayKey) || typeof response.rowsGz !== 'string') return null;
+ const sinceDay = response.sinceDay === null ? null : response.sinceDay;
+ if (sinceDay !== null && !isDayKey(sinceDay)) return null;
+ try {
+ const json = await gunzipAsync(Buffer.from(response.rowsGz, 'base64'), {
+ maxOutputLength: MAX_ROWS_JSON_BYTES,
+ });
+ const rows = sanitizeUsageDeviceRows(JSON.parse(json.toString('utf8')));
+ return rows ? { kind: 'rows', todayKey: response.todayKey, sinceDay, rows } : null;
+ } catch {
+ return null;
+ }
+}
diff --git a/apps/desktop/src/main/usage/usageHistory.ts b/apps/desktop/src/main/usage/usageHistory.ts
index d46a571015..e22add3b67 100644
--- a/apps/desktop/src/main/usage/usageHistory.ts
+++ b/apps/desktop/src/main/usage/usageHistory.ts
@@ -11,6 +11,13 @@
* - 有缓存时立即返回 stale payload, 后台刷新并写回磁盘; renderer 保持"更新中"感知并短轮询补 fresh。
* - 无缓存时才走同步聚合, 成功后落盘。纯函数 readUsageHistoryWith() 不带 IO 缓存, 便于单测。
*
+ * 设备范围 (device):
+ * - 'local' (默认): 只读本机库, 首页仪表盘沿用。
+ * - 'all': 本机 + 同账号其它电脑的原始行 (peerUsageSync 经 device-link 拉取并缓存),
+ * 合并后走同一条聚合链路。设置 → 用量历史默认使用。
+ * - 其它值: 某一台其它电脑的 deviceId, 只聚合该设备的缓存行。
+ * 多设备范围在其它设备同步期间返回 stale, renderer 的短轮询据此拿到合并后的结果。
+ *
* streak / anomaly / 估算全部是导出的纯函数, 单测不需要 DB / Electron。
* 日期一律用本地时区 day key (localDayKey 同口径); renderer 以 payload.todayKey 为锚,
* 不自己取系统日期。
@@ -21,6 +28,7 @@ import path from 'node:path';
import { app } from 'electron';
import { getAllSpendDays, localDayKey } from '../localDb/dailySpend';
import { getModelUsageSince, type DailyModelUsageRow } from '../localDb/dailyModelUsage';
+import { getSessionUsageSince, getUsageTaskMeta } from '../localDb/dailySessionUsage';
import { getCurrentDbClientUserId } from '../localDb/client/current';
import { createLogger } from '../logger';
import {
@@ -38,6 +46,12 @@ import {
type ModelPriceOverridesSnapshot,
} from './referenceModelPricing';
import { computePriceQuoteTurnMoney } from './turnCostCalculator';
+import {
+ getPeerUsageSync,
+ type PeerUsageSnapshot,
+ type UsageDeviceSummary,
+} from './peerUsageSync';
+import type { UsageDeviceRows } from './usageDeviceRows';
import { currentLedgerCurrency } from './ledgerCurrency.js';
import {
addCompatibleRegionalMoney,
@@ -144,6 +158,89 @@ export interface UsageHistoryPayload {
last30DaysTokens: number;
};
anomaly: { isAnomalous: boolean; trailing7DayAvg: RegionalMoney | null };
+ /**
+ * 多设备范围才有: 参与合并的电脑 (含本机), 供设备选择器与「数据截至」标注。
+ * 'local' 范围与旧快照缺省。
+ */
+ devices?: UsageDeviceSummary[];
+ /** true = 正在从其它电脑读取, 结果可能还不含它们的最新数据。 */
+ devicesSyncing?: boolean;
+ /** 聚合时使用的跨设备数据版本 (main 内部新鲜度判断用)。 */
+ peerVersion?: number;
+ /** 按 modelDays 窗口返回的每日 × 任务 token (「最耗 token 的任务」按范围统计)。 */
+ taskDaily?: UsageHistoryTaskDay[];
+ /** taskDaily 涉及任务的元数据。 */
+ tasks?: UsageHistoryTask[];
+}
+
+export type UsageHistoryDeviceScope = 'local' | 'all' | (string & {});
+
+/** 本机任务的设备键;其它电脑的任务用它的 deviceId。 */
+export const LOCAL_TASK_DEVICE = 'local';
+
+/** 「最耗 token 的任务」的每日 × 任务一行。taskKey = `${deviceId}:${sessionId}`。 */
+export interface UsageHistoryTaskDay {
+ day: string;
+ taskKey: string;
+ tokens: number;
+}
+
+export interface UsageHistoryTask {
+ taskKey: string;
+ /** LOCAL_TASK_DEVICE 或其它电脑的 deviceId。 */
+ deviceId: string;
+ sessionId: string;
+ title: string;
+ model: string;
+ providerId: string | null;
+ contextTokens: number;
+ contextWindow: number;
+ /** unix ms */
+ lastActiveAt: number;
+}
+
+export function usageTaskKey(deviceId: string, sessionId: string): string {
+ return `${deviceId}:${sessionId}`;
+}
+
+/**
+ * 合并多台设备的原始行。同一 (天, agent, 模型, 币种, 金额口径) 的模型行相加,
+ * 保持与单机库一致的「每键一行」形状 —— 下游 modelDaily 与柱图按行取值, 不能出现重复键。
+ * 日账按天拼接各设备的多币种金额, 折叠仍由聚合链路按账本币种完成。
+ */
+export function combineUsageDeviceRows(sources: readonly UsageDeviceRows[]): UsageDeviceRows {
+ const spendByDay = new Map<string, RegionalMoney[]>();
+ const modelByKey = new Map<string, DailyModelUsageRow>();
+ for (const source of sources) {
+ for (const row of source.spendDays) {
+ const monies = spendByDay.get(row.day) ?? [];
+ monies.push(...row.monies);
+ spendByDay.set(row.day, monies);
+ }
+ for (const row of source.modelRows) {
+ const key = [row.day, row.agentKind, row.model, row.money.currency, row.money.kind].join('\u0000');
+ const existing = modelByKey.get(key);
+ if (!existing) {
+ modelByKey.set(key, { ...row });
+ continue;
+ }
+ existing.money =
+ addCompatibleRegionalMoney([existing.money, row.money], row.money.currency) ?? existing.money;
+ existing.inputTokens += row.inputTokens;
+ existing.outputTokens += row.outputTokens;
+ existing.cacheReadTokens += row.cacheReadTokens;
+ existing.cacheCreateTokens += row.cacheCreateTokens;
+ }
+ }
+ return {
+ spendDays: [...spendByDay.entries()]
+ .map(([day, monies]) => ({ day, monies }))
+ .sort((a, b) => (a.day < b.day ? -1 : a.day > b.day ? 1 : 0)),
+ modelRows: [...modelByKey.values()].sort((a, b) => (a.day < b.day ? -1 : a.day > b.day ? 1 : 0)),
+ // 任务行需保留设备归属,不在这里合并 —— 由 getTaskUsageSince 按设备分别打键。
+ sessionRows: [],
+ tasks: [],
+ };
}
/** YYYY-MM-DD → 前一天 (本地时区语义, 纯字符串进出)。 */
@@ -233,6 +330,10 @@ export function computeAnomaly(
export interface UsageHistoryDeps {
getAllSpendDays(): Promise<Array<{ day: string; monies: RegionalMoney[] }>>;
getModelUsageSince(sinceDayKey: string): Promise<DailyModelUsageRow[]>;
+ /** 每日 × 任务用量;缺省(旧测试替身)视为没有任务数据。 */
+ getTaskUsageSince?(
+ sinceDayKey: string,
+ ): Promise<{ rows: UsageHistoryTaskDay[]; tasks: UsageHistoryTask[] }>;
getGatewayModelPricing(): Promise<ModelPricingMap | null>;
getReferenceModelPricing(): ModelPricingMap;
/** 覆盖记录快照,一次聚合读一份——历史重合并逐行读文件会在慢盘上拖垮 Main 线程。 */
@@ -241,9 +342,35 @@ export interface UsageHistoryDeps {
todayKey(): string;
}
+/** 本机任务用量,按 LOCAL_TASK_DEVICE 打上设备键。 */
+function localTaskUsage(
+ rows: Awaited<ReturnType<typeof getSessionUsageSince>>,
+): { rows: UsageHistoryTaskDay[]; tasks: UsageHistoryTask[] } {
+ return tagTaskUsage(LOCAL_TASK_DEVICE, rows);
+}
+
+function tagTaskUsage(
+ deviceId: string,
+ usage: { rows: UsageDeviceRows['sessionRows']; tasks: UsageDeviceRows['tasks'] },
+): { rows: UsageHistoryTaskDay[]; tasks: UsageHistoryTask[] } {
+ return {
+ rows: usage.rows.map((row) => ({
+ day: row.day,
+ taskKey: usageTaskKey(deviceId, row.sessionId),
+ tokens: row.tokens,
+ })),
+ tasks: usage.tasks.map((task) => ({
+ ...task,
+ taskKey: usageTaskKey(deviceId, task.sessionId),
+ deviceId,
+ })),
+ };
+}
+
const defaultDeps: UsageHistoryDeps = {
getAllSpendDays,
getModelUsageSince,
+ getTaskUsageSince: async (sinceDayKey) => localTaskUsage(await getSessionUsageSince(sinceDayKey)),
getGatewayModelPricing,
getReferenceModelPricing,
getModelPriceOverridesSnapshot: readModelPriceOverridesSnapshot,
@@ -274,14 +401,22 @@ function normalizeWindowDays(value: number | 'all' | undefined, fallback: number
return Math.min(366, Math.max(1, Math.floor(value ?? fallback)));
}
+function normalizeDeviceScope(value: UsageHistoryDeviceScope | undefined): UsageHistoryDeviceScope {
+ return value && value.length > 0 ? value : 'local';
+}
+
function optsKey(opts?: UsageHistoryReadOptions): string {
+ const device = normalizeDeviceScope(opts?.device);
const days = normalizeWindowDays(opts?.days, 140);
const modelDays = normalizeWindowDays(opts?.modelDays, MODEL_WINDOW_DAYS);
const userId = getCurrentDbClientUserId() ?? 'anonymous';
// Keep the pre-window-split key for the default request so existing disk
// snapshots remain readable. Non-default model windows get their own key.
const modelSuffix = modelDays === MODEL_WINDOW_DAYS ? '' : `|modelDays=${modelDays}`;
- return `user=${encodeURIComponent(userId)}|days=${days}${modelSuffix}`;
+ // 'local' 沿用旧 key, 升级后首页与已有磁盘快照照常命中。
+ const deviceSuffix = device === 'local' ? '' : `|device=${encodeURIComponent(device)}`;
+ const taskSuffix = opts?.includeTasks ? '|tasks=1' : '';
+ return `user=${encodeURIComponent(userId)}|days=${days}${modelSuffix}${deviceSuffix}${taskSuffix}`;
}
function isFiniteNumber(value: unknown): value is number {
@@ -329,6 +464,10 @@ function validateUsageHistoryPayload(value: unknown): UsageHistoryPayload | null
streak: payload.streak,
totals: payload.totals,
anomaly: payload.anomaly,
+ ...(Array.isArray(payload.devices) ? { devices: payload.devices } : {}),
+ ...(Array.isArray(payload.taskDaily) && Array.isArray(payload.tasks)
+ ? { taskDaily: payload.taskDaily, tasks: payload.tasks }
+ : {}),
};
}
@@ -475,6 +614,13 @@ export interface UsageHistoryReadOptions {
days?: number | 'all';
/** Model/table aggregation window. `all` is used by Settings → Usage History. */
modelDays?: number | 'all';
+ /** 设备范围, 缺省 'local'。见文件头注释。 */
+ device?: UsageHistoryDeviceScope;
+ /**
+ * 附带「最耗 token 的任务」数据(taskDaily / tasks)。只有设置 → 用量历史需要;首页看板
+ * 每次用量变化都会刷新,不承担任务全量查询。
+ */
+ includeTasks?: boolean;
/**
* true = 事件触发的刷新, 需要绕过 10s 内存快返, 立即重新聚合 DB。
* mount / 展开仍使用 stale-while-refresh 快路径保证首帧速度。
@@ -486,7 +632,7 @@ async function refreshUsageHistory(expectedOptsKey: string, opts?: UsageHistoryR
if (opts?.forceRefresh) {
refreshInFlightByOptsKey.delete(expectedOptsKey);
const generation = nextRefreshGeneration(expectedOptsKey);
- return readUsageHistoryWith(defaultDeps, opts)
+ return readScopedUsageHistory(opts)
.then((payload) => {
const next = freshPayload(payload);
if (isLatestRefreshGeneration(expectedOptsKey, generation)) {
@@ -502,7 +648,7 @@ async function refreshUsageHistory(expectedOptsKey: string, opts?: UsageHistoryR
const current = refreshInFlightByOptsKey.get(expectedOptsKey);
if (current) return current;
const generation = nextRefreshGeneration(expectedOptsKey);
- const nextRefresh = readUsageHistoryWith(defaultDeps, opts)
+ const nextRefresh = readScopedUsageHistory(opts)
.then((payload) => {
const next = freshPayload(payload);
if (isLatestRefreshGeneration(expectedOptsKey, generation)) {
@@ -607,6 +753,9 @@ export async function readUsageHistoryWith(
const modelRows = modelCutoff === null
? allModelRows
: allModelRows.filter((r) => r.day >= modelCutoff);
+ const taskUsage = opts?.includeTasks && deps.getTaskUsageSince
+ ? await deps.getTaskUsageSince(modelCutoff ?? '0000-01-01')
+ : null;
// 每日 token 合计 → days 的 tooltip 数据。codex-only 日 daily_spend 无行 ($ 只有
// Claude 记), 也要并进 days, 否则热力图那天 hover 不到 token。
@@ -827,6 +976,7 @@ export async function readUsageHistoryWith(
days,
modelDaily,
models,
+ ...(taskUsage ? { taskDaily: taskUsage.rows, tasks: taskUsage.tasks } : {}),
streak: computeStreaks(activeDays, todayKey),
totals: {
today,
@@ -854,12 +1004,179 @@ export async function readUsageHistoryWith(
};
}
-/** 生产入口 (usage.ts adapter 注入给 IPC handler)。 */
+/**
+ * 其它电脑的行按它自己的本地日历记账,只精确到天,无法按小时换算到本机日历。
+ * 合并口径:各设备按本地日期计;对方已跨入本机的「明天」时,超出本机今天的行归到本机
+ * 今天 —— 否则那部分用量既不进今日合计,也不会出现在以本机今天为锚的图表里。
+ */
+export function clampPeerRowsToToday(rows: UsageDeviceRows, todayKey: string): UsageDeviceRows {
+ const clamp = (day: string): string => (day > todayKey ? todayKey : day);
+ return {
+ spendDays: rows.spendDays.map((row) => ({ ...row, day: clamp(row.day) })),
+ modelRows: rows.modelRows.map((row) => ({ ...row, day: clamp(row.day) })),
+ sessionRows: rows.sessionRows.map((row) => ({ ...row, day: clamp(row.day) })),
+ tasks: rows.tasks,
+ };
+}
+
+/** 按设备范围替换原始行读取; 价格、账本币种等其余依赖不变。 */
+export function usageHistoryDepsForScope(
+ base: UsageHistoryDeps,
+ scope: UsageHistoryDeviceScope,
+ snapshot: Pick<PeerUsageSnapshot, 'peerRows'>,
+): UsageHistoryDeps {
+ if (scope === 'local') return base;
+ let combined: Promise<UsageDeviceRows> | null = null;
+ const rows = (): Promise<UsageDeviceRows> => {
+ combined ??= (async () => {
+ const todayKey = base.todayKey();
+ const peer = (rows: UsageDeviceRows): UsageDeviceRows => clampPeerRowsToToday(rows, todayKey);
+ if (scope !== 'all') {
+ const one = snapshot.peerRows.get(scope);
+ return one
+ ? combineUsageDeviceRows([peer(one)])
+ : { spendDays: [], modelRows: [], sessionRows: [], tasks: [] };
+ }
+ const [spendDays, modelRows] = await Promise.all([
+ base.getAllSpendDays(),
+ base.getModelUsageSince('0000-01-01'),
+ ]);
+ return combineUsageDeviceRows([
+ { spendDays, modelRows, sessionRows: [], tasks: [] },
+ ...[...snapshot.peerRows.values()].map(peer),
+ ]);
+ })();
+ return combined;
+ };
+ return {
+ ...base,
+ getAllSpendDays: async () => (await rows()).spendDays,
+ getModelUsageSince: async (sinceDayKey) =>
+ (await rows()).modelRows.filter((row) => row.day >= sinceDayKey),
+ // 任务按设备分开保留(同一任务 id 在两台电脑上互不合并),其它电脑的行同样按本机今天夹取。
+ getTaskUsageSince: async (sinceDayKey) => {
+ const todayKey = base.todayKey();
+ const parts: Array<{ rows: UsageHistoryTaskDay[]; tasks: UsageHistoryTask[] }> = [];
+ if (scope === 'all' && base.getTaskUsageSince) {
+ parts.push(await base.getTaskUsageSince(sinceDayKey));
+ }
+ for (const [deviceId, peerRows] of snapshot.peerRows) {
+ if (scope !== 'all' && scope !== deviceId) continue;
+ const clamped = clampPeerRowsToToday(peerRows, todayKey);
+ parts.push(
+ tagTaskUsage(deviceId, {
+ rows: clamped.sessionRows.filter((row) => row.day >= sinceDayKey),
+ tasks: clamped.tasks,
+ }),
+ );
+ }
+ return {
+ rows: parts.flatMap((part) => part.rows),
+ tasks: parts.flatMap((part) => part.tasks),
+ };
+ },
+ };
+}
+
+/** 本机设备条目兜底: 设备目录尚未读到 (未登录 / 未连接) 时选择器仍有「本机」。 */
+function devicesWithSelf(snapshot: PeerUsageSnapshot): UsageDeviceSummary[] {
+ if (snapshot.devices.some((device) => device.isSelf)) return snapshot.devices;
+ return [
+ {
+ deviceId: snapshot.selfDeviceId ?? 'local',
+ name: '',
+ platform: null,
+ isSelf: true,
+ syncedAt: null,
+ status: 'ok',
+ },
+ ...snapshot.devices,
+ ];
+}
+
+async function readScopedUsageHistory(opts?: UsageHistoryReadOptions): Promise<UsageHistoryPayload> {
+ const scope = normalizeDeviceScope(opts?.device);
+ const peerSync = scope === 'local' ? null : getPeerUsageSync();
+ if (!peerSync) {
+ const payload = await readUsageHistoryWith(defaultDeps, opts);
+ // 未注入跨设备同步 (单测 / 启动窗口) 时多设备范围退化为本机, 选择器只剩本机。
+ return scope === 'local'
+ ? payload
+ : { ...payload, devices: devicesWithSelf({ version: 0, selfDeviceId: null, devices: [], peerRows: new Map() }) };
+ }
+ const snapshot = await peerSync.snapshot();
+ const payload = await readUsageHistoryWith(usageHistoryDepsForScope(defaultDeps, scope, snapshot), opts);
+ return {
+ ...payload,
+ devices: devicesWithSelf(snapshot),
+ devicesSyncing: peerSync.isSyncing(),
+ peerVersion: snapshot.version,
+ };
+}
+
+/**
+ * 生产入口 (usage.ts adapter 注入给 IPC handler)。
+ * 设备目录 / 状态 / 同步时间是展示元数据:在唯一出口按当前快照附上,不参与聚合与缓存
+ * 失效判断 —— 聚合只随用量行变化(见 peerUsageSync 的聚合版本)。
+ */
export async function readUsageHistory(opts?: UsageHistoryReadOptions): Promise<UsageHistoryPayload> {
+ const payload = await withCurrentLocalTasks(await readAggregatedUsageHistory(opts));
+ const peerSync = normalizeDeviceScope(opts?.device) === 'local' ? null : getPeerUsageSync();
+ if (!peerSync) return payload;
+ return {
+ ...payload,
+ devices: devicesWithSelf(await peerSync.snapshot()),
+ devicesSyncing: peerSync.isSyncing(),
+ };
+}
+
+/**
+ * 本机任务的标题 / 模型 / 删除状态同属展示元数据:在唯一出口按当前库覆盖,聚合缓存
+ * 只提供用量行。重命名、删除不产生用量,不能等下一次重聚合才生效。
+ */
+async function withCurrentLocalTasks(payload: UsageHistoryPayload): Promise<UsageHistoryPayload> {
+ if (!payload.tasks?.some((task) => task.deviceId === LOCAL_TASK_DEVICE)) return payload;
+ let current: Map<string, Awaited<ReturnType<typeof getUsageTaskMeta>>[number]>;
+ try {
+ current = new Map((await getUsageTaskMeta()).map((task) => [task.sessionId, task]));
+ } catch (err) {
+ log.debug('read usage task meta failed:', err instanceof Error ? err.message : String(err));
+ return payload;
+ }
+ return {
+ ...payload,
+ tasks: payload.tasks.flatMap((task) => {
+ if (task.deviceId !== LOCAL_TASK_DEVICE) return [task];
+ const meta = current.get(task.sessionId);
+ return meta ? [{ ...task, ...meta }] : [];
+ }),
+ };
+}
+
+async function readAggregatedUsageHistory(
+ opts?: UsageHistoryReadOptions,
+): Promise<UsageHistoryPayload> {
const key = optsKey(opts);
+ const peerSync = normalizeDeviceScope(opts?.device) === 'local' ? null : getPeerUsageSync();
+ // 节流的跨设备同步; 同步期间返回 stale, renderer 短轮询直到拿到合并后的结果。
+ if (peerSync) void peerSync.sync();
+ // 唯一的跨设备新鲜度判据:同步已结束,且聚合所用的设备数据版本就是当前版本。
+ // 同步在聚合过程中结束时版本已前进,这份结果不能标成最新。
+ const peerFresh = (payload: UsageHistoryPayload): boolean =>
+ !peerSync || (!peerSync.isSyncing() && payload.peerVersion === peerSync.version());
+ const settle = (payload: UsageHistoryPayload): UsageHistoryPayload => {
+ if (peerFresh(payload)) {
+ return freshPayload({ ...payload, ...(peerSync ? { devicesSyncing: false } : {}) });
+ }
+ // 版本已前进:后台按新数据重聚合,renderer 的 stale 短轮询随后拿到它。
+ if (peerSync && payload.peerVersion !== peerSync.version()) {
+ refreshUsageHistoryInBackground(key, opts);
+ }
+ return stalePayload({ ...payload, devicesSyncing: peerSync?.isSyncing() ?? false });
+ };
if (opts?.forceRefresh) {
const fresh = await refreshUsageHistory(key, opts);
- if (fresh) return freshPayload(fresh);
+ if (fresh) return settle(fresh);
if (cachedHistory && cachedHistoryOptsKey === key) return stalePayload(cachedHistory);
const diskPayload = await hydrateFromDisk(key);
if (diskPayload) return stalePayload(diskPayload);
@@ -867,7 +1184,15 @@ export async function readUsageHistory(opts?: UsageHistoryReadOptions): Promise<
}
if (cachedHistory && cachedHistoryOptsKey === key) {
if (refreshInFlightByOptsKey.has(key)) return stalePayload(cachedHistory);
- if (isMemoryFresh(cachedHistory)) return freshPayload(cachedHistory);
+ // 多设备范围只在输入变化时重聚合:本机用量 / 价格变化走 forceRefresh 推送,设备数据
+ // 变化体现为版本前进,跨天由 todayKey 判定。其余定时重读直接复用,不重扫全量历史;
+ // 同步进行中是否标为更新中由 settle(peerFresh)决定,与是否重聚合分开。
+ const reusable =
+ isMemoryFresh(cachedHistory) ||
+ (peerSync !== null &&
+ cachedHistory.peerVersion === peerSync.version() &&
+ cachedHistory.todayKey === localDayKey());
+ if (reusable) return settle(cachedHistory);
refreshUsageHistoryInBackground(key, opts);
return stalePayload(cachedHistory);
}
@@ -877,7 +1202,7 @@ export async function readUsageHistory(opts?: UsageHistoryReadOptions): Promise<
return stalePayload(diskPayload);
}
const fresh = await refreshUsageHistory(key, opts);
- return fresh ?? emptyUsageHistoryPayload();
+ return fresh ? settle(fresh) : emptyUsageHistoryPayload();
}
/** DB 出错时的兜底空 payload (查询型 handler fallback-data 模式)。 */
diff --git a/apps/desktop/src/main/usageBroadcaster.ts b/apps/desktop/src/main/usageBroadcaster.ts
index 9d863131bd..758b1f978e 100644
--- a/apps/desktop/src/main/usageBroadcaster.ts
+++ b/apps/desktop/src/main/usageBroadcaster.ts
@@ -28,6 +28,7 @@ import { incrementDailySpend, getTodaySpend, localDayKey } from './localDb/daily
import { getGatewayModelPricing } from './usage/modelPricing';
import type { XaiRateLimitSnapshot } from '../shared/xaiRateLimit';
import { incrementDailyModelUsage, type DailyModelUsageDelta } from './localDb/dailyModelUsage';
+import { incrementDailySessionUsage } from './localDb/dailySessionUsage';
import { getCurrentDbClientUserId, getDbClient } from './localDb/client/current';
import {
mergeClaudeSubscriptionUsageSnapshot,
@@ -178,16 +179,40 @@ export async function rebroadcastTodaySpend(): Promise<void> {
* (renderer 复用 USAGE_TODAY_SPEND_CHANGED / USAGE_TODAY_TOKENS_CHANGED 作刷新触发)。
*/
export async function recordModelTurnUsage(
- delta: DailyModelUsageDelta,
+ delta: DailyModelUsageDelta & {
+ /** 产生本轮用量的任务;给出时同时计入 daily_session_usage(「最耗 token 的任务」)。 */
+ sessionId?: string;
+ },
ts: number = Date.now(),
): Promise<void> {
+ const { sessionId, ...modelDelta } = delta;
try {
- await incrementDailyModelUsage(delta, ts);
+ await incrementDailyModelUsage(modelDelta, ts);
} catch (err) {
log.warn(
'recordModelTurnUsage failed:',
err instanceof Error ? err.message : String(err),
);
+ // 任务用量是模型用量的细分:模型行没记上时不单独计入任务,排行不会超出总量。
+ return;
+ }
+ if (!sessionId) return;
+ try {
+ await incrementDailySessionUsage(
+ sessionId,
+ [
+ modelDelta.inputTokensDelta,
+ modelDelta.outputTokensDelta,
+ modelDelta.cacheReadTokensDelta,
+ modelDelta.cacheCreateTokensDelta,
+ ].reduce((sum, value) => sum + (Number.isFinite(value) && value > 0 ? value : 0), 0),
+ ts,
+ );
+ } catch (err) {
+ log.warn(
+ 'record session turn usage failed:',
+ err instanceof Error ? err.message : String(err),
+ );
}
}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 3dde070bd2..2fcaae8c3c 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -7401,6 +7401,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
getHistory: (opts?: {
days?: number | 'all';
modelDays?: number | 'all';
+ /** 'local' (默认) / 'all' (所有设备合并) / 其它电脑的 deviceId。 */
+ device?: string;
forceRefresh?: boolean;
}): Promise<unknown> => ipcRenderer.invoke('maker:usage:history', opts),
/** Claude USD 推送 (per-turn, agentKind=claude-code 时订阅它)。 */
diff --git a/apps/desktop/src/renderer/components/settings/usage/UsageDeviceSelect.tsx b/apps/desktop/src/renderer/components/settings/usage/UsageDeviceSelect.tsx
new file mode 100644
index 0000000000..9e9493bf78
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/usage/UsageDeviceSelect.tsx
@@ -0,0 +1,160 @@
+/**
+ * UsageDeviceSelect — 用量历史的设备范围选择: 所有设备 (默认, 合并) / 本机 / 其它电脑。
+ *
+ * 选项与状态说明由 main 返回的 payload.devices 驱动 (见 main/usage/peerUsageSync.ts)。
+ * 其它电脑的数据来自最近一次成功读取, 每项下方注明「数据截至」或读不到的原因,
+ * 让用户知道合计里包含到哪一刻。外观沿用同页时间范围选择器。
+ */
+
+import React from 'react';
+import { useTranslation } from 'react-i18next';
+import * as Select from '@radix-ui/react-select';
+import { Check, ChevronDown } from 'lucide-react';
+
+import type { UsageHistoryDevice } from '@/hooks/useUsageHistory';
+
+export const USAGE_DEVICE_ALL = 'all';
+export const USAGE_DEVICE_LOCAL = 'local';
+
+export interface UsageDeviceOption {
+ /** 传给 useUsageHistory 的 device 值。 */
+ value: string;
+ device: UsageHistoryDevice | null;
+}
+
+/**
+ * 其它电脑只列出读到过用量的那些 (有「数据截至」): 从未读到的电脑对合计没有贡献,
+ * 列出来只是一排「暂无数据」噪音 (所有者 2026-09-26 裁决)。
+ */
+function hasPeerData(device: UsageHistoryDevice): boolean {
+ return !device.isSelf && device.syncedAt !== null;
+}
+
+/** 本机排第一, 其它电脑按名称排序; 手机不参与 (main 侧已过滤)。 */
+export function buildUsageDeviceOptions(
+ devices: readonly UsageHistoryDevice[],
+): UsageDeviceOption[] {
+ const self = devices.find((device) => device.isSelf) ?? null;
+ const peers = devices.filter(hasPeerData).sort((a, b) => a.name.localeCompare(b.name));
+ return [
+ { value: USAGE_DEVICE_ALL, device: null },
+ { value: USAGE_DEVICE_LOCAL, device: self },
+ ...peers.map((device) => ({ value: device.deviceId, device })),
+ ];
+}
+
+/** 至少有一台其它电脑时才值得显示选择器。 */
+export function hasPeerUsageDevices(devices: readonly UsageHistoryDevice[] | undefined): boolean {
+ return Boolean(devices?.some(hasPeerData));
+}
+
+/** 合并范围里有设备读不到最新数据 (离线、未授权、需要更新、失败)。 */
+export function hasIncompleteUsageDevices(
+ devices: readonly UsageHistoryDevice[] | undefined,
+): boolean {
+ return Boolean(
+ devices?.some(
+ (device) => hasPeerData(device) && device.status !== 'ok' && device.status !== 'syncing',
+ ),
+ );
+}
+
+const STATUS_KEY: Record<Exclude<UsageHistoryDevice['status'], 'ok' | 'syncing'>, string> = {
+ offline: 'usageHistory.device.status.offline',
+ 'remote-disabled': 'usageHistory.device.status.remoteDisabled',
+ unsupported: 'usageHistory.device.status.unsupported',
+ error: 'usageHistory.device.status.error',
+};
+
+const itemClassName =
+ 'flex w-full cursor-pointer select-none items-center justify-between gap-2 rounded-lg px-3 py-2 text-left text-13 text-[var(--text-primary)] outline-none data-[highlighted]:bg-[var(--surface-hover)] data-[state=checked]:bg-[var(--settings-menu-bg-selected)] data-[state=checked]:font-medium data-[state=checked]:text-[var(--settings-menu-text-selected)]';
+
+export function UsageDeviceSelect({
+ value,
+ devices,
+ onValueChange,
+}: {
+ value: string;
+ devices: readonly UsageHistoryDevice[];
+ onValueChange: (value: string) => void;
+}): React.JSX.Element {
+ const { t, i18n } = useTranslation();
+ const options = buildUsageDeviceOptions(devices);
+
+ const formatTime = (ts: number): string =>
+ new Intl.DateTimeFormat(i18n.language, {
+ month: 'short',
+ day: 'numeric',
+ hour: '2-digit',
+ minute: '2-digit',
+ }).format(new Date(ts));
+
+ const label = (option: UsageDeviceOption): string => {
+ if (option.value === USAGE_DEVICE_ALL) return t('usageHistory.device.all');
+ if (option.value === USAGE_DEVICE_LOCAL) {
+ return option.device?.name
+ ? t('usageHistory.device.selfNamed', { name: option.device.name })
+ : t('usageHistory.device.self');
+ }
+ return option.device?.name ?? option.value;
+ };
+
+ const detail = (device: UsageHistoryDevice | null): string | null => {
+ if (!device || device.isSelf) return null;
+ if (device.status === 'syncing') return t('usageHistory.device.status.syncing');
+ const since = device.syncedAt
+ ? t('usageHistory.device.status.syncedAt', { time: formatTime(device.syncedAt) })
+ : t('usageHistory.device.status.noData');
+ if (device.status === 'ok') return since;
+ return `${t(STATUS_KEY[device.status])} · ${since}`;
+ };
+
+ return (
+ <Select.Root value={value} onValueChange={onValueChange}>
+ <Select.Trigger
+ aria-label={t('usageHistory.device.ariaLabel')}
+ className="flex h-9 w-[190px] items-center justify-between gap-2 rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 text-13 text-[var(--text-primary)] outline-none focus:ring-2 focus:ring-[var(--focus-ring-soft)]"
+ >
+ <span className="min-w-0 truncate">
+ <Select.Value />
+ </span>
+ <Select.Icon asChild>
+ <ChevronDown size={15} className="shrink-0 text-[var(--text-tertiary)]" />
+ </Select.Icon>
+ </Select.Trigger>
+ <Select.Portal>
+ <Select.Content
+ position="popper"
+ side="bottom"
+ align="end"
+ sideOffset={4}
+ className="z-[10010] w-[var(--radix-select-trigger-width)] overflow-hidden rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-1"
+ >
+ <Select.Viewport>
+ {options.map((option) => {
+ const sub = detail(option.device);
+ return (
+ <Select.Item key={option.value} value={option.value} className={itemClassName}>
+ {/* DESIGN §4:面板与触发器等宽;长设备名截断,状态说明在面板内换行。 */}
+ <span className="flex min-w-0 flex-col">
+ <span className="truncate">
+ <Select.ItemText>{label(option)}</Select.ItemText>
+ </span>
+ {sub ? (
+ <span className="whitespace-normal break-words text-12 font-normal text-[var(--text-tertiary)]">
+ {sub}
+ </span>
+ ) : null}
+ </span>
+ <Select.ItemIndicator>
+ <Check size={14} strokeWidth={2.25} />
+ </Select.ItemIndicator>
+ </Select.Item>
+ );
+ })}
+ </Select.Viewport>
+ </Select.Content>
+ </Select.Portal>
+ </Select.Root>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx b/apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx
index b3cde6f290..a30256b6f0 100644
--- a/apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx
+++ b/apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx
@@ -2,11 +2,12 @@
* UsageHistorySection — 设置 → 用量历史 (issue #2785)。
*
* 职责边界 (维护者裁决): Billing 管 Cindy AI 的账单与账户信息; 本页只统计
- * **本机 Cindy App 内产生的 token 消耗**, 不出现金额、账户额度、预算或限额窗口,
+ * **Cindy App 内产生的 token 消耗**, 不出现金额、账户额度、预算或限额窗口,
* 也不纳入外部 Claude Code / Codex CLI / 网页版的用量 (那是 #2618)。
*
- * 因此页面上每个数字都来自 useUsageHistory → maker:usage:history → 本地库,
- * 不读任何账号快照 —— local / cloud personal / cloud org 三种身份看到的是同一个页面。
+ * 设备范围: 默认合并同账号所有电脑 (本机库 + 经 device-link 读到并缓存的其它电脑原始行),
+ * 也可切到单台设备。页面上每个数字仍来自 useUsageHistory → maker:usage:history, 不读任何
+ * 账号快照。「最耗 token 的任务」只有本机任务数据, 选中其它电脑时隐藏。
*
* 两个窗口不同, 标题里分别写明:
* - 热力图走完整 days[],按卡片实际宽度显示至少 20 周;连续活跃天数也走同一份历史
@@ -27,13 +28,21 @@ import { Check, ChevronDown, RefreshCw } from 'lucide-react';
import { Spinner } from '@/components/ui/spinner';
import { Input } from '@/components/ui/input';
import { useAuth } from '@/contexts/AuthContext';
-import { useUsageHistory } from '@/hooks/useUsageHistory';
+import { useUsageHistory, type UsageHistoryDevice } from '@/hooks/useUsageHistory';
import { UsageHeatmap } from '@/components/new-chat/UsageHeatmap';
import { usageModelKey } from '@/components/new-chat/usagePalette';
import { UsageStatRow } from './UsageStatRow';
import { UsageTokenBars } from './UsageTokenBars';
import { UsageAgentTable, UsageModelTable } from './UsageBreakdownTables';
-import { UsageTaskTable, useTopTokenSessions } from './UsageTaskTable';
+import { UsageTaskTable, buildUsageTaskRows, usageTaskCoverageStart } from './UsageTaskTable';
+import {
+ USAGE_DEVICE_ALL,
+ USAGE_DEVICE_LOCAL,
+ UsageDeviceSelect,
+ buildUsageDeviceOptions,
+ hasIncompleteUsageDevices,
+ hasPeerUsageDevices,
+} from './UsageDeviceSelect';
import {
buildAgentRows,
buildModelRows,
@@ -81,12 +90,47 @@ function Card({
export function UsageHistorySection(): React.JSX.Element {
const { t, i18n } = useTranslation();
const { user } = useAuth();
+ // 设备选择与记住的设备目录都属于某个账号:切换账号后不得带着旧账号的设备名或 deviceId。
+ const accountKey = user?.id ?? null;
+ const [deviceState, setDeviceState] = useState<{ accountKey: string | null; device: string }>({
+ accountKey,
+ device: USAGE_DEVICE_ALL,
+ });
+ const device = deviceState.accountKey === accountKey ? deviceState.device : USAGE_DEVICE_ALL;
+ const setDevice = (next: string): void => setDeviceState({ accountKey, device: next });
const { history, refreshing } = useUsageHistory({
userId: user?.id,
days: 'all',
modelDays: 'all',
allowPendingEstimates: true,
+ device,
+ includeTasks: true,
});
+ // 切换设备时新范围首帧可能还没有 payload; 沿用上次读到的设备列表, 选择器不闪没。
+ const [known, setKnown] = useState<{
+ accountKey: string | null;
+ devices: UsageHistoryDevice[];
+ } | null>(null);
+ React.useEffect(() => {
+ if (history?.devices) setKnown({ accountKey, devices: history.devices });
+ }, [accountKey, history?.devices]);
+ const devices =
+ history?.devices ?? (known?.accountKey === accountKey ? known.devices : undefined);
+ const showDevicePicker = hasPeerUsageDevices(devices) || device !== USAGE_DEVICE_ALL;
+ // 选中的电脑从账号里移除后回到合并视图, 不让选择器停在一个不存在的选项上。
+ React.useEffect(() => {
+ if (!devices || device === USAGE_DEVICE_ALL || device === USAGE_DEVICE_LOCAL) return;
+ if (!buildUsageDeviceOptions(devices).some((option) => option.value === device)) {
+ setDevice(USAGE_DEVICE_ALL);
+ }
+ }, [device, devices]);
+ // 进入页面后第一次读取其它电脑期间给一个轻量提示;之后每分钟的后台同步不再提示,避免闪烁。
+ const [firstSyncSettled, setFirstSyncSettled] = useState<string | null | undefined>(undefined);
+ React.useEffect(() => {
+ if (history && !history.devicesSyncing) setFirstSyncSettled(accountKey);
+ }, [accountKey, history]);
+ const initialDeviceSync =
+ firstSyncSettled !== accountKey && (history === null || history.devicesSyncing === true);
const [range, setRange] = useState<UsageHistoryRange>('30d');
const [heatmapWeeks, setHeatmapWeeks] = useState(20);
@@ -123,9 +167,9 @@ export function UsageHistorySection(): React.JSX.Element {
[history],
);
- // 任务行与用量聚合是两条数据源: 聚合里有 token, 本地任务却可能一条都没有
- // (用户删光了会话, 或列表还没加载完)。空时整张卡片不渲染, 不留空壳。
- const taskRows = useTopTokenSessions(range, history?.todayKey, user?.id);
+ // 所选范围内产生过 token 的任务(多设备范围含其它电脑的任务)。没有时整张卡片不渲染。
+ const taskRows = useMemo(() => buildUsageTaskRows(history, range), [history, range]);
+ const taskCoverageStart = useMemo(() => usageTaskCoverageStart(history, range), [history, range]);
const loading = history === null && refreshing;
const loadFailed = history === null && !refreshing;
const empty = history !== null && isUsageHistoryEmpty(history);
@@ -152,6 +196,9 @@ export function UsageHistorySection(): React.JSX.Element {
{t('usageHistory.range.label')}
</span>
<div className="ml-auto flex min-w-0 flex-wrap items-center gap-2">
+ {showDevicePicker ? (
+ <UsageDeviceSelect value={device} devices={devices ?? []} onValueChange={setDevice} />
+ ) : null}
<Select.Root value={range} onValueChange={handleRangeChange}>
<Select.Trigger
aria-label={t('usageHistory.range.ariaLabel')}
@@ -220,6 +267,20 @@ export function UsageHistorySection(): React.JSX.Element {
</div>
</div>
+ {initialDeviceSync ? (
+ <p
+ className="-mt-2 mb-3 inline-flex items-center gap-1.5 text-12 text-[var(--text-tertiary)]"
+ role="status"
+ >
+ <Spinner icon={RefreshCw} size={11} className="opacity-70" />
+ {t('usageHistory.device.loading')}
+ </p>
+ ) : device === USAGE_DEVICE_ALL && hasIncompleteUsageDevices(devices) ? (
+ <p className="-mt-2 mb-3 text-12 text-[var(--text-tertiary)]">
+ {t('usageHistory.device.partial')}
+ </p>
+ ) : null}
+
{loading ? (
<div
className="flex min-h-[176px] items-center justify-center rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] text-[var(--text-tertiary)]"
@@ -300,10 +361,22 @@ export function UsageHistorySection(): React.JSX.Element {
{taskRows.length > 0 && (
<Card
title={t('usageHistory.tasks.title')}
- subtitle={t('usageHistory.tasks.subtitle', { range: rangeLabel })}
+ subtitle={
+ taskCoverageStart
+ ? `${t('usageHistory.tasks.subtitle', { range: rangeLabel })} · ${t(
+ 'usageHistory.tasks.coverage',
+ {
+ date: new Intl.DateTimeFormat(i18n.language, {
+ month: 'short',
+ day: 'numeric',
+ }).format(new Date(`${taskCoverageStart}T12:00:00`)),
+ },
+ )}`
+ : t('usageHistory.tasks.subtitle', { range: rangeLabel })
+ }
>
<div className="overflow-x-auto">
- <UsageTaskTable rows={taskRows} rangeLabel={rangeLabel} />
+ <UsageTaskTable rows={taskRows} rangeLabel={rangeLabel} devices={devices} />
</div>
</Card>
)}
diff --git a/apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx b/apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx
index f399a0895f..cd23ef06be 100644
--- a/apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx
+++ b/apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx
@@ -1,68 +1,42 @@
/**
- * UsageTaskTable — 「最耗 token 的任务」。
+ * UsageTaskTable — 「最耗 token 的任务」(设置 → 用量历史)。
*
- * 数据来自本地会话表的用量历史查询 (并与 useCCSessions 的实时快照合并):
- * - tokens: Session.totalTokenUsage
- * - 上下文: contextTokens / contextWindow
- * - 供应商: Session.providerId, 经 providerDisplayNameById 映射成展示名
- * (内置 id 走设置页 i18n 标题, 自定义供应商回退目录里的 name)
- * - 最后活跃: userSendAt / updatedAt 中较新者 (与 SessionItem 同一条时间轴 ——
- * 旧版 DB 行只写 userSendAt), 走 sidebar 同一套 formatSidebarTime
+ * 数据来自用量历史 payload 的 taskDaily / tasks(main 侧 daily_session_usage,多设备范围
+ * 合并了其它电脑同步来的行):按所选时间范围对每个任务**在该范围内**产生的 token 求和,
+ * 取前 TOP_TASKS 名。每日 × 任务的记录从功能上线起积累,更早的用量不计入 —— 所选范围
+ * 早于最早记录时,卡片副标题注明「按天统计从 X 起」。
*
- * 两处口径必须在 UI 上讲清楚, 否则会被误读:
- * 1. totalTokenUsage 是该任务的**生命周期累计**, 不是窗口内增量。本表筛的是
- * "所选时间范围内活跃过的任务", 所以一个三个月前开始、昨天还在跑的任务会带着
- * 它的全部累计出现 —— 表头 tooltip 写明这一点。
- * 2. providerId 是会话**当前值**而非每轮事实, 且可为 null (跟随默认路由)。
- * null 留空 (照 SessionInfoMeta 既有的"无数据不显示"), 不臆造默认供应商;
- * 任务若中途切换过供应商, 早先的 token 也会归到当前这个上 —— 表头 tooltip
- * 写明"取当前选定的供应商", 不额外标记 (没有可靠的切换记录可依据)。
+ * 任务标题是跳转到该任务的链接;整行是鼠标的放大命中区(键盘仍只落在链接上)。其它电脑
+ * 的任务只有在远程设备列表里能找到时才可点击(需要该设备已连接)。
*
- * 远程会话 (device-link) 的 token 字段可能缺失或为 0 —— 同样按"无数据不显示"过滤掉。
- *
- * 用量历史查询跳过侧栏按 updatedAt 截断的 1000 行列表,返回完整 sessions 候选集;
- * 因此 all / 较早日期范围仍能从全量历史中筛出 Top N。查询只读取 sessions 表,
- * 不计算消息预览,避免把统计页变成整库 messages 扫描。
+ * 标题 / 模型 / 供应商 / 上下文取任务当前值,不是每轮事实;providerId 为 null 留空。
*/
-import React, { useEffect, useMemo, useRef, useState } from 'react';
+import React from 'react';
import { useTranslation } from 'react-i18next';
+import { Link, useNavigate } from 'react-router-dom';
import { cn } from '@/lib/utils';
import { formatCompactTokens, formatModelShort } from '@/lib/usageFormat';
-import { useCCSessions } from '@/hooks/useCCSessions';
-import * as sessionService from '@/lib/sessionService';
-import type { Session, UsageHistorySession } from '@/lib/ccAgent.types';
import { formatSidebarTime } from '@/features/cc-agent/lib/formatSidebarTime';
import { useProviders } from '@/hooks/useProviders';
-import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';
+import type { UsageHistoryDevice, UsageHistoryPayload } from '@/hooks/useUsageHistory';
import { usageRankColor } from '@/components/new-chat/usagePalette';
import { providerDisplayNameById } from '@/lib/providerDisplayName';
+import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';
+import { useRemoteProjectSessions } from '@/features/device-link/remoteProjectsStore';
import { formatUsagePercent } from './formatUsagePercent';
-import {
- isUsageDayInRange,
- isUsageHistorySingleDay,
- type UsageHistoryRange,
-} from './usageHistoryStats';
+import { isUsageDayInRange, type UsageHistoryRange } from './usageHistoryStats';
/** 展示条数 —— 与"最耗"的语义匹配, 不做成完整列表 (那是任务侧栏的事)。 */
const TOP_TASKS = 8;
const UNKNOWN_VALUE = '—';
+/** payload 里本机任务的设备键(见 main usageHistory LOCAL_TASK_DEVICE)。 */
+const LOCAL_TASK_DEVICE = 'local';
/**
- * 列宽口径: 右侧五列 (模型/供应商/token/上下文/最后活跃) 都是短的定长内容, 让它们
- * 按各自内容取满宽 —— 这几列是要被读数的, 不能被挤窄或截断; pl-3 是列间距, 否则
- * 相邻两列的数字会贴到一起。任务名是用户输入的自由文本, 长度没有上限, 只能反过来
- * 吃右侧列分完后剩下的空间。
- *
- * 列间距取 12px 而不是 16px: 侧栏可拉到 480 (useSidebarResize MAX_WIDTH), 主窗下限
- * 800, 此时设置页卡片内的表格只剩约 230px。列间距落在 nowrap 单元格上是**不可收缩**
- * 宽度, 五列就是 5 份 —— 12px 比 16px 省下 20px, 直接抬高开始溢出的窗口宽度。
- * 12 与 16 同在 DESIGN.md §5 间距刻度上, 这个字号下的分隔效果没有可见差别。
- *
- * 实现上靠 `w-full + max-w-0` (任务列自身 pl-0): 自动布局的表格若不加这一对,
- * 会先按 nowrap 的最长任务名算出列宽、把整张卡片横向撑开, 内层的 truncate 因为
- * 没有可收缩的宽度而失效。max-w-0 让这一列先塌到 0, w-full 再让它领走余量。
+ * 列宽口径: 右侧五列都是短的定长内容, 按各自内容取满宽; 任务名是自由文本, 只能吃剩下
+ * 的空间。`w-full + max-w-0` 让任务列先塌到 0 再领走余量, 内层 truncate 才生效。
*/
const TH_CLASS =
'whitespace-nowrap border-b border-[var(--border-default)] pb-2 pl-3 text-right text-12 font-medium text-[var(--text-secondary)]';
@@ -70,196 +44,88 @@ const TD_CLASS =
'whitespace-nowrap border-b border-[var(--border-default)] py-2 pl-3 text-right text-13 tabular-nums';
const TASK_COL_CLASS = 'w-full max-w-0 pl-0';
-/** 与 SessionItem 一致: 取两者中较新的值, 兼容只写 userSendAt 的存量行。 */
-function lastActiveIso(session: { updatedAt: string; userSendAt: string | null }): string {
- return session.userSendAt && session.userSendAt > session.updatedAt
- ? session.userSendAt
- : session.updatedAt;
-}
-
-function localDayKeyFromIso(iso: string): string | null {
- const date = new Date(iso);
- if (!Number.isFinite(date.getTime())) return null;
- const month = String(date.getMonth() + 1).padStart(2, '0');
- const day = String(date.getDate()).padStart(2, '0');
- return `${date.getFullYear()}-${month}-${day}`;
+export interface UsageTaskRow {
+ taskKey: string;
+ deviceId: string;
+ sessionId: string;
+ title: string;
+ model: string;
+ providerId: string | null;
+ contextTokens: number;
+ contextWindow: number;
+ lastActiveAt: number;
+ /** 所选范围内的 token。 */
+ tokens: number;
}
-function activeWithinRange(
- iso: string | null | undefined,
+/** 按所选范围汇总每个任务的 token,降序取前 TOP_TASKS。 */
+export function buildUsageTaskRows(
+ history: UsageHistoryPayload | null,
range: UsageHistoryRange,
- todayKey: string,
-): boolean {
- if (!iso) return false;
- const day = localDayKeyFromIso(iso);
- return day !== null && isUsageDayInRange(day, todayKey, range);
-}
-
-/**
- * 用量范围只应按用户真正发送消息的时间筛选。updatedAt 还会被重命名、归档、
- * 置顶等元数据更新推进;只有存量行没有 userSendAt 时才回退到 updatedAt。
- */
-export function usageActivityIso(session: Pick<Session, 'updatedAt' | 'userSendAt'>): string {
- return session.userSendAt ?? session.updatedAt;
-}
-
-/**
- * 任务表只按会话的最后活跃时间筛选,无法证明某个任务在单日范围内实际活跃过。
- * 因此 today 与 day:* 都隐藏这张聚合表,避免把累计 token 误读成当天用量。
- */
-export function shouldHideUsageTaskTable(range: UsageHistoryRange): boolean {
- return isUsageHistorySingleDay(range);
-}
-
-export type UsageSessionsState =
- | { scopeKey: string | null; status: 'loading' }
- | { scopeKey: string | null; status: 'ready'; sessions: UsageHistorySession[] }
- | { scopeKey: string | null; status: 'error' };
-
-/** Only a snapshot belonging to the current data owner may feed the table. */
-export function usageSessionsForScope(
- state: UsageSessionsState,
- scopeKey: string | null,
-): UsageHistorySession[] {
- return state.scopeKey === scopeKey && state.status === 'ready' ? state.sessions : [];
-}
-
-/** Consume an existing deleted-session push without weakening the full-query scope. */
-export function removeUsageSessionForScope(
- state: UsageSessionsState,
- scopeKey: string | null,
- sessionId: string,
-): UsageSessionsState {
- if (state.scopeKey !== scopeKey || state.status !== 'ready') return state;
- return {
- ...state,
- sessions: state.sessions.filter((session) => session.id !== sessionId),
- };
+): UsageTaskRow[] {
+ if (!history?.taskDaily || !history.tasks || !history.todayKey) return [];
+ const tokensByTask = new Map<string, number>();
+ for (const row of history.taskDaily) {
+ if (!isUsageDayInRange(row.day, history.todayKey, range)) continue;
+ tokensByTask.set(row.taskKey, (tokensByTask.get(row.taskKey) ?? 0) + row.tokens);
+ }
+ const rows: UsageTaskRow[] = [];
+ for (const task of history.tasks) {
+ const tokens = tokensByTask.get(task.taskKey) ?? 0;
+ if (tokens > 0) rows.push({ ...task, tokens });
+ }
+ return rows.sort((a, b) => b.tokens - a.tokens).slice(0, TOP_TASKS);
}
/**
- * Merge live sidebar metadata into the full usage-history row without letting
- * the sidebar's potentially stale token snapshot replace the database total.
+ * 最早有每日 × 任务记录的日期;所选范围早于它时返回它(用于「按天统计从 X 起」),
+ * 否则返回 null。
*/
-export function mergeUsageSessionSnapshots(
- fullSession: UsageHistorySession,
- liveSession: Session,
-): UsageHistorySession {
- return {
- ...fullSession,
- title: liveSession.title,
- model: liveSession.model,
- providerId: liveSession.providerId,
- contextTokens: liveSession.contextTokens,
- contextWindow: liveSession.contextWindow,
- userSendAt: liveSession.userSendAt,
- updatedAt: liveSession.updatedAt,
- totalTokenUsage: fullSession.totalTokenUsage,
- };
-}
-
-/**
- * 候选行 —— 单独暴露成 hook, 让调用方能在**渲染卡片之前**知道有没有行。
- * 组件内部返回 null 会留下一张只有标题、正文全空的卡片 (会话被删光 / 列表首次加载中)。
- */
-export function useTopTokenSessions(
- range: UsageHistoryRange = '30d',
- todayKeyOverride?: string,
- accountScopeKey?: string,
-): UsageHistorySession[] {
- // 归档的任务同样消耗过 token, 统计口径不该因为用户归档而变。
- const { sessions: recentSessions } = useCCSessions({ includeArchived: 'all' });
- const scopeKey = accountScopeKey ?? null;
- const deletedSessionIdsRef = useRef<Set<string>>(new Set());
- const [usageSessions, setUsageSessions] = useState<UsageSessionsState>(() => ({
- scopeKey,
- status: 'loading',
- }));
-
- useEffect(() => {
- let cancelled = false;
- deletedSessionIdsRef.current = new Set();
- setUsageSessions({ scopeKey, status: 'loading' });
- const sessionsPush = window.electronAPI?.localDb?.sessionsPush;
- const unsubscribe = sessionsPush?.onPatched(({ sessionId, patch }, ownerStamp) => {
- if (!isDataOwnerPushCurrent(ownerStamp) || patch.status !== 'deleted') return;
- deletedSessionIdsRef.current.add(sessionId);
- setUsageSessions((state) => removeUsageSessionForScope(state, scopeKey, sessionId));
- });
- // The task table intentionally uses the full-query snapshot as its
- // lifecycle-total source. It does not maintain a second partial live-update
- // path: the usage charts own dated live refresh, while this aggregate is
- // refreshed when its account scope changes or the page remounts.
- void sessionService
- .list(20, 'all', { usageHistory: true })
- .then((rows) => {
- if (cancelled) return;
- const deletedSessionIds = deletedSessionIdsRef.current;
- setUsageSessions({
- scopeKey,
- status: 'ready',
- sessions: rows.filter((session) => !deletedSessionIds.has(session.id)),
- });
- })
- .catch(() => {
- if (!cancelled) setUsageSessions({ scopeKey, status: 'error' });
- });
- return () => {
- cancelled = true;
- unsubscribe?.();
- };
- }, [scopeKey]);
-
- const sessions = useMemo(() => {
- // The sidebar snapshot is capped at 1000 rows and cannot stand in for the
- // full usage-history query. Hide the aggregate until that query succeeds;
- // showing the truncated or failed fallback would mislabel the ranking.
- if (usageSessions.scopeKey !== scopeKey || usageSessions.status !== 'ready') return [];
- const scopedSessions = usageSessionsForScope(usageSessions, scopeKey);
- const byId = new Map(scopedSessions.map((session) => [session.id, session]));
- // 侧栏快照只补充实时元数据;其 totalTokenUsage 可能滞后,保留全量查询的累计值。
- for (const session of recentSessions) {
- if (deletedSessionIdsRef.current.has(session.id)) continue;
- const usageSession = byId.get(session.id);
- byId.set(
- session.id,
- usageSession ? mergeUsageSessionSnapshots(usageSession, session) : session,
- );
- }
- return [...byId.values()];
- }, [recentSessions, scopeKey, usageSessions]);
-
- return useMemo(() => {
- // Sessions retain only their latest activity timestamp, so they cannot
- // prove historical membership for an exact calendar day. Hide this
- // aggregate rather than presenting a task as active on a day it may not
- // have used. The day-level charts and agent/model tables use dated usage
- // records and remain exact.
- if (shouldHideUsageTaskTable(range)) return [];
- const now = new Date();
- const todayKey =
- todayKeyOverride ??
- `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
- return sessions
- .filter(
- (session) =>
- session.totalTokenUsage > 0 &&
- activeWithinRange(usageActivityIso(session), range, todayKey),
- )
- .sort((a, b) => b.totalTokenUsage - a.totalTokenUsage)
- .slice(0, TOP_TASKS);
- }, [range, sessions, todayKeyOverride]);
+export function usageTaskCoverageStart(
+ history: UsageHistoryPayload | null,
+ range: UsageHistoryRange,
+): string | null {
+ if (!history?.taskDaily?.length || !history.todayKey) return null;
+ const earliest = history.taskDaily.reduce(
+ (min, row) => (row.day < min ? row.day : min),
+ history.taskDaily[0].day,
+ );
+ // 所选范围内是否有早于最早记录的日期:检查最早记录的前一天是否落在范围里。
+ const [y, m, d] = earliest.split('-').map(Number);
+ const prev = new Date(y, (m ?? 1) - 1, (d ?? 1) - 1);
+ const prevKey = `${prev.getFullYear()}-${String(prev.getMonth() + 1).padStart(2, '0')}-${String(prev.getDate()).padStart(2, '0')}`;
+ return isUsageDayInRange(prevKey, history.todayKey, range) ? earliest : null;
}
export function UsageTaskTable({
rows,
rangeLabel,
+ devices,
}: {
- rows: UsageHistorySession[];
+ rows: UsageTaskRow[];
rangeLabel: string;
+ devices?: readonly UsageHistoryDevice[];
}): React.JSX.Element {
const { t } = useTranslation();
const { providers } = useProviders();
+ const navigate = useNavigate();
+ const remoteSessions = useRemoteProjectSessions();
+ const deviceNames = new Map((devices ?? []).map((device) => [device.deviceId, device.name]));
+
+ /** 其它电脑的任务:只认该设备当前已连接时的会话快照(断线后快照仍保留,但任务不可达)。 */
+ const remoteSessionFor = (row: UsageTaskRow) =>
+ remoteSessions.find(
+ (session) =>
+ session.id === row.sessionId &&
+ session.deviceLinkDeviceId === row.deviceId &&
+ session.deviceLinkConnectionStatus === 'connected',
+ ) ?? null;
+
+ const openRow = (row: UsageTaskRow): void => {
+ const remote = row.deviceId === LOCAL_TASK_DEVICE ? null : remoteSessionFor(row);
+ if (row.deviceId !== LOCAL_TASK_DEVICE && !remote) return;
+ void resolveSessionRoute(row.sessionId, remote).then((route) => navigate(route));
+ };
return (
<table className="w-full border-collapse">
@@ -283,37 +149,72 @@ export function UsageTaskTable({
</tr>
</thead>
<tbody>
- {rows.map((session, index) => {
- const providerName = session.providerId
- ? providerDisplayNameById(session.providerId, providers, t)
+ {rows.map((row, index) => {
+ const isLocal = row.deviceId === LOCAL_TASK_DEVICE;
+ const openable = isLocal || remoteSessionFor(row) !== null;
+ const deviceName = isLocal ? null : (deviceNames.get(row.deviceId) ?? null);
+ const providerName = row.providerId
+ ? providerDisplayNameById(row.providerId, providers, t)
: null;
- const contextRatio =
- session.contextWindow > 0 ? session.contextTokens / session.contextWindow : null;
+ const contextRatio = row.contextWindow > 0 ? row.contextTokens / row.contextWindow : null;
+ const title = row.title || UNKNOWN_VALUE;
return (
- <tr key={session.id}>
+ <tr
+ key={row.taskKey}
+ data-task-key={row.taskKey}
+ className={cn(
+ openable && 'cursor-pointer transition-colors hover:bg-[var(--surface-hover)]',
+ )}
+ // 整行只是鼠标的放大命中区;键盘与读屏仍落在标题链接上。
+ onClick={openable ? () => openRow(row) : undefined}
+ >
<td className={cn(TD_CLASS, TASK_COL_CLASS, 'text-left')}>
<span className="flex min-w-0 items-center gap-2">
<span
className="size-2 shrink-0 rounded-[2px]"
style={{ backgroundColor: usageRankColor(index) }}
/>
- <span className="truncate font-medium" title={session.title}>
- {session.title}
+ <span className="flex min-w-0 flex-col">
+ {openable ? (
+ <Link
+ to={`/cc-agent/${row.sessionId}`}
+ onClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ openRow(row);
+ }}
+ className="truncate rounded-[4px] font-medium text-[var(--text-primary)] underline-offset-2 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ title={title}
+ >
+ {title}
+ </Link>
+ ) : (
+ <span className="truncate font-medium" title={title}>
+ {title}
+ </span>
+ )}
+ {deviceName ? (
+ <span className="truncate text-12 font-normal text-[var(--text-tertiary)]">
+ {deviceName}
+ </span>
+ ) : null}
</span>
</span>
</td>
<td className={cn(TD_CLASS, 'text-[var(--text-tertiary)]')}>
- {formatModelShort(session.model)}
+ {row.model ? formatModelShort(row.model) : UNKNOWN_VALUE}
</td>
<td className={cn(TD_CLASS, 'text-[var(--text-tertiary)]')}>
{providerName ?? UNKNOWN_VALUE}
</td>
- <td className={TD_CLASS}>{formatCompactTokens(session.totalTokenUsage)}</td>
+ <td className={TD_CLASS}>{formatCompactTokens(row.tokens)}</td>
<td className={cn(TD_CLASS, 'text-[var(--text-tertiary)]')}>
{contextRatio === null ? UNKNOWN_VALUE : formatUsagePercent(contextRatio)}
</td>
<td className={cn(TD_CLASS, 'text-[var(--text-tertiary)]')}>
- {formatSidebarTime(lastActiveIso(session), t) || UNKNOWN_VALUE}
+ {row.lastActiveAt > 0
+ ? formatSidebarTime(new Date(row.lastActiveAt).toISOString(), t) || UNKNOWN_VALUE
+ : UNKNOWN_VALUE}
</td>
</tr>
);
diff --git a/apps/desktop/src/renderer/components/settings/usage/__tests__/usageHistoryDateSelection.test.tsx b/apps/desktop/src/renderer/components/settings/usage/__tests__/usageHistoryDateSelection.test.tsx
index 4e2de20483..8256dca496 100644
--- a/apps/desktop/src/renderer/components/settings/usage/__tests__/usageHistoryDateSelection.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/usage/__tests__/usageHistoryDateSelection.test.tsx
@@ -14,10 +14,11 @@ vi.mock('@/hooks/useUsageHistory', () => ({
useUsageHistory: () => ({ history: state.history, refreshing: false }),
}));
vi.mock('../UsageTaskTable', () => ({
- useTopTokenSessions: (range: string) => {
+ buildUsageTaskRows: (_history: unknown, range: string) => {
state.taskRange = range;
return [];
},
+ usageTaskCoverageStart: () => null,
UsageTaskTable: () => null,
}));
vi.mock('../UsageStatRow', () => ({
diff --git a/apps/desktop/src/renderer/components/settings/usage/__tests__/usageHistoryDevices.test.tsx b/apps/desktop/src/renderer/components/settings/usage/__tests__/usageHistoryDevices.test.tsx
new file mode 100644
index 0000000000..77c05111a7
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/usage/__tests__/usageHistoryDevices.test.tsx
@@ -0,0 +1,194 @@
+// @vitest-environment jsdom
+import React from 'react';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { cleanup, render } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { UsageHistoryDevice, UsageHistoryPayload } from '@/hooks/useUsageHistory';
+import { UsageHistorySection } from '../UsageHistorySection';
+import {
+ buildUsageDeviceOptions,
+ hasIncompleteUsageDevices,
+ hasPeerUsageDevices,
+} from '../UsageDeviceSelect';
+
+const state = vi.hoisted(() => ({
+ history: null as UsageHistoryPayload | null,
+ requests: [] as Array<{ device?: string }>,
+ taskRows: [] as unknown[],
+ userId: null as string | null,
+}));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }),
+}));
+vi.mock('@/contexts/AuthContext', () => ({
+ useAuth: () => ({ user: state.userId ? { id: state.userId } : null }),
+}));
+vi.mock('@/hooks/useUsageHistory', () => ({
+ useUsageHistory: (opts: { device?: string }) => {
+ state.requests.push(opts);
+ return { history: state.history, refreshing: false };
+ },
+}));
+vi.mock('../UsageTaskTable', () => ({
+ buildUsageTaskRows: () => state.taskRows,
+ usageTaskCoverageStart: () => null,
+ UsageTaskTable: () => <output data-testid="tasks" />,
+}));
+vi.mock('../UsageStatRow', () => ({ UsageStatRow: () => null }));
+vi.mock('../UsageBreakdownTables', () => ({
+ UsageAgentTable: () => null,
+ UsageModelTable: () => null,
+}));
+afterEach(() => {
+ cleanup();
+ state.requests = [];
+ state.taskRows = [];
+ state.userId = null;
+});
+
+const money = {
+ amount: 0,
+ currency: 'USD' as const,
+ approximate: false,
+ kind: 'actual-cost' as const,
+};
+
+function device(over: Partial<UsageHistoryDevice> & { deviceId: string }): UsageHistoryDevice {
+ return {
+ name: over.deviceId,
+ platform: 'darwin',
+ isSelf: false,
+ syncedAt: null,
+ status: 'ok',
+ ...over,
+ };
+}
+
+function history(devices?: UsageHistoryDevice[]): UsageHistoryPayload {
+ return {
+ generatedAt: 0,
+ todayKey: '2026-09-26',
+ days: [{ day: '2026-09-26', money, tokens: 100 }],
+ modelDaily: [],
+ models: [],
+ totals: {
+ today: money,
+ last30Days: money,
+ last30DaysWithEstimatedValue: money,
+ last30DaysEstimatedValue: money,
+ todayTokens: 100,
+ last30DaysTokens: 100,
+ },
+ streak: { current: 1, longest: 1 },
+ anomaly: { isAnomalous: false, trailing7DayAvg: null },
+ ...(devices ? { devices } : {}),
+ };
+}
+
+describe('usage device options', () => {
+ it('orders all devices, this device, then other computers by name', () => {
+ const options = buildUsageDeviceOptions([
+ device({ deviceId: 'z', name: 'Zed', syncedAt: 2 }),
+ device({ deviceId: 'self', name: 'Studio', isSelf: true }),
+ device({ deviceId: 'a', name: 'Air', syncedAt: 1 }),
+ device({ deviceId: 'never', name: 'Never read', status: 'offline' }),
+ ]);
+ expect(options.map((option) => option.value)).toEqual(['all', 'local', 'a', 'z']);
+ expect(options[1].device?.name).toBe('Studio');
+ });
+
+ it('flags merged totals as incomplete only for unreadable computers', () => {
+ const self = device({ deviceId: 'self', isSelf: true });
+ expect(hasPeerUsageDevices([self])).toBe(false);
+ expect(hasPeerUsageDevices(undefined)).toBe(false);
+ expect(hasIncompleteUsageDevices([self, device({ deviceId: 'b', status: 'syncing' })])).toBe(
+ false,
+ );
+ expect(
+ hasIncompleteUsageDevices([self, device({ deviceId: 'b', status: 'offline', syncedAt: 1 })]),
+ ).toBe(true);
+ // 从未读到的电脑不列出,也不触发「合计可能偏少」。
+ const never = device({ deviceId: 'c', status: 'unsupported' });
+ expect(hasPeerUsageDevices([self, never])).toBe(false);
+ expect(hasIncompleteUsageDevices([self, never])).toBe(false);
+ });
+});
+
+describe('Usage history device scope', () => {
+ it('requests the merged all-devices scope by default and hides the picker without other computers', () => {
+ state.history = history([device({ deviceId: 'self', isSelf: true })]);
+ const view = render(<UsageHistorySection />);
+ expect(state.requests.at(-1)?.device).toBe('all');
+ expect(view.queryByLabelText('usageHistory.device.ariaLabel')).toBeNull();
+ expect(view.queryByText('usageHistory.device.partial')).toBeNull();
+ });
+
+ it('shows the picker, the incomplete note and the merged task card with other computers', () => {
+ state.history = history([
+ device({ deviceId: 'self', isSelf: true }),
+ device({ deviceId: 'laptop', status: 'offline', syncedAt: 1 }),
+ ]);
+ state.taskRows = [{}];
+ const view = render(<UsageHistorySection />);
+ expect(view.getByLabelText('usageHistory.device.ariaLabel')).toBeTruthy();
+ expect(view.getByText('usageHistory.device.partial')).toBeTruthy();
+ expect(view.getByText('usageHistory.tasks.subtitle')).toBeTruthy();
+ expect(view.getByTestId('tasks')).toBeTruthy();
+ });
+});
+
+describe('usage device select panel', () => {
+ it('binds the dropdown panel to the trigger width (DESIGN.md §4)', () => {
+ const source = readFileSync(resolve(__dirname, '../UsageDeviceSelect.tsx'), 'utf8');
+ expect(source).toContain('w-[var(--radix-select-trigger-width)]');
+ expect(source).not.toContain('min-w-[var(--radix-select-trigger-width)]');
+ expect(source).not.toMatch(/max-w-\[\d+px\]/);
+ });
+});
+
+describe('usage device scope across accounts', () => {
+ it('drops the previous account devices and selection when the account changes', () => {
+ state.userId = 'account-a';
+ state.history = history([
+ device({ deviceId: 'self', isSelf: true }),
+ device({ deviceId: 'laptop-a', name: 'Laptop A', syncedAt: 1 }),
+ ]);
+ const view = render(<UsageHistorySection />);
+ expect(view.getByLabelText('usageHistory.device.ariaLabel')).toBeTruthy();
+
+ // 新账号的首帧还没有 payload(或回退空 payload 不带 devices)。
+ state.userId = 'account-b';
+ state.history = null;
+ view.rerender(<UsageHistorySection />);
+ expect(state.requests.at(-1)?.device).toBe('all');
+ expect(view.queryByLabelText('usageHistory.device.ariaLabel')).toBeNull();
+ expect(view.queryByText('Laptop A')).toBeNull();
+ });
+});
+
+describe('usage device first-load hint', () => {
+ it('shows a quiet loading line during the first device sync only', () => {
+ state.history = {
+ ...history([device({ deviceId: 'self', isSelf: true })]),
+ devicesSyncing: true,
+ };
+ const view = render(<UsageHistorySection />);
+ expect(view.getByText('usageHistory.device.loading')).toBeTruthy();
+
+ state.history = {
+ ...history([
+ device({ deviceId: 'self', isSelf: true }),
+ device({ deviceId: 'b', syncedAt: 1 }),
+ ]),
+ devicesSyncing: false,
+ };
+ view.rerender(<UsageHistorySection />);
+ expect(view.queryByText('usageHistory.device.loading')).toBeNull();
+
+ // 之后每分钟的后台同步不再提示。
+ state.history = { ...state.history, devicesSyncing: true };
+ view.rerender(<UsageHistorySection />);
+ expect(view.queryByText('usageHistory.device.loading')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/components/settings/usage/__tests__/usageHistoryStats.test.ts b/apps/desktop/src/renderer/components/settings/usage/__tests__/usageHistoryStats.test.ts
index 57a36f0a0b..eae1184f53 100644
--- a/apps/desktop/src/renderer/components/settings/usage/__tests__/usageHistoryStats.test.ts
+++ b/apps/desktop/src/renderer/components/settings/usage/__tests__/usageHistoryStats.test.ts
@@ -1,6 +1,5 @@
import { describe, expect, it } from 'vitest';
-import type { Session } from '@/lib/ccAgent.types';
import type { UsageHistoryPayload } from '@/hooks/useUsageHistory';
import {
buildAgentRows,
@@ -15,14 +14,6 @@ import {
usageRangeDay,
toUsageDays,
} from '../usageHistoryStats';
-import {
- removeUsageSessionForScope,
- mergeUsageSessionSnapshots,
- shouldHideUsageTaskTable,
- usageActivityIso,
- usageSessionsForScope,
- type UsageSessionsState,
-} from '../UsageTaskTable';
const zeroMoney = {
amount: 0,
@@ -66,14 +57,6 @@ function payload(over: Partial<UsageHistoryPayload> = {}): UsageHistoryPayload {
};
}
-describe('shouldHideUsageTaskTable', () => {
- it('单日范围(包括 today)隐藏无法精确归因的任务表', () => {
- expect(shouldHideUsageTaskTable('today')).toBe(true);
- expect(shouldHideUsageTaskTable('day:2026-08-20')).toBe(true);
- expect(shouldHideUsageTaskTable('7d')).toBe(false);
- });
-});
-
describe('isUsageHistorySingleDay', () => {
it('识别 today 与日期钻取范围', () => {
expect(isUsageHistorySingleDay('today')).toBe(true);
@@ -90,48 +73,6 @@ describe('usageRangeDay', () => {
});
});
-describe('usage task session scope', () => {
- const readyState = (scopeKey: string): UsageSessionsState => ({
- scopeKey,
- status: 'ready',
- sessions: [{ id: 'session-a' } as Session],
- });
-
- it('账号切换的过渡帧不暴露旧账号的全量快照', () => {
- expect(usageSessionsForScope(readyState('owner-a'), 'owner-b')).toEqual([]);
- });
-
- it('只从同一账号的快照消费 deleted 事件', () => {
- const state = readyState('owner-a');
- expect(removeUsageSessionForScope(state, 'owner-a', 'session-a')).toMatchObject({
- scopeKey: 'owner-a',
- status: 'ready',
- sessions: [],
- });
- expect(removeUsageSessionForScope(state, 'owner-b', 'session-a')).toBe(state);
- });
-
- it('合并实时元数据时保留全量查询的累计 token', () => {
- const fullSession = {
- id: 'session-a',
- title: '历史标题',
- totalTokenUsage: 1000,
- } as Session;
- const liveSession = {
- id: 'session-a',
- title: '最新标题',
- totalTokenUsage: 100,
- } as Session;
-
- expect(mergeUsageSessionSnapshots(fullSession, liveSession)).toMatchObject({
- id: 'session-a',
- title: '最新标题',
- totalTokenUsage: 1000,
- });
- });
-
-});
-
describe('cacheHitRate', () => {
it('输出 token 不进分母 (与逐轮卡片同一公式)', () => {
expect(
@@ -405,16 +346,3 @@ describe('filterUsageHistoryPayload', () => {
});
});
-describe('usageActivityIso', () => {
- it('忽略元数据更新时间,优先使用用户发送时间;存量行才回退 updatedAt', () => {
- expect(
- usageActivityIso({
- userSendAt: '2026-08-20T10:00:00.000Z',
- updatedAt: '2026-08-22T10:00:00.000Z',
- }),
- ).toBe('2026-08-20T10:00:00.000Z');
- expect(usageActivityIso({ userSendAt: null, updatedAt: '2026-08-22T10:00:00.000Z' })).toBe(
- '2026-08-22T10:00:00.000Z',
- );
- });
-});
diff --git a/apps/desktop/src/renderer/components/settings/usage/__tests__/usageTaskTable.test.tsx b/apps/desktop/src/renderer/components/settings/usage/__tests__/usageTaskTable.test.tsx
new file mode 100644
index 0000000000..9d70f59ab8
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/usage/__tests__/usageTaskTable.test.tsx
@@ -0,0 +1,150 @@
+// @vitest-environment jsdom
+import React from 'react';
+import { cleanup, fireEvent, render, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { UsageHistoryPayload, UsageHistoryTask } from '@/hooks/useUsageHistory';
+import { UsageTaskTable, buildUsageTaskRows, usageTaskCoverageStart } from '../UsageTaskTable';
+
+const state = vi.hoisted(() => ({
+ navigate: vi.fn(),
+ remoteSessions: [] as Array<{
+ id: string;
+ deviceLinkDeviceId?: string;
+ deviceLinkConnectionStatus?: string;
+ }>,
+}));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }),
+}));
+vi.mock('react-router-dom', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('react-router-dom')>()),
+ useNavigate: () => state.navigate,
+}));
+vi.mock('@/hooks/useProviders', () => ({ useProviders: () => ({ providers: [] }) }));
+vi.mock('@/features/device-link/remoteProjectsStore', () => ({
+ useRemoteProjectSessions: () => state.remoteSessions,
+}));
+vi.mock('@/lib/orcaSessionIdentity', () => ({
+ resolveSessionRoute: async (id: string) => `/cc-agent/${id}`,
+}));
+afterEach(() => {
+ cleanup();
+ state.navigate.mockReset();
+ state.remoteSessions = [];
+});
+
+function task(deviceId: string, sessionId: string, title = sessionId): UsageHistoryTask {
+ return {
+ taskKey: `${deviceId}:${sessionId}`,
+ deviceId,
+ sessionId,
+ title,
+ model: 'gpt-5.5',
+ providerId: null,
+ contextTokens: 0,
+ contextWindow: 0,
+ lastActiveAt: 1,
+ };
+}
+
+function history(
+ taskDaily: UsageHistoryPayload['taskDaily'],
+ tasks: UsageHistoryTask[],
+): UsageHistoryPayload {
+ return { todayKey: '2026-09-26', taskDaily, tasks } as UsageHistoryPayload;
+}
+
+describe('buildUsageTaskRows', () => {
+ const payload = history(
+ [
+ { day: '2026-09-26', taskKey: 'local:a', tokens: 100 },
+ { day: '2026-09-10', taskKey: 'local:a', tokens: 900 },
+ { day: '2026-09-26', taskKey: 'laptop:b', tokens: 300 },
+ { day: '2026-09-25', taskKey: 'local:b', tokens: 50 },
+ ],
+ [task('local', 'a'), task('laptop', 'b'), task('local', 'b')],
+ );
+
+ it('sums only the tokens inside the selected range and ranks by them', () => {
+ expect(buildUsageTaskRows(payload, 'today').map((r) => [r.taskKey, r.tokens])).toEqual([
+ ['laptop:b', 300],
+ ['local:a', 100],
+ ]);
+ expect(buildUsageTaskRows(payload, '30d').map((r) => [r.taskKey, r.tokens])).toEqual([
+ ['local:a', 1000],
+ ['laptop:b', 300],
+ ['local:b', 50],
+ ]);
+ expect(buildUsageTaskRows(payload, 'day:2026-09-25').map((r) => r.taskKey)).toEqual([
+ 'local:b',
+ ]);
+ });
+
+ it('keeps the same session id on two devices as separate tasks', () => {
+ expect(buildUsageTaskRows(payload, 'all').map((r) => r.taskKey)).toContain('local:b');
+ expect(buildUsageTaskRows(payload, 'all').map((r) => r.taskKey)).toContain('laptop:b');
+ });
+
+ it('reports the coverage start only when the range reaches before the first record', () => {
+ expect(usageTaskCoverageStart(payload, 'all')).toBe('2026-09-10');
+ expect(usageTaskCoverageStart(payload, '30d')).toBe('2026-09-10');
+ expect(usageTaskCoverageStart(payload, '7d')).toBeNull();
+ });
+});
+
+describe('UsageTaskTable navigation', () => {
+ it('opens local tasks and reachable remote tasks, and leaves unreachable remote tasks inert', async () => {
+ state.remoteSessions = [
+ { id: 'remote-ok', deviceLinkDeviceId: 'laptop', deviceLinkConnectionStatus: 'connected' },
+ // 断线后保留的快照、以及另一台电脑上的同名任务都不可点击。
+ {
+ id: 'remote-offline',
+ deviceLinkDeviceId: 'laptop',
+ deviceLinkConnectionStatus: 'disconnected',
+ },
+ {
+ id: 'other-device',
+ deviceLinkDeviceId: 'desktop',
+ deviceLinkConnectionStatus: 'connected',
+ },
+ ];
+ const rows = [
+ { ...task('local', 'mine', 'Mine'), tokens: 3 },
+ { ...task('laptop', 'remote-ok', 'Reachable'), tokens: 2 },
+ { ...task('laptop', 'remote-gone', 'Unreachable'), tokens: 1 },
+ { ...task('laptop', 'remote-offline', 'Offline'), tokens: 1 },
+ { ...task('laptop', 'other-device', 'Elsewhere'), tokens: 1 },
+ ];
+ const view = render(
+ <MemoryRouter>
+ <UsageTaskTable
+ rows={rows}
+ rangeLabel="30d"
+ devices={[
+ {
+ deviceId: 'laptop',
+ name: 'Laptop',
+ platform: null,
+ isSelf: false,
+ syncedAt: 1,
+ status: 'ok',
+ },
+ ]}
+ />
+ </MemoryRouter>,
+ );
+ fireEvent.click(view.getByRole('link', { name: 'Mine' }));
+ await waitFor(() => expect(state.navigate).toHaveBeenLastCalledWith('/cc-agent/mine'));
+
+ fireEvent.click(view.container.querySelector('tr[data-task-key="laptop:remote-ok"]')!);
+ await waitFor(() => expect(state.navigate).toHaveBeenLastCalledWith('/cc-agent/remote-ok'));
+ expect(view.getAllByText('Laptop')).toHaveLength(4);
+
+ expect(view.queryByRole('link', { name: 'Unreachable' })).toBeNull();
+ expect(view.queryByRole('link', { name: 'Offline' })).toBeNull();
+ expect(view.queryByRole('link', { name: 'Elsewhere' })).toBeNull();
+ fireEvent.click(view.container.querySelector('tr[data-task-key="laptop:remote-gone"]')!);
+ expect(state.navigate).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useUsageHistoryPeerRefresh.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/useUsageHistoryPeerRefresh.test.tsx
new file mode 100644
index 0000000000..ea1f2d2929
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/__tests__/useUsageHistoryPeerRefresh.test.tsx
@@ -0,0 +1,115 @@
+// @vitest-environment jsdom
+import { act, cleanup, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { emitPatch } from '@/lib/sessionsBus';
+
+import { useUsageHistory } from '../useUsageHistory';
+
+const money = {
+ amount: 0,
+ currency: 'USD' as const,
+ approximate: false,
+ kind: 'actual-cost' as const,
+};
+const payload = {
+ generatedAt: 1,
+ todayKey: '2026-09-26',
+ days: [],
+ modelDaily: [],
+ models: [],
+ streak: { current: 0, longest: 0 },
+ totals: {
+ today: money,
+ last30Days: money,
+ last30DaysWithEstimatedValue: money,
+ last30DaysEstimatedValue: money,
+ todayTokens: 0,
+ last30DaysTokens: 0,
+ },
+ anomaly: { isAnomalous: false, trailing7DayAvg: null },
+};
+
+const getHistory = vi.fn<
+ (opts?: { device?: string; includeTasks?: boolean }) => Promise<typeof payload>
+>(async () => payload);
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ getHistory.mockClear();
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ maker: {
+ usage: {
+ getHistory,
+ onTodaySpendChanged: () => () => {},
+ onTodayTokensChanged: () => () => {},
+ onModelPricingChanged: () => () => {},
+ },
+ },
+ };
+});
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+const callsFor = (device: string | undefined) =>
+ getHistory.mock.calls.filter(([opts]) => opts?.device === device).length;
+
+describe('useUsageHistory peer refresh', () => {
+ it('re-reads a multi-device scope periodically while mounted and stops on unmount', async () => {
+ const view = renderHook(() => useUsageHistory({ userId: 'peer-refresh', device: 'all' }));
+ await act(async () => {});
+ expect(callsFor('all')).toBe(1);
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(60_000);
+ });
+ expect(callsFor('all')).toBe(2);
+
+ view.unmount();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(120_000);
+ });
+ expect(callsFor('all')).toBe(2);
+ });
+
+ it('does not poll the local-only scope', async () => {
+ renderHook(() => useUsageHistory({ userId: 'peer-refresh-local' }));
+ await act(async () => {});
+ const initial = callsFor(undefined);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(180_000);
+ });
+ expect(callsFor(undefined)).toBe(initial);
+ });
+
+ it('re-reads when a task is renamed or deleted, but not on unrelated session patches', async () => {
+ renderHook(() => useUsageHistory({ userId: 'task-meta-refresh', device: 'all' }));
+ await act(async () => {});
+ const initial = callsFor('all');
+
+ emitPatch('s1', { pinned: true } as never);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5_000);
+ });
+ expect(callsFor('all')).toBe(initial);
+
+ emitPatch('s1', { title: 'Renamed' });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5_000);
+ });
+ expect(callsFor('all')).toBe(initial + 1);
+ });
+
+ it('requests task data only for callers that opt in', async () => {
+ renderHook(() => useUsageHistory({ userId: 'tasks-default' }));
+ renderHook(() => useUsageHistory({ userId: 'tasks-opt-in', includeTasks: true }));
+ await act(async () => {});
+ expect(getHistory.mock.calls.map(([opts]) => opts?.includeTasks === true)).toEqual([
+ false,
+ true,
+ ]);
+ });
+});
diff --git a/apps/desktop/src/renderer/hooks/useUsageHistory.ts b/apps/desktop/src/renderer/hooks/useUsageHistory.ts
index 85abf9953d..663486e53d 100644
--- a/apps/desktop/src/renderer/hooks/useUsageHistory.ts
+++ b/apps/desktop/src/renderer/hooks/useUsageHistory.ts
@@ -29,6 +29,9 @@ import {
zeroUsageMoney,
type RegionalMoney,
} from '../../shared/regionalMoney';
+import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';
+import type { Session } from '@/lib/ccAgent.types';
+import { onPatch as onSessionPatch } from '@/lib/sessionsBus';
export interface UsageHistoryModel {
agentKind: 'claude-code' | 'codex' | 'pi';
@@ -56,6 +59,26 @@ export interface UsageHistoryModelDay {
cacheCreateTokens?: number;
}
+/** 参与用量合并的电脑 (main 侧 peerUsageSync 的 UsageDeviceSummary 投影)。 */
+export interface UsageHistoryDevice {
+ deviceId: string;
+ name: string;
+ platform: string | null;
+ isSelf: boolean;
+ /** 最近一次成功读取该设备的时间; 本机与从未读到的设备为 null。 */
+ syncedAt: number | null;
+ status: 'ok' | 'syncing' | 'offline' | 'remote-disabled' | 'unsupported' | 'error';
+}
+
+const DEVICE_STATUSES = new Set<UsageHistoryDevice['status']>([
+ 'ok',
+ 'syncing',
+ 'offline',
+ 'remote-disabled',
+ 'unsupported',
+ 'error',
+]);
+
export interface UsageHistoryPayload {
generatedAt: number;
todayKey: string;
@@ -76,12 +99,38 @@ export interface UsageHistoryPayload {
last30DaysTokens: number;
};
anomaly: { isAnomalous: boolean; trailing7DayAvg: RegionalMoney | null };
+ /** 多设备范围才有: 参与合并的电脑 (含本机)。 */
+ devices?: UsageHistoryDevice[];
+ /** true = main 正在从其它电脑读取。 */
+ devicesSyncing?: boolean;
+ /** 每日 × 任务 token(「最耗 token 的任务」按范围统计)。taskKey = `${deviceId}:${sessionId}`。 */
+ taskDaily?: Array<{ day: string; taskKey: string; tokens: number }>;
+ /** taskDaily 涉及任务的元数据;deviceId 为 'local' 表示本机任务。 */
+ tasks?: UsageHistoryTask[];
+}
+
+export interface UsageHistoryTask {
+ taskKey: string;
+ deviceId: string;
+ sessionId: string;
+ title: string;
+ model: string;
+ providerId: string | null;
+ contextTokens: number;
+ contextWindow: number;
+ /** unix ms */
+ lastActiveAt: number;
}
/** 热力图窗口: 20 周 = 140 天。 */
const HISTORY_WINDOW_DAYS = 140;
const MODEL_WINDOW_DAYS = 30;
const REFRESH_DEBOUNCE_MS = 2000;
+/**
+ * 多设备范围的定时重读间隔。其它电脑产生的用量没有推送到本机, 页面开着时靠它定期
+ * 触发 main 侧 (同样按 60s 节流的) 跨设备同步; 只看本机时不启用。
+ */
+const PEER_REFRESH_INTERVAL_MS = 60_000;
/** 价格表冷启动未就绪时的补拉延迟 (对齐 main 侧 5s fetch 超时 + 余量)。 */
const PRICING_RETRY_DELAY_MS = 6000;
/** main 返回 stale 磁盘快照时的补拉延迟: 让后台聚合先完成, 同时保持更新感知。 */
@@ -144,6 +193,7 @@ interface StoredUsageHistoryPayload {
streak?: unknown;
totals?: unknown;
anomaly?: unknown;
+ devices?: unknown;
}
function finiteNumber(value: unknown, fallback = 0): number {
@@ -154,6 +204,32 @@ function isAgentKind(value: unknown): value is UsageHistoryModel['agentKind'] {
return value === 'claude-code' || value === 'codex' || value === 'pi';
}
+function parseDevices(value: unknown): UsageHistoryDevice[] | undefined {
+ if (!Array.isArray(value)) return undefined;
+ const devices: UsageHistoryDevice[] = [];
+ for (const raw of value as Array<Record<string, unknown> | null>) {
+ if (!raw || typeof raw.deviceId !== 'string' || typeof raw.name !== 'string') continue;
+ const status = raw.status as UsageHistoryDevice['status'];
+ devices.push({
+ deviceId: raw.deviceId,
+ name: raw.name,
+ platform: typeof raw.platform === 'string' ? raw.platform : null,
+ isSelf: raw.isSelf === true,
+ // 快照可能损坏:超出 Date 范围的时间格式化时会抛错,按未同步处理。
+ syncedAt:
+ typeof raw.syncedAt === 'number' &&
+ Number.isFinite(raw.syncedAt) &&
+ raw.syncedAt > 0 &&
+ raw.syncedAt <= 8.64e15
+ ? raw.syncedAt
+ : null,
+ // 快照里的「读取中」没有意义: 下次打开会重新同步, 先按离线展示缓存时间。
+ status: DEVICE_STATUSES.has(status) && status !== 'syncing' ? status : 'offline',
+ });
+ }
+ return devices;
+}
+
function readSnapshot(scopeKey: string): UsageHistoryPayload | null {
try {
localStorage.removeItem(
@@ -270,7 +346,9 @@ function readSnapshot(scopeKey: string): UsageHistoryPayload | null {
: normalizeRegionalMoney(anomaly.trailing7DayAvg) ??
legacyActual(anomaly.trailing7DayAvg);
+ const devices = parseDevices(parsed.devices);
return {
+ ...(devices ? { devices } : {}),
generatedAt: finiteNumber(parsed.generatedAt, Date.now()),
todayKey: typeof parsed.todayKey === 'string' ? parsed.todayKey : '',
stale: parsed.stale === true,
@@ -324,11 +402,17 @@ interface UsageHistoryScopeState {
listeners: Set<(p: UsageHistoryPayload | null) => void>;
statusListeners: Set<(refreshing: boolean) => void>;
refreshing: boolean;
- request: {
- days: number | 'all';
- modelDays: number | 'all';
- allowPendingEstimates: boolean;
- };
+ request: UsageHistoryRequest;
+}
+
+interface UsageHistoryRequest {
+ days: number | 'all';
+ modelDays: number | 'all';
+ allowPendingEstimates: boolean;
+ /** 'local' / 'all' / 其它电脑的 deviceId。 */
+ device: string;
+ /** 附带「最耗 token 的任务」数据。 */
+ includeTasks: boolean;
}
const scopes = new Map<string, UsageHistoryScopeState>();
@@ -339,14 +423,12 @@ function normalizeScopeKey(userId?: string | null): string {
function getScope(
scopeKey: string,
- request: {
- days: number | 'all';
- modelDays: number | 'all';
- allowPendingEstimates: boolean;
- } = {
+ request: UsageHistoryRequest = {
days: HISTORY_WINDOW_DAYS,
modelDays: MODEL_WINDOW_DAYS,
allowPendingEstimates: false,
+ device: 'local',
+ includeTasks: false,
},
): UsageHistoryScopeState {
let state = scopes.get(scopeKey);
@@ -406,6 +488,8 @@ async function load(scopeKey: string, opts?: { forceRefresh?: boolean; resetPric
.getHistory({
days: scope.request.days,
modelDays: scope.request.modelDays,
+ ...(scope.request.device === 'local' ? {} : { device: scope.request.device }),
+ ...(scope.request.includeTasks ? { includeTasks: true } : {}),
...(opts?.forceRefresh ? { forceRefresh: true } : {}),
})
.then((res) => {
@@ -469,6 +553,9 @@ async function load(scopeKey: string, opts?: { forceRefresh?: boolean; resetPric
return scope.inflight;
}
+/** 影响「最耗 token 的任务」展示的任务字段。 */
+const TASK_META_KEYS = ['title', 'status', 'model', 'providerId'] as const;
+
export type UsageHistoryWindow = number | 'all';
function normalizeWindow(value: UsageHistoryWindow | undefined, fallback: number): number | 'all' {
@@ -476,22 +563,20 @@ function normalizeWindow(value: UsageHistoryWindow | undefined, fallback: number
return Math.min(366, Math.max(1, Math.floor(value ?? fallback)));
}
-function scopeKeyForRequest(
- scopeKey: string,
- request: {
- days: number | 'all';
- modelDays: number | 'all';
- allowPendingEstimates: boolean;
- },
-): string {
+function scopeKeyForRequest(scopeKey: string, request: UsageHistoryRequest): string {
if (
request.days === HISTORY_WINDOW_DAYS &&
request.modelDays === MODEL_WINDOW_DAYS &&
- !request.allowPendingEstimates
+ !request.allowPendingEstimates &&
+ request.device === 'local' &&
+ !request.includeTasks
) {
return scopeKey;
}
- return `${scopeKey}|days=${request.days}|modelDays=${request.modelDays}|allowPendingEstimates=${request.allowPendingEstimates ? 1 : 0}`;
+ // 'local' 沿用旧 key, 升级后已有的本机快照照常 hydrate。
+ const deviceSuffix = request.device === 'local' ? '' : `|device=${encodeURIComponent(request.device)}`;
+ const taskSuffix = request.includeTasks ? '|tasks=1' : '';
+ return `${scopeKey}|days=${request.days}|modelDays=${request.modelDays}|allowPendingEstimates=${request.allowPendingEstimates ? 1 : 0}${deviceSuffix}${taskSuffix}`;
}
export function useUsageHistory(opts?: {
@@ -501,16 +586,22 @@ export function useUsageHistory(opts?: {
modelDays?: UsageHistoryWindow;
/** Token-only consumers may render the payload while prices finish loading. */
allowPendingEstimates?: boolean;
+ /** 'local' (默认, 只看本机) / 'all' (所有设备合并) / 其它电脑的 deviceId。 */
+ device?: string;
+ /** 附带「最耗 token 的任务」数据;只有设置 → 用量历史需要(首页看板不读)。 */
+ includeTasks?: boolean;
}): {
history: UsageHistoryPayload | null;
refreshing: boolean;
} {
const paused = opts?.paused ?? false;
const scopeKey = normalizeScopeKey(opts?.userId);
- const request = {
+ const request: UsageHistoryRequest = {
days: normalizeWindow(opts?.days, HISTORY_WINDOW_DAYS),
modelDays: normalizeWindow(opts?.modelDays, MODEL_WINDOW_DAYS),
allowPendingEstimates: opts?.allowPendingEstimates ?? false,
+ device: opts?.device || 'local',
+ includeTasks: opts?.includeTasks ?? false,
};
const scopedKey = scopeKeyForRequest(scopeKey, request);
const scope = getScope(scopedKey, request);
@@ -560,15 +651,40 @@ export function useUsageHistory(opts?: {
const offSpend = window.electronAPI.maker.usage.onTodaySpendChanged(scheduleRefresh);
const offTokens = window.electronAPI.maker.usage.onTodayTokensChanged(scheduleRefresh);
const offPricing = window.electronAPI.maker.usage.onModelPricingChanged(scheduleRefresh);
+ // 任务的标题 / 删除等元数据变化不产生用量:只需重读,Main 在出口按当前库覆盖本机任务
+ // 元数据,不强制重聚合。
+ let metaTimer: ReturnType<typeof setTimeout> | null = null;
+ const onTaskMetaPatch = (_sessionId: string, patch: Partial<Session>) => {
+ if (!TASK_META_KEYS.some((key) => key in patch)) return;
+ if (metaTimer) clearTimeout(metaTimer);
+ metaTimer = setTimeout(() => {
+ metaTimer = null;
+ void load(scopedKey);
+ }, REFRESH_DEBOUNCE_MS);
+ };
+ const offLocalPatch = onSessionPatch(onTaskMetaPatch);
+ const offPushPatch = window.electronAPI.localDb?.sessionsPush?.onPatched(
+ ({ sessionId, patch }, stamp) => {
+ if (isDataOwnerPushCurrent(stamp)) onTaskMetaPatch(sessionId, patch);
+ },
+ );
+ const peerTimer =
+ request.device === 'local'
+ ? null
+ : setInterval(() => void load(scopedKey), PEER_REFRESH_INTERVAL_MS);
return () => {
activeScope.listeners.delete(setScopedHistory);
activeScope.statusListeners.delete(setIsRefreshing);
deactivateScopeIfUnused(activeScope);
if (timer) clearTimeout(timer);
+ if (metaTimer) clearTimeout(metaTimer);
+ offLocalPatch();
+ offPushPatch?.();
offSpend();
offTokens();
offPricing();
+ if (peerTimer) clearInterval(peerTimer);
};
}, [paused, scopedKey]);
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 9a8d168616..0e737077c5 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -6516,7 +6516,7 @@
}
},
"usageHistory": {
- "description": "Token usage produced inside Cindy on this device. Records start accumulating when the feature ships; earlier history is not backfilled.",
+ "description": "Token usage produced inside Cindy across your computers, combined by default; you can also view one device at a time. Other computers must be online and allow remote control to be read; when one can't be reached, its last-read data is used. Records start accumulating when the feature ships; earlier history is not backfilled.",
"empty": "No usage recorded yet. This fills in once you start a chat.",
"loadFailed": "Unable to load usage history. Reopen Settings to try again.",
"range": {
@@ -6528,6 +6528,24 @@
"7d": "Last 7 days",
"today": "Today"
},
+ "device": {
+ "label": "Device",
+ "ariaLabel": "Filter usage by device",
+ "all": "All devices",
+ "self": "This device",
+ "selfNamed": "This device ({{name}})",
+ "loading": "Loading usage from your other devices…",
+ "status": {
+ "syncing": "Reading…",
+ "syncedAt": "Data as of {{time}}",
+ "offline": "Offline",
+ "remoteDisabled": "Remote control not allowed",
+ "unsupported": "Needs a Cindy update",
+ "error": "Couldn't read",
+ "noData": "No data yet"
+ },
+ "partial": "Some computers couldn't be read just now, so totals may be low. Check each device's status in the device list."
+ },
"cacheHitTooltip": "Cache read / (input + cache read + cache write) — the same formula as the message card.",
"summary": {
"title": "Overview"
@@ -6581,7 +6599,8 @@
},
"tasks": {
"title": "Top sessions by tokens",
- "subtitle": "Sessions active in {{range}}, ranked by lifetime tokens",
+ "subtitle": "Sessions with the most tokens in {{range}}",
+ "coverage": "Daily tracking since {{date}}",
"col": {
"task": "Session",
"model": "Model",
@@ -6591,7 +6610,7 @@
"lastActive": "Last active"
},
"providerTooltip": "The provider currently selected for the session; blank when none is pinned.",
- "tokensTooltip": "The session's lifetime total; {{range}} only filters active sessions and is not an incremental total."
+ "tokensTooltip": "Counts only the tokens this session used in {{range}}."
}
},
"usageDashboard": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index f9f8602422..c03582817a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -6514,7 +6514,7 @@
}
},
"usageHistory": {
- "description": "このデバイスの Cindy 内で発生したトークン使用量です。記録は機能の提供開始時から蓄積され、それ以前の履歴は補完されません。",
+ "description": "お使いの各コンピュータの Cindy 内で発生したトークン使用量です。既定では合算して表示し、1 台ずつ表示することもできます。ほかのコンピュータはオンラインでリモート操作を許可している場合に読み取れます。読み取れないときは前回読み取ったデータを使います。記録は機能の提供開始時から蓄積され、それ以前の履歴は補完されません。",
"empty": "まだ使用記録がありません。会話を実行すると蓄積が始まります。",
"loadFailed": "使用履歴を読み込めませんでした。設定を開き直して、もう一度お試しください。",
"range": {
@@ -6526,6 +6526,24 @@
"7d": "直近 7 日",
"today": "今日"
},
+ "device": {
+ "label": "デバイス",
+ "ariaLabel": "使用量のデバイスを絞り込む",
+ "all": "すべてのデバイス",
+ "self": "このデバイス",
+ "selfNamed": "このデバイス({{name}})",
+ "loading": "ほかのデバイスの使用量を読み込み中…",
+ "status": {
+ "syncing": "読み取り中…",
+ "syncedAt": "{{time}} 時点のデータ",
+ "offline": "オフライン",
+ "remoteDisabled": "リモート操作が許可されていません",
+ "unsupported": "Cindy の更新が必要です",
+ "error": "読み取りに失敗しました",
+ "noData": "データなし"
+ },
+ "partial": "一部のコンピュータの最新使用量を読み取れなかったため、合計が少なく表示されている可能性があります。デバイス一覧で各台の状態を確認できます。"
+ },
"cacheHitTooltip": "キャッシュ読取 ÷(入力 + キャッシュ読取 + キャッシュ書込)。メッセージカードと同じ基準です。",
"summary": {
"title": "概要"
@@ -6579,7 +6597,8 @@
},
"tasks": {
"title": "トークン消費の多いセッション",
- "subtitle": "{{range}}に稼働したセッションを累計トークン順に表示",
+ "subtitle": "{{range}}にトークンを最も消費したセッション",
+ "coverage": "日別集計は {{date}} から",
"col": {
"task": "セッション",
"model": "モデル",
@@ -6589,7 +6608,7 @@
"lastActive": "最終アクティブ"
},
"providerTooltip": "セッションで現在選択されているプロバイダー。未指定の場合は空欄です。",
- "tokensTooltip": "セッションの累計値です。{{range}}はアクティブなセッションの絞り込みにのみ使われ、期間内の増分ではありません。"
+ "tokensTooltip": "このセッションが{{range}}に使用したトークンのみを集計します。"
}
},
"usageDashboard": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 85a4e7060f..376e366988 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -6514,7 +6514,7 @@
}
},
"usageHistory": {
- "description": "이 기기의 Cindy 내부에서 발생한 토큰 사용량입니다. 기능 출시 시점부터 기록이 쌓이며 이전 기록은 채워지지 않습니다.",
+ "description": "내 여러 컴퓨터의 Cindy 내부에서 발생한 토큰 사용량입니다. 기본적으로 합산해 표시하며 한 대씩 볼 수도 있습니다. 다른 컴퓨터는 온라인 상태이고 원격 제어를 허용해야 읽을 수 있으며, 읽지 못할 때는 마지막으로 읽은 데이터를 사용합니다. 기능 출시 시점부터 기록이 쌓이며 이전 기록은 채워지지 않습니다.",
"empty": "아직 사용 기록이 없습니다. 대화를 실행하면 쌓이기 시작합니다.",
"loadFailed": "사용량 기록을 불러오지 못했습니다. 설정을 다시 열어 재시도해 주세요.",
"range": {
@@ -6526,6 +6526,24 @@
"7d": "최근 7일",
"today": "오늘"
},
+ "device": {
+ "label": "기기",
+ "ariaLabel": "사용량 기기 필터",
+ "all": "모든 기기",
+ "self": "이 기기",
+ "selfNamed": "이 기기 ({{name}})",
+ "loading": "다른 기기의 사용량을 불러오는 중…",
+ "status": {
+ "syncing": "읽는 중…",
+ "syncedAt": "{{time}} 기준 데이터",
+ "offline": "오프라인",
+ "remoteDisabled": "원격 제어가 허용되지 않음",
+ "unsupported": "Cindy 업데이트 필요",
+ "error": "읽기 실패",
+ "noData": "데이터 없음"
+ },
+ "partial": "일부 컴퓨터의 최신 사용량을 읽지 못해 합계가 적게 표시될 수 있습니다. 기기 목록에서 각 기기의 상태를 확인하세요."
+ },
"cacheHitTooltip": "캐시 읽기 ÷ (입력 + 캐시 읽기 + 캐시 쓰기) — 메시지 카드와 동일한 기준입니다.",
"summary": {
"title": "개요"
@@ -6579,7 +6597,8 @@
},
"tasks": {
"title": "토큰 사용이 많은 세션",
- "subtitle": "{{range}} 동안 활동한 세션을 누적 토큰 순으로 정렬",
+ "subtitle": "{{range}} 동안 토큰을 가장 많이 사용한 세션",
+ "coverage": "일별 집계는 {{date}}부터",
"col": {
"task": "세션",
"model": "모델",
@@ -6589,7 +6608,7 @@
"lastActive": "마지막 활동"
},
"providerTooltip": "세션에 현재 선택된 제공자입니다. 지정하지 않은 경우 비워 둡니다.",
- "tokensTooltip": "해당 세션의 누적 값입니다. {{range}}은(는) 활성 세션을 필터링하는 데만 사용되며 해당 기간의 증가분이 아닙니다."
+ "tokensTooltip": "이 세션이 {{range}} 동안 사용한 토큰만 집계합니다."
}
},
"usageDashboard": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 431dd4a1fc..73ce60d07d 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -6514,7 +6514,7 @@
}
},
"usageHistory": {
- "description": "这台设备上 Cindy 内部产生的 token 用量。记录从该功能上线起积累,不回填更早的历史。",
+ "description": "你各台电脑上 Cindy 内部产生的 token 用量,默认合并显示,也可以只看某一台。其它电脑需要在线并允许远程控制才能读取,暂时读不到时沿用上次读到的数据。记录从该功能上线起积累,不回填更早的历史。",
"empty": "还没有用量记录。跑过对话之后,这里会开始积累。",
"loadFailed": "无法加载用量历史。请重新打开设置后重试。",
"range": {
@@ -6526,6 +6526,24 @@
"7d": "最近 7 天",
"today": "今天"
},
+ "device": {
+ "label": "设备",
+ "ariaLabel": "筛选用量所属设备",
+ "all": "所有设备",
+ "self": "本机",
+ "selfNamed": "本机({{name}})",
+ "loading": "正在读取其它设备的用量…",
+ "status": {
+ "syncing": "正在读取…",
+ "syncedAt": "数据截至 {{time}}",
+ "offline": "离线",
+ "remoteDisabled": "未允许远程控制",
+ "unsupported": "需要更新 Cindy",
+ "error": "读取失败",
+ "noData": "暂无数据"
+ },
+ "partial": "部分电脑暂时读不到最新用量,合计可能偏少。可在设备列表中查看各台状态。"
+ },
"cacheHitTooltip": "缓存读取 ÷(输入 + 缓存读取 + 缓存写入),与消息卡片同口径。",
"summary": {
"title": "概览"
@@ -6579,7 +6597,8 @@
},
"tasks": {
"title": "最耗 token 的任务",
- "subtitle": "{{range}}内活跃过的任务,按累计 token 排序",
+ "subtitle": "{{range}}内消耗 token 最多的任务",
+ "coverage": "按天统计从 {{date}} 起",
"col": {
"task": "任务",
"model": "模型",
@@ -6589,7 +6608,7 @@
"lastActive": "最后活跃"
},
"providerTooltip": "取该任务当前选定的供应商;未指定时留空。",
- "tokensTooltip": "该任务的生命周期累计;{{range}}仅用于筛选活跃任务,不表示该范围内的增量。"
+ "tokensTooltip": "只统计该任务在{{range}}内产生的 token。"
}
},
"usageDashboard": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 0440eac0b1..2b9eef91ba 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -6514,7 +6514,7 @@
}
},
"usageHistory": {
- "description": "這台裝置上 Cindy 內部產生的 token 用量。紀錄從該功能上線起累積,不回填更早的歷史。",
+ "description": "你各台電腦上 Cindy 內部產生的 token 用量,預設合併顯示,也可以只看某一台。其他電腦需要在線並允許遠端控制才能讀取,暫時讀不到時沿用上次讀到的資料。紀錄從該功能上線起累積,不回填更早的歷史。",
"empty": "還沒有用量紀錄。跑過對話之後,這裡會開始累積。",
"loadFailed": "無法載入用量歷史。請重新開啟設定後再試一次。",
"range": {
@@ -6526,6 +6526,24 @@
"7d": "最近 7 天",
"today": "今天"
},
+ "device": {
+ "label": "裝置",
+ "ariaLabel": "篩選用量所屬裝置",
+ "all": "所有裝置",
+ "self": "本機",
+ "selfNamed": "本機({{name}})",
+ "loading": "正在讀取其他裝置的用量…",
+ "status": {
+ "syncing": "正在讀取…",
+ "syncedAt": "資料截至 {{time}}",
+ "offline": "離線",
+ "remoteDisabled": "未允許遠端控制",
+ "unsupported": "需要更新 Cindy",
+ "error": "讀取失敗",
+ "noData": "暫無資料"
+ },
+ "partial": "部分電腦暫時讀不到最新用量,合計可能偏少。可在裝置清單中查看各台狀態。"
+ },
"cacheHitTooltip": "快取讀取 ÷(輸入 + 快取讀取 + 快取寫入),與訊息卡片同口徑。",
"summary": {
"title": "概覽"
@@ -6579,7 +6597,8 @@
},
"tasks": {
"title": "最耗 token 的任務",
- "subtitle": "{{range}}內活躍過的任務,按累計 token 排序",
+ "subtitle": "{{range}}內消耗 token 最多的任務",
+ "coverage": "按天統計從 {{date}} 起",
"col": {
"task": "任務",
"model": "模型",
@@ -6589,7 +6608,7 @@
"lastActive": "最後活躍"
},
"providerTooltip": "取該任務目前選定的供應商;未指定時留空。",
- "tokensTooltip": "該任務的生命週期累計;{{range}}僅用於篩選活躍任務,不代表該範圍內的增量。"
+ "tokensTooltip": "只統計該任務在{{range}}內產生的 token。"
}
},
"usageDashboard": {
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 4c23ebf3d0..f21c6f4e98 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -6671,6 +6671,10 @@ interface ElectronAPI {
getHistory: (opts?: {
days?: number | 'all';
modelDays?: number | 'all';
+ /** 'local' (默认) / 'all' (所有设备合并) / 其它电脑的 deviceId。 */
+ device?: string;
+ /** 附带「最耗 token 的任务」数据;只有设置 → 用量历史需要。 */
+ includeTasks?: boolean;
forceRefresh?: boolean;
}) => Promise<import('../main/usage/usageHistory').UsageHistoryPayload>;
onTodaySpendChanged: (
diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.md
index 53fd2c32bf..47a47dd8b5 100644
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@ -38,7 +38,7 @@
| `desktop.overlay.toast` | desktop | Toast | App 常驻 ToastContainer(用户可见出口,不展开业务逻辑) | Toast, ToastContainer | apps/desktop/src/renderer/components/ui/toast/Toast.tsx, apps/desktop/src/renderer/components/ui/toast/ToastContainer.tsx, apps/desktop/src/renderer/components/ui/toast/index.ts | 5 | 4 | 3 |
| `desktop.plugins.app-main` | desktop | 插件主视图 | hash `/apps/:ghostId`(GhostMainViewFeatureLayout) | GhostMainViewFeatureLayout, GhostMainViewHost | apps/desktop/src/renderer/features/plugin/GhostMainViewFeatureLayout.tsx, apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx | 0 | 0 | 0 |
| `desktop.plugins.installed` | desktop | 已装插件 | hash `/plugins`(GhostPluginPage) | AddMarketplaceDialog, GhostPluginDetailView, GhostPluginPage, MarketPluginDetailView, MyPublishesSection, PluginManagementLayout, PluginScopePicker, UpdateAllDialog | apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx, apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx, apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx, apps/desktop/src/renderer/features/plugin/plugin-motion.css | 31 | 0 | 59 |
-| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BillingSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CindyMakeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DialogueDirectorySection.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GeneralSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.settings-search.ts, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HarnessVersionMenuRow.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.settings-search.ts, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/PersonalizationDetails.settings-search.ts, apps/desktop/src/renderer/components/settings/PersonalizationSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/PiKernelVersionRow.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderImportDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.settings-search.ts, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.settings-search.ts, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchBox.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchNavigation.ts, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.settings-search.ts, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.settings-search.ts, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.settings-search.ts, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/cindyMakeVisibility.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dialogueDirectoryDisplay.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/modelManagementPresentation.ts, apps/desktop/src/renderer/components/settings/modelManagementState.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/settingsSearchCatalog.ts, apps/desktop/src/renderer/components/settings/settingsSearchTypes.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.settings-search.ts, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageCharts.css, apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/useProviderSubscriptionCard.ts, apps/desktop/src/renderer/components/settings/useSettingsSectionTarget.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 138 | 109 | 549 |
+| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BillingSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CindyMakeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DialogueDirectorySection.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GeneralSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.settings-search.ts, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HarnessVersionMenuRow.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.settings-search.ts, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/PersonalizationDetails.settings-search.ts, apps/desktop/src/renderer/components/settings/PersonalizationSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/PiKernelVersionRow.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderImportDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.settings-search.ts, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.settings-search.ts, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchBox.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchNavigation.ts, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.settings-search.ts, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.settings-search.ts, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.settings-search.ts, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/cindyMakeVisibility.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dialogueDirectoryDisplay.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/modelManagementPresentation.ts, apps/desktop/src/renderer/components/settings/modelManagementState.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/settingsSearchCatalog.ts, apps/desktop/src/renderer/components/settings/settingsSearchTypes.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageDeviceSelect.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.settings-search.ts, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageCharts.css, apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/useProviderSubscriptionCard.ts, apps/desktop/src/renderer/components/settings/useSettingsSectionTarget.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 138 | 109 | 553 |
| `desktop.shell.main-layout` | desktop | 主窗口壳(标题栏 / 左右栏 / 内容区) | main BrowserWindow → renderer/index.tsx → main-entry.tsx → App → MainLayout (`#/` 受保护壳) | ChromeActions, DeviceSectionHeader, FeishuConflictDialogHost, GhostMediaLightboxHost, MainLayout, ProjectsSection, RightSidebar, RightSidebarShell, SessionShareImportWizard, Sidebar, UpdateNoticeDialog, WindowControls | apps/desktop/src/renderer/cindy-brain/GhostMediaLightboxHost.tsx, apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx, apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx, apps/desktop/src/renderer/components/layout/BrowserWebviewPool.tsx, apps/desktop/src/renderer/components/layout/ChromeActions.tsx, apps/desktop/src/renderer/components/layout/ContentHeader.tsx, apps/desktop/src/renderer/components/layout/CredentialStoreBanner.tsx, apps/desktop/src/renderer/components/layout/FadeSwitcher.tsx, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx, apps/desktop/src/renderer/components/layout/MainEntryRedirect.tsx, apps/desktop/src/renderer/components/layout/MainLayout.tsx, apps/desktop/src/renderer/components/layout/RightSidebar.tsx, apps/desktop/src/renderer/components/layout/RightSidebarDetach.tsx, apps/desktop/src/renderer/components/layout/RightSidebarMaximize.tsx, apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/components/layout/chromeActionsGeometry.ts, apps/desktop/src/renderer/components/layout/chromeActionsLayout.ts, apps/desktop/src/renderer/components/layout/railChromeActions.ts, apps/desktop/src/renderer/components/layout/windowDrag.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx, apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx, apps/desktop/src/renderer/components/sidebar/DatabaseSizeWarningBanner.tsx, apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx, apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx, apps/desktop/src/renderer/components/sidebar/Sidebar.tsx, apps/desktop/src/renderer/components/sidebar/SidebarIconButton.tsx, apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx, apps/desktop/src/renderer/components/sidebar/SortableList.tsx, apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx, apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx, apps/desktop/src/renderer/components/sidebar/VendorIcon.tsx, apps/desktop/src/renderer/components/sidebar/VendorReadinessBadge.tsx, apps/desktop/src/renderer/components/sidebar/WorktreeBadge.tsx, apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx, apps/desktop/src/renderer/components/title-bar/MenuButton.tsx, apps/desktop/src/renderer/components/title-bar/WindowControls.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/DeviceSectionHeader.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/layout/LayoutRoot.tsx, apps/desktop/src/renderer/layout/PanelDragController.tsx, apps/desktop/src/renderer/layout/PanelDragPrototype.tsx, apps/desktop/src/renderer/layout/collapsePrefs.ts, apps/desktop/src/renderer/layout/layoutDevTools.ts, apps/desktop/src/renderer/layout/panePlacement.tsx, apps/desktop/src/renderer/layout/paneWidths.tsx, apps/desktop/src/renderer/layout/panelMaximize.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 137 | 46 | 259 |
| `desktop.skillhub.local` | desktop | SkillHub 本地技能 | hash `/skillhub/local` 及统一详情 `/skillhub/detail`(旧详情链接重定向) | InstallTargetPicker, PluginManagementLayout, SkillDetailLayout, SkillhubDetailRoute, SkillhubDetailView, SkillhubFeatureLayout, SkillhubHomeView, SkillhubLocalLayout, SkillhubMarketDetailView | apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailRoute.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubLocalLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx | 39 | 0 | 45 |
| `desktop.skillhub.market` | desktop | SkillHub 市场 | hash `/skillhub/market`(SkillhubMarketListView) | InstallTargetPicker, MarketCard, MarketInfoEditDialog, SkillhubMarketDetailView, SkillhubMarketListView, VisibilityEditorDialog | apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx, apps/desktop/src/renderer/features/skillhub/components/HomeMarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInfoEditDialog.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInstallStatus.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketListError.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketLocalSkills.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketPreviewTree.tsx, apps/desktop/src/renderer/features/skillhub/components/OfficialSkillBadge.tsx, apps/desktop/src/renderer/features/skillhub/components/PlatformTagSelector.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillIcon.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillTagList.tsx, apps/desktop/src/renderer/features/skillhub/components/TeamScopePicker.tsx, apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsx | 47 | 0 | 53 |
diff --git a/docs/design-rules/usage-history-charts.md b/docs/design-rules/usage-history-charts.md
index d4d5cb8b18..8c35cf067e 100644
--- a/docs/design-rules/usage-history-charts.md
+++ b/docs/design-rules/usage-history-charts.md
@@ -11,6 +11,10 @@
柱体自身的裁剪采用同一登记处理。按钮的透明命中层不裁剪数据图元,不继承 pill 外形;键盘按钮语义、可访问日期/用量名称和 `aria-pressed` 保留。非交互渲染分支仍不创建按钮,其格子遵守同一成员登记。
+## 设备范围(2026-09-26 所有者需求)
+
+用量历史默认合并同账号所有电脑的用量,时间范围选择器左侧增加设备选择器:所有设备(默认)/ 本机 / 其它电脑。外观、尺寸与时间范围选择器一致(36px 胶囊触发器、同一下拉菜单样式;按 `DESIGN.md §4` 面板与触发器等宽,长设备名截断、状态说明在面板内换行),选项下方以 12px tertiary 文字注明其它电脑的「数据截至」时间或读不到的原因(离线、未允许远程控制、需要更新 Cindy、读取失败)。其它电脑只列出读到过用量的(有「数据截至」),从未读到的不显示;没有这样的电脑时不显示选择器。进入页面后第一次读取其它电脑期间,控件下方显示一行 12px tertiary 的小 spinner +「正在读取其它设备的用量…」,之后每分钟的后台同步不再提示。合并视图里有电脑读不到最新数据时,控件下方显示一行 12px tertiary 提示。「最耗 token 的任务」按所选时间范围统计每个任务在该范围内产生的 token(每日 × 任务记录,从功能上线起积累;所选范围早于最早记录时副标题注明「按天统计从 X 起」),多设备范围合并其它电脑的任务并在任务名下方用 12px tertiary 标出设备名。任务标题、模型与删除状态取当前值:页面打开期间重命名或删除任务会随即反映,不等下一次用量变化。任务标题是跳转到该任务的链接,整行是鼠标的放大命中区(hover 使用 `--surface-hover`);其它电脑的任务仅在该设备已连接、能找到对应任务时可点击。各设备的用量按其本地日期计(记录只精确到天,无法按小时换算);其它电脑已跨入本机「明天」时,超出本机今天的部分计入本机今天,避免今日合计和图表漏掉。读取其它电脑走后台链路,对方不会显示「正在被控制」横幅;0.1.93 及更早版本的电脑不去读取,状态为「需要更新 Cindy」。切换账号时设备选择回到「所有设备」,不保留上一个账号的设备列表。热力图、柱图、表格与配色规则不因设备范围改变。
+
## 页面排版(2026-09-08 所有者反馈)
用量历史对齐其他设置页面的阅读层级,沿用 `DESIGN.md §3` 的现有字号 Token,不修改全局字号或共享首页排版:
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 72b4912f3a..bf89e8ff2e 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -130,6 +130,29 @@ raw history 降级。任务列表活动推送不变,当前轮的正文、工
该标记只恢复此前的检查故障,不恢复 Agent 执行失败;旧脚本不输出、旧客户端不识别均不影响
原有退出码语义。实现见 `scheduler-host/pre-run-hook.ts` 与 `scheduler-host/storage.ts`。
+## 用量历史跨设备合并
+
+新增只读 invoke `maker:usage:device-rows`(Desktop ↔ Desktop,已登记 allowlist)。请求可选
+`{ sinceDay: 'YYYY-MM-DD' }`;被控端回 `{ format: 'usage-device-rows-v1', todayKey, sinceDay,
+rowsGz }`,`rowsGz` 为本机 `daily_spend` / `daily_model_usage` / `daily_session_usage` 原始行
+及全部记过用量任务的当前标题、模型、供应商、上下文与最后活跃时间 JSON 的 gzip + base64
+(任务元数据不分增量区间,每次都是完整集合,控制端整体覆盖;不在集合里的任务连同旧行丢弃)。
+任务元数据与 `local-db:sessions:list` 走同一远端 Bot 可见性判据,隐藏伙伴的任务及其行不外发;
+压缩后仍超帧预算回 `{ format, oversize: true }`。只含按天 × 模型、按天 × 任务的 token 与金额及任务展示元数据,不含消息内容或凭证;handler 无 sender 依赖、无副作用。控制端按账号缓存每台电脑最近一次读到的行,
+增量从缓存 `todayKey` 前一天起拉;被控端回的 `sinceDay` 与请求不一致时按全量替换。
+新增端到端可选能力 `background-link-v1`(`DEVICE_LINK_CAPABILITY_BACKGROUND_LINK_V1`,link-open 与
+link-accept 双向声明,不改 relay)。Desktop 控制端在本机没有订阅对端任何 topic 时建链即声明
+(`apps/desktop/src/main/device-link/backgroundLink.ts`,所有建链与自动重开入口共用这一判据);新被控端
+见到后不装 legacy `'*'`,不亮被控横幅、不转发推送、不挡无人值守更新重启,控制端之后显式 subscribe
+照常生效。旧被控端忽略该能力、照旧装 legacy `'*'`,所以用量读取走 `remoteBackgroundInvoke`:
+0.1.93 及更早的正式版或版本未知的电脑不建链;新建链路时对端未在 link-accept 声明支持,且本机仍无订阅,
+就立即关闭这条链路并按需要更新处理,同一版本不再重试。已就绪的链路直接复用。
+旧控制端与 Mobile 不声明该能力,行为不变。
+旧被控端回 `CHANNEL_NOT_ALLOWED`,控制端把该电脑标为需要更新,不影响其它电脑;旧控制端
+不调用新通道,行为不变。手机不参与读取,也未新增入口。本机 `maker:usage:history` 仍只对
+受信 renderer 开放。不改 relay、帧限制或服务器权限,服务端无需改动。实现见
+`apps/desktop/src/main/usage/usageDeviceRows.ts` 与 `peerUsageSync.ts`。
+
## 事实来源
| 内容 | 权威来源 |
diff --git a/packages/device-link/src/__tests__/allowlist.test.ts b/packages/device-link/src/__tests__/allowlist.test.ts
index baaedbdb3f..9123185fee 100644
--- a/packages/device-link/src/__tests__/allowlist.test.ts
+++ b/packages/device-link/src/__tests__/allowlist.test.ts
@@ -172,6 +172,12 @@ describe('REMOTE_INVOKE_ALLOWLIST', () => {
expect(REMOTE_INVOKE_ALLOWLIST.has('maker:usage:model-pricing')).toBe(true);
});
+ it('放行用量历史跨设备合并的原始用量行只读读取', () => {
+ expect(REMOTE_INVOKE_ALLOWLIST.has('maker:usage:device-rows')).toBe(true);
+ // 本机聚合入口仍只对受信 renderer 开放, 不经隧道暴露。
+ expect(REMOTE_INVOKE_ALLOWLIST.has('maker:usage:history')).toBe(false);
+ });
+
it('放行 Codex 官方额度读取与 desktop 绑定的人工 reset offer', () => {
expect(REMOTE_INVOKE_ALLOWLIST.has('maker:usage:codex-rate-limits')).toBe(true);
expect(REMOTE_INVOKE_ALLOWLIST.has('maker:usage:codex-rate-limit-reset')).toBe(true);
diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.ts
index 3e1dcd8694..e0a063166d 100644
--- a/packages/device-link/src/allowlist.ts
+++ b/packages/device-link/src/allowlist.ts
@@ -465,6 +465,12 @@ const EXTENDED_INVOKE_CHANNELS: readonly string[] = [
// 被控端视角的单价(与被控端桌面 tooltip 同源)。无 sender 依赖、无副作用;老被控端无此 channel
// → CHANNEL_NOT_ALLOWED → 控制端隐藏价格(与桌面「无价不显示」口径一致)。
'maker:usage:model-pricing',
+ // 用量历史跨设备合并(只读):同账号另一台电脑读取被控端 daily_spend / daily_model_usage
+ // 原始行,合并进它自己的「所有设备」用量历史。数据真相在被控端;只含按天 × 模型聚合的
+ // token 与金额,不含会话、消息或凭证。入参仅可选 sinceDay(YYYY-MM-DD),无 sender 依赖、
+ // 无副作用;响应 gzip 编码,超帧预算回结构化 oversize。老被控端无此 channel →
+ // CHANNEL_NOT_ALLOWED → 控制端把该设备标为「版本过旧」,不影响其它设备。
+ 'maker:usage:device-rows',
// 网关 API key **presence-only** 探测:只回 { present: boolean },不回、也永不扩展为读取
// 密钥材料 —— 这是「账号与密钥永不放行」大类下的窄口径例外(同 DL_VOICE_CREDENTIAL_SYNC
// 的例外定位,禁止泛化)。用途:控制端模型选择器判断折扣版(codex/)是否该置灰,判定依据
diff --git a/packages/device-link/src/protocol.ts b/packages/device-link/src/protocol.ts
index 31cef1d8c8..63a0455ed4 100644
--- a/packages/device-link/src/protocol.ts
+++ b/packages/device-link/src/protocol.ts
@@ -137,6 +137,14 @@ export const CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1 = 'maker-event-batch-v1'
/** Accepts ordered current-text snapshots and history repair hints, including after backpressure. */
export const CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1 = 'session-text-snapshot-v1';
+/**
+ * 后台链路(link-open / link-accept 双向声明)。控制端在本机没有订阅对端任何 topic 时建链
+ * 即声明:被控端不装 legacy `'*'` 兼容订阅 —— 不亮被控横幅、不转发推送、不挡无人值守更新
+ * 重启 —— 直到控制端显式 subscribe。被控端在 link-accept 声明支持;旧被控端忽略该能力,
+ * 照旧装 legacy `'*'`,只读类后台请求须先确认对端支持(见 desktop remoteBackgroundInvoke)。
+ */
+export const DEVICE_LINK_CAPABILITY_BACKGROUND_LINK_V1 = 'background-link-v1';
+
export interface LinkAcceptPayload {
appVersion: string;
/** 被控端 allowlist 的指纹,便于控制端探测版本差异 */