Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(im): Telegram 群消息全文入库与游标持久化 (#1945)

Chris Zhangf9b099f5e15a
diff --git a/apps/desktop/drizzle/0086_orange_surge.sql b/apps/desktop/drizzle/0086_orange_surge.sql
new file mode 100644
index 0000000000..1b31826bf3
--- /dev/null
+++ b/apps/desktop/drizzle/0086_orange_surge.sql
@@ -0,0 +1,7 @@
+CREATE TABLE IF NOT EXISTS `hook_group_context_cursors` (
+ `provider` text NOT NULL,
+ `cursor_key` text NOT NULL,
+ `cursor_id` integer NOT NULL,
+ `updated_at` integer NOT NULL,
+ PRIMARY KEY(`provider`, `cursor_key`)
+);
diff --git a/apps/desktop/drizzle/meta/0086_snapshot.json b/apps/desktop/drizzle/meta/0086_snapshot.json
new file mode 100644
index 0000000000..cc92f985e6
--- /dev/null
+++ b/apps/desktop/drizzle/meta/0086_snapshot.json
@@ -0,0 +1,3890 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "cb0166d9-e42c-4135-8658-f291594a7c81",
+ "prevId": "daddbf8c-2d5f-48e4-8f12-f760511b47fa",
+ "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": {},
+ "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_messages": {
+ "name": "hook_group_messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "thread_id": {
+ "name": "thread_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_name": {
+ "name": "chat_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "author": {
+ "name": "author",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_bot": {
+ "name": "is_bot",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "file_names": {
+ "name": "file_names",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "hook_group_messages_msg_idx": {
+ "name": "hook_group_messages_msg_idx",
+ "columns": [
+ "provider",
+ "chat_id",
+ "thread_id",
+ "message_id"
+ ],
+ "isUnique": true
+ },
+ "hook_group_messages_window_idx": {
+ "name": "hook_group_messages_window_idx",
+ "columns": [
+ "provider",
+ "chat_id",
+ "thread_id",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "im_bindings": {
+ "name": "im_bindings",
+ "columns": {
+ "channel": {
+ "name": "channel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_context_id": {
+ "name": "bot_context_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scope_key": {
+ "name": "scope_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "target_session_id": {
+ "name": "target_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attached_at": {
+ "name": "attached_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attached_via_card_message_id": {
+ "name": "attached_via_card_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_im_bindings_target": {
+ "name": "idx_im_bindings_target",
+ "columns": [
+ "target_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "im_bindings_target_session_id_sessions_id_fk": {
+ "name": "im_bindings_target_session_id_sessions_id_fk",
+ "tableFrom": "im_bindings",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "target_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "im_bindings_channel_bot_context_id_user_id_scope_key_pk": {
+ "columns": [
+ "channel",
+ "bot_context_id",
+ "user_id",
+ "scope_key"
+ ],
+ "name": "im_bindings_channel_bot_context_id_user_id_scope_key_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "media_blobs": {
+ "name": "media_blobs",
+ "columns": {
+ "hash": {
+ "name": "hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ext": {
+ "name": "ext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mime_type": {
+ "name": "mime_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bytes": {
+ "name": "bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_cache": {
+ "name": "is_cache",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_access_at": {
+ "name": "last_access_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "media_refs": {
+ "name": "media_refs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "hash": {
+ "name": "hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ref_kind": {
+ "name": "ref_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ref_id": {
+ "name": "ref_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "origin_session_id": {
+ "name": "origin_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "origin_kind": {
+ "name": "origin_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "origin_id": {
+ "name": "origin_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "media_refs_hash_idx": {
+ "name": "media_refs_hash_idx",
+ "columns": [
+ "hash"
+ ],
+ "isUnique": false
+ },
+ "media_refs_ref_idx": {
+ "name": "media_refs_ref_idx",
+ "columns": [
+ "ref_kind",
+ "ref_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "media_refs_hash_media_blobs_hash_fk": {
+ "name": "media_refs_hash_media_blobs_hash_fk",
+ "tableFrom": "media_refs",
+ "tableTo": "media_blobs",
+ "columnsFrom": [
+ "hash"
+ ],
+ "columnsTo": [
+ "hash"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "messages": {
+ "name": "messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_use_id": {
+ "name": "tool_use_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_meta": {
+ "name": "agent_meta",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "rewind_at": {
+ "name": "rewind_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_messages_session_client": {
+ "name": "uniq_messages_session_client",
+ "columns": [
+ "session_id",
+ "client_id"
+ ],
+ "isUnique": true
+ },
+ "idx_messages_session_created": {
+ "name": "idx_messages_session_created",
+ "columns": [
+ "session_id",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "idx_messages_created_at": {
+ "name": "idx_messages_created_at",
+ "columns": [
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_messages_rewind_at": {
+ "name": "idx_messages_rewind_at",
+ "columns": [
+ "rewind_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "messages_session_id_sessions_id_fk": {
+ "name": "messages_session_id_sessions_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "migration_history": {
+ "name": "migration_history",
+ "columns": {
+ "seq": {
+ "name": "seq",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "file_name": {
+ "name": "file_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content_hash": {
+ "name": "content_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "applied_at": {
+ "name": "applied_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "migration_meta": {
+ "name": "migration_meta",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_teams": {
+ "name": "orca_teams",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "lead_session_id": {
+ "name": "lead_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_active_team_per_lead": {
+ "name": "uniq_active_team_per_lead",
+ "columns": [
+ "lead_session_id"
+ ],
+ "isUnique": true,
+ "where": "\"orca_teams\".\"status\" = 'active'"
+ },
+ "idx_orca_teams_status": {
+ "name": "idx_orca_teams_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_teams_lead_session_id_sessions_id_fk": {
+ "name": "orca_teams_lead_session_id_sessions_id_fk",
+ "tableFrom": "orca_teams",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "lead_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_worker_creation_reservations": {
+ "name": "orca_worker_creation_reservations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_orca_worker_creation_reservations_team_label": {
+ "name": "uniq_orca_worker_creation_reservations_team_label",
+ "columns": [
+ "team_id",
+ "lower(\"label\")"
+ ],
+ "isUnique": true
+ },
+ "idx_orca_worker_creation_reservations_expires_at": {
+ "name": "idx_orca_worker_creation_reservations_expires_at",
+ "columns": [
+ "expires_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_worker_creation_reservations_team_id_orca_teams_id_fk": {
+ "name": "orca_worker_creation_reservations_team_id_orca_teams_id_fk",
+ "tableFrom": "orca_worker_creation_reservations",
+ "tableTo": "orca_teams",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_workers": {
+ "name": "orca_workers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'idle'"
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "worktree_branch": {
+ "name": "worktree_branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'developer'"
+ },
+ "focused": {
+ "name": "focused",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "idle_since": {
+ "name": "idle_since",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_orca_workers_session_id": {
+ "name": "uniq_orca_workers_session_id",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true
+ },
+ "uniq_orca_workers_team_label": {
+ "name": "uniq_orca_workers_team_label",
+ "columns": [
+ "team_id",
+ "lower(\"label\")"
+ ],
+ "isUnique": true
+ },
+ "uniq_orca_workers_focused_per_team": {
+ "name": "uniq_orca_workers_focused_per_team",
+ "columns": [
+ "team_id"
+ ],
+ "isUnique": true,
+ "where": "\"orca_workers\".\"focused\" = true"
+ },
+ "idx_orca_workers_team_id": {
+ "name": "idx_orca_workers_team_id",
+ "columns": [
+ "team_id"
+ ],
+ "isUnique": false
+ },
+ "idx_orca_workers_status": {
+ "name": "idx_orca_workers_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_workers_team_id_orca_teams_id_fk": {
+ "name": "orca_workers_team_id_orca_teams_id_fk",
+ "tableFrom": "orca_workers",
+ "tableTo": "orca_teams",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "orca_workers_session_id_sessions_id_fk": {
+ "name": "orca_workers_session_id_sessions_id_fk",
+ "tableFrom": "orca_workers",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_aliases": {
+ "name": "project_aliases",
+ "columns": {
+ "project_key": {
+ "name": "project_key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "alias": {
+ "name": "alias",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_project_aliases_updated_at": {
+ "name": "idx_project_aliases_updated_at",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_automation_consents": {
+ "name": "project_automation_consents",
+ "columns": {
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "consented_at": {
+ "name": "consented_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "config_hash": {
+ "name": "config_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "recent_workdirs": {
+ "name": "recent_workdirs",
+ "columns": {
+ "path": {
+ "name": "path",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_recent_workdirs_last_used_at": {
+ "name": "idx_recent_workdirs_last_used_at",
+ "columns": [
+ "last_used_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "right_sidebar_tabs": {
+ "name": "right_sidebar_tabs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "right_sidebar_tabs_session_idx": {
+ "name": "right_sidebar_tabs_session_idx",
+ "columns": [
+ "session_id",
+ "position"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "right_sidebar_tabs_session_id_sessions_id_fk": {
+ "name": "right_sidebar_tabs_session_id_sessions_id_fk",
+ "tableFrom": "right_sidebar_tabs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "schedule_runs": {
+ "name": "schedule_runs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "schedule_id": {
+ "name": "schedule_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fired_at": {
+ "name": "fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "error_msg": {
+ "name": "error_msg",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "estimated_value_usd": {
+ "name": "estimated_value_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_amount": {
+ "name": "cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "estimated_value_amount": {
+ "name": "estimated_value_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_currency": {
+ "name": "cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_is_approximate": {
+ "name": "cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "cost_attribution": {
+ "name": "cost_attribution",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'legacy'"
+ },
+ "result_text": {
+ "name": "result_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pre_run_hook_result": {
+ "name": "pre_run_hook_result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "read_at": {
+ "name": "read_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "heartbeat_at": {
+ "name": "heartbeat_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedule_runs_schedule": {
+ "name": "idx_schedule_runs_schedule",
+ "columns": [
+ "schedule_id",
+ "fired_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "schedule_runs_schedule_id_schedules_id_fk": {
+ "name": "schedule_runs_schedule_id_schedules_id_fk",
+ "tableFrom": "schedule_runs",
+ "tableTo": "schedules",
+ "columnsFrom": [
+ "schedule_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "schedule_runs_session_id_sessions_id_fk": {
+ "name": "schedule_runs_session_id_sessions_id_fk",
+ "tableFrom": "schedule_runs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "schedules": {
+ "name": "schedules",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "job_type": {
+ "name": "job_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'prompt'"
+ },
+ "job_config": {
+ "name": "job_config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "execution_mode": {
+ "name": "execution_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'agent'"
+ },
+ "script_config": {
+ "name": "script_config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'user'"
+ },
+ "project_config_id": {
+ "name": "project_config_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "legacy_session_fallback": {
+ "name": "legacy_session_fallback",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'cron'"
+ },
+ "cron_expr": {
+ "name": "cron_expr",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "recurring": {
+ "name": "recurring",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "manual": {
+ "name": "manual",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "interval_ms": {
+ "name": "interval_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "effort": {
+ "name": "effort",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fast_mode": {
+ "name": "fast_mode",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_kind": {
+ "name": "workspace_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'project'"
+ },
+ "use_worktree": {
+ "name": "use_worktree",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "target_session_id": {
+ "name": "target_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "persistent_session": {
+ "name": "persistent_session",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "silent_when_idle": {
+ "name": "silent_when_idle",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "pre_run_hook_command": {
+ "name": "pre_run_hook_command",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pre_run_hook_timeout_ms": {
+ "name": "pre_run_hook_timeout_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "skip_log_session_id": {
+ "name": "skip_log_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "notify_desktop": {
+ "name": "notify_desktop",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "notify_feishu": {
+ "name": "notify_feishu",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "notify_wecom_group": {
+ "name": "notify_wecom_group",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_fired_at": {
+ "name": "last_fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_finished_at": {
+ "name": "last_finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "next_fire_at": {
+ "name": "next_fire_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expire_at": {
+ "name": "expire_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedules_active_next": {
+ "name": "idx_schedules_active_next",
+ "columns": [
+ "status",
+ "next_fire_at"
+ ],
+ "isUnique": false
+ },
+ "idx_schedules_target_session": {
+ "name": "idx_schedules_target_session",
+ "columns": [
+ "target_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "schedules_target_session_id_sessions_id_fk": {
+ "name": "schedules_target_session_id_sessions_id_fk",
+ "tableFrom": "schedules",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "target_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "schedules_skip_log_session_id_sessions_id_fk": {
+ "name": "schedules_skip_log_session_id_sessions_id_fk",
+ "tableFrom": "schedules",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "skip_log_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_goals": {
+ "name": "session_goals",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "objective": {
+ "name": "objective",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "budget_tokens": {
+ "name": "budget_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "max_turns": {
+ "name": "max_turns",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "no_progress_limit": {
+ "name": "no_progress_limit",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "turns_used": {
+ "name": "turns_used",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "tokens_used": {
+ "name": "tokens_used",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "no_progress_streak": {
+ "name": "no_progress_streak",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "usage_reset_at": {
+ "name": "usage_reset_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_reason": {
+ "name": "last_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_session_goals_status": {
+ "name": "idx_session_goals_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_goals_session_id_sessions_id_fk": {
+ "name": "session_goals_session_id_sessions_id_fk",
+ "tableFrom": "session_goals",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_pr_refs": {
+ "name": "session_pr_refs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner": {
+ "name": "owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "repo": {
+ "name": "repo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "first_seen_at": {
+ "name": "first_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_session_pr_refs": {
+ "name": "uniq_session_pr_refs",
+ "columns": [
+ "session_id",
+ "owner",
+ "repo",
+ "pr_number"
+ ],
+ "isUnique": true
+ },
+ "idx_session_pr_refs_session_last_seen": {
+ "name": "idx_session_pr_refs_session_last_seen",
+ "columns": [
+ "session_id",
+ "last_seen_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_pr_refs_session_id_sessions_id_fk": {
+ "name": "session_pr_refs_session_id_sessions_id_fk",
+ "tableFrom": "session_pr_refs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'New Maker'"
+ },
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_kind": {
+ "name": "workspace_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'project'"
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'claude-sonnet-4-6'"
+ },
+ "effort": {
+ "name": "effort",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'high'"
+ },
+ "permission_mode": {
+ "name": "permission_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'ask'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "total_token_usage": {
+ "name": "total_token_usage",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_usd": {
+ "name": "total_cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_amount": {
+ "name": "total_cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_currency": {
+ "name": "total_cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "total_cost_is_approximate": {
+ "name": "total_cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "context_tokens": {
+ "name": "context_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "context_window": {
+ "name": "context_window",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "fast_mode": {
+ "name": "fast_mode",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "plan_mode_enabled": {
+ "name": "plan_mode_enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "cleared_at": {
+ "name": "cleared_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pinned_at": {
+ "name": "pinned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_send_at": {
+ "name": "user_send_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'cc'"
+ },
+ "orca_role": {
+ "name": "orca_role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "parent_session_id": {
+ "name": "parent_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "forked_at_message_id": {
+ "name": "forked_at_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "worktree_path": {
+ "name": "worktree_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'desktop'"
+ },
+ "feishu_open_id": {
+ "name": "feishu_open_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "feishu_bot_app_id": {
+ "name": "feishu_bot_app_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "im_bot_context_id": {
+ "name": "im_bot_context_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "im_user_id": {
+ "name": "im_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "used_project_context": {
+ "name": "used_project_context",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "codex_history_has_product_prompt": {
+ "name": "codex_history_has_product_prompt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "extra_dirs": {
+ "name": "extra_dirs",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "remote_host_id": {
+ "name": "remote_host_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "active_turn_started_at": {
+ "name": "active_turn_started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "active_turn_pid": {
+ "name": "active_turn_pid",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_turn_ended_at": {
+ "name": "last_turn_ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_sessions_updated_at": {
+ "name": "idx_sessions_updated_at",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_user_send_at": {
+ "name": "idx_sessions_user_send_at",
+ "columns": [
+ "user_send_at"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_sdk_session_id": {
+ "name": "idx_sessions_sdk_session_id",
+ "columns": [
+ "sdk_session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_workdir_created": {
+ "name": "idx_sessions_workdir_created",
+ "columns": [
+ "working_dir",
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_created_at": {
+ "name": "idx_sessions_created_at",
+ "columns": [
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_workspace_kind": {
+ "name": "idx_sessions_workspace_kind",
+ "columns": [
+ "workspace_kind"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_parent_session_id": {
+ "name": "idx_sessions_parent_session_id",
+ "columns": [
+ "parent_session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_orca_role": {
+ "name": "idx_sessions_orca_role",
+ "columns": [
+ "orca_role"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_worktree_path": {
+ "name": "idx_sessions_worktree_path",
+ "columns": [
+ "worktree_path"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_feishu_lookup": {
+ "name": "idx_sessions_feishu_lookup",
+ "columns": [
+ "source",
+ "feishu_bot_app_id",
+ "feishu_open_id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_im_lookup": {
+ "name": "idx_sessions_im_lookup",
+ "columns": [
+ "source",
+ "im_bot_context_id",
+ "im_user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "sessions_parent_session_id_sessions_id_fk": {
+ "name": "sessions_parent_session_id_sessions_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "parent_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "skill_usage_exposures": {
+ "name": "skill_usage_exposures",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "analyzer_version": {
+ "name": "analyzer_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'6'"
+ },
+ "raw_file_path": {
+ "name": "raw_file_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "raw_line_no": {
+ "name": "raw_line_no",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "skill_name": {
+ "name": "skill_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "skill_path": {
+ "name": "skill_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "skill_document_hash": {
+ "name": "skill_document_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "exposure_content_hash": {
+ "name": "exposure_content_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "document_hash_source": {
+ "name": "document_hash_source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_use_id": {
+ "name": "tool_use_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "seen_at": {
+ "name": "seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_call_count": {
+ "name": "tool_call_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "repeated_tool_call_count": {
+ "name": "repeated_tool_call_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "tool_error_count": {
+ "name": "tool_error_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "command_call_count": {
+ "name": "command_call_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "command_failure_count": {
+ "name": "command_failure_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ }
+ },
+ "indexes": {
+ "idx_skill_usage_exposures_skill_document_version": {
+ "name": "idx_skill_usage_exposures_skill_document_version",
+ "columns": [
+ "analyzer_version",
+ "skill_name",
+ "skill_document_hash"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_session": {
+ "name": "idx_skill_usage_exposures_session",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_raw_file": {
+ "name": "idx_skill_usage_exposures_raw_file",
+ "columns": [
+ "raw_file_path"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "skill_usage_exposures_raw_file_path_skill_usage_sources_raw_file_path_fk": {
+ "name": "skill_usage_exposures_raw_file_path_skill_usage_sources_raw_file_path_fk",
+ "tableFrom": "skill_usage_exposures",
+ "tableTo": "skill_usage_sources",
+ "columnsFrom": [
+ "raw_file_path"
+ ],
+ "columnsTo": [
+ "raw_file_path"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "skill_usage_sources": {
+ "name": "skill_usage_sources",
+ "columns": {
+ "raw_file_path": {
+ "name": "raw_file_path",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "analyzer_version": {
+ "name": "analyzer_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'6'"
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mtime_ms": {
+ "name": "mtime_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "size_bytes": {
+ "name": "size_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "last_scanned_at": {
+ "name": "last_scanned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'ok'"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_skill_usage_sources_session": {
+ "name": "idx_skill_usage_sources_session",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_sources_sdk_session": {
+ "name": "idx_skill_usage_sources_sdk_session",
+ "columns": [
+ "sdk_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "vec_table_meta": {
+ "name": "vec_table_meta",
+ "columns": {
+ "vec_table": {
+ "name": "vec_table",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "dim": {
+ "name": "dim",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "registered_at": {
+ "name": "registered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "notes": {
+ "name": "notes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_file_attachments": {
+ "name": "wechat_file_attachments",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "abs_path": {
+ "name": "abs_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "original_name": {
+ "name": "original_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mime_type": {
+ "name": "mime_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bytes": {
+ "name": "bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'staged'"
+ },
+ "promoted_at": {
+ "name": "promoted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_wechat_file_attachments_task": {
+ "name": "idx_wechat_file_attachments_task",
+ "columns": [
+ "binding_epoch",
+ "task_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "wechat_file_attachments_binding_epoch_wechat_sync_state_binding_epoch_fk": {
+ "name": "wechat_file_attachments_binding_epoch_wechat_sync_state_binding_epoch_fk",
+ "tableFrom": "wechat_file_attachments",
+ "tableTo": "wechat_sync_state",
+ "columnsFrom": [
+ "binding_epoch"
+ ],
+ "columnsTo": [
+ "binding_epoch"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wechat_file_attachments_task_id_wechat_inbox_id_fk": {
+ "name": "wechat_file_attachments_task_id_wechat_inbox_id_fk",
+ "tableFrom": "wechat_file_attachments",
+ "tableTo": "wechat_inbox",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wechat_file_attachments_session_id_sessions_id_fk": {
+ "name": "wechat_file_attachments_session_id_sessions_id_fk",
+ "tableFrom": "wechat_file_attachments",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_inbox": {
+ "name": "wechat_inbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "platform_message_id": {
+ "name": "platform_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "platform_seq": {
+ "name": "platform_seq",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "peer_id": {
+ "name": "peer_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "received_at": {
+ "name": "received_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "platform_created_at": {
+ "name": "platform_created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "lease_until": {
+ "name": "lease_until",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "conversation_epoch": {
+ "name": "conversation_epoch",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "payload_json": {
+ "name": "payload_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_nonce": {
+ "name": "context_nonce",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_ciphertext": {
+ "name": "context_ciphertext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_tag": {
+ "name": "context_tag",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "last_error_code": {
+ "name": "last_error_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_wechat_inbox_platform_message": {
+ "name": "uniq_wechat_inbox_platform_message",
+ "columns": [
+ "binding_epoch",
+ "platform_message_id"
+ ],
+ "isUnique": true
+ },
+ "idx_wechat_inbox_queue": {
+ "name": "idx_wechat_inbox_queue",
+ "columns": [
+ "binding_epoch",
+ "status",
+ "received_at"
+ ],
+ "isUnique": false
+ },
+ "idx_wechat_inbox_lease": {
+ "name": "idx_wechat_inbox_lease",
+ "columns": [
+ "binding_epoch",
+ "lease_until"
+ ],
+ "isUnique": false
+ },
+ "idx_wechat_inbox_conversation": {
+ "name": "idx_wechat_inbox_conversation",
+ "columns": [
+ "binding_epoch",
+ "peer_id",
+ "conversation_epoch"
+ ],
+ "isUnique": false
+ },
+ "uniq_wechat_inbox_running_session": {
+ "name": "uniq_wechat_inbox_running_session",
+ "columns": [
+ "binding_epoch",
+ "session_id"
+ ],
+ "isUnique": true,
+ "where": "\"wechat_inbox\".\"session_id\" IS NOT NULL AND \"wechat_inbox\".\"status\" IN ('dispatching', 'accepted_running', 'waiting_desktop', 'delivery_pending')"
+ }
+ },
+ "foreignKeys": {
+ "wechat_inbox_binding_epoch_wechat_sync_state_binding_epoch_fk": {
+ "name": "wechat_inbox_binding_epoch_wechat_sync_state_binding_epoch_fk",
+ "tableFrom": "wechat_inbox",
+ "tableTo": "wechat_sync_state",
+ "columnsFrom": [
+ "binding_epoch"
+ ],
+ "columnsTo": [
+ "binding_epoch"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wechat_inbox_session_id_sessions_id_fk": {
+ "name": "wechat_inbox_session_id_sessions_id_fk",
+ "tableFrom": "wechat_inbox",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_outbox": {
+ "name": "wechat_outbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chunk_index": {
+ "name": "chunk_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "media_json": {
+ "name": "media_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "next_retry_at": {
+ "name": "next_retry_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "delivered_at": {
+ "name": "delivered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_wechat_outbox_client_id": {
+ "name": "uniq_wechat_outbox_client_id",
+ "columns": [
+ "binding_epoch",
+ "client_id"
+ ],
+ "isUnique": true
+ },
+ "idx_wechat_outbox_delivery": {
+ "name": "idx_wechat_outbox_delivery",
+ "columns": [
+ "binding_epoch",
+ "status",
+ "next_retry_at"
+ ],
+ "isUnique": false
+ },
+ "idx_wechat_outbox_task": {
+ "name": "idx_wechat_outbox_task",
+ "columns": [
+ "binding_epoch",
+ "task_id",
+ "chunk_index"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "wechat_outbox_binding_epoch_wechat_sync_state_binding_epoch_fk": {
+ "name": "wechat_outbox_binding_epoch_wechat_sync_state_binding_epoch_fk",
+ "tableFrom": "wechat_outbox",
+ "tableTo": "wechat_sync_state",
+ "columnsFrom": [
+ "binding_epoch"
+ ],
+ "columnsTo": [
+ "binding_epoch"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wechat_outbox_task_id_wechat_inbox_id_fk": {
+ "name": "wechat_outbox_task_id_wechat_inbox_id_fk",
+ "tableFrom": "wechat_outbox",
+ "tableTo": "wechat_inbox",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_sync_state": {
+ "name": "wechat_sync_state",
+ "columns": {
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "sync_cursor": {
+ "name": "sync_cursor",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "last_poll_at": {
+ "name": "last_poll_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_error_code": {
+ "name": "last_error_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_wechat_sync_active": {
+ "name": "uniq_wechat_sync_active",
+ "columns": [
+ "is_active"
+ ],
+ "isUnique": true,
+ "where": "\"wechat_sync_state\".\"is_active\" = 1"
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {
+ "uniq_orca_worker_creation_reservations_team_label": {
+ "columns": {
+ "lower(\"label\")": {
+ "isExpression": true
+ }
+ }
+ },
+ "uniq_orca_workers_team_label": {
+ "columns": {
+ "lower(\"label\")": {
+ "isExpression": true
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/apps/desktop/drizzle/meta/_journal.json b/apps/desktop/drizzle/meta/_journal.json
index 7930194420..88de3ce325 100644
--- a/apps/desktop/drizzle/meta/_journal.json
+++ b/apps/desktop/drizzle/meta/_journal.json
@@ -603,6 +603,13 @@
"when": 1785574922980,
"tag": "0085_skinny_iron_man",
"breakpoints": true
+ },
+ {
+ "idx": 86,
+ "version": "6",
+ "when": 1786019953044,
+ "tag": "0086_orange_surge",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 55d0228aa4..268e8fee4f 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -1066,7 +1066,9 @@ async function teardownAuthAccountBoundary(reason: string): Promise<void> {
} catch (err) {
authBoundaryLog.error(`stopHookControlAccount on ${reason} failed (non-fatal):`, err);
} finally {
- resetHookControlOwnerBoundary();
+ // Auth/runtime boundaries keep durable group cursors for a later relogin;
+ // only explicit account deletion is a data-removal boundary.
+ resetHookControlOwnerBoundary({ clearPersisted: reason === 'account-deletion' });
}
// Every Ghost sandbox can retain live OAuth, subscription, or in-memory
// state. Stop them before changing owners; resident Ghosts are recreated by
diff --git a/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts b/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts
index 3d6b230c12..3cae7dd1f3 100644
--- a/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts
+++ b/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts
@@ -184,6 +184,7 @@ function makeDispatcher(overrides?: {
terminalLedger?: HookRequestLedger;
config?: HookConnectionConfig | null;
prepareWorktree?: HookDispatcherDeps['prepareWorktree'];
+ buildContextPrefix?: HookDispatcherDeps['buildContextPrefix'];
dialogue?: HookDispatcherDeps['dialogue'];
abortSession?: HookDispatcherDeps['abortSession'];
subscribeUiContinuation?: HookDispatcherDeps['subscribeUiContinuation'];
@@ -204,6 +205,7 @@ function makeDispatcher(overrides?: {
terminalLedger: overrides?.terminalLedger,
runner,
prepareWorktree: overrides?.prepareWorktree,
+ buildContextPrefix: overrides?.buildContextPrefix,
dialogue: overrides?.dialogue,
abortSession: overrides?.abortSession,
subscribeUiContinuation: overrides?.subscribeUiContinuation,
@@ -421,6 +423,55 @@ describe('dispatcher 核心语义', () => {
});
});
+ it('切账号清排队时不提交未受理群游标,并为已 queued 任务补 cancelled 终态', async () => {
+ const fr = fakeRunner();
+ const rollbacks: string[] = [];
+ let commitCount = 0;
+ const { d } = makeDispatcher({
+ runner: fr.runner,
+ buildContextPrefix: async () => ({
+ prefix: '<group_chat_context>背景</group_chat_context>',
+ commit: async () => {
+ commitCount += 1;
+ const label = `commit-${commitCount}`;
+ return {
+ rollback: async () => {
+ rollbacks.push(label);
+ },
+ };
+ },
+ }),
+ });
+ const c = collector();
+ const externalKey = 'telegram:group:bot:-900:9:g0';
+
+ d.handleDispatch('conn-1', dispatch({ requestId: 'running', externalKey }), c.send);
+ await tick();
+ await fr.calls[0]?.onProviderAccepted?.();
+ d.handleDispatch('conn-1', dispatch({ requestId: 'queued-1', externalKey }), c.send);
+ await tick();
+ d.handleDispatch('conn-1', dispatch({ requestId: 'queued-2', externalKey }), c.send);
+ await tick();
+
+ expect(c.ofType('task.ack').map((message) => message.payload.result)).toEqual([
+ 'accepted',
+ 'queued',
+ 'queued',
+ ]);
+ const draining = d.deactivateAccount();
+ fr.finish({ finalText: '旧账号任务' });
+ await draining;
+
+ expect(commitCount).toBe(1);
+ expect(rollbacks).toEqual([]);
+ expect(
+ c.ofType('turn.end').map((message) => [message.payload.requestId, message.payload.status]),
+ ).toEqual([
+ ['queued-1', 'cancelled'],
+ ['queued-2', 'cancelled'],
+ ]);
+ });
+
it('收口期间的重新激活会被后到的关闭请求作废', async () => {
const fr = fakeRunner();
const { d } = makeDispatcher({ runner: fr.runner });
@@ -1655,6 +1706,197 @@ describe('dispatcher 核心语义', () => {
]);
});
+ it('排队任务只在真正开始时 commit, 取消队列前项不丢后项上下文', async () => {
+ const fr = fakeRunner();
+ const committed: string[] = [];
+ const { d } = makeDispatcher({
+ runner: fr.runner,
+ buildContextPrefix: async (payload) => ({
+ prefix: '<group_chat_context>背景</group_chat_context>',
+ commit: () => {
+ committed.push(payload.requestId);
+ },
+ }),
+ });
+ const c = collector();
+ const externalKey = 'telegram:group:bot:-900:9:g0';
+
+ d.handleDispatch('conn-1', dispatch({ requestId: 'running', externalKey }), c.send);
+ await tick();
+ await fr.calls[0]?.onProviderAccepted?.();
+ d.handleDispatch('conn-1', dispatch({ requestId: 'queued-a', externalKey }), c.send);
+ await tick();
+ d.handleDispatch('conn-1', dispatch({ requestId: 'queued-b', externalKey }), c.send);
+ await tick();
+
+ expect(committed).toEqual(['running']);
+ d.cancel('conn-1', 'queued-a');
+ await tick();
+ expect(committed).toEqual(['running']);
+
+ fr.finish({ finalText: 'running done' });
+ await tick();
+ expect(fr.calls).toHaveLength(2);
+ await fr.calls[1]?.onProviderAccepted?.();
+ expect(committed).toEqual(['running', 'queued-b']);
+
+ fr.finish({ finalText: 'queued b done' });
+ await tick();
+ expect(c.ofType('turn.end').map((m) => m.payload.requestId)).toEqual([
+ 'queued-a',
+ 'running',
+ 'queued-b',
+ ]);
+ });
+
+ it('已出队但 provider 未受理的群任务在切账号时 cancelled 且不提交游标', async () => {
+ const committed: string[] = [];
+ const fr = fakeRunner();
+ const { d } = makeDispatcher({
+ runner: fr.runner,
+ abortSession: async () => undefined,
+ buildContextPrefix: async (payload) => ({
+ prefix: '<group_chat_context>背景</group_chat_context>',
+ commit: async () => {
+ committed.push(payload.requestId);
+ },
+ }),
+ });
+ const c = collector();
+ const externalKey = 'telegram:group:bot:-900:9:g0';
+
+ d.handleDispatch('conn-1', dispatch({ requestId: 'running', externalKey }), c.send);
+ await tick();
+ await fr.calls[0]?.onProviderAccepted?.();
+ d.handleDispatch('conn-1', dispatch({ requestId: 'queued-inflight', externalKey }), c.send);
+ await tick();
+
+ fr.finish({ finalText: 'running done' });
+ await tick();
+ expect(fr.calls).toHaveLength(2);
+ expect(committed).toEqual(['running']);
+
+ const draining = d.deactivateAccount();
+ await tick();
+ expect(
+ c.ofType('turn.end').find((message) => message.payload.requestId === 'queued-inflight')
+ ?.payload,
+ ).toMatchObject({ status: 'cancelled' });
+
+ fr.finish({ finalText: 'must not cross account boundary' });
+ await draining;
+ expect(committed).toEqual(['running']);
+ });
+
+ it('直达任务 provider 未受理前账号失效不提交游标,并补 cancelled 终态', async () => {
+ const rollback = vi.fn(async () => undefined);
+ const commit = vi.fn(async () => ({ rollback }));
+ const fr = fakeRunner();
+ const { d } = makeDispatcher({
+ runner: fr.runner,
+ abortSession: async () => undefined,
+ buildContextPrefix: async () => ({
+ prefix: '<group_chat_context>背景</group_chat_context>',
+ commit,
+ }),
+ });
+ const c = collector();
+
+ d.handleDispatch(
+ 'conn-1',
+ dispatch({ requestId: 'not-accepted', externalKey: 'telegram:group:bot:-900:9:g0' }),
+ c.send,
+ );
+ await tick();
+ expect(c.last('task.ack')?.payload.result).toBe('accepted');
+ expect(fr.calls).toHaveLength(1);
+ expect(commit).not.toHaveBeenCalled();
+
+ const draining = d.deactivateAccount();
+ fr.finish({ finalText: '旧账号任务' });
+ await draining;
+
+ expect(commit).not.toHaveBeenCalled();
+ expect(rollback).not.toHaveBeenCalled();
+ expect(
+ c.ofType('turn.end').filter((message) => message.payload.requestId === 'not-accepted'),
+ ).toHaveLength(1);
+ expect(
+ c.ofType('turn.end').find((message) => message.payload.requestId === 'not-accepted')?.payload,
+ ).toMatchObject({ status: 'cancelled' });
+ });
+
+ it('直达任务只在 provider 受理后提交一次群游标', async () => {
+ const commit = vi.fn(async () => undefined);
+ const fr = fakeRunner();
+ const { d } = makeDispatcher({
+ runner: fr.runner,
+ buildContextPrefix: async () => ({
+ prefix: '<group_chat_context>背景</group_chat_context>',
+ commit,
+ }),
+ });
+ const c = collector();
+
+ d.handleDispatch(
+ 'conn-1',
+ dispatch({ requestId: 'accepted-once', externalKey: 'telegram:group:bot:-900:9:g0' }),
+ c.send,
+ );
+ await tick();
+ expect(commit).not.toHaveBeenCalled();
+
+ await fr.calls[0]?.onProviderAccepted?.();
+ expect(commit).toHaveBeenCalledTimes(1);
+
+ fr.finish({ finalText: 'done' });
+ await tick();
+ expect(c.last('turn.end')?.payload).toMatchObject({
+ requestId: 'accepted-once',
+ status: 'ok',
+ });
+ });
+
+ it('provider 受理后的群游标持久化失败不反转任务,旧游标留待下次重带', async () => {
+ const log = { info: vi.fn(), warn: vi.fn() };
+ const commit = vi.fn(async () => {
+ throw new Error('database is readonly');
+ });
+ const fr = fakeRunner();
+ const { d } = makeDispatcher({
+ runner: fr.runner,
+ log,
+ buildContextPrefix: async () => ({
+ prefix: '<group_chat_context>背景</group_chat_context>',
+ commit,
+ }),
+ });
+ const c = collector();
+
+ d.handleDispatch(
+ 'conn-1',
+ dispatch({ requestId: 'persist-failed', externalKey: 'telegram:group:bot:-900:9:g0' }),
+ c.send,
+ );
+ await tick();
+ await fr.calls[0]?.onProviderAccepted?.();
+
+ expect(commit).toHaveBeenCalledTimes(1);
+ expect(log.warn).toHaveBeenCalledWith(
+ expect.stringContaining(
+ 'group context cursor commit failed after provider acceptance: requestId=persist-failed',
+ ),
+ );
+
+ fr.finish({ finalText: '磁盘失败也要继续' });
+ await tick();
+ expect(c.last('turn.end')?.payload).toMatchObject({
+ requestId: 'persist-failed',
+ status: 'ok',
+ finalText: '磁盘失败也要继续',
+ });
+ });
+
it('runner 失败 -> turn.end status=error 且 errorMessage 非空', async () => {
const fr = fakeRunner();
const { d } = makeDispatcher({ runner: fr.runner });
@@ -1677,7 +1919,8 @@ describe('dispatcher 核心语义', () => {
// 同一同步 tick 内连发(ws 同步 emit 场景) —— 修复前会各开一个新 session
d.handleDispatch('conn-1', dispatch({ requestId: 'r1' }), c.send);
d.handleDispatch('conn-1', dispatch({ requestId: 'r2' }), c.send);
- await tick(6);
+ // 会话定位与受理链含多个微任务;多给几轮,不改变 FIFO 语义。
+ await tick(30);
const acks = c.ofType('task.ack').map((m) => m.payload);
expect(acks).toHaveLength(2);
@@ -1981,7 +2224,8 @@ describe('dispatcher 核心语义', () => {
await tick();
for (let i = 0; i < 21; i++) {
d.handleDispatch('conn-1', dispatch({ requestId: `q${i}` }), c.send);
- await tick();
+ // 会话定位与受理链含多个微任务;多给几轮,不改变 FIFO 语义。
+ await tick(30);
}
const acks = c.ofType('task.ack').map((m) => m.payload);
const overflow = acks[acks.length - 1];
diff --git a/apps/desktop/src/main/hook-control/__tests__/groupWindow.test.ts b/apps/desktop/src/main/hook-control/__tests__/groupWindow.test.ts
index 10de7567c1..b43ea5c894 100644
--- a/apps/desktop/src/main/hook-control/__tests__/groupWindow.test.ts
+++ b/apps/desktop/src/main/hook-control/__tests__/groupWindow.test.ts
@@ -1,7 +1,7 @@
/**
* groupWindow(group-relay-v1 本地群窗口)单测: 入窗幂等、永久留存、lane 解析、
* 上下文拼装(trigger 剔重 / 游标增量 / 字符预算)。DB 用内存 better-sqlite3
- * 直接执行 0083 migration SQL, 经 drizzle 同步 driver 假装成 DbClient。
+ * 直接执行 0083 + 0086 migration SQL, 经 drizzle 同步 driver 假装成 DbClient。
*/
import fs from 'node:fs';
@@ -17,6 +17,7 @@ const holder = vi.hoisted(() => ({ drizzle: null as unknown }));
vi.mock('../../localDb/client/current.js', () => ({
getDbClient: () => ({ drizzle: holder.drizzle }),
+ tryGetDbClient: () => ({ drizzle: holder.drizzle }),
}));
import {
@@ -39,9 +40,14 @@ function recordGroupMessage(payload: GroupMessagePayload): Promise<boolean> {
function migrationSql(): string {
const dir = path.resolve(__dirname, '../../../../drizzle');
- const file = fs.readdirSync(dir).find((name) => name.startsWith('0083_'));
- if (!file) throw new Error('0083 migration not found');
- return fs.readFileSync(path.join(dir, file), 'utf8').replaceAll('--> statement-breakpoint', ';');
+ return ['0083_', '0086_']
+ .map((prefix) => {
+ const file = fs.readdirSync(dir).find((name) => name.startsWith(prefix));
+ if (!file) throw new Error(`${prefix} migration not found`);
+ return fs.readFileSync(path.join(dir, file), 'utf8');
+ })
+ .join('\n')
+ .replaceAll('--> statement-breakpoint', ';');
}
function frame(overrides: Partial<GroupMessagePayload> = {}): GroupMessagePayload {
@@ -60,11 +66,11 @@ function frame(overrides: Partial<GroupMessagePayload> = {}): GroupMessagePayloa
let sqlite: InstanceType<typeof Database>;
-beforeEach(() => {
+beforeEach(async () => {
sqlite = new Database(':memory:');
sqlite.exec(migrationSql());
holder.drizzle = drizzle(sqlite);
- resetGroupContextCursors();
+ await resetGroupContextCursors();
});
afterEach(() => {
@@ -133,6 +139,212 @@ describe('recordGroupMessage', () => {
expect(rows.n).toBe(1);
});
+ it('正文全文入库, 但拼 prompt 仍按 500 字符截断', async () => {
+ const text = 'x'.repeat(700);
+ await recordGroupMessage(frame({ messageId: 'long', text }));
+ const row = sqlite
+ .prepare('SELECT text FROM hook_group_messages WHERE message_id = ?')
+ .get('long') as { text: string };
+ expect(row.text).toBe(text);
+
+ const prefix = (
+ await buildGroupContextPrefix({
+ requestId: 'long-context',
+ externalKey: 'telegram:group:1:-900:9:g1',
+ workspace: 'chat',
+ sessionId: null,
+ prompt: 'q',
+ })
+ ).prefix;
+ expect(prefix).toContain('x'.repeat(500));
+ expect(prefix).not.toContain('x'.repeat(501));
+ });
+
+ it('重置只删除官方 provider 的持久游标', async () => {
+ await recordGroupMessage(frame({ messageId: 'cursor-reset' }));
+ const assembly = await buildGroupContextPrefix({
+ requestId: 'cursor-reset-context',
+ externalKey: 'telegram:group:1:-900:9:g1',
+ workspace: 'chat',
+ sessionId: null,
+ prompt: 'q',
+ });
+ await assembly.commit();
+ sqlite
+ .prepare(
+ `INSERT INTO hook_group_context_cursors
+ (provider, cursor_key, cursor_id, updated_at) VALUES (?, ?, ?, ?)`,
+ )
+ .run('telegram-personal:bot-1', 'bot-1:-900:', 99, Date.now());
+
+ await resetGroupContextCursors();
+ expect(
+ sqlite
+ .prepare('SELECT 1 FROM hook_group_context_cursors WHERE provider = ?')
+ .get('telegram:9'),
+ ).toBeUndefined();
+ expect(
+ sqlite
+ .prepare('SELECT cursor_id FROM hook_group_context_cursors WHERE provider = ?')
+ .get('telegram-personal:bot-1') as { cursor_id: number },
+ ).toEqual({ cursor_id: 99 });
+ });
+
+ it('受理代次在写库前失效时不推进内存或持久游标', async () => {
+ await recordGroupMessage(frame({ messageId: 'guard-before', text: '待受理消息' }));
+ const first = await buildGroupContextPrefix({
+ requestId: 'guard-before-context',
+ externalKey: 'telegram:group:1:-900:9:g1',
+ workspace: 'chat',
+ sessionId: null,
+ prompt: 'q',
+ });
+
+ await first.commit(() => false);
+ expect(
+ sqlite
+ .prepare('SELECT 1 FROM hook_group_context_cursors WHERE provider = ?')
+ .get('telegram:9'),
+ ).toBeUndefined();
+ const replay = await buildGroupContextPrefix({
+ requestId: 'guard-before-replay',
+ externalKey: 'telegram:group:1:-900:9:g1',
+ workspace: 'chat',
+ sessionId: null,
+ prompt: 'q',
+ });
+ expect(replay.prefix).toContain('待受理消息');
+ });
+
+ it('写库后代次失效会回滚本次推进', async () => {
+ await recordGroupMessage(frame({ messageId: 'guard-rollback', text: '仍待受理' }));
+ const assembly = await buildGroupContextPrefix({
+ requestId: 'guard-rollback-context',
+ externalKey: 'telegram:group:1:-900:9:g1',
+ workspace: 'chat',
+ sessionId: null,
+ prompt: 'q',
+ });
+ let guardCalls = 0;
+ await assembly.commit(() => ++guardCalls === 1);
+ expect(guardCalls).toBe(2);
+ expect(
+ sqlite
+ .prepare('SELECT 1 FROM hook_group_context_cursors WHERE provider = ?')
+ .get('telegram:9'),
+ ).toBeUndefined();
+ const replay = await buildGroupContextPrefix({
+ requestId: 'guard-rollback-replay',
+ externalKey: 'telegram:group:1:-900:9:g1',
+ workspace: 'chat',
+ sessionId: null,
+ prompt: 'q',
+ });
+ expect(replay.prefix).toContain('仍待受理');
+ });
+
+ it('写库后代次失效只回滚本次写入, 不覆盖更高游标', async () => {
+ await recordGroupMessage(frame({ messageId: 'guard-after', text: '待回滚消息' }));
+ const assembly = await buildGroupContextPrefix({
+ requestId: 'guard-after-context',
+ externalKey: 'telegram:group:1:-900:9:g1',
+ workspace: 'chat',
+ sessionId: null,
+ prompt: 'q',
+ });
+ let guardCalls = 0;
+ await assembly.commit(() => {
+ guardCalls += 1;
+ if (guardCalls === 1) return true;
+ sqlite
+ .prepare(
+ `INSERT INTO hook_group_context_cursors
+ (provider, cursor_key, cursor_id, updated_at) VALUES (?, ?, ?, ?)
+ ON CONFLICT(provider, cursor_key) DO UPDATE SET cursor_id = excluded.cursor_id`,
+ )
+ .run('telegram:9', 'telegram:group:1:-900:9', 99, Date.now());
+ return false;
+ });
+ expect(guardCalls).toBe(2);
+ expect(
+ sqlite
+ .prepare(
+ 'SELECT cursor_id FROM hook_group_context_cursors WHERE provider = ? AND cursor_key = ?',
+ )
+ .get('telegram:9', 'telegram:group:1:-900:9'),
+ ).toEqual({ cursor_id: 99 });
+ });
+
+ it('commit 返回后由受理方回滚时恢复本次游标', async () => {
+ await recordGroupMessage(frame({ messageId: 'receipt-rollback', text: '待补偿消息' }));
+ const assembly = await buildGroupContextPrefix({
+ requestId: 'receipt-rollback-context',
+ externalKey: 'telegram:group:1:-900:9:g1',
+ workspace: 'chat',
+ sessionId: null,
+ prompt: 'q',
+ });
+
+ const receipt = await assembly.commit();
+ expect(receipt).toBeDefined();
+ await receipt?.rollback();
+ expect(
+ sqlite
+ .prepare('SELECT 1 FROM hook_group_context_cursors WHERE provider = ?')
+ .get('telegram:9'),
+ ).toBeUndefined();
+ const replay = await buildGroupContextPrefix({
+ requestId: 'receipt-rollback-replay',
+ externalKey: 'telegram:group:1:-900:9:g1',
+ workspace: 'chat',
+ sessionId: null,
+ prompt: 'q',
+ });
+ expect(replay.prefix).toContain('待补偿消息');
+ });
+
+ it('游标 UPSERT 成功后不依赖写后回读,仍返回回滚凭据', async () => {
+ await recordGroupMessage(frame({ messageId: 'post-write-read-failure' }));
+ const assembly = await buildGroupContextPrefix({
+ requestId: 'post-write-read-failure-context',
+ externalKey: 'telegram:group:1:-900:9:g1',
+ workspace: 'chat',
+ sessionId: null,
+ prompt: 'q',
+ });
+
+ const baseDrizzle = holder.drizzle as object;
+ let selectCalls = 0;
+ holder.drizzle = new Proxy(baseDrizzle, {
+ get(target, property, receiver) {
+ if (property === 'select') {
+ const select = Reflect.get(target, property, target) as (...args: unknown[]) => unknown;
+ return (...args: unknown[]) => {
+ selectCalls += 1;
+ if (selectCalls > 1) throw new Error('post-write read failed');
+ return Reflect.apply(select, target, args);
+ };
+ }
+ return Reflect.get(target, property, target);
+ },
+ });
+
+ try {
+ const receipt = await assembly.commit();
+ expect(receipt).toBeDefined();
+ expect(selectCalls).toBe(1);
+ expect(
+ sqlite
+ .prepare(
+ 'SELECT cursor_id FROM hook_group_context_cursors WHERE provider = ? AND cursor_key = ?',
+ )
+ .get('telegram:9', 'telegram:group:1:-900:9'),
+ ).toEqual({ cursor_id: 1 });
+ } finally {
+ holder.drizzle = drizzle(sqlite);
+ }
+ });
+
it('群历史不按时间过期,但每个 principal + 群/topic 只保留最近 500 条', async () => {
for (let i = 0; i < 502; i += 1) {
await recordGroupMessage(frame({ messageId: `m${i}`, text: `msg ${i}` }));
@@ -345,7 +557,26 @@ describe('buildGroupContextPrefix', () => {
source: { im: 'telegram', triggerMessageId: '3' },
});
expect(replay.prefix).toContain('部署失败了');
- firstAssembly.commit();
+ await firstAssembly.commit();
+ expect(
+ sqlite
+ .prepare(
+ 'SELECT cursor_id FROM hook_group_context_cursors WHERE provider = ? AND cursor_key = ?',
+ )
+ .get('telegram:9', 'telegram:group:1:-900:42:9') as { cursor_id: number },
+ ).toEqual({ cursor_id: 3 });
+
+ // 模拟进程重启: 清掉内存态但保留 DB, 恢复后不重复已提交消息。
+ await resetGroupContextCursors({ clearPersisted: false });
+ const restored = await buildGroupContextPrefix({
+ requestId: 'r3-restart',
+ externalKey,
+ workspace: 'chat',
+ sessionId: null,
+ prompt: '怎么回事?',
+ source: { im: 'telegram', triggerMessageId: '3' },
+ });
+ expect(restored.prefix).toBe('');
await recordGroupMessage(
frame({ messageId: '4', text: '重启后恢复了', author: { name: '@user303' } }),
diff --git a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
index ff40336cf2..3fd28c3be7 100644
--- a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
+++ b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
@@ -504,6 +504,23 @@ describe('hook session-runner 的 userSendAt 时序(未分类误判回归)', ()
expect(h.touchUserSendInDb).toHaveBeenCalledWith('sess-old');
});
+ it('provider 接受后才执行回调,回调失败不反转已受理 turn', async () => {
+ const onProviderAccepted = vi.fn(async () => {
+ h.calls.push('providerAccepted');
+ throw new Error('cursor db unavailable');
+ });
+ const runner = createMakerHookSessionRunner({ log });
+
+ const outcome = await runner.run(baseReq({ onProviderAccepted }));
+
+ expect(outcome.status).toBe('ok');
+ expect(onProviderAccepted).toHaveBeenCalledTimes(1);
+ expect(h.calls.indexOf('createMessage')).toBeLessThan(h.calls.indexOf('providerAccepted'));
+ expect(log.warn).toHaveBeenCalledWith(
+ expect.stringContaining('provider-accepted callback failed for session=sess-new'),
+ );
+ });
+
it('入站图片附件:ingest 进媒体总仓挂 session-attachment 引用,喂 agent 用 blob 绝对路径,落库用 cindy-media url', async () => {
const runner = createMakerHookSessionRunner({ log });
const outcome = await runner.run(
diff --git a/apps/desktop/src/main/hook-control/dispatcher.ts b/apps/desktop/src/main/hook-control/dispatcher.ts
index e6c3b78204..3ad96842c5 100644
--- a/apps/desktop/src/main/hook-control/dispatcher.ts
+++ b/apps/desktop/src/main/hook-control/dispatcher.ts
@@ -176,6 +176,11 @@ export interface HookRunRequest {
origin: { connectionId: string; connectionName: string; externalKey: string };
/** IM 来源元数据(平台 + thread 上下文); 省略 = 旧 server 不发。 */
source?: TaskSource;
+ /**
+ * provider 已实际接受本次发送后的副作用。runner 只在 send outcome
+ * 确认为 dispatched 后 await;失败必须由调用方自行降级,不能反转已受理 turn。
+ */
+ onProviderAccepted?: () => void | Promise<void>;
/**
* 执行中渲染快照回调(turn.progress 链路)。runner 合成「过程区时间线 +
* 部分正文」的完整 markdown 快照并节流回调; dispatcher 注入的实现把它
@@ -237,12 +242,18 @@ export interface HookDispatcherDeps {
* 可选: 为派发组装本地群上下文前缀(group-relay-v1 窗口, 生产为
* groupWindow.buildGroupContextPrefix)。只影响发给 agent 的 prompt,
* 不影响会话标题与 UI 渲染(二者用 source.userText / 原始 prompt);
- * 失败或空装配 = 无前缀, 绝不因上下文拒单。commit 在任务被受理
- * (accepted/queued)后由本模块调用, 拒单不推进窗口游标。
+ * 失败或空装配 = 无前缀, 绝不因上下文拒单。两条路径都只在 provider
+ * 实际受理后提交;拒单、取消或清队列都不推进窗口游标。
*/
- buildContextPrefix?: (
- payload: TaskDispatchPayload,
- ) => Promise<{ prefix: string; commit: () => void }>;
+ buildContextPrefix?: (payload: TaskDispatchPayload) => Promise<{
+ prefix: string;
+ commit: (
+ guard?: () => boolean | Promise<boolean>,
+ ) =>
+ | void
+ | { rollback(): void | Promise<void> }
+ | Promise<void | { rollback(): void | Promise<void> }>;
+ }>;
/**
* 可选: 内置「对话」伪目录(chat 保留别名)的解析面。rootDir 在每次
* dispatch 时解析当前 data owner 的 app 托管目录根,allocateDir 为新会话
@@ -377,7 +388,6 @@ const TURN_DELIVERY_ACK_MAX_DELAY_MS = 60_000;
const REOPEN_TTL_MS = 24 * 60 * 60_000;
/** 续跑记账条数上限(FIFO 淘汰最老), 同 ackHistory 语义: 防长驻进程无界增长。 */
const MAX_PENDING_REOPENS = 200;
-
/**
* 原对话不再落在工作目录映射内时(被移到映射外的项目, 或映射本身被改/删),
* 回给渠道的一次性说明(Slack / Telegram 侧文案不进 locale, 与 interactions.ts
@@ -492,6 +502,11 @@ export function buildHookSessionTitle(
return `[${contextTag}${displayProvider}${dmTag}] ${snippet}`;
}
+type ContextCursorReceipt = { rollback(): void | Promise<void> };
+type ContextCursorCommit = (
+ guard?: () => boolean | Promise<boolean>,
+) => void | ContextCursorReceipt | Promise<void | ContextCursorReceipt>;
+
/** 待执行任务(定位已完成, 排队即执行参数就绪)。 */
interface PendingTask {
connectionId: string;
@@ -501,6 +516,8 @@ interface PendingTask {
externalKey: string;
run: HookRunRequest;
accountGeneration: number;
+ /** 群上下文游标提交回调;仅在 provider 实际受理后调用。 */
+ commitContextCursor?: ContextCursorCommit;
/** 会话定位阶段产生的一次性说明, 前置到本次 turn.end 的 finalText。 */
notice?: string;
/**
@@ -617,6 +634,34 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
if (keyChains.get(key) === stored) keyChains.delete(key);
});
}
+ /** 同一 session 的受理段串行化,避免不同 externalKey 并发判断空闲并同时占槽。 */
+ const sessionAdmissionChains = new Map<string, Promise<void>>();
+ async function serializeSessionAdmission(
+ sessionId: string,
+ fn: () => Promise<void>,
+ ): Promise<void> {
+ const previous = sessionAdmissionChains.get(sessionId);
+ let release!: () => void;
+ const current = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const stored = previous
+ ? previous.then(
+ () => current,
+ () => current,
+ )
+ : current;
+ sessionAdmissionChains.set(sessionId, stored);
+ try {
+ if (previous !== undefined) await previous;
+ await fn();
+ } finally {
+ release();
+ if (sessionAdmissionChains.get(sessionId) === stored) {
+ sessionAdmissionChains.delete(sessionId);
+ }
+ }
+ }
/** 每连接当前发送函数(transport 重建后由 onConnected / handleDispatch 刷新)。 */
const sendFns = new Map<string, (m: HookMessage) => boolean>();
/** 离线积压的 turn.end, 按连接缓存; durable terminal 先记 pending, 发送成功后标 sent。 */
@@ -663,6 +708,15 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
const queues = new Map<string, PendingTask[]>();
/** connectionId + requestId -> 正在执行它的 session(cancel 定位与归属校验用, 收口即清)。 */
const runningByRequest = new Map<string, { sessionId: string; connectionId: string }>();
+ /**
+ * 已开始执行但 provider 尚未受理的 Telegram 群任务。账号边界必须把其
+ * accepted / queued ACK 收成 cancelled;accepted=true 后消息已交给 agent,
+ * 不再按未受理任务处理。
+ */
+ const pendingGroupAdmissions = new Map<
+ string,
+ { task: PendingTask; accepted: boolean; cancelled: boolean }
+ >();
/** 已请求取消的 connectionId + requestId(execute 收口时据此把结果改写为 cancelled)。 */
const cancelRequested = new Set<string>();
/** 每连接最近一次 welcome 宣告的能力集(turn.reopen 的 feature gate)。 */
@@ -1279,6 +1333,10 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
running.delete(sessionId);
return;
}
+ const pendingGroupAdmission = task.commitContextCursor
+ ? { task, accepted: false, cancelled: false }
+ : null;
+ if (pendingGroupAdmission) pendingGroupAdmissions.set(requestKey, pendingGroupAdmission);
// 这条消息线交给新任务了: 撤掉上一轮失败留下的续跑观察与记账。连接还在, 所以要
// 发收口帧把那条旧消息定稿; 但不再记待续跑(它已经不是"最新一轮"了)。
dropContinuation(sessionId, { silent: false, remember: false });
@@ -1343,6 +1401,15 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
onProgress,
onInteraction,
onInteractionCancel,
+ ...(task.commitContextCursor
+ ? {
+ onProviderAccepted: async () => {
+ if (pendingGroupAdmission?.cancelled) return;
+ if (pendingGroupAdmission) pendingGroupAdmission.accepted = true;
+ await commitTaskContextCursor(task);
+ },
+ }
+ : {}),
// runner 建/取到 session 后, 拿它真正要跑的那个目录回来问一次 ——
// 那个目录可能与这里校验过的不是同一个(见 isDirAuthorized 的说明)。
isDirAuthorized: (dir) => dirStillAllowed(task.connectionId, dir),
@@ -1357,6 +1424,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
}
}
runningByRequest.delete(requestKey);
+ pendingGroupAdmissions.delete(requestKey);
if (!isCurrentGeneration(task.accountGeneration)) {
cancelRequested.delete(requestKey);
running.delete(sessionId);
@@ -1451,6 +1519,45 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
void promise.finally(() => executing.delete(promise));
}
+ /**
+ * provider 已受理后才推进 durable cursor。此时即使账号代次随后失效,消息也
+ * 已交给 agent,游标前移是正确的;持久化失败则保留旧游标,下次最多重复携带,
+ * 不能为了游标写入失败反转一个已经受理的 turn。
+ */
+ async function commitTaskContextCursor(
+ task: Pick<PendingTask, 'requestId' | 'commitContextCursor'>,
+ ): Promise<void> {
+ if (!task.commitContextCursor) return;
+ try {
+ await task.commitContextCursor();
+ } catch (error) {
+ log.warn(
+ `group context cursor commit failed after provider acceptance: requestId=${task.requestId} error=${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ }
+ }
+
+ /** 已回 ACK 的任务在取消或账号边界被清掉时必须有 durable 终态。 */
+ function finishTaskAsCancelled(task: PendingTask): void {
+ const turnEnd: TurnEndPayload = {
+ requestId: task.requestId,
+ externalKey: task.externalKey,
+ sessionId: task.run.sessionId,
+ status: 'cancelled',
+ finalText: '',
+ errorMessage: null,
+ usage: { durationMs: null },
+ };
+ sendOrBuffer(task.connectionId, makeTurnEnd(turnEnd), {
+ connectionId: task.connectionId,
+ requestId: task.requestId,
+ ack: task.ack,
+ turnEnd: durableTurnEnd(turnEnd),
+ });
+ }
+
/**
* 会话定位(接管 / 绑定复用 / 新建), 返回 run 参数或拒绝原因。
* notice: 需要随本次 turn.end 一并告知渠道用户的一次性说明(会话被移动 /
@@ -1929,7 +2036,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
serializeByKey(`${connectionId} ${payload.externalKey}`, async () => {
try {
let contextPrefix = '';
- let commitContextCursor: () => void = () => undefined;
+ let commitContextCursor: ContextCursorCommit | undefined;
if (buildContextPrefix) {
try {
const assembly = await buildContextPrefix(dispatchPayload);
@@ -1966,48 +2073,61 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
},
accountGeneration: admittedGeneration,
reopenCapable: supportsReopen(connectionId),
+ ...((payload.externalKey.startsWith('telegram:group:') ||
+ payload.externalKey.startsWith('telegram:topic:')) &&
+ commitContextCursor
+ ? { commitContextCursor }
+ : {}),
...(resolved.notice ? { notice: resolved.notice } : {}),
...(resolved.cleanupWorktree ? { cleanupWorktree: resolved.cleanupWorktree } : {}),
};
const sessionId = resolved.run.sessionId;
- const queue = queues.get(sessionId) ?? [];
-
- if (running.has(sessionId) || runner.isBusy(sessionId) || queue.length > 0) {
- if (queue.length >= MAX_QUEUE_PER_SESSION) {
+ await serializeSessionAdmission(sessionId, async () => {
+ if (!isCurrentGeneration(admittedGeneration)) return;
+ const initialQueue = queues.get(sessionId) ?? [];
+ const initiallyBusy =
+ running.has(sessionId) || runner.isBusy(sessionId) || initialQueue.length > 0;
+ if (initiallyBusy && initialQueue.length >= MAX_QUEUE_PER_SESSION) {
reply(connectionId, send, rejected(payload.requestId, 'invalid'));
log.warn(`dispatch queue overflow: session=${sessionId}`);
return;
}
+
+ // 排队任务只保存 commit 回调;provider 尚未受理,不得提前推进 durable cursor。
+ const queue = queues.get(sessionId) ?? [];
+ if (running.has(sessionId) || runner.isBusy(sessionId) || queue.length > 0) {
+ const ack: TaskAckPayload = {
+ requestId: payload.requestId,
+ result: 'queued',
+ reason: null,
+ sessionId,
+ queuePosition: queue.length,
+ };
+ const task: PendingTask = {
+ ...taskBase,
+ ack,
+ };
+ queue.push(task);
+ queues.set(sessionId, queue);
+ reply(connectionId, send, ack);
+ // 排队时目标 session 可能是 desktop 侧用户手动在跑(runner.isBusy),
+ // 没有本模块的收口点 —— 轮询兜底: 空闲即 drain
+ if (!running.has(sessionId)) scheduleDrainPoll(sessionId);
+ return;
+ }
+
+ running.add(sessionId);
const ack: TaskAckPayload = {
requestId: payload.requestId,
- result: 'queued',
+ result: 'accepted',
reason: null,
sessionId,
- queuePosition: queue.length,
+ queuePosition: null,
};
const task: PendingTask = { ...taskBase, ack };
- queue.push(task);
- queues.set(sessionId, queue);
- commitContextCursor();
reply(connectionId, send, ack);
- // 排队时目标 session 可能是 desktop 侧用户手动在跑(runner.isBusy),
- // 没有本模块的收口点 —— 轮询兜底: 空闲即 drain
- if (!running.has(sessionId)) scheduleDrainPoll(sessionId);
- return;
- }
-
- running.add(sessionId);
- commitContextCursor();
- const ack: TaskAckPayload = {
- requestId: payload.requestId,
- result: 'accepted',
- reason: null,
- sessionId,
- queuePosition: null,
- };
- const task: PendingTask = { ...taskBase, ack };
- reply(connectionId, send, ack);
- startExecution(task);
+ startExecution(task);
+ });
} catch (err) {
if (!isCurrentGeneration(admittedGeneration)) return;
log.warn(`handleDispatch failed: ${err instanceof Error ? err.message : String(err)}`);
@@ -2067,6 +2187,18 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
for (const timer of drainPolls.values()) clearTimeout(timer);
drainPolls.clear();
+ for (const admission of pendingGroupAdmissions.values()) {
+ if (admission.accepted || admission.cancelled) continue;
+ admission.cancelled = true;
+ finishTaskAsCancelled(admission.task);
+ }
+ // 只收口本 PR 新增的“携带群上下文 commit”任务;Slack/X 普通队列保持
+ // 既有账号 teardown 语义。终态必须在 sendFns / delivery buffer 清理前落下。
+ for (const queue of queues.values()) {
+ for (const task of queue) {
+ if (task.commitContextCursor) finishTaskAsCancelled(task);
+ }
+ }
queues.clear();
sendFns.clear();
pendingTurnEnds.clear();
@@ -2095,13 +2227,14 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
}
}
await Promise.allSettled(aborts);
- await Promise.allSettled([...keyChains.values()]);
+ await Promise.allSettled([...keyChains.values(), ...sessionAdmissionChains.values()]);
await Promise.allSettled([...executing]);
ackHistory.clear();
inflightRequests.clear();
running.clear();
runningByRequest.clear();
+ pendingGroupAdmissions.clear();
cancelRequested.clear();
// 切账号时 execute() 会在代际检查处提前 return, 走不到收口那行删除 ——
// 不在这里清的话, 每次切账号都永久留下一条 sessionId + 完整工作目录路径
@@ -2109,6 +2242,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
awaitingPersist.clear();
staleTakeoverReplacements.clear();
keyChains.clear();
+ sessionAdmissionChains.clear();
})();
accountDeactivation = drain.finally(() => {
accountDeactivation = null;
@@ -2241,21 +2375,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
if (idx >= 0) {
const [task] = queue.splice(idx, 1);
if (queue.length === 0) queues.delete(sessionId);
- const turnEnd: TurnEndPayload = {
- requestId: task.requestId,
- externalKey: task.externalKey,
- sessionId: task.run.sessionId,
- status: 'cancelled',
- finalText: '',
- errorMessage: null,
- usage: { durationMs: null },
- };
- sendOrBuffer(connectionId, makeTurnEnd(turnEnd), {
- connectionId,
- requestId: task.requestId,
- ack: task.ack,
- turnEnd: durableTurnEnd(turnEnd),
- });
+ finishTaskAsCancelled(task);
log.info(`hook task ${requestId} cancelled while queued`);
return;
}
diff --git a/apps/desktop/src/main/hook-control/groupWindow.ts b/apps/desktop/src/main/hook-control/groupWindow.ts
index cb7f971617..a9d74cd657 100644
--- a/apps/desktop/src/main/hook-control/groupWindow.ts
+++ b/apps/desktop/src/main/hook-control/groupWindow.ts
@@ -25,6 +25,7 @@ import {
assembleGroupWindowContext,
createFenceNeutralizer,
recordGroupWindowEntry,
+ resetGroupWindowCursors,
type GroupContextAssembly,
} from '../im/shared/groupWindowCore.js';
import { getDbClient } from '../localDb/client/current.js';
@@ -124,8 +125,8 @@ export async function sweepGroupWindowExpired(): Promise<void> {
}
/**
- * 每 lane 的增量游标(上次拼装到的窗口行 id)。内存态: 重启后首次派发会
- * 重新包含整个窗口(一次性冗余, 可接受), 之后恢复增量语义。
+ * 每 lane 的增量游标(上次拼装到的窗口行 id)。内存态只作热缓存, 持久事实在
+ * hook_group_context_cursors; 重启后首次派发从本地 DB 恢复增量语义。
*/
const contextCursors = new Map<string, number>();
@@ -141,7 +142,7 @@ const NO_CONTEXT: GroupContextAssembly = { prefix: '', commit: () => undefined }
/**
* 为一次 hook 派发组装本地群上下文前缀。非群 lane / 窗口为空返回空装配。
- * 只读窗口; 游标推进延迟到 commit(由 dispatcher 在任务受理后调用)。
+ * 只读窗口; 游标推进延迟到 commit(由 dispatcher 在 provider 实际受理后调用)。
*/
export async function buildGroupContextPrefix(
payload: TaskDispatchPayload,
@@ -172,9 +173,25 @@ export async function buildGroupContextPrefix(
});
}
-/** 测试与登出清理: 重置内存游标(窗口行随 DB 生命周期)。 */
-export function resetGroupContextCursors(): void {
- contextCursors.clear();
+/** 测试与登出清理: 只清理官方群 provider 的内存态与持久游标。 */
+export function resetGroupContextCursors(options?: {
+ clearPersisted?: boolean;
+}): Promise<void> {
+ return resetGroupWindowCursors({
+ cursors: contextCursors,
+ providerPrefixes: ['telegram:'],
+ providerNames: ['telegram'],
+ ...(options?.clearPersisted === false ? { clearPersisted: false } : {}),
+ });
+}
+
+/** 同步生命周期入口使用的安全收口: 异步清理失败只记日志, 不产生 unhandled rejection。 */
+export function resetGroupContextCursorsSafely(options?: {
+ clearPersisted?: boolean;
+}): void {
+ void resetGroupContextCursors(options).catch((error: unknown) => {
+ log.warn(`group context cursor reset failed: ${String(error)}`);
+ });
}
/** 设置卡数据源:官方群窗口里出现过的群,按最近活跃排序。 */
diff --git a/apps/desktop/src/main/hook-control/ipc.ts b/apps/desktop/src/main/hook-control/ipc.ts
index 84d151edbf..d4f37a76f0 100644
--- a/apps/desktop/src/main/hook-control/ipc.ts
+++ b/apps/desktop/src/main/hook-control/ipc.ts
@@ -86,7 +86,7 @@ import {
buildGroupContextPrefix,
listTelegramKnownGroupsForStableBinding,
mergeTelegramGroupActivationViews,
- resetGroupContextCursors,
+ resetGroupContextCursorsSafely,
} from './groupWindow.js';
import { createHookDispatcher } from './dispatcher.js';
import { createMakerHookSessionRunner } from './session-runner.js';
@@ -1064,9 +1064,9 @@ export async function stopHookControlAccount(): Promise<void> {
}
/** Stop and discard all state tied to the current data owner; IPC stays registered. */
-export function resetHookControlOwnerBoundary(): void {
+export function resetHookControlOwnerBoundary(options?: { clearPersisted?: boolean }): void {
unregisterSlackToolBridge();
- resetGroupContextCursors();
+ resetGroupContextCursorsSafely(options);
resetTelegramSpeakerRegistrationCache();
manager?.dispose();
manager = null;
@@ -1081,5 +1081,7 @@ export function disposeHookControl(): void {
disposeAuthListener?.();
disposeAuthListener = null;
observedAuthRealm = null;
- resetHookControlOwnerBoundary();
+ // App quit is not an account unbind: preserve the durable cursor and only
+ // discard the in-memory cache so the next process resumes incrementally.
+ resetHookControlOwnerBoundary({ clearPersisted: false });
}
diff --git a/apps/desktop/src/main/hook-control/manager.ts b/apps/desktop/src/main/hook-control/manager.ts
index 757f8ec6b9..9de42b4f9a 100644
--- a/apps/desktop/src/main/hook-control/manager.ts
+++ b/apps/desktop/src/main/hook-control/manager.ts
@@ -94,6 +94,7 @@ import {
groupLaneOf,
recordGroupMessage,
resetGroupContextCursors,
+ resetGroupContextCursorsSafely,
sweepGroupWindowExpired,
} from './groupWindow.js';
import { parseTelegramConnectUrl } from './telegramDeepLink.js';
@@ -1520,7 +1521,7 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookCont
drainLanePendingPrefs(lane);
drainLanePendingBehavior(lane);
if (lane.config.provider === 'telegram') {
- resetGroupContextCursors();
+ resetGroupContextCursorsSafely();
resetTelegramSpeakerRegistrationCache();
}
}
@@ -3095,7 +3096,8 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookCont
lane.serverFeatures = [];
lane.serverWelcomeReceived = false;
}
- resetGroupContextCursors();
+ // 普通账号边界只清内存热缓存;明确删除账号数据时才清官方群 durable cursor。
+ await resetGroupContextCursors({ clearPersisted: false });
resetTelegramSpeakerRegistrationCache();
notifySlackToolProviderEnabledIfChanged();
notifyStatus(toView());
diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.ts
index e69b744a7e..79f23bce29 100644
--- a/apps/desktop/src/main/hook-control/session-runner.ts
+++ b/apps/desktop/src/main/hook-control/session-runner.ts
@@ -1034,6 +1034,18 @@ export function createMakerHookSessionRunner(deps: {
releaseTelegramGroupTurn();
return fail(`send not dispatched: ${outcome.reason}`);
}
+ // 与个人 IM turnRunner 的 route-resolved 时机一致:只有 provider 已
+ // 实际接受本次 send 后才执行 durable 群游标提交。回调失败不能反转
+ // 已受理 turn;旧游标会让下次最多重复携带,而不会永久跳过消息。
+ try {
+ await req.onProviderAccepted?.();
+ } catch (err) {
+ log.warn(
+ `provider-accepted callback failed for session=${session.id.slice(-8)}: ${
+ err instanceof Error ? err.message : String(err)
+ }`,
+ );
+ }
} catch (err) {
if (turnChangeSetStarted) clearPendingTurnChangeSets(session.id);
observer.stop();
diff --git a/apps/desktop/src/main/im/__tests__/connectionLifecycle.test.ts b/apps/desktop/src/main/im/__tests__/connectionLifecycle.test.ts
index fe3310111f..62494aff71 100644
--- a/apps/desktop/src/main/im/__tests__/connectionLifecycle.test.ts
+++ b/apps/desktop/src/main/im/__tests__/connectionLifecycle.test.ts
@@ -59,6 +59,21 @@ describe('serialized IM connection lifecycle', () => {
expect(stopConnection).toHaveBeenCalledTimes(2);
});
+ it('forwards the stop reason to the serialized connection teardown', async () => {
+ const stopConnection = vi.fn(async (_reason?: string) => undefined);
+ const lifecycle = createSerializedConnectionLifecycle({
+ startConnection: vi.fn(async () => undefined),
+ stopConnection,
+ onStartError: vi.fn(),
+ });
+
+ lifecycle.start();
+ await vi.waitFor(() => expect(lifecycle.isStarted()).toBe(true));
+ await lifecycle.stop('quit');
+
+ expect(stopConnection).toHaveBeenCalledWith('quit');
+ });
+
it('cancels a queued start when logout wins the race', async () => {
const startConnection = vi.fn(async () => undefined);
const stopConnection = vi.fn(async () => undefined);
diff --git a/apps/desktop/src/main/im/connectionLifecycle.ts b/apps/desktop/src/main/im/connectionLifecycle.ts
index 1c182d99ae..c5b4d1a709 100644
--- a/apps/desktop/src/main/im/connectionLifecycle.ts
+++ b/apps/desktop/src/main/im/connectionLifecycle.ts
@@ -5,7 +5,7 @@
*/
export interface SerializedConnectionLifecycle {
start(): void;
- stop(): Promise<void>;
+ stop(reason?: string): Promise<void>;
runWhileStarted<T>(operation: () => Promise<T>): Promise<T>;
isStarted(): boolean;
}
@@ -13,7 +13,7 @@ export interface SerializedConnectionLifecycle {
/** Dependencies are injected so lifecycle ordering stays unit-testable. */
export interface SerializedConnectionLifecycleDeps {
startConnection(): Promise<void>;
- stopConnection(): Promise<void>;
+ stopConnection(reason?: string): Promise<void>;
onStartError(error: unknown): void;
}
@@ -55,14 +55,14 @@ export function createSerializedConnectionLifecycle(
});
},
- async stop(): Promise<void> {
+ async stop(reason?: string): Promise<void> {
const shouldStopConnection = needsStop;
started = false;
needsStop = false;
generation += 1;
await enqueue(async () => {
if (!shouldStopConnection) return;
- await deps.stopConnection();
+ await deps.stopConnection(reason);
});
},
diff --git a/apps/desktop/src/main/im/index.ts b/apps/desktop/src/main/im/index.ts
index d643afb5ee..c620ac024e 100644
--- a/apps/desktop/src/main/im/index.ts
+++ b/apps/desktop/src/main/im/index.ts
@@ -550,7 +550,7 @@ async function reconcileOwnerScopedImWorkingDirs(): Promise<void> {
const connectionLifecycle = createSerializedConnectionLifecycle({
startConnection: initializeImConnection,
- stopConnection: async () => {
+ stopConnection: async (reason) => {
// Transports stop first so no new message can enter while account-scoped
// orchestrator and binding caches are being discarded.
try {
@@ -565,9 +565,10 @@ const connectionLifecycle = createSerializedConnectionLifecycle({
}
}
bindingStore.resetRuntime();
- // 群上下文游标是账号内存态 — 登出/换号必须清零, 防止新账号复用旧游标
- // 造成上下文窗口被静默跳过。
- resetTelegramGroupContextCursors();
+ // 普通退出、登出、换账号与模式切换都只清内存热缓存, 保留本地 DB 游标;
+ // 只有明确删除账号数据时才清持久表。Telegram bot 解绑由 hook-control 的
+ // binding identity reset 单独处理, 不把 auth logout 误当成数据删除。
+ await resetTelegramGroupContextCursors({ clearPersisted: reason === 'account-deletion' });
}
},
onStartError: (err) => {
@@ -651,5 +652,5 @@ export async function stopImConnection(reason: string): Promise<void> {
// are released, so old-account work cannot resume against a new account.
await waitForImAccountGenerationIdle(closingGeneration);
}
- await connectionLifecycle.stop();
+ await connectionLifecycle.stop(reason);
}
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
index b02a3f7ba6..3568245e0b 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
@@ -379,6 +379,7 @@ function setupSessionWithId(
interface TurnOverrides {
userMessageId?: string;
text?: string;
+ onRouteResolved?: (sessionId: string) => void | Promise<void>;
}
async function runDefaultTurn(
@@ -401,6 +402,7 @@ async function startDefaultTurn(
text: overrides.text ?? 'PROMPT_SECRET full user message TOKEN_VALUE file body',
attachments: [],
onTurnComplete,
+ ...(overrides.onRouteResolved ? { onRouteResolved: overrides.onRouteResolved } : {}),
});
return { onTurnComplete, turnPromise };
}
@@ -1010,11 +1012,13 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
const busy = new CredentialModeSwitchBusyError(['busy-session']);
mocks.getMaker.mockReturnValue(createMakerCreateSessionFailureHarness(busy));
const onTurnComplete = vi.fn();
+ const onRouteResolved = vi.fn();
- await runDefaultTurn(onTurnComplete);
+ await runDefaultTurn(onTurnComplete, { onRouteResolved });
await flushMicrotasks();
expect(onTurnComplete).toHaveBeenCalledTimes(1);
+ expect(onRouteResolved).not.toHaveBeenCalled();
expect(mocks.feishuIm.removeMessageReaction).toHaveBeenCalledWith('msg-user', 'reaction-1');
expect(mocks.feishuIm.sendText).toHaveBeenCalledWith(
'ou_user',
@@ -1032,18 +1036,23 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
mocks.feishuIm.reactToMessage.mockImplementation(async (messageId: string) => `reaction-${messageId}`);
const h = setupSession(async () => ({ accepted: true }));
const firstComplete = vi.fn();
+ const firstRouteResolved = vi.fn();
await runDefaultTurn(firstComplete, {
userMessageId: 'msg-first',
text: 'first user message',
+ onRouteResolved: firstRouteResolved,
});
expect(firstComplete).not.toHaveBeenCalled();
expect(h.send).toHaveBeenCalledTimes(1);
+ expect(firstRouteResolved).toHaveBeenCalledTimes(1);
const secondComplete = vi.fn();
+ const secondRouteResolved = vi.fn();
await runDefaultTurn(secondComplete, {
userMessageId: 'msg-second',
text: 'second user message',
+ onRouteResolved: secondRouteResolved,
});
await flushMicrotasks();
@@ -1053,6 +1062,7 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
expect(mocks.feishuIm.sendText).not.toHaveBeenCalled();
expect(mocks.feishuIm.sendMarkdownText).toHaveBeenCalledTimes(1);
expect(secondComplete).not.toHaveBeenCalled();
+ expect(secondRouteResolved).not.toHaveBeenCalled();
expect(mocks.persistUserMessage).toHaveBeenCalledTimes(1);
h.emit({
@@ -1072,6 +1082,7 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
});
expect(firstComplete).toHaveBeenCalledTimes(1);
+ expect(secondRouteResolved).toHaveBeenCalledTimes(1);
expect(mocks.feishuIm.removeMessageReaction).toHaveBeenCalledWith('msg-first', 'reaction-msg-first');
expect(mocks.persistUserMessage).toHaveBeenCalledTimes(2);
// assistant 落库收口在 messagePersistBroadcaster(经 wireSessionToIpcExternal),
@@ -1222,7 +1233,7 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
});
});
- it('reports the attached Desktop route before provider startup', async () => {
+ it('reports the attached Desktop route only after provider startup is accepted', async () => {
const h = setupAttachedSession(async () => ({ accepted: true }));
const onRouteResolved = vi.fn();
const beforeProviderStart = vi.fn(async () => undefined);
@@ -1240,7 +1251,7 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
expect(dispatch.kind).toBe('accepted');
expect(onRouteResolved).toHaveBeenCalledWith('desktop-attached-session');
- expect(onRouteResolved.mock.invocationCallOrder[0]).toBeLessThan(
+ expect(onRouteResolved.mock.invocationCallOrder[0]).toBeGreaterThan(
beforeProviderStart.mock.invocationCallOrder[0]!,
);
@@ -1854,7 +1865,7 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
it('does not report route resolution before auth passes on an existing route', async () => {
// 群窗口游标的 commit 挂在 onRouteResolved 上(prepareAgentTurnText 契约):
- // 鉴权失败被拒的消息若先触发它, 这批群上下文会被游标永久跳过。
+ // 受理前鉴权失败若先触发它, 这批群上下文会被游标永久跳过。
mocks.readXdGatewayApiKey.mockReturnValue(null);
mocks.findActiveSession.mockResolvedValue({
id: 'feishu-session',
@@ -1958,10 +1969,22 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
async (messageId: string) => `reaction-${messageId}`,
);
const h = setupSession(async () => ({ accepted: true }));
- await runDefaultTurn(vi.fn(), { userMessageId: 'msg-first', text: 'first user message' });
- await runDefaultTurn(vi.fn(), { userMessageId: 'msg-second', text: 'second user message' });
+ const firstRouteResolved = vi.fn();
+ await runDefaultTurn(vi.fn(), {
+ userMessageId: 'msg-first',
+ text: 'first user message',
+ onRouteResolved: firstRouteResolved,
+ });
+ const secondRouteResolved = vi.fn();
+ await runDefaultTurn(vi.fn(), {
+ userMessageId: 'msg-second',
+ text: 'second user message',
+ onRouteResolved: secondRouteResolved,
+ });
await flushMicrotasks();
expect(h.send).toHaveBeenCalledTimes(1);
+ expect(firstRouteResolved).toHaveBeenCalledTimes(1);
+ expect(secondRouteResolved).not.toHaveBeenCalled();
const result = await getRunner().stopActiveTurn({
botContextId: 'cli_test_bot',
@@ -1977,6 +2000,7 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
'reaction-msg-second',
);
});
+ expect(secondRouteResolved).not.toHaveBeenCalled();
// abort 触发的 done 不得把已丢弃的排队消息派发出去
h.emit({ type: 'done', data: {} });
diff --git a/apps/desktop/src/main/im/shared/groupWindowCore.ts b/apps/desktop/src/main/im/shared/groupWindowCore.ts
index a885f8a1d9..b7362f087e 100644
--- a/apps/desktop/src/main/im/shared/groupWindowCore.ts
+++ b/apps/desktop/src/main/im/shared/groupWindowCore.ts
@@ -1,15 +1,17 @@
/** 官方/个人 Telegram bot 群消息窗口共享核心;provider 必填且读写/GC 不跨命名空间。 */
-import { and, desc, eq, gt, lt, type SQL } from 'drizzle-orm';
+import { and, desc, eq, gt, like, lt, or, sql, type SQL } from 'drizzle-orm';
-import { getDbClient } from '../../localDb/client/current';
-import { hookGroupMessages } from '../../localDb/schema';
+import { getDbClient, tryGetDbClient } from '../../localDb/client/current';
+import { hookGroupContextCursors, hookGroupMessages } from '../../localDb/schema';
import type { Logger } from '../../logger';
export const GROUP_WINDOW_ENTRY_TEXT_MAX_CHARS = 500;
const CONTEXT_READ_LIMIT = 500;
const CONTEXT_MAX_CHARS = 4_000;
const CURSOR_MAX_KEYS = 1000;
+const CURSOR_ROLLBACK_MAX_ATTEMPTS = 3;
+const CURSOR_ROLLBACK_RETRY_DELAY_MS = 25;
export type GroupWindowRetentionPolicy = { keepPerKey: number; keepPerNamespace: number };
@@ -28,7 +30,23 @@ export interface GroupWindowEntryInput {
export interface GroupContextAssembly {
prefix: string;
/** 任务/消息被实际受理后调用;拒绝时不调用,未读批次留给下次触发。 */
- commit: () => void;
+ commit: (
+ guard?: GroupContextCommitGuard,
+ ) =>
+ | void
+ | GroupContextCommitReceipt
+ | Promise<void | GroupContextCommitReceipt>;
+}
+
+/**
+ * 可选的受理代次守卫。持久游标写入前后都会检查它;账号边界在中途失效时,
+ * commit 必须回滚自己刚写入的游标,避免“任务没跑但上下文已跳过”。
+ */
+export type GroupContextCommitGuard = () => boolean | Promise<boolean>;
+
+/** commit 已落下游标后的补偿句柄;只撤销本次写入,不覆盖并发推进的更高游标。 */
+export interface GroupContextCommitReceipt {
+ rollback(): Promise<void>;
}
interface GroupWindowRow {
@@ -60,7 +78,7 @@ export async function recordGroupWindowEntry(
chatName: entry.chatName,
author: entry.author.name,
isBot: entry.author.isBot === true ? 1 : 0,
- text: entry.text.slice(0, GROUP_WINDOW_ENTRY_TEXT_MAX_CHARS),
+ text: entry.text,
fileNames: entry.fileNames?.length ? JSON.stringify(entry.fileNames) : null,
sentAt: entry.sentAt,
createdAt: Date.now(),
@@ -108,6 +126,108 @@ export async function recordGroupWindowEntry(
return true;
}
+async function readPersistedCursor(provider: string, cursorKey: string): Promise<number> {
+ const rows = await getDbClient()
+ .drizzle.select({ cursorId: hookGroupContextCursors.cursorId })
+ .from(hookGroupContextCursors)
+ .where(
+ and(
+ eq(hookGroupContextCursors.provider, provider),
+ eq(hookGroupContextCursors.cursorKey, cursorKey),
+ ),
+ )
+ .limit(1);
+ return rows[0]?.cursorId ?? 0;
+}
+
+async function persistCursor(
+ provider: string,
+ cursorKey: string,
+ cursorId: number,
+ previousCursor: number,
+): Promise<number> {
+ const now = Date.now();
+ await getDbClient()
+ .drizzle.insert(hookGroupContextCursors)
+ .values({ provider, cursorKey, cursorId, updatedAt: now })
+ .onConflictDoUpdate({
+ target: [hookGroupContextCursors.provider, hookGroupContextCursors.cursorKey],
+ // Multiple lanes may finish close together. Never let an older commit
+ // move a durable cursor backwards.
+ set: {
+ cursorId: sql`MAX(cursor_id, excluded.cursor_id)`,
+ updatedAt: now,
+ },
+ });
+ // The UPSERT is the durable write boundary. Do not read the row back here:
+ // a successful write must still leave the caller with a rollback receipt if
+ // a subsequent read happens to fail. The in-memory value is monotonic, and
+ // a concurrent higher commit is protected by the update/rollback guards.
+ return Math.max(previousCursor, cursorId);
+}
+
+/**
+ * 仅在该行仍等于本次 commit 写入的 maxId 时回滚,避免覆盖并发任务已经推进的
+ * 更高游标。旧值为 0 时删除行,保持空游标的原始形态。
+ */
+async function rollbackPersistedCursor(
+ provider: string,
+ cursorKey: string,
+ maxId: number,
+ previousCursor: number,
+): Promise<number> {
+ const db = getDbClient().drizzle;
+ const rowFilter = and(
+ eq(hookGroupContextCursors.provider, provider),
+ eq(hookGroupContextCursors.cursorKey, cursorKey),
+ eq(hookGroupContextCursors.cursorId, maxId),
+ );
+ if (previousCursor > 0) {
+ await db
+ .update(hookGroupContextCursors)
+ .set({ cursorId: previousCursor, updatedAt: Date.now() })
+ .where(rowFilter);
+ } else {
+ await db.delete(hookGroupContextCursors).where(rowFilter);
+ }
+ return readPersistedCursor(provider, cursorKey);
+}
+
+function rememberCursor(cursors: Map<string, number>, cursorKey: string, cursor: number): void {
+ cursors.set(cursorKey, cursor);
+ if (cursors.size <= CURSOR_MAX_KEYS) return;
+ const oldest = cursors.keys().next().value;
+ if (oldest !== undefined) cursors.delete(oldest);
+}
+
+/** 清理指定 provider 命名空间的内存态与持久游标。 */
+export async function resetGroupWindowCursors(args: {
+ cursors: Map<string, number>;
+ providerPrefixes: readonly string[];
+ providerNames?: readonly string[];
+ clearPersisted?: boolean;
+}): Promise<void> {
+ args.cursors.clear();
+ if (
+ args.clearPersisted === false ||
+ (args.providerPrefixes.length === 0 && (args.providerNames?.length ?? 0) === 0)
+ )
+ return;
+ const filters = [
+ ...args.providerPrefixes.map((prefix) =>
+ like(hookGroupContextCursors.provider, `${prefix}%`),
+ ),
+ ...(args.providerNames ?? []).map((provider) =>
+ eq(hookGroupContextCursors.provider, provider),
+ ),
+ ];
+ const dbClient = tryGetDbClient();
+ if (!dbClient) return;
+ await dbClient
+ .drizzle.delete(hookGroupContextCursors)
+ .where(filters.length === 1 ? filters[0] : or(...filters));
+}
+
async function readRows(args: {
provider: string;
chatId: string;
@@ -146,7 +266,9 @@ export async function assembleGroupWindowContext(args: {
neutralize: (value: string) => string;
log: Logger;
}): Promise<GroupContextAssembly> {
- const cursor = args.cursors.get(args.cursorKey) ?? 0;
+ const inMemoryCursor = args.cursors.get(args.cursorKey);
+ const cursor = inMemoryCursor ?? (await readPersistedCursor(args.provider, args.cursorKey));
+ if (inMemoryCursor === undefined) rememberCursor(args.cursors, args.cursorKey, cursor);
const read = (threadFilter: SQL<unknown>) =>
readRows({ provider: args.provider, chatId: args.chatId, threadFilter, cursor });
const primaryRows = await read(eq(hookGroupMessages.threadId, args.threadId));
@@ -169,7 +291,9 @@ export async function assembleGroupWindowContext(args: {
/* 老行损坏时静默丢附件标注 */
}
}
- const line = args.neutralize(`[${row.author}] ${row.text}${fileNote}`);
+ const line = args.neutralize(
+ `[${row.author}] ${row.text.slice(0, GROUP_WINDOW_ENTRY_TEXT_MAX_CHARS)}${fileNote}`,
+ );
if (totalChars + line.length > CONTEXT_MAX_CHARS) {
truncated = true;
break;
@@ -185,13 +309,79 @@ export async function assembleGroupWindowContext(args: {
const commit =
maxId > cursor
- ? (): void => {
+ ? async (
+ guard?: GroupContextCommitGuard,
+ ): Promise<void | GroupContextCommitReceipt> => {
const current = args.cursors.get(args.cursorKey) ?? 0;
if (maxId <= current) return;
- args.cursors.set(args.cursorKey, maxId);
- if (args.cursors.size > CURSOR_MAX_KEYS) {
- const oldest = args.cursors.keys().next().value;
- if (oldest !== undefined) args.cursors.delete(oldest);
+ if (guard !== undefined && !(await guard())) return;
+ try {
+ const previousDurableCursor = await readPersistedCursor(args.provider, args.cursorKey);
+ const durableCursor = await persistCursor(
+ args.provider,
+ args.cursorKey,
+ maxId,
+ previousDurableCursor,
+ );
+ let rolledBack = false;
+ const receipt: GroupContextCommitReceipt = {
+ rollback: async (): Promise<void> => {
+ if (rolledBack) return;
+ let lastError: unknown;
+ for (let attempt = 0; attempt < CURSOR_ROLLBACK_MAX_ATTEMPTS; attempt += 1) {
+ try {
+ const restoredDurableCursor = await rollbackPersistedCursor(
+ args.provider,
+ args.cursorKey,
+ maxId,
+ previousDurableCursor,
+ );
+ const latest = args.cursors.get(args.cursorKey) ?? 0;
+ if (latest <= maxId) {
+ rememberCursor(
+ args.cursors,
+ args.cursorKey,
+ Math.max(current, restoredDurableCursor),
+ );
+ }
+ // Keep the receipt live until the durable restore has
+ // completed. A transient SQLite failure must leave the
+ // caller able to retry the compensation instead of
+ // silently turning a failed rollback into a permanent
+ // cursor advance.
+ rolledBack = true;
+ return;
+ } catch (error) {
+ lastError = error;
+ if (attempt + 1 < CURSOR_ROLLBACK_MAX_ATTEMPTS) {
+ await new Promise<void>((resolve) =>
+ setTimeout(resolve, CURSOR_ROLLBACK_RETRY_DELAY_MS * (attempt + 1)),
+ );
+ }
+ }
+ }
+ const rollbackError =
+ lastError instanceof Error ? lastError : new Error(String(lastError));
+ args.log.warn(`group context cursor rollback failed: ${rollbackError.message}`);
+ // Do not report compensation as successful after the bounded
+ // retry budget is exhausted. Callers must keep the failure
+ // visible rather than discarding an unexecuted task as if its
+ // durable cursor had been restored.
+ throw rollbackError;
+ },
+ };
+ if (guard !== undefined && !(await guard())) {
+ await receipt.rollback();
+ return;
+ }
+ const latest = args.cursors.get(args.cursorKey) ?? 0;
+ if (durableCursor > latest) rememberCursor(args.cursors, args.cursorKey, durableCursor);
+ return receipt;
+ } catch (error) {
+ // Durable cursor failure must not turn an already-routable message
+ // into a stuck queue/running slot. Keep the old in-memory cursor so
+ // the same batch is retried on the next trigger.
+ args.log.warn(`group context cursor persist failed: ${String(error)}`);
}
}
: (): void => undefined;
diff --git a/apps/desktop/src/main/im/shared/messageHandler.ts b/apps/desktop/src/main/im/shared/messageHandler.ts
index cb0deb79c6..2bd7f19423 100644
--- a/apps/desktop/src/main/im/shared/messageHandler.ts
+++ b/apps/desktop/src/main/im/shared/messageHandler.ts
@@ -194,7 +194,7 @@ export function createMessageHandler(
// ── invoke agent ────────────────────────────────────────────────────────
// 送模型正文改写钩子(群上下文拼装): 失败按"不改写"降级, 不阻断消息。
- let prepared: { agentText: string; commit?: () => void } | null = null;
+ let prepared: { agentText: string; commit?: () => void | Promise<void> } | null = null;
if (adapter.prepareAgentTurnText) {
try {
prepared = await adapter.prepareAgentTurnText(event);
@@ -215,9 +215,11 @@ export function createMessageHandler(
...(prepared ? { agentText: prepared.agentText } : {}),
...(prepared?.commit
? {
- // 路由解析成功 = 消息确定会被派发/排队 — 群窗口游标此刻才推进,
- // 路由失败(鉴权缺失等)不推进, 上下文批次下次仍进 prompt。
- onRouteResolved: () => prepared?.commit?.(),
+ // turnRunner 只在 provider 真正接受消息后调用;排队、停止与
+ // teardown 都不推进游标, 受理前失败时上下文批次下次仍进 prompt。
+ onRouteResolved: async () => {
+ await prepared?.commit?.();
+ },
}
: {}),
attachments: event.attachments,
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index c65cea8a0b..528bb37292 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -227,6 +227,8 @@ interface QueuedSend {
notified: boolean;
queueMode: 'internal' | 'external';
beforeProviderStart?: () => Promise<void>;
+ /** Durable route side effects run only after provider acceptance, never on enqueue. */
+ onRouteResolved?: (sessionId: string) => void | Promise<void>;
turnPermissionPolicy?: TurnPermissionPolicy;
}
@@ -326,8 +328,8 @@ export interface ImRunAgentTurnArgs {
outputCardMessageId?: string;
outputCardPrefix?: string;
onTurnComplete?: () => void;
- /** Reports the concrete channel/default or attached Desktop session before provider startup. */
- onRouteResolved?: (sessionId: string) => void;
+ /** Reports the concrete session only after the provider accepts this message. */
+ onRouteResolved?: (sessionId: string) => void | Promise<void>;
/** Keep fire-and-forget work inside the ingress account's drain boundary. */
trackBackgroundTask?: (operation: () => Promise<void>) => void;
/** Optional per-turn host policy (personal WeChat routes confirmations to Desktop). */
@@ -599,10 +601,6 @@ export function createTurnRunner(
return { kind: 'rejected', reason: 'missing_auth' };
}
}
- // onRouteResolved 必须在鉴权通过之后才算"路由解析成功" —— 群窗口游标的
- // commit 挂在它上面, 鉴权失败被拒的消息若先触发它, 这批群上下文会被游标
- // 永久跳过(prepareAgentTurnText 的契约: 路由失败不推进游标)。
- args.onRouteResolved?.(row.id);
// ── thread 名片卡(threadScoped 新 thread 会话)─────────────────────────
// 在 bot 第一条回复之前发进 thread, 让用户第一眼理解"这个 thread = 一条
// 独立会话";首条消息的 oneshot 标题生成完成后, 名片原地升级为正式标题
@@ -744,6 +742,7 @@ export function createTurnRunner(
notified: false,
queueMode: args.queueMode,
...(args.beforeProviderStart ? { beforeProviderStart: args.beforeProviderStart } : {}),
+ ...(args.onRouteResolved ? { onRouteResolved: args.onRouteResolved } : {}),
...(turnPermissionPolicy ? { turnPermissionPolicy } : {}),
};
@@ -930,6 +929,18 @@ export function createTurnRunner(
});
return { kind: 'rejected', reason: outcome.reason };
}
+ // Route side effects include the durable group cursor commit. The
+ // provider has accepted this send now; invoking the callback here keeps
+ // queued teardown and SESSION_RUNNING requeue paths from advancing it.
+ try {
+ await item.onRouteResolved?.(rowId);
+ } catch (err) {
+ log.warn(
+ `route-resolved callback failed for session=${rowId.slice(-8)}: ${
+ err instanceof Error ? err.message : String(err)
+ }`,
+ );
+ }
return { kind: 'accepted', acceptedAt: acceptedAt || Date.now() };
} catch (err) {
if (turnChangeSetStarted) clearPendingTurnChangeSets(rowId);
diff --git a/apps/desktop/src/main/im/shared/types.ts b/apps/desktop/src/main/im/shared/types.ts
index 6e19a60535..664170a215 100644
--- a/apps/desktop/src/main/im/shared/types.ts
+++ b/apps/desktop/src/main/im/shared/types.ts
@@ -150,13 +150,13 @@ export interface ImChannelAdapter {
/**
* 送模型正文的改写钩子(群上下文拼装等): 返回 agentText 替换发给 agent 的
* 文本 —— 落库与标题生成仍用渠道原文, 桌面 transcript 不被上下文前缀污染。
- * commit 在路由解析成功(消息确定会被派发/排队)时调用, 是群窗口游标推进的
- * 时机锚点; 路由失败(如鉴权缺失)不调用, 这批上下文下次仍会进入 prompt。
+ * commit 在消息完成鉴权、session wiring 且确定被派发/排队后调用, 是群窗口
+ * 游标推进的时机锚点; 受理前失败不调用, 这批上下文下次仍会进入 prompt。
* 返回 null = 不改写。钩子抛错按"不改写"降级, 不阻断消息。
*/
prepareAgentTurnText?(event: IMMessageEvent): Promise<{
agentText: string;
- commit?: () => void;
+ commit?: () => void | Promise<void>;
} | null>;
/**
* 按入站事件给该轮挂 per-turn 权限策略(telegram 群成员触发 → 破坏性调用
diff --git a/apps/desktop/src/main/im/telegram/__tests__/groupWindow.test.ts b/apps/desktop/src/main/im/telegram/__tests__/groupWindow.test.ts
index 35e0701108..ef6bbe8e24 100644
--- a/apps/desktop/src/main/im/telegram/__tests__/groupWindow.test.ts
+++ b/apps/desktop/src/main/im/telegram/__tests__/groupWindow.test.ts
@@ -2,7 +2,7 @@
* 个人 Telegram 群窗口单测: 入窗幂等、按键 GC、TTL、上下文拼装(trigger 剔重 /
* 游标 commit 延迟 / 字符预算 / 栅栏中和)、与官方通道行(provider='telegram')
* 的隔离。harness 与 hook-control/groupWindow.test.ts 同款: 内存 better-sqlite3
- * 执行 0083 migration, drizzle 同步 driver 假装 DbClient。
+ * 执行 0083 + 0086 migration, drizzle 同步 driver 假装 DbClient。
*/
import fs from 'node:fs';
@@ -18,6 +18,7 @@ const holder = vi.hoisted(() => ({ drizzle: null as unknown }));
vi.mock('../../../localDb/client/current', () => ({
getDbClient: () => ({ drizzle: holder.drizzle }),
+ tryGetDbClient: () => ({ drizzle: holder.drizzle }),
}));
import {
@@ -30,9 +31,14 @@ import {
function migrationSql(): string {
const dir = path.resolve(__dirname, '../../../../../drizzle');
- const file = fs.readdirSync(dir).find((name) => name.startsWith('0083_'));
- if (!file) throw new Error('0083 migration not found');
- return fs.readFileSync(path.join(dir, file), 'utf8').replaceAll('--> statement-breakpoint', ';');
+ return ['0083_', '0086_']
+ .map((prefix) => {
+ const file = fs.readdirSync(dir).find((name) => name.startsWith(prefix));
+ if (!file) throw new Error(`${prefix} migration not found`);
+ return fs.readFileSync(path.join(dir, file), 'utf8');
+ })
+ .join('\n')
+ .replaceAll('--> statement-breakpoint', ';');
}
let entrySeq = 0;
@@ -56,11 +62,11 @@ const LANE = { botId: 'bot-1', chatId: '-900', threadId: '' };
let sqlite: InstanceType<typeof Database>;
-beforeEach(() => {
+beforeEach(async () => {
sqlite = new Database(':memory:');
sqlite.exec(migrationSql());
holder.drizzle = drizzle(sqlite);
- resetTelegramGroupContextCursors();
+ await resetTelegramGroupContextCursors();
});
afterEach(() => {
@@ -102,6 +108,48 @@ describe('recordTelegramGroupMessage', () => {
};
expect(row.is_bot).toBe(1);
});
+
+ it('正文全文入库, 但拼 prompt 仍按 500 字符截断', async () => {
+ const text = 'x'.repeat(700);
+ await recordTelegramGroupMessage(entry({ messageId: 'long', text }));
+ const row = sqlite
+ .prepare('SELECT text FROM hook_group_messages WHERE message_id = ?')
+ .get('long') as { text: string };
+ expect(row.text).toBe(text);
+
+ const prefix = (
+ await buildTelegramGroupContextPrefix({ ...LANE, triggerMessageId: 'none' })
+ ).prefix;
+ expect(prefix).toContain('x'.repeat(500));
+ expect(prefix).not.toContain('x'.repeat(501));
+ });
+
+ it('重置只删除个人 Telegram provider 的持久游标', async () => {
+ await recordTelegramGroupMessage(entry({ messageId: 'cursor-reset' }));
+ const assembly = await buildTelegramGroupContextPrefix({
+ ...LANE,
+ triggerMessageId: 'none',
+ });
+ await assembly.commit();
+ sqlite
+ .prepare(
+ `INSERT INTO hook_group_context_cursors
+ (provider, cursor_key, cursor_id, updated_at) VALUES (?, ?, ?, ?)`,
+ )
+ .run('telegram:9', 'telegram:group:1:-900:9', 99, Date.now());
+
+ await resetTelegramGroupContextCursors();
+ expect(
+ sqlite
+ .prepare('SELECT 1 FROM hook_group_context_cursors WHERE provider = ?')
+ .get('telegram-personal:bot-1'),
+ ).toBeUndefined();
+ expect(
+ sqlite
+ .prepare('SELECT cursor_id FROM hook_group_context_cursors WHERE provider = ?')
+ .get('telegram:9') as { cursor_id: number },
+ ).toEqual({ cursor_id: 99 });
+ });
});
describe('buildTelegramGroupContextPrefix', () => {
@@ -124,7 +172,17 @@ describe('buildTelegramGroupContextPrefix', () => {
// 不 commit → 第二次拼装仍包含
const again = await buildTelegramGroupContextPrefix({ ...LANE, triggerMessageId: 't1' });
expect(again.prefix).toContain('旧消息');
- again.commit();
+ await again.commit();
+ expect(
+ sqlite
+ .prepare(
+ 'SELECT cursor_id FROM hook_group_context_cursors WHERE provider = ? AND cursor_key = ?',
+ )
+ .get('telegram-personal:bot-1', 'bot-1:-900:') as { cursor_id: number },
+ ).toEqual({ cursor_id: 1 });
+
+ // 模拟进程重启: 清掉内存态但保留 DB, 恢复后不重复已提交消息。
+ await resetTelegramGroupContextCursors({ clearPersisted: false });
// commit 后 → 增量为空
const after = await buildTelegramGroupContextPrefix({ ...LANE, triggerMessageId: 't2' });
expect(after.prefix).toBe('');
@@ -135,7 +193,7 @@ describe('buildTelegramGroupContextPrefix', () => {
await recordTelegramGroupMessage(entry({ messageId: 'only', text: '@bot hi' }));
const asm = await buildTelegramGroupContextPrefix({ ...LANE, triggerMessageId: 'only' });
expect(asm.prefix).toBe('');
- asm.commit();
+ await asm.commit();
await recordTelegramGroupMessage(entry({ messageId: 'next', text: '新消息' }));
const after = await buildTelegramGroupContextPrefix({ ...LANE, triggerMessageId: 't' });
expect(after.prefix).toContain('新消息');
diff --git a/apps/desktop/src/main/im/telegram/adapter.ts b/apps/desktop/src/main/im/telegram/adapter.ts
index 85215b34e6..42dd2aa8d7 100644
--- a/apps/desktop/src/main/im/telegram/adapter.ts
+++ b/apps/desktop/src/main/im/telegram/adapter.ts
@@ -139,7 +139,9 @@ export function buildTelegramAdapter(
// 顺序: 群窗口(较远的背景) → 引用块(直接相关) → 发言人 → 用户正文。
return {
agentText: `${persona}${ambientBlock}${assembly.prefix}${replyBlock}${speakerLine}${event.text}`,
- commit: assembly.commit,
+ commit: async () => {
+ await assembly.commit();
+ },
};
},
};
diff --git a/apps/desktop/src/main/im/telegram/groupWindow.ts b/apps/desktop/src/main/im/telegram/groupWindow.ts
index f7a6202a46..e8a3db5f6e 100644
--- a/apps/desktop/src/main/im/telegram/groupWindow.ts
+++ b/apps/desktop/src/main/im/telegram/groupWindow.ts
@@ -24,6 +24,7 @@ import {
createFenceNeutralizer,
GROUP_WINDOW_ENTRY_TEXT_MAX_CHARS,
recordGroupWindowEntry,
+ resetGroupWindowCursors,
type GroupContextAssembly,
} from '../shared/groupWindowCore';
import { getDbClient } from '../../localDb/client/current';
@@ -69,8 +70,8 @@ export async function recordTelegramGroupMessage(entry: TelegramGroupWindowEntry
}
/**
- * 每 lane 的增量游标(上次拼装到的窗口行 id)。内存态: 重启后首次触发会
- * 重新包含整个窗口(一次性冗余, 可接受), 之后恢复增量语义。
+ * 每 lane 的增量游标(上次拼装到的窗口行 id)。内存态只作热缓存, 持久事实在
+ * hook_group_context_cursors; 重启后首次触发从本地 DB 恢复增量语义。
*/
const contextCursors = new Map<string, number>();
@@ -134,9 +135,16 @@ export async function buildTelegramGroupContextPrefix(args: {
});
}
-/** 测试与登出清理: 重置内存游标(窗口行随账号 DB 生命周期)。 */
-export function resetTelegramGroupContextCursors(): void {
- contextCursors.clear();
+/** 测试与登出清理: 只清理个人 Telegram provider 的内存态与持久游标。 */
+export function resetTelegramGroupContextCursors(options?: {
+ clearPersisted?: boolean;
+}): Promise<void> {
+ return resetGroupWindowCursors({
+ cursors: contextCursors,
+ providerPrefixes: ['telegram-personal:'],
+ providerNames: [TELEGRAM_PERSONAL_WINDOW_PROVIDER],
+ ...(options?.clearPersisted === false ? { clearPersisted: false } : {}),
+ });
}
/**
diff --git a/apps/desktop/src/main/im/wechat/WechatIM.ts b/apps/desktop/src/main/im/wechat/WechatIM.ts
index f254b2199b..9d8f290ea1 100644
--- a/apps/desktop/src/main/im/wechat/WechatIM.ts
+++ b/apps/desktop/src/main/im/wechat/WechatIM.ts
@@ -96,6 +96,16 @@ interface ActiveTask {
terminalCommitted: boolean;
}
+function activePeerIdForSession<
+ T extends { routeSessionId?: string; task: { sessionId: string } },
+>(activeTasks: ReadonlyMap<string, T>, sessionId: string | undefined): string | null {
+ if (!sessionId) return null;
+ const peers = [...activeTasks.entries()]
+ .filter(([, active]) => (active.routeSessionId ?? active.task.sessionId) === sessionId)
+ .map(([peerId]) => peerId);
+ return peers.length === 1 ? peers[0]! : null;
+}
+
interface PendingWechatInteraction {
request: InteractionRequest;
resolve: (decision: InteractionDecision) => void;
@@ -466,13 +476,7 @@ export class WechatIM extends BaseIM implements RichChannelIM {
}
getActivePeerIdForSession(sessionId: string | undefined): string | null {
- if (!sessionId) return null;
- const peers = [...this.#activeTasks.entries()]
- .filter(
- ([, active]) => (active.routeSessionId ?? active.task.sessionId) === sessionId,
- )
- .map(([peerId]) => peerId);
- return peers.length === 1 ? peers[0]! : null;
+ return activePeerIdForSession(this.#activeTasks, sessionId);
}
async handleTextInteraction(
@@ -1973,6 +1977,7 @@ function machineErrorCode(error: unknown): string {
}
export const __testing = {
+ activePeerIdForSession,
acceptedPollTaskIds,
authorizationCancelPhase,
classifyOutboxSendError,
diff --git a/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts b/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts
index e6c36b9aea..8783d7e9ce 100644
--- a/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts
+++ b/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts
@@ -75,6 +75,26 @@ describe('WechatIM host boundary', () => {
).toBe(true);
});
+ it('排队等待 provider 受理时按 task session 回退微信 peer', () => {
+ const activeTasks = new Map<
+ string,
+ { routeSessionId?: string; task: { sessionId: string } }
+ >([
+ ['peer-queued', { task: { sessionId: 'wechat-task-session' } }],
+ ['peer-other', { task: { sessionId: 'other-session' } }],
+ ]);
+
+ expect(__testing.activePeerIdForSession(activeTasks, 'wechat-task-session')).toBe(
+ 'peer-queued',
+ );
+
+ activeTasks.get('peer-queued')!.routeSessionId = 'accepted-route-session';
+ expect(__testing.activePeerIdForSession(activeTasks, 'wechat-task-session')).toBeNull();
+ expect(__testing.activePeerIdForSession(activeTasks, 'accepted-route-session')).toBe(
+ 'peer-queued',
+ );
+ });
+
it('keeps staged files only for accepted poll tasks', () => {
const accepted = __testing.acceptedPollTaskIds({
committed: true,
diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.ts
index 9067c02be4..6bae90efc9 100644
--- a/apps/desktop/src/main/localDb/schema.ts
+++ b/apps/desktop/src/main/localDb/schema.ts
@@ -1520,3 +1520,20 @@ export const hookGroupMessages = sqliteTable(
byWindow: index('hook_group_messages_window_idx').on(t.provider, t.chatId, t.threadId, t.id),
}),
);
+
+/**
+ * 群消息窗口的已提交游标。游标与消息池同属本地 DB,但按 provider 命名空间
+ * 隔离,登出/换绑时只清理对应 bot 的行。
+ */
+export const hookGroupContextCursors = sqliteTable(
+ 'hook_group_context_cursors',
+ {
+ provider: text('provider').notNull(),
+ cursorKey: text('cursor_key').notNull(),
+ cursorId: integer('cursor_id').notNull(),
+ updatedAt: integer('updated_at').notNull(),
+ },
+ (t) => ({
+ pk: primaryKey({ columns: [t.provider, t.cursorKey] }),
+ }),
+);