Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
merge: update empty project retention for latest main
Dashb1b7f871ff52
diff --cc apps/desktop/drizzle/0106_retain_all_recent_workdirs.sqlindex 0000000000,0000000000..e0ac49d1ecnew file mode 100644--- /dev/null+++ b/apps/desktop/drizzle/0106_retain_all_recent_workdirs.sql@@@ -1,0 -1,0 +1,1 @@@++SELECT 1;diff --cc apps/desktop/drizzle/meta/0106_snapshot.jsonindex 0000000000,0000000000..aeeaf18b3anew file mode 100644--- /dev/null+++ b/apps/desktop/drizzle/meta/0106_snapshot.json@@@ -1,0 -1,0 +1,5795 @@@++{++ "id": "0f13f9e7-9393-4f45-9e45-7747add59383",++ "prevId": "ff51d467-9cdb-483f-8397-6043b5e7aabd",++ "version": "6",++ "dialect": "sqlite",++ "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",++ "columnsFrom": [++ "session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ }++ },++ "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",++ "columnsFrom": [++ "requesting_bot_id"++ ],++ "tableTo": "bot_profiles",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ },++ "bot_delegations_target_bot_id_bot_profiles_id_fk": {++ "name": "bot_delegations_target_bot_id_bot_profiles_id_fk",++ "tableFrom": "bot_delegations",++ "columnsFrom": [++ "target_bot_id"++ ],++ "tableTo": "bot_profiles",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ },++ "bot_delegations_parent_session_id_sessions_id_fk": {++ "name": "bot_delegations_parent_session_id_sessions_id_fk",++ "tableFrom": "bot_delegations",++ "columnsFrom": [++ "parent_session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "set null"++ },++ "bot_delegations_child_session_id_sessions_id_fk": {++ "name": "bot_delegations_child_session_id_sessions_id_fk",++ "tableFrom": "bot_delegations",++ "columnsFrom": [++ "child_session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "set null"++ }++ },++ "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"++ ],++ "where": "\"bot_direct_message_threads\".\"status\" = 'active'",++ "isUnique": true++ },++ "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",++ "columnsFrom": [++ "bot_a_id"++ ],++ "tableTo": "bot_profiles",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ },++ "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",++ "columnsFrom": [++ "bot_b_id"++ ],++ "tableTo": "bot_profiles",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ }++ },++ "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",++ "columnsFrom": [++ "thread_id"++ ],++ "tableTo": "bot_direct_message_threads",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ },++ "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",++ "columnsFrom": [++ "sender_bot_id"++ ],++ "tableTo": "bot_profiles",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ },++ "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",++ "columnsFrom": [++ "recipient_bot_id"++ ],++ "tableTo": "bot_profiles",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ },++ "bot_direct_messages_sender_session_id_sessions_id_fk": {++ "name": "bot_direct_messages_sender_session_id_sessions_id_fk",++ "tableFrom": "bot_direct_messages",++ "columnsFrom": [++ "sender_session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "set null"++ },++ "bot_direct_messages_recipient_session_id_sessions_id_fk": {++ "name": "bot_direct_messages_recipient_session_id_sessions_id_fk",++ "tableFrom": "bot_direct_messages",++ "columnsFrom": [++ "recipient_session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "set null"++ }++ },++ "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",++ "columnsFrom": [++ "bot_id"++ ],++ "tableTo": "bot_profiles",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ },++ "bot_lifecycle_events_session_id_sessions_id_fk": {++ "name": "bot_lifecycle_events_session_id_sessions_id_fk",++ "tableFrom": "bot_lifecycle_events",++ "columnsFrom": [++ "session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "set null"++ }++ },++ "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",++ "columnsFrom": [++ "bot_id"++ ],++ "tableTo": "bot_profiles",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ }++ },++ "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",++ "columnsFrom": [++ "canonical_session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "set null"++ }++ },++ "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",++ "columnsFrom": [++ "bot_id"++ ],++ "tableTo": "bot_profiles",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ },++ "bot_runtime_snapshots_session_id_sessions_id_fk": {++ "name": "bot_runtime_snapshots_session_id_sessions_id_fk",++ "tableFrom": "bot_runtime_snapshots",++ "columnsFrom": [++ "session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ }++ },++ "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"++ ],++ "where": "\"bot_session_links\".\"role\" = 'canonical'",++ "isUnique": true++ },++ "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",++ "columnsFrom": [++ "bot_id"++ ],++ "tableTo": "bot_profiles",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ },++ "bot_session_links_session_id_sessions_id_fk": {++ "name": "bot_session_links_session_id_sessions_id_fk",++ "tableFrom": "bot_session_links",++ "columnsFrom": [++ "session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ }++ },++ "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",++ "columnsFrom": [++ "target_session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ }++ },++ "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",++ "columnsFrom": [++ "hash"++ ],++ "tableTo": "media_blobs",++ "columnsTo": [++ "hash"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ }++ },++ "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"++ ],++ "where": "\"messages\".\"role\" = 'error' AND \"messages\".\"rewind_at\" IS NULL",++ "isUnique": false++ }++ },++ "foreignKeys": {++ "messages_session_id_sessions_id_fk": {++ "name": "messages_session_id_sessions_id_fk",++ "tableFrom": "messages",++ "columnsFrom": [++ "session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ }++ },++ "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"++ ],++ "where": "\"orca_teams\".\"status\" = 'active'",++ "isUnique": true++ },++ "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",++ "columnsFrom": [++ "lead_session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ }++ },++ "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",++ "columnsFrom": [++ "team_id"++ ],++ "tableTo": "orca_teams",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ }++ },++ "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"++ ],++ "where": "\"orca_workers\".\"focused\" = true",++ "isUnique": 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",++ "columnsFrom": [++ "team_id"++ ],++ "tableTo": "orca_teams",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ },++ "orca_workers_session_id_sessions_id_fk": {++ "name": "orca_workers_session_id_sessions_id_fk",++ "tableFrom": "orca_workers",++ "columnsFrom": [++ "session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ }++ },++ "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"++ ],++ "where": "\"right_sidebar_tabs\".\"kind\" = 'subagents'",++ "isUnique": true++ },++ "right_sidebar_tabs_bot_artifacts_singleton_idx": {++ "name": "right_sidebar_tabs_bot_artifacts_singleton_idx",++ "columns": [++ "session_id"++ ],++ "where": "\"right_sidebar_tabs\".\"kind\" = 'bot-artifacts'",++ "isUnique": true++ }++ },++ "foreignKeys": {++ "right_sidebar_tabs_session_id_sessions_id_fk": {++ "name": "right_sidebar_tabs_session_id_sessions_id_fk",++ "tableFrom": "right_sidebar_tabs",++ "columnsFrom": [++ "session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ }++ },++ "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"++ ],++ "where": "\"schedule_runs\".\"status\" = 'running'",++ "isUnique": false++ },++ "idx_schedule_runs_running_heartbeat": {++ "name": "idx_schedule_runs_running_heartbeat",++ "columns": [++ "heartbeat_at"++ ],++ "where": "\"schedule_runs\".\"status\" = 'running' AND \"schedule_runs\".\"heartbeat_at\" IS NOT NULL",++ "isUnique": false++ },++ "idx_schedule_runs_running_legacy": {++ "name": "idx_schedule_runs_running_legacy",++ "columns": [++ "fired_at"++ ],++ "where": "\"schedule_runs\".\"status\" = 'running' AND \"schedule_runs\".\"heartbeat_at\" IS NULL",++ "isUnique": false++ },++ "idx_schedule_runs_unread_terminal": {++ "name": "idx_schedule_runs_unread_terminal",++ "columns": [++ "schedule_id",++ "status",++ "fired_at"++ ],++ "where": "\"schedule_runs\".\"read_at\" IS NULL AND \"schedule_runs\".\"status\" IN ('success', 'failed', 'aborted', 'interrupted')",++ "isUnique": false++ },++ "idx_schedule_runs_session_latest": {++ "name": "idx_schedule_runs_session_latest",++ "columns": [++ "session_id",++ "fired_at",++ "id"++ ],++ "where": "\"schedule_runs\".\"session_id\" IS NOT NULL",++ "isUnique": false++ }++ },++ "foreignKeys": {++ "schedule_runs_schedule_id_schedules_id_fk": {++ "name": "schedule_runs_schedule_id_schedules_id_fk",++ "tableFrom": "schedule_runs",++ "columnsFrom": [++ "schedule_id"++ ],++ "tableTo": "schedules",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ },++ "schedule_runs_session_id_sessions_id_fk": {++ "name": "schedule_runs_session_id_sessions_id_fk",++ "tableFrom": "schedule_runs",++ "columnsFrom": [++ "session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "set null"++ }++ },++ "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",++ "columnsFrom": [++ "session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ },++ "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",++ "columnsFrom": [++ "run_id"++ ],++ "tableTo": "schedule_runs",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ }++ },++ "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",++ "columnsFrom": [++ "target_session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "set null"++ },++ "schedules_skip_log_session_id_sessions_id_fk": {++ "name": "schedules_skip_log_session_id_sessions_id_fk",++ "tableFrom": "schedules",++ "columnsFrom": [++ "skip_log_session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "set null"++ }++ },++ "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",++ "columnsFrom": [++ "session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ }++ },++ "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",++ "columnsFrom": [++ "session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ }++ },++ "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++ },++ "context_window_runtime": {++ "name": "context_window_runtime",++ "type": "integer",++ "primaryKey": false,++ "notNull": false,++ "autoincrement": false++ },++ "fast_mode": {++ "name": "fast_mode",++ "type": "integer",++ "primaryKey": false,++ "notNull": true,++ "autoincrement": false,++ "default": false++ },++ "plan_mode_enabled": {++ "name": "plan_mode_enabled",++ "type": "integer",++ "primaryKey": false,++ "notNull": true,++ "autoincrement": false,++ "default": false++ },++ "cleared_at": {++ "name": "cleared_at",++ "type": "integer",++ "primaryKey": false,++ "notNull": false,++ "autoincrement": false++ },++ "pinned_at": {++ "name": "pinned_at",++ "type": "integer",++ "primaryKey": false,++ "notNull": false,++ "autoincrement": false++ },++ "summary": {++ "name": "summary",++ "type": "text",++ "primaryKey": false,++ "notNull": false,++ "autoincrement": false++ },++ "provider_id": {++ "name": "provider_id",++ "type": "text",++ "primaryKey": false,++ "notNull": false,++ "autoincrement": false++ },++ "user_send_at": {++ "name": "user_send_at",++ "type": "integer",++ "primaryKey": false,++ "notNull": false,++ "autoincrement": false++ },++ "agent_kind": {++ "name": "agent_kind",++ "type": "text",++ "primaryKey": false,++ "notNull": true,++ "autoincrement": false,++ "default": "'cc'"++ },++ "orca_role": {++ "name": "orca_role",++ "type": "text",++ "primaryKey": false,++ "notNull": false,++ "autoincrement": false++ },++ "parent_session_id": {++ "name": "parent_session_id",++ "type": "text",++ "primaryKey": false,++ "notNull": false,++ "autoincrement": false++ },++ "forked_at_message_id": {++ "name": "forked_at_message_id",++ "type": "text",++ "primaryKey": false,++ "notNull": false,++ "autoincrement": false++ },++ "worktree_path": {++ "name": "worktree_path",++ "type": "text",++ "primaryKey": false,++ "notNull": false,++ "autoincrement": false++ },++ "source": {++ "name": "source",++ "type": "text",++ "primaryKey": false,++ "notNull": true,++ "autoincrement": false,++ "default": "'desktop'"++ },++ "feishu_open_id": {++ "name": "feishu_open_id",++ "type": "text",++ "primaryKey": false,++ "notNull": false,++ "autoincrement": false++ },++ "feishu_bot_app_id": {++ "name": "feishu_bot_app_id",++ "type": "text",++ "primaryKey": false,++ "notNull": false,++ "autoincrement": false++ },++ "im_bot_context_id": {++ "name": "im_bot_context_id",++ "type": "text",++ "primaryKey": false,++ "notNull": false,++ "autoincrement": false++ },++ "im_user_id": {++ "name": "im_user_id",++ "type": "text",++ "primaryKey": false,++ "notNull": false,++ "autoincrement": false++ },++ "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",++ "columnsFrom": [++ "parent_session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "set null"++ }++ },++ "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",++ "columnsFrom": [++ "raw_file_path"++ ],++ "tableTo": "skill_usage_sources",++ "columnsTo": [++ "raw_file_path"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ }++ },++ "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",++ "columnsFrom": [++ "session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ },++ "subagent_run_aliases_run_id_subagent_runs_id_fk": {++ "name": "subagent_run_aliases_run_id_subagent_runs_id_fk",++ "tableFrom": "subagent_run_aliases",++ "columnsFrom": [++ "run_id"++ ],++ "tableTo": "subagent_runs",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ }++ },++ "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",++ "columnsFrom": [++ "session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ }++ },++ "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",++ "columnsFrom": [++ "binding_epoch"++ ],++ "tableTo": "wechat_sync_state",++ "columnsTo": [++ "binding_epoch"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ },++ "wechat_file_attachments_task_id_wechat_inbox_id_fk": {++ "name": "wechat_file_attachments_task_id_wechat_inbox_id_fk",++ "tableFrom": "wechat_file_attachments",++ "columnsFrom": [++ "task_id"++ ],++ "tableTo": "wechat_inbox",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ },++ "wechat_file_attachments_session_id_sessions_id_fk": {++ "name": "wechat_file_attachments_session_id_sessions_id_fk",++ "tableFrom": "wechat_file_attachments",++ "columnsFrom": [++ "session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "set null"++ }++ },++ "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"++ ],++ "where": "\"wechat_inbox\".\"session_id\" IS NOT NULL AND \"wechat_inbox\".\"status\" IN ('dispatching', 'accepted_running', 'waiting_desktop', 'delivery_pending')",++ "isUnique": true++ }++ },++ "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",++ "columnsFrom": [++ "binding_epoch"++ ],++ "tableTo": "wechat_sync_state",++ "columnsTo": [++ "binding_epoch"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ },++ "wechat_inbox_session_id_sessions_id_fk": {++ "name": "wechat_inbox_session_id_sessions_id_fk",++ "tableFrom": "wechat_inbox",++ "columnsFrom": [++ "session_id"++ ],++ "tableTo": "sessions",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "set null"++ }++ },++ "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",++ "columnsFrom": [++ "binding_epoch"++ ],++ "tableTo": "wechat_sync_state",++ "columnsTo": [++ "binding_epoch"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ },++ "wechat_outbox_task_id_wechat_inbox_id_fk": {++ "name": "wechat_outbox_task_id_wechat_inbox_id_fk",++ "tableFrom": "wechat_outbox",++ "columnsFrom": [++ "task_id"++ ],++ "tableTo": "wechat_inbox",++ "columnsTo": [++ "id"++ ],++ "onUpdate": "no action",++ "onDelete": "cascade"++ }++ },++ "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"++ ],++ "where": "\"wechat_sync_state\".\"is_active\" = 1",++ "isUnique": true++ }++ },++ "foreignKeys": {},++ "compositePrimaryKeys": {},++ "uniqueConstraints": {},++ "checkConstraints": {}++ }++ },++ "views": {},++ "enums": {},++ "_meta": {++ "columns": {},++ "schemas": {},++ "tables": {}++ },++ "internal": {++ "indexes": {++ "uniq_orca_worker_creation_reservations_team_label": {++ "columns": {++ "lower(\"label\")": {++ "isExpression": true++ }++ }++ },++ "uniq_orca_workers_team_label": {++ "columns": {++ "lower(\"label\")": {++ "isExpression": true++ }++ }++ }++ }++ }++}diff --cc apps/desktop/drizzle/meta/_journal.jsonindex 56ab6c4cd3,d337d3608c..5c4f387887--- a/apps/desktop/drizzle/meta/_journal.json+++ b/apps/desktop/drizzle/meta/_journal.json@@@ -635,9 -635,114 +635,121 @@@{"idx": 90,"version": "6",- "when": 1786527610111,- "tag": "0090_retain_all_recent_workdirs",+ "when": 1786726026223,+ "tag": "0090_distinguish_xai_provider_provenance",+ "breakpoints": true+ },+ {+ "idx": 91,+ "version": "6",+ "when": 1786794359638,+ "tag": "0091_amazing_blur",+ "breakpoints": true+ },+ {+ "idx": 92,+ "version": "6",+ "when": 1786696564943,+ "tag": "0092_fixed_zeigeist",+ "breakpoints": true+ },+ {+ "idx": 93,+ "version": "6",+ "when": 1787333855020,+ "tag": "0093_parched_switch",+ "breakpoints": true+ },+ {+ "idx": 94,+ "version": "6",+ "when": 1787387261372,+ "tag": "0094_repair_custom_provider_timestamps",+ "breakpoints": true+ },+ {+ "idx": 95,+ "version": "6",+ "when": 1787644558248,+ "tag": "0095_scope_messages_fts_update_trigger",+ "breakpoints": true+ },+ {+ "idx": 96,+ "version": "6",+ "when": 1787721235534,+ "tag": "0096_stabilize_messages_fts_rows",+ "breakpoints": true+ },+ {+ "idx": 97,+ "version": "6",+ "when": 1787739425748,+ "tag": "0097_fresh_stryfe",+ "breakpoints": true+ },+ {+ "idx": 98,+ "version": "6",+ "when": 1787833091152,+ "tag": "0098_bright_baron_zemo",+ "breakpoints": true+ },+ {+ "idx": 99,+ "version": "6",+ "when": 1787938177701,+ "tag": "0099_boring_champions",+ "breakpoints": true+ },+ {+ "idx": 100,+ "version": "6",+ "when": 1787992937440,+ "tag": "0100_segment_messages_fts_cjk",+ "breakpoints": true+ },+ {+ "idx": 101,+ "version": "6",+ "when": 1788431426308,+ "tag": "0101_repair_cjk_fts_missing_rows",+ "breakpoints": true+ },+ {+ "idx": 102,+ "version": "6",+ "when": 1788503589671,+ "tag": "0102_optimal_ender_wiggin",+ "breakpoints": true+ },+ {+ "idx": 103,+ "version": "6",+ "when": 1788596996011,+ "tag": "0103_bot_mode",+ "breakpoints": true+ },+ {+ "idx": 104,+ "version": "6",+ "when": 1788783797334,+ "tag": "0104_schedule-model-harness",+ "breakpoints": true+ },+ {+ "idx": 105,+ "version": "6",+ "when": 1789033649781,+ "tag": "0105_context_window_runtime",+ "breakpoints": true++ },++ {++ "idx": 106,++ "version": "6",++ "when": 1789194577226,++ "tag": "0106_retain_all_recent_workdirs",+ "breakpoints": true}]}diff --cc apps/desktop/drizzle/scripts/0106_retain_all_recent_workdirs.tsindex 5614abc622,0000000000..9e3b0caf99mode 100644,000000..100644--- a/apps/desktop/drizzle/scripts/0106_retain_all_recent_workdirs.ts+++ b/apps/desktop/drizzle/scripts/0106_retain_all_recent_workdirs.ts@@@ -1,88 -1,0 +1,86 @@@+import type Database from 'better-sqlite3';++function canonicalize(raw: string, platform: NodeJS.Platform): string | null {+ void platform;+ let path = raw.trim().replace(/\\/g, '/');+ while (path.length > 1 && path.endsWith('/')) {+ if (/^[A-Za-z]:\/$/.test(path)) break;+ path = path.slice(0, -1);+ }+ if (path.includes('/.cindy-worktrees/') || path.includes('/.xdt-worktrees/')) {+ return null;+ }+ return path || null;+}++function comparisonIdentity(path: string, platform: NodeJS.Platform): string {+ if (platform === 'win32' && (/^[A-Za-z]:\//.test(path) || path.startsWith('//'))) {+ return path.toLowerCase();+ }+ return path;+}++function runForPlatform(db: Database.Database, platform: NodeJS.Platform): void {+ const recentColumns = db.prepare('PRAGMA table_info(recent_workdirs)').all() as Array<{+ name: string;+ }>;+ if (recentColumns.length === 0) return;++ const merged = new Map<string, { path: string; timestamp: number }>();+ const merge = (rawPath: string, timestamp: number): void => {+ const path = canonicalize(rawPath, platform);+ if (!path) return;+ const identity = comparisonIdentity(path, platform);+ const previous = merged.get(identity);+ if (previous === undefined || timestamp > previous.timestamp) {+ merged.set(identity, { path, timestamp });+ }+ };+ const existingRows = db+ .prepare('SELECT path, last_used_at AS ts FROM recent_workdirs')+ .all() as Array<{ path: string; ts: number }>;+ for (const row of existingRows) merge(row.path, row.ts);++ const sessionColumns = new Set(+ (db.prepare('PRAGMA table_info(sessions)').all() as Array<{ name: string }>).map(+ (column) => column.name,+ ),+ );- // Missing/unknown provenance must not turn automation workdirs into durable user projects.- // `source` predates every supported runtime schema, but sparse replay fixtures may omit it.+ if (sessionColumns.has('working_dir') && sessionColumns.has('source')) {+ const timestampColumns = ['user_send_at', 'updated_at', 'created_at'].filter((column) =>+ sessionColumns.has(column),+ );+ const timestampExpression =+ timestampColumns.length > 0 ? `COALESCE(${timestampColumns.join(', ')}, 0)` : '0';+ const predicates = ['working_dir IS NOT NULL', "TRIM(working_dir) != ''"];+ predicates.push("source IN ('desktop', 'plugin')");+ if (sessionColumns.has('workspace_kind')) predicates.push("workspace_kind = 'project'");+ if (sessionColumns.has('remote_host_id')) predicates.push('remote_host_id IS NULL');++ const rows = db+ .prepare(+ `SELECT working_dir AS path,+ ${timestampExpression} AS ts+ FROM sessions+ WHERE ${predicates.join('\n AND ')}`,+ )+ .all() as Array<{ path: string; ts: number }>;+ for (const row of rows) {+ merge(row.path, typeof row.ts === 'number' && row.ts > 0 ? row.ts : 0);+ }+ }++ db.prepare('DELETE FROM recent_workdirs').run();+ const insert = db.prepare(+ `INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?)+ ON CONFLICT(path) DO UPDATE SET+ last_used_at = MAX(recent_workdirs.last_used_at, excluded.last_used_at)`,+ );+ for (const { path, timestamp } of merged.values()) insert.run(path, timestamp);+}++function run(db: Database.Database): void {+ runForPlatform(db, process.platform);+}++module.exports = { run, runForPlatform };diff --cc apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.tsindex 38f98b8370,c5a4c5a0a5..acb3d897ce--- a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts+++ b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts@@@ -27,12 -27,14 +27,16 @@@ const h = vi.hoisted(() => (isSessionStillRemovable: vi.fn(),cancelSessionOperations: vi.fn(),cleanupRemovedSession: vi.fn(),+ runtimeCleanup: vi.fn(),removeSessionRefs: vi.fn(),+ hasRegisteredWorktreeForSession: vi.fn(),recycleWorktreeForRemovedSession: vi.fn(),isOwnerScopeCurrent: vi.fn(),+ upsertRecentWorkdir: vi.fn(async () => true),+ captureOwnerScope: false,drizzle: {},+ readBindings: vi.fn(),+ requestRecycle: vi.fn(),userDataPath: '',agentIslandService: {handleSessionMetadataPatch: vi.fn(),@@@ -99,12 -101,16 +107,18 @@@ beforeEach(() =>h.cancelSessionOperations.mockResolvedValue(undefined);h.cleanupRemovedSession.mockResolvedValue(undefined);h.removeSessionRefs.mockResolvedValue(0);+ h.hasRegisteredWorktreeForSession.mockReturnValue(true);h.recycleWorktreeForRemovedSession.mockResolvedValue(undefined);h.isOwnerScopeCurrent.mockReturnValue(true);+ h.upsertRecentWorkdir.mockResolvedValue(true);+ h.captureOwnerScope = false;+ h.readBindings.mockReset().mockResolvedValue([]);+ h.requestRecycle.mockReset().mockResolvedValue(undefined);+ Object.assign(h.drizzle, { select: () => ({ from: () => ({ where: () => ({ limit: h.readBindings }) }) }) });setSessionRemovalCancelOperations(h.cancelSessionOperations);setSessionRemovalCleanup(h.cleanupRemovedSession);+ setSessionWorktreeRecycle(h.requestRecycle);+ setSessionRuntimeCleanup(h.runtimeCleanup);setSessionRouteLockImplementation(h.withSendToSessionLock);});@@@ -186,125 -263,6 +271,112 @@@ describe('setSessionsStatusInDb', () =expect(h.closeSession).not.toHaveBeenCalled();expect(h.recycleWorktreeForRemovedSession).not.toHaveBeenCalled();+ expect(h.upsertRecentWorkdir).not.toHaveBeenCalled();+ });++ it.each(['desktop', 'plugin'] as const)(+ 'touches retained local %s projects when batch archiving and broadcasts the refresh',+ async (source) => {+ h.tx.mockResolvedValueOnce([+ {+ sessionId: 's1',+ title: 'T1',+ workingDir: '/repo',+ workspaceKind: 'project',+ remoteHostId: null,+ source,+ status: 'archived',+ },+ ]);+ const now = vi.spyOn(Date, 'now').mockReturnValue(1_786_500_200_000);++ try {+ await setSessionsStatusInDb(['s1'], 'archived');+ } finally {+ now.mockRestore();+ }++ expect(h.upsertRecentWorkdir).toHaveBeenCalledWith(+ '/repo',+ 1_786_500_200_000,+ process.platform,+ expect.objectContaining({ tx: h.tx, drizzle: h.drizzle }),+ );+ expect(h.webContentsSend).toHaveBeenCalledWith('local-db:recent-workdirs:changed', {+ path: '/repo',+ });+ },+ );+- it('does not retain remote or dialogue workdirs during batch archive', async () => {++ it('does not retain remote, dialogue, or scheduler workdirs during batch archive', async () => {+ h.tx.mockResolvedValueOnce([+ {+ sessionId: 'remote',+ title: 'Remote',+ workingDir: '/remote/repo',+ workspaceKind: 'project',+ remoteHostId: 'host-a',+ source: 'desktop',+ status: 'archived',+ },+ {+ sessionId: 'dialogue',+ title: 'Dialogue',+ workingDir: '/managed/dialogue',+ workspaceKind: 'dialogue',+ remoteHostId: null,+ source: 'desktop',+ status: 'archived',+ },- ]);-- await setSessionsStatusInDb(['remote', 'dialogue'], 'archived');-- expect(h.upsertRecentWorkdir).not.toHaveBeenCalled();- expect(h.webContentsSend).not.toHaveBeenCalledWith(- 'local-db:recent-workdirs:changed',- expect.anything(),- );- });-- it('does not retain scheduler projects during batch archive', async () => {- h.tx.mockResolvedValueOnce([+ {+ sessionId: 'scheduled',+ title: 'Scheduled',+ workingDir: '/scheduled/repo',+ workspaceKind: 'project',+ remoteHostId: null,+ source: 'scheduler',+ status: 'archived',+ },+ ]);+- await setSessionsStatusInDb(['scheduled'], 'archived');++ await setSessionsStatusInDb(['remote', 'dialogue', 'scheduled'], 'archived');++ expect(h.upsertRecentWorkdir).not.toHaveBeenCalled();+ expect(h.webContentsSend).not.toHaveBeenCalledWith(+ 'local-db:recent-workdirs:changed',+ expect.anything(),+ );+ });++ it('touches the entry database but suppresses the batch refresh after an owner switch', async () => {+ h.captureOwnerScope = true;+ h.tx.mockImplementationOnce(async () => {+ h.isOwnerScopeCurrent.mockReturnValue(false);+ return [+ {+ sessionId: 's1',+ title: 'T1',+ workingDir: '/repo',+ workspaceKind: 'project',+ remoteHostId: null,+ source: 'desktop',+ status: 'archived',+ },+ ];+ });++ await setSessionsStatusInDb(['s1'], 'archived');++ expect(h.upsertRecentWorkdir).toHaveBeenCalledWith(+ '/repo',+ expect.any(Number),+ process.platform,+ expect.objectContaining({ tx: h.tx, drizzle: h.drizzle }),+ );+ expect(h.webContentsSend).not.toHaveBeenCalledWith(+ 'local-db:recent-workdirs:changed',+ expect.anything(),+ );});it('acquires overlapping batch route locks once in stable order', async () => {diff --cc apps/desktop/src/main/localDb/__tests__/retainAllRecentWorkdirsMigration.test.tsindex 57e8c1b6bd,0000000000..1fa36044a9mode 100644,000000..100644--- a/apps/desktop/src/main/localDb/__tests__/retainAllRecentWorkdirsMigration.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/retainAllRecentWorkdirsMigration.test.ts@@@ -1,227 -1,0 +1,223 @@@+import Database from 'better-sqlite3';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+- const migration = require('../../../../drizzle/scripts/0090_retain_all_recent_workdirs.ts') as {++const migration = require('../../../../drizzle/scripts/0106_retain_all_recent_workdirs.ts') as {+ run: (db: Database.Database) => void;+ runForPlatform: (db: Database.Database, platform: NodeJS.Platform) => void;+};++let db: Database.Database;++beforeEach(() => {+ db = new Database(':memory:');+ db.exec(`+ CREATE TABLE sessions (+ id TEXT PRIMARY KEY NOT NULL,+ source TEXT,+ workspace_kind TEXT NOT NULL,+ remote_host_id TEXT,+ working_dir TEXT,+ status TEXT NOT NULL,+ user_send_at INTEGER,+ updated_at INTEGER NOT NULL,+ created_at INTEGER NOT NULL+ );+ CREATE TABLE recent_workdirs (+ path TEXT PRIMARY KEY NOT NULL,+ last_used_at INTEGER NOT NULL+ );+ `);+});++afterEach(() => db.close());++function seedSession(input: {+ id: string;+ path: string;+ timestamp: number;+ source?: string;+ status?: string;+ remoteHostId?: string | null;+}): void {+ db.prepare(+ `INSERT INTO sessions (+ id, source, workspace_kind, remote_host_id, working_dir, status,+ user_send_at, updated_at, created_at+ ) VALUES (?, ?, 'project', ?, ?, ?, ?, ?, ?)`,+ ).run(+ input.id,+ input.source ?? 'desktop',+ input.remoteHostId ?? null,+ input.path,+ input.status ?? 'active',+ input.timestamp,+ input.timestamp,+ input.timestamp,+ );+}++function recentRows(): Array<{ path: string; last_used_at: number }> {+ return db.prepare('SELECT path, last_used_at FROM recent_workdirs ORDER BY path').all() as Array<{+ path: string;+ last_used_at: number;+ }>;+}+- describe('0090 retain all recent workdirs migration', () => {++describe('0106 retain all recent workdirs migration', () => {+ it('backfills every local project without a ten-project cap, including deleted sessions', () => {+ for (let index = 0; index < 14; index += 1) {+ seedSession({+ id: `session-${index}`,+ path: `/workspace/project-${index}`,+ timestamp: 1_000 + index,+ status: index === 0 ? 'deleted' : 'active',+ });+ }++ migration.run(db);++ expect(recentRows()).toHaveLength(14);+ expect(recentRows()).toContainEqual({ path: '/workspace/project-0', last_used_at: 1_000 });+ });++ it('backfills historical local plugin projects without admitting scheduler workdirs', () => {+ seedSession({+ id: 'plugin-archived',+ path: '/workspace/plugin-project',+ timestamp: 2_000,+ source: 'plugin',+ status: 'archived',+ });+ seedSession({+ id: 'scheduler-archived',+ path: '/workspace/scheduler-project',+ timestamp: 3_000,+ source: 'scheduler',+ status: 'archived',+ });+ seedSession({+ id: 'unknown-archived',+ path: '/workspace/unknown-project',+ timestamp: 4_000,+ source: 'future-source',+ status: 'archived',+ });++ migration.run(db);+- expect(recentRows()).toEqual([- { path: '/workspace/plugin-project', last_used_at: 2_000 },- ]);++ expect(recentRows()).toEqual([{ path: '/workspace/plugin-project', last_used_at: 2_000 }]);+ });++ it('normalizes duplicate path spellings and keeps the newest activity time', () => {+ seedSession({ id: 'old', path: 'D:\\work\\project-a\\', timestamp: 1_000 });+ seedSession({ id: 'new', path: 'D:/work/project-a', timestamp: 2_000 });++ migration.run(db);++ expect(recentRows()).toEqual([{ path: 'D:/work/project-a', last_used_at: 2_000 }]);+ });++ it('preserves a newer existing timestamp and is idempotent', () => {+ seedSession({ id: 'session-a', path: '/workspace/project-a', timestamp: 1_000 });+ db.prepare('INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?)').run(+ '/workspace/project-a',+ 3_000,+ );++ migration.run(db);+ migration.run(db);++ expect(recentRows()).toEqual([{ path: '/workspace/project-a', last_used_at: 3_000 }]);+ });++ it('excludes remote projects and Cindy-managed worktrees', () => {+ seedSession({+ id: 'remote',+ path: '/workspace/remote',+ timestamp: 1_000,+ remoteHostId: 'host-a',+ });+ seedSession({+ id: 'managed',+ path: '/workspace/project/.cindy-worktrees/task-a',+ timestamp: 2_000,+ });+ seedSession({ id: 'local', path: '/workspace/local', timestamp: 3_000 });++ migration.run(db);++ expect(recentRows()).toEqual([{ path: '/workspace/local', last_used_at: 3_000 }]);+ });++ it('fails closed against a sparse legacy sessions table without source provenance', () => {+ db.exec(`+ DROP TABLE sessions;+ CREATE TABLE sessions (+ id TEXT PRIMARY KEY NOT NULL,+ working_dir TEXT,+ created_at INTEGER+ );+ INSERT INTO sessions (id, working_dir, created_at)+ VALUES ('legacy', '/workspace/legacy', 4000);+ INSERT INTO recent_workdirs (path, last_used_at)+ VALUES ('/workspace/already-retained', 3000);+ `);++ migration.run(db);+- expect(recentRows()).toEqual([- { path: '/workspace/already-retained', last_used_at: 3_000 },- ]);++ expect(recentRows()).toEqual([{ path: '/workspace/already-retained', last_used_at: 3_000 }]);+ });++ it('deduplicates legacy Windows drive and UNC casing identities', () => {+ db.prepare('INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?)').run(+ 'D:/Work/Project-A',+ 3_000,+ );+ db.prepare('INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?)').run(+ 'd:/work/project-a',+ 2_000,+ );+ db.prepare('INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?)').run(+ '//Server/Share/Project-B',+ 4_000,+ );+ db.prepare('INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?)').run(+ '//server/share/project-b',+ 5_000,+ );+ db.prepare('INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?)').run(+ 'D:/ÉCOLE/Plugin-Project',+ 5_500,+ );+ seedSession({+ id: 'plugin-windows',+ path: 'd:/école/plugin-project',+ timestamp: 6_000,+ source: 'plugin',+ status: 'archived',+ });++ migration.runForPlatform(db, 'win32');++ expect(recentRows()).toEqual([+ { path: '//server/share/project-b', last_used_at: 5_000 },+ { path: 'D:/Work/Project-A', last_used_at: 3_000 },+ { path: 'd:/école/plugin-project', last_used_at: 6_000 },+ ]);+ });++ it('keeps POSIX path casing distinct', () => {+ db.prepare('INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?)').run(+ '/Workspace/Project-A',+ 1_000,+ );+ db.prepare('INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?)').run(+ '/workspace/project-a',+ 2_000,+ );++ migration.runForPlatform(db, 'linux');++ expect(recentRows()).toHaveLength(2);+ });+});diff --cc apps/desktop/src/main/localDb/client/WorkerThreadTransport.tsindex 95741b8c68,3fd19d1bdb..af2b86a60d--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts@@@ -311,14 -448,20 +448,26 @@@ function dispatchTx(readyDb, payload)return sessionsRenameTitles(readyDb, request.args);case 'sessions.setStatus':return sessionsSetStatus(readyDb, request.args);+ case 'recentWorkdirs.mergeWindowsIdentity':+ return recentWorkdirsMergeWindowsIdentity(readyDb, request.args);+ case 'recentWorkdirs.removeWindowsIdentity':+ return recentWorkdirsRemoveWindowsIdentity(readyDb, request.args);+ case 'projectAliases.replaceIdentity':+ return projectAliasesReplaceIdentity(readyDb, request.args);+ case 'toolResults.compactSession':+ return compactSessionToolResults(readyDb, request.args);case 'session.agentSwitchFallback':return sessionAgentSwitchFallback(readyDb, request.args);+ case 'context.rebuild':+ return contextRebuild(readyDb, request.args);+ case 'message.insert':+ return messageInsert(readyDb, request.args);+ case 'message.updateContent':+ return messageUpdateContent(readyDb, request.args);+ case 'message.leaseMutate':+ return messageLeaseMutate(readyDb, request.args);+ case 'message.rewindUserAfterClear':+ return messageRewindUserAfterClear(readyDb, request.args);case 'message.delete':return messageDelete(readyDb, request.args);case 'im.deleteBindings':@@@ -332,72 -477,80 +483,145 @@@}}- // ⚠️ 与 worker/opHandlers/tx.ts 的 recentWorkdirsMergeWindowsIdentity 保持一致。+function recentWorkdirsMergeWindowsIdentity(readyDb, args) {+ const payload = asRecord(args, 'recentWorkdirs.mergeWindowsIdentity args');+ const path = expectString(payload.path, 'path');+ const lastUsedAt = expectNumber(payload.lastUsedAt, 'lastUsedAt');+ return readyDb.transaction(() => {+ const matches = recentWorkdirWindowsIdentityRows(readyDb, path);+ const representative = matches+ .slice()+ .sort((a, b) => b.lastUsedAt - a.lastUsedAt || a.rowid - b.rowid)[0];+ const representativePath = representative?.path ?? path;+ const newestTimestamp = Math.max(lastUsedAt, ...matches.map((row) => row.lastUsedAt));- readyDb.prepare(- 'INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?) ON CONFLICT(path) DO UPDATE SET last_used_at = MAX(recent_workdirs.last_used_at, excluded.last_used_at)',- ).run(representativePath, newestTimestamp);++ readyDb++ .prepare(++ 'INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?) ON CONFLICT(path) DO UPDATE SET last_used_at = MAX(recent_workdirs.last_used_at, excluded.last_used_at)',++ )++ .run(representativePath, newestTimestamp);+ const removeVariant = readyDb.prepare('DELETE FROM recent_workdirs WHERE path = ?');+ for (const row of matches) {+ if (row.path !== representativePath) removeVariant.run(row.path);+ }+ })();+}+- // ⚠️ 与 worker/opHandlers/tx.ts 的 recentWorkdirsRemoveWindowsIdentity 保持一致。+function recentWorkdirsRemoveWindowsIdentity(readyDb, args) {+ const payload = asRecord(args, 'recentWorkdirs.removeWindowsIdentity args');+ const path = expectString(payload.path, 'path');+ return readyDb.transaction(() => {+ const matches = recentWorkdirWindowsIdentityRows(readyDb, path);+ const removeVariant = readyDb.prepare('DELETE FROM recent_workdirs WHERE path = ?');+ let changes = 0;+ for (const row of matches) changes += removeVariant.run(row.path).changes;+ return { changes };+ })();+}++function recentWorkdirWindowsIdentityRows(readyDb, path) {+ const identity = path.toLowerCase();+ return readyDb+ .prepare('SELECT rowid, path, last_used_at AS lastUsedAt FROM recent_workdirs')+ .all()+ .filter((row) => row.path.toLowerCase() === identity);+}+- // ⚠️ 与 worker/opHandlers/tx.ts 的 projectAliasesReplaceIdentity 保持一致。+function projectAliasesReplaceIdentity(readyDb, args) {+ const payload = asRecord(args, 'projectAliases.replaceIdentity args');+ const projectKey = expectString(payload.projectKey, 'projectKey');+ const comparisonKey = expectString(payload.comparisonKey, 'comparisonKey');+ if (typeof payload.foldCase !== 'boolean') throw invalidArgs('foldCase must be a boolean');+ const alias = nullableString(payload.alias);+ const updatedAt = expectNumber(payload.updatedAt, 'updatedAt');+ return readyDb.transaction(() => {+ const rows = readyDb.prepare('SELECT project_key AS projectKey FROM project_aliases').all();+ const removeAlias = readyDb.prepare('DELETE FROM project_aliases WHERE project_key = ?');+ for (const row of rows) {+ const identity = payload.foldCase ? row.projectKey.toLowerCase() : row.projectKey;+ if (identity === comparisonKey) removeAlias.run(row.projectKey);+ }+ if (alias == null) return null;+ readyDb+ .prepare('INSERT INTO project_aliases (project_key, alias, updated_at) VALUES (?, ?, ?)')+ .run(projectKey, alias, updatedAt);+ return { projectKey, alias, updatedAt };+ })();+}++ // Keep in sync with worker/opHandlers/tx.ts:skillUsageApplyMutation.+ function skillUsageApplyMutation(readyDb, args) {+ const payload = asRecord(args, 'skillUsage.applyMutation args');+ const kind = expectString(payload.kind, 'kind');+ if (kind === 'persist') {+ const rawSource = asRecord(payload.source, 'source');+ const source = {+ rawFilePath: expectString(rawSource.rawFilePath, 'source.rawFilePath'),+ analyzerVersion: expectString(rawSource.analyzerVersion, 'source.analyzerVersion'),+ agentKind: expectString(rawSource.agentKind, 'source.agentKind'),+ sessionId: expectString(rawSource.sessionId, 'source.sessionId'),+ sdkSessionId: expectString(rawSource.sdkSessionId, 'source.sdkSessionId'),+ mtimeMs: expectNumber(rawSource.mtimeMs, 'source.mtimeMs'),+ sizeBytes: expectNumber(rawSource.sizeBytes, 'source.sizeBytes'),+ scannedAt: expectNumber(rawSource.scannedAt, 'source.scannedAt'),+ };+ const exposures = expectArray(payload.exposures, 'exposures');+ const upsertSource = readyDb.prepare(+ "INSERT INTO skill_usage_sources (raw_file_path, analyzer_version, agent_kind, session_id, sdk_session_id, mtime_ms, size_bytes, last_scanned_at, status, error) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'ok', NULL) ON CONFLICT(raw_file_path) DO UPDATE SET analyzer_version = excluded.analyzer_version, agent_kind = excluded.agent_kind, session_id = excluded.session_id, sdk_session_id = excluded.sdk_session_id, mtime_ms = excluded.mtime_ms, size_bytes = excluded.size_bytes, last_scanned_at = excluded.last_scanned_at, status = 'ok', error = NULL",+ );+ const deleteExposure = readyDb.prepare(+ 'DELETE FROM skill_usage_exposures WHERE raw_file_path = ? AND analyzer_version = ?',+ );+ const insertExposure = readyDb.prepare(+ 'INSERT INTO skill_usage_exposures (id, analyzer_version, raw_file_path, raw_line_no, session_id, sdk_session_id, agent_kind, skill_name, skill_path, skill_document_hash, exposure_content_hash, document_hash_source, source, tool_use_id, seen_at, tool_call_count, repeated_tool_call_count, tool_error_count, command_call_count, command_failure_count) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',+ );+ return readyDb.transaction(() => {+ upsertSource.run(source.rawFilePath, source.analyzerVersion, source.agentKind, source.sessionId, source.sdkSessionId, source.mtimeMs, source.sizeBytes, source.scannedAt);+ deleteExposure.run(source.rawFilePath, source.analyzerVersion);+ for (let index = 0; index < exposures.length; index += 1) {+ const row = asRecord(exposures[index], 'exposures.' + index);+ insertExposure.run(+ source.analyzerVersion + ':' + expectString(row.id, 'exposures.' + index + '.id'),+ source.analyzerVersion,+ expectString(row.rawFilePath, 'exposures.' + index + '.rawFilePath'),+ expectNumber(row.rawLineNo, 'exposures.' + index + '.rawLineNo'),+ expectString(row.sessionId, 'exposures.' + index + '.sessionId'),+ expectString(row.sdkSessionId, 'exposures.' + index + '.sdkSessionId'),+ expectString(row.agentKind, 'exposures.' + index + '.agentKind'),+ expectString(row.skillName, 'exposures.' + index + '.skillName'),+ nullableString(row.skillPath),+ nullableString(row.skillDocumentHash),+ expectString(row.exposureContentHash, 'exposures.' + index + '.exposureContentHash'),+ expectString(row.documentHashSource, 'exposures.' + index + '.documentHashSource'),+ expectString(row.source, 'exposures.' + index + '.source'),+ nullableString(row.toolUseId),+ expectNumber(row.seenAt, 'exposures.' + index + '.seenAt'),+ expectNumber(row.toolCallCount, 'exposures.' + index + '.toolCallCount'),+ expectNumber(row.repeatedToolCallCount, 'exposures.' + index + '.repeatedToolCallCount'),+ expectNumber(row.toolErrorCount, 'exposures.' + index + '.toolErrorCount'),+ expectNumber(row.commandCallCount, 'exposures.' + index + '.commandCallCount'),+ expectNumber(row.commandFailureCount, 'exposures.' + index + '.commandFailureCount'),+ );+ }+ })();+ }+ if (kind === 'deleteBefore') {+ const analyzerVersion = expectString(payload.analyzerVersion, 'analyzerVersion');+ const recentSince = expectNumber(payload.recentSince, 'recentSince');+ return readyDb.transaction(() => {+ readyDb.prepare('DELETE FROM skill_usage_exposures WHERE analyzer_version = ? AND seen_at < ?').run(analyzerVersion, recentSince);+ readyDb.prepare('DELETE FROM skill_usage_sources WHERE analyzer_version = ? AND mtime_ms < ? AND raw_file_path NOT IN (SELECT raw_file_path FROM skill_usage_exposures)').run(analyzerVersion, recentSince);+ })();+ }+ if (kind === 'promote') {+ const analyzerVersion = expectString(payload.analyzerVersion, 'analyzerVersion');+ return readyDb.transaction(() => {+ readyDb.prepare("INSERT INTO migration_meta (key, value) VALUES ('skill_usage_analyzer_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(analyzerVersion);+ readyDb.prepare('DELETE FROM skill_usage_exposures WHERE analyzer_version <> ?').run(analyzerVersion);+ })();+ }+ throw invalidArgs('unknown skill usage mutation: ' + kind);+ }+// ⚠️ 与 worker/opHandlers/tx.ts 的 imDeleteBindings 保持一致。function imDeleteBindings(readyDb, args) {const payload = asRecord(args, 'im.deleteBindings args');@@@ -692,10 -1003,10 +1074,10 @@@ function sessionsSetStatus(readyDb, argthrow Object.assign(new Error('invalid status: ' + status), { code: 'INVALID_ARGS' });}const selectSession = readyDb.prepare(- 'SELECT id, title, working_dir AS workingDir, workspace_kind AS workspaceKind, status FROM sessions WHERE id = ? LIMIT 1',+ 'SELECT id, title, working_dir AS workingDir, workspace_kind AS workspaceKind, status, source FROM sessions WHERE id = ? LIMIT 1',);const updateSession = readyDb.prepare(- 'UPDATE sessions SET status = ?, updated_at = ? WHERE id = ? RETURNING id, title, working_dir AS workingDir, workspace_kind AS workspaceKind',+ 'UPDATE sessions SET status = ?, updated_at = ? WHERE id = ? RETURNING id, title, working_dir AS workingDir, workspace_kind AS workspaceKind, remote_host_id AS remoteHostId, source',);return readyDb.transaction(() => {const applied = [];@@@ -1942,8 -2417,8 +2490,7 @@@ const SLEEP_DETECTION_SLACK_MS = 5_000/** RPC 超时评估结果:reject = 真超时;rearm = 定时器横跨系统睡眠,应重置预算续等。 */export type RpcTimeoutVerdict =-- | { kind: 'reject'; wallElapsedMs: number }-- | { kind: 'rearm'; wallElapsedMs: number };++ { kind: 'reject'; wallElapsedMs: number } | { kind: 'rearm'; wallElapsedMs: number };/*** 判定一次 RPC 超时是真超时还是「跨睡眠假超时」。@@@ -2012,10 -2487,10 +2559,7 @@@ export class WorkerThreadTransport implsend<R = unknown>(op: string, args?: unknown, transferList?: unknown[]): Promise<R> {if (this.closed || this.closing) {return Promise.reject(-- createDbTransportError(-- DB_TRANSPORT_NOT_SENT,-- 'db worker transport is closed',-- ),++ createDbTransportError(DB_TRANSPORT_NOT_SENT, 'db worker transport is closed'),);}const id = this.nextId++;@@@ -2051,9 -2526,9 +2595,7 @@@on(event: 'vec-status', cb: (payload: VecStatusEvent) => void): void;on(event: EventName,-- cb:-- | ((payload: LogEvent) => void)-- | ((payload: VecStatusEvent) => void),++ cb: ((payload: LogEvent) => void) | ((payload: VecStatusEvent) => void),): void {const listeners = this.eventListeners.get(event) ?? new Set<(payload: unknown) => void>();listeners.add(cb as (payload: unknown) => void);@@@ -2078,10 -2553,10 +2620,7 @@@} finally {this.closed = true;this.rejectAllPending(-- createDbTransportError(-- DB_TRANSPORT_OUTCOME_UNKNOWN,-- 'db worker transport closed',-- ),++ createDbTransportError(DB_TRANSPORT_OUTCOME_UNKNOWN, 'db worker transport closed'),createDbTransportError(DB_TRANSPORT_NOT_SENT, 'db worker transport closed'),);await this.worker.terminate();@@@ -2112,11 -2587,11 +2651,7 @@@const onTimeout = (): void => {const index = this.queued.indexOf(item);if (index < 0) return;-- const verdict = evaluateRpcTimeout(-- item.budgetStartedAtMs,-- Date.now(),-- this.rpcTimeoutMs,-- );++ const verdict = evaluateRpcTimeout(item.budgetStartedAtMs, Date.now(), this.rpcTimeoutMs);if (verdict.kind === 'rearm') {item.budgetStartedAtMs = Date.now();item.queueTimeout = setTimeout(onTimeout, this.rpcTimeoutMs);@@@ -2140,11 -2615,11 +2675,7 @@@const onTimeout = (): void => {const pending = this.pending.get(id);if (!pending) return;-- const verdict = evaluateRpcTimeout(-- pending.sentAtMs,-- Date.now(),-- this.rpcTimeoutMs,-- );++ const verdict = evaluateRpcTimeout(pending.sentAtMs, Date.now(), this.rpcTimeoutMs);if (verdict.kind === 'rearm') {// 跨睡眠假超时:重置预算续等,请求在唤醒后照常完成或在真超时时拒绝。this.emitClientLog('warn', {@@@ -2168,10 -2643,10 +2699,7 @@@this.drainQueue();};const budgetElapsedMs = Date.now() - item.budgetStartedAtMs;-- const remainingBudgetMs = Math.max(-- 1,-- this.rpcTimeoutMs - budgetElapsedMs,-- );++ const remainingBudgetMs = Math.max(1, this.rpcTimeoutMs - budgetElapsedMs);const timeout = setTimeout(onTimeout, remainingBudgetMs);this.pending.set(id, {resolve: item.resolve,@@@ -2184,13 -2659,13 +2712,7 @@@} catch (err) {clearTimeout(timeout);this.pending.delete(id);-- item.reject(-- createDbTransportError(-- DB_TRANSPORT_NOT_SENT,-- toError(err).message,-- err,-- ),-- );++ item.reject(createDbTransportError(DB_TRANSPORT_NOT_SENT, toError(err).message, err));this.drainQueue();}}diff --cc apps/desktop/src/main/localDb/client/__tests__/tx.test.tsindex 3c6bc52f3b,470c67f921..77eb0340ba--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts@@@ -17,15 -20,40 +20,49 @@@ CREATE TABLE migration_historycontent_hash TEXT NOT NULL,applied_at INTEGER NOT NULL);+ CREATE TABLE skill_usage_sources (+ raw_file_path TEXT PRIMARY KEY,+ analyzer_version TEXT NOT NULL,+ agent_kind TEXT NOT NULL,+ session_id TEXT NOT NULL,+ sdk_session_id TEXT NOT NULL,+ mtime_ms INTEGER NOT NULL,+ size_bytes INTEGER NOT NULL,+ last_scanned_at INTEGER NOT NULL,+ status TEXT NOT NULL,+ error TEXT+ );+ CREATE TABLE skill_usage_exposures (+ id TEXT PRIMARY KEY,+ analyzer_version TEXT NOT NULL,+ raw_file_path TEXT NOT NULL,+ raw_line_no INTEGER NOT NULL,+ session_id TEXT NOT NULL,+ sdk_session_id TEXT NOT NULL,+ agent_kind TEXT NOT NULL,+ skill_name TEXT NOT NULL,+ skill_path TEXT,+ skill_document_hash TEXT,+ exposure_content_hash TEXT NOT NULL,+ document_hash_source TEXT NOT NULL,+ source TEXT NOT NULL,+ tool_use_id TEXT,+ seen_at INTEGER NOT NULL,+ tool_call_count INTEGER NOT NULL,+ repeated_tool_call_count INTEGER NOT NULL,+ tool_error_count INTEGER NOT NULL,+ command_call_count INTEGER NOT NULL,+ command_failure_count INTEGER NOT NULL+ );+CREATE TABLE recent_workdirs (+ path TEXT PRIMARY KEY NOT NULL,+ last_used_at INTEGER NOT NULL+);+CREATE TABLE project_aliases (+ project_key TEXT PRIMARY KEY NOT NULL,+ alias TEXT NOT NULL,+ updated_at INTEGER NOT NULL+);CREATE TABLE sessions (id TEXT PRIMARY KEY,title TEXT NOT NULL DEFAULT 'New Maker',@@@ -873,164 -1495,6 +1504,106 @@@ describe('db worker tx handlers', () =}, { useInlineWorker });});- it.each([false, true])(- 'recentWorkdirs.mergeWindowsIdentity rolls back canonical insert when cleanup fails (inline=%s)',- async (useInlineWorker) => {- await withClient(async (client) => {- await client.exec(- 'INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?), (?, ?)',- ['D:/Work/Project-A', 3_000, 'd:/work/project-a', 2_000],- );- await client.exec(`- CREATE TRIGGER fail_recent_workdir_cleanup- BEFORE DELETE ON recent_workdirs- BEGIN- SELECT RAISE(ABORT, 'forced cleanup failure');- END- `);-- await expect(- client.tx('recentWorkdirs.mergeWindowsIdentity', {- path: 'd:/work/project-a',- lastUsedAt: 4_000,- }),- ).rejects.toThrow(/forced cleanup failure/);-- await expect(- client.query<{ path: string; lastUsedAt: number }>(- 'SELECT path, last_used_at AS lastUsedAt FROM recent_workdirs ORDER BY path',- ),- ).resolves.toEqual([- { path: 'D:/Work/Project-A', lastUsedAt: 3_000 },- { path: 'd:/work/project-a', lastUsedAt: 2_000 },- ]);- }, { useInlineWorker });- },- );-- it.each([false, true])(- 'recentWorkdirs.mergeWindowsIdentity keeps the existing display path while refreshing activity (inline=%s)',- async (useInlineWorker) => {- await withClient(async (client) => {- await client.exec('INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?)', [- 'D:/Work/Project-A',- 3_000,- ]);-- await client.tx('recentWorkdirs.mergeWindowsIdentity', {- path: 'd:/work/project-a',- lastUsedAt: 4_000,- });-- await expect(- client.query<{ path: string; lastUsedAt: number }>(- 'SELECT path, last_used_at AS lastUsedAt FROM recent_workdirs',- ),- ).resolves.toEqual([{ path: 'D:/Work/Project-A', lastUsedAt: 4_000 }]);- }, { useInlineWorker });- },- );-+ it.each([false, true])(+ 'recentWorkdirs.mergeWindowsIdentity folds non-ASCII Windows casing (inline=%s)',+ async (useInlineWorker) => {+ await withClient(+ async (client) => {+ await client.exec('INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?)', [+ 'D:/École/Project-A',+ 3_000,+ ]);++ await client.tx('recentWorkdirs.mergeWindowsIdentity', {+ path: 'd:/école/project-a',+ lastUsedAt: 4_000,+ });++ await expect(+ client.query<{ path: string; lastUsedAt: number }>(+ 'SELECT path, last_used_at AS lastUsedAt FROM recent_workdirs',+ ),+ ).resolves.toEqual([{ path: 'D:/École/Project-A', lastUsedAt: 4_000 }]);+ },+ { useInlineWorker },+ );+ },+ );++ it.each([false, true])(- 'recentWorkdirs.removeWindowsIdentity deletes every non-ASCII casing variant (inline=%s)',++ 'recentWorkdirs.removeWindowsIdentity deletes every casing variant (inline=%s)',+ async (useInlineWorker) => {+ await withClient(+ async (client) => {+ await client.exec(+ 'INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?), (?, ?)',+ ['D:/École/Project-A', 3_000, 'd:/école/project-a', 4_000],+ );++ await expect(+ client.tx('recentWorkdirs.removeWindowsIdentity', {+ path: 'D:/ÉCOLE/PROJECT-A',+ }),+ ).resolves.toEqual({ changes: 2 });+ await expect(client.query('SELECT path FROM recent_workdirs')).resolves.toEqual([]);+ },+ { useInlineWorker },+ );+ },+ );++ it.each([false, true])(- 'projectAliases.replaceIdentity replaces and clears every Unicode casing variant atomically (inline=%s)',++ 'projectAliases.replaceIdentity replaces and clears casing variants atomically (inline=%s)',+ async (useInlineWorker) => {+ await withClient(+ async (client) => {+ await client.exec(+ 'INSERT INTO project_aliases (project_key, alias, updated_at) VALUES (?, ?, ?), (?, ?, ?)',+ [+ 'local:D:/École/Project-A',+ 'Newest alias',+ 2_000,+ 'local:d:/école/project-a',+ 'Older alias',+ 1_000,+ ],+ );++ await expect(+ client.tx('projectAliases.replaceIdentity', {+ projectKey: 'local:D:/ÉCOLE/PROJECT-A',+ comparisonKey: 'local:d:/école/project-a',+ foldCase: true,+ alias: 'Replacement',+ updatedAt: 3_000,+ }),+ ).resolves.toEqual({+ projectKey: 'local:D:/ÉCOLE/PROJECT-A',+ alias: 'Replacement',+ updatedAt: 3_000,+ });+ await expect(+ client.query('SELECT project_key AS projectKey, alias FROM project_aliases'),+ ).resolves.toEqual([{ projectKey: 'local:D:/ÉCOLE/PROJECT-A', alias: 'Replacement' }]);++ await expect(+ client.tx('projectAliases.replaceIdentity', {+ projectKey: 'local:d:/école/project-a',+ comparisonKey: 'local:d:/école/project-a',+ foldCase: true,+ alias: null,+ updatedAt: 4_000,+ }),+ ).resolves.toBeNull();+ await expect(client.query('SELECT project_key FROM project_aliases')).resolves.toEqual(+ [],+ );+ },+ { useInlineWorker },+ );+ },+ );+it('sessions.renameTitles applies title changes atomically with preconditions', async () => {await withClient(async (client) => {await seedSession(client, 's1', {@@@ -1084,6 -1548,32 +1657,68 @@@});});++ it.each([false, true])(++ 'sessions.setStatus returns project retention identity (inline=%s)',++ async (useInlineWorker) => {++ await withClient(++ async (client) => {++ await seedSession(client, 'local', { workingDir: '/local/repo' });++ await seedSession(client, 'remote', { workingDir: '/remote/repo' });++ await client.exec('UPDATE sessions SET remote_host_id = ?, source = ? WHERE id = ?', [++ 'host-a',++ 'plugin',++ 'remote',++ ]);++++ await expect(++ client.tx('sessions.setStatus', {++ sessionIds: ['local', 'remote'],++ status: 'archived',++ }),++ ).resolves.toEqual([++ expect.objectContaining({++ sessionId: 'local',++ remoteHostId: null,++ source: 'desktop',++ }),++ expect.objectContaining({++ sessionId: 'remote',++ remoteHostId: 'host-a',++ source: 'plugin',++ }),++ ]);++ },++ { useInlineWorker },++ );++ },++ );+++ it.each([false, true])(+ 'sessions.setStatus rejects Bot tasks atomically (inline=%s)',+ async (useInlineWorker) => {+ await withClient(+ async (client) => {+ await seedSession(client, 'regular');+ await seedSession(client, 'bot', { source: 'bot' });++ await expect(+ client.tx('sessions.setStatus', {+ sessionIds: ['regular', 'bot'],+ status: 'archived',+ }),+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ await expect(+ client.query('SELECT id, status FROM sessions ORDER BY id'),+ ).resolves.toEqual([+ { id: 'bot', status: 'active' },+ { id: 'regular', status: 'active' },+ ]);+ },+ { useInlineWorker },+ );+ },+ );+it('rewind.commit follows transcript parent links and preserves the prior assistant when timestamps are inverted', async () => {await withClient(async (client) => {await seedSession(client, 's1');diff --cc apps/desktop/src/main/localDb/client/tx/types.tsindex 020083074d,a5bc598d2e..65302bdb80--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@@ -19,10 -19,13 +19,16 @@@ export type DbTxName| 'orca.reconcileInactiveTeamWorkersForLead'| 'sessions.renameTitles'| 'sessions.setStatus'+ | 'recentWorkdirs.mergeWindowsIdentity'+ | 'recentWorkdirs.removeWindowsIdentity'+ | 'projectAliases.replaceIdentity'+ | 'toolResults.compactSession'| 'session.agentSwitchFallback'+ | 'context.rebuild'+ | 'message.insert'+ | 'message.updateContent'+ | 'message.leaseMutate'+ | 'message.rewindUserAfterClear'| 'message.delete'| 'im.deleteBindings'| 'im.replaceBinding'@@@ -349,6 -440,16 +445,33 @@@ export interface SessionsSetStatusResulstatus: 'active' | 'archived';}++export interface RecentWorkdirsMergeWindowsIdentityArgs {++ path: string;++ lastUsedAt: number;++}++++export interface RecentWorkdirsRemoveWindowsIdentityArgs {++ path: string;++}++++export interface ProjectAliasesReplaceIdentityArgs {++ projectKey: string;++ comparisonKey: string;++ foldCase: boolean;++ alias: string | null;++ updatedAt: number;++}+++ export interface CompactSessionToolResultsArgs {+ sessionId: string;+ now: number;+ }++ export interface CompactSessionToolResultsResult {+ compactedRows: number;+ originalBytes: number;+ }+/** session.importShare 的单条 session 行(lead 与协同 Worker 共用形状)。 */export interface SessionImportShareSessionRow {id: string;@@@ -462,6 -563,221 +585,246 @@@ export interface ImDeleteBindingsArgs}>;}+ export interface BotsCreateProfileArgs {+ id: string;+ displayName: string;+ description: string;+ avatar: string;+ avatarColor: string;+ identitySource: string;+ capabilitiesJson: string;+ eventSubscription?: {+ id: string;+ name: string;+ status: 'active' | 'paused';+ ruleJson: string;+ };+ now: number;+ }++ export interface BotsUpdateProfileArgs {+ id: string;+ displayName?: string;+ description?: string;+ avatar?: string;+ avatarColor?: string;+ status?: string;+ hiddenAt?: number | null;+ pinnedAt?: number | null;+ identitySource: string;+ capabilitiesJson: string;+ profileContentChanged: boolean;+ expectedCurrentVersion: number;+ /** Avatar-only edits do not advance the profile version; migrations also compare the address. */+ expectedAvatar?: string;+ /** Storage-only compatibility changes must not reorder the teammate list. */+ preserveUpdatedAt?: boolean;+ /** Inserted and made authoritative in the same tx as the avatar address. */+ botAvatarRef?: { id: string; hash: string; createdAt: number };+ clearBotAvatarRefs?: boolean;+ now: number;+ }++ export interface BotsUpdateAttentionArgs {+ botId: string;+ /** Null means a successful observation is clearing prior attention. */+ reason: string | null;+ observedAt: number;+ }++ export interface BotsReplaceCanonicalSessionArgs {+ botId: string;+ expectedCanonicalSessionId: string | null;+ /** One-time compatibility evidence already validated by reconcileCanonicalLink. */+ compatibilityMissingCanonicalSessionId?: string | null;+ expectedProfileVersion: number;+ session: {+ id: string;+ title: string;+ workingDir: string | null;+ workspaceKind: string;+ model: string;+ effort: string;+ permissionMode: string;+ agentKind: string;+ remoteHostId: string | null;+ providerId: string | null;+ parentSessionId?: string | null;+ extraDirs: string;+ fastMode?: boolean;+ source: string;+ createdAt: number;+ updatedAt: number;+ };+ now: number;+ }++ export interface BotsReconcileCanonicalLinkArgs {+ botId: string;+ now: number;+ }++ export interface BotsReconcileCanonicalLinkResult {- status: 'unchanged' | 'repaired-mirror' | 'migrated' | 'missing-pointer' | 'missing-session' | 'conflict';++ status:++ | 'unchanged'++ | 'repaired-mirror'++ | 'migrated'++ | 'missing-pointer'++ | 'missing-session'++ | 'conflict';+ canonicalSessionId: string | null;+ }++ export interface BotsReplaceCanonicalSessionResult {+ created: boolean;+ canonicalSessionId: string | null;+ archivedCanonicalSessionId: string | null;+ }++ export interface BotsPrepareRuntimeArgs {+ snapshot: {- id: string; botId: string; sessionId: string; profileVersion: number; agentKind: string;- workingDir: string; memoryScopeKey: string | null; configuredJson: string; resolvedJson: string;++ id: string;++ botId: string;++ sessionId: string;++ profileVersion: number;++ agentKind: string;++ workingDir: string;++ memoryScopeKey: string | null;++ configuredJson: string;++ resolvedJson: string;+ preparedAt: number;+ };+ eventId: string;+ eventPayloadJson: string;+ }++ export interface BotsFinishRuntimeArgs {+ snapshotId: string;+ botId: string;+ sessionId: string;+ status: 'applied' | 'degraded' | 'failed';+ finishedAt: number;+ failureJson: string | null;+ eventId: string;+ eventType: 'runtime-applied' | 'runtime-failed';+ eventPayloadJson: string;+ }+ export interface BotsFinishDelegationArgs {+ delegationId: string;+ status: 'completed' | 'failed' | 'cancelled' | 'timed-out';+ resultSummary: string | null;+ outputArtifactsJson: string;+ lastError: string | null;+ tokensUsed?: number;+ completedAt: number;+ }++ export interface BotsFinishDelegationResult {+ id: string;+ parentSessionId: string | null;+ childSessionId: string | null;+ status: 'queued' | 'running' | 'waiting' | 'completed' | 'failed' | 'cancelled' | 'timed-out';+ }++ export interface BotsReparentDelegationsArgs {+ botId: string;+ previousParentSessionId: string;+ nextParentSessionId: string;+ now: number;+ }++ export interface BotsReparentDelegationsResult {+ delegationIds: string[];+ }++ export interface BotsCreateDelegationArgs {+ maxActiveChildren: number;+ delegation: {- id: string; requestingBotId: string; targetBotId: string | null; parentSessionId: string;- childSessionId: string; objective: string; contextRefsJson: string;- permissionSnapshotJson: string; lineageJson: string; targetProfileVersion: number | null;- depth: number; createdAt: number;++ id: string;++ requestingBotId: string;++ targetBotId: string | null;++ parentSessionId: string;++ childSessionId: string;++ objective: string;++ contextRefsJson: string;++ permissionSnapshotJson: string;++ lineageJson: string;++ targetProfileVersion: number | null;++ depth: number;++ createdAt: number;+ };+ session: BotsReplaceCanonicalSessionArgs['session'];+ }++ export interface BotsReopenDelegationArgs {+ worktreePath?: string | null;+ maxActiveChildren: number;+ delegationId: string;+ requestingBotId: string;+ expectedStatus: 'completed' | 'failed' | 'cancelled' | 'timed-out';+ parentSessionId: string;+ childSessionId: string;+ objective: string;+ permissionSnapshotJson: string;+ targetBotId: string | null;+ targetProfileVersion: number | null;+ session: BotsReplaceCanonicalSessionArgs['session'];+ reopenedAt: number;+ }++ export interface BotsReopenDelegationResult {+ reopened: boolean;+ previousParentSessionId: string | null;+ }++ export interface BotsLifecycleTransitionArgs {- botId: string; canonicalSessionId: string | null; expectedProfileStatus: string;- at: number; eventId: string;++ botId: string;++ canonicalSessionId: string | null;++ expectedProfileStatus: string;++ at: number;++ eventId: string;+ }+ export interface BotsArchiveLifecycleArgs extends BotsLifecycleTransitionArgs {- expectedProfileStatus: string; worktreeDisposition: string;++ expectedProfileStatus: string;++ worktreeDisposition: string;+ }+ export interface BotsDeleteProfileArgs {+ botId: string;+ sessionIds: string[];+ keepTaskHistory: boolean;+ at: number;+ }+ export interface ImRotateSessionArgs {+ previousSessionId: string | null;+ detachBinding: {+ channel: string;+ botContextId: string;+ userId: string;+ scopeKey: string;+ targetSessionId: string;+ } | null;+ session: {+ id: string;+ title: string;+ workingDir: string;+ workspaceKind: 'project' | 'dialogue';+ model: string;+ effort: string;+ permissionMode: string;+ fastMode: boolean;+ agentKind: string;+ source: string;+ providerId: string | null;+ imBotContextId: string;+ imUserId: string;+ };+ now: number;+ }++ export interface ImRotateSessionResult {+ previousStatus: 'active' | 'archived' | 'deleted' | null;+ }+export type WechatInboxStatus =| 'pending'| 'dispatching'@@@ -781,10 -1116,13 +1163,16 @@@ export type DbTxArgsByName ='orca.reconcileInactiveTeamWorkersForLead': OrcaReconcileInactiveTeamWorkersForLeadArgs;'sessions.renameTitles': SessionsRenameTitlesArgs;'sessions.setStatus': SessionsSetStatusArgs;+ 'recentWorkdirs.mergeWindowsIdentity': RecentWorkdirsMergeWindowsIdentityArgs;+ 'recentWorkdirs.removeWindowsIdentity': RecentWorkdirsRemoveWindowsIdentityArgs;+ 'projectAliases.replaceIdentity': ProjectAliasesReplaceIdentityArgs;+ 'toolResults.compactSession': CompactSessionToolResultsArgs;'session.agentSwitchFallback': SessionAgentSwitchFallbackArgs;+ 'context.rebuild': ContextRebuildArgs;+ 'message.insert': MessageInsertArgs;+ 'message.updateContent': MessageUpdateContentArgs;+ 'message.leaseMutate': MessageLeaseMutateArgs;+ 'message.rewindUserAfterClear': MessageRewindUserAfterClearArgs;'message.delete': MessageDeleteArgs;'im.deleteBindings': ImDeleteBindingsArgs;'im.replaceBinding': ImReplaceBindingArgs;@@@ -829,14 -1185,13 +1235,20 @@@ export type DbTxResultByName ='orca.reconcileInactiveTeamWorkersForLead': string[];'sessions.renameTitles': SessionsRenameTitleResult[];'sessions.setStatus': SessionsSetStatusResultItem[];+ 'recentWorkdirs.mergeWindowsIdentity': undefined;+ 'recentWorkdirs.removeWindowsIdentity': { changes: number };+ 'projectAliases.replaceIdentity': {+ projectKey: string;+ alias: string;+ updatedAt: number;+ } | null;+ 'toolResults.compactSession': CompactSessionToolResultsResult;'session.agentSwitchFallback': undefined;+ 'context.rebuild': undefined;+ 'message.insert': { changes: number };+ 'message.updateContent': { changes: number };+ 'message.leaseMutate': { changes: number };+ 'message.rewindUserAfterClear': { changes: number };'message.delete': MessageDeleteResult;'im.deleteBindings': undefined;'im.replaceBinding': undefined;diff --cc apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.tsindex 99179c044e,38f1cdf2a6..23e64abd91--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts@@@ -26,25 -30,26 +31,36 @@@ const h = vi.hoisted(() => (relocate: vi.fn(async (): Promise<{ persistedSdkSessionId: string | null }> => ({persistedSdkSessionId: null,})),+ closeSession: vi.fn(async (_sessionId: string) => undefined),tapWindowBroadcast: vi.fn(),- webContentsSend: vi.fn(),+ windows: [] as Array<{+ isDestroyed: ReturnType<typeof vi.fn>;+ webContents: { send: ReturnType<typeof vi.fn> };+ }>,summarizeSession: vi.fn(async () => undefined),+ stopAndRemovePiSubagentRuns: vi.fn(async (_root: string) => true),+ writePiSubagentDeletedTombstone: vi.fn(async (_agentHome: string, _sessionId: string) => undefined),+ clearPiSubagentDeletedTombstone: vi.fn(async (_agentHome: string, _sessionId: string) => undefined),+ getMakerIfReady: vi.fn((): {+ isSessionAlive: (id: string) => boolean;+ closeSession: (id: string) => Promise<void>;+ } | null => null),+ closeIdleSessionForMove: vi.fn(async (_sessionId: string) => true),+ withRehydrateCloseSuppressed: vi.fn(+ async (_sessionId: string, task: () => Promise<void>) => task(),+ ),+ setPinnedSectionCardMode: vi.fn(),- upsertRecentWorkdir: vi.fn(async () => undefined),+ upsertRecentWorkdir: vi.fn(+ async (+ _path: string | null | undefined,+ _atMs?: number,+ _platform?: NodeJS.Platform,+ _client?: { drizzle: ReturnType<typeof drizzle> },- ) => {- void _path;- void _atMs;- void _platform;- void _client;- return true;- },++ ) => true,+ ),+ captureOwnerScope: false,+ ownerCurrent: true,++ requestRecycle: vi.fn(async () => undefined),routeLock: vi.fn(async <T>(_sessionId: string, task: () => Promise<T>): Promise<T> =>task(),) as SessionRouteLockMock,@@@ -67,7 -82,8 +93,8 @@@ vi.mock('../../../logger', () => (createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),}));vi.mock('../../client/current', () => ({- getDbClient: () => ({ drizzle: h.db }),+ getDbClient: () => h.client,+ getCurrentDbClientUserId: () => 'test-user',}));vi.mock('../../dialogueWorkspace', () => ({ ensureDialogueWorkspaceDir: vi.fn() }));vi.mock('../../../git-context/prRefsStore', () => ({@@@ -76,12 -92,8 +103,12 @@@vi.mock('../../../imageCacheStore', () => ({ removeSession: vi.fn(async () => undefined) }));vi.mock('../recentWorkdirs', () => ({ upsertRecentWorkdir: h.upsertRecentWorkdir }));vi.mock('../../../device-link/broadcast-tap.js', () => ({- getSafeDataOwnerPushStamp: vi.fn(() => undefined),- tapWindowBroadcast: h.tapWindowBroadcast,+ captureDataOwnerBroadcastScope: vi.fn(() =>+ h.captureOwnerScope ? { ownerStamp: { dataOwnerId: 'owner-a', generation: 1 } } : null,+ ),+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),+ isDataOwnerBroadcastScopeCurrent: vi.fn(() => h.ownerCurrent),+ tapWindowBroadcast: h.tapWindowBroadcast,}));vi.mock('../../../sessionTaskSummary.js', () => ({maybeGenerateSessionTaskSummary: h.summarizeSession,@@@ -92,9 -111,32 +126,33 @@@ vi.mock('../../../sessionIds', () => (vi.mock('../../../maker-host/claude-transcript-relocation.js', () => ({relocateClaudeTranscriptsForSessionMove: h.relocate,}));+ // Loaded dynamically by the cleanup's launcher gate; the real module pulls in+ // the whole Host.+ vi.mock('../../../maker-host/index.js', () => ({+ getMakerIfReady: h.getMakerIfReady,+ withRehydrateCloseSuppressed: h.withRehydrateCloseSuppressed,+ }));+ // delete 路径的 removeHookAttachmentDir 会真删 turn change-set;归档路径动态+ // import cindy-brain(重副作用模块)。两者都 mock 掉,本文件只断言广播行为。+ vi.mock('../../../turn-change-set/store.js', () => ({+ removeTurnChangeSetsForSession: vi.fn(async () => undefined),+ }));+ vi.mock('../../../cindy-brain/index.js', () => ({+ notifyGhostSessionEvent: vi.fn(),+ }));- import { registerSessionIpc } from '../sessions';+ import {+ broadcastSessionPatched,+ patchSessionMetaInDb,+ persistSessionFields,+ registerSessionIpc,+ resumeDeletedPiSubagentCleanup,+ setSessionRuntimeCleanup,++ setSessionWorktreeRecycle,+ } from '../sessions';+ import { retireDeletedPiSubagentState } from '../piSubagentDeletion';import { setSessionRouteLockImplementation } from '../../sessionRouteLock';+ import { assertTrustedAppRendererEvent } from '../../../security/trustedAppRenderer.js';function createDb(): void {const sqlite = new Database(':memory:');@@@ -172,10 -219,20 +239,21 @@@INSERT INTO sessions (id, working_dir, agent_kind, remote_host_id, workspace_kind, source, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'review', 1, 1)- `).run('review-local', '/review/dir', 'codex', null, 'dialogue');+ `,+ )+ .run('review-local', '/review/dir', 'codex', null, 'dialogue');+ sqlite+ .prepare(+ `+ INSERT INTO sessions (+ id, working_dir, agent_kind, remote_host_id, workspace_kind, source, created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, 'bot', 1, 1)+ `,+ )+ .run('bot-local', '/bot/dir', 'pi', null, 'dialogue');h.sqlite = sqlite;-- h.db = drizzle(sqlite, { schema: { messages, sessions } });++ h.db = drizzle(sqlite, { schema: { messages, recentWorkdirs, sessions } });+ h.client = { drizzle: h.db };}async function invokeUpdate(id: string, patch: Record<string, unknown>): Promise<unknown> {@@@ -184,27 -241,49 +262,61 @@@return handler({}, id, patch);}+async function invokePatchMeta(id: string, patch: Record<string, unknown>): Promise<unknown> {+ const handler = h.handlers.get('local-db:sessions:patch-meta');+ if (!handler) throw new Error('patch-meta handler not registered');+ return handler({}, id, patch);+}++ async function invokeCreate(body: Record<string, unknown>): Promise<unknown> {+ const handler = h.handlers.get('local-db:sessions:create');+ if (!handler) throw new Error('create handler not registered');+ return handler({ sender: { id: 7 } }, body);+ }+beforeEach(() => {vi.clearAllMocks();h.relocate.mockImplementation(async () => ({ persistedSdkSessionId: null }));+ h.closeSession.mockClear();h.routeLock.mockImplementation(async (_sessionId, task) => task());+ h.upsertRecentWorkdir.mockImplementation(async () => true);+ h.captureOwnerScope = false;+ h.ownerCurrent = true;++ h.requestRecycle.mockResolvedValue(undefined);h.handlers.clear();+ h.windows = [];+ h.stopAndRemovePiSubagentRuns.mockClear();+ h.stopAndRemovePiSubagentRuns.mockImplementation(async () => true);+ h.writePiSubagentDeletedTombstone.mockClear();+ h.writePiSubagentDeletedTombstone.mockImplementation(async () => undefined);+ h.clearPiSubagentDeletedTombstone.mockClear();+ h.clearPiSubagentDeletedTombstone.mockImplementation(async () => undefined);+ h.getMakerIfReady.mockReset();+ h.closeIdleSessionForMove.mockReset();+ h.closeIdleSessionForMove.mockImplementation(async (sessionId) => {+ await h.withRehydrateCloseSuppressed(sessionId, () => h.closeSession(sessionId));+ return true;+ });+ h.withRehydrateCloseSuppressed.mockClear();+ h.withRehydrateCloseSuppressed.mockImplementation(async (_sessionId, task) => task());+ h.getMakerIfReady.mockReturnValue({ isSessionAlive: () => false, closeSession: h.closeSession });+ h.userDataDir = mkdtempSync(path.join(os.tmpdir(), 'cindy-sessions-update-'));createDb();setSessionRouteLockImplementation(h.routeLock);- registerSessionIpc();+ setSessionRuntimeCleanup(h.runtimeCleanup);++ setSessionWorktreeRecycle(h.requestRecycle);+ registerSessionIpc(undefined, { closeIdleSessionForMove: h.closeIdleSessionForMove });});- afterEach(() => {+ afterEach(async () => {+ setSessionRuntimeCleanup(null);++ setSessionWorktreeRecycle(null);setSessionRouteLockImplementation(null);+ const dir = h.userDataDir;+ if (dir) {+ rmSync(dir, { recursive: true, force: true });+ h.userDataDir = null;+ }});describe('local-db:sessions:update handler wiring', () => {@@@ -437,6 -605,144 +638,240 @@@);});+ it('broadcasts status-only patches so secondary windows converge on delete', async () => {+ await invokeUpdate('cc-local', { status: 'deleted' });++ const persisted = h+ .sqlite!.prepare('SELECT status FROM sessions WHERE id = ?')+ .get('cc-local') as { status: string };+ expect(persisted.status).toBe('deleted');+ // #3175 回归:纯 status 变化(无 title / settings / project / pinnedAt)也必须广播+ // sessions:patched,否则「在新窗口打开」的副窗口收不到删除,仍停留在旧视图。+ expect(h.tapWindowBroadcast).toHaveBeenCalledWith(+ 'local-db:sessions:patched',+ expect.objectContaining({+ sessionId: 'cc-local',+ patch: { status: 'deleted' },+ }),+ );+ expect(h.compactSessionToolResultsBestEffort).toHaveBeenCalledWith(+ expect.objectContaining({ sessionId: 'cc-local' }),+ );+ });+++ it('touches a retained local project when the generic writer archives it', async () => {++ h.sqlite!++ .prepare("UPDATE sessions SET workspace_kind = 'project', source = 'plugin' WHERE id = ?")++ .run('codex-local');++ h.windows = [++ { isDestroyed: vi.fn(() => false), webContents: { send: vi.fn() } },++ ];++ const now = vi.spyOn(Date, 'now').mockReturnValue(1_786_500_050_000);++++ try {++ await invokeUpdate('codex-local', { status: 'archived' });++ } finally {++ now.mockRestore();++ }++++ expect(h.upsertRecentWorkdir).toHaveBeenCalledWith(++ '/old/dir',++ 1_786_500_050_000,++ process.platform,++ h.client,++ );++ expect(h.windows[0]?.webContents.send).toHaveBeenCalledWith(++ 'local-db:recent-workdirs:changed',++ { path: '/old/dir' },++ );++ });++++ it('touches a retained local project when patch-meta archives it', async () => {++ h.sqlite!++ .prepare("UPDATE sessions SET workspace_kind = 'project' WHERE id = ?")++ .run('codex-local');++ h.windows = [++ { isDestroyed: vi.fn(() => false), webContents: { send: vi.fn() } },++ ];++ const now = vi.spyOn(Date, 'now').mockReturnValue(1_786_500_150_000);++++ try {++ await invokePatchMeta('codex-local', { status: 'archived' });++ } finally {++ now.mockRestore();++ }++++ expect(h.upsertRecentWorkdir).toHaveBeenCalledWith(++ '/old/dir',++ 1_786_500_150_000,++ process.platform,++ h.client,++ );++ expect(h.windows[0]?.webContents.send).toHaveBeenCalledWith(++ 'local-db:recent-workdirs:changed',++ { path: '/old/dir' },++ );++ });++++ it.each(['archived', 'deleted'] as const)(++ 'does not retain scheduler projects when the generic writer marks them %s',++ async (status) => {++ h.sqlite!++ .prepare("UPDATE sessions SET workspace_kind = 'project', source = 'scheduler' WHERE id = ?")++ .run('codex-local');++++ await invokeUpdate('codex-local', { status });++++ expect(h.upsertRecentWorkdir).not.toHaveBeenCalled();++ },++ );++++ it('suppresses the recent-project refresh after an owner switch', async () => {++ h.sqlite!++ .prepare("UPDATE sessions SET workspace_kind = 'project' WHERE id = ?")++ .run('codex-local');++ h.captureOwnerScope = true;++ h.windows = [++ { isDestroyed: vi.fn(() => false), webContents: { send: vi.fn() } },++ ];++ h.routeLock.mockImplementationOnce(async (_sessionId, task) => {++ const result = await task();++ h.ownerCurrent = false;++ return result;++ });++++ await invokeUpdate('codex-local', { status: 'archived' });++++ expect(h.upsertRecentWorkdir).toHaveBeenCalledWith(++ '/old/dir',++ expect.any(Number),++ process.platform,++ h.client,++ );++ expect(h.windows[0]?.webContents.send).not.toHaveBeenCalledWith(++ 'local-db:recent-workdirs:changed',++ expect.anything(),++ );++ });+++ it('broadcasts local unarchive status patches to every window (#3175)', async () => {+ h.sqlite!.prepare("UPDATE sessions SET status = 'archived' WHERE id = ?").run('codex-local');++ await invokeUpdate('codex-local', { status: 'active' });+ await vi.dynamicImportSettled();++ const persisted = h+ .sqlite!.prepare('SELECT status FROM sessions WHERE id = ?')+ .get('codex-local') as { status: string };+ expect(persisted.status).toBe('active');+ expect(h.tapWindowBroadcast).toHaveBeenCalledWith('local-db:sessions:patched', {+ sessionId: 'codex-local',+ patch: { status: 'active' },+ });+ expect(h.compactSessionToolResultsBestEffort).not.toHaveBeenCalled();+ });++ // setStatus 的归档形是 { status, pinnedAt: null }:广播沿用置顶合并逻辑,+ // 归档一并清 pin 与摘要(归档列表不该保留 pin 标记)。+ it('broadcasts local archive status patches with the unpin merge (#3175)', async () => {+ await invokeUpdate('codex-local', { status: 'archived', pinnedAt: null });+ await vi.dynamicImportSettled();++ const persisted = h+ .sqlite!.prepare('SELECT status, pinned_at AS pinnedAt FROM sessions WHERE id = ?')+ .get('codex-local') as { status: string; pinnedAt: number | null };+ expect(persisted.status).toBe('archived');+ expect(persisted.pinnedAt).toBeNull();+ expect(h.tapWindowBroadcast).toHaveBeenCalledWith('local-db:sessions:patched', {+ sessionId: 'codex-local',+ patch: { status: 'archived', pinnedAt: null, summary: null },+ });+ expect(h.compactSessionToolResultsBestEffort).toHaveBeenCalledWith(+ expect.objectContaining({ sessionId: 'codex-local' }),+ );+ });++ it('cleans runtime state before releasing the local terminal status lock', async () => {+ const order: string[] = [];+ h.runtimeCleanup.mockImplementationOnce(() => order.push('runtime-cleanup'));+ h.routeLock.mockImplementationOnce(async (_sessionId, task) => {+ const result = await task();+ order.push('lock-released');+ h.sqlite!.prepare("UPDATE sessions SET status = 'active' WHERE id = ?").run('codex-local');+ return result;+ });++ await invokeUpdate('codex-local', { status: 'archived' });++ expect(order).toEqual(['runtime-cleanup', 'lock-released']);+ expect(h.runtimeCleanup).toHaveBeenCalledOnce();+ });++ it('cleans runtime state before releasing the remote terminal status lock', async () => {+ const order: string[] = [];+ h.runtimeCleanup.mockImplementationOnce(() => order.push('runtime-cleanup'));+ h.routeLock.mockImplementationOnce(async (_sessionId, task) => {+ const result = await task();+ order.push('lock-released');+ h.sqlite!.prepare("UPDATE sessions SET status = 'active' WHERE id = ?").run('codex-local');+ return result;+ });++ await patchSessionMetaInDb('codex-local', { status: 'archived' });++ expect(order).toEqual(['runtime-cleanup', 'lock-released']);+ expect(h.runtimeCleanup).toHaveBeenCalledOnce();+ });++ // 竞态收敛(review on #3225):写入与查询不在同一串行区间,归档写入后、查询前+ // 另一窗口可能已把行推进到 deleted。广播必须携带持久化后的 updated.status,+ // 否则副窗/控制端镜像会被请求值回滚成旧 UI 状态(已删除任务复活)。+ // routeLock 是测试注入的实现:在锁内写库完成后、handler 继续查询前,模拟+ // 另一窗口的删除落库。+ it('broadcasts the persisted status when a concurrent window deletes between write and read', async () => {+ h.routeLock.mockImplementation(async (_sessionId, task) => {+ await task();+ h.sqlite!.prepare("UPDATE sessions SET status = 'deleted' WHERE id = ?").run('codex-local');+ });++ await invokeUpdate('codex-local', { status: 'archived' });+ await vi.dynamicImportSettled();++ expect(h.tapWindowBroadcast).toHaveBeenCalledWith('local-db:sessions:patched', {+ sessionId: 'codex-local',+ patch: { status: 'deleted' },+ });+ // 不再出现携带请求值的回滚广播+ const statusPatches = h.tapWindowBroadcast.mock.calls+ .filter(([channel]) => channel === 'local-db:sessions:patched')+ .map(([, payload]) => (payload as { patch: { status?: string } }).patch.status);+ expect(statusPatches).toEqual(['deleted']);+ });++ // 竞态收敛(review on #3225 第二轮):读行与广播之间还有 await(摘要清理 /+ // recent-workdir / 转录迁移),期间另一窗口可删除并先广播 deleted;本 handler+ // 恢复后若用旧快照广播 archived,该广播是最后一条,镜像不会自愈——已删任务+ // 持久复活。upsertRecentWorkdir 是已 mock 的依赖:在其 await 期间模拟删除落库,+ // 断言广播前重读了状态。+ it('re-reads status before broadcasting when an await intervenes after the row read', async () => {+ h.upsertRecentWorkdir.mockImplementationOnce(async () => {+ h.sqlite!.prepare("UPDATE sessions SET status = 'deleted' WHERE id = ?").run('cc-local');++ return true;+ });++ await invokeUpdate('cc-local', { status: 'archived', workspaceKind: 'project' });+ await vi.dynamicImportSettled();++ expect(h.tapWindowBroadcast).toHaveBeenCalledWith('local-db:sessions:patched', {+ sessionId: 'cc-local',+ patch: expect.objectContaining({ status: 'deleted' }),+ });+ const statusPatches = h.tapWindowBroadcast.mock.calls+ .filter(([channel]) => channel === 'local-db:sessions:patched')+ .map(([, payload]) => (payload as { patch: { status?: string } }).patch.status);+ expect(statusPatches).toEqual(['deleted']);+ });+it('broadcasts pin and unpin patches to device-link subscribers', async () => {const pinnedAt = '2026-08-03T04:08:26.000Z';await invokeUpdate('codex-local', { pinnedAt });diff --cc apps/desktop/src/main/localDb/ipc/sessions.tsindex b6509c5b78,db8f0abd55..80b69d7cca--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@@ -35,11 -62,9 +62,12 @@@ import { removeSessionRefsIfDeleted asimport { removeWechatSessionAttachmentDir } from '../../im/wechat/mediaStaging';import { upsertRecentWorkdir } from './recentWorkdirs';import { createLogger } from '../../logger';-import { DESKTOP_VISIBLE_SESSION_SOURCES } from '../../../shared/sessionSource.js';+import {+ DESKTOP_VISIBLE_SESSION_SOURCES,+ isRetainableProjectSessionSource,+} from '../../../shared/sessionSource.js';import { normalizeWorkingDirForStorage } from '../../../shared/workingDir.js';+ import { assertRendererSessionSourceAllowed } from './sessionSourceGuard.js';import type { SessionReference } from '../../../shared/sessionReference.js';import * as broadcastTap from '../../device-link/broadcast-tap.js';import { notifyAgentIslandSessionPatch } from '../agentIslandSessionPatch';@@@ -89,6 -160,13 +163,11 @@@ export function setSessionRemovalCleanusessionRemovalCleanup = cleanupRemovedSession;}+ /** Composition-root injection keeps the localDb IPC layer independent of worktree implementation modules. */-export function setSessionWorktreeRecycle(- recycle: SessionWorktreeRecycle | null,-): void {++export function setSessionWorktreeRecycle(recycle: SessionWorktreeRecycle | null): void {+ sessionWorktreeRecycle = recycle;+ }+function captureOwnerScope(): OwnerScope {try {const capture = broadcastTap.captureDataOwnerBroadcastScope;@@@ -113,9 -192,62 +193,78 @@@ async function withStatusWriteLock<T>sessionId: string,status: unknown,task: () => Promise<T>,+ alreadyLocked = false,): Promise<T> {- if (status === undefined) return task();- return withSessionRouteLock(sessionId, task);+ const write = async () => {+ const resources = status === undefined ? [] : await readSessionWorktreeResources(db, sessionId);+ const physicalResources = await Promise.all(resources.map(physicalWorktreeKey));+ const mutate = async () => {- if (status === 'archived' || status === 'deleted') await requestWorktreeRecycle(sessionId, resources);++ if (status === 'archived' || status === 'deleted')++ await requestWorktreeRecycle(sessionId, resources);+ const result = await task();+ for (const resource of physicalResources) notifyWorktreeRecycleOpportunity(resource);+ return result;+ };+ return withWorktreeMutation(resources, mutate);+ };+ if (status === undefined || alreadyLocked) return write();+ return withSessionRouteLock(sessionId, write);+ }+-async function requestWorktreeRecycle(sessionId: string, resources: readonly string[] = []): Promise<void> {++async function requestWorktreeRecycle(++ sessionId: string,++ resources: readonly string[] = [],++): Promise<void> {+ const recycle = sessionWorktreeRecycle;+ if (!recycle) throw new Error('worktree recycle implementation is not wired');+ await recycle(sessionId, resources);+ }++ /** Persist a terminal cleanup intent using references from the same DB snapshot. */+ export async function requestSessionWorktreeRecycle(+ db: DbClient['drizzle'],+ sessionId: string,+ ): Promise<void> {+ await requestWorktreeRecycle(sessionId, await readSessionWorktreeResources(db, sessionId));+ }++ /** Read from the same captured database that will receive the status/path update. */-async function readSessionWorktreeResources(db: DbClient['drizzle'], sessionId: string): Promise<string[]> {++async function readSessionWorktreeResources(++ db: DbClient['drizzle'],++ sessionId: string,++): Promise<string[]> {+ try {- const [row] = await db.select({- workingDir: sessions.workingDir, worktreePath: sessions.worktreePath, remoteHostId: sessions.remoteHostId,- }).from(sessions).where(eq(sessions.id, sessionId)).limit(1);++ const [row] = await db++ .select({++ workingDir: sessions.workingDir,++ worktreePath: sessions.worktreePath,++ remoteHostId: sessions.remoteHostId,++ })++ .from(sessions)++ .where(eq(sessions.id, sessionId))++ .limit(1);+ if (!row || row.remoteHostId) return [];+ return [row.workingDir, row.worktreePath].flatMap((value) => {+ const root = value ? managedWorktreeRoot(value) : null;+ return root ? [root] : [];+ });+ } catch {+ throwIpcError('PRECONDITION_FAILED', 'Worktree references are temporarily unavailable');+ }+ }++ async function withWorktreeMutation<T>(resources: string[], task: () => Promise<T>): Promise<T> {+ try {+ return await withWorktreeResourceLocks(resources, task);+ } catch (error) {+ const code = (error as { code?: string })?.code;+ if (code && error instanceof Error && error.message.startsWith(`[${code}]`)) throw error;+ log.warn('worktree mutation postponed', { code: code ?? 'unavailable' });- throwIpcError('PRECONDITION_FAILED', 'Worktree is busy or its recovery record could not be saved');++ throwIpcError(++ 'PRECONDITION_FAILED',++ 'Worktree is busy or its recovery record could not be saved',++ );+ }}async function writeSessionPatch(@@@ -173,15 -306,32 +323,40 @@@ export function broadcastSessionPatchedif (ownerScope !== undefined && !isOwnerScopeCurrent(ownerScope)) return;const hasCapturedScope = ownerScope !== undefined && ownerScope !== null;const ownerStamp = hasCapturedScope ? ownerScope.ownerStamp : getSafeOwnerPushStamp();- if (hasCapturedScope) {- broadcastTap.tapWindowBroadcast('local-db:sessions:patched', { sessionId, patch }, ownerStamp);- } else if (ownerStamp === undefined) {- broadcastTap.tapWindowBroadcast('local-db:sessions:patched', { sessionId, patch });- } else {- broadcastTap.tapWindowBroadcast('local-db:sessions:patched', { sessionId, patch }, ownerStamp);+ try {+ if (hasCapturedScope) {- broadcastTap.tapWindowBroadcast('local-db:sessions:patched', { sessionId, patch }, ownerStamp);++ broadcastTap.tapWindowBroadcast(++ 'local-db:sessions:patched',++ { sessionId, patch },++ ownerStamp,++ );+ } else if (ownerStamp === undefined) {+ broadcastTap.tapWindowBroadcast('local-db:sessions:patched', { sessionId, patch });+ } else {- broadcastTap.tapWindowBroadcast('local-db:sessions:patched', { sessionId, patch }, ownerStamp);++ broadcastTap.tapWindowBroadcast(++ 'local-db:sessions:patched',++ { sessionId, patch },++ ownerStamp,++ );+ }+ } catch (error) {+ log.warn('session patch device-link broadcast failed', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });}- for (const w of BrowserWindow.getAllWindows()) {- if (!w.isDestroyed()) {+ let windows: ReturnType<typeof BrowserWindow.getAllWindows> = [];+ try {+ windows = BrowserWindow.getAllWindows();+ } catch (error) {+ log.warn('session patch window enumeration failed', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ for (const w of windows) {+ try {+ if (w.isDestroyed()) continue;if (hasCapturedScope) {w.webContents.send('local-db:sessions:patched', { sessionId, patch }, ownerStamp);} else if (ownerStamp === undefined) {@@@ -193,29 -348,12 +373,26 @@@}}- /** 刷新本机窗口的 recent_workdirs cache;异步写跨 owner 后不得误投给新账号。 */+function broadcastRecentWorkdirsChanged(path: string, ownerScope: OwnerScope): void {+ if (!isOwnerScopeCurrent(ownerScope)) return;+ const hasCapturedScope = ownerScope !== null;+ const ownerStamp = hasCapturedScope ? ownerScope.ownerStamp : getSafeOwnerPushStamp();- for (const w of BrowserWindow.getAllWindows()) {- if (w.isDestroyed()) continue;++ for (const window of BrowserWindow.getAllWindows()) {++ if (window.isDestroyed()) continue;+ if (hasCapturedScope || ownerStamp !== undefined) {- w.webContents.send('local-db:recent-workdirs:changed', { path }, ownerStamp);++ window.webContents.send('local-db:recent-workdirs:changed', { path }, ownerStamp);+ } else {- w.webContents.send('local-db:recent-workdirs:changed', { path });++ window.webContents.send('local-db:recent-workdirs:changed', { path });+ }+ }+}+/**- * worktree 回收真正跑完后通知本机所有窗口重拉 worktree 快照。+ * worktree 回收真正跑完后通知本机所有窗口更新对应 session 的 worktree 缓存。*- * 没有这条推送,renderer 只能在归档/删除动作里"顺手"刷一次 worktree map,而回收- * 是下面 fire-and-forget 的异步链(动态 import → 关子进程 → git worktree remove →- * 文件系统清理),store 条目被移除的时刻远晚于状态 IPC 返回。renderer 那次刷新会- * 快照到仍然存在的旧条目,归档列表上的 worktree 徽标就一直陈旧,直到某次无关的- * 刷新才纠正(codex review P1)。+ * 回收是下面 fire-and-forget 的异步链(动态 import → 关子进程 → git worktree remove →+ * 文件系统清理),store 条目被移除的时刻远晚于状态 IPC 返回。这条推送提供回收完成的+ * 权威时机;payload 保持为单个 sessionId,renderer 不需要重拉全表。** 只广播给本机窗口、不进 device-link tap:控制端(手机/另一台桌面)的远程会话* worktree 元数据走 device-link 自己的镜像链路,不经本机 WorktreeContext。@@@ -246,12 -386,26 +425,28 @@@ export async function recycleSessionWorcapturedScope?: SessionRecycleScope,): Promise<void> {if (status !== 'deleted' && status !== 'archived') return;+ // Capture before queueing: an account switch while waiting cannot redirect cleanup.try {- // Callers that already crossed an async status write pass the owner/DB- // captured at operation entry. The fallback is only for direct callers.- const ownerScope = capturedScope?.ownerScope ?? captureOwnerScope();- const mediaDb = capturedScope?.mediaDb ?? getDbClient().drizzle;- if (!isOwnerScopeCurrent(ownerScope)) return;+ const scope = capturedScope ?? captureSessionRecycleScope();+ await queueSessionWorktreeRecycle(() => recycleSessionWorktreeInQueue(sessionId, scope));+ } catch (error) {+ log.warn('worktree recycle scheduling postponed', {- sessionId, code: (error as NodeJS.ErrnoException).code ?? 'unavailable',++ sessionId,++ code: (error as NodeJS.ErrnoException).code ?? 'unavailable',+ });+ }+ }++ async function recycleSessionWorktreeInQueue(+ sessionId: string,+ capturedScope: SessionRecycleScope,+ ): Promise<void> {+ const affectedWorktreeSessionIds = new Set<string>();+ try {+ const { ownerScope, mediaDb } = capturedScope;- const ownerIsCurrent = (): boolean => isOwnerScopeCurrent(ownerScope) && getDbClient().drizzle === mediaDb;++ const ownerIsCurrent = (): boolean =>++ isOwnerScopeCurrent(ownerScope) && getDbClient().drizzle === mediaDb;+ if (!ownerIsCurrent()) return;const cancelOperations = sessionRemovalCancelOperations;const cleanupRemovedSession = sessionRemovalCleanup;if (!cancelOperations || !cleanupRemovedSession) {@@@ -1002,33 -1182,65 +1223,68 @@@ export function registerSessionIpc// listSessions 行为一致:'all' 白名单 ['active','archived'])const statusFilter: 'active' | 'archived' | null =status === 'active' || status === 'archived' ? status : null;- // 按 DESKTOP_VISIBLE_SESSION_SOURCES 白名单过滤 — 包含 IM 渠道- // (feishu/slack/discord)与本机自动化(scheduler/learn/shared);- // feishu 会话以「对话」分组展示(workspaceKind='dialogue')。- const sourceFilter = inArray(sessions.source, DESKTOP_VISIBLE_SESSION_SOURCES);- const statusWhere = () =>- statusFilter ? eq(sessions.status, statusFilter) : ne(sessions.status, 'deleted');- const rows = await selectSessionListRows(db, and(sourceFilter, statusWhere()), cap);-- let mergedRows = rows;- if (includePinned) {- const pinnedRows = await selectSessionListRows(- db,- and(sourceFilter, statusWhere(), isNotNull(sessions.pinnedAt)),- null,- );- mergedRows = mergeSessionListRows(rows, pinnedRows);- }+ const loadRows = async () => {+ // 按 DESKTOP_VISIBLE_SESSION_SOURCES 白名单过滤 — 包含 IM 渠道+ // (feishu/slack/discord)与本机自动化(scheduler/learn/shared);+ // feishu 会话以「对话」分组展示(workspaceKind='dialogue')。+ const sourceFilter = inArray(sessions.source, DESKTOP_VISIBLE_SESSION_SOURCES);+ const statusWhere = () =>+ statusFilter ? eq(sessions.status, statusFilter) : ne(sessions.status, 'deleted');+ const rows = await selectSessionListRows(db, and(sourceFilter, statusWhere()), cap);++ let mergedRows = rows;+ if (includePinned) {+ const pinnedRows = await selectSessionListRows(+ db,+ and(sourceFilter, statusWhere(), isNotNull(sessions.pinnedAt)),+ null,+ );+ mergedRows = mergeSessionListRows(rows, pinnedRows);+ }- const queryFinishedAt = performance.now();- const result = mergedRows.map((r) =>- sessionToCamel({- ...r.session,- messageCount: r.messageCount,- latestMessageContent: r.latestMessageContent,- latestMessageRole: r.latestMessageRole,- }),- );+ scheduleSessionListProjectionBackfill(mergedRows);+ return mergedRows.map((r) =>+ sessionToCamel(- projectSessionContextWindow({- ...r.session,- messageCount: r.messageCount,- latestMessageExtract: r.latestMessageExtract,- latestMessageRole: r.latestMessageRole,- }, opts.resolveContextWindow),++ projectSessionContextWindow(++ {++ ...r.session,++ messageCount: r.messageCount,++ latestMessageExtract: r.latestMessageExtract,++ latestMessageRole: r.latestMessageRole,++ },++ opts.resolveContextWindow,++ ),+ ),+ );+ };+ const loadUsageHistoryRows = async () => {+ // 用量历史的“最耗任务”必须覆盖整个会话表,再由 renderer 按所选日历范围+ // 精确筛选;不能复用侧栏按 updatedAt 截断的 1000 行列表。这里刻意不算+ // messageCount / preview,避免为统计页引入整库 messages 扫描。+ const sourceFilter = inArray(sessions.source, DESKTOP_VISIBLE_SESSION_SOURCES);+ const statusWhere = () =>+ statusFilter ? eq(sessions.status, statusFilter) : ne(sessions.status, 'deleted');+ const rows = await selectSessionUsageRows(db, and(sourceFilter, statusWhere()));+ return rows.map((row) =>+ sessionUsageToCamel(projectSessionContextWindow(row, opts.resolveContextWindow)),+ );+ };+ // key 用同一快照上的 userId + clientEpoch + 归一化参数。+ // forceRefresh / status 重拉带 fresh,不并入写前那次查询。+ const result = usageHistory+ ? await loadUsageHistoryRows()+ : userId && !fresh+ ? await runSessionListSingleFlight(+ buildSessionListFlightKey({+ userId,+ clientEpoch,+ cap,+ statusFilter,+ includePinned,+ }),+ loadRows,+ )+ : await loadRows();const finishedAt = performance.now();const filter = statusFilter ?? 'all';const elapsedMs = Math.round(finishedAt - startedAt);@@@ -1093,6 -1313,33 +1357,35 @@@if (workspaceKind === 'dialogue' && !explicitWorkingDir) {log.info('[localDb] allocated dialogue workspace', { sessionId: id, workingDir });}+ const requestedWritableDirs = createBody?.writableDirs ?? [];- if (!Array.isArray(requestedWritableDirs)- || !requestedWritableDirs.every((dir) => typeof dir === 'string')) {++ if (++ !Array.isArray(requestedWritableDirs) ||++ !requestedWritableDirs.every((dir) => typeof dir === 'string')++ ) {+ throwIpcError('INVALID_PARAMS', 'writableDirs must be string[]');+ }+ const requestedRemoteHostId = normalizeRemoteHostId(createBody?.remoteHostId);+ if (requestedRemoteHostId && requestedWritableDirs.length > 0) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'remote writable directories can only be revoked from an existing task',+ );+ }+ if (!requestedRemoteHostId && requestedWritableDirs.length > 0) {+ try {+ await consumeWritableDirectoryPickerGrants({+ scopeId: id,+ senderId: event.sender.id,+ requestedDirs: requestedWritableDirs,+ previousDirs: [],+ });+ } catch (error) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ error instanceof Error ? error.message : 'Writable directory authorization failed',+ );+ }+ }// body 透传 agentKind / orcaRole 给 mapper;非法值已由上方校验拦截,默认值由 mapper 兜底。const insertRow = sessionCreateToRow(id, { ...createBody, workspaceKind, workingDir }, now);await ensureProjectGitInitialized({@@@ -1103,7 -1350,11 +1396,15 @@@autoSnapshotEnabled: readGitSafetySettings().autoSnapshotEnabled,source: 'local-db:sessions:create',});- await db.insert(sessions).values(insertRow);- const resource = !insertRow.remoteHostId && insertRow.workingDir- ? managedWorktreeRoot(insertRow.workingDir) : null;- const insert = async () => { await db.insert(sessions).values(insertRow); };++ const resource =++ !insertRow.remoteHostId && insertRow.workingDir++ ? managedWorktreeRoot(insertRow.workingDir)++ : null;++ const insert = async () => {++ await db.insert(sessions).values(insertRow);++ };+ if (resource) await withWorktreeMutation([resource], insert);+ else await insert();const [row] = await db.select().from(sessions).where(eq(sessions.id, id));if (!row) throwIpcError('NOT_FOUND', 'Session 创建后查询失败');// recent-workdirs: 项目目录走 sidebar 分组,要进"最近"列表;dialogue 目录是@@@ -1360,187 -1612,270 +1662,283 @@@const sid = requireString(id, 'id');const ownerScope = captureOwnerScope();const p = requireObject(patch, 'patch');+ if (p.extraDirs !== undefined || p.writableDirs !== undefined) {+ throwIpcError(+ 'UNSUPPORTED_CAPABILITY',+ 'directory grants must be changed through maker:set-*-dirs',+ );+ }const dbClient = getDbClient();const db = dbClient.drizzle;- if (p.workspaceKind !== undefined) {- const value = p.workspaceKind;- if (value !== 'project' && value !== 'dialogue') {- throwIpcError('INVALID_PARAMS', `invalid workspaceKind: ${String(value)}`);+ // 工作目录切换必须和发送/懒启动共用同一把路由锁。否则发送可能在+ // 读取旧目录后、写入新目录前重建 runtime,随后仍在旧目录执行。+ const update = async () => {+ if (p.workspaceKind !== undefined) {+ const value = p.workspaceKind;+ if (value !== 'project' && value !== 'dialogue') {+ throwIpcError('INVALID_PARAMS', `invalid workspaceKind: ${String(value)}`);+ }}- }- const ALLOWED_UPDATE_ORCA_ROLES = new Set<string>(['lead', 'worker']);- if (- p.orcaRole !== undefined &&- p.orcaRole !== null &&- !ALLOWED_UPDATE_ORCA_ROLES.has(p.orcaRole as string)- ) {- throwIpcError('INVALID_PARAMS', `invalid orcaRole: ${String(p.orcaRole)}`);- }- if (typeof p.workingDir === 'string') {- p.workingDir = normalizeWorkingDirForStorage(p.workingDir) ?? null;- }- const REVIEW_IMMUTABLE_FIELDS = new Set([- 'workingDir',- 'workspaceKind',- 'model',- 'providerId',- 'effort',- 'permissionMode',- 'fastMode',- 'planModeEnabled',- 'orcaRole',- 'extraDirs',- ]);- if (Object.keys(p).some((key) => REVIEW_IMMUTABLE_FIELDS.has(key))) {- const [target] = await db- .select({ source: sessions.source })- .from(sessions)- .where(eq(sessions.id, sid))- .limit(1);- if (target?.source === 'review') {- throwIpcError(- 'UNSUPPORTED_CAPABILITY',- 'Review task settings are fixed to the source task',- );+ const ALLOWED_UPDATE_ORCA_ROLES = new Set<string>(['lead', 'worker']);+ if (+ p.orcaRole !== undefined &&+ p.orcaRole !== null &&+ !ALLOWED_UPDATE_ORCA_ROLES.has(p.orcaRole as string)+ ) {+ throwIpcError('INVALID_PARAMS', `invalid orcaRole: ${String(p.orcaRole)}`);}- }- // 会话移动转录迁移:patch 带 workingDir 时先留存旧值,update 后对比实际变化。- // CLI 转录按 cwd 转码目录存放,workingDir 变了必须跟着搬,否则 resume 报- // "No conversation found with session ID"(见 claude-transcript-relocation.ts)。- const beforeMove =- p.workingDir !== undefined- ? (- await db- .select({- workingDir: sessions.workingDir,- agentKind: sessions.agentKind,- remoteHostId: sessions.remoteHostId,- })- .from(sessions)- .where(eq(sessions.id, sid))- )[0]- : undefined;- // 只有纯设置字段(model/effort 等)才跳过 bump;凡带 activity 字段- // (clearedAt / sdkSessionId / status / token 用量等)仍需更新 updatedAt,- // 否则本地 /clear 后重启侧栏时间回退旧值。- const SETTINGS_ONLY_FIELDS = new Set([- 'model',- 'effort',- 'permissionMode',- 'fastMode',- 'planModeEnabled',- 'providerId',- 'orcaRole',- 'extraDirs',- 'pinnedAt',- 'workingDir',- 'workspaceKind',- 'title',- ]);- const isSettingsOnly = Object.keys(p).every((k) => SETTINGS_ONLY_FIELDS.has(k));- const setObj = sessionPatchToRow(p as Parameters<typeof sessionPatchToRow>[0], {- bumpUpdatedAt: !isSettingsOnly,- });- // 用户手动改名(重命名框 / 侧边栏)走这条:告诉自动起名收手。同值改名不会让- // 条件写落空,不显式说一声的话智能标题会把他刚保存的名字盖掉(review P1)。- // **必须先于 UPDATE**:写库是一次 worker RPC 往返,改名提交与这里拿到回执之间- // 有真实时间差,在那期间智能标题仍能满足 `WHERE title = 期望值` 把名字盖掉。- // 先记号后写库,代价只是写库失败时该会话本进程内不再自动起名 —— 用户毕竟确实- // 按下过保存,这个方向的偏差是安全的。- if (typeof p.title === 'string') noteUserTitleWritten(sid);- await withStatusWriteLock(sid, p.status, () => writeSessionPatch(db, sid, setObj, p.status));- // session-git-pr-context:/clear 经此处写 clearedAt——边界之前的消息对用户- // 不可见,PR 引用同步重算(fire-and-forget,内部按 clearedAt/rewindAt 过滤)。- if (p.clearedAt !== undefined) {- noteSessionClearBoundary(sid, p.clearedAt as string | null);- // sidebar-card-mode(codex review):summary 是基于 clear 前内容生成的,clear 后- // 已过时;SessionCard / rail flyout 优先用 summary 而非 preview,不清就会继续- // 显示旧任务摘要。这里一并清空,待 clear 后新一轮 turn-done 重新生成。- await db.update(sessions).set({ summary: null }).where(eq(sessions.id, sid));- // 广播 summary:null,让已挂载的 sidebar 立即清掉旧摘要(codex review)——renderer 的- // clearSession 乐观 patch 只带 sdkSessionId/clearedAt、不含 summary,本 update handler- // 也不另发 patched;不广播则卡片/rail 会继续显示 clear 前摘要直到一次全量 refresh。- if (isOwnerScopeCurrent(ownerScope)) {- broadcastSessionPatched(sid, { summary: null }, ownerScope);+ if (typeof p.workingDir === 'string') {+ p.workingDir = normalizeWorkingDirForStorage(p.workingDir) ?? null;}- void recomputePrRefsForSession(sid).catch(() => undefined);- }- // workingDir 实际变化的本机 cc 会话:迁移 CLI 转录后再查询返回行/广播,保证- // renderer 拿到更新结果时转录已就位(用户可立即续聊),且迁移中持久化的最新- // sdkSessionId 能进返回行与广播 patch——否则 renderer 留着旧 resume id,下一次- // lazy-create 仍会 resume 到 pre-fork 会话。内部 best-effort 不抛错。- // 动态 import 避免 localDb → maker-host 的静态模块环(同下方 sessionTaskSummary)。- if (- beforeMove &&- beforeMove.agentKind === 'cc' &&- !beforeMove.remoteHostId &&- beforeMove.workingDir &&- typeof p.workingDir === 'string' &&- p.workingDir &&- normalizeWorkingDirForStorage(beforeMove.workingDir) !== p.workingDir- ) {- const m = await import('../../maker-host/claude-transcript-relocation.js');- const reloc = await m.relocateClaudeTranscriptsForSessionMove(+ const REVIEW_IMMUTABLE_FIELDS = new Set([+ 'workingDir',+ 'workspaceKind',+ 'model',+ 'providerId',+ 'effort',+ 'permissionMode',+ 'fastMode',+ 'planModeEnabled',+ 'orcaRole',+ 'extraDirs',+ 'writableDirs',+ ]);+ if (Object.keys(p).some((key) => REVIEW_IMMUTABLE_FIELDS.has(key))) {+ const [target] = await db+ .select({ source: sessions.source })+ .from(sessions)+ .where(eq(sessions.id, sid))+ .limit(1);+ if (target?.source === 'review') {+ throwIpcError(+ 'UNSUPPORTED_CAPABILITY',+ 'Review task settings are fixed to the source task',+ );+ }+ }+ // 会话移动转录迁移:patch 带 workingDir 时先留存旧值,update 后对比实际变化。+ // CLI 转录按 cwd 转码目录存放,workingDir 变了必须跟着搬,否则 resume 报+ // "No conversation found with session ID"(见 claude-transcript-relocation.ts)。+ const beforeMove =+ p.workingDir !== undefined+ ? (+ await db+ .select({+ workingDir: sessions.workingDir,+ agentKind: sessions.agentKind,+ remoteHostId: sessions.remoteHostId,+ })+ .from(sessions)+ .where(eq(sessions.id, sid))+ )[0]+ : undefined;+ const movingLocalNonClaudeSession =+ beforeMove &&+ beforeMove.agentKind !== 'cc' &&+ !beforeMove.remoteHostId &&+ beforeMove.workingDir &&+ typeof p.workingDir === 'string' &&+ p.workingDir &&+ normalizeWorkingDirForStorage(beforeMove.workingDir) !== p.workingDir;+ // Pi/Codex keep a live Maker handle whose cwd is fixed at bootstrap. Close it+ // before persisting the new directory so the next send lazily recreates the+ // runtime with the moved session's cwd instead of continuing in the old one.+ if (movingLocalNonClaudeSession) {+ if (!opts.closeIdleSessionForMove) {+ throwIpcError('INTERNAL', '会话移动 runtime 操作未配置');+ }+ const idle = await opts.closeIdleSessionForMove(sid);+ if (idle === false) {+ throwIpcError('PRECONDITION_FAILED', '运行中的任务不能移动');+ }+ }+ // 只有纯设置字段(model/effort 等)才跳过 bump;凡带 activity 字段+ // (clearedAt / sdkSessionId / status / token 用量等)仍需更新 updatedAt,+ // 否则本地 /clear 后重启侧栏时间回退旧值。+ const SETTINGS_ONLY_FIELDS = new Set([+ 'model',+ 'effort',+ 'permissionMode',+ 'fastMode',+ 'planModeEnabled',+ 'providerId',+ 'orcaRole',+ 'extraDirs',+ 'writableDirs',+ 'pinnedAt',+ 'workingDir',+ 'workspaceKind',+ 'title',+ ]);+ const isSettingsOnly = Object.keys(p).every((k) => SETTINGS_ONLY_FIELDS.has(k));+ const setObj = sessionPatchToRow(p as Parameters<typeof sessionPatchToRow>[0], {+ bumpUpdatedAt: !isSettingsOnly,+ });+ if (p.clearedAt !== undefined) {+ setObj.summary = null;+ setObj.listPreview = null;+ setObj.listPreviewRole = null;+ }+ // 用户手动改名(重命名框 / 侧边栏)走这条:告诉自动起名收手。同值改名不会让+ // 条件写落空,不显式说一声的话智能标题会把他刚保存的名字盖掉(review P1)。+ // **必须先于 UPDATE**:写库是一次 worker RPC 往返,改名提交与这里拿到回执之间+ // 有真实时间差,在那期间智能标题仍能满足 `WHERE title = 期望值` 把名字盖掉。+ // 先记号后写库,代价只是写库失败时该会话本进程内不再自动起名 —— 用户毕竟确实+ // 按下过保存,这个方向的偏差是安全的。+ if (typeof p.title === 'string') noteUserTitleWritten(sid);+ await withStatusWriteLock(+ db,sid,- beforeMove.workingDir,- p.workingDir,+ p.status,+ async () => {+ if (p.status !== undefined) await assertGenericSessionLifecycleAllowed(db, sid);+ await writeSessionPatch(db, sid, setObj, p.status);+ cleanupSessionRuntimeForTerminalStatus(sid, p.status);+ },+ p.workingDir !== undefined,);- if (reloc.persistedSdkSessionId) {- (p as Record<string, unknown>).sdkSessionId = reloc.persistedSdkSessionId;+ // session-git-pr-context:/clear 经此处写 clearedAt——边界之前的消息对用户+ // 不可见,PR 引用同步重算(fire-and-forget,内部按 clearedAt/rewindAt 过滤)。+ if (p.clearedAt !== undefined) {+ noteSessionClearBoundary(sid, p.clearedAt as string | null);+ // sidebar-card-mode(codex review):summary 是基于 clear 前内容生成的,clear 后+ // 已过时;置顶卡片优先用 summary 而非 preview,不清就会继续显示旧任务摘要。+ // 与 clearedAt 同一句 UPDATE 置空,避免崩溃后非 NULL 缓存绕过 clear 边界。+ if (isOwnerScopeCurrent(ownerScope)) {+ broadcastSessionPatched(sid, { summary: null, preview: null }, ownerScope);+ }+ void recomputePrRefsForSession(sid).catch(() => undefined);}- }- const row = await selectSessionWithCount(db, sid);- if (!row) throwIpcError('NOT_FOUND', 'Session 不存在');- const updated = sessionToCamel(row);- const broadcastPatch =- p.pinnedAt === undefined- ? p- : {- ...p,- pinnedAt: updated.pinnedAt,- ...(updated.pinnedAt === null ? {} : { status: updated.status }),- };- const projectTargetChanged = p.workspaceKind !== undefined || p.workingDir !== undefined;- const settingsChanged = Object.keys(p).some((key) => REMOTE_PERSIST_FIELDS.has(key));- const titleChanged = p.title !== undefined;- if (- (projectTargetChanged || p.status === 'deleted' || p.status === 'archived') &&- row.workspaceKind === 'project' &&- row.workingDir &&- !row.remoteHostId &&- isRetainableProjectSessionSource(row.source)- ) {- const touched = await upsertRecentWorkdir(- row.workingDir,- Date.now(),- process.platform,- dbClient,- );- if (touched) broadcastRecentWorkdirsChanged(row.workingDir, ownerScope);- }- if (projectTargetChanged || settingsChanged || titleChanged || p.pinnedAt !== undefined) {- if (isOwnerScopeCurrent(ownerScope)) {- broadcastSessionPatched(sid, broadcastPatch, ownerScope);+ // workingDir 实际变化的本机 cc 会话:迁移 CLI 转录后再查询返回行/广播,保证+ // renderer 拿到更新结果时转录已就位(用户可立即续聊),且迁移中持久化的最新+ // sdkSessionId 能进返回行与广播 patch——否则 renderer 留着旧 resume id,下一次+ // lazy-create 仍会 resume 到 pre-fork 会话。内部 best-effort 不抛错。+ // 动态 import 避免 localDb → maker-host 的静态模块环(同下方 sessionTaskSummary)。+ if (+ beforeMove &&+ beforeMove.agentKind === 'cc' &&+ !beforeMove.remoteHostId &&+ beforeMove.workingDir &&+ typeof p.workingDir === 'string' &&+ p.workingDir &&+ normalizeWorkingDirForStorage(beforeMove.workingDir) !== p.workingDir+ ) {+ const m = await import('../../maker-host/claude-transcript-relocation.js');+ const reloc = await m.relocateClaudeTranscriptsForSessionMove(+ sid,+ beforeMove.workingDir,+ p.workingDir,+ );+ if (reloc.persistedSdkSessionId) {+ (p as Record<string, unknown>).sdkSessionId = reloc.persistedSdkSessionId;+ }}- }- // sidebar-card-mode: 会话被置顶那一刻补生成任务摘要(turn-done 路径只覆盖- // "置顶后又跑过 turn"的会话)。动态 import 避免 localDb → maker-host 的静态- // 模块环;fire-and-forget,模块内部自带置顶/节流守卫。- if (p.pinnedAt !== undefined && updated.pinnedAt !== null) {- void import('../../sessionTaskSummary.js').then((m) =>- m.maybeGenerateSessionTaskSummary(sid),- );- }- notifyAgentIslandSessionPatch(updated.id, {- status: updated.status,- title: updated.title,- workingDir: updated.workingDir,- workspaceKind: updated.workspaceKind,+ const row = await selectSessionWithCount(db, sid);+ if (!row) throwIpcError('NOT_FOUND', 'Session 不存在');+ // 取消置顶后摘要不再有展示面,立刻清掉,避免列表/再次置顶前继续吃旧句。+ if (p.pinnedAt !== undefined && row.pinnedAt == null) {+ await db.update(sessions).set({ summary: null }).where(eq(sessions.id, sid));+ row.summary = null;+ }+ const updated = sessionToCamel(row);+ const projectTargetChanged = p.workspaceKind !== undefined || p.workingDir !== undefined;+ const settingsChanged = Object.keys(p).some((key) => REMOTE_PERSIST_FIELDS.has(key));+ const titleChanged = p.title !== undefined;+ // 归档/删除这类纯 status 变化也要广播:本机多窗口收敛靠 sessions:patched,+ // 否则「在新窗口打开」的副窗口无从得知会话已被移除,仍停留在旧视图(#3175)。+ const statusChanged = p.status !== undefined;+ if (- projectTargetChanged &&++ (projectTargetChanged || p.status === 'deleted' || p.status === 'archived') &&+ row.workspaceKind === 'project' &&+ row.workingDir &&- !row.remoteHostId++ !row.remoteHostId &&++ isRetainableProjectSessionSource(row.source)+ ) {- await upsertRecentWorkdir(row.workingDir, Date.now());++ const touched = await upsertRecentWorkdir(++ row.workingDir,++ Date.now(),++ process.platform,++ dbClient,++ );++ if (touched) broadcastRecentWorkdirsChanged(row.workingDir, ownerScope);+ }+ // status 广播必须用**广播时刻的持久化真值**,不能带请求值 p.status,也不能用+ // 上方读行的快照:写入(withStatusWriteLock)与广播不在同一串行区间,且读行+ // 之后、广播之前还有 await(摘要清理 / recent-workdir / 转录迁移),两个窗口+ // 对同一任务并发操作时,本请求可能在此期间被另一窗口推进到更晚的终态(如+ // 归档写入后被删除)。用过期值广播会把镜像回滚成旧 UI 状态(已删除任务在+ // 副窗/控制端复活),且若本广播是最后一条,镜像不会自愈。+ //+ // 因此含 status 的 patch 在广播前(所有 await 之后)**重读一次**:重读与广播+ // 之间无 await,同进程单事件循环下不可能再插入并发写;即便并发删除的广播+ // 晚于本广播到达,镜像最终也收敛到 deleted。+ let broadcastStatus = updated.status;+ if (p.status !== undefined) {+ const [currentRow] = await db+ .select({ status: sessions.status })+ .from(sessions)+ .where(eq(sessions.id, sid))+ .limit(1);+ if (currentRow) broadcastStatus = currentRow.status;+ }+ const broadcastPatch =+ p.pinnedAt === undefined && p.status === undefined+ ? p+ : {+ ...p,+ ...(p.pinnedAt !== undefined ? { pinnedAt: updated.pinnedAt } : {}),+ ...(p.status !== undefined ? { status: broadcastStatus } : {}),+ ...(p.pinnedAt !== undefined && updated.pinnedAt === null ? { summary: null } : {}),+ ...(p.pinnedAt !== undefined && updated.pinnedAt !== null+ ? { status: broadcastStatus }+ : {}),+ };+ if (+ projectTargetChanged ||+ settingsChanged ||+ titleChanged ||+ statusChanged ||+ p.pinnedAt !== undefined+ ) {+ if (isOwnerScopeCurrent(ownerScope)) {+ broadcastSessionPatched(sid, broadcastPatch, ownerScope);+ }+ }+ // sidebar-card-mode: 会话被置顶那一刻补生成任务摘要(turn-done 路径只覆盖+ // "置顶后又跑过 turn"的会话)。动态 import 避免 localDb → maker-host 的静态+ // 模块环;fire-and-forget,模块内部自带置顶/节流守卫。+ if (p.pinnedAt !== undefined && updated.pinnedAt !== null) {+ void import('../../sessionTaskSummary.js').then((m) =>+ m.maybeGenerateSessionTaskSummary(sid, { force: true }),+ );+ }+ notifyAgentIslandSessionPatch(updated.id, {+ status: updated.status,+ title: updated.title,+ workingDir: updated.workingDir,+ workspaceKind: updated.workspaceKind,+ });+ scheduleWorktreeRecycleForStatusChange(sid, p.status, { ownerScope, mediaDb: db });+ notifyGhostSessionStatusChange(sid, p.status, updated.workingDir);+ cleanupSessionTerminalArtifacts(sid, p.status);+ compactTerminalSessionToolResults(dbClient, sid, p.status);+ return updated;+ };+ if (p.workingDir === undefined) return update();+ return withSessionRouteLock(sid, async () => {- const [binding] = await db.select({ remoteHostId: sessions.remoteHostId }).from(sessions).where(eq(sessions.id, sid)).limit(1);- const resource = !binding?.remoteHostId && typeof p.workingDir === 'string'- ? managedWorktreeRoot(p.workingDir) : null;++ const [binding] = await db++ .select({ remoteHostId: sessions.remoteHostId })++ .from(sessions)++ .where(eq(sessions.id, sid))++ .limit(1);++ const resource =++ !binding?.remoteHostId && typeof p.workingDir === 'string'++ ? managedWorktreeRoot(p.workingDir)++ : null;+ const resources = await readSessionWorktreeResources(db, sid);+ if (resource) resources.push(resource);+ return withWorktreeMutation(resources, update);});- scheduleWorktreeRecycleForStatusChange(sid, p.status, { ownerScope, mediaDb: db });- notifyGhostSessionStatusChange(sid, p.status, updated.workingDir);- removeHookAttachmentDir(sid, p.status);- return updated;});// 窄口径会话元数据编辑(status / title / pinnedAt)。专为 device-link 控制端**远程**@@@ -1605,27 -1955,18 +2018,33 @@@ export async function patchSessionMetaIconst setObj = sessionPatchToRow(patch, { bumpUpdatedAt: false });// 控制端远程改名走这条,与本机改名同口径(同样先记号后写库)。if (patch.title !== undefined) noteUserTitleWritten(sessionId);- const { updated, source } = await withStatusWriteLock(sessionId, patch.status, async () => {- const updated = await withStatusWriteLock(db, sessionId, patch.status, async () => {++ const { updated, source } = await withStatusWriteLock(db, sessionId, patch.status, async () => {+ if (patch.status !== undefined) await assertGenericSessionLifecycleAllowed(db, sessionId);await writeSessionPatch(db, sessionId, setObj, patch.status);const row = await selectSessionWithCount(db, sessionId);if (!row) throwIpcError('NOT_FOUND', 'Session 不存在');+ if (patch.pinnedAt !== undefined && row.pinnedAt == null) {+ await db.update(sessions).set({ summary: null }).where(eq(sessions.id, sessionId));+ row.summary = null;+ }+ cleanupSessionRuntimeForTerminalStatus(sessionId, patch.status);- return sessionToCamel(row);+ return { updated: sessionToCamel(row), source: row.source };});+ if (+ (patch.status === 'deleted' || patch.status === 'archived') &&+ updated.workspaceKind === 'project' &&+ updated.workingDir &&+ !updated.remoteHostId &&+ isRetainableProjectSessionSource(source)+ ) {+ const touched = await upsertRecentWorkdir(+ updated.workingDir,+ Date.now(),+ process.platform,+ dbClient,+ );+ if (touched) broadcastRecentWorkdirsChanged(updated.workingDir, ownerScope);+ }notifyAgentIslandSessionPatch(updated.id, {status: updated.status,title: updated.title,@@@ -1767,38 -2140,37 +2218,54 @@@ export async function setSessionsStatusif (sessionIds.length === 0) return [];const ownerScope = captureOwnerScope();const dbClient = getDbClient();- const applied = await withSessionRouteLocks(sessionIds, () =>- dbClient.tx('sessions.setStatus', { sessionIds, status }).catch((err) => {- const code = (err as { code?: string }).code;- const message = err instanceof Error ? err.message : String(err);- if (code === 'NOT_FOUND' || code === 'INVALID_PARAMS' || code === 'PRECONDITION_FAILED') {- throwIpcError(code, message);+ const applied = await withSessionRouteLocks(sessionIds, async () => {+ const resources: string[] = [];+ const perSession = new Map<string, string[]>();+ for (const id of sessionIds) {+ const paths = await readSessionWorktreeResources(dbClient.drizzle, id);+ perSession.set(id, paths);+ resources.push(...paths);+ }+ const physicalResources = await Promise.all([...new Set(resources)].map(physicalWorktreeKey));+ return withWorktreeMutation(resources, async () => {+ if (status === 'archived') {+ for (const id of sessionIds) await requestWorktreeRecycle(id, perSession.get(id));}- throw err;- }),- );+ const rows = await dbClient.tx('sessions.setStatus', { sessionIds, status }).catch((err) => {+ const code = (err as { code?: string }).code;+ const message = err instanceof Error ? err.message : String(err);+ if (code === 'NOT_FOUND' || code === 'INVALID_PARAMS' || code === 'PRECONDITION_FAILED') {+ throwIpcError(code, message);+ }+ throw err;- });- for (const item of rows) {- cleanupSessionRuntimeForTerminalStatus(item.sessionId, item.status);- }- for (const resource of physicalResources) notifyWorktreeRecycleOpportunity(resource);- return rows;++ });++ for (const item of rows) {++ cleanupSessionRuntimeForTerminalStatus(item.sessionId, item.status);++ }++ for (const resource of physicalResources) notifyWorktreeRecycleOpportunity(resource);++ return rows;+ });+ });+ for (const item of applied) {+ compactTerminalSessionToolResults(dbClient, item.sessionId, item.status);+ }+ if (status === 'archived') {+ const touchedAt = Date.now();+ const localProjectDirs = new Set(+ applied.flatMap((item) =>+ item.workspaceKind === 'project' &&+ item.workingDir &&+ !item.remoteHostId &&+ isRetainableProjectSessionSource(item.source)+ ? [item.workingDir]+ : [],+ ),+ );+ for (const workingDir of localProjectDirs) {- const touched = await upsertRecentWorkdir(- workingDir,- touchedAt,- process.platform,- dbClient,- );++ const touched = await upsertRecentWorkdir(workingDir, touchedAt, process.platform, dbClient);+ if (touched) broadcastRecentWorkdirsChanged(workingDir, ownerScope);+ }+ }if (!isOwnerScopeCurrent(ownerScope))return applied.map((item) => ({sessionId: item.sessionId,@@@ -1829,6 -2201,69 +2296,69 @@@}));}+ const piSubagentCleanupTimers = new Map<string, NodeJS.Timeout>();+ const piSubagentCleanupEpoch = new Map<string, number>();+ /** Longer than the adapter's own close budget, so a normal close is never cut short. */+ const PI_SUBAGENT_CLEANUP_CLOSE_TIMEOUT_MS = 15_000;++ function piSubagentCleanupCurrentEpoch(sessionId: string): number {+ return piSubagentCleanupEpoch.get(sessionId) ?? 0;+ }++ function cancelDeletedPiSubagentCleanupImpl(sessionId: string): void {+ piSubagentCleanupEpoch.set(sessionId, piSubagentCleanupCurrentEpoch(sessionId) + 1);+ const timer = piSubagentCleanupTimers.get(sessionId);+ if (!timer) return;+ clearTimeout(timer);+ piSubagentCleanupTimers.delete(sessionId);+ }++ bindDeletedPiSubagentCleanupCancel(cancelDeletedPiSubagentCleanupImpl);++ /**+ * Detach Bot-owned tasks before the owning Profile is permanently removed.+ * Kept transcripts become ordinary archived tasks; discarded transcripts+ * become ordinary deleted tombstones so no inaccessible source=bot orphan is+ * left after the Bot FK graph is cascaded away.+ */+ export async function deleteBotProfileAndDetachSessionsInDb(+ botId: string,+ sessionIds: string[],+ keepTaskHistory: boolean,+ ): Promise<void> {+ const ids = [...new Set(sessionIds)];+ const ownerScope = captureOwnerScope();+ const db = getDbClient().drizzle;- const commitDeletion = () => commitBotProfileDeletion({- botId,- sessionIds: ids,- keepTaskHistory,- });- const committed = ids.length > 0- ? await withSessionRouteLocks(ids, commitDeletion)- : await commitDeletion();++ const commitDeletion = () =>++ commitBotProfileDeletion({++ botId,++ sessionIds: ids,++ keepTaskHistory,++ });++ const committed =++ ids.length > 0 ? await withSessionRouteLocks(ids, commitDeletion) : await commitDeletion();+ const status = committed.status;+ const committedSessionIds = [...new Set(committed.sessionIds)];++ for (const id of committedSessionIds) {+ notifyAgentIslandSessionPatch(id, { status });+ broadcastSessionPatched(id, { status, source: 'desktop' }, ownerScope);+ notifyGhostSessionStatusChange(id, status, null);+ removeHookAttachmentDir(id, status);+ if (status === 'deleted') {+ void imageCacheStore.removeSession(id).catch((error) => {+ log.warn('Bot task image cleanup failed', { sessionId: id, error: String(error) });+ });+ void removeWechatSessionAttachmentDir(id).catch((error) => {+ log.warn('Bot task attachment cleanup failed', { sessionId: id, error: String(error) });+ });+ void removeDeletedSessionMediaRefs(id, db).catch((error) => {+ log.warn('Bot task media cleanup failed', { sessionId: id, error: String(error) });+ });+ }+ }+ }+/*** hook 入站附件目录回收(fire-and-forget): deleted/archived 都是终态,* 文件在 turn 送出后即无用。所有把 session 置为终态的路径都应调用。@@@ -1854,6 -2289,262 +2384,270 @@@ function removeHookAttachmentDir(sessio});}+ /**+ * Can this parent task still start a durable Subagent?+ *+ * Only one thing can: the `cindy-subagent` extension, which exists solely+ * inside the parent PI process. `stopAndRemovePiSubagentRuns` finishes by+ * scanning for an empty run root and deleting it — so if the parent is still+ * alive, a launch entering after that scan recreates the root and spawns a+ * detached runner, on the deleted task's inherited provider credentials, with+ * the cleanup already reporting success and its retry timer discarded. The+ * publish-intent-first protocol makes the converse true: a launch that started+ * before the parent died has already written its `queued` status, so the scan+ * sees it and stops it.+ *+ * This function only proves the launcher in *this* process stopped. Other+ * supported instances share userData, so a parent PI elsewhere can still be+ * alive; the per-session tombstone written before the scan is what stops those+ * launches. Not the host-level launch fence: that one blocks *every* session+ * for the duration, and this is one deleted task's cleanup.+ *+ * `closeSession` is idempotent and is issued here rather than waited for+ * elsewhere: the worktree recycle path also closes the session, but the two are+ * unordered and its close is best-effort, so waiting on it could mean waiting+ * forever. It resolves only after `proc.close()` confirms the PI process exited+ * (adapter contract); if the close failed the session is left in `error`, which+ * `isSessionAlive` still reports as alive — so the recheck below stays+ * conservative by construction.+ */+ async function piSubagentLauncherProvenStopped(sessionId: string): Promise<boolean> {+ let maker: ReturnType<typeof import('../../maker-host/index.js').getMakerIfReady>;+ try {+ // Dynamic, like every other maker-host use here: localDb must not take a+ // static edge on it.+ const mh = await import('../../maker-host/index.js');+ maker = mh.getMakerIfReady();+ } catch (err) {+ // Unable to ask is not permission to proceed.+ log.warn('PI Subagent cleanup could not reach the Maker host', {+ sessionId,+ err: err instanceof Error ? err.message : String(err),+ });+ return false;+ }+ // Nothing loaded in *this* process. Another instance sharing userData may+ // still have the parent PI alive; the deleted-task tombstone (written before+ // this function is used as a scan gate) is what stops its launches. Returning+ // true here only means there is no local launcher left to close.+ if (!maker) return true;+ if (!maker.isSessionAlive(sessionId)) return true;+ const closing = maker.closeSession(sessionId).catch((err: unknown) => {+ log.warn('PI Subagent cleanup close of the deleted parent task failed', {+ sessionId,+ err: err instanceof Error ? err.message : String(err),+ });+ });+ // Bounded. `closeSession` has no deadline of its own, and this path used to+ // await nothing unbounded: a wedged close would otherwise park this attempt+ // forever, and with it the retry that is supposed to keep trying. Giving up+ // returns "not proven stopped", so the backoff re-enters — and `Session.close`+ // hands back the same in-flight promise, so no second close is issued.+ let deadline: NodeJS.Timeout | undefined;+ const closed = await Promise.race([+ closing.then(() => true),+ new Promise<boolean>((resolve) => {+ deadline = setTimeout(() => resolve(false), PI_SUBAGENT_CLEANUP_CLOSE_TIMEOUT_MS);+ deadline.unref?.();+ }),- ]).finally(() => { if (deadline) clearTimeout(deadline); });++ ]).finally(() => {++ if (deadline) clearTimeout(deadline);++ });+ if (!closed) {+ log.warn('PI Subagent cleanup timed out closing the deleted parent task', { sessionId });+ return false;+ }+ return !maker.isSessionAlive(sessionId);+ }++ function scheduleDeletedPiSubagentCleanup(sessionId: string, attempt = 0): void {+ if (piSubagentCleanupTimers.has(sessionId)) return;+ const epoch = piSubagentCleanupCurrentEpoch(sessionId);+ const marker = setTimeout(() => undefined, 0);+ marker.unref?.();+ piSubagentCleanupTimers.set(sessionId, marker);+ void (async () => {+ const agentHome = path.join(app.getPath('userData'), 'pi-agent-home');+ const superseded = (): boolean => piSubagentCleanupCurrentEpoch(sessionId) !== epoch;+ try {+ if (superseded()) return;+ // Tombstone first, before asking whether *this* process still has a+ // launcher. Dev, packaged and --passive instances share userData, so a+ // parent PI in another process can still spawn after our local Maker+ // reports the task unloaded. The in-Pi launcher reads this marker after+ // publishing queued and before spawn — same opposite-order protocol as+ // the launch fence. Without it, stopAndRemove deleting an empty root is+ // not a proof.+ try {+ await writePiSubagentDeletedTombstone(agentHome, sessionId);+ } catch (err) {+ log.warn('PI Subagent cleanup could not write the deleted-task tombstone', {+ sessionId,+ err: err instanceof Error ? err.message : String(err),+ });+ throw err;+ }+ if (superseded()) {+ await clearPiSubagentDeletedTombstone(agentHome, sessionId);+ return;+ }+ // Every attempt, not just the first: the parent may still have been alive+ // when an earlier one gave up, and this is the only thing standing+ // between the conclusive scan and a launch that outruns it.+ if (await piSubagentLauncherProvenStopped(sessionId)) {+ if (superseded()) {+ await clearPiSubagentDeletedTombstone(agentHome, sessionId);+ return;+ }+ const removed = await stopAndRemovePiSubagentRuns(piSubagentRunRoot(agentHome, sessionId));+ if (removed) {+ piSubagentCleanupTimers.delete(sessionId);+ return;+ }+ } else {+ log.warn('PI Subagent cleanup deferred: the deleted parent task is still running', {+ sessionId,+ attempt,+ });+ }+ } catch (err) {+ log.warn('PI Subagent cleanup attempt failed', {+ sessionId,+ err: err instanceof Error ? err.message : String(err),+ });+ }+ if (superseded()) return;- const delayMs = Math.min(60_000, 1_000 * (2 ** Math.min(attempt, 6)));++ const delayMs = Math.min(60_000, 1_000 * 2 ** Math.min(attempt, 6));+ const timer = setTimeout(() => {+ piSubagentCleanupTimers.delete(sessionId);+ scheduleDeletedPiSubagentCleanup(sessionId, attempt + 1);+ }, delayMs);+ timer.unref?.();+ piSubagentCleanupTimers.set(sessionId, timer);+ })();+ }++ export async function resumeDeletedPiSubagentCleanup(): Promise<void> {- const parentRoot = path.join(app.getPath('userData'), 'pi-agent-home', 'runtime', 'pi-subagent-runs');++ const parentRoot = path.join(++ app.getPath('userData'),++ 'pi-agent-home',++ 'runtime',++ 'pi-subagent-runs',++ );+ let idsFromDisk: string[] = [];+ try {+ const entries = await fs.readdir(parentRoot, { withFileTypes: true });+ idsFromDisk = entries+ .filter((entry) => entry.isDirectory() && entry.name && !/[\\/\0]/.test(entry.name))+ .map((entry) => entry.name);+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;+ }++ const db = getDbClient().drizzle;+ // Deleted PI parents must get a tombstone even when they never grew a run+ // root. Crash between the delete commit and the fire-and-forget write would+ // otherwise leave another shared-userData process free to launch later.+ const deletedPi = await db+ .select({ id: sessions.id })+ .from(sessions)+ .where(and(eq(sessions.status, 'deleted'), eq(sessions.agentKind, 'pi')));+- const diskDeleted = idsFromDisk.length === 0++ const diskDeleted =++ idsFromDisk.length === 0+ ? []+ : await db+ .select({ id: sessions.id })+ .from(sessions)+ .where(and(inArray(sessions.id, idsFromDisk), eq(sessions.status, 'deleted')));++ const ids = new Set<string>();+ for (const row of deletedPi) ids.add(row.id);+ for (const row of diskDeleted) ids.add(row.id);+ for (const id of ids) scheduleDeletedPiSubagentCleanup(id);+ }++ /**+ * Terminal task artifact cleanup. Archive only removes one-shot hook files;+ * delete additionally stops and removes detached PI Subagents owned by the+ * parent task. All status writers must pass through this helper.+ */+ function cleanupSessionTerminalArtifacts(sessionId: string, status: unknown): void {+ if (status !== 'deleted' && status !== 'archived') return;+ if (status === 'deleted') {+ void removeTurnChangeSetsForSession(sessionId).catch((err) => {+ log.warn('turn change-set cleanup failed', {+ sessionId,+ err: err instanceof Error ? err.message : String(err),+ });+ });+ scheduleDeletedPiSubagentCleanup(sessionId);+ }+ const attachRoot = path.join(app.getPath('userData'), 'hook-attachments');+ const attachDir = path.join(attachRoot, sessionId);+ if (!attachDir.startsWith(attachRoot + path.sep)) return;+ void fs.rm(attachDir, { recursive: true, force: true }).catch((err) => {+ log.warn('hook attachment dir cleanup failed', {+ sessionId,+ err: err instanceof Error ? err.message : String(err),+ });+ });+ }++ const pendingSessionListProjectionBackfill = new Map<string, SessionListProjectionBackfillItem>();+ let sessionListProjectionBackfillInFlight = false;++ /**+ * list 算出来的 preview / count 异步写回 sessions。+ * 必须合成一次 RPC:首屏 1000 行每人两条 drizzle UPDATE 会打爆 worker 队列+ * (inFlight=128 queued=512)。两次 list 交错时也先攒进同一批。+ */+ function scheduleSessionListProjectionBackfill(rows: readonly SessionListRow[]): void {+ for (const row of rows) {+ const sessionId = row.session.id;+ const item = pendingSessionListProjectionBackfill.get(sessionId) ?? { id: sessionId };+ if (row.session.listPreview == null && row.latestMessageExtract != null) {+ const preview = finalizePlainPreview(row.latestMessageExtract, row.latestMessageRole);+ if (preview != null) {+ item.preview = preview;+ item.role = row.latestMessageRole;+ }+ }+ if (row.session.listMessageCount == null) {+ item.count = row.messageCount;+ }+ if (item.preview !== undefined || item.count !== undefined) {+ pendingSessionListProjectionBackfill.set(sessionId, item);+ }+ }+ void drainSessionListProjectionBackfill();+ }++ async function drainSessionListProjectionBackfill(): Promise<void> {+ if (sessionListProjectionBackfillInFlight) return;+ if (pendingSessionListProjectionBackfill.size === 0) return;+ sessionListProjectionBackfillInFlight = true;+ try {+ while (pendingSessionListProjectionBackfill.size > 0) {+ const items = Array.from(pendingSessionListProjectionBackfill.values());+ pendingSessionListProjectionBackfill.clear();+ try {+ await persistSessionListProjectionBatch(items);+ } catch (err) {+ log.warn('session list projection backfill failed', {+ count: items.length,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }+ } finally {+ sessionListProjectionBackfillInFlight = false;+ if (pendingSessionListProjectionBackfill.size > 0) {+ void drainSessionListProjectionBackfill();+ }+ }+ }+/** {@link selectSessionListRows} 的行形状——与 sessionToCamel 的入参对齐。 */interface SessionListRow {session: typeof sessions.$inferSelect;diff --cc apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex 60b0aca4d9,714211e02b..c1adafa2d3--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@@ -75,14 -79,20 +79,26 @@@ export function tx(db: Database.Databasreturn sessionsRenameTitles(db, txArgs);case 'sessions.setStatus':return sessionsSetStatus(db, txArgs);+ case 'recentWorkdirs.mergeWindowsIdentity':+ return recentWorkdirsMergeWindowsIdentity(db, txArgs);+ case 'recentWorkdirs.removeWindowsIdentity':+ return recentWorkdirsRemoveWindowsIdentity(db, txArgs);+ case 'projectAliases.replaceIdentity':+ return projectAliasesReplaceIdentity(db, txArgs);+ case 'toolResults.compactSession':+ return compactSessionToolResults(db, txArgs);case 'session.agentSwitchFallback':return sessionAgentSwitchFallback(db, txArgs);+ case 'context.rebuild':+ return contextRebuild(db, txArgs);+ case 'message.insert':+ return messageInsert(db, txArgs);+ case 'message.updateContent':+ return messageUpdateContent(db, txArgs);+ case 'message.leaseMutate':+ return messageLeaseMutate(db, txArgs);+ case 'message.rewindUserAfterClear':+ return messageRewindUserAfterClear(db, txArgs);case 'message.delete':return messageDelete(db, txArgs);case 'im.deleteBindings':@@@ -130,90 -176,964 +182,1033 @@@}}+function recentWorkdirsMergeWindowsIdentity(db: Database.Database, args: unknown): void {+ const payload = asRecord(args, 'recentWorkdirs.mergeWindowsIdentity args');+ const path = expectString(payload.path, 'path');+ const lastUsedAt = expectNumber(payload.lastUsedAt, 'lastUsedAt');- const transaction = db.transaction(() => {++ db.transaction(() => {+ const matches = recentWorkdirWindowsIdentityRows(db, path);+ const representative = matches+ .slice()+ .sort((a, b) => b.lastUsedAt - a.lastUsedAt || a.rowid - b.rowid)[0];+ const representativePath = representative?.path ?? path;+ const newestTimestamp = Math.max(lastUsedAt, ...matches.map((row) => row.lastUsedAt));+ db.prepare(+ `INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?)+ ON CONFLICT(path) DO UPDATE SET+ last_used_at = MAX(recent_workdirs.last_used_at, excluded.last_used_at)`,+ ).run(representativePath, newestTimestamp);+ const removeVariant = db.prepare('DELETE FROM recent_workdirs WHERE path = ?');+ for (const row of matches) {+ if (row.path !== representativePath) removeVariant.run(row.path);+ }- });- transaction();++ })();+}+- function recentWorkdirsRemoveWindowsIdentity(- db: Database.Database,- args: unknown,- ): { changes: number } {++function recentWorkdirsRemoveWindowsIdentity(db: Database.Database, args: unknown): { changes: number } {+ const payload = asRecord(args, 'recentWorkdirs.removeWindowsIdentity args');+ const path = expectString(payload.path, 'path');- const transaction = db.transaction(() => {++ return db.transaction(() => {+ const matches = recentWorkdirWindowsIdentityRows(db, path);+ const removeVariant = db.prepare('DELETE FROM recent_workdirs WHERE path = ?');+ let changes = 0;+ for (const row of matches) changes += removeVariant.run(row.path).changes;+ return { changes };- });- return transaction();++ })();+}++function recentWorkdirWindowsIdentityRows(+ db: Database.Database,+ path: string,+): Array<{ rowid: number; path: string; lastUsedAt: number }> {+ const identity = path.toLowerCase();+ const rows = db+ .prepare('SELECT rowid, path, last_used_at AS lastUsedAt FROM recent_workdirs')+ .all() as Array<{ rowid: number; path: string; lastUsedAt: number }>;+ return rows.filter((row) => row.path.toLowerCase() === identity);+}++function projectAliasesReplaceIdentity(+ db: Database.Database,+ args: unknown,+): { projectKey: string; alias: string; updatedAt: number } | null {+ const payload = asRecord(args, 'projectAliases.replaceIdentity args');+ const projectKey = expectString(payload.projectKey, 'projectKey');+ const comparisonKey = expectString(payload.comparisonKey, 'comparisonKey');- if (typeof payload.foldCase !== 'boolean') {- throw invalidArgs('foldCase must be a boolean');- }++ if (typeof payload.foldCase !== 'boolean') throw invalidArgs('foldCase must be a boolean');+ const alias = nullableString(payload.alias);+ const updatedAt = expectNumber(payload.updatedAt, 'updatedAt');+ return db.transaction(() => {- const rows = db- .prepare('SELECT project_key AS projectKey FROM project_aliases')- .all() as Array<{- projectKey: string;- }>;++ const rows = db.prepare('SELECT project_key AS projectKey FROM project_aliases').all() as Array<{ projectKey: string }>;+ const removeAlias = db.prepare('DELETE FROM project_aliases WHERE project_key = ?');+ for (const row of rows) {+ const identity = payload.foldCase ? row.projectKey.toLowerCase() : row.projectKey;+ if (identity === comparisonKey) removeAlias.run(row.projectKey);+ }+ if (alias == null) return null;- db.prepare('INSERT INTO project_aliases (project_key, alias, updated_at) VALUES (?, ?, ?)').run(- projectKey,- alias,- updatedAt,- );++ db.prepare('INSERT INTO project_aliases (project_key, alias, updated_at) VALUES (?, ?, ?)').run(projectKey, alias, updatedAt);+ return { projectKey, alias, updatedAt };+ })();+}++ function botsCreateProfile(db: Database.Database, args: unknown): void {+ const p = asRecord(args, 'bots.createProfile args');+ const id = expectString(p.id, 'id');+ const now = expectNumber(p.now, 'now');+ db.transaction(() => {+ const config = JSON.parse(expectString(p.capabilitiesJson, 'capabilitiesJson'));+ const rows = db.prepare(`SELECT p.id, p.display_name AS name, v.capabilities_json AS config, v.identity_source AS identity+ FROM bot_profiles p JOIN bot_profile_versions v ON v.bot_id = p.id AND v.version = p.current_version+ WHERE p.status != 'archived'`).all() as Array<{ id: string; name: string; config: string; identity: string }>;+ if (rows.some(row => normalizeBotName(row.name) === normalizeBotName(expectString(p.displayName, 'displayName'))) ||+ (config.templateId === 'cindy' && rows.some(row => JSON.parse(row.config).templateId === 'cindy' || inferBotTemplatePresetId(row.identity) === 'cindy'))) {+ throw Object.assign(new Error('A matching companion already exists'), { code: 'ALREADY_EXISTS' });+ }+ db.prepare(`INSERT INTO bot_profiles+ (id, display_name, description, avatar, avatar_color, status, current_version,+ canonical_session_id, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, 'active', 1, NULL, ?, ?)`)+ .run(id, expectString(p.displayName, 'displayName'), expectString(p.description, 'description'),+ expectString(p.avatar, 'avatar'), expectString(p.avatarColor, 'avatarColor'), now, now);+ db.prepare(`INSERT INTO bot_profile_versions+ (id, bot_id, version, identity_source, capabilities_json, created_at)+ VALUES (?, ?, 1, ?, ?, ?)`)+ .run(`${id}:v1`, id, expectString(p.identitySource, 'identitySource'),+ expectString(p.capabilitiesJson, 'capabilitiesJson'), now);+ if (p.botAvatarRef !== undefined) {+ const ref = asRecord(p.botAvatarRef, 'botAvatarRef');+ const hash = expectString(ref.hash, 'botAvatarRef.hash');+ if (!/^[0-9a-f]{64}$/.test(hash)) throw new Error('botAvatarRef.hash is invalid');+ db.prepare(`INSERT INTO media_refs+ (id, hash, ref_kind, ref_id, origin_kind, created_at)+ VALUES (?, ?, 'bot-avatar', ?, 'user', ?)`)+ .run(expectString(ref.id, 'botAvatarRef.id'), hash, id, expectNumber(ref.createdAt, 'botAvatarRef.createdAt'));+ }+ db.prepare(`INSERT INTO bot_lifecycle_events+ (id, bot_id, session_id, event_type, payload_json, created_at)+ VALUES (?, ?, NULL, 'created', '{}', ?)`)+ .run(`${id}:created:${now}`, id, now);+ })();+ }++ function botsUpdateProfile(db: Database.Database, args: unknown): { currentVersion: number } {+ const p = asRecord(args, 'bots.updateProfile args');+ const id = expectString(p.id, 'id');+ const expectedVersion = expectNumber(p.expectedCurrentVersion, 'expectedCurrentVersion');+ const now = expectNumber(p.now, 'now');+ const avatarRef = p.botAvatarRef === undefined+ ? null+ : asRecord(p.botAvatarRef, 'botAvatarRef');+ const clearAvatarRefs = p.clearBotAvatarRefs === undefined+ ? false+ : p.clearBotAvatarRefs === true;+ if (p.clearBotAvatarRefs !== undefined && typeof p.clearBotAvatarRefs !== 'boolean') {+ throw new Error('clearBotAvatarRefs must be a boolean');+ }+ if (avatarRef && p.avatar === undefined) {+ throw new Error('botAvatarRef requires an avatar address');+ }+ return db.transaction(() => {+ const current = db.prepare('SELECT current_version AS currentVersion, display_name AS displayName, avatar FROM bot_profiles WHERE id = ?')+ .get(id) as { currentVersion: number; displayName: string; avatar: string } | undefined;+ if (!current) throw Object.assign(new Error('Bot 不存在'), { code: 'NOT_FOUND' });+ if (current.currentVersion !== expectedVersion) {+ throw Object.assign(new Error('Bot Profile 已被另一处更新,请刷新后重试'), { code: 'PRECONDITION_FAILED' });+ }+ if (p.expectedAvatar !== undefined && current.avatar !== expectString(p.expectedAvatar, 'expectedAvatar')) {+ throw Object.assign(new Error('Teammate avatar changed during update'), { code: 'PRECONDITION_FAILED' });+ }+ if (p.displayName !== undefined && normalizeBotName(expectString(p.displayName, 'displayName')) !== normalizeBotName(current.displayName)) {+ const name = normalizeBotName(expectString(p.displayName, 'displayName'));+ const others = db.prepare("SELECT display_name AS name FROM bot_profiles WHERE id != ? AND status != 'archived'").all(id) as Array<{ name: string }>;+ if (others.some(row => normalizeBotName(row.name) === name)) throw Object.assign(new Error('A companion with this name already exists'), { code: 'ALREADY_EXISTS' });+ }+ if (p.preserveUpdatedAt !== undefined && typeof p.preserveUpdatedAt !== 'boolean') {+ throw new Error('preserveUpdatedAt must be a boolean');+ }+ const fields = p.preserveUpdatedAt === true ? ['updated_at = updated_at'] : ['updated_at = ?'];+ const values: unknown[] = p.preserveUpdatedAt === true ? [] : [now];+ for (const [key, column] of [+ ['displayName', 'display_name'], ['description', 'description'], ['avatar', 'avatar'],+ ['avatarColor', 'avatar_color'], ['status', 'status'],+ ] as const) {+ if (p[key] !== undefined) {+ fields.push(`${column} = ?`);+ values.push(expectString(p[key], key));+ }+ }+ for (const [key, column] of [+ ['hiddenAt', 'hidden_at'], ['pinnedAt', 'pinned_at'],+ ] as const) {+ if (p[key] !== undefined) {+ fields.push(`${column} = ?`);+ values.push(p[key] === null ? null : expectNumber(p[key], key));+ }+ }+ const changed = p.profileContentChanged === true;+ const nextVersion = changed ? expectedVersion + 1 : expectedVersion;+ if (changed) {+ fields.push('current_version = ?');+ values.push(nextVersion);+ }+ values.push(id);+ db.prepare(`UPDATE bot_profiles SET ${fields.join(', ')} WHERE id = ?`).run(...values);+ if (avatarRef) {+ const refId = expectString(avatarRef.id, 'botAvatarRef.id');+ const hash = expectString(avatarRef.hash, 'botAvatarRef.hash');+ if (!/^[0-9a-f]{64}$/.test(hash)) throw new Error('botAvatarRef.hash is invalid');+ db.prepare(`INSERT INTO media_refs+ (id, hash, ref_kind, ref_id, origin_kind, created_at)+ VALUES (?, ?, 'bot-avatar', ?, 'user', ?)`)+ .run(refId, hash, id, expectNumber(avatarRef.createdAt, 'botAvatarRef.createdAt'));+ db.prepare("DELETE FROM media_refs WHERE ref_kind = 'bot-avatar' AND ref_id = ? AND id <> ?")+ .run(id, refId);+ } else if (clearAvatarRefs) {+ db.prepare("DELETE FROM media_refs WHERE ref_kind = 'bot-avatar' AND ref_id = ?").run(id);+ }+ if (changed) {+ db.prepare(`INSERT INTO bot_profile_versions+ (id, bot_id, version, identity_source, capabilities_json, created_at)+ VALUES (?, ?, ?, ?, ?, ?)`)+ .run(`${id}:v${nextVersion}`, id, nextVersion, expectString(p.identitySource, 'identitySource'),+ expectString(p.capabilitiesJson, 'capabilitiesJson'), now);+ // Hermes capability epoch: the permanent canonical Chat follows the+ // latest Profile on its next runtime bootstrap. Route/group/worker links+ // remain pinned to the version they were created with.+ db.prepare(`UPDATE bot_session_links SET profile_version = ?+ WHERE bot_id = ? AND role = 'canonical' AND archived_at IS NULL`)+ .run(nextVersion, id);+ }+ return { currentVersion: nextVersion };+ })();+ }++ const BOT_DURABLE_ATTENTION_REASONS = new Set([+ 'agent_blocked',+ 'missing_config',+ 'provider_auth_or_access',+ 'provider_quota_limit',+ ]);++ /**+ * Profile-level attention follows a single monotonic clock. A delayed success+ * or failure from an older Session must never overwrite a newer observation.+ */+ function botsUpdateAttention(+ db: Database.Database,+ args: unknown,+ ): { changed: boolean } {+ const p = asRecord(args, 'bots.updateAttention args');+ const botId = expectString(p.botId, 'botId');+ const observedAt = expectNumber(p.observedAt, 'observedAt');+ const reason = p.reason === null ? null : expectString(p.reason, 'reason');+ if (reason !== null && !BOT_DURABLE_ATTENTION_REASONS.has(reason)) {+ throw Object.assign(new Error('unsupported Bot attention reason'), { code: 'INVALID_PARAMS' });+ }+ const result = reason === null+ ? db.prepare(`UPDATE bot_profiles+ SET attention_reason = NULL, attention_at = NULL+ WHERE id = ? AND attention_at IS NOT NULL AND attention_at <= ?`)+ .run(botId, observedAt)+ : db.prepare(`UPDATE bot_profiles+ SET attention_reason = ?, attention_at = ?+ WHERE id = ? AND (attention_at IS NULL OR attention_at <= ?)`)+ .run(reason, observedAt, botId, observedAt);+ return { changed: result.changes > 0 };+ }++ function botsReplaceCanonicalSession(+ db: Database.Database,+ args: unknown,+ ): {+ created: boolean;+ canonicalSessionId: string | null;+ archivedCanonicalSessionId: string | null;+ } {+ const p = asRecord(args, 'bots.replaceCanonicalSession args');+ const botId = expectString(p.botId, 'botId');+ const expectedCanonical =+ p.expectedCanonicalSessionId === null+ ? null+ : expectString(p.expectedCanonicalSessionId, 'expectedCanonicalSessionId');+ const compatibilityMissingCanonicalSessionId =+ p.compatibilityMissingCanonicalSessionId == null+ ? null+ : expectString(+ p.compatibilityMissingCanonicalSessionId,+ 'compatibilityMissingCanonicalSessionId',+ );+ const expectedVersion = expectNumber(p.expectedProfileVersion, 'expectedProfileVersion');+ const s = asRecord(p.session, 'session');+ const now = expectNumber(p.now, 'now');+ return db.transaction(() => {+ const bot = db+ .prepare(+ `SELECT status, current_version AS currentVersion+ FROM bot_profiles WHERE id = ?`,+ )+ .get(botId) as { status: string; currentVersion: number } | undefined;+ if (!bot) throw Object.assign(new Error('Bot 不存在'), { code: 'NOT_FOUND' });+ if (bot.status !== 'active')+ throw Object.assign(new Error('Bot 已暂停,不能创建新的任务'), {+ code: 'PRECONDITION_FAILED',+ });+ const canonicalLink = db+ .prepare(+ `SELECT session_id AS sessionId FROM bot_session_links+ WHERE bot_id = ? AND role = 'canonical'`,+ )+ .get(botId) as { sessionId: string } | undefined;+ // The compatibility mirror is never runtime authority. Legacy rows are+ // promoted into bot_session_links by bots.reconcileCanonicalLink before+ // this transaction is called; without a link we fail the caller's CAS.+ const canonicalSessionId = canonicalLink?.sessionId ?? null;+ if (canonicalSessionId !== expectedCanonical) {+ return { created: false, canonicalSessionId, archivedCanonicalSessionId: null };+ }+ if (bot.currentVersion !== expectedVersion) {+ throw Object.assign(new Error('Bot Profile 已更新,请刷新后重试'), {+ code: 'PRECONDITION_FAILED',+ });+ }+ const version = db+ .prepare('SELECT version FROM bot_profile_versions WHERE bot_id = ? AND version = ?')+ .get(botId, bot.currentVersion) as { version: number } | undefined;+ if (!version)+ throw Object.assign(new Error('Bot 当前 Profile 版本不存在'), {+ code: 'PRECONDITION_FAILED',+ });+ const sessionId = expectString(s.id, 'session.id');+ // A healthy canonical task is permanent. Long conversations compact in+ // place; replacement is reserved for a missing/deleted task.+ if (canonicalSessionId) {+ const previous = db+ .prepare('SELECT status FROM sessions WHERE id = ?')+ .get(canonicalSessionId) as { status: string } | undefined;+ if (previous && previous.status !== 'deleted') {+ return { created: false, canonicalSessionId, archivedCanonicalSessionId: null };+ }+ }+ db.prepare(+ `INSERT INTO sessions+ (id, title, working_dir, workspace_kind, model, effort, permission_mode, status,+ sdk_session_id, total_token_usage, total_cost_usd, context_tokens, context_window,+ fast_mode, plan_mode_enabled, cleared_at, pinned_at, user_send_at, agent_kind,+ orca_role, parent_session_id, forked_at_message_id, worktree_path, extra_dirs,+ remote_host_id, provider_id, source, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, 'active', NULL, 0, 0, 0, 0, ?, 0, NULL, NULL, NULL,+ ?, NULL, NULL, NULL, NULL, ?, ?, ?, ?, ?, ?)`,+ ).run(+ sessionId,+ expectString(s.title, 'session.title'),+ nullableString(s.workingDir),+ expectString(s.workspaceKind, 'session.workspaceKind'),+ expectString(s.model, 'session.model'),+ expectString(s.effort, 'session.effort'),+ expectString(s.permissionMode, 'session.permissionMode'),+ s.fastMode === true ? 1 : 0,+ expectString(s.agentKind, 'session.agentKind'),+ expectString(s.extraDirs, 'session.extraDirs'),+ nullableString(s.remoteHostId),+ nullableString(s.providerId),+ expectString(s.source, 'session.source'),+ expectNumber(s.createdAt, 'session.createdAt'),+ expectNumber(s.updatedAt, 'session.updatedAt'),+ );+ let archived: string | null = null;+ let missingCanonicalSessionId: string | null = compatibilityMissingCanonicalSessionId;+ if (canonicalSessionId) {+ const previous = db+ .prepare('SELECT source, status FROM sessions WHERE id = ?')+ .get(canonicalSessionId) as { source: string; status: string } | undefined;+ if (!previous) missingCanonicalSessionId = canonicalSessionId;+ db.prepare(+ `UPDATE bot_session_links SET role = 'history', archived_at = ?+ WHERE bot_id = ? AND session_id = ? AND role = 'canonical'`,+ ).run(now, botId, canonicalSessionId);+ if (previous?.source === 'bot') {+ if (previous.status !== 'deleted') {+ db.prepare("UPDATE sessions SET status = 'archived', updated_at = ? WHERE id = ?").run(+ now,+ canonicalSessionId,+ );+ }+ // Even a soft-deleted canonical Session can own queued descendants;+ // hand them the same terminal cleanup path during recovery.+ archived = canonicalSessionId;+ }+ }+ db.prepare(+ `INSERT INTO bot_session_links+ (id, bot_id, session_id, profile_version, role, route_key, created_at, archived_at)+ VALUES (?, ?, ?, ?, 'canonical', NULL, ?, NULL)`,+ ).run(`${botId}:${sessionId}`, botId, sessionId, version.version, now);+ db.prepare('UPDATE bot_profiles SET canonical_session_id = ?, updated_at = ? WHERE id = ?').run(+ sessionId,+ now,+ botId,+ );+ const canonicalEventType = canonicalSessionId || missingCanonicalSessionId+ ? 'canonical-recovered'+ : 'canonical-created';+ db.prepare(+ `INSERT INTO bot_lifecycle_events+ (id, bot_id, session_id, event_type, payload_json, created_at) VALUES (?, ?, ?, ?, ?, ?)`,+ ).run(+ `${botId}:${canonicalEventType}:${sessionId}`,+ botId,+ sessionId,+ canonicalEventType,+ JSON.stringify({+ previousCanonicalSessionId: canonicalSessionId,+ missingCanonicalSessionId,+ profileVersion: version.version,+ }),+ now,+ );+ return { created: true, canonicalSessionId: sessionId, archivedCanonicalSessionId: archived };+ })();+ }++ function botsReconcileCanonicalLink(+ db: Database.Database,+ args: unknown,+ ): {+ status: 'unchanged' | 'repaired-mirror' | 'migrated' | 'missing-pointer' | 'missing-session' | 'conflict';+ canonicalSessionId: string | null;+ } {+ const p = asRecord(args, 'bots.reconcileCanonicalLink args');+ const botId = expectString(p.botId, 'botId');+ const now = expectNumber(p.now, 'now');+ return db.transaction(() => {+ const bot = db.prepare(`SELECT canonical_session_id AS canonicalSessionId,+ current_version AS currentVersion FROM bot_profiles WHERE id = ?`).get(botId) as+ | { canonicalSessionId: string | null; currentVersion: number } | undefined;+ if (!bot) throw Object.assign(new Error('Bot 不存在'), { code: 'NOT_FOUND' });++ const links = db.prepare(`SELECT id, session_id AS sessionId, profile_version AS profileVersion+ FROM bot_session_links WHERE bot_id = ? AND role = 'canonical'`).all(botId) as Array<{+ id: string;+ sessionId: string;+ profileVersion: number;+ }>;+ if (links.length > 1) {+ throw Object.assign(new Error('Bot 存在多个 canonical link,拒绝自动选择'), {+ code: 'PRECONDITION_FAILED',+ });+ }++ const authoritative = links[0]?.sessionId ?? null;+ if (authoritative) {+ const session = db.prepare('SELECT status FROM sessions WHERE id = ?').get(authoritative) as+ | { status: string } | undefined;+ if (!session || session.status === 'deleted') {+ return { status: 'missing-session' as const, canonicalSessionId: null };+ }+ if (bot.canonicalSessionId === authoritative) {+ return { status: 'unchanged' as const, canonicalSessionId: authoritative };+ }+ db.prepare('UPDATE bot_profiles SET canonical_session_id = ?, updated_at = ? WHERE id = ?')+ .run(authoritative, now, botId);+ db.prepare(`INSERT INTO bot_lifecycle_events+ (id, bot_id, session_id, event_type, payload_json, created_at)+ VALUES (?, ?, ?, 'canonical-mirror-repaired', ?, ?)`).run(+ `${botId}:canonical-mirror-repaired:${authoritative}:${now}`,+ botId,+ authoritative,+ JSON.stringify({ previousCanonicalSessionId: bot.canonicalSessionId }),+ now,+ );+ return { status: 'repaired-mirror' as const, canonicalSessionId: authoritative };+ }++ if (!bot.canonicalSessionId) {+ return { status: 'missing-pointer' as const, canonicalSessionId: null };+ }++ const legacySession = db.prepare(`SELECT source, status FROM sessions WHERE id = ?`)+ .get(bot.canonicalSessionId) as { source: string; status: string } | undefined;+ if (!legacySession || legacySession.status === 'deleted') {+ return { status: 'missing-session' as const, canonicalSessionId: null };+ }+ if (legacySession.source !== 'bot') {+ return { status: 'conflict' as const, canonicalSessionId: null };+ }+ const existingLink = db.prepare(`SELECT bot_id AS botId, role FROM bot_session_links+ WHERE session_id = ?`).get(bot.canonicalSessionId) as+ | { botId: string; role: string } | undefined;+ if (existingLink) {+ return { status: 'conflict' as const, canonicalSessionId: null };+ }++ db.prepare(`INSERT INTO bot_session_links+ (id, bot_id, session_id, profile_version, role, route_key, created_at, archived_at)+ VALUES (?, ?, ?, ?, 'canonical', NULL, ?, NULL)`).run(+ `${botId}:${bot.canonicalSessionId}`,+ botId,+ bot.canonicalSessionId,+ bot.currentVersion,+ now,+ );+ db.prepare(`INSERT INTO bot_lifecycle_events+ (id, bot_id, session_id, event_type, payload_json, created_at)+ VALUES (?, ?, ?, 'canonical-migrated', ?, ?)`).run(+ `${botId}:canonical-migrated:${bot.canonicalSessionId}:${now}`,+ botId,+ bot.canonicalSessionId,+ JSON.stringify({ profileVersion: bot.currentVersion }),+ now,+ );+ return { status: 'migrated' as const, canonicalSessionId: bot.canonicalSessionId };+ })();+ }++ function botsPrepareRuntime(db: Database.Database, args: unknown): void {+ const p = asRecord(args, 'bots.prepareRuntime args');+ const s = asRecord(p.snapshot, 'snapshot');+ const preparedAt = expectNumber(s.preparedAt, 'snapshot.preparedAt');+ db.transaction(() => {+ db.prepare(`INSERT INTO bot_runtime_snapshots+ (id, bot_id, session_id, profile_version, agent_kind, working_dir, memory_scope_key,+ configured_json, resolved_json, status, prepared_at, applied_at, failed_at, failure_json)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'prepared', ?, NULL, NULL, NULL)`)+ .run(expectString(s.id, 'snapshot.id'), expectString(s.botId, 'snapshot.botId'),+ expectString(s.sessionId, 'snapshot.sessionId'), expectNumber(s.profileVersion, 'snapshot.profileVersion'),+ expectString(s.agentKind, 'snapshot.agentKind'), expectString(s.workingDir, 'snapshot.workingDir'),+ nullableString(s.memoryScopeKey), expectString(s.configuredJson, 'snapshot.configuredJson'),+ expectString(s.resolvedJson, 'snapshot.resolvedJson'), preparedAt);+ db.prepare(`INSERT INTO bot_lifecycle_events+ (id, bot_id, session_id, event_type, payload_json, created_at)+ VALUES (?, ?, ?, 'runtime-prepared', ?, ?)`)+ .run(expectString(p.eventId, 'eventId'), expectString(s.botId, 'snapshot.botId'),+ expectString(s.sessionId, 'snapshot.sessionId'), expectString(p.eventPayloadJson, 'eventPayloadJson'), preparedAt);+ })();+ }++ function botsFinishRuntime(db: Database.Database, args: unknown): boolean {+ const p = asRecord(args, 'bots.finishRuntime args');+ const status = expectString(p.status, 'status');+ const finishedAt = expectNumber(p.finishedAt, 'finishedAt');+ return db.transaction(() => {+ const write = status === 'failed'+ ? db.prepare(`UPDATE bot_runtime_snapshots SET status = 'failed', applied_at = NULL,+ failed_at = ?, failure_json = ? WHERE id = ? AND status = 'prepared'`)+ .run(finishedAt, nullableString(p.failureJson), expectString(p.snapshotId, 'snapshotId'))+ : db.prepare(`UPDATE bot_runtime_snapshots SET status = ?, applied_at = ?,+ failed_at = NULL, failure_json = NULL WHERE id = ? AND status = 'prepared'`)+ .run(status, finishedAt, expectString(p.snapshotId, 'snapshotId'));+ if (write.changes !== 1) return false;+ db.prepare(`INSERT INTO bot_lifecycle_events+ (id, bot_id, session_id, event_type, payload_json, created_at) VALUES (?, ?, ?, ?, ?, ?)`)+ .run(expectString(p.eventId, 'eventId'), expectString(p.botId, 'botId'),+ expectString(p.sessionId, 'sessionId'), expectString(p.eventType, 'eventType'),+ expectString(p.eventPayloadJson, 'eventPayloadJson'), finishedAt);+ return true;+ })();+ }++++ function insertBotSession(db: Database.Database, s: Record<string, unknown>): void {+ db.prepare(`INSERT INTO sessions+ (id, title, working_dir, workspace_kind, model, effort, permission_mode, status,+ sdk_session_id, total_token_usage, total_cost_usd, context_tokens, context_window,+ fast_mode, plan_mode_enabled, cleared_at, pinned_at, user_send_at, agent_kind,+ orca_role, parent_session_id, forked_at_message_id, worktree_path, extra_dirs,+ remote_host_id, provider_id, source, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, 'active', NULL, 0, 0, 0, 0, ?, 0, NULL, NULL, NULL,+ ?, NULL, ?, NULL, NULL, ?, ?, ?, ?, ?, ?)`)+ .run(expectString(s.id, 'session.id'), expectString(s.title, 'session.title'),+ nullableString(s.workingDir), expectString(s.workspaceKind, 'session.workspaceKind'),+ expectString(s.model, 'session.model'), expectString(s.effort, 'session.effort'),+ expectString(s.permissionMode, 'session.permissionMode'), s.fastMode === true ? 1 : 0,+ expectString(s.agentKind, 'session.agentKind'),+ nullableString(s.parentSessionId),+ expectString(s.extraDirs, 'session.extraDirs'), nullableString(s.remoteHostId), nullableString(s.providerId),+ expectString(s.source, 'session.source'), expectNumber(s.createdAt, 'session.createdAt'),+ expectNumber(s.updatedAt, 'session.updatedAt'));+ }++ function botsFinishDelegation(+ db: Database.Database,+ args: unknown,+ ): { id: string; parentSessionId: string | null; childSessionId: string | null; status: string } | null {+ const p = asRecord(args, 'bots.finishDelegation args');+ return db.transaction(() => {+ const values: unknown[] = [+ expectString(p.status, 'status'), nullableString(p.resultSummary),+ expectString(p.outputArtifactsJson, 'outputArtifactsJson'), nullableString(p.lastError),+ ];+ const tokenSet = p.tokensUsed === undefined ? '' : ', tokens_used = ?';+ if (p.tokensUsed !== undefined) values.push(expectNumber(p.tokensUsed, 'tokensUsed'));+ const completedAt = expectNumber(p.completedAt, 'completedAt');+ values.push(completedAt, completedAt, expectString(p.delegationId, 'delegationId'));+ const row = db.prepare(`UPDATE bot_delegations SET status = ?, result_summary = ?, output_artifacts_json = ?, last_error = ?+ ${tokenSet}, pending_interaction_json = NULL, completed_at = ?, completion_delivered_at = NULL, updated_at = ?+ WHERE id = ? AND status IN ('queued','running','waiting')+ RETURNING id, parent_session_id AS parentSessionId, child_session_id AS childSessionId, status`)+ .get(...values) as+ | { id: string; parentSessionId: string | null; childSessionId: string | null; status: string }+ | undefined;+ if (!row) return null;+ if (row.childSessionId) {+ // The delegation terminal transition owns its child task's terminal+ // archive: `sessions.setStatus` refuses `source = 'bot'` rows on purpose+ // (generic UI archive must not bypass Bot lifecycle bookkeeping), so the+ // archive has to happen in this very transaction. Doing it anywhere else+ // (a follow-up generic write that can also be swallowed) leaves the+ // child task `active` forever and the guardian reports a supervision+ // anomaly (PR #2829 QA).+ db.prepare(`UPDATE sessions SET status = 'archived', updated_at = ?+ WHERE id = ? AND status = 'active'`)+ .run(completedAt, row.childSessionId);+ db.prepare(`UPDATE bot_session_links SET role = 'history',+ route_key = NULL, archived_at = ? WHERE session_id = ?`)+ .run(completedAt, row.childSessionId);+ }+ return row;+ })();+ }++ function botsReparentDelegations(+ db: Database.Database,+ args: unknown,+ ): { delegationIds: string[] } {+ const p = asRecord(args, 'bots.reparentDelegations args');+ const botId = expectString(p.botId, 'botId');+ const previousParentSessionId = expectString(p.previousParentSessionId, 'previousParentSessionId');+ const nextParentSessionId = expectString(p.nextParentSessionId, 'nextParentSessionId');+ const at = expectNumber(p.now, 'now');+ return db.transaction(() => {+ const rows = db.prepare(`SELECT id, child_session_id AS childSessionId+ FROM bot_delegations+ WHERE requesting_bot_id = ? AND parent_session_id = ?+ AND target_bot_id IS NULL`)+ .all(botId, previousParentSessionId) as Array<{+ id: string;+ childSessionId: string | null;+ }>;+ if (rows.length === 0) return { delegationIds: [] };+ db.prepare(`UPDATE bot_delegations SET parent_session_id = ?, updated_at = ?+ WHERE requesting_bot_id = ? AND parent_session_id = ?+ AND target_bot_id IS NULL`)+ .run(nextParentSessionId, at, botId, previousParentSessionId);+ const updateChild = db.prepare(`UPDATE sessions SET parent_session_id = ?, updated_at = ?+ WHERE id = ? AND status <> 'deleted'`);+ for (const row of rows) {+ if (row.childSessionId) updateChild.run(nextParentSessionId, at, row.childSessionId);+ }+ return { delegationIds: rows.map((row) => row.id) };+ })();+ }++ function botsCreateDelegation(db: Database.Database, args: unknown): void {+ const p = asRecord(args, 'bots.createDelegation args');+ const d = asRecord(p.delegation, 'delegation');+ const requestingBotId = expectString(d.requestingBotId, 'delegation.requestingBotId');+ const maxActiveChildren = expectNumber(p.maxActiveChildren, 'maxActiveChildren');+ const createdAt = expectNumber(d.createdAt, 'delegation.createdAt');+ db.transaction(() => {+ const count = db.prepare(`SELECT COUNT(*) AS count FROM bot_delegations+ WHERE requesting_bot_id = ? AND status IN ('queued','running','waiting')`)+ .get(requestingBotId) as { count: number };+ if (count.count >= maxActiveChildren) throw new Error('BOT_DELEGATION_CONCURRENCY_LIMIT');+ // null = 委派给一条普通 Cindy 任务(非 Bot),不建 bot_session_links 行。+ const targetBotId = nullableString(d.targetBotId);+ const targetProfileVersion = d.targetProfileVersion === null || d.targetProfileVersion === undefined+ ? null+ : expectNumber(d.targetProfileVersion, 'delegation.targetProfileVersion');+ const s = asRecord(p.session, 'session');+ insertBotSession(db, s);+ const childSessionId = expectString(d.childSessionId, 'delegation.childSessionId');+ const delegationId = expectString(d.id, 'delegation.id');+ if (targetBotId) {+ db.prepare(`INSERT INTO bot_session_links+ (id, bot_id, session_id, profile_version, role, route_key, created_at, archived_at)+ VALUES (?, ?, ?, ?, 'delegation', ?, ?, NULL)`)+ .run(`${targetBotId}:${childSessionId}`, targetBotId, childSessionId,+ targetProfileVersion,+ `delegation:${delegationId}`, createdAt);+ }+ db.prepare(`INSERT INTO bot_delegations+ (id, requesting_bot_id, target_bot_id, parent_session_id, child_session_id, objective,+ context_refs_json, artifact_refs_json, permission_snapshot_json, lineage_json,+ target_profile_version, depth, budget_tokens, tokens_used, status, result_summary,+ last_error, created_at, accepted_at, completed_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, '[]', ?, ?, ?, ?, NULL, 0, 'queued', NULL, NULL, ?, NULL, NULL, ?)`)+ .run(delegationId, requestingBotId, targetBotId,+ expectString(d.parentSessionId, 'delegation.parentSessionId'), childSessionId,+ expectString(d.objective, 'delegation.objective'), expectString(d.contextRefsJson, 'delegation.contextRefsJson'),+ expectString(d.permissionSnapshotJson, 'delegation.permissionSnapshotJson'),+ expectString(d.lineageJson, 'delegation.lineageJson'),+ targetProfileVersion,+ expectNumber(d.depth, 'delegation.depth'),+ createdAt, createdAt);+ })();+ }++ function botsReopenDelegation(+ db: Database.Database,+ args: unknown,+ ): { reopened: boolean; previousParentSessionId: string | null } {+ const p = asRecord(args, 'bots.reopenDelegation args');+ const delegationId = expectString(p.delegationId, 'delegationId');+ const requestingBotId = expectString(p.requestingBotId, 'requestingBotId');+ const expectedStatus = expectString(p.expectedStatus, 'expectedStatus');+ if (!['completed', 'failed', 'cancelled', 'timed-out'].includes(expectedStatus)) {+ throw new Error('bots.reopenDelegation expectedStatus must be terminal');+ }+ const targetBotId = nullableString(p.targetBotId);+ const targetProfileVersion = p.targetProfileVersion === null || p.targetProfileVersion === undefined+ ? null+ : expectNumber(p.targetProfileVersion, 'targetProfileVersion');+ const reopenedAt = expectNumber(p.reopenedAt, 'reopenedAt');+ const maxActiveChildren = expectNumber(p.maxActiveChildren, 'maxActiveChildren');++ return db.transaction(() => {+ const current = db.prepare(`SELECT requesting_bot_id AS requestingBotId,+ target_bot_id AS targetBotId, target_profile_version AS targetProfileVersion,+ parent_session_id AS parentSessionId, status+ FROM bot_delegations WHERE id = ?`).get(delegationId) as+ | {+ requestingBotId: string;+ targetBotId: string | null;+ targetProfileVersion: number | null;+ parentSessionId: string | null;+ status: string;+ }+ | undefined;+ if (+ !current+ || current.requestingBotId !== requestingBotId+ || current.targetBotId !== targetBotId+ || current.targetProfileVersion !== targetProfileVersion+ || current.status !== expectedStatus+ ) {+ return { reopened: false, previousParentSessionId: current?.parentSessionId ?? null };+ }+ const count = db.prepare(`SELECT COUNT(*) AS count FROM bot_delegations+ WHERE requesting_bot_id = ? AND id <> ? AND status IN ('queued','running','waiting')`)+ .get(requestingBotId, delegationId) as { count: number };+ if (count.count >= maxActiveChildren) throw new Error('BOT_DELEGATION_CONCURRENCY_LIMIT');++ const session = asRecord(p.session, 'session');+ insertBotSession(db, session);+ const childSessionId = expectString(p.childSessionId, 'childSessionId');+ if (p.worktreePath != null) {+ db.prepare('UPDATE sessions SET worktree_path = ? WHERE id = ?')+ .run(expectString(p.worktreePath, 'worktreePath'), childSessionId);+ }+ if (targetBotId) {+ db.prepare(`INSERT INTO bot_session_links+ (id, bot_id, session_id, profile_version, role, route_key, created_at, archived_at)+ VALUES (?, ?, ?, ?, 'delegation', ?, ?, NULL)`)+ .run(`${targetBotId}:${childSessionId}`, targetBotId, childSessionId,+ targetProfileVersion, `delegation:${delegationId}`, reopenedAt);+ }+ const updated = db.prepare(`UPDATE bot_delegations SET+ parent_session_id = ?, child_session_id = ?, objective = ?,+ permission_snapshot_json = ?, status = 'queued', result_summary = NULL,+ output_artifacts_json = '[]', pending_interaction_json = NULL, last_error = NULL, tokens_used = 0,+ run_sequence = run_sequence + 1, accepted_at = NULL, completed_at = NULL,+ completion_delivered_at = NULL, updated_at = ?+ WHERE id = ? AND status = ?`).run(+ expectString(p.parentSessionId, 'parentSessionId'),+ childSessionId,+ expectString(p.objective, 'objective'),+ expectString(p.permissionSnapshotJson, 'permissionSnapshotJson'),+ reopenedAt,+ delegationId,+ expectedStatus,+ );+ if (updated.changes !== 1) throw new Error('BOT_DELEGATION_REOPEN_RACE');+ return { reopened: true, previousParentSessionId: current.parentSessionId };+ })();+ }++ function botsPauseLifecycle(db: Database.Database, args: unknown): void {+ const p = asRecord(args, 'bots.pauseLifecycle args');+ const botId = expectString(p.botId, 'botId');+ const at = expectNumber(p.at, 'at');+ db.transaction(() => {+ const profile = db.prepare(`UPDATE bot_profiles SET status = 'paused', updated_at = ?+ WHERE id = ? AND status = ?`)+ .run(at, botId, expectString(p.expectedProfileStatus, 'expectedProfileStatus'));+ if (profile.changes !== 1) throw Object.assign(+ new Error('Bot 生命周期已被另一处操作更新'),+ { code: 'PRECONDITION_FAILED' },+ );+ db.prepare(`INSERT INTO bot_lifecycle_events+ (id, bot_id, session_id, event_type, payload_json, created_at)+ VALUES (?, ?, ?, 'pause-requested', ?, ?)`)+ .run(expectString(p.eventId, 'eventId'), botId, nullableString(p.canonicalSessionId), '{}', at);+ })();+ }++ function botsResumeLifecycle(db: Database.Database, args: unknown): void {+ const p = asRecord(args, 'bots.resumeLifecycle args');+ const botId = expectString(p.botId, 'botId');+ const at = expectNumber(p.at, 'at');+ db.transaction(() => {+ const profile = db.prepare(`UPDATE bot_profiles SET status = 'active', updated_at = ?+ WHERE id = ? AND status = ?`)+ .run(at, botId, expectString(p.expectedProfileStatus, 'expectedProfileStatus'));+ if (profile.changes !== 1) throw Object.assign(+ new Error('Bot 生命周期已被另一处操作更新'),+ { code: 'PRECONDITION_FAILED' },+ );+ db.prepare(`INSERT INTO bot_lifecycle_events+ (id, bot_id, session_id, event_type, payload_json, created_at)+ VALUES (?, ?, ?, 'resumed', ?, ?)`)+ .run(expectString(p.eventId, 'eventId'), botId, nullableString(p.canonicalSessionId), '{}', at);+ })();+ }++ function botsArchiveLifecycle(db: Database.Database, args: unknown): { sessions: number } {+ const p = asRecord(args, 'bots.archiveLifecycle args');+ const botId = expectString(p.botId, 'botId');+ const at = expectNumber(p.at, 'at');+ return db.transaction(() => {+ const sessions = db.prepare(`UPDATE sessions SET status = 'archived', updated_at = ?+ WHERE source = 'bot' AND id IN (SELECT session_id FROM bot_session_links WHERE bot_id = ?)`)+ .run(at, botId).changes;+ db.prepare("UPDATE bot_session_links SET role = 'history', archived_at = ? WHERE bot_id = ?")+ .run(at, botId);+ const profile = db.prepare(`UPDATE bot_profiles SET status = 'archived', canonical_session_id = NULL,+ updated_at = ? WHERE id = ? AND status = ?`)+ .run(at, botId, expectString(p.expectedProfileStatus, 'expectedProfileStatus'));+ if (profile.changes !== 1) throw Object.assign(new Error('Bot 生命周期已被另一处操作更新'), { code: 'PRECONDITION_FAILED' });+ db.prepare(`INSERT INTO bot_lifecycle_events+ (id, bot_id, session_id, event_type, payload_json, created_at)+ VALUES (?, ?, ?, 'archived', ?, ?)`)+ .run(expectString(p.eventId, 'eventId'), botId, nullableString(p.canonicalSessionId),+ JSON.stringify({ worktreeDisposition: expectString(p.worktreeDisposition, 'worktreeDisposition'), sessions }), at);+ return { sessions };+ })();+ }++ /** Shared preflight and final transaction guard: deleting a profile must never cascade shared history. */+ function assertBotHasNoSharedHistory(db: Database.Database, botId: string): void {+ const sharedHistory = db.prepare(`SELECT 1 WHERE+ EXISTS (SELECT 1 FROM bot_delegations+ WHERE target_bot_id = ? OR (requesting_bot_id = ? AND target_bot_id IS NOT NULL))+ OR EXISTS (SELECT 1 FROM bot_direct_message_threads+ WHERE bot_a_id = ? OR bot_b_id = ?)+ OR EXISTS (SELECT 1 FROM bot_direct_messages+ WHERE sender_bot_id = ? OR recipient_bot_id = ?)`)+ .get(botId, botId, botId, botId, botId, botId);+ if (sharedHistory) throw Object.assign(+ new Error('Bot 有共享委派或私聊历史,不能永久删除'),+ { code: 'BOT_SHARED_HISTORY_REFERENCED' },+ );+ }++ function botsDeleteProfile(+ db: Database.Database,+ args: unknown,+ ): { sessionIds: string[]; status: 'archived' | 'deleted' } {+ const p = asRecord(args, 'bots.deleteProfile args');+ const botId = expectString(p.botId, 'botId');+ const sessionIds = [...new Set(expectArray(p.sessionIds, 'sessionIds').map((value, index) =>+ expectString(value, `sessionIds.${index}`),+ ))];+ if (typeof p.keepTaskHistory !== 'boolean') {+ throw new Error('keepTaskHistory must be a boolean');+ }+ const keepTaskHistory = p.keepTaskHistory;+ const at = expectNumber(p.at, 'at');+ const status: 'archived' | 'deleted' = keepTaskHistory ? 'archived' : 'deleted';+ return db.transaction(() => {+ const profile = db.prepare('SELECT status FROM bot_profiles WHERE id = ?').get(botId) as+ | { status: string }+ | undefined;+ if (!profile) throw Object.assign(new Error('Bot 不存在'), { code: 'NOT_FOUND' });+ if (profile.status !== 'archived') throw Object.assign(+ new Error('永久删除前 Bot 必须已归档'),+ { code: 'PRECONDITION_FAILED' },+ );++ // Profile foreign keys cascade into history shared with surviving Bots.+ // Check both delegation roles and actual message references before any mutation.+ assertBotHasNoSharedHistory(db, botId);++ const allSessionIds = [...new Set(sessionIds)];+ if (sessionIds.length > 0) {+ const placeholders = sessionIds.map(() => '?').join(',');+ const owned = db.prepare(`SELECT DISTINCT sessions.id+ FROM sessions+ INNER JOIN bot_session_links ON bot_session_links.session_id = sessions.id+ WHERE bot_session_links.bot_id = ? AND sessions.source = 'bot'+ AND sessions.id IN (${placeholders})`)+ .all(botId, ...sessionIds) as Array<{ id: string }>;+ if (owned.length !== sessionIds.length) throw Object.assign(+ new Error('只能分离属于该 Bot 的任务'),+ { code: 'PRECONDITION_FAILED' },+ );+ db.prepare(`UPDATE sessions SET source = 'desktop', status = ?, updated_at = ?+ WHERE source = 'bot' AND id IN (${placeholders})`)+ .run(status, at, ...sessionIds);+ }++ const hasMediaRefs = Boolean(db.prepare(+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'media_refs'",+ ).get());+ if (hasMediaRefs) {+ // The profile row and its private avatar reference are one deletion unit.+ // A process crash can no longer leave user-owned media permanently pinned.+ db.prepare("DELETE FROM media_refs WHERE ref_kind = 'bot-avatar' AND ref_id = ?")+ .run(botId);+ }+ const deleted = db.prepare("DELETE FROM bot_profiles WHERE id = ? AND status = 'archived'")+ .run(botId);+ if (deleted.changes !== 1) throw Object.assign(+ new Error('Bot 生命周期已被另一处操作更新'),+ { code: 'PRECONDITION_FAILED' },+ );+ return { sessionIds: allSessionIds, status };+ })();+ }++ function skillUsageApplyMutation(db: Database.Database, args: unknown): void {+ const payload = asRecord(args, 'skillUsage.applyMutation args');+ const kind = expectString(payload.kind, 'kind');++ if (kind === 'persist') {+ const rawSource = asRecord(payload.source, 'source');+ const source = {+ rawFilePath: expectString(rawSource.rawFilePath, 'source.rawFilePath'),+ analyzerVersion: expectString(rawSource.analyzerVersion, 'source.analyzerVersion'),+ agentKind: expectString(rawSource.agentKind, 'source.agentKind'),+ sessionId: expectString(rawSource.sessionId, 'source.sessionId'),+ sdkSessionId: expectString(rawSource.sdkSessionId, 'source.sdkSessionId'),+ mtimeMs: expectNumber(rawSource.mtimeMs, 'source.mtimeMs'),+ sizeBytes: expectNumber(rawSource.sizeBytes, 'source.sizeBytes'),+ scannedAt: expectNumber(rawSource.scannedAt, 'source.scannedAt'),+ };+ const exposures = expectArray(payload.exposures, 'exposures').map((raw, index) => {+ const row = asRecord(raw, `exposures.${index}`);+ return {+ id: expectString(row.id, `exposures.${index}.id`),+ rawFilePath: expectString(row.rawFilePath, `exposures.${index}.rawFilePath`),+ rawLineNo: expectNumber(row.rawLineNo, `exposures.${index}.rawLineNo`),+ sessionId: expectString(row.sessionId, `exposures.${index}.sessionId`),+ sdkSessionId: expectString(row.sdkSessionId, `exposures.${index}.sdkSessionId`),+ agentKind: expectString(row.agentKind, `exposures.${index}.agentKind`),+ skillName: expectString(row.skillName, `exposures.${index}.skillName`),+ skillPath: nullableString(row.skillPath),+ skillDocumentHash: nullableString(row.skillDocumentHash),+ exposureContentHash: expectString(row.exposureContentHash, `exposures.${index}.exposureContentHash`),+ documentHashSource: expectString(row.documentHashSource, `exposures.${index}.documentHashSource`),+ source: expectString(row.source, `exposures.${index}.source`),+ toolUseId: nullableString(row.toolUseId),+ seenAt: expectNumber(row.seenAt, `exposures.${index}.seenAt`),+ toolCallCount: expectNumber(row.toolCallCount, `exposures.${index}.toolCallCount`),+ repeatedToolCallCount: expectNumber(row.repeatedToolCallCount, `exposures.${index}.repeatedToolCallCount`),+ toolErrorCount: expectNumber(row.toolErrorCount, `exposures.${index}.toolErrorCount`),+ commandCallCount: expectNumber(row.commandCallCount, `exposures.${index}.commandCallCount`),+ commandFailureCount: expectNumber(row.commandFailureCount, `exposures.${index}.commandFailureCount`),+ };+ });++ const upsertSource = db.prepare(`+ INSERT INTO skill_usage_sources (+ raw_file_path, analyzer_version, agent_kind, session_id, sdk_session_id,+ mtime_ms, size_bytes, last_scanned_at, status, error+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'ok', NULL)+ ON CONFLICT(raw_file_path) DO UPDATE SET+ analyzer_version = excluded.analyzer_version,+ agent_kind = excluded.agent_kind,+ session_id = excluded.session_id,+ sdk_session_id = excluded.sdk_session_id,+ mtime_ms = excluded.mtime_ms,+ size_bytes = excluded.size_bytes,+ last_scanned_at = excluded.last_scanned_at,+ status = 'ok',+ error = NULL+ `);+ const deleteExposure = db.prepare(+ 'DELETE FROM skill_usage_exposures WHERE raw_file_path = ? AND analyzer_version = ?',+ );+ const insertExposure = db.prepare(`+ INSERT INTO skill_usage_exposures (+ id, analyzer_version, raw_file_path, raw_line_no, session_id, sdk_session_id, agent_kind,+ skill_name, skill_path, skill_document_hash, exposure_content_hash, document_hash_source,+ source, tool_use_id, seen_at, tool_call_count, repeated_tool_call_count,+ tool_error_count, command_call_count, command_failure_count+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ `);+ db.transaction(() => {+ upsertSource.run(+ source.rawFilePath,+ source.analyzerVersion,+ source.agentKind,+ source.sessionId,+ source.sdkSessionId,+ source.mtimeMs,+ source.sizeBytes,+ source.scannedAt,+ );+ deleteExposure.run(source.rawFilePath, source.analyzerVersion);+ for (const exposure of exposures) {+ insertExposure.run(+ `${source.analyzerVersion}:${exposure.id}`,+ source.analyzerVersion,+ exposure.rawFilePath,+ exposure.rawLineNo,+ exposure.sessionId,+ exposure.sdkSessionId,+ exposure.agentKind,+ exposure.skillName,+ exposure.skillPath,+ exposure.skillDocumentHash,+ exposure.exposureContentHash,+ exposure.documentHashSource,+ exposure.source,+ exposure.toolUseId,+ exposure.seenAt,+ exposure.toolCallCount,+ exposure.repeatedToolCallCount,+ exposure.toolErrorCount,+ exposure.commandCallCount,+ exposure.commandFailureCount,+ );+ }+ })();+ return;+ }++ if (kind === 'deleteBefore') {+ const analyzerVersion = expectString(payload.analyzerVersion, 'analyzerVersion');+ const recentSince = expectNumber(payload.recentSince, 'recentSince');+ db.transaction(() => {+ db.prepare(+ 'DELETE FROM skill_usage_exposures WHERE analyzer_version = ? AND seen_at < ?',+ ).run(analyzerVersion, recentSince);+ db.prepare(`+ DELETE FROM skill_usage_sources+ WHERE analyzer_version = ? AND mtime_ms < ?+ AND raw_file_path NOT IN (SELECT raw_file_path FROM skill_usage_exposures)+ `).run(analyzerVersion, recentSince);+ })();+ return;+ }++ if (kind === 'promote') {+ const analyzerVersion = expectString(payload.analyzerVersion, 'analyzerVersion');+ db.transaction(() => {+ db.prepare(`+ INSERT INTO migration_meta (key, value)+ VALUES ('skill_usage_analyzer_version', ?)+ ON CONFLICT(key) DO UPDATE SET value = excluded.value+ `).run(analyzerVersion);+ db.prepare('DELETE FROM skill_usage_exposures WHERE analyzer_version <> ?').run(analyzerVersion);+ })();+ return;+ }++ throw invalidArgs(`unknown skill usage mutation: ${kind}`);+ }+/** Remove every stale startup binding as one all-or-nothing repair. */function imDeleteBindings(db: Database.Database, args: unknown): void {const payload = asRecord(args, 'im.deleteBindings args');@@@ -603,10 -1730,10 +1807,10 @@@ function sessionsSetStatus(db: Databasethrow invalidArgs(`invalid status: ${status}`);}const selectSession = db.prepare(- 'SELECT id, title, working_dir AS workingDir, workspace_kind AS workspaceKind, status FROM sessions WHERE id = ? LIMIT 1',+ 'SELECT id, title, working_dir AS workingDir, workspace_kind AS workspaceKind, status, source FROM sessions WHERE id = ? LIMIT 1',);const updateSession = db.prepare(- 'UPDATE sessions SET status = ?, updated_at = ? WHERE id = ? RETURNING id, title, working_dir AS workingDir, workspace_kind AS workspaceKind',+ 'UPDATE sessions SET status = ?, updated_at = ? WHERE id = ? RETURNING id, title, working_dir AS workingDir, workspace_kind AS workspaceKind, remote_host_id AS remoteHostId, source',);const transaction = db.transaction(() => {const applied: Array<{@@@ -629,15 -1754,13 +1833,13 @@@code: 'PRECONDITION_FAILED',});}+ if ((existing as { source?: unknown }).source === 'bot') {+ throw Object.assign(new Error(`Bot 任务必须通过 Bot 生命周期管理: ${sessionId}`), {+ code: 'PRECONDITION_FAILED',+ });+ }const updated = updateSession.get(status, now, sessionId) as- | {- id: string;- title: string | null;- workingDir: string | null;- workspaceKind: string | null;- remoteHostId: string | null;- source: string | null;- }- | { id: string; title: string | null; workingDir: string | null; workspaceKind: string | null }++ | { id: string; title: string | null; workingDir: string | null; workspaceKind: string | null; remoteHostId: string | null; source: string | null }| undefined;if (!updated) {throw Object.assign(new Error(`Session 不存在: ${sessionId}`), { code: 'NOT_FOUND' });diff --cc apps/desktop/src/main/sidebarSettingsStore.tsindex eb4c52b120,53a16faa42..26e70ca348--- a/apps/desktop/src/main/sidebarSettingsStore.ts+++ b/apps/desktop/src/main/sidebarSettingsStore.ts@@@ -16,9 -16,11 +16,12 @@@ import { isIpcError } from '../shared/iimport { normalizeProjectKey, projectKeyComparisonKey } from '../shared/projectKeys.js';import {normalizeSidebarPinnedOrder,+ sidebarPinnedEntryComparisonKey,+ SIDEBAR_HIDDEN_MAIN_VIEW_MAX_ENTRIES,SIDEBAR_PINNED_ORDER_ENTRY_MAX_LENGTH,SIDEBAR_PINNED_ORDER_MAX_ENTRIES,+ isSidebarGhostId,+ type SidebarMainViewHiddenWriteRequest,type SidebarPinnedOrderMutation,type SidebarPinnedOrderWriteRequest,type SidebarLegacyRendererOwnerClaim,@@@ -258,35 -281,17 +282,33 @@@ function rebasePinnedReordercurrent: readonly string[],baseOrder: readonly string[],desiredOrder: readonly string[],+ localPlatform: string,): string[] {- const baseSet = new Set(baseOrder);- const currentSet = new Set(current);- const result = desiredOrder.filter((entry) => !baseSet.has(entry) || currentSet.has(entry));- const resultSet = new Set(result);-- for (let index = 0; index < current.length; index += 1) {- const entry = current[index];- if (baseSet.has(entry) || resultSet.has(entry)) continue;+ const identityOf = (entry: string) => sidebarPinnedEntryComparisonKey(entry, localPlatform);+ const baseIdentities = new Set(baseOrder.map(identityOf));+ const currentRepresentatives = new Map<string, string>();+ for (const entry of current) {+ const identity = identityOf(entry);+ if (!currentRepresentatives.has(identity)) currentRepresentatives.set(identity, entry);+ }++ const result: string[] = [];+ const resultIdentities = new Set<string>();+ for (const entry of desiredOrder) {+ const identity = identityOf(entry);+ if (resultIdentities.has(identity)) continue;-+ const durableRepresentative = currentRepresentatives.get(identity);+ if (baseIdentities.has(identity) && durableRepresentative == null) continue;-+ result.push(durableRepresentative ?? entry);+ resultIdentities.add(identity);+ }++ const durableEntries = Array.from(currentRepresentatives.entries());+ for (let index = 0; index < durableEntries.length; index += 1) {+ const [identity, entry] = durableEntries[index];+ if (baseIdentities.has(identity) || resultIdentities.has(identity)) continue;result.splice(Math.min(index, result.length), 0, entry);- resultSet.add(entry);+ resultIdentities.add(identity);}return normalizeSidebarPinnedOrder(result);@@@ -559,9 -625,9 +654,7 @@@ function readLegacyRendererOwnerMarkerif (backupState === 'missing') return { kind: 'missing' };}-- const raw = recoverBackup-- ? readAtomicFileSync(markerPath)-- : fs.readFileSync(readPath, 'utf-8');++ const raw = recoverBackup ? readAtomicFileSync(markerPath) : fs.readFileSync(readPath, 'utf-8');if (raw === null) return { kind: 'missing' };if (Buffer.byteLength(raw, 'utf-8') > MAX_LEGACY_RENDERER_OWNER_MARKER_BYTES) {return { kind: 'blocked' };@@@ -671,8 -737,8 +764,7 @@@ function claimLegacyRendererSidebarOwnereturn {...stamp,claimed: marker !== null,-- canInitialize:-- marker !== null && exclusiveAtStart && hasExclusiveSharedLegacyUserDataAccess(),++ canInitialize: marker !== null && exclusiveAtStart && hasExclusiveSharedLegacyUserDataAccess(),pinnedLegacyConsumed: marker?.pinnedLegacyConsumed === true,};}diff --cc apps/desktop/src/renderer/__tests__/machineSwitcherMenu.test.tsindex b0b4cba037,f2ae5dc4ad..ea3469514a--- a/apps/desktop/src/renderer/__tests__/machineSwitcherMenu.test.ts+++ b/apps/desktop/src/renderer/__tests__/machineSwitcherMenu.test.ts@@@ -54,56 -46,415 +46,418 @@@ describe('远程机器切换入口并�expect(sidebarUpperSource).not.toMatch(/[^t]setSelectedMachineId\(MACHINE_ALL\)/);});- it('SidebarTopNav 渲染 MachineSwitcherMenu 作列表末行(与新建 / 搜索同列表,固定不滚动)', () => {- expect(topNavSource).toContain("from '@/features/cc-agent/sidebar/MachineSwitcherMenu'");- // 末行:出现在 SidebarInlineSearch 之后。- const searchIdx = topNavSource.indexOf('<SidebarInlineSearch');- const menuIdx = topNavSource.indexOf('<MachineSwitcherMenu />');- expect(searchIdx).toBeGreaterThanOrEqual(0);- expect(menuIdx).toBeGreaterThan(searchIdx);+ it('SidebarTopNav 不再渲染 MachineSwitcherMenu(2026-08-13 并入段头标题)', () => {+ expect(topNavSource).not.toContain("from '@/features/cc-agent/sidebar/MachineSwitcherMenu'");+ expect(topNavSource).not.toContain('<MachineSwitcherMenu />');+ // 搜索行仍在;最小化面板存在且选用侧栏模式时,恢复入口插在插件与搜索之间。+ expect(topNavSource).toContain('<SidebarInlineSearch');+ });++ // 2026-08-12 用户裁决(对齐 Codex):任务列表向上滚动时,除「新建」外的顶部导航行+ // 一起滚走。实现为 SidebarTopNav 分段渲染 —— Shell 只画固定段,cc-agent 在自己的+ // 列表滚动容器最上方画可滚动段;归属由 feature-context 的开关声明,Shell 不判路由。+ it('顶部导航分两段:新建固定,其余行进任务列表滚动区', () => {+ const featureContextSource = read('features', 'feature-context.tsx');+ const sidebarShellSource = read('components', 'sidebar', 'Sidebar.tsx');++ // 三段渲染契约。+ expect(topNavSource).toContain(+ "export type SidebarTopNavSection = 'all' | 'pinned' | 'scrollable'",+ );+ expect(topNavSource).toContain("const showPinned = section !== 'scrollable'");+ expect(topNavSource).toContain("const showScrollable = section !== 'pinned'");++ // Shell:接管时只画固定段,否则整块常驻行(插件页等无长列表的视图)。+ expect(sidebarShellSource).toContain(+ "<SidebarTopNav section={ownsTopNavScrollableRows ? 'pinned' : 'all'} />",+ );+ // Shell 仍不感知路由:归属只读 context 开关(架构不变量:Shell 不 import router)。+ // 只查 import 语句——文件头注释里本就写着「刻意不 import useLocation」。+ expect(sidebarShellSource).toContain('useOwnsTopNavScrollableRows()');+ expect(sidebarShellSource).not.toMatch(/^import .*from 'react-router-dom'/m);++ // cc-agent:展开态声明接管,并把可滚动段画进滚动容器;rail 态交回 Shell。+ expect(sidebarUpperSource).toContain('useOwnTopNavScrollableRows(!isCollapsed)');+ expect(sidebarUpperSource).toContain('<SidebarTopNav section="scrollable" />');+ const scrollRefIdx = sidebarUpperSource.indexOf('ref={sidebarScrollRef}');+ const scrollableRowsIdx = sidebarUpperSource.indexOf('<SidebarTopNav section="scrollable" />');+ expect(scrollRefIdx).toBeGreaterThanOrEqual(0);+ expect(scrollableRowsIdx).toBeGreaterThan(scrollRefIdx);+ // 搜索打开时搜索行作为滚动容器直接子项 sticky;打开查询时记下并复位滚动,+ // 清查询时还原,不再用 overlay 盖住输入框。+ expect(topNavSource).toContain(+ "const pinSearch = section === 'scrollable' && search.query.trim().length > 0",+ );+ expect(topNavSource).toContain("pinSearch && 'sticky top-0 z-30 bg-[var(--cmd-palette-bg)]'");+ expect(topNavSource).toContain("if (section === 'scrollable')");+ expect(sidebarUpperSource).toContain('lastListScrollTopRef.current = el.scrollTop');+ expect(sidebarUpperSource).toContain(+ 'sidebarScrollRef.current?.scrollTo({ top: lastListScrollTopRef.current })',+ );+ expect(sidebarUpperSource).toContain('search.statusFilter');+ expect(sidebarUpperSource).toContain('searchProjectKey');+ expect(sidebarUpperSource).toContain('onContextMenu={(event) => event.stopPropagation()}');+ expect(sidebarUpperSource).toContain('{searchActive ? (');+ expect(sidebarUpperSource).toContain(+ '<div hidden={searchActive} className="flex flex-col gap-2">',+ );+ expect(sidebarUpperSource).toContain('freezeListScrollOnOpenRef.current = true');+ expect(sidebarUpperSource).toContain('const restoreListScroll = useCallback');+ expect(sidebarUpperSource).toContain('const restoreListScrollAfterPointer = useCallback');+ expect(sidebarUpperSource).toContain('restoreListScrollAfterPointer()');+ expect(sidebarUpperSource).toContain(+ "window.addEventListener('pointerup', onPointerEnd, true)",+ );+ expect(sidebarUpperSource).toContain("document.addEventListener('focusin', onFocusIn)");+ const inlineSearchSource = read('features', 'cc-agent', 'sidebar', 'SidebarInlineSearch.tsx');+ expect(inlineSearchSource).toContain('inputRef.current?.focus({ preventScroll: true })');+ expect(sidebarUpperSource).not.toContain('absolute inset-0 z-20');+ expect(sidebarUpperSource).not.toContain(+ "search.trimmed && 'sticky top-0 z-30 bg-[var(--cmd-palette-bg)]'",+ );++ // 声明语义与 useRegisterSidebarUpper 一致:卸载不复位,避免切到 /settings 时闪变。+ expect(featureContextSource).toContain('export function useOwnTopNavScrollableRows');+ expect(featureContextSource).toContain('export function useOwnsTopNavScrollableRows');+ });++ it('插件主视图紧随插件入口,面板恢复入口仍位于插件区与搜索之间', () => {+ const expandedPluginsIdx = topNavSource.indexOf('{pluginsRow}');+ const expandedMainViewsIdx = topNavSource.indexOf('{mainViewRows}', expandedPluginsIdx);+ const expandedRestoreIdx = topNavSource.indexOf('{restoreRow}', expandedPluginsIdx);+ const expandedSearchIdx = topNavSource.indexOf('{searchRow}', expandedRestoreIdx);+ expect(expandedPluginsIdx).toBeGreaterThanOrEqual(0);+ expect(expandedMainViewsIdx).toBeGreaterThan(expandedPluginsIdx);+ expect(expandedRestoreIdx).toBeGreaterThan(expandedMainViewsIdx);+ expect(expandedSearchIdx).toBeGreaterThan(expandedRestoreIdx);++ const persistentPluginsIdx = topNavSource.lastIndexOf('{pluginsRow}');+ const persistentMainViewsIdx = topNavSource.indexOf('{mainViewRows}', persistentPluginsIdx);+ const persistentRestoreIdx = topNavSource.indexOf('{restoreRow}', persistentMainViewsIdx);+ expect(persistentPluginsIdx).toBeGreaterThan(expandedPluginsIdx);+ expect(persistentMainViewsIdx).toBeGreaterThan(persistentPluginsIdx);+ expect(persistentRestoreIdx).toBeGreaterThan(persistentMainViewsIdx);++ const railPluginsIdx = sidebarUpperSource.indexOf("label={t('sidebar.tabs.plugins')}");+ const railRestoreIdx = sidebarUpperSource.indexOf('<GhostPanelRestoreEntry', railPluginsIdx);+ const railSearchIdx = sidebarUpperSource.indexOf('<ConversationSearchBox', railRestoreIdx);+ expect(railPluginsIdx).toBeGreaterThanOrEqual(0);+ expect(railRestoreIdx).toBeGreaterThan(railPluginsIdx);+ expect(railSearchIdx).toBeGreaterThan(railRestoreIdx);+ });++ // 2026-08-12 用户反馈:滚动后首行紧贴固定的「新建」被硬切、露出半截字。+ it('滚动后顶部渐隐,未滚动时不加 mask(避免裁掉首行 hover 胶囊 / 焦点环)', () => {+ // 按需启用:与右栏 TabBar 的 side-aware fade 同一取舍(常开 mask 会裁 border)。+ expect(sidebarUpperSource).toContain('const [topFade, setTopFade] = useState(false)');+ expect(sidebarUpperSource).toContain('const next = el.scrollTop > 1;');+ expect(sidebarUpperSource).toContain('...(topFade');+ // 用 mask-image(alpha)而非叠色块:透出侧栏自身背景,双主题天然正确、无需取色。+ expect(sidebarUpperSource).toContain(+ "WebkitMaskImage: 'linear-gradient(to bottom, transparent 0, black 24px)'",+ );+ expect(sidebarUpperSource).toContain(+ "maskImage: 'linear-gradient(to bottom, transparent 0, black 24px)'",+ );+ // jsdom 无 ResizeObserver:必须带 guard,否则测试环境构造即抛。+ expect(sidebarUpperSource).toContain("typeof ResizeObserver !== 'undefined'");});- it('连接中占位页不再自带 MachineSwitcherMenu(固定行已常驻,不会被困住)', () => {- const idx = sidebarUpperSource.indexOf('selectedMachineConnecting ?');- expect(idx).toBeGreaterThanOrEqual(0);- const branch = sidebarUpperSource.slice(idx, idx + 600);- expect(branch).not.toContain('<MachineSwitcherMenu');+ // 2026-08-12 用户裁决:整理菜单里「显示 / 任务信息」加行首图标,让选项一眼可辨。+ it('显示与任务信息选项带图标,显示模式与置顶段菜单同字形', () => {+ const filterSource = read('features', 'cc-agent', 'sidebar', 'SidebarFilterPopover.tsx');+ const pinnedSectionSource = read(+ 'features',+ 'cc-agent',+ 'sidebar',+ 'sections',+ 'PinnedSection.tsx',+ );++ // 显示模式:同一概念在两处菜单必须用同一个 lucide 字形(不各造一套)。+ expect(filterSource).toContain("labelKey: 'ccAgent.sidebar.viewStyleList', Icon: AlignJustify");+ expect(filterSource).toContain(+ "labelKey: 'ccAgent.sidebar.viewStyleListWide', Icon: LayoutList",+ );+ expect(pinnedSectionSource).toContain(+ "labelKey: 'ccAgent.sidebar.viewStyleList', Icon: AlignJustify",+ );+ expect(pinnedSectionSource).toContain(+ "labelKey: 'ccAgent.sidebar.viewStyleListWide', Icon: LayoutList",+ );++ // 任务信息各项各配数据类型图标;时间用 Clock 而非 Timer(后者是自动任务专用字形)。+ expect(filterSource).toContain("labelKey: 'ccAgent.sidebar.taskInfo.time', Icon: Clock");+ expect(filterSource).toContain("labelKey: 'ccAgent.sidebar.taskInfo.pr', Icon: GitPullRequest");+ expect(filterSource).toContain("labelKey: 'ccAgent.sidebar.taskInfo.worktree', Icon: Folders");+ expect(filterSource).toContain("labelKey: 'ccAgent.sidebar.taskInfo.tokens', Icon: Coins");+ expect(filterSource).toContain("labelKey: 'ccAgent.sidebar.taskInfo.cost', Icon: Wallet");+ expect(filterSource).not.toMatch(/taskInfo\.time', Icon: Timer/);++ // 抽象策略段(分组 / 排序 / 筛选维度)刻意不配图标,避免为凑图标而增噪。+ expect(filterSource).not.toMatch(/filterSortBy\.\w+', Icon:/);+ expect(filterSource).not.toMatch(/filterGroupBy\.\w+', Icon:/);+ expect(filterSource).not.toMatch(/filterStatus\.\w+', Icon:/);});- it('项目段头不再渲染 MachineSwitcherMenu(已移到顶部固定行)', () => {- expect(projectsSectionSource).not.toContain('MachineSwitcherMenu');+ // 2026-08-12 用户裁决:置顶段头的显示样式按钮显示**当前选中**的模式图标,+ // 此前恒为 LayoutGrid(网格),选文字/列表时与实际状态不符。+ it('置顶段头显示样式 trigger 的图标跟随当前模式', () => {+ const pinnedSectionSource = read(+ 'features',+ 'cc-agent',+ 'sidebar',+ 'sections',+ 'PinnedSection.tsx',+ );+ // 选项表提到模块级,菜单项与 trigger 共用同一张表(不各写一份字形映射)。+ expect(pinnedSectionSource).toContain('const VIEW_STYLE_OPTIONS');+ expect(pinnedSectionSource).toContain('function viewStyleIcon(mode: SidebarViewMode)');+ expect(pinnedSectionSource).toContain('const ViewStyleTriggerIcon = viewStyleIcon(mode)');+ expect(pinnedSectionSource).toContain('<ViewStyleTriggerIcon size={13} strokeWidth={2} />');+ // trigger 不再硬编码网格图标。+ expect(pinnedSectionSource).not.toContain('<LayoutGrid size={13} strokeWidth={2} />');});- it('项目视图:早退条件不再依赖 hasRemote 保留空段头(入口不在本段头)', () => {- expect(projectsSectionSource).not.toContain('useMachineSwitcher');- expect(projectsSectionSource).not.toContain('hasRemote');+ // 2026-08-12 用户裁决:侧栏空白处右键也能开整理菜单。+ it('侧栏空白处右键打开整理菜单(行级右键仍归各自的菜单)', () => {+ const filterSource = read('features', 'cc-agent', 'sidebar', 'SidebarFilterPopover.tsx');+ // 同一组件两种形态:段头按钮 / 受控光标定位(隐形 fixed trigger,同 ProjectNode 做法)。+ expect(filterSource).toContain('const isContextMode = contextMenuPos !== undefined');+ expect(filterSource).toContain("position: 'fixed'");+ expect(filterSource).toContain('left: contextMenuPos?.x ?? 0');+ expect(filterSource).toContain('top: contextMenuPos?.y ?? 0');++ // 滚动容器接右键;行级菜单靠自身 stopPropagation 抢先处理,这里只兜空白区。+ expect(sidebarUpperSource).toContain('onContextMenu={handleSidebarBlankContextMenu}');+ expect(sidebarUpperSource).toContain(+ 'setOrganizeMenuPos({ x: event.clientX, y: event.clientY })',+ );+ expect(sidebarUpperSource).toContain('contextMenuPos={organizeMenuPos}');+ });++ // 2026-08-13 实机回归:重命名输入框上右键,行级 handler 裸 return 让事件冒泡到+ // 滚动容器,整理菜单和系统的剪切/粘贴菜单叠着弹。编辑态必须 stopPropagation+ // (但不 preventDefault——系统可编辑菜单要照常出)。+ it('行级右键在编辑态阻止冒泡,不触发空白处整理菜单', () => {+ const files = [+ ['features', 'cc-agent', 'sidebar', 'SessionItem.tsx'],+ ['features', 'cc-agent', 'sidebar', 'SessionCard.tsx'],+ ['features', 'cc-agent', 'sidebar', 'sections', 'ProjectNode.tsx'],+ ] as const;+ for (const parts of files) {+ const source = read(...parts);+ // 编辑态分支必须 stopPropagation 后再 return;裸 `if (isEditing) return` 即回归。+ expect(source).toMatch(+ /if \(isEditing(?:Name)?\) \{\s*\n(?:\s*\/\/[^\n]*\n)*\s*e\.stopPropagation\(\);\s*\n\s*return;/,+ );+ expect(source).not.toMatch(+ /onContextMenu=\{\(e\) => \{\s*\n\s*if \(isEditing(?:Name)?\) return;/,+ );+ }});- it('日期分组头不再渲染 MachineSwitcherMenu(已移到顶部固定行)', () => {- expect(dateSectionSource).not.toContain('MachineSwitcherMenu');+ it('项目顺序与任务排序拆开,关分组不再改写 sortBy', () => {+ const hookSource = read('features', 'cc-agent', 'hooks', 'useSidebarFilter.ts');+ expect(hookSource).not.toContain('nextSortByAfterGroupByChange');+ expect(hookSource).toContain('setProjectOrder');+ expect(hookSource).toContain('migrateLegacyManualSort');});- it('日期分组视图:选中 0 会话的远程机器时仍渲染空态段头(空列表可感知)', () => {- // groups 为空且 filter 未激活、初始加载已结束时,若还选中了非「所有」的远程机器,- // machineFilterActive 让组件继续渲染空态段头(「空」标签),让用户看得出是机器- // 过滤导致的空列表而非白屏。- expect(dateSectionSource).toContain('machineFilterActive');- expect(dateSectionSource).toMatch(/selectedDeviceId\s*!==\s*MACHINE_ALL/);- expect(dateSectionSource).toContain(- 'if (groups.length === 0 && !isLoading && !filter.isFilterActive && !machineFilterActive) return null;',+ it('列表行也接收来源标签(平铺时项目会话不再丢项目名)', () => {+ const entryListSource = read('features', 'cc-agent', 'sidebar', 'SessionEntryList.tsx');+ expect(entryListSource).toContain('sourceLabel={sourceLabelMap?.get(entry.session.id)}');+ expect(+ entryListSource.match(/sourceLabel=\{sourceLabelMap\?\.get\(entry\.session\.id\)\}/g),+ ).toHaveLength(2);+ const automationGroupSource = read(+ 'features',+ 'cc-agent',+ 'sidebar',+ 'AutomationSessionGroupItem.tsx',);+ expect(automationGroupSource).toContain('sourceLabel: sourceLabelMap?.get(session.id)');+ const cardSource = read('features', 'cc-agent', 'sidebar', 'SessionCard.tsx');+ expect(cardSource).toContain('sourceLabel,');+ expect(cardSource).toContain('{sourceLabel ? (');+ const itemSource = read('features', 'cc-agent', 'sidebar', 'SessionItem.tsx');+ expect(itemSource).toContain('{sourceLabel ? (');});- it('按时间分组视图:整理侧边栏(filter)按钮默认隐藏、hover 段头才浮现', () => {- // 段头挂 group/sidebar-header,SidebarFilterPopover 包在 hover-reveal 容器里。- expect(dateSectionSource).toContain('group/sidebar-header');- expect(dateSectionSource).toContain('HEADER_HOVER_ACTION_CLASS');- // filter popover 包在 hover-reveal 容器里(默认隐藏,hover 段头才浮现)。- expect(dateSectionSource).toMatch(- /<div className=\{HEADER_HOVER_ACTION_CLASS\}>\s*<SidebarFilterPopover/,+ // 2026-08-12 用户裁决:筛选各维度选中后菜单不关闭(常要连调几项);排序与显示+ // 模式仍选完即关(一次一个决定)。+ it('筛选维度选中后保持菜单打开,排序 / 显示模式仍选完即关', () => {+ const filterSource = read('features', 'cc-agent', 'sidebar', 'SidebarFilterPopover.tsx');+ // keepOpen 走 onSelect 的 preventDefault(Radix 据此不关闭菜单)。+ expect(filterSource).toContain('keepOpen = false');+ expect(filterSource).toContain('if (keepOpen) event.preventDefault();');+ // 三个筛选维度都传 keepOpen。+ expect(filterSource).toMatch(/onSelect=\{\(\) => setStatus\(option\.value\)\}\s*\n\s*keepOpen/);+ expect(filterSource).toMatch(/onSelect=\{\(\) => setVendor\(option\.value\)\}\s*\n\s*keepOpen/);+ expect(filterSource).toMatch(+ /onSelect=\{\(\) => setLastActivity\(option\.value\)\}\s*\n\s*keepOpen/,+ );+ // 排序 / 显示模式不传(选完即关)。+ expect(filterSource).not.toMatch(+ /onSelect=\{\(\) => setSortBy\(option\.value\)\}\s*\n\s*keepOpen/,+ );+ expect(filterSource).not.toMatch(+ /onSelect=\{\(\) => setMainViewMode\(option\.value\)\}\s*\n\s*keepOpen/,);+ expect(filterSource).not.toMatch(+ /onSelect=\{\(\) => setProjectOrder\(option\.value\)\}\s*\n\s*keepOpen/,+ );+ expect(filterSource).toContain('checked={groupDevice}');+ expect(filterSource).not.toContain("disabled={sortBy === 'manual'}");});+ // 2026-08-13 用户裁决:「优先级」光看标签猜不出排序依据,需要 hover 说明。+ it('排序的「优先级」有 hover 说明,自解释的档位不加', () => {+ const filterSource = read('features', 'cc-agent', 'sidebar', 'SidebarFilterPopover.tsx');+ // 说明挂在选项表上(与 labelKey / Icon 同源),不在渲染处硬编码文案。+ expect(filterSource).toMatch(+ /value: 'priority',\s*\n\s*labelKey: 'ccAgent\.sidebar\.filterSortBy\.priority',\s*\n\s*tipKey: 'ccAgent\.sidebar\.filterSortByTip\.priority',/,+ );+ // recency / manual 名字自解释,不配说明——菜单不该变成说明书。+ expect(filterSource).not.toMatch(/filterSortBy\.recency',\s*\n?\s*tipKey/);+ expect(filterSource).not.toMatch(/filterSortBy\.manual',\s*\n?\s*tipKey/);+ // side="right":菜单贴侧栏右缘,提示往上下会压住相邻选项。+ expect(filterSource).toContain('<Tip text={tip} side="right">');+ // 渲染处从选项表取,tipKey 缺省时传 undefined(Tip 据此透明透传、不挂 tooltip)。+ expect(filterSource).toContain('tip={option.tipKey ? t(option.tipKey) : undefined}');+ });++ // 设计文档 §3.3 定稿 + 2026-08-12 用户重申:筛选不作用于置顶区。+ it('置顶区不受项目 / Agent / 最近活跃筛选影响(归档仍按状态隐藏)', () => {+ // 置顶会话:直接用 allGroups.pinned,不再套 vendor / project 过滤。+ expect(sidebarUpperSource).toMatch(+ /const visiblePinnedSessions = useMemo\(\(\) => \{[\s\S]*?return allGroups\.pinned;\s*\}, \[allGroups\.pinned\]\)/,+ );+ // 置顶项目:仍尊重「从侧栏移除」(用户显式隐藏),但不再按 project / vendor 过滤。+ const pinnedProjectsBlock = sidebarUpperSource.slice(+ sidebarUpperSource.indexOf('const visiblePinnedProjects'),+ sidebarUpperSource.indexOf('const visiblePinnedEntries'),+ );+ expect(pinnedProjectsBlock).toContain('hiddenProjectComparisonKeys');- expect(pinnedProjectsBlock).toContain('pinnedProjectKeys.has(project.projectKey)');++ expect(pinnedProjectsBlock).toContain('pinnedProjectComparisonKeys');++ expect(pinnedProjectsBlock).toContain('projectKeyComparisonSetHas');+ expect(pinnedProjectsBlock).not.toContain('vendorPredicate');+ expect(pinnedProjectsBlock).not.toContain('filter.projectsAsSet');+ expect(pinnedProjectsBlock).not.toContain('allowedProjects');+ // 「最近活跃」本就豁免:置顶取 allGroups(未经活跃时间收窄),不是 activityFilteredSessions。- expect(sidebarUpperSource).toContain('const allGroups = useProjectGroups(sidebarSessions');++ expect(sidebarUpperSource).toMatch(++ /const allGroups = useProjectGroups\(\s*sidebarSessions/,++ );+ });++ // 2026-08-12 用户裁决:任务信息按用户勾选顺序显示(先勾时间再勾费用 → 时间在前)。+ it('任务信息渲染顺序 = 勾选顺序,不再是固定的 pr → tokens → cost → time', () => {+ const infoMetaSource = read('features', 'cc-agent', 'sidebar', 'SessionInfoMeta.tsx');+ const filterCoreSource = read(+ 'features',+ 'cc-agent',+ 'hooks',+ 'helpers',+ 'sidebarFilterCore.ts',+ );++ // 勾选状态本身按先后追加(存储即顺序),这是整条链路的源头。+ expect(filterCoreSource).toContain('return prev.concat(field);');+ // 拼装遍历 fields 数组,而不是走固定的 if 序列。+ expect(infoMetaSource).toContain('for (const field of fields)');+ // PR 也参与排序:以 'pr' 占位进入 pieces,渲染时换成徽标。+ expect(infoMetaSource).toContain("if (field === 'pr' && hasPrRef)");+ expect(infoMetaSource).toContain("pieces.push({ key: 'pr', text: '' })");+ expect(infoMetaSource).toContain("piece.key === 'pr' ?");+ expect(infoMetaSource).toContain("if (field === 'worktree' && hasWorktree)");+ expect(infoMetaSource).toContain("piece.key === 'worktree' ?");+ // 菜单摘要的图标串同样按勾选顺序(遍历 taskInfoFields,不是遍历选项表)。+ const filterSource = read('features', 'cc-agent', 'sidebar', 'SidebarFilterPopover.tsx');+ expect(filterSource).toContain('{taskInfoFields.map((field) => {');+ });++ // 2026-08-12 用户裁决:任务信息行的当前选中项用图标表示,不再罗列短词。+ it('任务信息摘要用图标串,筛选各维度行也有图标', () => {+ const filterSource = read('features', 'cc-agent', 'sidebar', 'SidebarFilterPopover.tsx');+ // 摘要节点渲染已选项的图标(顺序见上一条:按勾选顺序);文字版留给 aria-label。+ expect(filterSource).toContain('valueNode={');+ expect(filterSource).toContain('aria-label={valueNode ? value : undefined}');+ // 具体维度行配图标(状态 / 项目 / Agent / 最近活跃 / 筛选 / 任务信息)。+ expect(filterSource).toContain('Icon={Filter}');+ expect(filterSource).toContain('toggleProject(DIALOGUE_FILTER_KEY)');+ expect(filterSource).toContain("t('ccAgent.sidebar.dialogues')");+ expect(filterSource).toContain('Icon={CircleDot}');+ expect(filterSource).toContain('Icon={Folder}');+ expect(filterSource).toContain('Icon={Bot}');+ expect(filterSource).toContain('Icon={CalendarClock}');+ expect(filterSource).toContain('Icon={Info}');+ });++ it('空态 / 远程任务 loading-error / 设备目录 loading / 连接中占位都挂范围标题', () => {+ const headerSource = read('features', 'cc-agent', 'sidebar', 'MainListScopeHeader.tsx');+ expect(headerSource).toContain('<MachineSwitcherMenu onOpenDisplaySettings=');+ expect(headerSource).not.toContain('filterActiveBadge');+ expect(headerSource).toContain('<SidebarFilterPopover');+ expect(projectsSectionSource).toContain('<MainListScopeHeader');+ expect(projectsSectionSource).toContain('hasMainListContent');+ expect(projectsSectionSource).not.toMatch(/if \(\s*allProjectKeysForOrder\.length === 0/);+ // 连接中 / 全屏 loading-error 不再把范围标题一起摘掉。设备目录 error 不展示+ // 占位提示,因此不属于这里的标题覆盖分支。+ const connectingIdx = sidebarUpperSource.indexOf('selectedMachineConnecting ?');+ expect(connectingIdx).toBeGreaterThanOrEqual(0);+ expect(sidebarUpperSource.slice(connectingIdx, connectingIdx + 900)).toContain(+ '<MainListScopeHeader',+ );+ expect(sidebarUpperSource).toContain('deviceGroupingAvailable');+ expect(sidebarUpperSource).not.toContain(+ "remoteDeviceDirectoryStatus === 'error' && !hasVisibleSidebarContent",+ );+ const placeholderMarkers = [+ 'remoteSessionBootstrapFailures.length > 0 && !hasVisibleSidebarContent',+ "remoteDeviceDirectoryStatus === 'loading' && !hasVisibleSidebarContent",+ 'remoteSessionBootstrapLoadingDevices.length > 0 && !hasVisibleSidebarContent',+ 'selectedMachineConnecting ?',+ ];+ for (const marker of placeholderMarkers) {+ const idx = sidebarUpperSource.indexOf(marker);+ expect(idx, `缺占位分支 ${marker}`).toBeGreaterThanOrEqual(0);+ expect(sidebarUpperSource.slice(idx, idx + 700), marker).toContain('<MainListScopeHeader');+ }+ // 空账户 / 只剩置顶:ProjectsSection 不再因无内容整段 return null。+ expect(projectsSectionSource).toContain('const hasMainListContent =');+ expect(projectsSectionSource).toContain('{hasMainListContent ? (');+ });++ it('项目段头标题即范围下拉(2026-08-13 定稿,推翻 2026-07「不挂段头」)', () => {+ expect(projectsSectionSource).toContain("from '../MainListScopeHeader'");+ expect(projectsSectionSource).toContain('<MainListScopeHeader');+ // 段头不再渲染硬编码的「全部任务」标题(标题文字由菜单 trigger 按范围决定)。+ expect(projectsSectionSource).not.toContain("t('ccAgent.sidebar.allSessions')");+ // 段级收起随合并取消:标题的点击语义让给范围切换。+ expect(projectsSectionSource).not.toContain('isSectionCollapsed');+ });++ it('项目视图:范围判定走 effective 选择 hook,不再有旧 hasRemoteMachines 结构', () => {+ // 单机范围下设备分组退场(2026-08-13 用户定稿)——生效与选项可见共用+ // deviceGroupingAvailable,由 effective 机器选择派生。+ expect(projectsSectionSource).toContain('useEffectiveSelectedMachineId');+ expect(projectsSectionSource).toContain(+ 'const singleMachineScope = selectedMachineId !== MACHINE_ALL && selectedMachineId.length === 1',+ );+ expect(projectsSectionSource).toContain(+ 'const deviceGroupingAvailable = hasRemoteDevices && !singleMachineScope',+ );+ expect(projectsSectionSource).toContain('hasRemoteDevices={deviceGroupingAvailable}');+ expect(projectsSectionSource).not.toContain('hasRemoteMachines');+ expect(sidebarUpperSource).toContain("if (device.status === 'rejected') continue;");+ expect(sidebarUpperSource).toContain(+ "if (device.status === 'connecting' && isRemoteDeviceMarkedDisconnected(device.deviceId))",+ );+ });++ // (侧边栏重设计 D 期:按日期分组段已删除,其 MachineSwitcherMenu / 空态 /+ // hover-reveal 断言随 DateGroupedSessionsSection.tsx 一并下线。)+it('机器过滤激活时其它 action 仍按默认 hover 收起(不随选中设备常驻)', () => {// 选中设备只体现在 MachineSwitcherMenu 自身(active 指示),其它 action 不因此常驻。expect(projectsSectionSource).not.toContain('useMachineFilterActive');diff --cc apps/desktop/src/renderer/__tests__/sidebarProjectRestore.test.tsindex 3bbbb4b7d8,b5ff9d852b..4b5351f42f--- a/apps/desktop/src/renderer/__tests__/sidebarProjectRestore.test.ts+++ b/apps/desktop/src/renderer/__tests__/sidebarProjectRestore.test.ts@@@ -99,6 -102,6 +102,85 @@@ describe('collectRestorableProjectKeys'expect(Array.from(keys)).toEqual([PROJECT_KEY]);});++++ it('restores a persistent project with no visible tasks', async () => {++ const keys = collectRestorableProjectKeys({++ sessions: [],++ persistentLocalProjects: [++ {++ workingDir: '/workspace/cindy',++ lastUsedAt: '2026-08-02T08:00:00.000Z',++ knownAgentKinds: [],++ },++ ],++ lastActivityCutoff: null,++ pinnedProjectKeys: new Set(),++ vendorPredicate: null,++ localPlatform: 'linux',++ });++ const ensureProjectIncluded = vi.fn();++++ await expect(++ restoreHiddenProjectIfPresent({++ projectKey: PROJECT_KEY,++ wasHiddenAtPickerOpen: true,++ setProjectHidden: vi.fn().mockResolvedValue(true),++ getCurrentProjectKeys: () => keys,++ ensureProjectIncluded,++ localPlatform: 'linux',++ }),++ ).resolves.toBe(true);++++ expect(ensureProjectIncluded).toHaveBeenCalledWith(PROJECT_KEY);++ });++++ it('applies activity and vendor filters to unpinned persistent projects', () => {++ const persistentLocalProjects = [++ {++ workingDir: '/workspace/cindy',++ lastUsedAt: '2026-01-01T00:00:00.000Z',++ knownAgentKinds: ['cc'],++ },++ ];++++ expect(++ collectRestorableProjectKeys({++ sessions: [],++ persistentLocalProjects,++ lastActivityCutoff: Date.parse('2026-08-01T00:00:00.000Z'),++ pinnedProjectKeys: new Set(),++ vendorPredicate: null,++ }).has(PROJECT_KEY),++ ).toBe(false);++ expect(++ collectRestorableProjectKeys({++ sessions: [],++ persistentLocalProjects,++ lastActivityCutoff: null,++ pinnedProjectKeys: new Set(),++ vendorPredicate: (session) => session.agentKind === 'codex',++ }).has(PROJECT_KEY),++ ).toBe(false);++ });++++ it('lets a pinned persistent project bypass activity and vendor filters', () => {++ const keys = collectRestorableProjectKeys({++ sessions: [],++ persistentLocalProjects: [++ {++ workingDir: 'C:/Workspace/Cindy',++ lastUsedAt: '2026-01-01T00:00:00.000Z',++ knownAgentKinds: ['cc'],++ },++ ],++ lastActivityCutoff: Date.parse('2026-08-01T00:00:00.000Z'),++ pinnedProjectKeys: new Set(['local:c:/workspace/cindy']),++ vendorPredicate: (session) => session.agentKind === 'codex',++ localPlatform: 'win32',++ });++++ expect(Array.from(keys)).toEqual(['local:C:/Workspace/Cindy']);++ });});describe('restoreHiddenProjectIfPresent', () => {diff --cc apps/desktop/src/renderer/__tests__/sidebarProjectSorting.test.tsindex a195bf9c94,62afd90d37..cf35f7cd4b--- a/apps/desktop/src/renderer/__tests__/sidebarProjectSorting.test.ts+++ b/apps/desktop/src/renderer/__tests__/sidebarProjectSorting.test.ts@@@ -68,40 -73,12 +73,27 @@@ describe('sidebar project sorting', ()expect(sorted.map((p) => p.workingDir)).toEqual(['/p/gamma', '/p/alpha', '/p/beta']);});- it('applies a stored Windows manual order to representatives with different casing', () => {++ it('applies a stored Windows order to persistent representatives with different casing', () => {+ const sorted = sortProjectsForSidebar(+ [+ project({ workingDir: 'd:/école/alpha', displayName: 'alpha' }),+ project({ workingDir: 'd:/école/beta', displayName: 'beta' }),+ ],- 'manual',++ 'recency',+ ['local:D:/École/BETA', 'local:D:/École/ALPHA'],++ 'custom',+ 'win32',+ );++ expect(sorted.map((p) => p.workingDir)).toEqual(['d:/école/beta', 'd:/école/alpha']);+ });+- it('sorts projects alphabetically by display name', () => {- const sorted = sortProjectsForSidebar(- [- project({ workingDir: '/p/zeta', displayName: 'zeta' }),- project({ workingDir: '/p/alpha', displayName: 'alpha' }),- project({ workingDir: '/p/Project 2', displayName: 'Project 2' }),- project({ workingDir: '/p/Project 10', displayName: 'Project 10' }),- ],- 'alphabetic',- [],- );-- expect(sorted.map((p) => p.displayName)).toEqual(['alpha', 'Project 2', 'Project 10', 'zeta']);- });-- it('sorts sessions by userSendAt, ignoring later updatedAt bumps', () => {- // 排序时钟 = userSendAt ?? updatedAt(以用户最近一次按下发送为主键)。- // laterSend.updatedAt 有意设得比 earlierSend 更新(模拟 agent 回复 / scheduler- // fire 只 bump updatedAt),验证这类改动不再重排:time 排序“最早优先”,- // 谁的 userSendAt 更早谁排前面,与 updatedAt 无关。+ // 排序时钟 = userSendAt ?? updatedAt(以用户最近一次按下发送为主键)。原先经+ // sortSessionsForSidebar(…, 'time') 间接验证;'time'(最早优先)2026-08-12 用户+ // 裁决删除后,直接对时钟函数断言——不变量本身没变,只是不再借道那个档位。+ it('uses userSendAt as the sort clock, ignoring later updatedAt bumps', () => {+ // laterSend.updatedAt 有意设得比 earlierSend 更新(模拟 agent 回复 / scheduler+ // fire 只 bump updatedAt),验证这类改动不影响排序时钟。const earlierSend = session({id: 'earlier-send',userSendAt: '2026-01-05T00:00:00.000Z',diff --cc apps/desktop/src/renderer/contexts/AuthContext.tsxindex 15263e6f58,112facca3c..98bc4821e5--- a/apps/desktop/src/renderer/contexts/AuthContext.tsx+++ b/apps/desktop/src/renderer/contexts/AuthContext.tsx@@@ -31,15 -34,27 +34,28 @@@ importimport { isSecondaryWindow } from '@/lib/secondaryWindow';import { setUserPromptOwner } from '@/lib/userPromptStore';import { bootstrapMemorySettingsFromMain, setMemorySettingsOwner } from '@/lib/memorySettingsStore';+ import {+ refreshChatEmbeddingFromMain,+ setChatEmbeddingSettingsOwner,+ } from '@/lib/chatEmbeddingStore';import { sessionsStore } from '@/lib/sessionsStore';+import { recentWorkdirsStore } from '@/lib/recentWorkdirsStore';import { isSidebarWindow } from '@/lib/sidebarWindow';import { isGhostPanelWindow } from '@/lib/ghostPanelWindow';+ import { setModelEnginePrefsOwner } from '@/state/modelEnginePrefs';+ import { setModelFavoritesOwner } from '@/state/modelFavorites';+ import { setProviderModelMemoryOwner } from '@/state/providerModelMemory';+ import { setFavoriteAnchorMemoryOwner } from '@/state/favoriteAnchorMemory';import { setNewMakerDraftOwner } from '@/state/newMakerDraft';+ import { setModelVisibilityOwner } from '@/state/modelVisibilityPrefs';import { setComposerDraftOwner } from '@/lib/composerDraftStore';+ import { setBotReadStateOwner } from '@/features/bots/botReadState';import { setPendingHandoffOwner } from '@/state/pendingFirstMessage';+ import { rememberSsoOrgIdentifier } from '@/state/ssoOrgHistory';+ import { setDeferredUiAssignmentOwner } from '@/features/cc-agent/deferredUiAssignment';import { invalidateProvidersSnapshot } from '@/lib/providersSnapshotStore';import { preloadLocalCatalogSnapshot } from '@/lib/localCatalogSnapshot';+ import { awaitDesktopLoginStateLoad } from '../../shared/authIpc';import { getDataOwnerGeneration, setDataOwnerGeneration } from './dataOwnerGeneration';/**diff --cc apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsxindex 9aa3a5ed22,8626e30643..44147b315b--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx@@@ -171,13 -174,16 +179,20 @@@ importgetVisibleSidebarSessionIds,pickSessionIdAfterRemoval,} from './lib/sessionRemovalNavigation';- import type {- AutomationScheduleAction,- AutomationScheduleSessionInfo,- AutomationSessionGroup,+ import { onRequestSessionSwitch, pickAdjacentSessionId } from './lib/sessionSwitchCommands';+ import {+ unreadSuccessScheduleRunIds,+ type AutomationScheduleAction,+ type AutomationScheduleSessionInfo,+ type AutomationSessionGroup,} from './lib/automationSidebarGrouping';- import { getSessionDeviceId } from '@/features/device-link/remoteProjectsStore';-import { getSessionDeviceId, remoteProjectsStore, useRemoteScheduleIndex } from '@/features/device-link/remoteProjectsStore';+import {++ getSessionDeviceId,++ remoteProjectsStore,++ useRemoteScheduleIndex,++} from '@/features/device-link/remoteProjectsStore';+ import {+ getRemoteSessionActivity,useRemoteSessionActivity,useRemoteSessionActivityRevision,} from '@/features/device-link/remoteSessionActivityStore';@@@ -208,12 -215,15 +224,17 @@@ importimport { getSessionListCollapseView } from './lib/sessionListCollapse';import { hasSessionSelectionModifier, type SessionClickModifiers } from './sidebar/SessionItem';import type { SessionMoveTarget } from './sidebar/sessionMoveTarget';- import { normalizeManualPinnedOrder, mergeVisibleReorder } from './hooks/helpers/sidebarFilterCore';+ import {+ DIALOGUE_FILTER_KEY,+ projectFilterIncludes,+ mergeVisibleReorder,+ normalizeManualPinnedOrder,+ } from './hooks/helpers/sidebarFilterCore';import {activePinnedSidebarEntryIds,+ buildPinnedSidebarRank,pinnedProjectEntryId,+ pinnedSidebarEntryComparisonKey,projectKeyFromPinnedEntryId,} from './lib/pinnedSidebarOrder';import { createLogger } from '@/lib/logger';@@@ -406,21 -404,44 +415,62 @@@ export function CCAgentSidebarUpper()const includeArchived = filter.status;const sessionsHook = useCCSessions({ includeArchived });const { sessions: allSessionsForAttention } = useCCSessions({ includeArchived: 'all' });+ const remoteProjectSessions = useRemoteProjectSessions();+ const remoteDevices = useRemoteDevices();+ const selectedMachineId = useEffectiveSelectedMachineId();const searchProjectSessions = useMemo(- () => allSessionsForAttention.filter((s) => !isOrcaWorkerSession(s)),- [allSessionsForAttention],+ () =>+ selectVisibleSessions(+ allSessionsForAttention,+ remoteProjectSessions,+ selectedMachineId,+ ).filter((session) => !isOrcaWorkerSession(session)),+ [allSessionsForAttention, remoteProjectSessions, selectedMachineId],);const projectAliases = useProjectAliases();- const searchProjectGroups = useProjectGroups(searchProjectSessions, projectAliases.aliases);+ const { entries: recentWorkdirs } = useRecentWorkdirs();+ const persistentLocalProjects = useMemo<PersistentLocalProject[]>(- () => buildPersistentLocalProjects(recentWorkdirs, searchProjectSessions, localPlatform),- [recentWorkdirs, searchProjectSessions, localPlatform],++ () => buildPersistentLocalProjects(recentWorkdirs, allSessionsForAttention, localPlatform),++ [recentWorkdirs, allSessionsForAttention, localPlatform],++ );++ const searchPersistentLocalProjects = useMemo(++ () =>++ selectedMachineId === MACHINE_ALL || selectedMachineId.includes(MACHINE_LOCAL)++ ? persistentLocalProjects++ : [],++ [persistentLocalProjects, selectedMachineId],+ );+ const searchProjectGroups = useProjectGroups(+ searchProjectSessions,+ projectAliases.aliases,+ false,- persistentLocalProjects,++ searchPersistentLocalProjects,++ localPlatform,++ );+ const restorableSelectionProjectKeys = useMemo(+ () => new Set(searchProjectGroups.projects.map((project) => project.projectKey)),+ [searchProjectGroups.projects],+ );+ const restorableSelectionProjectKeysRef = useRef(restorableSelectionProjectKeys);+ restorableSelectionProjectKeysRef.current = restorableSelectionProjectKeys;+ useLayoutEffect(+ () =>+ registerSidebarProjectRestoreHandler((projectKey) =>+ restoreSelectedHiddenProject({+ projectKey,+ hiddenProjectKeys,+ setProjectHidden: hiddenProjects.setProjectHidden,+ getCurrentProjectKeys: () => restorableSelectionProjectKeysRef.current,+ ensureProjectIncluded: filter.ensureProjectIncluded,+ localPlatform,+ }),+ ),+ [+ filter.ensureProjectIncluded,+ hiddenProjectKeys,+ hiddenProjects.setProjectHidden,+ localPlatform,+ ],);const visibleSearchProjects = useMemo(() => visibleSidebarProjects(searchProjectGroups.projects, hiddenProjectKeys, localPlatform),@@@ -623,16 -638,9 +667,16 @@@const fullActivePinnedIds = activePinnedSidebarEntryIds(filter.manualPinnedOrder,pinnedSessionIds,+ localPlatform,+ );++ const comparisonKey = (entryId: string) =>++ pinnedSidebarEntryComparisonKey(entryId, localPlatform);+ const baseOrder = normalizeManualPinnedOrder(+ filter.manualPinnedOrder,+ fullActivePinnedIds,- (entryId) => pinnedSidebarEntryComparisonKey(entryId, localPlatform),- );- const merged = mergeVisibleReorder(baseOrder, visibleNewOrder, (entryId) =>- pinnedSidebarEntryComparisonKey(entryId, localPlatform),++ comparisonKey,);- const baseOrder = normalizeManualPinnedOrder(filter.manualPinnedOrder, fullActivePinnedIds);- const merged = mergeVisibleReorder(baseOrder, visibleNewOrder);++ const merged = mergeVisibleReorder(baseOrder, visibleNewOrder, comparisonKey);void filter.setManualPinnedOrder(merged, fullActivePinnedIds, baseOrder).catch((err) => {log.warn('failed to persist rail pinned order', err);toast.error(t('ccAgent.sidebar.pinFailed'));@@@ -791,8 -758,7 +795,8 @@@ interface ExpandedPropsfilter: UseSidebarFilterReturn;hiddenProjects: UseHiddenProjectsReturn;projectAliases: ReturnType<typeof useProjectAliases>;- scheduleSessionIndex: ReturnType<typeof useAutomationScheduleSessionIndex>;+ scheduleSessionIndex: ReturnType<typeof usePublishedAutomationScheduleSessionIndex>;+ persistentLocalProjects: readonly PersistentLocalProject[];}/** rail 未分类隐藏态的空列表(引用稳定,免得 lampScope 发布 effect 空转)。 */@@@ -1096,8 -1079,10 +1118,12 @@@ function ExpandedView(const markAutomationSessionRunsRead = useCallback((sessionId: string) => {- const info = scheduleSessionIndex.get(sessionId);- if (!info?.unreadRunIds.length) return;- const info = remoteProjectsStore.getSessionScheduleInfo(sessionId) ?? scheduleSessionIndex.get(sessionId);++ const info =++ remoteProjectsStore.getSessionScheduleInfo(sessionId) ??++ scheduleSessionIndex.get(sessionId);+ // 成功进入即已读;历史失败在任务内容实际展示时确认,保留横幅、只清红点。+ const successUnreadRunIds = info ? unreadSuccessScheduleRunIds(info) : [];+ if (successUnreadRunIds.length === 0) return;// …AndSync:settle 后无条件触发 renderer 本地刷新。跨实例场景下这些 runId// 可能在 DB 里早已被另一实例标为已读(main no-op 且不广播),没有本地刷新// 通道的话,这里的过期未读快照永远等不到事件、红点无法自愈。@@@ -1155,14 -1173,30 +1214,37 @@@// 机器切换栏选中机器后整体过滤:本机 → 只本地会话;远程 → 只该机器会话。// 过滤在源头做,下游 grouping / pinned / projects / dialogues / date-grouped / search 自动继承。const selectedMachineId = useEffectiveSelectedMachineId();+ const visiblePersistentLocalProjects = useMemo(+ () =>+ selectedMachineId === MACHINE_ALL || selectedMachineId.includes(MACHINE_LOCAL)+ ? persistentLocalProjects+ : [],+ [persistentLocalProjects, selectedMachineId],+ );+ const localHostProjectOrder = useLocalHostProjectOrder({+ custom: filter.projectOrder === 'custom',+ keys: filter.manualProjectOrder,+ });+ const { orders: remoteHostProjectOrders } = useRemoteHostProjectOrders(selectedMachineId);const switcherDevices = useSwitcherDevices();+ // E 期「按设备分组」:远程设备顺序 + 名称/在线状态(设备切换栏同序同源)。+ // 空 map = 没有远程设备 → ProjectsSection 隐藏该分组选项、不切段。+ const remoteDeviceIndex = useMemo(() => {+ const index = new Map<string, { name: string; online: boolean }>();+ for (const device of switcherDevices) {+ if (device.status === 'rejected') continue;+ // connecting 含两种:真在连,以及断线缓存。后者不能撑开设备分组,+ // 否则最后一台远程掉线后仍会留下「本机」段头;重连后偏好自动恢复。+ if (device.status === 'connecting' && isRemoteDeviceMarkedDisconnected(device.deviceId)) {+ continue;+ }+ index.set(device.deviceId, {+ name: device.name,+ online: device.status === 'connected',+ });+ }+ return index;+ }, [switcherDevices]);const deviceListSettled = useDeviceLinkDeviceListSettled();const selectedDialogueDeviceResolution = useMemo(() => resolveDialogueDeviceTarget(selectedMachineId, switcherDevices, deviceListSettled),@@@ -1321,58 -1355,26 +1403,58 @@@if (cutoff === null) return sidebarSessions;return sidebarSessions.filter((s) => sessionActivityMs(s) >= cutoff);}, [sidebarSessions, filter.lastActivity]);+ const activityFilteredPersistentLocalProjects = useMemo(+ () =>+ filterPersistentLocalProjectsByLastActivity(+ visiblePersistentLocalProjects,+ cutoffForLastActivity(filter.lastActivity),+ ),+ [filter.lastActivity, visiblePersistentLocalProjects],+ );/* ---- Grouping & collapse ---- */- const allGroups = useProjectGroups(sidebarSessions, projectAliases.aliases);- const groups = useProjectGroups(activityFilteredSessions, projectAliases.aliases);+ const allGroups = useProjectGroups(+ sidebarSessions,+ projectAliases.aliases,+ false,+ visiblePersistentLocalProjects,++ localPlatform,+ );+ const groups = useProjectGroups(+ activityFilteredSessions,+ projectAliases.aliases,+ false,+ activityFilteredPersistentLocalProjects,++ localPlatform,+ );// 普通项目目录也需要保留「所有会话都已单独置顶」的项目身份,供用户继续// 从 ProjectNode 菜单置顶整个项目;实际项目子行在渲染前仍会排除已置顶会话。const groupsWithPinnedProjects = useProjectGroups(activityFilteredSessions,projectAliases.aliases,true,+ activityFilteredPersistentLocalProjects,++ localPlatform,);// Project pinning is independent from conversation pinning. This catalogue// keeps pinned conversations inside their project solely for project identity// and project-level actions; the normal project tree above remains deduped.- const allProjectGroups = useProjectGroups(sidebarSessions, projectAliases.aliases, true);+ const allProjectGroups = useProjectGroups(+ sidebarSessions,+ projectAliases.aliases,+ true,+ visiblePersistentLocalProjects,++ localPlatform,+ );const activeWorkingDirs = useMemo(() => allProjectGroups.projects.map((p) => p.projectKey),[allProjectGroups.projects],);- const collapse = useCollapsedProjects(activeWorkingDirs, sidebarSettingsSnapshot.dataOwnerId);+ const collapse = useCollapsedProjects(+ activeWorkingDirs,+ sidebarSettingsSnapshot.dataOwnerId,+ localPlatform,+ );- const collapsedProjectComparisonKeys = useMemo(- () => buildProjectKeyComparisonSet(collapse.collapsed, localPlatform),- [collapse.collapsed, localPlatform],- );// 项目过滤 GC 的「宇宙」用**全量**(不按机器过滤)项目键 —— 否则在某机器作用域下 remount,// gcProjectsAgainstActive 会把其它机器的项目从已保存的项目过滤里误删(它们只是被切换栏隐藏、@@@ -1382,12 -1384,7 +1464,13 @@@() => [...sessions, ...remoteProjectSessions].filter(passesOrcaAndStatus),[sessions, remoteProjectSessions, passesOrcaAndStatus],);- const projectUniverse = useProjectGroups(unfilteredProjectSessions, projectAliases.aliases, true);+ const projectUniverse = useProjectGroups(+ unfilteredProjectSessions,+ projectAliases.aliases,+ true,+ persistentLocalProjects,++ localPlatform,+ );// Visibility is a negative overlay only. Keep the raw universe above for// filter/manual-order GC, and expose a separate catalogue to sidebar UI.const visibleProjectUniverse = useMemo(@@@ -1525,17 -1515,16 +1601,29 @@@}return keys;}, [filter.manualPinnedOrder]);++ const pinnedProjectComparisonKeys = useMemo(++ () => buildProjectKeyComparisonSet(pinnedProjectKeys, localPlatform),++ [pinnedProjectKeys, localPlatform],++ );const restorableProjectKeys = useMemo(() =>collectRestorableProjectKeys({sessions: scopedSidebarSessions,++ persistentLocalProjects: visiblePersistentLocalProjects,lastActivityCutoff: cutoffForLastActivity(filter.lastActivity),pinnedProjectKeys,vendorPredicate,+ localPlatform,}),- [filter.lastActivity, localPlatform, pinnedProjectKeys, scopedSidebarSessions, vendorPredicate],- [filter.lastActivity, pinnedProjectKeys, scopedSidebarSessions, vendorPredicate],++ [++ filter.lastActivity,++ localPlatform,++ pinnedProjectKeys,++ scopedSidebarSessions,++ vendorPredicate,++ visiblePersistentLocalProjects,++ ],);const restorableProjectKeysRef = useRef(restorableProjectKeys);restorableProjectKeysRef.current = restorableProjectKeys;@@@ -1576,26 -1552,7 +1651,10 @@@) {return [];}- if (!pinnedProjectKeys.has(project.projectKey)) return [];+ if (+ !projectKeyComparisonSetHas(pinnedProjectComparisonKeys, project.projectKey, localPlatform)+ )+ return [];- if (- allowedProjectComparisonKeys !== null &&- !projectKeyComparisonSetHas(allowedProjectComparisonKeys, project.projectKey, localPlatform)- )- return [];-- const matchingSessions = vendorPredicate- ? project.sessions.filter(vendorPredicate)- : project.sessions;- if (- vendorPredicate &&- matchingSessions.length === 0 &&- !persistentProjectMatchesVendor(project, filter.vendor)- ) {- return [];- }return [{@@@ -1606,15 -1563,7 +1665,12 @@@},];});- }, [allProjectGroups.projects, hiddenProjectComparisonKeys, localPlatform, pinnedProjectKeys]);+ }, [+ allProjectGroups.projects,+ hiddenProjectComparisonKeys,- pinnedProjectComparisonKeys,- allowedProjectComparisonKeys,- filter.vendor,+ localPlatform,- vendorPredicate,++ pinnedProjectComparisonKeys,+ ]);const visiblePinnedEntries = useMemo<PinnedSidebarEntry[]>(() => {const entries: PinnedSidebarEntry[] = [@@@ -1673,22 -1623,44 +1731,50 @@@[visibleDialogues, dialogueSortBy],);+ const hostProjectSort = useMemo(() => {+ const scope = projectOrderWriteScopeForSelection(selectedMachineId);+ const hostSnapshot =+ scope.kind === 'host' && scope.deviceId === null+ ? localHostProjectOrder.snapshot+ : scope.kind === 'host' && scope.deviceId+ ? remoteHostProjectOrders.get(scope.deviceId)+ : undefined;+ const hostManual =+ scope.kind === 'host' && scope.deviceId === null+ ? localHostProjectOrder.snapshot.manualProjectOrder+ : scope.kind === 'host' && scope.deviceId+ ? (controllerManualOrderForDevice(scope.deviceId, hostSnapshot) ?? [])+ : [];+ const displayed = resolveDisplayedProjectOrder(scope, hostSnapshot, filter, hostManual);+ return {+ order: displayed.manualProjectOrder,+ projectOrder: displayed.projectOrder,+ sortBy: filter.sortBy,+ };+ }, [+ filter.manualProjectOrder,+ filter.projectOrder,+ filter.sortBy,+ localHostProjectOrder.snapshot,+ remoteHostProjectOrders,+ selectedMachineId,+ ]);+const visibleProjectsWithVendor = useMemo(() => {const unpinnedProjects = visibleProjects.filter(- (project) => !pinnedProjectKeys.has(project.projectKey),+ (project) =>+ !projectKeyComparisonSetHas(pinnedProjectComparisonKeys, project.projectKey, localPlatform),);const projects = unpinnedProjects.flatMap((project) => {const matchingSessions = vendorPredicate? project.sessions.filter(vendorPredicate): project.sessions;- if (matchingSessions.length === 0) return [];+ if (+ matchingSessions.length === 0 &&+ (!project.isPersistentLocal ||+ (vendorPredicate && !persistentProjectMatchesVendor(project, filter.vendor)))- ) {++ )+ return [];- }return [{...project,@@@ -1698,19 -1670,11 +1784,19 @@@});return sortProjectsForSidebar(projects,- filter.sortBy,- filter.manualProjectOrder,+ hostProjectSort.sortBy,+ hostProjectSort.order,+ hostProjectSort.projectOrder,+ localPlatform,);- }, [visibleProjects, pinnedProjectKeys, vendorPredicate, hostProjectSort]);+ }, [+ visibleProjects,+ pinnedProjectComparisonKeys,++ localPlatform,+ vendorPredicate,+ filter.vendor,- filter.sortBy,- filter.manualProjectOrder,- localPlatform,++ hostProjectSort,+ ]);// 折叠 rail 没有独立的 Pinned 项目瓷砖,因此项目面板必须保留置顶项目,// 否则侧栏折叠后这些项目及其取消置顶入口都会完全不可达。@@@ -1719,13 -1683,7 +1805,12 @@@const matchingSessions = vendorPredicate? project.sessions.filter(vendorPredicate): project.sessions;- if (matchingSessions.length === 0) return [];+ if (+ matchingSessions.length === 0 &&+ (!project.isPersistentLocal ||+ (vendorPredicate && !persistentProjectMatchesVendor(project, filter.vendor)))- ) {++ )+ return [];- }return [{...project,@@@ -1735,18 -1693,11 +1820,12 @@@});return sortProjectsForSidebar(projects,- filter.sortBy,- filter.manualProjectOrder,+ hostProjectSort.sortBy,+ hostProjectSort.order,+ hostProjectSort.projectOrder,+ localPlatform,);- }, [- visibleProjects,- vendorPredicate,- filter.vendor,- filter.sortBy,- filter.manualProjectOrder,- localPlatform,- ]);- }, [visibleProjects, vendorPredicate, hostProjectSort]);++ }, [visibleProjects, vendorPredicate, filter.vendor, hostProjectSort, localPlatform]);/*** Pinned 拖拽落定回调。SortableList 给的是当前 visible(含 vendor / projectsFilter@@@ -1768,51 -1719,28 +1847,35 @@@const fullActivePinnedIds = activePinnedSidebarEntryIds(filter.manualPinnedOrder,pinnedSessionIds,+ localPlatform,+ );++ const comparisonKey = (entryId: string) =>++ pinnedSidebarEntryComparisonKey(entryId, localPlatform);+ const baseOrder = normalizeManualPinnedOrder(+ filter.manualPinnedOrder,+ fullActivePinnedIds,- (entryId) => pinnedSidebarEntryComparisonKey(entryId, localPlatform),- );- const merged = mergeVisibleReorder(baseOrder, visibleNewOrder, (entryId) =>- pinnedSidebarEntryComparisonKey(entryId, localPlatform),++ comparisonKey,);- const baseOrder = normalizeManualPinnedOrder(filter.manualPinnedOrder, fullActivePinnedIds);- const merged = mergeVisibleReorder(baseOrder, visibleNewOrder);++ const merged = mergeVisibleReorder(baseOrder, visibleNewOrder, comparisonKey);void filter.setManualPinnedOrder(merged, fullActivePinnedIds, baseOrder).catch((err) => {log.warn('failed to persist pinned order', err);toast.error(t('ccAgent.sidebar.pinFailed'));});},- [sessions, remoteProjectSessions, filter, t],+ [sessions, remoteProjectSessions, filter, localPlatform, t],);- const visibleDateSessions = useMemo(() => {- return activityFilteredSessions.filter((s) => {- if (s.pinnedAt != null) return false;- if (vendorPredicate && !vendorPredicate(s)) return false;- if (s.workspaceKind !== 'dialogue') {- if (isSessionInProjectComparisonSet(s, pinnedProjectComparisonKeys, localPlatform)) {- return false;- }- }- if (allowedProjectComparisonKeys === null) return true;- return isSessionInProjectComparisonSet(s, allowedProjectComparisonKeys, localPlatform);- });- }, [- activityFilteredSessions,- vendorPredicate,- allowedProjectComparisonKeys,- pinnedProjectComparisonKeys,- localPlatform,- ]);-+ // D 期:按日期分组已删除(visibleDateSessions 随 DateGroupedSessionsSection 一并下线)。const hasVisibleSidebarContent =visiblePinnedEntries.length > 0 ||- (filter.groupBy === 'date'- ? visibleDateSessions.length > 0- : visibleUnclassified.length > 0 ||- visibleProjectsWithVendor.length > 0 ||- visibleDialogues.length > 0);+ visibleUnclassified.length > 0 ||+ visibleProjectsWithVendor.length > 0 ||+ visibleDialogues.length > 0;+ // 与 ProjectsSection.deviceGroupingAvailable 同一门控:范围收窄到单台机器时+ // 「按设备分组」选项隐藏。占位分支也要挂范围标题,不能各写一份。+ const deviceGroupingAvailable =+ (remoteDeviceIndex?.size ?? 0) > 0 &&+ !(selectedMachineId !== MACHINE_ALL && selectedMachineId.length === 1);const [selectedSessionIds, setSelectedSessionIds] = useState<Set<string>>(() => new Set());const [selectionAnchorSessionId, setSelectionAnchorSessionId] = useState<string | null>(null);diff --cc apps/desktop/src/renderer/features/cc-agent/hooks/helpers/sidebarFilterCore.tsindex 02bf4b1203,de77a3ca1c..bcabb29b64--- a/apps/desktop/src/renderer/features/cc-agent/hooks/helpers/sidebarFilterCore.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/helpers/sidebarFilterCore.ts@@@ -322,13 -457,16 +456,20 @@@ export function persistLastActivity(las/* ============================== sortBy load/persist ============================== */-const SORT_BY_VALUES: ReadonlySet<string> = new Set<FilterSortBy>(['recency', 'created', 'priority']);+const SORT_BY_VALUES: ReadonlySet<string> = new Set<FilterSortBy>([+ 'recency',- 'time',- 'manual',- 'alphabetic',++ 'created',++ 'priority',++]);+ const PROJECT_ORDER_VALUES: ReadonlySet<string> = new Set<FilterProjectOrder>([+ 'activity',+ 'custom',]);+ /**+ * 读 sortBy。已删除的 'alphabetic' / 'time' / 'manual' 存量值不在合法集合内,+ * 自动回退 'recency'。旧 'manual' 的项目序由 loadProjectOrder / migrateLegacyManualSort 接手。+ */export function loadSortBy(): FilterSortBy {const storage = safeStorage();if (!storage) return 'recency';@@@ -386,32 -643,13 +646,29 @@@ export function persistManualProjectOrdexport function normalizeManualProjectOrder(prev: readonly string[],activeWorkingDirs: readonly string[],+ localPlatform: string = '',): string[] {+ const activeKeys = normalizeProjectKeyList(activeWorkingDirs, localPlatform);- const activeSet = new Set(++ const activeIdentities = new Set(+ activeKeys.map((key) => projectKeyComparisonKey(key, localPlatform) ?? key),+ );+ const prevKeys: string[] = [];+ const seen = new Set<string>();- const next: string[] = [];-for (const wd of prev) {const key = normalizeProjectKey(wd);- if (key) prevKeys.push(key);+ if (!key) continue;- const comparisonKey = projectKeyComparisonKey(key, localPlatform) ?? key;- if (!activeSet.has(comparisonKey) || seen.has(comparisonKey)) continue;- seen.add(comparisonKey);- next.push(key);++ const identity = projectKeyComparisonKey(key, localPlatform) ?? key;++ if (!activeIdentities.has(identity) || seen.has(identity)) continue;++ seen.add(identity);++ prevKeys.push(key);+ }-+ for (const key of activeKeys) {- const comparisonKey = projectKeyComparisonKey(key, localPlatform) ?? key;- if (seen.has(comparisonKey)) continue;- seen.add(comparisonKey);- next.push(key);++ const identity = projectKeyComparisonKey(key, localPlatform) ?? key;++ if (seen.has(identity)) continue;++ seen.add(identity);++ prevKeys.push(key);}-- return next;- return reconcileManualProjectOrder(prevKeys, normalizeProjectKeyList(activeWorkingDirs));++ return prevKeys;}export function moveManualProjectOrder(@@@ -420,32 -658,21 +677,32 @@@sourceWorkingDir: string,targetWorkingDir: string,position: ManualProjectDropPosition,+ localPlatform: string = '',): string[] {- const normalized = normalizeManualProjectOrder(prev, activeWorkingDirs);+ const normalized = normalizeManualProjectOrder(prev, activeWorkingDirs, localPlatform);const sourceKey = normalizeProjectKey(sourceWorkingDir);const targetKey = normalizeProjectKey(targetWorkingDir);- if (!sourceKey || !targetKey || sourceKey === targetKey) return normalized;- const sourceIndex = normalized.indexOf(sourceKey);- const targetIndex = normalized.indexOf(targetKey);+ if (!sourceKey || !targetKey) return normalized;- const sourceComparisonKey = projectKeyComparisonKey(sourceKey, localPlatform) ?? sourceKey;- const targetComparisonKey = projectKeyComparisonKey(targetKey, localPlatform) ?? targetKey;- if (sourceComparisonKey === targetComparisonKey) return normalized;++ const sourceIdentity = projectKeyComparisonKey(sourceKey, localPlatform) ?? sourceKey;++ const targetIdentity = projectKeyComparisonKey(targetKey, localPlatform) ?? targetKey;++ if (sourceIdentity === targetIdentity) return normalized;+ const sourceIndex = normalized.findIndex(- (key) => (projectKeyComparisonKey(key, localPlatform) ?? key) === sourceComparisonKey,++ (key) => (projectKeyComparisonKey(key, localPlatform) ?? key) === sourceIdentity,+ );+ const targetIndex = normalized.findIndex(- (key) => (projectKeyComparisonKey(key, localPlatform) ?? key) === targetComparisonKey,++ (key) => (projectKeyComparisonKey(key, localPlatform) ?? key) === targetIdentity,+ );if (sourceIndex < 0 || targetIndex < 0) return normalized;+ const sourceRepresentative = normalized[sourceIndex] as string;const withoutSource = normalized.slice();withoutSource.splice(sourceIndex, 1);- const targetIndexAfterRemoval = withoutSource.indexOf(targetKey);+ const targetIndexAfterRemoval = withoutSource.findIndex(- (key) => (projectKeyComparisonKey(key, localPlatform) ?? key) === targetComparisonKey,++ (key) => (projectKeyComparisonKey(key, localPlatform) ?? key) === targetIdentity,+ );if (targetIndexAfterRemoval < 0) return normalized;const insertIndex = position === 'after' ? targetIndexAfterRemoval + 1 : targetIndexAfterRemoval;- withoutSource.splice(insertIndex, 0, sourceKey);+ withoutSource.splice(insertIndex, 0, sourceRepresentative);return withoutSource;}@@@ -589,6 -807,18 +846,23 @@@ export function mergeVisibleReorderreturn result;}+ /**+ * 第一次切到手动项目顺序:用切换前的可见视觉序填回全量 baseline 的可见槽位。+ * 隐藏项(其它机器 / 筛选)原位保留,不能把可见子集当成完整序再把其余甩到末尾。+ */+ export function snapshotManualProjectOrder(+ visualVisibleKeys: readonly string[],+ baselineKeys: readonly string[],++ localPlatform: string = '',+ ): string[] {- const fullOrder = normalizeManualProjectOrder([], baselineKeys);- return mergeVisibleReorder(fullOrder, visualVisibleKeys);++ const fullOrder = normalizeManualProjectOrder([], baselineKeys, localPlatform);++ return mergeVisibleReorder(++ fullOrder,++ visualVisibleKeys,++ (projectKey) => projectKeyComparisonKey(projectKey, localPlatform) ?? projectKey,++ );+ }+/*** GC:剔除 prev 中已不在 activeWorkingDirs 集合内的条目。* - prev === 'all' → 直接返回 prev(无变化)@@@ -616,15 -848,38 +892,36 @@@ export function gcProjectsAgainstActivereturn filtered;}+ function normalizeFilterEntry(raw: unknown): string | null {+ if (typeof raw !== 'string') return null;+ if (raw === DIALOGUE_FILTER_KEY) return DIALOGUE_FILTER_KEY;+ return normalizeProjectKey(raw);+ }+-function normalizeFilterProjectList(- values: readonly unknown[],- localPlatform?: string,-): string[] {++function normalizeFilterProjectList(values: readonly unknown[], localPlatform?: string): string[] {+ const seen = new Set<string>();+ const out: string[] = [];+ for (const value of values) {+ const key = normalizeFilterEntry(value);+ if (!key) continue;- const identity = localPlatform == null- ? key- : (projectFilterEntryIdentity(key, localPlatform) ?? key);++ const identity =++ localPlatform == null ? key : (projectFilterEntryIdentity(key, localPlatform) ?? key);+ if (seen.has(identity)) continue;+ seen.add(identity);+ out.push(key);+ }+ return out;+ }+-function normalizeProjectKeyList(values: readonly unknown[]): string[] {+function normalizeProjectKeyList(values: readonly unknown[], localPlatform: string = ''): string[] {const seen = new Set<string>();const out: string[] = [];for (const value of values) {const key = typeof value === 'string' ? normalizeProjectKey(value) : null;- if (!key || seen.has(key)) continue;- seen.add(key);+ if (!key) continue;- const comparisonKey = projectKeyComparisonKey(key, localPlatform) ?? key;- if (seen.has(comparisonKey)) continue;- seen.add(comparisonKey);++ const identity = projectKeyComparisonKey(key, localPlatform) ?? key;++ if (seen.has(identity)) continue;++ seen.add(identity);out.push(key);}return out;diff --cc apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.tsindex a6971b4997,d38e0bddf8..66a9baf7d9--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts@@@ -12,34 -12,43 +12,59 @@@ import { useMemo } from 'react'import type { Session } from '@/lib/ccAgent.types';import { useRemoteSshHosts } from '@/hooks/useRemoteSshHosts';+ import { buildBotSessionOwners } from '@/features/bots/botSessionOwners';+ import { useBotProfiles } from '@/features/bots/botStore';-import { groupSessions, type ProjectGroupsResult } from '../lib/projectGrouping';+import {+ groupSessions,+ type PersistentLocalProject,+ type ProjectGroupsResult,+} from '../lib/projectGrouping';- import { resolveRemoteProjectMachineIdentity } from '../lib/remoteProjectIdentity';+ import {+ collectAmbiguousDeviceNames,+ resolveRemoteProjectMachineIdentity,+ } from '../lib/remoteProjectIdentity';export function useProjectGroups(sessions: readonly Session[],projectAliases?: ReadonlyMap<string, string>,includePinnedInProjects: boolean = false,+ persistentLocalProjects?: readonly PersistentLocalProject[],++ localPlatform: string = '',): ProjectGroupsResult {const sshHosts = useRemoteSshHosts();+ /*+ 伙伴归属表。会话行本身不带 botId,归属只有伙伴档案知道 —— 档案还没加载完的+ 那一瞬间这张表是空的,伙伴任务就走原来的分组落到别处,**不会消失**。+ */+ const botProfiles = useBotProfiles();+ const botOwnerBySessionId = useMemo(() => buildBotSessionOwners(botProfiles), [botProfiles]);return useMemo(() => {const groups = groupSessions(sessions, {projectAliases,includePinnedInProjects,+ botOwnerBySessionId,+ persistentLocalProjects,- localPlatform: window.electronAPI.platform,++ localPlatform,});+ // 撞名判定要看全量项目(哪些设备名对应了多个 deviceId),所以先扫一遍再逐个富化。+ const ambiguousDeviceNames = collectAmbiguousDeviceNames(groups.projects);return {...groups,projects: groups.projects.map((project) => ({...project,- remoteMachineIdentity: resolveRemoteProjectMachineIdentity(project, sshHosts),+ remoteMachineIdentity: resolveRemoteProjectMachineIdentity(project, sshHosts, {+ ambiguousDeviceNames,+ }),})),};- }, [sessions, projectAliases, includePinnedInProjects, persistentLocalProjects, sshHosts]);- }, [sessions, projectAliases, includePinnedInProjects, sshHosts, botOwnerBySessionId]);++ }, [++ sessions,++ projectAliases,++ includePinnedInProjects,++ persistentLocalProjects,++ localPlatform,++ sshHosts,++ botOwnerBySessionId,++ ]);}diff --cc apps/desktop/src/renderer/features/cc-agent/hooks/useSidebarFilter.tsindex 5c2f684fbb,50d23b029f..3169c6b80b--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useSidebarFilter.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useSidebarFilter.ts@@@ -46,11 -48,10 +48,11 @@@ import { useCallback, useEffect, useLayimport { createLogger } from '@/lib/logger';import { isDataOwnerPushStampCurrent } from '@/contexts/dataOwnerGeneration';import type { DataOwnerPushStamp } from '../../../../shared/dataOwnerPush';--import type {-- SidebarPinnedOrderMutation,-- SidebarSettingsSnapshot,++import {++ sidebarPinnedEntryComparisonKey,++ type SidebarPinnedOrderMutation,++ type SidebarSettingsSnapshot,} from '../../../../shared/sidebarSettings';- import { pinnedSidebarEntryComparisonKey } from '../lib/pinnedSidebarOrder';import {loadStatus,@@@ -409,14 -442,18 +443,18 @@@ export function useSidebarFilterconst gc = useCallback((activeWorkingDirs: readonly string[]) => {setProjectsState((prev) => {- const next = gcProjectsAgainstActive(prev, activeWorkingDirs, localPlatform);- const next = gcProjectsAgainstActive(- prev,- activeWorkingDirs,- window.electronAPI.platform,- );++ const next = gcProjectsAgainstActive(prev, activeWorkingDirs, window.electronAPI.platform);if (next === prev) return prev;persistProjects(next, ownerId);return next;});setManualProjectOrderState((prev) => {if (prev.length === 0) return prev;- const next = normalizeManualProjectOrder(prev, activeWorkingDirs, localPlatform);- const next = normalizeManualProjectOrder(prev, activeWorkingDirs);++ const next = normalizeManualProjectOrder(++ prev,++ activeWorkingDirs,++ window.electronAPI.platform,++ );if (next.length === prev.length && next.every((wd, index) => wd === prev[index]))return prev;persistManualProjectOrder(next, ownerId);@@@ -454,7 -520,7 +521,11 @@@const setManualProjectOrder = useCallback((order: readonly string[], activeWorkingDirs: readonly string[]) => {setManualProjectOrderState((prev) => {- const next = normalizeManualProjectOrder(order, activeWorkingDirs, localPlatform);- const next = normalizeManualProjectOrder(order, activeWorkingDirs);++ const next = normalizeManualProjectOrder(++ order,++ activeWorkingDirs,++ window.electronAPI.platform,++ );if (next.length === prev.length && next.every((wd, index) => wd === prev[index]))return prev;persistManualProjectOrder(next, ownerId);@@@ -467,10 -533,7 +538,10 @@@const setManualPinnedOrder = useCallback((order: readonly string[], activeEntryIds: readonly string[], baseOrder: readonly string[]) =>updatePinnedOrder(- () => normalizeManualPinnedOrder(order, activeEntryIds),+ () =>+ normalizeManualPinnedOrder(order, activeEntryIds, (entryId) =>- pinnedSidebarEntryComparisonKey(entryId, localPlatform),++ sidebarPinnedEntryComparisonKey(entryId, window.electronAPI.platform),+ ),(_latestOrder, nextOrder) => ({kind: 'reorder',baseOrder: Array.from(baseOrder),@@@ -483,33 -546,22 +554,39 @@@const promotePin = useCallback((entryId: string) =>updatePinnedOrder(- (prev) =>- prev[0] === entryId- ? Array.from(prev)- : [entryId, ...prev.filter((id) => id !== entryId)],+ (prev) => {- const identity = pinnedSidebarEntryComparisonKey(entryId, localPlatform);- const firstMatches =- pinnedSidebarEntryComparisonKey(prev[0] ?? '', localPlatform) === identity;- const remaining = prev.filter(- (id) => pinnedSidebarEntryComparisonKey(id, localPlatform) !== identity,++ const identity = sidebarPinnedEntryComparisonKey(++ entryId,++ window.electronAPI.platform,+ );- if (firstMatches && remaining.length === prev.length - 1) return Array.from(prev);- return [firstMatches ? prev[0]! : entryId, ...remaining];++ return [++ entryId,++ ...prev.filter(++ (id) =>++ sidebarPinnedEntryComparisonKey(id, window.electronAPI.platform) !== identity,++ ),++ ];+ },() => ({ kind: 'promote', entryId }),),- [localPlatform, updatePinnedOrder],+ [updatePinnedOrder],);const removePin = useCallback((entryId: string) =>updatePinnedOrder(- (prev) => (prev.includes(entryId) ? prev.filter((id) => id !== entryId) : Array.from(prev)),+ (prev) => {- const identity = pinnedSidebarEntryComparisonKey(entryId, localPlatform);++ const identity = sidebarPinnedEntryComparisonKey(++ entryId,++ window.electronAPI.platform,++ );+ return prev.filter(- (id) => pinnedSidebarEntryComparisonKey(id, localPlatform) !== identity,++ (id) => sidebarPinnedEntryComparisonKey(id, window.electronAPI.platform) !== identity,+ );+ },() => ({ kind: 'remove', entryId }),),- [localPlatform, updatePinnedOrder],+ [updatePinnedOrder],);const isSessionContentFiltered =diff --cc apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.tsindex 6314b5dcde,4c6854c5af..cf655a6b16--- a/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.ts+++ b/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.ts@@@ -91,12 -96,34 +91,38 @@@ export interface ProjectNodesessions: Session[];/** 组内任意 session 的最大 sortTime(userSendAt ?? updatedAt),用于 Project 间排序 */latestActivityAt: string;+ /** 来自本地持久项目目录;即使当前视图没有匹配会话也应保留项目节点。 */+ isPersistentLocal?: boolean;+ /** 该持久项目在全量本地会话中出现过的 agentKind;空数组表示真正零会话。 */+ persistentLocalKnownAgentKinds?: readonly string[];}+ /**+ * 一个伙伴名下的全部任务。+ *+ * 与项目分组并列而不是嵌进去:**项目是磁盘上的实体目录,伙伴名是用户自己起的**,+ * 两套键天然不冲突。同一个伙伴可以在多个项目里干活,同一个项目也可以有多个伙伴,+ * 硬塞进一棵树只会两头都别扭。+ */+ export interface BotGroupNode {+ botId: string;+ /** 用户给伙伴起的名字。 */+ displayName: string;+ avatar: string;+ avatarColor: string;+ /** 该伙伴名下所有任务,已按 status 然后 sortTime desc 排序。 */+ sessions: Session[];+ latestActivityAt: string;+ }++ /** 分组时用来认伙伴的最小信息。渲染层从 botStore 的会话投影现拼。 */+ export interface BotSessionOwner {+ botId: string;+ displayName: string;+ avatar: string;+ avatarColor: string;+ }+export interface ProjectGroupsResult {pinned: Session[];dialogues: Session[];@@@ -113,26 -142,18 +141,36 @@@ export interface GroupSessionsOptions* when every conversation inside it is pinned.*/includePinnedInProjects?: boolean;+ /** Resource catalogues include created project sessions even before their first message. */+ includeDraftsInProjects?: boolean;+ /** 与会话生命周期解耦的本地项目目录,用于保留零会话项目。 */+ persistentLocalProjects?: readonly PersistentLocalProject[];+ /** 本地路径身份比较所需的平台;Windows 盘符与 UNC 路径忽略大小写。 */+ localPlatform?: string;+ /**+ * sessionId → 它属于哪个伙伴。+ *+ * 不给(或某条会话不在表里)时,伙伴任务按普通会话走原来的分组 —— 这是刻意的+ * 降级:伙伴档案还没加载完的那一瞬间,宁可让任务落到未分类,也不能让它**整个+ * 消失**。会话本身不带 botId,归属只有伙伴档案知道。+ */+ botOwnerBySessionId?: ReadonlyMap<string, BotSessionOwner>;}+export interface PersistentLocalProject {+ workingDir: string;+ lastUsedAt: string;+ /** 全量本地会话历史中的 agentKind;用于区分真正空项目与 vendor 不匹配。 */+ knownAgentKinds: readonly string[];+}++export interface RecentLocalProjectEntry {+ path: string;+ lastUsedAt: string;+ /** 持久层从包含软删除行的会话历史聚合出的 agentKind。 */+ knownAgentKinds?: readonly string[];+}+/* ============================== normalize ============================== *//**@@@ -149,67 -170,6 +187,62 @@@*/export const normalizeWorkingDir = normalizeWorkingDirForGrouping;+export function buildPersistentLocalProjects(+ entries: readonly RecentLocalProjectEntry[],+ sessions: readonly Session[],+ localPlatform: string,+): PersistentLocalProject[] {+ const knownKindsByComparisonKey = new Map<string, Set<string>>();+ for (const session of sessions) {+ if (+ session.workspaceKind === 'dialogue' ||+ session.remoteHostId != null ||+ session.deviceLinkDeviceId != null+ ) {+ continue;+ }+ const projectKey = projectIdentityKeyForSession(session);+ const comparisonKey = projectKeyComparisonKey(projectKey, localPlatform);+ if (!comparisonKey) continue;+ let kinds = knownKindsByComparisonKey.get(comparisonKey);+ if (!kinds) {+ kinds = new Set<string>();+ knownKindsByComparisonKey.set(comparisonKey, kinds);+ }+ kinds.add(session.agentKind ?? 'cc');+ }++ return entries.map((entry) => {+ const projectKey = projectIdentityKey('local', entry.path, null);+ const comparisonKey = projectKeyComparisonKey(projectKey, localPlatform);+ const persistedKinds = entry.knownAgentKinds ?? [];+ const visibleKinds =+ (comparisonKey && knownKindsByComparisonKey.get(comparisonKey)) ?? new Set<string>();+ return {+ workingDir: entry.path,+ lastUsedAt: entry.lastUsedAt,+ knownAgentKinds: Array.from(new Set([...persistedKinds, ...visibleKinds])).sort(),+ };+ });+}++export function filterPersistentLocalProjectsByLastActivity(+ projects: readonly PersistentLocalProject[],+ cutoffMs: number | null,+): readonly PersistentLocalProject[] {+ if (cutoffMs === null) return projects;+ return projects.filter((project) => toMs(project.lastUsedAt) >= cutoffMs);+}+- /**- * vendor 过滤下,历史上存在其它 vendor 会话的项目不能伪装成空项目;真正零会话- * 的目录不属于任何 vendor,仍保留创建入口。历史上存在目标 vendor 的项目也保留,- * 即使它因为 status 过滤暂时没有可见会话。- */+export function persistentProjectMatchesVendor(+ project: Pick<ProjectNode, 'isPersistentLocal' | 'persistentLocalKnownAgentKinds'>,+ vendor: string,+): boolean {+ if (!project.isPersistentLocal) return false;+ const knownKinds = project.persistentLocalKnownAgentKinds ?? [];+ return knownKinds.length === 0 || knownKinds.includes(vendor);+}+export function projectIdentityKeyForSession(session: Pick<Session, 'workingDir' | 'remoteHostId' | 'deviceLinkDeviceId'>,): string | null {@@@ -366,10 -320,7 +399,8 @@@ function normalizeProjectAliasesconst projectKey = normalizeProjectKey(key);const alias = typeof value === 'string' ? value.trim() : '';if (!projectKey || alias.length === 0) continue;- out.set(projectKey, alias);+ const comparisonKey = projectKeyComparisonKey(projectKey, localPlatform) ?? projectKey;- // Alias rows arrive newest-first. Legacy Windows casing variants collapse- // to one identity without allowing an older duplicate to overwrite it.+ if (!out.has(comparisonKey)) out.set(comparisonKey, alias);}return out;}@@@ -478,10 -448,9 +528,10 @@@ export function groupSessionssessions: readonly Session[],options: GroupSessionsOptions = {},): ProjectGroupsResult {- const aliases = normalizeProjectAliases(options.projectAliases);- if (!sessions || sessions.length === 0) {+ const localPlatform = options.localPlatform ?? '';+ const aliases = normalizeProjectAliases(options.projectAliases, localPlatform);+ if ((!sessions || sessions.length === 0) && !options.persistentLocalProjects?.length) {- return { pinned: [], dialogues: [], unclassified: [], projects: [] };+ return { pinned: [], dialogues: [], bots: [], unclassified: [], projects: [] };}// 1. Pinned —— active 在 archived 之上,同状态按 pinnedAt desc@@@ -495,24 -464,6 +545,20 @@@? sessions: sessions.filter((s) => s.pinnedAt == null);- // 持久目录是本地 Project 的稳定代表身份。Windows 上会话 cwd 的 casing 可能- // 来自另一条 OS/API 链路;若让会话先占 key,最后一条会话删除前后会在两个- // casing 之间翻转,连带切断 filter / alias / pin / manual order。先固定代表,- // 有会话与零会话两态都复用同一个 projectKey + workingDir。+ const persistentRepresentativeByComparison = new Map<+ string,+ { projectKey: string; workingDir: string }+ >();+ for (const project of options.persistentLocalProjects ?? []) {+ const workingDir = normalizeWorkingDir(project.workingDir);+ if (!workingDir) continue;+ const projectKey = projectIdentityKey('local', workingDir, null);- const comparisonKey = projectKeyComparisonKey(projectKey, options.localPlatform ?? '');++ const comparisonKey = projectKeyComparisonKey(projectKey, localPlatform);+ if (comparisonKey && !persistentRepresentativeByComparison.has(comparisonKey)) {+ persistentRepresentativeByComparison.set(comparisonKey, { projectKey, workingDir });+ }+ }+// 3. 按 normalize 后 workingDir 分组// 草稿判定主线:userSendAt == null(用户从未按下发送)。// 兜底:_count.messages === 0 —— userSendAt 依赖 sendMessage → SDK echo →@@@ -538,7 -501,7 +596,11 @@@const isAutoPlacedSession = s.source === 'scheduler' || s.source === 'plugin';if (dir == null ||- (!isAutoPlacedSession && !isOrcaLead && s.userSendAt == null && noPhysicalMessages)- (!options.includeDraftsInProjects && !isAutoPlacedSession && !isOrcaLead && s.userSendAt == null && noPhysicalMessages)++ (!options.includeDraftsInProjects &&++ !isAutoPlacedSession &&++ !isOrcaLead &&++ s.userSendAt == null &&++ noPhysicalMessages)) {unclassified.push(s);} else {@@@ -578,49 -528,7 +640,47 @@@}}- // 4. 合入与会话生命周期解耦的本地项目目录。持久目录已在上一步主导本地- // Project 的稳定代表身份;这里补足零会话节点并聚合 activity/vendor 元数据。+ const persistentProjectKeys = new Set<string>();+ const persistentLastUsedByKey = new Map<string, string>();+ const persistentKnownAgentKindsByKey = new Map<string, Set<string>>();+ const localProjectKeyByComparison = new Map<string, string>();+ for (const [projectKey, identity] of identityByKey) {+ if (identity.scope !== 'local') continue;+ const comparisonKey = projectKeyComparisonKey(projectKey, localPlatform);+ if (comparisonKey) localProjectKeyByComparison.set(comparisonKey, projectKey);+ }+ for (const project of options.persistentLocalProjects ?? []) {+ const workingDir = normalizeWorkingDir(project.workingDir);+ if (!workingDir) continue;+ const seedKey = projectIdentityKey('local', workingDir, null);+ const comparisonKey = projectKeyComparisonKey(seedKey, localPlatform);+ const projectKey = (comparisonKey && localProjectKeyByComparison.get(comparisonKey)) ?? seedKey;+ if (!groups.has(projectKey)) {+ groups.set(projectKey, []);+ identityByKey.set(projectKey, {+ scope: 'local',+ workingDir,+ remoteHostId: null,+ deviceLinkDeviceId: null,+ deviceLinkDeviceName: null,+ deviceLinkConnectionStatus: null,+ });+ if (comparisonKey) localProjectKeyByComparison.set(comparisonKey, projectKey);+ }+ persistentProjectKeys.add(projectKey);+ const current = persistentLastUsedByKey.get(projectKey);+ if (!current || toMs(project.lastUsedAt) > toMs(current)) {+ persistentLastUsedByKey.set(projectKey, project.lastUsedAt);+ }+ let knownKinds = persistentKnownAgentKindsByKey.get(projectKey);+ if (!knownKinds) {+ knownKinds = new Set<string>();+ persistentKnownAgentKindsByKey.set(projectKey, knownKinds);+ }+ for (const agentKind of project.knownAgentKinds) knownKinds.add(agentKind);+ }+- // 5. unclassified 排序 —— active 在 archived 之上,同状态按 sortTime desc+ // 4. unclassified 排序 —— active 在 archived 之上,同状态按 sortTime descdialogues.sort(compareSessionsByStatusThenSortTimeDesc);unclassified.sort(compareSessionsByStatusThenSortTimeDesc);@@@ -629,12 -556,10 +708,12 @@@// basename(minSegments=1),其余强制 minSegments=2 触发 parent 追溯。// createdAt 缺失时回退到 dir 字符串字典序,保证确定性。const allProjectKeys = Array.from(groups.keys());- const allDisplayDirs = allProjectKeys.map((projectKey) => identityByKey.get(projectKey)?.workingDir ?? projectKey);+ const allDisplayDirs = allProjectKeys.map(+ (projectKey) => identityByKey.get(projectKey)?.workingDir ?? projectKey,+ );const minSegByDir = new Map<string, number>();- // 6a. 先按 basename 分桶+ // 5a. 先按 basename 分桶const dirsByBasename = new Map<string, string[]>();for (const projectKey of allProjectKeys) {const identity = identityByKey.get(projectKey);diff --cc apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectRestore.tsindex 5df9b7e840,5315e56916..72a17710fc--- a/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectRestore.ts+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectRestore.ts@@@ -2,12 -2,50 +2,55 @@@ import type { Session } from '@/lib/ccAimport { projectKeyComparisonKey } from '../../../../shared/projectKeys';import { sessionActivityMs } from './dateSessionGrouping';--import { groupSessions, projectIdentityKeyForSession } from './projectGrouping';++import {++ groupSessions,++ projectIdentityKeyForSession,++ type PersistentLocalProject,++} from './projectGrouping';+ import { isProjectHidden } from './sidebarProjectVisibility';- type RestoreVendorPredicate = (session: Pick<Session, 'agentKind'>) => boolean;+ type SidebarProjectRestoreHandler = (projectKey: string) => Promise<boolean>;++ let sidebarProjectRestoreHandler: SidebarProjectRestoreHandler | null = null;++ function findMatchingProjectKey(+ projectKey: string,+ candidates: ReadonlySet<string>,+ localPlatform: string,+ ): string | null {+ const comparisonKey = projectKeyComparisonKey(projectKey, localPlatform);+ if (comparisonKey == null) return null;+ return (+ Array.from(candidates).find(+ (candidate) => projectKeyComparisonKey(candidate, localPlatform) === comparisonKey,+ ) ?? null+ );+ }++ /**+ * The sidebar owns both the hidden-project snapshot and the active Project+ * filter. Creation routes live in a sibling React tree, so they delegate the+ * restore transaction here instead of duplicating those two pieces of state.+ */+ export function registerSidebarProjectRestoreHandler(+ handler: SidebarProjectRestoreHandler,+ ): () => void {+ sidebarProjectRestoreHandler = handler;+ return () => {+ if (sidebarProjectRestoreHandler === handler) sidebarProjectRestoreHandler = null;+ };+ }++ export function requestSidebarProjectRestore(projectKey: string): Promise<boolean> {+ const handler = sidebarProjectRestoreHandler;+ return handler?.(projectKey) ?? Promise.resolve(false);+ }+-type RestoreVendorPredicate = (session: Pick<Session, 'agentKind'>) => boolean;++type RestoreVendorPredicate = (session: { agentKind?: string | null }) => boolean;interface CollectRestorableProjectKeysOptions {sessions: readonly Session[];++ persistentLocalProjects?: readonly PersistentLocalProject[];lastActivityCutoff: number | null;pinnedProjectKeys: ReadonlySet<string>;vendorPredicate: RestoreVendorPredicate | null;@@@ -25,36 -62,24 +68,52 @@@*/export function collectRestorableProjectKeys({sessions,++ persistentLocalProjects = [],lastActivityCutoff,pinnedProjectKeys,vendorPredicate,+ localPlatform = '',}: CollectRestorableProjectKeysOptions): ReadonlySet<string> {const vendorSessions = vendorPredicate ? sessions.filter(vendorPredicate) : sessions;++ const vendorProjects = vendorPredicate++ ? persistentLocalProjects.filter(++ (project) =>++ project.knownAgentKinds.length === 0 ||++ project.knownAgentKinds.some((agentKind) => vendorPredicate({ agentKind })),++ )++ : persistentLocalProjects;const activitySessions =lastActivityCutoff === null? vendorSessions: vendorSessions.filter((session) => sessionActivityMs(session) >= lastActivityCutoff);- const activityGroups = groupSessions(activitySessions, { includePinnedInProjects: true });- const allGroups =++ const activityProjects =+ lastActivityCutoff === null- ? activityGroups- : groupSessions(vendorSessions, { includePinnedInProjects: true });++ ? vendorProjects++ : vendorProjects.filter(++ (project) => new Date(project.lastUsedAt).getTime() >= lastActivityCutoff,++ );+ const activityGroups = groupSessions(activitySessions, {+ includePinnedInProjects: true,++ persistentLocalProjects: activityProjects,++ localPlatform,++ });++ const allGroups = groupSessions(sessions, {++ includePinnedInProjects: true,++ persistentLocalProjects,+ localPlatform,+ });- const allGroups =- lastActivityCutoff === null- ? activityGroups- : groupSessions(vendorSessions, { includePinnedInProjects: true, localPlatform });const projectKeys = new Set(activityGroups.projects.map((project) => project.projectKey));+ const pinnedComparisonKeys = new Set(+ Array.from(pinnedProjectKeys)+ .map((projectKey) => projectKeyComparisonKey(projectKey, localPlatform))+ .filter((projectKey): projectKey is string => projectKey != null),+ );for (const project of allGroups.projects) {- if (pinnedProjectKeys.has(project.projectKey)) projectKeys.add(project.projectKey);+ const comparisonKey = projectKeyComparisonKey(project.projectKey, localPlatform);+ if (comparisonKey != null && pinnedComparisonKeys.has(comparisonKey)) {+ projectKeys.add(project.projectKey);+ }}for (const session of allGroups.pinned) {if (session.workspaceKind === 'dialogue') continue;diff --cc apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectSorting.tsindex 61be8397af,fd7bbe891f..03596bf329--- a/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectSorting.ts+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectSorting.ts@@@ -1,32 -1,29 +1,30 @@@import type { Session } from '@/lib/ccAgent.types';- import type { FilterSortBy } from '../hooks/helpers/sidebarFilterCore';+ import type { FilterProjectOrder, FilterSortBy } from '../hooks/helpers/sidebarFilterCore';import { normalizeManualProjectOrder } from '../hooks/helpers/sidebarFilterCore';- import { sessionActivityMs } from './dateSessionGrouping';- import type { ProjectNode } from './projectGrouping';- import { projectKeyComparisonKey } from './projectGrouping';-- function toMs(iso: string | null | undefined): number {- if (!iso) return 0;- const t = new Date(iso).getTime();- return Number.isFinite(t) ? t : 0;- }+ import { sessionCreatedMs } from './dateSessionGrouping';-import type { ProjectNode } from './projectGrouping';++import { projectKeyComparisonKey, type ProjectNode } from './projectGrouping';+ /**+ * 创建时间排序独立于活动变化;其它档位保留调用方已排好的顺序。+ */export function sortSessionsForSidebar(sessions: readonly Session[],sortBy: FilterSortBy,): Session[] {- if (sortBy === 'time') {- return sessions.slice().sort((a, b) => sessionActivityMs(a) - sessionActivityMs(b));- }- return sessions.slice();+ return sortBy === 'created'- ? sessions.slice().sort((a, b) =>- sessionCreatedMs(b) - sessionCreatedMs(a) || a.id.localeCompare(b.id),- )++ ? sessions++ .slice()++ .sort((a, b) => sessionCreatedMs(b) - sessionCreatedMs(a) || a.id.localeCompare(b.id))+ : sessions.slice();}export function sortProjectsForSidebar(projects: readonly ProjectNode[],sortBy: FilterSortBy,manualProjectOrder: readonly string[],+ projectOrder: FilterProjectOrder = 'activity',+ localPlatform: string = '',): ProjectNode[] {const withSortedSessions = projects.map((project) => ({...project,@@@ -65,5 -43,13 +52,14 @@@);}+ if (sortBy === 'created') {- return withSortedSessions.sort((a, b) =>- Math.max(0, ...b.sessions.map(sessionCreatedMs)) -- Math.max(0, ...a.sessions.map(sessionCreatedMs)) ||- (a.sessions[0]?.id ?? '').localeCompare(b.sessions[0]?.id ?? ''),++ return withSortedSessions.sort(++ (a, b) =>++ Math.max(0, ...b.sessions.map(sessionCreatedMs)) -++ Math.max(0, ...a.sessions.map(sessionCreatedMs)) ||++ (a.sessions[0]?.id ?? '').localeCompare(b.sessions[0]?.id ?? ''),+ );+ }+return withSortedSessions;}diff --cc apps/desktop/src/renderer/features/cc-agent/sidebar/conversationSearchContext.tsxindex c8e162d9a7,ac7a3839e8..f84f3523a0--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/conversationSearchContext.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/conversationSearchContext.tsx@@@ -25,8 -27,20 +27,25 @@@ importimport { useNavigate } from 'react-router-dom';import { useCCSessions } from '@/hooks/useCCSessions';+import { useRecentWorkdirs } from '@/hooks/useRecentWorkdirs';import { isOrcaWorkerSession } from '@/lib/orcaSessionIdentity';+ import {+ requestRemoteSessionStatus,+ useRemoteProjectSessions,+ } from '@/features/device-link/remoteProjectsStore';-import { selectVisibleSessions } from '@/features/device-link/selectedMachineStore';++import {++ MACHINE_ALL,++ MACHINE_LOCAL,++ selectVisibleSessions,++} from '@/features/device-link/selectedMachineStore';+ import {+ useEffectiveSelectedMachineId,+ useSwitcherDevices,+ } from '@/features/device-link/useMachineSwitcher';+ import {+ searchDevicesFromSwitcher,+ shouldReleaseConversationSearchLock,+ } from '@/lib/conversationSearchFanout';import { useConversationSearchRequest } from '@/state/conversationSearchRequest';import { useProjectAliases } from '../hooks/useProjectAliases';import { useHiddenProjects } from '../hooks/useHiddenProjects';@@@ -40,8 -54,7 +59,11 @@@ importreconcileProjectSelectionWithVisibleProjects,useConversationSearch,} from './ConversationSearchBox';--import type { ProjectNode as ProjectNodeData } from '../lib/projectGrouping';- import { buildPersistentLocalProjects } from '../lib/projectGrouping';++import {++ buildPersistentLocalProjects,++ type PersistentLocalProject,++ type ProjectNode as ProjectNodeData,++} from '../lib/projectGrouping';interface ConversationSearchContextValue {/** 搜索状态机(query / 排序 / 筛选 / 结果 / handleSelect 等)。 */@@@ -59,17 -72,33 +81,51 @@@ export function ConversationSearchProviconst projectFilterRequest = useConversationSearchRequest();const [openSignal, setOpenSignal] = useState(0);- // allKnownProjects:全量会话(含归档)、排除 Orca worker,与 CCAgentSidebarUpper 同口径。+ // allKnownProjects:本机 ∪ 远程镜像(含归档)、按机器切换栏过滤、排除 Orca worker。const { sessions } = useCCSessions({ includeArchived: 'all' });+ const remoteProjectSessions = useRemoteProjectSessions();+ const selectedMachineId = useEffectiveSelectedMachineId();+ const switcherDevices = useSwitcherDevices();+ const searchDevices = useMemo(+ () => searchDevicesFromSwitcher(switcherDevices),+ [switcherDevices],+ );+ // Search status defaults to all. Pull archived remote buckets so a remote+ // project that only has archived tasks still appears in the project filter.+ useEffect(() => {+ for (const device of searchDevices) {+ if (!device.connected) continue;+ requestRemoteSessionStatus(device.deviceId, 'archived');+ }+ }, [searchDevices]);const { aliases } = useProjectAliases();const { hiddenProjectKeys } = useHiddenProjects();+ const { entries: recentWorkdirs } = useRecentWorkdirs();- const searchSessions = useMemo(() => sessions.filter((s) => !isOrcaWorkerSession(s)), [sessions]);- const persistentLocalProjects = useMemo(- () => buildPersistentLocalProjects(recentWorkdirs, searchSessions, window.electronAPI.platform),- [recentWorkdirs, searchSessions],+ const searchSessions = useMemo(+ () =>+ selectVisibleSessions(sessions, remoteProjectSessions, selectedMachineId).filter(+ (session) => !isOrcaWorkerSession(session),+ ),+ [remoteProjectSessions, selectedMachineId, sessions],+ );- const { projects } = useProjectGroups(searchSessions, aliases);++ const persistentLocalProjects = useMemo<PersistentLocalProject[]>(++ () => buildPersistentLocalProjects(recentWorkdirs, sessions, window.electronAPI.platform),++ [recentWorkdirs, sessions],++ );++ const visiblePersistentLocalProjects = useMemo(++ () =>++ selectedMachineId === MACHINE_ALL || selectedMachineId.includes(MACHINE_LOCAL)++ ? persistentLocalProjects++ : [],++ [persistentLocalProjects, selectedMachineId],++ );++ const { projects } = useProjectGroups(++ searchSessions,++ aliases,++ false,++ visiblePersistentLocalProjects,++ window.electronAPI.platform,+ );- const { projects } = useProjectGroups(searchSessions, aliases, false, persistentLocalProjects);const visibleProjects = useMemo(() => visibleSidebarProjects(projects, hiddenProjectKeys, window.electronAPI.platform),[projects, hiddenProjectKeys],diff --cc apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsxindex 932db25a0d,1a08bb9d03..53022c6ff6--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx@@@ -36,19 -62,39 +62,39 @@@ importimport {normalizeManualProjectOrder,mergeVisibleReorder,+ snapshotManualProjectOrder,+ loadDialogueGroupCollapsedKeys,+ persistDialogueGroupCollapsedKeys,+ DIALOGUE_GROUP_ALL_KEY,} from '../../hooks/helpers/sidebarFilterCore';- import { SidebarFilterPopover } from '../SidebarFilterPopover';+ import {+ advanceViewedPriorityHold,+ buildMainListEntries,+ getMainListEntrySessions,+ holdViewedPriorityRank,+ splitEntriesByDevice,+ type MainListDeviceSection,+ type MainListEntry,+ type ViewedPriorityHoldState,+ } from '../../lib/mainListModel';-import type { BotGroupNode } from '../../lib/projectGrouping';++import { projectKeyComparisonKey, type BotGroupNode } from '../../lib/projectGrouping';+ import { buildSessionSourceLabelMap } from '../../lib/sessionSourceLabel';+ import { useSessionAttentionKinds } from '@/lib/sessionAttentionStore';+ import { useSessionAttentionUrgencySet } from '../../contexts/SessionAttentionUrgencyContext';+ import {+ getRemoteSessionActivity,+ isRemoteSessionActivityActive,+ useRemoteSessionActivityRevision,+ } from '@/features/device-link/remoteSessionActivityStore';+ import { absorbSessionStarting } from '@/lib/sessionStartingStore';+ import type { DialogueDeviceTarget } from '../../lib/dialogueCreateTarget';+ import { MainListScopeHeader } from '../MainListScopeHeader';import { SectionCollapse } from '../SectionCollapse';+ import { SessionEntryList, SessionEntryRows } from '../SessionEntryList';import { useCollapsibleShowAll } from '../hooks/useCollapsibleShowAll';+ import { useAutomationGroupsCollapsed } from '../../hooks/useAutomationGroupCollapsed';import type { SessionClickHandler } from '../SessionItem';- import {- projectKeyComparisonKey,- type ProjectNode as ProjectNodeData,- } from '../../lib/projectGrouping';- import {- buildProjectKeyComparisonSet,- projectKeyComparisonSetHas,- } from '../../lib/sidebarProjectVisibility';+ import type { ProjectNode as ProjectNodeData } from '../../lib/projectGrouping';import type { UseSidebarFilterReturn } from '../../hooks/useSidebarFilter';import type {AutomationScheduleAction,@@@ -163,21 -284,47 +284,52 @@@ export function ProjectsSection(linkingCodexProject,onBrowseFiles,onArchiveAll,+ remoteDeviceIndex = null,+ onCreateDialogue,+ isCreateDialogueDisabled = false,}: ProjectsSectionProps) {const { t } = useTranslation();+ const localPlatform = window.electronAPI.platform;- const collapsedComparisonKeys = useMemo(- () => buildProjectKeyComparisonSet(collapsed, localPlatform),- [collapsed, localPlatform],++ const projectComparisonKey = useCallback(++ (projectKey: string) => projectKeyComparisonKey(projectKey, localPlatform) ?? projectKey,++ [localPlatform],+ );const reducedMotion = useReducedMotion();- // 拖拽只在 Project 分组下才有意义;sortBy 不强制要 'manual'——用户随手拖一下- // 我们就在 onReorder 里自动切到 manual 并持久化,避免"默认 recency 排序下永远拖不动"- // 的反直觉体验。- const projectDragEnabled = filter.groupBy === 'project';+ const selectedMachineForOrder = useEffectiveSelectedMachineId();+ const localHostProjectOrder = useLocalHostProjectOrder();+ const remoteHostProjectOrders = useRemoteHostProjectOrders(selectedMachineForOrder);+ // 主列表显示形态(B 期):text 紧凑行 / list 满宽两行卡。独立于置顶段的三态设置。+ const { mode: mainViewMode } = useSidebarMainViewMode();+ const mainSessionVariant: 'text' | 'list' = mainViewMode === 'list' ? 'list' : 'text';+ // SortableList 只在自定义项目顺序且按项目分组时挂载。+ // 折叠溢出且未点「显示全部」时禁用,避免只重排可见前缀。+ const projectOrderScope = projectOrderWriteScopeForSelection(selectedMachineForOrder);+ const hostSnapshotForDisplay = projectOrderScope.kind === 'host' && projectOrderScope.deviceId === null+ ? localHostProjectOrder.snapshot+ : projectOrderScope.kind === 'host' && projectOrderScope.deviceId+ ? remoteHostProjectOrders.orders.get(projectOrderScope.deviceId)+ : undefined;+ const displayedProjectOrder = resolveDisplayedProjectOrder(+ projectOrderScope,+ hostSnapshotForDisplay,+ filter,+ projectOrderScope.kind === 'host' && projectOrderScope.deviceId === null+ ? localHostProjectOrder.snapshot.manualProjectOrder+ : projectOrderScope.kind === 'host' && projectOrderScope.deviceId+ ? controllerManualOrderForDevice(projectOrderScope.deviceId, hostSnapshotForDisplay) ?? []+ : [],+ );+ const customProjectOrder = filter.groupBy === 'project' && displayedProjectOrder.projectOrder === 'custom';+ const projectDragEnabled = customProjectOrder;const projectKeysForOrderBaseline = allProjectKeysForOrder;- const [isSectionCollapsed, setIsSectionCollapsed] = useState(false);- const [showAllProjects, setShowAllProjects] = useCollapsibleShowAll(isSectionCollapsed);+ // 段级收起已随「全部任务 = 范围下拉」取消(2026-08-13 用户定稿):标题的点击+ // 语义让给机器范围切换;「想要紧凑」由右侧「收起所有分组」承接。+ const [showAllProjects, setShowAllProjects] = useCollapsibleShowAll(false);+ // 设备段各自的「显示全部」(2026-08-13 复核 P2:共用一个标志会让点任一段的+ // 段内按钮把所有段一起展开——按钮看起来是段内操作,作用域也必须是段内)。+ const [expandedDeviceSections, setExpandedDeviceSections] = useState<ReadonlySet<string>>(+ new Set(),+ );const getProjectId = useCallback((p: ProjectNodeData) => p.projectKey, []);@@@ -187,47 -334,61 +339,64 @@@// 不可见的 project(其它机器 / 被过滤掉的)必须**保持原位** —— 与置顶拖拽同一套「原位 merge」// 语义(mergeVisibleReorder),而不是把它们甩到末尾(否则切回「所有」时其它机器项目的相对// 位置会被无关拖拽悄悄打乱)。做法:先取全量规范顺序作 baseline,再把可见新序原位填回。- // projectKeysForOrderBaseline 是未过滤全量 universe 的 key,因此 baseline 含- // 隐藏项;setManualProjectOrder 内部会再归一化一次(对已规范的 merged 结果幂等)。- const fullOrder = normalizeManualProjectOrder(- filter.manualProjectOrder,- projectKeysForOrderBaseline,- localPlatform,- );- const merged = mergeVisibleReorder(- fullOrder,- visibleNewOrder,- (projectKey) => projectKeyComparisonKey(projectKey, localPlatform) ?? projectKey,- );- filter.setManualProjectOrder(merged, projectKeysForOrderBaseline);- // 用户随手一拖即表达"我要手动排序"的意图;如果当前不是 manual,自动切过去- // 并持久化,让拖拽结果立刻生效,不需要用户先去 Filter Popover 切换排序模式。- if (filter.sortBy !== 'manual') {- filter.setSortBy('manual');+ const scope = projectOrderWriteScopeForSelection(selectedMachineForOrder);+ const hostSnapshot = scope.kind === 'host' && scope.deviceId === null+ ? localHostProjectOrder.snapshot+ : scope.kind === 'host' && scope.deviceId+ ? remoteHostProjectOrders.orders.get(scope.deviceId)+ : undefined;+ const persistViewer = (order: readonly string[]) => {- const fullOrder = normalizeManualProjectOrder(filter.manualProjectOrder, projectKeysForOrderBaseline);- const merged = mergeVisibleReorder(fullOrder, order);++ const fullOrder = normalizeManualProjectOrder(filter.manualProjectOrder, projectKeysForOrderBaseline, localPlatform);++ const merged = mergeVisibleReorder(fullOrder, order, projectComparisonKey);+ filter.setManualProjectOrder(merged, projectKeysForOrderBaseline);+ if (filter.projectOrder !== 'custom') filter.setProjectOrder('custom');+ };+ if (projectOrderWriteLedger(scope, hostSnapshot) === 'host' && scope.kind === 'host' && scope.deviceId === null) {+ const localKeys = projectKeysForOrderBaseline.filter((key) => key.startsWith('local:'));+ const fullOrder = normalizeManualProjectOrder(+ localHostProjectOrder.snapshot.manualProjectOrder,+ localKeys,++ localPlatform,+ );- const next = mergeVisibleReorder(fullOrder, visibleNewOrder);++ const next = mergeVisibleReorder(fullOrder, visibleNewOrder, projectComparisonKey);+ void localHostProjectOrder.apply({+ manualProjectOrder: next,+ projectOrder: 'custom',+ }).then((result) => {+ if (result.kind === 'unavailable') persistViewer(visibleNewOrder);+ });+ return;}+ if (projectOrderWriteLedger(scope, hostSnapshot) === 'host' && scope.kind === 'host' && scope.deviceId) {+ const deviceId = scope.deviceId;+ const remoteKeys = projectKeysForOrderBaseline.filter((key) => key.startsWith(`device:${encodeURIComponent(deviceId)}:`));+ const current = controllerManualOrderForDevice(+ deviceId,+ remoteHostProjectOrders.orders.get(deviceId),+ ) ?? [];- const fullOrder = normalizeManualProjectOrder(current, remoteKeys);- const next = mergeVisibleReorder(fullOrder, visibleNewOrder);++ const fullOrder = normalizeManualProjectOrder(current, remoteKeys, localPlatform);++ const next = mergeVisibleReorder(fullOrder, visibleNewOrder, projectComparisonKey);+ void remoteHostProjectOrders.apply(deviceId, {+ manualProjectOrder: next,+ projectOrder: 'custom',+ }).then((result) => {+ if (result.kind === 'unavailable') persistViewer(visibleNewOrder);+ });+ return;+ }+ persistViewer(visibleNewOrder);},- [filter, localPlatform, projectKeysForOrderBaseline],+ [+ filter,+ localHostProjectOrder,+ projectKeysForOrderBaseline,+ remoteHostProjectOrders,+ selectedMachineForOrder,++ localPlatform,++ projectComparisonKey,+ ],);- // F-PJ-10:即使 projects 因 filter 收窄到空,也要保留段头供用户切回 Filter。- // 这里用原始 key 全集作为"是否有过任何 project"的判定 — 全部项目都被隐藏时- // 仍保留段头的 Add Project 入口,用户才能重新选择目录恢复项目。完全没有 project- // 且没有未分类 → 整段不渲染。(机器切换入口已移到侧栏顶部固定行,不再依赖本段头,- // 故无需再为「有远程机器」保留空段头。)- if (allProjectKeysForOrder.length === 0 && unclassified.length === 0 && !filter.isFilterActive) {- return null;- }-- const SectionToggleIcon = isSectionCollapsed ? ChevronRight : ChevronDown;- const sectionToggleLabel = isSectionCollapsed- ? t('ccAgent.sidebar.projectsSectionToggleExpand')- : t('ccAgent.sidebar.projectsSectionToggleCollapse');- // 右侧旧按钮保留 ProjectNode 级别行为:折叠/展开所有项目下面的会话。- const ProjectNodesToggleIcon = isAllCollapsed ? ChevronsUpDown : ChevronsDownUp;- const handleToggleAllProjectNodes = isAllCollapsed ? onExpandAll : onCollapseAll;- const projectNodesToggleLabel = isAllCollapsed- ? t('ccAgent.sidebar.projectsToggleExpand')- : t('ccAgent.sidebar.projectsToggleCollapse');// toggleDisabled 用 allKnownProjects(不是过滤后的 projects),避免 filter 收窄到 0 时// 即便没真正可折叠的目标,也保留视觉一致——但禁用按钮以避免无意义点击。const projectNodesToggleDisabled = allKnownProjects.length === 0;@@@ -236,25 -397,576 +405,576 @@@// 文字搜索是独立面板、不在本段内联过滤,故无需为它禁用。const disableSessionCollapse = false;- // 项目列表本身也折叠:最多显示 10 个项目,超出收起 + 「显示全部 N 项」。与会话同一套- // 规则(getSessionListCollapseView):始终保留"有需关注会话"的项目、以及包含当前会话的- // 项目;任何排序/筛选下都生效。+ // 优先级排序的运行时上下文。三个集合都在本地链路之上并入 device-link 远程+ // 活动镜像(2026-08-13 review P1:此前只喂本地 maker/attention,远程行自己的+ // 状态点亮着、排序却把它当 idle):+ // - waiting:本地 attention kind 为 awaiting / error、定时任务失败未读+ // (urgentSet,语义对齐 SessionItem 的 isUrgentFromContext)、远程+ // needs-interaction / error;+ // - attention:本地未读集 ∪ 远程有活动条目的会话(waiting ⊆ attention,+ // rank 函数先查 attention 再分档);+ // - running:本地 running ∪ 远程 running。+ // 整表订阅仅限本聚合组件(两个 store 头注的性能边界):本组件本就随+ // notifications 整集变化重渲染,不额外放大;远程镜像走整表版本号 + 逐 id 读,+ // 与 CCAgentSidebarUpper.projectAgg 同款先例。+ const attentionKinds = useSessionAttentionKinds();+ const urgentSet = useSessionAttentionUrgencySet();+ const remoteActivityRevision = useRemoteSessionActivityRevision();+ const collapsedAttentionToneFor = useCallback(+ (sessions: readonly Session[]) =>+ resolveCollapsedProjectAttentionTone({+ sessions,+ runningSessionIds,+ notifications,+ attentionKinds,+ urgentSessionIds: urgentSet,+ remotePhaseOf: (sessionId) => getRemoteSessionActivity(sessionId)?.phase,+ }),+ // eslint-disable-next-line react-hooks/exhaustive-deps -- remoteActivityRevision 代表 getRemoteSessionActivity 读到的整表内容+ [runningSessionIds, notifications, attentionKinds, urgentSet, remoteActivityRevision],+ );+ // 正在看的任务 id:files 路由下回落到被浏览文件所属任务。+ const viewedIdForSort = viewedSessionId ?? activeSessionId;+ const priorityContext = useMemo(() => {+ const running = new Set(runningSessionIds);+ const attention = new Set(notifications);+ const waiting = new Set<string>(urgentSet);+ for (const [sessionId, kind] of attentionKinds) {+ if (kind === 'awaiting' || kind === 'error') waiting.add(sessionId);+ }+ const considerRemote = (session: Session) => {+ const activity = getRemoteSessionActivity(session.id);+ if (!activity) return; // 本地会话 / 无活动条目:一次 Map 查找即返回+ if (activity.phase === 'running') {+ running.add(session.id);+ return;+ }+ // needs-interaction / error → waiting;completed(镜像只保留未读终态,+ // 已读收尾包会删条目)→ 完成未读档。+ attention.add(session.id);+ if (activity.phase === 'needs-interaction' || activity.phase === 'error') {+ waiting.add(session.id);+ }+ };+ for (const project of projects) for (const session of project.sessions) considerRemote(session);+ for (const session of dialogues) considerRemote(session);+ for (const session of unclassified) considerRemote(session);++ const hold = advanceViewedPriorityHold(+ viewedPriorityHold,+ viewedIdForSort,+ { runningSessionIds: running, attentionSessionIds: attention, waitingSessionIds: waiting },+ Date.now(),+ );++ return {+ runningSessionIds: running,+ attentionSessionIds: attention,+ waitingSessionIds: waiting,+ heldPriorityRanks: hold.heldPriorityRanks,+ recentlyViewedAtMs: hold.recentlyViewedAtMs,+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps -- remoteActivityRevision 代表 getRemoteSessionActivity 读到的整表内容+ }, [+ runningSessionIds,+ notifications,+ urgentSet,+ attentionKinds,+ projects,+ dialogues,+ unclassified,+ remoteActivityRevision,+ viewedIdForSort,+ ]);++ // starting 只让位给真实 in-flight:本地 isRunning(见 useStartingSessionIds),+ // 远程 running / needs-interaction。终态 attention 不再吸收 —— 旧终态会误伤+ // 新发送,新终态又要代次才能和旧的区分,两边补丁会来回打。没经过 running+ // 的快完成靠 TTL。+ useEffect(() => {+ const settled = new Set<string>();+ const considerRemote = (session: Session) => {+ if (isRemoteSessionActivityActive(getRemoteSessionActivity(session.id))) {+ settled.add(session.id);+ }+ };+ for (const project of projects) {+ for (const session of project.sessions) considerRemote(session);+ }+ for (const session of dialogues) considerRemote(session);+ for (const session of unclassified) considerRemote(session);+ absorbSessionStarting(settled);+ // eslint-disable-next-line react-hooks/exhaustive-deps -- remoteActivityRevision 代表 getRemoteSessionActivity 读到的整表内容+ }, [projects, dialogues, unclassified, remoteActivityRevision]);++ // E 期「按设备分组」:有远程设备连接 + 开关开 → 按设备切段(本机在前,+ // 远程按设备切换栏顺序);其余情况单段直渲。切段后按当前排序重排本段。+ // 自定义项目顺序可以和设备分组叠加:每段内项目行按全局序的子集排,段内可拖。+ // 范围收窄到单台机器时同样退场(2026-08-13 用户定稿):只有一台无段可切,+ // 唯一的段头还会和范围标题重复报同一个设备名;整理菜单的选项行同步隐藏+ // (deviceGroupingAvailable),偏好照旧不改写、范围放宽自动恢复。+ const hasRemoteDevices = (remoteDeviceIndex?.size ?? 0) > 0;+ const selectedMachineId = useEffectiveSelectedMachineId();+ const singleMachineScope = selectedMachineId !== MACHINE_ALL && selectedMachineId.length === 1;+ const deviceGroupingAvailable = hasRemoteDevices && !singleMachineScope;+ const deviceGroupingActive = deviceGroupingAvailable && filter.groupDevice;+ // F-PJ-10:未分类区在 projects 为具体多选状态时不渲染(spec 验收第 14 条)+ const unclassifiedHidden = filter.projects !== 'all';++ // 混排模型(D 期):项目行 / 散排对话 / 对话组统一为顶层条目并按同一口径排序。+ // 这有意推翻旧「Dialogue 固定段在 Projects 之后」的裁决(mainListModel.ts 文件头)。+ // 设备分组开启时,未分类草稿并进混排再按设备切段;单段路径仍走顶部独立段。+ const mixedEntries = useMemo(+ () =>+ buildMainListEntries({+ projects,+ dialogues,+ bots,+ unclassified: deviceGroupingActive && !unclassifiedHidden ? unclassified : [],+ groupBy: filter.groupBy,+ groupDialogue: filter.groupDialogue,+ sortBy: filter.sortBy,+ projectOrder: displayedProjectOrder.projectOrder,+ manualProjectOrder: displayedProjectOrder.manualProjectOrder,+ priorityContext,+ notifications,+ scheduleSessionIndex,+ }),+ [+ projects,+ dialogues,+ bots,+ unclassified,+ unclassifiedHidden,+ deviceGroupingActive,+ filter.groupBy,+ filter.groupDialogue,+ filter.sortBy,+ displayedProjectOrder,+ priorityContext,+ notifications,+ scheduleSessionIndex,+ ],+ );++ // 顶层条目折叠:最多显示 N 条,超出收起 + 「显示全部 N 项」。与会话同一套+ // 规则(getSessionListCollapseView):始终保留"有需关注会话"的条目、以及包含当前会话的+ // 条目;任何排序/筛选下都生效。+ const entrySessions = getMainListEntrySessions;+ // 折叠视图共用一份参数:非设备分组 = 全列表一份;设备分组 = 每段各一份(见+ // deviceSections)。attention 豁免用 priorityContext.attentionSessionIds——与+ // 排序同一口径(含远程活动镜像),远程 waiting/unread 的条目不能被折进+ // 「显示全部」。+ const collapseEntries = useCallback(+ (entries: readonly MainListEntry[], showAll: boolean) =>+ getSessionListCollapseView({+ entries,+ minVisibleCount: getProjectCollapseLimit(),+ showAll,+ disableCollapse: false,+ isFiltering: false,+ isActiveEntry: (entry) => entrySessions(entry).some((s) => s.id === viewedIdForSort),+ hasAttentionEntry: (entry) =>+ entrySessions(entry).some((s) => priorityContext.attentionSessionIds.has(s.id)),+ }),+ [viewedIdForSort, entrySessions, priorityContext],+ );const {- visibleEntries: visibleProjectNodes,+ visibleEntries: visibleMixedEntries,isOverflowing: projectsOverflow,totalCount: projectsTotal,- } = getSessionListCollapseView({- entries: projects,- minVisibleCount: getProjectCollapseLimit(),- showAll: showAllProjects,- disableCollapse: false,- isFiltering: false,- isActiveEntry: (p) => p.sessions.some((s) => s.id === activeSessionId),- hasAttentionEntry: (p) => p.sessions.some((s) => notifications.has(s.id)),- });+ } = collapseEntries(mixedEntries, showAllProjects);+ // SortableList 拖拽仍只作用于项目行(手动排序收窄裁决,设计文档 §9.3):+ // 混排下把可见条目切成「连续的项目行 run + 其间的散排条目」,项目 run 内可拖。+ const visibleProjectNodes = visibleMixedEntries+ .filter(+ (entry): entry is Extract<MainListEntry, { kind: 'project' }> => entry.kind === 'project',+ )+ .map((entry) => entry.project);- // F-PJ-10:未分类区在 projects 为具体多选状态时不渲染(spec 验收第 14 条)- const unclassifiedHidden = filter.projects !== 'all';+ // 第一次切到手动时,必须用切换前的视觉序(recency / priority 混排结果),+ // 不能在 custom+空序重算后再采集——那时项目行已按上游入参序排好,优先级视觉会丢。+ // 可见子集还要 merge 回全量 baseline,避免隐藏项目被甩到末尾。+ const preCustomVisualKeysRef = useRef<string[]>([]);+ if (filter.projectOrder !== 'custom') {+ preCustomVisualKeysRef.current = mixedEntries+ .filter(+ (entry): entry is Extract<MainListEntry, { kind: 'project' }> => entry.kind === 'project',+ )+ .map((entry) => entry.project.projectKey);+ }+ const prevProjectOrderRef = useRef(filter.projectOrder);+ useEffect(() => {+ const previous = prevProjectOrderRef.current;+ prevProjectOrderRef.current = filter.projectOrder;+ if (+ previous === 'custom' ||+ filter.projectOrder !== 'custom' ||+ filter.groupBy !== 'project' ||+ filter.manualProjectOrder.length > 0+ ) {+ return;+ }+ const keys = preCustomVisualKeysRef.current;+ if (keys.length === 0) return;+ filter.setManualProjectOrder(- snapshotManualProjectOrder(keys, projectKeysForOrderBaseline),++ snapshotManualProjectOrder(keys, projectKeysForOrderBaseline, localPlatform),+ projectKeysForOrderBaseline,+ );- }, [filter, projectKeysForOrderBaseline]);++ }, [filter, projectKeysForOrderBaseline, localPlatform]);++ const deviceSections = useMemo<MainListDeviceSection[]>(() => {+ if (!deviceGroupingActive) return [{ deviceId: null, entries: [...visibleMixedEntries] }];+ // 设备分组:对**全量**条目先切段,折叠上限在渲染时每段独立应用(2026-08-13+ // review P1:此前先全局折叠再切段,排在前 N 名之外的设备连段头一起消失,+ // 看起来像"这台设备没有任务"——设备是最外层层级,折叠只能发生在段内)。+ return splitEntriesByDevice(mixedEntries, [...(remoteDeviceIndex?.keys() ?? [])], {+ sortBy: filter.sortBy,+ projectOrder: filter.projectOrder,+ manualProjectOrder: filter.manualProjectOrder,+ priorityContext,+ });+ }, [+ deviceGroupingActive,+ visibleMixedEntries,+ mixedEntries,+ remoteDeviceIndex,+ filter.sortBy,+ filter.projectOrder,+ filter.manualProjectOrder,+ priorityContext,+ ]);+ // 设备段折叠(E 期):本机段 key 'local'。+ const [collapsedDevices, setCollapsedDevices] = useState<ReadonlySet<string>>(new Set());+ // 「对话」组折叠:与项目行折叠同级的分组状态(用户裁决:对话组的折叠交互与+ // 项目分组一致,含「收起所有分组」批量操作)。按分组 key 记忆——单一列表只有+ // 一个组(DIALOGUE_GROUP_ALL_KEY);按设备分组时每个设备段各有一个对话组,+ // 折叠互相独立(2026-08-12 实机反馈:共用一个 boolean 会点一个全展开)。+ // 持久化为显示类本地偏好。+ const [collapsedDialogueGroups, setCollapsedDialogueGroups] = useState<ReadonlySet<string>>(() =>+ loadDialogueGroupCollapsedKeys(),+ );+ const setDialogueCollapsed = useCallback((keys: readonly string[], next: boolean) => {+ setCollapsedDialogueGroups((prev) => {+ const nextSet = new Set(prev);+ for (const key of keys) {+ if (next) nextSet.add(key);+ else nextSet.delete(key);+ }+ // 在函数式更新里持久化:批量收起与单组切换共用一条路径;localStorage+ // 同值重写幂等,StrictMode 双调用无副作用差异。+ persistDialogueGroupCollapsedKeys(nextSet);+ return nextSet;+ });+ }, []);+ const toggleDeviceSection = useCallback((key: string) => {+ setCollapsedDevices((prev) => {+ const next = new Set(prev);+ if (next.has(key)) next.delete(key);+ else next.add(key);+ return next;+ });+ }, []);++ // 「展开/收起所有分组」按钮(E 期):+ // 单层(仅组层或仅设备层)→ 收起所有 ↔ 展开所有;+ // 双层(设备 + 组层同时存在)→ 循环:收组层 → 收设备层 → 全部展开。+ // 组层 = 项目行 + 自动任务组 + 「对话」组行。项目侧复用 ProjectNode 折叠状态,+ // 自动任务组复用 owner-scoped 持久化状态,对话组沿用本地显示偏好。+ const hasGroupLayer = mixedEntries.some((entry) => entry.kind !== 'session');+ // 当前可见的对话组 key:设备分组下 = 各含对话组条目的设备段;否则单一组。+ // 「收起/展开所有分组」只作用于这些可见 key,不动其它模式下的记忆。+ const visibleDialogueGroupKeys = useMemo<string[]>(() => {+ if (!deviceGroupingActive) {+ return visibleMixedEntries.some((entry) => entry.kind === 'dialogue-group')+ ? [DIALOGUE_GROUP_ALL_KEY]+ : [];+ }+ return deviceSections+ .filter((section) => section.entries.some((entry) => entry.kind === 'dialogue-group'))+ .map((section) => deviceSectionKey(section.deviceId));+ }, [deviceGroupingActive, visibleMixedEntries, deviceSections]);+ const allDialogueGroupsCollapsed =+ visibleDialogueGroupKeys.length === 0 ||+ visibleDialogueGroupKeys.every((key) => collapsedDialogueGroups.has(key));+ const visibleAutomationGroupKeys = useMemo(+ () =>+ mixedEntries+ .filter(+ (entry): entry is Extract<MainListEntry, { kind: 'automation-group' }> =>+ entry.kind === 'automation-group',+ )+ .map((entry) => entry.group.id),+ [mixedEntries],+ );+ const legacyAutomationGroupKeys = useMemo(+ () =>+ new Map(+ mixedEntries.flatMap((entry) =>+ entry.kind === 'automation-group' && entry.group.legacyId+ ? [[entry.group.id, entry.group.legacyId] as const]+ : [],+ ),+ ),+ [mixedEntries],+ );+ const [+ allAutomationGroupsCollapsed,+ setAllAutomationGroupsCollapsed,+ isAutomationGroupCollapsed,+ setAutomationGroupCollapsed,+ ] = useAutomationGroupsCollapsed(+ visibleAutomationGroupKeys,+ filter.groupBy,+ legacyAutomationGroupKeys,+ );+ // 组层是否收齐必须看**当前范围**有没有项目行。allKnownProjects 是全机器宇宙,+ // 单机范围下本机只有对话组、远端仍有项目时 length>0;isAllCollapsed 却来自+ // 当前范围的 activeWorkingDirs,此时为空并恒为 false,foldState 会卡在+ // collapse-groups。有可见项目行才并上 isAllCollapsed。+ const hasVisibleProjectGroups = mixedEntries.some((entry) => entry.kind === 'project');+ const allGroupsCollapsed =+ (!hasVisibleProjectGroups || isAllCollapsed) &&+ allDialogueGroupsCollapsed &&+ allAutomationGroupsCollapsed;+ const hasDeviceLayer = deviceGroupingActive && deviceSections.length > 0;+ const allDevicesCollapsed =+ hasDeviceLayer &&+ deviceSections.every((section) => collapsedDevices.has(deviceSectionKey(section.deviceId)));+ const foldState: 'collapse-groups' | 'collapse-devices' | 'expand-all' | null = (() => {+ if (!hasGroupLayer && !hasDeviceLayer) return null;+ if (hasGroupLayer && !allGroupsCollapsed) return 'collapse-groups';+ if (hasDeviceLayer && !allDevicesCollapsed) return 'collapse-devices';+ return 'expand-all';+ })();+ const handleFoldAll = useCallback(() => {+ if (foldState === 'collapse-groups') {+ onCollapseAll();+ setDialogueCollapsed(visibleDialogueGroupKeys, true);+ setAllAutomationGroupsCollapsed(true);+ return;+ }+ if (foldState === 'collapse-devices') {+ setCollapsedDevices(+ new Set(deviceSections.map((section) => deviceSectionKey(section.deviceId))),+ );+ return;+ }+ // expand-all:全部层级展开(设备段 + 项目行 + 自动任务组 + 对话组)。+ setCollapsedDevices(new Set());+ onExpandAll();+ setDialogueCollapsed(visibleDialogueGroupKeys, false);+ setAllAutomationGroupsCollapsed(false);+ }, [+ foldState,+ deviceSections,+ visibleDialogueGroupKeys,+ onCollapseAll,+ onExpandAll,+ setDialogueCollapsed,+ setAllAutomationGroupsCollapsed,+ ]);+ const foldLabel =+ foldState === 'collapse-groups'+ ? hasDeviceLayer+ ? t('ccAgent.sidebar.foldAll.collapseProjects')+ : t('ccAgent.sidebar.foldAll.collapseGroups')+ : foldState === 'collapse-devices'+ ? t('ccAgent.sidebar.foldAll.collapseDevices')+ : t('ccAgent.sidebar.foldAll.expandAll');+ const FoldIcon = foldState === 'expand-all' ? ChevronsUpDown : ChevronsDownUp;+ // 散排行的来源标签:平铺时项目会话也要标项目名,不能只喂 dialogues。+ const flattenedSessionsForSourceLabels = useMemo(() => {+ if (filter.groupBy === 'project') return dialogues;+ return [...projects.flatMap((project) => project.sessions), ...dialogues];+ }, [filter.groupBy, projects, dialogues]);+ const dialogueSourceLabelMap = useMemo(+ () =>+ buildSessionSourceLabelMap(+ flattenedSessionsForSourceLabels,+ allKnownProjects,+ t('ccAgent.sidebar.dialogues'),+ ),+ [flattenedSessionsForSourceLabels, allKnownProjects, t],+ );++ // F-PJ-10:即使 projects 因 filter 收窄到空,也要保留段头供用户切回 Filter。+ // 这里用原始 key 全集作为"是否有过任何 project"的判定 — 全部项目都被隐藏时+ // 仍保留段头,用户才能重新选择目录恢复项目。完全没有 project、未分类与对话+ // 时仍画范围标题行(2026-08-13 第 4 轮 review P1:段头恒在),不画列表树。+ // 早退必须在全部 hooks 之后——rules of hooks。+ const hasMainListContent =+ allProjectKeysForOrder.length > 0 ||+ unclassified.length > 0 ||+ dialogues.length > 0 ||+ filter.isFilterActive;++ const renderProjectNode = (project: ProjectNodeData): ReactNode => (+ <ProjectNode+ key={project.projectKey}+ project={project}+ statusFilter={filter.status}+ isCollapsed={collapsed.has(project.projectKey)}+ collapsedAttentionTone={+ collapsed.has(project.projectKey) ? collapsedAttentionToneFor(project.sessions) : null+ }+ parentSectionCollapsed={false}+ activeSessionId={activeSessionId}+ runningSessionIds={runningSessionIds}+ attachedSessionIds={attachedSessionIds}+ notifications={notifications}+ scheduleSessionIndex={scheduleSessionIndex}+ selectedSessionIds={selectedSessionIds}+ disableSessionCollapse={disableSessionCollapse}+ // 按设备分段时段头已写明设备,行内不再重复标注归属(2026-08-12 用户裁决)。+ hideRemoteMachineLabel={deviceGroupingActive}+ onToggle={onToggleProject}+ isProjectPinned={false}+ onToggleProjectPin={onToggleProjectPin}+ onRenameProject={onRenameProject}+ onRemoveFromSidebar={onRemoveFromSidebar}+ onSessionClick={onSessionClick}+ onAction={onAction}+ onRename={onRename}+ onTogglePin={onTogglePin}+ onMoveSession={onMoveSession}+ projectOptions={projectOptions}+ onScheduleAction={onScheduleAction}+ sessionVariant={mainSessionVariant}+ onCreateInProject={onCreateInProject}+ onOpenConversationSearch={onOpenConversationSearch}+ onOpenInExplorer={onOpenInExplorer}+ onLinkCodexProject={onLinkCodexProject}+ linkingCodexProject={linkingCodexProject === project.projectKey}+ onBrowseFiles={onBrowseFiles}+ onArchiveAll={onArchiveAll}+ />+ );++ // 散排任务行 / 自动任务组 / 「对话」组行。散排行与自动任务组带来源标签(hover);+ // 对话组行 = 可折叠的分组头 + 组内会话(折叠上限与对话段旧口径一致)。dialogueGroupKey 标识+ // 该组属于哪个段(设备段 key / 单一列表 DIALOGUE_GROUP_ALL_KEY),折叠独立。+ // dialogueDeviceTarget:按设备分组时该段的设备(null = 本机段),组头新建即落在+ // 这台设备上;不分组时传 undefined,由上层按当前机器作用域推断。+ const renderNonProjectEntry = (+ entry: MainListEntry,+ dialogueGroupKey: string,+ dialogueDeviceTarget?: DialogueDeviceTarget | null,+ ): ReactNode => {+ if (entry.kind === 'session' || entry.kind === 'automation-group') {+ return (+ <SessionEntryRows+ key={entry.kind === 'session' ? entry.session.id : `automation-group:${entry.group.id}`}+ entries={[entry]}+ activeSessionId={activeSessionId}+ runningSessionIds={runningSessionIds}+ attachedSessionIds={attachedSessionIds}+ notifications={notifications}+ selectedSessionIds={selectedSessionIds}+ onSessionClick={onSessionClick}+ onAction={onAction}+ onRename={onRename}+ onTogglePin={onTogglePin}+ onMoveSession={onMoveSession}+ projectOptions={projectOptions}+ onScheduleAction={onScheduleAction}+ automationGroupCollapsed={isAutomationGroupCollapsed}+ onAutomationGroupCollapsedChange={setAutomationGroupCollapsed}+ sourceLabelMap={dialogueSourceLabelMap}+ sessionVariant={mainSessionVariant}+ // 混排下每条散排对话各是一个单条列表,若都补顶线,会与上一行的底线叠成+ // 两根横线(2026-08-12 实机反馈)。底线已覆盖行间分割,这里只关顶线。+ showFirstDivider={false}+ />+ );+ }+ if (entry.kind === 'bot-group') {+ const groupKey = `bot:${entry.bot.botId}`;+ const isCollapsed = collapsedDialogueGroups.has(groupKey);+ return (+ <SessionGroupNode+ key={`bot-group:${entry.bot.botId}`}+ sessions={entry.bot.sessions}+ groupIcon={+ <BotAvatar+ bot={{+ name: entry.bot.displayName,+ avatar: entry.bot.avatar,+ avatarColor: entry.bot.avatarColor,+ }}+ // xs = 20px,与组头 15px 图标同一档视觉重量(头像是实心块,略小于线条图标会显轻)。+ size="xs"+ className="shrink-0"+ />+ }+ groupTitle={entry.bot.displayName}+ createLabel={t('bots.sidebar.newTaskWith', { name: entry.bot.displayName })}+ collapsed={isCollapsed}+ onToggle={() => setDialogueCollapsed([groupKey], !isCollapsed)}+ onCreateDialogue={() => onOpenBot?.(entry.bot.botId)}+ isCreateDisabled={!onOpenBot}+ parentSectionCollapsed={false}+ disableSessionCollapse={disableSessionCollapse}+ activeSessionId={activeSessionId}+ runningSessionIds={runningSessionIds}+ attachedSessionIds={attachedSessionIds}+ notifications={notifications}+ scheduleSessionIndex={scheduleSessionIndex}+ selectedSessionIds={selectedSessionIds}+ onSessionClick={onSessionClick}+ onAction={onAction}+ onRename={onRename}+ onTogglePin={onTogglePin}+ onMoveSession={onMoveSession}+ projectOptions={projectOptions}+ onScheduleAction={onScheduleAction}+ sessionVariant={mainSessionVariant}+ />+ );+ }+ if (entry.kind === 'dialogue-group') {+ const isCollapsed = collapsedDialogueGroups.has(dialogueGroupKey);+ // 目标设备离线时不能在它上面新建(被控端才是真正的创建方)——与远程项目行的+ // 新建同款保护(isDeviceLinkWriteBlocked / actionsUnavailable 文案)。+ const targetDeviceOffline = Boolean(+ dialogueDeviceTarget && !remoteDeviceIndex?.get(dialogueDeviceTarget.deviceId)?.online,+ );+ // 显式目标下不看作用域解析的 pending:目标已定,无需等设备目录 settle。+ const createDisabled =+ (dialogueDeviceTarget === undefined ? isCreateDialogueDisabled : false) ||+ targetDeviceOffline;+ return (+ <SessionGroupNode+ key={`dialogue-group:${dialogueGroupKey}`}+ sessions={entry.sessions}+ collapsed={isCollapsed}+ onToggle={() => setDialogueCollapsed([dialogueGroupKey], !isCollapsed)}+ onCreateDialogue={() => onCreateDialogue(dialogueDeviceTarget)}+ isCreateDisabled={createDisabled}+ createDisabledReason={+ targetDeviceOffline ? t('ccAgent.remoteSession.actionsUnavailable') : undefined+ }+ parentSectionCollapsed={false}+ disableSessionCollapse={disableSessionCollapse}+ activeSessionId={activeSessionId}+ runningSessionIds={runningSessionIds}+ attachedSessionIds={attachedSessionIds}+ notifications={notifications}+ scheduleSessionIndex={scheduleSessionIndex}+ selectedSessionIds={selectedSessionIds}+ onSessionClick={onSessionClick}+ onAction={onAction}+ onRename={onRename}+ onTogglePin={onTogglePin}+ onMoveSession={onMoveSession}+ projectOptions={projectOptions}+ onScheduleAction={onScheduleAction}+ sessionVariant={mainSessionVariant}+ />+ );+ }+ return null;+ };return (<div className="flex flex-col gap-0.5 w-full">