Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(desktop): 会话列表预览缓存并封顶消息计数 (#3462)
Dash51bed271946b
diff --git a/apps/desktop/drizzle/0097_fresh_stryfe.sql b/apps/desktop/drizzle/0097_fresh_stryfe.sqlnew file mode 100644index 0000000000..027b7d63fd--- /dev/null+++ b/apps/desktop/drizzle/0097_fresh_stryfe.sql@@ -0,0 +1 @@+SELECT 1;\ No newline at end of filediff --git a/apps/desktop/drizzle/meta/0097_snapshot.json b/apps/desktop/drizzle/meta/0097_snapshot.jsonnew file mode 100644index 0000000000..b6c8a5d1ff--- /dev/null+++ b/apps/desktop/drizzle/meta/0097_snapshot.json@@ -0,0 +1,4438 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "1a52644f-09ab-4a17-ad9d-878590e73f6d",+ "prevId": "0301f553-95d2-4bd4-a120-d131780848c7",+ "tables": {+ "account_usage_snapshots": {+ "name": "account_usage_snapshots",+ "columns": {+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "snapshot": {+ "name": "snapshot",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "agent_input_queue_snapshots": {+ "name": "agent_input_queue_snapshots",+ "columns": {+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "payload": {+ "name": "payload",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "agent_input_queue_snapshots_session_id_sessions_id_fk": {+ "name": "agent_input_queue_snapshots_session_id_sessions_id_fk",+ "tableFrom": "agent_input_queue_snapshots",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "custom_mcp_servers": {+ "name": "custom_mcp_servers",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "transport": {+ "name": "transport",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "headers": {+ "name": "headers",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "sort_order": {+ "name": "sort_order",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_custom_mcp_servers_sort_order": {+ "name": "idx_custom_mcp_servers_sort_order",+ "columns": [+ "sort_order"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "custom_providers": {+ "name": "custom_providers",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "runtimes": {+ "name": "runtimes",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "auth": {+ "name": "auth",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "sort_order": {+ "name": "sort_order",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_custom_providers_sort_order": {+ "name": "idx_custom_providers_sort_order",+ "columns": [+ "sort_order"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "daily_model_usage": {+ "name": "daily_model_usage",+ "columns": {+ "day": {+ "name": "day",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cost_usd": {+ "name": "cost_usd",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_amount": {+ "name": "cost_amount",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_currency": {+ "name": "cost_currency",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'USD'"+ },+ "cost_is_approximate": {+ "name": "cost_is_approximate",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "input_tokens": {+ "name": "input_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "output_tokens": {+ "name": "output_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cache_read_tokens": {+ "name": "cache_read_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cache_create_tokens": {+ "name": "cache_create_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "daily_model_usage_day_agent_kind_model_cost_currency_pk": {+ "columns": [+ "day",+ "agent_kind",+ "model",+ "cost_currency"+ ],+ "name": "daily_model_usage_day_agent_kind_model_cost_currency_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "daily_spend": {+ "name": "daily_spend",+ "columns": {+ "day": {+ "name": "day",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cost_usd": {+ "name": "cost_usd",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_amount": {+ "name": "cost_amount",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_currency": {+ "name": "cost_currency",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'USD'"+ },+ "cost_is_approximate": {+ "name": "cost_is_approximate",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "daily_spend_day_cost_currency_pk": {+ "columns": [+ "day",+ "cost_currency"+ ],+ "name": "daily_spend_day_cost_currency_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "device_link_ownership": {+ "name": "device_link_ownership",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "owner_id": {+ "name": "owner_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "owner_pid": {+ "name": "owner_pid",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "owner_label": {+ "name": "owner_label",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "heartbeat_at": {+ "name": "heartbeat_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "embedding_jobs": {+ "name": "embedding_jobs",+ "columns": {+ "rowid": {+ "name": "rowid",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "source_id": {+ "name": "source_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "chunk_index": {+ "name": "chunk_index",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "model_id": {+ "name": "model_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "vec_table": {+ "name": "vec_table",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scheduled_at": {+ "name": "scheduled_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "locked_at": {+ "name": "locked_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_embedding_jobs_natural": {+ "name": "uniq_embedding_jobs_natural",+ "columns": [+ "source",+ "source_id",+ "chunk_index",+ "model_id"+ ],+ "isUnique": true+ },+ "idx_embedding_jobs_status_scheduled": {+ "name": "idx_embedding_jobs_status_scheduled",+ "columns": [+ "status",+ "scheduled_at"+ ],+ "isUnique": false+ },+ "idx_embedding_jobs_source_id": {+ "name": "idx_embedding_jobs_source_id",+ "columns": [+ "source",+ "source_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "embedding_meta": {+ "name": "embedding_meta",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "ghost_cards": {+ "name": "ghost_cards",+ "columns": {+ "call_id": {+ "name": "call_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "ghost_id": {+ "name": "ghost_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "html": {+ "name": "html",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "height": {+ "name": "height",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "v": {+ "name": "v",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 1+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "ghost_cards_updated_at_idx": {+ "name": "ghost_cards_updated_at_idx",+ "columns": [+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "hook_group_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": {}+ },+ "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+ }+ },+ "foreignKeys": {+ "messages_session_id_sessions_id_fk": {+ "name": "messages_session_id_sessions_id_fk",+ "tableFrom": "messages",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "messages_fts_rows": {+ "name": "messages_fts_rows",+ "columns": {+ "fts_rowid": {+ "name": "fts_rowid",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "message_id": {+ "name": "message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "messages_fts_rows_message_id_idx": {+ "name": "messages_fts_rows_message_id_idx",+ "columns": [+ "message_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "migration_history": {+ "name": "migration_history",+ "columns": {+ "seq": {+ "name": "seq",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "file_name": {+ "name": "file_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "content_hash": {+ "name": "content_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "applied_at": {+ "name": "applied_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "migration_meta": {+ "name": "migration_meta",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "orca_teams": {+ "name": "orca_teams",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "lead_session_id": {+ "name": "lead_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "completed_at": {+ "name": "completed_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_active_team_per_lead": {+ "name": "uniq_active_team_per_lead",+ "columns": [+ "lead_session_id"+ ],+ "isUnique": true,+ "where": "\"orca_teams\".\"status\" = 'active'"+ },+ "idx_orca_teams_status": {+ "name": "idx_orca_teams_status",+ "columns": [+ "status"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "orca_teams_lead_session_id_sessions_id_fk": {+ "name": "orca_teams_lead_session_id_sessions_id_fk",+ "tableFrom": "orca_teams",+ "tableTo": "sessions",+ "columnsFrom": [+ "lead_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "orca_worker_creation_reservations": {+ "name": "orca_worker_creation_reservations",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "label": {+ "name": "label",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_orca_worker_creation_reservations_team_label": {+ "name": "uniq_orca_worker_creation_reservations_team_label",+ "columns": [+ "team_id",+ "lower(\"label\")"+ ],+ "isUnique": true+ },+ "idx_orca_worker_creation_reservations_expires_at": {+ "name": "idx_orca_worker_creation_reservations_expires_at",+ "columns": [+ "expires_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "orca_worker_creation_reservations_team_id_orca_teams_id_fk": {+ "name": "orca_worker_creation_reservations_team_id_orca_teams_id_fk",+ "tableFrom": "orca_worker_creation_reservations",+ "tableTo": "orca_teams",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "orca_workers": {+ "name": "orca_workers",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'idle'"+ },+ "label": {+ "name": "label",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "worktree_branch": {+ "name": "worktree_branch",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'developer'"+ },+ "focused": {+ "name": "focused",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "idle_since": {+ "name": "idle_since",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_orca_workers_session_id": {+ "name": "uniq_orca_workers_session_id",+ "columns": [+ "session_id"+ ],+ "isUnique": true+ },+ "uniq_orca_workers_team_label": {+ "name": "uniq_orca_workers_team_label",+ "columns": [+ "team_id",+ "lower(\"label\")"+ ],+ "isUnique": true+ },+ "uniq_orca_workers_focused_per_team": {+ "name": "uniq_orca_workers_focused_per_team",+ "columns": [+ "team_id"+ ],+ "isUnique": true,+ "where": "\"orca_workers\".\"focused\" = true"+ },+ "idx_orca_workers_team_id": {+ "name": "idx_orca_workers_team_id",+ "columns": [+ "team_id"+ ],+ "isUnique": false+ },+ "idx_orca_workers_status": {+ "name": "idx_orca_workers_status",+ "columns": [+ "status"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "orca_workers_team_id_orca_teams_id_fk": {+ "name": "orca_workers_team_id_orca_teams_id_fk",+ "tableFrom": "orca_workers",+ "tableTo": "orca_teams",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "orca_workers_session_id_sessions_id_fk": {+ "name": "orca_workers_session_id_sessions_id_fk",+ "tableFrom": "orca_workers",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_aliases": {+ "name": "project_aliases",+ "columns": {+ "project_key": {+ "name": "project_key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "alias": {+ "name": "alias",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_project_aliases_updated_at": {+ "name": "idx_project_aliases_updated_at",+ "columns": [+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_automation_consents": {+ "name": "project_automation_consents",+ "columns": {+ "working_dir": {+ "name": "working_dir",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "consented_at": {+ "name": "consented_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "config_hash": {+ "name": "config_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "recent_workdirs": {+ "name": "recent_workdirs",+ "columns": {+ "path": {+ "name": "path",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_recent_workdirs_last_used_at": {+ "name": "idx_recent_workdirs_last_used_at",+ "columns": [+ "last_used_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "right_sidebar_tabs": {+ "name": "right_sidebar_tabs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "is_active": {+ "name": "is_active",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "right_sidebar_tabs_session_idx": {+ "name": "right_sidebar_tabs_session_idx",+ "columns": [+ "session_id",+ "position"+ ],+ "isUnique": false+ },+ "right_sidebar_tabs_subagents_singleton_idx": {+ "name": "right_sidebar_tabs_subagents_singleton_idx",+ "columns": [+ "session_id"+ ],+ "isUnique": true,+ "where": "\"right_sidebar_tabs\".\"kind\" = 'subagents'"+ }+ },+ "foreignKeys": {+ "right_sidebar_tabs_session_id_sessions_id_fk": {+ "name": "right_sidebar_tabs_session_id_sessions_id_fk",+ "tableFrom": "right_sidebar_tabs",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "schedule_runs": {+ "name": "schedule_runs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "schedule_id": {+ "name": "schedule_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "fired_at": {+ "name": "fired_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "finished_at": {+ "name": "finished_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "error_msg": {+ "name": "error_msg",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cost_usd": {+ "name": "cost_usd",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "estimated_value_usd": {+ "name": "estimated_value_usd",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_amount": {+ "name": "cost_amount",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "estimated_value_amount": {+ "name": "estimated_value_amount",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_currency": {+ "name": "cost_currency",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cost_is_approximate": {+ "name": "cost_is_approximate",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "cost_attribution": {+ "name": "cost_attribution",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'legacy'"+ },+ "result_text": {+ "name": "result_text",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "pre_run_hook_result": {+ "name": "pre_run_hook_result",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "read_at": {+ "name": "read_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "heartbeat_at": {+ "name": "heartbeat_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_schedule_runs_schedule": {+ "name": "idx_schedule_runs_schedule",+ "columns": [+ "schedule_id",+ "fired_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "schedule_runs_schedule_id_schedules_id_fk": {+ "name": "schedule_runs_schedule_id_schedules_id_fk",+ "tableFrom": "schedule_runs",+ "tableTo": "schedules",+ "columnsFrom": [+ "schedule_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "schedule_runs_session_id_sessions_id_fk": {+ "name": "schedule_runs_session_id_sessions_id_fk",+ "tableFrom": "schedule_runs",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "schedules": {+ "name": "schedules",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "prompt": {+ "name": "prompt",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "job_type": {+ "name": "job_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'prompt'"+ },+ "job_config": {+ "name": "job_config",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "execution_mode": {+ "name": "execution_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'agent'"+ },+ "script_config": {+ "name": "script_config",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'user'"+ },+ "project_config_id": {+ "name": "project_config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "legacy_session_fallback": {+ "name": "legacy_session_fallback",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'cron'"+ },+ "cron_expr": {+ "name": "cron_expr",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "timezone": {+ "name": "timezone",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "recurring": {+ "name": "recurring",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "manual": {+ "name": "manual",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "interval_ms": {+ "name": "interval_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "effort": {+ "name": "effort",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "fast_mode": {+ "name": "fast_mode",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "working_dir": {+ "name": "working_dir",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_kind": {+ "name": "workspace_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'project'"+ },+ "use_worktree": {+ "name": "use_worktree",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "target_session_id": {+ "name": "target_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "persistent_session": {+ "name": "persistent_session",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "silent_when_idle": {+ "name": "silent_when_idle",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "pre_run_hook_command": {+ "name": "pre_run_hook_command",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "pre_run_hook_timeout_ms": {+ "name": "pre_run_hook_timeout_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "skip_log_session_id": {+ "name": "skip_log_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "notify_desktop": {+ "name": "notify_desktop",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "notify_feishu": {+ "name": "notify_feishu",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "notify_wecom_group": {+ "name": "notify_wecom_group",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_fired_at": {+ "name": "last_fired_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_finished_at": {+ "name": "last_finished_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "next_fire_at": {+ "name": "next_fire_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expire_at": {+ "name": "expire_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_schedules_active_next": {+ "name": "idx_schedules_active_next",+ "columns": [+ "status",+ "next_fire_at"+ ],+ "isUnique": false+ },+ "idx_schedules_target_session": {+ "name": "idx_schedules_target_session",+ "columns": [+ "target_session_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "schedules_target_session_id_sessions_id_fk": {+ "name": "schedules_target_session_id_sessions_id_fk",+ "tableFrom": "schedules",+ "tableTo": "sessions",+ "columnsFrom": [+ "target_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "schedules_skip_log_session_id_sessions_id_fk": {+ "name": "schedules_skip_log_session_id_sessions_id_fk",+ "tableFrom": "schedules",+ "tableTo": "sessions",+ "columnsFrom": [+ "skip_log_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "session_goals": {+ "name": "session_goals",+ "columns": {+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "objective": {+ "name": "objective",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "budget_tokens": {+ "name": "budget_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "max_turns": {+ "name": "max_turns",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "no_progress_limit": {+ "name": "no_progress_limit",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "turns_used": {+ "name": "turns_used",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "tokens_used": {+ "name": "tokens_used",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "no_progress_streak": {+ "name": "no_progress_streak",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "usage_reset_at": {+ "name": "usage_reset_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_reason": {+ "name": "last_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "started_at": {+ "name": "started_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_session_goals_status": {+ "name": "idx_session_goals_status",+ "columns": [+ "status"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "session_goals_session_id_sessions_id_fk": {+ "name": "session_goals_session_id_sessions_id_fk",+ "tableFrom": "session_goals",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "session_pr_refs": {+ "name": "session_pr_refs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "owner": {+ "name": "owner",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "repo": {+ "name": "repo",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "pr_number": {+ "name": "pr_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "first_seen_at": {+ "name": "first_seen_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_seen_at": {+ "name": "last_seen_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_session_pr_refs": {+ "name": "uniq_session_pr_refs",+ "columns": [+ "session_id",+ "owner",+ "repo",+ "pr_number"+ ],+ "isUnique": true+ },+ "idx_session_pr_refs_session_last_seen": {+ "name": "idx_session_pr_refs_session_last_seen",+ "columns": [+ "session_id",+ "last_seen_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "session_pr_refs_session_id_sessions_id_fk": {+ "name": "session_pr_refs_session_id_sessions_id_fk",+ "tableFrom": "session_pr_refs",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "sessions": {+ "name": "sessions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'New Maker'"+ },+ "working_dir": {+ "name": "working_dir",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_kind": {+ "name": "workspace_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'project'"+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'claude-sonnet-4-6'"+ },+ "effort": {+ "name": "effort",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'high'"+ },+ "permission_mode": {+ "name": "permission_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'ask'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "sdk_session_id": {+ "name": "sdk_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "total_token_usage": {+ "name": "total_token_usage",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "total_cost_usd": {+ "name": "total_cost_usd",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "total_cost_amount": {+ "name": "total_cost_amount",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "total_cost_currency": {+ "name": "total_cost_currency",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "total_cost_is_approximate": {+ "name": "total_cost_is_approximate",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "context_tokens": {+ "name": "context_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "context_window": {+ "name": "context_window",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "fast_mode": {+ "name": "fast_mode",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "plan_mode_enabled": {+ "name": "plan_mode_enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "cleared_at": {+ "name": "cleared_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "pinned_at": {+ "name": "pinned_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_send_at": {+ "name": "user_send_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'cc'"+ },+ "orca_role": {+ "name": "orca_role",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "parent_session_id": {+ "name": "parent_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "forked_at_message_id": {+ "name": "forked_at_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "worktree_path": {+ "name": "worktree_path",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'desktop'"+ },+ "feishu_open_id": {+ "name": "feishu_open_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "feishu_bot_app_id": {+ "name": "feishu_bot_app_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "im_bot_context_id": {+ "name": "im_bot_context_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "im_user_id": {+ "name": "im_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "used_project_context": {+ "name": "used_project_context",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "codex_history_has_product_prompt": {+ "name": "codex_history_has_product_prompt",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "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": "'[]'"+ },+ "remote_host_id": {+ "name": "remote_host_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "active_turn_started_at": {+ "name": "active_turn_started_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "active_turn_pid": {+ "name": "active_turn_pid",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_turn_ended_at": {+ "name": "last_turn_ended_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "list_preview": {+ "name": "list_preview",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "list_preview_role": {+ "name": "list_preview_role",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "list_message_count": {+ "name": "list_message_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_sessions_updated_at": {+ "name": "idx_sessions_updated_at",+ "columns": [+ "updated_at"+ ],+ "isUnique": false+ },+ "idx_sessions_user_send_at": {+ "name": "idx_sessions_user_send_at",+ "columns": [+ "user_send_at"+ ],+ "isUnique": false+ },+ "idx_sessions_sdk_session_id": {+ "name": "idx_sessions_sdk_session_id",+ "columns": [+ "sdk_session_id"+ ],+ "isUnique": false+ },+ "idx_sessions_workdir_created": {+ "name": "idx_sessions_workdir_created",+ "columns": [+ "working_dir",+ "created_at",+ "id"+ ],+ "isUnique": false+ },+ "idx_sessions_created_at": {+ "name": "idx_sessions_created_at",+ "columns": [+ "created_at",+ "id"+ ],+ "isUnique": false+ },+ "idx_sessions_workspace_kind": {+ "name": "idx_sessions_workspace_kind",+ "columns": [+ "workspace_kind"+ ],+ "isUnique": false+ },+ "idx_sessions_parent_session_id": {+ "name": "idx_sessions_parent_session_id",+ "columns": [+ "parent_session_id"+ ],+ "isUnique": false+ },+ "idx_sessions_orca_role": {+ "name": "idx_sessions_orca_role",+ "columns": [+ "orca_role"+ ],+ "isUnique": false+ },+ "idx_sessions_worktree_path": {+ "name": "idx_sessions_worktree_path",+ "columns": [+ "worktree_path"+ ],+ "isUnique": false+ },+ "idx_sessions_feishu_lookup": {+ "name": "idx_sessions_feishu_lookup",+ "columns": [+ "source",+ "feishu_bot_app_id",+ "feishu_open_id"+ ],+ "isUnique": false+ },+ "idx_sessions_im_lookup": {+ "name": "idx_sessions_im_lookup",+ "columns": [+ "source",+ "im_bot_context_id",+ "im_user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "sessions_parent_session_id_sessions_id_fk": {+ "name": "sessions_parent_session_id_sessions_id_fk",+ "tableFrom": "sessions",+ "tableTo": "sessions",+ "columnsFrom": [+ "parent_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "skill_usage_exposures": {+ "name": "skill_usage_exposures",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "analyzer_version": {+ "name": "analyzer_version",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'6'"+ },+ "raw_file_path": {+ "name": "raw_file_path",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "raw_line_no": {+ "name": "raw_line_no",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "sdk_session_id": {+ "name": "sdk_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "skill_name": {+ "name": "skill_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "skill_path": {+ "name": "skill_path",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "skill_document_hash": {+ "name": "skill_document_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "exposure_content_hash": {+ "name": "exposure_content_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "document_hash_source": {+ "name": "document_hash_source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tool_use_id": {+ "name": "tool_use_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "seen_at": {+ "name": "seen_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tool_call_count": {+ "name": "tool_call_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "repeated_tool_call_count": {+ "name": "repeated_tool_call_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "tool_error_count": {+ "name": "tool_error_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "command_call_count": {+ "name": "command_call_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "command_failure_count": {+ "name": "command_failure_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ }+ },+ "indexes": {+ "idx_skill_usage_exposures_skill_document_version": {+ "name": "idx_skill_usage_exposures_skill_document_version",+ "columns": [+ "analyzer_version",+ "skill_name",+ "skill_document_hash"+ ],+ "isUnique": false+ },+ "idx_skill_usage_exposures_session": {+ "name": "idx_skill_usage_exposures_session",+ "columns": [+ "session_id"+ ],+ "isUnique": false+ },+ "idx_skill_usage_exposures_raw_file": {+ "name": "idx_skill_usage_exposures_raw_file",+ "columns": [+ "raw_file_path"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "skill_usage_exposures_raw_file_path_skill_usage_sources_raw_file_path_fk": {+ "name": "skill_usage_exposures_raw_file_path_skill_usage_sources_raw_file_path_fk",+ "tableFrom": "skill_usage_exposures",+ "tableTo": "skill_usage_sources",+ "columnsFrom": [+ "raw_file_path"+ ],+ "columnsTo": [+ "raw_file_path"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "skill_usage_sources": {+ "name": "skill_usage_sources",+ "columns": {+ "raw_file_path": {+ "name": "raw_file_path",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "analyzer_version": {+ "name": "analyzer_version",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'6'"+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "sdk_session_id": {+ "name": "sdk_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mtime_ms": {+ "name": "mtime_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "size_bytes": {+ "name": "size_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "last_scanned_at": {+ "name": "last_scanned_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'ok'"+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_skill_usage_sources_session": {+ "name": "idx_skill_usage_sources_session",+ "columns": [+ "session_id"+ ],+ "isUnique": false+ },+ "idx_skill_usage_sources_sdk_session": {+ "name": "idx_skill_usage_sources_sdk_session",+ "columns": [+ "sdk_session_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "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": {}+ },+ "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 5c636856b9..4a07f73df8 100644--- a/apps/desktop/drizzle/meta/_journal.json+++ b/apps/desktop/drizzle/meta/_journal.json@@ -680,6 +680,13 @@"when": 1787721235534,"tag": "0096_stabilize_messages_fts_rows","breakpoints": true+ },+ {+ "idx": 97,+ "version": "6",+ "when": 1787739425748,+ "tag": "0097_fresh_stryfe",+ "breakpoints": true}]}\ No newline at end of filediff --git a/apps/desktop/drizzle/scripts/0097_fresh_stryfe.ts b/apps/desktop/drizzle/scripts/0097_fresh_stryfe.tsnew file mode 100644index 0000000000..294e814879--- /dev/null+++ b/apps/desktop/drizzle/scripts/0097_fresh_stryfe.ts@@ -0,0 +1,23 @@+import type Database from 'better-sqlite3';++function tableColumnNames(db: Database.Database, tableName: string): string[] {+ return db+ .prepare(`PRAGMA table_info('${tableName}')`)+ .all()+ .map((row) => String((row as { name: unknown }).name));+}++function run(db: Database.Database): void {+ const columns = new Set(tableColumnNames(db, 'sessions'));+ if (!columns.has('list_preview')) {+ db.exec('ALTER TABLE sessions ADD COLUMN list_preview text');+ }+ if (!columns.has('list_preview_role')) {+ db.exec('ALTER TABLE sessions ADD COLUMN list_preview_role text');+ }+ if (!columns.has('list_message_count')) {+ db.exec('ALTER TABLE sessions ADD COLUMN list_message_count integer');+ }+}++module.exports = { run };diff --git a/apps/desktop/src/main/__tests__/sessionTaskSummary.test.ts b/apps/desktop/src/main/__tests__/sessionTaskSummary.test.tsindex 9f91603728..6c1fd0f46e 100644--- a/apps/desktop/src/main/__tests__/sessionTaskSummary.test.ts+++ b/apps/desktop/src/main/__tests__/sessionTaskSummary.test.ts@@ -240,19 +240,22 @@ describe('sessionListPreviewPatch', () => {describe('turn-done list preview refresh', () => {it('回合结束后先刷新列表预览,再按需生成置顶摘要', () => {- const registerSource = readFileSync(resolve(__dirname, '..', 'maker-ipc', 'register.ts'), 'utf8');+ const registerSource = readFileSync(+ resolve(__dirname, '..', 'maker-ipc', 'register.ts'),+ 'utf8',+ );const summarySource = readFileSync(resolve(__dirname, '..', 'sessionTaskSummary.ts'), 'utf8');expect(registerSource).toContain('await refreshSessionListPreview(session.id);');- expect(registerSource).toContain('await maybeGenerateSessionTaskSummary(session.id, { force: true });');+ expect(registerSource).toContain(+ 'await maybeGenerateSessionTaskSummary(session.id, { force: true });',+ );expect(registerSource.indexOf('await refreshSessionListPreview(session.id);')).toBeLessThan(registerSource.indexOf('await maybeGenerateSessionTaskSummary(session.id, { force: true });'),);expect(summarySource).toContain('export async function refreshSessionListPreview');expect(summarySource).toContain('const ownerScope = captureOwnerScope();');expect(summarySource).toContain('if (!isOwnerScopeCurrent(ownerScope)) return;');- expect(summarySource).toContain(- 'broadcastSessionListPreview(sessionId, preview, ownerScope);',- );+ expect(summarySource).toContain('broadcastSessionListPreview(sessionId, preview, ownerScope);');expect(summarySource).toContain("import { latestMessageText, latestVisiblePreview } from './localDb/latestMessageText.js';",);@@ -271,8 +274,9 @@ describe('turn-done list preview refresh', () => {const updateEnd = messagesSource.indexOf('function clampLimit', updateStart);const updateBlock = messagesSource.slice(updateStart, updateEnd);expect(updateBlock).toContain('const ownerScope = captureOwnerBroadcastScope();');+ expect(updateBlock).toContain("await dbClient.tx('message.updateContent'");expect(updateBlock.indexOf('const ownerScope = captureOwnerBroadcastScope();')).toBeLessThan(- updateBlock.indexOf('.update(messages)'),+ updateBlock.indexOf("await dbClient.tx('message.updateContent'"),);expect(updateBlock).toContain('await maybeBroadcastSessionListPreview(sessionId, row, ownerScope);',@@ -285,17 +289,17 @@ describe('turn-done list preview refresh', () => {expect(broadcastBlock).toContain('latest = await latestVisiblePreviewRow(sessionId);');expect(broadcastBlock).toContain('if (latest?.clientId !== row.clientId) return;');expect(broadcastBlock).toContain(- 'preview: extractMessagePreview(row.content, row.role)',+ 'const preview = extractMessagePreview(row.content, row.role);',);+ expect(broadcastBlock).not.toContain('await persistSessionListPreview');+ expect(broadcastBlock).toContain('patch: { preview }');expect(broadcastBlock).not.toContain('if (!preview) return;');expect(latestSource).toContain('export async function latestVisiblePreviewRow');expect(latestSource).toContain('or(isNull(sessions.clearedAt), gt(messages.createdAt, sessions.clearedAt))',);expect(latestSource).toContain('const joinedMessageRowid = sql<number>`"messages"."rowid"`;');- expect(latestSource).toContain(- '.orderBy(desc(messages.createdAt), desc(joinedMessageRowid))',- );+ expect(latestSource).toContain('.orderBy(desc(messages.createdAt), desc(joinedMessageRowid))');expect(latestSource).toContain("CASE WHEN json_valid(${messages.agentMeta}) THEN json_extract(${messages.agentMeta}, '$.autoResume') END IS NOT 1",);diff --git a/apps/desktop/src/main/__tests__/sessionsListIncludePinned.test.ts b/apps/desktop/src/main/__tests__/sessionsListIncludePinned.test.tsindex 90cec56d9e..b7c49463db 100644--- a/apps/desktop/src/main/__tests__/sessionsListIncludePinned.test.ts+++ b/apps/desktop/src/main/__tests__/sessionsListIncludePinned.test.ts@@ -140,7 +140,7 @@ function listRow(id: string, patch: Record<string, unknown> = {}) {return {session: sessionRow(id, patch),messageCount: 0,- latestMessageContent: null,+ latestMessageExtract: null,latestMessageRole: null,};}diff --git a/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts b/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.tsindex c385f57e2a..2eecc6e295 100644--- a/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts+++ b/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts@@ -81,7 +81,9 @@ vi.mock('../logger', () => ({}));// 被 sessions.ts 顶层 import 但与本测试无关的副作用模块,全部 stub 掉避免触碰 electron app 路径。vi.mock('../localDb/dialogueWorkspace', () => ({ ensureDialogueWorkspaceDir: vi.fn() }));-vi.mock('../git-context/prRefsStore', () => ({ recomputePrRefsForSession: vi.fn(() => Promise.resolve()) }));+vi.mock('../git-context/prRefsStore', () => ({+ recomputePrRefsForSession: vi.fn(() => Promise.resolve()),+}));vi.mock('../localDb/ipc/recentWorkdirs', () => ({ upsertRecentWorkdir: vi.fn() }));vi.mock('../device-link/broadcast-tap', () => ({captureDataOwnerBroadcastScope: vi.fn(() => null),@@ -98,7 +100,11 @@ vi.mock('../localDb/ipc/subagentRuns.js', () => ({}));import { notifyAgentIslandSessionPatch } from '../localDb/agentIslandSessionPatch.js';-import { clearSessionContextInDb, touchUserSendInDb, persistSessionFields } from '../localDb/ipc/sessions.js';+import {+ clearSessionContextInDb,+ touchUserSendInDb,+ persistSessionFields,+} from '../localDb/ipc/sessions.js';import {backgroundTurnPredatesSessionClear,noteSessionClearBoundary,@@ -149,7 +155,7 @@ describe('touchUserSendInDb 广播 sessions:patched(device-link 项目归属收const payload = tapArg?.[1] as { sessionId: string; patch: Record<string, unknown> };expect(payload.sessionId).toBe('sess-2');expect(typeof payload.patch.userSendAt).toBe('string'); // ISO- expect(typeof payload.patch.updatedAt).toBe('string'); // ISO+ expect(typeof payload.patch.updatedAt).toBe('string'); // ISO});it('atomic guard: UPDATE no-op 时(验证 SELECT 返回空)跳过广播,不向 renderer 发送过时值', async () => {@@ -196,11 +202,11 @@ describe('clearSessionContextInDb 广播 sessions:patched(device-link /clear 收const iso = new Date(atMs).toISOString();expect(h.webContentsSend).toHaveBeenCalledWith('local-db:sessions:patched', {sessionId: 'sess-clear',- patch: { sdkSessionId: null, clearedAt: iso, updatedAt: iso },+ patch: { sdkSessionId: null, clearedAt: iso, updatedAt: iso, preview: null },});expect(h.tapWindowBroadcast).toHaveBeenCalledWith('local-db:sessions:patched', {sessionId: 'sess-clear',- patch: { sdkSessionId: null, clearedAt: iso, updatedAt: iso },+ patch: { sdkSessionId: null, clearedAt: iso, updatedAt: iso, preview: null },});expect(h.broadcastSubagentRunsInvalidated).toHaveBeenCalledWith('sess-clear', null);});@@ -270,7 +276,10 @@ describe('persistSessionFields(远程 set-* 回流:字段白名单 + 广播)', (} as Record<string, unknown>);expect(h.updateSetCalls).toHaveLength(1);- expect(h.updateSetCalls[0]).toMatchObject({ model: 'claude-opus-4-8', providerId: 'anthropic' });+ expect(h.updateSetCalls[0]).toMatchObject({+ model: 'claude-opus-4-8',+ providerId: 'anthropic',+ });expect(lastTapPatch()!.patch).toEqual({ model: 'claude-opus-4-8', providerId: 'anthropic' });});@@ -288,11 +297,18 @@ describe('persistSessionFields(远程 set-* 回流:字段白名单 + 广播)', (extraDirs: ['/a', '/b'],permissionMode: 'plan',} as Record<string, unknown>);- expect(lastTapPatch()!.patch).toEqual({ fastMode: true, extraDirs: ['/a', '/b'], permissionMode: 'plan' });+ expect(lastTapPatch()!.patch).toEqual({+ fastMode: true,+ extraDirs: ['/a', '/b'],+ permissionMode: 'plan',+ });});it('patch 不含任何白名单字段 → 早退:不写库、不广播', async () => {- await persistSessionFields('sess-2', { title: 'x', status: 'archived' } as Record<string, unknown>);+ await persistSessionFields('sess-2', { title: 'x', status: 'archived' } as Record<+ string,+ unknown+ >);expect(h.updateSetCalls).toHaveLength(0);expect(h.tapWindowBroadcast).not.toHaveBeenCalled();});diff --git a/apps/desktop/src/main/im/shared/sessionRepo.ts b/apps/desktop/src/main/im/shared/sessionRepo.tsindex e1e2c464ee..d8775ddb0e 100644--- a/apps/desktop/src/main/im/shared/sessionRepo.ts+++ b/apps/desktop/src/main/im/shared/sessionRepo.ts@@ -500,7 +500,13 @@ export async function clearContext(sessionId: string): Promise<void> {const db = getDbClient().drizzle;await db.update(sessions)- .set({ sdkSessionId: null, clearedAt: Date.now(), updatedAt: Date.now() })+ .set({+ sdkSessionId: null,+ clearedAt: Date.now(),+ updatedAt: Date.now(),+ listPreview: null,+ listPreviewRole: null,+ }).where(eq(sessions.id, sessionId));}@@ -537,6 +543,8 @@ export async function resetSessionToDefaults(sdkSessionId: null,clearedAt: Date.now(),updatedAt: Date.now(),+ listPreview: null,+ listPreviewRole: null,}).where(eq(sessions.id, sessionId));setSessionProvider(sessionId, defaults.providerId);@@ -563,6 +571,8 @@ export async function switchSessionWorkingDir(sdkSessionId: null,clearedAt: Date.now(),updatedAt: Date.now(),+ listPreview: null,+ listPreviewRole: null,}).where(eq(sessions.id, sessionId));broadcastSessionCreated(sessionId);diff --git a/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts b/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.tsindex fcf123c36c..e4be811774 100644--- a/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts@@ -332,12 +332,16 @@ describe('orcaTeamStore', () => {im_user_id TEXT,used_project_context INTEGER NOT NULL DEFAULT 0,codex_history_has_product_prompt INTEGER,+ codex_plan_json TEXT,extra_dirs TEXT NOT NULL DEFAULT '[]',remote_host_id TEXT,provider_id TEXT,active_turn_started_at INTEGER,active_turn_pid INTEGER,last_turn_ended_at INTEGER,+ list_preview TEXT,+ list_preview_role TEXT,+ list_message_count INTEGER,created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL);diff --git a/apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.ts b/apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.tsindex 7b42e7fbfb..b26e968a0d 100644--- a/apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.ts@@ -44,6 +44,9 @@ describe('sessionActiveTurn', () => {active_turn_started_at INTEGER,active_turn_pid INTEGER,last_turn_ended_at INTEGER,+ list_preview TEXT,+ list_preview_role TEXT,+ list_message_count INTEGER,created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL);diff --git a/apps/desktop/src/main/localDb/__tests__/sessionListMessageCount.test.ts b/apps/desktop/src/main/localDb/__tests__/sessionListMessageCount.test.tsindex 9574e9a317..68a4dafdf7 100644--- a/apps/desktop/src/main/localDb/__tests__/sessionListMessageCount.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/sessionListMessageCount.test.ts@@ -210,9 +210,15 @@ describe('sessions:list messageCount source', () => {expect(source).toMatch(/messageCount: SESSION_MESSAGE_COUNT_SQL,/);expect(source).not.toMatch(/leftJoin\(messages/);expect(source).not.toMatch(/MESSAGE_COUNT_COL/);- // 标量子查询里必须是 count(*)(无 LEFT JOIN 补行,空会话得 0),且限定 session_id。+ // 已回填时短路缓存列;未回填时 count(*) 是精确总数。expect(source).toMatch(- /SESSION_MESSAGE_COUNT_SQL = sql<number>`\(\s*SELECT count\(\*\) FROM messages m WHERE m\.session_id = \$\{sessions\.id\}/,+ /SESSION_MESSAGE_COUNT_SQL = sql<number>`\(\s*CASE/,+ );+ expect(source).toMatch(+ /WHEN \$\{sessions\.listMessageCount\} IS NOT NULL THEN \$\{sessions\.listMessageCount\}/,+ );+ expect(source).toMatch(+ /SELECT count\(\*\) FROM messages m WHERE m\.session_id = \$\{sessions\.id\}/,);expect(source).toMatch(/ORDER BY m\.created_at DESC, m\.rowid DESC LIMIT 1/);diff --git a/apps/desktop/src/main/localDb/__tests__/sessionListProjection.test.ts b/apps/desktop/src/main/localDb/__tests__/sessionListProjection.test.tsnew file mode 100644index 0000000000..2dbc4913aa--- /dev/null+++ b/apps/desktop/src/main/localDb/__tests__/sessionListProjection.test.ts@@ -0,0 +1,301 @@+import Database from 'better-sqlite3';+import { describe, expect, it } from 'vitest';++import { extractMessagePreview, finalizePlainPreview, sessionToCamel } from '../mapper';+import type { SessionRowWithCount } from '../mapper';+import {+ LATEST_VISIBLE_PREVIEW_FILTER_SQL,+ LIST_PREVIEW_EXTRACT_SQL,+ SESSION_LIST_PROJECTION_BACKFILL_SQL,+} from '../sessionListProjection.sql';++function openPreviewDb() {+ const db = new Database(':memory:');+ db.exec(`+ CREATE TABLE sessions (+ id TEXT PRIMARY KEY,+ cleared_at INTEGER,+ list_preview TEXT,+ list_preview_role TEXT,+ list_message_count INTEGER+ );+ CREATE TABLE messages (+ id TEXT PRIMARY KEY,+ session_id TEXT NOT NULL,+ role TEXT NOT NULL,+ content TEXT NOT NULL,+ agent_meta TEXT,+ rewind_at INTEGER,+ created_at INTEGER NOT NULL+ );+ CREATE INDEX idx_messages_session_created ON messages (session_id, created_at);+ `);+ return db;+}++const extractSql = `SELECT ${LIST_PREVIEW_EXTRACT_SQL} AS preview, m.role AS role+ FROM messages m+ JOIN sessions ON sessions.id = m.session_id+ WHERE m.session_id = ?+ AND ${LATEST_VISIBLE_PREVIEW_FILTER_SQL}+ AND (sessions.cleared_at IS NULL OR m.created_at > sessions.cleared_at)+ ORDER BY m.created_at DESC, m.rowid DESC+ LIMIT 1`;++describe('session list SQL preview extract', () => {+ it('extracts user .text and assistant JSON strings without slicing JSON', () => {+ const db = openPreviewDb();+ db.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');+ db.prepare(+ `INSERT INTO messages (id, session_id, role, content, agent_meta, rewind_at, created_at)+ VALUES (?, ?, ?, ?, NULL, NULL, ?)`,+ ).run('m1', 's1', 'user', JSON.stringify({ text: 'hello from user', images: [] }), 1);+ db.prepare(+ `INSERT INTO messages (id, session_id, role, content, agent_meta, rewind_at, created_at)+ VALUES (?, ?, ?, ?, NULL, NULL, ?)`,+ ).run('m2', 's1', 'assistant', JSON.stringify('assistant markdown'), 2);++ const row = db.prepare(extractSql).get('s1') as { preview: string; role: string };+ expect(row.role).toBe('assistant');+ expect(row.preview).toBe('assistant markdown');+ expect(finalizePlainPreview(row.preview, row.role)).toBe('assistant markdown');+ db.close();+ });++ it('skips autoResume user rows and tool_result blobs', () => {+ const db = openPreviewDb();+ db.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');+ db.prepare(+ `INSERT INTO messages (id, session_id, role, content, agent_meta, rewind_at, created_at)+ VALUES (?, ?, ?, ?, NULL, NULL, ?)`,+ ).run('m-user', 's1', 'user', JSON.stringify({ text: 'real question' }), 1);+ db.prepare(+ `INSERT INTO messages (id, session_id, role, content, agent_meta, rewind_at, created_at)+ VALUES (?, ?, ?, ?, ?, NULL, ?)`,+ ).run(+ 'm-resume',+ 's1',+ 'user',+ JSON.stringify({ text: '继续' }),+ JSON.stringify({ autoResume: true }),+ 3,+ );+ db.prepare(+ `INSERT INTO messages (id, session_id, role, content, agent_meta, rewind_at, created_at)+ VALUES (?, ?, ?, ?, NULL, NULL, ?)`,+ ).run('m-tool', 's1', 'tool_result', JSON.stringify({ text: 'x'.repeat(5000) }), 4);++ const row = db.prepare(extractSql).get('s1') as { preview: string; role: string };+ expect(row.role).toBe('user');+ expect(row.preview).toBe('real question');+ db.close();+ });++ it('fallback message count is the exact row total', () => {+ const db = openPreviewDb();+ db.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');+ const insert = db.prepare(+ `INSERT INTO messages (id, session_id, role, content, created_at) VALUES (?, 's1', 'tool_result', '[]', 1)`,+ );+ const tx = db.transaction(() => {+ for (let i = 0; i < 15; i += 1) insert.run(`m${i}`);+ });+ tx();+ const count = db+ .prepare(`SELECT count(*) AS n FROM messages m WHERE m.session_id = ?`)+ .get('s1') as { n: number };+ expect(count.n).toBe(15);+ db.close();+ });+});++describe('sessionToCamel list preview cache', () => {+ it('uses listPreview as-is and does not parse it as JSON', () => {+ const session = sessionToCamel({+ id: 's-1',+ title: 't',+ workingDir: null,+ workspaceKind: 'project',+ model: 'm',+ effort: 'high',+ permissionMode: 'ask',+ providerId: null,+ status: 'active',+ sdkSessionId: null,+ totalTokenUsage: 0,+ totalCostUsd: 0,+ totalCostAmount: 0,+ totalCostCurrency: null,+ totalCostIsApproximate: false,+ contextTokens: 0,+ contextWindow: 0,+ fastMode: false,+ planModeEnabled: false,+ clearedAt: null,+ pinnedAt: null,+ userSendAt: null,+ agentKind: 'cc',+ source: 'desktop',+ orcaRole: null,+ parentSessionId: null,+ forkedAtMessageId: null,+ worktreePath: null,+ usedProjectContext: false,+ extraDirs: '[]',+ remoteHostId: null,+ activeTurnStartedAt: null,+ lastTurnEndedAt: null,+ listPreview: 'cached preview',+ listPreviewRole: 'assistant',+ listMessageCount: 4,+ summary: null,+ createdAt: 1,+ updatedAt: 1,+ messageCount: 4,+ latestMessageExtract: 'should not win',+ latestMessageContent: JSON.stringify({ text: 'should not parse' }),+ latestMessageRole: 'user',+ } as SessionRowWithCount);+ expect(session.preview).toBe('cached preview');+ expect(session._count?.messages).toBe(4);+ });++ it('sanitizes cached listPreview the same way as SQL extracts', () => {+ const session = sessionToCamel({+ id: 's-1',+ title: 't',+ workingDir: null,+ workspaceKind: 'project',+ model: 'm',+ effort: 'high',+ permissionMode: 'ask',+ providerId: null,+ status: 'active',+ sdkSessionId: null,+ totalTokenUsage: 0,+ totalCostUsd: 0,+ totalCostAmount: 0,+ totalCostCurrency: null,+ totalCostIsApproximate: false,+ contextTokens: 0,+ contextWindow: 0,+ fastMode: false,+ planModeEnabled: false,+ clearedAt: null,+ pinnedAt: null,+ userSendAt: null,+ agentKind: 'cc',+ source: 'desktop',+ orcaRole: null,+ parentSessionId: null,+ forkedAtMessageId: null,+ worktreePath: null,+ usedProjectContext: false,+ extraDirs: '[]',+ remoteHostId: null,+ activeTurnStartedAt: null,+ lastTurnEndedAt: null,+ listPreview: '[UI_ACTION_TRIGGER] continue',+ listPreviewRole: 'user',+ listMessageCount: 4,+ summary: null,+ createdAt: 1,+ updatedAt: 1,+ messageCount: 4,+ } as SessionRowWithCount);+ expect(session.preview).toBeNull();+ });++ it('finalizes SQL extracts without JSON.parse of a truncated object', () => {+ expect(extractMessagePreview(JSON.stringify({ text: 'hello world' }), 'user')).toBe(+ 'hello world',+ );+ expect(finalizePlainPreview('hello world', 'user')).toBe('hello world');+ });+});++describe('session list projection backfill SQL', () => {+ it('recomputes NULL columns from messages and ignores stale payload values', () => {+ const db = openPreviewDb();+ db.prepare(+ `INSERT INTO sessions (id, cleared_at, list_preview, list_preview_role, list_message_count)+ VALUES (?, NULL, NULL, NULL, NULL), (?, NULL, 'keep me', 'user', NULL), (?, NULL, NULL, NULL, 7)`,+ ).run('s1', 's2', 's3');+ db.prepare(+ `INSERT INTO messages (id, session_id, role, content, created_at)+ VALUES (?, 's1', 'assistant', ?, 2), (?, 's1', 'user', ?, 1), (?, 's2', 'assistant', ?, 1)`,+ ).run('m1', JSON.stringify('hello'), 'm0', JSON.stringify({ text: 'older' }), 'm2', JSON.stringify('stale'));++ db.prepare(SESSION_LIST_PROJECTION_BACKFILL_SQL).run(+ JSON.stringify([+ { id: 's1', preview: 'stale payload', role: 'user', count: 99, hasPreview: 1, hasCount: 1 },+ { id: 's2', preview: 'overwrite?', role: 'assistant', count: 9, hasPreview: 1, hasCount: 1 },+ { id: 's3', preview: 'new preview', role: 'user', count: 99, hasPreview: 1, hasCount: 1 },+ ]),+ );++ expect(+ db+ .prepare(+ 'SELECT id, list_preview, list_preview_role, list_message_count FROM sessions ORDER BY id',+ )+ .all(),+ ).toEqual([+ { id: 's1', list_preview: 'hello', list_preview_role: 'assistant', list_message_count: 2 },+ { id: 's2', list_preview: 'keep me', list_preview_role: 'user', list_message_count: 1 },+ { id: 's3', list_preview: null, list_preview_role: null, list_message_count: 7 },+ ]);+ db.close();+ });++ it('does not write a pre-clear preview when cleared_at moved after list computed', () => {+ const db = openPreviewDb();+ db.prepare(+ `INSERT INTO sessions (id, cleared_at, list_preview, list_preview_role, list_message_count)+ VALUES (?, 50, NULL, NULL, NULL)`,+ ).run('s1');+ db.prepare(+ `INSERT INTO messages (id, session_id, role, content, created_at)+ VALUES (?, 's1', 'assistant', ?, 10), (?, 's1', 'user', ?, 80)`,+ ).run('old', JSON.stringify('hidden'), 'fresh', JSON.stringify({ text: 'after clear' }));++ db.prepare(SESSION_LIST_PROJECTION_BACKFILL_SQL).run(+ JSON.stringify([{ id: 's1', preview: 'hidden', role: 'assistant', count: 2 }]),+ );+ expect(+ db+ .prepare(+ 'SELECT list_preview, list_preview_role, list_message_count FROM sessions WHERE id = ?',+ )+ .get('s1'),+ ).toEqual({+ list_preview: 'after clear',+ list_preview_role: 'user',+ list_message_count: 2,+ });+ db.close();+ });++ it('uses cached list_message_count instead of recounting', () => {+ const db = openPreviewDb();+ db.prepare(+ 'INSERT INTO sessions (id, list_preview, list_preview_role, list_message_count) VALUES (?, NULL, NULL, 2)',+ ).run('s1');+ const insert = db.prepare(+ `INSERT INTO messages (id, session_id, role, content, created_at) VALUES (?, 's1', 'user', '"hi"', 1)`,+ );+ for (let i = 0; i < 5; i += 1) insert.run(`m${i}`);+ const row = db+ .prepare(+ `SELECT CASE+ WHEN list_message_count IS NOT NULL THEN list_message_count+ ELSE (+ SELECT count(*) FROM messages m WHERE m.session_id = sessions.id+ )+ END AS n FROM sessions WHERE id = ?`,+ )+ .get('s1') as { n: number };+ expect(row.n).toBe(2);+ db.close();+ });+});diff --git a/apps/desktop/src/main/localDb/__tests__/workingDirHistoryFilter.test.ts b/apps/desktop/src/main/localDb/__tests__/workingDirHistoryFilter.test.tsindex 07e35534f1..1d83f3a08d 100644--- a/apps/desktop/src/main/localDb/__tests__/workingDirHistoryFilter.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/workingDirHistoryFilter.test.ts@@ -65,6 +65,9 @@ function createLocalDb(): Database.Database {active_turn_started_at INTEGER,active_turn_pid INTEGER,last_turn_ended_at INTEGER,+ list_preview TEXT,+ list_preview_role TEXT,+ list_message_count INTEGER,created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL);diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.tsindex 459593a45f..5948681f34 100644--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts@@ -315,6 +315,14 @@ function dispatchTx(readyDb, payload) {return sessionAgentSwitchFallback(readyDb, request.args);case 'context.rebuild':return contextRebuild(readyDb, request.args);+ case 'message.insert':+ return messageInsert(readyDb, request.args);+ case 'message.updateContent':+ return messageUpdateContent(readyDb, request.args);+ case 'message.leaseMutate':+ return messageLeaseMutate(readyDb, request.args);+ case 'message.rewindUserAfterClear':+ return messageRewindUserAfterClear(readyDb, request.args);case 'message.delete':return messageDelete(readyDb, request.args);case 'im.deleteBindings':@@ -423,7 +431,7 @@ function contextRebuild(readyDb, args) {: expectNumber(payload.expectedClearedAt, 'expectedClearedAt');return readyDb.transaction(() => {const sessionResult = readyDb.prepare(- 'UPDATE sessions SET sdk_session_id = NULL, updated_at = ? WHERE id = ? AND ifnull(cleared_at, -1) = ifnull(?, -1)',+ 'UPDATE sessions SET sdk_session_id = NULL, updated_at = ?, list_message_count = NULL WHERE id = ? AND ifnull(cleared_at, -1) = ifnull(?, -1)',).run(updatedAt, sessionId, expectedClearedAt);if (sessionResult.changes !== 1) {throw Object.assign(new Error('Session missing or clear-boundary changed: ' + sessionId), {@@ -437,6 +445,126 @@ function contextRebuild(readyDb, args) {})();}+// ⚠️ 与 worker/opHandlers/tx.ts 的同名事务保持一致。+function messageInsert(readyDb, args) {+ const payload = asRecord(args, 'message.insert args');+ const sessionId = expectString(payload.sessionId, 'sessionId');+ const id = expectString(payload.id, 'id');+ const clientId = expectString(payload.clientId, 'clientId');+ const role = expectString(payload.role, 'role');+ const content = expectString(payload.content, 'content');+ const toolUseId = nullableString(payload.toolUseId);+ const agentMeta = nullableString(payload.agentMeta);+ const agentKind = nullableString(payload.agentKind);+ const createdAt = expectNumber(payload.createdAt, 'createdAt');+ const guarded = payload.guarded === true;+ const expected =+ payload.expectedClearBoundaryMs === undefined || payload.expectedClearBoundaryMs === null+ ? null+ : expectNumber(payload.expectedClearBoundaryMs, 'expectedClearBoundaryMs');+ return readyDb.transaction(() => {+ let changes = 0;+ if (guarded) {+ changes = readyDb.prepare(+ 'INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, agent_meta, agent_kind, created_at) SELECT ?, ?, ?, ?, ?, ?, ?, ?, ? FROM sessions AS s WHERE s.id = ? AND COALESCE(s.cleared_at, -1) = COALESCE(?, -1) ON CONFLICT(session_id, client_id) DO NOTHING',+ ).run(id, clientId, sessionId, role, content, toolUseId, agentMeta, agentKind, createdAt, sessionId, expected).changes;+ } else {+ changes = readyDb.prepare(+ 'INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, agent_meta, agent_kind, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',+ ).run(id, clientId, sessionId, role, content, toolUseId, agentMeta, agentKind, createdAt).changes;+ }+ if (changes > 0) {+ if (role === 'user' || role === 'assistant') {+ readyDb.prepare(+ 'UPDATE sessions SET list_preview = NULL, list_preview_role = NULL, list_message_count = NULL WHERE id = ?',+ ).run(sessionId);+ } else {+ readyDb.prepare('UPDATE sessions SET list_message_count = NULL WHERE id = ?').run(sessionId);+ }+ }+ return { changes };+ })();+}++function messageUpdateContent(readyDb, args) {+ const payload = asRecord(args, 'message.updateContent args');+ const sessionId = expectString(payload.sessionId, 'sessionId');+ const clientId = expectString(payload.clientId, 'clientId');+ const content = expectString(payload.content, 'content');+ return readyDb.transaction(() => {+ const changes = readyDb.prepare(+ 'UPDATE messages SET content = ? WHERE session_id = ? AND client_id = ?',+ ).run(content, sessionId, clientId).changes;+ if (changes > 0) {+ const row = readyDb.prepare(+ 'SELECT role, rewind_at FROM messages WHERE session_id = ? AND client_id = ? LIMIT 1',+ ).get(sessionId, clientId);+ if (row && row.rewind_at == null && (row.role === 'user' || row.role === 'assistant')) {+ readyDb.prepare(+ 'UPDATE sessions SET list_preview = NULL, list_preview_role = NULL WHERE id = ?',+ ).run(sessionId);+ }+ }+ return { changes };+ })();+}++function messageLeaseMutate(readyDb, args) {+ const payload = asRecord(args, 'message.leaseMutate args');+ const op = expectString(payload.op, 'op');+ const sessionId = expectString(payload.sessionId, 'sessionId');+ const clientId = expectString(payload.clientId, 'clientId');+ return readyDb.transaction(() => {+ let changes = 0;+ if (op === 'insert') {+ const createdAt = expectNumber(payload.createdAt, 'createdAt');+ changes = readyDb.prepare(+ "INSERT INTO messages (id, client_id, session_id, role, content, agent_meta, created_at, rewind_at) VALUES (?, ?, ?, 'assistant', ?, ?, ?, ?) ON CONFLICT(session_id, client_id) DO NOTHING",+ ).run(+ expectString(payload.id, 'id'),+ clientId,+ sessionId,+ expectString(payload.content, 'content'),+ nullableString(payload.agentMeta),+ createdAt,+ createdAt,+ ).changes;+ } else if (op === 'deleteByContent') {+ changes = readyDb.prepare(+ 'DELETE FROM messages WHERE session_id = ? AND client_id = ? AND content = ?',+ ).run(sessionId, clientId, expectString(payload.content, 'content')).changes;+ } else if (op === 'deleteById') {+ changes = readyDb.prepare(+ 'DELETE FROM messages WHERE id = ? AND session_id = ? AND client_id = ?',+ ).run(expectString(payload.id, 'id'), sessionId, clientId).changes;+ } else {+ throw Object.assign(new Error('unknown message.leaseMutate op: ' + op), { code: 'INVALID_ARGS' });+ }+ if (changes > 0) {+ readyDb.prepare('UPDATE sessions SET list_message_count = NULL WHERE id = ?').run(sessionId);+ }+ return { changes };+ })();+}++function messageRewindUserAfterClear(readyDb, args) {+ const payload = asRecord(args, 'message.rewindUserAfterClear args');+ const sessionId = expectString(payload.sessionId, 'sessionId');+ const clientId = expectString(payload.clientId, 'clientId');+ const rewoundAt = expectNumber(payload.rewoundAt, 'rewoundAt');+ return readyDb.transaction(() => {+ const changes = readyDb.prepare(+ "UPDATE messages SET rewind_at = ? WHERE session_id = ? AND client_id = ? AND role = 'user' AND rewind_at IS NULL",+ ).run(rewoundAt, sessionId, clientId).changes;+ if (changes > 0) {+ readyDb.prepare(+ 'UPDATE sessions SET list_preview = NULL, list_preview_role = NULL WHERE id = ?',+ ).run(sessionId);+ }+ return { changes };+ })();+}+// ⚠️ 与 worker/opHandlers/tx.ts 的同名事务保持一致。function messageDelete(readyDb, args) {const payload = asRecord(args, 'message.delete args');@@ -567,7 +695,7 @@ function messageDelete(readyDb, args) {}}const sessionResult = readyDb.prepare(- 'UPDATE sessions SET sdk_session_id = NULL, updated_at = ? WHERE id = ?',+ 'UPDATE sessions SET sdk_session_id = NULL, updated_at = ?, list_preview = NULL, list_preview_role = NULL, list_message_count = NULL WHERE id = ?',).run(updatedAt, sessionId);if (sessionResult.changes !== 1) {throw Object.assign(new Error('Session 不存在: ' + sessionId), { code: 'NOT_FOUND' });@@ -1012,6 +1140,12 @@ function orcaReleaseWorkerCreationReservation(readyDb, args) {);}+function invalidateSessionListProjection(readyDb, sessionId) {+ readyDb.prepare(+ 'UPDATE sessions SET list_preview = NULL, list_preview_role = NULL, list_message_count = NULL WHERE id = ?',+ ).run(sessionId);+}+function codexImportMessages(readyDb, args) {const payload = asRecord(args, 'codex.importMessages args');const sessionId = expectString(payload.sessionId, 'sessionId');@@ -1061,6 +1195,7 @@ function codexImportMessages(readyDb, args) {createdAt,}).changes;}+ if (count > 0) invalidateSessionListProjection(readyDb, sessionId);return count;})();return { changed };@@ -1111,6 +1246,7 @@ function claudeImportMessages(readyDb, args) {createdAt: expectNumber(row.createdAt, 'row.createdAt'),}).changes;}+ if (count > 0) invalidateSessionListProjection(readyDb, sessionId);return count;})();return { changed };@@ -1176,9 +1312,9 @@ function rewindCommit(readyDb, args) {rewindParentlessSubagentTail.run(now, sessionId, targetCreatedAt);}if (sdkSessionId) {- readyDb.prepare('UPDATE sessions SET user_send_at = ?, updated_at = ?, context_tokens = 0, context_window = 0, codex_plan_json = NULL, sdk_session_id = ? WHERE id = ?').run(now, now, sdkSessionId, sessionId);+ readyDb.prepare('UPDATE sessions SET user_send_at = ?, updated_at = ?, context_tokens = 0, context_window = 0, codex_plan_json = NULL, sdk_session_id = ?, list_preview = NULL, list_preview_role = NULL WHERE id = ?').run(now, now, sdkSessionId, sessionId);} else {- readyDb.prepare('UPDATE sessions SET user_send_at = ?, updated_at = ?, context_tokens = 0, context_window = 0, codex_plan_json = NULL WHERE id = ?').run(now, now, sessionId);+ readyDb.prepare('UPDATE sessions SET user_send_at = ?, updated_at = ?, context_tokens = 0, context_window = 0, codex_plan_json = NULL, list_preview = NULL, list_preview_role = NULL WHERE id = ?').run(now, now, sessionId);}})();}@@ -1321,7 +1457,7 @@ function sessionTreeRehydrate(readyDb, args) {}upsert.run(row.id, row.clientId, sessionId, row.role, content, row.toolUseId, agentMeta, row.agentKind, row.createdAt);}- readyDb.prepare('UPDATE sessions SET cleared_at = NULL, context_tokens = ?, context_window = ?, updated_at = ? WHERE id = ?').run(contextTokens, contextWindow, now, sessionId);+ readyDb.prepare('UPDATE sessions SET cleared_at = NULL, context_tokens = ?, context_window = ?, updated_at = ?, list_preview = NULL, list_preview_role = NULL, list_message_count = NULL WHERE id = ?').run(contextTokens, contextWindow, now, sessionId);return captured;})();return { messageCount: rows.length, hiddenClientIds };diff --git a/apps/desktop/src/main/localDb/client/__tests__/drizzleProxy.test.ts b/apps/desktop/src/main/localDb/client/__tests__/drizzleProxy.test.tsindex 75067d6eb8..69e8b75063 100644--- a/apps/desktop/src/main/localDb/client/__tests__/drizzleProxy.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/drizzleProxy.test.ts@@ -54,6 +54,11 @@ const DRIZZLE_PROXY_SCHEMA = [active_turn_started_at INTEGER,active_turn_pid INTEGER,last_turn_ended_at INTEGER,+ one_m INTEGER NOT NULL DEFAULT 0,+ codex_plan_json TEXT,+ list_preview TEXT,+ list_preview_role TEXT,+ list_message_count INTEGER,created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL)diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.tsindex 9d1029b4e7..2adc58a255 100644--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts@@ -45,6 +45,9 @@ CREATE TABLE sessions (codex_plan_json TEXT,parent_session_id TEXT,forked_at_message_id TEXT,+ list_preview TEXT,+ list_preview_role TEXT,+ list_message_count INTEGER,created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL);@@ -515,6 +518,176 @@ describe('db worker tx handlers', () => {});});+ it.each([false, true])(+ 'message.insert invalidates list projection in the same transaction (inline=%s)',+ async (useInlineWorker) => {+ await withClient(+ async (client) => {+ await seedSession(client, 's1');+ const seedCache = () =>+ client.exec(+ 'UPDATE sessions SET list_preview = ?, list_preview_role = ?, list_message_count = ? WHERE id = ?',+ ['keep me', 'user', 7, 's1'],+ );+ const readCache = () =>+ client.queryOne(+ 'SELECT list_preview, list_preview_role, list_message_count FROM sessions WHERE id = ?',+ ['s1'],+ );++ await seedCache();+ await expect(+ client.tx('message.insert', {+ id: 'm1',+ clientId: 'c1',+ sessionId: 's1',+ role: 'user',+ content: JSON.stringify({ text: 'hi' }),+ toolUseId: null,+ agentMeta: null,+ agentKind: 'cc',+ createdAt: 1,+ guarded: false,+ }),+ ).resolves.toEqual({ changes: 1 });+ await expect(readCache()).resolves.toEqual({+ list_preview: null,+ list_preview_role: null,+ list_message_count: null,+ });++ await seedCache();+ await expect(+ client.tx('message.insert', {+ id: 'm2',+ clientId: 'c2',+ sessionId: 's1',+ role: 'tool_result',+ content: '[]',+ toolUseId: 't1',+ agentMeta: null,+ agentKind: 'cc',+ createdAt: 2,+ guarded: false,+ }),+ ).resolves.toEqual({ changes: 1 });+ await expect(readCache()).resolves.toEqual({+ list_preview: 'keep me',+ list_preview_role: 'user',+ list_message_count: null,+ });+ },+ { useInlineWorker },+ );+ },+ );++ it.each([false, true])(+ 'import and treeRehydrate invalidate list projection only when messages change (inline=%s)',+ async (useInlineWorker) => {+ await withClient(+ async (client) => {+ await seedSession(client, 's1');+ const seedCache = async () => {+ await client.exec(+ 'UPDATE sessions SET list_preview = ?, list_preview_role = ?, list_message_count = ? WHERE id = ?',+ ['stale preview', 'user', 4, 's1'],+ );+ };+ const readCache = () =>+ client.queryOne(+ 'SELECT list_preview, list_preview_role, list_message_count FROM sessions WHERE id = ?',+ ['s1'],+ );+ const stale = {+ list_preview: 'stale preview',+ list_preview_role: 'user',+ list_message_count: 4,+ };+ const cleared = {+ list_preview: null,+ list_preview_role: null,+ list_message_count: null,+ };++ await seedCache();+ expect(+ await client.tx('codex.importMessages', {+ sessionId: 's1',+ importClientIdPrefix: 'codex-import:',+ sdkSessionId: 'thread-1',+ model: 'gpt-5',+ rows: [],+ }),+ ).toEqual({ changed: 0 });+ await expect(readCache()).resolves.toEqual(stale);++ expect(+ await client.tx('codex.importMessages', {+ sessionId: 's1',+ importClientIdPrefix: 'codex-import:',+ sdkSessionId: 'thread-1',+ model: 'gpt-5',+ rows: [+ {+ lineNo: 1,+ role: 'assistant',+ text: 'imported',+ content: 'imported',+ createdAt: 2000,+ },+ ],+ }),+ ).toEqual({ changed: 1 });+ await expect(readCache()).resolves.toEqual(cleared);++ await seedCache();+ expect(+ await client.tx('claude.importMessages', {+ sessionId: 's1',+ importClientIdPrefix: 'claude-import:',+ sdkSessionId: 'sdk-1',+ rows: [+ {+ lineNo: 7,+ partIndex: 0,+ role: 'assistant',+ content: { text: 'hello' },+ toolUseId: null,+ agentMeta: null,+ createdAt: 3000,+ },+ ],+ }),+ ).toEqual({ changed: 1 });+ await expect(readCache()).resolves.toEqual(cleared);++ await seedCache();+ await client.tx('session.treeRehydrate', {+ sessionId: 's1',+ now: 4000,+ contextTokens: 1,+ contextWindow: 200000,+ messages: [+ {+ id: 'tree-1',+ clientId: 'tree-1',+ role: 'assistant',+ content: JSON.stringify('active branch'),+ toolUseId: null,+ agentMeta: null,+ agentKind: 'pi',+ createdAt: 2500,+ },+ ],+ });+ await expect(readCache()).resolves.toEqual(cleared);+ },+ { useInlineWorker },+ );+ },+ );+it.each([false, true])('rewind.commit soft-deletes messages and resets session context (inline=%s)',async (useInlineWorker) => {@@ -1363,7 +1536,10 @@ describe('db worker tx handlers', () => {it('context.rebuild appends markers instead of deleting earlier rebuild boundaries', async () => {await withClient(async (client) => {await seedSession(client, 's1');- await client.exec('UPDATE sessions SET sdk_session_id = ? WHERE id = ?', ['native-a', 's1']);+ await client.exec(+ 'UPDATE sessions SET sdk_session_id = ?, list_preview = ?, list_preview_role = ?, list_message_count = ? WHERE id = ?',+ ['native-a', 'keep me', 'user', 9, 's1'],+ );await client.tx('context.rebuild', {sessionId: 's1',markerId: 'rebuild-1',@@ -1399,8 +1575,16 @@ describe('db worker tx handlers', () => {},]);await expect(- client.queryOne('SELECT sdk_session_id, updated_at FROM sessions WHERE id = ?', ['s1']),- ).resolves.toEqual({ sdk_session_id: null, updated_at: 2000 });+ client.queryOne(+ 'SELECT sdk_session_id, updated_at, list_preview, list_message_count FROM sessions WHERE id = ?',+ ['s1'],+ ),+ ).resolves.toEqual({+ sdk_session_id: null,+ updated_at: 2000,+ list_preview: 'keep me',+ list_message_count: null,+ });});});diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex 835fe0b262..3fa51c867d 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -21,6 +21,10 @@ export type DbTxName =| 'sessions.setStatus'| 'session.agentSwitchFallback'| 'context.rebuild'+ | 'message.insert'+ | 'message.updateContent'+ | 'message.leaseMutate'+ | 'message.rewindUserAfterClear'| 'message.delete'| 'im.deleteBindings'| 'im.replaceBinding'@@ -316,6 +320,42 @@ export interface ContextRebuildArgs {expectedClearedAt?: number | null;}+export interface MessageInsertArgs {+ id: string;+ clientId: string;+ sessionId: string;+ role: string;+ content: string;+ toolUseId: string | null;+ agentMeta: string | null;+ agentKind: string | null;+ createdAt: number;+ guarded: boolean;+ expectedClearBoundaryMs?: number | null;+}++export interface MessageUpdateContentArgs {+ sessionId: string;+ clientId: string;+ content: string;+}++export interface MessageLeaseMutateArgs {+ op: 'insert' | 'deleteByContent' | 'deleteById';+ sessionId: string;+ clientId: string;+ id?: string;+ content?: string;+ agentMeta?: string | null;+ createdAt?: number;+}++export interface MessageRewindUserAfterClearArgs {+ sessionId: string;+ clientId: string;+ rewoundAt: number;+}+/*** 一次消息删除动作涉及的全部本地记录。删除 assistant 时,这里会包含同一真实* 用户轮中的 thinking / tool / 自动续跑 / 多段 assistant;删除 user 时只有目标行。@@ -774,6 +814,10 @@ export type DbTxArgsByName = {'sessions.setStatus': SessionsSetStatusArgs;'session.agentSwitchFallback': SessionAgentSwitchFallbackArgs;'context.rebuild': ContextRebuildArgs;+ 'message.insert': MessageInsertArgs;+ 'message.updateContent': MessageUpdateContentArgs;+ 'message.leaseMutate': MessageLeaseMutateArgs;+ 'message.rewindUserAfterClear': MessageRewindUserAfterClearArgs;'message.delete': MessageDeleteArgs;'im.deleteBindings': ImDeleteBindingsArgs;'im.replaceBinding': ImReplaceBindingArgs;@@ -820,6 +864,10 @@ export type DbTxResultByName = {'sessions.setStatus': SessionsSetStatusResultItem[];'session.agentSwitchFallback': undefined;'context.rebuild': undefined;+ 'message.insert': { changes: number };+ 'message.updateContent': { changes: number };+ 'message.leaseMutate': { changes: number };+ 'message.rewindUserAfterClear': { changes: number };'message.delete': MessageDeleteResult;'im.deleteBindings': undefined;'im.replaceBinding': undefined;diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.tsindex f2cdf1d5ff..a221dcc911 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts@@ -91,6 +91,7 @@ function createDb(initialTitle: string): void {orca_role TEXT,remote_host_id TEXT,codex_history_has_product_prompt INTEGER,+ codex_plan_json TEXT,im_bot_context_id TEXT,im_user_id TEXT,summary TEXT,@@ -98,7 +99,10 @@ function createDb(initialTitle: string): void {plan_mode_enabled INTEGER NOT NULL DEFAULT 0,active_turn_started_at INTEGER,active_turn_pid INTEGER,- last_turn_ended_at INTEGER+ last_turn_ended_at INTEGER,+ list_preview TEXT,+ list_preview_role TEXT,+ list_message_count INTEGER);CREATE TABLE messages (id TEXT PRIMARY KEY,diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.tsindex 641e00e6ee..c0ff58ebbe 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts@@ -108,6 +108,7 @@ function createDb(): void {orca_role TEXT,remote_host_id TEXT,codex_history_has_product_prompt INTEGER,+ codex_plan_json TEXT,im_bot_context_id TEXT,im_user_id TEXT,summary TEXT,@@ -115,7 +116,10 @@ function createDb(): void {plan_mode_enabled INTEGER NOT NULL DEFAULT 0,active_turn_started_at INTEGER,active_turn_pid INTEGER,- last_turn_ended_at INTEGER+ last_turn_ended_at INTEGER,+ list_preview TEXT,+ list_preview_role TEXT,+ list_message_count INTEGER);CREATE TABLE messages (id TEXT PRIMARY KEY,diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.tsindex 5fe89bd64c..ee4a219a8c 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts@@ -176,7 +176,10 @@ function createDb(): void {plan_mode_enabled INTEGER NOT NULL DEFAULT 0,active_turn_started_at INTEGER,active_turn_pid INTEGER,- last_turn_ended_at INTEGER+ last_turn_ended_at INTEGER,+ list_preview TEXT,+ list_preview_role TEXT,+ list_message_count INTEGER);CREATE TABLE messages (id TEXT PRIMARY KEY,diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.tsindex c79f83ab18..8c1e36d1d6 100644--- a/apps/desktop/src/main/localDb/ipc/messages.ts+++ b/apps/desktop/src/main/localDb/ipc/messages.ts@@ -11,8 +11,9 @@ import { and, asc, eq, inArray, lt, lte, gt, gte, desc, isNull, or, sql, type SQimport { createId } from '@paralleldrive/cuid2';import { getDbClient } from '../client/current';-import { latestVisiblePreview, latestVisiblePreviewRow } from '../latestMessageText';+import { latestVisiblePreviewRow } from '../latestMessageText';import { messages, sessions } from '../schema';+import { persistSessionListPreview } from '../sessionListProjection';import {messageToCamel,messageCreateToRow,@@ -169,9 +170,13 @@ async function maybeBroadcastSessionListPreview(}if (latest?.clientId !== row.clientId) return;if (!isOwnerBroadcastScopeCurrent(ownerScope)) return;+ const preview = extractMessagePreview(row.content, row.role);+ // 不在这里落库。insert/update 事务已经把 list_preview 置空;事后 persist 无法+ // 校验同一 clientId 的内容版本,交错改写会把旧正文写回非 NULL 缓存。+ // 侧栏即时刷新靠广播;下次 list/回填从 messages 现算。broadcastOwnedPayload('local-db:sessions:patched',- { sessionId, patch: { preview: extractMessagePreview(row.content, row.role) } },+ { sessionId, patch: { preview } },ownerScope,);}@@ -945,10 +950,18 @@ export async function commitMessageDeletion(// 口径要动得连 maker-shared/sessionList 的 messageCountLabel 一起改。let preview: string | null = null;try {- preview = await latestVisiblePreview(sessionId);+ const latest = await latestVisiblePreviewRow(sessionId);+ preview = extractMessagePreview(latest?.content, latest?.role);+ await persistSessionListPreview(+ sessionId,+ preview,+ latest?.role ?? null,+ latest?.createdAt,+ latest?.clientId,+ );} catch (error) {- // 删除已经原子提交;投影查询失败不能把成功操作伪装成失败。广播保守空值,- // 后续 sessions:list / reseed 会按 DB 真相收敛。+ // 删除已经原子提交;message.delete 事务已把 list_preview / role / count 置 NULL,+ // 投影刷新失败不能把成功操作伪装成失败。广播保守空值,list 回落子查询。log.warn('message delete session projection refresh failed', {sessionId,deletedClientIds: clientIds,@@ -1097,15 +1110,11 @@ export async function rewindPersistedUserMessageAfterClear(if (!row) return;const rewoundAt = Date.now();- const updated = await dbClient.exec(- `UPDATE messages- SET rewind_at = ?- WHERE session_id = ?- AND client_id = ?- AND role = 'user'- AND rewind_at IS NULL`,- [rewoundAt, sessionId, clientId],- );+ const updated = await dbClient.tx('message.rewindUserAfterClear', {+ sessionId,+ clientId,+ rewoundAt,+ });if (!isOwnerBroadcastScopeCurrent(ownerScope)) return;if (updated.changes === 0) return;@@ -1269,12 +1278,14 @@ export async function updateMessageContent(content: unknown,): Promise<Message | null> {const ownerScope = captureOwnerBroadcastScope();- const db = getDbClient().drizzle;+ const dbClient = getDbClient();+ const db = dbClient.drizzle;const serialized = safeStringify(content);- await db- .update(messages)- .set({ content: serialized })- .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, clientId)));+ await dbClient.tx('message.updateContent', {+ sessionId,+ clientId,+ content: serialized,+ });// 窄回读:刻意不选 content——tool_result 全文可达 MB 级,整行回读会把大字段// 经 DB worker 的 postMessage 结构化克隆再送回主进程一次。content 就是本次// 写入值,用 serialized 回填;行不存在(clientId 未落库)仍以回读判 null。@@ -1449,35 +1460,20 @@ export async function createMessage(: (body.createdAt ?? now);const insertRow = messageCreateToRow(id, sessionId, body, visibleCreatedAt);try {- if (guarded) {- // Keep the session compare and message insert in one SQLite statement.- // A separate SELECT would allow /clear to win between the check and the- // INSERT on the DB worker.- const inserted = await dbClient.exec(- `INSERT INTO messages (- id, client_id, session_id, role, content, tool_use_id,- agent_meta, agent_kind, created_at- )- SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?- FROM sessions AS s- WHERE s.id = ?- AND COALESCE(s.cleared_at, -1) = COALESCE(?, -1)- ON CONFLICT(session_id, client_id) DO NOTHING`,- [- insertRow.id,- insertRow.clientId,- insertRow.sessionId,- insertRow.role,- insertRow.content,- insertRow.toolUseId,- insertRow.agentMeta,- insertRow.agentKind,- insertRow.createdAt,- sessionId,- expected,- ],- );- if (inserted.changes === 0) {+ const inserted = await dbClient.tx('message.insert', {+ id: insertRow.id,+ clientId: insertRow.clientId,+ sessionId,+ role: insertRow.role,+ content: insertRow.content,+ toolUseId: insertRow.toolUseId ?? null,+ agentMeta: insertRow.agentMeta ?? null,+ agentKind: insertRow.agentKind ?? null,+ createdAt: insertRow.createdAt,+ guarded,+ expectedClearBoundaryMs: guarded ? (expected ?? null) : undefined,+ });+ if (guarded && inserted.changes === 0) {const [existingAfterGuard] = await db.select().from(messages)@@ -1507,9 +1503,6 @@ export async function createMessage(}throw new Error('Message insert skipped without a clear-boundary change');}- } else {- await db.insert(messages).values(insertRow);- }} catch (err) {const after = await db.select()diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex b426bb014f..cc3e8d4f8f 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -23,6 +23,12 @@ import { getDbClient } from '../client/current';import * as currentDb from '../client/current';import type { DbClient } from '../client/DbClient';import { sessions, messages } from '../schema';+import {+ LIST_PREVIEW_EXTRACT_SQL,+ LATEST_VISIBLE_PREVIEW_FILTER_SQL,+ persistSessionListProjectionBatch,+ type SessionListProjectionBackfillItem,+} from '../sessionListProjection';import { buildSessionListFlightKey, runSessionListSingleFlight } from './sessionListSingleFlight';import { throwIpcError, requireString, requireObject } from '../../utils/ipcValidate';import { bindDeletedPiSubagentCleanupCancel } from './piSubagentDeletion';@@ -33,6 +39,7 @@ import {sessionCreateToRow,sessionPatchToRow,normalizeRemoteHostId,+ finalizePlainPreview,type SessionRowWithCount,} from '../mapper';import { ensureDialogueWorkspaceDir } from '../dialogueWorkspace';@@ -552,43 +559,49 @@ const MAX_LIMIT = 1000;* 也走同一条标量子查询,避免切任务时把几万行 join 进单行快照。** 由 sessionListMessageCount 回归测试守护。+ *+ * list_message_count 已回填时走缓存列,跳过 messages 扫描。未回填时 count(*) 精确总数+ * (侧栏文案仍用 messageCountLabel 把 ≥1001 显示成 1000+;wire `_count.messages` 保持精确)。+ * 非 NULL 即信任:绕过 createMessage 的 messages 增删必须同步投影。+ * import / treeRehydrate 置空三列;turn/review 租约、context.rebuild、createMessage 只置空计数。*/const SESSION_MESSAGE_COUNT_SQL = sql<number>`(- SELECT count(*) FROM messages m WHERE m.session_id = ${sessions.id}+ CASE+ WHEN ${sessions.listMessageCount} IS NOT NULL THEN ${sessions.listMessageCount}+ ELSE (+ SELECT count(*) FROM messages m WHERE m.session_id = ${sessions.id}+ )+ END)`.as('message_count');/**- * sidebar-card-mode:最近一条 user/assistant 消息的 content / role correlated 子查询。- * 跳过 tool_use/tool_result/thinking 等噪音 role;rewind 软删的消息不进预览。- * 命中 idx_messages_session_created (session_id, created_at) 索引,逐 session O(logN)。+ * sidebar-card-mode:最近一条可见 user/assistant 的预览抽出 / role。+ * list_preview 已回填时 CASE 短路,不碰 messages。否则 SQL 侧 json_extract 纯文本,+ * 不把整段 content 跨 worker RPC。autoResume 只检查 user 行的 agent_meta。*/-// .as(alias) 必须显式给——drizzle 对匿名 sql 字段在 better-sqlite3 下无法-// 稳定按 select key 映射,结果列取不到值(实测全 undefined → preview 恒 null)。-// clearedAt 边界与 messages:list 同口径:clear 过的会话只看 clearedAt 之后的消息,-// 否则卡片预览会露出 /clear 已隐藏的旧内容。-// autoResume 排除:silent-stop 自动续跑注入的「继续」(agentMeta.autoResume=true,-// 见 register.ts handleSilentStopTurnEnd)不是用户消息,渲染层显示为「已自动继续」-// 分隔卡,预览同样不能把它当最近消息展示(session.preview 经 device-link 直达手机-// 首页,漏了会显示一条用户没发过的消息)。按落库标记过滤,不按文本——用户真发-// 「继续」是合法消息。json_extract 对 JSON true 返回 1;缺字段返回 NULL,IS NOT 1 放行。-// 非法 JSON 必须用 CASE 挡住 json_extract,OR json_valid 不保证短路,会整句 malformed JSON。-const LATEST_MSG_CONTENT_SQL = sql<string | null>`(- SELECT m.content FROM messages m- WHERE m.session_id = ${sessions.id}- AND m.role IN ('user', 'assistant')- AND m.rewind_at IS NULL- AND (m.agent_meta IS NULL OR CASE WHEN json_valid(m.agent_meta) THEN json_extract(m.agent_meta, '$.autoResume') END IS NOT 1)- AND (${sessions.clearedAt} IS NULL OR m.created_at > ${sessions.clearedAt})- ORDER BY m.created_at DESC, m.rowid DESC LIMIT 1-)`.as('latest_message_content');+const LATEST_MSG_EXTRACT_SQL = sql<string | null>`(+ CASE+ WHEN ${sessions.listPreview} IS NOT NULL THEN NULL+ ELSE (+ SELECT ${sql.raw(LIST_PREVIEW_EXTRACT_SQL)} FROM messages m+ WHERE m.session_id = ${sessions.id}+ AND ${sql.raw(LATEST_VISIBLE_PREVIEW_FILTER_SQL)}+ AND (${sessions.clearedAt} IS NULL OR m.created_at > ${sessions.clearedAt})+ ORDER BY m.created_at DESC, m.rowid DESC LIMIT 1+ )+ END+)`.as('latest_message_extract');const LATEST_MSG_ROLE_SQL = sql<string | null>`(- SELECT m.role FROM messages m- WHERE m.session_id = ${sessions.id}- AND m.role IN ('user', 'assistant')- AND m.rewind_at IS NULL- AND (m.agent_meta IS NULL OR CASE WHEN json_valid(m.agent_meta) THEN json_extract(m.agent_meta, '$.autoResume') END IS NOT 1)- AND (${sessions.clearedAt} IS NULL OR m.created_at > ${sessions.clearedAt})- ORDER BY m.created_at DESC, m.rowid DESC LIMIT 1+ CASE+ WHEN ${sessions.listPreviewRole} IS NOT NULL THEN ${sessions.listPreviewRole}+ ELSE (+ SELECT m.role FROM messages m+ WHERE m.session_id = ${sessions.id}+ AND ${sql.raw(LATEST_VISIBLE_PREVIEW_FILTER_SQL)}+ AND (${sessions.clearedAt} IS NULL OR m.created_at > ${sessions.clearedAt})+ ORDER BY m.created_at DESC, m.rowid DESC LIMIT 1+ )+ END)`.as('latest_message_role');/**@@ -946,6 +959,8 @@ export async function clearSessionContextInDb(sessionId: string, atMs?: number):// make pre-clear history visible again or invalidate a newer input token.clearedAt: sql<number>`MAX(COALESCE(${sessions.clearedAt}, 0), ${ts})`,updatedAt: sql<number>`MAX(COALESCE(${sessions.updatedAt}, 0), ${ts})`,+ listPreview: null,+ listPreviewRole: null,}).where(eq(sessions.id, sessionId));const [updated] = await db@@ -974,6 +989,7 @@ export async function clearSessionContextInDb(sessionId: string, atMs?: number):sdkSessionId: null,clearedAt: new Date(effectiveClearedAt).toISOString(),updatedAt: new Date(effectiveUpdatedAt).toISOString(),+ preview: null,},ownerScope,);@@ -1040,11 +1056,12 @@ export function registerSessionIpc(mergedRows = mergeSessionListRows(rows, pinnedRows);}+ scheduleSessionListProjectionBackfill(mergedRows);return mergedRows.map((r) =>sessionToCamel({...r.session,messageCount: r.messageCount,- latestMessageContent: r.latestMessageContent,+ latestMessageExtract: r.latestMessageExtract,latestMessageRole: r.latestMessageRole,}),);@@ -1498,6 +1515,11 @@ export function registerSessionIpc(const setObj = sessionPatchToRow(p as Parameters<typeof sessionPatchToRow>[0], {bumpUpdatedAt: !isSettingsOnly,});+ if (p.clearedAt !== undefined) {+ setObj.summary = null;+ setObj.listPreview = null;+ setObj.listPreviewRole = null;+ }// 用户手动改名(重命名框 / 侧边栏)走这条:告诉自动起名收手。同值改名不会让// 条件写落空,不显式说一声的话智能标题会把他刚保存的名字盖掉(review P1)。// **必须先于 UPDATE**:写库是一次 worker RPC 往返,改名提交与这里拿到回执之间@@ -1520,13 +1542,9 @@ export function registerSessionIpc(noteSessionClearBoundary(sid, p.clearedAt as string | null);// sidebar-card-mode(codex review):summary 是基于 clear 前内容生成的,clear 后// 已过时;置顶卡片优先用 summary 而非 preview,不清就会继续显示旧任务摘要。- // 这里一并清空,待 clear 后新一轮 turn-done 重新生成。- await db.update(sessions).set({ summary: null }).where(eq(sessions.id, sid));- // 广播 summary:null,让已挂载的 sidebar 立即清掉旧摘要(codex review)——renderer 的- // clearSession 乐观 patch 只带 sdkSessionId/clearedAt、不含 summary,本 update handler- // 也不另发 patched;不广播则卡片/rail 会继续显示 clear 前摘要直到一次全量 refresh。+ // 与 clearedAt 同一句 UPDATE 置空,避免崩溃后非 NULL 缓存绕过 clear 边界。if (isOwnerScopeCurrent(ownerScope)) {- broadcastSessionPatched(sid, { summary: null }, ownerScope);+ broadcastSessionPatched(sid, { summary: null, preview: null }, ownerScope);}void recomputePrRefsForSession(sid).catch(() => undefined);}@@ -2142,11 +2160,65 @@ function cleanupSessionTerminalArtifacts(sessionId: string, status: unknown): vo});}+const pendingSessionListProjectionBackfill = new Map<string, SessionListProjectionBackfillItem>();+let sessionListProjectionBackfillInFlight = false;++/**+ * list 算出来的 preview / count 异步写回 sessions。+ * 必须合成一次 RPC:首屏 1000 行每人两条 drizzle UPDATE 会打爆 worker 队列+ * (inFlight=128 queued=512)。两次 list 交错时也先攒进同一批。+ */+function scheduleSessionListProjectionBackfill(rows: readonly SessionListRow[]): void {+ for (const row of rows) {+ const sessionId = row.session.id;+ const item = pendingSessionListProjectionBackfill.get(sessionId) ?? { id: sessionId };+ if (row.session.listPreview == null && row.latestMessageExtract != null) {+ const preview = finalizePlainPreview(row.latestMessageExtract, row.latestMessageRole);+ if (preview != null) {+ item.preview = preview;+ item.role = row.latestMessageRole;+ }+ }+ if (row.session.listMessageCount == null) {+ item.count = row.messageCount;+ }+ if (item.preview !== undefined || item.count !== undefined) {+ pendingSessionListProjectionBackfill.set(sessionId, item);+ }+ }+ void drainSessionListProjectionBackfill();+}++async function drainSessionListProjectionBackfill(): Promise<void> {+ if (sessionListProjectionBackfillInFlight) return;+ if (pendingSessionListProjectionBackfill.size === 0) return;+ sessionListProjectionBackfillInFlight = true;+ try {+ while (pendingSessionListProjectionBackfill.size > 0) {+ const items = Array.from(pendingSessionListProjectionBackfill.values());+ pendingSessionListProjectionBackfill.clear();+ try {+ await persistSessionListProjectionBatch(items);+ } catch (err) {+ log.warn('session list projection backfill failed', {+ count: items.length,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }+ } finally {+ sessionListProjectionBackfillInFlight = false;+ if (pendingSessionListProjectionBackfill.size > 0) {+ void drainSessionListProjectionBackfill();+ }+ }+}+/** {@link selectSessionListRows} 的行形状——与 sessionToCamel 的入参对齐。 */interface SessionListRow {session: typeof sessions.$inferSelect;messageCount: number;- latestMessageContent: string | null;+ latestMessageExtract: string | null;latestMessageRole: string | null;}@@ -2188,7 +2260,7 @@ function selectSessionListRows(.select({session: sessions,messageCount: SESSION_MESSAGE_COUNT_SQL,- latestMessageContent: LATEST_MSG_CONTENT_SQL,+ latestMessageExtract: LATEST_MSG_EXTRACT_SQL,latestMessageRole: LATEST_MSG_ROLE_SQL,}).from(sessions)@@ -2208,7 +2280,7 @@ async function selectSessionWithCount(.select({session: sessions,messageCount: SESSION_MESSAGE_COUNT_SQL,- latestMessageContent: LATEST_MSG_CONTENT_SQL,+ latestMessageExtract: LATEST_MSG_EXTRACT_SQL,latestMessageRole: LATEST_MSG_ROLE_SQL,}).from(sessions)@@ -2218,7 +2290,7 @@ async function selectSessionWithCount(return {...r.session,messageCount: r.messageCount,- latestMessageContent: r.latestMessageContent,+ latestMessageExtract: r.latestMessageExtract,latestMessageRole: r.latestMessageRole,};}diff --git a/apps/desktop/src/main/localDb/latestMessageText.ts b/apps/desktop/src/main/localDb/latestMessageText.tsindex 11961acbd2..2958ba812d 100644--- a/apps/desktop/src/main/localDb/latestMessageText.ts+++ b/apps/desktop/src/main/localDb/latestMessageText.ts@@ -64,6 +64,7 @@ export interface LatestVisiblePreviewRow {clientId: string;content: string;role: string;+ createdAt: number;}/**@@ -78,6 +79,7 @@ export async function latestVisiblePreviewRow(clientId: messages.clientId,content: messages.content,role: messages.role,+ createdAt: messages.createdAt,}).from(messages).innerJoin(sessions, eq(messages.sessionId, sessions.id))diff --git a/apps/desktop/src/main/localDb/mapper.ts b/apps/desktop/src/main/localDb/mapper.tsindex dccdd3c031..3a7bfd6c64 100644--- a/apps/desktop/src/main/localDb/mapper.ts+++ b/apps/desktop/src/main/localDb/mapper.ts@@ -86,6 +86,7 @@ export function setSessionRuntimeProjector(projector: SessionRuntimeProjector |export type SessionRowWithCount = SessionRow & {messageCount: number;latestMessageContent?: string | null;+ latestMessageExtract?: string | null;latestMessageRole?: string | null;};@@ -101,6 +102,22 @@ const PREVIEW_CONTENT_BOUND_CHARS = 4096;* - 解析失败 / 空文本 → null(渲染端隐藏预览行)* 换行折叠成空格——卡片预览是流式 3 行 clamp,不保留消息内排版。*/+export function finalizePlainPreview(+ text: string | null | undefined,+ role: string | null | undefined,+): string | null {+ if (!text) return null;+ let next = text;+ // 合成 UI 指令行(隐藏续跑 / 图片按钮)不进 sidebar 预览(review P2):它是+ // role='user' 的正常落库行,但对用户不可见 —— 预览显示隐藏英文指令会暴露+ // 实现细节。返回 null 与"无预览"同渲染语义。+ if (isSyntheticTriggerText(next)) return null;+ if (role === 'assistant') next = stripInternalWebCitations(next);+ const collapsed = next.replace(/\s+/g, ' ').trim();+ if (!collapsed) return null;+ return collapsed.length > PREVIEW_MAX_CHARS ? collapsed.slice(0, PREVIEW_MAX_CHARS) : collapsed;+}+export function extractMessagePreview(raw: string | null | undefined,role: string | null | undefined,@@ -119,15 +136,7 @@ export function extractMessagePreview(// 极端情况 content 不是合法 JSON(旧手工写入)——按纯文本兜底text = raw;}- if (!text) return null;- // 合成 UI 指令行(隐藏续跑 / 图片按钮)不进 sidebar 预览(review P2):它是- // role='user' 的正常落库行,但对用户不可见 —— 预览显示隐藏英文指令会暴露- // 实现细节。返回 null 与"无预览"同渲染语义。- if (isSyntheticTriggerText(text)) return null;- if (role === 'assistant') text = stripInternalWebCitations(text);- const collapsed = text.replace(/\s+/g, ' ').trim();- if (!collapsed) return null;- return collapsed.length > PREVIEW_MAX_CHARS ? collapsed.slice(0, PREVIEW_MAX_CHARS) : collapsed;+ return finalizePlainPreview(text, role);}/**@@ -228,10 +237,15 @@ export function sessionToCamel(row: SessionRowWithCount): Session {createdAt: new Date(row.createdAt).toISOString(),updatedAt: new Date(row.updatedAt).toISOString(),_count: { messages: row.messageCount },- preview: extractMessagePreview(- boundSerializedMessageContent(row.latestMessageContent),- row.latestMessageRole,- ),+ preview:+ row.listPreview != null+ ? finalizePlainPreview(row.listPreview, row.listPreviewRole)+ : row.latestMessageExtract != null+ ? finalizePlainPreview(row.latestMessageExtract, row.latestMessageRole)+ : extractMessagePreview(+ boundSerializedMessageContent(row.latestMessageContent),+ row.latestMessageRole,+ ),summary: row.summary ?? null,};return sessionRuntimeProjector ? { ...base, ...sessionRuntimeProjector(base) } : base;diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.tsindex eba6301597..cc7f6c7076 100644--- a/apps/desktop/src/main/localDb/schema.ts+++ b/apps/desktop/src/main/localDb/schema.ts@@ -219,6 +219,17 @@ export const sessions = sqliteTable(* sessionActiveTurn.ts 文件头。*/lastTurnEndedAt: integer('last_turn_ended_at'),+ /**+ * 侧栏列表投影:已提炼的 preview 纯文本(最多 140 字)。NULL = 尚未回填,+ * sessions:list 回落到 messages 相关子查询。不在 migration 里扫历史库。+ */+ listPreview: text('list_preview'),+ listPreviewRole: text('list_preview_role'),+ /**+ * 侧栏「N 条消息」缓存。口径与历史 count(*) 相同(不过滤 role/rewind/clear)。+ * 存精确总数;UI 把 ≥1001 显示成 1000+。NULL = 尚未回填。+ */+ listMessageCount: integer('list_message_count'),createdAt: integer('created_at').notNull(),updatedAt: integer('updated_at').notNull(),},diff --git a/apps/desktop/src/main/localDb/sessionListProjection.sql.ts b/apps/desktop/src/main/localDb/sessionListProjection.sql.tsnew file mode 100644index 0000000000..a842d848f5--- /dev/null+++ b/apps/desktop/src/main/localDb/sessionListProjection.sql.ts@@ -0,0 +1,60 @@+import { SESSION_LIST_MESSAGE_COUNT_CAP } from '@cindy/maker-shared/session-list';++export { SESSION_LIST_MESSAGE_COUNT_CAP };++/** SQL 抽出的预览原文上限。mapper 再折叠空白并截到 140。 */+export const LIST_PREVIEW_EXTRACT_CHARS = 512;++/**+ * 从 messages.content(JSON 字符串)抽出纯文本。对齐 extractMessagePreview 的解析口径:+ * JSON 字符串(assistant)原样取;user 对象取 .text;非法 JSON 当纯文本。+ * 不做 substr 截断半截 JSON——先 json_extract 再截。+ */+export const LIST_PREVIEW_EXTRACT_SQL = `CASE+ WHEN json_valid(m.content) = 0 THEN substr(m.content, 1, ${LIST_PREVIEW_EXTRACT_CHARS})+ WHEN json_type(m.content) = 'text' THEN substr(json_extract(m.content, '$'), 1, ${LIST_PREVIEW_EXTRACT_CHARS})+ WHEN m.role = 'user' AND json_type(m.content) = 'object' THEN substr(json_extract(m.content, '$.text'), 1, ${LIST_PREVIEW_EXTRACT_CHARS})+ ELSE NULL+END`;++/** autoResume 只出现在注入的 user「继续」行;assistant 不读 agent_meta,避免跨越多 MB content overflow。 */+export const LATEST_VISIBLE_PREVIEW_FILTER_SQL = `m.role IN ('user', 'assistant')+ AND m.rewind_at IS NULL+ AND (m.role != 'user' OR m.agent_meta IS NULL OR CASE WHEN json_valid(m.agent_meta) THEN json_extract(m.agent_meta, '$.autoResume') END IS NOT 1)`;++const LATEST_VISIBLE_PREVIEW_FROM_SQL = `FROM messages m+ WHERE m.session_id = sessions.id+ AND ${LATEST_VISIBLE_PREVIEW_FILTER_SQL}+ AND (sessions.cleared_at IS NULL OR m.created_at > sessions.cleared_at)+ ORDER BY m.created_at DESC, m.rowid DESC LIMIT 1`;++/**+ * 把仍为 NULL 的 preview / count 一次性写回 sessions。+ * 绑定 JSON 数组,只用 `id`;preview/count 在本句内从 messages 现算,+ * 避免 list 读出的旧 payload 盖住读后、写回前的失效。+ * 只填当前仍是 NULL 的列,避免盖掉写路径已经落好的值。+ */+export const SESSION_LIST_PROJECTION_BACKFILL_SQL = `UPDATE sessions+SET+ list_preview = CASE+ WHEN sessions.list_preview IS NULL THEN (+ SELECT ${LIST_PREVIEW_EXTRACT_SQL} ${LATEST_VISIBLE_PREVIEW_FROM_SQL}+ )+ ELSE sessions.list_preview+ END,+ list_preview_role = CASE+ WHEN sessions.list_preview IS NULL THEN (+ SELECT m.role ${LATEST_VISIBLE_PREVIEW_FROM_SQL}+ )+ ELSE sessions.list_preview_role+ END,+ list_message_count = CASE+ WHEN sessions.list_message_count IS NULL THEN (+ SELECT count(*) FROM messages m WHERE m.session_id = sessions.id+ )+ ELSE sessions.list_message_count+ END+FROM (+ SELECT json_extract(value, '$.id') AS id FROM json_each(?)+) AS payload+WHERE sessions.id = payload.id`;diff --git a/apps/desktop/src/main/localDb/sessionListProjection.ts b/apps/desktop/src/main/localDb/sessionListProjection.tsnew file mode 100644index 0000000000..aac47d6165--- /dev/null+++ b/apps/desktop/src/main/localDb/sessionListProjection.ts@@ -0,0 +1,130 @@+/**+ * sessions:list 的投影回填:写路径把 preview / count 落到 sessions 可空列。+ * SQL 片段见 sessionListProjection.sql.ts。+ */+import { and, eq, isNull, or, sql } from 'drizzle-orm';++import { getDbClient } from './client/current.js';+import { sessions } from './schema.js';+import {+ LATEST_VISIBLE_PREVIEW_FILTER_SQL,+ SESSION_LIST_MESSAGE_COUNT_CAP,+ SESSION_LIST_PROJECTION_BACKFILL_SQL,+} from './sessionListProjection.sql.js';++export {+ LIST_PREVIEW_EXTRACT_CHARS,+ LIST_PREVIEW_EXTRACT_SQL,+ LATEST_VISIBLE_PREVIEW_FILTER_SQL,+ SESSION_LIST_MESSAGE_COUNT_CAP,+ SESSION_LIST_PROJECTION_BACKFILL_SQL,+} from './sessionListProjection.sql.js';++export type SessionListProjectionBackfillItem = {+ id: string;+ preview?: string | null;+ role?: string | null;+ count?: number;+};++export function serializeSessionListProjectionBackfill(+ items: readonly SessionListProjectionBackfillItem[],+): string {+ return JSON.stringify(+ items.map((item) => ({+ id: item.id,+ preview: item.preview ?? null,+ role: item.role ?? null,+ count:+ item.count === undefined+ ? null+ : Math.min(Math.max(0, Math.floor(item.count)), SESSION_LIST_MESSAGE_COUNT_CAP),+ hasPreview: item.preview !== undefined ? 1 : 0,+ hasCount: item.count !== undefined ? 1 : 0,+ })),+ );+}++export async function persistSessionListPreview(+ sessionId: string,+ preview: string | null,+ role: string | null,+ visibleCreatedAt?: number | null,+ visibleClientId?: string | null,+): Promise<void> {+ const db = getDbClient().drizzle;+ if (preview == null) {+ await db+ .update(sessions)+ .set({ listPreview: null, listPreviewRole: null })+ .where(eq(sessions.id, sessionId));+ return;+ }+ const createdAt =+ typeof visibleCreatedAt === 'number' && Number.isFinite(visibleCreatedAt)+ ? Math.floor(visibleCreatedAt)+ : null;+ const clientId =+ typeof visibleClientId === 'string' && visibleClientId.length > 0 ? visibleClientId : null;+ const conds = [+ eq(sessions.id, sessionId),+ createdAt == null+ ? isNull(sessions.clearedAt)+ : or(isNull(sessions.clearedAt), sql`${sessions.clearedAt} < ${createdAt}`),+ ];+ if (createdAt != null && clientId != null) {+ conds.push(+ sql`NOT EXISTS (+ SELECT 1 FROM messages m+ WHERE m.session_id = ${sessions.id}+ AND ${sql.raw(LATEST_VISIBLE_PREVIEW_FILTER_SQL)}+ AND (${sessions.clearedAt} IS NULL OR m.created_at > ${sessions.clearedAt})+ AND (+ m.created_at > ${createdAt}+ OR (+ m.created_at = ${createdAt}+ AND m.rowid > (+ SELECT m2.rowid FROM messages m2+ WHERE m2.session_id = ${sessions.id} AND m2.client_id = ${clientId}+ LIMIT 1+ )+ )+ )+ )`,+ );+ }+ await db+ .update(sessions)+ .set({ listPreview: preview, listPreviewRole: role })+ .where(and(...conds));+}++export async function invalidateSessionListMessageCount(sessionId: string): Promise<void> {+ const db = getDbClient().drizzle;+ await db.update(sessions).set({ listMessageCount: null }).where(eq(sessions.id, sessionId));+}++export async function invalidateSessionListPreview(sessionId: string): Promise<void> {+ await persistSessionListPreview(sessionId, null, null);+}++export async function persistSessionListMessageCount(+ sessionId: string,+ count: number,+): Promise<void> {+ const db = getDbClient().drizzle;+ await db+ .update(sessions)+ .set({ listMessageCount: Math.max(0, Math.floor(count)) })+ .where(eq(sessions.id, sessionId));+}++/** 一次 RPC 回填整页 list 投影。空数组是 no-op。 */+export async function persistSessionListProjectionBatch(+ items: readonly SessionListProjectionBackfillItem[],+): Promise<void> {+ if (items.length === 0) return;+ await getDbClient().exec(SESSION_LIST_PROJECTION_BACKFILL_SQL, [+ serializeSessionListProjectionBackfill(items),+ ]);+}diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex fa2475bb72..341c02c15b 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -80,6 +80,14 @@ export function tx(db: Database.Database, args: unknown): unknown {return sessionAgentSwitchFallback(db, txArgs);case 'context.rebuild':return contextRebuild(db, txArgs);+ case 'message.insert':+ return messageInsert(db, txArgs);+ case 'message.updateContent':+ return messageUpdateContent(db, txArgs);+ case 'message.leaseMutate':+ return messageLeaseMutate(db, txArgs);+ case 'message.rewindUserAfterClear':+ return messageRewindUserAfterClear(db, txArgs);case 'message.delete':return messageDelete(db, txArgs);case 'im.deleteBindings':@@ -236,7 +244,7 @@ function contextRebuild(db: Database.Database, args: unknown): void {const transaction = db.transaction(() => {const sessionResult = db.prepare(- 'UPDATE sessions SET sdk_session_id = NULL, updated_at = ? WHERE id = ? AND ifnull(cleared_at, -1) = ifnull(?, -1)',+ 'UPDATE sessions SET sdk_session_id = NULL, updated_at = ?, list_message_count = NULL WHERE id = ? AND ifnull(cleared_at, -1) = ifnull(?, -1)',).run(updatedAt, sessionId, expectedClearedAt);if (sessionResult.changes !== 1) {@@ -253,6 +261,175 @@ function contextRebuild(db: Database.Database, args: unknown): void {transaction();}+function messageInsert(db: Database.Database, args: unknown): { changes: number } {+ const payload = asRecord(args, 'message.insert args');+ const sessionId = expectString(payload.sessionId, 'sessionId');+ const id = expectString(payload.id, 'id');+ const clientId = expectString(payload.clientId, 'clientId');+ const role = expectString(payload.role, 'role');+ const content = expectString(payload.content, 'content');+ const toolUseId = nullableString(payload.toolUseId);+ const agentMeta = nullableString(payload.agentMeta);+ const agentKind = nullableString(payload.agentKind);+ const createdAt = expectNumber(payload.createdAt, 'createdAt');+ const guarded = payload.guarded === true;+ const expected =+ payload.expectedClearBoundaryMs === undefined || payload.expectedClearBoundaryMs === null+ ? null+ : expectNumber(payload.expectedClearBoundaryMs, 'expectedClearBoundaryMs');+ const transaction = db.transaction(() => {+ let changes = 0;+ if (guarded) {+ changes = db+ .prepare(+ `INSERT INTO messages (+ id, client_id, session_id, role, content, tool_use_id,+ agent_meta, agent_kind, created_at+ )+ SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?+ FROM sessions AS s+ WHERE s.id = ?+ AND COALESCE(s.cleared_at, -1) = COALESCE(?, -1)+ ON CONFLICT(session_id, client_id) DO NOTHING`,+ )+ .run(+ id,+ clientId,+ sessionId,+ role,+ content,+ toolUseId,+ agentMeta,+ agentKind,+ createdAt,+ sessionId,+ expected,+ ).changes;+ } else {+ changes = db+ .prepare(+ `INSERT INTO messages (+ id, client_id, session_id, role, content, tool_use_id,+ agent_meta, agent_kind, created_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ )+ .run(id, clientId, sessionId, role, content, toolUseId, agentMeta, agentKind, createdAt)+ .changes;+ }+ if (changes > 0) {+ if (role === 'user' || role === 'assistant') {+ db.prepare(+ 'UPDATE sessions SET list_preview = NULL, list_preview_role = NULL, list_message_count = NULL WHERE id = ?',+ ).run(sessionId);+ } else {+ db.prepare('UPDATE sessions SET list_message_count = NULL WHERE id = ?').run(sessionId);+ }+ }+ return { changes };+ });+ return transaction();+}++function messageUpdateContent(db: Database.Database, args: unknown): { changes: number } {+ const payload = asRecord(args, 'message.updateContent args');+ const sessionId = expectString(payload.sessionId, 'sessionId');+ const clientId = expectString(payload.clientId, 'clientId');+ const content = expectString(payload.content, 'content');+ const transaction = db.transaction(() => {+ const changes = db+ .prepare('UPDATE messages SET content = ? WHERE session_id = ? AND client_id = ?')+ .run(content, sessionId, clientId).changes;+ if (changes > 0) {+ const row = db+ .prepare(+ 'SELECT role, rewind_at FROM messages WHERE session_id = ? AND client_id = ? LIMIT 1',+ )+ .get(sessionId, clientId) as { role: string; rewind_at: number | null } | undefined;+ if (row && row.rewind_at == null && (row.role === 'user' || row.role === 'assistant')) {+ db.prepare(+ 'UPDATE sessions SET list_preview = NULL, list_preview_role = NULL WHERE id = ?',+ ).run(sessionId);+ }+ }+ return { changes };+ });+ return transaction();+}++function messageLeaseMutate(db: Database.Database, args: unknown): { changes: number } {+ const payload = asRecord(args, 'message.leaseMutate args');+ const op = expectString(payload.op, 'op');+ const sessionId = expectString(payload.sessionId, 'sessionId');+ const clientId = expectString(payload.clientId, 'clientId');+ const transaction = db.transaction(() => {+ let changes = 0;+ if (op === 'insert') {+ changes = db+ .prepare(+ `INSERT INTO messages (+ id, client_id, session_id, role, content, agent_meta, created_at, rewind_at+ ) VALUES (?, ?, ?, 'assistant', ?, ?, ?, ?)+ ON CONFLICT(session_id, client_id) DO NOTHING`,+ )+ .run(+ expectString(payload.id, 'id'),+ clientId,+ sessionId,+ expectString(payload.content, 'content'),+ nullableString(payload.agentMeta),+ expectNumber(payload.createdAt, 'createdAt'),+ expectNumber(payload.createdAt, 'createdAt'),+ ).changes;+ } else if (op === 'deleteByContent') {+ changes = db+ .prepare('DELETE FROM messages WHERE session_id = ? AND client_id = ? AND content = ?')+ .run(sessionId, clientId, expectString(payload.content, 'content')).changes;+ } else if (op === 'deleteById') {+ changes = db+ .prepare('DELETE FROM messages WHERE id = ? AND session_id = ? AND client_id = ?')+ .run(expectString(payload.id, 'id'), sessionId, clientId).changes;+ } else {+ throw Object.assign(new Error(`unknown message.leaseMutate op: ${op}`), {+ code: 'INVALID_ARGS',+ });+ }+ if (changes > 0) {+ db.prepare('UPDATE sessions SET list_message_count = NULL WHERE id = ?').run(sessionId);+ }+ return { changes };+ });+ return transaction();+}++function messageRewindUserAfterClear(+ db: Database.Database,+ args: unknown,+): { changes: number } {+ const payload = asRecord(args, 'message.rewindUserAfterClear args');+ const sessionId = expectString(payload.sessionId, 'sessionId');+ const clientId = expectString(payload.clientId, 'clientId');+ const rewoundAt = expectNumber(payload.rewoundAt, 'rewoundAt');+ const transaction = db.transaction(() => {+ const changes = db+ .prepare(+ `UPDATE messages+ SET rewind_at = ?+ WHERE session_id = ?+ AND client_id = ?+ AND role = 'user'+ AND rewind_at IS NULL`,+ )+ .run(rewoundAt, sessionId, clientId).changes;+ if (changes > 0) {+ db.prepare(+ 'UPDATE sessions SET list_preview = NULL, list_preview_role = NULL WHERE id = ?',+ ).run(sessionId);+ }+ return { changes };+ });+ return transaction();+}+/** 一轮消息内容清除 + 原生上下文失效 + 隐藏重建标记,三者同成同败。 */function messageDelete(db: Database.Database,@@ -429,7 +606,7 @@ function messageDelete(}}const sessionResult = db.prepare(- 'UPDATE sessions SET sdk_session_id = NULL, updated_at = ? WHERE id = ?',+ 'UPDATE sessions SET sdk_session_id = NULL, updated_at = ?, list_preview = NULL, list_preview_role = NULL, list_message_count = NULL WHERE id = ?',).run(updatedAt, sessionId);if (sessionResult.changes !== 1) {throw Object.assign(new Error(`Session 不存在: ${sessionId}`), { code: 'NOT_FOUND' });@@ -596,6 +773,12 @@ function sessionsSetStatus(db: Database.Database, args: unknown): Array<{}>;}+function invalidateSessionListProjection(db: Database.Database, sessionId: string): void {+ db.prepare(+ 'UPDATE sessions SET list_preview = NULL, list_preview_role = NULL, list_message_count = NULL WHERE id = ?',+ ).run(sessionId);+}+function codexImportMessages(db: Database.Database, args: unknown): { changed: number } {const payload = asRecord(args, 'codex.importMessages args');const sessionId = expectString(payload.sessionId, 'sessionId');@@ -654,6 +837,7 @@ function codexImportMessages(db: Database.Database, args: unknown): { changed: ncreatedAt,}).changes;}+ if (changed > 0) invalidateSessionListProjection(db, sessionId);return changed;});return { changed: transaction() as number };@@ -704,6 +888,7 @@ function claudeImportMessages(db: Database.Database, args: unknown): { changed:createdAt: expectNumber(row.createdAt, 'row.createdAt'),}).changes;}+ if (changed > 0) invalidateSessionListProjection(db, sessionId);return changed;});return { changed: transaction() as number };@@ -797,14 +982,16 @@ function rewindCommit(db: Database.Database, args: unknown): void {db.prepare(`UPDATE sessionsSET user_send_at = ?, updated_at = ?, context_tokens = 0, context_window = 0,- codex_plan_json = NULL, sdk_session_id = ?+ codex_plan_json = NULL, sdk_session_id = ?,+ list_preview = NULL, list_preview_role = NULLWHERE id = ?`,).run(now, now, sdkSessionId, sessionId);} else {db.prepare(`UPDATE sessionsSET user_send_at = ?, updated_at = ?, context_tokens = 0, context_window = 0,- codex_plan_json = NULL+ codex_plan_json = NULL,+ list_preview = NULL, list_preview_role = NULLWHERE id = ?`,).run(now, now, sessionId);}@@ -1008,7 +1195,8 @@ function sessionTreeRehydrate(}db.prepare(`UPDATE sessions- SET cleared_at = NULL, context_tokens = ?, context_window = ?, updated_at = ?+ SET cleared_at = NULL, context_tokens = ?, context_window = ?, updated_at = ?,+ list_preview = NULL, list_preview_role = NULL, list_message_count = NULLWHERE id = ?`,).run(contextTokens, contextWindow, now, sessionId);return hiddenClientIds;diff --git a/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.tsindex 24173e26b5..1287971284 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts@@ -2,14 +2,9 @@ import { readFileSync } from 'node:fs';import { resolve } from 'node:path';import { describe, expect, it, vi } from 'vitest';-import {- performMessageDeletion,- type MessageDeleteHandlerDeps,-} from '../messageDeleteHandler';+import { performMessageDeletion, type MessageDeleteHandlerDeps } from '../messageDeleteHandler';-function makeDeps(- overrides: Partial<MessageDeleteHandlerDeps> = {},-): MessageDeleteHandlerDeps {+function makeDeps(overrides: Partial<MessageDeleteHandlerDeps> = {}): MessageDeleteHandlerDeps {return {getSessionRow: vi.fn(async () => ({ status: 'active', agentKind: 'cc' })),getMessage: vi.fn(async () => ({@@ -49,7 +44,12 @@ describe('performMessageDeletion', () => {source.indexOf('export function broadcastMessageDeleted'),);- expect(deletionBlock).toContain('preview = await latestVisiblePreview(sessionId);');+ expect(deletionBlock).toContain('const latest = await latestVisiblePreviewRow(sessionId);');+ expect(deletionBlock).toContain(+ 'preview = extractMessagePreview(latest?.content, latest?.role);',+ );+ expect(deletionBlock).toContain('await persistSessionListPreview(');+ expect(deletionBlock).toContain('latest?.createdAt');expect(deletionBlock).not.toContain('.where(eq(messages.sessionId, sessionId))');});@@ -102,10 +102,12 @@ describe('performMessageDeletion', () => {it('closes the old native session and rebuilds handoff from history without the target', async () => {const deps = makeDeps();- await expect(performMessageDeletion(deps, {- sessionId: 's1',- clientId: 'target',- })).resolves.toEqual({+ await expect(+ performMessageDeletion(deps, {+ sessionId: 's1',+ clientId: 'target',+ }),+ ).resolves.toEqual({sessionId: 's1',clientId: 'target',clientIds: ['target'],@@ -148,25 +150,27 @@ describe('performMessageDeletion', () => {it('recomputes the deletion range and handoff after queued records become durable', async () => {let drained = false;const deps = makeDeps({- getMessage: vi.fn(async () => drained- ? {- id: 'final-row',- role: 'assistant' as const,- deletedClientIds: ['progress', 'late-result', 'final'],- subagentTurnWindow: {- startedAtInclusive: 100,- startedAtExclusive: 700,- },- }- : {- id: 'final-row',- role: 'assistant' as const,- deletedClientIds: ['progress', 'final'],- subagentTurnWindow: {- startedAtInclusive: 100,- startedAtExclusive: 600,+ getMessage: vi.fn(async () =>+ drained+ ? {+ id: 'final-row',+ role: 'assistant' as const,+ deletedClientIds: ['progress', 'late-result', 'final'],+ subagentTurnWindow: {+ startedAtInclusive: 100,+ startedAtExclusive: 700,+ },+ }+ : {+ id: 'final-row',+ role: 'assistant' as const,+ deletedClientIds: ['progress', 'final'],+ subagentTurnWindow: {+ startedAtInclusive: 100,+ startedAtExclusive: 600,+ },},- }),+ ),drainPersistQueue: vi.fn(async () => {drained = true;}),@@ -227,10 +231,12 @@ describe('performMessageDeletion', () => {]),});- await expect(performMessageDeletion(deps, {- sessionId: 's1',- clientId: 'final',- })).resolves.toEqual({+ await expect(+ performMessageDeletion(deps, {+ sessionId: 's1',+ clientId: 'final',+ }),+ ).resolves.toEqual({sessionId: 's1',clientId: 'final',clientIds: ['progress', 'thinking', 'auto-resume', 'tool', 'final'],@@ -260,10 +266,12 @@ describe('performMessageDeletion', () => {getLiveSession: vi.fn(() => ({ isTurnRunning: () => true })),});- await expect(performMessageDeletion(deps, {- sessionId: 's1',- clientId: 'target',- })).rejects.toThrow('SESSION_RUNNING');+ await expect(+ performMessageDeletion(deps, {+ sessionId: 's1',+ clientId: 'target',+ }),+ ).rejects.toThrow('SESSION_RUNNING');expect(deps.listMessagesForContext).not.toHaveBeenCalled();expect(deps.closeSession).not.toHaveBeenCalled();expect(deps.commitDeletion).not.toHaveBeenCalled();@@ -274,10 +282,12 @@ describe('performMessageDeletion', () => {hasBackgroundActivity: vi.fn(() => true),});- await expect(performMessageDeletion(deps, {- sessionId: 's1',- clientId: 'target',- })).rejects.toThrow('SESSION_RUNNING');+ await expect(+ performMessageDeletion(deps, {+ sessionId: 's1',+ clientId: 'target',+ }),+ ).rejects.toThrow('SESSION_RUNNING');expect(deps.listMessagesForContext).not.toHaveBeenCalled();expect(deps.closeSession).not.toHaveBeenCalled();expect(deps.commitDeletion).not.toHaveBeenCalled();@@ -289,10 +299,12 @@ describe('performMessageDeletion', () => {hasBackgroundActivity: vi.fn(() => ++reads > 1),});- await expect(performMessageDeletion(deps, {- sessionId: 's1',- clientId: 'target',- })).rejects.toThrow('SESSION_RUNNING');+ await expect(+ performMessageDeletion(deps, {+ sessionId: 's1',+ clientId: 'target',+ }),+ ).rejects.toThrow('SESSION_RUNNING');expect(deps.listMessagesForContext).not.toHaveBeenCalled();expect(deps.closeSession).not.toHaveBeenCalled();expect(deps.commitDeletion).not.toHaveBeenCalled();@@ -303,10 +315,12 @@ describe('performMessageDeletion', () => {getMessage: vi.fn(async () => null),});- await expect(performMessageDeletion(deps, {- sessionId: 's1',- clientId: 'missing',- })).rejects.toThrow('NOT_FOUND');+ await expect(+ performMessageDeletion(deps, {+ sessionId: 's1',+ clientId: 'missing',+ }),+ ).rejects.toThrow('NOT_FOUND');expect(deps.listMessagesForContext).not.toHaveBeenCalled();expect(deps.commitDeletion).not.toHaveBeenCalled();});@@ -318,10 +332,12 @@ describe('performMessageDeletion', () => {]),});- await expect(performMessageDeletion(deps, {- sessionId: 's1',- clientId: 'target',- })).resolves.toEqual({+ await expect(+ performMessageDeletion(deps, {+ sessionId: 's1',+ clientId: 'target',+ }),+ ).resolves.toEqual({sessionId: 's1',clientId: 'target',clientIds: ['target'],diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnLease.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnLease.test.tsindex da7af96444..c31a5f36dd 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnLease.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnLease.test.ts@@ -6,6 +6,7 @@ import Database from 'better-sqlite3';import { afterEach, describe, expect, it } from 'vitest';import type { DbClient } from '../../localDb/client/DbClient.js';+import { tx as runDbTx } from '../../localDb/worker/opHandlers/tx.js';import {readPersistedSessionTurnLeases,refreshSessionTurnLeaseOwner,@@ -17,10 +18,11 @@ import {tryAcquireSessionTurnLease,} from '../sessionTurnLease.js';-function asLeaseClient(db: Database.Database): Pick<DbClient, 'exec' | 'query'> {+function asLeaseClient(db: Database.Database): Pick<DbClient, 'exec' | 'query' | 'tx'> {return {exec: async (sql, params = []) => db.prepare(sql).run(...params),query: async <T>(sql: string, params: unknown[] = []) => db.prepare(sql).all(...params) as T[],+ tx: async (name: string, args: unknown) => runDbTx(db, { name, args }) as never,};}@@ -41,7 +43,10 @@ describe('shared-process session turn lease', () => {id TEXT PRIMARY KEY,status TEXT NOT NULL,active_turn_started_at INTEGER,- last_turn_ended_at INTEGER+ last_turn_ended_at INTEGER,+ list_preview TEXT,+ list_preview_role TEXT,+ list_message_count INTEGER);CREATE TABLE messages (id TEXT PRIMARY KEY,@@ -137,6 +142,74 @@ describe('shared-process session turn lease', () => {]);});+ it('invalidates list_message_count when a lease row is inserted or deleted, not on no-op', async () => {+ const { first, raw } = setup();+ const owner = { instanceId: 'first', processId: 101 };+ const seedCount = (count: number) => {+ raw+ .prepare(+ 'UPDATE sessions SET list_preview = ?, list_preview_role = ?, list_message_count = ? WHERE id = ?',+ )+ .run('keep me', 'user', count, 'source-1');+ };+ const readProjection = () =>+ raw+ .prepare(+ 'SELECT list_preview, list_preview_role, list_message_count FROM sessions WHERE id = ?',+ )+ .get('source-1');++ seedCount(7);+ await expect(+ tryAcquireSessionTurnLease(first, {+ sessionId: 'source-1',+ turnId: 'turn-1',+ owner,+ createdAt: 1,+ }),+ ).resolves.toBe(true);+ expect(readProjection()).toEqual({+ list_preview: 'keep me',+ list_preview_role: 'user',+ list_message_count: null,+ });++ seedCount(8);+ await expect(+ tryAcquireSessionTurnLease(first, {+ sessionId: 'source-1',+ turnId: 'turn-1b',+ owner,+ createdAt: 2,+ }),+ ).resolves.toBe(false);+ expect(readProjection()).toEqual({+ list_preview: 'keep me',+ list_preview_role: 'user',+ list_message_count: 8,+ });++ seedCount(9);+ await expect(+ releaseSessionTurnLease(first, { sessionId: 'source-1', turnId: 'turn-1', owner }),+ ).resolves.toBe(true);+ expect(readProjection()).toEqual({+ list_preview: 'keep me',+ list_preview_role: 'user',+ list_message_count: null,+ });++ seedCount(10);+ await expect(+ releaseSessionTurnLease(first, { sessionId: 'source-1', turnId: 'turn-1', owner }),+ ).resolves.toBe(false);+ expect(readProjection()).toEqual({+ list_preview: 'keep me',+ list_preview_role: 'user',+ list_message_count: 10,+ });+ });+it('uses exact CAS release so a delayed old end cannot delete a successor', async () => {const { first } = setup();const owner = { instanceId: 'first', processId: 101 };diff --git a/apps/desktop/src/main/maker-ipc/sessionTurnLease.ts b/apps/desktop/src/main/maker-ipc/sessionTurnLease.tsindex efbe073d76..d3b9a887c9 100644--- a/apps/desktop/src/main/maker-ipc/sessionTurnLease.ts+++ b/apps/desktop/src/main/maker-ipc/sessionTurnLease.ts@@ -71,7 +71,7 @@ export class SilentStopTurnLeaseGate {}}-type SessionTurnLeaseDb = Pick<DbClient, 'exec' | 'query'>;+type SessionTurnLeaseDb = Pick<DbClient, 'exec' | 'query' | 'tx'>;function sessionTurnLeaseAgentMeta(lease: SessionTurnLease): string {return JSON.stringify({ sessionTurnLease: lease });@@ -128,21 +128,15 @@ export async function tryAcquireSessionTurnLease(},): Promise<boolean> {const lease: SessionTurnLease = { version: 1, turnId: input.turnId, owner: input.owner };- const result = await dbClient.exec(- `INSERT INTO messages (- id, client_id, session_id, role, content, agent_meta, created_at, rewind_at- ) VALUES (?, ?, ?, 'assistant', ?, ?, ?, ?)- ON CONFLICT(session_id, client_id) DO NOTHING`,- [- createId(),- sessionTurnLeaseClientId(input.owner),- input.sessionId,- sessionTurnLeaseToken(lease),- sessionTurnLeaseAgentMeta(lease),- input.createdAt,- input.createdAt,- ],- );+ const result = await dbClient.tx('message.leaseMutate', {+ op: 'insert',+ sessionId: input.sessionId,+ clientId: sessionTurnLeaseClientId(input.owner),+ id: createId(),+ content: sessionTurnLeaseToken(lease),+ agentMeta: sessionTurnLeaseAgentMeta(lease),+ createdAt: input.createdAt,+ });return result.changes === 1;}@@ -214,15 +208,16 @@ export async function refreshSessionTurnLeaseOwner(/** Delete only the exact turn that acquired the row; a delayed end cannot delete its successor. */export async function releaseSessionTurnLease(- dbClient: Pick<DbClient, 'exec'>,+ dbClient: Pick<DbClient, 'tx'>,input: { sessionId: string; turnId: string; owner: ReviewRunOwner },): Promise<boolean> {const lease: SessionTurnLease = { version: 1, turnId: input.turnId, owner: input.owner };- const result = await dbClient.exec(- `DELETE FROM messages- WHERE session_id = ? AND client_id = ? AND content = ?`,- [input.sessionId, sessionTurnLeaseClientId(input.owner), sessionTurnLeaseToken(lease)],- );+ const result = await dbClient.tx('message.leaseMutate', {+ op: 'deleteByContent',+ sessionId: input.sessionId,+ clientId: sessionTurnLeaseClientId(input.owner),+ content: sessionTurnLeaseToken(lease),+ });return result.changes === 1;}@@ -252,14 +247,15 @@ export async function readPersistedSessionTurnLeases(/** Remove a malformed row only while its immutable id still identifies the same lease row. */export async function discardInvalidSessionTurnLease(- dbClient: Pick<DbClient, 'exec'>,+ dbClient: Pick<DbClient, 'tx'>,row: Pick<PersistedSessionTurnLeaseRow, 'id' | 'clientId' | 'sessionId'>,): Promise<boolean> {- const result = await dbClient.exec(- `DELETE FROM messages- WHERE id = ? AND session_id = ? AND client_id = ?`,- [row.id, row.sessionId, row.clientId],- );+ const result = await dbClient.tx('message.leaseMutate', {+ op: 'deleteById',+ sessionId: row.sessionId,+ clientId: row.clientId,+ id: row.id,+ });return result.changes === 1;}diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewSourceLease.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewSourceLease.test.tsindex 4b8e12407e..562cfc9291 100644--- a/apps/desktop/src/main/reviewer/__tests__/reviewSourceLease.test.ts+++ b/apps/desktop/src/main/reviewer/__tests__/reviewSourceLease.test.ts@@ -6,6 +6,7 @@ import Database from 'better-sqlite3';import { afterEach, describe, expect, it } from 'vitest';import type { DbClient } from '../../localDb/client/DbClient.js';+import { tx as runDbTx } from '../../localDb/worker/opHandlers/tx.js';import {discardInvalidReviewSourceLease,readPersistedReviewSourceLease,@@ -14,10 +15,11 @@ import {tryAcquireReviewSourceLease,} from '../reviewSourceLease.js';-function asLeaseClient(db: Database.Database): Pick<DbClient, 'exec' | 'query'> {+function asLeaseClient(db: Database.Database): Pick<DbClient, 'exec' | 'query' | 'tx'> {return {exec: async (sql, params = []) => db.prepare(sql).run(...params),query: async <T>(sql: string, params: unknown[] = []) => db.prepare(sql).all(...params) as T[],+ tx: async (name: string, args: unknown) => runDbTx(db, { name, args }) as never,};}@@ -34,7 +36,13 @@ describe('Review source lease', () => {const first = new Database(dbPath);first.exec(`PRAGMA foreign_keys = ON;- CREATE TABLE sessions (id TEXT PRIMARY KEY, status TEXT NOT NULL);+ CREATE TABLE sessions (+ id TEXT PRIMARY KEY,+ status TEXT NOT NULL,+ list_preview TEXT,+ list_preview_role TEXT,+ list_message_count INTEGER+ );CREATE TABLE messages (id TEXT PRIMARY KEY,client_id TEXT NOT NULL,@@ -59,6 +67,87 @@ describe('Review source lease', () => {return { first: asLeaseClient(first), second: asLeaseClient(second), raw: first };}+ it('invalidates list_message_count when a lease row is inserted or deleted, not on no-op', async () => {+ const { first, second, raw } = setup();+ const owner = {+ instanceId: 'first',+ processId: 101,+ liveness: { version: 1 as const, port: 43101, token: 'first-owner-token' },+ };+ const other = { instanceId: 'second', processId: 202 };+ const seedCount = (count: number) => {+ raw+ .prepare(+ 'UPDATE sessions SET list_preview = ?, list_preview_role = ?, list_message_count = ? WHERE id = ?',+ )+ .run('keep me', 'user', count, 'source-1');+ };+ const readProjection = () =>+ raw+ .prepare(+ 'SELECT list_preview, list_preview_role, list_message_count FROM sessions WHERE id = ?',+ )+ .get('source-1');++ seedCount(7);+ await expect(+ tryAcquireReviewSourceLease(first, {+ sourceSessionId: 'source-1',+ runId: 'run-1',+ owner,+ createdAt: 1,+ }),+ ).resolves.toBe(true);+ expect(readProjection()).toEqual({+ list_preview: 'keep me',+ list_preview_role: 'user',+ list_message_count: null,+ });++ seedCount(8);+ await expect(+ tryAcquireReviewSourceLease(second, {+ sourceSessionId: 'source-1',+ runId: 'run-2',+ owner: other,+ createdAt: 2,+ }),+ ).resolves.toBe(false);+ expect(readProjection()).toEqual({+ list_preview: 'keep me',+ list_preview_role: 'user',+ list_message_count: 8,+ });++ seedCount(9);+ await expect(+ releaseReviewSourceLease(first, {+ sourceSessionId: 'source-1',+ runId: 'run-1',+ owner,+ }),+ ).resolves.toBe(true);+ expect(readProjection()).toEqual({+ list_preview: 'keep me',+ list_preview_role: 'user',+ list_message_count: null,+ });++ seedCount(10);+ await expect(+ releaseReviewSourceLease(first, {+ sourceSessionId: 'source-1',+ runId: 'run-1',+ owner,+ }),+ ).resolves.toBe(false);+ expect(readProjection()).toEqual({+ list_preview: 'keep me',+ list_preview_role: 'user',+ list_message_count: 10,+ });+ });+it('admits exactly one shared-database owner and allows a successor after CAS release', async () => {const { first, second, raw } = setup();const firstOwner = {diff --git a/apps/desktop/src/main/reviewer/reviewSourceLease.ts b/apps/desktop/src/main/reviewer/reviewSourceLease.tsindex f8ffa612b2..f1e060ebb1 100644--- a/apps/desktop/src/main/reviewer/reviewSourceLease.ts+++ b/apps/desktop/src/main/reviewer/reviewSourceLease.ts@@ -63,7 +63,7 @@ export function readReviewSourceLeaseFromAgentMeta(value: unknown): ReviewSource* A rewound assistant row stays out of history, FTS, prompts, and Review context.*/export async function tryAcquireReviewSourceLease(- dbClient: Pick<DbClient, 'exec'>,+ dbClient: Pick<DbClient, 'tx'>,input: {sourceSessionId: string;runId: string;@@ -76,27 +76,21 @@ export async function tryAcquireReviewSourceLease(runId: input.runId,owner: input.owner,};- const result = await dbClient.exec(- `INSERT INTO messages (- id, client_id, session_id, role, content, agent_meta, created_at, rewind_at- ) VALUES (?, ?, ?, 'assistant', ?, ?, ?, ?)- ON CONFLICT(session_id, client_id) DO NOTHING`,- [- createId(),- REVIEW_SOURCE_LEASE_CLIENT_ID,- input.sourceSessionId,- reviewSourceLeaseToken(lease),- reviewSourceLeaseAgentMeta(lease),- input.createdAt,- input.createdAt,- ],- );+ const result = await dbClient.tx('message.leaseMutate', {+ op: 'insert',+ sessionId: input.sourceSessionId,+ clientId: REVIEW_SOURCE_LEASE_CLIENT_ID,+ id: createId(),+ content: reviewSourceLeaseToken(lease),+ agentMeta: reviewSourceLeaseAgentMeta(lease),+ createdAt: input.createdAt,+ });return result.changes === 1;}/** Delete only the exact lease acquired by this run, never a newer successor. */export async function releaseReviewSourceLease(- dbClient: Pick<DbClient, 'exec'>,+ dbClient: Pick<DbClient, 'tx'>,input: {sourceSessionId: string;runId: string;@@ -108,11 +102,12 @@ export async function releaseReviewSourceLease(runId: input.runId,owner: input.owner,};- const result = await dbClient.exec(- `DELETE FROM messages- WHERE session_id = ? AND client_id = ? AND content = ?`,- [input.sourceSessionId, REVIEW_SOURCE_LEASE_CLIENT_ID, reviewSourceLeaseToken(lease)],- );+ const result = await dbClient.tx('message.leaseMutate', {+ op: 'deleteByContent',+ sessionId: input.sourceSessionId,+ clientId: REVIEW_SOURCE_LEASE_CLIENT_ID,+ content: reviewSourceLeaseToken(lease),+ });return result.changes === 1;}@@ -144,13 +139,14 @@ export async function readPersistedReviewSourceLease(/** Remove a malformed legacy/corrupt row only if its immutable id still matches. */export async function discardInvalidReviewSourceLease(- dbClient: Pick<DbClient, 'exec'>,+ dbClient: Pick<DbClient, 'tx'>,row: Pick<PersistedReviewSourceLeaseRow, 'id' | 'sourceSessionId'>,): Promise<boolean> {- const result = await dbClient.exec(- `DELETE FROM messages- WHERE id = ? AND session_id = ? AND client_id = ?`,- [row.id, row.sourceSessionId, REVIEW_SOURCE_LEASE_CLIENT_ID],- );+ const result = await dbClient.tx('message.leaseMutate', {+ op: 'deleteById',+ sessionId: row.sourceSessionId,+ clientId: REVIEW_SOURCE_LEASE_CLIENT_ID,+ id: row.id,+ });return result.changes === 1;}diff --git a/packages/maker-shared/src/__tests__/sessionList.test.ts b/packages/maker-shared/src/__tests__/sessionList.test.tsindex e943bce697..79f408989e 100644--- a/packages/maker-shared/src/__tests__/sessionList.test.ts+++ b/packages/maker-shared/src/__tests__/sessionList.test.ts@@ -209,6 +209,24 @@ describe('sessionList', () => {});});+ it('caps oversized message counts at 1000+', () => {+ const item = toRemoteSessionListItem(session('s-big', {+ title: '大库',+ workingDir: null,+ workspaceKind: 'dialogue',+ agentKind: 'codex',+ model: 'gpt-5.4',+ userSendAt: '2026-01-01T00:05:00.000Z',+ _count: { messages: 1001 },+ }), new Date('2026-01-01T00:10:00.000Z').getTime());++ expect(item).toMatchObject({+ detail: '活跃 · 5 分钟前 · 1000+ 条消息',+ messagePreview: null,+ lastActivityAt: '2026-01-01T00:05:00.000Z',+ });+ });+it('labels pi sessions as Pi instead of falling back to Claude Code', () => {// codex review 回归:共享标签映射二元化会让桌面创建的 Pi 会话在手机端显示成 Claude Code。const item = toRemoteSessionListItem(session('s-pi', {diff --git a/packages/maker-shared/src/sessionList.ts b/packages/maker-shared/src/sessionList.tsindex b473dab30d..fb188c42de 100644--- a/packages/maker-shared/src/sessionList.ts+++ b/packages/maker-shared/src/sessionList.ts@@ -940,8 +940,12 @@ function sessionStatusLabel(status: RemoteSession['status']): string {return '已删除';}+/** 与 Desktop sessions:list 封顶计数对齐:达到该值即显示 1000+。 */+export const SESSION_LIST_MESSAGE_COUNT_CAP = 1001;+function messageCountLabel(count: number | undefined): string | null {if (typeof count !== 'number') return null;+ if (count >= SESSION_LIST_MESSAGE_COUNT_CAP) return '1000+ 条消息';return `${count} 条消息`;}