Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): retain projects after sessions are removed
zyaoii246052dda719
diff --git a/apps/desktop/drizzle/0090_retain_all_recent_workdirs.sql b/apps/desktop/drizzle/0090_retain_all_recent_workdirs.sqlnew file mode 100644index 0000000000..e0ac49d1ec--- /dev/null+++ b/apps/desktop/drizzle/0090_retain_all_recent_workdirs.sql@@ -0,0 +1 @@+SELECT 1;diff --git a/apps/desktop/drizzle/meta/0090_snapshot.json b/apps/desktop/drizzle/meta/0090_snapshot.jsonnew file mode 100644index 0000000000..b4989354ae--- /dev/null+++ b/apps/desktop/drizzle/meta/0090_snapshot.json@@ -0,0 +1,4246 @@+{+ "id": "3ab67be6-1d93-4efc-8e4a-ed8d828ad41d",+ "prevId": "36f4dec3-66f7-4a85-b5ec-eb2212ca69c6",+ "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": {}+ },+ "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_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+ }+ },+ "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": {}+ },+ "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+ }+ },+ "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+ }+ },+ "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": {}+ },+ "schedules": {+ "name": "schedules",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "prompt": {+ "name": "prompt",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "job_type": {+ "name": "job_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'prompt'"+ },+ "job_config": {+ "name": "job_config",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "execution_mode": {+ "name": "execution_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'agent'"+ },+ "script_config": {+ "name": "script_config",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'user'"+ },+ "project_config_id": {+ "name": "project_config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "legacy_session_fallback": {+ "name": "legacy_session_fallback",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'cron'"+ },+ "cron_expr": {+ "name": "cron_expr",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "timezone": {+ "name": "timezone",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "recurring": {+ "name": "recurring",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "manual": {+ "name": "manual",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "interval_ms": {+ "name": "interval_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "effort": {+ "name": "effort",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "fast_mode": {+ "name": "fast_mode",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "working_dir": {+ "name": "working_dir",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_kind": {+ "name": "workspace_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'project'"+ },+ "use_worktree": {+ "name": "use_worktree",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "target_session_id": {+ "name": "target_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "persistent_session": {+ "name": "persistent_session",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "silent_when_idle": {+ "name": "silent_when_idle",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "pre_run_hook_command": {+ "name": "pre_run_hook_command",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "pre_run_hook_timeout_ms": {+ "name": "pre_run_hook_timeout_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "skip_log_session_id": {+ "name": "skip_log_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "notify_desktop": {+ "name": "notify_desktop",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "notify_feishu": {+ "name": "notify_feishu",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "notify_wecom_group": {+ "name": "notify_wecom_group",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_fired_at": {+ "name": "last_fired_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_finished_at": {+ "name": "last_finished_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "next_fire_at": {+ "name": "next_fire_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expire_at": {+ "name": "expire_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_schedules_active_next": {+ "name": "idx_schedules_active_next",+ "columns": [+ "status",+ "next_fire_at"+ ],+ "isUnique": false+ },+ "idx_schedules_target_session": {+ "name": "idx_schedules_target_session",+ "columns": [+ "target_session_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "schedules_target_session_id_sessions_id_fk": {+ "name": "schedules_target_session_id_sessions_id_fk",+ "tableFrom": "schedules",+ "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+ },+ "fast_mode": {+ "name": "fast_mode",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "plan_mode_enabled": {+ "name": "plan_mode_enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "cleared_at": {+ "name": "cleared_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "pinned_at": {+ "name": "pinned_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_send_at": {+ "name": "user_send_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'cc'"+ },+ "orca_role": {+ "name": "orca_role",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "parent_session_id": {+ "name": "parent_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "forked_at_message_id": {+ "name": "forked_at_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "worktree_path": {+ "name": "worktree_path",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'desktop'"+ },+ "feishu_open_id": {+ "name": "feishu_open_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "feishu_bot_app_id": {+ "name": "feishu_bot_app_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "im_bot_context_id": {+ "name": "im_bot_context_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "im_user_id": {+ "name": "im_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "used_project_context": {+ "name": "used_project_context",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "codex_history_has_product_prompt": {+ "name": "codex_history_has_product_prompt",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "extra_dirs": {+ "name": "extra_dirs",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "remote_host_id": {+ "name": "remote_host_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "active_turn_started_at": {+ "name": "active_turn_started_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "active_turn_pid": {+ "name": "active_turn_pid",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_turn_ended_at": {+ "name": "last_turn_ended_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_sessions_updated_at": {+ "name": "idx_sessions_updated_at",+ "columns": [+ "updated_at"+ ],+ "isUnique": false+ },+ "idx_sessions_user_send_at": {+ "name": "idx_sessions_user_send_at",+ "columns": [+ "user_send_at"+ ],+ "isUnique": false+ },+ "idx_sessions_sdk_session_id": {+ "name": "idx_sessions_sdk_session_id",+ "columns": [+ "sdk_session_id"+ ],+ "isUnique": false+ },+ "idx_sessions_workdir_created": {+ "name": "idx_sessions_workdir_created",+ "columns": [+ "working_dir",+ "created_at",+ "id"+ ],+ "isUnique": false+ },+ "idx_sessions_created_at": {+ "name": "idx_sessions_created_at",+ "columns": [+ "created_at",+ "id"+ ],+ "isUnique": false+ },+ "idx_sessions_workspace_kind": {+ "name": "idx_sessions_workspace_kind",+ "columns": [+ "workspace_kind"+ ],+ "isUnique": false+ },+ "idx_sessions_parent_session_id": {+ "name": "idx_sessions_parent_session_id",+ "columns": [+ "parent_session_id"+ ],+ "isUnique": false+ },+ "idx_sessions_orca_role": {+ "name": "idx_sessions_orca_role",+ "columns": [+ "orca_role"+ ],+ "isUnique": false+ },+ "idx_sessions_worktree_path": {+ "name": "idx_sessions_worktree_path",+ "columns": [+ "worktree_path"+ ],+ "isUnique": false+ },+ "idx_sessions_feishu_lookup": {+ "name": "idx_sessions_feishu_lookup",+ "columns": [+ "source",+ "feishu_bot_app_id",+ "feishu_open_id"+ ],+ "isUnique": false+ },+ "idx_sessions_im_lookup": {+ "name": "idx_sessions_im_lookup",+ "columns": [+ "source",+ "im_bot_context_id",+ "im_user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "sessions_parent_session_id_sessions_id_fk": {+ "name": "sessions_parent_session_id_sessions_id_fk",+ "tableFrom": "sessions",+ "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_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+ },+ "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+ },+ "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+ }+ }+ }+ }+ }+}\ No newline at end of filediff --git a/apps/desktop/drizzle/meta/_journal.json b/apps/desktop/drizzle/meta/_journal.jsonindex 7b10d90b09..56ab6c4cd3 100644--- a/apps/desktop/drizzle/meta/_journal.json+++ b/apps/desktop/drizzle/meta/_journal.json@@ -631,6 +631,13 @@"when": 1786257834139,"tag": "0089_rich_power_pack","breakpoints": true+ },+ {+ "idx": 90,+ "version": "6",+ "when": 1786527610111,+ "tag": "0090_retain_all_recent_workdirs",+ "breakpoints": true}]-}+}\ No newline at end of filediff --git a/apps/desktop/drizzle/scripts/0090_retain_all_recent_workdirs.ts b/apps/desktop/drizzle/scripts/0090_retain_all_recent_workdirs.tsnew file mode 100644index 0000000000..1775e37330--- /dev/null+++ b/apps/desktop/drizzle/scripts/0090_retain_all_recent_workdirs.ts@@ -0,0 +1,85 @@+import type Database from 'better-sqlite3';++function canonicalize(raw: string, platform: NodeJS.Platform): string | null {+ 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,+ ),+ );+ if (sessionColumns.has('working_dir')) {+ 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) != ''"];+ if (sessionColumns.has('source')) predicates.push("source = 'desktop'");+ 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 --git a/apps/desktop/src/main/localDb/__tests__/retainAllRecentWorkdirsMigration.test.ts b/apps/desktop/src/main/localDb/__tests__/retainAllRecentWorkdirsMigration.test.tsnew file mode 100644index 0000000000..f36430b301--- /dev/null+++ b/apps/desktop/src/main/localDb/__tests__/retainAllRecentWorkdirsMigration.test.ts@@ -0,0 +1,179 @@+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 {+ 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;+ 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 (?, 'desktop', 'project', ?, ?, ?, ?, ?, ?)`,+ ).run(+ input.id,+ 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', () => {+ 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('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('replays safely against a sparse legacy sessions table', () => {+ 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);+ `);++ migration.run(db);++ expect(recentRows()).toEqual([{ path: '/workspace/legacy', last_used_at: 4_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,+ );++ 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 },+ ]);+ });++ 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 --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.tsindex 2cfb196e8f..bba1d5591d 100644--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts@@ -311,6 +311,8 @@ 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 'session.agentSwitchFallback':return sessionAgentSwitchFallback(readyDb, request.args);case 'message.delete':@@ -326,6 +328,21 @@ function dispatchTx(readyDb, payload) {}}+// ⚠️ 与 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(() => {+ readyDb.prepare(+ 'INSERT INTO recent_workdirs (path, last_used_at) SELECT COALESCE((SELECT path FROM recent_workdirs WHERE LOWER(path) = LOWER(?) ORDER BY last_used_at DESC, rowid ASC LIMIT 1), ?), MAX(?, COALESCE(MAX(last_used_at), 0)) FROM recent_workdirs WHERE LOWER(path) = LOWER(?) ON CONFLICT(path) DO UPDATE SET last_used_at = MAX(recent_workdirs.last_used_at, excluded.last_used_at)',+ ).run(path, path, lastUsedAt, path);+ readyDb.prepare(+ 'DELETE FROM recent_workdirs WHERE LOWER(path) = LOWER(?) AND path != (SELECT path FROM recent_workdirs WHERE LOWER(path) = LOWER(?) ORDER BY last_used_at DESC, rowid ASC LIMIT 1)',+ ).run(path, path);+ })();+}+// ⚠️ 与 worker/opHandlers/tx.ts 的 imDeleteBindings 保持一致。function imDeleteBindings(readyDb, args) {const payload = asRecord(args, 'im.deleteBindings args');diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.tsindex c5ac70c7a1..72b8335f8e 100644--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts@@ -17,6 +17,10 @@ CREATE TABLE migration_history (content_hash TEXT NOT NULL,applied_at INTEGER NOT NULL);+CREATE TABLE recent_workdirs (+ path TEXT PRIMARY KEY NOT NULL,+ last_used_at INTEGER NOT NULL+);CREATE TABLE sessions (id TEXT PRIMARY KEY,title TEXT NOT NULL DEFAULT 'New Maker',@@ -862,6 +866,64 @@ 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('sessions.renameTitles applies title changes atomically with preconditions', async () => {await withClient(async (client) => {await seedSession(client, 's1', {diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex f3f62999e8..76be55b991 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -19,6 +19,7 @@ export type DbTxName =| 'orca.reconcileInactiveTeamWorkersForLead'| 'sessions.renameTitles'| 'sessions.setStatus'+ | 'recentWorkdirs.mergeWindowsIdentity'| 'session.agentSwitchFallback'| 'message.delete'| 'im.deleteBindings'@@ -736,6 +737,12 @@ export interface WechatUnbindCleanupResult {filePaths: string[];}+export interface RecentWorkdirsMergeWindowsIdentityArgs {+ /** Canonical lowercase Windows drive or UNC path. */+ path: string;+ lastUsedAt: number;+}+export type DbTxArgsByName = {'codex.importMessages': CodexImportMessagesArgs;'claude.importMessages': ClaudeImportMessagesArgs;@@ -757,6 +764,7 @@ export type DbTxArgsByName = {'orca.reconcileInactiveTeamWorkersForLead': OrcaReconcileInactiveTeamWorkersForLeadArgs;'sessions.renameTitles': SessionsRenameTitlesArgs;'sessions.setStatus': SessionsSetStatusArgs;+ 'recentWorkdirs.mergeWindowsIdentity': RecentWorkdirsMergeWindowsIdentityArgs;'session.agentSwitchFallback': SessionAgentSwitchFallbackArgs;'message.delete': MessageDeleteArgs;'im.deleteBindings': ImDeleteBindingsArgs;@@ -802,6 +810,7 @@ export type DbTxResultByName = {'orca.reconcileInactiveTeamWorkersForLead': string[];'sessions.renameTitles': SessionsRenameTitleResult[];'sessions.setStatus': SessionsSetStatusResultItem[];+ 'recentWorkdirs.mergeWindowsIdentity': undefined;'session.agentSwitchFallback': undefined;'message.delete': MessageDeleteResult;'im.deleteBindings': undefined;diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/recentWorkdirsDelete.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/recentWorkdirsDelete.test.tsindex c73b120d0d..655c9282b0 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/recentWorkdirsDelete.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/recentWorkdirsDelete.test.ts@@ -29,9 +29,7 @@ vi.mock('electron', () => ({}),},BrowserWindow: {- getAllWindows: () => [- { isDestroyed: () => false, webContents: { send: h.webContentsSend } },- ],+ getAllWindows: () => [{ isDestroyed: () => false, webContents: { send: h.webContentsSend } }],},}));vi.mock('../../../logger', () => ({@@ -41,7 +39,7 @@ vi.mock('../../client/current', () => ({getDbClient: () => ({ drizzle: h.db }),}));-import { registerRecentWorkdirsIpc } from '../recentWorkdirs';+import { registerRecentWorkdirsIpc, removeRecentWorkdir } from '../recentWorkdirs';function createDb(): void {h.sqlite?.close();@@ -52,15 +50,24 @@ function createDb(): void {last_used_at INTEGER NOT NULL);CREATE INDEX idx_recent_workdirs_last_used_at ON recent_workdirs(last_used_at);+ CREATE TABLE sessions (+ id TEXT PRIMARY KEY NOT NULL,+ working_dir TEXT,+ status TEXT NOT NULL DEFAULT 'active',+ workspace_kind TEXT NOT NULL DEFAULT 'project',+ remote_host_id TEXT,+ agent_kind TEXT NOT NULL DEFAULT 'cc'+ );`);h.sqlite = sqlite;h.db = drizzle(sqlite);}function seed(path: string, lastUsedAt: number): void {- h.sqlite!- .prepare('INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?)')- .run(path, lastUsedAt);+ h.sqlite!.prepare('INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?)').run(+ path,+ lastUsedAt,+ );}function rows(): Array<{ path: string }> {@@ -119,6 +126,27 @@ describe('local-db:recent-workdirs:remove', () => {expect(rows()).toEqual([]);});+ it('removes every legacy Windows casing variant for the same drive/UNC identity', async () => {+ seed('D:/Work/Project-A', 1_000);+ seed('d:/work/project-a', 2_000);+ seed('//Server/Share/Project-B', 3_000);+ seed('//server/share/project-b', 4_000);++ await removeRecentWorkdir('D:\\WORK\\PROJECT-A', 'win32');+ await removeRecentWorkdir('\\\\SERVER\\SHARE\\PROJECT-B', 'win32');++ expect(rows()).toEqual([]);+ });++ it('does not fold POSIX path casing when removing on Windows', async () => {+ seed('/Workspace/Project-A', 1_000);+ seed('/workspace/project-a', 2_000);++ await invoke('local-db:recent-workdirs:remove', { path: '/Workspace/Project-A' });++ expect(rows()).toEqual([{ path: '/workspace/project-a' }]);+ });+it('is idempotent: missing path resolves deleted:false without broadcasting', async () => {const res = (await invoke('local-db:recent-workdirs:remove', {path: '/not/in/table',@@ -178,4 +206,41 @@ describe('local-db:recent-workdirs:list exists probe', () => {expect(list[2].exists).toBe(false);expect(typeof list[0].lastUsedAt).toBe('string');});++ it('returns every explicitly retained project instead of truncating at ten', async () => {+ for (let i = 0; i < 14; i += 1) {+ seed(`/not-mounted/project-${i}`, 1_000 + i);+ }++ const list = (await invoke('local-db:recent-workdirs:list')) as Array<{ path: string }>;++ expect(list).toHaveLength(14);+ expect(list[0]?.path).toBe('/not-mounted/project-13');+ expect(list[13]?.path).toBe('/not-mounted/project-0');+ });++ it('retains agent-kind history after the last project session is soft-deleted', async () => {+ seed('/workspace/codex-only', 1_786_500_000_000);+ h.sqlite!+ .prepare(+ `INSERT INTO sessions (id, working_dir, status, workspace_kind, remote_host_id, agent_kind)+ VALUES (?, ?, 'active', 'project', NULL, 'codex')`,+ )+ .run('codex-session', '/workspace/codex-only');+ h.sqlite!+ .prepare("UPDATE sessions SET status = 'deleted' WHERE id = ?")+ .run('codex-session');++ const list = (await invoke('local-db:recent-workdirs:list')) as Array<{+ path: string;+ knownAgentKinds: string[];+ }>;++ expect(list).toEqual([+ expect.objectContaining({+ path: '/workspace/codex-only',+ knownAgentKinds: ['codex'],+ }),+ ]);+ });});diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/recentWorkdirsLru.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/recentWorkdirsLru.test.tsdeleted file mode 100644index adf02de2d1..0000000000--- a/apps/desktop/src/main/localDb/ipc/__tests__/recentWorkdirsLru.test.ts+++ /dev/null@@ -1,202 +0,0 @@-/**- * recentWorkdirsLru.test.ts — upsertRecentWorkdir 的 LRU 驱逐回归。- *- * 背景:驱逐原先写成 `getDbClient().drizzle.run(sql`...`)`。main 侧拿到的 drizzle 是- * createDrizzleProxy 的代理,只把 **query builder** 的终结方法转发给 worker RPC;直接在- * db 对象上跑 raw SQL 不经过 builder,会落进代理内部只会抛错的 fakeSqliteClient.prepare(),- * 再被 drizzle 包成 "Failed to run the query '...'",最后被 fire-and-forget 的 catch 吞成- * 一条 warn —— 驱逐 100% 静默失败,表一直涨过上限(线上实测 18 行 > 上限 10)。- *- * 所以 harness 必须用**代理**建,不能用真实 `drizzle(sqlite)`:同样的用例在真实 drizzle 上- * 会假绿,这正是 bug 当初溜过去的原因(见 recentWorkdirsDelete.test.ts 的 harness)。- */-import Database from 'better-sqlite3';-import { sql } from 'drizzle-orm';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import type { DbTransport } from '../../client/DbTransport.js';--/** 与 recentWorkdirs.ts 的模块私有常量对齐(未 export,这里跟随其语义硬编码)。 */-const MAX_RECENT_WORKDIRS = 10;--const h = vi.hoisted(() => ({- sqlite: null as InstanceType<typeof import('better-sqlite3')> | null,- client: null as { drizzle: unknown; exec: unknown } | null,- warns: [] as unknown[],- /** 本次 upsert 实际发给 backend 的 SQL,用于断言驱逐没退化成 SELECT + DELETE 两步。 */- statements: [] as string[],-}));--vi.mock('electron', () => ({- ipcMain: { handle: vi.fn() },- BrowserWindow: { getAllWindows: () => [] },-}));-vi.mock('../../../logger', () => ({- createLogger: () => ({- debug: vi.fn(),- info: vi.fn(),- warn: (...args: unknown[]) => {- h.warns.push(args);- },- error: vi.fn(),- }),-}));-vi.mock('../../client/current', () => ({- getDbClient: () => h.client,-}));--import { createDrizzleProxy } from '../../client/drizzleProxy';-import { upsertRecentWorkdir } from '../recentWorkdirs';--/**- * 假 transport:按 worker/dispatcher.ts 的 op 语义把 SQL 转发给真实 in-memory SQLite。- * 逐条对齐 worker/opHandlers:query → stmt.all / queryOne → stmt.get /- * run|exec → stmt.run / rawAll → stmt.raw().all / rawGet → stmt.raw().get- * (raw* 返回数组而非对象,见 opHandlers/rawAll.ts、rawGet.ts)。- */-function createTransport(): DbTransport {- return {- send: async (op: string, args?: unknown) => {- const { sql: text, params = [] } = (args ?? {}) as { sql: string; params?: unknown[] };- h.statements.push(text.replace(/\s+/g, ' ').trim());- const stmt = h.sqlite!.prepare(text);- if (op === 'query') return stmt.all(...(params as never[]));- if (op === 'queryOne') return stmt.get(...(params as never[]));- if (op === 'rawAll') return stmt.raw().all(...(params as never[]));- if (op === 'rawGet') return stmt.raw().get(...(params as never[]));- if (op === 'run' || op === 'exec') return stmt.run(...(params as never[]));- throw new Error(`unexpected op: ${op}`);- },- on: () => {},- onTerminated: () => {},- close: async () => {},- } as unknown as DbTransport;-}--function rows(): Array<{ path: string; last_used_at: number }> {- return h.sqlite!- .prepare('SELECT path, last_used_at FROM recent_workdirs ORDER BY last_used_at DESC')- .all() as Array<{ path: string; last_used_at: number }>;-}--beforeEach(() => {- h.sqlite?.close();- const sqlite = new Database(':memory:');- sqlite.exec(`- CREATE TABLE recent_workdirs (- path TEXT PRIMARY KEY NOT NULL,- last_used_at INTEGER NOT NULL- );- CREATE INDEX idx_recent_workdirs_last_used_at ON recent_workdirs(last_used_at);- `);- h.sqlite = sqlite;- h.warns = [];- h.statements = [];-- const transport = createTransport();- h.client = {- drizzle: createDrizzleProxy(() => transport),- // upsert 与驱逐必须全程留在上面这个**已捕获**的 drizzle handle 上。走 client.exec- // 会在 in-proc fallback 下于调用时再解析一次模块全局 getRawDb() —— insert 之后若发生- // 账号切换,驱逐就会打到新账号的库。这里故意让 exec 抛错:实现一旦回退去用它,- // 下面的用例立刻变红。- exec: () => {- throw new Error(- 'client.exec must not be used: eviction has to stay on the pinned drizzle handle',- );- },- };-});--describe('upsertRecentWorkdir LRU 驱逐', () => {- it('超过上限时删掉最旧的,只保留 MAX_RECENT_WORKDIRS 条', async () => {- const total = MAX_RECENT_WORKDIRS + 4;- for (let i = 0; i < total; i++) {- await upsertRecentWorkdir(`/Users/dash/Code/proj-${i}`, 1_700_000_000_000 + i * 1_000);- }-- const kept = rows();- expect(kept).toHaveLength(MAX_RECENT_WORKDIRS);- // 保留的必须是 lastUsedAt 最新的那批,最旧的 4 条被驱逐。- expect(kept.map((r) => r.path)).toEqual(- Array.from({ length: MAX_RECENT_WORKDIRS }, (_, k) => `/Users/dash/Code/proj-${total - 1 - k}`),- );- // 驱逐路径不得再走 fire-and-forget 的 catch —— 一条 warn 都不该有。- expect(h.warns).toEqual([]);- });-- it('存量已远超上限时,一次 upsert 就收敛到上限(不是每次只删 1 行)', async () => {- // 模拟修复前留下的脏数据:驱逐长期静默失败,表涨到 18 行(线上实测值)。- for (let i = 0; i < 18; i++) {- h.sqlite!- .prepare('INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?)')- .run(`/Users/dash/Code/stale-${i}`, 1_600_000_000_000 + i * 1_000);- }- expect(rows()).toHaveLength(18);-- await upsertRecentWorkdir('/Users/dash/Code/fresh', 1_700_000_000_000);-- // 子查询里的 `LIMIT -1 OFFSET n` 选中第 n+1 行起的全部行 → 一条 DELETE 一次到位。- const kept = rows();- expect(kept).toHaveLength(MAX_RECENT_WORKDIRS);- expect(kept[0]?.path).toBe('/Users/dash/Code/fresh');- expect(h.warns).toEqual([]);- });-- it('驱逐是单条 DELETE(子查询挑待删行),不退化成 SELECT 快照 + DELETE 两步', async () => {- // 分两步时,fire-and-forget 的并发 upsert 会在 SELECT 与 DELETE 之间刷新被选中的行,- // 前一个调用仍按旧快照把「刚用过的目录」删掉。单语句由 SQLite 原子求值,没有这个窗口。- for (let i = 0; i < MAX_RECENT_WORKDIRS + 2; i++) {- await upsertRecentWorkdir(`/Users/dash/Code/proj-${i}`, 1_700_000_000_000 + i * 1_000);- }-- const sent = h.statements.map((s) => s.toLowerCase());- // 驱逐不得单独发 SELECT 去取快照。- expect(sent.filter((s) => s.startsWith('select'))).toEqual([]);- const deletes = sent.filter((s) => s.startsWith('delete'));- expect(deletes.length).toBeGreaterThan(0);- // 每条 DELETE 都必须自带子查询,而不是 `in (?, ?, …)` 这种按快照展开的形式。- for (const stmt of deletes) expect(stmt).toMatch(/in \(select /);- expect(h.warns).toEqual([]);- });-- it('未超上限时不删任何行', async () => {- for (let i = 0; i < 3; i++) {- await upsertRecentWorkdir(`/Users/dash/Code/proj-${i}`, 1_700_000_000_000 + i * 1_000);- }- expect(rows()).toHaveLength(3);- expect(h.warns).toEqual([]);- });-- it('重复 upsert 同一目录只刷新时间戳,不新增行也不触发驱逐', async () => {- await upsertRecentWorkdir('/Users/dash/Code/proj-a', 1_700_000_000_000);- await upsertRecentWorkdir('/Users/dash/Code/proj-a', 1_700_000_009_000);-- const kept = rows();- expect(kept).toHaveLength(1);- expect(kept[0]).toMatchObject({ path: '/Users/dash/Code/proj-a', last_used_at: 1_700_000_009_000 });- expect(h.warns).toEqual([]);- });-});--describe('drizzleProxy 契约', () => {- it('db 级 raw SQL(db.run(sql`...`))不被代理支持 —— 驱逐不能依赖这条路径', () => {- const proxy = h.client!.drizzle as { run: (q: unknown) => unknown };- // 这就是修复前的写法。注意它是**同步** throw(drizzle better-sqlite3 的 db.run 是- // 同步 API),不是 rejected promise —— 所以原代码 `await db.run(...)` 的错误是靠外层- // try/catch 兜住的。哪天代理开始支持 db 级 raw SQL,这条会变红,提醒回头更新- // recentWorkdirs.ts 里那段注释。- let caught: unknown;- try {- proxy.run(sql`DELETE FROM recent_workdirs WHERE path = 'nope'`);- } catch (err) {- caught = err;- }- expect((caught as Error | undefined)?.message).toMatch(/Failed to run the query/);- // 根因只在 cause 里 —— upsertRecentWorkdir 的 warn 因此必须带上 cause,否则日志- // 只剩一条无因果的 SQL。- expect((caught as Error).cause).toMatchObject({- message: expect.stringContaining('worker RPC'),- });- });-});diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/recentWorkdirsRetention.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/recentWorkdirsRetention.test.tsnew file mode 100644index 0000000000..50b333047c--- /dev/null+++ b/apps/desktop/src/main/localDb/ipc/__tests__/recentWorkdirsRetention.test.ts@@ -0,0 +1,155 @@+/**+ * recentWorkdirsRetention.test.ts — 持久项目目录写入契约。+ *+ * 项目目录与会话生命周期解耦:upsert 只新增或刷新时间,任何自动容量淘汰都会让+ * 已清空会话的项目再次从侧栏消失。条目只由显式 remove IPC 删除。+ */+import Database from 'better-sqlite3';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { DbTransport } from '../../client/DbTransport.js';++const h = vi.hoisted(() => ({+ sqlite: null as InstanceType<typeof import('better-sqlite3')> | null,+ client: null as {+ drizzle: unknown;+ tx: (name: string, args: unknown) => Promise<unknown>;+ } | null,+ warns: [] as unknown[],+}));++vi.mock('electron', () => ({+ ipcMain: { handle: vi.fn() },+ BrowserWindow: { getAllWindows: () => [] },+}));+vi.mock('../../../logger', () => ({+ createLogger: () => ({+ debug: vi.fn(),+ info: vi.fn(),+ warn: (...args: unknown[]) => h.warns.push(args),+ error: vi.fn(),+ }),+}));+vi.mock('../../client/current', () => ({+ getDbClient: () => h.client,+}));++import { createDrizzleProxy } from '../../client/drizzleProxy';+import { upsertRecentWorkdir } from '../recentWorkdirs';++function createTransport(): DbTransport {+ return {+ send: async (op: string, args?: unknown) => {+ const { sql: text, params = [] } = (args ?? {}) as { sql: string; params?: unknown[] };+ const stmt = h.sqlite!.prepare(text);+ if (op === 'query') return stmt.all(...(params as never[]));+ if (op === 'queryOne') return stmt.get(...(params as never[]));+ if (op === 'rawAll') return stmt.raw().all(...(params as never[]));+ if (op === 'rawGet') return stmt.raw().get(...(params as never[]));+ if (op === 'run' || op === 'exec') return stmt.run(...(params as never[]));+ throw new Error(`unexpected op: ${op}`);+ },+ on: () => {},+ onTerminated: () => {},+ close: async () => {},+ } as unknown as DbTransport;+}++function rows(): Array<{ path: string; last_used_at: number }> {+ return h+ .sqlite!.prepare('SELECT path, last_used_at FROM recent_workdirs ORDER BY last_used_at DESC')+ .all() as Array<{ path: string; last_used_at: number }>;+}++beforeEach(() => {+ h.sqlite?.close();+ const sqlite = new Database(':memory:');+ sqlite.exec(`+ CREATE TABLE recent_workdirs (+ path TEXT PRIMARY KEY NOT NULL,+ last_used_at INTEGER NOT NULL+ );+ CREATE INDEX idx_recent_workdirs_last_used_at ON recent_workdirs(last_used_at);+ `);+ h.sqlite = sqlite;+ h.warns = [];+ h.client = {+ drizzle: createDrizzleProxy(() => createTransport()),+ tx: async (name: string, args: unknown) => {+ if (name !== 'recentWorkdirs.mergeWindowsIdentity') throw new Error(`unexpected tx: ${name}`);+ const input = args as { path: string; lastUsedAt: number };+ return h.sqlite!.transaction(() => {+ h.sqlite!.prepare(+ `INSERT INTO recent_workdirs (path, last_used_at)+ SELECT COALESCE(+ (SELECT path FROM recent_workdirs+ WHERE LOWER(path) = LOWER(?)+ ORDER BY last_used_at DESC, rowid ASC LIMIT 1),+ ?+ ),+ MAX(?, COALESCE(MAX(last_used_at), 0))+ FROM recent_workdirs+ WHERE LOWER(path) = LOWER(?)+ ON CONFLICT(path) DO UPDATE SET+ last_used_at = MAX(recent_workdirs.last_used_at, excluded.last_used_at)`,+ ).run(input.path, input.path, input.lastUsedAt, input.path);+ h.sqlite!+ .prepare(+ `DELETE FROM recent_workdirs+ WHERE LOWER(path) = LOWER(?)+ AND path != (+ SELECT path FROM recent_workdirs+ WHERE LOWER(path) = LOWER(?)+ ORDER BY last_used_at DESC, rowid ASC LIMIT 1+ )`,+ )+ .run(input.path, input.path);+ })();+ },+ };+});++describe('upsertRecentWorkdir retention', () => {+ it('retains every explicitly added project even after the list grows beyond ten', async () => {+ const total = 14;+ for (let i = 0; i < total; i += 1) {+ await upsertRecentWorkdir(`/Users/dash/Code/project-${i}`, 1_700_000_000_000 + i * 1_000);+ }++ expect(rows()).toHaveLength(total);+ expect(rows().map((row) => row.path)).toEqual(+ Array.from({ length: total }, (_, index) => `/Users/dash/Code/project-${total - 1 - index}`),+ );+ expect(h.warns).toEqual([]);+ });++ it('refreshes an existing project without inserting a duplicate or regressing activity time', async () => {+ await upsertRecentWorkdir('/Users/dash/Code/project-a', 1_700_000_000_000);+ await upsertRecentWorkdir('/Users/dash/Code/project-a', 1_700_000_009_000);+ await upsertRecentWorkdir('/Users/dash/Code/project-a', 1_700_000_001_000);++ expect(rows()).toEqual([+ { path: '/Users/dash/Code/project-a', last_used_at: 1_700_000_009_000 },+ ]);+ expect(h.warns).toEqual([]);+ });++ it('deduplicates Windows drive and UNC casing while preserving the stable display path', async () => {+ await upsertRecentWorkdir('D:\\Work\\Project-A', 3_000, 'win32');+ await upsertRecentWorkdir('d:/work/project-a/', 2_000, 'win32');+ await upsertRecentWorkdir('\\\\Server\\Share\\Project-B', 4_000, 'win32');+ await upsertRecentWorkdir('//server/share/project-b/', 5_000, 'win32');++ expect(rows()).toEqual([+ { path: '//Server/Share/Project-B', last_used_at: 5_000 },+ { path: 'D:/Work/Project-A', last_used_at: 3_000 },+ ]);+ });++ it('keeps POSIX path casing distinct', async () => {+ await upsertRecentWorkdir('/Workspace/Project-A', 1_000, 'linux');+ await upsertRecentWorkdir('/workspace/project-a', 2_000, 'linux');++ expect(rows()).toHaveLength(2);+ });+});diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.tsindex 18119b36e9..65dc185d72 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts@@ -12,7 +12,7 @@ import Database from 'better-sqlite3';import { drizzle } from 'drizzle-orm/better-sqlite3';import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';-import { messages, sessions } from '../../schema';+import { messages, recentWorkdirs, sessions } from '../../schema';import type { SessionRouteLock } from '../../sessionRouteLock';type SessionRouteLockMock = SessionRouteLock &@@ -20,13 +20,25 @@ type SessionRouteLockMock = SessionRouteLock &const h = vi.hoisted(() => ({db: null as ReturnType<typeof drizzle> | null,+ client: null as { drizzle: ReturnType<typeof drizzle> } | null,sqlite: null as InstanceType<typeof import('better-sqlite3')> | null,handlers: new Map<string, (...args: unknown[]) => unknown>(),relocate: vi.fn(async (): Promise<{ persistedSdkSessionId: string | null }> => ({persistedSdkSessionId: null,})),tapWindowBroadcast: vi.fn(),+ webContentsSend: vi.fn(),summarizeSession: vi.fn(async () => undefined),+ upsertRecentWorkdir: vi.fn(+ async (+ _path: string | null | undefined,+ _atMs?: number,+ _platform?: NodeJS.Platform,+ _client?: { drizzle: ReturnType<typeof drizzle> },+ ) => true,+ ),+ captureOwnerScope: false,+ ownerCurrent: true,routeLock: vi.fn(async <T>(_sessionId: string, task: () => Promise<T>): Promise<T> =>task(),) as SessionRouteLockMock,@@ -38,23 +50,32 @@ vi.mock('electron', () => ({h.handlers.set(channel, handler);}),},- BrowserWindow: { getAllWindows: () => [] },+ app: { getPath: () => 'C:\\cindy-test-user-data' },+ BrowserWindow: {+ getAllWindows: () => [+ { isDestroyed: () => false, webContents: { send: h.webContentsSend } },+ ],+ },}));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,}));vi.mock('../../dialogueWorkspace', () => ({ ensureDialogueWorkspaceDir: vi.fn() }));vi.mock('../../../git-context/prRefsStore', () => ({recomputePrRefsForSession: vi.fn(async () => undefined),}));vi.mock('../../../imageCacheStore', () => ({ removeSession: vi.fn(async () => undefined) }));-vi.mock('../recentWorkdirs', () => ({ upsertRecentWorkdir: 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,+ ),+ isDataOwnerBroadcastScopeCurrent: vi.fn(() => h.ownerCurrent),}));vi.mock('../../../sessionTaskSummary.js', () => ({maybeGenerateSessionTaskSummary: h.summarizeSession,@@ -129,6 +150,10 @@ function createDb(): void {created_at INTEGER NOT NULL,rewind_at INTEGER);+ CREATE TABLE recent_workdirs (+ path TEXT PRIMARY KEY NOT NULL,+ last_used_at INTEGER NOT NULL+ );`);const insert = sqlite.prepare(`INSERT INTO sessions (id, working_dir, agent_kind, remote_host_id, workspace_kind, created_at, updated_at)@@ -144,6 +169,7 @@ function createDb(): void {`).run('review-local', '/review/dir', 'codex', null, 'dialogue');h.sqlite = sqlite;h.db = drizzle(sqlite, { schema: { messages, sessions } });+ h.client = { drizzle: h.db };}async function invokeUpdate(id: string, patch: Record<string, unknown>): Promise<unknown> {@@ -152,10 +178,19 @@ async function invokeUpdate(id: string, patch: Record<string, unknown>): Promisereturn 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);+}+beforeEach(() => {vi.clearAllMocks();h.relocate.mockImplementation(async () => ({ persistedSdkSessionId: null }));h.routeLock.mockImplementation(async (_sessionId, task) => task());+ h.upsertRecentWorkdir.mockImplementation(async () => true);+ h.captureOwnerScope = false;+ h.ownerCurrent = true;h.handlers.clear();createDb();setSessionRouteLockImplementation(h.routeLock);@@ -167,6 +202,103 @@ afterEach(() => {});describe('local-db:sessions:update handler wiring', () => {+ it('touches the retained local project at the soft-delete activity time', async () => {+ h.sqlite!+ .prepare("UPDATE sessions SET workspace_kind = 'project' WHERE id = ?")+ .run('codex-local');+ const now = vi.spyOn(Date, 'now').mockReturnValue(1_786_500_000_000);++ try {+ await invokeUpdate('codex-local', { status: 'deleted' });+ } finally {+ now.mockRestore();+ }++ expect(h.upsertRecentWorkdir).toHaveBeenCalledWith(+ '/old/dir',+ 1_786_500_000_000,+ process.platform,+ h.client,+ );+ expect(h.webContentsSend).toHaveBeenCalledWith('local-db:recent-workdirs:changed', {+ path: '/old/dir',+ });+ });++ it('touches the retained local project when device-link soft-deletes through patch-meta', async () => {+ h.sqlite!+ .prepare("UPDATE sessions SET workspace_kind = 'project' WHERE id = ?")+ .run('codex-local');+ const now = vi.spyOn(Date, 'now').mockReturnValue(1_786_500_100_000);++ try {+ await invokePatchMeta('codex-local', { status: 'deleted' });+ } finally {+ now.mockRestore();+ }++ expect(h.upsertRecentWorkdir).toHaveBeenCalledWith(+ '/old/dir',+ 1_786_500_100_000,+ process.platform,+ h.client,+ );+ expect(h.webContentsSend).toHaveBeenCalledWith('local-db:recent-workdirs:changed', {+ path: '/old/dir',+ });+ });++ it('touches only the handler-entry database and suppresses broadcast after owner switch', async () => {+ h.sqlite!+ .prepare("UPDATE sessions SET workspace_kind = 'project' WHERE id = ?")+ .run('codex-local');+ const oldClient = h.client!;+ const nextSqlite = new Database(':memory:');+ nextSqlite.exec(`+ CREATE TABLE recent_workdirs (+ path TEXT PRIMARY KEY NOT NULL,+ last_used_at INTEGER NOT NULL+ );+ `);+ const nextClient = { drizzle: drizzle(nextSqlite, { schema: { recentWorkdirs } }) };+ h.captureOwnerScope = true;+ h.upsertRecentWorkdir.mockImplementation(+ async (+ _path: string | null | undefined,+ atMs?: number,+ _platform?: NodeJS.Platform,+ client?: typeof oldClient,+ ) => {+ await client!.drizzle+ .insert(recentWorkdirs)+ .values({ path: '/old/dir', lastUsedAt: atMs! });+ return true;+ },+ );+ h.routeLock.mockImplementation(async (_sessionId, task) => {+ const result = await task();+ h.client = nextClient as typeof h.client;+ h.ownerCurrent = false;+ return result;+ });++ try {+ await invokeUpdate('codex-local', { status: 'deleted' });++ expect(+ h.sqlite!.prepare('SELECT path FROM recent_workdirs').all(),+ ).toEqual([{ path: '/old/dir' }]);+ expect(nextSqlite.prepare('SELECT path FROM recent_workdirs').all()).toEqual([]);+ expect(h.webContentsSend).not.toHaveBeenCalledWith(+ 'local-db:recent-workdirs:changed',+ expect.anything(),+ expect.anything(),+ );+ } finally {+ nextSqlite.close();+ }+ });+it('does not resurrect a deleted task through the generic status writer', async () => {h.sqlite!.prepare("UPDATE sessions SET status = 'deleted' WHERE id = ?").run('codex-local');diff --git a/apps/desktop/src/main/localDb/ipc/recentWorkdirs.ts b/apps/desktop/src/main/localDb/ipc/recentWorkdirs.tsindex 792bbccad8..38fd0c083a 100644--- a/apps/desktop/src/main/localDb/ipc/recentWorkdirs.ts+++ b/apps/desktop/src/main/localDb/ipc/recentWorkdirs.ts@@ -11,34 +11,30 @@* session 会经 upsertRecentWorkdir 重新入列,已迁移的死路径则一去不返。* recent 只影响项目列表展示,不再充当 device-link remote-workdir-guard* 的放行依据;远程入口始终实时探测目录当前是否可访问。- * - upsert 不暴露 IPC —— 由 main 内部在 session 创建路径上调用 upsertRecentWorkdir,- * 避免 renderer 私自污染该表。生命周期与 session 解耦:归档 / 删除 session- * 都不影响这张表。+ * - upsert 不暴露 IPC —— 由 main 内部在 session 创建和本地项目软删除路径上调用,+ * 避免 renderer 私自污染该表。生命周期与 session 解耦:归档 / 删除不会移除目录;+ * 软删除会刷新最后活动时间,确保清空会话后的项目仍服从同一活动筛选语义。* - upsert 失败仅日志,不抛 —— 这是"用户体验增强"数据,不该挡住 session 创建主流程。*/import { stat } from 'node:fs/promises';import { BrowserWindow, ipcMain } from 'electron';-import { desc, eq, inArray } from 'drizzle-orm';+import { and, desc, eq, isNotNull, isNull, sql } from 'drizzle-orm';+import type { DbClient } from '../client/DbClient.js';import { getDbClient } from '../client/current';-import { recentWorkdirs } from '../schema';+import { recentWorkdirs, sessions } from '../schema';import { createLogger } from '../../logger';import { requireString } from '../../utils/ipcValidate.js';import { getManagedWorktreeBasePath } from '../../../shared/managedWorktreePaths';+import { normalizeWorkingDirForGrouping } from '../../../shared/workingDir';const log = createLogger('recentWorkdirs');/**- * 最大保留条目数。超过即按 lastUsedAt 升序淘汰最旧条目(LRU)。- * 取 10 是因为下拉 UI 4 条以上就要滚,10 已经远超日常活跃项目数;- * 同时给"重启后再打开第 11 个旧项目"留了缓冲。- */-const MAX_RECENT_WORKDIRS = 10;--/**- * 归一化 recent_workdirs 主键形态,避免同一目录因分隔符差异成多条记录。+ * 归一化 recent_workdirs 存储形态。Windows drive / UNC 的大小写仅用于比较身份,+ * 不改写展示 casing;运行时命名事务负责合并同一比较身份的遗留变体。** 规则(与 projectGrouping.normalizeWorkingDir 同步但**不**做 worktree-strip* —— 这里要保留用户实际选过的目录原样, worktree 折叠是 sidebar 显示语义):@@ -57,6 +53,7 @@ const MAX_RECENT_WORKDIRS = 10;*/export function normalizeRecentWorkdirPath(raw: string | null | undefined,+ localPlatform: NodeJS.Platform = process.platform,): string | null {if (typeof raw !== 'string') return null;const trimmed = raw.trim();@@ -70,67 +67,45 @@ export function normalizeRecentWorkdirPath(return s;}+function isCaseInsensitiveWindowsPath(path: string, localPlatform: NodeJS.Platform): boolean {+ return localPlatform === 'win32' && (/^[A-Za-z]:\//.test(path) || path.startsWith('//'));+}+/**- * upsert: 把一个工作目录的 lastUsedAt 刷成 now (或指定 ms)。已存在则覆盖时间戳;+ * upsert: 把一个工作目录的 lastUsedAt 刷成 now (或指定 ms)。已存在则取较新时间戳;* 不存在则插入。fire-and-forget: 失败仅日志,不影响调用方。*- * path 写入前会被 normalizeRecentWorkdirPath 处理 —— 保证主键唯一形态。+ * path 写入前会被 normalizeRecentWorkdirPath 处理;Windows 大小写身份由命名事务去重。*/export async function upsertRecentWorkdir(path: string | null | undefined,atMs: number = Date.now(),-): Promise<void> {- const normalized = normalizeRecentWorkdirPath(path);- if (!normalized) return;+ localPlatform: NodeJS.Platform = process.platform,+ client?: DbClient,+): Promise<boolean> {+ const normalized = normalizeRecentWorkdirPath(path, localPlatform);+ if (!normalized) return false;try {- // 只取一次 drizzle handle,upsert 与驱逐全程复用它 —— 两端必须 pin 在同一个- // backend 上。getDbClient() 读的是模块级可变 current(账号切换 / client 重新初始化- // 会 set 或 clear 它);而 in-proc fallback client(worker 起不来时装的那个)的- // drizzle 是 getter、exec 则在调用时才解析模块全局 getRawDb()。混用「已捕获的- // drizzle」和「晚绑定的 exec」时,只要 insert 之后这个 fire-and-forget helper 被挂起- // 期间发生账号切换,驱逐就会打到新账号的库上:旧库该裁的没裁,新库反而被裁一行。- const db = getDbClient().drizzle;+ const targetClient = client ?? getDbClient();+ if (isCaseInsensitiveWindowsPath(normalized, localPlatform)) {+ // Windows drive / UNC 的合并与遗留变体清理必须同成同败;命名 tx 在 worker+ // 与 in-proc 共用一条事务实现,MAX 也避免旧调用回退较新的 lastUsedAt。+ await targetClient.tx('recentWorkdirs.mergeWindowsIdentity', {+ path: normalized,+ lastUsedAt: atMs,+ });+ return true;+ }++ const db = targetClient.drizzle;await db.insert(recentWorkdirs).values({ path: normalized, lastUsedAt: atMs }).onConflictDoUpdate({target: recentWorkdirs.path,- set: { lastUsedAt: atMs },+ set: { lastUsedAt: sql`MAX(${recentWorkdirs.lastUsedAt}, ${atMs})` },});- // LRU 驱逐:超过 MAX_RECENT_WORKDIRS 的行按 lastUsedAt 从旧到新淘汰。- //- // 必须是**一条** DELETE,待删集合由子查询在同一条语句里求值 —— 不能先 SELECT 出- // 快照再按快照 DELETE。session 创建路径以 void 调用本 helper(fire-and-forget),两个- // upsert 会交错:若分两步,A 选中最旧的 X 之后 B 刷新了 X,A 仍按旧快照删掉 X ——- // 用户刚用过的目录反而从「最近」里消失,交错还会让列表少于上限。单语句在 SQLite 里- // 原子求值,最坏只是驱逐重复执行(幂等,结果一致)。- //- // 用 query builder 而不是 client.exec 拼 raw SQL,两个原因:- // 1. pin(见上):builder 走的是已捕获的 db handle,不会二次解析 DbClient。- // 2. main 侧的 drizzle 是 createDrizzleProxy 的代理,只把 **query builder** 的终结方法- // 转发给 worker RPC(完整清单见 drizzleProxy.ts 的 terminalMethods:all / get / run /- // values / execute,以及 then / catch / finally 触发的隐式执行)。在 db 对象上跑 raw SQL- // (db.run(sql`...`))不经过 builder,会落进代理内部那个只会抛错的- // fakeSqliteClient.prepare(),被 fire-and-forget 的 catch 吞成一条 warn —— 驱逐- // 100% 静默失败(本 PR 修的就是这个)。子查询的 limit / offset 是 builder 内部的- // SQL 构造,不是 db 级 raw SQL,照样走代理。- //- // SQLite 的 OFFSET 必须跟着 LIMIT,而这里要的是"从第 n+1 行起全部":- // - 不能传 -1(SQLite 表示无上限的写法):drizzle 会把数字 -1 丢掉只留 offset,生成- // `... offset ?`,SQLite 直接报 `near "offset": syntax error`;- // - 也不能传 sql`-1` 绕过:limit() 的类型只收 number | Placeholder,typecheck 不过。- // 所以用 MAX_SAFE_INTEGER 表达"无上限"(表上限十几行,永远取不满)。- //- // 一次删掉所有超出上限的行,不是每次删 1 行:稳态下单条 INSERT 最多新增 1 条,自然- // 也只删 1 条;而驱逐曾长期静默失败留下的脏数据(本机库涨到 18 行)在下一次 upsert- // 就一次清到上限,不用等多轮。- const doomed = db- .select({ path: recentWorkdirs.path })- .from(recentWorkdirs)- .orderBy(desc(recentWorkdirs.lastUsedAt))- .limit(Number.MAX_SAFE_INTEGER)- .offset(MAX_RECENT_WORKDIRS);- await db.delete(recentWorkdirs).where(inArray(recentWorkdirs.path, doomed));+ return true;} catch (err) {log.warn('[localDb] upsertRecentWorkdir failed', {path: normalized,@@ -139,6 +114,7 @@ export async function upsertRecentWorkdir(// 根因全在 cause 里。不带上就只能对着一条无因果的 SQL 反向猜。cause: err instanceof Error && err.cause instanceof Error ? err.cause.message : undefined,});+ return false;}}@@ -157,25 +133,55 @@ async function dirExists(path: string): Promise<boolean> {}}+function recentWorkdirProjectIdentity(+ path: string,+ localPlatform: NodeJS.Platform,+): string | null {+ const grouped = normalizeWorkingDirForGrouping(path);+ if (!grouped) return null;+ return isCaseInsensitiveWindowsPath(grouped, localPlatform) ? grouped.toLowerCase() : grouped;+}+export function registerRecentWorkdirsIpc(): void {ipcMain.handle('local-db:recent-workdirs:list', async () => {const db = getDbClient().drizzle;- // LIMIT 是兜底 —— upsert 已经按 MAX_RECENT_WORKDIRS 驱逐过,- // 这里加 limit 防御任何"绕过 upsert"的写入路径(比如未来的 migration)- // 漏挂驱逐导致 UI 突然出现一长串。- const rows = await db- .select()- .from(recentWorkdirs)- .orderBy(desc(recentWorkdirs.lastUsedAt))- .limit(MAX_RECENT_WORKDIRS);- // 存在性探测:最多 10 条本地路径的并发 access,开销可忽略。+ const rows = await db.select().from(recentWorkdirs).orderBy(desc(recentWorkdirs.lastUsedAt));+ const sessionRows = await db+ .selectDistinct({+ workingDir: sessions.workingDir,+ agentKind: sessions.agentKind,+ })+ .from(sessions)+ .where(+ and(+ eq(sessions.workspaceKind, 'project'),+ isNull(sessions.remoteHostId),+ isNotNull(sessions.workingDir),+ ),+ );+ const knownKindsByPath = new Map<string, Set<string>>();+ for (const session of sessionRows) {+ if (!session.workingDir) continue;+ const identity = recentWorkdirProjectIdentity(session.workingDir, process.platform);+ if (!identity) continue;+ const kinds = knownKindsByPath.get(identity) ?? new Set<string>();+ kinds.add(session.agentKind ?? 'cc');+ knownKindsByPath.set(identity, kinds);+ }+ // 存在性探测与条目数解耦;项目只有显式移除才会退出这份持久目录。const exists = await Promise.all(rows.map((r) => dirExists(r.path)));// 返回 ISO 字符串避免序列化数字时区岐义 —— 跟 sessions IPC 输出风格一致。- return rows.map((r, i) => ({- path: r.path,- lastUsedAt: new Date(r.lastUsedAt).toISOString(),- exists: exists[i],- }));+ return rows.map((r, i) => {+ const identity = recentWorkdirProjectIdentity(r.path, process.platform);+ return {+ path: r.path,+ lastUsedAt: new Date(r.lastUsedAt).toISOString(),+ exists: exists[i],+ knownAgentKinds: Array.from(+ (identity && knownKindsByPath.get(identity)) ?? [],+ ).sort(),+ };+ });});ipcMain.handle('local-db:recent-workdirs:remove', async (_evt, input: unknown) => {@@ -183,16 +189,7 @@ export function registerRecentWorkdirsIpc(): void {const raw = requireString(body.path, 'path');// 归一化后再删,保证与写入侧同一主键形态;归一失败(纯空白等)当 no-op,// 删除本身幂等,不值得为它抛错。- const normalized = normalizeRecentWorkdirPath(raw);- if (!normalized) return { deleted: false };- const db = getDbClient().drizzle;- // 必须显式 .run():worker 代理的 DbClient 对隐式 await 的 DML 走 executeAll,- // 会丢弃 RunResult(见 drizzleProxy.test.ts),导致真删了也报 deleted:false。- const result = (await db- .delete(recentWorkdirs)- .where(eq(recentWorkdirs.path, normalized))- .run()) as { changes?: number } | undefined;- const deleted = (result?.changes ?? 0) > 0;+ const { deleted, normalizedPath: normalized } = await removeRecentWorkdir(raw);log.info('[localDb] recent workdir removed by user', { path: normalized, deleted });// 广播到本机所有窗口:发起删除的 renderer 已乐观 patch 自己的 store,// 其它窗口(以及 device-link 远程调用落地时的被控端窗口)靠这个刷新,@@ -208,3 +205,24 @@ export function registerRecentWorkdirsIpc(): void {return { deleted };});}++/** 可注入平台的删除核心,供跨平台 CI 明确覆盖 Windows drive / UNC identity。 */+export async function removeRecentWorkdir(+ rawPath: string,+ localPlatform: NodeJS.Platform = process.platform,+): Promise<{ deleted: boolean; normalizedPath: string }> {+ const normalized = normalizeRecentWorkdirPath(rawPath, localPlatform);+ if (!normalized) return { deleted: false, normalizedPath: rawPath };+ const db = getDbClient().drizzle;+ // 必须显式 .run():worker 代理的 DbClient 对隐式 await 的 DML 走 executeAll,+ // 会丢弃 RunResult(见 drizzleProxy.test.ts),导致真删了也报 deleted:false。+ const result = (await db+ .delete(recentWorkdirs)+ .where(+ isCaseInsensitiveWindowsPath(normalized, localPlatform)+ ? sql`lower(${recentWorkdirs.path}) = lower(${normalized})`+ : eq(recentWorkdirs.path, normalized),+ )+ .run()) as { changes?: number } | undefined;+ return { deleted: (result?.changes ?? 0) > 0, normalizedPath: normalized };+}diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 3fbb72a9d5..d860156cc4 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -190,6 +190,21 @@ export function broadcastSessionPatched(}}+/** 刷新本机窗口的 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;+ if (hasCapturedScope || ownerStamp !== undefined) {+ w.webContents.send('local-db:recent-workdirs:changed', { path }, ownerStamp);+ } else {+ w.webContents.send('local-db:recent-workdirs:changed', { path });+ }+ }+}+/*** worktree 回收真正跑完后通知本机所有窗口重拉 worktree 快照。*@@ -1342,7 +1357,8 @@ export function registerSessionIpc(const sid = requireString(id, 'id');const ownerScope = captureOwnerScope();const p = requireObject(patch, 'patch');- const db = getDbClient().drizzle;+ const dbClient = getDbClient();+ const db = dbClient.drizzle;if (p.workspaceKind !== undefined) {const value = p.workspaceKind;if (value !== 'project' && value !== 'dialogue') {@@ -1485,12 +1501,18 @@ export function registerSessionIpc(const settingsChanged = Object.keys(p).some((key) => REMOTE_PERSIST_FIELDS.has(key));const titleChanged = p.title !== undefined;if (- projectTargetChanged &&+ (projectTargetChanged || p.status === 'deleted') &&row.workspaceKind === 'project' &&row.workingDir &&!row.remoteHostId) {- await upsertRecentWorkdir(row.workingDir, Date.now());+ 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)) {@@ -1574,7 +1596,8 @@ export async function patchSessionMetaInDb(throwIpcError('INVALID_PARAMS', 'title must be a string');}- const db = getDbClient().drizzle;+ const dbClient = getDbClient();+ const db = dbClient.drizzle;const setObj = sessionPatchToRow(patch, { bumpUpdatedAt: false });// 控制端远程改名走这条,与本机改名同口径(同样先记号后写库)。if (patch.title !== undefined) noteUserTitleWritten(sessionId);@@ -1584,6 +1607,20 @@ export async function patchSessionMetaInDb(if (!row) throwIpcError('NOT_FOUND', 'Session 不存在');return sessionToCamel(row);});+ if (+ patch.status === 'deleted' &&+ updated.workspaceKind === 'project' &&+ updated.workingDir &&+ !updated.remoteHostId+ ) {+ 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,diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex ee50faedc2..6749e1632c 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -75,6 +75,8 @@ export function tx(db: Database.Database, args: unknown): unknown {return sessionsRenameTitles(db, txArgs);case 'sessions.setStatus':return sessionsSetStatus(db, txArgs);+ case 'recentWorkdirs.mergeWindowsIdentity':+ return recentWorkdirsMergeWindowsIdentity(db, txArgs);case 'session.agentSwitchFallback':return sessionAgentSwitchFallback(db, txArgs);case 'message.delete':@@ -124,6 +126,38 @@ export function tx(db: Database.Database, args: unknown): unknown {}}+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.prepare(+ `INSERT INTO recent_workdirs (path, last_used_at)+ SELECT COALESCE(+ (SELECT path FROM recent_workdirs+ WHERE LOWER(path) = LOWER(?)+ ORDER BY last_used_at DESC, rowid ASC LIMIT 1),+ ?+ ),+ MAX(?, COALESCE(MAX(last_used_at), 0))+ FROM recent_workdirs+ WHERE LOWER(path) = LOWER(?)+ ON CONFLICT(path) DO UPDATE SET+ last_used_at = MAX(recent_workdirs.last_used_at, excluded.last_used_at)`,+ ).run(path, path, lastUsedAt, path);+ db.prepare(+ `DELETE FROM recent_workdirs+ WHERE LOWER(path) = LOWER(?)+ AND path != (+ SELECT path FROM recent_workdirs+ WHERE LOWER(path) = LOWER(?)+ ORDER BY last_used_at DESC, rowid ASC LIMIT 1+ )`,+ ).run(path, path);+ });+ transaction();+}+/** 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');diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 7db53e86bb..a188b9ae26 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -4562,7 +4562,7 @@ contextBridge.exposeInMainWorld('electronAPI', {/** 从最近列表移除一条(列表卫生,不动 sessions / 磁盘;再次使用会重新入列)。 */remove: (input: { path: string }): Promise<unknown> =>ipcRenderer.invoke('local-db:recent-workdirs:remove', input),- /** Broadcast: 任一窗口/远程调用删除条目后通知,其它窗口据此重拉列表。 */+ /** Broadcast: 目录移除或活动时间刷新后通知,renderer 据此重拉列表。 */onChanged: createIpcFanOut('local-db:recent-workdirs:changed'),},rightSidebarTabs: {diff --git a/apps/desktop/src/renderer/__tests__/authContextRace.test.ts b/apps/desktop/src/renderer/__tests__/authContextRace.test.tsindex 5c9d1c1144..a5f1f49ffa 100644--- a/apps/desktop/src/renderer/__tests__/authContextRace.test.ts+++ b/apps/desktop/src/renderer/__tests__/authContextRace.test.ts@@ -42,6 +42,7 @@ describe('AuthContext auth-state races', () => {it('publishes a data-owner generation at every auth boundary', () => {expect(source).toContain('cancelRemoteOptimisticSendsForDataOwnerBoundary();');expect(source).toContain('setDataOwnerGeneration(dataOwnerId, ownerGeneration);');+ expect(source).toContain('recentWorkdirsStore.setDataOwner(getDataOwnerGeneration());');expect(source).toContain('invalidateProvidersSnapshot();');expect(source).toContain('publishDataOwnerGeneration(state.dataOwnerId, state.ownerGeneration);',diff --git a/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx b/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsxindex 7bcb369e00..98d38acc6c 100644--- a/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx+++ b/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx@@ -26,6 +26,7 @@ const mocks = vi.hoisted(() => {return {service,reset: vi.fn(),+ setRecentWorkdirsOwner: vi.fn(),getMe: vi.fn(async () => ({ role: 'user' })),clearWorkersCache: vi.fn(),invalidateProvidersSnapshot: vi.fn(),@@ -52,6 +53,9 @@ vi.mock('@/lib/authService', () => ({vi.mock('@/lib/sessionsStore', () => ({sessionsStore: { reset: mocks.reset },}));+vi.mock('@/lib/recentWorkdirsStore', () => ({+ recentWorkdirsStore: { setDataOwner: mocks.setRecentWorkdirsOwner },+}));vi.mock('@/lib/meService', () => ({ getMe: mocks.getMe }));vi.mock('@/features/cc-agent/hooks/useWorkers', () => ({clearWorkersCache: mocks.clearWorkersCache,@@ -133,6 +137,7 @@ describe('AuthContext session cache boundaries', () => {beforeEach(() => {mocks.reset.mockClear();+ mocks.setRecentWorkdirsOwner.mockClear();mocks.getMe.mockClear();mocks.clearWorkersCache.mockClear();mocks.invalidateProvidersSnapshot.mockClear();@@ -162,10 +167,18 @@ describe('AuthContext session cache boundaries', () => {await waitFor(() => expect(view.result.current.user?.id).toBe('account-a'));expect(mocks.reset).toHaveBeenCalledTimes(1);expect(mocks.invalidateProvidersSnapshot).toHaveBeenCalledTimes(1);+ expect(mocks.setRecentWorkdirsOwner).toHaveBeenCalledWith({+ dataOwnerId: 'account-a',+ generation: 1,+ });act(() => mocks.emitAuth(authState('account-b')));expect(mocks.reset).toHaveBeenCalledTimes(2);expect(mocks.invalidateProvidersSnapshot).toHaveBeenCalledTimes(2);+ expect(mocks.setRecentWorkdirsOwner).toHaveBeenCalledWith({+ dataOwnerId: 'account-b',+ generation: 1,+ });act(() => mocks.emitAuth(authState('account-b')));expect(mocks.reset).toHaveBeenCalledTimes(2);diff --git a/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts b/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.tsindex f56c09823e..5b123902b5 100644--- a/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts+++ b/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts@@ -57,9 +57,14 @@ describe('pinned project sidebar integration', () => {expect(dateStart).toBeGreaterThanOrEqual(0);expect(dateEnd).toBeGreaterThan(dateStart);- expect(dateBlock).toContain('pinnedProjectKeys.has(pinnedProjectKey)');expect(dateBlock).toContain(- '[activityFilteredSessions, vendorPredicate, filter.projectsAsSet, pinnedProjectKeys]',+ 'isSessionInProjectComparisonSet(s, pinnedProjectComparisonKeys, localPlatform)',+ );+ expect(dateBlock).toContain(+ 'isSessionInProjectComparisonSet(s, allowedProjectComparisonKeys, localPlatform)',+ );+ expect(dateBlock).toContain(+ 'allowedProjectComparisonKeys,\n pinnedProjectComparisonKeys,\n localPlatform,',);});@@ -102,6 +107,24 @@ describe('pinned project sidebar integration', () => {expect(sidebarSource).toContain('if (restored) return;');});+ it('uses comparison identity for Browse Files and Archive All action membership', () => {+ const browseStart = sidebarSource.indexOf('const handleBrowseFiles = useCallback(');+ const browseEnd = sidebarSource.indexOf('/* ---- Rename handler ---- */', browseStart);+ const archiveStart = sidebarSource.indexOf('const handleArchiveAllInProject = useCallback(');+ const archiveEnd = sidebarSource.indexOf('\n return (', archiveStart);++ expect(browseStart).toBeGreaterThanOrEqual(0);+ expect(browseEnd).toBeGreaterThan(browseStart);+ expect(archiveStart).toBeGreaterThanOrEqual(0);+ expect(archiveEnd).toBeGreaterThan(archiveStart);+ expect(sidebarSource.slice(browseStart, browseEnd)).toContain(+ 'isSessionInProject(s, targetProjectKey, localPlatform)',+ );+ expect(sidebarSource.slice(archiveStart, archiveEnd)).toContain(+ 'isSessionInProject(session, targetProjectKey, localPlatform)',+ );+ });+it('prunes hidden projects from filters in every renderer hook', () => {expect(filterHookSource).toContain('const next = removeProjectsFromFilter(');expect(filterHookSource).toContain(diff --git a/apps/desktop/src/renderer/__tests__/projectGrouping.test.ts b/apps/desktop/src/renderer/__tests__/projectGrouping.test.tsindex 76d9d16847..9f6ce1ce96 100644--- a/apps/desktop/src/renderer/__tests__/projectGrouping.test.ts+++ b/apps/desktop/src/renderer/__tests__/projectGrouping.test.ts@@ -7,14 +7,23 @@import { describe, expect, it } from 'vitest';import {+ buildPersistentLocalProjects,deviceLinkProjectKey,extractDisplayName,+ filterPersistentLocalProjectsByLastActivity,groupSessions,normalizeProjectKey,normalizeWorkingDir,projectIdentityKey,pinnedSessionIdsInDisplayOrder,+ persistentProjectMatchesVendor,} from '@/features/cc-agent/lib/projectGrouping';+import {+ gcProjectsAgainstActive,+ normalizeManualPinnedOrder,+ normalizeManualProjectOrder,+} from '@/features/cc-agent/hooks/helpers/sidebarFilterCore';+import { pinnedProjectEntryId } from '@/features/cc-agent/lib/pinnedSidebarOrder';import type { Session } from '@/lib/ccAgent.types';/* ---------------- helpers ---------------- */@@ -208,6 +217,186 @@ describe('groupSessions', () => {});});+ it('keeps a persistent local project after its last session disappears', () => {+ const r = groupSessions([], {+ persistentLocalProjects: [+ {+ workingDir: 'D:\\AIWork\\empty-project\\',+ lastUsedAt: '2026-08-12T08:00:00.000Z',+ knownAgentKinds: [],+ },+ ],+ });++ expect(r.projects).toEqual([+ expect.objectContaining({+ projectKey: 'local:D:/AIWork/empty-project',+ workingDir: 'D:/AIWork/empty-project',+ displayName: 'empty-project',+ sessions: [],+ latestActivityAt: '2026-08-12T08:00:00.000Z',+ isPersistentLocal: true,+ }),+ ]);+ });++ it('merges a persistent local project with its sessions instead of duplicating it', () => {+ const session = s({ workingDir: 'D:\\AIWork\\Project-A' });+ const r = groupSessions([session], {+ persistentLocalProjects: [+ {+ workingDir: 'd:/aiwork/project-a/',+ lastUsedAt: '2026-08-12T08:00:00.000Z',+ knownAgentKinds: ['cc'],+ },+ ],+ localPlatform: 'win32',+ });++ expect(r.projects).toHaveLength(1);+ expect(r.projects[0]).toMatchObject({+ projectKey: 'local:d:/aiwork/project-a',+ workingDir: 'd:/aiwork/project-a',+ sessions: [session],+ isPersistentLocal: true,+ });+ });++ it('keeps Windows project filter, alias, pin, and order identity after the last session disappears', () => {+ const projectKey = 'local:d:/aiwork/project-a';+ const retainedProject = {+ workingDir: 'd:/aiwork/project-a',+ lastUsedAt: '2026-08-12T08:00:00.000Z',+ knownAgentKinds: ['cc'],+ };+ const aliases = new Map([[projectKey, 'Stable project']]);+ const withSession = groupSessions([s({ workingDir: 'D:\\AIWork\\Project-A' })], {+ persistentLocalProjects: [retainedProject],+ projectAliases: aliases,+ localPlatform: 'win32',+ }).projects[0]!;+ const afterDelete = groupSessions([], {+ persistentLocalProjects: [retainedProject],+ projectAliases: aliases,+ localPlatform: 'win32',+ }).projects[0]!;++ expect(afterDelete.projectKey).toBe(withSession.projectKey);+ expect(withSession.workingDir).toBe('d:/aiwork/project-a');+ expect(afterDelete.displayName).toBe('Stable project');+ expect(gcProjectsAgainstActive([projectKey], [afterDelete.projectKey])).toEqual([projectKey]);+ expect(normalizeManualProjectOrder([projectKey], [afterDelete.projectKey])).toEqual([+ projectKey,+ ]);+ const pinEntry = pinnedProjectEntryId(projectKey);+ expect(normalizeManualPinnedOrder([pinEntry], [pinnedProjectEntryId(afterDelete.projectKey)]))+ .toEqual([pinEntry]);+ });++ it('applies last-activity cutoff to persistent projects using lastUsedAt', () => {+ const projects = [+ {+ workingDir: '/workspace/old',+ lastUsedAt: '2026-07-01T00:00:00.000Z',+ knownAgentKinds: [] as string[],+ },+ {+ workingDir: '/workspace/recent',+ lastUsedAt: '2026-08-10T00:00:00.000Z',+ knownAgentKinds: [] as string[],+ },+ ];++ expect(+ filterPersistentLocalProjectsByLastActivity(+ projects,+ Date.parse('2026-08-01T00:00:00.000Z'),+ ).map((project) => project.workingDir),+ ).toEqual(['/workspace/recent']);+ expect(filterPersistentLocalProjectsByLastActivity(projects, null)).toEqual(projects);+ });++ it('distinguishes a truly empty project from a vendor-mismatched historical project', () => {+ const deletedCcSession = s({+ workingDir: '/workspace/cc-only',+ agentKind: 'cc',+ status: 'deleted',+ });+ const visibleSessionsAfterDeletion = [deletedCcSession].filter(+ (session) => session.status !== 'deleted',+ );+ const persistent = buildPersistentLocalProjects(+ [+ {+ path: '/workspace/cc-only',+ lastUsedAt: '2026-08-12T08:00:00.000Z',+ knownAgentKinds: ['cc'],+ },+ { path: '/workspace/truly-empty', lastUsedAt: '2026-08-12T07:00:00.000Z' },+ ],+ visibleSessionsAfterDeletion,+ 'linux',+ );+ const grouped = groupSessions([], { persistentLocalProjects: persistent });+ const ccOnly = grouped.projects.find((project) => project.workingDir.endsWith('/cc-only'))!;+ const trulyEmpty = grouped.projects.find((project) =>+ project.workingDir.endsWith('/truly-empty'),+ )!;++ expect(ccOnly.persistentLocalKnownAgentKinds).toEqual(['cc']);+ expect(persistentProjectMatchesVendor(ccOnly, 'codex')).toBe(false);+ expect(persistentProjectMatchesVendor(ccOnly, 'cc')).toBe(true);+ expect(trulyEmpty.persistentLocalKnownAgentKinds).toEqual([]);+ expect(persistentProjectMatchesVendor(trulyEmpty, 'codex')).toBe(true);+ });++ it('combines last-activity and vendor filtering without inventing mismatched empty shells', () => {+ const persistent = buildPersistentLocalProjects(+ [+ { path: '/workspace/cc-recent', lastUsedAt: '2026-08-12T08:00:00.000Z' },+ { path: '/workspace/empty-recent', lastUsedAt: '2026-08-12T07:00:00.000Z' },+ { path: '/workspace/empty-old', lastUsedAt: '2026-07-01T00:00:00.000Z' },+ ],+ [s({ workingDir: '/workspace/cc-recent', agentKind: 'cc' })],+ 'linux',+ );+ const activityFiltered = filterPersistentLocalProjectsByLastActivity(+ persistent,+ Date.parse('2026-08-01T00:00:00.000Z'),+ );+ const visibleForCodex = groupSessions([], {+ persistentLocalProjects: activityFiltered,+ }).projects.filter((project) => persistentProjectMatchesVendor(project, 'codex'));++ expect(visibleForCodex.map((project) => project.workingDir)).toEqual([+ '/workspace/empty-recent',+ ]);+ });++ it('does not let an older session regress retained project activity', () => {+ const retainedLastUsedAt = '2026-08-12T08:00:00.000Z';+ const grouped = groupSessions(+ [+ s({+ workingDir: '/workspace/project-a',+ userSendAt: '2026-08-01T08:00:00.000Z',+ updatedAt: '2026-08-01T08:00:00.000Z',+ }),+ ],+ {+ persistentLocalProjects: [+ {+ workingDir: '/workspace/project-a',+ lastUsedAt: retainedLastUsedAt,+ knownAgentKinds: ['cc'],+ },+ ],+ },+ );++ expect(grouped.projects[0]?.latestActivityAt).toBe(retainedLastUsedAt);+ });+it('can keep an individually pinned conversation in the project catalogue', () => {const pinned = s({id: 'pinned-in-project',@@ -891,7 +1080,12 @@ describe('pinnedSessionIdsInDisplayOrder(拖拽 baseline:与置顶段同序 sts({ id: 'p-mid', pinnedAt: '2026-02-15T00:00:00.000Z' }),];// active 段按 pinnedAt desc: p-new, p-mid, p-old;归档置顶排在所有 active 之后。- expect(pinnedSessionIdsInDisplayOrder(sessions)).toEqual(['p-new', 'p-mid', 'p-old', 'p-archived']);+ expect(pinnedSessionIdsInDisplayOrder(sessions)).toEqual([+ 'p-new',+ 'p-mid',+ 'p-old',+ 'p-archived',+ ]);});it('本地 + 远程置顶合并后统一按 pinnedAt desc 排(不分本地 / 远程)', () => {diff --git a/apps/desktop/src/renderer/__tests__/recentWorkdirsStore.test.ts b/apps/desktop/src/renderer/__tests__/recentWorkdirsStore.test.tsnew file mode 100644index 0000000000..c409e69a11--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/recentWorkdirsStore.test.ts@@ -0,0 +1,111 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++describe('recentWorkdirsStore changed push', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ vi.resetModules();+ });++ it('refreshes the cached activity immediately after a main-process touch broadcast', async () => {+ let rows = [+ {+ path: 'D:/Work/Project-A',+ lastUsedAt: '2026-08-10T00:00:00.000Z',+ exists: true,+ },+ ];+ let onChanged: ((payload: unknown, ownerStamp?: unknown) => void) | undefined;+ const list = vi.fn(async () => rows);+ vi.stubGlobal('window', {+ electronAPI: {+ localDb: {+ recentWorkdirs: {+ list,+ remove: vi.fn(),+ onChanged: (callback: typeof onChanged) => {+ onChanged = callback;+ return () => {};+ },+ },+ },+ },+ });++ const { recentWorkdirsStore } = await import('@/lib/recentWorkdirsStore');+ await recentWorkdirsStore.ensure();+ expect(recentWorkdirsStore.get()?.[0]?.lastUsedAt).toBe('2026-08-10T00:00:00.000Z');++ rows = [+ {+ path: 'D:/Work/Project-A',+ lastUsedAt: '2026-08-12T12:00:00.000Z',+ exists: true,+ },+ ];+ onChanged?.({ path: 'D:/Work/Project-A' });++ await vi.waitFor(() => {+ expect(recentWorkdirsStore.get()?.[0]?.lastUsedAt).toBe('2026-08-12T12:00:00.000Z');+ });+ expect(list).toHaveBeenCalledTimes(2);+ });++ it('clears the previous owner cache and fences a late in-flight response', async () => {+ const pending: Array<{+ resolve: (rows: Array<{ path: string; lastUsedAt: string; exists: boolean }>) => void;+ }> = [];+ const list = vi.fn(+ () =>+ new Promise<Array<{ path: string; lastUsedAt: string; exists: boolean }>>((resolve) => {+ pending.push({ resolve });+ }),+ );+ vi.stubGlobal('window', {+ electronAPI: {+ localDb: {+ recentWorkdirs: {+ list,+ remove: vi.fn(),+ onChanged: () => () => {},+ },+ },+ },+ });++ const { recentWorkdirsStore } = await import('@/lib/recentWorkdirsStore');+ recentWorkdirsStore.setDataOwner({ dataOwnerId: 'owner-a', generation: 1 });+ const ownerAInitialRequest = recentWorkdirsStore.ensure();+ expect(list).toHaveBeenCalledTimes(1);+ pending[0]!.resolve([+ { path: '/owner-a/cached', lastUsedAt: '2026-08-12T00:00:00.000Z', exists: true },+ ]);+ await ownerAInitialRequest;+ expect(recentWorkdirsStore.get()?.map((entry) => entry.path)).toEqual([+ '/owner-a/cached',+ ]);++ const ownerARefresh = recentWorkdirsStore.forceRefresh();+ expect(list).toHaveBeenCalledTimes(2);++ recentWorkdirsStore.setDataOwner({ dataOwnerId: 'owner-b', generation: 2 });+ expect(recentWorkdirsStore.get()).toBeNull();+ const ownerBRequest = recentWorkdirsStore.ensure();+ expect(list).toHaveBeenCalledTimes(3);++ pending[2]!.resolve([+ { path: '/owner-b/project', lastUsedAt: '2026-08-13T00:00:00.000Z', exists: true },+ ]);+ await ownerBRequest;+ expect(recentWorkdirsStore.get()?.map((entry) => entry.path)).toEqual([+ '/owner-b/project',+ ]);++ pending[1]!.resolve([+ { path: '/owner-a/project', lastUsedAt: '2026-08-12T00:00:00.000Z', exists: true },+ ]);+ await ownerARefresh;+ expect(recentWorkdirsStore.get()?.map((entry) => entry.path)).toEqual([+ '/owner-b/project',+ ]);+ });+});diff --git a/apps/desktop/src/renderer/__tests__/sidebarProjectVisibility.test.ts b/apps/desktop/src/renderer/__tests__/sidebarProjectVisibility.test.tsindex fc68fe2abc..13f4d58806 100644--- a/apps/desktop/src/renderer/__tests__/sidebarProjectVisibility.test.ts+++ b/apps/desktop/src/renderer/__tests__/sidebarProjectVisibility.test.ts@@ -3,6 +3,8 @@ import { describe, expect, it } from 'vitest';import {buildProjectKeyComparisonSet,isProjectHidden,+ isSessionInProject,+ isSessionInProjectComparisonSet,isSessionInHiddenProject,projectKeyComparisonSetHas,sidebarSessionsWithHiddenProjectsAsDialogues,@@ -127,6 +129,34 @@ describe('sidebar project visibility', () => {).toBe(true);});+ it('uses retained Windows comparison identity for session-level filter and pin selectors', () => {+ const retainedComparisonKeys = buildProjectKeyComparisonSet(+ new Set(['local:d:/aiwork/project-a']),+ 'win32',+ );+ const differentlyCasedSession = session({ workingDir: 'D:\\AIWork\\Project-A' });++ expect(+ isSessionInProjectComparisonSet(+ differentlyCasedSession,+ retainedComparisonKeys,+ 'win32',+ ),+ ).toBe(true);+ });++ it('selects Browse/Archive action members through retained Windows identity', () => {+ const differentlyCasedSession = session({ workingDir: 'D:\\AIWork\\Project-A' });++ expect(+ isSessionInProject(+ differentlyCasedSession,+ 'local:d:/aiwork/project-a',+ 'win32',+ ),+ ).toBe(true);+ });+it('does not hide a different-cased POSIX double-slash project', () => {const hidden = new Set(['local://mnt/Repo']);const lowerCaseProjectTask = session({ workingDir: '//mnt/repo' }) as Session;diff --git a/apps/desktop/src/renderer/contexts/AuthContext.tsx b/apps/desktop/src/renderer/contexts/AuthContext.tsxindex a072dca57d..15263e6f58 100644--- a/apps/desktop/src/renderer/contexts/AuthContext.tsx+++ b/apps/desktop/src/renderer/contexts/AuthContext.tsx@@ -32,6 +32,7 @@ import { isSecondaryWindow } from '@/lib/secondaryWindow';import { setUserPromptOwner } from '@/lib/userPromptStore';import { bootstrapMemorySettingsFromMain, setMemorySettingsOwner } from '@/lib/memorySettingsStore';import { sessionsStore } from '@/lib/sessionsStore';+import { recentWorkdirsStore } from '@/lib/recentWorkdirsStore';import { isSidebarWindow } from '@/lib/sidebarWindow';import { isGhostPanelWindow } from '@/lib/ghostPanelWindow';import { setNewMakerDraftOwner } from '@/state/newMakerDraft';@@ -97,6 +98,7 @@ function publishDataOwnerGeneration(dataOwnerId: string | null, ownerGeneration?cancelRemoteOptimisticSendsForDataOwnerBoundary();}setDataOwnerGeneration(dataOwnerId, ownerGeneration);+ recentWorkdirsStore.setDataOwner(getDataOwnerGeneration());setSelectedMachineOwner(dataOwnerId);if (previousOwnerId !== dataOwnerId) invalidateProvidersSnapshot();}diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsxindex 3009f10378..266ba1e35d 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx@@ -50,6 +50,7 @@ import { cn } from '@/lib/utils';import { toast } from '@/lib/toast';import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';import { useCCSessions } from '@/hooks/useCCSessions';+import { useRecentWorkdirs } from '@/hooks/useRecentWorkdirs';import { refreshPendingAlerts, usePendingAlertAttention } from '@/hooks/usePendingAlertAttention';import { useAppShortcut } from '@/hooks/useAppShortcut';import { useModifierHold } from '@/hooks/useModifierHold';@@ -121,11 +122,15 @@ import { useSessionLifecycleActions } from './hooks/useSessionLifecycleActions';import { useSidebarFilter, type UseSidebarFilterReturn } from './hooks/useSidebarFilter';import { useHiddenProjects, type UseHiddenProjectsReturn } from './hooks/useHiddenProjects';import {+ buildPersistentLocalProjects,+ filterPersistentLocalProjectsByLastActivity,normalizeProjectKey,normalizeWorkingDir,projectIdentityKey,projectIdentityKeyForSession,pinnedSessionIdsInDisplayOrder,+ persistentProjectMatchesVendor,+ type PersistentLocalProject,type ProjectNode,} from './lib/projectGrouping';import { projectDisplayLabelWithMachine } from './lib/remoteProjectIdentity';@@ -140,6 +145,8 @@ import { isOrcaWorkerSession, resolveSessionRoute } from '@/lib/orcaSessionIdentimport {buildProjectKeyComparisonSet,isProjectHidden,+ isSessionInProject,+ isSessionInProjectComparisonSet,projectKeyComparisonSetHas,sidebarSessionsWithHiddenProjectsAsDialogues,visibleSidebarProjects,@@ -401,7 +408,17 @@ export function CCAgentSidebarUpper() {[allSessionsForAttention],);const projectAliases = useProjectAliases();- const searchProjectGroups = useProjectGroups(searchProjectSessions, projectAliases.aliases);+ const { entries: recentWorkdirs } = useRecentWorkdirs();+ const persistentLocalProjects = useMemo<PersistentLocalProject[]>(+ () => buildPersistentLocalProjects(recentWorkdirs, searchProjectSessions, localPlatform),+ [recentWorkdirs, searchProjectSessions, localPlatform],+ );+ const searchProjectGroups = useProjectGroups(+ searchProjectSessions,+ projectAliases.aliases,+ false,+ persistentLocalProjects,+ );const visibleSearchProjects = useMemo(() => visibleSidebarProjects(searchProjectGroups.projects, hiddenProjectKeys, localPlatform),[searchProjectGroups.projects, hiddenProjectKeys, localPlatform],@@ -675,6 +692,7 @@ export function CCAgentSidebarUpper() {hiddenProjects={hiddenProjects}projectAliases={projectAliases}scheduleSessionIndex={scheduleSessionIndex}+ persistentLocalProjects={persistentLocalProjects}/></div></div>@@ -764,6 +782,7 @@ interface ExpandedProps {hiddenProjects: UseHiddenProjectsReturn;projectAliases: ReturnType<typeof useProjectAliases>;scheduleSessionIndex: ReturnType<typeof useAutomationScheduleSessionIndex>;+ persistentLocalProjects: readonly PersistentLocalProject[];}/** rail 未分类隐藏态的空列表(引用稳定,免得 lampScope 发布 effect 空转)。 */@@ -794,6 +813,7 @@ function ExpandedView({hiddenProjects,projectAliases,scheduleSessionIndex,+ persistentLocalProjects,}: ExpandedProps) {const { t, i18n } = useTranslation();const localPlatform = window.electronAPI.platform;@@ -1125,6 +1145,13 @@ function ExpandedView({// 机器切换栏选中机器后整体过滤:本机 → 只本地会话;远程 → 只该机器会话。// 过滤在源头做,下游 grouping / pinned / projects / dialogues / date-grouped / search 自动继承。const selectedMachineId = useEffectiveSelectedMachineId();+ const visiblePersistentLocalProjects = useMemo(+ () =>+ selectedMachineId === MACHINE_ALL || selectedMachineId.includes(MACHINE_LOCAL)+ ? persistentLocalProjects+ : [],+ [persistentLocalProjects, selectedMachineId],+ );const switcherDevices = useSwitcherDevices();const deviceListSettled = useDeviceLinkDeviceListSettled();const selectedDialogueDeviceResolution = useMemo(@@ -1284,21 +1311,45 @@ function ExpandedView({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,+ );+ const groups = useProjectGroups(+ activityFilteredSessions,+ projectAliases.aliases,+ false,+ activityFilteredPersistentLocalProjects,+ );// 普通项目目录也需要保留「所有会话都已单独置顶」的项目身份,供用户继续// 从 ProjectNode 菜单置顶整个项目;实际项目子行在渲染前仍会排除已置顶会话。const groupsWithPinnedProjects = useProjectGroups(activityFilteredSessions,projectAliases.aliases,true,+ activityFilteredPersistentLocalProjects,);// 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,+ );const activeWorkingDirs = useMemo(() => allProjectGroups.projects.map((p) => p.projectKey),[allProjectGroups.projects],@@ -1313,7 +1364,12 @@ function ExpandedView({() => [...sessions, ...remoteProjectSessions].filter(passesOrcaAndStatus),[sessions, remoteProjectSessions, passesOrcaAndStatus],);- const projectUniverse = useProjectGroups(unfilteredProjectSessions, projectAliases.aliases, true);+ const projectUniverse = useProjectGroups(+ unfilteredProjectSessions,+ projectAliases.aliases,+ true,+ persistentLocalProjects,+ );// 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(@@ -1459,19 +1515,31 @@ function ExpandedView({() => buildProjectKeyComparisonSet(hiddenProjectKeys, localPlatform),[hiddenProjectKeys, localPlatform],);+ const allowedProjectComparisonKeys = useMemo(+ () =>+ filter.projectsAsSet === null+ ? null+ : buildProjectKeyComparisonSet(filter.projectsAsSet, localPlatform),+ [filter.projectsAsSet, localPlatform],+ );+ const pinnedProjectComparisonKeys = useMemo(+ () => buildProjectKeyComparisonSet(pinnedProjectKeys, localPlatform),+ [pinnedProjectKeys, localPlatform],+ );const visiblePinnedSessions = useMemo(() => {// 置顶段用 allGroups.pinned(未经"最近活跃 N 天"筛选)——置顶内容不受活跃时间过滤影响,// 久未活跃的置顶会话也始终显示。vendor / project 过滤仍照常生效。return allGroups.pinned.filter((session) => {if (vendorPredicate && !vendorPredicate(session)) return false;- const allowedProjects = filter.projectsAsSet;- if (allowedProjects === null) return true;- if (session.workspaceKind === 'dialogue') return false;- const projectKey = projectIdentityKeyForSession(session);- return projectKey != null && allowedProjects.has(projectKey);+ if (allowedProjectComparisonKeys === null) return true;+ return isSessionInProjectComparisonSet(+ session,+ allowedProjectComparisonKeys,+ localPlatform,+ );});- }, [allGroups.pinned, vendorPredicate, filter.projectsAsSet]);+ }, [allGroups.pinned, vendorPredicate, allowedProjectComparisonKeys, localPlatform]);const visiblePinnedProjects = useMemo(() => {const allowedProjects = filter.projectsAsSet;@@ -1487,7 +1555,13 @@ function ExpandedView({const matchingSessions = vendorPredicate? project.sessions.filter(vendorPredicate): project.sessions;- if (vendorPredicate && matchingSessions.length === 0) return [];+ if (+ vendorPredicate &&+ matchingSessions.length === 0 &&+ !persistentProjectMatchesVendor(project, filter.vendor)+ ) {+ return [];+ }return [{@@ -1503,6 +1577,7 @@ function ExpandedView({hiddenProjectComparisonKeys,pinnedProjectKeys,filter.projectsAsSet,+ filter.vendor,vendorPredicate,]);@@ -1570,7 +1645,13 @@ function ExpandedView({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,@@ -1583,6 +1664,7 @@ function ExpandedView({visibleProjects,pinnedProjectKeys,vendorPredicate,+ filter.vendor,filter.sortBy,filter.manualProjectOrder,]);@@ -1594,7 +1676,13 @@ function ExpandedView({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,@@ -1603,7 +1691,7 @@ function ExpandedView({];});return sortProjectsForSidebar(projects, filter.sortBy, filter.manualProjectOrder);- }, [visibleProjects, vendorPredicate, filter.sortBy, filter.manualProjectOrder]);+ }, [visibleProjects, vendorPredicate, filter.vendor, filter.sortBy, filter.manualProjectOrder]);/*** Pinned 拖拽落定回调。SortableList 给的是当前 visible(含 vendor / projectsFilter@@ -1637,22 +1725,24 @@ function ExpandedView({);const visibleDateSessions = useMemo(() => {- const allowedProjects = filter.projectsAsSet;return activityFilteredSessions.filter((s) => {if (s.pinnedAt != null) return false;if (vendorPredicate && !vendorPredicate(s)) return false;if (s.workspaceKind !== 'dialogue') {- const pinnedProjectKey = projectIdentityKeyForSession(s);- if (pinnedProjectKey != null && pinnedProjectKeys.has(pinnedProjectKey)) return false;+ if (isSessionInProjectComparisonSet(s, pinnedProjectComparisonKeys, localPlatform)) {+ return false;+ }}- if (allowedProjects === null) return true;- if (s.workspaceKind === 'dialogue') return false;- const wd = normalizeWorkingDir(s.workingDir);- if (wd == null) return false;- const key = projectIdentityKeyForSession(s);- return key != null && allowedProjects.has(key);+ if (allowedProjectComparisonKeys === null) return true;+ return isSessionInProjectComparisonSet(s, allowedProjectComparisonKeys, localPlatform);});- }, [activityFilteredSessions, vendorPredicate, filter.projectsAsSet, pinnedProjectKeys]);+ }, [+ activityFilteredSessions,+ vendorPredicate,+ allowedProjectComparisonKeys,+ pinnedProjectComparisonKeys,+ localPlatform,+ ]);const hasVisibleSidebarContent =visiblePinnedEntries.length > 0 ||@@ -2147,7 +2237,7 @@ function ExpandedView({(project: ProjectNode) => {const targetProjectKey = project.projectKey;const inProject = (s: (typeof sessions)[number]): boolean =>- projectIdentityKeyForSession(s) === targetProjectKey && s.status !== 'deleted';+ isSessionInProject(s, targetProjectKey, localPlatform) && s.status !== 'deleted';const navigateToProjectSession = (id: string) => {if (project.scope === 'remote') {navigate(`/cc-agent/${id}`);@@ -2172,7 +2262,7 @@ function ExpandedView({}toast.warning(t('ccAgent.sidebar.browseEmpty'));},- [activeSessionId, sessions, navigate, t],+ [activeSessionId, sessions, navigate, t, localPlatform],);/* ---- Rename handler ---- */@@ -2785,7 +2875,7 @@ function ExpandedView({const targetProjectKey = project.projectKey;const action = projectBulkArchiveActionForStatus(filter.status);const belongsToProject = (session: Session): boolean =>- projectIdentityKeyForSession(session) === targetProjectKey;+ isSessionInProject(session, targetProjectKey, localPlatform);// 只对**本地** sessions 归档:device-link 远程会话的运行态不在本渲染进程(runningSessionIds 是// 本地 makerChatStore 的),无法像本地那样把「正在运行」的排除掉 —— 批量归档时可能把被控端正在@@ -2945,6 +3035,7 @@ function ExpandedView({navigate,patchLocal,filter.status,+ localPlatform,t,],);diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.tsindex ec3e627e8c..a6971b4997 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts@@ -12,18 +12,28 @@ import { useMemo } from 'react';import type { Session } from '@/lib/ccAgent.types';import { useRemoteSshHosts } from '@/hooks/useRemoteSshHosts';-import { groupSessions, type ProjectGroupsResult } from '../lib/projectGrouping';+import {+ groupSessions,+ type PersistentLocalProject,+ type ProjectGroupsResult,+} from '../lib/projectGrouping';import { resolveRemoteProjectMachineIdentity } from '../lib/remoteProjectIdentity';export function useProjectGroups(sessions: readonly Session[],projectAliases?: ReadonlyMap<string, string>,includePinnedInProjects: boolean = false,+ persistentLocalProjects?: readonly PersistentLocalProject[],): ProjectGroupsResult {const sshHosts = useRemoteSshHosts();return useMemo(() => {- const groups = groupSessions(sessions, { projectAliases, includePinnedInProjects });+ const groups = groupSessions(sessions, {+ projectAliases,+ includePinnedInProjects,+ persistentLocalProjects,+ localPlatform: window.electronAPI.platform,+ });return {...groups,projects: groups.projects.map((project) => ({@@ -31,5 +41,5 @@ export function useProjectGroups(remoteMachineIdentity: resolveRemoteProjectMachineIdentity(project, sshHosts),})),};- }, [sessions, projectAliases, includePinnedInProjects, sshHosts]);+ }, [sessions, projectAliases, includePinnedInProjects, persistentLocalProjects, sshHosts]);}diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.ts b/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.tsindex 91c046941d..eeb9998f33 100644--- a/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.ts+++ b/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.ts@@ -50,12 +50,7 @@ import {} from '../../../../shared/projectKeys';import type { RemoteProjectMachineIdentity } from './remoteProjectIdentity';-export {- deviceLinkProjectKey,- normalizeProjectKey,- projectKeyComparisonKey,- projectIdentityKey,-};+export { deviceLinkProjectKey, normalizeProjectKey, projectKeyComparisonKey, projectIdentityKey };/* ============================== Types ============================== */@@ -96,6 +91,10 @@ export interface ProjectNode {sessions: Session[];/** 组内任意 session 的最大 sortTime(userSendAt ?? updatedAt),用于 Project 间排序 */latestActivityAt: string;+ /** 来自本地持久项目目录;即使当前视图没有匹配会话也应保留项目节点。 */+ isPersistentLocal?: boolean;+ /** 该持久项目在全量本地会话中出现过的 agentKind;空数组表示真正零会话。 */+ persistentLocalKnownAgentKinds?: readonly string[];}export interface ProjectGroupsResult {@@ -114,6 +113,24 @@ export interface GroupSessionsOptions {* when every conversation inside it is pinned.*/includePinnedInProjects?: boolean;+ /** 与会话生命周期解耦的本地项目目录,用于保留零会话项目。 */+ persistentLocalProjects?: readonly PersistentLocalProject[];+ /** 本地路径身份比较所需的平台;Windows 盘符与 UNC 路径忽略大小写。 */+ localPlatform?: string;+}++export interface PersistentLocalProject {+ workingDir: string;+ lastUsedAt: string;+ /** 全量本地会话历史中的 agentKind;用于区分真正空项目与 vendor 不匹配。 */+ knownAgentKinds: readonly string[];+}++export interface RecentLocalProjectEntry {+ path: string;+ lastUsedAt: string;+ /** 持久层从包含软删除行的会话历史聚合出的 agentKind。 */+ knownAgentKinds?: readonly string[];}/* ============================== normalize ============================== */@@ -132,13 +149,79 @@ export interface GroupSessionsOptions {*/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 {const workingDir = normalizeWorkingDir(session.workingDir);if (workingDir == null) return null;- if (session.deviceLinkDeviceId) return deviceLinkProjectKey(session.deviceLinkDeviceId, workingDir);- return projectIdentityKey(session.remoteHostId ? 'remote' : 'local', workingDir, session.remoteHostId ?? null);+ if (session.deviceLinkDeviceId)+ return deviceLinkProjectKey(session.deviceLinkDeviceId, workingDir);+ return projectIdentityKey(+ session.remoteHostId ? 'remote' : 'local',+ workingDir,+ session.remoteHostId ?? null,+ );}export function getProjectIdentity(session: Session): ProjectIdentity | null {@@ -272,9 +355,7 @@ function extractDisplayNameFromIndex(return { name: fallback, segments: maxSegments };}-function normalizeProjectAliases(- raw: GroupSessionsOptions['projectAliases'],-): Map<string, string> {+function normalizeProjectAliases(raw: GroupSessionsOptions['projectAliases']): Map<string, string> {const out = new Map<string, string>();if (!raw) return out;const entries = raw instanceof Map ? raw.entries() : Object.entries(raw);@@ -392,7 +473,7 @@ export function groupSessions(options: GroupSessionsOptions = {},): ProjectGroupsResult {const aliases = normalizeProjectAliases(options.projectAliases);- if (!sessions || sessions.length === 0) {+ if ((!sessions || sessions.length === 0) && !options.persistentLocalProjects?.length) {return { pinned: [], dialogues: [], unclassified: [], projects: [] };}@@ -407,6 +488,24 @@ export function groupSessions(? 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 ?? '');+ if (comparisonKey && !persistentRepresentativeByComparison.has(comparisonKey)) {+ persistentRepresentativeByComparison.set(comparisonKey, { projectKey, workingDir });+ }+ }+// 3. 按 normalize 后 workingDir 分组// 草稿判定主线:userSendAt == null(用户从未按下发送)。// 兜底:_count.messages === 0 —— userSendAt 依赖 sendMessage → SDK echo →@@ -440,38 +539,98 @@ export function groupSessions(// device-link 远程会话也归 'remote' scope(复用隐藏本机 FS 入口的渲染分支),// 但用独立 device: key,且不带 remoteHostId(与 SSH 维度互斥)。const scope: ProjectScope = isDeviceLink || s.remoteHostId ? 'remote' : 'local';- const projectKey = isDeviceLink+ let projectKey = isDeviceLink? deviceLinkProjectKey(s.deviceLinkDeviceId as string, dir): projectIdentityKey(scope, dir, s.remoteHostId ?? null);+ let identityWorkingDir = dir;+ if (scope === 'local') {+ const comparisonKey = projectKeyComparisonKey(+ projectKey,+ options.localPlatform ?? '',+ );+ const representative = comparisonKey+ ? persistentRepresentativeByComparison.get(comparisonKey)+ : undefined;+ if (representative) {+ projectKey = representative.projectKey;+ identityWorkingDir = representative.workingDir;+ }+ }const arr = groups.get(projectKey);if (arr) arr.push(s);else groups.set(projectKey, [s]);if (!identityByKey.has(projectKey)) {identityByKey.set(projectKey, {scope,- workingDir: dir,- remoteHostId: isDeviceLink ? null : s.remoteHostId ?? null,+ workingDir: identityWorkingDir,+ remoteHostId: isDeviceLink ? null : (s.remoteHostId ?? null),deviceLinkDeviceId: isDeviceLink ? (s.deviceLinkDeviceId as string) : null,- deviceLinkDeviceName: isDeviceLink ? s.deviceLinkDeviceName ?? null : null,- deviceLinkConnectionStatus: isDeviceLink ? s.deviceLinkConnectionStatus ?? 'connected' : null,+ deviceLinkDeviceName: isDeviceLink ? (s.deviceLinkDeviceName ?? null) : null,+ deviceLinkConnectionStatus: isDeviceLink+ ? (s.deviceLinkConnectionStatus ?? 'connected')+ : null,});}}}- // 4. unclassified 排序 —— active 在 archived 之上,同状态按 sortTime desc+ // 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, options.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, options.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 descdialogues.sort(compareSessionsByStatusThenSortTimeDesc);unclassified.sort(compareSessionsByStatusThenSortTimeDesc);- // 5. 同名消歧 — "先创建优先":在每个 basename 相同的 dir 集合里,按+ // 6. 同名消歧 — "先创建优先":在每个 basename 相同的 dir 集合里,按// "该 dir 下最早 createdAt 的 Session 升序"排序,排序第一的获胜者保留纯// 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>();- // 5a. 先按 basename 分桶+ // 6a. 先按 basename 分桶const dirsByBasename = new Map<string, string[]>();for (const projectKey of allProjectKeys) {const identity = identityByKey.get(projectKey);@@ -483,7 +642,7 @@ export function groupSessions(else dirsByBasename.set(basename, [projectKey]);}- // 5b. 每个 basename 桶内确定获胜者+ // 6b. 每个 basename 桶内确定获胜者for (const [, dirsInBucket] of dirsByBasename) {if (dirsInBucket.length === 1) {// 唯一 basename,无需消歧;走默认 minSegments=1@@ -516,7 +675,7 @@ export function groupSessions(}}- // 5c. 构造 ProjectNode+ // 6c. 构造 ProjectNode// - 获胜者 (minSeg=1):即使 basename 与其他 dir 冲突也强制保留 1 段(先创建优先)// - 非获胜者 (minSeg=2):通过 extractDisplayName 走至少 2 段的消歧// - 唯一 basename (minSeg=1):走默认 1 段(无冲突自然 1 段返回)@@ -529,8 +688,8 @@ export function groupSessions(// latestActivityAt 取"全员里 sortTime 最大"——project 间排序按真实最近活跃时间,// 不被 active-first 的组内排序污染(否则只有 archived 的 project 会被强行按// 较旧的 active 时间下沉,与用户预期不符)。- let latestMs = 0;- let latestIso = '';+ let latestIso = persistentLastUsedByKey.get(projectKey) ?? '';+ let latestMs = toMs(latestIso);for (const s of sess) {const t = sortTimeMs(s);if (t > latestMs) {@@ -575,10 +734,14 @@ export function groupSessions(segments,sessions: sorted,latestActivityAt: latestIso,+ isPersistentLocal: persistentProjectKeys.has(projectKey) || undefined,+ persistentLocalKnownAgentKinds: persistentProjectKeys.has(projectKey)+ ? Array.from(persistentKnownAgentKindsByKey.get(projectKey) ?? []).sort()+ : undefined,});}- // 6. Project 间排序+ // 7. Project 间排序projects.sort(compareProjectsByLatestSessionDesc);return { pinned, dialogues, unclassified, projects };diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectVisibility.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectVisibility.tsindex 760aa75c2a..3e15ece00e 100644--- a/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectVisibility.ts+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectVisibility.ts@@ -63,19 +63,41 @@ export function projectKeyComparisonSetHas(return comparisonKey != null && comparisonKeys.has(comparisonKey);}-function isSessionInHiddenProjectComparisonSet(+/** Session-level project selectors must use the same comparison identity as project nodes. */+export function isSessionInProjectComparisonSet(session: SidebarProjectSession,- hiddenProjectComparisonKeys: ReadonlySet<string>,+ projectComparisonKeys: ReadonlySet<string>,localPlatform: string,): boolean {if (session.workspaceKind === 'dialogue') return false;return projectKeyComparisonSetHas(- hiddenProjectComparisonKeys,+ projectComparisonKeys,projectIdentityKeyForSession(session),localPlatform,);}+/** Single-project action membership using the same local Windows comparison identity. */+export function isSessionInProject(+ session: SidebarProjectSession,+ projectKey: string,+ localPlatform: string,+): boolean {+ if (session.workspaceKind === 'dialogue') return false;+ const sessionProjectKey = projectIdentityKeyForSession(session);+ const sessionComparisonKey = projectKeyComparisonKey(sessionProjectKey, localPlatform);+ const projectComparisonKey = projectKeyComparisonKey(projectKey, localPlatform);+ return sessionComparisonKey != null && sessionComparisonKey === projectComparisonKey;+}++function isSessionInHiddenProjectComparisonSet(+ session: SidebarProjectSession,+ hiddenProjectComparisonKeys: ReadonlySet<string>,+ localPlatform: string,+): boolean {+ return isSessionInProjectComparisonSet(session, hiddenProjectComparisonKeys, localPlatform);+}+export function visibleSidebarProjects(projects: readonly ProjectNode[],hiddenProjectKeys: ReadonlySet<string>,diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/conversationSearchContext.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/conversationSearchContext.tsxindex 3b090def3f..c8e162d9a7 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/conversationSearchContext.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/conversationSearchContext.tsx@@ -25,6 +25,7 @@ import {import { useNavigate } from 'react-router-dom';import { useCCSessions } from '@/hooks/useCCSessions';+import { useRecentWorkdirs } from '@/hooks/useRecentWorkdirs';import { isOrcaWorkerSession } from '@/lib/orcaSessionIdentity';import { useConversationSearchRequest } from '@/state/conversationSearchRequest';import { useProjectAliases } from '../hooks/useProjectAliases';@@ -40,6 +41,7 @@ import {useConversationSearch,} from './ConversationSearchBox';import type { ProjectNode as ProjectNodeData } from '../lib/projectGrouping';+import { buildPersistentLocalProjects } from '../lib/projectGrouping';interface ConversationSearchContextValue {/** 搜索状态机(query / 排序 / 筛选 / 结果 / handleSelect 等)。 */@@ -61,15 +63,15 @@ export function ConversationSearchProvider({ children }: { children: ReactNode }const { sessions } = useCCSessions({ includeArchived: 'all' });const { aliases } = useProjectAliases();const { hiddenProjectKeys } = useHiddenProjects();+ const { entries: recentWorkdirs } = useRecentWorkdirs();const searchSessions = useMemo(() => sessions.filter((s) => !isOrcaWorkerSession(s)), [sessions]);- const { projects } = useProjectGroups(searchSessions, aliases);+ const persistentLocalProjects = useMemo(+ () => buildPersistentLocalProjects(recentWorkdirs, searchSessions, window.electronAPI.platform),+ [recentWorkdirs, searchSessions],+ );+ const { projects } = useProjectGroups(searchSessions, aliases, false, persistentLocalProjects);const visibleProjects = useMemo(- () =>- visibleSidebarProjects(- projects,- hiddenProjectKeys,- window.electronAPI.platform,- ),+ () => visibleSidebarProjects(projects, hiddenProjectKeys, window.electronAPI.platform),[projects, hiddenProjectKeys],);const allowedSessionIds = useMemo(@@ -100,11 +102,7 @@ export function ConversationSearchProvider({ children }: { children: ReactNode }useEffect(() => {if (search.lockedProjectKey &&- isProjectHidden(- search.lockedProjectKey,- hiddenProjectKeys,- window.electronAPI.platform,- )+ isProjectHidden(search.lockedProjectKey, hiddenProjectKeys, window.electronAPI.platform)) {search.reset();search.clearLock();@@ -119,7 +117,8 @@ export function ConversationSearchProvider({ children }: { children: ReactNode }if (next.length === search.projectSelection.length &&next.every((projectKey, index) => projectKey === search.projectSelection[index])- ) return;+ )+ return;search.setProjectSelection(next.length > 0 ? next : 'all');}, [hiddenProjectKeys,diff --git a/apps/desktop/src/renderer/hooks/useRecentWorkdirs.ts b/apps/desktop/src/renderer/hooks/useRecentWorkdirs.tsindex f75bcdc45b..5295c2ebf5 100644--- a/apps/desktop/src/renderer/hooks/useRecentWorkdirs.ts+++ b/apps/desktop/src/renderer/hooks/useRecentWorkdirs.ts@@ -11,6 +11,7 @@import { useEffect, useRef, useState } from 'react';+import { getDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';import {recentWorkdirsStore,type RecentWorkdirEntry,@@ -44,9 +45,16 @@ export function useRecentWorkdirs(): UseRecentWorkdirsReturn {const unsub = recentWorkdirsStore.subscribe(() => {const next = recentWorkdirsStore.get();- if (next !== null) {- setSnapshot(next);- setIsLoading(false);+ setSnapshot(next);+ setIsLoading(next === null);+ if (next === null && getDataOwnerGeneration().dataOwnerId !== null) {+ void recentWorkdirsStore+ .ensure()+ .then(() => setError(null))+ .catch((e: unknown) => {+ setError(e instanceof Error ? e : new Error(String(e)));+ setIsLoading(false);+ });}});diff --git a/apps/desktop/src/renderer/lib/recentWorkdirsStore.ts b/apps/desktop/src/renderer/lib/recentWorkdirsStore.tsindex 78c7807658..de06243f0c 100644--- a/apps/desktop/src/renderer/lib/recentWorkdirsStore.ts+++ b/apps/desktop/src/renderer/lib/recentWorkdirsStore.ts@@ -13,11 +13,15 @@* (main 端 session 创建广播 = 可能新增了 recent_workdirs row)* - 调用方 (hook) 也可以主动调 forceRefresh*- * 不订阅 sessionsPush.onPatched —— 字段变更 (rename / pin / archive) 不影响- * recent_workdirs 表。+ * 普通字段变更 (rename / pin / archive) 不影响 recent_workdirs;软删除会由 main+ * 刷新 lastUsedAt,并经 recentWorkdirs.onChanged 触发强制重拉。*/-import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';+import {+ getDataOwnerGeneration,+ isDataOwnerPushCurrent,+ type DataOwnerGeneration,+} from '@/contexts/dataOwnerGeneration';export interface RecentWorkdirEntry {/** 绝对路径(写入时已 trim,跟 sessions.workingDir 形态一致)。 */@@ -26,10 +30,14 @@ export interface RecentWorkdirEntry {lastUsedAt: string;/** 目录是否仍在磁盘上(main 侧 list 时探测);false → UI 置灰提示已迁移/删除。 */exists: boolean;+ /** 包含软删除历史的 project agentKind 聚合,供 vendor 过滤识别非空项目。 */+ knownAgentKinds?: readonly string[];}let cache: RecentWorkdirEntry[] | null = null;-let inflight: Promise<RecentWorkdirEntry[]> | null = null;+let activeOwner = getDataOwnerGeneration();+let requestGeneration = 0;+let inflight: { generation: number; promise: Promise<RecentWorkdirEntry[]> } | null = null;const subs = new Set<() => void>();function notify(): void {@@ -60,31 +68,56 @@ export const recentWorkdirsStore = {/** 命中即 noop,dedupe 并发请求。 */async ensure(): Promise<void> {- if (cache) return;+ if (cache !== null) return;if (!inflight) {- inflight = fetchList()+ const generation = requestGeneration;+ const promise = fetchList().then((data) => {+ if (generation !== requestGeneration) return data;cache = data;- inflight = null;+ if (inflight?.generation === generation) inflight = null;notify();return data;}).catch((e) => {- inflight = null;+ if (generation !== requestGeneration) return [];+ if (generation === requestGeneration && inflight?.generation === generation) {+ inflight = null;+ }throw e;});+ inflight = { generation, promise };}- await inflight;+ await inflight.promise;},/** 强制重拉(drop cache 后 ensure)。 */async forceRefresh(): Promise<RecentWorkdirEntry[]> {+ requestGeneration += 1;cache = null;inflight = null;await this.ensure();return cache ?? [];},+ /**+ * 同步切换 owner scope。清空旧快照并使所有旧 owner 的在途读取失效;只有同一+ * owner + generation 启动的最新请求才允许写回 cache。+ */+ setDataOwner(owner: DataOwnerGeneration): void {+ if (+ activeOwner.dataOwnerId === owner.dataOwnerId &&+ activeOwner.generation === owner.generation+ ) {+ return;+ }+ activeOwner = { ...owner };+ requestGeneration += 1;+ cache = null;+ inflight = null;+ notify();+ },+/*** 从最近列表移除一条(用户在项目选择器 hover 删除)。* 先乐观 patch 本地 cache(行消失零延迟),再发 IPC;IPC 失败时重拉一次@@ -109,6 +142,7 @@ export const recentWorkdirsStore = {/** 仅供测试 / 登出清理。 */reset(): void {+ requestGeneration += 1;cache = null;inflight = null;notify();@@ -130,9 +164,8 @@ if (typeof window !== 'undefined') {});});}- // 删除广播:别的窗口(或 device-link 远程调用)移除条目时,本窗口的模块级- // 缓存也要跟上,否则删掉的项目在这里仍可选。发起删除的窗口自己已乐观 patch,- // 重拉一次幂等无害。+ // 变更广播:显式移除与软删除 activity touch 都会改变持久目录投影;强制重拉+ // 保证本窗口的 lastActivity 过滤立即看到新时间,而不是等下一次 session 创建。const recentApi = window.electronAPI?.localDb?.recentWorkdirs;if (recentApi?.onChanged) {recentApi.onChanged((_payload, ownerStamp) => {diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex fa4891841b..ae64f0bc20 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -4121,7 +4121,14 @@ interface ElectronAPI {};recentWorkdirs: {/** 列出"最近工作目录"按 lastUsedAt desc;归档/删除 session 都不影响本列表。 */- list: () => Promise<Array<{ path: string; lastUsedAt: string; exists: boolean }>>;+ list: () => Promise<+ Array<{+ path: string;+ lastUsedAt: string;+ exists: boolean;+ knownAgentKinds: string[];+ }>+ >;/** 从最近列表移除一条(列表卫生,不动 sessions / 磁盘;再次使用会重新入列)。 */remove: (input: { path: string }) => Promise<{ deleted: boolean }>;/** Broadcast: 任一窗口/远程调用删除条目后通知;返回退订函数。 */