Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(plugins): 插件单一模型字段与后台隐藏任务 (#6073)

Chris Zhang226c83d31a28
diff --git a/apps/desktop/drizzle/0126_melodic_toxin.sql b/apps/desktop/drizzle/0126_melodic_toxin.sql
new file mode 100644
index 0000000000..5308d64123
--- /dev/null
+++ b/apps/desktop/drizzle/0126_melodic_toxin.sql
@@ -0,0 +1 @@
+ALTER TABLE `sessions` ADD `hidden_at` integer;
\ No newline at end of file
diff --git a/apps/desktop/drizzle/meta/0126_snapshot.json b/apps/desktop/drizzle/meta/0126_snapshot.json
new file mode 100644
index 0000000000..38517b5ae8
--- /dev/null
+++ b/apps/desktop/drizzle/meta/0126_snapshot.json
@@ -0,0 +1,6937 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "690c9c45-3fc0-4ff8-84d4-ed935c3850bd",
+ "prevId": "713a8a25-ebe4-441d-abaf-13a07bd1bda9",
+ "tables": {
+ "account_usage_snapshots": {
+ "name": "account_usage_snapshots",
+ "columns": {
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "snapshot": {
+ "name": "snapshot",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "agent_input_queue_snapshots": {
+ "name": "agent_input_queue_snapshots",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "agent_input_queue_snapshots_session_id_sessions_id_fk": {
+ "name": "agent_input_queue_snapshots_session_id_sessions_id_fk",
+ "tableFrom": "agent_input_queue_snapshots",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "auto_review_projections": {
+ "name": "auto_review_projections",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "lead_id": {
+ "name": "lead_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "revision": {
+ "name": "revision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "projected_revision": {
+ "name": "projected_revision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": -1
+ },
+ "version": {
+ "name": "version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "auto_review_projections_lead_idx": {
+ "name": "auto_review_projections_lead_idx",
+ "columns": [
+ "lead_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "auto_review_projections_session_id_sessions_id_fk": {
+ "name": "auto_review_projections_session_id_sessions_id_fk",
+ "tableFrom": "auto_review_projections",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "auto_review_projections_lead_id_sessions_id_fk": {
+ "name": "auto_review_projections_lead_id_sessions_id_fk",
+ "tableFrom": "auto_review_projections",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "lead_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "auto_review_projections_session_id_lead_id_pk": {
+ "columns": [
+ "session_id",
+ "lead_id"
+ ],
+ "name": "auto_review_projections_session_id_lead_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_delegations": {
+ "name": "bot_delegations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "requesting_bot_id": {
+ "name": "requesting_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "target_bot_id": {
+ "name": "target_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "parent_session_id": {
+ "name": "parent_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "child_session_id": {
+ "name": "child_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "objective": {
+ "name": "objective",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_refs_json": {
+ "name": "context_refs_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "artifact_refs_json": {
+ "name": "artifact_refs_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "permission_snapshot_json": {
+ "name": "permission_snapshot_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "lineage_json": {
+ "name": "lineage_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "target_profile_version": {
+ "name": "target_profile_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "depth": {
+ "name": "depth",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "budget_tokens": {
+ "name": "budget_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tokens_used": {
+ "name": "tokens_used",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "result_summary": {
+ "name": "result_summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "output_artifacts_json": {
+ "name": "output_artifacts_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "pending_interaction_json": {
+ "name": "pending_interaction_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "run_sequence": {
+ "name": "run_sequence",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "accepted_at": {
+ "name": "accepted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "completion_delivered_at": {
+ "name": "completion_delivered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_delegations_requester_status": {
+ "name": "idx_bot_delegations_requester_status",
+ "columns": [
+ "requesting_bot_id",
+ "status"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_delegations_target_status": {
+ "name": "idx_bot_delegations_target_status",
+ "columns": [
+ "target_bot_id",
+ "status"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_delegations_parent_session": {
+ "name": "idx_bot_delegations_parent_session",
+ "columns": [
+ "parent_session_id"
+ ],
+ "isUnique": false
+ },
+ "uniq_bot_delegations_child_session": {
+ "name": "uniq_bot_delegations_child_session",
+ "columns": [
+ "child_session_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "bot_delegations_requesting_bot_id_bot_profiles_id_fk": {
+ "name": "bot_delegations_requesting_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_delegations",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "requesting_bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_delegations_target_bot_id_bot_profiles_id_fk": {
+ "name": "bot_delegations_target_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_delegations",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "target_bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_delegations_parent_session_id_sessions_id_fk": {
+ "name": "bot_delegations_parent_session_id_sessions_id_fk",
+ "tableFrom": "bot_delegations",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "parent_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "bot_delegations_child_session_id_sessions_id_fk": {
+ "name": "bot_delegations_child_session_id_sessions_id_fk",
+ "tableFrom": "bot_delegations",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "child_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_direct_message_threads": {
+ "name": "bot_direct_message_threads",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_a_id": {
+ "name": "bot_a_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_b_id": {
+ "name": "bot_b_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "close_reason": {
+ "name": "close_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "message_count": {
+ "name": "message_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "max_messages": {
+ "name": "max_messages",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "blocked_until": {
+ "name": "blocked_until",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "closed_at": {
+ "name": "closed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_bot_dm_threads_active_pair": {
+ "name": "uniq_bot_dm_threads_active_pair",
+ "columns": [
+ "bot_a_id",
+ "bot_b_id"
+ ],
+ "isUnique": true,
+ "where": "\"bot_direct_message_threads\".\"status\" = 'active'"
+ },
+ "idx_bot_dm_threads_pair_updated": {
+ "name": "idx_bot_dm_threads_pair_updated",
+ "columns": [
+ "bot_a_id",
+ "bot_b_id",
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_direct_messages": {
+ "name": "bot_direct_messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "thread_id": {
+ "name": "thread_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sequence": {
+ "name": "sequence",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sender_bot_id": {
+ "name": "sender_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "recipient_bot_id": {
+ "name": "recipient_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sender_session_id": {
+ "name": "sender_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "recipient_session_id": {
+ "name": "recipient_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "delivery_status": {
+ "name": "delivery_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "sender_name": {
+ "name": "sender_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "recipient_name": {
+ "name": "recipient_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "bridge_session_id": {
+ "name": "bridge_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_bot_direct_messages_thread_sequence": {
+ "name": "uniq_bot_direct_messages_thread_sequence",
+ "columns": [
+ "thread_id",
+ "sequence"
+ ],
+ "isUnique": true
+ },
+ "idx_bot_direct_messages_thread_created": {
+ "name": "idx_bot_direct_messages_thread_created",
+ "columns": [
+ "thread_id",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_direct_messages_thread_id_bot_direct_message_threads_id_fk": {
+ "name": "bot_direct_messages_thread_id_bot_direct_message_threads_id_fk",
+ "tableFrom": "bot_direct_messages",
+ "tableTo": "bot_direct_message_threads",
+ "columnsFrom": [
+ "thread_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_direct_messages_sender_session_id_sessions_id_fk": {
+ "name": "bot_direct_messages_sender_session_id_sessions_id_fk",
+ "tableFrom": "bot_direct_messages",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "sender_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "bot_direct_messages_recipient_session_id_sessions_id_fk": {
+ "name": "bot_direct_messages_recipient_session_id_sessions_id_fk",
+ "tableFrom": "bot_direct_messages",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "recipient_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_group_members": {
+ "name": "bot_group_members",
+ "columns": {
+ "group_id": {
+ "name": "group_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_seen_sequence": {
+ "name": "last_seen_sequence",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "joined_at": {
+ "name": "joined_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_group_members_bot": {
+ "name": "idx_bot_group_members_bot",
+ "columns": [
+ "bot_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_group_members_group_id_bot_groups_id_fk": {
+ "name": "bot_group_members_group_id_bot_groups_id_fk",
+ "tableFrom": "bot_group_members",
+ "tableTo": "bot_groups",
+ "columnsFrom": [
+ "group_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_group_members_bot_id_bot_profiles_id_fk": {
+ "name": "bot_group_members_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_group_members",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "bot_group_members_group_id_bot_id_pk": {
+ "columns": [
+ "group_id",
+ "bot_id"
+ ],
+ "name": "bot_group_members_group_id_bot_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_group_messages": {
+ "name": "bot_group_messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "group_id": {
+ "name": "group_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sequence": {
+ "name": "sequence",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'message'"
+ },
+ "author_kind": {
+ "name": "author_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "author_bot_id": {
+ "name": "author_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "author_name": {
+ "name": "author_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "mentions_json": {
+ "name": "mentions_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{\"all\":false,\"botIds\":[]}'"
+ },
+ "notice_code": {
+ "name": "notice_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "plan_id": {
+ "name": "plan_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "files_json": {
+ "name": "files_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "attachments_json": {
+ "name": "attachments_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_bot_group_messages_group_sequence": {
+ "name": "uniq_bot_group_messages_group_sequence",
+ "columns": [
+ "group_id",
+ "sequence"
+ ],
+ "isUnique": true
+ },
+ "uniq_bot_group_messages_group_client": {
+ "name": "uniq_bot_group_messages_group_client",
+ "columns": [
+ "group_id",
+ "client_id"
+ ],
+ "isUnique": true,
+ "where": "\"bot_group_messages\".\"client_id\" IS NOT NULL"
+ }
+ },
+ "foreignKeys": {
+ "bot_group_messages_group_id_bot_groups_id_fk": {
+ "name": "bot_group_messages_group_id_bot_groups_id_fk",
+ "tableFrom": "bot_group_messages",
+ "tableTo": "bot_groups",
+ "columnsFrom": [
+ "group_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_group_plan_steps": {
+ "name": "bot_group_plan_steps",
+ "columns": {
+ "plan_id": {
+ "name": "plan_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_name": {
+ "name": "bot_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task": {
+ "name": "task",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "result_message_id": {
+ "name": "result_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "bot_group_plan_steps_plan_id_bot_group_plans_id_fk": {
+ "name": "bot_group_plan_steps_plan_id_bot_group_plans_id_fk",
+ "tableFrom": "bot_group_plan_steps",
+ "tableTo": "bot_group_plans",
+ "columnsFrom": [
+ "plan_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "bot_group_plan_steps_plan_id_position_pk": {
+ "columns": [
+ "plan_id",
+ "position"
+ ],
+ "name": "bot_group_plan_steps_plan_id_position_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_group_plans": {
+ "name": "bot_group_plans",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "group_id": {
+ "name": "group_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "request_text": {
+ "name": "request_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attachments_json": {
+ "name": "attachments_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "organizer_bot_id": {
+ "name": "organizer_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organizer_name": {
+ "name": "organizer_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "current_step": {
+ "name": "current_step",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "work_dir": {
+ "name": "work_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "branch": {
+ "name": "branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_group_plans_group_created": {
+ "name": "idx_bot_group_plans_group_created",
+ "columns": [
+ "group_id",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_group_plans_group_id_bot_groups_id_fk": {
+ "name": "bot_group_plans_group_id_bot_groups_id_fk",
+ "tableFrom": "bot_group_plans",
+ "tableTo": "bot_groups",
+ "columnsFrom": [
+ "group_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_groups": {
+ "name": "bot_groups",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "reply_mode": {
+ "name": "reply_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'all'"
+ },
+ "speaking_mode": {
+ "name": "speaking_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'auto'"
+ },
+ "organizer_bot_id": {
+ "name": "organizer_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "project_dir": {
+ "name": "project_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_groups_updated": {
+ "name": "idx_bot_groups_updated",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_lifecycle_events": {
+ "name": "bot_lifecycle_events",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "event_type": {
+ "name": "event_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload_json": {
+ "name": "payload_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_lifecycle_events_bot_created": {
+ "name": "idx_bot_lifecycle_events_bot_created",
+ "columns": [
+ "bot_id",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_lifecycle_events_session_created": {
+ "name": "idx_bot_lifecycle_events_session_created",
+ "columns": [
+ "session_id",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_lifecycle_events_bot_id_bot_profiles_id_fk": {
+ "name": "bot_lifecycle_events_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_lifecycle_events",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_lifecycle_events_session_id_sessions_id_fk": {
+ "name": "bot_lifecycle_events_session_id_sessions_id_fk",
+ "tableFrom": "bot_lifecycle_events",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_profile_versions": {
+ "name": "bot_profile_versions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "version": {
+ "name": "version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "identity_source": {
+ "name": "identity_source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "capabilities_json": {
+ "name": "capabilities_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_bot_profile_versions_bot_version": {
+ "name": "uniq_bot_profile_versions_bot_version",
+ "columns": [
+ "bot_id",
+ "version"
+ ],
+ "isUnique": true
+ },
+ "idx_bot_profile_versions_bot_created": {
+ "name": "idx_bot_profile_versions_bot_created",
+ "columns": [
+ "bot_id",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_profile_versions_bot_id_bot_profiles_id_fk": {
+ "name": "bot_profile_versions_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_profile_versions",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_profiles": {
+ "name": "bot_profiles",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "display_name": {
+ "name": "display_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "avatar": {
+ "name": "avatar",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'🤖'"
+ },
+ "avatar_color": {
+ "name": "avatar_color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'violet'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "hidden_at": {
+ "name": "hidden_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pinned_at": {
+ "name": "pinned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "attention_reason": {
+ "name": "attention_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "attention_at": {
+ "name": "attention_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "current_version": {
+ "name": "current_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "canonical_session_id": {
+ "name": "canonical_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_profiles_status_updated": {
+ "name": "idx_bot_profiles_status_updated",
+ "columns": [
+ "status",
+ "updated_at"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_profiles_canonical_session": {
+ "name": "idx_bot_profiles_canonical_session",
+ "columns": [
+ "canonical_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_profiles_canonical_session_id_sessions_id_fk": {
+ "name": "bot_profiles_canonical_session_id_sessions_id_fk",
+ "tableFrom": "bot_profiles",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "canonical_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_runtime_snapshots": {
+ "name": "bot_runtime_snapshots",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "profile_version": {
+ "name": "profile_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "memory_scope_key": {
+ "name": "memory_scope_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "configured_json": {
+ "name": "configured_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "resolved_json": {
+ "name": "resolved_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "prepared_at": {
+ "name": "prepared_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "applied_at": {
+ "name": "applied_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "failed_at": {
+ "name": "failed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "failure_json": {
+ "name": "failure_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_runtime_snapshots_bot_prepared": {
+ "name": "idx_bot_runtime_snapshots_bot_prepared",
+ "columns": [
+ "bot_id",
+ "prepared_at"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_runtime_snapshots_session_prepared": {
+ "name": "idx_bot_runtime_snapshots_session_prepared",
+ "columns": [
+ "session_id",
+ "prepared_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_runtime_snapshots_bot_id_bot_profiles_id_fk": {
+ "name": "bot_runtime_snapshots_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_runtime_snapshots",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_runtime_snapshots_session_id_sessions_id_fk": {
+ "name": "bot_runtime_snapshots_session_id_sessions_id_fk",
+ "tableFrom": "bot_runtime_snapshots",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_session_links": {
+ "name": "bot_session_links",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "profile_version": {
+ "name": "profile_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "route_key": {
+ "name": "route_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_bot_session_links_session": {
+ "name": "uniq_bot_session_links_session",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true
+ },
+ "uniq_bot_session_links_canonical_per_bot": {
+ "name": "uniq_bot_session_links_canonical_per_bot",
+ "columns": [
+ "bot_id"
+ ],
+ "isUnique": true,
+ "where": "\"bot_session_links\".\"role\" = 'canonical'"
+ },
+ "idx_bot_session_links_bot_role": {
+ "name": "idx_bot_session_links_bot_role",
+ "columns": [
+ "bot_id",
+ "role"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_session_links_bot_id_bot_profiles_id_fk": {
+ "name": "bot_session_links_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_session_links",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_session_links_session_id_sessions_id_fk": {
+ "name": "bot_session_links_session_id_sessions_id_fk",
+ "tableFrom": "bot_session_links",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "custom_mcp_servers": {
+ "name": "custom_mcp_servers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "transport": {
+ "name": "transport",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "headers": {
+ "name": "headers",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_custom_mcp_servers_sort_order": {
+ "name": "idx_custom_mcp_servers_sort_order",
+ "columns": [
+ "sort_order"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "custom_providers": {
+ "name": "custom_providers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "runtimes": {
+ "name": "runtimes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "auth": {
+ "name": "auth",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_custom_providers_sort_order": {
+ "name": "idx_custom_providers_sort_order",
+ "columns": [
+ "sort_order"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "daily_model_usage": {
+ "name": "daily_model_usage",
+ "columns": {
+ "day": {
+ "name": "day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_amount": {
+ "name": "cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_currency": {
+ "name": "cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'USD'"
+ },
+ "cost_is_approximate": {
+ "name": "cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "input_tokens": {
+ "name": "input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "output_tokens": {
+ "name": "output_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cache_read_tokens": {
+ "name": "cache_read_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cache_create_tokens": {
+ "name": "cache_create_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "daily_model_usage_day_agent_kind_model_cost_currency_pk": {
+ "columns": [
+ "day",
+ "agent_kind",
+ "model",
+ "cost_currency"
+ ],
+ "name": "daily_model_usage_day_agent_kind_model_cost_currency_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "daily_session_usage": {
+ "name": "daily_session_usage",
+ "columns": {
+ "day": {
+ "name": "day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tokens": {
+ "name": "tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "daily_session_usage_day_session_id_pk": {
+ "columns": [
+ "day",
+ "session_id"
+ ],
+ "name": "daily_session_usage_day_session_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "daily_spend": {
+ "name": "daily_spend",
+ "columns": {
+ "day": {
+ "name": "day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_amount": {
+ "name": "cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_currency": {
+ "name": "cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'USD'"
+ },
+ "cost_is_approximate": {
+ "name": "cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "daily_spend_day_cost_currency_pk": {
+ "columns": [
+ "day",
+ "cost_currency"
+ ],
+ "name": "daily_spend_day_cost_currency_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "device_link_ownership": {
+ "name": "device_link_ownership",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_pid": {
+ "name": "owner_pid",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_label": {
+ "name": "owner_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "heartbeat_at": {
+ "name": "heartbeat_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "embedding_jobs": {
+ "name": "embedding_jobs",
+ "columns": {
+ "rowid": {
+ "name": "rowid",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source_id": {
+ "name": "source_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chunk_index": {
+ "name": "chunk_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "vec_table": {
+ "name": "vec_table",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scheduled_at": {
+ "name": "scheduled_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "locked_at": {
+ "name": "locked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_embedding_jobs_natural": {
+ "name": "uniq_embedding_jobs_natural",
+ "columns": [
+ "source",
+ "source_id",
+ "chunk_index",
+ "model_id"
+ ],
+ "isUnique": true
+ },
+ "idx_embedding_jobs_status_scheduled": {
+ "name": "idx_embedding_jobs_status_scheduled",
+ "columns": [
+ "status",
+ "scheduled_at"
+ ],
+ "isUnique": false
+ },
+ "idx_embedding_jobs_source_id": {
+ "name": "idx_embedding_jobs_source_id",
+ "columns": [
+ "source",
+ "source_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "embedding_meta": {
+ "name": "embedding_meta",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "ghost_cards": {
+ "name": "ghost_cards",
+ "columns": {
+ "call_id": {
+ "name": "call_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ghost_id": {
+ "name": "ghost_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "html": {
+ "name": "html",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "height": {
+ "name": "height",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "v": {
+ "name": "v",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "ghost_cards_updated_at_idx": {
+ "name": "ghost_cards_updated_at_idx",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "hook_group_context_cursors": {
+ "name": "hook_group_context_cursors",
+ "columns": {
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cursor_key": {
+ "name": "cursor_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cursor_id": {
+ "name": "cursor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "hook_group_context_cursors_updated_at_idx": {
+ "name": "hook_group_context_cursors_updated_at_idx",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "hook_group_context_cursors_provider_cursor_key_pk": {
+ "columns": [
+ "provider",
+ "cursor_key"
+ ],
+ "name": "hook_group_context_cursors_provider_cursor_key_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "hook_group_message_stats": {
+ "name": "hook_group_message_stats",
+ "columns": {
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "row_count": {
+ "name": "row_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text_bytes": {
+ "name": "text_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "hook_group_messages": {
+ "name": "hook_group_messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "thread_id": {
+ "name": "thread_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_name": {
+ "name": "chat_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "author": {
+ "name": "author",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_bot": {
+ "name": "is_bot",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "file_names": {
+ "name": "file_names",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "hook_group_messages_msg_idx": {
+ "name": "hook_group_messages_msg_idx",
+ "columns": [
+ "provider",
+ "chat_id",
+ "thread_id",
+ "message_id"
+ ],
+ "isUnique": true
+ },
+ "hook_group_messages_window_idx": {
+ "name": "hook_group_messages_window_idx",
+ "columns": [
+ "provider",
+ "chat_id",
+ "thread_id",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "im_bindings": {
+ "name": "im_bindings",
+ "columns": {
+ "channel": {
+ "name": "channel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_context_id": {
+ "name": "bot_context_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scope_key": {
+ "name": "scope_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "target_session_id": {
+ "name": "target_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attached_at": {
+ "name": "attached_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attached_via_card_message_id": {
+ "name": "attached_via_card_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_im_bindings_target": {
+ "name": "idx_im_bindings_target",
+ "columns": [
+ "target_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "im_bindings_target_session_id_sessions_id_fk": {
+ "name": "im_bindings_target_session_id_sessions_id_fk",
+ "tableFrom": "im_bindings",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "target_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "im_bindings_channel_bot_context_id_user_id_scope_key_pk": {
+ "columns": [
+ "channel",
+ "bot_context_id",
+ "user_id",
+ "scope_key"
+ ],
+ "name": "im_bindings_channel_bot_context_id_user_id_scope_key_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "im_notification_origins": {
+ "name": "im_notification_origins",
+ "columns": {
+ "channel": {
+ "name": "channel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_context_id": {
+ "name": "bot_context_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "im_notification_origins_channel_bot_context_id_user_id_message_id_pk": {
+ "columns": [
+ "channel",
+ "bot_context_id",
+ "user_id",
+ "message_id"
+ ],
+ "name": "im_notification_origins_channel_bot_context_id_user_id_message_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "media_blobs": {
+ "name": "media_blobs",
+ "columns": {
+ "hash": {
+ "name": "hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ext": {
+ "name": "ext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mime_type": {
+ "name": "mime_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bytes": {
+ "name": "bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_cache": {
+ "name": "is_cache",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_access_at": {
+ "name": "last_access_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "media_invocations": {
+ "name": "media_invocations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner": {
+ "name": "owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "capability": {
+ "name": "capability",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "guide_revision": {
+ "name": "guide_revision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "guide_json": {
+ "name": "guide_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "response_json": {
+ "name": "response_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "media_invocations_owner_created_at_idx": {
+ "name": "media_invocations_owner_created_at_idx",
+ "columns": [
+ "owner",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "media_invocations_owner_state_idx": {
+ "name": "media_invocations_owner_state_idx",
+ "columns": [
+ "owner",
+ "state"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "media_refs": {
+ "name": "media_refs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "hash": {
+ "name": "hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ref_kind": {
+ "name": "ref_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ref_id": {
+ "name": "ref_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "origin_session_id": {
+ "name": "origin_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "origin_kind": {
+ "name": "origin_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "origin_id": {
+ "name": "origin_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "media_refs_hash_idx": {
+ "name": "media_refs_hash_idx",
+ "columns": [
+ "hash"
+ ],
+ "isUnique": false
+ },
+ "media_refs_ref_idx": {
+ "name": "media_refs_ref_idx",
+ "columns": [
+ "ref_kind",
+ "ref_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "media_refs_hash_media_blobs_hash_fk": {
+ "name": "media_refs_hash_media_blobs_hash_fk",
+ "tableFrom": "media_refs",
+ "tableTo": "media_blobs",
+ "columnsFrom": [
+ "hash"
+ ],
+ "columnsTo": [
+ "hash"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "messages": {
+ "name": "messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_use_id": {
+ "name": "tool_use_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_meta": {
+ "name": "agent_meta",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "rewind_at": {
+ "name": "rewind_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_messages_session_client": {
+ "name": "uniq_messages_session_client",
+ "columns": [
+ "session_id",
+ "client_id"
+ ],
+ "isUnique": true
+ },
+ "idx_messages_session_created": {
+ "name": "idx_messages_session_created",
+ "columns": [
+ "session_id",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "idx_messages_created_at": {
+ "name": "idx_messages_created_at",
+ "columns": [
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_messages_rewind_at": {
+ "name": "idx_messages_rewind_at",
+ "columns": [
+ "rewind_at"
+ ],
+ "isUnique": false
+ },
+ "idx_messages_active_error_tail": {
+ "name": "idx_messages_active_error_tail",
+ "columns": [
+ "session_id",
+ "created_at"
+ ],
+ "isUnique": false,
+ "where": "\"messages\".\"role\" = 'error' AND \"messages\".\"rewind_at\" IS NULL"
+ }
+ },
+ "foreignKeys": {
+ "messages_session_id_sessions_id_fk": {
+ "name": "messages_session_id_sessions_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "messages_fts_rows": {
+ "name": "messages_fts_rows",
+ "columns": {
+ "fts_rowid": {
+ "name": "fts_rowid",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "messages_fts_rows_message_id_idx": {
+ "name": "messages_fts_rows_message_id_idx",
+ "columns": [
+ "message_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "migration_history": {
+ "name": "migration_history",
+ "columns": {
+ "seq": {
+ "name": "seq",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "file_name": {
+ "name": "file_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content_hash": {
+ "name": "content_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "applied_at": {
+ "name": "applied_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "migration_meta": {
+ "name": "migration_meta",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_remote_opens": {
+ "name": "orca_remote_opens",
+ "columns": {
+ "remote_session_id": {
+ "name": "remote_session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "device_id": {
+ "name": "device_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_teams": {
+ "name": "orca_teams",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "lead_session_id": {
+ "name": "lead_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_active_team_per_lead": {
+ "name": "uniq_active_team_per_lead",
+ "columns": [
+ "lead_session_id"
+ ],
+ "isUnique": true,
+ "where": "\"orca_teams\".\"status\" = 'active'"
+ },
+ "idx_orca_teams_status": {
+ "name": "idx_orca_teams_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_teams_lead_session_id_sessions_id_fk": {
+ "name": "orca_teams_lead_session_id_sessions_id_fk",
+ "tableFrom": "orca_teams",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "lead_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_worker_creation_reservations": {
+ "name": "orca_worker_creation_reservations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_orca_worker_creation_reservations_team_label": {
+ "name": "uniq_orca_worker_creation_reservations_team_label",
+ "columns": [
+ "team_id",
+ "lower(\"label\")"
+ ],
+ "isUnique": true
+ },
+ "idx_orca_worker_creation_reservations_expires_at": {
+ "name": "idx_orca_worker_creation_reservations_expires_at",
+ "columns": [
+ "expires_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_worker_creation_reservations_team_id_orca_teams_id_fk": {
+ "name": "orca_worker_creation_reservations_team_id_orca_teams_id_fk",
+ "tableFrom": "orca_worker_creation_reservations",
+ "tableTo": "orca_teams",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_workers": {
+ "name": "orca_workers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'idle'"
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "worktree_branch": {
+ "name": "worktree_branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'developer'"
+ },
+ "focused": {
+ "name": "focused",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "idle_since": {
+ "name": "idle_since",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "execution_device_id": {
+ "name": "execution_device_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "remote_session_id": {
+ "name": "remote_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_bridged_message_id": {
+ "name": "last_bridged_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "remote_released_at": {
+ "name": "remote_released_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pending_remote_report": {
+ "name": "pending_remote_report",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "remote_stop_confirmed_at": {
+ "name": "remote_stop_confirmed_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_orca_workers_session_id": {
+ "name": "uniq_orca_workers_session_id",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true
+ },
+ "uniq_orca_workers_team_label": {
+ "name": "uniq_orca_workers_team_label",
+ "columns": [
+ "team_id",
+ "lower(\"label\")"
+ ],
+ "isUnique": true
+ },
+ "uniq_orca_workers_focused_per_team": {
+ "name": "uniq_orca_workers_focused_per_team",
+ "columns": [
+ "team_id"
+ ],
+ "isUnique": true,
+ "where": "\"orca_workers\".\"focused\" = true"
+ },
+ "idx_orca_workers_team_id": {
+ "name": "idx_orca_workers_team_id",
+ "columns": [
+ "team_id"
+ ],
+ "isUnique": false
+ },
+ "idx_orca_workers_status": {
+ "name": "idx_orca_workers_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_workers_team_id_orca_teams_id_fk": {
+ "name": "orca_workers_team_id_orca_teams_id_fk",
+ "tableFrom": "orca_workers",
+ "tableTo": "orca_teams",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "orca_workers_session_id_sessions_id_fk": {
+ "name": "orca_workers_session_id_sessions_id_fk",
+ "tableFrom": "orca_workers",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "plugin_task_requests": {
+ "name": "plugin_task_requests",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "plugin_id": {
+ "name": "plugin_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "operation": {
+ "name": "operation",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "target_id": {
+ "name": "target_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "request_key": {
+ "name": "request_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "fingerprint": {
+ "name": "fingerprint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "revision": {
+ "name": "revision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "plugin_task_request_key": {
+ "name": "plugin_task_request_key",
+ "columns": [
+ "plugin_id",
+ "operation",
+ "target_id",
+ "request_key"
+ ],
+ "isUnique": true
+ },
+ "plugin_task_target": {
+ "name": "plugin_task_target",
+ "columns": [
+ "target_id",
+ "plugin_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_aliases": {
+ "name": "project_aliases",
+ "columns": {
+ "project_key": {
+ "name": "project_key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "alias": {
+ "name": "alias",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_project_aliases_updated_at": {
+ "name": "idx_project_aliases_updated_at",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_automation_consents": {
+ "name": "project_automation_consents",
+ "columns": {
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "consented_at": {
+ "name": "consented_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "config_hash": {
+ "name": "config_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "recent_workdirs": {
+ "name": "recent_workdirs",
+ "columns": {
+ "path": {
+ "name": "path",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_recent_workdirs_last_used_at": {
+ "name": "idx_recent_workdirs_last_used_at",
+ "columns": [
+ "last_used_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "right_sidebar_tabs": {
+ "name": "right_sidebar_tabs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "right_sidebar_tabs_session_idx": {
+ "name": "right_sidebar_tabs_session_idx",
+ "columns": [
+ "session_id",
+ "position"
+ ],
+ "isUnique": false
+ },
+ "right_sidebar_tabs_subagents_singleton_idx": {
+ "name": "right_sidebar_tabs_subagents_singleton_idx",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true,
+ "where": "\"right_sidebar_tabs\".\"kind\" = 'subagents'"
+ },
+ "right_sidebar_tabs_bot_artifacts_singleton_idx": {
+ "name": "right_sidebar_tabs_bot_artifacts_singleton_idx",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true,
+ "where": "\"right_sidebar_tabs\".\"kind\" = 'bot-artifacts'"
+ }
+ },
+ "foreignKeys": {
+ "right_sidebar_tabs_session_id_sessions_id_fk": {
+ "name": "right_sidebar_tabs_session_id_sessions_id_fk",
+ "tableFrom": "right_sidebar_tabs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "schedule_runs": {
+ "name": "schedule_runs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "schedule_id": {
+ "name": "schedule_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fired_at": {
+ "name": "fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "error_msg": {
+ "name": "error_msg",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "estimated_value_usd": {
+ "name": "estimated_value_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_amount": {
+ "name": "cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "estimated_value_amount": {
+ "name": "estimated_value_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_currency": {
+ "name": "cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_is_approximate": {
+ "name": "cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "cost_attribution": {
+ "name": "cost_attribution",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'legacy'"
+ },
+ "result_text": {
+ "name": "result_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pre_run_hook_result": {
+ "name": "pre_run_hook_result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "read_at": {
+ "name": "read_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "heartbeat_at": {
+ "name": "heartbeat_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedule_runs_schedule": {
+ "name": "idx_schedule_runs_schedule",
+ "columns": [
+ "schedule_id",
+ "fired_at"
+ ],
+ "isUnique": false
+ },
+ "idx_schedule_runs_running_schedule": {
+ "name": "idx_schedule_runs_running_schedule",
+ "columns": [
+ "schedule_id"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"status\" = 'running'"
+ },
+ "idx_schedule_runs_running_heartbeat": {
+ "name": "idx_schedule_runs_running_heartbeat",
+ "columns": [
+ "heartbeat_at"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"status\" = 'running' AND \"schedule_runs\".\"heartbeat_at\" IS NOT NULL"
+ },
+ "idx_schedule_runs_running_legacy": {
+ "name": "idx_schedule_runs_running_legacy",
+ "columns": [
+ "fired_at"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"status\" = 'running' AND \"schedule_runs\".\"heartbeat_at\" IS NULL"
+ },
+ "idx_schedule_runs_unread_terminal": {
+ "name": "idx_schedule_runs_unread_terminal",
+ "columns": [
+ "schedule_id",
+ "status",
+ "fired_at"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"read_at\" IS NULL AND \"schedule_runs\".\"status\" IN ('success', 'failed', 'aborted', 'interrupted')"
+ },
+ "idx_schedule_runs_session_latest": {
+ "name": "idx_schedule_runs_session_latest",
+ "columns": [
+ "session_id",
+ "fired_at",
+ "id"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"session_id\" IS NOT NULL"
+ }
+ },
+ "foreignKeys": {
+ "schedule_runs_schedule_id_schedules_id_fk": {
+ "name": "schedule_runs_schedule_id_schedules_id_fk",
+ "tableFrom": "schedule_runs",
+ "tableTo": "schedules",
+ "columnsFrom": [
+ "schedule_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "schedule_runs_session_id_sessions_id_fk": {
+ "name": "schedule_runs_session_id_sessions_id_fk",
+ "tableFrom": "schedule_runs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "schedule_session_latest_runs": {
+ "name": "schedule_session_latest_runs",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "fired_at": {
+ "name": "fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedule_session_latest_runs_run": {
+ "name": "idx_schedule_session_latest_runs_run",
+ "columns": [
+ "run_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "schedule_session_latest_runs_session_id_sessions_id_fk": {
+ "name": "schedule_session_latest_runs_session_id_sessions_id_fk",
+ "tableFrom": "schedule_session_latest_runs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "schedule_session_latest_runs_run_id_schedule_runs_id_fk": {
+ "name": "schedule_session_latest_runs_run_id_schedule_runs_id_fk",
+ "tableFrom": "schedule_session_latest_runs",
+ "tableTo": "schedule_runs",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "schedules": {
+ "name": "schedules",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "job_type": {
+ "name": "job_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'prompt'"
+ },
+ "job_config": {
+ "name": "job_config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "execution_mode": {
+ "name": "execution_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'agent'"
+ },
+ "script_config": {
+ "name": "script_config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'user'"
+ },
+ "project_config_id": {
+ "name": "project_config_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "legacy_session_fallback": {
+ "name": "legacy_session_fallback",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'cron'"
+ },
+ "cron_expr": {
+ "name": "cron_expr",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "recurring": {
+ "name": "recurring",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "manual": {
+ "name": "manual",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "interval_ms": {
+ "name": "interval_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_agent_kind": {
+ "name": "model_agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "effort": {
+ "name": "effort",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fast_mode": {
+ "name": "fast_mode",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_kind": {
+ "name": "workspace_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'project'"
+ },
+ "use_worktree": {
+ "name": "use_worktree",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "target_session_id": {
+ "name": "target_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "persistent_session": {
+ "name": "persistent_session",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "silent_when_idle": {
+ "name": "silent_when_idle",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "pre_run_hook_command": {
+ "name": "pre_run_hook_command",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pre_run_hook_timeout_ms": {
+ "name": "pre_run_hook_timeout_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "skip_log_session_id": {
+ "name": "skip_log_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "notify_desktop": {
+ "name": "notify_desktop",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "notify_feishu": {
+ "name": "notify_feishu",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "notify_wecom_group": {
+ "name": "notify_wecom_group",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_fired_at": {
+ "name": "last_fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_finished_at": {
+ "name": "last_finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "next_fire_at": {
+ "name": "next_fire_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expire_at": {
+ "name": "expire_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedules_active_next": {
+ "name": "idx_schedules_active_next",
+ "columns": [
+ "status",
+ "next_fire_at"
+ ],
+ "isUnique": false
+ },
+ "idx_schedules_target_session": {
+ "name": "idx_schedules_target_session",
+ "columns": [
+ "target_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "schedules_target_session_id_sessions_id_fk": {
+ "name": "schedules_target_session_id_sessions_id_fk",
+ "tableFrom": "schedules",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "target_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "schedules_skip_log_session_id_sessions_id_fk": {
+ "name": "schedules_skip_log_session_id_sessions_id_fk",
+ "tableFrom": "schedules",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "skip_log_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_goals": {
+ "name": "session_goals",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "objective": {
+ "name": "objective",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "budget_tokens": {
+ "name": "budget_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "max_turns": {
+ "name": "max_turns",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "no_progress_limit": {
+ "name": "no_progress_limit",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "turns_used": {
+ "name": "turns_used",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "tokens_used": {
+ "name": "tokens_used",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "no_progress_streak": {
+ "name": "no_progress_streak",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "usage_reset_at": {
+ "name": "usage_reset_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_reason": {
+ "name": "last_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_session_goals_status": {
+ "name": "idx_session_goals_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_goals_session_id_sessions_id_fk": {
+ "name": "session_goals_session_id_sessions_id_fk",
+ "tableFrom": "session_goals",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_pr_refs": {
+ "name": "session_pr_refs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner": {
+ "name": "owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "repo": {
+ "name": "repo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "first_seen_at": {
+ "name": "first_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_session_pr_refs": {
+ "name": "uniq_session_pr_refs",
+ "columns": [
+ "session_id",
+ "owner",
+ "repo",
+ "pr_number"
+ ],
+ "isUnique": true
+ },
+ "idx_session_pr_refs_session_last_seen": {
+ "name": "idx_session_pr_refs_session_last_seen",
+ "columns": [
+ "session_id",
+ "last_seen_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_pr_refs_session_id_sessions_id_fk": {
+ "name": "session_pr_refs_session_id_sessions_id_fk",
+ "tableFrom": "session_pr_refs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_task_tags": {
+ "name": "session_task_tags",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tag_id": {
+ "name": "tag_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "session_task_tags_tag_idx": {
+ "name": "session_task_tags_tag_idx",
+ "columns": [
+ "tag_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_task_tags_session_id_sessions_id_fk": {
+ "name": "session_task_tags_session_id_sessions_id_fk",
+ "tableFrom": "session_task_tags",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "session_task_tags_tag_id_task_tags_id_fk": {
+ "name": "session_task_tags_tag_id_task_tags_id_fk",
+ "tableFrom": "session_task_tags",
+ "tableTo": "task_tags",
+ "columnsFrom": [
+ "tag_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "session_task_tags_session_id_tag_id_pk": {
+ "columns": [
+ "session_id",
+ "tag_id"
+ ],
+ "name": "session_task_tags_session_id_tag_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'New Maker'"
+ },
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_kind": {
+ "name": "workspace_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'project'"
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'claude-sonnet-4-6'"
+ },
+ "effort": {
+ "name": "effort",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'high'"
+ },
+ "permission_mode": {
+ "name": "permission_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'ask'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "total_token_usage": {
+ "name": "total_token_usage",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_usd": {
+ "name": "total_cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_amount": {
+ "name": "total_cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_currency": {
+ "name": "total_cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "total_cost_is_approximate": {
+ "name": "total_cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "context_tokens": {
+ "name": "context_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "context_window": {
+ "name": "context_window",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "context_window_runtime": {
+ "name": "context_window_runtime",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fast_mode": {
+ "name": "fast_mode",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "plan_mode_enabled": {
+ "name": "plan_mode_enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "cleared_at": {
+ "name": "cleared_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pinned_at": {
+ "name": "pinned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "hidden_at": {
+ "name": "hidden_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_send_at": {
+ "name": "user_send_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'cc'"
+ },
+ "orca_role": {
+ "name": "orca_role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "parent_session_id": {
+ "name": "parent_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "forked_at_message_id": {
+ "name": "forked_at_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "worktree_path": {
+ "name": "worktree_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'desktop'"
+ },
+ "feishu_open_id": {
+ "name": "feishu_open_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "feishu_bot_app_id": {
+ "name": "feishu_bot_app_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "im_bot_context_id": {
+ "name": "im_bot_context_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "im_user_id": {
+ "name": "im_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "im_default_route": {
+ "name": "im_default_route",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "used_project_context": {
+ "name": "used_project_context",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "codex_history_has_product_prompt": {
+ "name": "codex_history_has_product_prompt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "codex_plan_json": {
+ "name": "codex_plan_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "extra_dirs": {
+ "name": "extra_dirs",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "writable_dirs": {
+ "name": "writable_dirs",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "remote_host_id": {
+ "name": "remote_host_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_device_id": {
+ "name": "agent_device_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "orca_remote_lead": {
+ "name": "orca_remote_lead",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "active_turn_started_at": {
+ "name": "active_turn_started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "active_turn_pid": {
+ "name": "active_turn_pid",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_turn_ended_at": {
+ "name": "last_turn_ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "list_preview": {
+ "name": "list_preview",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "list_preview_role": {
+ "name": "list_preview_role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "list_message_count": {
+ "name": "list_message_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_sessions_updated_at": {
+ "name": "idx_sessions_updated_at",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_user_send_at": {
+ "name": "idx_sessions_user_send_at",
+ "columns": [
+ "user_send_at"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_sdk_session_id": {
+ "name": "idx_sessions_sdk_session_id",
+ "columns": [
+ "sdk_session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_workdir_created": {
+ "name": "idx_sessions_workdir_created",
+ "columns": [
+ "working_dir",
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_created_at": {
+ "name": "idx_sessions_created_at",
+ "columns": [
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_workspace_kind": {
+ "name": "idx_sessions_workspace_kind",
+ "columns": [
+ "workspace_kind"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_parent_session_id": {
+ "name": "idx_sessions_parent_session_id",
+ "columns": [
+ "parent_session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_orca_role": {
+ "name": "idx_sessions_orca_role",
+ "columns": [
+ "orca_role"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_worktree_path": {
+ "name": "idx_sessions_worktree_path",
+ "columns": [
+ "worktree_path"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_feishu_lookup": {
+ "name": "idx_sessions_feishu_lookup",
+ "columns": [
+ "source",
+ "feishu_bot_app_id",
+ "feishu_open_id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_im_lookup": {
+ "name": "idx_sessions_im_lookup",
+ "columns": [
+ "source",
+ "im_bot_context_id",
+ "im_user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "sessions_parent_session_id_sessions_id_fk": {
+ "name": "sessions_parent_session_id_sessions_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "parent_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "shared_task_events": {
+ "name": "shared_task_events",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "shared_task_id": {
+ "name": "shared_task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "revision": {
+ "name": "revision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "terminal": {
+ "name": "terminal",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "snapshot": {
+ "name": "snapshot",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "recorded_at": {
+ "name": "recorded_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "shared_task_events_revision_idx": {
+ "name": "shared_task_events_revision_idx",
+ "columns": [
+ "shared_task_id",
+ "kind",
+ "revision"
+ ],
+ "isUnique": true
+ },
+ "shared_task_events_session_idx": {
+ "name": "shared_task_events_session_idx",
+ "columns": [
+ "session_id",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "shared_task_events_session_id_sessions_id_fk": {
+ "name": "shared_task_events_session_id_sessions_id_fk",
+ "tableFrom": "shared_task_events",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "skill_usage_exposures": {
+ "name": "skill_usage_exposures",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "analyzer_version": {
+ "name": "analyzer_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'6'"
+ },
+ "raw_file_path": {
+ "name": "raw_file_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "raw_line_no": {
+ "name": "raw_line_no",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "skill_name": {
+ "name": "skill_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "skill_path": {
+ "name": "skill_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "skill_document_hash": {
+ "name": "skill_document_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "exposure_content_hash": {
+ "name": "exposure_content_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "document_hash_source": {
+ "name": "document_hash_source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_use_id": {
+ "name": "tool_use_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "seen_at": {
+ "name": "seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_call_count": {
+ "name": "tool_call_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "repeated_tool_call_count": {
+ "name": "repeated_tool_call_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "tool_error_count": {
+ "name": "tool_error_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "command_call_count": {
+ "name": "command_call_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "command_failure_count": {
+ "name": "command_failure_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ }
+ },
+ "indexes": {
+ "idx_skill_usage_exposures_skill_document_version": {
+ "name": "idx_skill_usage_exposures_skill_document_version",
+ "columns": [
+ "analyzer_version",
+ "skill_name",
+ "skill_document_hash"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_skill_recent": {
+ "name": "idx_skill_usage_exposures_skill_recent",
+ "columns": [
+ "skill_name",
+ "analyzer_version",
+ "seen_at"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_skill_recent_any_version": {
+ "name": "idx_skill_usage_exposures_skill_recent_any_version",
+ "columns": [
+ "skill_name",
+ "seen_at"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_analyzer_recent_source": {
+ "name": "idx_skill_usage_exposures_analyzer_recent_source",
+ "columns": [
+ "analyzer_version",
+ "seen_at",
+ "raw_file_path"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_session": {
+ "name": "idx_skill_usage_exposures_session",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_raw_file": {
+ "name": "idx_skill_usage_exposures_raw_file",
+ "columns": [
+ "raw_file_path"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "skill_usage_exposures_raw_file_path_skill_usage_sources_raw_file_path_fk": {
+ "name": "skill_usage_exposures_raw_file_path_skill_usage_sources_raw_file_path_fk",
+ "tableFrom": "skill_usage_exposures",
+ "tableTo": "skill_usage_sources",
+ "columnsFrom": [
+ "raw_file_path"
+ ],
+ "columnsTo": [
+ "raw_file_path"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "skill_usage_sources": {
+ "name": "skill_usage_sources",
+ "columns": {
+ "raw_file_path": {
+ "name": "raw_file_path",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "analyzer_version": {
+ "name": "analyzer_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'6'"
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mtime_ms": {
+ "name": "mtime_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "size_bytes": {
+ "name": "size_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "last_scanned_at": {
+ "name": "last_scanned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'ok'"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_skill_usage_sources_session": {
+ "name": "idx_skill_usage_sources_session",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_sources_sdk_session": {
+ "name": "idx_skill_usage_sources_sdk_session",
+ "columns": [
+ "sdk_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subagent_run_aliases": {
+ "name": "subagent_run_aliases",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "alias": {
+ "name": "alias",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "subagent_run_aliases_lookup_idx": {
+ "name": "subagent_run_aliases_lookup_idx",
+ "columns": [
+ "session_id",
+ "provider",
+ "alias",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "subagent_run_aliases_session_id_sessions_id_fk": {
+ "name": "subagent_run_aliases_session_id_sessions_id_fk",
+ "tableFrom": "subagent_run_aliases",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "subagent_run_aliases_run_id_subagent_runs_id_fk": {
+ "name": "subagent_run_aliases_run_id_subagent_runs_id_fk",
+ "tableFrom": "subagent_run_aliases",
+ "tableTo": "subagent_runs",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "subagent_run_aliases_run_id_alias_pk": {
+ "columns": [
+ "run_id",
+ "alias"
+ ],
+ "name": "subagent_run_aliases_run_id_alias_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subagent_runs": {
+ "name": "subagent_runs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "logical_agent_id": {
+ "name": "logical_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "parent_tool_use_id": {
+ "name": "parent_tool_use_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "aliases": {
+ "name": "aliases",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "provider_run_ids": {
+ "name": "provider_run_ids",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'running'"
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "returned_result": {
+ "name": "returned_result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "returned_result_empty": {
+ "name": "returned_result_empty",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "returned_result_truncated": {
+ "name": "returned_result_truncated",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "reasoning_effort": {
+ "name": "reasoning_effort",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "total_tokens": {
+ "name": "total_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tool_uses": {
+ "name": "tool_uses",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "duration_ms": {
+ "name": "duration_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "capabilities": {
+ "name": "capabilities",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "activity": {
+ "name": "activity",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "rewind_at": {
+ "name": "rewind_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "subagent_runs_logical_idx": {
+ "name": "subagent_runs_logical_idx",
+ "columns": [
+ "session_id",
+ "provider",
+ "logical_agent_id"
+ ],
+ "isUnique": false
+ },
+ "subagent_runs_session_idx": {
+ "name": "subagent_runs_session_idx",
+ "columns": [
+ "session_id",
+ "rewind_at",
+ "deleted_at",
+ "started_at"
+ ],
+ "isUnique": false
+ },
+ "subagent_runs_parent_tool_use_idx": {
+ "name": "subagent_runs_parent_tool_use_idx",
+ "columns": [
+ "session_id",
+ "parent_tool_use_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "subagent_runs_session_id_sessions_id_fk": {
+ "name": "subagent_runs_session_id_sessions_id_fk",
+ "tableFrom": "subagent_runs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "task_tags": {
+ "name": "task_tags",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name_customized": {
+ "name": "name_customized",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "favorite_order": {
+ "name": "favorite_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "revision": {
+ "name": "revision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ }
+ },
+ "indexes": {
+ "task_tags_name_idx": {
+ "name": "task_tags_name_idx",
+ "columns": [
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "vec_table_meta": {
+ "name": "vec_table_meta",
+ "columns": {
+ "vec_table": {
+ "name": "vec_table",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "dim": {
+ "name": "dim",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "registered_at": {
+ "name": "registered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "notes": {
+ "name": "notes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_file_attachments": {
+ "name": "wechat_file_attachments",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "abs_path": {
+ "name": "abs_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "original_name": {
+ "name": "original_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mime_type": {
+ "name": "mime_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bytes": {
+ "name": "bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'staged'"
+ },
+ "promoted_at": {
+ "name": "promoted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_wechat_file_attachments_task": {
+ "name": "idx_wechat_file_attachments_task",
+ "columns": [
+ "binding_epoch",
+ "task_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "wechat_file_attachments_binding_epoch_wechat_sync_state_binding_epoch_fk": {
+ "name": "wechat_file_attachments_binding_epoch_wechat_sync_state_binding_epoch_fk",
+ "tableFrom": "wechat_file_attachments",
+ "tableTo": "wechat_sync_state",
+ "columnsFrom": [
+ "binding_epoch"
+ ],
+ "columnsTo": [
+ "binding_epoch"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wechat_file_attachments_task_id_wechat_inbox_id_fk": {
+ "name": "wechat_file_attachments_task_id_wechat_inbox_id_fk",
+ "tableFrom": "wechat_file_attachments",
+ "tableTo": "wechat_inbox",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wechat_file_attachments_session_id_sessions_id_fk": {
+ "name": "wechat_file_attachments_session_id_sessions_id_fk",
+ "tableFrom": "wechat_file_attachments",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_inbox": {
+ "name": "wechat_inbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "platform_message_id": {
+ "name": "platform_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "platform_seq": {
+ "name": "platform_seq",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "peer_id": {
+ "name": "peer_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "received_at": {
+ "name": "received_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "platform_created_at": {
+ "name": "platform_created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "lease_until": {
+ "name": "lease_until",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "conversation_epoch": {
+ "name": "conversation_epoch",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "payload_json": {
+ "name": "payload_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_nonce": {
+ "name": "context_nonce",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_ciphertext": {
+ "name": "context_ciphertext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_tag": {
+ "name": "context_tag",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "last_error_code": {
+ "name": "last_error_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_wechat_inbox_platform_message": {
+ "name": "uniq_wechat_inbox_platform_message",
+ "columns": [
+ "binding_epoch",
+ "platform_message_id"
+ ],
+ "isUnique": true
+ },
+ "idx_wechat_inbox_queue": {
+ "name": "idx_wechat_inbox_queue",
+ "columns": [
+ "binding_epoch",
+ "status",
+ "received_at"
+ ],
+ "isUnique": false
+ },
+ "idx_wechat_inbox_lease": {
+ "name": "idx_wechat_inbox_lease",
+ "columns": [
+ "binding_epoch",
+ "lease_until"
+ ],
+ "isUnique": false
+ },
+ "idx_wechat_inbox_conversation": {
+ "name": "idx_wechat_inbox_conversation",
+ "columns": [
+ "binding_epoch",
+ "peer_id",
+ "conversation_epoch"
+ ],
+ "isUnique": false
+ },
+ "uniq_wechat_inbox_running_session": {
+ "name": "uniq_wechat_inbox_running_session",
+ "columns": [
+ "binding_epoch",
+ "session_id"
+ ],
+ "isUnique": true,
+ "where": "\"wechat_inbox\".\"session_id\" IS NOT NULL AND \"wechat_inbox\".\"status\" IN ('dispatching', 'accepted_running', 'waiting_desktop', 'delivery_pending')"
+ }
+ },
+ "foreignKeys": {
+ "wechat_inbox_binding_epoch_wechat_sync_state_binding_epoch_fk": {
+ "name": "wechat_inbox_binding_epoch_wechat_sync_state_binding_epoch_fk",
+ "tableFrom": "wechat_inbox",
+ "tableTo": "wechat_sync_state",
+ "columnsFrom": [
+ "binding_epoch"
+ ],
+ "columnsTo": [
+ "binding_epoch"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wechat_inbox_session_id_sessions_id_fk": {
+ "name": "wechat_inbox_session_id_sessions_id_fk",
+ "tableFrom": "wechat_inbox",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_outbox": {
+ "name": "wechat_outbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chunk_index": {
+ "name": "chunk_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "media_json": {
+ "name": "media_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "next_retry_at": {
+ "name": "next_retry_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "delivered_at": {
+ "name": "delivered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_wechat_outbox_client_id": {
+ "name": "uniq_wechat_outbox_client_id",
+ "columns": [
+ "binding_epoch",
+ "client_id"
+ ],
+ "isUnique": true
+ },
+ "idx_wechat_outbox_delivery": {
+ "name": "idx_wechat_outbox_delivery",
+ "columns": [
+ "binding_epoch",
+ "status",
+ "next_retry_at"
+ ],
+ "isUnique": false
+ },
+ "idx_wechat_outbox_task": {
+ "name": "idx_wechat_outbox_task",
+ "columns": [
+ "binding_epoch",
+ "task_id",
+ "chunk_index"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "wechat_outbox_binding_epoch_wechat_sync_state_binding_epoch_fk": {
+ "name": "wechat_outbox_binding_epoch_wechat_sync_state_binding_epoch_fk",
+ "tableFrom": "wechat_outbox",
+ "tableTo": "wechat_sync_state",
+ "columnsFrom": [
+ "binding_epoch"
+ ],
+ "columnsTo": [
+ "binding_epoch"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wechat_outbox_task_id_wechat_inbox_id_fk": {
+ "name": "wechat_outbox_task_id_wechat_inbox_id_fk",
+ "tableFrom": "wechat_outbox",
+ "tableTo": "wechat_inbox",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_sync_state": {
+ "name": "wechat_sync_state",
+ "columns": {
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "sync_cursor": {
+ "name": "sync_cursor",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "last_poll_at": {
+ "name": "last_poll_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_error_code": {
+ "name": "last_error_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_wechat_sync_active": {
+ "name": "uniq_wechat_sync_active",
+ "columns": [
+ "is_active"
+ ],
+ "isUnique": true,
+ "where": "\"wechat_sync_state\".\"is_active\" = 1"
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {
+ "uniq_orca_worker_creation_reservations_team_label": {
+ "columns": {
+ "lower(\"label\")": {
+ "isExpression": true
+ }
+ }
+ },
+ "uniq_orca_workers_team_label": {
+ "columns": {
+ "lower(\"label\")": {
+ "isExpression": true
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/apps/desktop/drizzle/meta/_journal.json b/apps/desktop/drizzle/meta/_journal.json
index a9a5bcb755..29a4a6230e 100644
--- a/apps/desktop/drizzle/meta/_journal.json
+++ b/apps/desktop/drizzle/meta/_journal.json
@@ -883,6 +883,13 @@
"when": 1791563747047,
"tag": "0125_magical_night_thrasher",
"breakpoints": true
+ },
+ {
+ "idx": 126,
+ "version": "6",
+ "when": 1791978396032,
+ "tag": "0126_melodic_toxin",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cindyMediaCatalog.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cindyMediaCatalog.test.ts
index d8eefc71d3..f21060ee01 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/cindyMediaCatalog.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/cindyMediaCatalog.test.ts
@@ -10,7 +10,6 @@ import { describe, it, expect } from 'vitest';
import {
deriveCindyMediaConfig,
- filterLegacyCindyMediaConfig,
selectExecutableCoreMediaModels,
type CindyMediaProviderSlice,
} from '../cindyMediaCatalog';
@@ -54,47 +53,6 @@ describe('selectExecutableCoreMediaModels', () => {
});
});
-describe('filterLegacyCindyMediaConfig', () => {
- const models = [
- {
- id: 'media:xd:core-video', modelId: 'core-video', providerId: 'xd',
- label: 'Core', supportsEdit: true,
- },
- {
- id: 'media:xd:shared-video', modelId: 'shared-video', providerId: 'xd',
- label: 'Gateway', supportsEdit: true,
- },
- {
- id: 'media:local:shared-video', modelId: 'shared-video', providerId: 'local',
- label: 'Local', supportsEdit: true,
- },
- ];
- const config = {
- models,
- defaults: { standard: models[0]!.id, draft: models[0]!.id, best: models[0]!.id },
- };
-
- it('旧通道按完整来源筛选并恢复失效默认,不缩减 Core 原目录', () => {
- const legacy = filterLegacyCindyMediaConfig(
- config,
- (model) => model.providerId === 'local' && model.modelId === 'shared-video',
- );
- expect(legacy.models).toEqual([models[2]]);
- expect(legacy.defaults).toEqual({
- standard: models[2]!.id,
- draft: models[2]!.id,
- best: models[2]!.id,
- });
- expect(config.models).toHaveLength(3);
- expect(config.defaults.standard).toBe(models[0]!.id);
- });
-
- it('保留仍可执行的默认;没有旧通道候选时不伪造选型', () => {
- expect(filterLegacyCindyMediaConfig(config, () => true)).toEqual(config);
- expect(filterLegacyCindyMediaConfig(config, () => false)).toEqual({ models: [], defaults: null });
- });
-});
-
describe('deriveCindyMediaConfig — 正常目录', () => {
it('清单按目录序、label 取 name、providerId 记归属;draft/best 缺省回落 standard', () => {
const image = deriveCindyMediaConfig([XD], 'image');
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cindyOverrideWhitelist.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cindyOverrideWhitelist.test.ts
deleted file mode 100644
index 8e214832d9..0000000000
--- a/apps/desktop/src/main/cindy-brain/__tests__/cindyOverrideWhitelist.test.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-/**
- * cindyOverrideWhitelist.test.ts — 钉档白名单单测(纯函数,无 Electron)。
- *
- * 核心守护:text.*(快问快答)的取值是轻量任务模型链档位键(codex-gpt-5.4-mini
- * 等供应商×模型组合),不是媒体目录模型 id——校验若错拿图像目录,text 钉档
- * 恒被 INVALID_PARAMS 拒绝(详情页「操作失败」),这是本文件的由来。
- */
-
-import { describe, expect, it } from 'vitest';
-
-import { isCindyOverrideModelAllowed } from '../cindyOverrideWhitelist';
-
-const CATALOGS = {
- image: [
- { id: 'img-pro', supportsEdit: true },
- { id: 'img-basic' },
- ],
- video: [{ id: 'vid-pro' }],
- embed: [{ id: 'emb-1' }],
- // text.* 的目录钉全集(调用侧按当前供应商目录现算)。
- textPinIds: ['cat:xd:codex:codex/gpt-5.5', 'cat:openai:codex:gpt-5.5'],
-} as const;
-
-describe('isCindyOverrideModelAllowed', () => {
- it('model=null = 清除覆盖(恢复跟随默认),任何类目都放行', () => {
- expect(isCindyOverrideModelAllowed('text.oneshot', null, CATALOGS)).toBe(true);
- expect(isCindyOverrideModelAllowed('image.generate', null, CATALOGS)).toBe(true);
- expect(isCindyOverrideModelAllowed('video.generate', null, CATALOGS)).toBe(true);
- });
-
- it('text.* 放行轻量档位键(兼容既有形态)与当前目录钉', () => {
- expect(isCindyOverrideModelAllowed('text.oneshot', 'codex-gpt-5.4-mini', CATALOGS)).toBe(true);
- expect(isCindyOverrideModelAllowed('text.oneshot', 'litellm-kimi-k2.6', CATALOGS)).toBe(true);
- expect(isCindyOverrideModelAllowed('text.oneshot', 'cat:xd:codex:codex/gpt-5.5', CATALOGS)).toBe(true);
- expect(isCindyOverrideModelAllowed('text.oneshot', 'cat:openai:codex:gpt-5.5', CATALOGS)).toBe(true);
- });
-
- it('text.* 拒绝裸模型名、不在目录的钉值、媒体目录 id 与空串', () => {
- // 档位键 ≠ 模型名:消费方只认这两类编码,放行裸名会让钉档静默回落默认。
- expect(isCindyOverrideModelAllowed('text.oneshot', 'moonshotai/kimi-k2.6', CATALOGS)).toBe(false);
- expect(isCindyOverrideModelAllowed('text.oneshot', 'cat:xd:codex:no-such-model', CATALOGS)).toBe(false);
- expect(isCindyOverrideModelAllowed('text.oneshot', 'img-pro', CATALOGS)).toBe(false);
- expect(isCindyOverrideModelAllowed('text.oneshot', '', CATALOGS)).toBe(false);
- });
-
- it('image.* 钉图像目录;image.edit 额外要求 supportsEdit', () => {
- expect(isCindyOverrideModelAllowed('image.generate', 'img-pro', CATALOGS)).toBe(true);
- expect(isCindyOverrideModelAllowed('image.generate', 'img-basic', CATALOGS)).toBe(true);
- expect(isCindyOverrideModelAllowed('image.edit', 'img-pro', CATALOGS)).toBe(true);
- expect(isCindyOverrideModelAllowed('image.edit', 'img-basic', CATALOGS)).toBe(false);
- expect(isCindyOverrideModelAllowed('image.generate', 'codex-gpt-5.4-mini', CATALOGS)).toBe(false);
- });
-
- it('video.* 钉视频目录,不要求 supportsEdit', () => {
- expect(isCindyOverrideModelAllowed('video.generate', 'vid-pro', CATALOGS)).toBe(true);
- expect(isCindyOverrideModelAllowed('video.edit', 'vid-pro', CATALOGS)).toBe(true);
- expect(isCindyOverrideModelAllowed('video.generate', 'img-pro', CATALOGS)).toBe(false);
- });
-
- it('embed.* 钉向量目录(上游 #1707 新增的能力域)', () => {
- expect(isCindyOverrideModelAllowed('embed.text', 'emb-1', CATALOGS)).toBe(true);
- expect(isCindyOverrideModelAllowed('embed.text', 'vid-pro', CATALOGS)).toBe(false);
- });
-
- it('非字符串值(数字/对象/undefined)一律拒', () => {
- expect(isCindyOverrideModelAllowed('text.oneshot', 42, CATALOGS)).toBe(false);
- expect(isCindyOverrideModelAllowed('image.generate', { id: 'img-pro' }, CATALOGS)).toBe(false);
- expect(isCindyOverrideModelAllowed('video.generate', undefined, CATALOGS)).toBe(false);
- });
-
- it('未知类目一律拒(IPC 层已先按 CINDY_CAPABILITY_KEYS 过滤,这里是纵深)', () => {
- expect(isCindyOverrideModelAllowed('fs.read', 'img-pro', CATALOGS)).toBe(false);
- });
-
- it('原型继承键(toString/constructor/__proto__)不当轻量档位放行', () => {
- // `value in UTILITY_MODEL_PROFILES` 会把继承键当真:入库后消费侧拿不到
- // profile,该意识的快问快答持续 NO_CANDIDATE 直到清钉。
- expect(isCindyOverrideModelAllowed('text.oneshot', 'toString', CATALOGS)).toBe(false);
- expect(isCindyOverrideModelAllowed('text.oneshot', 'constructor', CATALOGS)).toBe(false);
- expect(isCindyOverrideModelAllowed('text.oneshot', '__proto__', CATALOGS)).toBe(false);
- });
-});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cindyPrefsStore.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cindyPrefsStore.test.ts
index 9d1477524a..8eb789cbab 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/cindyPrefsStore.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/cindyPrefsStore.test.ts
@@ -1,7 +1,7 @@
/**
- * cindyPrefsStore.test.ts — cindy 槽后端覆盖存储的 normalize 单测。
- * 存储真身经 createOverrideSettingsFile 落 userData,依赖 electron;这里
- * 只测纯函数 normalize(坏形态清洗),读写链路由 IPC 层与 slot 测试覆盖。
+ * cindyPrefsStore.test.ts — cindy 槽隐藏配置(在途并发上限)的 normalize 单测。
+ * 旧 `overrides` 只为一次性迁移保留快问快答钉值;迁移读写链路见
+ * pluginModelPrefsMigration.test.ts。
*/
import { describe, it, expect, vi } from 'vitest';
@@ -14,96 +14,39 @@ vi.mock('../../maker-host/logger-adapter.js', () => ({
const { __testing } = await import('../cindyPrefsStore');
describe('normalize(坏形态清洗)', () => {
- it('合法覆盖保留;未知能力键、空串、非对象条目全部清掉', () => {
+ it('整体不是对象 / 缺键 → 空表,没有 overrides 字段', () => {
+ expect(__testing.normalize(null)).toEqual({ inflightLimits: {} });
+ expect(__testing.normalize({})).toEqual({ inflightLimits: {} });
+ expect(__testing.normalize({ overrides: 42 })).toEqual({ inflightLimits: {} });
+ });
+
+ it('inflightLimits:正整数保留,0/负数/小数/字符串/非对象全部清掉', () => {
expect(
__testing.normalize({
- overrides: {
- art: { 'image.generate': 'gpt-image-2', 'image.upscale': 'x', 'image.edit': '' },
- broken: 'not-an-object',
- empty: {},
- },
+ inflightLimits: { art: 3, zero: 0, neg: -1, frac: 1.5, str: '2', nan: NaN },
}),
- ).toEqual({ overrides: { art: { 'image.generate': 'gpt-image-2' } }, inflightLimits: {} });
+ ).toEqual({ inflightLimits: { art: 3 } });
+ expect(__testing.normalize({ inflightLimits: 'nope' })).toEqual({ inflightLimits: {} });
});
- it('旧 Gemini 图片 alias 映射到新 ID,保留已自定义用户的模型选择', () => {
+ it('旧 overrides 只留快问快答钉值供迁移,媒体/向量覆盖与坏条目不再读取', () => {
expect(
__testing.normalize({
overrides: {
- art: {
- 'image.generate': 'gemini-3-pro-image-preview',
- 'image.edit': 'gemini-3.1-flash-image-preview',
- 'video.generate': 'gemini-3-pro-image-preview',
- },
+ art: { 'image.generate': 'gpt-image-2', 'text.oneshot': 'cat:xd:codex:gpt-5.5' },
+ media: { 'video.generate': 'vid-pro', 'embed.text': 'emb-1' },
+ blank: { 'text.oneshot': '' },
+ broken: 'not-an-object',
},
+ inflightLimits: { art: 'bad' },
}),
).toEqual({
+ inflightLimits: {},
overrides: {
- art: {
- 'image.generate': 'gemini-3-pro-image',
- 'image.edit': 'gemini-3.1-flash-image',
- // 迁移只作用于图片能力,避免改写其它类别的未知值。
- 'video.generate': 'gemini-3-pro-image-preview',
- },
+ art: { 'text.oneshot': 'cat:xd:codex:gpt-5.5' },
+ media: {},
+ blank: {},
},
- inflightLimits: {},
});
});
-
- it('整体不是对象 / 缺 overrides → 空表', () => {
- expect(__testing.normalize(null)).toEqual({ overrides: {}, inflightLimits: {} });
- expect(__testing.normalize({ overrides: 42 })).toEqual({ overrides: {}, inflightLimits: {} });
- });
-
- it('inflightLimits:正整数保留,0/负数/小数/字符串/非对象全部清掉', () => {
- expect(
- __testing.normalize({
- inflightLimits: { art: 3, zero: 0, neg: -1, frac: 1.5, str: '2', nan: NaN },
- }),
- ).toEqual({ overrides: {}, inflightLimits: { art: 3 } });
- expect(__testing.normalize({ inflightLimits: 'nope' })).toEqual({ overrides: {}, inflightLimits: {} });
- });
-
- it('overrides 与 inflightLimits 互不影响(一边坏了另一边照常保留)', () => {
- expect(
- __testing.normalize({
- overrides: { art: { 'image.generate': 'gpt-image-2' } },
- inflightLimits: { art: 'bad' },
- }),
- ).toEqual({ overrides: { art: { 'image.generate': 'gpt-image-2' } }, inflightLimits: {} });
- expect(
- __testing.normalize({ overrides: 42, inflightLimits: { art: 2 } }),
- ).toEqual({ overrides: {}, inflightLimits: { art: 2 } });
- });
-});
-
-/**
- * 取值域映射 —— 写入校验拿哪份白名单全看它。
- *
- * 这不是形式主义:映射漏一个类目时,该类目的下拉在设置里照常渲染、照常可选,
- * 一选就被别的类目的白名单拒掉,前端回滚成一句通用 toast —— 界面上看不出是
- * "这个能力的钉选功能整个不工作"(PR #1707 review 实际发生过两次)。
- */
-describe('cindyCapabilityValueDomain(取值域映射)', () => {
- it('每个已登记的能力键都有映射,没有落进兜底分支的', async () => {
- const { CINDY_CAPABILITY_KEYS, cindyCapabilityValueDomain } = await import(
- '../cindyPrefsStore'
- );
- for (const key of CINDY_CAPABILITY_KEYS) {
- expect(cindyCapabilityValueDomain(key), key).toMatch(
- /^(image|video|embed|utilityChain)$/,
- );
- }
- });
-
- it('类目归属逐条锁死(embed 不能落到 image;text 不走媒体目录)', async () => {
- const { cindyCapabilityValueDomain } = await import('../cindyPrefsStore');
- expect(cindyCapabilityValueDomain('image.generate')).toBe('image');
- expect(cindyCapabilityValueDomain('image.edit')).toBe('image');
- expect(cindyCapabilityValueDomain('video.generate')).toBe('video');
- expect(cindyCapabilityValueDomain('video.edit')).toBe('video');
- expect(cindyCapabilityValueDomain('embed.text')).toBe('embed');
- // 轻量链档位键(codex-gpt-5.4-mini 等)与媒体目录 model id 不是同一个词汇表。
- expect(cindyCapabilityValueDomain('text.oneshot')).toBe('utilityChain');
- });
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts
index 43730c387d..2c247f8c9d 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts
@@ -70,7 +70,6 @@ function makeSlot(overrides: Partial<CindySlotDeps> = {}): {
generateVideo: ReturnType<typeof vi.fn>;
editVideo: ReturnType<typeof vi.fn>;
resolveOwnedMedia: ReturnType<typeof vi.fn>;
- getOverride: ReturnType<typeof vi.fn>;
getImageConfig: ReturnType<typeof vi.fn>;
getVideoConfig: ReturnType<typeof vi.fn>;
videoCapabilities: ReturnType<typeof vi.fn>;
@@ -116,7 +115,6 @@ function makeSlot(overrides: Partial<CindySlotDeps> = {}): {
);
const imageCapabilities = vi.fn(() => null);
const resolveOwnedMedia = vi.fn(async (_ghostId: string, hash: string) => `/disk/${hash}.png`);
- const getOverride = vi.fn((_ghostId: string, _capability: string) => null as string | null);
const getImageConfig = vi.fn(() => ({
models: [
{ id: 'gpt-image-2', label: 'GPT Image 2' },
@@ -173,7 +171,6 @@ function makeSlot(overrides: Partial<CindySlotDeps> = {}): {
generateVideo,
editVideo,
resolveOwnedMedia,
- getOverride,
getImageConfig,
getVideoConfig,
imageCapabilities,
@@ -195,7 +192,6 @@ function makeSlot(overrides: Partial<CindySlotDeps> = {}): {
generateVideo,
editVideo,
resolveOwnedMedia,
- getOverride,
getImageConfig,
getVideoConfig,
videoCapabilities,
@@ -224,7 +220,7 @@ describe('载荷校验', () => {
).toMatchObject({ ok: false });
});
- it('Art keeps its saved subscription image selection for generation and editing with the unified label', async () => {
+ it('Art keeps an explicit subscription image model for generation and editing with the unified label', async () => {
setActiveCatalog(BUNDLED_CATALOG);
setOpenAiImagesApiKeyConfigured(false);
const config = deriveCindyMediaConfig(getActiveCatalog().providers, 'image');
@@ -232,9 +228,8 @@ describe('载荷校验', () => {
expect(config.models.find(m => m.id === id)).toMatchObject({ label: 'GPT Image Gen', supportsEdit: true });
const { slot, generateImage, editImage } = makeSlot({
getImageConfig: () => config,
- getOverride: () => id,
});
- for (const request of [REQ, EDIT_REQ]) {
+ for (const request of [{ ...REQ, model: id }, { ...EDIT_REQ, model: id }]) {
expect(await slot.handleModelRequest('art', request)).toMatchObject({
ok: true, model: id, modelLabel: 'GPT Image Gen',
});
@@ -786,67 +781,21 @@ describe('目录空清单 = 能力暂不可用', () => {
expect(editImage).not.toHaveBeenCalled();
});
- it('清单空时用户钉的旧覆盖也不生效(不拿不在册型号下单)', async () => {
- const { slot, generateImage } = makeSlot({
- getImageConfig: vi.fn(() => EMPTY_CONFIG) as unknown as CindySlotDeps['getImageConfig'],
- getOverride: vi.fn(() => 'gpt-image-2') as unknown as CindySlotDeps['getOverride'],
- });
- expect(await slot.handleModelRequest('art', REQ)).toMatchObject({ ok: false });
- expect(generateImage).not.toHaveBeenCalled();
- });
});
-describe('意识专属后端覆盖(解析表第②层)', () => {
- it('新版 Provider-aware 覆盖保留精确来源到最终派发', async () => {
- const { slot, generateImage } = makeSlot({
- getMediaOverride: vi.fn(() => ({
- modelId: 'gpt-image-2',
- providerId: 'openai',
- label: 'GPT Image 2',
- })),
- });
-
- const result = await slot.handleModelRequest('art', REQ);
-
- expect(result).toMatchObject({ ok: true, model: 'gpt-image-2', modelLabel: 'GPT Image 2' });
- expect(generateImage).toHaveBeenCalledWith({
- prompt: '一只猫',
- model: 'gpt-image-2',
- providerId: 'openai',
- });
- });
-
- it('覆盖压过档位;调用显式点名仍压过覆盖;下架型号的覆盖静默落回', async () => {
- const pinned = makeSlot({
- getOverride: vi.fn(() => 'gemini-3-pro-image') as unknown as CindySlotDeps['getOverride'],
- });
- // 覆盖 > tier
- await pinned.slot.handleModelRequest('art', { ...REQ, tier: 'draft' });
- expect(pinned.generateImage).toHaveBeenLastCalledWith({
- prompt: '一只猫',
- model: 'gemini-3-pro-image',
- });
- // 显式点名 > 覆盖
- await pinned.slot.handleModelRequest('art', { ...REQ, model: 'gpt-image-2' });
- expect(pinned.generateImage).toHaveBeenLastCalledWith({ prompt: '一只猫', model: 'gpt-image-2' });
-
- // 钉的型号已不在白名单 → 忽略覆盖,落回默认,不拒单。
- const stale = makeSlot({
- getOverride: vi.fn(() => 'retired-model-9') as unknown as CindySlotDeps['getOverride'],
- });
- const r = await stale.slot.handleModelRequest('art', REQ);
- expect(r).toMatchObject({ ok: true });
- expect(stale.generateImage).toHaveBeenLastCalledWith({ prompt: '一只猫', model: 'gpt-image-2' });
- });
-
- it('覆盖按能力键全名取(出图/改图/视频各自独立)', async () => {
- const { slot, getOverride } = makeSlot();
+describe('媒体选型没有逐插件覆盖(2026-10 起只走系统默认)', () => {
+ it('默认 → 档位 → 调用显式点名;不再向宿主查询插件覆盖', async () => {
+ const { slot, generateImage, editImage, generateVideo } = makeSlot();
await slot.handleModelRequest('art', REQ);
- expect(getOverride).toHaveBeenLastCalledWith('art', 'image.generate');
+ expect(generateImage).toHaveBeenLastCalledWith({ prompt: '一只猫', model: 'gpt-image-2' });
+ await slot.handleModelRequest('art', { ...REQ, tier: 'draft' });
+ expect(generateImage).toHaveBeenLastCalledWith({ prompt: '一只猫', model: 'gemini-3.1-flash-image' });
+ await slot.handleModelRequest('art', { ...REQ, tier: 'draft', model: 'gemini-3-pro-image' });
+ expect(generateImage).toHaveBeenLastCalledWith({ prompt: '一只猫', model: 'gemini-3-pro-image' });
await slot.handleModelRequest('art', EDIT_REQ);
- expect(getOverride).toHaveBeenLastCalledWith('art', 'image.edit');
+ expect(editImage).toHaveBeenLastCalledWith(expect.objectContaining({ model: 'gpt-image-2' }));
await slot.handleModelRequest('art', { type: 'cindy-request', kind: 'gen_video', prompt: '一只猫奔跑' });
- expect(getOverride).toHaveBeenLastCalledWith('art', 'video.generate');
+ expect(generateVideo).toHaveBeenLastCalledWith(expect.objectContaining({ model: 'seedance-fast' }));
});
});
@@ -1789,7 +1738,6 @@ describe('寄存(deposit_media / release_media)', () => {
generateVideo: vi.fn(),
editVideo: vi.fn(),
resolveOwnedMedia: vi.fn(),
- getOverride: vi.fn(() => null),
getImageConfig: vi.fn(() => ({ models: [], defaults: null })),
getVideoConfig: vi.fn(() => ({ models: [], defaults: null })),
saveGhostMedia: vi.fn(),
@@ -1897,42 +1845,48 @@ describe('快问快答(oneshot_text)', () => {
});
});
- // 2026-08-05:选型优先级 = 用户钉档 > 身份卡声明(oneshotModel)> 系统默认链。
- it('选型优先级:用户钉档 > 身份卡声明 > 系统默认链', async () => {
+ // 选型优先级 = 用户在插件详情选的模型 > 身份卡声明(oneshotModel)> 系统辅助模型链。
+ it('选型优先级:用户选的模型 > 身份卡声明 > 系统辅助模型链', async () => {
const oneshotText = vi.fn(async (_params: { route?: unknown }) => ({ ok: true as const, text: 'ok' }));
const declared = { model: { text: ['oneshot'], oneshotModel: 'codex/gpt-5.5' } };
const resolveOneshotModel = vi.fn(() => ({ providerId: 'xd', agentKind: 'codex' as const, model: 'codex/gpt-5.5' }));
- // ① 用户钉了轻量档位键:原样下传,声明不生效(resolve 不调用)。
+ // ① 用户选了完整组合:钉死该 供应商×agent×模型,声明不生效(resolve 不调用)。
+ const getOneshotModelSelection = vi.fn(() => ({
+ providerId: 'openai', agentKind: 'codex' as const, model: 'gpt-5.5',
+ }));
const pinned = makeSlot({
getGhost: () => fakeGhost(declared),
- getOverride: () => 'litellm-kimi-k2.6',
+ getOneshotModelSelection,
resolveOneshotModel,
oneshotText,
});
await pinned.slot.handleModelRequest('art', ONESHOT);
+ expect(getOneshotModelSelection).toHaveBeenCalledWith('art');
expect(oneshotText).toHaveBeenLastCalledWith(
- expect.objectContaining({ route: { kind: 'utility-profile', profileId: 'litellm-kimi-k2.6' } }),
+ expect.objectContaining({
+ route: { kind: 'catalog', providerId: 'openai', agentKind: 'codex', model: 'gpt-5.5' },
+ }),
);
expect(resolveOneshotModel).not.toHaveBeenCalled();
- // ② 用户钉了目录钉(cat: 编码):解码成 供应商×agent×模型。
- const catalogPinned = makeSlot({
+ // ② 用户选的组合缺供应商(手改文件):照样钉死,交执行侧推断,不回落默认链。
+ const noProvider = makeSlot({
getGhost: () => fakeGhost(declared),
- getOverride: () => 'cat:openai:codex:gpt-5.5',
+ getOneshotModelSelection: () => ({ agentKind: 'claude-code' as const, model: 'claude-sonnet' }),
oneshotText,
});
- await catalogPinned.slot.handleModelRequest('art', ONESHOT);
+ await noProvider.slot.handleModelRequest('art', ONESHOT);
expect(oneshotText).toHaveBeenLastCalledWith(
expect.objectContaining({
- route: { kind: 'catalog', providerId: 'openai', agentKind: 'codex', model: 'gpt-5.5' },
+ route: { kind: 'catalog', agentKind: 'claude-code', model: 'claude-sonnet' },
}),
);
- // ③ 无钉档 + 声明可解析:走声明路由。
+ // ③ 未选模型 + 声明可解析:走声明路由。
const declaredOnly = makeSlot({
getGhost: () => fakeGhost(declared),
- getOverride: () => null,
+ getOneshotModelSelection: () => null,
resolveOneshotModel,
oneshotText,
});
@@ -1944,38 +1898,41 @@ describe('快问快答(oneshot_text)', () => {
}),
);
- // ④ 无钉档 + 声明解析不到(目录没有/已停用):按未声明,跟随默认链。
+ // ④ 未选模型 + 声明解析不到(目录没有/已停用):按未声明,跟随系统辅助模型链。
const unresolved = makeSlot({
getGhost: () => fakeGhost(declared),
- getOverride: () => null,
+ getOneshotModelSelection: () => null,
resolveOneshotModel: () => null,
oneshotText,
});
await unresolved.slot.handleModelRequest('art', ONESHOT);
expect(oneshotText.mock.lastCall?.[0]?.route).toBeUndefined();
- // ⑤ 无钉档无声明:route 缺省,跟随默认链。
+ // ⑤ 未选模型无声明:route 缺省,跟随系统辅助模型链。
const plain = makeSlot({
getGhost: () => fakeGhost({ model: { text: ['oneshot'] } }),
- getOverride: () => null,
+ getOneshotModelSelection: () => null,
oneshotText,
});
await plain.slot.handleModelRequest('art', ONESHOT);
expect(oneshotText.mock.lastCall?.[0]?.route).toBeUndefined();
});
- // 2026-08-06 终审:带 cat: 前缀但解码失败的钉档值必须 fail-closed——目录钉的
- // 语义是「钉死不回落」,静默落到系统默认链会悄悄烧错链路的钱。
- it('畸形目录钉(cat: 前缀但解码失败)→ NO_CANDIDATE,不回落默认链、不下链', async () => {
- const oneshotText = vi.fn(async () => ({ ok: true as const, text: 'ok' }));
+ it('每单现读用户选择:改回跟随默认后下一单即走系统辅助模型链', async () => {
+ const oneshotText = vi.fn(async (_params: { route?: unknown }) => ({ ok: true as const, text: 'ok' }));
+ let selection: { providerId: string; agentKind: 'codex'; model: string } | null = {
+ providerId: 'openai', agentKind: 'codex', model: 'gpt-5.5',
+ };
const { slot } = makeSlot({
getGhost: () => fakeGhost({ model: { text: ['oneshot'] } }),
- getOverride: () => 'cat:broken',
+ getOneshotModelSelection: () => selection,
oneshotText,
});
- const r = await slot.handleModelRequest('art', ONESHOT);
- expect(r).toMatchObject({ ok: false, errorCode: 'NO_CANDIDATE' });
- expect(oneshotText).not.toHaveBeenCalled();
+ await slot.handleModelRequest('art', ONESHOT);
+ expect(oneshotText.mock.lastCall?.[0]?.route).toMatchObject({ model: 'gpt-5.5' });
+ selection = null;
+ await slot.handleModelRequest('art', ONESHOT);
+ expect(oneshotText.mock.lastCall?.[0]?.route).toBeUndefined();
});
it('链路失败三档映射:no_candidate → NO_CANDIDATE,timeout → TIMEOUT,failed → INTERNAL', async () => {
@@ -2284,7 +2241,7 @@ describe('文本转向量(embed_text)', () => {
);
});
- it('选型:tier 档位 / 显式 model / 意识专属覆盖,白名单外明拒', async () => {
+ it('选型:tier 档位 / 显式 model,白名单外明拒', async () => {
const embedText = vi.fn(async () => ({ embeddings: [fakeVec(1)], modelUsed: 'x' }));
const { slot } = withEmbed({ embedText } as unknown as Partial<CindySlotDeps>);
await slot.handleModelRequest('art', { ...EMBED, tier: 'draft' });
@@ -2299,18 +2256,6 @@ describe('文本转向量(embed_text)', () => {
await slot.handleModelRequest('art', { ...EMBED, model: 'not-in-catalog' }),
).toMatchObject({ ok: false, errorCode: 'INVALID_PARAMS' });
- // 覆盖表(用户在插件详情页钉的后端)优先于目录默认,但仍受白名单约束。
- const pinned = vi.fn(async () => ({ embeddings: [fakeVec(1)], modelUsed: 'x' }));
- const { slot: slot2 } = withEmbed({
- embedText: pinned,
- getOverride: vi.fn((_g: string, cap: string) =>
- cap === 'embed.text' ? 'voyage/voyage-4-large' : null,
- ),
- } as unknown as Partial<CindySlotDeps>);
- await slot2.handleModelRequest('art', EMBED);
- expect(pinned).toHaveBeenLastCalledWith(
- expect.objectContaining({ model: 'voyage/voyage-4-large' }),
- );
});
it('目录无可用向量型号 → NO_CANDIDATE,不出网', async () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/customImageChannel.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/customImageChannel.test.ts
index 9c4755460e..43b1e0e899 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/customImageChannel.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/customImageChannel.test.ts
@@ -6,7 +6,6 @@ import { buildUserProvider, type Provider } from '@cindy/model-providers';
import { createCustomImageChannel, registerCustomImageChannels } from '../customImageChannel.js';
import { pruneDynamicImageChannels } from '../byokImageChannel.js';
import { ImageChannelRegistry } from '../imageChannelRegistry.js';
-import { filterLegacyCindyMediaConfig } from '../cindyMediaCatalog.js';
const MODEL = 'team/gpt-image-2.5-sunburst';
const PNG = Buffer.from('89504e470d0a1a0a', 'hex');
@@ -84,18 +83,14 @@ function harness(initial = provider()) {
}
describe('standalone custom OpenAI Images', () => {
- it('keeps URL-capable custom sources in Core but out of legacy image preferences', () => {
+ it('keeps URL-capable custom sources in Core but out of the legacy image channel', () => {
const h = harness();
const registry = new ImageChannelRegistry();
registry.register('relay', h.channel);
registry.register('existing', { ready: () => true, generateImage: vi.fn(), editImage: vi.fn() });
- const custom = { id: 'media:relay:image', modelId: MODEL, providerId: 'relay', label: 'Custom', supportsEdit: true };
- const existing = { ...custom, id: 'media:existing:image', providerId: 'existing', label: 'Existing' };
- const config = { models: [custom, existing], defaults: { standard: custom.id, draft: custom.id, best: custom.id } };
- const legacy = filterLegacyCindyMediaConfig(config, model => registry.isProviderLegacyReady(model.providerId, model.modelId));
- expect(legacy).toEqual({ models: [existing], defaults: { standard: existing.id, draft: existing.id, best: existing.id } });
+ expect(registry.isProviderLegacyReady('relay', MODEL)).toBe(false);
+ expect(registry.isProviderLegacyReady('existing', MODEL)).toBe(true);
expect(registry.isProviderReady('relay', MODEL)).toBe(true);
- expect(config.models).toEqual([custom, existing]);
expect(h.fetchImplementation).not.toHaveBeenCalled();
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalFileIpc.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalFileIpc.test.ts
index b3165b9610..d4ffe45493 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalFileIpc.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalFileIpc.test.ts
@@ -22,13 +22,12 @@ import { authorizeGhostTokenBroker } from '../ghostFirstPartyPrivilege.js';
import { createGhostInstallReceipt, type GhostInstallReceipt } from '../ghostInstallReceipt.js';
import { classifyGhostLocalUpdateSource } from '../ghostLocalUpdateSource.js';
import { confirmedTaskCapability } from '../ghostInstallConsent.js';
-import { isCindyOverrideModelAllowed } from '../cindyOverrideWhitelist.js';
type Handler = (event: unknown, ...args: unknown[]) => Promise<unknown>;
const callbackChannels = {
inspect: 'ghosts:inspect', update: 'ghosts:update', exportGhost: 'ghosts:export',
- cindyPrefs: 'ghosts:cindy-prefs:set', errandPrefs: 'ghosts:errand-prefs:set',
+ errandPrefs: 'ghosts:errand-prefs:set',
};
const createCallbacks = createGhostProductionCallbacks<Record<keyof typeof callbackChannels, Handler>>({
functions: [
@@ -255,14 +254,6 @@ function harness(
installedGhostStoragePart,
resolveInstalledGhost,
availableGhosts: () => Array.from(installed.values()),
- CINDY_CAPABILITY_KEYS: ['image.generate'],
- isCindyOverrideModelAllowed,
- getGhostMediaPreferenceConfig: () => ({ models: [] }),
- getCatalogEmbedConfig: () => ({ models: [] }),
- buildTextOneshotPinOptions: () => [],
- getActiveCatalog: () => ({}),
- readModelDisableOverrides: () => ({}),
- writeGhostCindyOverride: vi.fn((id: string) => ({ id })),
writePluginTaskConfig: vi.fn((id: string) => ({ id })),
validatePluginTaskConfig: vi.fn(async () => {}),
getGhostSetupChangeBus: () => ({ emit: vi.fn() }),
@@ -455,15 +446,12 @@ describe('local file recovery and source gates through production IPC callbacks'
expect(target.release).toHaveBeenCalledOnce();
});
- it.each(['cindy', 'errand'])('binds %s preferences to the current physical instance and rejects missing targets', async (kind) => {
+ it('binds plugin model and task preferences to the current physical instance and rejects missing targets', async () => {
const target = harness({ namespace: 'xd', approval: 'invalid' });
- const handler = target.callbacks['ghosts:' + kind + '-prefs:set'];
- const args = kind === 'cindy' ? ['image.generate', null] : [null];
- expect(await handler({}, 'filo-local', ...args)).toMatchObject(
- kind === 'cindy' ? { overrides: { id: '_ns__xd__filo-local' } } : { config: { id: '_ns__xd__filo-local' } },
- );
+ const handler = target.callbacks['ghosts:errand-prefs:set'];
+ expect(await handler({}, 'filo-local', null)).toMatchObject({ config: { id: '_ns__xd__filo-local' } });
target.installed.clear();
- await expect(Promise.resolve().then(() => handler({}, 'filo-local', ...args))).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ await expect(Promise.resolve().then(() => handler({}, 'filo-local', null))).rejects.toMatchObject({ code: 'NOT_FOUND' });
});
it('does not update an enterprise instance from a local file', async () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostPreferenceRelocation.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostPreferenceRelocation.test.ts
index eed3ae22a1..ea2047802a 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostPreferenceRelocation.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostPreferenceRelocation.test.ts
@@ -16,8 +16,7 @@ vi.mock('../../maker-host/logger-adapter.js', () => ({
import * as locks from '../../device-link/crossProcessLock.js';
import {
- relocateGhostCindyPrefs, readGhostCindyOverrides, readGhostCindyInflightLimit,
- writeGhostCindyOverride, writeGhostCindyInflightLimit,
+ relocateGhostCindyPrefs, readGhostCindyInflightLimit, writeGhostCindyInflightLimit,
} from '../cindyPrefsStore.js';
import {
relocateGhostErrandPrefs, readPluginTaskConfig, readGhostErrandSessionId,
@@ -82,11 +81,6 @@ function write(file: string, value: unknown, ownerId = owner.id): string {
}
const writers = [
- {
- name: 'Cindy override', resource: resources[0],
- prime: () => readGhostCindyOverrides(from),
- write: (id: string) => writeGhostCindyOverride(id, 'image.generate', 'next-model'),
- },
{
name: 'Cindy limit', resource: resources[0],
prime: () => readGhostCindyInflightLimit(from),
@@ -305,8 +299,8 @@ describe.each(resources)('$name relocation', (resource) => {
describe.each([
{
resource: resources[0],
- read: (id: string) => [readGhostCindyOverrides(id), readGhostCindyInflightLimit(id)],
- empty: [{}, null],
+ read: (id: string) => readGhostCindyInflightLimit(id),
+ empty: null,
},
{
resource: resources[1],
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts
index 62b44e7f47..86e5ec2597 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts
@@ -109,7 +109,7 @@ async function seedSourceResources() {
}), { skillSourceDir: path.join(root, from) });
fs.mkdirSync(path.join(scope.dir, 'ghost-kv'));
fs.writeFileSync(path.join(scope.dir, 'ghost-kv', from + '.json'), JSON.stringify({ private: 'org' }));
- cindy.writeGhostCindyOverride(from, 'image.generate', 'org-model');
+ cindy.writeGhostCindyInflightLimit(from, 3);
errand.writePluginTaskConfig(from, { permissionMode: 'auto', workingDir: '/org-workspace' });
errand.writeGhostErrandSessionId(from, 'org-session');
errand.writeGhostErrandSessionId(from, 'org-keyed-session', 'draft');
@@ -136,7 +136,7 @@ it('installs a same-name root without changing legacy data or UI references', as
expect(fs.readFileSync(path.join(scope.dir, 'ghosts-install-state', from + '.json'), 'utf8')).toBe(receiptBefore);
expect(fs.readFileSync(path.join(scope.dir, 'ghost-kv', from + '.json'), 'utf8')).toBe(JSON.stringify({ private: 'org' }));
expect(fs.existsSync(path.join(scope.dir, 'ghost-kv', '_root__' + from + '.json'))).toBe(false);
- expect(cindy.readGhostCindyOverrides(from)['image.generate']).toBe('org-model');
+ expect(cindy.readGhostCindyInflightLimit(from)).toBe(3);
expect(errand.readPluginTaskConfig(from)).toMatchObject({ permissionMode: 'auto', workingDir: '/org-workspace' });
expect(errand.readGhostErrandSessionId(from, 'draft')).toBe('org-keyed-session');
expect(unread.readGhostUnread(from)).toMatchObject({ summary: 'org activity', at: 100 });
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginModelPrefsIpc.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginModelPrefsIpc.test.ts
new file mode 100644
index 0000000000..97f8fef97a
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginModelPrefsIpc.test.ts
@@ -0,0 +1,115 @@
+/**
+ * pluginModelPrefsIpc.test.ts — 插件详情「模型与任务」的读通道:沿用 ghosts:errand-prefs,
+ * 额外带出系统辅助模型显示名;旧的逐能力 ghosts:cindy-prefs 通道已移除。
+ * 回调取自生产 index.ts 源码(同 ghostLocalFileIpc 的抽取方式)。
+ */
+
+import fs from 'node:fs';
+import { describe, expect, it, vi } from 'vitest';
+
+import { createGhostProductionCallbacks } from './ghostProductionCallbacksFixture.js';
+
+type SyncHandler = (event: { returnValue?: unknown }, ...args: unknown[]) => void;
+
+const createCallbacks = createGhostProductionCallbacks<{ errandPrefs: SyncHandler }>({
+ callbacks: { errandPrefs: ['ipcMain.on', 'ghosts:errand-prefs'] },
+});
+
+function read(deps: Record<string, unknown>, ghostId: unknown): unknown {
+ const event: { returnValue?: unknown } = {};
+ createCallbacks(deps).errandPrefs(event, ghostId);
+ return event.returnValue;
+}
+
+describe('ghosts:errand-prefs (plugin model & tasks)', () => {
+ it('returns the stored config and the current auxiliary model label, read fresh each time', () => {
+ const readPluginTaskConfig = vi.fn(() => ({ permissionMode: 'auto' }));
+ let refs = ['cat:xai:codex:grok-4.6'];
+ const deps = {
+ readPluginTaskConfig,
+ getEffectiveAuxiliaryModelChain: () => ({ refs }),
+ formatAuxiliaryModelRefLabel: (ref: string) => (ref.endsWith('grok-4.6') ? 'Grok 4.6' : 'GPT-5.5'),
+ };
+ expect(read(deps, 'writer')).toEqual({
+ config: { permissionMode: 'auto' },
+ auxiliaryModelLabel: 'Grok 4.6',
+ });
+ expect(readPluginTaskConfig).toHaveBeenCalledWith('writer');
+ // 系统辅助模型改了:不缓存,下次打开详情页即跟随。
+ refs = ['cat:openai:codex:gpt-5.5'];
+ expect(read(deps, 'writer')).toMatchObject({ auxiliaryModelLabel: 'GPT-5.5' });
+ });
+
+ it('reports no auxiliary model when the chain is empty and ignores malformed ids', () => {
+ const readPluginTaskConfig = vi.fn();
+ expect(read({
+ readPluginTaskConfig,
+ getEffectiveAuxiliaryModelChain: () => ({ refs: [] }),
+ formatAuxiliaryModelRefLabel: vi.fn(),
+ }, 42)).toEqual({ config: {}, auxiliaryModelLabel: null });
+ expect(readPluginTaskConfig).not.toHaveBeenCalled();
+ });
+
+ it('no longer registers the per-ability cindy-prefs channels', () => {
+ const source = fs.readFileSync(new URL('../index.ts', import.meta.url), 'utf8');
+ expect(source).not.toContain("'ghosts:cindy-prefs'");
+ expect(source).not.toContain("'ghosts:cindy-prefs:set'");
+ });
+});
+
+type OneshotSelection = { providerId?: string; agentKind: string; model: string } | null;
+
+const createSelection = createGhostProductionCallbacks<{
+ getPluginOneshotModelSelection: (ghostId: string) => OneshotSelection;
+}>({ functions: ['getPluginOneshotModelSelection'] });
+
+describe('getPluginOneshotModelSelection (plugin oneshot model pin)', () => {
+ function select(config: Record<string, unknown>, resolved: OneshotSelection): {
+ result: OneshotSelection;
+ resolve: ReturnType<typeof vi.fn>;
+ } {
+ const resolve = vi.fn(() => resolved);
+ const { getPluginOneshotModelSelection } = createSelection({
+ readPluginTaskConfig: () => config,
+ resolveOneshotCatalogModel: resolve,
+ getActiveCatalog: () => ({}),
+ readModelDisableOverrides: () => undefined,
+ readProviderOrder: () => ['xd', 'openai'],
+ hasOneshotProviderCredential: () => true,
+ });
+ return { result: getPluginOneshotModelSelection('writer'), resolve };
+ }
+
+ it('keeps the user-chosen provider when the Pi route only resolves on another provider', () => {
+ // 用户选的供应商没有快问快答通道,目录只在另一家解析到同名模型:不换供应商。
+ const { result, resolve } = select(
+ { agentKind: 'pi', providerId: 'my-relay', model: 'gpt-5.5' },
+ { providerId: 'openai', agentKind: 'codex', model: 'gpt-5.5' },
+ );
+ expect(resolve.mock.calls[0]?.[3]).toEqual(['my-relay', 'xd', 'openai']);
+ expect(result).toEqual({ agentKind: 'pi', model: 'gpt-5.5', providerId: 'my-relay' });
+ });
+
+ it('uses the resolved oneshot route when it stays on the user-chosen provider', () => {
+ const { result } = select(
+ { agentKind: 'pi', providerId: 'my-relay', model: 'gpt-5.5' },
+ { providerId: 'my-relay', agentKind: 'codex', model: 'gpt-5.5' },
+ );
+ expect(result).toEqual({ providerId: 'my-relay', agentKind: 'codex', model: 'gpt-5.5' });
+ });
+
+ it('accepts any resolved provider when the user did not choose one', () => {
+ const { result } = select(
+ { model: 'gpt-5.5' },
+ { providerId: 'openai', agentKind: 'codex', model: 'gpt-5.5' },
+ );
+ expect(result).toEqual({ providerId: 'openai', agentKind: 'codex', model: 'gpt-5.5' });
+ });
+
+ it('returns null when no model is chosen and pins explicit non-Pi selections as-is', () => {
+ expect(select({}, null).result).toBeNull();
+ const { result, resolve } = select({ agentKind: 'cc', providerId: 'anthropic', model: 'claude-sonnet' }, null);
+ expect(resolve).not.toHaveBeenCalled();
+ expect(result).toEqual({ agentKind: 'claude-code', model: 'claude-sonnet', providerId: 'anthropic' });
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginModelPrefsMigration.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginModelPrefsMigration.test.ts
new file mode 100644
index 0000000000..4da3cc04de
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginModelPrefsMigration.test.ts
@@ -0,0 +1,139 @@
+/**
+ * pluginModelPrefsMigration.test.ts — 旧布局 → 升级后:插件详情「Cindy 能力」的
+ * 逐项钉档(ghost-cindy-prefs.json `overrides`)一次性迁移到插件唯一的「模型」
+ * 字段(ghost-errand-prefs.json `errand`)。真实落盘,不 mock 存储层。
+ */
+
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const owner = vi.hoisted(() => ({ root: '', id: 'owner-a' }));
+
+vi.mock('../../appSessionState.js', () => ({
+ ownerScopedUserDataPath: (...parts: string[]) => path.join(owner.root, owner.id, ...parts),
+ activeOwnerScopeKey: () => owner.id,
+ isAppSessionBoundaryPending: () => false,
+}));
+vi.mock('../../maker-host/logger-adapter.js', () => ({
+ desktopMakerLogger: { child: () => ({ info: vi.fn(), warn: vi.fn() }) },
+}));
+
+const cindy = await import('../cindyPrefsStore.js');
+const task = await import('../pluginTaskPrefsStore.js');
+
+const CINDY_FILE = 'ghost-cindy-prefs.json';
+const TASK_FILE = 'ghost-errand-prefs.json';
+
+function writeJson(file: string, value: unknown): void {
+ const target = path.join(owner.root, owner.id, file);
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, JSON.stringify(value));
+}
+
+function readJson(file: string): unknown {
+ const target = path.join(owner.root, owner.id, file);
+ return fs.existsSync(target) ? JSON.parse(fs.readFileSync(target, 'utf8')) : undefined;
+}
+
+beforeEach(() => {
+ owner.root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-plugin-model-migration-'));
+ owner.id = 'owner-a';
+ cindy.__testing.resetStore();
+ task.__testing.resetLegacyPinMigration();
+});
+
+afterEach(() => {
+ fs.rmSync(owner.root, { recursive: true, force: true });
+});
+
+describe('legacy per-ability pins → plugin model preference', () => {
+ it('migrates catalog pins, drops profile keys and media overrides, keeps other keys', () => {
+ // 旧布局:快问快答目录钉 / 轻量档位键 / 媒体与向量覆盖 / 并发上限 / 未知键。
+ writeJson(CINDY_FILE, {
+ overrides: {
+ writer: { 'text.oneshot': 'cat:openai:codex:gpt-5.5', 'image.generate': 'gpt-image-2' },
+ claude: { 'text.oneshot': 'cat:my%3Arelay:claude-code:claude/sonnet:latest' },
+ profile: { 'text.oneshot': 'codex-gpt-5.4-mini' },
+ broken: { 'text.oneshot': 'cat:broken' },
+ art: { 'image.edit': 'media:xd:gpt-image-2', 'embed.text': 'emb-1' },
+ chosen: { 'text.oneshot': 'cat:xd:codex:gpt-5.5' },
+ },
+ inflightLimits: { writer: 2 },
+ futureKey: { keep: true },
+ });
+ writeJson(TASK_FILE, {
+ errand: {
+ writer: { permissionMode: 'acceptEdits', workingDir: '/project', effort: 'high', fastMode: true },
+ chosen: { agentKind: 'pi', providerId: 'local', model: 'qwen', permissionMode: 'auto' },
+ },
+ sessions: { writer: 'session-1' },
+ });
+
+ expect(task.readPluginTaskConfig('writer')).toEqual({
+ agentKind: 'codex',
+ providerId: 'openai',
+ model: 'gpt-5.5',
+ permissionMode: 'acceptEdits',
+ workingDir: '/project',
+ });
+ expect(task.readPluginTaskConfig('claude')).toEqual({
+ agentKind: 'cc',
+ providerId: 'my:relay',
+ model: 'claude/sonnet:latest',
+ });
+ // 用户已为任务显式选过模型:不覆盖。
+ expect(task.readPluginTaskConfig('chosen')).toEqual({
+ agentKind: 'pi', providerId: 'local', model: 'qwen', permissionMode: 'auto',
+ });
+ // 轻量档位键、解码失败与媒体/向量覆盖直接丢弃 = 跟随系统默认。
+ expect(task.readPluginTaskConfig('profile')).toEqual({});
+ expect(task.readPluginTaskConfig('broken')).toEqual({});
+ expect(task.readPluginTaskConfig('art')).toEqual({});
+ expect(task.readGhostErrandSessionId('writer')).toBe('session-1');
+
+ // 旧文件删掉 overrides,其它键原样保留;旧版本读到缺键 = 无覆盖。
+ expect(readJson(CINDY_FILE)).toEqual({ inflightLimits: { writer: 2 }, futureKey: { keep: true } });
+ expect(cindy.readGhostCindyInflightLimit('writer')).toBe(2);
+ expect(cindy.readLegacyOneshotPins()).toBeNull();
+ });
+
+ it('is idempotent and never re-applies a pin after the user changes the model', () => {
+ writeJson(CINDY_FILE, { overrides: { writer: { 'text.oneshot': 'cat:xd:codex:gpt-5.5' } } });
+ expect(task.readPluginTaskConfig('writer')).toMatchObject({ model: 'gpt-5.5' });
+ // 迁移后旧文件已无内容可留,整份删除。
+ expect(readJson(CINDY_FILE)).toBeUndefined();
+ task.writePluginTaskConfig('writer', null);
+ task.__testing.resetLegacyPinMigration();
+ expect(task.readPluginTaskConfig('writer')).toEqual({});
+ });
+
+ it('runs on first write too, before the written config is computed', () => {
+ writeJson(CINDY_FILE, { overrides: { writer: { 'text.oneshot': 'cat:xd:codex:gpt-5.5' } } });
+ expect(task.writePluginTaskConfig('other', { permissionMode: 'auto' })).toEqual({ permissionMode: 'auto' });
+ expect(readJson(TASK_FILE)).toMatchObject({
+ errand: {
+ writer: { agentKind: 'codex', providerId: 'xd', model: 'gpt-5.5' },
+ other: { permissionMode: 'auto' },
+ },
+ });
+ });
+
+ it('migrates each owner scope separately', () => {
+ writeJson(CINDY_FILE, { overrides: { writer: { 'text.oneshot': 'cat:xd:codex:gpt-5.5' } } });
+ expect(task.readPluginTaskConfig('writer')).toMatchObject({ model: 'gpt-5.5' });
+ owner.id = 'owner-b';
+ writeJson(CINDY_FILE, { overrides: { writer: { 'text.oneshot': 'cat:openai:codex:gpt-5.4' } } });
+ expect(task.readPluginTaskConfig('writer')).toMatchObject({ providerId: 'openai', model: 'gpt-5.4' });
+ });
+
+ it('leaves an unreadable legacy file untouched and reads current config', () => {
+ const target = path.join(owner.root, owner.id, CINDY_FILE);
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, '{not json');
+ writeJson(TASK_FILE, { errand: { writer: { permissionMode: 'auto' } } });
+ expect(task.readPluginTaskConfig('writer')).toEqual({ permissionMode: 'auto' });
+ expect(fs.readFileSync(target, 'utf8')).toBe('{not json');
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/taskSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/taskSlot.test.ts
index 20facc1d4f..7b0a7ba397 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/taskSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/taskSlot.test.ts
@@ -119,3 +119,57 @@ it('accepts bounded plugin-authored scope, never caller-supplied authority', ()
expect(validPluginTaskRequest({...request,plan:{...request.plan,ownerApproved:true}})).toBe(false);
expect(validPluginTaskRequest({...request,plan:{...request.plan,items:[{...item,task:'x'.repeat(8001)}]}})).toBe(false);
});
+
+describe('background tasks (agent.hiddenTasks)', () => {
+ const declared = { enabled: true, taskCapabilityApproved: true, approval: {state:'approved', revision:'r'},
+ manifest: { agent: { tasks: true, hiddenTasks: true } } } as InstalledGhost;
+ const undeclared = { ...declared, manifest: { agent: { tasks: true } } } as InstalledGhost;
+ const create = { type: 'tasks-request', kind: 'create', requestKey: 'one', title: 'Work' };
+
+ it('validates hidden on create and the setHidden operation shape', () => {
+ expect(validPluginTaskRequest({ ...create, hidden: true })).toBe(true);
+ expect(validPluginTaskRequest({ ...create, hidden: false })).toBe(true);
+ expect(validPluginTaskRequest({ ...create, hidden: 'yes' })).toBe(false);
+ expect(validPluginTaskRequest({ type: 'tasks-request', kind: 'setHidden', taskId: 'own', hidden: false })).toBe(true);
+ expect(validPluginTaskRequest({ type: 'tasks-request', kind: 'setHidden', taskId: 'own' })).toBe(false);
+ expect(validPluginTaskRequest({ type: 'tasks-request', kind: 'setHidden', hidden: true })).toBe(false);
+ expect(validPluginTaskRequest({ type: 'tasks-request', kind: 'setHidden', taskId: 'own', hidden: true, sessionId: 'other' })).toBe(false);
+ expect(validPluginTaskRequest({ type: 'tasks-request', kind: 'get', taskId: 'own', hidden: true })).toBe(false);
+ });
+
+ it('denies hidden creation and setHidden without the declaration, before reaching the handler', async () => {
+ const handler = vi.fn(async () => ({ taskId: 't' }));
+ const deps = { getGhost: () => undeclared, handler, isCurrent: () => true };
+ for (const payload of [
+ { ...create, hidden: true },
+ { type: 'tasks-request', kind: 'setHidden', taskId: 't', hidden: true },
+ { type: 'tasks-request', kind: 'setHidden', taskId: 't', hidden: false },
+ ]) {
+ expect(await handlePluginTaskRequest('p', payload, deps)).toMatchObject({ ok: false, error: { code: 'PERMISSION_DENIED' } });
+ }
+ expect(handler).not.toHaveBeenCalled();
+ // hidden:false is the default and remains available to every tasks plugin.
+ expect(await handlePluginTaskRequest('p', { ...create, hidden: false }, deps)).toMatchObject({ ok: true });
+ expect(handler).toHaveBeenCalledTimes(1);
+ });
+
+ it('forwards declared requests and advertises the operation and declaration', async () => {
+ const handler = vi.fn(async () => ({ taskId: 't', hidden: true }));
+ const deps = { getGhost: () => declared, handler, isCurrent: () => true };
+ expect(await handlePluginTaskRequest('p', { type: 'tasks-request', kind: 'setHidden', taskId: 't', hidden: true }, deps))
+ .toEqual({ ok: true, data: { taskId: 't', hidden: true } });
+ const caps = await handlePluginTaskRequest('p', { type: 'tasks-request', kind: 'capabilities' }, deps);
+ expect(caps).toMatchObject({ ok: true, data: { hiddenTasks: true } });
+ expect((caps as { data: { operations: string[] } }).data.operations).toContain('setHidden');
+ const plain = await handlePluginTaskRequest('p', { type: 'tasks-request', kind: 'capabilities' }, { ...deps, getGhost: () => undeclared });
+ expect(plain).toMatchObject({ ok: true, data: { hiddenTasks: false } });
+ });
+
+ it('does not grant hidden tasks from an unpaired historical value', async () => {
+ const handler = vi.fn();
+ const legacy = { ...declared, manifest: { agent: { tasks: true, hiddenTasks: 'yes' } } } as unknown as InstalledGhost;
+ expect(await handlePluginTaskRequest('p', { ...create, hidden: true }, { getGhost: () => legacy, handler, isCurrent: () => true }))
+ .toMatchObject({ ok: false, error: { code: 'PERMISSION_DENIED' } });
+ expect(handler).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/cindyMediaCatalog.ts b/apps/desktop/src/main/cindy-brain/cindyMediaCatalog.ts
index 9ba1574c15..a6689df973 100644
--- a/apps/desktop/src/main/cindy-brain/cindyMediaCatalog.ts
+++ b/apps/desktop/src/main/cindy-brain/cindyMediaCatalog.ts
@@ -71,29 +71,6 @@ export interface CindyMediaCatalogConfig {
defaults: { standard: string; draft: string; best: string } | null;
}
-/**
- * 仅在旧 cindy-request 入口收窄候选;失效默认随清单一起恢复,交给既有偏好
- * 迁移逻辑持久化,不能只在执行时换型号而保留页面上的旧配置。
- */
-export function filterLegacyCindyMediaConfig<T extends CindyMediaCatalogConfig['models'][number]>(
- config: { models: T[]; defaults: CindyMediaCatalogConfig['defaults'] },
- isExecutable: (model: T) => boolean,
-): { models: T[]; defaults: CindyMediaCatalogConfig['defaults'] } {
- const models = config.models.filter(isExecutable);
- if (models.length === 0) return { models, defaults: null };
- const valid = (id: string | undefined) =>
- id !== undefined && models.some((model) => model.id === id) ? id : null;
- const standard = valid(config.defaults?.standard) ?? models[0]!.id;
- return {
- models,
- defaults: {
- standard,
- draft: valid(config.defaults?.draft) ?? standard,
- best: valid(config.defaults?.best) ?? standard,
- },
- };
-}
-
/**
* 向量派单唯一的执行来源。图像已经是多来源(imageChannelRegistry 按 providerId
* 取通道),向量还没有对应的分流层,所以这里必须写死。
diff --git a/apps/desktop/src/main/cindy-brain/cindyOverrideWhitelist.ts b/apps/desktop/src/main/cindy-brain/cindyOverrideWhitelist.ts
deleted file mode 100644
index 0b26cbf832..0000000000
--- a/apps/desktop/src/main/cindy-brain/cindyOverrideWhitelist.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * cindyOverrideWhitelist.ts — ghosts:cindy-prefs:set 的白名单校验(纯函数,零 Electron,可直测)。
- *
- * 按能力键类目分流:image.* / video.* 钉的是媒体目录里的模型 id;text.*(快问
- * 快答)钉的是轻量任务模型链的**档位键**(供应商×模型,见 shared/utilityModelProfiles)。
- * 判据必须与消费方严格同集合——cindySlot 把 override 当 pinnedProfileId 用
- * isUtilityModelProviderKind 复核,这里放行的值链路必须认,否则用户钉档存进去
- * 也是静默回落默认。
- */
-
-import { isUtilityModelProviderKind } from '../../shared/utilityModelProfiles.js';
-
-/** 媒体目录条目(本函数只读 id 与 image 的 supportsEdit)。 */
-export interface CindyOverrideCatalogs {
- image: readonly { id: string; supportsEdit?: boolean }[];
- video: readonly { id: string }[];
- embed: readonly { id: string }[];
- /**
- * text.* 合法目录钉值全集(cat: 编码,由调用侧按当前供应商目录现算);
- * 轻量档位键另行放行(与消费方 pinnedProfileId 同判据)。
- */
- textPinIds: readonly string[];
-}
-
-/**
- * 校验一项覆盖值是否可写入。model 为 null = 清除覆盖(恢复跟随默认),任何
- * 类目都放行;非字符串 / 空串一律拒(IPC 入参是 unknown,这里是最窄防线)。
- */
-export function isCindyOverrideModelAllowed(
- capability: string,
- model: unknown,
- catalogs: CindyOverrideCatalogs,
-): boolean {
- if (model === null) return true;
- if (typeof model !== 'string' || model.length === 0) return false;
- if (capability.startsWith('text.')) {
- return isUtilityModelProviderKind(model) || catalogs.textPinIds.includes(model);
- }
- if (capability.startsWith('video.')) {
- return catalogs.video.some((m) => m.id === model);
- }
- if (capability === 'image.edit') {
- return catalogs.image.some((m) => m.id === model && m.supportsEdit === true);
- }
- if (capability.startsWith('image.')) {
- return catalogs.image.some((m) => m.id === model);
- }
- if (capability.startsWith('embed.')) {
- return catalogs.embed.some((m) => m.id === model);
- }
- return false;
-}
diff --git a/apps/desktop/src/main/cindy-brain/cindyPrefsStore.ts b/apps/desktop/src/main/cindy-brain/cindyPrefsStore.ts
index 0cf7cf1766..a9fdff22e0 100644
--- a/apps/desktop/src/main/cindy-brain/cindyPrefsStore.ts
+++ b/apps/desktop/src/main/cindy-brain/cindyPrefsStore.ts
@@ -1,18 +1,17 @@
/**
- * cindyPrefsStore —— cindy 槽"意识专属后端覆盖"的持久化(解析表第②层)。
+ * cindyPrefsStore —— cindy 槽的用户级隐藏配置(在途并发上限)。
*
* File: <userData>/ghost-cindy-prefs.json
*
- * 形态:{ overrides: { <ghostId>: { "image.generate": "<白名单模型>", … } },
- * inflightLimits: { <ghostId>: <正整数并发上限> } }
- * - 没写 = 跟随默认(出厂 = 自带 proxy 基座;规则 20:override 与默认值
- * 分开记,清除即重新跟随当下默认);
- * - inflightLimits:该意识同时能跑几单 cindy 代办(隐藏配置层级,无
+ * 形态:{ inflightLimits: { <ghostId>: <正整数并发上限> } }
+ * - inflightLimits:该插件同时能跑几单 cindy 代办(隐藏配置层级,无
* Settings UI,直接改文件或让 agent 改);缺项 = 不限并发(系统默认);
- * - 抽离意识**不**清覆盖——与布局位置"重新注入原位复活"同语义,重装回来
- * 钉的后端还在;
- * - 已确认的一对一模型 rename 在读取 normalize 时兼容映射,保留用户显式
- * override;真正失效的值仍由消费方(cindySlot)校验,静默落回默认并留日志。
+ * - 抽离插件**不**清配置——与布局位置"重新注入原位复活"同语义。
+ *
+ * 旧版这里还有 `overrides`(插件详情「Cindy 能力」逐项钉的模型)。2026-10 起
+ * 插件只有一个「模型」字段,存在 pluginTaskPrefsStore;旧 `overrides` 只留给
+ * 一次性迁移读取(见 readLegacyOneshotPins / clearLegacyOverrides),迁移后
+ * 从文件里删掉该键。旧版本回退读到缺键视为无覆盖,不会判损坏。
*/
import { desktopMakerLogger } from '../maker-host/logger-adapter.js';
@@ -22,93 +21,29 @@ import { assertGhostPrefsWritable, relocateGhostPreferenceMaps } from './ghostPr
const log = desktopMakerLogger.child('cindy-prefs-store');
+export const GHOST_CINDY_PREFS_FILE = 'ghost-cindy-prefs.json';
+
export async function relocateGhostCindyPrefs(from: string, to: string): Promise<void> {
- await relocateGhostPreferenceMaps('ghost-cindy-prefs.json', ['overrides', 'inflightLimits'], from, to, () => {
+ // 尚未迁移的旧 overrides 跟着一起搬,迁移时才能落到正确的插件身份上。
+ await relocateGhostPreferenceMaps(GHOST_CINDY_PREFS_FILE, ['overrides', 'inflightLimits'], from, to, () => {
store = createStore();
});
}
-/** cindy 槽能力键(类目.动作;与身份卡详单同一词汇表,当前包含 video)。 */
-// text.oneshot(快问快答)与图像/视频同表:每项覆盖记的都是一组供应商×模型。
-// 文本类的取值是轻量任务模型链的档位键(codex-gpt-5.4-mini 等),不是媒体目录模型 id。
-export const CINDY_CAPABILITY_KEYS = [
- 'image.generate',
- 'image.edit',
- 'video.generate',
- 'video.edit',
- 'text.oneshot',
- // 向量类的取值是 embedding catalog 的 model id(与媒体同为"一组供应商×模型",
- // 不同于 text.oneshot 那种轻量链档位键)。
- 'embed.text',
-] as const;
-export type CindyCapabilityKey = (typeof CINDY_CAPABILITY_KEYS)[number];
-
-/** 覆盖值的取值域来自哪份清单(写入校验按此选白名单)。 */
-export type CindyCapabilityValueDomain = 'image' | 'video' | 'embed' | 'utilityChain';
-
-/**
- * 能力键 → 取值域。
- *
- * 写成**穷举 switch** 而不是前缀 if/else 链:新增能力类目时 TS 会在这里报缺分支,
- * 而不是让它悄悄落进某个兜底分支、被别的类目的白名单拒掉。这个坑已经踩过两次
- * (PR #1707 review):
- * - `embed.*` 落进图像白名单 —— 设置里下拉能选,一选就回滚成一句通用 toast;
- * - `text.oneshot` 同样落在那里,而它的取值是轻量链档位键(codex-gpt-5.4-mini 等),
- * 跟图像目录的 model id 根本不是一个词汇表,所以钉快问快答后端一直是必然失败。
- * 两者都属于"界面看起来正常、一操作就静默回滚"的类型,不写死映射就还会再来一次。
- */
-export function cindyCapabilityValueDomain(
- capability: CindyCapabilityKey,
-): CindyCapabilityValueDomain {
- switch (capability) {
- case 'image.generate':
- case 'image.edit':
- return 'image';
- case 'video.generate':
- case 'video.edit':
- return 'video';
- case 'embed.text':
- return 'embed';
- case 'text.oneshot':
- return 'utilityChain';
- }
-}
-
-export interface GhostCindyPrefs {
- /** ghostId → 能力键 → 白名单模型 id(缺项 = 跟随默认)。 */
- overrides: Record<string, Partial<Record<CindyCapabilityKey, string>>>;
+interface GhostCindyPrefs {
/** ghostId → 在途代办并发上限(正整数;缺项 = 不限并发)。 */
inflightLimits: Record<string, number>;
+ /**
+ * 旧版逐能力钉档里的快问快答钉值(ghostId → 原始字符串),只供一次性迁移;
+ * 其它能力键(图像/视频/向量)不再有消费者,读取时直接忽略。
+ */
+ overrides?: Record<string, { 'text.oneshot'?: string }>;
}
-const DEFAULTS: GhostCindyPrefs = { overrides: {}, inflightLimits: {} };
-
-/** 已确认的一对一图片模型 rename;旧 override 代表明确的用户选择,可无歧义迁移。 */
-const LEGACY_IMAGE_MODEL_ALIASES: Readonly<Record<string, string>> = {
- 'gemini-3-pro-image-preview': 'gemini-3-pro-image',
- 'gemini-3.1-flash-image-preview': 'gemini-3.1-flash-image',
-};
-
-function normalizeModelOverride(capability: CindyCapabilityKey, model: string): string {
- if (capability !== 'image.generate' && capability !== 'image.edit') return model;
- return LEGACY_IMAGE_MODEL_ALIASES[model] ?? model;
-}
+const DEFAULTS: GhostCindyPrefs = { inflightLimits: {} };
function normalize(raw: unknown): GhostCindyPrefs {
- if (!raw || typeof raw !== 'object') return { overrides: {}, inflightLimits: {} };
- const overridesRaw = (raw as { overrides?: unknown }).overrides;
- const overrides: GhostCindyPrefs['overrides'] = {};
- if (overridesRaw && typeof overridesRaw === 'object') {
- for (const [ghostId, capsRaw] of Object.entries(overridesRaw as Record<string, unknown>)) {
- if (!capsRaw || typeof capsRaw !== 'object') continue;
- const caps: Partial<Record<CindyCapabilityKey, string>> = {};
- for (const key of CINDY_CAPABILITY_KEYS) {
- const v = (capsRaw as Record<string, unknown>)[key];
- if (typeof v === 'string' && v.length > 0) caps[key] = normalizeModelOverride(key, v);
- }
- if (Object.keys(caps).length > 0) overrides[ghostId] = caps;
- }
- }
+ if (!raw || typeof raw !== 'object') return { inflightLimits: {} };
// 并发上限:只收正整数,其它形态(0/负数/小数/字符串)一律丢弃 = 回到不限。
const limitsRaw = (raw as { inflightLimits?: unknown }).inflightLimits;
const inflightLimits: GhostCindyPrefs['inflightLimits'] = {};
@@ -117,12 +52,20 @@ function normalize(raw: unknown): GhostCindyPrefs {
if (typeof v === 'number' && Number.isInteger(v) && v >= 1) inflightLimits[ghostId] = v;
}
}
- return { overrides, inflightLimits };
+ const overridesRaw = (raw as { overrides?: unknown }).overrides;
+ if (!overridesRaw || typeof overridesRaw !== 'object') return { inflightLimits };
+ const overrides: NonNullable<GhostCindyPrefs['overrides']> = {};
+ for (const [ghostId, capsRaw] of Object.entries(overridesRaw as Record<string, unknown>)) {
+ if (!capsRaw || typeof capsRaw !== 'object') continue;
+ const pin = (capsRaw as Record<string, unknown>)['text.oneshot'];
+ overrides[ghostId] = typeof pin === 'string' && pin.length > 0 ? { 'text.oneshot': pin } : {};
+ }
+ return { inflightLimits, overrides };
}
function createStore() {
return createOverrideSettingsFile<GhostCindyPrefs>({
- filePath: () => ownerScopedUserDataPath('ghost-cindy-prefs.json'),
+ filePath: () => ownerScopedUserDataPath(GHOST_CINDY_PREFS_FILE),
defaults: DEFAULTS,
normalize,
log,
@@ -133,53 +76,24 @@ function createStore() {
let store = createStore();
-/** 读某意识的全部覆盖(缺省空对象 = 全跟随默认)。 */
-export function readGhostCindyOverrides(ghostId: string): Partial<Record<CindyCapabilityKey, string>> {
- // 本文件是"直接改文件也算配置入口"的隐藏配置(inflightLimits 无 UI),
- // 读前做 mtime 守卫失效:文件没变零开销,手改后下一单即生效。
- store.invalidateIfChanged();
- return store.read().overrides[ghostId] ?? {};
-}
-
-/**
- * 写/清一项覆盖:model 为 null 即清除(恢复跟随默认,规则 20 语义)。
- * 白名单校验由 IPC 层做(存储层不感知模型清单)。
- */
-export function writeGhostCindyOverride(
- ghostId: string,
- capability: CindyCapabilityKey,
- model: string | null,
-): Partial<Record<CindyCapabilityKey, string>> {
- assertGhostPrefsWritable('ghost-cindy-prefs.json');
- // 写前同样失效缓存:避免把用户刚手改的文件内容用旧缓存整体覆写掉。
- store.invalidateIfChanged();
- const overrides = { ...store.read().overrides };
- const caps = { ...(overrides[ghostId] ?? {}) };
- if (model === null) delete caps[capability];
- else caps[capability] = model;
- if (Object.keys(caps).length === 0) delete overrides[ghostId];
- else overrides[ghostId] = caps;
- store.writePatch({ overrides });
- log.info('ghost cindy override written', { ghostId, capability, model });
- return caps;
-}
-
-/** 读某意识的在途并发上限;null = 未配置 = 不限并发。 */
+/** 读某插件的在途并发上限;null = 未配置 = 不限并发。 */
export function readGhostCindyInflightLimit(ghostId: string): number | null {
- // 同上:mtime 守卫现读,手改 ghost-cindy-prefs.json 后下一单即按新上限判。
+ // 本文件是"直接改文件也算配置入口"的隐藏配置(无 UI),读前做 mtime 守卫
+ // 失效:文件没变零开销,手改后下一单即按新上限判。
store.invalidateIfChanged();
return store.read().inflightLimits[ghostId] ?? null;
}
/**
- * 写/清某意识的在途并发上限:limit 为 null 即清除(恢复不限,规则 20 语义)。
+ * 写/清某插件的在途并发上限:limit 为 null 即清除(恢复不限,规则 20 语义)。
* 只收正整数,非法值直接抛(调用方应在入口校验,这里是最后防线)。
*/
export function writeGhostCindyInflightLimit(ghostId: string, limit: number | null): void {
- assertGhostPrefsWritable('ghost-cindy-prefs.json');
+ assertGhostPrefsWritable(GHOST_CINDY_PREFS_FILE);
if (limit !== null && (!Number.isInteger(limit) || limit < 1)) {
throw new Error(`inflight limit 必须是正整数或 null,收到:${String(limit)}`);
}
+ // 写前失效缓存:避免把用户刚手改的文件内容用旧缓存整体覆写掉。
store.invalidateIfChanged();
const inflightLimits = { ...store.read().inflightLimits };
if (limit === null) delete inflightLimits[ghostId];
@@ -188,4 +102,31 @@ export function writeGhostCindyInflightLimit(ghostId: string, limit: number | nu
log.info('ghost cindy inflight limit written', { ghostId, limit });
}
-export const __testing = { normalize };
+/**
+ * 旧布局迁移专用:文件里仍有 `overrides` 键时返回 ghostId → 旧快问快答钉值
+ * (没有钉快问快答的插件值为 null);已迁移 / 从未有过覆盖 / 文件不可读返回 null。
+ */
+export function readLegacyOneshotPins(): Record<string, string | null> | null {
+ store.invalidateIfChanged();
+ const overrides = store.read().overrides;
+ if (!overrides) return null;
+ return Object.fromEntries(
+ Object.entries(overrides).map(([ghostId, caps]) => [ghostId, caps['text.oneshot'] ?? null]),
+ );
+}
+
+/** 迁移完成后删除旧 `overrides` 键(保留其它键;文件随之为空则整份删除)。 */
+export function clearLegacyOverrides(): void {
+ assertGhostPrefsWritable(GHOST_CINDY_PREFS_FILE);
+ store.invalidateIfChanged();
+ if (!store.read().overrides) return;
+ store.writePatch({ overrides: undefined });
+ log.info('legacy ghost cindy overrides removed after migration');
+}
+
+export const __testing = {
+ normalize,
+ resetStore: () => {
+ store = createStore();
+ },
+};
diff --git a/apps/desktop/src/main/cindy-brain/cindySlot.ts b/apps/desktop/src/main/cindy-brain/cindySlot.ts
index 932be2626c..f823ec4980 100644
--- a/apps/desktop/src/main/cindy-brain/cindySlot.ts
+++ b/apps/desktop/src/main/cindy-brain/cindySlot.ts
@@ -82,10 +82,7 @@ import type { CindyProxySearchService } from '../mcp-integrations/cindyProxySear
import { probeImageSize } from './imageProbe.js';
import { isLibraryBlobRelPath, isLibrarySidecarRelPath } from './librarySlot.js';
import { assertLibraryEditImageSource } from './imageChannelRegistry.js';
-import {
- decodeCatalogPin,
- type OneshotRoute,
-} from '../utility-model/textOneshotPinOptions.js';
+import type { OneshotRoute } from '../utility-model/textOneshotPinOptions.js';
import type { AgentKind } from '@cindy/model-providers';
/**
@@ -138,12 +135,6 @@ export interface CindyImageCapabilities {
maxEditImages?: number;
}
-export interface CindyMediaOverrideSelection {
- modelId: string;
- providerId: string;
- label?: string;
-}
-
export interface CindySlotDeps {
getGhost(id: string): InstalledGhost | null;
/** 当前账号作用域;跨 await 的媒体任务必须捕获并持续复核。 */
@@ -211,19 +202,13 @@ export interface CindySlotDeps {
*/
resolveOwnedMedia(ghostId: string, hash: string, ownerScopeKey: string): Promise<string | null>;
/**
- * 意识专属后端覆盖(解析表第②层,用户在意识详情页钉的);无覆盖返回
- * null。capability 为能力键(image.generate / video.edit …);返回值仍过
- * 白名单校验(型号可能已随主机演进下架)。
- */
- getOverride(ghostId: string, capability: string): string | null;
- /**
- * Provider-aware 媒体覆盖。新版 Host 偏好按 providerId + modelId 保存;存在时
- * 必须贯穿能力校验与最终派发,不能降回裸 modelId 后走 first-wins。
+ * 用户在插件详情「模型与任务」里显式选的模型(与插件新建任务共用同一份
+ * 配置,见 pluginTaskPrefsStore);null = 未选 = 跟随默认。只作用于快问快答;
+ * 图像/视频/向量没有逐插件覆盖,始终走目录默认与插件请求里的档位/型号。
*/
- getMediaOverride?(
+ getOneshotModelSelection?(
ghostId: string,
- capability: string,
- ): CindyMediaOverrideSelection | null;
+ ): { providerId?: string; agentKind: AgentKind; model: string } | null;
/**
* 当前图像能力配置——真身是 providers.json 运行时目录(与会话模型列表
* 同一获取来源),每单现读跟随热更。models = 白名单与显示名;defaults =
@@ -318,8 +303,8 @@ export interface CindySlotDeps {
maxTokens?: number;
timeoutMs: number;
/**
- * 本次快问快答的路由(用户钉档或身份卡声明偏好解析出的终态,见
- * utility-model/textOneshotPinOptions);缺省 = 跟随系统默认轻量链。
+ * 本次快问快答的路由(用户在详情页选的模型或身份卡声明偏好解析出的终态,
+ * 见 utility-model/textOneshotPinOptions);缺省 = 跟随系统辅助模型链。
*/
route?: OneshotRoute;
}): Promise<
@@ -852,7 +837,6 @@ export class GhostCindySlot {
};
}
const defaults = cfg.defaults;
- const whitelist = new Set(cfg.models.map((m) => m.id));
let model = defaults.standard;
let providerId: string | undefined;
let providerModelLabel: string | undefined;
@@ -862,23 +846,6 @@ export class GhostCindySlot {
}
model = defaults[p.tier as GhostModelTier];
}
- const capability = `${info.category}.${info.action}`;
- const mediaOverride = this.deps.getMediaOverride?.(ghostId, capability) ?? null;
- if (mediaOverride) {
- model = mediaOverride.modelId;
- providerId = mediaOverride.providerId;
- providerModelLabel = mediaOverride.label;
- } else {
- const override = this.deps.getOverride(ghostId, capability);
- if (override !== null) {
- if (whitelist.has(override)) {
- model = override;
- } else {
- // 钉的型号已随白名单演进下架:落回上面的档位/默认,不让老配置卡死能力。
- this.deps.log?.warn('ghost cindy override no longer whitelisted, ignored', { ghostId, override });
- }
- }
- }
if (p.model !== undefined) {
if (typeof p.model !== 'string') {
return { ok: false, message: 'model 不合法(必须是字符串)' };
@@ -1531,8 +1498,8 @@ export class GhostCindySlot {
/**
* oneshot_text:快问快答(2026-07-31 开闸)。轻量任务模型链直答一次,
* 文字随本次 invoke 递回;不产媒体、不进任何会话。选型不自由:只接受
- * 用户钉档或身份卡声明的偏好(2026-08-05 起,解析权在主机),都没有才走
- * 系统默认链。失败面全部结构化(errorCode 稳定契约,见 shared 类型注释)。
+ * 用户在详情页选的模型或身份卡声明的偏好(解析权在主机),都没有才走
+ * 系统辅助模型链。失败面全部结构化(errorCode 稳定契约,见 shared 类型注释)。
* 在途并发闸与媒体代办共用同一计数与用户上限——它们花的都是用户的额度。
*/
private async handleOneshotText(
@@ -1617,27 +1584,14 @@ export class GhostCindySlot {
const prompt = expectJson
? `${p.prompt}\n\n(只输出 JSON 本体,不要任何解释、前后缀或代码围栏)`
: p.prompt;
- // 选型优先级:用户在详情页的钉档 > 身份卡声明的偏好模型 > 系统默认链。
- // 钉档两形态:轻量档位键(随系统链演进的逻辑档位)与目录钉(cat: 编码的
- // 供应商×agent×模型);声明解析不到(目录没有/已停用/不可路由)按未声明处理。
- const override = this.deps.getOverride(ghostId, 'text.oneshot') ?? undefined;
+ // 选型优先级:用户在详情页选的模型 > 身份卡声明的偏好模型 > 系统辅助模型链。
+ // 用户选的是一组完整的 供应商×agent×模型,钉死不回落(失败如实返回,不悄悄
+ // 换链路烧钱);声明解析不到(目录没有/已停用/不可路由)按未声明处理。
+ // 每单现读,不缓存:系统辅助模型改动后,跟随默认的插件下一单即跟随。
+ const selected = this.deps.getOneshotModelSelection?.(ghostId) ?? null;
let route: OneshotRoute | undefined;
- if (override !== undefined) {
- const catalogPin = decodeCatalogPin(override);
- if (catalogPin) {
- route = { kind: 'catalog', ...catalogPin };
- } else if (override.startsWith('cat:')) {
- // 带目录钉前缀但解码失败(存储损坏/未来格式):目录钉的语义是「钉死
- // 不回落」,静默落到系统默认链会悄悄烧错链路的钱——按无可选通道
- // 收单,引导用户到详情页重新钉档。
- return {
- ok: false,
- message: '快问快答的钉档值无法解析(可能已损坏或来自新版本),请到插件详情页重新钉档',
- errorCode: 'NO_CANDIDATE',
- };
- } else {
- route = { kind: 'utility-profile', profileId: override };
- }
+ if (selected) {
+ route = { kind: 'catalog', ...selected };
} else {
const declaredModel = ghost.manifest.cindy?.oneshotModel;
const resolved = declaredModel ? this.deps.resolveOneshotModel?.(declaredModel) : null;
@@ -1881,8 +1835,6 @@ export class GhostCindySlot {
}
model = cfg.defaults[p.tier as GhostModelTier];
}
- const override = this.deps.getOverride(ghostId, 'embed.text');
- if (override && whitelist.has(override)) model = override;
if (p.model !== undefined) {
if (typeof p.model !== 'string' || !whitelist.has(p.model)) {
return {
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 8df079df2f..549e5ec29e 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -1871,6 +1871,9 @@ Host 能力字段。v2 的 \`slots\` 只用于存量包兼容,新插件不得
要请用户新建一条**自动化**(让插件里的内容定期自己刷新),另写
\`"agent": { "schedule": true }\`(可与前两项并存),见 §4.11.2。它只能打开预填好的
创建面板,任务由用户选好模型后亲手保存才存在;详情页单列一档。
+用普通任务接口(§4.11.3)写 \`"agent": { "tasks": true }\`;需要把自己创建的任务放到后台
+(不进任务列表、搜索与通知)时再加 \`"hiddenTasks": true\`,它必须与 \`"tasks": true\` 同时
+出现,否则拒装;详情页单列一档。
**node 工作进程详单**(声明 node 时必写,详见 §4.12):
@@ -2416,11 +2419,13 @@ const r = await cindy.send({
标题同一条),不拉起 Agent、没有工具、碰不到用户文件、不进任何会话——
要"干活"(读文件、查资料、多步操作)请用派活(§4.11.1);
- 选型仍不在你手里(没有 tier/model 参数),但有两级偏好:**用户可在插件
- 详情页把这项能力钉到他供应商列表里的任意文本模型**(钉死,失败不回落);
- 你也可以在身份卡 \`cindy\` 里声明 \`"oneshotModel": "<目录模型 id>"\` 表达
- 偏好——主机目录解析得到(且用户没停用)就用它,解析不到按未声明处理。
- 优先级:用户钉档 > 你的声明 > 系统默认链。声明只表达意图,别拿它当可用性
- 保证;**更老的宿主会整份拒装含此字段的身份卡**(cindy 详单未知类目硬拒),
+ 详情页「模型与任务」里给这个插件选一个模型**(插件只有这一个模型字段,快问
+ 快答与你新建的任务共用;选了就钉死,失败不回落);你也可以在身份卡
+ \`cindy\` 里声明 \`"oneshotModel": "<目录模型 id>"\` 表达偏好——主机目录解析
+ 得到(且用户没停用)就用它,解析不到按未声明处理。优先级:用户选的模型 >
+ 你的声明 > 系统辅助模型链。出图/视频/向量没有逐插件选模,按 tier 与系统默认走。
+ 声明只表达意图,别拿它当可用性保证;**更老的宿主会整份拒装含此字段的身份卡**
+ (cindy 详单未知类目硬拒),
声明前确认目标用户群的主机版本;
- \`errorCode:'NO_CANDIDATE'\` = 用户当前没有可用的快速通道(未配置或凭证
不可用)。**这是正常失败面**:如实提示用户,不要重试轰炸;
@@ -3868,7 +3873,8 @@ const q = await cindy.agent.queryErrand({ jobId: r.jobId });
主机强制的边界(都不是建议):
- **任务只进普通 user 消息**,绝不进 system prompt;
-- errand 会话在**侧边栏可见**,用户可随时旁观、叫停——没有隐身会话;
+- errand 会话在**侧边栏可见**,用户可随时旁观、叫停——errand 不支持隐藏;普通任务的
+ 后台隐藏只能经 §4.11.3 的 \`hiddenTasks\` 声明,且用户始终能在插件详情页查看与接手;
- 这是旧版任务接口,不是插件全部 AI 能力。普通任务管理用 §4.11.3,继续用户任务用 §4.11,
快问快答用 §4.0.2;不要把这些能力统一称为代办。
- 新建任务共用插件详情「任务设置」中的模型组合(Agent、供应商、模型、推理强度、Fast)。
@@ -3983,13 +3989,13 @@ const r = await cindy.agent.requestSchedule({
插件身份/业务关联在调用方保存,不把普通任务做成另一种产品对象。伙伴的完成回叫只属于伙伴自己的流程。
声明 \`"agent": { "tasks": true }\` 后,逻辑页可使用 \`cindy.tasks\`。它是独立权限,
-旧 \`errand\` 声明不自动取得该权限;用户仍可在侧边栏查看和接手这些任务。
+旧 \`errand\` 声明不自动取得该权限。任务默认可见:出现在任务列表,用户可查看和接手。
安装时已明确展示并确认的任务能力不重复询问;否则首次使用时通过现有宿主权限界面确认并记录独立批准。旧版保存的未知字段不会自动授权。
用户拒绝或确认界面不可用时返回 \`PERMISSION_DENIED\`,不影响插件其它功能;不得自动循环重试确认。
面板通过既有逻辑页通道调用,不获得新的 preload 或内部 IPC 权限。
先调用 \`capabilities()\` 获取实际支持操作。当前仅支持本插件创建的本机普通任务:
-\`models\`、\`create\`、\`get\`、\`setModel\`、\`list\`、\`send\`、\`getRun\`、\`listRuns\`、\`readMessages\`、\`cancel\`。
+\`models\`、\`create\`、\`get\`、\`setModel\`、\`list\`、\`send\`、\`getRun\`、\`listRuns\`、\`readMessages\`、\`cancel\`、\`setHidden\`。
可对自有任务调用 \`startTeam({taskId})\` 启用 Orca 主任务,并用 \`getTeam({taskId})\` 读取实际协同状态。协调主任务需经用户授权 Auto,Worker 自动沿用 Auto。
这些任务及其 Worker 不提供 \`cindy_helper\` 的账号级历史或跨任务控制能力,\`cindy_memory.session_search\` 也拒绝历史检索;协调使用独立 Orca 工具,结果由插件通过 \`readMessages/getTeam\` 读取。旧 errand/workspace 不因来源标记受到限制;明确卸载撤销归属后,调用方已无正在执行的输入或已接受新真人输入时,保留的用户任务恢复普通 helper 与历史检索能力;仍执行旧插件输入时继续受限,自动回报和插件输入重试不构成真人接管。这不恢复插件控制权,也不保证停止已接受执行,不构成通用执行沙箱。
在首次派发前调用 \`setTeamPlan({taskId,plan:{concurrency,task,items}})\`,每项包含
@@ -4008,6 +4014,26 @@ const r = await cindy.agent.requestSchedule({
暂不支持接管任意现有任务、远程/伙伴任务、其它配置修改、归档、队列暂停或事件订阅。
旧 \`agent.errand\` 接口不变。
+**后台任务(可选,需声明 \`hiddenTasks\`)**。任务默认可见。只有身份卡写了
+\`"agent": { "tasks": true, "hiddenTasks": true }\`(详情页与安装/更新确认中单列一项权限),
+插件才能把**自己创建的**任务放到后台:不进任务列表、会话搜索、未结束提示、新任务通知与灵动岛,
+手机任务列表同样不显示。它不改变任务权限、模型或执行方式,也不授予其它任务的访问权。
+未声明时 \`create({hidden:true})\` 与 \`setHidden\` 返回 \`PERMISSION_DENIED\`;
+\`capabilities().hiddenTasks\` 表示当前插件是否已声明。用户始终可以在插件详情页「后台任务」
+看到这些任务、打开查看,或「显示到任务列表」接手;插件被卸载时它们会自动恢复显示。
+请把后台任务用于用户不需要逐条关注的批量/辅助工作,并在插件界面说明它们在哪里能找到。
+
+\`\`\`js
+const caps = await cindy.tasks.capabilities();
+const bg = await cindy.tasks.create({ requestKey: 'grade-42-create', title: '批改第 42 份作答',
+ hidden: caps.hiddenTasks === true }); // 未声明时退回默认的可见任务
+// bg.hidden === true;get/list 快照都带 hidden 布尔值。hidden 参与 requestKey 的幂等摘要。
+await cindy.tasks.send({ taskId: bg.taskId, expectedRevision: bg.revision,
+ requestKey: 'grade-42-send', text: '按评分标准批改并给出分数。' });
+// 出现需要用户处理的问题时,把它显示到任务列表(与用户在详情页点击效果相同):
+await cindy.tasks.setHidden({ taskId: bg.taskId, hidden: false });
+\`\`\`
+
\`\`\`js
// requestWriteAccess({taskId, mode: 'auto'}) 请求宿主原生确认,不能替用户确认。
// 拒绝或失败后,同一账号代际/安装修订/任务在当前宿主进程不再自动弹窗(更换 mode 也不重置)。
@@ -4890,6 +4916,7 @@ Cindy 统一归类、随机选择与排序,同批每个场景和每个插件
- keywords(已废弃字段,旧包兼容保留,新意识别写)有单字词 · kind 写了但不是 "chip"(可省略) · schemaVersion 不是 3 · 缺 minCindyVersion
- cindy 详单格式错(已知类目的动作不是合法标识、空数组或重复动作)
- agent 详单格式错(background / errand / schedule 存在但不是 true;基础点击触发请写 \`agent: {}\`)
+ · \`hiddenTasks\` 不是布尔值,或写了 \`hiddenTasks: true\` 却没有 \`tasks: true\`
- node 详单格式错(entry 不是包内 CommonJS .js/.cjs、protocol 不在 json-rpc-stdio / mcp-stdio、
resident 又写 idleTimeoutSeconds);未知 command/args/shell/env 只保留,不传给进程启动器
- id 用了 \`cindy-\` 前缀(平台保留,正式版用户通道拒装)。\`filo-\` / \`xd-\` 只是普通名称,不授予官方资格
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 6fcad343db..26f0701e7c 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -346,7 +346,6 @@ import { submitAndAwaitVideo } from '../cindy-proxy-media/video/run.js';
import {
deriveCindyMediaConfig,
- filterLegacyCindyMediaConfig,
selectExecutableCoreMediaModels,
type CindyCapabilityKind,
type CindyMediaCatalogConfig,
@@ -532,23 +531,10 @@ import {
formatAuxiliaryModelRefLabel,
getEffectiveAuxiliaryModelChain,
} from '../utility-model/resolveAuxiliaryModelChain.js';
-import { utilityModelPinOptions } from '../../shared/utilityModelProfiles.js';
import { isKnownEmbeddingModel } from '@cindy/embedding-client';
-import {
- buildTextOneshotPinOptions,
- encodeCatalogPin,
- resolveOneshotCatalogModel,
-} from '../utility-model/textOneshotPinOptions.js';
+import { resolveOneshotCatalogModel } from '../utility-model/textOneshotPinOptions.js';
import { hasOneshotProviderCredential } from '../utility-model/oneshotProviderUsability.js';
-import {
- CINDY_CAPABILITY_KEYS,
- readGhostCindyOverrides,
- readGhostCindyInflightLimit,
- writeGhostCindyOverride,
- relocateGhostCindyPrefs,
- type CindyCapabilityKey,
-} from './cindyPrefsStore.js';
-import { isCindyOverrideModelAllowed } from './cindyOverrideWhitelist.js';
+import { readGhostCindyInflightLimit, relocateGhostCindyPrefs } from './cindyPrefsStore.js';
import { createGhostComposerListHandler } from './ghostComposerIpc.js';
import { GHOST_COMPOSER_LIST_CHANNEL } from '../../shared/ghostComposer.js';
import {
@@ -4225,36 +4211,6 @@ function getGhostMediaPreferenceConfig(
};
}
-/** 存量钉定已失效或旧插件无法表达时,一次性升级为当前可用选型。 */
-function resolveAndMigrateGhostMediaPreference(
- ghostId: string,
- capability: GhostMediaCapability,
- config: CindyMediaPreferenceConfig,
- preference: string | undefined,
-): CindyMediaPreferenceModel | null {
- const selected = resolveMediaPreferenceOrDefault(config, preference);
- if (preference && selected && preference !== selected.id) {
- try {
- writeGhostCindyOverride(ghostId, capability, selected.id);
- log.info('migrating stale ghost media preference to available model', {
- ghostId,
- capability,
- previousPreference: preference,
- nextPreference: selected.id,
- });
- } catch (error) {
- log.warn('persisting migrated ghost media preference failed; using runtime fallback', {
- ghostId,
- capability,
- previousPreference: preference,
- fallbackPreference: selected.id,
- error: error instanceof Error ? error.message : String(error),
- });
- }
- }
- return selected;
-}
-
/**
* 插件配置页的模型目录;这里只读目录,不提供任何生成入口。Host 只按 Gateway mode
* 切图片/视频大类并透传 modalities,具体动作支持度由插件自行解释。
@@ -4352,9 +4308,9 @@ async function getGhostConfigurableMediaModels(
}
/**
- * 读取插件在 Host「Cindy 能力」中的现有媒体选型。
- * 已配置模型失效,或旧插件无法表达完整来源时,回落到当前第一个
- * 可用模型,并一次性迁移存量配置,保证页面展示与实际执行一致。
+ * 读取插件当前会用到的媒体选型。插件没有逐项媒体覆盖(2026-10 起详情页只有
+ * 一个「模型」字段,只管快问快答与新建任务),这里始终返回系统默认选型;
+ * 旧插件无法表达完整来源时同样按兼容规则收敛到一个可用来源。
*/
function getGhostConfiguredMediaModel(
ghostId: string,
@@ -4382,13 +4338,7 @@ function getGhostConfiguredMediaModel(
}
const config = getGhostMediaPreferenceConfig(ghostId, mediaCapability);
- const override = readGhostCindyOverrides(ghostId)[mediaCapability];
- const selected = resolveAndMigrateGhostMediaPreference(
- ghostId,
- mediaCapability,
- config,
- override,
- );
+ const selected = resolveMediaPreferenceOrDefault(config, undefined);
if (!selected) {
return {
ok: false,
@@ -4973,6 +4923,39 @@ configureProviderMediaRuntime({
},
});
+/**
+ * 插件详情「模型」字段(与插件新建任务共用 pluginTaskPrefsStore)→ 快问快答的
+ * 供应商×agent×模型。每单现读;未选 = null = 跟随身份卡声明/系统辅助模型链。
+ */
+function getPluginOneshotModelSelection(
+ ghostId: string,
+): { providerId?: string; agentKind: AgentKind; model: string } | null {
+ const config = readPluginTaskConfig(ghostId);
+ if (!config.model) return null;
+ if (!config.agentKind || config.agentKind === 'pi') {
+ // 两种情况按目录解析一条快问快答可路由的 供应商×agent×模型:
+ // - 手改文件只写了 model;
+ // - 用户给插件选的是 Pi 路线(快问快答只有 codex / claude-code 通道):同一
+ // 供应商×模型换成可用通道执行。
+ // 用户显式选了供应商时钉死该供应商:解析结果落到别家(该供应商不可用/无通道)
+ // 一律不采用,绝不换另一家同名模型执行计费。解析不到或不一致都按用户显式选择
+ // 原样返回(执行侧推断不出即如实失败),不悄悄换回系统链。
+ const resolved = resolveOneshotCatalogModel(
+ getActiveCatalog(),
+ readModelDisableOverrides(),
+ config.model,
+ config.providerId ? [config.providerId, ...readProviderOrder()] : readProviderOrder(),
+ hasOneshotProviderCredential,
+ );
+ if (resolved && (!config.providerId || resolved.providerId === config.providerId)) return resolved;
+ }
+ return {
+ agentKind: config.agentKind === 'cc' ? 'claude-code' : (config.agentKind ?? 'codex'),
+ model: config.model,
+ ...(config.providerId ? { providerId: config.providerId } : {}),
+ };
+}
+
/**
* Plugin media and storage use the same process-local AppSession owner
* boundary as the rest of the owner-scoped runtime.
@@ -5054,38 +5037,9 @@ export function getGhostCindySlot(): GhostCindySlot {
// 画面参数按型号二次校验的数据源(registry capabilities)。
imageCapabilities: getGhostImageCapabilities,
videoCapabilities: getGhostVideoCapabilities,
- getMediaOverride: (ghostId, capability) => {
- const value = readGhostCindyOverrides(ghostId)[capability as CindyCapabilityKey] ?? null;
- if (!value) return null;
- const mediaCapability = capability as GhostMediaCapability;
- const config = getGhostMediaPreferenceConfig(ghostId, mediaCapability);
- const videoRegistry = capability.startsWith('video.') ? getVideoProviderRegistry() : null;
- // Core 专用选型不能交给旧执行器。复用存量配置迁移,确保回退后
- // 用户保存的 provider + modelId 与实际执行一致,不影响 Core 清单。
- const executableConfig = filterLegacyCindyMediaConfig(
- config,
- (model) => capability.startsWith('video.')
- ? videoRegistry?.hasAlias(model.modelId, model.providerId) ?? false
- : getImageChannelRegistry().isProviderLegacyReady(model.providerId, model.modelId),
- );
- const selected = resolveAndMigrateGhostMediaPreference(
- ghostId,
- mediaCapability,
- executableConfig,
- value,
- );
- return selected
- ? {
- providerId: selected.providerId,
- modelId: selected.modelId,
- label: selected.label,
- }
- : null;
- },
- getOverride: (ghostId, capability) => {
- const value = readGhostCindyOverrides(ghostId)[capability as CindyCapabilityKey] ?? null;
- return value && !decodeMediaPreference(value) ? value : null;
- },
+ // 插件详情「模型」字段(与插件新建任务共用 pluginTaskPrefsStore);每单现读,
+ // 未选 = null = 跟随身份卡声明/系统辅助模型链,辅助模型改动后自动跟随。
+ getOneshotModelSelection: getPluginOneshotModelSelection,
getImageConfig: getCatalogImageConfig,
getVideoConfig: getCatalogVideoConfig,
getEmbedConfig: getCatalogEmbedConfig,
@@ -5155,11 +5109,14 @@ export function getGhostCindySlot(): GhostCindySlot {
const r = await requestUtilityText(getMaker(), prompt, {
maxTokens,
timeoutMs,
- // 路由两形态:轻量档位键走链档钉(不认的值下游忽略回默认链);
- // 目录钉走显式供应商路径(钉死,不回落)。
- ...(route?.kind === 'utility-profile' ? { pinnedProfileId: route.profileId } : {}),
- ...(route?.kind === 'catalog'
- ? { providerId: route.providerId, agentKind: route.agentKind, model: route.model }
+ // 用户选的模型 / 身份卡声明走显式供应商路径(钉死,不回落);
+ // 缺省 route = 系统辅助模型链。
+ ...(route
+ ? {
+ ...(route.providerId ? { providerId: route.providerId } : {}),
+ agentKind: route.agentKind,
+ model: route.model,
+ }
: {}),
});
if (r.ok) {
@@ -8915,97 +8872,6 @@ export function registerGhostIpc(): void {
return resolved;
});
- // ── cindy 槽后端覆盖(解析表第②层;意识详情页「Cindy 能力」区)──
- // 读走 sendSync:详情页首帧要和其它信息同帧渲染(规则 7 无跳变),
- // 文件读取极小。写走 invoke,白名单在此校验(存储层不感知模型清单)。
- ipcMain.on('ghosts:cindy-prefs', (event, ghostId: unknown) => {
- const storedOverrides = typeof ghostId === 'string' ? readGhostCindyOverrides(ghostId) : {};
- const overrides = { ...storedOverrides };
- for (const capability of GHOST_MEDIA_CAPABILITIES) {
- const value = storedOverrides[capability];
- if (!value) continue;
- const selected = resolveAndMigrateGhostMediaPreference(
- ghostId as string,
- capability,
- getGhostMediaPreferenceConfig(ghostId as string, capability),
- value,
- );
- if (selected) overrides[capability] = selected.id;
- else delete overrides[capability];
- }
- // 每类目一份 options + defaultModel(当前包含 image/video 两类;下拉按
- // 能力键的类目取对应清单)。defaultModel:目录默认选型的展示信息
- // ("默认(GPT Image 2)"),让用户看得见"跟随"当下跟的是谁;
- // null = 目录没有该类目的模型(能力暂不可用),渲染层据此显示灰字而非下拉。
- const byKind = (cfg: CindyMediaCatalogConfig | CindyMediaPreferenceConfig) => {
- const standard = cfg.defaults?.standard;
- return {
- options: cfg.models,
- defaultModel:
- standard === undefined ? null : (cfg.models.find((m) => m.id === standard) ?? null),
- };
- };
- // 文本类(快问快答)的可选项 = 当前供应商目录里的全部文本模型(2026-08-05
- // 与刘佳黎定稿:安装插件即承担其成本,主机如实展示可选面)。每一项精确钉
- // 一组 供应商×agent×模型(cat: 编码)。defaultModel = 当前辅助模型链链首,
- // declaredModel = 身份卡声明的偏好(解析得到才给)——让"跟随默认"
- // 行如实说出当前实际跟的是谁。
- const textChain = getEffectiveAuxiliaryModelChain();
- const textDefaultId = textChain.refs[0] ?? null;
- const textDefaultLabel =
- textDefaultId === null ? null : formatAuxiliaryModelRefLabel(textDefaultId);
- const textOptions = buildTextOneshotPinOptions(
- getActiveCatalog(),
- readModelDisableOverrides(),
- readProviderOrder(),
- hasOneshotProviderCredential,
- );
- // 纯展示口径,不走 findAvailableGhost 的"当前会话可用"闸:插件被当前项目
- // 停用时卡片的其余部分(overrides/options)照常渲染,声明偏好也不该凭空消失。
- const declaredRaw = typeof ghostId === 'string'
- ? (findInstalledGhostByInstanceId(getGhostManager().list(), ghostId) ??
- getGhostManager().list().find((g) => g.manifest.id === ghostId))?.manifest.cindy?.oneshotModel
- : undefined;
- const declaredResolved = declaredRaw
- ? resolveOneshotCatalogModel(
- getActiveCatalog(),
- readModelDisableOverrides(),
- declaredRaw,
- readProviderOrder(),
- hasOneshotProviderCredential,
- )
- : null;
- event.returnValue = {
- overrides,
- image: byKind(getGhostMediaPreferenceConfig(ghostId as string, 'image.generate')),
- imageEdit: byKind(getGhostMediaPreferenceConfig(ghostId as string, 'image.edit')),
- video: byKind(getGhostMediaPreferenceConfig(ghostId as string, 'video.generate')),
- videoEdit: byKind(getGhostMediaPreferenceConfig(ghostId as string, 'video.edit')),
- text: {
- options: textOptions,
- defaultModel:
- textDefaultId === null || textDefaultLabel === null
- ? null
- : { id: textDefaultId, label: textDefaultLabel },
- declaredModel:
- declaredResolved && declaredRaw
- ? {
- id: encodeCatalogPin(
- declaredResolved.providerId,
- declaredResolved.agentKind,
- declaredResolved.model,
- ),
- label: declaredRaw,
- }
- : null,
- // 存量轻量档位钉(目录扩展前钉下的合法值)的展示名表:渲染层据此给
- // 老钉值回显友好名,而不是把合法档位钉当 stale 原样露出 id。
- utilityProfiles: utilityModelPinOptions(),
- },
- // 向量类与图像/视频同源(都走目录派生),不同于文本类的轻量链档位。
- embed: byKind(getCatalogEmbedConfig()),
- };
- });
// ── 目录级禁用(ghostWorkdirPrefs;插件页的项目范围视图)──
// 读走 sendSync:切换范围时禁用清单要与卡片同帧渲染(规则 7 无跳变),
// 文件读取极小且带 mtime 缓存。写走 invoke;写后广播 ghosts:changed
@@ -9044,64 +8910,16 @@ export function registerGhostIpc(): void {
},
);
- ipcMain.handle(
- 'ghosts:cindy-prefs:set',
- (_event, ghostId: unknown, capability: unknown, model: unknown) => {
- if (typeof ghostId !== 'string' || ghostId.trim().length === 0) {
- throwIpcError('INVALID_PARAMS', 'ghostId must be a non-empty string');
- }
- if (!(CINDY_CAPABILITY_KEYS as readonly string[]).includes(capability as string)) {
- throwIpcError('INVALID_PARAMS', `unknown capability: ${String(capability)}`);
- }
- // 白名单按能力键类目分流:image.*/video.*/embed.* 钉各媒体目录模型 id;
- // text.*(快问快答)钉轻量档位键或目录钉(cat: 编码)——与消费方(cindySlot
- // route)同一判据,否则存进去的值链路不认。刻意不查凭证态(与清单的凭证
- // 过滤不同):凭证是瞬态(可以后补/会过期),钉档是持久意图;执行侧
- // fail-closed 兜底,不在这层把「暂时没配 key」当成非法值。
- if (
- !isCindyOverrideModelAllowed(capability as string, model, {
- image: getGhostMediaPreferenceConfig(
- ghostId,
- capability === 'image.edit' ? 'image.edit' : 'image.generate',
- ).models,
- video: getGhostMediaPreferenceConfig(
- ghostId,
- capability === 'video.edit' ? 'video.edit' : 'video.generate',
- ).models,
- embed: getCatalogEmbedConfig().models,
- textPinIds: buildTextOneshotPinOptions(
- getActiveCatalog(),
- readModelDisableOverrides(),
- ).map((o) => o.id),
- })
- ) {
- throwIpcError(
- 'INVALID_PARAMS',
- 'model must be null or an allowed model of the capability category',
- );
- }
- const ghost = findGhostForInstanceId(ghostId);
- if (!ghost) throwIpcError('NOT_FOUND', '插件实例已变化,请刷新后重试');
- const storedId = installedGhostStoragePart(ghost);
- const overrides = writeGhostCindyOverride(
- storedId,
- capability as CindyCapabilityKey,
- model as string | null,
- );
- getGhostSetupChangeBus().emit(storedId, {
- source: 'host_config',
- ref: `cindy-pref:${String(capability)}`,
- });
- return { overrides };
- },
- );
-
// Plugin task preferences: ordinary tasks and the legacy errand adapter share
// this configuration. Keep existing IPC names for renderer compatibility.
// Save validates the current route; creation/execution revalidate independently.
+ // The same model fields also drive the plugin's quick answers (cindy.text.oneshot);
+ // auxiliaryModelLabel names the system auxiliary model the "follow default" row uses.
ipcMain.on('ghosts:errand-prefs', (event, ghostId: unknown) => {
+ const auxiliaryRef = getEffectiveAuxiliaryModelChain().refs[0] ?? null;
event.returnValue = {
config: typeof ghostId === 'string' ? readPluginTaskConfig(ghostId) : {},
+ auxiliaryModelLabel: auxiliaryRef === null ? null : formatAuxiliaryModelRefLabel(auxiliaryRef),
};
});
ipcMain.handle('ghosts:errand-prefs:set', async (event, ghostId: unknown, config: unknown) => {
diff --git a/apps/desktop/src/main/cindy-brain/pluginTaskPrefsStore.ts b/apps/desktop/src/main/cindy-brain/pluginTaskPrefsStore.ts
index 64cc69d9a1..36dc68b45c 100644
--- a/apps/desktop/src/main/cindy-brain/pluginTaskPrefsStore.ts
+++ b/apps/desktop/src/main/cindy-brain/pluginTaskPrefsStore.ts
@@ -7,6 +7,10 @@
* New ordinary tasks use ask; the legacy adapter retains its historical default.
* Permissions stay independently user-owned, never caller-inherited.
* Model admission belongs to the shared ordinary-session resolver, never this store.
+ * The same model fields are the plugin's single "model" preference: Cindy quick
+ * answers (cindy.text.oneshot) use them too; empty = the system auxiliary model.
+ * Legacy per-ability oneshot catalog pins (ghost-cindy-prefs.json `overrides`)
+ * are migrated here once on first read; see migrateLegacyOneshotPins.
*/
import {
@@ -16,7 +20,13 @@ import {
import { desktopMakerLogger } from '../maker-host/logger-adapter.js';
import { createOverrideSettingsFile } from '../maker-host/override-settings-file.js';
import { ownerScopedUserDataPath } from '../appSessionState.js';
+import { decodeCatalogModelPin } from '../../shared/catalogModelPin.js';
import { assertGhostPrefsWritable, relocateGhostPreferenceMaps } from './ghostPreferenceRelocation.js';
+import {
+ GHOST_CINDY_PREFS_FILE,
+ clearLegacyOverrides,
+ readLegacyOneshotPins,
+} from './cindyPrefsStore.js';
/** User-owned plugin task permission policy. A model source never grants authority. */
export function clampPluginTaskPermissionMode(value: unknown, fallback: GhostErrandPermissionMode = 'ask'): GhostErrandPermissionMode {
@@ -159,8 +169,85 @@ export async function validatePluginTaskConfig(raw: unknown): Promise<void> {
await validateSelection(config);
}
+/** 已完成旧钉档迁移的 owner 作用域(按旧文件的 owner 路径区分账号)。 */
+const legacyPinMigrationDone = new Set<string>();
+
+/**
+ * 一次性迁移(幂等):旧插件详情「Cindy 能力」里快问快答的目录钉(cat: 编码的
+ * 供应商×agent×模型)→ 本插件的「模型」字段。规则:
+ * - 只在该插件的任务配置还没有 model 时写入 agentKind/providerId/model;effort 与
+ * fastMode 留空,由现有解析按模型默认补;权限、目录等其它字段原样保留;
+ * - 已有 model(用户已显式选过)、轻量档位键(非 cat:)、解码失败的值,以及图像/
+ * 视频/向量覆盖一律丢弃(它们从此跟随系统默认);
+ * - 先写新配置、再删旧文件的 `overrides` 键:中途失败下一次读取重跑,已写入的
+ * 插件因已有 model 被跳过,不会重复或覆盖。
+ */
+function migrateLegacyOneshotPins(): void {
+ let scope: string;
+ try {
+ scope = ownerScopedUserDataPath(GHOST_CINDY_PREFS_FILE);
+ } catch {
+ return;
+ }
+ if (legacyPinMigrationDone.has(scope)) return;
+ try {
+ const legacy = readLegacyOneshotPins();
+ if (legacy) {
+ assertGhostPrefsWritable('ghost-errand-prefs.json');
+ store.invalidateIfChanged();
+ const errand = { ...store.read().errand };
+ const migrated: string[] = [];
+ const kept: string[] = [];
+ const dropped: string[] = [];
+ for (const [ghostId, pin] of Object.entries(legacy)) {
+ if (pin === null) continue;
+ const route = decodeCatalogModelPin(pin);
+ if (!route) {
+ dropped.push(ghostId);
+ continue;
+ }
+ const current = errand[ghostId] ?? {};
+ if (current.model !== undefined) {
+ kept.push(ghostId);
+ continue;
+ }
+ const rest: PluginTaskConfig = { ...current };
+ delete rest.effort;
+ delete rest.fastMode;
+ const next = normalizeConfig({
+ ...rest,
+ agentKind: route.agentKind === 'claude-code' ? 'cc' : 'codex',
+ providerId: route.providerId,
+ model: route.model,
+ });
+ if (next.model === undefined || next.providerId === undefined) {
+ dropped.push(ghostId);
+ continue;
+ }
+ errand[ghostId] = next;
+ migrated.push(ghostId);
+ }
+ if (migrated.length > 0) store.writePatch({ errand });
+ clearLegacyOverrides();
+ log.info('legacy plugin oneshot pins migrated to plugin model preference', {
+ source: GHOST_CINDY_PREFS_FILE,
+ migrated,
+ keptExistingModel: kept,
+ droppedUnsupportedPins: dropped,
+ });
+ }
+ legacyPinMigrationDone.add(scope);
+ } catch (error) {
+ // 迁移失败(偏好正在搬迁/文件暂不可写)不影响读取:本次按现有配置返回,下次重试。
+ log.warn('legacy plugin oneshot pin migration failed; will retry', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+}
+
/** 读某插件的任务配置(缺省空对象 = 全跟随默认)。 */
export function readPluginTaskConfig(ghostId: string): PluginTaskConfig {
+ migrateLegacyOneshotPins();
// mtime 守卫现读:直接改文件也算配置入口(与 cindy prefs 同契约)。
store.invalidateIfChanged();
return store.read().errand[ghostId] ?? {};
@@ -173,6 +260,7 @@ export function readPluginTaskConfig(ghostId: string): PluginTaskConfig {
*/
export function writePluginTaskConfig(ghostId: string, config: unknown): PluginTaskConfig {
assertGhostPrefsWritable('ghost-errand-prefs.json');
+ migrateLegacyOneshotPins();
store.invalidateIfChanged();
const errand = { ...store.read().errand };
const cfg = config === null ? {} : normalizeConfig(config);
@@ -205,4 +293,9 @@ export function writeGhostErrandSessionId(
log.info('ghost errand session mapping written', { ghostId, sessionKey: sessionKey ?? null, sessionId });
}
-export const __testing = { normalize, normalizeConfig, sessionMapKey };
+export const __testing = {
+ normalize,
+ normalizeConfig,
+ sessionMapKey,
+ resetLegacyPinMigration: () => legacyPinMigrationDone.clear(),
+};
diff --git a/apps/desktop/src/main/cindy-brain/taskSlot.ts b/apps/desktop/src/main/cindy-brain/taskSlot.ts
index ac6afe98b9..3f617b69e0 100644
--- a/apps/desktop/src/main/cindy-brain/taskSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/taskSlot.ts
@@ -1,4 +1,4 @@
-import type { InstalledGhost } from '../../shared/ghost.js';
+import { ghostDeclaresHiddenTasks, type InstalledGhost } from '../../shared/ghost.js';
import type { PluginTaskRequest, PluginTaskResult } from '../../shared/pluginTasks.js';
import { isPluginTeamPlanWithinBudget } from '../../shared/pluginTasks.js';
import { hasPluginTaskApproval } from './taskCapability.js';
@@ -20,6 +20,7 @@ export const PLUGIN_TASK_OPERATIONS = [
'listRuns',
'cancel',
'readMessages',
+ 'setHidden',
] as const;
export type PluginTaskHandler = (pluginId: string, request: PluginTaskRequest) => Promise<unknown>;
const object = (v: unknown): v is Record<string, unknown> =>
@@ -32,7 +33,7 @@ export function validPluginTaskRequest(value: unknown): value is PluginTaskReque
capabilities: [],
models: [],
setModel: ['taskId', 'expectedRevision', 'route'],
- create: ['requestKey', 'title', 'route', 'isolatedWorkspace', 'callId'],
+ create: ['requestKey', 'title', 'route', 'isolatedWorkspace', 'callId', 'hidden'],
list: ['after', 'limit'],
get: ['taskId'],
requestWriteAccess: ['taskId', 'mode'],
@@ -45,6 +46,7 @@ export function validPluginTaskRequest(value: unknown): value is PluginTaskReque
listRuns: ['taskId', 'after', 'limit'],
readMessages: ['taskId', 'after', 'limit'],
cancel: ['runId', 'requestKey'],
+ setHidden: ['taskId', 'hidden'],
};
if (typeof value.kind !== 'string' || !Object.hasOwn(allowed, value.kind)) return false;
const kind = value.kind;
@@ -54,8 +56,10 @@ export function validPluginTaskRequest(value: unknown): value is PluginTaskReque
if (kind === 'requestWriteAccess' && value.mode !== undefined && !['acceptEdits', 'auto'].includes(String(value.mode))) return false;
const requires = (key: string) => text(value[key], 128);
if (['create', 'send', 'cancel'].includes(value.kind) && !requires('requestKey')) return false;
- if (['get', 'setModel', 'send', 'listRuns', 'readMessages', 'requestWriteAccess', 'startTeam', 'getTeam', 'setTeamPlan', 'releaseWorker'].includes(value.kind) && !requires('taskId'))
+ if (['get', 'setModel', 'send', 'listRuns', 'readMessages', 'requestWriteAccess', 'startTeam', 'getTeam', 'setTeamPlan', 'releaseWorker', 'setHidden'].includes(value.kind) && !requires('taskId'))
return false;
+ if (kind === 'setHidden' && typeof value.hidden !== 'boolean') return false;
+ if (value.hidden !== undefined && typeof value.hidden !== 'boolean') return false;
if (['getRun', 'cancel'].includes(value.kind) && !requires('runId')) return false;
if (kind === 'setModel' && (!object(value.route) || !Number.isSafeInteger(value.expectedRevision) || (value.expectedRevision as number) < 0)) return false;
if (value.callId !== undefined && !text(value.callId, 128)) return false;
@@ -135,6 +139,11 @@ export async function handlePluginTaskRequest(
try { await deps.ensureAuthorized(); } catch { /* No UI or persistence failure grants nothing. */ }
}
if (!permitted()) return error('PERMISSION_DENIED', 'Plugin task capability is unavailable');
+ // Background tasks need their own manifest declaration (agent.hiddenTasks with tasks);
+ // hidden:false on create is the default and stays available to every tasks plugin.
+ const declaresHiddenTasks = () => ghostDeclaresHiddenTasks(deps.getGhost(pluginId)?.manifest);
+ if (((value.kind === 'create' && value.hidden === true) || value.kind === 'setHidden') && !declaresHiddenTasks())
+ return error('PERMISSION_DENIED', 'Background tasks require agent.hiddenTasks in ghost.json');
if (value.kind === 'capabilities')
return {
ok: true,
@@ -146,6 +155,7 @@ export async function handlePluginTaskRequest(
maxPageSize: 100,
exactRoute: true,
sourceCallContext: true,
+ hiddenTasks: declaresHiddenTasks(),
},
};
if (!deps.handler) return error('HOST_NOT_READY', 'Task service is not ready', true);
diff --git a/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts b/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts
index c858e9092b..41af413a0d 100644
--- a/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts
+++ b/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts
@@ -1,6 +1,17 @@
import { DL_HISTORY_QUERY_CHANNEL } from '@cindy/device-link';
-export type RemoteBotSessionAccess = 'ordinary' | 'visible' | 'hidden' | 'missing';
+/**
+ * - ordinary / visible:正常可见;hidden:伙伴隐藏,任何远端读写都按不存在处理;
+ * - background:插件后台隐藏任务,只从列表类结果(任务列表、运行中列表)中排除,单任务读取
+ * 与操作照常,手机插件页可深链打开(未结束提示只回 id,已在源查询排除);missing:不存在。
+ */
+export type RemoteBotSessionAccess = 'ordinary' | 'visible' | 'hidden' | 'background' | 'missing';
+
+/** 列表类 channel:插件后台隐藏任务不出现在这些结果里(与本机任务列表同口径)。 */
+const BACKGROUND_EXCLUDED_LIST_CHANNELS = new Set([
+ 'local-db:sessions:list',
+ 'maker:list-active',
+]);
type Lookup = (sessionId: string, kind?: 'session' | 'bot') => Promise<RemoteBotSessionAccess>;
export type RemoteBotSessionBatchLookup = (ids: readonly string[], kind: 'session' | 'bot') => Promise<ReadonlyMap<string, RemoteBotSessionAccess>>;
let lookup: Lookup | null = null;
@@ -127,7 +138,7 @@ export async function projectRemoteSessionResult(channel: string, value: unknown
for (const id of ids) access.set(id, await lookup(id, 'session'));
}
const visible = (id: unknown) => typeof id === 'string'
- && (access.get(id) === 'ordinary' || access.get(id) === 'visible');
+ && (access.get(id) === 'ordinary' || access.get(id) === 'visible' || access.get(id) === 'background');
// The page and its foreign references share one fresh, source-owned lookup.
// Missing or hidden page members invalidate pagination; optional parents
// are simply omitted, including on cached/queued delivery after a hide.
@@ -161,6 +172,9 @@ export async function projectRemoteSessionResult(channel: string, value: unknown
}
const activeLookup = lookup;
const activeBatchLookup = batchLookup;
+ const excludeBackground = BACKGROUND_EXCLUDED_LIST_CHANNELS.has(channel);
+ const excluded = (access: RemoteBotSessionAccess) =>
+ access === 'hidden' || (excludeBackground && access === 'background');
const identity = (item: unknown) => {
const row = record(item);
const ref = record(row?.ref);
@@ -172,7 +186,7 @@ export async function projectRemoteSessionResult(channel: string, value: unknown
const project = async (item: unknown) => {
const key = identity(item);
if (!key) return item;
- return await activeLookup(key.id, key.kind) === 'hidden' ? null : item;
+ return excluded(await activeLookup(key.id, key.kind)) ? null : item;
};
if (Array.isArray(value)) {
const identities = value.map(identity);
@@ -191,7 +205,7 @@ export async function projectRemoteSessionResult(channel: string, value: unknown
}
return value.filter((item, index) => {
const key = identities[index];
- return item !== null && (!key || (accessByKind.get(key.kind)?.get(key.id) ?? 'hidden') !== 'hidden');
+ return item !== null && (!key || !excluded(accessByKind.get(key.kind)?.get(key.id) ?? 'hidden'));
});
}
const row = record(value);
diff --git a/apps/desktop/src/main/hook-control/recentSessions.ts b/apps/desktop/src/main/hook-control/recentSessions.ts
index 5be5d61b56..d092755c44 100644
--- a/apps/desktop/src/main/hook-control/recentSessions.ts
+++ b/apps/desktop/src/main/hook-control/recentSessions.ts
@@ -77,6 +77,8 @@ export async function listRecentHookSessions(
isNull(sessions.remoteHostId),
or(isNull(sessions.orcaRole), ne(sessions.orcaRole, 'worker')),
inArray(sessions.source, DESKTOP_TASK_LIST_SESSION_SOURCES),
+ // 插件后台隐藏任务不出现在最近任务中。
+ isNull(sessions.hiddenAt),
),
)
.orderBy(desc(sql`COALESCE(${sessions.userSendAt}, ${sessions.updatedAt})`))
diff --git a/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts b/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts
index b76badce38..4772dad8ef 100644
--- a/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts
@@ -102,6 +102,7 @@ function createSearchDb(): Database.Database {
plan_mode_enabled INTEGER NOT NULL DEFAULT 0,
cleared_at INTEGER,
pinned_at INTEGER,
+ hidden_at INTEGER,
summary TEXT,
provider_id TEXT,
user_send_at INTEGER,
@@ -220,3 +221,28 @@ describe('conversationSearch recent activity SQL filtering', () => {
}
});
});
+
+describe('conversationSearch plugin background tasks', () => {
+ it('excludes hidden tasks from title and content candidates', async () => {
+ const db = createSearchDb();
+ const client = makeSearchDbClient(db);
+ setCurrentDbClient(client, 'test-user');
+ mocks.searchChatHistoryHybrid.mockResolvedValue({
+ hits: [], sessions: {}, vectorUsed: false, vectorSkipReason: null,
+ nextOffset: null, hasMore: false, poolSize: 0, poolCapped: false,
+ });
+ try {
+ insertSearchSession(db, 'shown', 10, null);
+ insertSearchSession(db, 'background', 20, null);
+ db.prepare('UPDATE sessions SET hidden_at = 5 WHERE id = ?').run('background');
+ const response = await searchConversations({ query: 'needle', semanticMode: 'keyword' });
+ expect(response.results.map((result) => result.session.id)).toEqual(['shown']);
+ expect(mocks.searchChatHistoryHybrid).toHaveBeenCalledWith(
+ expect.objectContaining({ sessionIds: ['shown'] }),
+ );
+ } finally {
+ clearCurrentDbClient(client);
+ db.close();
+ }
+ });
+});
diff --git a/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts b/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts
index 1f6f44ac9f..4c288471a4 100644
--- a/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts
@@ -106,10 +106,11 @@ describeMigrationReplay('migration replay', () => {
it.each(['missing', 'legacy', 'partial'])('replays remote report persistence with %s Worker schema', (shape) => {
const { db, cleanup } = createTempDb();
try {
- db.exec("CREATE TABLE migration_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); CREATE TABLE migration_history (seq INTEGER PRIMARY KEY, file_name TEXT NOT NULL, content_hash TEXT NOT NULL, applied_at INTEGER NOT NULL)");
+ // Later migrations (0126 sessions.hidden_at) need the sessions table this fixture predates.
+ db.exec("CREATE TABLE migration_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); CREATE TABLE migration_history (seq INTEGER PRIMARY KEY, file_name TEXT NOT NULL, content_hash TEXT NOT NULL, applied_at INTEGER NOT NULL); CREATE TABLE sessions (id TEXT PRIMARY KEY)");
if (shape !== 'missing') db.exec(`CREATE TABLE orca_workers (id TEXT PRIMARY KEY${shape === 'partial' ? ', pending_remote_report TEXT' : ''}); INSERT INTO orca_workers (id) VALUES ('worker-1');`);
const result = runMigrationReplay(db, { drizzleDir: drizzleDir(), currentVersion: 124 });
- expect(result.applied.map((migration) => migration.seq)).toEqual([125]);
+ expect(result.applied.map((migration) => migration.seq)[0]).toBe(125);
expect(tableExists(db, 'orca_remote_opens')).toBe(true);
if (shape !== 'missing') {
expect(columnNames(db, 'orca_workers')).toEqual(expect.arrayContaining(['pending_remote_report', 'remote_stop_confirmed_at']));
@@ -117,6 +118,22 @@ describeMigrationReplay('migration replay', () => {
}
} finally { cleanup(); }
});
+ it('adds nullable sessions.hidden_at to a populated database without touching existing tasks', () => {
+ const { db, cleanup } = createTempDb();
+ try {
+ db.exec("CREATE TABLE migration_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); CREATE TABLE migration_history (seq INTEGER PRIMARY KEY, file_name TEXT NOT NULL, content_hash TEXT NOT NULL, applied_at INTEGER NOT NULL)");
+ db.exec("CREATE TABLE sessions (id TEXT PRIMARY KEY, title TEXT NOT NULL, status TEXT NOT NULL, pinned_at INTEGER, updated_at INTEGER NOT NULL); INSERT INTO sessions VALUES ('a', 'Visible', 'active', NULL, 1), ('b', 'Pinned', 'archived', 5, 2);");
+ const result = runMigrationReplay(db, { drizzleDir: drizzleDir(), currentVersion: 125 });
+ expect(result.applied.map((migration) => migration.seq)[0]).toBe(126);
+ expect(columnNames(db, 'sessions')).toContain('hidden_at');
+ expect(db.prepare('SELECT id, title, status, pinned_at, updated_at, hidden_at FROM sessions ORDER BY id').all()).toEqual([
+ { id: 'a', title: 'Visible', status: 'active', pinned_at: null, updated_at: 1, hidden_at: null },
+ { id: 'b', title: 'Pinned', status: 'archived', pinned_at: 5, updated_at: 2, hidden_at: null },
+ ]);
+ db.prepare("UPDATE sessions SET hidden_at = 9 WHERE id = 'a'").run();
+ expect(db.prepare("SELECT count(*) AS n FROM sessions WHERE hidden_at IS NULL").get()).toEqual({ n: 1 });
+ } finally { cleanup(); }
+ });
it('commits the complete fresh schema and task presets in one outer transaction', () => {
const { db, cleanup } = createTempDb();
try {
diff --git a/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts b/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts
index c04fa4a953..abfffbe1b1 100644
--- a/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts
@@ -467,6 +467,7 @@ describe('orcaTeamStore', () => {
plan_mode_enabled INTEGER NOT NULL DEFAULT 0,
cleared_at INTEGER,
pinned_at INTEGER,
+ hidden_at INTEGER,
summary TEXT,
user_send_at INTEGER,
agent_kind TEXT NOT NULL DEFAULT 'codex',
diff --git a/apps/desktop/src/main/localDb/__tests__/remoteHistoryPagination.test.ts b/apps/desktop/src/main/localDb/__tests__/remoteHistoryPagination.test.ts
index 7059f8263d..0e46fa2611 100644
--- a/apps/desktop/src/main/localDb/__tests__/remoteHistoryPagination.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/remoteHistoryPagination.test.ts
@@ -45,7 +45,7 @@ describe.each(modes)('%s remote history visibility', (mode) => {
CREATE TABLE sessions (id TEXT PRIMARY KEY, title TEXT DEFAULT '', working_dir TEXT,
agent_kind TEXT DEFAULT 'codex', workspace_kind TEXT DEFAULT 'project', model TEXT DEFAULT '',
status TEXT DEFAULT 'active', source TEXT DEFAULT 'desktop', orca_role TEXT,
- parent_session_id TEXT, created_at INTEGER, updated_at INTEGER, user_send_at INTEGER);
+ parent_session_id TEXT, created_at INTEGER, updated_at INTEGER, user_send_at INTEGER, hidden_at INTEGER);
CREATE TABLE messages (id TEXT PRIMARY KEY, client_id TEXT, session_id TEXT, role TEXT,
content TEXT, tool_use_id TEXT, agent_meta TEXT, agent_kind TEXT, created_at INTEGER, rewind_at INTEGER);
CREATE VIRTUAL TABLE messages_fts USING fts5(message_id UNINDEXED, content);
diff --git a/apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.ts b/apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.ts
index 185d6f4dcd..208e5a8be6 100644
--- a/apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.ts
@@ -48,6 +48,7 @@ describe('sessionActiveTurn', () => {
status TEXT NOT NULL DEFAULT 'active',
source TEXT NOT NULL DEFAULT 'desktop',
cleared_at INTEGER,
+ hidden_at INTEGER,
active_turn_started_at INTEGER,
active_turn_pid INTEGER,
last_turn_ended_at INTEGER,
@@ -510,6 +511,23 @@ describe('sessionActiveTurn', () => {
]);
});
+ it('excludes plugin background tasks from both red-dot legs', async () => {
+ const { listInterruptedPendingSessionIds, listErrorTailPendingSessionIds } = await import('../sessionActiveTurn.js');
+ const client = createTestDbClient();
+ const now = Date.now();
+ await seedSession(client, 's-visible', { startedAt: now - 1000, source: 'plugin' });
+ await seedSession(client, 's-background', { startedAt: now - 1000, source: 'plugin' });
+ for (const id of ['s-visible', 's-background']) {
+ await client.exec(
+ 'INSERT INTO messages (id, client_id, session_id, role, content, created_at, rewind_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
+ [`${id}-err`, `${id}-err`, id, 'error', '{"message":"boom"}', now - 500, null],
+ );
+ }
+ await client.exec('UPDATE sessions SET hidden_at = ? WHERE id = ?', [now, 's-background']);
+ expect(await listInterruptedPendingSessionIds()).toEqual(['s-visible']);
+ expect(await listErrorTailPendingSessionIds()).toEqual(['s-visible']);
+ });
+
it('hasAssistantProgressAfterMessage detects agent output after the user row', async () => {
const { hasAssistantProgressAfterMessage } = await import('../sessionActiveTurn.js');
const client = createTestDbClient();
diff --git a/apps/desktop/src/main/localDb/agentIslandSessionPatch.ts b/apps/desktop/src/main/localDb/agentIslandSessionPatch.ts
index 33bfd59e84..04bff19d93 100644
--- a/apps/desktop/src/main/localDb/agentIslandSessionPatch.ts
+++ b/apps/desktop/src/main/localDb/agentIslandSessionPatch.ts
@@ -4,9 +4,11 @@ export interface AgentIslandSessionPatch {
title?: unknown;
workingDir?: unknown;
workspaceKind?: unknown;
+ /** 插件后台隐藏时刻;非空 = 任务转入后台,灵动岛与菜单栏收起该任务。 */
+ hiddenAt?: unknown;
}
-/** 把本地 session 归档/删除和 metadata 更新同步给 Agent Island。 */
+/** 把本地 session 归档/删除/转入后台和 metadata 更新同步给 Agent Island。 */
export function notifyAgentIslandSessionPatch(
sessionId: string,
patch: AgentIslandSessionPatch,
@@ -15,7 +17,11 @@ export function notifyAgentIslandSessionPatch(
.then(({ getAgentIslandService }) => {
const service = getAgentIslandService();
if (!service) return;
- if (patch.status === 'archived' || patch.status === 'deleted') {
+ if (
+ patch.status === 'archived' ||
+ patch.status === 'deleted' ||
+ (patch.hiddenAt !== undefined && patch.hiddenAt !== null)
+ ) {
service.handleSessionClosed(sessionId);
return;
}
diff --git a/apps/desktop/src/main/localDb/client/__tests__/drizzleProxy.test.ts b/apps/desktop/src/main/localDb/client/__tests__/drizzleProxy.test.ts
index 7d5f74e15d..0f9ba7995f 100644
--- a/apps/desktop/src/main/localDb/client/__tests__/drizzleProxy.test.ts
+++ b/apps/desktop/src/main/localDb/client/__tests__/drizzleProxy.test.ts
@@ -37,6 +37,7 @@ const DRIZZLE_PROXY_SCHEMA = [
plan_mode_enabled INTEGER NOT NULL DEFAULT 0,
cleared_at INTEGER,
pinned_at INTEGER,
+ hidden_at INTEGER,
user_send_at INTEGER,
agent_kind TEXT NOT NULL DEFAULT 'cc',
orca_role TEXT,
diff --git a/apps/desktop/src/main/localDb/conversationSearch.ts b/apps/desktop/src/main/localDb/conversationSearch.ts
index 488099d1ab..08a0fd95e6 100644
--- a/apps/desktop/src/main/localDb/conversationSearch.ts
+++ b/apps/desktop/src/main/localDb/conversationSearch.ts
@@ -331,6 +331,8 @@ async function listSearchableSessions(
const agentCond = filters.agentKind === 'all' ? undefined : eq(sessions.agentKind, filters.agentKind);
const sessionIdsCond = filters.sessionIds ? inArray(sessions.id, filters.sessionIds) : undefined;
const workerCond = or(isNull(sessions.orcaRole), ne(sessions.orcaRole, 'worker'));
+ // 插件后台隐藏任务不进入任何会话搜索;用户从插件详情页「后台任务」查看与接手。
+ const visibleCond = isNull(sessions.hiddenAt);
const activityCutoff = cutoffForLastActivity(filters.lastActivity);
// 兼容存量 DB 行:旧版 touchUserSendInDb 只写 user_send_at 不 bump updated_at,
// 侧栏排序用 max(userSendAt, updatedAt),这里也同步用 OR 避免漏掉这些行。
@@ -346,6 +348,7 @@ async function listSearchableSessions(
agentCond,
sessionIdsCond,
workerCond,
+ visibleCond,
activityCond,
))
.orderBy(desc(sessions.updatedAt));
diff --git a/apps/desktop/src/main/localDb/hiddenSessionRegistry.ts b/apps/desktop/src/main/localDb/hiddenSessionRegistry.ts
new file mode 100644
index 0000000000..a1b4c9c5a6
--- /dev/null
+++ b/apps/desktop/src/main/localDb/hiddenSessionRegistry.ts
@@ -0,0 +1,106 @@
+import { isNotNull } from 'drizzle-orm';
+import type { DbClient } from './client/DbClient.js';
+import * as currentDb from './client/current.js';
+import { sessions } from './schema.js';
+import { createLogger } from '../logger.js';
+
+const log = createLogger('hidden-session-registry');
+
+/**
+ * 插件后台隐藏任务(`sessions.hidden_at` 非空)的进程内同步索引。
+ *
+ * Agent 灵动岛、菜单栏运行状态与系统通知走同步事件路径,不能每个事件都查库;
+ * 这里按当前账号数据库缓存一份隐藏任务 id。数据库仍是唯一事实来源:
+ * - 账号数据库切换后首次访问会重新加载(加载前按「未隐藏」处理,宁可多显示一次);
+ * - 宿主写入 hidden_at 的唯一入口(创建 / setHidden / 卸载显示)同步调用 {@link noteSessionHidden}。
+ */
+let owner: DbClient | null = null;
+let hiddenIds = new Set<string>();
+let loaded = false;
+let loading: Promise<void> | null = null;
+/** 加载期间已被宿主显式改动的 id:加载结果不得覆盖这些更新的事实。 */
+let touchedDuringLoad = new Set<string>();
+/** 加载失败后的重试冷却:同步判定在每个 Agent 事件上调用,不能把失败放大成逐事件查库。 */
+const RETRY_AFTER_FAILURE_MS = 30_000;
+let failedAt = 0;
+
+function currentClient(): DbClient | null {
+ // 与 sessions:list 读快照同一纪律:启动/切账号窗口内读不到就按「无账号库」处理。
+ try {
+ return currentDb.getCurrentDbClientSnapshot?.()?.client ?? null;
+ } catch {
+ return null;
+ }
+}
+
+function adopt(client: DbClient): void {
+ if (owner === client) return;
+ owner = client;
+ hiddenIds = new Set();
+ loaded = false;
+ loading = null;
+ touchedDuringLoad = new Set();
+ failedAt = 0;
+}
+
+/** 当前账号数据库的隐藏任务索引尚未加载时启动一次加载;已加载或加载中直接复用。 */
+export function ensureHiddenSessionRegistryLoaded(): Promise<void> {
+ const client = currentClient();
+ if (!client) return Promise.resolve();
+ adopt(client);
+ if (loaded) return Promise.resolve();
+ if (loading) return loading;
+ if (failedAt && Date.now() - failedAt < RETRY_AFTER_FAILURE_MS) return Promise.resolve();
+ let pending: Promise<void> | null = null;
+ pending = (async () => {
+ try {
+ const rows = await client.drizzle
+ .select({ id: sessions.id })
+ .from(sessions)
+ .where(isNotNull(sessions.hiddenAt));
+ if (owner !== client) return;
+ for (const row of rows) {
+ if (!touchedDuringLoad.has(row.id)) hiddenIds.add(row.id);
+ }
+ loaded = true;
+ touchedDuringLoad = new Set();
+ } catch (error) {
+ if (owner === client) failedAt = Date.now();
+ log.warn('load hidden sessions failed', {
+ err: error instanceof Error ? error.message : String(error),
+ });
+ } finally {
+ if (owner === client && loading === pending) loading = null;
+ }
+ })();
+ loading = pending;
+ return pending;
+}
+
+/** 同步判断:当前账号下该任务是否为插件后台隐藏任务。未加载时触发加载并按可见处理。 */
+export function isSessionHiddenSync(sessionId: string): boolean {
+ const client = currentClient();
+ if (!client) return false;
+ if (owner !== client || !loaded) void ensureHiddenSessionRegistryLoaded();
+ return owner === client && hiddenIds.has(sessionId);
+}
+
+/** 宿主写入 hidden_at 后同步登记(hidden=true 隐藏,false 恢复可见)。 */
+export function noteSessionHidden(sessionId: string, hidden: boolean, client = currentClient()): void {
+ if (!client || client !== currentClient()) return;
+ adopt(client);
+ if (!loaded) touchedDuringLoad.add(sessionId);
+ if (hidden) hiddenIds.add(sessionId);
+ else hiddenIds.delete(sessionId);
+ if (!loaded) void ensureHiddenSessionRegistryLoaded();
+}
+
+/** 仅供测试。 */
+export function resetHiddenSessionRegistryForTesting(): void {
+ owner = null;
+ hiddenIds = new Set();
+ loaded = false;
+ loading = null;
+ touchedDuringLoad = new Set();
+ failedAt = 0;
+}
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
index 43ca577c38..2c2e4dc53d 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -281,6 +281,7 @@ function createDb(filename = ':memory:'): void {
plan_mode_enabled INTEGER NOT NULL DEFAULT 0,
cleared_at INTEGER,
pinned_at INTEGER,
+ hidden_at INTEGER,
summary TEXT,
provider_id TEXT,
user_send_at INTEGER,
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSessionAccess.db.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSessionAccess.db.test.ts
index 501b8faf6b..a8ebbfc1a5 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSessionAccess.db.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSessionAccess.db.test.ts
@@ -26,11 +26,12 @@ beforeEach(() => {
beforeReply = undefined;
sqlite = new Database(':memory:');
sqlite.exec(`
- CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT);
+ CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT, hidden_at INTEGER);
CREATE TABLE bot_profiles (id TEXT PRIMARY KEY, hidden_at INTEGER, status TEXT);
CREATE TABLE bot_session_links (session_id TEXT UNIQUE, bot_id TEXT);
INSERT INTO bot_profiles VALUES ('visible', NULL, 'active'), ('hidden', 1, 'active'), ('archived', NULL, 'archived');
- INSERT INTO sessions VALUES ('ordinary', 'desktop'), ('visible', 'bot'), ('hidden', 'bot'), ('archived', 'bot'), ('orphan', 'bot');
+ INSERT INTO sessions (id, source) VALUES ('ordinary', 'desktop'), ('visible', 'bot'), ('hidden', 'bot'), ('archived', 'bot'), ('orphan', 'bot');
+ INSERT INTO sessions (id, source, hidden_at) VALUES ('background', 'plugin', 5);
INSERT INTO bot_session_links VALUES ('visible', 'visible'), ('hidden', 'hidden'), ('archived', 'archived');
`);
const transport: DbTransport = {
@@ -68,7 +69,7 @@ describe('remote visibility batch SQL', () => {
it('returns 1,000 authorized tasks in order without a per-row RPC burst or interactive admission', async () => {
const rows = Array.from({ length: 1000 }, (_, i) => ({ id: `task-${i}` }));
- const insert = sqlite.prepare("INSERT INTO sessions VALUES (?, 'desktop')");
+ const insert = sqlite.prepare("INSERT INTO sessions (id, source) VALUES (?, 'desktop')");
sqlite.transaction(() => { for (const row of rows) insert.run(row.id); })();
const input = [...rows, { id: 'hidden' }, rows[0]];
expect(await runAsBackgroundDbRpc(() => projectRemoteSessionResult('local-db:sessions:list', input)))
@@ -78,6 +79,17 @@ describe('remote visibility batch SQL', () => {
expect(calls.every((call) => call.params.length <= 200 && call.admission === 'background')).toBe(true);
});
+ it('omits plugin background tasks from list channels while single reads still resolve them', async () => {
+ const rows = [{ id: 'ordinary' }, { id: 'background' }];
+ expect(await projectRemoteSessionResult('local-db:sessions:list', rows)).toEqual([{ id: 'ordinary' }]);
+ expect(await projectRemoteSessionResult('maker:list-active', [{ sessionId: 'ordinary' }, { sessionId: 'background' }]))
+ .toEqual([{ sessionId: 'ordinary' }]);
+ expect(await projectRemoteSessionResult('maker:list-active', { format: 'active-sessions-v2', sessions: [{ sessionId: 'background' }] }))
+ .toEqual({ format: 'active-sessions-v2', sessions: [] });
+ expect(await projectRemoteSessionResult('local-db:sessions:get', { id: 'background' })).toEqual({ id: 'background' });
+ expect(await projectRemoteSessionResult('local-db:sessions:get-many', rows)).toEqual(rows);
+ });
+
it('discards already read chunks and stops issuing SQL if the data owner changes', async () => {
const ids = Array.from({ length: 450 }, (_, i) => `task-${i}`);
beforeReply = () => { if (calls.length === 2) state.owner++; };
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSessionAccess.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSessionAccess.test.ts
index 58a4595adc..1740ea5907 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSessionAccess.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSessionAccess.test.ts
@@ -11,10 +11,11 @@ let db: Database.Database;
beforeEach(() => {
h.current = true;
db = new Database(':memory:');
- db.exec(`CREATE TABLE sessions(id TEXT PRIMARY KEY, source TEXT);
+ db.exec(`CREATE TABLE sessions(id TEXT PRIMARY KEY, source TEXT, hidden_at INTEGER);
CREATE TABLE bot_session_links(session_id TEXT PRIMARY KEY, bot_id TEXT);
CREATE TABLE bot_profiles(id TEXT PRIMARY KEY, hidden_at INTEGER, status TEXT);
- INSERT INTO sessions VALUES ('ordinary','desktop'),('visible','bot'),('hidden','bot'),('archived','bot'),('orphan','bot');
+ INSERT INTO sessions(id, source) VALUES ('ordinary','desktop'),('visible','bot'),('hidden','bot'),('archived','bot'),('orphan','bot');
+ INSERT INTO sessions(id, source, hidden_at) VALUES ('background','plugin',5);
INSERT INTO bot_profiles VALUES ('v',NULL,'active'),('h',1,'active'),('a',NULL,'archived');
INSERT INTO bot_session_links VALUES ('visible','v'),('hidden','h'),('archived','a');`);
h.db = drizzle(db);
@@ -32,6 +33,11 @@ describe('batch DB visibility', () => {
expect(Object.fromEntries(await readRemoteBotSessionAccessBatch(['v','h','a','no'], 'bot')))
.toEqual({ v:'visible', h:'hidden', a:'hidden', no:'missing' });
});
+ it('marks plugin background tasks as background, not hidden', async () => {
+ expect(await readRemoteBotSessionAccess('background')).toBe('background');
+ db.exec("UPDATE sessions SET hidden_at=NULL WHERE id='background'");
+ expect(await readRemoteBotSessionAccess('background')).toBe('ordinary');
+ });
it('bounds queries and denies the entire result when ownership changes', async () => {
const select = vi.spyOn(h.db!, 'select');
const ids = Array.from({ length: 600 }, (_, i) => `missing${i}`);
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts
index b56e428d16..edf9b089e1 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts
@@ -89,6 +89,7 @@ function createDb(initialTitle: string): void {
fast_mode INTEGER NOT NULL DEFAULT 0,
cleared_at INTEGER,
pinned_at INTEGER,
+ hidden_at INTEGER,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
agent_kind TEXT NOT NULL DEFAULT 'cc',
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsHiddenTasks.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsHiddenTasks.test.ts
new file mode 100644
index 0000000000..c9064f5002
--- /dev/null
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsHiddenTasks.test.ts
@@ -0,0 +1,211 @@
+/**
+ * 插件后台隐藏任务(sessions.hidden_at)在本机任务列表上的口径回归:
+ * - local-db:sessions:list 排除隐藏任务,单任务读取仍返回(带 hiddenAt);
+ * - setSessionHidden 是唯一宿主写入口:隐藏广播 hiddenAt patch 并收起灵动岛,
+ * 恢复显示清列、刷新 updatedAt 并发「新建」推送让侧栏整体重拉。
+ */
+import Database from 'better-sqlite3';
+import { drizzle } from 'drizzle-orm/better-sqlite3';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { messages, sessions } from '../../schema';
+
+const h = vi.hoisted(() => ({
+ db: null as ReturnType<typeof drizzle> | null,
+ sqlite: null as InstanceType<typeof import('better-sqlite3')> | null,
+ handlers: new Map<string, (...args: unknown[]) => unknown>(),
+ tapWindowBroadcast: vi.fn(),
+ emitSessionCreated: vi.fn(),
+ notifyAgentIslandSessionPatch: vi.fn(),
+}));
+
+vi.mock('electron', () => ({
+ ipcMain: {
+ handle: vi.fn((channel: string, handler: (...args: unknown[]) => unknown) => {
+ h.handlers.set(channel, handler);
+ }),
+ },
+ BrowserWindow: { getAllWindows: () => [] },
+}));
+vi.mock('../../../logger', () => ({
+ createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
+}));
+vi.mock('../../client/current', () => {
+ const client = { get drizzle() { return h.db; } };
+ return {
+ getDbClient: () => client,
+ getCurrentDbClientUserId: () => 'test-user',
+ getCurrentDbClientSnapshot: () => ({ client, userId: 'test-user', clientEpoch: 1 }),
+ };
+});
+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('../../../device-link/broadcast-tap.js', () => ({
+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),
+ tapWindowBroadcast: h.tapWindowBroadcast,
+}));
+vi.mock('../../agentIslandSessionPatch', () => ({ notifyAgentIslandSessionPatch: h.notifyAgentIslandSessionPatch }));
+vi.mock('../sessionCreatedBroadcast', () => ({ emitSessionCreated: h.emitSessionCreated }));
+vi.mock('../../../messagePersistBroadcaster', () => ({ noteSessionClearBoundary: vi.fn() }));
+vi.mock('../../../sessionTaskSummary.js', () => ({ backfillPinnedSessionSummaries: vi.fn() }));
+vi.mock('../../../security/trustedAppRenderer.js', () => ({ assertTrustedAppRendererEvent: vi.fn(), isTrustedAppRendererWindow: () => true }));
+
+import { registerSessionIpc } from '../sessions';
+import { setSessionHidden } from '../sessionHidden';
+import { isSessionHiddenSync, resetHiddenSessionRegistryForTesting } from '../../hiddenSessionRegistry';
+
+function createDb(): void {
+ h.sqlite?.close();
+ const sqlite = new Database(':memory:');
+ sqlite.exec(`
+ CREATE TABLE task_tags(id TEXT PRIMARY KEY,name TEXT,color TEXT,favorite_order INTEGER,sort_order INTEGER,revision INTEGER,name_customized INTEGER NOT NULL DEFAULT 0);
+ CREATE TABLE session_task_tags(session_id TEXT,tag_id TEXT);
+ CREATE TABLE sessions (
+ id TEXT PRIMARY KEY NOT NULL,
+ title TEXT NOT NULL DEFAULT 'New CCS',
+ working_dir TEXT,
+ model TEXT NOT NULL DEFAULT 'claude-sonnet-4-6',
+ effort TEXT NOT NULL DEFAULT 'high',
+ permission_mode TEXT NOT NULL DEFAULT 'ask',
+ status TEXT NOT NULL DEFAULT 'active',
+ sdk_session_id TEXT,
+ total_token_usage INTEGER NOT NULL DEFAULT 0,
+ total_cost_usd REAL NOT NULL DEFAULT 0,
+ total_cost_amount REAL NOT NULL DEFAULT 0,
+ total_cost_currency TEXT,
+ total_cost_is_approximate INTEGER NOT NULL DEFAULT 0,
+ context_tokens INTEGER NOT NULL DEFAULT 0,
+ context_window INTEGER NOT NULL DEFAULT 0,
+ context_window_runtime INTEGER,
+ fast_mode INTEGER NOT NULL DEFAULT 0,
+ cleared_at INTEGER,
+ pinned_at INTEGER,
+ hidden_at INTEGER,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL,
+ agent_kind TEXT NOT NULL DEFAULT 'cc',
+ user_send_at INTEGER,
+ parent_session_id TEXT,
+ forked_at_message_id TEXT,
+ worktree_path TEXT,
+ source TEXT NOT NULL DEFAULT 'desktop',
+ feishu_open_id TEXT,
+ feishu_bot_app_id TEXT,
+ used_project_context INTEGER NOT NULL DEFAULT 0,
+ extra_dirs TEXT NOT NULL DEFAULT '[]',
+ writable_dirs TEXT NOT NULL DEFAULT '[]',
+ one_m INTEGER NOT NULL DEFAULT 0,
+ workspace_kind TEXT NOT NULL DEFAULT 'project',
+ orca_role TEXT,
+ remote_host_id TEXT,
+ agent_device_id TEXT,
+ orca_remote_lead TEXT,
+ codex_history_has_product_prompt INTEGER,
+ codex_plan_json TEXT,
+ im_bot_context_id TEXT,
+ im_user_id TEXT,
+ im_default_route TEXT,
+ summary TEXT,
+ provider_id TEXT,
+ plan_mode_enabled INTEGER NOT NULL DEFAULT 0,
+ active_turn_started_at INTEGER,
+ active_turn_pid INTEGER,
+ last_turn_ended_at INTEGER,
+ list_preview TEXT,
+ list_preview_role TEXT,
+ list_message_count INTEGER
+ );
+ CREATE TABLE messages (
+ id TEXT PRIMARY KEY,
+ client_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ role TEXT NOT NULL,
+ content TEXT NOT NULL,
+ tool_use_id TEXT,
+ agent_meta TEXT,
+ created_at INTEGER NOT NULL,
+ rewind_at INTEGER
+ );
+ INSERT INTO sessions (id, title, status, source, created_at, updated_at) VALUES
+ ('visible', 'Visible', 'active', 'desktop', 1, 30),
+ ('plugin-visible', 'Plugin visible', 'active', 'plugin', 1, 20),
+ ('background', 'Background', 'active', 'plugin', 1, 10),
+ ('deleted-bg', 'Deleted', 'deleted', 'plugin', 1, 5);
+ UPDATE sessions SET hidden_at = 7 WHERE id IN ('background', 'deleted-bg');
+ `);
+ h.sqlite = sqlite;
+ h.db = drizzle(sqlite, { schema: { messages, sessions } });
+}
+
+async function list(status: unknown = 'active'): Promise<string[]> {
+ const handler = h.handlers.get('local-db:sessions:list')!;
+ const rows = await handler({}, 100, status, { fresh: true }) as Array<{ id: string }>;
+ return rows.map((row) => row.id);
+}
+
+function readRow(id: string): { hidden_at: number | null; updated_at: number } {
+ return h.sqlite!.prepare('SELECT hidden_at, updated_at FROM sessions WHERE id = ?').get(id) as {
+ hidden_at: number | null; updated_at: number;
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ h.handlers.clear();
+ createDb();
+ resetHiddenSessionRegistryForTesting();
+ registerSessionIpc();
+});
+
+describe('plugin background tasks in the local task list', () => {
+ it('omits hidden tasks from every list filter but keeps single-task reads', async () => {
+ expect(await list('active')).toEqual(['visible', 'plugin-visible']);
+ expect(await list('all')).toEqual(['visible', 'plugin-visible']);
+ const row = await h.handlers.get('local-db:sessions:get')!({}, 'background') as { hiddenAt: string | null };
+ expect(row.hiddenAt).toBe(new Date(7).toISOString());
+ const visible = await h.handlers.get('local-db:sessions:get')!({}, 'visible') as { hiddenAt: string | null };
+ expect(visible.hiddenAt).toBeNull();
+ });
+
+ it('hides through the shared writer: patch broadcast, island cleanup and sync registry', async () => {
+ expect(await setSessionHidden({ sessionId: 'plugin-visible', hidden: true, now: 100 })).toBe(true);
+ expect(readRow('plugin-visible')).toEqual({ hidden_at: 100, updated_at: 20 });
+ expect(h.tapWindowBroadcast).toHaveBeenCalledWith('local-db:sessions:patched',
+ { sessionId: 'plugin-visible', patch: { hiddenAt: new Date(100).toISOString() } });
+ expect(h.notifyAgentIslandSessionPatch).toHaveBeenCalledWith('plugin-visible', { hiddenAt: new Date(100).toISOString() });
+ expect(h.emitSessionCreated).not.toHaveBeenCalled();
+ expect(isSessionHiddenSync('plugin-visible')).toBe(true);
+ expect(await list()).toEqual(['visible']);
+ // Repeating the same state is a no-op without another broadcast.
+ expect(await setSessionHidden({ sessionId: 'plugin-visible', hidden: true, now: 200 })).toBe(false);
+ expect(h.tapWindowBroadcast).toHaveBeenCalledTimes(1);
+ });
+
+ it('reveals by clearing hidden_at, bumping updatedAt and announcing the task like a new one', async () => {
+ expect(await setSessionHidden({ sessionId: 'background', hidden: false, now: 500 })).toBe(true);
+ expect(readRow('background')).toEqual({ hidden_at: null, updated_at: 500 });
+ expect(h.tapWindowBroadcast).toHaveBeenCalledWith('local-db:sessions:patched',
+ { sessionId: 'background', patch: { hiddenAt: null, updatedAt: new Date(500).toISOString() } });
+ expect(h.emitSessionCreated).toHaveBeenCalledWith('background');
+ expect(h.notifyAgentIslandSessionPatch).not.toHaveBeenCalled();
+ expect(isSessionHiddenSync('background')).toBe(false);
+ expect(await list()).toEqual(['background', 'visible', 'plugin-visible']);
+ });
+
+ it('never touches deleted tasks and runs the caller check before writing', async () => {
+ expect(await setSessionHidden({ sessionId: 'deleted-bg', hidden: false })).toBe(false);
+ expect(readRow('deleted-bg').hidden_at).toBe(7);
+ await expect(setSessionHidden({ sessionId: 'visible', hidden: true, assertCurrent: () => { throw new Error('changed'); } }))
+ .rejects.toThrow('changed');
+ expect(readRow('visible').hidden_at).toBeNull();
+ });
+
+ it('loads the sync registry from the database for tasks hidden before this process', async () => {
+ expect(isSessionHiddenSync('background')).toBe(false);
+ await list();
+ await vi.waitFor(() => expect(isSessionHiddenSync('background')).toBe(true));
+ expect(isSessionHiddenSync('visible')).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts
index 8470d39ddb..11fdb0788c 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts
@@ -107,6 +107,7 @@ function createDb(): void {
fast_mode INTEGER NOT NULL DEFAULT 0,
cleared_at INTEGER,
pinned_at INTEGER,
+ hidden_at INTEGER,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
agent_kind TEXT NOT NULL DEFAULT 'cc',
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
index d15b1bc1e2..67b0f0ceb1 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
@@ -221,6 +221,7 @@ function createDb(): void {
fast_mode INTEGER NOT NULL DEFAULT 0,
cleared_at INTEGER,
pinned_at INTEGER,
+ hidden_at INTEGER,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
agent_kind TEXT NOT NULL DEFAULT 'cc',
diff --git a/apps/desktop/src/main/localDb/ipc/botRemoteSessionAccess.ts b/apps/desktop/src/main/localDb/ipc/botRemoteSessionAccess.ts
index 996234f86b..aed02f980d 100644
--- a/apps/desktop/src/main/localDb/ipc/botRemoteSessionAccess.ts
+++ b/apps/desktop/src/main/localDb/ipc/botRemoteSessionAccess.ts
@@ -33,12 +33,14 @@ export async function readRemoteBotSessionAccessBatch(
const rows = await db.select({
id: sessions.id,
source: sessions.source,
+ hiddenAt: sessions.hiddenAt,
visible: sql<number>`${sql.raw(remoteVisibleSessionSql('sessions'))}`,
}).from(sessions)
.where(inArray(sessions.id, chunk));
if (!isDataOwnerBroadcastScopeCurrent(owner)) return denyAll();
for (const row of rows) {
- access.set(row.id, row.source !== 'bot' ? 'ordinary'
+ // 插件后台隐藏任务:列表类结果不返回,单任务读取/操作仍允许(插件页深链打开)。
+ access.set(row.id, row.source !== 'bot' ? (row.hiddenAt != null ? 'background' : 'ordinary')
: row.visible ? 'visible' : 'hidden');
}
}
diff --git a/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts b/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts
index 464ae0a45d..f0341ab646 100644
--- a/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts
@@ -26,6 +26,7 @@ import { and, eq, isNull, isNotNull, ne, or } from 'drizzle-orm';
import { getDbClient } from '../client/current';
import { sessions } from '../schema';
+import { noteSessionHidden } from '../hiddenSessionRegistry.js';
import { upsertRecentWorkdir } from './recentWorkdirs';
import { createLogger } from '../../logger';
import { pickSessionForWorkdir } from '../pluginWorkspaceDedupe';
@@ -148,6 +149,11 @@ export async function createPluginTaskSession(params: {
permissionMode: 'ask' | 'plan' | 'acceptEdits' | 'auto';
/** 用户亲选的项目目录(绝对路径);缺省 = 专属 dialogue 目录。 */
workingDir?: string;
+ /**
+ * 后台隐藏任务(插件声明 agent.hiddenTasks):同一次 INSERT 带上 hidden_at,
+ * 任务从不闪进列表;调用方不应再为它广播「新建」推送。
+ */
+ hidden?: boolean;
notifySessionCreated?: (info: { sessionId: string; workdir?: string }) => void;
}): Promise<string> {
if (params.shouldContinue && !params.shouldContinue()) throw new Error('Plugin task owner changed');
@@ -157,7 +163,9 @@ export async function createPluginTaskSession(params: {
? (normalizeWorkingDirForStorage(params.workingDir) ?? undefined)
: undefined;
const workspaceKind = projectDir ? ('project' as const) : ('dialogue' as const);
+ if (params.hidden) noteSessionHidden(id, true);
const { row: insertRow } = await openSession({ id, now, source: 'plugin',
+ ...(params.hidden ? { hiddenAt: now } : {}),
body: { workingDir: projectDir, workspaceKind, permissionMode: params.permissionMode,
agentKind: params.agentKind, model: params.model, effort: params.effort,
fastMode: params.fastMode, providerId: params.providerId,
@@ -185,6 +193,7 @@ export async function createPluginTaskSession(params: {
log.info('[plugin-task] session created', {
sessionId: id,
ghostId: params.ghostId,
+ hidden: params.hidden === true,
workspaceKind,
workingDir: insertRow.workingDir,
});
diff --git a/apps/desktop/src/main/localDb/ipc/sessionHidden.ts b/apps/desktop/src/main/localDb/ipc/sessionHidden.ts
new file mode 100644
index 0000000000..1b0d882407
--- /dev/null
+++ b/apps/desktop/src/main/localDb/ipc/sessionHidden.ts
@@ -0,0 +1,54 @@
+import { and, eq, isNotNull, isNull, ne } from 'drizzle-orm';
+import type { DbClient } from '../client/DbClient.js';
+import { getCurrentDbClientSnapshot, getDbClient } from '../client/current.js';
+import { sessions } from '../schema.js';
+import { noteSessionHidden } from '../hiddenSessionRegistry.js';
+import { notifyAgentIslandSessionPatch } from '../agentIslandSessionPatch.js';
+import { broadcastSessionPatched } from './sessions.js';
+import { emitSessionCreated } from './sessionCreatedBroadcast.js';
+
+/**
+ * `sessions.hidden_at` 的唯一宿主写入口(插件 setHidden、详情页「显示到任务列表」、
+ * 卸载时恢复显示共用)。创建时直接带 hidden_at 落库的路径见 createPluginTaskSession。
+ *
+ * - 隐藏:只写 hidden_at,不改 updatedAt;广播 `sessions:patched {hiddenAt}`,
+ * renderer 据此把任务移出列表,灵动岛同步收起该任务。
+ * - 显示:清 hidden_at 并刷新 updatedAt(让任务落在列表前部、不被 1000 条上限截掉),
+ * 广播 patched 后再发一次「新建」推送,复用侧栏与远端控制端的整体重拉。
+ *
+ * 已删除任务不处理;状态未变化时返回 false 且不广播。调用方负责归属与权限校验,
+ * `assertCurrent` 在写入前同步执行,用于复核账号与插件授权。
+ */
+export async function setSessionHidden(input: {
+ sessionId: string;
+ hidden: boolean;
+ db?: DbClient;
+ assertCurrent?: () => void;
+ now?: number;
+}): Promise<boolean> {
+ const client = input.db ?? getDbClient();
+ const now = input.now ?? Date.now();
+ input.assertCurrent?.();
+ const updated = await client.drizzle
+ .update(sessions)
+ .set(input.hidden ? { hiddenAt: now } : { hiddenAt: null, updatedAt: now })
+ .where(and(
+ eq(sessions.id, input.sessionId),
+ ne(sessions.status, 'deleted'),
+ input.hidden ? isNull(sessions.hiddenAt) : isNotNull(sessions.hiddenAt),
+ ))
+ .returning({ id: sessions.id });
+ if (!updated.length) return false;
+ noteSessionHidden(input.sessionId, input.hidden, client);
+ // 账号已切换时不向新账号的窗口广播旧账号的任务变化。
+ if (getCurrentDbClientSnapshot()?.client !== client) return true;
+ const iso = new Date(now).toISOString();
+ if (input.hidden) {
+ broadcastSessionPatched(input.sessionId, { hiddenAt: iso });
+ notifyAgentIslandSessionPatch(input.sessionId, { hiddenAt: iso });
+ } else {
+ broadcastSessionPatched(input.sessionId, { hiddenAt: null, updatedAt: iso });
+ emitSessionCreated(input.sessionId);
+ }
+ return true;
+}
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index bc27353604..8ee2ec9615 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -80,6 +80,7 @@ import { assertRendererSessionSourceAllowed } from './sessionSourceGuard.js';
import type { SessionReference } from '../../../shared/sessionReference.js';
import * as broadcastTap from '../../device-link/broadcast-tap.js';
import { notifyAgentIslandSessionPatch } from '../agentIslandSessionPatch';
+import { ensureHiddenSessionRegistryLoaded } from '../hiddenSessionRegistry.js';
import { noteSessionClearBoundary } from '../../messagePersistBroadcaster';
import {
ackSessionTurnEndedDurable,
@@ -1257,6 +1258,8 @@ export function registerSessionIpc(
// sidebar-card-mode: 首次 list(db 必然 ready)触发一次置顶摘要回填——
// 老置顶会话没有 turn-done 触发点。模块内部 once 守卫 + 串行 + swallow。
void import('../../sessionTaskSummary.js').then((m) => m.backfillPinnedSessionSummaries());
+ // 首次 list 即账号库就绪:预热插件后台任务索引,灵动岛/通知的同步判定从此可用。
+ void ensureHiddenSessionRegistryLoaded();
const cap = clampLimit(limit, 20);
const includePinned = shouldIncludePinnedSessions(options);
const fresh = shouldBypassSessionListSingleFlight(options);
@@ -1301,7 +1304,12 @@ export function registerSessionIpc(
// (feishu/slack/discord)与本机自动化(scheduler/learn/shared);
// feishu 会话以「对话」分组展示(workspaceKind='dialogue')。/review 审查任务
// 只从来源任务的审查卡片打开,不进普通任务列表(用量历史仍包含)。
- const sourceFilter = inArray(sessions.source, DESKTOP_TASK_LIST_SESSION_SOURCES);
+ // 插件后台隐藏任务(hidden_at 非空)同样不进任务列表,只在插件详情页「后台任务」
+ // 查看与接手;手机/远控经 device-link 调同一 handler,口径一致。
+ const sourceFilter = and(
+ inArray(sessions.source, DESKTOP_TASK_LIST_SESSION_SOURCES),
+ isNull(sessions.hiddenAt),
+ );
const statusWhere = () =>
statusFilter ? eq(sessions.status, statusFilter) : ne(sessions.status, 'deleted');
const rows = await selectSessionListRows(db, and(sourceFilter, statusWhere(), ids ? inArray(sessions.id, ids) : undefined), cap, before);
diff --git a/apps/desktop/src/main/localDb/mapper.ts b/apps/desktop/src/main/localDb/mapper.ts
index 659b298334..9caf3178f6 100644
--- a/apps/desktop/src/main/localDb/mapper.ts
+++ b/apps/desktop/src/main/localDb/mapper.ts
@@ -261,6 +261,7 @@ export function sessionToCamel(row: SessionRowWithCount): Session {
planModeEnabled: !!row.planModeEnabled,
clearedAt: msToIso(row.clearedAt),
pinnedAt: msToIso(row.pinnedAt),
+ hiddenAt: msToIso(row.hiddenAt),
userSendAt: msToIso(row.userSendAt),
agentKind: row.agentKind as AgentKind,
source: normalizeSessionSource(row.source),
diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.ts
index f36246c0e6..e5a05705f1 100644
--- a/apps/desktop/src/main/localDb/schema.ts
+++ b/apps/desktop/src/main/localDb/schema.ts
@@ -109,6 +109,13 @@ export const sessions = sqliteTable(
planModeEnabled: integer('plan_mode_enabled', { mode: 'boolean' }).notNull().default(false),
clearedAt: integer('cleared_at'), // unix ms
pinnedAt: integer('pinned_at'), // unix ms
+ /**
+ * 后台隐藏时刻(unix ms)。非 NULL = 插件以 `agent.hiddenTasks` 声明创建或切换为
+ * 隐藏的后台任务:不进入任务列表、搜索、未结束提示与新任务通知;用户仍可在插件
+ * 详情页「后台任务」打开或显示到任务列表。NULL = 普通可见任务(存量行全部为 NULL)。
+ * 用量统计等全量口径不按此列过滤。
+ */
+ hiddenAt: integer('hidden_at'), // unix ms
/**
* 任务现状一句话摘要(仅置顶段卡片模式展示/生成)。
* 由 main/sessionTaskSummary.ts 在置顶会话 turn 结束或置顶时经 oneShot 生成,
diff --git a/apps/desktop/src/main/localDb/sessionActiveTurn.ts b/apps/desktop/src/main/localDb/sessionActiveTurn.ts
index e4b498df50..28e7dd964e 100644
--- a/apps/desktop/src/main/localDb/sessionActiveTurn.ts
+++ b/apps/desktop/src/main/localDb/sessionActiveTurn.ts
@@ -388,6 +388,8 @@ export async function listInterruptedPendingRows(): Promise<
// 只统计桌面 sidebar 可见来源(含 feishu/slack 等 IM 渠道)——
// 不可见来源的红点无处展示也无法清除。
inArray(sessions.source, DESKTOP_TASK_LIST_SESSION_SOURCES),
+ // 插件后台隐藏任务不在侧栏展示,红点无处展示也无法清除。
+ isNull(sessions.hiddenAt),
gt(sessions.activeTurnStartedAt, sql`COALESCE(${sessions.lastTurnEndedAt}, 0)`),
gt(sessions.activeTurnStartedAt, sql`COALESCE(${sessions.clearedAt}, 0)`),
// 只认「开始于本进程启动之前」的 turn —— 排除正在跑的(见 _bootAtMs 注释)。
@@ -447,6 +449,7 @@ export async function listErrorTailPendingRows(): Promise<
and(
eq(sessions.status, 'active'),
inArray(sessions.source, DESKTOP_TASK_LIST_SESSION_SOURCES),
+ isNull(sessions.hiddenAt),
eq(messages.role, 'error'),
isNull(messages.rewindAt),
// /clear 可见性边界(见上方 ⚠️ 3):clear 之前的行在视图里已不可见,不能算告警。
diff --git a/apps/desktop/src/main/localDb/sessionOpening.ts b/apps/desktop/src/main/localDb/sessionOpening.ts
index 6c9b64778a..06302ee7a8 100644
--- a/apps/desktop/src/main/localDb/sessionOpening.ts
+++ b/apps/desktop/src/main/localDb/sessionOpening.ts
@@ -31,6 +31,8 @@ export async function openSession<T = void>(input: {
now?: number;
body: SessionOpenBody;
source?: OpenedSessionRow['source'];
+ /** Background task (plugin `agent.hiddenTasks`): committed hidden in the same INSERT. */
+ hiddenAt?: number;
assertCurrent?: () => void;
/** Sample effective authority after async preparation, directly before committing. */
finalize?: () => Pick<SessionOpenBody, 'permissionMode' | 'parentSessionId'>;
@@ -64,7 +66,8 @@ export async function openSession<T = void>(input: {
assertCurrent();
const mapped = sessionCreateToRow(id, { ...prepared, ...input.finalize?.() }, now);
if (!mapped.model) throw new Error('任务模型不可用,请重新选择');
- const row = { ...mapped, model: mapped.model, ...(input.source ? { source: input.source } : {}) };
+ const row = { ...mapped, model: mapped.model, ...(input.source ? { source: input.source } : {}),
+ ...(input.hiddenAt !== undefined ? { hiddenAt: input.hiddenAt } : {}) };
input.onPersistenceStarted?.();
let value: T;
if (commit) value = await commit(row, assertCurrent);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginHiddenTasks.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginHiddenTasks.test.ts
new file mode 100644
index 0000000000..a0e7c0e933
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginHiddenTasks.test.ts
@@ -0,0 +1,142 @@
+/**
+ * 插件详情页「后台任务」IPC 业务体:只列本插件经有效创建回执拥有、仍在后台且未删除的任务;
+ * 显示到任务列表复用宿主写入口并复核归属。
+ */
+import Database from 'better-sqlite3';
+import { drizzle } from 'drizzle-orm/better-sqlite3';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { DbClient } from '../../localDb/client/DbClient.js';
+import {
+ createPluginBackgroundTaskHandlers,
+ revealAllPluginHiddenTasks,
+ selectPluginHiddenTaskRows,
+} from '../pluginHiddenTasks.js';
+
+let sqlite: Database.Database;
+let db: DbClient;
+
+beforeEach(() => {
+ sqlite = new Database(':memory:');
+ sqlite.exec(`
+ CREATE TABLE sessions (id TEXT PRIMARY KEY, title TEXT, status TEXT, source TEXT, hidden_at INTEGER, updated_at INTEGER);
+ CREATE TABLE plugin_task_requests (id TEXT PRIMARY KEY, plugin_id TEXT, operation TEXT, target_id TEXT,
+ request_key TEXT, fingerprint TEXT, payload TEXT, revision INTEGER, created_at INTEGER);
+ INSERT INTO sessions VALUES
+ ('bg-new', 'New', 'active', 'plugin', 5, 30),
+ ('bg-old', 'Old', 'archived', 'plugin', 5, 10),
+ ('shown', 'Shown', 'active', 'plugin', NULL, 40),
+ ('deleted', 'Deleted', 'deleted', 'plugin', 5, 50),
+ ('revoked', 'Revoked', 'active', 'plugin', 5, 60),
+ ('other', 'Other plugin', 'active', 'plugin', 5, 70);
+ INSERT INTO plugin_task_requests VALUES
+ ('bg-new', 'demo', 'create', '', 'k1', 'f', '{"route":{}}', 0, 1),
+ ('bg-old', 'demo', 'create', '', 'k2', 'f', '{"route":{}}', 0, 1),
+ ('shown', 'demo', 'create', '', 'k3', 'f', '{}', 0, 1),
+ ('deleted', 'demo', 'create', '', 'k4', 'f', '{}', 0, 1),
+ ('revoked', 'demo', 'create', '', 'k5', 'f', '{"ownershipRevoked":true}', 0, 1),
+ ('other', 'elsewhere', 'create', '', 'k6', 'f', '{}', 0, 1),
+ ('send-1', 'demo', 'send', 'bg-new', 'k7', 'f', '{}', 0, 1);
+ `);
+ db = { drizzle: drizzle(sqlite) } as unknown as DbClient;
+});
+
+describe('plugin background task rows', () => {
+ it('lists only owned, hidden, undeleted tasks of this plugin, newest first', async () => {
+ expect((await selectPluginHiddenTaskRows(db, 'demo')).map((row) => row.taskId)).toEqual(['bg-new', 'bg-old']);
+ expect((await selectPluginHiddenTaskRows(db, 'demo', { taskId: 'other' }))).toEqual([]);
+ expect((await selectPluginHiddenTaskRows(db, 'elsewhere')).map((row) => row.taskId)).toEqual(['other']);
+ });
+});
+
+describe('revealing every plugin background task', () => {
+ const addHiddenTasks = (count: number) => {
+ for (let i = 0; i < count; i += 1) {
+ sqlite.prepare("INSERT INTO sessions VALUES (?, 'Bulk', 'active', 'plugin', 5, ?)").run(`bulk-${i}`, 100 + i);
+ sqlite.prepare("INSERT INTO plugin_task_requests VALUES (?, 'bulk', 'create', '', ?, 'f', '{}', 0, 1)")
+ .run(`bulk-${i}`, `kb-${i}`);
+ }
+ };
+
+ it('reveals beyond one batch until nothing of this plugin stays hidden', async () => {
+ addHiddenTasks(5);
+ const reveal = vi.fn(async (taskId: string) => {
+ sqlite.prepare('UPDATE sessions SET hidden_at = NULL WHERE id = ?').run(taskId);
+ });
+ await revealAllPluginHiddenTasks(db, 'bulk', reveal, { batchSize: 2 });
+ expect(reveal).toHaveBeenCalledTimes(5);
+ expect(new Set(reveal.mock.calls.map(([id]) => id)).size).toBe(5);
+ expect(await selectPluginHiddenTaskRows(db, 'bulk')).toEqual([]);
+ // 其它插件的后台任务不受影响。
+ expect((await selectPluginHiddenTaskRows(db, 'demo')).map((row) => row.taskId)).toEqual(['bg-new', 'bg-old']);
+ });
+
+ it('throws instead of looping when a reveal does not take effect', async () => {
+ addHiddenTasks(5);
+ const reveal = vi.fn(async () => undefined);
+ await expect(revealAllPluginHiddenTasks(db, 'bulk', reveal, { batchSize: 2 })).rejects.toThrow('still hidden');
+ expect(reveal).toHaveBeenCalledTimes(2);
+ });
+
+ it('stops at maxBatches', async () => {
+ addHiddenTasks(5);
+ const reveal = vi.fn(async (taskId: string) => {
+ sqlite.prepare('UPDATE sessions SET hidden_at = NULL WHERE id = ?').run(taskId);
+ });
+ await expect(revealAllPluginHiddenTasks(db, 'bulk', reveal, { batchSize: 2, maxBatches: 2 }))
+ .rejects.toThrow('after 2 batches');
+ expect(reveal).toHaveBeenCalledTimes(4);
+ });
+});
+
+describe('plugin background task IPC handlers', () => {
+ const setup = (overrides: Partial<Parameters<typeof createPluginBackgroundTaskHandlers>[0]> = {}) => {
+ const setHidden = vi.fn(async (input: { sessionId: string; hidden: boolean; assertCurrent: () => void }) => {
+ input.assertCurrent();
+ sqlite.prepare('UPDATE sessions SET hidden_at = NULL WHERE id = ?').run(input.sessionId);
+ return true;
+ });
+ const handlers = createPluginBackgroundTaskHandlers({
+ currentDb: () => db,
+ isInstalled: (id) => id === 'demo',
+ isRunning: (id) => id === 'bg-new',
+ setHidden,
+ ...overrides,
+ });
+ return { handlers, setHidden };
+ };
+
+ it('projects status, last activity and running state', async () => {
+ const { handlers } = setup();
+ expect(await handlers.list('demo')).toEqual({ items: [
+ { taskId: 'bg-new', title: 'New', status: 'active', updatedAt: 30, running: true },
+ { taskId: 'bg-old', title: 'Old', status: 'archived', updatedAt: 10, running: false },
+ ] });
+ });
+
+ it('reveals only a hidden task owned by the plugin and treats already visible tasks as done', async () => {
+ const { handlers, setHidden } = setup();
+ await expect(handlers.reveal('demo', 'bg-old')).resolves.toEqual({ ok: true });
+ expect(setHidden).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'bg-old', hidden: false, db }));
+ expect((await handlers.list('demo')).items.map((item) => item.taskId)).toEqual(['bg-new']);
+ await expect(handlers.reveal('demo', 'other')).resolves.toEqual({ ok: true });
+ await expect(handlers.reveal('demo', 'shown')).resolves.toEqual({ ok: true });
+ expect(setHidden).toHaveBeenCalledTimes(1);
+ expect(sqlite.prepare("SELECT hidden_at FROM sessions WHERE id = 'other'").get()).toEqual({ hidden_at: 5 });
+ });
+
+ it('rejects malformed input, uninstalled plugins and a missing account database', async () => {
+ const { handlers } = setup();
+ await expect(handlers.list('')).rejects.toThrow('INVALID_PARAMS');
+ await expect(handlers.reveal('demo', 42)).rejects.toThrow('INVALID_PARAMS');
+ await expect(handlers.list('elsewhere')).rejects.toThrow('NOT_FOUND');
+ const offline = setup({ currentDb: () => null }).handlers;
+ await expect(offline.list('demo')).rejects.toThrow('PRECONDITION_FAILED');
+ });
+
+ it('refuses to write when the account changes before the reveal', async () => {
+ let current: DbClient | null = db;
+ const { handlers, setHidden } = setup({ currentDb: () => current });
+ setHidden.mockImplementationOnce(async (input) => { current = null; input.assertCurrent(); return true; });
+ await expect(handlers.reveal('demo', 'bg-new')).rejects.toThrow('Account changed');
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
index 38e0b0a4f7..23bc1f367f 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
@@ -978,3 +978,79 @@ it('registers a complete scope once and permits only identical replays', async (
await expect(f.service.setTeamPlan('p',task.taskId,{...plan,task:'Publish'})).rejects.toThrow('immutable');
await expect(f.service.setTeamPlan('p',task.taskId,{...plan,items:[{...plan.items[0]!,task:'Publish'}]})).rejects.toThrow('immutable');
});
+
+describe('background tasks', () => {
+ const declaredFixture = () => {
+ const f = fixture();
+ let declared = true;
+ f.deps.assertHiddenTasksAllowed = () => {
+ if (!declared) throw new PluginTaskError('PERMISSION_DENIED', 'Background tasks require agent.hiddenTasks');
+ };
+ f.deps.createSession = vi.fn(async (_p, taskId, title, resolvedConfig, _isolated, _requested, onPersistenceStarted, _callId, hidden) => {
+ onPersistenceStarted();
+ f.tasks.set(taskId, { taskId, title, resolvedConfig, revision: 1, status: 'active', permissionMode: 'plan', hidden: hidden === true });
+ });
+ f.deps.setHidden = vi.fn(async (taskId: string, hidden: boolean, assertAllowed: () => void) => {
+ assertAllowed();
+ f.tasks.set(taskId, { ...f.tasks.get(taskId)!, hidden });
+ });
+ return { ...f, undeclare: () => { declared = false; } };
+ };
+
+ it('creates a hidden task in the same creation call and reports hidden in get/list snapshots', async () => {
+ const f = declaredFixture();
+ const task = await f.service.create('p', { requestKey: 'bg', title: 'Background', hidden: true });
+ expect(task.hidden).toBe(true);
+ expect(f.deps.createSession).toHaveBeenCalledWith('p', task.taskId, 'Background', f.route, undefined, undefined, expect.any(Function), undefined, true);
+ expect((await f.service.get('p', task.taskId)).hidden).toBe(true);
+ expect((await f.service.list('p')).items.map(item => item.hidden)).toEqual([true]);
+ // Exact replay reads the same task; the hidden flag is part of the request fingerprint.
+ expect((await f.service.create('p', { requestKey: 'bg', title: 'Background', hidden: true })).taskId).toBe(task.taskId);
+ await expect(f.service.create('p', { requestKey: 'bg', title: 'Background' })).rejects.toMatchObject({ code: 'IDEMPOTENCY_CONFLICT' });
+ });
+
+ it('keeps visible creation unchanged: hidden=false snapshot and the legacy fingerprint', async () => {
+ const f = declaredFixture();
+ const task = await f.service.create('p', { requestKey: 'plain', title: 'Plain', hidden: false });
+ expect(task.hidden).toBe(false);
+ expect((await f.service.create('p', { requestKey: 'plain', title: 'Plain' })).taskId).toBe(task.taskId);
+ // Views without the field (older readers) are normalized to a boolean.
+ const legacy = fixture();
+ expect((await legacy.create()).hidden).toBe(false);
+ });
+
+ it('switches only its own task, rechecks the declaration and skips no-op writes', async () => {
+ const f = declaredFixture();
+ const task = await f.service.create('p', { requestKey: 'own', title: 'Own' });
+ expect((await f.service.setHidden('p', { taskId: task.taskId, hidden: true })).hidden).toBe(true);
+ expect((await f.service.setHidden('p', { taskId: task.taskId, hidden: true })).hidden).toBe(true);
+ expect(f.deps.setHidden).toHaveBeenCalledTimes(1);
+ expect((await f.service.setHidden('p', { taskId: task.taskId, hidden: false })).hidden).toBe(false);
+ await expect(f.service.setHidden('other', { taskId: task.taskId, hidden: true })).rejects.toMatchObject({ code: 'TASK_NOT_FOUND' });
+ await expect(f.service.setHidden('p', { taskId: 'missing', hidden: true })).rejects.toMatchObject({ code: 'TASK_NOT_FOUND' });
+ f.undeclare();
+ await expect(f.service.setHidden('p', { taskId: task.taskId, hidden: true })).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ await expect(f.service.create('p', { requestKey: 'later', title: 'Later', hidden: true })).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ expect(f.deps.setHidden).toHaveBeenCalledTimes(2);
+ });
+
+ it('denies background tasks when the host has no declaration check wired', async () => {
+ const f = fixture();
+ await expect(f.service.create('p', { requestKey: 'bg', title: 'Background', hidden: true })).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ expect(f.deps.createSession).not.toHaveBeenCalled();
+ });
+
+ it('reveals background tasks before revoking ownership on uninstall, and aborts when reveal fails', async () => {
+ const f = declaredFixture();
+ const order: string[] = [];
+ f.deps.revealPluginTasks = vi.fn(async () => { order.push('reveal'); });
+ const revoke = vi.spyOn(f.deps.store, 'revokePlugin').mockImplementation(async () => { order.push('revoke'); });
+ await f.service.withUninstall('p', async () => { order.push('remove'); });
+ expect(order).toEqual(['reveal', 'revoke', 'remove']);
+ f.deps.revealPluginTasks = vi.fn(async () => { throw new Error('db'); });
+ const remove = vi.fn(async () => {});
+ await expect(f.service.withUninstall('p', remove)).rejects.toThrow('db');
+ expect(revoke).toHaveBeenCalledTimes(1);
+ expect(remove).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/pluginHiddenTasks.ts b/apps/desktop/src/main/maker-ipc/pluginHiddenTasks.ts
new file mode 100644
index 0000000000..092a54ab8d
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/pluginHiddenTasks.ts
@@ -0,0 +1,140 @@
+import { and, desc, eq, isNotNull, ne, sql } from 'drizzle-orm';
+import type { DbClient } from '../localDb/client/DbClient.js';
+import { pluginTaskRequests, sessions } from '../localDb/schema.js';
+import type { PluginBackgroundTask } from '../../shared/pluginTasks.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+
+/** 插件详情页「后台任务」一次最多列出的条数(按最后活动时间倒序)。 */
+export const PLUGIN_BACKGROUND_TASK_LIST_LIMIT = 1000;
+
+/** 与 pluginTaskStore.list 同一判据:创建回执合法且未被卸载撤销归属。 */
+const OWNED_RECEIPT_SQL = sql`(json_valid(${pluginTaskRequests.payload})
+ AND json_type(${pluginTaskRequests.payload}) = 'object'
+ AND coalesce(json_type(${pluginTaskRequests.payload}, '$.ownershipRevoked'), 'null') != 'true')`;
+
+/**
+ * 本插件经创建回执拥有、当前处于后台隐藏(hidden_at 非空)且未删除的普通任务。
+ * 只认 create 回执,不按 source='plugin' 一刀切;Worker 与远程任务没有创建回执,天然不在其中。
+ */
+export async function selectPluginHiddenTaskRows(
+ db: DbClient,
+ pluginId: string,
+ options: { taskId?: string; limit?: number } = {},
+): Promise<Array<{ taskId: string; title: string; status: string; updatedAt: number }>> {
+ return db.drizzle
+ .select({
+ taskId: sessions.id,
+ title: sessions.title,
+ status: sessions.status,
+ updatedAt: sessions.updatedAt,
+ })
+ .from(sessions)
+ .innerJoin(pluginTaskRequests, eq(pluginTaskRequests.id, sessions.id))
+ .where(and(
+ eq(pluginTaskRequests.pluginId, pluginId),
+ eq(pluginTaskRequests.operation, 'create'),
+ eq(sessions.source, 'plugin'),
+ isNotNull(sessions.hiddenAt),
+ ne(sessions.status, 'deleted'),
+ options.taskId ? eq(sessions.id, options.taskId) : undefined,
+ OWNED_RECEIPT_SQL,
+ ))
+ .orderBy(desc(sessions.updatedAt), desc(sessions.id))
+ .limit(options.limit ?? PLUGIN_BACKGROUND_TASK_LIST_LIMIT);
+}
+
+/**
+ * 卸载前把本插件的全部后台任务恢复显示(不受列表展示上限约束):分批查询并逐条
+ * reveal,直到查不到隐藏任务。已恢复过的任务再次出现说明 reveal 没生效,直接抛错,
+ * 不死循环;maxBatches(默认 1000)再兜一层上限。
+ */
+export async function revealAllPluginHiddenTasks(
+ db: DbClient,
+ pluginId: string,
+ reveal: (taskId: string) => Promise<unknown>,
+ options: { batchSize?: number; maxBatches?: number } = {},
+): Promise<void> {
+ const batchSize = options.batchSize ?? PLUGIN_BACKGROUND_TASK_LIST_LIMIT;
+ const maxBatches = options.maxBatches ?? 1000;
+ const attempted = new Set<string>();
+ for (let batch = 0; batch < maxBatches; batch += 1) {
+ const rows = await selectPluginHiddenTaskRows(db, pluginId, { limit: batchSize });
+ if (rows.length === 0) return;
+ for (const row of rows) {
+ if (attempted.has(row.taskId)) {
+ throw new Error(`Plugin background task ${row.taskId} is still hidden after reveal`);
+ }
+ attempted.add(row.taskId);
+ await reveal(row.taskId);
+ }
+ }
+ throw new Error(`Plugin background tasks still hidden after ${maxBatches} batches`);
+}
+
+export interface PluginBackgroundTaskDeps {
+ /** 当前账号数据库;未就绪返回 null。 */
+ currentDb(): DbClient | null;
+ /** 插件是否仍安装在当前账号下(停用的插件也要能查看与接手后台任务)。 */
+ isInstalled(pluginId: string): boolean;
+ isRunning(taskId: string): boolean;
+ setHidden(input: {
+ sessionId: string;
+ hidden: boolean;
+ db: DbClient;
+ assertCurrent: () => void;
+ }): Promise<boolean>;
+}
+
+function requireId(value: unknown, name: string): string {
+ if (typeof value !== 'string' || !value.trim() || value.length > 256) {
+ throwIpcError('INVALID_PARAMS', `${name} must be a non-empty string`);
+ }
+ return value;
+}
+
+/**
+ * 详情页「后台任务」的两个本机 IPC 业务体(列表 / 显示到任务列表)。
+ * 透明性兜底:插件停用后同样可见;只经 Desktop 可信窗口调用,不登记 device-link。
+ */
+export function createPluginBackgroundTaskHandlers(deps: PluginBackgroundTaskDeps) {
+ const requireDb = (pluginId: string): DbClient => {
+ const db = deps.currentDb();
+ if (!db) throwIpcError('PRECONDITION_FAILED', 'Task storage is unavailable');
+ if (!deps.isInstalled(pluginId)) throwIpcError('NOT_FOUND', 'Plugin is not installed');
+ return db;
+ };
+ return {
+ list: async (rawPluginId: unknown): Promise<{ items: PluginBackgroundTask[] }> => {
+ const pluginId = requireId(rawPluginId, 'pluginId');
+ const db = requireDb(pluginId);
+ const rows = await selectPluginHiddenTaskRows(db, pluginId);
+ if (deps.currentDb() !== db) throwIpcError('PRECONDITION_FAILED', 'Account changed');
+ return {
+ items: rows.map((row) => ({
+ taskId: row.taskId,
+ title: row.title,
+ status: row.status === 'archived' ? 'archived' : 'active',
+ updatedAt: row.updatedAt,
+ running: deps.isRunning(row.taskId),
+ })),
+ };
+ },
+ reveal: async (rawPluginId: unknown, rawTaskId: unknown): Promise<{ ok: true }> => {
+ const pluginId = requireId(rawPluginId, 'pluginId');
+ const taskId = requireId(rawTaskId, 'taskId');
+ const db = requireDb(pluginId);
+ const [row] = await selectPluginHiddenTaskRows(db, pluginId, { taskId });
+ // 已经显示(或被别处显示)视为成功:用户意图已达成,列表刷新即可。
+ if (!row) return { ok: true };
+ await deps.setHidden({
+ sessionId: taskId,
+ hidden: false,
+ db,
+ assertCurrent: () => {
+ if (deps.currentDb() !== db) throwIpcError('PRECONDITION_FAILED', 'Account changed');
+ },
+ });
+ return { ok: true };
+ },
+ };
+}
diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
index 75d1a30384..7250e828f7 100644
--- a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
+++ b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
@@ -108,7 +108,21 @@ export interface PluginTaskServiceDeps {
requestedRoute: PluginTaskRoute | undefined,
onPersistenceStarted: () => void,
callId?: string,
+ /** Background task: the Session row is inserted with hidden_at set (never flashes into lists). */
+ hidden?: boolean,
): Promise<void>;
+ /**
+ * Re-checks `agent.hiddenTasks` (with tasks) for this plugin; throws PERMISSION_DENIED.
+ * The pipe checks first; the service re-checks behind its receipt queue.
+ */
+ assertHiddenTasksAllowed?(pluginId: string): void;
+ /**
+ * Shared Host writer for `sessions.hidden_at` (plugin setHidden and the detail-page reveal).
+ * `assertAllowed` runs synchronously right before the write.
+ */
+ setHidden?(taskId: string, hidden: boolean, assertAllowed: () => void): Promise<void>;
+ /** Uninstall fallback: reveal this plugin's background tasks before ownership is revoked. */
+ revealPluginTasks?(pluginId: string): Promise<void>;
setModel?(taskId: string, route: PluginTaskRoute, assertCurrent: () => Promise<void>): Promise<{ status: string }>;
readSession(taskId: string): Promise<PluginTaskView | null>;
assertTeamPlanUnstarted?(taskId: string): Promise<void>;
@@ -153,6 +167,10 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
operations = Promise.all([operations, result.catch(() => undefined)]).then(() => undefined);
return result;
};
+ const assertHiddenTasksAllowed = (pluginId: string) => {
+ if (!deps.assertHiddenTasksAllowed) fail('PERMISSION_DENIED', 'Background tasks are unavailable');
+ deps.assertHiddenTasksAllowed!(pluginId);
+ };
const assertDispatch = async (pluginId: string, taskId: string) => {
const view = await ownTask(pluginId, taskId);
deps.assertAuthorized(pluginId);
@@ -178,7 +196,7 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
return fail('TASK_NOT_FOUND', 'Task not found');
deps.assertCurrent();
deps.assertAuthorized(pluginId);
- return view;
+ return { ...view, hidden: view.hidden === true };
};
const ownRun = async (pluginId: string, runId: string) => {
const row = await deps.store.get(runId);
@@ -240,6 +258,10 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
completeOperation,
/** Retain receipts and user content, but never reuse an uninstalled installation's ownership. */
withUninstall: (pluginId: string, remove: () => Promise<void>) => exclusive(async () => {
+ // Background tasks must never outlive the detail page that discloses them.
+ // Reveal first: a failure aborts the uninstall like a failed revocation.
+ await deps.revealPluginTasks?.(pluginId);
+ deps.assertCurrent();
await deps.store.revokePlugin(pluginId);
deps.assertCurrent();
await remove();
@@ -254,11 +276,15 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
},
create: (
pluginId: string,
- request: { requestKey: string; title: string; route?: PluginTaskRoute; isolatedWorkspace?: boolean; callId?: string },
+ request: { requestKey: string; title: string; route?: PluginTaskRoute; isolatedWorkspace?: boolean; callId?: string; hidden?: boolean },
) =>
exclusive(async () => {
deps.assertAuthorized(pluginId);
- const input = [request.title, request.route ?? null, ...(request.isolatedWorkspace ? [true] : []), ...(request.callId ? [{ callId: request.callId }] : [])];
+ const hidden = request.hidden === true;
+ if (hidden) assertHiddenTasksAllowed(pluginId);
+ // hidden:false is the default; only a background request changes the fingerprint,
+ // so existing visible receipts replay unchanged.
+ const input = [request.title, request.route ?? null, ...(request.isolatedWorkspace ? [true] : []), ...(request.callId ? [{ callId: request.callId }] : []), ...(hidden ? [{ hidden: true }] : [])];
const fingerprint = hash(input);
let row = replay(
await deps.store.find(pluginId, 'create', '', request.requestKey),
@@ -286,8 +312,16 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
let persistenceStarted = false;
try {
deps.assertCurrent();
- await deps.createSession(pluginId, taskId, request.title, route, request.isolatedWorkspace, request.route,
- () => { persistenceStarted = true; }, request.callId);
+ const onPersistenceStarted = () => { persistenceStarted = true; };
+ // Visible creation keeps its original call shape; only background tasks add the flag.
+ if (hidden) {
+ assertHiddenTasksAllowed(pluginId);
+ await deps.createSession(pluginId, taskId, request.title, route, request.isolatedWorkspace, request.route,
+ onPersistenceStarted, request.callId, true);
+ } else {
+ await deps.createSession(pluginId, taskId, request.title, route, request.isolatedWorkspace, request.route,
+ onPersistenceStarted, request.callId);
+ }
} catch (error) {
// Once INSERT starts, even an error is ambiguous. Never free that key
// or infer failure from a subsequently deleted/filtered Session.
@@ -335,6 +369,20 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
return { ...result, task: await ownTask(pluginId, request.taskId) };
}),
get: (pluginId: string, taskId: string) => exclusive(() => ownTask(pluginId, taskId)),
+ /** Background/visible switch for this plugin's own local task; Workers and remote tasks are not plugin tasks. */
+ setHidden: (pluginId: string, request: { taskId: string; hidden: boolean }) => exclusive(async () => {
+ assertHiddenTasksAllowed(pluginId);
+ const task = await ownTask(pluginId, request.taskId);
+ if (!deps.setHidden) return fail('HOST_NOT_READY', 'Task visibility service is not ready');
+ if (task.hidden !== request.hidden) {
+ await deps.setHidden(request.taskId, request.hidden, () => {
+ deps.assertCurrent();
+ deps.assertAuthorized(pluginId);
+ assertHiddenTasksAllowed(pluginId);
+ });
+ }
+ return ownTask(pluginId, request.taskId);
+ }),
list: (pluginId: string, after = '', limit = 50) =>
exclusive(async () => {
deps.assertAuthorized(pluginId);
@@ -344,7 +392,7 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
// The store projects valid create payloads as empty to avoid loading plans.
if (row.payload !== '' && !ownsTaskReceipt(row, pluginId)) continue;
const view = await deps.readSession(row.id);
- if (view && view.status !== 'deleted') items.push(view);
+ if (view && view.status !== 'deleted') items.push({ ...view, hidden: view.hidden === true });
}
return { items, nextCursor: rows.length === limit ? rows.at(-1)!.id : null };
}),
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 4f7bfe3a06..23924222fb 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -9,6 +9,10 @@ import { assertPluginWorkerDirectoryScope, resolvePluginWorkerDirectory } from '
import { PluginWriteAccessGate } from './pluginWriteAccessGate.js';
import { pluginWorkerCompletedAt } from './pluginWorkerCompletion.js';
import { createPluginTaskStore } from './pluginTaskStore.js';
+import { createPluginBackgroundTaskHandlers, revealAllPluginHiddenTasks } from './pluginHiddenTasks.js';
+import { setSessionHidden } from '../localDb/ipc/sessionHidden.js';
+import { isSessionHiddenSync } from '../localDb/hiddenSessionRegistry.js';
+import { ghostDeclaresHiddenTasks } from '../../shared/ghost.js';
import { hasAcceptedUserTaskInput } from './pluginTaskInput.js';
import { controlOwnedSessionExecution, isSameSessionExecution, withdrawOwnedSessionInputs } from './sessionExecutionOwnership.js';
import { showMobilePluginTaskPermission, setPluginTaskHandler, getPluginTaskSourceSessionId, setPluginTaskUninstaller, setPluginTaskRelocator, isPluginTaskAuthorized, getPluginTaskInstallRevision, pluginTaskAuthorizationRevision } from '../cindy-brain/index.js';
@@ -4783,6 +4787,8 @@ function handleAgentIslandSessionStopped(
}
function shouldNotifyAgentIslandForSession(sessionId: string): boolean {
+ // 插件后台隐藏任务不在灵动岛/菜单栏展示运行中,也不提醒(显示到任务列表后恢复)。
+ if (isSessionHiddenSync(sessionId)) return false;
return shouldNotifyAgentIslandForSessionByPolicy(
AGENT_ISLAND_DISPLAY_CONFIG,
isKnownOrcaWorkerSession(sessionId),
@@ -12477,7 +12483,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
assertCurrent();
if (workers.length || reservations.length) throw new PluginTaskError('TASK_BUSY', 'Register the team plan before creating Workers');
},
- createSession: async (pluginId, taskId, title, route, isolatedWorkspace, requestedRoute, onPersistenceStarted, callId) => {
+ createSession: async (pluginId, taskId, title, route, isolatedWorkspace, requestedRoute, onPersistenceStarted, callId, hidden) => {
assertPlugin(pluginId);
const cfg = readPluginTaskConfig(pluginId);
const configurationIsCurrent = () => {
@@ -12510,13 +12516,30 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
onPersistenceStarted,
permissionMode: clampPluginTaskPermissionMode(cfg.permissionMode),
...(workingDir ? { workingDir } : {}),
- shouldContinue: () => getCurrentDbClientSnapshot() === snapshot && isPluginTaskAuthorized(pluginId) && configurationIsCurrent(),
+ ...(hidden ? { hidden: true } : {}),
+ shouldContinue: () => getCurrentDbClientSnapshot() === snapshot && isPluginTaskAuthorized(pluginId) && configurationIsCurrent()
+ && (!hidden || ghostDeclaresHiddenTasks(findGhostForInstanceId(pluginId)?.manifest)),
notifySessionCreated: ({ sessionId, workdir }) => {
+ // 插件订阅口径不因隐藏改变(isGhostEligibleSessionRow);后台任务不发「新建」推送,
+ // 不进侧栏、手机列表与新任务通知。
notifyGhostSessionEvent('created', { sessionId, workdir });
- broadcastSessionCreated(sessionId);
+ if (!hidden) broadcastSessionCreated(sessionId);
},
});
},
+ assertHiddenTasksAllowed: pluginId => {
+ assertPlugin(pluginId);
+ if (!ghostDeclaresHiddenTasks(findGhostForInstanceId(pluginId)?.manifest))
+ throw new PluginTaskError('PERMISSION_DENIED', 'Background tasks require agent.hiddenTasks in ghost.json');
+ },
+ setHidden: async (taskId, hidden, assertAllowed) => {
+ await setSessionHidden({ sessionId: taskId, hidden, db: snapshot.client, assertCurrent: assertAllowed });
+ },
+ revealPluginTasks: async pluginId => {
+ // 不受详情页列表的展示上限约束:分批恢复全部,避免卸载撤销归属后仍有任务隐藏。
+ await revealAllPluginHiddenTasks(snapshot.client, pluginId, taskId =>
+ setSessionHidden({ sessionId: taskId, hidden: false, db: snapshot.client, assertCurrent }));
+ },
readSession: async taskId => {
assertCurrent();
const [row] = await snapshot.client.drizzle.select().from(sessions).where(eq(sessions.id, taskId)).limit(1);
@@ -12533,7 +12556,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
effort: selected.effort ?? '', fastMode: selected.fastMode }
: { agentKind: row.agentKind as PluginTaskRoute['agentKind'], providerId: row.providerId ?? '', model: row.model, effort: row.effort, fastMode: row.fastMode };
const revision = Number.parseInt(pluginTaskConfigHash('sha256').update(JSON.stringify([resolvedConfig, row.permissionMode, row.planModeEnabled, row.workingDir, row.status, row.orcaRole])).digest('hex').slice(0, 12), 16);
- return { taskId, title: row.title, status: row.status, revision, resolvedConfig, workingDir: row.workingDir ?? undefined, permissionMode: row.permissionMode, planModeEnabled: !!row.planModeEnabled };
+ return { taskId, title: row.title, status: row.status, revision, resolvedConfig, workingDir: row.workingDir ?? undefined, permissionMode: row.permissionMode, planModeEnabled: !!row.planModeEnabled, hidden: row.hiddenAt != null };
},
dispatch: async (pluginId, taskId, clientId, text) => {
assertPlugin(pluginId);
@@ -12865,6 +12888,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
case 'setModel': return service.setModel(pluginId, request);
case 'create': return service.create(pluginId, request);
case 'get': return service.get(pluginId, request.taskId);
+ case 'setHidden': return service.setHidden(pluginId, request);
case 'list': return service.list(pluginId, request.after, request.limit);
case 'send': return service.send(pluginId, request);
case 'readMessages': {
@@ -12932,6 +12956,27 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
ipcMain.handle('maker:get-plugin-write-access-recovery', (event, taskId: unknown) => pluginWriteAccessFromHost(event, taskId, false));
ipcMain.handle('maker:retry-plugin-write-access', (event, taskId: unknown) => pluginWriteAccessFromHost(event, taskId, true));
+ // 插件详情页「后台任务」:只服务本机可信窗口(打开/显示到任务列表都是本机 UI 动作),
+ // 不登记 device-link;停用的插件同样可查,透明性不依赖插件仍可运行。
+ const pluginBackgroundTasks = createPluginBackgroundTaskHandlers({
+ currentDb: () => getCurrentDbClientSnapshot()?.client ?? null,
+ isInstalled: pluginId => findGhostForInstanceId(pluginId) !== null,
+ isRunning: taskId => maker.getSession(taskId)?.isTurnRunning() === true,
+ setHidden: input => setSessionHidden(input),
+ });
+ const assertLocalBackgroundTaskUi = (event: Electron.IpcMainInvokeEvent) => {
+ if (isDeviceLinkInvoke()) throwIpcError('PERMISSION_DENIED', 'Local task UI required');
+ assertTrustedAppRendererEvent(event);
+ };
+ ipcMain.handle('ghosts:background-tasks:list', (event, pluginId: unknown) => {
+ assertLocalBackgroundTaskUi(event);
+ return pluginBackgroundTasks.list(pluginId);
+ });
+ ipcMain.handle('ghosts:background-tasks:reveal', (event, pluginId: unknown, taskId: unknown) => {
+ assertLocalBackgroundTaskUi(event);
+ return pluginBackgroundTasks.reveal(pluginId, taskId);
+ });
+
// Legacy result-returning adapter; ordinary task configuration lives above.
setGhostErrandRunner(
createGhostErrandRunner({
@@ -12970,7 +13015,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
notifySessionCreated: (info) => notifyGhostSessionEvent('created', info),
});
// errand 会话在侧边栏可见(与 workspace 槽同通道刷新)——透明是这个
- // 能力的安全边界之一,不做隐藏会话。
+ // 能力的安全边界之一,errand 不支持隐藏。普通任务只有声明 agent.hiddenTasks
+ // 才能转入后台,且用户始终能在插件详情页「后台任务」查看与接手。
broadcastSessionCreated(sessionId);
return sessionId;
},
diff --git a/apps/desktop/src/main/right-sidebar-window/__tests__/preload-contract.test.ts b/apps/desktop/src/main/right-sidebar-window/__tests__/preload-contract.test.ts
index 095879b054..f67d119547 100644
--- a/apps/desktop/src/main/right-sidebar-window/__tests__/preload-contract.test.ts
+++ b/apps/desktop/src/main/right-sidebar-window/__tests__/preload-contract.test.ts
@@ -224,7 +224,7 @@ describe('sidebarWindowPreload 椤跺眰濂戠害', () => {
}
for (const key of [
'install', 'uninstall', 'inspect', 'devRuntime', 'devCall',
- 'approve', 'revokeApproval', 'setCindyPref', 'listCardsBySession',
+ 'approve', 'revokeApproval', 'setErrandConfig', 'listCardsBySession',
]) {
expect(ghostKeys).not.toEqual(expect.arrayContaining([key]));
}
diff --git a/apps/desktop/src/main/utility-model/oneshotProviderUsability.ts b/apps/desktop/src/main/utility-model/oneshotProviderUsability.ts
index b67b96c4b1..4ed1cbc1e8 100644
--- a/apps/desktop/src/main/utility-model/oneshotProviderUsability.ts
+++ b/apps/desktop/src/main/utility-model/oneshotProviderUsability.ts
@@ -4,7 +4,7 @@ import { codexAccountState } from '../maker-host/codex-account-auth.js';
*
* 钉档清单只应列出**当下真能跑**的 (供应商 × agent):用户没配 key / 没登录的
* 供应商,钉上只会在执行期 fail-closed(NO_CANDIDATE)——给一个选了就没用的
- * 选项是清单的失职。这里全部走同步缓存态(cindy-prefs 读 handler 是 sendSync,
+ * 选项是清单的失职。这里全部走同步缓存态(读 handler 是 sendSync,
* 不能 async);它是展示层过滤,不是安全边界——执行侧仍逐候选现查现验。
*/
import { storedCustomProviderId, type AgentKind, type Provider } from '@cindy/model-providers';
diff --git a/apps/desktop/src/main/utility-model/textOneshotPinOptions.ts b/apps/desktop/src/main/utility-model/textOneshotPinOptions.ts
index f2ee23739b..a00992f9cf 100644
--- a/apps/desktop/src/main/utility-model/textOneshotPinOptions.ts
+++ b/apps/desktop/src/main/utility-model/textOneshotPinOptions.ts
@@ -1,19 +1,16 @@
import { isOpenAiSubscriptionProvider } from '@cindy/model-providers';
/**
- * textOneshotPinOptions.ts — 快问快答(text.oneshot)钉档的目录模型清单与路由解析。
+ * textOneshotPinOptions.ts — 快问快答(text.oneshot)可选目录模型清单与路由解析。
*
- * 背景(2026-08-05 与刘佳黎定稿):钉档可选项从 9 个轻量档位扩展为**当前供应商
- * 目录里的全部文本模型**——用户安装插件即承担其成本,主机在安装/详情页如实
- * 展示可选面,不再用一份小清单替用户做成本决定。
+ * 可选项是**当前供应商目录里的全部文本模型**(2026-08-05 与刘佳黎定稿)——用户
+ * 安装插件即承担其成本,主机如实展示可选面。目录钉('cat:' 编码)精确钉死一组
+ * 供应商×agent×模型,系统辅助模型设置沿用这一编码。
*
- * 钉值两种形态(消费方都要认):
- * - 轻量档位键(如 'litellm-kimi-k2.6',见 utilityModelProfiles):随系统链演进
- * 的逻辑档位,覆盖表里的既有形态;
- * - 目录钉(本文件 'cat:' 编码):精确钉死一组 供应商×agent×模型。
- *
- * 插件还可在身份卡 `cindy.oneshotModel` 声明**偏好**模型 id(目录模型,如
- * 'codex/gpt-5.5'):解析优先级 = 用户钉档 > 插件声明 > 系统默认链。声明只表达
- * 意图——目录没有 / 已停用 / 不可路由时按未声明处理,绝不构成硬依赖。
+ * 插件详情的「模型」字段与插件新建任务共用 pluginTaskPrefsStore(2026-10 合并,
+ * 旧的逐能力钉档已迁移);插件还可在身份卡 `cindy.oneshotModel` 声明**偏好**
+ * 模型 id(目录模型,如 'codex/gpt-5.5'):解析优先级 = 用户选的模型 > 插件声明 >
+ * 系统辅助模型链。声明只表达意图——目录没有 / 已停用 / 不可路由时按未声明处理,
+ * 绝不构成硬依赖。
*
* 纯逻辑、零 Electron:被 cindySlot(类型)与 IPC 接线共用,单测直测。
*/
@@ -46,10 +43,16 @@ const ONESHOT_ROUTE_AGENTS = ['codex', 'claude-code'] as const;
*/
const ONESHOT_EXECUTABLE_BUILTIN_PROVIDERS = new Set(['xd', 'openai', 'xai']);
-/** 一次快问快答的路由:用户钉档或插件声明解析出的终态。 */
-export type OneshotRoute =
- | { kind: 'utility-profile'; profileId: string }
- | { kind: 'catalog'; providerId: string; agentKind: AgentKind; model: string };
+/**
+ * 一次快问快答的路由:用户在插件详情选的模型或插件声明解析出的终态。
+ * providerId 缺省时由执行侧按 agent×模型唯一推断,推断不出即 fail closed。
+ */
+export type OneshotRoute = {
+ kind: 'catalog';
+ providerId?: string;
+ agentKind: AgentKind;
+ model: string;
+};
/** 目录钉编码:cat:<providerId>:<agentKind>:<modelId>(modelId 可含 '/' 与 ':')。 */
export function encodeCatalogPin(providerId: string, agentKind: AgentKind, model: string): string {
diff --git a/apps/desktop/src/preload/ghostPreload.ts b/apps/desktop/src/preload/ghostPreload.ts
index dbcc663716..e36e5e462c 100644
--- a/apps/desktop/src/preload/ghostPreload.ts
+++ b/apps/desktop/src/preload/ghostPreload.ts
@@ -68,7 +68,7 @@ contextBridge.exposeInMainWorld('cindy', {
library: (req: Record<string, unknown>): Promise<unknown> =>
ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'library-request' }),
tasks: Object.fromEntries(
- ['capabilities', 'models', 'setModel', 'requestWriteAccess', 'startTeam', 'getTeam', 'setTeamPlan', 'releaseWorker', 'create', 'list', 'get', 'send', 'getRun', 'listRuns', 'cancel', 'readMessages'].map(kind => [
+ ['capabilities', 'models', 'setModel', 'requestWriteAccess', 'startTeam', 'getTeam', 'setTeamPlan', 'releaseWorker', 'create', 'list', 'get', 'send', 'getRun', 'listRuns', 'cancel', 'readMessages', 'setHidden'].map(kind => [
kind, async (req: Record<string, unknown> = {}): Promise<unknown> => {
const result = await ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'tasks-request', kind });
if (result?.ok === true) return result.data;
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 828618340c..05b1dfa9c1 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1042,22 +1042,6 @@ const appearanceSettingsInfo = ipcRenderer.sendSync(
'appearance-settings:get-sync',
) as AppearanceSettings | null;
-type CindyMediaPreferenceOption = {
- id: string;
- label: string;
- group: string;
- providerId: string;
- providerName: string;
- modelId: string;
- modelName: string;
- routing?: import('@cindy/model-providers').Provider['routing'];
-};
-
-type CindyMediaPreferenceKind = {
- options: CindyMediaPreferenceOption[];
- defaultModel: CindyMediaPreferenceOption | null;
-};
-
contextBridge.exposeInMainWorld('electronAPI', {
modelFavoritesHost: {
ready: () => ipcRenderer.send(FAVORITE_HOST_READY),
@@ -1314,54 +1298,13 @@ contextBridge.exposeInMainWorld('electronAPI', {
expectedInstalledInstanceId: string;
},
): Promise<{ ghost: unknown }> => ipcRenderer.invoke('ghosts:update', lizFilePath, opts),
- cindyPrefsSync: (
- id: string,
- ): {
- overrides: Record<string, string>;
- /**
- * 每类目一份下拉数据(能力键按类目取对应清单)。
- * options 为空或 defaultModel 为 null = 目录没给该类目模型,能力暂不可用。
- */
- image: CindyMediaPreferenceKind;
- imageEdit: CindyMediaPreferenceKind;
- video: CindyMediaPreferenceKind;
- videoEdit: CindyMediaPreferenceKind;
- /** 文本类(快问快答):选项是当前供应商目录的全部文本模型(cat: 编码钉值,
- * 带供应商/模型/徽标等结构化字段供富列表渲染);declaredModel = 身份卡声明
- * 的偏好模型;utilityProfiles = 存量轻量档位钉的展示名表(老钉值回显用)。 */
- text: {
- options: Array<{
- id: string;
- label: string;
- group: string;
- providerId: string;
- agentKind: string;
- modelId: string;
- modelName: string;
- icon?: string;
- budget: boolean;
- subscription: boolean;
- routing?: import('@cindy/model-providers').Provider['routing'];
- agentSuffix?: string;
- }>;
- defaultModel: { id: string; label: string } | null;
- declaredModel?: { id: string; label: string } | null;
- utilityProfiles?: Array<{ id: string; label: string }>;
- };
- /** 向量类(文本转向量):同 image/video 走目录派生。 */
- embed: {
- options: Array<{ id: string; label: string }>;
- defaultModel: { id: string; label: string } | null;
- };
- } => ipcRenderer.sendSync('ghosts:cindy-prefs', id),
- setCindyPref: (
+ /**
+ * 插件「模型与任务」配置(快问快答与插件新建任务共用;sendSync 首帧同帧渲染)。
+ * auxiliaryModelLabel = 当前系统辅助模型的显示名(未选模型时快问快答跟随它)。
+ */
+ errandPrefsSync: (
id: string,
- capability: string,
- model: string | null,
- ): Promise<{ overrides: Record<string, string> }> =>
- ipcRenderer.invoke('ghosts:cindy-prefs:set', id, capability, model),
- /** 派活(errand)每插件配置(插件详情页「AI 代办」卡;sendSync 首帧同帧渲染)。 */
- errandPrefsSync: (id: string): { config: Record<string, unknown> } =>
+ ): { config: Record<string, unknown>; auxiliaryModelLabel?: string | null } =>
ipcRenderer.sendSync('ghosts:errand-prefs', id),
setErrandConfig: (
id: string,
@@ -1398,6 +1341,13 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('ghosts:set-enabled', id, enabled, expectedInstalledApproval),
requestTaskApproval: (id: string): Promise<{ granted: boolean }> =>
ipcRenderer.invoke('ghosts:request-task-approval', id),
+ /** 详情页「后台任务」:本插件转入后台的任务(仅本机窗口,不进 device-link)。 */
+ listBackgroundTasks: (id: string): Promise<{
+ items: Array<{ taskId: string; title: string; status: 'active' | 'archived'; updatedAt: number; running: boolean }>;
+ }> => ipcRenderer.invoke('ghosts:background-tasks:list', id),
+ /** 「显示到任务列表」:与插件 cindy.tasks.setHidden 共用宿主写入口。 */
+ revealBackgroundTask: (id: string, taskId: string): Promise<{ ok: true }> =>
+ ipcRenderer.invoke('ghosts:background-tasks:reveal', id, taskId),
/** 目录级禁用清单(插件页项目范围视图;sendSync 保证切换同帧渲染)。 */
workdirPrefsSync: (workdir: string): { disabled: string[] } =>
ipcRenderer.sendSync('ghosts:workdir-prefs', workdir),
diff --git a/apps/desktop/src/renderer/__tests__/sessionEventNotification.test.ts b/apps/desktop/src/renderer/__tests__/sessionEventNotification.test.ts
index 5c98b26255..6290462f2e 100644
--- a/apps/desktop/src/renderer/__tests__/sessionEventNotification.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sessionEventNotification.test.ts
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
botOwnedSessionNotificationTitle,
findSessionNotificationSession,
+ isReviewSessionNotificationTarget,
sendSessionEventNotification,
} from '@/lib/sessionEventNotification';
import { applyRemoteSessionActivity, clearRemoteSessionActivity, getRemoteSessionActivity } from '@/features/device-link/remoteSessionActivityStore';
@@ -197,3 +198,22 @@ describe('shared session event notifications', () => {
);
});
});
+
+describe('tasks omitted from the task list', () => {
+ afterEach(() => { Reflect.deleteProperty(window, 'electronAPI'); });
+ it('suppresses plugin background tasks resolved from the database, but not visible ones', async () => {
+ const rows: Record<string, unknown> = {
+ bg: { id: 'bg', source: 'plugin', hiddenAt: '2026-10-15T00:00:00.000Z' },
+ shown: { id: 'shown', source: 'plugin', hiddenAt: null },
+ review: { id: 'review', source: 'review' },
+ };
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: { localDb: { sessions: { get: async (id: string) => rows[id] ?? null } } },
+ });
+ expect(await isReviewSessionNotificationTarget('bg')).toBe(true);
+ expect(await isReviewSessionNotificationTarget('review')).toBe(true);
+ expect(await isReviewSessionNotificationTarget('shown')).toBe(false);
+ expect(await isReviewSessionNotificationTarget('missing')).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/sessionsStoreStatusBucketMigration.test.tsx b/apps/desktop/src/renderer/__tests__/sessionsStoreStatusBucketMigration.test.tsx
index bfc2035a44..b3331f0cf6 100644
--- a/apps/desktop/src/renderer/__tests__/sessionsStoreStatusBucketMigration.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/sessionsStoreStatusBucketMigration.test.tsx
@@ -105,6 +105,58 @@ describe('sessionsStore status bucket migration', () => {
expect(patched).toHaveBeenCalledTimes(2);
});
+ it('removes a task moved to the background from every bucket and refetches the loaded buckets', async () => {
+ const hidden = session('plugin-task');
+ const keep = session('keep');
+ mocks.list.mockImplementation(async () => [hidden, keep]);
+ await sessionsStore.ensureByFilter('active');
+ await sessionsStore.ensureByFilter('all');
+ mocks.list.mockReset();
+ mocks.list.mockImplementation(async () => [keep]);
+ const patched = vi.fn();
+ const off = sessionsStore.subscribePatches(patched);
+ const snapshots: string[][] = [];
+ const offStore = sessionsStore.subscribe(() => {
+ const active = sessionsStore.getByFilter('active');
+ if (active) snapshots.push(active.map((row) => row.id));
+ });
+ try {
+ sessionsStore.patchLocal('plugin-task', { hiddenAt: '2026-10-15T00:00:00.000Z' });
+ // The first notification already removed the row in place, before any refetch.
+ expect(snapshots[0]).toEqual(['keep']);
+ expect(sessionsStore.findById('plugin-task')).toBeNull();
+ expect(patched).toHaveBeenCalledWith('plugin-task', { hiddenAt: '2026-10-15T00:00:00.000Z' },
+ expect.objectContaining({ id: 'plugin-task', hiddenAt: '2026-10-15T00:00:00.000Z' }));
+ await waitFor(() => expect(requestedFilters().sort()).toEqual(['active', 'all']));
+ await waitFor(() => expect(sessionsStore.getByFilter('active')?.map((row) => row.id)).toEqual(['keep']));
+ expect(sessionsStore.getByFilter('all')?.map((row) => row.id)).toEqual(['keep']);
+ // A reveal patch alone does not insert a row; the created push refetches instead.
+ sessionsStore.patchLocal('plugin-task', { hiddenAt: null });
+ expect(sessionsStore.findById('plugin-task')).toBeNull();
+ } finally { off(); offStore(); }
+ });
+
+ it('keeps a task hidden when the hide push beats an in-flight list response', async () => {
+ const pending = deferred<Session[]>();
+ mocks.list.mockReturnValueOnce(pending.promise);
+ const loading = sessionsStore.ensureByFilter('active');
+ // Hidden before the first list response lands: nothing is cached yet.
+ sessionsStore.patchLocal('plugin-task', { hiddenAt: '2026-10-15T00:00:00.000Z' });
+ expect(sessionsStore.getByFilter('active')).toBeNull();
+ pending.resolve([session('keep'), session('plugin-task')]);
+ await loading;
+ expect(sessionsStore.getByFilter('active')?.map(({ id }) => id)).toEqual(['keep']);
+ // Local optimistic inserts do not bring it back either.
+ sessionsStore.prependCreated(session('plugin-task'));
+ expect(sessionsStore.findById('plugin-task')).toBeNull();
+
+ // Revealed: later list responses may include it again.
+ sessionsStore.patchLocal('plugin-task', { hiddenAt: null, updatedAt: '2026-10-15T00:01:00.000Z' });
+ mocks.list.mockResolvedValueOnce([session('plugin-task'), session('keep')]);
+ await sessionsStore.forceRefresh('active');
+ expect(sessionsStore.getByFilter('active')?.map(({ id }) => id)).toEqual(['plugin-task', 'keep']);
+ });
+
it('moves a row with an authoritative timestamp into archived and all without querying', async () => {
const target = session('archive-me', 'active', '2026-08-27T00:00:00.000Z');
const keepActive = session('keep-active', 'active', '2026-08-27T00:30:00.000Z');
diff --git a/apps/desktop/src/renderer/cindy-brain/CindyCapabilityPrefs.tsx b/apps/desktop/src/renderer/cindy-brain/CindyCapabilityPrefs.tsx
deleted file mode 100644
index 9a6fbcd705..0000000000
--- a/apps/desktop/src/renderer/cindy-brain/CindyCapabilityPrefs.tsx
+++ /dev/null
@@ -1,452 +0,0 @@
-/**
- * Host-rendered model preferences for Cindy abilities declared by a Plugin.
- * [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
- */
-
-import { useCallback, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Check, ChevronDown, Sparkles } from 'lucide-react';
-
-import { toast } from '@/lib/toast';
-import { cn } from '@/lib/utils';
-import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
-import { ModelIconMark } from '@/components/new-chat/ModelSelector';
-import { OneshotModelPinPicker, type OneshotPinOption } from '@/cindy-brain/OneshotModelPinPicker';
-
-/** 跟随默认在 select 里的哨兵值(覆盖表里"没有这项"= 跟随默认)。 */
-const FOLLOW_DEFAULT_VALUE = '__default__';
-
-interface MediaModelOption {
- id: string;
- modelId: string;
- label: string;
- providerId: string;
- providerName: string;
- routing?: import('@cindy/model-providers').Provider['routing'];
-}
-
-/** 媒体模型沿用原来的轻量下拉,只在模型名前补来源 Provider 图标。 */
-function MediaModelPicker({
- value,
- defaultModel,
- options,
- onChange,
- ariaLabel,
- dense,
-}: {
- value?: string;
- defaultModel: MediaModelOption;
- options: readonly MediaModelOption[];
- onChange: (pin: string | null) => void;
- ariaLabel: string;
- dense?: boolean;
-}) {
- const { t } = useTranslation();
- const [open, setOpen] = useState(false);
- const current = value
- ? options.find((option) => option.id === value) ??
- options.find((option) => option.providerId === 'xd' && option.modelId === value) ??
- options.find((option) => option.modelId === value)
- : undefined;
- const staleValue = value && !current ? value : null;
- const selected = current ?? defaultModel;
- const selectable = options.filter((option) => option.id !== defaultModel.id);
- const triggerLabel =
- current?.label ??
- staleValue ??
- t('settings.ghosts.detail.cindyPrefs.defaultOption', { model: defaultModel.label });
-
- const select = (pin: string | null): void => {
- if (pin !== value) onChange(pin);
- setOpen(false);
- };
-
- const optionClass = (active: boolean): string =>
- cn(
- 'flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left transition-colors',
- 'hover:bg-[var(--model-item-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
- dense ? 'text-12 leading-5' : 'text-13 leading-5',
- active && 'bg-[var(--model-item-hover)]',
- );
-
- return (
- <Popover open={open} onOpenChange={setOpen}>
- <PopoverTrigger asChild>
- <button
- type="button"
- role="combobox"
- aria-label={ariaLabel}
- aria-expanded={open}
- aria-haspopup="listbox"
- className={cn(
- 'flex h-8 w-[300px] max-w-[60%] min-w-0 shrink items-center gap-2 rounded-full border border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] py-0 pl-3 pr-2.5 text-[var(--settings-input-text)] outline-none focus:ring-2 focus:ring-[var(--focus-ring-soft)]',
- dense ? 'text-12' : 'text-13',
- )}
- >
- {!staleValue && (
- <ModelIconMark
- providerId={selected.providerId}
- name={selected.providerName}
- routing={selected.routing}
- withMargin={false}
- dense
- />
- )}
- <span className="min-w-0 flex-1 truncate text-left">{triggerLabel}</span>
- <ChevronDown size={13} className="shrink-0 text-[var(--text-tertiary)]" />
- </button>
- </PopoverTrigger>
- <PopoverContent
- align="end"
- sideOffset={6}
- className="w-[300px] overflow-hidden rounded-xl border border-[var(--model-dropdown-border)] bg-[var(--model-dropdown-bg)] p-1 shadow-[var(--shadow-menu)]"
- >
- <div role="listbox" aria-label={ariaLabel} className="max-h-[300px] overflow-y-auto">
- <button
- type="button"
- role="option"
- aria-selected={value === undefined}
- className={optionClass(value === undefined)}
- onClick={() => select(null)}
- >
- <ModelIconMark
- providerId={defaultModel.providerId}
- name={defaultModel.providerName}
- routing={defaultModel.routing}
- withMargin={false}
- dense
- />
- <span className="min-w-0 flex-1 truncate text-[var(--model-item-text)]">
- {t('settings.ghosts.detail.cindyPrefs.defaultOption', { model: defaultModel.label })}
- </span>
- {value === undefined && (
- <Check size={15} className="shrink-0 text-[var(--model-item-check)]" />
- )}
- </button>
- {selectable.map((option) => {
- const active = value === option.id;
- return (
- <button
- key={option.id}
- type="button"
- role="option"
- aria-selected={active}
- title={option.providerName}
- className={optionClass(active)}
- onClick={() => select(option.id)}
- >
- <ModelIconMark
- providerId={option.providerId}
- name={option.providerName}
- routing={option.routing}
- withMargin={false}
- dense
- />
- <span className="min-w-0 flex-1 truncate text-[var(--model-item-text)]">
- {option.label}
- </span>
- {active && <Check size={15} className="shrink-0 text-[var(--model-item-check)]" />}
- </button>
- );
- })}
- {staleValue && (
- <button
- type="button"
- role="option"
- aria-selected
- className={optionClass(true)}
- onClick={() => select(staleValue)}
- >
- <span className="min-w-0 flex-1 truncate text-[var(--model-item-text)]">
- {staleValue}
- </span>
- <Check size={15} className="shrink-0 text-[var(--model-item-check)]" />
- </button>
- )}
- </div>
- </PopoverContent>
- </Popover>
- );
-}
-
-/**
- * Ghost 申请的每项 Cindy 能力一行,可钉后端(供应商×模型)。
- * Settings 详情与 Plugin 详情共用这一份实现,避免两个入口产生不同配置口径。
- */
-export function CindyCapabilityPrefs({
- ghostId,
- capabilities,
- appearance = 'settings',
-}: {
- ghostId: string;
- /** 能力键全名列表(image.generate / video.edit …,来自身份卡详单)。 */
- capabilities: readonly string[];
- /** Plugin detail aligns the fallback editor with the shared Plugin surface. */
- appearance?: 'settings' | 'plugin';
-}) {
- const { t } = useTranslation();
- const [prefs] = useState(() => window.electronAPI.ghosts.cindyPrefsSync(ghostId));
- const [overrides, setOverrides] = useState<Record<string, string>>(prefs.overrides);
-
- const handleChange = useCallback(
- async (capability: string, value: string) => {
- const model = value === FOLLOW_DEFAULT_VALUE ? null : value;
- const prev = overrides;
- setOverrides((current) => {
- const next = { ...current };
- if (model === null) delete next[capability];
- else next[capability] = model;
- return next;
- });
- try {
- const result = await window.electronAPI.ghosts.setCindyPref(ghostId, capability, model);
- setOverrides(result.overrides);
- return true;
- } catch {
- setOverrides(prev);
- toast.error(t('settings.ghosts.errors.generic'));
- return false;
- }
- },
- [ghostId, overrides, t],
- );
-
- return (
- <div
- className={cn(
- 'cindy-capability-prefs min-w-0 max-w-full flex flex-col gap-3 rounded-xl border px-5 py-4',
- appearance === 'plugin'
- ? 'border-[color-mix(in_srgb,var(--border-default)_72%,transparent)] bg-[color-mix(in_srgb,var(--surface-elevated)_82%,var(--surface))]'
- : 'border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)]',
- )}
- >
- <div className="flex items-center gap-2">
- <Sparkles size={14} className="text-[var(--text-tertiary)]" />
- <p
- className={cn(
- 'font-medium text-[var(--text-primary)]',
- appearance === 'plugin' ? 'text-14 leading-[1.571]' : 'text-13',
- )}
- >
- {t('settings.ghosts.detail.cindyPrefs.title')}
- </p>
- </div>
- <p
- className={cn(
- 'text-[var(--text-tertiary)]',
- appearance === 'plugin' ? 'text-13 leading-5' : 'text-12',
- )}
- >
- {t('settings.ghosts.detail.cindyPrefs.desc')}
- </p>
- {capabilities.map((capability) => {
- // 按能力键的类目取对应清单。少一个分支的后果不是少个下拉,而是拿
- // **图像模型清单**去填一个文本能力——用户存进去的值链路根本不认。
- const isText = capability.startsWith('text.');
- const kind =
- capability === 'video.edit'
- ? prefs.videoEdit
- : capability.startsWith('video.')
- ? prefs.video
- : isText
- ? prefs.text
- : capability.startsWith('embed.')
- ? prefs.embed
- : capability === 'image.edit'
- ? prefs.imageEdit
- : prefs.image;
- // 目录没给这个类目任何模型 = 能力暂不可用:行照旧显示(插件确实申请了
- // 这项能力),但右侧不给下拉,改一句不可点的灰字,不拿旧型号冒充可选。
- const defaultModel = kind.defaultModel;
- const unavailable = kind.options.length === 0 || defaultModel === null;
- // 文本类例外:目录清单空(含凭证过滤后为空)但用户已有一个 text pin 时,
- // 仍要能把它清掉/改掉——unavailable 的灰字会锁死坏 pin(Codex 2026-08-06
- // P1)。此时渲染选择器,只露出「跟随默认」与 stale 行。
- const textPinUnavailable = isText
- ? unavailable && overrides[capability] === undefined
- : unavailable;
- // 文本类:身份卡声明了偏好模型时,"跟随默认"行如实说出实际路由
- // (插件声明优先于系统链;用户在下面的钉档永远最大)。
- const declaredModel = isText ? (prefs.text?.declaredModel ?? null) : null;
- const current = overrides[capability];
- const selectValue =
- current && current !== defaultModel?.id ? current : FOLLOW_DEFAULT_VALUE;
- if (isText) {
- // 快问快答:目录全量文本模型的富列表选择器(图标/折扣与订阅徽标/分组/
- // 搜索,对齐新建对话的模型选择器)。
- const textOptions: readonly OneshotPinOption[] = prefs.text?.options ?? [];
- // 存量轻量档位钉(目录扩展前钉下的合法值)回显友好名,不当 stale 露 id。
- const legacyPinLabel = current
- ? (prefs.text?.utilityProfiles?.find((p) => p.id === current)?.label ?? null)
- : null;
- return (
- <div
- key={capability}
- className="cindy-capability-row flex min-w-0 items-center justify-between gap-4"
- >
- <span
- className={cn(
- 'min-w-0 text-[var(--text-secondary)]',
- appearance === 'plugin' ? 'text-13 leading-5' : 'text-12',
- )}
- >
- {t(`settings.ghosts.detail.cindyPrefs.cap.${capability}`)}
- </span>
- {textPinUnavailable ? (
- <span
- className={cn(
- 'cindy-capability-empty min-w-0 truncate text-[var(--text-tertiary)]',
- appearance === 'plugin' ? 'text-13 leading-5' : 'text-12',
- )}
- >
- {t('settings.ghosts.detail.cindyPrefs.noModels')}
- </span>
- ) : (
- <OneshotModelPinPicker
- value={selectValue === FOLLOW_DEFAULT_VALUE ? undefined : selectValue}
- defaultLabel={defaultModel?.label ?? ''}
- declaredLabel={declaredModel?.label ?? null}
- legacyPinLabel={legacyPinLabel}
- options={textOptions}
- onChange={(pin) => handleChange(capability, pin ?? FOLLOW_DEFAULT_VALUE)}
- ariaLabel={t(`settings.ghosts.detail.cindyPrefs.cap.${capability}`)}
- dense={appearance !== 'plugin'}
- />
- )}
- </div>
- );
- }
-
- // image/video 保持原有轻量下拉,只用 Provider 图标区分同名模型的不同来源。
- if (!capability.startsWith('embed.')) {
- const mediaOptions = kind.options as unknown as readonly MediaModelOption[];
- const mediaDefault = defaultModel as unknown as MediaModelOption;
- return (
- <div
- key={capability}
- className="cindy-capability-row flex min-w-0 items-center justify-between gap-4"
- >
- <span
- className={cn(
- 'min-w-0 text-[var(--text-secondary)]',
- appearance === 'plugin' ? 'text-13 leading-5' : 'text-12',
- )}
- >
- {t(`settings.ghosts.detail.cindyPrefs.cap.${capability}`)}
- </span>
- {unavailable && current === undefined ? (
- <span
- className={cn(
- 'cindy-capability-empty min-w-0 truncate text-[var(--text-tertiary)]',
- appearance === 'plugin' ? 'text-13 leading-5' : 'text-12',
- )}
- >
- {t('settings.ghosts.detail.cindyPrefs.noModels')}
- </span>
- ) : unavailable ? (
- <button
- type="button"
- className={cn(
- 'shrink-0 text-[var(--text-secondary)] hover:text-[var(--text-primary)]',
- appearance === 'plugin' ? 'text-13 leading-5' : 'text-12',
- )}
- onClick={() => void handleChange(capability, FOLLOW_DEFAULT_VALUE)}
- >
- {t('settings.defaults.restore')}
- </button>
- ) : (
- <MediaModelPicker
- value={selectValue === FOLLOW_DEFAULT_VALUE ? undefined : selectValue}
- defaultModel={mediaDefault}
- options={mediaOptions}
- onChange={(pin) => handleChange(capability, pin ?? FOLLOW_DEFAULT_VALUE)}
- ariaLabel={t(`settings.ghosts.detail.cindyPrefs.cap.${capability}`)}
- dense={appearance !== 'plugin'}
- />
- )}
- </div>
- );
- }
-
- // embed 类目继续使用原生 select。
- const options: { id: string; label: string; group?: string }[] = kind.options;
- const selectable = options.filter((o) => o.id !== defaultModel?.id);
- const groupNames: string[] = [];
- for (const o of selectable) {
- const g = o.group ?? '';
- if (!groupNames.includes(g)) groupNames.push(g);
- }
- // 覆盖值已不在当前清单(目录演进/形态更替):如实显示原值,不假装跟随默认。
- const staleOverride =
- current &&
- selectValue !== FOLLOW_DEFAULT_VALUE &&
- !selectable.some((o) => o.id === current)
- ? current
- : null;
- return (
- <div
- key={capability}
- className="cindy-capability-row flex min-w-0 items-center justify-between gap-4"
- >
- <span
- className={cn(
- 'min-w-0 text-[var(--text-secondary)]',
- appearance === 'plugin' ? 'text-13 leading-5' : 'text-12',
- )}
- >
- {t(`settings.ghosts.detail.cindyPrefs.cap.${capability}`)}
- </span>
- {unavailable ? (
- <span
- className={cn(
- 'cindy-capability-empty min-w-0 truncate text-[var(--text-tertiary)]',
- appearance === 'plugin' ? 'text-13 leading-5' : 'text-12',
- )}
- >
- {t('settings.ghosts.detail.cindyPrefs.noModels')}
- </span>
- ) : (
- <select
- value={selectValue}
- onChange={(event) => void handleChange(capability, event.target.value)}
- aria-label={t(`settings.ghosts.detail.cindyPrefs.cap.${capability}`)}
- className={cn(
- 'cindy-capability-select h-8 w-[300px] max-w-[60%] min-w-0 shrink appearance-none rounded-full border border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] py-0 pl-3 pr-8 text-[var(--settings-input-text)] outline-none focus:ring-2 focus:ring-[var(--focus-ring-soft)]',
- appearance === 'plugin' ? 'text-13 leading-5' : 'text-12',
- )}
- >
- <option value={FOLLOW_DEFAULT_VALUE}>
- {t('settings.ghosts.detail.cindyPrefs.defaultOption', {
- model: defaultModel.label,
- })}
- </option>
- {groupNames.map((groupName) =>
- groupName === '' ? (
- selectable
- .filter((o) => (o.group ?? '') === '')
- .map((o) => (
- <option key={o.id} value={o.id}>
- {o.label}
- </option>
- ))
- ) : (
- <optgroup key={groupName} label={groupName}>
- {selectable
- .filter((o) => o.group === groupName)
- .map((o) => (
- <option key={o.id} value={o.id}>
- {o.label}
- </option>
- ))}
- </optgroup>
- ),
- )}
- {staleOverride ? <option value={staleOverride}>{staleOverride}</option> : null}
- </select>
- )}
- </div>
- );
- })}
- </div>
- );
-}
diff --git a/apps/desktop/src/renderer/cindy-brain/OneshotModelPinPicker.tsx b/apps/desktop/src/renderer/cindy-brain/OneshotModelPinPicker.tsx
index a9b350f1cc..6ce1eb4ec9 100644
--- a/apps/desktop/src/renderer/cindy-brain/OneshotModelPinPicker.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/OneshotModelPinPicker.tsx
@@ -6,7 +6,7 @@ import { ModelSelector } from '@/components/new-chat/ModelSelector';
import { PROVIDER_TITLE_KEY } from '@/lib/providerDisplayName';
import { decodeCatalogModelPin } from '../../shared/catalogModelPin';
-/** 主侧 cindy-prefs 下发的目录钉条目(与 TextOneshotPinOption 同形)。 */
+/** 主侧下发的目录钉条目(与 TextOneshotPinOption 同形;系统辅助模型设置使用)。 */
export interface OneshotPinOption {
id: string;
label: string;
@@ -65,25 +65,19 @@ export function oneshotPickerProviders(options: readonly OneshotPinOption[]): Pr
}
export function OneshotModelPinPicker({
- value, defaultLabel, declaredLabel, legacyPinLabel, options, onChange, ariaLabel,
+ value, options, onChange, ariaLabel,
dense, defaultOptionLabel, disabled, groupByProvider = false,
}: {
/** 当前钉值;undefined = 跟随默认。 */
value?: string;
- /** 系统默认链链首的展示文案(未声明偏好时"跟随默认"行用)。 */
- defaultLabel: string;
- /** 身份卡声明的偏好模型文案(声明存在时"跟随默认"行如实显示它)。 */
- declaredLabel: string | null;
- /** 存量轻量档位钉(目录扩展前钉下的合法档位键)的展示名;null/缺省 = 不是档位钉。 */
- legacyPinLabel?: string | null;
options: readonly OneshotPinOption[];
/** null = 清除钉档(恢复跟随默认)。 */
onChange: (pin: string | null) => void | boolean | Promise<void | boolean>;
ariaLabel: string;
/** 紧凑字号(设置页 12px;插件详情页 13px)。 */
dense?: boolean;
- /** Generic settings surfaces can supply their own automatic-route copy. */
- defaultOptionLabel?: string;
+ /** Copy for the "no pin" row (the caller's automatic route). */
+ defaultOptionLabel: string;
searchPlaceholder?: string;
noResultsLabel?: string;
unavailableLabel?: string;
@@ -97,9 +91,6 @@ export function OneshotModelPinPicker({
const current = value ? options.find((option) => option.id === value) : undefined;
const decoded = value ? decodeCatalogModelPin(value) : null;
const route = current ?? (decoded ? { ...decoded, modelId: decoded.model } : null);
- const automaticLabel = defaultOptionLabel ?? (declaredLabel
- ? t('settings.ghosts.detail.cindyPrefs.defaultOptionDeclared', { model: declaredLabel })
- : t('settings.ghosts.detail.cindyPrefs.defaultOption', { model: defaultLabel }));
const providers = useMemo(() => oneshotPickerProviders(options).map((provider) => ({
...provider,
name: groupByProvider && PROVIDER_TITLE_KEY[provider.id]
@@ -107,7 +98,7 @@ export function OneshotModelPinPicker({
})), [options, groupByProvider, t]);
const currentAgent = route && knownAgent(route.agentKind) ? route.agentKind : undefined;
const vendor = currentAgent === 'claude-code' ? 'cc' : currentAgent;
- const unavailable = !!value && !legacyPinLabel && (!current || current.available === false);
+ const unavailable = !!value && (!current || current.available === false);
return <ModelSelector
providersOverride={providers}
modelId={route?.modelId ?? value ?? ''}
@@ -131,9 +122,9 @@ export function OneshotModelPinPicker({
dense={dense}
disabled={disabled}
ariaContext={ariaLabel}
- unknownModelLabel={() => legacyPinLabel ?? current?.modelName ?? value ?? automaticLabel}
+ unknownModelLabel={() => current?.modelName ?? value ?? defaultOptionLabel}
sourceDisconnected={unavailable}
- fallbackOption={{ active: value === undefined, label: automaticLabel,
+ fallbackOption={{ active: value === undefined, label: defaultOptionLabel,
onSelect: () => value !== undefined ? onChange(null) : undefined }}
/>;
}
diff --git a/apps/desktop/src/renderer/cindy-brain/PluginTaskPrefs.tsx b/apps/desktop/src/renderer/cindy-brain/PluginTaskPrefs.tsx
index 8b7ef74ec0..b87163a7a7 100644
--- a/apps/desktop/src/renderer/cindy-brain/PluginTaskPrefs.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/PluginTaskPrefs.tsx
@@ -1,20 +1,21 @@
-import { Button } from '@/components/ui/button';
-/** User preferences for new plugin tasks; uses the ordinary model/permission controls. */
+/**
+ * Plugin "Model & tasks" preferences: the plugin's single model field (used by
+ * Cindy quick answers and by the tasks the plugin creates) plus the task
+ * permission and working-directory rows. Reuses the ordinary model/permission
+ * controls; persistence stays in ghost-errand-prefs.json via ghosts:errand-prefs.
+ */
-import { useModelPickerAgents } from '@/hooks/useAvailableAgents';
import { useCallback, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { Bot, FolderOpen, X } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { useModelPickerAgents } from '@/hooks/useAvailableAgents';
import { extractIpcError } from '@/utils/ipcError';
import { cn } from '@/lib/utils';
import { ModelSelector } from '@/components/new-chat/ModelSelector';
import { PermissionSelector } from '@/components/new-chat/PermissionSelector';
-import {
- getEffortForModel,
- getFastModeForModel,
- useNewMakerDraft,
-} from '@/state/newMakerDraft';
+import { getEffortForModel, getFastModeForModel } from '@/state/newMakerDraft';
import type { Effort } from '@/lib/userPreferences.types';
const PERMISSION_ALLOWED = new Set(['ask', 'acceptEdits', 'auto']);
@@ -36,19 +37,20 @@ export function PluginTaskPrefs({
ghostId,
appearance = 'settings',
legacyDefault = false,
+ showTaskRows = true,
}: {
ghostId: string;
/** Plugin detail aligns the card with the shared Plugin surface. */
appearance?: 'settings' | 'plugin';
/** Old errand-only plugins retain their original default until the user chooses a mode. */
legacyDefault?: boolean;
+ /** Plugins that cannot create tasks (quick answers only) show just the model row. */
+ showTaskRows?: boolean;
}) {
const { t } = useTranslation();
- const [config, setConfig] = useState<TaskConfig>(
- () => (window.electronAPI.ghosts.errandPrefsSync(ghostId).config ?? {}) as TaskConfig,
- );
- // This previews panel creation. Calls from a task use its current route.
- const draft = useNewMakerDraft();
+ const [initial] = useState(() => window.electronAPI.ghosts.errandPrefsSync(ghostId));
+ const [config, setConfig] = useState<TaskConfig>(() => (initial.config ?? {}) as TaskConfig);
+ const auxiliaryModelLabel = initial.auxiliaryModelLabel ?? null;
const [error, setError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
@@ -74,21 +76,23 @@ export function PluginTaskPrefs({
[config, ghostId, t],
);
- const followVendor: 'cc' | 'codex' | 'pi' =
- draft.vendor === 'pi' ? 'pi' : draft.vendor === 'codex' ? 'codex' : 'cc';
- const vendor: 'cc' | 'codex' | 'pi' = config.agentKind ?? followVendor;
- const pickerAgents = useModelPickerAgents(vendor === 'cc' ? 'claude-code' : vendor);
-
+ // Explicit model = the complete saved combination. Without one the plugin follows
+ // the system auxiliary model (quick answers) and the originating task (new tasks).
const customized = [config.agentKind, config.model, config.providerId, config.effort, config.fastMode]
.some(value => value !== undefined);
- const shownProvider = config.providerId ?? draft.lastByVendor[vendor]?.providerId ?? null;
- const shownModel = config.model ?? draft.lastByVendor[vendor].model;
- const routeEffort = customized ? config.effort : draft.lastByVendor[vendor]?.effort;
- const shownEffort = (routeEffort ??
- getEffortForModel(shownModel) ??
- 'high') as Effort;
+ const vendor = config.agentKind;
+ const pickerAgents = useModelPickerAgents(
+ vendor === 'cc' ? 'claude-code' : (vendor ?? 'codex'),
+ );
+ const shownModel = config.model ?? '';
+ const shownEffort = (config.effort ?? getEffortForModel(shownModel) ?? 'high') as Effort;
const shownFast = config.fastMode ?? getFastModeForModel(shownModel);
const permissionMode = config.permissionMode ?? (legacyDefault ? 'plan' : 'ask');
+ const restoreModel = (): Promise<boolean> =>
+ save({ permissionMode: config.permissionMode, workingDir: config.workingDir });
+ const followLabel = auxiliaryModelLabel
+ ? t('settings.ghosts.detail.errandPrefs.followAuxiliary', { model: auxiliaryModelLabel })
+ : t('settings.ghosts.detail.errandPrefs.followAuxiliaryUnset');
const pickWorkingDir = async (): Promise<void> => {
const result = await window.electronAPI.showOpenDirectoryDialog();
@@ -97,14 +101,16 @@ export function PluginTaskPrefs({
}
};
- const labelCls = cn(
- 'min-w-0 shrink-0 text-[var(--text-secondary)]',
- appearance === 'plugin' ? 'text-13 leading-5' : 'text-12',
- );
+ const textCls = appearance === 'plugin' ? 'text-13 leading-5' : 'text-12 leading-4';
+ // Label column keeps its own width: a full-width field trigger must never
+ // squeeze the label to zero and cover it (its title tooltip then appeared over
+ // the label text).
const row = (key: string, control: ReactNode): ReactNode => (
- <div className="flex min-w-0 items-center justify-between gap-4">
- <span className={labelCls}>{t(`settings.ghosts.detail.errandPrefs.${key}`)}</span>
- {control}
+ <div className="flex min-w-0 items-center gap-4" data-plugin-task-row={key}>
+ <span className={cn('w-24 shrink-0 text-[var(--text-secondary)]', textCls)}>
+ {t(`settings.ghosts.detail.errandPrefs.${key}`)}
+ </span>
+ <div className="flex min-w-0 flex-1 items-center gap-2">{control}</div>
</div>
);
@@ -117,121 +123,124 @@ export function PluginTaskPrefs({
: 'border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)]',
)}
>
- <div className="flex items-center gap-2">
- <Bot size={14} className="text-[var(--text-tertiary)]" />
- <p
- className={cn(
- 'font-medium text-[var(--text-primary)]',
- appearance === 'plugin' ? 'text-14 leading-[1.571]' : 'text-13',
- )}
- >
- {t('settings.ghosts.detail.errandPrefs.title')}
- </p>
- </div>
- <p
- className={cn(
- 'text-[var(--text-tertiary)]',
- appearance === 'plugin' ? 'text-13 leading-5' : 'text-12',
- )}
- >
- {t(`settings.ghosts.detail.errandPrefs.${legacyDefault ? 'legacyDesc' : 'desc'}`)}
- </p>
-
- {/* 模型选择器占满整行(标题在上、控件 w-full 在下,与 IM 默认配置同款):
- field 形态的面板宽度绑定 trigger 宽度(DESIGN.md §4),压到 60% 会让下拉
- 窄到把模型名截断,所以这里给它整行宽度。 */}
- <div className="flex min-w-0 flex-col gap-2">
- <div className="flex items-center justify-between gap-2">
- <span className="text-12 leading-4 text-[var(--text-secondary)]">
- {t(`settings.ghosts.detail.errandPrefs.${customized ? 'sourceCustom' : 'sourceDefault'}`)}
- </span>
- {customized ? <Button type="button" variant="secondary" tone="quiet" size="sm" disabled={saving}
- onClick={() => save({ permissionMode: config.permissionMode, workingDir: config.workingDir })}>
- {t('settings.ghosts.detail.errandPrefs.restoreModel')}
- </Button> : null}
+ <div className="flex flex-col gap-1">
+ <div className="flex items-center gap-2">
+ <Bot size={14} className="text-[var(--text-tertiary)]" />
+ <p
+ className={cn(
+ 'font-medium text-[var(--text-primary)]',
+ appearance === 'plugin' ? 'text-14 leading-[1.571]' : 'text-13',
+ )}
+ >
+ {t('settings.ghosts.detail.errandPrefs.title')}
+ </p>
</div>
- <span className={labelCls}>{t('settings.ghosts.detail.errandPrefs.model')}</span>
- <ModelSelector
- disabled={saving}
- unifiedAgents={pickerAgents}
- onUnifiedSelect={({ engine, providerId, modelId, effort, fast }) => save({
- ...config,
- agentKind: engine,
- providerId,
- model: modelId,
- effort: TASK_EFFORTS.has(effort ?? '') ? effort : undefined,
- fastMode: fast,
- })}
- modelId={shownModel}
- effort={shownEffort}
- fastMode={shownFast}
- vendorKey={vendor}
- currentProviderId={shownProvider}
- triggerVariant="field"
- popoverSide="bottom"
- ariaContext={t('settings.ghosts.detail.errandPrefs.model')}
- onModelChange={(modelId) =>
- // 选模型即整组钉住(agent 一起钉,防草稿随后换 vendor 让模型悬空)。
- save({ ...config, agentKind: vendor, providerId: shownProvider ?? undefined, model: modelId, effort: undefined, fastMode: false })
- }
- onEffortChange={(effort) => {
- if (!TASK_EFFORTS.has(effort)) return;
- return save({ ...config, agentKind: vendor, providerId: shownProvider ?? undefined, model: shownModel, effort, fastMode: shownFast });
- }}
- onFastModeChange={(enabled) =>
- save({ ...config, agentKind: vendor, providerId: shownProvider ?? undefined, model: shownModel,
- effort: TASK_EFFORTS.has(routeEffort ?? '') ? routeEffort : undefined, fastMode: enabled })
- }
- onProviderChange={(providerId, modelId, reconciledEffort, reconciledFast) =>
- save({
- ...config,
- agentKind: vendor,
- model: modelId ?? shownModel,
- effort: TASK_EFFORTS.has(reconciledEffort ?? '')
- ? reconciledEffort
- : undefined,
- providerId: providerId ?? undefined,
- fastMode: reconciledFast ?? false,
- })
- }
- />
+ <p className={cn('text-[var(--text-tertiary)]', textCls)}>
+ {t(`settings.ghosts.detail.errandPrefs.${showTaskRows ? 'desc' : 'descModelOnly'}`)}
+ </p>
</div>
- {error ? <p role="alert" className="text-12 leading-5 text-[var(--text-secondary)]">{error}</p> : null}
-
{row(
- 'permission',
- <PermissionSelector
- disabled={saving}
- permissionMode={permissionMode}
- fallbackModeLabel={permissionMode === 'plan' ? t('settings.ghosts.detail.errandPrefs.legacyPermission') : undefined}
- vendorKey={vendor}
- triggerVariant="field"
- ariaContext={t('settings.ghosts.detail.errandPrefs.permission')}
- disabledModes={{
- default: t('settings.ghosts.detail.errandPrefs.permissionDisabled'),
- bypassPermissions: t('settings.ghosts.detail.errandPrefs.permissionDisabled'),
- }}
- onPermissionModeChange={(mode) => {
- // disabledModes 已灰置非法档;这里再执一道白名单(UI 不是安全边界,
- // 存储层与协议层各有一道,三道口径一致)。
- if (!PERMISSION_ALLOWED.has(mode)) return;
- save({
- ...config,
- permissionMode: mode as 'ask' | 'acceptEdits' | 'auto',
- });
- }}
- />,
+ 'model',
+ <>
+ <div className="min-w-0 flex-1">
+ <ModelSelector
+ disabled={saving}
+ unifiedAgents={pickerAgents}
+ onUnifiedSelect={({ engine, providerId, modelId, effort, fast }) => save({
+ ...config,
+ agentKind: engine,
+ providerId,
+ model: modelId,
+ effort: TASK_EFFORTS.has(effort ?? '') ? effort : undefined,
+ fastMode: fast,
+ })}
+ modelId={shownModel}
+ effort={shownEffort}
+ fastMode={shownFast}
+ vendorKey={vendor}
+ currentProviderId={config.providerId ?? null}
+ triggerVariant="field"
+ popoverSide="bottom"
+ dense={appearance !== 'plugin'}
+ ariaContext={t('settings.ghosts.detail.errandPrefs.model')}
+ fallbackOption={{
+ active: !customized,
+ label: followLabel,
+ onSelect: () => (customized ? restoreModel() : undefined),
+ }}
+ onModelChange={(modelId) => {
+ // 选模型即整组钉住(agent 一起钉);未选过时没有可钉的 agent,交给统一面板。
+ if (!vendor) return false;
+ return save({ ...config, agentKind: vendor, model: modelId, effort: undefined, fastMode: false });
+ }}
+ onEffortChange={(effort) => {
+ if (!customized || !TASK_EFFORTS.has(effort)) return;
+ return save({ ...config, effort, fastMode: shownFast });
+ }}
+ onFastModeChange={(enabled) => {
+ if (!customized) return false;
+ return save({ ...config, fastMode: enabled });
+ }}
+ onProviderChange={(providerId, modelId, reconciledEffort, reconciledFast) => {
+ if (!vendor) return false;
+ return save({
+ ...config,
+ agentKind: vendor,
+ model: modelId ?? config.model,
+ effort: TASK_EFFORTS.has(reconciledEffort ?? '') ? reconciledEffort : undefined,
+ providerId: providerId ?? undefined,
+ fastMode: reconciledFast ?? false,
+ });
+ }}
+ />
+ </div>
+ {customized ? (
+ <Button type="button" variant="secondary" tone="quiet" size="sm" disabled={saving}
+ className="shrink-0" onClick={() => void restoreModel()}>
+ {t('settings.ghosts.detail.errandPrefs.restoreModel')}
+ </Button>
+ ) : null}
+ </>,
)}
- {row(
+ {showTaskRows ? row(
+ 'permission',
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <PermissionSelector
+ disabled={saving}
+ permissionMode={permissionMode}
+ fallbackModeLabel={permissionMode === 'plan' ? t('settings.ghosts.detail.errandPrefs.legacyPermission') : undefined}
+ vendorKey={vendor}
+ triggerVariant="field"
+ ariaContext={t('settings.ghosts.detail.errandPrefs.permission')}
+ disabledModes={{
+ default: t('settings.ghosts.detail.errandPrefs.permissionDisabled'),
+ bypassPermissions: t('settings.ghosts.detail.errandPrefs.permissionDisabled'),
+ }}
+ onPermissionModeChange={(mode) => {
+ // disabledModes 已灰置非法档;这里再执一道白名单(UI 不是安全边界,
+ // 存储层与协议层各有一道,三道口径一致)。
+ if (!PERMISSION_ALLOWED.has(mode)) return;
+ save({
+ ...config,
+ permissionMode: mode as 'ask' | 'acceptEdits' | 'auto',
+ });
+ }}
+ />
+ {legacyDefault && config.permissionMode === undefined ? (
+ <p className="text-12 leading-4 text-[var(--text-tertiary)]">
+ {t('settings.ghosts.detail.errandPrefs.legacyPermissionHint')}
+ </p>
+ ) : null}
+ </div>,
+ ) : null}
+
+ {showTaskRows ? row(
'workdir',
- <div className="flex min-w-0 max-w-[60%] items-center gap-2">
+ <>
<span
- className={cn(
- 'min-w-0 flex-1 truncate text-right text-[var(--text-tertiary)]',
- appearance === 'plugin' ? 'text-13 leading-5' : 'text-12',
- )}
+ className={cn('min-w-0 flex-1 truncate text-[var(--text-tertiary)]', textCls)}
title={config.workingDir}
>
{config.workingDir ?? t('settings.ghosts.detail.errandPrefs.workdirDefault')}
@@ -257,8 +266,10 @@ export function PluginTaskPrefs({
<FolderOpen size={13} />
{t('settings.ghosts.detail.errandPrefs.workdirPick')}
</Button>
- </div>,
- )}
+ </>,
+ ) : null}
+
+ {error ? <p role="alert" className="text-12 leading-5 text-[var(--text-secondary)]">{error}</p> : null}
</fieldset>
);
}
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/OneshotModelPinPicker.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/OneshotModelPinPicker.test.tsx
index 22c3673c97..8df45f5285 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/OneshotModelPinPicker.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/OneshotModelPinPicker.test.tsx
@@ -71,8 +71,8 @@ const xdOption: OneshotPinOption = {
};
describe('OneshotModelPinPicker shared A adapter', () => {
- const mount = (extra = {}) => render(<OneshotModelPinPicker defaultLabel="Automatic"
- declaredLabel={null} options={options} onChange={vi.fn()} ariaLabel="Auxiliary model" {...extra} />);
+ const mount = (extra = {}) => render(<OneshotModelPinPicker defaultOptionLabel="Automatic"
+ options={options} onChange={vi.fn()} ariaLabel="Auxiliary model" {...extra} />);
it('uses the shared picker with all host-approved routes, without a separate Agent step', () => {
mount();
@@ -115,7 +115,7 @@ describe('OneshotModelPinPicker shared A adapter', () => {
expect(onChange).toHaveBeenCalledWith(xdOption.id);
});
- it('preserves failure results, same-pin no-op, automatic clearing, and legacy labels', async () => {
+ it('preserves failure results, same-pin no-op, automatic clearing, and unknown-pin labels', async () => {
const onChange = vi.fn(async () => false);
const view = mount({ value: OPENROUTER_PIN, onChange });
expect(await picker.onUnifiedSelect!({ providerId: 'openrouter', modelId: 'openai/gpt-5-mini',
@@ -126,8 +126,9 @@ describe('OneshotModelPinPicker shared A adapter', () => {
expect(await picker.fallbackOption!.onSelect()).toBe(false);
expect(onChange).toHaveBeenLastCalledWith(null);
view.unmount();
- mount({ value: 'legacy', legacyPinLabel: 'Budget tier' });
- expect(picker.sourceDisconnected).toBe(false);
- expect(picker.unknownModelLabel!('legacy')).toBe('Budget tier');
+ mount({ value: 'retired' });
+ expect(picker.sourceDisconnected).toBe(true);
+ expect(picker.unknownModelLabel!('retired')).toBe('retired');
+ expect(picker.fallbackOption?.label).toBe('Automatic');
});
});
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/PluginTaskPrefs.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/PluginTaskPrefs.test.tsx
index 9dd5b51ccb..bab6132038 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/PluginTaskPrefs.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/PluginTaskPrefs.test.tsx
@@ -3,18 +3,27 @@ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/re
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { PluginTaskPrefs } from '../PluginTaskPrefs';
-const state = vi.hoisted(() => ({ config: {} as Record<string, unknown>, save: vi.fn() }));
-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+const state = vi.hoisted(() => ({
+ config: {} as Record<string, unknown>,
+ auxiliaryModelLabel: 'Grok 4.6' as string | null | undefined,
+ save: vi.fn(),
+}));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, values?: Record<string, string>) =>
+ values?.model ? `${key}:${values.model}` : key,
+ }),
+}));
vi.mock('@/hooks/useAvailableAgents', () => ({ useModelPickerAgents: () => [] }));
vi.mock('@/state/newMakerDraft', () => ({
- useNewMakerDraft: () => ({ vendor: 'codex', lastByVendor: { codex: { model: 'gpt-6-astra', providerId: 'openai', effort: 'high' } } }),
getEffortForModel: () => undefined, getFastModeForModel: () => false,
}));
vi.mock('@/components/new-chat/ModelSelector', () => ({ ModelSelector: (props: any) => (
<>
<button disabled={props.disabled} data-testid="model" onClick={() => props.onUnifiedSelect({ engine: 'codex', providerId: 'openai', modelId: 'chosen', effort: 'high', fast: false })}>
- {props.vendorKey}/{props.currentProviderId}/{props.modelId}
+ {props.fallbackOption?.active ? props.fallbackOption.label : `${props.vendorKey}/${props.currentProviderId}/${props.modelId}`}
</button>
+ <button data-testid="follow" onClick={() => props.fallbackOption?.onSelect()}>follow</button>
<button data-testid="fast" onClick={() => props.onFastModeChange(true)}>Fast</button>
</>
) }));
@@ -25,8 +34,12 @@ vi.mock('@/components/new-chat/PermissionSelector', () => ({ PermissionSelector:
beforeEach(() => {
state.config = {};
+ state.auxiliaryModelLabel = 'Grok 4.6';
state.save.mockReset().mockImplementation(async (_id, config) => ({ config }));
- (window as any).electronAPI = { ghosts: { errandPrefsSync: () => ({ config: state.config }), setErrandConfig: state.save } };
+ (window as unknown as { electronAPI: unknown }).electronAPI = { ghosts: {
+ errandPrefsSync: () => ({ config: state.config, auxiliaryModelLabel: state.auxiliaryModelLabel }),
+ setErrandConfig: state.save,
+ } };
});
afterEach(cleanup);
it.each([undefined, 'medium'])('changing Fast preserves only the configured effort (%s), never the display fallback', async effort => {
@@ -35,32 +48,70 @@ it.each([undefined, 'medium'])('changing Fast preserves only the configured effo
fireEvent.click(screen.getByTestId('fast'));
await waitFor(() => expect(state.save).toHaveBeenCalledWith('plugin', {...state.config, fastMode:true}));
});
-it('previews the complete current panel route and uses ordinary task permissions independently', () => {
+it('follows the system auxiliary model by default, without previewing a new-task draft', () => {
render(<PluginTaskPrefs ghostId="plugin" />);
- expect(screen.getByTestId('model').textContent).toBe('codex/openai/gpt-6-astra');
+ expect(screen.getByTestId('model').textContent).toBe('settings.ghosts.detail.errandPrefs.followAuxiliary:Grok 4.6');
+ expect(screen.getByText('settings.ghosts.detail.errandPrefs.title')).toBeTruthy();
+ expect(screen.getByText('settings.ghosts.detail.errandPrefs.desc')).toBeTruthy();
+ expect(screen.queryByText('settings.ghosts.detail.errandPrefs.restoreModel')).toBeNull();
expect(screen.getByTestId('permission').textContent).toBe('ask');
- expect(screen.getByText('settings.ghosts.detail.errandPrefs.sourceDefault')).toBeTruthy();
+ // Following the default is already the state; selecting it again writes nothing.
+ fireEvent.click(screen.getByTestId('follow'));
+ expect(state.save).not.toHaveBeenCalled();
+});
+it('names the follow-default row even when no auxiliary model is configured (older hosts omit the label)', () => {
+ state.auxiliaryModelLabel = undefined;
+ render(<PluginTaskPrefs ghostId="plugin" />);
+ expect(screen.getByTestId('model').textContent).toBe('settings.ghosts.detail.errandPrefs.followAuxiliaryUnset');
+});
+it('saves the complete selected combination as the plugin model', async () => {
+ state.config = { permissionMode: 'auto' };
+ render(<PluginTaskPrefs ghostId="plugin" />);
+ fireEvent.click(screen.getByTestId('model'));
+ await waitFor(() => expect(state.save).toHaveBeenCalledWith('plugin', {
+ permissionMode: 'auto', agentKind: 'codex', providerId: 'openai', model: 'chosen', effort: 'high', fastMode: false,
+ }));
+ expect(screen.getByTestId('model').textContent).toBe('codex/openai/chosen');
+ expect(screen.getByText('settings.ghosts.detail.errandPrefs.restoreModel')).toBeTruthy();
+});
+it('quick-answer-only plugins show just the model row', () => {
+ render(<PluginTaskPrefs ghostId="plugin" showTaskRows={false} />);
+ expect(screen.getByTestId('model')).toBeTruthy();
+ expect(screen.getByText('settings.ghosts.detail.errandPrefs.descModelOnly')).toBeTruthy();
+ expect(screen.queryByTestId('permission')).toBeNull();
+ expect(screen.queryByText('settings.ghosts.detail.errandPrefs.workdir')).toBeNull();
+});
+it('keeps the label column outside the full-width picker so its tooltip cannot cover the label', () => {
+ render(<PluginTaskPrefs ghostId="plugin" />);
+ const label = screen.getByText('settings.ghosts.detail.errandPrefs.model');
+ expect(label.className).toContain('shrink-0');
+ expect(label.contains(screen.getByTestId('model'))).toBe(false);
+ expect(label.closest('[data-plugin-task-row="model"]')).toBeTruthy();
});
it('preserves legacy permissions until the user explicitly chooses an ordinary mode', async () => {
render(<PluginTaskPrefs ghostId="plugin" legacyDefault />);
expect(screen.getByTestId('permission').textContent).toBe('plan');
expect(screen.getByTestId('permission').getAttribute('data-legacy-label')).toBe('settings.ghosts.detail.errandPrefs.legacyPermission');
+ expect(screen.getByText('settings.ghosts.detail.errandPrefs.legacyPermissionHint')).toBeTruthy();
expect(state.save).not.toHaveBeenCalled();
fireEvent.click(screen.getByTestId('permission'));
await waitFor(() => expect(state.save).toHaveBeenCalledWith('plugin', { permissionMode: 'ask' }));
+ expect(screen.queryByText('settings.ghosts.detail.errandPrefs.legacyPermissionHint')).toBeNull();
});
-it('resetting the model preserves explicitly selected permissions and directory', async () => {
+it.each(['restoreModel', 'follow'])('resetting the model via %s preserves explicitly selected permissions and directory', async (control) => {
state.config = { agentKind: 'codex', model: 'old', providerId: 'old-connection', permissionMode: 'auto', workingDir: '/selected' };
render(<PluginTaskPrefs ghostId="plugin" />);
- fireEvent.click(screen.getByText('settings.ghosts.detail.errandPrefs.restoreModel'));
+ fireEvent.click(control === 'follow'
+ ? screen.getByTestId('follow')
+ : screen.getByText('settings.ghosts.detail.errandPrefs.restoreModel'));
await waitFor(() => expect(state.save).toHaveBeenCalledWith('plugin', { permissionMode: 'auto', workingDir: '/selected' }));
- expect(screen.getByTestId('model').textContent).toBe('codex/openai/gpt-6-astra');
+ expect(screen.getByTestId('model').textContent).toBe('settings.ghosts.detail.errandPrefs.followAuxiliary:Grok 4.6');
});
it('shows actionable host validation errors and restores the saved selection', async () => {
state.save.mockRejectedValue(new Error('[INVALID_PARAMS] 供应商未连接,请修复连接后重试'));
render(<PluginTaskPrefs ghostId="plugin" />);
fireEvent.click(screen.getByTestId('model'));
await waitFor(() => expect(screen.getByRole('alert').textContent).toContain('修复连接'));
- expect(screen.getByTestId('model').textContent).toBe('codex/openai/gpt-6-astra');
+ expect(screen.getByTestId('model').textContent).toBe('settings.ghosts.detail.errandPrefs.followAuxiliary:Grok 4.6');
expect((screen.getByTestId('model') as HTMLButtonElement).disabled).toBe(false);
});
diff --git a/apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx b/apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx
index 45f12d4a5c..867660c88d 100644
--- a/apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx
@@ -274,8 +274,6 @@ export function AuxiliaryModelSection() {
surfacing Harness or a thinking-depth control. */}
<OneshotModelPinPicker
value={pin ?? undefined}
- defaultLabel=""
- declaredLabel={null}
options={slotOptions}
onChange={(next) => applySlot(index, next)}
ariaLabel={t(`settings.auxiliaryModels.${slotKey}.ariaLabel`)}
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index 913828ed42..828eef97cf 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -100,6 +100,7 @@ import {
botOwnedSessionNotificationTitle,
findSessionNotificationSession,
isReviewSessionNotificationTarget,
+ isBackgroundTaskNotificationTarget,
sendSessionEventNotification,
} from '@/lib/sessionEventNotification';
import { isReviewSessionSource } from '../../../shared/sessionSource';
@@ -1175,6 +1176,8 @@ function ExpandedView({
if (session && isOrcaWorkerSession(session)) return;
// /review 审查任务不单独通知:结果回到来源任务,由来源任务的轮次收尾通知。
if (session && isReviewSessionSource(session.source)) return;
+ // 插件后台隐藏任务不单独通知;显示到任务列表后恢复。
+ if (session && isBackgroundTaskNotificationTarget(session)) return;
if (session) {
const title = projectDraftSessionTitle(session.title, unnamedLabelRef.current);
sendSessionEventNotification(sessionId, title, kind, {
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionNotifications.test.ts b/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionNotifications.test.ts
index 3584e15103..089b8b81de 100644
--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionNotifications.test.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionNotifications.test.ts
@@ -5,7 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';
import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';
import { isOrcaWorkerSession } from '@/lib/orcaSessionIdentity';
-import { BOT_GROUP_LANE_SESSION, findSessionNotificationSession } from '@/lib/sessionEventNotification';
+import { BOT_GROUP_LANE_SESSION, findSessionNotificationSession, isBackgroundTaskNotificationTarget } from '@/lib/sessionEventNotification';
import { isReviewSessionSource } from '../../../../shared/sessionSource';
const source = ts.createSourceFile('sidebar.tsx', readFileSync(resolve(
@@ -44,6 +44,7 @@ type NotificationSession = {
source: string;
status?: 'active' | 'archived';
deviceLinkDeviceId?: string;
+ hiddenAt?: string | null;
};
const send = vi.fn();
const reviewTarget = vi.fn(async () => false);
@@ -67,6 +68,7 @@ function dispatcher(local: NotificationSession[], remote: NotificationSession[]
projectDraftSessionTitle,
sendSessionEventNotification: send,
isReviewSessionNotificationTarget: reviewTarget,
+ isBackgroundTaskNotificationTarget,
botOwnedSessionNotificationTitle: botTitle,
BOT_GROUP_LANE_SESSION,
t: () => 'Unnamed task',
@@ -107,6 +109,14 @@ describe('disabled Make notification dispatch', () => {
});
});
+ it('suppresses plugin background tasks and notifies again once they are shown', () => {
+ dispatcher([{ id: 'bg', title: 'Background', source: 'plugin', hiddenAt: '2026-10-15T00:00:00.000Z' }])('bg', 'done');
+ expect(send).not.toHaveBeenCalled();
+ expect(reviewTarget).not.toHaveBeenCalled();
+ dispatcher([{ id: 'bg', title: 'Background', source: 'plugin', hiddenAt: null }])('bg', 'done');
+ expect(send).toHaveBeenCalledWith('bg', 'Background', 'done', { remoteDevice: false, remoteDeviceId: undefined });
+ });
+
it('preserves the unknown-task fallback', async () => {
dispatcher([])('unknown', 'error');
await Promise.resolve();
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
index 97104727a1..e605a8e57e 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
@@ -28,8 +28,8 @@ import {
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
-import { CindyCapabilityPrefs } from '@/cindy-brain/CindyCapabilityPrefs';
import { GhostLibrarySection } from './GhostLibrarySection';
+import { PluginBackgroundTasksSection } from './PluginBackgroundTasksSection';
import { PluginTaskPrefs } from '@/cindy-brain/PluginTaskPrefs';
import { GhostSettingsWebview } from '@/cindy-brain/GhostSettingsWebview';
import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
@@ -45,6 +45,7 @@ import { Switch } from '@/components/ui/switch';
import { toast } from '@/lib/toast';
import { cn } from '@/lib/utils';
import {
+ ghostDeclaresHiddenTasks,
ghostTrustLabelKey,
isUserInstallReservedGhostId,
type GhostPermissionItem,
@@ -137,7 +138,6 @@ export function GhostPluginDetailView({
enabled &&
(primaryAction === 'panel' ||
(primaryAction === 'command' && detail.canUse));
- const cindyCapabilities = detail.cindyCapabilities;
// Local imports with the same id cannot use the host gh credential. Match the
// official receipt before advertising that connection in this plugin's UI.
const hasGithubConnection =
@@ -152,7 +152,6 @@ export function GhostPluginDetailView({
hasGithubConnection ||
detail.hasMainView ||
detail.hasSettingsUi ||
- cindyCapabilities.length > 0 ||
detail.hasTaskPreferences;
const summary = hasGithubConnection
? t('ccAgent.gitContext.pr.setup.account.summary')
@@ -512,21 +511,21 @@ export function GhostPluginDetailView({
{t('routines.pluginCapability')}
</p>
) : null}
- {cindyCapabilities.length > 0 ? (
- <CindyCapabilityPrefs
- ghostId={detail.id}
- capabilities={cindyCapabilities}
- appearance="plugin"
- />
- ) : null}
{detail.hasTaskPreferences ? (
<PluginTaskPrefs ghostId={detail.id} appearance="plugin"
+ showTaskRows={detail.hasPluginTasks}
legacyDefault={ghost?.manifest.agent?.errand === true && !ghost.manifest.agent?.tasks && !ghost.manifest.workspace} />
) : null}
</div>
</section>
) : null}
+ <PluginBackgroundTasksSection
+ ghostId={detail.id}
+ installed={ghost !== null}
+ hiddenTasksDeclared={ghostDeclaresHiddenTasks(ghost?.manifest)}
+ />
+
{detail.tools.length > 0 ? <ToolsSection tools={detail.tools} /> : null}
{detail.permissions.length > 0 ? <PermissionSummary items={detail.permissions} /> : null}
diff --git a/apps/desktop/src/renderer/features/plugin/PluginBackgroundTasksSection.tsx b/apps/desktop/src/renderer/features/plugin/PluginBackgroundTasksSection.tsx
new file mode 100644
index 0000000000..6174c757df
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/PluginBackgroundTasksSection.tsx
@@ -0,0 +1,179 @@
+/**
+ * PluginBackgroundTasksSection — 插件详情页「后台任务」区块(2026-10)。
+ * ---------------------------------------------------------------------------
+ * 声明 `agent.hiddenTasks` 的插件可以把自己创建的任务放到后台(不进任务列表、搜索与
+ * 通知)。这里是透明性兜底:列出本插件当前在后台的任务,每行可「打开任务」或
+ * 「显示到任务列表」(与插件 `cindy.tasks.setHidden` 共用宿主写入口)。
+ *
+ * - 声明了 hiddenTasks 时总是渲染(空状态说明);其它已安装插件仅在确有后台任务时渲染
+ * (更新移除 hiddenTasks 甚至 tasks 声明后,已在后台的任务仍须可见可接手);
+ * - 数据走 Desktop 专用 IPC `ghosts:background-tasks:*`,不进 device-link;
+ * - 颜色只用语义 token,Light / Dark 由主题变量自动适配。
+ */
+import { useCallback, useEffect, useState } from 'react';
+import { useInRouterContext, useNavigate } from 'react-router-dom';
+import { useTranslation } from 'react-i18next';
+import { RefreshCw } from 'lucide-react';
+
+import { Button } from '@/components/ui/button';
+import { formatRelative } from '@/hooks/useRelativeTime';
+import { sessionsStore } from '@/lib/sessionsStore';
+import { toast } from '@/lib/toast';
+import { cn } from '@/lib/utils';
+import type { PluginBackgroundTask } from '../../../shared/pluginTasks';
+
+const SECTION_CLASS = 'mt-10';
+const HEADING_CLASS = 'text-18 font-medium leading-[1.444] text-[var(--text-primary)]';
+const SURFACE_CLASS =
+ 'border border-[color-mix(in_srgb,var(--border-default)_72%,transparent)] bg-[color-mix(in_srgb,var(--surface-elevated)_82%,var(--surface))]';
+
+export interface PluginBackgroundTasksSectionProps {
+ ghostId: string;
+ /** 插件已安装(纯市场视图没有本机任务,不发起任何查询)。 */
+ installed: boolean;
+ /** manifest 同时声明了 agent.hiddenTasks;声明时空列表也渲染空状态。 */
+ hiddenTasksDeclared: boolean;
+}
+
+export function PluginBackgroundTasksSection(props: PluginBackgroundTasksSectionProps) {
+ if (!props.installed) return null;
+ return <PluginBackgroundTasksSectionInner {...props} />;
+}
+
+function PluginBackgroundTasksSectionInner({ ghostId, hiddenTasksDeclared }: PluginBackgroundTasksSectionProps) {
+ const { t } = useTranslation();
+ const inRouter = useInRouterContext();
+ const [items, setItems] = useState<PluginBackgroundTask[] | null>(null);
+ const [loadFailed, setLoadFailed] = useState(false);
+ const [revealing, setRevealing] = useState<string | null>(null);
+
+ const refresh = useCallback(async () => {
+ try {
+ const result = await window.electronAPI.ghosts.listBackgroundTasks(ghostId);
+ setItems(Array.isArray(result?.items) ? result.items : []);
+ setLoadFailed(false);
+ } catch {
+ setLoadFailed(true);
+ }
+ }, [ghostId]);
+
+ useEffect(() => {
+ void refresh();
+ // 插件转入后台 / 显示到任务列表都会广播 hiddenAt patch;据此刷新,不轮询。
+ return sessionsStore.subscribePatches((_id, patch) => {
+ if (Object.prototype.hasOwnProperty.call(patch, 'hiddenAt')) void refresh();
+ });
+ }, [refresh]);
+
+ const reveal = async (task: PluginBackgroundTask) => {
+ if (revealing) return;
+ setRevealing(task.taskId);
+ try {
+ await window.electronAPI.ghosts.revealBackgroundTask(ghostId, task.taskId);
+ toast.success(t('settings.ghosts.backgroundTasks.revealed'));
+ } catch {
+ toast.error(t('settings.ghosts.backgroundTasks.revealFailed'));
+ } finally {
+ setRevealing(null);
+ void refresh();
+ }
+ };
+
+ // 未声明 hiddenTasks:没有(或读不到)后台任务时整个区块不出现,不给其它插件多一块空区。
+ if (!hiddenTasksDeclared && (items === null || items.length === 0)) return null;
+
+ return (
+ <section className={SECTION_CLASS} aria-labelledby="ghost-background-tasks-title">
+ <div className="flex min-h-[26px] items-center justify-between gap-4">
+ <h2 id="ghost-background-tasks-title" className={HEADING_CLASS}>
+ {t('settings.ghosts.backgroundTasks.title')}
+ </h2>
+ <button
+ type="button"
+ onClick={() => void refresh()}
+ aria-label={t('settings.ghosts.backgroundTasks.refresh')}
+ className="shrink-0 rounded-md p-1 text-[var(--text-secondary)] transition-colors duration-150 hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ <RefreshCw size={14} aria-hidden="true" />
+ </button>
+ </div>
+ <p className="mt-1 max-w-[760px] text-13 leading-5 text-[var(--text-secondary)]">
+ {t('settings.ghosts.backgroundTasks.description')}
+ </p>
+ <div className={cn(SURFACE_CLASS, 'mt-4 max-w-[760px] rounded-xl')}>
+ {loadFailed ? (
+ <p className="px-5 py-4 text-13 leading-5 text-[var(--warning-fg)]">
+ {t('settings.ghosts.backgroundTasks.loadFailed')}
+ </p>
+ ) : items === null ? (
+ <p className="px-5 py-4 text-13 leading-5 text-[var(--text-tertiary)]">
+ {t('settings.ghosts.backgroundTasks.loading')}
+ </p>
+ ) : items.length === 0 ? (
+ <p className="px-5 py-4 text-13 leading-5 text-[var(--text-tertiary)]">
+ {t('settings.ghosts.backgroundTasks.empty')}
+ </p>
+ ) : (
+ <ul className="divide-y divide-[color-mix(in_srgb,var(--border-default)_72%,transparent)]">
+ {items.map((task) => (
+ <li
+ key={task.taskId}
+ data-testid="plugin-background-task"
+ className="flex min-h-14 items-center gap-3 px-5 py-3"
+ >
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-14 font-medium leading-[1.571] text-[var(--text-primary)]">
+ {task.title}
+ </p>
+ <p className="mt-0.5 truncate text-12 leading-[1.5] text-[var(--text-tertiary)]">
+ {t(
+ task.running
+ ? 'settings.ghosts.backgroundTasks.statusRunning'
+ : task.status === 'archived'
+ ? 'settings.ghosts.backgroundTasks.statusArchived'
+ : 'settings.ghosts.backgroundTasks.statusIdle',
+ )}
+ {' · '}
+ {t('settings.ghosts.backgroundTasks.lastActive', {
+ time: formatRelative(task.updatedAt, Date.now(), t),
+ })}
+ </p>
+ </div>
+ {inRouter ? <OpenTaskButton taskId={task.taskId} /> : null}
+ <Button
+ variant="secondary"
+ size="sm"
+ compact
+ type="button"
+ loading={revealing === task.taskId}
+ disabled={revealing !== null && revealing !== task.taskId}
+ onClick={() => void reveal(task)}
+ >
+ {t('settings.ghosts.backgroundTasks.reveal')}
+ </Button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ </section>
+ );
+}
+
+/** 与 /review 审查卡片「打开任务」同一路由;任务不在列表里也能按 id 打开。 */
+function OpenTaskButton({ taskId }: { taskId: string }) {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ return (
+ <Button
+ variant="secondary"
+ size="sm"
+ compact
+ tone="quiet"
+ type="button"
+ onClick={() => navigate(`/cc-agent/${taskId}`)}
+ >
+ {t('settings.ghosts.backgroundTasks.open')}
+ </Button>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
index 539afcbafe..2645b09920 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
@@ -76,7 +76,6 @@ vi.mock('react-i18next', () => ({
'settings.ghosts.detail.expandInfoValue': `Show full ${String(options?.label ?? '')}`,
'settings.ghosts.detail.collapseInfoValue': `Collapse ${String(options?.label ?? '')}`,
'settings.ghosts.detail.panelNotDocked': 'Not docked',
- 'settings.ghosts.detail.cindyPrefs.noModels': 'No models available',
'settings.providers.openai.title': 'OpenAI',
'settings.providers.xd.title': 'Cindy AI',
'settings.defaults.restore': 'Restore default',
@@ -89,7 +88,6 @@ vi.mock('react-i18next', () => ({
}));
import type { GhostPermissionItem } from '../../../../shared/ghost';
-import { CindyCapabilityPrefs } from '@/cindy-brain/CindyCapabilityPrefs';
import {
DetailsSection,
GhostPluginDetailView,
@@ -153,8 +151,8 @@ const detail: GhostPluginDetail = {
permissions: [],
tools: [],
hasSettingsUi: false,
- cindyCapabilities: [],
hasTaskPreferences: false,
+ hasPluginTasks: false,
panelMinWidth: 320,
installDir: '/tmp/cindy-brain/builtin.example',
trust: {
@@ -268,6 +266,23 @@ describe('Ghost plugin detail sections', () => {
unmount();
},
);
+ it('places Background Tasks after settings and before Tools for plugins declaring hiddenTasks', async () => {
+ vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} });
+ const listBackgroundTasks = vi.fn(async () => ({ items: [
+ { taskId: 'bg-1', title: 'Hidden grading', status: 'active' as const, updatedAt: Date.now(), running: false },
+ ] }));
+ Object.assign(window.electronAPI, { ghosts: { listBackgroundTasks, revealBackgroundTask: vi.fn() } });
+ const ghost = { manifest: { agent: { tasks: true, hiddenTasks: true } }, enabled: true, taskCapabilityApproved: true } as InstalledGhost;
+ render(<GhostPluginDetailView ghost={ghost} detail={{ ...detail, tools: [{ name: 'render', description: 'Render.' }] }} panelStatus="Docked" onBack={vi.fn()} onToggle={vi.fn()} onUse={vi.fn()} onUpdate={vi.fn()} onUpdateFromFile={vi.fn()} onUninstall={vi.fn()} toggleDisabled={false} />);
+ expect(await screen.findByText('Hidden grading')).toBeTruthy();
+ expect(listBackgroundTasks).toHaveBeenCalledWith(detail.id);
+ const heading = screen.getByRole('heading', { name: 'settings.ghosts.backgroundTasks.title' });
+ const tools = screen.getByRole('heading', { name: 'Tools' });
+ expect(heading.compareDocumentPosition(tools) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ // Outside a router the open action is omitted; showing in the task list stays available.
+ expect(screen.queryByRole('button', { name: 'settings.ghosts.backgroundTasks.open' })).toBeNull();
+ expect(screen.getByRole('button', { name: 'settings.ghosts.backgroundTasks.reveal' })).toBeTruthy();
+ });
it('lets the user retry task permission, disables duplicate clicks, and hides after approval', async () => {
vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} });
let finish!: (value: { granted: boolean }) => void;
@@ -835,415 +850,68 @@ describe('Ghost plugin detail sections', () => {
expect(screen.getByText('By Cindy').className).toContain('truncate');
});
- it('uses each Cindy capability catalog in the responsive control group', () => {
- Object.defineProperty(window, 'electronAPI', {
- configurable: true,
- value: {
- ghosts: {
- cindyPrefsSync: () => ({
- overrides: {},
- image: {
- options: [
- {
- id: 'image-default',
- label: 'Image Default',
- providerId: 'xd',
- providerName: 'Cindy AI',
- },
- {
- id: 'image-option',
- label: 'Image Option',
- providerId: 'xd',
- providerName: 'Cindy AI',
- },
- ],
- defaultModel: {
- id: 'image-default',
- label: 'Image Default',
- providerId: 'xd',
- providerName: 'Cindy AI',
- },
- },
- imageEdit: {
- options: [
- {
- id: 'image-edit',
- label: 'Image Edit',
- providerId: 'xd',
- providerName: 'Cindy AI',
- },
- {
- id: 'image-edit-option',
- label: 'Image Edit Option',
- providerId: 'xd',
- providerName: 'Cindy AI',
- },
- ],
- defaultModel: {
- id: 'image-edit',
- label: 'Image Edit',
- providerId: 'xd',
- providerName: 'Cindy AI',
- },
- },
- video: {
- options: [{ id: 'video-default', label: 'Video Default' }],
- defaultModel: { id: 'video-default', label: 'Video Default' },
- },
- videoEdit: {
- options: [{ id: 'video-edit', label: 'Video Edit' }],
- defaultModel: { id: 'video-edit', label: 'Video Edit' },
- },
- }),
- setCindyPref: vi.fn(),
- },
- },
- });
-
- const { container } = render(
- <CindyCapabilityPrefs
- ghostId="builtin.example"
- capabilities={['image.generate', 'image.edit']}
- appearance="plugin"
- />,
- );
-
- expect(container.querySelector('.cindy-capability-prefs')).toBeTruthy();
- expect(container.querySelector('.cindy-capability-row')).toBeTruthy();
- const pickers = screen.getAllByRole('combobox');
- expect(pickers).toHaveLength(2);
- fireEvent.click(pickers[0]!);
- expect(within(screen.getByRole('listbox')).getAllByRole('option')).toHaveLength(2);
- expect(screen.getByText('Image Option')).toBeTruthy();
- fireEvent.click(pickers[0]!);
- fireEvent.click(pickers[1]!);
- expect(within(screen.getByRole('listbox')).getAllByRole('option')).toHaveLength(2);
- expect(screen.getByText('Image Edit Option')).toBeTruthy();
- expect(pickers[0]!.className).toContain('max-w-[60%]');
- });
-
- // 2026-08-05:快问快答钉档扩展为目录全量文本模型——富列表选择器(供应商
- // 分组 / 折扣与订阅徽标 / 搜索),身份卡声明偏好时"跟随默认"行如实展示。
- it('text capability uses the shared picker and preserves exact subscription route selection', async () => {
- vi.stubGlobal(
- 'ResizeObserver',
- class {
- observe() {}
- unobserve() {}
- disconnect() {}
- },
- );
- const setCindyPref = vi.fn(async () => ({ overrides: {} }));
- Object.defineProperty(window, 'electronAPI', {
- configurable: true,
- value: {
- ghosts: {
- cindyPrefsSync: () => ({
- overrides: {},
- image: { options: [], defaultModel: null },
- imageEdit: { options: [], defaultModel: null },
- video: { options: [], defaultModel: null },
- videoEdit: { options: [], defaultModel: null },
- text: {
- options: [
- {
- id: 'cat:xd:codex:codex/gpt-5.5',
- label: 'Codex · GPT 5.5 折扣 · Cindy AI',
- group: 'Cindy AI',
- providerId: 'xd',
- agentKind: 'codex',
- modelId: 'codex/gpt-5.5',
- modelName: 'GPT 5.5 折扣',
- agentSuffix: 'Codex',
- budget: true,
- subscription: false,
- },
- {
- id: 'cat:openai:codex:gpt-5.5',
- label: 'Codex · GPT 5.5 · OpenAI',
- group: 'OpenAI',
- providerId: 'openai',
- agentKind: 'codex',
- modelId: 'gpt-5.5',
- modelName: 'GPT 5.5',
- agentSuffix: 'Codex',
- budget: false,
- subscription: true,
- },
- {
- id: 'cat:openai:codex:chatgpt/gpt-5.5',
- label: 'Codex · GPT 5.5 · OpenAI',
- group: 'OpenAI',
- providerId: 'openai',
- agentKind: 'codex',
- modelId: 'chatgpt/gpt-5.5',
- modelName: 'GPT 5.5',
- agentSuffix: 'Codex',
- budget: false,
- subscription: true,
- },
- {
- id: 'cat:openai:claude-code:chatgpt/gpt-5.5',
- label: 'Claude Code · GPT 5.5 · OpenAI',
- group: 'OpenAI',
- providerId: 'openai',
- agentKind: 'claude-code',
- modelId: 'chatgpt/gpt-5.5',
- modelName: 'GPT 5.5',
- agentSuffix: 'Claude Code',
- budget: false,
- subscription: true,
- },
- ],
- defaultModel: { id: 'codex-gpt-5.4-mini', label: 'gpt-5.4-mini · Codex' },
- declaredModel: { id: 'cat:xd:codex:codex/gpt-5.5', label: 'codex/gpt-5.5' },
- },
- }),
- setCindyPref,
- },
- },
- });
-
- render(
- <CindyCapabilityPrefs
- ghostId="xdt-knowledge"
- capabilities={['text.oneshot']}
- appearance="plugin"
- />,
- );
- fireEvent.click(
- screen.getByRole('button', { name: /settings.ghosts.detail.cindyPrefs.cap.text.oneshot/ }),
- );
-
- const listbox = await screen.findByRole('listbox');
- expect(document.querySelector('[data-unified-model-panel]')).toBeTruthy();
- expect(within(listbox).getByRole('group', { name: 'Cindy AI' })).toBeTruthy();
- expect(within(listbox).getByRole('group', { name: 'OpenAI' })).toBeTruthy();
- expect(listbox.querySelector('[data-row-customize]')).not.toBeNull();
- expect(listbox.querySelector('[data-agent-kind]')).toBeNull();
- const plainRow = within(listbox)
- .getByText('GPT 5.5', { exact: true })
- .closest<HTMLElement>('[role="option"]')!;
- expect(within(plainRow).queryByText('settings.providers.models.subscription')).toBeNull();
- fireEvent.click(plainRow);
- await waitFor(() =>
- expect(setCindyPref).toHaveBeenCalledWith(
- 'xdt-knowledge',
- 'text.oneshot',
- 'cat:openai:codex:gpt-5.5',
- ),
- );
- // A different supported Harness must remain reachable after replacing the old Agent step.
- fireEvent.click(
- screen.getByRole('button', { name: /settings.ghosts.detail.cindyPrefs.cap.text.oneshot/ }),
- );
- const reopened = await screen.findByRole('listbox');
- const routeRow = within(reopened)
- .getByText('GPT 5.5', { exact: true })
- .closest<HTMLElement>('[role="option"]')!;
- fireEvent.click(routeRow.querySelector('[data-row-customize]')!);
- const flyout = await screen.findByTestId('unified-model-config-flyout');
- expect(flyout.querySelector('[role="slider"], [data-fast-toggle]')).toBeNull();
- fireEvent.click(flyout.querySelector('[data-engine-capsule="cc"]')!);
- fireEvent.click(routeRow);
- await waitFor(() =>
- expect(setCindyPref).toHaveBeenLastCalledWith(
- 'xdt-knowledge',
- 'text.oneshot',
- 'cat:openai:claude-code:chatgpt/gpt-5.5',
- ),
- );
-
- vi.unstubAllEnvs();
- });
-
- // 2026-08-05 review:存量轻量档位钉(目录扩展前的合法钉值)回显友好名,
- // 不当 stale 露原始 id。
- it('text capability shows a friendly label for a legacy utility-profile pin', () => {
- vi.stubGlobal(
- 'ResizeObserver',
- class {
- observe() {}
- unobserve() {}
- disconnect() {}
- },
- );
- Object.defineProperty(window, 'electronAPI', {
- configurable: true,
- value: {
- ghosts: {
- cindyPrefsSync: () => ({
- overrides: { 'text.oneshot': 'litellm-kimi-k2.6' },
- image: { options: [], defaultModel: null },
- imageEdit: { options: [], defaultModel: null },
- video: { options: [], defaultModel: null },
- videoEdit: { options: [], defaultModel: null },
- text: {
- options: [
- {
- id: 'cat:xd:codex:codex/gpt-5.5',
- label: 'Codex · GPT 5.5 折扣 · Cindy AI',
- group: 'Cindy AI',
- providerId: 'xd',
- agentKind: 'codex',
- modelId: 'codex/gpt-5.5',
- modelName: 'GPT 5.5 折扣',
- budget: true,
- subscription: false,
- },
- ],
- defaultModel: { id: 'codex-gpt-5.4-mini', label: 'gpt-5.4-mini · Codex' },
- utilityProfiles: [{ id: 'litellm-kimi-k2.6', label: 'kimi-k2.6 · Gateway' }],
- },
- }),
- setCindyPref: vi.fn(async () => ({ overrides: {} })),
- },
+ it.each([
+ { name: 'quick answers only', manifest: { cindy: { text: ['oneshot'] } }, taskRows: false },
+ { name: 'plugin tasks', manifest: { agent: { tasks: true } }, taskRows: true },
+ ])('shows one model field for $name and no per-ability model card', ({ manifest, taskRows }) => {
+ vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} });
+ Object.assign(window.electronAPI, {
+ ghosts: {
+ errandPrefsSync: () => ({ config: {}, auxiliaryModelLabel: 'Grok 4.6' }),
+ setErrandConfig: vi.fn(async () => ({ config: {} })),
},
+ showOpenDirectoryDialog: vi.fn(),
});
-
- render(
- <CindyCapabilityPrefs
- ghostId="xdt-knowledge"
- capabilities={['text.oneshot']}
- appearance="plugin"
- />,
- );
- const trigger = screen.getByRole('button', {
- name: /settings.ghosts.detail.cindyPrefs.cap.text.oneshot/,
- });
- expect(trigger.textContent).toContain('kimi-k2.6 · Gateway');
- expect(trigger.textContent).not.toContain('litellm-kimi-k2.6');
- vi.unstubAllEnvs();
- });
-
- // 2026-08-05 review:stale 目录钉(模型已下架)点中 = 当前值,只收起不回写
- // (回写必被白名单拒成「操作失败」);清钉走「跟随默认」行。
- it('stale catalog pin is not rewritten and can be cleared through the default row', async () => {
- vi.stubGlobal(
- 'ResizeObserver',
- class {
- observe() {}
- unobserve() {}
- disconnect() {}
+ const ghost: InstalledGhost = {
+ manifest: {
+ schemaVersion: 3, minCindyVersion: '0.1.0', kind: 'chip', id: 'model-plugin',
+ name: 'Model plugin', version: '1.0.0', entry: 'main.js',
+ ...(manifest as Partial<InstalledGhost['manifest']>),
},
- );
- const setCindyPref = vi.fn(async () => ({ overrides: {} }));
- Object.defineProperty(window, 'electronAPI', {
- configurable: true,
- value: {
- ghosts: {
- cindyPrefsSync: () => ({
- overrides: { 'text.oneshot': 'cat:gone:codex:retired-model' },
- image: { options: [], defaultModel: null },
- imageEdit: { options: [], defaultModel: null },
- video: { options: [], defaultModel: null },
- videoEdit: { options: [], defaultModel: null },
- text: {
- options: [
- {
- id: 'cat:xd:codex:codex/gpt-5.5',
- label: 'Codex · GPT 5.5 折扣 · Cindy AI',
- group: 'Cindy AI',
- providerId: 'xd',
- agentKind: 'codex',
- modelId: 'codex/gpt-5.5',
- modelName: 'GPT 5.5 折扣',
- budget: true,
- subscription: false,
- },
- ],
- defaultModel: { id: 'codex-gpt-5.4-mini', label: 'gpt-5.4-mini · Codex' },
- utilityProfiles: [],
- },
- }),
- setCindyPref,
- },
- },
- });
-
+ dir: '/plugins/model-plugin',
+ namespace: null,
+ enabled: true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000002' },
+ ...(taskRows ? { taskCapabilityApproved: true as const } : {}),
+ trust: detail.trust,
+ };
+ const projected = toGhostPluginDetail(ghost);
+ expect(projected).toMatchObject({ hasTaskPreferences: true, hasPluginTasks: taskRows });
render(
- <CindyCapabilityPrefs
- ghostId="xdt-knowledge"
- capabilities={['text.oneshot']}
- appearance="plugin"
+ <GhostPluginDetailView
+ ghost={ghost}
+ detail={projected}
+ panelStatus={null}
+ onBack={vi.fn()}
+ onToggle={vi.fn()}
+ onUse={vi.fn()}
+ onUpdate={vi.fn()}
+ onUpdateFromFile={vi.fn()}
+ onUninstall={vi.fn()}
+ toggleDisabled={false}
/>,
);
- fireEvent.click(
- screen.getByRole('button', { name: /settings.ghosts.detail.cindyPrefs.cap.text.oneshot/ }),
- );
- const listbox = await screen.findByRole('listbox');
- // Retired pins remain visible on the trigger, but never become selectable routes.
- expect(
- screen.getByRole('button', { name: /settings.ghosts.detail.cindyPrefs.cap.text.oneshot/ })
- .textContent,
- ).toContain('retired-model');
- expect(within(listbox).queryByText('cat:gone:codex:retired-model')).toBeNull();
- expect(setCindyPref).not.toHaveBeenCalled();
- fireEvent.click(within(listbox).getAllByRole('option')[0]!);
- await waitFor(() =>
- expect(setCindyPref).toHaveBeenCalledWith('xdt-knowledge', 'text.oneshot', null),
- );
- vi.unstubAllEnvs();
+ expect(screen.getByText('settings.ghosts.detail.errandPrefs.title')).toBeTruthy();
+ expect(screen.queryByText('settings.ghosts.detail.cindyPrefs.title')).toBeNull();
+ expect(screen.getAllByText('settings.ghosts.detail.errandPrefs.model')).toHaveLength(1);
+ expect(screen.getByText(`settings.ghosts.detail.errandPrefs.${taskRows ? 'desc' : 'descModelOnly'}`)).toBeTruthy();
+ expect(Boolean(screen.queryByText('settings.ghosts.detail.errandPrefs.permission'))).toBe(taskRows);
+ expect(Boolean(screen.queryByText('settings.ghosts.detail.errandPrefs.workdir'))).toBe(taskRows);
});
- it('keeps a reset entry for a stale media override when the catalog has no models', async () => {
- const setCindyPref = vi.fn(async () => ({ overrides: {} }));
- Object.defineProperty(window, 'electronAPI', {
- configurable: true,
- value: {
- ghosts: {
- cindyPrefsSync: () => ({
- overrides: { 'video.generate': 'retired-video-model' },
- image: {
- options: [
- {
- id: 'image-default',
- label: 'Image Default',
- providerId: 'xd',
- providerName: 'Cindy AI',
- },
- ],
- defaultModel: {
- id: 'image-default',
- label: 'Image Default',
- providerId: 'xd',
- providerName: 'Cindy AI',
- },
- },
- imageEdit: {
- options: [{ id: 'image-edit', label: 'Image Edit' }],
- defaultModel: { id: 'image-edit', label: 'Image Edit' },
- },
- // 目录没给视频清单 = 能力暂不可用。
- video: { options: [], defaultModel: null },
- videoEdit: { options: [], defaultModel: null },
- }),
- setCindyPref,
- },
+ it('does not show the model card for media-only plugins (media always follows the system default)', () => {
+ const ghost: InstalledGhost = {
+ manifest: {
+ schemaVersion: 3, minCindyVersion: '0.1.0', kind: 'chip', id: 'art', name: 'Art',
+ version: '1.0.0', entry: 'main.js', cindy: { image: ['generate', 'edit'], embed: ['text'] },
},
- });
-
- const { container } = render(
- <CindyCapabilityPrefs
- ghostId="builtin.example"
- capabilities={['image.generate', 'video.generate', 'video.edit']}
- appearance="plugin"
- />,
- );
-
- // 三行都在(插件确实申请了这三项能力),但只有图像那行给下拉。
- expect(container.querySelectorAll('.cindy-capability-row')).toHaveLength(3);
- expect(screen.getAllByRole('combobox')).toHaveLength(1);
-
- const empties = container.querySelectorAll('.cindy-capability-empty');
- expect(empties).toHaveLength(1);
- expect(empties[0]!.textContent).toBe('No models available');
- expect(empties[0]!.className).toContain('text-[var(--text-tertiary)]');
-
- fireEvent.click(screen.getByRole('button', { name: 'Restore default' }));
- await waitFor(() => {
- expect(setCindyPref).toHaveBeenCalledWith('builtin.example', 'video.generate', null);
- });
+ dir: '/plugins/art',
+ namespace: null,
+ enabled: true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000003' },
+ trust: detail.trust,
+ };
+ expect(toGhostPluginDetail(ghost)).toMatchObject({ hasTaskPreferences: false, hasPluginTasks: false });
});
it('shows only the Tool description after an explicit click', async () => {
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/PluginBackgroundTasksSection.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/PluginBackgroundTasksSection.test.tsx
new file mode 100644
index 0000000000..dda6be1e0c
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/PluginBackgroundTasksSection.test.tsx
@@ -0,0 +1,135 @@
+/**
+ * 插件详情页「后台任务」区块:声明 hiddenTasks 时的列表/空状态、未声明时不占位、
+ * 打开任务走 /cc-agent 路由、「显示到任务列表」调用宿主 IPC 并刷新。
+ * @vitest-environment jsdom
+ */
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const h = vi.hoisted(() => ({
+ patchListeners: new Set<(id: string, patch: Record<string, unknown>) => void>(),
+ toast: { success: vi.fn(), error: vi.fn() },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: Record<string, unknown>) =>
+ options?.time !== undefined ? `${key}:${String(options.time)}` : key,
+ }),
+}));
+vi.mock('@/lib/toast', () => ({ toast: h.toast }));
+vi.mock('@/lib/sessionsStore', () => ({
+ sessionsStore: {
+ subscribePatches: (fn: (id: string, patch: Record<string, unknown>) => void) => {
+ h.patchListeners.add(fn);
+ return () => h.patchListeners.delete(fn);
+ },
+ },
+}));
+
+import { PluginBackgroundTasksSection } from '../PluginBackgroundTasksSection';
+
+const listBackgroundTasks = vi.fn();
+const revealBackgroundTask = vi.fn();
+
+function Location() {
+ const location = useLocation();
+ return <span data-testid="location">{location.pathname}</span>;
+}
+
+function renderSection(props: { installed?: boolean; hiddenTasksDeclared?: boolean } = {}) {
+ return render(
+ <MemoryRouter initialEntries={['/plugins/demo']}>
+ <Routes>
+ <Route path="*" element={(
+ <>
+ <PluginBackgroundTasksSection
+ ghostId="demo"
+ installed={props.installed ?? true}
+ hiddenTasksDeclared={props.hiddenTasksDeclared ?? true}
+ />
+ <Location />
+ </>
+ )} />
+ </Routes>
+ </MemoryRouter>,
+ );
+}
+
+beforeEach(() => {
+ h.patchListeners.clear();
+ listBackgroundTasks.mockReset();
+ revealBackgroundTask.mockReset();
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ ghosts: { listBackgroundTasks, revealBackgroundTask },
+ };
+});
+afterEach(() => {
+ delete (window as unknown as { electronAPI?: unknown }).electronAPI;
+});
+
+describe('PluginBackgroundTasksSection', () => {
+ it('lists hidden tasks with status and last activity, opens them by route and reveals them', async () => {
+ listBackgroundTasks.mockResolvedValueOnce({ items: [
+ { taskId: 'run-1', title: 'Nightly grading', status: 'active', updatedAt: Date.now() - 5 * 60_000, running: true },
+ { taskId: 'old-1', title: 'Old batch', status: 'archived', updatedAt: Date.now() - 2 * 3_600_000, running: false },
+ ] });
+ renderSection();
+ expect(await screen.findByText('Nightly grading')).toBeTruthy();
+ expect(screen.getByRole('heading', { name: 'settings.ghosts.backgroundTasks.title' })).toBeTruthy();
+ expect(screen.getAllByTestId('plugin-background-task')).toHaveLength(2);
+ expect(screen.getByText(/settings\.ghosts\.backgroundTasks\.statusRunning/)).toBeTruthy();
+ expect(screen.getByText(/settings\.ghosts\.backgroundTasks\.statusArchived/)).toBeTruthy();
+ expect(screen.getAllByText(/settings\.ghosts\.backgroundTasks\.lastActive:/)).toHaveLength(2);
+ expect(listBackgroundTasks).toHaveBeenCalledWith('demo');
+
+ fireEvent.click(screen.getAllByRole('button', { name: 'settings.ghosts.backgroundTasks.open' })[0]);
+ expect(screen.getByTestId('location').textContent).toBe('/cc-agent/run-1');
+
+ revealBackgroundTask.mockResolvedValueOnce({ ok: true });
+ listBackgroundTasks.mockResolvedValueOnce({ items: [] });
+ fireEvent.click(screen.getAllByRole('button', { name: 'settings.ghosts.backgroundTasks.reveal' })[1]);
+ await waitFor(() => expect(revealBackgroundTask).toHaveBeenCalledWith('demo', 'old-1'));
+ await waitFor(() => expect(screen.getByText('settings.ghosts.backgroundTasks.empty')).toBeTruthy());
+ expect(h.toast.success).toHaveBeenCalledWith('settings.ghosts.backgroundTasks.revealed');
+ });
+
+ it('shows the empty state when the plugin declares background tasks but has none', async () => {
+ listBackgroundTasks.mockResolvedValue({ items: [] });
+ renderSection();
+ expect(await screen.findByText('settings.ghosts.backgroundTasks.empty')).toBeTruthy();
+ });
+
+ it('refreshes when a hiddenAt patch arrives', async () => {
+ listBackgroundTasks.mockResolvedValueOnce({ items: [] });
+ renderSection();
+ await screen.findByText('settings.ghosts.backgroundTasks.empty');
+ listBackgroundTasks.mockResolvedValueOnce({ items: [
+ { taskId: 'new-1', title: 'Fresh background', status: 'active', updatedAt: Date.now(), running: false },
+ ] });
+ for (const listener of h.patchListeners) listener('other', { title: 'x' });
+ expect(listBackgroundTasks).toHaveBeenCalledTimes(1);
+ for (const listener of h.patchListeners) listener('new-1', { hiddenAt: new Date().toISOString() });
+ expect(await screen.findByText('Fresh background')).toBeTruthy();
+ });
+
+ it('stays out of the page without background tasks and never queries for uninstalled market views', async () => {
+ listBackgroundTasks.mockResolvedValue({ items: [] });
+ const { container } = renderSection({ hiddenTasksDeclared: false });
+ await waitFor(() => expect(listBackgroundTasks).toHaveBeenCalled());
+ expect(container.querySelector('section')).toBeNull();
+ listBackgroundTasks.mockClear();
+ const other = renderSection({ installed: false, hiddenTasksDeclared: false });
+ expect(other.container.querySelector('section')).toBeNull();
+ expect(listBackgroundTasks).not.toHaveBeenCalled();
+ });
+
+ it('still discloses leftover background tasks after the declaration was removed', async () => {
+ listBackgroundTasks.mockResolvedValue({ items: [
+ { taskId: 'left-1', title: 'Left behind', status: 'active', updatedAt: Date.now(), running: false },
+ ] });
+ renderSection({ hiddenTasksDeclared: false });
+ expect(await screen.findByText('Left behind')).toBeTruthy();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
index a1fa649ff4..2c2f925ae6 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
@@ -19,17 +19,6 @@ import { installedGhostStoragePart } from '../../../../shared/pluginIdentity';
import type { PluginMarketItem } from '../../../../shared/pluginMarket';
import { marketItemMatchesInstalledGhost } from './pluginMarketPresentation';
-/**
- * cindy 详单里**可钉后端**的类目 —— 详情页给每个申请到的动作渲染一行模型选择。
- *
- * 新增 cindy 能力类目时必须回到这里登记,否则那个类目在详情页**完全没有选型
- * 入口**(不是少个下拉:`cindyCapabilities` 为空时整张卡片都不渲染),插件只能
- * 吃全局默认档。2026-08-04 加 `embed` 时就漏过一次。
- *
- * `media` 有意不在其中:寄存(deposit)不经模型,没有"用哪个型号"可选。
- */
-const PINNABLE_CINDY_CATEGORIES = ['image', 'video', 'text', 'embed'] as const;
-
export interface GhostPluginListItem {
/** Instance key (storage part). Use this for enable/uninstall/panel IPC. */
id: string;
@@ -84,9 +73,14 @@ export interface GhostPluginDetail extends GhostPluginListItem {
permissions: GhostPermissionItem[];
tools: readonly GhostToolDecl[];
hasSettingsUi: boolean;
- cindyCapabilities: readonly string[];
- /** 新建普通任务的能力共用宿主「任务设置」,包含旧 errand 适配器。 */
+ /**
+ * 宿主「模型与任务」卡:插件的唯一模型字段(快问快答与新建任务共用)。声明了
+ * 快问快答(cindy.text 含 oneshot)或任何新建任务能力即展示;图像/视频/向量
+ * 没有逐插件选模,始终跟随系统默认。
+ */
hasTaskPreferences: boolean;
+ /** 能新建任务(agent.tasks / 旧 agent.errand / workspace):卡片额外展示权限与工作目录。 */
+ hasPluginTasks: boolean;
panelMinWidth: number | null;
installDir: string | null;
}
@@ -309,6 +303,8 @@ export function toGhostPluginDetail(
): GhostPluginDetail {
const listItem = toGhostPluginListItem(ghost, presentation);
const { manifest } = ghost;
+ const hasPluginTasks =
+ !!manifest.workspace || manifest.agent?.errand === true || manifest.agent?.tasks === true;
return {
...listItem,
trust: listItem.trust!,
@@ -317,10 +313,8 @@ export function toGhostPluginDetail(
permissions: ghostPermissionItems(manifest),
tools: manifest.tools ?? [],
hasSettingsUi: Boolean(manifest.settingsHtml),
- cindyCapabilities: PINNABLE_CINDY_CATEGORIES.flatMap((category) =>
- (manifest.cindy?.[category] ?? []).map((action) => `${category}.${action}`),
- ),
- hasTaskPreferences: !!manifest.workspace || manifest.agent?.errand === true || manifest.agent?.tasks === true,
+ hasTaskPreferences: hasPluginTasks || (manifest.cindy?.text ?? []).includes('oneshot'),
+ hasPluginTasks,
panelMinWidth: manifest.panel ? (manifest.panel.minWidth ?? 280) : null,
installDir: ghost.dir,
};
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 911d102391..57482d1873 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -6366,6 +6366,8 @@
"agentTasksRequest": "Review task permission",
"agentTasks": "Can create and manage its own Cindy tasks",
"agentTasksDetail": "Can send messages, read results and stop its own executions. Tasks remain visible to you. Uses this plugin’s AI settings and may incur model charges; does not grant access to other tasks.",
+ "agentHiddenTasks": "Can create background tasks hidden from the task list",
+ "agentHiddenTasksDetail": "Tasks this plugin creates can stay out of the task list, search and notifications. You can always view, open or show them in the task list from Background Tasks on this plugin’s page; uninstalling the plugin shows them again.",
"agentErrand": "Create tasks, perform work, and read results",
"agentErrandDetail": "Created tasks appear in Cindy’s task list, where you can view progress and continue the conversation.",
"agentSchedule": "Can ask you to create an automation",
@@ -6486,28 +6488,12 @@
"infoVersion": "Version",
"updateTitle": "Update version",
"updateDesc": "Pick a new .cindy file to replace the installed version in place; enabled state and panel position are preserved.",
- "cindyPrefs": {
- "title": "Cindy abilities",
- "desc": "Each Cindy delegation ability this plugin requested can be pinned to a specific model; defaults follow the system (built-in proxy).",
- "cap": {
- "image.generate": "Image generation",
- "image.edit": "Image editing",
- "video.generate": "Video generation",
- "video.edit": "Image-to-video",
- "text.oneshot": "Quick answer (text)",
- "embed.text": "Text to vector"
- },
- "defaultOption": "{{model}} (default)",
- "defaultOptionDeclared": "{{model}} (plugin declared)",
- "searchPlaceholder": "Search models or providers",
- "budgetBadge": "Discount",
- "noModels": "No models available"
- },
"errandPrefs": {
- "title": "Task settings",
- "desc": "For tasks created by this plugin. New tasks use the originating task’s model, or the current new-task selection when created from a panel. Existing tasks keep their own model. Permissions are set separately and use ordinary task defaults. Full access is never inherited.",
- "legacyDesc": "For tasks created by this plugin. New tasks use the originating task’s model, or the current new-task selection when created from a panel. Existing tasks keep their own model. The legacy API retains its original permissions until you explicitly choose a mode.",
+ "title": "Model & tasks",
+ "desc": "Used for this plugin’s quick answers and the tasks it creates; defaults to the system auxiliary model, and new tasks default to the originating task’s model.",
+ "descModelOnly": "Used for this plugin’s quick answers; defaults to the system auxiliary model.",
"legacyPermission": "Keep original permissions",
+ "legacyPermissionHint": "The legacy API keeps its original permissions until you choose a mode.",
"agent": "Agent",
"model": "Model",
"permission": "Write access",
@@ -6516,8 +6502,8 @@
"workdirDefault": "Plugin's dedicated folder (default)",
"workdirPick": "Choose…",
"workdirClear": "Reset to default folder",
- "sourceDefault": "Follow the originating task; panel default shown below",
- "sourceCustom": "Use the model selected for this plugin",
+ "followAuxiliary": "Follow system auxiliary model · {{model}}",
+ "followAuxiliaryUnset": "Follow system auxiliary model",
"restoreModel": "Reset model"
},
"toolsTitle": "Tools",
@@ -6573,6 +6559,22 @@
"commandPaletteSource": {
"team": "Team shared"
},
+ "backgroundTasks": {
+ "title": "Background Tasks",
+ "description": "Tasks this plugin runs in the background, outside the task list. Open one to check it, or show it in the task list to use it as usual.",
+ "refresh": "Refresh Background Tasks",
+ "loading": "Loading background tasks…",
+ "loadFailed": "Could not load background tasks",
+ "empty": "No background tasks",
+ "statusRunning": "Running",
+ "statusIdle": "Idle",
+ "statusArchived": "Archived",
+ "lastActive": "Last activity {{time}}",
+ "open": "Open Task",
+ "reveal": "Show in Task List",
+ "revealed": "Task shown in the task list",
+ "revealFailed": "Could not show the task in the task list"
+ },
"library": {
"title": "Durable library",
"loading": "Loading library info…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index f917a04a09..6b5b09aa06 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -6341,6 +6341,8 @@
"agentTasksRequest": "セッション権限を確認",
"agentTasks": "このプラグインの Cindy セッションを作成・管理できます",
"agentTasksDetail": "メッセージの送信、結果の読み取り、自身の実行の停止ができます。セッションはユーザーに表示されます。プラグインの AI 設定を使用し、モデル料金が発生する場合があります。他のセッションへのアクセスは許可されません。",
+ "agentHiddenTasks": "セッションリストに表示されないバックグラウンドセッションを作成できます",
+ "agentHiddenTasksDetail": "このプラグインが作成したセッションを、セッションリスト・検索・通知に表示しないようにできます。プラグイン詳細の「バックグラウンドセッション」からいつでも確認したり開いたり、セッションリストに表示したりできます。プラグインをアンインストールすると再び表示されます。",
"agentErrand": "タスクを作成し、作業を実行して結果を取得できます",
"agentErrandDetail": "作成したタスクは Cindy のタスク一覧に表示され、進行状況を確認して会話を続けられます。",
"agentSchedule": "自動化の新規作成をあなたに依頼できます",
@@ -6461,28 +6463,12 @@
"infoVersion": "バージョン",
"updateTitle": "バージョン更新",
"updateDesc": "新しい .cindy ファイルを選んでその場で置き換えます。有効状態とパネル位置は保持されます。",
- "cindyPrefs": {
- "title": "Cindy 能力",
- "desc": "このプラグインが申請した Cindy 代行能力ごとに使用モデルを指定できます。既定ではシステム(内蔵プロキシ)に従います。",
- "cap": {
- "image.generate": "画像生成",
- "image.edit": "画像編集",
- "video.generate": "動画生成",
- "video.edit": "画像から動画",
- "text.oneshot": "クイック回答(テキスト)",
- "embed.text": "テキストのベクトル化"
- },
- "defaultOption": "{{model}}(既定)",
- "defaultOptionDeclared": "{{model}}(プラグイン宣言)",
- "searchPlaceholder": "モデルやプロバイダを検索",
- "budgetBadge": "割引",
- "noModels": "利用可能なモデルなし"
- },
"errandPrefs": {
- "title": "タスク設定",
- "desc": "このプラグインが作成するタスクの設定です。新規タスクは呼び出し元のモデルを使い、パネルから作成する場合は現在の新規タスクの選択を使います。既存タスクのモデルは維持されます。権限は別途設定し、通常のタスクの既定権限を使います。フルアクセスは継承しません。",
- "legacyDesc": "このプラグインが作成するタスクの設定です。新規タスクは呼び出し元のモデルを使い、パネルから作成する場合は現在の新規タスクの選択を使います。既存タスクのモデルは維持されます。旧 API は元の権限を維持します。権限を選ぶと、その設定を使用します。",
+ "title": "モデルとタスク",
+ "desc": "このプラグインのクイック回答と、プラグインが作成するタスクに使うモデルです。既定ではシステムの補助モデルに従い、新規タスクは呼び出し元タスクのモデルを使います。",
+ "descModelOnly": "このプラグインのクイック回答に使うモデルです。既定ではシステムの補助モデルに従います。",
"legacyPermission": "元の権限を維持",
+ "legacyPermissionHint": "旧 API は元の権限を維持します。権限を選ぶと、その設定を使用します。",
"agent": "Agent",
"model": "モデル",
"permission": "書き込み権限",
@@ -6491,8 +6477,8 @@
"workdirDefault": "プラグイン専用フォルダー(既定)",
"workdirPick": "選択…",
"workdirClear": "既定のフォルダーに戻す",
- "sourceDefault": "呼び出し元に従う(下はパネル作成時のモデル)",
- "sourceCustom": "このプラグイン用に選択したモデル",
+ "followAuxiliary": "システムの補助モデルに従う · {{model}}",
+ "followAuxiliaryUnset": "システムの補助モデルに従う",
"restoreModel": "モデルをリセット"
},
"toolsTitle": "Tools",
@@ -6548,6 +6534,22 @@
"commandPaletteSource": {
"team": "チーム共有"
},
+ "backgroundTasks": {
+ "title": "バックグラウンドセッション",
+ "description": "このプラグインがバックグラウンドで実行している、セッションリストに表示されないセッションです。開いて確認するか、セッションリストに表示して通常どおり使用できます。",
+ "refresh": "バックグラウンドセッションを更新",
+ "loading": "バックグラウンドセッションを読み込み中…",
+ "loadFailed": "バックグラウンドセッションを読み込めませんでした",
+ "empty": "バックグラウンドセッションはありません",
+ "statusRunning": "実行中",
+ "statusIdle": "待機中",
+ "statusArchived": "アーカイブ済み",
+ "lastActive": "最終アクティビティ {{time}}",
+ "open": "セッションを開く",
+ "reveal": "セッションリストに表示",
+ "revealed": "セッションをセッションリストに表示しました",
+ "revealFailed": "セッションをセッションリストに表示できませんでした"
+ },
"library": {
"title": "永続ライブラリ",
"loading": "ライブラリ情報を読み込み中…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 4a812337ff..4b1e0e50d1 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -6341,6 +6341,8 @@
"agentTasksRequest": "세션 권한 확인",
"agentTasks": "이 플러그인의 Cindy 세션을 만들고 관리할 수 있음",
"agentTasksDetail": "메시지를 보내고 결과를 읽으며 자신의 실행을 중지할 수 있습니다. 세션은 사용자에게 표시됩니다. 플러그인의 AI 설정을 사용하며 모델 비용이 발생할 수 있습니다. 다른 세션에 대한 접근 권한은 부여하지 않습니다.",
+ "agentHiddenTasks": "세션 목록에 표시되지 않는 백그라운드 세션을 만들 수 있음",
+ "agentHiddenTasksDetail": "이 플러그인이 만든 세션을 세션 목록, 검색, 알림에 표시하지 않을 수 있습니다. 플러그인 상세의 「백그라운드 세션」에서 언제든지 확인하고 열거나 세션 목록에 표시할 수 있으며, 플러그인을 제거하면 다시 표시됩니다.",
"agentErrand": "작업을 만들고 실행하며 결과를 읽을 수 있습니다",
"agentErrandDetail": "생성된 작업은 Cindy 작업 목록에 표시되며 진행 상황을 확인하고 대화를 이어갈 수 있습니다.",
"agentSchedule": "자동화 새로 만들기를 요청할 수 있음",
@@ -6461,28 +6463,12 @@
"infoVersion": "버전",
"updateTitle": "버전 업데이트",
"updateDesc": "새 .cindy 파일을 선택해 설치된 버전을 그 자리에서 교체합니다. 활성 상태와 패널 위치는 유지됩니다.",
- "cindyPrefs": {
- "title": "Cindy 능력",
- "desc": "이 플러그인이 신청한 각 Cindy 대행 능력마다 사용할 모델을 지정할 수 있습니다. 기본값은 시스템(내장 프록시)을 따릅니다.",
- "cap": {
- "image.generate": "이미지 생성",
- "image.edit": "이미지 편집",
- "video.generate": "영상 생성",
- "video.edit": "이미지로 영상",
- "text.oneshot": "빠른 답변(텍스트)",
- "embed.text": "텍스트 벡터 변환"
- },
- "defaultOption": "{{model}} (기본값)",
- "defaultOptionDeclared": "{{model}}(플러그인 선언)",
- "searchPlaceholder": "모델 또는 제공자 검색",
- "budgetBadge": "할인",
- "noModels": "사용 가능한 모델 없음"
- },
"errandPrefs": {
- "title": "작업 설정",
- "desc": "이 플러그인이 만드는 작업의 설정입니다. 새 작업은 호출한 작업의 모델을 사용하며, 패널에서 만들면 현재 새 작업의 선택을 사용합니다. 기존 작업은 자신의 모델을 유지합니다. 권한은 별도로 설정하며 일반 작업의 기본 권한을 사용합니다. 전체 접근 권한은 상속하지 않습니다.",
- "legacyDesc": "이 플러그인이 만드는 작업의 설정입니다. 새 작업은 호출한 작업의 모델을 사용하며, 패널에서 만들면 현재 새 작업의 선택을 사용합니다. 기존 작업은 자신의 모델을 유지합니다. 기존 API는 원래 권한을 유지합니다. 권한을 선택하면 해당 설정을 사용합니다.",
+ "title": "모델 및 작업",
+ "desc": "이 플러그인의 빠른 답변과 플러그인이 만드는 작업에 사용할 모델입니다. 기본적으로 시스템 보조 모델을 따르며, 새 작업은 호출한 작업의 모델을 사용합니다.",
+ "descModelOnly": "이 플러그인의 빠른 답변에 사용할 모델입니다. 기본적으로 시스템 보조 모델을 따릅니다.",
"legacyPermission": "기존 권한 유지",
+ "legacyPermissionHint": "기존 API는 원래 권한을 유지합니다. 권한을 선택하면 해당 설정을 사용합니다.",
"agent": "Agent",
"model": "모델",
"permission": "쓰기 권한",
@@ -6491,8 +6477,8 @@
"workdirDefault": "플러그인 전용 폴더(기본)",
"workdirPick": "선택…",
"workdirClear": "기본 폴더로 되돌리기",
- "sourceDefault": "호출한 작업 따르기 · 아래는 패널의 기본 모델",
- "sourceCustom": "이 플러그인용으로 선택한 모델 사용",
+ "followAuxiliary": "시스템 보조 모델 따르기 · {{model}}",
+ "followAuxiliaryUnset": "시스템 보조 모델 따르기",
"restoreModel": "모델 초기화"
},
"toolsTitle": "Tools",
@@ -6548,6 +6534,22 @@
"commandPaletteSource": {
"team": "팀 공유"
},
+ "backgroundTasks": {
+ "title": "백그라운드 세션",
+ "description": "이 플러그인이 백그라운드에서 실행하며 세션 목록에 표시되지 않는 세션입니다. 열어서 확인하거나 세션 목록에 표시해 평소처럼 사용할 수 있습니다.",
+ "refresh": "백그라운드 세션 새로 고침",
+ "loading": "백그라운드 세션을 불러오는 중…",
+ "loadFailed": "백그라운드 세션을 불러오지 못했습니다",
+ "empty": "백그라운드 세션이 없습니다",
+ "statusRunning": "실행 중",
+ "statusIdle": "대기 중",
+ "statusArchived": "보관됨",
+ "lastActive": "마지막 활동 {{time}}",
+ "open": "세션 열기",
+ "reveal": "세션 목록에 표시",
+ "revealed": "세션을 세션 목록에 표시했습니다",
+ "revealFailed": "세션을 세션 목록에 표시하지 못했습니다"
+ },
"library": {
"title": "영구 라이브러리",
"loading": "라이브러리 정보를 불러오는 중…",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 0b80ef02ae..e78c9f69b1 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -6341,6 +6341,8 @@
"agentTasksRequest": "确认任务权限",
"agentTasks": "可创建和管理本插件的 Cindy 任务",
"agentTasksDetail": "可发送消息、读取结果和停止本插件的执行,任务对你可见。沿用插件的 AI 配置,可能产生模型费用;不授予其他任务的访问权。",
+ "agentHiddenTasks": "可创建不显示在任务列表里的后台任务",
+ "agentHiddenTasksDetail": "本插件创建的任务可以不出现在任务列表、搜索和通知里。你可以随时在插件详情的「后台任务」中查看、打开,或显示到任务列表;卸载插件时这些任务会恢复显示。",
"agentErrand": "可以新建任务、执行工作并读取结果",
"agentErrandDetail": "创建的任务会出现在 Cindy 的任务列表中,可以查看过程并继续交流。",
"agentSchedule": "可以请你新建自动化",
@@ -6461,28 +6463,12 @@
"infoVersion": "版本",
"updateTitle": "更新版本",
"updateDesc": "选择新的 .cindy 文件原位替换;启用状态与面板位置保持不变。",
- "cindyPrefs": {
- "title": "Cindy 能力",
- "desc": "这个插件申请的每项 Cindy 代办能力,可单独指定用哪个模型;默认跟随系统(自带 Proxy)。",
- "cap": {
- "image.generate": "出图",
- "image.edit": "改图",
- "video.generate": "生成视频",
- "video.edit": "图生视频",
- "text.oneshot": "快问快答(文字)",
- "embed.text": "文本转向量"
- },
- "defaultOption": "{{model}}(默认)",
- "defaultOptionDeclared": "{{model}}(插件声明)",
- "searchPlaceholder": "搜索模型或供应商",
- "budgetBadge": "折扣",
- "noModels": "暂无可用模型"
- },
"errandPrefs": {
- "title": "任务设置",
- "desc": "用于插件创建的任务。默认沿用发起任务的模型;从面板新建时使用当前新任务选择。已有任务保留自己的模型。权限独立设置,默认使用普通任务的默认权限,不继承完全访问。",
- "legacyDesc": "用于插件创建的任务。默认沿用发起任务的模型;从面板新建时使用当前新任务选择。已有任务保留自己的模型。旧接口保留原有权限行为;选择权限后按你的设置执行。",
+ "title": "模型与任务",
+ "desc": "模型用于这个插件的快问快答和它新建的任务,默认跟随系统辅助模型;新建任务默认沿用发起任务的模型。",
+ "descModelOnly": "模型用于这个插件的快问快答,默认跟随系统辅助模型。",
"legacyPermission": "保留原权限设置",
+ "legacyPermissionHint": "旧接口保留原有权限行为;选择权限后按你的设置执行。",
"agent": "Agent",
"model": "模型",
"permission": "动手权限",
@@ -6491,8 +6477,8 @@
"workdirDefault": "插件专属文件夹(默认)",
"workdirPick": "选择…",
"workdirClear": "恢复默认目录",
- "sourceDefault": "跟随发起任务;下方预览面板新建模型",
- "sourceCustom": "使用为此插件选择的模型",
+ "followAuxiliary": "跟随系统辅助模型 · {{model}}",
+ "followAuxiliaryUnset": "跟随系统辅助模型",
"restoreModel": "恢复默认模型"
},
"toolsTitle": "Tools",
@@ -6548,6 +6534,22 @@
"commandPaletteSource": {
"team": "团队共享"
},
+ "backgroundTasks": {
+ "title": "后台任务",
+ "description": "本插件放在后台运行、不显示在任务列表里的任务。可以打开查看,或显示到任务列表后照常使用。",
+ "refresh": "刷新后台任务",
+ "loading": "正在读取后台任务…",
+ "loadFailed": "未能读取后台任务",
+ "empty": "暂无后台任务",
+ "statusRunning": "运行中",
+ "statusIdle": "空闲",
+ "statusArchived": "已归档",
+ "lastActive": "最后活动 {{time}}",
+ "open": "打开任务",
+ "reveal": "显示到任务列表",
+ "revealed": "任务已显示到任务列表",
+ "revealFailed": "未能将任务显示到任务列表"
+ },
"library": {
"title": "持久作品库",
"loading": "正在读取库信息…",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 02ad464939..1b15646701 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -6341,6 +6341,8 @@
"agentTasksRequest": "確認任務權限",
"agentTasks": "可建立和管理本插件的 Cindy 任務",
"agentTasksDetail": "可傳送訊息、讀取結果和停止本插件的執行,任務對你可見。沿用插件的 AI 配置,可能產生模型費用;不授予其他任務的存取權。",
+ "agentHiddenTasks": "可建立不顯示在任務列表裡的後臺任務",
+ "agentHiddenTasksDetail": "本插件建立的任務可以不出現在任務列表、搜尋和通知裡。你可以隨時在插件詳情的「後臺任務」中查看、開啟,或顯示到任務列表;解除安裝插件時這些任務會恢復顯示。",
"agentErrand": "可建立任務、執行工作並讀取結果",
"agentErrandDetail": "建立的任務會顯示在 Cindy 任務列表中,可查看過程並繼續交流。",
"agentSchedule": "可以請你新建自動化",
@@ -6461,28 +6463,12 @@
"infoVersion": "版本",
"updateTitle": "更新版本",
"updateDesc": "選擇新的 .cindy 檔案原位替換;生效狀態與面板位置保持不變。",
- "cindyPrefs": {
- "title": "Cindy 能力",
- "desc": "這個插件申請的每項 Cindy 代辦能力,可單獨指定用哪個模型;預設跟隨系統(自帶 Proxy)。",
- "cap": {
- "image.generate": "出圖",
- "image.edit": "改圖",
- "video.generate": "生成影片",
- "video.edit": "圖生影片",
- "text.oneshot": "快問快答(文字)",
- "embed.text": "文字轉向量"
- },
- "defaultOption": "{{model}}(預設)",
- "defaultOptionDeclared": "{{model}}(插件宣告)",
- "searchPlaceholder": "搜尋模型或供應商",
- "budgetBadge": "折扣",
- "noModels": "暫無可用模型"
- },
"errandPrefs": {
- "title": "任務設定",
- "desc": "用於插件建立的任務。預設沿用發起任務的模型;從面板新建時使用目前的新任務選擇。已有任務保留自己的模型。權限獨立設定,預設使用一般任務的預設權限,不繼承完全存取。",
- "legacyDesc": "用於插件建立的任務。預設沿用發起任務的模型;從面板新建時使用目前的新任務選擇。已有任務保留自己的模型。舊介面保留原有權限行為;選擇權限後依你的設定執行。",
+ "title": "模型與任務",
+ "desc": "模型用於這個插件的快問快答和它新建的任務,預設跟隨系統輔助模型;新建任務預設沿用發起任務的模型。",
+ "descModelOnly": "模型用於這個插件的快問快答,預設跟隨系統輔助模型。",
"legacyPermission": "保留原權限設定",
+ "legacyPermissionHint": "舊介面保留原有權限行為;選擇權限後依你的設定執行。",
"agent": "Agent",
"model": "模型",
"permission": "動手權限",
@@ -6491,8 +6477,8 @@
"workdirDefault": "插件專屬資料夾(預設)",
"workdirPick": "選擇…",
"workdirClear": "恢復預設目錄",
- "sourceDefault": "跟隨發起任務;下方預覽面板新建模型",
- "sourceCustom": "使用為此插件選擇的模型",
+ "followAuxiliary": "跟隨系統輔助模型 · {{model}}",
+ "followAuxiliaryUnset": "跟隨系統輔助模型",
"restoreModel": "還原預設模型"
},
"toolsTitle": "Tools",
@@ -6548,6 +6534,22 @@
"commandPaletteSource": {
"team": "團隊共享"
},
+ "backgroundTasks": {
+ "title": "後臺任務",
+ "description": "本插件放在後臺執行、不顯示在任務列表裡的任務。可以開啟查看,或顯示到任務列表後照常使用。",
+ "refresh": "重新整理後臺任務",
+ "loading": "正在讀取後臺任務…",
+ "loadFailed": "未能讀取後臺任務",
+ "empty": "暫無後臺任務",
+ "statusRunning": "執行中",
+ "statusIdle": "閒置",
+ "statusArchived": "已封存",
+ "lastActive": "最後活動 {{time}}",
+ "open": "開啟任務",
+ "reveal": "顯示到任務列表",
+ "revealed": "任務已顯示到任務列表",
+ "revealFailed": "未能將任務顯示到任務列表"
+ },
"library": {
"title": "持久作品庫",
"loading": "正在讀取庫資訊…",
diff --git a/apps/desktop/src/renderer/lib/ccAgent.types.ts b/apps/desktop/src/renderer/lib/ccAgent.types.ts
index 26f8b5c7e8..f4e2b9c208 100644
--- a/apps/desktop/src/renderer/lib/ccAgent.types.ts
+++ b/apps/desktop/src/renderer/lib/ccAgent.types.ts
@@ -361,6 +361,12 @@ export interface Session {
planModeEnabled?: boolean;
clearedAt: string | null; // ISO 8601 — messages before this timestamp are hidden
pinnedAt: string | null; // ISO 8601 — when pinned, null = not pinned
+ /**
+ * 插件后台隐藏时刻(ISO 8601)。非 null = 声明 `agent.hiddenTasks` 的插件创建/切换的后台任务,
+ * 主进程任务列表已排除;只会出现在单任务读取(插件详情页「后台任务」打开或深链)。
+ * 老 payload 缺失按 null(可见)处理。
+ */
+ hiddenAt?: string | null;
/**
* 用户最近一次"按下发送"的时刻(ISO 8601,null = 从未发过)。
* Sidebar 排序唯一时间轴:null ⟺ 草稿(归未分类),非 null 即按倒序上浮。
diff --git a/apps/desktop/src/renderer/lib/sessionEventNotification.ts b/apps/desktop/src/renderer/lib/sessionEventNotification.ts
index 30608a3c20..8ff0c45cc8 100644
--- a/apps/desktop/src/renderer/lib/sessionEventNotification.ts
+++ b/apps/desktop/src/renderer/lib/sessionEventNotification.ts
@@ -40,19 +40,29 @@ export function findSessionNotificationSession<T extends { id: string; title?: u
export const BOT_GROUP_LANE_SESSION: unique symbol = Symbol('bot-group-lane-session');
/**
- * /review Reviewer tasks are omitted from the ordinary task list and never notify
- * on their own: the result is published to the source task, which is where the
- * user (and the source agent) continues.
+ * Tasks omitted from the ordinary task list never notify on their own:
+ * - /review Reviewer tasks publish their result to the source task, which is where
+ * the user (and the source agent) continues;
+ * - plugin background tasks (`hiddenAt`) are disclosed on the plugin detail page
+ * and notify again once the user shows them in the task list.
*/
export async function isReviewSessionNotificationTarget(sessionId: string): Promise<boolean> {
const row = await window.electronAPI.localDb.sessions.get(sessionId).catch(() => null);
return (
!!row
&& typeof row === 'object'
- && isReviewSessionSource((row as { source?: unknown }).source)
+ && (
+ isReviewSessionSource((row as { source?: unknown }).source)
+ || isBackgroundTaskNotificationTarget(row as { hiddenAt?: unknown })
+ )
);
}
+/** Plugin background task: no OS / in-app completion notification while hidden. */
+export function isBackgroundTaskNotificationTarget(session: { hiddenAt?: unknown } | null | undefined): boolean {
+ return typeof session?.hiddenAt === 'string' && session.hiddenAt.length > 0;
+}
+
/** Resolve Bot-owned tasks omitted from the ordinary desktop session list. */
export async function botOwnedSessionNotificationTitle(
sessionId: string,
diff --git a/apps/desktop/src/renderer/lib/sessionsStore.ts b/apps/desktop/src/renderer/lib/sessionsStore.ts
index 47599879d8..d06ae02a03 100644
--- a/apps/desktop/src/renderer/lib/sessionsStore.ts
+++ b/apps/desktop/src/renderer/lib/sessionsStore.ts
@@ -88,6 +88,18 @@ class SessionBucketCache extends Map<ListStatusFilter, Session[]> {
const cache = new SessionBucketCache();
const inflight = new Map<ListStatusFilter, Promise<Session[]>>();
+/**
+ * 已收到「转入后台」推送(hiddenAt 非空)的任务。推送可能早于任务进缓存(首次列表请求
+ * 在途),所以不论当时是否移除了行都登记;列表响应与本地插入写缓存前据此过滤,直到
+ * 收到 hiddenAt:null(恢复显示)。
+ */
+const hiddenSessionIds = new Set<string>();
+
+function withoutHiddenSessions(list: Session[]): Session[] {
+ if (hiddenSessionIds.size === 0) return list;
+ const next = list.filter((session) => !hiddenSessionIds.has(session.id));
+ return next.length === list.length ? list : next;
+}
/** 列表请求期间收到的 session 费用权威值及其本地事件版本。 */
interface SessionSpendOverride {
revision: number;
@@ -702,7 +714,9 @@ export const sessionsStore = {
let promise = inflight.get(filter);
if (!promise) {
const request = fetchFilter(filter, opts)
- .then((data) => {
+ .then((fetched) => {
+ // 转入后台推送可能早于这次列表响应到达:提交前按已知后台任务过滤。
+ const data = withoutHiddenSessions(fetched);
// reset / forceRefresh 会把旧 request 从 inflight 移除。只有仍被
// 当前桶认领的 request 才能提交,避免旧账号请求回填新账号缓存。
if (inflight.get(filter) === request) {
@@ -958,6 +972,26 @@ export const sessionsStore = {
*/
patchLocal(id: string, patch: Partial<Session>): void {
if (!id || !patch) return;
+ // 插件把任务转入后台(hiddenAt 非空):主进程列表已排除它,这里与删除一样从所有桶
+ // 就地移除;再整体重拉一次,补齐满桶空位并压过转入后台前发出的旧列表请求。
+ // 不论当时是否在缓存里都登记,挡住随后到达的旧列表响应。恢复显示的 hiddenAt:null
+ // 只解除登记,再由紧随的 sessions:created 推送触发重拉。
+ if (typeof patch.hiddenAt === 'string' && patch.hiddenAt.length > 0) {
+ hiddenSessionIds.add(id);
+ const row = this.findById(id);
+ let removed = false;
+ for (const [filter, list] of cache) {
+ const next = list.filter((session) => session.id !== id);
+ if (next.length === list.length) continue;
+ cache.set(filter, next);
+ removed = true;
+ }
+ if (removed) notify();
+ patchSubs.forEach((fn) => fn(id, patch, row ? mergeSession(row, patch) : null));
+ if (removed) void this.forceRefreshAll().catch(() => undefined);
+ return;
+ }
+ if (patch.hiddenAt === null) hiddenSessionIds.delete(id);
const pendingBeforePatch =
patch.status !== undefined ? pendingStatusTransitions.get(id) : undefined;
const sourceSession = patch.status !== undefined ? this.findById(id) : null;
@@ -1098,6 +1132,8 @@ export const sessionsStore = {
if (session.source === 'bot') return;
// /review 审查任务同样不进普通任务列表,只从来源任务的审查卡片打开。
if (session.source === 'review') return;
+ // 已转入后台的任务不经本地插入回到列表。
+ if (hiddenSessionIds.has(session.id)) return;
// 插入前叠乐观预览:createSession 往往先于 sessions:created 刷新返回,但预览
// 必须在入库前就登记。若不在这里叠,第一帧仍是哨兵,用户会先看到「未命名任务」。
const [withPreview] = applyAutoTitlePreviews([session]);
@@ -1119,6 +1155,7 @@ export const sessionsStore = {
autoTitlePreviews.clear();
sessionTitleOverrides.clear();
sessionStatusOverrides.clear();
+ hiddenSessionIds.clear();
statusTransitionGeneration += 1;
pendingStatusTransitions.clear();
for (const waiters of pendingStatusTransitionWaiters.values()) {
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 6bfccf2548..b031177c82 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1121,22 +1121,6 @@ interface GoalStatusPayload {
lastReason: string | null;
}
-type CindyMediaPreferenceOption = {
- id: string;
- label: string;
- group: string;
- providerId: string;
- providerName: string;
- modelId: string;
- modelName: string;
- routing?: import('@cindy/model-providers').Provider['routing'];
-};
-
-type CindyMediaPreferenceKind = {
- options: CindyMediaPreferenceOption[];
- defaultModel: CindyMediaPreferenceOption | null;
-};
-
type ElectronLocalDbSessionListOptions = {
/** Local list continuation; does not change the default capped query. */
before?: { updatedAt: number; id: string };
@@ -1343,55 +1327,14 @@ interface ElectronAPI {
},
) => Promise<{ ghost: import('../shared/ghost').InstalledGhost }>;
/**
- * cindy 槽后端覆盖:首帧同步读(规则 7);overrides 键为 "image.generate"
- * 等能力键;image/video 各一份下拉数据,defaultModel = 目录默认
- * 选型的展示信息("默认(GPT Image 2)")。
- * options 空 + defaultModel null = 目录没给该类目模型(能力暂不可用),
- * 渲染层显示灰字而非下拉。
+ * 插件「模型与任务」配置:首帧同步读(规则 7);config 缺项 = 跟随默认。
+ * 模型字段同时用于快问快答与插件新建任务;auxiliaryModelLabel = 当前系统
+ * 辅助模型显示名(未选模型时快问快答跟随它;旧主进程缺省)。
*/
- cindyPrefsSync: (id: string) => {
- overrides: Record<string, string>;
- image: CindyMediaPreferenceKind;
- imageEdit: CindyMediaPreferenceKind;
- video: CindyMediaPreferenceKind;
- videoEdit: CindyMediaPreferenceKind;
- /** 文本类(快问快答):选项是当前供应商目录的全部文本模型(cat: 编码钉值,
- * 带供应商/模型/徽标等结构化字段供富列表渲染);declaredModel = 身份卡声明
- * 的偏好模型(目录里解析得到才给,"跟随默认"行据此如实展示实际路由)。 */
- text: {
- options: Array<{
- id: string;
- label: string;
- group: string;
- providerId: string;
- agentKind: string;
- modelId: string;
- modelName: string;
- icon?: string;
- budget: boolean;
- subscription: boolean;
- routing?: ProviderRoutingPayload;
- agentSuffix?: string;
- }>;
- defaultModel: { id: string; label: string } | null;
- declaredModel?: { id: string; label: string } | null;
- /** 存量轻量档位钉(目录扩展前的合法钉值)的展示名表,老钉值回显友好名用。 */
- utilityProfiles?: Array<{ id: string; label: string }>;
- };
- /** 向量类(文本转向量):同 image/video 走目录派生。 */
- embed: {
- options: Array<{ id: string; label: string }>;
- defaultModel: { id: string; label: string } | null;
- };
+ errandPrefsSync: (id: string) => {
+ config: Record<string, unknown>;
+ auxiliaryModelLabel?: string | null;
};
- /** 写/清一项覆盖(model=null 即恢复跟随默认);返回该意识最新覆盖表。 */
- setCindyPref: (
- id: string,
- capability: string,
- model: string | null,
- ) => Promise<{ overrides: Record<string, string> }>;
- /** 派活(errand)每插件配置:首帧同步读(规则 7);config 缺项 = 跟随默认。 */
- errandPrefsSync: (id: string) => { config: Record<string, unknown> };
/** 整卡替换派活配置(null / 空对象 = 全恢复跟随默认);返回清洗后的落盘值。 */
setErrandConfig: (
id: string,
@@ -1423,6 +1366,12 @@ interface ElectronAPI {
acknowledgeRetirement: (id: string) => Promise<{ ok: true }>;
setEnabled: (id: string, enabled: boolean, expectedInstalledApproval?: string) => Promise<{ ok: true }>;
requestTaskApproval: (id: string) => Promise<{ granted: boolean }>;
+ /** 详情页「后台任务」:本插件转入后台(hidden)且未删除的任务。 */
+ listBackgroundTasks: (id: string) => Promise<{
+ items: Array<{ taskId: string; title: string; status: 'active' | 'archived'; updatedAt: number; running: boolean }>;
+ }>;
+ /** 「显示到任务列表」:清除后台隐藏,任务重新出现在任务列表。 */
+ revealBackgroundTask: (id: string, taskId: string) => Promise<{ ok: true }>;
/** 目录级禁用清单(插件页项目范围视图;sendSync 切换同帧渲染)。 */
workdirPrefsSync: (workdir: string) => { disabled: string[] };
/** 写/清一条目录级例外(disabled=false 即清除,回到跟随全局)。 */
diff --git a/apps/desktop/src/shared/__tests__/ghost.tasks.test.ts b/apps/desktop/src/shared/__tests__/ghost.tasks.test.ts
index 2658674709..7232e8a173 100644
--- a/apps/desktop/src/shared/__tests__/ghost.tasks.test.ts
+++ b/apps/desktop/src/shared/__tests__/ghost.tasks.test.ts
@@ -1,5 +1,7 @@
import { describe, expect, it } from 'vitest';
import {
+ diffGhostPermissionItems,
+ ghostDeclaresHiddenTasks,
ghostManifestToLegacyV2DigestFormat,
ghostPermissionItems,
validateGhostManifest,
@@ -48,3 +50,57 @@ it.each(['future', { future: true }, ['future'], null, false])('retains historic
expect(again.ok && again.manifest).toEqual(result.manifest);
expect(validateGhostManifest(raw).ok).toBe(false);
});
+
+describe('background tasks declaration (agent.hiddenTasks)', () => {
+ it('requires tasks and lists a distinct permission right after agent:tasks', () => {
+ const result = validateGhostManifest({ ...base, agent: { tasks: true, hiddenTasks: true } });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.manifest.agent).toEqual({ tasks: true, hiddenTasks: true });
+ expect(ghostDeclaresHiddenTasks(result.manifest)).toBe(true);
+ const keys = ghostPermissionItems(result.manifest).map(item => item.key);
+ expect(keys.indexOf('agent:hidden-tasks')).toBe(keys.indexOf('agent:tasks') + 1);
+ expect(ghostPermissionItems(result.manifest).find(item => item.key === 'agent:hidden-tasks'))
+ .toMatchObject({ kind: 'agent', labelKey: 'agentHiddenTasks', detailKey: 'agentHiddenTasksDetail' });
+ });
+ it.each([
+ { hiddenTasks: true },
+ { errand: true, hiddenTasks: true },
+ { tasks: false, hiddenTasks: true },
+ { tasks: true, hiddenTasks: 'yes' },
+ ])('rejects %j for new packages', (agent) => {
+ expect(validateGhostManifest({ ...base, agent }).ok).toBe(false);
+ });
+ it('treats hiddenTasks:false as the default visible behavior', () => {
+ const result = validateGhostManifest({ ...base, agent: { tasks: true, hiddenTasks: false } });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.manifest.agent).toEqual({ tasks: true });
+ expect(ghostPermissionItems(result.manifest).some(item => item.key === 'agent:hidden-tasks')).toBe(false);
+ });
+ it('counts adding the declaration as an added permission on update', () => {
+ const prev = validateGhostManifest({ ...base, agent: { tasks: true } });
+ const next = validateGhostManifest({ ...base, agent: { tasks: true, hiddenTasks: true } });
+ expect(prev.ok && next.ok).toBe(true);
+ if (!prev.ok || !next.ok) return;
+ expect(diffGhostPermissionItems(prev.manifest, next.manifest).added.map(item => item.key)).toEqual(['agent:hidden-tasks']);
+ });
+ it.each([
+ { tasks: true, hiddenTasks: 'yes' },
+ { hiddenTasks: true, errand: true },
+ ])('retains historical installed value %j without granting background tasks', (agent) => {
+ const result = validateInstalledGhostManifest({ ...base, agent });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(ghostDeclaresHiddenTasks(result.manifest)).toBe(false);
+ expect(ghostPermissionItems(result.manifest).some(item => item.key === 'agent:hidden-tasks')).toBe(false);
+ });
+ it('survives the installed snapshot round trip', () => {
+ const result = validateInstalledGhostManifest({ ...base, agent: { tasks: true, hiddenTasks: true } });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(ghostDeclaresHiddenTasks(result.manifest)).toBe(true);
+ const again = validateNormalizedGhostManifest(ghostManifestToAuthorFormat(result.manifest));
+ expect(again.ok && again.manifest).toEqual(result.manifest);
+ });
+});
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 477e3fe67b..65f1971664 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -195,7 +195,8 @@ export interface GhostCardNeeds {
* - errand 会话默认跑在专属对话目录、权限档默认 plan(只读);用户可在
* 设置里按插件放开到 acceptEdits/auto,**永不提供 bypassPermissions**
* (2026-07-31 Lizi 定案);
- * - errand 会话在侧边栏可见、可旁观、可随时停,不存在隐身会话;
+ * - errand 会话在侧边栏可见、可旁观、可随时停,不存在隐身会话(errand 不支持
+ * 隐藏;普通任务的后台隐藏只经 `tasks` + `hiddenTasks` 声明,见下);
* - 每插件同时最多 1 单在途,任务表在内存(重启即丢,查询按"查无此单、
* 可重新提交"处理)。
*/
@@ -203,6 +204,17 @@ export interface GhostAgentNeeds {
background?: boolean;
errand?: boolean;
tasks?: boolean;
+ /**
+ * hiddenTasks = 「可创建不显示在任务列表里的后台任务」(2026-10)。
+ *
+ * 必须与 `tasks: true` 同时声明(清单校验强制)。任务默认仍对用户可见;只有声明
+ * 本项后,插件才能经 `cindy.tasks.create({hidden: true})` / `cindy.tasks.setHidden`
+ * 把**自己创建的**普通任务放到后台:不进任务列表、搜索、未结束提示、新任务通知与
+ * 灵动岛。透明性兜底(全部主机代码强制):用户始终能在插件详情页「后台任务」查看、
+ * 打开并「显示到任务列表」;插件卸载时其后台任务自动恢复显示。不授予其它任务的
+ * 访问权,也不改变任务权限。未声明时 hidden / setHidden 返回 PERMISSION_DENIED。
+ */
+ hiddenTasks?: boolean;
/**
* schedule = 「可以请你新建自动化任务」(2026-08-04)。
*
@@ -544,8 +556,7 @@ export type GhostCindyTextAction = (typeof GHOST_CINDY_TEXT_ACTIONS)[number];
* 自己的 kv / 文件里解决。
*
* 为什么与 text.oneshot 分成两档而不是塞进同一个能力键:两者花的是不同的钱
- * (轻量任务模型链 vs embedding 模型),用户在能力偏好里钉的也是两套不同的型号,
- * 合成一档就没法只授权其中一样。信任面同 oneshot —— 只花额度,拿不到任何宿主
+ * (轻量任务模型链 vs embedding 模型),合成一档就没法只授权其中一样。信任面同 oneshot —— 只花额度,拿不到任何宿主
* 能力,不进会话。
*/
export const GHOST_CINDY_EMBED_ACTIONS = ['text'] as const;
@@ -565,9 +576,9 @@ export type GhostCindySearchAction = (typeof GHOST_CINDY_SEARCH_ACTIONS)[number]
/**
* cindy 槽能力详单(卡槽⑤配套,原名模型槽,2026-07-11 设计定案):声明"这个意识被允许
* 向主机点哪几类代办"——类目与动作之外只有**意图级**字段(oneshotModel 偏好,
- * 2026-08-05 起),**不构成任何硬依赖**(选型权在主机的解析表:调用时显式点名 >
- * 用户在详情页的钉档(意识专属覆盖)> 意识声明的偏好模型 > 用户能力偏好 >
- * 出厂默认;意识只表达意图,永不腐烂)。插件详情与代办资格审共同消费。
+ * 2026-08-05 起),**不构成任何硬依赖**(选型权在主机:快问快答 = 用户在详情页给
+ * 插件选的模型 > 意识声明的偏好模型 > 系统辅助模型链;媒体/向量 = 调用时显式点名 >
+ * 档位 > 目录默认;意识只表达意图,永不腐烂)。插件详情与代办资格审共同消费。
*/
export interface GhostCindyNeeds {
/** 图像类:generate=出图,edit=改图(改图仅限本意识名下媒体)。 */
@@ -585,7 +596,7 @@ export interface GhostCindyNeeds {
/**
* 快问快答偏好模型(目录模型 id,如 "codex/gpt-5.5";须与 text 含 "oneshot"
* 成对)。主机能从当前供应商目录解析到(且用户未停用)就用它,解析不到按
- * 未声明处理;用户在详情页的钉档永远优先于本声明。
+ * 未声明处理;用户在插件详情给插件选的模型永远优先于本声明。
* 未实现本字段的兼容宿主保留声明但不使用它;插件仍需处理旧宿主差异。
*/
oneshotModel?: string;
@@ -1925,6 +1936,14 @@ export function ghostPermissionProjectionFingerprint(manifest: GhostManifest): s
);
}
+/**
+ * 插件是否声明了后台隐藏任务能力。只认 `tasks: true` + `hiddenTasks: true` 组合:
+ * 已安装快照里不成对的历史值只作为未知数据保留,不授予(见 validateGhostManifestInput)。
+ */
+export function ghostDeclaresHiddenTasks(manifest: Pick<GhostManifest, 'agent'> | null | undefined): boolean {
+ return manifest?.agent?.tasks === true && manifest.agent.hiddenTasks === true;
+}
+
export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionItem[] {
const items: GhostPermissionItem[] = [];
for (const [category, actions] of Object.entries(manifest.cindy ?? {})) {
@@ -2002,6 +2021,17 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt
if (manifest.agent?.tasks === true) {
items.unshift({ key: 'agent:tasks', kind: 'agent', labelKey: 'agentTasks', detailKey: 'agentTasksDetail' });
}
+ // 后台隐藏任务:独立 key 单列(理由同 schedule —— 并进 agent:tasks 会让更新里
+ // 新增 hiddenTasks 时 added 为空,扩权复核拦不住)。排在 agent:tasks 之后。
+ if (ghostDeclaresHiddenTasks(manifest)) {
+ const tasksIndex = items.findIndex((item) => item.key === 'agent:tasks');
+ items.splice(tasksIndex + 1, 0, {
+ key: 'agent:hidden-tasks',
+ kind: 'agent',
+ labelKey: 'agentHiddenTasks',
+ detailKey: 'agentHiddenTasksDetail',
+ });
+ }
// 「可以请你新建自动化任务」:独立 key 单列一档。理由同 badge/errand ——
// diffGhostPermissionItems 按 key + detail 比对,若并进任何既有 key,已装插件
// 在更新里新增 schedule 时 added 为空,plugin-market 的扩权复核不会拦,用户会
@@ -4347,10 +4377,20 @@ function validateGhostManifestInput(value: unknown, preserveHistoricalTasks: boo
if (!preserveHistoricalTasks && agentRaw.tasks !== undefined && typeof agentRaw.tasks !== 'boolean') {
return { ok: false, reason: 'agent.tasks must be boolean' };
}
+ // hiddenTasks 依赖 tasks。已安装快照(preserveHistoricalTasks)不因历史值拒绝,
+ // 非 true+true 组合只作为未知数据保留,运行期经 ghostDeclaresHiddenTasks 判定不授予。
+ if (!preserveHistoricalTasks && agentRaw.hiddenTasks !== undefined) {
+ if (typeof agentRaw.hiddenTasks !== 'boolean') {
+ return { ok: false, reason: 'agent.hiddenTasks must be boolean' };
+ }
+ if (agentRaw.hiddenTasks === true && agentRaw.tasks !== true) {
+ return { ok: false, reason: 'agent.hiddenTasks: true 需要同时声明 agent.tasks: true' };
+ }
+ }
if (agentRaw.schedule !== undefined && typeof agentRaw.schedule !== 'boolean') {
return { ok: false, reason: 'agent.schedule 必须是布尔值' };
}
- if (agentRaw.background !== true && agentRaw.errand !== true && agentRaw.schedule !== true && agentRaw.tasks !== true && Object.keys(unknownDeclarationFields(agentRaw, preserveHistoricalTasks ? ['background', 'errand', 'schedule'] : ['background', 'errand', 'schedule', 'tasks'])).length === 0) {
+ if (agentRaw.background !== true && agentRaw.errand !== true && agentRaw.schedule !== true && agentRaw.tasks !== true && Object.keys(unknownDeclarationFields(agentRaw, preserveHistoricalTasks ? ['background', 'errand', 'schedule'] : ['background', 'errand', 'schedule', 'tasks', 'hiddenTasks'])).length === 0) {
return {
ok: false,
reason:
@@ -4358,10 +4398,11 @@ function validateGhostManifestInput(value: unknown, preserveHistoricalTasks: boo
};
}
agent = {
- ...unknownDeclarationFields(agentRaw, preserveHistoricalTasks ? ['background', 'errand', 'schedule'] : ['background', 'errand', 'schedule', 'tasks']),
+ ...unknownDeclarationFields(agentRaw, preserveHistoricalTasks ? ['background', 'errand', 'schedule'] : ['background', 'errand', 'schedule', 'tasks', 'hiddenTasks']),
...(agentRaw.background === true ? { background: true } : {}),
...(agentRaw.errand === true ? { errand: true } : {}),
...(agentRaw.tasks === true ? { tasks: true } : {}),
+ ...(agentRaw.tasks === true && agentRaw.hiddenTasks === true ? { hiddenTasks: true } : {}),
...(agentRaw.schedule === true ? { schedule: true } : {}),
};
}
@@ -6807,7 +6848,7 @@ export type GhostAgentModelsResult =
export const GHOST_MEDIA_MODEL_TYPES = ['image', 'video'] as const;
export type GhostMediaModelType = (typeof GHOST_MEDIA_MODEL_TYPES)[number];
-/** Host「Cindy 能力」区域现有的四项媒体模型配置键。 */
+/** 四项 Cindy 媒体能力键(cindy-preference 只读查询用;插件没有逐项选模,返回系统默认选型)。 */
export const GHOST_MEDIA_CAPABILITIES = [
'image.generate',
'image.edit',
diff --git a/apps/desktop/src/shared/pluginTasks.ts b/apps/desktop/src/shared/pluginTasks.ts
index f3e5e3db7f..1c35f7bdfc 100644
--- a/apps/desktop/src/shared/pluginTasks.ts
+++ b/apps/desktop/src/shared/pluginTasks.ts
@@ -25,6 +25,23 @@ export interface PluginTaskView {
permissionMode?: string;
/** Independent Plan Mode; the stored permission remains available after it ends. */
planModeEnabled?: boolean;
+ /**
+ * Background task: omitted from the task list, search, notifications and Agent Island.
+ * Only plugins declaring `agent.hiddenTasks` can set it; the user can still open or
+ * reveal it from the plugin detail page. The task service always returns a boolean;
+ * the field is optional only for Host-internal readers that predate it.
+ */
+ hidden?: boolean;
+}
+/** Plugin detail page「后台任务」row (Desktop-only IPC; never sent to the plugin sandbox). */
+export interface PluginBackgroundTask {
+ taskId: string;
+ title: string;
+ status: 'active' | 'archived';
+ /** Last activity, unix ms. */
+ updatedAt: number;
+ /** A turn is running in this Desktop process. */
+ running: boolean;
}
export interface PluginTaskRun {
runId: string;
@@ -68,7 +85,10 @@ export type PluginTaskRequest = (
title: string;
route?: PluginTaskRoute;
isolatedWorkspace?: boolean;
+ /** Requires `agent.hiddenTasks`; creates the task as a background task. */
+ hidden?: boolean;
}
+ | { type: 'tasks-request'; kind: 'setHidden'; taskId: string; hidden: boolean }
| { type: 'tasks-request'; kind: 'list'; after?: string; limit?: number }
| { type: 'tasks-request'; kind: 'get'; taskId: string }
| { type: 'tasks-request'; kind: 'startTeam' | 'getTeam'; taskId: string }
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index 5569af6bd1..667e7fa455 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -140,6 +140,10 @@ Library 请求同时绑定迁移代次和安装批准,根解析、排队及开
只在首次任务能力调用通过既有宿主权限界面确认,原插件的启用态、其它能力、凭证和
设置保持不变。拒绝、窗口不可用、账号或安装版本变化均不授予任务权限;同能力更新
保留既有明确批准,移除该能力后不保留。清单或旧未知字段本身不能补写批准。
+- `agent.hiddenTasks`(后台任务)只在与 `agent.tasks: true` 同时声明时有效:新包缺 tasks 或非布尔
+ 直接拒装;已安装快照里不成对的历史值原样保留但不授予。它单列为 `agent:hidden-tasks` 权限,
+ 更新新增即「权限变多」;运行期由 taskSlot 与任务服务按身份卡双重守门。透明性兜底与多端口径见
+ [`plugin-task-api-implementation.md`](plugin-task-api-implementation.md)「后台任务」。
- **Agent 在途调用不需要重复登记具体操作。** 插件工具是否执行由当前
`ghost_call` 的 Cindy Agent 授权决定;普通网络和当前工作目录操作使用主机
下发且仍在途的 `callId`。随包代码与 CLI 继续使用已有 Node 工作进程,顶层
@@ -446,6 +450,8 @@ Library 请求同时绑定迁移代次和安装批准,根解析、排队及开
- 模型调用一律走 Cindy 统一通道,不允许插件自建绕过通道的推理请求。
- 插件是沙箱小程序,不等于 AI 代办。模型与任务相关能力必须分别描述:
- 快问快答(`cindy.text.oneshot`)不创建任务、没有 Agent 工具;沿用其统一轻量模型通道。
+ 模型依次取插件详情的「模型」字段(与插件新建任务共用、钉死不回落)、身份卡
+ `oneshotModel` 声明、系统辅助模型链;每单现读,辅助模型改动后跟随默认的插件自动跟随。
- `agent.run` 承接已有用户任务的继续/新建/分叉,保留原任务的交互与权限语义;
真实点击票/后台关联授权不因共用模型校验而扩大。
- `cindy.tasks` 创建并管理插件自己的普通任务,有独立的 tasks 声明、批准与持久回执;
@@ -454,9 +460,13 @@ Library 请求同时绑定迁移代次和安装批准,根解析、排队及开
- `agent.errand` 是旧的派活取件适配器,保留专属任务映射与结果回传,不作为其它能力的产品抽象。
- 用户界面、Agent 工具、伙伴和插件的新建任务共用普通 Session 创建入口。伙伴的完成回报、
时间线与信号留在伙伴层;插件按需查询结果,不默认唤醒伙伴或另一个 Agent。
-- 插件详情「任务设置」是插件新建任务的共用偏好,普通任务、工作区新建与旧 errand 使用
- 同一配置。显式完整模型组合优先;缺省从宿主验证的发起任务继承,面板无发起任务则使用
- 当前新任务的完整选择,不优先翻找 Claude Code 的历史草稿。模型选择不授予权限或目录。
+- 插件详情「模型与任务」是插件唯一的模型偏好(快问快答与新建任务共用)加任务权限与
+ 工作目录,普通任务、工作区新建与旧 errand 使用同一配置;只声明快问快答的插件只显示
+ 模型行。图像/视频/向量没有逐插件选模,始终走系统默认与调用方档位。旧版逐能力选模
+ (`ghost-cindy-prefs.json` 的 `overrides`)在主进程首次读取任务配置时一次性迁移:
+ 快问快答的 `cat:` 目录钉仅在插件尚未选模型时写入 agent/供应商/模型,其余覆盖丢弃,
+ 并删除该键(保留 `inflightLimits` 等其它键)。新建任务时显式完整模型组合优先;
+ 缺省从宿主验证的发起任务继承,面板无发起任务则使用当前新任务的完整选择,不优先翻找 Claude Code 的历史草稿。模型选择不授予权限或目录。
保存、新建和插件派发前复用普通独立任务的模型/供应商/Agent 准入,不另建目录或选择器。
连接状态不等于额度、网络及远端参数一定可用;执行失败如实返回,不静默换型号或账号。
- 插件新建普通任务的权限仅来自用户的插件设置或既有宿主确认流程,默认普通任务的 `ask`,允许
diff --git a/docs/dev-rules/plugin-task-api-implementation.md b/docs/dev-rules/plugin-task-api-implementation.md
index e5b741778f..138adcdff6 100644
--- a/docs/dev-rules/plugin-task-api-implementation.md
+++ b/docs/dev-rules/plugin-task-api-implementation.md
@@ -90,7 +90,8 @@ if (capabilities.operations.includes('models')) {
| `agent.errand` | 共用模型解析;无显式覆盖时优先保留已有专属任务的当前模型。配置冲突时只在新任务创建成功后替换映射,旧历史保留 | 旧权限边界、sessionKey、jobId 与结果取回协议保持兼容 |
| `workspace.ensureSession` | 已有工作区入口照常复用;新建才使用插件设置/发起任务/当前新任务完整组合 | 目录仍经亲选或原有确认流程;只建入口、不运行 Agent |
| `agent.run` | 操作已有用户任务;本机任务校验其当前组合,远程任务交由执行宿主校验,继续/新建/分叉仍按原接口继承用户任务 | 保留原有点击票、任务关联和源权限限制;不套用插件自有任务权限或取件协议 |
-| 快问快答/媒体生成 | 各自已有通道,不受任务默认配置支配 | 不变成普通任务或代办 |
+| 快问快答 | 与新建任务共用插件详情的唯一「模型」字段:用户显式选模即钉死该组合;未选时依次取身份卡 `oneshotModel` 声明、系统辅助模型链(每单现读) | 不创建任务、没有工具,走轻量文本通道 |
+| 媒体生成/向量 | 没有逐插件选模,走调用方档位/点名与系统默认 | 不变成普通任务或代办 |
`tasks.capabilities().sourceCallContext` 声明支持 create 的可选 `callId`。Agent 在处理
在途插件工具时可转传该调用 ID;宿主只接受同插件、本机、仍在途的归属,不接受插件
@@ -135,9 +136,10 @@ Claude Code 适配层 `toSdkModelString` 会按目录窗口自动追加 `[1m]`
## 已接入
-- `capabilities/models/create/list/get/setModel/send/getRun/listRuns/readMessages/cancel`。
+- `capabilities/models/create/list/get/setModel/send/getRun/listRuns/readMessages/cancel/setHidden`。
+- create 可传 `hidden:true`、`setHidden({taskId, hidden})` 切换,`get`/`list` 快照恒返回 `hidden` 布尔值;仅身份卡声明 `agent.hiddenTasks: true`(必须同时 `agent.tasks: true`)时可用,见下文「后台任务」。
- create 可传 isolatedWorkspace:true,由宿主分配独立空作答目录;返回本任务 workingDir 与 permissionMode,插件不能覆盖权限。
-- 创建用户可见的普通本地 Session;工作目录及权限来自用户配置,不接受插件传入绕过权限、任意目录或另一插件身份。普通任务创建前复用 Worker 的目录身份判据:配置路径必须仍为原规范路径,改链、缺失或非目录拒绝;异步解析后复核账号、tasks 批准及配置。缺省/isolatedWorkspace 仍由宿主分配目录,旧 errand 路径不变。旧别名配置没有原目标证据,不自动授权当前目标;这不解决校验后的目录置换窗口。
+- 默认创建用户可见的普通本地 Session(声明 hiddenTasks 后可在同一次 INSERT 中创建后台任务);工作目录及权限来自用户配置,不接受插件传入绕过权限、任意目录或另一插件身份。普通任务创建前复用 Worker 的目录身份判据:配置路径必须仍为原规范路径,改链、缺失或非目录拒绝;异步解析后复核账号、tasks 批准及配置。缺省/isolatedWorkspace 仍由宿主分配目录,旧 errand 路径不变。旧别名配置没有原目标证据,不自动授权当前目标;这不解决校验后的目录置换窗口。
- 发送走普通输入协调器,使用持久 requestKey 去重和稳定输入 ID;重复请求不会再次启动模型。
- 指定 provider、model、effort、Fast 必须通过当前目录核验;派发前再次核验,不静默 fallback。
- 创建回执写入后、创建 Session 前,按原始请求重新解析路由并与已受理路由比较;默认模型配置变化则拒绝,不静默使用旧值。目录解析及创建器的最终 continuation 同时复核 agentKind/model/provider/effort/Fast、目录和权限。
@@ -152,6 +154,42 @@ Claude Code 适配层 `toSdkModelString` 会按目录窗口自动追加 `[1m]`
- 请求跨账号切换后不能继续操作新账号数据库。禁用插件后不能继续发送或停止。
- 用户通过插件页或市场卸载时,在删除插件包前持久撤销其旧任务归属;保留任务、消息、作答文件、成绩和回执。正常更新保留归属;卸载重装后旧任务和旧 requestKey 不再可用,新请求键可创建新任务。撤销写入失败则不删除包;删除包失败时已撤销的归属不回滚。此处不改变内置插件 orphan/audience 自动回收路径。
+## 后台任务(agent.hiddenTasks)
+
+任务默认可见。声明 `agent.hiddenTasks: true` 的插件可以把**自己经 create 回执拥有的**本地普通任务
+放到后台:`sessions.hidden_at`(可空毫秒时间戳,migration 0126)非空即隐藏,存量行全部为 NULL。
+
+- **声明与权限**:v3 直接能力字段,`GhostAgentNeeds.hiddenTasks`;新包校验要求布尔且依赖 `tasks: true`,
+ 已安装快照里不成对的历史值只作为未知数据保留、不授予(`ghostDeclaresHiddenTasks` 统一判定)。权限项
+ `agent:hidden-tasks` 单列在 `agent:tasks` 之后,进入详情页权限区与安装/更新确认;更新新增该声明按
+ 「权限变多」触发确认,旧 receipt 缺字段视为未声明,不报错、不迁移。管子(taskSlot)先按身份卡拒绝,
+ 服务在回执队列内再经 `assertHiddenTasksAllowed` 复核插件批准与声明;未声明返回 `PERMISSION_DENIED`,
+ `hidden:false` 是默认值,所有 tasks 插件可用。
+- **幂等**:只有 `hidden:true` 进入 create 的请求摘要,存量可见回执的重放摘要不变。
+- **写入口**:创建时由 `openSession({hiddenAt})` 在同一次 INSERT 落库,不发「新建」推送;切换与用户
+ 显示统一走 `localDb/ipc/sessionHidden.setSessionHidden`:隐藏广播 `sessions:patched {hiddenAt}`
+ (renderer 从各桶移除并重拉、灵动岛收起),显示清列并刷新 updatedAt、广播 patched 后再发
+ `sessions:created` 让侧栏与控制端整体重拉。归属复用 `ownTask`(创建回执 + 账号/批准复核),远程任务
+ 与 Worker 没有创建回执,`readSession` 不认,不支持 setHidden。
+- **可见性口径**:`local-db:sessions:list`、会话搜索(conversationSearch)、未结束提示两条腿
+ (sessionActiveTurn)、hook-control 最近任务排除隐藏任务;用量统计等全量口径不排除。灵动岛/菜单栏
+ 运行态与系统通知经 `hiddenSessionRegistry` 同步判定跳过(首次 list 时按账号库预热,加载前按可见处理);
+ renderer 通知兜底按单任务读取的 `hiddenAt` 判定。`subscriptionGateway.isGhostEligibleSessionRow`
+ 不因隐藏改变,插件仍可订阅自己的任务。
+- **透明性兜底**:插件详情页「后台任务」区块(设置之后、Tools 之前)列出本插件回执拥有、仍在后台且未删除
+ 的任务(标题、最后活动、运行状态),可「打开任务」(`/cc-agent/:id`,与审查卡片同一路由)或「显示到
+ 任务列表」。停用插件同样可查;更新移除 hiddenTasks(甚至 tasks)声明后仍有遗留后台任务时区块照常出现,
+ 未声明且没有后台任务的插件不显示该区块。卸载时 `withUninstall`
+ 先把该插件的后台任务全部恢复显示,再撤销归属;恢复失败则不卸载。内置插件 orphan/audience 自动回收路径
+ 未改,不经此恢复。
+- **多端**:SSH 远程工作区——插件任务只建在本机,不涉及。设备互联/手机——列表走同一个
+ `local-db:sessions:list`;远端边界(`remoteBotSessionBoundary`)把隐藏任务标为 `background`,只从
+ `sessions:list` / `maker:list-active` 结果中排除,`sessions:get` 等单任务读取与操作照常(插件页深链
+ 可打开)。详情页的两个新 IPC `ghosts:background-tasks:list` / `ghosts:background-tasks:reveal` **只登记
+ Desktop**:它们服务本机插件详情页(打开任务、显示到任务列表都是本机 UI 动作),手机端没有插件详情页
+ 入口,按 allowlist 默认拒绝不进白名单;handler 同时拒绝 device-link 调用并校验可信窗口。手机列表在
+ 任务转入后台的瞬间不会主动移除已加载的行,下一次列表重拉后消失(手机端未改,未单独验证)。
+
## 与伙伴的共用和隔离
`sessionExecutionOwnership.ts` 提供执行身份比较、锁内二次核对、按归属撤回排队输入。伙伴委派与插件任务均使用这套函数。
@@ -160,7 +198,7 @@ Claude Code 适配层 `toSdkModelString` 会按目录窗口自动追加 `[1m]`
## 当前限制与后续工作
-- 仅本插件创建的本地普通任务;不支持选择既有任务、远端任务或 Bot;自有普通任务可通过 startTeam 成为 Orca Lead。
+- 仅本插件创建的本地普通任务;不支持选择既有任务、远端任务或 Bot(setHidden 同样只作用于自有本地任务);自有普通任务可通过 startTeam 成为 Orca Lead。
- 已支持通过 `setModel` 修改任务模型;尚未开放其它配置修改/归档任务、队列暂停、事件订阅、逐输入费用与用量。usage 明确返回 unavailable。
- 回执已经持久化,但完整的重启后终态补账、无输入别名的自动续跑归属尚未闭环。缺少原生证据时返回 reconciling,不重放请求、不报告成功;目前不应作为无人值守正式评测的完成依据。
- 一旦 Session INSERT 已开始、创建进程中断或回执撤回失败,结果仍可能不明:保留回执,重放只读取已存在任务,不补建,可能返回 TASK_NOT_FOUND。旧孤立回执没有本次失败证据,不自动修复;已删除任务不复活、已撤销任务及旧 key 不接管。此限制与创建前明确失败后的显式重试不同。
diff --git a/docs/plugin-setup-runtime.md b/docs/plugin-setup-runtime.md
index 13307d6e2b..43bc5f6203 100644
--- a/docs/plugin-setup-runtime.md
+++ b/docs/plugin-setup-runtime.md
@@ -741,4 +741,7 @@ revision 去旧和四语言文案。
- 每次 update 抢焦点,或 ChatInput 恢复时后台窗口抢焦点;
- terminal 状态立即 dismissed,用户看不到完成或取消反馈;
- 插件卸载、停用、manifest/tool 漂移时没有 `unavailable` 收口;
-- 隐藏会话的 Agent Island 仍显示 running,无法提示等待插件配置。
+- (已处理)隐藏会话的 Agent Island 仍显示 running,无法提示等待插件配置:插件后台任务
+ (`sessions.hidden_at` 非空,需声明 `agent.hiddenTasks`)不进入 Agent Island / 菜单栏运行态,
+ 转入后台时收起已有条目,也不发系统通知;等待插件配置的设置卡留在该任务内,用户从插件详情页
+ 「后台任务」打开任务即可看到并处理,或「显示到任务列表」后按普通任务提醒。
diff --git a/packages/plugin-protocol/src/__tests__/manifest.test.ts b/packages/plugin-protocol/src/__tests__/manifest.test.ts
index 66a9665da0..1d0884de1a 100644
--- a/packages/plugin-protocol/src/__tests__/manifest.test.ts
+++ b/packages/plugin-protocol/src/__tests__/manifest.test.ts
@@ -1865,3 +1865,15 @@ describe('cindy 详单:media/text/embed/search 类目与 oneshotModel 校验', (
}
});
});
+
+describe('agent.hiddenTasks declaration', () => {
+ const v3 = { schemaVersion: 3, minCindyVersion: '0.1.0', id: 'bg-tasks', name: 'Background', version: '1.0.0', entry: 'main.js' };
+ it('accepts it only together with agent.tasks', () => {
+ const ok = validateGhostManifest({ ...v3, agent: { tasks: true, hiddenTasks: true } });
+ expect(ok.ok && ok.manifest.agent).toEqual({ tasks: true, hiddenTasks: true });
+ expect(validateGhostManifest({ ...v3, agent: { hiddenTasks: true } }).ok).toBe(false);
+ expect(validateGhostManifest({ ...v3, agent: { tasks: true, hiddenTasks: 'yes' } }).ok).toBe(false);
+ const visible = validateGhostManifest({ ...v3, agent: { tasks: true, hiddenTasks: false } });
+ expect(visible.ok && visible.manifest.agent).toEqual({ tasks: true });
+ });
+});
diff --git a/packages/plugin-protocol/src/manifest.ts b/packages/plugin-protocol/src/manifest.ts
index c0ab89a13b..953264669e 100644
--- a/packages/plugin-protocol/src/manifest.ts
+++ b/packages/plugin-protocol/src/manifest.ts
@@ -207,6 +207,8 @@ export interface GhostAgentNeeds {
background?: boolean;
errand?: boolean;
tasks?: boolean;
+ /** 后台隐藏任务;必须与 `tasks: true` 同时声明。 */
+ hiddenTasks?: boolean;
schedule?: boolean;
}
@@ -2939,10 +2941,16 @@ export function validateGhostManifest(value: unknown): ManifestValidation {
if (agentRaw.tasks !== undefined && typeof agentRaw.tasks !== 'boolean') {
return { ok: false, reason: 'agent.tasks must be boolean' };
}
+ if (agentRaw.hiddenTasks !== undefined && typeof agentRaw.hiddenTasks !== 'boolean') {
+ return { ok: false, reason: 'agent.hiddenTasks must be boolean' };
+ }
+ if (agentRaw.hiddenTasks === true && agentRaw.tasks !== true) {
+ return { ok: false, reason: 'agent.hiddenTasks: true 需要同时声明 agent.tasks: true' };
+ }
if (agentRaw.schedule !== undefined && typeof agentRaw.schedule !== 'boolean') {
return { ok: false, reason: 'agent.schedule 必须是布尔值' };
}
- if (agentRaw.background !== true && agentRaw.errand !== true && agentRaw.schedule !== true && agentRaw.tasks !== true && Object.keys(unknownDeclarationFields(agentRaw, ['background', 'errand', 'schedule', 'tasks'])).length === 0) {
+ if (agentRaw.background !== true && agentRaw.errand !== true && agentRaw.schedule !== true && agentRaw.tasks !== true && Object.keys(unknownDeclarationFields(agentRaw, ['background', 'errand', 'schedule', 'tasks', 'hiddenTasks'])).length === 0) {
return {
ok: false,
reason:
@@ -2950,10 +2958,11 @@ export function validateGhostManifest(value: unknown): ManifestValidation {
};
}
agent = {
- ...unknownDeclarationFields(agentRaw, ['background', 'errand', 'schedule', 'tasks']),
+ ...unknownDeclarationFields(agentRaw, ['background', 'errand', 'schedule', 'tasks', 'hiddenTasks']),
...(agentRaw.background === true ? { background: true } : {}),
...(agentRaw.errand === true ? { errand: true } : {}),
...(agentRaw.tasks === true ? { tasks: true } : {}),
+ ...(agentRaw.tasks === true && agentRaw.hiddenTasks === true ? { hiddenTasks: true } : {}),
...(agentRaw.schedule === true ? { schedule: true } : {}),
};
}