Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix: 自动化等入口统一模型选择器并支持切换 Harness (#4061)
Chris Zhanga31eb20857a7
diff --git a/apps/desktop/drizzle/0104_schedule-model-harness.sql b/apps/desktop/drizzle/0104_schedule-model-harness.sqlnew file mode 100644index 0000000000..e0ac49d1ec--- /dev/null+++ b/apps/desktop/drizzle/0104_schedule-model-harness.sql@@ -0,0 +1 @@+SELECT 1;diff --git a/apps/desktop/drizzle/meta/0104_snapshot.json b/apps/desktop/drizzle/meta/0104_snapshot.jsonnew file mode 100644index 0000000000..eca5313968--- /dev/null+++ b/apps/desktop/drizzle/meta/0104_snapshot.json@@ -0,0 +1,5788 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "fd130f32-aea4-433b-bcc0-647be7e90a5d",+ "prevId": "25abf59a-bd8b-42dc-9683-f9a021475250",+ "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": {+ "bot_direct_message_threads_bot_a_id_bot_profiles_id_fk": {+ "name": "bot_direct_message_threads_bot_a_id_bot_profiles_id_fk",+ "tableFrom": "bot_direct_message_threads",+ "tableTo": "bot_profiles",+ "columnsFrom": [+ "bot_a_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "bot_direct_message_threads_bot_b_id_bot_profiles_id_fk": {+ "name": "bot_direct_message_threads_bot_b_id_bot_profiles_id_fk",+ "tableFrom": "bot_direct_message_threads",+ "tableTo": "bot_profiles",+ "columnsFrom": [+ "bot_b_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "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'"+ },+ "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_bot_id_bot_profiles_id_fk": {+ "name": "bot_direct_messages_sender_bot_id_bot_profiles_id_fk",+ "tableFrom": "bot_direct_messages",+ "tableTo": "bot_profiles",+ "columnsFrom": [+ "sender_bot_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "bot_direct_messages_recipient_bot_id_bot_profiles_id_fk": {+ "name": "bot_direct_messages_recipient_bot_id_bot_profiles_id_fk",+ "tableFrom": "bot_direct_messages",+ "tableTo": "bot_profiles",+ "columnsFrom": [+ "recipient_bot_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "bot_direct_messages_sender_session_id_sessions_id_fk": {+ "name": "bot_direct_messages_sender_session_id_sessions_id_fk",+ "tableFrom": "bot_direct_messages",+ "tableTo": "sessions",+ "columnsFrom": [+ "sender_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "bot_direct_messages_recipient_session_id_sessions_id_fk": {+ "name": "bot_direct_messages_recipient_session_id_sessions_id_fk",+ "tableFrom": "bot_direct_messages",+ "tableTo": "sessions",+ "columnsFrom": [+ "recipient_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_lifecycle_events": {+ "name": "bot_lifecycle_events",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "bot_id": {+ "name": "bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "payload_json": {+ "name": "payload_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_bot_lifecycle_events_bot_created": {+ "name": "idx_bot_lifecycle_events_bot_created",+ "columns": [+ "bot_id",+ "created_at"+ ],+ "isUnique": false+ },+ "idx_bot_lifecycle_events_session_created": {+ "name": "idx_bot_lifecycle_events_session_created",+ "columns": [+ "session_id",+ "created_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "bot_lifecycle_events_bot_id_bot_profiles_id_fk": {+ "name": "bot_lifecycle_events_bot_id_bot_profiles_id_fk",+ "tableFrom": "bot_lifecycle_events",+ "tableTo": "bot_profiles",+ "columnsFrom": [+ "bot_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "bot_lifecycle_events_session_id_sessions_id_fk": {+ "name": "bot_lifecycle_events_session_id_sessions_id_fk",+ "tableFrom": "bot_lifecycle_events",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_profile_versions": {+ "name": "bot_profile_versions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "bot_id": {+ "name": "bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "identity_source": {+ "name": "identity_source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "capabilities_json": {+ "name": "capabilities_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_bot_profile_versions_bot_version": {+ "name": "uniq_bot_profile_versions_bot_version",+ "columns": [+ "bot_id",+ "version"+ ],+ "isUnique": true+ },+ "idx_bot_profile_versions_bot_created": {+ "name": "idx_bot_profile_versions_bot_created",+ "columns": [+ "bot_id",+ "created_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "bot_profile_versions_bot_id_bot_profiles_id_fk": {+ "name": "bot_profile_versions_bot_id_bot_profiles_id_fk",+ "tableFrom": "bot_profile_versions",+ "tableTo": "bot_profiles",+ "columnsFrom": [+ "bot_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_profiles": {+ "name": "bot_profiles",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "display_name": {+ "name": "display_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "avatar": {+ "name": "avatar",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'🤖'"+ },+ "avatar_color": {+ "name": "avatar_color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'violet'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "hidden_at": {+ "name": "hidden_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "pinned_at": {+ "name": "pinned_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "attention_reason": {+ "name": "attention_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "attention_at": {+ "name": "attention_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "current_version": {+ "name": "current_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 1+ },+ "canonical_session_id": {+ "name": "canonical_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_bot_profiles_status_updated": {+ "name": "idx_bot_profiles_status_updated",+ "columns": [+ "status",+ "updated_at"+ ],+ "isUnique": false+ },+ "idx_bot_profiles_canonical_session": {+ "name": "idx_bot_profiles_canonical_session",+ "columns": [+ "canonical_session_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "bot_profiles_canonical_session_id_sessions_id_fk": {+ "name": "bot_profiles_canonical_session_id_sessions_id_fk",+ "tableFrom": "bot_profiles",+ "tableTo": "sessions",+ "columnsFrom": [+ "canonical_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_runtime_snapshots": {+ "name": "bot_runtime_snapshots",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "bot_id": {+ "name": "bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "profile_version": {+ "name": "profile_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "working_dir": {+ "name": "working_dir",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "memory_scope_key": {+ "name": "memory_scope_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "configured_json": {+ "name": "configured_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "resolved_json": {+ "name": "resolved_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "prepared_at": {+ "name": "prepared_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "applied_at": {+ "name": "applied_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "failed_at": {+ "name": "failed_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "failure_json": {+ "name": "failure_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_bot_runtime_snapshots_bot_prepared": {+ "name": "idx_bot_runtime_snapshots_bot_prepared",+ "columns": [+ "bot_id",+ "prepared_at"+ ],+ "isUnique": false+ },+ "idx_bot_runtime_snapshots_session_prepared": {+ "name": "idx_bot_runtime_snapshots_session_prepared",+ "columns": [+ "session_id",+ "prepared_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "bot_runtime_snapshots_bot_id_bot_profiles_id_fk": {+ "name": "bot_runtime_snapshots_bot_id_bot_profiles_id_fk",+ "tableFrom": "bot_runtime_snapshots",+ "tableTo": "bot_profiles",+ "columnsFrom": [+ "bot_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "bot_runtime_snapshots_session_id_sessions_id_fk": {+ "name": "bot_runtime_snapshots_session_id_sessions_id_fk",+ "tableFrom": "bot_runtime_snapshots",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "bot_session_links": {+ "name": "bot_session_links",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "bot_id": {+ "name": "bot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "profile_version": {+ "name": "profile_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 1+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "route_key": {+ "name": "route_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_bot_session_links_session": {+ "name": "uniq_bot_session_links_session",+ "columns": [+ "session_id"+ ],+ "isUnique": true+ },+ "uniq_bot_session_links_canonical_per_bot": {+ "name": "uniq_bot_session_links_canonical_per_bot",+ "columns": [+ "bot_id"+ ],+ "isUnique": true,+ "where": "\"bot_session_links\".\"role\" = 'canonical'"+ },+ "idx_bot_session_links_bot_role": {+ "name": "idx_bot_session_links_bot_role",+ "columns": [+ "bot_id",+ "role"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "bot_session_links_bot_id_bot_profiles_id_fk": {+ "name": "bot_session_links_bot_id_bot_profiles_id_fk",+ "tableFrom": "bot_session_links",+ "tableTo": "bot_profiles",+ "columnsFrom": [+ "bot_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "bot_session_links_session_id_sessions_id_fk": {+ "name": "bot_session_links_session_id_sessions_id_fk",+ "tableFrom": "bot_session_links",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "custom_mcp_servers": {+ "name": "custom_mcp_servers",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "transport": {+ "name": "transport",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "headers": {+ "name": "headers",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "sort_order": {+ "name": "sort_order",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_custom_mcp_servers_sort_order": {+ "name": "idx_custom_mcp_servers_sort_order",+ "columns": [+ "sort_order"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "custom_providers": {+ "name": "custom_providers",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "runtimes": {+ "name": "runtimes",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "auth": {+ "name": "auth",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "sort_order": {+ "name": "sort_order",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_custom_providers_sort_order": {+ "name": "idx_custom_providers_sort_order",+ "columns": [+ "sort_order"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "daily_model_usage": {+ "name": "daily_model_usage",+ "columns": {+ "day": {+ "name": "day",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cost_usd": {+ "name": "cost_usd",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_amount": {+ "name": "cost_amount",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_currency": {+ "name": "cost_currency",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'USD'"+ },+ "cost_is_approximate": {+ "name": "cost_is_approximate",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "input_tokens": {+ "name": "input_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "output_tokens": {+ "name": "output_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cache_read_tokens": {+ "name": "cache_read_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cache_create_tokens": {+ "name": "cache_create_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "daily_model_usage_day_agent_kind_model_cost_currency_pk": {+ "columns": [+ "day",+ "agent_kind",+ "model",+ "cost_currency"+ ],+ "name": "daily_model_usage_day_agent_kind_model_cost_currency_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "daily_spend": {+ "name": "daily_spend",+ "columns": {+ "day": {+ "name": "day",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cost_usd": {+ "name": "cost_usd",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_amount": {+ "name": "cost_amount",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_currency": {+ "name": "cost_currency",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'USD'"+ },+ "cost_is_approximate": {+ "name": "cost_is_approximate",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "daily_spend_day_cost_currency_pk": {+ "columns": [+ "day",+ "cost_currency"+ ],+ "name": "daily_spend_day_cost_currency_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "device_link_ownership": {+ "name": "device_link_ownership",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "owner_id": {+ "name": "owner_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "owner_pid": {+ "name": "owner_pid",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "owner_label": {+ "name": "owner_label",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "heartbeat_at": {+ "name": "heartbeat_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "embedding_jobs": {+ "name": "embedding_jobs",+ "columns": {+ "rowid": {+ "name": "rowid",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "source_id": {+ "name": "source_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "chunk_index": {+ "name": "chunk_index",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "model_id": {+ "name": "model_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "vec_table": {+ "name": "vec_table",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scheduled_at": {+ "name": "scheduled_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "locked_at": {+ "name": "locked_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_embedding_jobs_natural": {+ "name": "uniq_embedding_jobs_natural",+ "columns": [+ "source",+ "source_id",+ "chunk_index",+ "model_id"+ ],+ "isUnique": true+ },+ "idx_embedding_jobs_status_scheduled": {+ "name": "idx_embedding_jobs_status_scheduled",+ "columns": [+ "status",+ "scheduled_at"+ ],+ "isUnique": false+ },+ "idx_embedding_jobs_source_id": {+ "name": "idx_embedding_jobs_source_id",+ "columns": [+ "source",+ "source_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "embedding_meta": {+ "name": "embedding_meta",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "ghost_cards": {+ "name": "ghost_cards",+ "columns": {+ "call_id": {+ "name": "call_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "ghost_id": {+ "name": "ghost_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "html": {+ "name": "html",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "height": {+ "name": "height",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "v": {+ "name": "v",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 1+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "ghost_cards_updated_at_idx": {+ "name": "ghost_cards_updated_at_idx",+ "columns": [+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "hook_group_context_cursors": {+ "name": "hook_group_context_cursors",+ "columns": {+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cursor_key": {+ "name": "cursor_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cursor_id": {+ "name": "cursor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "hook_group_context_cursors_updated_at_idx": {+ "name": "hook_group_context_cursors_updated_at_idx",+ "columns": [+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "hook_group_context_cursors_provider_cursor_key_pk": {+ "columns": [+ "provider",+ "cursor_key"+ ],+ "name": "hook_group_context_cursors_provider_cursor_key_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "hook_group_message_stats": {+ "name": "hook_group_message_stats",+ "columns": {+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "row_count": {+ "name": "row_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "text_bytes": {+ "name": "text_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "hook_group_messages": {+ "name": "hook_group_messages",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "chat_id": {+ "name": "chat_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "thread_id": {+ "name": "thread_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "message_id": {+ "name": "message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "chat_name": {+ "name": "chat_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "author": {+ "name": "author",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "is_bot": {+ "name": "is_bot",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "text": {+ "name": "text",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "file_names": {+ "name": "file_names",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "sent_at": {+ "name": "sent_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "hook_group_messages_msg_idx": {+ "name": "hook_group_messages_msg_idx",+ "columns": [+ "provider",+ "chat_id",+ "thread_id",+ "message_id"+ ],+ "isUnique": true+ },+ "hook_group_messages_window_idx": {+ "name": "hook_group_messages_window_idx",+ "columns": [+ "provider",+ "chat_id",+ "thread_id",+ "id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "im_bindings": {+ "name": "im_bindings",+ "columns": {+ "channel": {+ "name": "channel",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "bot_context_id": {+ "name": "bot_context_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "scope_key": {+ "name": "scope_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "target_session_id": {+ "name": "target_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "attached_at": {+ "name": "attached_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "attached_via_card_message_id": {+ "name": "attached_via_card_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_im_bindings_target": {+ "name": "idx_im_bindings_target",+ "columns": [+ "target_session_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "im_bindings_target_session_id_sessions_id_fk": {+ "name": "im_bindings_target_session_id_sessions_id_fk",+ "tableFrom": "im_bindings",+ "tableTo": "sessions",+ "columnsFrom": [+ "target_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "im_bindings_channel_bot_context_id_user_id_scope_key_pk": {+ "columns": [+ "channel",+ "bot_context_id",+ "user_id",+ "scope_key"+ ],+ "name": "im_bindings_channel_bot_context_id_user_id_scope_key_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "media_blobs": {+ "name": "media_blobs",+ "columns": {+ "hash": {+ "name": "hash",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "ext": {+ "name": "ext",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "bytes": {+ "name": "bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "is_cache": {+ "name": "is_cache",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_access_at": {+ "name": "last_access_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "media_invocations": {+ "name": "media_invocations",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "owner": {+ "name": "owner",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "model_id": {+ "name": "model_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "capability": {+ "name": "capability",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "guide_revision": {+ "name": "guide_revision",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "guide_json": {+ "name": "guide_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "response_json": {+ "name": "response_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "media_invocations_owner_created_at_idx": {+ "name": "media_invocations_owner_created_at_idx",+ "columns": [+ "owner",+ "created_at"+ ],+ "isUnique": false+ },+ "media_invocations_owner_state_idx": {+ "name": "media_invocations_owner_state_idx",+ "columns": [+ "owner",+ "state"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "media_refs": {+ "name": "media_refs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "hash": {+ "name": "hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ref_kind": {+ "name": "ref_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ref_id": {+ "name": "ref_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "origin_session_id": {+ "name": "origin_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "origin_kind": {+ "name": "origin_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "origin_id": {+ "name": "origin_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "label": {+ "name": "label",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "media_refs_hash_idx": {+ "name": "media_refs_hash_idx",+ "columns": [+ "hash"+ ],+ "isUnique": false+ },+ "media_refs_ref_idx": {+ "name": "media_refs_ref_idx",+ "columns": [+ "ref_kind",+ "ref_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "media_refs_hash_media_blobs_hash_fk": {+ "name": "media_refs_hash_media_blobs_hash_fk",+ "tableFrom": "media_refs",+ "tableTo": "media_blobs",+ "columnsFrom": [+ "hash"+ ],+ "columnsTo": [+ "hash"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "messages": {+ "name": "messages",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tool_use_id": {+ "name": "tool_use_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_meta": {+ "name": "agent_meta",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "rewind_at": {+ "name": "rewind_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_messages_session_client": {+ "name": "uniq_messages_session_client",+ "columns": [+ "session_id",+ "client_id"+ ],+ "isUnique": true+ },+ "idx_messages_session_created": {+ "name": "idx_messages_session_created",+ "columns": [+ "session_id",+ "created_at"+ ],+ "isUnique": false+ },+ "idx_messages_created_at": {+ "name": "idx_messages_created_at",+ "columns": [+ "created_at",+ "id"+ ],+ "isUnique": false+ },+ "idx_messages_rewind_at": {+ "name": "idx_messages_rewind_at",+ "columns": [+ "rewind_at"+ ],+ "isUnique": false+ },+ "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": {}+ },+ "sessions": {+ "name": "sessions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'New Maker'"+ },+ "working_dir": {+ "name": "working_dir",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_kind": {+ "name": "workspace_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'project'"+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'claude-sonnet-4-6'"+ },+ "effort": {+ "name": "effort",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'high'"+ },+ "permission_mode": {+ "name": "permission_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'ask'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "sdk_session_id": {+ "name": "sdk_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "total_token_usage": {+ "name": "total_token_usage",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "total_cost_usd": {+ "name": "total_cost_usd",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "total_cost_amount": {+ "name": "total_cost_amount",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "total_cost_currency": {+ "name": "total_cost_currency",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "total_cost_is_approximate": {+ "name": "total_cost_is_approximate",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "context_tokens": {+ "name": "context_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "context_window": {+ "name": "context_window",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "fast_mode": {+ "name": "fast_mode",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "plan_mode_enabled": {+ "name": "plan_mode_enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "cleared_at": {+ "name": "cleared_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "pinned_at": {+ "name": "pinned_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_send_at": {+ "name": "user_send_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'cc'"+ },+ "orca_role": {+ "name": "orca_role",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "parent_session_id": {+ "name": "parent_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "forked_at_message_id": {+ "name": "forked_at_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "worktree_path": {+ "name": "worktree_path",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'desktop'"+ },+ "feishu_open_id": {+ "name": "feishu_open_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "feishu_bot_app_id": {+ "name": "feishu_bot_app_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "im_bot_context_id": {+ "name": "im_bot_context_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "im_user_id": {+ "name": "im_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "used_project_context": {+ "name": "used_project_context",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "codex_history_has_product_prompt": {+ "name": "codex_history_has_product_prompt",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "codex_plan_json": {+ "name": "codex_plan_json",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "extra_dirs": {+ "name": "extra_dirs",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "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": {}+ },+ "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": {}+ },+ "vec_table_meta": {+ "name": "vec_table_meta",+ "columns": {+ "vec_table": {+ "name": "vec_table",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "model_id": {+ "name": "model_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "dim": {+ "name": "dim",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "registered_at": {+ "name": "registered_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "notes": {+ "name": "notes",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "wechat_file_attachments": {+ "name": "wechat_file_attachments",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "binding_epoch": {+ "name": "binding_epoch",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "abs_path": {+ "name": "abs_path",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "original_name": {+ "name": "original_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "bytes": {+ "name": "bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'staged'"+ },+ "promoted_at": {+ "name": "promoted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_wechat_file_attachments_task": {+ "name": "idx_wechat_file_attachments_task",+ "columns": [+ "binding_epoch",+ "task_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "wechat_file_attachments_binding_epoch_wechat_sync_state_binding_epoch_fk": {+ "name": "wechat_file_attachments_binding_epoch_wechat_sync_state_binding_epoch_fk",+ "tableFrom": "wechat_file_attachments",+ "tableTo": "wechat_sync_state",+ "columnsFrom": [+ "binding_epoch"+ ],+ "columnsTo": [+ "binding_epoch"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "wechat_file_attachments_task_id_wechat_inbox_id_fk": {+ "name": "wechat_file_attachments_task_id_wechat_inbox_id_fk",+ "tableFrom": "wechat_file_attachments",+ "tableTo": "wechat_inbox",+ "columnsFrom": [+ "task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "wechat_file_attachments_session_id_sessions_id_fk": {+ "name": "wechat_file_attachments_session_id_sessions_id_fk",+ "tableFrom": "wechat_file_attachments",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "wechat_inbox": {+ "name": "wechat_inbox",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "binding_epoch": {+ "name": "binding_epoch",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "platform_message_id": {+ "name": "platform_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "platform_seq": {+ "name": "platform_seq",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "peer_id": {+ "name": "peer_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "received_at": {+ "name": "received_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "platform_created_at": {+ "name": "platform_created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "lease_until": {+ "name": "lease_until",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "conversation_epoch": {+ "name": "conversation_epoch",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "payload_json": {+ "name": "payload_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "context_nonce": {+ "name": "context_nonce",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "context_ciphertext": {+ "name": "context_ciphertext",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "context_tag": {+ "name": "context_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "last_error_code": {+ "name": "last_error_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_wechat_inbox_platform_message": {+ "name": "uniq_wechat_inbox_platform_message",+ "columns": [+ "binding_epoch",+ "platform_message_id"+ ],+ "isUnique": true+ },+ "idx_wechat_inbox_queue": {+ "name": "idx_wechat_inbox_queue",+ "columns": [+ "binding_epoch",+ "status",+ "received_at"+ ],+ "isUnique": false+ },+ "idx_wechat_inbox_lease": {+ "name": "idx_wechat_inbox_lease",+ "columns": [+ "binding_epoch",+ "lease_until"+ ],+ "isUnique": false+ },+ "idx_wechat_inbox_conversation": {+ "name": "idx_wechat_inbox_conversation",+ "columns": [+ "binding_epoch",+ "peer_id",+ "conversation_epoch"+ ],+ "isUnique": false+ },+ "uniq_wechat_inbox_running_session": {+ "name": "uniq_wechat_inbox_running_session",+ "columns": [+ "binding_epoch",+ "session_id"+ ],+ "isUnique": true,+ "where": "\"wechat_inbox\".\"session_id\" IS NOT NULL AND \"wechat_inbox\".\"status\" IN ('dispatching', 'accepted_running', 'waiting_desktop', 'delivery_pending')"+ }+ },+ "foreignKeys": {+ "wechat_inbox_binding_epoch_wechat_sync_state_binding_epoch_fk": {+ "name": "wechat_inbox_binding_epoch_wechat_sync_state_binding_epoch_fk",+ "tableFrom": "wechat_inbox",+ "tableTo": "wechat_sync_state",+ "columnsFrom": [+ "binding_epoch"+ ],+ "columnsTo": [+ "binding_epoch"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "wechat_inbox_session_id_sessions_id_fk": {+ "name": "wechat_inbox_session_id_sessions_id_fk",+ "tableFrom": "wechat_inbox",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "wechat_outbox": {+ "name": "wechat_outbox",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "binding_epoch": {+ "name": "binding_epoch",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "chunk_index": {+ "name": "chunk_index",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "text": {+ "name": "text",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "media_json": {+ "name": "media_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "next_retry_at": {+ "name": "next_retry_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "delivered_at": {+ "name": "delivered_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_wechat_outbox_client_id": {+ "name": "uniq_wechat_outbox_client_id",+ "columns": [+ "binding_epoch",+ "client_id"+ ],+ "isUnique": true+ },+ "idx_wechat_outbox_delivery": {+ "name": "idx_wechat_outbox_delivery",+ "columns": [+ "binding_epoch",+ "status",+ "next_retry_at"+ ],+ "isUnique": false+ },+ "idx_wechat_outbox_task": {+ "name": "idx_wechat_outbox_task",+ "columns": [+ "binding_epoch",+ "task_id",+ "chunk_index"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "wechat_outbox_binding_epoch_wechat_sync_state_binding_epoch_fk": {+ "name": "wechat_outbox_binding_epoch_wechat_sync_state_binding_epoch_fk",+ "tableFrom": "wechat_outbox",+ "tableTo": "wechat_sync_state",+ "columnsFrom": [+ "binding_epoch"+ ],+ "columnsTo": [+ "binding_epoch"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "wechat_outbox_task_id_wechat_inbox_id_fk": {+ "name": "wechat_outbox_task_id_wechat_inbox_id_fk",+ "tableFrom": "wechat_outbox",+ "tableTo": "wechat_inbox",+ "columnsFrom": [+ "task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "wechat_sync_state": {+ "name": "wechat_sync_state",+ "columns": {+ "binding_epoch": {+ "name": "binding_epoch",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "is_active": {+ "name": "is_active",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "sync_cursor": {+ "name": "sync_cursor",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "last_poll_at": {+ "name": "last_poll_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_error_code": {+ "name": "last_error_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_wechat_sync_active": {+ "name": "uniq_wechat_sync_active",+ "columns": [+ "is_active"+ ],+ "isUnique": true,+ "where": "\"wechat_sync_state\".\"is_active\" = 1"+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "indexes": {+ "uniq_orca_worker_creation_reservations_team_label": {+ "columns": {+ "lower(\"label\")": {+ "isExpression": true+ }+ }+ },+ "uniq_orca_workers_team_label": {+ "columns": {+ "lower(\"label\")": {+ "isExpression": true+ }+ }+ }+ }+ }+}\ No newline at end of filediff --git a/apps/desktop/drizzle/meta/_journal.json b/apps/desktop/drizzle/meta/_journal.jsonindex 0154777e97..061fda29b6 100644--- a/apps/desktop/drizzle/meta/_journal.json+++ b/apps/desktop/drizzle/meta/_journal.json@@ -729,6 +729,13 @@"when": 1788596996011,"tag": "0103_bot_mode","breakpoints": true+ },+ {+ "idx": 104,+ "version": "6",+ "when": 1788783797334,+ "tag": "0104_schedule-model-harness",+ "breakpoints": true}]}\ No newline at end of filediff --git a/apps/desktop/drizzle/scripts/0104_schedule-model-harness.ts b/apps/desktop/drizzle/scripts/0104_schedule-model-harness.tsnew file mode 100644index 0000000000..ffbfaefd61--- /dev/null+++ b/apps/desktop/drizzle/scripts/0104_schedule-model-harness.ts@@ -0,0 +1,9 @@+import type Database from 'better-sqlite3';++function run(db: Database.Database): void {+ const columns = db.prepare("PRAGMA table_info('schedules')").all() as Array<{ name: string }>;+ if (columns.length === 0 || columns.some((column) => column.name === 'model_agent_kind')) return;+ db.exec('ALTER TABLE `schedules` ADD `model_agent_kind` text');+}++module.exports = { run };diff --git a/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts b/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.tsindex 7e4204358c..a887c8308b 100644--- a/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts@@ -102,6 +102,45 @@ function columnNames(db: Database.Database, tableName: string): string[] {}describeMigrationReplay('migration replay', () => {+ it.each(['missing table', 'legacy table', 'existing column'] as const)(+ 'replays the scheduled Harness migration safely with %s',+ (state) => {+ const { db, cleanup } = createTempDb();+ const stagedDir = mkdtempSync(path.join(tmpdir(), 'xdmaker-drizzle-scheduled-harness-'));+ try {+ db.exec('CREATE TABLE migration_meta (key TEXT PRIMARY KEY NOT NULL, value TEXT NOT NULL)');+ const migration = listMigrations(drizzleDir()).find((item) => item.seq === 104)!;+ copyFileSync(migration.sqlPath, path.join(stagedDir, migration.fileName));+ mkdirSync(path.join(stagedDir, 'scripts'));+ copyFileSync(migration.tsScriptPath!, path.join(stagedDir, 'scripts', path.basename(migration.tsScriptPath!)));+ if (state !== 'missing table') {+ db.exec(`CREATE TABLE schedules (id TEXT PRIMARY KEY, agent_kind TEXT, model TEXT);+ INSERT INTO schedules VALUES ('legacy-schedule', 'codex', 'legacy-model');`);+ if (state === 'existing column') {+ db.exec(`ALTER TABLE schedules ADD model_agent_kind TEXT;+ UPDATE schedules SET model_agent_kind = 'pi';`);+ }+ }+ for (let replay = 0; replay < 2; replay += 1) {+ const result = runMigrationReplay(db, { drizzleDir: stagedDir, currentVersion: 103 });+ expect(result.applied.map((item) => item.seq)).toEqual([104]);+ if (state === 'missing table') {+ expect(tableExists(db, 'schedules')).toBe(false);+ } else {+ expect(db.prepare('SELECT * FROM schedules').all()).toEqual([{+ id: 'legacy-schedule', agent_kind: 'codex', model: 'legacy-model',+ model_agent_kind: state === 'existing column' ? 'pi' : null,+ }]);+ }+ expect(db.prepare("SELECT value FROM migration_meta WHERE key = 'schema_version'").pluck().get()).toBe('104');+ }+ } finally {+ rmSync(stagedDir, { recursive: true, force: true });+ cleanup();+ }+ },+ );+it('replays every drizzle migration into a fresh database', () => {const { db, cleanup } = createTempDb();try {diff --git a/apps/desktop/src/main/localDb/mapper.ts b/apps/desktop/src/main/localDb/mapper.tsindex 9404cd8889..d074dd7b09 100644--- a/apps/desktop/src/main/localDb/mapper.ts+++ b/apps/desktop/src/main/localDb/mapper.ts@@ -666,6 +666,7 @@ export function scheduleToCamel(row: ScheduleRow): Schedule {manual: !!row.manual,intervalMs: row.intervalMs ?? undefined,agentKind: row.agentKind as SchedulerAgentKind,+ modelAgentKind: row.modelAgentKind ?? undefined,model: row.model ?? undefined,providerId: row.providerId ?? undefined,effort: row.effort ?? undefined,@@ -717,6 +718,7 @@ export function scheduleCreateToRow(s: Schedule): ScheduleInsert {manual: s.manual,intervalMs: s.intervalMs ?? null,agentKind: s.agentKind,+ modelAgentKind: s.modelAgentKind ?? null,model: s.model ?? null,providerId: s.providerId ?? null,effort: (s.effort as ScheduleInsert['effort']) ?? null,@@ -771,6 +773,7 @@ export function schedulePatchToRow(patch: Partial<Schedule>): Partial<ScheduleIn// intervalMs:undefined → null(清空,回退到 cron 槽位语义);数字原样写if (hasKey(patch, 'intervalMs')) out.intervalMs = patch.intervalMs ?? null;if (hasKey(patch, 'agentKind')) out.agentKind = patch.agentKind as ScheduleInsert['agentKind'];+ if (hasKey(patch, 'modelAgentKind')) out.modelAgentKind = patch.modelAgentKind ?? null;if (hasKey(patch, 'model')) out.model = patch.model ?? null;if (hasKey(patch, 'providerId')) out.providerId = patch.providerId ?? null;if (hasKey(patch, 'effort')) out.effort = (patch.effort as ScheduleInsert['effort']) ?? null;diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.tsindex 03235f456d..f6a758644a 100644--- a/apps/desktop/src/main/localDb/schema.ts+++ b/apps/desktop/src/main/localDb/schema.ts@@ -1145,6 +1145,8 @@ export const schedules = sqliteTable(*/intervalMs: integer('interval_ms'),agentKind: text('agent_kind', { enum: ['claude-code', 'codex', 'pi'] }).notNull(),+ /** NULL preserves legacy bound-task Harness inheritance. */+ modelAgentKind: text('model_agent_kind', { enum: ['claude-code', 'codex', 'pi'] }),model: text('model'),/*** 显式选定的供应商(来源)id。NULL = 回落该 agent 原生默认来源(no-break,diff --git a/apps/desktop/src/main/maker-host/__tests__/model-route-guard-live.test.ts b/apps/desktop/src/main/maker-host/__tests__/model-route-guard-live.test.tsindex a6f7560b77..194486098a 100644--- a/apps/desktop/src/main/maker-host/__tests__/model-route-guard-live.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/model-route-guard-live.test.ts@@ -6,7 +6,8 @@ const h = vi.hoisted(() => ({effectiveSourceIdForModel: vi.fn(),}));-vi.mock('@cindy/model-providers', () => ({+vi.mock('@cindy/model-providers', async (importOriginal) => ({+ findCatalogModel: (await importOriginal<typeof import('@cindy/model-providers')>()).findCatalogModel,connectedProvidersForAgent: vi.fn(() => []),effectiveSourceIdForModel: h.effectiveSourceIdForModel,getModel: vi.fn(() => null),@@ -40,6 +41,7 @@ vi.mock('../model-plane/modelPlanePolicy.js', () => ({import {resolveDefaultScheduleRoute,+ resolveScheduledModelSelectionLive,resolveLenientSessionRoute,} from '../model-route-guard-live.js';@@ -131,3 +133,17 @@ describe('resolveLenientSessionRoute provider-list outage', () => {});});});+++describe('scheduled selection uses the live source copy', () => {+ it('reads the current catalog without claiming credentials and preserves the requested route', async () => {+ const selection = { agentKind: 'pi' as const, model: 'same-model', providerId: 'selected', effort: 'ultra' as const, fastMode: true };+ h.listProviders.mockResolvedValue([+ { id: 'other', connected: true, models: { pi: [{ id: 'same-model', efforts: ['ultra'], defaultEffort: 'ultra', supportsFastMode: true }] } },+ { id: 'selected', connected: true, models: { pi: [{ id: 'same-model', efforts: ['medium'], defaultEffort: 'medium', supportsFastMode: false }] } },+ ]);+ await expect(resolveScheduledModelSelectionLive(selection)).resolves.toEqual({ ...selection, effort: 'medium', fastMode: false });+ expect(h.listProviders).toHaveBeenLastCalledWith({ allowSideEffects: false, catalog: h.catalog });+ expect(selection).toMatchObject({ effort: 'ultra', fastMode: true });+ });+});diff --git a/apps/desktop/src/main/maker-host/model-route-guard-live.ts b/apps/desktop/src/main/maker-host/model-route-guard-live.tsindex a86c719c6f..c1248c7c05 100644--- a/apps/desktop/src/main/maker-host/model-route-guard-live.ts+++ b/apps/desktop/src/main/maker-host/model-route-guard-live.ts@@ -26,6 +26,7 @@ import {type ProviderView,} from '@cindy/model-providers';+import { resolveScheduledModelSelection, type ScheduledModelSelection } from '../maker-ipc/scheduledModelSelection';import { getDesktopProviderService } from './createDesktopProviderService.js';import {getActiveCatalog,@@ -277,6 +278,16 @@ export async function resolveLenientSessionRoute(return route;}+/** Resolve one provider-specific snapshot after route admission for fresh and bound sends. */+export async function resolveScheduledModelSelectionLive(+ selection: ScheduledModelSelection,+): Promise<ScheduledModelSelection> {+ const providers = await getDesktopProviderService().listProviders({+ allowSideEffects: false, catalog: getActiveCatalog(),+ });+ return resolveScheduledModelSelection(selection, providers);+}+/*** 某 (来源, 模型, agent) 拷贝的能力快照(efforts / Fast)。scheduler runner 在停用轴* 隐式改道后按落地拷贝 reconcile effort/fastMode 用(merged capability 分辨不出来源diff --git a/apps/desktop/src/main/maker-ipc/__tests__/scheduleIntervalJsonBoundary.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/scheduleIntervalJsonBoundary.test.tsindex de4bc1fbf9..045cc14b3b 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/scheduleIntervalJsonBoundary.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/scheduleIntervalJsonBoundary.test.ts@@ -12,9 +12,14 @@*/import { describe, expect, it, vi } from 'vitest';+import type { Schedule, CreateScheduleInput, UpdateScheduleInput } from '@cindy/maker-scheduler';+import { BUILTIN_TEMPLATES, Scheduler } from '@cindy/maker-scheduler';+import { applyTemplateToMobileScheduleDraft, buildMobileScheduleInput, createMobileScheduleDraft, updateDraftBoundSessionId } from '@cindy/maker-shared/schedule-form';++const handlers = vi.hoisted(() => new Map<string, (...args: unknown[]) => Promise<unknown>>());vi.mock('electron', () => ({- ipcMain: { handle: vi.fn() },+ ipcMain: { handle: vi.fn((name, handler) => handlers.set(name, handler)) },BrowserWindow: { getAllWindows: vi.fn(() => []) },app: {getPath: vi.fn(() => '/tmp/cindy-test-user-data'),@@ -28,12 +33,17 @@ vi.mock('../../device-link/broadcast-tap.js', () => ({tapWindowBroadcast: vi.fn(),}));+vi.mock('../../device-link/invoke-context.js', () => ({ isDeviceLinkInvoke: () => true }));+vi.mock('../../agent-island/service.js', () => ({getAgentIslandService: () => null,}));import {normalizeLegacyDeviceLinkIntervalClear,+ normalizeLegacyDeviceLinkModelSelection,+ registerScheduleHandlers,+ setSchedulerReady,normalizeNullableIntervalMs,} from '../schedule';@@ -114,3 +124,92 @@ describe('normalizeLegacyDeviceLinkIntervalClear(旧版 mobile 的清空兼容)'expect(normalizeLegacyDeviceLinkIntervalClear(partial, true)).toBe(partial);});});+++describe('scheduled model selection IPC compatibility', () => {+ const existing = { id: 'bound-schedule', targetSessionId: 'bound', agentKind: 'codex',+ modelAgentKind: 'pi', model: 'pi-model', providerId: 'pi-source', effort: 'high', fastMode: true } as Schedule;+ const fullForm = { cronExpr: '0 9 * * *', manual: false, notify: { desktop: true, feishu: false },+ targetSessionId: 'bound', agentKind: 'codex', model: 'pi-model' } as UpdateScheduleInput;++ it('normalizes an old Mobile full form inside the update handler before partial merge', async () => {+ const updateFromCurrent = vi.fn(async (_id, update) => ({ ...existing, ...await update(existing) }));+ setSchedulerReady({ updateFromCurrent } as never, {} as never);+ registerScheduleHandlers();+ const wire = JSON.parse(JSON.stringify({ ...fullForm, model: 'codex-model' }));+ const result = await handlers.get('maker:schedule:update')!(null, existing.id, wire);+ expect(result).toMatchObject({ agentKind: 'codex', modelAgentKind: 'codex', model: 'codex-model', fastMode: false });+ expect(result).toHaveProperty('providerId', undefined);+ expect(result).toHaveProperty('effort', undefined);+ expect(updateFromCurrent).toHaveBeenCalledTimes(1);+ expect(existing).toMatchObject({ modelAgentKind: 'pi', providerId: 'pi-source', fastMode: true });+ });++ it('preserves an untouched old full form and genuine local/remote partial updates', () => {+ expect(normalizeLegacyDeviceLinkModelSelection(existing, fullForm, true)).toBe(fullForm);+ const partial = { model: 'other' };+ expect(normalizeLegacyDeviceLinkModelSelection(existing, partial, true)).toBe(partial);+ const local = { ...fullForm, model: 'other' };+ expect(normalizeLegacyDeviceLinkModelSelection(existing, local, false)).toBe(local);+ const modern = { ...fullForm, model: 'other', modelAgentKind: 'pi' as const };+ expect(normalizeLegacyDeviceLinkModelSelection(existing, modern, true)).toBe(modern);+ });++ it('clears the old explicit route when the old full form clears its model', () => {+ const wire = JSON.parse(JSON.stringify({ ...fullForm, model: undefined }));+ expect(normalizeLegacyDeviceLinkModelSelection(existing, wire, true)).toMatchObject({+ modelAgentKind: undefined, model: undefined, providerId: undefined, effort: undefined, fastMode: false,+ });+ });++ it.each([+ { model: '', rebind: false }, { model: ' ', rebind: false }, { model: '', rebind: true },+ ])('saves and reopens a Mobile bound form after clearing its model: %j', async ({ model, rebind }) => {+ let saved = { ...existing, ...fullForm, name: 'Bound', prompt: 'Run',+ recurring: true, timezone: 'UTC', status: 'active', workspaceKind: 'dialogue' } as Schedule;+ const storage = {+ get: vi.fn(async () => ({ ...saved })),+ update: vi.fn(async (_id: string, patch: Partial<Schedule>) => {+ saved = { ...saved, ...patch };+ return { ...saved };+ }),+ };+ const scheduler = new Scheduler({ storage: storage as never, runner: { fire: vi.fn() } });+ setSchedulerReady(scheduler, storage as never);+ registerScheduleHandlers();+ const originalDraft = createMobileScheduleDraft({ ...saved, source: 'user' });+ const draft = rebind+ ? { ...updateDraftBoundSessionId(originalDraft, 'new-codex', 'codex'), persistentSession: true }+ : originalDraft;+ const targetSessionId = rebind ? 'new-codex' : 'bound';+ const wire = JSON.parse(JSON.stringify(buildMobileScheduleInput({ ...draft, model })));+ expect(wire).not.toHaveProperty('modelAgentKind');+ const result = await handlers.get('maker:schedule:update')!(null, existing.id, wire);+ expect(result).toMatchObject({ agentKind: 'codex', targetSessionId, persistentSession: rebind,+ modelAgentKind: undefined, model: undefined, providerId: undefined, effort: 'high', fastMode: false });+ expect(storage.update).toHaveBeenCalledTimes(1);+ const reopened = createMobileScheduleDraft({ ...saved, source: 'user' });+ expect(reopened).toMatchObject({ agentKind: 'codex', model: '', modelAgentKind: undefined });+ const unchanged = JSON.parse(JSON.stringify(buildMobileScheduleInput({ ...reopened, name: 'Renamed' })));+ await handlers.get('maker:schedule:update')!(null, existing.id, unchanged);+ expect(saved).toMatchObject({ name: 'Renamed', agentKind: 'codex', model: undefined, modelAgentKind: undefined });+ });++ it.each([true, false])('passes a Mobile template choice and Fast=%s through the real creation handler', async (fastMode) => {+ const template = BUILTIN_TEMPLATES[0]!;+ const draft = applyTemplateToMobileScheduleDraft(createMobileScheduleDraft(), {+ ...template, agentKind: 'pi', model: 'pi-model', providerId: 'pi-source', fastMode: true,+ useWorktree: false,+ });+ const input = buildMobileScheduleInput({ ...draft, targetSessionId: 'bound', effort: 'high', fastMode });+ const create = vi.fn(async (input: CreateScheduleInput) => input);+ setSchedulerReady({ create } as never, {} as never);+ registerScheduleHandlers();+ const wire = JSON.parse(JSON.stringify({ templateId: template.id, overrides: input }));+ await handlers.get('maker:schedule:create-from-template')!(null, wire);+ expect(create).toHaveBeenCalledWith(expect.objectContaining({+ targetSessionId: 'bound', agentKind: 'pi', modelAgentKind: 'pi', model: 'pi-model',+ providerId: 'pi-source', effort: 'high', fastMode,+ }));+ });+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.tsnew file mode 100644index 0000000000..46db0e72aa--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/scheduledModelSelection.test.ts@@ -0,0 +1,145 @@+import { describe, expect, it, vi } from 'vitest';+import type { CatalogModel, ProviderView } from '@cindy/model-providers';+import { applyScheduledModelSelection, assertScheduledHarnessSupported, resolveScheduledModelSelection, ScheduledModelSelectionBusyError, type ScheduledModelSelection } from '../scheduledModelSelection';++const selection: ScheduledModelSelection = {+ agentKind: 'pi', model: 'test-model', providerId: 'custom', effort: null, fastMode: false,+};+function fixture(agentKind: ScheduledModelSelection['agentKind'] = 'codex') {+ return {+ getTarget: vi.fn(async () => ({ agentKind, status: 'active' })),+ isBusy: vi.fn(() => false),+ resolveSelection: vi.fn(async (selection: ScheduledModelSelection) => selection),+ switchHarness: vi.fn(async (_selection: ScheduledModelSelection) => ({ engineReady: true })),+ applyModel: vi.fn(async (_selection: ScheduledModelSelection) => {}),+ };+}++describe('saved automation model selection at dispatch', () => {+ it('hands history to the target Harness before applying the complete model configuration', async () => {+ const deps = fixture();+ await applyScheduledModelSelection(selection, deps);+ expect(deps.switchHarness).toHaveBeenCalledWith(selection);+ expect(deps.applyModel).toHaveBeenCalledWith(selection);+ expect(deps.switchHarness.mock.invocationCallOrder[0]).toBeLessThan(deps.applyModel.mock.invocationCallOrder[0]);+ });+ it('uses the ordinary model path without a handoff for the same Harness', async () => {+ const deps = fixture('pi');+ await applyScheduledModelSelection(selection, deps);+ expect(deps.switchHarness).not.toHaveBeenCalled();+ expect(deps.applyModel).toHaveBeenCalledWith(selection);+ });+ it('defers busy work without changing or staging either configuration', async () => {+ const deps = fixture();+ deps.isBusy.mockReturnValue(true);+ await expect(applyScheduledModelSelection(selection, deps)).rejects.toBeInstanceOf(ScheduledModelSelectionBusyError);+ expect(deps.switchHarness).not.toHaveBeenCalled();+ expect(deps.applyModel).not.toHaveBeenCalled();+ });+ it.each(['missing', 'archived', 'deleted'])('returns the resolved snapshot for %s target recovery without touching the target', async (status) => {+ const deps = fixture();+ const expected = { ...selection, effort: 'medium' as const };+ deps.getTarget.mockResolvedValue(status === 'missing' ? null as never : { agentKind: 'codex', status });+ deps.resolveSelection.mockResolvedValue(expected);+ await expect(applyScheduledModelSelection(selection, deps)).resolves.toEqual(expected);+ expect(deps.switchHarness).not.toHaveBeenCalled();+ expect(deps.applyModel).not.toHaveBeenCalled();+ });+ it('does not apply a model to a Harness that failed to become ready', async () => {+ const deps = fixture();+ deps.switchHarness.mockResolvedValue({ engineReady: false });+ await expect(applyScheduledModelSelection(selection, deps)).rejects.toThrow('did not become ready');+ expect(deps.applyModel).not.toHaveBeenCalled();+ });++ it('resolves omitted effort before either the Harness switch or model application', async () => {+ const deps = fixture();+ deps.resolveSelection.mockImplementation(async (choice) => resolveScheduledModelSelection(choice, [provider('custom')]));+ await applyScheduledModelSelection(selection, deps);+ const expected = { ...selection, effort: 'medium' };+ expect(deps.switchHarness).toHaveBeenCalledWith(expected);+ expect(deps.applyModel).toHaveBeenCalledWith(expected);+ expect(deps.resolveSelection.mock.invocationCallOrder[0]).toBeLessThan(deps.switchHarness.mock.invocationCallOrder[0]);+ });++ it('leaves the target untouched when the saved provider is unavailable', async () => {+ const deps = fixture();+ deps.resolveSelection.mockImplementation(async (choice) => resolveScheduledModelSelection(choice, [provider('other')]));+ await expect(applyScheduledModelSelection(selection, deps)).rejects.toThrow('unavailable');+ expect(deps.switchHarness).not.toHaveBeenCalled();+ expect(deps.applyModel).not.toHaveBeenCalled();+ });+ it('clears stale Fast before switching Harness or applying the saved selection', async () => {+ const deps = fixture();+ deps.resolveSelection.mockImplementation(async (choice) => resolveScheduledModelSelection(choice, [provider('custom')]));+ const expected = { ...selection, effort: 'medium', fastMode: false };+ await expect(applyScheduledModelSelection({ ...selection, providerId: null, fastMode: true }, deps))+ .resolves.toEqual(expected);+ expect(deps.switchHarness).toHaveBeenCalledWith(expected);+ expect(deps.applyModel).toHaveBeenCalledWith(expected);+ });+ it('rejects an unsupported bound Harness before route preparation or runtime mutation', async () => {+ const deps = { ...fixture(), getTarget: vi.fn(async () => ({+ agentKind: 'codex' as const, status: 'active', remoteHostId: 'ssh-host',+ })) };+ await expect(applyScheduledModelSelection(selection, deps)).rejects.toThrow('current Harness');+ expect(deps.resolveSelection).not.toHaveBeenCalled();+ expect(deps.switchHarness).not.toHaveBeenCalled();+ expect(deps.applyModel).not.toHaveBeenCalled();+ });+});++function provider(id: string, model: Partial<CatalogModel> = {}): ProviderView {+ return {+ id, name: id, source: 'user', connected: true, agents: ['pi'],+ auth: { method: 'none' }, routing: { pi: {} },+ models: { pi: [{ id: 'test-model', name: 'Test model', contextWindow: 128_000,+ efforts: ['low', 'medium', 'high'], defaultEffort: 'medium', ...model }] },+ } as ProviderView;+}++describe('saved effort uses the selected provider and Harness catalog copy', () => {+ it.each([null, 'ultra'] as const)('fills or reconciles %s to the route default', (effort) => {+ const selected = provider('custom', { efforts: ['low', 'high'], defaultEffort: 'high' });+ const other = provider('other', { efforts: ['low'], defaultEffort: 'low' });+ selected.models.codex = [{ ...selected.models.pi![0]!, efforts: ['medium'], defaultEffort: 'medium' }];+ expect(resolveScheduledModelSelection({ ...selection, effort }, [other, selected]))+ .toMatchObject({ agentKind: 'pi', providerId: 'custom', effort: 'high' });+ });+ it('preserves a supported explicit tier rather than replacing it with the default', () => {+ expect(resolveScheduledModelSelection({ ...selection, effort: 'low' }, [provider('custom')]).effort).toBe('low');+ });+ it('materializes the default provider before resolving its effort', () => {+ expect(resolveScheduledModelSelection({ ...selection, providerId: null }, [provider('custom')]))+ .toMatchObject({ providerId: 'custom', effort: 'medium' });+ });+ it('clears stale effort for a model with no adjustable tiers', () => {+ expect(resolveScheduledModelSelection({ ...selection, effort: 'high' }, [+ provider('custom', { efforts: [], defaultEffort: undefined }),+ ]).effort).toBeNull();+ });+ it.each([true, false, undefined])('uses only the selected route Fast capability (%s)', (supportsFastMode) => {+ const selected = provider('custom', { supportsFastMode });+ selected.models.codex = [{ ...selected.models.pi![0]!, supportsFastMode: true }];+ const providers = [provider('other', { supportsFastMode: true }), selected];+ expect(resolveScheduledModelSelection({ ...selection, fastMode: true }, providers).fastMode)+ .toBe(supportsFastMode === true);+ expect(resolveScheduledModelSelection(selection, providers).fastMode).toBe(false);+ });+});++describe('bound target Harness capability', () => {+ it.each([{ remoteHostId: 'ssh-host' }, { orcaRole: 'lead' }, { orcaRole: 'worker' }])(+ 'rejects cross-Harness overrides on %j while preserving same-Harness and follow modes', (restriction) => {+ const target = { agentKind: 'codex' as const, status: 'active', ...restriction };+ expect(() => assertScheduledHarnessSupported(target, 'pi')).toThrow('current Harness');+ expect(() => assertScheduledHarnessSupported(target, 'codex')).not.toThrow();+ expect(() => assertScheduledHarnessSupported(target, undefined)).not.toThrow();+ },+ );+ it('preserves ordinary local cross-Harness selection and archived-target recovery', () => {+ expect(() => assertScheduledHarnessSupported({ agentKind: 'codex', status: 'active' }, 'pi')).not.toThrow();+ expect(() => assertScheduledHarnessSupported({ agentKind: 'codex', status: 'archived', remoteHostId: 'ssh-host' }, 'pi')).not.toThrow();+ expect(() => assertScheduledHarnessSupported(null, 'pi')).not.toThrow();+ });+});diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 8d404262ec..22b9d32911 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -69,6 +69,7 @@ import {DL_SESSION_REFERENCE_CAPABILITY_CHANNEL,} from '@cindy/device-link';import { and, desc, eq, gte, inArray, isNull, lt, sql } from 'drizzle-orm';+import { applyScheduledModelSelection, ScheduledModelSelectionBusyError, type ScheduledModelSelection, type ScheduledModelSelectionLease } from './scheduledModelSelection';import { app, BrowserWindow, dialog, ipcMain, shell, type IpcMainInvokeEvent } from 'electron';import {activeOwnerScopeKey,@@ -866,6 +867,7 @@ import {import {pinExclusiveSessionProvider,resolveLenientSessionRoute,+ resolveScheduledModelSelectionLive,shouldApplyExclusiveProviderRerouteLive,verdictForModelRoute,} from '../maker-host/model-route-guard-live.js';@@ -3157,7 +3159,7 @@ function settlePendingCredentialSwitch(sessionId: string, source: string): voidlet refreshRemoteCodexMcpOnTurnSettledHolder: ((sessionId: string) => void) | null = null;let deferredCodexRestartHolder: DeferredCodexRestartService | null = null;let pendingAgentSwitchApplyHolder:- ((sessionId: string, signal?: AbortSignal) => Promise<() => void>) | null = null;+ ((sessionId: string, signal?: AbortSignal, selection?: ScheduledModelSelection) => Promise<{ release: () => void; selection?: ScheduledModelSelection }>) | null = null;let cancelPendingAgentSwitchHolder: ((sessionId: string) => void) | null = null;let gitSnapshotCoordinator: GitSnapshotCoordinator | null = null;const sessionTurnActivityTracker = new SessionTurnActivityTracker();@@ -3337,11 +3339,25 @@ export function clearWorkingDirectoryRecoveryForOwnerBoundary(): void {* 并完成 send 后才 release。启动期 holder 尚未就绪时不可能已有进程内 pending* intent,返回 no-op release 即可。*/+export function acquirePendingAgentSwitchForDirectSend(+ sessionId: string, signal?: AbortSignal,+): Promise<() => void>;+export function acquirePendingAgentSwitchForDirectSend(+ sessionId: string, signal: AbortSignal | undefined, selection: ScheduledModelSelection,+): Promise<ScheduledModelSelectionLease>;export async function acquirePendingAgentSwitchForDirectSend(sessionId: string,signal?: AbortSignal,-): Promise<() => void> {- return pendingAgentSwitchApplyHolder?.(sessionId, signal) ?? (() => {});+ selection?: ScheduledModelSelection,+): Promise<(() => void) | ScheduledModelSelectionLease> {+ if (selection && !pendingAgentSwitchApplyHolder) throw new Error('Scheduled model selection is not initialized');+ const lease = await pendingAgentSwitchApplyHolder?.(sessionId, signal, selection);+ if (!selection) return lease?.release ?? (() => {});+ if (!lease?.selection) {+ lease?.release();+ throw new Error('Scheduled model selection was not resolved');+ }+ return { release: lease.release, selection: lease.selection };}/** 直发路径在 createSession / 重读 live session 之前关掉不健康原生会话。 */@@ -5108,6 +5124,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 已设间隔算出 now+null 立即触发,mobile 必须据此回退旧 wire 形态(省略// key,由旧引擎的隐式清空承担等价语义)。supportsScheduleIntervalNullClear: true,+ // Full scheduled model selection, including bound Harness changes and template overrides.+ supportsScheduleModelSelection: true,};});@@ -8060,15 +8078,48 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)withCloseSuppressed: withRehydrateCloseSuppressed,log,});- pendingAgentSwitchApplyHolder = async (sessionId, signal) => {+ pendingAgentSwitchApplyHolder = async (sessionId, signal, selection) => {const release = await acquireSendToSessionLock(sessionId);try {await applyPendingAgentSwitchIfIdle(agentSwitchDeps, sessionId, {bootstrapAfterSwitch: true,signal,});+ let resolvedSelection: ScheduledModelSelection | undefined;+ if (selection) {+ resolvedSelection = await applyScheduledModelSelection(selection, {+ getTarget: async () => {+ const row = await agentSwitchDeps.getSessionRow(sessionId);+ return row ? { agentKind: dbToMakerAgentKind(row.agentKind), status: row.status,+ remoteHostId: row.remoteHostId, orcaRole: row.orcaRole } : null;+ },+ isBusy: () => isSessionInTurn(sessionId) || !!maker.getSession(sessionId)?.isTurnRunning(),+ resolveSelection: async (route) => {+ const reroute = await assertModelRouteUsable(route.agentKind, route.model, route.providerId);+ return resolveScheduledModelSelectionLive({ ...route,+ providerId: reroute && shouldApplyExclusiveProviderRerouteLive(route.providerId)+ ? reroute : route.providerId,+ });+ },+ switchHarness: (route) => performSessionAgentSwitch(agentSwitchDeps, {+ sessionId, targetAgentKind: route.agentKind, model: route.model,+ providerId: route.providerId, effort: route.effort, fastMode: route.fastMode,+ applyNow: true, signal,+ }),+ applyModel: async (route) => {+ if (signal?.aborted) throw new Error('Scheduled model selection aborted');+ const result = await applySessionRuntimeSelection(sessionId, route.model, route.providerId,+ { effort: route.effort, fastMode: route.fastMode },+ { source: 'user', sessionLockHeld: true, applyingUserSelectionOnSend: true });+ if (result.deferred) throw new ScheduledModelSelectionBusyError('Scheduled model selection deferred');+ if (result.superseded || runtimeSelectionRequiresModelWindowConfirmation(result)) {+ throw new Error('Scheduled model selection could not be applied');+ }+ },+ });+ }await contextOverflowRolloverHolder?.prepareUnhealthySession(sessionId);- return release;+ return { release, selection: resolvedSelection };} catch (err) {release();throw err;diff --git a/apps/desktop/src/main/maker-ipc/schedule.ts b/apps/desktop/src/main/maker-ipc/schedule.tsindex 9fa3b35dd6..fa408955e5 100644--- a/apps/desktop/src/main/maker-ipc/schedule.ts+++ b/apps/desktop/src/main/maker-ipc/schedule.ts@@ -43,6 +43,7 @@ import { ipcMain, BrowserWindow, app } from 'electron';import type { AgentKind, Maker } from '@cindy/maker-core';import type {Scheduler,+ Schedule,CreateScheduleInput,UpdateScheduleInput,ListFilter,@@ -258,6 +259,31 @@ export function normalizeLegacyDeviceLinkIntervalClear<return { ...patch, intervalMs: undefined };}+/** Old Mobile submits a full form without the explicit Harness field. Normalize only+ * that trusted remote shape; prompt-only patches and local partial updates keep their semantics.+ * Compare with the saved form Harness (not its override) so an untouched old form cannot+ * accidentally undo an existing cross-Harness choice. Run inside updateFromCurrent's lock.+ */+export function normalizeLegacyDeviceLinkModelSelection(+ existing: Schedule,+ patch: UpdateScheduleInput,+ isRemoteInvoke: boolean,+): UpdateScheduleInput {+ if (!isRemoteInvoke || Object.prototype.hasOwnProperty.call(patch, 'modelAgentKind')+ || typeof patch.cronExpr !== 'string' || typeof patch.agentKind !== 'string'+ || (patch.model !== undefined && typeof patch.model !== 'string')+ || !Object.prototype.hasOwnProperty.call(patch, 'manual')+ || !Object.prototype.hasOwnProperty.call(patch, 'notify')+ || !(patch.targetSessionId ?? existing.targetSessionId)) return patch;+ const model = patch.model?.trim() || undefined;+ if (patch.agentKind === existing.agentKind && model === (existing.model?.trim() || undefined)) return patch;+ return { ...patch, modelAgentKind: model ? patch.agentKind : undefined,+ // The old bound form omits empty model/provider/effort and has no Fast control.+ // Clear the previous route when the visible selection changes instead of retaining+ // a provider or Fast preference belonging to the old Harness/model.+ model, providerId: patch.providerId, effort: patch.effort, fastMode: patch.fastMode ?? false };+}+function listAllTemplates(): ScheduleTemplate[] {const projectTemplates: ScheduleTemplate[] = [];return [...BUILTIN_TEMPLATES, ...projectTemplates];@@ -282,9 +308,11 @@ function buildCreateScheduleInput(manual: overrides.manual,intervalMs: overrides.intervalMs,agentKind: overrides.agentKind ?? template.agentKind ?? 'claude-code',+ modelAgentKind: overrides.modelAgentKind,model: overrides.model ?? template.model,providerId: overrides.providerId ?? template.providerId,effort: overrides.effort ?? template.effort,+ fastMode: overrides.fastMode ?? template.fastMode,workingDir: overrides.workingDir,useWorktree: overrides.useWorktree ?? template.useWorktree ?? false,targetSessionId: overrides.targetSessionId,@@ -351,9 +379,13 @@ export function registerScheduleHandlers(getMaker?: () => Maker | null): void {scheduler.updateFromCurrent(scheduleId, (existing) =>stabilizePreRunHookForUpdate(existing,- normalizeLegacyDeviceLinkIntervalClear(- normalizeNullableIntervalMs(- patch as UpdateScheduleInput & { intervalMs?: number | null },+ normalizeLegacyDeviceLinkModelSelection(+ existing,+ normalizeLegacyDeviceLinkIntervalClear(+ normalizeNullableIntervalMs(+ patch as UpdateScheduleInput & { intervalMs?: number | null },+ ),+ isDeviceLinkInvoke(),),isDeviceLinkInvoke(),),diff --git a/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts b/apps/desktop/src/main/maker-ipc/scheduledModelSelection.tsnew file mode 100644index 0000000000..9cde9a4ea9--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts@@ -0,0 +1,84 @@+import type { AgentKind, Effort } from '@cindy/maker-core';+import { effectiveSourceIdForModel, findCatalogModel, type ProviderView } from '@cindy/model-providers';+import { resolveCompatibleSessionRuntimeEffort } from './sessionRuntimeControl';++/** A saved automation choice, applied only while its target's send lock is held. */+export interface ScheduledModelSelection {+ agentKind: AgentKind;+ model: string;+ providerId: string | null;+ effort: Effort | null;+ fastMode: boolean;+}++export interface ScheduledModelSelectionLease {+ release: () => void;+ selection: ScheduledModelSelection;+}++export class ScheduledModelSelectionBusyError extends Error {}++interface ScheduledModelTarget {+ agentKind: AgentKind;+ status: string;+ remoteHostId?: string | null;+ orcaRole?: string | null;+}++/** Enforce the existing runtime boundary at save time as well as dispatch. */+export function assertScheduledHarnessSupported(+ target: ScheduledModelTarget | null,+ agentKind: AgentKind | undefined,+): void {+ if (target?.status !== 'active' || !agentKind || target.agentKind === agentKind) return;+ if (target.remoteHostId || target.orcaRole) {+ throw new Error('SSH and Orca automation targets must keep their current Harness');+ }+}++/** Saved selections may outlive catalog effort/Fast support; resolve the actual route first. */+export function resolveScheduledModelSelection(+ selection: ScheduledModelSelection,+ providers: ProviderView[],+): ScheduledModelSelection {+ const providerId = selection.providerId ??+ effectiveSourceIdForModel(providers, null, selection.model, selection.agentKind);+ const provider = providers.find((candidate) => candidate.id === providerId);+ const model = findCatalogModel(provider, selection.model, selection.agentKind, { exact: true });+ if (!provider?.connected || !model) {+ throw new Error(`Scheduled model "${selection.model}" is unavailable from provider "${providerId ?? 'default'}"`);+ }+ return {+ ...selection,+ providerId,+ effort: resolveCompatibleSessionRuntimeEffort(model, selection.effort),+ fastMode: selection.fastMode && model.supportsFastMode === true,+ };+}++/** Reuse the ordinary history handoff; never stage an automation intent on a busy task. */+export async function applyScheduledModelSelection(+ selection: ScheduledModelSelection,+ deps: {+ getTarget: () => Promise<ScheduledModelTarget | null>;+ isBusy: () => boolean;+ resolveSelection: (selection: ScheduledModelSelection) => Promise<ScheduledModelSelection>;+ switchHarness: (selection: ScheduledModelSelection) => Promise<{ engineReady: boolean; retryPending?: boolean }>;+ applyModel: (selection: ScheduledModelSelection) => Promise<void>;+ },+): Promise<ScheduledModelSelection> {+ const target = await deps.getTarget();+ // The runner owns missing/archived target recovery, including persistent-task rebinding.+ if (!target || target.status === 'archived' || target.status === 'deleted') {+ return deps.resolveSelection(selection);+ }+ if (deps.isBusy()) throw new ScheduledModelSelectionBusyError('Scheduled model selection waits for the current turn');+ assertScheduledHarnessSupported(target, selection.agentKind);+ const resolved = await deps.resolveSelection(selection);+ if (target.agentKind !== resolved.agentKind) {+ const result = await deps.switchHarness(resolved);+ if (!result.engineReady || result.retryPending) throw new Error('Scheduled Harness switch did not become ready');+ }+ await deps.applyModel(resolved);+ return resolved;+}diff --git a/apps/desktop/src/main/scheduler-host/__tests__/project-automation-loader.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/project-automation-loader.test.tsindex ba7549da39..a845af25de 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/project-automation-loader.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/project-automation-loader.test.ts@@ -1,12 +1,18 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';+import { promises as fs } from 'node:fs';+import { tmpdir } from 'node:os';+import * as path from 'node:path';import type { Schedule } from '@cindy/maker-scheduler';import {__testing,+ ProjectAutomationLoader,schedulesDiffer,type ProjectScheduleConfig,} from '../project-automation-loader';+import { scheduleCreateToRow, schedulePatchToRow, scheduleToCamel } from '../../localDb/mapper';+import { PROJECT_AUTOMATION_REL_SEGMENTS } from '../../../shared/projectAutomationPaths';const workingDir = 'C:\\project';@@ -86,3 +92,55 @@ describe('project automation provider reconciliation', () => {).toBe(true);});});++describe('project automation explicit Harness reconciliation', () => {+ it('detects marker-only changes, persists them, and clears them without losing the bound task', () => {+ const current: Schedule = { ...projectSchedule({ desktop: true, feishu: false }),+ agentKind: 'pi', model: 'test-model', persistentSession: true, targetSessionId: 'bound-codex' };+ const config = projectConfig({ agentKind: 'pi', modelAgentKind: 'pi', model: 'test-model', persistentSession: true });+ expect(schedulesDiffer(current, config, workingDir)).toBe(true);+ const input = __testing.scheduleConfigToUpdateInput(config, workingDir);+ expect(input.modelAgentKind).toBe('pi');+ const saved = scheduleToCamel({ ...scheduleCreateToRow(current),+ ...schedulePatchToRow({ modelAgentKind: input.modelAgentKind }),+ } as Parameters<typeof scheduleToCamel>[0]);+ expect(saved).toMatchObject({ modelAgentKind: 'pi', persistentSession: true, targetSessionId: 'bound-codex' });+ expect(schedulesDiffer(saved, config, workingDir)).toBe(false);++ const legacy = { ...config, modelAgentKind: undefined };+ expect(schedulesDiffer(saved, legacy, workingDir)).toBe(true);+ const clearInput = __testing.scheduleConfigToUpdateInput(legacy, workingDir);+ expect(clearInput).toHaveProperty('modelAgentKind', undefined);+ const cleared = scheduleToCamel({ ...scheduleCreateToRow(saved),+ ...schedulePatchToRow({ modelAgentKind: clearInput.modelAgentKind }),+ } as Parameters<typeof scheduleToCamel>[0]);+ expect(cleared.modelAgentKind).toBeUndefined();+ expect(cleared.targetSessionId).toBe('bound-codex');+ expect(schedulesDiffer(cleared, legacy, workingDir)).toBe(false);+ });++ it.each([+ { override: {}, valid: true },+ { override: { modelAgentKind: 'pi', model: 'test-model' }, valid: true },+ { override: { modelAgentKind: 'invalid', model: 'test-model' }, valid: false },+ { override: { modelAgentKind: 'pi' }, valid: false },+ ])('loads version 1 project files with compatible Harness validation: %j', async ({ override, valid }) => {+ const dir = await fs.mkdtemp(path.join(tmpdir(), 'cindy-project-harness-'));+ try {+ const file = path.join(dir, ...PROJECT_AUTOMATION_REL_SEGMENTS);+ await fs.mkdir(path.dirname(file), { recursive: true });+ const config = { ...projectConfig(), ...override };+ await fs.writeFile(file, JSON.stringify({ version: 1, schedules: [config] }));+ // File loading must not access the scheduler or database.+ const loader = new ProjectAutomationLoader({+ get scheduler(): never { throw new Error('file loading must not access the scheduler'); },+ get storage(): never { throw new Error('file loading must not access storage'); },+ getDb(): never { throw new Error('file loading must not access the database'); },+ logger: { warn: vi.fn(), debug: vi.fn() },+ });+ expect(await loader.loadProjectSchedules(dir)).toEqual(valid ? [config] : null);+ } finally {+ await fs.rm(dir, { recursive: true, force: true });+ }+ });+});diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.tsindex f0e55a8d76..560dcc7169 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts@@ -35,6 +35,7 @@ const mocks = vi.hoisted(() => ({setSessionProvider: vi.fn(),hydrateSessionProvider: vi.fn(),setSessionFastMode: vi.fn(),+ setSessionEffort: vi.fn(),isSessionInTurn: vi.fn(),}));@@ -46,6 +47,7 @@ vi.mock('../../maker-host/session-provider-store.js', () => ({vi.mock('../../maker-host/session-effort-store.js', () => ({setSessionFastMode: mocks.setSessionFastMode,+ setSessionEffort: mocks.setSessionEffort,}));vi.mock('../../localDb/ipc/messages.js', () => ({@@ -77,6 +79,9 @@ vi.mock('../runners/_shared', () => ({}));import { MakerScheduleRunner } from '../runner';+import { applyScheduledModelSelection, resolveScheduledModelSelection } from '../../maker-ipc/scheduledModelSelection';+import type { ProviderView } from '@cindy/model-providers';+import type { Scheduler } from '@cindy/maker-scheduler';type SessionSendOptions = Parameters<Session['send']>[1];type SendImpl = (@@ -221,11 +226,14 @@ function createRunnerHarness(model?: string;effort?: string;fastMode?: boolean;+ agentKind?: Session['agentKind'];workDir?: string;sdkSessionId?: string;} | null = null,opts: {sessionAlive?: boolean;+ acquirePendingAgentSwitch?: ConstructorParameters<typeof MakerScheduleRunner>[0]['acquirePendingAgentSwitch'];+ resolveModelSelection?: ConstructorParameters<typeof MakerScheduleRunner>[0]['resolveModelSelection'];activeSessions?: Session[];availableModels?: Array<{id: string;@@ -262,6 +270,8 @@ function createRunnerHarness(notifier,logger: createLogger(),checkModelRoute: opts.checkModelRoute,+ acquirePendingAgentSwitch: opts.acquirePendingAgentSwitch,+ resolveModelSelection: opts.resolveModelSelection,resolveRouteCopyCapabilities: opts.resolveRouteCopyCapabilities,resolveDefaultModelRoute: opts.resolveDefaultModelRoute,});@@ -294,6 +304,106 @@ describe('MakerScheduleRunner model selection', () => {mocks.getSessionRowSnapshot.mockResolvedValue({ status: 'active' });});+ describe('resolved automation selection survives the full fire', () => {+ it.each(['active', 'archived', 'missing'] as const)('uses the explicit Pi route for a %s Codex target', async (status) => {+ const h = createSessionHarness();+ Object.assign(h.session, { agentKind: 'pi', model: 'shared-model' });+ const release = vi.fn();+ const providers = [{+ id: 'selected', name: 'Selected', source: 'user', connected: true, agents: ['pi'],+ auth: { method: 'none' }, routing: { pi: {} },+ models: { pi: [{ id: 'shared-model', name: 'Shared', efforts: ['medium', 'high'], defaultEffort: 'high', supportsFastMode: false }] },+ }] as unknown as ProviderView[];+ mocks.getSessionRowSnapshot.mockResolvedValue(status === 'missing' ? null : { status });+ const harness = createRunnerHarness(h, { agentKind: 'pi', model: 'shared-model', effort: 'high', fastMode: false, workDir: '/work' }, {+ sessionAlive: status === 'active',+ // The merged copy deliberately conflicts with the selected provider copy.+ availableModels: [{ id: 'shared-model', efforts: ['low'], defaultEffort: 'low' }],+ acquirePendingAgentSwitch: async (_id, _signal, selection) => ({+ release,+ selection: await applyScheduledModelSelection(selection!, {+ getTarget: async () => status === 'missing' ? null : { agentKind: 'codex', status },+ isBusy: () => false,+ resolveSelection: async (choice) => resolveScheduledModelSelection(choice, providers),+ switchHarness: async () => ({ engineReady: true }),+ applyModel: async () => {},+ }),+ }),+ });+ const update = vi.fn(async () => undefined);+ harness.runner.attachScheduler({ update, isRunSilenced: () => false } as unknown as Scheduler);+ const schedule = baseSchedule({ agentKind: 'codex', modelAgentKind: 'pi', model: 'shared-model',+ targetSessionId: h.session.id, persistentSession: true, effort: 'ultra', fastMode: true });+ const saved = structuredClone(schedule);+ const opts = await fireToCompletion(harness, h, schedule);+ expect(opts).toMatchObject({ agentKind: 'pi', model: 'shared-model', providerId: 'selected', effort: 'high', fastMode: false });+ expect(mocks.setSessionFastMode).toHaveBeenLastCalledWith(h.session.id, false);+ expect(mocks.setSessionEffort).toHaveBeenLastCalledWith(h.session.id, 'high');+ expect(mocks.backfillSessionMeta).toHaveBeenCalledWith(expect.anything(), h.session.id,+ expect.objectContaining({ effort: 'high', fastMode: false, providerId: 'selected' }), expect.anything());+ expect(h.setEffort.mock.calls.flat()).not.toContain('low');+ expect(schedule).toEqual(saved);+ expect(release).toHaveBeenCalledTimes(1);+ if (status !== 'active') {+ expect(update).toHaveBeenCalledWith(schedule.id, { targetSessionId: undefined });+ expect(update).toHaveBeenCalledWith(schedule.id, { targetSessionId: h.session.id });+ expect(harness.createSession.mock.calls[0][0].id).not.toBe(schedule.targetSessionId);+ }+ });++ it.each([null, 'ultra', 'none'] as const)('resolves fresh explicit routes before creation, including %s effort', async (effort) => {+ const h = createSessionHarness();+ Object.assign(h.session, { agentKind: 'pi', model: 'shared-model' });+ const selectedEfforts = effort === 'none' ? [] : ['medium', 'high'];+ const providers = [{+ id: 'selected', name: 'Selected', connected: true, agents: ['pi'],+ models: { pi: [{ id: 'shared-model', name: 'Shared', efforts: selectedEfforts,+ defaultEffort: effort === 'none' ? null : 'high', supportsFastMode: false }] },+ }, {+ id: 'other', name: 'Other', connected: true, agents: ['pi'],+ models: { pi: [{ id: 'shared-model', name: 'Shared', efforts: ['ultra'], defaultEffort: 'ultra', supportsFastMode: true }] },+ }] as unknown as ProviderView[];+ const resolveModelSelection = vi.fn(async (choice) => resolveScheduledModelSelection(choice, providers));+ const harness = createRunnerHarness(h, null, {+ availableModels: [{ id: 'shared-model', efforts: ['ultra'], defaultEffort: 'ultra' }],+ resolveModelSelection,+ });+ const schedule = baseSchedule({ agentKind: 'pi', modelAgentKind: 'pi', model: 'shared-model',+ providerId: 'selected', effort: effort === null ? undefined : 'ultra', fastMode: true });+ const saved = structuredClone(schedule);+ const opts = await fireToCompletion(harness, h, schedule);+ const expectedEffort = effort === 'none' ? undefined : 'high';+ expect(opts).toMatchObject({ agentKind: 'pi', model: 'shared-model', providerId: 'selected',+ effort: expectedEffort, fastMode: false });+ expect(resolveModelSelection).toHaveBeenCalledTimes(1);+ expect(resolveModelSelection.mock.invocationCallOrder[0]).toBeLessThan(harness.createSession.mock.invocationCallOrder[0]);+ expect(mocks.setSessionFastMode).toHaveBeenLastCalledWith(h.session.id, false);+ expect(mocks.setSessionEffort).toHaveBeenLastCalledWith(h.session.id, expectedEffort ?? null);+ expect(mocks.backfillSessionMeta).toHaveBeenCalledWith(expect.anything(), h.session.id,+ expect.objectContaining({ effort: expectedEffort, fastMode: false, providerId: 'selected' }), expect.anything());+ expect(h.send).toHaveBeenCalledTimes(1);+ expect(schedule).toEqual(saved);+ });++ it('keeps resolved null effort instead of restoring saved or historical tiers', async () => {+ const h = createSessionHarness();+ Object.assign(h.session, { agentKind: 'pi', model: 'fixed-model' });+ const harness = createRunnerHarness(h, { agentKind: 'pi', model: 'fixed-model', effort: 'ultra', workDir: '/work' }, {+ sessionAlive: true,+ availableModels: [{ id: 'fixed-model', efforts: ['low'], defaultEffort: 'low' }],+ acquirePendingAgentSwitch: async () => ({ release: vi.fn(), selection: {+ agentKind: 'pi', model: 'fixed-model', providerId: 'selected', effort: null, fastMode: false,+ } }),+ });+ const opts = await fireToCompletion(harness, h, baseSchedule({ agentKind: 'pi', modelAgentKind: 'pi',+ model: 'fixed-model', targetSessionId: h.session.id, effort: 'high', fastMode: true }));+ expect(opts.effort).toBeUndefined();+ expect(h.setEffort).not.toHaveBeenCalled();+ expect(mocks.setSessionEffort).toHaveBeenLastCalledWith(h.session.id, null);+ expect(mocks.backfillSessionMeta.mock.calls.at(-1)?.[2].effort).toBeUndefined();+ });+ });+describe('effort reconcile —— fire 时按所选模型能力 clamp(issue #456)', () => {it('超额档(gpt-5.5 只到 xhigh + effort=max)→ createSession 收到 clamp 后的 xhigh', async () => {const h = createSessionHarness();diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.tsindex 0368e898e4..fd65048cfb 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts@@ -22,6 +22,8 @@ import { AcceptedCallbackDispatchCancelled } from '../../maker-ipc/acceptedCallbimport type { AgentEvent, Maker, Session, SessionSendResult } from '@cindy/maker-core';import { SCHEDULER_RUN_ID_VENDOR_OPTION } from '@cindy/maker-scheduler';import type { FireContext, Logger, Notifier, Schedule, ScheduleRun } from '@cindy/maker-scheduler';+import type { ProviderView } from '@cindy/model-providers';+import { resolveScheduledModelSelection } from '../../maker-ipc/scheduledModelSelection';import {setCodexAppliedCustomProviderRoutes,type CodexCustomProviderRoute,@@ -39,6 +41,7 @@ const mocks = vi.hoisted(() => ({setSessionProvider: vi.fn(),hydrateSessionProvider: vi.fn(),setSessionFastMode: vi.fn(),+ setSessionEffort: vi.fn(),}));vi.mock('../../maker-host/session-provider-store.js', () => ({@@ -49,6 +52,7 @@ vi.mock('../../maker-host/session-provider-store.js', () => ({vi.mock('../../maker-host/session-effort-store.js', () => ({setSessionFastMode: mocks.setSessionFastMode,+ setSessionEffort: mocks.setSessionEffort,}));vi.mock('../../localDb/ipc/messages.js', () => ({@@ -367,6 +371,8 @@ function createRunnerHarness(metaModel?: string;/** 停用轴裁决桩(缺省 = 不裁决,与生产未接线时一致)。 */checkModelRoute?: MakerScheduleRunnerDeps['checkModelRoute'];+ acquirePendingAgentSwitch?: MakerScheduleRunnerDeps['acquirePendingAgentSwitch'];+ resolveModelSelection?: MakerScheduleRunnerDeps['resolveModelSelection'];} = {},) {const logger = createLogger();@@ -380,7 +386,7 @@ function createRunnerHarness(getSession: vi.fn(() => liveSession),getSessionMeta: vi.fn(async () => ({id: SESSION_ID,- agentKind: 'claude-code',+ agentKind: session.agentKind,workDir: '/tmp/bound',model: opts.metaModel ?? 'claude-opus-4-6',effort: opts.metaEffort,@@ -403,6 +409,8 @@ function createRunnerHarness(logger,schedulerQueue,checkModelRoute: opts.checkModelRoute,+ acquirePendingAgentSwitch: opts.acquirePendingAgentSwitch,+ resolveModelSelection: opts.resolveModelSelection,});return {runner,@@ -438,6 +446,131 @@ beforeEach(() => {});describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {+ it('dispatches a fresh implicit provider route using the resolved fire-local schedule', async () => {+ const h = createSessionHarness(async () => ({ accepted: true }));+ Object.assign(h.session, { agentKind: 'pi', model: 'shared-model' });+ mocks.setSessionProvider.mockImplementationOnce((_sessionId, providerId) => {+ mocks.getSessionProvider.mockReturnValue(providerId);+ });+ const providers: ProviderView[] = [{+ id: 'selected', name: 'Selected', connected: true, agents: ['pi'],+ source: 'user', auth: { method: 'apiKey' },+ routing: { pi: { upstream: 'https://selected.invalid/v1', authStrategy: 'none', wireProtocol: 'openai-responses' } },+ models: { pi: [{ id: 'shared-model', name: 'Shared', mode: 'chat', contextWindow: 128_000, efforts: ['high'],+ defaultEffort: 'high', supportsFastMode: false }] },+ }];+ const resolveModelSelection = vi.fn<NonNullable<MakerScheduleRunnerDeps['resolveModelSelection']>>(+ async (choice) => resolveScheduledModelSelection(choice, providers),+ );+ const checkModelRoute = vi.fn<NonNullable<MakerScheduleRunnerDeps['checkModelRoute']>>(+ async () => ({ kind: 'pass' }),+ );+ const queue = createQueueHarness({ busy: false });+ const { runner, maker, notifier } = createRunnerHarness(h.session, queue.deps, {+ resolveModelSelection, checkModelRoute,+ });+ vi.mocked(maker.isSessionAlive).mockReturnValue(false);+ const schedule = heartbeatSchedule({ targetSessionId: undefined, workingDir: '/work',+ agentKind: 'pi', modelAgentKind: 'pi', model: 'shared-model', fastMode: true });+ const saved = structuredClone(schedule);+ const fire = runner.fire(schedule, createFireContext());+ const result = fire.catch((error: unknown) => error);+ await vi.waitFor(() => expect(queue.enqueueCalls).toHaveLength(1));+ expect(resolveModelSelection).toHaveBeenCalledWith(expect.objectContaining({ providerId: null }));+ expect(maker.createSession).toHaveBeenCalledWith(expect.objectContaining({+ agentKind: 'pi', model: 'shared-model', providerId: 'selected', effort: 'high', fastMode: false,+ }));+ // A fresh handle was already created on this route. The store and queue+ // baseline must agree before acceptance checks for credential changes.+ expect(mocks.setSessionProvider).toHaveBeenLastCalledWith(SESSION_ID, 'selected');+ expect(mocks.setSessionProvider.mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(queue.deps.enqueuePrompt).mock.invocationCallOrder[0],+ );+ await queue.accept();+ expect(checkModelRoute).toHaveBeenLastCalledWith('pi', 'shared-model', 'selected');+ expect(mocks.setSessionProvider).toHaveBeenLastCalledWith(SESSION_ID, 'selected');+ expect(mocks.backfillSessionMeta.mock.calls.at(-1)?.[2]).toMatchObject({+ providerId: 'selected', effort: 'high', fastMode: false,+ });+ await vi.waitFor(() => expect(h.listenerCount()).toBe(1));+ h.emit({ type: 'done', data: {}, source: 'pi' });+ await expect(result).resolves.toMatchObject({ sessionId: SESSION_ID });+ expect(latestNotifiedRun(notifier).status).toBe('success');+ expect(schedule).toEqual(saved);+ });++ it.each([+ { agentKind: 'pi' as const, effort: 'high' as const, fastMode: false },+ { agentKind: 'pi' as const, effort: null, fastMode: false },+ { agentKind: 'pi' as const, effort: 'high' as const, fastMode: true },+ { agentKind: 'codex' as const, effort: 'high' as const, fastMode: false },+ ])('keeps the resolved selection through queue acceptance: %j', async (axes) => {+ const h = createSessionHarness(async () => ({ accepted: true }));+ const setFastMode = vi.fn(async () => {});+ Object.assign(h.session, { agentKind: axes.agentKind, model: 'shared-model', setFastMode });+ mocks.getSessionProvider.mockReturnValue('selected');+ const queue = createQueueHarness({ busy: false });+ const release = vi.fn();+ const { runner, maker } = createRunnerHarness(h.session, queue.deps, {+ metaModel: 'shared-model', metaEffort: 'ultra', metaFastMode: true,+ availableModels: [{ id: 'shared-model', efforts: ['low'], defaultEffort: 'low' }],+ acquirePendingAgentSwitch: async () => ({ release, selection: {+ model: 'shared-model', providerId: 'selected', ...axes,+ } }),+ });+ const schedule = heartbeatSchedule({ agentKind: axes.agentKind, modelAgentKind: axes.agentKind,+ model: 'shared-model', effort: 'ultra', fastMode: true });+ const saved = structuredClone(schedule);+ const fire = runner.fire(schedule, createFireContext());+ await vi.waitFor(() => expect(queue.enqueueCalls).toHaveLength(1));+ expect(release).toHaveBeenCalledTimes(1);+ expect(maker.createSession).toHaveBeenCalledWith(expect.objectContaining({+ effort: axes.effort ?? undefined, fastMode: axes.fastMode, providerId: 'selected',+ }));+ h.setEffort.mockClear();+ mocks.setSessionFastMode.mockClear();+ await queue.accept();+ if (axes.agentKind === 'pi') expect(mocks.setSessionFastMode).toHaveBeenLastCalledWith(SESSION_ID, axes.fastMode);+ else expect(setFastMode).toHaveBeenLastCalledWith(axes.fastMode);+ expect(mocks.setSessionEffort).toHaveBeenLastCalledWith(SESSION_ID, axes.effort);+ if (axes.effort) expect(h.setEffort).toHaveBeenLastCalledWith(axes.effort);+ else expect(h.setEffort).not.toHaveBeenCalled();+ expect(mocks.backfillSessionMeta.mock.calls.at(-1)?.[2]).toMatchObject({+ effort: axes.effort ?? undefined, fastMode: axes.fastMode, providerId: 'selected',+ });+ await vi.waitFor(() => expect(h.listenerCount()).toBe(1));+ h.emit({ type: 'done', data: {}, source: 'pi' });+ await fire;+ expect(schedule).toEqual(saved);+ });++ it.each(['harness-changed', 'effort-failed', 'fast-failed'] as const)(+ 'blocks queued dispatch if the resolved selection cannot be honored (%s)', async (failure) => {+ const h = createSessionHarness(async () => ({ accepted: true }));+ const setFastMode = vi.fn(async () => {});+ Object.assign(h.session, { agentKind: 'codex', model: 'shared-model', setFastMode });+ mocks.getSessionProvider.mockReturnValue('selected');+ const queue = createQueueHarness({ busy: false });+ const { runner } = createRunnerHarness(h.session, queue.deps, {+ metaModel: 'shared-model', metaEffort: 'high',+ acquirePendingAgentSwitch: async () => ({ release: vi.fn(), selection: {+ agentKind: 'codex', model: 'shared-model', providerId: 'selected', effort: 'high', fastMode: false,+ } }),+ });+ const fire = runner.fire(heartbeatSchedule({ agentKind: 'codex', modelAgentKind: 'codex',+ model: 'shared-model', effort: 'ultra', fastMode: true }), createFireContext());+ const result = fire.catch((error: unknown) => error);+ await vi.waitFor(() => expect(queue.enqueueCalls).toHaveLength(1));+ if (failure === 'harness-changed') Object.assign(h.session, { agentKind: 'pi' });+ if (failure === 'effort-failed') h.setEffort.mockRejectedValue(new Error('unavailable'));+ if (failure === 'fast-failed') setFastMode.mockRejectedValue(new Error('unavailable'));+ await queue.accept();+ expect(await result).toBeInstanceOf(Error);+ expect(h.send).not.toHaveBeenCalled();+ expect(h.session.abort).toHaveBeenCalled();+ },+ );+it.each(['permission', 'plan', 'switching', 'missing', 'replaced'])('defers queued routine acceptance after %s changes and runs with a fresh snapshot', async (change) => {const h = createSessionHarness(async () => ({ accepted: true }));const queue = createQueueHarness({ busy: true });diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.tsindex f8dd2947e1..37cc535185 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts@@ -1,3 +1,4 @@+import type { ScheduledModelSelection } from '../../maker-ipc/scheduledModelSelection';import { describe, expect, it, vi, beforeEach } from 'vitest';import type {@@ -53,6 +54,7 @@ vi.mock('../runners/_shared', () => ({}));import { MakerScheduleRunner } from '../runner';+import { ScheduledModelSelectionBusyError } from '../../maker-ipc/scheduledModelSelection';import { isHeadlessGhostSetupTurn } from '../../mcp-integrations/ghostSetupInteractionSurface';type SessionSendOptions = Parameters<Session['send']>[1];@@ -299,7 +301,7 @@ describe('MakerScheduleRunner send outcome policy', () => {expect(notifier.notify).not.toHaveBeenCalled();});- it('applies a deferred switch before heartbeat meta lookup and creates the target engine session', async () => {+ it.each([false, true])('applies the route before heartbeat meta lookup (explicit selection: %s)', async (explicit) => {const order: string[] = [];const h = createSessionHarness(async () => {order.push('send');@@ -311,9 +313,9 @@ describe('MakerScheduleRunner send outcome policy', () => {const releaseAgentSwitchLock = vi.fn(() => {order.push('release');});- const acquirePendingAgentSwitch = vi.fn(async () => {+ const acquirePendingAgentSwitch = vi.fn(async (_id: string, _signal?: AbortSignal, selection?: ScheduledModelSelection) => {order.push('apply');- return releaseAgentSwitchLock;+ return selection ? { release: releaseAgentSwitchLock, selection } : releaseAgentSwitchLock;});const { runner, maker } = createRunnerHarness(h.session, { acquirePendingAgentSwitch });vi.mocked(maker.getSessionMeta).mockImplementation(async () => {@@ -340,14 +342,21 @@ describe('MakerScheduleRunner send outcome policy', () => {baseSchedule({targetSessionId: 'scheduler-session',agentKind: 'claude-code',- model: undefined,+ model: explicit ? 'gpt-5.5-codex' : undefined,+ ...(explicit ? { modelAgentKind: 'codex' as const, providerId: 'xd', effort: 'high', fastMode: true } : {}),}),ctx,),).rejects.toThrow(/cancelled-before-dispatch/);expect(order.slice(0, 2)).toEqual(['apply', 'meta']);- expect(acquirePendingAgentSwitch).toHaveBeenCalledWith('scheduler-session', ctx.signal);+ if (explicit) {+ expect(acquirePendingAgentSwitch).toHaveBeenCalledWith('scheduler-session', ctx.signal, {+ agentKind: 'codex', model: 'gpt-5.5-codex', providerId: 'xd', effort: 'high', fastMode: true,+ });+ } else {+ expect(acquirePendingAgentSwitch).toHaveBeenCalledWith('scheduler-session', ctx.signal);+ }expect(maker.createSession).toHaveBeenCalledWith(expect.objectContaining({id: 'scheduler-session',@@ -359,6 +368,19 @@ describe('MakerScheduleRunner send outcome policy', () => {expect(order).toEqual(['apply', 'meta', 'send', 'release']);});++ it('defers an explicit selection when the target is busy without dispatching', async () => {+ const h = createSessionHarness(async () => ({ accepted: true }));+ const { runner, maker } = createRunnerHarness(h.session, {+ acquirePendingAgentSwitch: vi.fn(async () => { throw new ScheduledModelSelectionBusyError('busy'); }),+ });+ const result = await runner.fire(baseSchedule({ targetSessionId: 'scheduler-session',+ modelAgentKind: 'pi', model: 'grok-4.6' }), createFireContext());+ expect(result).toMatchObject({ deferred: true, sessionId: 'scheduler-session' });+ expect(maker.createSession).not.toHaveBeenCalled();+ expect(h.send).not.toHaveBeenCalled();+ });+it('releases the heartbeat route lock before deferring to recent user activity', async () => {const order: string[] = [];const h = createSessionHarness(async () => ({ accepted: true }));diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerShared.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerShared.test.tsindex 9c614446ae..df822bc053 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerShared.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerShared.test.ts@@ -55,6 +55,13 @@ function createSessionHarness() {}describe('backfillSessionMeta', () => {+ it.each([true, false])('persists the resolved Fast state (%s), including clearing a stale true', async (fastMode) => {+ const { db, set } = createUpdateDb();+ const { logger } = createLogger();+ await backfillSessionMeta(db, 'sess-1', { fastMode }, logger);+ expect(set).toHaveBeenCalledWith(expect.objectContaining({ fastMode }));+ });+it('preserves teammate permissions while updating routine runtime metadata', async () => {const { db, set } = createUpdateDb();const { logger } = createLogger();diff --git a/apps/desktop/src/main/scheduler-host/__tests__/storage.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/storage.test.tsindex 27fde5eaa2..a08950048a 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/storage.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/storage.test.ts@@ -146,6 +146,25 @@ describe('scheduleToCamel', () => {});describe('scheduleCreateToRow', () => {+ it('round-trips an explicit model Harness and clears it without changing the legacy agent', () => {+ const original = baseSchedule({ agentKind: 'codex', modelAgentKind: 'pi', model: 'test-model', providerId: 'custom', fastMode: true });+ const row = scheduleCreateToRow(original);+ expect(row.modelAgentKind).toBe('pi');+ expect(scheduleToCamel(row as ScheduleRowLike)).toEqual(original);+ expect(scheduleCreateToRow(baseSchedule()).modelAgentKind).toBeNull();+ expect(schedulePatchToRow({ modelAgentKind: undefined })).toEqual({ modelAgentKind: null });+ expect(schedulePatchToRow({ name: 'renamed' })).not.toHaveProperty('modelAgentKind');+ const followed = scheduleToCamel({ ...row, ...schedulePatchToRow({+ modelAgentKind: undefined, model: undefined, providerId: undefined,+ effort: undefined, fastMode: undefined,+ }) } as ScheduleRowLike);+ expect(followed).toMatchObject({ agentKind: 'codex', fastMode: false });+ expect(followed.modelAgentKind).toBeUndefined();+ expect(followed.model).toBeUndefined();+ expect(followed.providerId).toBeUndefined();+ expect(followed.effort).toBeUndefined();+ });+it('拆 notify 为两列', () => {const row = scheduleCreateToRow(baseSchedule({ notify: { desktop: false, feishu: true } }));expect(row.notifyDesktop).toBe(false);diff --git a/apps/desktop/src/main/scheduler-host/index.ts b/apps/desktop/src/main/scheduler-host/index.tsindex 69e52aad15..dcbf5ba8fa 100644--- a/apps/desktop/src/main/scheduler-host/index.ts+++ b/apps/desktop/src/main/scheduler-host/index.ts@@ -25,9 +25,12 @@ import type { FeishuIM } from '@cindy/im';import { dialogueWorkspaceRootDir } from '../localDb/dialogueWorkspace';import { sessions } from '../localDb/schema.js';import { isReviewSessionSource } from '../../shared/sessionSource.js';+import { dbToMakerAgentKind } from '../../shared/agentKindConversion.js';+import { assertScheduledHarnessSupported } from '../maker-ipc/scheduledModelSelection';import {resolveDefaultScheduleRoute,resolveRouteCopyCapabilities,+ resolveScheduledModelSelectionLive,verdictForModelRoute,} from '../maker-host/model-route-guard-live.js';import { getAgentIslandService } from '../agent-island/service.js';@@ -109,6 +112,7 @@ async function startSchedulerInternal(deps: StartSchedulerDeps): Promise<SchedulbeforeDispatchUserTurn: deps.beforeDispatchUserTurn,onUndispatchedUserTurn: deps.onUndispatchedUserTurn,acquirePendingAgentSwitch: acquirePendingAgentSwitchForDirectSend,+ resolveModelSelection: resolveScheduledModelSelectionLive,onSessionCreated: broadcastSessionCreated,// 停用轴裁决:每次 fire 前判保存路由是否已被用户停用(见 runner deps 注释)。checkModelRoute: verdictForModelRoute,@@ -173,16 +177,20 @@ async function startSchedulerInternal(deps: StartSchedulerDeps): Promise<Schedul// Review sessions are host-owned read-only tasks, not normal unattended// automation targets. Re-read their durable source for CRUD and every fire// so renderer filtering or a restored schedule row cannot bypass isolation.- validateTargetSession: async (targetSessionId) => {+ validateTargetSession: async (targetSessionId, _operation, selection) => {const [row] = await deps.getDb()- .select({ source: sessions.source })+ .select({ source: sessions.source, agentKind: sessions.agentKind,+ status: sessions.status, remoteHostId: sessions.remoteHostId, orcaRole: sessions.orcaRole }).from(sessions).where(eq(sessions.id, targetSessionId)).limit(1);if (isReviewSessionSource(row?.source)) {throw new Error('Review tasks cannot be targets of scheduled automations');}+ assertScheduledHarnessSupported(row ? {+ ...row, agentKind: dbToMakerAgentKind(row.agentKind),+ } : null, selection.modelAgentKind);},// 卡死收口的通知出口。通知投递平时住在两个 runner 里(它们各自持 notifier),而// 卡死收口刻意绕过 runner —— 要么它压根不返回、要么它把守卫 abort 当普通中断处理。diff --git a/apps/desktop/src/main/scheduler-host/project-automation-loader.ts b/apps/desktop/src/main/scheduler-host/project-automation-loader.tsindex 340c211275..4d789a8b06 100644--- a/apps/desktop/src/main/scheduler-host/project-automation-loader.ts+++ b/apps/desktop/src/main/scheduler-host/project-automation-loader.ts@@ -48,6 +48,8 @@ export interface ProjectScheduleConfig {manual?: boolean;intervalMs?: number;agentKind?: 'claude-code' | 'codex' | 'pi';+ /** 显式模型选择的 Harness;省略时保留旧配置的跟随绑定任务语义。 */+ modelAgentKind?: 'claude-code' | 'codex' | 'pi';model?: string;/** 可选:显式来源(供应商)id。省略 → 走原生默认来源(与旧配置字节级一致)。详见 Schedule.providerId。 */providerId?: string;@@ -453,6 +455,8 @@ function scheduleConfigToCreateInput(manual: config.manual ?? false,intervalMs: config.intervalMs,agentKind: config.agentKind ?? 'claude-code',+ // 恒带 key:配置删除显式选择后,reconcile 清除已保存的标记。+ modelAgentKind: config.modelAgentKind,model: config.model,providerId: config.providerId,effort: config.effort,@@ -493,6 +497,7 @@ export function schedulesDiffer(schedule.manual !== expected.manual ||schedule.intervalMs !== expected.intervalMs ||schedule.agentKind !== expected.agentKind ||+ schedule.modelAgentKind !== expected.modelAgentKind ||schedule.model !== expected.model ||(schedule.providerId ?? undefined) !== (expected.providerId ?? undefined) ||schedule.effort !== expected.effort ||@@ -561,6 +566,8 @@ function isProjectScheduleConfig(value: unknown): value is ProjectScheduleConfigoptionalBoolean(config.manual) &&optionalNumber(config.intervalMs) &&optionalAgentKind(config.agentKind) &&+ optionalAgentKind(config.modelAgentKind) &&+ (config.modelAgentKind === undefined || (typeof config.model === 'string' && config.model.trim() !== '')) &&optionalString(config.model) &&optionalString(config.providerId) &&optionalString(config.effort) &&diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.tsindex 56fdd6712a..a7848cd6ec 100644--- a/apps/desktop/src/main/scheduler-host/runner.ts+++ b/apps/desktop/src/main/scheduler-host/runner.ts@@ -1,3 +1,4 @@+import { ScheduledModelSelectionBusyError, type ScheduledModelSelection, type ScheduledModelSelectionLease } from '../maker-ipc/scheduledModelSelection';import { UI_ACTION_TRIGGER_PREFIX } from '../../shared/interruptedTurn.js';import { routinePermissionSnapshot } from './routinePermission.js';/**@@ -68,7 +69,7 @@ import {setSessionProvider,hydrateSessionProvider,} from '../maker-host/session-provider-store.js';-import { setSessionFastMode } from '../maker-host/session-effort-store.js';+import { setSessionEffort, setSessionFastMode } from '../maker-host/session-effort-store.js';import {CredentialModeSwitchBusyError,isCodexThreadModelProviderIdentityMismatch,@@ -243,7 +244,9 @@ export interface MakerScheduleRunnerDeps {* 锁住 heartbeat session、落实 deferred switch 并 bootstrap 新 live session。* runner 在 Session.send 返回后 release。*/- acquirePendingAgentSwitch?: (sessionId: string, signal?: AbortSignal) => Promise<() => void>;+ acquirePendingAgentSwitch?: (sessionId: string, signal?: AbortSignal, selection?: ScheduledModelSelection) => Promise<(() => void) | ScheduledModelSelectionLease>;+ /** Resolve the same provider-specific snapshot for fresh explicit choices. */+ resolveModelSelection?: (selection: ScheduledModelSelection) => Promise<ScheduledModelSelection>;/** 新建可见会话落库后通知本机窗口与 device-link 列表订阅者。 */onSessionCreated?: (sessionId: string) => void;/** 可选:撞忙排队桥。未注入时心跳撞忙回退为顺延(deferFire)旧行为。 */@@ -660,14 +663,44 @@ export class MakerScheduleRunner implements ScheduleRunner {// 持续会话当前选定的来源(供应商)id —— schedule.providerId 留空时沿用它// (与 model 留空沿用 meta.model 对称)。取自 sessions.provider_id 快照,null=未选。let heartbeatProviderId: string | null = null;+ // Fire-local catalog snapshot. Keep the saved preferences untouched, but never+ // re-read their stale effort/Fast after the host has resolved the actual route.+ let resolvedSelection: ScheduledModelSelection | undefined;// 2. heartbeat archived/missing 兜底if (isHeartbeat) {// 直发路径不经过 makerSendTransaction。先落实 pending switch,再读取 meta/row,// 才能让本轮 createSession 与 send 都指向切换后的 live engine。throwIfFireAborted(ctx.signal, 'credential switch setup');- holder.releaseAgentSwitchLock =- (await this.deps.acquirePendingAgentSwitch?.(sessionId, ctx.signal)) ?? undefined;+ const selection: ScheduledModelSelection | undefined = schedule.modelAgentKind && schedule.model?.trim()+ ? { agentKind: schedule.modelAgentKind, model: schedule.model,+ providerId: schedule.providerId?.trim() || null,+ effort: (schedule.effort as Effort | undefined) ?? null, fastMode: schedule.fastMode === true }+ : undefined;+ if (selection && this.deps.schedulerQueue?.isSessionBusy(sessionId)) {+ return this.failOrDeferSessionRunning(schedule, ctx, sessionId, true);+ }+ if (selection && !this.deps.acquirePendingAgentSwitch) {+ throw new Error('Scheduled model selection is not available');+ }+ try {+ const lease = await (selection+ ? this.deps.acquirePendingAgentSwitch?.(sessionId, ctx.signal, selection)+ : this.deps.acquirePendingAgentSwitch?.(sessionId, ctx.signal));+ holder.releaseAgentSwitchLock = typeof lease === 'function' ? lease : lease?.release;+ if (selection) {+ if (!lease || typeof lease === 'function') throw new Error('Scheduled model selection was not resolved');+ resolvedSelection = lease.selection;+ schedule = { ...schedule, agentKind: resolvedSelection.agentKind,+ model: resolvedSelection.model, providerId: resolvedSelection.providerId ?? undefined,+ effort: resolvedSelection.effort ?? undefined, fastMode: resolvedSelection.fastMode };+ }+ } catch (error) {+ if (error instanceof ScheduledModelSelectionBusyError) {+ return this.failOrDeferSessionRunning(schedule, ctx, sessionId, true);+ }+ throw error;+ }throwIfFireAborted(ctx.signal, 'credential switch setup');const [meta, row] = await Promise.all([this.deps.maker.getSessionMeta(sessionId).catch(() => null),@@ -728,6 +761,11 @@ export class MakerScheduleRunner implements ScheduleRunner {// 升级为可见排队)。B1 活跃礼让仍优先:用户正在对话时连队都不排,顺延到// 用户空闲再说。桥未注入(测试/启动早期)时走原直发路径,行为不变。if (this.deps.schedulerQueue?.isSessionBusy(sessionId)) {+ if (selection) {+ holder.releaseAgentSwitchLock?.();+ holder.releaseAgentSwitchLock = undefined;+ return this.failOrDeferSessionRunning(schedule, ctx, sessionId, true);+ }const liveSession = this.deps.maker.getSession(sessionId);if (liveSession &&@@ -826,9 +864,9 @@ export class MakerScheduleRunner implements ScheduleRunner {// 都空时按 agentKind 兜底 (与 renderer schedulerFallbackModel 同源),// 不留空字符串 — UI picker 显示 placeholder。// 普通 schedule 沿用既有默认权限;伙伴例行任务继承当前伙伴的权限和计划模式。- const effectiveAgentKind = isHeartbeat+ const effectiveAgentKind = resolvedSelection?.agentKind ?? (isHeartbeat? (heartbeatAgentKind ?? schedule.agentKind)- : schedule.agentKind;+ : (schedule.modelAgentKind ?? schedule.agentKind));const rawModel = schedule.model?.trim()? schedule.model: isHeartbeat@@ -887,7 +925,7 @@ export class MakerScheduleRunner implements ScheduleRunner {// 确保「不影响 Claude」。heartbeat 沿用 session meta 里的 fast 态,非 heartbeat 取 schedule。let fastMode =effectiveAgentKind === 'codex' || effectiveAgentKind === 'pi'- ? isHeartbeat+ ? isHeartbeat && !schedule.modelAgentKind? heartbeatFastMode: schedule.fastMode: undefined;@@ -912,23 +950,40 @@ export class MakerScheduleRunner implements ScheduleRunner {reroutedProviderId = verdict.providerId;}}+ if (!isHeartbeat && schedule.modelAgentKind && !resolvedSelection) {+ if (!this.deps.resolveModelSelection) throw new Error('Scheduled model selection is not available');+ resolvedSelection = await this.deps.resolveModelSelection({+ agentKind: effectiveAgentKind, model, providerId: createProviderId,+ effort: (schedule.effort as Effort | undefined) ?? null, fastMode: fastMode === true,+ });+ createProviderId = resolvedSelection.providerId;+ fastMode = resolvedSelection.fastMode;+ schedule = { ...schedule, agentKind: resolvedSelection.agentKind,+ model: resolvedSelection.model, providerId: resolvedSelection.providerId ?? undefined,+ effort: resolvedSelection.effort ?? undefined, fastMode: resolvedSelection.fastMode };+ }// issue #456:未门控入口(定时任务 fire)按所选模型自报的 supported efforts 把 effort// clamp 到最高兼容档,避免把模型不支持的档(如 gpt-5.5 + max/ultra)透给上游被拒。// 模型已声明支持的档原样保留(不降级 —— 保 #352 交互式口径);schedule 配置本身不回写,// 只影响本次 fire 的运行值(该模型日后支持该档时自动生效)。直发 / 排队两路径共用// reconcileEffortForModel(见其注释),口径一致;lookup 失败不阻断 headless 运行。- let reconciledEffort = this.reconcileEffortForModel(- effectiveAgentKind,- model,- schedule.effort,- schedule.id,- );+ if (resolvedSelection && createProviderId !== resolvedSelection.providerId) {+ throw new Error('Scheduled model route changed after selection; retry with the current catalog');+ }+ let reconciledEffort = resolvedSelection+ ? resolvedSelection.effort ?? undefined+ : this.reconcileEffortForModel(+ effectiveAgentKind,+ model,+ schedule.effort,+ schedule.id,+ );// 隐式改道后的来源级 reconcile(PR #744 review 第二十七轮):上面的 clamp 用的是// merged capability,分辨不出来源差异 —— 改道后的落地拷贝 effort 支持可能更窄、// 可能不支持 Fast,原样透传会被上游拒。按 (verdict.providerId, model) 的拷贝重查:// 仍支持则保留,不支持取该拷贝默认档(与 model-route-guard withEffort 同口径);// Fast 不支持则清掉。查不到 / 目录故障保持 merged 口径,不阻断 headless 运行。- if (reroutedProviderId && this.deps.resolveRouteCopyCapabilities) {+ if (!resolvedSelection && reroutedProviderId && this.deps.resolveRouteCopyCapabilities) {try {const copy = await this.deps.resolveRouteCopyCapabilities(effectiveAgentKind,@@ -1190,7 +1245,12 @@ export class MakerScheduleRunner implements ScheduleRunner {// 当前 effort(heartbeatEffort)而非 undefined —— 否则「只换 model、不改 effort」换到不支持// 当前档的模型时,reconcile(undefined) 返回 undefined、heartbeatEffortChanged=false,会话仍带// 旧的 max 跑到新的 capped 模型被上游拒(PR #479 review「Clamp followed effort when switching models」)。- const desiredEffort = schedule.effort ? schedule.effort : heartbeatEffort;+ if (resolvedSelection && runtimeModel !== resolvedSelection.model) {+ throw new Error('Scheduled model selection did not reach the live session');+ }+ const desiredEffort = resolvedSelection+ ? resolvedSelection.effort ?? undefined+ : schedule.effort || heartbeatEffort;// runtimeModel===model 且未走 follow(desiredEffort===schedule.effort)时直接复用上方// createSession 已算好的 reconciledEffort,不重复 lookup / 不重复打 reconcile 日志。const runtimeReconciledEffort =@@ -1221,10 +1281,15 @@ export class MakerScheduleRunner implements ScheduleRunner {// 仅当 fresh 且要落的档 == createSession 已应用的档时,setEffort 只是幂等兜底,失败可照常落库。if (reusedLiveSession || runtimeReconciledEffort !== reconciledEffort)effortSwitchApplied = false;+ if (resolvedSelection) throw new Error('Scheduled effort selection could not be applied', { cause: err });this.deps.logger.warn?.('[runner] heartbeat setEffort failed (non-fatal)', err);}}+ if (resolvedSelection && effortSwitchApplied) {+ setSessionEffort(session.id, resolvedSelection.effort);+ }+// 4.4.2 per-session 来源(供应商)注入。语义与 model 对称、但更简单 —— provider 走// 独立的内存 store(session-provider-store),不依赖 session 是否复用,写入即对下一个// 请求生效,故无需 fresh/reuse 落库区分。@@ -1234,8 +1299,12 @@ export class MakerScheduleRunner implements ScheduleRunner {// 时内存为空,这一步把 DB 里的 provider_id 补回来 → honor 聊天所选来源)。// - 非 heartbeat Claude 且留空 → 把实时解析出的默认来源显式写入,确保 spawn// credential mode、proxy 路由、coordinator baseline 与落库使用同一个 provider。+ // - fresh 显式模型选择 → 同步本轮解析来源,避免入队后把新 handle 的已选路由+ // 误判成凭证切换;不把本轮默认来源回写到自动化偏好。// - 其它非 heartbeat 且留空 → 保持既有默认路由语义。- if (explicitProviderId) {+ if (!isHeartbeat && resolvedSelection) {+ setSessionProvider(session.id, resolvedSelection.providerId);+ } else if (explicitProviderId) {setSessionProvider(session.id, explicitProviderId);} else if (reroutedProviderId) {// 停用轴 reroute:隐式默认落点被停用,fire 前已裁决出启用替代 —— 复用的 live@@ -1285,6 +1354,7 @@ export class MakerScheduleRunner implements ScheduleRunner {// 落 runtimeReconciledEffort(按实际运行模型 clamp 后的值),session 行 effort 反映真跑的档,// 不落超额的原始配置,也不落「为一个没切成功的模型 clamp 出来的」错档(PR #479 review)。effort: effortSwitchApplied ? runtimeReconciledEffort : undefined,+ fastMode: resolvedSelection?.fastMode,// heartbeat 模型被 schedule.model 覆盖时落库 —— chat UI picker 与// 下次 fire 读到的 meta.model 必须跟实际运行一致(4.4.1 已 setModel)。// 同 effort: 复用路径 setModel 失败时跳过, 留给下次 fire 重试。@@ -1340,6 +1410,8 @@ export class MakerScheduleRunner implements ScheduleRunner {{model: session.model ?? model,effort: runtimeReconciledEffort,+ fastMode,+ resolvedSelection,providerId: getSessionProvider(session.id),},{@@ -1740,6 +1812,7 @@ export class MakerScheduleRunner implements ScheduleRunner {model?: string;effort?: string;fastMode?: boolean;+ resolvedSelection?: ScheduledModelSelection;providerId: string | null;},options?: { sessionAlreadyBound?: boolean; onAccepted?: () => void },@@ -1780,6 +1853,7 @@ export class MakerScheduleRunner implements ScheduleRunner {model?: string;effort?: string;fastMode?: boolean;+ resolvedSelection?: ScheduledModelSelection;providerId: string | null;},markHeadlessTurnDispatched: () => void,@@ -2256,6 +2330,7 @@ export class MakerScheduleRunner implements ScheduleRunner {model?: string;effort?: string;fastMode?: boolean;+ resolvedSelection?: ScheduledModelSelection;providerId: string | null;},): Promise<void> {@@ -2293,6 +2368,11 @@ export class MakerScheduleRunner implements ScheduleRunner {}}const nextProviderId = applyProviderId ?? currentProviderId;+ const resolvedSelection = baseline.resolvedSelection;+ if (resolvedSelection && (live.agentKind !== resolvedSelection.agentKind ||+ targetModel !== resolvedSelection.model || nextProviderId !== resolvedSelection.providerId)) {+ throw new QueuedRouteDisabledError('Scheduled model route changed before queued dispatch');+ }if (crossesCodexAppliedCustomProviderIdentity({agentKind: live.agentKind,@@ -2339,6 +2419,9 @@ export class MakerScheduleRunner implements ScheduleRunner {live.codexCindyRemoteCompactionCompatible,})) {+ if (resolvedSelection) {+ throw new QueuedRouteDisabledError('Scheduled model route requires rebuilding before queued dispatch');+ }// 早退 = 本轮沿用 live 当前路由派发:这条保留路由自己也要过停用裁决 ——// 目标来源启用但需要凭证切换、而**当前**来源在排队等待期间被停用时,不裁决// 就成了绕过口,照发等于继续经停用路由扣费(PR #744 review 第十轮)。@@ -2441,12 +2524,17 @@ export class MakerScheduleRunner implements ScheduleRunner {// 快照 clamp 后 setEffort 会覆盖用户的新选择;而运行时无 live effort getter、拿不到当前真实值 ——// 遵循「follow 且当前值不可知 → 不动 effort」(PR #479 review「Re-read effort before following// queued sessions」)。显式 effort 才是权威意图,按实际运行模型 clamp 后下发。- const reconciledEffort = this.reconcileEffortForModel(- live.agentKind,- runtimeModel,- schedule.effort,- schedule.id,- );+ if (resolvedSelection && runtimeModel !== resolvedSelection.model) {+ throw new QueuedRouteDisabledError('Scheduled model selection did not reach the queued session');+ }+ const reconciledEffort = resolvedSelection+ ? resolvedSelection.effort ?? undefined+ : this.reconcileEffortForModel(+ live.agentKind,+ runtimeModel,+ schedule.effort,+ schedule.id,+ );// 显式 effort 存在即下发,不靠 `!== baseline.effort` 判断:baseline.effort 是 enqueue 时刻快照,// 且上一次 fire 可能已把它 backfill 成 clamp 后的值 —— 若据此判"未变"而 skip,当用户在排队期间// 把 live effort 调低时,这一 turn 会跑用户的低档而非 schedule 的显式档。setEffort 幂等,显式档@@ -2459,9 +2547,20 @@ export class MakerScheduleRunner implements ScheduleRunner {await live.setEffort(reconciledEffort as Effort);} catch (err) {effortApplied = false;+ if (resolvedSelection) throw new QueuedRouteDisabledError('Scheduled effort selection could not be applied', { cause: err });this.deps.logger.warn?.('[runner] queued heartbeat setEffort failed (non-fatal)', err);}}+ if (resolvedSelection && effortApplied) {+ setSessionEffort(live.id, resolvedSelection.effort);+ }+ if (resolvedSelection && live.agentKind === 'codex') {+ try {+ await live.setFastMode(resolvedSelection.fastMode);+ } catch (err) {+ throw new QueuedRouteDisabledError('Scheduled Fast selection could not be applied', { cause: err });+ }+ }// applyProviderId = 裁决后的落地来源:显式来源(通过裁决)或隐式默认被停用时的// 替代来源(reject 已在上方抛错中止,走不到这里)。if (applyProviderId) {@@ -2470,13 +2569,14 @@ export class MakerScheduleRunner implements ScheduleRunner {if (live.agentKind === 'pi') {setSessionFastMode(live.id, baseline.fastMode === true);}- if ((modelChanged && modelApplied) || (effortChanged && effortApplied) || applyProviderId) {+ if (resolvedSelection || (modelChanged && modelApplied) || (effortChanged && effortApplied) || applyProviderId) {await backfillSessionMeta(this.deps.getDb(),live.id,{model: modelChanged && modelApplied ? targetModel : undefined,effort: effortChanged && effortApplied ? reconciledEffort : undefined,+ fastMode: resolvedSelection?.fastMode,providerId: applyProviderId ?? undefined,},this.deps.logger,diff --git a/apps/desktop/src/main/scheduler-host/runners/_shared.ts b/apps/desktop/src/main/scheduler-host/runners/_shared.tsindex 01c73e8f11..2197e216f0 100644--- a/apps/desktop/src/main/scheduler-host/runners/_shared.ts+++ b/apps/desktop/src/main/scheduler-host/runners/_shared.ts@@ -28,6 +28,7 @@ import type { SchedulerDrizzleDb } from '../storage';*/export interface BackfillSessionMetaPatch {effort?: string;+ fastMode?: boolean;/*** heartbeat 模式 schedule.model 覆盖了绑定 session 的旧 model 时落库,* 让 chat UI model picker 与下次 fire 读到的 meta.model 跟实际运行一致。@@ -64,6 +65,7 @@ export async function backfillSessionMeta(};if (meta.permissionMode !== null) patch.permissionMode = meta.permissionMode ?? 'bypassPermissions';if (meta.effort) patch.effort = meta.effort;+ if (meta.fastMode !== undefined) patch.fastMode = meta.fastMode;if (meta.model) patch.model = meta.model;if (meta.providerId) patch.providerId = meta.providerId;if (meta.workspaceKind) patch.workspaceKind = meta.workspaceKind;diff --git a/apps/desktop/src/renderer/__tests__/composerMorphScope.test.ts b/apps/desktop/src/renderer/__tests__/composerMorphScope.test.tsindex 294c3333d0..b92fb37f6e 100644--- a/apps/desktop/src/renderer/__tests__/composerMorphScope.test.ts+++ b/apps/desktop/src/renderer/__tests__/composerMorphScope.test.ts@@ -62,7 +62,8 @@ describe('composer morph scope', () => {describe('设置字段里的 AgentSelect 宽度契约', () => {it('两处设置场景都用 field 形态,不得把工具条形态塞进字段', () => {for (const src of [settingsModel, workspacePrefs]) {- expect(src).toContain('<AgentSelect');+ expect(src).toContain('<ModelSelector');+ expect(src).not.toContain('<AgentSelect');expect(src).toContain('triggerVariant="field"');}});diff --git a/apps/desktop/src/renderer/__tests__/imDefaultSettingsLogic.test.ts b/apps/desktop/src/renderer/__tests__/imDefaultSettingsLogic.test.tsindex ad88839b5d..125cd350e4 100644--- a/apps/desktop/src/renderer/__tests__/imDefaultSettingsLogic.test.ts+++ b/apps/desktop/src/renderer/__tests__/imDefaultSettingsLogic.test.ts@@ -3,7 +3,6 @@ import { describe, expect, it } from 'vitest';import {buildAgentSettingsPatch,mergeSettingsPatch,- resolveAgentSwitchSettings,} from '@/components/settings/imDefaultSettingsLogic';import {IM_DEFAULT_SETTINGS,@@ -54,118 +53,3 @@ describe('im default settings logic', () => {});});});--describe('resolveAgentSwitchSettings (切 harness 时收敛目标 agent 的模型/供应商/强度)', () => {- const current = { providerId: 'stale-provider', model: 'retired-model', effort: 'high' } as const;- const resolveProviderId = (modelId: string, providerId: string | null): string | null =>- providerId ?? `provider-of-${modelId}`;- /**- * 组件里 resolveEffort 的等价实现(顺序照 ImDefaultSettingsSection):- * 当前值 → 该模型的 override → 该模型的 defaultEffort → 该模型首档 → agent 出厂值。- * 传它进去正是为了锁住「切 agent 与切模型对同一模型给出同一强度」。- */- const makeResolveEffort =- (- catalog: Record<- string,- { efforts: readonly string[]; defaultEffort?: string; override?: string }- >,- agentFallback: string,- ) =>- (modelId: string, requested: string): 'low' | 'medium' | 'high' | 'xhigh' => {- const model = catalog[modelId];- if (!model || model.efforts.length === 0) return requested as 'high';- if (model.efforts.includes(requested)) return requested as 'high';- if (model.override && model.efforts.includes(model.override)) return model.override as 'high';- if (model.defaultEffort && model.efforts.includes(model.defaultEffort)) {- return model.defaultEffort as 'high';- }- if (model.efforts.includes(agentFallback)) return agentFallback as 'high';- return model.efforts[0] as 'high';- };-- it('已存模型不在可用清单里 → 换成清单首个, 供应商重解, 强度按新模型能力回落', () => {- expect(- resolveAgentSwitchSettings({- current: { ...current },- available: [{ id: 'live-model', efforts: ['low', 'medium'] }],- resolveEffort: makeResolveEffort({ 'live-model': { efforts: ['low', 'medium'] } }, 'medium'),- resolveProviderId,- }),- ).toEqual({- model: 'live-model',- providerId: 'provider-of-live-model',- effort: 'medium',- });- });-- it('已存模型仍可用 → 保留模型与强度, 但仍重解供应商(旧 providerId 可能已断开)', () => {- expect(- resolveAgentSwitchSettings({- current: { providerId: 'openai', model: 'live-model', effort: 'high' },- available: [{ id: 'live-model', efforts: ['high', 'low'] }],- resolveEffort: makeResolveEffort({ 'live-model': { efforts: ['high', 'low'] } }, 'low'),- resolveProviderId: (modelId, providerId) => (providerId === 'openai' ? 'openai' : modelId),- }),- ).toEqual({ model: 'live-model', providerId: 'openai', effort: 'high' });- });-- it('agent 出厂强度也不被新模型支持 → 取该模型的首个强度', () => {- expect(- resolveAgentSwitchSettings({- current: { ...current },- available: [{ id: 'live-model', efforts: ['xhigh'] }],- resolveEffort: makeResolveEffort({ 'live-model': { efforts: ['xhigh'] } }, 'medium'),- resolveProviderId,- }).effort,- ).toBe('xhigh');- });-- it('强度回落必须先用该模型自己的 defaultEffort, 而不是先跳到 agent 出厂值', () => {- // 新模型支持 low/medium/xhigh: 当前 high 不支持 → 该模型 defaultEffort=xhigh 优先,- // 不能因为 agent 出厂值 medium 也在清单里就先用它(review 指出的顺序错位)。- expect(- resolveAgentSwitchSettings({- current: { ...current },- available: [{ id: 'live-model', efforts: ['low', 'medium', 'xhigh'] }],- resolveEffort: makeResolveEffort(- { 'live-model': { efforts: ['low', 'medium', 'xhigh'], defaultEffort: 'xhigh' } },- 'medium',- ),- resolveProviderId,- }).effort,- ).toBe('xhigh');- });-- it('模型级 override 优先于该模型的 defaultEffort 与 agent 出厂值', () => {- expect(- resolveAgentSwitchSettings({- current: { ...current },- available: [{ id: 'live-model', efforts: ['low', 'medium', 'xhigh'] }],- resolveEffort: makeResolveEffort(- {- 'live-model': {- efforts: ['low', 'medium', 'xhigh'],- defaultEffort: 'xhigh',- override: 'low',- },- },- 'medium',- ),- resolveProviderId,- }).effort,- ).toBe('low');- });-- it('该 agent 当下一个可用模型都没有 → 原样保留, 不抹成空值', () => {- const kept = { ...current };- expect(- resolveAgentSwitchSettings({- current: kept,- available: [],- resolveEffort: makeResolveEffort({}, 'medium'),- resolveProviderId,- }),- ).toEqual(kept);- });-});diff --git a/apps/desktop/src/renderer/__tests__/makerSharedFixtureParity.test.ts b/apps/desktop/src/renderer/__tests__/makerSharedFixtureParity.test.tsindex e93716553d..2cab9d457c 100644--- a/apps/desktop/src/renderer/__tests__/makerSharedFixtureParity.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerSharedFixtureParity.test.ts@@ -32,8 +32,11 @@ describe('maker-shared desktop parity fixture', () => {expect(hasOwn(input, 'effort')).toBe(true);expect(input.model).toBeUndefined();expect(input.effort).toBeUndefined();- expect(hasOwn(input, 'fastMode')).toBe(false);}+ // Mobile has no explicit follow/override action and preserves a saved Fast+ // choice. Desktop's full follow selection must clear it for future recovery.+ expect(hasOwn(sharedInput, 'fastMode')).toBe(false);+ expect(desktopInput).toHaveProperty('fastMode', undefined);});it('keeps shared file preview categories compatible with desktop attachment categories', () => {diff --git a/apps/desktop/src/renderer/__tests__/schedulerModelPopoverOverlay.test.tsx b/apps/desktop/src/renderer/__tests__/schedulerModelPopoverOverlay.test.tsxindex 270abea60d..e9c7fd2514 100644--- a/apps/desktop/src/renderer/__tests__/schedulerModelPopoverOverlay.test.tsx+++ b/apps/desktop/src/renderer/__tests__/schedulerModelPopoverOverlay.test.tsx@@ -80,34 +80,7 @@ vi.mock('@/components/new-chat/ModelSelector', () => ({ModelIconMark: () => null,}));-vi.mock('@/components/new-chat/AgentSelect', () => ({- AgentSelect: ({- value,- onChange,- disabled,- side,- useMorphPopover,- overlayContentClassName,- }: {- value: string;- onChange: (value: 'codex') => void;- disabled?: boolean;- side?: string;- useMorphPopover?: boolean;- overlayContentClassName?: string;- }) => (- <button- type="button"- data-testid="scheduler-agent-select"- data-value={value}- data-disabled={String(disabled === true)}- data-side={side}- data-use-morph={String(useMorphPopover === true)}- data-overlay-class={overlayContentClassName}- onClick={() => onChange('codex')}- />- ),-}));+vi.mock('@/hooks/useAvailableAgents', () => ({ useModelPickerAgents: () => ['claude-code', 'codex', 'pi'] }));vi.mock('@/hooks/useAgentCapabilities', () => ({getCachedCapabilities: () => null,@@ -129,7 +102,7 @@ vi.mock('@/hooks/useProviders', () => ({useProviders: () => ({ providers: [] }),}));-import { AgentTabs, ModelEffortChip } from '@/features/scheduler/components/ScheduleChips';+import { ModelEffortChip } from '@/features/scheduler/components/ScheduleChips';const requestProviderModelsAutoRefresh = vi.fn(async () => ({ ok: true as const }));@@ -141,26 +114,14 @@ beforeEach(() => {});describe('scheduler model popover overlay behavior', () => {- it('raises the shared harness dropdown above the schedule dialog', () => {- const onChange = vi.fn();- render(<AgentTabs value="claude-code" onChange={onChange} />);-- const selector = screen.getByTestId('scheduler-agent-select');- expect(selector.getAttribute('data-value')).toBe('cc');- expect(selector.getAttribute('data-side')).toBe('top');- expect(selector.getAttribute('data-use-morph')).toBe('false');- expect(selector.getAttribute('data-overlay-class')).toBe('z-[10010]');-- fireEvent.click(selector);- expect(onChange).toHaveBeenCalledWith('codex');- });-it('keeps wheel events inside the model popover and raises nested model options above it', () => {const onOuterWheel = vi.fn();render(<div onWheel={onOuterWheel}><ModelEffortChip+ onSelect={vi.fn()}+ onFollowSession={vi.fn()}agentKind="claude-code"modelValue="claude-opus-4-8"onChangeModel={vi.fn()}@@ -194,6 +155,8 @@ describe('scheduler model popover overlay behavior', () => {it('requests a silent refresh when the scheduler model selector opens', async () => {render(<ModelEffortChip+ onSelect={vi.fn()}+ onFollowSession={vi.fn()}agentKind="claude-code"modelValue="claude-opus-4-8"onChangeModel={vi.fn()}@@ -215,6 +178,8 @@ describe('scheduler model popover overlay behavior', () => {it('keeps an effort-only bound override labeled as following the session model', () => {render(<ModelEffortChip+ onSelect={vi.fn()}+ onFollowSession={vi.fn()}agentKind="claude-code"modelValue=""onChangeModel={vi.fn()}diff --git a/apps/desktop/src/renderer/__tests__/schedulerTemplateEntry.test.ts b/apps/desktop/src/renderer/__tests__/schedulerTemplateEntry.test.tsindex ea0f1eae50..d503dc60e0 100644--- a/apps/desktop/src/renderer/__tests__/schedulerTemplateEntry.test.ts+++ b/apps/desktop/src/renderer/__tests__/schedulerTemplateEntry.test.ts@@ -3,9 +3,12 @@import { createElement, type ReactNode } from 'react';import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import type { ScheduleTemplate } from '@cindy/maker-scheduler';+import type { Schedule, ScheduleTemplate } from '@cindy/maker-scheduler';+import type { ProviderView } from '@cindy/model-providers';+import type { SessionReference } from '../../shared/sessionReference';import { SchedulerPage } from '@/features/scheduler/SchedulerPage';+import { ScheduleFormDialog } from '@/features/scheduler/components/ScheduleFormDialog';import {oneTimeCronAfterUsageReset,systemTimeZone,@@ -14,6 +17,10 @@ import {import { pluginScheduleNavigationState } from '@/features/scheduler/lib/pluginScheduleCreateIntent';const createSchedule = vi.fn();+const modelFixtures = vi.hoisted(() => ({+ providers: [] as ProviderView[],+ sessionReferences: new Map<string, SessionReference>(),+}));const toastMocks = vi.hoisted(() => ({success: vi.fn(),warning: vi.fn(),@@ -131,7 +138,7 @@ vi.mock('@/features/scheduler/hooks/useScheduleUnreadRunCounts', () => ({}));vi.mock('@/features/scheduler/hooks/useSessionReferences', () => ({- useSessionReferences: () => new Map(),+ useSessionReferences: () => modelFixtures.sessionReferences,}));vi.mock('@/hooks/useFeishuBot', () => ({@@ -143,9 +150,12 @@ vi.mock('@/hooks/useProjectPickerOptions', () => ({}));vi.mock('@/hooks/useAgentCapabilities', () => ({- useAgentCapabilities: () => ({+ useAgentCapabilities: (agentKind: string) => ({capabilities: {availableModels: [+ ...(agentKind === 'codex' ? [{+ id: 'gpt-5.5', displayName: 'GPT 5.5', efforts: ['high'], defaultEffort: 'high',+ }] : []),{id: 'claude-sonnet-4-6',displayName: 'Claude Sonnet 4.6',@@ -162,13 +172,13 @@ vi.mock('@/hooks/useAgentCapabilities', () => ({defaultEffort: 'medium',},],- hasFastMode: false,+ hasFastMode: agentKind === 'codex',},}),}));vi.mock('@/hooks/useProviders', () => ({- useProviders: () => ({ providers: [] }),+ useProviders: () => ({ providers: modelFixtures.providers }),}));vi.mock('@/state/newMakerDraft', () => ({@@ -178,10 +188,16 @@ vi.mock('@/state/newMakerDraft', () => ({vi.mock('@/features/scheduler/components/ScheduleChips', async () => {const React = await import('react');return {- AgentTabs: ({ value }: { value: string }) =>- React.createElement('div', { 'data-testid': 'agent-kind' }, value),- ModelEffortChip: ({ modelValue }: { modelValue: string }) =>- React.createElement('div', { 'data-testid': 'model-value' }, modelValue),+ ModelEffortChip: ({ modelValue, agentKind, fastMode, onChangeFast }: {+ modelValue: string; agentKind: string; fastMode?: boolean; onChangeFast?: (enabled: boolean) => void;+ }) =>+ React.createElement(React.Fragment, null,+ React.createElement('div', { 'data-testid': 'agent-kind' }, agentKind),+ React.createElement('div', { 'data-testid': 'model-value' }, modelValue),+ React.createElement('button', {+ type: 'button', 'aria-label': 'Toggle Fast',+ onClick: () => onChangeFast?.(!fastMode),+ })),ProjectChip: () => React.createElement('div'),ScheduleChip: ({ cronExpr }: { cronExpr: string }) =>React.createElement('div', { 'data-testid': 'cron-expr' }, cronExpr),@@ -191,6 +207,8 @@ vi.mock('@/features/scheduler/components/ScheduleChips', async () => {});beforeEach(() => {+ modelFixtures.providers = [];+ modelFixtures.sessionReferences.clear();createSchedule.mockImplementation(async (input) => ({ id: 'created-schedule', ...input }));routerMocks.location.pathname = '/cc-agent/scheduled';routerMocks.location.search = '';@@ -447,3 +465,42 @@ describe('Scheduler template entry', () => {);});});++describe('editing legacy bound automations', () => {+ it.each([true, false])('persists Fast=%s and the Harness without reselecting the model', async (fastMode) => {+ const initial: Schedule = {+ id: 'legacy-bound', name: 'Legacy automation', prompt: 'Continue the task',+ kind: 'cron', cronExpr: '0 * * * *', timezone: 'UTC', recurring: true, manual: false,+ agentKind: 'codex', model: 'gpt-5.5', providerId: 'custom-fast', effort: 'high',+ fastMode: !fastMode, targetSessionId: 'bound-task', workspaceKind: 'dialogue', useWorktree: false,+ notify: { desktop: true, feishu: false }, status: 'active', createdAt: 1, updatedAt: 1,+ };+ expect(initial.modelAgentKind).toBeUndefined();+ modelFixtures.providers = [{+ id: 'custom-fast', name: 'Custom Fast', source: 'user', connected: true, agents: ['codex'],+ auth: { method: 'apiKey' },+ routing: { codex: { upstream: 'https://custom.example/v1', authStrategy: 'api-key-header' } },+ models: { codex: [{+ id: 'gpt-5.5', name: 'GPT 5.5', contextWindow: 200_000,+ efforts: ['high'], defaultEffort: 'high', supportsFastMode: true,+ }] },+ }];+ modelFixtures.sessionReferences.set('bound-task', {+ sessionId: 'bound-task', state: 'available', status: 'active', agentKind: 'codex',+ });+ const onSubmit = vi.fn(async () => undefined);+ render(createElement(ScheduleFormDialog, {+ open: true, onOpenChange: vi.fn(), initial, onSubmit,+ }));++ // Exercise the current-row Fast callback only: no model-row selection is emitted.+ fireEvent.click(screen.getByRole('button', { name: 'Toggle Fast' }));+ fireEvent.click(screen.getByRole('button', { name: 'scheduler.editor.promptDialog.saveAria' }));++ await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));+ expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({+ targetSessionId: 'bound-task', agentKind: 'codex', modelAgentKind: 'codex',+ model: 'gpt-5.5', providerId: 'custom-fast', effort: 'high', fastMode,+ }), true);+ });+});diff --git a/apps/desktop/src/renderer/__tests__/unifiedModelPanelRendering.test.tsx b/apps/desktop/src/renderer/__tests__/unifiedModelPanelRendering.test.tsxindex 6419eef9e2..e337a4eada 100644--- a/apps/desktop/src/renderer/__tests__/unifiedModelPanelRendering.test.tsx+++ b/apps/desktop/src/renderer/__tests__/unifiedModelPanelRendering.test.tsx@@ -3903,6 +3903,16 @@ describe('统一面板 · 清收藏锚点也等待回执', () => {});describe('global default A contract', () => {+ it.each([false, ['pi'] as const])('hides Fast when this entry cannot dispatch it (%s)', async (fastModeConfigurable) => {+ const select = vi.fn();+ renderPanel({ vendorKey: 'codex', modelId: 'gpt-5.5', currentProviderId: 'xd',+ onUnifiedSelect: select, onFastModeChange: undefined, fastModeConfigurable });+ const flyout = await openRowFlyout('GPT-5.5');+ expect(flyout.querySelector('[data-fast-toggle]')).toBeNull();+ await act(async () => { fireEvent.click(rowFor('GPT-5.5')); });+ expect(select).toHaveBeenCalledWith(expect.objectContaining({ engine: 'codex', fast: false }));+ });+it('defaults to A and limits a model-only settings field to its writable Harness', async () => {const change = vi.fn();const { container } = renderPanel({ vendorKey: 'cc', onProviderChange: change,diff --git a/apps/desktop/src/renderer/cindy-brain/GhostErrandPrefs.tsx b/apps/desktop/src/renderer/cindy-brain/GhostErrandPrefs.tsxindex 7c5884e62b..34a0a3ea3a 100644--- a/apps/desktop/src/renderer/cindy-brain/GhostErrandPrefs.tsx+++ b/apps/desktop/src/renderer/cindy-brain/GhostErrandPrefs.tsx@@ -4,7 +4,7 @@** 选择器复用草稿页同一套组件(2026-07-31 Lizi 要求,不另搭下拉),展示与* 交互与新建对话一致,不暴露「跟随默认 / 钉住」这层概念:- * - Agent = VendorSegmentedSwitcher(cc/codex/pi 分段);+ * - Harness 与模型作为完整配置由共享选择器一起保存;* - 模型/推理强度/Fast/供应商 = ModelSelector 的 field 形态,占满整行(标题在上、* 控件 w-full 在下,与 IM 默认配置同款);面板宽度绑定 trigger(DESIGN.md §4);* - 动手权限 = PermissionSelector(权限下拉全仓只此一份,不得私搭),@@ -19,6 +19,7 @@* 亲选(与 pick 槽同一哲学)。*/+import { useModelPickerAgents } from '@/hooks/useAvailableAgents';import { useCallback, useState, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import { Bot, FolderOpen, X } from 'lucide-react';@@ -27,7 +28,6 @@ import { toast } from '@/lib/toast';import { cn } from '@/lib/utils';import { ModelSelector } from '@/components/new-chat/ModelSelector';import { PermissionSelector } from '@/components/new-chat/PermissionSelector';-import { VendorSegmentedSwitcher } from '@/components/new-chat/VendorSegmentedSwitcher';import {getEffortForModel,getFastModeForModel,@@ -95,6 +95,8 @@ export function GhostErrandPrefs({const followVendor: 'cc' | 'codex' | 'pi' =draft.vendor === 'pi' ? 'pi' : draft.vendor === 'codex' ? 'codex' : 'cc';const vendor: 'cc' | 'codex' | 'pi' = config.agentKind ?? followVendor;+ const pickerAgents = useModelPickerAgents(vendor === 'cc' ? 'claude-code' : vendor);+const shownModel = config.model ?? draft.lastByVendor[vendor].model;const shownEffort = (config.effort ??getEffortForModel(shownModel) ??@@ -149,35 +151,21 @@ export function GhostErrandPrefs({{t('settings.ghosts.detail.errandPrefs.desc')}</p>- {row(- 'agent',- <VendorSegmentedSwitcher- value={vendor}- dense- width={200}- ariaLabel={t('settings.ghosts.detail.errandPrefs.agent')}- onChange={(next) => {- if (next === vendor && config.agentKind !== undefined) return;- // 换 agent 连带清掉模型组(跨 agent 的模型 id 互不通用);点选即把该组- // 值钉进本插件配置(未选过时才实时跟随草稿)。- save({- ...config,- agentKind: next === 'pi' ? 'pi' : next === 'codex' ? 'codex' : 'cc',- model: undefined,- effort: undefined,- fastMode: undefined,- providerId: undefined,- });- }}- />,- )}-{/* 模型选择器占满整行(标题在上、控件 w-full 在下,与 IM 默认配置同款):field 形态的面板宽度绑定 trigger 宽度(DESIGN.md §4),压到 60% 会让下拉窄到把模型名截断,所以这里给它整行宽度。 */}<div className="flex min-w-0 flex-col gap-2"><span className={labelCls}>{t('settings.ghosts.detail.errandPrefs.model')}</span><ModelSelector+ unifiedAgents={pickerAgents}+ onUnifiedSelect={({ engine, providerId, modelId, effort, fast }) => save({+ ...config,+ agentKind: engine,+ providerId,+ model: modelId,+ effort: ERRAND_EFFORTS.has(effort ?? '') ? effort : undefined,+ fastMode: fast,+ })}modelId={shownModel}effort={shownEffort}fastMode={shownFast}diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsxindex 01aa7697f7..27c6510d35 100644--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx@@ -687,6 +687,8 @@ interface ModelSelectorProps {maxVisibleModelRows?: number;/** 关闭模型的 effort / Fast 编辑入口与行内状态摘要;只选择模型 id 的设置项使用。 */configurationEnabled?: boolean;+ /** Restrict Fast to the Harnesses this entry can persist and dispatch; false disables it. */+ fastModeConfigurable?: boolean | readonly AgentKind[];/** 语义同 ModelSelectorContentProps.unifiedPanel(统一模型选择器面板,默认开启)。 */unifiedPanel?: boolean;/** 语义同 ModelSelectorContentProps.sessionEngineFilter(统一面板的会话内形态)。 */@@ -823,6 +825,8 @@ interface ModelSelectorContentProps {followSession?: { active: boolean; label: string; onFollow: () => void | boolean | Promise<void | boolean> };/** 是否显示模型的 effort / Fast 编辑入口。 */configurationEnabled?: boolean;+ /** Restrict Fast to the Harnesses this entry can persist and dispatch; false disables it. */+ fastModeConfigurable?: boolean | readonly AgentKind[];/** A is the default for every entry. False is reserved for capabilities-only remote compatibility. */unifiedPanel?: boolean;/**@@ -1037,6 +1041,7 @@ function ModelSelectorContentView({onNavigateToProviders,followSession,configurationEnabled = true,+ fastModeConfigurable = true,unifiedPanel: useUnifiedPanel = true,sessionEngineFilter,unifiedAgents: requestedUnifiedAgents,@@ -2702,12 +2707,12 @@ function ModelSelectorContentView({);const unifiedAgentFastCapable = useCallback((agent: AgentKind): boolean =>- !!(onFastModeChange || onUnifiedSelect) && (agent === 'claude-code'+ (typeof fastModeConfigurable === 'boolean' ? fastModeConfigurable : fastModeConfigurable.includes(agent)) && !!(onFastModeChange || onUnifiedSelect) && (agent === 'claude-code'? !!cc.capabilities?.hasFastMode: agent === 'codex'? !!codex.capabilities?.hasFastMode: !!pi.capabilities?.hasFastMode),- [cc.capabilities, codex.capabilities, pi.capabilities, onFastModeChange, onUnifiedSelect],+ [cc.capabilities, codex.capabilities, pi.capabilities, onFastModeChange, onUnifiedSelect, fastModeConfigurable],);if (emptyState) return emptyState;@@ -3195,6 +3200,7 @@ export function ModelSelector({popoverSide = 'top',maxVisibleModelRows,configurationEnabled = true,+ fastModeConfigurable = true,unifiedPanel: useUnifiedPanel = true,sessionEngineFilter,unifiedAgents,@@ -3947,6 +3953,7 @@ export function ModelSelector({onProviderChange={onProviderChange}onNavigateToProviders={onNavigateToProviders}configurationEnabled={configurationEnabled}+ fastModeConfigurable={fastModeConfigurable}providersOverride={providersOverride}unifiedPanel={unifiedPanel}sessionEngineFilter={contentSessionEngineFilter}diff --git a/apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx b/apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsxindex f0a40ea38a..22597e5f35 100644--- a/apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx+++ b/apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx@@ -4,10 +4,10 @@* 由 HookConnectionsSection 在每个目录卡片下渲染(用户反馈: 偏好属于目录* 条目本身, 不该是独立区块): agent / 模型(含思考强度) / 权限模式三个字段。*- * **三个控件一律复用应用标准选择器,本文件不自建任何选择 UI**(2026-07 用户+ * **两个控件一律复用应用标准选择器,本文件不自建任何选择 UI**(2026-07 用户* 定稿: 这里曾私搭一套裸下拉, 露出 'claude-code' 原始 id、自己拼一遍可选模型* 清单、effort 直接显示未经 i18n 的 low/medium/high):- * - agent -> AgentSelect(引擎下拉, 与首页新建对话工具条同一个)+ * - Harness 与模型由 ModelSelector 一次提交, 不保留独立引擎控件。* - 模型 -> ModelSelector 的 field trigger, **composer 同款全功能形态**(供应商* 分段/订阅来源/推理强度全开; 2026-07 用户定稿基准: 全软件一个模型* 选择面板, 处处同行为, 差异只有样式)。来源落本地@@ -35,6 +35,7 @@* 颜色一律走主题 token(规则 16)。*/+import { useModelPickerAgents } from '@/hooks/useAvailableAgents';import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';@@ -44,7 +45,6 @@ import { extractIpcError } from '@/utils/ipcError';import { useAgentCapabilities, type AgentCapabilities } from '@/hooks/useAgentCapabilities';import { ModelSelector } from '@/components/new-chat/ModelSelector';import { PermissionSelector } from '@/components/new-chat/PermissionSelector';-import { AgentSelect } from '@/components/new-chat/AgentSelect';import type { MakerVendor } from '@/lib/ccAgent.types';import {getProviderModelEffort,@@ -66,7 +66,6 @@ import {AGENT_KINDS,HOOK_DEFAULT_PERMISSION_MODE,isKnownAgent,- patchForAgentChange,patchForModelChange,resolveEffectiveRow,type ImDefaultsLike,@@ -495,20 +494,7 @@ function toVendorKey(agentKind: string | null): 'cc' | 'codex' | 'pi' {return agentKind === 'codex' || agentKind === 'pi' ? agentKind : 'cc';}-/**- * 选择器的 vendor key → hook prefs 的 agentKind。- * MakerVendor 还含 'orca' 等本编辑器不支持的值 —— 分段只有 Claude/Codex 两项,该分支- * 物理不可达;若未来有人把别的 vendor 接进来,fail-fast 好过静默写成 claude-code- * 偏好(Copilot review)。- */-function toAgentKind(vendor: MakerVendor): KnownAgent {- if (vendor === 'codex') return 'codex';- if (vendor === 'pi') return 'pi';- if (vendor === 'cc') return 'claude-code';- throw new Error(`WorkspacePrefsEditor: unsupported vendor '${vendor}' for hook prefs`);-}--/** 目录卡片内的偏好编辑行(agent / 模型 / 权限三字段)。alias 为该行当前生效别名。 */+/** 目录卡片内的偏好编辑行(完整模型配置 / 权限)。alias 为该行当前生效别名。 */export function WorkspacePrefsEditor({alias,state,@@ -543,6 +529,8 @@ export function WorkspacePrefsEditor({const disabled = !state.editable || state.pendingWs === alias;const vendorKey = toVendorKey(eff.agentKind.id);+ const pickerAgents = useModelPickerAgents(vendorKey === 'cc' ? 'claude-code' : vendorKey === 'pi' ? 'pi' : 'codex');+/** 落一个模型选择(分段行与 flat 行共用): 随手写入 (agent, model) 配对并校准 effort。 */const applyModel = (next: string) => {if (next === prefs.model || eff.agentKind.id === null) return;@@ -554,46 +542,6 @@ export function WorkspacePrefsEditor({return (<div className="flex flex-wrap items-end gap-2">- {/* agent 分段是固定 168px 的 pill,不参与压缩 —— 卡片变窄时整块换行,- 而不是把 Claude / Codex 两段挤到溢出容器。- 禁用只看行级只读态,**不含 effAgentCaps === null**:patchForAgentChange 只清- model/effort、不做能力校准,切 agent 本身不需要当前 agent 的清单;若跟着- caps 一起禁,当前 agent 能力请求瞬时失败就把整行钉死,用户连切到另一个- (可用的)agent 都不行(codex review)。模型/权限字段仍按 caps 禁用 ——- 它们的选项列表真的来自 caps。 */}- {/* 引擎选择用与新建对话工具条同一个下拉(AgentSelect, #1350): 定宽分段器每- 多一个引擎就窄一截(168px 三等分 = 每段 56px, Pi 已贴边), 而下拉只渲染- 当前引擎, 引擎数量不再影响布局; 未选中项也不再因为置灰而看着像不可用。 */}- {/* 确定宽度是 field 形态的前提: PrefsField 只有 min-w-0 时, trigger 的 w-full- 解析不到包含块宽度, 字段会缩到当前标签的固有宽度(选 Pi 时 trigger 与绑定- 它的面板只有一个短标签宽, 选项行图标/文字/勾选被截断, codex review #1490)。- 168px = 被替换的定宽分段器原宽度, 视觉落位不变。 */}- <PrefsField- label={t('settings.tina.prefs.agentLabel')}- className="w-[168px] shrink-0 basis-[168px]"- >- <AgentSelect- value={vendorKey}- // 设置字段形态: trigger 撑满字段、面板绑 trigger 实测宽度- // (DESIGN.md §4 Select & Dropdown 宽度铁则); dense 与同排 ModelSelector 齐高。- triggerVariant="field"- dense- side="bottom"- // 可及名带行别名:每行目录都有一个同样的选择器,不带别名时读屏听到的- // 全部是同一个名字,行与行无法分辨(codex review)。- ariaContext={`${t('settings.tina.prefs.agentLabel')} · ${alias}`}- disabled={disabled}- // 当前值可能是**继承值**(prefs.agentKind 为 null / 过期未知值时显示解析出的- // 默认 agent),重选它 = 钉成显式偏好 —— 与模型字段的 reselectEmitsChange 同语义;- // 显式同值由下方 nextAgent === prefs.agentKind 去重,不产生空写。- reselectEmitsChange- onChange={(next) => {- const nextAgent = toAgentKind(next);- if (nextAgent === prefs.agentKind) return;- state.applyPatch(alias, patchForAgentChange(nextAgent));- }}- />- </PrefsField>{/* 模型 + 思考强度同一个控件, **composer 同款全功能标准面板**(2026-07 用户定稿基准: 全软件一个模型选择面板, 处处同行为, 差异只有样式):供应商分段、订阅来源、推理强度全开。来源(providerId)是纯客户端维度, 落本地@@ -603,6 +551,13 @@ export function WorkspacePrefsEditor({不会拼出不可能路由 —— 「选 A 落 B」的根因(选了来源没地方存)已消除。 */}<PrefsField label={t('settings.tina.prefs.modelLabel')} className="flex-1 basis-[220px]"><ModelSelector+ fastModeConfigurable={false}+ unifiedAgents={pickerAgents}+ onUnifiedSelect={({ engine, modelId, providerId, effort }) => state.applyPatch(+ alias,+ { agentKind: engine === 'cc' ? 'claude-code' : engine, model: modelId, effort: effort || null },+ providerId,+ )}modelId={eff.model.id ?? ''}effort={eff.effort.id ?? ''}vendorKey={vendorKey}@@ -612,9 +567,8 @@ export function WorkspacePrefsEditor({dense// 可及名上下文与 agent 分段同规则(字段名 · 行别名),多卡片同屏读屏可区分。ariaContext={`${t('settings.tina.prefs.modelLabel')} · ${alias}`}- // 能力清单未就绪才禁用; agent 未显式设置时也可直接选模型(随手把- // agent 显式配对写入, 与 Slack 卡「选中模型即落 (agent, model)」同规则)- disabled={disabled || effAgentCaps === null || eff.agentKind.id === null}+ // 当前 Harness 的能力加载失败也能改选其它可用 Harness。+ disabled={disabled}// 这一行的 modelId 可能是**解析出来的继承值**(prefs.model 为 null 时来自 IM// 新会话默认), 点它的语义是「把继承值钉成本目录的显式偏好」, 必须照常回调 ——// 否则用户点了没反应, 之后上游默认一变这条偏好就被静默改掉。diff --git a/apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx b/apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsxindex 8330a7a10f..47d19dc5ef 100644--- a/apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx+++ b/apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx@@ -5,6 +5,7 @@* 静默改写;非 thread 渠道通过 `/new` 显式应用。*/+import { useModelPickerAgents } from '@/hooks/useAvailableAgents';import {connectedProvidersForAgent,getModel,@@ -14,7 +15,6 @@ import { MessageSquare, AlertTriangle } from 'lucide-react';import { useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { AgentSelect } from '@/components/new-chat/AgentSelect';import { ModelSelector } from '@/components/new-chat/ModelSelector';import { PermissionSelector } from '@/components/new-chat/PermissionSelector';import { type ModelDescriptor, useAgentCapabilities } from '@/hooks/useAgentCapabilities';@@ -39,7 +39,6 @@ import { DefaultOverrideControls } from './DefaultOverrideControls';import {buildAgentSettingsPatch,mergeSettingsPatch,- resolveAgentSwitchSettings,} from './imDefaultSettingsLogic';function vendorKeyFor(agentKind: ImDefaultAgentKind): 'cc' | 'codex' | 'pi' {@@ -84,6 +83,8 @@ export function ImDefaultSettingsSection({const [settings, setSettings] = useState<ImDefaultSettingsState | null>(null);const [pending, setPending] = useState(false);+ const pickerAgents = useModelPickerAgents(settings?.agentKind ?? 'claude-code');+useEffect(() => {let cancelled = false;setSettings(null);@@ -256,21 +257,6 @@ export function ImDefaultSettingsSection({: null: null;- const changeAgent = (agentKind: ImDefaultAgentKind) => {- if (agentKind === settings.agentKind) return;- // 只写 agentKind 会把目标 agent 上一次的模型原样带回来 —— 那个模型可能已停用- // 或供应商已断开, UI 照显而派发时静默降级。与 changeModel 同口径收敛。- const next = resolveAgentSwitchSettings({- current: settings.agents[agentKind],- available: modelsByAgent[agentKind],- // 与 changeModel 共用同一条解析链(model override / defaultEffort 先于 agent 出厂值)- resolveEffort: (modelId, requested) => resolveEffort(agentKind, modelId, requested),- resolveProviderId: (modelId, providerId) =>- resolveProviderId(agentKind, modelId, providerId),- });- void persist({ agentKind, ...buildAgentSettingsPatch(agentKind, next) });- };-const changeModel = (model: string,providerId: string | null = activeSettings.providerId,@@ -335,30 +321,28 @@ export function ImDefaultSettingsSection({/></div>- <div className="grid gap-4 md:grid-cols-[minmax(0,0.95fr)_minmax(0,1.05fr)]">- <div className="flex flex-col gap-2">- <span className="text-12 font-medium text-[var(--text-secondary)]">- {t('settings.imBot.defaults.agentLabel')}- </span>- {/* 与新建对话工具条同一个引擎下拉(AgentSelect, #1350): 手写三选一分段在- 窄列里三等分 + truncate, 引擎一多就挤; 且未选中项置灰看着像不可用。 */}- <AgentSelect- value={vendorKeyFor(settings.agentKind)}- // 字段形态: 与右侧模型选择器同高同宽规格, 面板绑 trigger 宽度- // (DESIGN.md §4 Select & Dropdown 宽度铁则)。- triggerVariant="field"- side="bottom"- disabled={pending}- ariaContext={t('settings.imBot.defaults.agentLabel')}- onChange={(next) => changeAgent(agentKindOfVendor(next))}- />- </div>-+ <div><div className="flex flex-col gap-2"><span className="text-12 font-medium text-[var(--text-secondary)]">{t('settings.imBot.defaults.modelLabel')}</span><ModelSelector+ fastModeConfigurable={false}+ unifiedAgents={pickerAgents}+ onUnifiedSelect={({ engine, modelId, providerId, effort }) => {+ const agentKind = agentKindOfVendor(engine);+ return persist({+ agentKind,+ ...buildAgentSettingsPatch(agentKind, {+ ...settings.agents[agentKind],+ model: modelId,+ providerId,+ effort: isImDefaultEffort(effort)+ ? effort+ : resolveEffort(agentKind, modelId, ''),+ }),+ });+ }}modelId={activeSettings.model}effort={activeSettings.effort}onModelChange={(modelId) => changeModel(modelId)}diff --git a/apps/desktop/src/renderer/components/settings/__tests__/ImDefaultSettingsSection.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/ImDefaultSettingsSection.test.tsxindex 52d467d926..776583faf8 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/ImDefaultSettingsSection.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/ImDefaultSettingsSection.test.tsx@@ -1,5 +1,5 @@// @vitest-environment jsdom-import { cleanup, render, screen } from '@testing-library/react';+import { cleanup, render, screen, fireEvent, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { IM_DEFAULT_SETTINGS, type ImDefaultSettingsState } from '../../../../shared/imDefaultSettings';@@ -59,12 +59,15 @@ vi.mock('@/hooks/useProviders', () => ({useProviders: () => ({ providers: [] }),}));-vi.mock('@/components/new-chat/AgentSelect', () => ({- AgentSelect: () => null,+vi.mock('@/hooks/useAvailableAgents', () => ({+ useModelPickerAgents: () => ['claude-code', 'codex', 'pi'],}));vi.mock('@/components/new-chat/ModelSelector', () => ({- ModelSelector: () => null,+ ModelSelector: ({ onUnifiedSelect, fastModeConfigurable }: {+ onUnifiedSelect: (selection: object) => void; fastModeConfigurable: boolean;+ }) => <button data-testid="select-codex" data-fast-configurable={String(fastModeConfigurable)}+ onClick={() => onUnifiedSelect({ engine: 'codex', modelId: 'gpt-5.5', providerId: 'xd', effort: 'low', fast: false })}>Select Codex</button>,}));vi.mock('@/components/new-chat/PermissionSelector', () => ({@@ -96,6 +99,19 @@ function defaults(agentKind: ImDefaultSettingsState['agentKind']): ImDefaultSett}describe('ImDefaultSettingsSection Pi channel warning', () => {+ it('saves the complete selection in one update while preserving permissions', async () => {+ const save = vi.fn(async (_patch: unknown) => defaults('codex'));+ window.electronAPI.maker.imDefaultSettingsSet = save;+ render(<ImDefaultSettingsSection />);+ await screen.findByText('settings.imBot.defaults.modelLabel');+ expect(screen.getByTestId('select-codex').getAttribute('data-fast-configurable')).toBe('false');+ fireEvent.click(screen.getByTestId('select-codex'));+ await waitFor(() => expect(save).toHaveBeenCalledTimes(1));+ expect(save.mock.calls[0]?.[0]).toEqual({ agentKind: 'codex', agents: {+ codex: { providerId: 'xd', model: 'gpt-5.5', effort: 'low' },+ } });+ });+beforeEach(() => {capabilityMockState.loadingAgent = null;capabilityMockState.errorAgent = null;@@ -156,7 +172,7 @@ describe('ImDefaultSettingsSection Pi channel warning', () => {};render(<ImDefaultSettingsSection channel="wechat" />);- await screen.findByText('settings.imBot.defaults.agentLabel');+ await screen.findByText('settings.imBot.defaults.modelLabel');expect(screen.queryByRole('status')).toBeNull();});@@ -192,7 +208,7 @@ describe('ImDefaultSettingsSection Pi channel warning', () => {} as unknown as typeof window.electronAPI;render(<ImDefaultSettingsSection channel="wechat" />);- await screen.findByText('settings.imBot.defaults.agentLabel');+ await screen.findByText('settings.imBot.defaults.modelLabel');expect(screen.queryByText('settings.imBot.defaults.agentUnsupportedOnChannelHint'),).toBeNull();@@ -202,7 +218,7 @@ describe('ImDefaultSettingsSection Pi channel warning', () => {capabilityMockState.loadingAgent = 'pi';render(<ImDefaultSettingsSection channel="wechat" />);- await screen.findByText('settings.imBot.defaults.agentLabel');+ await screen.findByText('settings.imBot.defaults.modelLabel');expect(screen.queryByText('settings.imBot.defaults.agentUnsupportedOnChannelHint'),).toBeNull();@@ -212,7 +228,7 @@ describe('ImDefaultSettingsSection Pi channel warning', () => {capabilityMockState.errorAgent = 'pi';render(<ImDefaultSettingsSection channel="wechat" />);- await screen.findByText('settings.imBot.defaults.agentLabel');+ await screen.findByText('settings.imBot.defaults.modelLabel');expect(screen.queryByText('settings.imBot.defaults.agentUnsupportedOnChannelHint'),).toBeNull();@@ -221,7 +237,7 @@ describe('ImDefaultSettingsSection Pi channel warning', () => {it('does not warn for Pi on channels without turn policy (feishu)', async () => {render(<ImDefaultSettingsSection channel="feishu" />);- await screen.findByText('settings.imBot.defaults.agentLabel');+ await screen.findByText('settings.imBot.defaults.modelLabel');expect(screen.queryByText('settings.imBot.defaults.agentUnsupportedOnChannelHint'),).toBeNull();@@ -231,14 +247,14 @@ describe('ImDefaultSettingsSection Pi channel warning', () => {// Telegram / 钉钉仅在群聊(event.speaker 存在)挂 turnPermissionPolicy,// 主人私聊 Pi 可用;设置 UI 不区分群聊/私聊,不能整体警告。const first = render(<ImDefaultSettingsSection channel="telegram" />);- await first.findByText('settings.imBot.defaults.agentLabel');+ await first.findByText('settings.imBot.defaults.modelLabel');expect(screen.queryByText('settings.imBot.defaults.agentUnsupportedOnChannelHint'),).toBeNull();cleanup();const second = render(<ImDefaultSettingsSection channel="dingtalk" />);- await second.findByText('settings.imBot.defaults.agentLabel');+ await second.findByText('settings.imBot.defaults.modelLabel');expect(screen.queryByText('settings.imBot.defaults.agentUnsupportedOnChannelHint'),).toBeNull();@@ -253,7 +269,7 @@ describe('ImDefaultSettingsSection Pi channel warning', () => {cleanup();const wechat = render(<ImDefaultSettingsSection channel="wechat" />);- await wechat.findByText('settings.imBot.defaults.agentLabel');+ await wechat.findByText('settings.imBot.defaults.modelLabel');expect(wechat.queryByText('settings.imBot.defaults.groupPermissionLabel'),).toBeNull();diff --git a/apps/desktop/src/renderer/components/settings/__tests__/WorkspacePrefsEditorRendering.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/WorkspacePrefsEditorRendering.test.tsxindex e0f221b951..3e0da474e9 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/WorkspacePrefsEditorRendering.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/WorkspacePrefsEditorRendering.test.tsx@@ -41,49 +41,13 @@ vi.mock('@/hooks/useAgentCapabilities', () => ({},}));-// 三个重依赖选择器只验「用了它、参数对」,内部行为由各自的测试负责。-// AgentSelect stub 把每个引擎渲染成一个可点按钮:点击即以该 vendor 回调,-// 便于验证「切换」与「重选当前项(reselectEmitsChange)」两条写入路径。-vi.mock('@/components/new-chat/AgentSelect', () => ({- AgentSelect: (props: {- value: string;- disabled?: boolean;- ariaContext?: string;- reselectEmitsChange?: boolean;- side?: string;- triggerVariant?: string;- dense?: boolean;- onChange: (next: string) => void;- }) => (- <div- data-testid="agent-select"- data-value={props.value}- data-disabled={props.disabled ? 'true' : 'false'}- data-aria-context={props.ariaContext}- data-reselect-emits={props.reselectEmitsChange ? 'true' : 'false'}- data-side={props.side}- data-trigger-variant={props.triggerVariant}- data-dense={props.dense ? 'true' : 'false'}- >- {['cc', 'codex', 'pi'].map((vendor) => (- <button- key={vendor}- type="button"- data-testid={`agent-option-${vendor}`}- disabled={props.disabled === true}- onClick={() => props.onChange(vendor)}- >- {vendor}- </button>- ))}- </div>- ),-}));-+vi.mock('@/hooks/useAvailableAgents', () => ({ useModelPickerAgents: () => ['claude-code', 'codex', 'pi'] }));vi.mock('@/components/new-chat/ModelSelector', () => ({ModelSelector: (props: {modelId: string;+ fastModeConfigurable?: boolean;+ onUnifiedSelect?: (selection: { engine: 'cc' | 'codex' | 'pi'; modelId: string; providerId: string; effort: string; fast: boolean; favoriteUid: null }) => void;effort: string;vendorKey: string;triggerVariant?: string;@@ -110,10 +74,17 @@ vi.mock('@/components/new-chat/ModelSelector', () => ({data-reselect-emits={String(props.reselectEmitsChange === true)}// 未知模型的 trigger 文案由调用方给出;这里回放它对一个不存在的 id 的结果。data-unknown-label={props.unknownModelLabel?.('ghost-model-1') ?? ''}+ data-fast-configurable={String(props.fastModeConfigurable)}onClick={() => props.onModelChange('gpt-5.5')}// 分段行点击(供应商, 模型, effort)原子选择 —— 回放 onProviderChange 的行为锁触发器。onKeyDown={() => props.onProviderChange?.('anthropic', 'claude-opus-5')}- />+ >+ {(['cc', 'codex', 'pi'] as const).map((engine) => (+ <button key={engine} data-testid={`model-harness-${engine}`} disabled={props.disabled}+ onClick={(event) => { event.stopPropagation(); props.onUnifiedSelect?.({ engine,+ modelId: engine === 'cc' ? 'claude-opus-4-8' : 'gpt-5.5', providerId: 'xd', effort: 'high', fast: false, favoriteUid: null }); }} />+ ))}+ </div>),}));@@ -171,24 +142,12 @@ afterEach(() => {});describe('WorkspacePrefsEditor 复用标准选择器', () => {- it('三个字段分别落在标准组件上,且都用 field 形态', () => {+ it('模型与权限使用标准 field,模型内切 Harness', () => {render(<WorkspacePrefsEditor alias="cindy" state={stateWith()} maxVisibleModelRows={6} />);- // agent: 与新建对话工具条同一个引擎下拉,不再是露原始 id 的裸下拉- const agent = screen.getByTestId('agent-select');- expect(agent.getAttribute('data-value')).toBe('cc');- expect(agent.getAttribute('data-side')).toBe('bottom');- // 设置字段形态: 面板宽度绑 trigger(DESIGN.md §4 宽度铁则); dense 与同排 ModelSelector 齐高- expect(agent.getAttribute('data-trigger-variant')).toBe('field');- expect(agent.getAttribute('data-dense')).toBe('true');- // field 形态的 trigger 是 w-full, 外层字段必须自带确定宽度, 否则整列缩到- // 标签固有宽度、面板跟着缩(codex review #1490)。- const agentField = agent.closest('div.flex.min-w-0.flex-col');- expect(agentField?.className).toContain('w-[168px]');- expect(agentField?.className).toContain('basis-[168px]');- expect(agent.textContent).not.toContain('claude-code');-+ expect(screen.queryByTestId('agent-select')).toBeNull();const model = screen.getByTestId('model-selector');+ expect(model.getAttribute('data-fast-configurable')).toBe('false');expect(model.getAttribute('data-model')).toBe('claude-opus-4-8');expect(model.getAttribute('data-vendor')).toBe('cc');expect(model.getAttribute('data-trigger-variant')).toBe('field');@@ -278,9 +237,9 @@ describe('WorkspacePrefsEditor 复用标准选择器', () => {render(<WorkspacePrefsEditor alias="cindy" state={stateWith()} />);expect(screen.getByTestId('model-selector').getAttribute('data-effort')).toBe('high');- // 字段 label 只剩 agent / 模型 / 权限三个+ // 字段 label 只剩模型与权限expect(screen.queryByText('settings.tina.prefs.effortLabel')).toBeNull();- expect(screen.getByText('settings.tina.prefs.agentLabel')).toBeTruthy();+ expect(screen.queryByText('settings.tina.prefs.agentLabel')).toBeNull();expect(screen.getByText('settings.tina.prefs.modelLabel')).toBeTruthy();expect(screen.getByText('settings.tina.prefs.permissionLabel')).toBeTruthy();});@@ -301,15 +260,14 @@ describe('WorkspacePrefsEditor 复用标准选择器', () => {/>,);- expect(screen.getByTestId('agent-select').getAttribute('data-value')).toBe('codex');expect(screen.getByTestId('model-selector').getAttribute('data-vendor')).toBe('codex');expect(screen.getByTestId('permission-selector').getAttribute('data-vendor')).toBe('codex');});- it('不可编辑时整行三个控件同步禁用', () => {+ it('不可编辑时模型与权限同步禁用', () => {render(<WorkspacePrefsEditor alias="cindy" state={stateWith({ editable: false })} />);- expect(screen.getByTestId('agent-select').getAttribute('data-disabled')).toBe('true');+ expect(screen.getByTestId('model-selector').getAttribute('data-disabled')).toBe('true');expect(screen.getByTestId('model-selector').getAttribute('data-disabled')).toBe('true');expect(screen.getByTestId('permission-selector').getAttribute('data-disabled')).toBe('true');});@@ -319,8 +277,8 @@ describe('WorkspacePrefsEditor 复用标准选择器', () => {it('禁用态的 agent 分段在按钮级禁用,键盘也进不去', () => {render(<WorkspacePrefsEditor alias="cindy" state={stateWith({ editable: false })} />);- expect(screen.getByTestId('agent-select').getAttribute('data-disabled')).toBe('true');- const options = ['cc', 'codex', 'pi'].map((v) => screen.getByTestId(`agent-option-${v}`));+ expect(screen.getByTestId('model-selector').getAttribute('data-disabled')).toBe('true');+ const options = ['cc', 'codex', 'pi'].map((v) => screen.getByTestId(`model-harness-${v}`));for (const opt of options) expect((opt as HTMLButtonElement).disabled).toBe(true);options[1]?.click();@@ -329,9 +287,9 @@ describe('WorkspacePrefsEditor 复用标准选择器', () => {it('写入在途时同样按钮级禁用', () => {render(<WorkspacePrefsEditor alias="cindy" state={stateWith({ pendingWs: 'cindy' })} />);- expect(screen.getByTestId('agent-select').getAttribute('data-disabled')).toBe('true');+ expect(screen.getByTestId('model-selector').getAttribute('data-disabled')).toBe('true');for (const vendor of ['cc', 'codex', 'pi']) {- expect((screen.getByTestId(`agent-option-${vendor}`) as HTMLButtonElement).disabled).toBe(+ expect((screen.getByTestId(`model-harness-${vendor}`) as HTMLButtonElement).disabled).toBe(true,);}@@ -361,13 +319,13 @@ describe('WorkspacePrefsEditor 复用标准选择器', () => {);// 重选当前显示的 Claude = 把继承值钉成显式,否则 IM 默认一变这条目录被静默改掉- expect(screen.getByTestId('agent-select').getAttribute('data-reselect-emits')).toBe('true');- screen.getByTestId('agent-option-cc').click();+ expect(screen.getByTestId('model-selector').getAttribute('data-reselect-emits')).toBe('true');+ screen.getByTestId('model-harness-cc').click();expect(applyPatch).toHaveBeenCalledWith('cindy', {agentKind: 'claude-code',- model: null,- effort: null,- });+ model: 'claude-opus-4-8',+ effort: 'high',+ }, 'xd');});it('未知/过期 agentKind 归一到默认 agent,分段控件不禁死', () => {@@ -387,56 +345,50 @@ describe('WorkspacePrefsEditor 复用标准选择器', () => {);// 显示为默认 agent(claude-code)而非裸值;caps 可解析 → 整行不因 null caps 禁死- expect(screen.getByTestId('agent-select').getAttribute('data-value')).toBe('cc');- expect(screen.getByTestId('agent-select').getAttribute('data-disabled')).toBe('false');+ expect(screen.getByTestId('model-selector').getAttribute('data-vendor')).toBe('cc');+ expect(screen.getByTestId('model-selector').getAttribute('data-disabled')).toBe('false');// 用户可以选 Codex 纠正过期值- screen.getByTestId('agent-option-codex').click();+ screen.getByTestId('model-harness-codex').click();expect(applyPatch).toHaveBeenCalledWith('cindy', {agentKind: 'codex',- model: null,- effort: null,- });+ model: 'gpt-5.5',+ effort: 'high',+ }, 'xd');});- it('切换 agent 写入配对 patch(清掉旧模型/档位)', () => {+ it('切换 Harness 原子写入选中的模型与档位,保留权限', () => {render(<WorkspacePrefsEditor alias="cindy" state={stateWith()} />);- screen.getByTestId('agent-option-codex').click();+ screen.getByTestId('model-harness-codex').click();expect(applyPatch).toHaveBeenCalledWith('cindy', {agentKind: 'codex',- model: null,- effort: null,- });+ model: 'gpt-5.5',+ effort: 'high',+ }, 'xd');});- // 能力请求在途/失败(caps=null)不能把 agent 分段禁死:patchForAgentChange 只清- // model/effort、不做能力校准,切 agent 不需要当前 agent 的清单;跟着禁会让瞬时- // 失败变成死局,用户连切到另一个(可用的)agent 都不行(codex review 2026-07-25)。- // 模型/权限字段的选项列表真的来自 caps,维持禁用。- it('caps 未就绪: agent 选择器仍可切换,模型/权限字段禁用', () => {+ // 当前 Harness 的能力失败不能阻止改选另一个 Harness;权限仍依赖当前能力。+ it('当前 Harness caps 未就绪仍能选其他 Harness,权限字段保持禁用', () => {capsUnavailable = true;render(<WorkspacePrefsEditor alias="cindy" state={stateWith()} />);- expect(screen.getByTestId('agent-select').getAttribute('data-disabled')).toBe('false');- screen.getByTestId('agent-option-codex').click();+ expect(screen.getByTestId('model-selector').getAttribute('data-disabled')).toBe('false');+ screen.getByTestId('model-harness-codex').click();expect(applyPatch).toHaveBeenCalledWith('cindy', {agentKind: 'codex',- model: null,- effort: null,- });- expect(screen.getByTestId('model-selector').getAttribute('data-disabled')).toBe('true');+ model: 'gpt-5.5',+ effort: 'high',+ }, 'xd');+ expect(screen.getByTestId('model-selector').getAttribute('data-disabled')).toBe('false');expect(screen.getByTestId('permission-selector').getAttribute('data-disabled')).toBe('true');});// 读屏可及名:三个字段都带「字段名 · 行别名」上下文,多卡片同屏行与行可区分// (三个字段统一经 ariaContext 前置到各自 trigger 的 aria-label)。- it('三个字段都带 alias 化 ariaContext', () => {+ it('两个字段都带 alias 化 ariaContext', () => {render(<WorkspacePrefsEditor alias="cindy" state={stateWith()} />);- expect(screen.getByTestId('agent-select').getAttribute('data-aria-context')).toBe(- 'settings.tina.prefs.agentLabel · cindy',- );expect(screen.getByTestId('model-selector').getAttribute('data-aria-context')).toBe('settings.tina.prefs.modelLabel · cindy',);diff --git a/apps/desktop/src/renderer/components/settings/__tests__/hookWorkspacePrefsLogic.test.ts b/apps/desktop/src/renderer/components/settings/__tests__/hookWorkspacePrefsLogic.test.tsindex 0a5dc993f7..5f73fb1832 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/hookWorkspacePrefsLogic.test.ts+++ b/apps/desktop/src/renderer/components/settings/__tests__/hookWorkspacePrefsLogic.test.ts@@ -7,7 +7,6 @@ import { describe, expect, it } from 'vitest';import {HOOK_DEFAULT_PERMISSION_MODE,- patchForAgentChange,patchForModelChange,resolveEffectiveRow,resolveEffectivePermissionMode,@@ -27,34 +26,6 @@ const CODEX_CAPS: PrefsAgentCaps = {permissionModes: [{ id: 'ask' }, { id: 'bypassPermissions' }],};-describe('patchForAgentChange', () => {- it('换 agent: 清 model/effort(与 agent 强绑定)', () => {- expect(patchForAgentChange('codex')).toEqual({- agentKind: 'codex',- model: null,- effort: null,- });- });-- // 2026-07 安全修正:原实现会在「新 agent 不支持该权限档」时把 permissionMode 清成 null,- // 而 null = 无显式偏好 = 派发侧回落 bypassPermissions(完全访问)。于是用户选了更严的- // acceptEdits, 只要切一下 agent 就被静默放宽 —— 正是原注释声称要防的那件事。- // 现在一律原样保留, 由 resolveEffectivePermissionMode 统一校准到最严档。- it('换 agent: 权限档永不清空 —— 清空会静默放宽成 bypassPermissions', () => {- const patch = patchForAgentChange('codex');- expect(patch).not.toHaveProperty('permissionMode');- expect(patchForAgentChange('claude-code')).not.toHaveProperty('permissionMode');- });-- it('agent 置 null(跟随默认): 整组清空, 权限档保留', () => {- expect(patchForAgentChange(null)).toEqual({- agentKind: null,- model: null,- effort: null,- });- });-});-describe('resolveEffectiveRow — 过期存量值归一化(与派发侧 defaults.ts 同口径)', () => {const IM_DEFAULTS = {agentKind: 'claude-code',diff --git a/apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts b/apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.tsindex 692c16aecb..3f971e6e67 100644--- a/apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts+++ b/apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts@@ -37,23 +37,6 @@ export interface PrefsAgentCaps {permissionModes: Array<{ id: string }>;}-/**- * 换 agent 的联动 patch(next=null 即「跟随默认」)。- *- * **权限档一律原样保留, 绝不因「新 agent 不支持」而清空**(2026-07 安全修正):- * 清空 = 回到「无显式偏好」= 派发侧的 bypassPermissions 历史默认, 于是用户选了- * acceptEdits 再切一下 agent 就被静默放宽成完全访问 —— 正是原注释声称要防的那件事。- * 保留原值后, 显示与派发都由同一个 resolveEffectivePermissionMode 校准到新 agent 的- * **最严**档; 切回原 agent 时用户的原始选择还在, 意图不丢。- */-export function patchForAgentChange(next: string | null): HookPrefsPatch {- if (next === null) {- // 跟随默认: agent/model/effort 整组清空(model/effort 与 agent 强绑定, 换组必失效)- return { agentKind: null, model: null, effort: null };- }- return { agentKind: next, model: null, effort: null };-}-/** 换 model 的联动 patch(agentKind 随手配对写入 + effort 校准)。 */export function patchForModelChange(agentKind: string,diff --git a/apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts b/apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.tsindex e6918f388e..77c919df0b 100644--- a/apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts+++ b/apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts@@ -1,49 +1,10 @@import type {ImDefaultAgentKind,ImDefaultAgentSettings,- ImDefaultEffort,ImDefaultSettingsPatch,ImDefaultSettingsState,} from '../../../shared/imDefaultSettings';-/**- * 切 harness 时把目标 agent 的模型/供应商/思考强度一并收敛到当前可用清单。- *- * 为何必需: 切 agent 只写 agentKind 时, 目标 agent 带的是上次(或出厂默认)- * 的 model —— 那个模型可能已停用、供应商已断开或从未接入。UI 会照显,- * 而 headless runner 派发时才静默降级换模型, 用户无感(正是 modelsByAgent- * 里「停用的供应商/模型不该可选」要防的事, PR #744 review)。changeModel 一直- * 做这层收敛, changeAgent 漏了 —— 两边必须同口径。- *- * available 为空(该 agent 当下一个可用模型都没有)时原样保留已存值: 宁可- * 维持用户选过的值, 也不把它抹成空字符串。- */-export function resolveAgentSwitchSettings(args: {- current: ImDefaultAgentSettings;- available: ReadonlyArray<{ id: string; efforts?: readonly string[] }>;- /**- * 强度解析, **必须传 changeModel 用的那一个**(组件里的 resolveEffort)。- *- * 不要在这里另写一套回落: 那条链是「当前值 → 该模型的 override → 该模型的- * defaultEffort → 该模型首档 → agent 出厂值」, model-specific 的两步在 agent-wide- * 兜底**之前**。本函数曾自己实现成「当前值 → agent-wide → 首档」, 于是切 agent 与- * 切模型对同一个模型给出不同强度(review 指出)。共用同一个函数是唯一不会再分叉的写法。- */- resolveEffort: (modelId: string, requested: ImDefaultEffort) => ImDefaultEffort;- resolveProviderId: (modelId: string, providerId: string | null) => string | null;-}): ImDefaultAgentSettings {- const { current, available, resolveEffort, resolveProviderId } = args;- if (available.length === 0) return current;- const keptModel = available.find((m) => m.id === current.model);- const model = keptModel ?? available[0]!;- return {- model: model.id,- // 模型没换时仍要重解供应商: 旧 providerId 可能指向已断开的供应商。- providerId: resolveProviderId(model.id, keptModel ? current.providerId : null),- effort: resolveEffort(model.id, current.effort),- };-}-export function buildAgentSettingsPatch(agentKind: ImDefaultAgentKind,nextSettings: ImDefaultAgentSettings,diff --git a/apps/desktop/src/renderer/features/cc-agent/CreateWorkerPopover.tsx b/apps/desktop/src/renderer/features/cc-agent/CreateWorkerPopover.tsxindex cb58a6742a..2f9ca4ab44 100644--- a/apps/desktop/src/renderer/features/cc-agent/CreateWorkerPopover.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CreateWorkerPopover.tsx@@ -1,3 +1,4 @@+import { useModelPickerAgents } from '@/hooks/useAvailableAgents';import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { useNavigate } from 'react-router-dom';@@ -118,6 +119,7 @@ export function CreateWorkerPopover({const ccCaps = useAgentCapabilities('claude-code', deviceId);const codexCaps = useAgentCapabilities('codex', deviceId);const piCaps = useAgentCapabilities('pi', deviceId);+ const pickerAgents = useModelPickerAgents(agent, deviceId);const localProviders = useProviders();const remoteProviders = useDeviceProviders(deviceId);const providers = deviceId ? remoteProviders.providers : localProviders.providers;@@ -718,22 +720,15 @@ export function CreateWorkerPopover({)}</div>- <div className="mb-4 grid grid-cols-[220px_minmax(0,1fr)] gap-4">- <div className="min-w-0">- <div className="mb-2 text-12 font-medium uppercase tracking-[0.5px] text-[var(--text-tertiary)]">- {t('orca.createWorker.agentLabel')}- </div>- {/* 应用标准 Agent 分段控件(替换此前手写的按钮组;与 New Maker / IM 目录偏好同款,- 「不自建选择 UI」的组件复用原则)。 */}+ <div className="mb-4 grid gap-4">+ {deviceId && remoteProviders.unsupported && (<VendorSegmentedSwitchervalue={vendorKey}width={220}ariaLabel={t('orca.createWorker.agentLabel')}- onChange={(next) =>- updateAgent(next === 'codex' ? 'codex' : next === 'pi' ? 'pi' : 'claude-code')- }+ onChange={(next) => updateAgent(next === 'codex' ? 'codex' : next === 'pi' ? 'pi' : 'claude-code')}/>- </div>+ )}<div className="min-w-0"><div className="mb-2 text-12 font-medium uppercase tracking-[0.5px] text-[var(--text-tertiary)]">@@ -750,6 +745,16 @@ export function CreateWorkerPopover({<FastModeToggle enabled={fast} onToggle={() => setFast((v) => !v)} />)}<ModelSelector+ fastModeConfigurable={['codex', 'pi']}+ unifiedAgents={sshRemote ? (pickerAgents ?? ['claude-code', 'codex']).filter((kind) => kind !== 'pi') : pickerAgents}+ onUnifiedSelect={deviceId && remoteProviders.unsupported ? undefined : (selection) => {+ const nextAgent = selection.engine === 'cc' ? 'claude-code' : selection.engine;+ updateAgent(nextAgent);+ setModel(selection.modelId);+ setProviderSource(selection.providerId);+ setEffort(selection.effort ?? '');+ setFast(selection.fast);+ }}modelId={model}effort={effort}onModelChange={updateModel}diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/CreateWorkerPopover.test.tsx b/apps/desktop/src/renderer/features/cc-agent/__tests__/CreateWorkerPopover.test.tsxindex 2167475c39..57843e33fb 100644--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/CreateWorkerPopover.test.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/CreateWorkerPopover.test.tsx@@ -134,6 +134,7 @@ vi.mock('react-router-dom', async (importOriginal) => ({vi.mock('@/components/new-chat/ModelSelector', () => ({ModelSelector: (props: {modelId: string;+ onUnifiedSelect?: (selection: { engine: 'cc' | 'codex'; modelId: string; providerId: string; effort: string; fast: boolean; favoriteUid: null }) => void;effort?: string;currentProviderId?: string | null;onProviderChange?: (providerId: string | null, modelId?: string, effort?: string, fast?: boolean) => void;@@ -157,6 +158,8 @@ vi.mock('@/components/new-chat/ModelSelector', () => ({data-effort={props.effort ?? ''}>{props.modelId}+ <button data-testid="pick-claude-model" onClick={() => props.onUnifiedSelect?.({ engine: 'cc', modelId: 'claude-sonnet-4-6', providerId: 'anthropic', effort: 'high', fast: false, favoriteUid: null })} />+ <button data-testid="pick-codex-config" onClick={() => props.onUnifiedSelect?.({ engine: 'codex', modelId: 'gpt-5.5', providerId: 'xd', effort: 'low', fast: false, favoriteUid: null })} /><buttontype="button"data-testid="pick-openai-row"@@ -246,7 +249,7 @@ describe('CreateWorkerPopover', () => {resetProviderModelMemoryForTest();});- it('centers the setup and keeps agent and model on one row without changing its size', () => {+ it('centers the setup and uses one model picker without a competing Harness control', () => {render(<CreateWorkerPopover open onClose={vi.fn()} onCreate={vi.fn()} />);const panel = screen.getByText('orca.createWorker.title').closest('.relative.z-10');@@ -257,12 +260,8 @@ describe('CreateWorkerPopover', () => {expect(panel?.className).toContain('w-[500px]');expect(panel?.className).toContain('p-6');- const agentSwitcher = screen.getByRole('tablist', {- name: 'orca.createWorker.agentLabel',- });- const pairedFields = agentSwitcher.closest('.grid');- expect(pairedFields?.className).toContain('grid-cols-[220px_minmax(0,1fr)]');- expect(pairedFields?.contains(screen.getByTestId('model-selector'))).toBe(true);+ expect(screen.queryByRole('tablist', { name: 'orca.createWorker.agentLabel' })).toBeNull();+ expect(screen.getByTestId('model-selector').closest('.grid')).toBeTruthy();const permissionMode = screen.getByTestId('worker-permission-mode');expect(permissionMode.textContent).toContain('orca.createWorker.permissionLabel');@@ -591,7 +590,7 @@ describe('CreateWorkerPopover', () => {await waitFor(() =>expect(screen.getByTestId('model-selector').textContent).toBe('codex/gpt-5.5'),);- fireEvent.click(screen.getByRole('tab', { name: 'Claude' }));+ fireEvent.click(screen.getByTestId('pick-claude-model'));await waitFor(() =>expect(screen.getByTestId('model-selector').textContent).toBe('claude-sonnet-4-6'),@@ -1063,7 +1062,7 @@ describe('CreateWorkerPopover', () => {);});- it('keeps live source and effort edits across agent tab switches', async () => {+ it('saves the complete selected configuration after switching Harness twice', async () => {// 切 tab 的恢复读的是 prefs:切走前必须把当前 agent 的 live 编辑快照进内存// prefs,否则「选好来源/改好 effort 还没提交就切了个 tab」会被静默回滚到打开// 弹窗时的旧值(codex review)。@@ -1094,6 +1093,8 @@ describe('CreateWorkerPopover', () => {{ id: 'gpt-5.5', efforts: ['low', 'medium', 'high'], defaultEffort: 'high', supportsFastMode: false },];mocks.capabilitiesByAgent.codex = { availableModels: [{ id: 'gpt-5.5' }] };+ mocks.modelsByAgent['claude-code'] = [model('claude-sonnet-4-6')];+ mocks.capabilitiesByAgent['claude-code'] = { availableModels: [{ id: 'claude-sonnet-4-6' }] };const onCreate = vi.fn();render(<CreateWorkerPopover open onClose={vi.fn()} onCreate={onCreate} />);@@ -1102,11 +1103,11 @@ describe('CreateWorkerPopover', () => {);fireEvent.click(screen.getByTestId('pick-xd-row-bare'));fireEvent.click(screen.getByTestId('edit-active-effort'));- fireEvent.click(screen.getByRole('tab', { name: 'Claude' }));+ fireEvent.click(screen.getByTestId('pick-claude-model'));await waitFor(() =>- expect(screen.getByTestId('model-selector').textContent).toContain('claude-opus-4-7'),+ expect(screen.getByTestId('model-selector').textContent).toContain('claude-sonnet-4-6'),);- fireEvent.click(screen.getByRole('tab', { name: 'Codex' }));+ fireEvent.click(screen.getByTestId('pick-codex-config'));await waitFor(() =>expect(screen.getByTestId('model-selector').dataset.currentProvider).toBe('xd'),);diff --git a/apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx b/apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsxindex 21815567dc..8f6cdb98e6 100644--- a/apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx+++ b/apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx@@ -29,6 +29,7 @@ import { Plus, Timer } from 'lucide-react';import { useLocation, useNavigate } from 'react-router-dom';import { useTranslation } from 'react-i18next';+import { scheduleToUserCreateInput } from './lib/scheduleFormLogic';import { cn } from '@/lib/utils';import { WINDOW_DRAG_STYLE, WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';import { toast } from '@/lib/toast';@@ -68,30 +69,6 @@ import {readPluginScheduleCreateIntent,} from './lib/pluginScheduleCreateIntent';-function scheduleToUserCreateInput(- schedule: Schedule,- overrides: Partial<CreateScheduleInput> = {},-): CreateScheduleInput {- return {- name: schedule.name,- prompt: schedule.prompt,- kind: schedule.kind,- cronExpr: schedule.cronExpr,- timezone: schedule.timezone,- recurring: schedule.recurring,- manual: schedule.manual,- intervalMs: schedule.intervalMs,- agentKind: schedule.agentKind,- model: schedule.model,- effort: schedule.effort,- workspaceKind: schedule.workspaceKind,- workingDir: schedule.workingDir,- useWorktree: schedule.useWorktree,- persistentSession: schedule.persistentSession,- notify: schedule.notify,- ...overrides,- };-}/*** 排序:active 与 expired 同 rank(一次性已跑完的任务不再单独沉底,diff --git a/apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsx b/apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsxindex edd0ca1dba..7d3d615ebd 100644--- a/apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsx+++ b/apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsx@@ -1,11 +1,10 @@+import { useModelPickerAgents } from '@/hooks/useAvailableAgents';import * as React from 'react';import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { ChevronDown, ExternalLink, Folder, MessageCircle, Timer, SlidersHorizontal } from 'lucide-react';import { useTranslation } from 'react-i18next';import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/popover';import { Tip } from '@/components/ui/tooltip';-import { agentKindToVendor } from '@/components/sidebar/VendorIcon';-import { AgentSelect } from '@/components/new-chat/AgentSelect';import {addRecentFolder,FolderPickerPopover,@@ -166,28 +165,6 @@ export function ProjectChip({);}-/**- * Scheduler compatibility adapter: keep the persisted scheduler kind shape,- * while sharing the same AgentSelect dropdown used by IM settings and chat.- */-export function AgentTabs({ value, onChange, disabled }: { value: AgentKind; onChange: (v: AgentKind) => void; disabled?: boolean }) {- return (- <AgentSelect- value={agentKindToVendor(value)}- disabled={disabled}- side="top"- // ScheduleFormDialog 是 Radix modal。MorphPopover 的 custom portal 不在- // Dialog focus scope 内,动画结束聚焦选中项时会被拉回并立即自动收起;- // 此处使用 Radix Popover,让嵌套焦点与 outside-interaction 语义正确组合。- useMorphPopover={false}- overlayContentClassName="z-[10010]"- onChange={(vendor) => {- onChange(vendor === 'cc' ? 'claude-code' : vendor === 'pi' ? 'pi' : 'codex');- }}- />- );-}-export function ScheduleSettingsButton({cwd,enabled,@@ -1047,6 +1024,8 @@ function previewConfigFor(mode: EditableScheduleMenuMode, current: CodexSchedule}export function ModelEffortChip({+ onSelect,+ onFollowSession,agentKind,modelValue,onChangeModel,@@ -1060,6 +1039,8 @@ export function ModelEffortChip({fastMode,onChangeFast,}: {+ onSelect: NonNullable<React.ComponentProps<typeof ModelSelectorContent>['onUnifiedSelect']>;+ onFollowSession: () => void;agentKind: AgentKind;modelValue: string;onChangeModel: (v: string) => void;@@ -1078,7 +1059,7 @@ export function ModelEffortChip({onChangeProviderId: (providerId: string) => void;/** 0 个 / 引导连接来源时跳设置→供应商页;不传则来源轨不显示「连接」入口。 */onNavigateToProviders?: () => void;- /** Fast 模式状态 + 回调(与聊天一致,收进模型选择器 Edit 配置列)。heartbeat 态不传 → Edit 无 Fast。 */+ /** Fast 模式状态 + 回调(与聊天一致,收进模型选择器 Edit 配置列)。绑定任务同样保存,下一次触发时应用。 */fastMode?: boolean;onChangeFast?: (v: boolean) => void;}) {@@ -1107,6 +1088,7 @@ export function ModelEffortChip({},[disabled, discovery],);+ const pickerAgents = useModelPickerAgents(agentKind);const caps = useAgentCapabilities(agentKind);// 触发器(trigger)展示用:仍按 codex/ 折扣模型的 XD 网关来源可见性过滤,算出当前// 选中模型名。下拉内容本体改用聊天的 ModelSelectorContent(它内部按来源/api-key 自行@@ -1133,9 +1115,12 @@ export function ModelEffortChip({const followsSessionModel = usesBoundSessionModel({ followSession, model: modelValue });const effectiveId = followsSessionModel ? '' : modelValue || getScheduleDefaultModel(agentKind);const current = models.find((m) => m.id === effectiveId);- const allowedEfforts = (current?.efforts ?? []) as readonly EffortValue[];- const fallbackEffort = (current?.defaultEffort ?? 'high') as EffortValue;- const effectiveEffort: EffortValue = effortValue && allowedEfforts.includes(effortValue) ? effortValue : fallbackEffort;+ const sourceId = effectiveSourceIdForModel(providers, providerId || null, effectiveId, agentKind);+ const source = providers.find((provider) => provider.id === sourceId);+ const catalogModel = source ? getModel(source, effectiveId, agentKind) : undefined;+ const effectiveEffort = effortValue || catalogModel?.defaultEffort || current?.defaultEffort || '';+ const modelLabel = catalogModel?.name || current?.displayName || effectiveId;+ const agentLabel = t(`newChat.modelSelector.trigger.agent.${agentKind === 'claude-code' ? 'claudeCode' : agentKind}`);const effortLabel = (e: EffortValue) => t(`effortLevels.${e}`);const display = followsSessionModel? [@@ -1145,9 +1130,8 @@ export function ModelEffortChip({: null,effortValue ? effortLabel(effortValue) : null,].filter(Boolean).join(' · ')- : current- ? `${current.displayName} · ${allowedEfforts.length ? effortLabel(effectiveEffort) : t('scheduler.chips.model.effortDefault')}`- : t('scheduler.chips.model.default');+ : [agentLabel, modelLabel, effectiveEffort ? effortLabel(effectiveEffort as EffortValue) : null,+ fastMode ? '⚡' : null].filter(Boolean).join(' · ');// railSources 仅用于 nativeDefault 归一化(下拉宽度由 ModelSelectorContent 内容自适应,见 w-auto)。const vendorKey = agentKind === 'claude-code' ? 'cc' : agentKind;@@ -1215,6 +1199,9 @@ export function ModelEffortChip({{/* 直接复用聊天的下拉内容本体(唯一真源:聊天选择器改了这里跟着变)。来源轨 / 模型分组 / 搜索 / effort / 空态全套自带;followSession 行为 opt-in。 */}<ModelSelectorContent+ fastModeConfigurable={['codex', 'pi']}+ unifiedAgents={pickerAgents}+ onUnifiedSelect={onSelect}vendorKey={vendorKey}modelId={effectiveId}effort={effectiveEffort}@@ -1246,9 +1233,7 @@ export function ModelEffortChip({active: isFollowingSession,label: t('scheduler.chips.model.followSession'),onFollow: () => {- onChangeModel('');- onChangeEffort('');- onChangeProviderId('');+ onFollowSession();},}: undefineddiff --git a/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx b/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsxindex a2ee457a93..795a4d2f23 100644--- a/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx+++ b/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx@@ -23,7 +23,6 @@ import { applyTemplateParams } from '@cindy/maker-scheduler/template-engine';import { ScriptCapabilityMultiSelect } from './ScriptCapabilityMultiSelect';import {- getScheduleAgentPrefs,getScheduleDefaultModel,rememberScheduleFormPrefs,useScheduleForm,@@ -50,7 +49,6 @@ import {generateProjectScheduleId,} from '../lib/projectAutomationConfig';import {- AgentTabs,ModelEffortChip,ProjectChip,ScheduleChip,@@ -131,7 +129,7 @@ export function ScheduleFormDialog({}: Props) {const { t } = useTranslation();const formApi = useScheduleForm(initial);- const { form, setField, setDestination, setRunMode, selectBoundSession, applyTemplateAgentFields, reset, toInput, validate } = formApi;+ const { form, setField, selectModelConfiguration, setDestination, setRunMode, selectBoundSession, applyTemplateAgentFields, reset, toInput, validate } = formApi;const caps = useAgentCapabilities(form.agentKind);const { providers } = useProviders();// "运行会话"三态(fresh / persistent / bound)与心跳形态派生值。@@ -454,10 +452,10 @@ export function ScheduleFormDialog({}, [form.model, form.agentKind, form.targetSessionId, setField]);useEffect(() => {- if (!currentModelEfforts || !form.effort) return;+ if (form.modelAgentKind || !currentModelEfforts || !form.effort) return;const allowed = currentModelEfforts as readonly string[];if (!allowed.includes(form.effort)) setField('effort', '');- }, [currentModelEfforts, form.effort, setField]);+ }, [form.modelAgentKind, currentModelEfforts, form.effort, setField]);// Fast 模式门控:agent 级 hasFastMode × 该 (生效来源, 模型) 的 supportsFastMode(per-provider,// 唯一真相)。生效来源按 form.providerId 解析(空则该模型的默认来源)。Claude 当前 hasFastMode@@ -471,8 +469,10 @@ export function ScheduleFormDialog({// 切到 Claude / 不支持 fast 的模型时,清掉表单里残留的 fast 态,// 杜绝脏值经 toInput 流向 createSession(与上面 effort 失配自动清除同思路)。useEffect(() => {- if (form.fastMode && !showFastModeToggle) setField('fastMode', false);- }, [form.fastMode, showFastModeToggle, setField]);+ if (!form.modelAgentKind && !caps.loading && providers.length > 0 && form.fastMode && !showFastModeToggle) {+ setField('fastMode', false);+ }+ }, [form.modelAgentKind, caps.loading, providers.length, form.fastMode, showFastModeToggle, setField]);const handleSubmit = async () => {const err = validate();@@ -1404,23 +1404,14 @@ export function ScheduleFormDialog({</>)}<div className="min-w-0 flex-1" />- {/* 有真实绑定时 agentKind 跟随绑定会话,切换只会造成 resume 错配 → 禁用 */}- <AgentTabs- value={form.agentKind}- disabled={isBound}- onChange={(v) => {- const prefs = getScheduleAgentPrefs(v);- setField('agentKind', v);- // model 走三级回退(含 prefs.model),保证切 agent 后也是显式值- setField('model', getScheduleDefaultModel(v));- // providerId 沿用该 agent 的任务记忆;新 agent 未连同一来源时- // ModelSelectorContent 会回落到其原生默认(activeSourceId),不会错路由。- setField('providerId', prefs.providerId);- setField('effort', prefs.effort);- setField('fastMode', prefs.fastMode);- }}- /><ModelEffortChip+ onSelect={({ engine, modelId, providerId, effort, fast }) => selectModelConfiguration({+ agentKind: engine === 'cc' ? 'claude-code' : engine,+ model: modelId, providerId, effort: (effort ?? '') as typeof form.effort,+ fastMode: fast,+ })}+ onFollowSession={() => selectModelConfiguration(null,+ boundSessionReference?.agentKind === 'cc' ? 'claude-code' : boundSessionReference?.agentKind)}agentKind={form.agentKind}modelValue={form.model}onChangeModel={(v) => setField('model', v)}@@ -1431,7 +1422,11 @@ export function ScheduleFormDialog({onChangeProviderId={(v) => setField('providerId', v)}onNavigateToProviders={() => navigate('/settings?tab=providers')}fastMode={form.fastMode}- onChangeFast={hideWorkspaceFields ? undefined : (v) => setField('fastMode', v)}+ onChangeFast={(v) => {+ setField('fastMode', v);+ // Fast-only edits also make legacy model selections explicit.+ if (form.model.trim()) setField('modelAgentKind', form.agentKind);+ }}/></div><buttondiff --git a/apps/desktop/src/renderer/features/scheduler/hooks/__tests__/useScheduleForm.validate.test.tsx b/apps/desktop/src/renderer/features/scheduler/hooks/__tests__/useScheduleForm.validate.test.tsxindex 97bc2d2b17..f3513e9975 100644--- a/apps/desktop/src/renderer/features/scheduler/hooks/__tests__/useScheduleForm.validate.test.tsx+++ b/apps/desktop/src/renderer/features/scheduler/hooks/__tests__/useScheduleForm.validate.test.tsx@@ -2,8 +2,11 @@import { act, renderHook } from '@testing-library/react';import { describe, expect, it } from 'vitest';+import type { Schedule, ScheduleTemplate } from '@cindy/maker-scheduler';+import type { Session } from '@/lib/ccAgent.types';import { useScheduleForm } from '../useScheduleForm';+import { formToProjectConfig } from '../../lib/projectAutomationConfig';/*** 回归(codex review #966):script 模式不展示前置检查区块,buildScheduleInput@@ -38,3 +41,123 @@ describe('useScheduleForm validate — script 模式跳过隐藏的前置检查expect(result.current.validate()).toBeNull();});});+++describe('saved automation model selection', () => {+ const template: ScheduleTemplate = {+ id: 'model-template', name: 'Model template', description: '',+ category: 'code-quality', source: 'builtin',+ };++ it.each(['codex', 'pi'] as const)('saves the %s template Harness with its model after binding a task', (agentKind) => {+ const { result } = renderHook(() => useScheduleForm(null));+ act(() => result.current.selectBoundSession({ id: 'bound-codex', agentKind: 'codex' } as Session));+ expect(result.current.toInput()).toHaveProperty('modelAgentKind', undefined);++ act(() => result.current.applyTemplateAgentFields({+ ...template, agentKind, model: 'template-model', providerId: 'custom', effort: 'medium', fastMode: true,+ }));+ expect(result.current.toInput()).toMatchObject({+ targetSessionId: 'bound-codex', agentKind: 'codex', modelAgentKind: agentKind,+ model: 'template-model', providerId: 'custom', effort: 'medium', fastMode: true,+ });++ act(() => result.current.selectModelConfiguration(null));+ expect(result.current.toInput()).toMatchObject({+ targetSessionId: 'bound-codex', agentKind: 'codex', modelAgentKind: undefined,+ model: undefined, providerId: undefined, effort: undefined, fastMode: undefined,+ });+ });++ it('keeps following the bound task when the template supplies no model selection', () => {+ const { result } = renderHook(() => useScheduleForm(null));+ act(() => result.current.selectBoundSession({ id: 'bound-codex', agentKind: 'codex' } as Session));+ act(() => result.current.applyTemplateAgentFields(template));+ expect(result.current.toInput()).toMatchObject({+ targetSessionId: 'bound-codex', agentKind: 'codex', modelAgentKind: undefined,+ model: undefined, providerId: undefined, effort: undefined, fastMode: undefined,+ });+ });++ it('saves every selected axis for the next fire and clears all overrides when following the task', () => {+ const { result } = renderHook(() => useScheduleForm(null));+ const baselineAgent = result.current.form.agentKind;+ act(() => result.current.setField('targetSessionId', 'existing-task'));+ act(() => result.current.selectModelConfiguration({+ agentKind: 'pi', model: 'test-model', providerId: 'custom', effort: 'medium', fastMode: true,+ }));+ expect(result.current.toInput()).toMatchObject({+ targetSessionId: 'existing-task', agentKind: baselineAgent, modelAgentKind: 'pi',+ model: 'test-model', providerId: 'custom', effort: 'medium', fastMode: true,+ });+ act(() => result.current.setRunMode('fresh'));+ act(() => result.current.setRunMode('bound'));+ expect(result.current.toInput()).toMatchObject({ modelAgentKind: 'pi', model: 'test-model', fastMode: true });+ act(() => result.current.selectModelConfiguration(null));+ expect(result.current.toInput()).toMatchObject({ modelAgentKind: undefined, model: undefined, effort: undefined, providerId: undefined });+ expect(result.current.form.fastMode).toBe(false);+ expect(result.current.toInput()).toHaveProperty('fastMode', undefined);+ });++ it('restores the bound Harness after an explicit override and fresh/persistent round trip', () => {+ const { result } = renderHook(() => useScheduleForm(null));+ act(() => result.current.selectBoundSession({ id: 'bound-codex', agentKind: 'codex' } as Session));+ act(() => result.current.setRunMode('persistent'));+ act(() => result.current.selectModelConfiguration({+ agentKind: 'pi', model: 'test-model', providerId: 'custom', effort: 'medium', fastMode: true,+ }));+ act(() => result.current.setRunMode('fresh'));+ act(() => result.current.setRunMode('persistent'));+ act(() => result.current.selectModelConfiguration(null));+ expect(result.current.toInput()).toMatchObject({+ targetSessionId: 'bound-codex', persistentSession: true, agentKind: 'codex',+ modelAgentKind: undefined, model: undefined, effort: undefined, providerId: undefined,+ });+ expect(result.current.form.fastMode).toBe(false);+ });++ it('uses the current bound reference when reopening a saved override', () => {+ const { result } = renderHook(() => useScheduleForm(null));+ const saved = { ...result.current.toInput(), id: 'schedule', targetSessionId: 'bound-codex',+ agentKind: 'pi', modelAgentKind: 'pi', model: 'test-model' } as Schedule;+ act(() => result.current.reset(saved));+ act(() => result.current.selectModelConfiguration(null, 'codex'));+ expect(result.current.toInput()).toMatchObject({ agentKind: 'codex', modelAgentKind: undefined });+ act(() => result.current.selectModelConfiguration({+ agentKind: 'pi', model: 'test-model', providerId: 'custom', effort: 'medium', fastMode: false,+ }));+ act(() => result.current.selectModelConfiguration(null));+ expect(result.current.toInput()).toMatchObject({ agentKind: 'codex', modelAgentKind: undefined });+ });++ it.each([false, true])('preserves the bound baseline across save, reopen and follow (persistent: %s)', (persistentSession) => {+ const { result } = renderHook(() => useScheduleForm(null));+ const saved = { ...result.current.toInput(), id: 'schedule', targetSessionId: 'bound-codex',+ agentKind: 'codex', modelAgentKind: 'pi', model: 'test-model', persistentSession } as Schedule;+ act(() => result.current.reset(saved));+ act(() => result.current.setField('name', 'Renamed'));+ expect(result.current.form.agentKind).toBe('pi');+ const input = result.current.toInput();+ expect(input).toMatchObject({ name: 'Renamed', agentKind: 'codex', modelAgentKind: 'pi', model: 'test-model' });+ expect(input).not.toHaveProperty('boundAgent');+ expect(formToProjectConfig(result.current.form, 'daily')).toMatchObject({ agentKind: 'codex', modelAgentKind: 'pi' });+ act(() => result.current.reset({ ...saved, ...input } as Schedule));+ act(() => result.current.setRunMode('fresh'));+ expect(result.current.toInput()).toMatchObject({ agentKind: 'pi', modelAgentKind: 'pi', targetSessionId: undefined });+ act(() => result.current.setRunMode(persistentSession ? 'persistent' : 'bound'));+ expect(result.current.toInput()).toMatchObject({ agentKind: 'codex', modelAgentKind: 'pi' });+ act(() => result.current.selectModelConfiguration(null));+ expect(result.current.toInput()).toMatchObject({ agentKind: 'codex', modelAgentKind: undefined, model: undefined });+ });++ it('does not restore a previous target Harness after selecting another bound task', () => {+ const { result } = renderHook(() => useScheduleForm(null));+ act(() => result.current.selectBoundSession({ id: 'old', agentKind: 'codex' } as Session));+ act(() => result.current.selectBoundSession({ id: 'new', agentKind: 'cc' } as Session));+ act(() => result.current.selectModelConfiguration({+ agentKind: 'pi', model: 'test-model', providerId: 'custom', effort: 'medium', fastMode: false,+ }));+ act(() => result.current.selectModelConfiguration(null));+ expect(result.current.toInput()).toMatchObject({ targetSessionId: 'new', agentKind: 'claude-code' });+ });+});diff --git a/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.ts b/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.tsindex e536cb146c..5ca39caaf3 100644--- a/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.ts+++ b/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.ts@@ -230,7 +230,9 @@ export function makeFormFromSchedule(s: Schedule | null): ScheduleFormState {timezone: s.timezone,recurring: s.recurring,manual: s.manual,- agentKind: s.agentKind,+ agentKind: s.modelAgentKind ?? s.agentKind,+ modelAgentKind: s.modelAgentKind,+ boundAgent: s.targetSessionId ? { sessionId: s.targetSessionId, agentKind: s.agentKind } : undefined,model: s.model ?? '',providerId: s.providerId ?? '',effort: s.effort && isEffortValue(s.effort) ? s.effort : '',@@ -257,6 +259,10 @@ export type Destination = 'local' | 'worktree' | 'thread';export interface UseScheduleFormResult {form: ScheduleFormState;+ selectModelConfiguration: (+ selection: Pick<ScheduleFormState, 'agentKind' | 'model' | 'providerId' | 'effort' | 'fastMode'> | null,+ followedAgentKind?: ScheduleFormState['agentKind'],+ ) => void;setField: <K extends keyof ScheduleFormState>(k: K, v: ScheduleFormState[K]) => void;/** 改 destination 时同步改 useWorktree / targetSessionId 三态互斥。 */setDestination: (d: Destination) => void;@@ -302,20 +308,41 @@ export function useScheduleForm(initial: Schedule | null = null): UseScheduleFor[],);+ const selectModelConfiguration: UseScheduleFormResult['selectModelConfiguration'] = useCallback((selection, followedAgentKind) => {+ setForm((form) => {+ if (selection) {+ const boundAgent = form.targetSessionId && form.targetSessionId !== PENDING_SESSION_ID &&+ form.boundAgent?.sessionId !== form.targetSessionId+ ? { sessionId: form.targetSessionId, agentKind: form.agentKind } : form.boundAgent;+ return { ...form, ...selection, boundAgent, modelAgentKind: selection.agentKind };+ }+ const agentKind = followedAgentKind ??+ (form.boundAgent?.sessionId === form.targetSessionId+ ? form.boundAgent.agentKind : form.agentKind);+ const boundAgent = followedAgentKind && form.targetSessionId+ ? { sessionId: form.targetSessionId, agentKind } : form.boundAgent;+ return { ...form, agentKind, boundAgent, model: '', providerId: '', effort: '', fastMode: false, modelAgentKind: undefined };+ });+ }, []);+const reset = useCallback((s: Schedule | null = null, overrides?: Partial<ScheduleFormState>) => {const next = { ...makeFormFromSchedule(s), ...overrides };+ if (next.targetSessionId && next.boundAgent?.sessionId !== next.targetSessionId) {+ next.boundAgent = { sessionId: next.targetSessionId, agentKind: s?.agentKind ?? next.agentKind };+ }lastBindingRef.current = captureBinding(next);setForm(next);}, []);const applyTemplateAgentFields = useCallback((template: ScheduleTemplate) => {- setForm((f) => ({- ...f,- ...resolveTemplateAgentFields(f, template, {+ setForm((f) => {+ const selection = resolveTemplateAgentFields(f, template, {getDefaultModel: getScheduleDefaultModel,getAgentPrefs: getScheduleAgentPrefs,- }),- }));+ });+ // A template that supplies a model is an explicit selection, even while following a bound task.+ return { ...f, ...selection, modelAgentKind: selection.model.trim() ? selection.agentKind : undefined };+ });}, []);/**@@ -364,7 +391,9 @@ export function useScheduleForm(initial: Schedule | null = null): UseScheduleFor...f,targetSessionId: session.id,agentKind: sessionAgentKindToScheduleAgentKind(session.agentKind),+ boundAgent: { sessionId: session.id, agentKind: sessionAgentKindToScheduleAgentKind(session.agentKind) },model: '',+ modelAgentKind: undefined,// 绑定会话 = 跟随其模型/来源,providerId 一并清空(与 model/effort 同语义)。providerId: '',effort: '',@@ -416,5 +445,5 @@ export function useScheduleForm(initial: Schedule | null = null): UseScheduleFor// heartbeat 分支 model/effort 恒带 key(空值 undefined → update patch 清列 = 跟随会话)。const toInput = useCallback((): CreateScheduleInput => buildScheduleInput(form), [form]);- return { form, setField, setDestination, setRunMode, selectBoundSession, applyTemplateAgentFields, reset, toInput, validate };+ return { form, setField, selectModelConfiguration, setDestination, setRunMode, selectBoundSession, applyTemplateAgentFields, reset, toInput, validate };}diff --git a/apps/desktop/src/renderer/features/scheduler/lib/__tests__/projectAutomationConfig.test.ts b/apps/desktop/src/renderer/features/scheduler/lib/__tests__/projectAutomationConfig.test.tsindex c6d00f3278..907a1f9a02 100644--- a/apps/desktop/src/renderer/features/scheduler/lib/__tests__/projectAutomationConfig.test.ts+++ b/apps/desktop/src/renderer/features/scheduler/lib/__tests__/projectAutomationConfig.test.ts@@ -1,6 +1,7 @@import { describe, it, expect } from 'vitest';-import { formToProjectConfig, projectAutomationConfigPath } from '../projectAutomationConfig';+import { formToProjectConfig, projectAutomationConfigPath, scheduleToProjectConfig } from '../projectAutomationConfig';+import type { Schedule } from '@cindy/maker-scheduler';import type { ScheduleFormState } from '../scheduleFormLogic';describe('projectAutomationConfigPath', () => {@@ -78,3 +79,32 @@ describe('project automation providerId serialization', () => {expect(config.providerId).toBe('openai');});});++describe('project automation explicit Harness serialization', () => {+ it('preserves the selection through JSON and omits its marker when following', () => {+ const form = makeForm({ agentKind: 'pi', modelAgentKind: 'pi', model: 'test-model',+ providerId: 'custom', effort: 'medium', fastMode: true, persistentSession: true,+ targetSessionId: 'bound-codex' });+ expect(JSON.parse(JSON.stringify(formToProjectConfig(form, 'daily')))).toMatchObject({+ agentKind: 'pi', modelAgentKind: 'pi', model: 'test-model', providerId: 'custom',+ effort: 'medium', fastMode: true, persistentSession: true,+ });+ const followed = JSON.parse(JSON.stringify(formToProjectConfig({ ...form,+ agentKind: 'codex', modelAgentKind: undefined, model: '', providerId: '', effort: '', fastMode: false,+ }, 'daily')));+ expect(followed.agentKind).toBe('codex');+ expect(followed).not.toHaveProperty('modelAgentKind');+ expect(followed).not.toHaveProperty('model');+ expect(followed).not.toHaveProperty('fastMode');+ });++ it('preserves the explicit Harness when exporting an existing schedule', () => {+ const config = scheduleToProjectConfig({+ id: 's1', name: 'n', prompt: 'p', cronExpr: '0 9 * * *',+ agentKind: 'codex', modelAgentKind: 'pi', model: 'test-model', persistentSession: true,+ } as Schedule, 'daily');+ expect(JSON.parse(JSON.stringify(config))).toMatchObject({+ agentKind: 'codex', modelAgentKind: 'pi', model: 'test-model', persistentSession: true,+ });+ });+});diff --git a/apps/desktop/src/renderer/features/scheduler/lib/__tests__/scheduleFormLogic.test.ts b/apps/desktop/src/renderer/features/scheduler/lib/__tests__/scheduleFormLogic.test.tsindex ca1e1305b1..e391219136 100644--- a/apps/desktop/src/renderer/features/scheduler/lib/__tests__/scheduleFormLogic.test.ts+++ b/apps/desktop/src/renderer/features/scheduler/lib/__tests__/scheduleFormLogic.test.ts@@ -17,11 +17,12 @@*/import { describe, expect, it } from 'vitest';-import type { ScheduleTemplate } from '@cindy/maker-scheduler';+import type { Schedule, ScheduleTemplate } from '@cindy/maker-scheduler';import type { ProviderView } from '@cindy/model-providers';import {PENDING_SESSION_ID,+ scheduleToUserCreateInput,buildHookCommandForScriptFile,applyRunMode,buildScheduleInput,@@ -867,3 +868,19 @@ describe('formToProjectConfig — preRunHook 序列化(项目自动化)', () =>expect(config.preRunHook).toEqual({ command: 'node scripts/check.mjs', timeoutMs: 30_000 });});});+++describe('scheduleToUserCreateInput', () => {+ it.each([undefined, 'pi'] as const)('copies the full model choice into an unbound task (override: %s)', (modelAgentKind) => {+ const original = { id: 'project-job', name: 'Job', source: 'project', projectConfigId: 'project',+ agentKind: 'codex', modelAgentKind, model: 'shared-model', providerId: 'selected', effort: 'high',+ fastMode: true, targetSessionId: 'old-target', persistentSession: true,+ } as Schedule;+ const input = scheduleToUserCreateInput(original, { name: 'Copy' });+ expect(input).toMatchObject({ name: 'Copy', agentKind: modelAgentKind ?? 'codex', modelAgentKind,+ model: 'shared-model', providerId: 'selected', effort: 'high', fastMode: true, persistentSession: true });+ expect(input).not.toHaveProperty('targetSessionId');+ expect(input).not.toHaveProperty('projectConfigId');+ expect(original.agentKind).toBe('codex');+ });+});diff --git a/apps/desktop/src/renderer/features/scheduler/lib/projectAutomationConfig.ts b/apps/desktop/src/renderer/features/scheduler/lib/projectAutomationConfig.tsindex 22249c265b..9ea4f22ccb 100644--- a/apps/desktop/src/renderer/features/scheduler/lib/projectAutomationConfig.ts+++ b/apps/desktop/src/renderer/features/scheduler/lib/projectAutomationConfig.ts@@ -1,6 +1,6 @@import type { Schedule } from '@cindy/maker-scheduler';-import { buildPreRunHook } from './scheduleFormLogic';+import { buildPreRunHook, scheduleAgentKindForForm } from './scheduleFormLogic';import type { ScheduleFormState } from '../hooks/useScheduleForm';import { stripTrailingPathSeparators } from '../../../../shared/pathText';import { PROJECT_AUTOMATION_REL_SEGMENTS } from '../../../../shared/projectAutomationPaths';@@ -15,6 +15,8 @@ export interface ProjectScheduleConfig {manual?: boolean;intervalMs?: number;agentKind?: 'claude-code' | 'codex' | 'pi';+ /** 显式模型选择的 Harness;省略时保留旧配置的跟随绑定任务语义。 */+ modelAgentKind?: 'claude-code' | 'codex' | 'pi';model?: string;/** 显式来源(供应商)id;省略 = 使用该 Agent 的原生默认来源。 */providerId?: string;@@ -58,6 +60,7 @@ export function scheduleToProjectConfig(manual: schedule.manual,intervalMs: schedule.intervalMs,agentKind: schedule.agentKind,+ modelAgentKind: schedule.modelAgentKind,model: schedule.model,providerId: schedule.providerId || undefined,effort: schedule.effort,@@ -86,7 +89,8 @@ export function formToProjectConfig(recurring: form.recurring,manual: form.manual,intervalMs: form.intervalMs,- agentKind: form.agentKind,+ agentKind: scheduleAgentKindForForm(form),+ modelAgentKind: form.model.trim() ? form.modelAgentKind : undefined,model: form.model.trim() || undefined,providerId: form.providerId.trim() || undefined,effort: form.effort || undefined,diff --git a/apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.ts b/apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.tsindex 188febd361..b64e8e37e3 100644--- a/apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.ts+++ b/apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.ts@@ -14,7 +14,7 @@* - buildScheduleInput:表单 → CreateScheduleInput(原 toInput 迁入)*/-import type { CreateScheduleInput, ScheduleTemplate, ScheduleWorkspaceKind, ScriptCapability } from '@cindy/maker-scheduler';+import type { Schedule, CreateScheduleInput, ScheduleTemplate, ScheduleWorkspaceKind, ScriptCapability } from '@cindy/maker-scheduler';import {effectiveSourceIdForModel,getModel,@@ -120,6 +120,9 @@ export interface ScheduleFormState {/** 手动模式:true → 创建后永不自动 fire,只能 Run now。UI 上需要 recurring=false 才能勾。 */manual: boolean;agentKind: 'claude-code' | 'codex' | 'pi';+ modelAgentKind?: 'claude-code' | 'codex' | 'pi';+ /** The bound task's baseline, independent of the editable model choice. Form-only. */+ boundAgent?: { sessionId: string; agentKind: ScheduleFormState['agentKind'] };model: string;/*** 显式选定的来源(供应商)id。'' = 跟随该 agent 原生默认来源(no-break,与未升级@@ -275,6 +278,8 @@ export interface RememberedBinding {effort: EffortValue | '';fastMode: boolean;agentKind: ScheduleFormState['agentKind'];+ modelAgentKind?: ScheduleFormState['modelAgentKind'];+ boundAgent?: ScheduleFormState['boundAgent'];}/** 从 form 提取绑定快照;无真实绑定返回 null。 */@@ -287,6 +292,8 @@ export function captureBinding(form: ScheduleFormState): RememberedBinding | nuleffort: form.effort,fastMode: form.fastMode,agentKind: form.agentKind,+ modelAgentKind: form.modelAgentKind,+ boundAgent: form.boundAgent,};}@@ -320,6 +327,8 @@ export function applyRunMode(effort: remembered.effort,fastMode: remembered.fastMode,agentKind: remembered.agentKind,+ modelAgentKind: remembered.modelAgentKind,+ boundAgent: remembered.boundAgent,}: f;@@ -497,6 +506,13 @@ export function parseScriptTimeoutMs(sec: string): number | undefined {return Number.isFinite(n) && n > 0 ? Math.floor(n * 1000) : undefined;}+/** Preserve a binding's baseline when saving; unbound tasks use the selected Harness. */+export function scheduleAgentKindForForm(form: ScheduleFormState): ScheduleFormState['agentKind'] {+ return form.executionMode !== 'script' && hasRealBinding(form) &&+ form.boundAgent?.sessionId === form.targetSessionId.trim()+ ? form.boundAgent.agentKind : form.agentKind;+}+export function buildScheduleInput(form: ScheduleFormState): CreateScheduleInput {const isHeartbeat = !!form.targetSessionId.trim();const isScript = (form.executionMode ?? 'agent') === 'script';@@ -514,7 +530,8 @@ export function buildScheduleInput(form: ScheduleFormState): CreateScheduleInput// 恒带 key:编辑 Cron 任务时 undefined 会沿 storage patch 契约清空旧 intervalMs;// 相对间隔任务则原样保留权威值,不能从可能陈旧的 cronExpr 重新推导。intervalMs: form.intervalMs,- agentKind: form.agentKind,+ agentKind: scheduleAgentKindForForm(form),+ modelAgentKind: !isScript && form.model.trim() ? form.modelAgentKind : undefined,workspaceKind: form.workspaceKind,useWorktree: !isScript && form.workspaceKind === 'project' && form.useWorktree,persistentSession: !isScript && form.persistentSession,@@ -540,6 +557,8 @@ export function buildScheduleInput(form: ScheduleFormState): CreateScheduleInputif (isHeartbeat) {base.useWorktree = false;+ // Keep the key when following so an update clears a previously saved Fast override.+ base.fastMode = form.modelAgentKind ? form.fastMode : undefined;base.model = form.model.trim() || undefined;base.providerId = form.providerId.trim() || undefined;base.effort = form.effort && isEffortValue(form.effort) ? form.effort : undefined;@@ -558,3 +577,32 @@ export function buildScheduleInput(form: ScheduleFormState): CreateScheduleInputif (form.agentKind === 'codex' || form.agentKind === 'pi') base.fastMode = form.fastMode;return base;}++/** Clone/demote drops the binding, so freeze the explicitly selected Harness for the new task. */+export function scheduleToUserCreateInput(+ schedule: Schedule,+ overrides: Partial<CreateScheduleInput> = {},+): CreateScheduleInput {+ return {+ name: schedule.name,+ prompt: schedule.prompt,+ kind: schedule.kind,+ cronExpr: schedule.cronExpr,+ timezone: schedule.timezone,+ recurring: schedule.recurring,+ manual: schedule.manual,+ intervalMs: schedule.intervalMs,+ agentKind: schedule.modelAgentKind ?? schedule.agentKind,+ modelAgentKind: schedule.modelAgentKind,+ model: schedule.model,+ providerId: schedule.providerId,+ fastMode: schedule.fastMode,+ effort: schedule.effort,+ workspaceKind: schedule.workspaceKind,+ workingDir: schedule.workingDir,+ useWorktree: schedule.useWorktree,+ persistentSession: schedule.persistentSession,+ notify: schedule.notify,+ ...overrides,+ };+}diff --git a/apps/desktop/src/renderer/hooks/useAvailableAgents.ts b/apps/desktop/src/renderer/hooks/useAvailableAgents.tsindex 8058a0fbdb..c7bff45932 100644--- a/apps/desktop/src/renderer/hooks/useAvailableAgents.ts+++ b/apps/desktop/src/renderer/hooks/useAvailableAgents.ts@@ -306,6 +306,15 @@ export function __resetAvailableAgentsCacheForTest(): void {agentsCacheInvalidationScheduled.clear();}+/** Model pickers keep the current Harness visible while excluding unregistered runtimes. */+export function useModelPickerAgents(current: RuntimeAgentKind, deviceId?: string | null): readonly RuntimeAgentKind[] | undefined {+ const { availableVendors, loaded } = useAvailableAgents(deviceId);+ if (!loaded) return undefined;+ return (['claude-code', 'codex', 'pi'] as const).filter(+ (agent) => agent === current || availableVendors.has(toVendor(agent)),+ );+}+/** Synchronous projection of the same runtime roster used by the client picker. */export function getCachedAvailableVendors(): ReadonlySet<MakerVendor> | null {return agentsCache.get('')?.vendors ?? null;diff --git a/apps/mobile/app/automations/[deviceId].tsx b/apps/mobile/app/automations/[deviceId].tsxindex cec718eeb3..fe22f9568e 100644--- a/apps/mobile/app/automations/[deviceId].tsx+++ b/apps/mobile/app/automations/[deviceId].tsx@@ -64,6 +64,7 @@ import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';import {applyMobileTemplateParams,applyScheduleWireCompat,+ ScheduleModelSelectionUnsupportedError,applyTemplateToMobileScheduleDraft,buildMobileScheduleInput,createMobileScheduleDraft,@@ -73,6 +74,7 @@ import {localizeScheduleDraftValidation,localizeTemplateParamValidation,MOBILE_SCHEDULE_PENDING_SESSION_ID,+ resolveMobileScheduleBinding,updateDraftAgentKind,updateDraftBoundSessionId,updateDraftCronExpr,@@ -432,7 +434,6 @@ export default function AutomationsScreen() {return;}}- const input = buildMobileScheduleInput(formDraft);const actionKey = formMode === 'edit' ? `edit:${formScheduleId}` : 'create';setBusyAction(actionKey);setError(null);@@ -445,22 +446,25 @@ export default function AutomationsScreen() {await openLink(deviceId);await subscribe(`automations:${deviceId}`, deviceId, ['sessions']);});- // intervalMs:null 的清空表达只有新 desktop 认识(旧引擎会当成已设间隔立即- // 触发),发送前按 host 能力位降级 wire 形态;探测失败按不支持处理- // (失败方向的取舍见 applyScheduleWireCompat 注释)。- const wireInput = await (async () => {- if (input.intervalMs !== null) return input;- const caps = await maker.getCapabilities(formDraft.agentKind).catch(() => null);- const supportsIntervalNullClear = !!(- caps as { supportsScheduleIntervalNullClear?: boolean } | null- )?.supportsScheduleIntervalNullClear;- return applyScheduleWireCompat(input, { supportsIntervalNullClear });- })();+ const resolvedDraft = await resolveMobileScheduleBinding(formDraft, async (id) =>+ await maker.getSession(id) as RemoteSession);+ const input = buildMobileScheduleInput(resolvedDraft);+ // Negotiate on every save, including numeric intervals and template creation.+ // Unknown/old hosts must not silently accept an unsupported bound selection.+ const caps = await maker.getCapabilities(resolvedDraft.agentKind).catch(() => null) as {+ supportsScheduleIntervalNullClear?: boolean;+ supportsScheduleModelSelection?: boolean;+ } | null;+ const supportsModelSelection = caps?.supportsScheduleModelSelection === true;+ const wireInput = applyScheduleWireCompat(input, {+ supportsIntervalNullClear: caps?.supportsScheduleIntervalNullClear === true,+ supportsModelSelection,+ });const saved = await (async () => {if (formMode === 'edit' && formScheduleId) {return withTransientRemoteRetry(() => maker.schedule.update(formScheduleId, wireInput));}- if (selectedTemplate && !templatePromptDirty) {+ if (selectedTemplate && !templatePromptDirty && supportsModelSelection) {return maker.schedule.createFromTemplate({templateId: selectedTemplate.id,paramValues: templateParamValues,@@ -480,7 +484,8 @@ export default function AutomationsScreen() {}await loadSchedules().catch(() => undefined);} catch (err) {- setFormError(formatRemoteError(err));+ setFormError(err instanceof ScheduleModelSelectionUnsupportedError+ ? t('deviceLink.remoteError.channelNotAllowed') : formatRemoteError(err));} finally {setBusyAction(null);}@@ -499,6 +504,7 @@ export default function AutomationsScreen() {syncRuns,templateParamValues,templatePromptDirty,+ t,]);const runScheduleAction = useCallback(async (@@ -1223,7 +1229,7 @@ function ScheduleFormCard({accessibilityState={{ checked: session.id === boundSessionInputValue.trim() }}disabled={busy}key={session.id}- onPress={() => onChange(updateDraftBoundSessionId(draft, session.id))}+ onPress={() => onChange(updateDraftBoundSessionId(draft, session.id, session.agentKind))}selected={session.id === boundSessionInputValue.trim()}style={styles.boundSessionOption}testID="automations.form.boundSessionOption"@@ -1248,7 +1254,8 @@ function ScheduleFormCard({<TextInputautoCapitalize="none"editable={!busy}- onChangeText={(value) => onChange(updateDraftBoundSessionId(draft, value))}+ onChangeText={(value) => onChange(updateDraftBoundSessionId(draft, value,+ sessions.find((session) => session.id === value.trim())?.agentKind))}placeholder="session id"placeholderTextColor={colors.textTertiary}style={styles.input}diff --git a/docs/product-rules/model-selector-unified.md b/docs/product-rules/model-selector-unified.mdindex 4c709e4b8d..542282723e 100644--- a/docs/product-rules/model-selector-unified.md+++ b/docs/product-rules/model-selector-unified.md@@ -178,7 +178,11 @@| M7 | i18n(zh/en+术语表)/token 登记/超长适配 | locales / globals.css / tailwind || M8 | 测试:新逻辑单测 + 更新受影响测试锁(逐条列明有意变更) | `__tests__/` |-设置类入口(scheduler/IM/Hook/Subagent/GhostErrand/CreateWorker)**不改交互结构**;其内嵌 ModelSelector 面板通过组件演进自然更新,回归验证纳入 M8。+设置类入口统一复用 ModelSelector 面板。自动化、IM 默认、Hook 工作目录、插件快问快答和 Worker 支持保存 Harness 的入口,必须通过 `onUnifiedSelect` 一次提交 Harness、来源、模型及该入口支持的配置,删除重复的 Harness 控件。只存模型或有意固定 Harness 的专用入口保留其契约限制;IM 默认和 Hook 工作目录不存 Fast,不展示 Fast 开关。++绑定已有任务的自动化在保存时只更新自动化配置,下次触发时才通过现有任务切换流程应用完整选择;目标正忙时顺延,不能抢占当前轮次。新增的 `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.mdindex a0e2aa3966..5b7250f510 100644--- a/docs/product-rules/telegram-bot-parity.md+++ b/docs/product-rules/telegram-bot-parity.md@@ -101,6 +101,7 @@ Cindy 有两个 Telegram bot,用户看到的是同一个产品:任务列表,随后消息路由到这个新任务;旧任务保留为历史,不得复用原任务 ID、只清 SDK上下文,也不得拖到下一条普通消息才落任务。新任务的 agent、模型、来源、思考强度和权限档均在执行 `/new` 时从各自入口的当前默认配置重新解析;当前项目目录作为 lane 偏好保留。+桌面 IM 默认配置与目录偏好统一使用标准模型选择器,一次保存 Harness、来源、模型和思考强度;不额外展示独立 Harness 控件,不展示无法保存的 Fast。两侧的配置归属与权限规则保持各自既有契约。两侧的成功提示、帮助与命令菜单都必须按这个真实结果称为「新任务」,不得沿用旧的「新对话/清掉上下文」说法。官方 bot 通过 `session-new-v1` 双向能力协商执行立即创建,滚动升级时旧 Desktop 才退回旧的diff --git a/packages/maker-scheduler/src/__tests__/scheduler.test.ts b/packages/maker-scheduler/src/__tests__/scheduler.test.tsindex e08d9dd7a8..348fa0652c 100644--- a/packages/maker-scheduler/src/__tests__/scheduler.test.ts+++ b/packages/maker-scheduler/src/__tests__/scheduler.test.ts@@ -163,6 +163,7 @@ function makeHarness(opts?: {validateTargetSession?: (targetSessionId: string,operation: 'create' | 'update' | 'fire',+ selection: Pick<Schedule, 'modelAgentKind'>,) => Promise<void>;/** 传入共享 storage / clock 模拟"两个 app 实例共用同一 DB"的双开场景。 */storage?: InMemoryStorage;@@ -214,6 +215,16 @@ describe('Scheduler', () => {h = makeHarness();});++ it('persists an explicit Harness with its model and clears it when following the target', async () => {+ const saved = await h.scheduler.create({ ...baseInput, modelAgentKind: 'pi', model: 'grok-4.6' });+ expect(saved.modelAgentKind).toBe('pi');+ await expect(h.scheduler.update(saved.id, { model: undefined })).rejects.toThrow(/Harness/);+ const followed = await h.scheduler.update(saved.id, { modelAgentKind: undefined, model: undefined });+ expect(followed?.modelAgentKind).toBeUndefined();+ await expect(h.scheduler.create({ ...baseInput, modelAgentKind: 'pi', model: '' })).rejects.toThrow(/Harness/);+ });+it('create() computes nextFireAt and adds to active map', async () => {const sch = await h.scheduler.create({ ...baseInput });// From 00:00:30, next minute boundary = 00:01:00@@ -265,6 +276,43 @@ describe('Scheduler', () => {expect(blankDir.workspaceKind).toBe('dialogue');});+ it('passes the complete candidate Harness to host validation before saving and firing', async () => {+ let allowedAgent = 'codex';+ const validateTargetSession = vi.fn(async (+ _target: string,+ _operation: 'create' | 'update' | 'fire',+ selection: Pick<Schedule, 'modelAgentKind'>,+ ) => {+ if (selection.modelAgentKind && selection.modelAgentKind !== allowedAgent) {+ throw new Error('target Harness is fixed');+ }+ });+ const local = makeHarness({ validateTargetSession });+ await expect(local.scheduler.create({ ...baseInput, targetSessionId: 'bound',+ modelAgentKind: 'pi', model: 'test-model' })).rejects.toThrow('Harness is fixed');+ expect(local.storage.schedules.size).toBe(0);+ const schedule = await local.scheduler.create({ ...baseInput, targetSessionId: 'bound',+ modelAgentKind: 'codex', model: 'test-model' });+ await expect(local.scheduler.update(schedule.id, { modelAgentKind: 'pi' }))+ .rejects.toThrow('Harness is fixed');+ expect((await local.storage.get(schedule.id))?.modelAgentKind).toBe('codex');+ await local.scheduler.update(schedule.id, { name: 'same route' });+ expect(validateTargetSession).toHaveBeenLastCalledWith('bound', 'update',+ expect.objectContaining({ modelAgentKind: 'codex' }));++ // A changed host capability must also be checked on automatic and manual runs.+ allowedAgent = 'pi';+ local.clock.setTo(Date.UTC(2026, 0, 1, 0, 1, 5));+ await local.scheduler.tick();+ expect(local.fireCalls).toHaveLength(0);+ expect(validateTargetSession).toHaveBeenLastCalledWith('bound', 'fire',+ expect.objectContaining({ modelAgentKind: 'codex' }));+ await local.scheduler.runNow(schedule.id);+ expect(local.fireCalls).toHaveLength(0);+ const follow = await local.scheduler.update(schedule.id, { modelAgentKind: undefined });+ expect(follow.modelAgentKind).toBeUndefined();+ });+it('rejects persisted Review targets at create, update, automatic fire, and runNow after restart', async () => {const sourceBySessionId = new Map<string, string>([['session-normal', 'desktop'],diff --git a/packages/maker-scheduler/src/engine/scheduler.ts b/packages/maker-scheduler/src/engine/scheduler.tsindex c7d74a2a86..501b77a239 100644--- a/packages/maker-scheduler/src/engine/scheduler.ts+++ b/packages/maker-scheduler/src/engine/scheduler.ts@@ -56,9 +56,14 @@ function normalizeScriptConfig(}function validateScheduleExecutionShape(- schedule: Pick<Schedule, 'executionMode' | 'scriptConfig' | 'workspaceKind' | 'workingDir' | 'useWorktree' | 'targetSessionId' | 'persistentSession' | 'prompt' | 'silentWhenIdle'>,+ schedule: Pick<Schedule, 'executionMode' | 'scriptConfig' | 'workspaceKind' | 'workingDir' | 'useWorktree' | 'targetSessionId' | 'persistentSession' | 'prompt' | 'silentWhenIdle' | 'modelAgentKind' | 'model'>,opts: { checkAgentPrompt: boolean } = { checkAgentPrompt: true },): void {+ if (schedule.modelAgentKind != null) {+ if (!['claude-code', 'codex', 'pi'].includes(schedule.modelAgentKind) || !schedule.model?.trim()) {+ throw new Error('Explicit scheduled model Harness requires a supported Harness and model');+ }+ }if ((schedule.executionMode ?? 'agent') !== 'script') {// 堵 update 逃逸:script 任务(prompt 合法为空)经 patch 只切 executionMode='agent'// 时,若不校验会落库空提示词的 agent 任务,触发即烧一轮空输入。checkAgentPrompt@@ -106,6 +111,7 @@ export interface SchedulerOptions {validateTargetSession?: (targetSessionId: string,operation: 'create' | 'update' | 'fire',+ selection: Pick<Schedule, 'modelAgentKind'>,) => Promise<void>;/*** 被动模式:本实例不参与自动触发 —— start() 不装 tick 时钟、不做僵尸 run 清理@@ -771,7 +777,7 @@ export class Scheduler extends EventEmitter {this.updateInflightAttempt(runId, 'running');try {if (schedule.targetSessionId) {- await this.validateTargetSession?.(schedule.targetSessionId, 'fire');+ await this.validateTargetSession?.(schedule.targetSessionId, 'fire', schedule);}const result = await this.runner.fire(schedule, {runId,@@ -1081,7 +1087,7 @@ export class Scheduler extends EventEmitter {this.updateInflightAttempt(runId, 'running');try {if (schedule.targetSessionId) {- await this.validateTargetSession?.(schedule.targetSessionId, 'fire');+ await this.validateTargetSession?.(schedule.targetSessionId, 'fire', schedule);}const result = await this.runner.fire(schedule, {runId,@@ -1323,7 +1329,7 @@ export class Scheduler extends EventEmitter {};validateScheduleExecutionShape(schedule);if (schedule.targetSessionId) {- await this.validateTargetSession?.(schedule.targetSessionId, 'create');+ await this.validateTargetSession?.(schedule.targetSessionId, 'create', schedule);}const inserted = await this.storage.insert(schedule);this.activeSchedules.set(id, inserted);@@ -1386,7 +1392,7 @@ export class Scheduler extends EventEmitter {},);if (candidate.targetSessionId) {- await this.validateTargetSession?.(candidate.targetSessionId, 'update');+ await this.validateTargetSession?.(candidate.targetSessionId, 'update', candidate);}// expired 是一次性任务已消费的终态。编辑后的配置若已经表达为“循环且非手动”,// 继续保留 expired 会让持久化状态与排期语义冲突:即使算出了 nextFireAt,任务也diff --git a/packages/maker-scheduler/src/types.ts b/packages/maker-scheduler/src/types.tsindex f296821363..e62f5de39a 100644--- a/packages/maker-scheduler/src/types.ts+++ b/packages/maker-scheduler/src/types.ts@@ -213,6 +213,8 @@ export interface Schedule {*/intervalMs?: number;agentKind: AgentKind;+ /** Explicit model-picker Harness. Absent on legacy schedules: bound tasks keep their live Harness. */+ modelAgentKind?: AgentKind;model?: string;/*** 显式选定的供应商(来源)id。undefined / 空 → 回落该 agent 原生默认来源@@ -345,6 +347,8 @@ export interface CreateScheduleInput {/** Interval 语义间隔(毫秒)。详见 Schedule.intervalMs。 */intervalMs?: number;agentKind: AgentKind;+ /** Explicit model-picker Harness. Absent on legacy schedules: bound tasks keep their live Harness. */+ modelAgentKind?: AgentKind;model?: string;/*** 显式选定的供应商(来源)id。undefined / 空 → 回落该 agent 原生默认来源diff --git a/packages/maker-shared/src/__tests__/scheduleForm.test.ts b/packages/maker-shared/src/__tests__/scheduleForm.test.tsindex e9f1c696e3..8f1d38f16b 100644--- a/packages/maker-shared/src/__tests__/scheduleForm.test.ts+++ b/packages/maker-shared/src/__tests__/scheduleForm.test.ts@@ -1,13 +1,15 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import {applyMobileTemplateParams,applyScheduleWireCompat,+ ScheduleModelSelectionUnsupportedError,applyTemplateToMobileScheduleDraft,buildMobileScheduleInput,createMobileScheduleDraft,createTemplateParamDefaults,deriveMobileScheduleSessionMode,MOBILE_SCHEDULE_PENDING_SESSION_ID,+ resolveMobileScheduleBinding,updateDraftAgentKind,updateDraftBoundSessionId,updateDraftCronExpr,@@ -458,3 +460,140 @@ describe('mobile schedule form model', () => {function hasOwn(value: object, key: string): boolean {return Object.prototype.hasOwnProperty.call(value, key);}+++describe('mobile explicit Harness round-trip', () => {+ it.each(['cc', 'codex', 'pi'] as const)('records the selected target Harness (%s) while preserving its model override', (targetAgentKind) => {+ const draft = createMobileScheduleDraft(schedule({ agentKind: 'codex', modelAgentKind: 'pi',+ model: 'pi-model', providerId: 'pi-source', effort: 'high', fastMode: true, targetSessionId: 'old' }));+ const selected = updateDraftBoundSessionId(draft, 'new', targetAgentKind);+ const expectedAgentKind = targetAgentKind === 'cc' ? 'claude-code' : targetAgentKind;+ expect(selected.boundAgent).toEqual({ sessionId: 'new', agentKind: expectedAgentKind });+ expect(buildMobileScheduleInput(selected)).toMatchObject({ agentKind: expectedAgentKind,+ modelAgentKind: 'pi', model: 'pi-model', providerId: 'pi-source', effort: 'high', fastMode: true });+ expect(buildMobileScheduleInput({ ...selected, model: '', persistentSession: true })).toMatchObject({+ agentKind: expectedAgentKind, targetSessionId: 'new', persistentSession: true,+ });+ expect(updateDraftBoundSessionId(selected, 'new', targetAgentKind)).toBe(selected);+ });++ it('resolves a manually entered target before serializing a persistent binding', async () => {+ const draft = createMobileScheduleDraft(schedule({ agentKind: 'pi', modelAgentKind: 'pi',+ model: 'pi-model', targetSessionId: 'old' }));+ const changed = updateDraftSessionMode(updateDraftBoundSessionId(draft, 'new'), 'persistent');+ expect(changed.boundAgent).toBeUndefined();+ const getSession = vi.fn(async (id: string) => ({ id, agentKind: 'codex' as const }));+ const resolved = await resolveMobileScheduleBinding(changed, getSession);+ expect(getSession).toHaveBeenCalledExactlyOnceWith('new');+ expect(buildMobileScheduleInput(resolved)).toMatchObject({ agentKind: 'codex', modelAgentKind: 'pi',+ targetSessionId: 'new', persistentSession: true });+ await expect(resolveMobileScheduleBinding(resolved, getSession)).resolves.toBe(resolved);+ await expect(resolveMobileScheduleBinding(updateDraftSessionMode(changed, 'fresh'), getSession))+ .resolves.toMatchObject({ targetSessionId: '' });+ expect(getSession).toHaveBeenCalledTimes(1);+ await expect(resolveMobileScheduleBinding(changed, async () => { throw new Error('offline'); }))+ .rejects.toThrow('offline');+ });++ it.each(['bound', MOBILE_SCHEDULE_PENDING_SESSION_ID])('creates a Harness override when a legacy binding (%s) is explicitly switched', (targetSessionId) => {+ const draft = createMobileScheduleDraft(schedule({ agentKind: 'claude-code', model: 'claude-sonnet-4-6',+ targetSessionId, providerId: 'old-source', effort: 'high', fastMode: true }));+ const selected = updateDraftAgentKind(draft, 'codex');+ expect(selected.modelAgentKind).toBe('codex');+ // Complete the pending picker before simulating the device-link JSON boundary.+ const input = JSON.parse(JSON.stringify(buildMobileScheduleInput({ ...selected, targetSessionId: 'bound' })));+ expect(input).toMatchObject({ targetSessionId: 'bound',+ agentKind: targetSessionId === 'bound' ? 'claude-code' : 'codex', modelAgentKind: 'codex',+ model: 'gpt-5.5', providerId: '', effort: '', fastMode: false });+ expect(draft.modelAgentKind).toBeUndefined();+ expect(updateDraftAgentKind(draft, 'claude-code')).toBe(draft);+ });++ it('retains the explicit Pi choice while the user fills its dynamic model', () => {+ const draft = createMobileScheduleDraft(schedule({ agentKind: 'codex', model: 'gpt-5.5', targetSessionId: 'bound' }));+ const selected = updateDraftAgentKind(draft, 'pi');+ expect(selected).toMatchObject({ modelAgentKind: 'pi', model: '' });+ const input = JSON.parse(JSON.stringify(buildMobileScheduleInput({ ...selected, model: 'pi-model', providerId: 'pi-source' })));+ expect(input).toMatchObject({ agentKind: 'codex', modelAgentKind: 'pi', model: 'pi-model', providerId: 'pi-source' });+ });++ it.each([false, true])('materializes a template model on a followed binding (worktree: %s)', (useWorktree) => {+ const draft = createMobileScheduleDraft(schedule({ agentKind: 'codex', model: '', targetSessionId: 'bound' }));+ const template: RemoteScheduleTemplate = { id: 'pi-template', name: 'Pi task', description: '', category: 'custom',+ source: 'user', agentKind: 'pi', model: 'pi-model', providerId: 'pi-source', effort: 'high', fastMode: true, useWorktree };+ const selected = applyTemplateToMobileScheduleDraft(draft, template);+ const input = JSON.parse(JSON.stringify(buildMobileScheduleInput(selected)));+ expect(input).toMatchObject({ agentKind: useWorktree ? 'pi' : 'codex', modelAgentKind: 'pi', model: 'pi-model',+ providerId: 'pi-source', effort: 'high', fastMode: true, useWorktree });+ if (useWorktree) expect(input).not.toHaveProperty('targetSessionId');+ else expect(input.targetSessionId).toBe('bound');+ expect(draft.modelAgentKind).toBeUndefined();+ });++ it('does not create a model override for an empty-model template or an untouched fresh Pi choice', () => {+ const draft = createMobileScheduleDraft(schedule({ agentKind: 'codex', model: '', targetSessionId: 'bound' }));+ const selected = applyTemplateToMobileScheduleDraft(draft, { id: 'follow', name: 'Follow', description: '', category: 'custom',+ source: 'user', agentKind: 'pi', model: '' });+ expect(buildMobileScheduleInput(selected)).not.toHaveProperty('modelAgentKind');+ expect(buildMobileScheduleInput(updateDraftAgentKind(createMobileScheduleDraft(), 'pi'))).not.toHaveProperty('modelAgentKind');+ });++ it('displays and preserves the Desktop override through a JSON update', () => {+ const draft = createMobileScheduleDraft(schedule({ agentKind: 'codex', modelAgentKind: 'pi',+ model: 'shared-model', providerId: 'selected', effort: 'high', fastMode: true, targetSessionId: 'bound' }));+ expect(draft.agentKind).toBe('pi');+ const input = JSON.parse(JSON.stringify(buildMobileScheduleInput({ ...draft, name: 'Renamed' })));+ expect(input).toMatchObject({ agentKind: 'codex', modelAgentKind: 'pi', model: 'shared-model',+ providerId: 'selected', effort: 'high', fastMode: true, targetSessionId: 'bound' });+ expect(input).not.toHaveProperty('boundAgent');+ const reopened = createMobileScheduleDraft(schedule(input));+ expect(buildMobileScheduleInput(reopened)).toMatchObject({ agentKind: 'codex', modelAgentKind: 'pi' });+ expect(buildMobileScheduleInput(updateDraftSessionMode(reopened, 'fresh'))).toMatchObject({+ agentKind: 'pi', modelAgentKind: 'pi', targetSessionId: undefined,+ });+ expect(buildMobileScheduleInput(updateDraftBoundSessionId(reopened, 'another-task'))).toMatchObject({+ agentKind: 'pi', targetSessionId: 'another-task',+ });+ });+ it('replaces a saved Pi marker and clears its provider when Mobile chooses Codex', () => {+ const draft = createMobileScheduleDraft(schedule({ agentKind: 'codex', modelAgentKind: 'pi',+ model: 'pi-model', providerId: 'pi-only', fastMode: true, targetSessionId: 'bound' }));+ const selected = updateDraftAgentKind(draft, 'codex');+ const input = JSON.parse(JSON.stringify(buildMobileScheduleInput(selected)));+ expect(input).toMatchObject({ agentKind: 'codex', modelAgentKind: 'codex', model: 'gpt-5.5',+ providerId: '', effort: '', fastMode: false });+ });+ it('keeps older schedules without an override in follow mode', () => {+ const draft = createMobileScheduleDraft(schedule({ targetSessionId: 'bound', model: '' }));+ expect(buildMobileScheduleInput(draft)).not.toHaveProperty('modelAgentKind');+ });+});+++describe('mixed-version scheduled model selections', () => {+ it.each([null, 600_000])('rejects an explicit bound selection on old/unknown hosts with interval %s', (intervalMs) => {+ const input = { ...buildMobileScheduleInput(createMobileScheduleDraft(schedule())),+ targetSessionId: 'bound', modelAgentKind: 'pi' as const, agentKind: 'pi' as const,+ model: 'pi-model', providerId: 'pi-source', fastMode: true, intervalMs };+ const saved = structuredClone(input);+ expect(() => applyScheduleWireCompat(input, { supportsIntervalNullClear: true }))+ .toThrow(ScheduleModelSelectionUnsupportedError);+ expect(applyScheduleWireCompat(input, { supportsIntervalNullClear: true, supportsModelSelection: true })).toBe(input);+ expect(input).toEqual(saved);+ });++ it('materializes fresh selections into legacy fields without losing model settings', () => {+ const input = { ...buildMobileScheduleInput(createMobileScheduleDraft(schedule())),+ targetSessionId: undefined, modelAgentKind: 'pi' as const, agentKind: 'codex' as const,+ model: 'pi-model', providerId: 'pi-source', effort: 'high', fastMode: true, intervalMs: null };+ const wire = JSON.parse(JSON.stringify(applyScheduleWireCompat(input, { supportsIntervalNullClear: false })));+ expect(wire).toMatchObject({ agentKind: 'pi', model: 'pi-model', providerId: 'pi-source', effort: 'high', fastMode: true });+ expect(wire).not.toHaveProperty('modelAgentKind');+ expect(wire).not.toHaveProperty('intervalMs');+ });++ it('keeps legacy follow bindings editable on an old host', () => {+ const input = { ...buildMobileScheduleInput(createMobileScheduleDraft(schedule())), targetSessionId: 'bound' };+ expect(applyScheduleWireCompat(input, { supportsIntervalNullClear: true })).toBe(input);+ });+});diff --git a/packages/maker-shared/src/scheduleForm.ts b/packages/maker-shared/src/scheduleForm.tsindex 0232b5ebff..112c891a34 100644--- a/packages/maker-shared/src/scheduleForm.ts+++ b/packages/maker-shared/src/scheduleForm.ts@@ -53,6 +53,9 @@ export interface MobileScheduleDraft {*/intervalMinutesTouched?: boolean;agentKind: RemoteScheduleAgentKind;+ modelAgentKind?: RemoteScheduleAgentKind;+ /** Form-only baseline; changing the selected model must not overwrite this binding. */+ boundAgent?: { sessionId: string; agentKind: RemoteScheduleAgentKind };model: string;providerId: string;effort: string;@@ -168,8 +171,11 @@ export function createMobileScheduleDraft(timezone: schedule.timezone?.trim() || DEFAULT_TIMEZONE,intervalMinutes: intervalMsToSupportedMinutes(schedule.intervalMs),...(typeof schedule.intervalMs === 'number' ? { sourceIntervalMs: schedule.intervalMs } : {}),- agentKind: schedule.agentKind ?? 'claude-code',- model: schedule.model ?? defaultModelFor(schedule.agentKind ?? 'claude-code'),+ agentKind: schedule.modelAgentKind ?? schedule.agentKind ?? 'claude-code',+ modelAgentKind: schedule.modelAgentKind,+ boundAgent: schedule.targetSessionId+ ? { sessionId: schedule.targetSessionId, agentKind: schedule.agentKind ?? 'claude-code' } : undefined,+ model: schedule.model ?? (schedule.targetSessionId ? '' : defaultModelFor(schedule.modelAgentKind ?? schedule.agentKind ?? 'claude-code')),providerId: schedule.providerId ?? '',effort: schedule.effort ?? '',fastMode: !!schedule.fastMode,@@ -201,6 +207,7 @@ export function applyTemplateToMobileScheduleDraft(paramValues: Record<string, string> = {},): MobileScheduleDraft {const agentKind = template.agentKind ?? draft.agentKind;+ const model = template.model ?? (draft.agentKind === agentKind ? draft.model : defaultModelFor(agentKind));return {...draft,name: template.name || draft.name,@@ -212,7 +219,9 @@ export function applyTemplateToMobileScheduleDraft(intervalMinutes: '',intervalMinutesTouched: true,agentKind,- model: template.model ?? (draft.agentKind === agentKind ? draft.model : defaultModelFor(agentKind)),+ // A template producing a model is an explicit choice, including a legacy bound draft.+ ...(model.trim() || draft.modelAgentKind ? { modelAgentKind: agentKind } : {}),+ model,// 模板若固定了 provider,必须随模板一起落到新建任务;否则 Pi 的空模型会在// host 侧按错误的默认来源解析。模板未指定时才保留同 agent 的用户选择。providerId: template.providerId ?? (draft.agentKind === agentKind ? draft.providerId : ''),@@ -391,7 +400,8 @@ export function buildMobileScheduleInput(draft: MobileScheduleDraft): RemoteSche&& typeof draft.sourceIntervalMs === 'number'? draft.sourceIntervalMs: null,- agentKind: draft.agentKind,+ agentKind: draft.executionMode !== 'script' && targetSessionId && draft.boundAgent?.sessionId === targetSessionId+ ? draft.boundAgent.agentKind : draft.agentKind,workspaceKind: draft.workspaceKind,useWorktree: draft.workspaceKind === 'project' && draft.useWorktree,persistentSession: draft.persistentSession,@@ -420,11 +430,21 @@ export function buildMobileScheduleInput(draft: MobileScheduleDraft): RemoteSche};}+ // An empty model follows the bound task. Omit the marker so the full-form+ // device-link normalization can clear an existing explicit selection.+ if (draft.modelAgentKind && draft.model.trim()) {+ input.modelAgentKind = draft.agentKind;+ input.model = draft.model.trim();+ input.providerId = draft.providerId.trim();+ input.effort = draft.effort.trim();+ input.fastMode = draft.fastMode;+ }+if (targetSessionId) {input.useWorktree = false;- input.model = draft.model.trim() || undefined;+ input.model = draft.modelAgentKind ? draft.model.trim() : draft.model.trim() || undefined;const effort = draft.effort.trim();- input.effort = isMobileScheduleEffort(effort) ? effort : undefined;+ input.effort = isMobileScheduleEffort(effort) ? effort : draft.modelAgentKind ? '' : undefined;return input;}@@ -444,8 +464,10 @@ export function buildMobileScheduleInput(draft: MobileScheduleDraft): RemoteSchereturn input;}+export class ScheduleModelSelectionUnsupportedError extends Error {}+/**- * 按被控端能力决定 intervalMs 清空的 wire 形态(device-link 两端版本会错位):+ * 按被控端能力决定 intervalMs 清空与显式模型选择的 wire 形态(device-link 两端版本会错位):** - 新 desktop(capabilities.supportsScheduleIntervalNullClear)认识 null,* IPC 入口把它归一化成引擎的「带 key 的 undefined」显式清空;@@ -458,10 +480,20 @@ export function buildMobileScheduleInput(draft: MobileScheduleDraft): RemoteSche*/export function applyScheduleWireCompat(input: RemoteScheduleWriteInput,- opts: { supportsIntervalNullClear: boolean },+ opts: { supportsIntervalNullClear: boolean; supportsModelSelection?: boolean },): RemoteScheduleWriteInput {- if (opts.supportsIntervalNullClear || input.intervalMs !== null) return input;- const { intervalMs: _legacyDropped, ...legacy } = input;+ let compatible = input;+ if (!opts.supportsModelSelection && input.modelAgentKind) {+ // Old hosts cannot apply an explicit bound selection. Do not report a successful+ // save when Harness/Fast would be ignored. Fresh creation can use its legacy fields.+ if (input.targetSessionId) {+ throw new ScheduleModelSelectionUnsupportedError('Scheduled model selection requires a newer desktop');+ }+ const { modelAgentKind, ...legacy } = input;+ compatible = { ...legacy, agentKind: modelAgentKind };+ }+ if (opts.supportsIntervalNullClear || compatible.intervalMs !== null) return compatible;+ const { intervalMs: _legacyDropped, ...legacy } = compatible;return legacy;}@@ -473,6 +505,8 @@ export function updateDraftAgentKind(return {...draft,agentKind,+ // Selecting another Harness must leave follow mode even on pre-upgrade bindings.+ ...(draft.modelAgentKind || draft.targetSessionId.trim() ? { modelAgentKind: agentKind } : {}),model: defaultModelFor(agentKind),providerId: '',effort: '',@@ -588,12 +622,21 @@ export function updateDraftSessionMode(export function updateDraftBoundSessionId(draft: MobileScheduleDraft,targetSessionId: string,+ targetAgentKind?: RemoteScheduleAgentKind | 'cc',): MobileScheduleDraft {const nextTargetSessionId = targetSessionId.trim() || MOBILE_SCHEDULE_PENDING_SESSION_ID;+ const boundAgent = targetAgentKind && nextTargetSessionId !== MOBILE_SCHEDULE_PENDING_SESSION_ID+ ? { sessionId: nextTargetSessionId, agentKind: targetAgentKind === 'cc' ? 'claude-code' as const : targetAgentKind }+ : draft.boundAgent?.sessionId === nextTargetSessionId ? draft.boundAgent : undefined;+ const agentKind = !draft.modelAgentKind && !draft.model.trim() && boundAgent+ ? boundAgent.agentKind : draft.agentKind;if (!draft.persistentSession &&draft.targetSessionId === nextTargetSessionId &&- !draft.useWorktree+ !draft.useWorktree &&+ draft.boundAgent?.sessionId === boundAgent?.sessionId &&+ draft.boundAgent?.agentKind === boundAgent?.agentKind &&+ draft.agentKind === agentKind) {return draft;}@@ -601,10 +644,27 @@ export function updateDraftBoundSessionId(...draft,persistentSession: false,targetSessionId: nextTargetSessionId,+ boundAgent,+ agentKind,useWorktree: false,};}+/** Resolve manually entered ids before saving; never infer a new target's Harness from its model override. */+export async function resolveMobileScheduleBinding(+ draft: MobileScheduleDraft,+ getSession: (id: string) => Promise<{ id: string; agentKind: RemoteScheduleAgentKind | 'cc' }>,+): Promise<MobileScheduleDraft> {+ if (draft.executionMode === 'script' || !hasMobileScheduleRealBinding(draft)) return draft;+ const targetSessionId = draft.targetSessionId.trim();+ if (draft.boundAgent?.sessionId === targetSessionId) return draft;+ const target = await getSession(targetSessionId);+ return {+ ...updateDraftBoundSessionId(draft, targetSessionId, target.agentKind),+ persistentSession: draft.persistentSession,+ };+}+function isMobileScheduleEffort(value: string): value is MobileScheduleEffort {return (MOBILE_SCHEDULE_EFFORT_VALUES as readonly string[]).includes(value);}diff --git a/packages/maker-shared/src/scheduleTypes.ts b/packages/maker-shared/src/scheduleTypes.tsindex 3d33a92739..90dd5a91f5 100644--- a/packages/maker-shared/src/scheduleTypes.ts+++ b/packages/maker-shared/src/scheduleTypes.ts@@ -30,6 +30,7 @@ export interface RemoteScheduleWriteInput {*/intervalMs?: number | null;agentKind: RemoteScheduleAgentKind;+ modelAgentKind?: RemoteScheduleAgentKind;model?: string;providerId?: string;effort?: string;@@ -100,6 +101,7 @@ export interface RemoteSchedule {manual?: boolean;intervalMs?: number;agentKind?: RemoteScheduleAgentKind;+ modelAgentKind?: RemoteScheduleAgentKind;model?: string;providerId?: string;effort?: string;