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): 渠道默认模型同时管到仍跟随默认的已有任务 (#5155)

Lizifaff4c71e419
diff --git a/apps/desktop/drizzle/0119_hard_vindicator.sql b/apps/desktop/drizzle/0119_hard_vindicator.sql
new file mode 100644
index 0000000000..79dcce5b28
--- /dev/null
+++ b/apps/desktop/drizzle/0119_hard_vindicator.sql
@@ -0,0 +1 @@
+ALTER TABLE `sessions` ADD `im_default_route` text;
\ No newline at end of file
diff --git a/apps/desktop/drizzle/meta/0119_snapshot.json b/apps/desktop/drizzle/meta/0119_snapshot.json
new file mode 100644
index 0000000000..89f2c4557a
--- /dev/null
+++ b/apps/desktop/drizzle/meta/0119_snapshot.json
@@ -0,0 +1,6636 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "ee1f5fc9-e9de-4252-a505-65045e2f5e61",
+ "prevId": "cbc1b27d-dd3b-475c-abce-7ab49f9aa98e",
+ "tables": {
+ "account_usage_snapshots": {
+ "name": "account_usage_snapshots",
+ "columns": {
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "snapshot": {
+ "name": "snapshot",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "agent_input_queue_snapshots": {
+ "name": "agent_input_queue_snapshots",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "agent_input_queue_snapshots_session_id_sessions_id_fk": {
+ "name": "agent_input_queue_snapshots_session_id_sessions_id_fk",
+ "tableFrom": "agent_input_queue_snapshots",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_delegations": {
+ "name": "bot_delegations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "requesting_bot_id": {
+ "name": "requesting_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "target_bot_id": {
+ "name": "target_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "parent_session_id": {
+ "name": "parent_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "child_session_id": {
+ "name": "child_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "objective": {
+ "name": "objective",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_refs_json": {
+ "name": "context_refs_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "artifact_refs_json": {
+ "name": "artifact_refs_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "permission_snapshot_json": {
+ "name": "permission_snapshot_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "lineage_json": {
+ "name": "lineage_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "target_profile_version": {
+ "name": "target_profile_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "depth": {
+ "name": "depth",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "budget_tokens": {
+ "name": "budget_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tokens_used": {
+ "name": "tokens_used",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "result_summary": {
+ "name": "result_summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "output_artifacts_json": {
+ "name": "output_artifacts_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "pending_interaction_json": {
+ "name": "pending_interaction_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "run_sequence": {
+ "name": "run_sequence",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "accepted_at": {
+ "name": "accepted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "completion_delivered_at": {
+ "name": "completion_delivered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_delegations_requester_status": {
+ "name": "idx_bot_delegations_requester_status",
+ "columns": [
+ "requesting_bot_id",
+ "status"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_delegations_target_status": {
+ "name": "idx_bot_delegations_target_status",
+ "columns": [
+ "target_bot_id",
+ "status"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_delegations_parent_session": {
+ "name": "idx_bot_delegations_parent_session",
+ "columns": [
+ "parent_session_id"
+ ],
+ "isUnique": false
+ },
+ "uniq_bot_delegations_child_session": {
+ "name": "uniq_bot_delegations_child_session",
+ "columns": [
+ "child_session_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "bot_delegations_requesting_bot_id_bot_profiles_id_fk": {
+ "name": "bot_delegations_requesting_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_delegations",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "requesting_bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_delegations_target_bot_id_bot_profiles_id_fk": {
+ "name": "bot_delegations_target_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_delegations",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "target_bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_delegations_parent_session_id_sessions_id_fk": {
+ "name": "bot_delegations_parent_session_id_sessions_id_fk",
+ "tableFrom": "bot_delegations",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "parent_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "bot_delegations_child_session_id_sessions_id_fk": {
+ "name": "bot_delegations_child_session_id_sessions_id_fk",
+ "tableFrom": "bot_delegations",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "child_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_direct_message_threads": {
+ "name": "bot_direct_message_threads",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_a_id": {
+ "name": "bot_a_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_b_id": {
+ "name": "bot_b_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "close_reason": {
+ "name": "close_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "message_count": {
+ "name": "message_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "max_messages": {
+ "name": "max_messages",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "blocked_until": {
+ "name": "blocked_until",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "closed_at": {
+ "name": "closed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_bot_dm_threads_active_pair": {
+ "name": "uniq_bot_dm_threads_active_pair",
+ "columns": [
+ "bot_a_id",
+ "bot_b_id"
+ ],
+ "isUnique": true,
+ "where": "\"bot_direct_message_threads\".\"status\" = 'active'"
+ },
+ "idx_bot_dm_threads_pair_updated": {
+ "name": "idx_bot_dm_threads_pair_updated",
+ "columns": [
+ "bot_a_id",
+ "bot_b_id",
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_direct_messages": {
+ "name": "bot_direct_messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "thread_id": {
+ "name": "thread_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sequence": {
+ "name": "sequence",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sender_bot_id": {
+ "name": "sender_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "recipient_bot_id": {
+ "name": "recipient_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sender_session_id": {
+ "name": "sender_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "recipient_session_id": {
+ "name": "recipient_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "delivery_status": {
+ "name": "delivery_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "sender_name": {
+ "name": "sender_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "recipient_name": {
+ "name": "recipient_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "bridge_session_id": {
+ "name": "bridge_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_bot_direct_messages_thread_sequence": {
+ "name": "uniq_bot_direct_messages_thread_sequence",
+ "columns": [
+ "thread_id",
+ "sequence"
+ ],
+ "isUnique": true
+ },
+ "idx_bot_direct_messages_thread_created": {
+ "name": "idx_bot_direct_messages_thread_created",
+ "columns": [
+ "thread_id",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_direct_messages_thread_id_bot_direct_message_threads_id_fk": {
+ "name": "bot_direct_messages_thread_id_bot_direct_message_threads_id_fk",
+ "tableFrom": "bot_direct_messages",
+ "tableTo": "bot_direct_message_threads",
+ "columnsFrom": [
+ "thread_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_direct_messages_sender_session_id_sessions_id_fk": {
+ "name": "bot_direct_messages_sender_session_id_sessions_id_fk",
+ "tableFrom": "bot_direct_messages",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "sender_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "bot_direct_messages_recipient_session_id_sessions_id_fk": {
+ "name": "bot_direct_messages_recipient_session_id_sessions_id_fk",
+ "tableFrom": "bot_direct_messages",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "recipient_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_group_members": {
+ "name": "bot_group_members",
+ "columns": {
+ "group_id": {
+ "name": "group_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_seen_sequence": {
+ "name": "last_seen_sequence",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "joined_at": {
+ "name": "joined_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_group_members_bot": {
+ "name": "idx_bot_group_members_bot",
+ "columns": [
+ "bot_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_group_members_group_id_bot_groups_id_fk": {
+ "name": "bot_group_members_group_id_bot_groups_id_fk",
+ "tableFrom": "bot_group_members",
+ "tableTo": "bot_groups",
+ "columnsFrom": [
+ "group_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_group_members_bot_id_bot_profiles_id_fk": {
+ "name": "bot_group_members_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_group_members",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "bot_group_members_group_id_bot_id_pk": {
+ "columns": [
+ "group_id",
+ "bot_id"
+ ],
+ "name": "bot_group_members_group_id_bot_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_group_messages": {
+ "name": "bot_group_messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "group_id": {
+ "name": "group_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sequence": {
+ "name": "sequence",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'message'"
+ },
+ "author_kind": {
+ "name": "author_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "author_bot_id": {
+ "name": "author_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "author_name": {
+ "name": "author_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "mentions_json": {
+ "name": "mentions_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{\"all\":false,\"botIds\":[]}'"
+ },
+ "notice_code": {
+ "name": "notice_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "plan_id": {
+ "name": "plan_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "files_json": {
+ "name": "files_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_bot_group_messages_group_sequence": {
+ "name": "uniq_bot_group_messages_group_sequence",
+ "columns": [
+ "group_id",
+ "sequence"
+ ],
+ "isUnique": true
+ },
+ "uniq_bot_group_messages_group_client": {
+ "name": "uniq_bot_group_messages_group_client",
+ "columns": [
+ "group_id",
+ "client_id"
+ ],
+ "isUnique": true,
+ "where": "\"bot_group_messages\".\"client_id\" IS NOT NULL"
+ }
+ },
+ "foreignKeys": {
+ "bot_group_messages_group_id_bot_groups_id_fk": {
+ "name": "bot_group_messages_group_id_bot_groups_id_fk",
+ "tableFrom": "bot_group_messages",
+ "tableTo": "bot_groups",
+ "columnsFrom": [
+ "group_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_group_plan_steps": {
+ "name": "bot_group_plan_steps",
+ "columns": {
+ "plan_id": {
+ "name": "plan_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_name": {
+ "name": "bot_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task": {
+ "name": "task",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "result_message_id": {
+ "name": "result_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "bot_group_plan_steps_plan_id_bot_group_plans_id_fk": {
+ "name": "bot_group_plan_steps_plan_id_bot_group_plans_id_fk",
+ "tableFrom": "bot_group_plan_steps",
+ "tableTo": "bot_group_plans",
+ "columnsFrom": [
+ "plan_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "bot_group_plan_steps_plan_id_position_pk": {
+ "columns": [
+ "plan_id",
+ "position"
+ ],
+ "name": "bot_group_plan_steps_plan_id_position_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_group_plans": {
+ "name": "bot_group_plans",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "group_id": {
+ "name": "group_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "request_text": {
+ "name": "request_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organizer_bot_id": {
+ "name": "organizer_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organizer_name": {
+ "name": "organizer_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "current_step": {
+ "name": "current_step",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "work_dir": {
+ "name": "work_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "branch": {
+ "name": "branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_group_plans_group_created": {
+ "name": "idx_bot_group_plans_group_created",
+ "columns": [
+ "group_id",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_group_plans_group_id_bot_groups_id_fk": {
+ "name": "bot_group_plans_group_id_bot_groups_id_fk",
+ "tableFrom": "bot_group_plans",
+ "tableTo": "bot_groups",
+ "columnsFrom": [
+ "group_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_groups": {
+ "name": "bot_groups",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "reply_mode": {
+ "name": "reply_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'all'"
+ },
+ "speaking_mode": {
+ "name": "speaking_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'auto'"
+ },
+ "organizer_bot_id": {
+ "name": "organizer_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "project_dir": {
+ "name": "project_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_groups_updated": {
+ "name": "idx_bot_groups_updated",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_lifecycle_events": {
+ "name": "bot_lifecycle_events",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "event_type": {
+ "name": "event_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload_json": {
+ "name": "payload_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_lifecycle_events_bot_created": {
+ "name": "idx_bot_lifecycle_events_bot_created",
+ "columns": [
+ "bot_id",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_lifecycle_events_session_created": {
+ "name": "idx_bot_lifecycle_events_session_created",
+ "columns": [
+ "session_id",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_lifecycle_events_bot_id_bot_profiles_id_fk": {
+ "name": "bot_lifecycle_events_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_lifecycle_events",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_lifecycle_events_session_id_sessions_id_fk": {
+ "name": "bot_lifecycle_events_session_id_sessions_id_fk",
+ "tableFrom": "bot_lifecycle_events",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_profile_versions": {
+ "name": "bot_profile_versions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "version": {
+ "name": "version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "identity_source": {
+ "name": "identity_source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "capabilities_json": {
+ "name": "capabilities_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_bot_profile_versions_bot_version": {
+ "name": "uniq_bot_profile_versions_bot_version",
+ "columns": [
+ "bot_id",
+ "version"
+ ],
+ "isUnique": true
+ },
+ "idx_bot_profile_versions_bot_created": {
+ "name": "idx_bot_profile_versions_bot_created",
+ "columns": [
+ "bot_id",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_profile_versions_bot_id_bot_profiles_id_fk": {
+ "name": "bot_profile_versions_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_profile_versions",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_profiles": {
+ "name": "bot_profiles",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "display_name": {
+ "name": "display_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "avatar": {
+ "name": "avatar",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'🤖'"
+ },
+ "avatar_color": {
+ "name": "avatar_color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'violet'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "hidden_at": {
+ "name": "hidden_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pinned_at": {
+ "name": "pinned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "attention_reason": {
+ "name": "attention_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "attention_at": {
+ "name": "attention_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "current_version": {
+ "name": "current_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "canonical_session_id": {
+ "name": "canonical_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_profiles_status_updated": {
+ "name": "idx_bot_profiles_status_updated",
+ "columns": [
+ "status",
+ "updated_at"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_profiles_canonical_session": {
+ "name": "idx_bot_profiles_canonical_session",
+ "columns": [
+ "canonical_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_profiles_canonical_session_id_sessions_id_fk": {
+ "name": "bot_profiles_canonical_session_id_sessions_id_fk",
+ "tableFrom": "bot_profiles",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "canonical_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_runtime_snapshots": {
+ "name": "bot_runtime_snapshots",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "profile_version": {
+ "name": "profile_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "memory_scope_key": {
+ "name": "memory_scope_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "configured_json": {
+ "name": "configured_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "resolved_json": {
+ "name": "resolved_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "prepared_at": {
+ "name": "prepared_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "applied_at": {
+ "name": "applied_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "failed_at": {
+ "name": "failed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "failure_json": {
+ "name": "failure_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_runtime_snapshots_bot_prepared": {
+ "name": "idx_bot_runtime_snapshots_bot_prepared",
+ "columns": [
+ "bot_id",
+ "prepared_at"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_runtime_snapshots_session_prepared": {
+ "name": "idx_bot_runtime_snapshots_session_prepared",
+ "columns": [
+ "session_id",
+ "prepared_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_runtime_snapshots_bot_id_bot_profiles_id_fk": {
+ "name": "bot_runtime_snapshots_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_runtime_snapshots",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_runtime_snapshots_session_id_sessions_id_fk": {
+ "name": "bot_runtime_snapshots_session_id_sessions_id_fk",
+ "tableFrom": "bot_runtime_snapshots",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_session_links": {
+ "name": "bot_session_links",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "profile_version": {
+ "name": "profile_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "route_key": {
+ "name": "route_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_bot_session_links_session": {
+ "name": "uniq_bot_session_links_session",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true
+ },
+ "uniq_bot_session_links_canonical_per_bot": {
+ "name": "uniq_bot_session_links_canonical_per_bot",
+ "columns": [
+ "bot_id"
+ ],
+ "isUnique": true,
+ "where": "\"bot_session_links\".\"role\" = 'canonical'"
+ },
+ "idx_bot_session_links_bot_role": {
+ "name": "idx_bot_session_links_bot_role",
+ "columns": [
+ "bot_id",
+ "role"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_session_links_bot_id_bot_profiles_id_fk": {
+ "name": "bot_session_links_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_session_links",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_session_links_session_id_sessions_id_fk": {
+ "name": "bot_session_links_session_id_sessions_id_fk",
+ "tableFrom": "bot_session_links",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "custom_mcp_servers": {
+ "name": "custom_mcp_servers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "transport": {
+ "name": "transport",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "headers": {
+ "name": "headers",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_custom_mcp_servers_sort_order": {
+ "name": "idx_custom_mcp_servers_sort_order",
+ "columns": [
+ "sort_order"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "custom_providers": {
+ "name": "custom_providers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "runtimes": {
+ "name": "runtimes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "auth": {
+ "name": "auth",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_custom_providers_sort_order": {
+ "name": "idx_custom_providers_sort_order",
+ "columns": [
+ "sort_order"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "daily_model_usage": {
+ "name": "daily_model_usage",
+ "columns": {
+ "day": {
+ "name": "day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_amount": {
+ "name": "cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_currency": {
+ "name": "cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'USD'"
+ },
+ "cost_is_approximate": {
+ "name": "cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "input_tokens": {
+ "name": "input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "output_tokens": {
+ "name": "output_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cache_read_tokens": {
+ "name": "cache_read_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cache_create_tokens": {
+ "name": "cache_create_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "daily_model_usage_day_agent_kind_model_cost_currency_pk": {
+ "columns": [
+ "day",
+ "agent_kind",
+ "model",
+ "cost_currency"
+ ],
+ "name": "daily_model_usage_day_agent_kind_model_cost_currency_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "daily_session_usage": {
+ "name": "daily_session_usage",
+ "columns": {
+ "day": {
+ "name": "day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tokens": {
+ "name": "tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "daily_session_usage_day_session_id_pk": {
+ "columns": [
+ "day",
+ "session_id"
+ ],
+ "name": "daily_session_usage_day_session_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "daily_spend": {
+ "name": "daily_spend",
+ "columns": {
+ "day": {
+ "name": "day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_amount": {
+ "name": "cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_currency": {
+ "name": "cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'USD'"
+ },
+ "cost_is_approximate": {
+ "name": "cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "daily_spend_day_cost_currency_pk": {
+ "columns": [
+ "day",
+ "cost_currency"
+ ],
+ "name": "daily_spend_day_cost_currency_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "device_link_ownership": {
+ "name": "device_link_ownership",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_pid": {
+ "name": "owner_pid",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_label": {
+ "name": "owner_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "heartbeat_at": {
+ "name": "heartbeat_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "embedding_jobs": {
+ "name": "embedding_jobs",
+ "columns": {
+ "rowid": {
+ "name": "rowid",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source_id": {
+ "name": "source_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chunk_index": {
+ "name": "chunk_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "vec_table": {
+ "name": "vec_table",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scheduled_at": {
+ "name": "scheduled_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "locked_at": {
+ "name": "locked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_embedding_jobs_natural": {
+ "name": "uniq_embedding_jobs_natural",
+ "columns": [
+ "source",
+ "source_id",
+ "chunk_index",
+ "model_id"
+ ],
+ "isUnique": true
+ },
+ "idx_embedding_jobs_status_scheduled": {
+ "name": "idx_embedding_jobs_status_scheduled",
+ "columns": [
+ "status",
+ "scheduled_at"
+ ],
+ "isUnique": false
+ },
+ "idx_embedding_jobs_source_id": {
+ "name": "idx_embedding_jobs_source_id",
+ "columns": [
+ "source",
+ "source_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "embedding_meta": {
+ "name": "embedding_meta",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "ghost_cards": {
+ "name": "ghost_cards",
+ "columns": {
+ "call_id": {
+ "name": "call_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ghost_id": {
+ "name": "ghost_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "html": {
+ "name": "html",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "height": {
+ "name": "height",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "v": {
+ "name": "v",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "ghost_cards_updated_at_idx": {
+ "name": "ghost_cards_updated_at_idx",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "hook_group_context_cursors": {
+ "name": "hook_group_context_cursors",
+ "columns": {
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cursor_key": {
+ "name": "cursor_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cursor_id": {
+ "name": "cursor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "hook_group_context_cursors_updated_at_idx": {
+ "name": "hook_group_context_cursors_updated_at_idx",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "hook_group_context_cursors_provider_cursor_key_pk": {
+ "columns": [
+ "provider",
+ "cursor_key"
+ ],
+ "name": "hook_group_context_cursors_provider_cursor_key_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "hook_group_message_stats": {
+ "name": "hook_group_message_stats",
+ "columns": {
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "row_count": {
+ "name": "row_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text_bytes": {
+ "name": "text_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "hook_group_messages": {
+ "name": "hook_group_messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "thread_id": {
+ "name": "thread_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_name": {
+ "name": "chat_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "author": {
+ "name": "author",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_bot": {
+ "name": "is_bot",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "file_names": {
+ "name": "file_names",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "hook_group_messages_msg_idx": {
+ "name": "hook_group_messages_msg_idx",
+ "columns": [
+ "provider",
+ "chat_id",
+ "thread_id",
+ "message_id"
+ ],
+ "isUnique": true
+ },
+ "hook_group_messages_window_idx": {
+ "name": "hook_group_messages_window_idx",
+ "columns": [
+ "provider",
+ "chat_id",
+ "thread_id",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "im_bindings": {
+ "name": "im_bindings",
+ "columns": {
+ "channel": {
+ "name": "channel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_context_id": {
+ "name": "bot_context_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scope_key": {
+ "name": "scope_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "target_session_id": {
+ "name": "target_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attached_at": {
+ "name": "attached_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attached_via_card_message_id": {
+ "name": "attached_via_card_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_im_bindings_target": {
+ "name": "idx_im_bindings_target",
+ "columns": [
+ "target_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "im_bindings_target_session_id_sessions_id_fk": {
+ "name": "im_bindings_target_session_id_sessions_id_fk",
+ "tableFrom": "im_bindings",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "target_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "im_bindings_channel_bot_context_id_user_id_scope_key_pk": {
+ "columns": [
+ "channel",
+ "bot_context_id",
+ "user_id",
+ "scope_key"
+ ],
+ "name": "im_bindings_channel_bot_context_id_user_id_scope_key_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "im_notification_origins": {
+ "name": "im_notification_origins",
+ "columns": {
+ "channel": {
+ "name": "channel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_context_id": {
+ "name": "bot_context_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "im_notification_origins_channel_bot_context_id_user_id_message_id_pk": {
+ "columns": [
+ "channel",
+ "bot_context_id",
+ "user_id",
+ "message_id"
+ ],
+ "name": "im_notification_origins_channel_bot_context_id_user_id_message_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "media_blobs": {
+ "name": "media_blobs",
+ "columns": {
+ "hash": {
+ "name": "hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ext": {
+ "name": "ext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mime_type": {
+ "name": "mime_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bytes": {
+ "name": "bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_cache": {
+ "name": "is_cache",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_access_at": {
+ "name": "last_access_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "media_invocations": {
+ "name": "media_invocations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner": {
+ "name": "owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "capability": {
+ "name": "capability",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "guide_revision": {
+ "name": "guide_revision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "guide_json": {
+ "name": "guide_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "response_json": {
+ "name": "response_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "media_invocations_owner_created_at_idx": {
+ "name": "media_invocations_owner_created_at_idx",
+ "columns": [
+ "owner",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "media_invocations_owner_state_idx": {
+ "name": "media_invocations_owner_state_idx",
+ "columns": [
+ "owner",
+ "state"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "media_refs": {
+ "name": "media_refs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "hash": {
+ "name": "hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ref_kind": {
+ "name": "ref_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ref_id": {
+ "name": "ref_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "origin_session_id": {
+ "name": "origin_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "origin_kind": {
+ "name": "origin_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "origin_id": {
+ "name": "origin_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "media_refs_hash_idx": {
+ "name": "media_refs_hash_idx",
+ "columns": [
+ "hash"
+ ],
+ "isUnique": false
+ },
+ "media_refs_ref_idx": {
+ "name": "media_refs_ref_idx",
+ "columns": [
+ "ref_kind",
+ "ref_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "media_refs_hash_media_blobs_hash_fk": {
+ "name": "media_refs_hash_media_blobs_hash_fk",
+ "tableFrom": "media_refs",
+ "tableTo": "media_blobs",
+ "columnsFrom": [
+ "hash"
+ ],
+ "columnsTo": [
+ "hash"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "messages": {
+ "name": "messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_use_id": {
+ "name": "tool_use_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_meta": {
+ "name": "agent_meta",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "rewind_at": {
+ "name": "rewind_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_messages_session_client": {
+ "name": "uniq_messages_session_client",
+ "columns": [
+ "session_id",
+ "client_id"
+ ],
+ "isUnique": true
+ },
+ "idx_messages_session_created": {
+ "name": "idx_messages_session_created",
+ "columns": [
+ "session_id",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "idx_messages_created_at": {
+ "name": "idx_messages_created_at",
+ "columns": [
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_messages_rewind_at": {
+ "name": "idx_messages_rewind_at",
+ "columns": [
+ "rewind_at"
+ ],
+ "isUnique": false
+ },
+ "idx_messages_active_error_tail": {
+ "name": "idx_messages_active_error_tail",
+ "columns": [
+ "session_id",
+ "created_at"
+ ],
+ "isUnique": false,
+ "where": "\"messages\".\"role\" = 'error' AND \"messages\".\"rewind_at\" IS NULL"
+ }
+ },
+ "foreignKeys": {
+ "messages_session_id_sessions_id_fk": {
+ "name": "messages_session_id_sessions_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "messages_fts_rows": {
+ "name": "messages_fts_rows",
+ "columns": {
+ "fts_rowid": {
+ "name": "fts_rowid",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "messages_fts_rows_message_id_idx": {
+ "name": "messages_fts_rows_message_id_idx",
+ "columns": [
+ "message_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "migration_history": {
+ "name": "migration_history",
+ "columns": {
+ "seq": {
+ "name": "seq",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "file_name": {
+ "name": "file_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content_hash": {
+ "name": "content_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "applied_at": {
+ "name": "applied_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "migration_meta": {
+ "name": "migration_meta",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_teams": {
+ "name": "orca_teams",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "lead_session_id": {
+ "name": "lead_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_active_team_per_lead": {
+ "name": "uniq_active_team_per_lead",
+ "columns": [
+ "lead_session_id"
+ ],
+ "isUnique": true,
+ "where": "\"orca_teams\".\"status\" = 'active'"
+ },
+ "idx_orca_teams_status": {
+ "name": "idx_orca_teams_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_teams_lead_session_id_sessions_id_fk": {
+ "name": "orca_teams_lead_session_id_sessions_id_fk",
+ "tableFrom": "orca_teams",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "lead_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_worker_creation_reservations": {
+ "name": "orca_worker_creation_reservations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_orca_worker_creation_reservations_team_label": {
+ "name": "uniq_orca_worker_creation_reservations_team_label",
+ "columns": [
+ "team_id",
+ "lower(\"label\")"
+ ],
+ "isUnique": true
+ },
+ "idx_orca_worker_creation_reservations_expires_at": {
+ "name": "idx_orca_worker_creation_reservations_expires_at",
+ "columns": [
+ "expires_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_worker_creation_reservations_team_id_orca_teams_id_fk": {
+ "name": "orca_worker_creation_reservations_team_id_orca_teams_id_fk",
+ "tableFrom": "orca_worker_creation_reservations",
+ "tableTo": "orca_teams",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_workers": {
+ "name": "orca_workers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'idle'"
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "worktree_branch": {
+ "name": "worktree_branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'developer'"
+ },
+ "focused": {
+ "name": "focused",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "idle_since": {
+ "name": "idle_since",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_orca_workers_session_id": {
+ "name": "uniq_orca_workers_session_id",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true
+ },
+ "uniq_orca_workers_team_label": {
+ "name": "uniq_orca_workers_team_label",
+ "columns": [
+ "team_id",
+ "lower(\"label\")"
+ ],
+ "isUnique": true
+ },
+ "uniq_orca_workers_focused_per_team": {
+ "name": "uniq_orca_workers_focused_per_team",
+ "columns": [
+ "team_id"
+ ],
+ "isUnique": true,
+ "where": "\"orca_workers\".\"focused\" = true"
+ },
+ "idx_orca_workers_team_id": {
+ "name": "idx_orca_workers_team_id",
+ "columns": [
+ "team_id"
+ ],
+ "isUnique": false
+ },
+ "idx_orca_workers_status": {
+ "name": "idx_orca_workers_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_workers_team_id_orca_teams_id_fk": {
+ "name": "orca_workers_team_id_orca_teams_id_fk",
+ "tableFrom": "orca_workers",
+ "tableTo": "orca_teams",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "orca_workers_session_id_sessions_id_fk": {
+ "name": "orca_workers_session_id_sessions_id_fk",
+ "tableFrom": "orca_workers",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_aliases": {
+ "name": "project_aliases",
+ "columns": {
+ "project_key": {
+ "name": "project_key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "alias": {
+ "name": "alias",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_project_aliases_updated_at": {
+ "name": "idx_project_aliases_updated_at",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_automation_consents": {
+ "name": "project_automation_consents",
+ "columns": {
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "consented_at": {
+ "name": "consented_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "config_hash": {
+ "name": "config_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "recent_workdirs": {
+ "name": "recent_workdirs",
+ "columns": {
+ "path": {
+ "name": "path",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_recent_workdirs_last_used_at": {
+ "name": "idx_recent_workdirs_last_used_at",
+ "columns": [
+ "last_used_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "right_sidebar_tabs": {
+ "name": "right_sidebar_tabs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "right_sidebar_tabs_session_idx": {
+ "name": "right_sidebar_tabs_session_idx",
+ "columns": [
+ "session_id",
+ "position"
+ ],
+ "isUnique": false
+ },
+ "right_sidebar_tabs_subagents_singleton_idx": {
+ "name": "right_sidebar_tabs_subagents_singleton_idx",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true,
+ "where": "\"right_sidebar_tabs\".\"kind\" = 'subagents'"
+ },
+ "right_sidebar_tabs_bot_artifacts_singleton_idx": {
+ "name": "right_sidebar_tabs_bot_artifacts_singleton_idx",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true,
+ "where": "\"right_sidebar_tabs\".\"kind\" = 'bot-artifacts'"
+ }
+ },
+ "foreignKeys": {
+ "right_sidebar_tabs_session_id_sessions_id_fk": {
+ "name": "right_sidebar_tabs_session_id_sessions_id_fk",
+ "tableFrom": "right_sidebar_tabs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "schedule_runs": {
+ "name": "schedule_runs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "schedule_id": {
+ "name": "schedule_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fired_at": {
+ "name": "fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "error_msg": {
+ "name": "error_msg",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "estimated_value_usd": {
+ "name": "estimated_value_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_amount": {
+ "name": "cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "estimated_value_amount": {
+ "name": "estimated_value_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_currency": {
+ "name": "cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_is_approximate": {
+ "name": "cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "cost_attribution": {
+ "name": "cost_attribution",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'legacy'"
+ },
+ "result_text": {
+ "name": "result_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pre_run_hook_result": {
+ "name": "pre_run_hook_result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "read_at": {
+ "name": "read_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "heartbeat_at": {
+ "name": "heartbeat_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedule_runs_schedule": {
+ "name": "idx_schedule_runs_schedule",
+ "columns": [
+ "schedule_id",
+ "fired_at"
+ ],
+ "isUnique": false
+ },
+ "idx_schedule_runs_running_schedule": {
+ "name": "idx_schedule_runs_running_schedule",
+ "columns": [
+ "schedule_id"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"status\" = 'running'"
+ },
+ "idx_schedule_runs_running_heartbeat": {
+ "name": "idx_schedule_runs_running_heartbeat",
+ "columns": [
+ "heartbeat_at"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"status\" = 'running' AND \"schedule_runs\".\"heartbeat_at\" IS NOT NULL"
+ },
+ "idx_schedule_runs_running_legacy": {
+ "name": "idx_schedule_runs_running_legacy",
+ "columns": [
+ "fired_at"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"status\" = 'running' AND \"schedule_runs\".\"heartbeat_at\" IS NULL"
+ },
+ "idx_schedule_runs_unread_terminal": {
+ "name": "idx_schedule_runs_unread_terminal",
+ "columns": [
+ "schedule_id",
+ "status",
+ "fired_at"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"read_at\" IS NULL AND \"schedule_runs\".\"status\" IN ('success', 'failed', 'aborted', 'interrupted')"
+ },
+ "idx_schedule_runs_session_latest": {
+ "name": "idx_schedule_runs_session_latest",
+ "columns": [
+ "session_id",
+ "fired_at",
+ "id"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"session_id\" IS NOT NULL"
+ }
+ },
+ "foreignKeys": {
+ "schedule_runs_schedule_id_schedules_id_fk": {
+ "name": "schedule_runs_schedule_id_schedules_id_fk",
+ "tableFrom": "schedule_runs",
+ "tableTo": "schedules",
+ "columnsFrom": [
+ "schedule_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "schedule_runs_session_id_sessions_id_fk": {
+ "name": "schedule_runs_session_id_sessions_id_fk",
+ "tableFrom": "schedule_runs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "schedule_session_latest_runs": {
+ "name": "schedule_session_latest_runs",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "fired_at": {
+ "name": "fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedule_session_latest_runs_run": {
+ "name": "idx_schedule_session_latest_runs_run",
+ "columns": [
+ "run_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "schedule_session_latest_runs_session_id_sessions_id_fk": {
+ "name": "schedule_session_latest_runs_session_id_sessions_id_fk",
+ "tableFrom": "schedule_session_latest_runs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "schedule_session_latest_runs_run_id_schedule_runs_id_fk": {
+ "name": "schedule_session_latest_runs_run_id_schedule_runs_id_fk",
+ "tableFrom": "schedule_session_latest_runs",
+ "tableTo": "schedule_runs",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "schedules": {
+ "name": "schedules",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "job_type": {
+ "name": "job_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'prompt'"
+ },
+ "job_config": {
+ "name": "job_config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "execution_mode": {
+ "name": "execution_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'agent'"
+ },
+ "script_config": {
+ "name": "script_config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'user'"
+ },
+ "project_config_id": {
+ "name": "project_config_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "legacy_session_fallback": {
+ "name": "legacy_session_fallback",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'cron'"
+ },
+ "cron_expr": {
+ "name": "cron_expr",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "recurring": {
+ "name": "recurring",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "manual": {
+ "name": "manual",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "interval_ms": {
+ "name": "interval_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_agent_kind": {
+ "name": "model_agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "effort": {
+ "name": "effort",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fast_mode": {
+ "name": "fast_mode",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_kind": {
+ "name": "workspace_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'project'"
+ },
+ "use_worktree": {
+ "name": "use_worktree",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "target_session_id": {
+ "name": "target_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "persistent_session": {
+ "name": "persistent_session",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "silent_when_idle": {
+ "name": "silent_when_idle",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "pre_run_hook_command": {
+ "name": "pre_run_hook_command",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pre_run_hook_timeout_ms": {
+ "name": "pre_run_hook_timeout_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "skip_log_session_id": {
+ "name": "skip_log_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "notify_desktop": {
+ "name": "notify_desktop",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "notify_feishu": {
+ "name": "notify_feishu",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "notify_wecom_group": {
+ "name": "notify_wecom_group",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_fired_at": {
+ "name": "last_fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_finished_at": {
+ "name": "last_finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "next_fire_at": {
+ "name": "next_fire_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expire_at": {
+ "name": "expire_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedules_active_next": {
+ "name": "idx_schedules_active_next",
+ "columns": [
+ "status",
+ "next_fire_at"
+ ],
+ "isUnique": false
+ },
+ "idx_schedules_target_session": {
+ "name": "idx_schedules_target_session",
+ "columns": [
+ "target_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "schedules_target_session_id_sessions_id_fk": {
+ "name": "schedules_target_session_id_sessions_id_fk",
+ "tableFrom": "schedules",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "target_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "schedules_skip_log_session_id_sessions_id_fk": {
+ "name": "schedules_skip_log_session_id_sessions_id_fk",
+ "tableFrom": "schedules",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "skip_log_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_goals": {
+ "name": "session_goals",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "objective": {
+ "name": "objective",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "budget_tokens": {
+ "name": "budget_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "max_turns": {
+ "name": "max_turns",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "no_progress_limit": {
+ "name": "no_progress_limit",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "turns_used": {
+ "name": "turns_used",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "tokens_used": {
+ "name": "tokens_used",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "no_progress_streak": {
+ "name": "no_progress_streak",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "usage_reset_at": {
+ "name": "usage_reset_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_reason": {
+ "name": "last_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_session_goals_status": {
+ "name": "idx_session_goals_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_goals_session_id_sessions_id_fk": {
+ "name": "session_goals_session_id_sessions_id_fk",
+ "tableFrom": "session_goals",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_pr_refs": {
+ "name": "session_pr_refs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner": {
+ "name": "owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "repo": {
+ "name": "repo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "first_seen_at": {
+ "name": "first_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_session_pr_refs": {
+ "name": "uniq_session_pr_refs",
+ "columns": [
+ "session_id",
+ "owner",
+ "repo",
+ "pr_number"
+ ],
+ "isUnique": true
+ },
+ "idx_session_pr_refs_session_last_seen": {
+ "name": "idx_session_pr_refs_session_last_seen",
+ "columns": [
+ "session_id",
+ "last_seen_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_pr_refs_session_id_sessions_id_fk": {
+ "name": "session_pr_refs_session_id_sessions_id_fk",
+ "tableFrom": "session_pr_refs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_task_tags": {
+ "name": "session_task_tags",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tag_id": {
+ "name": "tag_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "session_task_tags_tag_idx": {
+ "name": "session_task_tags_tag_idx",
+ "columns": [
+ "tag_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_task_tags_session_id_sessions_id_fk": {
+ "name": "session_task_tags_session_id_sessions_id_fk",
+ "tableFrom": "session_task_tags",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "session_task_tags_tag_id_task_tags_id_fk": {
+ "name": "session_task_tags_tag_id_task_tags_id_fk",
+ "tableFrom": "session_task_tags",
+ "tableTo": "task_tags",
+ "columnsFrom": [
+ "tag_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "session_task_tags_session_id_tag_id_pk": {
+ "columns": [
+ "session_id",
+ "tag_id"
+ ],
+ "name": "session_task_tags_session_id_tag_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'New Maker'"
+ },
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_kind": {
+ "name": "workspace_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'project'"
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'claude-sonnet-4-6'"
+ },
+ "effort": {
+ "name": "effort",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'high'"
+ },
+ "permission_mode": {
+ "name": "permission_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'ask'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "total_token_usage": {
+ "name": "total_token_usage",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_usd": {
+ "name": "total_cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_amount": {
+ "name": "total_cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_currency": {
+ "name": "total_cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "total_cost_is_approximate": {
+ "name": "total_cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "context_tokens": {
+ "name": "context_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "context_window": {
+ "name": "context_window",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "context_window_runtime": {
+ "name": "context_window_runtime",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fast_mode": {
+ "name": "fast_mode",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "plan_mode_enabled": {
+ "name": "plan_mode_enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "cleared_at": {
+ "name": "cleared_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pinned_at": {
+ "name": "pinned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_send_at": {
+ "name": "user_send_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'cc'"
+ },
+ "orca_role": {
+ "name": "orca_role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "parent_session_id": {
+ "name": "parent_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "forked_at_message_id": {
+ "name": "forked_at_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "worktree_path": {
+ "name": "worktree_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'desktop'"
+ },
+ "feishu_open_id": {
+ "name": "feishu_open_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "feishu_bot_app_id": {
+ "name": "feishu_bot_app_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "im_bot_context_id": {
+ "name": "im_bot_context_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "im_user_id": {
+ "name": "im_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "im_default_route": {
+ "name": "im_default_route",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "used_project_context": {
+ "name": "used_project_context",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "codex_history_has_product_prompt": {
+ "name": "codex_history_has_product_prompt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "codex_plan_json": {
+ "name": "codex_plan_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "extra_dirs": {
+ "name": "extra_dirs",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "writable_dirs": {
+ "name": "writable_dirs",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "remote_host_id": {
+ "name": "remote_host_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "active_turn_started_at": {
+ "name": "active_turn_started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "active_turn_pid": {
+ "name": "active_turn_pid",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_turn_ended_at": {
+ "name": "last_turn_ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "list_preview": {
+ "name": "list_preview",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "list_preview_role": {
+ "name": "list_preview_role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "list_message_count": {
+ "name": "list_message_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_sessions_updated_at": {
+ "name": "idx_sessions_updated_at",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_user_send_at": {
+ "name": "idx_sessions_user_send_at",
+ "columns": [
+ "user_send_at"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_sdk_session_id": {
+ "name": "idx_sessions_sdk_session_id",
+ "columns": [
+ "sdk_session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_workdir_created": {
+ "name": "idx_sessions_workdir_created",
+ "columns": [
+ "working_dir",
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_created_at": {
+ "name": "idx_sessions_created_at",
+ "columns": [
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_workspace_kind": {
+ "name": "idx_sessions_workspace_kind",
+ "columns": [
+ "workspace_kind"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_parent_session_id": {
+ "name": "idx_sessions_parent_session_id",
+ "columns": [
+ "parent_session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_orca_role": {
+ "name": "idx_sessions_orca_role",
+ "columns": [
+ "orca_role"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_worktree_path": {
+ "name": "idx_sessions_worktree_path",
+ "columns": [
+ "worktree_path"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_feishu_lookup": {
+ "name": "idx_sessions_feishu_lookup",
+ "columns": [
+ "source",
+ "feishu_bot_app_id",
+ "feishu_open_id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_im_lookup": {
+ "name": "idx_sessions_im_lookup",
+ "columns": [
+ "source",
+ "im_bot_context_id",
+ "im_user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "sessions_parent_session_id_sessions_id_fk": {
+ "name": "sessions_parent_session_id_sessions_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "parent_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "shared_task_events": {
+ "name": "shared_task_events",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "shared_task_id": {
+ "name": "shared_task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "revision": {
+ "name": "revision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "terminal": {
+ "name": "terminal",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "snapshot": {
+ "name": "snapshot",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "recorded_at": {
+ "name": "recorded_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "shared_task_events_revision_idx": {
+ "name": "shared_task_events_revision_idx",
+ "columns": [
+ "shared_task_id",
+ "kind",
+ "revision"
+ ],
+ "isUnique": true
+ },
+ "shared_task_events_session_idx": {
+ "name": "shared_task_events_session_idx",
+ "columns": [
+ "session_id",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "shared_task_events_session_id_sessions_id_fk": {
+ "name": "shared_task_events_session_id_sessions_id_fk",
+ "tableFrom": "shared_task_events",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "skill_usage_exposures": {
+ "name": "skill_usage_exposures",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "analyzer_version": {
+ "name": "analyzer_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'6'"
+ },
+ "raw_file_path": {
+ "name": "raw_file_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "raw_line_no": {
+ "name": "raw_line_no",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "skill_name": {
+ "name": "skill_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "skill_path": {
+ "name": "skill_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "skill_document_hash": {
+ "name": "skill_document_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "exposure_content_hash": {
+ "name": "exposure_content_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "document_hash_source": {
+ "name": "document_hash_source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_use_id": {
+ "name": "tool_use_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "seen_at": {
+ "name": "seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_call_count": {
+ "name": "tool_call_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "repeated_tool_call_count": {
+ "name": "repeated_tool_call_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "tool_error_count": {
+ "name": "tool_error_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "command_call_count": {
+ "name": "command_call_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "command_failure_count": {
+ "name": "command_failure_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ }
+ },
+ "indexes": {
+ "idx_skill_usage_exposures_skill_document_version": {
+ "name": "idx_skill_usage_exposures_skill_document_version",
+ "columns": [
+ "analyzer_version",
+ "skill_name",
+ "skill_document_hash"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_skill_recent": {
+ "name": "idx_skill_usage_exposures_skill_recent",
+ "columns": [
+ "skill_name",
+ "analyzer_version",
+ "seen_at"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_skill_recent_any_version": {
+ "name": "idx_skill_usage_exposures_skill_recent_any_version",
+ "columns": [
+ "skill_name",
+ "seen_at"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_analyzer_recent_source": {
+ "name": "idx_skill_usage_exposures_analyzer_recent_source",
+ "columns": [
+ "analyzer_version",
+ "seen_at",
+ "raw_file_path"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_session": {
+ "name": "idx_skill_usage_exposures_session",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_raw_file": {
+ "name": "idx_skill_usage_exposures_raw_file",
+ "columns": [
+ "raw_file_path"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "skill_usage_exposures_raw_file_path_skill_usage_sources_raw_file_path_fk": {
+ "name": "skill_usage_exposures_raw_file_path_skill_usage_sources_raw_file_path_fk",
+ "tableFrom": "skill_usage_exposures",
+ "tableTo": "skill_usage_sources",
+ "columnsFrom": [
+ "raw_file_path"
+ ],
+ "columnsTo": [
+ "raw_file_path"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "skill_usage_sources": {
+ "name": "skill_usage_sources",
+ "columns": {
+ "raw_file_path": {
+ "name": "raw_file_path",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "analyzer_version": {
+ "name": "analyzer_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'6'"
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mtime_ms": {
+ "name": "mtime_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "size_bytes": {
+ "name": "size_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "last_scanned_at": {
+ "name": "last_scanned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'ok'"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_skill_usage_sources_session": {
+ "name": "idx_skill_usage_sources_session",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_sources_sdk_session": {
+ "name": "idx_skill_usage_sources_sdk_session",
+ "columns": [
+ "sdk_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subagent_run_aliases": {
+ "name": "subagent_run_aliases",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "alias": {
+ "name": "alias",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "subagent_run_aliases_lookup_idx": {
+ "name": "subagent_run_aliases_lookup_idx",
+ "columns": [
+ "session_id",
+ "provider",
+ "alias",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "subagent_run_aliases_session_id_sessions_id_fk": {
+ "name": "subagent_run_aliases_session_id_sessions_id_fk",
+ "tableFrom": "subagent_run_aliases",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "subagent_run_aliases_run_id_subagent_runs_id_fk": {
+ "name": "subagent_run_aliases_run_id_subagent_runs_id_fk",
+ "tableFrom": "subagent_run_aliases",
+ "tableTo": "subagent_runs",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "subagent_run_aliases_run_id_alias_pk": {
+ "columns": [
+ "run_id",
+ "alias"
+ ],
+ "name": "subagent_run_aliases_run_id_alias_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subagent_runs": {
+ "name": "subagent_runs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "logical_agent_id": {
+ "name": "logical_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "parent_tool_use_id": {
+ "name": "parent_tool_use_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "aliases": {
+ "name": "aliases",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "provider_run_ids": {
+ "name": "provider_run_ids",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'running'"
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "returned_result": {
+ "name": "returned_result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "returned_result_empty": {
+ "name": "returned_result_empty",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "returned_result_truncated": {
+ "name": "returned_result_truncated",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "reasoning_effort": {
+ "name": "reasoning_effort",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "total_tokens": {
+ "name": "total_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tool_uses": {
+ "name": "tool_uses",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "duration_ms": {
+ "name": "duration_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "capabilities": {
+ "name": "capabilities",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "activity": {
+ "name": "activity",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "rewind_at": {
+ "name": "rewind_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "subagent_runs_logical_idx": {
+ "name": "subagent_runs_logical_idx",
+ "columns": [
+ "session_id",
+ "provider",
+ "logical_agent_id"
+ ],
+ "isUnique": false
+ },
+ "subagent_runs_session_idx": {
+ "name": "subagent_runs_session_idx",
+ "columns": [
+ "session_id",
+ "rewind_at",
+ "deleted_at",
+ "started_at"
+ ],
+ "isUnique": false
+ },
+ "subagent_runs_parent_tool_use_idx": {
+ "name": "subagent_runs_parent_tool_use_idx",
+ "columns": [
+ "session_id",
+ "parent_tool_use_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "subagent_runs_session_id_sessions_id_fk": {
+ "name": "subagent_runs_session_id_sessions_id_fk",
+ "tableFrom": "subagent_runs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "task_tags": {
+ "name": "task_tags",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name_customized": {
+ "name": "name_customized",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "favorite_order": {
+ "name": "favorite_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "revision": {
+ "name": "revision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ }
+ },
+ "indexes": {
+ "task_tags_name_idx": {
+ "name": "task_tags_name_idx",
+ "columns": [
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "vec_table_meta": {
+ "name": "vec_table_meta",
+ "columns": {
+ "vec_table": {
+ "name": "vec_table",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "dim": {
+ "name": "dim",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "registered_at": {
+ "name": "registered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "notes": {
+ "name": "notes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_file_attachments": {
+ "name": "wechat_file_attachments",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "abs_path": {
+ "name": "abs_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "original_name": {
+ "name": "original_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mime_type": {
+ "name": "mime_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bytes": {
+ "name": "bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'staged'"
+ },
+ "promoted_at": {
+ "name": "promoted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_wechat_file_attachments_task": {
+ "name": "idx_wechat_file_attachments_task",
+ "columns": [
+ "binding_epoch",
+ "task_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "wechat_file_attachments_binding_epoch_wechat_sync_state_binding_epoch_fk": {
+ "name": "wechat_file_attachments_binding_epoch_wechat_sync_state_binding_epoch_fk",
+ "tableFrom": "wechat_file_attachments",
+ "tableTo": "wechat_sync_state",
+ "columnsFrom": [
+ "binding_epoch"
+ ],
+ "columnsTo": [
+ "binding_epoch"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wechat_file_attachments_task_id_wechat_inbox_id_fk": {
+ "name": "wechat_file_attachments_task_id_wechat_inbox_id_fk",
+ "tableFrom": "wechat_file_attachments",
+ "tableTo": "wechat_inbox",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wechat_file_attachments_session_id_sessions_id_fk": {
+ "name": "wechat_file_attachments_session_id_sessions_id_fk",
+ "tableFrom": "wechat_file_attachments",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_inbox": {
+ "name": "wechat_inbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "platform_message_id": {
+ "name": "platform_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "platform_seq": {
+ "name": "platform_seq",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "peer_id": {
+ "name": "peer_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "received_at": {
+ "name": "received_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "platform_created_at": {
+ "name": "platform_created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "lease_until": {
+ "name": "lease_until",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "conversation_epoch": {
+ "name": "conversation_epoch",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "payload_json": {
+ "name": "payload_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_nonce": {
+ "name": "context_nonce",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_ciphertext": {
+ "name": "context_ciphertext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_tag": {
+ "name": "context_tag",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "last_error_code": {
+ "name": "last_error_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_wechat_inbox_platform_message": {
+ "name": "uniq_wechat_inbox_platform_message",
+ "columns": [
+ "binding_epoch",
+ "platform_message_id"
+ ],
+ "isUnique": true
+ },
+ "idx_wechat_inbox_queue": {
+ "name": "idx_wechat_inbox_queue",
+ "columns": [
+ "binding_epoch",
+ "status",
+ "received_at"
+ ],
+ "isUnique": false
+ },
+ "idx_wechat_inbox_lease": {
+ "name": "idx_wechat_inbox_lease",
+ "columns": [
+ "binding_epoch",
+ "lease_until"
+ ],
+ "isUnique": false
+ },
+ "idx_wechat_inbox_conversation": {
+ "name": "idx_wechat_inbox_conversation",
+ "columns": [
+ "binding_epoch",
+ "peer_id",
+ "conversation_epoch"
+ ],
+ "isUnique": false
+ },
+ "uniq_wechat_inbox_running_session": {
+ "name": "uniq_wechat_inbox_running_session",
+ "columns": [
+ "binding_epoch",
+ "session_id"
+ ],
+ "isUnique": true,
+ "where": "\"wechat_inbox\".\"session_id\" IS NOT NULL AND \"wechat_inbox\".\"status\" IN ('dispatching', 'accepted_running', 'waiting_desktop', 'delivery_pending')"
+ }
+ },
+ "foreignKeys": {
+ "wechat_inbox_binding_epoch_wechat_sync_state_binding_epoch_fk": {
+ "name": "wechat_inbox_binding_epoch_wechat_sync_state_binding_epoch_fk",
+ "tableFrom": "wechat_inbox",
+ "tableTo": "wechat_sync_state",
+ "columnsFrom": [
+ "binding_epoch"
+ ],
+ "columnsTo": [
+ "binding_epoch"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wechat_inbox_session_id_sessions_id_fk": {
+ "name": "wechat_inbox_session_id_sessions_id_fk",
+ "tableFrom": "wechat_inbox",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_outbox": {
+ "name": "wechat_outbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chunk_index": {
+ "name": "chunk_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "media_json": {
+ "name": "media_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "next_retry_at": {
+ "name": "next_retry_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "delivered_at": {
+ "name": "delivered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_wechat_outbox_client_id": {
+ "name": "uniq_wechat_outbox_client_id",
+ "columns": [
+ "binding_epoch",
+ "client_id"
+ ],
+ "isUnique": true
+ },
+ "idx_wechat_outbox_delivery": {
+ "name": "idx_wechat_outbox_delivery",
+ "columns": [
+ "binding_epoch",
+ "status",
+ "next_retry_at"
+ ],
+ "isUnique": false
+ },
+ "idx_wechat_outbox_task": {
+ "name": "idx_wechat_outbox_task",
+ "columns": [
+ "binding_epoch",
+ "task_id",
+ "chunk_index"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "wechat_outbox_binding_epoch_wechat_sync_state_binding_epoch_fk": {
+ "name": "wechat_outbox_binding_epoch_wechat_sync_state_binding_epoch_fk",
+ "tableFrom": "wechat_outbox",
+ "tableTo": "wechat_sync_state",
+ "columnsFrom": [
+ "binding_epoch"
+ ],
+ "columnsTo": [
+ "binding_epoch"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wechat_outbox_task_id_wechat_inbox_id_fk": {
+ "name": "wechat_outbox_task_id_wechat_inbox_id_fk",
+ "tableFrom": "wechat_outbox",
+ "tableTo": "wechat_inbox",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_sync_state": {
+ "name": "wechat_sync_state",
+ "columns": {
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "sync_cursor": {
+ "name": "sync_cursor",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "last_poll_at": {
+ "name": "last_poll_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_error_code": {
+ "name": "last_error_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_wechat_sync_active": {
+ "name": "uniq_wechat_sync_active",
+ "columns": [
+ "is_active"
+ ],
+ "isUnique": true,
+ "where": "\"wechat_sync_state\".\"is_active\" = 1"
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {
+ "uniq_orca_worker_creation_reservations_team_label": {
+ "columns": {
+ "lower(\"label\")": {
+ "isExpression": true
+ }
+ }
+ },
+ "uniq_orca_workers_team_label": {
+ "columns": {
+ "lower(\"label\")": {
+ "isExpression": true
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/apps/desktop/drizzle/meta/_journal.json b/apps/desktop/drizzle/meta/_journal.json
index 6c3fa5cb74..6e8c1bc3d3 100644
--- a/apps/desktop/drizzle/meta/_journal.json
+++ b/apps/desktop/drizzle/meta/_journal.json
@@ -834,6 +834,13 @@
"when": 1790517291835,
"tag": "0118_cynical_thunderball",
"breakpoints": true
+ },
+ {
+ "idx": 119,
+ "version": "6",
+ "when": 1790535750822,
+ "tag": "0119_hard_vindicator",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/apps/desktop/src/main/__tests__/imDefaultSettingsIpcSecurity.test.ts b/apps/desktop/src/main/__tests__/imDefaultSettingsIpcSecurity.test.ts
new file mode 100644
index 0000000000..d42ba59c11
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/imDefaultSettingsIpcSecurity.test.ts
@@ -0,0 +1,57 @@
+import { readFileSync } from 'node:fs';
+
+import { describe, expect, it } from 'vitest';
+
+const source = readFileSync(new URL('../bootstrap-electron.ts', import.meta.url), 'utf8');
+
+describe('im default settings IPC security contract', () => {
+ // 保存/重置会按旧默认批量补写老任务的跟随记录, 并让下一条 IM 消息切换现有任务的
+ // 运行路由 —— sender 校验必须拦在任何回填或写设置之前, 不能让导航到外部页面的
+ // preload frame 改写渠道默认并推动任务切路由(codex review P1, PR #5155)。
+ it.each([
+ ['IM_DEFAULT_SETTINGS_SET', 'writeImDefaultSettingsPatch('],
+ ['IM_DEFAULT_SETTINGS_RESET', 'resetImDefaultSettings'],
+ ] as const)('guards %s before any backfill or settings write', (channel, writeCall) => {
+ const handler = source.indexOf(`MAKER_IPC_INVOKE.${channel},`);
+ expect(handler).toBeGreaterThanOrEqual(0);
+ const guard = source.indexOf('assertTrustedAppRendererEvent(event);', handler);
+ const backfill = source.indexOf('prepareImDefaultSettingsChange(', handler);
+ const write = source.indexOf(writeCall, handler);
+ expect(guard).toBeGreaterThan(handler);
+ expect(backfill).toBeGreaterThan(guard);
+ expect(write).toBeGreaterThan(guard);
+ });
+
+ // owner 边界(PR #5155 review P1): 回填跨多个 await, 期间登出/切号会让落库与设置
+ // 写入漂到别的 owner —— 进入时快照 owner scope, 写设置前在同一同步块内复核
+ // scope 未变且无 boundary 在途, 不满足即失败重试。
+ it.each([
+ ['IM_DEFAULT_SETTINGS_SET', 'writeImDefaultSettingsPatch('],
+ ['IM_DEFAULT_SETTINGS_RESET', 'resetImDefaultSettings'],
+ ] as const)('pins the owner scope at entry and re-checks it right before %s writes', (channel, writeCall) => {
+ const handler = source.indexOf(`MAKER_IPC_INVOKE.${channel},`);
+ expect(handler).toBeGreaterThanOrEqual(0);
+ const capture = source.indexOf('const ownerScopeKey = activeOwnerScopeKey();', handler);
+ const backfill = source.indexOf('prepareImDefaultSettingsChange(', handler);
+ const ownerGuard = source.indexOf('assertOwnerScopeSettledForWrite(ownerScopeKey);', handler);
+ const write = source.indexOf(writeCall, handler);
+ expect(capture).toBeGreaterThan(handler);
+ expect(backfill).toBeGreaterThan(capture);
+ expect(ownerGuard).toBeGreaterThan(backfill);
+ expect(write).toBeGreaterThan(ownerGuard);
+ });
+
+ // 仅路由默认实际变化时才要求阻塞式回填(PR #5155 review P2): 只改权限档等不动
+ // 路由指纹的保存不该被无关的供应商目录故障挡下。
+ it.each(['IM_DEFAULT_SETTINGS_SET', 'IM_DEFAULT_SETTINGS_RESET'] as const)(
+ 'requires the blocking backfill only when the route default actually changes (%s)',
+ (channel) => {
+ const handler = source.indexOf(`MAKER_IPC_INVOKE.${channel},`);
+ expect(handler).toBeGreaterThanOrEqual(0);
+ const gate = source.indexOf('routeDefaultChanged', handler);
+ const backfill = source.indexOf('prepareImDefaultSettingsChange(', handler);
+ expect(gate).toBeGreaterThan(handler);
+ expect(gate).toBeLessThan(backfill);
+ },
+ );
+});
diff --git a/apps/desktop/src/main/__tests__/imStartupDefaultRouteBackfill.test.ts b/apps/desktop/src/main/__tests__/imStartupDefaultRouteBackfill.test.ts
new file mode 100644
index 0000000000..22a92f4cd3
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/imStartupDefaultRouteBackfill.test.ts
@@ -0,0 +1,19 @@
+import { readFileSync } from 'node:fs';
+
+import { describe, expect, it } from 'vitest';
+
+const source = readFileSync(new URL('../im/index.ts', import.meta.url), 'utf8');
+
+describe('im startup default route backfill wiring', () => {
+ // 启动期补齐历史任务的跟随记录(PR #5155 review P2): 回填不能只等设置保存/
+ // 重置触发 —— 从未动过设置的升级老任务要靠 startImConnection(localDb 就绪
+ // 权威时点)带起的这次补齐拿到记录。
+ it('kicks the startup backfill from startImConnection', () => {
+ const start = source.indexOf('export function startImConnection');
+ expect(start).toBeGreaterThanOrEqual(0);
+ const backfill = source.indexOf('void backfillImDefaultRoutesAtStartup();', start);
+ const connect = source.indexOf('connectionLifecycle.start();', start);
+ expect(backfill).toBeGreaterThan(start);
+ expect(connect).toBeGreaterThan(backfill);
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
index a0a2e11843..8c8130209f 100644
--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
@@ -382,11 +382,14 @@ describe('session runtime control wiring', () => {
const axisValidation = setModel.indexOf('if (atomicSelection) {');
expect(axisValidation).toBeGreaterThan(-1);
expect(setModel).not.toContain("if (internalOptions.source !== 'user' && atomicSelection)");
+ // 用户 picker 选择按显式能力校验; 配置跟随(configStaged)带的是任务已有的
+ // 档位/Fast(Fast 根本不在渠道默认里), 不是用户对目标模型的显式选择 ——
+ // 目标模型不支持时轴收敛而不是拒(PR #5155 review P2)。
expect(setModel).toContain(
- "internalOptions.source === 'user' || internalOptions.effortExplicit === true",
+ 'effortExplicit:\n (internalOptions.source === \'user\' && internalOptions.configStaged !== true) ||\n internalOptions.effortExplicit === true',
);
expect(setModel).toContain(
- "internalOptions.source === 'user' || internalOptions.fastExplicit === true",
+ 'fastExplicit:\n (internalOptions.source === \'user\' && internalOptions.configStaged !== true) ||\n internalOptions.fastExplicit === true',
);
expect(setModel).toContain("allowFixedEffortPlaceholder: internalOptions.source === 'user'");
expect(axisValidation).toBeLessThan(setModel.indexOf('applyRuntimeSetModelChange({'));
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index f612df946d..f98c8e3e4b 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -272,6 +272,7 @@ import {
im,
feishuIm,
telegramIm,
+ prepareImDefaultSettingsChange,
registerTelegramBotConfigIpc,
startImOrchestrators,
startImConnection,
@@ -808,12 +809,17 @@ import {
shouldStartReadinessConsumers,
} from './maker-host/account-provider-readiness-ensure.js';
import {
+ previewImDefaultSettingsPatch,
readImDefaultSettingsState,
resetImDefaultSettings,
resetImDefaultSettingsGlobal,
resetImDefaultSettingsChannel,
writeImDefaultSettingsPatch,
} from './im/defaultSettingsStore.js';
+import { readImDefaultSettingsFingerprint } from './im/defaultSessionSettings.js';
+import { fingerprintImDefaultSettings } from './im/shared/channelDefaultRoute.js';
+import { IM_DEFAULT_SETTINGS } from '../shared/imDefaultSettings.js';
+import { assertOwnerScopeSettledForWrite } from './im/ownerScopedStorage.js';
import { hasClaudeNativeLogin } from './maker-host/claude-native-auth.js';
import {
connectClaudeNativeLogin,
@@ -4700,15 +4706,76 @@ const registerIpcHandlers = () => {
});
ipcMain.handle(
MAKER_IPC_INVOKE.IM_DEFAULT_SETTINGS_SET,
- async (_e, patch: unknown, rawChannel: unknown) => {
+ async (event, patch: unknown, rawChannel: unknown) => {
+ // 本 handler 已升级为可批量改任务记录、并在下一条 IM 消息时切任务路由的操作,
+ // 必须先验证调用方是可信主渲染器 —— 不能让被导航到外部页面的 preload 窗口
+ // 改写渠道默认(PR #5155 review P1, 同 SUBAGENT_MODEL_SETTINGS_SET)。
+ assertTrustedAppRendererEvent(event);
+ // owner 边界(PR #5155 review P1): 回填跨多个 await, 期间登出/切号会让落库与
+ // 设置写入漂到别的 owner —— 进入时快照 owner scope; 回填自身已在
+ // prepareImDefaultSettingsChange 内固定 DbClient 并复核 epoch, 这里在写设置
+ // 前的同一同步块内再校验 scope 未变且无 boundary 在途, 不满足失败重试。
+ const ownerScopeKey = activeOwnerScopeKey();
const channel = parseImDefaultSettingsChannel(rawChannel);
const parsedPatch = parseImDefaultSettingsPatch(patch);
+ // 仅路由默认实际变化时才要求阻塞式回填(PR #5155 review P2): 只改权限档等
+ // 不动路由指纹的保存不该被无关的供应商目录故障挡下 —— 路由默认没变就不存在
+ // 「提交后丢失回填机会」。
+ const routeDefaultChanged =
+ fingerprintImDefaultSettings(previewImDefaultSettingsPatch(parsedPatch, channel)) !==
+ readImDefaultSettingsFingerprint(channel);
+ // 写新设置之前按旧默认给老任务补跟随记录(见 prepareImDefaultSettingsChange)。
+ // 回填失败必须挡住本次保存: 记录补不上就提交新默认的话, 还停在旧默认上的
+ // 老任务之后只能按新默认匹配, 永久失去跟随资格(PR #5155 review P2)。
+ if (routeDefaultChanged) {
+ try {
+ await prepareImDefaultSettingsChange(channel);
+ } catch (err) {
+ throwIpcError(
+ 'INTERNAL',
+ `渠道默认未保存:旧任务的跟随记录补全失败,请重试(${err instanceof Error ? err.message : String(err)})`,
+ );
+ }
+ }
+ try {
+ assertOwnerScopeSettledForWrite(ownerScopeKey);
+ } catch (err) {
+ throwIpcError(
+ 'INTERNAL',
+ `渠道默认未保存:账号切换中,请重试(${err instanceof Error ? err.message : String(err)})`,
+ );
+ }
writeImDefaultSettingsPatch(parsedPatch, channel);
return imDefaultSettingsWire(channel);
},
);
- ipcMain.handle(MAKER_IPC_INVOKE.IM_DEFAULT_SETTINGS_RESET, async (_e, rawChannel: unknown) => {
+ ipcMain.handle(MAKER_IPC_INVOKE.IM_DEFAULT_SETTINGS_RESET, async (event, rawChannel: unknown) => {
+ // 同 SET: 回填会批量改任务记录, 必须先验证调用方(PR #5155 review P1)。
+ assertTrustedAppRendererEvent(event);
+ // 同 SET: 进入时快照 owner scope, 写设置前校验 scope 未变且无 boundary 在途。
+ const ownerScopeKey = activeOwnerScopeKey();
const channel = parseImDefaultSettingsChannel(rawChannel);
+ // 同 SET: 仅路由默认实际变化时才要求阻塞式回填(PR #5155 review P2)。
+ const routeDefaultChanged =
+ readImDefaultSettingsFingerprint(channel) !== fingerprintImDefaultSettings(IM_DEFAULT_SETTINGS);
+ if (routeDefaultChanged) {
+ try {
+ await prepareImDefaultSettingsChange(channel);
+ } catch (err) {
+ throwIpcError(
+ 'INTERNAL',
+ `渠道默认未重置:旧任务的跟随记录补全失败,请重试(${err instanceof Error ? err.message : String(err)})`,
+ );
+ }
+ }
+ try {
+ assertOwnerScopeSettledForWrite(ownerScopeKey);
+ } catch (err) {
+ throwIpcError(
+ 'INTERNAL',
+ `渠道默认未重置:账号切换中,请重试(${err instanceof Error ? err.message : String(err)})`,
+ );
+ }
if (channel) {
resetImDefaultSettingsChannel(channel);
} else {
diff --git a/apps/desktop/src/main/im/__tests__/defaultSettingsStore.test.ts b/apps/desktop/src/main/im/__tests__/defaultSettingsStore.test.ts
index 2ae3df3d4a..af746ab066 100644
--- a/apps/desktop/src/main/im/__tests__/defaultSettingsStore.test.ts
+++ b/apps/desktop/src/main/im/__tests__/defaultSettingsStore.test.ts
@@ -33,6 +33,7 @@ vi.mock('../ownerScopedStorage.js', () => ({
import { IM_DEFAULT_SETTINGS } from '../../../shared/imDefaultSettings.js';
import {
__testing,
+ previewImDefaultSettingsPatch,
readImDefaultSettings,
readImDefaultSettingsState,
resetImDefaultSettings,
@@ -76,6 +77,20 @@ describe('im default settings store', () => {
expect(normalized.agents['claude-code']).toEqual(IM_DEFAULT_SETTINGS.agents['claude-code']);
});
+ it('previews a patch merge without writing (route-change gate for the blocking backfill)', () => {
+ writeImDefaultSettingsPatch({ agents: { codex: { providerId: null, model: 'gpt-5.5', effort: 'high' } } }, 'feishu');
+ const before = readImDefaultSettings('feishu');
+
+ const merged = previewImDefaultSettingsPatch({ groupPermissionMode: 'bypassPermissions' }, 'feishu');
+
+ // 合并结果包含补丁效果, 路由轴与现状一致 —— 调用方据此判断路由指纹是否变化。
+ expect(merged.groupPermissionMode).toBe('bypassPermissions');
+ expect(merged.agentKind).toBe(before.agentKind);
+ expect(merged.agents).toEqual(before.agents);
+ // 预览不写盘。
+ expect(readImDefaultSettings('feishu')).toEqual(before);
+ });
+
it('persists only the changed agent override so untouched agents keep inheriting future defaults', () => {
writeImDefaultSettingsPatch({
agents: {
diff --git a/apps/desktop/src/main/im/__tests__/ownerScopedStorage.test.ts b/apps/desktop/src/main/im/__tests__/ownerScopedStorage.test.ts
index 19f14f5e52..e0977d80ed 100644
--- a/apps/desktop/src/main/im/__tests__/ownerScopedStorage.test.ts
+++ b/apps/desktop/src/main/im/__tests__/ownerScopedStorage.test.ts
@@ -12,6 +12,8 @@ interface TestSession {
const mocks = vi.hoisted(() => ({
root: '',
+ ownerScopeKey: 'owner-1',
+ boundaryPending: false,
session: {
mode: 'signed-out',
dataOwnerId: null,
@@ -36,6 +38,8 @@ vi.mock('electron', () => ({
vi.mock('../../appSessionState.js', () => ({
getActiveAppSession: () => ({ ...mocks.session }),
+ activeOwnerScopeKey: () => mocks.ownerScopeKey,
+ isAppSessionBoundaryPending: () => mocks.boundaryPending,
dataOwnerStorageKey: (ownerId: string) => `key-${ownerId}`,
ownerScopedUserDataPath: (...parts: string[]) => {
const owner = mocks.session.dataOwnerId;
@@ -53,7 +57,7 @@ vi.mock('../../ownerNamespaceMigration.js', () => ({
hasLegacyOwnerNamespaceClaim: () => true,
}));
-import { __testing, claimLegacyImPath, ownerScopedImSecrets } from '../ownerScopedStorage';
+import { __testing, assertOwnerScopeSettledForWrite, claimLegacyImPath, ownerScopedImSecrets } from '../ownerScopedStorage';
function setSession(mode: TestSession['mode'], ownerId: string | null): void {
mocks.session = { mode, dataOwnerId: ownerId, generation: mocks.session.generation + 1 };
@@ -69,6 +73,8 @@ function writeLegacySecret(name: string, value: string): string {
describe('IM owner-scoped storage', () => {
beforeEach(() => {
mocks.root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-im-owner-scope-'));
+ mocks.ownerScopeKey = 'owner-1';
+ mocks.boundaryPending = false;
setSession('signed-out', null);
});
@@ -76,6 +82,20 @@ describe('IM owner-scoped storage', () => {
fs.rmSync(mocks.root, { recursive: true, force: true });
});
+ it('assertOwnerScopeSettledForWrite fail-closes owner switches and in-flight boundaries', () => {
+ // 写设置前的账号边界校验(PR #5155 review P1): scope 未变且无 boundary 在途才
+ // 允许写 owner 域存储 —— 登出/切号过渡期间写入会落进登出命名空间或下一个
+ // 账号; 不满足即抛错让保存失败重试。
+ expect(() => assertOwnerScopeSettledForWrite(mocks.ownerScopeKey)).not.toThrow();
+
+ mocks.boundaryPending = true;
+ expect(() => assertOwnerScopeSettledForWrite(mocks.ownerScopeKey)).toThrow(/retry the save/);
+
+ mocks.boundaryPending = false;
+ mocks.ownerScopeKey = 'owner-2';
+ expect(() => assertOwnerScopeSettledForWrite('owner-1')).toThrow(/retry the save/);
+ });
+
it('isolates credentials by data owner and never lets local claim cloud legacy data', () => {
const legacy = writeLegacySecret('feishu_bot_app_secret', 'legacy-cloud-secret');
diff --git a/apps/desktop/src/main/im/defaultSessionSettings.ts b/apps/desktop/src/main/im/defaultSessionSettings.ts
index 758badc031..c4f5afdd1a 100644
--- a/apps/desktop/src/main/im/defaultSessionSettings.ts
+++ b/apps/desktop/src/main/im/defaultSessionSettings.ts
@@ -32,6 +32,7 @@ import { createLogger } from '../logger';
import { getMaker } from '../maker-host';
import { getDesktopProviderService } from '../maker-host/createDesktopProviderService';
import { readImDefaultSettings } from './defaultSettingsStore';
+import { fingerprintImDefaultSettings, type ImDefaultRoute } from './shared/channelDefaultRoute';
import type { ImOrchestratorConfig } from './shared/types';
const log = createLogger('im:defaults');
@@ -43,6 +44,8 @@ export interface ResolvedImSessionDefaults {
providerId: string | null;
permissionMode: PermissionMode;
fastMode: boolean;
+ /** 本次解析所读原始设置的指纹(与上面的值出自同一次读取), 写进任务的跟随记录。 */
+ fingerprint: string;
}
export function getImDefaultEffortFor(
@@ -99,6 +102,31 @@ export async function resolveImSessionDefaults(
providerId,
permissionMode: raw.permissionMode ?? config.defaultPermissionMode,
fastMode: false,
+ fingerprint: fingerprintImDefaultSettings(raw),
+ };
+}
+
+/** 渠道当前原始设置的指纹 —— 不读供应商列表, 供每条消息的廉价比对。 */
+export function readImDefaultSettingsFingerprint(channel?: ImDefaultSettingsChannel): string {
+ return fingerprintImDefaultSettings(readImDefaultSettings(channel));
+}
+
+/**
+ * 保存的原始默认路由 —— **不经过**模型可用性回落 / 来源改道。
+ *
+ * `resolveImSessionDefaults` 在旧默认失效(来源断开、模型停用/下架)时会把落点
+ * 挪到别的可用路由上; 而历史任务记录的是当年真实落到的旧路由。给「按旧默认认领
+ * 历史任务」这类值比较用的必须是这份原始值, 否则旧默认一坏就永远匹配不到
+ * (PR #5155 review P2)。
+ */
+export function readImRawDefaultRoute(channel?: ImDefaultSettingsChannel): ImDefaultRoute {
+ const raw = readImDefaultSettings(channel);
+ const settings = raw.agents[raw.agentKind];
+ return {
+ agentKind: raw.agentKind,
+ model: settings.model,
+ providerId: settings.providerId?.trim() || null,
+ effort: settings.effort,
};
}
diff --git a/apps/desktop/src/main/im/defaultSettingsStore.ts b/apps/desktop/src/main/im/defaultSettingsStore.ts
index 885328a1b1..dcdfc00e37 100644
--- a/apps/desktop/src/main/im/defaultSettingsStore.ts
+++ b/apps/desktop/src/main/im/defaultSettingsStore.ts
@@ -265,6 +265,19 @@ export function writeImDefaultSettingsPatch(
return readImDefaultSettingsState(channel);
}
+/**
+ * 合并后的设置预览(不写盘) —— 保存前比较路由指纹用: 只改权限档等不动路由默认的
+ * 保存, 不该被阻塞式回填(PR #5155 review P2)。
+ */
+export function previewImDefaultSettingsPatch(
+ patch: ImDefaultSettingsPatch,
+ channel?: ImDefaultSettingsChannel,
+): ImDefaultSettings {
+ const document = store.read();
+ const current = channel ? document.channels[channel] : document.global;
+ return mergeSettingsPatch(current, patch);
+}
+
export function resetImDefaultSettings(): ImDefaultSettings {
return store.reset().global;
}
diff --git a/apps/desktop/src/main/im/discord/__tests__/sessionAuth.test.ts b/apps/desktop/src/main/im/discord/__tests__/sessionAuth.test.ts
index eba2f6eb88..d0a7ea4c06 100644
--- a/apps/desktop/src/main/im/discord/__tests__/sessionAuth.test.ts
+++ b/apps/desktop/src/main/im/discord/__tests__/sessionAuth.test.ts
@@ -74,6 +74,7 @@ describe('checkDiscordSessionAuth', () => {
providerId: 'openai',
permissionMode: 'auto' as const,
fastMode: false,
+ fingerprint: 'fp',
};
});
const checkAuth = vi.fn(
@@ -117,6 +118,7 @@ describe('checkDiscordSessionAuth', () => {
providerId: 'anthropic',
permissionMode: 'auto' as const,
fastMode: false,
+ fingerprint: 'fp',
}));
const checkAuth = vi.fn(async () => ({ ok: true, missing: null }));
diff --git a/apps/desktop/src/main/im/discord/uiText.ts b/apps/desktop/src/main/im/discord/uiText.ts
index 3c386d13c7..6c421dd462 100644
--- a/apps/desktop/src/main/im/discord/uiText.ts
+++ b/apps/desktop/src/main/im/discord/uiText.ts
@@ -54,7 +54,7 @@ export const ui = {
const message = `⚠️ 当前 Discord 对话使用供应商「${provider}」(${model}),${reason}。`;
return attached
? `${message}\n请在 desktop 的 Settings → 模型供应商中修复认证后,直接继续发送消息。`
- : `${message}\n“新对话配置”只影响新对话;修改后请发送 \`/new\`,再继续聊天。`;
+ : `${message}\n修改“新对话配置”后直接继续发送消息即可;若当前对话单独选过模型,请发送 \`/model\` 重新选择。`;
},
controlInProgress:
'🎮 你 /ctr 还在选择中呢 — 先把上面那张卡片操作完(或点 🚪 退出),再来发别的~',
diff --git a/apps/desktop/src/main/im/feishu/uiText.ts b/apps/desktop/src/main/im/feishu/uiText.ts
index 7823a9fda7..35f6e46d28 100644
--- a/apps/desktop/src/main/im/feishu/uiText.ts
+++ b/apps/desktop/src/main/im/feishu/uiText.ts
@@ -59,7 +59,7 @@ export const ui = {
const message = `⚠️ 当前对话使用供应商「${provider}」(${model}),${reason}。`;
return attached
? `${message}\n请在 desktop 的 Settings → 模型供应商中修复认证后,直接继续发送消息。`
- : `${message}\n“新对话配置”只影响新对话;修改后请发送 \`/new\`,再继续聊天。`;
+ : `${message}\n修改“新对话配置”后直接继续发送消息即可;若当前对话单独选过模型,请发送 \`/model\` 重新选择。`;
},
controlInProgress:
'🎮 你 /ctr 还在选择中呢 — 先把上面那张卡片操作完(或点 🚪 退出),再来发别的~',
diff --git a/apps/desktop/src/main/im/index.ts b/apps/desktop/src/main/im/index.ts
index 125b90513d..7fb756d0f6 100644
--- a/apps/desktop/src/main/im/index.ts
+++ b/apps/desktop/src/main/im/index.ts
@@ -59,6 +59,10 @@ import { ipcMain, BrowserWindow, dialog, type IpcMainEvent } from 'electron';
import { and, eq, like, ne, sql } from 'drizzle-orm';
import { getDbClient } from '../localDb/client/current';
+import {
+ captureSessionRuntimeControlOwnerEpoch,
+ sessionRuntimeControlOwnerEpochMatches,
+} from '../maker-ipc/sessionRuntimeControl.js';
import { sessions } from '../localDb/schema';
import {
im,
@@ -78,6 +82,8 @@ import { wireWechatOrchestrator } from './wechat';
import { wireWecomOrchestrator } from './wecom';
import { resetTelegramGroupContextCursors } from './telegram/groupWindow';
import { getImOrchestrator, listImOrchestrators } from './shared/orchestrator';
+import { backfillLegacyImDefaultRoutes, backfillLegacyImDefaultRoutesAtStartup } from './shared/channelDefaultRouteSync';
+import type { ImDefaultSettingsChannel } from '../../shared/imDefaultSettings';
import { createSerializedConnectionLifecycle } from './connectionLifecycle';
import {
activateImAccountBoundary,
@@ -89,7 +95,7 @@ import {
import { configureImAccountScope } from './accountScopeBridge';
import type { ImOrchestratorConfig } from './shared/types';
import { bindingStore, executeDetach } from './binding';
-import { IM_DEFAULT_EFFORT_OVERRIDES, IM_DEFAULT_SETTINGS } from '../../shared/imDefaultSettings';
+import { IM_DEFAULT_EFFORT_OVERRIDES, IM_DEFAULT_SETTINGS, IM_DEFAULT_SETTINGS_CHANNELS } from '../../shared/imDefaultSettings';
import { getAuthState } from '../authManager';
import { getUpdateStatus, isUpdateRelaunchImminent } from '../updateService';
@@ -626,6 +632,53 @@ configureImAccountScope({
* `feishuBot:save` kept failing with `[IM_NOT_READY]` (the account boundary is
* activated inside `im.init()`), with no way out but manually updating.
*/
+/**
+ * 渠道默认即将被保存 / 恢复: 先给上线前建的、仍在用旧默认的任务补跟随记录,
+ * 让它们在下一条消息时换到新默认。只处理指定渠道(各渠道设置相互独立, 全局
+ * 设置只给官方 hook 用)。
+ *
+ * 补录失败**必须挡住本次保存**(PR #5155 review P2): 记录补不上就提交新默认的话,
+ * 还停在旧默认上的老任务之后只能按新默认匹配, 永久失去跟随资格。抛错让调用方
+ * 放弃本次保存, 用户重试即可; 不把失败当已完成。
+ */
+export async function prepareImDefaultSettingsChange(
+ channel: ImDefaultSettingsChannel | undefined,
+): Promise<void> {
+ if (!channel) return;
+ const config = getImOrchestrator(channel)?.adapter.config;
+ if (!config) return;
+ // owner 边界(PR #5155 review P1): 回填跨多个 await, 期间登出/换号会让全局
+ // getDbClient 指向新 owner —— 进入时捕获 owner epoch 与 DbClient, 回填全程复用
+ // 同一客户端; 结束后校验边界未变, 变了就失败重试, 绝不把 A 发起的保存写进 B。
+ const ownerEpoch = captureSessionRuntimeControlOwnerEpoch();
+ const dbClient = getDbClient();
+ try {
+ await backfillLegacyImDefaultRoutes(channel, config, dbClient);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ log.warn(`default route backfill failed for ${channel} (blocking settings save): ${msg}`);
+ throw new Error(msg);
+ }
+ if (!sessionRuntimeControlOwnerEpochMatches(ownerEpoch)) {
+ log.warn(`default route backfill raced an owner switch for ${channel}; save aborted for retry`);
+ throw new Error('app session owner changed during backfill; retry the save');
+ }
+}
+
+/**
+ * 启动期一次性补齐各渠道历史任务的跟随记录: 枚举有 orchestrator 配置的渠道,
+ * 交给 backfillLegacyImDefaultRoutesAtStartup 逐个 best-effort 补齐。
+ */
+export async function backfillImDefaultRoutesAtStartup(): Promise<void> {
+ await backfillLegacyImDefaultRoutesAtStartup(
+ IM_DEFAULT_SETTINGS_CHANNELS.flatMap((source) => {
+ const config = getImOrchestrator(source)?.adapter.config;
+ return config ? [{ source, config }] : [];
+ }),
+ getDbClient(),
+ );
+}
+
export function startImConnection(): void {
if (connectionLifecycle.isStarted()) {
log.info('startImConnection: already started, skip');
@@ -640,6 +693,11 @@ export function startImConnection(): void {
}
log.info('startImConnection: kicking off im.init()');
+ // 启动期补齐历史任务的跟随记录(见 backfillLegacyImDefaultRoutesAtStartup):
+ // 从未保存/重置过渠道设置的升级老任务等不到设置保存触发回填, 趁当前基线还能
+ // 识别先补一次, 不依赖用户以后主动保存(PR #5155 review P2)。后台 best-effort,
+ // 不挡连接; DbClient 同样要求 localDb 已 ensureReady, 时序保证同下。
+ void backfillImDefaultRoutesAtStartup();
// 先 preload binding 表, 再 init bot WS。preload 必须在 init 之前完成 ——
// bot 上线后第一个进来的消息会经 runAgentTurn 同步查 bindingStore.get(),
// 此时 forward map 必须已经填好, 否则会被当成"没接管"误路由到默认 session。
diff --git a/apps/desktop/src/main/im/ownerScopedStorage.ts b/apps/desktop/src/main/im/ownerScopedStorage.ts
index 18c389eb20..6224f1e45e 100644
--- a/apps/desktop/src/main/im/ownerScopedStorage.ts
+++ b/apps/desktop/src/main/im/ownerScopedStorage.ts
@@ -11,8 +11,10 @@ import path from 'node:path';
import type { IMHost, IMSecretReadResult } from '@cindy/im';
import {
+ activeOwnerScopeKey,
dataOwnerStorageKey,
getActiveAppSession,
+ isAppSessionBoundaryPending,
ownerScopedUserDataPath,
} from '../appSessionState.js';
import { hasLegacyOwnerNamespaceClaim } from '../ownerNamespaceMigration.js';
@@ -38,6 +40,19 @@ function currentVerifiedCloudOwnerKey(): string | null {
return dataOwnerStorageKey(session.dataOwnerId);
}
+/**
+ * 写 owner 域设置前的账号边界校验(PR #5155 review P1): 进入 handler 时快照的
+ * owner scope 仍未变、且没有登出/切号 boundary 在途, 才允许把本次保存写进 owner
+ * 域存储 —— boundary 在途时「当前 owner」处于 A→B 的过渡, 写入会落进登出命名空间
+ * 或下一个账号; 不满足即抛错失败重试(与 botModelRouteReconciler / SUBAGENT 设置
+ * 同口径: boundary 在途一律 fail-closed)。
+ */
+export function assertOwnerScopeSettledForWrite(expectedScopeKey: string): void {
+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== expectedScopeKey) {
+ throw new Error('app session owner boundary active or changed; retry the save');
+ }
+}
+
function readLegacyOwnerKey(): string | null | undefined {
const marker = legacyOwnerMarkerPath();
if (!fs.existsSync(marker)) return undefined;
diff --git a/apps/desktop/src/main/im/shared/__tests__/cardActionTakeoverReplace.test.ts b/apps/desktop/src/main/im/shared/__tests__/cardActionTakeoverReplace.test.ts
index 22b6487eaf..2260f6a46b 100644
--- a/apps/desktop/src/main/im/shared/__tests__/cardActionTakeoverReplace.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/cardActionTakeoverReplace.test.ts
@@ -34,6 +34,7 @@ const mocks = vi.hoisted(() => ({
readPermissionMode: vi.fn(async () => 'auto'),
updatePermissionMode: vi.fn(async () => {}),
updateModelEffort: vi.fn(async () => {}),
+ markManualOverride: vi.fn(async () => {}),
getSessionProvider: vi.fn<() => string | null>(() => null),
setSessionProvider: vi.fn(),
isSessionInTurn: vi.fn(() => false),
@@ -84,6 +85,9 @@ vi.mock('../sessionRepo', () => ({
updateModelEffort: mocks.updateModelEffort,
updatePermissionMode: mocks.updatePermissionMode,
}));
+vi.mock('../manualRouteOverride', () => ({
+ markImSessionManualRouteOverride: mocks.markManualOverride,
+}));
vi.mock('../../../maker-host/session-provider-store', () => ({
getSessionProvider: mocks.getSessionProvider,
normalizeSessionProviderId: (providerId: string | null | undefined) =>
@@ -826,6 +830,62 @@ describe('model:pick 持久化失败', () => {
expect(mocks.cancelPendingAgentSwitchForSession).not.toHaveBeenCalled();
});
+ it('选择落地后才写「脱离跟随」手动墓碑', async () => {
+ // 「单独改过」按选择行为判定、不看取值相等(同值重选也永久脱离),
+ // 但必须在选择真正落地后写(PR #5155 review P2)。
+ const im = makeIm();
+
+ await pressModelPick(im);
+
+ expect(mocks.markManualOverride).toHaveBeenCalledWith('sess-target');
+ expect(mocks.cancelPendingAgentSwitchForSession).toHaveBeenCalledWith('sess-target');
+ });
+
+ it('失败回滚的选择不写手动墓碑', async () => {
+ // 若在 updateModelEffort 里立碑, 失败回滚(同一函数)会让失败的选择永久脱离
+ // 默认跟随(PR #5155 review P2)。
+ mocks.readModelRouteSnapshot.mockResolvedValueOnce({
+ model: 'claude-sonnet-4-6',
+ effort: 'medium',
+ providerId: 'openrouter',
+ });
+ mocks.applyRuntimeSetModelChange.mockRejectedValueOnce(new Error('runtime rejected'));
+ const im = makeIm();
+
+ await pressModelPick(im);
+
+ expect(mocks.markManualOverride).not.toHaveBeenCalled();
+ expect(mocks.cancelPendingAgentSwitchForSession).not.toHaveBeenCalled();
+ });
+
+ it('墓碑写失败按选择失败处理: 整体回滚并报错', async () => {
+ mocks.readModelRouteSnapshot.mockResolvedValueOnce({
+ model: 'claude-sonnet-4-6',
+ effort: 'medium',
+ providerId: 'openrouter',
+ });
+ mocks.markManualOverride.mockRejectedValueOnce(new Error('db closed'));
+ const im = makeIm();
+
+ await pressModelPick(im);
+
+ expect(mocks.updateModelEffort).toHaveBeenNthCalledWith(
+ 2,
+ 'sess-target',
+ 'claude-sonnet-4-6',
+ 'medium',
+ 'openrouter',
+ );
+ // 延迟凭证切换登记也要一并撤销, 否则 turn 收口仍会应用已报失败的选择
+ // (PR #5155 review P2)。
+ expect(mocks.clearPendingCredentialSwitchForSession).toHaveBeenCalledWith('sess-target');
+ expect(mocks.cancelPendingAgentSwitchForSession).not.toHaveBeenCalled();
+ expect(im.updateInteractiveCard).toHaveBeenCalledWith(
+ 'model-card',
+ expect.objectContaining({ body: slackUi.cards.model.failed('db closed') }),
+ );
+ });
+
it('live setEffort 失败时恢复 route store 和 live model', async () => {
const live = {
agentKind: 'claude-code',
diff --git a/apps/desktop/src/main/im/shared/__tests__/channelDefaultRoute.test.ts b/apps/desktop/src/main/im/shared/__tests__/channelDefaultRoute.test.ts
new file mode 100644
index 0000000000..eae52e17a2
--- /dev/null
+++ b/apps/desktop/src/main/im/shared/__tests__/channelDefaultRoute.test.ts
@@ -0,0 +1,227 @@
+import { describe, expect, it } from 'vitest';
+
+import { IM_DEFAULT_SETTINGS, type ImDefaultSettings } from '../../../../shared/imDefaultSettings';
+import {
+ buildImDefaultRouteRecord,
+ buildImManualRouteOverrideRecord,
+ decideImDefaultRoute,
+ fingerprintImDefaultSettings,
+ imDefaultRouteMayNeedSync,
+ parseImDefaultRouteRecord,
+ sameImDefaultRoute,
+ type ImDefaultRoute,
+ type ImDefaultRouteRecord,
+} from '../channelDefaultRoute';
+
+const OLD: ImDefaultRoute = { agentKind: 'claude-code', model: 'claude-opus-4-8', providerId: null, effort: 'xhigh' };
+const NEW: ImDefaultRoute = { agentKind: 'codex', model: 'gpt-5.5', providerId: 'openai', effort: 'high' };
+const PICKED: ImDefaultRoute = { agentKind: 'claude-code', model: 'claude-sonnet-5', providerId: 'xd', effort: 'high' };
+
+function record(overrides: Partial<ImDefaultRouteRecord> = {}): ImDefaultRouteRecord {
+ return { v: 1, fp: 'fp-old', route: OLD, ...overrides };
+}
+
+function settings(patch: Partial<ImDefaultSettings> = {}): ImDefaultSettings {
+ return { ...structuredClone(IM_DEFAULT_SETTINGS), ...patch };
+}
+
+describe('fingerprintImDefaultSettings', () => {
+ it('changes with any engine route setting but not with permission modes', () => {
+ const base = settings();
+ const fp = fingerprintImDefaultSettings(base);
+ expect(fingerprintImDefaultSettings(settings({ permissionMode: 'bypassPermissions' }))).toBe(fp);
+ expect(fingerprintImDefaultSettings(settings({ groupPermissionMode: 'ask' }))).toBe(fp);
+ expect(fingerprintImDefaultSettings(settings({ agentKind: 'codex' }))).not.toBe(fp);
+ // 选定引擎之外的设置也算: 选定引擎的模型全被停用时会回落到别的引擎。
+ const pi = structuredClone(base);
+ pi.agents.pi.model = 'other-model';
+ expect(fingerprintImDefaultSettings(pi)).not.toBe(fp);
+ const effort = structuredClone(base);
+ effort.agents[base.agentKind].effort = 'low';
+ expect(fingerprintImDefaultSettings(effort)).not.toBe(fp);
+ });
+});
+
+describe('im default route record', () => {
+ it('round-trips and rejects malformed records', () => {
+ const json = buildImDefaultRouteRecord('fp', OLD, { route: NEW, fp: 'fp-new' });
+ expect(parseImDefaultRouteRecord(json)).toEqual({ v: 1, fp: 'fp', route: OLD, pendingRoute: NEW, pendingFp: 'fp-new' });
+ expect(
+ parseImDefaultRouteRecord(buildImDefaultRouteRecord('fp', OLD, { route: NEW, fp: 'fp-new', rev: 7 })),
+ ).toEqual({ v: 1, fp: 'fp', route: OLD, pendingRoute: NEW, pendingFp: 'fp-new', pendingRev: 7 });
+ expect(parseImDefaultRouteRecord(buildImDefaultRouteRecord('fp', OLD))).toEqual({ v: 1, fp: 'fp', route: OLD });
+ expect(parseImDefaultRouteRecord(buildImManualRouteOverrideRecord(OLD))).toEqual({
+ v: 1,
+ fp: '',
+ route: OLD,
+ manual: true,
+ });
+ expect(parseImDefaultRouteRecord(null)).toBeNull();
+ expect(parseImDefaultRouteRecord('not json')).toBeNull();
+ expect(parseImDefaultRouteRecord(JSON.stringify({ v: 2, fp: 'fp', route: OLD }))).toBeNull();
+ expect(parseImDefaultRouteRecord(JSON.stringify({ v: 1, fp: 'fp', route: { ...OLD, agentKind: 'x' } }))).toBeNull();
+ expect(parseImDefaultRouteRecord(JSON.stringify({ v: 1, fp: 'fp', route: OLD, pendingRoute: {} }))).toBeNull();
+ });
+
+ it('only resolves new defaults when the settings fingerprint moved', () => {
+ expect(imDefaultRouteMayNeedSync(null, 'fp-new')).toBe(false);
+ expect(imDefaultRouteMayNeedSync(record(), 'fp-old')).toBe(false);
+ expect(imDefaultRouteMayNeedSync(record(), 'fp-new')).toBe(true);
+ });
+});
+
+describe('sameImDefaultRoute', () => {
+ it('treats an implicit provider and its pinned source as the same route', () => {
+ const pinned = { ...OLD, providerId: 'xd' };
+ expect(sameImDefaultRoute(OLD, pinned)).toBe(false);
+ expect(sameImDefaultRoute(OLD, pinned, (route) => route.providerId ?? 'xd')).toBe(true);
+ expect(sameImDefaultRoute(OLD, { ...OLD, effort: 'low' }, (route) => route.providerId ?? 'xd')).toBe(false);
+ });
+});
+
+describe('decideImDefaultRoute', () => {
+ const decide = (input: Omit<Parameters<typeof decideImDefaultRoute>[0], 'targetFp'> & { targetFp?: string }) =>
+ decideImDefaultRoute({ targetFp: 'fp-new', ...input });
+
+ it('switches a task that still runs the recorded default', () => {
+ expect(decide({ record: record(), current: OLD, target: NEW })).toEqual({ kind: 'switch' });
+ });
+
+ it('keeps a task the user changed (applied pick)', () => {
+ expect(decide({ record: record(), current: PICKED, target: NEW })).toEqual({ kind: 'manual' });
+ });
+
+ it('keeps a task whose user pick is still pending', () => {
+ expect(
+ decide({ record: record(), current: OLD, target: NEW, pendingIntent: PICKED }),
+ ).toEqual({ kind: 'manual' });
+ });
+
+ it('adopts the record when the task still runs the recorded route', () => {
+ expect(decide({ record: record(), current: OLD, target: OLD })).toEqual({ kind: 'adopt' });
+ });
+
+ it('adopts the record when its own pending target already landed on the task', () => {
+ // 发送路径替本功能应用了意图、记录还没跟上: 仍是跟随中的任务, 只补指纹。
+ expect(
+ decide({ record: record({ pendingRoute: NEW, pendingFp: 'fp-older' }), current: NEW, target: NEW }),
+ ).toEqual({ kind: 'adopt' });
+ });
+
+ it('does not adopt a manual pick that happens to equal the new default', () => {
+ // 用户单独改成 NEW、默认随后也改到 NEW: 不能洗成跟随, 否则下次默认变化会盖掉用户的选择
+ // (chatgpt-codex-connector P2, PR #5155)。
+ expect(decide({ record: record(), current: NEW, target: NEW })).toEqual({ kind: 'manual' });
+ });
+
+ it('never follows again once the task carries a manual override marker', () => {
+ // 同值重选在路由值上无痕, 选择落地时立墓碑; 此后无论默认怎么变都不跟随
+ // (greptile P1 补充, PR #5155)。
+ const tombstoned = { ...record(), manual: true as const };
+ expect(decide({ record: tombstoned, current: OLD, target: NEW })).toEqual({ kind: 'manual' });
+ expect(decide({ record: tombstoned, current: OLD, target: OLD })).toEqual({ kind: 'manual' });
+ expect(decide({ record: tombstoned, current: NEW, target: NEW })).toEqual({ kind: 'manual' });
+ });
+
+ it('does not re-register its own pending switch to the same target', () => {
+ expect(
+ decide({
+ record: record({ pendingRoute: NEW }),
+ current: OLD,
+ target: NEW,
+ pendingIntent: NEW,
+ }),
+ ).toEqual({ kind: 'staged' });
+ });
+
+ it('treats a user re-pick of the same route as a manual choice', () => {
+ // 自动切换未生效时用户又明确挑了同一模型/来源: 意图被顶掉但值一模一样,
+ // 只靠路由值会误认成自己的意图(greptile P1, PR #5155)。注册修订号每次
+ // set/clear 都推进, 对不上就按用户选择对待, 并清掉过时的待生效声称。
+ expect(
+ decide({
+ record: record({ pendingRoute: NEW, pendingFp: 'fp-new', pendingRev: 3 }),
+ current: OLD,
+ target: NEW,
+ pendingIntent: NEW,
+ pendingRev: 4,
+ }),
+ ).toEqual({ kind: 'manual', clearStalePending: true });
+ });
+
+ it('recognizes its own staged switch by registration revision', () => {
+ expect(
+ decide({
+ record: record({ pendingRoute: NEW, pendingFp: 'fp-new', pendingRev: 3 }),
+ current: OLD,
+ target: NEW,
+ pendingIntent: NEW,
+ pendingRev: 3,
+ }),
+ ).toEqual({ kind: 'staged' });
+ });
+
+ it('recognizes its own staged switch by fingerprint even after a provider re-route', () => {
+ const rerouted: ImDefaultRoute = { ...NEW, providerId: 'openai-copy' };
+ expect(
+ decide({
+ record: record({ pendingRoute: rerouted, pendingFp: 'fp-new' }),
+ current: OLD,
+ target: NEW,
+ pendingIntent: rerouted,
+ }),
+ ).toEqual({ kind: 'staged' });
+ expect(
+ decide({
+ record: record({ pendingRoute: rerouted, pendingFp: 'fp-older' }),
+ current: OLD,
+ target: NEW,
+ pendingIntent: rerouted,
+ }),
+ ).toEqual({ kind: 'switch' });
+ });
+
+ it('re-targets its own pending switch when the default changed again', () => {
+ const newer: ImDefaultRoute = { ...NEW, model: 'gpt-5.6' };
+ expect(
+ decide({
+ record: record({ pendingRoute: NEW }),
+ current: OLD,
+ target: newer,
+ pendingIntent: NEW,
+ }),
+ ).toEqual({ kind: 'switch' });
+ });
+
+ it('drops its own stale pending switch when the default moved back', () => {
+ expect(
+ decide({
+ record: record({ pendingRoute: NEW }),
+ current: OLD,
+ target: OLD,
+ pendingIntent: NEW,
+ }),
+ ).toEqual({ kind: 'adopt', cancelPendingIntent: true });
+ });
+
+ it('keeps following after its pending switch was lost (restart) or already applied', () => {
+ const newer: ImDefaultRoute = { ...NEW, model: 'gpt-5.6' };
+ // 意图丢失: 任务仍在记录的旧路由上。
+ expect(
+ decide({ record: record({ pendingRoute: NEW }), current: OLD, target: newer }),
+ ).toEqual({ kind: 'switch' });
+ // 意图已被发送路径应用, 记录尚未更新, 默认又变了。
+ expect(
+ decide({ record: record({ pendingRoute: NEW }), current: NEW, target: newer }),
+ ).toEqual({ kind: 'switch' });
+ });
+
+ it('compares providers through the normalizer', () => {
+ const pinnedOld = { ...OLD, providerId: 'xd' };
+ const normalizeProvider = (route: ImDefaultRoute) => route.providerId ?? 'xd';
+ expect(decide({ record: record(), current: pinnedOld, target: NEW })).toEqual({ kind: 'manual' });
+ expect(
+ decide({ record: record(), current: pinnedOld, target: NEW, normalizeProvider }),
+ ).toEqual({ kind: 'switch' });
+ });
+});
diff --git a/apps/desktop/src/main/im/shared/__tests__/channelDefaultRouteSync.test.ts b/apps/desktop/src/main/im/shared/__tests__/channelDefaultRouteSync.test.ts
new file mode 100644
index 0000000000..06add06369
--- /dev/null
+++ b/apps/desktop/src/main/im/shared/__tests__/channelDefaultRouteSync.test.ts
@@ -0,0 +1,763 @@
+/**
+ * 渠道默认跟随(channelDefaultRouteSync)在真 SQLite 上的读写:
+ * 何时切、切完记录落什么、失败怎么回退、老任务怎么补记录。
+ * 切换本身(register.ts 的路由选择)在这里是替身 —— 它的语义由伙伴模型对齐覆盖。
+ */
+
+import Database from 'better-sqlite3';
+import { drizzle } from 'drizzle-orm/better-sqlite3';
+import { getTableConfig } from 'drizzle-orm/sqlite-core';
+import { eq } from 'drizzle-orm';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ fingerprint: vi.fn(() => 'fp-new'),
+ resolveDefaults: vi.fn(),
+ rawDefault: vi.fn(),
+ listProviders: vi.fn(async (): Promise<unknown[] | null> => []),
+ applyRoute: vi.fn(),
+ readPendingRoute: vi.fn(() => undefined as unknown),
+ cancelPending: vi.fn(),
+ ownerScopeKey: vi.fn((): string => 'owner-1'),
+ boundaryPending: vi.fn((): boolean => false),
+}));
+
+vi.mock('electron', () => ({
+ BrowserWindow: { getAllWindows: () => [] },
+ app: { getPath: () => '/tmp/never-used-here' },
+}));
+vi.mock('../../../device-link/broadcast-tap', () => ({
+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),
+ tapWindowBroadcast: vi.fn(),
+}));
+vi.mock('../../../logger', () => ({
+ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),
+ maskPath: (p: string) => p,
+}));
+vi.mock('../../../maker-host/session-provider-store', () => ({
+ setSessionProvider: vi.fn(),
+}));
+vi.mock('../../../maker-host/createDesktopProviderService', () => ({
+ getDesktopProviderService: () => ({ listProviders: mocks.listProviders }),
+}));
+vi.mock('@cindy/model-providers', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@cindy/model-providers')>()),
+ // 隐式来源一律落到 'xd' —— 足够验证「隐式 == 钉住的 xd」归一化。
+ effectiveSourceIdForModel: vi.fn(() => 'xd'),
+}));
+vi.mock('../../defaultSessionSettings', () => ({
+ getImDefaultEffortFor: vi.fn(() => 'high'),
+ readImDefaultSettingsFingerprint: mocks.fingerprint,
+ readImRawDefaultRoute: mocks.rawDefault,
+ resolveImSessionDefaults: mocks.resolveDefaults,
+}));
+vi.mock('../../../maker-ipc/register', () => ({
+ acquirePendingAgentSwitchForImSend: vi.fn(async (_id: string, sync: () => Promise<void>) => {
+ await sync();
+ return () => {};
+ }),
+ applySessionRouteUnderSendLock: mocks.applyRoute,
+ readPendingAgentSwitchRoute: mocks.readPendingRoute,
+ cancelPendingAgentSwitchForSession: mocks.cancelPending,
+}));
+vi.mock('../../../maker-ipc/sendToSessionLock', () => ({
+ withSendToSessionLock: async <T>(_id: string, run: () => Promise<T>) => run(),
+}));
+vi.mock('../../../appSessionState.js', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../../../appSessionState.js')>()),
+ activeOwnerScopeKey: mocks.ownerScopeKey,
+ isAppSessionBoundaryPending: mocks.boundaryPending,
+}));
+
+let db: ReturnType<typeof drizzle>;
+vi.mock('../../../localDb/client/current', () => ({
+ getDbClient: () => ({ drizzle: db }),
+}));
+
+const { sessions } = await import('../../../localDb/schema');
+const {
+ backfillLegacyImDefaultRoutes,
+ backfillLegacyImDefaultRoutesAtStartup,
+ createImChannelDefaultRouteSync,
+ resetImSessionToChannelDefaults,
+} = await import('../channelDefaultRouteSync');
+const { markImSessionManualRouteOverride } = await import('../manualRouteOverride');
+const { buildImDefaultRouteRecord, buildImManualRouteOverrideRecord, parseImDefaultRouteRecord } = await import('../channelDefaultRoute');
+import type { ImDefaultRoute } from '../channelDefaultRoute';
+import type { ImOrchestratorConfig } from '../types';
+
+const CONFIG = { agentKind: 'claude-code' } as ImOrchestratorConfig;
+const OLD: ImDefaultRoute = { agentKind: 'claude-code', model: 'claude-opus-4-8', providerId: null, effort: 'xhigh' };
+const NEW: ImDefaultRoute = { agentKind: 'codex', model: 'gpt-5.5', providerId: 'openai', effort: 'high' };
+
+function createTableSql(): string {
+ const config = getTableConfig(sessions);
+ const cols = config.columns.map((col) => {
+ const parts = [`"${col.name}"`, col.getSQLType()];
+ if (col.primary) parts.push('PRIMARY KEY');
+ if (col.notNull) parts.push('NOT NULL');
+ const dflt = col.default;
+ if (dflt !== undefined && typeof dflt !== 'object') {
+ parts.push(`DEFAULT ${typeof dflt === 'string' ? `'${dflt}'` : Number(dflt)}`);
+ }
+ return parts.join(' ');
+ });
+ return `CREATE TABLE "${config.name}" (${cols.join(', ')})`;
+}
+
+function dbAgentKind(kind: ImDefaultRoute['agentKind']): string {
+ return kind === 'claude-code' ? 'cc' : kind;
+}
+
+async function insertTask(
+ id: string,
+ route: ImDefaultRoute,
+ opts: {
+ source?: string;
+ record?: string | null;
+ remoteHostId?: string | null;
+ marker?: boolean;
+ status?: 'active' | 'archived' | 'deleted';
+ fastMode?: boolean;
+ } = {},
+): Promise<void> {
+ const source = opts.source ?? 'feishu';
+ const marker = opts.marker !== false;
+ await db.insert(sessions).values({
+ id,
+ title: id,
+ status: opts.status ?? 'active',
+ agentKind: dbAgentKind(route.agentKind),
+ model: route.model,
+ providerId: route.providerId,
+ effort: route.effort,
+ fastMode: opts.fastMode === true,
+ permissionMode: 'auto',
+ workingDir: '/tmp/im',
+ source,
+ remoteHostId: opts.remoteHostId ?? null,
+ imDefaultRoute: opts.record === undefined ? buildImDefaultRouteRecord('fp-old', OLD) : opts.record,
+ ...(source === 'feishu'
+ ? marker ? { feishuBotAppId: 'cli_bot', feishuOpenId: 'ou_user' } : {}
+ : marker ? { imBotContextId: 'bot', imUserId: 'user' } : {}),
+ createdAt: 1,
+ updatedAt: 1,
+ } as typeof sessions.$inferInsert);
+}
+
+async function rowOf(id: string) {
+ const [row] = await db.select().from(sessions).where(eq(sessions.id, id));
+ return row!;
+}
+
+async function setRoute(id: string, route: ImDefaultRoute): Promise<void> {
+ await db
+ .update(sessions)
+ .set({
+ agentKind: dbAgentKind(route.agentKind),
+ model: route.model,
+ providerId: route.providerId,
+ effort: route.effort as typeof sessions.$inferInsert.effort,
+ })
+ .where(eq(sessions.id, id));
+}
+
+function sync(isRouteUsable = vi.fn(async () => true)) {
+ return createImChannelDefaultRouteSync({ source: 'feishu', config: CONFIG, isRouteUsable });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ const raw = new Database(':memory:');
+ raw.exec(createTableSql());
+ db = drizzle(raw);
+ // clearAllMocks 不清实现、也不清 mockResolvedValueOnce 队列: 默认实现必须每次
+ // 重设, 排队后未被消费的 Once(如「无候选行就不碰目录」的用例)会泄漏进下一个
+ // 用例 —— 逐个 mockReset 清干净再重设。
+ mocks.fingerprint.mockReset().mockReturnValue('fp-new');
+ mocks.rawDefault.mockReset().mockReturnValue(OLD);
+ mocks.readPendingRoute.mockReset().mockReturnValue(undefined);
+ mocks.listProviders.mockReset().mockResolvedValue([]);
+ mocks.resolveDefaults.mockReset().mockResolvedValue({ ...NEW, permissionMode: 'auto', fastMode: false, fingerprint: 'fp-new' });
+ mocks.ownerScopeKey.mockReset().mockReturnValue('owner-1');
+ mocks.boundaryPending.mockReset().mockReturnValue(false);
+ mocks.applyRoute.mockReset();
+ mocks.cancelPending.mockReset();
+ mocks.applyRoute.mockImplementation(async (id: string, route: ImDefaultRoute) => {
+ await setRoute(id, route);
+ return 'applied';
+ });
+});
+
+describe('syncUnderLock', () => {
+ it('switches a following task and records the read-back route under the new fingerprint', async () => {
+ await insertTask('t1', OLD);
+ await expect(sync().syncUnderLock('t1')).resolves.toBe(false);
+
+ expect(mocks.applyRoute).toHaveBeenCalledWith('t1', { ...NEW, fastMode: false }, 'claude-code');
+ const record = parseImDefaultRouteRecord((await rowOf('t1')).imDefaultRoute);
+ expect(record).toEqual({ v: 1, fp: 'fp-new', route: NEW });
+ });
+
+ it('records what actually landed when the switch re-routed the provider', async () => {
+ await insertTask('t1', OLD);
+ mocks.applyRoute.mockImplementation(async (id: string, route: ImDefaultRoute) => {
+ await setRoute(id, { ...route, providerId: 'openai-copy' });
+ return 'applied';
+ });
+ await sync().syncUnderLock('t1');
+
+ const record = parseImDefaultRouteRecord((await rowOf('t1')).imDefaultRoute);
+ expect(record?.route.providerId).toBe('openai-copy');
+ });
+
+ it('keeps the old fingerprint and remembers the pending target while the runtime is busy', async () => {
+ await insertTask('t1', OLD);
+ mocks.applyRoute.mockResolvedValue('staged');
+ // true = 跟随切换被暂缓, 调用方本次不得再走通用意图应用(PR #5155 review P1)。
+ await expect(sync().syncUnderLock('t1')).resolves.toBe(true);
+
+ const record = parseImDefaultRouteRecord((await rowOf('t1')).imDefaultRoute);
+ expect(record).toEqual({ v: 1, fp: 'fp-old', route: OLD, pendingRoute: NEW, pendingFp: 'fp-new' });
+ });
+
+ it('keeps the task\'s own Fast setting when following the new default', async () => {
+ // 渠道默认不存 Fast —— 跟随切换只换路由, 任务单独开过的 Fast 不能被清掉
+ // (chatgpt-codex-connector P2, PR #5155)。
+ await insertTask('t1', OLD, { fastMode: true });
+ await sync().syncUnderLock('t1');
+
+ expect(mocks.applyRoute).toHaveBeenCalledWith('t1', { ...NEW, fastMode: true }, 'claude-code');
+ });
+
+ it('still defers the generic apply when the staged claim write fails', async () => {
+ // 登记后声称的落库瞬时失败不能丢「暂缓」信号, 否则外层通用意图应用会把刚登记
+ // 的意图应用到仍在承载后台工作的会话上(PR #5155 review P1)。
+ await insertTask('t1', OLD);
+ mocks.readPendingRoute.mockReturnValueOnce(undefined).mockReturnValue(NEW);
+ mocks.applyRoute.mockImplementation(async () => {
+ db = { update: () => { throw new Error('db closed') } } as never;
+ return 'staged';
+ });
+
+ await expect(sync().syncUnderLock('t1')).resolves.toBe(true);
+ });
+
+ it('remembers the staged intent as registered, then does not re-register it', async () => {
+ await insertTask('t1', OLD);
+ const rerouted: ImDefaultRoute = { ...NEW, providerId: 'openai-copy' };
+ mocks.applyRoute.mockResolvedValue('staged');
+ mocks.readPendingRoute
+ .mockReturnValueOnce(undefined)
+ .mockReturnValue({ ...rerouted, rev: 5 });
+ await sync().syncUnderLock('t1');
+
+ expect(parseImDefaultRouteRecord((await rowOf('t1')).imDefaultRoute)).toEqual({
+ v: 1,
+ fp: 'fp-old',
+ route: OLD,
+ pendingRoute: rerouted,
+ pendingFp: 'fp-new',
+ pendingRev: 5,
+ });
+ // 下一条消息: 不重新登记, 只尝试应用自己登记的意图(仍忙 → 继续等)。
+ mocks.applyRoute.mockClear();
+ await sync().syncUnderLock('t1');
+ expect(mocks.applyRoute).toHaveBeenCalledTimes(1);
+ expect(mocks.applyRoute).toHaveBeenCalledWith('t1', null, 'claude-code');
+ expect(parseImDefaultRouteRecord((await rowOf('t1')).imDefaultRoute)?.pendingRoute).toEqual(rerouted);
+
+ // 再下一条: 空闲了, 意图应用成功 → 记录读回的路由与新指纹。
+ mocks.applyRoute.mockImplementationOnce(async (id: string) => {
+ await setRoute(id, rerouted);
+ return 'applied';
+ });
+ await sync().syncUnderLock('t1');
+ expect(parseImDefaultRouteRecord((await rowOf('t1')).imDefaultRoute)).toEqual({
+ v: 1,
+ fp: 'fp-new',
+ route: rerouted,
+ });
+ });
+
+ it('clears its stale claim but leaves the intent alone when the user re-picked the same route', async () => {
+ // 自动切换未生效时用户又明确挑了同值: 注册修订号变了, 这是用户的选择
+ // (greptile P1, PR #5155) —— 不登记不应用, 只清掉自己的过时声称。
+ await insertTask('t1', OLD, {
+ record: buildImDefaultRouteRecord('fp-old', OLD, { route: NEW, fp: 'fp-new', rev: 3 }),
+ });
+ mocks.readPendingRoute.mockReturnValue({ ...NEW, rev: 4 });
+ await sync().syncUnderLock('t1');
+
+ expect(mocks.applyRoute).not.toHaveBeenCalled();
+ expect(mocks.cancelPending).not.toHaveBeenCalled();
+ expect((await rowOf('t1')).imDefaultRoute).toBe(buildImDefaultRouteRecord('fp-old', OLD));
+ });
+
+ it('withdraws its intent and restores the claim when the staged claim rewrite fails', async () => {
+ // 暂缓声称(pendingRev 补写)失败时不能留「无修订号声称 + 带修订号意图」—— 下一条
+ // 消息会把系统意图误判成用户选择, 走 manual 后被通用 apply 用更宽的忙判定应用掉
+ // (chatgpt-codex-connector P2, PR #5155)。撤回意图、恢复原声称, 下一条消息重试。
+ await insertTask('t1', OLD);
+ mocks.readPendingRoute.mockReturnValueOnce(undefined).mockReturnValue({ ...NEW, rev: 5 });
+ mocks.applyRoute.mockResolvedValue('staged');
+ const real = db;
+ let updates = 0;
+ db = new Proxy(real, {
+ get(target, prop, receiver) {
+ if (prop === 'update') {
+ return (...args: unknown[]) => {
+ updates += 1;
+ // 第 1 次 = 预写声称(成功); 第 2 次 = 补 pendingRev 的声称(故障); 第 3 次 = 恢复。
+ if (updates === 2) throw new Error('database is locked');
+ return (target.update as unknown as (...a: unknown[]) => unknown)(...args);
+ };
+ }
+ return Reflect.get(target, prop, receiver);
+ },
+ }) as typeof db;
+
+ await expect(sync().syncUnderLock('t1')).resolves.toBe(true);
+ db = real;
+
+ expect(mocks.cancelPending).toHaveBeenCalledWith('t1');
+ expect((await rowOf('t1')).imDefaultRoute).toBe(buildImDefaultRouteRecord('fp-old', OLD));
+ });
+
+ it('withdraws its staged intent without blocking when applying it fails', async () => {
+ await insertTask('t1', OLD, {
+ record: buildImDefaultRouteRecord('fp-old', OLD, { route: NEW, fp: 'fp-new' }),
+ });
+ mocks.readPendingRoute.mockReturnValue(NEW);
+ mocks.applyRoute.mockRejectedValue(new Error('model window confirmation required'));
+ await expect(sync().syncUnderLock('t1')).resolves.toBe(false);
+
+ expect(mocks.applyRoute).toHaveBeenCalledWith('t1', null, 'claude-code');
+ expect((await rowOf('t1')).imDefaultRoute).toBe(buildImDefaultRouteRecord('fp-old', OLD));
+ });
+
+ it('defers the generic apply when the catalog is unreadable and a system claim is live', async () => {
+ // 上一条消息已把默认切换登记为 staged; 下一条消息目录暂不可读时不能丢「暂缓」
+ // 信号 —— 通用 apply 的忙判定只看 isTurnRunning(PR #5155 review P2)。
+ await insertTask('t1', OLD, {
+ record: buildImDefaultRouteRecord('fp-old', OLD, { route: NEW, fp: 'fp-new', rev: 5 }),
+ });
+ mocks.readPendingRoute.mockReturnValue({ ...NEW, rev: 5 });
+ mocks.listProviders.mockResolvedValueOnce(null);
+
+ await expect(sync().syncUnderLock('t1')).resolves.toBe(true);
+ expect(mocks.resolveDefaults).not.toHaveBeenCalled();
+ expect(mocks.applyRoute).not.toHaveBeenCalled();
+ });
+
+ it('does not defer on catalog failure when the live intent is not its own claim', async () => {
+ await insertTask('t1', OLD, {
+ record: buildImDefaultRouteRecord('fp-old', OLD, { route: NEW, fp: 'fp-new', rev: 5 }),
+ });
+ // 用户重挑的同值意图(修订号不同)—— 不挡通用应用。
+ mocks.readPendingRoute.mockReturnValue({ ...NEW, rev: 6 });
+ mocks.listProviders.mockResolvedValueOnce(null);
+
+ await expect(sync().syncUnderLock('t1')).resolves.toBe(false);
+ });
+
+ it('leaves a task the user changed alone', async () => {
+ await insertTask('t1', { ...OLD, model: 'claude-sonnet-5' });
+ await sync().syncUnderLock('t1');
+
+ expect(mocks.applyRoute).not.toHaveBeenCalled();
+ expect((await rowOf('t1')).imDefaultRoute).toBe(buildImDefaultRouteRecord('fp-old', OLD));
+ });
+
+ it('never touches a task carrying the manual override marker', async () => {
+ // 同值重选落地时立的墓碑: 不再跟随, 也不必解析新默认(greptile P1 补充, PR #5155)。
+ const tombstone = buildImManualRouteOverrideRecord(OLD);
+ await insertTask('t1', OLD, { record: tombstone });
+ await sync().syncUnderLock('t1');
+
+ expect(mocks.resolveDefaults).not.toHaveBeenCalled();
+ expect(mocks.applyRoute).not.toHaveBeenCalled();
+ expect((await rowOf('t1')).imDefaultRoute).toBe(tombstone);
+ });
+
+ it('treats a pinned native source as the recorded implicit default', async () => {
+ await insertTask('t1', { ...OLD, providerId: 'xd' });
+ await sync().syncUnderLock('t1');
+
+ expect(mocks.applyRoute).toHaveBeenCalled();
+ });
+
+ it('never blocks the message and restores the record when the switch fails', async () => {
+ await insertTask('t1', OLD);
+ mocks.applyRoute.mockRejectedValue(new Error('model window unknown'));
+ await expect(sync().syncUnderLock('t1')).resolves.toBe(false);
+
+ expect((await rowOf('t1')).imDefaultRoute).toBe(buildImDefaultRouteRecord('fp-old', OLD));
+ expect((await rowOf('t1')).model).toBe(OLD.model);
+ });
+
+ it('keeps the current route when the new default is not usable', async () => {
+ await insertTask('t1', OLD);
+ await sync(vi.fn(async () => false)).syncUnderLock('t1');
+
+ expect(mocks.applyRoute).not.toHaveBeenCalled();
+ expect((await rowOf('t1')).imDefaultRoute).toBe(buildImDefaultRouteRecord('fp-old', OLD));
+ });
+
+ it('adopts the new fingerprint only when the task still runs the recorded route', async () => {
+ await insertTask('t1', NEW, { record: buildImDefaultRouteRecord('fp-old', NEW) });
+ await sync().syncUnderLock('t1');
+
+ expect(mocks.applyRoute).not.toHaveBeenCalled();
+ expect(parseImDefaultRouteRecord((await rowOf('t1')).imDefaultRoute)).toEqual({ v: 1, fp: 'fp-new', route: NEW });
+ });
+
+ it('does not re-adopt a manual pick that happens to equal the new default', async () => {
+ // 记录的路由是 OLD, 任务当前跑 NEW(用户单独挑的, 恰好与新默认一致): 不能洗成跟随。
+ await insertTask('t1', NEW);
+ await sync().syncUnderLock('t1');
+
+ expect(mocks.applyRoute).not.toHaveBeenCalled();
+ expect((await rowOf('t1')).imDefaultRoute).toBe(buildImDefaultRouteRecord('fp-old', OLD));
+ });
+
+ it('does nothing while the settings fingerprint is unchanged', async () => {
+ await insertTask('t1', OLD);
+ mocks.fingerprint.mockReturnValue('fp-old');
+ await sync().syncUnderLock('t1');
+
+ expect(mocks.resolveDefaults).not.toHaveBeenCalled();
+ expect(mocks.applyRoute).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['another channel', { source: 'telegram' }],
+ ['a desktop task', { source: 'desktop' }],
+ ['a remote task', { remoteHostId: 'ssh-1' }],
+ ['a task without channel markers (official hook)', { marker: false }],
+ ['an archived task', { status: 'archived' as const }],
+ ['a task without a record', { record: null }],
+ ])('ignores %s', async (_label, opts) => {
+ await insertTask('t1', OLD, opts);
+ await sync().syncUnderLock('t1');
+
+ expect(mocks.applyRoute).not.toHaveBeenCalled();
+ });
+});
+
+describe('previewSwitchTarget', () => {
+ it('returns the new default only when this message will switch to it', async () => {
+ await insertTask('follow', OLD);
+ await insertTask('manual', { ...OLD, model: 'claude-sonnet-5' });
+ const s = sync();
+
+ await expect(s.previewSwitchTarget('follow')).resolves.toEqual(NEW);
+ await expect(s.previewSwitchTarget('manual')).resolves.toBeNull();
+ await expect(sync(vi.fn(async () => false)).previewSwitchTarget('follow')).resolves.toBeNull();
+ expect(mocks.applyRoute).not.toHaveBeenCalled();
+ expect((await rowOf('follow')).imDefaultRoute).toBe(buildImDefaultRouteRecord('fp-old', OLD));
+ });
+});
+
+describe('backfillLegacyImDefaultRoutes', () => {
+ it('records only legacy tasks of this channel that still run the old default', async () => {
+ mocks.resolveDefaults.mockResolvedValue({ ...OLD, permissionMode: 'auto', fastMode: false, fingerprint: 'fp-old' });
+ mocks.fingerprint.mockReturnValue('fp-old');
+ await insertTask('legacy-default', OLD, { record: null });
+ await insertTask('legacy-pinned', { ...OLD, providerId: 'xd' }, { record: null });
+ await insertTask('legacy-changed', { ...OLD, model: 'claude-sonnet-5' }, { record: null });
+ await insertTask('legacy-other-channel', OLD, { record: null, source: 'telegram' });
+ await insertTask('recorded', { ...OLD, model: 'claude-sonnet-5' });
+
+ await expect(backfillLegacyImDefaultRoutes('feishu', CONFIG)).resolves.toBe(2);
+
+ expect(parseImDefaultRouteRecord((await rowOf('legacy-default')).imDefaultRoute)).toEqual({
+ v: 1,
+ fp: 'fp-old',
+ route: OLD,
+ });
+ expect(parseImDefaultRouteRecord((await rowOf('legacy-pinned')).imDefaultRoute)?.route.providerId).toBe('xd');
+ expect((await rowOf('legacy-changed')).imDefaultRoute).toBeNull();
+ expect((await rowOf('legacy-other-channel')).imDefaultRoute).toBeNull();
+ expect((await rowOf('recorded')).imDefaultRoute).toBe(buildImDefaultRouteRecord('fp-old', OLD));
+ });
+
+ it('keeps an effort-only manual change out when the old default still resolves to its own route', async () => {
+ mocks.resolveDefaults.mockResolvedValue({ ...OLD, permissionMode: 'auto', fastMode: false, fingerprint: 'fp-old' });
+ mocks.fingerprint.mockReturnValue('fp-old');
+ await insertTask('legacy-effort-changed', { ...OLD, effort: 'low' }, { record: null });
+
+ await expect(backfillLegacyImDefaultRoutes('feishu', CONFIG)).resolves.toBe(0);
+ expect((await rowOf('legacy-effort-changed')).imDefaultRoute).toBeNull();
+ });
+
+ it('matches by the saved raw default when the old default fell back to another route', async () => {
+ // 旧默认的来源断开/模型下架后解析会回落到别的路由, 拿回落值匹配历史任务永远
+ // 匹配不到, 它们会永久失去跟随资格(chatgpt-codex-connector P2, PR #5155)。
+ mocks.fingerprint.mockReturnValue('fp-old');
+ mocks.rawDefault.mockReturnValue({ ...OLD, providerId: 'openai', effort: 'xhigh' });
+ mocks.resolveDefaults.mockResolvedValue({ ...NEW, permissionMode: 'auto', fastMode: false, fingerprint: 'fp-old' });
+ await insertTask('legacy-broken-default', { ...OLD, providerId: 'openai' }, { record: null });
+ await insertTask('legacy-on-fallback', NEW, { record: null });
+ await insertTask('legacy-off-raw', { ...OLD, providerId: 'other' }, { record: null });
+ // 只改过 effort 的历史任务也是「单独改过」, 不能被认领(PR #5155 review P1)。
+ await insertTask('legacy-effort-only', { ...OLD, providerId: 'openai', effort: 'low' }, { record: null });
+
+ await expect(backfillLegacyImDefaultRoutes('feishu', CONFIG)).resolves.toBe(2);
+
+ expect(parseImDefaultRouteRecord((await rowOf('legacy-broken-default')).imDefaultRoute)).toEqual({
+ v: 1,
+ fp: 'fp-old',
+ route: { ...OLD, providerId: 'openai' },
+ });
+ expect((await rowOf('legacy-on-fallback')).imDefaultRoute).not.toBeNull();
+ expect((await rowOf('legacy-off-raw')).imDefaultRoute).toBeNull();
+ expect((await rowOf('legacy-effort-only')).imDefaultRoute).toBeNull();
+ });
+
+ it('matches by the saved raw default when the old default cannot be resolved at all', async () => {
+ // 旧默认坏到解析不出来(如全部模型被停用): 不能把保存也堵死, 按原始默认认领。
+ mocks.fingerprint.mockReturnValue('fp-old');
+ mocks.resolveDefaults.mockRejectedValue(new Error('im default session has no enabled chat model'));
+ await insertTask('legacy-default', OLD, { record: null });
+
+ await expect(backfillLegacyImDefaultRoutes('feishu', CONFIG)).resolves.toBe(1);
+ expect(parseImDefaultRouteRecord((await rowOf('legacy-default')).imDefaultRoute)).toEqual({
+ v: 1,
+ fp: 'fp-old',
+ route: OLD,
+ });
+ });
+
+ it('leaves explicitly pinned historical landings alone even when the source later died', async () => {
+ // 隐式默认(null)建任务时可能被系统钉成当时的有效来源 A, 也可能本来就是用户
+ // 手动钉的 —— 断开的来源证明不了出身, 无法区分时保守不认领, 不拿脏数据误切
+ // 用户单独改过的任务(PR #5155 review P2 后续裁决)。
+ mocks.fingerprint.mockReturnValue('fp-old');
+ mocks.rawDefault.mockReturnValue(OLD);
+ mocks.resolveDefaults.mockResolvedValue({ ...OLD, permissionMode: 'auto', fastMode: false, fingerprint: 'fp-old' });
+ await insertTask('legacy-pinned-dead', { ...OLD, providerId: 'dead-source' }, { record: null });
+ await insertTask('legacy-pinned-live', { ...OLD, providerId: 'live-source' }, { record: null });
+
+ await expect(backfillLegacyImDefaultRoutes('feishu', CONFIG)).resolves.toBe(0);
+
+ expect((await rowOf('legacy-pinned-dead')).imDefaultRoute).toBeNull();
+ expect((await rowOf('legacy-pinned-live')).imDefaultRoute).toBeNull();
+ });
+
+ it('reads and writes through the client captured at entry (owner boundary)', async () => {
+ // 回填跨多个 await, 期间登出/换号会让全局 getDbClient 指向新 owner —— 必须全程
+ // 复用进入时捕获的客户端, 不能在 await 间隙重读全局(PR #5155 review P1)。
+ mocks.resolveDefaults.mockResolvedValue({ ...OLD, permissionMode: 'auto', fastMode: false, fingerprint: 'fp-old' });
+ mocks.fingerprint.mockReturnValue('fp-old');
+ await insertTask('legacy-default', OLD, { record: null });
+ const realDb = db;
+ const captured = { drizzle: realDb } as never;
+ // 全局客户端在回填中途被换/销毁(owner 切换)。
+ db = { select: () => { throw new Error('owner switched') }, update: () => { throw new Error('owner switched') } } as never;
+
+ await expect(backfillLegacyImDefaultRoutes('feishu', CONFIG, captured)).resolves.toBe(1);
+ db = realDb;
+
+ expect(parseImDefaultRouteRecord((await rowOf('legacy-default')).imDefaultRoute)).not.toBeNull();
+ });
+
+ it('claims revivable archived tasks that still run the old default', async () => {
+ // 归档/软删的可复活任务: findActiveSession 会原地复活且不补记录, 保存前不认领
+ // 就永久错过(PR #5155 review P2)。
+ mocks.resolveDefaults.mockResolvedValue({ ...OLD, permissionMode: 'auto', fastMode: false, fingerprint: 'fp-old' });
+ mocks.fingerprint.mockReturnValue('fp-old');
+ await insertTask('legacy-archived', OLD, { record: null, status: 'archived' });
+ await insertTask('legacy-deleted', OLD, { record: null, status: 'deleted' });
+
+ await expect(backfillLegacyImDefaultRoutes('feishu', CONFIG)).resolves.toBe(2);
+
+ expect((await rowOf('legacy-archived')).imDefaultRoute).not.toBeNull();
+ expect((await rowOf('legacy-deleted')).imDefaultRoute).not.toBeNull();
+ });
+
+ it('fails instead of reporting done when the provider catalog is unavailable', async () => {
+ // 返回 0 会被调用方当成「补完了」照常提交新默认, 还停在旧默认上的老任务之后只
+ // 能按新默认匹配, 永久失去跟随资格 —— 必须抛错让本次保存失败重试(PR #5155 P2)。
+ await insertTask('legacy-default', OLD, { record: null });
+ mocks.listProviders.mockResolvedValueOnce(null);
+
+ await expect(backfillLegacyImDefaultRoutes('feishu', CONFIG)).rejects.toThrow(/provider catalog unavailable/);
+ expect((await rowOf('legacy-default')).imDefaultRoute).toBeNull();
+ });
+
+ it('does not need the catalog when no legacy task is left', async () => {
+ await insertTask('recorded', OLD);
+ mocks.listProviders.mockResolvedValueOnce(null);
+
+ await expect(backfillLegacyImDefaultRoutes('feishu', CONFIG)).resolves.toBe(0);
+ });
+});
+
+describe('backfillLegacyImDefaultRoutesAtStartup', () => {
+ it('claims legacy rows for every configured channel at startup', async () => {
+ // 回填只由设置保存/重置触发的话, 从未动过设置的升级老任务永远拿不到记录 ——
+ // 后续版本改内置默认后会永久固定在旧默认(PR #5155 review P2)。
+ mocks.fingerprint.mockReturnValue('fp-old');
+ await insertTask('legacy-feishu', OLD, { record: null });
+ await insertTask('legacy-telegram', OLD, { record: null, source: 'telegram' });
+
+ await expect(
+ backfillLegacyImDefaultRoutesAtStartup([
+ { source: 'feishu', config: CONFIG },
+ { source: 'telegram', config: CONFIG },
+ ]),
+ ).resolves.toBeUndefined();
+
+ expect(parseImDefaultRouteRecord((await rowOf('legacy-feishu')).imDefaultRoute)).toEqual({
+ v: 1,
+ fp: 'fp-old',
+ route: OLD,
+ });
+ expect(parseImDefaultRouteRecord((await rowOf('legacy-telegram')).imDefaultRoute)).toEqual({
+ v: 1,
+ fp: 'fp-old',
+ route: OLD,
+ });
+ });
+
+ it('keeps sweeping the remaining channels when one startup backfill fails', async () => {
+ // 启动补齐 best-effort: 单个渠道失败只告警不抛错(下次启动重试), 不能把其余
+ // 渠道也带掉, 更不能挡连接启动(PR #5155 review P2)。
+ mocks.fingerprint.mockReturnValue('fp-old');
+ await insertTask('legacy-feishu', OLD, { record: null });
+ await insertTask('legacy-telegram', OLD, { record: null, source: 'telegram' });
+ // 第一个渠道拿不到供应商目录 → 该渠道报错; 不影响第二个渠道。
+ mocks.listProviders.mockResolvedValueOnce(null);
+
+ await expect(
+ backfillLegacyImDefaultRoutesAtStartup([
+ { source: 'feishu', config: CONFIG },
+ { source: 'telegram', config: CONFIG },
+ ]),
+ ).resolves.toBeUndefined();
+
+ expect((await rowOf('legacy-feishu')).imDefaultRoute).toBeNull();
+ expect(parseImDefaultRouteRecord((await rowOf('legacy-telegram')).imDefaultRoute)).toEqual({
+ v: 1,
+ fp: 'fp-old',
+ route: OLD,
+ });
+ });
+});
+
+describe('markImSessionManualRouteOverride', () => {
+ it('marks a channel-owned task so it stops following for good', async () => {
+ await insertTask('t1', OLD);
+ await markImSessionManualRouteOverride('t1');
+
+ expect(parseImDefaultRouteRecord((await rowOf('t1')).imDefaultRoute)).toEqual({
+ v: 1,
+ fp: '',
+ route: OLD,
+ manual: true,
+ });
+ });
+
+ it('reads and writes through the client captured at entry (owner boundary)', async () => {
+ // 墓碑读写跨 await, 期间登出/切号会让全局 getDbClient 指向新 owner —— 必须全程
+ // 复用进入时捕获的客户端, 不能在 await 间隙重读全局(PR #5155 review P1)。
+ await insertTask('t1', OLD);
+ const realDb = db;
+ const write = markImSessionManualRouteOverride('t1');
+ // 全局客户端在中途被换成别的 owner(必炸)。
+ db = {
+ select: () => { throw new Error('owner switched'); },
+ update: () => { throw new Error('owner switched'); },
+ } as never;
+ await write;
+ db = realDb;
+
+ expect(parseImDefaultRouteRecord((await rowOf('t1')).imDefaultRoute)?.manual).toBe(true);
+ });
+
+ it('refuses to write the marker when the owner scope changed mid-flight', async () => {
+ // owner 换了还写 = 把 A 的墓碑写进 B 的同 ID 任务; 不写又假装成功 = A 的手动
+ // 选择没有墓碑、会被渠道默认覆盖 —— 写入前复核 owner scope, 变了就抛错让上层
+ // 按选择失败重试(PR #5155 review P1)。
+ await insertTask('t1', OLD);
+ mocks.ownerScopeKey.mockReturnValueOnce('owner-1').mockReturnValueOnce('owner-2');
+
+ await expect(markImSessionManualRouteOverride('t1')).rejects.toThrow(/retry the selection/);
+ expect((await rowOf('t1')).imDefaultRoute).toBe(buildImDefaultRouteRecord('fp-old', OLD));
+ });
+
+ it('refuses to write the marker while an account boundary is in flight', async () => {
+ await insertTask('t1', OLD);
+ mocks.boundaryPending.mockReturnValueOnce(true);
+
+ await expect(markImSessionManualRouteOverride('t1')).rejects.toThrow(/retry the selection/);
+ expect((await rowOf('t1')).imDefaultRoute).toBe(buildImDefaultRouteRecord('fp-old', OLD));
+ });
+
+ it('does not touch tasks outside the channel follow surface', async () => {
+ await insertTask('desktop', OLD, { source: 'desktop', record: null });
+ await insertTask('remote', OLD, { remoteHostId: 'ssh-1' });
+ await markImSessionManualRouteOverride('desktop');
+ await markImSessionManualRouteOverride('remote');
+
+ expect((await rowOf('desktop')).imDefaultRoute).toBeNull();
+ expect((await rowOf('remote')).imDefaultRoute).toBe(buildImDefaultRouteRecord('fp-old', OLD));
+ });
+});
+
+describe('resetImSessionToChannelDefaults', () => {
+ it('writes the new route with its record and drops a stale pending switch', async () => {
+ await insertTask('t1', { ...OLD, model: 'claude-sonnet-5' });
+ mocks.readPendingRoute.mockReturnValue(NEW);
+ await resetImSessionToChannelDefaults(
+ 't1',
+ CONFIG,
+ {
+ id: 't1',
+ agentKind: 'codex',
+ workingDir: '/tmp/im',
+ model: 'gpt-5.5',
+ effort: 'high',
+ permissionMode: 'auto',
+ fastMode: false,
+ sdkSessionId: null,
+ providerId: 'openai',
+ defaultRouteFingerprint: 'fp-new',
+ },
+ 'feishu',
+ );
+
+ const row = await rowOf('t1');
+ expect(row.model).toBe('gpt-5.5');
+ expect(parseImDefaultRouteRecord(row.imDefaultRoute)).toEqual({ v: 1, fp: 'fp-new', route: NEW });
+ expect(mocks.cancelPending).toHaveBeenCalledWith('t1');
+ });
+});
+
+describe('createSession', () => {
+ it('records the channel default it created the task from, and keeps a revived row as is', async () => {
+ const { createImSessionRepo } = await import('../sessionRepo');
+ mocks.resolveDefaults.mockResolvedValue({ ...NEW, permissionMode: 'auto', fastMode: false, fingerprint: 'fp-new' });
+ const ns = {
+ source: 'feishu',
+ sessionIdFor: (bot: string, user: string) => `feishu_${bot}_${user}`,
+ defaultTitle: () => 'Feishu',
+ ensureWorkingDir: () => '/tmp/im',
+ extraInsertColumns: (bot: string, user: string) => ({ feishuBotAppId: bot, feishuOpenId: user }),
+ } as unknown as Parameters<typeof createImSessionRepo>[1];
+ const repo = createImSessionRepo(CONFIG, ns);
+
+ const created = await repo.createSession('cli_bot', 'ou_user');
+ expect(parseImDefaultRouteRecord((await rowOf(created.id)).imDefaultRoute)).toEqual({
+ v: 1,
+ fp: 'fp-new',
+ route: NEW,
+ });
+
+ // 冲突(复活)分支不碰路由与记录 —— 残留行保留自己的设置。
+ await db.update(sessions).set({ status: 'archived', imDefaultRoute: 'kept' }).where(eq(sessions.id, created.id));
+ await repo.createSession('cli_bot', 'ou_user');
+ expect((await rowOf(created.id)).imDefaultRoute).toBe('kept');
+ });
+});
diff --git a/apps/desktop/src/main/im/shared/__tests__/sessionRepoRevive.test.ts b/apps/desktop/src/main/im/shared/__tests__/sessionRepoRevive.test.ts
index 26b2bca862..bc01e1ed9d 100644
--- a/apps/desktop/src/main/im/shared/__tests__/sessionRepoRevive.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/sessionRepoRevive.test.ts
@@ -439,6 +439,7 @@ describe('sessionRepo.createFreshSession', () => {
providerId: 'xai',
permissionMode: 'bypassPermissions',
workingDir: '/tmp/telegram',
+ defaultRouteFingerprint: 'fp-telegram',
};
mocks.selectLimit.mockResolvedValueOnce([old]);
const repo = createImSessionRepo(
@@ -469,6 +470,15 @@ describe('sessionRepo.createFreshSession', () => {
}),
}),
);
+ const rotateCall = (mocks.tx.mock.calls as unknown as Array<[string, unknown]>).find(
+ ([name]) => name === 'im.rotateSession',
+ );
+ const rotated = rotateCall?.[1] as { session: { imDefaultRoute: string | null; effort: string } };
+ expect(JSON.parse(rotated.session.imDefaultRoute!)).toEqual({
+ v: 1,
+ fp: 'fp-telegram',
+ route: { agentKind: 'pi', model: 'grok-4.6', providerId: 'xai', effort: rotated.session.effort },
+ });
expect(routeLock).toHaveBeenCalledWith('telegram_bot_user', expect.any(Function));
expect(routeLock).toHaveBeenCalledWith('old-task', expect.any(Function));
});
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 6784208083..84dc4bc42b 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
@@ -1278,7 +1278,9 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
turnPermissionPolicy,
});
- expect(acquirePendingAgentSwitch).toHaveBeenCalledWith('feishu-session');
+ expect(acquirePendingAgentSwitch).toHaveBeenCalledWith('feishu-session', {
+ channelOwned: true,
+ });
expect(oldSession.send).not.toHaveBeenCalled();
expect(switchedSession.send).toHaveBeenCalledWith(
expect.anything(),
@@ -3121,6 +3123,150 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
);
});
+ const followRoute = {
+ agentKind: 'claude-code' as const,
+ model: 'claude-opus-4-8',
+ providerId: 'xd',
+ effort: 'xhigh',
+ };
+ const oldRouteRow = {
+ id: 'feishu-session',
+ agentKind: 'claude-code' as const,
+ workingDir: 'F:\\XDMaker',
+ model: 'claude-opus-4-8',
+ effort: 'xhigh' as const,
+ permissionMode: 'auto' as const,
+ fastMode: false,
+ sdkSessionId: null,
+ providerId: 'anthropic',
+ };
+ const followRouteRow = { ...oldRouteRow, providerId: 'xd' };
+ function mockFollowProviders() {
+ mocks.readXdGatewayApiKey.mockReturnValue('xd-gateway-key');
+ mocks.hasCustomProviderKey.mockReturnValue(false);
+ mocks.listProviders.mockResolvedValue([
+ {
+ id: 'xd',
+ name: 'XD',
+ source: 'builtin',
+ connected: true,
+ agents: ['claude-code'],
+ models: { 'claude-code': [{ id: 'claude-opus-4-8' }], codex: [] },
+ routing: {
+ 'claude-code': { upstream: 'https://gateway.example', authStrategy: 'gateway-key' },
+ },
+ },
+ {
+ id: 'anthropic',
+ name: 'Anthropic',
+ source: 'builtin',
+ connected: false,
+ agents: ['claude-code'],
+ models: { 'claude-code': [{ id: 'claude-opus-4-8' }], codex: [] },
+ routing: {
+ 'claude-code': { upstream: 'https://api.anthropic.com', authStrategy: 'oauth-passthrough' },
+ },
+ },
+ ]);
+ }
+ const followAuthMissingText = () =>
+ ui.agent.authMissing?.({
+ agentKind: 'claude-code',
+ model: 'claude-opus-4-8',
+ providerId: 'anthropic',
+ providerLabel: 'Anthropic',
+ missing: 'provider-disconnected',
+ attached: false,
+ });
+
+ it('re-checks auth on the actual route when the follow switch did not land before send', async () => {
+ // 授权检查只过了「将要切到」的新默认路由; 跟随切换失败被吞后这条消息会按旧路由
+ // 发送 —— 必须按实际路由补一次授权检查, 旧供应商断开时给出缺授权提示, 而不是进
+ // 发送流程运行时失败(PR #5155 review P2)。
+ mockFollowProviders();
+ mocks.findActiveSession.mockResolvedValue(oldRouteRow);
+ mocks.peekSessionById.mockResolvedValue(oldRouteRow);
+ const h = setupSession(async () => ({ accepted: true }));
+ const channelDefaultRoute = {
+ previewSwitchTarget: vi.fn(async () => followRoute),
+ syncBeforeWiring: vi.fn(async () => {}),
+ };
+ const localRunner = createTurnRunner(fakeAdapter, fakeRepo, fakeCards, { channelDefaultRoute });
+
+ await localRunner.runAgentTurn({
+ botContextId: 'cli_test_bot',
+ userId: 'ou_user',
+ userMessageId: 'msg-follow-switch-failed',
+ text: 'follow the new default',
+ attachments: [],
+ });
+
+ expect(channelDefaultRoute.previewSwitchTarget).toHaveBeenCalledWith('feishu-session');
+ expect(h.send).not.toHaveBeenCalled();
+ expect(mocks.feishuIm.sendText).toHaveBeenCalledWith('ou_user', followAuthMissingText(), {
+ threadTs: undefined,
+ });
+ });
+
+ it('sends on the followed route without an extra auth rejection when the switch landed', async () => {
+ mockFollowProviders();
+ mocks.findActiveSession.mockResolvedValue(oldRouteRow);
+ mocks.peekSessionById.mockResolvedValue(followRouteRow);
+ const h = setupSession(async () => ({ accepted: true }));
+ const channelDefaultRoute = {
+ previewSwitchTarget: vi.fn(async () => followRoute),
+ syncBeforeWiring: vi.fn(async () => {}),
+ };
+ const localRunner = createTurnRunner(fakeAdapter, fakeRepo, fakeCards, { channelDefaultRoute });
+
+ await localRunner.runAgentTurn({
+ botContextId: 'cli_test_bot',
+ userId: 'ou_user',
+ userMessageId: 'msg-follow-switch-landed',
+ text: 'follow the new default',
+ attachments: [],
+ });
+
+ expect(h.send).toHaveBeenCalledTimes(1);
+ expect(mocks.feishuIm.sendText).not.toHaveBeenCalledWith(
+ 'ou_user',
+ followAuthMissingText(),
+ expect.anything(),
+ );
+ });
+
+ it('re-checks auth on the read-back route when a cold task cannot follow before wiring', async () => {
+ // 未接线的任务接线前先对齐跟随; 切换失败保持旧路由时, 读回的旧路由必须补授权
+ // 检查 —— 否则这条消息会带着只验过新路由的结果接线旧路由(PR #5155 review P2)。
+ mockFollowProviders();
+ mocks.findActiveSession.mockResolvedValue(oldRouteRow);
+ mocks.peekSessionById.mockResolvedValue(oldRouteRow);
+ const h = createSessionHarness(async () => ({ accepted: true }));
+ mocks.getMaker.mockReturnValue({
+ ...createMakerHarness(h.session),
+ getSession: vi.fn(() => undefined),
+ });
+ const channelDefaultRoute = {
+ previewSwitchTarget: vi.fn(async () => followRoute),
+ syncBeforeWiring: vi.fn(async () => {}),
+ };
+ const localRunner = createTurnRunner(fakeAdapter, fakeRepo, fakeCards, { channelDefaultRoute });
+
+ await localRunner.runAgentTurn({
+ botContextId: 'cli_test_bot',
+ userId: 'ou_user',
+ userMessageId: 'msg-cold-follow-failed',
+ text: 'follow the new default',
+ attachments: [],
+ });
+
+ expect(channelDefaultRoute.syncBeforeWiring).toHaveBeenCalledWith('feishu-session');
+ expect(h.send).not.toHaveBeenCalled();
+ expect(mocks.feishuIm.sendText).toHaveBeenCalledWith('ou_user', followAuthMissingText(), {
+ threadTs: undefined,
+ });
+ });
+
it('reuses the default route provider snapshot for new-session auth checks', async () => {
const providers = [
{
@@ -3906,4 +4052,227 @@ describe('初始流式输出面创建失败的收口降级(#2164)', () => {
});
});
});
+ describe('channel default route follow', () => {
+ function coldMakerHarness(session: Session, order: string[]) {
+ let wired = false;
+ return {
+ getSession: vi.fn(() => (wired ? session : undefined)),
+ createSession: vi.fn(async () => {
+ order.push('wire');
+ wired = true;
+ return session;
+ }),
+ on: vi.fn((listener: (event: MakerEvent) => void) => {
+ makerEventListeners.push(listener);
+ return () => {
+ makerEventListeners = makerEventListeners.filter((candidate) => candidate !== listener);
+ };
+ }),
+ };
+ }
+
+ function providersWith(models: string[]) {
+ return [
+ {
+ id: 'xd',
+ name: 'XD',
+ source: 'builtin',
+ connected: true,
+ agents: ['claude-code', 'codex'],
+ models: { 'claude-code': models.map((id) => ({ id })), codex: [] },
+ routing: {
+ 'claude-code': { upstream: 'https://gateway.example', authStrategy: 'gateway-key' },
+ codex: { upstream: 'https://gateway.example/v1', authStrategy: 'gateway-key' },
+ },
+ },
+ ];
+ }
+
+ it('follows the new default before wiring a cold channel task', async () => {
+ mocks.listProviders.mockResolvedValue(providersWith(['claude-opus-4-7', 'claude-opus-4-8']));
+ const order: string[] = [];
+ const h = createSessionHarness(async () => ({ accepted: true }), 'feishu-session');
+ const maker = coldMakerHarness(h.session, order);
+ mocks.getMaker.mockReturnValue(maker);
+ mocks.peekSessionById.mockResolvedValue({
+ id: 'feishu-session',
+ agentKind: 'claude-code',
+ workingDir: 'F:\\XDMaker',
+ model: 'claude-opus-4-8',
+ effort: 'high',
+ permissionMode: 'bypassPermissions',
+ fastMode: false,
+ sdkSessionId: null,
+ providerId: null,
+ });
+ let vendorOptionsDuringSync: Record<string, unknown> | undefined;
+ let localRunner!: ImTurnRunner;
+ const channelDefaultRoute = {
+ previewSwitchTarget: vi.fn(async () => ({
+ agentKind: 'claude-code' as const,
+ model: 'claude-opus-4-8',
+ providerId: null,
+ effort: 'high',
+ })),
+ syncBeforeWiring: vi.fn(async () => {
+ order.push('sync');
+ vendorOptionsDuringSync = localRunner.vendorOptionsForSession('feishu-session');
+ }),
+ };
+ const acquirePendingAgentSwitch = vi.fn(async () => vi.fn());
+ localRunner = createTurnRunner(fakeAdapter, fakeRepo, fakeCards, {
+ acquirePendingAgentSwitch,
+ channelDefaultRoute,
+ });
+ try {
+ await localRunner.runAgentTurn({
+ botContextId: 'cli_test_bot',
+ userId: 'ou_user',
+ userMessageId: 'msg-follow-cold',
+ text: 'hello',
+ attachments: [],
+ });
+
+ expect(channelDefaultRoute.previewSwitchTarget).toHaveBeenCalledWith('feishu-session');
+ expect(order).toEqual(['sync', 'wire']);
+ // 切换重建会话(若有)要能拿到渠道 vendorOptions, 否则 bot 专属工具会丢。
+ expect(vendorOptionsDuringSync).toEqual({ feishuChatId: 'ou_user', source: 'feishu' });
+ expect(maker.createSession).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'feishu-session', model: 'claude-opus-4-8', effort: 'high' }),
+ );
+ expect(acquirePendingAgentSwitch).toHaveBeenCalledWith('feishu-session', {
+ channelOwned: true,
+ });
+ expect(localRunner.vendorOptionsForSession('feishu-session')).toEqual({
+ feishuChatId: 'ou_user',
+ source: 'feishu',
+ });
+ } finally {
+ localRunner.disposeAllSessions();
+ }
+ });
+
+ it('wires the current route when no follow switch is due', async () => {
+ const order: string[] = [];
+ const h = createSessionHarness(async () => ({ accepted: true }), 'feishu-session');
+ const maker = coldMakerHarness(h.session, order);
+ mocks.getMaker.mockReturnValue(maker);
+ const channelDefaultRoute = {
+ previewSwitchTarget: vi.fn(async () => null),
+ syncBeforeWiring: vi.fn(async () => undefined),
+ };
+ const localRunner = createTurnRunner(fakeAdapter, fakeRepo, fakeCards, {
+ acquirePendingAgentSwitch: vi.fn(async () => vi.fn()),
+ channelDefaultRoute,
+ });
+ try {
+ await localRunner.runAgentTurn({
+ botContextId: 'cli_test_bot',
+ userId: 'ou_user',
+ userMessageId: 'msg-follow-none',
+ text: 'hello',
+ attachments: [],
+ });
+
+ expect(channelDefaultRoute.syncBeforeWiring).not.toHaveBeenCalled();
+ expect(maker.createSession).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'feishu-session', model: 'claude-opus-4-7' }),
+ );
+ } finally {
+ localRunner.disposeAllSessions();
+ }
+ });
+
+ it('checks auth against the followed route when the old default is unusable', async () => {
+ // 旧默认指向已断开的供应商; 新默认可用 —— 不能先被「缺授权」挡掉。
+ mocks.listProviders.mockResolvedValue(providersWith(['claude-opus-4-7', 'claude-opus-4-8']));
+ mocks.findActiveSession.mockResolvedValue({
+ id: 'feishu-session',
+ agentKind: 'claude-code',
+ workingDir: 'F:\\XDMaker',
+ model: 'claude-opus-4-7',
+ effort: 'xhigh',
+ permissionMode: 'bypassPermissions',
+ fastMode: false,
+ sdkSessionId: null,
+ providerId: 'disconnected-provider',
+ });
+ mocks.peekSessionById.mockResolvedValue({
+ id: 'feishu-session',
+ agentKind: 'claude-code',
+ workingDir: 'F:\\XDMaker',
+ model: 'claude-opus-4-8',
+ effort: 'high',
+ permissionMode: 'bypassPermissions',
+ fastMode: false,
+ sdkSessionId: null,
+ providerId: 'xd',
+ });
+ const order: string[] = [];
+ const h = createSessionHarness(async () => ({ accepted: true }), 'feishu-session');
+ const maker = coldMakerHarness(h.session, order);
+ mocks.getMaker.mockReturnValue(maker);
+ const channelDefaultRoute = {
+ previewSwitchTarget: vi.fn(async () => ({
+ agentKind: 'claude-code' as const,
+ model: 'claude-opus-4-8',
+ providerId: 'xd',
+ effort: 'high',
+ })),
+ syncBeforeWiring: vi.fn(async () => undefined),
+ };
+ const localRunner = createTurnRunner(fakeAdapter, fakeRepo, fakeCards, {
+ acquirePendingAgentSwitch: vi.fn(async () => vi.fn()),
+ channelDefaultRoute,
+ });
+ try {
+ await localRunner.runAgentTurn({
+ botContextId: 'cli_test_bot',
+ userId: 'ou_user',
+ userMessageId: 'msg-follow-auth',
+ text: 'hello',
+ attachments: [],
+ });
+
+ expect(channelDefaultRoute.syncBeforeWiring).toHaveBeenCalledWith('feishu-session');
+ expect(maker.createSession).toHaveBeenCalledWith(
+ expect.objectContaining({ model: 'claude-opus-4-8', providerId: 'xd' }),
+ );
+ expect(h.send).toHaveBeenCalled();
+ } finally {
+ localRunner.disposeAllSessions();
+ }
+ });
+
+ it('never follows channel defaults on a /ctr attached desktop task', async () => {
+ const h = setupAttachedSession(async () => ({ accepted: true }));
+ const channelDefaultRoute = {
+ previewSwitchTarget: vi.fn(async () => null),
+ syncBeforeWiring: vi.fn(async () => undefined),
+ };
+ const acquirePendingAgentSwitch = vi.fn(async () => vi.fn());
+ const localRunner = createTurnRunner(fakeAdapter, fakeRepo, fakeCards, {
+ acquirePendingAgentSwitch,
+ channelDefaultRoute,
+ });
+ try {
+ await localRunner.runAgentTurn({
+ botContextId: 'cli_test_bot',
+ userId: 'ou_user',
+ userMessageId: 'msg-follow-attached',
+ text: 'hello',
+ attachments: [],
+ });
+
+ expect(h.send).toHaveBeenCalled();
+ expect(channelDefaultRoute.previewSwitchTarget).not.toHaveBeenCalled();
+ expect(acquirePendingAgentSwitch).toHaveBeenCalledWith('desktop-attached-session', {
+ channelOwned: false,
+ });
+ expect(localRunner.vendorOptionsForSession('desktop-attached-session')).toBeUndefined();
+ } finally {
+ localRunner.disposeAllSessions();
+ }
+ });
+ });
});
diff --git a/apps/desktop/src/main/im/shared/cardActionHandler.ts b/apps/desktop/src/main/im/shared/cardActionHandler.ts
index 036d609bd2..1f618a13e0 100644
--- a/apps/desktop/src/main/im/shared/cardActionHandler.ts
+++ b/apps/desktop/src/main/im/shared/cardActionHandler.ts
@@ -73,6 +73,7 @@ import {
updateModelEffort,
updatePermissionMode,
} from './sessionRepo';
+import { markImSessionManualRouteOverride } from './manualRouteOverride';
import { changeSessionPermissionMode } from './permissionModeControl';
import type { ImCardBuilders } from './cardBuilders';
import { enqueueAskCardPatch } from './askCardPatchQueue';
@@ -419,6 +420,22 @@ export function createCardActionHandler(
if (!liveAfterModel) {
log.info(`model:pick: no live session for ${sessionId.slice(-8)} — DB updated only`);
}
+ // 「脱离跟随」墓碑只在选择真正落地后写: 上面任何失败都会回滚持久路由, 若在
+ // updateModelEffort 里立碑, 失败回滚(同一函数)会让失败的选择永久脱离默认
+ // 跟随(PR #5155 review P2)。写失败按选择失败处理 —— 整体回滚并报错重试。
+ try {
+ await markImSessionManualRouteOverride(sessionId);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ log.warn(`model:pick manual override marker failed: ${msg}`);
+ // applyRuntimeSetModelChange 可能已向 PendingCredentialSwitch 登记了延迟目标,
+ // 失败回滚必须一并撤销, 否则 turn 收口仍会应用一个卡片已报失败的选择
+ // (PR #5155 review P2)。
+ clearPendingCredentialSwitchForSession(sessionId);
+ await restorePersistentRoute('manual override marker');
+ await rollbackRuntimeChange('manual override marker');
+ return msg;
+ }
// 这次 IM 选择晚于 renderer 登记的跨引擎 intent;只有整条 route 更新成功后
// 才取消旧 intent,失败回滚时仍保留它供下一次发送重试。
cancelPendingAgentSwitchForSession(sessionId);
diff --git a/apps/desktop/src/main/im/shared/channelDefaultRoute.ts b/apps/desktop/src/main/im/shared/channelDefaultRoute.ts
new file mode 100644
index 0000000000..571ebe8fc2
--- /dev/null
+++ b/apps/desktop/src/main/im/shared/channelDefaultRoute.ts
@@ -0,0 +1,241 @@
+/**
+ * 个人 IM 渠道任务「跟随渠道默认」的记录与判定(纯逻辑, 无 IO)。
+ *
+ * 渠道默认(设置页「新对话配置」)改了之后, 仍跟随默认的已有任务在下一条渠道
+ * 消息到来时换到新默认; 用户用 `/model`、桌面或手机单独改过路由的任务不动。
+ *
+ * 「跟随」按状态判断, 不拿旧默认值去猜: 渠道每次把默认落到任务上(建任务 /
+ * `/new` / 跟随切换成功)都在 `sessions.im_default_route` 记下当时的设置指纹与
+ * **读回的实际路由**; 之后任务当前路由与记录不一致 = 有人单独改过。
+ */
+import type { AgentKind } from '@cindy/maker-core';
+
+import type { ImDefaultSettings } from '../../../shared/imDefaultSettings.js';
+
+export interface ImDefaultRoute {
+ agentKind: AgentKind;
+ model: string;
+ providerId: string | null;
+ effort: string | null;
+}
+
+export interface ImDefaultRouteRecord {
+ v: 1;
+ /** 应用默认时渠道原始设置的指纹(fingerprintImDefaultSettings)。 */
+ fp: string;
+ /** 应用后任务上的实际路由。 */
+ route: ImDefaultRoute;
+ /** 已登记、尚未生效的跟随切换意图(登记后读回, 任务在跑 / 意图待发送时应用)。 */
+ pendingRoute?: ImDefaultRoute;
+ /** 登记该意图时的设置指纹 —— 设置没再变就不重复登记。 */
+ pendingFp?: string;
+ /**
+ * 登记该意图时 pending 注册表的修订号。用户重新挑选(哪怕选了同一模型/来源)
+ * 会推进修订号 —— 光比路由值分不出「自己的意图」和「用户挑了同值」,后者必须
+ * 按用户选择对待,不能被下一次默认变化覆盖。
+ */
+ pendingRev?: number;
+ /**
+ * 用户单独改过路由的永久标记(脱离跟随)。同值重选在路由值上无痕, 只能在用户
+ * 选择落地时立碑; 之后无论默认怎么变都不再跟随, `/new` 重置才会重新跟随
+ * (greptile P1 补充, PR #5155)。
+ */
+ manual?: true;
+}
+
+const AGENT_KINDS: readonly AgentKind[] = ['claude-code', 'codex', 'pi'];
+
+/**
+ * 渠道原始设置里影响路由的部分。三个引擎都算进去: 选定引擎的模型全被停用时
+ * 解析会回落到别的引擎, 那边的设置同样决定落点。权限档不在内 —— 它不跟随。
+ */
+export function fingerprintImDefaultSettings(raw: ImDefaultSettings): string {
+ return JSON.stringify([
+ raw.agentKind,
+ AGENT_KINDS.map((agent) => {
+ const settings = raw.agents[agent];
+ return settings ? [settings.providerId ?? null, settings.model, settings.effort] : null;
+ }),
+ ]);
+}
+
+function parseRoute(value: unknown): ImDefaultRoute | null {
+ if (!value || typeof value !== 'object') return null;
+ const r = value as Record<string, unknown>;
+ if (!AGENT_KINDS.includes(r.agentKind as AgentKind)) return null;
+ if (typeof r.model !== 'string' || !r.model) return null;
+ if (r.providerId !== null && typeof r.providerId !== 'string') return null;
+ if (r.effort !== null && typeof r.effort !== 'string') return null;
+ return {
+ agentKind: r.agentKind as AgentKind,
+ model: r.model,
+ providerId: (r.providerId as string | null) || null,
+ effort: (r.effort as string | null) || null,
+ };
+}
+
+/** 坏记录按「无记录」处理 —— 宁可不跟随, 不因脏数据误切用户的任务。 */
+export function parseImDefaultRouteRecord(json: string | null | undefined): ImDefaultRouteRecord | null {
+ if (!json) return null;
+ let value: unknown;
+ try {
+ value = JSON.parse(json);
+ } catch {
+ return null;
+ }
+ if (!value || typeof value !== 'object') return null;
+ const r = value as Record<string, unknown>;
+ if (r.v !== 1 || typeof r.fp !== 'string') return null;
+ const route = parseRoute(r.route);
+ if (!route) return null;
+ const manual = r.manual === true;
+ const pendingRoute = r.pendingRoute === undefined ? undefined : parseRoute(r.pendingRoute);
+ if (pendingRoute === null) return null;
+ const pendingFp = typeof r.pendingFp === 'string' ? r.pendingFp : undefined;
+ const pendingRev = typeof r.pendingRev === 'number' && Number.isFinite(r.pendingRev) ? r.pendingRev : undefined;
+ return {
+ v: 1,
+ fp: r.fp,
+ route,
+ ...(manual ? { manual: true } : {}),
+ ...(pendingRoute ? { pendingRoute } : {}),
+ ...(pendingRoute && pendingFp ? { pendingFp } : {}),
+ ...(pendingRoute && pendingRev !== undefined ? { pendingRev } : {}),
+ };
+}
+
+export function serializeImDefaultRouteRecord(record: ImDefaultRouteRecord): string {
+ return JSON.stringify(record);
+}
+
+export function buildImDefaultRouteRecord(
+ fp: string,
+ route: ImDefaultRoute,
+ pending?: { route: ImDefaultRoute; fp: string; rev?: number },
+): string {
+ return serializeImDefaultRouteRecord({
+ v: 1,
+ fp,
+ route,
+ ...(pending
+ ? {
+ pendingRoute: pending.route,
+ pendingFp: pending.fp,
+ ...(pending.rev !== undefined ? { pendingRev: pending.rev } : {}),
+ }
+ : {}),
+ });
+}
+
+/**
+ * 用户单独改过路由的永久标记(脱离跟随)。同值重选在路由值上无痕 —— 记录一旦写成
+ * 这份墓碑就不再跟随渠道默认, `/new` 重置会用普通记录覆盖它、重新跟随。
+ */
+export function buildImManualRouteOverrideRecord(route: ImDefaultRoute): string {
+ return serializeImDefaultRouteRecord({ v: 1, fp: '', route, manual: true });
+}
+
+/**
+ * 路由相等。供应商由调用方先归一化: 系统会把隐式来源(null)钉成具体来源
+ * (启动改道 / 切换时的独占改道), 不归一化会把这类系统行为误判成用户改过。
+ */
+export function sameImDefaultRoute(
+ a: ImDefaultRoute,
+ b: ImDefaultRoute,
+ normalizeProvider: (route: ImDefaultRoute) => string | null = (route) => route.providerId,
+): boolean {
+ return (
+ a.agentKind === b.agentKind &&
+ a.model === b.model &&
+ (a.effort ?? null) === (b.effort ?? null) &&
+ normalizeProvider(a) === normalizeProvider(b)
+ );
+}
+
+/** 指纹没变就不必解析新默认(每条消息都会走到这里, 这一步不碰供应商列表)。 */
+export function imDefaultRouteMayNeedSync(
+ record: ImDefaultRouteRecord | null,
+ fp: string,
+): record is ImDefaultRouteRecord {
+ return !!record && record.fp !== fp;
+}
+
+export type ImDefaultRouteDecision =
+ /** 当前路由已是新默认: 只更新记录(必要时撤掉本功能此前登记的过时意图)。 */
+ | { kind: 'adopt'; cancelPendingIntent?: true }
+ /** 本功能此前登记的跟随切换仍待生效, 且目标没变: 不重复登记。 */
+ | { kind: 'staged' }
+ /** 仍跟随默认, 需要切到新默认。 */
+ | { kind: 'switch' }
+ /**
+ * 用户单独改过(已生效或已挑选待生效): 不动。
+ * `clearStalePending` = 记录里挂着的待生效意图已被用户的选择顶掉,
+ * 顺手清掉这条过时声称, 免得用户的选择落地后被误认成「跟随中的切换落地」。
+ */
+ | { kind: 'manual'; clearStalePending?: true };
+
+/**
+ * 记录里的待生效声称是否就是这一个在世意图 —— 本功能登记、尚未被用户顶掉。
+ * 注册表有修订号就必须逐号对上(用户重挑过哪怕同值也算用户的);
+ * 读不到修订号(测试最小 harness)才回落按值比较。
+ */
+export function recordClaimsPendingIntent(
+ record: ImDefaultRouteRecord | null | undefined,
+ pendingIntent: ImDefaultRoute | undefined,
+ pendingRev: number | undefined,
+ normalizeProvider?: (route: ImDefaultRoute) => string | null,
+): boolean {
+ if (!record || record.manual || !record.pendingRoute || !pendingIntent) return false;
+ return (
+ sameImDefaultRoute(pendingIntent, record.pendingRoute, normalizeProvider) &&
+ (pendingRev === undefined || record.pendingRev === pendingRev)
+ );
+}
+
+/**
+ * `current` 取 DB 持久路由: 用户的选择要么已落库, 要么是待应用的切换意图;
+ * 自动回退 / Agent 自选只在内存里生效, 与伙伴配置变更同口径 —— 渠道默认一改就覆盖它们。
+ */
+export function decideImDefaultRoute(input: {
+ record: ImDefaultRouteRecord;
+ current: ImDefaultRoute;
+ target: ImDefaultRoute;
+ /** 解析出 target 的设置指纹。 */
+ targetFp: string;
+ /** 会话上待应用的切换意图目标(无则 undefined)。 */
+ pendingIntent?: ImDefaultRoute;
+ /** 当前待应用意图在 pending 注册表的修订号(读回时带出)。 */
+ pendingRev?: number;
+ normalizeProvider?: (route: ImDefaultRoute) => string | null;
+}): ImDefaultRouteDecision {
+ const same = (a: ImDefaultRoute, b: ImDefaultRoute) =>
+ sameImDefaultRoute(a, b, input.normalizeProvider);
+ const { record, current, target, pendingIntent } = input;
+ // 用户单独改过(含同值重选的墓碑): 永不跟随。
+ if (record.manual) return { kind: 'manual' };
+ // 「仍在跟随」的证据: 当前路由就是记录的路由, 或落到了本功能登记的待生效目标上
+ // (意图被发送路径应用了、记录还没来得及更新)。**不能**用「恰好等于新默认」当证据 ——
+ // 用户单独改成 B、默认随后也改成 B 时, 按值相等认领会把手动覆盖洗成跟随
+ // (chatgpt-codex-connector P2, PR #5155)。
+ const followingNow =
+ same(current, record.route) || (!!record.pendingRoute && same(current, record.pendingRoute));
+ if (pendingIntent) {
+ // 意图是不是本功能登记的那一次: 路由值相等还不够 —— 自动切换未生效时用户又
+ // 明确挑了同样的模型/来源, 会顶掉登记、值却一模一样(greptile P1, PR #5155)。
+ // 修订号每次 set/clear 都推进, 用户重新挑过就对不上; 对不上一律按用户选择。
+ const ours = recordClaimsPendingIntent(record, pendingIntent, input.pendingRev, input.normalizeProvider);
+ if (!ours) {
+ return record.pendingRoute ? { kind: 'manual', clearStalePending: true } : { kind: 'manual' };
+ }
+ // 自己登记的: 设置没再变就等发送路径应用(按指纹判断 —— 登记时系统可能改道了
+ // 来源, 意图与 target 不必逐字相等); 设置又改了就改登记到最新目标;
+ // 设置改回了任务当前路由 → 撤掉过时意图。
+ if (record.pendingFp ? record.pendingFp === input.targetFp : same(pendingIntent, target)) {
+ return { kind: 'staged' };
+ }
+ return same(current, target) ? { kind: 'adopt', cancelPendingIntent: true } : { kind: 'switch' };
+ }
+ if (same(current, target)) return followingNow ? { kind: 'adopt' } : { kind: 'manual' };
+ if (followingNow) return { kind: 'switch' };
+ return { kind: 'manual' };
+}
diff --git a/apps/desktop/src/main/im/shared/channelDefaultRouteSync.ts b/apps/desktop/src/main/im/shared/channelDefaultRouteSync.ts
new file mode 100644
index 0000000000..2bda046835
--- /dev/null
+++ b/apps/desktop/src/main/im/shared/channelDefaultRouteSync.ts
@@ -0,0 +1,574 @@
+/**
+ * 个人 IM 渠道任务跟随渠道默认 —— 读写 `sessions.im_default_route` 并驱动切换。
+ *
+ * 时机: 渠道自有任务收到下一条消息、进入 send 锁之后(acquirePendingAgentSwitchForImSend
+ * 的回调)。切换走与伙伴模型对齐同一套路由选择(跨引擎带交接, 会话忙时留意图);
+ * 任何失败都只记日志、保持原路由, 绝不挡住用户这条消息。判定规则见
+ * channelDefaultRoute.ts。
+ */
+import { and, eq, inArray, isNull } from 'drizzle-orm';
+import type { AgentKind } from '@cindy/maker-core';
+import { effectiveSourceIdForModel, type ProviderView } from '@cindy/model-providers';
+
+import type { ImDefaultSettingsChannel } from '../../../shared/imDefaultSettings.js';
+import { getDbClient } from '../../localDb/client/current';
+import { sessions } from '../../localDb/schema';
+import { createLogger } from '../../logger';
+import { getDesktopProviderService } from '../../maker-host/createDesktopProviderService';
+import {
+ acquirePendingAgentSwitchForImSend,
+ applySessionRouteUnderSendLock,
+ cancelPendingAgentSwitchForSession,
+ readPendingAgentSwitchRoute,
+} from '../../maker-ipc/register';
+import { withSendToSessionLock } from '../../maker-ipc/sendToSessionLock';
+import {
+ readImDefaultSettingsFingerprint,
+ readImRawDefaultRoute,
+ resolveImSessionDefaults,
+} from '../defaultSessionSettings';
+import {
+ buildImDefaultRouteRecord,
+ decideImDefaultRoute,
+ imDefaultRouteMayNeedSync,
+ parseImDefaultRouteRecord,
+ recordClaimsPendingIntent,
+ sameImDefaultRoute,
+ serializeImDefaultRouteRecord,
+ type ImDefaultRoute,
+ type ImDefaultRouteDecision,
+ type ImDefaultRouteRecord,
+} from './channelDefaultRoute';
+import { resetSessionToDefaults, toCoreAgentKind, type ImSessionRow } from './sessionRepo';
+import type { ImOrchestratorConfig } from './types';
+
+const log = createLogger('im:default-route');
+
+type RouteAuthCheck = (route: Pick<ImDefaultRoute, 'agentKind' | 'model' | 'providerId'>) => Promise<boolean>;
+
+export interface ImChannelDefaultRouteSync {
+ /**
+ * 本条消息若会触发跟随切换, 返回将要切到的目标路由(新默认可用才返回), 供
+ * 发送前的授权检查按真实会跑的路由判断 —— 旧默认坏掉时不能先被「缺授权」挡掉。
+ * 只读, 不登记任何东西。
+ */
+ previewSwitchTarget(sessionId: string): Promise<ImDefaultRoute | null>;
+ /**
+ * 在 send 锁内对齐。从不抛错。
+ * 返回 true = 跟随切换被暂缓(会话有后台工作 / 待处理交互) —— 调用方本次不得再走
+ * 通用意图应用(那里的忙判定只看 isTurnRunning, 会立即应用刚登记的意图、跨引擎时
+ * 重建仍在承载后台工作的会话, PR #5155 review P1)。
+ */
+ syncUnderLock(sessionId: string): Promise<boolean>;
+ /**
+ * 未接线(无运行实例)的任务在接线前先对齐, 避免先用可能已坏的旧路由起一次进程。
+ * 自己取放 send 锁, 从不抛错。
+ */
+ syncBeforeWiring(sessionId: string): Promise<void>;
+}
+
+interface SessionRouteRow {
+ source: string | null;
+ status: string;
+ remoteHostId: string | null;
+ orcaRole: string | null;
+ agentKind: string;
+ model: string | null;
+ providerId: string | null;
+ effort: string | null;
+ /** Fast 不属于路由; 只有跟随切换用得到(保留任务自己的开关), 回填选择不带它。 */
+ fastMode?: boolean | null;
+ imDefaultRoute: string | null;
+ feishuBotAppId: string | null;
+ imBotContextId: string | null;
+}
+
+async function readSessionRouteRow(sessionId: string): Promise<SessionRouteRow | null> {
+ const [row] = await getDbClient()
+ .drizzle.select({
+ source: sessions.source,
+ status: sessions.status,
+ remoteHostId: sessions.remoteHostId,
+ orcaRole: sessions.orcaRole,
+ agentKind: sessions.agentKind,
+ model: sessions.model,
+ providerId: sessions.providerId,
+ effort: sessions.effort,
+ fastMode: sessions.fastMode,
+ imDefaultRoute: sessions.imDefaultRoute,
+ feishuBotAppId: sessions.feishuBotAppId,
+ imBotContextId: sessions.imBotContextId,
+ })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ return row ?? null;
+}
+
+/** 本渠道自己的活跃本机任务。官方 hook / 已轮换的 Telegram 任务没有渠道标记列。 */
+function isChannelOwnedRow(
+ row: SessionRouteRow,
+ source: string,
+ opts?: { includeRevivable?: boolean },
+): boolean {
+ const statusOk =
+ row.status === 'active' ||
+ (opts?.includeRevivable === true && (row.status === 'archived' || row.status === 'deleted'));
+ if (row.source !== source || !statusOk) return false;
+ if (row.remoteHostId || row.orcaRole || !row.model) return false;
+ return source === 'feishu' ? !!row.feishuBotAppId : !!row.imBotContextId;
+}
+
+function currentRouteOf(row: SessionRouteRow): ImDefaultRoute {
+ return {
+ agentKind: toCoreAgentKind(row.agentKind),
+ model: row.model ?? '',
+ providerId: row.providerId?.trim() || null,
+ effort: row.effort ?? null,
+ };
+}
+
+/**
+ * 隐式来源按「新路由选择」口径落到具体来源 —— 系统建会话钉住 / 切换时独占改道
+ * 用的就是这个口径, 与它钉出的具体 id 视为同一条路由。显式来源原样比较。
+ */
+function providerNormalizer(providers: ProviderView[]) {
+ return (route: ImDefaultRoute): string | null =>
+ route.providerId ?? effectiveSourceIdForModel(providers, null, route.model, route.agentKind as AgentKind);
+}
+
+async function listProviders(): Promise<ProviderView[] | null> {
+ try {
+ return await getDesktopProviderService().listProviders({ allowSideEffects: true });
+ } catch {
+ return null;
+ }
+}
+
+interface Evaluation {
+ decision: ImDefaultRouteDecision;
+ record: ImDefaultRouteRecord;
+ current: ImDefaultRoute;
+ target: ImDefaultRoute;
+ targetFingerprint: string;
+ providers: ProviderView[];
+ /**
+ * 任务当前的 Fast 开关。渠道默认不存 Fast, 跟随切换只管 Agent/模型/来源/档位,
+ * 单独开过 Fast 的任务不能被顺手清掉(chatgpt-codex-connector P2, PR #5155)。
+ */
+ currentFastMode: boolean;
+}
+
+export function createImChannelDefaultRouteSync(deps: {
+ source: ImDefaultSettingsChannel;
+ config: ImOrchestratorConfig;
+ isRouteUsable: RouteAuthCheck;
+}): ImChannelDefaultRouteSync {
+ const { source, config } = deps;
+
+ async function evaluate(sessionId: string): Promise<Evaluation | 'defer-unknown' | null> {
+ const row = await readSessionRouteRow(sessionId);
+ if (!row || !isChannelOwnedRow(row, source)) return null;
+ const record = parseImDefaultRouteRecord(row.imDefaultRoute);
+ // 用户单独改过路由(墓碑): 永不跟随, 不必解析新默认。
+ if (record?.manual) return null;
+ if (!imDefaultRouteMayNeedSync(record, readImDefaultSettingsFingerprint(source))) return null;
+ const providers = await listProviders();
+ // 目录拿不到就无法可靠比对来源, 本条消息先按原路由走 —— 但若记录仍认领着在世
+ // 的系统意图, 调用方必须暂缓通用意图应用(PR #5155 review P2)。
+ if (!providers) return 'defer-unknown';
+ const defaults = await resolveImSessionDefaults(config, providers, source);
+ const target: ImDefaultRoute = {
+ agentKind: defaults.agentKind,
+ model: defaults.model,
+ providerId: defaults.providerId,
+ effort: defaults.effort,
+ };
+ const current = currentRouteOf(row);
+ const pending = readPendingAgentSwitchRoute(sessionId);
+ const decision = decideImDefaultRoute({
+ record,
+ current,
+ target,
+ targetFp: defaults.fingerprint,
+ pendingIntent: pending
+ ? {
+ agentKind: pending.agentKind,
+ model: pending.model,
+ providerId: pending.providerId,
+ effort: pending.effort ?? null,
+ }
+ : undefined,
+ pendingRev: pending?.rev,
+ normalizeProvider: providerNormalizer(providers),
+ });
+ return {
+ decision,
+ record,
+ current,
+ target,
+ targetFingerprint: defaults.fingerprint,
+ providers,
+ currentFastMode: row.fastMode === true,
+ };
+ }
+
+ async function writeRecord(sessionId: string, json: string): Promise<void> {
+ await getDbClient()
+ .drizzle.update(sessions)
+ .set({ imDefaultRoute: json })
+ .where(eq(sessions.id, sessionId));
+ }
+
+ async function switchRoute(sessionId: string, e: Evaluation): Promise<boolean> {
+ if (!(await deps.isRouteUsable(e.target))) {
+ log.warn(
+ `default route sync skipped: new ${source} default unusable ` +
+ `session=...${sessionId.slice(-8)} target=${e.target.agentKind}/${e.target.model}`,
+ );
+ return false;
+ }
+ // 先记下待生效目标(指纹保持旧值): 意图丢失(重启)或应用失败时, 下一条消息
+ // 仍能认出这是「跟随中的任务」并重试, 而不是误判为用户改过。
+ const pendingFor = (route: ImDefaultRoute, rev?: number) => ({
+ route,
+ fp: e.targetFingerprint,
+ ...(rev !== undefined ? { rev } : {}),
+ });
+ await writeRecord(sessionId, buildImDefaultRouteRecord(e.record.fp, e.record.route, pendingFor(e.target)));
+ let outcome: 'applied' | 'staged';
+ try {
+ outcome = await applySessionRouteUnderSendLock(
+ sessionId,
+ // Fast 不属于渠道默认: 保留任务自己的开关, 不拿新任务的固定默认覆盖。
+ { ...e.target, fastMode: e.currentFastMode },
+ e.current.agentKind,
+ );
+ } catch (err) {
+ await writeRecord(sessionId, serializeImDefaultRouteRecord(e.record));
+ throw err;
+ }
+ if (outcome === 'staged') {
+ // 记登记后读回的意图与它的注册修订号 —— 系统登记时可能改道了来源;
+ // 下一条消息据此认出「自己的意图」(用户重新挑过会换修订号, 不会误认)。
+ // 这次写失败也不能丢「暂缓」结论: 否则外层会继续通用意图应用, 把刚登记的
+ // 意图应用到仍在承载后台工作的会话上(PR #5155 review P1)。
+ try {
+ const intent = readPendingAgentSwitchRoute(sessionId);
+ if (intent) {
+ await writeRecord(
+ sessionId,
+ buildImDefaultRouteRecord(
+ e.record.fp,
+ e.record.route,
+ pendingFor(
+ {
+ agentKind: intent.agentKind,
+ model: intent.model,
+ providerId: intent.providerId,
+ effort: intent.effort ?? null,
+ },
+ intent.rev,
+ ),
+ ),
+ );
+ }
+ } catch (err) {
+ // 声称写失败不能留「无修订号的声称 + 带修订号的意图」: 下一条消息的
+ // decideImDefaultRoute 会把系统意图误判成用户选择, 走 manual 后被通用 apply
+ // 用更宽的忙判定应用掉(chatgpt-codex-connector P2, PR #5155)。撤回本次意图
+ // 并恢复原声称 —— 下一条消息按「仍在跟随」重新发起切换, 自愈确定。
+ // (send 锁在手, 意图必然是本次登记的, 不会误伤用户的选择。)
+ log.warn(
+ `default route staged claim write failed; withdrawing intent session=...${sessionId.slice(-8)}: ` +
+ (err instanceof Error ? err.message : String(err)),
+ );
+ cancelPendingAgentSwitchForSession(sessionId);
+ try {
+ await writeRecord(sessionId, buildImDefaultRouteRecord(e.record.fp, e.record.route));
+ } catch (restoreErr) {
+ log.warn(
+ `default route claim restore failed (non-fatal) session=...${sessionId.slice(-8)}: ` +
+ (restoreErr instanceof Error ? restoreErr.message : String(restoreErr)),
+ );
+ }
+ }
+ log.info(`default route switch staged session=...${sessionId.slice(-8)} (runtime busy)`);
+ return true;
+ }
+ await recordApplied(sessionId, e);
+ return false;
+ }
+
+ /**
+ * 忙时登记的跟随意图由这里自己应用, 不交给通用发送路径: 同引擎应用失败在那边会
+ * 直接让用户这条消息失败。这里失败则撤回意图、保持原路由。
+ */
+ async function applyStaged(sessionId: string, e: Evaluation): Promise<boolean> {
+ let outcome: 'applied' | 'staged';
+ try {
+ outcome = await applySessionRouteUnderSendLock(sessionId, null, e.current.agentKind);
+ } catch (err) {
+ await writeRecord(sessionId, buildImDefaultRouteRecord(e.record.fp, e.record.route));
+ throw err;
+ }
+ if (outcome === 'applied') {
+ await recordApplied(sessionId, e);
+ return false;
+ }
+ return true;
+ }
+
+ async function recordApplied(sessionId: string, e: Evaluation): Promise<void> {
+ // 记录读回的实际路由 —— 系统可能在应用时改道来源 / 校正档位。
+ const after = await readSessionRouteRow(sessionId);
+ const applied = after ? currentRouteOf(after) : e.target;
+ const normalize = providerNormalizer(e.providers);
+ if (!sameImDefaultRoute(applied, e.target, normalize)) {
+ log.warn(
+ `default route switch landed on a different route session=...${sessionId.slice(-8)} ` +
+ `target=${e.target.agentKind}/${e.target.model} actual=${applied.agentKind}/${applied.model}`,
+ );
+ }
+ await writeRecord(sessionId, buildImDefaultRouteRecord(e.targetFingerprint, applied));
+ log.info(
+ `default route followed session=...${sessionId.slice(-8)} ` +
+ `${e.current.agentKind}/${e.current.model} -> ${applied.agentKind}/${applied.model}`,
+ );
+ }
+
+ async function previewSwitchTarget(sessionId: string): Promise<ImDefaultRoute | null> {
+ try {
+ const e = await evaluate(sessionId);
+ if (!e || e === 'defer-unknown') return null;
+ if (e.decision.kind !== 'switch' && e.decision.kind !== 'staged') return null;
+ return (await deps.isRouteUsable(e.target)) ? e.target : null;
+ } catch (err) {
+ log.warn(`default route preview failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);
+ return null;
+ }
+ }
+
+ /**
+ * 目录暂不可读、无法判定要不要跟随时, 记录仍认领着在世系统意图 ⇒ 本次暂缓通用
+ * 意图应用(返回 true): 那里的忙判定只看 isTurnRunning, 会把刚登记的意图应用到
+ * 仍在承载后台工作/交互的会话上(PR #5155 review P2)。认不出是自己的意图就不挡。
+ */
+ async function followClaimStillPending(sessionId: string): Promise<boolean> {
+ try {
+ const row = await readSessionRouteRow(sessionId);
+ if (!row || !isChannelOwnedRow(row, source)) return false;
+ const pending = readPendingAgentSwitchRoute(sessionId);
+ return recordClaimsPendingIntent(
+ parseImDefaultRouteRecord(row.imDefaultRoute),
+ pending
+ ? {
+ agentKind: pending.agentKind,
+ model: pending.model,
+ providerId: pending.providerId,
+ effort: pending.effort ?? null,
+ }
+ : undefined,
+ pending?.rev,
+ );
+ } catch (err) {
+ log.warn(
+ `default route pending-claim check failed (non-fatal) session=...${sessionId.slice(-8)}: ` +
+ (err instanceof Error ? err.message : String(err)),
+ );
+ return false;
+ }
+ }
+
+ async function syncUnderLock(sessionId: string): Promise<boolean> {
+ try {
+ const e = await evaluate(sessionId);
+ if (e === 'defer-unknown') return await followClaimStillPending(sessionId);
+ if (!e) return false;
+ switch (e.decision.kind) {
+ case 'adopt':
+ if (e.decision.cancelPendingIntent) cancelPendingAgentSwitchForSession(sessionId);
+ await writeRecord(sessionId, buildImDefaultRouteRecord(e.targetFingerprint, e.current));
+ return false;
+ case 'switch':
+ return await switchRoute(sessionId, e);
+ case 'staged':
+ return await applyStaged(sessionId, e);
+ case 'manual':
+ // 用户的选择顶掉了本功能登记的待生效意图: 清掉过时声称, 但绝不动用户的意图。
+ if (e.decision.clearStalePending) {
+ await writeRecord(sessionId, buildImDefaultRouteRecord(e.record.fp, e.record.route));
+ }
+ return false;
+ }
+ } catch (err) {
+ log.warn(
+ `default route sync failed (non-fatal, keeping current route) session=...${sessionId.slice(-8)}: ` +
+ (err instanceof Error ? err.message : String(err)),
+ );
+ return false;
+ }
+ }
+
+ async function syncBeforeWiring(sessionId: string): Promise<void> {
+ try {
+ const release = await acquirePendingAgentSwitchForImSend(sessionId, () => syncUnderLock(sessionId));
+ release();
+ } catch (err) {
+ log.warn(
+ `default route pre-wiring sync failed (non-fatal) session=...${sessionId.slice(-8)}: ` +
+ (err instanceof Error ? err.message : String(err)),
+ );
+ }
+ }
+
+ return { previewSwitchTarget, syncUnderLock, syncBeforeWiring };
+}
+
+/**
+ * 本功能上线前建的任务没有记录。保存 / 恢复渠道默认之前, 把仍在用**旧默认**的这类
+ * 任务补上旧默认的记录, 让它们在下一条消息时跟随新默认。规则允许的「历史缺少状态」
+ * 情形, 只做值比较。返回补记的任务数。
+ *
+ * 旧默认的识别有两条路, 只靠解析结果会漏(chatgpt-codex-connector P2, PR #5155):
+ * 旧默认的来源断开 / 模型停用后, `resolveImSessionDefaults` 会把旧设置回落到别的
+ * 可用路由, 拿回落值去跟历史任务实际落点比永远匹配不到, 这些任务的 `im_default_route`
+ * 会一直空着 —— 而用户正是在修坏默认时最需要迁移它们。所以同时按**保存的原始默认**
+ * (未过可用性回落)认领。
+ *
+ * 匹配要求**整条路由相等**(含 effort): 思考强度是承诺按手动选择保护的路由轴, 只
+ * 改过 effort 的历史任务不能被认领(PR #5155 review P1);原始默认的 effort 在设置
+ * 保存时就已按模型 reconcile 过, 与历史落点一致。
+ *
+ * 另外两类历史兼容落点(PR #5155 review P2):
+ * - 归档/软删的可复活任务: 用户从 IM 再发消息会原地复活, 复活不补记录, 保存前
+ * 不认领就永久错过 —— 回填一并覆盖。
+ * - 隐式默认(null)建任务时被系统钉成当时的有效来源, 该来源后来断开后两条候选
+ * 都对不上 —— **不认领**: 「来源已断开」无法证明当年是系统钉住还是用户手动
+ * 钉的, 无法区分时保守不动(同 thread 后续裁决); 本功能之后建的任务在创建时
+ * 就写记录(route 含钉住的来源), 不依赖这层历史猜测。
+ *
+ * 无法可靠识别时(供应商目录拿不到)必须抛错而不是返回 0: 调用方把 0 当成「补完了」
+ * 就会提交新默认, 下一次只能按新默认匹配, 还停在旧默认上的老任务永久失去跟随资格。
+ */
+export async function backfillLegacyImDefaultRoutes(
+ source: ImDefaultSettingsChannel,
+ config: ImOrchestratorConfig,
+ /** 进入时捕获的客户端: 读写全程复用, 不在 await 间隙重读全局(owner 切换后指向新账号)。 */
+ dbClient: ReturnType<typeof getDbClient> = getDbClient(),
+): Promise<number> {
+ const rows = await dbClient
+ .drizzle.select({
+ id: sessions.id,
+ source: sessions.source,
+ status: sessions.status,
+ remoteHostId: sessions.remoteHostId,
+ orcaRole: sessions.orcaRole,
+ agentKind: sessions.agentKind,
+ model: sessions.model,
+ providerId: sessions.providerId,
+ effort: sessions.effort,
+ imDefaultRoute: sessions.imDefaultRoute,
+ feishuBotAppId: sessions.feishuBotAppId,
+ imBotContextId: sessions.imBotContextId,
+ })
+ .from(sessions)
+ .where(
+ and(
+ eq(sessions.source, source),
+ // 归档/软删的可复活任务一并覆盖: findActiveSession 会原地复活它们且不补
+ // 记录, 保存前不认领就永久错过(PR #5155 review P2)。
+ inArray(sessions.status, ['active', 'archived', 'deleted']),
+ isNull(sessions.imDefaultRoute),
+ ),
+ );
+ const legacyRows = rows.filter((row) => isChannelOwnedRow(row, source, { includeRevivable: true }));
+ // 没有要补的就不碰供应商目录 —— 目录不可用也挡不住用户的设置保存。
+ if (legacyRows.length === 0) return 0;
+ const providers = await listProviders();
+ if (!providers) {
+ throw new Error(
+ `provider catalog unavailable; cannot backfill ${source} default-route records`,
+ );
+ }
+ const rawDefault = readImRawDefaultRoute(source);
+ const fingerprint = readImDefaultSettingsFingerprint(source);
+ let resolvedDefault: ImDefaultRoute | null = null;
+ try {
+ const defaults = await resolveImSessionDefaults(config, providers, source);
+ resolvedDefault = {
+ agentKind: defaults.agentKind,
+ model: defaults.model,
+ providerId: defaults.providerId,
+ effort: defaults.effort,
+ };
+ } catch (err) {
+ // 旧默认已坏到解析不出来(如全部模型被停用): 只按保存的原始默认认领 —— 用户
+ // 正是要存新默认来修它, 不能因为解析旧默认失败而把保存也堵死。
+ log.warn(
+ `default route backfill: old ${source} default unresolvable; matching raw settings only: ` +
+ (err instanceof Error ? err.message : String(err)),
+ );
+ }
+ const normalize = providerNormalizer(providers);
+ let count = 0;
+ for (const row of legacyRows) {
+ const current = currentRouteOf(row);
+ // 匹配只认整条路由相等: 隐式默认的历史钉住与用户手动钉住无法区分(断开的来源
+ // 证明不了出身), 无法区分时保守不认领(PR #5155 review P2 后续裁决)。
+ const matches =
+ (!!resolvedDefault && sameImDefaultRoute(current, resolvedDefault, normalize)) ||
+ sameImDefaultRoute(current, rawDefault, normalize);
+ if (!matches) continue;
+ await dbClient
+ .drizzle.update(sessions)
+ .set({ imDefaultRoute: buildImDefaultRouteRecord(fingerprint, current) })
+ .where(and(eq(sessions.id, row.id), isNull(sessions.imDefaultRoute)));
+ count += 1;
+ }
+ if (count > 0) log.info(`backfilled default route records for ${count} legacy ${source} task(s)`);
+ return count;
+}
+
+/**
+ * 启动期补齐:回填此前只由设置保存/重置触发, 升级时已有、`im_default_route` 仍
+ * 为空的老任务若用户从未动过设置就永远轮不到 —— 同步对空记录直接跳过, 后续
+ * 版本把内置默认从 A 改到 B 后, 这些未自定义的老任务会永久固定在 A
+ * (PR #5155 review P2)。在仍能识别当前基线的启动阶段补上, 不依赖用户以后
+ * 主动保存。
+ *
+ * 每次启动都跑(幂等: 无候选行即返回, 也是失败后的自愈重试); 失败只告警、
+ * 不挡连接启动。只补记录不写设置, 全程复用进入时捕获的 DbClient(owner
+ * 切换后不跨账号写)。
+ */
+export async function backfillLegacyImDefaultRoutesAtStartup(
+ entries: Array<{ source: ImDefaultSettingsChannel; config: ImOrchestratorConfig }>,
+ dbClient: ReturnType<typeof getDbClient> = getDbClient(),
+): Promise<void> {
+ for (const { source, config } of entries) {
+ try {
+ await backfillLegacyImDefaultRoutes(source, config, dbClient);
+ } catch (err) {
+ log.warn(
+ `default route startup backfill failed for ${source} (retries next boot): ` +
+ (err instanceof Error ? err.message : String(err)),
+ );
+ }
+ }
+}
+
+/**
+ * 单行渠道的 `/new`: 在 send 锁内把任务重置为渠道默认(连同跟随记录), 并撤掉残留的
+ * 切换意图 —— 否则重置前登记的意图会在下一条消息时把刚重置的任务又切走。
+ */
+export async function resetImSessionToChannelDefaults(
+ sessionId: string,
+ config: ImOrchestratorConfig,
+ prepared: ImSessionRow | undefined,
+ channel: ImDefaultSettingsChannel,
+): Promise<void> {
+ await withSendToSessionLock(sessionId, async () => {
+ await resetSessionToDefaults(sessionId, config, prepared, channel);
+ if (readPendingAgentSwitchRoute(sessionId)) cancelPendingAgentSwitchForSession(sessionId);
+ });
+}
diff --git a/apps/desktop/src/main/im/shared/manualRouteOverride.ts b/apps/desktop/src/main/im/shared/manualRouteOverride.ts
new file mode 100644
index 0000000000..5140e7ef78
--- /dev/null
+++ b/apps/desktop/src/main/im/shared/manualRouteOverride.ts
@@ -0,0 +1,73 @@
+/**
+ * 用户单独改过路由的持久标记(脱离渠道默认跟随)。
+ *
+ * 「单独改过」按选择行为判定、不看取值: 用户经 `/model`、桌面或手机重选路由,
+ * 即使选的恰与当前/默认同值, 任务此后也不再跟随渠道默认(greptile P1 补充,
+ * PR #5155)。同值重选在路由值上无痕, 只能在**用户选择落地**时立墓碑
+ * (`buildImManualRouteOverrideRecord`); `/new` 重置会用普通记录覆盖、重新跟随。
+ *
+ * 本模块保持叶子(只依赖 localDb 与纯逻辑), maker-ipc 与 IM 侧都能调用, 不引入
+ * 循环依赖。只给渠道自有任务写 —— 其它任务没有跟随记录, 写了只是垃圾。
+ */
+import { eq } from 'drizzle-orm';
+
+import { dbToMakerAgentKind } from '../../../shared/agentKindConversion.js';
+import {
+ IM_DEFAULT_SETTINGS_CHANNELS,
+ type ImDefaultSettingsChannel,
+} from '../../../shared/imDefaultSettings.js';
+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../../appSessionState.js';
+import { getDbClient } from '../../localDb/client/current';
+import { sessions } from '../../localDb/schema';
+import { createLogger } from '../../logger';
+import { buildImManualRouteOverrideRecord, type ImDefaultRoute } from './channelDefaultRoute';
+
+const log = createLogger('im:default-route');
+
+export async function markImSessionManualRouteOverride(sessionId: string): Promise<void> {
+ // owner 边界(PR #5155 review P1): 读写跨 await, 期间登出/切号会让全局 getDbClient
+ // 指向新 owner —— B 有同 ID 任务会被写进 A 的墓碑, 否则更新零行还按成功返回,
+ // A 的手动选择从此没有墓碑、会被渠道默认覆盖。进入时捕获 owner scope 与 DbClient,
+ // 全程复用同一客户端; 写入前复核 scope 未变且无 boundary 在途, 不满足抛错让上层
+ // 按选择失败重试(与设置保存的 owner 边界校验同口径)。
+ const ownerScopeKey = activeOwnerScopeKey();
+ const dbClient = getDbClient();
+ const [row] = await dbClient
+ .drizzle.select({
+ source: sessions.source,
+ status: sessions.status,
+ remoteHostId: sessions.remoteHostId,
+ orcaRole: sessions.orcaRole,
+ agentKind: sessions.agentKind,
+ model: sessions.model,
+ providerId: sessions.providerId,
+ effort: sessions.effort,
+ feishuBotAppId: sessions.feishuBotAppId,
+ imBotContextId: sessions.imBotContextId,
+ })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ if (!row) return;
+ if (row.status !== 'active' || row.remoteHostId || row.orcaRole || !row.model) return;
+ const source = row.source;
+ if (!source || !IM_DEFAULT_SETTINGS_CHANNELS.includes(source as ImDefaultSettingsChannel)) return;
+ if (source === 'feishu' ? !row.feishuBotAppId : !row.imBotContextId) return;
+ const route: ImDefaultRoute = {
+ agentKind: dbToMakerAgentKind(row.agentKind),
+ model: row.model,
+ providerId: row.providerId?.trim() || null,
+ effort: row.effort ?? null,
+ };
+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== ownerScopeKey) {
+ throw new Error('app session owner changed before manual override marker write; retry the selection');
+ }
+ await dbClient
+ .drizzle.update(sessions)
+ .set({ imDefaultRoute: buildImManualRouteOverrideRecord(route) })
+ .where(eq(sessions.id, sessionId));
+ log.info(
+ `manual route override recorded session=...${sessionId.slice(-8)} ` +
+ `(${route.agentKind}/${route.model}; stops following channel defaults)`,
+ );
+}
diff --git a/apps/desktop/src/main/im/shared/orchestrator.ts b/apps/desktop/src/main/im/shared/orchestrator.ts
index b79121a148..6d99d54495 100644
--- a/apps/desktop/src/main/im/shared/orchestrator.ts
+++ b/apps/desktop/src/main/im/shared/orchestrator.ts
@@ -11,7 +11,12 @@
*/
import { createLogger } from '../../logger';
-import { acquirePendingAgentSwitchForDirectSend } from '../../maker-ipc/register';
+import {
+ acquirePendingAgentSwitchForDirectSend,
+ acquirePendingAgentSwitchForImSend,
+ registerSwitchedSessionVendorOptionsResolver,
+} from '../../maker-ipc/register';
+import { createImChannelDefaultRouteSync } from './channelDefaultRouteSync';
import { createImSessionRepo, type ImSessionRepo } from './sessionRepo';
import { createCardBuilders, type ImCardBuilders } from './cardBuilders';
import { createTurnRunner, type ImTurnRunner } from './turnRunner';
@@ -72,9 +77,22 @@ export function createImOrchestrator(adapter: ImChannelAdapter): ImOrchestrator
projectSwitching: adapter.projectSwitching === true,
});
const cards = createCardBuilders(adapter.ui, repo.getDefaultEffortFor);
+ const defaultRouteSync = createImChannelDefaultRouteSync({
+ source: adapter.sessions.source,
+ config: adapter.config,
+ isRouteUsable: (route) => turnRunner.hasAuthForRoute(route),
+ });
const turnRunner = createTurnRunner(adapter, repo, cards, {
- acquirePendingAgentSwitch: acquirePendingAgentSwitchForDirectSend,
+ acquirePendingAgentSwitch: (sessionId, opts) =>
+ opts?.channelOwned
+ ? acquirePendingAgentSwitchForImSend(sessionId, () => defaultRouteSync.syncUnderLock(sessionId))
+ : acquirePendingAgentSwitchForDirectSend(sessionId),
+ channelDefaultRoute: defaultRouteSync,
});
+ // 切换引擎重建会话时补回本渠道的 vendorOptions(bot 专属工具依赖它)。
+ registerSwitchedSessionVendorOptionsResolver((sessionId) =>
+ turnRunner.vendorOptionsForSession(sessionId),
+ );
const slash = createSlashHandlers(adapter, repo, cards, turnRunner);
const attachMessageHandler = createMessageHandler(adapter, slash, turnRunner);
diff --git a/apps/desktop/src/main/im/shared/sessionRepo.ts b/apps/desktop/src/main/im/shared/sessionRepo.ts
index d94a549d95..ffa31023a3 100644
--- a/apps/desktop/src/main/im/shared/sessionRepo.ts
+++ b/apps/desktop/src/main/im/shared/sessionRepo.ts
@@ -32,6 +32,7 @@ import {
resolveImSessionDefaults,
type ResolvedImSessionDefaults,
} from '../defaultSessionSettings';
+import { buildImDefaultRouteRecord } from './channelDefaultRoute';
import { broadcastSessionCreated, broadcastSessionPatched } from './sessionBroadcast';
import type { ImOrchestratorConfig, ImSessionNamespace } from './types';
@@ -73,6 +74,11 @@ export interface ImSessionRow {
* 只读路径按需带出, 建会话路径不填(那时归属由 ns.workspaceKind 决定)。
*/
workspaceKind?: 'project' | 'dialogue' | null;
+ /**
+ * 仅 prepareNewSession 产出的行带: 解析这组默认值时所读渠道设置的指纹。
+ * 建任务 / `/new` 把它连同路由写进 `im_default_route`(跟随记录)。
+ */
+ defaultRouteFingerprint?: string;
}
export interface SessionModelRouteSnapshot {
@@ -426,6 +432,7 @@ export function createImSessionRepo(
status: 'active',
agentKind: toDbAgentKind(row.agentKind),
providerId: row.providerId,
+ imDefaultRoute: defaultRouteRecordFor(row),
source: ns.source,
...ns.extraInsertColumns(botContextId, userId),
createdAt: now,
@@ -552,6 +559,7 @@ export function createImSessionRepo(
fastMode: fresh.fastMode,
agentKind: toDbAgentKind(fresh.agentKind),
providerId: fresh.providerId,
+ imDefaultRoute: defaultRouteRecordFor(fresh),
source: ns.source,
imBotContextId,
imUserId,
@@ -597,9 +605,21 @@ function rowFromDefaults(
sdkSessionId: null,
remoteHostId: null,
providerId: defaults.providerId,
+ defaultRouteFingerprint: defaults.fingerprint,
};
}
+/** 按渠道默认建出 / 重置的行对应的跟随记录; 非默认来源的行返回 null。 */
+function defaultRouteRecordFor(row: ImSessionRow): string | null {
+ if (!row.defaultRouteFingerprint) return null;
+ return buildImDefaultRouteRecord(row.defaultRouteFingerprint, {
+ agentKind: row.agentKind,
+ model: row.model,
+ providerId: row.providerId,
+ effort: row.effort,
+ });
+}
+
// ── sessionId 维度的更新操作(渠道无关, 无需工厂) ─────────────────────────────
/** Bump userSendAt so sidebar (if ever surfaced) sorts IM sessions correctly. */
@@ -662,6 +682,7 @@ export async function resetSessionToDefaults(
providerId: defaults.providerId,
permissionMode: defaults.permissionMode,
fastMode: defaults.fastMode,
+ imDefaultRoute: defaultRouteRecordFor(defaults),
// Personal WeChat exposes a user-selected channel working directory.
// It applies only at the explicit `/new` boundary; existing context is
// never moved silently.
@@ -735,6 +756,9 @@ export async function readModelRouteSnapshot(
* - string → 显式选定该供应商(路由按它走);
* - null → 清除显式选择,回落默认路由。
* 显式传入(含 null)时一并写列,使 IM 选模型与应用内一样能锁定路由源、跨重启 hydrate 仍生效。
+ *
+ * 只写路由列 —— 「脱离跟随」墓碑由调用方在**选择真正落地后**写(PR #5155 review P2):
+ * 本函数也被失败回滚复用, 在这里立碑会让失败的选择永久脱离默认跟随。
*/
export async function updateModelEffort(
sessionId: string,
diff --git a/apps/desktop/src/main/im/shared/slashCommands.ts b/apps/desktop/src/main/im/shared/slashCommands.ts
index 6be5011c15..3f539d5cf7 100644
--- a/apps/desktop/src/main/im/shared/slashCommands.ts
+++ b/apps/desktop/src/main/im/shared/slashCommands.ts
@@ -22,7 +22,7 @@ import {
} from '@cindy/model-providers';
import { createLogger } from '../../logger';
-import { resetSessionToDefaults } from './sessionRepo';
+import { resetImSessionToChannelDefaults } from './channelDefaultRouteSync';
import type { ImSessionRepo } from './sessionRepo';
import type { ImCardBuilders } from './cardBuilders';
import type { ImTurnRunner } from './turnRunner';
@@ -303,7 +303,7 @@ export function createSlashHandlers(
const row =
existing ?? (await repo.createSession(ctx.botContextId, ctx.userId, undefined, prepared));
if (existing) {
- await resetSessionToDefaults(row.id, adapter.config, prepared, adapter.channel);
+ await resetImSessionToChannelDefaults(row.id, adapter.config, prepared, adapter.channel);
}
await turnRunner.disposeOneSession(row.id);
await safeSendText(ctx, ui.slash.new);
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index 47ae52e061..ed3e0f8d7d 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -160,6 +160,8 @@ import {
} from './sessionRepo';
import type { ImCardBuilders } from './cardBuilders';
import type { ImChannelAdapter } from './types';
+import { sameImDefaultRoute, type ImDefaultRoute } from './channelDefaultRoute';
+import type { ImChannelDefaultRouteSync } from './channelDefaultRouteSync';
import {
changeSessionPermissionMode,
type PermissionModeChangeResult,
@@ -271,6 +273,13 @@ interface TurnState {
/** Whether a callback-bound text response has already been reserved. */
chunkedReplyBegun: boolean;
queueMode: 'internal' | 'external';
+ /**
+ * 授权检查通过的「将要运行」路由(渠道默认跟随会切过去的那条; 未跟随则为 null)。
+ * 发送时刻实际路由不是它 = 跟随切换失败被吞、消息会按旧路由发送 —— 必须按实际
+ * 路由补一次授权检查, 否则旧供应商断开时消息进旧路由的发送流程运行时失败,
+ * 而不是给出缺授权提示(PR #5155 review P2)。
+ */
+ followAuthRoute: ImDefaultRoute | null;
terminalPromise: Promise<ImTurnTerminal>;
resolveTerminal: ((terminal: ImTurnTerminal) => void) | null;
}
@@ -526,6 +535,11 @@ export interface ImTurnRunner {
disposeOneSession(sessionId: string): Promise<void>;
/** Get the live Maker Session for a given DB session id, or null. */
getMakerSessionById(sessionId: string): MakerSession | null;
+ /**
+ * 本渠道已接线自有任务的渠道 vendorOptions(切换引擎重建会话时补回);
+ * 未接线 / 接管 / 通知回复任务返回 undefined。
+ */
+ vendorOptionsForSession(sessionId: string): Record<string, unknown> | undefined;
/** Permission choices exposed by the session's concrete Agent implementation. */
getPermissionModes(agentKind: AgentKind): PermissionModeDescriptor[];
changePermissionMode(args: {
@@ -550,9 +564,29 @@ export interface ImTurnRunner {
}): Promise<{ stopped: boolean; droppedQueued: number }>;
}
+/** row 的路由快照 —— 跟随切换的实际落点比对用。 */
+function routeOfRow(
+ row: Pick<ImSessionRow, 'agentKind' | 'model' | 'providerId' | 'effort'>,
+): ImDefaultRoute {
+ return {
+ agentKind: row.agentKind,
+ model: row.model,
+ providerId: row.providerId,
+ effort: row.effort,
+ };
+}
+
export interface ImTurnRunnerDeps {
- /** 锁住 session 并落实 deferred switch;IM 在刷新 live session + send 后 release。 */
- acquirePendingAgentSwitch?: (sessionId: string) => Promise<() => void>;
+ /**
+ * 锁住 session 并落实 deferred switch;IM 在刷新 live session + send 后 release。
+ * `channelOwned` = 本渠道自有任务(非 `/ctr` 接管、非通知回复): 锁内先对齐渠道默认跟随。
+ */
+ acquirePendingAgentSwitch?: (
+ sessionId: string,
+ opts?: { channelOwned?: boolean },
+ ) => Promise<() => void>;
+ /** 渠道默认跟随: 发送前授权检查按真实会跑的路由判断; 未接线的任务接线前先对齐。 */
+ channelDefaultRoute?: Pick<ImChannelDefaultRouteSync, 'previewSwitchTarget' | 'syncBeforeWiring'>;
}
export function createTurnRunner(
@@ -599,6 +633,8 @@ export function createTurnRunner(
* the cache, both spawn a maker session, and the second clobbers the first
* in `sessionStates`. */
const wiringInFlight = new Map<string, Promise<SessionState>>();
+ /** 接线前跟随切换期间, 切换重建会话要用的渠道 vendorOptions(见 vendorOptionsForSession)。 */
+ const coldWiringVendorOptions = new Map<string, Record<string, unknown>>();
/**
* agent switch 主动 close 的旧 Session。只有对象身份和 close reason 都匹配才
* 忽略;同一业务 sessionId 下的用户关闭或新引擎关闭必须照常清缓存。
@@ -778,11 +814,26 @@ export function createTurnRunner(
}
const row = target.row;
const allowedFileRoots = resolveTurnFileRoots(row.workingDir, row.remoteHostId);
+ let followTarget: ImDefaultRoute | null | undefined = null;
if (!target.authChecked) {
- const auth = await checkImRouteAuthDetailed(row, undefined, authCheckDeps());
+ // 渠道默认跟随: 本条消息会在 send 锁内切到新默认时, 按新路由检查授权 ——
+ // 否则旧默认坏掉(如供应商断开)时, 消息会先被「缺授权」挡掉, 永远换不过去。
+ followTarget =
+ !target.attached && !target.notificationReply
+ ? await deps.channelDefaultRoute?.previewSwitchTarget(row.id)
+ : null;
+ const authRow = followTarget
+ ? {
+ ...row,
+ agentKind: followTarget.agentKind,
+ model: followTarget.model,
+ providerId: followTarget.providerId,
+ }
+ : row;
+ const auth = await checkImRouteAuthDetailed(authRow, undefined, authCheckDeps());
if (!auth.ok) {
if (args.queueMode === 'internal') {
- const authStatus = { ...auth, agentKind: row.agentKind, model: row.model };
+ const authStatus = { ...auth, agentKind: authRow.agentKind, model: authRow.model };
const text =
ui.agent.authMissing?.({ ...authStatus, attached: target.attached }) ??
ui.agent.apiKeyMissing;
@@ -871,12 +922,64 @@ export function createTurnRunner(
terminalErrorCode: null,
chunkedReplyBegun: false,
queueMode: args.queueMode,
+ followAuthRoute: followTarget ?? null,
terminalPromise,
resolveTerminal,
};
+ // 未接线的任务(如重启后)要跟随新默认: 接线前先对齐, 不先用可能已坏的旧路由
+ // 起一次进程。只换接线用的路由; `row` 保持入口读到的值(标题等逻辑按它判断,
+ // 跨引擎切换清掉的原生会话 id 不应被当成「新对话」)。
+ let wireTarget = target;
+ if (
+ followTarget &&
+ deps.channelDefaultRoute &&
+ !sessionStates.has(row.id) &&
+ !wiringInFlight.has(row.id) &&
+ !getMaker().getSession(row.id)
+ ) {
+ coldWiringVendorOptions.set(row.id, adapter.buildVendorOptions(userId, target.scopeKey));
+ try {
+ await deps.channelDefaultRoute.syncBeforeWiring(row.id);
+ } finally {
+ coldWiringVendorOptions.delete(row.id);
+ }
+ const refreshed = await repo.peekSessionById(row.id);
+ if (refreshed) {
+ // 跟随切换没生效(失败被吞、保持原路由)时这条消息会按旧路由发送, 而此前的
+ // 授权检查只验过新默认路由 —— 按实际路由补一次, 旧供应商断开时在这里给出
+ // 缺授权提示, 而不是进旧路由的发送流程运行时失败(PR #5155 review P2)。
+ if (!sameImDefaultRoute(routeOfRow(refreshed), followTarget)) {
+ const auth = await checkImRouteAuthDetailed(refreshed, undefined, authCheckDeps());
+ if (!auth.ok) {
+ const authStatus = { ...auth, agentKind: refreshed.agentKind, model: refreshed.model };
+ if (args.queueMode === 'internal') {
+ const text =
+ ui.agent.authMissing?.({ ...authStatus, attached: target.attached }) ??
+ ui.agent.apiKeyMissing;
+ const consumed = (await args.onEarlyReject?.('missing_auth', text)) ?? false;
+ if (!consumed) await replyMissingAuth(userId, authStatus, scopeKey, target.attached);
+ }
+ await discardHandedOverAck(userMessageId, args.ackReactionIdPromise);
+ return { kind: 'rejected', reason: 'missing_auth' };
+ }
+ }
+ wireTarget = {
+ ...target,
+ row: {
+ ...target.row,
+ agentKind: refreshed.agentKind,
+ model: refreshed.model,
+ effort: refreshed.effort,
+ fastMode: refreshed.fastMode,
+ providerId: refreshed.providerId,
+ sdkSessionId: refreshed.sdkSessionId,
+ },
+ };
+ }
+ }
let state: SessionState;
try {
- state = await ensureSessionWired(target, userId);
+ state = await ensureSessionWired(wireTarget, userId);
} catch (err) {
if (isCredentialModeSwitchBusyError(err)) {
if (args.queueMode === 'internal') {
@@ -1089,7 +1192,9 @@ export function createTurnRunner(
};
agentSwitchCloseSuppressed.set(rowId, suppression);
try {
- releaseAgentSwitchLock = await deps.acquirePendingAgentSwitch(rowId);
+ releaseAgentSwitchLock = await deps.acquirePendingAgentSwitch(rowId, {
+ channelOwned: !state.attached && !item.turn.notificationReply,
+ });
} finally {
agentSwitchCloseSuppressed.delete(rowId);
}
@@ -1100,6 +1205,36 @@ export function createTurnRunner(
} else {
await refreshSessionAfterPendingAgentSwitch(state, rowId, userId);
}
+ // 发送时刻的实际路由兜底: 授权检查只验过「将要切到」的新默认路由, 跟随切换
+ // 失败被吞后这条消息会按旧路由发送 —— 按实际路由补一次授权检查, 旧供应商断开
+ // 时在这里给出缺授权提示, 而不是进发送流程运行时失败(PR #5155 review P2)。
+ // 冷路径在接线前已查过一次, 这里兜的是接线后切换才失败 / 热任务的切换失败。
+ const followAuthRoute = item.turn.followAuthRoute;
+ if (followAuthRoute) {
+ const landed = await repo.peekSessionById(rowId);
+ if (landed && !sameImDefaultRoute(routeOfRow(landed), followAuthRoute)) {
+ const auth = await checkImRouteAuthDetailed(landed, undefined, authCheckDeps());
+ if (!auth.ok) {
+ const authStatus = { ...auth, agentKind: landed.agentKind, model: landed.model };
+ if (item.turn.queueMode === 'internal') {
+ const text =
+ ui.agent.authMissing?.({ ...authStatus, attached: state.attached }) ??
+ ui.agent.apiKeyMissing;
+ const consumed = (await item.onEarlyReject?.('missing_auth', text)) ?? false;
+ if (!consumed) await replyMissingAuth(userId, authStatus, item.turn.scopeKey, state.attached);
+ }
+ // 文案已在上面按缺授权发过(外部队列由调用方消费), 这里只走收口。
+ await handleSendPreDispatchFailure(state, userId, {
+ turn: item.turn,
+ source: `${channel}-runner`,
+ reason: 'missing_auth',
+ context: buildSendContext(rowId),
+ onEarlyReject: async () => true,
+ });
+ return { kind: 'rejected', reason: 'missing_auth' };
+ }
+ }
+ }
// session-agent-switch:本路径直发 session.send(不经 makerSendTransaction),
// 交接注入自己接——切换后首条消息若来自 IM 渠道,新引擎同样需要交接上下文
@@ -3743,6 +3878,13 @@ export function createTurnRunner(
disposeAllSessions,
disposeOneSession,
getMakerSessionById,
+ vendorOptionsForSession: (sessionId) => {
+ const cold = coldWiringVendorOptions.get(sessionId);
+ if (cold) return cold;
+ const state = sessionStates.get(sessionId);
+ if (!state || state.preserveSessionConfig) return undefined;
+ return adapter.buildVendorOptions(state.userId, state.scopeKey);
+ },
getPermissionModes: (agentKind) => getMaker().getCapabilities(agentKind).permissionModes,
changePermissionMode: (args) =>
changeSessionPermissionMode({
diff --git a/apps/desktop/src/main/im/telegram/uiText.ts b/apps/desktop/src/main/im/telegram/uiText.ts
index 80d67cf049..33e4f334ff 100644
--- a/apps/desktop/src/main/im/telegram/uiText.ts
+++ b/apps/desktop/src/main/im/telegram/uiText.ts
@@ -62,7 +62,7 @@ export const ui = {
const message = `⚠️ 当前 Telegram 对话使用供应商「${provider}」(${model}),${reason}。`;
return attached
? `${message}\n请在 desktop 的 Settings → 模型供应商中修复认证后,直接继续发送消息。`
- : `${message}\n“新对话配置”会用于新任务;修改后请发送 \`/new\`,再继续聊天。`;
+ : `${message}\n修改“新对话配置”后直接继续发送消息即可;若当前任务单独选过模型,请发送 \`/model\` 重新选择。`;
},
controlInProgress:
'🎮 你 /ctr 还在选择中呢 — 先把上面那张卡片操作完(或点 🚪 退出),再来发别的~',
diff --git a/apps/desktop/src/main/im/wechat/index.ts b/apps/desktop/src/main/im/wechat/index.ts
index df69b9469f..d3ce65bbb7 100644
--- a/apps/desktop/src/main/im/wechat/index.ts
+++ b/apps/desktop/src/main/im/wechat/index.ts
@@ -1,6 +1,6 @@
import type { ImOrchestratorConfig } from '../shared/types';
import { createImOrchestrator } from '../shared/orchestrator';
-import { resetSessionToDefaults } from '../shared/sessionRepo';
+import { resetImSessionToChannelDefaults } from '../shared/channelDefaultRouteSync';
import { buildWechatAdapter } from './adapter';
import type { WechatIM } from './WechatIM';
@@ -11,7 +11,7 @@ export function wireWechatOrchestrator(wechatIm: WechatIM, config: ImOrchestrato
repo: orchestrator.repo,
config,
resetSessionToDefaults: (sessionId, nextConfig, prepared) =>
- resetSessionToDefaults(sessionId, nextConfig, prepared, 'wechat'),
+ resetImSessionToChannelDefaults(sessionId, nextConfig, prepared, 'wechat'),
});
}
diff --git a/apps/desktop/src/main/im/wechat/uiText.ts b/apps/desktop/src/main/im/wechat/uiText.ts
index a5154658d2..a48ebdf40a 100644
--- a/apps/desktop/src/main/im/wechat/uiText.ts
+++ b/apps/desktop/src/main/im/wechat/uiText.ts
@@ -46,7 +46,7 @@ export const ui = {
const message = `⚠️ 当前微信对话使用供应商「${provider}」(${model}),${reason}。`;
return attached
? `${message}\n请在 desktop 的 Settings → 模型供应商中修复认证后,直接继续发送消息。`
- : `${message}\n“新对话配置”只影响新对话;修改后请发送 \`/new\`,再继续聊天。`;
+ : `${message}\n修改“新对话配置”后直接继续发送消息即可;若当前对话单独选过模型,请发送 \`/model\` 重新选择。`;
},
controlInProgress:
'🎮 你 /ctr 还在选择中呢 — 先把上面那张卡片操作完(或点 🚪 退出),再来发别的~',
@@ -73,8 +73,8 @@ export const ui = {
// turnPermissionPolicy 分类:agent(如 Pi)未声明该 capability,任何权限模式
// 都无法提供微信所需的逐条确认 → 换 Agent;已声明的 agent 仅个别模式不可用
// (如 bypassPermissions / acceptEdits) → 换权限模式。
- // 注意:微信渠道的 Agent 配置只在 /new 时应用到现有会话(设置仅影响新对话),
- // 所以「换 Agent」指引必须带 /new,否则用户改完设置重发仍路由到旧 Agent。
+ // 注意:跟随渠道默认的会话在下一条消息就会换到新 Agent, 但单独选过 Agent / 模型
+ // 的会话不跟随设置, 所以「换 Agent」指引仍带 /new, 否则这类会话重发仍路由到旧 Agent。
agentUnsupported:
'⚠️ 当前 Agent 不支持个人微信的逐条权限确认,消息无法启动。\n' +
'请在 desktop 设置里把微信渠道的 Agent 换成 Claude Code 或 Codex,再在微信发送 /new,然后重试。',
diff --git a/apps/desktop/src/main/im/wecom/uiText.ts b/apps/desktop/src/main/im/wecom/uiText.ts
index fb8bc6334a..25f7faad43 100644
--- a/apps/desktop/src/main/im/wecom/uiText.ts
+++ b/apps/desktop/src/main/im/wecom/uiText.ts
@@ -37,7 +37,7 @@ export const ui = {
const message = `⚠️ 当前企业微信对话使用「${provider}」(${model}),${reason}。`;
return attached
? `${message}\n请在 desktop 修复认证后继续发送消息。`
- : `${message}\n修改后请发送 \`/new\` 开始新任务。`;
+ : `${message}\n修改“新对话配置”后直接继续发送消息即可;若当前对话单独选过模型,请发送 \`/new\` 开始新任务。`;
},
controlInProgress: '🎮 接管选择尚未完成,请先处理上一条交互消息。',
credentialBusy: '⏳ 本地 Agent 正在运行,暂时不能切换凭证模式,请稍后重试。',
diff --git a/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts b/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts
index daacb5c874..8fcbf70939 100644
--- a/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts
@@ -112,6 +112,7 @@ function createSearchDb(): Database.Database {
feishu_bot_app_id TEXT,
im_bot_context_id TEXT,
im_user_id TEXT,
+ im_default_route TEXT,
used_project_context INTEGER NOT NULL DEFAULT 0,
codex_history_has_product_prompt INTEGER,
codex_plan_json TEXT,
diff --git a/apps/desktop/src/main/localDb/__tests__/drizzle-proxy-perf.bench.ts b/apps/desktop/src/main/localDb/__tests__/drizzle-proxy-perf.bench.ts
index a998b7d3f0..2dac7daf14 100644
--- a/apps/desktop/src/main/localDb/__tests__/drizzle-proxy-perf.bench.ts
+++ b/apps/desktop/src/main/localDb/__tests__/drizzle-proxy-perf.bench.ts
@@ -60,6 +60,7 @@ const CREATE_TABLES = [
feishu_bot_app_id TEXT,
im_bot_context_id TEXT,
im_user_id TEXT,
+ im_default_route TEXT,
used_project_context INTEGER NOT NULL DEFAULT 0,
codex_history_has_product_prompt INTEGER,
extra_dirs TEXT NOT NULL DEFAULT '[]',
diff --git a/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts b/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts
index 468e44b1e2..8a53aa28cc 100644
--- a/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts
@@ -409,6 +409,7 @@ describe('orcaTeamStore', () => {
feishu_bot_app_id TEXT,
im_bot_context_id TEXT,
im_user_id TEXT,
+ im_default_route TEXT,
used_project_context INTEGER NOT NULL DEFAULT 0,
codex_history_has_product_prompt INTEGER,
codex_plan_json TEXT,
diff --git a/apps/desktop/src/main/localDb/__tests__/workingDirHistoryFilter.test.ts b/apps/desktop/src/main/localDb/__tests__/workingDirHistoryFilter.test.ts
index 3ed96d4c60..87d266a6b7 100644
--- a/apps/desktop/src/main/localDb/__tests__/workingDirHistoryFilter.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/workingDirHistoryFilter.test.ts
@@ -58,6 +58,7 @@ function createLocalDb(): Database.Database {
feishu_bot_app_id TEXT,
im_bot_context_id TEXT,
im_user_id TEXT,
+ im_default_route TEXT,
used_project_context INTEGER NOT NULL DEFAULT 0,
codex_history_has_product_prompt INTEGER,
extra_dirs TEXT NOT NULL DEFAULT '[]',
diff --git a/apps/desktop/src/main/localDb/client/__tests__/drizzleProxy.test.ts b/apps/desktop/src/main/localDb/client/__tests__/drizzleProxy.test.ts
index a4a028d2bc..dc42af68f3 100644
--- a/apps/desktop/src/main/localDb/client/__tests__/drizzleProxy.test.ts
+++ b/apps/desktop/src/main/localDb/client/__tests__/drizzleProxy.test.ts
@@ -48,6 +48,7 @@ const DRIZZLE_PROXY_SCHEMA = [
feishu_bot_app_id TEXT,
im_bot_context_id TEXT,
im_user_id TEXT,
+ im_default_route TEXT,
used_project_context INTEGER NOT NULL DEFAULT 0,
codex_history_has_product_prompt INTEGER,
extra_dirs TEXT NOT NULL DEFAULT '[]',
diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
index 46714050f1..68e0e3f13a 100644
--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
@@ -90,6 +90,7 @@ CREATE TABLE sessions (
source TEXT NOT NULL DEFAULT 'desktop',
im_bot_context_id TEXT,
im_user_id TEXT,
+ im_default_route TEXT,
remote_host_id TEXT,
active_turn_started_at INTEGER,
last_turn_ended_at INTEGER,
@@ -2916,6 +2917,7 @@ describe('db worker tx handlers', () => {
fastMode: false,
agentKind: 'pi',
providerId: 'xai',
+ imDefaultRoute: 'default-route-record',
source: 'telegram',
imBotContextId: 'bot',
imUserId: 'user',
@@ -2926,7 +2928,7 @@ describe('db worker tx handlers', () => {
expect(result).toEqual({ previousStatus: 'active' });
await expect(
client.query(
- `SELECT id, status, im_bot_context_id, im_user_id
+ `SELECT id, status, im_bot_context_id, im_user_id, im_default_route
FROM sessions WHERE id IN ('telegram-old', 'telegram-new') ORDER BY id`,
),
).resolves.toEqual([
@@ -2935,12 +2937,14 @@ describe('db worker tx handlers', () => {
status: 'active',
im_bot_context_id: 'bot',
im_user_id: 'user',
+ im_default_route: 'default-route-record',
},
{
id: 'telegram-old',
status: 'archived',
im_bot_context_id: null,
im_user_id: null,
+ im_default_route: null,
},
]);
await expect(client.query('SELECT * FROM im_bindings')).resolves.toEqual([]);
diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.ts
index 1f96d67984..311d7a826c 100644
--- a/apps/desktop/src/main/localDb/client/tx/types.ts
+++ b/apps/desktop/src/main/localDb/client/tx/types.ts
@@ -970,6 +970,8 @@ export interface ImRotateSessionArgs {
agentKind: string;
source: string;
providerId: string | null;
+ /** 跟随渠道默认的记录(JSON, 见 im/shared/channelDefaultRoute.ts)。 */
+ imDefaultRoute?: string | null;
imBotContextId: string;
imUserId: string;
};
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
index 78b96d821f..3b9e469392 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -285,6 +285,7 @@ function createDb(filename = ':memory:'): void {
codex_plan_json TEXT,
im_bot_context_id TEXT,
im_user_id TEXT,
+ im_default_route TEXT,
active_turn_started_at INTEGER,
active_turn_pid INTEGER,
last_turn_ended_at INTEGER,
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts
index 86e3c718c1..97fedf8972 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts
@@ -110,6 +110,7 @@ function createDb(initialTitle: string): void {
codex_plan_json TEXT,
im_bot_context_id TEXT,
im_user_id TEXT,
+ im_default_route TEXT,
summary TEXT,
provider_id TEXT,
plan_mode_enabled INTEGER NOT NULL DEFAULT 0,
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts
index 5bf5bee866..f3af100fa9 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts
@@ -127,6 +127,7 @@ function createDb(): void {
codex_plan_json TEXT,
im_bot_context_id TEXT,
im_user_id TEXT,
+ im_default_route TEXT,
summary TEXT,
provider_id TEXT,
plan_mode_enabled INTEGER NOT NULL DEFAULT 0,
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
index 8118cbeded..b1338857fa 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
@@ -240,6 +240,7 @@ function createDb(): void {
codex_plan_json TEXT,
im_bot_context_id TEXT,
im_user_id TEXT,
+ im_default_route TEXT,
summary TEXT,
provider_id TEXT,
plan_mode_enabled INTEGER NOT NULL DEFAULT 0,
diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.ts
index 641c5072de..0f075eeba9 100644
--- a/apps/desktop/src/main/localDb/schema.ts
+++ b/apps/desktop/src/main/localDb/schema.ts
@@ -189,6 +189,12 @@ export const sessions = sqliteTable(
*/
imBotContextId: text('im_bot_context_id'),
imUserId: text('im_user_id'),
+ /**
+ * 个人 IM 渠道任务「跟随渠道默认」的记录(JSON,见 im/shared/channelDefaultRoute.ts)。
+ * 渠道建任务 / `/new` / 跟随切换成功时写入;当前路由与记录不一致 = 用户单独改过。
+ * NULL = 无记录(非 IM 任务或本列上线前建的任务)。
+ */
+ imDefaultRoute: text('im_default_route'),
/**
* 本 session 创建时是否注入了 project-context 知识(来自 .cindy/project-knowledge/)。
* 仅在创建瞬间由 main IPC 写入;后续不变。
diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
index 4c9a3ba03a..9c10e26238 100644
--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
@@ -2177,8 +2177,8 @@ function imRotateSession(
`INSERT INTO sessions (
id, title, working_dir, workspace_kind, model, effort, permission_mode,
fast_mode, status, agent_kind, provider_id, source, im_bot_context_id,
- im_user_id, created_at, updated_at, user_send_at
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?, ?, ?, ?, ?, ?)`,
+ im_user_id, im_default_route, created_at, updated_at, user_send_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
);
const retirePrevious = db.prepare(
`UPDATE sessions
@@ -2211,6 +2211,7 @@ function imRotateSession(
expectString(session.source, 'session.source'),
expectString(session.imBotContextId, 'session.imBotContextId'),
expectString(session.imUserId, 'session.imUserId'),
+ nullableString(session.imDefaultRoute),
now,
now,
now,
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
index 6c86d1ce66..470008a370 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
@@ -6,6 +6,7 @@ import {
createPendingAgentSwitchRegistry,
performSessionAgentSwitch,
registerMakerSessionAgentSwitchHandler,
+ settleSystemRouteSwitchIntent,
type AgentSwitchSessionRow,
type MakerSessionAgentSwitchHandlerDeps,
type PendingAgentSwitchIntent,
@@ -167,6 +168,44 @@ describe('same-engine selection at send', () => {
});
describe('performSessionAgentSwitch', () => {
+ it('keeps the config-staged identity through resume-fallback recovery re-entry', async () => {
+ // 渠道默认触发的跨引擎切换若走 resume 回落恢复, 恢复意图必须保留 configStaged ——
+ // 否则被通用路径消费时当成用户选择打上 manual 墓碑, 任务永久脱离跟随
+ // (chatgpt-codex-connector P2, PR #5155)。
+ let row = makeRow();
+ let failFallback = true;
+ const onUserRouteSelectionLanded = vi.fn();
+ const pending = createPendingAgentSwitchRegistry();
+ const { deps } = makeDeps({
+ pendingSwitches: pending,
+ onUserRouteSelectionLanded,
+ getSessionRow: async () => ({ ...row }),
+ findParkedEngineSession: async (_id, kind) =>
+ kind === 'codex' ? { sdkSessionId: 'broken-codex', watermarkCreatedAt: 0, watermarkRowid: 0 } : null,
+ applyAgentSwitchToDb: async (_id, patch) => {
+ row = { ...row, ...patch, providerId: patch.providerId ?? null, sdkSessionId: patch.sdkSessionId ?? null };
+ },
+ insertBoundaryMessage: async () => 'boundary-1',
+ bootstrapSwitchedSession: async () => {
+ throw new Error('resume failed');
+ },
+ applyResumeFallbackAtomically: async () => {
+ if (failFallback) throw new Error('db locked');
+ row.sdkSessionId = null;
+ },
+ });
+ await performSessionAgentSwitch(deps, { ...validParams, configStaged: true });
+ await applyPendingAgentSwitchIfIdle(deps, 's1');
+ expect(pending.get('s1')?.resumeFallbackRecovery).toBeDefined();
+ expect(onUserRouteSelectionLanded).not.toHaveBeenCalled();
+
+ // 恢复尾段重试成功后被消费: 仍然是系统配置切换, 不立碑。
+ failFallback = false;
+ await applyPendingAgentSwitchIfIdle(deps, 's1');
+ expect(onUserRouteSelectionLanded).not.toHaveBeenCalled();
+ expect(pending.get('s1')).toBeUndefined();
+ });
+
it('cycles Claude → Codex → Pi → Claude → Codex and recovers a broken parked thread once', async () => {
let row = makeRow();
const parked = new Map<string, string>();
@@ -1019,3 +1058,138 @@ describe('Phase 2:切回停泊引擎(resume + 增量交接)', () => {
expect(pending).toContain('最早的问题');
});
});
+
+describe('settleSystemRouteSwitchIntent', () => {
+ const intent = { targetAgentKind: 'codex', model: 'gpt-5.5', providerId: 'openai' };
+
+ it('reports applied once the intent is gone', () => {
+ expect(
+ settleSystemRouteSwitchIntent({ stagedIntent: intent, remainingIntent: undefined, sessionIdle: true }),
+ ).toBe('applied');
+ });
+
+ it('keeps a post-commit resume fallback tail staged for the next message', () => {
+ const recovery = { ...intent, resumeFallbackRecovery: { boundaryClientId: null } };
+ expect(
+ settleSystemRouteSwitchIntent({ stagedIntent: recovery, remainingIntent: recovery, sessionIdle: true }),
+ ).toBe('staged');
+ });
+
+ it('treats a busy session or a superseding pick as staged', () => {
+ expect(
+ settleSystemRouteSwitchIntent({ stagedIntent: intent, remainingIntent: intent, sessionIdle: false }),
+ ).toBe('staged');
+ const newer = { ...intent, model: 'gpt-5.6' };
+ expect(
+ settleSystemRouteSwitchIntent({ stagedIntent: intent, remainingIntent: newer, sessionIdle: true }),
+ ).toBe('staged');
+ });
+
+ it('flags a swallowed apply failure so the caller withdraws the intent', () => {
+ // fail-continue 的跨引擎应用失败会把意图原样留着 —— 不能当「任务正忙」上报,
+ // 否则后续消息会反复重试同一个必然失败的切换(PR #5155 review P1)。
+ expect(
+ settleSystemRouteSwitchIntent({ stagedIntent: intent, remainingIntent: intent, sessionIdle: true }),
+ ).toBe('failed');
+ });
+});
+
+describe('landed user route selection', () => {
+ function pickHarness() {
+ const pending = createPendingAgentSwitchRegistry();
+ const landed: string[] = [];
+ const { deps } = makeDeps({
+ pendingSwitches: pending,
+ selectSameAgentModel: async (id, choice, applyNow) => {
+ if (!applyNow) {
+ pending.set(id, choice);
+ return { deferred: true };
+ }
+ return { deferred: false };
+ },
+ onUserRouteSelectionLanded: (id) => {
+ landed.push(id);
+ },
+ });
+ return { deps, landed };
+ }
+
+ it('reports a user pick when it lands — 同值重选也要永久脱离跟随', async () => {
+ const h = pickHarness();
+ // 同引擎 picker 选择(sameAgentSelection)。
+ await performSessionAgentSwitch(h.deps, {
+ sessionId: 's1',
+ targetAgentKind: 'claude-code',
+ model: 'claude-fable-5',
+ providerId: 'xd',
+ });
+ await applyPendingAgentSwitchIfIdle(h.deps, 's1');
+ expect(h.landed).toEqual(['s1']);
+ });
+
+ it('reports a cross-engine user pick but not system-staged or agent selections', async () => {
+ const h = pickHarness();
+ await performSessionAgentSwitch(h.deps, { ...validParams });
+ await applyPendingAgentSwitchIfIdle(h.deps, 's1');
+ expect(h.landed).toEqual(['s1']);
+
+ h.landed.length = 0;
+ // 系统配置对齐(IM 渠道默认跟随 / 伙伴模型对齐)的意图落地不算用户改路由。
+ await performSessionAgentSwitch(h.deps, { ...validParams, configStaged: true });
+ await applyPendingAgentSwitchIfIdle(h.deps, 's1');
+ expect(h.landed).toEqual([]);
+
+ // Agent 自选同样由默认变化覆盖, 不得脱离。
+ await performSessionAgentSwitch(h.deps, {
+ ...validParams,
+ model: 'gpt-6',
+ runtimeSource: 'agent',
+ });
+ await applyPendingAgentSwitchIfIdle(h.deps, 's1');
+ expect(h.landed).toEqual([]);
+ });
+
+ it('keeps the intent when the manual-override marker cannot be persisted', async () => {
+ // 同值重选的唯一证据就是墓碑: 写入失败不得把选择当成功消费 —— 意图保留、
+ // 下一条消息重试(PR #5155 review P2)。
+ const pending = createPendingAgentSwitchRegistry();
+ const { deps } = makeDeps({
+ pendingSwitches: pending,
+ selectSameAgentModel: async (id, choice, applyNow) => {
+ if (!applyNow) {
+ pending.set(id, choice);
+ return { deferred: true };
+ }
+ return { deferred: false };
+ },
+ onUserRouteSelectionLanded: async () => {
+ throw new Error('db closed');
+ },
+ });
+ await performSessionAgentSwitch(deps, {
+ sessionId: 's1',
+ targetAgentKind: 'claude-code',
+ model: 'claude-fable-5',
+ providerId: 'xd',
+ });
+
+ await expect(applyPendingAgentSwitchIfIdle(deps, 's1')).rejects.toThrow('db closed');
+ expect(pending.get('s1')).toBeDefined();
+ });
+
+ it('blocks the send for a cross-engine pick too when the marker cannot be persisted', async () => {
+ // 跨引擎用户意图的 fail-continue 不适用于墓碑失败: 发送继续 + 进程退出会把
+ // 同值重选的唯一证据一起丢掉(PR #5155 review P2)。
+ const pending = createPendingAgentSwitchRegistry();
+ const { deps } = makeDeps({
+ pendingSwitches: pending,
+ onUserRouteSelectionLanded: async () => {
+ throw new Error('db closed');
+ },
+ });
+ await performSessionAgentSwitch(deps, { ...validParams });
+
+ await expect(applyPendingAgentSwitchIfIdle(deps, 's1')).rejects.toThrow('db closed');
+ expect(pending.get('s1')).toBeDefined();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 925dc1ee62..40747c0a56 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -8,6 +8,7 @@ import { handleListDevices, defaultDeps as deviceDirectoryDeps } from '../device
import { getSelfDeviceId, remoteInvoke as invokeBotPeer } from '../device-link/index.js';
import { registerModelFavoritesSync } from './modelFavoritesSync.js';
import { advanceRuntimeRecoveryNotice } from '../im/shared/runtimeRecoveryNotice.js';
+import { markImSessionManualRouteOverride } from '../im/shared/manualRouteOverride.js';
import { configureAppDefaultModelSelection } from './appDefaultModelControl.js';
import type { BuiltinApiKeyBridgeDeps } from '../secrets/builtinApiKeyBridge.js';
import { setBotInvitationWelcomeDispatch } from './botInvitation.js';
@@ -826,6 +827,7 @@ import {
performSessionAgentSwitch,
projectPendingAgentSwitchIntent,
registerMakerSessionAgentSwitchHandler,
+ settleSystemRouteSwitchIntent,
type MakerSessionAgentSwitchHandlerDeps,
} from './sessionAgentSwitchHandler.js';
import { pendingHarnessRuntimeMutation, setSessionRuntimeHarness } from './sessionRuntimeHarnessSelection.js';
@@ -3396,8 +3398,41 @@ function settlePendingCredentialSwitch(sessionId: string, source: string): void
let refreshRemoteCodexMcpOnTurnSettledHolder: ((sessionId: string) => void) | null = null;
let deferredCodexRestartHolder: DeferredCodexRestartService | null = null;
let pendingAgentSwitchApplyHolder:
- ((sessionId: string, signal?: AbortSignal, selection?: ScheduledModelSelection) => Promise<{ release: () => void; selection?: ScheduledModelSelection }>) | null = null;
+ ((
+ sessionId: string,
+ signal?: AbortSignal,
+ selection?: ScheduledModelSelection,
+ beforeApply?: () => Promise<boolean | void>,
+ ) => Promise<{ release: () => void; selection?: ScheduledModelSelection }>) | null = null;
let cancelPendingAgentSwitchHolder: ((sessionId: string) => void) | null = null;
+
+/** 会话级完整路由选择(引擎 + 模型 + 来源 + 档位 + Fast)。 */
+export interface SessionRouteSelection {
+ agentKind: AgentKind;
+ model: string;
+ providerId: string | null;
+ effort: string | null;
+ fastMode: boolean;
+}
+let readPendingAgentSwitchRouteHolder:
+ ((sessionId: string) => PendingAgentSwitchRouteRead | undefined) | null = null;
+let applySessionRouteUnderSendLockHolder:
+ ((sessionId: string, route: SessionRouteSelection | null, currentAgentKind: AgentKind) => Promise<'applied' | 'staged'>) | null = null;
+/**
+ * 切换引擎后重建会话时补回渠道专属 vendorOptions(IM 的会话 id / 对端等)。
+ * 切换建会话只读 DB 行, 不补的话 IM 任务切完引擎会悄悄丢掉 bot 专属工具。
+ */
+const switchedSessionVendorOptionsResolvers = new Set<
+ (sessionId: string) => Record<string, unknown> | undefined
+>();
+
+function resolveSwitchedSessionVendorOptions(sessionId: string): Record<string, unknown> | undefined {
+ for (const resolve of switchedSessionVendorOptionsResolvers) {
+ const options = resolve(sessionId);
+ if (options) return options;
+ }
+ return undefined;
+}
let gitSnapshotCoordinator: GitSnapshotCoordinator | null = null;
const sessionTurnActivityTracker = new SessionTurnActivityTracker();
const reviewRunOwner: ReviewRunOwner = { instanceId: randomUUID(), processId: process.pid };
@@ -3612,6 +3647,65 @@ export function cancelPendingAgentSwitchForSession(sessionId: string): void {
cancelPendingAgentSwitchHolder?.(sessionId);
}
+/**
+ * IM 渠道直发专用: 在同一把 send 锁内, 先跑 `syncUnderLock`(渠道默认跟随对齐),
+ * 再按普通直发语义应用待切换意图。`syncUnderLock` 抛错会让本条消息失败,
+ * 调用方必须自行吞掉非致命错误。
+ */
+export async function acquirePendingAgentSwitchForImSend(
+ sessionId: string,
+ syncUnderLock: () => Promise<boolean | void>,
+): Promise<() => void> {
+ const lease = await pendingAgentSwitchApplyHolder?.(sessionId, undefined, undefined, syncUnderLock);
+ return lease?.release ?? (() => {});
+}
+
+/** 会话上待应用的切换意图目标(用户挑的或系统登记的)读回投影。 */
+export interface PendingAgentSwitchRouteRead extends Omit<SessionRouteSelection, 'fastMode'> {
+ /**
+ * 意图在 pending 注册表的修订号(set / clear 都推进)。与跟随记录里的 pendingRev
+ * 相等 = 同一次登记; 用户重新挑过(哪怕选了同值)会换号, 据此不把用户选择
+ * 误认成系统登记的跟随意图(PR #5155 review P1)。
+ */
+ rev?: number;
+}
+
+/** 会话上待应用的切换意图目标(用户挑的或系统登记的); 无意图返回 undefined。 */
+export function readPendingAgentSwitchRoute(
+ sessionId: string,
+): PendingAgentSwitchRouteRead | undefined {
+ return readPendingAgentSwitchRouteHolder?.(sessionId);
+}
+
+/**
+ * 系统发起的整条路由切换(与伙伴模型对齐同一套): 登记意图, 会话空闲时当场应用;
+ * `route` 传 null = 只应用此前登记、仍待生效的意图。
+ * 调用方必须已持有该会话的 send 锁(acquirePendingAgentSwitchForImSend 的回调内)。
+ * 返回 'staged' = 会话忙(或切换已过 commit 点、恢复尾段待重试), 意图留待安全边界
+ * 应用。应用失败会撤回本次意图后抛错 —— 包括底层按 fail-continue 吞掉的跨引擎
+ * 应用失败: 那种失败留下的意图不能伪装成「任务正忙」让上层反复重试同一个必然
+ * 失败的切换(PR #5155 review P1)。
+ */
+export async function applySessionRouteUnderSendLock(
+ sessionId: string,
+ route: SessionRouteSelection | null,
+ currentAgentKind: AgentKind,
+): Promise<'applied' | 'staged'> {
+ const apply = applySessionRouteUnderSendLockHolder;
+ if (!apply) throw new Error('Session route selection is not initialized');
+ return apply(sessionId, route, currentAgentKind);
+}
+
+/** 注册切换后重建会话用的 vendorOptions 解析器; 返回注销函数。 */
+export function registerSwitchedSessionVendorOptionsResolver(
+ resolve: (sessionId: string) => Record<string, unknown> | undefined,
+): () => void {
+ switchedSessionVendorOptionsResolvers.add(resolve);
+ return () => {
+ switchedSessionVendorOptionsResolvers.delete(resolve);
+ };
+}
+
/**
* 运行时 model/provider 切换的 pending 桥接。
*
@@ -8533,6 +8627,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 重连 / agent 安装 / codex daemon MCP 注入), 否则会以远端
// workingDir 在本机 spawn。
remoteHostId: row.remoteHostId ?? undefined,
+ vendorOptions: resolveSwitchedSessionVendorOptions(sessionId),
});
if (co.extraDirs === undefined) {
try {
@@ -8560,13 +8655,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
effort: (intent.effort ?? null) as SessionRuntimeProfile['effort'],
fastMode: intent.fastMode ?? false,
}, { source: 'user', sessionLockHeld: true, applyingUserSelectionOnSend: applyNow,
- runtimeSource: intent.runtimeSource, assertSelectionCurrent });
+ runtimeSource: intent.runtimeSource, configStaged: intent.configStaged === true,
+ assertSelectionCurrent });
return result;
},
onPendingSwitchChanged: (sessionId, intent) => {
if (intent) recordUserSessionRuntimeMutation(sessionId);
broadcastSessionPatched(sessionId, { agentSwitchIntent: intent });
},
+ // 用户选择落地 → 给 IM 任务打「脱离跟随」标记(同值重选也永久脱离, PR #5155)。
+ onUserRouteSelectionLanded: (sessionId) => markImSessionManualRouteOverride(sessionId),
log,
};
registerMakerSessionAgentSwitchHandler(makerSessionRegistry, agentSwitchDeps);
@@ -8613,17 +8711,28 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
withCloseSuppressed: withRehydrateCloseSuppressed,
log,
});
- pendingAgentSwitchApplyHolder = async (sessionId, signal, selection) => {
+ pendingAgentSwitchApplyHolder = async (sessionId, signal, selection, beforeApply) => {
let stage = 'direct-send:acquire';
+ let deferPendingApply = false;
const release = await acquireSendToSessionLock(sessionId, undefined, () => stage);
try {
stage = 'direct-send:reconcileBotModelRoute';
await reconcileBotModelRoute(sessionId, true);
+ if (beforeApply) {
+ stage = 'direct-send:beforeApply';
+ // 回调(IM 渠道默认跟随对齐)返回 true = 跟随切换被暂缓(会话有后台工作 / 待处理
+ // 交互): 本次不能再走通用意图应用 —— 那里只看 isTurnRunning, 会把刚登记的意图
+ // 立即应用, 跨引擎时关闭并重建仍在承载后台工作的 Session, 绕过跟随自己的安全
+ // 边界(PR #5155 review P1)。意图留待安全边界 / 下一条消息。
+ deferPendingApply = (await beforeApply()) === true;
+ }
stage = 'direct-send:applyPendingAgentSwitchIfIdle';
- await applyPendingAgentSwitchIfIdle(agentSwitchDeps, sessionId, {
- bootstrapAfterSwitch: true,
- signal,
- });
+ if (!deferPendingApply) {
+ await applyPendingAgentSwitchIfIdle(agentSwitchDeps, sessionId, {
+ bootstrapAfterSwitch: true,
+ signal,
+ });
+ }
let resolvedSelection: ScheduledModelSelection | undefined;
if (selection) {
stage = 'direct-send:applyScheduledModelSelection';
@@ -11485,6 +11594,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
type InternalRuntimeSelectionOptions = {
source: 'user' | SessionRuntimeMutationSource;
runtimeSource?: 'agent';
+ /** 系统配置对齐(IM 渠道默认跟随 / 伙伴模型对齐)登记: 落地时不打「脱离跟随」标记。 */
+ configStaged?: boolean;
assertSelectionCurrent?: () => void;
/** Internal calls from the send / switch transaction already own the route lock. */
sessionLockHeld?: boolean;
@@ -11680,6 +11791,36 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return { baseline, effective, control, pendingMutation };
};
+ /**
+ * 系统按配置发起的整条路由选择(伙伴模型对齐 / IM 渠道默认跟随): 跨引擎登记切换
+ * 意图(应用时带交接), 同引擎按用户选择语义登记; 都不在这里抢占运行中的轮次。
+ * 调用方持有 send 锁。
+ */
+ const stageSessionRouteSelection = async (
+ sessionId: string,
+ route: SessionRouteSelection,
+ currentAgentKind: AgentKind,
+ ): Promise<void> => {
+ if (route.agentKind !== currentAgentKind) {
+ await performSessionAgentSwitch(agentSwitchDeps, {
+ sessionId, targetAgentKind: route.agentKind, model: route.model,
+ providerId: route.providerId, effort: route.effort, fastMode: route.fastMode,
+ configStaged: true,
+ });
+ } else {
+ await applyWithVerifiedModelWindow((confirmedContextWindow) =>
+ applySessionRuntimeSelection(sessionId, route.model, route.providerId,
+ { effort: route.effort as SessionRuntimeProfile['effort'], fastMode: route.fastMode,
+ ...(confirmedContextWindow === undefined ? {} : { confirmedContextWindow }) },
+ { source: 'user', deferWhileRunning: true, sessionLockHeld: true, configStaged: true }));
+ }
+ };
+ const isSessionIdleForRouteApply = (sessionId: string): boolean => {
+ const live = maker.getSession(sessionId) as WiredSession | undefined;
+ return !live?.isTurnRunning() && (live?.listBackgroundTasks().length ?? 0) === 0
+ && !hasPendingAgentInteractionForSession(sessionId);
+ };
+
const reconcileBotModelRoute = createBotModelRouteReconciler({
ownerEpoch: captureSessionRuntimeControlOwnerEpoch,
withSessionLock: withSendToSessionLock,
@@ -11733,30 +11874,61 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
};
},
apply: async (sessionId, route, current) => {
- if (route.agentKind !== current.agentKind) {
- await performSessionAgentSwitch(agentSwitchDeps, {
- sessionId, targetAgentKind: route.agentKind, model: route.model,
- providerId: route.providerId, effort: route.effort, fastMode: route.fastMode,
- });
- } else {
- await applyWithVerifiedModelWindow((confirmedContextWindow) =>
- applySessionRuntimeSelection(sessionId, route.model, route.providerId,
- { effort: route.effort as SessionRuntimeProfile['effort'], fastMode: route.fastMode,
- ...(confirmedContextWindow === undefined ? {} : { confirmedContextWindow }) },
- { source: 'user', deferWhileRunning: true, sessionLockHeld: true }));
- }
+ await stageSessionRouteSelection(sessionId, route, current.agentKind);
// Consume the same model/Harness intent as the normal send path. Its
// verified window protection and history handoff also apply here; a Bot
// settings save need not wait for a second user message. Busy runtimes
// retain their intent for the existing safe-boundary coordinator.
- const live = maker.getSession(sessionId) as WiredSession | undefined;
- if (!live?.isTurnRunning() && (live?.listBackgroundTasks().length ?? 0) === 0
- && !hasPendingAgentInteractionForSession(sessionId)) {
+ if (isSessionIdleForRouteApply(sessionId)) {
await applyPendingAgentSwitchIfIdle(agentSwitchDeps, sessionId, { bootstrapAfterSwitch: true });
}
},
});
+ readPendingAgentSwitchRouteHolder = (sessionId) => {
+ const intent = agentSwitchPending.get(sessionId);
+ return intent
+ ? {
+ agentKind: intent.targetAgentKind,
+ model: intent.model,
+ providerId: intent.providerId ?? null,
+ effort: intent.effort ?? null,
+ rev: agentSwitchPending.revision?.(sessionId),
+ }
+ : undefined;
+ };
+ applySessionRouteUnderSendLockHolder = async (sessionId, route, currentAgentKind) => {
+ // route=null: 只应用此前已登记(且仍在)的意图。
+ let staged = agentSwitchPending.get(sessionId);
+ try {
+ if (route) {
+ await stageSessionRouteSelection(sessionId, route, currentAgentKind);
+ // 登记时系统可能改道来源; 按登记后的意图对象认「自己的」, 不按字段比较。
+ staged = agentSwitchPending.get(sessionId);
+ }
+ if (!staged) return 'applied';
+ if (!isSessionIdleForRouteApply(sessionId)) return 'staged';
+ await applyPendingAgentSwitchIfIdle(agentSwitchDeps, sessionId, { bootstrapAfterSwitch: true });
+ } catch (error) {
+ // 系统发起的切换失败不能卡住用户这条消息, 也不能留一个会在下次发送时反复失败的意图。
+ if (staged && agentSwitchPending.get(sessionId) === staged) cancelPendingAgentSwitchHolder?.(sessionId);
+ throw error;
+ }
+ const settle = settleSystemRouteSwitchIntent({
+ stagedIntent: staged,
+ remainingIntent: agentSwitchPending.get(sessionId),
+ sessionIdle: isSessionIdleForRouteApply(sessionId),
+ });
+ if (settle === 'failed') {
+ // 应用没抛错但也没生效: 跨引擎意图的应用失败被底层按 fail-continue 吞掉、
+ // 意图原样留着。不能当「任务正忙」上报, 否则上层每条消息都会重试同一个必然
+ // 失败的切换; 撤回意图、报错让上层保持原路由(PR #5155 review P1)。
+ cancelPendingAgentSwitchHolder?.(sessionId);
+ throw new Error('session route switch did not apply; pending intent withdrawn');
+ }
+ return settle;
+ };
+
configureBotRuntimeEpochRefreshRequest((sessionId, reason) => {
return (async () => {
const refresh = (live: WiredSession) => {
@@ -16593,9 +16765,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
model: catalogModel,
effort: atomicSelection.effort,
fastMode: atomicSelection.fastMode,
+ // 配置跟随(IM 渠道默认跟随 / 伙伴模型对齐)带的是**任务已有的**档位/Fast
+ // (Fast 根本不在渠道默认里), 不是用户对目标模型的显式能力选择 —— 目标模型
+ // 不支持时应收敛而不是拒, 否则任务会在每条消息上反复失败、永远跟不过去
+ // (PR #5155 review P2)。用户 picker 选择仍按显式校验。
effortExplicit:
- internalOptions.source === 'user' || internalOptions.effortExplicit === true,
- fastExplicit: internalOptions.source === 'user' || internalOptions.fastExplicit === true,
+ (internalOptions.source === 'user' && internalOptions.configStaged !== true) ||
+ internalOptions.effortExplicit === true,
+ fastExplicit:
+ (internalOptions.source === 'user' && internalOptions.configStaged !== true) ||
+ internalOptions.fastExplicit === true,
allowFixedEffortPlaceholder: internalOptions.source === 'user',
});
if (!axes.ok && axes.reason === 'effort-unavailable') {
@@ -16621,6 +16800,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
clearPendingCredentialSwitchForSession(sessionId, { wake: false });
const intent = {
...(internalOptions.runtimeSource ? { runtimeSource: internalOptions.runtimeSource } : {}),
+ ...(internalOptions.configStaged === true ? { configStaged: true } : {}),
sameAgentSelection: true,
targetAgentKind: dbToMakerAgentKind(runtimeStatus.agentKind),
model,
diff --git a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
index 6cf2190d75..8c90780553 100644
--- a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
@@ -212,6 +212,13 @@ export interface MakerSessionAgentSwitchHandlerDeps {
sessionId: string,
intent: PublicAgentSwitchIntent | null,
): void;
+ /**
+ * 用户选择的路由落地(应用成功)后回调 —— 供 IM 侧给任务打「脱离跟随」标记:
+ * 「单独改过」按选择行为判定, 同值重选也永久脱离跟随(greptile P1 补充, PR #5155)。
+ * 系统配置对齐(configStaged)与 Agent 自选不触发。**失败会抛错**: 墓碑写不进去时
+ * 意图保留、下一条消息重试, 不把用户选择当成功消费。
+ */
+ onUserRouteSelectionLanded?(sessionId: string): void | Promise<void>;
log: {
info(message: string, fields?: Record<string, unknown>): void;
warn(message: string, fields?: Record<string, unknown>): void;
@@ -245,6 +252,11 @@ export interface SessionAgentSwitchResult {
export interface PendingAgentSwitchIntent {
/** Agent-requested complete selection, exposed by the runtime control query. */
runtimeSource?: 'agent';
+ /**
+ * 系统配置对齐(IM 渠道默认跟随 / 伙伴模型对齐)登记的意图 —— 不是用户选择,
+ * 落地时不给任务打「脱离跟随」标记。用户 picker 选择不带此标(PR #5155)。
+ */
+ configStaged?: boolean;
/** SET_MODEL intent: apply the route without a cross-engine handoff. */
sameAgentSelection?: boolean;
targetAgentKind: AgentKind;
@@ -371,6 +383,8 @@ export async function performSessionAgentSwitch(
/** Abort signal for direct scheduler/IM sends; checked at side-effect boundaries. */
signal?: AbortSignal;
runtimeSource?: 'agent';
+ /** 系统配置对齐(IM 渠道默认跟随 / 伙伴模型对齐)登记: 落地时不打「脱离跟随」标记。 */
+ configStaged?: boolean;
/** Recheck caller CAS after asynchronous validation, before staging any intent. */
assertSelectionCurrent?: () => void;
},
@@ -444,6 +458,7 @@ export async function performSessionAgentSwitch(
...(typeof params.fastMode === 'boolean' ? { fastMode: params.fastMode } : {}),
sameAgentSelection: true,
...(params.runtimeSource ? { runtimeSource: params.runtimeSource } : {}),
+ ...(params.configStaged === true ? { configStaged: true } : {}),
}, false, params.assertSelectionCurrent);
return {
switched: false,
@@ -496,6 +511,7 @@ export async function performSessionAgentSwitch(
if (!params.applyNow && deps.pendingSwitches) {
const intent: PendingAgentSwitchIntent = {
...(params.runtimeSource ? { runtimeSource: params.runtimeSource } : {}),
+ ...(params.configStaged === true ? { configStaged: true } : {}),
targetAgentKind,
model,
providerId: normalizedProviderId,
@@ -650,6 +666,7 @@ export async function performSessionAgentSwitch(
// 下一条消息先重试原子恢复尾段,而不是带半状态继续 lazy-create。
deps.pendingSwitches?.set(sessionId, {
...(params.runtimeSource ? { runtimeSource: params.runtimeSource } : {}),
+ ...(params.configStaged === true ? { configStaged: true } : {}),
targetAgentKind,
model,
providerId: normalizedProviderId,
@@ -674,6 +691,7 @@ export async function performSessionAgentSwitch(
// 避免只清 sdk id 后 DB pending 与实际注入内容分叉。
deps.pendingSwitches?.set(sessionId, {
...(params.runtimeSource ? { runtimeSource: params.runtimeSource } : {}),
+ ...(params.configStaged === true ? { configStaged: true } : {}),
targetAgentKind,
model,
providerId: normalizedProviderId,
@@ -751,8 +769,73 @@ export async function performSessionAgentSwitch(
* 保留原有失败后继续发送的行为。resume 回落事务
* 已进入 commit point 后若失败,则只重试其原子恢复尾段。
*/
+/** 墓碑写失败: 一律阻止发送并保留可重试状态 —— 不适用跨引擎的 fail-continue(PR #5155 review P2)。 */
+export class UserRouteSelectionMarkerError extends Error {
+ readonly cause: unknown;
+
+ constructor(cause: unknown) {
+ super(cause instanceof Error ? cause.message : String(cause));
+ this.name = 'UserRouteSelectionMarkerError';
+ this.cause = cause;
+ }
+}
+
+/**
+ * 用户选择落地 → 给任务打「脱离跟随」标记。只认用户选择: 系统配置对齐
+ * (configStaged)与 Agent 自选都由默认变化覆盖, 不得永久脱离。
+ *
+ * **先立碑再清意图**: 同值重选的唯一证据就是这份墓碑, 写入必须等成功 —— 失败抛错
+ * 让意图保留、下一条消息重试, 不得把选择当成功消费(PR #5155 review P2)。
+ */
+async function noteLandedUserRouteSelection(
+ deps: MakerSessionAgentSwitchHandlerDeps,
+ sessionId: string,
+ intent: PendingAgentSwitchIntent,
+): Promise<void> {
+ if (intent.configStaged === true || intent.runtimeSource === 'agent') return;
+ try {
+ await deps.onUserRouteSelectionLanded?.(sessionId);
+ } catch (err) {
+ deps.log.warn('failed to record landed user route selection', {
+ sessionId,
+ err: err instanceof Error ? err.message : String(err),
+ });
+ // 保留可重试状态: 切换事务内部的同引擎 no-op 收口可能已把意图清掉, 重新登记,
+ // 下一条消息重试立碑 —— 否则进程一退, 在世证据与落点双双丢失(PR #5155 review P2)。
+ if (!deps.pendingSwitches?.get(sessionId)) deps.pendingSwitches?.set(sessionId, intent);
+ throw new UserRouteSelectionMarkerError(err);
+ }
+}
+
const pendingAgentSwitchApplyInFlight = new Map<string, Promise<void>>();
+/**
+ * 系统路由切换(`applySessionRouteUnderSendLock`)应用后的意图收口裁决。
+ *
+ * `applyPendingAgentSwitchIfIdle` 对跨引擎意图是 fail-continue: 应用失败只记日志、
+ * 意图原样保留、不抛错(上一条语义注释)。调用方若把「意图还在」一律当「任务正忙」,
+ * 后续消息会反复重试同一个必然失败的切换 —— 必须区分「忙 / 恢复尾段待重试」与
+ * 「应用失败被吞」, 后者要撤回意图并报错(PR #5155 review P1)。
+ */
+export function settleSystemRouteSwitchIntent(input: {
+ /** 本次要应用的意图(登记后读回)。 */
+ stagedIntent: unknown;
+ /** 应用尝试之后仍在登记的意图。 */
+ remainingIntent: unknown;
+ /** 应用尝试之后会话是否空闲(不忙 = 意图没被真的推迟, 而是没生效)。 */
+ sessionIdle: boolean;
+}): 'applied' | 'staged' | 'failed' {
+ const { stagedIntent, remainingIntent, sessionIdle } = input;
+ if (!remainingIntent) return 'applied';
+ // resume 回落尾段待重试 = 切换已过 commit 点, 保留意图是对的, 下一条消息续跑。
+ if ((remainingIntent as { resumeFallbackRecovery?: unknown } | null)?.resumeFallbackRecovery) {
+ return 'staged';
+ }
+ // 意图被更晚的选择超车, 或应用瞬间会话又忙起来了: 留给各自的收口, 按待生效处理。
+ if (remainingIntent !== stagedIntent || !sessionIdle) return 'staged';
+ return 'failed';
+}
+
export function applyPendingAgentSwitchIfIdle(
deps: MakerSessionAgentSwitchHandlerDeps,
sessionId: string,
@@ -777,6 +860,7 @@ export function applyPendingAgentSwitchIfIdle(
if (result.deferred || result.superseded) {
throw new Error('model selection could not be applied before send');
}
+ await noteLandedUserRouteSelection(deps, sessionId, intent);
if (deps.pendingSwitches?.get(sessionId) === intent) {
deps.pendingSwitches.clear(sessionId);
deps.onPendingSwitchChanged?.(sessionId, null);
@@ -804,6 +888,7 @@ export function applyPendingAgentSwitchIfIdle(
recovery.boundaryContent,
);
deps.setPendingHandoff(sessionId, recovery.handoff, recoveryHandoffGeneration);
+ await noteLandedUserRouteSelection(deps, sessionId, intent);
if (deps.pendingSwitches?.get(sessionId) === intent) {
deps.pendingSwitches.clear(sessionId);
deps.onPendingSwitchChanged?.(sessionId, null);
@@ -814,6 +899,10 @@ export function applyPendingAgentSwitchIfIdle(
sessionId,
targetAgentKind: intent.targetAgentKind,
runtimeSource: intent.runtimeSource,
+ // 系统配置对齐的身份必须随重入传递: resume 回落的恢复意图丢了它, 就会被
+ // 当成用户选择打上 manual 墓碑, 任务永久脱离跟随(chatgpt-codex-connector P2,
+ // PR #5155)。
+ configStaged: intent.configStaged,
model: intent.model,
providerId: intent.providerId,
effort: intent.effort,
@@ -829,9 +918,16 @@ export function applyPendingAgentSwitchIfIdle(
throw new Error('Harness switch recovery is pending; retry the send after recovery');
}
// CAS 语义:执行期间用户可能又选了另一个目标,不能把新意图一起清掉。
- if (!result.retryPending && deps.pendingSwitches?.get(sessionId) === intent) {
- deps.pendingSwitches.clear(sessionId);
- deps.onPendingSwitchChanged?.(sessionId, null);
+ if (!result.retryPending) {
+ // 同引擎 CAS 超车(sameEngineSuperseded)= 这次选择没落地, 不立碑。
+ if (result.sameEngineSuperseded !== true) {
+ await noteLandedUserRouteSelection(deps, sessionId, intent);
+ }
+ // CAS 语义:执行期间用户可能又选了另一个目标,不能把新意图一起清掉。
+ if (deps.pendingSwitches?.get(sessionId) === intent) {
+ deps.pendingSwitches.clear(sessionId);
+ deps.onPendingSwitchChanged?.(sessionId, null);
+ }
}
// Once the switch has committed, the intent has been consumed even if
// cancellation arrived during the final bootstrap step. The caller's
@@ -845,7 +941,15 @@ export function applyPendingAgentSwitchIfIdle(
err: err instanceof Error ? err.message : String(err),
});
// Never send on the old model after the user's selected route failed preparation.
- if (intent.sameAgentSelection || intent.runtimeSource === 'agent') throw err;
+ // 墓碑写失败同理: 跨引擎的 fail-continue 也必须挡住 —— 发送继续 + 进程退出会把
+ // 同值重选的唯一证据一起丢掉(PR #5155 review P2)。
+ if (
+ err instanceof UserRouteSelectionMarkerError ||
+ intent.sameAgentSelection ||
+ intent.runtimeSource === 'agent'
+ ) {
+ throw err;
+ }
}
})().finally(() => {
if (pendingAgentSwitchApplyInFlight.get(sessionId) === run) {
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index fd96d89845..722702466f 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -4310,13 +4310,13 @@
"defaults": {
"title": "New Conversation Configuration",
"channelDescriptions": {
- "feishu": "New Feishu conversations use this Agent and model. Send /new in an existing DM to apply it.",
+ "feishu": "New Feishu conversations use this Agent and model. Existing sessions switch over on their next message unless their model was changed manually.",
"slack": "New Slack threads use this Agent and model.",
- "discord": "New Discord conversations use this Agent and model. Send /new in an existing DM to apply it.",
- "wechat": "New WeChat conversations use this Agent, model, and permission mode. Send /new in an existing chat to apply them.",
- "telegram": "New Telegram conversations use this Agent and model. Send /new in an existing conversation to apply it.",
- "dingtalk": "New DingTalk conversations use this Agent and model. Send /new in an existing conversation to apply it.",
- "wecom": "New WeCom conversations use this Agent, model, and permission mode. Send /new in an existing chat to apply them."
+ "discord": "New Discord conversations use this Agent and model. Existing sessions switch over on their next message unless their model was changed manually.",
+ "wechat": "New WeChat conversations use this Agent, model, and permission mode. Existing sessions switch to this Agent and model on their next message unless their model was changed manually; send /new in an existing chat to apply the permission mode.",
+ "telegram": "New Telegram conversations use this Agent and model. Existing sessions switch over on their next message unless their model was changed manually.",
+ "dingtalk": "New DingTalk conversations use this Agent and model. Existing sessions switch over on their next message unless their model was changed manually.",
+ "wecom": "New WeCom conversations use this Agent, model, and permission mode. Existing sessions switch to this Agent and model on their next message unless their model was changed manually; send /new in an existing chat to apply the permission mode."
},
"agentLabel": "Agent",
"agentUnsupportedOnChannelHint": "{{agent}} Agent does not support per-message permission confirmations on this channel; messages cannot be processed. Switch to Claude Code or Codex.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 93d03f7b69..1d31c99843 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -4309,13 +4309,13 @@
"defaults": {
"title": "新規会話設定",
"channelDescriptions": {
- "feishu": "Feishu の新規会話では、この Agent とモデルを使用します。既存の DM には /new で適用します。",
+ "feishu": "Feishu の新規会話では、この Agent とモデルを使用します。モデルを個別に変更していない既存のセッションは、次のメッセージを受信したときに切り替わります。",
"slack": "Slack の新しいスレッドでは、この Agent とモデルを使用します。",
- "discord": "Discord の新規会話では、この Agent とモデルを使用します。既存の DM には /new で適用します。",
- "wechat": "WeChat の新規会話では、この Agent・モデル・権限モードを使用します。既存のチャットには /new で適用します。",
- "telegram": "Telegram の新規会話では、この Agent とモデルを使用します。既存の会話には /new で適用します。",
- "dingtalk": "DingTalk の新規会話では、この Agent とモデルを使用します。既存の会話には /new で適用します。",
- "wecom": "WeCom の新規会話では、この Agent・モデル・権限モードを使用します。既存のチャットには /new で適用します。"
+ "discord": "Discord の新規会話では、この Agent とモデルを使用します。モデルを個別に変更していない既存のセッションは、次のメッセージを受信したときに切り替わります。",
+ "wechat": "WeChat の新規会話では、この Agent・モデル・権限モードを使用します。モデルを個別に変更していない既存のセッションは、次のメッセージを受信したときにこの Agent とモデルに切り替わります。権限モードは既存のチャットに /new を送信すると適用されます。",
+ "telegram": "Telegram の新規会話では、この Agent とモデルを使用します。モデルを個別に変更していない既存のセッションは、次のメッセージを受信したときに切り替わります。",
+ "dingtalk": "DingTalk の新規会話では、この Agent とモデルを使用します。モデルを個別に変更していない既存のセッションは、次のメッセージを受信したときに切り替わります。",
+ "wecom": "WeCom の新規会話では、この Agent・モデル・権限モードを使用します。モデルを個別に変更していない既存のセッションは、次のメッセージを受信したときにこの Agent とモデルに切り替わります。権限モードは既存のチャットに /new を送信すると適用されます。"
},
"agentLabel": "Agent",
"agentUnsupportedOnChannelHint": "{{agent}} Agent はこのチャンネルでメッセージごとの権限確認に対応していないため、メッセージを処理できません。Claude Code または Codex に切り替えてください。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 03434c508c..5c68e2340d 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -4309,13 +4309,13 @@
"defaults": {
"title": "새 대화 설정",
"channelDescriptions": {
- "feishu": "새 Feishu 대화는 이 Agent와 모델을 사용합니다. 기존 DM에는 /new를 보내 적용하세요.",
+ "feishu": "새 Feishu 대화는 이 Agent와 모델을 사용합니다. 모델을 따로 바꾸지 않은 기존 세션은 다음 메시지를 받을 때 전환됩니다.",
"slack": "새 Slack 스레드는 이 Agent와 모델을 사용합니다.",
- "discord": "새 Discord 대화는 이 Agent와 모델을 사용합니다. 기존 DM에는 /new를 보내 적용하세요.",
- "wechat": "새 WeChat 대화는 이 Agent, 모델, 권한 모드를 사용합니다. 기존 채팅에는 /new를 보내 적용하세요.",
- "telegram": "새 Telegram 대화는 이 Agent와 모델을 사용합니다. 기존 대화에는 /new를 보내 적용하세요.",
- "dingtalk": "새 DingTalk 대화는 이 Agent와 모델을 사용합니다. 기존 대화에는 /new를 보내 적용하세요.",
- "wecom": "새 WeCom 대화는 이 Agent, 모델, 권한 모드를 사용합니다. 기존 채팅에는 /new를 보내 적용하세요."
+ "discord": "새 Discord 대화는 이 Agent와 모델을 사용합니다. 모델을 따로 바꾸지 않은 기존 세션은 다음 메시지를 받을 때 전환됩니다.",
+ "wechat": "새 WeChat 대화는 이 Agent, 모델, 권한 모드를 사용합니다. 모델을 따로 바꾸지 않은 기존 세션은 다음 메시지를 받을 때 이 Agent와 모델로 전환되며, 권한 모드는 기존 채팅에 /new를 보내 적용하세요.",
+ "telegram": "새 Telegram 대화는 이 Agent와 모델을 사용합니다. 모델을 따로 바꾸지 않은 기존 세션은 다음 메시지를 받을 때 전환됩니다.",
+ "dingtalk": "새 DingTalk 대화는 이 Agent와 모델을 사용합니다. 모델을 따로 바꾸지 않은 기존 세션은 다음 메시지를 받을 때 전환됩니다.",
+ "wecom": "새 WeCom 대화는 이 Agent, 모델, 권한 모드를 사용합니다. 모델을 따로 바꾸지 않은 기존 세션은 다음 메시지를 받을 때 이 Agent와 모델로 전환되며, 권한 모드는 기존 채팅에 /new를 보내 적용하세요."
},
"agentLabel": "Agent",
"agentUnsupportedOnChannelHint": "{{agent}} Agent는 이 채널에서 메시지별 권한 확인을 지원하지 않아 메시지를 처리할 수 없습니다. Claude Code 또는 Codex로 전환하세요.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 9a19d7770f..d98ec5e1d9 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -4309,13 +4309,13 @@
"defaults": {
"title": "新对话配置",
"channelDescriptions": {
- "feishu": "飞书新对话会使用这组 Agent 和模型;已有私聊发送 /new 后应用。",
+ "feishu": "飞书新对话会使用这组 Agent 和模型;已有任务若没单独改过模型,会在收到下一条消息时切换过来。",
"slack": "Slack 新 thread 会使用这组 Agent 和模型。",
- "discord": "Discord 新对话会使用这组 Agent 和模型;已有私聊发送 /new 后应用。",
- "wechat": "微信新对话会使用这组 Agent、模型和权限模式;已有私聊发送 /new 后应用。",
- "telegram": "Telegram 新对话会使用这组 Agent 和模型;已有对话发送 /new 后应用。",
- "dingtalk": "钉钉新对话会使用这组 Agent 和模型;已有对话发送 /new 后应用。",
- "wecom": "企业微信新对话会使用这组 Agent、模型和权限模式;已有对话发送 /new 后应用。"
+ "discord": "Discord 新对话会使用这组 Agent 和模型;已有任务若没单独改过模型,会在收到下一条消息时切换过来。",
+ "wechat": "微信新对话会使用这组 Agent、模型和权限模式;已有任务若没单独改过模型,会在收到下一条消息时换用这组 Agent 和模型,权限模式仍在已有私聊发送 /new 后应用。",
+ "telegram": "Telegram 新对话会使用这组 Agent 和模型;已有任务若没单独改过模型,会在收到下一条消息时切换过来。",
+ "dingtalk": "钉钉新对话会使用这组 Agent 和模型;已有任务若没单独改过模型,会在收到下一条消息时切换过来。",
+ "wecom": "企业微信新对话会使用这组 Agent、模型和权限模式;已有任务若没单独改过模型,会在收到下一条消息时换用这组 Agent 和模型,权限模式仍在已有对话发送 /new 后应用。"
},
"agentLabel": "Agent",
"agentUnsupportedOnChannelHint": "{{agent}} Agent 不支持此渠道的逐条权限确认,消息将无法处理。请改用 Claude Code 或 Codex。",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index c0562345bb..556209062e 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -4309,13 +4309,13 @@
"defaults": {
"title": "新對話配置",
"channelDescriptions": {
- "feishu": "飛書新對話會使用這組 Agent 和模型;已有私聊傳送 /new 後應用。",
+ "feishu": "飛書新對話會使用這組 Agent 和模型;已有任務若沒有單獨改過模型,會在收到下一則訊息時切換過來。",
"slack": "Slack 新 thread 會使用這組 Agent 和模型。",
- "discord": "Discord 新對話會使用這組 Agent 和模型;已有私聊傳送 /new 後應用。",
- "wechat": "微信新對話會使用這組 Agent、模型和權限模式;已有私聊傳送 /new 後應用。",
- "telegram": "Telegram 新對話會使用這組 Agent 和模型;已有對話傳送 /new 後應用。",
- "dingtalk": "釘釘新對話會使用這組 Agent 和模型;已有對話傳送 /new 後應用。",
- "wecom": "企業微信新對話會使用這組 Agent、模型和權限模式;已有對話傳送 /new 後應用。"
+ "discord": "Discord 新對話會使用這組 Agent 和模型;已有任務若沒有單獨改過模型,會在收到下一則訊息時切換過來。",
+ "wechat": "微信新對話會使用這組 Agent、模型和權限模式;已有任務若沒有單獨改過模型,會在收到下一則訊息時換用這組 Agent 和模型,權限模式仍在已有私聊傳送 /new 後應用。",
+ "telegram": "Telegram 新對話會使用這組 Agent 和模型;已有任務若沒有單獨改過模型,會在收到下一則訊息時切換過來。",
+ "dingtalk": "釘釘新對話會使用這組 Agent 和模型;已有任務若沒有單獨改過模型,會在收到下一則訊息時切換過來。",
+ "wecom": "企業微信新對話會使用這組 Agent、模型和權限模式;已有任務若沒有單獨改過模型,會在收到下一則訊息時換用這組 Agent 和模型,權限模式仍在已有對話傳送 /new 後應用。"
},
"agentLabel": "Agent",
"agentUnsupportedOnChannelHint": "{{agent}} Agent 不支援此渠道的逐條權限確認,訊息將無法處理。請改用 Claude Code 或 Codex。",
diff --git a/docs/product-rules/model-selector-unified.md b/docs/product-rules/model-selector-unified.md
index a08dddbeea..74de99df01 100644
--- a/docs/product-rules/model-selector-unified.md
+++ b/docs/product-rules/model-selector-unified.md
@@ -192,6 +192,8 @@
设置类入口统一复用 ModelSelector 面板。自动化、IM 默认、Hook 工作目录、插件快问快答和 Worker 支持保存 Harness 的入口,必须通过 `onUnifiedSelect` 一次提交 Harness、来源、模型及该入口支持的配置,删除重复的 Harness 控件。只存模型或有意固定 Harness 的专用入口保留其契约限制;IM 默认和 Hook 工作目录不存 Fast,不展示 Fast 开关。
+个人 IM 渠道的 IM 默认同样只在保存时更新配置:该渠道仍跟随默认(未被 `/model`、桌面或手机单独改过路由)的已有任务,在收到下一条渠道消息时经现有任务切换流程换到新默认,目标正忙时顺延;单独改过的任务不动,权限档不跟随。规则见 [telegram-bot-parity](telegram-bot-parity.md) 的 `/new` 不变量一节。
+
绑定已有任务的自动化在保存时只更新自动化配置,下次触发时才通过现有任务切换流程应用完整选择;目标正忙时顺延,不能抢占当前轮次。新增的 `modelAgentKind` 标识显式 Harness 选择;旧记录不补默认值,继续跟随绑定任务的 Harness。选择“跟随”会清除整套显式覆盖,切换新建/绑定模式往返时保留用户已选配置。
项目自动化的 `schedules.json` 同样保存可选的 `modelAgentKind`,导出、加载与配置同步均保留该标记;删除标记时清除数据库中的覆盖,已有绑定任务不丢失。旧版 `version: 1` 文件无需补字段。自动触发前按实际来源、Harness 和模型的当前目录拷贝补齐或收敛 effort,并清除已不受支持的 Fast;仍有效的用户选择保持不变。
diff --git a/docs/product-rules/telegram-bot-parity.md b/docs/product-rules/telegram-bot-parity.md
index eee633d8c8..f134c88a17 100644
--- a/docs/product-rules/telegram-bot-parity.md
+++ b/docs/product-rules/telegram-bot-parity.md
@@ -109,6 +109,13 @@ Cindy 有两个 Telegram bot,用户看到的是同一个产品:
任务列表,随后消息路由到这个新任务;旧任务保留为历史,不得复用原任务 ID、只清 SDK
上下文,也不得拖到下一条普通消息才落任务。新任务的 agent、模型、来源、思考强度和权限档
均在执行 `/new` 时从各自入口的当前默认配置重新解析;当前项目目录作为 lane 偏好保留。
+个人 bot(与飞书等其它个人 IM 渠道同一套)另有「跟随渠道默认」:已有任务只要没被 `/model`、
+桌面或手机单独改过路由,渠道默认的 Agent/模型/来源/思考强度一改,就在收到下一条消息时
+切到新默认(跨引擎带交接,运行中的轮次不被打断),不必 `/new`;权限档不跟随,仍在 `/new`
+时应用。判定按状态(建任务/`/new`/跟随切换时写入的 `sessions.im_default_route` 记录),
+见 `im/shared/channelDefaultRoute.ts`。切换只动路由四件套,任务单独开过的 Fast 保持不变;
+「单独改过」按选择行为判定而非取值相等——单独挑的恰与新默认相同也算改过,此后不再跟随。
+官方 bot 不受影响。
桌面 IM 默认配置与目录偏好统一使用标准模型选择器,一次保存 Harness、来源、模型和思考强度;不额外展示独立 Harness 控件,不展示无法保存的 Fast。两侧的配置归属与权限规则保持各自既有契约。
两侧的成功提示、帮助与命令菜单都必须按这个真实结果称为「新任务」,不得沿用旧的
「新对话/清掉上下文」说法。
@@ -149,7 +156,7 @@ Hook 与本地 IM 共享消息级来源及上下文快照结构。本地所有
| `/start` | **无** | **有** | Telegram 私聊首次交互必发 `/start`(START 按钮);官方 bot 的首次交互走服务端 deep-link 绑定流程,不需要这条命令。见注册表 `parityNote`——这是**唯一一条个人侧独有**的命令 |
| typing 保活总上限 | 10 分钟 + 设备在线门控 | 5 分钟(`typingKeepaliveMaxMs`) | 超过即停发,turn 异常悬挂时不无限打 API。官方那档带设备在线门控,跨服务端,本仓兑现不了——已在 `presentationCapabilities.ts` 声明为车道差异 |
| **离线期积压消息多久算过期** | **10 分钟**(`controller.ts` 的 `STALE_UPDATE_MS`)。超龄的 update **整条静默消费**:不回复、不派发、也不做群中继;只有成员生命周期(退群 / 群迁移)照跑,因为那是幂等的名单状态,跳过会让离群成员一直收中继 | **60 分钟**(`packages/lizi-im/src/telegram/index.ts` 的 `STALE_MESSAGE_MS`)。私聊超龄直接跳过(连「我不认识你」的陌生人提示也一起跳——隔夜再回同样是诈尸);**群消息照常入本地窗口**,只拦 turn 触发——历史价值与「该不该现在回答」是两件事。时间戳缺失/不可信时**按新鲜放行**(拦错等于吞掉用户当下发的消息,比多回一条陈旧消息严重得多) | 阈值差 6 倍是**写下来的有意选择**(`STALE_MESSAGE_MS` 的注释):**服务端离线 = 故障,桌面关机 = 预期状态**。用户合上电脑一小时再打开,那条正等回复的消息仍然该被处理;但跨夜、跨半天的整批积压用户早已不在等,逐条回答只会刷屏并派出过期任务。两侧闸门的由来是同一次实踩——2026-07-27 上线后整批历史消息被「诈尸」回复、半夜给离线桌面派了过期任务;官方当时就上了 10 分钟闸,个人 bot 那时**一道闸都没有**,后来补的时候顺势按自己的暴露面放宽。别照着官方那个数去「对齐」个人侧 |
-| **新会话的默认 agent / 模型 / 思考强度 / 权限档从哪读** | 读**全局**那份(`hook-control/session-runner.ts` 把 channel 传 `undefined`;只有 Slack 传 `'slack'`)。取值链:本机目录偏好的显式字段(正本 `owners/<hash>/hook-workspace-prefs.json`,键是 `(channel, teamId, workspace)`;升级后每个渠道第一次连上时从 server `user_prefs` 按目录合并迁入,本地已写的键含未同步清空墓碑一律保留)> 桌面端 IM 新会话默认(建 session 那一刻实时读)> 当前可用模型清单首项 > 草稿裸值。迁完之后 server `user_prefs` 只作 `/model` 卡镜像,不再是派发正本。**权限档另走一条**:显式且该 agent 支持 > 显式但不支持时回落该 agent **最严**档 > 从未填过显式档时 `bypassPermissions`——「不支持时只能更严不能更宽」是 2026-07 的安全修正,因为这是无人值守链路。注意 hook 的注入面(`HookDefaultsDeps.readDefaults`)**根本不接草稿里的 `permissionMode`**,是刻意不消费 | 读 **Telegram 渠道独有**的那份(`im/shared/sessionRepo.ts` 把 `ns.source`(`'telegram'`)传给 `resolveImSessionDefaults` → `readImDefaultSettings('telegram')`)。权限档直接用草稿的:`raw.permissionMode ?? config.defaultPermissionMode`(草稿里这个字段出厂值是 `'auto'`) | 裁决就写在 `session-runner.ts` 那行的注释里:**官方 Telegram hook 与个人 bot 是两个独立入口**,个人用 `channel='telegram'`、官方群继续读 global,**为的是避免 IM 默认那张设置卡静默改写另一入口的新会话路由**。用户可见的后果:设置里「Telegram 的新会话默认」**只动个人 bot**;官方 bot 的工作目录行偏好(本机正本,Slack / 官方 Telegram / X 同一套)压过全局 IM 默认,和那张个人卡仍然不是同一份。想「让两处一致」之前,先想清楚哪张设置卡该管哪条入口——这不是漏配,是按入口隔离 |
+| **新会话的默认 agent / 模型 / 思考强度 / 权限档从哪读** | 读**全局**那份(`hook-control/session-runner.ts` 把 channel 传 `undefined`;只有 Slack 传 `'slack'`)。取值链:本机目录偏好的显式字段(正本 `owners/<hash>/hook-workspace-prefs.json`,键是 `(channel, teamId, workspace)`;升级后每个渠道第一次连上时从 server `user_prefs` 按目录合并迁入,本地已写的键含未同步清空墓碑一律保留)> 桌面端 IM 新会话默认(建 session 那一刻实时读)> 当前可用模型清单首项 > 草稿裸值。迁完之后 server `user_prefs` 只作 `/model` 卡镜像,不再是派发正本。**权限档另走一条**:显式且该 agent 支持 > 显式但不支持时回落该 agent **最严**档 > 从未填过显式档时 `bypassPermissions`——「不支持时只能更严不能更宽」是 2026-07 的安全修正,因为这是无人值守链路。注意 hook 的注入面(`HookDefaultsDeps.readDefaults`)**根本不接草稿里的 `permissionMode`**,是刻意不消费 | 读 **Telegram 渠道独有**的那份(`im/shared/sessionRepo.ts` 把 `ns.source`(`'telegram'`)传给 `resolveImSessionDefaults` → `readImDefaultSettings('telegram')`)。权限档直接用草稿的:`raw.permissionMode ?? config.defaultPermissionMode`(草稿里这个字段出厂值是 `'auto'`)。**已有任务**:没被单独改过路由的,在下一条消息时跟随这份默认的 Agent/模型/来源/思考强度(`im/shared/channelDefaultRouteSync.ts`),权限档不跟随 | 裁决就写在 `session-runner.ts` 那行的注释里:**官方 Telegram hook 与个人 bot 是两个独立入口**,个人用 `channel='telegram'`、官方群继续读 global,**为的是避免 IM 默认那张设置卡静默改写另一入口的新会话路由**。用户可见的后果:设置里「Telegram 的新会话默认」**只动个人 bot**;官方 bot 的工作目录行偏好(本机正本,Slack / 官方 Telegram / X 同一套)压过全局 IM 默认,和那张个人卡仍然不是同一份。想「让两处一致」之前,先想清楚哪张设置卡该管哪条入口——这不是漏配,是按入口隔离 |
| lane 模型 | per-principal | per-chat | 已在 `presentationCapabilities.ts` 声明 |
| `message_thread_id` 的**归属判据在哪一侧** | 在**服务端**:桌面这半拿不到 `is_topic_message`(协议 payload 里没有这个字段),只按服务端下发的 threadId 分桶 | 在**客户端**:入站消息走 `laneThreadIdOf`、卡片回调走 `parseCallbackQuery`,都用 `is_topic_message === true` 门控——不是 forum topic 就记进主群流(threadId 空串) | 这个字段有**两个含义**,混用会出真故障:Telegram 对**普通群的 reply 链**也会给 `message_thread_id`(值 = reply root)。**投递位置**用裸值(带上它消息就投对地方,个人侧的出站与 typing 即如此;服务端 `topicThreadIdOf` 的注释也明写「不要拿归属标识替换投递位置参数」);**归属**必须靠 `is_topic_message` 门控。而这个门控字段**只有持有 Telegram 连接的那一侧拿得到**——个人 bot 直连拿得到,官方 bot 的桌面这半只拿服务端下发的 payload,所以判据只能在服务端。这是架构决定的车道差异,不是谁漏做,已在 `presentationCapabilities.ts` 声明为 `threadIdDualSemantics`。**曾经的实机故障**:服务端早期把普通群 reply 链的 `message_thread_id` 当 topic 下发,那些发言散进一个个 reply-root 桶,agent 在群里答「我看不到群里的历史消息」(2026-08-03 实测:172 条在主群流、另有若干 reply-root 桶)。服务端现已按 `is_topic_message` 门控(`controller.ts` 的 `topicThreadIdOf`;**是否已上生产未核**),客户端保留一层兜底救存量错桶行——`buildGroupContextPrefix` 的 `fallbackThreadFilter` 让**主群流**额外读所有非空 threadId 的行(宁可多读同群发言、不可漏读),**topic lane 不读兜底集**:topic 之间严格隔离的优先级高于补读,代价是存量错桶行在 topic lane 里仍看不到 |
| 终稿特效 `messageEffectId` | 有 | 无 | 官方装饰位,已声明 |