Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(chat): 持久化聊天历史并降低空闲轮询 (#7242)
bobo8088df4403d1
diff --git a/apps/desktop/drizzle/0133_chat_history_cache.sql b/apps/desktop/drizzle/0133_chat_history_cache.sqlnew file mode 100644index 0000000000..5dc6248bff--- /dev/null+++ b/apps/desktop/drizzle/0133_chat_history_cache.sql@@ -0,0 +1,15 @@+CREATE TABLE `chat_cache_messages` (+ `namespace` text NOT NULL,+ `room_id` text NOT NULL,+ `message_id` text NOT NULL,+ `payload` text NOT NULL,+ PRIMARY KEY(`namespace`, `room_id`, `message_id`)+);+--> statement-breakpoint+CREATE TABLE `chat_cache_rooms` (+ `namespace` text NOT NULL,+ `room_id` text NOT NULL,+ `state` text NOT NULL,+ `version` integer NOT NULL,+ PRIMARY KEY(`namespace`, `room_id`)+);diff --git a/apps/desktop/drizzle/meta/0133_snapshot.json b/apps/desktop/drizzle/meta/0133_snapshot.jsonnew file mode 100644index 0000000000..c8488d809d--- /dev/null+++ b/apps/desktop/drizzle/meta/0133_snapshot.json@@ -0,0 +1,7323 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "52de84ef-479e-42a4-addc-f53173feb95a",+ "prevId": "84f21dac-eba7-41de-8850-0e3f81ef2927",+ "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": {}+ },+ "auto_review_projections": {+ "name": "auto_review_projections",+ "columns": {+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "lead_id": {+ "name": "lead_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "revision": {+ "name": "revision",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "projected_revision": {+ "name": "projected_revision",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": -1+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 1+ },+ "payload": {+ "name": "payload",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "auto_review_projections_lead_idx": {+ "name": "auto_review_projections_lead_idx",+ "columns": [+ "lead_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "auto_review_projections_session_id_sessions_id_fk": {+ "name": "auto_review_projections_session_id_sessions_id_fk",+ "tableFrom": "auto_review_projections",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "auto_review_projections_lead_id_sessions_id_fk": {+ "name": "auto_review_projections_lead_id_sessions_id_fk",+ "tableFrom": "auto_review_projections",+ "tableTo": "sessions",+ "columnsFrom": [+ "lead_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "auto_review_projections_session_id_lead_id_pk": {+ "columns": [+ "session_id",+ "lead_id"+ ],+ "name": "auto_review_projections_session_id_lead_id_pk"+ }+ },+ "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": "'{}'"+ },+ "group_task_posts_json": {+ "name": "group_task_posts_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_group_members": {+ "name": "bot_group_members",+ "columns": {+ "group_id": {+ "name": "group_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "bot_id": {+ "name": "bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_seen_sequence": {+ "name": "last_seen_sequence",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "joined_at": {+ "name": "joined_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_bot_group_members_bot": {+ "name": "idx_bot_group_members_bot",+ "columns": [+ "bot_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "bot_group_members_group_id_bot_groups_id_fk": {+ "name": "bot_group_members_group_id_bot_groups_id_fk",+ "tableFrom": "bot_group_members",+ "tableTo": "bot_groups",+ "columnsFrom": [+ "group_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "bot_group_members_bot_id_bot_profiles_id_fk": {+ "name": "bot_group_members_bot_id_bot_profiles_id_fk",+ "tableFrom": "bot_group_members",+ "tableTo": "bot_profiles",+ "columnsFrom": [+ "bot_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "bot_group_members_group_id_bot_id_pk": {+ "columns": [+ "group_id",+ "bot_id"+ ],+ "name": "bot_group_members_group_id_bot_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_group_messages": {+ "name": "bot_group_messages",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "group_id": {+ "name": "group_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "sequence": {+ "name": "sequence",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'message'"+ },+ "author_kind": {+ "name": "author_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "author_bot_id": {+ "name": "author_bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "author_name": {+ "name": "author_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "mentions_json": {+ "name": "mentions_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{\"all\":false,\"botIds\":[]}'"+ },+ "notice_code": {+ "name": "notice_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "plan_id": {+ "name": "plan_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "files_json": {+ "name": "files_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "attachments_json": {+ "name": "attachments_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_group_messages_group_sequence": {+ "name": "uniq_bot_group_messages_group_sequence",+ "columns": [+ "group_id",+ "sequence"+ ],+ "isUnique": true+ },+ "uniq_bot_group_messages_group_client": {+ "name": "uniq_bot_group_messages_group_client",+ "columns": [+ "group_id",+ "client_id"+ ],+ "isUnique": true,+ "where": "\"bot_group_messages\".\"client_id\" IS NOT NULL"+ }+ },+ "foreignKeys": {+ "bot_group_messages_group_id_bot_groups_id_fk": {+ "name": "bot_group_messages_group_id_bot_groups_id_fk",+ "tableFrom": "bot_group_messages",+ "tableTo": "bot_groups",+ "columnsFrom": [+ "group_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_group_plan_steps": {+ "name": "bot_group_plan_steps",+ "columns": {+ "plan_id": {+ "name": "plan_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "bot_id": {+ "name": "bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "bot_name": {+ "name": "bot_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "task": {+ "name": "task",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "result_message_id": {+ "name": "result_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "started_at": {+ "name": "started_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "finished_at": {+ "name": "finished_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "bot_group_plan_steps_plan_id_bot_group_plans_id_fk": {+ "name": "bot_group_plan_steps_plan_id_bot_group_plans_id_fk",+ "tableFrom": "bot_group_plan_steps",+ "tableTo": "bot_group_plans",+ "columnsFrom": [+ "plan_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "bot_group_plan_steps_plan_id_position_pk": {+ "columns": [+ "plan_id",+ "position"+ ],+ "name": "bot_group_plan_steps_plan_id_position_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_group_plans": {+ "name": "bot_group_plans",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "group_id": {+ "name": "group_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "request_text": {+ "name": "request_text",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "attachments_json": {+ "name": "attachments_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "organizer_bot_id": {+ "name": "organizer_bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organizer_name": {+ "name": "organizer_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "current_step": {+ "name": "current_step",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "work_dir": {+ "name": "work_dir",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "branch": {+ "name": "branch",+ "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_group_plans_group_created": {+ "name": "idx_bot_group_plans_group_created",+ "columns": [+ "group_id",+ "created_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "bot_group_plans_group_id_bot_groups_id_fk": {+ "name": "bot_group_plans_group_id_bot_groups_id_fk",+ "tableFrom": "bot_group_plans",+ "tableTo": "bot_groups",+ "columnsFrom": [+ "group_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_groups": {+ "name": "bot_groups",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "reply_mode": {+ "name": "reply_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'all'"+ },+ "speaking_mode": {+ "name": "speaking_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'auto'"+ },+ "organizer_bot_id": {+ "name": "organizer_bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "project_dir": {+ "name": "project_dir",+ "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_groups_updated": {+ "name": "idx_bot_groups_updated",+ "columns": [+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "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": {}+ },+ "chat_cache_messages": {+ "name": "chat_cache_messages",+ "columns": {+ "namespace": {+ "name": "namespace",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "room_id": {+ "name": "room_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "message_id": {+ "name": "message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "payload": {+ "name": "payload",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "chat_cache_messages_namespace_room_id_message_id_pk": {+ "columns": [+ "namespace",+ "room_id",+ "message_id"+ ],+ "name": "chat_cache_messages_namespace_room_id_message_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "chat_cache_rooms": {+ "name": "chat_cache_rooms",+ "columns": {+ "namespace": {+ "name": "namespace",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "room_id": {+ "name": "room_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "chat_cache_rooms_namespace_room_id_pk": {+ "columns": [+ "namespace",+ "room_id"+ ],+ "name": "chat_cache_rooms_namespace_room_id_pk"+ }+ },+ "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_remote_opens": {+ "name": "orca_remote_opens",+ "columns": {+ "remote_session_id": {+ "name": "remote_session_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "device_id": {+ "name": "device_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": {},+ "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+ },+ "execution_device_id": {+ "name": "execution_device_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "remote_session_id": {+ "name": "remote_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_bridged_message_id": {+ "name": "last_bridged_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "remote_released_at": {+ "name": "remote_released_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "pending_remote_report": {+ "name": "pending_remote_report",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "remote_stop_confirmed_at": {+ "name": "remote_stop_confirmed_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_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": {}+ },+ "plugin_task_requests": {+ "name": "plugin_task_requests",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "plugin_id": {+ "name": "plugin_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "operation": {+ "name": "operation",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "target_id": {+ "name": "target_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "request_key": {+ "name": "request_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "fingerprint": {+ "name": "fingerprint",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "payload": {+ "name": "payload",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "revision": {+ "name": "revision",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "plugin_task_request_key": {+ "name": "plugin_task_request_key",+ "columns": [+ "plugin_id",+ "operation",+ "target_id",+ "request_key"+ ],+ "isUnique": true+ },+ "plugin_task_target": {+ "name": "plugin_task_target",+ "columns": [+ "target_id",+ "plugin_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "plugin_usage_events": {+ "name": "plugin_usage_events",+ "columns": {+ "call_id": {+ "name": "call_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "subject_id": {+ "name": "subject_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "history_generation": {+ "name": "history_generation",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "occurred_at": {+ "name": "occurred_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tool_name": {+ "name": "tool_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "entry_kind": {+ "name": "entry_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'tool'"+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "version": {+ "name": "version",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "release_id": {+ "name": "release_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "outcome": {+ "name": "outcome",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'unknown'"+ },+ "report_target": {+ "name": "report_target",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "report_state": {+ "name": "report_state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'not-applicable'"+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "attempt_count": {+ "name": "attempt_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ }+ },+ "indexes": {+ "plugin_usage_events_time_idx": {+ "name": "plugin_usage_events_time_idx",+ "columns": [+ "subject_id",+ "occurred_at"+ ],+ "isUnique": false+ },+ "plugin_usage_events_task_idx": {+ "name": "plugin_usage_events_task_idx",+ "columns": [+ "subject_id",+ "session_id",+ "occurred_at"+ ],+ "isUnique": false+ },+ "plugin_usage_events_pending_idx": {+ "name": "plugin_usage_events_pending_idx",+ "columns": [+ "next_attempt_at",+ "occurred_at"+ ],+ "isUnique": false,+ "where": "\"plugin_usage_events\".\"report_state\" = 'pending'"+ }+ },+ "foreignKeys": {+ "plugin_usage_events_subject_id_plugin_usage_subjects_id_fk": {+ "name": "plugin_usage_events_subject_id_plugin_usage_subjects_id_fk",+ "tableFrom": "plugin_usage_events",+ "tableTo": "plugin_usage_subjects",+ "columnsFrom": [+ "subject_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "plugin_usage_subjects": {+ "name": "plugin_usage_subjects",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "stable_key": {+ "name": "stable_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "source_kind": {+ "name": "source_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "plugin_id": {+ "name": "plugin_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "source_key": {+ "name": "source_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "server_root": {+ "name": "server_root",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ghost_id": {+ "name": "ghost_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "display_name": {+ "name": "display_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "binding_revision": {+ "name": "binding_revision",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "recording_started_at": {+ "name": "recording_started_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "history_generation": {+ "name": "history_generation",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ }+ },+ "indexes": {+ "plugin_usage_subjects_source_idx": {+ "name": "plugin_usage_subjects_source_idx",+ "columns": [+ "stable_key"+ ],+ "isUnique": true+ },+ "plugin_usage_subjects_binding_idx": {+ "name": "plugin_usage_subjects_binding_idx",+ "columns": [+ "ghost_id",+ "binding_revision"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "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+ },+ "agent_device_id": {+ "name": "agent_device_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'"+ },+ "scheduled_model_baseline": {+ "name": "scheduled_model_baseline",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "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+ },+ "hidden_at": {+ "name": "hidden_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+ },+ "last_activity_at": {+ "name": "last_activity_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+ },+ "im_default_route": {+ "name": "im_default_route",+ "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+ },+ "agent_device_id": {+ "name": "agent_device_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "orca_remote_lead": {+ "name": "orca_remote_lead",+ "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 filediff --git a/apps/desktop/drizzle/meta/_journal.json b/apps/desktop/drizzle/meta/_journal.jsonindex 18db7e1fdd..5e9c519f95 100644--- a/apps/desktop/drizzle/meta/_journal.json+++ b/apps/desktop/drizzle/meta/_journal.json@@ -932,6 +932,13 @@"when": 1792992079336,"tag": "0132_abnormal_dazzler","breakpoints": true+ },+ {+ "idx": 133,+ "version": "6",+ "when": 1793008292097,+ "tag": "0133_chat_history_cache",+ "breakpoints": true}]}\ No newline at end of filediff --git a/apps/desktop/src/main/bot-autonomy/botsChangedSignal.ts b/apps/desktop/src/main/bot-autonomy/botsChangedSignal.tsindex 796dc6d3ad..4a14db3786 100644--- a/apps/desktop/src/main/bot-autonomy/botsChangedSignal.ts+++ b/apps/desktop/src/main/bot-autonomy/botsChangedSignal.ts@@ -4,12 +4,21 @@* 归档伙伴不必等 60 秒的定时重读。本文件不 import 任何模块,发送方不因此加载观察层依赖。*/let listener: (() => void) | null = null;+const subscribers = new Set<() => void>();++export function subscribeBotProfilesChanged(next: () => void): () => void {+ subscribers.add(next);+ return () => { subscribers.delete(next); };+}export function setBotAutonomyBotsChangedListener(next: (() => void) | null): void {listener = next;}export function signalBotAutonomyBotsChanged(): void {+ for (const next of subscribers) {+ try { next(); } catch { /* A reader cannot block a committed profile change. */ }+ }try {listener?.();} catch {diff --git a/apps/desktop/src/main/companion-cloud/runtime.ts b/apps/desktop/src/main/companion-cloud/runtime.tsindex d85e414b6b..9fa3661f87 100644--- a/apps/desktop/src/main/companion-cloud/runtime.ts+++ b/apps/desktop/src/main/companion-cloud/runtime.ts@@ -176,6 +176,8 @@ export function startCompanionCloud(input: {humanActorId: string;selfDeviceId?: string;current: () => boolean;+ /** Durable Chat Server display projection; takeover and runtime reconstruction still read authoritative history. */+ transcript?: (roomId: string, actorId: string, refresh: boolean) => Promise<CompanionTranscriptMessage[]>;/** Active local companions whose home is this computer (and not demoted). */bots: () => CompanionCloudBot[];/** A local companion the owner paused: not synced or moved, and a merge asks to resume it first. */@@ -763,9 +765,11 @@ export function startCompanionCloud(input: {if (!actor) throw new Error('COMPANION_NOT_FOUND');const roomId = await mirror.ensureRoom(actor.externalId, actor.id, actor.name);// The room orders by arrival (older history may be uploaded later): read it whole, show it- // by message time. The first page re-reads; older pages reuse that read.+ // by message time. The durable reader validates its cached scan against room+ // changes; the legacy reader reuses a recent scan for older pages.const cached = transcripts.get(roomId);- const messages = before && cached && Date.now() - cached.at < TRANSCRIPT_CACHE_MS ? cached.messages+ const messages = input.transcript ? await input.transcript(roomId, actor.id, !before)+ : before && cached && Date.now() - cached.at < TRANSCRIPT_CACHE_MS ? cached.messages: await readAllRoomMessages(input.api, roomId, actor.id);transcripts.set(roomId, { at: Date.now(), messages });return transcriptPageOf(messages, before ? Number(before) : undefined);diff --git a/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts b/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.tsindex b550a8209d..b80212359f 100644--- a/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts@@ -112,7 +112,8 @@ describeMigrationReplay('migration replay', () => {db.exec("CREATE TABLE bot_delegations (id TEXT PRIMARY KEY)");db.exec("INSERT INTO sessions (id) VALUES ('legacy-session')");const result = runMigrationReplay(db, { drizzleDir: drizzleDir(), currentVersion: 124 });- expect(result.applied.map((migration) => migration.seq)).toEqual([125, 126, 127, 128, 129, 130, 131, 132]);+ expect(result.applied.map((migration) => migration.seq)).toEqual([125, 126, 127, 128, 129, 130, 131, 132, 133]);+ expect(columnNames(db, 'chat_cache_rooms')).toEqual(['namespace', 'room_id', 'state', 'version']);expect(columnNames(db, 'sessions')).toContain('scheduled_model_baseline');expect(columnNames(db, 'sessions')).toContain('last_activity_at');expect(db.prepare('SELECT last_activity_at FROM sessions').get()).toEqual({ last_activity_at: null });diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex c31d15c2d1..47892838e8 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -1,7 +1,9 @@import type { PluginUsageTransaction, PluginUsageHandle } from '../../../../shared/pluginUsage.js';import type { TaskTagRequest, TaskTagResult } from '@cindy/maker-shared';+import type { ChatCacheTransaction, ChatCacheResult } from '../../worker/opHandlers/chatCacheTx.js';export type DbTxName =+ | 'chatCache.execute'| 'usage.recordMediaSpend'| 'authorization.readProjection'| 'pluginUsage.execute'@@ -1412,6 +1414,7 @@ export type DbTxArgsByName = {'recentWorkdirs.mergeWindowsIdentity': RecentWorkdirsMergeWindowsIdentityArgs;'recentWorkdirs.removeWindowsIdentity': RecentWorkdirsRemoveWindowsIdentityArgs;'pluginUsage.execute': PluginUsageTransaction;+ 'chatCache.execute': ChatCacheTransaction;'taskTags.execute': TaskTagRequest & { newId?: string; callerSessionId?: string };'projectAliases.replaceIdentity': ProjectAliasesReplaceIdentityArgs;'toolResults.compactSession': CompactSessionToolResultsArgs;@@ -1508,6 +1511,7 @@ export type DbTxResultByName = {'recentWorkdirs.mergeWindowsIdentity': undefined;'recentWorkdirs.removeWindowsIdentity': { changes: number };'pluginUsage.execute': PluginUsageHandle | null;+ 'chatCache.execute': ChatCacheResult;'taskTags.execute': TaskTagResult;'projectAliases.replaceIdentity': {projectKey: string;diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.tsindex 1dd2934d7c..94d314c909 100644--- a/apps/desktop/src/main/localDb/schema.ts+++ b/apps/desktop/src/main/localDb/schema.ts@@ -22,6 +22,21 @@ import {import type { SessionSource } from '../../shared/sessionSource.js';+/** Rebuildable Chat Server projection inside the owner's database; namespace includes server and reader. */+export const chatCacheRooms = sqliteTable('chat_cache_rooms', {+ namespace: text('namespace').notNull(),+ roomId: text('room_id').notNull(),+ state: text('state').notNull(),+ version: integer('version').notNull(),+}, t => ({ pk: primaryKey({ columns: [t.namespace, t.roomId] }) }));++export const chatCacheMessages = sqliteTable('chat_cache_messages', {+ namespace: text('namespace').notNull(),+ roomId: text('room_id').notNull(),+ messageId: text('message_id').notNull(),+ payload: text('payload').notNull(),+}, t => ({ pk: primaryKey({ columns: [t.namespace, t.roomId, t.messageId] }) }));+const speedSetting = customType<{ data: FastMode; driverData: number }>({dataType: () => 'integer',toDriver: fastModeToStorage,diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/chatCacheTx.test.ts b/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/chatCacheTx.test.tsnew file mode 100644index 0000000000..95a80b406f--- /dev/null+++ b/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/chatCacheTx.test.ts@@ -0,0 +1,62 @@+import Database from 'better-sqlite3';+import { readFileSync } from 'node:fs';+import { afterEach, beforeEach, expect, it } from 'vitest';+import { tx } from '../tx.js';+import type { DbClient } from '../../../client/DbClient.js';+import { createSqliteChatHistoryStore } from '../../../../maker-ipc/chatHistoryStore.js';+import type { ChatHistoryState } from '@cindy/maker-shared/chat-history';++// Unit tier: actual worker transaction and SQLite rollback. A cursor committed before its+// tombstone would permanently resurrect content after restart; old Bot tests never covered it.+let db: Database.Database;+let client: DbClient;+beforeEach(() => {+ db = new Database(':memory:');+ db.exec(readFileSync(new URL('../../../../../../drizzle/0133_chat_history_cache.sql', import.meta.url), 'utf8'));+ client = { tx: async (name: string, args: unknown) => tx(db, { name, args }) } as DbClient;+});+afterEach(() => db.close());+const state = (cursor = '10', deleted = false): ChatHistoryState => ({ generation: 'one', cursor, metadataDirty: false,+ snapshot: { room: { id: 'room' }, cursor, messages: [] }, pages: { 'limit=100': ['m'] },+ messages: { m: { id: 'm', seq: '1', revision: deleted ? 2 : 1, deleted } } });+const store = (endpoint = 'https://chat.example', human = 'human', reader = human, current = () => true) =>+ createSqliteChatHistoryStore(client, endpoint, human, reader, current);++it('rolls back cursor, page coverage and tombstone together, then survives a new store instance', async () => {+ const cache = store(); await cache.read('room'); await cache.write('room', state());+ db.exec("CREATE TRIGGER fail_chat_write BEFORE UPDATE ON chat_cache_messages BEGIN SELECT RAISE(ABORT, 'disk full'); END;");+ await expect(cache.write('room', state('11', true))).rejects.toThrow('disk full');+ expect(await store().read('room')).toEqual(state());+ db.exec('DROP TRIGGER fail_chat_write');+ await cache.write('room', state('11', true));+ expect(await store().read('room')).toEqual(state('11', true));+});++it('partitions server, verified owner and acting reader, and refuses late owner writes', async () => {+ const cache = store(); await cache.read('room'); await cache.write('room', state());+ for (const other of [store('https://other.example'), store(undefined, 'other-human'), store(undefined, undefined, 'bot')])+ expect(await other.read('room')).toBeUndefined();+ let current = true; const captured = store(undefined, undefined, undefined, () => current);+ await captured.read('room'); current = false;+ await expect(captured.write('room', state('20'))).rejects.toThrow('OWNER_CHANGED');+ expect(await cache.read('room')).toEqual(state());+});++it('refuses to overwrite another instance’s newer cursor and evicts revoked data', async () => {+ const first = store(), second = store();+ await first.read('room'); await second.read('room');+ await first.write('room', state('20', true));+ // Deletes must honor the same CAS boundary as writes, including version reuse after reset.+ await expect(second.write('room', null)).rejects.toThrow('CHAT_CACHE_CONFLICT');+ await expect(second.write('room', state())).rejects.toThrow('CHAT_CACHE_CONFLICT');+ expect(await second.read('room')).toEqual(state('20', true));+ await second.write('room', null);+ // The numeric version restarts at 1 after reset; the old generation must still lose CAS.+ await second.write('room', { ...state('30', true), generation: 'rebuilt' });+ await expect(first.write('room', null)).rejects.toThrow('CHAT_CACHE_CONFLICT');+ await expect(first.write('room', state('21'))).rejects.toThrow('CHAT_CACHE_CONFLICT');+ expect(await second.read('room')).toMatchObject({ cursor: '30', generation: 'rebuilt' });+ await second.write('room', null);+ expect(await first.read('room')).toBeUndefined();+ expect(db.prepare('SELECT count(*) AS n FROM chat_cache_messages').get()).toEqual({ n: 0 });+});diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/chatCacheTx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/chatCacheTx.tsnew file mode 100644index 0000000000..9ecc168f59--- /dev/null+++ b/apps/desktop/src/main/localDb/worker/opHandlers/chatCacheTx.ts@@ -0,0 +1,45 @@+import type Database from 'better-sqlite3';+import type { ChatHistoryState } from '@cindy/maker-shared/chat-history';++export type ChatCacheTransaction = { namespace: string; room: string } & (+ | { action: 'read' }+ | { action: 'write'; version: number | null; generation: string | null; state: ChatHistoryState | null }+);+export interface ChatCacheResult { version: number | null; state?: ChatHistoryState; conflict?: boolean }++/** Cursor/page coverage and every message change share one SQLite transaction. */+export function runChatCacheTransaction(db: Database.Database, input: ChatCacheTransaction): ChatCacheResult {+ return db.transaction(() => {+ const args = [input.namespace, input.room];+ const row = db.prepare('SELECT version,state FROM chat_cache_rooms WHERE namespace=? AND room_id=?').get(...args) as+ { version: number; state: string } | undefined;+ if (input.action === 'read') {+ if (!row) return { version: null };+ const messages = db.prepare('SELECT message_id,payload FROM chat_cache_messages WHERE namespace=? AND room_id=?').all(...args) as Array<{ message_id: string; payload: string }>;+ return { version: row.version, state: { ...JSON.parse(row.state), messages: Object.fromEntries(messages.map(m => [m.message_id, JSON.parse(m.payload)])) } };+ }+ if ((row?.version ?? null) !== input.version || (row ? JSON.parse(row.state).generation : null) !== input.generation)+ return { conflict: true, version: row?.version ?? null };+ if (!input.state) {+ db.prepare('DELETE FROM chat_cache_messages WHERE namespace=? AND room_id=?').run(...args);+ db.prepare('DELETE FROM chat_cache_rooms WHERE namespace=? AND room_id=?').run(...args);+ return { version: null };+ }+ const version = (row?.version ?? 0) + 1;+ const { messages, ...state } = input.state;+ db.prepare(`INSERT INTO chat_cache_rooms(namespace,room_id,state,version) VALUES(?,?,?,?)+ ON CONFLICT(namespace,room_id) DO UPDATE SET state=excluded.state,version=excluded.version`).run(...args, JSON.stringify(state), version);+ const previous = db.prepare('SELECT message_id,payload FROM chat_cache_messages WHERE namespace=? AND room_id=?').all(...args) as Array<{ message_id: string; payload: string }>;+ const known = new Map(previous.map(m => [m.message_id, m.payload]));+ const upsert = db.prepare(`INSERT INTO chat_cache_messages(namespace,room_id,message_id,payload) VALUES(?,?,?,?)+ ON CONFLICT(namespace,room_id,message_id) DO UPDATE SET payload=excluded.payload`);+ for (const [id, message] of Object.entries(messages)) {+ const payload = JSON.stringify(message);+ if (known.get(id) !== payload) upsert.run(...args, id, payload);+ known.delete(id);+ }+ const remove = db.prepare('DELETE FROM chat_cache_messages WHERE namespace=? AND room_id=? AND message_id=?');+ for (const id of known.keys()) remove.run(...args, id);+ return { version };+ })();+}diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex 1c492d5430..e33ca60d80 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -15,6 +15,7 @@ import { inferBotTemplatePresetId } from '../../../../shared/botTemplatePreset.jimport type Database from 'better-sqlite3';import type { DbTxName, SessionsSetTerminalStatusResult } from '../../client/tx/types.js';+import { runChatCacheTransaction, type ChatCacheTransaction } from './chatCacheTx.js';import { computeForkSourceMessagesDigest, type ForkSourceMessage } from '../../forkRecoverySnapshot.js';import { normalizeWorkingDirForStorage } from '../../../../shared/workingDir.js';import { capImportedToolResultContent } from '../../../../shared/toolResultPersistCap.js';@@ -70,6 +71,8 @@ function dispatchTransaction(db: Database.Database, args: unknown): unknown {const txArgs = payload.args;switch (name) {+ case 'chatCache.execute':+ return runChatCacheTransaction(db, txArgs as ChatCacheTransaction);case 'usage.recordMediaSpend':return recordMediaSpend(db, txArgs as import('../../client/tx/types.js').MediaSpendArgs);case 'authorization.readProjection':diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.tsindex a780f959dc..d2f6a20f5d 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts@@ -83,6 +83,7 @@ vi.mock('ws', async () => {});import { ChatResponseError, REACTION_REVISION_MESSAGE_LIMIT, splitChatMessageText, withChatServer } from '../chatServer.js';import { t } from '../../i18n.js';+import { signalBotAutonomyBotsChanged } from '../../bot-autonomy/botsChangedSignal.js';import { projectBotGroupExecutionFailures } from '@cindy/maker-shared/botGroupPresentation';import { botGroupRuntimeFailureCode, settleUndispatchedBotGroupTurn } from '../botGroupRuntimeFailure.js';import { authorizeGroupTool } from '../botGroupToolAuthorization.js';@@ -2502,7 +2503,7 @@ describe('Chat Server result delivery and refresh', () => {fixture.handle.mockImplementation(route => route === '/actors'? { body: [{ id: botId, kind: 'bot', externalId: 'local-bot', name: 'Renamed' }] } : response(route));// Reads return on the old registry; the next background registration replaces it afterwards.- await vi.advanceTimersByTimeAsync(6000);+ await vi.advanceTimersByTimeAsync(60_000);await service.getGroup(roomId);await vi.advanceTimersByTimeAsync(300);expect(deps.onChanged).toHaveBeenCalledWith(expect.objectContaining({ groupId: '' }), undefined);@@ -2526,6 +2527,7 @@ describe('Chat Server result delivery and refresh', () => {expect(deps.onChanged).toHaveBeenCalledWith(expect.objectContaining({ groupId: roomId }), undefined);vi.mocked(socket.send).mockClear();socket.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor: '43', changes: [] }));+ await vi.advanceTimersByTimeAsync(0);expect(socket.send).toHaveBeenCalledWith(JSON.stringify({ type: 'ack', scope: `conversation:${roomId}`, cursor: '43' }));});@@ -3226,6 +3228,65 @@ describe('Chat Server result delivery and refresh', () => {expect(deps.dispatch).toHaveBeenCalledOnce();});+ // Unit: two-minute idle installations previously performed 60 claims per Bot and+ // refreshed identity every six seconds. Preserve the bounded unopened-room fallback.+ it('backs off idle claims independently from profile refresh while keeping a bounded fallback', async () => {+ fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];+ claimed = true;+ await vi.advanceTimersByTimeAsync(120_000);+ const count = (path: string) => fixture.handle.mock.calls.filter(([route]) => route === path).length;+ expect(count('/executions/claim')).toBeGreaterThanOrEqual(5);+ expect(count('/executions/claim')).toBeLessThanOrEqual(12);+ expect(count('/me')).toBeLessThanOrEqual(3);+ expect(count('/actors')).toBeLessThanOrEqual(3);+ expect(count('/profile/refresh')).toBe(1);+ });++ // PR #7242, unit: the idle cadence test never invalidated a recent registration.+ // A failed forced refresh must still register a new bot when the poll backoff ends.+ it.each(['/me', '/actors'])('retries a failed forced %s refresh before the idle throttle expires', async failedRoute => {+ await vi.advanceTimersByTimeAsync(2000);+ const requestStart = fixture.requests.length;+ const newActor = { id: '20000000-0000-4000-8000-000000000002', kind: 'bot', externalId: 'new-bot', name: 'New' };+ fixture.profiles = [{ id: 'new-bot', displayName: 'New', avatar: null, status: 'active' }];+ let fail = true;+ fixture.handle.mockImplementation((route, method) => {+ if (fail && route === failedRoute) return { status: 503, body: { error: { code: 'UNAVAILABLE' } } };+ if (route === '/actors') return { body: method === 'POST' ? newActor : [] };+ if (route === '/executions/claim') return { body: { execution: null } };+ return response(route);+ });+ signalBotAutonomyBotsChanged();+ await vi.advanceTimersByTimeAsync(2000);+ expect(fixture.handle.mock.calls.filter(([route, method]) => route === '/actors' && method === 'POST')).toHaveLength(0);+ fail = false;+ await vi.advanceTimersByTimeAsync(10_000);+ expect(fixture.handle.mock.calls.filter(([route, method]) => route === '/actors' && method === 'POST')).toHaveLength(1);+ expect(fixture.requests.slice(requestStart).some(request => request.url.endsWith('/executions/claim') && request.actor === newActor.id)).toBe(true);+ const registered = fixture.handle.mock.calls.filter(([route]) => route === '/me').length;+ await vi.advanceTimersByTimeAsync(10_000);+ expect(fixture.handle.mock.calls.filter(([route]) => route === '/me')).toHaveLength(registered);+ });++ // Unit: a notice racing an old empty response must not inherit that response's idle delay.+ it('claims immediately when a queued notice arrives during an empty claim', async () => {+ fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];+ claimed = true;+ const socket = await live();+ let finish!: (value: unknown) => void;+ fixture.handle.mockImplementation(route => route === '/executions/claim'+ ? new Promise(resolve => { finish = resolve; }) : response(route));+ await vi.advanceTimersByTimeAsync(20_000);+ expect(finish).toBeTypeOf('function');+ socket.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor: '8',+ changes: [{ type: 'execution.changed', entityId: execution.id, data: { status: 'queued', botId } }] }));+ await vi.advanceTimersByTimeAsync(250);+ claimed = false; fixture.handle.mockImplementation(response);+ finish({ body: { execution: null } });+ await vi.advanceTimersByTimeAsync(0);+ expect(deps.dispatch).toHaveBeenCalledOnce();+ });+it('keeps realtime claims inside the poll backoff after a 429', async () => {fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];const socket = await live();@@ -4079,6 +4140,8 @@ describe('Chat authentication recovery and polling backoff', () => {const meCalls = () => fixture.requests.filter(r => new URL(r.url).pathname === '/v1/me').length;expect(meCalls()).toBe(5);await vi.advanceTimersByTimeAsync(6_000);+ expect(meCalls()).toBe(5);+ await vi.advanceTimersByTimeAsync(54_000);expect(meCalls()).toBe(6);expect(fixture.refresh).not.toHaveBeenCalled();});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerCompanion.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerCompanion.test.tsindex df10fc53e4..bb3c8f33c8 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerCompanion.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerCompanion.test.ts@@ -44,7 +44,9 @@ vi.mock('ws', async () => {import { withChatServer } from '../chatServer.js';import { createCompanionHomeRegistry } from '../../companion-cloud/homes.js';import { createCompanionCloudState } from '../../companion-cloud/state.js';-import type { CompanionCloudHost } from '../../companion-cloud/runtime.js';+import { activeCompanionCloud, type CompanionCloudHost } from '../../companion-cloud/runtime.js';+import * as chatRoom from '../../companion-cloud/room.js';+import type { ChatHistoryState } from '@cindy/maker-shared/chat-history';import type { BotGroupChatService, BotGroupChatServiceDeps } from '../botGroupChatService.js';const selfId = '30000000-0000-4000-8000-000000000001';@@ -99,7 +101,54 @@ describe('Chat Server cloud companions', () => {deps = { ensureLane: vi.fn(), abortLane: vi.fn(async () => {}), dispatch: vi.fn(), companionCloud: host } as unknown as BotGroupChatServiceDeps;service = withChatServer({ listGroups: vi.fn(async () => ({ ok: true, groups: [] })), dispose: vi.fn() } as unknown as BotGroupChatService, deps);});- afterEach(() => { service.dispose(); vi.useRealTimers(); vi.unstubAllEnvs(); vi.clearAllMocks(); });+ afterEach(() => { service.dispose(); vi.useRealTimers(); vi.unstubAllEnvs(); vi.clearAllMocks(); vi.restoreAllMocks(); });++ // PR #7242, unit: production transcript paging must reuse a scan, but still+ // observe delta edits, reset and revoked access. Existing room tests bypassed this injection.+ it('reuses a checked transcript for older pages and revalidates changes before reusing it', async () => {+ claimed = true;+ const scans = vi.spyOn(chatRoom, 'readAllRoomMessages');+ const saved = new Map<string, ChatHistoryState>();+ deps.chatHistoryStore = () => ({+ read: async room => structuredClone(saved.get(room)),+ write: async (room, state) => { if (state) saved.set(room, structuredClone(state)); else saved.delete(room); },+ });+ const message = (seq: number, text = `text ${seq}`) => ({ id: `m${seq}`, seq: String(seq), authorId: selfId,+ createdAt: new Date(seq * 1000).toISOString(), content: [{ type: 'text', text }] });+ let cursor = '1', mode: 'same' | 'edit' | 'reset' | 'forbidden' = 'same';+ fixture.handle.mockImplementation((route, method, body) => {+ if (route === '/conversations') return { body: { id: roomId } };+ if (route.endsWith('/snapshot')) return { body: { room: { id: roomId, kind: 'direct' }, messages: [], cursor } };+ if (route.includes('/messages?')) {+ const before = Number(new URL(`https://fixture${route}`).searchParams.get('before') ?? 111);+ return { body: Array.from({ length: 110 }, (_, i) => message(110 - i, mode === 'reset' ? 'reset' : undefined))+ .filter(m => Number(m.seq) < before).slice(0, 100) };+ }+ if (route.startsWith('/changes?')) {+ if (mode === 'forbidden') return { status: 403, body: { error: { code: 'FORBIDDEN' } } };+ if (mode === 'reset') return { status: 409, body: { error: { code: 'RESET_REQUIRED' } } };+ return { body: { cursor, changes: mode === 'edit' ? [{ type: 'message.updated', data: { message: { ...message(1, 'edited'), revision: 2 } } }] : [] } };+ }+ return respond(route, method, body);+ });+ await vi.advanceTimersByTimeAsync(2000);+ const runtime = activeCompanionCloud()!;+ const first = await runtime.transcript('local-bot');+ const reads = () => fixture.handle.mock.calls.filter(([route]) => route.startsWith('/changes?') || route.includes('/messages?')).length;+ const initialReads = reads();+ expect((await runtime.transcript('local-bot', first.nextBefore)).messages).toHaveLength(10);+ expect(reads()).toBe(initialReads);+ expect(scans).toHaveBeenCalledTimes(1);++ cursor = '2'; mode = 'edit'; vi.setSystemTime(Date.now() + 31_000);+ expect((await runtime.transcript('local-bot', first.nextBefore)).messages[0]!.text).toBe('edited');+ expect(reads()).toBe(initialReads + 1);+ expect(scans).toHaveBeenCalledTimes(2);+ cursor = '3'; mode = 'reset'; vi.setSystemTime(Date.now() + 31_000);+ expect((await runtime.transcript('local-bot', first.nextBefore)).messages[0]!.text).toBe('reset');+ mode = 'forbidden'; vi.setSystemTime(Date.now() + 31_000);+ await expect(runtime.transcript('local-bot', first.nextBefore)).rejects.toThrow('FORBIDDEN');+ });it('claims an empty home for this computer once', async () => {claimed = true;@@ -132,9 +181,13 @@ describe('Chat Server cloud companions', () => {await vi.advanceTimersByTimeAsync(10_000);expect(calls(`/actors/${botActor}`, 'PATCH').length).toBeGreaterThan(0);expect(calls('/executions/claim')).toHaveLength(0);- // Registration succeeds on a later cycle: this computer is the home and starts claiming.+ // Registration is retried by the 60s actor refresh, not the former 5s cadence.+ // A failed home registration must still fence claims throughout that interval.patch = () => { home = 'desk-1'; return { body: { id: botActor, homeDeviceId: 'desk-1' } }; };await vi.advanceTimersByTimeAsync(20_000);+ expect(calls('/executions/claim')).toHaveLength(0);+ expect(calls(`/actors/${botActor}`, 'PATCH')).toHaveLength(1);+ await vi.advanceTimersByTimeAsync(32_000);expect(calls('/executions/claim').length).toBeGreaterThan(0);});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerGroupOpen.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerGroupOpen.test.tsindex 8fba6deaad..ab406d8ac6 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerGroupOpen.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerGroupOpen.test.ts@@ -66,6 +66,7 @@ vi.mock('ws', async () => {});import { withChatServer } from '../chatServer.js';import type { BotGroupChatService, BotGroupChatServiceDeps } from '../botGroupChatService.js';+import type { ChatHistoryState, ChatHistoryStore } from '@cindy/maker-shared/chat-history';const selfId = '30000000-0000-4000-8000-000000000001';const rooms = Array.from({ length: 8 }, (_, index) => `10000000-0000-4000-8000-00000000000${index + 1}`);@@ -121,6 +122,133 @@ describe('Chat Server group open latency (simulated 100ms per request)', () => {});afterEach(() => { service.dispose(); vi.useRealTimers(); vi.unstubAllEnvs(); vi.clearAllMocks(); });+ // Unit: a membership reset while execution metadata is loading must not relabel old messages as the new history.+ it('retries a composed group view if its cached history resets during another HTTP read', async () => {+ const disk = new Map<string, ChatHistoryState>();+ fixture.handle.mockImplementation(route => route.startsWith('/changes?')+ ? { body: { cursor: '57', changes: [], hasMore: false } } : response(route));+ const store: ChatHistoryStore = { read: async room => structuredClone(disk.get(room)), write: async (room, state) => {+ if (state) disk.set(room, structuredClone(state)); else disk.delete(room);+ } };+ service.dispose(); service = withChatServer(local as unknown as BotGroupChatService,+ { onChanged, chatHistoryStore: () => store } as unknown as BotGroupChatServiceDeps);+ await timed(() => service.getGroup(rooms[0])); await connected();+ fixture.timing = route => ({ serve: 100, deliver: route.endsWith('/executions') ? 500 : 100 });+ const pending = service.getGroup(rooms[0]);+ // Latest message page has been read from disk; the response is waiting for execution state.+ await vi.advanceTimersByTimeAsync(120);+ fixture.page = [];+ fixture.sockets[0].emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${rooms[0]}`, cursor: '58',+ changes: [{ type: 'membership.changed' }] }));+ const result = await timed(() => pending);+ expect(result.value).toMatchObject({ ok: true, group: { messages: [] } });+ });++ // Unit: production adapter + persisted projection; old open-path tests only covered HTTP invalidation.+ it('persists historical edits before ACK and reopens from disk with only an incremental read', async () => {+ const disk = new Map<string, ChatHistoryState>();+ let block: Promise<void> | undefined;+ let finish!: () => void;+ const store: ChatHistoryStore = { read: async room => structuredClone(disk.get(room)), write: async (room, state) => {+ await block; if (state) disk.set(room, structuredClone(state)); else disk.delete(room);+ } };+ const open = () => withChatServer(local as unknown as BotGroupChatService,+ { onChanged, chatHistoryStore: () => store } as unknown as BotGroupChatServiceDeps);+ service.dispose(); service = open();+ const old = { ...message, id: '50000000-0000-4000-8000-000000000002', seq: '2', revision: 1 };+ fixture.page = Array.from({ length: 100 }, (_, index) => ({ ...message, seq: String(200 - index),+ id: `50000000-0000-4000-8000-${String(200 - index).padStart(12, '0')}` }));+ let head = '57';+ fixture.handle.mockImplementation(route => route.startsWith('/changes?') ? { body: { cursor: head, changes: [], hasMore: false } }+ : route.includes('/messages?') && route.includes('before=5') ? { body: [old] } : response(route));+ await timed(() => service.getGroup(rooms[0]));+ await timed(() => service.getGroup(rooms[0], { beforeSequence: 5 }));+ await connected();+ await timed(() => service.getGroup(rooms[0]));+ block = new Promise(resolve => { finish = resolve; });+ const ws = fixture.sockets[0]; vi.mocked(ws.send).mockClear();+ ws.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${rooms[0]}`, cursor: '58', changes: [+ { type: 'message.updated', entityId: old.id, data: { message: { ...old, revision: 2, content: [{ type: 'text', text: 'edited remotely' }] } } },+ ] }));+ await vi.advanceTimersByTimeAsync(0);+ expect(sent().some(frame => frame.type === 'ack')).toBe(false);+ expect(disk.get(rooms[0])?.cursor).toBe('57');+ head = '58'; finish(); block = undefined;+ await vi.advanceTimersByTimeAsync(0);+ expect(sent()).toContainEqual({ type: 'ack', scope: `conversation:${rooms[0]}`, cursor: '58' });+ const refreshed = await timed(() => service.getGroup(rooms[0], { sourceMessageIds: [old.id] }));+ expect(refreshed.value.ok && refreshed.value.group.messageUpdates?.[0]?.content).toBe('edited remotely');+ service.dispose(); service = open();+ const restart = await timed(() => service.getGroup(rooms[0], { beforeSequence: 5 }));+ expect(restart.value.ok && restart.value.group.messages[0]?.content).toBe('edited remotely');+ expect(restart.routes.filter(route => route.includes('/snapshot') || route.includes('/messages?'))).toEqual([]);+ expect(restart.routes.some(route => route.startsWith('/changes?') && route.includes('after=58'))).toBe(true);+ });++ // Unit: an old-page update must retain the authoritative thread-share projection,+ // including a deleted source, instead of replacing it with its untrusted fallback.+ it('decorates cached old-page message updates with thread references', async () => {+ const disk = new Map<string, ChatHistoryState>();+ const store: ChatHistoryStore = { read: async room => structuredClone(disk.get(room)), write: async (room, state) => {+ if (state) disk.set(room, structuredClone(state)); else disk.delete(room);+ } };+ service.dispose(); service = withChatServer(local as unknown as BotGroupChatService,+ { onChanged, chatHistoryStore: () => store } as unknown as BotGroupChatServiceDeps);+ const root = { ...message, id: '50000000-0000-4000-8000-000000000003', replyCount: 1 };+ const reply = { ...message, id: '50000000-0000-4000-8000-000000000004', seq: '2', threadRootId: root.id, deleted: true, content: [] };+ const share = { ...message, id: '50000000-0000-4000-8000-000000000005', seq: '3', content: [{ type: 'card',+ namespace: 'cindy.thread-share', schemaRevision: 1, fallback: 'deleted private text', data: { messageId: reply.id, threadRootId: root.id } }] };+ fixture.handle.mockImplementation(route => route.startsWith('/changes?') ? { body: { cursor: '57', changes: [], hasMore: false } }+ : route.endsWith('/snapshot') ? { body: { room: room(rooms[0]), members: [], messages: [{ ...reply, id: '50000000-0000-4000-8000-000000000006', deleted: false, content: message.content }, reply, root], cursor: '57' } }+ : route.includes('/messages?') && route.includes('before=5') ? { body: [share, root] } : response(route));+ await timed(() => service.getGroup(rooms[0], { beforeSequence: 5 }));+ const result = await timed(() => service.getGroup(rooms[0], { sourceMessageIds: [share.id, root.id],+ shownShares: [{ id: share.id, messageId: reply.id, threadRootId: root.id }] }));+ expect(result.value.ok && result.value.group.messageUpdates?.find(view => view.id === share.id)?.threadShare)+ .toMatchObject({ messageId: reply.id, status: 'unavailable', content: '' });+ expect(result.value.ok && result.value.group.messageUpdates?.find(view => view.id === root.id)?.threadPreview?.replies[0]?.text).toBe('hello');+ });++ // Unit: all successful local /read writers must update the durable UI projection+ // even while WS is unavailable; existing HTTP tests had no persistent cache.+ it.each(['main', 'thread', 'follow'] as const)('invalidates personal metadata after a local %s write without a socket notice', async action => {+ const disk = new Map<string, ChatHistoryState>();+ const store: ChatHistoryStore = { read: async room => structuredClone(disk.get(room)), write: async (room, state) => {+ if (state) disk.set(room, structuredClone(state)); else disk.delete(room);+ } };+ service.dispose(); service = withChatServer(local as unknown as BotGroupChatService,+ { onChanged, chatHistoryStore: () => store } as unknown as BotGroupChatServiceDeps);+ const root = { ...message, authorId: '30000000-0000-4000-8000-000000000002', replyCount: 1 };+ const reply = { ...root, id: '50000000-0000-4000-8000-000000000002', seq: '2', threadRootId: root.id };+ let mainRead = '0', threadRead = '0', following = false;+ fixture.page = [root];+ fixture.handle.mockImplementation((route, method, body) => {+ if (route.endsWith('/read') && method === 'POST') {+ if (body.threadRootId) { threadRead = body.readSeq; following = body.following ?? following; }+ else mainRead = body.readSeq;+ return { body: { following } };+ }+ if (route.endsWith('/snapshot')) return { body: { room: room(rooms[0]), members: [], messages: [reply, root], cursor: '57',+ reads: [{ thread_key: 'main', read_seq: mainRead }, { thread_key: root.id, read_seq: threadRead, following }] } };+ if (route.endsWith('/members')) return { body: [] };+ if (route.endsWith(`/messages/${root.id}`)) return { body: root };+ if (route.includes('threadRootId=')) return { body: [reply] };+ if (route.startsWith('/changes?')) return { body: { cursor: '57', changes: [], hasMore: false } };+ return response(route);+ });+ await timed(() => service.getGroup(rooms[0]));+ const result = await timed(() => action === 'main'+ ? service.chatServer!.manage({ groupId: rooms[0], action: { type: 'read', messageId: root.id } })+ : action === 'thread' ? service.chatServer!.thread({ groupId: rooms[0], rootId: root.id, markRead: true })+ : service.chatServer!.followThread({ groupId: rooms[0], rootId: root.id, following: true }));+ expect(result.value.ok).toBe(true);+ await timed(() => service.getGroup(rooms[0]));+ expect(disk.get(rooms[0])?.snapshot).toMatchObject({ reads: [+ { thread_key: 'main', read_seq: action === 'main' ? '1' : '0' },+ { thread_key: root.id, read_seq: action === 'thread' ? '2' : '0', following: action === 'follow' },+ ] });+ });+it('opens a group in three request rounds and a followed group in two', async () => {const firstOpen = await timed(() => service.getGroup(rooms[0]));await warm();@@ -212,6 +340,7 @@ describe('Chat Server group open latency (simulated 100ms per request)', () => {vi.mocked(fixture.sockets[0].send).mockClear();onChanged.mockClear();fixture.sockets[0].emit('message', JSON.stringify({ type: 'ready' }));+ await vi.advanceTimersByTimeAsync(0);expect(sent()).toContainEqual({ type: 'subscribe', scope: `conversation:${rooms[0]}`, after: '58' });// A reconnect still re-reads every followed room once, after the 150ms coalescing window.await vi.advanceTimersByTimeAsync(150);diff --git a/apps/desktop/src/main/maker-ipc/botGroupChatService.ts b/apps/desktop/src/main/maker-ipc/botGroupChatService.tsindex 82a6d6f068..654f79594c 100644--- a/apps/desktop/src/main/maker-ipc/botGroupChatService.ts+++ b/apps/desktop/src/main/maker-ipc/botGroupChatService.ts@@ -123,6 +123,8 @@ export async function settleBotGroupLaneTerminal(}export interface BotGroupChatServiceDeps {+ /** A durable, owner-captured UI projection; tests and hosts without persistence can omit it. */+ chatHistoryStore?: (endpoint: string, humanActorId: string, readerActorId: string, current: () => boolean) => import('@cindy/maker-shared/chat-history').ChatHistoryStore;/*** With `plan`, the Bot's 分工 Session for that plan (bot-group-chat.md §7.4); with* `threadRootId`, the Bot's own lane for that Thread (§3); with `talkPlanId`, its owndiff --git a/apps/desktop/src/main/maker-ipc/chatHistoryStore.ts b/apps/desktop/src/main/maker-ipc/chatHistoryStore.tsnew file mode 100644index 0000000000..c4fc6aabfc--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/chatHistoryStore.ts@@ -0,0 +1,30 @@+import { createHash } from 'node:crypto';+import type { DbClient } from '../localDb/client/DbClient.js';+import type { ChatHistoryStore } from '@cindy/maker-shared/chat-history';++/** The captured DbClient belongs to the current owner, never to whichever owner is logged in later. */+export function createSqliteChatHistoryStore(db: DbClient, endpoint: string, humanActorId: string, readerActorId: string,+ current: () => boolean): ChatHistoryStore {+ const namespace = createHash('sha256').update(JSON.stringify([endpoint.replace(/\/$/, ''), humanActorId, readerActorId])).digest('hex');+ const versions = new Map<string, number | null>();+ const generations = new Map<string, string | null>();+ const assertCurrent = () => { if (!current()) throw new Error('OWNER_CHANGED'); };+ return {+ async read(room) {+ assertCurrent();+ const result = await db.tx('chatCache.execute', { action: 'read', namespace, room });+ assertCurrent(); versions.set(room, result.version);+ generations.set(room, result.state?.generation ?? null);+ return result.state;+ },+ async write(room, state) {+ assertCurrent();+ const result = await db.tx('chatCache.execute', { action: 'write', namespace, room, state,+ version: versions.get(room) ?? null, generation: generations.get(room) ?? null });+ assertCurrent();+ if (result.conflict) { versions.delete(room); throw new Error('CHAT_CACHE_CONFLICT'); }+ versions.set(room, result.version);+ generations.set(room, state?.generation ?? null);+ },+ };+}diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.tsindex 38ac84a264..f0ba0055b8 100644--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@ -7,7 +7,7 @@ import { app, net, nativeImage } from 'electron';import { validateAvatarUpload } from '../profileEdit.js';import { uploadPublicAsset } from '../ossPublicUpload.js';import { getClientEndpoint } from '../clientEndpointsService.js';-import { signalBotAutonomyBotsChanged } from '../bot-autonomy/botsChangedSignal.js';+import { signalBotAutonomyBotsChanged, subscribeBotProfilesChanged } from '../bot-autonomy/botsChangedSignal.js';import { t } from '../i18n.js';import { readFile as readMedia } from '../cindy-media/blobStore.js';import { getAccessToken, refresh } from '../authManager.js';@@ -61,6 +61,8 @@ import { createThreadProjection, isShareableThreadReply, threadPreviewAttachmentimport { companionSnapshot, registerCompanionHomes } from '../companion-cloud/homes.js';import { startCompanionCloud, type CompanionCloudRuntime } from '../companion-cloud/runtime.js';import { DIRECT_ROOM_COMPLETION, deliverDirectRoomMessage, directRoomClientId } from '../companion-cloud/directRoom.js';+import { createChatHistory, type ChatHistory } from '@cindy/maker-shared/chat-history';+import { readAllRoomMessages } from '../companion-cloud/room.js';interface Actor { id: string; kind: string; externalId: string; name: string; avatar?: string | null; avatarSource?: string | null; homeDeviceId?: string | null; disabled?: boolean }interface Member { id: string; kind: 'human' | 'bot' | 'integration'; name: string; state: string; role: 'owner' | 'admin' | 'member' | 'guest';@@ -131,6 +133,10 @@ const THREAD_LIST_LIMIT = 50;const CHANGE_COALESCE_MS = 150;/** A realtime notice of newly queued work claims it this soon instead of on the next 2s tick. */const CLAIM_TRIGGER_MS = 250;+const ACTOR_REFRESH_MS = 60_000;+const PROFILE_REFRESH_MS = 300_000;+/** Room notices are hints, not a complete work feed: keep a bounded fallback for unopened rooms. */+const IDLE_CLAIM_MAX_MS = 15_000;/** How often a busy companion's rooms are re-read for work queued in its other conversations. */const LANE_SWEEP_MS = 10_000;/** A room snapshot reused for a send while its realtime subscription reports no change since. */@@ -341,11 +347,24 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDlet savedShadows = JSON.stringify(deps.companionCloud?.homes.persistedShadows() ?? []);let connected = false;const current = () => !disposed && (!scope || !deps.isOwnerScopeCurrent || deps.isOwnerScopeCurrent(scope));- const history = chatLocalHistory(config.baseUrl, current);+ const displayHistory = chatLocalHistory(config.baseUrl, current);const sendJournal = chatSendJournal<SavedChatSend>(config.baseUrl, current);const executorId = `desktop:${randomUUID()}`;let actors: Actor[] = [];let selfId = '';+ const histories = new Map<string, ChatHistory>();+ const transcriptViews = new Map<string, { generation: string; cursor: string; messages: Awaited<ReturnType<typeof readAllRoomMessages>> }>();+ function history(reader = selfId): ChatHistory | undefined {+ if (!selfId || !deps.chatHistoryStore) return undefined;+ let value = histories.get(reader);+ if (!value) {+ value = createChatHistory({ api: route => api(route, 'GET', undefined, reader === selfId ? undefined : reader),+ store: deps.chatHistoryStore(config.baseUrl, selfId, reader, current), current, newGeneration: randomUUID });+ if (connected) value.reconnect();+ histories.set(reader, value);+ }+ return value;+ }let supportsDissolve = false;let supportsListRemoval = false;let supportsMemberAvatar = false;@@ -355,7 +374,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD};personalList.subscribe(row => {if (!current()) return;- if (row.hidden) { history.forget(row.conversationId); sendJournal.forgetRoom(row.conversationId); }+ if (row.hidden) { displayHistory.forget(row.conversationId); sendJournal.forgetRoom(row.conversationId); }deps.onChanged?.({ groupId: row.conversationId, change: 'list', listState: row }, scope);for (const [source, target] of upgradedGroups) if (target === row.conversationId)deps.onChanged?.({ groupId: source, change: 'list', listState: row }, scope);@@ -367,6 +386,12 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDlet companion: CompanionCloudRuntime | undefined;let companionSelf: string | null = null;let actorsStale = false;+ let claimWakeVersion = 0;+ const unsubscribeProfiles = subscribeBotProfilesChanged(() => {+ actorsStale = true;+ claimWakeVersion++;+ idleClaims.clear();+ });// Who reacted can change while counts stay the same. A realtime reaction change versions only its// message; a reset that skipped events versions the whole room (and makes per-message versions moot).// Both ride on the group, so every loaded page and the Thread see them on refresh. A recreated runtime@@ -470,6 +495,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDconst queuedHints = new Map<string, Map<string, string>>();/** When each busy companion's own rooms are next re-read for work its realtime notices missed. */const laneSweeps = new Map<string, number>();+ const idleClaims = new Map<string, { misses: number; next: number }>();const metadata = new Map<string, Promise<void>>();/*** Followed room scopes, each with the newest cursor this process has read or acked. It only@@ -540,9 +566,10 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD},notify: deps.onChatMessageNotification,}) : undefined;- const changed = (roomId: string) => {+ const changed = (roomId: string, synchronized = false) => {if (!current()) return;invalidate(roomId);+ if (!synchronized) history()?.invalidate(roomId);if (pendingChanges.has(roomId)) return;pendingChanges.set(roomId, setTimeout(() => {pendingChanges.delete(roomId);@@ -628,7 +655,9 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD}const media = createChatMedia(api, current, deps.log, { allowLoopback: !app.isPackaged && process.env.XDT_ISOLATED === '1' && config.baseUrl === 'http://127.0.0.1:3018' });const threads = createThreadProjection<Message>({- threadPage: (roomId, rootId, limit, before) => api<Message[]>(`/conversations/${roomId}/messages?threadRootId=${rootId}&limit=${limit}${before ? `&before=${before}` : ''}`),+ threadPage: (roomId, rootId, limit, before) => history()?.page<Message>(roomId,+ new URLSearchParams({ threadRootId: rootId, limit: String(limit), ...(before ? { before } : {}) }))+ ?? api<Message[]>(`/conversations/${roomId}/messages?threadRootId=${rootId}&limit=${limit}${before ? `&before=${before}` : ''}`),// The same visibility rule as every other single-message read.message: async (roomId, messageId) => await readMessage(roomId, messageId) ?? null,filled: roomId => changed(roomId),@@ -783,7 +812,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD}/*** Read and send paths use the registration they already have and refresh it in the background- * (same five-second throttle, 60-second profile refresh and auth backoff as before); only the+ * (one-minute actor refresh, five-minute profile refresh and the auth backoff); only the* first registration of this account is awaited. Management paths that map local companions to* actors still await `register()`.*/@@ -796,7 +825,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDlet registryKey = '';async function register() {if (refreshActors) return refreshActors;- if (Date.now() - registeredAt < 5000 && !actorsStale) return;+ if (selfId && Date.now() - registeredAt < ACTOR_REFRESH_MS && !actorsStale) return;refreshActors = (async () => {actorsStale = false;profiles = await getDbClient().drizzle.select().from(botProfiles).where(undefined);@@ -812,7 +841,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD// a server without the capability never sees the field (its strict contract would reject it).directRoomClaims = companionHome && me.capabilities?.directRoomClaim === true;// Refresh from the issuing auth server, never overwrite with a stale device cache.- if (Date.now() - profileRefreshedAt > 60000) {+ if (Date.now() - profileRefreshedAt > PROFILE_REFRESH_MS) {await api('/profile/refresh', 'POST').then(() => { profileRefreshedAt = Date.now(); }).catch(() => undefined);}actors = await api<Actor[]>('/actors');@@ -843,7 +872,12 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD// refresh, or actor.changed racing its own list notice): tell them to read again.if (replaced) { changed(''); for (const roomId of rooms.keys()) changed(roomId); }}- })().finally(() => { refreshActors = undefined; });+ })().catch(error => {+ // A forced refresh consumes the stale flag before I/O. On failure, keep it+ // pending so a recent successful pass cannot defer recovery for a minute.+ actorsStale = true;+ throw error;+ }).finally(() => { refreshActors = undefined; });return refreshActors;}/** Claim empty homes for this computer and publish where every companion runs. */@@ -859,6 +893,28 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDif (companion && companionSelf !== self) { companion.dispose(); companion = undefined; }companionSelf = self;companion ??= startCompanionCloud({ api, host, endpoint: config.baseUrl, humanActorId: selfId, selfDeviceId: self, current, log: deps.log,+ transcript: deps.chatHistoryStore ? async (roomId, actorId, refresh) => {+ // Keep message-time ordering for imported history, but reuse covered pages after delta sync.+ const cache = history()!;+ const key = `${actorId}:${roomId}`;+ if (refresh) cache.invalidate(roomId);+ for (let attempt = 0; attempt < 3; attempt++) {+ const snapshot = await cache.snapshot(roomId);+ const previous = transcriptViews.get(key);+ // Even older pages pass ensure() for expiry, reconnect and authorization.+ // Unchanged room revisions can reuse the sorted transcript without rescanning 500 pages.+ if (previous?.generation === snapshot.cacheGeneration && previous.cursor === snapshot.cursor) return previous.messages;+ const messages = await readAllRoomMessages(async <T>(route: string): Promise<T> => {+ const query = new URL(`https://chat.invalid${route}`).searchParams;+ return await cache.page(roomId, query) as T;+ }, roomId, actorId);+ if (cache.generation(roomId) === snapshot.cacheGeneration) {+ transcriptViews.set(key, { generation: snapshot.cacheGeneration, cursor: snapshot.cursor, messages });+ return messages;+ }+ }+ throw new Error('CHAT_HISTORY_CHANGED');+ } : undefined,bots: () => actors.filter(a => a.kind === 'bot' && !a.disabled && a.homeDeviceId === self && localBot(a.id)?.status === 'active'&& !companion?.isShadowed(a.externalId)).map(a => ({ botId: a.externalId, actorId: a.id, name: a.name })),paused: botId => profiles.find(p => p.id === botId)?.status === 'paused',@@ -926,12 +982,16 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDif (!current() || socket !== ws) { ws.close(); return; }ws.send(JSON.stringify({ type: 'auth', token: getAccessToken() }));});- ws.on('message', raw => {+ let frames = Promise.resolve();+ ws.on('message', raw => { frames = frames.then(async () => {if (!current() || socket !== ws) return;try {const event = JSON.parse(String(raw));if (event.type === 'ready') {memberJoinedClaims = true;+ claimWakeVersion++;+ idleClaims.clear();+ for (const cache of histories.values()) cache.reconnect();reconnectDelay = 500; connected = true;threads.reset();// Replay and list sync may lag behind ready. Fence all snapshot reads,@@ -943,10 +1003,11 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDfor (const [roomId, cursor] of rooms) ws.send(JSON.stringify({ type: 'subscribe', scope: `conversation:${roomId}`, after: cursor }));void syncPersonalList(true).then(() => { if (current() && socket === ws) { for (const roomId of rooms.keys()) { changed(roomId); autoContinuePlans(roomId); } changed(''); } }).catch(() => ws.close());} else if (event.type === 'changes') {- // This adapter stores no client history. Each invalidation re-reads authoritative- // state; a reconnect resumes after the last cursor this process has read or acked.+ // Durable UI projections commit before ACK. Serial frames preserve the cursor order.if (event.scope.startsWith('conversation:')) {const roomId = event.scope.slice(13);+ await history()?.receive(roomId, event, rooms.get(roomId));+ if (!current() || socket !== ws) return;if ((event.changes ?? []).some((change: { type?: string; data?: { dissolvedAt?: unknown } }) => change.type === 'conversation.updated' && change.data?.dissolvedAt)) retirePlanning(roomId);if (rooms.has(roomId)) advanceRoom(roomId, event.cursor);for (const change of event.changes ?? []) {@@ -955,7 +1016,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDif (change.type === 'message.updated' || change.type === 'message.deleted') threads.invalidate(roomId, change.entityId);if (change.type === 'reaction.changed' && typeof change.entityId === 'string') bumpMessageReactions(roomId, change.entityId);}- changed(roomId);+ changed(roomId, true);const changes: unknown[] = Array.isArray(event.changes) ? event.changes : [];const types = changes.map(change => (change as { type?: unknown } | null)?.type);// Lease renewals append no change; ordinary chatter cannot revoke a lease, so it does@@ -985,9 +1046,11 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDif (change.type === 'conversation.updated' && change.data?.dissolvedAt) retirePlanning(change.entityId);if (change.type === 'membership.changed' || change.type === 'conversation.updated') changed(change.entityId);// A Thread read on another device clears its unread here too.- if (change.type === 'read.changed' && typeof change.entityId === 'string') changed(change.entityId);+ if (change.type === 'read.changed' && typeof change.entityId === 'string') {+ history()?.invalidate(change.entityId, true); changed(change.entityId);+ }}- if (companionHome && (event.changes ?? []).some((change: { type?: unknown }) => change?.type === 'actor.changed')) void refreshHomes();+ if ((event.changes ?? []).some((change: { type?: unknown }) => change?.type === 'actor.changed')) void refreshHomes();changed('');}ws.send(JSON.stringify({ type: 'ack', scope: event.scope, cursor: event.cursor }));@@ -996,6 +1059,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDif (event.error?.code !== 'RESET_REQUIRED' || typeof head !== 'string' || !/^\d+$/.test(head)) { ws.close(); return; }void (async () => {if (supportsListRemoval) await personalList.resync(api);+ for (const cache of histories.values()) cache.reconnect();if (!current() || socket !== ws || ws.readyState !== WebSocket.OPEN) return;for (const roomId of rooms.keys()) changed(roomId);changed('');@@ -1003,6 +1067,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD})().catch(() => ws.close());} else if (event.type === 'scope_error' && event.scope.startsWith('conversation:')) {const roomId = event.scope.slice(13);+ await history()?.clear(roomId);if (event.error?.code === 'RESET_REQUIRED') {void api<Snapshot>(`/conversations/${roomId}/snapshot`).then(value => {if (!current() || socket !== ws || ws.readyState !== WebSocket.OPEN) return;@@ -1015,18 +1080,19 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD}).catch(() => ws.close());} else {rooms.delete(roomId);- history.forget(roomId); sendJournal.forgetRoom(roomId);+ displayHistory.forget(roomId); sendJournal.forgetRoom(roomId);// Access may come back with a narrower history; re-read every reference.threads.reset();changed(roomId);}}} catch { ws.close(); }- });+ }).catch(() => ws.close()); });ws.on('error', () => ws.close());ws.on('close', () => {if (!current() || socket !== ws) return;connected = false;+ for (const cache of histories.values()) cache.reconnect();reconnect = setTimeout(connect, reconnectDelay);reconnectDelay = Math.min(reconnectDelay * 2, 15000);});@@ -1294,6 +1360,14 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDreturn { version, updates: Object.fromEntries(shownShares.filter(share => !byId.has(share.id)).map(({ id: shareId, sharerId, ...card }) =>[shareId, shareView(card, sharerId && (actors.find(actor => actor.externalId === sharerId)?.id ?? sharerId))])) };}+ async function writeReadState<T = unknown>(roomId: string, data: Record<string, unknown>): Promise<T> {+ const value = await api<T>(`/conversations/${roomId}/read`, 'POST', data);+ // Reads/follows advance actor scope, not the conversation cursor. Apply the+ // same metadata invalidation for every local writer, even without a WS echo.+ history()?.invalidate(roomId, true);+ changed(roomId);+ return value;+ }/*** The reader is looking at this Thread's latest page: move its server read position to the* newest reply read. Only a forward move is written, so the refresh it causes writes nothing.@@ -1307,8 +1381,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDconst newest = newestFirst.reduce((max, m) => BigInt(m.seq) > max ? BigInt(m.seq) : max, BigInt(root.seq));if (newest > before) {try {- await api(`/conversations/${roomId}/read`, 'POST', { operationId: randomUUID(), threadRootId: root.id, readSeq: String(newest) });- changed(roomId);+ await writeReadState(roomId, { operationId: randomUUID(), threadRootId: root.id, readSeq: String(newest) });} catch (error) {deps.log?.warn('Chat thread read not recorded', { groupId: roomId, ...chatErrorDiagnostic(error) });}@@ -1326,12 +1399,11 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDconst read = s.reads.find(entry => entry.thread_key === rootId);if (next === undefined) return read?.following === true;// The read position the server keeps never moves back, so restating it changes nothing else.- const written = await api<{ following: boolean }>(`/conversations/${roomId}/read`, 'POST', {+ const written = await writeReadState<{ following: boolean }>(roomId, {operationId: randomUUID(), threadRootId: rootId, readSeq: read?.read_seq ?? '0', following: next });- changed(roomId);return written.following;}- async function detail(roomId: string, options?: unknown, summaryOnly = false): Promise<BotGroupDetail> {+ async function detail(roomId: string, options?: unknown, summaryOnly = false, attempt = 0): Promise<BotGroupDetail> {id.parse(roomId);const o = z.object({ conversationKind: z.literal('direct').optional(), beforeSequence: z.number().int().positive().optional(), limit: z.number().int().min(1).max(100).optional(),sourceMessageIds: z.array(id).optional(),@@ -1344,9 +1416,17 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD// A followed room reports every later change, so its snapshot may run alongside. A new// room first takes the snapshot cursor it will follow from, before the rest is read.const direct = o.conversationKind === 'direct';- const snapshotRead = direct ? directSnapshot(roomId) : groupSnapshot(roomId);+ let cacheGeneration: string | undefined;+ const snapshotRead = deps.chatHistoryStore ? (async () => {+ await ensureRegistered();+ const value = await history()!.snapshot<Snapshot>(roomId);+ cacheGeneration = value.cacheGeneration;+ if (direct ? value.room.kind !== 'direct' : !isGroupRoom(value.room)) throw new Error('NOT_A_GROUP');+ subscribe(roomId, value.cursor);+ return value;+ })() : direct ? directSnapshot(roomId) : groupSnapshot(roomId);if (!rooms.has(roomId)) await snapshotRead;- const messagesRead = summaryOnly ? null : api<Message[]>(`/conversations/${roomId}/messages?${query}`);+ const messagesRead = summaryOnly ? null : history()?.page<Message>(roomId, query) ?? api<Message[]>(`/conversations/${roomId}/messages?${query}`);const executionsRead = direct ? Promise.resolve([] as Execution[]) : api<Execution[]>(`/conversations/${roomId}/executions`);for (const read of [messagesRead, executionsRead]) read?.catch(() => undefined);const s = await snapshotRead;@@ -1376,13 +1456,20 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDif (deciding) speakers.push({ botId: deciding.botId, sessionId: null, activity: 'planning' });// Sidebar refresh must not download every attachment in every group's history.const messages = summaryOnly ? [] : await messageViews(roomId, page, s.members, ownerMembers);- const shares = summaryOnly || direct ? undefined : await decorateThreads(roomId, messages, page, s.messages, s.members, true, o.shownShares);+ const projection = !summaryOnly ? await history()?.projection<Message>(roomId, o.sourceMessageIds ?? []) : undefined;+ const messageUpdates = projection ? await messageViews(roomId, projection.messages, s.members, ownerMembers) : undefined;+ const shares = summaryOnly || direct ? undefined : await decorateThreads(roomId, [...messages, ...(messageUpdates ?? [])],+ [...page, ...(projection?.messages ?? [])], s.messages, s.members, true, o.shownShares);+ if (cacheGeneration && history()?.generation(roomId) !== cacheGeneration) {+ if (attempt >= 2) throw new Error('CHAT_HISTORY_CHANGED');+ return detail(roomId, options, summaryOnly, attempt + 1);+ }const threadShareUpdates = shares?.updates;const reads = threadReads(s);const unread = reads ? s.messages.filter(m => !m.deleted && m.origin !== 'system' && m.origin !== 'import' && m.authorId !== selfId&& (!m.threadRootId || m.mentions?.includes(selfId) || s.reads?.some(read => read.thread_key === m.threadRootId && read.following))&& BigInt(m.seq) > (reads.get(m.threadRootId ?? 'main') ?? 0n)) : null;- if (reads) for (const view of messages) if (!view.threadRootId && (view.replyCount ?? 0) > 0) view.threadUnread = threadUnread(view.id, s.messages, reads);+ if (reads) for (const view of [...messages, ...(messageUpdates ?? [])]) if (!view.threadRootId && (view.replyCount ?? 0) > 0) view.threadUnread = threadUnread(view.id, s.messages, reads);const threadList = reads && !direct ? threadSummaries(roomId, s, page, reads) : undefined;messages.sort((a, b) => a.sequence - b.sequence);const last = s.messages[0];@@ -1411,7 +1498,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDincomingMessageTimes: incomingMessageTimes(s.messages, s.members),...(unread ? { serverUnread: { count: Math.min(99, unread.length), mentioned: unread.some(m => m.mentions?.includes(selfId)) } } : {}),createdAt: Date.parse(s.room.created_at), updatedAt: Date.parse(s.room.updated_at ?? s.room.created_at),- messages, executionFailures, ...(threadShareUpdates && Object.keys(threadShareUpdates).length ? { threadShareUpdates } : {}),+ messages, ...(projection ? { historyRevision: projection.generation, messageUpdates } : {}), executionFailures, ...(threadShareUpdates && Object.keys(threadShareUpdates).length ? { threadShareUpdates } : {}),...(shares ? { threadShareVersion: shares.version } : {}), ...(threadList ? { threads: threadList } : {}), hasMoreBefore: page.length === (o.limit ?? 100), plans,round: { status: deciding || executions.some(e => ['queued', 'running'].includes(e.status)) ? 'running' : 'idle', speakers,othersActive: executions.some(e => ['queued', 'running', 'needs_input'].includes(e.status) && e.requester_id !== selfId@@ -2157,6 +2244,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDfunction forgetRun(run: Running) {running.delete(run.execution.id);const botId = run.execution.bot_id;+ idleClaims.delete(botId);if (!runsOf(botId).length) return;const hints = queuedHints.get(botId) ?? new Map<string, string>();hints.set(`room:${run.execution.conversation_id}`, run.execution.conversation_id);@@ -2227,11 +2315,22 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDsettledValues(await settleBounded(ready, ready.length, async actor => {const runs = runsOf(actor.id);if (runs.length) { await claimBesideRuns(actor.id, runs); return; }+ const idle = idleClaims.get(actor.id);+ if (idle && Date.now() < idle.next) return;// An idle companion takes the oldest work wherever it is. Notices of its other queued work stay,// so that work starts beside this turn; with nothing left to take, they are stale.laneSweeps.delete(actor.id);+ const wakeVersion = claimWakeVersion;const execution = await claim(actor.id);- if (!execution) { queuedHints.delete(actor.id); return; }+ if (!execution) {+ queuedHints.delete(actor.id);+ const misses = Math.min((idle?.misses ?? 0) + 1, 4);+ // Positive jitter prevents installations started together from staying in lockstep.+ if (wakeVersion === claimWakeVersion)+ idleClaims.set(actor.id, { misses, next: Date.now() + Math.min(2000 * 2 ** (misses - 1), IDLE_CLAIM_MAX_MS) + Math.random() * 1000 });+ return;+ }+ idleClaims.delete(actor.id);queuedHints.get(actor.id)?.delete(execution.id);void runExecution(execution);}));@@ -2246,8 +2345,10 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDreturn claiming;}let claimTrigger: ReturnType<typeof setTimeout> | undefined;- /** Claims newly queued work shortly after its realtime notice; the two-second poll stays the fallback. */+ /** A work notice bypasses idle backoff, but never the auth/rate-limit backoff. */function triggerClaim() {+ claimWakeVersion++;+ idleClaims.clear();if (claimTrigger || !current()) return;claimTrigger = setTimeout(() => {claimTrigger = undefined;@@ -2413,8 +2514,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDif (message.threadRootId) throw new Error('MAIN_MESSAGE_REQUIRED');const read = snapshot.reads.find(entry => entry.thread_key === 'main')?.read_seq ?? '0';if (BigInt(message.seq) > BigInt(read)) {- await api(`/conversations/${target}/read`, 'POST', { operationId: `read-main:${message.seq}`, readSeq: message.seq });- changed(target);+ await writeReadState(target, { operationId: `read-main:${message.seq}`, readSeq: message.seq });}return {};}@@ -2781,7 +2881,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD}),getGroup: (roomId, options) => safe(async () => {if ((options as { cacheOnly?: boolean } | undefined)?.cacheOnly === true) {- const group = history.read(id.parse(roomId));+ const group = displayHistory.read(id.parse(roomId));if (!group || personalList.hidden(group.id)) throw new Error('CONVERSATION_NOT_FOUND');return { ok: true as const, group };}@@ -2791,13 +2891,13 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDif (personalList.hidden(target)) throw new Error('CONVERSATION_NOT_FOUND');const group = await detail(target, options);if (personalList.hidden(target)) throw new Error('CONVERSATION_NOT_FOUND');- if (!(options as { beforeSequence?: number } | undefined)?.beforeSequence) history.save(target, group);+ if (!(options as { beforeSequence?: number } | undefined)?.beforeSequence) displayHistory.save(target, group);return { ok: true as const, group };}catch (error) {const failure = chatGroupFailure(error);if (['NOT_FOUND', 'PERMISSION_DENIED'].includes(failure.errorCode)) {- history.forget(id.parse(roomId)); history.forget(target); sendJournal.forgetRoom(target);+ displayHistory.forget(id.parse(roomId)); displayHistory.forget(target); sendJournal.forgetRoom(target);}throw error;}@@ -2998,7 +3098,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDif (s.members.some(m => m.ownerActorId === selfId && m.role === 'owner')) await api(`/conversations/${room}`, 'PATCH', { operationId: randomUUID(), expectedRevision: s.room.revision, archived: true }, managementActor(s));else await api(`/conversations/${room}/members`, 'POST', { operationId: randomUUID(), actorId: selfId, action: 'leave' });resolvedGroups.delete(id.parse(groupId));- history.forget(room); history.forget(id.parse(groupId)); sendJournal.forgetRoom(room);+ displayHistory.forget(room); displayHistory.forget(id.parse(groupId)); sendJournal.forgetRoom(room);changed(room); return { ok: true as const };}),continueRound: groupId => safe(async () => {@@ -3015,6 +3115,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDeditPlanStep: input => safe(() => actPlan(input, 'reassign')),dispose: () => {chatNotifications?.dispose();+ unsubscribeProfiles();disposed = true; threads.dispose(); clearInterval(timer); clearInterval(heartbeat); clearTimeout(reconnect); clearTimeout(claimTrigger); socket?.close();companion?.dispose(); companion = undefined; deps.companionCloud?.homes.reset();for (const refresh of attachmentRefreshes.values()) clearTimeout(refresh);diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex d494ba2827..b0b67dd7df 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -640,6 +640,7 @@ import {import { createBotGroupChatService, settleBotGroupLaneTerminal, type BotGroupChatService, type BotGroupChatServiceDeps, type BotGroupLaneTerminal } from './botGroupChatService.js';import { settleUndispatchedBotGroupTurn } from './botGroupRuntimeFailure.js';import { withChatServer } from './chatServer.js';+import { createSqliteChatHistoryStore } from './chatHistoryStore.js';import { showDesktopChatMessage } from '../notificationService.js';import { companionHomes, isCompanionShadowed } from '../companion-cloud/homes.js';import { createCompanionCloudHost } from '../companion-cloud/host.js';@@ -13052,6 +13053,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const companionTurnActive = (sessionId: string) => !!maker.getSession(sessionId)?.isTurnRunning?.()|| inputCoordinator.getQueueControlSnapshot(sessionId).pendingQueue.length > 0;const botGroupChatDeps: BotGroupChatServiceDeps = {+ chatHistoryStore: (endpoint, human, reader, current) => createSqliteChatHistoryStore(getDbClient(), endpoint, human, reader, current),ensureLane: async (input) => {try {return await ensureBotGroupLaneSession(input);diff --git a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsxindex 58aae4ded0..6cb844efde 100644--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx@@ -231,6 +231,7 @@ function BotGroupChatContent({ groupId, direct }: { groupId: string; direct: booconst [planPending, setPlanPending] = useState<PlanPending | null>(null);const planPendingRef = useRef(false);const loadRef = useRef<(additionalSources?: string[], changedIds?: string[]) => void>(() => {});+ const resetHistoryRef = useRef<() => void>(() => {});const scrollRef = useRef<HTMLDivElement>(null);const contentRef = useRef<HTMLDivElement>(null);const followMessageBottom = useSmoothMessageFollow(scrollRef, contentRef, state.kind === 'ready');@@ -251,6 +252,18 @@ function BotGroupChatContent({ groupId, direct }: { groupId: string; direct: booconst loadingOlderRef = useRef(false);const locatingRef = useRef(false);+ // Every older-page read belongs to the generation visible when it started. A+ // reset discovered here must also cancel in-flight latest-page/auxiliary reads.+ const acceptHistoryPage = useCallback((page: BotGroupDetail, revision: string | undefined) => {+ const current = stateRef.current;+ if (current.kind !== 'ready' || current.group.historyRevision !== revision) return false;+ if (page.historyRevision && page.historyRevision !== revision) {+ resetHistoryRef.current();+ return false;+ }+ return true;+ }, []);+useEffect(() => {let cancelled = false;const discardOutbox = () => {@@ -295,7 +308,7 @@ function BotGroupChatContent({ groupId, direct }: { groupId: string; direct: booreturn;}const displayed = stateRef.current;- if (!hasTimeline) void api.getBotGroup(groupId, { cacheOnly: true, ...(direct ? { conversationKind: 'direct' } : {}) }).then(cached => {+ if (!hasTimeline && reloadVersion === 0) void api.getBotGroup(groupId, { cacheOnly: true, ...(direct ? { conversationKind: 'direct' } : {}) }).then(cached => {if (!cached.ok || hasTimeline || !isCurrent()) return;hasTimeline = true;setState({ kind: 'ready', group: cached.group, older: [], olderPlans: [], olderHasMore: cached.group.hasMoreBefore, readToken: 0 });@@ -329,13 +342,13 @@ function BotGroupChatContent({ groupId, direct }: { groupId: string; direct: booconst changed = shown.older.filter((message) => changedIds.includes(message.id)&& !latestIds.has(message.id) && !quoted.some((target) => target.id === message.id));const targets = [...quoted, ...changed].sort((a, b) => b.sequence - a.sequence);- if (targets.length > 0) void recheckOlderCopies(api, targets, isCurrent);+ if (targets.length > 0) void recheckOlderCopies(api, targets, result.group.historyRevision, isCurrent);}if (displayed.kind === 'ready' && displayed.group.id === groupId && result.group.messages.length > 0) {const latestFrom = Math.min(...result.group.messages.map((message) => message.sequence));const refreshed = await refreshPendingBotGroupAttachments(displayed.older, latestFrom, async (before) => {const page = await api.getBotGroup(groupId, { ...(direct ? { conversationKind: 'direct' as const } : {}), beforeSequence: before });- return page.ok && isCurrent() ? page.group.messages : null;+ return page.ok && isCurrent() && acceptHistoryPage(page.group, result.group.historyRevision) ? page.group.messages : null;});if (refreshed && isCurrent()) {const fresh = new Map(refreshed.map((message) => [message.sequence, message]));@@ -394,6 +407,7 @@ function BotGroupChatContent({ groupId, direct }: { groupId: string; direct: booconst recheckOlderCopies = async (api: NonNullable<ReturnType<typeof botGroupApi>>,targets: BotGroupMessageView[],+ historyRevision: string | undefined,isCurrent: () => boolean,) => {setUnverifiedOriginals((previous) => new Set([...previous, ...targets.map((target) => target.id)]));@@ -402,7 +416,7 @@ function BotGroupChatContent({ groupId, direct }: { groupId: string; direct: boolet messages: BotGroupMessageView[] | null = null;try {const read = await api.getBotGroup(groupId, { ...(direct ? { conversationKind: 'direct' as const } : {}), beforeSequence: remaining[0]!.sequence + 1 });- messages = read.ok ? read.group.messages : null;+ messages = read.ok && isCurrent() && acceptHistoryPage(read.group, historyRevision) ? read.group.messages : null;} catch {messages = null;}@@ -424,6 +438,15 @@ function BotGroupChatContent({ groupId, direct }: { groupId: string; direct: boo}};loadRef.current = (additionalSources, changedIds) => load(additionalSources, changedIds);+ resetHistoryRef.current = () => {+ cancelled = true;+ queued = null;+ clearRetry();+ prependAnchorRef.current = null;+ stateRef.current = { kind: 'loading' };+ setState(stateRef.current);+ setReloadVersion(value => value + 1);+ };load();const unsubscribe =botGroupApi()?.onBotGroupChanged?.((payload, ownerStamp) => {@@ -449,9 +472,10 @@ function BotGroupChatContent({ groupId, direct }: { groupId: string; direct: booclearRetry();version += 1;loadRef.current = () => {};+ resetHistoryRef.current = () => {};unsubscribe();};- }, [groupId, reloadVersion, navigate]);+ }, [groupId, reloadVersion, navigate, acceptHistoryPage]);// An older page may land across a refresh. Recheck that set once per version; source// and attachment completion pushes then refresh every displayed share together.@@ -801,10 +825,12 @@ function BotGroupChatContent({ groupId, direct }: { groupId: string; direct: bootoast.error(t('bots.groupChat.timeline.loadEarlierFailed'));return null;}+ if (!acceptHistoryPage(result.group, base.group.historyRevision)) return null;// The latest page started over meanwhile (more than a page arrived): this page was read// below a timeline that is gone and would sit under the new one with the gap still in it.- const stillLoaded = (timeline: GroupViewState) => !anchorId || (timeline.kind === 'ready'- && (timeline.group.messages.some(message => message.id === anchorId) || timeline.older.some(message => message.id === anchorId)));+ const stillLoaded = (timeline: GroupViewState) => timeline.kind === 'ready'+ && timeline.group.historyRevision === base.group.historyRevision+ && (!anchorId || timeline.group.messages.some(message => message.id === anchorId) || timeline.older.some(message => message.id === anchorId));if (!stillLoaded(stateRef.current)) return null;const element = scrollRef.current;const current = stateRef.current;@@ -819,10 +845,16 @@ function BotGroupChatContent({ groupId, direct }: { groupId: string; direct: booconst executionFailures = previous.group === base.group? result.group.executionFailures ?? previous.group.executionFailures: previous.group.executionFailures;+ const updates = new Map(previous.group === base.group ? result.group.messageUpdates?.map(message => [message.id, message]) : []);+ const applyUpdates = (messages: BotGroupMessageView[]) => updates.size+ ? messages.map(message => updates.get(message.id) ?? message) : messages;+ const older = previous.group === base.group+ ? mergeBotGroupMessages(previous.older, result.group.messages)+ : mergeBotGroupMessages(result.group.messages, previous.older);return {...previous,- group: { ...previous.group, executionFailures },- older: mergeBotGroupMessages(previous.older, result.group.messages),+ group: { ...previous.group, messages: applyUpdates(previous.group.messages), executionFailures },+ older: applyUpdates(older),olderPlans: mergeBotGroupPlans(result.group.plans, previous.olderPlans),olderHasMore: result.group.hasMoreBefore,};diff --git a/apps/desktop/src/renderer/features/bots/BotGroupTimelineModel.ts b/apps/desktop/src/renderer/features/bots/BotGroupTimelineModel.tsindex af7e4a387e..51e59e4a0b 100644--- a/apps/desktop/src/renderer/features/bots/BotGroupTimelineModel.ts+++ b/apps/desktop/src/renderer/features/bots/BotGroupTimelineModel.ts@@ -101,6 +101,9 @@ export function mergeBotGroupLatestPage(previous: BotGroupLoadedTimeline,next: BotGroupDetail,): BotGroupLoadedTimeline {+ if (next.historyRevision && next.historyRevision !== previous.group.historyRevision) {+ return { group: next, older: [], olderPlans: [], olderHasMore: next.hasMoreBefore };+ }const page = next.messages;const floor = page.reduce((min, message) => Math.min(min, message.sequence), Number.POSITIVE_INFINITY);const ceiling = previous.group.messages.reduce((max, message) => Math.max(max, message.sequence), Number.NEGATIVE_INFINITY);@@ -123,9 +126,11 @@ export function mergeBotGroupLatestPage(const pushedOut = next.hasMoreBefore? previous.group.messages.filter((message) => message.sequence < floor): [];+ const updates = new Map(next.messageUpdates?.map(message => [message.id, message]));+ const refreshedOlder = updates.size ? stabilizeById(previous.older, previous.older.map(message => updates.get(message.id) ?? message)) : previous.older;const older = withThreadUnread(pushedOut.length > 0- ? stabilizeById(previous.older, mergeBotGroupMessages(previous.older, pushedOut))- : previous.older, next.threads);+ ? stabilizeById(refreshedOlder, mergeBotGroupMessages(refreshedOlder, pushedOut.map(message => updates.get(message.id) ?? message)))+ : refreshedOlder, next.threads);// The first rows moving down take over what the old latest page said about earlier history.const olderHasMore = pushedOut.length > 0 && previous.older.length === 0 ? previous.group.hasMoreBefore : previous.olderHasMore;const messages = stabilizeById(previous.group.messages, page, previous.older);diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsxindex d0722ec6ac..9e85045952 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx@@ -30,6 +30,7 @@ const mocks = vi.hoisted(() => ({groupId: 'g1',navigate: vi.fn(),getBotGroup: vi.fn(),+ cachedGroup: null as BotGroupDetail | null,sendBotGroupMessage: vi.fn(),stopBotGroupRound: vi.fn(),continueBotGroupRound: vi.fn(),@@ -285,6 +286,7 @@ beforeEach(() => {mocks.toastError.mockReset();mocks.toastInfo.mockReset();mocks.pushes = [];+ mocks.cachedGroup = null;mocks.getBotGroup.mockReset().mockResolvedValue({ ok: true, group: detail() });mocks.sendBotGroupMessage.mockReset().mockResolvedValue({ ok: true, messageId: 'u2' });mocks.stopBotGroupRound.mockReset().mockResolvedValue({ ok: true });@@ -324,7 +326,9 @@ beforeEach(() => {maker: {chatServer: { thread: mocks.thread, reply: mocks.reply, shareToMain: mocks.shareToMain, reactors: vi.fn(async () => ({ ok: true, reactors: [] })) },listBotGroups: vi.fn(async () => ({ ok: true, groups: [] })),- getBotGroup: (...args: unknown[]) => (args[1] as { cacheOnly?: boolean } | undefined)?.cacheOnly ? Promise.resolve({ ok: false, errorCode: 'NOT_FOUND' }) : mocks.getBotGroup(...args),+ getBotGroup: (...args: unknown[]) => (args[1] as { cacheOnly?: boolean } | undefined)?.cacheOnly+ ? Promise.resolve(mocks.cachedGroup ? { ok: true, group: mocks.cachedGroup } : { ok: false, errorCode: 'NOT_FOUND' })+ : mocks.getBotGroup(...args),sendBotGroupMessage: (...args: unknown[]) => mocks.sendBotGroupMessage(...args),stopBotGroupRound: (...args: unknown[]) => mocks.stopBotGroupRound(...args),continueBotGroupRound: (...args: unknown[]) => mocks.continueBotGroupRound(...args),@@ -961,16 +965,83 @@ describe('BotGroupChatView', () => {const pending = new Promise<{ ok: true; group: BotGroupDetail }>(resolve => { finish = resolve; });mocks.getBotGroup.mockResolvedValueOnce({ ok: true, group: detail({ messages: [latest], hasMoreBefore: true, executionFailures: [failure] }) }).mockReturnValueOnce(pending)- .mockResolvedValue({ ok: true, group: detail({ name: 'Fresh group', messages: [latest], executionFailures: [] }) });+ .mockResolvedValue({ ok: true, group: detail({ name: 'Fresh group', messages: [{ ...latest, content: 'Fresh question' }], executionFailures: [] }) });renderView();fireEvent.click(await screen.findByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));await act(async () => mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'round' })));await screen.findByText('Fresh group');- await act(async () => finish?.({ ok: true, group: detail({ messages: [source], executionFailures: [failure] }) }));+ await act(async () => finish?.({ ok: true, group: detail({ messages: [source], messageUpdates: [latest], executionFailures: [failure] }) }));expect(screen.getByText('Earlier question')).toBeTruthy();+ expect(screen.getByText('Fresh question')).toBeTruthy();+ expect(screen.queryByText('Latest question')).toBeNull();expect(screen.queryByText('bots.groupChat.notice.runtimeFailure.AUTH_REQUIRED:Bot')).toBeNull();});+ // PR #7242: latest-page tests did not cover a reset first discovered by pagination,+ // or an in-flight page from the previous generation. Unit: exercise the real view.+ it('discards the entire visible history when an older page reports a new history revision', async () => {+ const latest = msg({ id: 'latest', sequence: 100, content: 'Old latest' });+ const older = msg({ id: 'older', sequence: 50, content: 'Old earlier' });+ let finish: ((result: { ok: true; group: BotGroupDetail }) => void) | undefined;+ let finishStaleRefresh: ((result: { ok: true; group: BotGroupDetail }) => void) | undefined;+ const pending = new Promise<{ ok: true; group: BotGroupDetail }>(resolve => { finish = resolve; });+ const staleRefresh = new Promise<{ ok: true; group: BotGroupDetail }>(resolve => { finishStaleRefresh = resolve; });+ mocks.getBotGroup.mockResolvedValueOnce({ ok: true, group: detail({ historyRevision: 'a', messages: [latest], hasMoreBefore: true }) })+ .mockResolvedValueOnce({ ok: true, group: detail({ historyRevision: 'a', messages: [older], hasMoreBefore: true }) })+ .mockReturnValueOnce(staleRefresh)+ .mockResolvedValueOnce({ ok: true, group: detail({ historyRevision: 'b', messages: [], hasMoreBefore: false }) })+ .mockReturnValueOnce(pending);+ renderView();+ fireEvent.click(await screen.findByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));+ await screen.findByText('Old earlier');+ // The independent display cache can still hold the revoked window while delta sync resets.+ mocks.cachedGroup = detail({ historyRevision: 'a', messages: [latest], hasMoreBefore: true });+ await act(async () => mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'messages' })));+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' })));+ expect(screen.queryByText('Old earlier')).toBeNull();+ expect(screen.queryByText('Old latest')).toBeNull();+ expect(mocks.getBotGroup.mock.calls.at(-1)).toEqual(['g1', undefined]);+ await act(async () => finishStaleRefresh?.({ ok: true, group: detail({ historyRevision: 'a', messages: [latest], hasMoreBefore: true }) }));+ expect(screen.queryByText('Old latest')).toBeNull();+ await act(async () => finish?.({ ok: true, group: detail({ historyRevision: 'b', messages: [msg({ id: 'new', content: 'New history' })] }) }));+ expect(screen.getByText('New history')).toBeTruthy();+ expect(screen.queryByText('Old latest')).toBeNull();+ });++ it('ignores a late older page from a previous history revision even when the anchor survives', async () => {+ const latest = msg({ id: 'latest', sequence: 100, content: 'Old latest' });+ let finish: ((result: { ok: true; group: BotGroupDetail }) => void) | undefined;+ const pending = new Promise<{ ok: true; group: BotGroupDetail }>(resolve => { finish = resolve; });+ mocks.getBotGroup.mockResolvedValueOnce({ ok: true, group: detail({ historyRevision: 'a', messages: [latest], hasMoreBefore: true }) })+ .mockReturnValueOnce(pending)+ .mockResolvedValue({ ok: true, group: detail({ historyRevision: 'b', messages: [{ ...latest, content: 'New latest' }], hasMoreBefore: true }) });+ renderView();+ fireEvent.click(await screen.findByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));+ await act(async () => mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'messages' })));+ await screen.findByText('New latest');+ await act(async () => finish?.({ ok: true, group: detail({ historyRevision: 'a', messages: [msg({ id: 'old', content: 'Revoked history' })] }) }));+ expect(screen.queryByText('Revoked history')).toBeNull();+ expect(screen.getByText('New latest')).toBeTruthy();+ expect(mocks.getBotGroup).toHaveBeenCalledTimes(3);+ });++ it('applies pagination message updates to both the latest page and previously loaded history', async () => {+ const latest = msg({ id: 'latest', sequence: 100, content: 'Unedited latest' });+ const older = msg({ id: 'older', sequence: 50, content: 'Undeleted earlier' });+ mocks.getBotGroup.mockResolvedValueOnce({ ok: true, group: detail({ historyRevision: 'a', messages: [latest], hasMoreBefore: true }) })+ .mockResolvedValueOnce({ ok: true, group: detail({ historyRevision: 'a', messages: [older], hasMoreBefore: true }) })+ .mockResolvedValueOnce({ ok: true, group: detail({ historyRevision: 'a', messages: [], messageUpdates: [+ { ...latest, content: 'Edited latest' }, { ...older, content: '', deleted: true },+ ] }) });+ renderView();+ fireEvent.click(await screen.findByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));+ await screen.findByText('Undeleted earlier');+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' })));+ expect(screen.queryByText('Undeleted earlier')).toBeNull();+ expect(screen.queryByText('Unedited latest')).toBeNull();+ expect(screen.getByText('Edited latest')).toBeTruthy();+ });+it('drops an older page that answers after the latest page started over', async () => {const latest = msg({ id: 'latest', sequence: 100, content: 'Latest question' });const source = msg({ id: 'older', sequence: 4, content: 'Earlier question' });diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupTimelineModel.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupTimelineModel.test.tsindex 37e4d55d0d..decaa2bb41 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupTimelineModel.test.ts+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupTimelineModel.test.ts@@ -41,6 +41,16 @@ const page = (from: number, to: number) => Array.from({ length: to - from + 1 },msg({ id: `m${from + index}`, sequence: from + index, content: `第 ${from + index} 条` }));describe('push refresh merge', () => {+ // Unit: edits/deletions of already opened history must arrive without reloading every page.+ it('applies historical message projections and discards all pages across a history reset', () => {+ const first: BotGroupLoadedTimeline = { group: { ...detail(page(10, 12), true), historyRevision: 'a' }, older: page(1, 3), olderPlans: [], olderHasMore: true };+ const edited = { ...first.older[0]!, content: 'edited remotely' };+ const deleted = { ...first.older[1]!, deleted: true, content: '' };+ const next = { ...first.group, messageUpdates: [edited, deleted] };+ const merged = mergeBotGroupLatestPage(first, next);+ expect(merged.older).toEqual([edited, deleted, first.older[2]]);+ expect(mergeBotGroupLatestPage(merged, { ...next, historyRevision: 'b', messageUpdates: [] }).older).toEqual([]);+ });it('keeps rows pushed out of the latest page instead of leaving a gap', () => {const first: BotGroupLoadedTimeline = { group: detail(page(1, 3), true), older: [], olderPlans: [], olderHasMore: false };// Two new messages arrive; a three-message page no longer covers 1 and 2.diff --git a/apps/mobile/src/__tests__/chatHistoryStore.test.ts b/apps/mobile/src/__tests__/chatHistoryStore.test.tsnew file mode 100644index 0000000000..588da7da51--- /dev/null+++ b/apps/mobile/src/__tests__/chatHistoryStore.test.ts@@ -0,0 +1,91 @@+import { beforeEach, expect, it, vi } from 'vitest';+const disk = vi.hoisted(() => new Map<string, string>());+const files = vi.hoisted(() => new Map<string, string>());+const io = vi.hoisted(() => ({+ read: vi.fn(async (key: string) => files.get(key) ?? null),+ write: vi.fn(async (key: string, value: string) => { files.set(key, value); }),+ remove: vi.fn(async (key: string) => { files.delete(key); }),+ files: vi.fn(async () => [...files.keys()]),+}));+vi.mock('@/session/historyDiskStoreExpo', () => ({ createHistoryDiskIO: () => io }));+vi.mock('@/session/cacheWriteNotice', () => ({ notifyCacheWriteFailure: vi.fn() }));+vi.mock('@react-native-async-storage/async-storage', () => ({ default: {+ getItem: async (key: string) => disk.get(key) ?? null,+ setItem: async (key: string, value: string) => {+ const total = [...disk].filter(([existing]) => existing !== key).reduce((sum, [, text]) => sum + text.length, value.length);+ if (total > 6 * 1024 * 1024) throw new Error('SQLITE_FULL');+ disk.set(key, value);+ },+ removeItem: async (key: string) => { disk.delete(key); },+} }));+import { createMobileChatHistoryStore, clearMobileChatHistoryStore } from '@/chat/chatHistoryStore';+import type { ChatHistoryState } from '@cindy/maker-shared/chat-history';+const state: ChatHistoryState = { generation: 'a', cursor: '12', metadataDirty: false,+ snapshot: { room: { id: 'room' }, cursor: '12', messages: [] }, pages: { 'limit=100': ['m'] }, messages: { m: { id: 'm', seq: '1', revision: 2, deleted: true } } };+const store = (owner = 'owner', realm = 'global', endpoint = 'https://chat.example', human = 'human', current = () => true) =>+ createMobileChatHistoryStore(owner, realm, endpoint, human, current);+beforeEach(() => { disk.clear(); files.clear(); vi.clearAllMocks(); });+// Unit: actual mobile storage entry points, not native mocks of the cache algorithm.+it('restores data and cursor together and partitions owner, region, server and verified identity', async () => {+ const first = store(); await first.read('room'); await first.write('room', state);+ expect(await store().read('room')).toEqual(state);+ for (const other of [store('other'), store(undefined, 'cn'), store(undefined, undefined, 'https://other.example'), store(undefined, undefined, undefined, 'other-human')])+ expect(await other.read('room')).toBeUndefined();+ let current = true; const old = store(undefined, undefined, undefined, undefined, () => current);+ await old.read('room'); current = false;+ await expect(old.write('room', null)).rejects.toThrow('OWNER_CHANGED');+ expect(await store().read('room')).toEqual(state);+});+it('prevents concurrent mounts from overwriting a newer durable cursor', async () => {+ const a = store(), b = store(); await a.read('room'); await b.read('room');+ await a.write('room', state);+ // A stale revocation/cleanup cannot erase another mount's newer commit.+ await expect(b.write('room', null)).rejects.toThrow('CHAT_CACHE_CONFLICT');+ await expect(b.write('room', { ...state, cursor: '3' })).rejects.toThrow('CHAT_CACHE_CONFLICT');+ expect(await store().read('room')).toEqual(state);+ await b.read('room'); await a.write('room', null);+ await a.write('room', { ...state, generation: 'rebuilt' });+ await expect(b.write('room', null)).rejects.toThrow('CHAT_CACHE_CONFLICT');+ await expect(b.write('room', state)).rejects.toThrow('CHAT_CACHE_CONFLICT');+ expect(await store().read('room')).toMatchObject({ generation: 'rebuilt', cursor: '12' });+ await a.write('room', null); expect(await b.read('room')).toBeUndefined();+});++// Unit regression: each room is below the old per-value cap, but their total exceeds+// Android AsyncStorage's shared budget and used to break unrelated draft/outbox writes.+it('persists many room histories without consuming the preferences database', async () => {+ const cache = store();+ const large = { ...state, messages: { m: { ...state.messages.m, text: 'x'.repeat(250_000) } } };+ for (let index = 0; index < 30; index++) await cache.write(`room-${index}`, large);+ expect(await store().read('room-29')).toEqual(large);+ expect(disk.size).toBe(0);+});++// Unit: logout must drain a native write already in flight before deleting files,+// and revoke its old instance even when its caller has not rerendered yet.+it('drains a delayed write on account cleanup and fences old and queued instances', async () => {+ const old = store(); await old.write('room', state);+ let finish!: () => void;+ io.write.mockImplementationOnce(async (key, value) => {+ await new Promise<void>(resolve => { finish = resolve; }); files.set(key, value);+ });+ const pending = old.write('room', { ...state, cursor: '13' });+ const rejected = expect(pending).rejects.toThrow('OWNER_CHANGED');+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'), { interval: 1 });+ const clearing = clearMobileChatHistoryStore();+ await expect(old.write('another', state)).rejects.toThrow('OWNER_CHANGED');+ finish(); await rejected; await clearing;+ expect(files.size).toBe(0);+ await expect(old.read('room')).rejects.toThrow('OWNER_CHANGED');+ expect(await store().read('room')).toBeUndefined();+});++it('attempts every deletion and retries failures before a new account can persist', async () => {+ const old = store(); await old.write('a', state); await old.write('b', state);+ io.remove.mockRejectedValueOnce(new Error('busy'));+ await expect(clearMobileChatHistoryStore()).rejects.toThrow('Chat cache cleanup failed');+ expect(files.size).toBe(1);+ await clearMobileChatHistoryStore(); expect(files.size).toBe(0);+ const next = store('new-owner'); await next.write('room', state);+ expect(await next.read('room')).toEqual(state);+});diff --git a/apps/mobile/src/__tests__/chatServerEndpointDiscovery.test.tsx b/apps/mobile/src/__tests__/chatServerEndpointDiscovery.test.tsxindex d675b27ef1..a4ca26a54a 100644--- a/apps/mobile/src/__tests__/chatServerEndpointDiscovery.test.tsx+++ b/apps/mobile/src/__tests__/chatServerEndpointDiscovery.test.tsx@@ -12,6 +12,7 @@ const h = vi.hoisted(() => ({history: new Map<string, string>(),sockets: [] as any[],}));+vi.mock('expo-crypto', () => ({ randomUUID: () => 'fixture-generation' }));vi.mock('@/auth/AuthContext', () => ({ useAuth: () => h.auth }));vi.mock('@react-native-async-storage/async-storage', () => ({ default: {getItem: async (key: string) => h.storage.get(key) ?? null,@@ -76,7 +77,7 @@ beforeEach(() => {if (path.endsWith('/snapshot')) return { room, members: [], messages: [], cursor: '1' };if ((path.endsWith('/executions') || path.includes('/execution-failures?'))) return [];if (path.includes('/messages?')) return [];- if (path.includes('/changes?')) return { head: '1' };+ if (path.includes('/changes?')) return { head: '1', cursor: '1', changes: [], hasMore: false };if (options.method === 'POST') return { id: self };throw new Error('Unexpected fixture request');});diff --git a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsxindex 8c02223e1d..2353b0f317 100644--- a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx+++ b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx@@ -70,7 +70,7 @@ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });beforeEach(async () => {setMobileAuthOwner(null); peekChatMessages(id); await clearHistoryDisk();await clearRemoteResourceCache(); h.auth.user.id = 'owner';- await mobileDurableOutbox.activate(''); h.disk.clear(); setMobileAuthOwner('owner');+ await mobileDurableOutbox.activate(''); h.disk.clear(); h.history.clear(); setMobileAuthOwner('owner');await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);vi.clearAllMocks(); h.foreground.clear(); showChat = false; h.auth.accountGeneration = 1; h.legacy.items = []; h.targets = []; h.legacy.isOnline.mockReturnValue(false);vi.stubGlobal('WebSocket', class { close() {} });@@ -78,6 +78,7 @@ beforeEach(async () => {options.assertCurrent();if (path.startsWith('/v1/conversations?')) return [room];if (path === '/v1/me') return { actor: { id: self, kind: 'human' } };+ if (path.startsWith('/v1/changes?')) return { head: '1', cursor: '1', changes: [], hasMore: false };if (path.endsWith('/members')) return [{ id: self, kind: 'human', state: 'joined', name: 'Me', ownerActorId: self, ownerName: '', role: 'member', avatar: null }];if (path.endsWith('/snapshot')) return { room, members: [{ id: self, kind: 'human', state: 'joined', name: 'Me', ownerActorId: self, ownerName: '', role: 'member', avatar: null }], messages: [], cursor: '1' };if ((path.endsWith('/executions') || path.includes('/execution-failures?'))) return [];@@ -214,6 +215,43 @@ it('imports read_seq and acknowledges only displayed incoming messages with theiawait act(async () => { await chat.markRead!([messages[0].id, messages[1].id]); });expect(h.auth.apiFetch.mock.calls.filter(([path]) => path.endsWith('/read'))).toHaveLength(1);});+// Unit: conversation head is unchanged by another device's personal read position.+// The actual roster refresh must replace snapshot.reads even when message delta is empty.+it.each(['refresh', 'read-event', 'reconnect'] as const)('refreshes personal read metadata with an unchanged room head on %s', async trigger => {+ const sockets: Array<{ onmessage: ((event: { data: string }) => void) | null; send: ReturnType<typeof vi.fn> }> = [];+ vi.stubGlobal('WebSocket', class {+ readyState = 1; onmessage = null; onopen = null; onclose = null; onerror = null;+ send = vi.fn(); close() {}+ constructor() { sockets.push(this); }+ });+ const frame = async (value: unknown) => { await act(async () => { sockets.at(-1)!.onmessage!({ data: JSON.stringify(value) }); }); };+ let readSeq = '0';+ const reply = { id: self, seq: '5', authorId: id, author: { kind: 'human', name: 'Other' },+ content: [{ type: 'text', text: 'reply' }], createdAt: '2026-10-09T10:00:00Z', deleted: false, threadRootId: id };+ const original = h.auth.apiFetch.getMockImplementation()!;+ h.auth.apiFetch.mockImplementation(async (path, options) => {+ if (path.startsWith('/v1/conversations?')) return [{ ...room, head: '5' }];+ if (path.includes('/changes?')) return { head: '5', cursor: '5', changes: [], hasMore: false };+ const value = await original(path, options);+ return path.endsWith('/snapshot') ? { ...value, messages: [reply], cursor: '5', reads: [+ { thread_key: 'main', read_seq: '0' }, { thread_key: id, read_seq: readSeq, following: true },+ ] } : value;+ });+ await render();+ const unread = () => (roster.items[0].chatUnread?.threadCount ?? 0) > 0;+ expect(unread()).toBe(true);+ await frame({ type: 'ready', actorId: self });+ expect(sockets[0].send.mock.calls.some(([body]) => JSON.parse(body).type === 'subscribe')).toBe(true);+ readSeq = '5';+ if (trigger === 'refresh') await act(async () => { await roster.refresh(); });+ else if (trigger === 'read-event') await frame({ type: 'changes', scope: `actor:${self}`, cursor: '6',+ changes: [{ type: 'read.changed', entityId: id, data: {} }] });+ else {+ await act(async () => { for (const listener of h.foreground) listener('active'); });+ await frame({ type: 'ready', actorId: self });+ }+ expect(unread()).toBe(false);+});it('resolves everyone using authorized members at send time instead of the displayed snapshot', async () => {const joined = '00000000-0000-4000-8000-000000000003';const invited = '00000000-0000-4000-8000-000000000004';@@ -326,7 +364,7 @@ it('clears access on everyone member-read rejection and ignores an older authorih.auth.apiFetch.mockImplementation(async (path, options) => {if (path.endsWith('/members')) throw Object.assign(new Error('NOT_MEMBER'), { status: 403 });const value = await original(path, options);- if (path.endsWith('/snapshot')) await new Promise<void>(resolve => { finish = resolve; });+ if (path.startsWith('/v1/changes?')) await new Promise<void>(resolve => { finish = resolve; });return value;});await act(async () => { chat.reload(); });@@ -452,7 +490,7 @@ it('exposes an actor-scope personal hide to the current screen and clears it afth.auth.apiFetch.mockImplementation(async (path, options) => {if (path === '/v1/me') return { actor: { id: self, kind: 'human' }, capabilities: { conversationListStateVersion: 1 } };if (path.startsWith('/v1/conversation-list-state?')) return [];- if (path.startsWith('/v1/changes?')) return { head: '10' };+ if (path.startsWith('/v1/changes?scope=actor:')) return { head: '10' };return allowed(path, options);});showChat = true; await render();diff --git a/apps/mobile/src/__tests__/chatServerSubscription.test.ts b/apps/mobile/src/__tests__/chatServerSubscription.test.tsindex 483bb7cbf4..93685435f5 100644--- a/apps/mobile/src/__tests__/chatServerSubscription.test.ts+++ b/apps/mobile/src/__tests__/chatServerSubscription.test.ts@@ -8,8 +8,27 @@ function socket(): MockSocket {send: vi.fn(), close: vi.fn(() => ws.onclose?.({} as CloseEvent)) } as ChatSocket & { send: ReturnType<typeof vi.fn>; close: ReturnType<typeof vi.fn> };sockets.push(ws); return ws;}-const receive = async (ws: ChatSocket, data: unknown) => { ws.onmessage?.({ data: JSON.stringify(data) } as MessageEvent); await Promise.resolve(); await Promise.resolve(); };+const receive = async (ws: ChatSocket, data: unknown) => {+ ws.onmessage?.({ data: JSON.stringify(data) } as MessageEvent);+ // Frames now await persistence and run in order before acknowledgement.+ for (let tick = 0; tick < 8; tick++) await Promise.resolve();+};let stop = () => {};+it('acknowledges only after the changed projection is persisted and closes on a failed write', async () => {+ let finish!: () => void;+ const changed = vi.fn(() => new Promise<void>(resolve => { finish = resolve; }));+ stop = subscribeChatServer({ baseUrl: 'https://chat.example.invalid', token: async () => 'fixture', current: () => true,+ socket, ready: async () => ({ scope: `actor:${actorId}`, cursor: '0' }), changed, unavailable: vi.fn() });+ await Promise.resolve(); const ws = sockets[0];+ await receive(ws, { type: 'ready', actorId }); ws.send.mockClear();+ await receive(ws, { type: 'changes', scope: `actor:${actorId}`, cursor: '1', changes: [] });+ expect(ws.send).not.toHaveBeenCalled();+ finish(); for (let tick = 0; tick < 8; tick++) await Promise.resolve();+ expect(ws.send).toHaveBeenLastCalledWith(JSON.stringify({ type: 'ack', scope: `actor:${actorId}`, cursor: '1' }));+ changed.mockRejectedValueOnce(new Error('storage full')); ws.send.mockClear();+ await receive(ws, { type: 'changes', scope: `actor:${actorId}`, cursor: '2', changes: [] });+ expect(ws.send).not.toHaveBeenCalled(); expect(ws.close).toHaveBeenCalled();+});it('waits for reset state before resubscribing and ignores completion after disposal', async () => {let finish!: () => void;const reset = vi.fn(() => new Promise<void>(resolve => { finish = resolve; }));diff --git a/apps/mobile/src/__tests__/useCloudCompanionRoom.test.tsx b/apps/mobile/src/__tests__/useCloudCompanionRoom.test.tsxindex 8d10b50acb..b61efa419d 100644--- a/apps/mobile/src/__tests__/useCloudCompanionRoom.test.tsx+++ b/apps/mobile/src/__tests__/useCloudCompanionRoom.test.tsx@@ -3,14 +3,17 @@ import { act, createElement } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, expect, it, vi } from 'vitest';-const h = vi.hoisted(() => ({ owner: 'owner:1:global', current: true, companionRoom: vi.fn(), history: vi.fn(), media: vi.fn(), disk: new Map<string, string>() }));+const h = vi.hoisted(() => ({ owner: 'owner:1:global', current: true, companionRoom: vi.fn(), history: vi.fn(), media: vi.fn(), disk: new Map<string, string>(), appStateListeners: new Set<(state: string) => void>() }));vi.mock('@/session/historyDiskStoreExpo', () => ({ createHistoryDiskIO: () => ({read: async (key: string) => h.disk.get(key) ?? null,write: async (key: string, value: string) => { h.disk.set(key, value); },remove: async (key: string) => { h.disk.delete(key); }, files: async () => [...h.disk.keys()],}) }));vi.mock('@/config/env', () => ({ getActiveMobileSessionRealm: () => 'global' }));-vi.mock('react-native', () => ({ AppState: { addEventListener: () => ({ remove() {} }) } }));+vi.mock('react-native', () => ({ AppState: { addEventListener: (_event: string, listener: (state: string) => void) => {+ h.appStateListeners.add(listener);+ return { remove() { h.appStateListeners.delete(listener); } };+} } }));vi.mock('expo-crypto', () => ({ digestStringAsync: vi.fn(async () => 'hash'), CryptoDigestAlgorithm: { SHA256: 'SHA-256' }, CryptoEncoding: { HEX: 'hex' } }));vi.mock('expo-router', async () => {const { useEffect } = await import('react');@@ -35,7 +38,7 @@ function Probe() { result = useCloudCompanionRoom('actor', 'Writer', true); retuconst render = () => act(async () => root.render(createElement(Probe)));beforeEach(async () => {setMobileAuthOwner(null); peekCloudConversation('actor'); await clearHistoryDisk(); setMobileAuthOwner('owner');- vi.resetAllMocks(); h.owner = 'owner:1:global'; h.current = true;+ vi.resetAllMocks(); h.owner = 'owner:1:global'; h.current = true; h.appStateListeners.clear();h.companionRoom.mockResolvedValue(ROOM); h.history.mockResolvedValue({ messages: [], before: null });root = createRoot(document.createElement('div'));});@@ -64,6 +67,81 @@ it('has no address to fetch before the room is known', async () => {expect(h.media).not.toHaveBeenCalled();});+// Unit tier: older 1:1 pages must consume server corrections and disappear after a history reset.+it('updates old messages outside the latest private-chat page and drops them on a history reset', async () => {+ const message = (id: string, deleted = false) => ({ id, seq: id, deleted, content: [{ type: 'text', text: id }] });+ h.history.mockResolvedValueOnce({ messages: [message('2')], before: '2', historyRevision: 'A' });+ await render();+ h.history.mockResolvedValueOnce({ messages: [message('1')], before: null, historyRevision: 'A' });+ await act(async () => { await result.loadOlder(); });+ h.history.mockResolvedValueOnce({ messages: [message('3')], before: '3', historyRevision: 'A',+ messageUpdates: [{ ...message('2'), content: [{ type: 'text', text: 'edited' }] }, message('1', true)] });+ await act(async () => { await result.reload(); });+ expect(result.messages.map(value => [value.id, value.deleted, value.content[0]?.text])).toEqual([+ ['3', false, '3'], ['2', false, 'edited'], ['1', true, '1'],+ ]);+ h.history.mockResolvedValueOnce({ messages: [message('3')], before: null, historyRevision: 'B' });+ await act(async () => { await result.reload(); });+ expect(result.messages.map(value => value.id)).toEqual(['3']);+});++// PR #7242, unit: the existing refresh test had already loaded an older page.+// A full first page shifts without changing length when one new message arrives.+it('keeps the displaced oldest message when a full private-chat page refreshes', async () => {+ const message = (seq: number) => ({ id: String(seq), seq: String(seq), content: [{ type: 'text', text: String(seq) }] });+ h.history.mockResolvedValueOnce({ messages: Array.from({ length: 100 }, (_, i) => message(100 - i)), before: '1', historyRevision: 'A' });+ await render();+ h.history.mockResolvedValueOnce({ messages: Array.from({ length: 100 }, (_, i) => message(101 - i)), before: '2', historyRevision: 'A',+ messageUpdates: [{ ...message(1), content: [{ type: 'text', text: 'edited' }] }] });+ await act(async () => { await result.reload(); });+ expect(result.messages.map(value => value.id)).toEqual(Array.from({ length: 101 }, (_, i) => String(101 - i)));+ expect(result.messages.at(-1)?.content[0]?.text).toBe('edited');+ expect(result.before).toBe('1');+ expect(peekCloudConversation('actor')?.messages).toEqual(result.messages);+ expect(h.history).toHaveBeenCalledTimes(2);+});++it('ignores a delayed older private-chat page after the displayed history was reset', async () => {+ h.history.mockResolvedValueOnce({ messages: [{ id: 'new' }], before: '2', historyRevision: 'A' });+ await render();+ let finish!: (value: unknown) => void;+ h.history.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ let older!: Promise<void>;+ await act(async () => { older = result.loadOlder(); });+ h.history.mockResolvedValueOnce({ messages: [{ id: 'allowed' }], before: null, historyRevision: 'B' });+ await act(async () => { await result.reload(); });+ await act(async () => { finish({ messages: [{ id: 'no-longer-visible' }], before: null, historyRevision: 'A' }); await older; });+ expect(result.messages.map(value => value.id)).toEqual(['allowed']);+});++// Unit tier: a foreground refresh invalidates pagination responses, but a failed refresh must+// still let the user retry pagination when that stale request settles (success or failure).+it.each(['success', 'failure'] as const)('releases stale pagination after a failed foreground refresh and older-page %s', async outcome => {+ h.history.mockResolvedValueOnce({ messages: [{ id: 'new' }], before: '2', historyRevision: 'A' });+ await render();+ let finish!: (value: unknown) => void;+ let fail!: (error: Error) => void;+ h.history.mockImplementationOnce(() => new Promise((resolve, reject) => { finish = resolve; fail = reject; }));+ let older!: Promise<void>;+ await act(async () => { older = result.loadOlder(); });+ expect(result.loadingOlder).toBe(true);+ h.history.mockRejectedValueOnce(new Error('NETWORK_ERROR'));+ await act(async () => { h.appStateListeners.forEach(listener => listener('active')); });+ await act(async () => {+ if (outcome === 'success') finish({ messages: [{ id: 'stale' }], before: null, historyRevision: 'A' });+ else fail(new Error('NETWORK_ERROR'));+ await older;+ });+ expect(result.loadingOlder).toBe(false);+ expect(result.status).toBe('ready');+ expect(result.messages.map(message => message.id)).toEqual(['new']);+ expect(result.before).toBe('2');+ h.history.mockResolvedValueOnce({ messages: [{ id: 'older' }], before: null, historyRevision: 'A' });+ await act(async () => { await result.loadOlder(); });+ expect(result.messages.map(message => message.id)).toEqual(['new', 'older']);+ expect(result.before).toBeNull();+});+// Integration: the cloud-only route must hydrate before resolving the companion room.// Existing coverage tested signed attachment access but never reopened this route offline.it('restores a saved cloud transcript across remount and process-cache loss, then purges revoked access', async () => {diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsxindex 40b91bfac1..8af7cd15c6 100644--- a/apps/mobile/src/auth/AuthContext.tsx+++ b/apps/mobile/src/auth/AuthContext.tsx@@ -125,6 +125,7 @@ import { clearRemoteResourceCache } from '@/device-link/remoteResourceCache';import { clearCachedHomeListSnapshot } from '@/session/mobileHomeListCache';import { getMobileAuthOwner, invalidateMobileAuthOwnerForSwitch, setMobileAuthOwner } from '@/auth/authOwnerGeneration';import { updateCredentialAccessToken } from '@/remote-desktop/credentialIdentity';+import { clearMobileChatHistoryStore } from '@/chat/chatHistoryStore';import { clearCachedSessionMessages } from '@/session/mobileSessionMessageCache';import { clearHistoryDisk } from '@/session/remoteHistoryDiskCache';import { clearAllMobileVoiceCredentials } from '@/session/mobileVoiceCredentialStore';@@ -895,6 +896,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {clearAllMobileVoiceInputHistories().catch(() => undefined),clearAllMobileVoiceDictionaryCaches().catch(() => undefined),clearCachedSessionMessages(),+ clearMobileChatHistoryStore(),clearHistoryDisk(),clearRemoteResourceCache().catch(() => undefined),clearCachedHomeListSnapshot().catch(() => undefined),@@ -2973,6 +2975,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {console.warn('[auth] speaker filter cleanup pending; will retry');});await clearCachedSessionMessages().catch(() => undefined);+ await clearMobileChatHistoryStore().catch(() => undefined);await clearHistoryDisk();// 首页设备+会话快照与消息缓存一样属于账号数据,登出必须清掉。await clearRemoteResourceCache().catch(() => undefined);diff --git a/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx b/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsxindex b39a3974aa..3d255309d9 100644--- a/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx+++ b/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx@@ -8,6 +8,8 @@ const native = vi.hoisted(() => ({replaceRoute: vi.fn(),closeAccount: undefined as (() => void) | undefined,storage: new Map<string, string>(),+ chatFiles: new Map<string, string>(),+ removeChatFile: vi.fn(),readSecure: vi.fn(),deleteSecure: vi.fn(),writeSecure: vi.fn(),@@ -92,7 +94,8 @@ vi.mock('@/auth/pkce', () => ({createState: () => `fixture-state-${++native.state}`,}));vi.mock('@/auth/deviceId', () => ({ ensureDeviceId: async () => 'fixture-device', hasStoredDeviceId: async () => true }));-vi.mock('@/auth/mobileAccountVault', () => ({+vi.mock('@/auth/mobileAccountVault', async (original) => ({+ ...(await original<typeof import('../mobileAccountVault')>()),readMobileAccountVault: async () => null,clearMobileLoginCredentialsForLogout: native.logoutCleanup,listMobileSavedAccounts: () => [],@@ -103,7 +106,7 @@ vi.mock('@/auth/nativeSocial', () => ({}));vi.mock('@/auth/ssoOrgHistory', () => ({ rememberSsoOrgIdentifier: async () => {} }));vi.mock('@/auth/canaryChannelSync', () => ({}));vi.mock('@/auth/xdOrgBetaDefault', () => ({}));-vi.mock('@/analytics/mobileTapdb', () => ({ clearTapdbUser: async () => {}, stopMobileTapdbReporting: async () => {} }));+vi.mock('@/analytics/mobileTapdb', () => ({ setTapdbUser: async () => {}, clearTapdbUser: async () => {}, stopMobileTapdbReporting: async () => {} }));vi.mock('@/analytics/analyticsConsentStore', () => ({ clearAnalyticsConsent: async () => {} }));vi.mock('@/notifications/pushNotifications', () => ({ unregisterPushTokenBestEffort: native.unregisterPush }));vi.mock('@/session/agentCapabilitiesCache', () => ({ resetAgentCapabilitiesCache: async () => {} }));@@ -111,6 +114,14 @@ vi.mock('@/session/composerPaletteCache', () => ({ resetComposerPaletteCache: asvi.mock('@/device-link/remoteResourceCache', () => ({ clearRemoteResourceCache: async () => {} }));vi.mock('@/session/mobileHomeListCache', () => ({ clearCachedHomeListSnapshot: async () => {} }));vi.mock('@/remote-desktop/credentialIdentity', () => ({ updateCredentialAccessToken() {} }));+vi.mock('@/session/historyDiskStoreExpo', () => ({ createHistoryDiskIO: () => ({+ read: async (key: string) => native.chatFiles.get(key) ?? null,+ write: async (key: string, value: string) => { native.chatFiles.set(key, value); },+ remove: native.removeChatFile,+ files: async () => [...native.chatFiles.keys()],+}) }));+// Cache failure banners belong to the app shell, not AuthProvider's listener lifecycle.+vi.mock('@/session/cacheWriteNotice', () => ({ notifyCacheWriteFailure: vi.fn() }));vi.mock('@/session/mobileSessionMessageCache', () => ({ clearCachedSessionMessages: async () => {} }));vi.mock('@/session/remoteHistoryDiskCache', () => ({ clearHistoryDisk: async () => {} }));vi.mock('@/session/mobileVoiceCredentialStore', () => ({ clearAllMobileVoiceCredentials: async () => {} }));@@ -197,7 +208,8 @@ describe('browser auth session lifecycle (real AuthProvider, mocked native/netwonative.providers.mockReset().mockResolvedValue({ social: ['wechat'], emailCode: true, smsCode: false });native.initialUrl.mockReset().mockResolvedValue(null);native.requestCode.mockReset().mockResolvedValue(undefined);- native.storage.clear();+ native.storage.clear(); native.chatFiles.clear();+ native.removeChatFile.mockReset().mockImplementation(async (key: string) => { native.chatFiles.delete(key); });native.writeSecure.mockReset().mockImplementation(async (key: string, value: string) => { native.storage.set(key, value); });native.logoutCleanup.mockReset();native.unregisterPush.mockReset();@@ -253,16 +265,49 @@ describe('browser auth session lifecycle (real AuthProvider, mocked native/netwonative.logoutCleanup.mockImplementationOnce(async () => {native.storage.delete('cindy.mobile.auth.session.v1');});+ native.chatFiles.set('fixture-room.json', 'private chat history');native.clearSpeaker.mockRejectedValueOnce(new Error('keychain unavailable'));const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});await act(async () => { await auth[action](); });expect(native.clearSpeaker).toHaveBeenCalledWith(owner.accountKey);+ expect(native.chatFiles.size).toBe(0);expect(native.storage.has('cindy.mobile.auth.session.v1')).toBe(false);expect(native.storage.has('cindy.mobile.auth.userProfile')).toBe(false);expect(getMobileAuthOwner().accountKey).toBe('');expect(warn).toHaveBeenCalledWith('[auth] speaker filter cleanup pending; will retry');});+ // PR #7242: logout-only coverage did not prove the next fresh login gates identity+ // publication on retrying failed disk cleanup. Unit, real AuthProvider + chat store.+ it('retries failed logout chat cleanup before a fresh login can persist or activate its identity', async () => {+ native.chatFiles.set('fixture-room.json', 'private chat history');+ native.removeChatFile.mockRejectedValueOnce(new Error('file busy'));+ await act(async () => { await auth.logout(); });+ expect(native.chatFiles.size).toBe(1);+ await restartProvider();+ await act(async () => { await auth.dispatchLoginAction({ type: 'reset' }); });+ native.exchange.mockResolvedValue({+ status: 'ok', accessToken: 'fixture-access', refreshToken: 'fixture-refresh', expiresIn: 3600,+ membership: { id: 'fixture-org-user', kind: 'organization', role: 'member', displayName: 'Fixture',+ email: '[email protected]', orgId: 'fixture-org', orgName: 'Fixture Organization' },+ });+ native.removeChatFile.mockRejectedValueOnce(new Error('still busy'));+ await start();+ await emitLink(callbackUrl());+ expect(native.removeChatFile).toHaveBeenCalledTimes(2);+ expect(auth.isAuthenticated).toBe(false);+ expect(native.storage.has('cindy.mobile.auth.session.v1')).toBe(false);+ expect(native.storage.has('cindy.mobile.auth.accounts.v1')).toBe(false);+ expect(native.chatFiles.size).toBe(1);++ await act(async () => { await auth.dispatchLoginAction({ type: 'reset' }); });+ await start();+ await emitLink(callbackUrl());+ expect(native.chatFiles.size).toBe(0);+ expect(auth.isAuthenticated).toBe(true);+ expect(native.storage.get('cindy.mobile.auth.session.v1')).toContain('fixture-refresh');+ });+it.each(['sso', 'social'] as const)('retains %s login on Android dismiss and accepts a delayed deep link', async (kind) => {await start(kind);expect(auth.loginState?.step).toBe('browser-redirect');diff --git a/apps/mobile/src/chat/chatHistoryStore.ts b/apps/mobile/src/chat/chatHistoryStore.tsnew file mode 100644index 0000000000..1f885053cc--- /dev/null+++ b/apps/mobile/src/chat/chatHistoryStore.ts@@ -0,0 +1,81 @@+import { sha256 } from '@noble/hashes/sha256';+import { bytesToHex } from '@noble/hashes/utils';+import type { ChatHistoryState, ChatHistoryStore } from '@cindy/maker-shared/chat-history';+import type { HistoryDiskIO } from '@/session/historyDiskStore';++const writes = new Map<string, Promise<unknown>>();+let io: Promise<HistoryDiskIO> | undefined;+let epoch = 0;+let clearing: Promise<void> | undefined;+const disk = () => io ??= import('@/session/historyDiskStoreExpo')+ .then(({ createHistoryDiskIO }) => createHistoryDiskIO('chat-history-v1'))+ .catch(error => { io = undefined; throw error; });+async function persist(operation: () => Promise<void>) {+ try { await operation(); }+ catch (error) {+ void import('@/session/cacheWriteNotice').then(module => module.notifyCacheWriteFailure()).catch(() => undefined);+ throw error;+ }+}++/** Private, disposable files share the existing atomic replacement backend; no AsyncStorage quota. */+export function createMobileChatHistoryStore(owner: string, realm: string, endpoint: string, human: string, current: () => boolean): ChatHistoryStore {+ const generation = epoch;+ const versions = new Map<string, number | null>();+ const generations = new Map<string, string | null>();+ const assertCurrent = () => { if (!owner || !current() || generation !== epoch || clearing) throw new Error('OWNER_CHANGED'); };+ function serial<T>(room: string, action: (files: HistoryDiskIO, key: string) => Promise<T>): Promise<T> {+ const key = `${bytesToHex(sha256(JSON.stringify([owner, realm, endpoint, human, room])))}.json`;+ const pending = (writes.get(key) ?? Promise.resolve()).catch(() => undefined).then(async () => {+ assertCurrent();+ const files = await disk(); assertCurrent();+ const result = await action(files, key);+ assertCurrent();+ return result;+ });+ writes.set(key, pending);+ void pending.finally(() => { if (writes.get(key) === pending) writes.delete(key); }).catch(() => undefined);+ return pending;+ }+ const decode = (text: string | null): { version: number; state: ChatHistoryState } | null => {+ if (!text) return null;+ try { const value = JSON.parse(text); return value?.state?.snapshot && value?.state?.generation && Number.isSafeInteger(value.version) ? value : null; }+ catch { return null; }+ };+ return {+ read: room => serial(room, async (files, key) => {+ const value = decode(await files.read(key));+ versions.set(room, value?.version ?? null);+ generations.set(room, value?.state.generation ?? null);+ return value?.state;+ }),+ write: (room, state) => serial(room, async (files, key) => {+ const old = decode(await files.read(key));+ if ((old?.version ?? null) !== (versions.get(room) ?? null)+ || (old?.state.generation ?? null) !== (generations.get(room) ?? null)) throw new Error('CHAT_CACHE_CONFLICT');+ assertCurrent();+ if (!state) { await persist(() => files.remove(key)); versions.set(room, null); generations.set(room, null); return; }+ const version = (old?.version ?? 0) + 1;+ const payload = JSON.stringify({ version, state });+ await persist(() => files.write(key, payload));+ versions.set(room, version); generations.set(room, state.generation);+ }),+ };+}++/** Fence old mounts synchronously, drain native writes, then remove every account's files. */+export function clearMobileChatHistoryStore(): Promise<void> {+ if (clearing) return clearing;+ epoch++;+ const pending = [...writes.values()];+ clearing = (async () => {+ await Promise.allSettled(pending);+ await persist(async () => {+ const files = await disk();+ const results = await Promise.allSettled((await files.files()).map(name => files.remove(name)));+ const errors = results.flatMap(result => result.status === 'rejected' ? [result.reason] : []);+ if (errors.length) throw new AggregateError(errors, 'Chat cache cleanup failed');+ });+ })().finally(() => { clearing = undefined; });+ return clearing;+}diff --git a/apps/mobile/src/chat/chatServerClient.ts b/apps/mobile/src/chat/chatServerClient.tsindex 1435afeecd..103c0021b9 100644--- a/apps/mobile/src/chat/chatServerClient.ts+++ b/apps/mobile/src/chat/chatServerClient.ts@@ -1,4 +1,5 @@import { createConversationListState } from '@cindy/maker-shared/chatConversationList';+import type { ChatHistory } from '@cindy/maker-shared/chat-history';/** The existing Chat Server HTTP contract; no device-link or executor registration. */import { botGroupMessageSummaryText, readBotGroupExecutionFailure, readBotGroupQuote, readBotGroupQuoteCard, readBotGroupTaskCard, readImportedBotGroupRuntimeFailureCode, type BotGroupAttachment, type BotGroupMemberView, type BotGroupMessageView, type BotGroupRemoteChatData } from '@cindy/maker-shared/botGroupChat';import { chatGroupMemberName as memberName, botGroupExecutionFailureBatches, projectBotGroupExecutionFailures } from '@cindy/maker-shared/botGroupPresentation';@@ -25,12 +26,12 @@ export interface ChatMessage {content: Array<{ type: string; text?: string; fallback?: string; mediaId?: string; caption?: string;namespace?: string; schemaRevision?: number; data?: Record<string, unknown> }>;}-export interface ChatSnapshot { room: ChatRoom; members: ChatMember[]; messages: ChatMessage[]; cursor: string; reads?: Array<{ thread_key: string; read_seq: string; muted?: boolean; following?: boolean }> }+export interface ChatSnapshot { cacheGeneration?: string; room: ChatRoom; members: ChatMember[]; messages: ChatMessage[]; cursor: string; reads?: Array<{ thread_key: string; read_seq: string; muted?: boolean; following?: boolean }> }export interface ChatExecutionFailure {id: string; conversation_id?: string; source_message_id: string; bot_id: string; epoch: number; status?: string;failure_code?: unknown; updated_at?: string; plan_id?: string | null;}-export interface ChatPage { threadRootId?: string; snapshot: ChatSnapshot; messages: ChatMessage[]; before: string | null; failures?: ChatExecutionFailure[] }+export interface ChatPage { threadRootId?: string; snapshot: ChatSnapshot; messages: ChatMessage[]; before: string | null; failures?: ChatExecutionFailure[]; historyRevision?: string }/** `actorId` acts as one of the account's own actors (Chat Server `X-Chat-Actor`). */export type ChatRequest = <T>(path: string, method?: 'GET' | 'POST' | 'PATCH', body?: unknown, actorId?: string, signal?: AbortSignal) => Promise<T>;/** An actor the account owns; a companion's `externalId` is its bot id on every computer. */@@ -38,7 +39,7 @@ export interface ChatActor { id: string; kind: string; externalId: string; name:export interface ChatCapabilities { companionHome: boolean }/** Compare-and-set result: a conflict carries the main computer another device already chose. */export type ChatSetHomeResult = { ok: true; homeDeviceId: string } | { ok: false; homeDeviceId: string | null };-export interface ChatHistoryPage { messages: ChatMessage[]; before: string | null }+export interface ChatHistoryPage { messages: ChatMessage[]; before: string | null; historyRevision?: string; messageUpdates?: ChatMessage[] }export type ChatGroupSettingsAction =| { type: 'update'; expectedRevision: number; name?: string; description?: string; responseMode?: 'all' | 'mentioned'; speakingMode?: 'auto' | 'sequential'; organizerId?: string | null; archived?: boolean }| { type: 'member'; actorId: string; action: 'invite' | 'remove' | 'role'; role?: 'admin' | 'member' };@@ -237,7 +238,14 @@ export function chatGroupView(page: ChatPage, selfId: string, actors: readonly ChasMoreBefore: page.before !== null, round: { status: 'idle', speakers: [], canContinue: false }, supportsAttachments: false };}-export function createChatServerClient(request: ChatRequest, personalList = createConversationListState()) {+export function createChatServerClient(request: ChatRequest, personalList = createConversationListState(),+ openHistory?: (human: string) => Promise<ChatHistory>) {+ let historyCache: Promise<ChatHistory> | undefined;+ const cache = () => openHistory ? historyCache ??= identity().then(openHistory).catch(error => { historyCache = undefined; throw error; }) : undefined;+ async function messagePage(room: string, query: string) {+ const stored = await cache();+ return stored ? stored.page<ChatMessage>(room, new URLSearchParams(query)) : request<ChatMessage[]>(`/conversations/${room}/messages?${query}`);+ }// Preserve the posted quote through a lost response. Retrying an operation must// not change its content/recipients if the original is subsequently edited or removed.const postedQuotes = new Map<string, { content: ChatMessage['content']; mentions: string[] }>();@@ -258,25 +266,41 @@ export function createChatServerClient(request: ChatRequest, personalList = creaif (!Array.isArray(value)) throw new Error('INVALID_CHAT_EXECUTIONS');return value.filter(row => sources.has(row.source_message_id));}- async function history(roomId: string, before?: string | null): Promise<ChatHistoryPage> {- const messages = await request<ChatMessage[]>(`/conversations/${chatId(roomId)}/messages?limit=100${before ? `&before=${chatCursor(before)}` : ''}`);+ async function history(roomId: string, before?: string | null, shownIds: string[] = [], attempt = 0): Promise<ChatHistoryPage> {+ const stored = await cache();+ if (!before) stored?.invalidate(roomId);+ const snapshot = await stored?.snapshot(roomId);+ const messages = await messagePage(chatId(roomId), `limit=100${before ? `&before=${chatCursor(before)}` : ''}`);if (!Array.isArray(messages)) throw new Error('INVALID_CHAT_MESSAGES');const next = messages.length === 100 ? chatCursor(messages.at(-1)!.seq) : null;if (before && next && BigInt(next) >= BigInt(before)) throw new Error('INVALID_CHAT_PAGE');- return { messages, before: next };+ const projection = await stored?.projection<ChatMessage>(roomId, shownIds);+ if (projection && snapshot?.cacheGeneration !== projection.generation) {+ if (attempt >= 2) throw new Error('CHAT_HISTORY_CHANGED');+ return history(roomId, before, shownIds, attempt + 1);+ }+ return { messages, before: next, ...(projection ? { historyRevision: projection.generation, messageUpdates: projection.messages } : {}) };}let supportsDissolve = false;let supportsListRemoval = false;let singleSpeaker = false;+ let lastIdentity: { id: string; at: number } | undefined;+ let readingIdentity: Promise<string> | undefined;async function identity() {- const me = await request<{ actor: { id: string; kind: string }; capabilities?: { groupLifecycleVersion?: number; conversationListStateVersion?: number; groupSingleSpeaker?: number } }>('/me');- if (me.actor.kind !== 'human') throw new Error('INVALID_CHAT_IDENTITY');- supportsDissolve = me.capabilities?.groupLifecycleVersion === 1;- supportsListRemoval = me.capabilities?.conversationListStateVersion === 1;- singleSpeaker = me.capabilities?.groupSingleSpeaker === 1;- return chatId(me.actor.id);+ if (openHistory && lastIdentity && Date.now() - lastIdentity.at < 60_000) return lastIdentity.id;+ return readingIdentity ??= (async () => {+ const me = await request<{ actor: { id: string; kind: string }; capabilities?: { groupLifecycleVersion?: number; conversationListStateVersion?: number; groupSingleSpeaker?: number } }>('/me');+ if (me.actor.kind !== 'human') throw new Error('INVALID_CHAT_IDENTITY');+ supportsDissolve = me.capabilities?.groupLifecycleVersion === 1;+ supportsListRemoval = me.capabilities?.conversationListStateVersion === 1;+ singleSpeaker = me.capabilities?.groupSingleSpeaker === 1;+ const id = chatId(me.actor.id); lastIdentity = { id, at: Date.now() };+ return id;+ })().finally(() => { readingIdentity = undefined; });}return {+ invalidateHistory(room: string, metadata = false) { void historyCache?.then(value => value.invalidate(room, metadata)).catch(() => undefined); },+ async refreshHistory(room: string, metadata = false) { const value = await cache(); value?.invalidate(room, metadata); await value?.snapshot(room); },personalList,lifecycleCapabilities: () => ({ supportsDissolve, supportsListRemoval, singleSpeaker }),async groupSettings(roomId: string) {@@ -397,7 +421,9 @@ export function createChatServerClient(request: ChatRequest, personalList = crea},/** Main-timeline messages of any room kind (a companion's room is `direct`), newest first. */history,- async snapshot(roomId: string): Promise<ChatSnapshot> {+ async snapshot(roomId: string, metadata = false): Promise<ChatSnapshot> {+ const stored = await cache();+ if (stored) { stored.invalidate(roomId, metadata); return stored.snapshot<ChatSnapshot>(chatId(roomId)); }return request(`/conversations/${chatId(roomId)}/snapshot`);},async members(roomId: string): Promise<ChatMember[]> {@@ -405,19 +431,20 @@ export function createChatServerClient(request: ChatRequest, personalList = creaif (!Array.isArray(members)) throw new Error('INVALID_CHAT_MEMBERS');return members;},- async load(roomId: string, oldest?: string, threadRootId?: string): Promise<ChatPage> {+ async load(roomId: string, oldest?: string, threadRootId?: string, attempt = 0): Promise<ChatPage> {const room = chatId(roomId);const threadQuery = threadRootId ? `&threadRootId=${chatId(threadRootId)}` : '';- const snapshot = await request<ChatSnapshot>(`/conversations/${room}/snapshot`);+ const stored = await cache();+ const snapshot = stored ? await stored.snapshot<ChatSnapshot>(room) : await request<ChatSnapshot>(`/conversations/${room}/snapshot`);if (snapshot.room.id !== room || !Array.isArray(snapshot.members)) throw new Error('INVALID_CHAT_SNAPSHOT');chatCursor(snapshot.cursor);// Snapshot includes Thread replies; the message endpoint selects the main timeline.- let batch = await request<ChatMessage[]>(`/conversations/${room}/messages?limit=100${threadQuery}`);+ let batch = await messagePage(room, `limit=100${threadQuery}`);const messages = [...batch];let before = batch.length === 100 ? chatCursor(batch.at(-1)!.seq) : null;// Reauthorize and re-read the displayed window on invalidation, including edits/removals.while (oldest && before && BigInt(before) > BigInt(chatCursor(oldest))) {- batch = await request<ChatMessage[]>(`/conversations/${room}/messages?limit=100&before=${before}${threadQuery}`);+ batch = await messagePage(room, `limit=100&before=${before}${threadQuery}`);const next = batch.length === 100 ? chatCursor(batch.at(-1)!.seq) : null;if (next && BigInt(next) >= BigInt(before)) throw new Error('INVALID_CHAT_PAGE');messages.push(...batch); before = next;@@ -426,13 +453,25 @@ export function createChatServerClient(request: ChatRequest, personalList = creaconst root = await request<ChatMessage>(`/conversations/${room}/messages/${chatId(threadRootId)}`);messages.push(root);}- return { snapshot, messages, before, ...(threadRootId ? { threadRootId } : {}), failures: await failures(room, messages) };+ const executionFailures = await failures(room, messages);+ const projection = await stored?.projection<ChatMessage>(room, []);+ if (projection && snapshot.cacheGeneration !== projection.generation) {+ if (attempt >= 2) throw new Error('CHAT_HISTORY_CHANGED');+ return this.load(roomId, undefined, threadRootId, attempt + 1);+ }+ return { snapshot, messages, before, ...(projection ? { historyRevision: projection.generation } : {}),+ ...(threadRootId ? { threadRootId } : {}), failures: executionFailures };},async older(roomId: string, page: ChatPage): Promise<ChatPage> {if (!page.before) return page;- const messages = await request<ChatMessage[]>(`/conversations/${chatId(roomId)}/messages?limit=100&before=${chatCursor(page.before)}${page.threadRootId ? `&threadRootId=${chatId(page.threadRootId)}` : ''}`);- const loaded = [...page.messages, ...messages];- return { ...page, messages: loaded, failures: await failures(roomId, loaded),+ const messages = await messagePage(chatId(roomId), `limit=100&before=${chatCursor(page.before)}${page.threadRootId ? `&threadRootId=${chatId(page.threadRootId)}` : ''}`);+ const projection = await (await cache())?.projection<ChatMessage>(roomId, page.messages.map(message => message.id));+ if (projection && projection.generation !== page.historyRevision) return this.load(roomId, undefined, page.threadRootId);+ const updates = new Map(projection?.messages.map(message => [message.id, message]));+ const loaded = [...page.messages.map(message => updates.get(message.id) ?? message), ...messages];+ const executionFailures = await failures(roomId, loaded);+ if (projection && (await cache())?.generation(roomId) !== projection.generation) return this.load(roomId, undefined, page.threadRootId);+ return { ...page, messages: loaded, failures: executionFailures,before: messages.length === 100 ? chatCursor(messages.at(-1)!.seq) : null };},async media(roomId: string, mediaId: string, signal?: AbortSignal): Promise<BotGroupAttachment> {diff --git a/apps/mobile/src/chat/chatServerSubscription.ts b/apps/mobile/src/chat/chatServerSubscription.tsindex 9ccc48114b..049fd22ba4 100644--- a/apps/mobile/src/chat/chatServerSubscription.ts+++ b/apps/mobile/src/chat/chatServerSubscription.ts@@ -14,7 +14,7 @@ export function subscribeChatServer(options: {baseUrl: string; token(): Promise<string | null>; current(): boolean;socket(url: string): ChatSocket;ready(actorId: string): Promise<{ scope: string; cursor: string } | Array<{ scope: string; cursor: string }>>;- changed(changes?: Array<{ type: string; data: unknown }>): void; unavailable(): void; available?(): void;+ changed(changes?: Array<{ type: string; entityId?: string; data: unknown }>): void | Promise<void>; unavailable(): void; available?(): void;reset?(): Promise<void>;}) {let stopped = false;@@ -34,9 +34,11 @@ export function subscribeChatServer(options: {deadline = setTimeout(() => ws.close(), 15000);ws.onopen = () => { if (current(ws)) ws.send(JSON.stringify({ type: 'auth', token })); else ws.close(); };const scopes = new Set<string>();+ let frames = Promise.resolve();ws.onmessage = event => {if (!current(ws)) return;- void (async () => {+ frames = frames.then(async () => {+ if (!current(ws)) return;const value = JSON.parse(String(event.data));if (value.type === 'ready') {clearTimeout(deadline);@@ -50,18 +52,21 @@ export function subscribeChatServer(options: {options.available?.();}} else if (value.type === 'changes' && scopes.has(value.scope)) {- options.changed(value.changes);- ws.send(JSON.stringify({ type: 'ack', scope: value.scope, cursor: chatCursor(value.cursor) }));+ await options.changed(value.changes);+ if (current(ws) && ws.readyState === 1) ws.send(JSON.stringify({ type: 'ack', scope: value.scope, cursor: chatCursor(value.cursor) }));} else if (value.type === 'scope_error' && scopes.has(value.scope)) {// A full authenticated reload clears removed membership and resets expired cursors.- options.changed(value.changes);if (value.error?.code === 'RESET_REQUIRED' && value.error?.details?.head) {+ await options.changed(value.changes);const head = chatCursor(value.error.details.head);await options.reset?.();if (current(ws) && ws.readyState === 1) ws.send(JSON.stringify({ type: 'subscribe', scope: value.scope, after: head }));- } else { stopped = true; options.unavailable(); ws.close(); }+ } else {+ try { await options.changed(value.changes); }+ finally { stopped = true; options.unavailable(); ws.close(); }+ }} else if (value.type === 'error') ws.close();- })().catch(() => { if (current(ws)) ws.close(); });+ }).catch(() => { if (current(ws)) ws.close(); });};ws.onerror = () => { if (current(ws)) ws.close(); };ws.onclose = () => { if (current(ws)) { clearTimeout(deadline); schedule(); } };diff --git a/apps/mobile/src/chat/cloudConversationCache.ts b/apps/mobile/src/chat/cloudConversationCache.tsindex 39cae8c3be..f0129a2b92 100644--- a/apps/mobile/src/chat/cloudConversationCache.ts+++ b/apps/mobile/src/chat/cloudConversationCache.ts@@ -2,7 +2,7 @@ import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeimport { clearHistoryDisk, historyDiskAuthority, readConversationDisk, writeConversationDisk } from '@/session/remoteHistoryDiskCache';import type { ChatMessage } from './chatServerClient';-export interface CachedCloudConversation { roomId: string; messages: ChatMessage[]; before: string | null }+export interface CachedCloudConversation { roomId: string; messages: ChatMessage[]; before: string | null; historyRevision?: string }const namespace = 'cloud-companion';let owner = getMobileAuthOwner();const pages = new Map<string, CachedCloudConversation>();diff --git a/apps/mobile/src/chat/useChatServer.ts b/apps/mobile/src/chat/useChatServer.tsindex c37573a504..23773fc878 100644--- a/apps/mobile/src/chat/useChatServer.ts+++ b/apps/mobile/src/chat/useChatServer.ts@@ -15,6 +15,8 @@ import { useRemoteSyncCoordinator } from '@/device-link/remoteSyncTask';import type { BotGroupChatState } from '@/session/useBotGroupChat';import { chatAccessLost, chatCursor, chatGroupView, chatHttpsUrl, chatRoomRow, chatReadAt, chatReadSequence, chatLastReplyAt, chatLastReplySequence, createChatServerClient, type ChatActor, type ChatPage, type ChatRequest, type ChatSnapshot } from './chatServerClient';import { subscribeChatServer } from './chatServerSubscription';+import { createChatHistory } from '@cindy/maker-shared/chat-history';+import { createMobileChatHistoryStore } from './chatHistoryStore';import { cacheChatMessages, forgetChatMessages, peekChatMessages, readChatMessages, subscribeChatInvalidation } from './chatMessageCache';// Shared only within the current authenticated account generation and realm.@@ -58,9 +60,19 @@ export function useChatClient() {const url = await endpoint(); check();const result = await deps.current.apiFetch<T>(`/v1${path}`, { baseUrl: url, method, cache: 'no-store', ...(body !== undefined ? { body } : {}),...(actorId ? { headers: { 'X-Chat-Actor': actorId } } : {}), ...(signal ? { signal } : {}), assertCurrent: check });- check(); return result;+ check();+ if (method !== 'GET') {+ const room = path.match(/^\/conversations\/([^/]+)/)?.[1];+ if (room) client.invalidateHistory(room, path.endsWith('/read'));+ }+ return result;};- const client = createChatServerClient(request, listFor(owner));+ const client = createChatServerClient(request, listFor(owner), async human => {+ const url = await endpoint(); check();+ const { randomUUID } = await import('expo-crypto');+ return createChatHistory({ api: request, current, newGeneration: randomUUID,+ store: createMobileChatHistoryStore(auth.user!.id, realm, url, human, current) });+ });return { owner, realm, userId: auth.user?.id ?? '', current, baseUrl, endpoint, request, client,token: async () => { check(); await client.me(); const token = await deps.current.getAccessToken(); check(); return token; }, enabled: !!auth.user };}, [owner, !!auth.user]);@@ -102,8 +114,9 @@ export function useChatServerRoster(enabled: boolean) {try {const cached = snapshots.current.get(room.id);const value = cached?.owner === api.owner && room.head !== undefined && cached.head === room.head- && !run.reasons.some(reason => ['changed', 'connected', 'visible'].includes(reason))- ? cached.value : await api.client.snapshot(room.id);+ && !run.reasons.some(reason => ['focus', 'changed', 'connected', 'visible'].includes(reason))+ ? cached.value : await api.client.snapshot(room.id, room.head === undefined+ || run.reasons.some(reason => ['focus', 'connected', 'visible'].includes(reason)));fresh.set(room.id, { owner: api.owner, head: room.head, value });// An archive can land between the list and the newer snapshot.if (!value.room.archived) rows.push(chatRoomRow(room, value, self));@@ -171,7 +184,17 @@ export function useChatServerRoster(enabled: boolean) {}await read({ reason: 'connected' });return { scope: `actor:${actorId}`, cursor };- }, reset: () => api.client.resyncListState(), changed: changes => { for (const change of changes ?? []) if (change.type === 'conversation.list.changed') api.client.personalList.merge(change.data); void read({ reason: 'changed' }); }, available: () => { subscribed = true; }, unavailable: () => { subscribed = false; } });+ }, reset: async () => { await api.client.resyncListState(); await read({ reason: 'connected' }); }, changed: changes => {+ for (const change of changes ?? []) {+ if (change.type === 'conversation.list.changed') api.client.personalList.merge(change.data);+ // Personal read positions live in actor scope and do not advance room.head.+ if (change.type === 'read.changed' && typeof change.entityId === 'string') {+ api.client.invalidateHistory(change.entityId, true);+ snapshots.current.delete(change.entityId);+ }+ }+ return read({ reason: 'changed' });+ }, available: () => { subscribed = true; }, unavailable: () => { subscribed = false; } });}).catch(() => {}); // HTTP read presents endpoint errors.};start();@@ -258,7 +281,7 @@ export function useChatServerGroup(groupId: string, enabled: boolean, threadRootelse setState(old => ({ identity, value: old.identity === identity && old.value.kind === 'ready' ? old.value : { kind: 'error', message: error instanceof Error && error.message === 'CHAT_ENDPOINT_UNAVAILABLE' ? error.message : 'CHAT_READ_FAILED' }, online: false, loadingOlder: false }));}}, identity);- const reload = useCallback(() => { void request({ reason: 'changed' }); }, [request]);+ const reload = useCallback(() => { api.client.invalidateHistory(groupId, true); void request({ reason: 'changed' }); }, [api, groupId, request]);useFocusEffect(useCallback(() => {if (!enabled || !api.enabled || !groupId) return;let stop: (() => void) | undefined;@@ -281,12 +304,17 @@ export function useChatServerGroup(groupId: string, enabled: boolean, threadRootif ((error as { code?: string }).code !== 'RESET_REQUIRED') throw error;return '0';}) : null;+ api.client.invalidateHistory(groupId, true);await request({ reason: 'connected' });const latest = page.current;if (!freshRead.current || !latest || latest.identity !== identity) throw new Error('CHAT_READ_FAILED');return head === null ? { scope: `conversation:${groupId}`, cursor: latest.page.snapshot.cursor }: [{ scope: `conversation:${groupId}`, cursor: latest.page.snapshot.cursor }, { scope: `actor:${actorId}`, cursor: head }];- }, reset: () => api.client.resyncListState(), changed: changes => { for (const change of changes ?? []) if (change.type === 'conversation.list.changed') api.client.personalList.merge(change.data); reload(); }, available: () => { subscribed = true; }, unavailable: () => { subscribed = false; freshRead.current = false; } });+ }, reset: async () => { await api.client.resyncListState(); await api.client.refreshHistory(groupId, true); await request({ reason: 'connected' }); }, changed: async changes => {+ for (const change of changes ?? []) if (change.type === 'conversation.list.changed') api.client.personalList.merge(change.data);+ try { await api.client.refreshHistory(groupId, changes?.some(change => change.type === 'read.changed')); }+ finally { void request({ reason: 'changed' }); }+ }, available: () => { subscribed = true; }, unavailable: () => { subscribed = false; freshRead.current = false; api.client.invalidateHistory(groupId); } });}).catch(() => {}); // Read presents endpoint errors.};start();diff --git a/apps/mobile/src/chat/useCloudCompanionRoom.ts b/apps/mobile/src/chat/useCloudCompanionRoom.tsindex 30a9b442d2..63e1d06e9c 100644--- a/apps/mobile/src/chat/useCloudCompanionRoom.ts+++ b/apps/mobile/src/chat/useCloudCompanionRoom.ts@@ -13,6 +13,7 @@ const sha256Hex = (text: string) => Crypto.digestStringAsync(Crypto.CryptoDigesttype RoomState = {identity: string; roomId: string | null; messages: ChatMessage[]; before: string | null;status: 'loading' | 'ready' | 'error'; loadingOlder: boolean;+ historyRevision?: string;};/** The companion's read-only 1:1 cloud conversation: the latest page, then older pages on demand. */@@ -47,22 +48,16 @@ export function useCloudCompanionRoom(actorId: string, name: string, enabled: boconst previous = latest.current.identity === identity ? latest.current : null;try {const roomId = previous?.roomId ?? await api.client.companionRoom(actorId, name, sha256Hex);- const page = await api.client.history(roomId);- const oldest = previous?.roomId === roomId ? previous.messages.reduce<string | undefined>((seq, message) =>- !seq || BigInt(message.seq) < BigInt(seq) ? message.seq : seq, undefined) : undefined;- while (page.before && oldest && BigInt(page.before) > BigInt(oldest)) {- const before = page.before;- const older = await api.client.history(roomId, before);- if (run !== generation.current || !valid()) return;- const known = new Set(page.messages.map(message => message.id));- page.messages.push(...older.messages.filter(message => !known.has(message.id)));- page.before = older.before;- if (page.before === before) throw new Error('INVALID_CHAT_PAGE');- }+ const page = await api.client.history(roomId, undefined, previous?.messages.map(message => message.id));if (run !== generation.current || !valid()) return;- // Revalidate the opened window too: old edits/deletions must not survive hydration.- const next = { identity, roomId, messages: page.messages, before: page.before,- status: 'ready' as const, loadingOlder: false };+ // Keep pages already loaded above the refreshed newest page.+ const fresh = new Set(page.messages.map(message => message.id));+ const updates = new Map(page.messageUpdates?.map(message => [message.id, message]));+ const sameHistory = !page.historyRevision || page.historyRevision === previous?.historyRevision;+ const kept = sameHistory && previous?.roomId === roomId+ ? previous.messages.filter(message => !fresh.has(message.id)).map(message => updates.get(message.id) ?? message) : [];+ const next = { identity, roomId, messages: [...page.messages, ...kept], before: kept.length ? previous!.before : page.before,+ historyRevision: page.historyRevision, status: 'ready' as const, loadingOlder: false };void cacheCloudConversation(actorId, next); setState(next);} catch (error) {if (run !== generation.current || !valid()) return;@@ -81,21 +76,32 @@ export function useCloudCompanionRoom(actorId: string, name: string, enabled: boconst current = latest.current;if (current.identity !== identity || !current.roomId || !current.before || olderPending.current) return;olderPending.current = true;+ const run = generation.current;setState(old => ({ ...old, loadingOlder: true }));try {const page = await api.client.history(current.roomId, current.before);- if (!valid() || latest.current.roomId !== current.roomId) return;- if (latest.current.messages !== current.messages) {- setState(old => ({ ...old, loadingOlder: false })); return;+ if (!valid() || run !== generation.current || latest.current.roomId !== current.roomId) return;+ if (page.historyRevision && page.historyRevision !== current.historyRevision) {+ void forgetCloudConversation(actorId);+ setState(old => ({ ...old, messages: [], before: null, status: 'loading', loadingOlder: false }));+ await reload(); return;}const ids = new Set(current.messages.map(message => message.id));const next = { ...current, messages: [...current.messages, ...page.messages.filter(message => !ids.has(message.id))], before: page.before, loadingOlder: false };void cacheCloudConversation(actorId, { ...next, roomId: current.roomId }); setState(next);} catch (error) {- if (valid() && chatAccessLost(error)) { void forgetCloudConversation(actorId); setState({ ...initial(), status: 'error' }); }- if (valid()) setState(old => ({ ...old, loadingOlder: false }));- } finally { olderPending.current = false; }- }, [api, identity]);+ if (valid() && run === generation.current) {+ if (chatAccessLost(error)) void forgetCloudConversation(actorId);+ setState(old => chatAccessLost(error) ? { ...initial(), status: 'error' } : { ...old, loadingOlder: false });+ }+ } finally {+ olderPending.current = false;+ // A refresh can invalidate this page without replacing the visible state if it fails.+ // Settle this request's loading indicator even when its message result was discarded.+ if (valid()) setState(old => old.identity === identity && old.roomId === current.roomId && old.loadingOlder+ ? { ...old, loadingOlder: false } : old);+ }+ }, [actorId, api, identity, reload]);/** The signed address of one attachment, fetched when it is opened (a stale address is simply fetched again). */const media = useCallback(async (mediaId: string): Promise<BotGroupAttachment> => {const current = latest.current;diff --git a/docs/dev-rules/multi-account-database-architecture.md b/docs/dev-rules/multi-account-database-architecture.mdindex 8ddbc2a959..c20b6bb9a4 100644--- a/docs/dev-rules/multi-account-database-architecture.md+++ b/docs/dev-rules/multi-account-database-architecture.md@@ -301,3 +301,55 @@ family。客户端收到当前 family 失效时,只清理当前 Profile。下一步仍应为 Registry SQLite 适配器、Profile Context、Runtime Lease 和旁路文件建立单独任务;在这些边界得到实现验证前,不应创建新的业务表或批量 migration。++## 11. 聊天数据投影补充(2026-10-26)++> 状态:优化分支已实现首批 Chat 投影,尚未发布;没有迁移全库 Profile。11.2 的完整逻辑集合仍为后续设计,当前物理表见下文。+> 当前路径与账号代次按 [modelDefaultsProfile.ts](../../apps/desktop/src/main/localDb/modelDefaultsProfile.ts) 和 [appSessionState.ts](../../apps/desktop/src/main/appSessionState.ts) 核对;消息同步、恢复与可靠发送见 [伙伴群聊](../product-rules/bot-group-chat.md) 第 11 节。++### 11.1 账号分区++复用当前账号数据库生命周期。当前实现路径来自 `ownerDatabasePath()`,格式为 `<userData>/<品牌前缀>-<ownerId>.db`;部分其他状态位于 `owners/<owner哈希>/`。不得把 本文架构基线 的未来 Profile 路径描述成已经全面实现,也不为本次改造批量给所有旧表加 owner_id。++在账号库中增加 Chat namespace:可信服务端点/realm + 已验证 issuer + membership 身份映射。一个账号访问不同 Chat 服务的数据不得串用,同一房间在直连、device-link 两种路径上不得重复。`deviceId` 是执行地点,不能成为聊天归属主键;消息作者也不等于缓存所有者。++本轮 Desktop 的具体实现是捕获当前 owner 的 `DbClient`,以规范化 endpoint、服务端 `/me` 验证的 human actor ID 和实际 reader actor ID 的 SHA256 作为 namespace。服务端 actor 已绑定 issuer-qualified membership;客户端不自行解析未验证 JWT 来建立归属。migration `0133` 新增:++| 物理表 | 主键 | 内容 |+| --- | --- | --- |+| `chat_cache_rooms` | namespace + room_id | snapshot 元数据、cursor、reset generation、确切页覆盖、metadataDirty、CAS version |+| `chat_cache_messages` | namespace + room_id + message_id | 当前服务器消息 JSON,保留 revision、十进制 seq、tombstone 和未知内容块 |++两表由 `chatCache.execute` worker 事务原子读写;只更新发生变化的消息行。Desktop 与 Mobile 的单房间删除同写入一样校验 version + generation,旧实例不得删除另一实例刚提交或重建的投影;撤权清理碰到并发冲突时仍向当前调用者返回撤权错误,下次读取重新校验权限。账号退出的全量清理仍先失效实例并等待在途写入。查询范围由本地 coverage 决定,seq 用 BigInt 排序,不以 JSON 文本字符串顺序替代消息顺序。每房间最多 500 个已下载页;缺页从服务器补齐。缓存与 canonical messages、未确认发送、附件实际文件分离,reset 只清 Chat 投影。++Mobile 使用现有文件缓存后端的 `cache/chat-history-v1/` 目录,以稳定 ownerId、realm、endpoint、human actor 和 roomId 的 SHA-256 作为文件名;不使用登录 generation 作为永久主键。一个房间的消息、页覆盖与游标放入同一原子替换文件,进程内按文件串行加 version + generation CAS,避免多个挂载回写旧版。正文不占用 AsyncStorage 的共享容量,不新增原生依赖。切账号和退出清理先同步撤销旧实例写权,等待在途文件操作结束后尝试删除全部文件;失败会保留待重试内容,下一次登录在激活身份前重新清理。系统回收可重建缓存后重新 bootstrap,服务器仍保存权威历史。++运行时捕获 ownerGeneration 与数据库句柄;每次跨 await 的写入、事件分发、ACK 和 outbox 执行都复核当前代次。账号切换时停止旧发送和订阅,再切换读取。generation 是运行时代次,不能写进永久主键,避免再次登录制造新库。++退出登录清除凭证并阻断读取;草稿、未确认发送等私有数据按现行账号保留/明确删除策略处理,不能为了重建缓存顺带删除。匿名/本地 Profile 不冒充服务器账号。首次账号映射或迁移有歧义时保留原库并停止关联,不能猜测合并。++### 11.2 推荐表/集合++下表是后续完整逻辑模型,不是本轮新增表清单或可直接执行的 migration。Desktop 与 Mobile 已共用 `maker-shared/chat-history` 算法、分别注入上述存储适配;未来新增原生 SQLite 依赖若触发 fingerprint 变化,仍须走 Mobile 冷更规则。++| 建议集合 | 核心字段/索引 | 用途 |+| --- | --- | --- |+| `chat_namespaces` | local namespace id、可信 endpoint key、issuer、membership binding、schema version | 账号库内进一步区分服务器与身份域 |+| `chat_actors` | namespace + actorId;kind、资料、owner、版本/同步代次 | 群与私聊复用参与者;不强绑本机 bot_profiles |+| `chat_conversations` | namespace + conversationId;kind、状态、元数据版本、lastMessage、activity、summary version | 本地列表与打开入口;个人列表状态单独存 |+| `chat_members` | conversation + actor;role/state/historyFrom/accessRevision | 可见性和权限投影;执行时仍由服务器核验 |+| `chat_messages` | 稳定 localId、可空 serverId、conversation、author/requester、thread/reply、content、revision、createdSeq、createdAt、deleted | 唯一 serverId;按房间/话题和顺序分页;未知块保留原数据 |+| `chat_message_sources` | namespace、sourceKind、sourceSessionId、sourceMessageId、partIndex、serverMessageId | 私聊镜像、长消息拆块与 canonical 主 Session 的精确映射 |+| `chat_reactions`、`chat_reads` | message + actor + emoji;conversation + actor + thread + readSeq/个人标记 | 表情与读位独立更新,不能依赖正文 revision 一起增长 |+| `chat_plans`、`chat_executions` | 服务端实体 ID、revision/epoch、状态、来源消息 | 安排卡与执行状态投影;不保存其他成员私有工具明细 |+| `chat_media_refs` | message、server mediaId、本机引用、下载/校验状态 | 复用媒体仓;短期签名 URL 不作持久身份 |+| `chat_sync_scopes` | namespace + scope;durableCursor、head/floor、bootstrap/reset generation、状态 | 持久化同步进度;每个 actor/房间独立 |+| `chat_pending_refreshes` | scope、entity/range、目标版本/触发 cursor | 不能直接应用的变化先持久化为待补任务 |+| `chat_history_ranges` | conversation、thread、order kind、边界、snapshot watermark、complete/stale | 区分已下载页面、缺口与需重新校验的旧范围 |+| `chat_outbox` | stable clientId/operationId、immutable payload、目标身份、状态、retryAt、回执、附件引用 | 跨重启可靠发送与未知结果恢复;不随投影重建删除 |+| `chat_drafts`、`chat_view_state` | conversation/thread、草稿、滚动锚点、设备内偏好 | 切群恢复;草稿默认仅本设备,跨端草稿另行定义 |+| `chat_runtime_links` | conversation + companion + lane/grant → 本机 Session、执行地点 | 复用既有私聊主 Session、群主线/话题/分工 Session |++sequence/cursor 在协议上保留十进制字符串,计算不得经过不安全的 JavaScript Number;本地索引使用经过范围校验的 64 位表示,或可保持数值顺序的编码,不能直接按可变长字符串排序。原始 JSON 不足以替代分页与关联索引。++旧本地 `bot_group_members.lastSeenSequence` 是伙伴交付进度,不是用户已读;旧 bot_profile 外键无法代表跨账号人类成员。新模型需明确区分,不能只把旧表改名后直接作为统一 Chat 表。diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 91d4bf8300..ab8e442f9d 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -386,6 +386,20 @@ fragment 只允许一个闭集 `app` 提示,不允许额外 `#` / `?` 段;sgp-prod 都部署该页面后,才把 `createInvite` 生成的链接切换为 https。旧客户端点击 https 链接经页面转到 `cindy://` 仍可用,但粘贴 https 链接需要新版客户端。Chat Server API 不变。+## 聊天持久投影的历史修正(2026-10-26)++`BotGroupDetail` 可选追加 `historyRevision?: string` 与 `messageUpdates?: BotGroupMessageView[]`。+前者是不透明的本地投影重建代次,不是服务器房间 revision;新版 UI 发现它变化时丢弃已加载旧页,+再按需补历史。后者返回现有 `sourceMessageIds` 所列已展示消息的当前授权投影,包含删除 tombstone;+不把这些消息追加到最新页,按稳定 id 替换已有旧页。旧客户端忽略附加字段,新客户端连接旧 Host+时沿用原刷新行为。无新 IPC channel、无新的执行权限或服务端必需 capability。++HTTP 继续使用现有 snapshot、messages 与 `/changes`;游标为十进制字符串,计算使用 BigInt。+Desktop 推送帧串行提交本地事务后 ACK;Mobile 活动群先通过 changes 补齐并落盘,再 ACK 通知。+未加载范围不因推进 cursor 被标成已下载。收到 RESET_REQUIRED、成员历史边界变化或明确撤权后,+清除/重建旧覆盖,不能只换最新 100 条而保留未校验旧正文。无 hydrated message 的旧服务端事件+降级为重建投影;新增字段缺省时保留旧端行为。发送与执行上下文仍由现有服务端权限判断。+## 群消息附件的结构化投影Chat Server 群消息投影(Desktop IPC 与 `bot-group-chat` 远程资源共用 `BotGroupMessageView`)的diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.mdindex 976195c733..42be57f493 100644--- a/docs/product-rules/bot-group-chat.md+++ b/docs/product-rules/bot-group-chat.md@@ -1,8 +1,9 @@# 伙伴群聊-> **状态**:权威产品规则(authoritative)。第一、二阶段已实现;第三阶段手机端实现中(第 8 节)。+> **状态**:权威产品规则(authoritative)。本文保留早期本地群的分期说明;当前正式群已接入 Chat Server,手机包含直连和经电脑两条路径(第 8、10 节)。代码核对日期:2026-10-26;具体环境发布情况需单独验证。> **读取时机**:新增或修改伙伴群聊的数据、发言编排、群专线 Session、分工(负责人、安排、分工 Session、群工作目录)、群聊界面、手机端群聊或相关 IPC/远程资源前。> 伙伴身份、Profile、主任务与后台任务的通用契约仍以 [`cindy-bots-runtime.md`](cindy-bots-runtime.md) 为准。+> 当前数据链路与后续优化提案见第 11 节;本地表结构见 [多账号数据库架构](../dev-rules/multi-account-database-architecture.md) 第 11 节,私聊衔接见 [云端伙伴](cloud-companions.md) 第 4.1 节。首批分支实现与后续目标在第 11.0 节分开登记,尚未发布;现行产品规则按该节注明的边界衔接。## 1. 定位与分期@@ -19,7 +20,8 @@能力未部署时明确不可用;旧服务器或旧电脑不通过归档/兼容删除冒充解散。服务端合同、部署前置与兼容细节见 [`protocol-compatibility.md`](../dev-rules/protocol-compatibility.md) 的对应章节。-用户把自己的 2–6 位伙伴放进一个群,用户说一句,伙伴们按规则接话。群聊服务真实工作:+早期本地群以用户自己的 2–6 位伙伴为典型场景;正式服务器群还支持跨账号的人与伙伴成员。+用户发消息,伙伴们按规则接话。群聊服务真实工作:一件事可以由几位伙伴讨论,也可以由负责人分好工,从策划、设计到开发一步步做完。| 阶段 | 范围 | 状态 |@@ -27,7 +29,7 @@| 1 群聊基础 | 本机、同账号伙伴;建群、群里发言、@ 点名、继续讨论、停止、群设置;Desktop | 本文档 || 2 分工 | 负责人伙伴出安排、用户点开始后伙伴一步步做;群工作目录(项目文件夹或群自己的文件夹,git 项目共用一个 worktree 与分支)、每步做完停下等继续(可在本机打开自动交接) | 第 7 节 || 3 手机端 | 手机查看与发言、分工操作、分工停下时推送 | 第 8 节 |-| Chat Server | 跨账号、跨区域的人与伙伴群聊 | 正式接线与旧群迁移补丁中;见第 10 节,需完成部署与存量操作兼容验收后发布 |+| Chat Server | 跨账号、跨区域的人与伙伴群聊 | 客户端正式路径已接线并包含旧群迁移;见第 10 节,发布仍需按具体环境验证部署与兼容能力 |群聊涉及会话生命周期、伙伴运行时与权限,只能由 Core 承载,不做成插件。@@ -62,11 +64,15 @@## 3. 数据与所有权-- 群数据属于当前账号的本地数据库:`bot_groups`(群)、`bot_group_members`(成员与顺序)、- `bot_group_messages`(多作者消息时间线)。群消息时间线是群的权威记录,按 `sequence` 排序。-- 每位成员在每个群里有一条隐藏的**群专线 Session**:`source = 'bot'`,`bot_session_links.role = 'group'`,- `route_key = 'group:<groupId>'`。它与伙伴主任务共享同一个 Profile 与 Bot Home,按需在第一次轮到该伙伴- 发言时创建。+- **正式服务器群的权威记录在 Chat Server**:群、成员、消息、读位、安排和执行分别由服务端实体管理。+ Desktop 经 `withChatServer()` 读取;手机可直连或经电脑读取同一房间。本机目前的短时 snapshot/summary 缓存+ 不等于持久消息库,打开群详情仍会读取服务器。+- `bot_groups`(群)、`bot_group_members`(成员与顺序)、`bot_group_messages`(按 `sequence` 排序的时间线)+ 是早期本地群结构,现仍保留作旧群迁移来源及本机执行关联;不能据此把正式服务器群理解为本机数据库主导。+ 群工作目录、本机自动交接等设备偏好继续按当前账号隔离保存。+- 每位伙伴在每个群里有隐藏的**群专线 Session**:`source = 'bot'`,`bot_session_links.role = 'group'`。+ 早期本地群的 `route_key = 'group:<groupId>'`;服务器群还按执行授权隔离,话题另外隔离上下文。+ Session 按需创建,复用伙伴 Profile 与 Bot Home 的规则,并遵守服务器群的权限档;它不替代共享群消息记录。- **话题是独立对话(2026-10-21,Chris:「话题要真的能把独立事件隔离到独立 session,像 Slack 一样」)**:服务器群里,伙伴在某个话题(Thread)里第一次被叫到时,宿主为「这个话题 × 这次授权 × 这位伙伴」另开一条隐藏 Session,`role = 'group'`,`route_key = '<群专线 route_key>:thread:<根消息 id>'`;之后这个话题里的消息都进它,主群仍用群专线。@@ -77,7 +83,8 @@Profile 版本,权限档跟随伙伴主任务。唯一的例外是灵动岛报错卡:群专线失败时灵动岛照常留下这张卡,点击回到它所在的群并处置被点的那张卡,规则见 `cindy-bots-runtime.md` 6.2;失败本身仍按 4.4 显示在群时间线里。- 伙伴被删除时,其成员关系一并移除;群里已有的消息保留发言时的名字快照。-- 删除群会删除群、成员与群消息,并归档各成员在该群的群专线 Session;伙伴本身、记忆与私聊不受影响。+- 早期本地群的删除会删除本机群、成员与群消息,并归档群专线 Session;伙伴本身、记忆与私聊不受影响。+ 正式服务器群使用第 1 节的解散、退出和个人列表移除,不能沿用本地删除语义清空共享历史。### 3.1 附件@@ -85,7 +92,8 @@- 入口与普通聊天一致:电脑上「+」→「添加文件、图片或视频…」、粘贴、拖入;手机上「+」里的照片、拍照、文件(iOS 有最近照片),以及粘贴图片。一条消息最多 20 个附件;有附件时可以不写字。-- 附件属于用户那条消息(`bot_group_messages.attachments_json`),时间线里显示图片缩略图和文件名。+- 附件属于用户那条消息:早期本地群使用 `bot_group_messages.attachments_json`,正式服务器群使用消息 content 中的 media 块。+ 时间线里显示图片缩略图和文件名。- 主群时间线、Thread 根消息与 Thread 回复共用同一套附件呈现(`BotGroupMessageAttachments`):图片点开看图器,文件 chip 预览或交系统应用。主群里附件与正文同在一个气泡内、排在正文之后(自己的消息也是一个气泡,不再把图片拆在气泡外);@@ -411,10 +419,12 @@ Chat Server 声明 `capabilities.groupSingleSpeaker: 1` 时,服务器群按下### 7.6 数据与生命周期-- 安排与步骤持久保存:`bot_group_plans`、`bot_group_plan_steps`;群的负责人与项目文件夹保存在 `bot_groups`。- 安排卡与交接消息仍是 `bot_group_messages` 时间线里的消息,带安排 id 与文件列表。+- 早期本地群的安排与步骤保存在 `bot_group_plans`、`bot_group_plan_steps`,负责人和项目文件夹保存在 `bot_groups`;+ 安排卡与交接消息属于 `bot_group_messages`。正式服务器群的共享安排、执行和卡片以 Chat Server 为准,+ 项目文件夹、worktree、分工 Session 关联等本机执行信息另按账号隔离保存,见第 10 节。- 应用退出或重启时进行中的一步结束,安排停在该步「没做完 · 重试」,不自动续跑。-- 删除群聊:删除安排与步骤数据,归档各成员在该群的群专线与分工 Session;worktree 与分支保留。+- 早期本地群删除时删除安排与步骤数据,归档群专线与分工 Session;worktree 与分支保留。+ 正式服务器群遵守第 1 节的生命周期,解散停止执行但保留权限内的历史。- 移出成员:它未开始的步骤在轮到时提示伙伴不可用并停下,用户可重试(换人后)或停止;伙伴本身不受影响。## 8. 手机端(第三阶段)@@ -761,7 +771,7 @@ Desktop 群聊与话题之间的分隔线支持左右拖拽和方向键调宽;点 × 先收起,直到出现比收起时更新的未读回复才再出现(按回复序号判断,删除或滑出窗口的回复不会让它重新出现)。已经开在旁边的话题不进提示。不做跨群的全局话题面板(Chris:「到不同频道去看」)。- **已读**:话题面板打开、且停在最新回复处时,把已读位置推进到读到的最新回复;往上翻看时新到的回复保持未读,滚回底部才记为已读。只前进不后退,翻更早的页不算已读。另一台电脑读过,服务器推送 `read.changed`,这里刷新后未读随之清掉;- 「查看更早」打开的旧页不重新读取,其中话题入口的未读随最新话题列表更新。+ 「查看更早」打开的旧页复用本地覆盖,编辑/删除按增量修正,表情/回复数按需重读受影响页;话题入口的未读随最新话题列表更新。- **关注开关**:话题面板右上角「关注」,默认关;打开后显示「已关注」,这个话题的新回复会进群聊右下角的提示。在话题里回复、被 @ 都不会自动关注(Chris:「以免回了一个就关注了,一直通知」),服务端同时去掉了自动关注并清空历史自动关注(cindy-server#1003)。关注状态存在服务器(`POST /conversations/:id/read` 的 `following`,重述原已读位置,不改变已读),@@ -822,3 +832,156 @@ Desktop 群聊与话题之间的分隔线支持左右拖拽和方向键调宽;- Android 可另行开启可见的后台连接,持续通知提供停止按钮;不依赖 Google 服务。它受系统休眠、厂商限制、用户强行停止和网络影响,不是强杀后保活。凭证仅在内存,由现有登录模块刷新;未授权通知时不启动。- 原生接线与服务端部署、FCM 项目配置和真机送达是独立交付项,构建通过不能代替收到通知的实测。++## 11. 聊天本地数据与同步优化(2026-10-26)++> 状态:首批降耗与消息投影已在优化分支实现,尚未发布。主干已补展示缓存与持久发送队列;后续 inbox、显式私聊镜像修订仍是设计目标,不能将整节视为全部上线。+> 客户端核对基线 `0e5057e36f001c0b241104cdc8741deeb15c0e10`;服务端 `9524de9deda2e6313b29a11652d2f90bf3c2788c`。+> SGP 观测、服务器实际表结构与降耗计划维护在服务端仓现有 [Chat Server 合同](https://github.com/xindong/cindy-server/blob/main/docs/chat-server.md),不在客户端重复维护完整运维记录。++实现核对入口:[chatServer.ts](../../apps/desktop/src/main/maker-ipc/chatServer.ts)、[BotGroupChatView.tsx](../../apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx)、[手机 Chat 客户端](../../apps/mobile/src/chat/chatServerClient.ts)。原有文档中的本地群分期不能替代当前代码事实。++### 11.0 本轮实现与边界++- 服务端 `userPrincipal` 已改为已有身份只读,首次创建用 `INSERT ... DO NOTHING`,并发冲突后另一次 SELECT;每次仍校验 disabled 与 actingAs 归属。+- Desktop actor 刷新兜底从 5 秒调整为 60 秒,Auth profile 刷新从 60 秒调整为 300 秒。本机伙伴变化信号、云端 `actor.changed` 仍可主动失效;强制刷新失败保留失效标记,按既有错误退避重试,不能受最近成功登记的 60 秒节流阻挡。+- 每个空闲伙伴独立按 2 / 4 / 8 / 15 秒空领取退避,另加最多 1 秒抖动;本机 2 秒调度 tick 带来不到 2 秒额外等待,因此稳定空闲兜底约 16–18 秒。queued 通知、重连和运行结束重置退避;401/429 等失败等待优先,运行中 15 秒续租及忙碌 lane 的检查保留。尚无覆盖全部未打开房间的可靠工作通知,因此没有拉长到 60 秒。+- 共用 [chatHistory.ts](../../packages/maker-shared/src/chatHistory.ts):首次 snapshot,缺页才取 messages,重启/重连按已提交 cursor 读 changes。已加载旧消息按 revision 更新/保留删除 tombstone;最新页变化后保留旧范围覆盖,分页边界移动不导致所有旧页重新下载。变化正文不带的表情聚合/话题回复数只刷新受影响的已展示页。+- Desktop 在账号 SQLite 的 `chat_cache_rooms`、`chat_cache_messages` 中保存投影(追加 migration `0133`);worker 事务同时提交消息、覆盖范围、snapshot、generation 与 cursor,并用 version + generation 防止并行实例回写旧状态(包括清除重建后的版本号重复)。WebSocket 按序处理,落盘完成后 ACK。+- Mobile 复用现有私有文件缓存能力,在 `cache/chat-history-v1/` 中按账号/realm/endpoint/已验证 human actor/房间生成哈希文件名;每房间消息、页覆盖、游标原子替换,跨挂载 CAS。聊天正文不占用 AsyncStorage,避免多房间累计挤满偏好/草稿的共享库;不新增原生依赖或冷更输入。切账号及退出先失效旧实例、等待在途写入后清理文件,清理失败在下一次登录前重试。元数据失效标记必须在刷新成功落盘后消费,CAS 冲突重试不能丢弃,刷新期间到达的新标记也必须保留。活动群的通知先完成增量补齐再 ACK;列表的跨设备已读通知单独失效相应房间读位,重连、actor 游标重置及手动刷新重新校准个人元数据。+- `RESET_REQUIRED`、游标超前或成员变化会重建整房间覆盖;界面通过 `historyRevision` 丢弃旧页。翻页、引用原文及附件补读也检查代次:发现重置立即清空旧窗口、作废在途读取并重载最新页,不能再次用展示缓存恢复失效窗口。旧代次迟到回包不能混入新窗口。同代次翻页的 `messageUpdates` 同步修正已显示消息,若已有更晚的刷新结果则保留该结果,并补读新加载范围。明确撤权清除投影,普通网络失败保留磁盘数据。增量投影恢复仍需在线校验;主干的独立展示缓存可先显示已保存内容,得知重置或撤权后立即废弃,离线副本不代表最新授权。已校验热缓存最多复用 30 秒,显式刷新/重连立即补 changes;组装详情期间遇到投影代次变化必须重读,不能把旧正文标成新代次。+- Desktop 本地已读、话题已读及关注写入共用失效入口,HTTP 成功后立即使个人元数据失效,不依赖 WebSocket 回声。+- Desktop 群详情返回 `messageUpdates` 修正已展示旧页,更新同样经过话题预览/贴回来源解析,不能把已删除来源的卡片退回旧 fallback;私聊云端转录和手机私聊同样复用持久消息与游标。手机私聊刷新后丢弃过期分页响应,但请求结束仍清除同一房间的加载状态,刷新失败后可以继续翻页。canonical Session、执行授权与接管恢复不读取这份 UI 缓存。Desktop 私聊首次仍按现有消息时间排序合同读取有界历史,后续复用页并补增量。++本轮本地验证:Desktop 聊天/私聊/SQLite/时间线定向测试 492 项、Mobile 聊天与私聊 95 项、共享同步核心 10 项通过;migration 回放 15 项通过。新增持久层与同步测试文件单独运行均低于 5 秒。Desktop Light/Dark 的 56 个 UI 检查变体通过,并检查总览图;未做手机真机、跨设备实网或生产容量验收。服务端全量测试及成员队列扫描上限修复对照见服务端合同。++当前仍会读取执行/安排/失败状态,侧栏也保留旧接口;并未实现零 HTTP 切群、账号 inbox、草稿迁移、actor scope 持久游标或显式修改本机历史后反向修订服务器镜像。缓存最多覆盖每房间 500 页,超限优先淘汰最早的消息范围并保留本次返回页,不能按插入顺序淘汰而让一次新消息触发整段历史重拉;超长积压超过 20 个 changes 批次时重建投影。后续目标与取舍见以下各节。++### 11.1 目标与业务边界++建议统一为「服务器保存已确认的共享聊天记录 → 当前账号的本地数据库保存可恢复投影 → 界面订阅本地变化」。群聊和伙伴私聊共用消息、成员、未读、同步、发送队列模型;伙伴运行时仍独立管理 Session、工具、权限、主力电脑和执行租约。++```mermaid+flowchart LR+ Server["Chat Server:共享记录与权限"] -->|"snapshot / changes"| Sync["账号同步服务"]+ Sync -->|"事务提交后 ACK"| DB["当前账号本地库"]+ DB -->|"列表、消息、读位"| UI["群聊与私聊界面"]+ UI -->|"持久待发送记录"| Outbox["账号发送队列"]+ Outbox -->|"唯一投递路径与幂等 ID"| Delivery["服务器命令或既有 Session 通道"]+ Delivery --> Runtime["伙伴运行时:权限、Session、租约"]+ Runtime -->|"可共享的最终消息与状态"| Server+```++SGP 采样改变了优化顺序:当前请求主要是伙伴领取工作、身份与伙伴列表刷新,不能只优化打开群时的历史读取。先处理鉴权的无变化写入和高频轮询,再推进聊天本地投影;两项工作可分别交付。++| 业务场景 | 目标行为 |+| --- | --- |+| 切回已读过的群或私聊 | 立即显示当前账号的本地记录;同步健康且没有缺口时,不因切换重拉完整详情 |+| 首次打开、翻到未下载的历史 | 有界分页取数、落库、显示;不预下载所有群的全部消息 |+| 新消息、编辑、删除、表情变化 | 增量合并到对应记录,包括已翻开的旧页面;不会重新触发伙伴执行 |+| 断线或重启 | 从已持久化游标补齐;不能把内存收到通知当作同步完成 |+| 账号切换 | 数据库、内存、请求、订阅、发送队列一起切换;迟到结果不能进入新账号 |+| 群成员被移出、权限收紧 | 根据明确权限事件收窄本地可见数据;网络故障不等于权限被撤销 |+| 伙伴主力电脑在线/离线/接管 | 房间和聊天记录身份稳定,执行地点可以变;保留现有本机与 device-link 能力 |+| 本机尚未上云的伙伴 | 保留本机使用能力;使用本地稳定标识,注册成功后建立映射,不能新建第二份记录 |++「聊天记录」只包含当前用户有权看到的内容。工具参数、私有推理、权限确认、后台执行上下文,不因统一聊天数据层而变成群成员可读的数据。++### 11.2 当前读取与缓存++正式群通过 `withChatServer()` 接入服务器;旧 `bot_groups` 等表仍用于旧群迁移和本机执行关联,不是正式服务器群消息的权威存储。新增 Chat 投影只缓存已下载范围,不冒充完整历史或执行数据库。++`BotGroupChatView` 在 groupId 变化时加载详情;生产 `getGroup → detail` 通过持久投影读取 snapshot 与主时间线,30 秒内可复用已校验状态,过期/重连/本地写入后补 changes。管理、发送授权准备和执行上下文继续走现有权威读取。约 60 秒 summary 缓存仍供侧栏使用。旧页通过可选 `messageUpdates` 和 `historyRevision` 接收修正与重建信号。++主干已为 Desktop 增加持久 outbox 与发送 journal,为 Mobile 接入 durable outbox;保存的展示窗口与增量投影分工见 [本地接入合同](../dev-rules/chat-server-local-test.md)。本轮手机增加独立的持久消息投影,复用原列表缓存、读位和 endpoint 规则;直连服务器和经电脑 Remote Resource 仍是同一房间的两种访问路径。++伙伴私聊以 canonical 主 Session 为本机界面入口;在线远端通过 device-link,离线远端读取服务器房间。主力电脑镜像用户可见消息及最终回复,按 `sourceId` 导入去重;重复 sourceId 返回既有记录,不会自动把旧记录更新为新内容。Desktop 云端转录首次可能多页回读后按消息时间排序,之后从持久覆盖范围读取并按 cursor 修正。手机私聊保留按需翻页,刷新时修正已展示旧页。显式修改的反向镜像仍待协议设计。++### 11.3 同步算法与历史变化++以下包含完整目标;已实现范围以 11.0 为准。主干已补本地展示首屏与持久发送;草稿、账号 inbox 与通用待补任务表仍不在本轮范围。++#### 11.3.1 首次打开和正常增量++1. 先查询本地数据库,恢复最后可见页面、草稿与滚动锚点;界面区分「正在同步」和「尚未下载」。+2. 无本地投影时获取一致 snapshot 与 cursor;现有服务端 snapshot 使用事务快照,适合作为房间基线。snapshot 的最新 100 条包含话题,不能据此声明主时间线已完整下载。+3. 从基线 cursor 重放 changes,分页补齐主时间线/指定话题缺口。历史页、snapshot 和 changes 并发返回时按版本与基线合并;晚到的旧页不能覆盖已处理的编辑或复活 tombstone。+4. 实体更新、派生状态和 durable cursor 在一个本地事务提交后再 ACK;无法直接应用的实体变化,将待补任务与 cursor 同事务保存,保证崩溃后仍会补齐。界面在实体刷新前显示待同步状态,不能误称内容已最新。+5. 相同事件重复收到应幂等。服务端 changes 可能按当前权限重取实体,并非事件发生时的旧正文;按实体 revision 合并,表情、读位等另外遵循自身顺序/版本,不能因为消息正文 revision 相同就丢弃。+6. 部分事件被可见性过滤,返回空 events 仍可能推进 cursor;按服务端返回 cursor 提交,不用最后一个可见事件推算。++现有表情事件的实体重取不等于返回完整表情集合,需按事件数据能力应用或有界批量重读相关实体。一次变化应尽量只更新受影响消息/卡片,避免所有事件都触发完整 snapshot + executions + plans。++账号列表初始化也要保证无丢事件窗口:建议新增与 actor cursor 一致的 inbox snapshot;兼容旧接口时先取得 cursor,再读列表,再重放期间变化。不能先读列表、再拿新 cursor 而跳过期间更新。++#### 11.3.2 必须接收哪些历史变化++| 变化 | 本地动作 | 是否触发伙伴工作 |+| --- | --- | --- |+| 显式编辑消息 | 同一 serverId 按 revision 更新正文、引用预览、摘要/搜索投影 | 否;用户另行明确重做才产生新命令 |+| 删除消息 | 保留必要 tombstone 与版本,清除正文、搜索索引、失效预览与不再授权的媒体引用 | 否;正在执行的取消由服务端执行状态决定 |+| 表情、跟随、已读、标为未读 | 更新对应独立实体和个人状态 | 否 |+| 安排/执行状态 | 更新相应卡片和状态投影 | 仅执行系统按新租约领取,不由界面变化触发 |+| 成员退出、访问范围收紧 | 使相关范围不可读,清理受影响缓存/索引/媒体引用并停止订阅 | 不扩大执行权限 |+| 补传过去的私聊记录 | 幂等补入历史位置,保持当前滚动锚点;默认不新增通知/未读 | 否,保持 import 语义 |+| Agent 压缩上下文、内部 rewind 或工具日志变化 | 只影响执行记录;不自动转为聊天删除/重写 | 否 |++私聊需要补充「显式用户可见修改 → source mapping → 服务端修订/删除」合同。现有 import 去重不是编辑同步。长消息拆块需要 partIndex 映射和多块一致更新/删除策略,不能仅靠文本相似度匹配。++#### 11.3.3 断线、reset 与撤权++- 正常断线从 durable cursor 继续;重连加入抖动和有界并发,优先当前房间、账号列表,再按需追后台房间。+- `RESET_REQUIRED` 意味着游标过期或可见历史边界变化;将已缓存的相关历史范围标为 stale,不仅重取最新 100 条。旧范围重新验证前不能作为最新有效正文对外展示/搜索;按需重取,并补建 tombstone/权限边界。+- 分页返回没有某条消息不等于该消息已删除;只有权威删除或完成了对应范围校验才能清除。新旧页之间的空洞显式记录。+- 确认被移除或权限收紧后,及时收窄本地缓存;普通超时、5xx、Token 过期不能误删历史。离线设备无法实时获知远端撤权,必须明确这是离线权限信息滞后的固有限制。+- 不订阅所有房间。现有单连接最多 16 个 scope,actor 也占一个;优先账号 inbox 与当前/少量活跃房间。后台摘要由账号级变更更新,进入房间再补正文游标。++### 11.4 可靠发送++发送前在当前账号库生成 clientId/operationId,写入不可变 payload 与 outbox,再显示 pending。附件先固定到账号拥有的可靠存储并建立引用,不能只保存可能被外部修改的原文件路径。发送回执建立 localId → serverId 关系,推送早于回执时也必须最终合并为一条。++状态至少区分:待发送、上传中、发送中、结果未知、服务器已接受、失败可重试。服务器已接受消息与伙伴开始/完成执行是两套状态。崩溃、超时、重连使用同一 operationId 和相同 payload 重试;不重新生成 ID 造成重复消息。仅以相同正文和附件数量猜测去重不足以支撑可靠发送。++服务端新增可验证的发送关联能力应向后兼容;不能向其他成员泄露不必要的内部 source 信息。旧端使用回执关联,新端启用完整能力后再取消启发式匹配。命令保留期与最长自动重试期限须一起定义;超过幂等凭据保留期的未知结果先查证,不自动生成新 ID 重发。++### 11.5 降低聊天读取开销++- 新增轻量、分页的账号 inbox 投影:房间信息、可见最后消息摘要、个人未读/列表状态、必要执行概况及版本。避免侧栏逐群请求 3 个详情接口。此处是建议能力,不是已存在的新 API 路径。+- 摘要和未读遵守每位成员 history_from、话题关注、导入及本人消息规则;不能缓存一个房间摘要无差别给所有成员,也不能每次打开列表全表 COUNT。+- 当前房间正文用局部增量和有界历史页;旧协议过渡期合并相同请求,按变化范围失效、限制并发、调整后台刷新频率,不能用长 TTL 掩盖权限变化。+- inbox 投影会增加写入/扇出成本:小群可按成员维护个人派生状态,大群要评估事件合并、共享房间状态+个人读位的读取组合。先测成员数和活跃分布,再决定物化粒度,不预设全量逐成员写是免费的。++### 11.6 交付、验证与回滚++| 批次 | 交付 | 可观察验收 |+| --- | --- | --- |+| 0 测量与服务端低风险降耗 | 补路由/claim/DB等待指标;actor 鉴权去无变化写入;不改聊天 wire 语义 | 正常身份请求不产生 actor UPDATE,首次并发创建/禁用/actingAs 行为保持;对照 CPU、WAL、锁等待和延迟 |+| 1 轮询与工作唤醒 | 分离 register 与领取;可靠工作通知、断线补拉、空领取退避;旧端兼容 | 无工作时请求显著下降;主力电脑切换、遗漏通知、入群工作、并发 lane、租约续期均不丢工作不重复执行 |+| 2 群聊本地投影 | 账号隔离表、持久游标、历史范围、可靠 outbox;按能力接入 inbox | 热切群本地首屏,稳定同步时零完整详情重拉;旧页编辑/删除正确;崩溃后从提交游标恢复 |+| 3 私聊统一 | source mapping、显式修订同步、历史时间分页、runtime overlay | 原私聊功能不退化,导入不重跑,长消息不重复,接管后身份和历史稳定 |+| 4 Mobile 与服务端进一步降耗 | 同一同步规则的手机适配;按观测优化实时调度/dispatch/保留 | 直连与经电脑不出现两份房间;后台恢复、冷更边界与峰值压测达标 |++上表阶段 2 的 inbox 依赖服务端增量能力,可先单独交付;未具备能力的客户端保留有界兼容读取。阶段 0、1 应优先于大规模客户端表迁移,因为能更早降低当前 SGP 的主要开销。++验证至少覆盖以下真实故障输入,而非只测字段常量:++- 发送已经成功但回执丢失后重启;推送先于回执;附件上传后切换账号。+- 旧历史页请求在编辑/删除事件之后返回;同一事件重复、乱序;表情变化但正文版本不变。+- cursor 过期、缺页、被过滤事件、成员权限收紧;离线后重新登录同账号与换账号。+- 注册缺失 actor 并发创建、actor 被禁用、同账号代伙伴、跨账号 actingAs 拒绝。+- 空 claim、普通执行、入群工作、不同 lane 并行、主力电脑接管、断线漏通知与租约到期。+- 私聊长消息拆块、旧历史晚到、内部压缩与显式删除的区别;不能因收到历史而再次执行。++性能对照优先使用「每在线设备每分钟请求数」「每次有效领取对应 claim 次数」「每千请求 actor UPDATE/DB CPU/WAL」「每次切群请求与字节」「每个变更的 DB 查询数」,同时看 P95/P99 和失败率。目标是降低单位业务成本,不以缩容后的单 Pod CPU 上升判断退步。++建议验收目标(待同硬件、同数据、同网络基线校准,**不是已测结果或容量承诺**):无资料变化的空闲 `/me + /actors` 请求减少至少 90%;可靠通知健康时空领取请求减少至少 90%;账号库已有数据的热切换首屏 P95 ≤150 ms;新增消息到可见、执行唤醒延迟不劣于基线。节省 CPU 的比例不能直接套用请求下降比例。++压测在隔离环境做:固定在线设备与每设备伙伴数,分别覆盖空闲、活跃群、私聊导入、编辑旧消息、大群扇出、断线重连。测试 100/500/1,000 WS 每实例、2/20/200/1,000 成员群、1 千/10 万/100 万消息历史,以及逐级提升事件速率;这些只是输入档位。记录实际承载点、pool wait、DB CPU/I/O/WAL、锁等待、队列积压、API 延迟、内存、网络与慢消费者。生产只做有界只读观测和分阶段灰度。++所有本地 schema 只追加 migration,不重写历史;保留旧群迁移来源和 Session。投影可重建,outbox/草稿/source mapping/唯一消息不可当缓存清空。回滚时一次只保留一个发送消费者,同一 operationId 继续查证/重试,不能让新旧链路各发送一次。旧客户端与新服务端、旧服务端与新客户端分别做能力降级验证;服务端发布和 migration 在独立仓按它的部署规则推进。++### 11.7 推荐的产品取舍++以下作为实现讨论默认值,尚不替代产品裁决:显式编辑/删除同步到各端,Agent 内部上下文压缩不删聊天;历史补传不制造未读;草稿先按设备保存;离线发送明确展示待发送且不静默切换执行电脑;权限变化优先于缓存命中;聊天列表以本地投影显示,服务器仍是共享记录与权限的最终依据。++真正需要长期维护的是一份按账号隔离、可增量修正、可恢复的聊天数据库,以及低成本的工作唤醒机制。单纯加长当前 snapshot TTL,无法解决历史变化、跨端一致性、可靠发送,也无法解决本次观察到的主要服务器开销。diff --git a/docs/product-rules/cloud-companions.md b/docs/product-rules/cloud-companions.mdindex c70bb4743d..33ab5004c3 100644--- a/docs/product-rules/cloud-companions.md+++ b/docs/product-rules/cloud-companions.md@@ -125,7 +125,12 @@## 4. 1:1 对话层同步-- 每个伙伴在 Chat Server 上有一个固定的私聊房间(主人 ↔ 伙伴),房间 ID 由伙伴 actor ID 确定,+> 2026-10-26 代码核对:本机界面仍以伙伴主 Session 为入口,在线远端使用 device-link,离线远端读取云端房间;+> 当前不是各端共用的持久聊天投影。`mirror.ts` 通过 sourceId 导入去重,重复导入不会自动更新旧消息;+> 显式编辑/删除的跨端修订同步需要补充合同。首次云端转录读取还可能多页回读后按时间排序,再在内存复用。+> 持久消息投影的首批分支实现与后续目标见本节 4.1 及 [伙伴群聊](bot-group-chat.md) 第 11 节,尚未发布;下述执行和权限边界继续适用。++- 每个伙伴在 Chat Server 上有一个固定的私聊房间(主人 ↔ 伙伴),房间 ID 由主人 human actor 与伙伴 actor 的组合确定,任意电脑并发创建得到同一个房间。- 主力电脑把主任务里用户可见的消息和伙伴的最终回复按顺序导入这个房间(导入不触发伙伴执行、不发通知),以本机消息 ID 去重,断网后从上次位置续传。主人发送的图片和文件经房间附件上传,其他设备可以打开,换电脑时下载到新电脑;@@ -160,6 +165,22 @@- 房间里由主人直接发出的消息(例如未来的离线排队)在主力电脑上线后由它领取,作为「来自其他设备」的消息投递进主任务;伙伴回复由导入同步回房间,不重复写。主任务未在运行时按它保存的权限档唤醒,不借后台唤醒的默认完全访问。房间消息等同同账号设备远程操作这台电脑,只在这台电脑开启「允许同账号设备控制本机」时投递(否则该条执行失败、不进主任务);房间消息没有经认证的设备标识,无法按「已撤销的控制设备」逐台拒绝。+### 4.1 私聊统一数据层(2026-10-26)++> 状态:云端消息的持久读取投影与历史增量修正已在优化分支实现,尚未发布;主干已补展示缓存与持久发送,反向镜像修订与时间分页仍待实现。现行发送路径、权限及主力电脑行为保留。本地表与账号边界见 [多账号数据库架构](../dev-rules/multi-account-database-architecture.md) 第 11 节;完整交付范围见 [伙伴群聊](bot-group-chat.md) 11.0。++Desktop `runtime.transcript()` 经注入的 Chat History 读取,首次按现有时间排序合同读有界历史,后续复用持久页覆盖并补 changes;新消息导致分页边界移动时拼接已知范围,不重新下载所有旧页。翻页先走共享同步的有效性检查,generation 与 cursor 未变时复用已排序的整段结果,不逐页重扫;主动刷新、过期或重连仍校准 changes,历史修订、重置及撤权不能被五分钟展示缓存遮住。Mobile 的 `history()` 同样落盘,刷新时以 message ID 修正已展示的编辑/删除;房间与历史代次未变时保留被新消息挤出首屏的已加载消息,不按新旧数组长度决定保留;reset generation 变化时清掉旧页。接管、merge 和主任务重建仍走完整、权威读取,不能把有界 UI 缓存当作全部历史导入。++先统一**记录与同步**,保留 canonical 主 Session 的现有执行能力:本机发送仍可交本机,在线远端按现有 device-link 路径执行,最终可见消息按 source mapping 镜像到同一个 direct 房间。流式输出作为有权限的临时运行状态,最终回复到达后按映射合并,不持久化每个 token 为聊天变更。++每条用户输入确定唯一投递路径,禁止同时「POST 房间以触发执行」和「直接投递 Session」执行两次。云端排队发送仅在明确能力、远程控制授权与离线产品行为确定后启用;不能为了统一协议削弱本机离线能力、静默接管其他电脑或绕过执行授权。++群主线、Thread、分工和伙伴主私聊保持独立 Session/lane;统一 Chat 表不合并它们的模型上下文。工作目录、worktree、主力电脑、本机自动交接属于运行/设备偏好,不塞进公共消息正文。++当前私聊历史回补可能晚到,因此 `created_seq` 到达顺序与显示时间顺序不同。建议增加稳定的 `(createdAt, serverId)` 历史分页能力及对应索引,cursor 仍负责变化同步;避免每次先取全部历史再排序。相同时间用稳定次序,晚到记录插入历史时保持用户滚动位置。新索引必须先做真实数据规模的执行计划与构建成本验证。++显式修改用户可见消息时,通过 `sourceSessionId + sourceMessageId + partIndex` 找到服务器记录并同步修订/删除。当前 `/import` 重复 sourceId 只去重,不能当编辑协议使用;长消息拆块需要一致更新/删除规则。内部上下文压缩或工具日志变化不自动删除聊天,历史补传不触发执行或新增通知。实现入口为 `companion-cloud/mirror.ts`、`runtime.ts`、`room.ts`,跨端新能力须先明确兼容合同。+## 5. 管理用户开放的其他电脑- 伙伴可以在用户开放的其他电脑上干活:沿用协同(Orca)的跨电脑执行,`get_workspace_info` 返回的diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.jsonindex ca75161b3e..94716bc268 100644--- a/packages/maker-shared/package.json+++ b/packages/maker-shared/package.json@@ -16,6 +16,7 @@"./branding": "./src/branding.ts","./brand-identity": "./src/brandIdentity.ts","./chat-quotes": "./src/chatQuotes.ts",+ "./chat-history": "./src/chatHistory.ts","./chat-reply-quote": "./src/chatReplyQuote.ts","./command-display": "./src/commandDisplay.ts","./client-endpoints": "./src/clientEndpoints.ts",diff --git a/packages/maker-shared/src/__tests__/chatHistory.test.ts b/packages/maker-shared/src/__tests__/chatHistory.test.tsnew file mode 100644index 0000000000..8d02da2981--- /dev/null+++ b/packages/maker-shared/src/__tests__/chatHistory.test.ts@@ -0,0 +1,228 @@+import { describe, expect, it, vi } from 'vitest';+import { createChatHistory, type ChatHistoryBatch, type ChatHistoryState, type ChatHistoryStore } from '../chatHistory.js';++// Unit tier: UI history previously refetched pages and lost edits outside the latest page.+// Exercise the actual cache entry points with restart, durable failure and ordered wire events.+function fixture() {+ const disk = new Map<string, ChatHistoryState>();+ const store: ChatHistoryStore = {+ read: async room => structuredClone(disk.get(room)),+ write: vi.fn(async (room, state) => { if (state) disk.set(room, structuredClone(state)); else disk.delete(room); }),+ };+ const message = (id: string, revision = 1, deleted = false) => ({ id, seq: id, revision, deleted, text: deleted ? '' : `v${revision}`, threadRootId: null });+ let batch: ChatHistoryBatch = { cursor: '10', changes: [] };+ let live = true;+ let generation = 0;+ const api = vi.fn(async (route: string): Promise<unknown> => {+ if (route.endsWith('/snapshot')) return { room: { id: 'room', kind: 'group' }, messages: [message('9')], cursor: '10' };+ if (route.startsWith('/changes?')) return batch;+ return [message('2'), message('1')];+ });+ const open = () => createChatHistory({ api: api as <T>(route: string) => Promise<T>, store, current: () => live, newGeneration: () => String(++generation) });+ const page = new URLSearchParams('limit=100&before=5');+ return { disk, store, api, open, message, page, setBatch: (value: ChatHistoryBatch) => { batch = value; }, leave: () => { live = false; } };+}++describe('durable chat history', () => {+ it('retries a concurrent writer conflict without overwriting its newer historical edit', async () => {+ const f = fixture(); const cache = f.open(); await cache.page('room', f.page);+ vi.mocked(f.store.write).mockImplementationOnce(async () => {+ const newer = f.disk.get('room')!;+ newer.cursor = '11'; newer.messages['1'] = f.message('1', 2);+ throw new Error('CHAT_CACHE_CONFLICT');+ });+ await cache.receive('room', { cursor: '12', changes: [{ type: 'message.deleted', data: { message: f.message('2', 2, true) } }] }, '10');+ expect(f.disk.get('room')?.cursor).toBe('12');+ expect((await cache.projection('room', ['1', '2'])).messages).toEqual([f.message('1', 2), f.message('2', 2, true)]);+ });++ // Unit: another mounted cache can win between actor-read invalidation and save.+ // A retry must still refresh personal metadata before callers acknowledge that event.+ it('retains personal metadata invalidation across a concurrent writer conflict', async () => {+ const f = fixture(); let readSeq = '0';+ const original = f.api.getMockImplementation()!;+ f.api.mockImplementation(async route => route.endsWith('/snapshot')+ ? { room: { id: 'room' }, cursor: '10', messages: [], reads: [{ thread_key: 'main', read_seq: readSeq }] }+ : original(route));+ const cache = f.open(); await cache.snapshot('room');+ readSeq = '9'; cache.invalidate('room', true);+ vi.mocked(f.store.write).mockRejectedValueOnce(new Error('CHAT_CACHE_CONFLICT'));+ expect(await cache.snapshot('room')).toMatchObject({ reads: [{ read_seq: '9' }] });+ expect(f.disk.get('room')?.snapshot).toMatchObject({ reads: [{ read_seq: '9' }] });+ // A second notice arriving during the metadata read must outlive the first+ // refresh's successful commit as well, rather than being cleared with it.+ const responding = f.api.getMockImplementation()!;+ let finish!: () => void;+ f.api.mockImplementation(async route => {+ const value = await responding(route);+ if (route.endsWith('/snapshot')) await new Promise<void>(resolve => { finish = resolve; });+ return value;+ });+ cache.invalidate('room', true); const pending = cache.snapshot('room');+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'), { interval: 1 });+ readSeq = '10'; cache.invalidate('room', true); finish(); await pending;+ f.api.mockImplementation(responding);+ expect(await cache.snapshot('room')).toMatchObject({ reads: [{ read_seq: '10' }] });+ });++ it('stitches known ranges when a new message shifts all older pagination boundaries', async () => {+ const f = fixture(); const cache = f.open();+ let newest = 6;+ f.api.mockImplementation(async route => {+ if (route.endsWith('/snapshot')) return { room: { id: 'room' }, messages: [], cursor: '10' };+ const query = new URL(`https://fixture${route}`).searchParams;+ const before = Number(query.get('before') ?? newest + 1);+ return Array.from({ length: Math.min(3, before - 1) }, (_, n) => f.message(String(before - 1 - n)));+ });+ await cache.page('room', new URLSearchParams('limit=3'));+ await cache.page('room', new URLSearchParams('limit=3&before=4'));+ await cache.receive('room', { cursor: '11', changes: [{ type: 'message.created', data: { message: f.message('7') } }] }, '10');+ newest = 7; f.api.mockClear();+ expect((await cache.page('room', new URLSearchParams('limit=3'))).map(m => m.id)).toEqual(['7', '6', '5']);+ expect((await cache.page('room', new URLSearchParams('limit=3&before=5'))).map(m => m.id)).toEqual(['4', '3', '2']);+ expect(f.api).toHaveBeenCalledTimes(1);+ });+ it('reuses covered pages after restart and applies edits and tombstones outside the latest window', async () => {+ const f = fixture();+ await f.open().page('room', f.page);+ f.api.mockClear();+ f.setBatch({ cursor: '12', changes: [+ { type: 'message.updated', entityId: '1', data: { message: f.message('1', 2) } },+ { type: 'message.deleted', entityId: '2', data: { message: f.message('2', 2, true) } },+ ] });+ const fresh = f.open();+ expect(await fresh.page('room', f.page)).toEqual([f.message('2', 2, true), f.message('1', 2)]);+ expect(f.api.mock.calls.map(([route]) => route)).toEqual(['/changes?scope=conversation:room&after=10&limit=100']);+ expect(f.disk.get('room')?.cursor).toBe('12');+ await fresh.page('room', new URLSearchParams('limit=100&before=8'));+ expect(f.api.mock.calls.at(-1)?.[0]).toBe('/conversations/room/messages?limit=100&before=8');+ // A late page carrying revision 1 never resurrects revision 2.+ expect((await fresh.projection('room', ['2'])).messages).toEqual([f.message('2', 2, true)]);+ });++ // PR #7242, unit: one new head at the 500-page limit used to evict each next+ // page during a forward scan. Existing shifted-boundary coverage never filled the cache.+ it('retains the next cached pages during a full scan at capacity after a new message', async () => {+ const f = fixture();+ const state: ChatHistoryState = { generation: 'saved', snapshot: { room: { id: 'room' }, messages: [], cursor: '10' },+ cursor: '10', messages: {}, pages: {}, metadataDirty: false };+ // One message per page keeps the capacity/eviction regression small while using+ // the same production page, persistence and coverage-stitching entry points.+ for (let seq = 500; seq >= 1; seq--) {+ state.messages[String(seq)] = f.message(String(seq));+ state.pages[seq === 500 ? 'limit=1' : `limit=1&before=${seq + 1}`] = [String(seq)];+ }+ f.disk.set('room', state);+ const cache = f.open();+ await cache.receive('room', { cursor: '11', changes: [{ type: 'message.created', data: { message: f.message('501') } }] }, '10');+ f.api.mockImplementation(async route => {+ const before = new URL(`https://fixture${route}`).searchParams.get('before');+ return [f.message(before ? String(Number(before) - 1) : '501')];+ });+ // receive() does not mark the restored cache checked; retain its real empty delta read.+ const messagesApi = f.api.getMockImplementation()!;+ f.api.mockImplementation(async route => route.startsWith('/changes?')+ ? { cursor: '11', changes: [] } : messagesApi(route));+ for (let seq = 501; seq >= 2; seq--) {+ const query = new URLSearchParams(seq === 501 ? 'limit=1' : `limit=1&before=${seq + 1}`);+ expect((await cache.page('room', query)).map(message => message.id)).toEqual([String(seq)]);+ }+ expect(f.api.mock.calls.filter(([route]) => route.includes('/messages?'))).toHaveLength(1);+ expect(Object.keys(f.disk.get('room')!.pages)).toHaveLength(500);+ // Evicting old coverage must not prune the very page the caller is receiving.+ expect(await cache.page('room', new URLSearchParams('limit=1&before=2'))).toEqual([f.message('1')]);+ expect(Object.keys(f.disk.get('room')!.pages)).toHaveLength(500);+ });++ // Personal read positions have an actor cursor, separate from room message changes.+ it('reauthorizes personal snapshot metadata after reconnect even when room changes are empty', async () => {+ const f = fixture(); let readSeq = '0';+ const original = f.api.getMockImplementation()!;+ f.api.mockImplementation(async route => route.endsWith('/snapshot')+ ? { room: { id: 'room' }, cursor: '10', messages: [], reads: [{ thread_key: 'main', read_seq: readSeq }] }+ : original(route));+ const cache = f.open(); await cache.snapshot('room');+ readSeq = '9'; cache.reconnect();+ expect(await cache.snapshot('room')).toMatchObject({ reads: [{ read_seq: '9' }] });+ f.api.mockClear(); cache.invalidate('room'); await cache.snapshot('room');+ expect(f.api.mock.calls.map(([route]) => route)).toEqual(['/changes?scope=conversation:room&after=10&limit=100']);+ // A room loaded from disk after the connection is restored needs the same calibration.+ const restarted = f.open(); readSeq = '10'; restarted.reconnect();+ expect(await restarted.snapshot('room')).toMatchObject({ reads: [{ read_seq: '10' }] });+ });++ it('drops every older range on RESET_REQUIRED and changes the renderer generation', async () => {+ const f = fixture(); const cache = f.open();+ await cache.page('room', f.page);+ const previous = (await cache.projection('room', ['1'])).generation;+ f.api.mockImplementationOnce(async () => { throw new Error('RESET_REQUIRED'); });+ cache.reconnect();+ expect((await cache.projection('room', ['1'])).messages).toEqual([]);+ expect((await cache.projection('room', [])).generation).not.toBe(previous);+ expect(f.disk.get('room')?.pages).toEqual({});+ await cache.page('room', f.page);+ expect(f.api.mock.calls.at(-1)?.[0]).toContain('/messages?');+ });++ it('refreshes reaction aggregates on an old visible page instead of silently retaining old badges', async () => {+ const f = fixture(); const cache = f.open(); await cache.page('room', f.page);+ await cache.receive('room', { cursor: '11', changes: [{ type: 'reaction.changed', entityId: '1', data: { message: f.message('1') } }] }, '10');+ f.api.mockClear();+ f.api.mockResolvedValueOnce([{ ...f.message('2') }, { ...f.message('1'), reactions: [{ emoji: 'like', count: 2 }] }]);+ expect((await cache.projection('room', ['1'])).messages).toEqual([{ ...f.message('1'), reactions: [{ emoji: 'like', count: 2 }] }]);+ expect(f.api.mock.calls.map(([route]) => route)).toEqual(['/conversations/room/messages?limit=100&before=5']);+ });++ it('does not advance a durable cursor when saving an event fails, and replays it on restart', async () => {+ const f = fixture(); const cache = f.open();+ await cache.page('room', f.page);+ const batch = { cursor: '11', changes: [{ type: 'message.deleted', data: { message: f.message('1', 2, true) } }] };+ vi.mocked(f.store.write).mockRejectedValueOnce(new Error('disk full'));+ await expect(cache.receive('room', batch, '10')).rejects.toThrow('disk full');+ expect(f.disk.get('room')?.cursor).toBe('10');+ f.setBatch(batch);+ expect((await f.open().page('room', f.page))[1]).toEqual(f.message('1', 2, true));+ });++ it('serializes a delayed page with the next edit and verifies a subscription gap through changes', async () => {+ const f = fixture(); const cache = f.open(); await cache.snapshot('room');+ let finish!: (value: unknown) => void;+ f.api.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ const page = cache.page('room', f.page);+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'), { interval: 1 });+ const receive = cache.receive('room', { cursor: '11', changes: [{ type: 'message.updated', data: { message: f.message('1', 2) } }] }, '10');+ finish([f.message('1')]); await page; await receive;+ expect((await cache.page('room', f.page))[0]).toEqual(f.message('1', 2));+ f.api.mockClear();+ f.setBatch({ cursor: '20', changes: [{ type: 'message.deleted', data: { message: f.message('1', 3, true) } }] });+ await cache.receive('room', { cursor: '20', changes: [] }, '19');+ expect(f.api.mock.calls[0]?.[0]).toContain('after=11');+ expect((await cache.page('room', f.page))[0]).toEqual(f.message('1', 3, true));+ });++ // PR #7242, unit: a stale deletion conflict must not hide the permission error+ // that makes the caller clear its UI; the next read still has to reauthorize.+ it('preserves a revocation error when another mount wins the cleanup CAS', async () => {+ const f = fixture(); const cache = f.open(); await cache.page('room', f.page);+ vi.mocked(f.store.write).mockImplementationOnce(async () => {+ f.disk.get('room')!.generation = 'newer';+ throw new Error('CHAT_CACHE_CONFLICT');+ });+ f.api.mockRejectedValueOnce(new Error('FORBIDDEN')); cache.reconnect();+ await expect(cache.snapshot('room')).rejects.toThrow('FORBIDDEN');+ expect(f.disk.get('room')?.generation).toBe('newer');+ f.api.mockRejectedValueOnce(new Error('FORBIDDEN'));+ await expect(cache.snapshot('room')).rejects.toThrow('FORBIDDEN');+ expect(f.disk.has('room')).toBe(false);+ });++ it('clears revoked history and never persists a response after an owner switch', async () => {+ const f = fixture(); const cache = f.open(); await cache.page('room', f.page);+ f.api.mockRejectedValueOnce(new Error('CONVERSATION_NOT_FOUND')); cache.reconnect();+ await expect(cache.snapshot('room')).rejects.toThrow('CONVERSATION_NOT_FOUND');+ expect(f.disk.has('room')).toBe(false);+ f.api.mockImplementationOnce(async () => { f.leave(); return { room: { id: 'room' }, messages: [], cursor: '20' }; });+ await expect(cache.snapshot('room')).rejects.toThrow('OWNER_CHANGED');+ expect(f.disk.has('room')).toBe(false);+ });+});diff --git a/packages/maker-shared/src/botGroupChat.ts b/packages/maker-shared/src/botGroupChat.tsindex 7dbd0f0256..d7a0115102 100644--- a/packages/maker-shared/src/botGroupChat.ts+++ b/packages/maker-shared/src/botGroupChat.ts@@ -507,6 +507,10 @@ export interface BotGroupSummary {}export interface BotGroupDetail extends BotGroupSummary {+ /** Durable cache generation. A changed value discards pages from a previous history/permission boundary. */+ historyRevision?: string;+ /** Current authorized versions of already displayed messages, including deletion tombstones. */+ messageUpdates?: BotGroupMessageView[];/** Room-wide; bumped when a reset skipped realtime events or the chat runtime was recreated, so every message's reactors count as changed. */reactionRevision?: number;/** Per message id; bumped by realtime reaction changes, so a same-count change of who reacted is noticed. */diff --git a/packages/maker-shared/src/chatHistory.ts b/packages/maker-shared/src/chatHistory.tsnew file mode 100644index 0000000000..59d0f12f10--- /dev/null+++ b/packages/maker-shared/src/chatHistory.ts@@ -0,0 +1,278 @@+/** A disposable, authorized server projection. Runtime/model history is deliberately separate. */+export interface ChatHistoryMessage {+ id: string; seq: string; revision?: number; deleted?: boolean; threadRootId?: string | null;+}+export interface ChatHistorySnapshot {+ room: { id: string; kind?: string }; cursor: string; messages: ChatHistoryMessage[];+}+export interface ChatHistoryState {+ generation: string;+ snapshot: ChatHistorySnapshot;+ cursor: string;+ messages: Record<string, ChatHistoryMessage>;+ /** Exact server page membership. Absence means not loaded, including after reset. */+ pages: Record<string, string[]>;+ /** Aggregates absent from change bodies (reactions/reply counts) need a page refresh. */+ stalePages?: string[];+ metadataDirty: boolean;+}+export interface ChatHistoryStore {+ read: (room: string) => Promise<ChatHistoryState | undefined>;+ /** State, message revisions/tombstones, page coverage and cursor commit together. */+ write: (room: string, state: ChatHistoryState | null) => Promise<void>;+}+export interface ChatHistoryChange {+ type: string; entityId?: string; data?: { message?: ChatHistoryMessage; threadRootId?: string | null };+}+export interface ChatHistoryBatch { cursor: string; changes: ChatHistoryChange[]; hasMore?: boolean }+type Api = <T>(route: string) => Promise<T>;+const isCursor = (value: unknown): value is string => typeof value === 'string' && /^\d+$/.test(value);+const errorCode = (error: unknown) => error && typeof error === 'object' && 'code' in error && typeof error.code === 'string'+ ? error.code : error instanceof Error ? error.message : '';++export function createChatHistory(input: { api: Api; store: ChatHistoryStore; current: () => boolean; newGeneration: () => string }) {+ const chains = new Map<string, Promise<unknown>>();+ const states = new Map<string, ChatHistoryState>();+ const checked = new Map<string, number>();+ const metadataConnection = new Map<string, number>();+ const dirty = new Set<string>();+ // A refresh consumes only the invalidation it successfully committed. New+ // notices during I/O and notices surviving CAS retries must remain pending.+ const metadataDirty = new Map<string, number>();+ let nextMetadataInvalidation = 0;+ let connection = 0;+ function assertCurrent() { if (!input.current()) throw new Error('OWNER_CHANGED'); }+ function serial<T>(room: string, run: () => Promise<T>): Promise<T> {+ const pending = (chains.get(room) ?? Promise.resolve()).catch(() => undefined).then(async () => {+ assertCurrent();+ for (let attempt = 0; ; attempt++) {+ try { const result = await run(); assertCurrent(); return result; }+ catch (error) {+ states.delete(room); checked.delete(room); metadataConnection.delete(room);+ if (errorCode(error) === 'CHAT_CACHE_CONFLICT' && attempt < 2) continue;+ if (['FORBIDDEN', 'NOT_MEMBER', 'NOT_A_MEMBER', 'CONVERSATION_NOT_FOUND', 'ACTOR_NOT_FOUND', 'ACCOUNT_UNAVAILABLE'].includes(errorCode(error))) {+ assertCurrent();+ try { await input.store.write(room, null); }+ catch (cleanupError) {+ // Another mount may have committed a newer projection. Leave it alone,+ // but preserve this caller's revocation error so its UI clears stale data.+ if (errorCode(cleanupError) !== 'CHAT_CACHE_CONFLICT') throw cleanupError;+ }+ }+ throw error;+ }+ }+ });+ chains.set(room, pending);+ void pending.finally(() => { if (chains.get(room) === pending) chains.delete(room); }).catch(() => undefined);+ return pending;+ }+ async function save(room: string, state: ChatHistoryState) {+ assertCurrent();+ state.stalePages = state.stalePages?.filter(key => state.pages[key]);+ // Keep only covered pages and the snapshot, never every change in the room's history.+ const retained = new Set([...state.snapshot.messages.map(m => m.id), ...Object.values(state.pages).flat()]);+ for (const id of Object.keys(state.messages)) if (!retained.has(id)) delete state.messages[id];+ await input.store.write(room, state);+ assertCurrent(); states.set(room, state);+ }+ async function bootstrap(room: string) {+ dirty.delete(room);+ const invalidation = metadataDirty.get(room);+ const epoch = connection;+ const snapshot = await input.api<ChatHistorySnapshot>(`/conversations/${room}/snapshot`);+ if (!isCursor(snapshot.cursor) || snapshot.room.id !== room || !Array.isArray(snapshot.messages)) throw new Error('CHAT_RESPONSE_INVALID');+ const state: ChatHistoryState = { generation: input.newGeneration(), snapshot, cursor: snapshot.cursor, messages: {}, pages: {}, metadataDirty: false };+ for (const message of snapshot.messages) state.messages[message.id] = message;+ await save(room, state);+ if (metadataDirty.get(room) === invalidation) metadataDirty.delete(room);+ if (epoch === connection) { checked.set(room, Date.now()); metadataConnection.set(room, epoch); }+ return state;+ }+ function merge(state: ChatHistoryState, message: ChatHistoryMessage) {+ const previous = state.messages[message.id];+ if (!previous || (message.revision ?? 0) >= (previous.revision ?? 0))+ state.messages[message.id] = { ...previous, ...message };+ }+ /** Returns false when the membership/history boundary requires a new bootstrap. */+ function apply(state: ChatHistoryState, batch: ChatHistoryBatch): boolean {+ if (!isCursor(batch.cursor) || !Array.isArray(batch.changes)) throw new Error('CHAT_RESPONSE_INVALID');+ if (BigInt(batch.cursor) <= BigInt(state.cursor)) return true;+ if (batch.changes.some(c => c.type === 'membership.changed')) return false;+ for (const change of batch.changes) {+ const message = change.data?.message;+ if (/^(message\.|reaction\.|pin\.)/.test(change.type)) {+ if (!message) return false;+ if (change.type === 'reaction.changed') {+ for (const [key, ids] of Object.entries(state.pages)) if (ids.includes(message.id)) stale(state, key);+ }+ if (message) {+ merge(state, message);+ if (change.type === 'message.created' && !state.snapshot.messages.some(m => m.id === message.id)) {+ state.snapshot.messages.push(message);+ state.snapshot.messages.sort((a, b) => BigInt(a.seq) > BigInt(b.seq) ? -1 : BigInt(a.seq) < BigInt(b.seq) ? 1 : 0);+ state.snapshot.messages = state.snapshot.messages.slice(0, 100);+ }+ // A new reply also changes its root's reply count. Refresh only pages containing that root.+ if (message.threadRootId && ['message.created', 'message.deleted'].includes(change.type))+ for (const [key, ids] of Object.entries(state.pages)) if (ids.includes(message.threadRootId)) stale(state, key);+ }+ if (change.type === 'message.created') {+ for (const key of Object.keys(state.pages)) {+ const query = new URLSearchParams(key);+ if (query.has('before')) continue;+ const ids = state.pages[key]!;+ // Preserve the old window as bounded coverage: new arrivals shift pagination+ // boundaries, but must not make every older page download again.+ const first = ids[0] && state.messages[ids[0]];+ if (first) {+ query.set('before', String(BigInt(first.seq) + 1n)); state.pages[query.toString()] = ids;+ if (state.stalePages?.includes(key)) stale(state, query.toString());+ }+ delete state.pages[key];+ }+ }+ } else if (!['execution.changed', 'plan.changed'].includes(change.type)) state.metadataDirty = true;+ }+ state.snapshot.messages = state.snapshot.messages.map(m => state.messages[m.id] ?? m);+ state.cursor = batch.cursor;+ return true;+ }+ function stale(state: ChatHistoryState, key: string) {+ state.stalePages ??= [];+ if (!state.stalePages.includes(key)) state.stalePages.push(key);+ }+ async function fetchPage<M extends ChatHistoryMessage>(room: string, state: ChatHistoryState, key: string) {+ const messages = await input.api<M[]>(`/conversations/${room}/messages?${key}`);+ if (!Array.isArray(messages)) throw new Error('CHAT_RESPONSE_INVALID');+ for (const message of messages) merge(state, message);+ const ids = messages.map(m => m.id); state.pages[key] = ids;+ state.stalePages = state.stalePages?.filter(value => value !== key);+ const excess = Object.keys(state.pages).length - 500;+ if (excess > 0) {+ // Retain the newest covered ranges, not insertion order: renaming a shifted+ // head must not evict the next page and cascade misses through a transcript.+ // Keep this response covered until page() has returned its message objects.+ const oldest = Object.entries(state.pages).filter(([pageKey]) => pageKey !== key)+ .map(([pageKey, pageIds]) => ({ key: pageKey,+ seq: BigInt(state.messages[pageIds[0] ?? '']?.seq ?? new URLSearchParams(pageKey).get('before') ?? '0') }))+ .sort((a, b) => a.seq < b.seq ? -1 : a.seq > b.seq ? 1 : 0);+ for (const page of oldest.slice(0, excess)) delete state.pages[page.key];+ }+ await save(room, state);+ return ids;+ }+ async function ensure(room: string, force = false): Promise<ChatHistoryState> {+ let state = states.get(room) ?? await input.store.read(room);+ assertCurrent();+ if (!state) return bootstrap(room);+ states.set(room, state);+ // Personal reads belong to actor scope, so room deltas cannot repair missed+ // read notifications on reconnect (including rooms first restored from disk).+ if (connection > 0 && metadataConnection.get(room) !== connection) state.metadataDirty = true;+ const invalidation = metadataDirty.get(room);+ if (invalidation !== undefined) state.metadataDirty = true;+ if (!force && !state.metadataDirty && !dirty.has(room) && Date.now() - (checked.get(room) ?? 0) < 30_000) return state;+ const epoch = connection;+ dirty.delete(room);+ try {+ // Bound one catch-up. A compacted or exceptionally long backlog is cheaper to rebootstrap.+ for (let page = 0; page < 20; page++) {+ const batch = await input.api<ChatHistoryBatch>(`/changes?scope=conversation:${room}&after=${state.cursor}&limit=100`);+ if (batch.hasMore && batch.cursor === state.cursor) throw new Error('CHAT_SYNC_STALLED');+ if (!apply(state, batch)) return bootstrap(room);+ await save(room, state);+ if (!batch.hasMore) {+ if (state.metadataDirty) {+ const snapshot = await input.api<ChatHistorySnapshot>(`/conversations/${room}/snapshot`);+ // Do not jump past changes committed between the delta and this metadata read.+ for (const message of snapshot.messages) merge(state, message);+ state.snapshot = { ...snapshot, cursor: state.cursor, messages: snapshot.messages.map(m => state!.messages[m.id]!) };+ state.metadataDirty = false;+ await save(room, state);+ if (metadataDirty.get(room) === invalidation) metadataDirty.delete(room);+ }+ if (epoch === connection) { checked.set(room, Date.now()); metadataConnection.set(room, epoch); }+ return state;+ }+ }+ return bootstrap(room);+ } catch (error) {+ if (['RESET_REQUIRED', 'CURSOR_AHEAD'].includes(errorCode(error))) return bootstrap(room);+ throw error;+ }+ }+ function coveredPage(state: ChatHistoryState, query: URLSearchParams): string[] | undefined {+ const before = query.get('before');+ if (!before) return undefined;+ const limit = Number(query.get('limit') ?? 100);+ let position = BigInt(before);+ const found = new Map<string, ChatHistoryMessage>();+ const candidates = Object.entries(state.pages).filter(([key]) => !state.stalePages?.includes(key)+ && ['threadRootId', 'all', 'after'].every(field => new URLSearchParams(key).get(field) === query.get(field)));+ while (candidates.length) {+ const covering = candidates.find(([key, ids]) => {+ const upper = new URLSearchParams(key).get('before');+ if (upper && BigInt(upper) < position) return false;+ const last = ids.at(-1);+ return !last || BigInt(state.messages[last]!.seq) < position;+ });+ if (!covering) return undefined;+ const [key, ids] = covering;+ for (const id of ids) {+ const message = state.messages[id]!;+ if (BigInt(message.seq) < position && BigInt(message.seq) < BigInt(before)) found.set(id, message);+ }+ const sorted = [...found.values()].sort((a, b) => BigInt(a.seq) > BigInt(b.seq) ? -1 : BigInt(a.seq) < BigInt(b.seq) ? 1 : 0);+ if (sorted.length >= limit || ids.length < Number(new URLSearchParams(key).get('limit') ?? 100)) return sorted.slice(0, limit).map(m => m.id);+ position = BigInt(state.messages[ids.at(-1)!]!.seq);+ candidates.splice(candidates.indexOf(covering), 1);+ }+ return undefined;+ }+ return {+ snapshot: <S extends ChatHistorySnapshot>(room: string): Promise<S & { cacheGeneration: string }> => serial(room, async () => {+ const state = await ensure(room);+ return { ...state.snapshot, cursor: state.cursor, cacheGeneration: state.generation } as S & { cacheGeneration: string };+ }),+ page: <M extends ChatHistoryMessage>(room: string, query: URLSearchParams): Promise<M[]> => serial(room, async () => {+ const state = await ensure(room);+ const key = query.toString();+ const ids = (state.stalePages?.includes(key) ? undefined : state.pages[key])+ ?? coveredPage(state, query) ?? await fetchPage<M>(room, state, key);+ return ids.map(id => state.messages[id] as M);+ }),+ /** A reconnect must verify membership and catch up before returning persisted content. */+ reconnect() { connection++; checked.clear(); },+ invalidate(room: string, metadata = false) {+ dirty.add(room); checked.delete(room);+ if (metadata) metadataDirty.set(room, ++nextMetadataInvalidation);+ },+ cursor(room: string) { return states.get(room)?.cursor; },+ generation(room: string) { return states.get(room)?.generation; },+ projection: <M extends ChatHistoryMessage>(room: string, ids: string[]) => serial(room, async () => {+ const state = await ensure(room);+ const shown = new Set(ids);+ for (const key of state.stalePages ?? [])+ if (state.pages[key]?.some(id => shown.has(id))) await fetchPage<M>(room, state, key);+ return { generation: state.generation, messages: ids.flatMap(id => state.messages[id] ? [state.messages[id] as M] : []) };+ }),+ receive: (room: string, batch: ChatHistoryBatch, subscribedAfter: string | undefined): Promise<string | undefined> => serial(room, async () => {+ const state = states.get(room) ?? await input.store.read(room);+ if (!state) return undefined;+ // Another foreground snapshot may have started this subscription beyond our durable cursor.+ // Catch up that gap instead of acknowledging unseen edits/deletions.+ if (!subscribedAfter || BigInt(subscribedAfter) > BigInt(state.cursor)) return (await ensure(room, true)).cursor;+ if (!apply(state, batch)) {+ await input.store.write(room, null); states.delete(room); checked.delete(room); metadataConnection.delete(room);+ return undefined;+ }+ await save(room, state);+ return state.cursor;+ }),+ clear: (room: string) => serial(room, async () => {+ await input.store.write(room, null); states.delete(room); checked.delete(room); metadataConnection.delete(room);+ }),+ };+}+export type ChatHistory = ReturnType<typeof createChatHistory>;