Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): add durable multi-harness Subagent workspace (#2263)
Chris Zhang38a25b32fa65
diff --git a/apps/desktop/drizzle/0089_rich_power_pack.sql b/apps/desktop/drizzle/0089_rich_power_pack.sqlnew file mode 100644index 0000000000..13a1d5081e--- /dev/null+++ b/apps/desktop/drizzle/0089_rich_power_pack.sql@@ -0,0 +1,42 @@+CREATE TABLE IF NOT EXISTS `subagent_run_aliases` (+ `session_id` text NOT NULL,+ `provider` text NOT NULL,+ `alias` text NOT NULL,+ `run_id` text NOT NULL,+ `created_at` integer NOT NULL,+ PRIMARY KEY(`run_id`, `alias`),+ FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade,+ FOREIGN KEY (`run_id`) REFERENCES `subagent_runs`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+CREATE INDEX IF NOT EXISTS `subagent_run_aliases_lookup_idx` ON `subagent_run_aliases` (`session_id`,`provider`,`alias`,`created_at`);--> statement-breakpoint+CREATE TABLE IF NOT EXISTS `subagent_runs` (+ `id` text PRIMARY KEY NOT NULL,+ `session_id` text NOT NULL,+ `provider` text NOT NULL,+ `logical_agent_id` text NOT NULL,+ `parent_tool_use_id` text,+ `aliases` text DEFAULT '[]' NOT NULL,+ `provider_run_ids` text DEFAULT '[]' NOT NULL,+ `status` text DEFAULT 'running' NOT NULL,+ `title` text,+ `description` text,+ `summary` text,+ `model` text,+ `reasoning_effort` text,+ `total_tokens` integer,+ `tool_uses` integer,+ `duration_ms` integer,+ `capabilities` text DEFAULT '{}' NOT NULL,+ `activity` text DEFAULT '[]' NOT NULL,+ `started_at` integer NOT NULL,+ `updated_at` integer NOT NULL,+ `ended_at` integer,+ `rewind_at` integer,+ `deleted_at` integer,+ FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+CREATE INDEX IF NOT EXISTS `subagent_runs_logical_idx` ON `subagent_runs` (`session_id`,`provider`,`logical_agent_id`);--> statement-breakpoint+CREATE INDEX IF NOT EXISTS `subagent_runs_session_idx` ON `subagent_runs` (`session_id`,`rewind_at`,`deleted_at`,`started_at`);--> statement-breakpoint+CREATE INDEX IF NOT EXISTS `subagent_runs_parent_tool_use_idx` ON `subagent_runs` (`session_id`,`parent_tool_use_id`);diff --git a/apps/desktop/drizzle/meta/0089_snapshot.json b/apps/desktop/drizzle/meta/0089_snapshot.jsonnew file mode 100644index 0000000000..13881729ca--- /dev/null+++ b/apps/desktop/drizzle/meta/0089_snapshot.json@@ -0,0 +1,4246 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "36f4dec3-66f7-4a85-b5ec-eb2212ca69c6",+ "prevId": "7e28c084-8cbc-4d74-a47f-f84ddefabae0",+ "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": {}+ },+ "custom_mcp_servers": {+ "name": "custom_mcp_servers",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "transport": {+ "name": "transport",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "headers": {+ "name": "headers",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "sort_order": {+ "name": "sort_order",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_custom_mcp_servers_sort_order": {+ "name": "idx_custom_mcp_servers_sort_order",+ "columns": [+ "sort_order"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "custom_providers": {+ "name": "custom_providers",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "runtimes": {+ "name": "runtimes",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "auth": {+ "name": "auth",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "sort_order": {+ "name": "sort_order",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_custom_providers_sort_order": {+ "name": "idx_custom_providers_sort_order",+ "columns": [+ "sort_order"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "daily_model_usage": {+ "name": "daily_model_usage",+ "columns": {+ "day": {+ "name": "day",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cost_usd": {+ "name": "cost_usd",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_amount": {+ "name": "cost_amount",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_currency": {+ "name": "cost_currency",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'USD'"+ },+ "cost_is_approximate": {+ "name": "cost_is_approximate",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "input_tokens": {+ "name": "input_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "output_tokens": {+ "name": "output_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cache_read_tokens": {+ "name": "cache_read_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cache_create_tokens": {+ "name": "cache_create_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "daily_model_usage_day_agent_kind_model_cost_currency_pk": {+ "columns": [+ "day",+ "agent_kind",+ "model",+ "cost_currency"+ ],+ "name": "daily_model_usage_day_agent_kind_model_cost_currency_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "daily_spend": {+ "name": "daily_spend",+ "columns": {+ "day": {+ "name": "day",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cost_usd": {+ "name": "cost_usd",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_amount": {+ "name": "cost_amount",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "cost_currency": {+ "name": "cost_currency",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'USD'"+ },+ "cost_is_approximate": {+ "name": "cost_is_approximate",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "daily_spend_day_cost_currency_pk": {+ "columns": [+ "day",+ "cost_currency"+ ],+ "name": "daily_spend_day_cost_currency_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "device_link_ownership": {+ "name": "device_link_ownership",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "owner_id": {+ "name": "owner_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "owner_pid": {+ "name": "owner_pid",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "owner_label": {+ "name": "owner_label",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "heartbeat_at": {+ "name": "heartbeat_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "embedding_jobs": {+ "name": "embedding_jobs",+ "columns": {+ "rowid": {+ "name": "rowid",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "source_id": {+ "name": "source_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "chunk_index": {+ "name": "chunk_index",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "model_id": {+ "name": "model_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "vec_table": {+ "name": "vec_table",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scheduled_at": {+ "name": "scheduled_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "locked_at": {+ "name": "locked_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_embedding_jobs_natural": {+ "name": "uniq_embedding_jobs_natural",+ "columns": [+ "source",+ "source_id",+ "chunk_index",+ "model_id"+ ],+ "isUnique": true+ },+ "idx_embedding_jobs_status_scheduled": {+ "name": "idx_embedding_jobs_status_scheduled",+ "columns": [+ "status",+ "scheduled_at"+ ],+ "isUnique": false+ },+ "idx_embedding_jobs_source_id": {+ "name": "idx_embedding_jobs_source_id",+ "columns": [+ "source",+ "source_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "embedding_meta": {+ "name": "embedding_meta",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "ghost_cards": {+ "name": "ghost_cards",+ "columns": {+ "call_id": {+ "name": "call_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "ghost_id": {+ "name": "ghost_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "html": {+ "name": "html",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "height": {+ "name": "height",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "v": {+ "name": "v",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 1+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "ghost_cards_updated_at_idx": {+ "name": "ghost_cards_updated_at_idx",+ "columns": [+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "hook_group_context_cursors": {+ "name": "hook_group_context_cursors",+ "columns": {+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cursor_key": {+ "name": "cursor_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cursor_id": {+ "name": "cursor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "hook_group_context_cursors_updated_at_idx": {+ "name": "hook_group_context_cursors_updated_at_idx",+ "columns": [+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "hook_group_context_cursors_provider_cursor_key_pk": {+ "columns": [+ "provider",+ "cursor_key"+ ],+ "name": "hook_group_context_cursors_provider_cursor_key_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "hook_group_message_stats": {+ "name": "hook_group_message_stats",+ "columns": {+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "row_count": {+ "name": "row_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "text_bytes": {+ "name": "text_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "hook_group_messages": {+ "name": "hook_group_messages",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "chat_id": {+ "name": "chat_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "thread_id": {+ "name": "thread_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "message_id": {+ "name": "message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "chat_name": {+ "name": "chat_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "author": {+ "name": "author",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "is_bot": {+ "name": "is_bot",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "text": {+ "name": "text",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "file_names": {+ "name": "file_names",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "sent_at": {+ "name": "sent_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "hook_group_messages_msg_idx": {+ "name": "hook_group_messages_msg_idx",+ "columns": [+ "provider",+ "chat_id",+ "thread_id",+ "message_id"+ ],+ "isUnique": true+ },+ "hook_group_messages_window_idx": {+ "name": "hook_group_messages_window_idx",+ "columns": [+ "provider",+ "chat_id",+ "thread_id",+ "id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "im_bindings": {+ "name": "im_bindings",+ "columns": {+ "channel": {+ "name": "channel",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "bot_context_id": {+ "name": "bot_context_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "scope_key": {+ "name": "scope_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "target_session_id": {+ "name": "target_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "attached_at": {+ "name": "attached_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "attached_via_card_message_id": {+ "name": "attached_via_card_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_im_bindings_target": {+ "name": "idx_im_bindings_target",+ "columns": [+ "target_session_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "im_bindings_target_session_id_sessions_id_fk": {+ "name": "im_bindings_target_session_id_sessions_id_fk",+ "tableFrom": "im_bindings",+ "tableTo": "sessions",+ "columnsFrom": [+ "target_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "im_bindings_channel_bot_context_id_user_id_scope_key_pk": {+ "columns": [+ "channel",+ "bot_context_id",+ "user_id",+ "scope_key"+ ],+ "name": "im_bindings_channel_bot_context_id_user_id_scope_key_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "media_blobs": {+ "name": "media_blobs",+ "columns": {+ "hash": {+ "name": "hash",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "ext": {+ "name": "ext",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "bytes": {+ "name": "bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "is_cache": {+ "name": "is_cache",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_access_at": {+ "name": "last_access_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "media_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+ }+ },+ "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": {}+ },+ "migration_history": {+ "name": "migration_history",+ "columns": {+ "seq": {+ "name": "seq",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "file_name": {+ "name": "file_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "content_hash": {+ "name": "content_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "applied_at": {+ "name": "applied_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "migration_meta": {+ "name": "migration_meta",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "orca_teams": {+ "name": "orca_teams",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "lead_session_id": {+ "name": "lead_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "completed_at": {+ "name": "completed_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_active_team_per_lead": {+ "name": "uniq_active_team_per_lead",+ "columns": [+ "lead_session_id"+ ],+ "isUnique": true,+ "where": "\"orca_teams\".\"status\" = 'active'"+ },+ "idx_orca_teams_status": {+ "name": "idx_orca_teams_status",+ "columns": [+ "status"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "orca_teams_lead_session_id_sessions_id_fk": {+ "name": "orca_teams_lead_session_id_sessions_id_fk",+ "tableFrom": "orca_teams",+ "tableTo": "sessions",+ "columnsFrom": [+ "lead_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "orca_worker_creation_reservations": {+ "name": "orca_worker_creation_reservations",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "label": {+ "name": "label",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_orca_worker_creation_reservations_team_label": {+ "name": "uniq_orca_worker_creation_reservations_team_label",+ "columns": [+ "team_id",+ "lower(\"label\")"+ ],+ "isUnique": true+ },+ "idx_orca_worker_creation_reservations_expires_at": {+ "name": "idx_orca_worker_creation_reservations_expires_at",+ "columns": [+ "expires_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "orca_worker_creation_reservations_team_id_orca_teams_id_fk": {+ "name": "orca_worker_creation_reservations_team_id_orca_teams_id_fk",+ "tableFrom": "orca_worker_creation_reservations",+ "tableTo": "orca_teams",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "orca_workers": {+ "name": "orca_workers",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'idle'"+ },+ "label": {+ "name": "label",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "worktree_branch": {+ "name": "worktree_branch",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'developer'"+ },+ "focused": {+ "name": "focused",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "idle_since": {+ "name": "idle_since",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_orca_workers_session_id": {+ "name": "uniq_orca_workers_session_id",+ "columns": [+ "session_id"+ ],+ "isUnique": true+ },+ "uniq_orca_workers_team_label": {+ "name": "uniq_orca_workers_team_label",+ "columns": [+ "team_id",+ "lower(\"label\")"+ ],+ "isUnique": true+ },+ "uniq_orca_workers_focused_per_team": {+ "name": "uniq_orca_workers_focused_per_team",+ "columns": [+ "team_id"+ ],+ "isUnique": true,+ "where": "\"orca_workers\".\"focused\" = true"+ },+ "idx_orca_workers_team_id": {+ "name": "idx_orca_workers_team_id",+ "columns": [+ "team_id"+ ],+ "isUnique": false+ },+ "idx_orca_workers_status": {+ "name": "idx_orca_workers_status",+ "columns": [+ "status"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "orca_workers_team_id_orca_teams_id_fk": {+ "name": "orca_workers_team_id_orca_teams_id_fk",+ "tableFrom": "orca_workers",+ "tableTo": "orca_teams",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "orca_workers_session_id_sessions_id_fk": {+ "name": "orca_workers_session_id_sessions_id_fk",+ "tableFrom": "orca_workers",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_aliases": {+ "name": "project_aliases",+ "columns": {+ "project_key": {+ "name": "project_key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "alias": {+ "name": "alias",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_project_aliases_updated_at": {+ "name": "idx_project_aliases_updated_at",+ "columns": [+ "updated_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "project_automation_consents": {+ "name": "project_automation_consents",+ "columns": {+ "working_dir": {+ "name": "working_dir",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "consented_at": {+ "name": "consented_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "config_hash": {+ "name": "config_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "recent_workdirs": {+ "name": "recent_workdirs",+ "columns": {+ "path": {+ "name": "path",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_recent_workdirs_last_used_at": {+ "name": "idx_recent_workdirs_last_used_at",+ "columns": [+ "last_used_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "right_sidebar_tabs": {+ "name": "right_sidebar_tabs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "is_active": {+ "name": "is_active",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "right_sidebar_tabs_session_idx": {+ "name": "right_sidebar_tabs_session_idx",+ "columns": [+ "session_id",+ "position"+ ],+ "isUnique": false+ },+ "right_sidebar_tabs_subagents_singleton_idx": {+ "name": "right_sidebar_tabs_subagents_singleton_idx",+ "columns": [+ "session_id"+ ],+ "isUnique": true,+ "where": "\"right_sidebar_tabs\".\"kind\" = 'subagents'"+ }+ },+ "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+ }+ },+ "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": {}+ },+ "schedules": {+ "name": "schedules",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "prompt": {+ "name": "prompt",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "job_type": {+ "name": "job_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'prompt'"+ },+ "job_config": {+ "name": "job_config",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "execution_mode": {+ "name": "execution_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'agent'"+ },+ "script_config": {+ "name": "script_config",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'user'"+ },+ "project_config_id": {+ "name": "project_config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "legacy_session_fallback": {+ "name": "legacy_session_fallback",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'cron'"+ },+ "cron_expr": {+ "name": "cron_expr",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "timezone": {+ "name": "timezone",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "recurring": {+ "name": "recurring",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "manual": {+ "name": "manual",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "interval_ms": {+ "name": "interval_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "effort": {+ "name": "effort",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "fast_mode": {+ "name": "fast_mode",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "working_dir": {+ "name": "working_dir",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_kind": {+ "name": "workspace_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'project'"+ },+ "use_worktree": {+ "name": "use_worktree",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "target_session_id": {+ "name": "target_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "persistent_session": {+ "name": "persistent_session",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "silent_when_idle": {+ "name": "silent_when_idle",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "pre_run_hook_command": {+ "name": "pre_run_hook_command",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "pre_run_hook_timeout_ms": {+ "name": "pre_run_hook_timeout_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "skip_log_session_id": {+ "name": "skip_log_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "notify_desktop": {+ "name": "notify_desktop",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "notify_feishu": {+ "name": "notify_feishu",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "notify_wecom_group": {+ "name": "notify_wecom_group",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_fired_at": {+ "name": "last_fired_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_finished_at": {+ "name": "last_finished_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "next_fire_at": {+ "name": "next_fire_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expire_at": {+ "name": "expire_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_schedules_active_next": {+ "name": "idx_schedules_active_next",+ "columns": [+ "status",+ "next_fire_at"+ ],+ "isUnique": false+ },+ "idx_schedules_target_session": {+ "name": "idx_schedules_target_session",+ "columns": [+ "target_session_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "schedules_target_session_id_sessions_id_fk": {+ "name": "schedules_target_session_id_sessions_id_fk",+ "tableFrom": "schedules",+ "tableTo": "sessions",+ "columnsFrom": [+ "target_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "schedules_skip_log_session_id_sessions_id_fk": {+ "name": "schedules_skip_log_session_id_sessions_id_fk",+ "tableFrom": "schedules",+ "tableTo": "sessions",+ "columnsFrom": [+ "skip_log_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "session_goals": {+ "name": "session_goals",+ "columns": {+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "objective": {+ "name": "objective",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "budget_tokens": {+ "name": "budget_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "max_turns": {+ "name": "max_turns",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "no_progress_limit": {+ "name": "no_progress_limit",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "turns_used": {+ "name": "turns_used",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "tokens_used": {+ "name": "tokens_used",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "no_progress_streak": {+ "name": "no_progress_streak",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "usage_reset_at": {+ "name": "usage_reset_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_reason": {+ "name": "last_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "started_at": {+ "name": "started_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_session_goals_status": {+ "name": "idx_session_goals_status",+ "columns": [+ "status"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "session_goals_session_id_sessions_id_fk": {+ "name": "session_goals_session_id_sessions_id_fk",+ "tableFrom": "session_goals",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "session_pr_refs": {+ "name": "session_pr_refs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "owner": {+ "name": "owner",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "repo": {+ "name": "repo",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "pr_number": {+ "name": "pr_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "first_seen_at": {+ "name": "first_seen_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_seen_at": {+ "name": "last_seen_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_session_pr_refs": {+ "name": "uniq_session_pr_refs",+ "columns": [+ "session_id",+ "owner",+ "repo",+ "pr_number"+ ],+ "isUnique": true+ },+ "idx_session_pr_refs_session_last_seen": {+ "name": "idx_session_pr_refs_session_last_seen",+ "columns": [+ "session_id",+ "last_seen_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "session_pr_refs_session_id_sessions_id_fk": {+ "name": "session_pr_refs_session_id_sessions_id_fk",+ "tableFrom": "session_pr_refs",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "sessions": {+ "name": "sessions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'New Maker'"+ },+ "working_dir": {+ "name": "working_dir",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_kind": {+ "name": "workspace_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'project'"+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'claude-sonnet-4-6'"+ },+ "effort": {+ "name": "effort",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'high'"+ },+ "permission_mode": {+ "name": "permission_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'ask'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "sdk_session_id": {+ "name": "sdk_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "total_token_usage": {+ "name": "total_token_usage",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "total_cost_usd": {+ "name": "total_cost_usd",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "total_cost_amount": {+ "name": "total_cost_amount",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "total_cost_currency": {+ "name": "total_cost_currency",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "total_cost_is_approximate": {+ "name": "total_cost_is_approximate",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "context_tokens": {+ "name": "context_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "context_window": {+ "name": "context_window",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "fast_mode": {+ "name": "fast_mode",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "plan_mode_enabled": {+ "name": "plan_mode_enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "cleared_at": {+ "name": "cleared_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "pinned_at": {+ "name": "pinned_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_send_at": {+ "name": "user_send_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'cc'"+ },+ "orca_role": {+ "name": "orca_role",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "parent_session_id": {+ "name": "parent_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "forked_at_message_id": {+ "name": "forked_at_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "worktree_path": {+ "name": "worktree_path",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'desktop'"+ },+ "feishu_open_id": {+ "name": "feishu_open_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "feishu_bot_app_id": {+ "name": "feishu_bot_app_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "im_bot_context_id": {+ "name": "im_bot_context_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "im_user_id": {+ "name": "im_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "used_project_context": {+ "name": "used_project_context",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "codex_history_has_product_prompt": {+ "name": "codex_history_has_product_prompt",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "extra_dirs": {+ "name": "extra_dirs",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "remote_host_id": {+ "name": "remote_host_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "active_turn_started_at": {+ "name": "active_turn_started_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "active_turn_pid": {+ "name": "active_turn_pid",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_turn_ended_at": {+ "name": "last_turn_ended_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_sessions_updated_at": {+ "name": "idx_sessions_updated_at",+ "columns": [+ "updated_at"+ ],+ "isUnique": false+ },+ "idx_sessions_user_send_at": {+ "name": "idx_sessions_user_send_at",+ "columns": [+ "user_send_at"+ ],+ "isUnique": false+ },+ "idx_sessions_sdk_session_id": {+ "name": "idx_sessions_sdk_session_id",+ "columns": [+ "sdk_session_id"+ ],+ "isUnique": false+ },+ "idx_sessions_workdir_created": {+ "name": "idx_sessions_workdir_created",+ "columns": [+ "working_dir",+ "created_at",+ "id"+ ],+ "isUnique": false+ },+ "idx_sessions_created_at": {+ "name": "idx_sessions_created_at",+ "columns": [+ "created_at",+ "id"+ ],+ "isUnique": false+ },+ "idx_sessions_workspace_kind": {+ "name": "idx_sessions_workspace_kind",+ "columns": [+ "workspace_kind"+ ],+ "isUnique": false+ },+ "idx_sessions_parent_session_id": {+ "name": "idx_sessions_parent_session_id",+ "columns": [+ "parent_session_id"+ ],+ "isUnique": false+ },+ "idx_sessions_orca_role": {+ "name": "idx_sessions_orca_role",+ "columns": [+ "orca_role"+ ],+ "isUnique": false+ },+ "idx_sessions_worktree_path": {+ "name": "idx_sessions_worktree_path",+ "columns": [+ "worktree_path"+ ],+ "isUnique": false+ },+ "idx_sessions_feishu_lookup": {+ "name": "idx_sessions_feishu_lookup",+ "columns": [+ "source",+ "feishu_bot_app_id",+ "feishu_open_id"+ ],+ "isUnique": false+ },+ "idx_sessions_im_lookup": {+ "name": "idx_sessions_im_lookup",+ "columns": [+ "source",+ "im_bot_context_id",+ "im_user_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "sessions_parent_session_id_sessions_id_fk": {+ "name": "sessions_parent_session_id_sessions_id_fk",+ "tableFrom": "sessions",+ "tableTo": "sessions",+ "columnsFrom": [+ "parent_session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "skill_usage_exposures": {+ "name": "skill_usage_exposures",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "analyzer_version": {+ "name": "analyzer_version",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'6'"+ },+ "raw_file_path": {+ "name": "raw_file_path",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "raw_line_no": {+ "name": "raw_line_no",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "sdk_session_id": {+ "name": "sdk_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "agent_kind": {+ "name": "agent_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "skill_name": {+ "name": "skill_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "skill_path": {+ "name": "skill_path",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "skill_document_hash": {+ "name": "skill_document_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "exposure_content_hash": {+ "name": "exposure_content_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "document_hash_source": {+ "name": "document_hash_source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tool_use_id": {+ "name": "tool_use_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "seen_at": {+ "name": "seen_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tool_call_count": {+ "name": "tool_call_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "repeated_tool_call_count": {+ "name": "repeated_tool_call_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "tool_error_count": {+ "name": "tool_error_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "command_call_count": {+ "name": "command_call_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "command_failure_count": {+ "name": "command_failure_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ }+ },+ "indexes": {+ "idx_skill_usage_exposures_skill_document_version": {+ "name": "idx_skill_usage_exposures_skill_document_version",+ "columns": [+ "analyzer_version",+ "skill_name",+ "skill_document_hash"+ ],+ "isUnique": false+ },+ "idx_skill_usage_exposures_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+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "reasoning_effort": {+ "name": "reasoning_effort",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "total_tokens": {+ "name": "total_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "tool_uses": {+ "name": "tool_uses",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "duration_ms": {+ "name": "duration_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "capabilities": {+ "name": "capabilities",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "activity": {+ "name": "activity",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "started_at": {+ "name": "started_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ended_at": {+ "name": "ended_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "rewind_at": {+ "name": "rewind_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "subagent_runs_logical_idx": {+ "name": "subagent_runs_logical_idx",+ "columns": [+ "session_id",+ "provider",+ "logical_agent_id"+ ],+ "isUnique": false+ },+ "subagent_runs_session_idx": {+ "name": "subagent_runs_session_idx",+ "columns": [+ "session_id",+ "rewind_at",+ "deleted_at",+ "started_at"+ ],+ "isUnique": false+ },+ "subagent_runs_parent_tool_use_idx": {+ "name": "subagent_runs_parent_tool_use_idx",+ "columns": [+ "session_id",+ "parent_tool_use_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "subagent_runs_session_id_sessions_id_fk": {+ "name": "subagent_runs_session_id_sessions_id_fk",+ "tableFrom": "subagent_runs",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "vec_table_meta": {+ "name": "vec_table_meta",+ "columns": {+ "vec_table": {+ "name": "vec_table",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "model_id": {+ "name": "model_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "dim": {+ "name": "dim",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "registered_at": {+ "name": "registered_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "notes": {+ "name": "notes",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "wechat_file_attachments": {+ "name": "wechat_file_attachments",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "binding_epoch": {+ "name": "binding_epoch",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "abs_path": {+ "name": "abs_path",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "original_name": {+ "name": "original_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "bytes": {+ "name": "bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'staged'"+ },+ "promoted_at": {+ "name": "promoted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_wechat_file_attachments_task": {+ "name": "idx_wechat_file_attachments_task",+ "columns": [+ "binding_epoch",+ "task_id"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "wechat_file_attachments_binding_epoch_wechat_sync_state_binding_epoch_fk": {+ "name": "wechat_file_attachments_binding_epoch_wechat_sync_state_binding_epoch_fk",+ "tableFrom": "wechat_file_attachments",+ "tableTo": "wechat_sync_state",+ "columnsFrom": [+ "binding_epoch"+ ],+ "columnsTo": [+ "binding_epoch"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "wechat_file_attachments_task_id_wechat_inbox_id_fk": {+ "name": "wechat_file_attachments_task_id_wechat_inbox_id_fk",+ "tableFrom": "wechat_file_attachments",+ "tableTo": "wechat_inbox",+ "columnsFrom": [+ "task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "wechat_file_attachments_session_id_sessions_id_fk": {+ "name": "wechat_file_attachments_session_id_sessions_id_fk",+ "tableFrom": "wechat_file_attachments",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "wechat_inbox": {+ "name": "wechat_inbox",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "binding_epoch": {+ "name": "binding_epoch",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "platform_message_id": {+ "name": "platform_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "platform_seq": {+ "name": "platform_seq",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "peer_id": {+ "name": "peer_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "received_at": {+ "name": "received_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "platform_created_at": {+ "name": "platform_created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "lease_until": {+ "name": "lease_until",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "conversation_epoch": {+ "name": "conversation_epoch",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "payload_json": {+ "name": "payload_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "context_nonce": {+ "name": "context_nonce",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "context_ciphertext": {+ "name": "context_ciphertext",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "context_tag": {+ "name": "context_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "last_error_code": {+ "name": "last_error_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_wechat_inbox_platform_message": {+ "name": "uniq_wechat_inbox_platform_message",+ "columns": [+ "binding_epoch",+ "platform_message_id"+ ],+ "isUnique": true+ },+ "idx_wechat_inbox_queue": {+ "name": "idx_wechat_inbox_queue",+ "columns": [+ "binding_epoch",+ "status",+ "received_at"+ ],+ "isUnique": false+ },+ "idx_wechat_inbox_lease": {+ "name": "idx_wechat_inbox_lease",+ "columns": [+ "binding_epoch",+ "lease_until"+ ],+ "isUnique": false+ },+ "idx_wechat_inbox_conversation": {+ "name": "idx_wechat_inbox_conversation",+ "columns": [+ "binding_epoch",+ "peer_id",+ "conversation_epoch"+ ],+ "isUnique": false+ },+ "uniq_wechat_inbox_running_session": {+ "name": "uniq_wechat_inbox_running_session",+ "columns": [+ "binding_epoch",+ "session_id"+ ],+ "isUnique": true,+ "where": "\"wechat_inbox\".\"session_id\" IS NOT NULL AND \"wechat_inbox\".\"status\" IN ('dispatching', 'accepted_running', 'waiting_desktop', 'delivery_pending')"+ }+ },+ "foreignKeys": {+ "wechat_inbox_binding_epoch_wechat_sync_state_binding_epoch_fk": {+ "name": "wechat_inbox_binding_epoch_wechat_sync_state_binding_epoch_fk",+ "tableFrom": "wechat_inbox",+ "tableTo": "wechat_sync_state",+ "columnsFrom": [+ "binding_epoch"+ ],+ "columnsTo": [+ "binding_epoch"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "wechat_inbox_session_id_sessions_id_fk": {+ "name": "wechat_inbox_session_id_sessions_id_fk",+ "tableFrom": "wechat_inbox",+ "tableTo": "sessions",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "wechat_outbox": {+ "name": "wechat_outbox",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "binding_epoch": {+ "name": "binding_epoch",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "chunk_index": {+ "name": "chunk_index",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "text": {+ "name": "text",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "media_json": {+ "name": "media_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "next_retry_at": {+ "name": "next_retry_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "delivered_at": {+ "name": "delivered_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_wechat_outbox_client_id": {+ "name": "uniq_wechat_outbox_client_id",+ "columns": [+ "binding_epoch",+ "client_id"+ ],+ "isUnique": true+ },+ "idx_wechat_outbox_delivery": {+ "name": "idx_wechat_outbox_delivery",+ "columns": [+ "binding_epoch",+ "status",+ "next_retry_at"+ ],+ "isUnique": false+ },+ "idx_wechat_outbox_task": {+ "name": "idx_wechat_outbox_task",+ "columns": [+ "binding_epoch",+ "task_id",+ "chunk_index"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "wechat_outbox_binding_epoch_wechat_sync_state_binding_epoch_fk": {+ "name": "wechat_outbox_binding_epoch_wechat_sync_state_binding_epoch_fk",+ "tableFrom": "wechat_outbox",+ "tableTo": "wechat_sync_state",+ "columnsFrom": [+ "binding_epoch"+ ],+ "columnsTo": [+ "binding_epoch"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "wechat_outbox_task_id_wechat_inbox_id_fk": {+ "name": "wechat_outbox_task_id_wechat_inbox_id_fk",+ "tableFrom": "wechat_outbox",+ "tableTo": "wechat_inbox",+ "columnsFrom": [+ "task_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "wechat_sync_state": {+ "name": "wechat_sync_state",+ "columns": {+ "binding_epoch": {+ "name": "binding_epoch",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "is_active": {+ "name": "is_active",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "sync_cursor": {+ "name": "sync_cursor",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "last_poll_at": {+ "name": "last_poll_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_error_code": {+ "name": "last_error_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "uniq_wechat_sync_active": {+ "name": "uniq_wechat_sync_active",+ "columns": [+ "is_active"+ ],+ "isUnique": true,+ "where": "\"wechat_sync_state\".\"is_active\" = 1"+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "indexes": {+ "uniq_orca_worker_creation_reservations_team_label": {+ "columns": {+ "lower(\"label\")": {+ "isExpression": true+ }+ }+ },+ "uniq_orca_workers_team_label": {+ "columns": {+ "lower(\"label\")": {+ "isExpression": true+ }+ }+ }+ }+ }+}\ No newline at end of filediff --git a/apps/desktop/drizzle/meta/_journal.json b/apps/desktop/drizzle/meta/_journal.jsonindex d4c5a999b2..7b10d90b09 100644--- a/apps/desktop/drizzle/meta/_journal.json+++ b/apps/desktop/drizzle/meta/_journal.json@@ -624,6 +624,13 @@"when": 1786092084443,"tag": "0088_thankful_captain_midlands","breakpoints": true+ },+ {+ "idx": 89,+ "version": "6",+ "when": 1786257834139,+ "tag": "0089_rich_power_pack",+ "breakpoints": true}]-}\ No newline at end of file+}diff --git a/apps/desktop/drizzle/scripts/0089_rich_power_pack.ts b/apps/desktop/drizzle/scripts/0089_rich_power_pack.tsnew file mode 100644index 0000000000..a29a50477a--- /dev/null+++ b/apps/desktop/drizzle/scripts/0089_rich_power_pack.ts@@ -0,0 +1,18 @@+import type Database from 'better-sqlite3';++function tableExists(db: Database.Database, tableName: string): boolean {+ return Boolean(+ db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(tableName),+ );+}++function run(db: Database.Database): void {+ if (!tableExists(db, 'right_sidebar_tabs')) return;+ db.exec(+ `CREATE UNIQUE INDEX IF NOT EXISTS right_sidebar_tabs_subagents_singleton_idx+ ON right_sidebar_tabs (session_id)+ WHERE kind = 'subagents'`,+ );+}++module.exports = { run };diff --git a/apps/desktop/src/main/__tests__/subagentObservationRewindFence.test.ts b/apps/desktop/src/main/__tests__/subagentObservationRewindFence.test.tsnew file mode 100644index 0000000000..3c4d43d915--- /dev/null+++ b/apps/desktop/src/main/__tests__/subagentObservationRewindFence.test.ts@@ -0,0 +1,340 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ __resetSubagentObservationRewindStateForTesting,+ beginSubagentRewindFence,+ captureSubagentObservationGeneration,+ clearSubagentObservationRewindState,+ enqueueSubagentObservationWrite,+ finishSubagentRewindFence,+ noteSubagentObservationTurnStarted,+ primeSubagentRewindFence,+} from '../subagentObservationRewindFence.js';++const SESSION = 'session-1';++function update(+ taskId: string,+ kind: 'spawn' | 'progress' | 'terminal',+ status: 'running' | 'completed' = kind === 'terminal' ? 'completed' : 'running',+) {+ return {+ provider: 'claude-code',+ taskId,+ status,+ subagentObservation: {+ kind,+ logicalSubagentId: taskId,+ },+ };+}++function enqueueWrite(data: unknown, writes: string[], value: string) {+ const stamp = captureSubagentObservationGeneration({+ sessionId: SESSION,+ data,+ source: 'claude-code',+ });+ if (!stamp) return Promise.resolve(null);+ return enqueueSubagentObservationWrite({+ sessionId: SESSION,+ stamp,+ enqueue: async () => {+ writes.push(value);+ return value;+ },+ });+}++beforeEach(() => {+ __resetSubagentObservationRewindStateForTesting();+});++afterEach(() => {+ __resetSubagentObservationRewindStateForTesting();+ vi.useRealTimers();+});++describe('Subagent observation Rewind generation fence', () => {+ it('drops Stop/SDK-rollback lifecycle frames that arrive inside a committed Rewind', async () => {+ const writes: string[] = [];+ await expect(enqueueWrite(update('old-task', 'spawn'), writes, 'old-spawn')).resolves.toBe(+ 'old-spawn',+ );++ const fence = beginSubagentRewindFence(SESSION);+ primeSubagentRewindFence(fence, [+ { provider: 'claude-code', identities: ['old-task'] },+ ]);+ const lateSpawn = enqueueWrite(update('late-task', 'spawn'), writes, 'late-spawn');+ const lateProgress = enqueueWrite(update('old-task', 'progress'), writes, 'late-progress');+ const lateTerminal = enqueueWrite(update('old-task', 'terminal'), writes, 'late-terminal');++ expect(writes).toEqual(['old-spawn']);+ finishSubagentRewindFence(fence, true);++ await expect(Promise.all([lateSpawn, lateProgress, lateTerminal])).resolves.toEqual([+ null,+ null,+ null,+ ]);+ expect(writes).toEqual(['old-spawn']);+ });++ it('freezes generation when the event is observed, before its durable enqueue runs', async () => {+ const writes: string[] = [];+ const data = update('boundary-task', 'spawn');+ const stamp = captureSubagentObservationGeneration({+ sessionId: SESSION,+ data,+ source: 'claude-code',+ });+ if (!stamp) throw new Error('expected generation stamp');++ const fence = beginSubagentRewindFence(SESSION);+ const pending = enqueueSubagentObservationWrite({+ sessionId: SESSION,+ stamp,+ enqueue: async () => {+ writes.push('boundary-task');+ return 'boundary-task';+ },+ });+ finishSubagentRewindFence(fence, true);++ await expect(pending).resolves.toBeNull();+ expect(writes).toEqual([]);+ });++ it('keeps duplicate/out-of-order old-task frames hidden but accepts a new task after commit', async () => {+ const writes: string[] = [];+ await enqueueWrite(update('old-task', 'spawn'), writes, 'old-spawn');+ const fence = beginSubagentRewindFence(SESSION);+ finishSubagentRewindFence(fence, true);++ await expect(enqueueWrite(update('old-task', 'spawn'), writes, 'old-spawn-again')).resolves.toBeNull();+ await expect(enqueueWrite(update('old-task', 'terminal'), writes, 'old-terminal')).resolves.toBeNull();+ await expect(enqueueWrite(update('old-task', 'progress'), writes, 'old-progress')).resolves.toBeNull();+ await expect(enqueueWrite(update('new-task', 'spawn'), writes, 'premature-new-spawn')).resolves.toBeNull();+ noteSubagentObservationTurnStarted(SESSION);+ await expect(enqueueWrite(update('new-task', 'spawn'), writes, 'new-spawn')).resolves.toBe(+ 'new-spawn',+ );+ await expect(enqueueWrite(update('new-task', 'terminal'), writes, 'new-terminal')).resolves.toBe(+ 'new-terminal',+ );++ expect(writes).toEqual(['old-spawn', 'new-spawn', 'new-terminal']);+ });++ it('migrates still-visible tasks and preserves their buffered and later terminal updates', async () => {+ const writes: string[] = [];+ await enqueueWrite(update('survivor', 'spawn'), writes, 'survivor-spawn');+ await enqueueWrite(update('withdrawn', 'spawn'), writes, 'withdrawn-spawn');+ const fence = beginSubagentRewindFence(SESSION);+ primeSubagentRewindFence(fence, [+ { provider: 'claude-code', identities: ['survivor'] },+ { provider: 'claude-code', identities: ['withdrawn'] },+ ]);+ const survivorProgress = enqueueWrite(+ update('survivor', 'progress'),+ writes,+ 'survivor-progress',+ );+ const survivorTerminal = enqueueWrite(+ update('survivor', 'terminal'),+ writes,+ 'survivor-terminal',+ );+ const withdrawnTerminal = enqueueWrite(+ update('withdrawn', 'terminal'),+ writes,+ 'withdrawn-terminal',+ );++ finishSubagentRewindFence(fence, true, [+ { provider: 'claude-code', identities: ['survivor'] },+ ]);++ await expect(Promise.all([+ survivorProgress,+ survivorTerminal,+ withdrawnTerminal,+ ])).resolves.toEqual(['survivor-progress', 'survivor-terminal', null]);+ await expect(+ enqueueWrite(update('survivor', 'progress'), writes, 'survivor-late-progress'),+ ).resolves.toBe('survivor-late-progress');+ await expect(+ enqueueWrite(update('withdrawn', 'progress'), writes, 'withdrawn-late-progress'),+ ).resolves.toBeNull();++ expect(writes).toEqual([+ 'survivor-spawn',+ 'withdrawn-spawn',+ 'survivor-progress',+ 'survivor-terminal',+ 'survivor-late-progress',+ ]);+ });++ it('replays buffered observations in arrival order when Rewind fails', async () => {+ const writes: string[] = [];+ await enqueueWrite(update('task', 'spawn'), writes, 'spawn');+ const fence = beginSubagentRewindFence(SESSION);+ const progress = enqueueWrite(update('task', 'progress'), writes, 'progress');+ const terminal = enqueueWrite(update('task', 'terminal'), writes, 'terminal');++ finishSubagentRewindFence(fence, false);++ await expect(Promise.all([progress, terminal])).resolves.toEqual(['progress', 'terminal']);+ expect(writes).toEqual(['spawn', 'progress', 'terminal']);+ });++ it('applies the same session-local fence to every provider without blocking other sessions', async () => {+ const writes: string[] = [];+ const fence = beginSubagentRewindFence(SESSION);+ const providers = ['claude-code', 'codex', 'pi'] as const;+ const pending = providers.map((provider) => {+ const data = {+ provider,+ taskId: `${provider}-task`,+ status: 'running',+ subagentObservation: { kind: 'spawn', logicalSubagentId: `${provider}-task` },+ };+ const stamp = captureSubagentObservationGeneration({+ sessionId: SESSION,+ data,+ source: provider,+ });+ if (!stamp) return Promise.resolve(null);+ return enqueueSubagentObservationWrite({+ sessionId: SESSION,+ stamp,+ enqueue: async () => {+ writes.push(provider);+ return provider;+ },+ });+ });+ const otherData = update('other-task', 'spawn');+ const otherStamp = captureSubagentObservationGeneration({+ sessionId: 'other-session',+ data: otherData,+ source: 'claude-code',+ });+ if (!otherStamp) throw new Error('expected other session stamp');+ await expect(+ enqueueSubagentObservationWrite({+ sessionId: 'other-session',+ stamp: otherStamp,+ enqueue: async () => {+ writes.push('other-session');+ return 'other-session';+ },+ }),+ ).resolves.toBe('other-session');++ finishSubagentRewindFence(fence, true);++ await expect(Promise.all(pending)).resolves.toEqual([null, null, null]);+ expect(writes).toEqual(['other-session']);+ });++ it('drops buffered writes when a closing session finishes its active Rewind', async () => {+ vi.useFakeTimers();+ const writes: string[] = [];+ const fence = beginSubagentRewindFence(SESSION);+ const pending = enqueueWrite(update('closing-task', 'progress'), writes, 'progress');++ expect(clearSubagentObservationRewindState(SESSION)).toBe(false);+ expect(vi.getTimerCount()).toBe(1);+ finishSubagentRewindFence(fence, false);++ await expect(pending).resolves.toBeNull();+ expect(writes).toEqual([]);+ expect(vi.getTimerCount()).toBe(0);+ expect(() => beginSubagentRewindFence(SESSION)).not.toThrow();+ });++ it('bounds deferred cleanup when an active Rewind never finishes', async () => {+ vi.useFakeTimers();+ const writes: string[] = [];+ const fence = beginSubagentRewindFence(SESSION);+ const pending = enqueueWrite(update('stuck-task', 'terminal'), writes, 'terminal');++ expect(clearSubagentObservationRewindState(SESSION)).toBe(false);+ expect(clearSubagentObservationRewindState(SESSION)).toBe(false);+ expect(vi.getTimerCount()).toBe(1);++ await vi.runAllTimersAsync();+ await expect(pending).resolves.toBeNull();+ expect(writes).toEqual([]);++ const nextFence = beginSubagentRewindFence(SESSION);+ finishSubagentRewindFence(fence, false);+ finishSubagentRewindFence(nextFence, false);+ expect(clearSubagentObservationRewindState(SESSION)).toBe(true);+ });++ it('lets a rebuilt session replace deferred state before the timeout', async () => {+ vi.useFakeTimers();+ const writes: string[] = [];+ const staleFence = beginSubagentRewindFence(SESSION);+ const stalePending = enqueueWrite(update('stale-task', 'progress'), writes, 'stale');+ expect(clearSubagentObservationRewindState(SESSION)).toBe(false);++ const freshFence = beginSubagentRewindFence(SESSION);+ await expect(stalePending).resolves.toBeNull();+ expect(vi.getTimerCount()).toBe(0);+ const freshWrite = enqueueWrite(update('fresh-task', 'spawn'), writes, 'fresh');++ finishSubagentRewindFence(staleFence, false);+ finishSubagentRewindFence(freshFence, false);+ await expect(freshWrite).resolves.toBe('fresh');+ expect(writes).toEqual(['fresh']);+ });++ it('lets a rebuilt provider turn replace deferred state before the timeout', async () => {+ vi.useFakeTimers();+ const writes: string[] = [];+ beginSubagentRewindFence(SESSION);+ const stalePending = enqueueWrite(update('stale-task', 'progress'), writes, 'stale');+ expect(clearSubagentObservationRewindState(SESSION)).toBe(false);++ noteSubagentObservationTurnStarted(SESSION);+ await expect(stalePending).resolves.toBeNull();+ expect(vi.getTimerCount()).toBe(0);+ await expect(enqueueWrite(update('fresh-task', 'spawn'), writes, 'fresh')).resolves.toBe('fresh');+ expect(writes).toEqual(['fresh']);+ });++ it('keeps deferred cleanup isolated to the closing session', async () => {+ vi.useFakeTimers();+ const writes: string[] = [];+ beginSubagentRewindFence(SESSION);+ const pending = enqueueWrite(update('closing-task', 'progress'), writes, 'closing');+ expect(clearSubagentObservationRewindState(SESSION)).toBe(false);++ const otherData = update('other-task', 'spawn');+ const otherStamp = captureSubagentObservationGeneration({+ sessionId: 'other-session',+ data: otherData,+ source: 'claude-code',+ });+ if (!otherStamp) throw new Error('expected other session stamp');+ await expect(+ enqueueSubagentObservationWrite({+ sessionId: 'other-session',+ stamp: otherStamp,+ enqueue: async () => {+ writes.push('other');+ return 'other';+ },+ }),+ ).resolves.toBe('other');++ await vi.runAllTimersAsync();+ await expect(pending).resolves.toBeNull();+ expect(writes).toEqual(['other']);+ });+});diff --git a/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts b/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.tsindex ed8b36963f..c385f57e2a 100644--- a/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts+++ b/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts@@ -55,6 +55,7 @@ const h = vi.hoisted(() => {return {tapWindowBroadcast: vi.fn(),webContentsSend: vi.fn(),+ broadcastSubagentRunsInvalidated: vi.fn(),agentIslandService: {handleSessionClosed: vi.fn(),handleSessionMetadataPatch: vi.fn(),@@ -92,6 +93,9 @@ vi.mock('../localDb/client/current', () => ({ getDbClient: () => ({ drizzle: h.fvi.mock('../agent-island/service.js', () => ({getAgentIslandService: () => h.agentIslandService,}));+vi.mock('../localDb/ipc/subagentRuns.js', () => ({+ broadcastSubagentRunsInvalidated: h.broadcastSubagentRunsInvalidated,+}));import { notifyAgentIslandSessionPatch } from '../localDb/agentIslandSessionPatch.js';import { clearSessionContextInDb, touchUserSendInDb, persistSessionFields } from '../localDb/ipc/sessions.js';@@ -198,6 +202,7 @@ describe('clearSessionContextInDb 广播 sessions:patched(device-link /clear 收sessionId: 'sess-clear',patch: { sdkSessionId: null, clearedAt: iso, updatedAt: iso },});+ expect(h.broadcastSubagentRunsInvalidated).toHaveBeenCalledWith('sess-clear', null);});it('把 DB 读回的有效 clear 边界登记给晚到 background 过滤器', async () => {@@ -225,6 +230,7 @@ describe('clearSessionContextInDb 广播 sessions:patched(device-link /clear 收await expect(clearSessionContextInDb(sessionId, requestedAt)).rejects.toThrow('db unavailable');+ expect(h.broadcastSubagentRunsInvalidated).not.toHaveBeenCalled();expect(backgroundTurnPredatesSessionClear(sessionId, requestedAt - 1)).toBe(true);expect(backgroundTurnPredatesSessionClear(sessionId, requestedAt + 1)).toBe(false);noteSessionClearBoundary(sessionId, null);diff --git a/apps/desktop/src/main/localDb/__tests__/subagentRuns.test.ts b/apps/desktop/src/main/localDb/__tests__/subagentRuns.test.tsnew file mode 100644index 0000000000..d8837dd2d2--- /dev/null+++ b/apps/desktop/src/main/localDb/__tests__/subagentRuns.test.ts@@ -0,0 +1,749 @@+import Database from 'better-sqlite3';+import { drizzle } from 'drizzle-orm/better-sqlite3';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import type { DbClient } from '../client/DbClient.js';+import { clearCurrentDbClient, setCurrentDbClient } from '../client/current.js';+import * as schema from '../schema.js';+import {+ getSubagentRunDetail,+ listVisibleSubagentObservationIdentities,+ listSubagentRuns,+ persistSubagentTaskUpdate,+} from '../subagentRuns.js';++describe('durable Subagent runs', () => {+ let rawDb: Database.Database;+ let client: DbClient;++ beforeEach(() => {+ rawDb = new Database(':memory:');+ rawDb.exec(`+ PRAGMA foreign_keys = ON;+ CREATE TABLE sessions (+ id TEXT PRIMARY KEY,+ status TEXT NOT NULL DEFAULT 'active',+ cleared_at INTEGER+ );+ CREATE TABLE messages (+ id TEXT PRIMARY KEY,+ client_id TEXT NOT NULL,+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,+ role TEXT NOT NULL,+ content TEXT NOT NULL,+ tool_use_id TEXT,+ created_at INTEGER NOT NULL,+ rewind_at INTEGER+ );+ CREATE TABLE subagent_runs (+ id TEXT PRIMARY KEY,+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,+ provider TEXT NOT NULL,+ logical_agent_id TEXT NOT NULL,+ parent_tool_use_id TEXT,+ aliases TEXT NOT NULL DEFAULT '[]',+ provider_run_ids TEXT NOT NULL DEFAULT '[]',+ status TEXT NOT NULL DEFAULT 'running',+ title TEXT,+ description TEXT,+ summary TEXT,+ model TEXT,+ reasoning_effort TEXT,+ total_tokens INTEGER,+ tool_uses INTEGER,+ duration_ms INTEGER,+ capabilities TEXT NOT NULL DEFAULT '{}',+ activity TEXT NOT NULL DEFAULT '[]',+ started_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ ended_at INTEGER,+ rewind_at INTEGER,+ deleted_at INTEGER+ );+ CREATE INDEX subagent_runs_logical_idx+ ON subagent_runs (session_id, provider, logical_agent_id);+ CREATE INDEX subagent_runs_session_idx+ ON subagent_runs (session_id, rewind_at, deleted_at, started_at);+ CREATE INDEX subagent_runs_parent_tool_use_idx+ ON subagent_runs (session_id, parent_tool_use_id);+ CREATE TABLE subagent_run_aliases (+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,+ provider TEXT NOT NULL,+ alias TEXT NOT NULL,+ run_id TEXT NOT NULL REFERENCES subagent_runs(id) ON DELETE CASCADE,+ created_at INTEGER NOT NULL,+ PRIMARY KEY (run_id, alias)+ );+ CREATE INDEX subagent_run_aliases_lookup_idx+ ON subagent_run_aliases (session_id, provider, alias, created_at);+ `);+ const db = drizzle(rawDb, { schema });+ client = {+ query: async <T = unknown>(sql: string, params: unknown[] = []) =>+ rawDb.prepare(sql).all(...params) as T[],+ queryOne: async <T = unknown>(sql: string, params: unknown[] = []) =>+ rawDb.prepare(sql).get(...params) as T | undefined,+ exec: async (sql, params = []) => rawDb.prepare(sql).run(...params),+ tx: async () => {+ throw new Error('tx is not used by this test');+ },+ drizzle: db,+ vecAvailable: false,+ dispose: async () => {},+ };+ setCurrentDbClient(client, 'subagent-test');+ rawDb.prepare('INSERT INTO sessions (id) VALUES (?)').run('session-1');+ });++ afterEach(() => {+ clearCurrentDbClient(client);+ rawDb.close();+ });++ it('survives reload, merges aliases, and returns the result sent to the parent', async () => {+ insertMessage('tool-use-1', 'tool_use', '{}', 'parent-tool-1', 900);++ const created = await persistSubagentTaskUpdate(+ 'session-1',+ observed({+ provider: 'pi',+ taskId: 'pi-child-1',+ parentToolUseId: 'parent-tool-1',+ status: 'running',+ title: 'Research plugins',+ description: 'Survey durable Subagent patterns',+ model: 'anthropic/claude-opus-5',+ updatedAt: '1970-01-01T00:00:01.000Z',+ }, { providerRunIds: ['pi-session-1'] }),+ 'pi',+ );+ expect(created).toMatchObject({ created: true, firstForSession: true });++ const merged = await persistSubagentTaskUpdate(+ 'session-1',+ observed({+ provider: 'pi',+ taskId: 'parent-tool-1',+ parentToolUseId: 'parent-tool-1',+ status: 'completed',+ summary: 'Found the reusable lifecycle contract',+ usage: { totalTokens: 1234, toolUses: 7, durationMs: 8000 },+ updatedAt: '1970-01-01T00:00:02.000Z',+ }, { kind: 'terminal', logicalSubagentId: 'pi-child-1' }),+ 'pi',+ );+ expect(merged).toEqual({+ runId: created!.runId,+ created: false,+ firstForSession: false,+ });+ insertMessage(+ 'tool-result-1',+ 'tool_result',+ JSON.stringify('Durable result returned to the parent'),+ 'parent-tool-1',+ 2100,+ );++ // Read through the DB API only: there is no renderer/live-map state to help.+ const listed = (await listSubagentRuns('session-1'))?.runs;+ expect(listed).toHaveLength(1);+ expect(listed?.[0]).toMatchObject({+ id: created!.runId,+ provider: 'pi',+ logicalAgentId: 'pi-child-1',+ parentToolUseId: 'parent-tool-1',+ providerRunIds: ['pi-session-1'],+ status: 'completed',+ title: 'Research plugins',+ summary: 'Found the reusable lifecycle contract',+ usage: { totalTokens: 1234, toolUses: 7, durationMs: 8000 },+ });+ const detail = await getSubagentRunDetail('session-1', 'pi', created!.runId);+ expect(detail?.activity.map((entry) => entry.kind)).toEqual(['started', 'completed']);+ expect(detail?.returnedResult).toBe('Durable result returned to the parent');+ expect(detail?.capabilities).toMatchObject({+ viewActivity: true,+ viewReturnedResult: true,+ viewFullTranscript: false,+ resume: false,+ steer: false,+ });+ expect((await getSubagentRunDetail('session-1', 'pi', 'parent-tool-1'))?.id).toBe(+ created!.runId,+ );+ expect((await getSubagentRunDetail('session-1', 'pi', 'pi-session-1'))?.id).toBe(+ created!.runId,+ );+ });++ it('keeps equal native aliases from different harnesses as separate Cindy runs', async () => {+ const claude = await persistSubagentTaskUpdate('session-1', observed({+ provider: 'claude-code',+ taskId: 'shared-native-id',+ status: 'running',+ updatedAt: '1970-01-01T00:00:01.000Z',+ }));+ const codex = await persistSubagentTaskUpdate('session-1', observed({+ provider: 'codex',+ taskId: 'shared-native-id',+ status: 'running',+ updatedAt: '1970-01-01T00:00:02.000Z',+ }));++ expect(claude).toMatchObject({ created: true, firstForSession: true });+ expect(codex).toMatchObject({ created: true, firstForSession: false });+ expect(codex?.runId).not.toBe(claude?.runId);+ expect((await listSubagentRuns('session-1'))?.runs.map((run) => run.provider)).toEqual([+ 'codex',+ 'claude-code',+ ]);+ expect(+ (await getSubagentRunDetail('session-1', 'claude-code', 'shared-native-id'))?.id,+ ).toBe(claude!.runId);+ expect((await getSubagentRunDetail('session-1', 'codex', 'shared-native-id'))?.id).toBe(+ codex!.runId,+ );+ expect(await getSubagentRunDetail('session-1', 'codex', claude!.runId)).toBeNull();+ });++ it('uses the terminal Codex summary instead of a spawn receipt as the returned result', async () => {+ insertMessage('codex-tool-use', 'tool_use', '{}', 'codex-spawn', 900);+ const spawned = await persistSubagentTaskUpdate(+ 'session-1',+ observed(+ {+ provider: 'codex',+ taskId: 'codex-spawn',+ parentToolUseId: 'codex-spawn',+ status: 'running',+ title: 'Audit auth',+ summary: 'Audit agent started',+ updatedAt: '1970-01-01T00:00:01.000Z',+ },+ { providerRunIds: ['codex-thread-1'] },+ ),+ );+ await persistSubagentTaskUpdate(+ 'session-1',+ {+ provider: 'codex',+ taskId: 'codex-spawn',+ parentToolUseId: 'codex-spawn',+ status: 'completed',+ title: 'spawnAgent',+ summary: 'The audit found no upstream conflict.',+ updatedAt: '1970-01-01T00:00:02.000Z',+ },+ 'codex',+ );+ expect(await getSubagentRunDetail('session-1', 'codex', spawned!.runId)).toMatchObject({+ status: 'running',+ title: 'Audit auth',+ summary: 'The audit found no upstream conflict.',+ });+ expect(+ (await getSubagentRunDetail('session-1', 'codex', spawned!.runId))?.returnedResult,+ ).toBeUndefined();+ await persistSubagentTaskUpdate(+ 'session-1',+ observed(+ {+ provider: 'codex',+ taskId: 'codex-spawn',+ parentToolUseId: 'codex-spawn',+ status: 'completed',+ updatedAt: '1970-01-01T00:00:02.100Z',+ },+ { kind: 'terminal' },+ ),+ );+ insertMessage(+ 'codex-spawn-receipt',+ 'tool_result',+ JSON.stringify('started: codex-thread-1'),+ 'codex-spawn',+ 1100,+ );++ expect(+ (await getSubagentRunDetail('session-1', 'codex', spawned!.runId))?.returnedResult,+ ).toBe('The audit found no upstream conflict.');+ });++ it('uses the terminal Claude summary instead of an async launch receipt', async () => {+ insertMessage('claude-tool-use', 'tool_use', '{}', 'claude-agent', 900);+ const spawned = await persistSubagentTaskUpdate(+ 'session-1',+ observed({+ provider: 'claude-code',+ taskId: 'claude-child',+ parentToolUseId: 'claude-agent',+ status: 'running',+ title: 'Audit persistence',+ updatedAt: '1970-01-01T00:00:01.000Z',+ }),+ );+ await persistSubagentTaskUpdate(+ 'session-1',+ observed(+ {+ provider: 'claude-code',+ taskId: 'claude-child',+ parentToolUseId: 'claude-agent',+ status: 'completed',+ summary: 'The durable audit completed successfully.',+ updatedAt: '1970-01-01T00:00:02.000Z',+ },+ { kind: 'terminal' },+ ),+ );+ insertMessage(+ 'claude-launch-receipt',+ 'tool_result',+ JSON.stringify([+ 'Async agent launched successfully.',+ "agentId: claude-child (internal ID - do not mention to user. Use SendMessage with to: 'claude-child' to continue this agent.)",+ 'The agent is working in the background. You will be notified automatically when it completes.',+ 'Briefly tell the user what you launched and end your response.',+ ].join('\n')),+ 'claude-agent',+ 1100,+ );++ expect(+ (await getSubagentRunDetail('session-1', 'claude-code', spawned!.runId))?.returnedResult,+ ).toBe('The durable audit completed successfully.');+ });++ it('creates a completed-only Codex spawn before later progress and terminal updates', async () => {+ // The translator reconstructs this parent tool boundary before emitting+ // the completed-only task update.+ insertMessage(+ 'completed-only-tool-use',+ 'tool_use',+ '{}',+ 'completed-only-spawn',+ 900,+ );+ const completedOnly = await persistSubagentTaskUpdate(+ 'session-1',+ observed(+ {+ provider: 'codex',+ taskId: 'completed-only-spawn',+ parentToolUseId: 'completed-only-spawn',+ status: 'completed',+ title: 'spawnAgent',+ summary: 'Initial completed snapshot',+ updatedAt: '1970-01-01T00:00:01.000Z',+ },+ { providerRunIds: ['completed-only-child'] },+ ),+ );++ expect(completedOnly).toMatchObject({ created: true, firstForSession: true });+ expect(await getSubagentRunDetail('session-1', 'codex', completedOnly!.runId)).toMatchObject({+ status: 'completed',+ summary: 'Initial completed snapshot',+ providerRunIds: ['completed-only-child'],+ });++ const progressed = await persistSubagentTaskUpdate(+ 'session-1',+ observed(+ {+ provider: 'codex',+ taskId: 'completed-only-spawn',+ status: 'running',+ usage: { totalTokens: 42 },+ updatedAt: '1970-01-01T00:00:02.000Z',+ },+ { kind: 'progress', providerRunIds: ['completed-only-child'] },+ ),+ );+ const terminal = await persistSubagentTaskUpdate(+ 'session-1',+ observed(+ {+ provider: 'codex',+ taskId: 'completed-only-spawn',+ status: 'completed',+ summary: 'Final descendant summary',+ updatedAt: '1970-01-01T00:00:03.000Z',+ },+ { kind: 'terminal', providerRunIds: ['completed-only-child'] },+ ),+ );++ expect(progressed).toMatchObject({ runId: completedOnly!.runId, created: false });+ expect(terminal).toMatchObject({ runId: completedOnly!.runId, created: false });+ expect(await getSubagentRunDetail('session-1', 'codex', completedOnly!.runId)).toMatchObject({+ status: 'completed',+ summary: 'Final descendant summary',+ usage: { totalTokens: 42 },+ providerRunIds: ['completed-only-child'],+ });+ });++ it('honors message rewind and clear boundaries without deleting audit rows', async () => {+ insertMessage('tool-use-2', 'tool_use', '{}', 'parent-tool-2', 900);+ insertMessage('tool-result-before-clear', 'tool_result', 'old result', 'parent-tool-2', 950);+ const created = await persistSubagentTaskUpdate('session-1', observed({+ provider: 'claude-code',+ taskId: 'claude-child-1',+ parentToolUseId: 'parent-tool-2',+ status: 'running',+ updatedAt: '1970-01-01T00:00:01.000Z',+ }));+ expect((await listSubagentRuns('session-1'))?.runs).toHaveLength(1);++ rawDb.prepare('UPDATE messages SET rewind_at = 1100 WHERE id = ?').run('tool-use-2');+ expect((await listSubagentRuns('session-1'))?.runs).toEqual([]);+ rawDb.prepare('UPDATE messages SET rewind_at = NULL WHERE id = ?').run('tool-use-2');+ rawDb.prepare('UPDATE sessions SET cleared_at = 1500 WHERE id = ?').run('session-1');+ expect((await listSubagentRuns('session-1'))?.runs).toEqual([]);++ const afterClear = await persistSubagentTaskUpdate('session-1', observed({+ provider: 'claude-code',+ taskId: 'claude-child-after-clear',+ status: 'running',+ updatedAt: '1970-01-01T00:00:02.000Z',+ }));+ expect(afterClear).toMatchObject({ created: true, firstForSession: true });++ const reusedParent = await persistSubagentTaskUpdate('session-1', observed({+ provider: 'claude-code',+ taskId: 'claude-child-reused-parent',+ parentToolUseId: 'parent-tool-2',+ status: 'completed',+ updatedAt: '1970-01-01T00:00:02.100Z',+ }));+ // A pre-clear tool row with the same provider id must not make the new run+ // visible or expose the old returned result.+ expect((await listSubagentRuns('session-1'))?.runs.map((run) => run.id)).toEqual([+ afterClear!.runId,+ ]);+ expect(+ await getSubagentRunDetail('session-1', 'claude-code', reusedParent!.runId),+ ).toBeNull();++ insertMessage('tool-use-after-clear', 'tool_use', '{}', 'parent-tool-2', 2200);+ expect((await listSubagentRuns('session-1'))?.runs.map((run) => run.id)).toContain(+ reusedParent!.runId,+ );+ expect(+ (await getSubagentRunDetail('session-1', 'claude-code', reusedParent!.runId))+ ?.returnedResult,+ ).toBeUndefined();+ insertMessage(+ 'tool-result-after-clear',+ 'tool_result',+ 'new result',+ 'parent-tool-2',+ 2300,+ );+ expect(+ (await getSubagentRunDetail('session-1', 'claude-code', reusedParent!.runId))+ ?.returnedResult,+ ).toBe('new result');++ expect(+ rawDb.prepare('SELECT id FROM subagent_runs WHERE id = ?').get(created!.runId),+ ).toBeTruthy();+ });++ it('keeps a parentless event observed before clear hidden when its write runs later', async () => {+ rawDb.prepare('UPDATE sessions SET cleared_at = 1500 WHERE id = ?').run('session-1');++ const created = await persistSubagentTaskUpdate(+ 'session-1',+ observed({+ provider: 'claude-code',+ taskId: 'parentless-before-clear',+ status: 'running',+ }),+ 'claude-code',+ 1000,+ );++ expect(created).toMatchObject({ created: true });+ expect(+ rawDb.prepare('SELECT started_at FROM subagent_runs WHERE id = ?').get(created!.runId),+ ).toEqual({ started_at: 1000 });+ expect((await listSubagentRuns('session-1'))?.runs).toEqual([]);+ });++ it('keeps a parentless Claude run terminal across duplicate and late lifecycle updates', async () => {+ const spawned = await persistSubagentTaskUpdate(+ 'session-1',+ observed(+ {+ provider: 'claude-code',+ taskId: 'parentless-claude-lifecycle',+ taskType: 'local_agent',+ status: 'running',+ title: 'Inspect the lifecycle',+ },+ { kind: 'spawn' },+ ),+ 'claude-code',+ 1000,+ );+ const terminal = await persistSubagentTaskUpdate(+ 'session-1',+ observed(+ {+ provider: 'claude-code',+ taskId: 'parentless-claude-lifecycle',+ status: 'completed',+ summary: 'Lifecycle captured',+ usage: { totalTokens: 700, toolUses: 4, durationMs: 1200 },+ },+ { kind: 'terminal' },+ ),+ 'claude-code',+ 2000,+ );+ const lateProgress = await persistSubagentTaskUpdate(+ 'session-1',+ observed(+ {+ provider: 'claude-code',+ taskId: 'parentless-claude-lifecycle',+ status: 'running',+ summary: 'Late progress must not reopen the run',+ },+ { kind: 'progress' },+ ),+ 'claude-code',+ 3000,+ );+ const duplicateTerminal = await persistSubagentTaskUpdate(+ 'session-1',+ observed(+ {+ provider: 'claude-code',+ taskId: 'parentless-claude-lifecycle',+ status: 'completed',+ summary: 'Lifecycle captured',+ usage: { totalTokens: 700, toolUses: 4, durationMs: 1200 },+ },+ { kind: 'terminal' },+ ),+ 'claude-code',+ 4000,+ );++ expect(terminal).toMatchObject({ runId: spawned!.runId, created: false });+ expect(lateProgress).toMatchObject({ runId: spawned!.runId, created: false });+ expect(duplicateTerminal).toMatchObject({ runId: spawned!.runId, created: false });+ expect((await listSubagentRuns('session-1'))?.runs).toHaveLength(1);+ expect(+ await getSubagentRunDetail('session-1', 'claude-code', spawned!.runId),+ ).toMatchObject({+ status: 'completed',+ title: 'Inspect the lifecycle',+ summary: 'Lifecycle captured',+ usage: { totalTokens: 700, toolUses: 4, durationMs: 1200 },+ });+ });++ it('returns every visible provider identity needed to prime a Rewind generation', async () => {+ insertMessage('tool-use-rewind-identity', 'tool_use', '{}', 'parent-tool', 900);+ const visible = await persistSubagentTaskUpdate(+ 'session-1',+ {+ provider: 'codex',+ taskId: 'logical-task',+ parentToolUseId: 'parent-tool',+ status: 'running',+ subagentObservation: {+ kind: 'spawn',+ logicalSubagentId: 'logical-task',+ parentToolUseId: 'parent-tool',+ identityAliases: ['card-alias'],+ providerRunIds: ['native-thread'],+ },+ },+ 'codex',+ 1000,+ );+ await persistSubagentTaskUpdate(+ 'session-1',+ observed({ provider: 'pi', taskId: 'rewound-task', status: 'running' }),+ 'pi',+ 1100,+ );+ rawDb+ .prepare('UPDATE subagent_runs SET rewind_at = 1200 WHERE logical_agent_id = ?')+ .run('rewound-task');++ expect(await listVisibleSubagentObservationIdentities('session-1')).toEqual([+ {+ provider: 'codex',+ identities: expect.arrayContaining([+ 'logical-task',+ 'parent-tool',+ 'card-alias',+ 'native-thread',+ ]),+ },+ ]);+ expect(visible).toBeTruthy();+ });++ it('excludes background Bash and Workflow aggregation from the Subagent workspace', async () => {+ expect(+ await persistSubagentTaskUpdate('session-1', observed({+ provider: 'claude-code',+ taskId: 'bash-1',+ taskType: 'local_bash',+ status: 'running',+ })),+ ).toBeNull();+ expect(+ await persistSubagentTaskUpdate('session-1', observed({+ provider: 'claude-code',+ taskId: 'workflow-1',+ taskType: 'local_workflow',+ status: 'running',+ })),+ ).toBeNull();+ expect((await listSubagentRuns('session-1'))?.runs).toEqual([]);+ });++ it('ignores unmarked Codex control calls and never joins runs by their receivers', async () => {+ const spawned = await persistSubagentTaskUpdate(+ 'session-1',+ observed(+ {+ provider: 'codex',+ taskId: 'spawn-card-1',+ status: 'running',+ title: 'Audit auth',+ },+ { providerRunIds: ['child-a', 'child-b'] },+ ),+ );++ expect(+ await persistSubagentTaskUpdate('session-1', {+ provider: 'codex',+ taskId: 'wait-call-1',+ status: 'completed',+ summary: 'wait completed',+ title: 'wait',+ receiverThreadIds: ['child-a', 'child-b'],+ }),+ ).toBeNull();+ expect(+ await persistSubagentTaskUpdate(+ 'session-1',+ observed(+ {+ provider: 'codex',+ taskId: 'send-call-1',+ status: 'running',+ receiverThreadIds: ['child-a'],+ },+ {+ kind: 'progress',+ logicalSubagentId: 'send-call-1',+ providerRunIds: ['child-a'],+ },+ ),+ ),+ ).toBeNull();++ const run = await getSubagentRunDetail('session-1', 'codex', spawned!.runId);+ expect(run).toMatchObject({+ logicalAgentId: 'spawn-card-1',+ title: 'Audit auth',+ status: 'running',+ providerRunIds: ['child-a', 'child-b'],+ });+ expect((await listSubagentRuns('session-1'))?.runs).toHaveLength(1);+ });++ it('paginates newest-first without making older runs unreachable', async () => {+ for (let index = 0; index < 55; index += 1) {+ await persistSubagentTaskUpdate('session-1', observed({+ provider: 'pi',+ taskId: `pi-child-${index}`,+ status: 'completed',+ updatedAt: new Date(1_000 + index).toISOString(),+ }));+ }++ const first = await listSubagentRuns('session-1');+ expect(first?.runs).toHaveLength(50);+ expect(first?.runs[0].logicalAgentId).toBe('pi-child-54');+ expect(first?.nextCursor).toBeTruthy();+ const second = await listSubagentRuns('session-1', { cursor: first?.nextCursor });+ expect(second?.runs).toHaveLength(5);+ expect(second?.runs.at(-1)?.logicalAgentId).toBe('pi-child-0');+ expect(second?.nextCursor).toBeUndefined();+ });++ it('filters rewound or missing parents before applying the page limit', async () => {+ const visible = await persistSubagentTaskUpdate('session-1', observed({+ provider: 'pi',+ taskId: 'visible-older-run',+ status: 'completed',+ updatedAt: '1970-01-01T00:00:01.000Z',+ }));+ for (let index = 0; index < 50; index += 1) {+ await persistSubagentTaskUpdate('session-1', observed({+ provider: 'claude-code',+ taskId: `hidden-run-${index}`,+ parentToolUseId: `missing-parent-${index}`,+ status: 'completed',+ updatedAt: new Date(2_000 + index).toISOString(),+ }));+ }++ const first = await listSubagentRuns('session-1');+ expect(first?.runs.map((run) => run.id)).toEqual([visible!.runId]);+ expect(first?.nextCursor).toBeUndefined();+ });++ function insertMessage(+ id: string,+ role: 'tool_use' | 'tool_result',+ content: string,+ toolUseId: string,+ createdAt: number,+ ): void {+ rawDb+ .prepare(+ 'INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',+ )+ .run(id, id, 'session-1', role, content, toolUseId, createdAt);+ }++ function observed(+ data: Record<string, unknown>,+ options: {+ kind?: 'spawn' | 'progress' | 'terminal';+ logicalSubagentId?: string;+ parentToolUseId?: string;+ providerRunIds?: string[];+ } = {},+ ): Record<string, unknown> {+ const logicalSubagentId =+ options.logicalSubagentId ?? (typeof data.taskId === 'string' ? data.taskId : 'subagent');+ const parentToolUseId =+ options.parentToolUseId ??+ (typeof data.parentToolUseId === 'string' ? data.parentToolUseId : undefined);+ return {+ ...data,+ subagentObservation: {+ kind: options.kind ?? 'spawn',+ logicalSubagentId,+ ...(parentToolUseId ? { parentToolUseId } : {}),+ ...(options.providerRunIds ? { providerRunIds: options.providerRunIds } : {}),+ },+ };+ }+});diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.tsindex 81417d874d..42d3c4a2bf 100644--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts@@ -419,10 +419,29 @@ function messageDelete(readyDb, args) {const markerContent = expectString(marker.content, 'contextMarker.content');const markerCreatedAt = expectNumber(marker.createdAt, 'contextMarker.createdAt');const updatedAt = expectNumber(payload.updatedAt, 'updatedAt');+ const rawSubagentTurnWindow = payload.subagentTurnWindow;+ const subagentTurnWindow = rawSubagentTurnWindow === undefined+ ? null+ : (() => {+ const window = asRecord(rawSubagentTurnWindow, 'subagentTurnWindow');+ const startedAtInclusive = expectNumber(window.startedAtInclusive, 'subagentTurnWindow.startedAtInclusive');+ const startedAtExclusive = window.startedAtExclusive === undefined+ ? undefined+ : expectNumber(window.startedAtExclusive, 'subagentTurnWindow.startedAtExclusive');+ if (+ !Number.isSafeInteger(startedAtInclusive)+ || startedAtInclusive < 0+ || (startedAtExclusive !== undefined+ && (!Number.isSafeInteger(startedAtExclusive) || startedAtExclusive < 0))+ ) {+ throw invalidArgs('subagentTurnWindow must contain non-negative integer timestamps');+ }+ return { startedAtInclusive, startedAtExclusive };+ })();return readyDb.transaction(() => {const selectTarget = readyDb.prepare(- "SELECT id, client_id AS clientId FROM messages WHERE session_id = ? AND client_id = ? AND role IN ('user', 'assistant', 'tool_use', 'tool_result', 'ask_user', 'plan_review', 'thinking', 'error') AND rewind_at IS NULL LIMIT 1",+ "SELECT id, client_id AS clientId, tool_use_id AS toolUseId FROM messages WHERE session_id = ? AND client_id = ? AND role IN ('user', 'assistant', 'tool_use', 'tool_result', 'ask_user', 'plan_review', 'thinking', 'error') AND rewind_at IS NULL LIMIT 1",);const targets = clientIds.map((clientId) => {const target = selectTarget.get(sessionId, clientId);@@ -456,6 +475,44 @@ function messageDelete(readyDb, args) {readyDb.prepare("DELETE FROM embedding_jobs WHERE source = 'chat' AND source_id = ?").run(target.id);}+ const subagentRunIds = new Set();+ const hasSubagentRuns = Boolean(+ readyDb.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'subagent_runs'").get(),+ );+ if (hasSubagentRuns) {+ const selectLinkedSubagents = readyDb.prepare(+ 'SELECT id FROM subagent_runs WHERE session_id = ? AND parent_tool_use_id = ? AND rewind_at IS NULL AND deleted_at IS NULL',+ );+ const parentToolUseIds = new Set(+ targets.flatMap((target) => target.toolUseId ? [target.toolUseId] : []),+ );+ for (const toolUseId of parentToolUseIds) {+ const linkedRows = selectLinkedSubagents.all(sessionId, toolUseId);+ for (const row of linkedRows) subagentRunIds.add(row.id);+ }+ if (subagentTurnWindow) {+ const parentlessRows = subagentTurnWindow.startedAtExclusive === undefined+ ? readyDb.prepare(+ 'SELECT id FROM subagent_runs WHERE session_id = ? AND parent_tool_use_id IS NULL AND rewind_at IS NULL AND deleted_at IS NULL AND started_at >= ?',+ ).all(sessionId, subagentTurnWindow.startedAtInclusive)+ : readyDb.prepare(+ 'SELECT id FROM subagent_runs WHERE session_id = ? AND parent_tool_use_id IS NULL AND rewind_at IS NULL AND deleted_at IS NULL AND started_at >= ? AND started_at < ?',+ ).all(sessionId, subagentTurnWindow.startedAtInclusive, subagentTurnWindow.startedAtExclusive);+ for (const row of parentlessRows) subagentRunIds.add(row.id);+ }+ const scrubSubagent = readyDb.prepare(+ "UPDATE subagent_runs SET title = NULL, description = NULL, summary = NULL, activity = '[]', updated_at = MAX(updated_at, ?), deleted_at = ? WHERE id = ? AND session_id = ? AND rewind_at IS NULL AND deleted_at IS NULL",+ );+ for (const runId of subagentRunIds) {+ const scrubbed = scrubSubagent.run(updatedAt, updatedAt, runId, sessionId);+ if (scrubbed.changes !== 1) {+ throw Object.assign(new Error('Subagent 删除竞态: ' + runId), {+ code: 'PRECONDITION_FAILED',+ });+ }+ }+ }+readyDb.prepare("DELETE FROM messages WHERE role = 'context_rebuild' AND session_id = ?").run(sessionId);// 保留不含正文/元数据的最小 tombstone,阻止外部 Claude/Codex transcript// importer 下次 messages:list 时把同一 clientId 重新导入;本地有效记录中@@ -485,6 +542,7 @@ function messageDelete(readyDb, args) {messageId: target.id,clientId: target.clientId,})),+ subagentRunIds: [...subagentRunIds].sort(),};})();}@@ -978,7 +1036,7 @@ function rewindCommit(readyDb, args) {const requireLatestUser = payload.requireLatestUser === true;const now = expectNumber(payload.now, 'now');const rows = readyDb.prepare(- 'SELECT id, client_id, role, created_at, agent_meta FROM messages WHERE session_id = ? AND rewind_at IS NULL',+ 'SELECT id, client_id, role, created_at, agent_meta, tool_use_id FROM messages WHERE session_id = ? AND rewind_at IS NULL',).all(sessionId);// edit-last-message 原子守卫(与 worker/opHandlers/tx.ts 镜像同步):软删同一// 临界区内断言 target 之后没有更新的可见 user 消息,命中 → 抛错,软删不发生。@@ -1002,8 +1060,29 @@ function rewindCommit(readyDb, args) {preserveMessageUuid,});const updateMessage = readyDb.prepare('UPDATE messages SET rewind_at = ? WHERE id = ?');+ const hasSubagentRuns = Boolean(+ readyDb.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'subagent_runs'").get(),+ );+ const rewindSubagentByParent = hasSubagentRuns+ ? readyDb.prepare('UPDATE subagent_runs SET rewind_at = ? WHERE session_id = ? AND rewind_at IS NULL AND parent_tool_use_id = ?')+ : null;+ const rewindParentlessSubagentTail = hasSubagentRuns+ ? readyDb.prepare('UPDATE subagent_runs SET rewind_at = ? WHERE session_id = ? AND rewind_at IS NULL AND parent_tool_use_id IS NULL AND started_at >= ?')+ : null;readyDb.transaction(() => {for (const id of idsToRewind) updateMessage.run(now, id);+ if (rewindSubagentByParent && rewindParentlessSubagentTail) {+ const rewoundIds = new Set(idsToRewind);+ const parentToolUseIds = new Set(+ rows.flatMap((row) => rewoundIds.has(row.id) && row.tool_use_id ? [row.tool_use_id] : []),+ );+ for (const toolUseId of parentToolUseIds) {+ rewindSubagentByParent.run(now, sessionId, toolUseId);+ }+ // Mirror worker/opHandlers/tx.ts: parentless same-ms rows are ambiguous,+ // so fail closed rather than expose work from a withdrawn branch.+ rewindParentlessSubagentTail.run(now, sessionId, targetCreatedAt);+ }if (sdkSessionId) {readyDb.prepare('UPDATE sessions SET user_send_at = ?, updated_at = ?, context_tokens = 0, context_window = 0, sdk_session_id = ? WHERE id = ?').run(now, now, sdkSessionId, sessionId);} else {diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.tsindex 8c67d4b0c9..00e0e00f9a 100644--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts@@ -91,6 +91,22 @@ CREATE TABLE messages (rewind_at INTEGER,UNIQUE(session_id, client_id));+CREATE TABLE subagent_runs (+ id TEXT PRIMARY KEY,+ session_id TEXT NOT NULL,+ provider TEXT NOT NULL DEFAULT 'claude-code',+ logical_agent_id TEXT NOT NULL DEFAULT '',+ parent_tool_use_id TEXT,+ status TEXT NOT NULL DEFAULT 'running',+ title TEXT,+ description TEXT,+ summary TEXT,+ activity TEXT NOT NULL DEFAULT '[]',+ started_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL DEFAULT 0,+ rewind_at INTEGER,+ deleted_at INTEGER+);CREATE TABLE im_bindings (channel TEXT NOT NULL,bot_context_id TEXT NOT NULL,@@ -533,6 +549,101 @@ describe('db worker tx handlers', () => {});});+ it.each([false, true])(+ 'rewind.commit hides linked and parentless Subagent tail rows across providers atomically (inline=%s)',+ async (useInlineWorker) => {+ await withClient(+ async (client) => {+ await seedSession(client, 's1');+ await client.exec(+ `INSERT INTO messages+ (id, client_id, session_id, role, content, tool_use_id, created_at)+ VALUES (?, ?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?, ?)`,+ [+ 'before',+ 'before-client',+ 's1',+ 'user',+ 'before',+ null,+ 100,+ 'target',+ 'target-client',+ 's1',+ 'tool_use',+ '{}',+ 'spawn-tool',+ 200,+ ],+ );+ await client.exec(+ `INSERT INTO subagent_runs+ (id, session_id, provider, parent_tool_use_id, started_at, rewind_at)+ VALUES+ (?, ?, ?, ?, ?, NULL),+ (?, ?, ?, ?, ?, NULL),+ (?, ?, ?, ?, ?, NULL),+ (?, ?, ?, ?, ?, NULL),+ (?, ?, ?, ?, ?, NULL),+ (?, ?, ?, ?, ?, NULL)`,+ [+ 'linked',+ 's1',+ 'pi',+ 'spawn-tool',+ 50,+ 'orphan-before',+ 's1',+ 'claude-code',+ null,+ 100,+ 'orphan-same-ms-claude',+ 's1',+ 'claude-code',+ null,+ 200,+ 'orphan-same-ms-codex',+ 's1',+ 'codex',+ null,+ 200,+ 'orphan-after-pi',+ 's1',+ 'pi',+ null,+ 201,+ 'orphan-after-codex',+ 's1',+ 'codex',+ null,+ 202,+ ],+ );++ await client.tx('rewind.commit', {+ sessionId: 's1',+ targetCreatedAt: 200,+ targetMessageId: 'target',+ targetClientId: 'target-client',+ now: 999,+ });++ await expect(+ client.query('SELECT id, rewind_at FROM subagent_runs ORDER BY id'),+ ).resolves.toEqual([+ { id: 'linked', rewind_at: 999 },+ { id: 'orphan-after-codex', rewind_at: 999 },+ { id: 'orphan-after-pi', rewind_at: 999 },+ { id: 'orphan-before', rewind_at: null },+ { id: 'orphan-same-ms-claude', rewind_at: 999 },+ { id: 'orphan-same-ms-codex', rewind_at: 999 },+ ]);+ },+ { useInlineWorker },+ );+ },+ );+it('session.treeRehydrate atomically replaces the visible projection and preserves old branches', async () => {await withClient(async (client) => {await seedSession(client, 's1', { contextTokens: 999, clearedAt: 50 });@@ -1212,8 +1323,10 @@ describe('db worker tx handlers', () => {});});- it('message.delete scrubs the selected AI round and invalidates native context atomically', async () => {- await withClient(async (client) => {+ it.each([false, true])(+ 'message.delete scrubs the selected AI round and parentless Subagents across providers atomically (inline=%s)',+ async (useInlineWorker) => {+ await withClient(async (client) => {await seedSession(client, 's1');await client.exec('UPDATE sessions SET sdk_session_id = ? WHERE id = ?', ['old-native',@@ -1240,11 +1353,86 @@ describe('db worker tx handlers', () => {job.lastInsertRowid,Buffer.from([1, 2, 3]),]);+ await client.exec('UPDATE messages SET tool_use_id = ? WHERE id = ?', [+ 'spawn-tool',+ 'tool',+ ]);+ await client.exec(+ `INSERT INTO subagent_runs+ (id, session_id, provider, logical_agent_id, parent_tool_use_id, title, description, summary, activity, started_at, updated_at)+ VALUES+ (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?),+ (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?),+ (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?),+ (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?),+ (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ [+ 'linked',+ 's1',+ 'pi',+ 'linked-task',+ 'spawn-tool',+ 'linked title',+ 'linked prompt',+ 'linked result',+ '[{"sequence":1,"summary":"linked activity"}]',+ 50,+ 60,+ 'parentless-claude',+ 's1',+ 'claude-code',+ 'claude-task',+ null,+ 'claude title',+ 'claude prompt',+ 'claude result',+ '[{"sequence":1,"summary":"claude activity"}]',+ 210,+ 220,+ 'next-claude',+ 's1',+ 'claude-code',+ 'next-task',+ null,+ 'next title',+ 'next prompt',+ 'next result',+ '[{"sequence":1,"summary":"next activity"}]',+ 300,+ 310,+ 'parentless-codex',+ 's1',+ 'codex',+ 'codex-task',+ null,+ 'codex title',+ 'codex prompt',+ 'codex result',+ '[{"sequence":1,"summary":"codex activity"}]',+ 220,+ 230,+ 'parentless-pi',+ 's1',+ 'pi',+ 'pi-task',+ null,+ 'pi title',+ 'pi prompt',+ 'pi result',+ '[{"sequence":1,"summary":"pi activity"}]',+ 230,+ 240,+ ],+ );await expect(client.tx('message.delete', {sessionId: 's1',clientIds: ['target', 'thinking', 'auto-resume', 'tool'],+ subagentTurnWindow: {+ startedAtInclusive: 100,+ startedAtExclusive: 300,+ },contextMarker: {id: 'ctx-id',clientId: 'ctx-client',@@ -1260,6 +1448,7 @@ describe('db worker tx handlers', () => {{ messageId: 'auto-resume', clientId: 'auto-resume' },{ messageId: 'tool', clientId: 'tool' },],+ subagentRunIds: ['linked', 'parentless-claude', 'parentless-codex', 'parentless-pi'],});await expect(@@ -1319,8 +1508,55 @@ describe('db worker tx handlers', () => {client.query('SELECT rowid FROM embedding_jobs WHERE source_id = ?', ['target']),).resolves.toEqual([]);await expect(client.query('SELECT rowid FROM chat_vec')).resolves.toEqual([]);- });- });+ await expect(+ client.query(+ 'SELECT id, title, description, summary, activity, deleted_at FROM subagent_runs ORDER BY id',+ ),+ ).resolves.toEqual([+ {+ id: 'linked',+ title: null,+ description: null,+ summary: null,+ activity: '[]',+ deleted_at: 500,+ },+ {+ id: 'next-claude',+ title: 'next title',+ description: 'next prompt',+ summary: 'next result',+ activity: '[{"sequence":1,"summary":"next activity"}]',+ deleted_at: null,+ },+ {+ id: 'parentless-claude',+ title: null,+ description: null,+ summary: null,+ activity: '[]',+ deleted_at: 500,+ },+ {+ id: 'parentless-codex',+ title: null,+ description: null,+ summary: null,+ activity: '[]',+ deleted_at: 500,+ },+ {+ id: 'parentless-pi',+ title: null,+ description: null,+ summary: null,+ activity: '[]',+ deleted_at: 500,+ },+ ]);+ }, { useInlineWorker });+ },+ );it('message.delete rejects non-deletable rows without clearing the sdk binding', async () => {await withClient(async (client) => {diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex 9ca6308231..848b8d8458 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -296,6 +296,15 @@ export interface SessionAgentSwitchFallbackArgs {export interface MessageDeleteArgs {sessionId: string;clientIds: string[];+ /**+ * Parentless Claude observations cannot be joined to a tool message. For an+ * assistant-round deletion, the caller supplies the surrounding real-user+ * time boundaries so the same transaction can retire those durable copies.+ */+ subagentTurnWindow?: {+ startedAtInclusive: number;+ startedAtExclusive?: number;+ };contextMarker: {id: string;clientId: string;@@ -310,6 +319,7 @@ export interface MessageDeleteResult {messageId: string;clientId: string;}>;+ subagentRunIds: string[];}export interface SessionsSetStatusResultItem {diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.tsindex ceda5e52c4..786ec0b47b 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts@@ -747,6 +747,10 @@ describe('getMessageDeletionTarget', () => {id: 'progress',role: 'assistant',deletedClientIds: ['progress', 'thinking', 'auto-resume', 'tool', 'final', 'error'],+ subagentTurnWindow: {+ startedAtInclusive: 1_000,+ startedAtExclusive: 1_800,+ },});});@@ -801,6 +805,10 @@ describe('getMessageDeletionTarget', () => {'trigger-legacy-raw','final',],+ subagentTurnWindow: {+ startedAtInclusive: 1_000,+ startedAtExclusive: 1_800,+ },});});@@ -860,6 +868,10 @@ describe('getMessageDeletionTarget', () => {'target',...Array.from({ length: 40 }, (_, index) => `next-trigger-${index}`),]);+ expect(target?.subagentTurnWindow).toEqual({+ startedAtInclusive: 1_000,+ startedAtExclusive: 3_000,+ });});it('keeps a blank real user message as a deletion boundary', async () => {@@ -883,6 +895,9 @@ describe('getMessageDeletionTarget', () => {id: 'target',role: 'assistant',deletedClientIds: ['target'],+ subagentTurnWindow: {+ startedAtInclusive: 1_200,+ },});});diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/rightSidebarTabs.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/rightSidebarTabs.test.tsindex 1db8ce82b1..a2dfbd3276 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/rightSidebarTabs.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/rightSidebarTabs.test.ts@@ -1,6 +1,6 @@/**- * rightSidebarTabs IPC handler unit tests —— 验证 5 个 channel(list / upsert / close /- * setActive / reorder)的正路径 + 关键错误码(RIGHT_SIDEBAR_TOO_MANY_TABS /+ * rightSidebarTabs IPC handler unit tests —— 验证 list / ensure-singleton / upsert / close /+ * setActive / reorder 的正路径 + 关键错误码(RIGHT_SIDEBAR_TOO_MANY_TABS /* RIGHT_SIDEBAR_STATE_TOO_LARGE / NOT_FOUND / INVALID_PARAMS)。规则 14:main 业务必带测。** 用 in-memory better-sqlite3 + drizzle 驱动真 SQL,避免 mock 整套 drizzle 链路。@@ -10,7 +10,7 @@ import Database from 'better-sqlite3';import { drizzle } from 'drizzle-orm/better-sqlite3';import { beforeEach, describe, expect, it, vi } from 'vitest';-import { rightSidebarTabs, sessions } from '../../schema';+import { rightSidebarTabs, sessions } from '../../schema.js';const h = vi.hoisted(() => ({db: null as ReturnType<typeof drizzle> | null,@@ -25,17 +25,18 @@ vi.mock('electron', () => ({},BrowserWindow: { getAllWindows: () => [] },}));-vi.mock('../../../logger', () => ({- createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),-}));vi.mock('../../../logger.js', () => ({createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),}));-vi.mock('../../client/current', () => ({+vi.mock('../../../security/trustedAppRenderer.js', () => ({+ assertTrustedAppRendererEvent: vi.fn(),+}));+vi.mock('../../client/current.js', () => ({getDbClient: () => ({ drizzle: h.db }),}));-import { registerRightSidebarTabsIpc } from '../rightSidebarTabs';+import { registerRightSidebarTabsIpc } from '../rightSidebarTabs.js';+import { assertTrustedAppRendererEvent } from '../../../security/trustedAppRenderer.js';function createDb(): Database.Database {const sqlite = new Database(':memory:');@@ -54,6 +55,8 @@ function createDb(): Database.Database {FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE);CREATE INDEX right_sidebar_tabs_session_idx ON right_sidebar_tabs (session_id, position);+ CREATE UNIQUE INDEX right_sidebar_tabs_subagents_singleton_idx+ ON right_sidebar_tabs (session_id) WHERE kind = 'subagents';`);sqlite.prepare(`INSERT INTO sessions (id) VALUES (?)`).run('s1');sqlite.prepare(`INSERT INTO sessions (id) VALUES (?)`).run('s2');@@ -62,7 +65,14 @@ function createDb(): Database.Database {}interface ListResp {- tabs: Array<{ id: string; sessionId: string; kind: string; position: number; state: unknown; isActive: boolean }>;+ tabs: Array<{+ id: string;+ sessionId: string;+ kind: string;+ position: number;+ state: unknown;+ isActive: boolean;+ }>;activeTabId: string | null;persistable?: boolean;}@@ -75,21 +85,45 @@ async function invoke<T>(channel: string, payload: unknown): Promise<T> {describe('rightSidebarTabs IPC', () => {beforeEach(() => {+ vi.mocked(assertTrustedAppRendererEvent).mockReset();h.handlers.clear();createDb();registerRightSidebarTabsIpc();});+ it('rejects every read and write handler before parsing untrusted payloads', async () => {+ vi.mocked(assertTrustedAppRendererEvent).mockImplementation(() => {+ throw new Error('UNTRUSTED_RENDERER');+ });+ const channels = [+ 'local-db:right-sidebar-tabs:list',+ 'local-db:right-sidebar-tabs:ensure-singleton',+ 'local-db:right-sidebar-tabs:upsert',+ 'local-db:right-sidebar-tabs:close',+ 'local-db:right-sidebar-tabs:setActive',+ 'local-db:right-sidebar-tabs:reorder',+ ];++ for (const channel of channels) {+ await expect(invoke(channel, undefined)).rejects.toThrow('UNTRUSTED_RENDERER');+ }+ expect(assertTrustedAppRendererEvent).toHaveBeenCalledTimes(channels.length);+ });+describe(':list', () => {it('empty session returns empty tabs + null activeTabId', async () => {- const result = await invoke<ListResp>('local-db:right-sidebar-tabs:list', { sessionId: 's1' });+ const result = await invoke<ListResp>('local-db:right-sidebar-tabs:list', {+ sessionId: 's1',+ });expect(result.tabs).toEqual([]);expect(result.activeTabId).toBeNull();expect(result.persistable).toBe(true);});it('unknown session returns a non-persistable empty bucket for remote sessions', async () => {- const result = await invoke<ListResp>('local-db:right-sidebar-tabs:list', { sessionId: 'remote-s1' });+ const result = await invoke<ListResp>('local-db:right-sidebar-tabs:list', {+ sessionId: 'remote-s1',+ });expect(result.tabs).toEqual([]);expect(result.activeTabId).toBeNull();expect(result.persistable).toBe(false);@@ -110,7 +144,9 @@ describe('rightSidebarTabs IPC', () => {position: 0,state: { selectedFilePath: 'a.ts' },});- const result = await invoke<ListResp>('local-db:right-sidebar-tabs:list', { sessionId: 's1' });+ const result = await invoke<ListResp>('local-db:right-sidebar-tabs:list', {+ sessionId: 's1',+ });expect(result.tabs.map((t) => t.id)).toEqual(['t1', 't2']);expect(result.tabs[0].state).toEqual({ selectedFilePath: 'a.ts' });expect(result.tabs[1].state).toEqual({ url: 'https://example.com' });@@ -147,7 +183,9 @@ describe('rightSidebarTabs IPC', () => {position: 0,state: { foo: 'bar' },});- const result = await invoke<ListResp>('local-db:right-sidebar-tabs:list', { sessionId: 's1' });+ const result = await invoke<ListResp>('local-db:right-sidebar-tabs:list', {+ sessionId: 's1',+ });expect(result.tabs).toHaveLength(1);expect(result.tabs[0].state).toEqual({ foo: 'bar' });});@@ -167,7 +205,9 @@ describe('rightSidebarTabs IPC', () => {position: 5,state: { v: 2 },});- const result = await invoke<ListResp>('local-db:right-sidebar-tabs:list', { sessionId: 's1' });+ const result = await invoke<ListResp>('local-db:right-sidebar-tabs:list', {+ sessionId: 's1',+ });expect(result.tabs).toHaveLength(1);expect(result.tabs[0].position).toBe(5);expect(result.tabs[0].state).toEqual({ v: 2 });@@ -216,6 +256,63 @@ describe('rightSidebarTabs IPC', () => {});});+ describe(':ensure-singleton', () => {+ it('rejects an untrusted renderer before accepting persistent state', async () => {+ vi.mocked(assertTrustedAppRendererEvent).mockImplementationOnce(() => {+ throw new Error('UNTRUSTED_RENDERER');+ });++ await expect(+ invoke('local-db:right-sidebar-tabs:ensure-singleton', {+ sessionId: 's1',+ kind: 'subagents',+ state: { selectedRunId: 'must-not-persist' },+ }),+ ).rejects.toThrow('UNTRUSTED_RENDERER');+ const listed = await invoke<ListResp>('local-db:right-sidebar-tabs:list', {+ sessionId: 's1',+ });+ expect(listed.tabs).toEqual([]);+ });++ it('returns one canonical Subagents tab across concurrent callers without activating it', async () => {+ const [first, second] = await Promise.all([+ invoke<{ tab: ListResp['tabs'][number]; created: boolean }>(+ 'local-db:right-sidebar-tabs:ensure-singleton',+ { sessionId: 's1', kind: 'subagents', state: { selectedRunId: null } },+ ),+ invoke<{ tab: ListResp['tabs'][number]; created: boolean }>(+ 'local-db:right-sidebar-tabs:ensure-singleton',+ { sessionId: 's1', kind: 'subagents', state: { selectedRunId: 'ignored-race' } },+ ),+ ]);++ expect(first.tab.id).toBe(second.tab.id);+ expect([first.created, second.created].filter(Boolean)).toHaveLength(1);+ const listed = await invoke<ListResp>('local-db:right-sidebar-tabs:list', {+ sessionId: 's1',+ });+ expect(listed.tabs).toHaveLength(1);+ expect(listed.tabs[0]).toMatchObject({ kind: 'subagents', isActive: false });+ expect(listed.activeTabId).toBeNull();+ });++ it('fails closed for unknown sessions and non-singleton kinds', async () => {+ await expect(+ invoke('local-db:right-sidebar-tabs:ensure-singleton', {+ sessionId: 'remote-s1',+ kind: 'subagents',+ }),+ ).resolves.toMatchObject({ tab: null, persistable: false });+ await expect(+ invoke('local-db:right-sidebar-tabs:ensure-singleton', {+ sessionId: 's1',+ kind: 'web-browser',+ }),+ ).rejects.toThrow(/INVALID_PARAMS/);+ });+ });+describe(':close', () => {it('deletes tab', async () => {await invoke('local-db:right-sidebar-tabs:upsert', {@@ -225,7 +322,9 @@ describe('rightSidebarTabs IPC', () => {position: 0,});await invoke('local-db:right-sidebar-tabs:close', { id: 't1' });- const result = await invoke<ListResp>('local-db:right-sidebar-tabs:list', { sessionId: 's1' });+ const result = await invoke<ListResp>('local-db:right-sidebar-tabs:list', {+ sessionId: 's1',+ });expect(result.tabs).toHaveLength(0);});@@ -266,7 +365,9 @@ describe('rightSidebarTabs IPC', () => {it('id=null clears active', async () => {await invoke('local-db:right-sidebar-tabs:setActive', { sessionId: 's1', id: 't1' });await invoke('local-db:right-sidebar-tabs:setActive', { sessionId: 's1', id: null });- const result = await invoke<ListResp>('local-db:right-sidebar-tabs:list', { sessionId: 's1' });+ const result = await invoke<ListResp>('local-db:right-sidebar-tabs:list', {+ sessionId: 's1',+ });expect(result.activeTabId).toBeNull();expect(result.tabs.filter((t) => t.isActive)).toHaveLength(0);});@@ -280,14 +381,31 @@ describe('rightSidebarTabs IPC', () => {describe(':reorder', () => {it('rewrites positions per orderedIds', async () => {- await invoke('local-db:right-sidebar-tabs:upsert', { id: 'a', sessionId: 's1', kind: 'file-browser', position: 0 });- await invoke('local-db:right-sidebar-tabs:upsert', { id: 'b', sessionId: 's1', kind: 'file-browser', position: 1 });- await invoke('local-db:right-sidebar-tabs:upsert', { id: 'c', sessionId: 's1', kind: 'file-browser', position: 2 });+ await invoke('local-db:right-sidebar-tabs:upsert', {+ id: 'a',+ sessionId: 's1',+ kind: 'file-browser',+ position: 0,+ });+ await invoke('local-db:right-sidebar-tabs:upsert', {+ id: 'b',+ sessionId: 's1',+ kind: 'file-browser',+ position: 1,+ });+ await invoke('local-db:right-sidebar-tabs:upsert', {+ id: 'c',+ sessionId: 's1',+ kind: 'file-browser',+ position: 2,+ });await invoke('local-db:right-sidebar-tabs:reorder', {sessionId: 's1',orderedIds: ['c', 'a', 'b'],});- const result = await invoke<ListResp>('local-db:right-sidebar-tabs:list', { sessionId: 's1' });+ const result = await invoke<ListResp>('local-db:right-sidebar-tabs:list', {+ sessionId: 's1',+ });expect(result.tabs.map((t) => t.id)).toEqual(['c', 'a', 'b']);expect(result.tabs.map((t) => t.position)).toEqual([0, 1, 2]);});@@ -304,9 +422,24 @@ describe('rightSidebarTabs IPC', () => {describe('cross-session isolation', () => {it('reorder one session does not affect another', async () => {- await invoke('local-db:right-sidebar-tabs:upsert', { id: 's1-a', sessionId: 's1', kind: 'file-browser', position: 0 });- await invoke('local-db:right-sidebar-tabs:upsert', { id: 's1-b', sessionId: 's1', kind: 'file-browser', position: 1 });- await invoke('local-db:right-sidebar-tabs:upsert', { id: 's2-a', sessionId: 's2', kind: 'web-browser', position: 0 });+ await invoke('local-db:right-sidebar-tabs:upsert', {+ id: 's1-a',+ sessionId: 's1',+ kind: 'file-browser',+ position: 0,+ });+ await invoke('local-db:right-sidebar-tabs:upsert', {+ id: 's1-b',+ sessionId: 's1',+ kind: 'file-browser',+ position: 1,+ });+ await invoke('local-db:right-sidebar-tabs:upsert', {+ id: 's2-a',+ sessionId: 's2',+ kind: 'web-browser',+ position: 0,+ });await invoke('local-db:right-sidebar-tabs:reorder', {sessionId: 's1',orderedIds: ['s1-b', 's1-a'],diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/subagentRunsBroadcast.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/subagentRunsBroadcast.test.tsnew file mode 100644index 0000000000..f901c215bf--- /dev/null+++ b/apps/desktop/src/main/localDb/ipc/__tests__/subagentRunsBroadcast.test.ts@@ -0,0 +1,167 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const h = vi.hoisted(() => {+ const trusted = {+ isDestroyed: vi.fn(() => false),+ webContents: { send: vi.fn() },+ };+ const navigated = {+ isDestroyed: vi.fn(() => false),+ webContents: { send: vi.fn() },+ };+ const destroyed = {+ isDestroyed: vi.fn(() => true),+ webContents: { send: vi.fn() },+ };+ return {+ trusted,+ navigated,+ destroyed,+ ipcHandlers: new Map<string, (event: unknown, payload: unknown) => unknown>(),+ getSubagentRunDetail: vi.fn(),+ listSubagentRuns: vi.fn(),+ scopeCurrent: true,+ activeStamp: { dataOwnerId: 'active-owner', ownerGeneration: 2 },+ };+});++vi.mock('electron', () => ({+ BrowserWindow: {+ getAllWindows: () => [h.trusted, h.navigated, h.destroyed],+ },+ ipcMain: {+ handle: vi.fn((channel: string, handler: (event: unknown, payload: unknown) => unknown) => {+ h.ipcHandlers.set(channel, handler);+ }),+ },+}));+vi.mock('../../../appSessionState.js', () => ({+ getActiveDataOwnerPushStamp: () => h.activeStamp,+}));+vi.mock('../../../device-link/broadcast-tap.js', () => ({+ isDataOwnerBroadcastScopeCurrent: () => h.scopeCurrent,+}));+vi.mock('../../../security/trustedAppRenderer.js', () => ({+ assertTrustedAppRendererEvent: vi.fn(),+ isTrustedAppRendererWindow: (window: unknown) => window === h.trusted,+}));+vi.mock('../../client/current.js', () => ({+ getDbClient: vi.fn(),+}));+vi.mock('../../subagentRuns.js', () => ({+ getSubagentRunDetail: h.getSubagentRunDetail,+ listSubagentRuns: h.listSubagentRuns,+}));++import { SUBAGENT_RUNS_CHANGED_CHANNEL } from '@cindy/maker-shared/subagent-workspace';+import {+ broadcastSubagentRunsChanged,+ broadcastSubagentRunsInvalidated,+ registerSubagentRunsIpc,+} from '../subagentRuns.js';++describe('Subagent runs broadcast boundary', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ h.ipcHandlers.clear();+ h.getSubagentRunDetail.mockResolvedValue(null);+ h.listSubagentRuns.mockResolvedValue({ runs: [] });+ h.scopeCurrent = true;+ });++ it('sends only to a currently trusted Cindy renderer window', () => {+ const payload = {+ sessionId: 'session-1',+ runId: 'run-1',+ created: true,+ firstForSession: true,+ };++ broadcastSubagentRunsChanged(payload);++ expect(h.trusted.webContents.send).toHaveBeenCalledWith(+ SUBAGENT_RUNS_CHANGED_CHANNEL,+ payload,+ h.activeStamp,+ );+ expect(h.navigated.webContents.send).not.toHaveBeenCalled();+ expect(h.destroyed.webContents.send).not.toHaveBeenCalled();+ });++ it('drops a late old-owner broadcast instead of relabeling it', () => {+ h.scopeCurrent = false;++ broadcastSubagentRunsChanged(+ { sessionId: 'session-1', runId: 'run-1', created: false, firstForSession: false },+ {+ ownerScopeKey: 'old-owner',+ ownerStamp: { dataOwnerId: 'old-owner', ownerGeneration: 1 },+ },+ );++ expect(h.trusted.webContents.send).not.toHaveBeenCalled();+ });++ it('uses the captured owner stamp when the scope is still current', () => {+ const captured = { dataOwnerId: 'captured-owner', ownerGeneration: 7 };+ const payload = {+ sessionId: 'session-1',+ runId: 'run-1',+ created: false,+ firstForSession: false,+ };++ broadcastSubagentRunsChanged(payload, {+ ownerScopeKey: 'captured-owner',+ ownerStamp: captured,+ });++ expect(h.trusted.webContents.send).toHaveBeenCalledWith(+ SUBAGENT_RUNS_CHANGED_CHANNEL,+ payload,+ captured,+ );+ });++ it('broadcasts a session-level invalidation for clear and rewind boundaries', () => {+ broadcastSubagentRunsInvalidated('session-1');++ expect(h.trusted.webContents.send).toHaveBeenCalledWith(+ SUBAGENT_RUNS_CHANGED_CHANNEL,+ {+ sessionId: 'session-1',+ runId: null,+ created: false,+ firstForSession: false,+ },+ h.activeStamp,+ );+ });++ it('validates and forwards provider-scoped detail lookups', async () => {+ registerSubagentRunsIpc();+ const detail = h.ipcHandlers.get('local-db:subagent-runs:detail');+ if (!detail) throw new Error('Subagent detail handler not registered');++ await expect(+ detail({}, {+ sessionId: 'session-1',+ provider: 'codex',+ runIdOrAlias: 'shared-native-id',+ }),+ ).resolves.toEqual({ supported: true, run: null });+ expect(h.getSubagentRunDetail).toHaveBeenCalledWith(+ 'session-1',+ 'codex',+ 'shared-native-id',+ );++ await expect(+ detail({}, {+ sessionId: 'session-1',+ provider: 'other-harness',+ runIdOrAlias: 'shared-native-id',+ }),+ ).rejects.toThrow(/provider/);+ });+});diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.tsindex d62c865619..2c60855fe3 100644--- a/apps/desktop/src/main/localDb/ipc/messages.ts+++ b/apps/desktop/src/main/localDb/ipc/messages.ts@@ -664,6 +664,19 @@ const AI_TURN_DELETION_ROLES = new Set(['error',]);+export interface SubagentTurnDeletionWindow {+ startedAtInclusive: number;+ startedAtExclusive?: number;+}++export interface MessageDeletionTarget {+ id: string;+ role: 'user' | 'assistant';+ deletedClientIds: string[];+ /** Present only when deleting an assistant round. */+ subagentTurnWindow?: SubagentTurnDeletionWindow;+}+/*** 消息菜单删除前解析本次动作的完整范围。user 仍只删除自己;assistant 以相邻* 真实 user 行为边界,返回整轮 AI 产出,并跳过 autoResume 这类隐藏 user 行。@@ -672,11 +685,7 @@ const AI_TURN_DELETION_ROLES = new Set([export async function getMessageDeletionTarget(sessionId: string,clientId: string,-): Promise<{- id: string;- role: 'user' | 'assistant';- deletedClientIds: string[];-} | null> {+): Promise<MessageDeletionTarget | null> {const db = getDbClient().drizzle;const [session] = await db.select({ clearedAt: sessions.clearedAt })@@ -811,7 +820,15 @@ export async function getMessageDeletionTarget(return [];});if (!deletedClientIds.includes(clientId)) return null;- return { id: row.id, role: row.role, deletedClientIds };+ return {+ id: row.id,+ role: row.role,+ deletedClientIds,+ subagentTurnWindow: {+ startedAtInclusive: priorUser?.createdAt ?? session.clearedAt ?? 0,+ ...(nextUser ? { startedAtExclusive: nextUser.createdAt } : {}),+ },+ };}/**@@ -824,9 +841,11 @@ export async function commitMessageDeletion(sessionId: string,clientIds: string[],handoff: string,+ subagentTurnWindow?: SubagentTurnDeletionWindow,): Promise<{sessionId: string;deletedClientIds: string[];+ subagentRunIds: string[];updatedAt: number;preview: string | null;}> {@@ -835,6 +854,7 @@ export async function commitMessageDeletion(const result = await getDbClient().tx('message.delete', {sessionId,clientIds,+ ...(subagentTurnWindow ? { subagentTurnWindow } : {}),contextMarker: {id: createId(),clientId: `context-rebuild:${createId()}`,@@ -920,6 +940,7 @@ export async function commitMessageDeletion(return {sessionId,deletedClientIds: result.messages.map((message) => message.clientId),+ subagentRunIds: result.subagentRunIds,updatedAt: now,preview,};diff --git a/apps/desktop/src/main/localDb/ipc/registerAll.ts b/apps/desktop/src/main/localDb/ipc/registerAll.tsindex 1fac29bece..2d2ce9b135 100644--- a/apps/desktop/src/main/localDb/ipc/registerAll.ts+++ b/apps/desktop/src/main/localDb/ipc/registerAll.ts@@ -19,6 +19,7 @@ import { registerSessionShareIpc } from './session-share';import { registerRecentWorkdirsIpc } from './recentWorkdirs';import { registerProjectAliasesIpc } from './projectAliases';import { registerRightSidebarTabsIpc } from './rightSidebarTabs';+import { registerSubagentRunsIpc } from './subagentRuns';import { registerDevSqliteVecIpc } from './dev/sqliteVec';import { registerSearchIpc } from './search';import { registerRemoteHistoryIpc } from './history';@@ -130,6 +131,7 @@ export function registerLocalDbIpc(opts: RegisterLocalDbIpcOpts = {}): void {registerRecentWorkdirsIpc();registerProjectAliasesIpc();registerRightSidebarTabsIpc();+ registerSubagentRunsIpc();registerSearchIpc();registerDevSqliteVecIpc();}diff --git a/apps/desktop/src/main/localDb/ipc/rightSidebarTabs.ts b/apps/desktop/src/main/localDb/ipc/rightSidebarTabs.tsindex c30861b467..1478f5ad90 100644--- a/apps/desktop/src/main/localDb/ipc/rightSidebarTabs.ts+++ b/apps/desktop/src/main/localDb/ipc/rightSidebarTabs.ts@@ -1,8 +1,9 @@/*** 右侧栏 Tab 持久化 IPC —— per-session 的多 Tab 容器(对标 Codex in-app browser sidebar)。*- * 5 个 channel(全部 `local-db:right-sidebar-tabs:*`):+ * 6 个 channel(全部 `local-db:right-sidebar-tabs:*`):* - `:list` 按 session 拉 tab 列表 + activeTabId+ * - `:ensure-singleton` 原子创建/读取声明为单例的 tab kind* - `:upsert` 新增 / 更新单个 tab(state JSON / position 等)* - `:close` 删除单个 tab* - `:setActive` 切换激活 tab(先清同 session 旧 active 再设新 active)@@ -20,16 +21,14 @@*/import { ipcMain } from 'electron';+import { createId } from '@paralleldrive/cuid2';import { and, asc, eq } from 'drizzle-orm';-import { getDbClient } from '../client/current';-import { rightSidebarTabs, sessions } from '../schema';-import {- requireObject,- requireString,- throwIpcError,-} from '../../utils/ipcValidate';-import { createLogger } from '../../logger';+import { getDbClient } from '../client/current.js';+import { rightSidebarTabs, sessions } from '../schema.js';+import { assertTrustedAppRendererEvent } from '../../security/trustedAppRenderer.js';+import { requireObject, requireString, throwIpcError } from '../../utils/ipcValidate.js';+import { createLogger } from '../../logger.js';const log = createLogger('rightSidebarTabs');@@ -39,6 +38,7 @@ const MAX_TABS_PER_SESSION = 20;16KB 已远超浏览器 tab(url + title + favicon URL ~400B)/ 文件 tab(~500B)实际需要,够防 plugin 误塞 dataURL / 大对象。 */const MAX_STATE_JSON_BYTES = 16 * 1024;+const SINGLETON_TAB_KINDS = new Set(['subagents']);export interface TabRow {id: string;@@ -95,7 +95,8 @@ function serializeState(value: unknown): string {}export function registerRightSidebarTabsIpc(): void {- ipcMain.handle('local-db:right-sidebar-tabs:list', async (_e, payload: unknown) => {+ ipcMain.handle('local-db:right-sidebar-tabs:list', async (event, payload: unknown) => {+ assertTrustedAppRendererEvent(event);const obj = requireObject(payload, 'list payload');const sessionId = requireString(obj.sessionId, 'sessionId');const db = getDbClient().drizzle;@@ -124,9 +125,78 @@ export function registerRightSidebarTabsIpc(): void {};});+ // Renderer caches are per window, so find-then-add there cannot enforce a+ // singleton while attached/detached hosts overlap. The partial unique index+ // is the authority; INSERT OR IGNORE + re-read returns one canonical row to+ // every caller without changing the user's active tab.+ ipcMain.handle('local-db:right-sidebar-tabs:ensure-singleton', async (event, payload: unknown) => {+ assertTrustedAppRendererEvent(event);+ const obj = requireObject(payload, 'ensure singleton payload');+ const sessionId = requireString(obj.sessionId, 'sessionId');+ const kind = requireString(obj.kind, 'kind');+ if (!SINGLETON_TAB_KINDS.has(kind)) {+ throwIpcError('INVALID_PARAMS', `${kind} is not a singleton tab kind`);+ }+ const stateJson = serializeState(obj.state);+ const db = getDbClient().drizzle;+ const sessionExists = await db+ .select({ id: sessions.id })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ if (sessionExists.length === 0) {+ return { tab: null, created: false, persistable: false };+ }+ const [existing] = await db+ .select()+ .from(rightSidebarTabs)+ .where(and(eq(rightSidebarTabs.sessionId, sessionId), eq(rightSidebarTabs.kind, kind)))+ .limit(1);+ if (existing) {+ return { tab: rowToTab(existing), created: false, persistable: true };+ }+ const current = await db+ .select({ id: rightSidebarTabs.id })+ .from(rightSidebarTabs)+ .where(eq(rightSidebarTabs.sessionId, sessionId));+ if (current.length >= MAX_TABS_PER_SESSION) {+ throwIpcError(+ 'RIGHT_SIDEBAR_TOO_MANY_TABS',+ `session ${sessionId} already has ${MAX_TABS_PER_SESSION} tabs (limit reached)`,+ );+ }+ const now = Date.now();+ const id = `t_${createId()}`;+ await db+ .insert(rightSidebarTabs)+ .values({+ id,+ sessionId,+ kind,+ position: current.length,+ state: stateJson,+ isActive: false,+ createdAt: now,+ updatedAt: now,+ })+ .onConflictDoNothing();+ const [canonical] = await db+ .select()+ .from(rightSidebarTabs)+ .where(and(eq(rightSidebarTabs.sessionId, sessionId), eq(rightSidebarTabs.kind, kind)))+ .limit(1);+ if (!canonical) throw new Error(`failed to ensure ${kind} tab for session ${sessionId}`);+ return {+ tab: rowToTab(canonical),+ created: canonical.id === id,+ persistable: true,+ };+ });+// upsert: 新增或更新 tab(state / position / kind)。kind 不变(新 tab 注册时定),// 但接口允许传以保持 IPC 形态对称(renderer 拿到 unknown kind 时可以 fallback)。- ipcMain.handle('local-db:right-sidebar-tabs:upsert', async (_e, payload: unknown) => {+ ipcMain.handle('local-db:right-sidebar-tabs:upsert', async (event, payload: unknown) => {+ assertTrustedAppRendererEvent(event);const obj = requireObject(payload, 'upsert payload');const id = requireString(obj.id, 'id');const sessionId = requireString(obj.sessionId, 'sessionId');@@ -166,7 +236,8 @@ export function registerRightSidebarTabsIpc(): void {return { ok: true };});- ipcMain.handle('local-db:right-sidebar-tabs:close', async (_e, payload: unknown) => {+ ipcMain.handle('local-db:right-sidebar-tabs:close', async (event, payload: unknown) => {+ assertTrustedAppRendererEvent(event);const obj = requireObject(payload, 'close payload');const id = requireString(obj.id, 'id');const db = getDbClient().drizzle;@@ -187,7 +258,8 @@ export function registerRightSidebarTabsIpc(): void {// setActive: 先把 session 内所有 tab 设 inactive,再设 target 为 active(targetId=null// 表示无激活态,close last tab 时使用)。两步操作不在事务里 —— 单 session 内 tab 数 ≤ 20,// 失败概率极低;真出现中间态 next list 时 UI 会展示"无激活 tab",用户重新点一下就好。- ipcMain.handle('local-db:right-sidebar-tabs:setActive', async (_e, payload: unknown) => {+ ipcMain.handle('local-db:right-sidebar-tabs:setActive', async (event, payload: unknown) => {+ assertTrustedAppRendererEvent(event);const obj = requireObject(payload, 'setActive payload');const sessionId = requireString(obj.sessionId, 'sessionId');const targetId = obj.id === null ? null : requireString(obj.id, 'id');@@ -205,9 +277,7 @@ export function registerRightSidebarTabsIpc(): void {const exists = await db.select({ id: rightSidebarTabs.id }).from(rightSidebarTabs)- .where(- and(eq(rightSidebarTabs.id, targetId), eq(rightSidebarTabs.sessionId, sessionId)),- )+ .where(and(eq(rightSidebarTabs.id, targetId), eq(rightSidebarTabs.sessionId, sessionId))).limit(1);if (exists.length === 0) {throwIpcError('NOT_FOUND', `tab ${targetId} not found in session ${sessionId}`);@@ -215,16 +285,15 @@ export function registerRightSidebarTabsIpc(): void {await db.update(rightSidebarTabs).set({ isActive: true, updatedAt: now })- .where(- and(eq(rightSidebarTabs.id, targetId), eq(rightSidebarTabs.sessionId, sessionId)),- );+ .where(and(eq(rightSidebarTabs.id, targetId), eq(rightSidebarTabs.sessionId, sessionId)));}return { ok: true };});// reorder: 一次性重写 same session 内全部 tab 的 position;orderedIds 数组下标 = 新 position。// 数组里漏的 id 不会被改动 —— renderer 端调用时应该传完整 orderedIds(同 session 当前全部 tab id)。- ipcMain.handle('local-db:right-sidebar-tabs:reorder', async (_e, payload: unknown) => {+ ipcMain.handle('local-db:right-sidebar-tabs:reorder', async (event, payload: unknown) => {+ assertTrustedAppRendererEvent(event);const obj = requireObject(payload, 'reorder payload');const sessionId = requireString(obj.sessionId, 'sessionId');if (!Array.isArray(obj.orderedIds)) {@@ -243,10 +312,7 @@ export function registerRightSidebarTabsIpc(): void {.update(rightSidebarTabs).set({ position: i, updatedAt: now }).where(- and(- eq(rightSidebarTabs.id, orderedIds[i]),- eq(rightSidebarTabs.sessionId, sessionId),- ),+ and(eq(rightSidebarTabs.id, orderedIds[i]), eq(rightSidebarTabs.sessionId, sessionId)),);}return { ok: true };diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 7f1f7cd569..e4efe5253c 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -56,6 +56,7 @@ import {} from './messages';import { assertTrustedAppRendererEvent } from '../../security/trustedAppRenderer.js';import { removeTurnChangeSetsForSession } from '../../turn-change-set/store.js';+import { broadcastSubagentRunsInvalidated } from './subagentRuns.js';const log = createLogger('sessions');const REMOTE_EDITABLE_META = new Set(['status', 'title', 'pinnedAt']);@@ -827,6 +828,7 @@ export async function clearSessionContextInDb(sessionId: string, atMs?: number):},ownerScope,);+ broadcastSubagentRunsInvalidated(sessionId, ownerScope);}}diff --git a/apps/desktop/src/main/localDb/ipc/subagentRuns.ts b/apps/desktop/src/main/localDb/ipc/subagentRuns.tsnew file mode 100644index 0000000000..2be73c1121--- /dev/null+++ b/apps/desktop/src/main/localDb/ipc/subagentRuns.ts@@ -0,0 +1,97 @@+/** Read-only renderer IPC for Cindy-owned durable Subagent records. */++import { BrowserWindow, ipcMain } from 'electron';+import {+ SUBAGENT_RUNS_CHANGED_CHANNEL,+ type SubagentProvider,+ type SubagentRunDetailResponse,+ type SubagentRunsChangedPayload,+ type SubagentRunsListResponse,+} from '@cindy/maker-shared/subagent-workspace';++import { getActiveDataOwnerPushStamp } from '../../appSessionState.js';+import {+ isDataOwnerBroadcastScopeCurrent,+ type DataOwnerBroadcastScope,+} from '../../device-link/broadcast-tap.js';+import {+ assertTrustedAppRendererEvent,+ isTrustedAppRendererWindow,+} from '../../security/trustedAppRenderer.js';+import {+ requireEnum,+ requireNonNegativeInt,+ requireObject,+ requireString,+} from '../../utils/ipcValidate.js';+import { getSubagentRunDetail, listSubagentRuns } from '../subagentRuns.js';++const SUBAGENT_PROVIDERS = [+ 'claude-code',+ 'codex',+ 'pi',+] as const satisfies readonly SubagentProvider[];++export function broadcastSubagentRunsChanged(+ payload: SubagentRunsChangedPayload,+ ownerScope?: DataOwnerBroadcastScope | null,+): void {+ if (ownerScope && !isDataOwnerBroadcastScopeCurrent(ownerScope)) return;+ const hasCapturedScope = ownerScope !== undefined && ownerScope !== null;+ const ownerStamp = hasCapturedScope+ ? ownerScope.ownerStamp+ : getActiveDataOwnerPushStamp();+ for (const window of BrowserWindow.getAllWindows()) {+ if (!window.isDestroyed() && isTrustedAppRendererWindow(window)) {+ try {+ window.webContents.send(SUBAGENT_RUNS_CHANGED_CHANNEL, payload, ownerStamp);+ } catch {+ // One closing renderer must not prevent invalidation of the others.+ }+ }+ }+}++export function broadcastSubagentRunsInvalidated(+ sessionId: string,+ ownerScope?: DataOwnerBroadcastScope | null,+): void {+ broadcastSubagentRunsChanged(+ {+ sessionId,+ runId: null,+ created: false,+ firstForSession: false,+ },+ ownerScope,+ );+}++export function registerSubagentRunsIpc(): void {+ ipcMain.handle('local-db:subagent-runs:list', async (event, input: unknown) => {+ assertTrustedAppRendererEvent(event);+ const body = requireObject(input, 'subagent runs list input');+ const sessionId = requireString(body.sessionId, 'sessionId');+ const cursor = body.cursor === undefined ? undefined : requireString(body.cursor, 'cursor');+ const limit = body.limit === undefined ? undefined : requireNonNegativeInt(body.limit, 'limit');+ const page = await listSubagentRuns(sessionId, { cursor, limit });+ return {+ supported: page !== null,+ runs: page?.runs ?? [],+ ...(page?.nextCursor ? { nextCursor: page.nextCursor } : {}),+ } satisfies SubagentRunsListResponse;+ });++ ipcMain.handle('local-db:subagent-runs:detail', async (event, input: unknown) => {+ assertTrustedAppRendererEvent(event);+ const body = requireObject(input, 'subagent run detail input');+ const sessionId = requireString(body.sessionId, 'sessionId');+ const provider = requireEnum(body.provider, SUBAGENT_PROVIDERS, 'provider');+ const runIdOrAlias = requireString(body.runIdOrAlias, 'runIdOrAlias');+ const run = await getSubagentRunDetail(sessionId, provider, runIdOrAlias);+ return {+ supported: run !== undefined,+ run: run ?? null,+ } satisfies SubagentRunDetailResponse;+ });+}diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.tsindex 7d71a54107..98e65995f5 100644--- a/apps/desktop/src/main/localDb/schema.ts+++ b/apps/desktop/src/main/localDb/schema.ts@@ -393,6 +393,110 @@ export const messages = sqliteTable(}),);+/**+ * Cindy-owned durable Subagent records.+ *+ * This table is intentionally harness-neutral. `logical_agent_id` is the+ * user-visible child identity inside the parent task; native PI session ids,+ * Codex thread ids and future Claude handles live in the opaque JSON arrays.+ * The renderer never receives filesystem-backed provider session references.+ *+ * `activity` is a bounded projection of lifecycle/progress observations. Full+ * native transcripts are a separate capability and may be supplied by later+ * harness adapters without changing this record shape.+ * Rows live for the parent task's lifetime and cascade with the session; list+ * IPC is cursor-paginated, while activity/text fields are bounded per row.+ */+export const subagentRuns = sqliteTable(+ 'subagent_runs',+ {+ id: text('id').primaryKey(),+ sessionId: text('session_id')+ .notNull()+ .references((): AnySQLiteColumn => sessions.id, { onDelete: 'cascade' }),+ provider: text('provider', { enum: ['claude-code', 'codex', 'pi'] }).notNull(),+ logicalAgentId: text('logical_agent_id').notNull(),+ parentToolUseId: text('parent_tool_use_id'),+ /** JSON string[] containing task/tool aliases observed for this logical child. */+ aliases: text('aliases').notNull().default('[]'),+ /** JSON string[] containing opaque harness-native child run/thread ids. */+ providerRunIds: text('provider_run_ids').notNull().default('[]'),+ status: text('status', {+ enum: ['running', 'completed', 'failed', 'stopped'],+ })+ .notNull()+ .default('running'),+ title: text('title'),+ description: text('description'),+ summary: text('summary'),+ model: text('model'),+ reasoningEffort: text('reasoning_effort'),+ totalTokens: integer('total_tokens'),+ toolUses: integer('tool_uses'),+ durationMs: integer('duration_ms'),+ /** JSON SubagentCapabilities; optional fields are fail-closed by readers. */+ capabilities: text('capabilities').notNull().default('{}'),+ /** JSON SubagentActivityEntry[]; writer enforces count/text bounds. */+ activity: text('activity').notNull().default('[]'),+ startedAt: integer('started_at').notNull(),+ updatedAt: integer('updated_at').notNull(),+ endedAt: integer('ended_at'),+ /** Future/repair visibility markers; normal reads fail closed when set. */+ rewindAt: integer('rewind_at'),+ deletedAt: integer('deleted_at'),+ },+ (t) => ({+ // Logical/native ids may legally be reused after a task clear or rewind.+ // Lookup uniqueness lives in the visible generation, not across all audit rows.+ byLogicalAgent: index('subagent_runs_logical_idx').on(+ t.sessionId,+ t.provider,+ t.logicalAgentId,+ ),+ bySession: index('subagent_runs_session_idx').on(+ t.sessionId,+ t.rewindAt,+ t.deletedAt,+ t.startedAt,+ ),+ byParentToolUse: index('subagent_runs_parent_tool_use_idx').on(t.sessionId, t.parentToolUseId),+ }),+);++/**+ * Indexed identity projection for Subagent observations.+ *+ * A harness may report the same logical child first by task id and later by+ * parent tool id or native thread id. Keeping the bounded alias array on the+ * run makes the record self-contained; this table makes matching O(log n)+ * instead of parsing every historical run on each progress event. Alias reuse+ * across clear/rewind generations is intentional, hence runId is part of the+ * primary key and readers select the newest visible run.+ */+export const subagentRunAliases = sqliteTable(+ 'subagent_run_aliases',+ {+ sessionId: text('session_id')+ .notNull()+ .references((): AnySQLiteColumn => sessions.id, { onDelete: 'cascade' }),+ provider: text('provider', { enum: ['claude-code', 'codex', 'pi'] }).notNull(),+ alias: text('alias').notNull(),+ runId: text('run_id')+ .notNull()+ .references((): AnySQLiteColumn => subagentRuns.id, { onDelete: 'cascade' }),+ createdAt: integer('created_at').notNull(),+ },+ (t) => ({+ pk: primaryKey({ columns: [t.runId, t.alias] }),+ byAlias: index('subagent_run_aliases_lookup_idx').on(+ t.sessionId,+ t.provider,+ t.alias,+ t.createdAt,+ ),+ }),+);+/*** session-git-pr-context: 会话关联的 GitHub PR 引用。* 来源是确定性提取(main 在消息落库单点扫 user/assistant 文本中的 PR URL,@@ -1073,10 +1177,10 @@ export const dailySpend = sqliteTable(costUsd: real('cost_usd').notNull().default(0),costAmount: real('cost_amount').notNull().default(0),/** 该行金额的币种。历史 NULL 行在迁移时按其 USD 口径填为 'USD'。 */- costCurrency: text('cost_currency', { enum: ['CNY', 'USD'] }).notNull().default('USD'),- costIsApproximate: integer('cost_is_approximate', { mode: 'boolean' })+ costCurrency: text('cost_currency', { enum: ['CNY', 'USD'] }).notNull()- .default(false),+ .default('USD'),+ costIsApproximate: integer('cost_is_approximate', { mode: 'boolean' }).notNull().default(false),/** 最后一次更新的 unix ms。 */updatedAt: integer('updated_at').notNull(),},@@ -1116,10 +1220,10 @@ export const dailyModelUsage = sqliteTable(costUsd: real('cost_usd').notNull().default(0),costAmount: real('cost_amount').notNull().default(0),/** 该行金额的币种。无金额的纯 token 行与历史 NULL 行迁移时填为 'USD'。 */- costCurrency: text('cost_currency', { enum: ['CNY', 'USD'] }).notNull().default('USD'),- costIsApproximate: integer('cost_is_approximate', { mode: 'boolean' })+ costCurrency: text('cost_currency', { enum: ['CNY', 'USD'] }).notNull()- .default(false),+ .default('USD'),+ costIsApproximate: integer('cost_is_approximate', { mode: 'boolean' }).notNull().default(false),inputTokens: integer('input_tokens').notNull().default(0),outputTokens: integer('output_tokens').notNull().default(0),cacheReadTokens: integer('cache_read_tokens').notNull().default(0),@@ -1325,6 +1429,11 @@ export const rightSidebarTabs = sqliteTable(},(t) => ({bySession: index('right_sidebar_tabs_session_idx').on(t.sessionId, t.position),+ // Other tab kinds may have multiple instances. Subagents is one durable+ // workspace per parent task and must remain singleton across two renderers.+ uniqSubagents: uniqueIndex('right_sidebar_tabs_subagents_singleton_idx')+ .on(t.sessionId)+ .where(sql`${t.kind} = 'subagents'`),}),);diff --git a/apps/desktop/src/main/localDb/subagentRuns.ts b/apps/desktop/src/main/localDb/subagentRuns.tsnew file mode 100644index 0000000000..a22f085931--- /dev/null+++ b/apps/desktop/src/main/localDb/subagentRuns.ts@@ -0,0 +1,808 @@+/** Host-owned durable projection of Subagent activity. */++import { createId } from '@paralleldrive/cuid2';+import {+ SUBAGENT_PR1_CAPABILITIES,+ type SubagentActivityEntry,+ type SubagentCapabilities,+ type SubagentProvider,+ type SubagentRun,+ type SubagentRunDetail,+ type SubagentRunStatus,+} from '@cindy/maker-shared/subagent-workspace';+import { normalizeSubagentObservation } from '@cindy/maker-shared/subagent-observation';+import {+ normalizeAgentTaskUpdate,+ subagentSpawnResultIndicatesRunning,+ type AgentTaskUpdate,+} from '@cindy/maker-shared/agent-task';+import { and, desc, eq, gt, inArray, isNull, lt, ne, or } from 'drizzle-orm';++import { getDbClient } from './client/current.js';+import { messages, sessions, subagentRunAliases, subagentRuns } from './schema.js';++const MAX_ALIAS_COUNT = 128;+const MAX_PROVIDER_RUN_IDS = 64;+const MAX_INDEXED_ALIAS_COUNT = MAX_ALIAS_COUNT + MAX_PROVIDER_RUN_IDS;+const MAX_ACTIVITY_ENTRIES = 200;+const MAX_RETURNED_RESULT_BYTES = 256 * 1024;+const DEFAULT_LIST_PAGE_SIZE = 50;+const MAX_LIST_PAGE_SIZE = 100;++const TEXT_LIMITS = {+ id: 512,+ title: 240,+ description: 8 * 1024,+ summary: 8 * 1024,+ model: 240,+ reasoningEffort: 80,+ activitySummary: 2 * 1024,+ lastToolName: 240,+} as const;++type SubagentRunRow = typeof subagentRuns.$inferSelect;++export interface PersistSubagentTaskUpdateResult {+ runId: string;+ created: boolean;+ firstForSession: boolean;+}++export interface VisibleSubagentObservationIdentity {+ provider: SubagentProvider;+ identities: string[];+}++function sliceWithoutDanglingSurrogate(value: string, end: number): string {+ let boundedEnd = end;+ if (boundedEnd > 0) {+ const last = value.charCodeAt(boundedEnd - 1);+ if (last >= 0xd800 && last <= 0xdbff) boundedEnd -= 1;+ }+ return value.slice(0, boundedEnd);+}++function boundedText(value: string | null | undefined, max: number): string | undefined {+ if (typeof value !== 'string') return undefined;+ const trimmed = value.trim();+ if (!trimmed) return undefined;+ return trimmed.length <= max ? trimmed : `${sliceWithoutDanglingSurrogate(trimmed, max - 1)}…`;+}++function boundedNumber(value: number | undefined): number | undefined {+ return typeof value === 'number' && Number.isFinite(value) && value >= 0+ ? Math.min(Number.MAX_SAFE_INTEGER, Math.floor(value))+ : undefined;+}++function parseStringArray(raw: string): string[] {+ try {+ const value: unknown = JSON.parse(raw);+ if (!Array.isArray(value)) return [];+ return value.filter((item): item is string => typeof item === 'string' && item.length > 0);+ } catch {+ return [];+ }+}++function parseActivity(raw: string): SubagentActivityEntry[] {+ try {+ const value: unknown = JSON.parse(raw);+ if (!Array.isArray(value)) return [];+ return value.filter((item): item is SubagentActivityEntry => {+ if (!item || typeof item !== 'object') return false;+ const entry = item as Partial<SubagentActivityEntry>;+ return (+ typeof entry.sequence === 'number' &&+ typeof entry.occurredAt === 'number' &&+ (entry.status === 'running' ||+ entry.status === 'completed' ||+ entry.status === 'failed' ||+ entry.status === 'stopped') &&+ (entry.kind === 'started' ||+ entry.kind === 'progress' ||+ entry.kind === 'message' ||+ entry.kind === 'question' ||+ entry.kind === 'decision' ||+ entry.kind === 'resumed' ||+ entry.kind === 'steered' ||+ entry.kind === 'completed' ||+ entry.kind === 'failed' ||+ entry.kind === 'stopped')+ );+ });+ } catch {+ return [];+ }+}++function parseCapabilities(raw: string): SubagentCapabilities {+ let value: Record<string, unknown> = {};+ try {+ const parsed: unknown = JSON.parse(raw);+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {+ value = parsed as Record<string, unknown>;+ }+ } catch {+ // Fail closed below.+ }+ const parentContext =+ value.parentContext === 'snapshot' || value.parentContext === 'live'+ ? value.parentContext+ : 'unknown';+ return {+ viewActivity: value.viewActivity === true,+ viewReturnedResult: value.viewReturnedResult === true,+ viewFullTranscript: value.viewFullTranscript === true,+ resume: value.resume === true,+ steer: value.steer === true,+ stop: value.stop === true,+ parentContext,+ };+}++function finiteTime(value: string | undefined, fallback: number): number {+ if (!value) return fallback;+ const parsed = Date.parse(value);+ return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : fallback;+}++function mergeUnique(+ values: readonly string[],+ incoming: readonly (string | undefined)[],+ max: number,+): string[] {+ const out = new Set(values);+ for (const raw of incoming) {+ const value = boundedText(raw, TEXT_LIMITS.id);+ if (value) out.add(value);+ if (out.size >= max) break;+ }+ return [...out].slice(0, max);+}++function terminal(status: SubagentRunStatus): boolean {+ return status === 'completed' || status === 'failed' || status === 'stopped';+}++function mergeStatus(+ previous: SubagentRunStatus | undefined,+ next: SubagentRunStatus,+ provider: SubagentProvider,+): SubagentRunStatus {+ if (!previous) return next;+ if (previous === 'failed' || previous === 'stopped') return previous;+ // Codex can discover a running descendant after the direct child appeared+ // complete; that is aggregate expansion, not resurrection of a failed run.+ if (previous === 'completed' && next === 'running' && provider !== 'codex') return previous;+ return next;+}++function activityKind(status: SubagentRunStatus, created: boolean): SubagentActivityEntry['kind'] {+ if (created && status === 'running') return 'started';+ if (status === 'completed') return 'completed';+ if (status === 'failed') return 'failed';+ if (status === 'stopped') return 'stopped';+ return 'progress';+}++function appendActivity(+ current: SubagentActivityEntry[],+ update: AgentTaskUpdate,+ status: SubagentRunStatus,+ occurredAt: number,+ created: boolean,+): SubagentActivityEntry[] {+ const summary = boundedText(update.summary ?? update.description, TEXT_LIMITS.activitySummary);+ const lastToolName = boundedText(update.lastToolName, TEXT_LIMITS.lastToolName);+ const kind = activityKind(status, created);+ const previous = current.at(-1);+ if (+ previous &&+ previous.kind === kind &&+ previous.status === status &&+ previous.summary === summary &&+ previous.lastToolName === lastToolName+ ) {+ return current;+ }+ const next: SubagentActivityEntry = {+ sequence: (previous?.sequence ?? 0) + 1,+ kind,+ status,+ ...(summary ? { summary } : {}),+ ...(lastToolName ? { lastToolName } : {}),+ occurredAt,+ };+ return [...current, next].slice(-MAX_ACTIVITY_ENTRIES);+}++function rowToRun(row: SubagentRunRow): SubagentRun {+ const usage = {+ ...(row.totalTokens !== null ? { totalTokens: row.totalTokens } : {}),+ ...(row.toolUses !== null ? { toolUses: row.toolUses } : {}),+ ...(row.durationMs !== null ? { durationMs: row.durationMs } : {}),+ };+ return {+ id: row.id,+ parentSessionId: row.sessionId,+ provider: row.provider,+ logicalAgentId: row.logicalAgentId,+ ...(row.parentToolUseId ? { parentToolUseId: row.parentToolUseId } : {}),+ identityAliases: parseStringArray(row.aliases),+ providerRunIds: parseStringArray(row.providerRunIds),+ status: row.status,+ ...(row.title ? { title: row.title } : {}),+ ...(row.description ? { description: row.description } : {}),+ ...(row.summary ? { summary: row.summary } : {}),+ ...(row.model ? { model: row.model } : {}),+ ...(row.reasoningEffort ? { reasoningEffort: row.reasoningEffort } : {}),+ ...(Object.keys(usage).length > 0 ? { usage } : {}),+ capabilities: parseCapabilities(row.capabilities),+ startedAt: row.startedAt,+ updatedAt: row.updatedAt,+ ...(row.endedAt !== null ? { endedAt: row.endedAt } : {}),+ };+}++async function matchingRow(+ sessionId: string,+ provider: SubagentProvider,+ incomingAliases: string[],+ clearedAt: number | null,+): Promise<SubagentRunRow | undefined> {+ if (incomingAliases.length === 0) return undefined;+ const db = getDbClient().drizzle;+ const visibility = [+ eq(subagentRuns.sessionId, sessionId),+ eq(subagentRuns.provider, provider),+ isNull(subagentRuns.rewindAt),+ isNull(subagentRuns.deletedAt),+ ...(clearedAt !== null ? [gt(subagentRuns.startedAt, clearedAt)] : []),+ ];+ const [indexed] = await db+ .select({ run: subagentRuns })+ .from(subagentRunAliases)+ .innerJoin(subagentRuns, eq(subagentRunAliases.runId, subagentRuns.id))+ .where(+ and(+ eq(subagentRunAliases.sessionId, sessionId),+ eq(subagentRunAliases.provider, provider),+ inArray(subagentRunAliases.alias, incomingAliases),+ ...visibility,+ ),+ )+ .orderBy(desc(subagentRuns.startedAt), desc(subagentRuns.id))+ .limit(1);+ if (indexed) return indexed.run;++ // Recovery fallback for a process crash between the run write and alias+ // projection. Normal updates use the indexed join above.+ const [direct] = await db+ .select()+ .from(subagentRuns)+ .where(+ and(+ ...visibility,+ or(+ inArray(subagentRuns.logicalAgentId, incomingAliases),+ inArray(subagentRuns.parentToolUseId, incomingAliases),+ ),+ ),+ )+ .orderBy(desc(subagentRuns.startedAt), desc(subagentRuns.id))+ .limit(1);+ return direct;+}++async function persistAliasProjection(+ row: SubagentRunRow | { id: string; sessionId: string; provider: SubagentProvider },+ aliases: string[],+ now: number,+): Promise<void> {+ if (aliases.length === 0) return;+ await getDbClient()+ .drizzle.insert(subagentRunAliases)+ .values(+ aliases.map((alias) => ({+ sessionId: row.sessionId,+ provider: row.provider,+ alias,+ runId: row.id,+ createdAt: now,+ })),+ )+ .onConflictDoNothing();+}++/**+ * Persist one existing `agent_task_update` observation. This function does not+ * launch, stop or otherwise control a harness; callers place it on the shared+ * durable-write FIFO so message and Subagent projections retain event order.+ */+export async function persistSubagentTaskUpdate(+ sessionId: string,+ data: unknown,+ source?: SubagentProvider,+ observedAt = Date.now(),+): Promise<PersistSubagentTaskUpdateResult | null> {+ const update = normalizeAgentTaskUpdate(data, source);+ const markedObservation =+ data && typeof data === 'object' && !Array.isArray(data)+ ? normalizeSubagentObservation((data as Record<string, unknown>).subagentObservation)+ : null;+ // Codex's completed spawn item carries the result summary but deliberately+ // leaves lifecycle authority to descendant tracking. It may enrich an+ // already-marked run, but can never create one or close it by itself.+ const codexSummaryEnrichment =+ !markedObservation &&+ source === 'codex' &&+ update?.provider === 'codex' &&+ update.status === 'completed' &&+ Boolean(update.summary);+ const observation =+ markedObservation ??+ (codexSummaryEnrichment && update+ ? {+ kind: 'progress' as const,+ logicalSubagentId: update.taskId,+ ...(update.parentToolUseId ? { parentToolUseId: update.parentToolUseId } : {}),+ }+ : null);+ if (+ !update ||+ !observation ||+ update.taskType === 'local_bash' ||+ update.taskType === 'local_workflow' ||+ (observation.kind === 'terminal' && !terminal(update.status)) ||+ (observation.kind === 'progress' && terminal(update.status) && !codexSummaryEnrichment)+ ) {+ return null;+ }++ const db = getDbClient().drizzle;+ const [session] = await db+ .select({ id: sessions.id, status: sessions.status, clearedAt: sessions.clearedAt })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ // Remote/device-link sessions are not owned by this database. PR1 fails+ // closed instead of accidentally attaching their events to the controller.+ if (!session || session.status === 'deleted') return null;++ const incomingIdentityAliases = mergeUnique(+ [],+ [+ observation.logicalSubagentId,+ observation.parentToolUseId,+ ...(observation.identityAliases ?? []),+ ],+ MAX_ALIAS_COUNT,+ );+ const incomingProviderRunIds = observation.kind === 'spawn'+ ? mergeUnique([], observation.providerRunIds ?? [], MAX_PROVIDER_RUN_IDS)+ : [];+ const lookupAliases = mergeUnique(+ incomingIdentityAliases,+ incomingProviderRunIds,+ MAX_INDEXED_ALIAS_COUNT,+ );+ const existing = await matchingRow(sessionId, update.provider, lookupAliases, session.clearedAt);+ // A progress/terminal event is never authority to invent a child or attach a+ // control call's receiver ids to an arbitrary existing run.+ if (!existing && observation.kind !== 'spawn') return null;+ const now = Number.isSafeInteger(observedAt) && observedAt >= 0 ? observedAt : Date.now();+ const updatedAt = finiteTime(update.updatedAt, now);+ if (codexSummaryEnrichment) {+ const summary = boundedText(update.summary, TEXT_LIMITS.summary);+ if (!existing || !summary) return null;+ const activity = appendActivity(+ parseActivity(existing.activity),+ { ...update, status: existing.status },+ existing.status,+ updatedAt,+ false,+ );+ await db+ .update(subagentRuns)+ .set({+ summary,+ activity: JSON.stringify(activity),+ updatedAt: Math.max(existing.updatedAt, updatedAt),+ })+ .where(eq(subagentRuns.id, existing.id));+ return { runId: existing.id, created: false, firstForSession: false };+ }+ const startedAt = existing?.startedAt ?? finiteTime(update.createdAt, updatedAt);+ const status = mergeStatus(existing?.status, update.status, update.provider);+ const aliases = mergeUnique(+ existing ? parseStringArray(existing.aliases) : [],+ incomingIdentityAliases,+ MAX_ALIAS_COUNT,+ );+ const providerRunIds = mergeUnique(+ existing ? parseStringArray(existing.providerRunIds) : [],+ incomingProviderRunIds,+ MAX_PROVIDER_RUN_IDS,+ );+ const activity = appendActivity(+ existing ? parseActivity(existing.activity) : [],+ update,+ status,+ updatedAt,+ !existing,+ );+ const parentToolUseId =+ boundedText(observation.parentToolUseId, TEXT_LIMITS.id) ??+ existing?.parentToolUseId ??+ null;+ const values = {+ parentToolUseId,+ aliases: JSON.stringify(aliases),+ providerRunIds: JSON.stringify(providerRunIds),+ status,+ title: boundedText(update.title, TEXT_LIMITS.title) ?? existing?.title ?? null,+ description:+ boundedText(update.description, TEXT_LIMITS.description) ?? existing?.description ?? null,+ summary: boundedText(update.summary, TEXT_LIMITS.summary) ?? existing?.summary ?? null,+ model:+ update.model === null+ ? null+ : (boundedText(update.model, TEXT_LIMITS.model) ?? existing?.model ?? null),+ reasoningEffort:+ boundedText(update.reasoningEffort, TEXT_LIMITS.reasoningEffort) ??+ existing?.reasoningEffort ??+ null,+ totalTokens: boundedNumber(update.usage?.totalTokens) ?? existing?.totalTokens ?? null,+ toolUses: boundedNumber(update.usage?.toolUses) ?? existing?.toolUses ?? null,+ durationMs: boundedNumber(update.usage?.durationMs) ?? existing?.durationMs ?? null,+ capabilities: existing?.capabilities ?? JSON.stringify(SUBAGENT_PR1_CAPABILITIES),+ activity: JSON.stringify(activity),+ startedAt,+ updatedAt: Math.max(existing?.updatedAt ?? 0, updatedAt),+ endedAt: terminal(status) ? (existing?.endedAt ?? updatedAt) : null,+ };++ if (existing) {+ // Index first: if the following denormalized row update fails, the alias+ // still points at a valid pre-existing run and a retry remains idempotent.+ await persistAliasProjection(+ existing,+ mergeUnique(aliases, providerRunIds, MAX_INDEXED_ALIAS_COUNT),+ now,+ );+ await db.update(subagentRuns).set(values).where(eq(subagentRuns.id, existing.id));+ return { runId: existing.id, created: false, firstForSession: false };+ }++ const [visibleBefore] = await db+ .select({ id: subagentRuns.id })+ .from(subagentRuns)+ .where(+ and(+ eq(subagentRuns.sessionId, sessionId),+ isNull(subagentRuns.rewindAt),+ isNull(subagentRuns.deletedAt),+ ...(session.clearedAt !== null ? [gt(subagentRuns.startedAt, session.clearedAt)] : []),+ ),+ )+ .limit(1);+ const id = createId();+ await db.insert(subagentRuns).values({+ id,+ sessionId,+ provider: update.provider,+ logicalAgentId: observation.logicalSubagentId,+ ...values,+ });+ await persistAliasProjection(+ { id, sessionId, provider: update.provider },+ mergeUnique(aliases, providerRunIds, MAX_INDEXED_ALIAS_COUNT),+ now,+ );+ return { runId: id, created: true, firstForSession: !visibleBefore };+}++async function readableSession(sessionId: string): Promise<{ clearedAt: number | null } | null> {+ const [session] = await getDbClient()+ .drizzle.select({ clearedAt: sessions.clearedAt })+ .from(sessions)+ .where(and(eq(sessions.id, sessionId), ne(sessions.status, 'deleted')))+ .limit(1);+ return session ?? null;+}++export async function listVisibleSubagentObservationIdentities(+ sessionId: string,+): Promise<VisibleSubagentObservationIdentity[]> {+ const session = await readableSession(sessionId);+ if (!session) return [];+ const rows = await getDbClient()+ .drizzle.select({+ provider: subagentRuns.provider,+ logicalAgentId: subagentRuns.logicalAgentId,+ parentToolUseId: subagentRuns.parentToolUseId,+ aliases: subagentRuns.aliases,+ providerRunIds: subagentRuns.providerRunIds,+ })+ .from(subagentRuns)+ .where(+ and(+ eq(subagentRuns.sessionId, sessionId),+ isNull(subagentRuns.rewindAt),+ isNull(subagentRuns.deletedAt),+ ...(session.clearedAt !== null ? [gt(subagentRuns.startedAt, session.clearedAt)] : []),+ ),+ );+ return rows.map((row) => ({+ provider: row.provider,+ identities: mergeUnique(+ parseStringArray(row.aliases),+ [+ row.logicalAgentId,+ row.parentToolUseId ?? undefined,+ ...parseStringArray(row.providerRunIds),+ ],+ MAX_INDEXED_ALIAS_COUNT,+ ),+ }));+}++async function visibleParentToolUseIds(+ sessionId: string,+ candidates: string[],+ clearedAt: number | null,+): Promise<Set<string>> {+ if (candidates.length === 0) return new Set();+ const rows = await getDbClient()+ .drizzle.select({ toolUseId: messages.toolUseId })+ .from(messages)+ .where(+ and(+ eq(messages.sessionId, sessionId),+ eq(messages.role, 'tool_use'),+ inArray(messages.toolUseId, candidates),+ isNull(messages.rewindAt),+ ...(clearedAt !== null ? [gt(messages.createdAt, clearedAt)] : []),+ ),+ );+ return new Set(rows.flatMap((row) => (row.toolUseId ? [row.toolUseId] : [])));+}++interface SubagentListCursor {+ startedAt: number;+ id: string;+}++function encodeCursor(row: Pick<SubagentRunRow, 'startedAt' | 'id'>): string {+ return Buffer.from(JSON.stringify({ startedAt: row.startedAt, id: row.id }), 'utf8').toString(+ 'base64url',+ );+}++function decodeCursor(raw: string | undefined): SubagentListCursor | null {+ if (!raw) return null;+ if (raw.length > 512) throw new Error('invalid Subagent list cursor');+ try {+ const value: unknown = JSON.parse(Buffer.from(raw, 'base64url').toString('utf8'));+ if (!value || typeof value !== 'object') throw new Error('invalid');+ const cursor = value as Partial<SubagentListCursor>;+ if (+ typeof cursor.startedAt !== 'number' ||+ !Number.isSafeInteger(cursor.startedAt) ||+ cursor.startedAt < 0 ||+ typeof cursor.id !== 'string' ||+ cursor.id.length === 0 ||+ cursor.id.length > TEXT_LIMITS.id+ ) {+ throw new Error('invalid');+ }+ return { startedAt: cursor.startedAt, id: cursor.id };+ } catch {+ throw new Error('invalid Subagent list cursor');+ }+}++export async function listSubagentRuns(+ sessionId: string,+ options: { cursor?: string; limit?: number } = {},+): Promise<{ runs: SubagentRun[]; nextCursor?: string } | null> {+ const session = await readableSession(sessionId);+ if (!session) return null;+ const db = getDbClient().drizzle;+ const cursor = decodeCursor(options.cursor);+ const requestedLimit =+ typeof options.limit === 'number' && Number.isFinite(options.limit)+ ? Math.floor(options.limit)+ : DEFAULT_LIST_PAGE_SIZE;+ const pageSize = Math.min(MAX_LIST_PAGE_SIZE, Math.max(1, requestedLimit));+ const baseConditions = [+ eq(subagentRuns.sessionId, sessionId),+ isNull(subagentRuns.rewindAt),+ isNull(subagentRuns.deletedAt),+ ];+ if (session.clearedAt !== null) {+ baseConditions.push(gt(subagentRuns.startedAt, session.clearedAt));+ }+ const visibleRows: SubagentRunRow[] = [];+ let scanCursor = cursor;+ let exhausted = false;+ // Parent visibility is defensive and can hide an entire raw batch. Keep+ // scanning bounded DB pages so those rows never strand older visible runs.+ while (visibleRows.length <= pageSize && !exhausted) {+ const conditions = [...baseConditions];+ if (scanCursor) {+ conditions.push(+ or(+ lt(subagentRuns.startedAt, scanCursor.startedAt),+ and(+ eq(subagentRuns.startedAt, scanCursor.startedAt),+ lt(subagentRuns.id, scanCursor.id),+ ),+ )!,+ );+ }+ const batch = await db+ .select()+ .from(subagentRuns)+ .where(and(...conditions))+ .orderBy(desc(subagentRuns.startedAt), desc(subagentRuns.id))+ .limit(pageSize + 1);+ if (batch.length === 0) break;+ const parentIds = batch.flatMap((row) => (row.parentToolUseId ? [row.parentToolUseId] : []));+ const visibleToolUseIds = await visibleParentToolUseIds(+ sessionId,+ parentIds,+ session.clearedAt,+ );+ visibleRows.push(+ ...batch.filter(+ (row) => !row.parentToolUseId || visibleToolUseIds.has(row.parentToolUseId),+ ),+ );+ const lastScanned = batch[batch.length - 1];+ scanCursor = { startedAt: lastScanned.startedAt, id: lastScanned.id };+ exhausted = batch.length < pageSize + 1;+ }+ const page = visibleRows.slice(0, pageSize);+ const runs = page.map(rowToRun);+ return {+ runs,+ ...(visibleRows.length > pageSize && page.length > 0+ ? { nextCursor: encodeCursor(page[page.length - 1]) }+ : {}),+ };+}++function parseMessageText(raw: string): string | undefined {+ try {+ const parsed: unknown = JSON.parse(raw);+ return typeof parsed === 'string' && parsed.trim() ? parsed : undefined;+ } catch {+ return raw.trim() ? raw : undefined;+ }+}++function truncateUtf8(value: string, maxBytes: number): { value: string; truncated: boolean } {+ if (Buffer.byteLength(value, 'utf8') <= maxBytes) return { value, truncated: false };+ let low = 0;+ let high = value.length;+ while (low < high) {+ const middle = Math.ceil((low + high) / 2);+ if (Buffer.byteLength(value.slice(0, middle), 'utf8') <= maxBytes) low = middle;+ else high = middle - 1;+ }+ return { value: sliceWithoutDanglingSurrogate(value, low), truncated: true };+}++async function resolveDetailRow(+ sessionId: string,+ provider: SubagentProvider,+ identifier: string,+ clearedAt: number | null,+): Promise<SubagentRunRow | undefined> {+ const db = getDbClient().drizzle;+ const visibility = [+ eq(subagentRuns.sessionId, sessionId),+ eq(subagentRuns.provider, provider),+ isNull(subagentRuns.rewindAt),+ isNull(subagentRuns.deletedAt),+ ...(clearedAt !== null ? [gt(subagentRuns.startedAt, clearedAt)] : []),+ ];+ const [direct] = await db+ .select()+ .from(subagentRuns)+ .where(and(eq(subagentRuns.id, identifier), ...visibility))+ .limit(1);+ if (direct) return direct;++ const [aliased] = await db+ .select({ run: subagentRuns })+ .from(subagentRunAliases)+ .innerJoin(subagentRuns, eq(subagentRunAliases.runId, subagentRuns.id))+ .where(+ and(+ eq(subagentRunAliases.sessionId, sessionId),+ eq(subagentRunAliases.provider, provider),+ eq(subagentRunAliases.alias, identifier),+ ...visibility,+ ),+ )+ .orderBy(desc(subagentRuns.updatedAt), desc(subagentRuns.id))+ .limit(1);+ return aliased?.run;+}++export async function getSubagentRunDetail(+ sessionId: string,+ provider: SubagentProvider,+ runIdOrAlias: string,+): Promise<SubagentRunDetail | null | undefined> {+ const session = await readableSession(sessionId);+ if (!session) return undefined;+ const normalizedIdentifier = boundedText(runIdOrAlias, TEXT_LIMITS.id);+ if (!normalizedIdentifier) return null;+ const row = await resolveDetailRow(sessionId, provider, normalizedIdentifier, session.clearedAt);+ if (!row) return null;+ if (row.parentToolUseId) {+ const visibleToolUseIds = await visibleParentToolUseIds(+ sessionId,+ [row.parentToolUseId],+ session.clearedAt,+ );+ if (!visibleToolUseIds.has(row.parentToolUseId)) return null;+ }++ const run = rowToRun(row);+ let returnedResult: string | undefined;+ let returnedResultTruncated = false;+ if (+ run.capabilities.viewReturnedResult &&+ row.provider === 'codex' &&+ row.status === 'completed' &&+ row.summary+ ) {+ const bounded = truncateUtf8(row.summary, MAX_RETURNED_RESULT_BYTES);+ returnedResult = bounded.value;+ returnedResultTruncated = bounded.truncated;+ } else if (+ run.capabilities.viewReturnedResult &&+ (row.provider === 'pi' || row.provider === 'claude-code') &&+ row.parentToolUseId &&+ terminal(row.status)+ ) {+ const [result] = await getDbClient()+ .drizzle.select({ content: messages.content })+ .from(messages)+ .where(+ and(+ eq(messages.sessionId, sessionId),+ eq(messages.role, 'tool_result'),+ eq(messages.toolUseId, row.parentToolUseId),+ isNull(messages.rewindAt),+ ...(session.clearedAt !== null ? [gt(messages.createdAt, session.clearedAt)] : []),+ ),+ )+ .orderBy(desc(messages.createdAt))+ .limit(1);+ const text = result ? parseMessageText(result.content) : undefined;+ // Claude's background Agent tool result is only a launch receipt. Once the+ // task reaches terminal state, expose the task_notification summary instead.+ const returnedText = row.provider === 'claude-code'+ && subagentSpawnResultIndicatesRunning('Agent', text)+ ? row.summary ?? undefined+ : text;+ if (returnedText) {+ const bounded = truncateUtf8(returnedText, MAX_RETURNED_RESULT_BYTES);+ returnedResult = bounded.value;+ returnedResultTruncated = bounded.truncated;+ }+ }++ return {+ ...run,+ activity: run.capabilities.viewActivity ? parseActivity(row.activity) : [],+ ...(returnedResult ? { returnedResult } : {}),+ ...(returnedResultTruncated ? { returnedResultTruncated: true } : {}),+ };+}diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex 467e77c697..72d75b9f67 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -217,7 +217,10 @@ function sessionAgentSwitchFallback(db: Database.Database, args: unknown): voidfunction messageDelete(db: Database.Database,args: unknown,-): { messages: Array<{ messageId: string; clientId: string }> } {+): {+ messages: Array<{ messageId: string; clientId: string }>;+ subagentRunIds: string[];+} {const payload = asRecord(args, 'message.delete args');const sessionId = expectString(payload.sessionId, 'sessionId');const clientIds = [...new Set(@@ -236,14 +239,36 @@ function messageDelete(const markerContent = expectString(marker.content, 'contextMarker.content');const markerCreatedAt = expectNumber(marker.createdAt, 'contextMarker.createdAt');const updatedAt = expectNumber(payload.updatedAt, 'updatedAt');+ const rawSubagentTurnWindow = payload.subagentTurnWindow;+ const subagentTurnWindow = rawSubagentTurnWindow === undefined+ ? null+ : (() => {+ const window = asRecord(rawSubagentTurnWindow, 'subagentTurnWindow');+ const startedAtInclusive = expectNumber(+ window.startedAtInclusive,+ 'subagentTurnWindow.startedAtInclusive',+ );+ const startedAtExclusive = window.startedAtExclusive === undefined+ ? undefined+ : expectNumber(window.startedAtExclusive, 'subagentTurnWindow.startedAtExclusive');+ if (+ !Number.isSafeInteger(startedAtInclusive)+ || startedAtInclusive < 0+ || (startedAtExclusive !== undefined+ && (!Number.isSafeInteger(startedAtExclusive) || startedAtExclusive < 0))+ ) {+ throw invalidArgs('subagentTurnWindow must contain non-negative integer timestamps');+ }+ return { startedAtInclusive, startedAtExclusive };+ })();const transaction = db.transaction(() => {const selectTarget = db.prepare(- "SELECT id, client_id AS clientId FROM messages WHERE session_id = ? AND client_id = ? AND role IN ('user', 'assistant', 'tool_use', 'tool_result', 'ask_user', 'plan_review', 'thinking', 'error') AND rewind_at IS NULL LIMIT 1",+ "SELECT id, client_id AS clientId, tool_use_id AS toolUseId FROM messages WHERE session_id = ? AND client_id = ? AND role IN ('user', 'assistant', 'tool_use', 'tool_result', 'ask_user', 'plan_review', 'thinking', 'error') AND rewind_at IS NULL LIMIT 1",);const targets = clientIds.map((clientId) => {const target = selectTarget.get(sessionId, clientId) as- | { id: string; clientId: string }+ | { id: string; clientId: string; toolUseId: string | null }| undefined;if (!target) {throw Object.assign(new Error(`Message 不存在或不可删除: ${clientId}`), {@@ -270,12 +295,88 @@ function messageDelete(}stmt.run(job.rowid);}- db.prepare("DELETE FROM embedding_jobs WHERE source = 'chat' AND source_id = ?").run(target.id);+ db.prepare("DELETE FROM embedding_jobs WHERE source = 'chat' AND source_id = ?").run(+ target.id,+ );+ }++ const subagentRunIds = new Set<string>();+ const hasSubagentRuns = Boolean(+ db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'subagent_runs'").get(),+ );+ if (hasSubagentRuns) {+ const selectLinkedSubagents = db.prepare(+ `SELECT id+ FROM subagent_runs+ WHERE session_id = ?+ AND parent_tool_use_id = ?+ AND rewind_at IS NULL+ AND deleted_at IS NULL`,+ );+ const parentToolUseIds = new Set(+ targets.flatMap((target) => (target.toolUseId ? [target.toolUseId] : [])),+ );+ for (const toolUseId of parentToolUseIds) {+ const linkedRows = selectLinkedSubagents.all(sessionId, toolUseId) as Array<{ id: string }>;+ for (const row of linkedRows) subagentRunIds.add(row.id);+ }+ if (subagentTurnWindow) {+ const parentlessRows = (+ subagentTurnWindow.startedAtExclusive === undefined+ ? db.prepare(+ `SELECT id+ FROM subagent_runs+ WHERE session_id = ?+ AND parent_tool_use_id IS NULL+ AND rewind_at IS NULL+ AND deleted_at IS NULL+ AND started_at >= ?`,+ ).all(sessionId, subagentTurnWindow.startedAtInclusive)+ : db.prepare(+ `SELECT id+ FROM subagent_runs+ WHERE session_id = ?+ AND parent_tool_use_id IS NULL+ AND rewind_at IS NULL+ AND deleted_at IS NULL+ AND started_at >= ?+ AND started_at < ?`,+ ).all(+ sessionId,+ subagentTurnWindow.startedAtInclusive,+ subagentTurnWindow.startedAtExclusive,+ )+ ) as Array<{ id: string }>;+ for (const row of parentlessRows) subagentRunIds.add(row.id);+ }+ const scrubSubagent = db.prepare(+ `UPDATE subagent_runs+ SET title = NULL,+ description = NULL,+ summary = NULL,+ activity = '[]',+ updated_at = MAX(updated_at, ?),+ deleted_at = ?+ WHERE id = ?+ AND session_id = ?+ AND rewind_at IS NULL+ AND deleted_at IS NULL`,+ );+ for (const runId of subagentRunIds) {+ const scrubbed = scrubSubagent.run(updatedAt, updatedAt, runId, sessionId);+ if (scrubbed.changes !== 1) {+ throw Object.assign(new Error(`Subagent 删除竞态: ${runId}`), {+ code: 'PRECONDITION_FAILED',+ });+ }+ }}// 旧重建标记的 handoff 可能包含本次目标消息;先删旧标记,只保留基于// 当前有效历史重新生成的最新版本,避免隐藏派生记录把内容留在本地。- db.prepare("DELETE FROM messages WHERE role = 'context_rebuild' AND session_id = ?").run(sessionId);+ db.prepare("DELETE FROM messages WHERE role = 'context_rebuild' AND session_id = ?").run(+ sessionId,+ );const scrubTarget = db.prepare("UPDATE messages SET role = 'message_tombstone', content = 'null', tool_use_id = NULL, agent_meta = NULL, agent_kind = NULL, rewind_at = ? WHERE id = ? AND session_id = ? AND client_id = ? AND role IN ('user', 'assistant', 'tool_use', 'tool_result', 'ask_user', 'plan_review', 'thinking', 'error') AND rewind_at IS NULL",);@@ -301,6 +402,7 @@ function messageDelete(messageId: target.id,clientId: target.clientId,})),+ subagentRunIds: [...subagentRunIds].sort(),};});return transaction();@@ -457,7 +559,11 @@ function codexImportMessages(db: Database.Database, args: unknown): { changed: nconst model = expectString(payload.model, 'model');const rows = expectArray(payload.rows, 'rows');const existing = readExistingMessageFingerprints(db, sessionId, importClientIdPrefix);- const existingImportedClientIds = readExistingImportedClientIds(db, sessionId, importClientIdPrefix);+ const existingImportedClientIds = readExistingImportedClientIds(+ db,+ sessionId,+ importClientIdPrefix,+ );const upsert = db.prepare(`INSERT INTO messages(id, client_id, session_id, role, content, tool_use_id, agent_meta, created_at, rewind_at)@@ -561,19 +667,25 @@ function rewindCommit(db: Database.Database, args: unknown): void {const payload = asRecord(args, 'rewind.commit args');const sessionId = expectString(payload.sessionId, 'sessionId');const targetCreatedAt = expectNumber(payload.targetCreatedAt, 'targetCreatedAt');- const targetMessageId = typeof payload.targetMessageId === 'string' ? payload.targetMessageId : null;+ const targetMessageId =+ typeof payload.targetMessageId === 'string' ? payload.targetMessageId : null;const targetClientId = typeof payload.targetClientId === 'string' ? payload.targetClientId : null;- const targetMessageUuid = typeof payload.targetMessageUuid === 'string' ? payload.targetMessageUuid : null;- const preserveMessageUuid = typeof payload.preserveMessageUuid === 'string' ? payload.preserveMessageUuid : null;- const sdkSessionId = typeof payload.sdkSessionId === 'string' && payload.sdkSessionId ? payload.sdkSessionId : null;+ const targetMessageUuid =+ typeof payload.targetMessageUuid === 'string' ? payload.targetMessageUuid : null;+ const preserveMessageUuid =+ typeof payload.preserveMessageUuid === 'string' ? payload.preserveMessageUuid : null;+ const sdkSessionId =+ typeof payload.sdkSessionId === 'string' && payload.sdkSessionId ? payload.sdkSessionId : null;const requireLatestUser = payload.requireLatestUser === true;const now = expectNumber(payload.now, 'now');- const rows = db.prepare(- `SELECT id, client_id, role, created_at, agent_meta+ const rows = db+ .prepare(+ `SELECT id, client_id, role, created_at, agent_meta, tool_use_idFROM messagesWHERE session_id = ?AND rewind_at IS NULL`,- ).all(sessionId) as RewindMessageRow[];+ )+ .all(sessionId) as RewindMessageRow[];// edit-last-message 原子守卫(requireLatestUser):与软删同一同步临界区内// 断言 target 之后没有更新的可见 user 消息(worker 单线程 + better-sqlite3// 同步执行,本函数内不可能被其它写操作打断)。命中 → 抛错,软删不发生,@@ -597,8 +709,44 @@ function rewindCommit(db: Database.Database, args: unknown): void {preserveMessageUuid,});const updateMessage = db.prepare('UPDATE messages SET rewind_at = ? WHERE id = ?');+ const hasSubagentRuns = Boolean(+ db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'subagent_runs'").get(),+ );+ const rewindSubagentByParent = hasSubagentRuns+ ? db.prepare(+ `UPDATE subagent_runs+ SET rewind_at = ?+ WHERE session_id = ?+ AND rewind_at IS NULL+ AND parent_tool_use_id = ?`,+ )+ : null;+ const rewindParentlessSubagentTail = hasSubagentRuns+ ? db.prepare(+ `UPDATE subagent_runs+ SET rewind_at = ?+ WHERE session_id = ?+ AND rewind_at IS NULL+ AND parent_tool_use_id IS NULL+ AND started_at >= ?`,+ )+ : null;const transaction = db.transaction(() => {for (const id of idsToRewind) updateMessage.run(now, id);+ if (rewindSubagentByParent && rewindParentlessSubagentTail) {+ const rewoundIds = new Set(idsToRewind);+ const parentToolUseIds = new Set(+ rows.flatMap((row) => (rewoundIds.has(row.id) && row.tool_use_id ? [row.tool_use_id] : [])),+ );+ for (const toolUseId of parentToolUseIds) {+ rewindSubagentByParent.run(now, sessionId, toolUseId);+ }+ // Older Claude task_updated events may not carry parentToolUseId. There+ // is no stable ordering key for a same-millisecond orphan, so fail closed+ // at the boundary: hiding a possibly older orphan is safer than exposing+ // work from the branch the user explicitly withdrew.+ rewindParentlessSubagentTail.run(now, sessionId, targetCreatedAt);+ }if (sdkSessionId) {db.prepare(`UPDATE sessions@@ -828,6 +976,7 @@ interface RewindMessageRow {role: string;created_at: number;agent_meta: string | null;+ tool_use_id: string | null;}interface RewindSelectOpts {@@ -902,8 +1051,9 @@ function forkSession(db: Database.Database, args: unknown): { messageCount: numbconst detachAgentSwitchSessions = payload.detachAgentSwitchSessions === true;const resetHandoffBoundaryClientId = nullableString(payload.resetHandoffBoundaryClientId);const newMessageIds = normalizeNewMessageIds(payload.newMessageIds);- const sourceMessages = db.prepare(- `SELECT client_id, role, content, tool_use_id, agent_meta, agent_kind, created_at+ const sourceMessages = db+ .prepare(+ `SELECT client_id, role, content, tool_use_id, agent_meta, agent_kind, created_atFROM messagesWHERE session_id = ?AND (? IS NULL OR created_at > ?)@@ -993,7 +1143,12 @@ function forkSession(db: Database.Database, args: unknown): { messageCount: numbresetHandoffBoundaryClientId,}),message.tool_use_id,- remapAgentMetaUuid(message.agent_meta, uuidMap, legacyTranscriptParentUuids, toolParentUuids),+ remapAgentMetaUuid(+ message.agent_meta,+ uuidMap,+ legacyTranscriptParentUuids,+ toolParentUuids,+ ),message.agent_kind,message.created_at,);diff --git a/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.tsindex 9fc15c8848..51cc110a19 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts@@ -25,9 +25,11 @@ function makeDeps(getLiveSession: vi.fn(() => ({ isTurnRunning: () => false })),hasBackgroundActivity: vi.fn(() => false),closeSession: vi.fn(async () => undefined),+ drainPersistQueue: vi.fn(async () => undefined),commitDeletion: vi.fn(async (sessionId, deletedClientIds) => ({sessionId,deletedClientIds,+ subagentRunIds: [],updatedAt: 500,preview: 'keep after',})),@@ -86,7 +88,7 @@ describe('performMessageDeletion', () => {resolve(process.cwd(), 'src/main/maker-ipc/register.ts'),'utf8',);- const onCommittedStart = registerSource.indexOf('onCommitted: ({ sessionId, deletedClientIds');+ const onCommittedStart = registerSource.indexOf('onCommitted:');expect(onCommittedStart).toBeGreaterThan(-1);const patchStart = registerSource.indexOf('broadcastSessionPatched(sessionId, {',@@ -111,22 +113,32 @@ describe('performMessageDeletion', () => {});expect(deps.closeSession).toHaveBeenCalledWith('s1');+ expect(deps.drainPersistQueue).toHaveBeenCalledOnce();+ expect(vi.mocked(deps.drainPersistQueue).mock.invocationCallOrder[0]!).toBeLessThan(+ vi.mocked(deps.listMessagesForContext).mock.invocationCallOrder[0]!,+ );+ expect(vi.mocked(deps.listMessagesForContext).mock.invocationCallOrder[0]!).toBeLessThan(+ vi.mocked(deps.commitDeletion).mock.invocationCallOrder[0]!,+ );+ expect(deps.getMessage).toHaveBeenCalledTimes(2);expect(deps.commitDeletion).toHaveBeenCalledWith('s1',['target'],expect.any(String),+ undefined,);const handoff = vi.mocked(deps.commitDeletion).mock.calls[0]?.[2] ?? '';expect(handoff).toContain('keep before');expect(handoff).toContain('keep after');expect(handoff).not.toContain('delete me');expect(handoff).toContain('treat only these records as the prior conversation');- // 第三参数是写入前取的代次(mock deps 未提供 readPendingHandoffGeneration → undefined)+ // 第三参数是最终历史读取前取的代次(mock deps 未提供 readPendingHandoffGeneration → undefined)expect(deps.setPendingHandoff).toHaveBeenCalledWith('s1', handoff, undefined);expect(deps.onCommitted).toHaveBeenCalledWith({sessionId: 's1',deletedClientIds: ['target'],+ subagentRunIds: [],updatedAt: 500,preview: 'keep after',},@@ -134,12 +146,76 @@ describe('performMessageDeletion', () => {);});+ it('recomputes the deletion range and handoff after queued records become durable', async () => {+ let drained = false;+ const deps = makeDeps({+ getMessage: vi.fn(async () => drained+ ? {+ id: 'final-row',+ role: 'assistant' as const,+ deletedClientIds: ['progress', 'late-result', 'final'],+ subagentTurnWindow: {+ startedAtInclusive: 100,+ startedAtExclusive: 700,+ },+ }+ : {+ id: 'final-row',+ role: 'assistant' as const,+ deletedClientIds: ['progress', 'final'],+ subagentTurnWindow: {+ startedAtInclusive: 100,+ startedAtExclusive: 600,+ },+ }),+ drainPersistQueue: vi.fn(async () => {+ drained = true;+ }),+ listMessagesForContext: vi.fn(async () => {+ expect(drained).toBe(true);+ return [+ { clientId: 'user', role: 'user', content: 'diagnose it', createdAt: 100 },+ { clientId: 'progress', role: 'assistant', content: 'checking', createdAt: 200 },+ {+ clientId: 'late-result',+ role: 'tool_result',+ content: 'queued sensitive result',+ createdAt: 500,+ },+ { clientId: 'final', role: 'assistant', content: 'fixed', createdAt: 600 },+ { clientId: 'next-user', role: 'user', content: 'thanks', createdAt: 700 },+ ];+ }),+ });++ await performMessageDeletion(deps, { sessionId: 's1', clientId: 'final' });++ expect(deps.getMessage).toHaveBeenCalledTimes(2);+ expect(deps.commitDeletion).toHaveBeenCalledWith(+ 's1',+ ['progress', 'late-result', 'final'],+ expect.any(String),+ {+ startedAtInclusive: 100,+ startedAtExclusive: 700,+ },+ );+ const handoff = vi.mocked(deps.commitDeletion).mock.calls[0]?.[2] ?? '';+ expect(handoff).toContain('diagnose it');+ expect(handoff).toContain('thanks');+ expect(handoff).not.toContain('queued sensitive result');+ });+it('deletes every AI record in the surrounding real user round', async () => {const deps = makeDeps({getMessage: vi.fn(async () => ({id: 'final-row',role: 'assistant' as const,deletedClientIds: ['progress', 'thinking', 'auto-resume', 'tool', 'final'],+ subagentTurnWindow: {+ startedAtInclusive: 100,+ startedAtExclusive: 700,+ },})),listMessagesForContext: vi.fn(async () => [{ clientId: 'user', role: 'user', content: 'diagnose it', createdAt: 100 },@@ -165,6 +241,10 @@ describe('performMessageDeletion', () => {'s1',['progress', 'thinking', 'auto-resume', 'tool', 'final'],expect.any(String),+ {+ startedAtInclusive: 100,+ startedAtExclusive: 700,+ },);const handoff = vi.mocked(deps.commitDeletion).mock.calls[0]?.[2] ?? '';expect(handoff).toContain('diagnose it');@@ -214,7 +294,7 @@ describe('performMessageDeletion', () => {sessionId: 's1',clientId: 'target',})).rejects.toThrow('SESSION_RUNNING');- expect(deps.listMessagesForContext).toHaveBeenCalledOnce();+ expect(deps.listMessagesForContext).not.toHaveBeenCalled();expect(deps.closeSession).not.toHaveBeenCalled();expect(deps.commitDeletion).not.toHaveBeenCalled();});@@ -247,6 +327,11 @@ describe('performMessageDeletion', () => {clientId: 'target',clientIds: ['target'],});- expect(deps.commitDeletion).toHaveBeenCalledWith('s1', ['target'], expect.any(String));+ expect(deps.commitDeletion).toHaveBeenCalledWith(+ 's1',+ ['target'],+ expect.any(String),+ undefined,+ );});});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/rewind-ipc.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/rewind-ipc.test.tsindex 579eea9515..248b53ac29 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/rewind-ipc.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/rewind-ipc.test.ts@@ -4,7 +4,14 @@ const mocks = vi.hoisted(() => ({handlers: new Map<string, (...args: unknown[]) => unknown>(),previewRewindAtMessage: vi.fn(),commitRewindAtMessage: vi.fn(),+ drainPersistQueue: vi.fn(),withSessionInputStoppedForRewind: vi.fn(),+ ownerScope: { ownerScopeKey: 'owner-1' },+ broadcastSubagentRunsInvalidated: vi.fn(),+ beginSubagentRewindFence: vi.fn(),+ finishSubagentRewindFence: vi.fn(),+ primeSubagentRewindFence: vi.fn(),+ listVisibleSubagentObservationIdentities: vi.fn(),}));vi.mock('electron', () => ({@@ -20,6 +27,10 @@ vi.mock('../../maker-orchestration/rewind.js', () => ({commitRewindAtMessage: mocks.commitRewindAtMessage,}));+vi.mock('../../messagePersistBroadcaster.js', () => ({+ drainPersistQueue: mocks.drainPersistQueue,+}));+vi.mock('../register.js', () => ({withSessionInputStoppedForRewind: mocks.withSessionInputStoppedForRewind,}));@@ -28,6 +39,24 @@ vi.mock('../../goal-host/index.js', () => ({getGoalController: () => null,}));+vi.mock('../../device-link/broadcast-tap.js', () => ({+ captureDataOwnerBroadcastScope: () => mocks.ownerScope,+}));++vi.mock('../../localDb/ipc/subagentRuns.js', () => ({+ broadcastSubagentRunsInvalidated: mocks.broadcastSubagentRunsInvalidated,+}));++vi.mock('../../localDb/subagentRuns.js', () => ({+ listVisibleSubagentObservationIdentities: mocks.listVisibleSubagentObservationIdentities,+}));++vi.mock('../../subagentObservationRewindFence.js', () => ({+ beginSubagentRewindFence: mocks.beginSubagentRewindFence,+ finishSubagentRewindFence: mocks.finishSubagentRewindFence,+ primeSubagentRewindFence: mocks.primeSubagentRewindFence,+}));+vi.mock('../../logger.js', () => ({createLogger: () => ({ warn: vi.fn() }),}));@@ -43,14 +72,25 @@ describe('maker rewind IPC stop-then-rewind', () => {beforeEach(() => {vi.clearAllMocks();mocks.handlers.clear();+ mocks.drainPersistQueue.mockResolvedValue(undefined);mocks.withSessionInputStoppedForRewind.mockImplementation(async (_sessionId: string, action: () => Promise<unknown>) => action(),);+ mocks.beginSubagentRewindFence.mockReturnValue({+ sessionId: 'session-1',+ token: Symbol('rewind'),+ });+ mocks.listVisibleSubagentObservationIdentities.mockResolvedValue([]);registerMakerRewindIpc();});it('runs normal rewind inside the stopped input boundary when requested', async () => {const session = { id: 'session-1' };+ const visibleBefore = [{ provider: 'claude-code', identities: ['before'] }];+ const visibleAfter = [{ provider: 'claude-code', identities: ['survivor'] }];+ mocks.listVisibleSubagentObservationIdentities+ .mockResolvedValueOnce(visibleBefore)+ .mockResolvedValueOnce(visibleAfter);mocks.commitRewindAtMessage.mockResolvedValue(session);const handler = mocks.handlers.get(MAKER_INVOKE.REWIND_COMMIT);if (!handler) throw new Error('rewind commit handler not registered');@@ -63,9 +103,27 @@ describe('maker rewind IPC stop-then-rewind', () => {'session-1',expect.any(Function),);+ expect(mocks.drainPersistQueue).toHaveBeenCalledOnce();+ expect(mocks.drainPersistQueue.mock.invocationCallOrder[0]!).toBeLessThan(+ mocks.commitRewindAtMessage.mock.invocationCallOrder[0]!,+ );expect(mocks.commitRewindAtMessage).toHaveBeenCalledWith('session-1', 'message-1', {requireLatestUser: false,});+ expect(mocks.broadcastSubagentRunsInvalidated).toHaveBeenCalledWith(+ 'session-1',+ mocks.ownerScope,+ );+ expect(mocks.beginSubagentRewindFence).toHaveBeenCalledWith('session-1');+ expect(mocks.primeSubagentRewindFence).toHaveBeenCalledWith(+ expect.any(Object),+ visibleBefore,+ );+ expect(mocks.finishSubagentRewindFence).toHaveBeenCalledWith(+ expect.any(Object),+ true,+ visibleAfter,+ );});it('waits through the post-Stop SESSION_RUNNING race before committing', async () => {@@ -83,6 +141,12 @@ describe('maker rewind IPC stop-then-rewind', () => {await expect(result).resolves.toBe(session);expect(mocks.commitRewindAtMessage).toHaveBeenCalledTimes(2);+ expect(mocks.drainPersistQueue).toHaveBeenCalledTimes(2);+ for (let index = 0; index < 2; index += 1) {+ expect(mocks.drainPersistQueue.mock.invocationCallOrder[index]!).toBeLessThan(+ mocks.commitRewindAtMessage.mock.invocationCallOrder[index]!,+ );+ }} finally {vi.useRealTimers();}@@ -102,6 +166,12 @@ describe('maker rewind IPC stop-then-rewind', () => {await rejection;expect(mocks.commitRewindAtMessage.mock.calls.length).toBeGreaterThan(1);expect(mocks.commitRewindAtMessage.mock.calls.length).toBeLessThanOrEqual(152);+ expect(mocks.broadcastSubagentRunsInvalidated).not.toHaveBeenCalled();+ expect(mocks.finishSubagentRewindFence).toHaveBeenCalledWith(+ expect.any(Object),+ false,+ [],+ );} finally {vi.useRealTimers();}@@ -118,8 +188,70 @@ describe('maker rewind IPC stop-then-rewind', () => {);expect(mocks.withSessionInputStoppedForRewind).not.toHaveBeenCalled();+ expect(mocks.drainPersistQueue).toHaveBeenCalledOnce();+ expect(mocks.drainPersistQueue.mock.invocationCallOrder[0]!).toBeLessThan(+ mocks.commitRewindAtMessage.mock.invocationCallOrder[0]!,+ );expect(mocks.commitRewindAtMessage).toHaveBeenCalledWith('session-1', 'message-1', {requireLatestUser: true,});});++ it('rolls back the Subagent fence when the post-commit identity refresh fails', async () => {+ const session = { id: 'session-1' };+ mocks.commitRewindAtMessage.mockResolvedValue(session);+ mocks.listVisibleSubagentObservationIdentities+ .mockResolvedValueOnce([])+ .mockRejectedValueOnce(new Error('transient identity read failure'));+ const handler = mocks.handlers.get(MAKER_INVOKE.REWIND_COMMIT);+ if (!handler) throw new Error('rewind commit handler not registered');++ await expect(handler({}, 'session-1', 'message-1')).rejects.toThrow(+ 'transient identity read failure',+ );+ expect(mocks.finishSubagentRewindFence).toHaveBeenCalledWith(+ expect.any(Object),+ false,+ [],+ );+ expect(mocks.broadcastSubagentRunsInvalidated).not.toHaveBeenCalled();+ });++ it('rolls back the Subagent fence when the initial identity query fails', async () => {+ mocks.listVisibleSubagentObservationIdentities.mockRejectedValueOnce(+ new Error('transient initial identity read failure'),+ );+ const handler = mocks.handlers.get(MAKER_INVOKE.REWIND_COMMIT);+ if (!handler) throw new Error('rewind commit handler not registered');++ await expect(handler({}, 'session-1', 'message-1')).rejects.toThrow(+ 'transient initial identity read failure',+ );+ expect(mocks.commitRewindAtMessage).not.toHaveBeenCalled();+ expect(mocks.finishSubagentRewindFence).toHaveBeenCalledWith(+ expect.any(Object),+ false,+ [],+ );+ });++ it.each(['spawn', 'progress', 'terminal'] as const)(+ 'makes an already queued %s observation durable before the rewind boundary is chosen',+ async (observationKind) => {+ const durableObservations: string[] = [];+ mocks.drainPersistQueue.mockImplementationOnce(async () => {+ durableObservations.push(observationKind);+ });+ mocks.commitRewindAtMessage.mockImplementationOnce(async () => {+ expect(durableObservations).toEqual([observationKind]);+ return { id: 'session-1' };+ });+ const handler = mocks.handlers.get(MAKER_INVOKE.REWIND_COMMIT);+ if (!handler) throw new Error('rewind commit handler not registered');++ await expect(handler({}, 'session-1', 'message-1', { stopIfRunning: true })).resolves.toEqual(+ { id: 'session-1' },+ );+ },+ );});diff --git a/apps/desktop/src/main/maker-ipc/messageDeleteHandler.ts b/apps/desktop/src/main/maker-ipc/messageDeleteHandler.tsindex 4e70a17bb9..2f4d6812c1 100644--- a/apps/desktop/src/main/maker-ipc/messageDeleteHandler.ts+++ b/apps/desktop/src/main/maker-ipc/messageDeleteHandler.ts@@ -11,6 +11,10 @@import { buildHandoffText, type HandoffSourceMessage } from './agentHandoff.js';import { MAKER_INVOKE } from './channels.js';import type { IpcHandlerRegistry } from './ipcHandlerRegistry.js';+import type {+ MessageDeletionTarget,+ SubagentTurnDeletionWindow,+} from '../localDb/ipc/messages.js';import { throwIpcError } from '../utils/ipcValidate.js';interface ContextSourceMessage extends HandoffSourceMessage {@@ -30,6 +34,7 @@ interface MessageDeleteSessionRow {interface MessageDeleteCommittedPayload {sessionId: string;deletedClientIds: string[];+ subagentRunIds: string[];updatedAt: number;preview: string | null;}@@ -39,19 +44,18 @@ export interface MessageDeleteHandlerDeps {getMessage(sessionId: string,clientId: string,- ): Promise<{- id: string;- role: 'user' | 'assistant';- deletedClientIds: string[];- } | null>;+ ): Promise<MessageDeletionTarget | null>;listMessagesForContext(sessionId: string): Promise<ContextSourceMessage[]>;getLiveSession(sessionId: string): { isTurnRunning(): boolean } | null | undefined;hasBackgroundActivity(sessionId: string): boolean;closeSession(sessionId: string): Promise<void>;+ /** Wait for chat/Subagent observations queued before the deletion barrier. */+ drainPersistQueue(): Promise<void>;commitDeletion(sessionId: string,clientIds: string[],handoff: string,+ subagentTurnWindow?: SubagentTurnDeletionWindow,): Promise<MessageDeleteCommittedPayload>;/** 见 sessionAgentSwitchHandler 同名字段:带代次写,防 /clear 竞态。 */setPendingHandoff(sessionId: string, handoff: string, expectedGeneration?: number): void;@@ -83,14 +87,14 @@ export async function performMessageDeletion(throwIpcError('INVALID_PARAMS', 'clientId required');}- const [sessionRow, target] = await Promise.all([+ const [sessionRow, initialTarget] = await Promise.all([deps.getSessionRow(sessionId),deps.getMessage(sessionId, clientId),]);if (!sessionRow || sessionRow.status === 'deleted') {throwIpcError('NOT_FOUND', `Session ${sessionId} not found`);}- if (!target) {+ if (!initialTarget) {throwIpcError('NOT_FOUND', 'Message 不存在或不可删除');}@@ -102,20 +106,6 @@ export async function performMessageDeletion(throwIpcError('SESSION_RUNNING', `Session ${sessionId} has background activity`);}- // 代次在读历史之前取:下面到 setPendingHandoff 之间有异步活,期间 /clear 过的话- // 这份按删除前历史算出的交接必须作废(见 registry.set 的 expectedGeneration)。- const handoffGeneration = deps.readPendingHandoffGeneration?.(sessionId);- const source = await deps.listMessagesForContext(sessionId);- const deletedClientIds = new Set(target.deletedClientIds);- const remaining = source.filter((message) => !deletedClientIds.has(message.clientId));- const label = engineLabel(sessionRow.agentKind);- const handoff = buildHandoffText(remaining, {- fromLabel: label,- toLabel: label,- sessionId,- reason: 'message-deletion',- });-return deps.withCloseSuppressed(sessionId, async () => {// 上面的读取和真正 close 之间仍可能有 dispatch 抢先;提交前再查一次,// 绝不在运行中的 turn 继续落输出时挖消息/切上下文。@@ -127,11 +117,34 @@ export async function performMessageDeletion(throwIpcError('SESSION_RUNNING', `Session ${sessionId} has background activity`);}if (currentLive) await deps.closeSession(sessionId);+ await deps.drainPersistQueue();++ // durable FIFO 里可能仍有在删除请求前产生、但尚未落库的 tool_result / Subagent+ // 观察。屏障后必须重读目标与历史,确保它们进入同一轮的删除范围且不会混入 handoff。+ // 代次也在这份最终历史之前读取;期间若发生 /clear,registry 会拒绝旧代 handoff。+ const handoffGeneration = deps.readPendingHandoffGeneration?.(sessionId);+ const [target, source] = await Promise.all([+ deps.getMessage(sessionId, clientId),+ deps.listMessagesForContext(sessionId),+ ]);+ if (!target) {+ throwIpcError('NOT_FOUND', 'Message 不存在或不可删除');+ }+ const deletedClientIds = new Set(target.deletedClientIds);+ const remaining = source.filter((message) => !deletedClientIds.has(message.clientId));+ const label = engineLabel(sessionRow.agentKind);+ const handoff = buildHandoffText(remaining, {+ fromLabel: label,+ toLabel: label,+ sessionId,+ reason: 'message-deletion',+ });const committed = await deps.commitDeletion(sessionId,target.deletedClientIds,handoff,+ target.subagentTurnWindow,);deps.setPendingHandoff(sessionId, handoff, handoffGeneration);await deps.onCommitted(committed, clientId);diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex cc40e3fd05..a8235058b8 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -179,6 +179,14 @@ import {import { invalidateWorkersByLeadSingleFlight } from '../localDb/ipc/orcaWorkerListSingleFlight.js';import { messageToCamel } from '../localDb/mapper.js';import { visibleMessageTextForConversationSearch } from '../localDb/conversationSearch.pure.js';+import { persistSubagentTaskUpdate } from '../localDb/subagentRuns.js';+import { broadcastSubagentRunsChanged } from '../localDb/ipc/subagentRuns.js';+import {+ captureSubagentObservationGeneration,+ clearSubagentObservationRewindState,+ enqueueSubagentObservationWrite,+ noteSubagentObservationTurnStarted,+} from '../subagentObservationRewindFence.js';import {applyAgentSwitchToSessionRow,applyAgentSwitchResumeFallbackAtomically,@@ -3477,6 +3485,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidpendingFailedTurnAssistantPersistId.delete(session.id);// 记录 turn 开始时刻,供 onTurnErrorEvent 判断 error 是否属于 /clear 之前的旧 turn。noteTurnStarted(session.id);+ noteSubagentObservationTurnStarted(session.id);// silent-stop 守卫:新 turn 开始 → 清 pendingResume + 记录时刻(陈旧判定)。silentStopAutoResumeGuard.noteTurnStarted(session.id);interruptedTurnAutoResumeGuard.noteTurnStarted(session.id, {@@ -3731,6 +3740,43 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voideventAgentMeta,);}+ if (event.type === 'agent_task_update') {+ // Subagent workspace is an observer only: normalize the existing+ // harness event into Cindy's durable record on the same FIFO as chat+ // messages. No launch/control path or provider payload is modified.+ const source =+ event.source === 'claude-code' || event.source === 'codex' || event.source === 'pi'+ ? event.source+ : undefined;+ const observedAt = Date.now();+ const generationStamp = captureSubagentObservationGeneration({+ sessionId: session.id,+ data: event.data,+ source,+ });+ if (generationStamp) void enqueueSubagentObservationWrite({+ sessionId: session.id,+ stamp: generationStamp,+ enqueue: () =>+ enqueueDurableWrite(`subagent_update:${session.id}`, async (ownerScope) => {+ const persisted = await persistSubagentTaskUpdate(+ session.id,+ event.data,+ source,+ observedAt,+ );+ if (persisted) {+ broadcastSubagentRunsChanged({ sessionId: session.id, ...persisted }, ownerScope);+ }+ return persisted;+ }),+ }).catch((error) => {+ log.warn('Subagent workspace persistence failed', {+ sessionId: session.id,+ error: error instanceof Error ? error.message : String(error),+ });+ });+ }// 先 broadcast 保 UI 实时性,再 flush(flush 只入队、不阻塞)。// Keep the raw event for main-side coordination/persistence, but only// cross renderer/device-link boundaries with the redacted copy.@@ -4782,6 +4828,12 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// 后台活动检测:会话进程已关闭(closeSession / 删除),清账并广播横幅熄灭。clearClaudeSessionBackgroundActivity(session.id);clearSessionPersistState(session.id);+ const subagentRewindStateCleared = clearSubagentObservationRewindState(session.id);+ if (!subagentRewindStateCleared) {+ log.warn('session close deferred active Subagent Rewind cleanup', {+ sessionId: session.id,+ });+ }// 进程关闭 ≠ 通知作废:临时会话调度(非 heartbeat / 非 persistentSession)在 run// 终态后立刻 closeSession,此刻完成卡片刚在灵动岛上弹出来。硬删条目会让它当场// 消失,所以这条路径保留仍在展示的卡片,由 dwell 到期或用户 ack 收掉。@@ -6712,16 +6764,28 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)getLiveSession: (sessionId) => maker.getSession(sessionId),hasBackgroundActivity: getClaudeSessionBackgroundActivity,closeSession: (sessionId) => maker.closeSession(sessionId),+ drainPersistQueue,commitDeletion: commitMessageDeletion,setPendingHandoff: (sessionId, handoff, expectedGeneration) =>agentHandoffPending.set(sessionId, handoff, expectedGeneration),readPendingHandoffGeneration: (sessionId) => agentHandoffPending.readGeneration(sessionId),- onCommitted: ({ sessionId, deletedClientIds, updatedAt, preview }, requestedClientId) => {+ onCommitted: (+ { sessionId, deletedClientIds, subagentRunIds, updatedAt, preview },+ requestedClientId,+ ) => {broadcastMessageDeleted({sessionId,clientId: requestedClientId,clientIds: deletedClientIds,});+ for (const runId of subagentRunIds) {+ broadcastSubagentRunsChanged({+ sessionId,+ runId,+ created: false,+ firstForSession: false,+ });+ }// 不带 _count:可见消息数不是列表的权威口径,拿它 patch 的错值会被 shallow merge 一直// 留住;权威口径受删除影响只有 0 或 +1,交给 sessions:list / reseed 收敛就够。// 见 commitMessageDeletion 的注释与 issue #1282。@@ -12878,6 +12942,13 @@ function redactEventForRenderer(event: AgentEvent): AgentEvent {const data = event.data as Record<string, unknown>;const safeData = { ...data };let changed = false;+ // Main consumes this Cindy-owned durable projection marker before the event+ // crosses renderer/device-link boundaries. Live task-card payloads therefore+ // keep their existing wire shape and older mobile clients need no upgrade.+ if (event.type === 'agent_task_update' && 'subagentObservation' in safeData) {+ delete safeData.subagentObservation;+ changed = true;+ }for (const key of ['message', 'sdkError'] as const) {if (typeof safeData[key] === 'string') {const redacted = redactSensitiveText(safeData[key]);diff --git a/apps/desktop/src/main/maker-ipc/rewind.ts b/apps/desktop/src/main/maker-ipc/rewind.tsindex c6e9f0caed..50ee7698e2 100644--- a/apps/desktop/src/main/maker-ipc/rewind.ts+++ b/apps/desktop/src/main/maker-ipc/rewind.ts@@ -12,7 +12,20 @@ import { ipcMain } from 'electron';import { createLogger } from '../logger.js';import { previewRewindAtMessage, commitRewindAtMessage } from '../maker-orchestration/rewind.js';+import { drainPersistQueue } from '../messagePersistBroadcaster.js';import { getGoalController } from '../goal-host/index.js';+import { captureDataOwnerBroadcastScope } from '../device-link/broadcast-tap.js';+import { broadcastSubagentRunsInvalidated } from '../localDb/ipc/subagentRuns.js';+import {+ listVisibleSubagentObservationIdentities,+ type VisibleSubagentObservationIdentity,+} from '../localDb/subagentRuns.js';+import {+ beginSubagentRewindFence,+ finishSubagentRewindFence,+ primeSubagentRewindFence,+ type SubagentRewindFence,+} from '../subagentObservationRewindFence.js';import { isIpcError, type IpcErrorCode } from '../../shared/ipc-errors.js';import { requireString, throwIpcError } from '../utils/ipcValidate.js';@@ -32,7 +45,7 @@ async function commitAfterStopping(const deadline = Date.now() + STOPPED_REWIND_TIMEOUT_MS;while (true) {try {- return await commitRewindAtMessage(sessionId, clientId, opts);+ return await commitAfterPersistBarrier(sessionId, clientId, opts);} catch (err) {if (!isIpcError(err) || err.code !== 'SESSION_RUNNING' || Date.now() >= deadline) {throw err;@@ -42,6 +55,20 @@ async function commitAfterStopping(}}+async function commitAfterPersistBarrier(+ sessionId: string,+ clientId: string,+ opts: { requireLatestUser: boolean },+) {+ // Rewind must see every chat/Subagent observation that was already queued+ // before its transaction chooses the visible tail. Otherwise a delayed+ // spawn can be inserted after the transaction with rewind_at=NULL and make+ // withdrawn work visible again. Drain first, then let commitRewindAtMessage+ // reload its target and transaction boundary from the durable store.+ await drainPersistQueue();+ return commitRewindAtMessage(sessionId, clientId, opts);+}+function wrapErr(err: unknown): never {const code: IpcErrorCode = isIpcError(err) ? err.code : 'INTERNAL';const msg = err instanceof Error ? err.message : String(err);@@ -77,6 +104,7 @@ export function registerMakerRewindIpc(): void {) => {const sid = requireString(sessionId, 'sessionId');const cid = requireString(clientId, 'clientId');+ const ownerScope = captureDataOwnerBroadcastScope();// edit-last-message 专用可选项:要求 target 必须是会话最新 user 消息,// 在 main 侧权威校验(renderer 的切片判定有 TOCTOU 窗口)。普通 Rewind// 不传 → 保持"可回到任意历史消息"的既有语义。@@ -86,13 +114,30 @@ export function registerMakerRewindIpc(): void {const stopIfRunning =!!opts && typeof opts === 'object' &&(opts as { stopIfRunning?: unknown }).stopIfRunning === true;+ let subagentFence: SubagentRewindFence | null = null;+ // This flag controls observation-generation advancement, not whether+ // the underlying message transaction has already committed.+ let fenceCommitted = false;+ let visibleSubagentIdentitiesAfterCommit: VisibleSubagentObservationIdentity[] = [];try {+ subagentFence = beginSubagentRewindFence(sid);+ primeSubagentRewindFence(+ subagentFence,+ await listVisibleSubagentObservationIdentities(sid),+ );// Normal Rewind owns stop -> authoritative idle -> commit as one main// transaction. Edit-last-message keeps its existing direct orchestration.const result = stopIfRunning? await withSessionInputStoppedForRewind(sid, () =>commitAfterStopping(sid, cid, { requireLatestUser }))- : await commitRewindAtMessage(sid, cid, { requireLatestUser });+ : await commitAfterPersistBarrier(sid, cid, { requireLatestUser });+ visibleSubagentIdentitiesAfterCommit =+ await listVisibleSubagentObservationIdentities(sid);+ // The fence may advance generations only after the post-commit+ // identity refresh succeeds. A failed refresh must take the same+ // rollback path as any other rewind failure so buffered observations+ // are not discarded behind an empty survivor set.+ fenceCommitted = true;// 回滚后缓存的待注入交接 / fork 来源标记都是按截断前的历史算出来的,丢弃它,// 让下次 send 按回滚后的现状重新判定——被回滚掉的正是当初携带来源标记的那一轮时,// DB 侧判定会自动重新 arm(它按 rewind_at 过滤)。@@ -100,10 +145,19 @@ export function registerMakerRewindIpc(): void {// 回滚后会话历史被截断,active 目标若继续就会对着变化后的上下文跑 —— 暂停它// (保留计数,用户 review 后可 resume)。fire-and-forget,失败不阻塞 rewind。void getGoalController()?.pauseGoal(sid, 'paused: conversation rewound').catch(() => {});+ broadcastSubagentRunsInvalidated(sid, ownerScope);return result;} catch (err) {log.warn('rewind:commit failed', { sid, cid, error: String(err) });wrapErr(err);+ } finally {+ if (subagentFence) {+ finishSubagentRewindFence(+ subagentFence,+ fenceCommitted,+ visibleSubagentIdentitiesAfterCommit,+ );+ }}},);diff --git a/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.ts b/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.tsindex 60501519d3..dc3b1b50e5 100644--- a/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.ts+++ b/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.ts@@ -376,6 +376,64 @@ describe('right-sidebar-window IPC', () => {).rejects.toThrow(/request.userInitiated/);});+ it('requires a provider-scoped Subagent focus and forwards the pair together', async () => {+ const controller = makeController();+ const { handler, mainWebContents } = registerController(controller);++ await handler(+ { sender: mainWebContents },+ {+ command: {+ type: 'open-subagents-tab',+ sessionId: 's1',+ focusRunId: 'shared-native-id',+ focusProvider: 'codex',+ focusTab: true,+ },+ allowOpen: true,+ },+ );++ expect(controller.routeCommand).toHaveBeenCalledWith({+ command: {+ type: 'open-subagents-tab',+ sessionId: 's1',+ focusRunId: 'shared-native-id',+ focusProvider: 'codex',+ focusTab: true,+ },+ allowOpen: true,+ });++ await expect(+ handler(+ { sender: mainWebContents },+ {+ command: {+ type: 'open-subagents-tab',+ sessionId: 's1',+ focusRunId: 'shared-native-id',+ },+ allowOpen: true,+ },+ ),+ ).rejects.toThrow(/focusRunId and command.focusProvider/);+ await expect(+ handler(+ { sender: mainWebContents },+ {+ command: {+ type: 'open-subagents-tab',+ sessionId: 's1',+ focusRunId: 'shared-native-id',+ focusProvider: 'other-harness',+ },+ allowOpen: true,+ },+ ),+ ).rejects.toThrow(/focusProvider/);+ });+it('open payload:缺省/空 = 用户手势;显式 false 透传;野值拒绝', async () => {const controller = makeController();registerController(controller);diff --git a/apps/desktop/src/main/right-sidebar-window/ipc.ts b/apps/desktop/src/main/right-sidebar-window/ipc.tsindex ba9db24f99..742231a06c 100644--- a/apps/desktop/src/main/right-sidebar-window/ipc.ts+++ b/apps/desktop/src/main/right-sidebar-window/ipc.ts@@ -8,10 +8,11 @@import { ipcMain } from 'electron';import type { BrowserWindow } from 'electron';+import type { SubagentProvider } from '@cindy/maker-shared/subagent-workspace';import { MAKER_INVOKE, MAKER_SEND } from '../maker-ipc/channels.js';import { createLogger } from '../logger.js';-import { requireObject, throwIpcError } from '../utils/ipcValidate.js';+import { requireEnum, requireObject, throwIpcError } from '../utils/ipcValidate.js';import type {RsbWindowCommand,RsbWindowCommandRouteRequest,@@ -22,6 +23,11 @@ import { hasActiveRsbNativePopupSurfaces } from '../rsb-browser-bridge/native-poimport type { RsbWindowController } from './controller.js';const log = createLogger('right-sidebar-window-ipc');+const SUBAGENT_PROVIDERS = [+ 'claude-code',+ 'codex',+ 'pi',+] as const satisfies readonly SubagentProvider[];function parseContext(raw: unknown): RsbWindowContext {const r = requireObject(raw, 'context');@@ -105,6 +111,48 @@ function parseCommand(raw: unknown): RsbWindowCommand {...(hasFocusTaskId ? { focusTaskId: r.focusTaskId as string | null } : {}),};}+ if (r.type === 'open-subagents-tab') {+ const hasFocusRunId =+ Object.prototype.hasOwnProperty.call(r, 'focusRunId') && r.focusRunId !== undefined;+ const hasFocusProvider =+ Object.prototype.hasOwnProperty.call(r, 'focusProvider') && r.focusProvider !== undefined;+ if (hasFocusRunId && r.focusRunId !== null && typeof r.focusRunId !== 'string') {+ throwIpcError('INVALID_PARAMS', 'command.focusRunId must be string | null');+ }+ const focusProvider = r.focusProvider === null || !hasFocusProvider+ ? r.focusProvider as null | undefined+ : requireEnum(r.focusProvider, SUBAGENT_PROVIDERS, 'command.focusProvider');+ const hasRunFocus = typeof r.focusRunId === 'string' && r.focusRunId.length > 0;+ const hasProviderFocus = typeof focusProvider === 'string';+ if (hasRunFocus !== hasProviderFocus) {+ throwIpcError(+ 'INVALID_PARAMS',+ 'command.focusRunId and command.focusProvider must be provided together',+ );+ }+ if (+ Object.prototype.hasOwnProperty.call(r, 'focusTab') &&+ r.focusTab !== undefined &&+ typeof r.focusTab !== 'boolean'+ ) {+ throwIpcError('INVALID_PARAMS', 'command.focusTab must be boolean');+ }+ if (+ Object.prototype.hasOwnProperty.call(r, 'revealSidebar') &&+ r.revealSidebar !== undefined &&+ typeof r.revealSidebar !== 'boolean'+ ) {+ throwIpcError('INVALID_PARAMS', 'command.revealSidebar must be boolean');+ }+ return {+ type: 'open-subagents-tab',+ sessionId: r.sessionId,+ ...(hasFocusRunId ? { focusRunId: r.focusRunId as string | null } : {}),+ ...(hasFocusProvider ? { focusProvider } : {}),+ ...(typeof r.focusTab === 'boolean' ? { focusTab: r.focusTab } : {}),+ ...(typeof r.revealSidebar === 'boolean' ? { revealSidebar: r.revealSidebar } : {}),+ };+ }if (r.type === 'open-turn-review') {if (!Array.isArray(r.changeSetIds)diff --git a/apps/desktop/src/main/subagentObservationRewindFence.ts b/apps/desktop/src/main/subagentObservationRewindFence.tsnew file mode 100644index 0000000000..9c61d0f5b7--- /dev/null+++ b/apps/desktop/src/main/subagentObservationRewindFence.ts@@ -0,0 +1,265 @@+import {+ normalizeAgentTaskUpdate,+ type AgentTaskUpdate,+} from '@cindy/maker-shared/agent-task';+import {+ normalizeSubagentObservation,+ type SubagentObservation,+} from '@cindy/maker-shared/subagent-observation';+import type { SubagentProvider } from '@cindy/maker-shared/subagent-workspace';++interface PendingObservationWrite<T> {+ generation: number;+ taskKey: string;+ enqueue: () => Promise<T>;+ resolve: (value: T | null) => void;+ reject: (error: unknown) => void;+}++interface SessionFenceState {+ generation: number;+ acceptsNewTasks: boolean;+ activeToken: symbol | null;+ clearRequested: boolean;+ clearTimer: ReturnType<typeof setTimeout> | null;+ taskGenerations: Map<string, number>;+ pending: PendingObservationWrite<unknown>[];+}++export interface SubagentRewindFence {+ sessionId: string;+ token: symbol;+}++export interface VisibleSubagentIdentity {+ provider: SubagentProvider;+ identities: readonly string[];+}++export interface SubagentObservationGenerationStamp {+ generation: number;+ taskKey: string;+}++const stateBySession = new Map<string, SessionFenceState>();+const DEFERRED_CLEAR_TIMEOUT_MS = 30_000;++function dropSessionState(sessionId: string, state: SessionFenceState): void {+ if (state.clearTimer) {+ clearTimeout(state.clearTimer);+ state.clearTimer = null;+ }+ for (const item of state.pending.splice(0)) item.resolve(null);+ state.activeToken = null;+ if (stateBySession.get(sessionId) === state) stateBySession.delete(sessionId);+}++function sessionState(sessionId: string): SessionFenceState {+ let state = stateBySession.get(sessionId);+ if (!state) {+ state = {+ generation: 0,+ acceptsNewTasks: true,+ activeToken: null,+ clearRequested: false,+ clearTimer: null,+ taskGenerations: new Map(),+ pending: [],+ };+ stateBySession.set(sessionId, state);+ }+ return state;+}++function observationFrom(data: unknown): SubagentObservation | null {+ if (!data || typeof data !== 'object' || Array.isArray(data)) return null;+ return normalizeSubagentObservation(+ (data as Record<string, unknown>).subagentObservation,+ );+}++function taskKey(update: AgentTaskUpdate, observation: SubagentObservation | null): string {+ return `${update.provider}:${observation?.logicalSubagentId ?? update.taskId}`;+}++function visibleIdentityKeys(visible: readonly VisibleSubagentIdentity[]): Set<string> {+ const keys = new Set<string>();+ for (const row of visible) {+ for (const identity of row.identities) {+ if (identity) keys.add(`${row.provider}:${identity}`);+ }+ }+ return keys;+}++function generationForObservation(+ state: SessionFenceState,+ update: AgentTaskUpdate,+ observation: SubagentObservation | null,+): number | null {+ const key = taskKey(update, observation);+ const known = state.taskGenerations.get(key);+ if (known !== undefined) return known;+ if (!state.acceptsNewTasks) return null;+ // A process can reattach to a native child and receive progress/terminal+ // without replaying spawn. Treat an unknown identity as current; the Rewind+ // snapshot below primes every already-visible durable alias, so those old+ // lifecycles remain on their prior generation after a successful commit.+ state.taskGenerations.set(key, state.generation);+ return state.generation;+}++function enqueuePending<T>(pending: PendingObservationWrite<T>): void {+ void pending.enqueue().then(pending.resolve, pending.reject);+}++/**+ * Start the session-local critical section before Stop / SDK rollback begins.+ * Observations arriving until commit/rollback are held outside the global+ * durable FIFO, so a long Rewind cannot stall unrelated chat/session writes.+ */+export function beginSubagentRewindFence(sessionId: string): SubagentRewindFence {+ let state = sessionState(sessionId);+ if (state.activeToken && state.clearRequested) {+ dropSessionState(sessionId, state);+ state = sessionState(sessionId);+ }+ if (state.activeToken) {+ throw new Error(`Subagent Rewind already active for session ${sessionId}`);+ }+ const token = Symbol(`subagent-rewind:${sessionId}`);+ state.activeToken = token;+ return { sessionId, token };+}++/** Add durable identities read after the fence was raised but before commit. */+export function primeSubagentRewindFence(+ fence: SubagentRewindFence,+ visible: readonly VisibleSubagentIdentity[],+): void {+ const state = stateBySession.get(fence.sessionId);+ if (!state || state.activeToken !== fence.token) return;+ for (const key of visibleIdentityKeys(visible)) {+ if (!state.taskGenerations.has(key)) state.taskGenerations.set(key, state.generation);+ }+}++/**+ * Finish a Rewind fence. Success advances the session generation, migrates+ * identities that remain visible after commit, replays their buffered frames,+ * and discards frames belonging to the withdrawn branch. Failure keeps the+ * generation and replays every buffered write in original arrival order.+ */+export function finishSubagentRewindFence(+ fence: SubagentRewindFence,+ committed: boolean,+ visibleAfterCommit: readonly VisibleSubagentIdentity[] = [],+): void {+ const state = stateBySession.get(fence.sessionId);+ if (!state || state.activeToken !== fence.token) return;+ if (state.clearRequested) {+ dropSessionState(fence.sessionId, state);+ return;+ }+ state.activeToken = null;+ const pending = state.pending.splice(0);+ if (committed) {+ state.generation += 1;+ state.acceptsNewTasks = false;+ const visibleKeys = visibleIdentityKeys(visibleAfterCommit);+ for (const key of visibleKeys) state.taskGenerations.set(key, state.generation);+ for (const item of pending) {+ if (visibleKeys.has(item.taskKey)) enqueuePending(item);+ else item.resolve(null);+ }+ return;+ }+ for (const item of pending) {+ if (item.generation === state.generation) enqueuePending(item);+ else item.resolve(null);+ }+}++/** The next provider turn is authoritative permission to accept new task ids. */+export function noteSubagentObservationTurnStarted(sessionId: string): void {+ let state = sessionState(sessionId);+ if (state.clearRequested) {+ dropSessionState(sessionId, state);+ state = sessionState(sessionId);+ }+ state.acceptsNewTasks = true;+}++/**+ * Persist one marked Subagent observation under the task generation captured+ * at its first spawn. Old-task duplicate/out-of-order frames stay rejected+ * after a successful Rewind, while a new task id after commit joins the new+ * generation normally. This is provider-neutral and leaves native harness+ * creation/control flows untouched.+ */+export function captureSubagentObservationGeneration(args: {+ sessionId: string;+ data: unknown;+ source?: SubagentProvider;+}): SubagentObservationGenerationStamp | null {+ const update = normalizeAgentTaskUpdate(args.data, args.source);+ if (!update) return null;+ const observation = observationFrom(args.data);+ const state = sessionState(args.sessionId);+ const key = taskKey(update, observation);+ const generation = generationForObservation(state, update, observation);+ return generation === null ? null : { generation, taskKey: key };+}++export function enqueueSubagentObservationWrite<T>(args: {+ sessionId: string;+ stamp: SubagentObservationGenerationStamp;+ enqueue: () => Promise<T>;+}): Promise<T | null> {+ const state = sessionState(args.sessionId);+ const generation = args.stamp.generation;+ if (generation !== state.generation) return Promise.resolve(null);++ if (!state.activeToken) return args.enqueue();++ return new Promise<T | null>((resolve, reject) => {+ state.pending.push({+ generation,+ taskKey: args.stamp.taskKey,+ enqueue: args.enqueue,+ resolve,+ reject,+ } as PendingObservationWrite<unknown>);+ });+}++export function clearSubagentObservationRewindState(sessionId: string): boolean {+ const state = stateBySession.get(sessionId);+ if (!state) return true;+ if (state.activeToken) {+ state.clearRequested = true;+ if (!state.clearTimer) {+ const activeToken = state.activeToken;+ state.clearTimer = setTimeout(() => {+ const current = stateBySession.get(sessionId);+ if (+ current === state &&+ current.clearRequested &&+ current.activeToken === activeToken+ ) {+ dropSessionState(sessionId, current);+ }+ }, DEFERRED_CLEAR_TIMEOUT_MS);+ state.clearTimer.unref?.();+ }+ return false;+ }+ dropSessionState(sessionId, state);+ return true;+}++export function __resetSubagentObservationRewindStateForTesting(): void {+ for (const [sessionId, state] of stateBySession) {+ dropSessionState(sessionId, state);+ }+}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 6aa94c69f0..ca88ac6528 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -1782,7 +1782,9 @@ contextBridge.exposeInMainWorld('electronAPI', {| { kind: 'conflict'; appId: string }| { kind: 'error'; reason: string };}> => ipcRenderer.invoke('discordBot:disconnect'),- setLifecycleAnnouncement: (enabled: boolean): Promise<{+ setLifecycleAnnouncement: (+ enabled: boolean,+ ): Promise<{ok: boolean;lifecycleAnnouncement: boolean;}> => ipcRenderer.invoke('discordBot:set-lifecycle-announcement', { enabled }),@@ -2073,10 +2075,12 @@ contextBridge.exposeInMainWorld('electronAPI', {/*** 被控端本地 main → 自身 renderer:控制端写穿的「新建会话默认启用 worktree」,* renderer 收到后 patchDraft 写真实草稿。仅被控端进程消费。- */+ */onMakerWorktreePrefApply: fanOutMakerWorktreePrefApply,/** 读取工作端 canonical baseRepo 对应的 live 源分支选择;未选择返回 null。 */- getNewMakerWorktreeBranchPreference: (baseRepo: string): Promise<{+ getNewMakerWorktreeBranchPreference: (+ baseRepo: string,+ ): Promise<{baseRepo: string;sourceBranch: string;revision: number;@@ -4479,6 +4483,13 @@ contextBridge.exposeInMainWorld('electronAPI', {/** 按 sessionId 拉 tab 列表 + activeTabId。 */list: (input: { sessionId: string }): Promise<unknown> =>ipcRenderer.invoke('local-db:right-sidebar-tabs:list', input),+ /** Atomically creates or returns one canonical tab for a singleton kind. */+ ensureSingleton: (input: {+ sessionId: string;+ kind: string;+ state?: unknown;+ }): Promise<unknown> =>+ ipcRenderer.invoke('local-db:right-sidebar-tabs:ensure-singleton', input),/** 新增 / 更新单个 tab(state JSON / position / kind)。state 缺省 → '{}'。 */upsert: (input: {id: string;@@ -4497,6 +4508,17 @@ contextBridge.exposeInMainWorld('electronAPI', {reorder: (input: { sessionId: string; orderedIds: string[] }): Promise<unknown> =>ipcRenderer.invoke('local-db:right-sidebar-tabs:reorder', input),},+ subagentRuns: {+ /** Durable Cindy-owned Subagent records for one parent task. */+ list: (input: { sessionId: string }): Promise<unknown> =>+ ipcRenderer.invoke('local-db:subagent-runs:list', input),+ /** Activity and returned result for one durable Subagent record. */+ detail: (+ input: import('@cindy/maker-shared/subagent-workspace').SubagentRunDetailRequest,+ ): Promise<unknown> => ipcRenderer.invoke('local-db:subagent-runs:detail', input),+ /** Small invalidation push; consumers re-read through list/detail. */+ onChanged: createIpcFanOut('local-db:subagent-runs:changed'),+ },projectAliases: {list: (): Promise<unknown> => ipcRenderer.invoke('local-db:project-aliases:list'),set: (input: { projectKey: string; alias: string }): Promise<unknown> =>@@ -5234,8 +5256,7 @@ contextBridge.exposeInMainWorld('electronAPI', {workerSessionId: string;workerId: string;workerPermissionMode: 'auto' | 'bypassPermissions';- }> =>- ipcRenderer.invoke('maker:session:enable-orca', leadSessionId, opts),+ }> => ipcRenderer.invoke('maker:session:enable-orca', leadSessionId, opts),/*** F-COLLAB: 关闭 lead session 的当前协同 workflow。diff --git a/apps/desktop/src/renderer/__tests__/AgentTaskCard.test.ts b/apps/desktop/src/renderer/__tests__/AgentTaskCard.test.tsindex 56c2f14e6b..9b3ca9fdcf 100644--- a/apps/desktop/src/renderer/__tests__/AgentTaskCard.test.ts+++ b/apps/desktop/src/renderer/__tests__/AgentTaskCard.test.ts@@ -31,12 +31,16 @@ vi.mock('@/hooks/useExpandedBlockMemory', () => ({}),}));-const { openBackgroundTasksTabMock } = vi.hoisted(() => ({+const { openBackgroundTasksTabMock, openSubagentsTabMock } = vi.hoisted(() => ({openBackgroundTasksTabMock: vi.fn().mockResolvedValue(undefined),+ openSubagentsTabMock: vi.fn().mockResolvedValue(undefined),}));vi.mock('@/features/right-sidebar/lib/openBackgroundTasksTab', () => ({openBackgroundTasksTab: openBackgroundTasksTabMock,}));+vi.mock('@/features/right-sidebar/lib/openSubagentsTab', () => ({+ openSubagentsTab: openSubagentsTabMock,+}));const { getWorkflowProgressForMock } = vi.hoisted(() => ({getWorkflowProgressForMock: vi.fn().mockResolvedValue(null),@@ -515,8 +519,9 @@ describe('AgentTaskCard', () => {expect(progressLine(container)?.textContent).toBe('2/2 Agent');});- it('renders no progress line when workflowProgress is absent, and keeps non-workflow cards off the panel entry', () => {+ it('renders no workflow progress line and opens ordinary Subagents in their durable panel', () => {openBackgroundTasksTabMock.mockClear();+ openSubagentsTabMock.mockClear();const workflow = render(React.createElement(AgentTaskCard, {sessionId: 'session-1',@@ -531,23 +536,59 @@ describe('AgentTaskCard', () => {expect(progressLine(workflow.container)).toBeNull();const normal = render(- React.createElement(AgentTaskCard, {- sessionId: 'session-1',- update: {- provider: 'claude-code',- taskId: 'task-1',- status: 'running',- title: 'Inspect files',- },- }),+ withPanelHost(+ 'session-1',+ React.createElement(AgentTaskCard, {+ sessionId: 'session-1',+ update: {+ provider: 'claude-code',+ taskId: 'task-1',+ status: 'running',+ title: 'Inspect files',+ },+ }),+ ),);- // 普通卡头部仍是展开 toggle,不触发面板。- const toggleBtn = normal.container.querySelector<HTMLButtonElement>('button[aria-expanded]');- expect(toggleBtn).not.toBeNull();+ const subagentButton = headerButton(normal.container);+ expect(subagentButton).not.toBeNull();act(() => {- toggleBtn!.click();+ subagentButton!.click();});expect(openBackgroundTasksTabMock).not.toHaveBeenCalled();+ expect(openSubagentsTabMock).toHaveBeenCalledWith('session-1', {+ focusRunId: 'task-1',+ focusProvider: 'claude-code',+ });expect(progressLine(normal.container)).toBeNull();});++ it('keeps Codex control cards expandable instead of opening a nonexistent Subagent run', () => {+ openSubagentsTabMock.mockClear();+ const { container } = render(+ withPanelHost(+ 'session-1',+ React.createElement(AgentTaskCard, {+ sessionId: 'session-1',+ toolCall: {+ clientId: 'wait-1',+ role: 'tool_use',+ content: '',+ toolName: 'collab:wait',+ toolUseId: 'wait-1',+ },+ update: {+ provider: 'codex',+ taskId: 'wait-1',+ status: 'completed',+ title: 'wait',+ },+ }),+ ),+ );++ const toggleButton = container.querySelector<HTMLButtonElement>('button[aria-expanded]');+ expect(toggleButton).not.toBeNull();+ act(() => toggleButton!.click());+ expect(openSubagentsTabMock).not.toHaveBeenCalled();+ });});diff --git a/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx b/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsxindex 0fcdb5b738..1bd22c6d3d 100644--- a/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx+++ b/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx@@ -20,6 +20,7 @@ import { Spinner } from '@/components/ui/spinner';import type { AgentTaskUpdate, ChatMessage } from '@/hooks/useCCAgentChat';import { getWorkflowProgressFor, isRemoteSessionSticky } from '@/lib/makerTransport';import { openBackgroundTasksTab } from '@/features/right-sidebar/lib/openBackgroundTasksTab';+import { openSubagentsTab } from '@/features/right-sidebar/lib/openSubagentsTab';import { extractWorkflowTaskId } from '@/features/right-sidebar/plugins/background-tasks/listSessionTasks';import { WorkflowAgentStrip } from '@/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip';import {@@ -31,6 +32,7 @@ import { cn } from '@/lib/utils';import { formatModelShortLabel } from '@/lib/modelShortLabel';import { CODEX_SUBAGENT_EFFORTS } from '../../../shared/subagentModelSettings';import {+ isSubagentSpawnToolName,PI_SUBAGENT_TOOL_NAME,subagentSpawnReceiptName,subagentSpawnResultIndicatesRunning,@@ -220,6 +222,10 @@ export function AgentTaskCard({ toolCall, update, result, subagentModel, session// 是「后台命令」—— 终端图标 + shell provider 标签,避免用户把跑测试的 bash// 误读成一个子 Agent。const isBash = update?.taskType === 'local_bash';+ const isSubagent =+ !isWorkflow &&+ !isBash &&+ (!toolCall?.toolName || isSubagentSpawnToolName(toolCall.toolName));const AvatarIcon = isWorkflow ? Workflow : isBash ? SquareTerminal : Bot;const title = compactText((isWorkflow ? update?.workflowName : undefined) ??@@ -287,19 +293,39 @@ export function AgentTaskCard({ toolCall, update, result, subagentModel, session.finally(() => setStopping(false));}, [sessionId, update?.taskId]);- // workflow 卡整卡点击 → 打开右栏后台任务面板并定位本任务(workflowTaskId 在- // 组件顶部与状态修正共用同一次推导)。三者缺一就退回传统展开交互,让- // description/summary 就地可读,不做「点了没反应」的假入口。+ // workflow / Subagent 卡整卡点击 → 打开对应 Cindy 右栏工作区并定位本任务。+ // Subagent 使用 Cindy 逻辑 id、父 toolUseId 等任一已知别名;工作区会把别名+ // 解析成持久 run id,因此三种 harness 不需要共享原生 thread/session 形态。+ // 定位信息不全时退回传统展开交互,让 description/summary 就地可读,不做+ // 「点了没反应」的假入口。//// panelReachable:内嵌宿主(协同 worker 面板 / workdir-browse 窄 rail / Orca// split)里右栏显示的是别的会话(或压根没在场),往本会话 bucket 写 tab 用户看// 不到 —— 那里必须退回展开区,否则卡片既点不动、又因面板入口化丢掉了展开区。const panelReachable = useSidebarPanelReachable(sessionId);- const canOpenInPanel = Boolean(sessionId) && Boolean(workflowTaskId) && panelReachable;- const openInPanel = useCallback(() => {+ const subagentFocusId =+ update?.taskId ?? update?.parentToolUseId ?? toolCall?.toolUseId ?? toolCall?.clientId;+ const canOpenWorkflowPanel =+ isWorkflow && Boolean(sessionId) && Boolean(workflowTaskId) && panelReachable;+ const canOpenSubagentPanel =+ isSubagent && Boolean(sessionId) && Boolean(subagentFocusId) && panelReachable;+ const canOpenInPanel = canOpenWorkflowPanel || canOpenSubagentPanel;+ const openWorkflowPanel = useCallback(() => {if (!sessionId || !workflowTaskId) return;void openBackgroundTasksTab(sessionId, { focusTaskId: workflowTaskId });}, [sessionId, workflowTaskId]);+ const openSubagentPanel = useCallback(() => {+ if (!sessionId || !subagentFocusId) return;+ void openSubagentsTab(sessionId, {+ focusRunId: subagentFocusId,+ focusProvider: provider,+ });+ }, [provider, sessionId, subagentFocusId]);+ const handleHeaderClick = canOpenWorkflowPanel+ ? openWorkflowPanel+ : canOpenSubagentPanel+ ? openSubagentPanel+ : toggle;// workflow 摘要行:当前运行中 agent 的 phaseTitle + 已收口/总数。收口判定走// workflowAgentVisualState 归一(与方块条 / 面板同一词表源,done 与 failed 都算收口)。@@ -358,14 +384,14 @@ export function AgentTaskCard({ toolCall, update, result, subagentModel, session{...(toolCall?.clientId ? { 'data-message-client-id': toolCall.clientId } : {})}><div className="w-full rounded-[12px] border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 py-2">- {/* 头部按钮:普通卡 = 展开 toggle;workflow 卡 = 打开后台任务面板入口。+ {/* 头部按钮:可达的 workflow/Subagent 卡 = 右栏详情入口;其余 = 展开 toggle。button 不能嵌套,停止按钮以兄弟节点挂在右侧(仅 running 时出现)。 */}<div className="flex w-full items-start gap-2"><buttontype="button"- onClick={isWorkflow && canOpenInPanel ? openInPanel : toggle}+ onClick={handleHeaderClick}className="flex min-w-0 flex-1 items-start gap-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"- {...(isWorkflow && canOpenInPanel+ {...(canOpenInPanel? { 'aria-label': t('chat.agentTask.openInPanel') }: {'aria-expanded': expanded,@@ -432,7 +458,7 @@ export function AgentTaskCard({ toolCall, update, result, subagentModel, session</span>)}</span>- {isWorkflow && canOpenInPanel ? (+ {canOpenInPanel ? (<PanelRightsize={14}className="mt-1 shrink-0 text-[var(--text-tertiary)]"@@ -470,9 +496,9 @@ export function AgentTaskCard({ toolCall, update, result, subagentModel, session)}</div>- {/* live workflow 卡不渲染展开区(详情在后台任务面板);历史 workflow 卡- (无 live taskId,面板无数据)保留展开区兜底展示 description/summary。 */}- {!(isWorkflow && canOpenInPanel) && (+ {/* 能进入右栏的 workflow/Subagent 卡不再重复渲染就地展开区;+ 不可达的嵌入宿主/历史降级路径仍保留 description/summary。 */}+ {!canOpenInPanel && (<Collapse open={expanded}><div className="mt-2 border-l-2 border-[var(--agent-actions-rail)] pl-3 text-13 leading-5 text-[var(--text-secondary)]">{description && <p className="mb-1">{description}</p>}diff --git a/apps/desktop/src/renderer/components/chat/__tests__/AgentTaskCardModelChip.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/AgentTaskCardModelChip.test.tsxindex 44226bf505..1f05766a51 100644--- a/apps/desktop/src/renderer/components/chat/__tests__/AgentTaskCardModelChip.test.tsx+++ b/apps/desktop/src/renderer/components/chat/__tests__/AgentTaskCardModelChip.test.tsx@@ -21,6 +21,10 @@ vi.mock('@/features/right-sidebar/lib/openBackgroundTasksTab', () => ({openBackgroundTasksTab: vi.fn(),}));+vi.mock('@/features/right-sidebar/lib/openSubagentsTab', () => ({+ openSubagentsTab: vi.fn(),+}));+vi.mock('@/features/right-sidebar/plugins/background-tasks/listSessionTasks', () => ({extractWorkflowTaskId: () => undefined,}));diff --git a/apps/desktop/src/renderer/components/chat/__tests__/AgentTaskCardSubagentLive.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/AgentTaskCardSubagentLive.test.tsxindex a8b1d5ba2d..c052802523 100644--- a/apps/desktop/src/renderer/components/chat/__tests__/AgentTaskCardSubagentLive.test.tsx+++ b/apps/desktop/src/renderer/components/chat/__tests__/AgentTaskCardSubagentLive.test.tsx@@ -30,6 +30,10 @@ vi.mock('@/features/right-sidebar/lib/openBackgroundTasksTab', () => ({openBackgroundTasksTab: vi.fn(),}));+vi.mock('@/features/right-sidebar/lib/openSubagentsTab', () => ({+ openSubagentsTab: vi.fn(),+}));+vi.mock('@/features/right-sidebar/plugins/background-tasks/listSessionTasks', () => ({extractWorkflowTaskId: () => undefined,}));@@ -101,7 +105,7 @@ describe('AgentTaskCard codex subagent live state', () => {});it('keeps the localized receipt for history replay (no live update)', () => {- // 历史回放拿不到 live update(agent_task_update 不落库),回执是唯一可读摘要。+ // 聊天卡的历史回放不重建 live update;持久详情在独立 Subagent 面板。const { container } = render(<AgentTaskCard toolCall={spawnToolCall()} result="/root/scout" />);expect(container.textContent ?? '').toContain('chat.agentTask.subagentStarted');});diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex e54b5c064f..e59608658e 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -111,7 +111,11 @@ import { useSessionBinding } from '@/hooks/useSessionBinding';import { useVendorAuthGate } from '@/hooks/useVendorAuthGate';import { useProviders } from '@/hooks/useProviders';import { useAuth } from '@/contexts/AuthContext';-import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';+import {+ getDataOwnerGeneration,+ isDataOwnerGenerationCurrent,+ isDataOwnerPushCurrent,+} from '@/contexts/dataOwnerGeneration';import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';import { canAccessBillingSettings } from '@/components/settings/billingVisibility';import { useDeviceProviders } from '@/hooks/useDeviceProviders';@@ -160,6 +164,7 @@ import {type MessageDeliveryMode,} from '@/lib/makerChatStore';import { openBackgroundTasksTab } from '@/features/right-sidebar/lib/openBackgroundTasksTab';+import { openSubagentsTab } from '@/features/right-sidebar/lib/openSubagentsTab';import { subscribeChatTaskFocus } from '@/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent';import { canFocusWithoutJumpLoad } from '@/lib/searchJumpTargeting';import { getMakerMemoryEnabled } from '@/lib/memorySettingsStore';@@ -544,6 +549,54 @@ export function CCAgentSessionView({navigate('/settings?tab=providers');});}, [navigate, sessionId, viewVisible]);++ // A task that has Subagents owns one durable Subagent tab. On history mount+ // we silently ensure the tab exists; the first live child also reveals the+ // sidebar, without stealing OS focus or replacing an already-active tab.+ useEffect(() => {+ if (!ownsWindowRoute || !viewVisible || !sessionId) return;+ let disposed = false;+ const requestOwner = getDataOwnerGeneration();+ void window.electronAPI.localDb.subagentRuns+ .list({ sessionId })+ .then((response) => {+ if (+ disposed ||+ !isDataOwnerGenerationCurrent(requestOwner) ||+ !response.supported ||+ response.runs.length === 0+ ) {+ return;+ }+ return openSubagentsTab(sessionId, {+ focusTab: false,+ revealSidebar: false,+ userInitiated: false,+ });+ })+ .catch(() => undefined);+ const unsubscribe = window.electronAPI.localDb.subagentRuns.onChanged(+ (payload, ownerStamp) => {+ if (+ disposed ||+ !isDataOwnerPushCurrent(ownerStamp) ||+ payload.runId === null ||+ payload.sessionId !== sessionId+ ) {+ return;+ }+ void openSubagentsTab(sessionId, {+ focusTab: false,+ revealSidebar: payload.created && payload.firstForSession,+ userInitiated: false,+ }).catch(() => undefined);+ },+ );+ return () => {+ disposed = true;+ unsubscribe();+ };+ }, [ownsWindowRoute, sessionId, viewVisible]);// MainLayout 经 Outlet context 下发右栏相关能力(二级路由由 CCAgentFeatureLayout// 透传,否则这里会断链拿不到):// - rightSidebarCollapsed:折叠态,用于 useProportionalWidth 的 compact 判定;diff --git a/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx b/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsxindex bcfab15dbd..095e3be723 100644--- a/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx@@ -15,7 +15,7 @@import { useEffect, useLayoutEffect, useRef, useState } from 'react';import { createPortal } from 'react-dom';import { useTranslation } from 'react-i18next';-import { Activity, FileDiff, FolderTree, Globe, ListTodo, Terminal } from 'lucide-react';+import { Activity, Bot, FileDiff, FolderTree, Globe, ListTodo, Terminal } from 'lucide-react';import type { LucideIcon } from 'lucide-react';import { cn } from '@/lib/utils';import type { TabKindId, TabKindMenuMeta } from './types';@@ -58,6 +58,14 @@ const MENU_ITEMS: TabKindMenuMeta[] = [enabled: true,singleton: true,},+ {+ kind: 'subagents',+ labelKey: 'rightSidebar.tabs.kinds.subagents',+ icon: Bot,+ order: 16,+ enabled: true,+ singleton: true,+ },{kind: 'background-tasks',labelKey: 'rightSidebar.tabs.kinds.backgroundTasks',diff --git a/apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx b/apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsxindex 76dee875fa..2a14f7b4e7 100644--- a/apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx@@ -11,6 +11,7 @@import {Activity,+ Bot,ChevronRight,FileDiff,FolderOpen,@@ -27,6 +28,7 @@ interface EmptyStateProps {onAddBrowserTab: () => void;onAddTerminalTab: () => void;onAddReviewTab: () => void;+ onAddSubagentsTab: () => void;onAddBackgroundTasksTab: () => void;onAddResourceUsageTab: () => void;}@@ -36,6 +38,7 @@ export function EmptyState({onAddBrowserTab,onAddTerminalTab,onAddReviewTab,+ onAddSubagentsTab,onAddBackgroundTasksTab,onAddResourceUsageTab,}: EmptyStateProps) {@@ -71,6 +74,12 @@ export function EmptyState({/>{/* 后台任务:顺序与 + dropdown 一致(review order=15 → background-tasksorder=17 → browser order=20)。 */}+ <ActionRow+ icon={Bot}+ label={t('rightSidebar.tabs.empty.openSubagents')}+ sub={t('rightSidebar.tabs.empty.subagentsSub')}+ onClick={onAddSubagentsTab}+ /><ActionRowicon={ListTodo}label={t('rightSidebar.tabs.empty.openBackgroundTasks')}diff --git a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsxindex 46c4fd5ac5..fca641b814 100644--- a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx@@ -506,6 +506,7 @@ export function RightSidebarShell({<EmptyStateonAddFileTab={() => handleAdd('file-browser')}onAddReviewTab={() => handleAdd('review')}+ onAddSubagentsTab={() => handleAdd('subagents')}onAddBackgroundTasksTab={() => handleAdd('background-tasks')}onAddResourceUsageTab={() => handleAdd('resource-usage')}onAddBrowserTab={() => handleAdd('web-browser')}diff --git a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsxindex 577f4fbd31..55e7133a2c 100644--- a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx@@ -21,6 +21,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import {Activity,+ Bot,FolderTree,Globe,Terminal,@@ -122,6 +123,7 @@ const KIND_ICON: Record<BuiltinTabKindId, LucideIcon> = {terminal: Terminal,review: GitPullRequestArrow,'orca-workers': UsersRound,+ subagents: Bot,'background-tasks': ListTodo,'resource-usage': Activity,};@@ -132,6 +134,7 @@ const KIND_LABEL_KEY: Record<BuiltinTabKindId, string> = {terminal: 'rightSidebar.tabs.kinds.terminal',review: 'rightSidebar.tabs.kinds.review','orca-workers': 'rightSidebar.tabs.kinds.collaboration',+ subagents: 'rightSidebar.tabs.kinds.subagents','background-tasks': 'rightSidebar.tabs.kinds.backgroundTasks','resource-usage': 'rightSidebar.tabs.kinds.resourceUsage',};diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/EmptyState.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/__tests__/EmptyState.test.tsxindex d84b5622bb..b2d378ea25 100644--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/EmptyState.test.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/EmptyState.test.tsx@@ -10,11 +10,15 @@ import { EmptyState } from '../EmptyState';afterEach(() => cleanup());-function renderEmptyState(onAddResourceUsageTab = vi.fn()) {+function renderEmptyState(+ onAddResourceUsageTab = vi.fn(),+ onAddSubagentsTab = vi.fn(),+) {return render(<EmptyStateonAddFileTab={vi.fn()}onAddReviewTab={vi.fn()}+ onAddSubagentsTab={onAddSubagentsTab}onAddBackgroundTasksTab={vi.fn()}onAddResourceUsageTab={onAddResourceUsageTab}onAddBrowserTab={vi.fn()}@@ -49,4 +53,11 @@ describe('EmptyState 面板收束(2026-08)', () => {fireEvent.click(screen.getByText('rightSidebar.tabs.empty.openResourceUsage'));expect(onAddResourceUsageTab).toHaveBeenCalledOnce();});++ it('提供 Subagent 工作区快捷入口', () => {+ const onAddSubagentsTab = vi.fn();+ renderEmptyState(vi.fn(), onAddSubagentsTab);+ fireEvent.click(screen.getByText('rightSidebar.tabs.empty.openSubagents'));+ expect(onAddSubagentsTab).toHaveBeenCalledOnce();+ });});diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/executeSidebarCommand.test.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/executeSidebarCommand.test.tsindex 9326cf09c1..973e648a54 100644--- a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/executeSidebarCommand.test.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/executeSidebarCommand.test.ts@@ -12,6 +12,9 @@ vi.mock('../openInSidebarFileBrowser', () => ({openExternalFileInSidebarFileBrowser: vi.fn(async () => undefined),openFileInSidebarFileBrowser: vi.fn(async () => undefined),}));+vi.mock('../openSubagentsTab', () => ({+ openSubagentsTab: vi.fn(async () => undefined),+}));vi.mock('../../plugins/orca-workers/actions', () => ({ensureOrcaWorkersTab: vi.fn(async () => undefined),closeOrcaWorkersTabAfterTeamEnd: vi.fn(async () => undefined),@@ -29,6 +32,7 @@ import {openFileInSidebarFileBrowser,} from '../openInSidebarFileBrowser';import { openUrlInSidebarBrowser } from '../openInSidebarBrowser';+import { openSubagentsTab } from '../openSubagentsTab';describe('executeSidebarCommand', () => {beforeEach(() => vi.clearAllMocks());@@ -72,6 +76,14 @@ describe('executeSidebarCommand', () => {focusTab: false,});await executeSidebarCommand({ type: 'close-orca-workers-tab', sessionId: 's1' });+ await executeSidebarCommand({+ type: 'open-subagents-tab',+ sessionId: 's1',+ focusRunId: 'shared-native-id',+ focusProvider: 'codex',+ focusTab: true,+ revealSidebar: true,+ });expect(ensureHydrated).toHaveBeenCalledWith('s1');expect(addOrFocusSingletonTab).toHaveBeenCalledWith('s1', 'terminal');@@ -85,5 +97,12 @@ describe('executeSidebarCommand', () => {focusTab: false,});expect(closeOrcaWorkersTabAfterTeamEnd).toHaveBeenCalledWith('s1');+ expect(openSubagentsTab).toHaveBeenCalledWith('s1', {+ focusRunId: 'shared-native-id',+ focusProvider: 'codex',+ focusTab: true,+ revealSidebar: true,+ userInitiated: false,+ });});});diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openSubagentsTab.test.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openSubagentsTab.test.tsnew file mode 100644index 0000000000..2199d449d0--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openSubagentsTab.test.ts@@ -0,0 +1,172 @@+// @vitest-environment jsdom++import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ bucket: {+ tabs: [] as Array<{ id: string; kind: string; state: unknown }>,+ activeTabId: null as string | null,+ },+}));++vi.mock('../../store', () => ({+ ensureSingletonTab: vi.fn(+ async () =>+ mocks.bucket.tabs.find((tab) => tab.kind === 'subagents') ?? {+ id: 'subagents-new',+ kind: 'subagents',+ state: { selectedRunId: null },+ },+ ),+ getBucket: vi.fn(() => mocks.bucket),+ patchTabState: vi.fn(async () => undefined),+ setActiveTab: vi.fn(async () => undefined),+}));+vi.mock('../detachedSidebarRouting', () => ({+ routeSidebarCommand: vi.fn(async () => 'attached'),+}));+vi.mock('../sidebarCommands', () => ({+ requestRightSidebarVisibility: vi.fn(),+}));++import { ensureSingletonTab, patchTabState, setActiveTab } from '../../store';+import { routeSidebarCommand } from '../detachedSidebarRouting';+import { openSubagentsTab } from '../openSubagentsTab';+import { requestRightSidebarVisibility } from '../sidebarCommands';++describe('openSubagentsTab', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.bucket.tabs = [];+ mocks.bucket.activeTabId = null;+ vi.mocked(routeSidebarCommand).mockResolvedValue('attached');+ });++ it('opens a focused singleton and carries a harness alias to the durable view', async () => {+ await openSubagentsTab('session-1', {+ focusRunId: 'native-child-1',+ focusProvider: 'codex',+ });++ expect(routeSidebarCommand).toHaveBeenCalledWith(+ {+ type: 'open-subagents-tab',+ sessionId: 'session-1',+ focusRunId: 'native-child-1',+ focusProvider: 'codex',+ focusTab: true,+ revealSidebar: true,+ },+ { allowOpen: true, userInitiated: true },+ );+ expect(routeSidebarCommand).toHaveBeenCalledTimes(4);+ expect(ensureSingletonTab).toHaveBeenCalledWith('session-1', 'subagents', {+ selectedRunId: null,+ selectedProvider: null,+ });+ expect(patchTabState).toHaveBeenCalledWith('session-1', 'subagents-new', expect.any(Function));+ expect(setActiveTab).toHaveBeenCalledWith('session-1', 'subagents-new');+ expect(requestRightSidebarVisibility).toHaveBeenCalledWith('open', {+ sessionId: 'session-1',+ userInitiated: true,+ });+ });++ it('silently adds the automatic tab without replacing another active tab', async () => {+ mocks.bucket.tabs = [{ id: 'files-1', kind: 'file-browser', state: null }];+ mocks.bucket.activeTabId = 'files-1';++ await openSubagentsTab('session-1', {+ focusTab: false,+ revealSidebar: false,+ userInitiated: false,+ });++ expect(routeSidebarCommand).toHaveBeenCalledWith(+ {+ type: 'open-subagents-tab',+ sessionId: 'session-1',+ focusRunId: null,+ focusProvider: null,+ focusTab: false,+ revealSidebar: false,+ },+ { allowOpen: false, userInitiated: false },+ );+ expect(ensureSingletonTab).toHaveBeenCalledWith('session-1', 'subagents', {+ selectedRunId: null,+ selectedProvider: null,+ });+ expect(setActiveTab).not.toHaveBeenCalled();+ expect(requestRightSidebarVisibility).not.toHaveBeenCalled();+ });++ it('focuses and patches the existing singleton when a card is clicked', async () => {+ mocks.bucket.tabs = [+ { id: 'subagents-existing', kind: 'subagents', state: { selectedRunId: null } },+ ];+ mocks.bucket.activeTabId = null;++ await openSubagentsTab('session-1', {+ focusRunId: 'parent-tool-1',+ focusProvider: 'claude-code',+ });++ expect(ensureSingletonTab).toHaveBeenCalledWith('session-1', 'subagents', {+ selectedRunId: null,+ selectedProvider: null,+ });+ expect(patchTabState).toHaveBeenCalledWith(+ 'session-1',+ 'subagents-existing',+ expect.any(Function),+ );+ const patcher = vi.mocked(patchTabState).mock.calls[0]?.[2];+ expect(patcher?.({ kept: true })).toEqual({+ kept: true,+ selectedRunId: 'parent-tool-1',+ selectedProvider: 'claude-code',+ });+ expect(setActiveTab).toHaveBeenCalledWith('session-1', 'subagents-existing');+ });++ it('reroutes to the detached host if ownership changes while SQLite is in flight', async () => {+ vi.mocked(routeSidebarCommand)+ .mockResolvedValueOnce('attached')+ .mockResolvedValueOnce('routed');++ await openSubagentsTab('session-1', { focusRunId: 'child-1', focusProvider: 'pi' });++ expect(ensureSingletonTab).toHaveBeenCalledTimes(1);+ expect(patchTabState).not.toHaveBeenCalled();+ expect(setActiveTab).not.toHaveBeenCalled();+ expect(requestRightSidebarVisibility).toHaveBeenCalledTimes(1);+ });++ it('reroutes after selection persistence if the detached host takes ownership', async () => {+ vi.mocked(routeSidebarCommand)+ .mockResolvedValueOnce('attached')+ .mockResolvedValueOnce('attached')+ .mockResolvedValueOnce('routed');++ await openSubagentsTab('session-1', { focusRunId: 'child-1', focusProvider: 'pi' });++ expect(patchTabState).toHaveBeenCalledTimes(1);+ expect(setActiveTab).not.toHaveBeenCalled();+ expect(requestRightSidebarVisibility).toHaveBeenCalledTimes(1);+ });++ it('reroutes after activation persistence if ownership changes during the write', async () => {+ vi.mocked(routeSidebarCommand)+ .mockResolvedValueOnce('attached')+ .mockResolvedValueOnce('attached')+ .mockResolvedValueOnce('attached')+ .mockResolvedValueOnce('routed');++ await openSubagentsTab('session-1', { focusRunId: 'child-1', focusProvider: 'pi' });++ expect(patchTabState).toHaveBeenCalledTimes(1);+ expect(setActiveTab).toHaveBeenCalledTimes(1);+ expect(requestRightSidebarVisibility).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.tsindex 7a37d8c27d..feb9aa5a90 100644--- a/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts@@ -12,6 +12,7 @@ import {openFileInSidebarFileBrowser,} from './openInSidebarFileBrowser';import { openBackgroundTasksTab } from './openBackgroundTasksTab';+import { openSubagentsTab } from './openSubagentsTab';import { openTurnReview } from './openTurnReview';import { openUrlInSidebarBrowser } from './openInSidebarBrowser';@@ -51,6 +52,17 @@ export async function executeSidebarCommand(command: RsbWindowCommand): Promise<});return;}+ if (command.type === 'open-subagents-tab') {+ await openSubagentsTab(command.sessionId, {+ ...(command.focusRunId && command.focusProvider+ ? { focusRunId: command.focusRunId, focusProvider: command.focusProvider }+ : {}),+ focusTab: command.focusTab !== false,+ revealSidebar: command.revealSidebar !== false,+ userInitiated: false,+ });+ return;+ }if (command.type === 'open-turn-review') {await openTurnReview(command.sessionId, command.changeSetIds, {selectedDiffId: command.selectedDiffId ?? null,diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.tsnew file mode 100644index 0000000000..924ca1646a--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts@@ -0,0 +1,92 @@+/** Programmatic entry for the per-task durable Subagent workspace. */++import type { SubagentProvider } from '@cindy/maker-shared/subagent-workspace';++import { ensureSingletonTab, getBucket, patchTabState, setActiveTab } from '../store';+import { routeSidebarCommand } from './detachedSidebarRouting';+import { requestRightSidebarVisibility } from './sidebarCommands';++export async function openSubagentsTab(+ sessionId: string,+ /** focusRunId accepts a Cindy run id or any stable harness/tool-call alias. */+ opts?: {+ focusRunId?: string;+ focusProvider?: SubagentProvider;+ userInitiated?: boolean;+ focusTab?: boolean;+ revealSidebar?: boolean;+ },+): Promise<void> {+ if (Boolean(opts?.focusRunId) !== Boolean(opts?.focusProvider)) {+ throw new Error('focusRunId and focusProvider must be provided together');+ }+ const focusTab = opts?.focusTab !== false;+ const revealSidebar = opts?.revealSidebar !== false;+ const command = {+ type: 'open-subagents-tab' as const,+ sessionId,+ focusRunId: opts?.focusRunId ?? null,+ focusProvider: opts?.focusProvider ?? null,+ focusTab,+ revealSidebar,+ };+ const routeOptions = {+ allowOpen: revealSidebar,+ userInitiated: opts?.userInitiated !== false,+ };+ const handleRouted = (routeResult: Awaited<ReturnType<typeof routeSidebarCommand>>): boolean => {+ if (routeResult === 'attached') return false;+ if (routeResult === 'routed' && revealSidebar) {+ requestRightSidebarVisibility('open', {+ sessionId,+ userInitiated: opts?.userInitiated !== false,+ });+ }+ return true;+ };+ const rerouteIfOwnershipMoved = async (): Promise<boolean> =>+ handleRouted(await routeSidebarCommand(command, routeOptions));+ const routeResult = await routeSidebarCommand(command, routeOptions);+ if (routeResult !== 'attached') {+ handleRouted(routeResult);+ return;+ }++ let tab = await ensureSingletonTab(sessionId, 'subagents', {+ selectedRunId: null,+ selectedProvider: null,+ });++ // Host ownership may change while hydrate/SQLite work is in flight. Ask+ // main again before mutating this renderer's active tab or selection; if a+ // detached host won, the same command is delivered there against the one+ // canonical DB row.+ if (await rerouteIfOwnershipMoved()) return;++ let bucket = getBucket(sessionId);+ if (!bucket.tabs.some((candidate) => candidate.id === tab.id)) {+ tab = await ensureSingletonTab(sessionId, 'subagents', {+ selectedRunId: null,+ selectedProvider: null,+ });+ bucket = getBucket(sessionId);+ }+ if (opts?.focusRunId) {+ await patchTabState(sessionId, tab.id, (current) => ({+ ...(current && typeof current === 'object' ? (current as Record<string, unknown>) : {}),+ selectedRunId: opts.focusRunId,+ selectedProvider: opts.focusProvider,+ }));+ if (await rerouteIfOwnershipMoved()) return;+ }+ if ((focusTab || bucket.activeTabId === null) && bucket.activeTabId !== tab.id) {+ await setActiveTab(sessionId, tab.id);+ if (await rerouteIfOwnershipMoved()) return;+ }+ if (revealSidebar) {+ requestRightSidebarVisibility('open', {+ sessionId,+ userInitiated: opts?.userInitiated !== false,+ });+ }+}diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/index.tsindex e1280cadd2..a66846ded4 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts@@ -14,5 +14,6 @@ import './web-browser';import './terminal';import './review';import './orca-workers';+import './subagents';import './background-tasks';import './resource-usage';diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsxnew file mode 100644index 0000000000..73729fe820--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx@@ -0,0 +1,608 @@+import { useCallback, useEffect, useMemo, useState } from 'react';+import type { ReactNode } from 'react';+import { useTranslation } from 'react-i18next';+import type { TFunction } from 'i18next';+import {+ AlertCircle,+ ArrowLeft,+ Bot,+ CheckCircle2,+ CircleStop,+ LoaderCircle,+ RefreshCw,+ type LucideIcon,+} from 'lucide-react';+import type {+ SubagentActivityEntry,+ SubagentProvider,+ SubagentRun,+ SubagentRunDetail,+} from '@cindy/maker-shared/subagent-workspace';++import { MarkdownRenderer } from '@/components/chat/MarkdownRenderer';+import { Spinner } from '@/components/ui/spinner';+import { getDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';+import { cn } from '@/lib/utils';+import { formatCompactTokens } from '@/lib/usageFormat';+import type { TabKindHostContext } from '../../types';+import type { SubagentsState } from './index';+import {+ isCurrentSubagentReadOwner,+ isCurrentSubagentRunsChange,+ subagentReadScopeKey,+} from './subagentChangeFence';++type LoadState = 'idle' | 'loading' | 'ready' | 'unsupported' | 'error';++function statusIcon(status: SubagentRun['status']): LucideIcon {+ if (status === 'completed') return CheckCircle2;+ if (status === 'failed') return AlertCircle;+ if (status === 'stopped') return CircleStop;+ return LoaderCircle;+}++function formatDuration(ms: number | undefined): string | undefined {+ if (typeof ms !== 'number' || !Number.isFinite(ms) || ms < 0) return undefined;+ const seconds = Math.max(1, Math.round(ms / 1000));+ if (seconds < 60) return `${seconds}s`;+ const minutes = Math.floor(seconds / 60);+ const rest = seconds % 60;+ return rest > 0 ? `${minutes}m ${rest}s` : `${minutes}m`;+}++function providerLabel(provider: SubagentProvider): string {+ if (provider === 'claude-code') return 'Claude Code';+ if (provider === 'codex') return 'Codex';+ return 'PI';+}++function runTitle(run: SubagentRun, fallback: string): string {+ return run.title?.trim() || run.description?.trim() || fallback;+}++function metadata(run: SubagentRun, t: TFunction): string[] {+ const parts = [providerLabel(run.provider)];+ if (run.model) parts.push(run.model);+ const duration = formatDuration(run.usage?.durationMs);+ if (duration) parts.push(duration);+ if (typeof run.usage?.totalTokens === 'number') {+ parts.push(+ t('rightSidebar.subagents.tokens', {+ value: formatCompactTokens(run.usage.totalTokens),+ }),+ );+ }+ return parts;+}++function StatusGlyph({ status, label }: { status: SubagentRun['status']; label: string }) {+ const Icon = statusIcon(status);+ return (+ <Spinner+ icon={Icon}+ size={14}+ spinning={status === 'running'}+ aria-label={label}+ title={label}+ className={cn('text-[var(--text-tertiary)]', status === 'failed' && 'text-[var(--error-fg)]')}+ />+ );+}++function RunRow({ run, onOpen }: { run: SubagentRun; onOpen: (run: SubagentRun) => void }) {+ const { t } = useTranslation();+ const title = runTitle(run, t('rightSidebar.subagents.untitled'));+ const statusLabel = t(`chat.agentTask.status.${run.status}`);+ return (+ <button+ type="button"+ onClick={() => onOpen(run)}+ className="flex w-full items-start gap-2 rounded-lg px-2 py-2 text-left transition-colors hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"+ >+ <span className="mt-0.5 inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-[var(--surface-chip)]">+ <StatusGlyph status={run.status} label={statusLabel} />+ </span>+ <span className="min-w-0 flex-1">+ <span className="block truncate text-13 font-medium leading-5 text-[var(--text-primary)]">+ {title}+ </span>+ <span className="mt-0.5 block truncate text-11 leading-4 text-[var(--text-tertiary)]">+ {metadata(run, t).join(' · ')}+ </span>+ {run.summary ? (+ <span className="mt-0.5 block line-clamp-2 text-12 leading-4 text-[var(--text-secondary)]">+ {run.summary}+ </span>+ ) : null}+ </span>+ </button>+ );+}++function ActivityRow({ entry }: { entry: SubagentActivityEntry }) {+ const { t } = useTranslation();+ const label = t(`rightSidebar.subagents.activityKinds.${entry.kind}`);+ return (+ <div className="relative flex gap-2 pb-3 pl-1 last:pb-0">+ <span className="mt-1 h-2 w-2 shrink-0 rounded-full bg-[var(--border-strong)]" />+ <div className="min-w-0 flex-1">+ <div className="flex items-center justify-between gap-2">+ <span className="text-12 font-medium text-[var(--text-secondary)]">{label}</span>+ <span className="shrink-0 text-10 text-[var(--text-tertiary)]">+ {new Date(entry.occurredAt).toLocaleTimeString([], {+ hour: '2-digit',+ minute: '2-digit',+ })}+ </span>+ </div>+ {entry.summary ? (+ <p className="mt-0.5 whitespace-pre-wrap text-12 leading-4 text-[var(--text-tertiary)]">+ {entry.summary}+ </p>+ ) : null}+ {entry.lastToolName ? (+ <p className="mt-0.5 truncate text-11 text-[var(--text-tertiary)]">+ {t('rightSidebar.subagents.lastTool', { tool: entry.lastToolName })}+ </p>+ ) : null}+ </div>+ </div>+ );+}++function DetailView({+ detail,+ loading,+ workdir,+ allowPrivilegedLinks,+ onBack,+}: {+ detail: SubagentRunDetail | null;+ loading: boolean;+ workdir: string;+ allowPrivilegedLinks: boolean;+ onBack: () => void;+}) {+ const { t } = useTranslation();+ if (loading && !detail) {+ return (+ <CenteredState icon={LoaderCircle} spinning label={t('rightSidebar.subagents.loading')} />+ );+ }+ if (!detail) {+ return (+ <div className="flex min-h-0 flex-1 flex-col">+ <HeaderBack onBack={onBack} title={t('rightSidebar.subagents.notFound')} />+ </div>+ );+ }+ const title = runTitle(detail, t('rightSidebar.subagents.untitled'));+ return (+ <div className="flex min-h-0 flex-1 flex-col">+ <HeaderBack onBack={onBack} title={title} status={detail.status} />+ <div className="min-h-0 flex-1 overflow-y-auto px-4 pb-6 pt-3">+ <dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 text-12">+ <dt className="text-[var(--text-tertiary)]">{t('rightSidebar.subagents.harness')}</dt>+ <dd className="truncate text-[var(--text-secondary)]">+ {providerLabel(detail.provider)}+ </dd>+ {detail.model ? (+ <>+ <dt className="text-[var(--text-tertiary)]">{t('rightSidebar.subagents.model')}</dt>+ <dd className="truncate text-[var(--text-secondary)]">{detail.model}</dd>+ </>+ ) : null}+ <dt className="text-[var(--text-tertiary)]">{t('rightSidebar.subagents.context')}</dt>+ <dd className="text-[var(--text-secondary)]">+ {t(`rightSidebar.subagents.contextValues.${detail.capabilities.parentContext}`)}+ </dd>+ </dl>++ {detail.description ? (+ <section className="mt-5">+ <SectionTitle>{t('rightSidebar.subagents.assignment')}</SectionTitle>+ <p className="whitespace-pre-wrap text-12 leading-5 text-[var(--text-secondary)]">+ {detail.description}+ </p>+ </section>+ ) : null}++ {detail.capabilities.viewReturnedResult && detail.returnedResult ? (+ <section className="mt-5">+ <SectionTitle>{t('rightSidebar.subagents.returnedResult')}</SectionTitle>+ <div className="text-13 leading-5 text-[var(--text-primary)]">+ <MarkdownRenderer+ workingDir={workdir}+ content={detail.returnedResult}+ allowPrivilegedLinks={allowPrivilegedLinks}+ />+ </div>+ {detail.returnedResultTruncated ? (+ <p className="mt-2 text-11 text-[var(--text-tertiary)]">+ {t('rightSidebar.subagents.resultTruncated')}+ </p>+ ) : null}+ </section>+ ) : detail.summary ? (+ <section className="mt-5">+ <SectionTitle>{t('rightSidebar.subagents.latestUpdate')}</SectionTitle>+ <p className="whitespace-pre-wrap text-12 leading-5 text-[var(--text-secondary)]">+ {detail.summary}+ </p>+ </section>+ ) : null}++ {detail.capabilities.viewActivity ? (+ <section className="mt-5">+ <SectionTitle>{t('rightSidebar.subagents.activity')}</SectionTitle>+ {detail.activity.length > 0 ? (+ <div className="mt-1">+ {detail.activity.map((entry) => (+ <ActivityRow key={entry.sequence} entry={entry} />+ ))}+ </div>+ ) : (+ <p className="text-12 text-[var(--text-tertiary)]">+ {t('rightSidebar.subagents.noActivity')}+ </p>+ )}+ </section>+ ) : null}++ {!detail.capabilities.viewFullTranscript ? (+ <p className="mt-5 rounded-lg bg-[var(--surface-subtle)] px-3 py-2 text-11 leading-4 text-[var(--text-tertiary)]">+ {t('rightSidebar.subagents.transcriptUnavailable')}+ </p>+ ) : null}+ </div>+ </div>+ );+}++function HeaderBack({+ onBack,+ title,+ status,+}: {+ onBack: () => void;+ title: string;+ status?: SubagentRun['status'];+}) {+ const { t } = useTranslation();+ return (+ <div className="flex h-11 shrink-0 items-center gap-2 border-b border-[var(--border-default)] px-3">+ <button+ type="button"+ onClick={onBack}+ title={t('rightSidebar.subagents.back')}+ aria-label={t('rightSidebar.subagents.back')}+ className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg text-[var(--text-secondary)] hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"+ >+ <ArrowLeft size={15} aria-hidden="true" />+ </button>+ <span className="min-w-0 flex-1 truncate text-13 font-medium text-[var(--text-primary)]">+ {title}+ </span>+ {status ? <StatusGlyph status={status} label={t(`chat.agentTask.status.${status}`)} /> : null}+ </div>+ );+}++function SectionTitle({ children }: { children: ReactNode }) {+ return (+ <h3 className="mb-2 text-11 font-semibold uppercase tracking-[0.06em] text-[var(--text-tertiary)]">+ {children}+ </h3>+ );+}++function CenteredState({+ icon: Icon,+ label,+ detail,+ spinning = false,+ action,+}: {+ icon: LucideIcon;+ label: string;+ detail?: string;+ spinning?: boolean;+ action?: ReactNode;+}) {+ return (+ <div className="flex min-h-0 flex-1 flex-col items-center justify-center px-8 text-center">+ <Spinner icon={Icon} spinning={spinning} size={20} className="text-[var(--text-tertiary)]" />+ <p className="mt-3 text-13 font-medium text-[var(--text-secondary)]">{label}</p>+ {detail ? (+ <p className="mt-1 text-12 leading-5 text-[var(--text-tertiary)]">{detail}</p>+ ) : null}+ {action}+ </div>+ );+}++interface SubagentsBodyProps {+ state: SubagentsState;+ ctx: TabKindHostContext;+ active?: boolean;+ shellVisible?: boolean;+}++export function SubagentsBody(props: SubagentsBodyProps) {+ const owner = getDataOwnerGeneration();+ // A tab host can survive task/account switches. Remount the stateful reader+ // at every ownership boundary so data from the previous scope is never+ // painted while the replacement IPC request is in flight.+ const scopeKey = subagentReadScopeKey(+ owner,+ props.ctx.sessionId,+ props.ctx.deviceLinkDeviceId,+ props.ctx.remoteHostId,+ );+ return <ScopedSubagentsBody key={scopeKey} {...props} />;+}++function ScopedSubagentsBody({+ state,+ ctx,+ active = true,+ shellVisible = true,+}: SubagentsBodyProps) {+ const { t } = useTranslation();+ const visible = active && shellVisible;+ const [loadState, setLoadState] = useState<LoadState>('idle');+ const [runs, setRuns] = useState<SubagentRun[]>([]);+ const [nextCursor, setNextCursor] = useState<string | null>(null);+ const [loadingMore, setLoadingMore] = useState(false);+ const [detail, setDetail] = useState<SubagentRunDetail | null>(null);+ const [detailLoading, setDetailLoading] = useState(false);+ const [detailRefreshVersion, setDetailRefreshVersion] = useState(0);+ const selectedRunAlias = state.selectedRunId ?? null;+ const selectedProviderHint = state.selectedProvider ?? null;+ const remoteDevice = ctx.deviceLinkDeviceId !== null;++ // New focus entrances always carry the harness. Old persisted tab state may+ // not; infer it only when the loaded page identifies one unambiguous+ // provider. Alias-to-run resolution itself remains host-owned and scoped by+ // (session, provider, alias), so a same-named run in another harness cannot+ // win because it happened to update later.+ const selectedProvider = useMemo(() => {+ if (!selectedRunAlias) return null;+ if (selectedProviderHint) return selectedProviderHint;+ const exact = runs.find((run) => run.id === selectedRunAlias);+ if (exact) return exact.provider;+ const matches = runs.filter(+ (run) =>+ run.logicalAgentId === selectedRunAlias ||+ run.parentToolUseId === selectedRunAlias ||+ run.identityAliases.includes(selectedRunAlias) ||+ run.providerRunIds.includes(selectedRunAlias),+ );+ const providers = new Set(matches.map((run) => run.provider));+ return providers.size === 1 ? matches[0]?.provider ?? null : null;+ }, [runs, selectedProviderHint, selectedRunAlias]);++ const loadRuns = useCallback(+ async (cursor?: string) => {+ const append = Boolean(cursor);+ const requestOwner = getDataOwnerGeneration();+ if (remoteDevice) {+ setLoadState('unsupported');+ setRuns([]);+ setNextCursor(null);+ return;+ }+ if (append) setLoadingMore(true);+ else setLoadState((current) => (current === 'ready' ? current : 'loading'));+ try {+ const response = await window.electronAPI.localDb.subagentRuns.list({+ sessionId: ctx.sessionId,+ ...(cursor ? { cursor } : {}),+ });+ if (!isCurrentSubagentReadOwner(requestOwner)) return;+ if (!response.supported) {+ setRuns([]);+ setNextCursor(null);+ setLoadState('unsupported');+ return;+ }+ setRuns((current) => {+ if (!append) return response.runs;+ const byId = new Map(current.map((run) => [run.id, run]));+ for (const run of response.runs) byId.set(run.id, run);+ return [...byId.values()];+ });+ setNextCursor(response.nextCursor ?? null);+ setLoadState('ready');+ } catch {+ if (isCurrentSubagentReadOwner(requestOwner) && !append) setLoadState('error');+ } finally {+ if (isCurrentSubagentReadOwner(requestOwner) && append) setLoadingMore(false);+ }+ },+ [ctx.sessionId, remoteDevice],+ );++ useEffect(() => {+ if (!visible) return;+ void loadRuns();+ let timer: ReturnType<typeof setTimeout> | null = null;+ const unsubscribe = window.electronAPI.localDb.subagentRuns.onChanged((payload, ownerStamp) => {+ if (!isCurrentSubagentRunsChange(payload, ownerStamp, ctx.sessionId)) return;+ if (timer) clearTimeout(timer);+ timer = setTimeout(() => {+ void loadRuns();+ setDetailRefreshVersion((version) => version + 1);+ }, 50);+ });+ return () => {+ if (timer) clearTimeout(timer);+ unsubscribe();+ };+ }, [ctx.sessionId, loadRuns, visible]);++ useEffect(() => {+ if (!visible || !selectedRunAlias || !selectedProvider || loadState === 'unsupported') {+ setDetail(null);+ setDetailLoading(false);+ return;+ }+ let disposed = false;+ const requestOwner = getDataOwnerGeneration();+ setDetailLoading(true);+ void window.electronAPI.localDb.subagentRuns+ .detail({+ sessionId: ctx.sessionId,+ provider: selectedProvider,+ runIdOrAlias: selectedRunAlias,+ })+ .then((response) => {+ if (disposed || !isCurrentSubagentReadOwner(requestOwner)) return;+ setDetail(response.supported ? response.run : null);+ if (+ response.run+ && (response.run.id !== selectedRunAlias || response.run.provider !== selectedProviderHint)+ ) {+ ctx.patchState({+ selectedRunId: response.run.id,+ selectedProvider: response.run.provider,+ });+ }+ })+ .catch(() => {+ if (!disposed && isCurrentSubagentReadOwner(requestOwner)) setDetail(null);+ })+ .finally(() => {+ if (!disposed && isCurrentSubagentReadOwner(requestOwner)) setDetailLoading(false);+ });+ return () => {+ disposed = true;+ };+ }, [+ ctx,+ detailRefreshVersion,+ loadState,+ selectedProvider,+ selectedProviderHint,+ selectedRunAlias,+ visible,+ ]);++ const grouped = useMemo(+ () => ({+ running: runs.filter((run) => run.status === 'running'),+ finished: runs.filter((run) => run.status !== 'running'),+ }),+ [runs],+ );++ const openRun = useCallback(+ (run: SubagentRun) => ctx.patchState({+ selectedRunId: run.id,+ selectedProvider: run.provider,+ }),+ [ctx],+ );+ const back = useCallback(+ () => ctx.patchState({ selectedRunId: null, selectedProvider: null }),+ [ctx],+ );++ if (loadState === 'idle' || loadState === 'loading') {+ return (+ <CenteredState icon={LoaderCircle} spinning label={t('rightSidebar.subagents.loading')} />+ );+ }+ if (loadState === 'unsupported') {+ return (+ <CenteredState+ icon={Bot}+ label={t('rightSidebar.subagents.unavailable')}+ detail={t('rightSidebar.subagents.unavailableDetail')}+ />+ );+ }+ if (selectedRunAlias) {+ return (+ <DetailView+ detail={detail}+ loading={detailLoading}+ workdir={ctx.workdir}+ allowPrivilegedLinks={ctx.deviceLinkDeviceId === null && !ctx.remoteHostId}+ onBack={back}+ />+ );+ }+ if (loadState === 'error') {+ return (+ <CenteredState+ icon={AlertCircle}+ label={t('rightSidebar.subagents.loadFailed')}+ action={+ <button+ type="button"+ onClick={() => void loadRuns()}+ className="mt-3 inline-flex h-8 items-center gap-1.5 rounded-lg border border-[var(--border-default)] px-3 text-12 text-[var(--text-secondary)] hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"+ >+ <RefreshCw size={13} aria-hidden="true" />+ {t('rightSidebar.subagents.retry')}+ </button>+ }+ />+ );+ }+ if (runs.length === 0) {+ return (+ <CenteredState+ icon={Bot}+ label={t('rightSidebar.subagents.empty')}+ detail={t('rightSidebar.subagents.emptyDetail')}+ />+ );+ }++ return (+ <div className="flex min-h-0 flex-1 flex-col">+ <div className="flex h-11 shrink-0 items-center gap-2 border-b border-[var(--border-default)] px-4">+ <Bot size={15} className="text-[var(--text-secondary)]" aria-hidden="true" />+ <h2 className="text-13 font-medium text-[var(--text-primary)]">+ {t('rightSidebar.tabs.kinds.subagents')}+ </h2>+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto px-2 py-2">+ {grouped.running.length > 0 ? (+ <section>+ <div className="px-2 pb-1 pt-1 text-10 font-semibold uppercase tracking-[0.06em] text-[var(--text-tertiary)]">+ {t('rightSidebar.subagents.running')}+ </div>+ {grouped.running.map((run) => (+ <RunRow key={run.id} run={run} onOpen={openRun} />+ ))}+ </section>+ ) : null}+ {grouped.finished.length > 0 ? (+ <section className={grouped.running.length > 0 ? 'mt-3' : undefined}>+ <div className="px-2 pb-1 pt-1 text-10 font-semibold uppercase tracking-[0.06em] text-[var(--text-tertiary)]">+ {t('rightSidebar.subagents.finished')}+ </div>+ {grouped.finished.map((run) => (+ <RunRow key={run.id} run={run} onOpen={openRun} />+ ))}+ </section>+ ) : null}+ {nextCursor ? (+ <button+ type="button"+ disabled={loadingMore}+ onClick={() => void loadRuns(nextCursor)}+ className="mx-2 mt-3 flex h-8 items-center justify-center rounded-lg border border-[var(--border-default)] px-3 text-12 text-[var(--text-secondary)] hover:bg-[var(--surface-hover)] disabled:cursor-wait disabled:opacity-60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"+ >+ {loadingMore+ ? t('rightSidebar.subagents.loading')+ : t('rightSidebar.subagents.loadEarlier')}+ </button>+ ) : null}+ </div>+ </div>+ );+}diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/__tests__/SubagentsBody.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/__tests__/SubagentsBody.test.tsxnew file mode 100644index 0000000000..98ce208df4--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/__tests__/SubagentsBody.test.tsx@@ -0,0 +1,173 @@+// @vitest-environment jsdom++import { cleanup, render, screen, waitFor } from '@testing-library/react';+import { act } from 'react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type {+ SubagentRunDetail,+ SubagentRunsChangedPayload,+} from '@cindy/maker-shared/subagent-workspace';++import {+ __testing as dataOwnerTesting,+ setDataOwnerGeneration,+} from '@/contexts/dataOwnerGeneration';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock('@/components/chat/MarkdownRenderer', () => ({+ MarkdownRenderer: ({ content }: { content: string }) => <>{content}</>,+}));++import { SubagentsBody } from '../SubagentsBody';++const OWNER_STAMP = { dataOwnerId: 'owner-1', ownerGeneration: 1 };++function detail(summary: string): SubagentRunDetail {+ return {+ id: 'run-1',+ parentSessionId: 'session-1',+ provider: 'pi',+ logicalAgentId: 'task-1',+ parentToolUseId: 'task-1',+ identityAliases: ['task-1'],+ providerRunIds: [],+ status: 'running',+ title: 'Research task',+ summary,+ capabilities: {+ viewActivity: false,+ viewReturnedResult: false,+ viewFullTranscript: false,+ resume: false,+ steer: false,+ stop: false,+ parentContext: 'unknown',+ },+ activity: [],+ startedAt: 100,+ updatedAt: 200,+ };+}++describe('SubagentsBody', () => {+ let onChanged: (payload: SubagentRunsChangedPayload, ownerStamp?: unknown) => void = () =>+ undefined;+ let currentDetail: SubagentRunDetail | null = detail('initial progress');+ const list = vi.fn(async () => ({+ supported: true,+ runs: currentDetail ? [currentDetail] : [],+ }));+ const loadDetail = vi.fn(async () => ({+ supported: true,+ run: currentDetail,+ }));++ beforeEach(() => {+ dataOwnerTesting.reset();+ setDataOwnerGeneration('owner-1', 1);+ currentDetail = detail('initial progress');+ list.mockClear();+ loadDetail.mockClear();+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: {+ localDb: {+ subagentRuns: {+ list,+ detail: loadDetail,+ onChanged: vi.fn((listener) => {+ onChanged = listener;+ return () => undefined;+ }),+ },+ },+ },+ });+ });++ afterEach(() => {+ cleanup();+ dataOwnerTesting.reset();+ Reflect.deleteProperty(window, 'electronAPI');+ });++ it('reloads the selected detail when a run change is pushed', async () => {+ render(+ <SubagentsBody+ state={{ selectedRunId: 'run-1', selectedProvider: 'pi' }}+ ctx={{+ tabId: 'tab-1',+ sessionId: 'session-1',+ workdir: '/workspace',+ remoteHostId: null,+ deviceLinkDeviceId: null,+ patchState: vi.fn(),+ onVisibilityChange: vi.fn(),+ setCloseInterceptor: vi.fn(() => () => undefined),+ }}+ />,+ );++ await screen.findByText('initial progress');+ const detailCallsBeforePush = loadDetail.mock.calls.length;+ currentDetail = detail('finished result');++ act(() => {+ onChanged(+ {+ sessionId: 'session-1',+ runId: 'run-1',+ created: false,+ firstForSession: false,+ },+ OWNER_STAMP,+ );+ });++ await screen.findByText('finished result');+ await waitFor(() => {+ expect(loadDetail.mock.calls.length).toBeGreaterThan(detailCallsBeforePush);+ });+ });++ it('removes stale list and detail content after a session boundary invalidation', async () => {+ render(+ <SubagentsBody+ state={{ selectedRunId: 'run-1', selectedProvider: 'pi' }}+ ctx={{+ tabId: 'tab-1',+ sessionId: 'session-1',+ workdir: '/workspace',+ remoteHostId: null,+ deviceLinkDeviceId: null,+ patchState: vi.fn(),+ onVisibilityChange: vi.fn(),+ setCloseInterceptor: vi.fn(() => () => undefined),+ }}+ />,+ );++ await screen.findByText('initial progress');+ currentDetail = null;++ act(() => {+ onChanged(+ {+ sessionId: 'session-1',+ runId: null,+ created: false,+ firstForSession: false,+ },+ OWNER_STAMP,+ );+ });++ await waitFor(() => {+ expect(screen.queryByText('initial progress')).toBeNull();+ expect(list).toHaveBeenCalledTimes(2);+ });+ });+});diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/__tests__/subagentChangeFence.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/__tests__/subagentChangeFence.test.tsnew file mode 100644index 0000000000..355b523067--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/__tests__/subagentChangeFence.test.ts@@ -0,0 +1,72 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import {+ __testing,+ getDataOwnerGeneration,+ setDataOwnerGeneration,+} from '@/contexts/dataOwnerGeneration';+import {+ isCurrentSubagentReadOwner,+ isCurrentSubagentRunsChange,+ subagentReadScopeKey,+} from '../subagentChangeFence';++const payload = {+ sessionId: 'session-1',+ runId: 'run-1',+ created: true,+ firstForSession: true,+};++describe('isCurrentSubagentRunsChange', () => {+ beforeEach(() => {+ __testing.reset();+ setDataOwnerGeneration('owner-new', 2);+ });++ afterEach(() => {+ __testing.reset();+ });++ it('accepts only the current owner and session', () => {+ expect(+ isCurrentSubagentRunsChange(+ payload,+ { dataOwnerId: 'owner-new', ownerGeneration: 2 },+ 'session-1',+ ),+ ).toBe(true);+ expect(+ isCurrentSubagentRunsChange(+ payload,+ { dataOwnerId: 'owner-old', ownerGeneration: 1 },+ 'session-1',+ ),+ ).toBe(false);+ expect(+ isCurrentSubagentRunsChange(+ payload,+ { dataOwnerId: 'owner-new', ownerGeneration: 2 },+ 'session-2',+ ),+ ).toBe(false);+ });++ it('invalidates in-flight reads and mounted state across owner or task switches', () => {+ setDataOwnerGeneration('owner-old', 1);+ const captured = getDataOwnerGeneration();+ const oldKey = subagentReadScopeKey(captured, 'session-1', null, null);++ setDataOwnerGeneration('owner-new', 2);+ const current = getDataOwnerGeneration();+ expect(isCurrentSubagentReadOwner(captured)).toBe(false);+ expect(isCurrentSubagentReadOwner(current)).toBe(true);+ expect(subagentReadScopeKey(current, 'session-1', null, null)).not.toBe(oldKey);+ expect(subagentReadScopeKey(current, 'session-2', null, null)).not.toBe(+ subagentReadScopeKey(current, 'session-1', null, null),+ );+ expect(subagentReadScopeKey(current, 'session-1', undefined, null)).not.toBe(+ subagentReadScopeKey(current, 'session-1', null, null),+ );+ });+});diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsxnew file mode 100644index 0000000000..c992014e24--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx@@ -0,0 +1,67 @@+/** Cindy-owned durable Subagent workspace tab. */++import { Bot } from 'lucide-react';+import type { TFunction } from 'i18next';+import type { SubagentProvider } from '@cindy/maker-shared/subagent-workspace';++import { registerTabKind } from '../../registry';+import type { TabKindPlugin } from '../../types';+import { SubagentsBody } from './SubagentsBody';++export interface SubagentsState {+ selectedRunId?: string | null;+ selectedProvider?: SubagentProvider | null;+}++const SUBAGENT_PROVIDERS = new Set<SubagentProvider>(['claude-code', 'codex', 'pi']);++function SubagentsTabPillTitle({ t }: { state: SubagentsState; t: TFunction }) {+ return <>{t('rightSidebar.tabs.kinds.subagents')}</>;+}++function SubagentsTabPillIcon() {+ return <Bot size={13} />;+}++const plugin: TabKindPlugin<SubagentsState> = {+ kind: 'subagents',+ menu: {+ kind: 'subagents',+ labelKey: 'rightSidebar.tabs.kinds.subagents',+ icon: Bot,+ order: 16,+ enabled: true,+ singleton: true,+ },+ TabPillTitle: SubagentsTabPillTitle,+ TabPillIcon: SubagentsTabPillIcon,+ TabBody: SubagentsBody,+ defaultState: () => ({ selectedRunId: null, selectedProvider: null }),+ serializeState: (state) => ({+ selectedRunId:+ typeof state.selectedRunId === 'string' && state.selectedRunId+ ? state.selectedRunId+ : null,+ selectedProvider:+ state.selectedProvider && SUBAGENT_PROVIDERS.has(state.selectedProvider)+ ? state.selectedProvider+ : null,+ }),+ hydrateState: (raw): SubagentsState => {+ if (!raw || typeof raw !== 'object') {+ return { selectedRunId: null, selectedProvider: null };+ }+ const selectedRunId = (raw as Record<string, unknown>).selectedRunId;+ const selectedProvider = (raw as Record<string, unknown>).selectedProvider;+ return {+ selectedRunId: typeof selectedRunId === 'string' && selectedRunId ? selectedRunId : null,+ selectedProvider:+ typeof selectedProvider === 'string'+ && SUBAGENT_PROVIDERS.has(selectedProvider as SubagentProvider)+ ? selectedProvider as SubagentProvider+ : null,+ };+ },+};++registerTabKind(plugin as unknown as TabKindPlugin, import.meta.hot);diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.tsnew file mode 100644index 0000000000..37dd9f2aa3--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts@@ -0,0 +1,37 @@+import type { SubagentRunsChangedPayload } from '@cindy/maker-shared/subagent-workspace';++import {+ isDataOwnerGenerationCurrent,+ isDataOwnerPushCurrent,+ type DataOwnerGeneration,+} from '@/contexts/dataOwnerGeneration';++/** Fence an in-flight list/detail response captured before an account switch. */+export function isCurrentSubagentReadOwner(owner: DataOwnerGeneration): boolean {+ return isDataOwnerGenerationCurrent(owner);+}++/** Force React state to remount when any task/owner/host ownership axis changes. */+export function subagentReadScopeKey(+ owner: DataOwnerGeneration,+ sessionId: string,+ deviceLinkDeviceId: string | null | undefined,+ remoteHostId: string | null,+): string {+ return JSON.stringify([+ owner.dataOwnerId,+ owner.generation,+ sessionId,+ deviceLinkDeviceId === undefined ? ['unresolved'] : ['resolved', deviceLinkDeviceId],+ remoteHostId,+ ]);+}++/** Ignore invalidations captured under a previous signed-in data owner. */+export function isCurrentSubagentRunsChange(+ payload: SubagentRunsChangedPayload,+ ownerStamp: unknown,+ sessionId: string,+): boolean {+ return payload.sessionId === sessionId && isDataOwnerPushCurrent(ownerStamp);+}diff --git a/apps/desktop/src/renderer/features/right-sidebar/store.ts b/apps/desktop/src/renderer/features/right-sidebar/store.tsindex 6b3d868f4b..cf990870e7 100644--- a/apps/desktop/src/renderer/features/right-sidebar/store.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/store.ts@@ -42,6 +42,7 @@ const MAX_TABS_PER_SESSION = 20;const MAX_STATE_JSON_BYTES = 16 * 1024;const cache = new Map<string, TabBucket>();const inflight = new Map<string, Promise<void>>();+const singletonInflight = new Map<string, Promise<TabState>>();const listeners = new Set<Listener>();const memoryOnlySessions = new Set<string>();const closeInterceptors = new Map<string, TabCloseInterceptor>();@@ -116,6 +117,7 @@ const pendingStateWriteOrder: string[] = [];const activeStateWrites = new Map<string, PendingTabStateWrite>();let stateWritePumpRunning = false;let storeGeneration = 0;+let cacheGeneration = 0;interface RightSidebarTabsListResult {tabs: Array<{ id: string; kind: string; state: unknown }>;@@ -124,6 +126,17 @@ interface RightSidebarTabsListResult {persistable?: boolean;}+interface EnsureSingletonTabResult {+ tab: {+ id: string;+ kind: string;+ position: number;+ state: unknown;+ } | null;+ created: boolean;+ persistable: boolean;+}+/*** cache miss 时 getBucket 返回的稳定单例。*@@ -141,9 +154,7 @@ function notify(sessionId: string): void {}function ipcApi() {- return typeof window !== 'undefined'- ? window.electronAPI?.localDb?.rightSidebarTabs- : undefined;+ return typeof window !== 'undefined' ? window.electronAPI?.localDb?.rightSidebarTabs : undefined;}function makeTabId(): string {@@ -341,8 +352,10 @@ async function settleTabStateWrites(sessionId: string, tabId: string): Promise<v// tab 后只会 noop,所以不会再有新写进入这个 key。等待 active 与 pending// 两代写全部落定后再 DELETE,避免队列中的 UPSERT 在 close 之后把 tab 行复活。while (true) {- const writes = [activeStateWrites.get(key)?.promise, pendingStateWrites.get(key)?.promise]- .filter((promise): promise is Promise<void> => promise != null);+ const writes = [+ activeStateWrites.get(key)?.promise,+ pendingStateWrites.get(key)?.promise,+ ].filter((promise): promise is Promise<void> => promise != null);if (writes.length === 0) return;await Promise.allSettled(writes);}@@ -456,7 +469,7 @@ export async function ensureHydrated(sessionId: string): Promise<void> {}const promise = (async () => {try {- const result = await ipc.list({ sessionId }) as RightSidebarTabsListResult;+ const result = (await ipc.list({ sessionId })) as RightSidebarTabsListResult;if (result.persistable === false) {markMemoryOnlySession(sessionId);} else {@@ -502,7 +515,9 @@ export async function addTab(const activate = opts?.activate !== false;const prev = getBucket(sessionId);if (prev.tabs.length >= MAX_TABS_PER_SESSION) {- throw new Error(`session ${sessionId} already has ${MAX_TABS_PER_SESSION} tabs (limit reached)`);+ throw new Error(+ `session ${sessionId} already has ${MAX_TABS_PER_SESSION} tabs (limit reached)`,+ );}if (!shouldPersist(sessionId)) {validateMemoryOnlyStateSize(initialState);@@ -596,6 +611,76 @@ export async function addOrFocusSingletonTab(return addTab(sessionId, kind, initialState);}+/**+ * DB-authoritative singleton creation for kinds backed by a partial unique+ * index. Unlike addOrFocusSingletonTab this is safe across the attached and+ * detached renderer stores. It does not activate or patch the tab; the host+ * that wins main's routing decision performs those user-visible mutations.+ */+export async function ensureSingletonTab(+ sessionId: string,+ kind: TabKindId,+ initialState: unknown = null,+): Promise<TabState> {+ await ensureHydrated(sessionId);+ const current = getBucket(sessionId);+ const local = current.tabs.find((tab) => tab.kind === kind);+ const ipc = ipcApi();+ if (!ipc?.ensureSingleton || !shouldPersist(sessionId)) {+ return local ?? addTab(sessionId, kind, initialState, { activate: false });+ }++ const key = `${sessionId}\0${kind}`;+ const pending = singletonInflight.get(key);+ if (pending) return pending;+ const generation = cacheGeneration;+ const ensure = (async (): Promise<TabState> => {+ const result = (await ipc.ensureSingleton({+ sessionId,+ kind,+ state: initialState,+ })) as EnsureSingletonTabResult;+ if (!result.persistable || !result.tab) {+ markMemoryOnlySession(sessionId);+ return local ?? addTab(sessionId, kind, initialState, { activate: false });+ }+ const existing = getBucket(sessionId).tabs.find((tab) => tab.id === result.tab?.id);+ const canonical: TabState = {+ id: result.tab.id,+ kind: result.tab.kind as TabKindId,+ state: existing?.state ?? result.tab.state,+ };+ if (generation !== cacheGeneration) return canonical;++ const bucket = getBucket(sessionId);+ const withoutSingleton = bucket.tabs.filter(+ (tab) => tab.id !== canonical.id && tab.kind !== kind,+ );+ const insertAt = Math.min(result.tab.position, withoutSingleton.length);+ const tabs = [...withoutSingleton];+ tabs.splice(insertAt, 0, canonical);+ setBucket(sessionId, {+ hydrated: true,+ tabs,+ activeTabId:+ bucket.activeTabId && tabs.some((tab) => tab.id === bucket.activeTabId)+ ? bucket.activeTabId+ : null,+ });+ return canonical;+ })();+ singletonInflight.set(key, ensure);+ void ensure.then(+ () => {+ if (singletonInflight.get(key) === ensure) singletonInflight.delete(key);+ },+ () => {+ if (singletonInflight.get(key) === ensure) singletonInflight.delete(key);+ },+ );+ return ensure;+}+export function setTabCloseInterceptor(tabId: string,interceptor: TabCloseInterceptor | null,@@ -666,7 +751,12 @@ export async function closeTab(const shouldContinue = await interceptor();if (shouldContinue === false) return;} catch (err) {- log.warn('tab close interceptor failed (vetoed)', { sessionId, tabId, kind: tab.kind, err });+ log.warn('tab close interceptor failed (vetoed)', {+ sessionId,+ tabId,+ kind: tab.kind,+ err,+ });return;}}@@ -675,7 +765,12 @@ export async function closeTab(const shouldContinue = await plugin.onBeforeClose(tab.state, { tabId, sessionId });if (shouldContinue === false) return;} catch (err) {- log.warn('plugin onBeforeClose failed (ignored)', { sessionId, tabId, kind: tab.kind, err });+ log.warn('plugin onBeforeClose failed (ignored)', {+ sessionId,+ tabId,+ kind: tab.kind,+ err,+ });}}}@@ -766,11 +861,14 @@ export async function closeTab(// 但只有 cache 仍指向我们尝试设置的 active 时才清,否则用户已切到// 别的 tab 且该 tab 已成功落库,强清会让 setActiveTab 对那个 tab// 多发一次 IPC,结果虽等价但语义上是"回退到无 active"的短暂漂移。- log.warn('closeTab: post-close setActive failed; clearing cache activeTabId for recovery', {- sessionId,- tabId,- err: activeErr,- });+ log.warn(+ 'closeTab: post-close setActive failed; clearing cache activeTabId for recovery',+ {+ sessionId,+ tabId,+ err: activeErr,+ },+ );const current = getBucket(sessionId);if (current.hydrated &&@@ -807,9 +905,7 @@ export async function closeTab(// activeTabId:只有"原 active 就是被关的 tab,且当前 active 仍是关闭时选出// 的替代者"才恢复回被关 tab;并发操作已把 active 指向别处时尊重现值。const activeTabId =- prev.activeTabId === tabId && now.activeTabId === nextActiveId- ? tabId- : now.activeTabId;+ prev.activeTabId === tabId && now.activeTabId === nextActiveId ? tabId : now.activeTabId;setBucket(sessionId, { tabs: restored, activeTabId });}throw err;@@ -827,10 +923,7 @@ export async function closeAllTabs(sessionId: string): Promise<void> {}/** 切换激活 tab —— 同 id 即 noop。失败回滚。 */-export async function setActiveTab(- sessionId: string,- tabId: string | null,-): Promise<void> {+export async function setActiveTab(sessionId: string, tabId: string | null): Promise<void> {const prev = getBucket(sessionId);if (tabId === prev.activeTabId) return;// closeTab 已把关闭中的 tab 从 bucket 乐观移除:若此时用户点击该 tab(或@@ -895,10 +988,7 @@ export function patchTabState(}/** 重排序 tab,orderedIds 必须包含 same session 当前**全部** tab id。失败回滚。 */-export async function reorderTabs(- sessionId: string,- orderedIds: string[],-): Promise<void> {+export async function reorderTabs(sessionId: string, orderedIds: string[]): Promise<void> {const prev = getBucket(sessionId);if (orderedIds.length !== prev.tabs.length) return;const map = new Map(prev.tabs.map((t) => [t.id, t]));@@ -933,8 +1023,10 @@ export async function reorderTabs(*/export function invalidateSessionCaches(): void {const sessionIds = [...cache.keys()];+ cacheGeneration += 1;cache.clear();inflight.clear();+ singletonInflight.clear();// 宿主迁移不等于登出:已入队写仍应继续落库。这里不能像 _resetStore 一样// resolve 后丢弃,否则新 renderer 会 hydrate 到旧 URL / title / reveal state。for (const sessionId of sessionIds) notify(sessionId);@@ -950,8 +1042,10 @@ export function subscribe(listener: Listener): () => void {/** 测试 / 登出清理。 */export function _resetStore(): void {+ cacheGeneration += 1;cache.clear();inflight.clear();+ singletonInflight.clear();memoryOnlySessions.clear();closeInterceptors.clear();pendingTabCreates.clear();diff --git a/apps/desktop/src/renderer/features/right-sidebar/types.ts b/apps/desktop/src/renderer/features/right-sidebar/types.tsindex ad03ebb6d0..5cd7496c1f 100644--- a/apps/desktop/src/renderer/features/right-sidebar/types.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/types.ts@@ -27,6 +27,7 @@ export type BuiltinTabKindId =| 'terminal'| 'review'| 'orca-workers'+ | 'subagents'| 'background-tasks'| 'resource-usage';export type TabKindId = BuiltinTabKindId | `ghost:${string}`;diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 1032b56c1b..0e5e31afb3 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -4437,6 +4437,7 @@"browser": "Browser","terminal": "Terminal","review": "Review",+ "subagents": "Subagent","backgroundTasks": "Background tasks","resourceUsage": "Resource Usage","collaboration": "Team",@@ -4462,6 +4463,8 @@"fileSub": "Files","openReview": "Open review","reviewSub": "Review",+ "openSubagents": "Open Subagent",+ "subagentsSub": "Durable child work","openBackgroundTasks": "Open background tasks","backgroundTasksSub": "Background tasks","openResourceUsage": "Open Resource Usage",@@ -4831,6 +4834,58 @@"expandAllAria": "Expand all files","collapseAllAria": "Collapse all files"},+ "subagents": {+ "running": "Running",+ "finished": "Finished",+ "empty": "No Subagent in this task yet",+ "emptyDetail": "Subagents created while this task runs will remain available here.",+ "loading": "Loading Subagents…",+ "unavailable": "Subagent history is unavailable",+ "unavailableDetail": "This remote device or older app version does not expose durable Subagent records yet.",+ "loadFailed": "Could not load Subagents",+ "retry": "Retry",+ "loadEarlier": "Load earlier Subagents",+ "untitled": "Subagent",+ "notFound": "Subagent not found",+ "back": "Back",+ "harness": "Harness",+ "model": "Model",+ "context": "Parent context",+ "contextValues": {+ "unknown": "Not reported by the Harness",+ "snapshot": "Parent task snapshot",+ "live": "Live parent task"+ },+ "assignment": "Assignment",+ "returnedResult": "Returned result",+ "resultTruncated": "The returned result was truncated for display.",+ "latestUpdate": "Latest update",+ "activity": "Activity",+ "noActivity": "No activity details were reported.",+ "transcript": "Transcript",+ "noTranscript": "No transcript entries were reported.",+ "transcriptUnavailable": "This Harness has not exposed a full child transcript to Cindy yet. Returned results and lifecycle activity remain available.",+ "transcriptRoles": {+ "parent": "Parent",+ "subagent": "Subagent",+ "tool": "Tool",+ "system": "System"+ },+ "lastTool": "Last tool: {{tool}}",+ "tokens": "{{value}} tokens",+ "activityKinds": {+ "started": "Started",+ "progress": "Progress",+ "message": "Message",+ "question": "Question",+ "decision": "Decision",+ "resumed": "Resumed",+ "steered": "Steered",+ "completed": "Completed",+ "failed": "Failed",+ "stopped": "Stopped"+ }+ },"backgroundTasks": {"running": "Running","completed": "Completed",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 47a78d2d47..b7cf88f233 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -4435,6 +4435,7 @@"browser": "ブラウザ","terminal": "ターミナル","review": "レビュー",+ "subagents": "サブエージェント","backgroundTasks": "バックグラウンドタスク","resourceUsage": "リソース使用量","collaboration": "コラボ",@@ -4460,6 +4461,8 @@"fileSub": "Files","openReview": "レビューを開く","reviewSub": "Review",+ "openSubagents": "サブエージェントを開く",+ "subagentsSub": "後から確認できる子タスク","openBackgroundTasks": "バックグラウンドタスクを開く","backgroundTasksSub": "Background tasks","openResourceUsage": "リソース使用量を開く",@@ -4829,6 +4832,58 @@"expandAllAria": "すべてのファイルを展開","collapseAllAria": "すべてのファイルを折りたたむ"},+ "subagents": {+ "running": "実行中",+ "finished": "終了",+ "empty": "このタスクにはまだサブエージェントがありません",+ "emptyDetail": "このタスクで作成されたサブエージェントは、ここに保持されます。",+ "loading": "サブエージェントを読み込み中…",+ "unavailable": "サブエージェント履歴を利用できません",+ "unavailableDetail": "このリモートデバイスまたは旧バージョンは、永続的なサブエージェント記録にまだ対応していません。",+ "loadFailed": "サブエージェントを読み込めませんでした",+ "retry": "再試行",+ "loadEarlier": "以前のサブエージェントを読み込む",+ "untitled": "サブエージェント",+ "notFound": "サブエージェントが見つかりません",+ "back": "戻る",+ "harness": "Harness",+ "model": "モデル",+ "context": "親タスクのコンテキスト",+ "contextValues": {+ "unknown": "Harness から報告されていません",+ "snapshot": "親タスクのスナップショット",+ "live": "親タスクをリアルタイム参照"+ },+ "assignment": "担当内容",+ "returnedResult": "返された結果",+ "resultTruncated": "返された結果は表示用に省略されています。",+ "latestUpdate": "最新の更新",+ "activity": "アクティビティ",+ "noActivity": "アクティビティの詳細は報告されていません。",+ "transcript": "記録",+ "noTranscript": "記録は報告されていません。",+ "transcriptUnavailable": "この Harness は完全な子タスク記録をまだ Cindy に提供していません。返された結果とライフサイクルは保持されます。",+ "transcriptRoles": {+ "parent": "親タスク",+ "subagent": "サブエージェント",+ "tool": "ツール",+ "system": "システム"+ },+ "lastTool": "最後のツール:{{tool}}",+ "tokens": "{{value}} tokens",+ "activityKinds": {+ "started": "開始",+ "progress": "進行",+ "message": "メッセージ",+ "question": "質問",+ "decision": "決定",+ "resumed": "再開",+ "steered": "方向調整",+ "completed": "完了",+ "failed": "失敗",+ "stopped": "停止"+ }+ },"backgroundTasks": {"running": "実行中","completed": "完了",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 6bf2c37c41..562da23534 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -4435,6 +4435,7 @@"browser": "브라우저","terminal": "터미널","review": "리뷰",+ "subagents": "하위 에이전트","backgroundTasks": "백그라운드 작업","resourceUsage": "리소스 사용량","collaboration": "협업",@@ -4460,6 +4461,8 @@"fileSub": "Files","openReview": "리뷰 열기","reviewSub": "Review",+ "openSubagents": "하위 에이전트 열기",+ "subagentsSub": "나중에도 볼 수 있는 하위 작업","openBackgroundTasks": "백그라운드 작업 열기","backgroundTasksSub": "Background tasks","openResourceUsage": "리소스 사용량 열기",@@ -4829,6 +4832,58 @@"expandAllAria": "모든 파일 펼치기","collapseAllAria": "모든 파일 접기"},+ "subagents": {+ "running": "실행 중",+ "finished": "종료됨",+ "empty": "이 작업에는 아직 하위 에이전트가 없습니다",+ "emptyDetail": "이 작업에서 생성된 하위 에이전트는 계속 여기에 보관됩니다.",+ "loading": "하위 에이전트 불러오는 중…",+ "unavailable": "하위 에이전트 기록을 사용할 수 없습니다",+ "unavailableDetail": "이 원격 기기 또는 이전 앱 버전은 아직 영구 하위 에이전트 기록을 제공하지 않습니다.",+ "loadFailed": "하위 에이전트를 불러올 수 없습니다",+ "retry": "다시 시도",+ "loadEarlier": "이전 하위 에이전트 불러오기",+ "untitled": "하위 에이전트",+ "notFound": "하위 에이전트를 찾을 수 없습니다",+ "back": "뒤로",+ "harness": "Harness",+ "model": "모델",+ "context": "상위 작업 컨텍스트",+ "contextValues": {+ "unknown": "Harness에서 보고하지 않음",+ "snapshot": "상위 작업 스냅샷",+ "live": "실시간 상위 작업"+ },+ "assignment": "할당 내용",+ "returnedResult": "반환된 결과",+ "resultTruncated": "반환된 결과가 표시를 위해 일부 생략되었습니다.",+ "latestUpdate": "최근 업데이트",+ "activity": "활동",+ "noActivity": "활동 세부 정보가 보고되지 않았습니다.",+ "transcript": "전체 기록",+ "noTranscript": "전체 기록 항목이 보고되지 않았습니다.",+ "transcriptUnavailable": "이 Harness는 아직 전체 하위 작업 기록을 Cindy에 제공하지 않습니다. 반환된 결과와 수명 주기 활동은 계속 보관됩니다.",+ "transcriptRoles": {+ "parent": "상위 작업",+ "subagent": "하위 에이전트",+ "tool": "도구",+ "system": "시스템"+ },+ "lastTool": "최근 도구: {{tool}}",+ "tokens": "{{value}} tokens",+ "activityKinds": {+ "started": "시작됨",+ "progress": "진행",+ "message": "메시지",+ "question": "질문",+ "decision": "결정",+ "resumed": "재개됨",+ "steered": "방향 조정됨",+ "completed": "완료됨",+ "failed": "실패",+ "stopped": "중지됨"+ }+ },"backgroundTasks": {"running": "실행 중","completed": "완료",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex f4e76ec5d9..7cd3099048 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -4435,6 +4435,7 @@"browser": "浏览器","terminal": "终端","review": "审查",+ "subagents": "Subagent","backgroundTasks": "后台任务","resourceUsage": "资源用量","collaboration": "协同",@@ -4460,6 +4461,8 @@"fileSub": "Files","openReview": "打开审查","reviewSub": "Review",+ "openSubagents": "打开 Subagent",+ "subagentsSub": "可持续回看的子任务","openBackgroundTasks": "打开后台任务","backgroundTasksSub": "Background tasks","openResourceUsage": "打开资源用量",@@ -4829,6 +4832,58 @@"expandAllAria": "展开所有文件","collapseAllAria": "收起所有文件"},+ "subagents": {+ "running": "运行中",+ "finished": "已结束",+ "empty": "本任务还没有 Subagent",+ "emptyDetail": "任务运行时创建的 Subagent 会持续保留在这里。",+ "loading": "正在读取 Subagent…",+ "unavailable": "Subagent 历史暂不可用",+ "unavailableDetail": "该远端设备或旧版应用尚未提供持久化的 Subagent 记录。",+ "loadFailed": "无法读取 Subagent",+ "retry": "重试",+ "loadEarlier": "读取更早的 Subagent",+ "untitled": "Subagent",+ "notFound": "未找到该 Subagent",+ "back": "返回",+ "harness": "Harness",+ "model": "模型",+ "context": "父任务上下文",+ "contextValues": {+ "unknown": "Harness 未报告",+ "snapshot": "父任务快照",+ "live": "实时父任务"+ },+ "assignment": "任务内容",+ "returnedResult": "回传结果",+ "resultTruncated": "回传结果过长,当前仅显示部分内容。",+ "latestUpdate": "最近更新",+ "activity": "活动记录",+ "noActivity": "Harness 暂未提供活动详情。",+ "transcript": "完整记录",+ "noTranscript": "Harness 暂未提供完整记录。",+ "transcriptUnavailable": "该 Harness 尚未向 Cindy 提供完整的子任务记录;已回传的结果和生命周期活动仍会保留。",+ "transcriptRoles": {+ "parent": "父任务",+ "subagent": "Subagent",+ "tool": "工具",+ "system": "系统"+ },+ "lastTool": "最近工具:{{tool}}",+ "tokens": "{{value}} tokens",+ "activityKinds": {+ "started": "已启动",+ "progress": "进展",+ "message": "消息",+ "question": "提问",+ "decision": "决定",+ "resumed": "已继续",+ "steered": "已调整方向",+ "completed": "已完成",+ "failed": "失败",+ "stopped": "已停止"+ }+ },"backgroundTasks": {"running": "运行中","completed": "已完成",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex ad039deac3..594368ed30 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -4435,6 +4435,7 @@"browser": "瀏覽器","terminal": "終端","review": "審查",+ "subagents": "Subagent","backgroundTasks": "後臺任務","resourceUsage": "資源用量","collaboration": "協同",@@ -4460,6 +4461,8 @@"fileSub": "Files","openReview": "開啟審查","reviewSub": "Review",+ "openSubagents": "開啟 Subagent",+ "subagentsSub": "可持續回看的子任務","openBackgroundTasks": "開啟後臺任務","backgroundTasksSub": "Background tasks","openResourceUsage": "開啟資源用量",@@ -4829,6 +4832,58 @@"expandAllAria": "展開所有檔案","collapseAllAria": "收起所有檔案"},+ "subagents": {+ "running": "執行中",+ "finished": "已結束",+ "empty": "本任務還沒有 Subagent",+ "emptyDetail": "任務執行時建立的 Subagent 會持續保留在這裡。",+ "loading": "正在讀取 Subagent…",+ "unavailable": "Subagent 歷史暫時無法使用",+ "unavailableDetail": "該遠端裝置或舊版應用程式尚未提供持久化的 Subagent 記錄。",+ "loadFailed": "無法讀取 Subagent",+ "retry": "重試",+ "loadEarlier": "讀取更早的 Subagent",+ "untitled": "Subagent",+ "notFound": "找不到該 Subagent",+ "back": "返回",+ "harness": "Harness",+ "model": "模型",+ "context": "父任務上下文",+ "contextValues": {+ "unknown": "Harness 未回報",+ "snapshot": "父任務快照",+ "live": "即時父任務"+ },+ "assignment": "任務內容",+ "returnedResult": "回傳結果",+ "resultTruncated": "回傳結果過長,目前僅顯示部分內容。",+ "latestUpdate": "最近更新",+ "activity": "活動記錄",+ "noActivity": "Harness 暫未提供活動詳情。",+ "transcript": "完整記錄",+ "noTranscript": "Harness 暫未提供完整記錄。",+ "transcriptUnavailable": "該 Harness 尚未向 Cindy 提供完整的子任務記錄;已回傳的結果和生命週期活動仍會保留。",+ "transcriptRoles": {+ "parent": "父任務",+ "subagent": "Subagent",+ "tool": "工具",+ "system": "系統"+ },+ "lastTool": "最近工具:{{tool}}",+ "tokens": "{{value}} tokens",+ "activityKinds": {+ "started": "已啟動",+ "progress": "進度",+ "message": "訊息",+ "question": "提問",+ "decision": "決定",+ "resumed": "已繼續",+ "steered": "已調整方向",+ "completed": "已完成",+ "failed": "失敗",+ "stopped": "已停止"+ }+ },"backgroundTasks": {"running": "執行中","completed": "已完成",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 4146b035a4..4c4b1d4074 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1913,9 +1913,7 @@ interface ElectronAPI {* `LOG_UPLOAD_EMPTY`(采到 0 条)/ `LOG_UPLOAD_FAILED`(网络)/ `LOG_UPLOAD_BUSY`。*/uploadLogsNow: () => Promise<LogUploadResult>;- onLogUploadSettingsChange: (- callback: (payload: LogUploadSettingsPayload) => void,- ) => () => void;+ onLogUploadSettingsChange: (callback: (payload: LogUploadSettingsPayload) => void) => () => void;// ── Profile 编辑(设置 → 用户卡片编辑名字 / 头像;直写服务端,跨设备生效) ──profileGetState: () => Promise<{@@ -4101,6 +4099,20 @@ interface ElectronAPI {}>;activeTabId: string | null;}>;+ ensureSingleton: (input: { sessionId: string; kind: string; state?: unknown }) => Promise<{+ tab: {+ id: string;+ sessionId: string;+ kind: string;+ position: number;+ state: unknown;+ isActive: boolean;+ createdAt: number;+ updatedAt: number;+ } | null;+ created: boolean;+ persistable: boolean;+ }>;/** 新增 / 更新单个 tab;超 20 抛 RIGHT_SIDEBAR_TOO_MANY_TABS;state >16KB 抛 RIGHT_SIDEBAR_STATE_TOO_LARGE。 */upsert: (input: {id: string;@@ -4113,6 +4125,20 @@ interface ElectronAPI {setActive: (input: { sessionId: string; id: string | null }) => Promise<{ ok: true }>;reorder: (input: { sessionId: string; orderedIds: string[] }) => Promise<{ ok: true }>;};+ subagentRuns: {+ list: (+ input: import('@cindy/maker-shared/subagent-workspace').SubagentRunsListRequest,+ ) => Promise<import('@cindy/maker-shared/subagent-workspace').SubagentRunsListResponse>;+ detail: (+ input: import('@cindy/maker-shared/subagent-workspace').SubagentRunDetailRequest,+ ) => Promise<import('@cindy/maker-shared/subagent-workspace').SubagentRunDetailResponse>;+ onChanged: (+ callback: (+ payload: import('@cindy/maker-shared/subagent-workspace').SubagentRunsChangedPayload,+ ownerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp,+ ) => void,+ ) => () => void;+ };projectAliases: {list: () => Promise<import('../shared/projectAliases').ProjectAlias[]>;set: (input: {@@ -5380,9 +5406,7 @@ interface ElectronAPI {id: string,action: import('../shared/turnChangeSet').TurnChangeAction,) => Promise<import('../shared/turnChangeSet').TurnChangeActionResult>;- onTurnChangeSetUpdated: (- cb: (data: unknown, ownerStamp?: unknown) => void,- ) => () => void;+ onTurnChangeSetUpdated: (cb: (data: unknown, ownerStamp?: unknown) => void) => () => void;onEvent: (cb: (data: unknown) => void) => () => void;onStatusChanged: (cb: (data: unknown) => void) => () => void;onInteractionRequest: (cb: (data: unknown) => void) => () => void;diff --git a/apps/desktop/src/shared/rightSidebarWindow.ts b/apps/desktop/src/shared/rightSidebarWindow.tsindex 80108789b5..4c004180fa 100644--- a/apps/desktop/src/shared/rightSidebarWindow.ts+++ b/apps/desktop/src/shared/rightSidebarWindow.ts@@ -5,6 +5,8 @@* (主窗镜像 store + 子窗口根组件)。只放纯类型,不放运行时代码。*/+import type { SubagentProvider } from '@cindy/maker-shared/subagent-workspace';+import type { ConversationSearchJump } from './conversationSearchJump.js';/** 子窗口全局状态:detached 是持久化偏好,lastOpen 是重启恢复用的状态,open 是运行时窗口开闭。 */@@ -49,6 +51,17 @@ export type RsbWindowCommand =sessionId: string;focusTaskId?: string | null;}+ /** 打开/聚焦 Cindy 持久化的 Subagent 工作区(每个父任务单例)。 */+ | {+ type: 'open-subagents-tab';+ sessionId: string;+ focusRunId?: string | null;+ focusProvider?: SubagentProvider | null;+ /** False adds the singleton without replacing the user's active tab. */+ focusTab?: boolean;+ /** False persists the tab without expanding the sidebar. */+ revealSidebar?: boolean;+ }| {type: 'open-turn-review';sessionId: string;diff --git a/packages/maker-core/src/agents/claude-code/__tests__/translator-context-window.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/translator-context-window.test.tsindex eaee32f58e..09399fa1b9 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/translator-context-window.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/translator-context-window.test.ts@@ -149,17 +149,32 @@ describe('Claude Code translator context window', () => {status: 'running',title: 'Review auth flow',description: 'Check the auth flow',+ subagentObservation: {+ kind: 'spawn',+ logicalSubagentId: 'task-1',+ parentToolUseId: 'toolu-1',+ },});expect(events[1].data).toMatchObject({status: 'running',summary: 'Read login code',lastToolName: 'Read',usage: { totalTokens: 1200, toolUses: 3, durationMs: 2500 },+ subagentObservation: {+ kind: 'progress',+ logicalSubagentId: 'task-1',+ parentToolUseId: 'toolu-1',+ },});expect(events[2].data).toMatchObject({status: 'completed',outputFile: '/tmp/task.md',summary: 'Auth flow looks correct',+ subagentObservation: {+ kind: 'terminal',+ logicalSubagentId: 'task-1',+ parentToolUseId: 'toolu-1',+ },});});diff --git a/packages/maker-core/src/agents/claude-code/__tests__/translator-subagent-model.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/translator-subagent-model.test.tsindex d08f42e18b..137fe79d2c 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/translator-subagent-model.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/translator-subagent-model.test.ts@@ -274,6 +274,11 @@ describe('Claude Code translator subagent model attribution', () => {parentToolUseId: 'toolu_agent_a',status: 'running',model: 'codex/gpt-5.6-sol',+ subagentObservation: {+ kind: 'spawn',+ logicalSubagentId: 'agent-a',+ parentToolUseId: 'toolu_agent_a',+ },});});diff --git a/packages/maker-core/src/agents/claude-code/__tests__/translator-workflow.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/translator-workflow.test.tsindex 1dfb783a1c..e27056dca1 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/translator-workflow.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/translator-workflow.test.ts@@ -50,7 +50,173 @@ async function translateOne(msg: Record<string, unknown>): Promise<AgentEvent[]>return events;}+async function translateSequence(messages: Record<string, unknown>[]): Promise<AgentEvent[]> {+ const queue = createAsyncQueue<AgentEvent>();+ const ctx = {+ rt: newRuntimeState(),+ turn: createTurnState(),+ log: { debug: vi.fn(), info: vi.fn(), warn: vi.fn() },+ getModel: () => 'claude-sonnet-4-5',+ getEffort: () => 'high',+ getPermissionMode: () => 'auto',+ onSessionId: vi.fn(),+ getSdkSessionId: () => undefined,+ getLogTitle: () => undefined,+ getSubagentTaskUsage: (taskId: string) =>+ taskId.endsWith('remote') ? { totalTokens: 900 } : { totalTokens: 700 },+ tracker: new UsageTracker(),+ };+ for (const message of messages) {+ translateSdkMessage(message as never, queue, ctx as never);+ }+ queue.end();+ const events: AgentEvent[] = [];+ for await (const event of queue) events.push(event);+ return events;+}+describe('Claude Code translator — workflow / task_updated', () => {+ it.each(['local_agent', 'remote_agent'] as const)(+ 'locks a parentless %s identity through sparse progress and terminal frames',+ async (taskType) => {+ const taskId = taskType === 'remote_agent' ? 'task-remote' : 'task-local';+ const events = await translateSequence([+ {+ type: 'system',+ subtype: 'task_started',+ task_id: taskId,+ task_type: taskType,+ description: `Run ${taskType}`,+ },+ {+ type: 'system',+ subtype: 'task_progress',+ task_id: taskId,+ summary: 'Halfway',+ },+ {+ type: 'system',+ subtype: 'task_notification',+ task_id: taskId,+ status: 'completed',+ summary: 'Finished',+ usage: { total_tokens: 0, tool_uses: 4, duration_ms: 1200 },+ },+ ]);++ expect(events.map((event) => event.data)).toEqual([+ expect.objectContaining({+ taskId,+ taskType,+ status: 'running',+ subagentObservation: { kind: 'spawn', logicalSubagentId: taskId },+ }),+ expect.objectContaining({+ taskId,+ status: 'running',+ summary: 'Halfway',+ subagentObservation: { kind: 'progress', logicalSubagentId: taskId },+ }),+ expect.objectContaining({+ taskId,+ status: 'completed',+ summary: 'Finished',+ usage: {+ totalTokens: taskType === 'remote_agent' ? 900 : 700,+ toolUses: 4,+ durationMs: 1200,+ },+ subagentObservation: { kind: 'terminal', logicalSubagentId: taskId },+ }),+ ]);+ for (const event of events) {+ expect((event.data as Record<string, unknown>).parentToolUseId).toBeUndefined();+ }+ },+ );++ it('keeps the latched parentless identity on duplicate and out-of-order terminal updates', async () => {+ const events = await translateSequence([+ {+ type: 'system',+ subtype: 'task_started',+ task_id: 'task-local',+ task_type: 'local_agent',+ },+ {+ type: 'system',+ subtype: 'task_notification',+ task_id: 'task-local',+ status: 'completed',+ summary: 'Done',+ },+ {+ type: 'system',+ subtype: 'task_progress',+ task_id: 'task-local',+ summary: 'Late progress',+ },+ {+ type: 'system',+ subtype: 'task_notification',+ task_id: 'task-local',+ status: 'completed',+ summary: 'Done',+ },+ {+ type: 'system',+ subtype: 'task_updated',+ task_id: 'task-local',+ patch: { status: 'killed' },+ },+ ]);++ expect(events.map((event) => (event.data as Record<string, unknown>).subagentObservation)).toEqual([+ { kind: 'spawn', logicalSubagentId: 'task-local' },+ { kind: 'terminal', logicalSubagentId: 'task-local' },+ { kind: 'progress', logicalSubagentId: 'task-local' },+ { kind: 'terminal', logicalSubagentId: 'task-local' },+ { kind: 'terminal', logicalSubagentId: 'task-local' },+ ]);+ });++ it('does not latch unconfirmed tasks or excluded bash/workflow tasks as Subagents', async () => {+ const events = await translateSequence([+ { type: 'system', subtype: 'task_started', task_id: 'unknown-task' },+ { type: 'system', subtype: 'task_notification', task_id: 'unknown-task', status: 'completed' },+ {+ type: 'system',+ subtype: 'task_started',+ task_id: 'bash-task',+ task_type: 'local_bash',+ tool_use_id: 'toolu-bash',+ },+ {+ type: 'system',+ subtype: 'task_notification',+ task_id: 'bash-task',+ status: 'completed',+ },+ {+ type: 'system',+ subtype: 'task_started',+ task_id: 'workflow-task',+ task_type: 'local_workflow',+ tool_use_id: 'toolu-workflow',+ },+ {+ type: 'system',+ subtype: 'task_updated',+ task_id: 'workflow-task',+ patch: { status: 'completed' },+ },+ ]);++ for (const event of events) {+ expect((event.data as Record<string, unknown>).subagentObservation).toBeUndefined();+ }+ });+it('maps task_updated patch.status=completed → completed (merge by taskId, no parentToolUseId)', async () => {const events = await translateOne({type: 'system',diff --git a/packages/maker-core/src/agents/claude-code/translator.ts b/packages/maker-core/src/agents/claude-code/translator.tsindex 5ec77a8e93..e18625e814 100644--- a/packages/maker-core/src/agents/claude-code/translator.ts+++ b/packages/maker-core/src/agents/claude-code/translator.ts@@ -123,6 +123,14 @@ export interface RuntimeState {resolvedSubagentModelByParentToolUseId: Map<string, string>;/** task_id 到启动它的 Agent tool_use.id 的别名映射。 */subagentParentToolUseIdByTaskId: Map<string, string>;+ /**+ * 已被 SDK 明确标记为 local_agent / remote_agent 的 task_id。+ * Claude 后续进度与终态帧可能省略 task_type / tool_use_id;一旦确认,+ * 该身份在本 RuntimeState 生命周期内保持单向锁存,避免持久记录停在 running。+ */+ confirmedSubagentTaskIds: Set<string>;+ /** 明确属于 local_bash / local_workflow 的 task_id;稀疏后续帧继续排除。 */+ excludedSubagentTaskIds: Set<string>;/*** 上一次 SDK assistant 消息提取出来的 agentMeta (uuid / sdkSessionId / model / ...).* 主 agent 的 stream_event 累积时用它补齐 transcript 锚点;subagent stream@@ -144,6 +152,8 @@ export function newRuntimeState(): RuntimeState {streamModelByParentToolUseId: new Map(),resolvedSubagentModelByParentToolUseId: new Map(),subagentParentToolUseIdByTaskId: new Map(),+ confirmedSubagentTaskIds: new Set(),+ excludedSubagentTaskIds: new Set(),lastAssistantMeta: null,lastResultUsageAggregate: null,};@@ -551,25 +561,30 @@ export function translateSdkMessage(if (subagentLaunch) {const { taskId, parentToolUseId, model, prompt } = subagentLaunch;ctx.rt.subagentParentToolUseIdByTaskId.set(taskId, parentToolUseId);+ ctx.rt.confirmedSubagentTaskIds.add(taskId);+ ctx.rt.excludedSubagentTaskIds.delete(taskId);if (model) {ctx.rt.resolvedSubagentModelByParentToolUseId.set(parentToolUseId, model);}if (prompt) {ctx.onSubagentTaskLaunched?.({ taskId, parentToolUseId, prompt, model });}- if (model) {- queue.push({- type: 'agent_task_update',- data: {- provider: 'claude-code',- taskId,+ queue.push({+ type: 'agent_task_update',+ data: {+ provider: 'claude-code',+ taskId,+ parentToolUseId,+ status: 'running',+ subagentObservation: {+ kind: 'spawn',+ logicalSubagentId: taskId,parentToolUseId,- status: 'running',- model,},- source: 'claude-code',- });- }+ ...(model ? { model } : {}),+ },+ source: 'claude-code',+ });}// 单独遍历: 不能复用 extractToolResultFullText, 见 onToolResultDone JSDoc。const completedToolUseIds = new Set(fullPairs.map((pair) => pair.toolUseId));@@ -854,7 +869,7 @@ function handleSystem(// 与上面三个事件共用 agent_task_update 通道 —— 下游 makerChatStore 按 taskId 做// 字段级 merge,故这里只需带上补丁里变化的字段。if (msg.subtype === 'task_updated') {- const update = toClaudeTaskUpdatedPatch(msg);+ const update = toClaudeTaskUpdatedPatch(msg, ctx.rt);if (update) {queue.push({type: 'agent_task_update',@@ -917,6 +932,33 @@ function toClaudeTaskUpdate(msg: {: undefined;// CLI 对纯心跳帧节流省略该字段;收窄失败/缺失都不下发(undefined = 下游沿用上一帧)。const workflowProgress = normalizeWorkflowProgressEntries(msg.workflow_progress);+ const taskType = msg.task_type;+ const explicitlySubagent = taskType === 'local_agent' || taskType === 'remote_agent';+ const explicitlyExcluded = taskType === 'local_bash' || taskType === 'local_workflow';+ if (explicitlySubagent) {+ rt.confirmedSubagentTaskIds.add(msg.task_id);+ rt.excludedSubagentTaskIds.delete(msg.task_id);+ } else if (explicitlyExcluded && !rt.confirmedSubagentTaskIds.has(msg.task_id)) {+ rt.excludedSubagentTaskIds.add(msg.task_id);+ }+ const isExcludedTask =+ !rt.confirmedSubagentTaskIds.has(msg.task_id) &&+ (explicitlyExcluded || rt.excludedSubagentTaskIds.has(msg.task_id));+ const isKnownSubagent =+ !isExcludedTask &&+ (Boolean(parentToolUseId) || explicitlySubagent || rt.confirmedSubagentTaskIds.has(msg.task_id));+ const subagentObservation = !isExcludedTask && isKnownSubagent+ ? {+ kind:+ msg.subtype === 'task_started'+ ? 'spawn' as const+ : msg.subtype === 'task_notification'+ ? 'terminal' as const+ : 'progress' as const,+ logicalSubagentId: msg.task_id,+ ...(parentToolUseId ? { parentToolUseId } : {}),+ }+ : undefined;return {provider: 'claude-code',taskId: msg.task_id,@@ -932,6 +974,7 @@ function toClaudeTaskUpdate(msg: {...(usage ? { usage } : {}),...(model ? { model } : {}),...(workflowProgress ? { workflowProgress } : {}),+ ...(subagentObservation ? { subagentObservation } : {}),};}@@ -949,16 +992,34 @@ function toClaudeTaskUpdate(msg: {function toClaudeTaskUpdatedPatch(msg: {task_id?: string;patch?: { status?: string; description?: string; error?: string };-}): AgentTaskUpdateEventData | null {+}, rt: RuntimeState): AgentTaskUpdateEventData | null {if (!msg.task_id || !msg.patch) return null;const { status: rawStatus, description, error } = msg.patch;const hasStatus = typeof rawStatus === 'string' && rawStatus.length > 0;const hasError = typeof error === 'string' && error.length > 0;if (!hasStatus && !hasError) return null;+ const status = mapTaskUpdatedStatus(rawStatus, hasError);+ const parentToolUseId = rt.subagentParentToolUseIdByTaskId.get(msg.task_id);+ const isExcludedTask =+ !rt.confirmedSubagentTaskIds.has(msg.task_id) &&+ rt.excludedSubagentTaskIds.has(msg.task_id);+ const isKnownSubagent =+ !isExcludedTask &&+ (Boolean(parentToolUseId) || rt.confirmedSubagentTaskIds.has(msg.task_id));return {provider: 'claude-code',taskId: msg.task_id,- status: mapTaskUpdatedStatus(rawStatus, hasError),+ ...(parentToolUseId ? { parentToolUseId } : {}),+ status,+ ...(isKnownSubagent+ ? {+ subagentObservation: {+ kind: status === 'running' ? 'progress' : 'terminal',+ logicalSubagentId: msg.task_id,+ ...(parentToolUseId ? { parentToolUseId } : {}),+ },+ }+ : {}),...(description ? { title: description } : {}),...(hasError ? { summary: error } : {}),};diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex e730d6d91e..6fa2383f53 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -16940,7 +16940,16 @@ describe('CodexAgent turn lifecycle', () => {expect(reconstructedTaskUpdate).toMatchObject({type: 'agent_task_update',turnScope: 'background',- data: { taskId: 'collab-completed-only', status: 'completed' },+ data: {+ taskId: 'collab-completed-only',+ status: 'completed',+ subagentObservation: {+ kind: 'spawn',+ logicalSubagentId: 'collab-completed-only',+ parentToolUseId: 'collab-completed-only',+ providerRunIds: ['child-thread'],+ },+ },});expect([reconstructedFullResult.backgroundTurnStartedAt,diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 340e8c5fa6..0122f367b4 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -3821,6 +3821,11 @@ export class CodexAgent extends BaseAgent {taskId: update.taskId,parentToolUseId: update.taskId,status: update.status,+ subagentObservation: {+ kind: update.status === 'running' ? 'progress' : 'terminal',+ logicalSubagentId: update.taskId,+ parentToolUseId: update.taskId,+ },...(update.agentPath ? { title: update.agentPath } : {}),...(update.model !== undefined ? { model: update.model } : {}),usage: {diff --git a/packages/maker-core/src/agents/codex/translator.test.ts b/packages/maker-core/src/agents/codex/translator.test.tsindex 4d38d3b348..c69cec1831 100644--- a/packages/maker-core/src/agents/codex/translator.test.ts+++ b/packages/maker-core/src/agents/codex/translator.test.ts@@ -1485,6 +1485,12 @@ describe('translateItemNotification collabAgentToolCall', () => {title: 'spawnAgent',description: 'Review the auth flow',receiverThreadIds: ['thread-2'],+ subagentObservation: {+ kind: 'spawn',+ logicalSubagentId: 'collab-1',+ parentToolUseId: 'collab-1',+ providerRunIds: ['thread-2'],+ },});expect(events[2].data).toMatchObject({toolUseId: 'collab-1',@@ -1495,6 +1501,77 @@ describe('translateItemNotification collabAgentToolCall', () => {status: 'completed',summary: 'thread-2: done',});+ expect(events[4].data).not.toHaveProperty('subagentObservation');+ });++ it('marks a completed-only spawn as a creation-capable Subagent observation', async () => {+ const q = createAsyncQueue<AgentEvent>();+ const ctx = makeCtx(newCodexRuntimeState());+ translateItemNotification(+ 'completed',+ {+ threadId: 'thread-1',+ turnId: 'turn-1',+ item: {+ type: 'collabAgentToolCall',+ id: 'completed-only-spawn',+ tool: 'spawnAgent',+ status: 'completed',+ senderThreadId: 'thread-1',+ receiverThreadIds: ['thread-2'],+ prompt: 'Finish without a started notification',+ agentsStates: { 'thread-2': { status: 'done' } },+ },+ },+ q,+ ctx,+ );++ const events = await collect(q);+ expect(events.map((event) => event.type)).toEqual([+ 'tool_use',+ 'tool_result_full',+ 'tool_result',+ 'agent_task_update',+ ]);+ expect(events[3].data).toMatchObject({+ provider: 'codex',+ taskId: 'completed-only-spawn',+ status: 'completed',+ subagentObservation: {+ kind: 'spawn',+ logicalSubagentId: 'completed-only-spawn',+ parentToolUseId: 'completed-only-spawn',+ providerRunIds: ['thread-2'],+ },+ });+ });++ it('keeps wait/send/resume control updates live-only', async () => {+ const q = createAsyncQueue<AgentEvent>();+ const ctx = makeCtx(newCodexRuntimeState());+ const params = {+ threadId: 'thread-1',+ turnId: 'turn-1',+ item: {+ type: 'collabAgentToolCall',+ id: 'wait-1',+ tool: 'wait',+ status: 'inProgress',+ senderThreadId: 'thread-1',+ receiverThreadIds: ['child-a', 'child-b'],+ agentsStates: {},+ },+ };++ translateItemNotification('started', params, q, ctx);++ const update = (await collect(q)).find((event) => event.type === 'agent_task_update');+ expect(update?.data).toMatchObject({+ taskId: 'wait-1',+ receiverThreadIds: ['child-a', 'child-b'],+ });+ expect(update?.data).not.toHaveProperty('subagentObservation');});});@@ -1548,6 +1625,13 @@ describe('translateItemNotification subAgentActivity', () => {status: 'running',title: '/root/survey_startup',model: 'gpt-5.6-terra',+ receiverThreadIds: ['thread-2'],+ subagentObservation: {+ kind: 'spawn',+ logicalSubagentId: 'spawn-1',+ parentToolUseId: 'spawn-1',+ providerRunIds: ['thread-2'],+ },});});diff --git a/packages/maker-core/src/agents/codex/translator.ts b/packages/maker-core/src/agents/codex/translator.tsindex 47a97648ed..cc8d134fac 100644--- a/packages/maker-core/src/agents/codex/translator.ts+++ b/packages/maker-core/src/agents/codex/translator.ts@@ -1865,7 +1865,12 @@ function handleCollabAgentToolCall(});queue.push({type: 'agent_task_update',- data: toCodexTaskUpdate(item, isError ? 'failed' : 'completed', fullText),+ data: toCodexTaskUpdate(+ item,+ isError ? 'failed' : 'completed',+ fullText,+ !hadToolUse,+ ),source: 'codex',});}@@ -1998,6 +2003,13 @@ function handleSubAgentActivity(taskId: item.id,parentToolUseId: item.id,status: 'running',+ subagentObservation: {+ kind: 'spawn',+ logicalSubagentId: item.id,+ parentToolUseId: item.id,+ ...(item.agentThreadId ? { providerRunIds: [item.agentThreadId] } : {}),+ },+ ...(item.agentThreadId ? { receiverThreadIds: [item.agentThreadId] } : {}),...(agentPath ? { title: agentPath } : {}),...(model ? { model } : {}),},@@ -2009,7 +2021,19 @@ function toCodexTaskUpdate(item: CollabAgentToolCallItem,status: AgentTaskStatus,summary?: string,+ completedOnly = false,): AgentTaskUpdateEventData {+ const isSpawn = item.tool.toLowerCase().startsWith('spawn');+ const subagentObservation = isSpawn && (status !== 'completed' || completedOnly)+ ? {+ kind: status === 'running' || completedOnly ? 'spawn' as const : 'terminal' as const,+ logicalSubagentId: item.id,+ parentToolUseId: item.id,+ ...(status === 'running' || completedOnly+ ? { providerRunIds: item.receiverThreadIds }+ : {}),+ }+ : undefined;return {provider: 'codex',taskId: item.id,@@ -2021,6 +2045,7 @@ function toCodexTaskUpdate(...(item.model ? { model: item.model } : {}),...(item.reasoningEffort ? { reasoningEffort: item.reasoningEffort } : {}),receiverThreadIds: item.receiverThreadIds,+ ...(subagentObservation ? { subagentObservation } : {}),raw: { tool: item.tool, agentsStates: item.agentsStates },};}diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.tsindex 5370f493d9..ab9aaa656f 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts@@ -31,6 +31,88 @@ function makeQueue(): { queue: AsyncQueue<AgentEvent>; events: AgentEvent[] } {const ev = (e: Record<string, unknown>): PiRpcEvent => e as unknown as PiRpcEvent;describe('pi translator', () => {+ it('marks only the Cindy subagent tool as a durable lifecycle', () => {+ const ctx = createPiTranslateContext(noopLogger);+ const { queue, events } = makeQueue();++ translatePiEvent(+ ev({ type: 'tool_execution_start', toolCallId: 'sa-1', toolName: 'subagent', args: {} }),+ queue,+ ctx,+ );+ translatePiEvent(+ ev({ type: 'tool_execution_end', toolCallId: 'sa-1', result: 'done', isError: false }),+ queue,+ ctx,+ );+ translatePiEvent(+ ev({ type: 'tool_execution_start', toolCallId: 'read-1', toolName: 'read', args: {} }),+ queue,+ ctx,+ );++ const updates = events.filter((event) => event.type === 'agent_task_update');+ expect(updates.map((event) => event.data)).toEqual([+ expect.objectContaining({+ taskId: 'sa-1',+ status: 'running',+ subagentObservation: expect.objectContaining({ kind: 'spawn' }),+ }),+ expect.objectContaining({+ taskId: 'sa-1',+ status: 'completed',+ subagentObservation: expect.objectContaining({ kind: 'terminal' }),+ }),+ ]);+ });++ it.each([+ ['failed', false, 'failed'],+ ['stopped', false, 'stopped'],+ ['stopped', true, 'stopped'],+ ['completed', true, 'completed'],+ ['running', true, 'failed'],+ ] as const)(+ 'preserves a reported %s Subagent status when the wrapper ends (isError=%s)',+ (reportedStatus, isError, expectedStatus) => {+ const ctx = createPiTranslateContext(noopLogger);+ const { queue, events } = makeQueue();++ translatePiEvent(+ ev({ type: 'tool_execution_start', toolCallId: 'sa-1', toolName: 'subagent', args: {} }),+ queue,+ ctx,+ );+ translatePiEvent(+ ev({+ type: 'tool_execution_update',+ toolCallId: 'sa-1',+ partialResult: {+ details: {+ __cindySubagent: 1,+ taskId: 'sa-1',+ status: reportedStatus,+ },+ },+ }),+ queue,+ ctx,+ );+ translatePiEvent(+ ev({ type: 'tool_execution_end', toolCallId: 'sa-1', result: 'done', isError }),+ queue,+ ctx,+ );++ const updates = events.filter((event) => event.type === 'agent_task_update');+ expect(updates.at(-1)?.data).toMatchObject({+ taskId: 'sa-1',+ status: expectedStatus,+ subagentObservation: expect.objectContaining({ kind: 'terminal' }),+ });+ },+ );+it('emits live assistant deltas before the authoritative final text', () => {const ctx = createPiTranslateContext(noopLogger);const { queue, events } = makeQueue();diff --git a/packages/maker-core/src/agents/pi/__tests__/subagentProgress.test.ts b/packages/maker-core/src/agents/pi/__tests__/subagentProgress.test.tsindex 42911ea7db..130bb06a4b 100644--- a/packages/maker-core/src/agents/pi/__tests__/subagentProgress.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/subagentProgress.test.ts@@ -26,6 +26,11 @@ describe('parsePiSubagentProgress', () => {taskId: 'sa-1',parentToolUseId: 'sa-1',status: 'running',+ subagentObservation: {+ kind: 'progress',+ logicalSubagentId: 'sa-1',+ parentToolUseId: 'sa-1',+ },title: 'scout',description: 'survey the auth flow',model: 'claude-haiku-4-5',diff --git a/packages/maker-core/src/agents/pi/subagent-progress.ts b/packages/maker-core/src/agents/pi/subagent-progress.tsindex 6bf3e02f0f..4688be7a59 100644--- a/packages/maker-core/src/agents/pi/subagent-progress.ts+++ b/packages/maker-core/src/agents/pi/subagent-progress.ts@@ -135,6 +135,11 @@ export function parsePiSubagentProgress(partialResult: unknown): PiSubagentProgrtaskId,parentToolUseId: taskId,status,+ subagentObservation: {+ kind: status === 'running' ? 'progress' : 'terminal',+ logicalSubagentId: taskId,+ parentToolUseId: taskId,+ },...(title ? { title } : {}),...(description ? { description } : {}),...(summary ? { summary } : {}),diff --git a/packages/maker-core/src/agents/pi/translator.ts b/packages/maker-core/src/agents/pi/translator.tsindex e51b60863c..24d086a353 100644--- a/packages/maker-core/src/agents/pi/translator.ts+++ b/packages/maker-core/src/agents/pi/translator.ts@@ -16,7 +16,8 @@*/import type { Logger } from '../../interfaces/logger.js';-import type { AgentEvent, UsageSnapshot } from '../../types/index.js';+import { PI_SUBAGENT_TOOL_NAME } from '@cindy/maker-shared/agent-task';+import type { AgentEvent, AgentTaskUpdateEventData, UsageSnapshot } from '../../types/index.js';import type { AsyncQueue } from '../shared/async-queue.js';import type { PiRpcEvent } from './rpc-client.js';import { parsePiSubagentProgress, type PiSubagentUsage } from './subagent-progress.js';@@ -88,6 +89,14 @@ export interface PiTranslateContext {* 用来算增量,避免同一批用量被反复加进 turn 记账。与其它 turn 计数器同点(agent_start)清空。*/delegatedUsage: Map<string, PiSubagentUsage>;+ /**+ * Tool calls explicitly identified as Cindy's PI Subagent extension.+ *+ * Preserve the display title across the start/update/end event split so the+ * terminal update remains self-describing even for consumers that do not+ * reduce it into the preceding live-card state.+ */+ subagentToolCalls: Map<string, AgentTaskUpdateEventData>;}export function createPiTranslateContext(logger: Logger): PiTranslateContext {@@ -112,6 +121,7 @@ export function createPiTranslateContext(logger: Logger): PiTranslateContext {generationHeartbeatTimer: null,generationHeartbeatReliable: true,delegatedUsage: new Map(),+ subagentToolCalls: new Map(),};}@@ -128,6 +138,7 @@ function stopPiGenerationHeartbeat(ctx: PiTranslateContext): void {export function disposePiTranslateContext(ctx: PiTranslateContext): void {stopPiGenerationHeartbeat(ctx);ctx.isStreaming = false;+ ctx.subagentToolCalls.clear();}function samplePiGenerationHeartbeat(ctx: PiTranslateContext, now = Date.now()): void {@@ -293,6 +304,7 @@ export function translatePiEvent(// 与其它 turn 计数器同点清:新 turn 的委派用量不该跟上一 turn 的累计值作差,// 也避免长会话里 taskId 条目无界堆积。ctx.delegatedUsage.clear();+ ctx.subagentToolCalls.clear();pushStatus(queue, ctx, 'Working…', true);return;}@@ -359,16 +371,39 @@ export function translatePiEvent(}case 'tool_execution_start': {+ const toolUseId = String(event.toolCallId ?? '');+ const toolName = String(event.toolName ?? 'tool');+ const toolArgs = (event.args as Record<string, unknown>) ?? {};queue.push({type: 'tool_use',data: {- toolUseId: String(event.toolCallId ?? ''),- toolName: String(event.toolName ?? 'tool'),- input: (event.args as Record<string, unknown>) ?? {},+ toolUseId,+ toolName,+ input: toolArgs,},source: 'pi',});- pushStatus(queue, ctx, `Running ${String(event.toolName ?? 'tool')}…`, true);+ if (toolName === PI_SUBAGENT_TOOL_NAME && toolUseId) {+ const rawTitle = toolArgs.agent;+ const title = typeof rawTitle === 'string' && rawTitle.trim()+ ? rawTitle.trim().slice(0, 96)+ : undefined;+ const update: AgentTaskUpdateEventData = {+ provider: 'pi',+ taskId: toolUseId,+ parentToolUseId: toolUseId,+ status: 'running',+ ...(title ? { title } : {}),+ subagentObservation: {+ kind: 'spawn',+ logicalSubagentId: toolUseId,+ parentToolUseId: toolUseId,+ },+ };+ ctx.subagentToolCalls.set(toolUseId, update);+ queue.push({ type: 'agent_task_update', data: update, source: 'pi' });+ }+ pushStatus(queue, ctx, `Running ${toolName}…`, true);return;}@@ -378,6 +413,13 @@ export function translatePiEvent(// 其它工具的流式中间结果照旧忽略 —— 载荷不带标记时 parse 返回 null。const progress = parsePiSubagentProgress(event.partialResult);if (progress) {+ const previousUpdate = ctx.subagentToolCalls.get(progress.update.taskId);+ if (previousUpdate) {+ ctx.subagentToolCalls.set(progress.update.taskId, {+ ...previousUpdate,+ ...progress.update,+ });+ }// 委派用量并进本 turn 的记账。子代理是独立 pi 进程,它的请求不走父进程的 usage 流,// 不在这里显式并进来,done.data.usage 与 register.ts 持久化的 session token/cost// 就会漏掉全部子代理花费(review)。@@ -390,9 +432,10 @@ export function translatePiEvent(case 'tool_execution_end': {const toolUseId = String(event.toolCallId ?? '');const isError = event.isError === true;+ const fullText = toolResultFullText(event.result);queue.push({type: 'tool_result_full',- data: { toolUseId, fullText: toolResultFullText(event.result), isError },+ data: { toolUseId, fullText, isError },source: 'pi',});queue.push({@@ -400,6 +443,33 @@ export function translatePiEvent(data: { summary: isError ? 'failed' : 'done', toolUseIds: [toolUseId] },source: 'pi',});+ const subagentToolCall = ctx.subagentToolCalls.get(toolUseId);+ if (subagentToolCall) {+ ctx.subagentToolCalls.delete(toolUseId);+ // Progress is the authoritative child lifecycle. A successful batch+ // tool result can still contain failed children, while cancellation+ // may finish the wrapper with isError=true after the child stopped.+ // Only a still-running child is completed/failed by the wrapper frame.+ const status = subagentToolCall.status === 'running'+ ? (isError ? 'failed' : 'completed')+ : subagentToolCall.status;+ queue.push({+ type: 'agent_task_update',+ data: {+ ...subagentToolCall,+ provider: 'pi',+ taskId: toolUseId,+ parentToolUseId: toolUseId,+ status,+ subagentObservation: {+ kind: 'terminal',+ logicalSubagentId: toolUseId,+ parentToolUseId: toolUseId,+ },+ },+ source: 'pi',+ });+ }return;}diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.tsindex ebaef7bfa3..6974ce4dbc 100644--- a/packages/maker-core/src/types/events.ts+++ b/packages/maker-core/src/types/events.ts@@ -10,6 +10,7 @@*/import type { WorkflowProgressEntry } from '@cindy/maker-shared/agent-task';+import type { SubagentObservation } from '@cindy/maker-shared/subagent-observation';import type { PiRuntimeCapabilityManifest } from './pi-runtime-capabilities.js';export type AgentEventType =@@ -94,6 +95,8 @@ export interface AgentTaskUpdateEventData {model?: string | null;reasoningEffort?: string;receiverThreadIds?: string[];+ /** Explicit durable-workspace identity; control/task-card-only updates omit it. */+ subagentObservation?: SubagentObservation;/*** workflow 逐 agent 进度树(taskType=local_workflow 时 task_progress 事件携带,* 经 `@cindy/maker-shared/agent-task` 的 normalizeWorkflowProgressEntries 收窄截断)。diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.jsonindex e33a7a04e4..ac81555324 100644--- a/packages/maker-shared/package.json+++ b/packages/maker-shared/package.json@@ -56,6 +56,8 @@"./session-selection": "./src/sessionSelection.ts","./session-title": "./src/sessionTitle.ts","./synthetic-trigger": "./src/syntheticTrigger.ts",+ "./subagent-observation": "./src/subagentObservation.ts",+ "./subagent-workspace": "./src/subagentWorkspace.ts","./system-card": "./src/systemCard.ts","./thinking-text": "./src/thinkingText.ts","./turn-continuation": "./src/turnContinuation.ts",diff --git a/packages/maker-shared/src/__tests__/agentTask.test.ts b/packages/maker-shared/src/__tests__/agentTask.test.tsindex b6c5b78721..8be9b963b0 100644--- a/packages/maker-shared/src/__tests__/agentTask.test.ts+++ b/packages/maker-shared/src/__tests__/agentTask.test.ts@@ -4,10 +4,12 @@ import {buildAgentTaskCardModel,findAgentTaskUpdate,isAgentTaskToolName,+ isSubagentSpawnToolName,mergeAgentTaskUpdate,PI_SUBAGENT_TOOL_NAME,normalizeAgentTaskUpdate,normalizeWorkflowProgressEntries,+ subagentSpawnResultIndicatesRunning,type AgentTaskUpdate,type WorkflowProgressEntry,} from '../agentTask.js';@@ -38,6 +40,26 @@ describe('isAgentTaskToolName', () => {});});+describe('isSubagentSpawnToolName', () => {+ it('separates real launches from Codex control cards', () => {+ for (const name of ['Task', 'Agent', 'subagent', 'collab:spawn', 'collab:spawnAgent']) {+ expect(isSubagentSpawnToolName(name)).toBe(true);+ }+ for (const name of ['collab:wait', 'collab:sendInput', 'collab:resumeAgent', 'collab:closeAgent']) {+ expect(isSubagentSpawnToolName(name)).toBe(false);+ expect(isAgentTaskToolName(name)).toBe(true);+ }+ });+});++describe('subagentSpawnResultIndicatesRunning', () => {+ it('fails closed when a tool result is missing', () => {+ expect(subagentSpawnResultIndicatesRunning('Agent', undefined)).toBe(false);+ expect(subagentSpawnResultIndicatesRunning('Task', null)).toBe(false);+ expect(subagentSpawnResultIndicatesRunning('collab:spawnAgent', undefined)).toBe(false);+ });+});+describe('normalizeAgentTaskUpdate', () => {it('returns null without a taskId or parentToolUseId', () => {expect(normalizeAgentTaskUpdate(null)).toBeNull();@@ -340,6 +362,27 @@ describe('buildAgentTaskCardModel', () => {expect(model.status).toBe('running');});+ it('REPRO: recognizes the full async Claude Agent launch receipt', () => {+ const model = buildAgentTaskCardModel({+ toolName: 'Agent',+ toolInput: { run_in_background: true, prompt: 'keep working' },+ result: [+ 'Async agent launched successfully.',+ "agentId: agent-1 (internal ID - do not mention to user. Use SendMessage with to: 'agent-1' to continue this agent.)",+ 'The agent is working in the background. You will be notified automatically when it completes.',+ 'Briefly tell the user what you launched and end your response.',+ ].join('\n'),+ update: {+ provider: 'claude-code',+ taskId: 'agent-1',+ parentToolUseId: 'agent-1',+ status: 'running',+ },+ });++ expect(model.status).toBe('running');+ });+it.each(['in_progress', 'in-progress', 'started', 'active'])('keeps a V1 spawn running for the %s state summary',(state) => {diff --git a/packages/maker-shared/src/agentTask.ts b/packages/maker-shared/src/agentTask.tsindex e4492a348a..ce8b8dea9a 100644--- a/packages/maker-shared/src/agentTask.ts+++ b/packages/maker-shared/src/agentTask.ts@@ -8,10 +8,11 @@* the two clients stay in lockstep. This module is presentation-neutral (no i18n strings,* no React): it returns structured data; each client formats labels in its own locale.*- * `agent_task_update` is a LIVE-only `AgentEvent` (never persisted), forwarded to the mobile- * controller over the `maker:event` device-link channel. The mobile store decodes it via- * `applyAgentTaskUpdateEvent` into a per-session map; the render layer links each update to- * its originating `Task`/`collab:*` tool-call (or renders it standalone when orphaned).+ * The renderer/device-link `agent_task_update` transport remains live-only. The desktop host+ * consumes a main-only Subagent observation marker before forwarding the existing payload,+ * and separately projects that observation into Cindy's durable workspace. Mobile decodes+ * the live event via+ * `applyAgentTaskUpdateEvent`; the render layer links it to its originating tool-call.*/export type AgentTaskStatus = 'running' | 'completed' | 'failed' | 'stopped';@@ -174,11 +175,16 @@ export function deriveAgentTaskStatus(** MCP 工具一律带 `mcp__` 前缀,不会与裸 `subagent` 撞名。*/-export function isAgentTaskToolName(toolName: string): boolean {+export function isSubagentSpawnToolName(toolName: string): boolean {return toolName === 'Agent'|| toolName === 'Task'|| toolName === PI_SUBAGENT_TOOL_NAME- || toolName.startsWith('collab:');+ || toolName === 'collab:spawn'+ || toolName === 'collab:spawnAgent';+}++export function isAgentTaskToolName(toolName: string): boolean {+ return isSubagentSpawnToolName(toolName) || toolName.startsWith('collab:');}/** PI 子代理工具名 —— maker-core 的 pi 扩展注册端与本文件的卡片判据共用,不各写字面量。 */@@ -384,14 +390,22 @@ export function subagentSpawnReceiptName(*/export function subagentSpawnResultIndicatesRunning(toolName: string | undefined,- result: string | undefined,+ result: string | null | undefined,): boolean {- const trimmed = result?.trim() ?? '';+ const trimmed = typeof result === 'string'+ ? result.trim().replace(/\r\n/g, '\n')+ : '';// Claude's asynchronous Agent tool returns a textual launch receipt while the// child is still running. Treat it like the structured Codex V1 receipt so a// paired stale `running` update does not close the task prematurely.if ((toolName === 'Agent' || toolName === 'Task')- && trimmed === 'Async agent launched successfully.') {+ && (+ trimmed === 'Async agent launched successfully.'+ || (+ trimmed.startsWith('Async agent launched successfully.\nagentId: ')+ && trimmed.includes('\nThe agent is working in the background.')+ )+ )) {return true;}if (toolName !== 'collab:spawnAgent') return false;diff --git a/packages/maker-shared/src/index.ts b/packages/maker-shared/src/index.tsindex 51a186c056..4c3505c764 100644--- a/packages/maker-shared/src/index.ts+++ b/packages/maker-shared/src/index.ts@@ -41,6 +41,8 @@ export * from './sessionListCollapse.js';export * from './sessionOperation.js';export * from './sessionSelection.js';export * from './syntheticTrigger.js';+export * from './subagentObservation.js';+export * from './subagentWorkspace.js';export * from './systemCard.js';export * from './toolUseDescriptor.js';export * from './thinkingText.js';diff --git a/packages/maker-shared/src/subagentObservation.test.ts b/packages/maker-shared/src/subagentObservation.test.tsnew file mode 100644index 0000000000..9365a5eb44--- /dev/null+++ b/packages/maker-shared/src/subagentObservation.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from 'vitest';++import { normalizeSubagentObservation } from './subagentObservation.js';++describe('normalizeSubagentObservation', () => {+ it('normalizes one harness-neutral spawn identity', () => {+ expect(+ normalizeSubagentObservation({+ kind: 'spawn',+ logicalSubagentId: ' child-1 ',+ parentToolUseId: ' tool-1 ',+ identityAliases: ['card-1', 'card-1', 42],+ providerRunIds: ['thread-1', 'thread-1', null],+ }),+ ).toEqual({+ kind: 'spawn',+ logicalSubagentId: 'child-1',+ parentToolUseId: 'tool-1',+ identityAliases: ['card-1'],+ providerRunIds: ['thread-1'],+ });+ });++ it.each([+ undefined,+ {},+ { kind: 'control', logicalSubagentId: 'child-1' },+ { kind: 'spawn', logicalSubagentId: '' },+ { kind: 'progress', logicalSubagentId: 'x'.repeat(513) },+ ])('fails closed for an invalid marker', (value) => {+ expect(normalizeSubagentObservation(value)).toBeNull();+ });+});diff --git a/packages/maker-shared/src/subagentObservation.ts b/packages/maker-shared/src/subagentObservation.tsnew file mode 100644index 0000000000..88b0abe599--- /dev/null+++ b/packages/maker-shared/src/subagentObservation.ts@@ -0,0 +1,66 @@+/**+ * Harness-neutral lifecycle marker for Cindy's durable Subagent workspace.+ *+ * This marker is deliberately nested on the existing live `agent_task_update`+ * event. The live card may still represent provider control calls, background+ * shell tasks, or workflows; only updates carrying a valid marker are durable+ * Subagent observations.+ */++export type SubagentObservationKind = 'spawn' | 'progress' | 'terminal';++export interface SubagentObservation {+ /** Only spawn observations may create a durable run or add provider ids. */+ kind: SubagentObservationKind;+ /** Stable Cindy identity for one delegated unit of work. */+ logicalSubagentId: string;+ /** Parent task tool call that launched this delegated work, when known. */+ parentToolUseId?: string;+ /** Additional stable card/task aliases, never filesystem paths. */+ identityAliases?: string[];+ /** Opaque native child session/thread ids, supplied by spawn observations only. */+ providerRunIds?: string[];+}++const MAX_ID_LENGTH = 512;+const MAX_IDENTITY_ALIASES = 128;+const MAX_PROVIDER_RUN_IDS = 64;++function normalizedId(value: unknown): string | undefined {+ if (typeof value !== 'string') return undefined;+ const trimmed = value.trim();+ if (!trimmed || trimmed.length > MAX_ID_LENGTH) return undefined;+ return trimmed;+}++function normalizedIds(value: unknown, max: number): string[] | undefined {+ if (value === undefined) return undefined;+ if (!Array.isArray(value)) return undefined;+ const ids = new Set<string>();+ for (const raw of value) {+ const id = normalizedId(raw);+ if (!id) continue;+ ids.add(id);+ if (ids.size >= max) break;+ }+ return [...ids];+}++/** Validate an untrusted event marker. Invalid markers fail closed. */+export function normalizeSubagentObservation(value: unknown): SubagentObservation | null {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ const raw = value as Record<string, unknown>;+ if (raw.kind !== 'spawn' && raw.kind !== 'progress' && raw.kind !== 'terminal') return null;+ const logicalSubagentId = normalizedId(raw.logicalSubagentId);+ if (!logicalSubagentId) return null;+ const parentToolUseId = normalizedId(raw.parentToolUseId);+ const identityAliases = normalizedIds(raw.identityAliases, MAX_IDENTITY_ALIASES);+ const providerRunIds = normalizedIds(raw.providerRunIds, MAX_PROVIDER_RUN_IDS);+ return {+ kind: raw.kind,+ logicalSubagentId,+ ...(parentToolUseId ? { parentToolUseId } : {}),+ ...(identityAliases !== undefined ? { identityAliases } : {}),+ ...(providerRunIds !== undefined ? { providerRunIds } : {}),+ };+}diff --git a/packages/maker-shared/src/subagentWorkspace.ts b/packages/maker-shared/src/subagentWorkspace.tsnew file mode 100644index 0000000000..85b144333b--- /dev/null+++ b/packages/maker-shared/src/subagentWorkspace.ts@@ -0,0 +1,170 @@+/**+ * Cindy-owned Subagent workspace contract.+ *+ * A `SubagentRun` is the durable, user-visible record in the parent task. It is+ * deliberately separate from a harness-native run/thread/session handle: one+ * Codex spawn may fan out to several child threads, while PI and Claude expose+ * different native identities. Renderer code must use `id`; harness adapters+ * may add opaque `providerRunIds` without changing the product model.+ */++export type SubagentProvider = 'claude-code' | 'codex' | 'pi';++export type SubagentRunStatus = 'running' | 'completed' | 'failed' | 'stopped';++export type SubagentActivityKind =+ | 'started'+ | 'progress'+ | 'message'+ | 'question'+ | 'decision'+ | 'resumed'+ | 'steered'+ | 'completed'+ | 'failed'+ | 'stopped';++export interface SubagentActivityEntry {+ /** Monotonic within one Cindy run. */+ sequence: number;+ kind: SubagentActivityKind;+ status: SubagentRunStatus;+ summary?: string;+ lastToolName?: string;+ occurredAt: number;+}++/**+ * Capability truth is data, not a provider-name switch in the UI. PR1 exposes+ * durable viewing only; later harness integrations can turn on the same fields+ * without changing the sidebar or database shape.+ */+export interface SubagentCapabilities {+ viewActivity: boolean;+ viewReturnedResult: boolean;+ viewFullTranscript: boolean;+ resume: boolean;+ steer: boolean;+ stop: boolean;+ parentContext: 'unknown' | 'snapshot' | 'live';+}++export interface SubagentRunUsage {+ totalTokens?: number;+ toolUses?: number;+ durationMs?: number;+}++export interface SubagentRun {+ /** Cindy-owned stable id. */+ id: string;+ parentSessionId: string;+ provider: SubagentProvider;+ /** Stable logical card identity inside the parent task. */+ logicalAgentId: string;+ /** Link back to the parent task's spawning tool call. */+ parentToolUseId?: string;+ /** Stable task/tool aliases accepted by the common detail entrance. */+ identityAliases: string[];+ /** Opaque harness-native run/thread ids; never filesystem paths. */+ providerRunIds: string[];+ status: SubagentRunStatus;+ title?: string;+ description?: string;+ summary?: string;+ model?: string;+ reasoningEffort?: string;+ usage?: SubagentRunUsage;+ capabilities: SubagentCapabilities;+ startedAt: number;+ updatedAt: number;+ endedAt?: number;+}++export type SubagentTranscriptRole = 'parent' | 'subagent' | 'tool' | 'system';++/**+ * Harness-neutral transcript entry. PR1 leaves this capability disabled, but+ * the durable contract is fixed now so PI, Codex and Claude adapters can fill+ * the same detail view without replacing its data model.+ */+export interface SubagentTranscriptEntry {+ id: string;+ sequence: number;+ role: SubagentTranscriptRole;+ content: string;+ occurredAt: number;+ toolName?: string;+}++export interface SubagentRunDetail extends SubagentRun {+ activity: SubagentActivityEntry[];+ /** The result explicitly returned to the parent task, when available. */+ returnedResult?: string;+ returnedResultTruncated?: boolean;+}++/** Provider-scoped lookup for a Cindy run id or harness-native alias. */+export interface SubagentRunDetailRequest {+ sessionId: string;+ provider: SubagentProvider;+ runIdOrAlias: string;+}++/** Lazy transcript contract for long-lived child sessions. */+export interface SubagentTranscriptPageRequest {+ sessionId: string;+ provider: SubagentProvider;+ runIdOrAlias: string;+ /** Opaque provider/resolver cursor returned by the previous page. */+ cursor?: string;+ /** The host clamps this value to a safe range. */+ limit?: number;+}++export interface SubagentTranscriptPageResponse {+ supported: boolean;+ entries: SubagentTranscriptEntry[];+ nextCursor?: string;+}++export interface SubagentRunsListRequest {+ sessionId: string;+ /** Opaque cursor returned by the previous page. */+ cursor?: string;+ /** The host clamps this value to a safe range. */+ limit?: number;+}++export interface SubagentRunsListResponse {+ supported: boolean;+ runs: SubagentRun[];+ nextCursor?: string;+}++export interface SubagentRunDetailResponse {+ supported: boolean;+ run: SubagentRunDetail | null;+}++export interface SubagentRunsChangedPayload {+ sessionId: string;+ /** Null invalidates the whole session projection after a clear/rewind boundary. */+ runId: string | null;+ created: boolean;+ /** True only when this is the first visible Subagent record in the task. */+ firstForSession: boolean;+}++export const SUBAGENT_RUNS_CHANGED_CHANNEL = 'local-db:subagent-runs:changed';++export const SUBAGENT_PR1_CAPABILITIES: Readonly<SubagentCapabilities> =+ Object.freeze({+ viewActivity: true,+ viewReturnedResult: true,+ viewFullTranscript: false,+ resume: false,+ steer: false,+ stop: false,+ parentContext: 'unknown',+ });