Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(sharing): share tasks across accounts with unified desktop and mobile flows

DavidShenbca321223d8b
diff --git a/.gitignore b/.gitignore
index 5f67254f3c..f8163ea330 100644
--- a/.gitignore
+++ b/.gitignore
@@ -198,3 +198,6 @@ github-result-*.json
# 内置插件种子已废弃(改走 plugin-store 安装);历史克隆含私有插件与凭证,永不入仓。
apps/desktop/resources/builtin-ghosts/
+
+# 本地验收截图与设计稿等任务产物(只在本地保存,不入仓)。
+artifacts/
diff --git a/AGENTS.md b/AGENTS.md
index 3c9eb63a7c..0eb9afeb02 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -52,6 +52,8 @@
提的,提交者身份不构成例外。
- 新增或调整产品功能、判断能力应进入 Core / Skill / 插件、设计人机交互或多端体验
前,必须先读 `docs/product-rules/core-product-principles.md`。
+- 修改共享任务、跨账号访客邀请、共享上下文或共享成员权限前,必须先读
+ `docs/product-rules/shared-task-mode.md`;复用 device-link,同账号远控行为不变。
- 修改伙伴(Bot)的身份、Session 生命周期、模型 fallback、工作目录、Skill / MCP 装配、
委派协作或伙伴设置前,必须先读 `docs/product-rules/cindy-bots-runtime.md`。
- 新增或修改 `/review`、Reviewer 任务、成果快照、Finding 协议、复核入口、结果呈现或
diff --git a/apps/desktop/drizzle/0114_shared_task_events.sql b/apps/desktop/drizzle/0114_shared_task_events.sql
new file mode 100644
index 0000000000..3a907f3989
--- /dev/null
+++ b/apps/desktop/drizzle/0114_shared_task_events.sql
@@ -0,0 +1,14 @@
+CREATE TABLE `shared_task_events` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `shared_task_id` text NOT NULL,
+ `session_id` text NOT NULL,
+ `revision` integer NOT NULL,
+ `kind` text NOT NULL,
+ `terminal` integer NOT NULL,
+ `snapshot` text,
+ `recorded_at` integer NOT NULL,
+ FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `shared_task_events_revision_idx` ON `shared_task_events` (`shared_task_id`,`kind`,`revision`);--> statement-breakpoint
+CREATE INDEX `shared_task_events_session_idx` ON `shared_task_events` (`session_id`,`id`);
\ No newline at end of file
diff --git a/apps/desktop/drizzle/meta/0114_snapshot.json b/apps/desktop/drizzle/meta/0114_snapshot.json
new file mode 100644
index 0000000000..590683e224
--- /dev/null
+++ b/apps/desktop/drizzle/meta/0114_snapshot.json
@@ -0,0 +1,6066 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "c5d29ae9-c017-4e7f-ba01-9e305d7b4cb8",
+ "prevId": "454a5925-19b5-4cb0-a1ef-9d2e0d6858d5",
+ "tables": {
+ "account_usage_snapshots": {
+ "name": "account_usage_snapshots",
+ "columns": {
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "snapshot": {
+ "name": "snapshot",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "agent_input_queue_snapshots": {
+ "name": "agent_input_queue_snapshots",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "agent_input_queue_snapshots_session_id_sessions_id_fk": {
+ "name": "agent_input_queue_snapshots_session_id_sessions_id_fk",
+ "tableFrom": "agent_input_queue_snapshots",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_delegations": {
+ "name": "bot_delegations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "requesting_bot_id": {
+ "name": "requesting_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "target_bot_id": {
+ "name": "target_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "parent_session_id": {
+ "name": "parent_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "child_session_id": {
+ "name": "child_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "objective": {
+ "name": "objective",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_refs_json": {
+ "name": "context_refs_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "artifact_refs_json": {
+ "name": "artifact_refs_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "permission_snapshot_json": {
+ "name": "permission_snapshot_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "lineage_json": {
+ "name": "lineage_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "target_profile_version": {
+ "name": "target_profile_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "depth": {
+ "name": "depth",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "budget_tokens": {
+ "name": "budget_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tokens_used": {
+ "name": "tokens_used",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "result_summary": {
+ "name": "result_summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "output_artifacts_json": {
+ "name": "output_artifacts_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "pending_interaction_json": {
+ "name": "pending_interaction_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "run_sequence": {
+ "name": "run_sequence",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "accepted_at": {
+ "name": "accepted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "completion_delivered_at": {
+ "name": "completion_delivered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_delegations_requester_status": {
+ "name": "idx_bot_delegations_requester_status",
+ "columns": [
+ "requesting_bot_id",
+ "status"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_delegations_target_status": {
+ "name": "idx_bot_delegations_target_status",
+ "columns": [
+ "target_bot_id",
+ "status"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_delegations_parent_session": {
+ "name": "idx_bot_delegations_parent_session",
+ "columns": [
+ "parent_session_id"
+ ],
+ "isUnique": false
+ },
+ "uniq_bot_delegations_child_session": {
+ "name": "uniq_bot_delegations_child_session",
+ "columns": [
+ "child_session_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "bot_delegations_requesting_bot_id_bot_profiles_id_fk": {
+ "name": "bot_delegations_requesting_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_delegations",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "requesting_bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_delegations_target_bot_id_bot_profiles_id_fk": {
+ "name": "bot_delegations_target_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_delegations",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "target_bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_delegations_parent_session_id_sessions_id_fk": {
+ "name": "bot_delegations_parent_session_id_sessions_id_fk",
+ "tableFrom": "bot_delegations",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "parent_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "bot_delegations_child_session_id_sessions_id_fk": {
+ "name": "bot_delegations_child_session_id_sessions_id_fk",
+ "tableFrom": "bot_delegations",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "child_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_direct_message_threads": {
+ "name": "bot_direct_message_threads",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_a_id": {
+ "name": "bot_a_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_b_id": {
+ "name": "bot_b_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "close_reason": {
+ "name": "close_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "message_count": {
+ "name": "message_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "max_messages": {
+ "name": "max_messages",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "blocked_until": {
+ "name": "blocked_until",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "closed_at": {
+ "name": "closed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_bot_dm_threads_active_pair": {
+ "name": "uniq_bot_dm_threads_active_pair",
+ "columns": [
+ "bot_a_id",
+ "bot_b_id"
+ ],
+ "isUnique": true,
+ "where": "\"bot_direct_message_threads\".\"status\" = 'active'"
+ },
+ "idx_bot_dm_threads_pair_updated": {
+ "name": "idx_bot_dm_threads_pair_updated",
+ "columns": [
+ "bot_a_id",
+ "bot_b_id",
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_direct_messages": {
+ "name": "bot_direct_messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "thread_id": {
+ "name": "thread_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sequence": {
+ "name": "sequence",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sender_bot_id": {
+ "name": "sender_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "recipient_bot_id": {
+ "name": "recipient_bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sender_session_id": {
+ "name": "sender_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "recipient_session_id": {
+ "name": "recipient_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "delivery_status": {
+ "name": "delivery_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "sender_name": {
+ "name": "sender_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "recipient_name": {
+ "name": "recipient_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "bridge_session_id": {
+ "name": "bridge_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_bot_direct_messages_thread_sequence": {
+ "name": "uniq_bot_direct_messages_thread_sequence",
+ "columns": [
+ "thread_id",
+ "sequence"
+ ],
+ "isUnique": true
+ },
+ "idx_bot_direct_messages_thread_created": {
+ "name": "idx_bot_direct_messages_thread_created",
+ "columns": [
+ "thread_id",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_direct_messages_thread_id_bot_direct_message_threads_id_fk": {
+ "name": "bot_direct_messages_thread_id_bot_direct_message_threads_id_fk",
+ "tableFrom": "bot_direct_messages",
+ "tableTo": "bot_direct_message_threads",
+ "columnsFrom": [
+ "thread_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_direct_messages_sender_session_id_sessions_id_fk": {
+ "name": "bot_direct_messages_sender_session_id_sessions_id_fk",
+ "tableFrom": "bot_direct_messages",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "sender_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "bot_direct_messages_recipient_session_id_sessions_id_fk": {
+ "name": "bot_direct_messages_recipient_session_id_sessions_id_fk",
+ "tableFrom": "bot_direct_messages",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "recipient_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_lifecycle_events": {
+ "name": "bot_lifecycle_events",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "event_type": {
+ "name": "event_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload_json": {
+ "name": "payload_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_lifecycle_events_bot_created": {
+ "name": "idx_bot_lifecycle_events_bot_created",
+ "columns": [
+ "bot_id",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_lifecycle_events_session_created": {
+ "name": "idx_bot_lifecycle_events_session_created",
+ "columns": [
+ "session_id",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_lifecycle_events_bot_id_bot_profiles_id_fk": {
+ "name": "bot_lifecycle_events_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_lifecycle_events",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_lifecycle_events_session_id_sessions_id_fk": {
+ "name": "bot_lifecycle_events_session_id_sessions_id_fk",
+ "tableFrom": "bot_lifecycle_events",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_profile_versions": {
+ "name": "bot_profile_versions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "version": {
+ "name": "version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "identity_source": {
+ "name": "identity_source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "capabilities_json": {
+ "name": "capabilities_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_bot_profile_versions_bot_version": {
+ "name": "uniq_bot_profile_versions_bot_version",
+ "columns": [
+ "bot_id",
+ "version"
+ ],
+ "isUnique": true
+ },
+ "idx_bot_profile_versions_bot_created": {
+ "name": "idx_bot_profile_versions_bot_created",
+ "columns": [
+ "bot_id",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_profile_versions_bot_id_bot_profiles_id_fk": {
+ "name": "bot_profile_versions_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_profile_versions",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_profiles": {
+ "name": "bot_profiles",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "display_name": {
+ "name": "display_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "avatar": {
+ "name": "avatar",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'🤖'"
+ },
+ "avatar_color": {
+ "name": "avatar_color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'violet'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "hidden_at": {
+ "name": "hidden_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pinned_at": {
+ "name": "pinned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "attention_reason": {
+ "name": "attention_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "attention_at": {
+ "name": "attention_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "current_version": {
+ "name": "current_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "canonical_session_id": {
+ "name": "canonical_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_profiles_status_updated": {
+ "name": "idx_bot_profiles_status_updated",
+ "columns": [
+ "status",
+ "updated_at"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_profiles_canonical_session": {
+ "name": "idx_bot_profiles_canonical_session",
+ "columns": [
+ "canonical_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_profiles_canonical_session_id_sessions_id_fk": {
+ "name": "bot_profiles_canonical_session_id_sessions_id_fk",
+ "tableFrom": "bot_profiles",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "canonical_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_runtime_snapshots": {
+ "name": "bot_runtime_snapshots",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "profile_version": {
+ "name": "profile_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "memory_scope_key": {
+ "name": "memory_scope_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "configured_json": {
+ "name": "configured_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "resolved_json": {
+ "name": "resolved_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "prepared_at": {
+ "name": "prepared_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "applied_at": {
+ "name": "applied_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "failed_at": {
+ "name": "failed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "failure_json": {
+ "name": "failure_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_bot_runtime_snapshots_bot_prepared": {
+ "name": "idx_bot_runtime_snapshots_bot_prepared",
+ "columns": [
+ "bot_id",
+ "prepared_at"
+ ],
+ "isUnique": false
+ },
+ "idx_bot_runtime_snapshots_session_prepared": {
+ "name": "idx_bot_runtime_snapshots_session_prepared",
+ "columns": [
+ "session_id",
+ "prepared_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_runtime_snapshots_bot_id_bot_profiles_id_fk": {
+ "name": "bot_runtime_snapshots_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_runtime_snapshots",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_runtime_snapshots_session_id_sessions_id_fk": {
+ "name": "bot_runtime_snapshots_session_id_sessions_id_fk",
+ "tableFrom": "bot_runtime_snapshots",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "bot_session_links": {
+ "name": "bot_session_links",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_id": {
+ "name": "bot_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "profile_version": {
+ "name": "profile_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "route_key": {
+ "name": "route_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_bot_session_links_session": {
+ "name": "uniq_bot_session_links_session",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true
+ },
+ "uniq_bot_session_links_canonical_per_bot": {
+ "name": "uniq_bot_session_links_canonical_per_bot",
+ "columns": [
+ "bot_id"
+ ],
+ "isUnique": true,
+ "where": "\"bot_session_links\".\"role\" = 'canonical'"
+ },
+ "idx_bot_session_links_bot_role": {
+ "name": "idx_bot_session_links_bot_role",
+ "columns": [
+ "bot_id",
+ "role"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "bot_session_links_bot_id_bot_profiles_id_fk": {
+ "name": "bot_session_links_bot_id_bot_profiles_id_fk",
+ "tableFrom": "bot_session_links",
+ "tableTo": "bot_profiles",
+ "columnsFrom": [
+ "bot_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "bot_session_links_session_id_sessions_id_fk": {
+ "name": "bot_session_links_session_id_sessions_id_fk",
+ "tableFrom": "bot_session_links",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "custom_mcp_servers": {
+ "name": "custom_mcp_servers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "transport": {
+ "name": "transport",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "headers": {
+ "name": "headers",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_custom_mcp_servers_sort_order": {
+ "name": "idx_custom_mcp_servers_sort_order",
+ "columns": [
+ "sort_order"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "custom_providers": {
+ "name": "custom_providers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "runtimes": {
+ "name": "runtimes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "auth": {
+ "name": "auth",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_custom_providers_sort_order": {
+ "name": "idx_custom_providers_sort_order",
+ "columns": [
+ "sort_order"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "daily_model_usage": {
+ "name": "daily_model_usage",
+ "columns": {
+ "day": {
+ "name": "day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_amount": {
+ "name": "cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_currency": {
+ "name": "cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'USD'"
+ },
+ "cost_is_approximate": {
+ "name": "cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "input_tokens": {
+ "name": "input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "output_tokens": {
+ "name": "output_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cache_read_tokens": {
+ "name": "cache_read_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cache_create_tokens": {
+ "name": "cache_create_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "daily_model_usage_day_agent_kind_model_cost_currency_pk": {
+ "columns": [
+ "day",
+ "agent_kind",
+ "model",
+ "cost_currency"
+ ],
+ "name": "daily_model_usage_day_agent_kind_model_cost_currency_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "daily_spend": {
+ "name": "daily_spend",
+ "columns": {
+ "day": {
+ "name": "day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_amount": {
+ "name": "cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_currency": {
+ "name": "cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'USD'"
+ },
+ "cost_is_approximate": {
+ "name": "cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "daily_spend_day_cost_currency_pk": {
+ "columns": [
+ "day",
+ "cost_currency"
+ ],
+ "name": "daily_spend_day_cost_currency_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "device_link_ownership": {
+ "name": "device_link_ownership",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_pid": {
+ "name": "owner_pid",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_label": {
+ "name": "owner_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "heartbeat_at": {
+ "name": "heartbeat_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "embedding_jobs": {
+ "name": "embedding_jobs",
+ "columns": {
+ "rowid": {
+ "name": "rowid",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source_id": {
+ "name": "source_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chunk_index": {
+ "name": "chunk_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "vec_table": {
+ "name": "vec_table",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scheduled_at": {
+ "name": "scheduled_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "locked_at": {
+ "name": "locked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_embedding_jobs_natural": {
+ "name": "uniq_embedding_jobs_natural",
+ "columns": [
+ "source",
+ "source_id",
+ "chunk_index",
+ "model_id"
+ ],
+ "isUnique": true
+ },
+ "idx_embedding_jobs_status_scheduled": {
+ "name": "idx_embedding_jobs_status_scheduled",
+ "columns": [
+ "status",
+ "scheduled_at"
+ ],
+ "isUnique": false
+ },
+ "idx_embedding_jobs_source_id": {
+ "name": "idx_embedding_jobs_source_id",
+ "columns": [
+ "source",
+ "source_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "embedding_meta": {
+ "name": "embedding_meta",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "ghost_cards": {
+ "name": "ghost_cards",
+ "columns": {
+ "call_id": {
+ "name": "call_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ghost_id": {
+ "name": "ghost_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "html": {
+ "name": "html",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "height": {
+ "name": "height",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "v": {
+ "name": "v",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "ghost_cards_updated_at_idx": {
+ "name": "ghost_cards_updated_at_idx",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "hook_group_context_cursors": {
+ "name": "hook_group_context_cursors",
+ "columns": {
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cursor_key": {
+ "name": "cursor_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cursor_id": {
+ "name": "cursor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "hook_group_context_cursors_updated_at_idx": {
+ "name": "hook_group_context_cursors_updated_at_idx",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "hook_group_context_cursors_provider_cursor_key_pk": {
+ "columns": [
+ "provider",
+ "cursor_key"
+ ],
+ "name": "hook_group_context_cursors_provider_cursor_key_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "hook_group_message_stats": {
+ "name": "hook_group_message_stats",
+ "columns": {
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "row_count": {
+ "name": "row_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text_bytes": {
+ "name": "text_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "hook_group_messages": {
+ "name": "hook_group_messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "thread_id": {
+ "name": "thread_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_name": {
+ "name": "chat_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "author": {
+ "name": "author",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_bot": {
+ "name": "is_bot",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "file_names": {
+ "name": "file_names",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "hook_group_messages_msg_idx": {
+ "name": "hook_group_messages_msg_idx",
+ "columns": [
+ "provider",
+ "chat_id",
+ "thread_id",
+ "message_id"
+ ],
+ "isUnique": true
+ },
+ "hook_group_messages_window_idx": {
+ "name": "hook_group_messages_window_idx",
+ "columns": [
+ "provider",
+ "chat_id",
+ "thread_id",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "im_bindings": {
+ "name": "im_bindings",
+ "columns": {
+ "channel": {
+ "name": "channel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_context_id": {
+ "name": "bot_context_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scope_key": {
+ "name": "scope_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "target_session_id": {
+ "name": "target_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attached_at": {
+ "name": "attached_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attached_via_card_message_id": {
+ "name": "attached_via_card_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_im_bindings_target": {
+ "name": "idx_im_bindings_target",
+ "columns": [
+ "target_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "im_bindings_target_session_id_sessions_id_fk": {
+ "name": "im_bindings_target_session_id_sessions_id_fk",
+ "tableFrom": "im_bindings",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "target_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "im_bindings_channel_bot_context_id_user_id_scope_key_pk": {
+ "columns": [
+ "channel",
+ "bot_context_id",
+ "user_id",
+ "scope_key"
+ ],
+ "name": "im_bindings_channel_bot_context_id_user_id_scope_key_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "im_notification_origins": {
+ "name": "im_notification_origins",
+ "columns": {
+ "channel": {
+ "name": "channel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_context_id": {
+ "name": "bot_context_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "im_notification_origins_channel_bot_context_id_user_id_message_id_pk": {
+ "columns": [
+ "channel",
+ "bot_context_id",
+ "user_id",
+ "message_id"
+ ],
+ "name": "im_notification_origins_channel_bot_context_id_user_id_message_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "media_blobs": {
+ "name": "media_blobs",
+ "columns": {
+ "hash": {
+ "name": "hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ext": {
+ "name": "ext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mime_type": {
+ "name": "mime_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bytes": {
+ "name": "bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_cache": {
+ "name": "is_cache",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_access_at": {
+ "name": "last_access_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "media_invocations": {
+ "name": "media_invocations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner": {
+ "name": "owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "capability": {
+ "name": "capability",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "guide_revision": {
+ "name": "guide_revision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "guide_json": {
+ "name": "guide_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "response_json": {
+ "name": "response_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "media_invocations_owner_created_at_idx": {
+ "name": "media_invocations_owner_created_at_idx",
+ "columns": [
+ "owner",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "media_invocations_owner_state_idx": {
+ "name": "media_invocations_owner_state_idx",
+ "columns": [
+ "owner",
+ "state"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "media_refs": {
+ "name": "media_refs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "hash": {
+ "name": "hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ref_kind": {
+ "name": "ref_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ref_id": {
+ "name": "ref_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "origin_session_id": {
+ "name": "origin_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "origin_kind": {
+ "name": "origin_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "origin_id": {
+ "name": "origin_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "media_refs_hash_idx": {
+ "name": "media_refs_hash_idx",
+ "columns": [
+ "hash"
+ ],
+ "isUnique": false
+ },
+ "media_refs_ref_idx": {
+ "name": "media_refs_ref_idx",
+ "columns": [
+ "ref_kind",
+ "ref_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "media_refs_hash_media_blobs_hash_fk": {
+ "name": "media_refs_hash_media_blobs_hash_fk",
+ "tableFrom": "media_refs",
+ "tableTo": "media_blobs",
+ "columnsFrom": [
+ "hash"
+ ],
+ "columnsTo": [
+ "hash"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "messages": {
+ "name": "messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_use_id": {
+ "name": "tool_use_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_meta": {
+ "name": "agent_meta",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "rewind_at": {
+ "name": "rewind_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_messages_session_client": {
+ "name": "uniq_messages_session_client",
+ "columns": [
+ "session_id",
+ "client_id"
+ ],
+ "isUnique": true
+ },
+ "idx_messages_session_created": {
+ "name": "idx_messages_session_created",
+ "columns": [
+ "session_id",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "idx_messages_created_at": {
+ "name": "idx_messages_created_at",
+ "columns": [
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_messages_rewind_at": {
+ "name": "idx_messages_rewind_at",
+ "columns": [
+ "rewind_at"
+ ],
+ "isUnique": false
+ },
+ "idx_messages_active_error_tail": {
+ "name": "idx_messages_active_error_tail",
+ "columns": [
+ "session_id",
+ "created_at"
+ ],
+ "isUnique": false,
+ "where": "\"messages\".\"role\" = 'error' AND \"messages\".\"rewind_at\" IS NULL"
+ }
+ },
+ "foreignKeys": {
+ "messages_session_id_sessions_id_fk": {
+ "name": "messages_session_id_sessions_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "messages_fts_rows": {
+ "name": "messages_fts_rows",
+ "columns": {
+ "fts_rowid": {
+ "name": "fts_rowid",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "messages_fts_rows_message_id_idx": {
+ "name": "messages_fts_rows_message_id_idx",
+ "columns": [
+ "message_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "migration_history": {
+ "name": "migration_history",
+ "columns": {
+ "seq": {
+ "name": "seq",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "file_name": {
+ "name": "file_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content_hash": {
+ "name": "content_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "applied_at": {
+ "name": "applied_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "migration_meta": {
+ "name": "migration_meta",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_teams": {
+ "name": "orca_teams",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "lead_session_id": {
+ "name": "lead_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_active_team_per_lead": {
+ "name": "uniq_active_team_per_lead",
+ "columns": [
+ "lead_session_id"
+ ],
+ "isUnique": true,
+ "where": "\"orca_teams\".\"status\" = 'active'"
+ },
+ "idx_orca_teams_status": {
+ "name": "idx_orca_teams_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_teams_lead_session_id_sessions_id_fk": {
+ "name": "orca_teams_lead_session_id_sessions_id_fk",
+ "tableFrom": "orca_teams",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "lead_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_worker_creation_reservations": {
+ "name": "orca_worker_creation_reservations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_orca_worker_creation_reservations_team_label": {
+ "name": "uniq_orca_worker_creation_reservations_team_label",
+ "columns": [
+ "team_id",
+ "lower(\"label\")"
+ ],
+ "isUnique": true
+ },
+ "idx_orca_worker_creation_reservations_expires_at": {
+ "name": "idx_orca_worker_creation_reservations_expires_at",
+ "columns": [
+ "expires_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_worker_creation_reservations_team_id_orca_teams_id_fk": {
+ "name": "orca_worker_creation_reservations_team_id_orca_teams_id_fk",
+ "tableFrom": "orca_worker_creation_reservations",
+ "tableTo": "orca_teams",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_workers": {
+ "name": "orca_workers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'idle'"
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "worktree_branch": {
+ "name": "worktree_branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'developer'"
+ },
+ "focused": {
+ "name": "focused",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "idle_since": {
+ "name": "idle_since",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_orca_workers_session_id": {
+ "name": "uniq_orca_workers_session_id",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true
+ },
+ "uniq_orca_workers_team_label": {
+ "name": "uniq_orca_workers_team_label",
+ "columns": [
+ "team_id",
+ "lower(\"label\")"
+ ],
+ "isUnique": true
+ },
+ "uniq_orca_workers_focused_per_team": {
+ "name": "uniq_orca_workers_focused_per_team",
+ "columns": [
+ "team_id"
+ ],
+ "isUnique": true,
+ "where": "\"orca_workers\".\"focused\" = true"
+ },
+ "idx_orca_workers_team_id": {
+ "name": "idx_orca_workers_team_id",
+ "columns": [
+ "team_id"
+ ],
+ "isUnique": false
+ },
+ "idx_orca_workers_status": {
+ "name": "idx_orca_workers_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_workers_team_id_orca_teams_id_fk": {
+ "name": "orca_workers_team_id_orca_teams_id_fk",
+ "tableFrom": "orca_workers",
+ "tableTo": "orca_teams",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "orca_workers_session_id_sessions_id_fk": {
+ "name": "orca_workers_session_id_sessions_id_fk",
+ "tableFrom": "orca_workers",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_aliases": {
+ "name": "project_aliases",
+ "columns": {
+ "project_key": {
+ "name": "project_key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "alias": {
+ "name": "alias",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_project_aliases_updated_at": {
+ "name": "idx_project_aliases_updated_at",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_automation_consents": {
+ "name": "project_automation_consents",
+ "columns": {
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "consented_at": {
+ "name": "consented_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "config_hash": {
+ "name": "config_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "recent_workdirs": {
+ "name": "recent_workdirs",
+ "columns": {
+ "path": {
+ "name": "path",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_recent_workdirs_last_used_at": {
+ "name": "idx_recent_workdirs_last_used_at",
+ "columns": [
+ "last_used_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "right_sidebar_tabs": {
+ "name": "right_sidebar_tabs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "right_sidebar_tabs_session_idx": {
+ "name": "right_sidebar_tabs_session_idx",
+ "columns": [
+ "session_id",
+ "position"
+ ],
+ "isUnique": false
+ },
+ "right_sidebar_tabs_subagents_singleton_idx": {
+ "name": "right_sidebar_tabs_subagents_singleton_idx",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true,
+ "where": "\"right_sidebar_tabs\".\"kind\" = 'subagents'"
+ },
+ "right_sidebar_tabs_bot_artifacts_singleton_idx": {
+ "name": "right_sidebar_tabs_bot_artifacts_singleton_idx",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true,
+ "where": "\"right_sidebar_tabs\".\"kind\" = 'bot-artifacts'"
+ }
+ },
+ "foreignKeys": {
+ "right_sidebar_tabs_session_id_sessions_id_fk": {
+ "name": "right_sidebar_tabs_session_id_sessions_id_fk",
+ "tableFrom": "right_sidebar_tabs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "schedule_runs": {
+ "name": "schedule_runs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "schedule_id": {
+ "name": "schedule_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fired_at": {
+ "name": "fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "error_msg": {
+ "name": "error_msg",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "estimated_value_usd": {
+ "name": "estimated_value_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_amount": {
+ "name": "cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "estimated_value_amount": {
+ "name": "estimated_value_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_currency": {
+ "name": "cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_is_approximate": {
+ "name": "cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "cost_attribution": {
+ "name": "cost_attribution",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'legacy'"
+ },
+ "result_text": {
+ "name": "result_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pre_run_hook_result": {
+ "name": "pre_run_hook_result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "read_at": {
+ "name": "read_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "heartbeat_at": {
+ "name": "heartbeat_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedule_runs_schedule": {
+ "name": "idx_schedule_runs_schedule",
+ "columns": [
+ "schedule_id",
+ "fired_at"
+ ],
+ "isUnique": false
+ },
+ "idx_schedule_runs_running_schedule": {
+ "name": "idx_schedule_runs_running_schedule",
+ "columns": [
+ "schedule_id"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"status\" = 'running'"
+ },
+ "idx_schedule_runs_running_heartbeat": {
+ "name": "idx_schedule_runs_running_heartbeat",
+ "columns": [
+ "heartbeat_at"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"status\" = 'running' AND \"schedule_runs\".\"heartbeat_at\" IS NOT NULL"
+ },
+ "idx_schedule_runs_running_legacy": {
+ "name": "idx_schedule_runs_running_legacy",
+ "columns": [
+ "fired_at"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"status\" = 'running' AND \"schedule_runs\".\"heartbeat_at\" IS NULL"
+ },
+ "idx_schedule_runs_unread_terminal": {
+ "name": "idx_schedule_runs_unread_terminal",
+ "columns": [
+ "schedule_id",
+ "status",
+ "fired_at"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"read_at\" IS NULL AND \"schedule_runs\".\"status\" IN ('success', 'failed', 'aborted', 'interrupted')"
+ },
+ "idx_schedule_runs_session_latest": {
+ "name": "idx_schedule_runs_session_latest",
+ "columns": [
+ "session_id",
+ "fired_at",
+ "id"
+ ],
+ "isUnique": false,
+ "where": "\"schedule_runs\".\"session_id\" IS NOT NULL"
+ }
+ },
+ "foreignKeys": {
+ "schedule_runs_schedule_id_schedules_id_fk": {
+ "name": "schedule_runs_schedule_id_schedules_id_fk",
+ "tableFrom": "schedule_runs",
+ "tableTo": "schedules",
+ "columnsFrom": [
+ "schedule_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "schedule_runs_session_id_sessions_id_fk": {
+ "name": "schedule_runs_session_id_sessions_id_fk",
+ "tableFrom": "schedule_runs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "schedule_session_latest_runs": {
+ "name": "schedule_session_latest_runs",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "fired_at": {
+ "name": "fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedule_session_latest_runs_run": {
+ "name": "idx_schedule_session_latest_runs_run",
+ "columns": [
+ "run_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "schedule_session_latest_runs_session_id_sessions_id_fk": {
+ "name": "schedule_session_latest_runs_session_id_sessions_id_fk",
+ "tableFrom": "schedule_session_latest_runs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "schedule_session_latest_runs_run_id_schedule_runs_id_fk": {
+ "name": "schedule_session_latest_runs_run_id_schedule_runs_id_fk",
+ "tableFrom": "schedule_session_latest_runs",
+ "tableTo": "schedule_runs",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "schedules": {
+ "name": "schedules",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "job_type": {
+ "name": "job_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'prompt'"
+ },
+ "job_config": {
+ "name": "job_config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "execution_mode": {
+ "name": "execution_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'agent'"
+ },
+ "script_config": {
+ "name": "script_config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'user'"
+ },
+ "project_config_id": {
+ "name": "project_config_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "legacy_session_fallback": {
+ "name": "legacy_session_fallback",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'cron'"
+ },
+ "cron_expr": {
+ "name": "cron_expr",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "recurring": {
+ "name": "recurring",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "manual": {
+ "name": "manual",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "interval_ms": {
+ "name": "interval_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_agent_kind": {
+ "name": "model_agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "effort": {
+ "name": "effort",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fast_mode": {
+ "name": "fast_mode",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_kind": {
+ "name": "workspace_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'project'"
+ },
+ "use_worktree": {
+ "name": "use_worktree",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "target_session_id": {
+ "name": "target_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "persistent_session": {
+ "name": "persistent_session",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "silent_when_idle": {
+ "name": "silent_when_idle",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "pre_run_hook_command": {
+ "name": "pre_run_hook_command",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pre_run_hook_timeout_ms": {
+ "name": "pre_run_hook_timeout_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "skip_log_session_id": {
+ "name": "skip_log_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "notify_desktop": {
+ "name": "notify_desktop",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "notify_feishu": {
+ "name": "notify_feishu",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "notify_wecom_group": {
+ "name": "notify_wecom_group",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_fired_at": {
+ "name": "last_fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_finished_at": {
+ "name": "last_finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "next_fire_at": {
+ "name": "next_fire_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expire_at": {
+ "name": "expire_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedules_active_next": {
+ "name": "idx_schedules_active_next",
+ "columns": [
+ "status",
+ "next_fire_at"
+ ],
+ "isUnique": false
+ },
+ "idx_schedules_target_session": {
+ "name": "idx_schedules_target_session",
+ "columns": [
+ "target_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "schedules_target_session_id_sessions_id_fk": {
+ "name": "schedules_target_session_id_sessions_id_fk",
+ "tableFrom": "schedules",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "target_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "schedules_skip_log_session_id_sessions_id_fk": {
+ "name": "schedules_skip_log_session_id_sessions_id_fk",
+ "tableFrom": "schedules",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "skip_log_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_goals": {
+ "name": "session_goals",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "objective": {
+ "name": "objective",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "budget_tokens": {
+ "name": "budget_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "max_turns": {
+ "name": "max_turns",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "no_progress_limit": {
+ "name": "no_progress_limit",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "turns_used": {
+ "name": "turns_used",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "tokens_used": {
+ "name": "tokens_used",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "no_progress_streak": {
+ "name": "no_progress_streak",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "usage_reset_at": {
+ "name": "usage_reset_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_reason": {
+ "name": "last_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_session_goals_status": {
+ "name": "idx_session_goals_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_goals_session_id_sessions_id_fk": {
+ "name": "session_goals_session_id_sessions_id_fk",
+ "tableFrom": "session_goals",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_pr_refs": {
+ "name": "session_pr_refs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner": {
+ "name": "owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "repo": {
+ "name": "repo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "first_seen_at": {
+ "name": "first_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_session_pr_refs": {
+ "name": "uniq_session_pr_refs",
+ "columns": [
+ "session_id",
+ "owner",
+ "repo",
+ "pr_number"
+ ],
+ "isUnique": true
+ },
+ "idx_session_pr_refs_session_last_seen": {
+ "name": "idx_session_pr_refs_session_last_seen",
+ "columns": [
+ "session_id",
+ "last_seen_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_pr_refs_session_id_sessions_id_fk": {
+ "name": "session_pr_refs_session_id_sessions_id_fk",
+ "tableFrom": "session_pr_refs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_task_tags": {
+ "name": "session_task_tags",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tag_id": {
+ "name": "tag_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "session_task_tags_tag_idx": {
+ "name": "session_task_tags_tag_idx",
+ "columns": [
+ "tag_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_task_tags_session_id_sessions_id_fk": {
+ "name": "session_task_tags_session_id_sessions_id_fk",
+ "tableFrom": "session_task_tags",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "session_task_tags_tag_id_task_tags_id_fk": {
+ "name": "session_task_tags_tag_id_task_tags_id_fk",
+ "tableFrom": "session_task_tags",
+ "tableTo": "task_tags",
+ "columnsFrom": [
+ "tag_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "session_task_tags_session_id_tag_id_pk": {
+ "columns": [
+ "session_id",
+ "tag_id"
+ ],
+ "name": "session_task_tags_session_id_tag_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'New Maker'"
+ },
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_kind": {
+ "name": "workspace_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'project'"
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'claude-sonnet-4-6'"
+ },
+ "effort": {
+ "name": "effort",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'high'"
+ },
+ "permission_mode": {
+ "name": "permission_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'ask'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "total_token_usage": {
+ "name": "total_token_usage",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_usd": {
+ "name": "total_cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_amount": {
+ "name": "total_cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_currency": {
+ "name": "total_cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "total_cost_is_approximate": {
+ "name": "total_cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "context_tokens": {
+ "name": "context_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "context_window": {
+ "name": "context_window",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "context_window_runtime": {
+ "name": "context_window_runtime",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fast_mode": {
+ "name": "fast_mode",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "plan_mode_enabled": {
+ "name": "plan_mode_enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "cleared_at": {
+ "name": "cleared_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pinned_at": {
+ "name": "pinned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_send_at": {
+ "name": "user_send_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'cc'"
+ },
+ "orca_role": {
+ "name": "orca_role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "parent_session_id": {
+ "name": "parent_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "forked_at_message_id": {
+ "name": "forked_at_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "worktree_path": {
+ "name": "worktree_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'desktop'"
+ },
+ "feishu_open_id": {
+ "name": "feishu_open_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "feishu_bot_app_id": {
+ "name": "feishu_bot_app_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "im_bot_context_id": {
+ "name": "im_bot_context_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "im_user_id": {
+ "name": "im_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "used_project_context": {
+ "name": "used_project_context",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "codex_history_has_product_prompt": {
+ "name": "codex_history_has_product_prompt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "codex_plan_json": {
+ "name": "codex_plan_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "extra_dirs": {
+ "name": "extra_dirs",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "writable_dirs": {
+ "name": "writable_dirs",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "remote_host_id": {
+ "name": "remote_host_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "active_turn_started_at": {
+ "name": "active_turn_started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "active_turn_pid": {
+ "name": "active_turn_pid",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_turn_ended_at": {
+ "name": "last_turn_ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "list_preview": {
+ "name": "list_preview",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "list_preview_role": {
+ "name": "list_preview_role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "list_message_count": {
+ "name": "list_message_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_sessions_updated_at": {
+ "name": "idx_sessions_updated_at",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_user_send_at": {
+ "name": "idx_sessions_user_send_at",
+ "columns": [
+ "user_send_at"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_sdk_session_id": {
+ "name": "idx_sessions_sdk_session_id",
+ "columns": [
+ "sdk_session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_workdir_created": {
+ "name": "idx_sessions_workdir_created",
+ "columns": [
+ "working_dir",
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_created_at": {
+ "name": "idx_sessions_created_at",
+ "columns": [
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_workspace_kind": {
+ "name": "idx_sessions_workspace_kind",
+ "columns": [
+ "workspace_kind"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_parent_session_id": {
+ "name": "idx_sessions_parent_session_id",
+ "columns": [
+ "parent_session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_orca_role": {
+ "name": "idx_sessions_orca_role",
+ "columns": [
+ "orca_role"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_worktree_path": {
+ "name": "idx_sessions_worktree_path",
+ "columns": [
+ "worktree_path"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_feishu_lookup": {
+ "name": "idx_sessions_feishu_lookup",
+ "columns": [
+ "source",
+ "feishu_bot_app_id",
+ "feishu_open_id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_im_lookup": {
+ "name": "idx_sessions_im_lookup",
+ "columns": [
+ "source",
+ "im_bot_context_id",
+ "im_user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "sessions_parent_session_id_sessions_id_fk": {
+ "name": "sessions_parent_session_id_sessions_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "parent_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "shared_task_events": {
+ "name": "shared_task_events",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "shared_task_id": {
+ "name": "shared_task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "revision": {
+ "name": "revision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "terminal": {
+ "name": "terminal",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "snapshot": {
+ "name": "snapshot",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "recorded_at": {
+ "name": "recorded_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "shared_task_events_revision_idx": {
+ "name": "shared_task_events_revision_idx",
+ "columns": [
+ "shared_task_id",
+ "kind",
+ "revision"
+ ],
+ "isUnique": true
+ },
+ "shared_task_events_session_idx": {
+ "name": "shared_task_events_session_idx",
+ "columns": [
+ "session_id",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "shared_task_events_session_id_sessions_id_fk": {
+ "name": "shared_task_events_session_id_sessions_id_fk",
+ "tableFrom": "shared_task_events",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "skill_usage_exposures": {
+ "name": "skill_usage_exposures",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "analyzer_version": {
+ "name": "analyzer_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'6'"
+ },
+ "raw_file_path": {
+ "name": "raw_file_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "raw_line_no": {
+ "name": "raw_line_no",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "skill_name": {
+ "name": "skill_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "skill_path": {
+ "name": "skill_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "skill_document_hash": {
+ "name": "skill_document_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "exposure_content_hash": {
+ "name": "exposure_content_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "document_hash_source": {
+ "name": "document_hash_source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_use_id": {
+ "name": "tool_use_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "seen_at": {
+ "name": "seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_call_count": {
+ "name": "tool_call_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "repeated_tool_call_count": {
+ "name": "repeated_tool_call_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "tool_error_count": {
+ "name": "tool_error_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "command_call_count": {
+ "name": "command_call_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "command_failure_count": {
+ "name": "command_failure_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ }
+ },
+ "indexes": {
+ "idx_skill_usage_exposures_skill_document_version": {
+ "name": "idx_skill_usage_exposures_skill_document_version",
+ "columns": [
+ "analyzer_version",
+ "skill_name",
+ "skill_document_hash"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_skill_recent": {
+ "name": "idx_skill_usage_exposures_skill_recent",
+ "columns": [
+ "skill_name",
+ "analyzer_version",
+ "seen_at"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_skill_recent_any_version": {
+ "name": "idx_skill_usage_exposures_skill_recent_any_version",
+ "columns": [
+ "skill_name",
+ "seen_at"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_analyzer_recent_source": {
+ "name": "idx_skill_usage_exposures_analyzer_recent_source",
+ "columns": [
+ "analyzer_version",
+ "seen_at",
+ "raw_file_path"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_session": {
+ "name": "idx_skill_usage_exposures_session",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_raw_file": {
+ "name": "idx_skill_usage_exposures_raw_file",
+ "columns": [
+ "raw_file_path"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "skill_usage_exposures_raw_file_path_skill_usage_sources_raw_file_path_fk": {
+ "name": "skill_usage_exposures_raw_file_path_skill_usage_sources_raw_file_path_fk",
+ "tableFrom": "skill_usage_exposures",
+ "tableTo": "skill_usage_sources",
+ "columnsFrom": [
+ "raw_file_path"
+ ],
+ "columnsTo": [
+ "raw_file_path"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "skill_usage_sources": {
+ "name": "skill_usage_sources",
+ "columns": {
+ "raw_file_path": {
+ "name": "raw_file_path",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "analyzer_version": {
+ "name": "analyzer_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'6'"
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mtime_ms": {
+ "name": "mtime_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "size_bytes": {
+ "name": "size_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "last_scanned_at": {
+ "name": "last_scanned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'ok'"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_skill_usage_sources_session": {
+ "name": "idx_skill_usage_sources_session",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_sources_sdk_session": {
+ "name": "idx_skill_usage_sources_sdk_session",
+ "columns": [
+ "sdk_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subagent_run_aliases": {
+ "name": "subagent_run_aliases",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "alias": {
+ "name": "alias",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "subagent_run_aliases_lookup_idx": {
+ "name": "subagent_run_aliases_lookup_idx",
+ "columns": [
+ "session_id",
+ "provider",
+ "alias",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "subagent_run_aliases_session_id_sessions_id_fk": {
+ "name": "subagent_run_aliases_session_id_sessions_id_fk",
+ "tableFrom": "subagent_run_aliases",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "subagent_run_aliases_run_id_subagent_runs_id_fk": {
+ "name": "subagent_run_aliases_run_id_subagent_runs_id_fk",
+ "tableFrom": "subagent_run_aliases",
+ "tableTo": "subagent_runs",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "subagent_run_aliases_run_id_alias_pk": {
+ "columns": [
+ "run_id",
+ "alias"
+ ],
+ "name": "subagent_run_aliases_run_id_alias_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subagent_runs": {
+ "name": "subagent_runs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "logical_agent_id": {
+ "name": "logical_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "parent_tool_use_id": {
+ "name": "parent_tool_use_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "aliases": {
+ "name": "aliases",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "provider_run_ids": {
+ "name": "provider_run_ids",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'running'"
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "returned_result": {
+ "name": "returned_result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "returned_result_empty": {
+ "name": "returned_result_empty",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "returned_result_truncated": {
+ "name": "returned_result_truncated",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "reasoning_effort": {
+ "name": "reasoning_effort",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "total_tokens": {
+ "name": "total_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tool_uses": {
+ "name": "tool_uses",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "duration_ms": {
+ "name": "duration_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "capabilities": {
+ "name": "capabilities",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "activity": {
+ "name": "activity",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "rewind_at": {
+ "name": "rewind_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "subagent_runs_logical_idx": {
+ "name": "subagent_runs_logical_idx",
+ "columns": [
+ "session_id",
+ "provider",
+ "logical_agent_id"
+ ],
+ "isUnique": false
+ },
+ "subagent_runs_session_idx": {
+ "name": "subagent_runs_session_idx",
+ "columns": [
+ "session_id",
+ "rewind_at",
+ "deleted_at",
+ "started_at"
+ ],
+ "isUnique": false
+ },
+ "subagent_runs_parent_tool_use_idx": {
+ "name": "subagent_runs_parent_tool_use_idx",
+ "columns": [
+ "session_id",
+ "parent_tool_use_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "subagent_runs_session_id_sessions_id_fk": {
+ "name": "subagent_runs_session_id_sessions_id_fk",
+ "tableFrom": "subagent_runs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "task_tags": {
+ "name": "task_tags",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name_customized": {
+ "name": "name_customized",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "favorite_order": {
+ "name": "favorite_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "revision": {
+ "name": "revision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ }
+ },
+ "indexes": {
+ "task_tags_name_idx": {
+ "name": "task_tags_name_idx",
+ "columns": [
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "vec_table_meta": {
+ "name": "vec_table_meta",
+ "columns": {
+ "vec_table": {
+ "name": "vec_table",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "dim": {
+ "name": "dim",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "registered_at": {
+ "name": "registered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "notes": {
+ "name": "notes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_file_attachments": {
+ "name": "wechat_file_attachments",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "abs_path": {
+ "name": "abs_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "original_name": {
+ "name": "original_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mime_type": {
+ "name": "mime_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bytes": {
+ "name": "bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'staged'"
+ },
+ "promoted_at": {
+ "name": "promoted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_wechat_file_attachments_task": {
+ "name": "idx_wechat_file_attachments_task",
+ "columns": [
+ "binding_epoch",
+ "task_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "wechat_file_attachments_binding_epoch_wechat_sync_state_binding_epoch_fk": {
+ "name": "wechat_file_attachments_binding_epoch_wechat_sync_state_binding_epoch_fk",
+ "tableFrom": "wechat_file_attachments",
+ "tableTo": "wechat_sync_state",
+ "columnsFrom": [
+ "binding_epoch"
+ ],
+ "columnsTo": [
+ "binding_epoch"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wechat_file_attachments_task_id_wechat_inbox_id_fk": {
+ "name": "wechat_file_attachments_task_id_wechat_inbox_id_fk",
+ "tableFrom": "wechat_file_attachments",
+ "tableTo": "wechat_inbox",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wechat_file_attachments_session_id_sessions_id_fk": {
+ "name": "wechat_file_attachments_session_id_sessions_id_fk",
+ "tableFrom": "wechat_file_attachments",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_inbox": {
+ "name": "wechat_inbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "platform_message_id": {
+ "name": "platform_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "platform_seq": {
+ "name": "platform_seq",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "peer_id": {
+ "name": "peer_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "received_at": {
+ "name": "received_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "platform_created_at": {
+ "name": "platform_created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "lease_until": {
+ "name": "lease_until",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "conversation_epoch": {
+ "name": "conversation_epoch",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "payload_json": {
+ "name": "payload_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_nonce": {
+ "name": "context_nonce",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_ciphertext": {
+ "name": "context_ciphertext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_tag": {
+ "name": "context_tag",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "last_error_code": {
+ "name": "last_error_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_wechat_inbox_platform_message": {
+ "name": "uniq_wechat_inbox_platform_message",
+ "columns": [
+ "binding_epoch",
+ "platform_message_id"
+ ],
+ "isUnique": true
+ },
+ "idx_wechat_inbox_queue": {
+ "name": "idx_wechat_inbox_queue",
+ "columns": [
+ "binding_epoch",
+ "status",
+ "received_at"
+ ],
+ "isUnique": false
+ },
+ "idx_wechat_inbox_lease": {
+ "name": "idx_wechat_inbox_lease",
+ "columns": [
+ "binding_epoch",
+ "lease_until"
+ ],
+ "isUnique": false
+ },
+ "idx_wechat_inbox_conversation": {
+ "name": "idx_wechat_inbox_conversation",
+ "columns": [
+ "binding_epoch",
+ "peer_id",
+ "conversation_epoch"
+ ],
+ "isUnique": false
+ },
+ "uniq_wechat_inbox_running_session": {
+ "name": "uniq_wechat_inbox_running_session",
+ "columns": [
+ "binding_epoch",
+ "session_id"
+ ],
+ "isUnique": true,
+ "where": "\"wechat_inbox\".\"session_id\" IS NOT NULL AND \"wechat_inbox\".\"status\" IN ('dispatching', 'accepted_running', 'waiting_desktop', 'delivery_pending')"
+ }
+ },
+ "foreignKeys": {
+ "wechat_inbox_binding_epoch_wechat_sync_state_binding_epoch_fk": {
+ "name": "wechat_inbox_binding_epoch_wechat_sync_state_binding_epoch_fk",
+ "tableFrom": "wechat_inbox",
+ "tableTo": "wechat_sync_state",
+ "columnsFrom": [
+ "binding_epoch"
+ ],
+ "columnsTo": [
+ "binding_epoch"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wechat_inbox_session_id_sessions_id_fk": {
+ "name": "wechat_inbox_session_id_sessions_id_fk",
+ "tableFrom": "wechat_inbox",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_outbox": {
+ "name": "wechat_outbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chunk_index": {
+ "name": "chunk_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "media_json": {
+ "name": "media_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "next_retry_at": {
+ "name": "next_retry_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "delivered_at": {
+ "name": "delivered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_wechat_outbox_client_id": {
+ "name": "uniq_wechat_outbox_client_id",
+ "columns": [
+ "binding_epoch",
+ "client_id"
+ ],
+ "isUnique": true
+ },
+ "idx_wechat_outbox_delivery": {
+ "name": "idx_wechat_outbox_delivery",
+ "columns": [
+ "binding_epoch",
+ "status",
+ "next_retry_at"
+ ],
+ "isUnique": false
+ },
+ "idx_wechat_outbox_task": {
+ "name": "idx_wechat_outbox_task",
+ "columns": [
+ "binding_epoch",
+ "task_id",
+ "chunk_index"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "wechat_outbox_binding_epoch_wechat_sync_state_binding_epoch_fk": {
+ "name": "wechat_outbox_binding_epoch_wechat_sync_state_binding_epoch_fk",
+ "tableFrom": "wechat_outbox",
+ "tableTo": "wechat_sync_state",
+ "columnsFrom": [
+ "binding_epoch"
+ ],
+ "columnsTo": [
+ "binding_epoch"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wechat_outbox_task_id_wechat_inbox_id_fk": {
+ "name": "wechat_outbox_task_id_wechat_inbox_id_fk",
+ "tableFrom": "wechat_outbox",
+ "tableTo": "wechat_inbox",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_sync_state": {
+ "name": "wechat_sync_state",
+ "columns": {
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "sync_cursor": {
+ "name": "sync_cursor",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "last_poll_at": {
+ "name": "last_poll_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_error_code": {
+ "name": "last_error_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_wechat_sync_active": {
+ "name": "uniq_wechat_sync_active",
+ "columns": [
+ "is_active"
+ ],
+ "isUnique": true,
+ "where": "\"wechat_sync_state\".\"is_active\" = 1"
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {
+ "uniq_orca_worker_creation_reservations_team_label": {
+ "columns": {
+ "lower(\"label\")": {
+ "isExpression": true
+ }
+ }
+ },
+ "uniq_orca_workers_team_label": {
+ "columns": {
+ "lower(\"label\")": {
+ "isExpression": true
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/apps/desktop/drizzle/meta/_journal.json b/apps/desktop/drizzle/meta/_journal.json
index 10b6787346..e0598f0814 100644
--- a/apps/desktop/drizzle/meta/_journal.json
+++ b/apps/desktop/drizzle/meta/_journal.json
@@ -799,6 +799,13 @@
"when": 1789868885746,
"tag": "0113_grey_cannonball",
"breakpoints": true
+ },
+ {
+ "idx": 114,
+ "version": "6",
+ "when": 1789905526324,
+ "tag": "0114_shared_task_events",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/apps/desktop/drizzle/scripts/0114_shared_task_events.ts b/apps/desktop/drizzle/scripts/0114_shared_task_events.ts
new file mode 100644
index 0000000000..04c1521446
--- /dev/null
+++ b/apps/desktop/drizzle/scripts/0114_shared_task_events.ts
@@ -0,0 +1,39 @@
+function run(db) {
+ if (db.prepare("SELECT 1 FROM sqlite_master WHERE type = ? AND name = ?").get("table", "session_meeting_events")) {
+ db.exec("INSERT INTO shared_task_events (id, shared_task_id, session_id, revision, kind, terminal, snapshot, recorded_at) SELECT id, meeting_id, session_id, revision, kind, terminal, snapshot, recorded_at FROM session_meeting_events");
+ db.exec("DROP TABLE session_meeting_events");
+ }
+ function renameId(value) {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
+ if (Object.prototype.hasOwnProperty.call(value, "meetingId")) {
+ value.sharedTaskId = value.meetingId;
+ delete value.meetingId;
+ }
+ }
+ function renameAuthor(value) {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
+ if (Object.prototype.hasOwnProperty.call(value, "meetingAuthor")) {
+ value.sharedTaskAuthor = value.meetingAuthor;
+ renameId(value.sharedTaskAuthor);
+ delete value.meetingAuthor;
+ }
+ }
+ function updateJson(table, column, change) {
+ if (!db.prepare("SELECT 1 FROM sqlite_master WHERE type = ? AND name = ?").get("table", table)) return;
+ const update = db.prepare(`UPDATE ${table} SET ${column} = ? WHERE rowid = ?`);
+ for (const row of db.prepare(`SELECT rowid AS rid, ${column} AS value FROM ${table} WHERE ${column} IS NOT NULL`).all()) {
+ let value;
+ try { value = JSON.parse(row.value); } catch { continue; }
+ const before = JSON.stringify(value);
+ change(value);
+ const after = JSON.stringify(value);
+ if (after !== before) update.run(after, row.rid);
+ }
+ }
+ updateJson("shared_task_events", "snapshot", renameId);
+ updateJson("messages", "agent_meta", renameAuthor);
+ updateJson("agent_input_queue_snapshots", "payload", (items) => {
+ if (Array.isArray(items)) items.forEach(renameAuthor);
+ });
+}
+module.exports = { run };
diff --git a/apps/desktop/src/main/__tests__/codexAuthLink.test.ts b/apps/desktop/src/main/__tests__/codexAuthLink.test.ts
index 5b5d5222db..fb14cc09df 100644
--- a/apps/desktop/src/main/__tests__/codexAuthLink.test.ts
+++ b/apps/desktop/src/main/__tests__/codexAuthLink.test.ts
@@ -62,8 +62,9 @@ afterEach(() => {
/** 两个路径最终是否解析到同一个 inode。 */
function sameInode(a: string, b: string): boolean {
- const sa = fs.statSync(a);
- const sb = fs.statSync(b);
+ // NTFS file IDs can exceed Number.MAX_SAFE_INTEGER; compare without rounding.
+ const sa = fs.statSync(a, { bigint: true });
+ const sb = fs.statSync(b, { bigint: true });
return sa.dev === sb.dev && sa.ino === sb.ino;
}
@@ -103,14 +104,14 @@ describe('relinkSharedCodexAuth', () => {
it.skipIf(!canLinkFile)('POSIX:系统 auth 原子替换后 symlink 自动跟随新 inode', async () => {
fs.writeFileSync(systemAuth, SYSTEM_CONTENT);
await relinkSharedCodexAuth(systemAuth, myAuth, 'darwin');
- const oldInode = fs.statSync(myAuth).ino;
+ const oldInode = fs.statSync(myAuth, { bigint: true }).ino;
const replacement = `${systemAuth}.new`;
fs.writeFileSync(replacement, JSON.stringify({ tokens: { access_token: 'rotated' } }));
fs.renameSync(replacement, systemAuth);
expect(fs.lstatSync(myAuth).isSymbolicLink()).toBe(true);
- expect(fs.statSync(myAuth).ino).not.toBe(oldInode);
+ expect(fs.statSync(myAuth, { bigint: true }).ino).not.toBe(oldInode);
expect(fs.readFileSync(myAuth, 'utf-8')).toContain('rotated');
});
diff --git a/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts b/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts
index 6abd3e76fd..b2dfa82825 100644
--- a/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts
+++ b/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts
@@ -383,6 +383,12 @@ describe('stripMainOnlySendOpts(直连路径消毒)', () => {
expect(stripMainOnlySendOpts(opts)).toEqual(opts);
});
+ it('strips nested sharedTask authors without mutating the input', () => {
+ const opts = { persistUserMessage: { clientId: 'message', content: 'text', sharedTaskAuthor: { accountId: 'forged' } } };
+ expect(stripMainOnlySendOpts(opts)).toEqual({ persistUserMessage: { clientId: 'message', content: 'text' } });
+ expect(opts.persistUserMessage.sharedTaskAuthor).toEqual({ accountId: 'forged' });
+ });
+
it('非对象输入原样返回(事务自己 ?? {} 兜底)', () => {
expect(stripMainOnlySendOpts(undefined)).toBeUndefined();
expect(stripMainOnlySendOpts(null)).toBeNull();
diff --git a/apps/desktop/src/main/__tests__/serverApiClient.test.ts b/apps/desktop/src/main/__tests__/serverApiClient.test.ts
index e6292e0d26..b2ce152cd4 100644
--- a/apps/desktop/src/main/__tests__/serverApiClient.test.ts
+++ b/apps/desktop/src/main/__tests__/serverApiClient.test.ts
@@ -156,6 +156,20 @@ describe('serverApiFetch', () => {
expect(mocks.invalidateSession).toHaveBeenCalledWith('account-unavailable');
});
+ it.each(['ACCOUNT_UNAVAILABLE', 'TOKEN_EXPIRED'])('detached teardown %s cannot refresh or invalidate the next account', async (code) => {
+ mocks.getAccessToken.mockReturnValue('test-new-token');
+ mocks.netFetch.mockResolvedValue({ ok: false, status: 401, json: async () => ({ error: { code } }) });
+ await expect(serverApiFetch('/api/resource', {
+ baseUrl: 'https://old-resource.example.test', token: 'test-old-token',
+ skipAutoRefresh: true, skipSessionInvalidation: true,
+ })).rejects.toMatchObject({ code, statusCode: 401 });
+ expect(mocks.netFetch).toHaveBeenCalledWith('https://old-resource.example.test/api/resource',
+ expect.objectContaining({ headers: expect.objectContaining({ Authorization: 'Bearer test-old-token' }) }));
+ expect(mocks.refresh).not.toHaveBeenCalled();
+ expect(mocks.invalidateSession).not.toHaveBeenCalled();
+ expect(mocks.getAccessToken).not.toHaveBeenCalled();
+ });
+
it.each(['INVALID_TOKEN', 'UNAUTHORIZED'])('%s refresh 一次后重试', async (code) => {
mocks.getAccessToken.mockReturnValueOnce('token-a').mockReturnValueOnce('token-b');
mocks.refresh.mockResolvedValue(true);
diff --git a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
index 8c2dc81a8d..e24b0c9b73 100644
--- a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
+++ b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
@@ -28,6 +28,7 @@ const h = vi.hoisted(() => ({
cancelSessionOperations: vi.fn(),
cleanupRemovedSession: vi.fn(),
runtimeCleanup: vi.fn(),
+ closeSharedTask: vi.fn(),
removeSessionRefs: vi.fn(),
hasRegisteredWorktreeForSession: vi.fn(),
recycleWorktreeForRemovedSession: vi.fn(),
@@ -65,6 +66,7 @@ vi.mock('../cindy-media/ledger', () => ({
removeSessionRefsIfDeleted: h.removeSessionRefs,
}));
vi.mock('../localDb/dialogueWorkspace', () => ({ ensureDialogueWorkspaceDir: vi.fn() }));
+vi.mock('../device-link/sharedTaskRuntime.js', () => ({ closeSharedTaskForTask: h.closeSharedTask }));
vi.mock('../git-context/prRefsStore', () => ({ recomputePrRefsForSession: vi.fn() }));
vi.mock('../localDb/ipc/recentWorkdirs', () => ({
upsertRecentWorkdir: h.upsertRecentWorkdir,
@@ -154,6 +156,7 @@ describe('setSessionsStatusInDb', () => {
}),
);
await setSessionsStatusInDb(ids, 'archived');
+ expect(h.closeSharedTask.mock.calls.map(([id]) => id)).toEqual(ids);
try {
await vi.waitFor(() => expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledOnce());
expect(h.closeSession).toHaveBeenCalledExactlyOnceWith('one');
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 3d3ca553c3..b6bec7ecda 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -586,9 +586,12 @@ import { issueWritableDirectoryPickerGrant } from './maker-ipc/writableDirectory
// 设备互联(跨设备远程控制): relay 连接 host + 开关/设备列表 IPC
import {
initDeviceLinkService,
+ isSharedTaskAvailable,
releaseDeviceLinkOwnershipBeforeLogout,
handleDeviceLinkSystemResume,
} from './device-link';
+import { closeSharedTasksBeforeLogout } from './device-link/sharedTaskRuntime.js';
+import { registerSharedTaskIpc } from './device-link/sharedTaskIpc.js';
import {
getUpdateRelaunchControllers,
hasInFlightRemoteInvokes,
@@ -2049,6 +2052,7 @@ async function teardownAuthAccountBoundary(reason: string): Promise<void> {
// (dispose 同步 clearCurrentDbClient,之后 store 不可用,只能等 15s+ 心跳
// 过期,同机幸存实例接管变慢)。内部带 1.5s 超时,不会卡住登出。
try {
+ await closeSharedTasksBeforeLogout();
await releaseDeviceLinkOwnershipBeforeLogout();
} catch (err) {
authBoundaryLog.error(
@@ -2073,6 +2077,7 @@ async function teardownAuthAccountBoundary(reason: string): Promise<void> {
// (dispose 同步 clearCurrentDbClient,之后 store 不可用,只能等 15s+ 心跳
// 过期,同机幸存实例接管变慢)。内部带 1.5s 超时,不会卡住登出。
try {
+ await closeSharedTasksBeforeLogout();
await releaseDeviceLinkOwnershipBeforeLogout();
} catch (err) {
authBoundaryLog.error(
@@ -9563,6 +9568,7 @@ app.on('ready', async () => {
// owning modules above; future collections/actions do not add tunnel channels.
registerRemoteResourcesIpc();
registerDeviceLinkIpc();
+ registerSharedTaskIpc(isSharedTaskAvailable);
registerFilePeerIpc();
registerRemoteDesktopIpc(isGlobalVoiceInputOverlaySender);
void startupPurgeDrain
diff --git a/apps/desktop/src/main/cindy-media/ledger.ts b/apps/desktop/src/main/cindy-media/ledger.ts
index e28848ddeb..81981725a2 100644
--- a/apps/desktop/src/main/cindy-media/ledger.ts
+++ b/apps/desktop/src/main/cindy-media/ledger.ts
@@ -31,6 +31,16 @@ function defaultDb(): LedgerDb {
return getDbClient().drizzle;
}
+/** Shared task reads use existing provenance; knowing a blob hash grants nothing. */
+export async function sessionCanRead(hash: string, sessionId: string, db: LedgerDb = defaultDb()): Promise<boolean> {
+ const rows = await db.select({ one: sql`1` }).from(mediaRefs).where(and(
+ eq(mediaRefs.hash, hash),
+ or(eq(mediaRefs.originSessionId, sessionId),
+ and(eq(mediaRefs.refKind, 'session-attachment'), eq(mediaRefs.refId, sessionId))),
+ )).limit(1).all();
+ return rows.length > 0;
+}
+
/**
* 引用方类型(多态引用,详见 schema.ts mediaRefs 注释)。
* 'ghost-grant':用户显式引渡给某意识的图(随 ghost_call attachments
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts
index 4edeb9d713..a37ec6befc 100644
--- a/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts
@@ -13,6 +13,7 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import {
DeviceLinkClient,
+ SHARED_TASK_CAPABILITY,
DeviceLinkError,
DEVICE_LINK_CAPABILITY_HISTORY_VIEW_V1,
DL_SUBSCRIBE_CHANNEL,
@@ -47,6 +48,12 @@ vi.mock('../../logger', async (importOriginal) => ({
vi.mock('../settings-store', () => ({
readDeviceLinkSettings: () => deviceLinkSettings.value,
}));
+const sharedTask = vi.hoisted(() => ({ refresh: vi.fn(), capture: vi.fn() }));
+vi.mock('../sharedTaskDispatch.js', async (original) => ({
+ ...await original<typeof import('../sharedTaskDispatch.js')>(),
+ refreshSharedTaskPeer: sharedTask.refresh,
+ captureSharedTaskPeer: sharedTask.capture,
+}));
import {
__testing,
@@ -237,6 +244,24 @@ afterEach(() => {
});
describe('[1] link-accept 发送失败的有限重试', () => {
+ it('refreshes first-join authority and ignores an older failed open after a newer success', async () => {
+ const client = mkClient();
+ __testing.setActiveClient(client as never);
+ const peer = 'shared-task~m~guest~g~d';
+ const payload = { controllerName: 'Guest', protocolVersion: PROTOCOL_VERSION, appVersion: '0.0.0-test', capabilities: [SHARED_TASK_CAPABILITY] };
+ let rejectOld!: (error: Error) => void;
+ sharedTask.capture.mockReturnValue({ author: { displayName: 'Guest' } });
+ sharedTask.refresh.mockImplementationOnce(() => new Promise<void>((_resolve, reject) => { rejectOld = reject; })).mockResolvedValue(undefined);
+ __testing.handleLinkOpen(client as never, peer, 'old', payload);
+ expect(client.sendLinkAccept).not.toHaveBeenCalled();
+ __testing.handleLinkOpen(client as never, peer, 'new', payload);
+ await Promise.resolve();
+ expect(client.sendLinkAccept).toHaveBeenCalledWith(peer, 'new', expect.anything());
+ rejectOld(new Error('old network failure'));
+ await Promise.resolve(); await Promise.resolve();
+ expect(client.closeLink).not.toHaveBeenCalled();
+ expect(client.sendLinkAccept).toHaveBeenCalledTimes(1);
+ });
it('declares history projection support in the host accept, including for legacy controllers', () => {
const client = mkClient();
__testing.setActiveClient(client as never);
diff --git a/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts b/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts
index 65cc19cb17..c80735aaf9 100644
--- a/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts
@@ -33,7 +33,13 @@ const realpathMock = vi.hoisted(() => vi.fn());
const openMock = vi.hoisted(() => vi.fn());
vi.mock('node:fs/promises', () => ({ stat: statMock, realpath: realpathMock, open: openMock }));
-import { fetchLocalMediaToOss, __testing } from '../mediaFetch.js';
+const assertSharedTaskMedia = vi.hoisted(() => vi.fn());
+vi.mock('../sharedTaskMediaAccess.js', () => ({ assertSharedTaskMedia }));
+
+import { fetchLocalMediaToOss, resolveAuthorizedMedia, __testing } from '../mediaFetch.js';
+import { runDeviceLinkInvokeContext } from '../invoke-context.js';
+import { sharedTaskMediaId } from '../sharedTaskMediaContext.js';
+import type { SharedTaskPeerCapture } from '../sharedTaskDispatch.js';
async function codeOf(fn: () => Promise<unknown>): Promise<string> {
try {
@@ -46,6 +52,7 @@ async function codeOf(fn: () => Promise<unknown>): Promise<string> {
beforeEach(() => {
vi.clearAllMocks();
+ assertSharedTaskMedia.mockReset();
__testing.uploadCache.clear();
statMock.mockResolvedValue({ size: 42, mtimeMs: 1000 });
realpathMock.mockImplementation(async (p: string) => p);
@@ -76,6 +83,44 @@ afterEach(() => {
});
describe('fetchLocalMediaToOss — scheme 路由', () => {
+ const sharedTask: SharedTaskPeerCapture = {
+ author: { sharedTaskId: 'shared', sessionId: 'task', memberId: 'guest', accountId: 'user', displayName: 'Guest' },
+ isCurrent: () => true,
+ authorize: () => true,
+ };
+ const shared = <T>(work: () => T) => runDeviceLinkInvokeContext({
+ controllerDeviceId: 'guest-device', channel: 'device-link:media:fetch', sharedTask,
+ }, work);
+
+ it('checks task authorization in the shared resolver before inline reads or file transfer', async () => {
+ assertSharedTaskMedia.mockRejectedValue(new Error('[PERMISSION_DENIED] Outside shared task'));
+ const arg = { url: 'xdt-image://other/a.png', prepareOnly: true };
+ await expect(shared(() => resolveAuthorizedMedia(arg, 1024))).rejects.toThrow('PERMISSION_DENIED');
+ await expect(shared(() => fetchLocalMediaToOss(arg))).rejects.toThrow('PERMISSION_DENIED');
+ expect(imageResolve).not.toHaveBeenCalled();
+ expect(openMock).not.toHaveBeenCalled();
+ expect(uploadLocalFile).not.toHaveBeenCalled();
+ });
+
+ it('preserves upload size limits and isolates shared-task upload cache', async () => {
+ const url = 'xdt-file://local?path=' + encodeURIComponent(path.resolve('work/a.png')) + '&maxBytes=100';
+ let scope: string | undefined;
+ uploadLocalFile.mockImplementation(async () => {
+ scope = sharedTaskMediaId();
+ return { key: 'shared-key', size: 42, contentType: 'image/png' };
+ });
+ await shared(() => fetchLocalMediaToOss({ url }));
+ expect(scope).toBe('shared');
+ expect(uploadLocalFile).toHaveBeenLastCalledWith(expect.any(String), expect.objectContaining({ maxBytes: 100 }));
+ imageResolve.mockReturnValue({ absPath: '/cache/a.png', mimeType: 'image/png' });
+ const image = { url: 'xdt-image://task/a.png' };
+ await fetchLocalMediaToOss(image);
+ await shared(() => fetchLocalMediaToOss(image));
+ await shared(() => fetchLocalMediaToOss(image));
+ expect(uploadLocalFile).toHaveBeenCalledTimes(3);
+ expect(scope).toBe('shared');
+ });
+
it.each([0, 65_536, 65_537])(
'prepares %s bytes inline only within the shared limit',
async (size) => {
diff --git a/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts b/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts
index 994733339f..ffea54a288 100644
--- a/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts
@@ -17,6 +17,9 @@ vi.mock('../../logger', () => ({
}));
import { rewriteOutboundMedia, __testing } from '../outboundMedia';
+import { buildUserMessageAttachmentPayload } from '../../../renderer/lib/messageAttachmentPayload';
+import { withSharedTaskMedia } from '../sharedTaskMediaContext.js';
+import { assertSharedTaskReferences } from '../sharedTaskDispatch.js';
import { parseAttachmentOssRef, isAttachmentOssRef } from '../../../shared/attachmentOssRef';
const SHA256 = 'a'.repeat(64);
@@ -38,6 +41,27 @@ beforeEach(() => {
});
describe('rewriteOutboundMedia — channel gating', () => {
+ it('uploads a real Desktop composer image even when its payload says desktop-host', async () => {
+ const attachment = buildUserMessageAttachmentPayload([{ id: 'image', name: 'a.png', path: '/controller/a.png', url: 'xdt-image://task/a.png', size: 10, ext: '.png', category: 'image', mimeType: 'image/png' }]);
+ expect(attachment.serializedFiles?.[0].pathOrigin).toBe('desktop-host');
+ resolveSafe.mockReturnValue({ absPath: '/cache/a.png', mimeType: 'image/png' });
+ uploadLocalFile.mockResolvedValue({ key: 'cindy/shared-task/sharedTask/u/a.png', contentType: 'image/png', size: 10, sha256: SHA256 });
+ const item = { files: attachment.serializedFiles, persistedContent: JSON.stringify({ images: attachment.persistImageRefs }), chatMessage: { images: attachment.imageAttachments } };
+ const result = await withSharedTaskMedia('sharedTask', () => rewriteOutboundMedia('maker:input:enqueue', ['task', item]));
+ expect(uploadLocalFile).toHaveBeenCalledWith('/cache/a.png', { contentType: 'image/png' });
+ expect(() => assertSharedTaskReferences(result[1], 'task', 0, 'sharedTask')).not.toThrow();
+ });
+ it('rewrites newly added shared queue-edit attachments and preserves host-owned existing files', async () => {
+ uploadLocalFile.mockResolvedValue({ key: 'cindy/shared-task/sharedTask/u/new.png', contentType: 'image/png', size: 10, sha256: SHA256 });
+ const item = { files: [{ path: '/host/cache/old.png', pathOrigin: 'desktop-host' }, { path: '/controller/new.png' }], persistedContent: JSON.stringify({ files: [{ path: '/host/cache/old.png' }, { path: '/controller/new.png' }] }) };
+ const result = await withSharedTaskMedia('sharedTask', () => rewriteOutboundMedia('maker:input:update-content', ['task', 'client', item], new Set(['/host/cache/old.png'])));
+ expect(uploadLocalFile).toHaveBeenCalledTimes(1);
+ expect(uploadLocalFile).toHaveBeenCalledWith('/controller/new.png', {});
+ const rewritten = result[2] as typeof item;
+ expect(rewritten.files[0].path).toBe('/host/cache/old.png');
+ expect(parseAttachmentOssRef(rewritten.files[1].path)?.ossKey).toBe('cindy/shared-task/sharedTask/u/new.png');
+ expect(rewritten.persistedContent).not.toContain('/controller/new.png');
+ });
it('非媒体 channel → 原样,不上传', async () => {
const args = [{ a: 1 }];
const out = await rewriteOutboundMedia('maker:set-model', args);
@@ -62,6 +86,17 @@ describe('rewriteOutboundMedia — channel gating', () => {
});
describe('rewriteQueued — persistedContent 同批改写 + 去重单上传', () => {
+ it('sends a shared Desktop attachment without leaking local optimistic/retry paths', async () => {
+ uploadLocalFile.mockResolvedValue({ key: 'cindy/shared-task/shared/u/file.pdf', size: 10, contentType: 'application/pdf', sha256: SHA256 });
+ const file = { name: 'file.pdf', path: '/local/file.pdf', mimeType: 'application/pdf', category: 'file' };
+ const input = { text: 'Read this', files: [file], persistedContent: JSON.stringify({ text: 'Read this', files: [{ name: file.name, path: file.path }] }),
+ chatMessage: { role: 'user', content: 'Read this', files: [file], images: [{ url: '/local/preview.png' }], retryFiles: [file], retryMentions: [{ path: '/local/file.pdf' }] } };
+ const result = await withSharedTaskMedia('shared', () => rewriteOutboundMedia('maker:input:enqueue', ['task', input]));
+ expect(() => assertSharedTaskReferences(result[1], 'task', 0, 'shared')).not.toThrow();
+ expect(uploadLocalFile).toHaveBeenCalledTimes(1);
+ expect((result[1] as typeof input).chatMessage).toEqual({ role: 'user', content: 'Read this' });
+ expect(input.chatMessage.files).toEqual([file]);
+ });
it('files[] 与 persistedContent 的同一附件用同一 OSS 引用,只上传一次', async () => {
resolveSafe.mockReturnValue({ absPath: '/abs/a.png', mimeType: 'image/png' });
uploadLocalFile
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskAccess.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskAccess.test.ts
new file mode 100644
index 0000000000..8acf2bbf9f
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskAccess.test.ts
@@ -0,0 +1,85 @@
+import { describe, expect, it } from 'vitest';
+import type { SharedTaskQueueItem } from '@cindy/device-link';
+import { SharedTaskAccess } from '../sharedTaskAccess';
+
+const identity = { sharedTaskId: 'sharedTask-1', sessionId: 'task-1', ownerAccountId: 'owner', hostDeviceId: 'host' };
+const a = { memberId: 'member-a', accountId: 'account-a', version: 1, deviceIds: ['device-a'] };
+const b = { memberId: 'member-b', accountId: 'account-b', version: 1, deviceIds: ['device-b'] };
+const caller = { accountId: a.accountId, deviceId: a.deviceIds[0] };
+const snapshot = (revision = 1, guests = [a, b]) => ({ ...identity, revision, status: 'active', guests });
+const loaded = () => {
+ const access = new SharedTaskAccess(identity);
+ access.applyVerifiedSnapshot(snapshot());
+ return access;
+};
+
+describe('task host sharedTask authority', () => {
+ it('revokes queued delivery after removal and ignores an older snapshot', () => {
+ const access = loaded();
+ const ticket = access.capture(caller, 'task-1', 'history.read');
+ expect(ticket.isCurrent()).toBe(true);
+ access.applyVerifiedSnapshot(snapshot(2, [b]));
+ expect(access.applyVerifiedSnapshot(snapshot(1))).toBe(false);
+ expect(ticket.isCurrent()).toBe(false);
+ expect(() => access.applyVerifiedSnapshot(snapshot(3))).toThrow('Revoked');
+ const fresh = { ...a, memberId: 'member-a-new' };
+ access.applyVerifiedSnapshot(snapshot(3, [fresh, b]));
+ expect(ticket.isCurrent()).toBe(false);
+ expect(access.capture(caller, 'task-1', 'history.read').isCurrent()).toBe(true);
+ });
+ it('changing one guest does not cancel another guest or the owner', () => {
+ const access = loaded();
+ const ticket = access.capture(caller, 'task-1', 'input.send');
+ const owner = access.capture({ accountId: 'owner', deviceId: 'owner-phone' }, 'task-1', 'approval.resolve');
+ access.applyVerifiedSnapshot(snapshot(2, [a]));
+ expect(ticket.isCurrent()).toBe(true);
+ expect(owner.isCurrent()).toBe(true);
+ });
+ it('is isolated between two sharedTasks shared by the same guest device', () => {
+ const access = loaded();
+ const otherIdentity = { ...identity, sharedTaskId: 'sharedTask-2', sessionId: 'task-2' };
+ const other = new SharedTaskAccess(otherIdentity);
+ other.applyVerifiedSnapshot({ ...snapshot(), ...otherIdentity });
+ const second = other.capture(caller, 'task-2', 'history.read');
+ access.close();
+ expect(second.isCurrent()).toBe(true);
+ });
+ it('cannot revive after local close or account logout even with a higher revision', () => {
+ const access = loaded();
+ const ticket = access.capture(caller, 'task-1', 'attachment.read');
+ access.close();
+ expect(access.applyVerifiedSnapshot(snapshot(50))).toBe(false);
+ expect(ticket.isCurrent()).toBe(false);
+ });
+ it('refuses reopening a server-closed sharedTask under its original ID', () => {
+ const access = loaded();
+ access.applyVerifiedSnapshot({ ...snapshot(2), status: 'closed' });
+ expect(() => access.applyVerifiedSnapshot(snapshot(3))).toThrow('cannot reopen');
+ });
+ it('does not silently replace a different scope or a conflicting revision', () => {
+ const access = loaded();
+ for (const key of Object.keys(identity)) {
+ expect(() => access.applyVerifiedSnapshot({ ...snapshot(2), [key]: 'different' })).toThrow('scope');
+ }
+ expect(() => access.applyVerifiedSnapshot(snapshot(1, [b]))).toThrow('Conflicting');
+ expect(access.applyVerifiedSnapshot(snapshot(1, [b, a]))).toBe(false);
+ });
+ it('invalidates old delivery when a device grant changes', () => {
+ const access = loaded();
+ const ticket = access.capture(caller, 'task-1', 'history.read');
+ expect(() => access.applyVerifiedSnapshot(snapshot(2, [{ ...a, deviceIds: ['device-a', 'device-c'] }, b]))).toThrow('revision');
+ access.applyVerifiedSnapshot(snapshot(2, [{ ...a, version: 2 }, b]));
+ expect(ticket.isCurrent()).toBe(false);
+ });
+ it('rereads pending status and snapshots caller identity across an await', () => {
+ const access = loaded();
+ let item: SharedTaskQueueItem = { sessionId: 'task-1', authorAccountId: 'account-a', state: 'pending' };
+ const mutableCaller = { ...caller };
+ const ticket = access.capture(mutableCaller, 'task-1', 'input.edit', () => item);
+ mutableCaller.accountId = 'owner';
+ item = { ...item, authorAccountId: 'account-b' };
+ expect(ticket.isCurrent()).toBe(false);
+ item = { ...item, authorAccountId: 'account-a', state: 'accepted' };
+ expect(ticket.isCurrent()).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskApi.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskApi.test.ts
new file mode 100644
index 0000000000..b5ed5e474b
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskApi.test.ts
@@ -0,0 +1,70 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const state = vi.hoisted(() => ({ key: 'account:1', endpoint: 'https://relay.example.test', authenticated: true, boundary: false, accountId: 'owner', region: 'global', token: 'test-old-token' }));
+const http = vi.hoisted(() => vi.fn());
+vi.mock('../../appSessionState.js', () => ({ activeOwnerScopeKey: () => state.key, isAppSessionBoundaryPending: () => state.boundary }));
+vi.mock('../../authManager.js', () => ({ getAuthState: () => ({ isAuthenticated: state.authenticated }),
+ getCurrentUserId: () => state.accountId, getActiveAuthRealm: () => state.region, getAccessToken: () => state.token }));
+vi.mock('../../clientEndpointsService.js', () => ({ getClientEndpoint: () => state.endpoint }));
+vi.mock('../../serverApiClient.js', () => ({ serverApiFetch: http }));
+import { captureSharedTaskBoundaryClose, sharedTaskApi } from '../sharedTaskApi.js';
+
+beforeEach(() => {
+ state.key = 'account:1'; state.endpoint = 'https://relay.example.test'; state.authenticated = true; state.boundary = false;
+ state.accountId = 'owner'; state.region = 'global'; state.token = 'test-old-token';
+ http.mockReset();
+});
+describe('sharedTask Main HTTP adapter', () => {
+ it.each(['SHARED_TASK_HOST_LIMIT', 'SHARED_TASK_JOIN_LIMIT', 'SHARED_TASK_GUEST_LIMIT'])(
+ 'preserves %s through redaction and Electron error serialization', async (code) => {
+ http.mockImplementation(async (_path, options) => {
+ expect(options.allowedRedactedErrorCodes).toContain(code);
+ throw Object.assign(new Error('private server details'), { code });
+ });
+ await expect(sharedTaskApi.create('session', 'Task')).rejects.toThrow('[' + code + '] Shared task limit reached');
+ });
+ it('closes across a pending logout with fixed old credentials and no auth side effects', async () => {
+ state.boundary = true;
+ const close = captureSharedTaskBoundaryClose('owner', 'global')!;
+ state.accountId = 'new-owner'; state.region = 'cn';
+ state.token = 'test-new-token'; state.endpoint = 'https://new-relay.example.test';
+ http.mockResolvedValue({ sharedTaskId: 'sharedTask', status: 'closed' });
+ await close('sharedTask');
+ expect(http).toHaveBeenCalledExactlyOnceWith('/api/device-link/shared-tasks/sharedTask/close',
+ expect.objectContaining({ token: 'test-old-token', baseUrl: 'https://relay.example.test',
+ skipAutoRefresh: true, skipSessionInvalidation: true, timeoutMs: 3_000, redactErrorDetails: true }));
+ });
+ it('cannot capture another account or region, or a cleared credential', () => {
+ expect(captureSharedTaskBoundaryClose('another', 'global')).toBeNull();
+ expect(captureSharedTaskBoundaryClose('owner', 'cn')).toBeNull();
+ state.token = '';
+ expect(captureSharedTaskBoundaryClose('owner', 'global')).toBeNull();
+ expect(http).not.toHaveBeenCalled();
+ });
+ it('uses a redacted, bounded request through the existing auth client', async () => {
+ http.mockImplementation(async (_path, options) => {
+ expect(options.baseUrl()).toBe(state.endpoint);
+ expect(options).toMatchObject({ timeoutMs: 15_000, cache: 'no-store', redactErrorDetails: true, logLabel: '/api/device-link/shared-tasks' });
+ return { sharedTaskId: 'sharedTask', status: 'closed' };
+ });
+ await expect(sharedTaskApi.close('sharedTask')).resolves.toMatchObject({ status: 'closed' });
+ });
+ it.each(['account', 'region', 'logout', 'boundary'])('blocks a retry after %s changes', async (change) => {
+ http.mockImplementation(async (_path, options) => {
+ expect(options.baseUrl()).toBe(state.endpoint);
+ if (change === 'account') state.key = 'account:2';
+ if (change === 'region') state.endpoint = 'https://other-relay.example.test';
+ if (change === 'logout') state.authenticated = false;
+ if (change === 'boundary') state.boundary = true;
+ return { endpoint: options.baseUrl() };
+ });
+ await expect(sharedTaskApi.close('sharedTask')).rejects.toThrow('account or region changed');
+ });
+ it('rejects late success when logout happens after sending', async () => {
+ http.mockImplementation(async () => {
+ state.authenticated = false;
+ return { sharedTaskId: 'sharedTask', status: 'closed' };
+ });
+ await expect(sharedTaskApi.close('sharedTask')).rejects.toThrow('account or region changed');
+ });
+});
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskCommands.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskCommands.test.ts
new file mode 100644
index 0000000000..e0ff668880
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskCommands.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { SharedTaskApi, SharedTaskListItem } from '@cindy/device-link';
+import { executeSharedTaskAccountCommand } from '../sharedTaskCommands.js';
+
+function listItem(sharedTaskId: string, overrides: Partial<SharedTaskListItem> = {}): SharedTaskListItem {
+ return {
+ sharedTaskId, sessionId: 'session-' + sharedTaskId, ownerAccountId: 'owner',
+ hostDeviceId: 'device-a', title: 'task ' + sharedTaskId, revision: 1, ...overrides,
+ };
+}
+
+function api(items: SharedTaskListItem[], failing = new Set<string>()): SharedTaskApi {
+ return {
+ list: vi.fn(async () => items),
+ close: vi.fn(async (sharedTaskId: string) => {
+ if (failing.has(sharedTaskId)) throw new Error('server busy');
+ return { sharedTaskId, status: 'closed' as const };
+ }),
+ } as unknown as SharedTaskApi;
+}
+
+describe('sharedTask account commands', () => {
+ it('lists owned shares for the caller account and flags locally hosted ones', async () => {
+ const list = [listItem('a'), listItem('b', { ownerAccountId: 'someone-else' }), listItem('c', { hostDeviceId: 'device-b' })];
+ const result = await executeSharedTaskAccountCommand({ action: 'owned' }, api(list), 'owner', { hostedIds: () => ['a'] });
+ expect(result).toEqual([
+ { ...listItem('a'), local: true },
+ { ...listItem('c', { hostDeviceId: 'device-b' }), local: false },
+ ]);
+ });
+
+ it('returns no owned shares without an account', async () => {
+ const listSpy = api([listItem('a')]);
+ expect(await executeSharedTaskAccountCommand({ action: 'owned' }, listSpy, undefined)).toEqual([]);
+ expect(listSpy.list).not.toHaveBeenCalled();
+ });
+
+ it('closes a locally hosted task through the host journal, not the raw api', async () => {
+ const closeHosted = vi.fn(async () => undefined);
+ const listSpy = api([listItem('a')]);
+ const result = await executeSharedTaskAccountCommand({ action: 'close', sharedTaskId: 'a' }, listSpy, 'owner',
+ { hostedIds: () => ['a'], closeHosted });
+ expect(closeHosted).toHaveBeenCalledWith('a');
+ expect(listSpy.close).not.toHaveBeenCalled();
+ expect(result).toEqual({ closed: ['a'], failed: [] });
+ });
+
+ it('closes remote-hosted tasks directly and keeps failed items for retry', async () => {
+ const closeHosted = vi.fn(async () => undefined);
+ const listSpy = api([listItem('a'), listItem('b', { hostDeviceId: 'device-b' }), listItem('c', { hostDeviceId: 'device-b' })], new Set(['c']));
+ const result = await executeSharedTaskAccountCommand({ action: 'close', all: true }, listSpy, 'owner',
+ { hostedIds: () => ['a'], closeHosted });
+ expect(closeHosted).toHaveBeenCalledTimes(1);
+ expect(listSpy.close).toHaveBeenCalledTimes(2);
+ expect(result).toEqual({ closed: ['a', 'b'], failed: [{ sharedTaskId: 'c' }] });
+ });
+
+ it('still rejects unknown account commands', async () => {
+ await expect(executeSharedTaskAccountCommand({ action: 'nope' }, api([]), 'owner'))
+ .rejects.toThrow('INVALID_PARAMS');
+ });
+});
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts
new file mode 100644
index 0000000000..93c8734de0
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts
@@ -0,0 +1,86 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import { assertSharedTaskInvoke, assertSharedTaskReferences, captureSharedTaskPush, setSharedTaskQueueReader, type SharedTaskPeerCapture } from '../sharedTaskDispatch.js';
+
+function capture(): SharedTaskPeerCapture {
+ return {
+ author: { sharedTaskId: 'sharedTask', sessionId: 'task', memberId: 'member', accountId: 'guest', displayName: 'Guest' },
+ isCurrent: () => true,
+ authorize: (operation, item) => operation !== 'input.edit' && operation !== 'input.withdraw' || item?.authorAccountId === 'guest',
+ };
+}
+afterEach(() => setSharedTaskQueueReader(null));
+describe('sharedTask dispatch scope', () => {
+ it('reads subagent context only through the shared parent task', () => {
+ for (const channel of ['local-db:subagent-runs:list', 'local-db:subagent-runs:detail', 'local-db:subagent-runs:transcript']) {
+ const request = { sessionId: 'task', provider: 'pi', runIdOrAlias: 'child' };
+ expect(() => assertSharedTaskInvoke(capture(), { channel, args: [request] })).not.toThrow();
+ for (const args of [[{ ...request, sessionId: 'other' }], [{ ...request, path: '/private' }], [request, 'other']]) {
+ expect(() => assertSharedTaskInvoke(capture(), { channel, args })).toThrow();
+ }
+ expect(() => assertSharedTaskInvoke({ ...capture(), isCurrent: () => false }, { channel, args: [request] })).toThrow();
+ }
+ });
+ it('allows only existing references from the member own pending row when editing', () => {
+ const payload = { channel: 'maker:input:update-content', args: ['task', 'message', { files: [{ path: '/host/cache/a.png' }] }] };
+ setSharedTaskQueueReader((_sid, clientId) => clientId === 'message' ? { sessionId: 'task', authorAccountId: 'guest', state: 'pending', attachments: [{ path: '/host/cache/a.png' }] } : undefined);
+ expect(() => assertSharedTaskInvoke(capture(), payload)).not.toThrow();
+ expect(() => assertSharedTaskInvoke(capture(), { ...payload, args: ['task', 'other', payload.args[2]] })).toThrow();
+ expect(() => assertSharedTaskInvoke(capture(), { ...payload, args: ['task', 'message', { files: [{ path: '/host/private.png' }] }] })).toThrow();
+ setSharedTaskQueueReader(() => ({ sessionId: 'task', authorAccountId: 'owner', state: 'pending', attachments: [{ path: '/host/cache/a.png' }] }));
+ expect(() => assertSharedTaskInvoke(capture(), payload)).toThrow();
+ });
+ it('never inherits the full-device allowlist or wildcard subscriptions', () => {
+ for (const channel of ['maker:create-session', 'maker:set-permission-mode', 'device-link:voice:credential-sync', 'local-db:sessions:list', 'maker:remote-resources:list']) {
+ expect(() => assertSharedTaskInvoke(capture(), { channel, args: ['task'] })).toThrow('PERMISSION_DENIED');
+ }
+ for (const topics of [['*'], ['sessions'], ['session:other'], ['session:task', 'session:other']]) {
+ expect(() => assertSharedTaskInvoke(capture(), { channel: 'device-link:subscribe', args: [{ topics }] })).toThrow();
+ }
+ expect(() => assertSharedTaskInvoke(capture(), { channel: 'device-link:subscribe', args: [{ topics: ['session:task'] }] })).not.toThrow();
+ });
+ it('allows shared task history and Agent settings, rejecting another task', () => {
+ for (const channel of ['local-db:messages:list', 'maker:set-model', 'maker:set-effort', 'maker:input:stop']) {
+ expect(() => assertSharedTaskInvoke(capture(), { channel, args: ['task'] })).not.toThrow();
+ expect(() => assertSharedTaskInvoke(capture(), { channel, args: ['other'] })).toThrow();
+ }
+ });
+ it('accepts media preparation and OSS fallback without granting the file-peer channel', () => {
+ for (const prepareOnly of [true, false]) {
+ expect(() => assertSharedTaskInvoke(capture(), {
+ channel: 'device-link:media:fetch', args: [{ url: 'xdt-image://task/a.png', prepareOnly }],
+ })).not.toThrow();
+ }
+ expect(() => assertSharedTaskInvoke(capture(), {
+ channel: 'device-link:media:fetch', args: [{ url: 'xdt-image://task/a.png', prepareOnly: true, sessionId: 'other' }],
+ })).toThrow();
+ expect(() => assertSharedTaskInvoke(capture(), {
+ channel: 'device-link:file-peer', args: [{ action: 'caps' }],
+ })).toThrow();
+ });
+ it('checks nested references in both structured and persisted content before hydration', () => {
+ for (const value of [
+ { agentReferences: [{ kind: 'message', sessionId: 'other' }] },
+ { persistedContent: JSON.stringify({ agentReferences: [{ kind: 'message', sessionId: 'other' }] }) },
+ { trustedSessionReferenceContexts: [{ sessionId: 'other' }] },
+ { agentReferences: [{ kind: 'bot', botId: 'private-bot' }] },
+ { files: [{ path: 'private/other-task.png', pathOrigin: 'desktop-host' }] },
+ { persistedContent: JSON.stringify({ images: [{ url: 'cindy-media://blobs/private.png' }] }) },
+ ]) expect(() => assertSharedTaskReferences(value, 'task')).toThrow();
+ expect(() => assertSharedTaskReferences({ agentReferences: [{ kind: 'message', sessionId: 'task' }] }, 'task')).not.toThrow();
+ });
+ it('reads queue ownership from the host and allows results after successful withdrawal', () => {
+ const payload = { channel: 'maker:input:remove', args: ['task', 'message'] };
+ expect(() => assertSharedTaskInvoke(capture(), payload)).toThrow();
+ setSharedTaskQueueReader(() => ({ sessionId: 'task', authorAccountId: 'owner', state: 'pending' }));
+ expect(() => assertSharedTaskInvoke(capture(), payload)).toThrow();
+ setSharedTaskQueueReader(() => ({ sessionId: 'task', authorAccountId: 'guest', state: 'pending' }));
+ expect(() => assertSharedTaskInvoke(capture(), payload)).not.toThrow();
+ setSharedTaskQueueReader(() => undefined);
+ expect(() => assertSharedTaskInvoke(capture(), payload, undefined, 'result')).not.toThrow();
+ });
+ it('rejects expired captured authorization and unbound sharedTask pushes without changing same-account traffic', () => {
+ expect(() => assertSharedTaskInvoke({ ...capture(), isCurrent: () => false }, { channel: 'local-db:messages:list', args: ['task'] })).toThrow();
+ expect(captureSharedTaskPush('shared-task~m~guest~g~d', 'maker:event', { sessionId: 'task' })).toBeNull();
+ expect(captureSharedTaskPush('my-phone', 'maker:provider:changed', {})?.()).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts
new file mode 100644
index 0000000000..c7e7ca5c5e
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts
@@ -0,0 +1,434 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createSharedTaskApi, parseSharedTaskSnapshot, type SharedTaskDetail } from '@cindy/device-link';
+import type { SharedTaskJournalEntry } from '../../localDb/sharedTasks.js';
+import { SharedTaskHost, type SharedTaskHostOptions } from '../sharedTaskHost.js';
+
+const detail = (revision = 1): SharedTaskDetail => ({
+ sharedTaskId: 'sharedTask', sessionId: 'session', ownerAccountId: 'owner', hostDeviceId: 'desktop',
+ revision, status: 'active', title: 'Task',
+ guests: [
+ { memberId: 'member-a', accountId: 'guest-a', deviceIds: ['phone-a'], version: 1 },
+ { memberId: 'member-b', accountId: 'guest-b', deviceIds: ['phone-b'], version: 1 },
+ ],
+ memberLabels: [],
+});
+const api = {
+ create: vi.fn(), list: vi.fn(), get: vi.fn(), invite: vi.fn(), join: vi.fn(),
+ remove: vi.fn(), leave: vi.fn(), close: vi.fn(),
+};
+let records: Map<string, SharedTaskJournalEntry>;
+let options: SharedTaskHostOptions;
+let host: SharedTaskHost;
+let current: boolean;
+let serverDetail: SharedTaskDetail;
+const canRead = (member = 'a') => host.authorize('sharedTask', { accountId: `guest-${member}`, deviceId: `phone-${member}` }, 'session', 'history.read').allowed;
+beforeEach(() => {
+ for (const fn of Object.values(api)) fn.mockReset();
+ current = true;
+ serverDetail = detail();
+ records = new Map();
+ api.create.mockResolvedValue({ sharedTaskId: 'sharedTask', revision: 1 });
+ api.get.mockImplementation(async () => serverDetail);
+ api.list.mockImplementation(async () => serverDetail.status === 'active' ? [serverDetail] : []);
+ options = {
+ api, ownerAccountId: 'owner', hostDeviceId: 'desktop', isCurrent: () => current,
+ readSession: vi.fn(async (id) => ({ id, title: 'Task', status: 'active' })),
+ revoke: vi.fn(), changed: vi.fn(), journal: {
+ async latest() { return structuredClone([...records.values()]); },
+ async recordAuthority(snapshot) {
+ const previous = records.get(snapshot.sharedTaskId);
+ if (previous?.terminal || (previous?.snapshot?.revision ?? 0) >= snapshot.revision) return false;
+ records.set(snapshot.sharedTaskId, { sharedTaskId: snapshot.sharedTaskId, sessionId: snapshot.sessionId,
+ terminal: snapshot.status === 'closed', snapshot: parseSharedTaskSnapshot(snapshot) });
+ return true;
+ },
+ async close(identity) {
+ records.set(identity.sharedTaskId, { sharedTaskId: identity.sharedTaskId, sessionId: identity.sessionId, terminal: true, snapshot: null });
+ },
+ },
+ };
+ host = new SharedTaskHost(options);
+});
+describe('task host sharedTask lifecycle', () => {
+ it('allows first sharing after an unshared task is archived and restored', async () => {
+ await host.closeLocallyForBoundary('session');
+ options.readSession = vi.fn(async (id) => ({ id, title: 'Task', status: 'archived' }));
+ await expect(host.open('session')).rejects.toThrow('unavailable');
+ expect(api.create).not.toHaveBeenCalled();
+ options.readSession = vi.fn(async (id) => ({ id, title: 'Task', status: 'active' }));
+ await expect(host.open('session')).resolves.toBe('sharedTask');
+ expect(canRead()).toBe(true);
+ });
+
+ it('waits for archive durability and server closure before creating a fresh share', async () => {
+ await host.open('session');
+ const oldCapture = host.capturePeer('shared-task~sharedTask~guest~member-a~phone-a')!;
+ let finishRefresh!: (value: SharedTaskDetail) => void;
+ api.get.mockImplementationOnce(() => new Promise<SharedTaskDetail>((resolve) => { finishRefresh = resolve; }));
+ const refresh = host.refresh('sharedTask');
+ const staleRejected = expect(refresh).rejects.toThrow('closed');
+ await vi.waitFor(() => expect(finishRefresh).toBeTypeOf('function'));
+ const persist = options.journal.close;
+ let finishWrite!: () => void;
+ options.journal.close = vi.fn(async (identity) => {
+ await new Promise<void>((resolve) => { finishWrite = resolve; });
+ await persist(identity);
+ });
+ const archive = host.closeLocallyForBoundary('session');
+ await vi.waitFor(() => expect(finishWrite).toBeTypeOf('function'));
+ const reopen = host.open('session');
+ await Promise.resolve();
+ expect(api.create).toHaveBeenCalledTimes(1);
+ expect(api.close).not.toHaveBeenCalled();
+ api.close.mockImplementation(async () => {
+ expect(records.get('sharedTask')?.terminal).toBe(true);
+ serverDetail = { ...detail(), sharedTaskId: 'fresh-sharedTask' };
+ });
+ api.create.mockImplementation(async () => {
+ expect(api.close).toHaveBeenCalledWith('sharedTask');
+ return { sharedTaskId: 'fresh-sharedTask', revision: 1 };
+ });
+ finishWrite();
+ await archive;
+ await expect(reopen).resolves.toBe('fresh-sharedTask');
+ finishRefresh(detail(2));
+ await staleRejected;
+ expect(oldCapture.isCurrent()).toBe(false);
+ expect(records.get('sharedTask')?.terminal).toBe(true);
+ expect(records.get('fresh-sharedTask')?.terminal).toBe(false);
+ expect(host.capturePeer('shared-task~fresh-sharedTask~guest~member-a~phone-a')?.isCurrent()).toBe(true);
+ });
+
+ it('keeps an old open fenced when the restored task is already sharing again', async () => {
+ let release!: () => void;
+ vi.mocked(options.readSession).mockImplementationOnce(async (id) => {
+ await new Promise<void>((resolve) => { release = resolve; });
+ return { id, title: 'Task', status: 'active' };
+ });
+ const oldOpen = host.open('session');
+ const rejected = expect(oldOpen).rejects.toThrow('closed');
+ await vi.waitFor(() => expect(release).toBeTypeOf('function'));
+ await host.closeLocallyForBoundary('session');
+ await expect(host.open('session')).resolves.toBe('sharedTask');
+ release();
+ await rejected;
+ expect(api.create).toHaveBeenCalledOnce();
+ });
+
+ it('preserves an unfinished archive fence across same-profile host replacement', async () => {
+ options.creationState = { pending: new Map(), identities: new Map() };
+ host = new SharedTaskHost(options);
+ await host.open('session');
+ const persist = options.journal.close;
+ let release!: () => void;
+ options.journal.close = vi.fn(async (identity) => {
+ await new Promise<void>((resolve) => { release = resolve; });
+ await persist(identity);
+ });
+ const archive = host.closeLocallyForBoundary('session');
+ await vi.waitFor(() => expect(release).toBeTypeOf('function'));
+ const disposing = host.dispose();
+ host = new SharedTaskHost(options);
+ const opening = host.open('session');
+ await Promise.resolve();
+ expect(api.create).toHaveBeenCalledOnce();
+ api.create.mockResolvedValue({ sharedTaskId: 'fresh', revision: 1 });
+ serverDetail = { ...detail(), sharedTaskId: 'fresh' };
+ release();
+ await archive;
+ await disposing;
+ await expect(opening).resolves.toBe('fresh');
+ expect(records.get('fresh')?.terminal).toBe(false);
+ });
+
+ it('retries inherited terminal server closures before re-sharing, without reusing old invitations', async () => {
+ await host.open('session');
+ await host.closeLocallyForBoundary('session');
+ await host.dispose();
+ host = new SharedTaskHost(options);
+ api.close.mockRejectedValueOnce(new Error('offline'));
+ await expect(host.open('session')).rejects.toThrow('offline');
+ expect(api.create).toHaveBeenCalledOnce();
+ api.create.mockResolvedValue({ sharedTaskId: 'fresh', revision: 1 });
+ serverDetail = { ...detail(), sharedTaskId: 'fresh' };
+ await expect(host.open('session')).resolves.toBe('fresh');
+ expect(api.close).toHaveBeenCalledTimes(2);
+ expect(host.capturePeer('shared-task~sharedTask~guest~member-a~phone-a')).toBeNull();
+ });
+
+ it.each([undefined, 'session'])('drains creates from a retired same-profile host at boundary (%s)', async (sessionId) => {
+ let reply!: (value: unknown) => void;
+ const request = vi.fn(() => new Promise<unknown>((resolve) => { reply = resolve; }));
+ options.creationState = { pending: new Map(), identities: new Map() };
+ options.api = createSharedTaskApi({ request, captureScope: () => ({ isCurrent: () => current }) });
+ host = new SharedTaskHost(options);
+ const opening = host.open('session');
+ const rejected = expect(opening).rejects.toThrow('account or region changed');
+ await vi.waitFor(() => expect(reply).toBeTypeOf('function'));
+ current = false;
+ await host.dispose();
+ const replacement = new SharedTaskHost({ ...options, isCurrent: () => true });
+ let finished = false;
+ const closing = replacement.closeLocallyForBoundary(sessionId).then((ids) => { finished = true; return ids; });
+ await Promise.resolve();
+ expect(finished).toBe(false);
+ reply({ sharedTaskId: 'late-sharedTask', revision: 1 });
+ expect(await closing).toEqual(['late-sharedTask']);
+ await rejected;
+ expect(records.get('late-sharedTask')?.terminal).toBe(true);
+ expect(replacement.capturePeer('shared-task~late-shared-task~guest~member-a~phone-a')).toBeNull();
+ });
+ it.each([undefined, 'session'])('drains a late committed create before releasing the outgoing profile (%s)', async (sessionId) => {
+ let reply!: (value: unknown) => void;
+ const request = vi.fn(() => new Promise<unknown>((resolve) => { reply = resolve; }));
+ options.api = createSharedTaskApi({ request, captureScope: () => ({ isCurrent: () => current }) });
+ const opening = host.open('session');
+ const rejected = expect(opening).rejects.toThrow(sessionId ? 'Shared task was closed' : 'account or region changed');
+ await vi.waitFor(() => expect(reply).toBeTypeOf('function'));
+ if (!sessionId) current = false;
+ let databaseReleased = false;
+ const persist = options.journal.close;
+ options.journal.close = vi.fn(async (identity) => {
+ expect(databaseReleased).toBe(false);
+ await persist(identity);
+ });
+ const boundary = host.closeLocallyForBoundary(sessionId).then((ids) => { databaseReleased = true; return ids; });
+ await Promise.resolve();
+ expect(databaseReleased).toBe(false);
+ reply({ sharedTaskId: 'late-sharedTask', revision: 1 });
+ expect(await boundary).toEqual(['late-sharedTask']);
+ await rejected;
+ expect(records.get('late-sharedTask')?.terminal).toBe(true);
+ expect(request).toHaveBeenCalledOnce();
+ current = true;
+ options.api = api;
+ api.list.mockResolvedValue([{ ...detail(), sharedTaskId: 'late-sharedTask' }]);
+ await new SharedTaskHost(options).restore();
+ expect(api.close).toHaveBeenCalledWith('late-sharedTask');
+ });
+ it('retains a committed identity while the initial authority fetch is pending', async () => {
+ let finish!: () => void;
+ api.get.mockImplementationOnce(async () => {
+ await new Promise<void>((resolve) => { finish = resolve; });
+ return detail();
+ });
+ const opening = host.open('session');
+ const rejected = expect(opening).rejects.toThrow('generation');
+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'));
+ current = false;
+ expect(await host.closeLocallyForBoundary()).toEqual(['sharedTask']);
+ expect(records.get('sharedTask')?.terminal).toBe(true);
+ finish();
+ await rejected;
+ });
+ it('does not grant an in-flight restore after the task boundary begins', async () => {
+ let release!: () => void;
+ options.readSession = vi.fn(async (id) => {
+ await new Promise<void>((resolve) => { release = resolve; });
+ return { id, title: 'Task', status: 'active' };
+ });
+ const refreshing = host.refresh('sharedTask');
+ await vi.waitFor(() => expect(release).toBeTypeOf('function'));
+ await host.closeLocallyForBoundary('session');
+ release();
+ await expect(refreshing).rejects.toThrow('closed');
+ expect(canRead()).toBe(false);
+ expect(host.capturePeer('shared-task~sharedTask~guest~member-a~phone-a')).toBeNull();
+ });
+ it('durably closes the outgoing profile after its network generation is fenced', async () => {
+ await host.open('session');
+ current = false;
+ await host.dispose();
+ await host.closeLocallyForBoundary();
+ expect(records.get('sharedTask')?.terminal).toBe(true);
+ expect(api.close).not.toHaveBeenCalled();
+ current = true;
+ const restored = new SharedTaskHost(options);
+ await restored.restore();
+ expect(api.close).toHaveBeenCalledWith('sharedTask');
+ expect(restored.capturePeer('shared-task~sharedTask~guest~member-a~phone-a')).toBeNull();
+ });
+
+ it('closes only the archived task and propagates a journal failure', async () => {
+ await host.open('session');
+ await host.closeLocallyForBoundary('another-task');
+ expect(canRead()).toBe(true);
+ options.journal.close = vi.fn(async () => { throw new Error('disk failed'); });
+ await expect(host.closeLocallyForBoundary('session')).rejects.toThrow('disk failed');
+ expect(canRead()).toBe(false);
+ await expect(host.dispose()).rejects.toThrow('disk failed');
+ });
+ it('invalidates old captures without revoking existing devices when a member adds a device', async () => {
+ await host.open('session');
+ expect(host.capturePeer('shared-task~sharedTask~host')).toBeNull();
+ expect(host.capturePeer('shared-task~sharedTask~guest~member-a~phone-b')).toBeNull();
+ const a = host.capturePeer('shared-task~sharedTask~guest~member-a~phone-a')!;
+ const b = host.capturePeer('shared-task~sharedTask~guest~member-b~phone-b')!;
+ expect(a.author.accountId).toBe('guest-a');
+ expect(a.isCurrent()).toBe(true);
+ serverDetail = { ...detail(2), guests: detail().guests.map((member) => member.memberId === 'member-a' ? { ...member, version: 2, deviceIds: [...member.deviceIds, 'second-phone'] } : member) };
+ await host.refresh('sharedTask');
+ expect(a.isCurrent()).toBe(false);
+ expect(b.isCurrent()).toBe(true);
+ expect(options.revoke).not.toHaveBeenCalled();
+ expect(host.capturePeer('shared-task~sharedTask~guest~member-a~phone-a')?.isCurrent()).toBe(true);
+ expect(host.capturePeer('shared-task~sharedTask~guest~member-a~second-phone')?.isCurrent()).toBe(true);
+ await host.dispose();
+ expect(b.isCurrent()).toBe(false);
+ });
+ it('opens an existing task and requires a server snapshot before granting access', async () => {
+ expect(canRead()).toBe(false);
+ expect(await host.open('session')).toBe('sharedTask');
+ expect(api.create).toHaveBeenCalledWith('session', 'Task', expect.any(Function));
+ expect(canRead()).toBe(true);
+ expect(records.get('sharedTask')?.snapshot?.revision).toBe(1);
+ });
+ it('does not authorize from a persisted snapshot while offline', async () => {
+ await options.journal.recordAuthority(detail());
+ api.list.mockRejectedValue(new Error('offline'));
+ await expect(host.restore()).rejects.toThrow('offline');
+ expect(canRead()).toBe(false);
+ });
+ it('restores members without a new join request after the host restarts', async () => {
+ await host.open('session');
+ await host.dispose();
+ host = new SharedTaskHost(options);
+ expect(canRead()).toBe(false);
+ await host.restore();
+ expect(canRead()).toBe(true);
+ expect(api.join).not.toHaveBeenCalled();
+ });
+ it('rejects another host or a different task returned for the create result', async () => {
+ serverDetail = { ...detail(), hostDeviceId: 'other-desktop' };
+ await expect(host.open('session')).rejects.toThrow('not hosted');
+ serverDetail = { ...detail(), sessionId: 'other-session' };
+ await expect(host.open('session')).rejects.toThrow('does not match');
+ expect(records.size).toBe(0);
+ expect(canRead()).toBe(false);
+ });
+ it('drops late replies after logout or host disposal', async () => {
+ api.get.mockImplementation(async () => { current = false; return detail(); });
+ await expect(host.open('session')).rejects.toThrow('generation');
+ expect(records.size).toBe(0);
+ expect(canRead()).toBe(false);
+ });
+ it('denies a removed member immediately while other peers continue working', async () => {
+ await host.open('session');
+ let finish!: () => void;
+ api.remove.mockImplementation(() => new Promise<void>((resolve) => { finish = resolve; }));
+ const removing = host.remove('sharedTask', 'member-a');
+ expect(canRead()).toBe(false);
+ expect(canRead('b')).toBe(true);
+ expect(options.revoke).not.toHaveBeenCalled();
+ await vi.waitFor(() => expect(api.remove).toHaveBeenCalled());
+ serverDetail = { ...detail(2), guests: [detail().guests[1]] };
+ finish();
+ await removing;
+ expect(options.revoke).toHaveBeenCalledExactlyOnceWith('sharedTask', 'member-a');
+ expect(canRead()).toBe(false);
+ expect(canRead('b')).toBe(true);
+ });
+ it('retains a removal fence on network failure and recovers it only by reconciliation', async () => {
+ await host.open('session');
+ api.remove.mockRejectedValue(new Error('offline'));
+ api.get.mockRejectedValueOnce(new Error('offline'));
+ await expect(host.remove('sharedTask', 'member-a')).rejects.toThrow('offline');
+ expect(canRead()).toBe(false);
+ expect(canRead('b')).toBe(true);
+ await host.refresh('sharedTask');
+ expect(canRead()).toBe(true);
+ expect(options.revoke).not.toHaveBeenCalled();
+ expect(host.capturePeer('shared-task~sharedTask~guest~member-a~phone-a')?.isCurrent()).toBe(true);
+ });
+ it('closes locally before awaiting the server and retries durable closure after restart', async () => {
+ await host.open('session');
+ api.close.mockRejectedValueOnce(new Error('offline'));
+ const closing = host.close('sharedTask');
+ expect(canRead()).toBe(false);
+ expect(host.detail('sharedTask')?.status).toBe('closed');
+ await expect(closing).rejects.toThrow('offline');
+ await host.dispose();
+ host = new SharedTaskHost(options);
+ api.close.mockResolvedValue({ sharedTaskId: 'sharedTask', status: 'closed' });
+ await host.restore();
+ expect(api.close).toHaveBeenCalledTimes(2);
+ expect(canRead()).toBe(false);
+ });
+ it('observes sharedTasks closed on another owner device without reviving cached members', async () => {
+ await host.open('session');
+ serverDetail = { ...detail(2), status: 'closed' };
+ await host.restore();
+ expect(canRead()).toBe(false);
+ expect(records.get('sharedTask')?.terminal).toBe(true);
+ });
+ it.each(['dispose', 'account-switch'] as const)('persists closure despite a pending refresh and %s', async (boundary) => {
+ await host.open('session');
+ let finish!: (value: SharedTaskDetail) => void;
+ api.get.mockImplementationOnce(() => new Promise<SharedTaskDetail>((resolve) => { finish = resolve; }));
+ const refresh = host.refresh('sharedTask');
+ await vi.waitFor(() => expect(finish).toBeDefined());
+ const refreshFailed = expect(refresh).rejects.toThrow('generation');
+ const closing = host.close('sharedTask');
+ const closeFailed = expect(closing).rejects.toThrow('generation');
+ if (boundary === 'account-switch') current = false;
+ else await host.dispose();
+ // The close record must not wait for the outstanding HTTP request.
+ expect(records.get('sharedTask')?.terminal).toBe(true);
+ finish(detail(2));
+ await refreshFailed;
+ await closeFailed;
+ expect(api.close).not.toHaveBeenCalled();
+ current = true;
+ host = new SharedTaskHost(options);
+ await host.restore();
+ expect(canRead()).toBe(false);
+ expect(api.close).toHaveBeenCalledOnce();
+ });
+ it('waits for the bound journal on dispose without waiting for network requests', async () => {
+ await host.open('session');
+ const persist = options.journal.close;
+ let finishWrite!: () => void;
+ options.journal.close = vi.fn((identity) => new Promise<void>((resolve) => {
+ finishWrite = () => { void persist(identity).then(resolve); };
+ }));
+ const closing = host.close('sharedTask');
+ const closeFailed = expect(closing).rejects.toThrow('generation');
+ let disposed = false;
+ const disposing = Promise.resolve(host.dispose()).then(() => { disposed = true; });
+ await Promise.resolve();
+ expect(disposed).toBe(false);
+ expect(canRead()).toBe(false);
+ finishWrite();
+ await disposing;
+ await closeFailed;
+ expect(records.get('sharedTask')?.terminal).toBe(true);
+ expect(api.close).not.toHaveBeenCalled();
+ });
+ it('surfaces journal failure during close and disposal instead of claiming durability', async () => {
+ await host.open('session');
+ options.journal.close = vi.fn().mockRejectedValue(new Error('disk unavailable'));
+ await expect(host.close('sharedTask')).rejects.toThrow('disk unavailable');
+ expect(canRead()).toBe(false);
+ expect(api.close).not.toHaveBeenCalled();
+ await expect(Promise.resolve(host.dispose())).rejects.toThrow('disk unavailable');
+ });
+ it('does not let late refresh revive an explicitly closed sharedTask', async () => {
+ await host.open('session');
+ let finish!: (value: SharedTaskDetail) => void;
+ api.get.mockImplementationOnce(() => new Promise<SharedTaskDetail>((resolve) => { finish = resolve; }));
+ const refresh = host.refresh('sharedTask');
+ await vi.waitFor(() => expect(finish).toBeDefined());
+ const close = host.close('sharedTask');
+ finish(detail(2));
+ await expect(refresh).rejects.toThrow('closed');
+ await close;
+ expect(canRead()).toBe(false);
+ expect(records.get('sharedTask')?.terminal).toBe(true);
+ });
+ it('keeps a live sharedTask usable when a background server refresh fails', async () => {
+ await host.open('session');
+ api.get.mockRejectedValueOnce(new Error('offline'));
+ await expect(host.refresh('sharedTask')).rejects.toThrow('offline');
+ expect(canRead()).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskMediaAccess.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskMediaAccess.test.ts
new file mode 100644
index 0000000000..b0a4ae9aad
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskMediaAccess.test.ts
@@ -0,0 +1,64 @@
+import path from 'node:path';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+const deps = vi.hoisted(() => ({ read: vi.fn(), session: vi.fn(), realpath: vi.fn(), query: vi.fn() }));
+vi.mock('../../localDb/client/current.js', () => ({ getDbClient: () => ({ query: deps.query }) }));
+vi.mock('node:fs/promises', () => ({ realpath: deps.realpath }));
+vi.mock('../../cindy-media/blobStore.js', () => ({ parseBlobUrl: (url: string) => url === 'cindy-media://blobs/hash.png' ? { hash: 'hash' } : null }));
+vi.mock('../../cindy-media/ledger.js', () => ({ sessionCanRead: deps.read }));
+vi.mock('../../localDb/ipc/sessions.js', () => ({ getSessionFsSnapshot: deps.session }));
+import { assertSharedTaskMedia } from '../sharedTaskMediaAccess.js';
+import type { SharedTaskPeerCapture } from '../sharedTaskDispatch.js';
+let current = true;
+const capture: SharedTaskPeerCapture = {
+ author: { sharedTaskId: 'shared', sessionId: 'task', memberId: 'm', accountId: 'u', displayName: 'Guest' },
+ isCurrent: () => current, authorize: () => current,
+};
+beforeEach(() => {
+ vi.resetAllMocks(); current = true;
+ deps.realpath.mockImplementation(async (value: string) => path.resolve(value));
+ deps.session.mockResolvedValue({ workingDir: path.resolve('workspace'), remoteHostId: null });
+ deps.query.mockResolvedValue([]);
+});
+describe('shared task media access', () => {
+ it('allows legacy generated media only when its complete URL occurs in host-authored task history', async () => {
+ const url = 'xdt-video://art/clip.mp4';
+ deps.query.mockResolvedValue([{ content: JSON.stringify({ text: '[video](' + url + ')' }) }]);
+ await assertSharedTaskMedia(url, capture);
+ expect(deps.query.mock.calls[0][0]).toContain("role IN ('assistant', 'tool_use', 'tool_result')");
+ expect(deps.query.mock.calls[0][1]).toEqual(['task', url]);
+ deps.query.mockResolvedValue([{ content: url + '.other' }]);
+ await expect(assertSharedTaskMedia(url, capture)).rejects.toThrow('PERMISSION_DENIED');
+ deps.query.mockResolvedValue([]);
+ await expect(assertSharedTaskMedia(url, capture)).rejects.toThrow('PERMISSION_DENIED');
+ });
+ it('requires task provenance even for a known managed blob', async () => {
+ deps.read.mockResolvedValue(false);
+ await expect(assertSharedTaskMedia('cindy-media://blobs/hash.png', capture)).rejects.toThrow('PERMISSION_DENIED');
+ deps.read.mockResolvedValue(true);
+ await assertSharedTaskMedia('cindy-media://blobs/hash.png', capture);
+ expect(deps.read).toHaveBeenLastCalledWith('hash', 'task');
+ });
+ it('rechecks membership after asynchronous ledger reads', async () => {
+ deps.read.mockImplementation(async () => { current = false; return true; });
+ await expect(assertSharedTaskMedia('cindy-media://blobs/hash.png', capture)).rejects.toThrow('PERMISSION_DENIED');
+ });
+ it('permits task workdir media but rejects siblings and symlink escapes', async () => {
+ const url = (file: string) => 'xdt-file://local?path=' + encodeURIComponent(path.resolve(file));
+ await assertSharedTaskMedia(url('workspace/art.png'), capture);
+ await expect(assertSharedTaskMedia(url('other/private.png'), capture)).rejects.toThrow();
+ deps.realpath.mockImplementation(async (file: string) => file.endsWith('link.png') ? path.resolve('other/private.png') : path.resolve(file));
+ await expect(assertSharedTaskMedia(url('workspace/link.png'), capture)).rejects.toThrow();
+ });
+ it('requires exact SSH task and host provenance before materialization', async () => {
+ deps.session.mockResolvedValue({ workingDir: '/work', remoteHostId: 'ssh' });
+ const url = 'xdt-file://local?path=/work/a.png&sessionId=task&remoteHostId=ssh&workdir=/work';
+ await assertSharedTaskMedia(url, capture);
+ await expect(assertSharedTaskMedia(url.replace('sessionId=task', 'sessionId=other'), capture)).rejects.toThrow();
+ await expect(assertSharedTaskMedia('xdt-file://local?path=/work/a.png', capture)).rejects.toThrow();
+ expect(deps.realpath).not.toHaveBeenCalled();
+ });
+ it('keeps legacy task image history scoped to its actual session', async () => {
+ await assertSharedTaskMedia('xdt-image://task/photo.png', capture);
+ await expect(assertSharedTaskMedia('xdt-image://other/photo.png', capture)).rejects.toThrow();
+ });
+});
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts
new file mode 100644
index 0000000000..e77e546e1f
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts
@@ -0,0 +1,130 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { DL_SUBSCRIBE_CHANNEL } from '@cindy/device-link';
+
+vi.mock('electron', () => ({
+ app: { getAppPath: () => '/tmp/cindy-test/app', getPath: () => '/tmp/cindy-test', getVersion: () => 'test' },
+ powerSaveBlocker: { start: () => 0, stop: () => {}, isStarted: () => false },
+ nativeImage: { createFromPath: () => ({ isEmpty: () => true }) },
+}));
+vi.mock('../settings-store', () => ({
+ readDeviceLinkSettings: () => ({ remoteControlEnabled: true, revokedControllers: [] }),
+}));
+
+import { __testing } from '../dispatch';
+import * as subscriptions from '../subscriptions';
+import { setSharedTaskDispatchHost } from '../sharedTaskDispatch';
+import type { SharedTaskHost } from '../sharedTaskHost';
+
+const guestA = 'shared-task~sharedTask-a~guest~member-a~device-a';
+const guestB = 'shared-task~sharedTask-b~guest~member-b~device-b';
+const grants = new Map<string, string>();
+const metadata = [
+ ['local-db:sessions:created', { sessionId: 'task-a' }],
+ ['local-db:sessions:patched', { sessionId: 'task-a', patch: { title: 'Updated task' } }],
+ ['local-db:sessions:activity', { sessionId: 'task-a', phase: 'completed', compactDetail: 'Done' }],
+ ['local-db:session:error-persisted', { sessionId: 'task-a', clientId: 'error-row' }],
+ ['usage:session-spend-changed', { sessionId: 'task-a', totalCost: 1 }],
+ ['usage:session-tokens-changed', { sessionId: 'task-a', totalTokens: 100 }],
+] as const;
+
+function client() {
+ return {
+ getStatus: vi.fn(() => 'online'), getReliableSendQueueDepth: vi.fn(() => 0),
+ canSendPush: vi.fn(() => true), sendPush: vi.fn(),
+ sendInvokeResult: vi.fn(), sendLinkAccept: vi.fn(), closeLink: vi.fn(),
+ };
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ __testing.reset();
+ grants.clear();
+ grants.set(guestA, 'task-a'); grants.set(guestB, 'task-b');
+ setSharedTaskDispatchHost({ capturePeer(source: string) {
+ const sessionId = grants.get(source);
+ if (!sessionId) return null;
+ const current = () => grants.get(source) === sessionId;
+ return {
+ author: { sharedTaskId: 'sharedTask-a', sessionId, memberId: 'member-a', accountId: 'guest', displayName: 'Guest' },
+ isCurrent: current, authorize: current,
+ };
+ } } as unknown as SharedTaskHost);
+});
+afterEach(() => {
+ __testing.reset();
+ setSharedTaskDispatchHost(null);
+ vi.useRealTimers();
+});
+
+describe('shared task metadata uses only its authorized task subscription', () => {
+ it.each(metadata)('delivers %s to the matching guest and ordinary list subscriber only', async (channel, payload) => {
+ const transport = client();
+ __testing.setActiveClient(transport as never);
+ subscriptions.subscribe(guestA, ['session:task-a']);
+ subscriptions.subscribe(guestB, ['session:task-b']);
+ subscriptions.subscribe('own-list', ['sessions']);
+ subscriptions.subscribe('own-task', ['session:task-a']);
+ __testing.forwardPush(channel, payload);
+ await vi.advanceTimersByTimeAsync(300);
+ expect(transport.sendPush.mock.calls.map((call) => call[0]).sort()).toEqual([guestA, 'own-list'].sort());
+ expect(transport.sendPush.mock.calls.every((call) => call[1] === channel && call[2].sessionId === 'task-a')).toBe(true);
+ });
+
+ it('keeps offline metadata under the task topic and replays it after that topic is restored', async () => {
+ const transport = client();
+ __testing.setActiveClient(transport as never);
+ subscriptions.subscribe(guestA, ['session:task-a']);
+ subscriptions.subscribe(guestB, ['session:task-b']);
+ subscriptions.clearController(guestA);
+ for (const [channel, payload] of metadata) __testing.forwardPush(channel, payload);
+ expect(transport.sendPush).not.toHaveBeenCalled();
+ expect(__testing.queuedPushesFor(guestA).map((item) => item.topic)).toEqual(metadata.map(() => 'session:task-a'));
+ expect(__testing.queuedPushesFor(guestB)).toEqual([]);
+ const result = __testing.handleSubscriptionFrame(guestA, {
+ channel: DL_SUBSCRIBE_CHANNEL, args: [{ topics: ['session:task-a'] }],
+ });
+ expect(result.ok).toBe(true);
+ await vi.advanceTimersByTimeAsync(300);
+ expect(transport.sendPush.mock.calls.filter((call) => metadata.some(([channel]) => channel === call[1]))).toHaveLength(metadata.length);
+ expect(__testing.queuedPushesFor(guestA)).toEqual([]);
+ });
+
+ it('queues metadata while the relay is offline even if the guest subscription remains active', () => {
+ const transport = client();
+ transport.getStatus.mockReturnValue('reconnecting');
+ __testing.setActiveClient(transport as never);
+ subscriptions.subscribe(guestA, ['session:task-a']);
+ __testing.forwardPush(...metadata[1]);
+ expect(transport.sendPush).not.toHaveBeenCalled();
+ expect(__testing.queuedPushesFor(guestA)).toEqual([expect.objectContaining({ topic: 'session:task-a', channel: metadata[1][0] })]);
+ });
+
+ it.each(['revoke', 'unsubscribe'] as const)('does not deliver deferred patch/activity after %s', async (boundary) => {
+ const transport = client();
+ transport.getReliableSendQueueDepth.mockReturnValue(100);
+ __testing.setActiveClient(transport as never);
+ subscriptions.subscribe(guestA, ['session:task-a']);
+ __testing.forwardPush(...metadata[1]);
+ __testing.forwardPush(...metadata[2]);
+ expect(transport.sendPush).not.toHaveBeenCalled();
+ if (boundary === 'revoke') grants.delete(guestA);
+ else subscriptions.unsubscribe(guestA, ['session:task-a']);
+ transport.getReliableSendQueueDepth.mockReturnValue(0);
+ await vi.advanceTimersByTimeAsync(600);
+ expect(transport.sendPush).not.toHaveBeenCalled();
+ });
+
+ it('does not grant global metadata, another task, or a revoked remembered subscriber', () => {
+ const transport = client();
+ __testing.setActiveClient(transport as never);
+ subscriptions.subscribe(guestA, ['session:task-a']);
+ __testing.forwardPush('maker:provider:changed', { sessionId: 'task-a' });
+ __testing.forwardPush('local-db:sessions:patched', { sessionId: 'other-task', patch: { title: 'Private' } });
+ __testing.forwardPush('local-db:sessions:activity', { phase: 'completed' });
+ subscriptions.clearController(guestA);
+ grants.delete(guestA);
+ for (const [channel, payload] of metadata) __testing.forwardPush(channel, payload);
+ expect(transport.sendPush).not.toHaveBeenCalled();
+ expect(__testing.queuedPushesFor(guestA)).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.ts
new file mode 100644
index 0000000000..23acedf77b
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.ts
@@ -0,0 +1,172 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+type HostRecord = {
+ options: { creationState: unknown; isCurrent(): boolean; revoke(sharedTaskId: string, memberId?: string): void };
+ restore: ReturnType<typeof vi.fn>;
+ dispose: ReturnType<typeof vi.fn>;
+ closeLocallyForBoundary: ReturnType<typeof vi.fn>;
+};
+const state = vi.hoisted(() => ({
+ accountId: 'owner', region: 'global', authenticated: true,
+ session: { mode: 'cloud', dataOwnerId: 'owner', generation: 1 }, boundary: false,
+ db: { client: { query: vi.fn() }, clientEpoch: 1 },
+ hosts: [] as HostRecord[], dispatch: vi.fn(),
+ captureClose: vi.fn(), close: vi.fn(),
+}));
+vi.mock('../../localDb/client/current.js', () => ({ getCurrentDbClientSnapshot: () => state.db }));
+vi.mock('../../localDb/sharedTasks.js', () => ({ createSharedTaskJournal: () => ({}) }));
+vi.mock('../../appSessionState.js', () => ({
+ activeOwnerScopeKey: () => [state.session.mode, state.session.dataOwnerId, state.session.generation].join(':'),
+ getActiveAppSession: () => ({ ...state.session }), isAppSessionBoundaryPending: () => state.boundary,
+}));
+vi.mock('../../authManager.js', () => ({
+ getAuthState: () => ({ isAuthenticated: state.authenticated }), getCurrentUserId: () => state.accountId,
+ getDeviceId: () => 'host-device', getActiveAuthRealm: () => state.region,
+}));
+vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: vi.fn(), debug: vi.fn() }) }));
+vi.mock('../sharedTaskApi.js', () => ({ sharedTaskApi: {}, captureSharedTaskBoundaryClose: state.captureClose }));
+vi.mock('../sharedTaskDispatch.js', () => ({ setSharedTaskDispatchHost: state.dispatch }));
+vi.mock('../sharedTaskHost.js', () => ({
+ SharedTaskHost: class {
+ restore = vi.fn(async () => undefined);
+ closeLocallyForBoundary = vi.fn(async () => ['sharedTask-a', 'sharedTask-b']);
+ // The real Host disposes each existing grant through this callback.
+ dispose = vi.fn(async () => { this.options.revoke('sharedTask-a'); });
+ constructor(readonly options: HostRecord['options']) { state.hosts.push(this); }
+ },
+}));
+
+import { closeSharedTasksBeforeLogout, requireSharedTaskHost, startSharedTaskRuntime, stopSharedTaskRuntime } from '../sharedTaskRuntime';
+
+function start() {
+ const client = { hasServerCapability: () => true, getStatus: () => 'online', start: vi.fn(), stop: vi.fn(), revoke: vi.fn() };
+ startSharedTaskRuntime({ client: client as never, revoke: client.revoke, changed: vi.fn() });
+ return client;
+}
+
+beforeEach(async () => {
+ await stopSharedTaskRuntime();
+ vi.useFakeTimers();
+ state.accountId = 'owner'; state.region = 'global'; state.authenticated = true; state.boundary = false;
+ state.session = { mode: 'cloud', dataOwnerId: 'owner', generation: 1 };
+ state.db = { client: { query: vi.fn() }, clientEpoch: 1 };
+ state.hosts.length = 0; state.dispatch.mockClear();
+ state.captureClose.mockReset().mockReturnValue(state.close);
+ state.close.mockReset().mockResolvedValue({ status: 'closed' });
+});
+afterEach(async () => {
+ await stopSharedTaskRuntime();
+ vi.useRealTimers();
+});
+
+describe('shared runtime stable owner recommit', () => {
+ it('preserves creation cleanup across same-profile rebind but not database replacement', () => {
+ start();
+ const original = state.hosts[0].options.creationState;
+ state.session.generation++;
+ requireSharedTaskHost();
+ expect(state.hosts[1].options.creationState).toBe(original);
+ state.db = { client: { query: vi.fn() }, clientEpoch: 2 };
+ start();
+ expect(state.hosts[2].options.creationState).not.toBe(original);
+ });
+ it('persists the outgoing journal before closing all shares with captured old identity', async () => {
+ start();
+ const outgoing = state.hosts[0];
+ let finish!: () => void;
+ outgoing.closeLocallyForBoundary.mockImplementation(() => new Promise<string[]>((resolve) => {
+ finish = () => resolve(['sharedTask-a', 'sharedTask-b']);
+ }));
+ state.boundary = true;
+ const closing = closeSharedTasksBeforeLogout();
+ expect(state.captureClose).toHaveBeenCalledExactlyOnceWith('owner', 'global');
+ expect(state.close).not.toHaveBeenCalled();
+ // Another binding cannot change which host/journal this cleanup stops.
+ finish();
+ await closing;
+ expect(outgoing.dispose).toHaveBeenCalledOnce();
+ expect(state.close.mock.calls).toEqual([['sharedTask-a'], ['sharedTask-b']]);
+ });
+ it('keeps durable cleanup when offline or credentials are already cleared', async () => {
+ start();
+ state.close.mockRejectedValue(new Error('offline'));
+ await expect(closeSharedTasksBeforeLogout()).resolves.toBeUndefined();
+ expect(state.hosts[0].closeLocallyForBoundary).toHaveBeenCalledOnce();
+ state.captureClose.mockReturnValue(null);
+ state.close.mockClear();
+ await closeSharedTasksBeforeLogout();
+ expect(state.close).not.toHaveBeenCalled();
+ });
+ it('does not report logout complete or send closure before the journal is durable', async () => {
+ start();
+ state.hosts[0].closeLocallyForBoundary.mockRejectedValue(new Error('disk failed'));
+ await expect(closeSharedTasksBeforeLogout()).rejects.toThrow('disk failed');
+ expect(state.close).not.toHaveBeenCalled();
+ expect(state.hosts[0].dispose).not.toHaveBeenCalled();
+ });
+ it('rebinds on the existing refresh tick without restarting relay or reviving old captures', async () => {
+ const relay = start();
+ const original = state.hosts[0];
+ const oldCapture = original.options.isCurrent;
+ expect(oldCapture()).toBe(true);
+ state.session.generation++;
+ expect(oldCapture()).toBe(false);
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(state.hosts).toHaveLength(2);
+ expect(original.dispose).toHaveBeenCalledOnce();
+ expect(state.hosts[1].restore).toHaveBeenCalledOnce();
+ expect(requireSharedTaskHost()).toBe(state.hosts[1]);
+ expect(oldCapture()).toBe(false);
+ expect(relay.start).not.toHaveBeenCalled();
+ expect(relay.stop).not.toHaveBeenCalled();
+ expect(relay.revoke).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(state.hosts).toHaveLength(2);
+ });
+
+ it('rebinds on demand before the next tick and restores authority into a new Host', () => {
+ start();
+ const original = requireSharedTaskHost();
+ state.session.generation++;
+ const replacement = requireSharedTaskHost();
+ expect(replacement).not.toBe(original);
+ expect(replacement).toBe(state.hosts[1]);
+ expect(state.hosts[1].restore).toHaveBeenCalledOnce();
+ });
+
+ it.each(['boundary', 'account', 'stable-owner', 'region', 'database', 'database-epoch', 'signed-out', 'local'])(
+ 'never rebinds across an unresolved %s boundary', async (change) => {
+ start(); state.session.generation++;
+ if (change === 'boundary') state.boundary = true;
+ if (change === 'account') state.accountId = 'other';
+ if (change === 'stable-owner') state.session.dataOwnerId = 'other';
+ if (change === 'region') state.region = 'cn';
+ if (change === 'database') state.db = { ...state.db, client: { query: vi.fn() } };
+ if (change === 'database-epoch') state.db = { ...state.db, clientEpoch: state.db.clientEpoch + 1 };
+ if (change === 'signed-out') state.authenticated = false;
+ if (change === 'local') state.session.mode = 'local';
+ expect(() => requireSharedTaskHost()).toThrow('PRECONDITION_FAILED');
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(state.hosts).toHaveLength(1);
+ },
+ );
+
+ it('waits for a stable same-owner boundary to finish, then rebinds', async () => {
+ start(); state.session.generation++; state.boundary = true;
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(state.hosts).toHaveLength(1);
+ state.boundary = false;
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(state.hosts).toHaveLength(2);
+ });
+
+ it('never reacquires a stopped relay owner on demand or by timer', async () => {
+ const relay = start();
+ await stopSharedTaskRuntime();
+ expect(relay.revoke).toHaveBeenCalledWith('sharedTask-a', undefined);
+ state.session.generation++;
+ expect(() => requireSharedTaskHost()).toThrow('PRECONDITION_FAILED');
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(state.hosts).toHaveLength(1);
+ });
+});
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskTransientAccess.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskTransientAccess.test.ts
new file mode 100644
index 0000000000..5c89081442
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskTransientAccess.test.ts
@@ -0,0 +1,134 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { PROTOCOL_VERSION, SHARED_TASK_CAPABILITY, type SharedTaskDetail } from '@cindy/device-link';
+
+vi.mock('electron', () => ({
+ app: { getAppPath: () => '/tmp/cindy-test/app', getPath: () => '/tmp/cindy-test', getVersion: () => 'test' },
+ powerSaveBlocker: { start: () => 0, stop: () => {}, isStarted: () => false },
+ nativeImage: { createFromPath: () => ({ isEmpty: () => true }) },
+}));
+vi.mock('../settings-store', () => ({
+ readDeviceLinkSettings: () => ({ remoteControlEnabled: true, revokedControllers: [] }),
+}));
+
+import { __testing, runInvoke, wireInboundDispatch } from '../dispatch';
+import { __testing as registry } from '../invoke-registry';
+import { SharedTaskHost } from '../sharedTaskHost';
+import { setSharedTaskDispatchHost } from '../sharedTaskDispatch';
+import type { SharedTaskJournalEntry } from '../../localDb/sharedTasks';
+
+const peer = 'shared-task~sharedTask~guest~member~phone';
+const read = { channel: 'local-db:messages:list', args: ['task'] };
+const subscribe = { channel: 'device-link:subscribe', args: [{ topics: ['session:task'] }] };
+let detail: SharedTaskDetail;
+let host: SharedTaskHost;
+const api = { create: vi.fn(), list: vi.fn(), get: vi.fn(), invite: vi.fn(), join: vi.fn(), remove: vi.fn(), leave: vi.fn(), close: vi.fn() };
+
+function client() {
+ return {
+ getStatus: vi.fn(() => 'online'), getConnectionEpoch: vi.fn(() => 1), getPeerLinkGeneration: vi.fn(() => 1),
+ getReliableSendQueueDepth: vi.fn(() => 0), canSendPush: vi.fn(() => true), sendPush: vi.fn(),
+ sendInvokeResult: vi.fn(), sendLinkAccept: vi.fn(), closeLink: vi.fn(), onFrame: vi.fn(),
+ };
+}
+
+beforeEach(async () => {
+ __testing.reset();
+ registry.reset();
+ for (const fn of Object.values(api)) fn.mockReset();
+ detail = {
+ sharedTaskId: 'sharedTask', sessionId: 'task', ownerAccountId: 'owner', hostDeviceId: 'desktop',
+ revision: 1, status: 'active', title: 'Task',
+ guests: [{ memberId: 'member', accountId: 'guest', deviceIds: ['phone'], version: 1 }], memberLabels: [],
+ };
+ api.get.mockImplementation(async () => structuredClone(detail));
+ let entry: SharedTaskJournalEntry | undefined;
+ host = new SharedTaskHost({
+ api, ownerAccountId: 'owner', hostDeviceId: 'desktop', isCurrent: () => true,
+ readSession: async (id) => ({ id, title: 'Task', status: 'active' }), revoke: vi.fn(), changed: vi.fn(),
+ journal: {
+ latest: async () => entry ? [entry] : [],
+ recordAuthority: async (snapshot) => {
+ entry = { sharedTaskId: 'sharedTask', sessionId: 'task', terminal: snapshot.status === 'closed', snapshot };
+ return true;
+ },
+ close: async () => { entry = { sharedTaskId: 'sharedTask', sessionId: 'task', terminal: true, snapshot: null }; },
+ },
+ });
+ setSharedTaskDispatchHost(host);
+ await host.refresh('sharedTask');
+});
+afterEach(() => {
+ __testing.reset(); registry.reset(); setSharedTaskDispatchHost(null);
+});
+
+describe('shared task temporary authority fences preserve membership', () => {
+ it.each(['suspended', 'revoked'] as const)('gates admission, subscription, link-open and final send while %s', async (state) => {
+ let rejectRemove!: (error: Error) => void;
+ let removal: Promise<void> | undefined;
+ if (state === 'suspended') {
+ api.remove.mockImplementation(() => new Promise<void>((_resolve, reject) => { rejectRemove = reject; }));
+ removal = host.remove('sharedTask', 'member');
+ await vi.waitFor(() => expect(rejectRemove).toBeTypeOf('function'));
+ } else {
+ detail = { ...detail, revision: 2, guests: [] };
+ await host.refresh('sharedTask');
+ }
+ const code = state === 'suspended' ? 'NOT_CONNECTED' : 'ACCESS_REVOKED';
+ expect(host.peerStatus(peer)).toBe(state === 'suspended' ? 'unavailable' : 'revoked');
+ expect(host.capturePeer(peer)).toBeNull();
+ expect(__testing.handleSubscriptionFrame(peer, subscribe)).toMatchObject({ ok: false, error: { code } });
+ const transport = client();
+ __testing.setActiveClient(transport as never);
+ __testing.handleLinkOpen(transport as never, peer, 'open', {
+ controllerName: 'Guest', protocolVersion: PROTOCOL_VERSION, appVersion: 'test', capabilities: [SHARED_TASK_CAPABILITY],
+ }, 0, true);
+ expect(transport.closeLink).toHaveBeenCalledWith(peer, state === 'suspended' ? 'transport-timeout' : 'revoked', 'inbound');
+ expect(transport.sendLinkAccept).not.toHaveBeenCalled();
+ __testing.sendInvokeResultSafe(transport as never, peer, 'late', { ok: true, result: 'private data' }, read.channel, read.args);
+ expect(transport.sendInvokeResult).toHaveBeenLastCalledWith(peer, 'late', expect.objectContaining({ ok: false, error: expect.objectContaining({ code }) }));
+ const handler = vi.fn(() => []);
+ registry.register(read.channel, handler);
+ wireInboundDispatch(transport as never);
+ transport.onFrame.mock.calls[0][0]({ v: PROTOCOL_VERSION, kind: 'invoke', src: peer, id: 'new', payload: read });
+ await vi.waitFor(() => expect(transport.sendInvokeResult).toHaveBeenCalledWith(peer, 'new', expect.objectContaining({ ok: false, error: expect.objectContaining({ code }) })));
+ expect(handler).not.toHaveBeenCalled();
+ if (removal) {
+ const failed = expect(removal).rejects.toThrow('offline');
+ rejectRemove(new Error('offline'));
+ await failed;
+ expect(host.peerStatus(peer)).toBe('available');
+ expect(__testing.handleSubscriptionFrame(peer, subscribe).ok).toBe(true);
+ expect((await runInvoke(peer, read)).ok).toBe(true);
+ }
+ });
+
+ it.each(['device-added', 'member-removed'] as const)('fences an in-flight read after %s without confusing stale capture with revocation', async (change) => {
+ let finish!: (value: unknown) => void;
+ registry.register(read.channel, () => new Promise((resolve) => { finish = resolve; }));
+ const result = runInvoke(peer, read);
+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'));
+ detail = { ...detail, revision: 2, guests: change === 'device-added'
+ ? [{ ...detail.guests[0], version: 2, deviceIds: ['phone', 'second-phone'] }] : [] };
+ await host.refresh('sharedTask');
+ finish([{ content: 'private data' }]);
+ expect(await result).toMatchObject({ ok: false, error: { code: change === 'device-added' ? 'NOT_CONNECTED' : 'ACCESS_REVOKED' } });
+ if (change === 'device-added') {
+ expect(host.capturePeer(peer)?.isCurrent()).toBe(true);
+ registry.register(read.channel, () => []);
+ expect((await runInvoke(peer, read)).ok).toBe(true);
+ }
+ });
+
+ it('denies an out-of-scope request without revoking an otherwise valid member', async () => {
+ expect(await runInvoke(peer, { ...read, args: ['another-task'] }))
+ .toMatchObject({ ok: false, error: { code: 'IPC_ERROR', message: expect.stringContaining('PERMISSION_DENIED') } });
+ expect(host.peerStatus(peer)).toBe('available');
+ expect(__testing.handleSubscriptionFrame(peer, subscribe).ok).toBe(true);
+ });
+
+ it('treats unrestored or replaced host authority as unavailable rather than revoked', async () => {
+ expect(host.peerStatus('shared-task~unknown~guest~member~phone')).toBe('unavailable');
+ setSharedTaskDispatchHost(null);
+ expect(await runInvoke(peer, read)).toMatchObject({ ok: false, error: { code: 'NOT_CONNECTED' } });
+ });
+});
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index f4508db79c..3ed87c2fc1 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -95,9 +95,12 @@ import {
hasRemoteBotSessionLookup, setRemoteBotSessionLookup,
} from './remoteBotSessionBoundary.js';
import { getControllerPlatform } from './controllerPlatform';
-import { runDeviceLinkInvokeContext } from './invoke-context';
+import { getDeviceLinkInvokeContext, runDeviceLinkInvokeContext } from './invoke-context';
+import { isSharedTaskPeer, SHARED_TASK_CAPABILITY } from '@cindy/device-link';
+import { captureSharedTaskPeer, captureSharedTaskPush, assertSharedTaskInvoke, sharedTaskMetadataTopic, sharedTaskAccessFailure } from './sharedTaskDispatch.js';
import { runAsBackgroundDbRpc } from '../localDb/client/rpcAdmission.js';
import { fetchLocalMediaToOss } from './mediaFetch';
+import { refreshSharedTaskPeer } from './sharedTaskDispatch.js';
import { transcribeRemoteVoiceInput } from './voiceTranscribe';
import { readTelegramRemoteStatus, setTelegramRemoteOnline } from './telegramRemoteControl';
import { adviseAndRecordVoiceInputDictionaryLearning } from '../voice-input/index.js';
@@ -184,6 +187,10 @@ function sendBotCheckedPush(
dst: string, channel: string, payload: unknown, send: (payload: unknown) => void,
failed: (error: unknown) => void,
): void | Promise<void> {
+ const sharedTaskFence = captureSharedTaskPush(dst, channel, payload);
+ if (!sharedTaskFence) return;
+ const deliver = send;
+ send = (projected) => { if (sharedTaskFence()) deliver(projected); };
if (!hasRemoteBotSessionLookup()) { send(payload); return; }
let size: number;
try { size = byteLength(JSON.stringify(payload)); } catch (error) { failed(error); return; }
@@ -925,7 +932,9 @@ function shouldAcquireRemoteInvokeBusyLease(
payload: InvokePayload | undefined,
): boolean {
if (!payload || typeof payload.channel !== 'string') return false;
- if (!readDeviceLinkSettings().remoteControlEnabled) return false;
+ if (isSharedTaskPeer(src)) {
+ if (!captureSharedTaskPeer(src)?.isCurrent()) return false;
+ } else if (!readDeviceLinkSettings().remoteControlEnabled) return false;
if (isControllerRevoked(src)) return false;
if (!REMOTE_INVOKE_ALLOWLIST.has(payload.channel)) return false;
if (
@@ -1546,6 +1555,7 @@ function stageSessionPatch(dst: string, payload: unknown, ownerStamp?: PushOwner
const patch = payload as SessionPatch | null;
if (!patch || typeof patch.sessionId !== 'string' || !patch.sessionId
|| !patch.patch || typeof patch.patch !== 'object' || Array.isArray(patch.patch)) return;
+ const subscriptionTopic = isSharedTaskPeer(dst) ? sharedTaskMetadataTopic('local-db:sessions:patched', patch)! : 'sessions';
let stage = sessionPatchStages.get(dst);
if (stage && !makerEventBatchOwnerStampEquals(stage.ownerStamp, ownerStamp)) {
clearSessionPatchStage(dst);
@@ -1556,7 +1566,7 @@ function stageSessionPatch(dst: string, payload: unknown, ownerStamp?: PushOwner
stage = new SessionPatchStage(ownerStamp,
() => {
if (!broadcastTap.isDataOwnerBroadcastScopeCurrent(owner)
- || !subscriptions.getControllersForTopic('sessions').includes(dst)) {
+ || !subscriptions.getControllersForTopic(subscriptionTopic).includes(dst)) {
clearSessionPatchStage(dst);
return false;
}
@@ -1568,7 +1578,7 @@ function stageSessionPatch(dst: string, payload: unknown, ownerStamp?: PushOwner
let failure: unknown;
await sendBotCheckedPush(dst, 'local-db:sessions:patched', item, (projected) => {
if (!isCurrent() || !broadcastTap.isDataOwnerBroadcastScopeCurrent(owner)
- || !subscriptions.getControllersForTopic('sessions').includes(dst)) return;
+ || !subscriptions.getControllersForTopic(subscriptionTopic).includes(dst)) return;
if (!activeClient || activeClient.canSendPush?.(dst) === false) {
throw new DeviceLinkError('NOT_CONNECTED', 'peer mirror paused');
}
@@ -1636,6 +1646,10 @@ function drainSessionActivityStage(dst: string, stage: SessionActivityStage): vo
| undefined;
if (!next) return;
const [key, item] = next;
+ if (isSharedTaskPeer(dst) && !subscriptions.getControllersForTopic(`session:${key}`).includes(dst)) {
+ stage.queue.delete(key);
+ continue;
+ }
try {
let backpressured = false;
sendBotCheckedPush(dst, SESSION_ACTIVITY_CHANNEL, item.payload, (projected) => {
@@ -1761,7 +1775,16 @@ function forwardPush(channel: string, payload: unknown, ownerStamp?: PushOwnerSt
if (channel === MAKER_PUSH.INTERACTION_DISMISSED) {
remotePayload = projectInteractionDismissedForRemote(remotePayload);
}
- const dsts = subscriptions.getControllersForTopic(topic);
+ const sharedTaskTopic = sharedTaskMetadataTopic(channel, remotePayload);
+ const targetsFor = (known: boolean): string[] => {
+ const lookup = known ? subscriptions.getKnownControllersForTopic : subscriptions.getControllersForTopic;
+ const ordinary = lookup(topic);
+ if (!sharedTaskTopic) return ordinary;
+ const shared = lookup(sharedTaskTopic).filter((dst) => isSharedTaskPeer(dst)
+ && captureSharedTaskPush(dst, channel, remotePayload)?.() === true);
+ return [...new Set([...ordinary, ...shared])];
+ };
+ const dsts = targetsFor(false);
// The active registry describes peer topic intent, not whether this host can
// currently write to the relay. During host-side reconnects sendPush is a
// silent no-op, so route queueable pushes through the offline backlog instead.
@@ -1800,16 +1823,16 @@ function forwardPush(channel: string, payload: unknown, ownerStamp?: PushOwnerSt
const historySessionId = readPushSessionId(remotePayload);
const deferred = historySessionId !== null && isDeferredHistoryPush(channel, remotePayload,
(id) => readHistoryToolName(historySessionId, id));
- const offlineTargets = subscriptions
- .getKnownControllersForTopic(topic)
+ const offlineTargets = targetsFor(true)
.filter((dst) => !liveTargets.includes(dst));
for (const dst of offlineTargets) {
if (deferred && historySessionId && subscriptions.hasHistoryView(dst, historySessionId)) continue;
- if (OFFLINE_QUEUEABLE_PUSH_CHANNELS.has(channel)) {
+ const sharedMetadata = isSharedTaskPeer(dst) && sharedTaskTopic !== null;
+ if (OFFLINE_QUEUEABLE_PUSH_CHANNELS.has(channel) || sharedMetadata) {
offlinePushQueue.enqueue(dst, {
channel,
payload: payloadFor(dst),
- topic,
+ topic: sharedMetadata ? sharedTaskTopic : topic,
...(ownerStamp ? { ownerStamp } : {}),
});
}
@@ -1912,7 +1935,8 @@ function sendPushBestEffortAuthorized(
const sessionId = readPushSessionId(payload);
const markForRecovery = () => {
if (sessionId && channel !== SESSION_SYNC_CHANNEL
- && topicForPush(channel, payload) === `session:${sessionId}`) {
+ && (topicForPush(channel, payload) === `session:${sessionId}`
+ || isSharedTaskPeer(dst) && sharedTaskMetadataTopic(channel, payload) === `session:${sessionId}`)) {
stageSessionSync(dst, sessionId, channel !== 'maker:event' || !isNonFinalTextPush(payload));
}
};
@@ -2293,11 +2317,13 @@ function isControllerRevoked(deviceId: string): boolean {
*/
const LINK_ACCEPT_RETRY_DELAYS_MS: readonly number[] = [500, 1_000, 2_000];
const linkAcceptRetryTimers = new Map<string, ReturnType<typeof setTimeout>>();
+const pendingSharedTaskOpens = new Map<string, object>();
/** 已撤权控制端反复 open 时,closeLink 与 warn 的最小间隔。 */
const REVOKED_LINK_OPEN_REJECT_INTERVAL_MS = 30_000;
const revokedLinkOpenRejectAt = new Map<string, number>();
function cancelLinkAcceptRetry(src: string): void {
+ pendingSharedTaskOpens.delete(src);
const timer = linkAcceptRetryTimers.get(src);
if (!timer) return;
clearTimeout(timer);
@@ -2305,6 +2331,7 @@ function cancelLinkAcceptRetry(src: string): void {
}
function cancelAllLinkAcceptRetries(): void {
+ pendingSharedTaskOpens.clear();
for (const src of [...linkAcceptRetryTimers.keys()]) cancelLinkAcceptRetry(src);
}
@@ -2340,9 +2367,57 @@ function handleLinkOpen(
requestId: string,
payload: LinkOpenPayload | undefined,
acceptAttempt = 0,
+ authorityReady = false,
): void {
// 同 src 的新 link-open / 本轮执行顶掉遗留的 accept 重试(requestId 已过时)
cancelLinkAcceptRetry(src);
+ // Cross-account logical peers never enter the same-account legacy wildcard.
+ if (isSharedTaskPeer(src)) {
+ if (!authorityReady) {
+ const attempt = {};
+ const epoch = client.getConnectionEpoch();
+ pendingSharedTaskOpens.set(src, attempt);
+ const current = () => pendingSharedTaskOpens.get(src) === attempt && activeClient === client &&
+ client.getConnectionEpoch() === epoch && client.getStatus() === 'online';
+ void refreshSharedTaskPeer(src).then(() => {
+ if (current()) {
+ handleLinkOpen(client, src, requestId, payload, acceptAttempt, true);
+ }
+ }).catch(() => {
+ // Authority fetch failure is transient, not a permanent user revocation.
+ if (current()) {
+ pendingSharedTaskOpens.delete(src);
+ client.closeLink(src, 'transport-timeout', 'inbound');
+ }
+ });
+ return;
+ }
+ const sharedTask = captureSharedTaskPeer(src);
+ if (!sharedTask) {
+ const failure = sharedTaskAccessFailure(src);
+ client.closeLink(src, !failure.ok && failure.error.code === 'ACCESS_REVOKED' ? 'revoked' : 'transport-timeout', 'inbound');
+ return;
+ }
+ if (!sanitizeControllerCapabilities(payload?.capabilities).includes(SHARED_TASK_CAPABILITY)) {
+ client.closeLink(src, 'revoked', 'inbound');
+ return;
+ }
+ try {
+ client.sendLinkAccept(src, requestId, {
+ appVersion: app.getVersion(), allowlistHash: computeAllowlistHash(),
+ capabilities: [DEVICE_LINK_CAPABILITY_HISTORY_VIEW_V1, SHARED_TASK_CAPABILITY],
+ });
+ } catch {
+ scheduleLinkAcceptRetry(client, src, requestId, payload, acceptAttempt + 1);
+ return;
+ }
+ markControllerLinkActive(client, src);
+ acceptedLinkControllers.add(src);
+ topicSubscriptionControllers.add(src);
+ subscriptions.updateControllerMetadata(src, sharedTask.author.displayName, sanitizeControllerCapabilities(payload?.capabilities));
+ flushRemoteInvokeResultOutbox(src);
+ return;
+ }
// 第二道开关校验(server 已是第一道)
if (!readDeviceLinkSettings().remoteControlEnabled) {
// server 正常不会转发到这里;真到了说明状态不一致,静默不 accept
@@ -2688,6 +2763,7 @@ function settleRemoteInvokeWithOrphanDeadline(
}
function currentRemoteInvokeAdmissionFailure(src: string): InvokeResultPayload | null {
+ if (isSharedTaskPeer(src)) return captureSharedTaskPeer(src) ? null : sharedTaskAccessFailure(src);
if (!readDeviceLinkSettings().remoteControlEnabled) {
return { ok: false, error: { code: 'REMOTE_DISABLED', message: 'remote control disabled' } };
}
@@ -2954,6 +3030,15 @@ function trySendInvokeResult(
args?: unknown[],
logFailure = true,
): { sent: true; result: InvokeResultPayload } | { sent: false; result: InvokeResultPayload } {
+ if (isSharedTaskPeer(src)) {
+ const sharedTask = captureSharedTaskPeer(src);
+ try {
+ if (!sharedTask || !channel) throw new Error('SharedTask unavailable');
+ assertSharedTaskInvoke(sharedTask, { channel, args: args ?? [] }, undefined, 'result');
+ } catch {
+ result = sharedTaskAccessFailure(src, sharedTask);
+ }
+ }
let candidate = result;
try {
client.sendInvokeResult(src, requestId, candidate);
@@ -3470,8 +3555,17 @@ function isRemoteSubscriptionTopic(value: unknown): value is Topic {
}
function handleSubscriptionFrame(src: string, payload: InvokePayload): InvokeResultPayload {
+ if (isSharedTaskPeer(src)) {
+ const sharedTask = captureSharedTaskPeer(src);
+ try {
+ if (!sharedTask) throw new Error('SharedTask unavailable');
+ assertSharedTaskInvoke(sharedTask, payload);
+ } catch {
+ return sharedTaskAccessFailure(src, sharedTask);
+ }
+ }
// 被控开关(server 已 gate invoke,这里二次兜底)
- if (!readDeviceLinkSettings().remoteControlEnabled) {
+ if (!isSharedTaskPeer(src) && !readDeviceLinkSettings().remoteControlEnabled) {
return { ok: false, error: { code: 'REMOTE_DISABLED', message: 'remote control disabled' } };
}
// 逐设备黑名单:已撤销 → 拒绝订阅(控制端据此 ACCESS_REVOKED 标记「已撤销」+ 移除该设备)。
@@ -3561,6 +3655,25 @@ export async function runInvoke(
src: string,
payload: InvokePayload | undefined,
timing = new RemoteInvokeTiming(),
+): Promise<InvokeResultPayload> {
+ if (!isSharedTaskPeer(src)) return runAuthorizedInvoke(src, payload, timing);
+ const sharedTask = captureSharedTaskPeer(src);
+ try {
+ if (!sharedTask || !payload) throw new Error('SharedTask unavailable');
+ assertSharedTaskInvoke(sharedTask, payload);
+ const result = await runDeviceLinkInvokeContext(
+ { controllerDeviceId: src, channel: payload.channel, sharedTask, sharedTaskSetting: { admitted: false } },
+ () => runAuthorizedInvoke(src, payload, timing),
+ );
+ if (!sharedTask.isCurrent()) throw new Error('SharedTask revoked');
+ return result;
+ } catch {
+ return sharedTaskAccessFailure(src, sharedTask);
+ }
+}
+
+async function runAuthorizedInvoke(
+ src: string, payload: InvokePayload | undefined, timing: RemoteInvokeTiming,
): Promise<InvokeResultPayload> {
return withRemoteDbAdmission(payload?.channel, () => executeRemoteInvoke(src, payload, timing));
}
@@ -3570,7 +3683,7 @@ async function executeRemoteInvoke(src: string, payload: InvokePayload | undefin
return { ok: false, error: { code: 'INTERNAL', message: 'malformed invoke payload' } };
}
// 双层校验之一:被控开关
- if (!readDeviceLinkSettings().remoteControlEnabled) {
+ if (!isSharedTaskPeer(src) && !readDeviceLinkSettings().remoteControlEnabled) {
return { ok: false, error: { code: 'REMOTE_DISABLED', message: 'remote control disabled' } };
}
// 逐设备黑名单:已撤销访问权限的控制端直接拒绝(早于 allowlist)。
@@ -3772,6 +3885,8 @@ async function executeRemoteInvoke(src: string, payload: InvokePayload | undefin
{
controllerDeviceId: src,
channel: payload.channel,
+ sharedTask: getDeviceLinkInvokeContext()?.sharedTask,
+ sharedTaskSetting: getDeviceLinkInvokeContext()?.sharedTaskSetting,
// 平台按 server 盖章的 src 查本机 presence 登记表,不采信控制端自报的任何
// 帧内字段(allowlist 只挡 channel 不挡 args,见下方 dispatchLocalInvoke 前的说明)。
controllerPlatform: getControllerPlatform(src),
@@ -3789,6 +3904,8 @@ async function executeRemoteInvoke(src: string, payload: InvokePayload | undefin
handlerCompleted = true;
if (hasRemoteBotSessionLookup()) await timing.measure('authorizeAfter', () => assertRemoteBotInvocationAllowed(args, payload.channel));
if (!broadcastTap.isDataOwnerBroadcastScopeCurrent(invocationOwner)) throw new Error('[NOT_FOUND] Session does not exist');
+ if (getDeviceLinkInvokeContext()?.sharedTask?.isCurrent() === false &&
+ !getDeviceLinkInvokeContext()?.sharedTaskSetting?.admitted) throw new Error('[PERMISSION_DENIED] SharedTask task access denied');
// 远程 set-* 回流:被控端 set-* runtime-only,补一次 DB 持久化 + 广播 patched,让控制端
// 镜像收敛到被控端真相(取代控制端乐观覆盖)。本机会话不走这条(走 renderer update)。
await timing.measure('persist', () => persistRemoteSetting(payload.channel, payload.args ?? [], result));
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index 3df7f6360e..2771798253 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -18,6 +18,10 @@ import { app, BrowserWindow } from 'electron';
import WebSocket from 'ws';
import {
DeviceLinkClient,
+ parseSharedTaskPeer,
+ probeSharedTaskHost,
+ sharedTaskTopics,
+ SHARED_TASK_CAPABILITY,
CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1,
CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1,
CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,
@@ -44,7 +48,7 @@ import {
import { DEVICE_LINK_VOICE_DICTIONARY_SNAPSHOT_CHANNEL } from '@cindy/maker-shared/device-link-contract';
import * as authManager from '../authManager';
import { remoteCredentialHost } from '../remote-desktop/credentialHost';
-import { getActiveDataOwnerPushStamp } from '../appSessionState.js';
+import { activeOwnerScopeKey, getActiveDataOwnerPushStamp, isAppSessionBoundaryPending } from '../appSessionState.js';
import { createLogger } from '../logger';
import { onQuit } from '../lifecycle';
import { getCurrentDbClientUserId } from '../localDb/client/current';
@@ -127,6 +131,9 @@ import {
import { onVoiceInputDictionaryChanged } from '../voice-input/VoiceInputDataStore';
import { resetAll as resetSubscriptionRefs, snapshotSubscriptions } from './subscriptionRefcount';
import { getControllersForTopic } from './subscriptions';
+import { getKnownControllerIds } from './subscriptions';
+import { startSharedTaskRuntime, stopSharedTaskRuntime } from './sharedTaskRuntime.js';
+import { sharedTaskApi } from './sharedTaskApi.js';
import {
MobileNotifyDeduper,
buildSessionNotifyPayload,
@@ -349,6 +356,9 @@ function refreshControllerDisplayNamesFromDirectory(generation: number): Promise
}
let client: DeviceLinkClient | null = null;
+// Local IPC metadata, never accepted from a push payload or sent over the wire.
+const sharedHostStreams = new Map<string, { streamId: string; epoch: number }>();
+let sharedHostSourceEpoch = 0;
/**
* transport-timeout 重开循环(控制端):被控端瞬时重置后 relay/presence 都不会
@@ -499,6 +509,7 @@ const RESPONSIVENESS_PROBE_TICK_MS = 5_000;
* 必须用同一份 —— 只在一处声明会让另一条路径静默降级(mobile 侧 review 实测过这个坑)。
*/
const CONTROLLER_CAPABILITIES = [
+ SHARED_TASK_CAPABILITY,
CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1,
CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,
CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1,
@@ -655,6 +666,7 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
return ok ? authManager.getAccessToken() : null;
},
getHello: (): HelloPayload => ({
+ capabilities: [SHARED_TASK_CAPABILITY],
deviceName: deviceName(),
platform: process.platform,
appVersion: app.getVersion(),
@@ -698,6 +710,17 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
probeInvoke: (deviceId, channel, args) => {
if (!client)
throw new Error('[DEVICE_LINK_NOT_CONNECTED] device-link client not initialized');
+ if (parseSharedTaskPeer(deviceId)) {
+ const probeClient = client;
+ const scope = activeOwnerScopeKey();
+ return probeSharedTaskHost(deviceId, {
+ isCurrent: () => client === probeClient && arbiter?.isOwner() === true &&
+ !isAppSessionBoundaryPending() && activeOwnerScopeKey() === scope && !revokedByRemote.has(deviceId),
+ get: (sharedTaskId) => sharedTaskApi.get(sharedTaskId),
+ openLink: () => probeClient.isLinkReady(deviceId) ? Promise.resolve() : openRemoteLink(deviceId, { observed: false }),
+ invoke: (probeChannel, probeArgs) => probeClient.invoke(deviceId, { channel: probeChannel, args: probeArgs }),
+ });
+ }
return client.invoke(deviceId, { channel, args }, resolveRemoteInvokeTimeoutMs(channel, args, 'desktop'));
},
onUnresponsiveChanged: (deviceId, unresponsive) => {
@@ -928,6 +951,11 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
// busy presence:每 5s 探一次本机是否有 turn 在跑,变化才上报(dedupe by value)
startBusyReporting();
+ client.onPeerStreamAccepted((peer, streamId) => {
+ if (parseSharedTaskPeer(peer)?.role !== 'host' || sharedHostStreams.get(peer)?.streamId === streamId) return;
+ sharedHostStreams.set(peer, { streamId, epoch: ++sharedHostSourceEpoch });
+ });
+
// 控制端:被控端转发回来的 push 帧 → re-broadcast 给 renderer 远程视图,
// 带上来源 deviceId(src),renderer 据此把事件路由到对应远程设备的 store
client.onFrame((env: Envelope) => {
@@ -953,6 +981,7 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
}
if (env.kind !== 'push') return;
const p = env.payload as PushPayload;
+ const sourceEpoch = sharedHostStreams.get(env.src)?.epoch;
// 词典同步帧在 main 侧消费,不转给 renderer —— 它不是远程视图事件,
// renderer 也不该看到别的设备的同步状态。
if (p?.channel === DL_VOICE_DICTIONARY_SYNC_CHANNEL) {
@@ -993,6 +1022,7 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
channel: MAKER_PUSH.EVENT,
payload: event,
...(p.ownerStamp ? { ownerStamp: p.ownerStamp } : {}),
+ ...(sourceEpoch !== undefined ? { sourceEpoch } : {}),
});
}
return;
@@ -1002,6 +1032,7 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
channel: p.channel,
payload: p.payload,
...(p.ownerStamp ? { ownerStamp: p.ownerStamp } : {}),
+ ...(sourceEpoch !== undefined ? { sourceEpoch } : {}),
});
});
@@ -1077,6 +1108,20 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
// 认领成功但期间已登出:不连(登出路径已 stop 仲裁,这里是 tick 竞态兜底)
if (!authManager.getAuthState().isAuthenticated) return;
linkTornDown = false;
+ if (client) startSharedTaskRuntime({
+ client,
+ revoke(sharedTaskId, memberId) {
+ for (const id of getKnownControllerIds()) {
+ const peer = parseSharedTaskPeer(id);
+ if (!peer || peer.role !== 'guest' || peer.sharedTaskId !== sharedTaskId ||
+ memberId && peer.memberId !== memberId) continue;
+ purgeRevokedController(id);
+ forgetControllerInvokeState(id);
+ client?.closeLink(id, 'revoked', 'inbound');
+ }
+ },
+ changed(sharedTaskId) { broadcast('shared-task:changed', { sharedTaskId }); },
+ });
client?.start();
stopNetworkWatch?.();
stopNetworkWatch = watchNetworkChanges(() => {
@@ -1251,6 +1296,7 @@ export function getMobileNotifyGeneration(): number {
* 同进程换账号登录还会把上一账号的控制端串到新账号。
*/
function teardownActiveLink(): void {
+ void stopSharedTaskRuntime().catch((error) => log.warn('sharedTask runtime teardown failed', error));
remoteCredentialHost.dispose();
stopNetworkWatch?.();
stopNetworkWatch = null;
@@ -1268,6 +1314,7 @@ function teardownActiveLink(): void {
subscriptionReplayScheduler.teardown();
presenceAvailableByDevice.clear();
revokedByRemote.clear();
+ sharedHostStreams.clear();
// 词典同步驱动是进程级的,**不随单次链路起停**:多实例仲裁的 demote → acquire
// 只会 client.start(),不会重跑 initDeviceLinkService,在这里 stop 掉它会让词典
// 同步在降级过一次之后永久失效。清空 presence 就够了 —— 没有对端就不会发送,
@@ -1310,6 +1357,11 @@ export function getDeviceLinkStatus(): DeviceLinkStatus {
return client?.getStatus() ?? 'stopped';
}
+export function isSharedTaskAvailable(): boolean {
+ return !linkTornDown && !!client?.hasServerCapability(SHARED_TASK_CAPABILITY) &&
+ authManager.getAuthState().isAuthenticated;
+}
+
/** 当前被熔断判定为「无响应」的目标设备(控制端本地判定,供 getState / UI 镜像)。 */
export function getUnresponsiveDeviceIds(): string[] {
return responsivenessTracker?.getUnresponsiveDeviceIds() ?? [];
@@ -1730,6 +1782,7 @@ export async function remoteSubscribe(
deviceId: string,
topics: string[],
): Promise<InvokeResultPayload> {
+ topics = sharedTaskTopics(deviceId, topics);
assertNotStandby();
assertRemoteControlTargetEnabled(deviceId);
if (!client) throw new Error('[DEVICE_LINK_NOT_CONNECTED] device-link client not initialized');
@@ -1788,6 +1841,7 @@ export async function remoteUnsubscribe(
deviceId: string,
topics: string[],
): Promise<InvokeResultPayload> {
+ topics = sharedTaskTopics(deviceId, topics);
assertNotStandby();
if (!client) throw new Error('[DEVICE_LINK_NOT_CONNECTED] device-link client not initialized');
return client.invoke(deviceId, { channel: DL_UNSUBSCRIBE_CHANNEL, args: [{ topics }] });
diff --git a/apps/desktop/src/main/device-link/invoke-context.ts b/apps/desktop/src/main/device-link/invoke-context.ts
index 6bb548c661..f62a48ab8f 100644
--- a/apps/desktop/src/main/device-link/invoke-context.ts
+++ b/apps/desktop/src/main/device-link/invoke-context.ts
@@ -10,10 +10,15 @@ import { AsyncLocalStorage } from 'node:async_hooks';
import { isMobilePlatform } from './controllerPlatform';
import * as subscriptions from './subscriptions.js';
+import type { SharedTaskPeerCapture } from './sharedTaskDispatch.js';
export interface DeviceLinkInvokeContext {
controllerDeviceId: string;
channel: string;
+ /** Host-verified sharedTask identity and revocation fence; never populated from wire args. */
+ sharedTask?: SharedTaskPeerCapture;
+ /** Shared only within this invoke; an admitted native mutation must finish or roll back. */
+ sharedTaskSetting?: { admitted: boolean };
/**
* 控制端平台(presence 登记的 `PresenceSnapshot.platform`);未登记时 undefined。
*
diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.ts
index 2b5bd71663..5f7ce851be 100644
--- a/apps/desktop/src/main/device-link/ipc.ts
+++ b/apps/desktop/src/main/device-link/ipc.ts
@@ -53,6 +53,8 @@ import {
} from './index';
import { getActiveControllers } from './dispatch';
import { rewriteOutboundMedia } from './outboundMedia';
+import { parseSharedTaskPeer } from '@cindy/device-link';
+import { withSharedTaskMedia } from './sharedTaskMediaContext.js';
import {
outboundSessionReferencesRequested,
rewriteOutboundSessionReferences,
@@ -141,7 +143,7 @@ export interface DeviceLinkIpcDeps {
* 出方向附件改写:把消息里的本机附件上传 OSS、替换成引用串(仅 send/steer/enqueue 生效)。
* 可选 —— 测试可不注入(跳过改写,行为同旧版纯透传)。
*/
- rewriteOutboundMedia?(channel: string, args: unknown[]): Promise<unknown[]>;
+ rewriteOutboundMedia?(channel: string, args: unknown[], existing?: ReadonlySet<string>): Promise<unknown[]>;
/** 控制端 main 在越过 device-link 前把相对引用解析为可信、预算化快照。 */
rewriteOutboundSessionReferences?(channel: string, args: unknown[]): Promise<unknown[]>;
}
@@ -648,7 +650,20 @@ export async function handleInvoke(
// 上传失败 → MEDIA_TRANSFER_FAILED,整条消息不发(产品决策:不静默丢附件)。
if (deps.rewriteOutboundMedia) {
try {
- callArgs = await deps.rewriteOutboundMedia(channel, callArgs);
+ const peer = parseSharedTaskPeer(normalizedDeviceId);
+ let existing: ReadonlySet<string> | undefined;
+ if (peer?.role === 'host' && channel === 'maker:input:update-content') {
+ const projection = await deps.invoke(normalizedDeviceId, 'maker:input:get-projection', [callArgs[0]]);
+ if (!projection.ok) throw new Error(projection.error.message);
+ const value = projection.result as { sessionId?: string; pendingQueue?: Array<{ clientId: string; files?: Array<{ path?: string; url?: string }> }> };
+ if (value?.sessionId !== callArgs[0] || !Array.isArray(value.pendingQueue)) throw new Error('Invalid shared input projection');
+ const item = value.pendingQueue.find((row) => row.clientId === callArgs[1]);
+ if (!item) throw new Error('Queued message is no longer pending');
+ existing = new Set((item.files ?? []).flatMap((file) => [file.path, file.url].filter((ref): ref is string => typeof ref === 'string')));
+ assertControlTargetEnabled(deps, normalizedDeviceId);
+ }
+ callArgs = await withSharedTaskMedia(peer?.role === 'host' ? peer.sharedTaskId : undefined,
+ () => existing ? deps.rewriteOutboundMedia!(channel, callArgs, existing) : deps.rewriteOutboundMedia!(channel, callArgs));
} catch (err) {
throwIpcError(
'DEVICE_LINK_MEDIA_TRANSFER_FAILED',
diff --git a/apps/desktop/src/main/device-link/mediaFetch.ts b/apps/desktop/src/main/device-link/mediaFetch.ts
index 875f682b86..9373a007c2 100644
--- a/apps/desktop/src/main/device-link/mediaFetch.ts
+++ b/apps/desktop/src/main/device-link/mediaFetch.ts
@@ -36,6 +36,8 @@ import { materializeSshRemoteMedia } from '../file-browser/ssh-media.js';
import { getSessionFsSnapshot } from '../localDb/ipc/sessions.js';
import { mimeOf, uploadLocalFile } from './mediaTransfer.js';
import { createLogger } from '../logger.js';
+import { getDeviceLinkInvokeContext } from './invoke-context.js';
+import { sharedTaskMediaId, withSharedTaskMedia } from './sharedTaskMediaContext.js';
const log = createLogger('device-link:mediaFetch');
@@ -314,6 +316,12 @@ export async function resolveAuthorizedMedia(arg: unknown, maximumBytes?: number
: {};
const url = record.url;
if (typeof url !== 'string' || !url) throw new Error('media:fetch 缺少 url');
+ const sharedTask = getDeviceLinkInvokeContext()?.sharedTask;
+ let sharedRoot: string | undefined;
+ if (sharedTask) {
+ const { assertSharedTaskMedia } = await import('./sharedTaskMediaAccess.js');
+ sharedRoot = await assertSharedTaskMedia(url, sharedTask);
+ }
const isPathMedia = url.startsWith('xdt-file://') || url.startsWith('xdt-audio://');
const sshOrigin = isPathMedia ? await parseSshMediaOrigin(url) : null;
const constraints: PathMediaConstraints = isPathMedia
@@ -367,6 +375,9 @@ export async function resolveAuthorizedMedia(arg: unknown, maximumBytes?: number
throw new Error('媒体文件不存在或不可读');
}
// realpath 再查:挡字面形式看似无害的 symlink 逃逸。
+ if (sharedRoot && !isInsideRealDir(real, sharedRoot)) {
+ throw new Error('[PERMISSION_DENIED] Media left the shared task workdir');
+ }
if (!isPathAllowedAgainst(real, getSensitiveMediaBlocklist())) {
log.warn(`media:fetch blocked sensitive realpath ${url.slice(0, 60)}`);
throw new Error('该路径位于敏感目录,已阻止远程取件');
@@ -413,6 +424,9 @@ export async function fetchLocalMediaToOss(arg: unknown): Promise<MediaFetchResu
: {};
const { absPath, mimeType, uploadExtHint, maxBytes } = await resolveAuthorizedMedia(arg);
const url = record.url as string;
+ const sharedTask = getDeviceLinkInvokeContext()?.sharedTask;
+ const mediaScope = sharedTask?.author.sharedTaskId ?? sharedTaskMediaId();
+ const cacheKey = mediaScope ? `${mediaScope}:${url}` : url;
const skipCache = record.skipCache === true;
if (record.prepareOnly === true && record.thumbnail !== true) {
const file = await open(absPath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
@@ -477,7 +491,7 @@ export async function fetchLocalMediaToOss(arg: unknown): Promise<MediaFetchResu
if (cacheable) {
st = await stat(absPath);
if (!skipCache) {
- const hit = lookupUploadCache(url, st.size, st.mtimeMs, Date.now());
+ const hit = lookupUploadCache(cacheKey, st.size, st.mtimeMs, Date.now());
if (hit) {
log.debug(`media:fetch cache hit ${url.slice(0, 40)} → ossKey=${hit.ossKey}`);
return { ossKey: hit.ossKey, mimeType: hit.mimeType, size: hit.size };
@@ -485,13 +499,14 @@ export async function fetchLocalMediaToOss(arg: unknown): Promise<MediaFetchResu
}
}
- const uploaded = await uploadLocalFile(absPath, {
+ if (sharedTask && !sharedTask.isCurrent()) throw new Error('[PERMISSION_DENIED] Shared task access revoked');
+ const uploaded = await withSharedTaskMedia(sharedTask?.author.sharedTaskId, () => uploadLocalFile(absPath, {
...(maxBytes !== null ? { maxBytes } : {}),
...(mimeType ? { contentType: mimeType } : {}),
...(uploadExtHint ? { extHint: uploadExtHint } : {}),
- });
+ }));
if (cacheable && st) {
- rememberUpload(url, {
+ rememberUpload(cacheKey, {
ossKey: uploaded.key,
mimeType: uploaded.contentType,
size: uploaded.size,
diff --git a/apps/desktop/src/main/device-link/mediaTransfer.ts b/apps/desktop/src/main/device-link/mediaTransfer.ts
index eaad3eeb79..9af61dc61a 100644
--- a/apps/desktop/src/main/device-link/mediaTransfer.ts
+++ b/apps/desktop/src/main/device-link/mediaTransfer.ts
@@ -35,6 +35,7 @@ import type { AttachmentIntegrity } from '@cindy/device-link';
import { serverApiFetch } from '../serverApiClient.js';
import { requireAppCapability } from '../appCapabilities.js';
import { deviceLinkApiBase } from './index.js';
+import { sharedTaskMediaId } from './sharedTaskMediaContext.js';
import { describeErrorChain } from '../utils/errorChain.js';
import { createLogger } from '../logger.js';
@@ -119,7 +120,7 @@ async function presignPut(
requireAppCapability('canUseDeviceLink', 'Device Link requires a Cindy account.');
return serverApiFetch<PresignPutResponse>(PRESIGN_PUT_PATH, {
method: 'POST',
- body: { size, ext, contentType },
+ body: { size, ext, contentType, ...(sharedTaskMediaId() ? { sharedTaskId: sharedTaskMediaId() } : {}) },
baseUrl: deviceLinkApiBase,
});
}
diff --git a/apps/desktop/src/main/device-link/outboundMedia.ts b/apps/desktop/src/main/device-link/outboundMedia.ts
index be6c9e9d76..e78a374425 100644
--- a/apps/desktop/src/main/device-link/outboundMedia.ts
+++ b/apps/desktop/src/main/device-link/outboundMedia.ts
@@ -16,6 +16,7 @@ import { createLogger } from '../logger';
import * as imageCacheStore from '../imageCacheStore';
import * as cindyMediaBlobStore from '../cindy-media/blobStore';
import { uploadLocalFile, uploadBuffer, type UploadResult } from './mediaTransfer';
+import { sharedTaskMediaId } from './sharedTaskMediaContext.js';
import {
OUTBOUND_IMAGE_INPUT_MAX_BYTES,
compressOutboundImage,
@@ -107,6 +108,7 @@ async function uploadAttachment(src: AttachmentSource): Promise<string> {
const rawPath = typeof src.path === 'string' && src.path ? src.path : '';
const ref = url || rawPath;
if (!ref) throw new Error('附件无可用来源(url/path/base64 皆空)');
+ if (parseAttachmentOssRef(ref)) return ref;
if (ref.startsWith('clipboard://')) throw new Error('附件为 clipboard 占位,无字节');
// 2a) xdt-image:// 缓存 → 视觉上下文语义(截图/剪贴板/生成图)压缩后 uploadBuffer;
@@ -306,9 +308,17 @@ function rewritePersistedContent(json: string, refMap: Map<string, string>): str
* 被控端 reload 历史裂图(PR #166 review)。chatMessage 在被控端不落库/不广播,无需改。
* 去重:每个附件按其 url/path 标识只上传一次 OSS,files[] 与 persistedContent 共用同一引用。
*/
-async function rewriteQueued(item: unknown): Promise<unknown> {
+async function rewriteQueued(item: unknown, existing: ReadonlySet<string> = new Set()): Promise<unknown> {
if (!item || typeof item !== 'object') return item;
- const it = item as { files?: unknown; persistedContent?: unknown };
+ let it = item as { files?: unknown; persistedContent?: unknown; chatMessage?: unknown };
+ if (sharedTaskMediaId() && it.chatMessage && typeof it.chatMessage === 'object') {
+ // The controller already owns its optimistic preview. Do not send its local
+ // paths or retry caches to the shared host as a second source of authority.
+ const preview = { ...it.chatMessage } as Record<string, unknown>;
+ for (const key of ['images', 'files', 'retryFiles', 'retryMentions']) delete preview[key];
+ it = { ...it, chatMessage: preview };
+ item = it;
+ }
if (!Array.isArray(it.files) || it.files.length === 0) return item; // 无 files[] → 无附件
// 原始 ref(url 或 path 字符串)→ OSS 引用;同一附件只传一次,供 files[] + persistedContent 复用。
@@ -316,6 +326,10 @@ async function rewriteQueued(item: unknown): Promise<unknown> {
const files: unknown[] = [];
for (const f of it.files) {
+ if (f && typeof f === 'object' && existing.has(sourceRefKey(f as AttachmentSource))) {
+ files.push(f);
+ continue;
+ }
if (
f &&
typeof f === 'object' &&
@@ -350,7 +364,12 @@ async function rewriteQueued(item: unknown): Promise<unknown> {
* 出方向附件改写入口:仅对携带附件的 channel 处理,返回新 args(不原地改 caller 数组)。
* 抛错由 handleInvoke 转 MEDIA_TRANSFER_FAILED。
*/
-export async function rewriteOutboundMedia(channel: string, args: unknown[]): Promise<unknown[]> {
+export async function rewriteOutboundMedia(channel: string, args: unknown[], existing: ReadonlySet<string> = new Set()): Promise<unknown[]> {
+ if (channel === 'maker:input:update-content' && sharedTaskMediaId()) {
+ const next = [...args];
+ next[2] = await rewriteQueued(next[2], existing);
+ return next;
+ }
const isQueued = QUEUED_SHAPE_CHANNELS.has(channel);
const isMessage = MESSAGE_SHAPE_CHANNELS.has(channel);
if (!isQueued && !isMessage) return args;
diff --git a/apps/desktop/src/main/device-link/sharedTaskAccess.ts b/apps/desktop/src/main/device-link/sharedTaskAccess.ts
new file mode 100644
index 0000000000..6fcc798610
--- /dev/null
+++ b/apps/desktop/src/main/device-link/sharedTaskAccess.ts
@@ -0,0 +1,105 @@
+import {
+ authorizeSharedTaskOperation,
+ parseSharedTaskSnapshot,
+ type SharedTaskCaller,
+ type SharedTaskDecision,
+ type SharedTaskIdentity,
+ type SharedTaskQueueItem,
+ type SharedTaskSnapshot,
+} from '@cindy/device-link';
+
+/**
+ * Per-sharedTask authority mirror owned by the task host. It contains no network or
+ * persistence: only the authenticated authority adapter may install snapshots.
+ * A replacement account/sharedTask must get a new instance; queued callbacks keep
+ * the old instance and therefore cannot regain permission after close().
+ */
+export class SharedTaskAccess {
+ private readonly identity: Readonly<SharedTaskIdentity>;
+ private snapshot: SharedTaskSnapshot | null = null;
+ private closed = false;
+ private readonly retiredMemberIds = new Set<string>();
+ private readonly suspendedMembers = new Map<string, number>();
+
+ constructor(identity: SharedTaskIdentity) {
+ this.identity = Object.freeze({ ...identity });
+ }
+
+ /** Returns false for a stale revision. Conflicting identities/revisions fail closed. */
+ applyVerifiedSnapshot(value: unknown): boolean {
+ const next = parseSharedTaskSnapshot(value);
+ for (const key of ['sharedTaskId', 'sessionId', 'ownerAccountId', 'hostDeviceId'] as const) {
+ if (next[key] !== this.identity[key]) throw new Error('SharedTask authority scope mismatch');
+ }
+ if (this.closed) return false;
+ if (this.snapshot) {
+ if (next.revision < this.snapshot.revision) return false;
+ if (next.revision === this.snapshot.revision) {
+ if (JSON.stringify(next) !== JSON.stringify(this.snapshot)) throw new Error('Conflicting sharedTask revision');
+ return false;
+ }
+ if (this.snapshot.status === 'closed') throw new Error('Closed sharedTask cannot reopen');
+ for (const guest of next.guests) {
+ if (this.retiredMemberIds.has(guest.memberId)) throw new Error('Revoked sharedTask member cannot return');
+ const previous = this.snapshot.guests.find((item) => item.memberId === guest.memberId);
+ if (previous && (guest.accountId !== previous.accountId || guest.version < previous.version ||
+ (guest.version === previous.version && JSON.stringify(guest.deviceIds) !== JSON.stringify(previous.deviceIds)))) {
+ throw new Error('Invalid sharedTask member revision');
+ }
+ }
+ for (const previous of this.snapshot.guests) {
+ if (!next.guests.some((item) => item.memberId === previous.memberId)) this.retiredMemberIds.add(previous.memberId);
+ }
+ }
+ this.snapshot = next;
+ return true;
+ }
+
+ authorize(
+ caller: SharedTaskCaller, sessionId: string, operation: string,
+ queueItem?: SharedTaskQueueItem,
+ ): SharedTaskDecision {
+ const decision = authorizeSharedTaskOperation(this.closed ? null : this.snapshot, caller, sessionId, operation, queueItem);
+ return decision.allowed && decision.role === 'guest' && this.suspendedMembers.has(decision.memberId)
+ ? { allowed: false, reason: 'not-a-member' } : decision;
+ }
+
+ /** Fence just this member while its removal is being committed/reconciled. */
+ suspendMember(memberId: string): () => void {
+ this.suspendedMembers.set(memberId, (this.suspendedMembers.get(memberId) ?? 0) + 1);
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ const count = (this.suspendedMembers.get(memberId) ?? 1) - 1;
+ if (count === 0) this.suspendedMembers.delete(memberId);
+ else this.suspendedMembers.set(memberId, count);
+ };
+ }
+
+ /**
+ * Recheck after awaits and immediately before delivery or side effects. The
+ * queue item must be re-read by the caller too; this is not a queue lock.
+ */
+ capture(
+ caller: SharedTaskCaller, sessionId: string, operation: string,
+ readQueueItem?: () => SharedTaskQueueItem | undefined,
+ ): { decision: SharedTaskDecision; isCurrent: () => boolean } {
+ const actor = { ...caller };
+ const decision = this.authorize(actor, sessionId, operation, readQueueItem?.());
+ return {
+ decision,
+ isCurrent: () => {
+ if (!decision.allowed) return false;
+ const now = this.authorize(actor, sessionId, operation, readQueueItem?.());
+ return now.allowed && now.role === decision.role && now.memberId === decision.memberId && now.memberVersion === decision.memberVersion;
+ },
+ };
+ }
+
+ /** Local close/logout prevents late authority replies from reviving access. */
+ close(): void {
+ this.closed = true;
+ this.snapshot = null;
+ }
+}
diff --git a/apps/desktop/src/main/device-link/sharedTaskApi.ts b/apps/desktop/src/main/device-link/sharedTaskApi.ts
new file mode 100644
index 0000000000..1d7f5d2bb8
--- /dev/null
+++ b/apps/desktop/src/main/device-link/sharedTaskApi.ts
@@ -0,0 +1,61 @@
+import { createSharedTaskApi, SharedTaskScopeChangedError } from '@cindy/device-link';
+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';
+import { getAccessToken, getActiveAuthRealm, getAuthState, getCurrentUserId } from '../authManager.js';
+import { getClientEndpoint } from '../clientEndpointsService.js';
+import { serverApiFetch } from '../serverApiClient.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+
+/** Main-owned adapter. Tokens remain inside the existing authenticated HTTP client. */
+export const sharedTaskApi = createSharedTaskApi({
+ captureScope() {
+ const key = activeOwnerScopeKey();
+ const endpoint = getClientEndpoint('deviceLinkApiBaseUrl');
+ return { isCurrent: () => getAuthState().isAuthenticated && !isAppSessionBoundaryPending() &&
+ activeOwnerScopeKey() === key && getClientEndpoint('deviceLinkApiBaseUrl') === endpoint };
+ },
+ async request(path, options) {
+ try {
+ return await serverApiFetch<unknown>(path, {
+ method: options.method,
+ body: options.body,
+ // Executed before EACH physical attempt, including automatic token refresh.
+ // A new account/region cannot submit an old invitation or moderation action.
+ baseUrl: () => {
+ if (!options.isCurrent()) throw new SharedTaskScopeChangedError();
+ return getClientEndpoint('deviceLinkApiBaseUrl');
+ },
+ timeoutMs: 15_000,
+ cache: 'no-store',
+ logLabel: '/api/device-link/shared-tasks',
+ redactErrorDetails: true,
+ allowedRedactedErrorCodes: ['NOT_FOUND', 'CONFLICT', 'PERMISSION_DENIED', 'INVALID_PARAMS', 'RATE_LIMITED',
+ 'SHARED_TASK_HOST_LIMIT', 'SHARED_TASK_JOIN_LIMIT', 'SHARED_TASK_GUEST_LIMIT'],
+ });
+ } catch (error) {
+ const code = error && typeof error === 'object' ? (error as { code?: unknown }).code : undefined;
+ if (code === 'SHARED_TASK_HOST_LIMIT' || code === 'SHARED_TASK_JOIN_LIMIT' || code === 'SHARED_TASK_GUEST_LIMIT') {
+ throwIpcError(code, 'Shared task limit reached');
+ }
+ throw error;
+ }
+ },
+});
+
+/** Capture only while the outgoing identity still owns the credentials. Unlike
+ * ordinary requests, this close-only cleanup may cross the pending boundary:
+ * its endpoint/token never refresh, and errors cannot log out the next account. */
+export function captureSharedTaskBoundaryClose(ownerAccountId: string, region: ReturnType<typeof getActiveAuthRealm>) {
+ if (getCurrentUserId() !== ownerAccountId || getActiveAuthRealm() !== region) return null;
+ const token = getAccessToken();
+ if (!token) return null;
+ const endpoint = getClientEndpoint('deviceLinkApiBaseUrl');
+ const api = createSharedTaskApi({
+ captureScope: () => ({ isCurrent: () => true }),
+ request: (path, options) => serverApiFetch<unknown>(path, {
+ method: options.method, body: options.body, token, baseUrl: endpoint,
+ skipAutoRefresh: true, skipSessionInvalidation: true, timeoutMs: 3_000,
+ cache: 'no-store', redactErrorDetails: true, logLabel: '/api/device-link/shared-tasks',
+ }),
+ });
+ return (sharedTaskId: string) => api.close(sharedTaskId);
+}
diff --git a/apps/desktop/src/main/device-link/sharedTaskCommands.ts b/apps/desktop/src/main/device-link/sharedTaskCommands.ts
new file mode 100644
index 0000000000..10230f260e
--- /dev/null
+++ b/apps/desktop/src/main/device-link/sharedTaskCommands.ts
@@ -0,0 +1,76 @@
+import type { SharedTaskApi, SharedTaskCloseResult, SharedTaskHostState, SharedTaskOwnedItem } from '@cindy/device-link';
+import type { SharedTaskHost } from './sharedTaskHost.js';
+import { requireString, throwIpcError } from '../utils/ipcValidate.js';
+
+function command(raw: unknown): Record<string, unknown> {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throwIpcError('INVALID_PARAMS', 'SharedTask command is required');
+ return raw as Record<string, unknown>;
+}
+function id(value: unknown): string {
+ const text = requireString(value, 'identifier');
+ if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(text)) throwIpcError('INVALID_PARAMS', 'Invalid sharedTask identifier');
+ return text;
+}
+
+/** Owner management is never exposed through guest task invoke permissions. */
+export async function executeSharedTaskHostCommand(raw: unknown, deps: {
+ available(): boolean; host(): SharedTaskHost;
+}): Promise<unknown> {
+ const input = command(raw);
+ if (input.action === 'state') {
+ const sessionId = id(input.sessionId);
+ if (!deps.available()) return { available: false, detail: null } satisfies SharedTaskHostState;
+ const host = deps.host();
+ const sharedTaskId = host.activeSharedTaskIds().find((key) => host.detail(key)?.sessionId === sessionId);
+ if (!sharedTaskId) return { available: true, detail: null } satisfies SharedTaskHostState;
+ await host.refresh(sharedTaskId);
+ const detail = host.detail(sharedTaskId);
+ return { available: true, detail } satisfies SharedTaskHostState;
+ }
+ if (!deps.available()) throwIpcError('UNSUPPORTED_CAPABILITY', 'SharedTask mode requires updated clients and server');
+ const host = deps.host();
+ if (input.action === 'open') return { sharedTaskId: await host.open(id(input.sessionId)) };
+ const sharedTaskId = id(input.sharedTaskId);
+ if (input.action === 'invite') return host.invite(sharedTaskId);
+ if (input.action === 'close') { await host.close(sharedTaskId); return { ok: true }; }
+ if (input.action === 'remove') { await host.remove(sharedTaskId, id(input.memberId)); return { ok: true }; }
+ throwIpcError('INVALID_PARAMS', 'Unknown sharedTask command');
+}
+
+/** Account API uses the caller's login, never the host's credentials. */
+export async function executeSharedTaskAccountCommand(raw: unknown, api: SharedTaskApi, accountId?: string, deps?: {
+ /** Shared tasks hosted by THIS profile; closable through the local host journal. */
+ hostedIds?(): string[];
+ closeHosted?(sharedTaskId: string): Promise<void>;
+}): Promise<unknown> {
+ const input = command(raw);
+ if (input.action === 'list') return (await api.list()).filter((item) => item.ownerAccountId !== accountId);
+ if (input.action === 'owned') {
+ if (!accountId) return [] satisfies SharedTaskOwnedItem[];
+ const hosted = deps?.hostedIds?.() ?? [];
+ return (await api.list())
+ .filter((item) => item.ownerAccountId === accountId)
+ .map((item) => ({ ...item, local: hosted.includes(item.sharedTaskId) })) satisfies SharedTaskOwnedItem[];
+ }
+ if (input.action === 'close') {
+ const result: SharedTaskCloseResult = { closed: [], failed: [] };
+ const targets = input.all === true
+ ? (await api.list()).filter((item) => item.ownerAccountId === accountId).map((item) => item.sharedTaskId)
+ : [id(input.sharedTaskId)];
+ for (const sharedTaskId of targets) {
+ try {
+ // Locally hosted tasks must go through the host so the closure is
+ // journaled and guests are revoked before the server answers.
+ if (deps?.hostedIds?.().includes(sharedTaskId) && deps.closeHosted) await deps.closeHosted(sharedTaskId);
+ else await api.close(sharedTaskId);
+ result.closed.push(sharedTaskId);
+ } catch { result.failed.push({ sharedTaskId }); }
+ }
+ return result;
+ }
+ if (input.action === 'join') return api.join(requireString(input.invitation, 'invitation'), requireString(input.displayName, 'displayName'));
+ const sharedTaskId = id(input.sharedTaskId);
+ if (input.action === 'get') return api.get(sharedTaskId);
+ if (input.action === 'leave') return api.leave(sharedTaskId);
+ throwIpcError('INVALID_PARAMS', 'Unknown sharedTask account command');
+}
diff --git a/apps/desktop/src/main/device-link/sharedTaskDispatch.ts b/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
new file mode 100644
index 0000000000..02a9b0c6e3
--- /dev/null
+++ b/apps/desktop/src/main/device-link/sharedTaskDispatch.ts
@@ -0,0 +1,177 @@
+import { isSharedTaskPeer, parseSharedTaskPeer, isSharedTaskAttachment, type InvokePayload, type InvokeResultPayload, type SharedTaskQueueItem } from '@cindy/device-link';
+import type { SharedTaskHost } from './sharedTaskHost.js';
+
+export type SharedTaskPeerCapture = NonNullable<ReturnType<SharedTaskHost['capturePeer']>>;
+let host: SharedTaskHost | null = null;
+let readQueueItem: ((sessionId: string, clientId: string) => (SharedTaskQueueItem & { attachments?: unknown }) | undefined) | null = null;
+export function setSharedTaskQueueReader(value: typeof readQueueItem): void { readQueueItem = value; }
+export function setSharedTaskDispatchHost(value: SharedTaskHost | null): void { host = value; }
+export function captureSharedTaskPeer(source: string): SharedTaskPeerCapture | null {
+ return host?.capturePeer(source) ?? null;
+}
+
+/** Only confirmed membership loss may evict a guest's shared task on the client. */
+export function sharedTaskAccessFailure(source: string, capture?: SharedTaskPeerCapture | null): InvokeResultPayload {
+ const status = host?.peerStatus(source) ?? 'unavailable';
+ if (status === 'revoked') return { ok: false, error: { code: 'ACCESS_REVOKED', message: 'Shared task access revoked' } };
+ if (status === 'unavailable' || !capture?.isCurrent()) {
+ return { ok: false, error: { code: 'NOT_CONNECTED', message: 'Shared task authority changed or is temporarily unavailable' } };
+ }
+ return { ok: false, error: { code: 'IPC_ERROR', message: '[PERMISSION_DENIED] Shared task request denied' } };
+}
+
+// These existing list events also carry single-task state. Shared peers receive
+// only this explicit subset through their task subscription, never `sessions`.
+const sessionMetadataChannels = new Set([
+ 'local-db:sessions:created', 'local-db:sessions:patched', 'local-db:sessions:activity',
+ 'local-db:session:error-persisted', 'usage:session-spend-changed', 'usage:session-tokens-changed',
+]);
+export function sharedTaskMetadataTopic(channel: string, payload: unknown): `session:${string}` | null {
+ const sessionId = record(payload)?.sessionId;
+ return sessionMetadataChannels.has(channel) && typeof sessionId === 'string' && sessionId.length > 0
+ ? `session:${sessionId}` : null;
+}
+
+/** A newly invited device can arrive before the periodic authority refresh. */
+export async function refreshSharedTaskPeer(source: string): Promise<void> {
+ const peer = parseSharedTaskPeer(source);
+ const capturedHost = host;
+ if (!peer || peer.role !== 'guest' || !capturedHost) throw new Error('Shared task host unavailable');
+ await capturedHost.refresh(peer.sharedTaskId);
+ if (host !== capturedHost) throw new Error('Shared task host changed');
+}
+
+// Deliberately separate from the same-account allowlist: adding a full-device
+// channel must never implicitly grant that capability to sharedTask guests.
+const sessionReads = new Set([
+ 'local-db:sessions:get', 'local-db:messages:list', 'local-db:messages:view',
+ 'local-db:messages:view-intent', 'local-db:messages:work-details',
+ 'local-db:messages:around', 'local-db:messages:around-client-id',
+ 'local-db:messages:estimatedSessionValue', 'maker:input:get-projection',
+ 'maker:session-in-turn', 'maker:session-background-activity',
+ 'maker:session-background-tasks:list', 'maker:get-context-usage',
+ 'maker:get-pending-interactions', 'maker:get-session-agent-switch-intent',
+]);
+const inputEdits = new Set(['maker:input:update-text', 'maker:input:update-content', 'maker:input:set-edit-lock']);
+const agentSettings = new Set(['maker:set-model', 'maker:set-effort', 'maker:set-fast-mode', 'maker:set-thinking-enabled', 'maker:switch-session-agent']);
+
+function record(value: unknown): Record<string, unknown> | null {
+ return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null;
+}
+function deny(): never { throw new Error('[PERMISSION_DENIED] SharedTask task access denied'); }
+
+/** Existing attachments can survive a text edit without being re-uploaded. The
+ * set comes exclusively from this member's current host-owned pending row. */
+export function sharedTaskOwnedQueueReferences(capture: SharedTaskPeerCapture, clientId: unknown): ReadonlySet<string> {
+ const result = new Set<string>();
+ const item = typeof clientId === 'string' ? readQueueItem?.(capture.author.sessionId, clientId) : undefined;
+ if (!item || !capture.authorize('input.edit', item)) return result;
+ if (Array.isArray(item.attachments)) for (const file of item.attachments) {
+ const row = record(file);
+ for (const key of ['path', 'url']) if (typeof row?.[key] === 'string') result.add(row[key] as string);
+ }
+ return result;
+}
+
+/** Input reference metadata is consumed before Agent execution, under host authority. */
+export function assertSharedTaskReferences(value: unknown, sessionId: string, depth = 0, sharedTaskId?: string, existing: ReadonlySet<string> = new Set()): void {
+ if (depth > 32) deny();
+ if (Array.isArray(value)) {
+ for (const child of value) assertSharedTaskReferences(child, sessionId, depth + 1, sharedTaskId, existing);
+ return;
+ }
+ const row = record(value);
+ if (!row) return;
+ for (const [key, child] of Object.entries(row)) {
+ if (['sessionId', 'parentSessionId', 'sourceSessionId', 'targetSessionId'].includes(key) && child !== sessionId) deny();
+ if (key === 'botId' || key === 'hostSnapshot') deny();
+ // Native Agent tools retain normal task permissions; client references are
+ // direct host reads and must come from this task's authorized upload area.
+ if ((key === 'path' || key === 'url') && child !== undefined && child !== null && child !== '' &&
+ !(typeof child === 'string' && (existing.has(child) || sharedTaskId && isSharedTaskAttachment(child, sharedTaskId)))) deny();
+ // Persisted reference chips are another input to host-side hydration.
+ if (key === 'persistedContent' && typeof child === 'string') {
+ let parsed: unknown;
+ try { parsed = JSON.parse(child); } catch { continue; }
+ assertSharedTaskReferences(parsed, sessionId, depth + 1, sharedTaskId, existing);
+ } else if (child && typeof child === 'object') assertSharedTaskReferences(child, sessionId, depth + 1, sharedTaskId, existing);
+ }
+}
+
+/** Validate the actual channel shape; unknown channels fail closed. */
+export function assertSharedTaskInvoke(
+ capture: SharedTaskPeerCapture, payload: InvokePayload, queueItem?: SharedTaskQueueItem,
+ phase: 'invoke' | 'result' = 'invoke',
+): void {
+ if (!capture.isCurrent()) deny();
+ const { channel } = payload;
+ const args = payload.args ?? [];
+ if (!Array.isArray(args)) deny();
+ const sessionId = capture.author.sessionId;
+ if (['local-db:subagent-runs:list', 'local-db:subagent-runs:detail', 'local-db:subagent-runs:transcript'].includes(channel)) {
+ const request = record(args[0]);
+ if (args.length !== 1 || !request || request.sessionId !== sessionId ||
+ Object.keys(request).some((key) => !['sessionId', 'provider', 'runIdOrAlias', 'cursor', 'limit'].includes(key)) ||
+ !capture.authorize('history.read')) deny();
+ assertSharedTaskReferences(request, sessionId);
+ return;
+ }
+ if (channel === 'device-link:media:fetch') {
+ const request = record(args[0]);
+ if (args.length !== 1 || !request || typeof request.url !== 'string' ||
+ Object.keys(request).some((key) => !['url', 'skipCache', 'thumbnail', 'prepareOnly'].includes(key)) ||
+ !capture.authorize('attachment.read')) deny();
+ // The media handler validates ledger/workdir ownership before reading bytes.
+ return;
+ }
+ // Display-only catalogs used by the existing remote composer. The provider
+ // response goes through dispatch's normal credential-free projection.
+ if (channel === 'maker:get-capabilities' || channel === 'maker:provider:list') {
+ if (args.length > 1 || !capture.authorize('history.read')) deny();
+ if (channel === 'maker:get-capabilities' && !['claude-code', 'codex', 'pi'].includes(String(args[0]))) deny();
+ if (channel === 'maker:provider:list' && args[0] !== undefined) {
+ const options = record(args[0]);
+ if (!options || Object.keys(options).some((key) => key !== 'capabilities') ||
+ !Array.isArray(options.capabilities) || options.capabilities.some((item) => typeof item !== 'string')) deny();
+ }
+ return;
+ }
+ if (channel === 'device-link:subscribe' || channel === 'device-link:unsubscribe') {
+ const topics = record(args[0])?.topics;
+ if (!Array.isArray(topics) || topics.length > 1 || topics.some((topic) => topic !== `session:${sessionId}`)) deny();
+ if (!capture.authorize('events.subscribe')) deny();
+ return;
+ }
+ if (args[0] !== sessionId) deny();
+ const operation = sessionReads.has(channel) ? 'history.read'
+ : ['maker:input:enqueue', 'maker:input:steer', 'maker:input:resume', 'maker:input:set-expanded'].includes(channel) ? 'input.send'
+ : channel === 'maker:input:stop' ? 'agent.stop'
+ : channel === 'maker:input:remove' ? 'input.withdraw'
+ : inputEdits.has(channel) ? 'input.edit'
+ : agentSettings.has(channel) ? 'agent.configure' : null;
+ if (!operation) deny();
+ if (phase === 'result') {
+ if (!capture.authorize('history.read')) deny();
+ } else {
+ if (!capture.authorize(operation, queueItem ?? (typeof args[1] === 'string'
+ ? readQueueItem?.(sessionId, args[1]) : undefined))) deny();
+ const existing = sharedTaskOwnedQueueReferences(capture, typeof args[1] === 'string' ? args[1] : record(args[1])?.clientId);
+ assertSharedTaskReferences(args.slice(1), sessionId, 0, capture.author.sharedTaskId, existing);
+ }
+}
+
+/** Synchronous last-mile gate, including batches, delayed pushes and offline replay. */
+export function captureSharedTaskPush(source: string, channel: string, payload: unknown): (() => boolean) | null {
+ if (!isSharedTaskPeer(source)) return () => true;
+ const capture = captureSharedTaskPeer(source);
+ if (!capture || !capture.authorize('events.subscribe')) return null;
+ const sessionId = capture.author.sessionId;
+ const row = record(payload);
+ if (row?.sessionId !== sessionId) return null;
+ // Never forward a device/account projection just because it has a sessionId.
+ if (!(channel.startsWith('maker:') || channel.startsWith('local-db:messages:') ||
+ sharedTaskMetadataTopic(channel, payload) !== null ||
+ channel.startsWith('usage:message-') || channel === 'usage:session-spend-changed' || channel === 'usage:session-tokens-changed')) return null;
+ if (channel === 'maker:event:batch' && (!Array.isArray(row.events) || row.events.some((event) => record(event)?.sessionId !== sessionId))) return null;
+ return () => capture.isCurrent();
+}
diff --git a/apps/desktop/src/main/device-link/sharedTaskHost.ts b/apps/desktop/src/main/device-link/sharedTaskHost.ts
new file mode 100644
index 0000000000..5f95491865
--- /dev/null
+++ b/apps/desktop/src/main/device-link/sharedTaskHost.ts
@@ -0,0 +1,395 @@
+import {
+ parseSharedTaskSnapshot, parseSharedTaskPeer, type SharedTaskApi, type SharedTaskCaller,
+ type SharedTaskDetail, type SharedTaskIdentity, type SharedTaskQueueItem,
+} from '@cindy/device-link';
+import type { SharedTaskJournal } from '../localDb/sharedTasks.js';
+import { SharedTaskAccess } from './sharedTaskAccess.js';
+
+interface HostedSharedTask {
+ identity: SharedTaskIdentity;
+ access: SharedTaskAccess;
+ detail: SharedTaskDetail | null;
+}
+/** Lifecycle bookkeeping survives same-profile runtime replacement; grants do not. */
+export interface SharedTaskCreationState {
+ pending: Map<Promise<unknown>, string>;
+ identities: Map<string, SharedTaskIdentity>;
+ closedSessions?: Set<string>;
+ sessionGenerations?: Map<string, number>;
+ taskClosures?: Map<string, Promise<string[]>>;
+}
+export interface SharedTaskHostOptions {
+ api: SharedTaskApi;
+ journal: SharedTaskJournal;
+ ownerAccountId: string;
+ hostDeviceId: string;
+ creationState?: SharedTaskCreationState;
+ /** Bound at construction to this profile/auth/region generation. */
+ isCurrent(): boolean;
+ readSession(sessionId: string): Promise<{ id: string; title: string; status: string } | null>;
+ /** Teardown only the affected sharedTask/member, not the shared relay connection. */
+ revoke(sharedTaskId: string, memberId?: string): void;
+ changed(sharedTaskId: string): void;
+}
+
+/** One task-hosting Desktop generation. Never grants access from disk alone. */
+export class SharedTaskHost {
+ private disposed = false;
+ private boundaryClosed = false;
+ private readonly closedSessions: Set<string>;
+ private readonly sessionGenerations: Map<string, number>;
+ private readonly taskClosures: Map<string, Promise<string[]>>;
+ private readonly creating: SharedTaskCreationState['pending'];
+ private readonly created: SharedTaskCreationState['identities'];
+ private readonly entries = new Map<string, HostedSharedTask>();
+ private readonly closed = new Set<string>();
+ private readonly chains = new Map<string, Promise<unknown>>();
+ // Keep failed writes too: disposal must not report durability after a disk error.
+ private readonly closeWrites = new Map<string, Promise<void>>();
+ private readonly reconciliation = new Map<string, Map<string, () => void>>();
+ constructor(private readonly options: SharedTaskHostOptions) {
+ const lifecycle: SharedTaskCreationState = options.creationState ?? { pending: new Map(), identities: new Map() };
+ this.creating = lifecycle.pending;
+ this.created = lifecycle.identities;
+ this.closedSessions = lifecycle.closedSessions ??= new Set();
+ this.sessionGenerations = lifecycle.sessionGenerations ??= new Map();
+ this.taskClosures = lifecycle.taskClosures ??= new Map();
+ }
+
+ private assertCurrent(): void {
+ if (this.disposed || this.boundaryClosed || !this.options.isCurrent()) throw new Error('SharedTask host generation changed');
+ }
+ private assertSessionGeneration(sessionId: string, generation: number): void {
+ this.assertCurrent();
+ if ((this.sessionGenerations.get(sessionId) ?? 0) !== generation) throw new Error('Shared task was closed');
+ }
+ private assertSessionOpen(sessionId: string, generation = this.sessionGenerations.get(sessionId) ?? 0): void {
+ this.assertSessionGeneration(sessionId, generation);
+ if (this.closedSessions.has(sessionId)) throw new Error('Shared task was closed');
+ }
+ private requireEntry(sharedTaskId: string): HostedSharedTask {
+ this.assertCurrent();
+ const entry = this.entries.get(sharedTaskId);
+ if (!entry || this.closed.has(sharedTaskId)) throw new Error('SharedTask is not active here');
+ return entry;
+ }
+ private serial<T>(sharedTaskId: string, work: () => Promise<T>): Promise<T> {
+ const result = (this.chains.get(sharedTaskId) ?? Promise.resolve()).catch(() => undefined).then(() => {
+ this.assertCurrent();
+ return work();
+ });
+ this.chains.set(sharedTaskId, result);
+ void result.finally(() => { if (this.chains.get(sharedTaskId) === result) this.chains.delete(sharedTaskId); }).catch(() => undefined);
+ return result;
+ }
+ private async accept(detail: SharedTaskDetail, generation: number): Promise<void> {
+ this.assertCurrent();
+ const snapshot = parseSharedTaskSnapshot(detail);
+ this.assertSessionOpen(snapshot.sessionId, generation);
+ if (snapshot.ownerAccountId !== this.options.ownerAccountId || snapshot.hostDeviceId !== this.options.hostDeviceId) throw new Error('SharedTask is not hosted by this device');
+ if (this.closed.has(snapshot.sharedTaskId)) throw new Error('SharedTask is closed locally');
+ const session = await this.options.readSession(snapshot.sessionId);
+ this.assertSessionOpen(snapshot.sessionId, generation);
+ if (!session || session.id !== snapshot.sessionId || session.status !== 'active') throw new Error('SharedTask task is unavailable');
+ const persisted = (await this.options.journal.latest()).find((item) => item.sharedTaskId === snapshot.sharedTaskId);
+ this.assertSessionOpen(snapshot.sessionId, generation);
+ if (persisted?.terminal || this.closed.has(snapshot.sharedTaskId)) throw new Error('SharedTask is closed locally');
+ if (persisted?.snapshot) {
+ const check = new SharedTaskAccess(persisted.snapshot);
+ check.applyVerifiedSnapshot(persisted.snapshot);
+ check.applyVerifiedSnapshot(snapshot);
+ if (persisted.snapshot.revision > snapshot.revision) return;
+ }
+ let entry = this.entries.get(snapshot.sharedTaskId);
+ if (entry) {
+ // Validate before writing a conflicting identity/revision into the journal.
+ for (const key of ['sharedTaskId', 'sessionId', 'ownerAccountId', 'hostDeviceId'] as const) {
+ if (entry.identity[key] !== snapshot[key]) throw new Error('SharedTask scope changed');
+ }
+ }
+ await this.options.journal.recordAuthority(snapshot);
+ this.assertSessionOpen(snapshot.sessionId, generation);
+ if (this.closed.has(snapshot.sharedTaskId)) return;
+ // A local close could have been persisted by another host callback while
+ // this write awaited; never treat a rejected insert as permission to grant.
+ const latest = (await this.options.journal.latest()).find((item) => item.sharedTaskId === snapshot.sharedTaskId);
+ this.assertSessionOpen(snapshot.sessionId, generation);
+ if (!latest || latest.terminal && snapshot.status !== 'closed' || this.closed.has(snapshot.sharedTaskId)) return;
+ if (!latest.snapshot || latest.snapshot.revision !== snapshot.revision) return;
+ if (!entry) {
+ entry = { identity: snapshot, access: new SharedTaskAccess(snapshot), detail: null };
+ this.entries.set(snapshot.sharedTaskId, entry);
+ }
+ if (entry.access.applyVerifiedSnapshot(snapshot) || entry.detail === null) {
+ for (const previous of entry.detail?.guests ?? []) {
+ const current = snapshot.guests.find((guest) => guest.memberId === previous.memberId);
+ // Adding another device invalidates old captures via member version,
+ // but does not revoke the existing devices or their subscriptions.
+ if (!current || previous.deviceIds.some((id) => !current.deviceIds.includes(id))) {
+ this.options.revoke(snapshot.sharedTaskId, previous.memberId);
+ }
+ }
+ entry.detail = detail;
+ if (snapshot.status === 'closed') {
+ entry.access.close();
+ this.closed.add(snapshot.sharedTaskId);
+ this.options.revoke(snapshot.sharedTaskId);
+ }
+ this.options.changed(snapshot.sharedTaskId);
+ }
+ }
+ private async refreshNow(sharedTaskId: string): Promise<void> {
+ this.assertCurrent();
+ const generations = new Map(this.sessionGenerations);
+ const detail = await this.options.api.get(sharedTaskId);
+ await this.accept(detail, generations.get(detail.sessionId) ?? 0);
+ for (const release of this.reconciliation.get(sharedTaskId)?.values() ?? []) release();
+ this.reconciliation.delete(sharedTaskId);
+ }
+ refresh(sharedTaskId: string): Promise<void> { return this.serial(sharedTaskId, () => this.refreshNow(sharedTaskId)); }
+
+ async open(sessionId: string): Promise<string> {
+ this.assertCurrent();
+ const generation = this.sessionGenerations.get(sessionId) ?? 0;
+ // An explicit open may re-share an unarchived task, only after the prior
+ // boundary has drained its creates and made their closures durable.
+ await this.taskClosures.get(sessionId);
+ this.assertSessionGeneration(sessionId, generation);
+ const session = await this.options.readSession(sessionId);
+ this.assertSessionGeneration(sessionId, generation);
+ if (!session || session.id !== sessionId || session.status !== 'active') throw new Error('SharedTask task is unavailable');
+ const journal = await this.options.journal.latest();
+ this.assertSessionGeneration(sessionId, generation);
+ // Server create is idempotent for an active task: close the previous IDs
+ // first, including closures inherited from another runtime or restart.
+ for (const item of journal) {
+ if (item.sessionId !== sessionId || !item.terminal) continue;
+ await this.options.api.close(item.sharedTaskId);
+ this.assertSessionGeneration(sessionId, generation);
+ }
+ this.closedSessions.delete(sessionId);
+ this.assertSessionOpen(sessionId, generation);
+ const rememberCreated = (sharedTaskId: string) => {
+ this.created.set(sharedTaskId, { sharedTaskId, sessionId, ownerAccountId: this.options.ownerAccountId, hostDeviceId: this.options.hostDeviceId });
+ };
+ const creating = this.options.api.create(sessionId, session.title, rememberCreated);
+ this.creating.set(creating, sessionId);
+ let created: Awaited<typeof creating>;
+ try {
+ created = await creating;
+ rememberCreated(created.sharedTaskId);
+ } finally { this.creating.delete(creating); }
+ if (this.boundaryClosed || this.closedSessions.has(sessionId)) {
+ // The boundary drains this request, journals the identity and closes it
+ // using outgoing credentials. Ordinary API scopes are already fenced.
+ throw new Error('Shared task was closed');
+ }
+ this.assertSessionOpen(sessionId, generation);
+ await this.serial(created.sharedTaskId, async () => {
+ const detail = await this.options.api.get(created.sharedTaskId);
+ if (detail.sessionId !== sessionId) throw new Error('SharedTask task does not match');
+ await this.accept(detail, generation);
+ });
+ const detail = this.entries.get(created.sharedTaskId)?.detail;
+ if (!detail || detail.sessionId !== sessionId || detail.status !== 'active') throw new Error('SharedTask could not be opened');
+ return created.sharedTaskId;
+ }
+
+ async restore(): Promise<void> {
+ this.assertCurrent();
+ const journal = await this.options.journal.latest();
+ this.assertCurrent();
+ const active = await this.options.api.list();
+ this.assertCurrent();
+ const owned = active.filter((item) => item.ownerAccountId === this.options.ownerAccountId && item.hostDeviceId === this.options.hostDeviceId);
+ for (const item of journal) {
+ if (item.terminal) this.closed.add(item.sharedTaskId);
+ else if (item.snapshot && !owned.some((sharedTask) => sharedTask.sharedTaskId === item.sharedTaskId)) {
+ this.closed.add(item.sharedTaskId);
+ this.entries.get(item.sharedTaskId)?.access.close();
+ this.options.revoke(item.sharedTaskId);
+ await this.options.journal.close(item.snapshot);
+ this.assertCurrent();
+ }
+ }
+ for (const item of owned) {
+ this.assertCurrent();
+ if (this.closed.has(item.sharedTaskId)) {
+ // Retry a previous explicit close that was persisted before connectivity
+ // failed. A process restart itself never closes an active sharedTask.
+ await this.options.api.close(item.sharedTaskId);
+ } else await this.refresh(item.sharedTaskId);
+ }
+ }
+
+ detail(sharedTaskId: string): SharedTaskDetail | null {
+ this.assertCurrent();
+ return this.entries.get(sharedTaskId)?.detail ?? null;
+ }
+ authorize(sharedTaskId: string, caller: SharedTaskCaller, sessionId: string, operation: string, queueItem?: SharedTaskQueueItem) {
+ if (this.disposed || !this.options.isCurrent() || this.closed.has(sharedTaskId)) return { allowed: false as const, reason: 'sharedTask-unavailable' as const };
+ return this.entries.get(sharedTaskId)?.access.authorize(caller, sessionId, operation, queueItem) ?? { allowed: false as const, reason: 'sharedTask-unavailable' as const };
+ }
+
+ invite(sharedTaskId: string) {
+ return this.serial(sharedTaskId, async () => {
+ this.requireEntry(sharedTaskId);
+ const invitation = await this.options.api.invite(sharedTaskId);
+ this.assertCurrent();
+ return invitation;
+ });
+ }
+ remove(sharedTaskId: string, memberId: string): Promise<void> {
+ const release = this.requireEntry(sharedTaskId).access.suspendMember(memberId);
+ // Suspend host reads/writes immediately. A failed request can leave this
+ // member authorized, so send permanent revocation only from fresh authority.
+ return this.serial(sharedTaskId, async () => {
+ try {
+ this.requireEntry(sharedTaskId);
+ await this.options.api.remove(sharedTaskId, memberId);
+ } finally {
+ // On an ambiguous timeout, regain permission only from a fresh authority
+ // response. If reconciliation also fails, this member stays suspended.
+ try {
+ await this.refreshNow(sharedTaskId);
+ release();
+ } catch (error) {
+ let pending = this.reconciliation.get(sharedTaskId);
+ if (!pending) this.reconciliation.set(sharedTaskId, pending = new Map());
+ const previous = pending.get(memberId);
+ pending.set(memberId, () => { previous?.(); release(); });
+ throw error;
+ }
+ }
+ });
+ }
+ close(sharedTaskId: string): Promise<void> {
+ this.assertCurrent();
+ const entry = this.entries.get(sharedTaskId);
+ if (!entry) throw new Error('SharedTask is not hosted here');
+ this.closed.add(sharedTaskId);
+ entry.access.close();
+ if (entry.detail) entry.detail = Object.freeze({ ...entry.detail, status: 'closed' });
+ // Start the profile-bound write before callbacks can dispose this host. It
+ // must not queue behind HTTP or be cancelled by an account generation check.
+ const persisted = this.options.journal.close(entry.identity);
+ this.closeWrites.set(sharedTaskId, persisted);
+ const closing = persisted.then(async () => {
+ this.assertCurrent();
+ await this.options.api.close(sharedTaskId);
+ });
+ this.options.revoke(sharedTaskId);
+ this.options.changed(sharedTaskId);
+ return closing;
+ }
+ /** A temporary authority fence is not evidence that membership was revoked. */
+ peerStatus(source: string): 'available' | 'unavailable' | 'revoked' {
+ const peer = parseSharedTaskPeer(source);
+ if (!peer || peer.role !== 'guest') return 'revoked';
+ if (this.closed.has(peer.sharedTaskId)) return 'revoked';
+ if (this.disposed || !this.options.isCurrent()) return 'unavailable';
+ const entry = this.entries.get(peer.sharedTaskId);
+ if (!entry?.detail) return 'unavailable';
+ if (this.boundaryClosed || this.closedSessions.has(entry.identity.sessionId)) return 'revoked';
+ const member = entry.detail.guests.find((guest) => guest.memberId === peer.memberId);
+ if (!member || !member.deviceIds.includes(peer.deviceId)) return 'revoked';
+ return entry.access.authorize({ accountId: member.accountId, deviceId: peer.deviceId },
+ entry.identity.sessionId, 'history.read').allowed ? 'available' : 'unavailable';
+ }
+
+ /** Only resolve relay-stamped logical peers against verified host authority. */
+ capturePeer(source: string) {
+ const peer = parseSharedTaskPeer(source);
+ if (!peer || peer.role !== 'guest' || this.disposed || !this.options.isCurrent()) return null;
+ const entry = this.entries.get(peer.sharedTaskId);
+ const member = entry?.detail?.guests.find((guest) => guest.memberId === peer.memberId);
+ if (!entry || !member || this.closed.has(peer.sharedTaskId)) return null;
+ const caller = Object.freeze({ accountId: member.accountId, deviceId: peer.deviceId });
+ const captured = entry.access.capture(caller, entry.identity.sessionId, 'history.read');
+ if (!captured.decision.allowed) return null;
+ const author = Object.freeze({
+ sharedTaskId: peer.sharedTaskId, sessionId: entry.identity.sessionId,
+ memberId: member.memberId, accountId: member.accountId,
+ displayName: entry.detail!.memberLabels.find((label) => label.memberId === member.memberId)?.displayName ?? member.accountId,
+ });
+ const isCurrent = () => !this.disposed && this.options.isCurrent() && captured.isCurrent();
+ return {
+ author, isCurrent,
+ authorize: (operation: string, queueItem?: SharedTaskQueueItem) =>
+ isCurrent() && entry.access.authorize(caller, author.sessionId, operation, queueItem).allowed,
+ };
+ }
+
+ activeSharedTaskIds(): string[] {
+ this.assertCurrent();
+ return [...this.entries].filter(([id, entry]) => !this.closed.has(id) && entry.detail?.status === 'active').map(([id]) => id);
+ }
+
+ /** Account teardown has already fenced network scopes. Durability must not depend on them. */
+ closeLocallyForBoundary(sessionId?: string): Promise<string[]> {
+ // Fence in-flight accept/open before the first journal await.
+ if (sessionId) {
+ this.closedSessions.add(sessionId);
+ this.sessionGenerations.set(sessionId, (this.sessionGenerations.get(sessionId) ?? 0) + 1);
+ }
+ else this.boundaryClosed = true;
+ let closing = this.persistBoundaryClosure(sessionId);
+ if (sessionId) {
+ const previous = this.taskClosures.get(sessionId);
+ if (previous) closing = Promise.all([previous, closing]).then((lists) => [...new Set(lists.flat())]);
+ this.taskClosures.set(sessionId, closing);
+ }
+ return closing;
+ }
+
+ private async persistBoundaryClosure(sessionId?: string): Promise<string[]> {
+ const identities = new Map<string, SharedTaskIdentity>();
+ for (const [id, entry] of this.entries) {
+ if (sessionId && entry.identity.sessionId !== sessionId) continue;
+ identities.set(id, entry.identity);
+ this.closed.add(id);
+ entry.access.close();
+ if (entry.detail) entry.detail = Object.freeze({ ...entry.detail, status: 'closed' });
+ this.options.revoke(id);
+ this.options.changed(id);
+ }
+ // Keep the outgoing profile alive through the existing bounded create
+ // requests. Their response observer runs before stale-scope rejection.
+ await Promise.allSettled([...this.creating].filter(([, sid]) => !sessionId || sid === sessionId).map(([pending]) => pending));
+ if (!sessionId) await Promise.all(this.taskClosures.values());
+ for (const [id, identity] of this.created) {
+ if (sessionId && identity.sessionId !== sessionId) continue;
+ identities.set(id, identity);
+ this.closed.add(id);
+ }
+ // Also close sharedTasks not restored yet (e.g. logout during authority fetch).
+ for (const item of await this.options.journal.latest()) {
+ if (item.terminal || !item.snapshot || sessionId && item.sessionId !== sessionId) continue;
+ if (item.snapshot.ownerAccountId !== this.options.ownerAccountId || item.snapshot.hostDeviceId !== this.options.hostDeviceId) continue;
+ identities.set(item.sharedTaskId, item.snapshot);
+ this.closed.add(item.sharedTaskId);
+ }
+ for (const [id, identity] of identities) {
+ const write = this.options.journal.close(identity);
+ this.closeWrites.set(id, write);
+ await write;
+ }
+ return [...identities.keys()];
+ }
+
+ /**
+ * Revokes synchronously. Await before releasing the old profile database or
+ * replacing this host; only local close writes drain, never HTTP requests.
+ * App exit itself does not close active sharedTasks.
+ */
+ async dispose(): Promise<void> {
+ this.disposed = true;
+ for (const [sharedTaskId, entry] of this.entries) {
+ entry.access.close();
+ this.options.revoke(sharedTaskId);
+ }
+ this.entries.clear();
+ const writes = await Promise.allSettled(this.closeWrites.values());
+ for (const write of writes) if (write.status === 'rejected') throw write.reason;
+ }
+}
diff --git a/apps/desktop/src/main/device-link/sharedTaskIpc.ts b/apps/desktop/src/main/device-link/sharedTaskIpc.ts
new file mode 100644
index 0000000000..795367622d
--- /dev/null
+++ b/apps/desktop/src/main/device-link/sharedTaskIpc.ts
@@ -0,0 +1,28 @@
+import { ipcMain } from 'electron';
+import { getCurrentUserId } from '../authManager.js';
+import { SHARED_TASK_ACCOUNT_CHANNEL, SHARED_TASK_HOST_CHANNEL } from '@cindy/device-link';
+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+import { getDeviceLinkInvokeContext } from './invoke-context.js';
+import { requireSharedTaskHost } from './sharedTaskRuntime.js';
+import { sharedTaskApi } from './sharedTaskApi.js';
+import { executeSharedTaskAccountCommand, executeSharedTaskHostCommand } from './sharedTaskCommands.js';
+
+/** Narrow Renderer adapter; account operations cannot be tunneled on somebody else's login. */
+export function registerSharedTaskIpc(available: () => boolean): void {
+ ipcMain.handle(SHARED_TASK_HOST_CHANNEL, async (event, raw: unknown) => {
+ const context = getDeviceLinkInvokeContext();
+ if (context?.sharedTask) throwIpcError('PERMISSION_DENIED', 'Only the sharedTask owner can manage members');
+ if (!context) assertTrustedAppRendererEvent(event);
+ return executeSharedTaskHostCommand(raw, { available, host: requireSharedTaskHost });
+ });
+ ipcMain.handle(SHARED_TASK_ACCOUNT_CHANNEL, async (event, raw: unknown) => {
+ if (getDeviceLinkInvokeContext()) throwIpcError('PERMISSION_DENIED', 'SharedTask account operations are local only');
+ assertTrustedAppRendererEvent(event);
+ if (!available()) throwIpcError('UNSUPPORTED_CAPABILITY', 'SharedTask mode requires updated clients and server');
+ return executeSharedTaskAccountCommand(raw, sharedTaskApi, getCurrentUserId() ?? undefined, {
+ hostedIds: () => { try { return requireSharedTaskHost().activeSharedTaskIds(); } catch { return []; } },
+ closeHosted: (sharedTaskId) => requireSharedTaskHost().close(sharedTaskId),
+ });
+ });
+}
diff --git a/apps/desktop/src/main/device-link/sharedTaskMediaAccess.ts b/apps/desktop/src/main/device-link/sharedTaskMediaAccess.ts
new file mode 100644
index 0000000000..dc1ba20128
--- /dev/null
+++ b/apps/desktop/src/main/device-link/sharedTaskMediaAccess.ts
@@ -0,0 +1,53 @@
+import path from 'node:path';
+import { realpath } from 'node:fs/promises';
+import { parseBlobUrl } from '../cindy-media/blobStore.js';
+import { sessionCanRead } from '../cindy-media/ledger.js';
+import { getSessionFsSnapshot } from '../localDb/ipc/sessions.js';
+import { getDbClient } from '../localDb/client/current.js';
+import type { SharedTaskPeerCapture } from './sharedTaskDispatch.js';
+
+function deny(): never { throw new Error('[PERMISSION_DENIED] Media does not belong to this shared task'); }
+
+/** Run before any local read/SSH transfer, and recheck membership after awaits. */
+export async function assertSharedTaskMedia(url: string, capture: SharedTaskPeerCapture): Promise<string | undefined> {
+ if (!capture.isCurrent() || !capture.authorize('attachment.read')) deny();
+ const sessionId = capture.author.sessionId;
+ const blob = parseBlobUrl(url);
+ if (blob) {
+ if (!await sessionCanRead(blob.hash, sessionId) || !capture.isCurrent()) deny();
+ return;
+ }
+ const parsed = new URL(url);
+ // Frozen legacy per-task cache, still resolved by the existing safe resolver.
+ if (parsed.protocol === 'xdt-image:' && decodeURIComponent(parsed.hostname) === sessionId) return;
+ if (parsed.protocol === 'xdt-video:' || parsed.protocol === 'xdt-image:') {
+ // Older generated caches predate the media ledger and use global hosts.
+ // Only a complete URL already emitted into this task's host-authored history
+ // grants access; guest/user text is not evidence of cache ownership.
+ const rows = await getDbClient().query<{ content: string }>(
+ "SELECT content FROM messages WHERE session_id = ? AND role IN ('assistant', 'tool_use', 'tool_result') AND instr(content, ?) > 0",
+ [sessionId, url],
+ );
+ const present = rows.some((row) => row.content.match(/xdt-(?:image|video):\/\/[^\s"'<>\x60\\)\]}]+/g)?.includes(url) === true);
+ if (!present || !capture.isCurrent()) deny();
+ return;
+ }
+ if (!['xdt-file:', 'xdt-audio:'].includes(parsed.protocol)) deny();
+ const snapshot = await getSessionFsSnapshot(sessionId);
+ if (!snapshot?.workingDir || !capture.isCurrent()) deny();
+ if (snapshot.remoteHostId) {
+ if (parsed.searchParams.get('sessionId') !== sessionId ||
+ parsed.searchParams.get('remoteHostId') !== snapshot.remoteHostId ||
+ parsed.searchParams.get('workdir') !== snapshot.workingDir) deny();
+ // The remote file-service stat/readFileChunk both check real ancestry under
+ // workdir (file-browser-core/scanner.ts); no controller-supplied root is used.
+ return;
+ }
+ if (parsed.searchParams.has('remoteHostId')) deny();
+ const requested = parsed.searchParams.get('path');
+ if (!requested || !path.isAbsolute(requested)) deny();
+ const [file, root] = await Promise.all([realpath(requested), realpath(snapshot.workingDir)]);
+ const relative = path.relative(root, file);
+ if (relative.startsWith('..') || path.isAbsolute(relative) || !capture.isCurrent()) deny();
+ return root;
+}
diff --git a/apps/desktop/src/main/device-link/sharedTaskMediaContext.ts b/apps/desktop/src/main/device-link/sharedTaskMediaContext.ts
new file mode 100644
index 0000000000..1db6a988c8
--- /dev/null
+++ b/apps/desktop/src/main/device-link/sharedTaskMediaContext.ts
@@ -0,0 +1,8 @@
+import { AsyncLocalStorage } from 'node:async_hooks';
+
+const scope = new AsyncLocalStorage<string>();
+/** Scope uploads for one trusted outbound call; never a global mutable flag. */
+export function withSharedTaskMedia<T>(sharedTaskId: string | undefined, work: () => T): T {
+ return sharedTaskId ? scope.run(sharedTaskId, work) : work();
+}
+export function sharedTaskMediaId(): string | undefined { return scope.getStore(); }
diff --git a/apps/desktop/src/main/device-link/sharedTaskRuntime.ts b/apps/desktop/src/main/device-link/sharedTaskRuntime.ts
new file mode 100644
index 0000000000..bcb9c51ca4
--- /dev/null
+++ b/apps/desktop/src/main/device-link/sharedTaskRuntime.ts
@@ -0,0 +1,137 @@
+import { SHARED_TASK_CAPABILITY, type DeviceLinkClient } from '@cindy/device-link';
+import { getCurrentDbClientSnapshot } from '../localDb/client/current.js';
+import { createSharedTaskJournal } from '../localDb/sharedTasks.js';
+import { activeOwnerScopeKey, getActiveAppSession, isAppSessionBoundaryPending } from '../appSessionState.js';
+import { getAuthState, getCurrentUserId, getDeviceId, getActiveAuthRealm } from '../authManager.js';
+import { createLogger } from '../logger.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+import { captureSharedTaskBoundaryClose, sharedTaskApi } from './sharedTaskApi.js';
+import { SharedTaskHost, type SharedTaskCreationState } from './sharedTaskHost.js';
+import { setSharedTaskDispatchHost } from './sharedTaskDispatch.js';
+
+const log = createLogger('shared-task');
+interface Binding {
+ host: SharedTaskHost;
+ stop(): Promise<void>;
+ dbEpoch: number;
+ database: object;
+ creationState: SharedTaskCreationState;
+ ownerAccountId: string;
+ region: ReturnType<typeof getActiveAuthRealm>;
+ current(): boolean;
+ rebindIfStable(): void;
+}
+let binding: Binding | null = null;
+let generation = 0;
+
+/** Binds verified authority to one relay owner, account, region and profile database. */
+export function startSharedTaskRuntime(options: {
+ client: DeviceLinkClient;
+ revoke(sharedTaskId: string, memberId?: string): void;
+ changed(sharedTaskId: string): void;
+}): void {
+ const previous = binding;
+ void previous?.stop().catch((error) => log.warn('sharedTask runtime disposal failed', error));
+ const db = getCurrentDbClientSnapshot();
+ const ownerAccountId = getCurrentUserId();
+ if (!db || !ownerAccountId) return;
+ const epoch = ++generation;
+ const scope = activeOwnerScopeKey();
+ const region = getActiveAuthRealm();
+ const creationState = previous?.database === db.client && previous.dbEpoch === db.clientEpoch &&
+ previous.ownerAccountId === ownerAccountId && previous.region === region
+ ? previous.creationState : { pending: new Map(), identities: new Map() };
+ let stopped = false;
+ let preservePeerLinks = false;
+ const current = () => !stopped && generation === epoch && getAuthState().isAuthenticated &&
+ getCurrentUserId() === ownerAccountId &&
+ !isAppSessionBoundaryPending() && activeOwnerScopeKey() === scope && getActiveAuthRealm() === region &&
+ getCurrentDbClientSnapshot()?.clientEpoch === db.clientEpoch;
+ const host = new SharedTaskHost({
+ api: sharedTaskApi, journal: createSharedTaskJournal(db.client),
+ ownerAccountId, hostDeviceId: getDeviceId(), creationState, isCurrent: current,
+ async readSession(sessionId) {
+ const rows = await db.client.query<{ id: string; title: string; status: string }>(
+ 'SELECT id, title, status FROM sessions WHERE id = ? LIMIT 1', [sessionId]);
+ return rows[0] ?? null;
+ },
+ revoke: (sharedTaskId, memberId) => {
+ // A stable projection recommit replaces authority captures, not members.
+ // Sending a permanent 'revoked' close here would strand valid guests.
+ if (!preservePeerLinks) options.revoke(sharedTaskId, memberId);
+ },
+ changed: options.changed,
+ });
+ let refreshing = false;
+ // A same-account stable projection can advance its generation without
+ // transferring the relay lease. Retire the old Host rather than relaxing
+ // its captured scope, so already-admitted callbacks remain invalid forever.
+ const rebindIfStable = () => {
+ if (stopped || generation !== epoch || binding?.host !== host || current() ||
+ isAppSessionBoundaryPending() || !getAuthState().isAuthenticated ||
+ getCurrentUserId() !== ownerAccountId || getActiveAuthRealm() !== region) return;
+ const active = getActiveAppSession();
+ const latestDb = getCurrentDbClientSnapshot();
+ if (active.mode !== 'cloud' || active.dataOwnerId !== ownerAccountId ||
+ latestDb?.client !== db.client || latestDb.clientEpoch !== db.clientEpoch ||
+ activeOwnerScopeKey() === scope) return;
+ preservePeerLinks = true;
+ startSharedTaskRuntime(options);
+ };
+ const refresh = async () => {
+ if (!current()) { rebindIfStable(); return; }
+ if (refreshing || !current() || !options.client.hasServerCapability(SHARED_TASK_CAPABILITY) ||
+ options.client.getStatus() !== 'online') return;
+ refreshing = true;
+ try { await host.restore(); }
+ catch { if (current()) log.debug('sharedTask authority refresh unavailable; retrying on next tick'); }
+ finally { refreshing = false; }
+ };
+ const timer = setInterval(() => { void refresh(); }, 5_000);
+ timer.unref?.();
+ binding = { host, dbEpoch: db.clientEpoch, database: db.client, creationState, ownerAccountId, region, current, rebindIfStable, stop() {
+ stopped = true;
+ clearInterval(timer);
+ if (binding?.host === host) setSharedTaskDispatchHost(null);
+ return host.dispose();
+ } };
+ setSharedTaskDispatchHost(host);
+ void refresh();
+}
+
+/** Ordinary process/relay ownership loss revokes live access but preserves membership. */
+export function stopSharedTaskRuntime(): Promise<void> {
+ return binding?.stop() ?? Promise.resolve();
+}
+
+export function requireSharedTaskHost(): SharedTaskHost {
+ binding?.rebindIfStable();
+ if (!binding?.current()) throwIpcError('PRECONDITION_FAILED', 'SharedTask host is unavailable');
+ return binding.host;
+}
+
+/** Must be awaited before disposing the outgoing profile; disk failure aborts handover. */
+export async function closeSharedTasksBeforeLogout(): Promise<void> {
+ const outgoing = binding;
+ if (!outgoing || outgoing.dbEpoch !== getCurrentDbClientSnapshot()?.clientEpoch) return;
+ const close = captureSharedTaskBoundaryClose(outgoing.ownerAccountId, outgoing.region);
+ const ids = await outgoing.host.closeLocallyForBoundary();
+ await outgoing.stop();
+ // Journal first; offline/expired credentials leave a durable retry for restore.
+ // Close concurrently under a bounded old-identity request before logout returns.
+ if (close) {
+ const results = await Promise.allSettled(ids.map((id) => close(id)));
+ if (results.some((result) => result.status === 'rejected')) {
+ log.debug('sharedTask boundary closure pending; retained journal for retry');
+ }
+ }
+}
+
+/** Terminal task state is durable before this runs; never reopen it on a later restore. */
+export async function closeSharedTaskForTask(sessionId: string, database: unknown): Promise<void> {
+ if (getCurrentDbClientSnapshot()?.client !== database) return;
+ if (!binding || binding.dbEpoch !== getCurrentDbClientSnapshot()?.clientEpoch) return;
+ const ids = await binding.host.closeLocallyForBoundary(sessionId);
+ // Network failure is retried from the terminal journal; never undo the task archive.
+ for (const id of ids) void sharedTaskApi.close(id).catch(() => undefined);
+}
diff --git a/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheOwner.test.ts b/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheOwner.test.ts
index 80a5eca2d1..a574845ac5 100644
--- a/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheOwner.test.ts
+++ b/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheOwner.test.ts
@@ -65,15 +65,19 @@ it('cancels the shared executor only after the last consumer releases it', async
const secondController = new AbortController();
let release!: () => void;
const pause = new Promise<void>((resolve) => { release = resolve; });
+ let started!: () => void;
+ const ready = new Promise<void>((resolve) => { started = resolve; });
let transferSignal!: AbortSignal;
const executor = vi.fn(async (dest: string, _progress: unknown, signal?: AbortSignal) => {
transferSignal = signal!;
await fs.writeFile(dest, 'old');
+ started();
await pause;
if (signal?.aborted) throw new Error('FILE_PEER_CANCELLED');
});
const first = fetchRemoteFileToCache(id, executor, vi.fn(), firstController.signal);
- await vi.waitFor(() => expect(executor).toHaveBeenCalledOnce());
+ await ready;
+ expect(executor).toHaveBeenCalledOnce();
const second = fetchRemoteFileToCache(id, executor, vi.fn(), secondController.signal);
firstController.abort();
await expect(first).rejects.toThrow('FILE_PEER_CANCELLED');
diff --git a/apps/desktop/src/main/localDb/__tests__/sharedTasks.test.ts b/apps/desktop/src/main/localDb/__tests__/sharedTasks.test.ts
new file mode 100644
index 0000000000..a670d7fa8e
--- /dev/null
+++ b/apps/desktop/src/main/localDb/__tests__/sharedTasks.test.ts
@@ -0,0 +1,92 @@
+import Database from 'better-sqlite3';
+import { readFileSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import { resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { createSharedTaskJournal } from '../sharedTasks.js';
+import type { SharedTaskSnapshot } from '@cindy/device-link';
+
+const snapshot = (revision = 1): SharedTaskSnapshot => ({
+ sharedTaskId: 'sharedTask', sessionId: 'session', ownerAccountId: 'owner', hostDeviceId: 'desktop',
+ revision, status: 'active', guests: [{ memberId: 'member', accountId: 'guest', version: 1, deviceIds: ['phone'] }],
+});
+let db: Database.Database;
+let journal: ReturnType<typeof createSharedTaskJournal>;
+beforeEach(() => {
+ db = new Database(':memory:');
+ db.pragma('foreign_keys = ON');
+ db.exec("CREATE TABLE sessions (id TEXT PRIMARY KEY); INSERT INTO sessions VALUES ('session'), ('other-session')");
+ db.exec(readFileSync(resolve(process.cwd(), 'drizzle/0114_shared_task_events.sql'), 'utf8'));
+ journal = createSharedTaskJournal({
+ async exec(sql, params = []) { return db.prepare(sql).run(...params); },
+ async query<T>(sql: string, params: unknown[] = []) { return db.prepare(sql).all(...params) as T[]; },
+ });
+});
+afterEach(() => db.close());
+
+it('moves development-era records and author metadata without rewriting message content', async () => {
+ db.exec(`
+ CREATE TABLE session_meeting_events (id INTEGER PRIMARY KEY, meeting_id TEXT, session_id TEXT,
+ revision INTEGER, kind TEXT, terminal INTEGER, snapshot TEXT, recorded_at INTEGER);
+ CREATE TABLE messages (agent_meta TEXT, content TEXT);
+ CREATE TABLE agent_input_queue_snapshots (payload TEXT);
+ `);
+ const legacy = { ...snapshot(), meetingId: 'legacy-share', sharedTaskId: undefined };
+ db.prepare("INSERT INTO session_meeting_events VALUES (1, 'legacy-share', 'session', 1, 'authority', 0, ?, 123)")
+ .run(JSON.stringify(legacy));
+ const author = { meetingId: 'legacy-share', sessionId: 'session', memberId: 'member', accountId: 'guest', displayName: 'Guest' };
+ const content = 'User text: meetingId and meetingAuthor must stay verbatim';
+ db.prepare('INSERT INTO messages VALUES (?, ?)').run(JSON.stringify({ meetingAuthor: author, uuid: 'message' }), content);
+ db.prepare('INSERT INTO messages VALUES (?, ?)').run('invalid legacy JSON', content);
+ db.prepare('INSERT INTO agent_input_queue_snapshots VALUES (?)').run(JSON.stringify([{ meetingAuthor: author, text: content }]));
+ const { run } = createRequire(import.meta.url)(resolve(process.cwd(), 'drizzle/scripts/0114_shared_task_events.ts'));
+ run(db);
+ run(db);
+ expect(await journal.latest()).toMatchObject([{ sharedTaskId: 'legacy-share', snapshot: { sharedTaskId: 'legacy-share' } }]);
+ expect(db.prepare("SELECT name FROM sqlite_master WHERE name = 'session_meeting_events'").get()).toBeUndefined();
+ const message = db.prepare('SELECT * FROM messages LIMIT 1').get() as { agent_meta: string; content: string };
+ expect(message.content).toBe(content);
+ expect(JSON.parse(message.agent_meta)).toEqual({ uuid: 'message', sharedTaskAuthor: { ...author, meetingId: undefined, sharedTaskId: 'legacy-share' } });
+ const queue = db.prepare('SELECT payload FROM agent_input_queue_snapshots').get() as { payload: string };
+ expect(JSON.parse(queue.payload)[0]).toMatchObject({ text: content, sharedTaskAuthor: { sharedTaskId: 'legacy-share' } });
+ expect(db.prepare('SELECT agent_meta FROM messages WHERE rowid = 2').get()).toEqual({ agent_meta: 'invalid legacy JSON' });
+});
+describe('sharedTask authority journal', () => {
+ it('retains membership changes and reads only the latest authority', async () => {
+ expect(await journal.recordAuthority(snapshot())).toBe(true);
+ expect(await journal.recordAuthority({ ...snapshot(2), guests: [] })).toBe(true);
+ expect(db.prepare('SELECT COUNT(*) AS n FROM shared_task_events').get()).toEqual({ n: 2 });
+ expect(await journal.latest()).toMatchObject([{ snapshot: { revision: 2, guests: [] }, terminal: false }]);
+ });
+ it('ignores stale and duplicate revisions without losing audit history', async () => {
+ await journal.recordAuthority(snapshot(2));
+ expect(await journal.recordAuthority(snapshot())).toBe(false);
+ expect(await journal.recordAuthority(snapshot(2))).toBe(false);
+ expect(await journal.latest()).toMatchObject([{ snapshot: { revision: 2 } }]);
+ });
+ it('does not let another task reuse a sharedTask identity', async () => {
+ await journal.recordAuthority(snapshot());
+ expect(await journal.recordAuthority({ ...snapshot(2), sessionId: 'other-session' })).toBe(false);
+ await journal.close({ ...snapshot(), sessionId: 'other-session' });
+ expect(await journal.latest()).toMatchObject([{ sessionId: 'session', terminal: false }]);
+ });
+ it.each(['local', 'server'])('keeps a %s closure terminal when late replies arrive', async (source) => {
+ await journal.recordAuthority(snapshot());
+ if (source === 'local') { await journal.close(snapshot()); await journal.close(snapshot()); }
+ else await journal.recordAuthority({ ...snapshot(2), status: 'closed' });
+ expect(await journal.recordAuthority(snapshot(20))).toBe(false);
+ expect(await journal.latest()).toMatchObject([{ terminal: true }]);
+ });
+ it('allows a fresh sharedTask for the same task after closing the previous one', async () => {
+ await journal.close(snapshot());
+ expect(await journal.recordAuthority({ ...snapshot(), sharedTaskId: 'new-sharedTask' })).toBe(true);
+ expect(await journal.latest()).toHaveLength(2);
+ });
+ it('cascades journal deletion only with its owning task', async () => {
+ await journal.recordAuthority(snapshot());
+ db.prepare("DELETE FROM sessions WHERE id = 'other-session'").run();
+ expect(await journal.latest()).toHaveLength(1);
+ db.prepare("DELETE FROM sessions WHERE id = 'session'").run();
+ expect(await journal.latest()).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
index a765d9585e..44c9333934 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
@@ -33,6 +33,7 @@ const h = vi.hoisted(() => ({
persistedSdkSessionId: null,
})),
closeSession: vi.fn(async (_sessionId: string) => undefined),
+ closeSharedTask: vi.fn(async (_sessionId: string, _database: unknown): Promise<void> => undefined),
tapWindowBroadcast: vi.fn(),
windows: [] as Array<{
trusted?: boolean;
@@ -109,6 +110,9 @@ vi.mock('../../../git-context/prRefsStore', () => ({
recomputePrRefsForSession: vi.fn(async () => undefined),
}));
vi.mock('../../../imageCacheStore', () => ({ removeSession: vi.fn(async () => undefined) }));
+vi.mock('../../../device-link/sharedTaskRuntime.js', () => ({
+ closeSharedTaskForTask: h.closeSharedTask,
+}));
vi.mock('../recentWorkdirs', () => ({ upsertRecentWorkdir: h.upsertRecentWorkdir }));
vi.mock('../../../device-link/broadcast-tap.js', () => ({
captureDataOwnerBroadcastScope: vi.fn(() =>
@@ -860,6 +864,7 @@ describe('local-db:sessions:update handler wiring', () => {
it('cleans runtime state before releasing the local terminal status lock', async () => {
const order: string[] = [];
h.runtimeCleanup.mockImplementationOnce(() => order.push('runtime-cleanup'));
+ h.closeSharedTask.mockImplementationOnce(async () => { order.push('sharing-closed'); });
h.routeLock.mockImplementationOnce(async (_sessionId, task) => {
const result = await task();
order.push('lock-released');
@@ -869,13 +874,15 @@ describe('local-db:sessions:update handler wiring', () => {
await invokeUpdate('codex-local', { status: 'archived' });
- expect(order).toEqual(['runtime-cleanup', 'lock-released']);
+ expect(order).toEqual(['runtime-cleanup', 'sharing-closed', 'lock-released']);
expect(h.runtimeCleanup).toHaveBeenCalledOnce();
+ expect(h.closeSharedTask).toHaveBeenCalledWith('codex-local', h.client);
});
it('cleans runtime state before releasing the remote terminal status lock', async () => {
const order: string[] = [];
h.runtimeCleanup.mockImplementationOnce(() => order.push('runtime-cleanup'));
+ h.closeSharedTask.mockImplementationOnce(async () => { order.push('sharing-closed'); });
h.routeLock.mockImplementationOnce(async (_sessionId, task) => {
const result = await task();
order.push('lock-released');
@@ -885,8 +892,9 @@ describe('local-db:sessions:update handler wiring', () => {
await patchSessionMetaInDb('codex-local', { status: 'archived' });
- expect(order).toEqual(['runtime-cleanup', 'lock-released']);
+ expect(order).toEqual(['runtime-cleanup', 'sharing-closed', 'lock-released']);
expect(h.runtimeCleanup).toHaveBeenCalledOnce();
+ expect(h.closeSharedTask).toHaveBeenCalledWith('codex-local', h.client);
});
// 竞态收敛(review on #3225):写入与查询不在同一串行区间,归档写入后、查询前
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 123790e029..60a15aee2a 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -1921,6 +1921,10 @@ export async function updateSessionInDb(
moveGuard?.assertCurrent();
await writeSessionPatch(db, sid, setObj, p.status);
cleanupSessionRuntimeForTerminalStatus(sid, p.status);
+ if (p.status === 'archived' || p.status === 'deleted') {
+ const { closeSharedTaskForTask } = await import('../../device-link/sharedTaskRuntime.js');
+ await closeSharedTaskForTask(sid, dbClient);
+ }
},
p.workingDir !== undefined,
);
@@ -2088,6 +2092,10 @@ export async function patchSessionMetaInDb(
row.summary = null;
}
cleanupSessionRuntimeForTerminalStatus(sessionId, patch.status);
+ if (patch.status === 'archived' || patch.status === 'deleted') {
+ const { closeSharedTaskForTask } = await import('../../device-link/sharedTaskRuntime.js');
+ await closeSharedTaskForTask(sessionId, dbClient);
+ }
return sessionToCamel(row);
});
notifyAgentIslandSessionPatch(updated.id, {
@@ -2286,6 +2294,10 @@ export async function setSessionsStatusInDb(
});
for (const item of rows) {
cleanupSessionRuntimeForTerminalStatus(item.sessionId, item.status);
+ if (item.status === 'archived') {
+ const { closeSharedTaskForTask } = await import('../../device-link/sharedTaskRuntime.js');
+ await closeSharedTaskForTask(item.sessionId, dbClient);
+ }
}
for (const resource of physicalResources) notifyWorktreeRecycleOpportunity(resource);
return rows;
diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.ts
index 8a70d158b4..b78b8b1c1c 100644
--- a/apps/desktop/src/main/localDb/schema.ts
+++ b/apps/desktop/src/main/localDb/schema.ts
@@ -20,6 +20,21 @@ import {
import type { SessionSource } from '../../shared/sessionSource.js';
+/** Per-profile authority journal. Snapshots are recovery/audit data, not offline grants. */
+export const sharedTaskEvents = sqliteTable('shared_task_events', {
+ id: integer('id').primaryKey({ autoIncrement: true }),
+ sharedTaskId: text('shared_task_id').notNull(),
+ sessionId: text('session_id').notNull().references((): AnySQLiteColumn => sessions.id, { onDelete: 'cascade' }),
+ revision: integer('revision').notNull(),
+ kind: text('kind', { enum: ['authority', 'local-close'] }).notNull(),
+ terminal: integer('terminal', { mode: 'boolean' }).notNull(),
+ snapshot: text('snapshot'),
+ recordedAt: integer('recorded_at').notNull(),
+}, (table) => ({
+ uniqueRevision: uniqueIndex('shared_task_events_revision_idx').on(table.sharedTaskId, table.kind, table.revision),
+ bySession: index('shared_task_events_session_idx').on(table.sessionId, table.id),
+}));
+
const SESSION_SOURCES = [
'desktop',
'feishu',
diff --git a/apps/desktop/src/main/localDb/sharedTasks.ts b/apps/desktop/src/main/localDb/sharedTasks.ts
new file mode 100644
index 0000000000..8baa2304ed
--- /dev/null
+++ b/apps/desktop/src/main/localDb/sharedTasks.ts
@@ -0,0 +1,55 @@
+import { parseSharedTaskSnapshot, type SharedTaskIdentity, type SharedTaskSnapshot } from '@cindy/device-link';
+import type { DbClient } from './client/DbClient.js';
+
+export interface SharedTaskJournalEntry {
+ sharedTaskId: string;
+ sessionId: string;
+ terminal: boolean;
+ snapshot: SharedTaskSnapshot | null;
+}
+
+/** Bound to one profile's DbClient; never resolves a different account after an await. */
+export function createSharedTaskJournal(db: Pick<DbClient, 'exec' | 'query'>, now: () => number = Date.now) {
+ return {
+ async recordAuthority(value: SharedTaskSnapshot): Promise<boolean> {
+ const snapshot = parseSharedTaskSnapshot(value);
+ // A single atomic statement records both the recovery snapshot and its
+ // membership audit entry. A terminal record permanently fences late replies.
+ const result = await db.exec(`
+ INSERT INTO shared_task_events (shared_task_id, session_id, revision, kind, terminal, snapshot, recorded_at)
+ SELECT ?, ?, ?, 'authority', ?, ?, ?
+ WHERE NOT EXISTS (
+ SELECT 1 FROM shared_task_events
+ WHERE shared_task_id = ? AND (terminal = 1 OR session_id <> ? OR revision >= ?)
+ )
+ ON CONFLICT (shared_task_id, kind, revision) DO NOTHING
+ `, [snapshot.sharedTaskId, snapshot.sessionId, snapshot.revision, snapshot.status === 'closed' ? 1 : 0,
+ JSON.stringify(snapshot), now(), snapshot.sharedTaskId, snapshot.sessionId, snapshot.revision]);
+ return result.changes > 0;
+ },
+ async close(identity: SharedTaskIdentity): Promise<void> {
+ // Revision zero is reserved for a local closure, not a server revision.
+ // Never manufacture a higher authority revision from the local clock.
+ const checked = parseSharedTaskSnapshot({ ...identity, revision: 1, status: 'closed', guests: [] });
+ await db.exec(`
+ INSERT INTO shared_task_events (shared_task_id, session_id, revision, kind, terminal, snapshot, recorded_at)
+ SELECT ?, ?, 0, 'local-close', 1, NULL, ?
+ WHERE NOT EXISTS (SELECT 1 FROM shared_task_events WHERE shared_task_id = ? AND session_id <> ?)
+ ON CONFLICT (shared_task_id, kind, revision) DO NOTHING
+ `, [checked.sharedTaskId, checked.sessionId, now(), checked.sharedTaskId, checked.sessionId]);
+ },
+ async latest(): Promise<SharedTaskJournalEntry[]> {
+ const rows = await db.query<{ shared_task_id: string; session_id: string; terminal: number; snapshot: string | null }>(`
+ SELECT shared_task_id, session_id, terminal, snapshot FROM shared_task_events
+ WHERE id IN (SELECT MAX(id) FROM shared_task_events GROUP BY shared_task_id)
+ `);
+ return rows.map((row) => {
+ const snapshot = row.snapshot === null ? null : parseSharedTaskSnapshot(JSON.parse(row.snapshot));
+ if (snapshot && (snapshot.sharedTaskId !== row.shared_task_id || snapshot.sessionId !== row.session_id)) throw new Error('SharedTask journal scope mismatch');
+ return { sharedTaskId: row.shared_task_id, sessionId: row.session_id, terminal: row.terminal === 1, snapshot };
+ });
+ },
+ };
+}
+
+export type SharedTaskJournal = ReturnType<typeof createSharedTaskJournal>;
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index 1f0c731cbc..342fa7c9f0 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -208,6 +208,22 @@ describe('AgentInputCoordinator Orca priority queue transactions', () => {
);
});
+ it('retains host-stamped sharedTask attribution when the queue drains outside the original invoke', async () => {
+ const h = createHarness();
+ const sid = 'sharedTask-task';
+ const author = { sharedTaskId: 'sharedTask', sessionId: sid, memberId: 'member', accountId: 'guest', displayName: 'Guest' };
+ h.setRunning(true);
+ h.coordinator.enqueue(sid, makeItem('sharedTask-input', 'hello', { sharedTaskAuthor: author, userName: author.displayName }));
+ expect(h.coordinator.getProjection(sid).pendingQueue[0].sharedTaskAuthor).toEqual(author);
+ h.setRunning(false);
+ h.coordinator.resume(sid);
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledWith(
+ sid, expect.anything(), expect.anything(),
+ expect.objectContaining({ userName: 'Guest', persistUserMessage: expect.objectContaining({ sharedTaskAuthor: author }) }),
+ );
+ });
+
it('restores first, reserves at the head with a host stamp, deduplicates, and emits once', async () => {
const h = createHarness();
const sid = 'priority-worker';
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sharedTaskContextUsage.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sharedTaskContextUsage.test.ts
new file mode 100644
index 0000000000..9e140f3f36
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sharedTaskContextUsage.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it, vi } from 'vitest';
+import { createSharedTaskContextUsageGuard } from '../sharedTaskContextUsage.js';
+import type { SharedTaskPeerCapture } from '../../device-link/sharedTaskDispatch.js';
+
+const capture: SharedTaskPeerCapture = {
+ author: { sharedTaskId: 'sharedTask', sessionId: 'task', memberId: 'member', accountId: 'guest', displayName: 'Guest' },
+ isCurrent: () => true,
+ authorize: () => true,
+};
+
+describe('shared task context usage cold-start authority', () => {
+ it.each(['ask', 'bypassPermissions'])('uses only the host snapshot, preserving host mode %s', async (permissionMode) => {
+ const guard = createSharedTaskContextUsageGuard(capture, 'task');
+ const malicious = { permissionMode: 'bypassPermissions', workingDir: '/private', remoteHostId: 'other-host',
+ extraDirs: ['/secrets'], writableDirs: ['/'], vendorOptions: { executable: 'untrusted' } };
+ const host = { permissionMode, workingDir: '/task', remoteHostId: 'task-host',
+ extraDirs: ['/allowed'], writableDirs: ['/task'], model: 'saved-model', planMode: false };
+ const resolved = await guard.resolveCreateOpts(malicious, async () => host);
+ expect(resolved).toEqual(host);
+ expect(resolved).not.toHaveProperty('vendorOptions');
+ });
+
+ it('does not even read guest option getters and permits host-driven cold queries without wire options', async () => {
+ const guard = createSharedTaskContextUsageGuard(capture, 'task');
+ const malicious = Object.defineProperty({}, 'workingDir', { enumerable: true, get() { throw new Error('wire touched'); } });
+ const host = { workingDir: '/task' };
+ expect(await guard.resolveCreateOpts(malicious, async () => host)).toBe(host);
+ expect(await guard.resolveCreateOpts(undefined, async () => host)).toBe(host);
+ });
+
+ it('fails closed when host state cannot be read', async () => {
+ const guard = createSharedTaskContextUsageGuard(capture, 'task');
+ await expect(guard.resolveCreateOpts({ workingDir: '/untrusted' }, async () => { throw new Error('DB unavailable'); }))
+ .rejects.toThrow('DB unavailable');
+ });
+
+ it('rejects cross-task and revoked requests before reading the task', async () => {
+ const read = vi.fn(async () => ({}));
+ for (const guard of [
+ createSharedTaskContextUsageGuard(capture, 'other-task'),
+ createSharedTaskContextUsageGuard({ ...capture, isCurrent: () => false }, 'task'),
+ createSharedTaskContextUsageGuard({ ...capture, authorize: () => false }, 'task'),
+ ]) await expect(guard.resolveCreateOpts({}, read)).rejects.toThrow('PERMISSION_DENIED');
+ expect(read).not.toHaveBeenCalled();
+ });
+
+ it('rejects revocation during the DB read and again before a delayed bootstrap side effect', async () => {
+ let current = true;
+ const guard = createSharedTaskContextUsageGuard({ ...capture, isCurrent: () => current }, 'task');
+ await expect(guard.resolveCreateOpts({}, async () => { current = false; return {}; })).rejects.toThrow('PERMISSION_DENIED');
+ current = true;
+ await guard.resolveCreateOpts({}, async () => ({}));
+ current = false;
+ const start = vi.fn();
+ expect(() => { guard.assertCurrent(); start(); }).toThrow('PERMISSION_DENIED');
+ expect(start).not.toHaveBeenCalled();
+ });
+
+ it('preserves ordinary local and same-account remote options without a DB lookup', async () => {
+ const guard = createSharedTaskContextUsageGuard(undefined, 'task');
+ const read = vi.fn(async () => ({}));
+ const wire = { workingDir: '/owner-task' };
+ expect(await guard.resolveCreateOpts(wire, read)).toBe(wire);
+ expect(await guard.resolveCreateOpts(undefined, read)).toBeUndefined();
+ expect(read).not.toHaveBeenCalled();
+ expect(guard.assertCurrent).not.toThrow();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sharedTaskInput.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sharedTaskInput.test.ts
new file mode 100644
index 0000000000..5033045df7
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sharedTaskInput.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from 'vitest';
+import { stampSharedTaskInput, assertSharedTaskQueueMutation } from '../sharedTaskInput.js';
+import type { SharedTaskPeerCapture } from '../../device-link/sharedTaskDispatch.js';
+import type { AgentInputQueuedMessage } from '../../../shared/agentInputQueue.js';
+
+const author = { sharedTaskId: 'sharedTask', sessionId: 'task', memberId: 'guest-id', accountId: 'guest', displayName: 'Guest' };
+const capture: SharedTaskPeerCapture = { author, isCurrent: () => true, authorize: () => true };
+const item = { clientId: 'message', text: 'hello', persistedContent: 'hello',
+ permissionMode: 'bypassPermissions', workingDir: 'untrusted', model: 'untrusted', effort: 'untrusted',
+ createOpts: { agentKind: 'pi', workingDir: 'untrusted', permissionMode: 'bypassPermissions', model: 'untrusted', vendorOptions: { extraDirs: ['private'] } },
+ vendorOptions: { extraDirs: ['private'] }, userName: 'Owner',
+ chatMessage: { clientId: 'message', role: 'user', content: 'hello' },
+} satisfies AgentInputQueuedMessage;
+
+describe('sharedTask input uses the task Agent authority', () => {
+ it.each(['ask', 'bypassPermissions'])('keeps the host permission mode %s, without a guest policy', (permissionMode) => {
+ const task = { agentKind: 'pi' as const, workingDir: 'host-workdir', model: 'host-model', permissionMode };
+ const result = stampSharedTaskInput(item, capture, task);
+ expect(result.createOpts).toEqual(task);
+ expect(result.permissionMode).toBe(permissionMode);
+ expect(result.workingDir).toBe('host-workdir');
+ expect(result).not.toHaveProperty('vendorOptions');
+ expect(result).not.toHaveProperty('turnPermissionPolicy');
+ expect(result.sharedTaskAuthor).toEqual(author);
+ expect(result.userName).toBe('Guest');
+ });
+ it('strips a forged author from ordinary local input and rejects revoked preparation', () => {
+ expect(stampSharedTaskInput({ ...item, sharedTaskAuthor: author }, undefined, undefined)).not.toHaveProperty('sharedTaskAuthor');
+ expect(() => stampSharedTaskInput(item, { ...capture, isCurrent: () => false }, item.createOpts)).toThrow();
+ });
+ it('allows editing only the original membership own pending message, rechecking revocation', () => {
+ const owned = { ...item, sharedTaskAuthor: author };
+ expect(() => assertSharedTaskQueueMutation(capture, 'task', 'input.edit', owned)).not.toThrow();
+ expect(() => assertSharedTaskQueueMutation(capture, 'task', 'input.withdraw', item)).toThrow();
+ expect(() => assertSharedTaskQueueMutation(capture, 'task', 'input.edit', { ...owned, sharedTaskAuthor: { ...author, memberId: 'retired-member' } })).toThrow();
+ expect(() => assertSharedTaskQueueMutation({ ...capture, isCurrent: () => false }, 'task', 'input.edit', owned)).toThrow();
+ expect(() => assertSharedTaskQueueMutation(undefined, 'task', 'input.edit', owned)).not.toThrow();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sharedTaskSetting.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sharedTaskSetting.test.ts
new file mode 100644
index 0000000000..b52d01987d
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sharedTaskSetting.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it, vi } from 'vitest';
+import { createSharedTaskSettingGuard } from '../sharedTaskSetting.js';
+import { applyRuntimeSetModelChange } from '../runtimeSetModel.js';
+import { commitRuntimeAxisAfterPersistence } from '../runtimeSelectionAxes.js';
+
+function harness() {
+ let current = true;
+ const transaction = { admitted: false };
+ const guard = createSharedTaskSettingGuard({
+ author: { sharedTaskId: 'sharedTask', sessionId: 'task', memberId: 'guest', accountId: 'account', displayName: 'Guest' },
+ isCurrent: () => current, authorize: () => current,
+ }, 'task', transaction);
+ return { guard, transaction, revoke() { current = false; } };
+}
+describe('sharedTask setting admission', () => {
+ it('rechecks membership after async model preflight, before any runtime change', async () => {
+ const h = harness();
+ const setModel = vi.fn();
+ const closeSession = vi.fn();
+ let resolve!: (value: boolean) => void;
+ const session = { agentKind: 'claude-code' as const, model: 'old', setModel,
+ requiresModelSwitchRebuild: () => new Promise<boolean>((done) => { resolve = done; }) };
+ const run = applyRuntimeSetModelChange({
+ maker: { getSession: () => session, listActiveSessions: () => [], closeSession },
+ sessionId: 'task', model: 'new', admit: h.guard.admit,
+ });
+ h.revoke();
+ resolve(false);
+ await expect(run).rejects.toThrow('SharedTask task access denied');
+ expect(setModel).not.toHaveBeenCalled();
+ expect(closeSession).not.toHaveBeenCalled();
+ });
+ it('finishes persistence of an admitted native operation after removal', async () => {
+ const h = harness();
+ h.guard.admit();
+ h.revoke();
+ const commit = vi.fn();
+ await commitRuntimeAxisAfterPersistence({
+ persist: async () => { h.guard(); }, commit, assertCanCommit: h.guard,
+ });
+ expect(commit).toHaveBeenCalledOnce();
+ });
+ it('does not block recovery when persistence fails after an admitted operation', async () => {
+ const h = harness();
+ h.guard.admit();
+ h.revoke();
+ const recover = vi.fn(async () => {});
+ const commit = vi.fn();
+ await expect(commitRuntimeAxisAfterPersistence({
+ persist: async () => { throw new Error('disk failed'); }, commit,
+ assertCanCommit: h.guard, recoverAfterPersistenceFailure: recover,
+ })).rejects.toThrow('disk failed');
+ expect(recover).toHaveBeenCalledOnce();
+ expect(commit).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index 7307917d83..8f958e2a2e 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -1,4 +1,6 @@
import { AUTO_REVIEW_SOURCE_CONTENT, AUTO_REVIEW_USER_INTENT } from '@cindy/maker-core';
+import { getDeviceLinkInvokeContext } from '../device-link/invoke-context.js';
+import { assertSharedTaskQueueMutation } from './sharedTaskInput.js';
/**
* AgentInputCoordinator — main 侧排队输入事务协调器。
*
@@ -227,6 +229,7 @@ export interface AgentInputSendOpts {
/** Session reservation 时回调本轮 vendor generation;必须在 send 返回前绑定 leftover。 */
onVendorTurnReserved?: (generation: number) => void;
persistUserMessage?: {
+ sharedTaskAuthor?: AgentInputQueuedMessage['sharedTaskAuthor'];
clientId: string;
content: string;
/** Overflow 重放用的 agent-facing wire payload(mention / 标注附件等)。 */
@@ -1543,6 +1546,7 @@ export class AgentInputCoordinator {
): AgentInputProjection {
const state = this.getState(sessionId);
item = captureOriginalSyntheticTrigger(item);
+ assertSharedTaskQueueMutation(getDeviceLinkInvokeContext()?.sharedTask, sessionId, 'input.send');
// 幂等去重(弱网重发防线,PR #881):同 clientId 重复投递说明是控制端(手机
// 断连自动重试 / 用户对 ack 丢失的消息重发)在补发同一条消息,不是新消息。
// 直接返回当前 projection、不再入队——否则同一条消息双入队、agent 跑两轮。
@@ -1948,6 +1952,8 @@ export class AgentInputCoordinator {
(opts?.expectedTurnGeneration === undefined ||
this.deps.getTurnGeneration?.(sessionId) === opts.expectedTurnGeneration);
if (!matchesExpectedTurn()) return false;
+ const sharedTask = getDeviceLinkInvokeContext()?.sharedTask;
+ assertSharedTaskQueueMutation(sharedTask, sessionId, 'input.send');
const state = this.getState(sessionId);
// Capture the clear boundary before any screening/reference/steer await. The
// live state may advance when `/clear` wins the race; this turn must retain
@@ -1957,6 +1963,7 @@ export class AgentInputCoordinator {
let steersStoredQueueItem = false;
if (opts?.removeFromQueue) {
const storedItem = state.pendingQueue.find((queued) => queued.clientId === item.clientId);
+ if (sharedTask) assertSharedTaskQueueMutation(sharedTask, sessionId, 'input.edit', storedItem);
if (storedItem) {
steersStoredQueueItem = true;
// Renderer projections intentionally omit trusted reference bodies. The main-owned
@@ -2169,6 +2176,7 @@ export class AgentInputCoordinator {
referenceContexts,
);
await this.deps.steerToAgent(sessionId, buildMakerUserMessage(item, referenceContexts), {
+ ...(item.sharedTaskAuthor ? { sharedTaskAuthor: item.sharedTaskAuthor } : {}),
[AUTO_REVIEW_SOURCE_CONTENT]: item.autoReviewUserText ?? '',
...(readAutoReviewUserText(item.persistedContent) === null
? { [AUTO_REVIEW_USER_INTENT]: item.autoReviewUserText ?? '' } : {}),
@@ -2518,6 +2526,9 @@ export class AgentInputCoordinator {
sessionId: string,
opts?: { keepQueue?: boolean; pauseQueue?: boolean; resumeOnUserInput?: boolean },
): AgentInputProjection {
+ const sharedTask = getDeviceLinkInvokeContext()?.sharedTask;
+ assertSharedTaskQueueMutation(sharedTask, sessionId, 'agent.stop');
+ if (sharedTask) opts = { ...opts, keepQueue: true };
const state = this.getState(sessionId);
const preserveQueue = opts?.keepQueue === true;
this.supersedePendingAutoResumeRecoveries(sessionId);
@@ -2617,6 +2628,7 @@ export class AgentInputCoordinator {
}
resume(sessionId: string): AgentInputProjection {
+ assertSharedTaskQueueMutation(getDeviceLinkInvokeContext()?.sharedTask, sessionId, 'input.send');
const state = this.getState(sessionId);
const recovery = state.recovery;
const pausedQueueHeadRecoveryClientId =
@@ -2951,6 +2963,7 @@ export class AgentInputCoordinator {
remove(sessionId: string, clientId: string): AgentInputProjection {
const state = this.getState(sessionId);
+ assertSharedTaskQueueMutation(getDeviceLinkInvokeContext()?.sharedTask, sessionId, 'input.withdraw', state.pendingQueue.find((item) => item.clientId === clientId));
if (state.steeringQueueClientIds.includes(clientId)) return this.getProjection(sessionId);
const before = state.pendingQueue.length;
const removed = state.pendingQueue.find((q) => q.clientId === clientId);
@@ -2995,6 +3008,7 @@ export class AgentInputCoordinator {
const trimmed = newText.trim();
if (!trimmed) return this.getProjection(sessionId);
const state = this.getState(sessionId);
+ assertSharedTaskQueueMutation(getDeviceLinkInvokeContext()?.sharedTask, sessionId, 'input.edit', state.pendingQueue.find((item) => item.clientId === clientId));
if (state.steeringQueueClientIds.includes(clientId)) return this.getProjection(sessionId);
state.pendingQueue = state.pendingQueue.map((entry) => {
if (entry.clientId !== clientId) return entry;
@@ -3059,6 +3073,7 @@ export class AgentInputCoordinator {
if (index < 0) return { projection: this.getProjection(sessionId), updated: false };
const current = state.pendingQueue[index];
const updated = updateQueuedMessageContent(current, next);
+ assertSharedTaskQueueMutation(getDeviceLinkInvokeContext()?.sharedTask, sessionId, 'input.edit', current);
const authorizationContentChanged = updated.text !== current.text
|| updated.persistedContent !== current.persistedContent
|| updated.files !== current.files
@@ -3216,6 +3231,7 @@ export class AgentInputCoordinator {
}
setExpanded(sessionId: string, expanded: boolean): AgentInputProjection {
+ assertSharedTaskQueueMutation(getDeviceLinkInvokeContext()?.sharedTask, sessionId, 'input.send');
const state = this.getState(sessionId);
state.queueExpanded = expanded;
this.emit(sessionId);
@@ -3279,6 +3295,7 @@ export class AgentInputCoordinator {
setEditLock(sessionId: string, clientId: string, locked: boolean): AgentInputProjection {
const state = this.getState(sessionId);
+ assertSharedTaskQueueMutation(getDeviceLinkInvokeContext()?.sharedTask, sessionId, 'input.edit', state.pendingQueue.find((item) => item.clientId === clientId));
state.queueEditLocks = toggleList(state.queueEditLocks, clientId, locked);
this.emit(sessionId);
if (!locked) {
@@ -4472,6 +4489,7 @@ export class AgentInputCoordinator {
...(head.fromMobileClient ? { fromMobileClient: true } : {}),
...(head.fromDeviceLinkClient ? { fromDeviceLinkClient: true } : {}),
persistUserMessage: {
+ ...(head.sharedTaskAuthor ? { sharedTaskAuthor: head.sharedTaskAuthor } : {}),
clientId: head.clientId,
content: head.persistedContent,
agentFacingWireContent: makerUserMessage,
@@ -6180,6 +6198,7 @@ export class AgentInputCoordinator {
content: item.persistedContent,
agentMeta: {
uuid: active.messageUuid,
+ ...(item.sharedTaskAuthor ? { sharedTaskAuthor: item.sharedTaskAuthor } : {}),
...(item.autoReviewUserText !== undefined ? { autoReviewUserText: item.autoReviewUserText } : {}),
sdkSessionId,
delivery: active.delivery,
diff --git a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
index a535a1b3c7..2a29b85337 100644
--- a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
+++ b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
@@ -620,6 +620,7 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
return requiresRemoteRebuild ? 'remote-unsupported' : 'not-needed';
}
if (!deps.rehydrateColdPiRuntimeForWindowVerification) return 'unknown-context';
+ target.assertCanCommit?.();
try {
await deps.rehydrateColdPiRuntimeForWindowVerification(sessionId);
} catch (error) {
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index 4d0cf17cc5..f380118331 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -267,6 +267,7 @@ type MakerSendOptions = {
/** Coordinator-transmitted provenance for device-link input.enqueue. */
fromDeviceLinkClient?: boolean;
persistUserMessage?: {
+ sharedTaskAuthor?: AgentInputQueuedMessage['sharedTaskAuthor'];
clientId?: unknown;
content?: unknown;
agentFacingWireContent?: unknown;
@@ -519,6 +520,7 @@ type ResolveSessionResult =
| { kind: 'failure'; result: DesktopMakerSendResult };
function readPersistUserMessageOption(sendOpts: MakerSendOptions): {
+ sharedTaskAuthor?: AgentInputQueuedMessage['sharedTaskAuthor'];
clientId: string;
content: unknown;
agentFacingWireContent?: IpcUserMessage;
@@ -538,6 +540,7 @@ function readPersistUserMessageOption(sendOpts: MakerSendOptions): {
const persist = sendOpts.persistUserMessage;
if (!persist || typeof persist.clientId !== 'string') return null;
return {
+ ...(persist.sharedTaskAuthor ? { sharedTaskAuthor: persist.sharedTaskAuthor } : {}),
clientId: persist.clientId,
content: persist.content,
...(persist.agentFacingWireContent && typeof persist.agentFacingWireContent === 'object'
@@ -1520,6 +1523,7 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
role: 'user',
content: persistUserMessage.content,
agentMeta: {
+ ...(persistUserMessage.sharedTaskAuthor ? { sharedTaskAuthor: persistUserMessage.sharedTaskAuthor } : {}),
uuid: so.messageUuid,
...(so.origin?.kind === 'scheduler'
? { autoReviewUserText: { kind: 'scheduled-continuation' } }
diff --git a/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts b/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts
index c3afa051e0..d464236b6b 100644
--- a/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts
+++ b/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts
@@ -154,7 +154,12 @@ export function attachMainOwnedInputBoundary(
*/
export function stripMainOnlySendOpts(sendOpts: unknown): unknown {
if (!sendOpts || typeof sendOpts !== 'object' || Array.isArray(sendOpts)) return sendOpts;
- const opts = sendOpts as Record<string, unknown>;
+ let opts = sendOpts as Record<string, unknown>;
+ const persisted = opts.persistUserMessage;
+ if (persisted && typeof persisted === 'object' && !Array.isArray(persisted) && 'sharedTaskAuthor' in persisted) {
+ const { sharedTaskAuthor: _ignoredAuthor, ...content } = persisted as Record<string, unknown>;
+ opts = { ...opts, persistUserMessage: content };
+ }
if (
!('fromMobileClient' in opts) &&
!('fromDeviceLinkClient' in opts) &&
@@ -167,7 +172,7 @@ export function stripMainOnlySendOpts(sendOpts: unknown): unknown {
!('toolsDisabled' in opts) &&
!('origin' in opts)
) {
- return sendOpts;
+ return opts;
}
const {
fromMobileClient: _ignoredMobile,
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 56713ecb46..0c3b3aa4e6 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1040,9 +1040,19 @@ import {
} from '../device-link/dispatch.js';
import {
deviceLinkInvokeControllerSupports,
+ getDeviceLinkInvokeContext,
isDeviceLinkInvoke,
isMobileControllerInvoke,
} from '../device-link/invoke-context.js';
+import { stampSharedTaskInput } from './sharedTaskInput.js';
+import { createSharedTaskContextUsageGuard } from './sharedTaskContextUsage.js';
+import { createSharedTaskSettingGuard } from './sharedTaskSetting.js';
+import { setSharedTaskQueueReader } from '../device-link/sharedTaskDispatch.js';
+
+function captureSharedTaskSettingGuard(sessionId: string) {
+ const context = getDeviceLinkInvokeContext();
+ return createSharedTaskSettingGuard(context?.sharedTask, sessionId, context?.sharedTaskSetting ?? { admitted: false });
+}
import {
attachMainOwnedInputBoundary,
buildMobileClientPromptNote,
@@ -6560,11 +6570,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return verdict.kind === 'reroute' ? verdict.providerId : undefined;
}
- async function bootstrapSession(o: CreateOpts): Promise<{
+ async function bootstrapSession(o: CreateOpts, assertAccess?: () => void): Promise<{
session: Awaited<ReturnType<typeof maker.createSession>>;
didInjectOrcaInstructions: boolean;
didInjectProjectContext: boolean;
}> {
+ assertAccess?.();
if (o.id && o.workingDir && !o.remoteHostId) {
o.workingDir = workingDirectoryRecovery.resolve(o.id, o.workingDir);
await workingDirectoryRecovery.observe(o.id, o.workingDir).catch((error) => {
@@ -6587,6 +6598,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
o.effort = runtimeOverride.effort ?? undefined;
o.fastMode = runtimeOverride.fastMode;
}
+ assertAccess?.();
await applyPersistedReviewMode(o);
await applyPersistedCindyMakeMarker(o, readSessionSource);
const didInjectOrcaInstructions = o.reviewMode === true ? false : applyOrcaInstructions(o);
@@ -6595,6 +6607,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const usingFallback = !!o.id && !!o.workingDir && !o.remoteHostId &&
workingDirectoryRecovery.isFallback(o.id, o.workingDir);
+ assertAccess?.();
await prepareDirectoryGrantsForBootstrap(o, {
statDirectory: usingFallback ? statWorkingDirectory : undefined,
realpathDirectory: usingFallback ? realpathWorkingDirectory : undefined,
@@ -6606,11 +6619,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
.from(sessions)
.where(eq(sessions.id, sessionId))
.limit(1);
+ assertAccess?.();
if (existing) await persistSessionFields(sessionId, patch);
},
});
await hydrateProviderIdBeforeSessionStart(o);
+ assertAccess?.();
await ensureManagedOllamaReadyForSession({
providerId: o.providerId,
remoteHostId: o.remoteHostId ?? null,
@@ -6650,6 +6665,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (pin) o.providerId = pin;
}
}
+ assertAccess?.();
const session = await maker.createSession(o);
await markProjectContextIfNeeded(session.id, didInjectProjectContext);
wireSessionToIpc(session);
@@ -12952,12 +12968,23 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (typeof sessionId !== 'string' || sessionId.length === 0) {
throwIpcError('INVALID_PARAMS', 'sessionId required');
}
+ const sharedTaskAccess = createSharedTaskContextUsageGuard(
+ getDeviceLinkInvokeContext()?.sharedTask, sessionId,
+ );
+ sharedTaskAccess.assertCurrent();
let sess = maker.getSession(sessionId);
if (!sess) {
- if (!createOpts) {
+ const trustedCreateOpts = await sharedTaskAccess.resolveCreateOpts(
+ createOpts, async () => ({
+ ...await readSharedTaskTaskCreateOpts(sessionId),
+ extraDirs: extraDirsForRuntime(await readSessionExtraDirsFromDb(sessionId)),
+ writableDirs: await readSessionWritableDirsFromDb(sessionId),
+ }),
+ );
+ if (!trustedCreateOpts) {
throwIpcError('NOT_FOUND', `Session ${sessionId} is not running`);
}
- const co = buildCreateOptsWithStderr({ ...(createOpts as CreateOpts), id: sessionId });
+ const co = buildCreateOptsWithStderr({ ...(trustedCreateOpts as CreateOpts), id: sessionId });
// session-agent-switch:先按 DB 行校正再判 claude-only——否则切到 codex 后
// 残留的 claude createOpts 会在这里 spawn 出旧引擎的 live session 并被后续
// send 复用(会话被劫持回旧引擎,2026-07-20 审计实锤)。
@@ -12994,12 +13021,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (row.length > 0) co.writableDirs = row;
}
try {
+ sharedTaskAccess.assertCurrent();
await ensureRemoteReadyForSessionStart({ createOpts: co });
const {
session: lazySess,
didInjectOrcaInstructions,
didInjectProjectContext,
- } = await bootstrapSession(co);
+ } = await bootstrapSession(co, sharedTaskAccess.assertCurrent);
await markOrcaRoleIfNeeded(lazySess.id, co.orcaRole);
log.info('context-usage: lazy create-session', {
sessionId,
@@ -13990,6 +14018,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
getPersistedClientIds: getPersistedInputClientIds,
});
agentInputCoordinatorHolder = inputCoordinator;
+ setSharedTaskQueueReader((sessionId, clientId) => {
+ const item = inputCoordinator.getProjection(sessionId).pendingQueue.find((pending) => pending.clientId === clientId);
+ return item ? { sessionId, authorAccountId: item.sharedTaskAuthor?.accountId ?? '', state: 'pending', attachments: item.files } : undefined;
+ });
getAgentIslandService()?.setCompletionDeferResolver((sessionId) =>
inputCoordinator.hasPendingQueuedWork(sessionId),
);
@@ -14412,6 +14444,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
throwIpcError('INVALID_PARAMS', 'queued.createOpts.agentKind invalid');
}
const normalized: AgentInputQueuedMessage = { ...msg };
+ delete normalized.sharedTaskAuthor;
delete normalized.autoReviewUserText;
// Only Main-created welcomes and restored host snapshots may carry this policy.
delete normalized.toolsDisabled;
@@ -14443,6 +14476,24 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
ipcMain.handle(DL_SESSION_REFERENCE_CAPABILITY_CHANNEL, () => ({ supported: true, version: 1 }));
+ async function readSharedTaskTaskCreateOpts(sid: string): Promise<AgentInputCreateOpts> {
+ const [row] = await getDbClient().drizzle.select().from(sessions).where(eq(sessions.id, sid)).limit(1);
+ if (!row || row.status !== 'active' || !row.workingDir) throwIpcError('NOT_FOUND', 'SharedTask task unavailable');
+ return {
+ agentKind: dbToMakerAgentKind(row.agentKind), workingDir: row.workingDir,
+ model: row.model, providerId: row.providerId, effort: row.effort,
+ permissionMode: row.permissionMode, fastMode: row.fastMode,
+ planMode: row.planModeEnabled, remoteHostId: row.remoteHostId ?? undefined,
+ resumeSessionId: row.sdkSessionId ?? undefined, orcaRole: row.orcaRole,
+ };
+ }
+
+ const prepareSharedTaskInput = async (sid: string, item: AgentInputQueuedMessage) => {
+ const sharedTask = getDeviceLinkInvokeContext()?.sharedTask;
+ if (!sharedTask) return item;
+ return stampSharedTaskInput(item, sharedTask, await readSharedTaskTaskCreateOpts(sid));
+ };
+
/**
* device-link 远控输入的自动起名(入队 / 插话共用)。
*
@@ -14738,7 +14789,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
await assertReviewExternalInputAllowed(sid);
const deviceLinkInvoke = isDeviceLinkInvoke();
if (!deviceLinkInvoke) assertTrustedAppRendererEvent(event);
- const parsed = requireQueuedMessage(item);
+ const parsed = await prepareSharedTaskInput(sid, requireQueuedMessage(item));
assertRemoteInputClearNotInFlight(sid, deviceLinkInvoke);
const clearBoundaryPrecondition = readRemoteInputClearBoundaryPrecondition(opts);
if (!deviceLinkInvoke) await observeLocalInputClearBoundary(sid);
@@ -14905,12 +14956,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
touchUserSend?: boolean;
} & AgentInputClearBoundaryOpts)
: undefined;
- const parsed = requireQueuedMessage(item, {
+ const parsed = await prepareSharedTaskInput(sid, requireQueuedMessage(item, {
// A device-link projection intentionally omits the trusted snapshot;
// Only the explicit remove-from-queue steer path may reattach it from
// the main-owned row; all other IPC paths remain fail-closed here.
allowMissingTrustedContexts: deviceLinkInvoke && steerOpts?.removeFromQueue === true,
- });
+ }));
assertRemoteInputClearNotInFlight(sid, deviceLinkInvoke);
const clearBoundaryPrecondition = readRemoteInputClearBoundaryPrecondition(opts);
if (!deviceLinkInvoke) await observeLocalInputClearBoundary(sid);
@@ -15678,7 +15729,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
let atomicSelection = selection as
{ effort: SessionRuntimeProfile['effort']; fastMode: boolean } | undefined;
const runtimeOwnerEpoch = captureSessionRuntimeControlOwnerEpoch();
+ const assertSharedTaskCurrent = captureSharedTaskSettingGuard(sessionId);
const assertRuntimeOwnerCurrent = (): void => {
+ assertSharedTaskCurrent();
internalOptions.assertSelectionCurrent?.();
if (!sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)) {
throwIpcError(
@@ -15688,6 +15741,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
};
const supersededByOwnerBoundary = (): boolean => {
+ assertSharedTaskCurrent();
if (sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)) return false;
if (internalOptions.source === 'user') {
assertRuntimeOwnerCurrent();
@@ -15894,6 +15948,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (internalOptions.source === 'user' && !internalOptions.applyingUserSelectionOnSend &&
!runtimeStatus.remoteHostId && !runtimeStatus.orcaRole) {
assertRuntimeOwnerCurrent();
+ assertSharedTaskCurrent.admit();
clearPendingCredentialSwitchForSession(sessionId, { wake: false });
const intent = {
...(internalOptions.runtimeSource ? { runtimeSource: internalOptions.runtimeSource } : {}),
@@ -15929,6 +15984,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (supersededByOwnerBoundary()) {
return { deferred: false, superseded: true };
}
+ assertSharedTaskCurrent.admit();
const generation = routeExplicit
? acceptSessionRuntimeMutation({
sessionId,
@@ -16058,6 +16114,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
);
}
if (!liveSessionBeforeRouteChange) {
+ assertRuntimeOwnerCurrent();
+ assertSharedTaskCurrent.admit();
try {
await rehydrateColdPiRuntimeForWindowVerification(sessionId);
} catch {
@@ -16234,7 +16292,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
onConfirmationRequired: (contextTokens) => {
confirmationContextTokens = contextTokens;
},
- assertCanCommit: assertRuntimeOwnerCurrent,
+ assertCanCommit: () => { assertRuntimeOwnerCurrent(); assertSharedTaskCurrent.admit(); },
beforeClose: () => {
clearPendingCredentialSwitchForSession(sessionId, { wake: false });
pendingClearedForWindowRebuild = true;
@@ -16411,6 +16469,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const result = routeExplicit
? await applyRuntimeSetModelChange({
maker,
+ admit: () => { assertRuntimeOwnerCurrent(); assertSharedTaskCurrent.admit(); },
sessionId,
model,
providerId: effectiveProviderId,
@@ -16562,6 +16621,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
if (atomicSelection) {
const selectionToCommit = atomicSelection;
+ assertRuntimeOwnerCurrent();
+ assertSharedTaskCurrent.admit();
// model/provider/effort/fast 是一次选择快照,必须在同一把 session 锁内收敛。
// applyRuntimeSetModelChange 可能 close + wake;若 effort/fast 留给 renderer
// 后续独立调用,queue drain 会用新 model + 旧偏好重建,跨控制端时还会发生
@@ -16625,6 +16686,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
const routeProjectionOwnerScope = captureDataOwnerBroadcastScope();
try {
+ assertRuntimeOwnerCurrent();
+ assertSharedTaskCurrent.admit();
await persistSessionFields(sessionId, patch);
} catch (persistenceError) {
// The live route and host stores are applied before SQLite so the
@@ -16891,7 +16954,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
throwIpcError('INVALID_PARAMS', 'sessionId + effort required');
}
const runtimeOwnerEpoch = captureSessionRuntimeControlOwnerEpoch();
+ const assertSharedTaskCurrent = captureSharedTaskSettingGuard(sessionId);
const assertOwnerCurrent = () => {
+ assertSharedTaskCurrent();
if (!sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)) {
throwIpcError(
'PRECONDITION_FAILED',
@@ -16903,6 +16968,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const remoteResponse = remoteInvoke ? {} : undefined;
const persistEffort = async () => {
if (!remoteResponse) return;
+ assertOwnerCurrent();
+ assertSharedTaskCurrent.admit();
await persistSessionFields(sessionId, { effort });
markRemoteSettingPersistedInsideHandler(remoteResponse);
};
@@ -16925,6 +16992,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const userIntent = agentSwitchPending.get(sessionId);
if (userIntent?.sameAgentSelection) {
assertOwnerCurrent();
+ assertSharedTaskCurrent.admit();
const result = await agentSwitchDeps.selectSameAgentModel!(sessionId,
{ ...userIntent, effort: effort }, false);
if (remoteResponse) markRemoteSettingPersistedInsideHandler(remoteResponse);
@@ -16969,10 +17037,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
? (await readSessionRuntimeProfiles(sessionId))?.effective
: undefined;
const result = await applyRuntimeEffortWithRecovery({
- applyRuntime: () =>
- sess.setEffort(
+ applyRuntime: () => {
+ assertOwnerCurrent();
+ assertSharedTaskCurrent.admit();
+ return sess.setEffort(
effort as 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra',
- ),
+ );
+ },
terminateSession: () => maker.closeSession(sessionId),
});
if (result === 'session-terminated') {
@@ -17328,7 +17399,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
throwIpcError('INVALID_PARAMS', 'sessionId + enabled required');
}
const runtimeOwnerEpoch = captureSessionRuntimeControlOwnerEpoch();
+ const assertSharedTaskCurrent = captureSharedTaskSettingGuard(sessionId);
const assertOwnerCurrent = () => {
+ assertSharedTaskCurrent();
if (!sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)) {
throwIpcError(
'PRECONDITION_FAILED',
@@ -17340,6 +17413,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const remoteResponse = remoteInvoke ? {} : undefined;
const persistFastMode = async () => {
if (!remoteResponse) return;
+ assertOwnerCurrent();
+ assertSharedTaskCurrent.admit();
await persistSessionFields(sessionId, { fastMode: enabled });
markRemoteSettingPersistedInsideHandler(remoteResponse);
};
@@ -17362,6 +17437,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const userIntent = agentSwitchPending.get(sessionId);
if (userIntent?.sameAgentSelection) {
assertOwnerCurrent();
+ assertSharedTaskCurrent.admit();
const result = await agentSwitchDeps.selectSameAgentModel!(sessionId,
{ ...userIntent, fastMode: enabled }, false);
if (remoteResponse) markRemoteSettingPersistedInsideHandler(remoteResponse);
@@ -17422,6 +17498,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const previousProfile = remoteInvoke
? (await readSessionRuntimeProfiles(sessionId))?.effective
: undefined;
+ assertOwnerCurrent();
+ assertSharedTaskCurrent.admit();
await sess.setFastMode(enabled);
await commitRuntimeAxisAfterPersistence({
persist: persistFastMode,
@@ -17467,9 +17545,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (typeof sessionId !== 'string' || typeof enabled !== 'boolean') {
throwIpcError('INVALID_PARAMS', 'sessionId + enabled required');
}
+ const assertSharedTaskCurrent = captureSharedTaskSettingGuard(sessionId);
await assertReviewSettingsUnlocked(sessionId);
+ assertSharedTaskCurrent();
const sess = maker.getSession(sessionId);
if (!sess) return;
+ assertSharedTaskCurrent.admit();
await sess.setThinkingEnabled(enabled);
},
);
diff --git a/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts b/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts
index 279d756e60..30d6a3a05c 100644
--- a/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts
+++ b/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts
@@ -65,6 +65,8 @@ export interface ApplyRuntimeSetModelChangeInput {
forceSessionRebuild?: boolean;
/** Fail closed before an otherwise-required runtime replacement mutates route state. */
assertSessionCloseSupported?: () => void;
+ /** Called after async preflight, immediately before the first setting side effect. */
+ admit?: () => void;
isSessionInTurn?: (sessionId: string) => boolean;
/**
* 会话自己正在跑 turn 时的延迟生效登记(PendingCredentialSwitchService.register)。
@@ -225,6 +227,7 @@ export async function applyRuntimeSetModelChange(
}
if (!sess && requiresCodexThreadRelink) {
+ input.admit?.();
await input.relinkCodexThread?.();
if (providerId !== undefined) setSessionProvider(sessionId, nextProviderId);
input.wakeSessionInputQueue?.(sessionId);
@@ -244,6 +247,7 @@ export async function applyRuntimeSetModelChange(
// 把 route/model 的生效边界固定在 turn 结束;pending 收口只关闭本 Session,
// 当前账号保持到回合边界,不能让工具续轮命中新账号。
if (input.registerPendingCredentialSwitch) {
+ input.admit?.();
await input.registerPendingCredentialSwitch(sessionId, {
model,
providerId: nextProviderId,
@@ -265,6 +269,7 @@ export async function applyRuntimeSetModelChange(
if (sess && (shouldCloseSession || requiresCodexThreadRelink)) {
input.assertSessionCloseSupported?.();
+ input.admit?.();
if (isSelfBusy() && input.registerPendingCredentialSwitch) {
// A required credential rebuild must also survive close failure: keeping
// the old process alive cannot be treated as applying the new account.
@@ -369,6 +374,7 @@ export async function applyRuntimeSetModelChange(
: { status: 'applied' };
}
+ input.admit?.();
if (providerId !== undefined) {
setSessionProvider(sessionId, nextProviderId);
// 显式选源且无需切换 → 取消尚未兑现的 pending(后选覆盖先选)。
diff --git a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
index 0f6dfa23d6..6cf2190d75 100644
--- a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
@@ -27,6 +27,8 @@
*/
import type { AgentKind } from '@cindy/maker-core';
+import { getDeviceLinkInvokeContext } from '../device-link/invoke-context.js';
+import { createSharedTaskSettingGuard } from './sharedTaskSetting.js';
import { MAKER_INVOKE } from './channels.js';
import type { IpcHandlerRegistry } from './ipcHandlerRegistry.js';
@@ -869,6 +871,8 @@ export function registerMakerSessionAgentSwitchHandler(
effort: unknown,
fastMode: unknown,
) => {
+ const context = getDeviceLinkInvokeContext();
+ const guard = createSharedTaskSettingGuard(context?.sharedTask, String(sessionId), context?.sharedTaskSetting ?? { admitted: false });
const run = () => performSessionAgentSwitch(deps, {
sessionId,
targetAgentKind,
@@ -876,6 +880,7 @@ export function registerMakerSessionAgentSwitchHandler(
providerId,
effort,
fastMode,
+ assertSelectionCurrent: guard.admit,
});
return typeof sessionId === 'string' && sessionId && deps.withSessionLock
? deps.withSessionLock(sessionId, run)
diff --git a/apps/desktop/src/main/maker-ipc/sharedTaskContextUsage.ts b/apps/desktop/src/main/maker-ipc/sharedTaskContextUsage.ts
new file mode 100644
index 0000000000..d07254e170
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/sharedTaskContextUsage.ts
@@ -0,0 +1,26 @@
+import type { SharedTaskPeerCapture } from '../device-link/sharedTaskDispatch.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+
+/** A context query can lazily start an Agent; its configuration is host-owned. */
+export function createSharedTaskContextUsageGuard(
+ sharedTask: SharedTaskPeerCapture | undefined,
+ sessionId: string,
+) {
+ const assertCurrent = () => {
+ if (sharedTask && (sharedTask.author.sessionId !== sessionId || !sharedTask.isCurrent() ||
+ !sharedTask.authorize('history.read'))) {
+ throwIpcError('PERMISSION_DENIED', 'SharedTask task access denied');
+ }
+ };
+ return {
+ assertCurrent,
+ async resolveCreateOpts<T>(wireOptions: unknown, readHostOptions: () => Promise<T>): Promise<unknown> {
+ assertCurrent();
+ if (!sharedTask) return wireOptions;
+ // Do not inspect or spread even one field of a guest's bootstrap options.
+ const hostOptions = await readHostOptions();
+ assertCurrent();
+ return hostOptions;
+ },
+ };
+}
diff --git a/apps/desktop/src/main/maker-ipc/sharedTaskInput.ts b/apps/desktop/src/main/maker-ipc/sharedTaskInput.ts
new file mode 100644
index 0000000000..fcbd35de17
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/sharedTaskInput.ts
@@ -0,0 +1,51 @@
+import type { AgentInputCreateOpts, AgentInputQueuedMessage } from '../../shared/agentInputQueue.js';
+import type { SharedTaskPeerCapture } from '../device-link/sharedTaskDispatch.js';
+import { assertSharedTaskReferences, sharedTaskOwnedQueueReferences } from '../device-link/sharedTaskDispatch.js';
+
+/** Build privileged input configuration from host truth, not guest queue snapshots. */
+export function stampSharedTaskInput(
+ item: AgentInputQueuedMessage, capture: SharedTaskPeerCapture | undefined,
+ task: AgentInputCreateOpts | undefined,
+): AgentInputQueuedMessage {
+ const stamped = { ...item };
+ delete stamped.sharedTaskAuthor;
+ if (!capture) return stamped;
+ if (!task || !capture.isCurrent() || !capture.authorize('input.send')) {
+ throw new Error('[PERMISSION_DENIED] SharedTask task access denied');
+ }
+ assertSharedTaskReferences(item, capture.author.sessionId, 0, capture.author.sharedTaskId, sharedTaskOwnedQueueReferences(capture, item.clientId));
+ // Only content comes from the guest. The task owns runtime/bootstrap settings.
+ stamped.createOpts = { ...task };
+ stamped.workingDir = task.workingDir;
+ stamped.permissionMode = task.permissionMode ?? 'ask';
+ stamped.model = task.model;
+ stamped.effort = task.effort ?? '';
+ delete stamped.vendorOptions;
+ delete stamped.origin;
+ delete stamped.autoResume;
+ delete stamped.autoResumeInfo;
+ delete stamped.recoveryCheckpoint;
+ delete stamped.bypassGhostHooks;
+ delete stamped.hostAcceptedAtMs;
+ stamped.sharedTaskAuthor = { ...capture.author };
+ stamped.userName = capture.author.displayName;
+ return stamped;
+}
+
+/** Run inside the synchronous queue mutation, after all asynchronous preparation. */
+export function assertSharedTaskQueueMutation(
+ capture: SharedTaskPeerCapture | undefined, sessionId: string,
+ operation: 'input.send' | 'input.edit' | 'input.withdraw' | 'agent.stop',
+ item?: AgentInputQueuedMessage,
+): void {
+ if (!capture) return;
+ const author = item?.sharedTaskAuthor;
+ if (capture.author.sessionId !== sessionId || !capture.isCurrent() ||
+ (operation === 'input.edit' || operation === 'input.withdraw') &&
+ (!author || author.sharedTaskId !== capture.author.sharedTaskId || author.memberId !== capture.author.memberId) ||
+ !capture.authorize(operation, item ? {
+ sessionId, authorAccountId: author?.accountId ?? '', state: 'pending',
+ } : undefined)) {
+ throw new Error('[PERMISSION_DENIED] SharedTask task access denied');
+ }
+}
diff --git a/apps/desktop/src/main/maker-ipc/sharedTaskSetting.ts b/apps/desktop/src/main/maker-ipc/sharedTaskSetting.ts
new file mode 100644
index 0000000000..1ff86670c4
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/sharedTaskSetting.ts
@@ -0,0 +1,19 @@
+import type { SharedTaskPeerCapture } from '../device-link/sharedTaskDispatch.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+
+/** One native setting transaction. Revocation fences admission, not its rollback. */
+export function createSharedTaskSettingGuard(
+ sharedTask: SharedTaskPeerCapture | undefined,
+ sessionId: string,
+ transaction: { admitted: boolean },
+) {
+ const assertCurrent = () => {
+ if (!transaction.admitted && sharedTask && (sharedTask.author.sessionId !== sessionId ||
+ !sharedTask.isCurrent() || !sharedTask.authorize('agent.configure'))) {
+ throwIpcError('PERMISSION_DENIED', 'SharedTask task access denied');
+ }
+ };
+ return Object.assign(assertCurrent, {
+ admit() { assertCurrent(); transaction.admitted = true; },
+ });
+}
diff --git a/apps/desktop/src/main/serverApiClient.ts b/apps/desktop/src/main/serverApiClient.ts
index 059234abb5..084b1665c3 100644
--- a/apps/desktop/src/main/serverApiClient.ts
+++ b/apps/desktop/src/main/serverApiClient.ts
@@ -45,6 +45,8 @@ export interface ApiFetchOptions {
token?: string | null;
/** 跳过 401 自动 refresh(避免无限循环;refresh 自身调用时禁用)。 */
skipAutoRefresh?: boolean;
+ /** Fixed-identity teardown requests must not invalidate a newer active account. */
+ skipSessionInvalidation?: boolean;
/**
* 目标服务 base URL(必传;来自 clientEndpoints 的对应字段或注入方)。
* 区域相关服务必须传 resolver:401 refresh 可能切换登录区域,重试前要重新
@@ -150,7 +152,7 @@ export async function serverApiFetch<T>(apiPath: string, opts: ApiFetchOptions):
const errCode = readErrorCode(result.data) ?? statusToCode(result.status);
const errMsg = readErrorMessage(result.data) ?? `请求失败 (${result.status})`;
if (
- result.status === 401 &&
+ !opts.skipSessionInvalidation && result.status === 401 &&
(errCode === 'ACCOUNT_UNAVAILABLE' ||
(refreshedAndRetried && isRefreshableUnauthorizedCode(errCode)))
) {
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 7cddae746a..4791495559 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -4381,6 +4381,12 @@ contextBridge.exposeInMainWorld('electronAPI', {
windowsSupport: (enabled) => ipcRenderer.invoke(DESKTOP_LOCAL.WINDOWS_SUPPORT, enabled),
stop: () => ipcRenderer.invoke(DESKTOP_LOCAL.STOP),
} satisfies RemoteDesktopApi,
+ sharedTask: {
+ host: (command: import('@cindy/device-link').SharedTaskHostCommand): Promise<unknown> =>
+ ipcRenderer.invoke('maker:shared-task', command),
+ account: (command: import('@cindy/device-link').SharedTaskAccountCommand): Promise<unknown> =>
+ ipcRenderer.invoke('shared-task:account', command),
+ },
deviceLink: {
getState: (): Promise<{
remoteControlEnabled: boolean;
diff --git a/apps/desktop/src/renderer/__tests__/cindyMakeInlineEntry.test.ts b/apps/desktop/src/renderer/__tests__/cindyMakeInlineEntry.test.ts
index 0c80d4b605..d1a07f7d75 100644
--- a/apps/desktop/src/renderer/__tests__/cindyMakeInlineEntry.test.ts
+++ b/apps/desktop/src/renderer/__tests__/cindyMakeInlineEntry.test.ts
@@ -1,6 +1,8 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
+import ts from 'typescript';
+import { isSharedTaskPeer } from '@cindy/device-link';
const composer = readFileSync(resolve(__dirname, '../components/new-chat/ChatInput.tsx'), 'utf8');
const sessionView = readFileSync(
@@ -23,14 +25,31 @@ describe('Cindy Make composer presentation', () => {
expect(promptHost).toBeGreaterThan(-1);
expect(mask).toBeGreaterThan(promptHost);
expect(input).toBeGreaterThan(mask);
- const interactionGuard = sessionView.slice(
- sessionView.indexOf('</InteractionPromptHost>'),
- mask,
- );
- expect(interactionGuard).toMatch(
- /pendingPlanReview ||[\s\S]*pendingPermission ||[\s\S]*pendingAskUser/,
- );
- expect(interactionGuard).toContain('pendingGhostGrantConfirm ? null');
+ const promptEnd = sessionView.indexOf('</InteractionPromptHost>');
+ // Parse the real guard so grouping/formatting does not change the contract.
+ const ast = ts.createSourceFile('session.tsx', sessionView, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+ let condition: ts.Expression | undefined;
+ const visit = (node: ts.Node) => {
+ if (ts.isConditionalExpression(node) && node.getStart(ast) > promptEnd && node.getStart(ast) < mask
+ && node.whenTrue.kind === ts.SyntaxKind.NullKeyword
+ && node.condition.getText(ast).includes('pendingGhostGrantConfirm')) {
+ condition = node.condition;
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(ast);
+ expect(condition).toBeDefined();
+ const prompts = ['pendingPlanReview', 'pendingPermission', 'pendingAskUser', 'pendingPluginSetup',
+ 'pendingIssueConfirm', 'pendingRenameSessionsConfirm', 'pendingGhostGrantConfirm'];
+ const hidesComposer = new Function('isSharedTaskPeer', 'remoteDeviceId', ...prompts,
+ `return Boolean(${condition!.getText(ast)});`);
+ for (const deviceId of [undefined, 'own-device', 'shared-task~m~host']) {
+ expect(hidesComposer(isSharedTaskPeer, deviceId, ...prompts.map(() => false))).toBe(false);
+ for (const active of prompts) {
+ expect(hidesComposer(isSharedTaskPeer, deviceId, ...prompts.map((name) => name === active)),
+ `${deviceId ?? 'local'}: ${active}`).toBe(deviceId !== 'shared-task~m~host');
+ }
+ }
expect(sessionView).toContain('if (cindyMakeInputLocked) return false;');
expect(sessionView).not.toContain('CindyMakeResumeCard');
const recovery = sessionView.indexOf(') : cindyMakeRecoveryId && session ? (');
diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
index 7f18fb6743..ebca926098 100644
--- a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
+++ b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
@@ -1452,6 +1452,6 @@ describe('远程交互接线不变式', () => {
const start = src.indexOf('function handleSubscriptionFrame');
expect(start).toBeGreaterThan(-1);
- expect(src.slice(start, start + 900)).toContain('o.topics.filter(isRemoteSubscriptionTopic)');
+ expect(src.slice(start, src.indexOf("const name = resolveControllerName", start))).toContain('o.topics.filter(isRemoteSubscriptionTopic)');
});
});
diff --git a/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts b/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts
index f2479d8834..f4a1159ecf 100644
--- a/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts
+++ b/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts
@@ -51,6 +51,15 @@ function mkSession(id: string, deviceLinkDeviceId?: string): Session {
return { id, status: 'active', deviceLinkDeviceId } as unknown as Session;
}
+it('never lists shared-task peers as devices, including disconnected and rejected peers', () => {
+ const peer = 'shared-task~share-1~host';
+ expect(buildSwitcherDevices({
+ fullList: [mkDevice('real-pc'), mkDevice(peer)],
+ syncedDevices: [{ deviceId: peer, deviceName: 'Shared task', sessionCount: 1, connected: false }],
+ revoked: new Set([peer]),
+ }).map(device => device.deviceId)).toEqual(['real-pc']);
+});
+
describe('selectVisibleSessions', () => {
afterEach(() => remoteProjectsStore.clear());
const local = [mkSession('l1'), mkSession('l2')];
diff --git a/apps/desktop/src/renderer/__tests__/remoteDataOwnerPushFence.test.ts b/apps/desktop/src/renderer/__tests__/remoteDataOwnerPushFence.test.ts
new file mode 100644
index 0000000000..366ac3912b
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/remoteDataOwnerPushFence.test.ts
@@ -0,0 +1,106 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+import { sharedTaskHostPeer } from '@cindy/device-link';
+import { setDataOwnerGeneration } from '../contexts/dataOwnerGeneration';
+import { bindSharedTaskPushOwner, isDeviceLinkRemotePushCurrent, isRemoteDataOwnerPushCurrent, resetRemoteDataOwnerPushFence } from '../lib/remoteDataOwnerPushFence';
+
+const peer = sharedTaskHostPeer('shared-task');
+const hostStamp = { dataOwnerId: 'host-account', ownerGeneration: 4 };
+const localStamp = { dataOwnerId: 'guest-account', ownerGeneration: 2 };
+
+beforeEach(() => {
+ resetRemoteDataOwnerPushFence();
+ setDataOwnerGeneration('guest-account', 2);
+});
+
+describe('shared task push owner', () => {
+ it('accepts a restarted host only after Main advances its verified source epoch', () => {
+ bindSharedTaskPushOwner(peer, 'host-account');
+ const push = (generation: number, sourceEpoch: number) => ({
+ deviceId: peer, ownerStamp: { ...hostStamp, ownerGeneration: generation }, sourceEpoch,
+ });
+ expect(isDeviceLinkRemotePushCurrent(push(7, 10), localStamp)).toBe(true);
+ expect(isDeviceLinkRemotePushCurrent(push(1, 10), localStamp)).toBe(false);
+ bindSharedTaskPushOwner(peer, 'host-account');
+ expect(isDeviceLinkRemotePushCurrent(push(1, 10), localStamp)).toBe(false);
+ expect(isDeviceLinkRemotePushCurrent(push(1, 11), localStamp)).toBe(true);
+ expect(isDeviceLinkRemotePushCurrent(push(8, 10), localStamp)).toBe(false);
+ expect(isDeviceLinkRemotePushCurrent(push(0, 11), localStamp)).toBe(false);
+ expect(isDeviceLinkRemotePushCurrent({ deviceId: peer, ownerStamp: hostStamp }, localStamp)).toBe(false);
+ expect(isDeviceLinkRemotePushCurrent(push(2, 11), localStamp)).toBe(true);
+ });
+
+ it('never resets an unrelated peer or accepts an epoch from a stale account', () => {
+ const other = sharedTaskHostPeer('other-task');
+ bindSharedTaskPushOwner(peer, 'host-account');
+ bindSharedTaskPushOwner(other, 'host-account');
+ const push = { deviceId: peer, ownerStamp: hostStamp, sourceEpoch: 1 };
+ expect(isDeviceLinkRemotePushCurrent(push, localStamp)).toBe(true);
+ expect(isDeviceLinkRemotePushCurrent({ ...push, deviceId: other }, localStamp)).toBe(true);
+ const next = { ...push, sourceEpoch: 2, ownerStamp: { ...hostStamp, ownerGeneration: 1 } };
+ expect(isDeviceLinkRemotePushCurrent(next, { ...localStamp, ownerGeneration: 1 })).toBe(false);
+ expect(isDeviceLinkRemotePushCurrent({ ...next, ownerStamp: { ...hostStamp, dataOwnerId: 'wrong' } }, localStamp)).toBe(false);
+ expect(isDeviceLinkRemotePushCurrent({ ...next, sourceEpoch: 1 }, localStamp)).toBe(false);
+ expect(isDeviceLinkRemotePushCurrent(next, localStamp)).toBe(true);
+ expect(isDeviceLinkRemotePushCurrent({ ...next, deviceId: other, sourceEpoch: 1 }, localStamp)).toBe(false);
+ expect(isRemoteDataOwnerPushCurrent('ordinary', localStamp, true, 1)).toBe(true);
+ expect(isRemoteDataOwnerPushCurrent('ordinary', { ...localStamp, ownerGeneration: 1 }, true, 2)).toBe(false);
+ });
+
+ it('accepts the authenticated host account with independent source and local generations', () => {
+ bindSharedTaskPushOwner(peer, 'host-account');
+ expect(isDeviceLinkRemotePushCurrent({ deviceId: peer, ownerStamp: hostStamp }, localStamp)).toBe(true);
+ expect(isDeviceLinkRemotePushCurrent({ deviceId: peer, ownerStamp: hostStamp }, { ...localStamp, ownerGeneration: 1 })).toBe(false);
+ expect(isRemoteDataOwnerPushCurrent(peer, { ...hostStamp, ownerGeneration: 3 })).toBe(false);
+ expect(isRemoteDataOwnerPushCurrent(peer, { ...hostStamp, dataOwnerId: 'guest-account' })).toBe(false);
+ });
+
+ it('requires an authenticated binding and a valid stamp for shared hosts', () => {
+ expect(isRemoteDataOwnerPushCurrent(peer, hostStamp)).toBe(false);
+ bindSharedTaskPushOwner(peer, 'host-account');
+ expect(isRemoteDataOwnerPushCurrent(peer, undefined)).toBe(false);
+ expect(isRemoteDataOwnerPushCurrent(peer, null)).toBe(false);
+ expect(isRemoteDataOwnerPushCurrent(peer, {})).toBe(false);
+ expect(isRemoteDataOwnerPushCurrent('shared-task~shared-task~guest~member~device', hostStamp)).toBe(false);
+ });
+
+ it('invalidates bindings when the local account or generation changes', () => {
+ bindSharedTaskPushOwner(peer, 'host-account');
+ setDataOwnerGeneration('guest-account', 3);
+ expect(isRemoteDataOwnerPushCurrent(peer, hostStamp)).toBe(false);
+ bindSharedTaskPushOwner(peer, 'host-account');
+ expect(isRemoteDataOwnerPushCurrent(peer, hostStamp)).toBe(true);
+ setDataOwnerGeneration('another-account', 4);
+ expect(isRemoteDataOwnerPushCurrent(peer, hostStamp)).toBe(false);
+ setDataOwnerGeneration(null, 5);
+ bindSharedTaskPushOwner(peer, 'host-account');
+ expect(isRemoteDataOwnerPushCurrent(peer, hostStamp)).toBe(false);
+ });
+
+ it('does not replace a current binding or roll back source generation during polling', () => {
+ bindSharedTaskPushOwner(peer, 'host-account');
+ expect(isRemoteDataOwnerPushCurrent(peer, hostStamp)).toBe(true);
+ bindSharedTaskPushOwner(peer, 'other-host');
+ expect(isRemoteDataOwnerPushCurrent(peer, { ...hostStamp, dataOwnerId: 'other-host' })).toBe(false);
+ bindSharedTaskPushOwner(peer, 'host-account');
+ expect(isRemoteDataOwnerPushCurrent(peer, { ...hostStamp, ownerGeneration: 3 })).toBe(false);
+ });
+
+ it('rejects delayed frames after removal, without affecting another shared task', () => {
+ const other = sharedTaskHostPeer('other-task');
+ bindSharedTaskPushOwner(peer, 'host-account');
+ bindSharedTaskPushOwner(other, 'host-account');
+ resetRemoteDataOwnerPushFence(peer);
+ expect(isRemoteDataOwnerPushCurrent(peer, hostStamp)).toBe(false);
+ expect(isRemoteDataOwnerPushCurrent(other, hostStamp)).toBe(true);
+ resetRemoteDataOwnerPushFence();
+ expect(isRemoteDataOwnerPushCurrent(other, hostStamp)).toBe(false);
+ });
+
+ it('retains same-account remote control and legacy unstamped compatibility', () => {
+ expect(isRemoteDataOwnerPushCurrent('ordinary-device', undefined)).toBe(true);
+ expect(isRemoteDataOwnerPushCurrent('ordinary-device', hostStamp)).toBe(false);
+ expect(isRemoteDataOwnerPushCurrent('ordinary-device', { ...localStamp, ownerGeneration: 9 })).toBe(true);
+ expect(isRemoteDataOwnerPushCurrent('ordinary-device', { ...localStamp, ownerGeneration: 8 })).toBe(false);
+ expect(isRemoteDataOwnerPushCurrent('ordinary-device', undefined)).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts b/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts
index b91c49dd6f..1a4feef34f 100644
--- a/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts
@@ -130,7 +130,7 @@ describe('CCAgentSessionView 接线不变式', () => {
expect(sidebarUpperSrc).toContain('isRemoteSessionWriteBlocked(session)');
expect(sidebarUpperSrc).toContain('selectedSessions.some(isRemoteSessionWriteBlocked)');
expect(sessionItemSrc).toContain(
- 'const remoteWritesBlocked = isRemoteSessionWriteBlocked(session)',
+ "const remoteWritesBlocked = isSharedTaskPeer(session.deviceLinkDeviceId ?? '') || isRemoteSessionWriteBlocked(session)",
);
expect(sessionCardSrc).toContain(
'const remoteWritesBlocked = isRemoteSessionWriteBlocked(session)',
diff --git a/apps/desktop/src/renderer/__tests__/sessionContentHeaderDragRegion.test.ts b/apps/desktop/src/renderer/__tests__/sessionContentHeaderDragRegion.test.ts
index 3349144d99..babdca1604 100644
--- a/apps/desktop/src/renderer/__tests__/sessionContentHeaderDragRegion.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sessionContentHeaderDragRegion.test.ts
@@ -10,10 +10,10 @@ const gitContextBadgeSource = readFileSync(resolve(ccAgentDir, 'GitContextBadge.
describe('SessionContentHeader window drag region', () => {
it('does not mark the whole injected session header as no-drag', () => {
expect(sessionHeaderSource).toContain(
- '<div className="flex min-w-0 items-center gap-0.5 pl-1">',
+ '<div className="flex w-full min-w-0 items-center gap-0.5 pl-1">',
);
expect(sessionHeaderSource).not.toMatch(
- /<div\s+className="flex min-w-0 items-center gap-0\.5 pl-1"[\s\S]{0,160}WebkitAppRegion: 'no-drag'/,
+ /<div\s+className="flex w-full min-w-0 items-center gap-0\.5 pl-1"[\s\S]{0,160}WebkitAppRegion: 'no-drag'/,
);
});
@@ -32,7 +32,7 @@ describe('SessionContentHeader window drag region', () => {
// 标题 span 留在 drag region 会让 onDoubleClick 被窗口拖拽区吞掉,
// 双击改名整体失效(d7dc967df 回归)。
expect(sessionHeaderSource).toMatch(
- /onDoubleClick=\{startEdit\}[\s\S]{0,240}style=\{WINDOW_NO_DRAG_STYLE\}/,
+ /onDoubleClick=\{sharedGuest \? undefined : startEdit\}[\s\S]{0,240}style=\{WINDOW_NO_DRAG_STYLE\}/,
);
});
@@ -40,7 +40,7 @@ describe('SessionContentHeader window drag region', () => {
// no-drag 之后拖窗习惯必须用 useManualWindowDrag 补回:按住标题移动
// 依旧拖动窗口,双击仍进改名(两者缺一都是回归)。
expect(sessionHeaderSource).toMatch(
- /\{\.\.\.titleManualDrag\}[\s\S]{0,80}onDoubleClick=\{startEdit\}/,
+ /\{\.\.\.titleManualDrag\}[\s\S]{0,80}onDoubleClick=\{sharedGuest \? undefined : startEdit\}/,
);
expect(sessionHeaderSource).toContain(
'const titleManualDrag = useManualWindowDrag();',
diff --git a/apps/desktop/src/renderer/__tests__/voiceInputEditorEditability.test.ts b/apps/desktop/src/renderer/__tests__/voiceInputEditorEditability.test.ts
index 0fecd2cdba..0f0237f438 100644
--- a/apps/desktop/src/renderer/__tests__/voiceInputEditorEditability.test.ts
+++ b/apps/desktop/src/renderer/__tests__/voiceInputEditorEditability.test.ts
@@ -29,7 +29,7 @@ describe('ChatInput voice lifecycle locks', () => {
const permissionEnd = chatInputSource.indexOf('/>', permissionStart);
expect(permissionEnd).toBeGreaterThan(permissionStart);
const permissionBlock = chatInputSource.slice(permissionStart, permissionEnd);
- expect(permissionBlock).toContain('disabled={composerEditorLocked || settingsLocked}');
+ expect(permissionBlock).toContain('disabled={composerEditorLocked || settingsLocked || sharedGuest}');
expect(permissionBlock).not.toContain('disabled={composerMutationLocked}');
});
diff --git a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx
index dd506bbe4a..ea9a238c4b 100644
--- a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx
+++ b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx
@@ -263,6 +263,7 @@ export const AssistantMessage = memo(function AssistantMessage({
currentSessionId ? originDeviceId(sessionFileOrigin) : undefined,
);
const isRemote = Boolean(remoteHostId);
+ const sharedGuest = isSharedTaskPeer(originDeviceId(sessionFileOrigin) ?? '');
const forkSupported = !isRemote && (!agentKind || (capabilities?.fork?.supported ?? true));
const handleFork = useForkAtMessage({
sessionId: currentSessionId,
@@ -409,10 +410,10 @@ export const AssistantMessage = memo(function AssistantMessage({
align="left"
hovered={hovered}
simplifiedBotConversation={simplifiedBotConversation}
- onFork={canFork ? handleFork : undefined}
+ onFork={!sharedGuest && canFork ? handleFork : undefined}
onAddToChat={messageDeepLink ? handleAddToChat : undefined}
onShareAsImage={handleShareAsImage}
- onDelete={currentSessionId && messageClientId ? handleDelete : undefined}
+ onDelete={!sharedGuest && currentSessionId && messageClientId ? handleDelete : undefined}
turnMoney={turnMoney}
turnCostUsd={turnCostUsd}
turnCostIsEstimate={turnCostIsEstimate}
@@ -425,3 +426,4 @@ export const AssistantMessage = memo(function AssistantMessage({
</div>
);
});
+import { isSharedTaskPeer } from '@cindy/device-link';
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index 35614f0dd6..cb14d098de 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -6374,6 +6374,7 @@ const MessageItem = memo(function MessageItem({
case 'user':
return (
<UserMessage
+ sharedAuthorName={message.sharedAuthorName}
workingDir={workingDir}
content={message.content}
sessionReferences={message.sessionReferences}
diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
index 0dbd706d1b..dcf7ff8495 100644
--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx
+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
@@ -1,4 +1,5 @@
import type { ImMessageSource } from '../../../shared/imMessageSource';
+import { isSharedTaskPeer } from '@cindy/device-link';
import { hasEmbeddedImPrompt } from './userMessageDisplayText';
/**
* UserMessage
@@ -143,6 +144,7 @@ type UserImageItem =
| { base64: string; mimeType: string; originalName?: string };
interface UserMessageProps {
+ sharedAuthorName?: string;
/** F2: session cwd used to resolve relative paths in inline @-chip refs.
* Stable per-session — only changes on session switch. */
workingDir: string;
@@ -941,6 +943,7 @@ export function renderContent(
// 老 UserImageItemView 已迁出,见 ChatImageView.tsx。
export function UserMessage({
+ sharedAuthorName,
workingDir,
allowPrivilegedLinks = true,
content,
@@ -978,6 +981,7 @@ export function UserMessage({
// context 更新会穿透 memo 触发重渲,替代旧的 render 期一次性读取)。
const sessionFileCtx = useChatSessionFile();
const remoteDeviceId = originDeviceId(sessionFileCtx.origin);
+ const sharedGuest = isSharedTaskPeer(remoteDeviceId ?? '');
const gitSafetyAutoSnapshotEnabled = useGitSafetyAutoSnapshotEnabledForDevice(remoteDeviceId);
const remoteMediaOrigin = useMemo(
() => toRemoteMediaOrigin(sessionFileCtx.origin, sessionFileCtx.workingDir),
@@ -1222,6 +1226,7 @@ export function UserMessage({
// 同时按 capabilities.fork.supported gate (Codex 现支持; 未来若 agent 不支持自动隐藏)。
const navigationMode = useSessionNavigationMode();
const canFork =
+ !sharedGuest &&
isInteractiveSessionNavigationMode(navigationMode) &&
Boolean(sessionId && messageClientId) &&
!isFirstUserMessage &&
@@ -1274,6 +1279,7 @@ export function UserMessage({
// NO_PRIOR_ASSISTANT。直接藏掉按钮,避免无效点击。
// 同时按 capabilities.rewind.supported gate;Codex 入口还要用户显式开启 Git safety。
const canRewind =
+ !sharedGuest &&
Boolean(sessionId && messageClientId) &&
!isFirstUserMessage &&
rewindSupported &&
@@ -1290,9 +1296,9 @@ export function UserMessage({
// 普通重发(onCommitOverride),故可编辑条件与 rewind 无关——只要有
// session/clientId 就能改了重发。
const isBlocked = Boolean(blockedByGhost);
- const canEdit = isBlocked
+ const canEdit = !sharedGuest && (isBlocked
? Boolean(sessionId && messageClientId)
- : canRewind && Boolean(isLastUserMessage);
+ : canRewind && Boolean(isLastUserMessage));
// 中断运行中的 turn——Stop 语义与输入框的 Stop 按钮完全一致
// (useCCAgentChat.stopSession):有排队消息时 keepQueue+pauseQueue(停当前 +
@@ -1367,7 +1373,7 @@ export function UserMessage({
onFork={!isBlocked && canFork ? handleFork : undefined}
onAddToChat={!isBlocked && messageDeepLink ? handleAddToChat : undefined}
onShareAsImage={handleShareAsImage}
- onDelete={!isBlocked && sessionId && messageClientId ? handleDelete : undefined}
+ onDelete={!sharedGuest && !isBlocked && sessionId && messageClientId ? handleDelete : undefined}
onEdit={canEdit ? handleEdit : undefined}
onRewind={!isBlocked && canRewind ? handleRewind : undefined}
rewindInFlight={rewindOpen}
@@ -1447,6 +1453,7 @@ export function UserMessage({
: 'max-w-[488px] items-end',
)}
>
+ {sharedAuthorName && <span className="text-12 text-[var(--text-secondary)]">{sharedAuthorName}</span>}
{orcaCommunication ? (
<div
className={cn(
diff --git a/apps/desktop/src/renderer/components/layout/__tests__/ChromeActions.fullscreen.test.tsx b/apps/desktop/src/renderer/components/layout/__tests__/ChromeActions.fullscreen.test.tsx
index aee6334d75..e8508e08c0 100644
--- a/apps/desktop/src/renderer/components/layout/__tests__/ChromeActions.fullscreen.test.tsx
+++ b/apps/desktop/src/renderer/components/layout/__tests__/ChromeActions.fullscreen.test.tsx
@@ -23,6 +23,9 @@ vi.mock('@/components/ui/dropdown-menu', () => ({
}));
import { ChromeActions } from '../ChromeActions';
+vi.mock('@/features/device-link/useSharedTaskTasks', () => ({ useSharedTaskTasks: vi.fn() }));
+vi.mock('@/features/device-link/JoinSharedTaskDialog', () => ({ JoinSharedTaskDialog: () => null }));
+vi.mock('@/features/device-link/SharedTaskEndedNotice', () => ({ SharedTaskEndedNotice: () => null }));
afterEach(() => {
cleanup();
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index f1728b622e..99bb71fa84 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -12,6 +12,7 @@ import {
type ReactNode,
} from 'react';
import { createPortal } from 'react-dom';
+import { isSharedTaskPeer } from '@cindy/device-link';
import { useNavigate } from 'react-router-dom';
import { buildLocalSkillPathRoute } from '@/features/skillhub/lib/localRoutes';
import { Folder, MessageSquarePlus, Mic, Pen, TriangleAlert, X } from 'lucide-react';
@@ -1156,6 +1157,7 @@ export function ChatInput({
// device-link 远程会话:null = 已确认本地会话,undefined = 所有权尚未解析,string = 远程会话。
// 预测守卫用原始值区分 null vs undefined,下游通路继续用 ?? undefined 归一化。
const deviceLinkDeviceId = _deviceLinkDeviceId;
+ const sharedGuest = isSharedTaskPeer(deviceLinkDeviceId ?? '');
const { t } = useTranslation();
const navigate = useNavigate();
const { preference: composerSendShortcutPreference } = useComposerSendShortcutPreference();
@@ -1229,7 +1231,7 @@ export function ChatInput({
// 会话内「新建目标」对本机与 device-link 远程会话都开放:远程会话的 setGoal / 状态
// 订阅经 goalApiFor / subscribeGoalStatusChanged 隧道到被控端 goal-host(目标随会话
// 在被控端自主续跑)。历史上 device-link 曾被排除(reviewer #354,当时无隧道路由)。
- const inSessionGoalEnabled = !!sessionId;
+ const inSessionGoalEnabled = !!sessionId && !sharedGuest;
// 无参 `/goal` 命令 → 等同点「新建目标」:main 广播 goalAction:'open-dialog',
// 这里按 sessionId 过滤后打开本会话的弹窗(命令侧已确保有 session)。
useEffect(() => {
@@ -1853,8 +1855,8 @@ export function ChatInput({
// 与下拉菜单看到的顺序一致。伙伴保留这两个入口;任务设置锁定时一起禁用。
const permissionCycleOptions = useMemo(
() =>
- settingsLocked ? [] : (activeAgentCapabilities?.permissionModes ?? []),
- [activeAgentCapabilities, settingsLocked],
+ settingsLocked || sharedGuest ? [] : (activeAgentCapabilities?.permissionModes ?? []),
+ [activeAgentCapabilities, settingsLocked, sharedGuest],
);
const permissionCycleOptionsRef = useRef(permissionCycleOptions);
permissionCycleOptionsRef.current = permissionCycleOptions;
@@ -1868,7 +1870,7 @@ export function ChatInput({
// 计划模式入口门控:agent capability(device-link 老被控端无此字段 → 隐藏)+ 父组件接线。
const planModeSupported = activeAgentCapabilities?.planMode?.supported === true;
const planModeEntry =
- !settingsLocked && planModeSupported && onPlanModeChange
+ !sharedGuest && !settingsLocked && planModeSupported && onPlanModeChange
? { enabled: planModeEnabled, onToggle: (next: boolean) => void onPlanModeChange(next) }
: undefined;
// 当前 activeModel 归属的 agent runtime —— 用于 send 预检里按 (model, agent) 查
@@ -8739,7 +8741,7 @@ export function ChatInput({
onPermissionModeChange={handlePermissionModeChange}
vendorKey={vendorKey}
deviceId={deviceLinkDeviceId ?? undefined}
- disabled={composerEditorLocked || settingsLocked}
+ disabled={composerEditorLocked || settingsLocked || sharedGuest}
dense={effectiveDenseToolbar}
iconOnly={useUltraCompactToolbar}
visualVariant={isCreateAgentVariant ? 'create-agent' : 'default'}
diff --git a/apps/desktop/src/renderer/components/title-bar/MenuButton.tsx b/apps/desktop/src/renderer/components/title-bar/MenuButton.tsx
index cb70eac5c6..0abf1cfbdd 100644
--- a/apps/desktop/src/renderer/components/title-bar/MenuButton.tsx
+++ b/apps/desktop/src/renderer/components/title-bar/MenuButton.tsx
@@ -15,15 +15,20 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Tip } from '@/components/ui/tooltip';
+import { JoinSharedTaskDialog } from '@/features/device-link/JoinSharedTaskDialog';
+import { useSharedTaskTasks } from '@/features/device-link/useSharedTaskTasks';
+import { SharedTaskEndedNotice } from '@/features/device-link/SharedTaskEndedNotice';
export function MenuButton({ onExitFullscreen }: { onExitFullscreen?: () => void }) {
const { t } = useTranslation();
const navigate = useNavigate();
const location = useLocation();
const [menuOpen, setMenuOpen] = useState(false);
+ const [joinOpen, setJoinOpen] = useState(false);
+ useSharedTaskTasks();
return (
- <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
+ <><DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
<DropdownMenuTrigger asChild>
<Tip text={t('titleBar.menu')} side="bottom" controlledOpen={menuOpen ? false : undefined}>
{/* 尺寸与 ChromeActions 的折叠按钮同规格(h-7 / 图标 15 / rounded-md),
@@ -44,6 +49,9 @@ export function MenuButton({ onExitFullscreen }: { onExitFullscreen?: () => void
</Tip>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="bg-titlebar border-titlebar-border">
+ <DropdownMenuItem className="focus:bg-titlebar-button-hover" onSelect={() => setJoinOpen(true)}>
+ {t('sharedTask.join')}
+ </DropdownMenuItem>
{onExitFullscreen && (
<DropdownMenuItem className="focus:bg-titlebar-button-hover" onSelect={onExitFullscreen}>
{t('contentHeader.exitFullscreen')}
@@ -113,5 +121,7 @@ export function MenuButton({ onExitFullscreen }: { onExitFullscreen?: () => void
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
+ <SharedTaskEndedNotice onJoin={() => setJoinOpen(true)} />
+ {joinOpen && <JoinSharedTaskDialog open={joinOpen} onOpenChange={setJoinOpen} />}</>
);
}
diff --git a/apps/desktop/src/renderer/components/title-bar/__tests__/MenuButton.test.tsx b/apps/desktop/src/renderer/components/title-bar/__tests__/MenuButton.test.tsx
index 9460881f56..1f1e570f32 100644
--- a/apps/desktop/src/renderer/components/title-bar/__tests__/MenuButton.test.tsx
+++ b/apps/desktop/src/renderer/components/title-bar/__tests__/MenuButton.test.tsx
@@ -20,6 +20,9 @@ vi.mock('@/lib/checkForUpdateWithToast', () => ({
}));
import { MenuButton } from '@/components/title-bar/MenuButton';
+vi.mock('@/features/device-link/useSharedTaskTasks', () => ({ useSharedTaskTasks: vi.fn() }));
+vi.mock('@/features/device-link/JoinSharedTaskDialog', () => ({ JoinSharedTaskDialog: () => null }));
+vi.mock('@/features/device-link/SharedTaskEndedNotice', () => ({ SharedTaskEndedNotice: () => null }));
afterEach(() => {
cleanup();
diff --git a/apps/desktop/src/renderer/components/ui/__tests__/confirmDialogA11y.test.tsx b/apps/desktop/src/renderer/components/ui/__tests__/confirmDialogA11y.test.tsx
index 2e31d9f1de..bc0b9b103f 100644
--- a/apps/desktop/src/renderer/components/ui/__tests__/confirmDialogA11y.test.tsx
+++ b/apps/desktop/src/renderer/components/ui/__tests__/confirmDialogA11y.test.tsx
@@ -99,6 +99,14 @@ describe('ConfirmDialog confirmIcon', () => {
});
describe('ConfirmDialog action layout', () => {
+ it.each([false, true])('preserves cancel focus with cancelFirst=%s', (cancelFirst) => {
+ render(<ConfirmDialog presentation="standard" cancelFirst={cancelFirst} open onOpenChange={() => {}}
+ title="Confirm" description="Description" confirmText="Confirm action" cancelText="Keep" />);
+ expect(screen.getAllByRole('button').map((button) => button.textContent)).toEqual(
+ cancelFirst ? ['Keep', 'Confirm action'] : ['Confirm action', 'Keep'],
+ );
+ expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Keep' }));
+ });
it('keeps action labels on one line without allowing buttons to shrink', () => {
render(
<ConfirmDialog
diff --git a/apps/desktop/src/renderer/components/ui/confirm-dialog.tsx b/apps/desktop/src/renderer/components/ui/confirm-dialog.tsx
index 449d9bc60f..6a7b00c0e1 100644
--- a/apps/desktop/src/renderer/components/ui/confirm-dialog.tsx
+++ b/apps/desktop/src/renderer/components/ui/confirm-dialog.tsx
@@ -13,6 +13,8 @@ import { Tooltip } from '@/components/ui/tooltip';
export interface ConfirmDialogProps {
/** Explicit pilot opt-in; unselected callers retain their existing presentation. */
presentation?: 'standard';
+ /** Explicit design opt-in for standard dialogs; existing callers keep confirm-first order. */
+ cancelFirst?: boolean;
open: boolean;
onOpenChange: (open: boolean) => void;
title: string;
@@ -97,6 +99,7 @@ export interface ConfirmDialogProps {
export function ConfirmDialog({
open,
presentation,
+ cancelFirst = false,
onOpenChange,
title,
description,
@@ -160,6 +163,14 @@ export function ConfirmDialog({
});
return () => cancelAnimationFrame(raf);
}, [open]);
+ const standardCancel = showCancel && (
+ <AlertDialog.Cancel asChild>
+ <Button size="lg" variant="secondary" disabled={loading} onClick={() => onCancel?.()}
+ className="h-auto min-h-9 min-w-[96px] max-w-full whitespace-normal [overflow-wrap:anywhere] border-[var(--confirm-btn-secondary-border)] bg-transparent py-1.5 text-[var(--confirm-btn-secondary-text)] enabled:hover:bg-[var(--confirm-btn-secondary-hover)] enabled:active:bg-[var(--confirm-btn-secondary-hover)]">
+ {resolvedCancelText}
+ </Button>
+ </AlertDialog.Cancel>
+ );
return (
<AlertDialog.Root open={open} onOpenChange={onOpenChange}>
<AlertDialog.Portal>
@@ -339,6 +350,7 @@ export function ConfirmDialog({
)}
{presentation === 'standard' ? (
<div className="mt-6 flex shrink-0 flex-wrap justify-end gap-2.5">
+ {cancelFirst && standardCancel}
<AlertDialog.Action asChild>
<Button
ref={confirmBtnRef}
@@ -374,19 +386,7 @@ export function ConfirmDialog({
{tertiaryText}
</Button>
)}
- {showCancel && (
- <AlertDialog.Cancel asChild>
- <Button
- size="lg"
- variant="secondary"
- disabled={loading}
- onClick={() => onCancel?.()}
- className="h-auto min-h-9 min-w-[96px] max-w-full whitespace-normal [overflow-wrap:anywhere] border-[var(--confirm-btn-secondary-border)] bg-transparent py-1.5 text-[var(--confirm-btn-secondary-text)] enabled:hover:bg-[var(--confirm-btn-secondary-hover)] enabled:active:bg-[var(--confirm-btn-secondary-hover)]"
- >
- {resolvedCancelText}
- </Button>
- </AlertDialog.Cancel>
- )}
+ {!cancelFirst && standardCancel}
</div>
) : (
<div className="mt-6 flex shrink-0 flex-wrap justify-end gap-2.5">
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botChatSurface.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botChatSurface.test.ts
index 7af0bc52e9..9810184f07 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botChatSurface.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botChatSurface.test.ts
@@ -66,7 +66,7 @@ describe('伙伴输入框只保留对话动作', () => {
});
it('伙伴仍可使用权限快捷键,锁定任务不能切换', () => {
- expect(chatInput).toContain('settingsLocked ? [] : (activeAgentCapabilities?.permissionModes ?? [])');
+ expect(chatInput).toContain('settingsLocked || sharedGuest ? [] : (activeAgentCapabilities?.permissionModes ?? [])');
expect(chatInput).not.toContain('settingsLocked || hideRuntimeControls');
});
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index a7e95c11af..eb02c74ba8 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -150,6 +150,7 @@ import { useSessionBinding } from '@/hooks/useSessionBinding';
import { useVendorAuthGate } from '@/hooks/useVendorAuthGate';
import { useProviders } from '@/hooks/useProviders';
import { useAuth } from '@/contexts/AuthContext';
+import { notifySharedTaskEnded } from '@/features/device-link/SharedTaskEndedNotice';
import {
getDataOwnerGeneration,
isDataOwnerGenerationCurrent,
@@ -1215,7 +1216,8 @@ export function CCAgentSessionView({
});
if (!decision.exit) return;
wasRemoteSessionRef.current = false;
- if (decision.toastOffline) {
+ const sharedTaskEnded = ownsWindowRoute && notifySharedTaskEnded(dev0);
+ if (decision.toastOffline && !sharedTaskEnded) {
toast.warning(t('settings.devices.toast.remoteSessionEnded'));
}
if (!ownsWindowRoute) {
@@ -5147,7 +5149,15 @@ export function CCAgentSessionView({
</div>
}
>
- {pendingPlanReview ? (
+ {isSharedTaskPeer(remoteDeviceId ?? '') ? (
+ (pendingPlanReview || pendingPermission || pendingAskUser || pendingPluginSetup || pendingIssueConfirm || pendingRenameSessionsConfirm || pendingGhostGrantConfirm) &&
+ <div className="space-y-2 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-4 text-[var(--text-primary)]">
+ <p className="text-13 text-[var(--text-secondary)]">{t('sharedTask.waitingHost')}</p>
+ <pre className="max-h-64 overflow-auto whitespace-pre-wrap break-words text-13">{pendingPlanReview?.plan ?? (pendingPermission
+ ? [pendingPermission.title ?? pendingPermission.toolName, pendingPermission.description, JSON.stringify(pendingPermission.input, null, 2)].filter(Boolean).join('\n')
+ : JSON.stringify(pendingAskUser?.questions ?? pendingPluginSetup ?? pendingIssueConfirm ?? pendingRenameSessionsConfirm ?? pendingGhostGrantConfirm, null, 2))}</pre>
+ </div>
+ ) : pendingPlanReview ? (
<>
<PlanViewerCard
pending={pendingPlanReview}
@@ -5214,7 +5224,7 @@ export function CCAgentSessionView({
) : null}
</InteractionPromptHost>
{/* 会话内 /goal 进行中状态条(composer 上方);无 goal 时返回 null 不占位。 */}
- <GoalIndicator sessionId={sessionId} />
+ {!isSharedTaskPeer(remoteDeviceId ?? '') && <GoalIndicator sessionId={sessionId} />}
{/* 互斥:控制端能终结的 pending interaction 会接管 composer;
Desktop-only 只读确认只能提示等待,必须保留 ChatInput,避免控制端
既处理不了确认又无法继续发送或排队消息。
@@ -5225,13 +5235,13 @@ export function CCAgentSessionView({
4. 默认 → ChatInput
Cindy Make 沿用输入框的背景与边框,准备详情限高滚动;
接管与 worktree 创建继续使用 90px 状态框。 */}
- {pendingPlanReview ||
+ {!isSharedTaskPeer(remoteDeviceId ?? '') && (pendingPlanReview ||
pendingPermission ||
pendingAskUser ||
pendingPluginSetup ||
pendingIssueConfirm ||
pendingRenameSessionsConfirm ||
- pendingGhostGrantConfirm ? null : sessionBinding.attached && sessionId ? (
+ pendingGhostGrantConfirm) ? null : sessionBinding.attached && sessionId ? (
<TakeoverMask
sessionId={sessionId}
channel={sessionBinding.identity?.channel ?? 'feishu'}
@@ -6284,3 +6294,4 @@ function ContextCapacityRing({
</Tip>
);
}
+import { isSharedTaskPeer } from '@cindy/device-link';
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index 8dd787d697..d6de783909 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -68,6 +68,8 @@ import { useOwnTopNavScrollableRows, useSidebarCollapsedState } from '../feature
import { SidebarTopNav } from '@/components/sidebar/SidebarTopNav';
import { SidebarFilterPopover } from './sidebar/SidebarFilterPopover';
import { MainListScopeHeader } from './sidebar/MainListScopeHeader';
+import { SharedTasksSection } from '@/features/device-link/SharedTasksSection';
+import { isSharedTaskPeer } from '@cindy/device-link';
import { stripTrailingPathSeparators } from '../../../shared/pathText';
import {
SessionAttentionUrgencyProvider,
@@ -570,7 +572,8 @@ export function CCAgentSidebarUpper() {
}
}, [filter.status, remoteDevices, selectedMachineId]);
const sessionsWithRemote = useMemo(
- () => selectVisibleSessions(sessionsHook.sessions, remoteProjectSessions, selectedMachineId),
+ () => selectVisibleSessions(sessionsHook.sessions, remoteProjectSessions, selectedMachineId)
+ .filter(session => !session.deviceLinkDeviceId || !isSharedTaskPeer(session.deviceLinkDeviceId)),
[sessionsHook.sessions, remoteProjectSessions, selectedMachineId],
);
const statusFilteredSessionsWithRemote = useMemo(
@@ -1391,7 +1394,8 @@ function ExpandedView({
);
const scopedSidebarSessions = useMemo(
() =>
- selectVisibleSessions(sessions, remoteProjectSessions, selectedMachineId).filter(
+ selectVisibleSessions(sessions, remoteProjectSessions, selectedMachineId)
+ .filter(session => !session.deviceLinkDeviceId || !isSharedTaskPeer(session.deviceLinkDeviceId)).filter(
passesOrcaAndStatus,
),
[sessions, remoteProjectSessions, selectedMachineId, passesOrcaAndStatus],
@@ -3590,6 +3594,10 @@ function ExpandedView({
) : null}
{/* 搜索时原列表只隐藏、不卸载:置顶段折叠等本地 state 才能保住。 */}
<div hidden={searchActive} className="flex flex-col gap-2">
+ <SharedTasksSection activeSessionId={activeSessionId} localSessions={sessions} onSelect={(id) => {
+ clearNotification(id);
+ navigate('/cc-agent/' + encodeURIComponent(id));
+ }} />
{remoteSessionBootstrapFailures.length > 0 && !hasVisibleSidebarContent ? (
<>
<MainListScopeHeader
diff --git a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
index a1aa4f5246..9f1e3ecb47 100644
--- a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
@@ -83,6 +83,8 @@ import { useRemoteProjectSessions } from '@/features/device-link/remoteProjectsS
import { isRemoteSessionWriteBlocked } from './lib/remoteSessionWriteGuard';
import { Tip } from '@/components/ui/tooltip';
import { TaskTagDots, TaskTagMenuSection, TaskTagEditor } from '@/features/task-tags/TaskTags';
+import { SharedTaskButton } from '@/features/device-link/SharedTaskButton';
+import { isSharedTaskPeer } from '@cindy/device-link';
const log = createLogger('SessionContentHeader');
@@ -148,6 +150,7 @@ export function SessionContentHeader({
// 会停留在旧值(Codex review P2)。prop 兜底覆盖 archived 等不在
// active 桶里的会话。
const session = routeSessionById.get(sessionProp.id) ?? sessionProp;
+ const sharedGuest = isSharedTaskPeer(session.deviceLinkDeviceId ?? '');
const { runningSessionIds } = useSessionRunningStatus(session.id);
const { confirm: confirmDialog } = useConfirmDialog();
const { runSessionAction, unarchiveSession } = useSessionLifecycleActions();
@@ -157,7 +160,7 @@ export function SessionContentHeader({
// Draft 判定与 SessionItem 同口径:标题仍是默认哨兵且无消息。
const isEmpty = isEmptyDraftSession(session);
const remoteWritesBlocked =
- readOnly || remoteSessionUnavailable || isRemoteSessionWriteBlocked(session);
+ readOnly || sharedGuest || remoteSessionUnavailable || isRemoteSessionWriteBlocked(session);
// 「移动到项目」/「导出会话…」可见性与 SessionItem 同条件。
const canMoveToProject =
!isEmpty && !session.remoteHostId && !session.deviceLinkDeviceId && !isArchived;
@@ -538,7 +541,7 @@ export function SessionContentHeader({
]);
return (
- <div className="flex min-w-0 items-center gap-0.5 pl-1">
+ <div className="flex w-full min-w-0 items-center gap-0.5 pl-1">
{isPinned && (
<Pin
size={13}
@@ -589,7 +592,7 @@ export function SessionContentHeader({
// 双击(死区内)不动窗、正常进入改名。
<span
{...titleManualDrag}
- onDoubleClick={startEdit}
+ onDoubleClick={sharedGuest ? undefined : startEdit}
title={displayTitle}
className="min-w-0 max-w-[40vw] cursor-default truncate text-sm font-medium text-foreground"
style={WINDOW_NO_DRAG_STYLE}
@@ -607,7 +610,14 @@ export function SessionContentHeader({
</span>
)}
- {!isEditing && !readOnly && (
+ {/* Task identity stays left; shared-task actions belong to the trailing toolbar. */}
+ {!readOnly && session.status === 'active' && <>
+ <GitContextBadge session={session} />
+ <div className="min-w-0 flex-1" aria-hidden />
+ <SharedTaskButton key={session.id} session={session} />
+ </>}
+
+ {!isEditing && !readOnly && !sharedGuest && (
// 菜单打开就把归档/删除的 dirty 预检发出去:用户从展开菜单到点条目至少
// 一次反应时间,足够这次 git status 跑完,点下去时命中缓存、零等待。
<DropdownMenu
@@ -819,7 +829,7 @@ export function SessionContentHeader({
)}
{/* session-git-pr-context:当前分支 + 关联 PR 徽标(非 git 目录 / dialogue 会话自动隐藏) */}
- <GitContextBadge session={session} />
+ {(readOnly || session.status !== 'active') && <GitContextBadge session={session} />}
{tagEditorOpen && <TaskTagEditor session={session} onClose={() => setTagEditorOpen(false)} />}
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
index 2d0b92fe78..1d4d2846b1 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
@@ -441,7 +441,7 @@ export const SessionItem = withSidebarNavigation<SessionItemProps>(function Sess
}}
/>
);
- const remoteWritesBlocked = isRemoteSessionWriteBlocked(session);
+ const remoteWritesBlocked = isSharedTaskPeer(session.deviceLinkDeviceId ?? '') || isRemoteSessionWriteBlocked(session);
const isAutomationGenerated = isAutomationGeneratedSession(session);
// heartbeat schedule 绑定标识(targetSessionId 指向本会话);schedule 删除/过期后
// schedulesStore 'changed' 刷新 → 列表为空 → 徽章消失。
@@ -1434,3 +1434,4 @@ function SessionAction({
</Tip>
);
}
+import { isSharedTaskPeer } from '@cindy/device-link';
diff --git a/apps/desktop/src/renderer/features/device-link/JoinSharedTaskDialog.tsx b/apps/desktop/src/renderer/features/device-link/JoinSharedTaskDialog.tsx
new file mode 100644
index 0000000000..d34e37df96
--- /dev/null
+++ b/apps/desktop/src/renderer/features/device-link/JoinSharedTaskDialog.tsx
@@ -0,0 +1,201 @@
+import * as Dialog from '@radix-ui/react-dialog';
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+import { Check, Users, X } from 'lucide-react';
+import { sharedTaskHostPeer, type SharedTaskDetail, type SharedTaskOwnedItem, type SharedTaskCloseResult } from '@cindy/device-link';
+import { Button } from '@/components/ui/button';
+import { FormField } from '@/components/ui/form-field';
+import { Input, Textarea } from '@/components/ui/input';
+import { ConfirmDialog } from '@/components/ui/confirm-dialog';
+import { useAuth } from '@/contexts/AuthContext';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
+import type { Session } from '@/lib/ccAgent.types';
+import { toast } from '@/lib/toast';
+import { remoteProjectsStore } from './remoteProjectsStore';
+import { bindSharedTaskPushOwner } from '@/lib/remoteDataOwnerPushFence';
+import { sharedTaskErrorKey } from './sharedTaskCompatibility';
+
+/** Invitation secrets remain in this form and the authenticated Main request only. */
+export function JoinSharedTaskDialog({ open, onOpenChange }: { open: boolean; onOpenChange(open: boolean): void }) {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const { dataOwnerId, isAuthenticated } = useAuth();
+ const ownerGeneration = getDataOwnerGeneration().generation;
+ const [invitation, setInvitation] = useState('');
+ const [displayName, setDisplayName] = useState('');
+ const [request, setRequest] = useState<{ sharedTaskId: string; memberId: string; status: 'joined' } | null>(null);
+ const [error, setError] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [joinedTitle, setJoinedTitle] = useState('');
+ const [confirmLeave, setConfirmLeave] = useState(false);
+ const [owned, setOwned] = useState<SharedTaskOwnedItem[] | null>(null);
+ const [ownedError, setOwnedError] = useState(false);
+ const [closeTargets, setCloseTargets] = useState<SharedTaskOwnedItem[] | null>(null);
+ const keepSharing = useRef<HTMLButtonElement>(null);
+ const pending = useRef(false);
+ const form = useRef<HTMLFormElement>(null);
+ const epoch = useRef(0);
+ const loadOwned = useCallback(async () => {
+ const captured = epoch.current;
+ const owner = getDataOwnerGeneration();
+ setOwnedError(false);
+ try {
+ const items = await window.electronAPI.sharedTask.account({ action: 'owned' }) as SharedTaskOwnedItem[];
+ if (captured === epoch.current && isDataOwnerGenerationCurrent(owner)) setOwned(items);
+ } catch {
+ if (captured === epoch.current && isDataOwnerGenerationCurrent(owner)) { setOwned(null); setOwnedError(true); }
+ }
+ }, []);
+ useEffect(() => {
+ epoch.current++;
+ setInvitation(''); setDisplayName(''); setRequest(null); setError(false);
+ setJoinedTitle(''); setConfirmLeave(false);
+ setOwned(null); setOwnedError(false); setCloseTargets(null);
+ pending.current = false; setBusy(false);
+ if (open && isAuthenticated) void loadOwned();
+ return () => { epoch.current++; };
+ }, [dataOwnerId, ownerGeneration, open, isAuthenticated, loadOwned]);
+ useEffect(() => {
+ if (closeTargets) keepSharing.current?.focus();
+ else if (open && !request) form.current?.querySelector('textarea')?.focus();
+ }, [closeTargets, open, request]);
+ const run = async (work: (current: () => boolean) => Promise<void>) => {
+ if (pending.current) return;
+ pending.current = true; setBusy(true);
+ const captured = epoch.current;
+ const owner = getDataOwnerGeneration();
+ const current = () => captured === epoch.current && isDataOwnerGenerationCurrent(owner);
+ try { await work(current); }
+ catch (error) { if (current()) toast.error(t(sharedTaskErrorKey(error))); }
+ finally { if (captured === epoch.current) { pending.current = false; setBusy(false); } }
+ };
+ const join = () => {
+ if (!/^[A-Za-z0-9_-]{43}$/.test(invitation.trim()) || !displayName.trim()) {
+ setError(true); form.current?.querySelector('textarea')?.focus(); return;
+ }
+ setError(false);
+ void run(async (current) => {
+ const result = await window.electronAPI.sharedTask.account({ action: 'join', invitation: invitation.trim(), displayName: displayName.trim() }) as NonNullable<typeof request>;
+ if (current()) { setInvitation(''); setRequest(result); }
+ if (!current()) return;
+ const detail = await window.electronAPI.sharedTask.account({ action: 'get', sharedTaskId: result.sharedTaskId }) as SharedTaskDetail;
+ if (current()) setJoinedTitle(detail.title);
+ });
+ };
+ const openTask = () => void run(async (current) => {
+ const detail = await window.electronAPI.sharedTask.account({ action: 'get', sharedTaskId: request!.sharedTaskId }) as SharedTaskDetail;
+ if (!current()) return;
+ const peer = sharedTaskHostPeer(detail.sharedTaskId);
+ bindSharedTaskPushOwner(peer, detail.ownerAccountId);
+ await window.electronAPI.deviceLink.openLink(peer);
+ if (!current()) return;
+ const session = await window.electronAPI.deviceLink.invoke(peer, 'local-db:sessions:get', [detail.sessionId]) as Session;
+ if (!current() || session?.id !== detail.sessionId) return;
+ remoteProjectsStore.setDeviceSessions(peer, detail.title, [session]);
+ navigate('/cc-agent/' + encodeURIComponent(session.id));
+ onOpenChange(false);
+ });
+ const closeOwned = () => void run(async (current) => {
+ if (!closeTargets || !current()) return;
+ const failed: SharedTaskOwnedItem[] = [];
+ let closed = 0;
+ // Only close the tasks displayed in the confirmation, including on retry.
+ for (const item of closeTargets) {
+ if (!current()) return;
+ try {
+ const result = await window.electronAPI.sharedTask.account({ action: 'close', sharedTaskId: item.sharedTaskId }) as SharedTaskCloseResult;
+ if (!current()) return;
+ if (result.closed.includes(item.sharedTaskId)) closed++;
+ else failed.push(item);
+ } catch {
+ if (!current()) return;
+ failed.push(item);
+ }
+ }
+ setOwned(failed);
+ setCloseTargets(failed.length ? failed : null);
+ window.dispatchEvent(new Event('cindy:shared-task-owned-changed'));
+ if (closed) toast.success(t('sharedTask.closedToast', { count: closed }));
+ if (failed.length) toast.error(t('sharedTask.closeFailedToast', { count: failed.length }));
+ else void loadOwned();
+ });
+ return <Dialog.Root open={open} onOpenChange={(value) => { if (!pending.current) onOpenChange(value); }}>
+ <Dialog.Portal>
+ <Dialog.Overlay className="fixed inset-0 z-[10000] bg-[var(--overlay-modal)]" />
+ <Dialog.Content className="fixed left-1/2 top-1/2 z-[10001] max-h-[calc(100dvh-32px)] w-[min(440px,calc(100vw-32px))] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-4 text-[var(--text-primary)]"
+ onOpenAutoFocus={(event) => {
+ const input = form.current?.querySelector('textarea');
+ if (input) { event.preventDefault(); input.focus(); }
+ }}
+ onEscapeKeyDown={(event) => {
+ if (pending.current || closeTargets) event.preventDefault();
+ if (!pending.current && closeTargets) setCloseTargets(null);
+ }}
+ onInteractOutside={(event) => { if (pending.current || closeTargets) event.preventDefault(); }}>
+ <div className="mb-4 flex items-center justify-between gap-2">
+ <Dialog.Title className="text-18 font-medium">{t(closeTargets ? 'sharedTask.closeAllTitle' : request ? 'sharedTask.title' : 'sharedTask.join')}</Dialog.Title>
+ {!closeTargets && <Dialog.Close asChild>
+ <Button variant="secondary" size="lg" className="w-9 border-transparent bg-transparent p-0" aria-label={t('sharedTask.dismiss')} disabled={busy}><X size={18} aria-hidden /></Button>
+ </Dialog.Close>}
+ </div>
+ <Dialog.Description className={request ? 'sr-only' : 'mb-4 text-13 text-[var(--text-secondary)]'}>{t(closeTargets ? 'sharedTask.closeAllBody' : request ? 'sharedTask.joinedBody' : 'sharedTask.joinIntro')}</Dialog.Description>
+ {closeTargets && <div>
+ <div className="max-h-56 space-y-2 overflow-y-auto">{closeTargets.map(item => <div key={item.sharedTaskId} className="rounded-lg border border-[var(--border-default)] p-3">
+ <p className="break-words text-13 font-medium">{item.title}</p>
+ <p className="text-11 text-[var(--text-secondary)]">{t(item.local ? 'sharedTask.thisDevice' : 'sharedTask.otherDevice')}</p>
+ </div>)}</div>
+ <p className="mt-4 text-12 text-[var(--text-secondary)]">{t('sharedTask.closeAllScopeNote')}</p>
+ <div className="mt-5 flex flex-wrap items-center justify-between gap-3">
+ <Button ref={keepSharing} variant="secondary" size="lg" disabled={busy} onClick={() => setCloseTargets(null)}>{t('sharedTask.closeAllKeep')}</Button>
+ <Button variant="primary" size="lg" loading={busy} onClick={closeOwned}
+ className="h-auto min-h-9 max-w-full whitespace-normal border-transparent bg-[hsl(var(--destructive))] py-1.5 text-[var(--accent-pure-cta-fg)] enabled:hover:border-transparent enabled:active:border-transparent enabled:hover:bg-[hsl(var(--destructive))] enabled:active:bg-[hsl(var(--destructive))]">
+ {t('sharedTask.closeAllAction', { count: closeTargets.length })}
+ </Button>
+ </div>
+ </div>}
+ <div hidden={!!closeTargets}>
+ {!isAuthenticated ? <p className="text-13">{t('sharedTask.login')}</p>
+ : request?.status === 'joined' ? <>
+ <div className="px-1 py-6 text-center">
+ <span className="mb-4 inline-flex size-11 items-center justify-center rounded-full border border-[var(--border-default)]"><Check size={18} aria-hidden /></span>
+ <h3 className="break-words text-14 font-medium">{joinedTitle ? t('sharedTask.joinedTitle', { title: joinedTitle }) : t('sharedTask.joined')}</h3>
+ <p className="mx-auto mb-5 mt-2 max-w-[280px] text-12 text-[var(--text-secondary)]">{t('sharedTask.joinedBody')}</p>
+ <Button variant="cta" size="lg" loading={busy} onClick={openTask}>{t('sharedTask.enterTask')}</Button>
+ </div>
+ <div className="border-t border-[var(--border-default)] pt-4"><Button variant="secondary" size="lg" className="w-full text-[var(--error-fg)]" disabled={busy} onClick={() => setConfirmLeave(true)}>{t('sharedTask.leave')}</Button></div>
+ </>
+ : <>
+ <div className="mb-4 flex items-center justify-between gap-3 rounded-lg border border-[var(--border-default)] p-3">
+ <div className="min-w-0"><p className="text-13">{t('sharedTask.ownedTitle')}</p>
+ <p className="text-11 text-[var(--text-secondary)]" role="status">{t(ownedError ? 'sharedTask.ownedLoadFailed' : owned === null ? 'sharedTask.loadingOwned' : 'sharedTask.ownedActiveCount', { count: owned?.length ?? 0 })}</p>
+ </div>
+ {ownedError ? <Button variant="secondary" disabled={busy} className="px-3 text-12" onClick={() => void loadOwned()}>{t('sharedTask.retryAction')}</Button>
+ : <Button variant="secondary" className="px-3 text-12" disabled={busy || !owned?.length} onClick={() => setCloseTargets([...(owned ?? [])])}>{t('sharedTask.closeAllShort')}</Button>}
+ </div>
+ <form ref={form} className="space-y-4" onSubmit={(event) => { event.preventDefault(); if (!closeTargets) join(); }}>
+ {request && <p className="text-13" role="status">{t('sharedTask.notJoined')}</p>}
+ <FormField label={t('sharedTask.invitation')} error={error ? t('sharedTask.invalid') : undefined}>
+ {(props) => <Textarea {...props} rows={3} className="min-h-[82px]" surface="ivory" value={invitation} onChange={setInvitation} disabled={busy} placeholder={t('sharedTask.invitationPlaceholder')} autoComplete="off" />}
+ </FormField>
+ <FormField label={t('sharedTask.joinNickname')}>
+ {(props) => <Input {...props} value={displayName} onChange={setDisplayName} disabled={busy} maxLength={32} placeholder={t('sharedTask.nicknamePlaceholder')} />}
+ </FormField>
+ <div className="flex items-start gap-2 rounded-lg bg-[var(--surface-chip)] p-3 text-12 text-[var(--text-secondary)]">
+ <Users size={16} className="mt-0.5 shrink-0" />
+ <p>{t('sharedTask.joinNotice')}</p>
+ </div>
+ <div className="flex justify-end pt-1"><Button type="submit" variant="cta" size="lg" loading={busy}>{t('sharedTask.join')}</Button></div>
+ </form></>}
+ </div>
+ <ConfirmDialog presentation="standard" cancelFirst open={confirmLeave} onOpenChange={(value) => { if (!pending.current) setConfirmLeave(value); }}
+ title={t('sharedTask.leaveTitle')} description={t('sharedTask.leaveBody')} cancelText={t('sharedTask.leaveKeep')}
+ confirmText={t('sharedTask.leave')} confirmVariant="destructive" loading={busy} zIndex={10002} maxWidth={440}
+ onConfirm={() => void run(async (current) => {
+ await window.electronAPI.sharedTask.account({ action: 'leave', sharedTaskId: request!.sharedTaskId });
+ if (current()) { setRequest(null); setJoinedTitle(''); setConfirmLeave(false); }
+ })} />
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>;
+}
diff --git a/apps/desktop/src/renderer/features/device-link/SharedTaskButton.tsx b/apps/desktop/src/renderer/features/device-link/SharedTaskButton.tsx
new file mode 100644
index 0000000000..599264f52e
--- /dev/null
+++ b/apps/desktop/src/renderer/features/device-link/SharedTaskButton.tsx
@@ -0,0 +1,277 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import * as Dialog from '@radix-ui/react-dialog';
+import { Check, Clock, FileText, Link2, Users, X, CircleStop } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import {
+ parseSharedTaskPeer, SHARED_TASK_HOST_CHANNEL,
+ type SharedTaskCloseResult, type SharedTaskDetail, type SharedTaskHostCommand,
+ type SharedTaskHostState, type SharedTaskOwnedItem,
+} from '@cindy/device-link';
+import type { Session } from '@/lib/ccAgent.types';
+import { useAuth } from '@/contexts/AuthContext';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
+import { Button } from '@/components/ui/button';
+import { ConfirmDialog } from '@/components/ui/confirm-dialog';
+import { JoinSharedTaskDialog } from './JoinSharedTaskDialog';
+import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
+import { toast } from '@/lib/toast';
+import { sharedTaskErrorKey } from './sharedTaskCompatibility';
+
+type SharedTaskTab = 'current' | 'owned';
+type ConfirmState =
+ | { kind: 'remove'; memberId: string; name: string }
+ | { kind: 'leave' }
+ | { kind: 'closeCurrent' }
+ | { kind: 'closeAll' };
+
+const tabButton = (active: boolean) => `rounded-full px-3 py-1 text-12 leading-5 transition-colors ${
+ active ? 'bg-[var(--surface-chip)] text-[var(--text-primary)]' : 'text-[var(--text-secondary)] hover:bg-[var(--surface-hover-soft)]'}`;
+
+/** Owner controls use the same task host locally and through own-device control. */
+export function SharedTaskButton({ session }: { session: Session }) {
+ const { t } = useTranslation();
+ const { dataOwnerId } = useAuth();
+ const ownerGeneration = getDataOwnerGeneration().generation;
+ const peer = session.deviceLinkDeviceId ? parseSharedTaskPeer(session.deviceLinkDeviceId) : null;
+ const guestSharedTaskId = peer?.role === 'host' ? peer.sharedTaskId : undefined;
+ const [open, setOpen] = useState(false);
+ const [tab, setTab] = useState<SharedTaskTab>('current');
+ const [state, setState] = useState<SharedTaskHostState | null>(null);
+ const [owned, setOwned] = useState<SharedTaskOwnedItem[] | null>(null);
+ const [confirm, setConfirm] = useState<ConfirmState | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [joinOpen, setJoinOpen] = useState(false);
+ const pending = useRef(false);
+ const epoch = useRef(0);
+ const host = useCallback((command: SharedTaskHostCommand) => session.deviceLinkDeviceId
+ ? window.electronAPI.deviceLink.invoke(session.deviceLinkDeviceId, SHARED_TASK_HOST_CHANNEL, [command])
+ : window.electronAPI.sharedTask.host(command), [session.deviceLinkDeviceId]);
+ const load = useCallback(async (captured: number) => {
+ const owner = getDataOwnerGeneration();
+ try {
+ const result: SharedTaskHostState = guestSharedTaskId
+ ? { available: true, detail: await window.electronAPI.sharedTask.account({ action: 'get', sharedTaskId: guestSharedTaskId }) as SharedTaskDetail }
+ : await host({ action: 'state', sessionId: session.id }) as SharedTaskHostState;
+ if (captured === epoch.current && isDataOwnerGenerationCurrent(owner)) setState(result);
+ } catch (error) {
+ if (captured === epoch.current && isDataOwnerGenerationCurrent(owner)
+ && sharedTaskErrorKey(error) === 'sharedTask.upgrade') {
+ setState({ available: false, detail: null });
+ }
+ }
+ }, [guestSharedTaskId, host, session.id]);
+ const loadOwned = useCallback(async (captured: number) => {
+ const owner = getDataOwnerGeneration();
+ try {
+ const items = await window.electronAPI.sharedTask.account({ action: 'owned' }) as SharedTaskOwnedItem[];
+ if (captured === epoch.current && isDataOwnerGenerationCurrent(owner)) setOwned(Array.isArray(items) ? items : []);
+ } catch (error) {
+ if (captured === epoch.current && isDataOwnerGenerationCurrent(owner)
+ && sharedTaskErrorKey(error) === 'sharedTask.upgrade') setOwned([]);
+ }
+ }, []);
+ const tabRef = useRef<SharedTaskTab>('current');
+ useEffect(() => {
+ const captured = ++epoch.current;
+ setState(null); setOwned(null); setConfirm(null); setTab('current');
+ tabRef.current = 'current';
+ pending.current = false; setBusy(false);
+ void load(captured);
+ if (!open) return () => { epoch.current++; };
+ void loadOwned(captured);
+ const timer = setInterval(() => {
+ if (pending.current) return;
+ void load(captured);
+ if (tabRef.current === 'owned') void loadOwned(captured);
+ }, 5_000);
+ return () => { epoch.current++; clearInterval(timer); };
+ }, [dataOwnerId, ownerGeneration, load, loadOwned, open]);
+ const switchTab = (next: SharedTaskTab) => {
+ tabRef.current = next; setTab(next); setConfirm(null);
+ if (next === 'owned') void loadOwned(epoch.current);
+ };
+ const run = async (work: () => Promise<unknown>, reload = true) => {
+ if (pending.current) return;
+ pending.current = true; setBusy(true);
+ const captured = epoch.current;
+ const owner = getDataOwnerGeneration();
+ const current = () => captured === epoch.current && isDataOwnerGenerationCurrent(owner);
+ try { await work(); if (reload && current()) {
+ window.dispatchEvent(new Event('cindy:shared-task-owned-changed'));
+ await load(captured); void loadOwned(captured);
+ } }
+ catch (error) { if (current()) toast.error(t(sharedTaskErrorKey(error))); }
+ finally { if (captured === epoch.current) { pending.current = false; setBusy(false); } }
+ };
+ const detail = state?.detail?.status === 'active' ? state.detail : null;
+ const invite = () => run(async () => {
+ const captured = epoch.current;
+ const owner = getDataOwnerGeneration();
+ const result = await host({ action: 'invite', sharedTaskId: detail!.sharedTaskId }) as { invitation: string };
+ if (captured !== epoch.current || !isDataOwnerGenerationCurrent(owner)) return;
+ try {
+ await navigator.clipboard.writeText(result.invitation);
+ } catch {
+ // The invitation already exists. A local clipboard failure is not a shared-state failure.
+ if (captured === epoch.current && isDataOwnerGenerationCurrent(owner)) toast.error(t('sharedTask.invitationCopyFailed'));
+ return;
+ }
+ if (captured === epoch.current && isDataOwnerGenerationCurrent(owner)) toast.success(t('sharedTask.invitationCopied'));
+ });
+ const closeAll = () => run(async () => {
+ const captured = epoch.current;
+ const owner = getDataOwnerGeneration();
+ const result = await window.electronAPI.sharedTask.account({ action: 'close', all: true }) as SharedTaskCloseResult;
+ if (captured !== epoch.current || !isDataOwnerGenerationCurrent(owner)) return;
+ setConfirm(null);
+ if (result.closed.length) toast.success(t('sharedTask.closedToast', { count: result.closed.length }));
+ if (result.failed.length) toast.error(t('sharedTask.closeFailedToast', { count: result.failed.length }));
+ });
+ const memberName = (memberId: string, fallback: string) =>
+ detail?.memberLabels.find((label) => label.memberId === memberId)?.displayName ?? fallback;
+ const confirmCopy = (state: ConfirmState): { title: string; body: string; keep: string; action: string; danger?: boolean; run(): void } => {
+ switch (state.kind) {
+ case 'remove':
+ return { title: t('sharedTask.removeNamedTitle', { name: state.name }), body: t('sharedTask.removeBody'), keep: t('sharedTask.removeKeep'), action: t('sharedTask.remove'),
+ run: () => void run(async () => { await host({ action: 'remove', sharedTaskId: detail!.sharedTaskId, memberId: state.memberId }); setConfirm(null); }) };
+ case 'leave':
+ return { title: t('sharedTask.leaveTitle'), body: t('sharedTask.leaveBody'), keep: t('sharedTask.leaveKeep'), action: t('sharedTask.leave'),
+ run: () => void run(async () => {
+ await window.electronAPI.sharedTask.account({ action: 'leave', sharedTaskId: guestSharedTaskId! });
+ setConfirm(null); setOpen(false);
+ }, false) };
+ case 'closeCurrent':
+ return { title: t('sharedTask.closeOneTitle'), body: t('sharedTask.closeOneBody'), keep: t('sharedTask.closeAllKeep'), action: t('sharedTask.close'),
+ run: () => void run(async () => { await host({ action: 'close', sharedTaskId: detail!.sharedTaskId }); setConfirm(null); toast.success(t('sharedTask.closedToast', { count: 1 })); }) };
+ case 'closeAll':
+ return { title: t('sharedTask.closeAllTitle'), body: t('sharedTask.closeAllBody'), keep: t('sharedTask.closeAllKeep'),
+ action: t('sharedTask.closeAllAction', { count: owned?.length ?? 0 }), danger: true,
+ run: () => void closeAll() };
+ }
+ };
+ const emptyIcon = (icon: React.ReactNode) => <span className="mb-4 inline-flex size-11 items-center justify-center rounded-full border border-[var(--border-default)]">{icon}</span>;
+ const noticeClass = 'my-4 flex items-start gap-2 rounded-lg bg-[var(--surface-chip)] p-3 text-12 text-[var(--text-secondary)]';
+ const avatarClass = 'inline-flex size-7 shrink-0 items-center justify-center rounded-full border border-[var(--border-default)] bg-[var(--surface-chip)] text-11';
+ const currentTab = !state ? <p className="text-[var(--text-secondary)]">{t('sharedTask.sharing')}</p>
+ : !state.available ? <p className="text-[var(--text-secondary)]">{t('sharedTask.upgrade')}</p>
+ : !detail && !guestSharedTaskId ? <>
+ <p className="mb-4 text-[var(--text-secondary)]">{t('sharedTask.startIntro')}</p>
+ <div className="my-2.5 flex items-center gap-2.5 rounded-lg border border-[var(--border-default)] p-3">
+ <FileText size={18} className="shrink-0" aria-hidden />
+ <div className="min-w-0">
+ <div className="break-words text-13 font-medium">{session.title || t('sharedTask.title')}</div>
+ <div className="text-11 text-[var(--text-secondary)]">{t(session.deviceLinkDeviceId ? 'sharedTask.runsOnHostDevice' : 'sharedTask.runsOnThisDevice')}</div>
+ </div>
+ </div>
+ <div className={noticeClass}><Users size={16} className="mt-0.5 shrink-0" aria-hidden /><p>{t('sharedTask.inviteNotice')}</p></div>
+ <p className="text-12 text-[var(--text-secondary)]">{t('sharedTask.offlineAutoClose')}</p>
+ <div className="mt-5"><Button variant="cta" size="lg" className="w-full" loading={busy} onClick={() => void run(() => host({ action: 'open', sessionId: session.id }))}>{t('sharedTask.open')}</Button></div>
+ </>
+ : detail && guestSharedTaskId ? <>
+ <div className="px-1 py-6 text-center">
+ {emptyIcon(<Check size={18} aria-hidden />)}
+ <h3 className="break-words text-14 font-medium">{t('sharedTask.joinedTitle', { title: detail.title })}</h3>
+ <p className="mx-auto mb-5 mt-2 max-w-[280px] text-12 text-[var(--text-secondary)]">{t('sharedTask.joinedBody')}</p>
+ <Button variant="cta" size="lg" onClick={() => setOpen(false)}>{t('sharedTask.enterTask')}</Button>
+ </div>
+ <div className="border-t border-[var(--border-default)] pt-4"><Button variant="secondary" size="lg" disabled={busy} className="w-full text-[var(--error-fg)]"
+ onClick={() => setConfirm({ kind: 'leave' })}>{t('sharedTask.leave')}</Button></div>
+ </>
+ : detail ? <>
+ <div className="mb-2 break-words text-12 text-[var(--text-secondary)]">{detail.title || session.title}</div>
+ <div className="my-4 flex items-center gap-3 rounded-lg border border-[var(--border-default)] p-3">
+ <Link2 size={18} className="shrink-0" aria-hidden />
+ <div className="min-w-0 flex-1 text-12 text-[var(--text-secondary)]">
+ <p>{t('sharedTask.inviteBoxTitle')}</p><p>{t('sharedTask.inviteBoxHint')}</p>
+ </div>
+ <Button variant="cta" size="lg" disabled={busy} className="px-4" onClick={() => void invite()}>{t('sharedTask.invite')}</Button>
+ </div>
+ <div className="mb-1 mt-4 text-12 text-[var(--text-secondary)]">{t('sharedTask.membersWithLimit', { count: detail.guests.length + 1 })}</div>
+ <div className="flex min-h-12 items-center gap-2.5 py-2.5">
+ <span className={avatarClass} aria-hidden>{t('sharedTask.me')}</span>
+ <div className="min-w-0 flex-1"><div className="text-13 font-medium">{t('sharedTask.me')}</div><div className="text-11 text-[var(--text-secondary)]">{t(session.deviceLinkDeviceId ? 'sharedTask.hostDevice' : 'sharedTask.thisDevice')}</div></div>
+ <span className="text-12 text-[var(--text-secondary)]">{t('sharedTask.roleHost')}</span>
+ </div>
+ {detail.guests.map((member) => {
+ const name = memberName(member.memberId, member.accountId);
+ return <div key={member.memberId} className="flex min-h-12 items-center gap-2.5 py-2.5">
+ <span className={avatarClass} aria-hidden>{Array.from(name)[0]}</span>
+ <div className="min-w-0 flex-1"><div className="break-words text-13 font-medium">{name}</div><div className="text-11 text-[var(--text-secondary)]">{t('sharedTask.roleGuest')}</div></div>
+ <Button variant="secondary" disabled={busy} className="shrink-0 px-3 text-12 text-[var(--error-fg)]"
+ onClick={() => setConfirm({ kind: 'remove', memberId: member.memberId, name })}>{t('sharedTask.removeShort')}</Button>
+ </div>;
+ })}
+ <div className={noticeClass}><Clock size={16} className="mt-0.5 shrink-0" aria-hidden /><p>{t(session.deviceLinkDeviceId ? 'sharedTask.remoteHostOfflineNote' : 'sharedTask.hostOfflineNote')}</p></div>
+ <div className="mt-5"><Button variant="secondary" size="lg" disabled={busy} className="text-[var(--error-fg)]"
+ onClick={() => setConfirm({ kind: 'closeCurrent' })}>{t('sharedTask.closeCurrent')}</Button></div>
+ </>
+ : <div className="px-1 py-6 text-center">
+ {emptyIcon(<CircleStop size={18} aria-hidden />)}
+ <h3 className="text-14 font-medium">{t('sharedTask.hostOfflineTitle')}</h3>
+ <p className="mx-auto mb-5 mt-2 max-w-[280px] text-12 text-[var(--text-secondary)]">{t('sharedTask.hostOfflineBody')}</p>
+ <Button variant="cta" size="lg" onClick={() => { setOpen(false); setJoinOpen(true); }}>{t('sharedTask.rejoin')}</Button>
+ </div>;
+ const ownedTab = owned === null ? <p className="text-[var(--text-secondary)]">{t('sharedTask.sharing')}</p>
+ : owned.length === 0 ? <div className="px-1 py-6 text-center">
+ {emptyIcon(<Check size={18} aria-hidden />)}
+ <h3 className="text-14 font-medium">{t('sharedTask.ownedEmptyTitle')}</h3>
+ <p className="mx-auto mb-5 mt-2 max-w-[280px] text-12 text-[var(--text-secondary)]">{t('sharedTask.ownedEmptyHint')}</p>
+ {!guestSharedTaskId && <Button variant="secondary" size="lg" onClick={() => switchTab('current')}>{t('sharedTask.shareCurrent')}</Button>}
+ </div>
+ : <>
+ <p className="mb-4 text-[var(--text-secondary)]">{t('sharedTask.ownedIntro', { count: owned.length })}</p>
+ {owned.map((item) => <div key={item.sharedTaskId} className="my-2.5 flex items-center gap-2.5 rounded-lg border border-[var(--border-default)] p-3">
+ <Users size={18} className="shrink-0" aria-hidden />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-13 font-medium">{item.title}</div>
+ <div className="text-11 text-[var(--text-secondary)]">{item.local ? t('sharedTask.thisDevice') : t('sharedTask.otherDevice')}
+ {item.sharedTaskId === detail?.sharedTaskId && <> · {t('sharedTask.guestCount', { count: detail.guests.length })}</>}
+ </div>
+ </div>
+ {item.sessionId === session.id && item.hostDeviceId === detail?.hostDeviceId
+ ? <Button variant="secondary" disabled={busy} className="px-3 text-12" onClick={() => switchTab('current')}>{t('sharedTask.manage')}</Button>
+ : <span className="shrink-0 rounded-full bg-[var(--surface-chip)] px-2 py-0.5 text-11 text-[var(--text-secondary)]">{t('sharedTask.sharingBadge')}</span>}
+ </div>)}
+ <div className="mt-4 border-t border-[var(--border-default)] pt-4 text-12 text-[var(--text-secondary)]">{t('sharedTask.closeAllNote')}</div>
+ <div className="mt-5"><Button variant="secondary" size="lg" disabled={busy} className="w-full gap-2 text-[var(--error-fg)]"
+ onClick={() => setConfirm({ kind: 'closeAll' })}><CircleStop size={18} aria-hidden />{t('sharedTask.closeAll', { count: owned.length })}</Button></div>
+ </>;
+ const confirmation = confirm ? confirmCopy(confirm) : null;
+ return <>
+ <Dialog.Root open={open} onOpenChange={(next) => { if (!pending.current) { setOpen(next); if (!next) setConfirm(null); } }}>
+ <Dialog.Trigger asChild>
+ <Button variant="secondary" size="lg" style={WINDOW_NO_DRAG_STYLE} className="ml-2 w-9 bg-transparent p-0" aria-label={t('sharedTask.title')} title={t('sharedTask.title')}>
+ <Users size={18} aria-hidden />
+ </Button>
+ </Dialog.Trigger>
+ <Dialog.Portal>
+ <Dialog.Overlay className="fixed inset-0 z-[10000] bg-[var(--overlay-modal)]" />
+ <Dialog.Content className="fixed left-1/2 top-1/2 z-[10001] max-h-[calc(100dvh-32px)] w-[min(440px,calc(100vw-32px))] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-4 text-[var(--text-primary)]"
+ aria-describedby={undefined}
+ onEscapeKeyDown={(event) => { if (pending.current || confirm) event.preventDefault(); }}
+ onInteractOutside={(event) => { if (pending.current || confirm) event.preventDefault(); }}>
+ <div className="mb-4 flex items-center justify-between gap-2">
+ <Dialog.Title className="text-18 font-medium">{t(guestSharedTaskId && state && !detail ? 'sharedTask.ended' : tab === 'owned' ? 'sharedTask.ownedTitle' : 'sharedTask.title')}</Dialog.Title>
+ <Dialog.Close asChild><Button variant="secondary" size="lg" className="w-9 border-transparent bg-transparent p-0" aria-label={t('sharedTask.dismiss')} disabled={busy}><X size={18} aria-hidden /></Button></Dialog.Close>
+ </div>
+ {!guestSharedTaskId && <div className="-mx-4 mb-4 flex gap-1.5 border-b border-[var(--border-default)] px-4 pb-3">
+ <Button variant="secondary" size="lg" className={tabButton(tab === 'current') + ' border-transparent'} aria-pressed={tab === 'current'} disabled={busy} onClick={() => switchTab('current')}>{t('sharedTask.tabCurrent')}</Button>
+ <Button variant="secondary" size="lg" className={tabButton(tab === 'owned') + ' border-transparent'} aria-pressed={tab === 'owned'} disabled={busy} onClick={() => switchTab('owned')}>
+ {t('sharedTask.tabOwned')}{owned !== null && <span className="ml-1 rounded-full bg-[var(--surface-chip)] px-1.5 text-11 text-[var(--text-secondary)]">{owned.length}</span>}
+ </Button>
+ </div>}
+ <div className="text-13">{tab === 'current' ? currentTab : ownedTab}</div>
+ <ConfirmDialog presentation="standard" cancelFirst open={!!confirmation} onOpenChange={(next) => { if (!next && !pending.current) setConfirm(null); }}
+ title={confirmation?.title ?? ''} description={confirmation?.body} cancelText={confirmation?.keep} confirmText={confirmation?.action}
+ confirmVariant="destructive" loading={busy} zIndex={10002} maxWidth={440} onConfirm={confirmation?.run}
+ content={confirm?.kind === 'closeAll' ? <>
+ <div className="space-y-2 rounded-lg bg-[var(--surface-chip)] p-3 text-12">
+ {(owned ?? []).map((item) => <div key={item.sharedTaskId} className="break-words">{item.title} <span className="text-[var(--text-secondary)]">· {item.local ? t('sharedTask.thisDevice') : t('sharedTask.otherDevice')}</span></div>)}
+ </div><p className="mt-4 text-12 text-[var(--text-secondary)]">{t('sharedTask.closeAllScopeNote')}</p>
+ </> : undefined} />
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
+ {joinOpen && <JoinSharedTaskDialog open={joinOpen} onOpenChange={setJoinOpen} />}
+ </>;
+}
diff --git a/apps/desktop/src/renderer/features/device-link/SharedTaskEndedNotice.tsx b/apps/desktop/src/renderer/features/device-link/SharedTaskEndedNotice.tsx
new file mode 100644
index 0000000000..56001158f4
--- /dev/null
+++ b/apps/desktop/src/renderer/features/device-link/SharedTaskEndedNotice.tsx
@@ -0,0 +1,50 @@
+import { useEffect, useState } from 'react';
+import * as Dialog from '@radix-ui/react-dialog';
+import { CircleStop, X } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { isSharedTaskPeer } from '@cindy/device-link';
+import { Button } from '@/components/ui/button';
+import { useAuth } from '@/contexts/AuthContext';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent, type DataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+
+const endedEvent = 'cindy:shared-task-access-ended';
+
+/** Presentation only, after the existing remote-session exit decision has revoked the view. */
+export function notifySharedTaskEnded(peer: string | undefined): boolean {
+ if (!peer || !isSharedTaskPeer(peer)) return false;
+ window.dispatchEvent(new CustomEvent(endedEvent, { detail: getDataOwnerGeneration() }));
+ return true;
+}
+
+/** Lives in the window menu so leaving the revoked task cannot unmount the ending screen. */
+export function SharedTaskEndedNotice({ onJoin }: { onJoin(): void }) {
+ const { t } = useTranslation();
+ const { dataOwnerId } = useAuth();
+ const [owner, setOwner] = useState<DataOwnerGeneration | null>(null);
+ useEffect(() => {
+ const receive = (event: Event) => {
+ const stamp = (event as CustomEvent<DataOwnerGeneration>).detail;
+ if (stamp && isDataOwnerGenerationCurrent(stamp)) setOwner(stamp);
+ };
+ window.addEventListener(endedEvent, receive);
+ return () => window.removeEventListener(endedEvent, receive);
+ }, []);
+ const open = !!owner && owner.dataOwnerId === dataOwnerId && isDataOwnerGenerationCurrent(owner);
+ return <Dialog.Root open={open} onOpenChange={(next) => { if (!next) setOwner(null); }}>
+ <Dialog.Portal>
+ <Dialog.Overlay className="fixed inset-0 z-[10000] bg-[var(--overlay-modal)]" />
+ <Dialog.Content className="fixed left-1/2 top-1/2 z-[10001] max-h-[calc(100dvh-32px)] w-[min(440px,calc(100vw-32px))] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-4 text-[var(--text-primary)]">
+ <div className="mb-4 flex items-center justify-between gap-2">
+ <Dialog.Title className="text-18 font-medium">{t('sharedTask.ended')}</Dialog.Title>
+ <Dialog.Close asChild><Button variant="secondary" size="lg" className="w-9 border-transparent bg-transparent p-0" aria-label={t('sharedTask.dismiss')}><X size={18} aria-hidden /></Button></Dialog.Close>
+ </div>
+ <div className="px-1 py-6 text-center">
+ <span className="mb-4 inline-flex size-11 items-center justify-center rounded-full border border-[var(--border-default)]"><CircleStop size={18} aria-hidden /></span>
+ <h3 className="text-14 font-medium">{t('sharedTask.ended')}</h3>
+ <Dialog.Description className="mx-auto mb-5 mt-2 max-w-[280px] text-12 text-[var(--text-secondary)]">{t('sharedTask.accessEndedBody')}</Dialog.Description>
+ <Button variant="cta" size="lg" onClick={() => { setOwner(null); onJoin(); }}>{t('sharedTask.rejoin')}</Button>
+ </div>
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>;
+}
diff --git a/apps/desktop/src/renderer/features/device-link/SharedTasksSection.tsx b/apps/desktop/src/renderer/features/device-link/SharedTasksSection.tsx
new file mode 100644
index 0000000000..40859b1b84
--- /dev/null
+++ b/apps/desktop/src/renderer/features/device-link/SharedTasksSection.tsx
@@ -0,0 +1,126 @@
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { ChevronDown, ChevronRight, Plus } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { isSharedTaskPeer, type SharedTaskOwnedItem } from '@cindy/device-link';
+import { Button } from '@/components/ui/button';
+import { SegmentedControl } from '@/components/ui/segmented-control';
+import { VendorIcon, agentKindToVendor } from '@/components/sidebar/VendorIcon';
+import type { Session } from '@/lib/ccAgent.types';
+import { useAuth } from '@/contexts/AuthContext';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
+import { toast } from '@/lib/toast';
+import { cn } from '@/lib/utils';
+import { useRemoteProjectSessions, isRemoteDeviceMarkedDisconnected, remoteProjectsStore } from './remoteProjectsStore';
+import { JoinSharedTaskDialog } from './JoinSharedTaskDialog';
+import { sharedTaskErrorKey } from './sharedTaskCompatibility';
+
+/** Uses the existing session mirror; choosing a task must not reconnect or fetch it again. */
+export function SharedTasksSection({ activeSessionId, localSessions = [], onSelect }: {
+ activeSessionId?: string | null;
+ localSessions?: readonly Session[];
+ onSelect(id: string): void;
+}) {
+ const { t } = useTranslation();
+ const { isAuthenticated, dataOwnerId } = useAuth();
+ const generation = getDataOwnerGeneration().generation;
+ const sessions = useRemoteProjectSessions();
+ const joined = useMemo(() => sessions.filter(session =>
+ !!session.deviceLinkDeviceId && isSharedTaskPeer(session.deviceLinkDeviceId)), [sessions]);
+ const [collapsed, setCollapsed] = useState(false);
+ const [joinOpen, setJoinOpen] = useState(false);
+ const [owned, setOwned] = useState<SharedTaskOwnedItem[]>([]);
+ const [tab, setTab] = useState<'owned' | 'joined'>('joined');
+ const [opening, setOpening] = useState<string | null>(null);
+ const pending = useRef(false);
+ const epoch = useRef(0);
+ useEffect(() => {
+ const captured = ++epoch.current;
+ const owner = getDataOwnerGeneration();
+ setOwned([]); setOpening(null); setJoinOpen(false); pending.current = false;
+ if (!isAuthenticated) return;
+ let loading = false;
+ const refresh = async () => {
+ if (loading) return;
+ loading = true;
+ try {
+ const items = await window.electronAPI.sharedTask.account({ action: 'owned' }) as SharedTaskOwnedItem[];
+ if (captured === epoch.current && isDataOwnerGenerationCurrent(owner)) setOwned(items);
+ } catch { /* Retain the last confirmed list during transient network failures. */ }
+ finally { loading = false; }
+ };
+ void refresh();
+ const timer = setInterval(() => { if (document.visibilityState !== 'hidden') void refresh(); }, 30_000);
+ window.addEventListener('cindy:shared-task-owned-changed', refresh);
+ window.addEventListener('focus', refresh);
+ document.addEventListener('visibilitychange', refresh);
+ return () => {
+ epoch.current++; clearInterval(timer);
+ window.removeEventListener('cindy:shared-task-owned-changed', refresh);
+ window.removeEventListener('focus', refresh);
+ document.removeEventListener('visibilitychange', refresh);
+ };
+ }, [isAuthenticated, dataOwnerId, generation]);
+ const both = owned.length > 0 && joined.length > 0;
+ const visibleTab = both ? tab : owned.length ? 'owned' : 'joined';
+ const openOwned = async (item: SharedTaskOwnedItem) => {
+ if (item.sessionId === activeSessionId || pending.current) return;
+ const owner = getDataOwnerGeneration();
+ const captured = epoch.current;
+ const current = () => captured === epoch.current && isDataOwnerGenerationCurrent(owner);
+ pending.current = true; setOpening(item.sharedTaskId);
+ try {
+ if (!item.local && !sessions.some(session => session.id === item.sessionId && session.deviceLinkDeviceId === item.hostDeviceId)) {
+ await window.electronAPI.deviceLink.openLink(item.hostDeviceId);
+ if (!current()) return;
+ remoteProjectsStore.pinSessionOrigin(item.hostDeviceId, item.sessionId);
+ }
+ if (current()) onSelect(item.sessionId);
+ } catch (error) { if (current()) toast.error(t(sharedTaskErrorKey(error))); }
+ finally { if (current()) { pending.current = false; setOpening(null); } }
+ };
+ if (!isAuthenticated) return null;
+ return <>{(owned.length > 0 || joined.length > 0) && <section className="mx-3 mb-2 border-b border-[var(--border-default)] pb-3" aria-label={t('sharedTask.title')}>
+ <div className="flex min-h-8 items-center justify-between gap-2">
+ {both ? <SegmentedControl role="tablist" fullWidth className="min-w-0 flex-1"
+ aria-label={t('sharedTask.title')} value={visibleTab} onValueChange={value => { setTab(value); setCollapsed(false); }}
+ options={[
+ { value: 'owned', label: t('sharedTask.ownedTab') },
+ { value: 'joined', label: t('sharedTask.joinedTab') },
+ ]} optionClassName="px-1.5" /> : <button type="button" aria-expanded={!collapsed} onClick={() => setCollapsed(value => !value)}
+ className="flex min-h-8 min-w-0 items-center gap-1.5 rounded-full px-2 text-12 text-[var(--text-secondary)] hover:bg-[var(--surface-hover-soft)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]">
+ {collapsed ? <ChevronRight size={14} aria-hidden /> : <ChevronDown size={14} aria-hidden />}
+ {t(visibleTab === 'owned' ? 'sharedTask.ownedSection' : 'sharedTask.joinedSection')}
+ </button>}
+ <Button variant="secondary" className="w-8 shrink-0 border-transparent bg-transparent p-0" aria-label={t('sharedTask.join')} title={t('sharedTask.join')} onClick={() => setJoinOpen(true)}><Plus size={16} aria-hidden /></Button>
+ </div>
+ {(!collapsed || both) && visibleTab === 'owned' && owned.map(item => <button key={item.sharedTaskId} type="button"
+ aria-current={item.sessionId === activeSessionId ? 'page' : undefined} disabled={!!opening} aria-busy={opening === item.sharedTaskId || undefined}
+ onClick={() => void openOwned(item)} title={item.title}
+ className={cn('my-0.5 flex min-h-14 w-full items-start gap-2.5 rounded-lg px-2.5 py-2.5 text-left hover:bg-[var(--surface-hover-soft)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]', item.sessionId === activeSessionId && 'bg-[var(--surface-chip)]')}>
+ <SharedTaskAgentIcon agentKind={(item.local ? localSessions : sessions).find(session => session.id === item.sessionId)?.agentKind} />
+ <span className="min-w-0 flex-1"><span className="block truncate text-13 font-medium text-[var(--text-primary)]">{item.title}</span>
+ <span className="mt-0.5 block truncate text-11 text-[var(--text-secondary)]">{t(item.local ? 'sharedTask.thisDevice' : 'sharedTask.otherDevice')}</span>
+ </span>
+ </button>)}
+ {(!collapsed || both) && visibleTab === 'joined' && joined.map(session => <button key={session.id} type="button"
+ aria-current={session.id === activeSessionId ? 'page' : undefined}
+ onClick={() => { if (session.id !== activeSessionId) onSelect(session.id); }}
+ className={cn('my-0.5 flex min-h-14 w-full items-start gap-2.5 rounded-lg px-2.5 py-2.5 text-left hover:bg-[var(--surface-hover-soft)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',
+ session.id === activeSessionId && 'bg-[var(--surface-chip)]')}
+ title={session.title || t('sharedTask.title')}>
+ <SharedTaskAgentIcon agentKind={session.agentKind} />
+ <span className="min-w-0 flex-1"><span className="block truncate text-13 font-medium text-[var(--text-primary)]">{session.title || t('sharedTask.title')}</span>
+ <span className="mt-0.5 block truncate text-11 text-[var(--text-secondary)]">{t(isRemoteDeviceMarkedDisconnected(session.deviceLinkDeviceId!) ? 'sharedTask.reconnecting' : 'sharedTask.title')}</span>
+ </span>
+ </button>)}
+ </section>}
+ <JoinSharedTaskDialog open={joinOpen} onOpenChange={setJoinOpen} />
+ </>;
+}
+
+function SharedTaskAgentIcon({ agentKind }: { agentKind?: Session['agentKind'] }) {
+ const vendor = agentKindToVendor(agentKind);
+ return <span className="mt-0.5 flex w-[15px] shrink-0 items-center justify-center" aria-hidden>
+ <VendorIcon vendor={vendor} size={vendor === 'cc' ? 13 : 12} />
+ </span>;
+}
diff --git a/apps/desktop/src/renderer/features/device-link/__tests__/JoinSharedTaskDialog.test.tsx b/apps/desktop/src/renderer/features/device-link/__tests__/JoinSharedTaskDialog.test.tsx
new file mode 100644
index 0000000000..72cbd5835f
--- /dev/null
+++ b/apps/desktop/src/renderer/features/device-link/__tests__/JoinSharedTaskDialog.test.tsx
@@ -0,0 +1,116 @@
+// @vitest-environment jsdom
+import { createElement } from 'react';
+import { render, screen, fireEvent, waitFor, cleanup, within, act } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { JoinSharedTaskDialog } from '../JoinSharedTaskDialog';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+const state = vi.hoisted(() => ({ account: vi.fn(), openLink: vi.fn(), invoke: vi.fn(), setSessions: vi.fn(), bind: vi.fn() }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string, args?: { title?: string }) => key + (args?.title ? ':' + args.title : '') }) }));
+vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ dataOwnerId: 'guest', isAuthenticated: true }) }));
+vi.mock('@/lib/toast', () => ({ toast: { error: vi.fn(), success: vi.fn() } }));
+vi.mock('../remoteProjectsStore', () => ({ remoteProjectsStore: { setDeviceSessions: state.setSessions } }));
+vi.mock('@/lib/remoteDataOwnerPushFence', () => ({ bindSharedTaskPushOwner: state.bind }));
+beforeEach(() => {
+ vi.clearAllMocks(); setDataOwnerGeneration('guest');
+ state.account.mockImplementation(async ({ action }) => action === 'owned' ? [] : action === 'join'
+ ? { sharedTaskId: 'share-1', memberId: 'member-1', status: 'joined' }
+ : { sharedTaskId: 'share-1', sessionId: 'task-1', ownerAccountId: 'host', title: 'Test Task', status: 'active' });
+ state.invoke.mockResolvedValue({ id: 'task-1' });
+ Object.assign(window, { electronAPI: { sharedTask: { account: state.account }, deviceLink: { openLink: state.openLink, invoke: state.invoke } } });
+});
+afterEach(cleanup);
+function open(onOpenChange = vi.fn()) {
+ render(createElement(MemoryRouter, null, createElement(JoinSharedTaskDialog, { open: true, onOpenChange })));
+ return onOpenChange;
+}
+function fill() {
+ fireEvent.change(screen.getByLabelText('sharedTask.invitation'), { target: { value: 'A'.repeat(43) } });
+ fireEvent.change(screen.getByLabelText('sharedTask.joinNickname'), { target: { value: 'Guest' } });
+ fireEvent.click(screen.getByRole('button', { name: 'sharedTask.join' }));
+}
+it('uses a multiline invitation form and focuses invalid input without sending', async () => {
+ open();
+ await act(async () => {});
+ expect(screen.getByLabelText('sharedTask.invitation').tagName).toBe('TEXTAREA');
+ expect(screen.getByLabelText('sharedTask.joinNickname').getAttribute('maxlength')).toBe('32');
+ expect(screen.getByText('sharedTask.joinNotice')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'sharedTask.join' }));
+ expect(document.activeElement).toBe(screen.getByLabelText('sharedTask.invitation'));
+ expect(state.account).not.toHaveBeenCalledWith(expect.objectContaining({ action: 'join' }));
+});
+
+const owned = [
+ { sharedTaskId: 'own-1', title: 'First owned task', local: true },
+ { sharedTaskId: 'own-2', title: 'Other computer task', local: false },
+];
+it('keeps the C confirmation in one dialog and preserves the invitation on cancel', async () => {
+ state.account.mockResolvedValue(owned); open();
+ await waitFor(() => expect((screen.getByRole('button', { name: 'sharedTask.closeAllShort' }) as HTMLButtonElement).disabled).toBe(false));
+ fireEvent.change(screen.getByLabelText('sharedTask.invitation'), { target: { value: 'A'.repeat(43) } });
+ fireEvent.change(screen.getByLabelText('sharedTask.joinNickname'), { target: { value: 'Guest' } });
+ fireEvent.click(screen.getByRole('button', { name: 'sharedTask.closeAllShort' }));
+ expect(screen.getAllByRole('dialog')).toHaveLength(1);
+ expect(screen.getByText('First owned task')).toBeTruthy();
+ expect(document.activeElement).toBe(screen.getByRole('button', { name: 'sharedTask.closeAllKeep' }));
+ fireEvent.click(screen.getByRole('button', { name: 'sharedTask.closeAllKeep' }));
+ expect((screen.getByLabelText('sharedTask.invitation') as HTMLTextAreaElement).value).toBe('A'.repeat(43));
+ expect((screen.getByLabelText('sharedTask.joinNickname') as HTMLInputElement).value).toBe('Guest');
+ expect(state.account).not.toHaveBeenCalledWith(expect.objectContaining({ action: 'close' }));
+});
+
+it('closes only confirmed owned tasks and retries just the failed task', async () => {
+ let secondAttempt = false;
+ state.account.mockImplementation(async ({ action, sharedTaskId }) => {
+ if (action === 'owned') return owned;
+ if (sharedTaskId === 'own-1' || secondAttempt) return { closed: [sharedTaskId], failed: [] };
+ secondAttempt = true; return { closed: [], failed: [{ sharedTaskId }] };
+ });
+ open();
+ await waitFor(() => expect((screen.getByRole('button', { name: 'sharedTask.closeAllShort' }) as HTMLButtonElement).disabled).toBe(false));
+ fireEvent.click(screen.getByRole('button', { name: 'sharedTask.closeAllShort' }));
+ fireEvent.click(screen.getByRole('button', { name: 'sharedTask.closeAllAction' }));
+ await waitFor(() => expect(screen.queryByText('First owned task')).toBeNull());
+ expect(screen.getByText('Other computer task')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'sharedTask.closeAllAction' }));
+ await waitFor(() => expect(screen.queryByText('sharedTask.closeAllTitle')).toBeNull());
+ const closes = state.account.mock.calls.map(([command]) => command).filter(command => command.action === 'close');
+ expect(closes).toEqual([
+ { action: 'close', sharedTaskId: 'own-1' }, { action: 'close', sharedTaskId: 'own-2' }, { action: 'close', sharedTaskId: 'own-2' },
+ ]);
+});
+
+it('stops the batch after an account change and ignores its late result', async () => {
+ let finish!: (value: unknown) => void;
+ state.account.mockImplementation(({ action }) => action === 'owned' ? Promise.resolve(owned) : new Promise(resolve => { finish = resolve; }));
+ open();
+ await waitFor(() => expect((screen.getByRole('button', { name: 'sharedTask.closeAllShort' }) as HTMLButtonElement).disabled).toBe(false));
+ fireEvent.click(screen.getByRole('button', { name: 'sharedTask.closeAllShort' }));
+ fireEvent.click(screen.getByRole('button', { name: 'sharedTask.closeAllAction' }));
+ await act(async () => {
+ setDataOwnerGeneration('another-account');
+ finish({ closed: ['own-1'], failed: [] });
+ });
+ expect(state.account).not.toHaveBeenCalledWith({ action: 'close', sharedTaskId: 'own-2' });
+});
+it('shows the joined task before entering through the existing remote link', async () => {
+ const close = open(); fill();
+ await screen.findByText('sharedTask.joinedTitle:Test Task');
+ expect(screen.queryByLabelText('sharedTask.invitation')).toBeNull();
+ expect(state.openLink).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'sharedTask.enterTask' }));
+ await waitFor(() => expect(close).toHaveBeenCalledWith(false));
+ expect(state.invoke).toHaveBeenCalledWith('shared-task~share-1~host', 'local-db:sessions:get', ['task-1']);
+});
+it('lets a newly joined visitor cancel leaving, then leave with confirmation', async () => {
+ open(); fill(); await screen.findByText('sharedTask.joinedTitle:Test Task');
+ fireEvent.click(screen.getByRole('button', { name: 'sharedTask.leave' }));
+ let dialog = screen.getByRole('alertdialog');
+ fireEvent.click(within(dialog).getByRole('button', { name: 'sharedTask.leaveKeep' }));
+ expect(state.account).not.toHaveBeenCalledWith(expect.objectContaining({ action: 'leave' }));
+ fireEvent.click(screen.getByRole('button', { name: 'sharedTask.leave' }));
+ dialog = screen.getByRole('alertdialog');
+ fireEvent.click(within(dialog).getByRole('button', { name: 'sharedTask.leave' }));
+ await waitFor(() => expect(state.account).toHaveBeenCalledWith({ action: 'leave', sharedTaskId: 'share-1' }));
+ await screen.findByLabelText('sharedTask.invitation');
+});
diff --git a/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskButton.test.tsx b/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskButton.test.tsx
new file mode 100644
index 0000000000..d42d5deaa6
--- /dev/null
+++ b/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskButton.test.tsx
@@ -0,0 +1,153 @@
+// @vitest-environment jsdom
+import { createElement } from 'react';
+import { act, fireEvent, waitFor, within } from '@testing-library/react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { sharedTaskHostPeer, type SharedTaskDetail } from '@cindy/device-link';
+import { SharedTaskButton } from '../SharedTaskButton';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import type { Session } from '@/lib/ccAgent.types';
+import { toast } from '@/lib/toast';
+const state = vi.hoisted(() => ({ invoke: vi.fn(), host: vi.fn(), account: vi.fn(), t: (key: string) => key }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: state.t }) }));
+vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ dataOwnerId: 'owner' }) }));
+vi.mock('@/lib/toast', () => ({ toast: { error: vi.fn(), success: vi.fn() } }));
+let container: HTMLDivElement;
+let root: Root;
+const ownerSession = { id: 'session-1' } as Session;
+const detail = {
+ sharedTaskId: 'st1', sessionId: 'session-1', ownerAccountId: 'owner', hostDeviceId: 'device-a',
+ revision: 1, status: 'active', guests: [], memberLabels: [], title: 'Task A',
+} as unknown as SharedTaskDetail;
+async function openWindow(session: Session) {
+ await act(async () => root.render(createElement(SharedTaskButton, { session })));
+ const trigger = [...container.querySelectorAll('button')][0];
+ await act(async () => { fireEvent.click(trigger); });
+ return document.body;
+}
+beforeEach(() => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ vi.clearAllMocks(); setDataOwnerGeneration('owner');
+ Object.assign(window, { electronAPI: {
+ deviceLink: { invoke: state.invoke },
+ sharedTask: { host: state.host, account: state.account },
+ } });
+ state.host.mockResolvedValue({ available: true, detail });
+ state.account.mockResolvedValue([]);
+ container = document.createElement('div');
+ document.body.append(container);
+ root = createRoot(container);
+});
+afterEach(async () => {
+ await act(async () => root.unmount());
+ container.remove();
+ document.body.innerHTML = '';
+});
+it('renders an upgrade instruction when an old host rejects the new channel', async () => {
+ state.host.mockRejectedValue(new Error('[DEVICE_LINK_CHANNEL_NOT_ALLOWED] unsupported'));
+ const body = await openWindow(ownerSession);
+ await waitFor(() => expect(body.textContent).toContain('sharedTask.upgrade'));
+ expect(body.textContent).not.toContain('sharedTask.open');
+});
+it('does not mislabel a timeout as an old host', async () => {
+ state.host.mockRejectedValue(new Error('[DEVICE_LINK_TIMEOUT] timeout'));
+ const body = await openWindow(ownerSession);
+ await waitFor(() => expect(body.textContent).toContain('sharedTask.sharing'));
+ expect(body.textContent).not.toContain('sharedTask.upgrade');
+});
+it('distinguishes a local clipboard failure from a shared-task request failure', async () => {
+ const copy = vi.fn().mockRejectedValue(new DOMException('Document is not focused.', 'NotAllowedError'));
+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: copy } });
+ state.host.mockImplementation((command: { action: string }) => command.action === 'invite'
+ ? Promise.resolve({ invitation: 'test-invitation' }) : Promise.resolve({ available: true, detail }));
+ const body = await openWindow(ownerSession);
+ fireEvent.click(within(body).getByRole('button', { name: 'sharedTask.invite' }));
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('sharedTask.invitationCopyFailed'));
+ expect(toast.error).not.toHaveBeenCalledWith('sharedTask.retry');
+ expect(toast.success).not.toHaveBeenCalled();
+ copy.mockResolvedValue(undefined);
+ await waitFor(() => expect(within(body).getByRole('button', { name: 'sharedTask.invite' }).hasAttribute('disabled')).toBe(false));
+ fireEvent.click(within(body).getByRole('button', { name: 'sharedTask.invite' }));
+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith('sharedTask.invitationCopied'));
+});
+
+it('keeps invitation request failures distinct and does not attempt to copy', async () => {
+ const copy = vi.fn();
+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: copy } });
+ state.host.mockImplementation((command: { action: string }) => command.action === 'invite'
+ ? Promise.reject(new Error('[DEVICE_LINK_TIMEOUT] timed out')) : Promise.resolve({ available: true, detail }));
+ const body = await openWindow(ownerSession);
+ fireEvent.click(within(body).getByRole('button', { name: 'sharedTask.invite' }));
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('sharedTask.retry'));
+ expect(copy).not.toHaveBeenCalled();
+});
+it('ignores a late unsupported response after the data owner changes', async () => {
+ let reject!: (error: unknown) => void;
+ state.host.mockReturnValue(new Promise((_resolve, fail) => { reject = fail; }));
+ const body = await openWindow(ownerSession);
+ setDataOwnerGeneration('other');
+ await act(async () => reject(new Error('[DEVICE_LINK_CHANNEL_NOT_ALLOWED] unsupported')));
+ expect(body.textContent).not.toContain('sharedTask.upgrade');
+});
+it('lists owned shares and routes close-all through the account command', async () => {
+ state.account.mockImplementation((command: { action: string }) => {
+ if (command.action === 'owned') {
+ return Promise.resolve([
+ { sharedTaskId: 'st1', sessionId: 'session-1', ownerAccountId: 'owner', hostDeviceId: 'device-a', title: 'Task A', revision: 1, local: true },
+ { sharedTaskId: 'st9', sessionId: 'session-9', ownerAccountId: 'owner', hostDeviceId: 'device-b', title: 'Task B', revision: 1, local: false },
+ ]);
+ }
+ if (command.action === 'close') return Promise.resolve({ closed: ['st1', 'st9'], failed: [] });
+ return Promise.resolve(detail);
+ });
+ const body = await openWindow(ownerSession);
+ await waitFor(() => expect(body.textContent).toContain('sharedTask.tabOwned'));
+ await act(async () => { fireEvent.click([...body.querySelectorAll('button')].find((b) => b.textContent?.startsWith('sharedTask.tabOwned'))!); });
+ await waitFor(() => expect(body.textContent).toContain('sharedTask.ownedIntro'));
+ expect(body.textContent).toContain('Task A');
+ expect(body.textContent).toContain('sharedTask.thisDevice');
+ expect(body.textContent).toContain('Task B');
+ await act(async () => { fireEvent.click([...body.querySelectorAll('button')].find((b) => b.textContent?.startsWith('sharedTask.closeAll'))!); });
+ await waitFor(() => expect(body.textContent).toContain('sharedTask.closeAllTitle'));
+ const confirmation = within(body).getByRole('alertdialog');
+ expect(confirmation.contains(document.activeElement)).toBe(true);
+ expect(document.activeElement?.textContent).toBe('sharedTask.closeAllKeep');
+ expect(within(confirmation).getAllByRole('button').map((button) => button.textContent)).toEqual([
+ 'sharedTask.closeAllKeep', 'sharedTask.closeAllAction',
+ ]);
+ expect(body.textContent).toContain('Task B');
+ await act(async () => { fireEvent.click([...body.querySelectorAll('button')].find((b) => b.textContent?.startsWith('sharedTask.closeAllAction'))!); });
+ await waitFor(() => expect(state.account).toHaveBeenCalledWith({ action: 'close', all: true }));
+});
+it('keeps the member screen behind a named removal confirmation and cancels without removing', async () => {
+ state.host.mockResolvedValue({ available: true, detail: { ...detail,
+ guests: [{ memberId: 'guest-1', accountId: 'guest-account' }],
+ memberLabels: [{ memberId: 'guest-1', displayName: 'Guest Name' }],
+ } });
+ const body = await openWindow(ownerSession);
+ expect(body.textContent).toContain('Guest Name');
+ expect(body.textContent).toContain('sharedTask.roleGuest');
+ expect(body.textContent).toContain('sharedTask.inviteBoxTitle');
+ fireEvent.click(within(body).getByRole('button', { name: 'sharedTask.removeShort' }));
+ const dialog = within(body).getByRole('alertdialog');
+ expect(dialog.textContent).toContain('sharedTask.removeNamedTitle');
+ fireEvent.click(within(dialog).getByRole('button', { name: 'sharedTask.removeKeep' }));
+ await waitFor(() => expect(within(body).queryByRole('alertdialog')).toBeNull());
+ expect(state.host.mock.calls.every(([command]) => command.action === 'state')).toBe(true);
+});
+it('does not route another local task management button to the current task', async () => {
+ state.account.mockResolvedValue([{ ...detail, sessionId: 'other-session', sharedTaskId: 'other-share', title: 'Other Task', local: true }]);
+ const body = await openWindow(ownerSession);
+ fireEvent.click(within(body).getByRole('button', { name: /sharedTask.tabOwned/ }));
+ await waitFor(() => expect(body.textContent).toContain('Other Task'));
+ expect(within(body).queryByRole('button', { name: 'sharedTask.manage' })).toBeNull();
+});
+it('shows the host-offline ending for a guest whose share closed', async () => {
+ state.account.mockImplementation((command: { action: string }) => command.action === 'get'
+ ? Promise.resolve({ ...detail, status: 'closed' })
+ : Promise.resolve([]));
+ const body = await openWindow({ id: 'session-1', deviceLinkDeviceId: sharedTaskHostPeer('st1') } as Session);
+ await waitFor(() => expect(body.textContent).toContain('sharedTask.hostOfflineTitle'));
+ expect(body.textContent).toContain('sharedTask.hostOfflineBody');
+ expect(body.textContent).not.toContain('sharedTask.leave');
+});
diff --git a/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskEndedNotice.test.tsx b/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskEndedNotice.test.tsx
new file mode 100644
index 0000000000..05e6dc5260
--- /dev/null
+++ b/apps/desktop/src/renderer/features/device-link/__tests__/SharedTaskEndedNotice.test.tsx
@@ -0,0 +1,33 @@
+// @vitest-environment jsdom
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { sharedTaskHostPeer } from '@cindy/device-link';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import { SharedTaskEndedNotice, notifySharedTaskEnded } from '../SharedTaskEndedNotice';
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ dataOwnerId: 'owner' }) }));
+beforeEach(() => setDataOwnerGeneration('owner'));
+afterEach(cleanup);
+
+it('keeps ordinary remote exits unchanged and offers a new invitation after a shared-task exit', () => {
+ const onJoin = vi.fn();
+ render(<SharedTaskEndedNotice onJoin={onJoin} />);
+ act(() => { expect(notifySharedTaskEnded('ordinary-device')).toBe(false); });
+ expect(screen.queryByRole('dialog')).toBeNull();
+ act(() => { expect(notifySharedTaskEnded(sharedTaskHostPeer('share-1'))).toBe(true); });
+ expect(screen.getByRole('dialog').textContent).toContain('sharedTask.accessEndedBody');
+ fireEvent.click(screen.getByRole('button', { name: 'sharedTask.rejoin' }));
+ expect(onJoin).toHaveBeenCalledOnce();
+ expect(screen.queryByRole('dialog')).toBeNull();
+});
+
+it('does not keep an ending notice visible across an account boundary', () => {
+ const onJoin = vi.fn();
+ const view = render(<SharedTaskEndedNotice onJoin={onJoin} />);
+ act(() => { notifySharedTaskEnded(sharedTaskHostPeer('share-1')); });
+ expect(screen.getByRole('dialog')).toBeTruthy();
+ setDataOwnerGeneration('other');
+ view.rerender(<SharedTaskEndedNotice onJoin={onJoin} />);
+ expect(screen.queryByRole('dialog')).toBeNull();
+});
diff --git a/apps/desktop/src/renderer/features/device-link/__tests__/SharedTasksSection.test.tsx b/apps/desktop/src/renderer/features/device-link/__tests__/SharedTasksSection.test.tsx
new file mode 100644
index 0000000000..1d3646fa6f
--- /dev/null
+++ b/apps/desktop/src/renderer/features/device-link/__tests__/SharedTasksSection.test.tsx
@@ -0,0 +1,87 @@
+// @vitest-environment jsdom
+import { render, screen, fireEvent, cleanup, waitFor, act } from '@testing-library/react';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { SharedTasksSection } from '../SharedTasksSection';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import type { Session } from '@/lib/ccAgent.types';
+const state = vi.hoisted(() => ({ sessions: [] as Session[], account: vi.fn(), openLink: vi.fn(), pin: vi.fn() }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string, args?: { count?: number }) => key + (args?.count === undefined ? '' : ':' + args.count) }) }));
+vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ dataOwnerId: 'guest', isAuthenticated: true }) }));
+vi.mock('../JoinSharedTaskDialog', () => ({ JoinSharedTaskDialog: () => null }));
+vi.mock('@/lib/toast', () => ({ toast: { error: vi.fn() } }));
+vi.mock('../remoteProjectsStore', () => ({
+ useRemoteProjectSessions: () => state.sessions, isRemoteDeviceMarkedDisconnected: () => false,
+ remoteProjectsStore: { pinSessionOrigin: state.pin },
+}));
+const guestTask = { id: 'joined-1', title: 'Joined task', deviceLinkDeviceId: 'shared-task~share-1~host' } as Session;
+beforeEach(() => {
+ vi.clearAllMocks(); setDataOwnerGeneration('guest');
+ state.sessions = [guestTask, { id: 'own-device-task', title: 'Own device task', deviceLinkDeviceId: 'my-computer' } as Session];
+ state.account.mockResolvedValue([]);
+ Object.assign(window, { electronAPI: { sharedTask: { account: state.account }, deviceLink: { openLink: state.openLink } } });
+});
+afterEach(cleanup);
+it('shows only joined tasks independently of the machine filter and does not reopen the active task', async () => {
+ const select = vi.fn();
+ render(<SharedTasksSection activeSessionId="joined-1" onSelect={select} />);
+ await act(async () => {});
+ expect(screen.getByText('sharedTask.joinedSection')).toBeTruthy();
+ expect(screen.queryByText('Own device task')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: /Joined task/ }));
+ expect(select).not.toHaveBeenCalled();
+ expect(state.openLink).not.toHaveBeenCalled();
+});
+it('navigates directly from a joined task without opening a new link', async () => {
+ const select = vi.fn();
+ render(<SharedTasksSection activeSessionId="another" onSelect={select} />);
+ await act(async () => {});
+ fireEvent.click(screen.getByRole('button', { name: /Joined task/ }));
+ expect(select).toHaveBeenCalledWith('joined-1');
+ expect(state.openLink).not.toHaveBeenCalled();
+});
+it('shows the owned group alone for a host, with local task navigation', async () => {
+ state.sessions=[]; state.account.mockResolvedValue([{ sharedTaskId: 'owned-1', sessionId: 'host-task', local: true, title: 'Hosted task' }]);
+ const select=vi.fn(); render(<SharedTasksSection onSelect={select} />);
+ await screen.findByText('sharedTask.ownedSection');
+ expect(screen.queryByRole('tablist')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: /Hosted task/ }));
+ expect(select).toHaveBeenCalledWith('host-task');
+ expect(state.openLink).not.toHaveBeenCalled();
+});
+it('switches roles with a segmented control, then falls back when sharing ends', async () => {
+ state.account.mockResolvedValue([{ sharedTaskId: 'owned-1', sessionId: 'host-task', local: true, title: 'Hosted task' }]);
+ const { rerender } = render(<SharedTasksSection onSelect={vi.fn()} />);
+ await screen.findByRole('tablist');
+ fireEvent.click(screen.getByRole('tab', { name: 'sharedTask.ownedTab' }));
+ expect(screen.getByRole('tab', { name: 'sharedTask.joinedTab' })).toBeTruthy();
+ expect(screen.getByText('Hosted task')).toBeTruthy();
+ expect(screen.queryByText('Joined task')).toBeNull();
+ state.account.mockResolvedValue([]);
+ window.dispatchEvent(new Event('cindy:shared-task-owned-changed'));
+ await waitFor(() => expect(screen.queryByRole('tablist')).toBeNull());
+ expect(screen.getByText('Joined task')).toBeTruthy();
+ state.sessions = [];
+ rerender(<SharedTasksSection onSelect={vi.fn()} />);
+ expect(screen.queryByRole('region')).toBeNull();
+});
+it('keeps the sidebar empty until sharing starts and hides it when the last owned share closes', async () => {
+ state.sessions = [];
+ render(<SharedTasksSection onSelect={vi.fn()} />);
+ await act(async () => {});
+ expect(screen.queryByRole('region')).toBeNull();
+ expect(screen.queryByRole('button')).toBeNull();
+ state.account.mockResolvedValue([{ sharedTaskId: 'owned-1', sessionId: 'host-task', local: true, title: 'Hosted task' }]);
+ window.dispatchEvent(new Event('cindy:shared-task-owned-changed'));
+ expect(await screen.findByRole('button', { name: 'sharedTask.ownedSection' })).toBeTruthy();
+ state.account.mockResolvedValue([]);
+ window.dispatchEvent(new Event('cindy:shared-task-owned-changed'));
+ await waitFor(() => expect(screen.queryByRole('region')).toBeNull());
+});
+it('does not register a remote origin or navigate after an account change during opening', async () => {
+ state.sessions=[]; state.account.mockResolvedValue([{ sharedTaskId: 'owned-1', sessionId: 'host-task', hostDeviceId: 'other-pc', local: false, title: 'Hosted task' }]);
+ let finish!: () => void; state.openLink.mockImplementation(() => new Promise<void>(resolve => { finish=resolve; }));
+ const select=vi.fn(); render(<SharedTasksSection onSelect={select} />);
+ fireEvent.click(await screen.findByRole('button', { name: /Hosted task/ }));
+ await act(async () => { setDataOwnerGeneration('new-account'); finish(); });
+ expect(state.pin).not.toHaveBeenCalled(); expect(select).not.toHaveBeenCalled();
+});
diff --git a/apps/desktop/src/renderer/features/device-link/__tests__/sharedTaskCompatibility.test.ts b/apps/desktop/src/renderer/features/device-link/__tests__/sharedTaskCompatibility.test.ts
new file mode 100644
index 0000000000..326cf93368
--- /dev/null
+++ b/apps/desktop/src/renderer/features/device-link/__tests__/sharedTaskCompatibility.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from 'vitest';
+import { sharedTaskErrorKey } from '../sharedTaskCompatibility';
+
+describe('shared-task compatibility errors', () => {
+ it.each([['SHARED_TASK_HOST_LIMIT', 'sharedTask.hostLimit'], ['SHARED_TASK_JOIN_LIMIT', 'sharedTask.joinLimit'],
+ ['SHARED_TASK_GUEST_LIMIT', 'sharedTask.guestLimit']])('explains %s without suggesting retry', (code, key) => {
+ expect(sharedTaskErrorKey(Object.assign(new Error('limit'), { code }))).toBe(key);
+ expect(sharedTaskErrorKey(new Error('[' + code + '] limit'))).toBe(key);
+ });
+ it.each(['DEVICE_LINK_CHANNEL_NOT_ALLOWED', 'DEVICE_LINK_VERSION_MISMATCH', 'UNSUPPORTED_CAPABILITY'])(
+ 'recognizes serialized and structured %s', (code) => {
+ expect(sharedTaskErrorKey(Object.assign(new Error('unsupported'), { code }))).toBe('sharedTask.upgrade');
+ expect(sharedTaskErrorKey(new Error(`Error invoking remote method 'device-link:invoke': Error: [${code}] unsupported`))).toBe('sharedTask.upgrade');
+ });
+ it.each(['DEVICE_LINK_NOT_CONNECTED', 'DEVICE_LINK_TIMEOUT', 'DEVICE_LINK_ACCESS_REVOKED', 'NOT_FOUND'])(
+ 'does not turn %s into an upgrade requirement', (code) => {
+ expect(sharedTaskErrorKey(new Error(`[${code}] DEVICE_LINK_CHANNEL_NOT_ALLOWED`))).toBe('sharedTask.retry');
+ });
+});
diff --git a/apps/desktop/src/renderer/features/device-link/sharedTaskCompatibility.ts b/apps/desktop/src/renderer/features/device-link/sharedTaskCompatibility.ts
new file mode 100644
index 0000000000..1255eb6355
--- /dev/null
+++ b/apps/desktop/src/renderer/features/device-link/sharedTaskCompatibility.ts
@@ -0,0 +1,11 @@
+import { extractIpcError } from '@/utils/ipcError';
+
+/** Only explicit capability failures imply an upgrade; offline is retryable. */
+export function sharedTaskErrorKey(error: unknown) {
+ const code = extractIpcError(error)?.code;
+ if (code === 'SHARED_TASK_HOST_LIMIT') return 'sharedTask.hostLimit';
+ if (code === 'SHARED_TASK_JOIN_LIMIT') return 'sharedTask.joinLimit';
+ if (code === 'SHARED_TASK_GUEST_LIMIT') return 'sharedTask.guestLimit';
+ return code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED' || code === 'DEVICE_LINK_VERSION_MISMATCH'
+ || code === 'UNSUPPORTED_CAPABILITY' ? 'sharedTask.upgrade' : 'sharedTask.retry';
+}
diff --git a/apps/desktop/src/renderer/features/device-link/switcherDevices.ts b/apps/desktop/src/renderer/features/device-link/switcherDevices.ts
index b6f3f5ef3a..c649f6bb2d 100644
--- a/apps/desktop/src/renderer/features/device-link/switcherDevices.ts
+++ b/apps/desktop/src/renderer/features/device-link/switcherDevices.ts
@@ -12,6 +12,7 @@
*/
import type { RemoteDeviceSummary } from './remoteProjectsStore';
+import { isSharedTaskPeer } from '@cindy/device-link';
import { compareDevicesByName, isMobilePlatform } from '@cindy/maker-shared/device-list';
export type DeviceConnectionStatus = 'connected' | 'connecting' | 'rejected';
@@ -73,6 +74,8 @@ export function buildSwitcherDevices({
const devices: SwitcherDevice[] = [];
for (const deviceId of candidates) {
+ // Shared tasks belong to task navigation, never the device selector.
+ if (isSharedTaskPeer(deviceId)) continue;
const cachedDevice = cached.get(deviceId);
let status: DeviceConnectionStatus = 'connecting';
if (revoked.has(deviceId)) {
diff --git a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
index ff51ba9a60..b7942d38ce 100644
--- a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
+++ b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
@@ -589,6 +589,8 @@ export function useDeviceLinkRemoteProjects(
// 要收的那些分片(review: codex 指出上一轮的修复因此无效)。
const authoritative = new Set(devices.map((d) => d.deviceId));
for (const deviceId of remoteProjectsStore.getAllDeviceIds()) {
+ // SharedTask shards are reconciled against membership, not the own-device directory.
+ if (deviceId.startsWith('shared-task~')) continue;
if (authoritative.has(deviceId) || eligible.has(deviceId)) continue;
log.debug(`removing cached shard absent from listDevices: ${deviceId.slice(0, 8)}`);
clearArchivedSessionRetry(deviceId);
diff --git a/apps/desktop/src/renderer/features/device-link/useSharedTaskTasks.ts b/apps/desktop/src/renderer/features/device-link/useSharedTaskTasks.ts
new file mode 100644
index 0000000000..88371e7730
--- /dev/null
+++ b/apps/desktop/src/renderer/features/device-link/useSharedTaskTasks.ts
@@ -0,0 +1,71 @@
+import { useEffect } from 'react';
+import { sharedTaskHostPeer, parseSharedTaskPeer, type SharedTaskListItem } from '@cindy/device-link';
+import { useAuth } from '@/contexts/AuthContext';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
+import type { Session } from '@/lib/ccAgent.types';
+import { remoteProjectsStore } from './remoteProjectsStore';
+import { bindSharedTaskPushOwner, resetRemoteDataOwnerPushFence } from '@/lib/remoteDataOwnerPushFence';
+
+/** SharedTask peers have their own authority list, independent of the user's device directory. */
+export function useSharedTaskTasks(): void {
+ const { isAuthenticated, dataOwnerId, dataOwnerRecoveryEpoch } = useAuth();
+ const ownerGeneration = getDataOwnerGeneration().generation;
+ useEffect(() => {
+ if (!isAuthenticated) return;
+ let disposed = false;
+ const owner = getDataOwnerGeneration();
+ const currentOwner = () => !disposed && isDataOwnerGenerationCurrent(owner);
+ let busy = false;
+ const linked = new Map<string, string>();
+ const poll = async () => {
+ if (busy || !currentOwner()) return;
+ busy = true;
+ try {
+ const sharedTasks = await window.electronAPI.sharedTask.account({ action: 'list' }) as SharedTaskListItem[];
+ if (!currentOwner()) return;
+ const current = new Set(sharedTasks.map((sharedTask) => sharedTaskHostPeer(sharedTask.sharedTaskId)));
+ for (const id of remoteProjectsStore.getAllDeviceIds()) {
+ if (!parseSharedTaskPeer(id) || current.has(id)) continue;
+ linked.delete(id);
+ resetRemoteDataOwnerPushFence(id);
+ remoteProjectsStore.removeDevice(id);
+ void window.electronAPI.deviceLink.closeLink(id);
+ }
+ for (const sharedTask of sharedTasks) {
+ if (!currentOwner()) return;
+ const peer = sharedTaskHostPeer(sharedTask.sharedTaskId);
+ bindSharedTaskPushOwner(peer, sharedTask.ownerAccountId);
+ try {
+ if (!linked.has(peer)) {
+ await window.electronAPI.deviceLink.openLink(peer);
+ if (!currentOwner()) return;
+ await window.electronAPI.deviceLink.subscribe(peer, ['session:' + sharedTask.sessionId]);
+ if (!currentOwner()) return;
+ linked.set(peer, sharedTask.sessionId);
+ }
+ const session = await window.electronAPI.deviceLink.invoke(peer, 'local-db:sessions:get', [sharedTask.sessionId]) as Session;
+ if (!currentOwner()) return;
+ if (session?.id !== sharedTask.sessionId) throw new Error('SharedTask task mismatch');
+ remoteProjectsStore.setDeviceSessions(peer, sharedTask.title, [session]);
+ } catch {
+ if (!currentOwner()) return;
+ remoteProjectsStore.markDeviceDisconnected(peer);
+ }
+ }
+ } catch { /* No authority response is not evidence of departure. */ }
+ finally { busy = false; }
+ };
+ void poll();
+ const timer = setInterval(() => { void poll(); }, 5_000);
+ return () => {
+ disposed = true;
+ clearInterval(timer);
+ for (const [peer, sessionId] of linked) {
+ if (!isDataOwnerGenerationCurrent(owner)) break;
+ void window.electronAPI.deviceLink.unsubscribe(peer, ['session:' + sessionId]).catch(() => undefined);
+ remoteProjectsStore.removeDevice(peer);
+ resetRemoteDataOwnerPushFence(peer);
+ }
+ };
+ }, [dataOwnerId, ownerGeneration, dataOwnerRecoveryEpoch, isAuthenticated]);
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index a9fc163d9d..631a9f5174 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -1,4 +1,103 @@
{
+ "sharedTask": {
+ "joinedSection": "Shared tasks I joined",
+ "ownedSection": "Shared tasks I started",
+ "ownedTab": "Started",
+ "joinedTab": "Joined",
+ "reconnecting": "Reconnecting…",
+ "ownedLoadFailed": "Unable to load",
+ "loadingOwned": "Loading…",
+ "ownedActiveCount": "{{count}} active",
+ "retryAction": "Retry",
+ "closeAllShort": "Close all sharing",
+ "invitationCopyFailed": "The invitation was created but could not be copied. Return to this window and try again.",
+ "accessEndedBody": "You can no longer access this shared task. To join again, ask the host for a new invitation.",
+ "joinIntro": "Paste the invitation from the host to enter the same task.",
+ "invitationPlaceholder": "Paste the invitation",
+ "joinNickname": "Your Name in This Task",
+ "nicknamePlaceholder": "What should we call you?",
+ "joinNotice": "After joining, you can view the full history and message the Agent directly, without waiting for host approval.",
+ "joinedTitle": "Joined “{{title}}”",
+ "joined": "Joined Shared Task",
+ "joinedBody": "You can view earlier messages, tool results and attachments, and message the same Agent.",
+ "enterTask": "Enter Task",
+ "inviteBoxTitle": "Send the invitation to your teammates",
+ "roleGuest": "Guest",
+ "removeShort": "Remove",
+ "removeNamedTitle": "Remove {{name}}?",
+ "shareCurrent": "Share Current Task",
+ "manage": "Manage",
+ "guestCount": "{{count}} guests",
+ "ownedTitle": "Shares I Started",
+ "ended": "Sharing Ended",
+ "rejoin": "Join With a New Invitation",
+ "otherDevice": "Other Computer",
+ "hostDevice": "Host Computer",
+ "runsOnHostDevice": "Running on the host computer",
+ "remoteHostOfflineNote": "Sharing closes when the host computer goes offline. Start sharing again and send a new invitation after reconnecting.",
+ "waitingHost": "Waiting for the host to respond. You can continue sending messages.",
+ "join": "Join Shared Task",
+ "joinHint": "Paste an invitation to open the shared task.",
+ "login": "Sign in to Cindy to join a task.",
+ "openTask": "Open Task",
+ "notJoined": "This task is no longer shared with you.",
+ "invitation": "Invitation",
+ "invalid": "Enter a valid invitation and your display name.",
+ "nickname": "Display Name",
+ "requestJoin": "Join",
+ "dismiss": "Close Dialog",
+ "title": "Share Task",
+ "hostLimit": "You can host up to 2 shared tasks at a time. Close one before trying again.",
+ "joinLimit": "You can join up to 2 shared tasks at a time. Leave one before trying again.",
+ "guestLimit": "This shared task already has 2 guests. You cannot join it yet.",
+ "retry": "Could not update sharing. Check your connection and retry.",
+ "upgrade": "Sharing requires updated clients and server.",
+ "sharing": "Guests can read all task content and use the Agent with this task’s permissions. Existing approvals stay with the owner.",
+ "open": "Start Sharing",
+ "members": "Members: {{count}}",
+ "host": "Host",
+ "remove": "Remove Guest",
+ "leave": "Leave Shared Task",
+ "invite": "Copy Invitation",
+ "close": "Stop Sharing",
+ "invitationCopied": "Invitation copied",
+ "tabCurrent": "Current Task",
+ "tabOwned": "Shared by Me",
+ "startIntro": "Invite a partner to read everything in this task and work with the same Agent.",
+ "runsOnThisDevice": "Runs on this device",
+ "inviteNotice": "Anyone holding the invitation can join after signing in, with the same Agent access as the host.",
+ "offlineAutoClose": "Sharing closes automatically when the host goes offline.",
+ "inviteBoxHint": "Full history and messaging after joining",
+ "membersWithLimit": "Members · {{count}} (up to 2 guests)",
+ "me": "Me",
+ "thisDevice": "This device",
+ "roleHost": "Host",
+ "hostOfflineNote": "Sharing closes automatically when this device goes offline. Re-enable sharing and invite again after coming back.",
+ "closeCurrent": "Stop Sharing This Task",
+ "sharingBadge": "Sharing",
+ "ownedIntro": "{{count}} tasks you share in this region",
+ "ownedEmptyTitle": "Nothing is being shared",
+ "ownedEmptyHint": "Open any task and click “Share Task” to invite a partner.",
+ "closeAll": "Stop All Sharing ({{count}})",
+ "closeAllNote": "After everything is closed, guests lose access and old invitations expire. Task history and Agent work are kept.",
+ "closeAllTitle": "Stop all sharing?",
+ "closeAllBody": "This closes every task you share in this region, including tasks hosted on other computers.",
+ "closeAllKeep": "Keep Sharing",
+ "closeAllAction": "Close {{count}} shares",
+ "closeAllScopeNote": "Task history and Agent work are kept; tasks you joined stay unaffected.",
+ "closeOneTitle": "Stop sharing this task?",
+ "closeOneBody": "All guests will lose access and the invitation will expire.",
+ "removeTitle": "Remove this guest?",
+ "removeBody": "The guest will lose access. Rejoining requires a new invitation from the host.",
+ "removeKeep": "Keep Guest",
+ "leaveTitle": "Leave this shared task?",
+ "leaveBody": "You will lose access to the task. Rejoining requires a new invitation from the host.",
+ "leaveKeep": "Stay in Task",
+ "hostOfflineTitle": "Host is offline",
+ "hostOfflineBody": "Sharing for this task is closed and the invitation has expired. Ask the host to share again and send a new invitation.",
+ "closedToast": "Stopped sharing for {{count}} tasks",
+ "closeFailedToast": "Some shares could not be closed ({{count}}). Retry later."
+ },
"privacyExit": {
"status": "This computer is being remotely controlled through Cindy",
"hint": "Click or press any key to disconnect…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 693856699a..7c443745bd 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -1,4 +1,103 @@
{
+ "sharedTask": {
+ "joinedSection": "参加した共有タスク",
+ "ownedSection": "開始した共有タスク",
+ "ownedTab": "開始",
+ "joinedTab": "参加",
+ "reconnecting": "再接続中…",
+ "ownedLoadFailed": "取得できません",
+ "loadingOwned": "取得中…",
+ "ownedActiveCount": "{{count}} 件が進行中",
+ "retryAction": "再試行",
+ "closeAllShort": "すべての共有を終了",
+ "invitationCopyFailed": "招待は作成されましたが、コピーできませんでした。このウィンドウに戻って再試行してください。",
+ "accessEndedBody": "この共有タスクにはアクセスできなくなりました。再参加するには、ホストに新しい招待を依頼してください。",
+ "joinIntro": "ホストから届いた招待を貼り付けて、同じタスクに参加します。",
+ "invitationPlaceholder": "招待内容を貼り付け",
+ "joinNickname": "タスク内でのニックネーム",
+ "nicknamePlaceholder": "表示する名前",
+ "joinNotice": "参加するとすべての履歴を閲覧でき、ホストの承認を待たずに Agent にメッセージを送信できます。",
+ "joinedTitle": "「{{title}}」に参加しました",
+ "joined": "共有タスクに参加しました",
+ "joinedBody": "参加前のメッセージ、ツールの結果、添付ファイルを確認し、同じ Agent にメッセージを送信できます。",
+ "enterTask": "タスクを開く",
+ "inviteBoxTitle": "仲間に招待を送信",
+ "roleGuest": "ゲスト",
+ "removeShort": "削除",
+ "removeNamedTitle": "{{name}}を削除しますか?",
+ "shareCurrent": "現在のタスクを共有",
+ "manage": "管理",
+ "guestCount": "ゲスト {{count}} 人",
+ "ownedTitle": "自分が開始した共有",
+ "ended": "共有が終了しました",
+ "rejoin": "新しい招待で参加",
+ "otherDevice": "他のパソコン",
+ "hostDevice": "ホストのパソコン",
+ "runsOnHostDevice": "ホストのパソコンで実行中",
+ "remoteHostOfflineNote": "ホストのパソコンがオフラインになると共有は自動で終了します。再接続後に共有を開始し、新しい招待を送信してください。",
+ "waitingHost": "ホストの対応を待っています。引き続きメッセージを送信できます。",
+ "join": "共有セッションに参加",
+ "joinHint": "招待を貼り付けて共有セッションを開きます。",
+ "login": "セッションに参加するには Cindy にログインしてください。",
+ "openTask": "セッションを開く",
+ "notJoined": "この共有セッションにはアクセスできません。",
+ "invitation": "招待",
+ "invalid": "有効な招待と表示名を入力してください。",
+ "nickname": "表示名",
+ "requestJoin": "参加",
+ "dismiss": "ダイアログを閉じる",
+ "title": "セッションを共有",
+ "hostLimit": "同時に共有できるタスクは 2 件までです。共有を 1 件終了してから再試行してください。",
+ "joinLimit": "同時に参加できる共有タスクは 2 件までです。1 件から退出してから再試行してください。",
+ "guestLimit": "この共有タスクにはすでにゲストが 2 人いるため、参加できません。",
+ "retry": "共有状態を更新できませんでした。接続を確認して再試行してください。",
+ "upgrade": "共有にはクライアントとサーバーの更新が必要です。",
+ "sharing": "参加者はすべての内容を閲覧し、このセッションの権限で Agent を使用できます。既存の承認は所有者が行います。",
+ "open": "共有を開始",
+ "members": "メンバー:{{count}} 人",
+ "host": "ホスト",
+ "remove": "ゲストを削除",
+ "leave": "共有セッションから退出",
+ "invite": "招待をコピー",
+ "close": "共有を停止",
+ "invitationCopied": "招待をコピーしました",
+ "tabCurrent": "現在のセッション",
+ "tabOwned": "自分が共有中",
+ "startIntro": "パートナーを招待して、このセッションのすべての内容を共有し、同じ Agent で協力できます。",
+ "runsOnThisDevice": "このパソコンで実行中",
+ "inviteNotice": "招待を持つユーザーはログイン後に参加でき、所有者と同じ Agent 権限を持ちます。",
+ "offlineAutoClose": "ホストがオフラインになると、共有は自動的に終了します。",
+ "inviteBoxHint": "参加後はすべての履歴の閲覧とメッセージ送信が可能",
+ "membersWithLimit": "メンバー · {{count}} 人(ゲストは最大 2 人)",
+ "me": "自分",
+ "thisDevice": "このパソコン",
+ "roleHost": "ホスト",
+ "hostOfflineNote": "このパソコンがオフラインになると共有は終了します。再開後はもう一度共有を開始して招待してください。",
+ "closeCurrent": "このセッションの共有を停止",
+ "sharingBadge": "共有中",
+ "ownedIntro": "このリージョンで自分が共有中の {{count}} 件",
+ "ownedEmptyTitle": "共有中のセッションはありません",
+ "ownedEmptyHint": "任意のセッションを開いて「セッションを共有」から招待できます。",
+ "closeAll": "すべての共有を停止({{count}})",
+ "closeAllNote": "すべて停止すると、ゲストはアクセスできなくなり、古い招待は無効になります。セッションの記録と Agent の作業は保持されます。",
+ "closeAllTitle": "すべての共有を停止しますか?",
+ "closeAllBody": "このリージョンで自分が共有中のすべてのセッション(他のパソコンを含む)を停止します。",
+ "closeAllKeep": "共有を続ける",
+ "closeAllAction": "{{count}} 件の共有を停止",
+ "closeAllScopeNote": "セッションの記録と Agent の作業は保持され、自分が参加している他のセッションには影響しません。",
+ "closeOneTitle": "このセッションの共有を停止しますか?",
+ "closeOneBody": "すべてのゲストはアクセスできなくなり、招待は無効になります。",
+ "removeTitle": "このゲストを削除しますか?",
+ "removeBody": "そのゲストはアクセスできなくなります。再参加にはホストの新しい招待が必要です。",
+ "removeKeep": "ゲストを残す",
+ "leaveTitle": "共有セッションから退出しますか?",
+ "leaveBody": "退出するとこのセッションにアクセスできなくなります。再参加にはホストの新しい招待が必要です。",
+ "leaveKeep": "セッションに残る",
+ "hostOfflineTitle": "ホストがオフラインです",
+ "hostOfflineBody": "このセッションの共有は終了し、招待は無効になりました。ホストに再度共有を開始してもらい、新しい招待を送ってもらってください。",
+ "closedToast": "{{count}} 件のセッションの共有を停止しました",
+ "closeFailedToast": "停止できなかった共有があります({{count}} 件)。後ほど再試行できます。"
+ },
"privacyExit": {
"status": "Cindy でリモート操作されています",
"hint": "クリックまたは任意のキーを押すと、切断を確認できます",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index f07465d8ca..be66c9eb4e 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -1,4 +1,103 @@
{
+ "sharedTask": {
+ "joinedSection": "참여한 공유 작업",
+ "ownedSection": "내가 시작한 공유 작업",
+ "ownedTab": "시작",
+ "joinedTab": "참여",
+ "reconnecting": "다시 연결 중…",
+ "ownedLoadFailed": "불러올 수 없음",
+ "loadingOwned": "불러오는 중…",
+ "ownedActiveCount": "{{count}}개 진행 중",
+ "retryAction": "다시 시도",
+ "closeAllShort": "모든 공유 종료",
+ "invitationCopyFailed": "초대가 생성되었지만 복사하지 못했습니다. 이 창으로 돌아와 다시 시도해 주세요.",
+ "accessEndedBody": "이 공유 작업에 더 이상 접근할 수 없습니다. 다시 참여하려면 호스트에게 새 초대를 요청하세요.",
+ "joinIntro": "호스트가 보낸 초대를 붙여넣어 같은 작업에 참여하세요.",
+ "invitationPlaceholder": "초대 내용 붙여넣기",
+ "joinNickname": "작업에서 사용할 닉네임",
+ "nicknamePlaceholder": "표시할 이름",
+ "joinNotice": "참여하면 전체 기록을 보고 호스트의 승인을 기다리지 않고 Agent에게 메시지를 보낼 수 있습니다.",
+ "joinedTitle": "「{{title}}」에 참여했습니다",
+ "joined": "공유 작업에 참여했습니다",
+ "joinedBody": "참여 전의 메시지, 도구 결과, 첨부 파일을 확인하고 같은 Agent에게 메시지를 보낼 수 있습니다.",
+ "enterTask": "작업 열기",
+ "inviteBoxTitle": "동료에게 초대 보내기",
+ "roleGuest": "게스트",
+ "removeShort": "제거",
+ "removeNamedTitle": "{{name}} 님을 제거할까요?",
+ "shareCurrent": "현재 작업 공유",
+ "manage": "관리",
+ "guestCount": "게스트 {{count}}명",
+ "ownedTitle": "내가 시작한 공유",
+ "ended": "공유가 종료되었습니다",
+ "rejoin": "새 초대로 참여",
+ "otherDevice": "다른 컴퓨터",
+ "hostDevice": "호스트 컴퓨터",
+ "runsOnHostDevice": "호스트 컴퓨터에서 실행 중",
+ "remoteHostOfflineNote": "호스트 컴퓨터가 오프라인이 되면 공유가 자동 종료됩니다. 다시 연결한 후 공유를 시작하고 새 초대를 보내세요.",
+ "waitingHost": "호스트의 응답을 기다리고 있습니다. 메시지는 계속 보낼 수 있습니다.",
+ "join": "공유 세션 참여",
+ "joinHint": "초대를 붙여넣어 공유 세션을 여세요.",
+ "login": "세션에 참가하려면 Cindy에 로그인하세요.",
+ "openTask": "세션 열기",
+ "notJoined": "이 공유 세션에 더 이상 접근할 수 없습니다.",
+ "invitation": "초대",
+ "invalid": "유효한 초대와 표시 이름을 입력하세요.",
+ "nickname": "표시 이름",
+ "requestJoin": "참여",
+ "dismiss": "대화 상자 닫기",
+ "title": "세션 공유",
+ "hostLimit": "동시에 공유할 수 있는 작업은 최대 2개입니다. 하나를 닫은 후 다시 시도하세요.",
+ "joinLimit": "동시에 참여할 수 있는 공유 작업은 최대 2개입니다. 하나에서 나간 후 다시 시도하세요.",
+ "guestLimit": "이 공유 작업에는 이미 게스트가 2명 있어 참여할 수 없습니다.",
+ "retry": "공유 상태를 업데이트하지 못했습니다. 연결을 확인한 후 다시 시도하세요.",
+ "upgrade": "공유하려면 클라이언트와 서버를 업데이트해야 합니다.",
+ "sharing": "참여자는 모든 내용을 보고 이 세션의 권한으로 Agent를 사용할 수 있습니다. 기존 승인은 소유자가 처리합니다.",
+ "open": "공유 시작",
+ "members": "멤버: {{count}}명",
+ "host": "호스트",
+ "remove": "게스트 내보내기",
+ "leave": "공유 세션 나가기",
+ "invite": "초대 복사",
+ "close": "공유 중지",
+ "invitationCopied": "초대를 복사했습니다",
+ "tabCurrent": "현재 세션",
+ "tabOwned": "내가 공유한 항목",
+ "startIntro": "파트너를 초대해 이 세션의 모든 내용을 함께 보고, 같은 Agent로 협업하세요.",
+ "runsOnThisDevice": "이 PC에서 실행 중",
+ "inviteNotice": "초대를 가진 사용자는 로그인 후 참여할 수 있으며, 호스트와 동일한 Agent 권한을 갖습니다.",
+ "offlineAutoClose": "호스트가 오프라인이 되면 공유는 자동으로 종료됩니다.",
+ "inviteBoxHint": "참여 후 전체 기록 조회와 메시지 전송 가능",
+ "membersWithLimit": "멤버 · {{count}}명 (최대 게스트 2명)",
+ "me": "나",
+ "thisDevice": "이 PC",
+ "roleHost": "호스트",
+ "hostOfflineNote": "이 PC가 오프라인이 되면 공유가 종료됩니다. 다시 온라인이 되면 공유를 다시 시작하고 초대해 주세요.",
+ "closeCurrent": "이 세션 공유 중지",
+ "sharingBadge": "공유 중",
+ "ownedIntro": "이 리전에서 내가 공유한 {{count}}개 세션",
+ "ownedEmptyTitle": "공유 중인 세션이 없습니다",
+ "ownedEmptyHint": "아무 세션이나 열고 \"세션 공유\"를 눌러 파트너를 초대하세요.",
+ "closeAll": "전체 공유 중지 ({{count}})",
+ "closeAllNote": "모두 중지하면 게스트는 접근할 수 없고 기존 초대는 만료됩니다. 세션 기록과 Agent 작업은 유지됩니다.",
+ "closeAllTitle": "전체 공유를 중지할까요?",
+ "closeAllBody": "이 리전에서 내가 공유한 모든 세션(다른 PC 포함)을 중지합니다.",
+ "closeAllKeep": "공유 유지",
+ "closeAllAction": "{{count}}개 공유 중지",
+ "closeAllScopeNote": "세션 기록과 Agent 작업은 유지되며, 내가 참여한 다른 세션에는 영향이 없습니다.",
+ "closeOneTitle": "이 세션 공유를 중지할까요?",
+ "closeOneBody": "모든 게스트가 접근할 수 없게 되고 초대는 만료됩니다.",
+ "removeTitle": "이 게스트를 내보낼까요?",
+ "removeBody": "해당 게스트는 접근할 수 없게 됩니다. 다시 참여하려면 호스트의 새 초대가 필요합니다.",
+ "removeKeep": "게스트 유지",
+ "leaveTitle": "공유 세션에서 나설까요?",
+ "leaveBody": "나가면 이 세션에 접근할 수 없습니다. 다시 참여하려면 호스트의 새 초대가 필요합니다.",
+ "leaveKeep": "세션에 남기",
+ "hostOfflineTitle": "호스트가 오프라인입니다",
+ "hostOfflineBody": "이 세션의 공유는 종료되었고 초대는 만료되었습니다. 호스트에게 공유를 다시 시작하고 새 초대를 보내달라고 요청하세요.",
+ "closedToast": "{{count}}개 세션의 공유를 중지했습니다",
+ "closeFailedToast": "중지하지 못한 공유가 있습니다({{count}}건). 나중에 다시 시도할 수 있습니다."
+ },
"privacyExit": {
"status": "Cindy를 통해 원격 제어 중입니다",
"hint": "화면을 클릭하거나 아무 키나 누르면 연결 끊기를 확인합니다",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index f024a9861e..e3d23d5a3e 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -1,4 +1,103 @@
{
+ "sharedTask": {
+ "joinedSection": "我加入的共享",
+ "ownedSection": "我开启的共享",
+ "ownedTab": "我开启的",
+ "joinedTab": "我加入的",
+ "reconnecting": "正在重新连接…",
+ "ownedLoadFailed": "暂时无法获取",
+ "loadingOwned": "正在获取…",
+ "ownedActiveCount": "{{count}} 个进行中",
+ "retryAction": "重试",
+ "closeAllShort": "关闭全部共享",
+ "invitationCopyFailed": "邀请已生成,但未能复制。请回到此窗口后重试。",
+ "accessEndedBody": "当前已无法访问这个共享任务。如需再次加入,请联系房主发送新邀请。",
+ "joinIntro": "粘贴房主发来的邀请,进入同一个任务。",
+ "invitationPlaceholder": "粘贴邀请内容",
+ "joinNickname": "你在任务中的昵称",
+ "nicknamePlaceholder": "怎么称呼你",
+ "joinNotice": "加入后可查看全部历史,并直接向 Agent 发消息,无需等待房主审批。",
+ "joinedTitle": "已加入「{{title}}」",
+ "joined": "已加入共享任务",
+ "joinedBody": "你可以查看加入前的消息、工具结果和附件,也可以向同一个 Agent 发消息。",
+ "enterTask": "进入任务",
+ "inviteBoxTitle": "将邀请发给你的伙伴",
+ "roleGuest": "访客",
+ "removeShort": "移除",
+ "removeNamedTitle": "移除{{name}}?",
+ "shareCurrent": "共享当前任务",
+ "manage": "管理",
+ "guestCount": "{{count}} 位访客",
+ "ownedTitle": "我发起的共享",
+ "ended": "共享已结束",
+ "rejoin": "使用新邀请加入",
+ "otherDevice": "其他电脑",
+ "hostDevice": "房主电脑",
+ "runsOnHostDevice": "运行在房主电脑",
+ "remoteHostOfflineNote": "房主电脑离线时,共享自动关闭。重新上线后需再次开启并邀请。",
+ "waitingHost": "等待房主处理,你可以继续发送消息。",
+ "join": "加入共享任务",
+ "joinHint": "粘贴邀请,进入同一个共享任务。",
+ "login": "请登录 Cindy 后加入任务",
+ "openTask": "打开任务",
+ "notJoined": "你已无法访问此共享任务。",
+ "invitation": "邀请内容",
+ "invalid": "请输入有效的邀请内容和昵称",
+ "nickname": "昵称",
+ "requestJoin": "加入",
+ "dismiss": "关闭窗口",
+ "title": "共享任务",
+ "hostLimit": "你最多同时开启 2 个共享任务,请先关闭一个再试。",
+ "joinLimit": "你最多同时加入 2 个共享任务,请先退出一个再试。",
+ "guestLimit": "此共享任务已有 2 名访客,暂时无法加入。",
+ "retry": "未能更新共享状态,请检查连接后重试",
+ "upgrade": "共享任务需要更新客户端和服务器。",
+ "sharing": "访客可以查看任务的全部内容,并按该任务现有权限使用 Agent。已有审批仍由房主处理。",
+ "open": "开启共享",
+ "members": "成员:{{count}} 人",
+ "host": "房主",
+ "remove": "移除访客",
+ "leave": "退出共享任务",
+ "invite": "复制邀请",
+ "close": "关闭共享",
+ "invitationCopied": "邀请已复制",
+ "tabCurrent": "当前任务",
+ "tabOwned": "我发起的",
+ "startIntro": "邀请伙伴查看这个任务的全部内容,一起与同一个 Agent 协作。",
+ "runsOnThisDevice": "运行在这台电脑",
+ "inviteNotice": "持有邀请的用户登录后即可加入,拥有与房主相同的 Agent 使用权限。",
+ "offlineAutoClose": "房主离线时,共享会自动关闭。",
+ "inviteBoxHint": "加入后可查看完整历史并发消息",
+ "membersWithLimit": "成员 · {{count}} 人(最多 2 位访客)",
+ "me": "我",
+ "thisDevice": "这台电脑",
+ "roleHost": "房主",
+ "hostOfflineNote": "这台电脑离线时,共享自动关闭。重新上线后需再次开启并邀请。",
+ "closeCurrent": "关闭此任务的共享",
+ "sharingBadge": "共享中",
+ "ownedIntro": "当前账号在此区域发起的 {{count}} 个共享任务",
+ "ownedEmptyTitle": "没有正在共享的任务",
+ "ownedEmptyHint": "回到任意任务,点击「共享任务」邀请伙伴。",
+ "closeAll": "关闭全部共享({{count}})",
+ "closeAllNote": "全部关闭后,访客无法继续访问,原邀请失效。任务记录和 Agent 工作会保留。",
+ "closeAllTitle": "关闭全部共享?",
+ "closeAllBody": "将关闭当前账号在此区域发起的全部共享,包含其他电脑上的任务。",
+ "closeAllKeep": "保持共享",
+ "closeAllAction": "关闭 {{count}} 个共享",
+ "closeAllScopeNote": "任务记录和 Agent 工作保留;你加入别人的任务不受影响。",
+ "closeOneTitle": "关闭此任务的共享?",
+ "closeOneBody": "所有访客将无法继续访问,原邀请将失效。",
+ "removeTitle": "移除这位访客?",
+ "removeBody": "该访客将无法继续访问。再次加入需要房主生成新邀请。",
+ "removeKeep": "保留访客",
+ "leaveTitle": "退出共享任务?",
+ "leaveBody": "退出后将无法访问这个任务。再次加入需要房主发送新邀请。",
+ "leaveKeep": "留在任务",
+ "hostOfflineTitle": "房主已离线",
+ "hostOfflineBody": "这个任务的共享已关闭,原邀请已失效。请联系房主重新开启共享并发送新邀请。",
+ "closedToast": "已关闭 {{count}} 个任务的共享",
+ "closeFailedToast": "部分共享未能关闭({{count}} 项),可稍后重试。"
+ },
"privacyExit": {
"status": "正在通过 Cindy 被远程控制",
"hint": "点击屏幕或按任意键,确认后断开连接",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index e1f00bbc28..ef6d00ebab 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -1,4 +1,103 @@
{
+ "sharedTask": {
+ "joinedSection": "我加入的共享",
+ "ownedSection": "我開啟的共享",
+ "ownedTab": "我開啟的",
+ "joinedTab": "我加入的",
+ "reconnecting": "正在重新連線…",
+ "ownedLoadFailed": "暫時無法取得",
+ "loadingOwned": "正在取得…",
+ "ownedActiveCount": "{{count}} 個進行中",
+ "retryAction": "重試",
+ "closeAllShort": "關閉全部共享",
+ "invitationCopyFailed": "邀請已產生,但未能複製。請回到此視窗後重試。",
+ "accessEndedBody": "目前已無法存取此共享任務。如需再次加入,請聯絡房主傳送新邀請。",
+ "joinIntro": "貼上房主傳來的邀請,進入同一個任務。",
+ "invitationPlaceholder": "貼上邀請內容",
+ "joinNickname": "你在任務中的暱稱",
+ "nicknamePlaceholder": "怎麼稱呼你",
+ "joinNotice": "加入後可查看全部歷史,並直接向 Agent 傳送訊息,無需等待房主審批。",
+ "joinedTitle": "已加入「{{title}}」",
+ "joined": "已加入共享任務",
+ "joinedBody": "你可以查看加入前的訊息、工具結果和附件,也可以向同一個 Agent 傳送訊息。",
+ "enterTask": "進入任務",
+ "inviteBoxTitle": "將邀請傳給你的夥伴",
+ "roleGuest": "訪客",
+ "removeShort": "移除",
+ "removeNamedTitle": "移除{{name}}?",
+ "shareCurrent": "共享目前任務",
+ "manage": "管理",
+ "guestCount": "{{count}} 位訪客",
+ "ownedTitle": "我發起的共享",
+ "ended": "共享已結束",
+ "rejoin": "使用新邀請加入",
+ "otherDevice": "其他電腦",
+ "hostDevice": "房主電腦",
+ "runsOnHostDevice": "在房主電腦上執行",
+ "remoteHostOfflineNote": "房主電腦離線時,共享會自動關閉。重新上線後需再次開啟並邀請。",
+ "waitingHost": "等待房主處理,你可以繼續傳送訊息。",
+ "join": "加入共享任務",
+ "joinHint": "貼上邀請,進入同一個共享任務。",
+ "login": "請登入 Cindy 後加入任務",
+ "openTask": "開啟任務",
+ "notJoined": "你已無法存取此共享任務。",
+ "invitation": "邀請內容",
+ "invalid": "請輸入有效的邀請內容和暱稱",
+ "nickname": "暱稱",
+ "requestJoin": "加入",
+ "dismiss": "關閉視窗",
+ "title": "共享任務",
+ "hostLimit": "你最多同時開啟 2 個共享任務,請先關閉一個再試。",
+ "joinLimit": "你最多同時加入 2 個共享任務,請先退出一個再試。",
+ "guestLimit": "此共享任務已有 2 名訪客,暫時無法加入。",
+ "retry": "無法更新共享狀態,請檢查連線後重試",
+ "upgrade": "共享任務需要更新客戶端與伺服器。",
+ "sharing": "訪客可以查看任務的全部內容,並按該任務現有權限使用 Agent。既有審批仍由房主處理。",
+ "open": "開啟共享",
+ "members": "成員:{{count}} 人",
+ "host": "主持人",
+ "remove": "移除訪客",
+ "leave": "離開共享任務",
+ "invite": "複製邀請",
+ "close": "停止共享",
+ "invitationCopied": "已複製邀請",
+ "tabCurrent": "目前任務",
+ "tabOwned": "我發起的",
+ "startIntro": "邀請夥伴查看這個任務的全部內容,一起與同一個 Agent 協作。",
+ "runsOnThisDevice": "執行在這台電腦",
+ "inviteNotice": "持有邀請的使用者登入後即可加入,擁有與房主相同的 Agent 使用權限。",
+ "offlineAutoClose": "房主離線時,共享會自動關閉。",
+ "inviteBoxHint": "加入後可查看完整歷史並傳送訊息",
+ "membersWithLimit": "成員 · {{count}} 人(最多 2 位訪客)",
+ "me": "我",
+ "thisDevice": "這台電腦",
+ "roleHost": "房主",
+ "hostOfflineNote": "這台電腦離線時,共享自動關閉。重新上線後需再次開啟並邀請。",
+ "closeCurrent": "關閉此任務的共享",
+ "sharingBadge": "共享中",
+ "ownedIntro": "目前帳號在此區域發起的 {{count}} 個共享任務",
+ "ownedEmptyTitle": "沒有正在共享的任務",
+ "ownedEmptyHint": "回到任意任務,點擊「共享任務」邀請夥伴。",
+ "closeAll": "關閉全部共享({{count}})",
+ "closeAllNote": "全部關閉後,訪客無法繼續存取,原邀請失效。任務記錄和 Agent 工作會保留。",
+ "closeAllTitle": "關閉全部共享?",
+ "closeAllBody": "將關閉目前帳號在此區域發起的全部共享,包含其他電腦上的任務。",
+ "closeAllKeep": "保持共享",
+ "closeAllAction": "關閉 {{count}} 個共享",
+ "closeAllScopeNote": "任務記錄和 Agent 工作保留;你加入別人的任務不受影響。",
+ "closeOneTitle": "關閉此任務的共享?",
+ "closeOneBody": "所有訪客將無法繼續存取,原邀請將失效。",
+ "removeTitle": "移除這位訪客?",
+ "removeBody": "該訪客將無法繼續存取。再次加入需要房主產生新邀請。",
+ "removeKeep": "保留訪客",
+ "leaveTitle": "離開共享任務?",
+ "leaveBody": "離開後將無法存取這個任務。再次加入需要房主傳送新邀請。",
+ "leaveKeep": "留在任務",
+ "hostOfflineTitle": "房主已離線",
+ "hostOfflineBody": "這個任務的共享已關閉,原邀請已失效。請聯絡房主重新開啟共享並傳送新邀請。",
+ "closedToast": "已關閉 {{count}} 個任務的共享",
+ "closeFailedToast": "部分共享未能關閉({{count}} 項),可稍後重試。"
+ },
"privacyExit": {
"status": "正在透過 Cindy 被遠端控制",
"hint": "點擊螢幕或按任意鍵,確認後中斷連線",
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 8bf544ca8f..0e1091904b 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -1,6 +1,7 @@
import { emitTaskTagCatalog } from '@/features/task-tags/taskTagEvents';
import { normalizeTaskTags } from '@cindy/maker-shared';
import type { ImMessageSource } from '../../shared/imMessageSource';
+import { sharedTaskAuthorName } from '@cindy/maker-shared';
import { readBotAuthorizationCard } from '../../shared/botAuthorization';
import { applyCindyMakeCardAttention } from './cindyMakeAttention';
import { confirmRemoteUsers, reserveRemoteUser } from './remoteUserHandoff';
@@ -473,6 +474,7 @@ export interface ChatMessage {
* 据此在气泡上方渲染"由自动化任务发送"标签。手动输入的消息无此字段。
*/
automationOrigin?: MessageAutomationOrigin;
+ sharedAuthorName?: string;
/** user 消息投递方式:普通新 turn 或运行中 steer。 */
delivery?: 'turn' | 'steer';
/** Hook 来源元数据(IM 平台 + 用户干净原文 + thread 上下文),UserMessage 据此渲染 Cindy 任务卡片。 */
@@ -7003,6 +7005,7 @@ type LiveIngressContext = {
ownerStamp?: unknown;
remoteDeviceId?: string;
ownerStampPresent?: boolean;
+ sourceEpoch?: number;
};
function isCurrentLiveIngress(context?: LiveIngressContext): boolean {
@@ -7014,7 +7017,7 @@ function isCurrentLiveIngress(context?: LiveIngressContext): boolean {
return !hasStamp || isDataOwnerPushStampCurrent(context.ownerStamp);
}
- return isRemoteDataOwnerPushCurrent(context.remoteDeviceId, context.ownerStamp, hasStamp);
+ return isRemoteDataOwnerPushCurrent(context.remoteDeviceId, context.ownerStamp, hasStamp, context.sourceEpoch);
}
function isCurrentLocalLiveIngress(ownerStamp: unknown): boolean {
@@ -7026,6 +7029,7 @@ function isCurrentLocalLiveIngress(ownerStamp: unknown): boolean {
function sameLiveIngressScope(a: LiveIngressContext, b: LiveIngressContext): boolean {
if (a.remoteDeviceId !== b.remoteDeviceId) return false;
+ if (a.sourceEpoch !== b.sourceEpoch) return false;
const aStamp = isDataOwnerPushStamp(a.ownerStamp) ? a.ownerStamp : null;
const bStamp = isDataOwnerPushStamp(b.ownerStamp) ? b.ownerStamp : null;
if (aStamp === null || bStamp === null) return aStamp === bStamp;
@@ -8554,12 +8558,14 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
channel?: string;
payload?: unknown;
ownerStamp?: unknown;
+ sourceEpoch?: number;
} | null;
if (!push?.channel) return;
const remoteIngress: LiveIngressContext = push.deviceId
? {
remoteDeviceId: push.deviceId,
ownerStamp: push.ownerStamp,
+ sourceEpoch: push.sourceEpoch,
ownerStampPresent: Object.prototype.hasOwnProperty.call(push, 'ownerStamp'),
}
: {};
@@ -17588,6 +17594,7 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {
// older Mobile clients into legacy Hook/system-card semantics.
const hookSource = m.agentMeta?.imSource ?? m.agentMeta?.hookSource;
return {
+ sharedAuthorName: sharedTaskAuthorName(m.agentMeta),
clientId: m.clientId,
role: m.role,
content: parsed.text,
diff --git a/apps/desktop/src/renderer/lib/remoteDataOwnerPushFence.ts b/apps/desktop/src/renderer/lib/remoteDataOwnerPushFence.ts
index 4dcf766423..e3ae1b1107 100644
--- a/apps/desktop/src/renderer/lib/remoteDataOwnerPushFence.ts
+++ b/apps/desktop/src/renderer/lib/remoteDataOwnerPushFence.ts
@@ -1,7 +1,10 @@
import {
getDataOwnerGeneration,
+ isDataOwnerGenerationCurrent,
isDataOwnerPushCurrent,
+ type DataOwnerGeneration,
} from '@/contexts/dataOwnerGeneration';
+import { parseSharedTaskPeer } from '@cindy/device-link';
import { isDataOwnerPushStamp, type DataOwnerPushStamp } from '../../shared/dataOwnerPush';
@@ -9,6 +12,19 @@ import { isDataOwnerPushStamp, type DataOwnerPushStamp } from '../../shared/data
const remoteOwnerStamps = new Map<string, DataOwnerPushStamp>();
/** Devices that have emitted at least one stamped frame in this connection. */
const remoteStampedDevices = new Set<string>();
+const sharedTaskOwners = new Map<string, { owner: DataOwnerGeneration; hostAccountId: string }>();
+/** Main's verified host-stream epochs; independent of either account generation. */
+const sharedHostSourceEpochs = new Map<string, number>();
+
+/** Only call with a current authenticated sharedTask list/detail response, before linking. */
+export function bindSharedTaskPushOwner(peer: string, hostAccountId: string): void {
+ if (parseSharedTaskPeer(peer)?.role !== 'host' || !hostAccountId) return;
+ const owner = getDataOwnerGeneration();
+ if (!owner.dataOwnerId) return;
+ const previous = sharedTaskOwners.get(peer);
+ if (previous && isDataOwnerGenerationCurrent(previous.owner) && previous.hostAccountId !== hostAccountId) return;
+ sharedTaskOwners.set(peer, { owner, hostAccountId });
+}
/**
* Validate a controlled-device push against the renderer's current account.
@@ -21,14 +37,30 @@ export function isRemoteDataOwnerPushCurrent(
remoteDeviceId: string,
ownerStamp: unknown,
ownerStampPresent = ownerStamp !== undefined,
+ sourceEpoch?: number,
): boolean {
const current = getDataOwnerGeneration();
if (current.dataOwnerId === null) return false;
+ const sharedTaskPeer = parseSharedTaskPeer(remoteDeviceId);
+ const sharedOwner = sharedTaskPeer ? sharedTaskOwners.get(remoteDeviceId) : undefined;
+ if (sharedTaskPeer && (sharedTaskPeer.role !== 'host' || !sharedOwner ||
+ !isDataOwnerGenerationCurrent(sharedOwner.owner) || !ownerStampPresent)) return false;
if (!ownerStampPresent) return !remoteStampedDevices.has(remoteDeviceId);
if (!isDataOwnerPushStamp(ownerStamp)) return false;
remoteStampedDevices.add(remoteDeviceId);
- if (ownerStamp.dataOwnerId !== current.dataOwnerId) return false;
+ if (ownerStamp.dataOwnerId !== (sharedOwner?.hostAccountId ?? current.dataOwnerId)) return false;
+ if (sharedTaskPeer && sourceEpoch !== undefined) {
+ if (!Number.isSafeInteger(sourceEpoch) || sourceEpoch < 1) return false;
+ const previousEpoch = sharedHostSourceEpochs.get(remoteDeviceId);
+ if (previousEpoch !== undefined && sourceEpoch < previousEpoch) return false;
+ if (previousEpoch !== sourceEpoch) {
+ // The host restarted. Keep the authenticated membership binding while
+ // dropping only the old process's generation watermark.
+ remoteOwnerStamps.delete(remoteDeviceId);
+ sharedHostSourceEpochs.set(remoteDeviceId, sourceEpoch);
+ }
+ } else if (sharedTaskPeer && sharedHostSourceEpochs.has(remoteDeviceId)) return false;
const previous = remoteOwnerStamps.get(remoteDeviceId);
if (
@@ -45,7 +77,7 @@ export function isRemoteDataOwnerPushCurrent(
/** Validate both the controller's local owner boundary and the controlled device's source owner. */
export function isDeviceLinkRemotePushCurrent(
- push: { deviceId: string; ownerStamp?: unknown },
+ push: { deviceId: string; ownerStamp?: unknown; sourceEpoch?: number },
localOwnerStamp: unknown,
): boolean {
if (!isDataOwnerPushCurrent(localOwnerStamp)) return false;
@@ -53,17 +85,22 @@ export function isDeviceLinkRemotePushCurrent(
push.deviceId,
push.ownerStamp,
Object.prototype.hasOwnProperty.call(push, 'ownerStamp'),
+ push.sourceEpoch,
);
}
export function resetRemoteDataOwnerPushFence(remoteDeviceId?: string): void {
if (remoteDeviceId !== undefined) {
+ sharedTaskOwners.delete(remoteDeviceId);
+ sharedHostSourceEpochs.delete(remoteDeviceId);
remoteOwnerStamps.delete(remoteDeviceId);
remoteStampedDevices.delete(remoteDeviceId);
return;
}
remoteOwnerStamps.clear();
remoteStampedDevices.clear();
+ sharedTaskOwners.clear();
+ sharedHostSourceEpochs.clear();
}
export const __testing = {
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 3ed003b649..a74a125385 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -3882,6 +3882,10 @@ interface ElectronAPI {
openRemoteDesktop: (target: { deviceId: string; name: string }) => Promise<void>;
remoteDesktopViewer: import('../shared/remoteDesktopViewer').RemoteDesktopViewerApi;
remoteDesktop: import('../shared/remoteDesktop').RemoteDesktopApi;
+ sharedTask: {
+ host(command: import('@cindy/device-link').SharedTaskHostCommand): Promise<unknown>;
+ account(command: import('@cindy/device-link').SharedTaskAccountCommand): Promise<unknown>;
+ };
deviceLink: {
getState: () => Promise<{
remoteControlEnabled: boolean;
diff --git a/apps/desktop/src/shared/agentInputQueue.ts b/apps/desktop/src/shared/agentInputQueue.ts
index ef103847aa..eb43dca60d 100644
--- a/apps/desktop/src/shared/agentInputQueue.ts
+++ b/apps/desktop/src/shared/agentInputQueue.ts
@@ -9,6 +9,7 @@
*/
import { stripChatQuoteMarkerLines } from '@cindy/maker-shared/chat-quotes';
+import type { SharedTaskAuthor } from '@cindy/maker-shared';
import { UI_ACTION_TRIGGER_PREFIX } from '@cindy/maker-shared/synthetic-trigger';
import { MENTION_TOKEN_SPLIT, parseMentionToken } from '@cindy/maker-shared/mention-ref';
import {
@@ -219,6 +220,8 @@ export interface RecoveryCheckpoint {
}
export interface AgentInputQueuedMessage {
+ /** Host-stamped attribution, retained in durable queue snapshots and messages. */
+ sharedTaskAuthor?: SharedTaskAuthor;
/** Host-captured authored text before plugin/reference decoration; omitted from wire projections. */
autoReviewUserText?: string;
/** Host-owned text-only input; retained by queue persistence and retry. */
diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.ts
index 6caded6ba7..0a7763f7b0 100644
--- a/apps/desktop/src/shared/ipc-errors.ts
+++ b/apps/desktop/src/shared/ipc-errors.ts
@@ -26,6 +26,9 @@ export type IpcErrorCode =
| 'SCHEDULER_NOT_READY'
| 'PERMISSION_DENIED'
| 'UNSUPPORTED_CAPABILITY'
+ | 'SHARED_TASK_HOST_LIMIT'
+ | 'SHARED_TASK_JOIN_LIMIT'
+ | 'SHARED_TASK_GUEST_LIMIT'
| 'APP_SHORTCUTS_WRITE_FAILED'
| 'NO_ACTIVE_TURN'
| 'SESSION_RUNNING'
@@ -294,6 +297,9 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>([
'SCHEDULER_NOT_READY',
'PERMISSION_DENIED',
'UNSUPPORTED_CAPABILITY',
+ 'SHARED_TASK_HOST_LIMIT',
+ 'SHARED_TASK_JOIN_LIMIT',
+ 'SHARED_TASK_GUEST_LIMIT',
'APP_SHORTCUTS_WRITE_FAILED',
'NO_ACTIVE_TURN',
'SESSION_RUNNING',
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsx
index f91a24c722..ef258712e4 100644
--- a/apps/mobile/app/devices/index.tsx
+++ b/apps/mobile/app/devices/index.tsx
@@ -31,7 +31,8 @@ import {
type ViewStyle,
} from 'react-native';
import { Text } from '@/components/AppText';
-import { DeviceLinkError, type DeviceView, type PresenceSnapshot } from '@cindy/device-link';
+import { DeviceLinkError, isSharedTaskPeer, type DeviceView, type PresenceSnapshot } from '@cindy/device-link';
+import { useSharedTasks } from '@/device-link/useSharedTasks';
import {
Archive,
Check,
@@ -125,7 +126,7 @@ import {
import { withTransientRemoteRetry } from '@/device-link/remoteRetry';
import { ConnectionRecoveryProgress } from '@/components/ConnectionBanner';
import { ConnectionNoticeOverlay, useDelayedConnectionNotice } from '@/components/ConnectionNoticeOverlay';
-import { resolveConnectionBannerVisibility, resolveConnectionBannerSyncActionVisibility, resolveHomeConnectionFeedback, type HomeConnectionError, type HomeDeviceFailure } from '@/components/connectionBannerVisibility';
+import { resolveConnectionBannerVisibility, resolveConnectionBannerSyncActionVisibility, resolveHomeConnectionFeedback, resolveHomeDeviceDisconnected, type HomeConnectionError, type HomeDeviceFailure } from '@/components/connectionBannerVisibility';
import { QuietSyncIndicator } from '@/components/QuietSyncIndicator';
import { runIndependentSnapshotReads } from '@/device-link/sessionSnapshotSingleFlight';
import { revokedDevicesStore, useRevokedDevices } from '@/device-link/revokedDevicesStore';
@@ -356,6 +357,7 @@ class HomeSyncScopeSupersededError extends Error {
}
export default function HomeScreen() {
+ useSharedTasks();
const screenFocused = useIsFocused();
return (
<RemoteSessionStoreSubscriptionGate enabled={screenFocused}>
@@ -1001,7 +1003,7 @@ function HomeScreenContent() {
const ghostDeviceIds = new Set<string>();
for (const session of remoteSessionStore.getSessions()) {
const shardId = session.deviceLinkDeviceId;
- if (shardId && !knownDeviceIds.has(shardId)) ghostDeviceIds.add(shardId);
+ if (shardId && !isSharedTaskPeer(shardId) && !knownDeviceIds.has(shardId)) ghostDeviceIds.add(shardId);
}
for (const deviceId of ghostDeviceIds) {
invalidateScheduleIndexForDevice(deviceId);
@@ -1847,10 +1849,7 @@ function HomeScreenContent() {
}, [home.deviceFilters, home.selectedDeviceId, initialHomeSettled, selectedDeviceId]);
// 连接层失败原因比请求级 error 更根因:unstable 在 online 时也需保持可见。
const activeConnectionIssue = status !== 'online' || connectionIssue?.kind === 'unstable' ? connectionIssue : null;
- const selectedDeviceDisconnected = status !== 'connecting' && home.deviceFilters.some((item) => item.deviceId !== null
- && (!selectedDeviceId || item.deviceId === selectedDeviceId) && item.sessionCount > 0)
- && !home.deviceFilters.some((item) => item.deviceId !== null
- && (!selectedDeviceId || item.deviceId === selectedDeviceId) && item.available);
+ const selectedDeviceDisconnected = resolveHomeDeviceDisconnected(home.deviceFilters, selectedDeviceId, status === 'connecting');
const showConnectionRow = selectedDeviceDisconnected || resolveConnectionBannerVisibility({
offline: status !== 'online',
connecting: status === 'connecting',
@@ -2867,6 +2866,12 @@ function HomeScreenContent() {
setChromeMenuCloseInstant(true);
setChromeMenuOpen(false);
}}
+ onOpenSharedSession={() => {
+ pendingMenuActionRef.current = null;
+ guardedPush('/shared-session');
+ setChromeMenuCloseInstant(true);
+ setChromeMenuOpen(false);
+ }}
onLogout={() => void logout()}
open={chromeMenuOpen}
user={user}
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index f988fb671d..b28a601548 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -4,10 +4,11 @@ import { getActiveMobileSessionRealm } from '@/config/env';
import { FailedScheduleNotice } from '@/session/FailedScheduleNotice';
import { shouldShowFailedScheduleNotice, type FailedScheduleRunSnapshot } from '@cindy/maker-shared/schedule-model';
import { useRemoteResourceSession } from '@/session/useRemoteResourceSession';
+import { SharedTaskEndedState } from '@/session/SharedTaskEndedState';
import { useSessionResourceCards } from '@/session/useSessionResourceCards';
import { SessionResourceCards } from '@/session/SessionResourceCards';
import { mobileDebugLog } from '@/debug/mobileDebugLog';
-import { isInFlightDeviceLinkError } from '@cindy/device-link';
+import { isInFlightDeviceLinkError, isSharedTaskPeer } from '@cindy/device-link';
import { takeRefinementContextTail, truncateRefinementReply } from '@cindy/voice-input-core';
import {
ArrowDown,
@@ -92,6 +93,8 @@ import { resolveEffectiveConnectionError } from '@/components/connectionBannerVi
import { PaperPlaneIcon } from '@/components/PaperPlaneIcon';
import { useDeviceLink } from '@/device-link/DeviceLinkContext';
import { useRevokedDevices } from '@/device-link/revokedDevicesStore';
+import { useSharedTaskAccess } from '@/device-link/useSharedTaskAccess';
+import { useLeaveSharedTask } from '@/device-link/useLeaveSharedTask';
import { useUnresponsiveDevices } from '@/device-link/unresponsiveDevicesStore';
import {
connectionRecoverySyncRetryDelayMs,
@@ -1322,6 +1325,7 @@ export default function SessionScreen() {
getPendingUploadCount,
} = useMobileLocalAttachments({
attachmentScopeKey: sessionId,
+ deviceId,
getAccessToken: () => auth.getAccessToken(),
getAttachmentCount: () => attachmentsRef.current.length,
onUploaded: (rawAttachment, candidate, localId) => {
@@ -2078,6 +2082,7 @@ export default function SessionScreen() {
setCodexResetRetryKey(null);
}
const isDeviceAccessRevoked = !!deviceId && revokedDevices.has(deviceId);
+ const isSharedTaskAccessRevoked = isDeviceAccessRevoked && isSharedTaskPeer(deviceId);
// 熔断 open:被控电脑「进程活着但不回包」的半死态;relay status 恒 online,必须单独入参。
const isDeviceUnresponsive = !!deviceId && unresponsiveDevices.has(deviceId);
// 熔断已关后残留的 DEVICE_UNRESPONSIVE 错误按陈旧丢弃,且必须一次性解析、
@@ -2236,6 +2241,12 @@ export default function SessionScreen() {
// 回执。把 AppState 作为回执 effect 的重算信号:离开 active 立刻取消未到期的
// 计时,回到 active 重新起满一轮 dwell。
const [appStateActive, setAppStateActive] = useState(AppState.currentState === 'active');
+ useSharedTaskAccess(deviceId, sessionId, appStateActive);
+ const sharedTaskExit = useLeaveSharedTask({
+ deviceId, enabled: settingsOpen && !isSharedTaskAccessRevoked,
+ onLeft: () => { setSettingsOpen(false); router.replace('/devices'); },
+ onError: (message) => { setSettingsOpen(false); setError(message); },
+ });
useEffect(() => {
const subscription = AppState.addEventListener('change', (nextState) => {
setAppStateActive(nextState === 'active');
@@ -2371,12 +2382,12 @@ export default function SessionScreen() {
() => buildSessionOperationLayout({
hasCurrentSession,
hasActivePendingInteraction,
- pendingInteractionBlocksComposer,
+ pendingInteractionBlocksComposer: pendingInteractionBlocksComposer && !isSharedTaskPeer(deviceId),
remoteUnavailableReason: composerRemoteUnavailableReason,
// composer 用 composer-only reason:Lead → editable(可发消息),worker → read-only。
readOnlyReason: composerReadOnlyReason,
}),
- [composerReadOnlyReason, composerRemoteUnavailableReason, hasActivePendingInteraction, hasCurrentSession, pendingInteractionBlocksComposer],
+ [composerReadOnlyReason, composerRemoteUnavailableReason, hasActivePendingInteraction, hasCurrentSession, pendingInteractionBlocksComposer, deviceId],
);
useEffect(() => {
if (!pendingInteractionActiveRequestId) return;
@@ -6782,6 +6793,7 @@ export default function SessionScreen() {
// 权限模式图标钮(2026-07-29 用户裁决,对齐 Codex,与新建页同位同款):
// 只显示档位图标,不带文字;危险档(auto / bypass)只染图标色。
const renderSessionPermissionButton = () => {
+ if (isSharedTaskPeer(deviceId)) return null;
const presentation = permissionPresentation(displayPermissionMode, displayPermissionLabel);
const accent = presentation.accent !== 'neutral'
? permissionAccentColor(presentation.accent, colors)
@@ -6819,7 +6831,7 @@ export default function SessionScreen() {
<ComposerToolbarLeftGroup testID="session.composerToolbarLeft">
{renderComposerAttachmentButton()}
{renderSessionPermissionButton()}
- {!sessionManagedByHost && planModeOn ? (
+ {!isSharedTaskPeer(deviceId) && !sessionManagedByHost && planModeOn ? (
<PlanModeChip
disabled={controlBusy || !canUseRemoteSessionControls}
onExit={() => togglePlanMode(false)}
@@ -8948,6 +8960,7 @@ export default function SessionScreen() {
currentSession={currentSession}
diffCount={diffCount}
isDeviceAccessRevoked={isDeviceAccessRevoked}
+ sharedTaskEnded={isSharedTaskAccessRevoked}
shareSelectionLeadingInset={nativeShellLayout.wideViewport
? Math.max(0, (windowDimensions.width - nativeShellLayout.contentMaxWidth) / 2)
: 0}
@@ -8996,7 +9009,7 @@ export default function SessionScreen() {
|| (connectionError ? t('session.screen.sessionNotSynced') : (deviceName || t('session.screen.conversationFallback')))}
/>
- {showConnectionBanner || showCachedHistoryNotice ? (
+ {!isSharedTaskAccessRevoked && (showConnectionBanner || showCachedHistoryNotice) ? (
<ConnectionBanner
density="compact"
cachedOnly={showCachedHistoryNotice}
@@ -9016,9 +9029,16 @@ export default function SessionScreen() {
) : null}
</View>
</View>
+ {sharedTaskExit.dialog}
{currentSession ? (
<SessionMenuSheet
tagDeviceId={deviceId}
+ onLeaveSharing={() => void sharedTaskExit.leave()}
+ leavingSharing={sharedTaskExit.busy}
+ onOpenSharing={() => {
+ setSettingsOpen(false);
+ router.push({ pathname: '/shared-session', params: { sessionId, deviceId } });
+ }}
providerName={providerAccountLabel}
messageOnly={sessionManagedByHost}
onOpenSearch={() => {
@@ -9142,7 +9162,7 @@ export default function SessionScreen() {
testID="session.contextSheetFileRow"
/>
</ContextSheetGroup>
-{!sessionManagedByHost ? <ContextSheetGroup label={t('session.common.groupMode')}>
+ {!isSharedTaskPeer(deviceId) && !sessionManagedByHost ? <ContextSheetGroup label={t('session.common.groupMode')}>
{planModeSupported ? (
// 点击即切换计划模式并关面板(产品决策,不做开关);已开启时显示 ✓,再点退出。
<ContextSheetRow
@@ -9298,7 +9318,11 @@ export default function SessionScreen() {
) : null}
{composerAnnotations.host}
<View style={styles.sessionMainLayer} testID="session.mainLayer">
- {sessionOperationLayout.composerSlot === 'missing-session' && remoteUnavailableReason ? (
+ {isSharedTaskAccessRevoked ? (
+ <ScrollView contentContainerStyle={{ paddingTop: topOverlayHeight + spacing.lg, paddingHorizontal: spacing.lg }}>
+ <SharedTaskEndedState onRejoin={() => router.replace('/shared-session')} />
+ </ScrollView>
+ ) : sessionOperationLayout.composerSlot === 'missing-session' && remoteUnavailableReason ? (
// 会话行尚未到达时保留状态占位;自动恢复类错误不再提供手动同步入口。
<SessionSyncPlaceholder
loading={loading}
@@ -9356,14 +9380,14 @@ export default function SessionScreen() {
loadEarlierProgressKey={oldestLoadedMessageCursor}
onCopyMessageLink={copyMessageLink}
onAddMessageToComposer={canUseComposer ? addMessageToComposer : undefined}
- onDeleteMessage={collaborationReadOnlyReason ? undefined : deleteMessage}
- onForkMessage={collaborationReadOnlyReason ? undefined : forkAtMessage}
+ onDeleteMessage={collaborationReadOnlyReason || isSharedTaskPeer(deviceId) ? undefined : deleteMessage}
+ onForkMessage={collaborationReadOnlyReason || isSharedTaskPeer(deviceId) ? undefined : forkAtMessage}
onLoadEarlier={loadEarlierMessages}
onLoadToolInput={loadToolInput}
onOpenForkOrigin={forkOrigin ? openForkOrigin : undefined}
onBlockingOverlayChange={handleMessageBlockingOverlayChange}
onOpenSessionLink={openSessionLink}
- onPreviewRewind={collaborationReadOnlyReason ? undefined : previewRewindAtMessage}
+ onPreviewRewind={collaborationReadOnlyReason || isSharedTaskPeer(deviceId) ? undefined : previewRewindAtMessage}
onEnterShareSelection={enterShareSelection}
onVisibleShareableMessageIdsReaderChange={handleVisibleShareableMessageIdsReaderChange}
shareSelectionActive={shareSelectionActive}
@@ -9431,14 +9455,14 @@ export default function SessionScreen() {
)}
</View>
- {nativeComposerFrameAvailable && sessionOperationLayout.composerSlot === 'editable' && !shareSelectionActive ? (
+ {!isSharedTaskAccessRevoked && nativeComposerFrameAvailable && sessionOperationLayout.composerSlot === 'editable' && !shareSelectionActive ? (
<SessionHeaderNativeBlur
edge="bottom"
height={bottomOverlayHeight + spacing.xxl}
inset={nativeShellLayout.keyboardBottomInset}
/>
) : null}
- <View
+ {!isSharedTaskAccessRevoked && <View
ref={bottomOverlayRef}
onLayout={handleBottomOverlayLayout}
pointerEvents="box-none"
@@ -9703,6 +9727,7 @@ export default function SessionScreen() {
) : null}
</View>
</View>
+ }
</ComposerKeyboardAvoidingView>
{shareSelectionActive && selectedShareMessages.length > 0 ? (
<ConversationShareSvg
@@ -9739,6 +9764,7 @@ function SessionHeaderBar({
currentSession,
diffCount,
isDeviceAccessRevoked,
+ sharedTaskEnded = false,
shareSelectionLeadingInset,
shareSelectAllNode,
syncing,
@@ -9764,6 +9790,7 @@ function SessionHeaderBar({
currentSession: RemoteSession | null;
diffCount: number;
isDeviceAccessRevoked: boolean;
+ sharedTaskEnded?: boolean;
/** 宽屏下与消息内容列共用的左侧 inset。 */
shareSelectionLeadingInset: number;
/** 分享选择模式下替换头部动作区。 */
@@ -9820,7 +9847,7 @@ function SessionHeaderBar({
settings: onOpenSettings,
usage: onOpenUsage,
} satisfies Record<SessionActionStripActionId, () => void>;
- const notice = compactSessionHeaderNotice({
+ const notice = sharedTaskEnded ? null : compactSessionHeaderNotice({
isDeviceAccessRevoked,
pendingCount,
queuePaused,
@@ -9870,7 +9897,7 @@ function SessionHeaderBar({
)}
{nativeHeader ? <SessionHeaderNativeTitle
- title={title}
+ title={sharedTaskEnded ? t('sharedTask.ended') : title}
tags={isDeviceAccessRevoked ? undefined : currentSession?.tags}
onTagsPress={onOpenSettings}
pinned={!messageOnly && !!currentSession?.pinnedAt}
@@ -9888,7 +9915,7 @@ function SessionHeaderBar({
/>
) : null}
<Text numberOfLines={1} style={styles.sessionHeaderTitle} testID="session.title">
- {title}
+ {sharedTaskEnded ? t('sharedTask.ended') : title}
</Text>
<TaskTagDots
tags={isDeviceAccessRevoked ? undefined : currentSession?.tags}
@@ -9905,7 +9932,7 @@ function SessionHeaderBar({
</View>
)}
- {nativeHeader ? (
+ {sharedTaskEnded ? null : nativeHeader ? (
<SessionHeaderNativeActions
available={!!currentSession}
desktopLabel={t('remoteDesktop.title')}
diff --git a/apps/mobile/app/shared-session.tsx b/apps/mobile/app/shared-session.tsx
new file mode 100644
index 0000000000..7c0b50593e
--- /dev/null
+++ b/apps/mobile/app/shared-session.tsx
@@ -0,0 +1,308 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { AppState, Keyboard, StyleSheet, View } from 'react-native';
+import { useFocusEffect, useLocalSearchParams, useRouter } from 'expo-router';
+import { useTranslation } from 'react-i18next';
+import { Check, Clock, FileText, Laptop, Link, Users } from 'lucide-react-native';
+import { sharedTaskHostPeer, parseSharedTaskPeer, SHARED_TASK_HOST_CHANNEL,
+ type SharedTaskHostCommand, type SharedTaskHostState, type SharedTaskListItem } from '@cindy/device-link';
+import { useAuth } from '@/auth/AuthContext';
+import { goBackGuarded } from '@/utils/backGuard';
+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
+import { useDeviceLink } from '@/device-link/DeviceLinkContext';
+import { useSharedTaskApi } from '@/device-link/useSharedTaskApi';
+import { sharedTaskErrorKey } from '@/device-link/sharedTaskCompatibility';
+import { isSharedTaskGone } from '@/device-link/sharedTaskAccessWatch';
+import { markDeviceAccessRevoked } from '@/device-link/accessRevoked';
+import { Text, TextInput } from '@/components/AppText';
+import { MainWindowRowButton } from '@/components/MobilePrimitives';
+import { SharedTaskAction, SharedTaskScreen } from '@/session/SharedTaskScreen';
+import { useSharedTaskConfirmation } from '@/session/useSharedTaskConfirmation';
+import { SharedTaskEndedState } from '@/session/SharedTaskEndedState';
+import { remoteSessionStore } from '@/session/remoteSessionStore';
+import { writeClipboardText } from '@/session/messageActions';
+import type { RemoteSession } from '@/session/types';
+import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';
+import { fontWeight, iconSize, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';
+
+/** Plan B management only; conversation/input continue through the ordinary remote task. */
+export default function SharedSessionScreen() {
+ const { sessionId, deviceId } = useLocalSearchParams<{ sessionId?: string; deviceId?: string }>();
+ const router = useRouter();
+ const { t } = useTranslation();
+ const { isAuthenticated, accountGeneration } = useAuth();
+ const api = useSharedTaskApi();
+ const confirmation = useSharedTaskConfirmation();
+ const link = useDeviceLink();
+ const { colors } = useTheme();
+ const styles = useThemedStyles(makeStyles);
+ const [invitation, setInvitation] = useState('');
+ const [name, setName] = useState('');
+ const [state, setState] = useState<SharedTaskHostState | null>(null);
+ const [tasks, setTasks] = useState<SharedTaskListItem[]>([]);
+ const [owned, setOwned] = useState<SharedTaskListItem[]>([]);
+ const [guestCounts, setGuestCounts] = useState<Record<string, number>>({});
+ const [deviceNames, setDeviceNames] = useState<Record<string, string>>({});
+ const [tab, setTab] = useState<'current' | 'owned'>('current');
+ const [joinedId, setJoinedId] = useState<string>();
+ const [ended, setEnded] = useState(false);
+ const [notice, setNotice] = useState('');
+ const [loadError, setLoadError] = useState('');
+ const [busy, setBusy] = useState(false);
+ const confirmationPending = useRef<object | null>(null);
+ const pending = useRef(false);
+ const mounted = useRef(true);
+ const epoch = useRef(0);
+ const peer = deviceId ? parseSharedTaskPeer(deviceId) : null;
+ const guestId = peer?.role === 'host' ? peer.sharedTaskId : joinedId;
+ const hostContext = !!sessionId && !!deviceId && !guestId;
+ const host = useCallback((command: SharedTaskHostCommand) => link.invoke(deviceId!, SHARED_TASK_HOST_CHANNEL, [command]), [deviceId, link.invoke]);
+ const endAccess = useCallback(() => {
+ confirmationPending.current = null;
+ setEnded(true); setState(null); setNotice('');
+ if (guestId) {
+ const target = sharedTaskHostPeer(guestId);
+ markDeviceAccessRevoked(target);
+ link.closeLink(target);
+ remoteSessionStore.removeDevice(target);
+ }
+ }, [guestId, link.closeLink]);
+ const load = useCallback(async (visible: () => boolean = () => true) => {
+ const captured = epoch.current;
+ const owner = getMobileAuthOwner();
+ const current = () => visible() && mounted.current && captured === epoch.current && isMobileAuthOwnerCurrent(owner);
+ if (!isAuthenticated || link.sharedTaskAvailable !== true || ended) return;
+ if (hostContext && tab === 'owned') {
+ const value = await api.list();
+ if (!current()) return;
+ const mine = value.filter((task) => task.ownerAccountId === owner.accountId);
+ setOwned(mine);
+ const counts: Record<string, number> = {};
+ for (const task of mine) {
+ if (!current()) return;
+ const detail = await api.get(task.sharedTaskId).catch(() => null);
+ if (detail) counts[task.sharedTaskId] = detail.memberLabels.length;
+ }
+ if (current()) setGuestCounts(counts);
+ // Device names are account-owned display data; a failed name lookup does not hide tasks.
+ const devices = await link.readDeviceList().catch(() => null);
+ if (current() && devices) setDeviceNames(Object.fromEntries(devices.devices.map((device) => [device.deviceId, device.name])));
+ } else if (guestId || hostContext) {
+ try {
+ const value = guestId ? { available: true, detail: await api.get(guestId) }
+ : await host({ action: 'state', sessionId: sessionId! }) as SharedTaskHostState;
+ if (!current()) return;
+ if (guestId && value.detail?.status === 'closed') endAccess();
+ else setState(value);
+ if (hostContext) {
+ const all = await api.list().catch(() => null);
+ if (current() && all) setOwned(all.filter((task) => task.ownerAccountId === owner.accountId));
+ }
+ } catch (error) {
+ if (current() && guestId && isSharedTaskGone(error)) endAccess();
+ else throw error;
+ }
+ } else {
+ const value = await api.list();
+ if (current()) setTasks(value.filter((task) => task.ownerAccountId !== owner.accountId));
+ }
+ }, [api, ended, endAccess, guestId, host, hostContext, isAuthenticated, link.readDeviceList, link.sharedTaskAvailable, sessionId, tab]);
+ useEffect(() => {
+ mounted.current = true;
+ epoch.current++; pending.current = false; setBusy(false);
+ setState(null); setTasks([]); setOwned([]); setGuestCounts({}); setJoinedId(undefined); setEnded(false);
+ setInvitation(''); setName(''); setNotice(''); setLoadError(''); setTab('current'); confirmationPending.current = null;
+ return () => { mounted.current = false; epoch.current++; };
+ }, [accountGeneration, deviceId, sessionId]);
+ useFocusEffect(useCallback(() => {
+ return () => { confirmationPending.current = null; };
+ }, []));
+ useFocusEffect(useCallback(() => {
+ let disposed = false;
+ let polling = false;
+ const poll = async () => {
+ if (disposed || polling || pending.current || AppState.currentState !== 'active') return;
+ polling = true;
+ const owner = getMobileAuthOwner();
+ try { await load(() => !disposed); if (!disposed && isMobileAuthOwnerCurrent(owner)) setLoadError(''); }
+ catch (error) {
+ if (!disposed && isMobileAuthOwnerCurrent(owner)) {
+ const key = sharedTaskErrorKey(error);
+ if (key === 'sharedTask.upgrade' && sessionId) setState({ available: false, detail: null });
+ else setLoadError(t(key));
+ }
+ } finally { polling = false; }
+ };
+ void poll();
+ const timer = setInterval(() => void poll(), 5_000);
+ return () => { disposed = true; clearInterval(timer); };
+ }, [accountGeneration, load, sessionId, t]));
+ const run = async (work: (current: () => boolean) => Promise<void>, reload = true) => {
+ if (pending.current) return;
+ pending.current = true; setBusy(true); setNotice('');
+ const owner = getMobileAuthOwner();
+ // A read already in flight must not restore state from before this action.
+ const captured = ++epoch.current;
+ const current = () => mounted.current && captured === epoch.current && isMobileAuthOwnerCurrent(owner);
+ try {
+ if (link.sharedTaskAvailable !== true) { setNotice(t(link.sharedTaskAvailable === false ? 'sharedTask.upgrade' : 'sharedTask.retry')); return; }
+ await work(current);
+ if (reload && current()) await load();
+ } catch (error) {
+ if (current()) {
+ if (guestId && isSharedTaskGone(error)) endAccess();
+ else setNotice(t(sharedTaskErrorKey(error)));
+ }
+ } finally { if (captured === epoch.current) { pending.current = false; setBusy(false); } }
+ };
+ const confirm = (title: string, body: string, cancel: string, action: string, work: (current: () => boolean) => Promise<void>, reload = true, extra?: { items?: string[]; note?: string }) => {
+ if (confirmationPending.current || pending.current) return;
+ const owner = getMobileAuthOwner();
+ const captured = epoch.current;
+ const request = {};
+ confirmationPending.current = request;
+ Keyboard.dismiss();
+ void confirmation.confirm({
+ title, message: [body, extra?.items?.join('\n'), extra?.note].filter(Boolean).join('\n\n'),
+ cancelLabel: cancel, confirmLabel: action, destructive: true, cancelable: true,
+ }).then((accepted) => {
+ if (confirmationPending.current !== request) return;
+ confirmationPending.current = null;
+ if (accepted && mounted.current && captured === epoch.current && isMobileAuthOwnerCurrent(owner)) void run(work, reload);
+ });
+ };
+ const openTask = async (id: string, current: () => boolean) => {
+ const detail = await api.get(id);
+ if (!current()) return;
+ if (detail.status !== 'active') { endAccess(); return; }
+ const target = sharedTaskHostPeer(id);
+ await link.openLink(target);
+ if (!current()) return;
+ const task = await link.invoke<RemoteSession>(target, 'local-db:sessions:get', [detail.sessionId]);
+ if (!current() || task.id !== detail.sessionId) return;
+ remoteSessionStore.setDeviceSessions(target, detail.title, [task]);
+ router.replace({ pathname: '/sessions/[sessionId]', params: { sessionId: detail.sessionId, deviceId: target, deviceName: detail.title } });
+ };
+ const detail = state?.detail?.status === 'active' ? state.detail : null;
+ const task = remoteSessionStore.getSessions().find((task) => task.id === sessionId && task.deviceLinkDeviceId === deviceId);
+ const title = detail?.title ?? task?.title ?? t('sharedTask.title');
+ const deviceName = (id: string) => deviceNames[id] ?? remoteSessionStore.getSessions().find((task) => task.deviceLinkDeviceId === id)?.deviceLinkDeviceName ?? t('sharedTask.hostDevice');
+ const closeTasks = (items: SharedTaskListItem[]) => confirm(
+ t('sharedTask.closeAllTitle'),
+ t('sharedTask.closeAllBody'),
+ t('sharedTask.closeAllKeep'), t('sharedTask.closeAllAction', { count: items.length }), async (current) => {
+ const results = await Promise.allSettled(items.map((item) => api.close(item.sharedTaskId)));
+ if (!current()) return;
+ const closed = new Set(items.filter((_, index) => results[index].status === 'fulfilled').map((item) => item.sharedTaskId));
+ setOwned((value) => value.filter((item) => !closed.has(item.sharedTaskId)));
+ const failed = results.length - closed.size;
+ setNotice(t(failed ? 'sharedTask.closeFailedToast' : 'sharedTask.closedToast', { count: failed || closed.size }));
+ }, true, { items: items.map((item) => item.title + ' · ' + deviceName(item.hostDeviceId)), note: t('sharedTask.closeAllScopeNote') });
+ const leave = () => confirm(t('sharedTask.leaveTitle'), t('sharedTask.leaveBody'), t('sharedTask.leaveKeep'), t('sharedTask.leave'), async (current) => {
+ await api.leave(guestId!);
+ if (!current()) return;
+ const target = sharedTaskHostPeer(guestId!);
+ link.closeLink(target); remoteSessionStore.removeDevice(target); router.replace('/devices');
+ }, false);
+ const taskCard = <View style={styles.taskRow}><FileText size={iconSize.md} color={colors.textTertiary} /><View style={styles.grow}><Text style={styles.taskTitle}>{title}</Text><Text style={styles.metadata}>{task?.deviceLinkDeviceName ?? t('sharedTask.runsOnHostDevice')}</Text></View></View>;
+ return <SharedTaskScreen
+ title={t(ended ? 'sharedTask.ended' : hostContext && tab === 'owned' ? 'sharedTask.ownedTitle' : hostContext || guestId ? 'sharedTask.title' : 'sharedTask.join')}
+ onClose={() => goBackGuarded(router, '/devices')}>
+ {confirmation.dialog}
+ {!isAuthenticated ? <Text style={styles.intro}>{t('sharedTask.login')}</Text> : ended ? <SharedTaskEndedState onRejoin={() => {
+ setJoinedId(undefined); setEnded(false); setState(null); setNotice(''); setLoadError('');
+ router.replace('/shared-session');
+ }} /> : link.sharedTaskAvailable !== true ? <Text style={styles.intro}>{t(link.sharedTaskAvailable === false ? 'sharedTask.upgrade' : 'sharedTask.retry')}</Text> : <>
+ {hostContext && <View style={styles.tabs}>
+ <MainWindowRowButton accessibilityLabel={t('sharedTask.tabCurrent')} selected={tab === 'current'} style={[styles.tab, tab === 'current' && styles.tabSelected]} onPress={() => { setNotice(''); setTab('current'); }}><Text style={styles.small}>{t('sharedTask.tabCurrent')}</Text></MainWindowRowButton>
+ <MainWindowRowButton accessibilityLabel={t('sharedTask.tabOwned')} selected={tab === 'owned'} style={[styles.tab, tab === 'owned' && styles.tabSelected]} onPress={() => { setNotice(''); setTab('owned'); }}><Text style={styles.small}>{t('sharedTask.tabOwned')}</Text><View style={styles.badge}><Text style={styles.metadata}>{owned.length}</Text></View></MainWindowRowButton>
+ </View>}
+ {!!notice && <Text accessibilityRole="alert" style={styles.noticeText}>{notice}</Text>}
+ {!!loadError && <Text accessibilityRole="alert" style={styles.noticeText}>{loadError}</Text>}
+ {hostContext && tab === 'owned' ? owned.length === 0 ? <View style={styles.empty}>
+ <View style={styles.largeIcon}><Check size={iconSize.md} color={colors.textPrimary} /></View>
+ <Text style={styles.emptyTitle}>{t('sharedTask.ownedEmptyTitle')}</Text><Text style={styles.emptyCopy}>{t('sharedTask.ownedEmptyHint')}</Text>
+ <SharedTaskAction action={{ label: t('sharedTask.shareCurrent'), onPress: () => setTab('current') }} />
+ </View> : <>
+ <Text style={styles.intro}>{t('sharedTask.ownedIntro', { count: owned.length })}</Text>
+ {owned.map((item) => <View key={item.sharedTaskId} style={styles.taskRow}><Users size={iconSize.md} color={colors.textTertiary} /><View style={styles.grow}><Text style={styles.taskTitle}>{item.title}</Text><Text style={styles.metadata}>{deviceName(item.hostDeviceId)}{guestCounts[item.sharedTaskId] !== undefined ? ' · ' + t('sharedTask.guestCount', { count: guestCounts[item.sharedTaskId] }) : ''}</Text></View>
+ {item.sessionId === sessionId && item.hostDeviceId === deviceId ? <SharedTaskAction compact action={{ label: t('sharedTask.manage'), onPress: () => setTab('current') }} /> : <View style={styles.badge}><Text style={styles.metadata}>{t('sharedTask.sharingBadge')}</Text></View>}
+ </View>)}
+ <View style={styles.rule} /><Text style={styles.smallMuted}>{t('sharedTask.closeAllNote')}</Text>
+ <View style={styles.footer}><SharedTaskAction grow action={{ label: t('sharedTask.closeAll', { count: owned.length }), tone: 'danger', disabled: busy, onPress: () => closeTasks([...owned]) }} /></View>
+ </> : guestId ? <>
+ <View style={styles.empty}>
+ <View style={styles.largeIcon}><Check size={iconSize.md} color={colors.textPrimary} /></View>
+ <Text style={styles.emptyTitle}>{detail ? t('sharedTask.joinedTitle', { title: detail.title }) : t('sharedTask.joined')}</Text>
+ <Text style={styles.emptyCopy}>{t('sharedTask.joinedBody')}</Text>
+ <SharedTaskAction action={{ label: t('sharedTask.enterTask'), tone: 'primary', busy, onPress: () => void run((current) => openTask(guestId, current), false) }} />
+ </View>
+ <View style={styles.rule} /><SharedTaskAction action={{ label: t('sharedTask.leave'), tone: 'danger', disabled: busy, onPress: leave }} />
+ </> : hostContext ? !state ? <Text style={styles.intro}>{t('shared.syncing')}</Text> : !state.available ? <Text style={styles.intro}>{t('sharedTask.upgrade')}</Text> : !detail ? <>
+ <Text style={styles.intro}>{t('sharedTask.startIntro')}</Text>{taskCard}
+ <View style={styles.noticeBox}><Users size={iconSize.sm} color={colors.textTertiary} /><Text style={[styles.smallMuted, styles.grow]}>{t('sharedTask.inviteNotice')}</Text></View>
+ <Text style={styles.smallMuted}>{t('sharedTask.offlineAutoClose')}</Text>
+ <View style={styles.footer}><SharedTaskAction grow action={{ label: t('sharedTask.open'), tone: 'primary', busy, onPress: () => void run(async () => { await host({ action: 'open', sessionId: sessionId! }); }) }} /></View>
+ </> : <>
+ <Text style={styles.caption}>{title}</Text>
+ <View style={styles.copyBox}><Link size={iconSize.md} color={colors.textTertiary} /><View style={styles.grow}><Text style={styles.smallMuted}>{t('sharedTask.inviteBoxTitle')}</Text><Text style={styles.smallMuted}>{t('sharedTask.inviteBoxHint')}</Text></View>
+ <SharedTaskAction compact action={{ label: t('sharedTask.invite'), tone: 'primary', disabled: busy, onPress: () => void run(async (current) => {
+ const result = await host({ action: 'invite', sharedTaskId: detail.sharedTaskId }) as { invitation: string };
+ if (!current()) return;
+ try { await writeClipboardText(result.invitation); if (current()) setNotice(t('sharedTask.invitationCopied')); }
+ catch { if (current()) setNotice(t('sharedTask.invitationCopyFailed')); }
+ }, false) }} />
+ </View>
+ <Text style={styles.peopleTitle}>{t('sharedTask.membersWithLimit', { count: detail.memberLabels.length + 1 })}</Text>
+ <View style={styles.person}><View style={styles.avatar}><Laptop size={iconSize.sm} color={colors.textTertiary} /></View><View style={styles.grow}><Text style={styles.personName}>{t('sharedTask.me')}</Text><Text style={styles.metadata}>{task?.deviceLinkDeviceName ?? t('sharedTask.hostDevice')}</Text></View><Text style={styles.smallMuted}>{t('sharedTask.roleHost')}</Text></View>
+ {detail.memberLabels.map((member) => <View key={member.memberId} style={styles.person}><View style={styles.avatar}><Text style={styles.metadata}>{Array.from(member.displayName)[0]}</Text></View><View style={styles.grow}><Text style={styles.personName}>{member.displayName}</Text><Text style={styles.metadata}>{t('sharedTask.roleGuest')}</Text></View>
+ <SharedTaskAction compact action={{ label: t('sharedTask.removeShort'), tone: 'danger', accessibilityLabel: t('sharedTask.removeNamedTitle', { name: member.displayName }), disabled: busy, onPress: () => confirm(t('sharedTask.removeNamedTitle', { name: member.displayName }), t('sharedTask.removeBody'), t('sharedTask.removeKeep'), t('sharedTask.remove'), async () => { await host({ action: 'remove', sharedTaskId: detail.sharedTaskId, memberId: member.memberId }); }) }} />
+ </View>)}
+ <View style={styles.noticeBox}><Clock size={iconSize.sm} color={colors.textTertiary} /><Text style={[styles.smallMuted, styles.grow]}>{t('sharedTask.remoteHostOfflineNote')}</Text></View>
+ <View style={styles.footer}><SharedTaskAction grow action={{ label: t('sharedTask.closeCurrent'), tone: 'danger', disabled: busy, onPress: () => confirm(t('sharedTask.closeOneTitle'), t('sharedTask.closeOneBody'), t('sharedTask.closeAllKeep'), t('sharedTask.close'), async () => { await host({ action: 'close', sharedTaskId: detail.sharedTaskId }); }) }} /></View>
+ </> : <>
+ <Text style={styles.intro}>{t('sharedTask.joinIntro')}</Text>
+ <View style={styles.field}><Text style={styles.label}>{t('sharedTask.invitation')}</Text><TextInput accessibilityLabel={t('sharedTask.invitation')} placeholder={t('sharedTask.invitationPlaceholder')} placeholderTextColor={colors.textTertiary} style={[styles.input, styles.invitation]} value={invitation} onChangeText={setInvitation} multiline textAlignVertical="top" autoCapitalize="none" autoCorrect={false} editable={!busy} /></View>
+ <View style={styles.field}><Text style={styles.label}>{t('sharedTask.joinNickname')}</Text><TextInput accessibilityLabel={t('sharedTask.joinNickname')} placeholder={t('sharedTask.nicknamePlaceholder')} placeholderTextColor={colors.textTertiary} style={styles.input} value={name} onChangeText={setName} maxLength={32} editable={!busy} /></View>
+ <View style={styles.noticeBox}><Users size={iconSize.sm} color={colors.textTertiary} /><Text style={[styles.smallMuted, styles.grow]}>{t('sharedTask.joinNotice')}</Text></View>
+ <View style={styles.footer}><SharedTaskAction grow action={{ label: t('sharedTask.join'), tone: 'primary', busy, disabled: !invitation.trim() || !name.trim(), onPress: () => void run(async (current) => {
+ if (!/^[A-Za-z0-9_-]{43}$/.test(invitation.trim()) || name.trim().length > 32) { setNotice(t('sharedTask.invalid')); return; }
+ const joined = await api.join(invitation.trim(), name.trim());
+ if (!current()) return;
+ Keyboard.dismiss(); setInvitation(''); setJoinedId(joined.sharedTaskId);
+ }, false) }} /></View>
+ {tasks.map((task) => <MainWindowRowButton key={task.sharedTaskId} accessibilityLabel={task.title} disabled={busy} onPress={() => { setNotice(''); setJoinedId(task.sharedTaskId); }}><Text style={styles.taskTitle}>{task.title}</Text></MainWindowRowButton>)}
+ </>}
+ </>}
+ </SharedTaskScreen>;
+}
+const makeStyles = (colors: ThemeColors) => StyleSheet.create({
+ intro: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.listBody, marginBottom: spacing.lg },
+ small: { color: colors.textPrimary, fontSize: typeScale.caption, lineHeight: lineHeight.caption },
+ smallMuted: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption },
+ taskTitle: { color: colors.textPrimary, fontSize: typeScale.footnote, lineHeight: lineHeight.listBody, fontWeight: fontWeight.medium },
+ metadata: { color: colors.textTertiary, fontSize: typeScale.micro, lineHeight: lineHeight.micro },
+ caption: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, marginBottom: spacing.sm },
+ noticeText: { color: colors.errorText, fontSize: typeScale.caption, lineHeight: lineHeight.caption, marginBottom: spacing.md },
+ taskRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.md, borderColor: colors.border, borderWidth: StyleSheet.hairlineWidth, borderRadius: radius.control, padding: spacing.md, marginVertical: spacing.sm },
+ copyBox: { flexDirection: 'row', alignItems: 'center', gap: spacing.md, borderColor: colors.border, borderWidth: StyleSheet.hairlineWidth, borderRadius: radius.control, padding: spacing.md, marginVertical: spacing.lg },
+ noticeBox: { flexDirection: 'row', alignItems: 'flex-start', gap: spacing.sm, backgroundColor: colors.surfaceChip, borderRadius: radius.control, padding: spacing.md, marginVertical: spacing.lg },
+ tabs: { flexDirection: 'row', gap: spacing.sm, borderBottomWidth: StyleSheet.hairlineWidth, borderColor: colors.border, marginHorizontal: -spacing.lg, paddingHorizontal: spacing.lg, paddingBottom: spacing.md, marginBottom: spacing.lg },
+ tab: { flex: 1, minHeight: 44, borderBottomWidth: 0, borderRadius: radius.pill, justifyContent: 'center', gap: spacing.sm, paddingHorizontal: spacing.md, paddingVertical: spacing.sm },
+ tabSelected: { backgroundColor: colors.surfaceChip },
+ badge: { borderRadius: radius.pill, backgroundColor: colors.surfaceChip, paddingHorizontal: spacing.sm, paddingVertical: spacing.xs },
+ grow: { flex: 1 },
+ field: { gap: spacing.xs, marginBottom: spacing.lg },
+ label: { color: colors.textPrimary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, fontWeight: fontWeight.medium },
+ input: { minHeight: 44, borderWidth: StyleSheet.hairlineWidth, borderColor: colors.border, borderRadius: radius.pill, paddingHorizontal: spacing.md, paddingVertical: spacing.sm, color: colors.textPrimary, backgroundColor: colors.surface, fontSize: typeScale.listBody, lineHeight: lineHeight.listBody },
+ invitation: { minHeight: 82, borderRadius: radius.control },
+ person: { flexDirection: 'row', alignItems: 'center', gap: spacing.md, minHeight: 48, paddingVertical: spacing.sm },
+ personName: { color: colors.textPrimary, fontSize: typeScale.footnote, lineHeight: lineHeight.listBody, fontWeight: fontWeight.medium },
+ peopleTitle: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, marginTop: spacing.lg, marginBottom: spacing.xs },
+ avatar: { width: 28, height: 28, borderRadius: radius.pill, borderWidth: StyleSheet.hairlineWidth, borderColor: colors.border, backgroundColor: colors.surfaceChip, alignItems: 'center', justifyContent: 'center' },
+ empty: { alignItems: 'center', paddingVertical: spacing.xl, paddingHorizontal: spacing.xs },
+ largeIcon: { width: 44, height: 44, borderRadius: radius.pill, borderWidth: StyleSheet.hairlineWidth, borderColor: colors.border, alignItems: 'center', justifyContent: 'center', marginBottom: spacing.lg },
+ emptyTitle: { color: colors.textPrimary, fontSize: typeScale.listBody, lineHeight: lineHeight.listBody, fontWeight: fontWeight.medium, textAlign: 'center' },
+ emptyCopy: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, textAlign: 'center', maxWidth: 280, marginTop: spacing.sm, marginBottom: spacing.lg },
+ rule: { height: StyleSheet.hairlineWidth, backgroundColor: colors.border, marginVertical: spacing.lg },
+ footer: { flexDirection: 'row', gap: spacing.sm, marginTop: spacing.lg },
+});
diff --git a/apps/mobile/metro.config.js b/apps/mobile/metro.config.js
index c543a10992..6282872988 100644
--- a/apps/mobile/metro.config.js
+++ b/apps/mobile/metro.config.js
@@ -21,6 +21,7 @@ const sharedArrayBufferPolyfill = path.join(__dirname, 'src/polyfills/sharedArra
const workspaceTsSourcePackages = [
'auth-client',
'device-link',
+ 'device-link-protocol',
'maker-shared',
'model-providers',
];
diff --git a/apps/mobile/src/__tests__/SessionMenuContextEntry.test.tsx b/apps/mobile/src/__tests__/SessionMenuContextEntry.test.tsx
index 5fee64c9f3..ae7a29d99f 100644
--- a/apps/mobile/src/__tests__/SessionMenuContextEntry.test.tsx
+++ b/apps/mobile/src/__tests__/SessionMenuContextEntry.test.tsx
@@ -8,6 +8,7 @@ import {
type SessionMenuSheetProps,
} from "@/session/SessionMenuSheet";
import { i18n } from "@/i18n";
+import { sharedTaskHostPeer } from '@cindy/device-link';
vi.mock("react-native", async () => {
const { createElement } = await import("react");
@@ -54,6 +55,7 @@ vi.mock("lucide-react-native", () =>
"Folder",
"GitBranch",
"Link2",
+ "LogOut",
"Monitor",
"Pencil",
"Pin",
@@ -106,6 +108,8 @@ it("reopening the primary menu after info does not initialize an engine, but ent
onContextError: vi.fn(),
onRefreshAccountUsage: vi.fn(),
onOpenSearch: vi.fn(),
+ onOpenSharing: vi.fn(),
+ onLeaveSharing: vi.fn(),
session: {
id: "a",
model: "custom",
@@ -136,6 +140,16 @@ it("reopening the primary menu after info does not initialize an engine, but ent
expect(search).not.toBeNull();
await act(async () => (search as HTMLElement).click());
expect(props.onOpenSearch).toHaveBeenCalledOnce();
+ const sharing = host.querySelector('[data-testid="session.sharingButton"]');
+ expect(sharing?.textContent).toBe('共享任务');
+ await act(async () => root.render(<SessionMenuSheet {...props} initialView="menu" session={{ ...props.session, deviceLinkDeviceId: sharedTaskHostPeer('shared') }} />));
+ expect(host.querySelector('[data-testid="session.sharingButton"]')).toBeNull();
+ const leave = host.querySelector('[data-testid="session.leaveSharingButton"]');
+ expect(leave?.textContent).toBe('退出共享任务');
+ await act(async () => (leave as HTMLElement).click());
+ expect(props.onLeaveSharing).toHaveBeenCalledOnce();
+ expect(props.onOpenSharing).not.toHaveBeenCalled();
+ await act(async () => root.render(<SessionMenuSheet {...props} initialView="menu" />));
const summary = host.querySelector('[data-testid="session.menuUsageRow"]');
expect(summary).not.toBeNull();
await act(async () => (summary as HTMLElement).click());
diff --git a/apps/mobile/src/__tests__/accessRevoked.test.ts b/apps/mobile/src/__tests__/accessRevoked.test.ts
index 7798a61eca..2b9596299e 100644
--- a/apps/mobile/src/__tests__/accessRevoked.test.ts
+++ b/apps/mobile/src/__tests__/accessRevoked.test.ts
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { DeviceLinkError, PROTOCOL_VERSION, type Envelope } from '@cindy/device-link';
import {
applyAccessRevokedFrame,
+ markDeviceAccessRevoked,
isAccessRevokedError,
withAccessRevokedHandling,
} from '@/device-link/accessRevoked';
@@ -89,6 +90,20 @@ describe('mobile device-link access revocation', () => {
await expect(withAccessRevokedHandling('dev-1', vi.fn(async () => 'ok'))).resolves.toBe('ok');
expect(revokedDevicesStore.has('dev-1')).toBe(false);
});
+
+ it.each([false, true])('late success cannot clear a newer revocation (initially revoked: %s)', async initiallyRevoked => {
+ if (initiallyRevoked) markDeviceAccessRevoked('dev-1');
+ let resolve!: (value: string) => void;
+ const result = withAccessRevokedHandling('dev-1', () => new Promise<string>(done => { resolve = done; }));
+ markDeviceAccessRevoked('dev-1');
+ resolve('old success');
+ await result;
+ expect(revokedDevicesStore.has('dev-1')).toBe(true);
+ await withAccessRevokedHandling('dev-2', async () => 'unaffected');
+ expect(revokedDevicesStore.has('dev-1')).toBe(true);
+ await withAccessRevokedHandling('dev-1', async () => 'new authorization');
+ expect(revokedDevicesStore.has('dev-1')).toBe(false);
+ });
});
describe('撤权与「设备无响应」熔断的竞态(review P1)', () => {
diff --git a/apps/mobile/src/__tests__/composerDraftSource.test.tsx b/apps/mobile/src/__tests__/composerDraftSource.test.tsx
index c78cdf679d..69d1b37dda 100644
--- a/apps/mobile/src/__tests__/composerDraftSource.test.tsx
+++ b/apps/mobile/src/__tests__/composerDraftSource.test.tsx
@@ -1,13 +1,14 @@
// @vitest-environment jsdom
import { act, createElement, useSyncExternalStore } from 'react';
import { createRoot, type Root } from 'react-dom/client';
-import { afterEach, expect, it } from 'vitest';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { createComposerDraftSource, useComposerVoiceDraftWriter, type ComposerDraftSource } from '@/session/composerDraftSource';
import { textComposerDocument } from '@/session/composerDocument';
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
let root: Root | undefined;
-afterEach(() => { act(() => root?.unmount()); root = undefined; });
+beforeEach(() => { vi.useFakeTimers(); });
+afterEach(() => { act(() => root?.unmount()); root = undefined; vi.useRealTimers(); });
it('typing and streamed dictation update subscribers without rendering the task or message list', () => {
const source = createComposerDraftSource(textComposerDocument(''));
@@ -27,7 +28,10 @@ it('typing and streamed dictation update subscribers without rendering the task
act(() => root!.render(createElement(Task)));
const before = { ...counts };
for (let index = 1; index <= 100; index++) {
- act(() => source.setDocument(textComposerDocument('听写内容'.repeat(index))));
+ act(() => {
+ source.setDocument(textComposerDocument('听写内容'.repeat(index)));
+ vi.advanceTimersToNextFrame();
+ });
}
expect(counts.task).toBe(before.task);
expect(counts.messages).toBe(before.messages);
@@ -35,6 +39,56 @@ it('typing and streamed dictation update subscribers without rendering the task
expect(container.textContent).toBe('听写内容'.repeat(100));
});
+it('coalesces a burst of native edits while send snapshots always contain the latest rich draft', () => {
+ const source = createComposerDraftSource(textComposerDocument(''));
+ const container = document.createElement('div');
+ const render = vi.fn();
+ function Input() {
+ const snapshot = useSyncExternalStore(source.subscribe, source.getSnapshot);
+ render(snapshot);
+ return createElement('span', null, snapshot.draft);
+ }
+ root = createRoot(container);
+ act(() => root!.render(createElement(Input)));
+ render.mockClear();
+ act(() => {
+ for (let index = 1; index <= 200; index++) {
+ source.setDocument(textComposerDocument('input'.repeat(index)));
+ expect(source.getSnapshot().draft).toBe('input'.repeat(index));
+ }
+ });
+ expect(render).not.toHaveBeenCalled();
+ act(() => vi.advanceTimersToNextFrame());
+ expect(render).toHaveBeenCalledTimes(1);
+ expect(container.textContent).toBe('input'.repeat(200));
+ const sent = source.getSnapshot();
+ act(() => {
+ source.setDocument(textComposerDocument(''));
+ vi.advanceTimersToNextFrame();
+ });
+ expect(sent.draft).toBe('input'.repeat(200));
+ expect(container.textContent).toBe('');
+});
+
+it('does not notify a replaced subscription again or retain work after the editor leaves', () => {
+ const source = createComposerDraftSource(textComposerDocument(''));
+ const replacement = vi.fn();
+ let unsubscribe = () => {};
+ const first = vi.fn(() => { unsubscribe(); unsubscribe = source.subscribe(replacement); });
+ unsubscribe = source.subscribe(first);
+ source.setDocument(textComposerDocument('draft'));
+ vi.advanceTimersToNextFrame();
+ expect(first).toHaveBeenCalledTimes(1);
+ expect(replacement).not.toHaveBeenCalled();
+ expect(source.getSnapshot().draft).toBe('draft');
+ source.setDocument(textComposerDocument('latest'));
+ unsubscribe();
+ expect(vi.getTimerCount()).toBe(0);
+ vi.advanceTimersToNextFrame();
+ expect(replacement).not.toHaveBeenCalled();
+ expect(source.getSnapshot().draft).toBe('latest');
+});
+
it('task switches detach old drafts and clearing the editor preserves the send snapshot', () => {
const first = createComposerDraftSource(textComposerDocument('first draft'));
const second = createComposerDraftSource(textComposerDocument('second draft'));
diff --git a/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsx b/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsx
index 047e762dd4..ec32240db7 100644
--- a/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsx
+++ b/apps/mobile/src/__tests__/composerRichInputLifecycle.test.tsx
@@ -73,15 +73,37 @@ function mount(hidden = false) {
};
bridge.inject.mockImplementation((script: string) => runInNewContext(script, { window: { cindyComposer: page } }));
root = createRoot(document.createElement('div'));
- act(() => root!.render(createElement(ComposerRichInput, {
- ref, document: page.document, hidden, onChangeDocument, onPasteImagesLoadFailed,
+ const renderDocument = (document: ComposerDocument) => act(() => root!.render(createElement(ComposerRichInput, {
+ ref, document, hidden, onChangeDocument, onPasteImagesLoadFailed,
accessibilityLabel: 'input', placeholder: '', height: 40, maxHeight: 264,
theme: { background: '#fff', border: '#aaa', chip: '#ddd', focus: '#555', placeholder: '#777', text: '#111', textSecondary: '#333' },
})));
+ renderDocument(page.document);
const send = (message: unknown) => act(() => bridge.onMessage({ nativeEvent: { data: JSON.stringify(message) } }));
- return { ref, page, send, onChangeDocument, onPasteImagesLoadFailed };
+ return { ref, page, send, onChangeDocument, onPasteImagesLoadFailed, renderDocument };
}
+it('never writes an older native edit back over later typing, but applies external replacements', () => {
+ const { page, send, onChangeDocument, renderDocument } = mount();
+ send({ type: 'ready' });
+ const id = page.id;
+ send({ type: 'change', documentId: id, document: textComposerDocument('a') });
+ const first = onChangeDocument.mock.lastCall![0];
+ send({ type: 'change', documentId: id, document: textComposerDocument('abc') });
+ const latest = onChangeDocument.mock.lastCall![0];
+ page.applyDocument.mockClear();
+ renderDocument(first);
+ renderDocument(latest);
+ expect(page.applyDocument).not.toHaveBeenCalled();
+ expect(page.id).toBe(id);
+ const empty = textComposerDocument('');
+ renderDocument(empty);
+ expect(page.document).toEqual(empty);
+ // Explicitly restoring a previously acknowledged draft is still a command.
+ renderDocument(first);
+ expect(page.document).toEqual(first);
+});
+
it('restores the latest accepted draft on every ready and accepts only the new document id', () => {
const { ref, page, send, onChangeDocument } = mount();
send({ type: 'ready' });
diff --git a/apps/mobile/src/__tests__/connectionBannerVisibility.test.ts b/apps/mobile/src/__tests__/connectionBannerVisibility.test.ts
index 041e9304ee..9c405124d8 100644
--- a/apps/mobile/src/__tests__/connectionBannerVisibility.test.ts
+++ b/apps/mobile/src/__tests__/connectionBannerVisibility.test.ts
@@ -1,8 +1,10 @@
import { describe, expect, it } from 'vitest';
+import { sharedTaskHostPeer } from '@cindy/device-link';
import {
resolveConnectionBannerSyncActionVisibility,
resolveConnectionBannerVisibility,
resolveEffectiveConnectionError,
+ resolveHomeDeviceDisconnected,
} from '@/components/connectionBannerVisibility';
const base = {
@@ -14,6 +16,17 @@ const base = {
deviceUnresponsive: false,
};
+it('does not infer shared task disconnection from the account device list', () => {
+ const guest = { deviceId: sharedTaskHostPeer('shared'), sessionCount: 1, available: false };
+ const host = { deviceId: 'my-computer', sessionCount: 2, available: false };
+ expect(resolveHomeDeviceDisconnected([guest], null, false)).toBe(false);
+ expect(resolveHomeDeviceDisconnected([guest, host], guest.deviceId, false)).toBe(false);
+ expect(resolveHomeDeviceDisconnected([guest, host], null, false)).toBe(true);
+ expect(resolveHomeDeviceDisconnected([guest, host], host.deviceId, false)).toBe(true);
+ expect(resolveHomeDeviceDisconnected([guest, { ...host, available: true }], null, false)).toBe(false);
+ expect(resolveHomeDeviceDisconnected([host], null, true)).toBe(false);
+});
+
describe('resolveConnectionBannerVisibility', () => {
it('normal connecting stays quiet, but real failures still surface during connecting', () => {
const connecting = { ...base, offline: true, connecting: true, offlineLongEnough: true };
diff --git a/apps/mobile/src/__tests__/envBundleTransform.test.ts b/apps/mobile/src/__tests__/envBundleTransform.test.ts
new file mode 100644
index 0000000000..f2ecf371ea
--- /dev/null
+++ b/apps/mobile/src/__tests__/envBundleTransform.test.ts
@@ -0,0 +1,54 @@
+import { createRequire } from 'node:module';
+import { resolve } from 'node:path';
+import { runInNewContext } from 'node:vm';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const require = createRequire(import.meta.url);
+const babel = require('@babel/core') as {
+ transformFileSync(filename: string, options: Record<string, unknown>): { code?: string };
+};
+const expoPreset = require('babel-preset-expo');
+
+afterEach(() => vi.unstubAllEnvs());
+
+describe('mobile endpoint overrides after Expo bundle transform', () => {
+ it.each([false, true])('keeps explicit endpoints without a runtime shell env (production=%s)', (isProd) => {
+ const env = {
+ EXPO_PUBLIC_CINDY_AUTH_REGION: 'global',
+ EXPO_PUBLIC_CINDY_AUTH_BASE_URL: 'http://localhost:3344',
+ EXPO_PUBLIC_XDT_DEVICE_LINK_API_BASE_URL: 'http://localhost:3335',
+ };
+ for (const [key, value] of Object.entries(env)) vi.stubEnv(key, value);
+ const filename = resolve(process.cwd(), 'src/config/env.ts');
+ const transformed = babel.transformFileSync(filename, {
+ babelrc: false, configFile: false, filename,
+ envName: isProd ? 'production' : 'development',
+ caller: { name: 'metro', platform: 'android', isDev: !isProd },
+ presets: [[expoPreset, { platform: 'android' }]],
+ });
+ expect(transformed.code).toBeTruthy();
+ const exports: Record<string, unknown> = {};
+ runInNewContext(transformed.code!, {
+ exports, process: { env: {} }, __DEV__: false,
+ require(id: string) {
+ if (id.startsWith('@babel/runtime/')) return require(id);
+ if (id === 'expo/virtual/env') return { env };
+ if (id === 'expo-application') return {};
+ if (id === 'expo-constants') return { expoConfig: { extra: { xdtProductionEnv: {
+ EXPO_PUBLIC_CINDY_AUTH_REGION: 'cn',
+ EXPO_PUBLIC_CINDY_AUTH_BASE_URL: 'https://fallback.example.invalid',
+ } } } };
+ if (id === '@cindy/maker-shared/client-endpoints') return {};
+ if (id === './endpointManifestLoader') return {
+ resolveMobileEndpointManifest() {
+ throw new Error('Importing endpoint overrides must not fetch a manifest');
+ },
+ };
+ throw new Error(`Unexpected import: ${id}`);
+ },
+ });
+ expect(exports.AUTH_REGION).toBe('global');
+ expect(exports.AUTH_API_BASE_URL).toBe(env.EXPO_PUBLIC_CINDY_AUTH_BASE_URL);
+ expect(exports.DEVICE_LINK_API_BASE_URL).toBe(env.EXPO_PUBLIC_XDT_DEVICE_LINK_API_BASE_URL);
+ });
+});
diff --git a/apps/mobile/src/__tests__/fixtures/theme-colors-snapshot.json b/apps/mobile/src/__tests__/fixtures/theme-colors-snapshot.json
index beb14181cb..36f061ad34 100644
--- a/apps/mobile/src/__tests__/fixtures/theme-colors-snapshot.json
+++ b/apps/mobile/src/__tests__/fixtures/theme-colors-snapshot.json
@@ -48,6 +48,8 @@
"statusDone": "#2AAE5B",
"permAutoAccent": "#417CDD",
"errorText": "#3C3F43",
+ "sharedTaskConfirmBackground": "#ac3535",
+ "sharedTaskConfirmForeground": "#fffefa",
"destructive": "#f43d3f",
"errorBorder": "#686B72",
"overlay": "rgba(38, 38, 38, 0.35)",
@@ -164,6 +166,8 @@
"statusDone": "#2AAE5B",
"permAutoAccent": "#417CDD",
"errorText": "#D4D4D4",
+ "sharedTaskConfirmBackground": "#ec9898",
+ "sharedTaskConfirmForeground": "#272727",
"destructive": "#f43d3f",
"errorBorder": "#BFC1C4",
"overlay": "rgba(0, 0, 0, 0.45)",
diff --git a/apps/mobile/src/__tests__/historyViewProvider.test.tsx b/apps/mobile/src/__tests__/historyViewProvider.test.tsx
index 9d192d983e..b116517213 100644
--- a/apps/mobile/src/__tests__/historyViewProvider.test.tsx
+++ b/apps/mobile/src/__tests__/historyViewProvider.test.tsx
@@ -4,6 +4,7 @@ import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
DEVICE_LINK_CAPABILITY_HISTORY_VIEW_V1,
+ SHARED_TASK_CAPABILITY,
type DeviceLinkClient,
type DeviceLinkStatus,
type LinkAcceptPayload,
@@ -63,6 +64,8 @@ const transport = vi.hoisted(() => {
connectNow = vi.fn();
notifyNetworkChanged = vi.fn();
getStatus = () => this.status;
+ serverCapabilities: string[] = [];
+ hasServerCapability = (capability: string) => this.serverCapabilities.includes(capability);
isOutboundExplicitlyClosed = () => false;
// No background recovery owner; each test explicitly starts the fresh read.
hasPendingRequestsTo = () => false;
@@ -111,6 +114,22 @@ beforeEach(async () => {
});
afterEach(async () => { await act(async () => root.unmount()); });
+describe('Provider shared-task relay compatibility', () => {
+ it('distinguishes an old online relay from disconnection and re-negotiates after upgrade', async () => {
+ const client = transport.clients[0];
+ expect(context.sharedTaskAvailable).toBeUndefined();
+ await act(async () => client.statusChanged('online'));
+ expect(context.sharedTaskAvailable).toBe(false);
+ await act(async () => client.statusChanged('connecting'));
+ expect(context.sharedTaskAvailable).toBeUndefined();
+ client.serverCapabilities = [SHARED_TASK_CAPABILITY];
+ await act(async () => client.statusChanged('online'));
+ expect(context.sharedTaskAvailable).toBe(true);
+ await act(async () => client.statusChanged('stopped'));
+ expect(context.sharedTaskAvailable).toBeUndefined();
+ });
+});
+
describe('Provider network recovery priority', () => {
const wifi = { type: 'WIFI', isConnected: true, isInternetReachable: true };
it('coalesces equal hints but expedites transport changes and offline recovery', async () => {
diff --git a/apps/mobile/src/__tests__/interactionModel.test.ts b/apps/mobile/src/__tests__/interactionModel.test.ts
index 91d5ebc91d..b2e0a75119 100644
--- a/apps/mobile/src/__tests__/interactionModel.test.ts
+++ b/apps/mobile/src/__tests__/interactionModel.test.ts
@@ -399,12 +399,13 @@ describe('interactionModel', () => {
it('keeps read-only pending interactions as a short desktop-style blocker', () => {
const interactionPanelSource = readFileSync(resolve(process.cwd(), 'src/session/InteractionPanel.tsx'), 'utf8');
- const readOnlyStart = interactionPanelSource.indexOf('if (readOnlyReason) {');
+ const readOnlyStart = interactionPanelSource.indexOf('if (readOnlyReason || isSharedTaskPeer(deviceId)) {');
const readOnlyEnd = interactionPanelSource.indexOf('return (', interactionPanelSource.indexOf('}', readOnlyStart));
const readOnlySource = interactionPanelSource.slice(readOnlyStart, readOnlyEnd);
expect(readOnlySource).toContain("t('interaction.panel.readOnlyTitle')");
- expect(readOnlySource).toContain('{readOnlyReason}');
+ expect(readOnlySource).toContain("{readOnlyReason ?? t('sharedTask.waitingHost')}");
+ expect(readOnlySource).toContain('JSON.stringify(activeInteraction.request, null, 2)');
expect(readOnlySource).not.toContain('当前请求类型');
expect(readOnlySource).not.toContain('不会回传协作编排决定');
expect(readOnlySource).not.toContain('手机版会保留会话显示');
diff --git a/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts b/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts
index 76e3f6ac63..74565ea0fe 100644
--- a/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts
+++ b/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts
@@ -22,6 +22,15 @@ const readFileChunk = vi.fn(async (_uri: string, _position: number, length: numb
);
describe('mobileAttachmentUpload', () => {
+ it('presigns against the captured shared task rather than the private account namespace', async () => {
+ const apiFetch = vi.fn(async () => ({ putUrl: 'https://oss.example/upload', key: 'cindy/shared-task/task/u/file.png', expiresAt: '2026-09-16T12:00:00Z' }));
+ await presignMobileAttachmentUpload({ name: 'file.png', size: 10, mimeType: 'image/png' }, {
+ token: 'token', sharedTaskId: 'task', deps: { apiFetch: apiFetch as unknown as typeof apiFetchRaw },
+ });
+ expect(apiFetch).toHaveBeenCalledWith('/api/device-link/media/presign-put', expect.objectContaining({
+ body: { size: 10, ext: 'png', contentType: 'image/png', sharedTaskId: 'task' },
+ }));
+ });
it('requests a device-link media presign-put with desktop-compatible file metadata', async () => {
const apiFetch = vi.fn(async () => ({
putUrl: 'https://oss.example/upload',
diff --git a/apps/mobile/src/__tests__/sendEnqueueRetry.test.ts b/apps/mobile/src/__tests__/sendEnqueueRetry.test.ts
index 07e91f6692..7c679e3373 100644
--- a/apps/mobile/src/__tests__/sendEnqueueRetry.test.ts
+++ b/apps/mobile/src/__tests__/sendEnqueueRetry.test.ts
@@ -30,7 +30,7 @@ describe('send enqueue weak-network retry ordering', () => {
};
it('重试门槛必须要求可安全重发的传输错误且非 in-flight(send 与 outbox 两条路径)', () => {
- expect(source).toContain("import { isInFlightDeviceLinkError } from '@cindy/device-link';");
+ expect(source).toContain("import { isInFlightDeviceLinkError, isSharedTaskPeer } from '@cindy/device-link';");
expect(source).toContain("code === 'NOT_CONNECTED' || code === 'BACKPRESSURE'");
expect(source).toContain("formatted.includes('[BACKPRESSURE]')");
const loops = extractRetryLoops();
diff --git a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
index 13b1defd02..2d987a11b5 100644
--- a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
@@ -255,7 +255,7 @@ describe('mobile session composer desktop-first surface', () => {
expect(source).not.toContain("import { BlurView } from 'expo-blur';");
expect(source).toContain("import { BlurBackdrop } from '@/session/BlurBackdrop';");
expect(source).toContain('<SessionHeaderNativeBlur height=');
- expect(source).toMatch(/<SessionHeaderNativeTitle\s+title=\{title\}/);
+ expect(source).toMatch(/<SessionHeaderNativeTitle\s+title=\{sharedTaskEnded \? t\('sharedTask.ended'\) : title\}/);
expect(source).toContain('<SessionHeaderNativeActions');
expect(source).toContain("sessionHeaderBar: {\n alignItems: 'center',\n backgroundColor: 'transparent'");
expect(source).toContain('sessionBottomLayer: {\n backgroundColor: colors.surface');
diff --git a/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts
index f7f3dddb85..b7d09611f2 100644
--- a/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts
@@ -44,7 +44,15 @@ describe('mobile session main layer desktop-first noise budget', () => {
// banner 渲染条件(useShowConnectionBanner):请求级 / transport hold error、可分类连接问题、
// 目标设备熔断 open(电脑端未响应)立即显示;普通弱网断线经防闪窗口后也显示,不再彻底静默。
- expect(routeSource).toContain('{showConnectionBanner || showCachedHistoryNotice ? (');
+ // Confirmed shared-task revocation has its own state, not a retry banner.
+ expect(routeSource).toContain('{!isSharedTaskAccessRevoked && (showConnectionBanner || showCachedHistoryNotice) ? (');
+ const revokedStart = source.indexOf('{isSharedTaskAccessRevoked ? (');
+ expect(revokedStart).toBeGreaterThan(-1);
+ const revokedEnd = source.indexOf("sessionOperationLayout.composerSlot === 'missing-session'", revokedStart);
+ expect(revokedEnd).toBeGreaterThan(revokedStart);
+ expect(source.slice(revokedStart, revokedEnd)).toContain('paddingTop: topOverlayHeight + spacing.lg');
+ expect(source.slice(revokedStart, revokedEnd)).toContain('<SharedTaskEndedState');
+ expect(source.slice(revokedStart, revokedEnd)).toContain("router.replace('/shared-session')");
expect(routeSource).toContain('cachedOnly={showCachedHistoryNotice}');
expect(source.replace(/\r\n/g, '\n'))
.toContain('useShowConnectionBanner(\n status,\n bannerError,');
@@ -97,8 +105,8 @@ describe('mobile session main layer desktop-first noise budget', () => {
expect(source).toContain('if (collaborationLabel) return collaborationLabel;');
// 写编排(设置/队列/fork-rewind/interaction)仍用写 read-only reason,不被放开。
expect(source).toContain('readOnlyReason={collaborationReadOnlyReason}');
- expect(source).toContain('onForkMessage={collaborationReadOnlyReason ? undefined : forkAtMessage}');
- expect(source).toContain('onPreviewRewind={collaborationReadOnlyReason ? undefined : previewRewindAtMessage}');
+ expect(source).toContain('onForkMessage={collaborationReadOnlyReason || isSharedTaskPeer(deviceId) ? undefined : forkAtMessage}');
+ expect(source).toContain('onPreviewRewind={collaborationReadOnlyReason || isSharedTaskPeer(deviceId) ? undefined : previewRewindAtMessage}');
});
it('resyncs sessions from connection recovery or target availability, not every presence tick', () => {
diff --git a/apps/mobile/src/__tests__/sharedSessionCompatibility.test.tsx b/apps/mobile/src/__tests__/sharedSessionCompatibility.test.tsx
new file mode 100644
index 0000000000..6dd99f8944
--- /dev/null
+++ b/apps/mobile/src/__tests__/sharedSessionCompatibility.test.tsx
@@ -0,0 +1,82 @@
+// @vitest-environment jsdom
+import { act, createElement, type ReactNode } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import SharedSessionScreen from '../../app/shared-session';
+
+const state = vi.hoisted(() => ({
+ params: { sessionId: 'session', deviceId: 'host' },
+ link: { sharedTaskAvailable: true as boolean | undefined, invoke: vi.fn() },
+ api: { list: vi.fn(async () => []), get: vi.fn() },
+ t: (key: string) => key,
+}));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: state.t }) }));
+vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));
+vi.mock('lucide-react-native', () => ({ Check: () => null, Laptop: () => null, Link: () => null, Users: () => null, Clock: () => null, FileText: () => null, Square: () => null, X: () => null }));
+vi.mock('@/device-link/accessRevoked', () => ({ markDeviceAccessRevoked: vi.fn() }));
+vi.mock('expo-router', async () => {
+ const { useEffect } = await import('react');
+ return { Stack: { Screen: () => null }, useLocalSearchParams: () => state.params, useRouter: () => ({}), useFocusEffect: (effect: () => void) => useEffect(effect, [effect]) };
+});
+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ isAuthenticated: true, accountGeneration: 1 }) }));
+vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => state.link }));
+vi.mock('@/device-link/useSharedTaskApi', () => ({ useSharedTaskApi: () => state.api }));
+vi.mock('@/session/remoteSessionStore', () => ({ remoteSessionStore: { getSessions: () => [] } }));
+vi.mock('@/session/messageActions', () => ({ writeClipboardText: vi.fn() }));
+vi.mock('@/utils/backGuard', () => ({ goBackGuarded: vi.fn() }));
+vi.mock('xdt-ios-action-sheet', () => ({ iosBottomActionSheetAvailable: false, showIosBottomActionSheet: vi.fn() }));
+vi.mock('react-native', () => ({
+ ActionSheetIOS: {},
+ Alert: { alert: vi.fn() }, AppState: { currentState: 'active' }, Keyboard: { dismiss: vi.fn() },
+ Platform: { OS: 'android' }, BackHandler: { addEventListener: () => ({ remove: vi.fn() }) },
+ KeyboardAvoidingView: ({ children }: { children?: ReactNode }) => createElement('div', null, children),
+ Pressable: ({ children }: { children?: ReactNode }) => createElement('div', null, children),
+ View: ({ children }: { children?: ReactNode }) => createElement('div', null, children),
+ ScrollView: ({ children }: { children?: ReactNode }) => createElement('div', null, children),
+ StyleSheet: { create: (value: unknown) => value },
+}));
+vi.mock('react-native-safe-area-context', () => ({ SafeAreaView: ({ children }: { children?: ReactNode }) => children }));
+vi.mock('@/components/AppText', () => ({
+ Text: ({ children }: { children?: ReactNode }) => createElement('span', null, children), TextInput: () => null,
+}));
+vi.mock('@/components/MobilePrimitives', () => ({
+ MainWindowActionButton: ({ action }: { action: { label: string } }) => createElement('button', null, action.label),
+ MainWindowRowButton: () => null,
+ MainWindowOptionButton: ({ label }: { label: string }) => createElement('button', null, label),
+}));
+vi.mock('@/platform/chrome/SimpleStackHeader', () => ({ SimpleStackHeader: () => null, simpleScreenSafeAreaEdges: () => [] }));
+vi.mock('@/theme', () => ({ useTheme: () => ({ colors: {} }), useThemedStyles: () => ({}) }));
+let host: HTMLDivElement;
+let root: Root;
+async function render() { await act(async () => root.render(createElement(SharedSessionScreen))); }
+beforeEach(() => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ vi.useFakeTimers(); vi.clearAllMocks(); state.link.sharedTaskAvailable = true;
+ host = document.createElement('div'); root = createRoot(host);
+});
+afterEach(async () => { await act(async () => root.unmount()); vi.useRealTimers(); });
+it('shows upgrade for an old host and recovers when the host gains the channel', async () => {
+ state.link.invoke.mockRejectedValue({ code: 'CHANNEL_NOT_ALLOWED' });
+ await render();
+ expect(host.textContent).toContain('sharedTask.upgrade');
+ expect(host.textContent).not.toContain('sharedTask.open');
+ state.link.invoke.mockResolvedValue({ available: true, detail: null });
+ await act(async () => vi.advanceTimersByTimeAsync(5_000));
+ expect(host.textContent).not.toContain('sharedTask.upgrade');
+ expect(host.textContent).toContain('sharedTask.open');
+});
+it('does not query an old relay and does not mislabel disconnected as old', async () => {
+ state.link.sharedTaskAvailable = false;
+ await render();
+ expect(host.textContent).toContain('sharedTask.upgrade');
+ expect(state.link.invoke).not.toHaveBeenCalled();
+ state.link.sharedTaskAvailable = undefined; await render();
+ expect(host.textContent).not.toContain('sharedTask.upgrade');
+ expect(host.textContent).toContain('sharedTask.retry');
+ expect(state.link.invoke).not.toHaveBeenCalled();
+});
+it('does not convert a timeout into an upgrade requirement', async () => {
+ state.link.invoke.mockRejectedValue({ code: 'INVOKE_TIMEOUT' }); await render();
+ expect(host.textContent).toContain('sharedTask.retry');
+ expect(host.textContent).not.toContain('sharedTask.upgrade');
+});
diff --git a/apps/mobile/src/__tests__/sharedTaskAccessWatch.test.ts b/apps/mobile/src/__tests__/sharedTaskAccessWatch.test.ts
new file mode 100644
index 0000000000..767660bab9
--- /dev/null
+++ b/apps/mobile/src/__tests__/sharedTaskAccessWatch.test.ts
@@ -0,0 +1,73 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { ApiError } from '@/api/client';
+import { watchSharedTaskAccess } from '@/device-link/sharedTaskAccessWatch';
+
+const active = { sharedTaskId: 'sharedTask', sessionId: 'session', status: 'active' };
+const disposers: (() => void)[] = [];
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => { disposers.splice(0).forEach(stop => stop()); vi.useRealTimers(); });
+function start(read: () => Promise<typeof active>, isCurrent = () => true) {
+ const onRevoked = vi.fn();
+ const stop = watchSharedTaskAccess({ ...active, read, isCurrent, onRevoked });
+ disposers.push(stop);
+ return { onRevoked, stop };
+}
+
+it('only polls again after the previous read settles', async () => {
+ let resolve!: (value: typeof active) => void;
+ const read = vi.fn(() => new Promise<typeof active>(done => { resolve = done; }));
+ const watch = start(read);
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(read).toHaveBeenCalledTimes(1);
+ resolve(active);
+ await vi.advanceTimersByTimeAsync(4_999);
+ expect(read).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(read).toHaveBeenCalledTimes(2);
+ expect(watch.onRevoked).not.toHaveBeenCalled();
+});
+
+it.each([
+ new ApiError('UNAUTHORIZED', 401, 'login expired'),
+ new ApiError('ROUTE_NOT_FOUND', 404, 'unsupported'),
+ new ApiError('NOT_FOUND', 503, 'unavailable'),
+ new Error('timeout'),
+])('does not infer revoked access from %s', async error => {
+ const read = vi.fn().mockRejectedValue(error);
+ const watch = start(read);
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(watch.onRevoked).not.toHaveBeenCalled();
+ expect(read).toHaveBeenCalledTimes(2);
+});
+
+it.each(['missing', 'closed'])('revokes once after a confirmed %s membership', async state => {
+ const read = state === 'missing'
+ ? vi.fn().mockRejectedValue(new ApiError('NOT_FOUND', 404, 'not found'))
+ : vi.fn().mockResolvedValue({ ...active, status: 'closed' });
+ const watch = start(read);
+ const other = start(async () => active);
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(watch.onRevoked).toHaveBeenCalledTimes(1);
+ expect(read).toHaveBeenCalledTimes(1);
+ expect(other.onRevoked).not.toHaveBeenCalled();
+});
+
+it.each(['stop', 'owner'])('ignores late responses after %s changes', async boundary => {
+ let reject!: (reason: Error) => void;
+ let current = true;
+ const read = vi.fn(() => new Promise<typeof active>((_, fail) => { reject = fail; }));
+ const old = start(read, () => current);
+ if (boundary === 'stop') old.stop(); else current = false;
+ const next = start(async () => active);
+ reject(new ApiError('NOT_FOUND', 404, 'not found'));
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(old.onRevoked).not.toHaveBeenCalled();
+ expect(next.onRevoked).not.toHaveBeenCalled();
+ expect(read).toHaveBeenCalledTimes(1);
+});
+
+it('ignores a closed detail for a different task', async () => {
+ const watch = start(async () => ({ ...active, sessionId: 'other', status: 'closed' }));
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(watch.onRevoked).not.toHaveBeenCalled();
+});
diff --git a/apps/mobile/src/__tests__/sharedTaskCompatibility.test.ts b/apps/mobile/src/__tests__/sharedTaskCompatibility.test.ts
new file mode 100644
index 0000000000..ce29e08fb8
--- /dev/null
+++ b/apps/mobile/src/__tests__/sharedTaskCompatibility.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+import { sharedTaskErrorKey } from '../device-link/sharedTaskCompatibility';
+
+describe('shared-task compatibility errors', () => {
+ it.each([['SHARED_TASK_HOST_LIMIT', 'sharedTask.hostLimit'], ['SHARED_TASK_JOIN_LIMIT', 'sharedTask.joinLimit'],
+ ['SHARED_TASK_GUEST_LIMIT', 'sharedTask.guestLimit']])('explains direct API and remote host %s', (code, key) => {
+ expect(sharedTaskErrorKey({ code })).toBe(key);
+ expect(sharedTaskErrorKey(Object.assign(new Error('[' + code + '] limit'), { code: 'IPC_ERROR' }))).toBe(key);
+ });
+ it.each(['CHANNEL_NOT_ALLOWED', 'VERSION_MISMATCH', 'DEVICE_LINK_CHANNEL_NOT_ALLOWED', 'UNSUPPORTED_CAPABILITY'])(
+ 'recognizes transport and serialized %s', (code) => {
+ expect(sharedTaskErrorKey({ code })).toBe('sharedTask.upgrade');
+ expect(sharedTaskErrorKey(Object.assign(new Error(`[${code}] unsupported`), { code: 'IPC_ERROR' }))).toBe('sharedTask.upgrade');
+ });
+ it.each(['NOT_CONNECTED', 'INVOKE_TIMEOUT', 'ACCESS_REVOKED', 'NOT_FOUND'])(
+ 'does not turn %s into an upgrade requirement', (code) => {
+ expect(sharedTaskErrorKey(Object.assign(new Error('[CHANNEL_NOT_ALLOWED]'), { code }))).toBe('sharedTask.retry');
+ });
+ it('does not match capability names inside unrelated error text', () => {
+ expect(sharedTaskErrorKey(new Error('[INTERNAL] CHANNEL_NOT_ALLOWED'))).toBe('sharedTask.retry');
+ });
+});
diff --git a/apps/mobile/src/__tests__/sharedTaskConfirmation.test.tsx b/apps/mobile/src/__tests__/sharedTaskConfirmation.test.tsx
new file mode 100644
index 0000000000..60ded1ce4c
--- /dev/null
+++ b/apps/mobile/src/__tests__/sharedTaskConfirmation.test.tsx
@@ -0,0 +1,75 @@
+// @vitest-environment jsdom
+import { act, type ReactNode } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { beforeEach, afterEach, expect, it, vi } from 'vitest';
+import { Platform } from 'react-native';
+import { useSharedTaskConfirmation } from '@/session/useSharedTaskConfirmation';
+
+const h = vi.hoisted(() => ({ native: vi.fn(), result: vi.fn(), close: () => {}, dark: false }));
+vi.mock('@/platform/chrome/showActionMenu', () => ({ showConfirm: h.native }));
+vi.mock('react-native', async () => {
+ const { createElement } = await import('react');
+ const view = ({ children, testID, style }: { children: ReactNode; testID?: string; style?: object }) => createElement('div', { 'data-testid': testID, style }, children);
+ return { Platform: { OS: 'android' }, View: view, ScrollView: view,
+ Modal: ({ children, onRequestClose }: { children: ReactNode; onRequestClose(): void }) => { h.close = onRequestClose; return createElement('div', { role: 'dialog' }, children); },
+ StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 },
+ AccessibilityInfo: { setAccessibilityFocus: vi.fn() }, findNodeHandle: () => null,
+ };
+});
+vi.mock('@/components/AppText', () => ({ Text: ({ children }: { children: ReactNode }) => <span>{children}</span> }));
+vi.mock('@/components/MobilePrimitives', () => ({
+ MainWindowActionButton: ({ action }: { action: { label: string; tone?: string; testID?: string; onPress(): void } }) => <button data-testid={action.testID} data-tone={action.tone} onClick={action.onPress}>{action.label}</button>,
+}));
+vi.mock('@/theme', async () => {
+ const { lightColors, darkColors } = await import('@/theme/tokens');
+ return { useThemedStyles: (make: (colors: typeof lightColors) => unknown) => make(h.dark ? darkColors : lightColors) };
+});
+let root: Root;
+let host: HTMLDivElement;
+const input = { title: 'Leave?', message: 'Access will end.', cancelLabel: 'Stay', confirmLabel: 'Leave', destructive: true };
+function Harness() {
+ const confirmation = useSharedTaskConfirmation();
+ return <><button onClick={() => { void confirmation.confirm(input).then(h.result); }}>open</button>{confirmation.dialog}</>;
+}
+async function click(text: string) { await act(async () => [...host.querySelectorAll('button')].find((button) => button.textContent === text)!.click()); }
+beforeEach(async () => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ vi.clearAllMocks(); Platform.OS = 'android'; h.dark = false;
+ host = document.createElement('div'); root = createRoot(host);
+ await act(async () => root.render(<Harness />));
+});
+afterEach(async () => { await act(async () => root.unmount()); });
+it('uses a compact themed Android dialog with neutral cancel and solid danger action', async () => {
+ await click('open');
+ expect(h.native).not.toHaveBeenCalled();
+ expect(host.querySelectorAll('[role=dialog]')).toHaveLength(1);
+ const actions = [...host.querySelector('[role=dialog]')!.querySelectorAll('button')];
+ expect(actions.map((button) => button.textContent)).toEqual(['Stay', 'Leave']);
+ expect(host.querySelector('[data-testid="sharedTask.confirmAccept"]')?.getAttribute('data-tone')).toBe('danger-solid');
+ const card = host.querySelector('[data-testid="sharedTask.confirmDialog"]') as HTMLElement;
+ expect(card.style.borderRadius).toBe('12px'); expect(card.style.maxWidth).toBe('400px');
+ await click('Stay'); expect(h.result).toHaveBeenLastCalledWith(false);
+ expect(host.querySelector('[role=dialog]')).toBeNull();
+});
+it('uses different theme surfaces in Light and Dark', async () => {
+ await click('open');
+ const light = (host.querySelector('[data-testid="sharedTask.confirmDialog"]') as HTMLElement).style.backgroundColor;
+ h.dark = true; await act(async () => root.render(<Harness />));
+ const dark = (host.querySelector('[data-testid="sharedTask.confirmDialog"]') as HTMLElement).style.backgroundColor;
+ expect(dark).not.toBe(light);
+});
+it('cancels on Android Back and resolves confirmation only once', async () => {
+ await click('open'); await act(async () => { h.close(); h.close(); });
+ expect(h.result).toHaveBeenCalledTimes(1); expect(h.result).toHaveBeenCalledWith(false);
+ await click('open'); await click('Leave'); expect(h.result).toHaveBeenLastCalledWith(true);
+});
+it('cancels an unresolved Android confirmation on unmount', async () => {
+ await click('open'); await act(async () => root.render(null));
+ expect(h.result).toHaveBeenCalledWith(false);
+});
+it('keeps iOS confirmation native without a second custom modal', async () => {
+ Platform.OS = 'ios'; h.native.mockResolvedValue(true); await click('open');
+ expect(h.native).toHaveBeenCalledWith(input);
+ expect(host.querySelector('[role=dialog]')).toBeNull();
+ expect(h.result).toHaveBeenCalledWith(true);
+});
diff --git a/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx b/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx
new file mode 100644
index 0000000000..b4e9168b2b
--- /dev/null
+++ b/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx
@@ -0,0 +1,183 @@
+// @vitest-environment jsdom
+import { act, createElement, type ReactNode } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { sharedTaskHostPeer } from '@cindy/device-link';
+import { setMobileAuthOwner } from '@/auth/authOwnerGeneration';
+import { ApiError } from '@/api/client';
+import { Platform } from 'react-native';
+import SharedSessionScreen from '../../app/shared-session';
+
+const h = vi.hoisted(() => ({
+ params: {} as { sessionId?: string; deviceId?: string }, generation: 1,
+ router: { replace: vi.fn() }, alert: vi.fn(), revoked: vi.fn(),
+ link: { sharedTaskAvailable: true, invoke: vi.fn(), openLink: vi.fn(), closeLink: vi.fn(), readDeviceList: vi.fn() },
+ api: { list: vi.fn(), get: vi.fn(), join: vi.fn(), leave: vi.fn(), close: vi.fn() },
+ store: { getSessions: () => [], removeDevice: vi.fn(), setDeviceSessions: vi.fn() },
+ t: (key: string, options?: { title?: string }) => options?.title ? key + ':' + options.title : key,
+}));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: h.t }) }));
+vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));
+vi.mock('lucide-react-native', () => ({ Check: () => null, Laptop: () => null, Link: () => null, Users: () => null, Clock: () => null, FileText: () => null, Square: () => null, X: () => null }));
+vi.mock('@/device-link/accessRevoked', () => ({ markDeviceAccessRevoked: h.revoked }));
+vi.mock('expo-router', async () => {
+ const { useEffect } = await import('react');
+ return { Stack: { Screen: () => null }, useLocalSearchParams: () => h.params, useRouter: () => h.router, useFocusEffect: (effect: () => void) => useEffect(effect, [effect]) };
+});
+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ isAuthenticated: true, accountGeneration: h.generation }) }));
+vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => h.link }));
+vi.mock('@/device-link/useSharedTaskApi', () => ({ useSharedTaskApi: () => h.api }));
+vi.mock('@/session/remoteSessionStore', () => ({ remoteSessionStore: h.store }));
+vi.mock('@/session/messageActions', () => ({ writeClipboardText: vi.fn() }));
+// Workflow/authorization tests; platform dialog rendering has separate coverage.
+vi.mock('@/session/useSharedTaskConfirmation', async () => {
+ const { showConfirm } = await import('@/platform/chrome/showActionMenu');
+ return { useSharedTaskConfirmation: () => ({ confirm: showConfirm, dialog: null }) };
+});
+vi.mock('@/utils/backGuard', () => ({ goBackGuarded: vi.fn() }));
+vi.mock('xdt-ios-action-sheet', () => ({ iosBottomActionSheetAvailable: false, showIosBottomActionSheet: vi.fn() }));
+vi.mock('react-native', () => ({
+ ActionSheetIOS: {},
+ Alert: { alert: h.alert }, AppState: { currentState: 'active' }, Keyboard: { dismiss: vi.fn() },
+ Platform: { OS: 'android' },
+ AccessibilityInfo: { setAccessibilityFocus: vi.fn() }, findNodeHandle: () => null,
+ View: ({ children, testID, accessibilityElementsHidden }: { children?: ReactNode; testID?: string; accessibilityElementsHidden?: boolean }) => createElement('div', { 'data-testid': testID, hidden: accessibilityElementsHidden }, children),
+ KeyboardAvoidingView: ({ children }: { children?: ReactNode }) => createElement('div', null, children),
+ Pressable: ({ children, onPress, accessibilityLabel }: { children?: ReactNode; onPress(): void; accessibilityLabel?: string }) => createElement('button', { onClick: onPress, 'aria-label': accessibilityLabel }, children),
+ ScrollView: ({ children }: { children?: ReactNode }) => createElement('div', null, children),
+ StyleSheet: { create: (value: unknown) => value },
+}));
+vi.mock('react-native-safe-area-context', () => ({ SafeAreaView: ({ children }: { children?: ReactNode }) => children }));
+vi.mock('@/components/AppText', () => ({
+ Text: ({ children }: { children?: ReactNode }) => createElement('span', null, children),
+ TextInput: ({ accessibilityLabel, multiline, maxLength, value, onChangeText }: { accessibilityLabel: string; multiline?: boolean; maxLength?: number; value: string; onChangeText(value: string): void }) => createElement(multiline ? 'textarea' : 'input', { 'aria-label': accessibilityLabel, maxLength, value, onInput: (e: { currentTarget: HTMLInputElement }) => onChangeText(e.currentTarget.value), onChange: () => {} }),
+}));
+vi.mock('@/components/MobilePrimitives', () => ({
+ MainWindowActionButton: ({ action }: { action: { label: string; disabled?: boolean; busy?: boolean; onPress(): void } }) => createElement('button', { disabled: action.disabled || action.busy, onClick: action.onPress }, action.label),
+ MainWindowRowButton: ({ children, onPress, accessibilityLabel }: { children?: ReactNode; onPress(): void; accessibilityLabel?: string }) => createElement('button', { onClick: onPress, 'aria-label': accessibilityLabel }, children),
+ MainWindowOptionButton: ({ label, onPress }: { label: string; onPress(): void }) => createElement('button', { onClick: onPress }, label),
+}));
+vi.mock('@/platform/chrome/SimpleStackHeader', () => ({ SimpleStackHeader: ({ title, onBack }: { title: string; onBack(): void }) => createElement('header', null, title, createElement('button', { onClick: onBack }, 'back')), simpleScreenSafeAreaEdges: () => [] }));
+vi.mock('@/theme', () => ({ useTheme: () => ({ colors: {} }), useThemedStyles: () => ({}) }));
+let element: HTMLDivElement;
+let root: Root;
+const detail = { sharedTaskId: 'shared', sessionId: 'task', status: 'active', title: 'Design review', memberLabels: [{ memberId: 'member', displayName: 'Guest' }] };
+const owned = (id: string) => ({ sharedTaskId: id, sessionId: 'task', title: id, ownerAccountId: 'owner', hostDeviceId: 'host' });
+async function render() { await act(async () => root.render(createElement(SharedSessionScreen))); }
+async function click(label: string) {
+ const button = [...element.querySelectorAll('button')].find((button) => button.textContent === label || button.getAttribute('aria-label') === label);
+ expect(button, label).toBeDefined(); await act(async () => button!.click());
+}
+async function fill(label: string, value: string) {
+ const input = element.querySelector('[aria-label="' + label + '"]') as HTMLInputElement;
+ await act(async () => { input.value = value; input.dispatchEvent(new Event('input', { bubbles: true })); });
+}
+const confirmation = () => h.alert.mock.lastCall![2] as { style: string; onPress(): void }[];
+beforeEach(() => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ vi.useFakeTimers(); vi.resetAllMocks(); h.params = {}; h.generation = 1;
+ Platform.OS = 'android';
+ setMobileAuthOwner('owner'); h.link.sharedTaskAvailable = true;
+ h.api.list.mockResolvedValue([]); h.api.get.mockResolvedValue(detail);
+ h.api.join.mockResolvedValue({ sharedTaskId: 'shared' });
+ h.link.invoke.mockResolvedValue({ available: true, detail: null });
+ h.link.readDeviceList.mockResolvedValue({ devices: [{ deviceId: 'host', name: 'Test computer' }] });
+ element = document.createElement('div'); root = createRoot(element);
+});
+afterEach(async () => { await act(async () => root.unmount()); vi.useRealTimers(); });
+it('uses a multiline invitation and stops at the joined screen before opening the task', async () => {
+ await render();
+ expect(element.querySelector('textarea')).not.toBeNull();
+ expect(element.querySelector('input')?.maxLength).toBe(32);
+ await fill('sharedTask.invitation', 'a'.repeat(43)); await fill('sharedTask.joinNickname', ' Guest ');
+ await click('sharedTask.join');
+ expect(h.api.join).toHaveBeenCalledWith('a'.repeat(43), 'Guest');
+ expect(element.textContent).toContain('sharedTask.joinedTitle:Design review');
+ expect(element.querySelector('textarea')).toBeNull();
+ expect(h.link.openLink).not.toHaveBeenCalled();
+ h.link.invoke.mockResolvedValue({ id: 'task' });
+ await click('sharedTask.enterTask');
+ expect(h.link.invoke).toHaveBeenCalledWith(sharedTaskHostPeer('shared'), 'local-db:sessions:get', ['task']);
+ expect(h.router.replace).toHaveBeenCalledWith(expect.objectContaining({ pathname: '/sessions/[sessionId]' }));
+});
+it.each(['ios', 'android'] as const)('%s preserves the page on cancel and rejects an old account confirmation', async (platform) => {
+ Platform.OS = platform;
+ h.params = { sessionId: 'task', deviceId: sharedTaskHostPeer('shared') }; await render();
+ const originalPage = element.innerHTML;
+ await click('sharedTask.leave');
+ expect(h.alert).toHaveBeenCalledTimes(1);
+ expect(element.innerHTML).toBe(originalPage);
+ await click('sharedTask.leave');
+ expect(h.alert).toHaveBeenCalledTimes(1);
+ await act(async () => confirmation()[0].onPress());
+ expect(element.innerHTML).toBe(originalPage);
+ expect(h.api.leave).not.toHaveBeenCalled();
+ await click('sharedTask.leave');
+ expect(confirmation()[0].style).toBe('cancel');
+ expect(h.api.leave).not.toHaveBeenCalled();
+ const old = confirmation()[1]; setMobileAuthOwner('other');
+ await act(async () => old.onPress!()); expect(h.api.leave).not.toHaveBeenCalled();
+ setMobileAuthOwner('owner'); await click('sharedTask.leave');
+ await act(async () => confirmation()[1].onPress!());
+ expect(h.api.leave).toHaveBeenCalledWith('shared');
+ expect(h.router.replace).toHaveBeenCalledWith('/devices');
+});
+it('replaces stale guest state only for confirmed membership loss and can join again', async () => {
+ h.api.list.mockResolvedValue([{ ...owned('shared'), ownerAccountId: 'someone' }]);
+ await render(); await click('shared');
+ expect(element.textContent).toContain('sharedTask.joinedTitle');
+ await click('sharedTask.leave');
+ const oldConfirm = confirmation()[1];
+ h.api.get.mockRejectedValue(new ApiError('NETWORK_ERROR', 0, 'offline'));
+ await act(async () => vi.advanceTimersByTimeAsync(5_000));
+ expect(element.textContent).not.toContain('sharedTask.ended'); expect(h.link.closeLink).not.toHaveBeenCalled();
+ h.api.get.mockRejectedValue(new ApiError('NOT_FOUND', 404, 'gone'));
+ await act(async () => vi.advanceTimersByTimeAsync(5_000));
+ expect(element.textContent).toContain('sharedTask.ended');
+ expect(element.textContent).not.toContain('sharedTask.leave');
+ expect(h.revoked).toHaveBeenCalledWith(sharedTaskHostPeer('shared'));
+ await act(async () => oldConfirm.onPress());
+ expect(h.api.leave).not.toHaveBeenCalled();
+ await click('sharedTask.rejoin'); expect(element.querySelector('textarea')).not.toBeNull();
+});
+it('closes only the confirmed owned tasks and retains failures for retry', async () => {
+ h.params = { sessionId: 'task', deviceId: 'host' };
+ h.api.list.mockResolvedValue([owned('one'), owned('two'), { ...owned('foreign'), ownerAccountId: 'other' }]);
+ await render(); await click('sharedTask.tabOwned'); await click('sharedTask.closeAll');
+ expect(h.alert.mock.lastCall![3].cancelable).toBe(true);
+ await act(async () => h.alert.mock.lastCall![3].onDismiss());
+ expect(h.api.close).not.toHaveBeenCalled();
+ expect(element.querySelector('header')?.textContent).toContain('sharedTask.ownedTitle');
+ await click('sharedTask.closeAll');
+ expect(h.api.close).not.toHaveBeenCalled();
+ expect(h.alert.mock.lastCall![1]).toContain('Test computer');
+ h.api.close.mockImplementation((id: string) => id === 'two' ? Promise.reject(new Error('offline')) : Promise.resolve());
+ h.api.list.mockResolvedValue([owned('two')]);
+ await act(async () => confirmation()[1].onPress!());
+ expect(h.api.close.mock.calls.map(([id]) => id)).toEqual(['one', 'two']);
+ expect(element.textContent).toContain('sharedTask.closeFailedToast');
+ expect(element.textContent).toContain('two'); expect(element.textContent).not.toContain('one');
+});
+it('guards current-task close and member removal behind separate confirmations', async () => {
+ h.params = { sessionId: 'task', deviceId: 'host' }; h.link.invoke.mockResolvedValue({ available: true, detail });
+ await render(); await click('sharedTask.removeShort');
+ expect(h.link.invoke).not.toHaveBeenCalledWith('host', 'maker:shared-task', [expect.objectContaining({ action: 'remove' })]);
+ await act(async () => confirmation()[1].onPress!());
+ expect(h.link.invoke).toHaveBeenCalledWith('host', 'maker:shared-task', [{ action: 'remove', sharedTaskId: 'shared', memberId: 'member' }]);
+ await click('sharedTask.closeCurrent');
+ await act(async () => confirmation()[1].onPress!());
+ expect(h.link.invoke).toHaveBeenCalledWith('host', 'maker:shared-task', [{ action: 'close', sharedTaskId: 'shared' }]);
+});
+it('ignores an old poll after switching away from and back to the current task', async () => {
+ h.params = { sessionId: 'task', deviceId: 'host' };
+ let finishOld!: (value: unknown) => void;
+ h.link.invoke.mockImplementationOnce(() => new Promise((resolve) => { finishOld = resolve; }));
+ await render();
+ await click('sharedTask.tabOwned');
+ h.link.invoke.mockResolvedValue({ available: true, detail });
+ await click('sharedTask.tabCurrent');
+ expect(element.textContent).toContain('Design review');
+ await act(async () => finishOld({ available: true, detail: null }));
+ expect(element.textContent).toContain('Design review');
+ expect(element.textContent).toContain('sharedTask.closeCurrent');
+});
diff --git a/apps/mobile/src/__tests__/useLeaveSharedTask.test.tsx b/apps/mobile/src/__tests__/useLeaveSharedTask.test.tsx
new file mode 100644
index 0000000000..5626e51c44
--- /dev/null
+++ b/apps/mobile/src/__tests__/useLeaveSharedTask.test.tsx
@@ -0,0 +1,86 @@
+// @vitest-environment jsdom
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { beforeEach, afterEach, expect, it, vi } from 'vitest';
+import { sharedTaskHostPeer } from '@cindy/device-link';
+import { setMobileAuthOwner } from '@/auth/authOwnerGeneration';
+import { useLeaveSharedTask } from '@/device-link/useLeaveSharedTask';
+
+const h = vi.hoisted(() => ({
+ confirm: vi.fn(), api: { leave: vi.fn() }, link: { closeLink: vi.fn() },
+ remove: vi.fn(), revoke: vi.fn(), revoked: vi.fn(), left: vi.fn(), error: vi.fn(),
+}));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('expo-router', async () => {
+ const { useEffect } = await import('react');
+ return { useFocusEffect: (effect: () => void) => useEffect(effect, [effect]) };
+});
+vi.mock('@/session/useSharedTaskConfirmation', () => ({ useSharedTaskConfirmation: () => ({ confirm: h.confirm, dialog: null }) }));
+vi.mock('@/device-link/useSharedTaskApi', () => ({ useSharedTaskApi: () => h.api }));
+vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => h.link }));
+vi.mock('@/session/remoteSessionStore', () => ({ remoteSessionStore: { removeDevice: h.remove } }));
+vi.mock('@/device-link/accessRevoked', () => ({ markDeviceAccessRevoked: h.revoke }));
+vi.mock('@/device-link/revokedDevicesStore', () => ({ revokedDevicesStore: { has: h.revoked } }));
+let root: Root;
+let host: HTMLDivElement;
+let resolveConfirm: (value: boolean) => void;
+const peer = sharedTaskHostPeer('shared');
+function Harness({ enabled = true, deviceId = peer }) {
+ const exit = useLeaveSharedTask({ deviceId, enabled, onLeft: h.left, onError: h.error });
+ return <button disabled={exit.busy} onClick={() => void exit.leave()}>leave</button>;
+}
+const click = () => act(async () => host.querySelector('button')!.click());
+beforeEach(async () => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ vi.resetAllMocks(); setMobileAuthOwner('owner');
+ h.confirm.mockImplementation(() => new Promise<boolean>((resolve) => { resolveConfirm = resolve; }));
+ h.api.leave.mockResolvedValue(undefined);
+ host = document.createElement('div'); root = createRoot(host);
+ await act(async () => root.render(<Harness />));
+});
+afterEach(async () => { await act(async () => root.unmount()); });
+it('opens only one native confirmation and cancelling leaves the task untouched', async () => {
+ await click(); await click();
+ expect(h.confirm).toHaveBeenCalledTimes(1);
+ expect(h.confirm).toHaveBeenCalledWith(expect.objectContaining({ destructive: true, cancelable: true }));
+ await act(async () => resolveConfirm(false));
+ expect(h.api.leave).not.toHaveBeenCalled(); expect(h.link.closeLink).not.toHaveBeenCalled();
+ expect(h.remove).not.toHaveBeenCalled(); expect(h.left).not.toHaveBeenCalled();
+ await click(); expect(h.confirm).toHaveBeenCalledTimes(2);
+});
+it('waits for successful leave before revoking only the shared peer and leaving the page', async () => {
+ let complete!: () => void;
+ h.api.leave.mockImplementation(() => new Promise<void>((resolve) => { complete = resolve; }));
+ await click(); await act(async () => resolveConfirm(true));
+ expect(h.api.leave).toHaveBeenCalledWith('shared');
+ expect(host.querySelector('button')!.disabled).toBe(true);
+ expect(h.link.closeLink).not.toHaveBeenCalled(); expect(h.left).not.toHaveBeenCalled();
+ await act(async () => complete());
+ expect(h.revoke).toHaveBeenCalledWith(peer); expect(h.link.closeLink).toHaveBeenCalledWith(peer);
+ expect(h.remove).toHaveBeenCalledWith(peer); expect(h.left).toHaveBeenCalledOnce();
+});
+it('retains task access on failure and allows retry', async () => {
+ h.api.leave.mockRejectedValue(new Error('offline'));
+ await click(); await act(async () => resolveConfirm(true));
+ expect(h.error).toHaveBeenCalledWith('sharedTask.retry');
+ expect(h.remove).not.toHaveBeenCalled(); expect(h.revoke).not.toHaveBeenCalled();
+ expect(h.link.closeLink).not.toHaveBeenCalled(); expect(h.left).not.toHaveBeenCalled();
+ await click(); expect(h.confirm).toHaveBeenCalledTimes(2);
+});
+it.each(['account', 'menu', 'device', 'revoked'])('ignores confirmation after %s changes', async (change) => {
+ await click();
+ if (change === 'account') setMobileAuthOwner('other');
+ if (change === 'menu') await act(async () => root.render(<Harness enabled={false} />));
+ if (change === 'device') await act(async () => root.render(<Harness deviceId={sharedTaskHostPeer('other')} />));
+ if (change === 'revoked') h.revoked.mockReturnValue(true);
+ await act(async () => resolveConfirm(true));
+ expect(h.api.leave).not.toHaveBeenCalled(); expect(h.left).not.toHaveBeenCalled();
+});
+it('ignores a completed leave after switching accounts', async () => {
+ let complete!: () => void;
+ h.api.leave.mockImplementation(() => new Promise<void>((resolve) => { complete = resolve; }));
+ await click(); await act(async () => resolveConfirm(true));
+ setMobileAuthOwner('other'); await act(async () => complete());
+ expect(h.link.closeLink).not.toHaveBeenCalled(); expect(h.remove).not.toHaveBeenCalled();
+ expect(h.left).not.toHaveBeenCalled();
+});
diff --git a/apps/mobile/src/__tests__/usePromptRecommendation.test.tsx b/apps/mobile/src/__tests__/usePromptRecommendation.test.tsx
index cb56cf6337..3ef18b1f19 100644
--- a/apps/mobile/src/__tests__/usePromptRecommendation.test.tsx
+++ b/apps/mobile/src/__tests__/usePromptRecommendation.test.tsx
@@ -179,6 +179,9 @@ it('defers an occupied completion until the draft is cleared', async () => {
await render({ running: false, revision: 20 }); await advance();
expect(request).not.toHaveBeenCalled();
await act(async () => composerSource.setDocument(textComposerDocument('')));
+ // Draft occupancy is published on the next frame; let React commit it before
+ // advancing the prediction's own debounce timer.
+ await act(async () => vi.advanceTimersToNextFrame());
await advance();
expect(request).toHaveBeenCalledTimes(1);
expect(value.prompt).toBe('Suggested next step');
diff --git a/apps/mobile/src/__tests__/useSessionResourceCards.test.tsx b/apps/mobile/src/__tests__/useSessionResourceCards.test.tsx
index 9b29784d3d..01b0b850e3 100644
--- a/apps/mobile/src/__tests__/useSessionResourceCards.test.tsx
+++ b/apps/mobile/src/__tests__/useSessionResourceCards.test.tsx
@@ -6,6 +6,7 @@ import type {
RemoteResource,
RemoteResourceChangedPayload,
} from '@cindy/device-link';
+import { sharedTaskHostPeer } from '@cindy/device-link';
const h = vi.hoisted(() => ({
get: vi.fn(),
@@ -139,6 +140,19 @@ function foreground(next: string) {
h.app.listeners.forEach((listener) => listener(next));
});
}
+it('does not discover host-wide cards or retry them for a shared-task guest', async () => {
+ const peer = sharedTaskHostPeer('shared-task');
+ root = createRoot(document.createElement('div'));
+ await act(async () => root!.render(createElement(Probe, { device: peer })));
+ expect(h.manifest).not.toHaveBeenCalled();
+ expect(views.get(peer)).toMatchObject({ resources: [], failed: false, blocked: false });
+ act(() => views.get(peer)!.refresh());
+ foreground('background'); foreground('active');
+ await advance(10_000);
+ expect(h.manifest).not.toHaveBeenCalled();
+ expect(h.get).not.toHaveBeenCalled();
+ expect(h.link.subscribe).not.toHaveBeenCalled();
+});
beforeEach(() => {
vi.useFakeTimers();
vi.resetAllMocks();
diff --git a/apps/mobile/src/__tests__/useSharedTasks.test.tsx b/apps/mobile/src/__tests__/useSharedTasks.test.tsx
new file mode 100644
index 0000000000..bedf55dede
--- /dev/null
+++ b/apps/mobile/src/__tests__/useSharedTasks.test.tsx
@@ -0,0 +1,41 @@
+// @vitest-environment jsdom
+import { act, createElement } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { useSharedTasks } from '../device-link/useSharedTasks';
+
+const state = vi.hoisted(() => ({
+ auth: { isAuthenticated: true, accountGeneration: 1 },
+ link: { status: 'online', sharedTaskAvailable: false as boolean | undefined,
+ openLink: vi.fn(), closeLink: vi.fn(), invoke: vi.fn() },
+ api: { list: vi.fn(async () => []) },
+ store: { getSessions: vi.fn(() => []), removeDevice: vi.fn(), setDeviceSessions: vi.fn() },
+}));
+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => state.auth }));
+vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => state.link }));
+vi.mock('@/device-link/useSharedTaskApi', () => ({ useSharedTaskApi: () => state.api }));
+vi.mock('@/session/remoteSessionStore', () => ({ remoteSessionStore: state.store }));
+let root: Root;
+function Probe() { useSharedTasks(); return null; }
+async function render() { await act(async () => root.render(createElement(Probe))); }
+beforeEach(() => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ vi.useFakeTimers(); vi.clearAllMocks();
+ state.link.status = 'online'; state.link.sharedTaskAvailable = false;
+ root = createRoot(document.createElement('div'));
+});
+afterEach(async () => { await act(async () => root.unmount()); vi.useRealTimers(); });
+it('does not poll an old relay, resumes after upgrade, and pauses without deleting history on disconnect', async () => {
+ await render();
+ await act(async () => vi.advanceTimersByTimeAsync(15_000));
+ expect(state.api.list).not.toHaveBeenCalled();
+ state.link.sharedTaskAvailable = true; await render();
+ expect(state.api.list).toHaveBeenCalledTimes(1);
+ await act(async () => vi.advanceTimersByTimeAsync(5_000));
+ expect(state.api.list).toHaveBeenCalledTimes(2);
+ state.link.status = 'connecting'; state.link.sharedTaskAvailable = undefined; await render();
+ await act(async () => vi.advanceTimersByTimeAsync(15_000));
+ expect(state.api.list).toHaveBeenCalledTimes(2);
+ expect(state.store.removeDevice).not.toHaveBeenCalled();
+ expect(state.link.closeLink).not.toHaveBeenCalled();
+});
diff --git a/apps/mobile/src/components/MobilePrimitives.tsx b/apps/mobile/src/components/MobilePrimitives.tsx
index 26d9150652..b67f97292d 100644
--- a/apps/mobile/src/components/MobilePrimitives.tsx
+++ b/apps/mobile/src/components/MobilePrimitives.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState, type ReactNode } from 'react';
+import { useEffect, useRef, useState, type ReactNode, type Ref } from 'react';
import { useTranslation } from 'react-i18next';
import { ChevronLeft } from 'lucide-react-native';
import {
@@ -12,6 +12,7 @@ import {
type AccessibilityState,
type PressableProps,
type StyleProp,
+ type TextStyle,
type ViewStyle,
} from 'react-native';
import { Text } from '@/components/AppText';
@@ -21,7 +22,7 @@ import { fontWeight, iconSize, iconStroke, useTheme, useThemedStyles, type Theme
import { lineHeight, radius, spacing, typeScale } from '@/theme/tokens';
type PillTone = 'default' | 'primary' | 'attention';
-type MainWindowActionTone = 'danger' | 'primary' | 'secondary';
+type MainWindowActionTone = 'danger' | 'danger-solid' | 'primary' | 'secondary';
type MainWindowActionDensity = 'compact' | 'default';
export interface MainWindowAction {
@@ -587,11 +588,15 @@ export function MainWindowActionButton({
density = 'default',
grow = false,
style,
+ textStyle,
+ buttonRef,
}: {
action: MainWindowAction;
density?: MainWindowActionDensity;
grow?: boolean;
style?: StyleProp<ViewStyle>;
+ textStyle?: StyleProp<TextStyle>;
+ buttonRef?: Ref<View>;
}) {
const styles = useThemedStyles(makeStyles);
const { colors } = useTheme();
@@ -600,6 +605,7 @@ export function MainWindowActionButton({
const disabled = action.disabled || action.busy || !action.onPress;
return (
<Pressable
+ ref={buttonRef}
accessibilityLabel={action.accessibilityLabel ?? action.label}
accessibilityRole="button"
accessibilityState={{
@@ -616,6 +622,7 @@ export function MainWindowActionButton({
action.active && tone === 'secondary' && styles.mainActionButtonActive,
tone === 'primary' && styles.mainActionButtonPrimary,
tone === 'danger' && styles.mainActionButtonDanger,
+ tone === 'danger-solid' && { backgroundColor: colors.sharedTaskConfirmBackground, borderColor: colors.sharedTaskConfirmBackground },
pressed && styles.pressed,
disabled && styles.disabled,
style,
@@ -623,7 +630,7 @@ export function MainWindowActionButton({
testID={action.testID}
>
{action.busy ? (
- <ActivityIndicator color={tone === 'primary' ? colors.ctaText : colors.textSecondary} size="small" />
+ <ActivityIndicator color={tone === 'danger-solid' ? colors.sharedTaskConfirmForeground : tone === 'primary' ? colors.ctaText : colors.textSecondary} size="small" />
) : (
<Text
numberOfLines={1}
@@ -632,6 +639,8 @@ export function MainWindowActionButton({
compact && styles.mainActionButtonTextCompact,
tone === 'primary' && styles.mainActionButtonPrimaryText,
tone === 'danger' && styles.mainActionButtonDangerText,
+ tone === 'danger-solid' && { color: colors.sharedTaskConfirmForeground },
+ textStyle,
]}
>
{action.label}
diff --git a/apps/mobile/src/components/connectionBannerVisibility.ts b/apps/mobile/src/components/connectionBannerVisibility.ts
index 801cfad0c1..c65b927b17 100644
--- a/apps/mobile/src/components/connectionBannerVisibility.ts
+++ b/apps/mobile/src/components/connectionBannerVisibility.ts
@@ -1,3 +1,5 @@
+import { isSharedTaskPeer } from '@cindy/device-link';
+
/**
* connectionBannerVisibility.ts — ConnectionBanner 可见性判定的决策核。
* 纯函数(不依赖 React / react-native),node 可单测;useShowConnectionBanner
@@ -55,6 +57,20 @@ export function resolveConnectionBannerSyncActionVisibility(input: {
export type HomeDeviceFailure = { deviceId: string; deviceName: string; error: string };
export type HomeConnectionError = string | HomeDeviceFailure | HomeDeviceFailure[] | null;
+/** Shared task peers have scoped membership checks, not account device presence. */
+export function resolveHomeDeviceDisconnected(
+ devices: readonly { deviceId: string | null; sessionCount: number; available: boolean }[],
+ selectedDeviceId: string | null,
+ connecting: boolean,
+): boolean {
+ if (connecting) return false;
+ const scoped = devices.filter((device) => device.deviceId !== null
+ && !isSharedTaskPeer(device.deviceId)
+ && (!selectedDeviceId || device.deviceId === selectedDeviceId));
+ return scoped.some((device) => device.sessionCount > 0)
+ && !scoped.some((device) => device.available);
+}
+
/** A recovering device must not mask another device's actionable failure on Home. */
export function resolveHomeConnectionFeedback(
error: HomeConnectionError,
diff --git a/apps/mobile/src/config/env.ts b/apps/mobile/src/config/env.ts
index 2071bf25f2..0a3290e1e3 100644
--- a/apps/mobile/src/config/env.ts
+++ b/apps/mobile/src/config/env.ts
@@ -33,8 +33,22 @@ const configuredBuildEnv = (configuredExpoExtra.xdtProductionEnv ??
{}) as Record<string, string>;
const configuredRegionGoogle = configuredExpoExtra.cindy?.google;
-function configuredValue(key: string): string {
- return process.env[key]?.trim() || configuredBuildEnv[key]?.trim() || '';
+// Expo only inlines static property reads; Hermes has no runtime shell env.
+const configuredPublicEnv = {
+ EXPO_PUBLIC_CINDY_AUTH_REGION: process.env.EXPO_PUBLIC_CINDY_AUTH_REGION,
+ EXPO_PUBLIC_CINDY_AUTH_BASE_URL: process.env.EXPO_PUBLIC_CINDY_AUTH_BASE_URL,
+ EXPO_PUBLIC_XDT_DEVICE_LINK_API_BASE_URL:
+ process.env.EXPO_PUBLIC_XDT_DEVICE_LINK_API_BASE_URL,
+ EXPO_PUBLIC_XDT_MOBILE_VOICE_LITELLM_BASE_URL:
+ process.env.EXPO_PUBLIC_XDT_MOBILE_VOICE_LITELLM_BASE_URL,
+ EXPO_PUBLIC_CINDY_VOICE_API_BASE_URL:
+ process.env.EXPO_PUBLIC_CINDY_VOICE_API_BASE_URL,
+ EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL:
+ process.env.EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL,
+};
+
+function configuredValue(key: keyof typeof configuredPublicEnv): string {
+ return configuredPublicEnv[key]?.trim() || configuredBuildEnv[key]?.trim() || '';
}
export const AUTH_REGION: CindyAuthRegion = (() => {
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index d746eb3b8d..577ca7a978 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -9,6 +9,10 @@ import { AppState, Platform } from 'react-native';
import { mobileDebugLog } from '@/debug/mobileDebugLog';
import {
DeviceLinkClient,
+ isSharedTaskPeer,
+ probeSharedTaskHost,
+ sharedTaskTopics,
+ SHARED_TASK_CAPABILITY,
DeviceLinkError,
CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1,
CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1,
@@ -35,6 +39,8 @@ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, use
import { deviceLinkWsUrl, DEVICE_LINK_API_BASE_URL } from '@/config/env';
import { MOBILE_VISUAL_MOCK_ENABLED } from '@/config/env';
import { useAuth } from '@/auth/AuthContext';
+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
+import { useSharedTaskApi } from './useSharedTaskApi';
import {
applyAccessRevokedFrame,
withAccessRevokedHandling,
@@ -153,6 +159,8 @@ import { createVisualMockDeviceLinkContext, seedVisualMockStore } from '@/debug/
export interface DeviceLinkContextValue {
status: DeviceLinkStatus;
+ /** Current online relay capability; undefined while not connected. */
+ sharedTaskAvailable?: boolean;
/** Peers with queued, running, or retrying recovery work. Read-only UI projection. */
recoveringDeviceIds: ReadonlySet<string>;
/** 连接层可分类的失败原因(鉴权失效/被顶号/超限/版本不符);null = 无异常 */
@@ -204,6 +212,7 @@ const recoveryDiagnostics = new WeakMap<DeviceLinkClient, ReturnType<typeof crea
* 被控端按能力缺失降级)。被控端只在看到对应能力后才发送新 wire 形状。
*/
const CONTROLLER_CAPABILITIES = [
+ SHARED_TASK_CAPABILITY,
CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1,
CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,
// maker:event 微批:被控端把同一会话的连续事件合并成一帧,本端拆包后逐条消费
@@ -342,6 +351,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
}
const auth = useAuth();
+ const sharedTaskApi = useSharedTaskApi();
const currentDataOwnerIdRef = useRef<string | null>(auth.user?.id ?? null);
currentDataOwnerIdRef.current = auth.user?.id ?? null;
const clientRef = useRef<DeviceLinkClient | null>(null);
@@ -411,6 +421,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
// 发起代仍为当前代时登记远端 ACK,避免迟到成功覆盖较新的 unsubscribe。
const backgroundReleaseGenerationRef = useRef(0);
const [status, setStatus] = useState<DeviceLinkStatus>('stopped');
+ const [sharedTaskAvailable, setSharedTaskAvailable] = useState<boolean | undefined>();
const [connectionIssue, setConnectionIssue] = useState<DeviceLinkConnectionIssue | null>(null);
const [presenceVersion, setPresenceVersion] = useState(0);
const [connectionEpoch, setConnectionEpoch] = useState(0);
@@ -498,6 +509,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
topics: readonly Topic[],
) => {
const releaseGeneration = backgroundReleaseGenerationRef.current;
+ topics = sharedTaskTopics(deviceId, topics);
const record = recoveryDiagnostics.get(client)?.capture(deviceId, connectionEpochRef.current);
await confirmTrackedSubscription({
isCurrent: () => presenceAvailableByDeviceRef.current.get(deviceId) !== false && !backgroundReleaseInFlightRef.current
@@ -532,6 +544,16 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
const probeUnresponsiveDevice = useCallback(
async (client: DeviceLinkClient, deviceId: string): Promise<void> => {
try {
+ if (isSharedTaskPeer(deviceId)) {
+ const owner = getMobileAuthOwner();
+ await probeSharedTaskHost(deviceId, {
+ isCurrent: () => clientRef.current === client && isMobileAuthOwnerCurrent(owner),
+ get: (sharedTaskId) => sharedTaskApi.get(sharedTaskId),
+ openLink: () => sendOpenLinkOnce(client, deviceId, true).request,
+ invoke: (channel, args) => sendInvokeWithAccessHandling(client, deviceId, channel, args, { allowProbe: true }),
+ });
+ return;
+ }
await sendOpenLinkOnce(client, deviceId, true).request;
await sendInvokeWithAccessHandling(
client,
@@ -544,7 +566,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
// swallow — settle 已在 sendOpenLink / sendInvoke 内完成。
}
},
- [sendOpenLinkOnce],
+ [sendOpenLinkOnce, sharedTaskApi],
);
const hasOutboundPeerRecoveryIntent = useCallback((
@@ -686,6 +708,15 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
wipeUnavailableDeviceMirror(deviceId);
},
onDeviceUnavailable: (deviceId) => {
+ if (isSharedTaskPeer(deviceId)) {
+ // Logical peers have no same-account presence entry. Preserve the
+ // existing bounded peer retry instead of waiting for an impossible
+ // physical-presence transition. Never restart the shared relay.
+ remoteSubscribedTopicsRef.current.delete(deviceId);
+ clearDeviceResponsivenessTrackingFor(deviceId);
+ setPresenceVersion((version) => version + 1);
+ return;
+ }
publishPresenceAvailabilityMutation(deviceId, (availabilityByDevice) => {
availabilityByDevice.set(deviceId, false);
});
@@ -711,7 +742,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
const releaseGeneration = backgroundReleaseGenerationRef.current;
return rebuildSessionSnapshot(client, deviceId, sessionId, epoch, {
...opts,
- subscriptionIdentity: remoteSubscribedTopicsRef.current.identity(deviceId, ['sessions', `session:${sessionId}`]),
+ subscriptionIdentity: remoteSubscribedTopicsRef.current.identity(deviceId, sharedTaskTopics(deviceId, ['sessions', `session:${sessionId}`])),
}, () => client === clientRef.current
&& client.getStatus() === 'online'
&& connectionEpochRef.current === epoch
@@ -812,6 +843,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
presenceUnavailableVerdictsRef.current.clear();
backgroundReleaseInFlightRef.current = false;
setStatus('stopped');
+ setSharedTaskAvailable(undefined);
setConnectionIssue(null);
// 登出 / 进程内切号:清掉所有 per-account 残留,避免下一个账号串到上一个账号的数据。
// - 供应商目录是 module 级单例缓存(useDeviceProviders 按 deviceId 命中),不随组件卸载清;
@@ -840,6 +872,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
getWsUrl: () => deviceLinkWsUrl(),
getToken: auth.getAccessToken,
getHello: () => ({
+ capabilities: [SHARED_TASK_CAPABILITY],
deviceName: mobileDeviceName(),
platform: Platform.OS,
appVersion: Constants.expoConfig?.version ?? '0.0.0',
@@ -894,6 +927,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
const offIssue = client.onConnectionIssue(setConnectionIssue);
const offStatus = client.onStatusChange((next) => {
setStatus(next);
+ setSharedTaskAvailable(next === 'online' ? client.hasServerCapability(SHARED_TASK_CAPABILITY) : undefined);
if (next !== 'online') {
catalogRefresh.clear();
openLinkInFlightRef.current.clear();
@@ -1042,12 +1076,14 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
const offFrame = client.onFrame((env) => routeFrame(env, {
currentDataOwnerId: currentDataOwnerIdRef.current,
onAccessRevoked: (deviceId) => {
+ if (isSharedTaskPeer(deviceId)) setPresenceVersion((version) => version + 1);
catalogRefresh.cancel(deviceId);
remoteSubscribedTopicsRef.current.delete(deviceId);
forcedPeerRecoveryIntentRef.current.cancel(deviceId);
peerRecoverySchedulerRef.current?.cancel(deviceId);
},
onLinkClosed: (deviceId, reason) => {
+ if (isSharedTaskPeer(deviceId)) setPresenceVersion((version) => version + 1);
catalogRefresh.cancel(deviceId);
resetRemoteProjectOrderPushFence(deviceId);
updateRehydrateSuppressionOnLinkClose(
@@ -1141,6 +1177,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
client.start();
const offResponseEvidence = subscribeRemoteResponseEvidence((deviceId) => {
+ if (client === clientRef.current && isSharedTaskPeer(deviceId)) setPresenceVersion((version) => version + 1);
const currentEpoch = capturePresenceAvailabilityEpoch(
remoteResponseEvidenceEpochs,
deviceId,
@@ -1367,6 +1404,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
}, [sendOpenLinkOnce]);
const subscribe = useCallback(async (owner: string, deviceId: string, topics: string[]) => {
+ topics = sharedTaskTopics(deviceId, topics);
// `owner` is the stable id of the mounted consumer (e.g. `session:<id>`). Tracking is
// idempotent per (owner, topic), so resync/retry resubscribes don't accumulate. The
// server subscribe is idempotent, so it's safe to (re)send the requested topics.
@@ -1379,6 +1417,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
}, [sendTrackedSubscribe]);
const unsubscribe = useCallback(async (owner: string, deviceId: string, topics: string[]) => {
+ topics = sharedTaskTopics(deviceId, topics);
// Drop only this owner's hold; release (server unsubscribe) the topics whose last owner
// just left. If a focused screen blurs before subscribe acknowledgement, a later cleanup may
// ask to unsubscribe an already-released owner; resend only topics that are currently unheld
@@ -1400,18 +1439,20 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
}, []);
const getPresenceAvailability = useCallback((deviceId: string): boolean | null => (
- presenceAvailableByDeviceRef.current.get(deviceId) ?? null
+ isSharedTaskPeer(deviceId) ? clientRef.current?.isLinkReady(deviceId) ?? false
+ : presenceAvailableByDeviceRef.current.get(deviceId) ?? null
), []);
const value = useMemo<DeviceLinkContextValue>(() => ({
beginBackgroundTransition,
status,
+ sharedTaskAvailable,
recoveringDeviceIds,
connectionIssue,
presenceVersion,
connectionEpoch,
lastPresenceSnapshot,
- getSubscriptionIdentity: (deviceId, topics) => remoteSubscribedTopicsRef.current.identity(deviceId, topics),
+ getSubscriptionIdentity: (deviceId, topics) => remoteSubscribedTopicsRef.current.identity(deviceId, sharedTaskTopics(deviceId, topics)),
getPresenceAvailability,
readDeviceList,
openLink,
@@ -1436,6 +1477,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
reopenLink,
presenceVersion,
status,
+ sharedTaskAvailable,
subscribe,
unsubscribe,
subscribeRemoteAgentRoster,
diff --git a/apps/mobile/src/device-link/accessRevoked.ts b/apps/mobile/src/device-link/accessRevoked.ts
index 859725d552..6b8b4b8db4 100644
--- a/apps/mobile/src/device-link/accessRevoked.ts
+++ b/apps/mobile/src/device-link/accessRevoked.ts
@@ -47,9 +47,13 @@ export async function withAccessRevokedHandling<T>(
deviceId: string,
operation: () => Promise<T>,
): Promise<T> {
+ const revocationToken = revokedDevicesStore.getRevocationToken(deviceId);
try {
const result = await operation();
- clearDeviceAccessRevoked(deviceId);
+ // A response started before a new revocation cannot restore access.
+ if (revokedDevicesStore.getRevocationToken(deviceId) === revocationToken) {
+ clearDeviceAccessRevoked(deviceId);
+ }
return result;
} catch (err) {
if (isAccessRevokedError(err)) markDeviceAccessRevoked(deviceId);
diff --git a/apps/mobile/src/device-link/revokedDevicesStore.ts b/apps/mobile/src/device-link/revokedDevicesStore.ts
index abae6faa47..1174a53e9f 100644
--- a/apps/mobile/src/device-link/revokedDevicesStore.ts
+++ b/apps/mobile/src/device-link/revokedDevicesStore.ts
@@ -1,6 +1,7 @@
import { useSyncExternalStore } from 'react';
const revoked = new Set<string>();
+const revocationTokens = new Map<string, object>();
let snapshot: ReadonlySet<string> = new Set();
const listeners = new Set<() => void>();
@@ -16,17 +17,20 @@ function emit(): void {
*/
export const revokedDevicesStore = {
markRevoked(deviceId: string): void {
+ if (deviceId) revocationTokens.set(deviceId, {});
if (!deviceId || revoked.has(deviceId)) return;
revoked.add(deviceId);
emit();
},
clearRevoked(deviceId: string): void {
+ revocationTokens.delete(deviceId);
if (!revoked.delete(deviceId)) return;
emit();
},
clearAll(): void {
+ revocationTokens.clear();
if (revoked.size === 0) return;
revoked.clear();
emit();
@@ -36,6 +40,10 @@ export const revokedDevicesStore = {
return revoked.has(deviceId);
},
+ getRevocationToken(deviceId: string): object | undefined {
+ return revocationTokens.get(deviceId);
+ },
+
getSnapshot(): ReadonlySet<string> {
return snapshot;
},
diff --git a/apps/mobile/src/device-link/sharedTaskAccessWatch.ts b/apps/mobile/src/device-link/sharedTaskAccessWatch.ts
new file mode 100644
index 0000000000..1f264c3ab8
--- /dev/null
+++ b/apps/mobile/src/device-link/sharedTaskAccessWatch.ts
@@ -0,0 +1,41 @@
+import { ApiError } from '@/api/client';
+
+/** Only an authoritative missing membership ends access; network failures do not. */
+export function isSharedTaskGone(error: unknown): boolean {
+ return error instanceof ApiError && error.status === 404 && error.code === 'NOT_FOUND';
+}
+
+/** Reconcile an open guest task when the relay can no longer route its revoke frame. */
+export function watchSharedTaskAccess(options: {
+ sharedTaskId: string;
+ sessionId: string;
+ read(): Promise<{ sharedTaskId: string; sessionId: string; status: string }>;
+ isCurrent(): boolean;
+ onRevoked(): void;
+}) {
+ let stopped = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const current = () => !stopped && options.isCurrent();
+ const revoke = () => {
+ if (!current()) return;
+ stopped = true;
+ options.onRevoked();
+ };
+ const check = async () => {
+ if (!current()) return;
+ try {
+ const detail = await options.read();
+ if (!current()) return;
+ if (detail.sharedTaskId === options.sharedTaskId && detail.sessionId === options.sessionId
+ && detail.status === 'closed') revoke();
+ } catch (error) {
+ // Timeout, offline, expired login and unsupported routes are not revocation.
+ if (isSharedTaskGone(error)) revoke();
+ } finally {
+ // A slow read occupies the only request slot; no interval can pile up reads.
+ if (current()) timer = setTimeout(() => void check(), 5_000);
+ }
+ };
+ void check();
+ return () => { stopped = true; if (timer !== undefined) clearTimeout(timer); };
+}
diff --git a/apps/mobile/src/device-link/sharedTaskCompatibility.ts b/apps/mobile/src/device-link/sharedTaskCompatibility.ts
new file mode 100644
index 0000000000..59d699ed74
--- /dev/null
+++ b/apps/mobile/src/device-link/sharedTaskCompatibility.ts
@@ -0,0 +1,14 @@
+/** Transport codes and anchored serialized host IPC codes, never arbitrary text. */
+export function sharedTaskErrorKey(error: unknown) {
+ let code = error && typeof error === 'object' ? (error as { code?: unknown }).code : undefined;
+ if (code === undefined || code === 'IPC_ERROR') {
+ const message = error instanceof Error ? error.message : '';
+ code = /^(?:Error invoking remote method '[^']+': Error: )?\[([A-Z0-9_]+)\]/.exec(message)?.[1];
+ }
+ if (code === 'SHARED_TASK_HOST_LIMIT') return 'sharedTask.hostLimit';
+ if (code === 'SHARED_TASK_JOIN_LIMIT') return 'sharedTask.joinLimit';
+ if (code === 'SHARED_TASK_GUEST_LIMIT') return 'sharedTask.guestLimit';
+ return code === 'CHANNEL_NOT_ALLOWED' || code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED'
+ || code === 'VERSION_MISMATCH' || code === 'DEVICE_LINK_VERSION_MISMATCH'
+ || code === 'UNSUPPORTED_CAPABILITY' ? 'sharedTask.upgrade' : 'sharedTask.retry';
+}
diff --git a/apps/mobile/src/device-link/useLeaveSharedTask.ts b/apps/mobile/src/device-link/useLeaveSharedTask.ts
new file mode 100644
index 0000000000..1ebf416b7b
--- /dev/null
+++ b/apps/mobile/src/device-link/useLeaveSharedTask.ts
@@ -0,0 +1,60 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useFocusEffect } from 'expo-router';
+import { useTranslation } from 'react-i18next';
+import { parseSharedTaskPeer } from '@cindy/device-link';
+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
+import { useSharedTaskConfirmation } from '@/session/useSharedTaskConfirmation';
+import { remoteSessionStore } from '@/session/remoteSessionStore';
+import { useDeviceLink } from './DeviceLinkContext';
+import { useSharedTaskApi } from './useSharedTaskApi';
+import { sharedTaskErrorKey } from './sharedTaskCompatibility';
+import { markDeviceAccessRevoked } from './accessRevoked';
+import { revokedDevicesStore } from './revokedDevicesStore';
+
+/** Exit directly from task details; cancelling never navigates or reloads the task. */
+export function useLeaveSharedTask({ deviceId, enabled, onLeft, onError }: {
+ deviceId?: string; enabled: boolean; onLeft(): void; onError(message: string): void;
+}) {
+ const { t } = useTranslation();
+ const api = useSharedTaskApi();
+ const confirmation = useSharedTaskConfirmation();
+ const { closeLink } = useDeviceLink();
+ const pending = useRef<object | null>(null);
+ const [busy, setBusy] = useState(false);
+ useEffect(() => {
+ pending.current = null; setBusy(false);
+ return () => { pending.current = null; };
+ }, [deviceId, enabled]);
+ useFocusEffect(useCallback(() => {
+ setBusy(false);
+ return () => { pending.current = null; };
+ }, []));
+ const leave = async () => {
+ const peer = deviceId ? parseSharedTaskPeer(deviceId) : null;
+ if (!enabled || !deviceId || peer?.role !== 'host' || pending.current || revokedDevicesStore.has(deviceId)) return;
+ const owner = getMobileAuthOwner();
+ const request = {};
+ pending.current = request;
+ const current = () => pending.current === request && isMobileAuthOwnerCurrent(owner);
+ try {
+ const accepted = await confirmation.confirm({
+ title: t('sharedTask.leaveTitle'), message: t('sharedTask.leaveBody'),
+ cancelLabel: t('sharedTask.leaveKeep'), confirmLabel: t('sharedTask.leave'),
+ destructive: true, cancelable: true,
+ });
+ if (!accepted || !current() || revokedDevicesStore.has(deviceId)) return;
+ setBusy(true);
+ await api.leave(peer.sharedTaskId);
+ if (!current()) return;
+ markDeviceAccessRevoked(deviceId);
+ closeLink(deviceId);
+ remoteSessionStore.removeDevice(deviceId);
+ onLeft();
+ } catch (error) {
+ if (current()) onError(t(sharedTaskErrorKey(error)));
+ } finally {
+ if (pending.current === request) { pending.current = null; setBusy(false); }
+ }
+ };
+ return { leave, busy, dialog: confirmation.dialog };
+}
diff --git a/apps/mobile/src/device-link/useSharedTaskAccess.ts b/apps/mobile/src/device-link/useSharedTaskAccess.ts
new file mode 100644
index 0000000000..c4e30c7475
--- /dev/null
+++ b/apps/mobile/src/device-link/useSharedTaskAccess.ts
@@ -0,0 +1,32 @@
+import { useCallback } from 'react';
+import { useFocusEffect } from 'expo-router';
+import { parseSharedTaskPeer } from '@cindy/device-link';
+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
+import { useAuth } from '@/auth/AuthContext';
+import { markDeviceAccessRevoked } from './accessRevoked';
+import { useDeviceLink } from './DeviceLinkContext';
+import { useSharedTaskApi } from './useSharedTaskApi';
+import { revokedDevicesStore } from './revokedDevicesStore';
+import { watchSharedTaskAccess } from './sharedTaskAccessWatch';
+
+/** Only the foreground guest task reconciles membership; other peers are untouched. */
+export function useSharedTaskAccess(deviceId: string | undefined, sessionId: string, appActive: boolean) {
+ const api = useSharedTaskApi();
+ const { accountGeneration } = useAuth();
+ const { status, sharedTaskAvailable, closeLink } = useDeviceLink();
+ useFocusEffect(useCallback(() => {
+ const peer = deviceId ? parseSharedTaskPeer(deviceId) : null;
+ if (!appActive || status !== 'online' || sharedTaskAvailable !== true
+ || !deviceId || peer?.role !== 'host' || revokedDevicesStore.has(deviceId)) return;
+ const owner = getMobileAuthOwner();
+ return watchSharedTaskAccess({
+ sharedTaskId: peer.sharedTaskId, sessionId,
+ read: () => api.get(peer.sharedTaskId),
+ isCurrent: () => isMobileAuthOwnerCurrent(owner),
+ onRevoked: () => {
+ markDeviceAccessRevoked(deviceId);
+ closeLink(deviceId);
+ },
+ });
+ }, [accountGeneration, api, appActive, closeLink, deviceId, sessionId, sharedTaskAvailable, status]));
+}
diff --git a/apps/mobile/src/device-link/useSharedTaskApi.ts b/apps/mobile/src/device-link/useSharedTaskApi.ts
new file mode 100644
index 0000000000..1b0b4b7032
--- /dev/null
+++ b/apps/mobile/src/device-link/useSharedTaskApi.ts
@@ -0,0 +1,20 @@
+import { useMemo } from 'react';
+import { createSharedTaskApi, SharedTaskScopeChangedError } from '@cindy/device-link';
+import { useAuth } from '@/auth/AuthContext';
+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
+import { DEVICE_LINK_API_BASE_URL } from '@/config/env';
+
+export function useSharedTaskApi() {
+ const { apiFetch, accountGeneration } = useAuth();
+ return useMemo(() => createSharedTaskApi({
+ captureScope() {
+ const owner = getMobileAuthOwner();
+ return { isCurrent: () => !!owner.accountId && isMobileAuthOwnerCurrent(owner) };
+ },
+ request(path, options) {
+ if (!options.isCurrent()) throw new SharedTaskScopeChangedError();
+ return apiFetch(path, { baseUrl: DEVICE_LINK_API_BASE_URL, method: options.method,
+ body: options.body, cache: 'no-store', timeoutMs: 12_000 });
+ },
+ }), [apiFetch, accountGeneration]);
+}
diff --git a/apps/mobile/src/device-link/useSharedTasks.ts b/apps/mobile/src/device-link/useSharedTasks.ts
new file mode 100644
index 0000000000..e24d1a77e8
--- /dev/null
+++ b/apps/mobile/src/device-link/useSharedTasks.ts
@@ -0,0 +1,53 @@
+import { useEffect } from 'react';
+import { isSharedTaskPeer, sharedTaskHostPeer } from '@cindy/device-link';
+import { useAuth } from '@/auth/AuthContext';
+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
+import { remoteSessionStore } from '@/session/remoteSessionStore';
+import type { RemoteSession } from '@/session/types';
+import { useDeviceLink } from './DeviceLinkContext';
+import { useSharedTaskApi } from './useSharedTaskApi';
+
+/** Shared tasks have their own account authority list, separate from paired devices. */
+export function useSharedTasks(): void {
+ const { accountGeneration, isAuthenticated } = useAuth();
+ const api = useSharedTaskApi();
+ const { openLink, closeLink, invoke, status, sharedTaskAvailable } = useDeviceLink();
+ useEffect(() => {
+ if (!isAuthenticated || status !== 'online' || sharedTaskAvailable !== true) return;
+ const owner = getMobileAuthOwner();
+ let disposed = false;
+ let busy = false;
+ const current = () => !disposed && isMobileAuthOwnerCurrent(owner);
+ const poll = async () => {
+ if (busy || !current()) return;
+ busy = true;
+ try {
+ const tasks = (await api.list()).filter((task) => task.ownerAccountId !== owner.accountId);
+ if (!current()) return;
+ const peers = new Set(tasks.map((task) => sharedTaskHostPeer(task.sharedTaskId)));
+ for (const task of remoteSessionStore.getSessions()) {
+ const peer = task.deviceLinkDeviceId;
+ if (peer && isSharedTaskPeer(peer) && !peers.has(peer)) {
+ closeLink(peer);
+ remoteSessionStore.removeDevice(peer);
+ }
+ }
+ for (const task of tasks) {
+ if (!current()) return;
+ const peer = sharedTaskHostPeer(task.sharedTaskId);
+ try {
+ await openLink(peer);
+ if (!current()) return;
+ const session = await invoke<RemoteSession>(peer, 'local-db:sessions:get', [task.sessionId]);
+ if (!current()) return;
+ if (session.id === task.sessionId) remoteSessionStore.setDeviceSessions(peer, task.title, [session]);
+ } catch { /* Keep offline history; only the authority list removes membership. */ }
+ }
+ } catch { /* A transient authority failure is not evidence of departure. */ }
+ finally { busy = false; }
+ };
+ void poll();
+ const timer = setInterval(() => { void poll(); }, 5_000);
+ return () => { disposed = true; clearInterval(timer); };
+ }, [accountGeneration, api, closeLink, invoke, isAuthenticated, openLink, sharedTaskAvailable, status]);
+}
diff --git a/apps/mobile/src/i18n/locales/en/index.ts b/apps/mobile/src/i18n/locales/en/index.ts
index 90203c8da8..a51e2acd9f 100644
--- a/apps/mobile/src/i18n/locales/en/index.ts
+++ b/apps/mobile/src/i18n/locales/en/index.ts
@@ -18,6 +18,7 @@ import interaction from './interaction.json';
import message from './message.json';
import models from './models.json';
import session from './session.json';
+import sharedTask from './sharedTask.json';
import settings from './settings.json';
import shared from './shared.json';
import startup from './startup.json';
@@ -37,6 +38,7 @@ export default {
message,
models,
session,
+ sharedTask,
settings,
shared,
startup,
diff --git a/apps/mobile/src/i18n/locales/en/sharedTask.json b/apps/mobile/src/i18n/locales/en/sharedTask.json
new file mode 100644
index 0000000000..54688e0b4e
--- /dev/null
+++ b/apps/mobile/src/i18n/locales/en/sharedTask.json
@@ -0,0 +1,89 @@
+{
+ "waitingHost": "Waiting for the host to respond. You can continue sending messages.",
+ "join": "Join Shared Task",
+ "joinHint": "Paste an invitation to open the shared task.",
+ "login": "Sign in to Cindy to join a task.",
+ "openTask": "Open Task",
+ "notJoined": "This task is no longer shared with you.",
+ "invitation": "Invitation",
+ "invalid": "Enter a valid invitation and your display name.",
+ "nickname": "Display Name",
+ "requestJoin": "Join",
+ "dismiss": "Close Dialog",
+ "title": "Share Task",
+ "hostLimit": "You can host up to 2 shared tasks at a time. Close one before trying again.",
+ "joinLimit": "You can join up to 2 shared tasks at a time. Leave one before trying again.",
+ "guestLimit": "This shared task already has 2 guests. You cannot join it yet.",
+ "retry": "Could not update sharing. Check your connection and retry.",
+ "upgrade": "Sharing requires updated clients and server.",
+ "sharing": "Guests can read all task content and use the Agent with this task’s permissions. Existing approvals stay with the owner.",
+ "open": "Start Sharing",
+ "members": "Members: {{count}}",
+ "host": "Host",
+ "remove": "Remove Guest",
+ "leave": "Leave Shared Task",
+ "invite": "Copy Invitation",
+ "close": "Stop Sharing",
+ "invitationCopied": "Invitation copied",
+ "invitationCopyFailed": "The invitation was created but could not be copied. Return to this window and try again.",
+ "accessEndedBody": "You can no longer access this shared task. To join again, ask the host for a new invitation.",
+ "joinIntro": "Paste the invitation from the host to enter the same task.",
+ "invitationPlaceholder": "Paste the invitation",
+ "joinNickname": "Your Name in This Task",
+ "nicknamePlaceholder": "What should we call you?",
+ "joinNotice": "After joining, you can view the full history and message the Agent directly, without waiting for host approval.",
+ "joinedTitle": "Joined “{{title}}”",
+ "joined": "Joined Shared Task",
+ "joinedBody": "You can view earlier messages, tool results and attachments, and message the same Agent.",
+ "enterTask": "Enter Task",
+ "inviteBoxTitle": "Send the invitation to your teammates",
+ "roleGuest": "Guest",
+ "removeShort": "Remove",
+ "removeNamedTitle": "Remove {{name}}?",
+ "shareCurrent": "Share Current Task",
+ "manage": "Manage",
+ "guestCount": "{{count}} guests",
+ "ownedTitle": "Shares I Started",
+ "ended": "Sharing Ended",
+ "rejoin": "Join With a New Invitation",
+ "otherDevice": "Other Computer",
+ "hostDevice": "Host Computer",
+ "runsOnHostDevice": "Running on the host computer",
+ "remoteHostOfflineNote": "Sharing closes when the host computer goes offline. Start sharing again and send a new invitation after reconnecting.",
+ "tabCurrent": "Current Task",
+ "tabOwned": "Shared by Me",
+ "startIntro": "Invite a partner to read everything in this task and work with the same Agent.",
+ "runsOnThisDevice": "Runs on this device",
+ "inviteNotice": "Anyone holding the invitation can join after signing in, with the same Agent access as the host.",
+ "offlineAutoClose": "Sharing closes automatically when the host goes offline.",
+ "inviteBoxHint": "Full history and messaging after joining",
+ "membersWithLimit": "Members · {{count}} (up to 2 guests)",
+ "me": "Me",
+ "thisDevice": "This device",
+ "roleHost": "Host",
+ "hostOfflineNote": "Sharing closes automatically when this device goes offline. Re-enable sharing and invite again after coming back.",
+ "closeCurrent": "Stop Sharing This Task",
+ "sharingBadge": "Sharing",
+ "ownedIntro": "{{count}} tasks you share in this region",
+ "ownedEmptyTitle": "Nothing is being shared",
+ "ownedEmptyHint": "Open any task and click “Share Task” to invite a partner.",
+ "closeAll": "Stop All Sharing ({{count}})",
+ "closeAllNote": "After everything is closed, guests lose access and old invitations expire. Task history and Agent work are kept.",
+ "closeAllTitle": "Stop all sharing?",
+ "closeAllBody": "This closes every task you share in this region, including tasks hosted on other computers.",
+ "closeAllKeep": "Keep Sharing",
+ "closeAllAction": "Close {{count}} shares",
+ "closeAllScopeNote": "Task history and Agent work are kept; tasks you joined stay unaffected.",
+ "closeOneTitle": "Stop sharing this task?",
+ "closeOneBody": "All guests will lose access and the invitation will expire.",
+ "removeTitle": "Remove this guest?",
+ "removeBody": "The guest will lose access. Rejoining requires a new invitation from the host.",
+ "removeKeep": "Keep Guest",
+ "leaveTitle": "Leave this shared task?",
+ "leaveBody": "You will lose access to the task. Rejoining requires a new invitation from the host.",
+ "leaveKeep": "Stay in Task",
+ "hostOfflineTitle": "Host is offline",
+ "hostOfflineBody": "Sharing for this task is closed and the invitation has expired. Ask the host to share again and send a new invitation.",
+ "closedToast": "Stopped sharing for {{count}} tasks",
+ "closeFailedToast": "Some shares could not be closed ({{count}}). Retry later."
+}
diff --git a/apps/mobile/src/i18n/locales/ja/index.ts b/apps/mobile/src/i18n/locales/ja/index.ts
index 90203c8da8..a51e2acd9f 100644
--- a/apps/mobile/src/i18n/locales/ja/index.ts
+++ b/apps/mobile/src/i18n/locales/ja/index.ts
@@ -18,6 +18,7 @@ import interaction from './interaction.json';
import message from './message.json';
import models from './models.json';
import session from './session.json';
+import sharedTask from './sharedTask.json';
import settings from './settings.json';
import shared from './shared.json';
import startup from './startup.json';
@@ -37,6 +38,7 @@ export default {
message,
models,
session,
+ sharedTask,
settings,
shared,
startup,
diff --git a/apps/mobile/src/i18n/locales/ja/sharedTask.json b/apps/mobile/src/i18n/locales/ja/sharedTask.json
new file mode 100644
index 0000000000..3de6631dff
--- /dev/null
+++ b/apps/mobile/src/i18n/locales/ja/sharedTask.json
@@ -0,0 +1,89 @@
+{
+ "waitingHost": "ホストの対応を待っています。引き続きメッセージを送信できます。",
+ "join": "共有セッションに参加",
+ "joinHint": "招待を貼り付けて共有セッションを開きます。",
+ "login": "セッションに参加するには Cindy にログインしてください。",
+ "openTask": "セッションを開く",
+ "notJoined": "この共有セッションにはアクセスできません。",
+ "invitation": "招待",
+ "invalid": "有効な招待と表示名を入力してください。",
+ "nickname": "表示名",
+ "requestJoin": "参加",
+ "dismiss": "ダイアログを閉じる",
+ "title": "セッションを共有",
+ "hostLimit": "同時に共有できるタスクは 2 件までです。共有を 1 件終了してから再試行してください。",
+ "joinLimit": "同時に参加できる共有タスクは 2 件までです。1 件から退出してから再試行してください。",
+ "guestLimit": "この共有タスクにはすでにゲストが 2 人いるため、参加できません。",
+ "retry": "共有状態を更新できませんでした。接続を確認して再試行してください。",
+ "upgrade": "共有にはクライアントとサーバーの更新が必要です。",
+ "sharing": "参加者はすべての内容を閲覧し、このセッションの権限で Agent を使用できます。既存の承認は所有者が行います。",
+ "open": "共有を開始",
+ "members": "メンバー:{{count}} 人",
+ "host": "ホスト",
+ "remove": "ゲストを削除",
+ "leave": "共有セッションから退出",
+ "invite": "招待をコピー",
+ "close": "共有を停止",
+ "invitationCopied": "招待をコピーしました",
+ "invitationCopyFailed": "招待は作成されましたが、コピーできませんでした。このウィンドウに戻って再試行してください。",
+ "accessEndedBody": "この共有タスクにはアクセスできなくなりました。再参加するには、ホストに新しい招待を依頼してください。",
+ "joinIntro": "ホストから届いた招待を貼り付けて、同じタスクに参加します。",
+ "invitationPlaceholder": "招待内容を貼り付け",
+ "joinNickname": "タスク内でのニックネーム",
+ "nicknamePlaceholder": "表示する名前",
+ "joinNotice": "参加するとすべての履歴を閲覧でき、ホストの承認を待たずに Agent にメッセージを送信できます。",
+ "joinedTitle": "「{{title}}」に参加しました",
+ "joined": "共有タスクに参加しました",
+ "joinedBody": "参加前のメッセージ、ツールの結果、添付ファイルを確認し、同じ Agent にメッセージを送信できます。",
+ "enterTask": "タスクを開く",
+ "inviteBoxTitle": "仲間に招待を送信",
+ "roleGuest": "ゲスト",
+ "removeShort": "削除",
+ "removeNamedTitle": "{{name}}を削除しますか?",
+ "shareCurrent": "現在のタスクを共有",
+ "manage": "管理",
+ "guestCount": "ゲスト {{count}} 人",
+ "ownedTitle": "自分が開始した共有",
+ "ended": "共有が終了しました",
+ "rejoin": "新しい招待で参加",
+ "otherDevice": "他のパソコン",
+ "hostDevice": "ホストのパソコン",
+ "runsOnHostDevice": "ホストのパソコンで実行中",
+ "remoteHostOfflineNote": "ホストのパソコンがオフラインになると共有は自動で終了します。再接続後に共有を開始し、新しい招待を送信してください。",
+ "tabCurrent": "現在のセッション",
+ "tabOwned": "自分が共有中",
+ "startIntro": "パートナーを招待して、このセッションのすべての内容を共有し、同じ Agent で協力できます。",
+ "runsOnThisDevice": "このパソコンで実行中",
+ "inviteNotice": "招待を持つユーザーはログイン後に参加でき、所有者と同じ Agent 権限を持ちます。",
+ "offlineAutoClose": "ホストがオフラインになると、共有は自動的に終了します。",
+ "inviteBoxHint": "参加後はすべての履歴の閲覧とメッセージ送信が可能",
+ "membersWithLimit": "メンバー · {{count}} 人(ゲストは最大 2 人)",
+ "me": "自分",
+ "thisDevice": "このパソコン",
+ "roleHost": "ホスト",
+ "hostOfflineNote": "このパソコンがオフラインになると共有は終了します。再開後はもう一度共有を開始して招待してください。",
+ "closeCurrent": "このセッションの共有を停止",
+ "sharingBadge": "共有中",
+ "ownedIntro": "このリージョンで自分が共有中の {{count}} 件",
+ "ownedEmptyTitle": "共有中のセッションはありません",
+ "ownedEmptyHint": "任意のセッションを開いて「セッションを共有」から招待できます。",
+ "closeAll": "すべての共有を停止({{count}})",
+ "closeAllNote": "すべて停止すると、ゲストはアクセスできなくなり、古い招待は無効になります。セッションの記録と Agent の作業は保持されます。",
+ "closeAllTitle": "すべての共有を停止しますか?",
+ "closeAllBody": "このリージョンで自分が共有中のすべてのセッション(他のパソコンを含む)を停止します。",
+ "closeAllKeep": "共有を続ける",
+ "closeAllAction": "{{count}} 件の共有を停止",
+ "closeAllScopeNote": "セッションの記録と Agent の作業は保持され、自分が参加している他のセッションには影響しません。",
+ "closeOneTitle": "このセッションの共有を停止しますか?",
+ "closeOneBody": "すべてのゲストはアクセスできなくなり、招待は無効になります。",
+ "removeTitle": "このゲストを削除しますか?",
+ "removeBody": "そのゲストはアクセスできなくなります。再参加にはホストの新しい招待が必要です。",
+ "removeKeep": "ゲストを残す",
+ "leaveTitle": "共有セッションから退出しますか?",
+ "leaveBody": "退出するとこのセッションにアクセスできなくなります。再参加にはホストの新しい招待が必要です。",
+ "leaveKeep": "セッションに残る",
+ "hostOfflineTitle": "ホストがオフラインです",
+ "hostOfflineBody": "このセッションの共有は終了し、招待は無効になりました。ホストに再度共有を開始してもらい、新しい招待を送ってもらってください。",
+ "closedToast": "{{count}} 件のセッションの共有を停止しました",
+ "closeFailedToast": "停止できなかった共有があります({{count}} 件)。後ほど再試行できます。"
+}
diff --git a/apps/mobile/src/i18n/locales/ko/index.ts b/apps/mobile/src/i18n/locales/ko/index.ts
index 90203c8da8..a51e2acd9f 100644
--- a/apps/mobile/src/i18n/locales/ko/index.ts
+++ b/apps/mobile/src/i18n/locales/ko/index.ts
@@ -18,6 +18,7 @@ import interaction from './interaction.json';
import message from './message.json';
import models from './models.json';
import session from './session.json';
+import sharedTask from './sharedTask.json';
import settings from './settings.json';
import shared from './shared.json';
import startup from './startup.json';
@@ -37,6 +38,7 @@ export default {
message,
models,
session,
+ sharedTask,
settings,
shared,
startup,
diff --git a/apps/mobile/src/i18n/locales/ko/sharedTask.json b/apps/mobile/src/i18n/locales/ko/sharedTask.json
new file mode 100644
index 0000000000..79fc1de613
--- /dev/null
+++ b/apps/mobile/src/i18n/locales/ko/sharedTask.json
@@ -0,0 +1,89 @@
+{
+ "waitingHost": "호스트의 응답을 기다리고 있습니다. 메시지는 계속 보낼 수 있습니다.",
+ "join": "공유 세션 참여",
+ "joinHint": "초대를 붙여넣어 공유 세션을 여세요.",
+ "login": "세션에 참가하려면 Cindy에 로그인하세요.",
+ "openTask": "세션 열기",
+ "notJoined": "이 공유 세션에 더 이상 접근할 수 없습니다.",
+ "invitation": "초대",
+ "invalid": "유효한 초대와 표시 이름을 입력하세요.",
+ "nickname": "표시 이름",
+ "requestJoin": "참여",
+ "dismiss": "대화 상자 닫기",
+ "title": "세션 공유",
+ "hostLimit": "동시에 공유할 수 있는 작업은 최대 2개입니다. 하나를 닫은 후 다시 시도하세요.",
+ "joinLimit": "동시에 참여할 수 있는 공유 작업은 최대 2개입니다. 하나에서 나간 후 다시 시도하세요.",
+ "guestLimit": "이 공유 작업에는 이미 게스트가 2명 있어 참여할 수 없습니다.",
+ "retry": "공유 상태를 업데이트하지 못했습니다. 연결을 확인한 후 다시 시도하세요.",
+ "upgrade": "공유하려면 클라이언트와 서버를 업데이트해야 합니다.",
+ "sharing": "참여자는 모든 내용을 보고 이 세션의 권한으로 Agent를 사용할 수 있습니다. 기존 승인은 소유자가 처리합니다.",
+ "open": "공유 시작",
+ "members": "멤버: {{count}}명",
+ "host": "호스트",
+ "remove": "게스트 내보내기",
+ "leave": "공유 세션 나가기",
+ "invite": "초대 복사",
+ "close": "공유 중지",
+ "invitationCopied": "초대를 복사했습니다",
+ "invitationCopyFailed": "초대가 생성되었지만 복사하지 못했습니다. 이 창으로 돌아와 다시 시도해 주세요.",
+ "accessEndedBody": "이 공유 작업에 더 이상 접근할 수 없습니다. 다시 참여하려면 호스트에게 새 초대를 요청하세요.",
+ "joinIntro": "호스트가 보낸 초대를 붙여넣어 같은 작업에 참여하세요.",
+ "invitationPlaceholder": "초대 내용 붙여넣기",
+ "joinNickname": "작업에서 사용할 닉네임",
+ "nicknamePlaceholder": "표시할 이름",
+ "joinNotice": "참여하면 전체 기록을 보고 호스트의 승인을 기다리지 않고 Agent에게 메시지를 보낼 수 있습니다.",
+ "joinedTitle": "「{{title}}」에 참여했습니다",
+ "joined": "공유 작업에 참여했습니다",
+ "joinedBody": "참여 전의 메시지, 도구 결과, 첨부 파일을 확인하고 같은 Agent에게 메시지를 보낼 수 있습니다.",
+ "enterTask": "작업 열기",
+ "inviteBoxTitle": "동료에게 초대 보내기",
+ "roleGuest": "게스트",
+ "removeShort": "제거",
+ "removeNamedTitle": "{{name}} 님을 제거할까요?",
+ "shareCurrent": "현재 작업 공유",
+ "manage": "관리",
+ "guestCount": "게스트 {{count}}명",
+ "ownedTitle": "내가 시작한 공유",
+ "ended": "공유가 종료되었습니다",
+ "rejoin": "새 초대로 참여",
+ "otherDevice": "다른 컴퓨터",
+ "hostDevice": "호스트 컴퓨터",
+ "runsOnHostDevice": "호스트 컴퓨터에서 실행 중",
+ "remoteHostOfflineNote": "호스트 컴퓨터가 오프라인이 되면 공유가 자동 종료됩니다. 다시 연결한 후 공유를 시작하고 새 초대를 보내세요.",
+ "tabCurrent": "현재 세션",
+ "tabOwned": "내가 공유한 항목",
+ "startIntro": "파트너를 초대해 이 세션의 모든 내용을 함께 보고, 같은 Agent로 협업하세요.",
+ "runsOnThisDevice": "이 PC에서 실행 중",
+ "inviteNotice": "초대를 가진 사용자는 로그인 후 참여할 수 있으며, 호스트와 동일한 Agent 권한을 갖습니다.",
+ "offlineAutoClose": "호스트가 오프라인이 되면 공유는 자동으로 종료됩니다.",
+ "inviteBoxHint": "참여 후 전체 기록 조회와 메시지 전송 가능",
+ "membersWithLimit": "멤버 · {{count}}명 (최대 게스트 2명)",
+ "me": "나",
+ "thisDevice": "이 PC",
+ "roleHost": "호스트",
+ "hostOfflineNote": "이 PC가 오프라인이 되면 공유가 종료됩니다. 다시 온라인이 되면 공유를 다시 시작하고 초대해 주세요.",
+ "closeCurrent": "이 세션 공유 중지",
+ "sharingBadge": "공유 중",
+ "ownedIntro": "이 리전에서 내가 공유한 {{count}}개 세션",
+ "ownedEmptyTitle": "공유 중인 세션이 없습니다",
+ "ownedEmptyHint": "아무 세션이나 열고 \"세션 공유\"를 눌러 파트너를 초대하세요.",
+ "closeAll": "전체 공유 중지 ({{count}})",
+ "closeAllNote": "모두 중지하면 게스트는 접근할 수 없고 기존 초대는 만료됩니다. 세션 기록과 Agent 작업은 유지됩니다.",
+ "closeAllTitle": "전체 공유를 중지할까요?",
+ "closeAllBody": "이 리전에서 내가 공유한 모든 세션(다른 PC 포함)을 중지합니다.",
+ "closeAllKeep": "공유 유지",
+ "closeAllAction": "{{count}}개 공유 중지",
+ "closeAllScopeNote": "세션 기록과 Agent 작업은 유지되며, 내가 참여한 다른 세션에는 영향이 없습니다.",
+ "closeOneTitle": "이 세션 공유를 중지할까요?",
+ "closeOneBody": "모든 게스트가 접근할 수 없게 되고 초대는 만료됩니다.",
+ "removeTitle": "이 게스트를 내보낼까요?",
+ "removeBody": "해당 게스트는 접근할 수 없게 됩니다. 다시 참여하려면 호스트의 새 초대가 필요합니다.",
+ "removeKeep": "게스트 유지",
+ "leaveTitle": "공유 세션에서 나설까요?",
+ "leaveBody": "나가면 이 세션에 접근할 수 없습니다. 다시 참여하려면 호스트의 새 초대가 필요합니다.",
+ "leaveKeep": "세션에 남기",
+ "hostOfflineTitle": "호스트가 오프라인입니다",
+ "hostOfflineBody": "이 세션의 공유는 종료되었고 초대는 만료되었습니다. 호스트에게 공유를 다시 시작하고 새 초대를 보내달라고 요청하세요.",
+ "closedToast": "{{count}}개 세션의 공유를 중지했습니다",
+ "closeFailedToast": "중지하지 못한 공유가 있습니다({{count}}건). 나중에 다시 시도할 수 있습니다."
+}
diff --git a/apps/mobile/src/i18n/locales/zh-CN/index.ts b/apps/mobile/src/i18n/locales/zh-CN/index.ts
index 90203c8da8..a51e2acd9f 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/index.ts
+++ b/apps/mobile/src/i18n/locales/zh-CN/index.ts
@@ -18,6 +18,7 @@ import interaction from './interaction.json';
import message from './message.json';
import models from './models.json';
import session from './session.json';
+import sharedTask from './sharedTask.json';
import settings from './settings.json';
import shared from './shared.json';
import startup from './startup.json';
@@ -37,6 +38,7 @@ export default {
message,
models,
session,
+ sharedTask,
settings,
shared,
startup,
diff --git a/apps/mobile/src/i18n/locales/zh-CN/sharedTask.json b/apps/mobile/src/i18n/locales/zh-CN/sharedTask.json
new file mode 100644
index 0000000000..8fa589ee55
--- /dev/null
+++ b/apps/mobile/src/i18n/locales/zh-CN/sharedTask.json
@@ -0,0 +1,89 @@
+{
+ "waitingHost": "等待房主处理,你可以继续发送消息。",
+ "join": "加入共享任务",
+ "joinHint": "粘贴邀请,进入同一个共享任务。",
+ "login": "请登录 Cindy 后加入任务",
+ "openTask": "打开任务",
+ "notJoined": "你已无法访问此共享任务。",
+ "invitation": "邀请内容",
+ "invalid": "请输入有效的邀请内容和昵称",
+ "nickname": "昵称",
+ "requestJoin": "加入",
+ "dismiss": "关闭窗口",
+ "title": "共享任务",
+ "hostLimit": "你最多同时开启 2 个共享任务,请先关闭一个再试。",
+ "joinLimit": "你最多同时加入 2 个共享任务,请先退出一个再试。",
+ "guestLimit": "此共享任务已有 2 名访客,暂时无法加入。",
+ "retry": "未能更新共享状态,请检查连接后重试",
+ "upgrade": "共享任务需要更新客户端和服务器。",
+ "sharing": "访客可以查看任务的全部内容,并按该任务现有权限使用 Agent。已有审批仍由房主处理。",
+ "open": "开启共享",
+ "members": "成员:{{count}} 人",
+ "host": "房主",
+ "remove": "移除访客",
+ "leave": "退出共享任务",
+ "invite": "复制邀请",
+ "close": "关闭共享",
+ "invitationCopied": "邀请已复制",
+ "invitationCopyFailed": "邀请已生成,但未能复制。请回到此窗口后重试。",
+ "accessEndedBody": "当前已无法访问这个共享任务。如需再次加入,请联系房主发送新邀请。",
+ "joinIntro": "粘贴房主发来的邀请,进入同一个任务。",
+ "invitationPlaceholder": "粘贴邀请内容",
+ "joinNickname": "你在任务中的昵称",
+ "nicknamePlaceholder": "怎么称呼你",
+ "joinNotice": "加入后可查看全部历史,并直接向 Agent 发消息,无需等待房主审批。",
+ "joinedTitle": "已加入「{{title}}」",
+ "joined": "已加入共享任务",
+ "joinedBody": "你可以查看加入前的消息、工具结果和附件,也可以向同一个 Agent 发消息。",
+ "enterTask": "进入任务",
+ "inviteBoxTitle": "将邀请发给你的伙伴",
+ "roleGuest": "访客",
+ "removeShort": "移除",
+ "removeNamedTitle": "移除{{name}}?",
+ "shareCurrent": "共享当前任务",
+ "manage": "管理",
+ "guestCount": "{{count}} 位访客",
+ "ownedTitle": "我发起的共享",
+ "ended": "共享已结束",
+ "rejoin": "使用新邀请加入",
+ "otherDevice": "其他电脑",
+ "hostDevice": "房主电脑",
+ "runsOnHostDevice": "运行在房主电脑",
+ "remoteHostOfflineNote": "房主电脑离线时,共享自动关闭。重新上线后需再次开启并邀请。",
+ "tabCurrent": "当前任务",
+ "tabOwned": "我发起的",
+ "startIntro": "邀请伙伴查看这个任务的全部内容,一起与同一个 Agent 协作。",
+ "runsOnThisDevice": "运行在这台电脑",
+ "inviteNotice": "持有邀请的用户登录后即可加入,拥有与房主相同的 Agent 使用权限。",
+ "offlineAutoClose": "房主离线时,共享会自动关闭。",
+ "inviteBoxHint": "加入后可查看完整历史并发消息",
+ "membersWithLimit": "成员 · {{count}} 人(最多 2 位访客)",
+ "me": "我",
+ "thisDevice": "这台电脑",
+ "roleHost": "房主",
+ "hostOfflineNote": "这台电脑离线时,共享自动关闭。重新上线后需再次开启并邀请。",
+ "closeCurrent": "关闭此任务的共享",
+ "sharingBadge": "共享中",
+ "ownedIntro": "当前账号在此区域发起的 {{count}} 个共享任务",
+ "ownedEmptyTitle": "没有正在共享的任务",
+ "ownedEmptyHint": "回到任意任务,点击「共享任务」邀请伙伴。",
+ "closeAll": "关闭全部共享({{count}})",
+ "closeAllNote": "全部关闭后,访客无法继续访问,原邀请失效。任务记录和 Agent 工作会保留。",
+ "closeAllTitle": "关闭全部共享?",
+ "closeAllBody": "将关闭当前账号在此区域发起的全部共享,包含其他电脑上的任务。",
+ "closeAllKeep": "保持共享",
+ "closeAllAction": "关闭 {{count}} 个共享",
+ "closeAllScopeNote": "任务记录和 Agent 工作保留;你加入别人的任务不受影响。",
+ "closeOneTitle": "关闭此任务的共享?",
+ "closeOneBody": "所有访客将无法继续访问,原邀请将失效。",
+ "removeTitle": "移除这位访客?",
+ "removeBody": "该访客将无法继续访问。再次加入需要房主生成新邀请。",
+ "removeKeep": "保留访客",
+ "leaveTitle": "退出共享任务?",
+ "leaveBody": "退出后将无法访问这个任务。再次加入需要房主发送新邀请。",
+ "leaveKeep": "留在任务",
+ "hostOfflineTitle": "房主已离线",
+ "hostOfflineBody": "这个任务的共享已关闭,原邀请已失效。请联系房主重新开启共享并发送新邀请。",
+ "closedToast": "已关闭 {{count}} 个任务的共享",
+ "closeFailedToast": "部分共享未能关闭({{count}} 项),可稍后重试。"
+}
diff --git a/apps/mobile/src/i18n/locales/zh-TW/index.ts b/apps/mobile/src/i18n/locales/zh-TW/index.ts
index 90203c8da8..a51e2acd9f 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/index.ts
+++ b/apps/mobile/src/i18n/locales/zh-TW/index.ts
@@ -18,6 +18,7 @@ import interaction from './interaction.json';
import message from './message.json';
import models from './models.json';
import session from './session.json';
+import sharedTask from './sharedTask.json';
import settings from './settings.json';
import shared from './shared.json';
import startup from './startup.json';
@@ -37,6 +38,7 @@ export default {
message,
models,
session,
+ sharedTask,
settings,
shared,
startup,
diff --git a/apps/mobile/src/i18n/locales/zh-TW/sharedTask.json b/apps/mobile/src/i18n/locales/zh-TW/sharedTask.json
new file mode 100644
index 0000000000..d06cb17be6
--- /dev/null
+++ b/apps/mobile/src/i18n/locales/zh-TW/sharedTask.json
@@ -0,0 +1,89 @@
+{
+ "waitingHost": "等待房主處理,你可以繼續傳送訊息。",
+ "join": "加入共享任務",
+ "joinHint": "貼上邀請,進入同一個共享任務。",
+ "login": "請登入 Cindy 後加入任務",
+ "openTask": "開啟任務",
+ "notJoined": "你已無法存取此共享任務。",
+ "invitation": "邀請內容",
+ "invalid": "請輸入有效的邀請內容和暱稱",
+ "nickname": "暱稱",
+ "requestJoin": "加入",
+ "dismiss": "關閉視窗",
+ "title": "共享任務",
+ "hostLimit": "你最多同時開啟 2 個共享任務,請先關閉一個再試。",
+ "joinLimit": "你最多同時加入 2 個共享任務,請先退出一個再試。",
+ "guestLimit": "此共享任務已有 2 名訪客,暫時無法加入。",
+ "retry": "無法更新共享狀態,請檢查連線後重試",
+ "upgrade": "共享任務需要更新客戶端與伺服器。",
+ "sharing": "訪客可以查看任務的全部內容,並按該任務現有權限使用 Agent。既有審批仍由房主處理。",
+ "open": "開啟共享",
+ "members": "成員:{{count}} 人",
+ "host": "主持人",
+ "remove": "移除訪客",
+ "leave": "離開共享任務",
+ "invite": "複製邀請",
+ "close": "停止共享",
+ "invitationCopied": "已複製邀請",
+ "invitationCopyFailed": "邀請已產生,但未能複製。請回到此視窗後重試。",
+ "accessEndedBody": "目前已無法存取此共享任務。如需再次加入,請聯絡房主傳送新邀請。",
+ "joinIntro": "貼上房主傳來的邀請,進入同一個任務。",
+ "invitationPlaceholder": "貼上邀請內容",
+ "joinNickname": "你在任務中的暱稱",
+ "nicknamePlaceholder": "怎麼稱呼你",
+ "joinNotice": "加入後可查看全部歷史,並直接向 Agent 傳送訊息,無需等待房主審批。",
+ "joinedTitle": "已加入「{{title}}」",
+ "joined": "已加入共享任務",
+ "joinedBody": "你可以查看加入前的訊息、工具結果和附件,也可以向同一個 Agent 傳送訊息。",
+ "enterTask": "進入任務",
+ "inviteBoxTitle": "將邀請傳給你的夥伴",
+ "roleGuest": "訪客",
+ "removeShort": "移除",
+ "removeNamedTitle": "移除{{name}}?",
+ "shareCurrent": "共享目前任務",
+ "manage": "管理",
+ "guestCount": "{{count}} 位訪客",
+ "ownedTitle": "我發起的共享",
+ "ended": "共享已結束",
+ "rejoin": "使用新邀請加入",
+ "otherDevice": "其他電腦",
+ "hostDevice": "房主電腦",
+ "runsOnHostDevice": "在房主電腦上執行",
+ "remoteHostOfflineNote": "房主電腦離線時,共享會自動關閉。重新上線後需再次開啟並邀請。",
+ "tabCurrent": "目前任務",
+ "tabOwned": "我發起的",
+ "startIntro": "邀請夥伴查看這個任務的全部內容,一起與同一個 Agent 協作。",
+ "runsOnThisDevice": "執行在這台電腦",
+ "inviteNotice": "持有邀請的使用者登入後即可加入,擁有與房主相同的 Agent 使用權限。",
+ "offlineAutoClose": "房主離線時,共享會自動關閉。",
+ "inviteBoxHint": "加入後可查看完整歷史並傳送訊息",
+ "membersWithLimit": "成員 · {{count}} 人(最多 2 位訪客)",
+ "me": "我",
+ "thisDevice": "這台電腦",
+ "roleHost": "房主",
+ "hostOfflineNote": "這台電腦離線時,共享自動關閉。重新上線後需再次開啟並邀請。",
+ "closeCurrent": "關閉此任務的共享",
+ "sharingBadge": "共享中",
+ "ownedIntro": "目前帳號在此區域發起的 {{count}} 個共享任務",
+ "ownedEmptyTitle": "沒有正在共享的任務",
+ "ownedEmptyHint": "回到任意任務,點擊「共享任務」邀請夥伴。",
+ "closeAll": "關閉全部共享({{count}})",
+ "closeAllNote": "全部關閉後,訪客無法繼續存取,原邀請失效。任務記錄和 Agent 工作會保留。",
+ "closeAllTitle": "關閉全部共享?",
+ "closeAllBody": "將關閉目前帳號在此區域發起的全部共享,包含其他電腦上的任務。",
+ "closeAllKeep": "保持共享",
+ "closeAllAction": "關閉 {{count}} 個共享",
+ "closeAllScopeNote": "任務記錄和 Agent 工作保留;你加入別人的任務不受影響。",
+ "closeOneTitle": "關閉此任務的共享?",
+ "closeOneBody": "所有訪客將無法繼續存取,原邀請將失效。",
+ "removeTitle": "移除這位訪客?",
+ "removeBody": "該訪客將無法繼續存取。再次加入需要房主產生新邀請。",
+ "removeKeep": "保留訪客",
+ "leaveTitle": "離開共享任務?",
+ "leaveBody": "離開後將無法存取這個任務。再次加入需要房主傳送新邀請。",
+ "leaveKeep": "留在任務",
+ "hostOfflineTitle": "房主已離線",
+ "hostOfflineBody": "這個任務的共享已關閉,原邀請已失效。請聯絡房主重新開啟共享並傳送新邀請。",
+ "closedToast": "已關閉 {{count}} 個任務的共享",
+ "closeFailedToast": "部分共享未能關閉({{count}} 項),可稍後重試。"
+}
diff --git a/apps/mobile/src/platform/chrome/showActionMenu.ts b/apps/mobile/src/platform/chrome/showActionMenu.ts
index 1f50a6dd3c..25f4a59efb 100644
--- a/apps/mobile/src/platform/chrome/showActionMenu.ts
+++ b/apps/mobile/src/platform/chrome/showActionMenu.ts
@@ -78,6 +78,7 @@ export function showConfirm(input: {
cancelLabel: string;
confirmLabel: string;
destructive?: boolean;
+ cancelable?: boolean;
}): Promise<boolean> {
return new Promise((resolve) => {
Alert.alert(input.title, input.message, [
@@ -91,6 +92,6 @@ export function showConfirm(input: {
text: input.confirmLabel,
onPress: () => resolve(true),
},
- ]);
+ ], { cancelable: input.cancelable ?? false, onDismiss: () => resolve(false) });
});
}
diff --git a/apps/mobile/src/session/ComposerRichInput.tsx b/apps/mobile/src/session/ComposerRichInput.tsx
index f976e53c70..c0995ee6e7 100644
--- a/apps/mobile/src/session/ComposerRichInput.tsx
+++ b/apps/mobile/src/session/ComposerRichInput.tsx
@@ -98,6 +98,7 @@ const ComposerWebInput = forwardRef<ComposerRichInputHandle, ComposerRichInputPr
useEffect(() => registerMobileMessageWebView('composer'), []);
const readyRef = useRef(false);
const webSignatureRef = useRef('');
+ const localDocumentsRef = useRef(new WeakSet<ComposerDocument>());
const projectedDraft = useMemo(() => composerDocumentProjectedText(document), [document]);
const webDocumentRef = useRef({ document, draft: projectedDraft, id: 0 });
const selectionRef = useRef<(ComposerSelection & { draft: string }) | null>(null);
@@ -186,6 +187,10 @@ const ComposerWebInput = forwardRef<ComposerRichInputHandle, ComposerRichInputPr
}, [inject]);
useEffect(() => {
+ // A native edit may advance again before React commits its previous
+ // snapshot. Echoes acknowledge that edit; they must not reset the DOM
+ // or caret to an older value. External replacements still apply below.
+ if (localDocumentsRef.current.delete(document)) return;
const signature = JSON.stringify(document);
if (signature === webSignatureRef.current) return;
webSignatureRef.current = signature;
@@ -401,6 +406,7 @@ const ComposerWebInput = forwardRef<ComposerRichInputHandle, ComposerRichInputPr
if (selectionRef.current?.atomRange) selectionRef.current = null;
webSignatureRef.current = JSON.stringify(normalized);
webDocumentRef.current = { document: normalized, draft: composerDocumentProjectedText(normalized), id: webDocumentRef.current.id };
+ localDocumentsRef.current.add(normalized);
onChangeDocument(normalized);
return;
}
diff --git a/apps/mobile/src/session/HomeChromeDrawer.tsx b/apps/mobile/src/session/HomeChromeDrawer.tsx
index b5ebc075cc..5aba8c870e 100644
--- a/apps/mobile/src/session/HomeChromeDrawer.tsx
+++ b/apps/mobile/src/session/HomeChromeDrawer.tsx
@@ -63,6 +63,7 @@ export function HomeChromeDrawer({
onOpenSearch,
onOpenAccounts,
onOpenDevices,
+ onOpenSharedSession,
onOpenSettings,
onLogout,
loggingOut = false,
@@ -76,6 +77,7 @@ export function HomeChromeDrawer({
onOpenSearch(): void;
onOpenAccounts(): void;
onOpenDevices(): void;
+ onOpenSharedSession?(): void;
onOpenSettings(): void;
onLogout(): void;
loggingOut?: boolean;
@@ -334,6 +336,16 @@ export function HomeChromeDrawer({
<Text numberOfLines={1} style={styles.menuLabel}>{t('devices.management.title')}</Text>
</Pressable>
+ {onOpenSharedSession && <Pressable
+ accessibilityLabel={t('sharedTask.join')}
+ accessibilityRole="button"
+ onPress={onOpenSharedSession}
+ style={({ pressed }) => [styles.menuRow, pressed && styles.pressed]}
+ >
+ <UsersRound color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />
+ <Text numberOfLines={1} style={styles.menuLabel}>{t('sharedTask.join')}</Text>
+ </Pressable>}
+
<Pressable
accessibilityLabel={t("devices.list.a11y.openSettings")}
accessibilityRole="button"
diff --git a/apps/mobile/src/session/InteractionPanel.tsx b/apps/mobile/src/session/InteractionPanel.tsx
index e8137dc891..5da466d2bd 100644
--- a/apps/mobile/src/session/InteractionPanel.tsx
+++ b/apps/mobile/src/session/InteractionPanel.tsx
@@ -1,5 +1,6 @@
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
+import { isSharedTaskPeer } from '@cindy/device-link';
import { mobilePresentationLocalizer } from '@/i18n/presentationLocalizer';
import {
Check,
@@ -224,7 +225,7 @@ export function InteractionPanel({
gap: touchLayout.cardGap,
padding: touchLayout.cardPadding,
};
- if (readOnlyReason) {
+ if (readOnlyReason || isSharedTaskPeer(deviceId)) {
return (
<View style={[styles.root, fillAvailableHeight && styles.rootFill, rootLayoutStyle]} testID="interaction.panel">
<PendingTaskHeader
@@ -235,7 +236,8 @@ export function InteractionPanel({
<View style={[styles.card, cardLayoutStyle]} testID="interaction.readOnlyCard">
<Text style={styles.kind}>{t('interaction.panel.readOnlyKind')}</Text>
<Text style={styles.cardTitle}>{t('interaction.panel.readOnlyTitle')}</Text>
- <Text style={styles.body}>{readOnlyReason}</Text>
+ <Text style={styles.body}>{readOnlyReason ?? t('sharedTask.waitingHost')}</Text>
+ {isSharedTaskPeer(deviceId) && <Text selectable style={styles.body}>{JSON.stringify(activeInteraction.request, null, 2)}</Text>}
</View>
</View>
);
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index 72cc327dc5..8056264377 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -4,6 +4,7 @@ import { downloadRemoteMediaShareTemp } from './remoteMediaDiskCacheExpo';
import { usePluginResultCard } from './usePluginResultCard';
import { extractPayloadToolResultMedia, managedToolMediaKind } from '@cindy/maker-shared/payload-summary';
import { AuthorizationMessageCard } from './AuthorizationMessageCard';
+import { sharedTaskAuthorName } from '@cindy/maker-shared';
import { CompanionMessageCard } from '@/session/CompanionMessageCard';
import { mobileDebugEnabled, mobileDebugLog } from '@/debug/mobileDebugLog';
import { createContext, Fragment, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentProps, type ReactNode } from 'react';
@@ -3293,6 +3294,8 @@ function MessageBubble({
]}
testID={isUser ? 'message.userBubble' : 'message.agentBubble'}
>
+ {isUser && sharedTaskAuthorName(item.message.source.agentMeta) ?
+ <Text style={styles.hookSourceTitle}>{sharedTaskAuthorName(item.message.source.agentMeta)}</Text> : null}
{hasPluginInvocations ? (
<PluginInvocationHeader
key={clientId}
diff --git a/apps/mobile/src/session/SessionMenuSheet.tsx b/apps/mobile/src/session/SessionMenuSheet.tsx
index 4a0c20e6e5..56ec1d0014 100644
--- a/apps/mobile/src/session/SessionMenuSheet.tsx
+++ b/apps/mobile/src/session/SessionMenuSheet.tsx
@@ -23,6 +23,7 @@ import {
ArchiveRestore,
Copy,
Link2,
+ LogOut,
Pencil,
Pin,
PinOff,
@@ -49,6 +50,7 @@ import { MainWindowActionGroup } from '@/components/MobilePrimitives';
import type { MobileMakerTransport, RemoteDirectoryEntry } from '@/device-link/mobileMakerTransport';
import type { MobileCodexRateLimitsResult } from '@cindy/maker-shared/device-link-contract';
import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';
+import { isSharedTaskPeer } from '@cindy/device-link';
import { computeContextSheetSnapHeights, type ContextSheetSnap } from '@/session/contextSheetModel';
import { writeClipboardText } from '@/session/messageActions';
import { normalizeExtraDirs } from '@/session/newSession';
@@ -133,6 +135,9 @@ export interface SessionMenuSheetProps {
onRegenerateTitle(): Promise<{ title: string | null }>;
/** 打开工作目录(复用文件浏览页);调用方负责关 sheet 并跳转。 */
onOpenWorkspace(): void;
+ onOpenSharing?: () => void;
+ onLeaveSharing?: () => void;
+ leavingSharing?: boolean;
onTogglePinned(): void;
onArchive(): void;
onRestore(): void;
@@ -167,6 +172,9 @@ export function SessionMenuSheet({
onRename,
onRegenerateTitle,
onOpenWorkspace,
+ onOpenSharing,
+ onLeaveSharing,
+ leavingSharing = false,
onTogglePinned,
onArchive,
onRestore,
@@ -480,10 +488,11 @@ export function SessionMenuSheet({
[codexRateLimits, i18nInstance.language],
);
const workspace = buildSessionInfoWorkspace(session);
- const showExtraDirs = sessionInfoShowsExtraDirs(session);
+ const sharedGuest = isSharedTaskPeer(session.deviceLinkDeviceId ?? '');
+ const showExtraDirs = !sharedGuest && sessionInfoShowsExtraDirs(session);
- const mainActions = messageOnly ? [] : actions.filter((action) => action.id !== 'delete' && action.id !== 'archive');
- const deleteAction = messageOnly ? undefined : actions.find((action) => action.id === 'delete');
+ const mainActions = messageOnly ? [] : actions.filter((action) => sharedGuest ? action.id === 'copyLink' : action.id !== 'delete' && action.id !== 'archive');
+ const deleteAction = messageOnly ? undefined : sharedGuest ? undefined : actions.find((action) => action.id === 'delete');
const confirmCodexReset = useCallback(() => {
if (!resetSummary?.canReset || codexResetBusy) return;
@@ -586,6 +595,24 @@ export function SessionMenuSheet({
{!messageOnly ? <SessionUsageSummary providerName={providerName} session={session} usage={menuUsage} contextUsage={contextUsage} onPress={openInfo} translucent={Platform.OS === 'ios'} /> : null}
+ {!messageOnly && isSharedTaskPeer(session.deviceLinkDeviceId) && onLeaveSharing ? (
+ Platform.OS === 'ios' ? <SessionDetailsNativeActions actions={[{
+ label: t('sharedTask.leave'), danger: true, disabled: leavingSharing,
+ onPress: onLeaveSharing, testID: 'session.leaveSharingButton',
+ }]} /> : <View style={styles.actionGroup}>
+ <MenuActionRow icon={LogOut} label={t('sharedTask.leave')} danger disabled={leavingSharing}
+ onPress={onLeaveSharing} testID="session.leaveSharingButton" />
+ </View>
+ ) : !messageOnly && onOpenSharing && !isSharedTaskPeer(session.deviceLinkDeviceId) ? (
+ Platform.OS === 'ios' ? <SessionDetailsNativeActions actions={[{
+ label: t('sharedTask.title'),
+ onPress: onOpenSharing,
+ testID: 'session.sharingButton',
+ }]} /> : <View style={styles.actionGroup}>
+ <MenuActionRow icon={Link2} label={t('sharedTask.title')}
+ onPress={onOpenSharing} testID="session.sharingButton" />
+ </View>
+ ) : null}
{Platform.OS === 'ios' ? (
<SessionDetailsNativeActions actions={mainActions.map(action => ({
label: action.id === 'copyLink' ? copyLabel(action.label, 'copyLink', t('session.menu.linkCopied')) : action.label,
@@ -747,6 +774,7 @@ export function SessionMenuSheet({
<View style={styles.infoActionRow}>
<MenuPillButton
label={t('session.menu.openDir')}
+ disabled={sharedGuest}
onPress={onOpenWorkspace}
testID="session.openWorkspaceButton"
/>
diff --git a/apps/mobile/src/session/SharedTaskEndedState.tsx b/apps/mobile/src/session/SharedTaskEndedState.tsx
new file mode 100644
index 0000000000..70afa8bacd
--- /dev/null
+++ b/apps/mobile/src/session/SharedTaskEndedState.tsx
@@ -0,0 +1,26 @@
+import { View, StyleSheet } from 'react-native';
+import { Square } from 'lucide-react-native';
+import { useTranslation } from 'react-i18next';
+import { Text } from '@/components/AppText';
+import { SharedTaskAction } from '@/session/SharedTaskScreen';
+import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';
+import { fontWeight, iconSize, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';
+
+/** Membership loss has a recovery action, without claiming an unverified offline cause. */
+export function SharedTaskEndedState({ onRejoin }: { onRejoin(): void }) {
+ const { t } = useTranslation();
+ const { colors } = useTheme();
+ const styles = useThemedStyles(makeStyles);
+ return <View style={styles.body} testID="sharedTask.ended">
+ <View style={styles.icon}><Square size={iconSize.md} color={colors.textTertiary} /></View>
+ <Text style={styles.title}>{t('sharedTask.ended')}</Text>
+ <Text style={styles.text}>{t('sharedTask.accessEndedBody')}</Text>
+ <SharedTaskAction action={{ label: t('sharedTask.rejoin'), tone: 'primary', onPress: onRejoin }} />
+ </View>;
+}
+const makeStyles = (colors: ThemeColors) => StyleSheet.create({
+ body: { paddingVertical: spacing.xl, paddingHorizontal: spacing.xs, alignItems: 'center' },
+ icon: { width: 44, height: 44, borderRadius: radius.pill, borderWidth: StyleSheet.hairlineWidth, borderColor: colors.border, alignItems: 'center', justifyContent: 'center', marginBottom: spacing.lg },
+ title: { color: colors.textPrimary, fontSize: typeScale.listBody, lineHeight: lineHeight.listBody, fontWeight: fontWeight.medium },
+ text: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, textAlign: 'center', maxWidth: 280, marginTop: spacing.sm, marginBottom: spacing.lg },
+});
diff --git a/apps/mobile/src/session/SharedTaskScreen.tsx b/apps/mobile/src/session/SharedTaskScreen.tsx
new file mode 100644
index 0000000000..d1d5cd4cd5
--- /dev/null
+++ b/apps/mobile/src/session/SharedTaskScreen.tsx
@@ -0,0 +1,35 @@
+import { type ReactNode, type Ref } from 'react';
+import { KeyboardAvoidingView, Platform, ScrollView, StyleSheet, type View } from 'react-native';
+import { SafeAreaView } from 'react-native-safe-area-context';
+import { MainWindowActionButton, type MainWindowAction } from '@/components/MobilePrimitives';
+import { SimpleStackHeader, simpleScreenSafeAreaEdges } from '@/platform/chrome/SimpleStackHeader';
+import { useThemedStyles, type ThemeColors } from '@/theme';
+import { fontWeight, spacing, typeScale } from '@/theme/tokens';
+
+/** Full-screen management; confirmations stay compact, with native material on iOS. */
+export function SharedTaskScreen({ title, onClose, children }: {
+ title: string; onClose(): void; children: ReactNode;
+}) {
+ const styles = useThemedStyles(makeStyles);
+ return <SafeAreaView edges={simpleScreenSafeAreaEdges()} style={styles.root}>
+ <SimpleStackHeader title={title} onBack={onClose} />
+ <KeyboardAvoidingView style={styles.body} enabled={Platform.OS === 'ios'} behavior="padding">
+ <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled" keyboardDismissMode="on-drag">{children}</ScrollView>
+ </KeyboardAvoidingView>
+ </SafeAreaView>;
+}
+
+export function SharedTaskAction({ action, grow = false, compact = false, buttonRef }: { action: MainWindowAction; grow?: boolean; compact?: boolean; buttonRef?: Ref<View> }) {
+ const styles = useThemedStyles(makeStyles);
+ return <MainWindowActionButton action={action} grow={grow} buttonRef={buttonRef} density="compact" style={styles.action} textStyle={[compact ? styles.compactActionText : styles.actionText, action.tone === 'danger' && styles.dangerText]} />;
+}
+
+const makeStyles = (colors: ThemeColors) => StyleSheet.create({
+ root: { flex: 1, backgroundColor: colors.surface },
+ body: { flex: 1 },
+ content: { padding: spacing.lg },
+ action: { minHeight: 44, paddingHorizontal: spacing.lg },
+ actionText: { fontSize: typeScale.listBody, fontWeight: fontWeight.regular },
+ compactActionText: { fontSize: typeScale.caption, fontWeight: fontWeight.regular },
+ dangerText: { color: colors.sharedTaskConfirmBackground },
+});
diff --git a/apps/mobile/src/session/composerDraftSource.ts b/apps/mobile/src/session/composerDraftSource.ts
index 602906ff0e..f6056a13dd 100644
--- a/apps/mobile/src/session/composerDraftSource.ts
+++ b/apps/mobile/src/session/composerDraftSource.ts
@@ -14,16 +14,34 @@ export interface ComposerDraftSnapshot {
export function createComposerDraftSource(document: ComposerDocument) {
let snapshot: ComposerDraftSnapshot = { document, draft: composerDocumentProjectedText(document) };
const listeners = new Set<() => void>();
+ let frame: number | null = null;
return {
getSnapshot: () => snapshot,
subscribe: (listener: () => void) => {
listeners.add(listener);
- return () => { listeners.delete(listener); };
+ return () => {
+ listeners.delete(listener);
+ if (listeners.size === 0 && frame !== null) {
+ cancelAnimationFrame(frame);
+ frame = null;
+ }
+ };
},
setDocument: (next: ComposerDocument) => {
if (snapshot.document === next) return;
snapshot = { document: next, draft: composerDocumentProjectedText(next) };
- for (const listener of listeners) listener();
+ // Keep send/persistence snapshots synchronous, but publish at most once
+ // per frame. Android's direct WebView emitter can deliver a burst of edits
+ // before React finishes committing its external-store subscribers.
+ if (frame !== null || listeners.size === 0) return;
+ frame = requestAnimationFrame(() => {
+ frame = null;
+ // React may replace subscriptions during notification. New listeners
+ // read the current snapshot on mount, not through this same iteration.
+ for (const listener of [...listeners]) {
+ if (listeners.has(listener)) listener();
+ }
+ });
},
};
}
diff --git a/apps/mobile/src/session/mobileAttachmentUpload.ts b/apps/mobile/src/session/mobileAttachmentUpload.ts
index 38e2089cc4..612850f8de 100644
--- a/apps/mobile/src/session/mobileAttachmentUpload.ts
+++ b/apps/mobile/src/session/mobileAttachmentUpload.ts
@@ -66,7 +66,7 @@ export function effectiveUploadMimeType(mimeType: string | undefined): string {
export async function presignMobileAttachmentUpload(
candidate: MobileAttachmentUploadCandidate,
- options: { token: string | null; deps?: UploadDeps },
+ options: { token: string | null; sharedTaskId?: string; deps?: UploadDeps },
): Promise<MobileAttachmentPresignResult> {
const apiFetch = options.deps?.apiFetch ?? apiFetchRaw;
const result = await withTransientRemoteRetry(
@@ -79,6 +79,7 @@ export async function presignMobileAttachmentUpload(
size: candidate.size,
contentType: effectiveUploadMimeType(candidate.mimeType),
ext: uploadExtForName(candidate.name),
+ ...(options.sharedTaskId ? { sharedTaskId: options.sharedTaskId } : {}),
},
}),
{ maxAttempts: PRESIGN_MAX_ATTEMPTS },
@@ -294,7 +295,7 @@ export async function statMobileAttachmentFileSize(uri: string): Promise<number>
export async function uploadMobileAttachment(
candidate: MobileAttachmentUploadCandidate,
body: MobileAttachmentUploadBody,
- options: { token: string | null; id?: string; deps?: UploadDeps },
+ options: { token: string | null; sharedTaskId?: string; id?: string; deps?: UploadDeps },
): Promise<RemoteSerializedAttachment> {
// 上传前先校验类型:不支持的本机文件(如 .zip)若先 presign + PUT、再在
// buildMobileUploadedAttachment 处被拒,会在 device-link OSS 桶里留下一个永不被引用、
@@ -327,6 +328,7 @@ export async function uploadMobileAttachmentFromFile(
fileUri: string,
options: {
token: string | null;
+ sharedTaskId?: string;
id?: string;
deps?: UploadDeps;
signal?: AbortSignal;
diff --git a/apps/mobile/src/session/mobileLocalAttachmentUpload.ts b/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
index 6dba058a74..2fb882b2c1 100644
--- a/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
+++ b/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
@@ -31,6 +31,8 @@ export interface MobileLocalAttachmentUploadCandidate {
name: string;
/** 发起上传的 composer 作用域(sessionId 等);仅供宿主隔离迟到异步结果。 */
attachmentScopeKey?: string;
+ /** Destination captured when enqueued, never read from a later active task. */
+ sharedTaskId?: string;
/** 同一作用域重复进入时也会递增的代际;避免 A → B → A 后接回最早 A 的旧结果。 */
attachmentScopeGeneration?: number;
mimeType?: string;
@@ -101,7 +103,7 @@ export interface MobileLocalAttachmentUploadDeps {
assertSize(size: number, candidate: MobileLocalAttachmentUploadCandidate): void;
/** 真正的 presign + PUT(uploadMobileAttachmentFromFile);signal 中止时应尽快断掉传输。 */
upload(
- candidate: { name: string; size: number; mimeType?: string },
+ candidate: { name: string; size: number; mimeType?: string; sharedTaskId?: string },
fileUri: string,
opts: { token: string; signal?: AbortSignal },
): Promise<RemoteSerializedAttachment>;
@@ -354,7 +356,7 @@ export function createMobileLocalAttachmentUploadController(
return;
}
const attachment = await step(deps.upload(
- { name: prepared.name, size, mimeType: prepared.mimeType || undefined },
+ { name: prepared.name, size, mimeType: prepared.mimeType || undefined, ...(source.sharedTaskId ? { sharedTaskId: source.sharedTaskId } : {}) },
prepared.uri,
{ token, signal },
), deps.discard);
diff --git a/apps/mobile/src/session/useMobileLocalAttachments.ts b/apps/mobile/src/session/useMobileLocalAttachments.ts
index ada8354cc0..4f789a4263 100644
--- a/apps/mobile/src/session/useMobileLocalAttachments.ts
+++ b/apps/mobile/src/session/useMobileLocalAttachments.ts
@@ -14,6 +14,7 @@
* - 页面卸载时 hook 自动 dispose(在途上传完成后回收 OSS 中转对象)。
*/
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { parseSharedTaskPeer } from '@cindy/device-link';
import { useTranslation } from 'react-i18next';
import { Platform } from 'react-native';
import * as DocumentPicker from 'expo-document-picker';
@@ -59,6 +60,7 @@ export interface UseMobileLocalAttachmentsOptions {
* 标注异步入口与上传完成结果不得写入新作用域。省略时保持旧的单作用域行为。
*/
attachmentScopeKey?: string;
+ deviceId?: string;
getAccessToken: () => Promise<string | null>;
/** 当前已入列附件数(限额用;pending 由 hook 自己计入)。 */
getAttachmentCount: () => number;
@@ -267,7 +269,7 @@ export function useMobileLocalAttachments(
if (candidate.kind === 'image') assertMobileImageSize(size);
else assertMobileDocumentSize(size);
},
- upload: (candidate, fileUri, opts) => uploadMobileAttachmentFromFile(candidate, fileUri, opts),
+ upload: (candidate, fileUri, opts) => uploadMobileAttachmentFromFile(candidate, fileUri, { ...opts, sharedTaskId: candidate.sharedTaskId }),
discard: (attachment) => discardMobileUploadedAttachment(attachment, {
getToken: () => optionsRef.current.getAccessToken(),
}),
@@ -366,6 +368,7 @@ export function useMobileLocalAttachments(
...candidate,
attachmentScopeGeneration,
attachmentScopeKey,
+ sharedTaskId: parseSharedTaskPeer(optionsRef.current.deviceId ?? '')?.sharedTaskId,
})),
opts,
);
diff --git a/apps/mobile/src/session/useSessionResourceCards.ts b/apps/mobile/src/session/useSessionResourceCards.ts
index 7bd8b5361e..fc9760ceec 100644
--- a/apps/mobile/src/session/useSessionResourceCards.ts
+++ b/apps/mobile/src/session/useSessionResourceCards.ts
@@ -3,6 +3,7 @@ import { AppState } from 'react-native';
import { useFocusEffect } from 'expo-router';
import { useTranslation } from 'react-i18next';
import {
+ isSharedTaskPeer,
resolveRemoteText,
type RemoteCollectionDescriptor,
type RemoteResource,
@@ -72,7 +73,9 @@ export function useSessionResourceCards(
const request = useRef<{ binding: string } | null>(null);
useFocusEffect(
useCallback(() => {
- if (!deviceId || !sessionId || !source || status !== 'online') return;
+ // These cards discover device-wide workflows. A shared guest uses the
+ // existing single-task history/input APIs, never the host resource catalog.
+ if (!deviceId || isSharedTaskPeer(deviceId) || !sessionId || !source || status !== 'online') return;
let disposed = false;
let reading = false;
let dirty = false;
diff --git a/apps/mobile/src/session/useSharedTaskConfirmation.tsx b/apps/mobile/src/session/useSharedTaskConfirmation.tsx
new file mode 100644
index 0000000000..836dbf1654
--- /dev/null
+++ b/apps/mobile/src/session/useSharedTaskConfirmation.tsx
@@ -0,0 +1,57 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { AccessibilityInfo, findNodeHandle, Modal, Platform, ScrollView, StyleSheet, View } from 'react-native';
+import { Text } from '@/components/AppText';
+import { MainWindowActionButton } from '@/components/MobilePrimitives';
+import { showConfirm } from '@/platform/chrome/showActionMenu';
+import { useThemedStyles, type ThemeColors } from '@/theme';
+import { fontWeight, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';
+
+type Confirmation = Parameters<typeof showConfirm>[0];
+
+/** iOS owns native material; Android follows the shared-task dialog design tokens. */
+export function useSharedTaskConfirmation() {
+ const [request, setRequest] = useState<Confirmation | null>(null);
+ const resolver = useRef<((accepted: boolean) => void) | null>(null);
+ const cancelButton = useRef<View>(null);
+ const styles = useThemedStyles(makeStyles);
+ useEffect(() => () => { resolver.current?.(false); resolver.current = null; }, []);
+ const settle = useCallback((accepted: boolean) => {
+ const resolve = resolver.current;
+ resolver.current = null; setRequest(null); resolve?.(accepted);
+ }, []);
+ const confirm = useCallback((next: Confirmation): Promise<boolean> => {
+ if (Platform.OS === 'ios') return showConfirm(next);
+ if (resolver.current) return Promise.resolve(false);
+ return new Promise((resolve) => { resolver.current = resolve; setRequest(next); });
+ }, []);
+ const dialog = request ? <Modal transparent animationType="fade" visible
+ onRequestClose={() => settle(false)}
+ onShow={() => { const handle = findNodeHandle(cancelButton.current); if (handle) AccessibilityInfo.setAccessibilityFocus(handle); }}>
+ <View style={styles.backdrop} testID="sharedTask.confirmBackdrop">
+ <View style={styles.card} accessibilityViewIsModal testID="sharedTask.confirmDialog">
+ <ScrollView style={styles.content} contentContainerStyle={styles.copy} bounces={false}>
+ <Text style={styles.title} accessibilityRole="header">{request.title}</Text>
+ {!!request.message && <Text style={styles.body}>{request.message}</Text>}
+ </ScrollView>
+ <View style={styles.actions}>
+ <MainWindowActionButton density="compact" buttonRef={cancelButton} style={styles.button}
+ action={{ label: request.cancelLabel, onPress: () => settle(false), testID: 'sharedTask.confirmCancel' }} />
+ <MainWindowActionButton density="compact" style={styles.button}
+ action={{ label: request.confirmLabel, tone: request.destructive ? 'danger-solid' : 'primary', onPress: () => settle(true), testID: 'sharedTask.confirmAccept' }} />
+ </View>
+ </View>
+ </View>
+ </Modal> : null;
+ return { confirm, dialog };
+}
+
+const makeStyles = (colors: ThemeColors) => StyleSheet.create({
+ backdrop: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: colors.overlay, padding: spacing.xl },
+ card: { width: '100%', maxWidth: 400, maxHeight: '80%', backgroundColor: colors.surfaceElevated, borderColor: colors.border, borderWidth: StyleSheet.hairlineWidth, borderRadius: radius.container, padding: spacing.lg, gap: spacing.lg },
+ content: { flexGrow: 0, flexShrink: 1 },
+ copy: { gap: spacing.md },
+ title: { color: colors.textPrimary, fontSize: typeScale.title, fontWeight: fontWeight.medium, lineHeight: lineHeight.subtitle },
+ body: { color: colors.textPrimary, fontSize: typeScale.body, lineHeight: lineHeight.body },
+ actions: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm },
+ button: { minHeight: 44, minWidth: 120, flexGrow: 1, flexShrink: 0 },
+});
diff --git a/apps/mobile/src/theme/tokens.ts b/apps/mobile/src/theme/tokens.ts
index 3ffcb4d4d0..7605453faa 100644
--- a/apps/mobile/src/theme/tokens.ts
+++ b/apps/mobile/src/theme/tokens.ts
@@ -158,6 +158,9 @@ export interface ThemeColors {
* 文字;状态指示红是另一档 #D91F37(statusError / statusRecording),不要混用。
*/
destructive: string;
+ /** Shared-task plan B destructive confirmation fill / label (approved 2026-09-20). */
+ sharedTaskConfirmBackground: string;
+ sharedTaskConfirmForeground: string;
/** 错误边框(跟随 borderStrong) */
errorBorder: string;
/**
@@ -446,6 +449,8 @@ export const lightColors: ThemeColors = {
permAutoAccent: '#417CDD',
errorText: '#3C3F43',
destructive: '#f43d3f',
+ sharedTaskConfirmBackground: '#ac3535',
+ sharedTaskConfirmForeground: '#fffefa',
errorBorder: '#686B72',
// overlay:遮罩双模式恒深(light 原 0.24 太浅近白;0.50 实机过重,用户定稿 0.35,2026-07-21)。
// 侧栏/抽屉毛玻璃底色另有 surfaceTranslucentSidebar,不受影响。
@@ -533,6 +538,8 @@ export const darkColors: ThemeColors = {
permAutoAccent: '#417CDD',
errorText: '#D4D4D4',
destructive: '#f43d3f',
+ sharedTaskConfirmBackground: '#ec9898',
+ sharedTaskConfirmForeground: '#272727',
errorBorder: '#BFC1C4',
overlay: 'rgba(0, 0, 0, 0.45)',
// homeListFab:反相中性(lead 裁决,见 lightColors 注释);dark 维持 #ECEDEF 柔白(非纯白 cta)。
diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.md
index 7d34afe89e..1585ec62fc 100644
--- a/docs/design-rules/DESIGN.md
+++ b/docs/design-rules/DESIGN.md
@@ -96,6 +96,7 @@ The grayscale rule is near-absolute. The following are the **only** sanctioned n
> **Additional narrowly-scoped exceptions** (documented in their respective component specs, do NOT generalize as system semantic colors):
>
> - **Cindy Make source comparison** — the owner-approved source overview (2026-09-20) combines local main and the online target in one row, with personal and its comparison to local main below. Matching main hashes appear once in `--status-success`; differing hashes show the local value in `--text-secondary` → the verified online target in `--status-success`, with a `--text-tertiary` arrow. The online green identifies the official target even when local main is behind; difference counts remain explicit. Unavailable lookups stay neutral. Both modes use the existing semantic tokens; no other version surface inherits this treatment.
+> - **Shared-task mobile confirmations** — only the management page is full-screen. Remove, leave, close-current and close-all use compact confirmations. iOS retains `showConfirm` and the system Alert with supported Liquid Glass / older-system fallback. On 2026-09-20 the user rejected Android's default green-text system Alert: Android uses a centered content-height card, container radius 12, themed elevated surface, neutral outlined Cancel and pill-shaped solid danger action using `sharedTaskConfirmBackground/Foreground`. Reuse Mobile action primitives, minimum target 44, wrap actions when needed, and scroll long descriptions. Android Back cancels; the scrim does not dismiss. Cancellation preserves the task, page, tab and scroll position. An in-task guest exits directly from task details, without another management page. No native configuration changes or simulated iOS glass. Desktop retains the Plan B shared window.
> - **CINDY checked Switch** — `--switch-track-on` uses blue `#417CDD` in CINDY Light and Dark (owner decision 2026-09-15, §15.17). This is an enabled-state signal, independently adjustable from focus, caret and Auto Approval despite sharing their current hue. Other themes retain their own checked-track colors.
> - **Windows taskbar attention badge** — the native OS overlay uses a fixed red background (`#D91F37`) and white digits with no outline (`#FFFFFF`) in both Light and Dark taskbars. This is the app-wide count of active tasks needing attention, not an error-only status. The image-specific semantic pair lives in `apps/desktop/src/main/windowsBadgeIcon.ts`; it is not an in-app theme token. Keep a 16-logical-pixel transparent canvas and center the circle and digits at 80% of their original size (user refinement, 2026-09-16). Render using the highest connected display scale and pass that physical-size image directly to the Windows Shell through the native taskbar bridge (Electron 41 otherwise forces overlays to 16 physical pixels). Redraw after display/DPI changes and taskbar recreation; keep the multi-resolution Electron overlay as a failure fallback. Use a circle for one digit, a rounded square for multiple digits, and `99+` above 99. The accessibility description keeps the exact total. Only the OS image may use its fitted 8–12px system-font digits; web typography and status-dot color rules are unchanged.
> - **Toast Info / Success / Warning / Error** — `#417CDD` / `#2AAE5B` / `#F3A115` / `#D91F37`(finalized 2026-07-17; Toast exemption lifted) — used ONLY on the 16×16 lucide icon inside Toast pill notifications. The pill body (background, text, border, close icon) remains strictly grayscale. Info blue #417CDD equals the focus-ring / Auto Approval value (originally #3B82F6, added 2026-07-14, now finalized); success/warning/error equal the global status colors (done green / status error / warning foreground).
diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.md
index 630044fc4a..5ff3ecbfa2 100644
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@ -11,19 +11,19 @@
计数快照日期:2026-09-20。生成命令:`pnpm design:inventory`。裸颜色匹配与 `scripts/hardcoded-color-audit.mjs` 共用 `scripts/shared/hardcoded-color-match.mjs`(HEX / RGB / HSL / OKLCH 等字面通道),两者在共享 matcher 内统一排除纯语义包装、注释及 PR 编号;数值颜色函数还需位于样式属性、CSS 声明/函数或任意值语境,普通文案字符串里的颜色函数文本不计入;字面 fallback 仍计入——语义 token 消费与注释引用不是迁移债务;裸圆角为粗粒度(`rounded*` class、`border-radius:` 与 React style 对象的 `borderRadius:`)。Token 计数为样式源里 `var(--token)` / `hsl(var(--token)` 的去重 ID 数;Mobile 的 ThemeColors / typeScale 等 RN 属性不计入此列,不能将 0 解释为未使用 Token。
-登记 surface 数:50。平台包含 Desktop 与 Mobile;静态入口发现不表示已迁移或已实机验证。
+登记 surface 数:51。平台包含 Desktop 与 Mobile;静态入口发现不表示已迁移或已实机验证。
| ID | 平台 | 标题 | 生产入口 | 可达组件 | 样式来源 | Token 数 | 裸颜色 | 裸圆角 |
| --- | --- | --- | --- | --- | --- | ---: | ---: | ---: |
| `desktop.auth.add-account` | desktop | 添加账号 | hash `/add-account`(ProtectedRoute → AddAccountLoginPage) | AddAccountLoginPage | apps/desktop/src/renderer/components/login/AddAccountLoginPage.tsx, apps/desktop/src/renderer/components/login/LoginBrandStage.tsx, apps/desktop/src/renderer/components/login/LoginCaptchaOverlay.tsx, apps/desktop/src/renderer/components/login/LoginControls.tsx, apps/desktop/src/renderer/components/login/LoginPage.tsx, apps/desktop/src/renderer/components/login/loginDesignTokens.ts | 59 | 0 | 20 |
| `desktop.auth.legacy-migration` | desktop | 首登数据迁移弹窗 | App 顶层挂载 LegacyMigrationDialog(仅主窗;main 检测到旧版 userData 经 `legacy-migration:state` 驱动) | LegacyMigrationDialog | apps/desktop/src/renderer/components/auth/LegacyMigrationDialog.tsx | 8 | 0 | 2 |
| `desktop.auth.login` | desktop | 登录页 | hash `/login`(GuestRoute → LoginPage) | LoginBrandStage, LoginCaptchaOverlay, LoginControls, LoginPage | apps/desktop/src/renderer/components/login/LoginBrandStage.tsx, apps/desktop/src/renderer/components/login/LoginCaptchaOverlay.tsx, apps/desktop/src/renderer/components/login/LoginControls.tsx, apps/desktop/src/renderer/components/login/LoginPage.tsx, apps/desktop/src/renderer/components/login/loginDesignTokens.ts | 59 | 0 | 20 |
-| `desktop.bots` | desktop | 伙伴(列表 / 对话 / 设置 / 历史 / 伙伴私聊) | hash `/bots`、`/bots/list`、`/bots/:botId`、`/bots/roster` 及伙伴当前/历史任务、伙伴私聊路由(BotsFeatureLayout) | BotBasicProfileFields, BotCollaborationCard, BotDirectMessageView, BotHistorySessionView, BotLifecycleSettings, BotModelChainEditor, BotRosterView, BotSessionView, BotSettingsDrawer, BotsHomeView, BotsListView, RemoteBotSessionView | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsx, apps/desktop/src/renderer/features/bots/BotAvatar.tsx, apps/desktop/src/renderer/features/bots/BotBasicProfileFields.tsx, apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx, apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx, apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx, apps/desktop/src/renderer/features/bots/BotCreateMenu.tsx, apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx, apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx, apps/desktop/src/renderer/features/bots/BotInvitationWelcome.tsx, apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx, apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx, apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx, apps/desktop/src/renderer/features/bots/BotRosterView.tsx, apps/desktop/src/renderer/features/bots/BotRoutines.tsx, apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx, apps/desktop/src/renderer/features/bots/BotSessionView.tsx, apps/desktop/src/renderer/features/bots/BotSettingsBlock.tsx, apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotWorkingStatus.tsx, apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx, apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx, apps/desktop/src/renderer/features/bots/BotsHomeView.tsx, apps/desktop/src/renderer/features/bots/BotsListView.tsx, apps/desktop/src/renderer/features/bots/BotsSidebar.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx, apps/desktop/src/renderer/features/bots/botAvatarIdentity.ts, apps/desktop/src/renderer/features/bots/botCapabilityDefaults.ts, apps/desktop/src/renderer/features/bots/botChatPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationTimeline.ts, apps/desktop/src/renderer/features/bots/botDelegationLive.ts, apps/desktop/src/renderer/features/bots/botGeneratedArtifacts.ts, apps/desktop/src/renderer/features/bots/botListDisplay.ts, apps/desktop/src/renderer/features/bots/botNavigation.ts, apps/desktop/src/renderer/features/bots/botPronounContext.tsx, apps/desktop/src/renderer/features/bots/botReadState.ts, apps/desktop/src/renderer/features/bots/botRosterDisplay.ts, apps/desktop/src/renderer/features/bots/botSessionOwners.ts, apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/botStore.ts, apps/desktop/src/renderer/features/bots/botWelcomeContext.ts, apps/desktop/src/renderer/features/bots/remoteBotRoster.ts, apps/desktop/src/renderer/features/bots/useBotGeneratedFileDeliveries.ts, apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts, apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/useRemoteBots.ts, apps/desktop/src/renderer/features/bots/useWorkingStatusCopy.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 291 | 43 | 482 |
+| `desktop.bots` | desktop | 伙伴(列表 / 对话 / 设置 / 历史 / 伙伴私聊) | hash `/bots`、`/bots/list`、`/bots/:botId`、`/bots/roster` 及伙伴当前/历史任务、伙伴私聊路由(BotsFeatureLayout) | BotBasicProfileFields, BotCollaborationCard, BotDirectMessageView, BotHistorySessionView, BotLifecycleSettings, BotModelChainEditor, BotRosterView, BotSessionView, BotSettingsDrawer, BotsHomeView, BotsListView, RemoteBotSessionView | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsx, apps/desktop/src/renderer/features/bots/BotAvatar.tsx, apps/desktop/src/renderer/features/bots/BotBasicProfileFields.tsx, apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx, apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx, apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx, apps/desktop/src/renderer/features/bots/BotCreateMenu.tsx, apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx, apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx, apps/desktop/src/renderer/features/bots/BotInvitationWelcome.tsx, apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx, apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx, apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx, apps/desktop/src/renderer/features/bots/BotRosterView.tsx, apps/desktop/src/renderer/features/bots/BotRoutines.tsx, apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx, apps/desktop/src/renderer/features/bots/BotSessionView.tsx, apps/desktop/src/renderer/features/bots/BotSettingsBlock.tsx, apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotWorkingStatus.tsx, apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx, apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx, apps/desktop/src/renderer/features/bots/BotsHomeView.tsx, apps/desktop/src/renderer/features/bots/BotsListView.tsx, apps/desktop/src/renderer/features/bots/BotsSidebar.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx, apps/desktop/src/renderer/features/bots/botAvatarIdentity.ts, apps/desktop/src/renderer/features/bots/botCapabilityDefaults.ts, apps/desktop/src/renderer/features/bots/botChatPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationTimeline.ts, apps/desktop/src/renderer/features/bots/botDelegationLive.ts, apps/desktop/src/renderer/features/bots/botGeneratedArtifacts.ts, apps/desktop/src/renderer/features/bots/botListDisplay.ts, apps/desktop/src/renderer/features/bots/botNavigation.ts, apps/desktop/src/renderer/features/bots/botPronounContext.tsx, apps/desktop/src/renderer/features/bots/botReadState.ts, apps/desktop/src/renderer/features/bots/botRosterDisplay.ts, apps/desktop/src/renderer/features/bots/botSessionOwners.ts, apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/botStore.ts, apps/desktop/src/renderer/features/bots/botWelcomeContext.ts, apps/desktop/src/renderer/features/bots/remoteBotRoster.ts, apps/desktop/src/renderer/features/bots/useBotGeneratedFileDeliveries.ts, apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts, apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/useRemoteBots.ts, apps/desktop/src/renderer/features/bots/useWorkingStatusCopy.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 291 | 43 | 483 |
| `desktop.chat.files` | desktop | 工作目录文件浏览 | hash `/cc-agent/files/:sessionId`(WorkdirBrowseRoute) | FileBodyView, FileTreeView, WorkdirBrowseRoute | apps/desktop/src/renderer/features/cc-agent/workdir-browse/DocSearchBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/DrawioPreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileBodyView.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileFilterInput.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTabsBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTreeView.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FilterResultList.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/ImagePreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/OpenInSystemActions.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/PdfPreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/SessionTabsBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/UnrenderablePlaceholder.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseRoute.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useChatRailCollapsed.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useChatRailResize.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useConfirmSwitchAwayIfDirty.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useDelayedFlag.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileContent.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileTree.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useOpenTabs.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useProjectFileList.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useRevealFileInTree.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/activeFileBodyHandle.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/docModeSwitchProjects.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/drawioExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/expandedStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileContentCache.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileIcon.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileMeta.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileScrollStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileSelectionParams.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/filterFiles.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/imageExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/markdownAutosave.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/openTabsStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/pdfExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/selectedFileStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchInput.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchPanel.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchResults.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/hooks/useProjectSearch.ts | 22 | 7 | 64 |
| `desktop.chat.new-draft` | desktop | 新建任务草稿页 | hash `/cc-agent/new`(NewMakerDraftRoute) | NewMakerDraftRoute | apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx | 15 | 0 | 2 |
-| `desktop.chat.orca-workflow` | desktop | Orca 协同工作台 | hash `/cc-agent/orca/:sessionId`(OrcaWorkflowRoute) | CCAgentSessionView, OrcaSplitView, OrcaWorkerPanel, OrcaWorkflowRoute | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaSplitView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkflowRoute.tsx | 271 | 43 | 388 |
+| `desktop.chat.orca-workflow` | desktop | Orca 协同工作台 | hash `/cc-agent/orca/:sessionId`(OrcaWorkflowRoute) | CCAgentSessionView, OrcaSplitView, OrcaWorkerPanel, OrcaWorkflowRoute | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaSplitView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkflowRoute.tsx | 271 | 43 | 389 |
| `desktop.chat.scheduled` | desktop | 调度任务列表 | hash `/cc-agent/scheduled`(SchedulerPage) | SchedulerPage | apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx, apps/desktop/src/renderer/features/scheduler/components/AgentMark.tsx, apps/desktop/src/renderer/features/scheduler/components/BoundSessionCard.tsx, apps/desktop/src/renderer/features/scheduler/components/ProjectAutomationNotifyBridge.tsx, apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsx, apps/desktop/src/renderer/features/scheduler/components/RunHistoryPane.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleSessionIndexOwner.tsx, apps/desktop/src/renderer/features/scheduler/components/ScheduleStatusChip.tsx, apps/desktop/src/renderer/features/scheduler/components/ScriptCapabilityMultiSelect.tsx, apps/desktop/src/renderer/features/scheduler/components/TaskListCell.tsx, apps/desktop/src/renderer/features/scheduler/components/TaskListFilterPopover.tsx, apps/desktop/src/renderer/features/scheduler/components/TaskListPane.tsx, apps/desktop/src/renderer/features/scheduler/components/TemplateCard.tsx, apps/desktop/src/renderer/features/scheduler/components/TemplateGallery.tsx, apps/desktop/src/renderer/features/scheduler/components/TemplateParamForm.tsx, apps/desktop/src/renderer/features/scheduler/hooks/useDeleteScheduleWithSessions.tsx, apps/desktop/src/renderer/features/scheduler/hooks/useReadFailedScheduleRuns.ts, apps/desktop/src/renderer/features/scheduler/hooks/useRunNowBusyGuard.ts, apps/desktop/src/renderer/features/scheduler/hooks/useRuns.ts, apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.ts, apps/desktop/src/renderer/features/scheduler/hooks/useScheduleUnreadRunCounts.ts, apps/desktop/src/renderer/features/scheduler/hooks/useSchedules.ts, apps/desktop/src/renderer/features/scheduler/hooks/useSessionReferences.ts, apps/desktop/src/renderer/features/scheduler/hooks/useTemplates.ts, apps/desktop/src/renderer/features/scheduler/index.ts, apps/desktop/src/renderer/features/scheduler/lib/cronCodexPreset.ts, apps/desktop/src/renderer/features/scheduler/lib/cronToHuman.ts, apps/desktop/src/renderer/features/scheduler/lib/failedScheduleDismissal.ts, apps/desktop/src/renderer/features/scheduler/lib/formatters.ts, apps/desktop/src/renderer/features/scheduler/lib/pluginScheduleCreateIntent.ts, apps/desktop/src/renderer/features/scheduler/lib/projectAutomationConfig.ts, apps/desktop/src/renderer/features/scheduler/lib/projectScheduleSidebarIndex.ts, apps/desktop/src/renderer/features/scheduler/lib/runHistoryGrouping.ts, apps/desktop/src/renderer/features/scheduler/lib/runUnread.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleRunReadSync.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleSessionBinding.ts, apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.ts, apps/desktop/src/renderer/features/scheduler/lib/schedulesStore.ts, apps/desktop/src/renderer/features/scheduler/lib/statusFilter.ts, apps/desktop/src/renderer/features/scheduler/lib/statusFilterStorage.ts, apps/desktop/src/renderer/features/scheduler/lib/templateLocalization.ts, apps/desktop/src/renderer/features/scheduler/lib/usageLimitScheduleCreateIntent.ts | 44 | 0 | 109 |
-| `desktop.chat.session` | desktop | 会话工作台 | hash `/cc-agent/:sessionId`;副窗经 `/cc-agent/boot` 解析后落到同一会话视图 | AssistantMessage, CCAgentFeatureLayout, CCAgentSessionView, ChatInput, PermissionPrompt | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 271 | 43 | 387 |
+| `desktop.chat.session` | desktop | 会话工作台 | hash `/cc-agent/:sessionId`;副窗经 `/cc-agent/boot` 解析后落到同一会话视图 | AssistantMessage, CCAgentFeatureLayout, CCAgentSessionView, ChatInput, PermissionPrompt | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 271 | 43 | 388 |
| `desktop.dev.maker-experimental` | desktop | Maker 实验诊断页 | hash `/maker-experimental`(MakerExperimentalView;EXPERIMENTAL_FEATURES 现为空,仍是生产路由) | MakerExperimentalView | apps/desktop/src/renderer/features/maker-experimental/MakerExperimentalView.tsx | 10 | 0 | 11 |
| `desktop.issues.guide` | desktop | Issue 引导页 | hash `/issues`(IssueTrackerFeatureLayout,已迁 GitHub 后的引导页) | IssueTrackerFeatureLayout | apps/desktop/src/renderer/features/issue-tracker/IssueTrackerFeatureLayout.tsx, apps/desktop/src/renderer/features/issue-tracker/MyIssueList.tsx, apps/desktop/src/renderer/features/issue-tracker/hooks/useMyIssues.ts, apps/desktop/src/renderer/features/issue-tracker/lib/myIssuesNotices.ts, apps/desktop/src/renderer/features/issue-tracker/lib/startIssueChat.ts | 0 | 0 | 8 |
| `desktop.native.app-menu` | desktop | 应用菜单 | Menu.setApplicationMenu(用户可见出口,不展开业务逻辑) | applicationMenuLabels | apps/desktop/src/main/applicationMenuLabels.ts | 0 | 0 | 0 |
@@ -51,20 +51,21 @@
| `desktop.window.sidebar` | desktop | 右侧栏独立窗口 | `?sidebarWindow=1` → renderer/sidebar-window-entry.tsx;hash `/sidebar-window` | RightSidebar, RightSidebarShell, SidebarWindowLayout | apps/desktop/src/main/right-sidebar-window/controller.ts, apps/desktop/src/main/right-sidebar-window/ipc.ts, apps/desktop/src/main/right-sidebar-window/registry.ts, apps/desktop/src/main/right-sidebar-window/resolveHostContext.ts, apps/desktop/src/main/right-sidebar-window/settings-store.ts, apps/desktop/src/main/right-sidebar-window/window.ts, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/sidebar-window-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 106 | 45 | 196 |
| `desktop.window.voice-dictionary-toast` | desktop | 语音词典 Toast 窗 | `?view=voice-input-dictionary-toast` → main-entry.tsx → VoiceInputDictionaryToast | VoiceInputDictionaryToast | apps/desktop/src/renderer/voice-input/VoiceInputDictionaryToast.tsx | 6 | 0 | 2 |
| `desktop.window.voice-overlay` | desktop | 语音输入浮窗 | `?view=voice-input-overlay` → main-entry.tsx → VoiceInputOverlay | VoiceInputOverlay, VoiceInputStatusNotice | apps/desktop/src/main/voice-input/global.ts, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css, apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsx, apps/desktop/src/renderer/voice-input/VoiceInputStatusNotice.tsx | 71 | 38 | 25 |
-| `mobile.account-deletion` | mobile | 账号注销 | app/account-deletion.tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, account-deletion, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/account-deletion.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 196 | 55 |
-| `mobile.auth` | mobile | 登录与添加账号 | app/(auth)/login.tsx / app/add-account.tsx | AccountSwitcherSheet, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, IncomingShareBridge, LoginCaptchaWebView, LoginSkinControls, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, _layout, add-account, gestureHandler, login, peerFileTransport, useLocale | apps/mobile/app/(auth)/login.tsx, apps/mobile/app/_layout.tsx, apps/mobile/app/add-account.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/LoginCaptchaWebView.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/LoginSkinControls.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 203 | 76 |
-| `mobile.automations` | mobile | 自动化 | app/automations/[deviceId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/automations/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 196 | 71 |
-| `mobile.chat.new` | mobile | 新建任务 | app/sessions/new.tsx | AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerAttachmentTray, ComposerFrame, ComposerFrame.ios, ComposerKeyboardAvoidingView, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetGoalView, ContextSheetGoalView.ios, ContextSheetMediaViews, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, ImageLightbox, IncomingShareBridge, MobileAgentMark, MobileAgentSwitcher, MobileChoicePickerList, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, MobileVendorIcon, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, NewTaskSelectionSheet, NewTaskSelectionSheet.ios, PaperPlaneIcon, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PlanModeChip, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, _layout, gestureHandler, new, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/new.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/PaperPlaneIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ContextSheetGoalView.ios.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileChoicePickerList.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/NativePermissionSheet.ios.tsx, apps/mobile/src/session/NativePermissionSheet.tsx, apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx, apps/mobile/src/session/NewTaskSelectionSheet.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 228 | 110 |
-| `mobile.chat.session` | mobile | 任务内容与输入 | app/sessions/[sessionId].tsx | AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, AuthorizationMessageCard, BlurBackdrop, CenteredScreen, ChatFileChipMenuSheet, CompanionMessageCard, ComposerAttachmentTray, ComposerExpandButton, ComposerExpandButton.ios, ComposerFrame, ComposerFrame.ios, ComposerKeyboardAvoidingView, ComposerNativeInput, ComposerNativeInput.ios, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerRichInput, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetGoalView, ContextSheetGoalView.ios, ContextSheetMediaViews, ConversationSearchFilterSheet, ConversationShareSvg, ConversationShareWebView, DeviceLinkContext, FailedScheduleNotice, HomeEntryProvider, HomeGlassMenuPanel, HomeNativeStackHeader, HomeSearchBar, ImageLightbox, IncomingShareBridge, InlineQueueSection, InlineQuoteChip, InlineReferenceChip, InteractionPanel, MarkdownBlockContent, MessageActionSheet, MessageRenderer, MobileAgentMark, MobileAgentSwitcher, MobileBoundaryNotice, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PaperPlaneIcon, PendingSendBubble, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PlanModeChip, PluginInvocationHeader, PromptRecommendation, PushNotificationsBridge, QuietSyncIndicator, QuoteCapsule, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RenameSessionModal, RewindPreviewPanel, SentInlineAtomBody, SessionActionSheet, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionListDrawer, SessionMenuSheet, SessionOptionsExpoSheet, SessionResourceCards, SessionSearchNative, SessionSearchNative.ios, SessionTailBanner, SessionUsageSummary, ShareImageNativeButton, ShareImageNativeButton.ios, ShareMessageCheckbox, ShareSelectAllButton, ShareSelectionBar, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, StreamingStatusText, TaskTags, TaskTagsSheet, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, [sessionId], _layout, gestureHandler, mathWebView, mediaPlayerWebView, mermaidWebView, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/PaperPlaneIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/AuthorizationMessageCard.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ChatFileChipMenuSheet.tsx, apps/mobile/src/session/CompanionMessageCard.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerExpandButton.ios.tsx, apps/mobile/src/session/ComposerExpandButton.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ComposerNativeInput.ios.tsx, apps/mobile/src/session/ComposerNativeInput.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerRichInput.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ContextSheetGoalView.ios.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/ConversationShareSvg.tsx, apps/mobile/src/session/ConversationShareWebView.tsx, apps/mobile/src/session/FailedScheduleNotice.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/InlineQueueSection.tsx, apps/mobile/src/session/InlineQuoteChip.tsx, apps/mobile/src/session/InlineReferenceChip.tsx, apps/mobile/src/session/InteractionPanel.tsx, apps/mobile/src/session/MarkdownBlockContent.tsx, apps/mobile/src/session/MessageActionSheet.tsx, apps/mobile/src/session/MessageRenderer.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileBoundaryNotice.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/NativePermissionSheet.ios.tsx, apps/mobile/src/session/NativePermissionSheet.tsx, apps/mobile/src/session/PendingSendBubble.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/PluginInvocationHeader.tsx, apps/mobile/src/session/PromptRecommendation.tsx, apps/mobile/src/session/QuoteCapsule.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/RewindPreviewPanel.tsx, apps/mobile/src/session/SentInlineAtomBody.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionListDrawer.tsx, apps/mobile/src/session/SessionMenuSheet.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SessionResourceCards.tsx, apps/mobile/src/session/SessionSearchNative.ios.tsx, apps/mobile/src/session/SessionSearchNative.tsx, apps/mobile/src/session/SessionTailBanner.tsx, apps/mobile/src/session/SessionUsageSummary.tsx, apps/mobile/src/session/ShareImageNativeButton.ios.tsx, apps/mobile/src/session/ShareImageNativeButton.tsx, apps/mobile/src/session/ShareMessageCheckbox.tsx, apps/mobile/src/session/ShareSelectAllButton.tsx, apps/mobile/src/session/ShareSelectionBar.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/StreamingStatusText.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/session/TaskTagsSheet.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/session/composerRichInputHtml.ts, apps/mobile/src/session/conversationShareWebViewHtml.ts, apps/mobile/src/session/mathWebView.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/mermaidWebView.tsx, apps/mobile/src/session/mermaidWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 7 | 229 | 252 |
-| `mobile.companions.direct` | mobile | 伙伴私聊回看 | app/companions/direct/[threadId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [threadId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/companions/direct/[threadId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 196 | 50 |
-| `mobile.device-management` | mobile | 设备管理 | app/devices/manage.tsx / app/devices/manage/[deviceId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceInformationFields, DeviceInformationFields.ios, DeviceLinkContext, DeviceManagementDialogs, DeviceManagementList, DeviceManagementList.ios, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RenameDeviceModal, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, manage, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/manage.tsx, apps/mobile/app/devices/manage/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceInformationFields.ios.tsx, apps/mobile/src/device-link/DeviceInformationFields.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/DeviceManagementDialogs.tsx, apps/mobile/src/device-link/DeviceManagementList.ios.tsx, apps/mobile/src/device-link/DeviceManagementList.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RenameDeviceModal.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 196 | 53 |
-| `mobile.devices` | mobile | 主机详情 | app/devices/[deviceId].tsx | AccountSwitcherSheet, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ConversationSearchFilterSheet, DeviceLinkContext, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeNativeStackHeader, HomeProjectMachineLabel, HomeSearchBar, IncomingShareBridge, MobileAgentMark, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, MobileVendorIcon, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteAccessGuide, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteTaskSuggestions, RenameSessionModal, SessionActionSheet, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionOptionsExpoSheet, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, TaskTags, ThemeProvider, [deviceId], _layout, gestureHandler, index, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/[deviceId].tsx, apps/mobile/app/devices/index.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 196 | 112 |
-| `mobile.files` | mobile | 任务文件与预览 | app/files/[sessionId].tsx / app/files/preview/[sessionId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HtmlBrowserChrome, HtmlBrowserChrome.ios, HtmlFileReader, HtmlWebsiteBrowser, ImageLightbox, IncomingShareBridge, MarkdownFileReader, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, [sessionId], _layout, gestureHandler, mediaPlayerWebView, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/files/[sessionId].tsx, apps/mobile/app/files/preview/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HtmlBrowserChrome.ios.tsx, apps/mobile/src/session/HtmlBrowserChrome.tsx, apps/mobile/src/session/HtmlFileReader.tsx, apps/mobile/src/session/HtmlWebsiteBrowser.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MarkdownFileReader.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 228 | 77 |
-| `mobile.home` | mobile | 主机与资源首页 | app/index.tsx / app/devices/index.tsx | AccountSwitcherSheet, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ConversationSearchFilterSheet, DeviceLinkContext, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeNativeStackHeader, HomeProjectMachineLabel, HomeSearchBar, IncomingShareBridge, MobileAgentMark, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, MobileVendorIcon, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteAccessGuide, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteTaskSuggestions, RenameSessionModal, SessionActionSheet, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionOptionsExpoSheet, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, TaskTags, ThemeProvider, _layout, gestureHandler, index, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/index.tsx, apps/mobile/app/index.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 196 | 108 |
-| `mobile.overlay.connection-startup` | mobile | 根布局挂载的启动与连接反馈 | app/_layout.tsx → StartupSplashOverlay / ConnectionNoticeProvider;各页面 ConnectionBanner | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ConnectionNoticeProvider, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 196 | 48 |
-| `mobile.remote-desktop` | mobile | 远程桌面 | app/devices/desktop/[deviceId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/desktop/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 196 | 48 |
-| `mobile.resources` | mobile | 远程资源列表与详情 | app/resources/[collectionId].tsx / app/resources/[collectionId]/[resourceId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteCompanionAvatar, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [collectionId], [resourceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/resources/[collectionId].tsx, apps/mobile/app/resources/[collectionId]/[resourceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 196 | 54 |
-| `mobile.settings` | mobile | 设置(含调试与日志上传可见入口) | app/settings.tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileChoicePickerList, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, settings, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/settings.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileChoicePickerList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 196 | 56 |
+| `mobile.account-deletion` | mobile | 账号注销 | app/account-deletion.tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, account-deletion, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/account-deletion.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 200 | 55 |
+| `mobile.auth` | mobile | 登录与添加账号 | app/(auth)/login.tsx / app/add-account.tsx | AccountSwitcherSheet, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, IncomingShareBridge, LoginCaptchaWebView, LoginSkinControls, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, _layout, add-account, gestureHandler, login, peerFileTransport, useLocale | apps/mobile/app/(auth)/login.tsx, apps/mobile/app/_layout.tsx, apps/mobile/app/add-account.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/LoginCaptchaWebView.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/LoginSkinControls.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 207 | 76 |
+| `mobile.automations` | mobile | 自动化 | app/automations/[deviceId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/automations/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 200 | 71 |
+| `mobile.chat.new` | mobile | 新建任务 | app/sessions/new.tsx | AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerAttachmentTray, ComposerFrame, ComposerFrame.ios, ComposerKeyboardAvoidingView, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetGoalView, ContextSheetGoalView.ios, ContextSheetMediaViews, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, ImageLightbox, IncomingShareBridge, MobileAgentMark, MobileAgentSwitcher, MobileChoicePickerList, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, MobileVendorIcon, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, NewTaskSelectionSheet, NewTaskSelectionSheet.ios, PaperPlaneIcon, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PlanModeChip, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, _layout, gestureHandler, new, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/new.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/PaperPlaneIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ContextSheetGoalView.ios.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileChoicePickerList.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/NativePermissionSheet.ios.tsx, apps/mobile/src/session/NativePermissionSheet.tsx, apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx, apps/mobile/src/session/NewTaskSelectionSheet.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 232 | 110 |
+| `mobile.chat.session` | mobile | 任务内容与输入 | app/sessions/[sessionId].tsx | AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, AuthorizationMessageCard, BlurBackdrop, CenteredScreen, ChatFileChipMenuSheet, CompanionMessageCard, ComposerAttachmentTray, ComposerExpandButton, ComposerExpandButton.ios, ComposerFrame, ComposerFrame.ios, ComposerKeyboardAvoidingView, ComposerNativeInput, ComposerNativeInput.ios, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerRichInput, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetGoalView, ContextSheetGoalView.ios, ContextSheetMediaViews, ConversationSearchFilterSheet, ConversationShareSvg, ConversationShareWebView, DeviceLinkContext, FailedScheduleNotice, HomeEntryProvider, HomeGlassMenuPanel, HomeNativeStackHeader, HomeSearchBar, ImageLightbox, IncomingShareBridge, InlineQueueSection, InlineQuoteChip, InlineReferenceChip, InteractionPanel, MarkdownBlockContent, MessageActionSheet, MessageRenderer, MobileAgentMark, MobileAgentSwitcher, MobileBoundaryNotice, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PaperPlaneIcon, PendingSendBubble, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PlanModeChip, PluginInvocationHeader, PromptRecommendation, PushNotificationsBridge, QuietSyncIndicator, QuoteCapsule, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RenameSessionModal, RewindPreviewPanel, SentInlineAtomBody, SessionActionSheet, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionListDrawer, SessionMenuSheet, SessionOptionsExpoSheet, SessionResourceCards, SessionSearchNative, SessionSearchNative.ios, SessionTailBanner, SessionUsageSummary, ShareImageNativeButton, ShareImageNativeButton.ios, ShareMessageCheckbox, ShareSelectAllButton, ShareSelectionBar, SharedTaskEndedState, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, StreamingStatusText, TaskTags, TaskTagsSheet, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, [sessionId], _layout, gestureHandler, mathWebView, mediaPlayerWebView, mermaidWebView, peerFileTransport, useLocale, useSharedTaskConfirmation | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/PaperPlaneIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/AuthorizationMessageCard.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ChatFileChipMenuSheet.tsx, apps/mobile/src/session/CompanionMessageCard.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerExpandButton.ios.tsx, apps/mobile/src/session/ComposerExpandButton.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ComposerNativeInput.ios.tsx, apps/mobile/src/session/ComposerNativeInput.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerRichInput.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ContextSheetGoalView.ios.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/ConversationShareSvg.tsx, apps/mobile/src/session/ConversationShareWebView.tsx, apps/mobile/src/session/FailedScheduleNotice.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/InlineQueueSection.tsx, apps/mobile/src/session/InlineQuoteChip.tsx, apps/mobile/src/session/InlineReferenceChip.tsx, apps/mobile/src/session/InteractionPanel.tsx, apps/mobile/src/session/MarkdownBlockContent.tsx, apps/mobile/src/session/MessageActionSheet.tsx, apps/mobile/src/session/MessageRenderer.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileBoundaryNotice.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/NativePermissionSheet.ios.tsx, apps/mobile/src/session/NativePermissionSheet.tsx, apps/mobile/src/session/PendingSendBubble.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/PluginInvocationHeader.tsx, apps/mobile/src/session/PromptRecommendation.tsx, apps/mobile/src/session/QuoteCapsule.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/RewindPreviewPanel.tsx, apps/mobile/src/session/SentInlineAtomBody.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionListDrawer.tsx, apps/mobile/src/session/SessionMenuSheet.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SessionResourceCards.tsx, apps/mobile/src/session/SessionSearchNative.ios.tsx, apps/mobile/src/session/SessionSearchNative.tsx, apps/mobile/src/session/SessionTailBanner.tsx, apps/mobile/src/session/SessionUsageSummary.tsx, apps/mobile/src/session/ShareImageNativeButton.ios.tsx, apps/mobile/src/session/ShareImageNativeButton.tsx, apps/mobile/src/session/ShareMessageCheckbox.tsx, apps/mobile/src/session/ShareSelectAllButton.tsx, apps/mobile/src/session/ShareSelectionBar.tsx, apps/mobile/src/session/SharedTaskEndedState.tsx, apps/mobile/src/session/SharedTaskScreen.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/StreamingStatusText.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/session/TaskTagsSheet.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/session/composerRichInputHtml.ts, apps/mobile/src/session/conversationShareWebViewHtml.ts, apps/mobile/src/session/mathWebView.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/mermaidWebView.tsx, apps/mobile/src/session/mermaidWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/session/useSharedTaskConfirmation.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 7 | 233 | 254 |
+| `mobile.chat.sharing` | mobile | 共享任务邀请与成员 | app/shared-session.tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SharedTaskEndedState, SharedTaskScreen, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, shared-session, useLocale, useSharedTaskConfirmation | apps/mobile/app/_layout.tsx, apps/mobile/app/shared-session.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SharedTaskEndedState.tsx, apps/mobile/src/session/SharedTaskScreen.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/useSharedTaskConfirmation.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 200 | 59 |
+| `mobile.companions.direct` | mobile | 伙伴私聊回看 | app/companions/direct/[threadId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [threadId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/companions/direct/[threadId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 200 | 50 |
+| `mobile.device-management` | mobile | 设备管理 | app/devices/manage.tsx / app/devices/manage/[deviceId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceInformationFields, DeviceInformationFields.ios, DeviceLinkContext, DeviceManagementDialogs, DeviceManagementList, DeviceManagementList.ios, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RenameDeviceModal, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, manage, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/manage.tsx, apps/mobile/app/devices/manage/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceInformationFields.ios.tsx, apps/mobile/src/device-link/DeviceInformationFields.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/DeviceManagementDialogs.tsx, apps/mobile/src/device-link/DeviceManagementList.ios.tsx, apps/mobile/src/device-link/DeviceManagementList.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RenameDeviceModal.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 200 | 53 |
+| `mobile.devices` | mobile | 主机详情 | app/devices/[deviceId].tsx | AccountSwitcherSheet, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ConversationSearchFilterSheet, DeviceLinkContext, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeNativeStackHeader, HomeProjectMachineLabel, HomeSearchBar, IncomingShareBridge, MobileAgentMark, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, MobileVendorIcon, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteAccessGuide, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteTaskSuggestions, RenameSessionModal, SessionActionSheet, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionOptionsExpoSheet, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, TaskTags, ThemeProvider, [deviceId], _layout, gestureHandler, index, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/[deviceId].tsx, apps/mobile/app/devices/index.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 200 | 112 |
+| `mobile.files` | mobile | 任务文件与预览 | app/files/[sessionId].tsx / app/files/preview/[sessionId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HtmlBrowserChrome, HtmlBrowserChrome.ios, HtmlFileReader, HtmlWebsiteBrowser, ImageLightbox, IncomingShareBridge, MarkdownFileReader, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, [sessionId], _layout, gestureHandler, mediaPlayerWebView, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/files/[sessionId].tsx, apps/mobile/app/files/preview/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HtmlBrowserChrome.ios.tsx, apps/mobile/src/session/HtmlBrowserChrome.tsx, apps/mobile/src/session/HtmlFileReader.tsx, apps/mobile/src/session/HtmlWebsiteBrowser.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MarkdownFileReader.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 232 | 77 |
+| `mobile.home` | mobile | 主机与资源首页 | app/index.tsx / app/devices/index.tsx | AccountSwitcherSheet, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ConversationSearchFilterSheet, DeviceLinkContext, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeNativeStackHeader, HomeProjectMachineLabel, HomeSearchBar, IncomingShareBridge, MobileAgentMark, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, MobileVendorIcon, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteAccessGuide, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteTaskSuggestions, RenameSessionModal, SessionActionSheet, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionOptionsExpoSheet, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, TaskTags, ThemeProvider, _layout, gestureHandler, index, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/index.tsx, apps/mobile/app/index.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 200 | 108 |
+| `mobile.overlay.connection-startup` | mobile | 根布局挂载的启动与连接反馈 | app/_layout.tsx → StartupSplashOverlay / ConnectionNoticeProvider;各页面 ConnectionBanner | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ConnectionNoticeProvider, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 200 | 48 |
+| `mobile.remote-desktop` | mobile | 远程桌面 | app/devices/desktop/[deviceId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/desktop/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 200 | 48 |
+| `mobile.resources` | mobile | 远程资源列表与详情 | app/resources/[collectionId].tsx / app/resources/[collectionId]/[resourceId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteCompanionAvatar, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [collectionId], [resourceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/resources/[collectionId].tsx, apps/mobile/app/resources/[collectionId]/[resourceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 200 | 54 |
+| `mobile.settings` | mobile | 设置(含调试与日志上传可见入口) | app/settings.tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileChoicePickerList, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, settings, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/settings.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileChoicePickerList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 200 | 56 |
### 生产路由覆盖
@@ -138,6 +139,7 @@
| apps/mobile/app/sessions/[sessionId].tsx | SessionScreen | `mobile.chat.session` |
| apps/mobile/app/sessions/new.tsx | NewRemoteSessionScreen | `mobile.chat.new` |
| apps/mobile/app/settings.tsx | SettingsScreen | `mobile.settings` |
+| apps/mobile/app/shared-session.tsx | SharedSessionScreen | `mobile.chat.sharing` |
### Mobile 布局 / 开发入口排除
@@ -212,6 +214,7 @@ Mobile 已由 DS-7 纳入同一台账(2026-09-10 静态入口发现),保
| `mobile.automations` | kirozeng 协调 / Codex 发现维护;页面 owner 待认领 | legacy | — | DS-7 已发现入口;Mobile 独立阶段接管,未迁移 | 2026-09-17 复查入口变化和页面 owner;动态内容、平台实际呈现留 Mobile 独立阶段验证 |
| `mobile.chat.new` | kirozeng 协调 / Codex 发现维护;页面 owner 待认领 | legacy | — | DS-7 已发现入口;Mobile 独立阶段接管,未迁移 | 2026-09-17 复查入口变化和页面 owner;动态内容、平台实际呈现留 Mobile 独立阶段验证 |
| `mobile.chat.session` | kirozeng 协调 / Codex 发现维护;页面 owner 待认领 | legacy | — | DS-7 已发现入口;Mobile 独立阶段接管,未迁移 | 2026-09-17 复查入口变化和页面 owner;动态内容、平台实际呈现留 Mobile 独立阶段验证 |
+| `mobile.chat.sharing` | unassigned | legacy | — | DS-7 发现入口,Mobile 独立阶段接管;未迁移 | 保持现状;发现问题记下一动作,本张不修视觉 |
| `mobile.companions.direct` | kirozeng 协调 / Codex 发现维护;页面 owner 待认领 | legacy | — | DS-7 已发现入口;Mobile 独立阶段接管,未迁移 | 2026-09-17 复查入口变化和页面 owner;动态内容、平台实际呈现留 Mobile 独立阶段验证 |
| `mobile.device-management` | kirozeng 协调 / Codex 发现维护;页面 owner 待认领 | legacy | — | DS-7 已发现入口;Mobile 独立阶段接管,未迁移 | 2026-09-17 复查入口变化和页面 owner;动态内容、平台实际呈现留 Mobile 独立阶段验证 |
| `mobile.devices` | kirozeng 协调 / Codex 发现维护;页面 owner 待认领 | legacy | — | DS-7 已发现入口;Mobile 独立阶段接管,未迁移 | 2026-09-17 复查入口变化和页面 owner;动态内容、平台实际呈现留 Mobile 独立阶段验证 |
diff --git a/docs/product-rules/shared-task-mode.md b/docs/product-rules/shared-task-mode.md
new file mode 100644
index 0000000000..69e1a21a93
--- /dev/null
+++ b/docs/product-rules/shared-task-mode.md
@@ -0,0 +1,204 @@
+# 共享任务:远程连接的多人版本
+
+> 产品裁决更新:2026-09-20。实现与验证进度见文末;本文不代表已上线。
+> 产品、代码、协议与存储统一使用“共享任务 / SharedTask”,开发期旧协议不保留兼容别名。
+
+## 定位
+
+房主分享一个现有任务,其他已登录用户通过邀请进入同一个远程任务页面,共享完整历史、上下文和 Agent。复用现有远程连接、输入队列、附件、语音输入和断线恢复,不做独立会议产品或普通讨论频道。
+
+用户明确要求减少复杂度:访客与房主触发的 Agent 调用使用相同任务权限。加入方式选择最简单方案,采用邀请即授权。
+
+## 用户流程
+
+1. 房主在任务内点击“共享任务”,开启共享并复制邀请。
+2. 访客在菜单“加入共享任务”粘贴邀请,登录后直接加入,无申请或批准步骤。
+3. 双方进入现有任务页面,查看全部历史、工具结果、上下文和附件,向同一个 Agent 发消息。
+4. 房主可复制新邀请、移除访客、停止共享;访客可退出。
+
+不增加申请记录、审批通知、在线人数、正在输入、编辑标记或独立会议页面。成员列表和消息作者只用于识别参与者。
+
+## 权限与顺序
+
+- 任务由原桌面运行,模型费用沿用房主连接;同账号远控行为不变。
+- 访客可发消息、使用附件和语音输入、修改 Agent/模型/推理设置、停止 Agent。
+- Agent 工具、shell、已有插件/MCP 沿用任务现有权限,Full Access 语义不变;已有需审批操作仍由房主处理。不添加访客专属沙箱、per-turn 权限或工具审批。邀请意味着房主信任访客使用该任务的 Agent 能力。
+- 房主保留共享管理、归档/删除/导出/分支、权限模式、工作目录、插件/MCP 配置和后台/定时任务管理权限。
+- 访客通过客户端接口只能直接访问共享任务及其资源,不能调用全局凭证、其他任务或任意主机文件接口。Agent 原生工具不承诺工作目录硬隔离。
+- 消息按主机现有输入队列顺序处理,保留 clientId 幂等。访客仅编辑/撤回自己未处理消息,房主可处理全部未处理消息;直接更新内容,不显示“已编辑”。
+- 发言者身份来自经过验证的账号和成员关系,不能信任消息正文或客户端自报的身份。
+
+## 邀请、成员和生命周期
+
+- 初版为减少服务器与带宽压力,每个账号同时最多开启 2 个共享任务、最多加入 2 个共享任务;两个角色独立计数,可以同时开启 2 个并加入另外 2 个。各自跨设备统计,加入名额跨房主统计。
+- 邀请可转发,持有邀请的登录用户即可加入;每个任务最多 2 位访客(加房主共 3 人),按账号计数。服务端在事务内强制校验,超额分别提示开启、加入或访客人数已满。
+- 已存在的超额共享及成员关系不自动关闭或踢出;只拒绝新增开启/加入,退出、移除、关闭或房主离线关闭后释放对应名额。访客临时断线不释放加入名额。
+- 同一账号重复加入幂等,多个设备不重复占用名额。邀请令牌只存摘要,不进入日志。
+- 移除或退出立即撤权;原邀请不可重入,房主生成新邀请后才能再次加入。
+- 停止共享、归档、房主登出使旧邀请和成员关系失效。重新共享产生新的共享 ID。
+- 归档后恢复为活动任务,可以显式重新开启共享;须先完成旧共享关闭,旧代次的请求仍然失效。
+- 房主设备的 relay 连接确认离线后,关闭该设备承载的共享,旧邀请与成员关系失效。重新上线不会恢复旧共享,需显式重新开启并发送新邀请。已由新连接接管的旧连接退出不算离线;TTL 内短暂网络抖动不承诺立即判定。
+- 服务端是成员关系权威;主机保存恢复与关闭记录。迟到响应、旧快照、缓存和重连不能恢复已撤销访问。
+- 访客断线保留成员关系,重连后可继续访问仍有效的共享;不能影响其他访客或同账号远控。
+- 正常断开触发关闭;relay 崩溃、路由过期或关闭落库失败由服务端每 30 秒扫描补偿。访客当前通过约 5 秒轮询更新界面;服务端授权在关闭提交后立即失效。
+- 不承诺撤回访客已经看到或下载的内容。
+
+## 实现约束
+
+- 复用 packages/device-link;新增跨账号的单任务授权,禁止降级为旧版全设备远控。
+- 同时校验 invoke、push、历史、附件、嵌套引用、离线补发与结果缓存的任务及成员归属。
+- Desktop 与 Mobile 复用现有任务页面;房主在手机上通过既有同账号远控管理共享。网页端和匿名访客不在范围内。
+- 新协议以能力协商开放;缺少能力提示升级。两区域独立,不默认跨区域加入。
+- 关闭记录必须落入原 profile 的 journal 后才能释放数据库;本地同步撤权,服务端失败下次恢复重试。
+- 登出时等待已发出的创建请求收尾,迟到的创建 ID 也必须先落关闭记录;在线关闭仅使用退出账号的固定凭证与端点,不刷新或影响新账号。
+- 移除请求未获确认前暂停该成员访问;网络失败须以服务端状态恢复。临时暂停或同账号新增设备造成的旧授权失效返回可重试错误,只有确认撤权才从访客端移除任务。
+- 本仓只改客户端;服务端实现位于独立 cindy-server 的本任务 worktree。两仓协议需一致。
+
+## 开发期命名与发布顺序
+
+2026-09-18 用户确认:功能仍在开发,不维护旧共享协议和存储命名兼容层。客户端和服务端各自维护本仓协议包并同步更新;独立 cindy-protocol 仓不再被当前 workspace 消费。
+
+- 类型与函数统一为 SharedTask / sharedTask,能力为 shared-task-v1,逻辑 peer 前缀为 shared-task~,REST 为 /api/device-link/shared-tasks,标识字段为 sharedTaskId,IPC 为 maker:shared-task / shared-task:account。普通同账号远控协议不变。
+- SQLite 使用 shared_task_events / shared_task_id;Prisma 使用 SharedTask、SharedTaskGuest、SharedTaskInvitation。旧标识仅用于历史 migration 与一次性搬迁输入,运行期无旧接口、双写或别名。
+- 不支持新旧共享版本混用。本地验证先停旧 relay,迁移数据库,再同时启动新版 relay 和房主、访客客户端。若目标环境已运行旧共享版本,合并前需建立可强制停旧并迁移的部署 gate,不能直接滚动发布改名版本。
+- 旧开发分支 migration 0108、0110 未进入 main,已与新主干编号冲突。基于 2026-09-20 的主干 0113 重新生成 0114_shared_task_events。旧分支沙箱保留原库备份,使用新的独立沙箱验收,禁止改写 schema_version 或强行打开不匹配库。正确迁移链内的历史共享记录、消息作者与队列作者由 companion 一次性搬迁,不删除历史消息。
+
+- 尚未部署共享功能的环境先执行服务端增量 migration,再升级全部 relay,最后发布客户端。已部署旧开发期共享版本的环境按上面的停旧窗口处理。服务端不改写既有同账号设备关系;不能把缺少共享能力的 relay 当作已支持。
+- 新客户端连接旧 relay 时,普通同账号远控继续使用原协议;共享入口提示升级,Mobile 不轮询旧 relay 的共享 API。新 relay 连接旧房主时,房主缺少共享 channel 的错误也提示升级,不能降级为全设备访问。
+- 错误处理只把明确的能力缺失或版本不兼容映射为升级提示,断网或超时错误仍提示重试。Mobile 连接未建立时将能力视为未知,显示重试;重新连接后重新读取能力,升级后可恢复共享。
+- Desktop 的本地 SQLite migration 0110 为增量建表,但“可从旧版升级”不等于“可用旧版打开新库”。既有 migration manifest / schema 校验会拒绝旧程序打开已升级数据库;本功能不放宽该保护。
+- 发布前保留升级前数据库备份。需要回退时优先修复新版;如必须恢复旧程序,应使用升级前的对应备份,并明确接受备份之后的数据不会随之保留。不得通过降低 schema 版本、删表或改历史 migration 强行回退。服务端回退时保留增量表,不执行破坏性 down migration。
+- 新旧版本真实混合部署尚未端到端实测;能力协商与错误提示的自动化回归不能替代该发布验收。
+
+## UI review 与全部关闭(2026-09-18)
+
+[单文件交互原型](../../artifacts/shared-task-design/index.html) 展示三种入口:A 任务顶部小面板与账号菜单;B 一个共享窗口,分当前任务与我发起的共享;C 侧栏入口与右侧管理面板。原型是设计展示,不是实际客户端或验收截图。Light/Dark、小屏及开启、加入、邀请、移除、全部关闭、离线结束一起评审。
+
+已选定方案 B:“共享任务 → 我发起的 → 关闭全部共享”。范围为当前账号、当前区域内由我发起的共享(含其他主机),不退出加入别人的任务、不停止 Agent、不删除任务、不影响同账号远控。确认面板列出任务与主机,默认取消;失败保留未关闭项供重试。
+
+实现状态(2026-09-20):已按方案 B 在 Desktop 落地统一共享任务窗口(`SharedTaskButton.tsx`),含「当前任务 / 我发起的」页签、确认面板(移除 / 退出 / 关闭当前 / 关闭全部,默认取消)与房主离线结束态;账号级 `owned` / `close` IPC(`shared-task:account`)支持跨主机关闭,失败保留未关闭项供重试。Mobile 仍沿用任务菜单内的共享入口。
+
+## 验收
+
+### 桌面共享任务入口修订(2026-09-20,用户确认)
+
+- 采用列表内分组:访客显示「我加入的共享」,房主显示「我开启的共享」。两种角色同时存在时,在同一分组内用标准胶囊切换条显示「我开启的 / 我加入的」,每次展示对应任务;只有一种角色时保持普通分组标题。分组及切换条均不显示计数,且不受下方设备筛选影响。
+- 共享不是常用功能:未开启且未加入共享任务时,整个分组隐藏,不保留空状态、加入按钮或分隔线;首次开启或加入后出现,最后一个共享关闭或退出后自动隐藏。首次加入继续使用原有菜单入口。
+- 设备菜单仅保留真实设备,不显示共享任务或内部 peer 标识。访客任务不再重复混入下方普通项目/任务列表。房主任务仍保留原项目归属,共享分组作为快捷入口。
+- 共享任务行沿用普通任务的 Agent 身份图标,按任务的 Agent 类型显示;不得因共享状态替换为人群图标。
+- 已加入任务直接打开既有任务页面,重复点击当前任务不重新连接、不清空页面。访客撤权继续使用现有结束提示与清理路径,不缓存已失效的可访问内容。
+- 加入弹窗采用 C 方案:标题说明下显示「我发起的共享 / N 个进行中」,右侧灰阶「关闭全部共享」,与底部加入按钮分离。无共享时禁用,获取失败可重试,不把未知状态当成零个。
+- 关闭确认在同一个窗口内替换表单内容,不叠加第二个弹窗;列出确认时的任务及所在电脑类别,默认聚焦取消。取消保留邀请与昵称。只关闭确认清单中的我发起的共享,失败保留未关闭项重试;不退出我加入的任务、不停止 Agent、不删除记录。账号变化或窗口退出后,旧请求不得继续操作下一项。
+- 本轮设计稿面向 Desktop;Mobile 仍遵循上文全屏主页面和平台确认控件规则。
+
+### 手机版交互修订(2026-09-20,用户确认)
+
+- 用户实机验收后否定“任务背景+共享半屏+确认半屏”的叠层,并进一步澄清:**共享主页面全屏,少量信息的确认使用弹窗**。这项澄清替代早期手机底部面板和之后“所有确认也全屏”的实现;Desktop 仍采用统一共享窗口。
+- 手机保留“当前任务/我发起的”结构。加入、成员、成功、结束与空状态使用完整页面;移除、退出、关闭当前和关闭全部使用紧凑确认,不另开全屏页,不再叠加两个半屏。iOS 复用 `showConfirm` 系统 Alert;Android 默认绿色按钮 Alert 已被用户否定,改为语义 token 的 12px 圆角卡片、灰阶取消与红色实心胶囊确认按钮,长正文可滚动、操作按空间换行,不通过原生配置改色。
+- 已进入任务的手机访客,在“任务详情”直接看到“退出共享任务”,不再进入共享成功/管理页,也不再重复显示“进入任务”。点击后确认,取消保持当前任务、详情面板及消息位置;确认成功才退出并清理该共享连接,失败保留任务可重试。房主仍显示“共享任务”管理入口,首次加入后的成功页仍保留“进入任务”。
+- 取消保留原页签、表单与滚动位置,Android 系统返回只取消、遮罩不关闭;只有确认才执行。弹窗拦截背景交互,防止重复弹出;账号、页面或授权上下文已变更的旧确认不能继续执行。全部关闭保留确认时的任务清单与影响范围。
+- iOS 沿用 `SimpleStackHeader` 原生导航和系统 UIAlertController。液态玻璃、旧版回退、按钮排列、动态字体、长内容滚动与无障碍遵循系统;不新增原生依赖或改动 runtime fingerprint。HTML 补充平台说明和 iOS / Android 示意切换,原型模糊不等于原生玻璃实测。
+- 本地自包含 HTML 已同步全屏主页面+紧凑确认弹窗;原型与真实客户端截图分别记录,不混用作验收证据。
+
+### Android CN 本轮补充验证(2026-09-20)
+
+- 访客任务详情改为直接退出后,最新 Android 主题确认框已在 CN 模拟器检查浅色/深色外观,按钮取消及系统返回保留原详情与消息位置。定向回归 21 项、Mobile 类型检查通过;iOS 原生确认与动态大字体尚未实机验证。当前主题确认框的确认退出分支由单测覆盖,真实确认退出记录来自同一业务逻辑的较早原生确认版本。
+- 较早的原生确认版本曾完成 Android CN 浅色/深色的退出弹窗、系统返回取消、按钮取消及确认退出验证。该 Android Alert 外观随后被用户否定,不能作为当前主题确认框的视觉通过证据。iOS 液态玻璃、VoiceOver、动态大字体和长任务清单滚动尚未实机验证,不能将 HTML 示意当成通过证据。
+- 访客“进入任务”失败定位到设备级资源 manifest:共享访客不具备该权限。手机不再请求整机 manifest,保留当前共享任务已有范围;CN 模拟器连续三次进入正常,读取完整历史,并发送消息收到同一 Agent 的 PLAN_B_CN_OK。
+- 临时断网不当作撤权;确认关闭或移除后隐藏发送与失效操作,显示可重新加入的结束态。加入、成功、退出确认、取消与重新加入已完成真实回归。
+- 全屏修订后已验证房主开启、成员页、我发起的、关闭全部确认、返回取消、关闭后空状态,以及移除访客的取消/确认。Light 与 Dark 均有真实 Android 截图;未宣称每一子界面均完成双主题覆盖。
+- 全屏访客补测:正常邀请加入后两次进入同一任务均成功;退出确认顶部返回恢复成功页,确认退出后可用新邀请重新加入并第三次进入。房主关闭共享后显示全屏结束页,隐藏输入和失效操作;“使用新邀请加入”返回空白加入表单。上述步骤均通过真实客户端操作,关键步骤已发送 Android PNG 截图。
+- Mobile 定向回归 54 项、scope、smoke 与 Desktop/Mobile 类型检查通过;根相关单测门禁仍未通过,剩余失败涉及 Windows 内置 Skill 文件复制 EPERM、环境模块测试加载器及输入推荐测试,不将定向结果记作完整门禁通过。
+- 此记录不覆盖 iOS、多主机批量关闭、多个访客并发及标准软键盘避让;先前 Gboard 手写浮条不能替代标准键盘测试。
+
+### Desktop 方案 B 子界面与本轮验证(2026-09-20)
+
+- 统一窗口宽 440px;房主保留「当前任务 / 我发起的」页签。开启页使用任务卡片、权限说明、离线提示与全宽主按钮;成员页使用邀请卡片、头像、身份及移除入口。
+- 加入页使用多行邀请输入框、最长 32 字昵称、说明与加入按钮。加入成功先显示任务标题和「进入任务」,不跳过成功页;生产界面不包含原型的填入演示按钮。
+- 移除、退出、关闭当前及全部关闭使用独立确认层,原界面保留在后方。按用户选定设计,左侧取消、右侧确认,默认聚焦取消;该排列仅在共享任务显式启用,不改变其他确认框。
+- 结束提示由窗口级组件承接,避免离开失效任务时一起卸载;「使用新邀请加入」打开加入表单。沿用现有撤权和导航判定,不新增访问权限。没有明确离线原因时使用“当前已无法访问”的通用文案,不能把手动关闭或移除误称为房主离线。
+- 两个真实 Electron 隔离客户端、不同账号:已验证开启、复制邀请、加入成功、进入任务读取历史、移除取消与确认、退出确认、重新邀请、关闭当前、关闭全部、空状态及结束后重新打开加入表单。截图来自原生窗口;截图前激活目标窗口,防止后台窗口缓存旧画面。
+- 已通过设置界面切换 Light/Dark。浅色目检加入、成员、成功、结束和确认页;深色目检空状态和移除确认。未将这些结果记为所有子界面的双主题全覆盖。
+- 实际重启房主隔离沙盒:访客出现结束提示;房主重新启动返回 ready 后,「我发起的」为 0,共享没有自动恢复。两个沙盒保持运行,房主主题已恢复浅色。
+- 定向回归 22 项通过,Desktop 类型检查通过,i18n 与术语表检查通过(存量告警保留)。本轮未验证 Mobile、多个访客并发、跨主机批量关闭和新的 Agent 工具调用;不据此宣称完整功能黑盒验收已完成。
+- 后续排查顶部错误 Toast:后台自动化点击复制邀请时,邀请请求成功,但浏览器剪贴板因文档失焦返回 NotAllowedError。已把复制失败与共享请求失败分别提示;实际鼠标事件点击复制成功。新增两项回归后,共享窗口定向测试 9 项通过,类型和文案检查通过。该失败不应被之前的成功路径总结掩盖。
+
+### 功能验收清单
+
+- 房主与两个不同账号访客进入同一任务,访客加入无需审批,完整历史可读,多人发言进入同一 Agent。
+- 原同账号远控、正常任务权限、Full Access、串行队列和重复输入幂等不退化。
+- 访客无法直接访问其他任务、伪造作者、改他人队列或响应房主审批。
+- 退出/移除/停止共享/归档/登出立即阻断后续访问,旧邀请和迟到响应不复活权限。
+- 访客重启恢复、房主离线关闭、断线补发、附件上传下载、SSH 工作区、Desktop/Mobile 和旧版拒绝有相应验证。
+- 一个访客停止 ACK 时其他访客和房主控制端仍可工作。
+- UI 使用语义 token 支持 Light/Dark,实际验证结果如实记录,不以类型检查代替联调。
+
+## 本地联调
+
+最小组合是一套测试服务、一个房主 Desktop 和一个访客客户端。验证多人并发时增加第二个访客,使用三个不同 Cindy 账号;同账号的两个实例走既有远控,不能用于验收跨账号共享。
+
+1. 在独立测试数据库和 Redis 上启动本任务版本的 device-link-server,并执行该服务的 Prisma migration。登录需使用同一测试区域的 auth-server;附件上传下载还需要可用的测试对象存储配置。不要把测试指向生产数据库。
+2. 两个 Desktop 使用不同 checkout、不同命名沙箱和独立端口。分别从各自 checkout 使用仓库根安全启动入口:
+
+ pnpm restart:desktop:local --region=global --isolated=sharing-host
+ pnpm restart:desktop:local --region=global --isolated=sharing-guest
+
+ 启动参数、端点与端口以 [Desktop 开发规则](../dev-rules/desktop-development.md) 为准;包装脚本会停止当前 checkout 的旧开发实例,因此不要在同一个 checkout 连续执行两次来模拟双客户端。也可用 Desktop 房主加 Mobile 访客;手机端点必须是手机可达的测试服务地址。
+3. 房主打开已有任务,开启共享并复制邀请。访客从菜单加入,确认无需审批即可进入普通任务页,能够查看加入前的消息、工具结果和附件。
+4. 同时发送不同内容,确认两个客户端看到同一 Agent 输出及正确作者。Agent 忙时编辑或撤回自己的待发送消息;修改其他成员的待发送消息应失败。编辑带图片的消息,保留旧附件并增加新附件,确认发送后和重载后都可打开。
+5. 分别验证切换 Agent、模型和推理设置、停止 Agent、普通权限与 Full Access。已有审批由房主处理,访客能查看请求并继续排队发消息。
+6. 访客断网后重连,确认有效共享与历史恢复。房主退出或确认离线后共享关闭、旧邀请失效,上线后需重新开启。单个访客断线时,另一个访客及同账号远控继续工作。
+7. 验证移除、退出、停止共享、归档和登出。旧邀请不能恢复已退出或移除的身份,新邀请可以重新加入;未共享任务与主机全局设置不可经访客客户端访问。
+8. 验证本地工作区及 SSH 工作区的图片、音频、视频,检查 Light/Dark 和小屏。旧服务端或旧客户端应提示升级,不得退化成全设备控制。
+
+## 兼容性补充验证(2026-09-17)
+
+- Desktop / Mobile 的旧主机错误提示、Mobile relay 能力状态与共享列表轮询相关 34 项自动化回归全部通过;覆盖断网不误报升级、升级后恢复、迟到旧账号响应不更新界面。
+- 根目录 `pnpm test:unit:related` 通过(退出码 0),Desktop / Mobile 类型检查通过。测试调度器 537 项通过、8 项按条件跳过;本地需将 Git Bash 加入测试进程 PATH,未修改或弱化测试。
+- 本轮未做新旧版本实机联调,无新增实机截图;上述自动化结果不计作 Mobile 实机或混合版本部署验收。
+
+## 验证记录(2026-09-16)
+
+以下保留当日实际结果。房主重启自动恢复的旧验收口径已被 2026-09-18 的“房主离线关闭共享”裁决取代,不再作为当前预期。
+
+### 真实双账号 Desktop 联调
+
+使用两个真实 Electron 开发客户端、不同账号和独立沙箱,连接隔离的 auth-server、device-link-server、PostgreSQL 与 Redis。Agent 使用真实模型并在房主执行工具;以下结果不是模拟 IPC 或 HTML 页面验证。
+
+- 房主开启共享并复制邀请;访客无需审批即可加入,能读取加入前历史并准确回答其中的测试暗号。
+- 访客发言进入同一个 Agent;房主和访客均显示访客作者、实时回复、工具活动和处理状态。
+- 访客触发真实 PowerShell 工具;Agent 忙时,访客编辑自己的待发送消息,撤回另一条待发送消息;最终只处理编辑后仍保留的消息,不显示编辑标记。
+- 房主移除访客后,访客立即离开任务、共享列表项消失;旧邀请被拒绝,房主生成新邀请后可以重新加入并读取历史。
+- 房主独立重启,访客窗口保持打开且未刷新;连接自动恢复,新消息收到 HOST_RESTART_RECOVERED。观察到可信连接来源代次从 1 递增到 2,房主进程代次从 2 回落到 1,推送仍正常接收。
+- 房主停止共享后,访客立即退出并看到远程任务已结束;原邀请无法重新加入。
+- 每个关键步骤均保存真实 PNG 截图,并通过手机可打开的文件图片链接发送。
+
+### 本轮修复与自动化验证
+
+- 修复跨账号房主推送被同账号过滤器丢弃:绑定服务端已验证的房主身份,同时保留访客本地账号边界和房主来源代次校验。
+- 修复共享任务状态、工具活动和用量没有实时同步:仅向该任务的已授权访客补发对应事件,不授予全局任务订阅。
+- 修复同账号状态重新提交与房主重启后的恢复:退役旧授权捕获,按可信新连接更新来源代次,拒绝迟到旧帧,不重启其他成员的 relay。
+- 断线健康检查改为读取已授权的单个任务,不再调用访客无权访问的全局任务列表;Desktop 与 Mobile 共用检查逻辑。
+- 补齐任务内子 Agent 历史与后台活动只读查询的范围校验。
+- 服务端共享状态轮询不再消耗邀请等写操作的限流额度;写操作仍按账号独立限流。
+- 最终 `pnpm test:unit:related` 完整通过(退出码 0),覆盖 Desktop、Mobile、device-link、maker-core、maker-shared、lizi-mcps 与 orca-workflow;Desktop、Mobile 类型检查通过,device-link TypeScript 检查通过。
+- 服务端单测 182 项通过、类型检查通过;另有 1 项真实多实例集成测试按条件跳过,不视为通过。
+- 先前客户端 SQLite 全量 migration 回放及共享记录测试 17 项通过;附件上传/编辑、历史媒体归属、作者校验、撤权、关闭与恢复竞态已有自动化回归。
+- 独立复核发现并修复上下文用量查询的冷启动配置入口:访客参数不能控制 Agent 启动,配置与目录授权只从主机读取,关键副作用前复验成员有效性;相关 14 项回归通过。房主重启修复的定向检查通过(Client 229 项、Owner fence 8 项、文本批处理 178 项),复核未报告剩余 P0/P1。
+
+### 尚未验证与已知限制
+
+- 真实 Mobile、两个访客同时在线、同账号控制端共存、单个访客停止 ACK、SSH 工作区与真实对象存储附件上传下载尚未完成端到端验证。Mobile 没有运行中的模拟器或匹配安装包;测试对象存储未配置。不能用单测或双 Desktop 结果替代这些验收。
+- 归档、登出、旧版能力拒绝等路径有自动化覆盖,未逐项做真实 UI 联调。
+- Light/Dark 和 390px 窄屏曾用真实 React 控件配合模拟账号/IPC 目检,仅证明控件展示;不计作完整 Electron 双主题或 Mobile 实机验收。
+- 无效、撤销或已停止共享的邀请会被拒绝,但当前错误提示笼统显示“未能更新共享状态,请检查连接后重试”,尚未区分邀请失效原因。
+- 未部署服务端或发布客户端。
+
+### 三轮独立 Review 与逐轮修复(2026-09-16)
+
+- 第 1 轮:合法新增设备不再撤销原设备连接;移除请求尚未确认时只暂停访问。在线登出先保存关闭记录,再用固定的退出账号凭证关闭服务端共享,失败留待恢复重试。
+- 第 2 轮:请求准入、建链、订阅、执行完成和最终发包统一区分临时不可用与确认撤权。登出与创建共享并发时,迟到的创建 ID 仍先写入关闭记录,旧数据库等待这些请求收尾后才释放。
+- 第 3 轮:同账号、区域和数据库的运行实例重绑定保留未完成创建的清理记录;归档后恢复的任务可重新共享,旧请求和旧共享不能复活。
+- 最后一轮未发现剩余确认的 P0/P1;最终生命周期与 dispatch 定向回归 51 项通过,Desktop/Mobile 类型检查与 device-link TypeScript 检查通过。
+- 源码冻结后重新执行根目录 `pnpm test:unit:related`,退出码 0:Desktop、Mobile、device-link、lizi-mcps、maker-core、maker-shared、orca-workflow 均通过;测试调度器 534 项通过、8 项按条件跳过。
+- 本次增补的实机登出测试未完成:隔离启动命令的最终检查报 `STARTUP_FAILED / Invalid array length`,定位到已有 `desktop-whoami` 进程子树遍历。未用模拟界面代替实机截图,也不将此轮自动化回归记为 UI 验收。
diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.md
index d63430fd41..ebe4df2a8b 100644
--- a/i18n/GLOSSARY.md
+++ b/i18n/GLOSSARY.md
@@ -487,6 +487,10 @@ Orca Worker 创建卡上的命名字段。它只是派活用的名字,不改
日志上报文案里对「App 自身运行日志」的用户可见说法。刻意不直接叫「日志」: 设置页同屏已有「日志目录」「Debug 日志」两处指本地文件, 而这里要表达的是被上报的那部分内容(基础设施运行记录, 不含对话)。proposed: 与「日志」的分工尚未产品裁决。
+### Shared Session
+
+远程连接的多人版本,按单个任务共享完整上下文和同一 Agent,不作为独立会议产品。
+
### shortcut listener permission
macOS TCC 的 kTCCServiceListenEvent(系统设置里叫「输入监控」)在 Cindy 内的对外称法。产品侧只按用途讲: 这个权限只服务语音输入快捷键的监听, 不讲系统实现, 所以 zh-CN 沿用设置页权限项已有的「监听权限」(settings.voiceInput.permissions.inputMonitoring.label), 不引入「输入监控」这个直译——后者听起来像 Cindy 在监控用户的全部输入, 与实际能力(只识别快捷键按键组合)不符, 反而制造隐私误解。禁用项都挂 whenEn 条件: 要引用 macOS 系统设置面板名本身时那是 OS 的 UI 名称, 不受本条约束。四语的比喻不统一(en listener / ja 監視 / ko 감지)是现状登记而非裁决——各语言内部一致但跨语言不同, 保持 proposed 等产品拍板, 先把清单摆出来防止继续在 listener / monitoring / detection 之间漂移。
diff --git a/i18n/glossary.json b/i18n/glossary.json
index 58c04c1069..86b2bd0f90 100644
--- a/i18n/glossary.json
+++ b/i18n/glossary.json
@@ -5,6 +5,13 @@
"sourceLocale": "en",
"punctuationExempt": ["desktop:settings.help.qnaFeedbackBodyTemplate"],
"terms": [
+ {
+ "id": "shared-session",
+ "status": "proposed",
+ "en": "Shared Session",
+ "translations": { "zh-CN": "共享任务", "zh-TW": "共享任務", "ja": "共有セッション", "ko": "공유 세션" },
+ "note": "远程连接的多人版本,按单个任务共享完整上下文和同一 Agent,不作为独立会议产品。"
+ },
{
"id": "chat-workspace",
"status": "proposed",
diff --git a/packages/device-link-protocol/src/protocol.ts b/packages/device-link-protocol/src/protocol.ts
index 5dfa5c8ac3..48acef3208 100644
--- a/packages/device-link-protocol/src/protocol.ts
+++ b/packages/device-link-protocol/src/protocol.ts
@@ -19,6 +19,8 @@
/** 协议版本:整数,只升不降;不兼容改动 +1。 */
export const PROTOCOL_VERSION = 1;
+export * from './sharedTask.js';
+
/** 单帧最大字节数(超过即回 PAYLOAD_TOO_LARGE 并丢弃,不断连;发送方应先行拒绝/裁剪) */
export const MAX_FRAME_BYTES = 2 * 1024 * 1024;
@@ -105,6 +107,8 @@ export interface HelloPayload {
remoteControlEnabled: boolean;
busy: boolean;
deviceInfo?: DeviceInfo;
+ /** Optional endpoint capabilities; sharedTask peers require explicit bilateral support. */
+ capabilities?: string[];
}
/** hello-ack 帧 payload(server→client) */
diff --git a/packages/device-link-protocol/src/sharedTask.ts b/packages/device-link-protocol/src/sharedTask.ts
new file mode 100644
index 0000000000..624d0b70d6
--- /dev/null
+++ b/packages/device-link-protocol/src/sharedTask.ts
@@ -0,0 +1,37 @@
+/**
+ * Task-scoped logical peers multiplexed over the existing reliable device link.
+ * A sharedTask peer is NOT a physical device identifier or an authorization grant.
+ * Relay and both endpoints must negotiate this capability before using it.
+ */
+export const SHARED_TASK_RELAY_CAPABILITY = 'shared-task-v1';
+export const SHARED_TASK_PEER_PREFIX = 'shared-task~';
+export type SharedTaskPeer =
+ | { sharedTaskId: string; role: 'host' }
+ | { sharedTaskId: string; role: 'guest'; memberId: string; deviceId: string };
+
+function identifier(value: string): string {
+ if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(value)) throw new Error('Invalid sharedTask peer identifier');
+ return value;
+}
+export function sharedTaskHostPeer(sharedTaskId: string): string {
+ return `${SHARED_TASK_PEER_PREFIX}${encodeURIComponent(identifier(sharedTaskId))}~host`;
+}
+export function sharedTaskGuestPeer(sharedTaskId: string, memberId: string, deviceId: string): string {
+ return `${SHARED_TASK_PEER_PREFIX}${encodeURIComponent(identifier(sharedTaskId))}~guest~${encodeURIComponent(identifier(memberId))}~${encodeURIComponent(identifier(deviceId))}`;
+}
+export function isSharedTaskPeer(value: unknown): value is `shared-task~${string}` {
+ return typeof value === 'string' && value.startsWith(SHARED_TASK_PEER_PREFIX);
+}
+/** Malformed reserved peers must be rejected, never retried as legacy device IDs. */
+export function parseSharedTaskPeer(value: unknown): SharedTaskPeer | null {
+ if (!isSharedTaskPeer(value) || value.length > 1600) return null;
+ try {
+ const parts = value.split('~');
+ const sharedTaskId = identifier(decodeURIComponent(parts[1] ?? ''));
+ if (parts.length === 3 && parts[2] === 'host' && sharedTaskHostPeer(sharedTaskId) === value) return { sharedTaskId, role: 'host' };
+ if (parts.length !== 5 || parts[2] !== 'guest') return null;
+ const memberId = identifier(decodeURIComponent(parts[3]));
+ const deviceId = identifier(decodeURIComponent(parts[4]));
+ return sharedTaskGuestPeer(sharedTaskId, memberId, deviceId) === value ? { sharedTaskId, role: 'guest', memberId, deviceId } : null;
+ } catch { return null; }
+}
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index 28bc710b50..968113b4b0 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -122,6 +122,48 @@ function makeHarness(opts?: {
const tick = (ms = 0): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
+describe('verified outbound stream notification', () => {
+ it('notifies before business delivery and keeps two peers independent across restart', async () => {
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 } });
+ h.client.start(); await tick(); h.current().ack();
+ const events: string[] = [];
+ const off = h.client.onPeerStreamAccepted((peer, stream) => { events.push(peer + ':' + stream); });
+ h.client.onFrame((frame) => { if (frame.kind === 'push') events.push('push:' + frame.src); });
+ const accept = async (peer: string, stream: string) => {
+ const opened = h.client.openLink(peer, { controllerName: 'Test', protocolVersion: 1, appVersion: '1' });
+ const request = h.current().sent.filter((e) => e.kind === 'link-open').at(-1)!;
+ h.current().push({ v: PROTOCOL_VERSION, kind: 'link-accept', id: request.id, src: peer, payload: {
+ appVersion: '1', allowlistHash: 'hash', capabilities: [DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT],
+ transportStreamId: stream,
+ } });
+ await opened;
+ };
+ const push = (peer: string, stream: string, seq: number) => {
+ for (const frame of encodeReliableFrames({ v: PROTOCOL_VERSION, kind: 'push', src: peer,
+ payload: { channel: 'maker:event', payload: {} },
+ }, stream, seq)) h.current().push(frame);
+ };
+ try {
+ h.current().push({ v: PROTOCOL_VERSION, kind: 'link-accept', id: 'unrequested', src: 'a',
+ payload: { appVersion: '1', allowlistHash: 'hash', transportStreamId: 'unverified' } });
+ expect(events).toEqual([]);
+ await accept('a', 'old');
+ await accept('b', 'steady');
+ push('a', 'old', 1); push('b', 'steady', 1); await tick();
+ expect(events).toEqual(['a:old', 'b:steady', 'push:a', 'push:b']);
+ await accept('a', 'new');
+ push('a', 'new', 1); push('b', 'steady', 2); await tick();
+ expect(events.slice(4)).toEqual(['a:new', 'push:a', 'push:b']);
+ push('a', 'old', 2); await tick();
+ expect(events).toHaveLength(7);
+ off();
+ await accept('a', 'last');
+ expect(events).toHaveLength(7);
+ expect(h.sockets).toHaveLength(1);
+ } finally { h.client.stop(); }
+ });
+});
+
describe('network change probes', () => {
it.each([true, false])('only post-hint valid inbound activity avoids the redundant probe (valid=%s)', async (valid) => {
vi.useFakeTimers();
diff --git a/packages/device-link/src/__tests__/sharedTask.test.ts b/packages/device-link/src/__tests__/sharedTask.test.ts
new file mode 100644
index 0000000000..1de20ff20d
--- /dev/null
+++ b/packages/device-link/src/__tests__/sharedTask.test.ts
@@ -0,0 +1,116 @@
+import { describe, expect, it } from 'vitest';
+import {
+ authorizeSharedTaskOperation as authorize,
+ parseSharedTaskSnapshot as parse,
+ isSharedTaskAttachment, sharedTaskTopics,
+} from '../sharedTask.js';
+import { buildAttachmentOssRef } from '../attachmentOssRef.js';
+
+const snapshot = () => ({
+ sharedTaskId: 'sharedTask-1', sessionId: 'session-1', ownerAccountId: 'owner', hostDeviceId: 'desktop',
+ status: 'active', revision: 1,
+ guests: [
+ { memberId: 'member-a', accountId: 'guest-a', version: 1, deviceIds: ['phone-a', 'desktop-a'] },
+ { memberId: 'member-b', accountId: 'guest-b', version: 1, deviceIds: ['phone-b'] },
+ ],
+});
+const guest = { accountId: 'guest-a', deviceId: 'phone-a' };
+const owner = { accountId: 'owner', deviceId: 'owner-phone' };
+
+describe('sharedTask authorization', () => {
+ it('keeps task subscriptions but removes the full-device list from shared peers', () => {
+ expect(sharedTaskTopics('shared-task~shared~host', ['sessions', 'session:task'])).toEqual(['session:task']);
+ expect(sharedTaskTopics('my-desktop', ['sessions', 'session:task'])).toEqual(['sessions', 'session:task']);
+ });
+ it('only permits attachment references in this sharing namespace', () => {
+ const ref = (ossKey: string) => buildAttachmentOssRef({ ossKey, originalName: 'image.png', mimeType: 'image/png', size: 1, sha256: 'a'.repeat(64) });
+ expect(isSharedTaskAttachment(ref('cindy/shared-task/shared/u/file.png'), 'shared')).toBe(true);
+ for (const key of ['cindy/shared-task/other/u/file.png', 'cindy/device-link/u/file.png', 'cindy/shared-task/shared/u/../file.png']) {
+ expect(isSharedTaskAttachment(ref(key), 'shared')).toBe(false);
+ }
+ expect(isSharedTaskAttachment('file:///private/file.png', 'shared')).toBe(false);
+ });
+ it.each(['history.read', 'attachment.read', 'attachment.upload', 'input.send', 'agent.configure', 'agent.stop'])(
+ 'lets an approved guest %s without treating them as the owner', (operation) => {
+ expect(authorize(parse(snapshot()), guest, 'session-1', operation)).toMatchObject({ allowed: true, role: 'guest', memberId: 'member-a' });
+ },
+ );
+ it.each(['approval.resolve', 'permission.configure', 'workdir.configure', 'plugins.configure',
+ 'history.delete', 'session.archive', 'session.export', 'session.fork', 'background.create', 'schedule.create', 'sharedTask.manage'])(
+ 'requires the owner for %s even when a guest can configure the model', (operation) => {
+ expect(authorize(parse(snapshot()), guest, 'session-1', operation)).toEqual({ allowed: false, reason: 'owner-required' });
+ expect(authorize(parse(snapshot()), owner, 'session-1', operation)).toMatchObject({ allowed: true, role: 'host' });
+ },
+ );
+ it('does not authorize a different task, unapproved device, or swapped account', () => {
+ const state = parse(snapshot());
+ expect(authorize(state, guest, 'session-2', 'history.read').allowed).toBe(false);
+ expect(authorize(state, { ...guest, deviceId: 'phone-b' }, 'session-1', 'history.read').allowed).toBe(false);
+ expect(authorize(state, { ...guest, accountId: 'stranger' }, 'session-1', 'history.read').allowed).toBe(false);
+ expect(authorize(state, owner, 'session-2', 'history.read').allowed).toBe(false);
+ });
+ it('denies unknown operations including toString rather than inheriting object properties', () => {
+ for (const operation of ['toString', '__proto__', 'approval.auto', 'shell.execute']) {
+ expect(authorize(parse(snapshot()), owner, 'session-1', operation)).toEqual({ allowed: false, reason: 'unknown-operation' });
+ }
+ });
+ it.each(['input.edit', 'input.withdraw'])('checks authoritative ownership and pending state for %s', (operation) => {
+ const state = parse(snapshot());
+ const item = { sessionId: 'session-1', authorAccountId: 'guest-b', state: 'pending' as const };
+ expect(authorize(state, guest, 'session-1', operation, item).allowed).toBe(false);
+ expect(authorize(state, owner, 'session-1', operation, item).allowed).toBe(true);
+ expect(authorize(state, guest, 'session-1', operation, { ...item, authorAccountId: 'guest-a' }).allowed).toBe(true);
+ expect(authorize(state, owner, 'session-1', operation, { ...item, state: 'accepted' }).allowed).toBe(false);
+ expect(authorize(state, owner, 'session-1', operation, { ...item, sessionId: 'session-2' }).allowed).toBe(false);
+ expect(authorize(state, owner, 'session-1', operation).allowed).toBe(false);
+ });
+ it('closed and not-yet-loaded sharedTasks cannot authorize their owner or guests', () => {
+ for (const actor of [guest, owner]) {
+ expect(authorize(null, actor, 'session-1', 'history.read').allowed).toBe(false);
+ expect(authorize(parse({ ...snapshot(), status: 'closed' }), actor, 'session-1', 'history.read').allowed).toBe(false);
+ }
+ });
+});
+
+describe('sharedTask authority decoding', () => {
+ it('projects unknown fields, copies and freezes nested device grants', () => {
+ const input = snapshot();
+ const parsed = parse({ ...input, token: 'invalid-fixture-secret', role: 'host' });
+ input.guests[0].deviceIds.push('attacker-device');
+ expect(parsed).not.toHaveProperty('token');
+ expect(parsed).not.toHaveProperty('role');
+ expect(parsed.guests[0].deviceIds).not.toContain('attacker-device');
+ expect(Object.isFrozen(parsed.guests[0].deviceIds)).toBe(true);
+ expect(Object.isFrozen(parsed.guests)).toBe(true);
+ });
+ it.each([0, -1, 0.5, Number.NaN, Number.MAX_SAFE_INTEGER + 1, '1'])(
+ 'rejects ambiguous revisions %s', (revision) => expect(() => parse({ ...snapshot(), revision })).toThrow(),
+ );
+ it('rejects duplicate accounts, members and device identities', () => {
+ for (const patch of [
+ { accountId: 'owner' }, { accountId: 'guest-a' }, { memberId: 'member-a' },
+ { deviceIds: ['phone-b', 'phone-b'] },
+ ]) {
+ const input = snapshot();
+ input.guests[1] = { ...input.guests[1], ...patch };
+ expect(() => parse(input)).toThrow();
+ }
+ });
+ it('scopes colliding device claims by authenticated account', () => {
+ const input = snapshot();
+ input.guests[1].deviceIds = ['phone-a', input.hostDeviceId];
+ const parsed = parse(input);
+ expect(authorize(parsed, { accountId: 'guest-b', deviceId: 'phone-a' }, 'session-1', 'history.read'))
+ .toMatchObject({ allowed: true, memberId: 'member-b' });
+ expect(authorize(parsed, { accountId: 'outsider', deviceId: 'phone-a' }, 'session-1', 'history.read').allowed).toBe(false);
+ });
+ it('counts members by account while permitting multiple devices for a member', () => {
+ expect(parse(snapshot()).guests).toHaveLength(2);
+ const input = snapshot();
+ input.guests.push(
+ { memberId: 'member-c', accountId: 'guest-c', version: 1, deviceIds: [] },
+ { memberId: 'member-d', accountId: 'guest-d', version: 1, deviceIds: [] },
+ );
+ expect(() => parse(input)).toThrow();
+ });
+});
diff --git a/packages/device-link/src/__tests__/sharedTaskApi.test.ts b/packages/device-link/src/__tests__/sharedTaskApi.test.ts
new file mode 100644
index 0000000000..44347944af
--- /dev/null
+++ b/packages/device-link/src/__tests__/sharedTaskApi.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, it, vi } from 'vitest';
+import { createSharedTaskApi, SharedTaskScopeChangedError } from '../sharedTaskApi.js';
+
+const snapshot = () => ({
+ sharedTaskId: 'sharedTask', sessionId: 'session', ownerAccountId: 'owner', hostDeviceId: 'desktop',
+ revision: 2, status: 'active', title: 'Task', guests: [{
+ memberId: 'member', accountId: 'guest', deviceIds: ['phone'], version: 1, displayName: 'Guest', joinedAt: 1,
+ }],
+});
+function setup() {
+ let generation = 1;
+ const request = vi.fn<(path: string, options: unknown) => Promise<unknown>>();
+ const api = createSharedTaskApi({ request, captureScope: () => {
+ const captured = generation;
+ return { isCurrent: () => captured === generation };
+ } });
+ return { api, request, changeAccountOrRegion: () => { generation++; } };
+}
+describe('sharedTask management client', () => {
+ it('observes a late create ID for host cleanup but never returns stale UI success', async () => {
+ const { api, request, changeAccountOrRegion } = setup();
+ const observed = vi.fn();
+ request.mockImplementation(async () => { changeAccountOrRegion(); return { sharedTaskId: 'sharedTask', revision: 1 }; });
+ await expect(api.create('session', 'Task', observed)).rejects.toBeInstanceOf(SharedTaskScopeChangedError);
+ expect(observed).toHaveBeenCalledExactlyOnceWith('sharedTask');
+ });
+ it('does not pass malformed create IDs to cleanup', async () => {
+ const { api, request } = setup();
+ const observed = vi.fn();
+ request.mockResolvedValue({ sharedTaskId: '../bad', revision: 1 });
+ await expect(api.create('session', 'Task', observed)).rejects.toThrow('identifier');
+ expect(observed).not.toHaveBeenCalled();
+ });
+ it('projects the server snapshot separately from display labels', async () => {
+ const { api, request } = setup();
+ const input = snapshot();
+ request.mockResolvedValue(input);
+ const detail = await api.get('sharedTask');
+ expect(detail.guests[0]).not.toHaveProperty('displayName');
+ expect(detail.memberLabels).toEqual([{ memberId: 'member', displayName: 'Guest', joinedAt: 1 }]);
+ input.guests[0].deviceIds.push('another');
+ expect(detail.guests[0].deviceIds).toEqual(['phone']);
+ expect(request).toHaveBeenCalledWith('/api/device-link/shared-tasks/sharedTask', expect.objectContaining({ method: 'GET' }));
+ });
+ it('keeps invitation credentials in POST bodies instead of URL paths', async () => {
+ const { api, request } = setup();
+ const invitation = 'x'.repeat(43);
+ request.mockResolvedValue({ sharedTaskId: 'sharedTask', memberId: 'member', status: 'joined', created: true });
+ await api.join(invitation, 'Guest');
+ expect(request).toHaveBeenCalledWith('/api/device-link/shared-tasks/join', expect.objectContaining({ method: 'POST', body: { invitation, displayName: 'Guest' } }));
+ expect(request.mock.calls[0][0]).not.toContain(invitation);
+ });
+ it('rejects late authority replies after account or region changes', async () => {
+ const { api, request, changeAccountOrRegion } = setup();
+ request.mockImplementation(async () => { changeAccountOrRegion(); return snapshot(); });
+ await expect(api.get('sharedTask')).rejects.toBeInstanceOf(SharedTaskScopeChangedError);
+ });
+ it('does not submit operations for an already invalid scope', async () => {
+ const request = vi.fn();
+ const api = createSharedTaskApi({ request, captureScope: () => ({ isCurrent: () => false }) });
+ await expect(api.close('sharedTask')).rejects.toBeInstanceOf(SharedTaskScopeChangedError);
+ expect(request).not.toHaveBeenCalled();
+ });
+ it('rejects responses for another sharedTask or member', async () => {
+ const { api, request } = setup();
+ request.mockResolvedValue({ ...snapshot(), sharedTaskId: 'other-sharedTask' });
+ await expect(api.get('sharedTask')).rejects.toThrow('scope mismatch');
+ request.mockResolvedValue({ memberId: 'other-member', status: 'removed' });
+ await expect(api.remove('sharedTask', 'member')).rejects.toThrow('scope mismatch');
+ });
+ it('validates decisions, identifier paths, and malformed snapshots', async () => {
+ const { api, request } = setup();
+ await expect(api.close('../devices')).rejects.toThrow();
+ expect(request).not.toHaveBeenCalled();
+ request.mockResolvedValue({ ...snapshot(), guests: [{ ...snapshot().guests[0], accountId: 'owner' }] });
+ await expect(api.get('sharedTask')).rejects.toThrow();
+ });
+ it('preserves server errors instead of silently accepting failed revocations', async () => {
+ const { api, request } = setup();
+ const error = new Error('Service unavailable');
+ request.mockRejectedValue(error);
+ await expect(api.remove('sharedTask', 'member')).rejects.toBe(error);
+ await expect(api.close('sharedTask')).rejects.toBe(error);
+ });
+ it('validates list bounds', async () => {
+ const { api, request } = setup();
+ request.mockResolvedValue({ sharedTasks: [snapshot(), snapshot()] });
+ await expect(api.list()).rejects.toThrow('Duplicate');
+ });
+});
diff --git a/packages/device-link/src/__tests__/sharedTaskProbe.test.ts b/packages/device-link/src/__tests__/sharedTaskProbe.test.ts
new file mode 100644
index 0000000000..c17bf34cab
--- /dev/null
+++ b/packages/device-link/src/__tests__/sharedTaskProbe.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it, vi } from 'vitest';
+import { sharedTaskHostPeer } from '../protocol.js';
+import { probeSharedTaskHost } from '../sharedTaskProbe.js';
+
+const peer = sharedTaskHostPeer('sharedTask');
+function fixture() {
+ return {
+ isCurrent: vi.fn(() => true),
+ get: vi.fn(async () => ({ sharedTaskId: 'sharedTask', sessionId: 'task', status: 'active' })),
+ openLink: vi.fn(async () => undefined),
+ invoke: vi.fn(async () => ({ ok: true })),
+ };
+}
+describe('shared task recovery probe', () => {
+ it('proves DB responsiveness using only the authorized task', async () => {
+ const deps = fixture();
+ await expect(probeSharedTaskHost(peer, deps)).resolves.toEqual({ ok: true });
+ expect(deps.get).toHaveBeenCalledWith('sharedTask');
+ expect(deps.openLink).toHaveBeenCalledOnce();
+ expect(deps.invoke).toHaveBeenCalledExactlyOnceWith('local-db:sessions:get', ['task']);
+ });
+ it('does not open a link without a current active membership response', async () => {
+ for (const detail of [
+ { sharedTaskId: 'other', sessionId: 'task', status: 'active' },
+ { sharedTaskId: 'sharedTask', sessionId: 'task', status: 'closed' },
+ ]) {
+ const deps = fixture();
+ deps.get.mockResolvedValue(detail);
+ await expect(probeSharedTaskHost(peer, deps)).rejects.toThrow();
+ expect(deps.openLink).not.toHaveBeenCalled();
+ }
+ });
+ it('does not reuse a stale account or link after either await', async () => {
+ for (const boundary of ['get', 'openLink'] as const) {
+ const deps = fixture();
+ if (boundary === 'get') deps.get.mockImplementation(async () => {
+ deps.isCurrent.mockReturnValue(false);
+ return { sharedTaskId: 'sharedTask', sessionId: 'task', status: 'active' };
+ });
+ else deps.openLink.mockImplementation(async () => { deps.isCurrent.mockReturnValue(false); });
+ await expect(probeSharedTaskHost(peer, deps)).rejects.toThrow();
+ expect(deps.invoke).not.toHaveBeenCalled();
+ }
+ });
+ it('keeps another peer probe independent when one fails', async () => {
+ const bad = fixture();
+ bad.openLink.mockRejectedValue(new Error('peer offline'));
+ const good = fixture();
+ const results = await Promise.allSettled([probeSharedTaskHost(peer, bad), probeSharedTaskHost(peer, good)]);
+ expect(results.map((r) => r.status)).toEqual(['rejected', 'fulfilled']);
+ expect(good.invoke).toHaveBeenCalledOnce();
+ });
+ it('rejects unknown peers before any request', async () => {
+ const deps = fixture();
+ await expect(probeSharedTaskHost('ordinary-device', deps)).rejects.toThrow();
+ expect(deps.get).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.ts
index 95de645e5e..5103279a92 100644
--- a/packages/device-link/src/allowlist.ts
+++ b/packages/device-link/src/allowlist.ts
@@ -410,6 +410,7 @@ const EXTENDED_INVOKE_CHANNELS: readonly string[] = [
// 本机查必空)。后台任务面板挂载水合用。老被控端无此 channel → CHANNEL_NOT_ALLOWED
// → 控制端降级空表(面板退化为事件流 + 消息扫描两源)。
'maker:session-background-tasks:list',
+ 'maker:session-background-activity',
// Durable PI Subagent truth and process handles live on the data-owning device.
// Reads and exact controls must execute there; the controller must never fall
// back to its own pi-agent-home for a remote task.
@@ -598,6 +599,8 @@ export const REMOTE_REVIEW_EXTERNAL_INPUT_CHANNELS: ReadonlySet<string> = new Se
/** 远程可调用的 invoke channel 全集(被控端 dispatch 前的权威校验依据) */
export const REMOTE_INVOKE_ALLOWLIST: ReadonlySet<string> = new Set([
+ // Same-account owner controls only; guest task dispatch has its own deny-by-default gate.
+ 'maker:shared-task',
'device-link:remote-desktop:v1',
...CORE_INVOKE_CHANNELS,
...EXTENDED_INVOKE_CHANNELS,
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index 1a6724c257..31ea949969 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -735,6 +735,7 @@ export class DeviceLinkClient {
private staleLinkNotifiedAt = new Map<string, number>();
private presenceHandlers = new Set<(snap: PresenceSnapshot) => void>();
private frameHandlers = new Set<InboundFrameHandler>();
+ private peerStreamAcceptedHandlers = new Set<(peer: string, streamId: string) => void>();
private issueHandlers = new Set<(issue: DeviceLinkConnectionIssue | null) => void>();
private peerRouteStateHandlers = new Set<
(change: DeviceLinkPeerRouteStateChanged) => void
@@ -989,6 +990,12 @@ export class DeviceLinkClient {
return this.status;
}
+ /** Verified outbound handshake, before recovered business frames are delivered. */
+ onPeerStreamAccepted(cb: (peer: string, streamId: string) => void): () => void {
+ this.peerStreamAcceptedHandlers.add(cb);
+ return () => this.peerStreamAcceptedHandlers.delete(cb);
+ }
+
/** 目标设备是否已完成 link-open / link-accept,可安全进入 streaming tier。 */
isLinkReady(dst: string): boolean {
const peer = this.peerTransport.get(dst);
@@ -2276,6 +2283,12 @@ export class DeviceLinkClient {
// link),两个方向共享同一份 PeerTransportState——覆盖会让入站方向
// 的重试耗尽误拆整条共享 relay(字段注释有完整语义)。
if (peer.reliable) {
+ if (env.src === p.dst && peer.remoteStreamId) {
+ for (const cb of this.peerStreamAcceptedHandlers) {
+ try { cb(env.src, peer.remoteStreamId); }
+ catch (error) { this.log.error('peer stream accepted handler threw', error); }
+ }
+ }
const resume = this.planReliableSendResume(peer);
this.commitReliableReceiveReady(env.src, peer);
this.commitReliableSendResume(env.src, peer, resume);
diff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.ts
index 58c2023beb..35bf406b6a 100644
--- a/packages/device-link/src/index.ts
+++ b/packages/device-link/src/index.ts
@@ -32,6 +32,9 @@ export * from "./fileAccess.js";
export * from "./filePeerRuntime.js";
export { FILE_PEER_RUNTIME_SOURCE } from "./filePeerRuntimeSource.js";
+export * from "./sharedTask.js";
+export * from "./sharedTaskApi.js";
+export * from "./sharedTaskProbe.js";
export * from "./modelFavorites.js";
export * from "./sessionListTransport.js";
diff --git a/packages/device-link/src/protocol.ts b/packages/device-link/src/protocol.ts
index 54f59d381a..36debcdba9 100644
--- a/packages/device-link/src/protocol.ts
+++ b/packages/device-link/src/protocol.ts
@@ -25,6 +25,9 @@ import {
type RelayErrorPayload,
} from '@cindy/device-link-protocol';
+export { SHARED_TASK_RELAY_CAPABILITY, SHARED_TASK_PEER_PREFIX, sharedTaskHostPeer, sharedTaskGuestPeer, isSharedTaskPeer, parseSharedTaskPeer } from '@cindy/device-link-protocol';
+export type { SharedTaskPeer } from '@cindy/device-link-protocol';
+
export {
MAX_FRAME_BYTES,
NOTIFY_BODY_MAX_LENGTH,
diff --git a/packages/device-link/src/sharedTask.ts b/packages/device-link/src/sharedTask.ts
new file mode 100644
index 0000000000..f4f029e62a
--- /dev/null
+++ b/packages/device-link/src/sharedTask.ts
@@ -0,0 +1,182 @@
+/**
+ * Task-scoped sharedTask authorization contract. This does not enable cross-account
+ * routing: the relay and host must authenticate the source before consuming it.
+ * Same-account device control continues to use its existing authorization path.
+ */
+import { isSharedTaskPeer } from './protocol.js';
+import { parseAttachmentOssRef } from './attachmentOssRef.js';
+
+/** Only objects issued for this shared task may be materialized on its host. */
+export function isSharedTaskAttachment(value: string, sharedTaskId: string): boolean {
+ const ref = parseAttachmentOssRef(value);
+ const parts = ref?.ossKey.split('/');
+ return !!parts && parts.length === 5 && parts[0] === 'cindy' && parts[1] === 'shared-task' &&
+ parts[2] === sharedTaskId && parts.slice(2).every((part) => /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(part));
+}
+
+export const SHARED_TASK_CAPABILITY = 'shared-task-v1';
+export const SHARED_TASK_MAX_ACTIVE_PER_OWNER = 2;
+export const SHARED_TASK_MAX_JOINED_PER_ACCOUNT = 2;
+export const SHARED_TASK_MAX_GUESTS = 2;
+/** Read existing development snapshots without revoking already joined guests.
+ * Admission limits are enforced by the server, not by rejecting stored history. */
+export const SHARED_TASK_MAX_SNAPSHOT_GUESTS = 3;
+/** Ordinary task screens also request the device-wide list; shared peers never do. */
+export function sharedTaskTopics<T extends string>(peer: string, topics: readonly T[]): T[] {
+ return topics.filter((topic) => !isSharedTaskPeer(peer) || topic !== 'sessions');
+}
+
+export interface SharedTaskIdentity {
+ readonly sharedTaskId: string;
+ readonly sessionId: string;
+ readonly ownerAccountId: string;
+ readonly hostDeviceId: string;
+}
+
+/** An approved account. Presence is a separate, non-authorizing projection. */
+export interface SharedTaskGrant {
+ readonly memberId: string;
+ readonly accountId: string;
+ /** Changes when this member's authorization changes, not on presence changes. */
+ readonly version: number;
+ readonly deviceIds: readonly string[];
+}
+
+/** A complete authority snapshot, never an arbitrary Renderer-supplied patch. */
+export interface SharedTaskSnapshot extends SharedTaskIdentity {
+ readonly revision: number;
+ readonly status: 'active' | 'closed';
+ /** Active guests only; owner identity is carried separately. */
+ readonly guests: readonly SharedTaskGrant[];
+}
+
+export type SharedTaskOperation =
+ | 'history.read' | 'events.subscribe' | 'attachment.read' | 'attachment.upload'
+ | 'file.read' | 'input.send' | 'input.edit' | 'input.withdraw' | 'agent.stop'
+ | 'agent.configure' | 'approval.resolve' | 'permission.configure'
+ | 'workdir.configure' | 'plugins.configure' | 'history.delete'
+ | 'session.archive' | 'session.export' | 'session.fork'
+ | 'background.create' | 'schedule.create' | 'sharedTask.manage';
+
+/** Derived from authenticated account/device claims, never from request args. */
+export interface SharedTaskCaller {
+ readonly accountId: string;
+ readonly deviceId: string;
+}
+
+/** Resolve this from the host queue, not from a caller-supplied message payload. */
+export interface SharedTaskQueueItem {
+ readonly sessionId: string;
+ readonly authorAccountId: string;
+ readonly state: 'pending' | 'accepted';
+}
+
+export type SharedTaskDenial =
+ | 'sharedTask-unavailable' | 'scope-mismatch' | 'not-a-member'
+ | 'owner-required' | 'queue-item-unavailable' | 'queue-item-not-owned'
+ | 'unknown-operation';
+
+export type SharedTaskDecision =
+ | { allowed: true; role: 'host' | 'guest'; memberId: string; memberVersion: number }
+ | { allowed: false; reason: SharedTaskDenial };
+
+const sharedOperations: ReadonlySet<string> = new Set<SharedTaskOperation>([
+ 'history.read', 'events.subscribe', 'attachment.read', 'attachment.upload',
+ 'file.read', 'input.send', 'agent.stop', 'agent.configure',
+]);
+const ownerOperations: ReadonlySet<string> = new Set<SharedTaskOperation>([
+ 'approval.resolve', 'permission.configure', 'workdir.configure', 'plugins.configure',
+ 'history.delete', 'session.archive', 'session.export', 'session.fork',
+ 'background.create', 'schedule.create', 'sharedTask.manage',
+]);
+
+/**
+ * Only task-level authorization. File ancestry, attachment ownership, tool risk,
+ * and queue transaction identity must ALSO be checked by the executing handler.
+ */
+export function authorizeSharedTaskOperation(
+ snapshot: SharedTaskSnapshot | null,
+ caller: SharedTaskCaller,
+ sessionId: string,
+ operation: string,
+ queueItem?: SharedTaskQueueItem,
+): SharedTaskDecision {
+ if (!snapshot || snapshot.status !== 'active') return { allowed: false, reason: 'sharedTask-unavailable' };
+ if (snapshot.sessionId !== sessionId) return { allowed: false, reason: 'scope-mismatch' };
+ const isOwner = caller.accountId === snapshot.ownerAccountId;
+ const guest = isOwner ? undefined : snapshot.guests.find((item) =>
+ item.accountId === caller.accountId && item.deviceIds.includes(caller.deviceId));
+ if (!isOwner && !guest) return { allowed: false, reason: 'not-a-member' };
+ const allowed: SharedTaskDecision = {
+ allowed: true,
+ role: isOwner ? 'host' : 'guest',
+ memberId: isOwner ? snapshot.ownerAccountId : guest!.memberId,
+ memberVersion: isOwner ? 0 : guest!.version,
+ };
+ if (sharedOperations.has(operation)) return allowed;
+ if (ownerOperations.has(operation)) return isOwner ? allowed : { allowed: false, reason: 'owner-required' };
+ if (operation === 'input.edit' || operation === 'input.withdraw') {
+ if (!queueItem || queueItem.sessionId !== sessionId || queueItem.state !== 'pending') {
+ return { allowed: false, reason: 'queue-item-unavailable' };
+ }
+ return isOwner || queueItem.authorAccountId === caller.accountId
+ ? allowed : { allowed: false, reason: 'queue-item-not-owned' };
+ }
+ return { allowed: false, reason: 'unknown-operation' };
+}
+
+function record(value: unknown): Record<string, unknown> {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid sharedTask snapshot');
+ return value as Record<string, unknown>;
+}
+
+function identifier(value: unknown): string {
+ if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(value)) {
+ throw new Error('Invalid sharedTask identifier');
+ }
+ return value;
+}
+
+function version(value: unknown): number {
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) {
+ throw new Error('Invalid sharedTask revision');
+ }
+ return value;
+}
+
+/** Validate/project a decoded response; parsing alone does NOT authenticate it. */
+export function parseSharedTaskSnapshot(value: unknown): SharedTaskSnapshot {
+ const row = record(value);
+ const ownerAccountId = identifier(row.ownerAccountId);
+ const hostDeviceId = identifier(row.hostDeviceId);
+ if (row.status !== 'active' && row.status !== 'closed') throw new Error('Invalid sharedTask status');
+ if (!Array.isArray(row.guests) || row.guests.length > SHARED_TASK_MAX_SNAPSHOT_GUESTS) {
+ throw new Error('Invalid sharedTask guests');
+ }
+ const accounts = new Set<string>([ownerAccountId]);
+ const members = new Set<string>();
+ const guests = row.guests.map((value): SharedTaskGrant => {
+ const guest = record(value);
+ const memberId = identifier(guest.memberId);
+ const accountId = identifier(guest.accountId);
+ if (accounts.has(accountId) || members.has(memberId)) throw new Error('Duplicate sharedTask member');
+ accounts.add(accountId);
+ members.add(memberId);
+ // Device claims are account-scoped. Two accounts can legitimately report
+ // the same deviceId; only the authenticated account+device pair is identity.
+ const devices = new Set<string>();
+ if (!Array.isArray(guest.deviceIds) || guest.deviceIds.length > 64) throw new Error('Invalid member devices');
+ const deviceIds = guest.deviceIds.map((value): string => {
+ const deviceId = identifier(value);
+ if (devices.has(deviceId)) throw new Error('Duplicate sharedTask device');
+ devices.add(deviceId);
+ return deviceId;
+ }).sort();
+ return Object.freeze({ memberId, accountId, version: version(guest.version), deviceIds: Object.freeze(deviceIds) });
+ }).sort((a, b) => a.memberId < b.memberId ? -1 : a.memberId > b.memberId ? 1 : 0);
+ return Object.freeze({
+ sharedTaskId: identifier(row.sharedTaskId), sessionId: identifier(row.sessionId),
+ ownerAccountId, hostDeviceId, revision: version(row.revision), status: row.status,
+ guests: Object.freeze(guests),
+ });
+}
diff --git a/packages/device-link/src/sharedTaskApi.ts b/packages/device-link/src/sharedTaskApi.ts
new file mode 100644
index 0000000000..63337504da
--- /dev/null
+++ b/packages/device-link/src/sharedTaskApi.ts
@@ -0,0 +1,141 @@
+import { parseSharedTaskSnapshot, SHARED_TASK_MAX_SNAPSHOT_GUESTS, type SharedTaskIdentity, type SharedTaskSnapshot } from './sharedTask.js';
+
+export const SHARED_TASK_HOST_CHANNEL = 'maker:shared-task';
+export const SHARED_TASK_ACCOUNT_CHANNEL = 'shared-task:account';
+export type SharedTaskHostCommand =
+ | { action: 'state' | 'open'; sessionId: string }
+ | { action: 'invite' | 'close'; sharedTaskId: string }
+ | { action: 'remove'; sharedTaskId: string; memberId: string };
+export type SharedTaskAccountCommand =
+ | { action: 'list' }
+ | { action: 'owned' }
+ | { action: 'close'; sharedTaskId?: string; all?: true }
+ | { action: 'get' | 'leave'; sharedTaskId: string }
+ | { action: 'join'; invitation: string; displayName: string };
+export interface SharedTaskHostState {
+ available: boolean;
+ detail: SharedTaskDetail | null;
+}
+
+export interface SharedTaskListItem extends SharedTaskIdentity { title: string; revision: number }
+/** Items this profile hosts carry the local flag so the window can label this device. */
+export type SharedTaskOwnedItem = SharedTaskListItem & { local: boolean };
+export interface SharedTaskCloseResult { closed: string[]; failed: { sharedTaskId: string }[] }
+export interface SharedTaskDetail extends SharedTaskSnapshot {
+ readonly title: string;
+ readonly memberLabels: readonly { memberId: string; displayName: string; joinedAt: number | null }[];
+}
+export interface SharedTaskApiOptions {
+ /** Use Desktop serverApiFetch / Mobile apiFetch; no independent auth or retry stack. */
+ request(path: string, options: { method: 'GET' | 'POST'; body?: unknown; isCurrent(): boolean }): Promise<unknown>;
+ /** Captures account AND region generation; false rejects late success after logout/switch. */
+ captureScope(): { isCurrent(): boolean };
+}
+
+function row(value: unknown): Record<string, unknown> {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid sharedTask response');
+ return value as Record<string, unknown>;
+}
+function id(value: unknown): string {
+ if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(value)) throw new Error('Invalid sharedTask identifier');
+ return value;
+}
+function label(value: unknown): string {
+ if (typeof value !== 'string' || !value.trim() || value.length > 128 || /[\u0000-\u001f\u007f]/.test(value)) throw new Error('Invalid sharedTask label');
+ return value;
+}
+function integer(value: unknown, min = 1): number {
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min) throw new Error('Invalid sharedTask number');
+ return value;
+}
+function array(value: unknown, max: number): unknown[] {
+ if (!Array.isArray(value) || value.length > max) throw new Error('Invalid sharedTask list');
+ return value;
+}
+function matching(value: unknown, expected: string): string {
+ if (id(value) !== expected) throw new Error('SharedTask response scope mismatch');
+ return expected;
+}
+
+export class SharedTaskScopeChangedError extends Error {
+ constructor() { super('SharedTask account or region changed'); this.name = 'SharedTaskScopeChangedError'; }
+}
+
+/** Management API only; never authorizes full-device IPC or enables a legacy relay. */
+export function createSharedTaskApi(options: SharedTaskApiOptions) {
+ async function request(path: string, method: 'GET' | 'POST' = 'GET', body?: unknown, observe?: (value: Record<string, unknown>) => void): Promise<Record<string, unknown>> {
+ const scope = options.captureScope();
+ if (!scope.isCurrent()) throw new SharedTaskScopeChangedError();
+ const value = await options.request(`/api/device-link/shared-tasks${path}`, {
+ method, ...(body === undefined ? {} : { body }), isCurrent: () => scope.isCurrent(),
+ });
+ const parsed = row(value);
+ // Creation cleanup must learn the committed ID even after an auth boundary.
+ // This observer is host-owned bookkeeping, never a success delivery to UI.
+ observe?.(parsed);
+ if (!scope.isCurrent()) throw new SharedTaskScopeChangedError();
+ return parsed;
+ }
+ const route = (sharedTaskId: string) => `/${encodeURIComponent(id(sharedTaskId))}`;
+ return {
+ async create(sessionId: string, title: string, observeCommitted?: (sharedTaskId: string) => void) {
+ const value = await request('', 'POST', { sessionId: id(sessionId), title: label(title) }, (value) => {
+ observeCommitted?.(id(value.sharedTaskId));
+ });
+ return { sharedTaskId: id(value.sharedTaskId), revision: integer(value.revision) };
+ },
+ async list(): Promise<SharedTaskListItem[]> {
+ const value = await request('');
+ const seen = new Set<string>();
+ return array(value.sharedTasks, 10_000).map((item) => {
+ const value = row(item);
+ const sharedTaskId = id(value.sharedTaskId);
+ if (seen.has(sharedTaskId)) throw new Error('Duplicate sharedTask');
+ seen.add(sharedTaskId);
+ return { sharedTaskId, sessionId: id(value.sessionId), ownerAccountId: id(value.ownerAccountId),
+ hostDeviceId: id(value.hostDeviceId), title: label(value.title), revision: integer(value.revision) };
+ });
+ },
+ async get(sharedTaskId: string): Promise<SharedTaskDetail> {
+ const value = await request(route(sharedTaskId));
+ matching(value.sharedTaskId, sharedTaskId);
+ const snapshot = parseSharedTaskSnapshot(value);
+ const memberLabels = array(value.guests, SHARED_TASK_MAX_SNAPSHOT_GUESTS).map((item) => {
+ const member = row(item);
+ return Object.freeze({ memberId: id(member.memberId), displayName: label(member.displayName),
+ joinedAt: member.joinedAt === null ? null : integer(member.joinedAt, 0) });
+ });
+ return Object.freeze({ ...snapshot, title: label(value.title), memberLabels: Object.freeze(memberLabels) });
+ },
+ async invite(sharedTaskId: string) {
+ const value = await request(`${route(sharedTaskId)}/invites`, 'POST', {});
+ matching(value.sharedTaskId, sharedTaskId);
+ if (typeof value.invitation !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(value.invitation)) throw new Error('Invalid sharedTask invitation');
+ return { sharedTaskId, invitation: value.invitation };
+ },
+ async join(invitation: string, displayName: string) {
+ if (!/^[A-Za-z0-9_-]{43}$/.test(invitation)) throw new Error('Invalid sharedTask invitation');
+ const value = await request('/join', 'POST', { invitation, displayName: label(displayName) });
+ if (value.status !== 'joined' || typeof value.created !== 'boolean') throw new Error('Invalid sharedTask admission');
+ return { sharedTaskId: id(value.sharedTaskId), memberId: id(value.memberId), status: value.status,
+ created: value.created };
+ },
+ async remove(sharedTaskId: string, memberId: string) {
+ const value = await request(`${route(sharedTaskId)}/members/${encodeURIComponent(id(memberId))}/remove`, 'POST', {});
+ if (value.status !== 'removed') throw new Error('Invalid sharedTask removal response');
+ return { memberId: matching(value.memberId, memberId), status: 'removed' as const };
+ },
+ async leave(sharedTaskId: string) {
+ const value = await request(`${route(sharedTaskId)}/leave`, 'POST', {});
+ if (value.status !== 'left') throw new Error('Invalid sharedTask departure response');
+ return { memberId: id(value.memberId), status: 'left' as const };
+ },
+ async close(sharedTaskId: string) {
+ const value = await request(`${route(sharedTaskId)}/close`, 'POST', {});
+ if (value.status !== 'closed') throw new Error('Invalid sharedTask closure response');
+ return { sharedTaskId: matching(value.sharedTaskId, sharedTaskId), status: 'closed' as const };
+ },
+ };
+}
+
+export type SharedTaskApi = ReturnType<typeof createSharedTaskApi>;
diff --git a/packages/device-link/src/sharedTaskProbe.ts b/packages/device-link/src/sharedTaskProbe.ts
new file mode 100644
index 0000000000..875062e14a
--- /dev/null
+++ b/packages/device-link/src/sharedTaskProbe.ts
@@ -0,0 +1,26 @@
+import { DeviceLinkError, parseSharedTaskPeer } from './protocol.js';
+
+/** A shared peer must prove DB health through its own task, never the owner's task list. */
+export async function probeSharedTaskHost<T>(peer: string, deps: {
+ isCurrent(): boolean;
+ get(sharedTaskId: string): Promise<{ sharedTaskId: string; sessionId: string; status: string }>;
+ openLink(): Promise<unknown>;
+ invoke(channel: string, args: unknown[]): Promise<T>;
+}): Promise<T> {
+ const parsed = parseSharedTaskPeer(peer);
+ const assertCurrent = () => {
+ if (!deps.isCurrent()) throw new DeviceLinkError('ACCESS_REVOKED', 'Shared task probe scope changed');
+ };
+ assertCurrent();
+ if (parsed?.role !== 'host') throw new DeviceLinkError('ACCESS_REVOKED', 'Invalid shared task host');
+ const detail = await deps.get(parsed.sharedTaskId);
+ assertCurrent();
+ if (detail.sharedTaskId !== parsed.sharedTaskId || detail.status !== 'active' || !detail.sessionId) {
+ throw new DeviceLinkError('ACCESS_REVOKED', 'Shared task unavailable');
+ }
+ await deps.openLink();
+ assertCurrent();
+ const result = await deps.invoke('local-db:sessions:get', [detail.sessionId]);
+ assertCurrent();
+ return result;
+}
diff --git a/packages/maker-shared/src/index.ts b/packages/maker-shared/src/index.ts
index ec8b5eae14..815d067633 100644
--- a/packages/maker-shared/src/index.ts
+++ b/packages/maker-shared/src/index.ts
@@ -44,6 +44,7 @@ export * from './sessionList.js';
export * from './sessionListCollapse.js';
export * from './sessionOperation.js';
export * from './sessionSelection.js';
+export * from './sharedTask.js';
export * from './syntheticTrigger.js';
export * from './subagentObservation.js';
export * from './subagentWorkspace.js';
diff --git a/packages/maker-shared/src/sharedTask.ts b/packages/maker-shared/src/sharedTask.ts
new file mode 100644
index 0000000000..14a6301fca
--- /dev/null
+++ b/packages/maker-shared/src/sharedTask.ts
@@ -0,0 +1,20 @@
+/** Product-neutral Session sharedTask primitives shared by Desktop and Mobile. */
+export type SharedTaskRole = 'host' | 'guest';
+export type SharedTaskStatus = 'active' | 'closed';
+
+/** Authenticated by the task host, persisted for attribution, never an authorization token. */
+export interface SharedTaskAuthor {
+ sharedTaskId: string;
+ sessionId: string;
+ memberId: string;
+ accountId: string;
+ displayName: string;
+}
+
+/** Tolerant projection for old history; this is attribution, never authority. */
+export function sharedTaskAuthorName(meta: unknown): string | undefined {
+ if (!meta || typeof meta !== 'object' || !('sharedTaskAuthor' in meta)) return undefined;
+ const author = meta.sharedTaskAuthor;
+ if (!author || typeof author !== 'object' || !('displayName' in author)) return undefined;
+ return typeof author.displayName === 'string' ? author.displayName.slice(0, 128) : undefined;
+}
diff --git a/scripts/shared/design-inventory.mjs b/scripts/shared/design-inventory.mjs
index 39851e20bc..8729404971 100644
--- a/scripts/shared/design-inventory.mjs
+++ b/scripts/shared/design-inventory.mjs
@@ -1399,6 +1399,7 @@ export function mobileCatalogSurfaces() {
['resources', '远程资源列表与详情', ['resources/[collectionId].tsx', 'resources/[collectionId]/[resourceId].tsx']],
['companions.direct', '伙伴私聊回看', ['companions/direct/[threadId].tsx']],
['chat.session', '任务内容与输入', ['sessions/[sessionId].tsx']],
+ ['chat.sharing', '共享任务邀请与成员', ['shared-session.tsx']],
['chat.new', '新建任务', ['sessions/new.tsx']],
['files', '任务文件与预览', ['files/[sessionId].tsx', 'files/preview/[sessionId].tsx']],
['automations', '自动化', ['automations/[deviceId].tsx']],