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(wecom): add enterprise IM and group notifications

DavidShen244ef23a8b77
diff --git a/apps/desktop/drizzle/0084_small_gwen_stacy.sql b/apps/desktop/drizzle/0084_small_gwen_stacy.sql
new file mode 100644
index 0000000000..02b80b212a
--- /dev/null
+++ b/apps/desktop/drizzle/0084_small_gwen_stacy.sql
@@ -0,0 +1 @@
+ALTER TABLE `schedules` ADD `notify_wecom_group` integer DEFAULT false NOT NULL;
\ No newline at end of file
diff --git a/apps/desktop/drizzle/meta/0084_snapshot.json b/apps/desktop/drizzle/meta/0084_snapshot.json
new file mode 100644
index 0000000000..a277ca4a2a
--- /dev/null
+++ b/apps/desktop/drizzle/meta/0084_snapshot.json
@@ -0,0 +1,3833 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "8344fb86-a506-45c9-bb6c-552a2482afa5",
+ "prevId": "0976a82c-a80e-41e0-94aa-4ac5b3fc90a5",
+ "tables": {
+ "account_usage_snapshots": {
+ "name": "account_usage_snapshots",
+ "columns": {
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "snapshot": {
+ "name": "snapshot",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "agent_input_queue_snapshots": {
+ "name": "agent_input_queue_snapshots",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "agent_input_queue_snapshots_session_id_sessions_id_fk": {
+ "name": "agent_input_queue_snapshots_session_id_sessions_id_fk",
+ "tableFrom": "agent_input_queue_snapshots",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "custom_mcp_servers": {
+ "name": "custom_mcp_servers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "transport": {
+ "name": "transport",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "headers": {
+ "name": "headers",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_custom_mcp_servers_sort_order": {
+ "name": "idx_custom_mcp_servers_sort_order",
+ "columns": [
+ "sort_order"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "custom_providers": {
+ "name": "custom_providers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "runtimes": {
+ "name": "runtimes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "auth": {
+ "name": "auth",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_custom_providers_sort_order": {
+ "name": "idx_custom_providers_sort_order",
+ "columns": [
+ "sort_order"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "daily_model_usage": {
+ "name": "daily_model_usage",
+ "columns": {
+ "day": {
+ "name": "day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_amount": {
+ "name": "cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_currency": {
+ "name": "cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "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_pk": {
+ "columns": [
+ "day",
+ "agent_kind",
+ "model"
+ ],
+ "name": "daily_model_usage_day_agent_kind_model_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "daily_spend": {
+ "name": "daily_spend",
+ "columns": {
+ "day": {
+ "name": "day",
+ "type": "text",
+ "primaryKey": true,
+ "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": false,
+ "autoincrement": false
+ },
+ "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": {},
+ "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_messages": {
+ "name": "hook_group_messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "thread_id": {
+ "name": "thread_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_name": {
+ "name": "chat_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "author": {
+ "name": "author",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_bot": {
+ "name": "is_bot",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "file_names": {
+ "name": "file_names",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "hook_group_messages_msg_idx": {
+ "name": "hook_group_messages_msg_idx",
+ "columns": [
+ "provider",
+ "chat_id",
+ "thread_id",
+ "message_id"
+ ],
+ "isUnique": true
+ },
+ "hook_group_messages_window_idx": {
+ "name": "hook_group_messages_window_idx",
+ "columns": [
+ "provider",
+ "chat_id",
+ "thread_id",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "im_bindings": {
+ "name": "im_bindings",
+ "columns": {
+ "channel": {
+ "name": "channel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_context_id": {
+ "name": "bot_context_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scope_key": {
+ "name": "scope_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "target_session_id": {
+ "name": "target_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attached_at": {
+ "name": "attached_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attached_via_card_message_id": {
+ "name": "attached_via_card_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_im_bindings_target": {
+ "name": "idx_im_bindings_target",
+ "columns": [
+ "target_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "im_bindings_target_session_id_sessions_id_fk": {
+ "name": "im_bindings_target_session_id_sessions_id_fk",
+ "tableFrom": "im_bindings",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "target_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "im_bindings_channel_bot_context_id_user_id_scope_key_pk": {
+ "columns": [
+ "channel",
+ "bot_context_id",
+ "user_id",
+ "scope_key"
+ ],
+ "name": "im_bindings_channel_bot_context_id_user_id_scope_key_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "media_blobs": {
+ "name": "media_blobs",
+ "columns": {
+ "hash": {
+ "name": "hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ext": {
+ "name": "ext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mime_type": {
+ "name": "mime_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bytes": {
+ "name": "bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_cache": {
+ "name": "is_cache",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_access_at": {
+ "name": "last_access_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "media_refs": {
+ "name": "media_refs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "hash": {
+ "name": "hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ref_kind": {
+ "name": "ref_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ref_id": {
+ "name": "ref_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "origin_session_id": {
+ "name": "origin_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "origin_kind": {
+ "name": "origin_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "origin_id": {
+ "name": "origin_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "media_refs_hash_idx": {
+ "name": "media_refs_hash_idx",
+ "columns": [
+ "hash"
+ ],
+ "isUnique": false
+ },
+ "media_refs_ref_idx": {
+ "name": "media_refs_ref_idx",
+ "columns": [
+ "ref_kind",
+ "ref_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "media_refs_hash_media_blobs_hash_fk": {
+ "name": "media_refs_hash_media_blobs_hash_fk",
+ "tableFrom": "media_refs",
+ "tableTo": "media_blobs",
+ "columnsFrom": [
+ "hash"
+ ],
+ "columnsTo": [
+ "hash"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "messages": {
+ "name": "messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_use_id": {
+ "name": "tool_use_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_meta": {
+ "name": "agent_meta",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "rewind_at": {
+ "name": "rewind_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_messages_session_client": {
+ "name": "uniq_messages_session_client",
+ "columns": [
+ "session_id",
+ "client_id"
+ ],
+ "isUnique": true
+ },
+ "idx_messages_session_created": {
+ "name": "idx_messages_session_created",
+ "columns": [
+ "session_id",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "idx_messages_created_at": {
+ "name": "idx_messages_created_at",
+ "columns": [
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_messages_rewind_at": {
+ "name": "idx_messages_rewind_at",
+ "columns": [
+ "rewind_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "messages_session_id_sessions_id_fk": {
+ "name": "messages_session_id_sessions_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "migration_history": {
+ "name": "migration_history",
+ "columns": {
+ "seq": {
+ "name": "seq",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "file_name": {
+ "name": "file_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content_hash": {
+ "name": "content_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "applied_at": {
+ "name": "applied_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "migration_meta": {
+ "name": "migration_meta",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_teams": {
+ "name": "orca_teams",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "lead_session_id": {
+ "name": "lead_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_active_team_per_lead": {
+ "name": "uniq_active_team_per_lead",
+ "columns": [
+ "lead_session_id"
+ ],
+ "isUnique": true,
+ "where": "\"orca_teams\".\"status\" = 'active'"
+ },
+ "idx_orca_teams_status": {
+ "name": "idx_orca_teams_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_teams_lead_session_id_sessions_id_fk": {
+ "name": "orca_teams_lead_session_id_sessions_id_fk",
+ "tableFrom": "orca_teams",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "lead_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_worker_creation_reservations": {
+ "name": "orca_worker_creation_reservations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_orca_worker_creation_reservations_team_label": {
+ "name": "uniq_orca_worker_creation_reservations_team_label",
+ "columns": [
+ "team_id",
+ "lower(\"label\")"
+ ],
+ "isUnique": true
+ },
+ "idx_orca_worker_creation_reservations_expires_at": {
+ "name": "idx_orca_worker_creation_reservations_expires_at",
+ "columns": [
+ "expires_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_worker_creation_reservations_team_id_orca_teams_id_fk": {
+ "name": "orca_worker_creation_reservations_team_id_orca_teams_id_fk",
+ "tableFrom": "orca_worker_creation_reservations",
+ "tableTo": "orca_teams",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_workers": {
+ "name": "orca_workers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'idle'"
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "worktree_branch": {
+ "name": "worktree_branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'developer'"
+ },
+ "focused": {
+ "name": "focused",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "idle_since": {
+ "name": "idle_since",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_orca_workers_session_id": {
+ "name": "uniq_orca_workers_session_id",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true
+ },
+ "uniq_orca_workers_team_label": {
+ "name": "uniq_orca_workers_team_label",
+ "columns": [
+ "team_id",
+ "lower(\"label\")"
+ ],
+ "isUnique": true
+ },
+ "uniq_orca_workers_focused_per_team": {
+ "name": "uniq_orca_workers_focused_per_team",
+ "columns": [
+ "team_id"
+ ],
+ "isUnique": true,
+ "where": "\"orca_workers\".\"focused\" = true"
+ },
+ "idx_orca_workers_team_id": {
+ "name": "idx_orca_workers_team_id",
+ "columns": [
+ "team_id"
+ ],
+ "isUnique": false
+ },
+ "idx_orca_workers_status": {
+ "name": "idx_orca_workers_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_workers_team_id_orca_teams_id_fk": {
+ "name": "orca_workers_team_id_orca_teams_id_fk",
+ "tableFrom": "orca_workers",
+ "tableTo": "orca_teams",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "orca_workers_session_id_sessions_id_fk": {
+ "name": "orca_workers_session_id_sessions_id_fk",
+ "tableFrom": "orca_workers",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_aliases": {
+ "name": "project_aliases",
+ "columns": {
+ "project_key": {
+ "name": "project_key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "alias": {
+ "name": "alias",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_project_aliases_updated_at": {
+ "name": "idx_project_aliases_updated_at",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_automation_consents": {
+ "name": "project_automation_consents",
+ "columns": {
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "consented_at": {
+ "name": "consented_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "config_hash": {
+ "name": "config_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "recent_workdirs": {
+ "name": "recent_workdirs",
+ "columns": {
+ "path": {
+ "name": "path",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_recent_workdirs_last_used_at": {
+ "name": "idx_recent_workdirs_last_used_at",
+ "columns": [
+ "last_used_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "right_sidebar_tabs": {
+ "name": "right_sidebar_tabs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "right_sidebar_tabs_session_idx": {
+ "name": "right_sidebar_tabs_session_idx",
+ "columns": [
+ "session_id",
+ "position"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "right_sidebar_tabs_session_id_sessions_id_fk": {
+ "name": "right_sidebar_tabs_session_id_sessions_id_fk",
+ "tableFrom": "right_sidebar_tabs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "schedule_runs": {
+ "name": "schedule_runs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "schedule_id": {
+ "name": "schedule_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fired_at": {
+ "name": "fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "error_msg": {
+ "name": "error_msg",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "estimated_value_usd": {
+ "name": "estimated_value_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_amount": {
+ "name": "cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "estimated_value_amount": {
+ "name": "estimated_value_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_currency": {
+ "name": "cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_is_approximate": {
+ "name": "cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "cost_attribution": {
+ "name": "cost_attribution",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'legacy'"
+ },
+ "result_text": {
+ "name": "result_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pre_run_hook_result": {
+ "name": "pre_run_hook_result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "read_at": {
+ "name": "read_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "heartbeat_at": {
+ "name": "heartbeat_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedule_runs_schedule": {
+ "name": "idx_schedule_runs_schedule",
+ "columns": [
+ "schedule_id",
+ "fired_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "schedule_runs_schedule_id_schedules_id_fk": {
+ "name": "schedule_runs_schedule_id_schedules_id_fk",
+ "tableFrom": "schedule_runs",
+ "tableTo": "schedules",
+ "columnsFrom": [
+ "schedule_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "schedule_runs_session_id_sessions_id_fk": {
+ "name": "schedule_runs_session_id_sessions_id_fk",
+ "tableFrom": "schedule_runs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "schedules": {
+ "name": "schedules",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "job_type": {
+ "name": "job_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'prompt'"
+ },
+ "job_config": {
+ "name": "job_config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "execution_mode": {
+ "name": "execution_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'agent'"
+ },
+ "script_config": {
+ "name": "script_config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'user'"
+ },
+ "project_config_id": {
+ "name": "project_config_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "legacy_session_fallback": {
+ "name": "legacy_session_fallback",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'cron'"
+ },
+ "cron_expr": {
+ "name": "cron_expr",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "recurring": {
+ "name": "recurring",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "manual": {
+ "name": "manual",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "interval_ms": {
+ "name": "interval_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "effort": {
+ "name": "effort",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fast_mode": {
+ "name": "fast_mode",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_kind": {
+ "name": "workspace_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'project'"
+ },
+ "use_worktree": {
+ "name": "use_worktree",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "target_session_id": {
+ "name": "target_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "persistent_session": {
+ "name": "persistent_session",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "silent_when_idle": {
+ "name": "silent_when_idle",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "pre_run_hook_command": {
+ "name": "pre_run_hook_command",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pre_run_hook_timeout_ms": {
+ "name": "pre_run_hook_timeout_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "skip_log_session_id": {
+ "name": "skip_log_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "notify_desktop": {
+ "name": "notify_desktop",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "notify_feishu": {
+ "name": "notify_feishu",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "notify_wecom_group": {
+ "name": "notify_wecom_group",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_fired_at": {
+ "name": "last_fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_finished_at": {
+ "name": "last_finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "next_fire_at": {
+ "name": "next_fire_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expire_at": {
+ "name": "expire_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedules_active_next": {
+ "name": "idx_schedules_active_next",
+ "columns": [
+ "status",
+ "next_fire_at"
+ ],
+ "isUnique": false
+ },
+ "idx_schedules_target_session": {
+ "name": "idx_schedules_target_session",
+ "columns": [
+ "target_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "schedules_target_session_id_sessions_id_fk": {
+ "name": "schedules_target_session_id_sessions_id_fk",
+ "tableFrom": "schedules",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "target_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "schedules_skip_log_session_id_sessions_id_fk": {
+ "name": "schedules_skip_log_session_id_sessions_id_fk",
+ "tableFrom": "schedules",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "skip_log_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_goals": {
+ "name": "session_goals",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "objective": {
+ "name": "objective",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "budget_tokens": {
+ "name": "budget_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "max_turns": {
+ "name": "max_turns",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "no_progress_limit": {
+ "name": "no_progress_limit",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "turns_used": {
+ "name": "turns_used",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "tokens_used": {
+ "name": "tokens_used",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "no_progress_streak": {
+ "name": "no_progress_streak",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "usage_reset_at": {
+ "name": "usage_reset_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_reason": {
+ "name": "last_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_session_goals_status": {
+ "name": "idx_session_goals_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_goals_session_id_sessions_id_fk": {
+ "name": "session_goals_session_id_sessions_id_fk",
+ "tableFrom": "session_goals",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_pr_refs": {
+ "name": "session_pr_refs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner": {
+ "name": "owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "repo": {
+ "name": "repo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "first_seen_at": {
+ "name": "first_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_session_pr_refs": {
+ "name": "uniq_session_pr_refs",
+ "columns": [
+ "session_id",
+ "owner",
+ "repo",
+ "pr_number"
+ ],
+ "isUnique": true
+ },
+ "idx_session_pr_refs_session_last_seen": {
+ "name": "idx_session_pr_refs_session_last_seen",
+ "columns": [
+ "session_id",
+ "last_seen_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_pr_refs_session_id_sessions_id_fk": {
+ "name": "session_pr_refs_session_id_sessions_id_fk",
+ "tableFrom": "session_pr_refs",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'New Maker'"
+ },
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_kind": {
+ "name": "workspace_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'project'"
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'claude-sonnet-4-6'"
+ },
+ "effort": {
+ "name": "effort",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'high'"
+ },
+ "permission_mode": {
+ "name": "permission_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'ask'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "total_token_usage": {
+ "name": "total_token_usage",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_usd": {
+ "name": "total_cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_amount": {
+ "name": "total_cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_currency": {
+ "name": "total_cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "total_cost_is_approximate": {
+ "name": "total_cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "context_tokens": {
+ "name": "context_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "context_window": {
+ "name": "context_window",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "fast_mode": {
+ "name": "fast_mode",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "plan_mode_enabled": {
+ "name": "plan_mode_enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "cleared_at": {
+ "name": "cleared_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pinned_at": {
+ "name": "pinned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_send_at": {
+ "name": "user_send_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'cc'"
+ },
+ "orca_role": {
+ "name": "orca_role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "parent_session_id": {
+ "name": "parent_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "forked_at_message_id": {
+ "name": "forked_at_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "worktree_path": {
+ "name": "worktree_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'desktop'"
+ },
+ "feishu_open_id": {
+ "name": "feishu_open_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "feishu_bot_app_id": {
+ "name": "feishu_bot_app_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "im_bot_context_id": {
+ "name": "im_bot_context_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "im_user_id": {
+ "name": "im_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "used_project_context": {
+ "name": "used_project_context",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "codex_history_has_product_prompt": {
+ "name": "codex_history_has_product_prompt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "extra_dirs": {
+ "name": "extra_dirs",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "remote_host_id": {
+ "name": "remote_host_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "active_turn_started_at": {
+ "name": "active_turn_started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "active_turn_pid": {
+ "name": "active_turn_pid",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_turn_ended_at": {
+ "name": "last_turn_ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_sessions_updated_at": {
+ "name": "idx_sessions_updated_at",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_user_send_at": {
+ "name": "idx_sessions_user_send_at",
+ "columns": [
+ "user_send_at"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_sdk_session_id": {
+ "name": "idx_sessions_sdk_session_id",
+ "columns": [
+ "sdk_session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_workdir_created": {
+ "name": "idx_sessions_workdir_created",
+ "columns": [
+ "working_dir",
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_created_at": {
+ "name": "idx_sessions_created_at",
+ "columns": [
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_workspace_kind": {
+ "name": "idx_sessions_workspace_kind",
+ "columns": [
+ "workspace_kind"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_parent_session_id": {
+ "name": "idx_sessions_parent_session_id",
+ "columns": [
+ "parent_session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_orca_role": {
+ "name": "idx_sessions_orca_role",
+ "columns": [
+ "orca_role"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_worktree_path": {
+ "name": "idx_sessions_worktree_path",
+ "columns": [
+ "worktree_path"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_feishu_lookup": {
+ "name": "idx_sessions_feishu_lookup",
+ "columns": [
+ "source",
+ "feishu_bot_app_id",
+ "feishu_open_id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_im_lookup": {
+ "name": "idx_sessions_im_lookup",
+ "columns": [
+ "source",
+ "im_bot_context_id",
+ "im_user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "sessions_parent_session_id_sessions_id_fk": {
+ "name": "sessions_parent_session_id_sessions_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "parent_session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "skill_usage_exposures": {
+ "name": "skill_usage_exposures",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "analyzer_version": {
+ "name": "analyzer_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'6'"
+ },
+ "raw_file_path": {
+ "name": "raw_file_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "raw_line_no": {
+ "name": "raw_line_no",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "skill_name": {
+ "name": "skill_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "skill_path": {
+ "name": "skill_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "skill_document_hash": {
+ "name": "skill_document_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "exposure_content_hash": {
+ "name": "exposure_content_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "document_hash_source": {
+ "name": "document_hash_source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_use_id": {
+ "name": "tool_use_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "seen_at": {
+ "name": "seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_call_count": {
+ "name": "tool_call_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "repeated_tool_call_count": {
+ "name": "repeated_tool_call_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "tool_error_count": {
+ "name": "tool_error_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "command_call_count": {
+ "name": "command_call_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "command_failure_count": {
+ "name": "command_failure_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ }
+ },
+ "indexes": {
+ "idx_skill_usage_exposures_skill_document_version": {
+ "name": "idx_skill_usage_exposures_skill_document_version",
+ "columns": [
+ "analyzer_version",
+ "skill_name",
+ "skill_document_hash"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_session": {
+ "name": "idx_skill_usage_exposures_session",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_raw_file": {
+ "name": "idx_skill_usage_exposures_raw_file",
+ "columns": [
+ "raw_file_path"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "skill_usage_exposures_raw_file_path_skill_usage_sources_raw_file_path_fk": {
+ "name": "skill_usage_exposures_raw_file_path_skill_usage_sources_raw_file_path_fk",
+ "tableFrom": "skill_usage_exposures",
+ "tableTo": "skill_usage_sources",
+ "columnsFrom": [
+ "raw_file_path"
+ ],
+ "columnsTo": [
+ "raw_file_path"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "skill_usage_sources": {
+ "name": "skill_usage_sources",
+ "columns": {
+ "raw_file_path": {
+ "name": "raw_file_path",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "analyzer_version": {
+ "name": "analyzer_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'6'"
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mtime_ms": {
+ "name": "mtime_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "size_bytes": {
+ "name": "size_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "last_scanned_at": {
+ "name": "last_scanned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'ok'"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_skill_usage_sources_session": {
+ "name": "idx_skill_usage_sources_session",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_sources_sdk_session": {
+ "name": "idx_skill_usage_sources_sdk_session",
+ "columns": [
+ "sdk_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "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 3836f7419e..533cc26e30 100644
--- a/apps/desktop/drizzle/meta/_journal.json
+++ b/apps/desktop/drizzle/meta/_journal.json
@@ -589,6 +589,13 @@
"when": 1785287922480,
"tag": "0083_gray_katie_power",
"breakpoints": true
+ },
+ {
+ "idx": 84,
+ "version": "6",
+ "when": 1785428363998,
+ "tag": "0084_small_gwen_stacy",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/apps/desktop/src/main/__tests__/notificationService.test.ts b/apps/desktop/src/main/__tests__/notificationService.test.ts
index 88d9f27e91..c2d6db7431 100644
--- a/apps/desktop/src/main/__tests__/notificationService.test.ts
+++ b/apps/desktop/src/main/__tests__/notificationService.test.ts
@@ -158,6 +158,11 @@ const baseDeps = (feishuIm: FakeFeishuIM) => ({
>[0]['feishuIm'],
});
+const withWecomGroup = (feishuIm: FakeFeishuIM, publishMarkdown: ReturnType<typeof vi.fn>) => ({
+ ...baseDeps(feishuIm),
+ wecomGroupPublisher: { publishMarkdown },
+});
+
describe('notificationService — channels 分发', () => {
beforeEach(() => {
// 每个用例重新注册 handler,避免相互污染。
@@ -192,6 +197,24 @@ describe('notificationService — channels 分发', () => {
expect(sendMobileSessionNotify).not.toHaveBeenCalled();
});
+ it('企微群通知失败不影响其它通知通道', async () => {
+ const { initNotificationService } = await freshService();
+ const publishMarkdown = vi.fn(async () => Promise.reject(new Error('webhook failed')));
+ initNotificationService(withWecomGroup(makeFeishuIm('ou_owner'), publishMarkdown));
+
+ await expect(
+ invokeHandler({
+ sessionId: 's-wecom',
+ title: 'Group',
+ kind: 'done',
+ channels: { desktop: false, wecomGroup: true },
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(publishMarkdown).toHaveBeenCalledWith(expect.stringContaining('Group'));
+ expect(markSessionNeedsAttention).toHaveBeenCalledWith('s-wecom');
+ });
+
it('payload 运行时校验:非法 kind / 超长 title / 空 sessionId 直接 reject,不进任何通道', async () => {
const { initNotificationService } = await freshService();
const feishuIm = makeFeishuIm('ou_owner');
diff --git a/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts b/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts
new file mode 100644
index 0000000000..a2d67a2250
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/wecomGroupNotification.test.ts
@@ -0,0 +1,161 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('electron', () => ({
+ ipcMain: { handle: vi.fn() },
+ net: { fetch: vi.fn() },
+ safeStorage: {},
+ app: {},
+}));
+vi.mock('../logger', () => ({
+ createLogger: () => ({ warn: vi.fn(), info: vi.fn(), error: vi.fn() }),
+}));
+vi.mock('../im/ownerScopedStorage', () => ({
+ ownerScopedImSecrets: {
+ read: vi.fn(() => null),
+ write: vi.fn(() => true),
+ remove: vi.fn(),
+ },
+}));
+vi.mock('../security/trustedAppRenderer', () => ({
+ assertTrustedAppRendererEvent: vi.fn(),
+}));
+
+import { WecomGroupNotificationService, __testing } from '../wecomGroupNotification';
+
+function response(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { 'content-type': 'application/json' },
+ });
+}
+
+function createSecrets(initial: string | null = null) {
+ let value = initial;
+ return {
+ read: vi.fn(() => value),
+ write: vi.fn((_name: string, next: string) => {
+ value = next;
+ return true;
+ }),
+ remove: vi.fn(() => {
+ value = null;
+ }),
+ };
+}
+
+describe('WeCom group notification security boundary', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('accepts only the official HTTPS webhook endpoint with one key parameter', () => {
+ expect(() =>
+ __testing.parseWebhookUrl('https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=0123456789'),
+ ).not.toThrow();
+ for (const invalid of [
+ 'http://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=x',
+ 'https://evil.example/cgi-bin/webhook/send?key=x',
+ 'https://qyapi.weixin.qq.com.evil.example/cgi-bin/webhook/send?key=x',
+ 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=x&next=https://evil.example',
+ 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send',
+ ]) {
+ expect(() => __testing.parseWebhookUrl(invalid)).toThrow('WECOM_GROUP_WEBHOOK_INVALID');
+ }
+ });
+
+ it('splits UTF-8 text without breaking code points or exceeding the byte limit', () => {
+ const chunks = __testing.splitUtf8('企'.repeat(20), 10);
+ expect(chunks.join('')).toBe('企'.repeat(20));
+ expect(chunks.every((chunk) => Buffer.byteLength(chunk, 'utf8') <= 10)).toBe(true);
+ });
+
+ it('tests before persisting and never exposes the stored URL', async () => {
+ const fetchImpl = vi.fn(async () => response({ errcode: 0, errmsg: 'ok' }));
+ const secrets = createSecrets();
+ const service = new WecomGroupNotificationService(fetchImpl, secrets);
+
+ const state = await service.saveAndTest(
+ 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=abcdefgh',
+ );
+
+ expect(fetchImpl).toHaveBeenCalledWith(
+ 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=abcdefgh',
+ expect.objectContaining({ method: 'POST', redirect: 'manual' }),
+ );
+ expect(secrets.write).toHaveBeenCalledOnce();
+ expect(state).toEqual({ configured: true, maskedKey: '••••efgh' });
+ expect(JSON.stringify(service.getState())).not.toContain('abcdefgh');
+ });
+
+ it('does not persist a webhook when the test call fails', async () => {
+ const fetchImpl = vi.fn(async () => response({ errcode: 93000, errmsg: 'invalid' }));
+ const secrets = createSecrets();
+ const service = new WecomGroupNotificationService(fetchImpl, secrets);
+
+ await expect(
+ service.saveAndTest('https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=abcdefgh'),
+ ).rejects.toThrow('WECOM_GROUP_SEND_FAILED:93000');
+ expect(secrets.write).not.toHaveBeenCalled();
+ });
+
+ it('does not persist a tested webhook after the account boundary changes', async () => {
+ let release: (() => void) | undefined;
+ let current = true;
+ const fetchImpl = vi.fn(async () => {
+ await new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ return response({ errcode: 0, errmsg: 'ok' });
+ });
+ const secrets = createSecrets();
+ const service = new WecomGroupNotificationService(fetchImpl, secrets);
+
+ const saving = service.saveAndTest(
+ 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=abcdefgh',
+ () => current,
+ );
+ await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalledOnce());
+ current = false;
+ release?.();
+
+ await expect(saving).rejects.toThrow('IM account changed');
+ expect(secrets.write).not.toHaveBeenCalled();
+ });
+
+ it('rejects redirects instead of following a changed destination', async () => {
+ const fetchImpl = vi.fn(
+ async () =>
+ new Response('', {
+ status: 302,
+ headers: { location: 'https://evil.example' },
+ }),
+ );
+ const url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=abcdefgh';
+ const service = new WecomGroupNotificationService(fetchImpl, createSecrets(url));
+
+ await expect(service.test()).rejects.toThrow('WECOM_GROUP_REDIRECT_REJECTED');
+ });
+
+ it('serializes concurrent publishes to preserve message order', async () => {
+ const releases: Array<() => void> = [];
+ const bodies: string[] = [];
+ const fetchImpl = vi.fn(async (_url: string, init: RequestInit) => {
+ bodies.push(String(init.body));
+ await new Promise<void>((resolve) => releases.push(resolve));
+ return response({ errcode: 0 });
+ });
+ const url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=abcdefgh';
+ const service = new WecomGroupNotificationService(fetchImpl, createSecrets(url));
+
+ const first = service.publishMarkdown('first');
+ const second = service.publishMarkdown('second');
+ await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalledTimes(1));
+ releases.shift()?.();
+ await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalledTimes(2));
+ releases.shift()?.();
+ await Promise.all([first, second]);
+
+ expect(bodies[0]).toContain('first');
+ expect(bodies[1]).toContain('second');
+ });
+});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 90cdd12574..791c89d2eb 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -268,6 +268,10 @@ import { reapClaudeOrphansSync } from './claude-orphan-reaper';
import { startAgentProcessPriorityWatcher } from './agent-process-priority';
import { initAppBadgeService, clearAllSessionAttention } from './appBadgeService';
import { initNotificationService } from './notificationService';
+import {
+ initWecomGroupNotificationIpc,
+ wecomGroupNotificationService,
+} from './wecomGroupNotification';
import { getAgentIslandService, initAgentIslandService } from './agent-island/service.js';
import {
isAppContentWindow,
@@ -559,7 +563,7 @@ import {
isImDefaultEffort,
isImDefaultPermissionMode,
isImDefaultSettingsChannel,
- isWechatUnsupportedPermissionMode,
+ isRemoteImUnsupportedPermissionMode,
type ImDefaultAgentKind,
type ImDefaultAgentSettings,
type ImDefaultSettingsChannel,
@@ -2558,7 +2562,9 @@ const registerIpcHandlers = () => {
initNotificationService({
getWindow: () => getWindow() ?? null,
feishuIm,
+ wecomGroupPublisher: wecomGroupNotificationService,
});
+ initWecomGroupNotificationIpc();
initAgentIslandService({
getMainWindow: () => getWindow() ?? null,
isPlannedRemoteDaemonClose: isCcMgrUpgradeInFlight,
@@ -2676,8 +2682,8 @@ const registerIpcHandlers = () => {
async (_e, patch: unknown, rawChannel: unknown) => {
const channel = parseImDefaultSettingsChannel(rawChannel);
const parsedPatch = parseImDefaultSettingsPatch(patch);
- if (channel === 'wechat' && isWechatUnsupportedPermissionMode(parsedPatch.permissionMode)) {
- throwIpcError('INVALID_PARAMS', 'personal WeChat does not support this permission mode');
+ if (isRemoteImUnsupportedPermissionMode(channel, parsedPatch.permissionMode)) {
+ throwIpcError('INVALID_PARAMS', 'remote IM channel does not support this permission mode');
}
writeImDefaultSettingsPatch(parsedPatch, channel);
return imDefaultSettingsWire(channel);
diff --git a/apps/desktop/src/main/im/__tests__/defaultSettingsStore.test.ts b/apps/desktop/src/main/im/__tests__/defaultSettingsStore.test.ts
index d2b814a222..4f65ea80a2 100644
--- a/apps/desktop/src/main/im/__tests__/defaultSettingsStore.test.ts
+++ b/apps/desktop/src/main/im/__tests__/defaultSettingsStore.test.ts
@@ -220,13 +220,18 @@ describe('im default settings store', () => {
expect(migrated.channels.wechat.agentKind).toBe(IM_DEFAULT_SETTINGS.agentKind);
});
- it.each(['acceptEdits', 'bypassPermissions'] as const)(
- 'rejects %s for personal WeChat without changing saved defaults',
- (permissionMode) => {
+ it.each([
+ ['wechat', 'acceptEdits', 'WECHAT_PERMISSION_MODE_UNSUPPORTED'],
+ ['wechat', 'bypassPermissions', 'WECHAT_PERMISSION_MODE_UNSUPPORTED'],
+ ['wecom', 'acceptEdits', 'WECOM_PERMISSION_MODE_UNSUPPORTED'],
+ ['wecom', 'bypassPermissions', 'WECOM_PERMISSION_MODE_UNSUPPORTED'],
+ ] as const)(
+ 'rejects %s/%s for remote IM without changing saved defaults',
+ (channel, permissionMode, errorCode) => {
expect(() =>
- writeImDefaultSettingsPatch({ permissionMode }, 'wechat'),
- ).toThrow('WECHAT_PERMISSION_MODE_UNSUPPORTED');
- expect(readImDefaultSettings('wechat').permissionMode).toBe('auto');
+ writeImDefaultSettingsPatch({ permissionMode }, channel),
+ ).toThrow(errorCode);
+ expect(readImDefaultSettings(channel).permissionMode).toBe('auto');
},
);
diff --git a/apps/desktop/src/main/im/defaultSettingsStore.ts b/apps/desktop/src/main/im/defaultSettingsStore.ts
index cb59122da1..23d836c711 100644
--- a/apps/desktop/src/main/im/defaultSettingsStore.ts
+++ b/apps/desktop/src/main/im/defaultSettingsStore.ts
@@ -20,7 +20,7 @@ import {
isImDefaultAgentKind,
isImDefaultEffort,
isImDefaultPermissionMode,
- isWechatUnsupportedPermissionMode,
+ isRemoteImUnsupportedPermissionMode,
} from '../../shared/imDefaultSettings.js';
import { desktopMakerLogger } from '../maker-host/logger-adapter.js';
import {
@@ -219,8 +219,12 @@ export function writeImDefaultSettingsPatch(
patch: ImDefaultSettingsPatch,
channel?: ImDefaultSettingsChannel,
): OverrideSettingsState<ImDefaultSettings> {
- if (channel === 'wechat' && isWechatUnsupportedPermissionMode(patch.permissionMode)) {
- throw new Error('WECHAT_PERMISSION_MODE_UNSUPPORTED');
+ if (isRemoteImUnsupportedPermissionMode(channel, patch.permissionMode)) {
+ throw new Error(
+ channel === 'wechat'
+ ? 'WECHAT_PERMISSION_MODE_UNSUPPORTED'
+ : 'WECOM_PERMISSION_MODE_UNSUPPORTED',
+ );
}
const document = store.read();
const current = channel ? document.channels[channel] : document.global;
diff --git a/apps/desktop/src/main/im/host.ts b/apps/desktop/src/main/im/host.ts
index 1aa7c3bcc2..edcee09837 100644
--- a/apps/desktop/src/main/im/host.ts
+++ b/apps/desktop/src/main/im/host.ts
@@ -19,6 +19,7 @@ import {
createDingTalkIM,
createFeishuIM,
createTelegramIM,
+ createWecomIM,
type IMHost,
} from '@cindy/im';
import { TencentIlinkTransport } from '@cindy/wechat-ilink';
@@ -70,6 +71,7 @@ const host: IMHost = {
feishuMediaDir: path.join(app.getPath('userData'), 'cc-agent', 'feishu-media'),
discordMediaDir: path.join(app.getPath('userData'), 'cc-agent', 'discord-media'),
telegramMediaDir: path.join(app.getPath('userData'), 'cc-agent', 'telegram-media'),
+ wecomMediaDir: path.join(app.getPath('userData'), 'cc-agent', 'wecom-media'),
},
// cindy-media 媒体总仓回调(规则 25):IM 入站图片按平台 token
// 免重下、内容寻址去重、isCache=true 吃缓存回收策略;包侧只摸字节和字符串。
@@ -170,6 +172,7 @@ export const telegramIm = createTelegramIM(host, {
export const dingtalkIm = createDingTalkIM(host, {
fetcher: (input, init) => net.fetch(input instanceof URL ? input.toString() : input, init),
});
+export const wecomIm = createWecomIM(host);
/**
* Telegram 个人 bot 的行为/人格/群参与配置 IPC(设置卡数据通道)。
* 必须由 bootstrap 显式调用(与 im.registerIpc() 同期) — 不能放模块顶层:
@@ -272,4 +275,11 @@ wechatCompatibilityPolicy.subscribe((decision) => {
log.warn('failed to apply personal WeChat compatibility policy');
});
});
-export const im = createIM([feishuIm, discordIm, wechatIm, telegramIm, dingtalkIm]);
+export const im = createIM([
+ feishuIm,
+ discordIm,
+ wechatIm,
+ telegramIm,
+ dingtalkIm,
+ wecomIm,
+]);
diff --git a/apps/desktop/src/main/im/index.ts b/apps/desktop/src/main/im/index.ts
index 90781fdb33..53f769ce07 100644
--- a/apps/desktop/src/main/im/index.ts
+++ b/apps/desktop/src/main/im/index.ts
@@ -67,12 +67,14 @@ import {
dingtalkIm,
wechatCompatibilityPolicy,
wechatIm,
+ wecomIm,
} from './host';
import { wireFeishuOrchestrator, type FeishuOrchestratorConfig } from './feishu';
import { wireDiscordOrchestrator } from './discord';
import { wireTelegramOrchestrator } from './telegram';
import { wireDingTalkOrchestrator } from './dingtalk';
import { wireWechatOrchestrator } from './wechat';
+import { wireWecomOrchestrator } from './wecom';
import { resetTelegramGroupContextCursors } from './telegram/groupWindow';
import { getImOrchestrator, listImOrchestrators } from './shared/orchestrator';
import { createSerializedConnectionLifecycle } from './connectionLifecycle';
@@ -106,6 +108,7 @@ export {
telegramIm,
dingtalkIm,
wechatIm,
+ wecomIm,
} from './host';
const log = createLogger('main:im');
@@ -189,6 +192,13 @@ const WECHAT_CONFIG: ImOrchestratorConfig = {
effortOverrides: IM_DEFAULT_EFFORT_OVERRIDES,
};
+const WECOM_CONFIG: ImOrchestratorConfig = {
+ agentKind: IM_DEFAULT_SETTINGS.agentKind,
+ defaultModel: IM_DEFAULT_SETTINGS.agents[IM_DEFAULT_SETTINGS.agentKind].model,
+ defaultPermissionMode: IM_DEFAULT_SETTINGS.permissionMode,
+ effortOverrides: IM_DEFAULT_EFFORT_OVERRIDES,
+};
+
export function startImOrchestrators(): void {
wechatCompatibilityPolicy.start();
if (wired) return;
@@ -209,6 +219,7 @@ export function startImOrchestrators(): void {
wireTelegramOrchestrator(telegramIm, TELEGRAM_CONFIG);
wireDingTalkOrchestrator(dingtalkIm, DINGTALK_CONFIG);
wireWechatOrchestrator(wechatIm, WECHAT_CONFIG);
+ wireWecomOrchestrator(wecomIm, WECOM_CONFIG);
ipcMain.handle('wechatBot:get-state', (event) => {
assertTrustedAppRendererEvent(event);
diff --git a/apps/desktop/src/main/im/shared/types.ts b/apps/desktop/src/main/im/shared/types.ts
index a0f35902db..4dc6c14157 100644
--- a/apps/desktop/src/main/im/shared/types.ts
+++ b/apps/desktop/src/main/im/shared/types.ts
@@ -28,7 +28,14 @@ import type {
import type { ChannelIM, ImOutputDriver, IMMessageEvent, IMUnsupportedEntry } from '@cindy/im';
/** 渠道名 — 同时是 sessions.source 列值与 IdentityKey.channel 的值域。 */
-export type ImChannelName = 'feishu' | 'slack' | 'discord' | 'wechat' | 'telegram' | 'dingtalk';
+export type ImChannelName =
+ | 'feishu'
+ | 'slack'
+ | 'discord'
+ | 'wechat'
+ | 'telegram'
+ | 'dingtalk'
+ | 'wecom';
/**
* IM 编排层的产品默认配置(由 main/im/index.ts 产品接线层注入)。
diff --git a/apps/desktop/src/main/im/wecom/adapter.ts b/apps/desktop/src/main/im/wecom/adapter.ts
new file mode 100644
index 0000000000..e78144cccc
--- /dev/null
+++ b/apps/desktop/src/main/im/wecom/adapter.ts
@@ -0,0 +1,59 @@
+import fs from 'node:fs';
+
+import type { RichChannelIM, WecomIM } from '@cindy/im';
+
+import type { ImChannelAdapter, ImOrchestratorConfig } from '../shared/types';
+import { ownerScopedImUserDataPath } from '../ownerScopedStorage';
+import { ui } from './uiText';
+import type { WecomTextInteractions } from './textInteractions';
+
+function ensureWorkingDir(botId: string): string {
+ const safeBotId = Buffer.from(botId, 'utf8').toString('base64url').slice(0, 96);
+ const dir = ownerScopedImUserDataPath('im-working-dir', `wecom-${safeBotId}`);
+ fs.mkdirSync(dir, { recursive: true });
+ return dir;
+}
+
+function sessionSafeUserId(userId: string): string {
+ return Buffer.from(userId, 'utf8').toString('base64url');
+}
+
+export function buildWecomAdapter(
+ wecomIm: WecomIM,
+ interactions: WecomTextInteractions,
+ config: ImOrchestratorConfig,
+): ImChannelAdapter {
+ return {
+ channel: 'wecom',
+ im: wecomIm as unknown as RichChannelIM,
+ output: {
+ kind: 'chunked-text',
+ im: wecomIm,
+ commitFinal: (output) => wecomIm.commitFinal(output),
+ },
+ config,
+ ui,
+ sessions: {
+ source: 'wecom',
+ sessionIdFor: (botId, userId) =>
+ `wecom_${sessionSafeUserId(botId)}_${sessionSafeUserId(userId)}`,
+ defaultTitle: (userId) =>
+ userId.startsWith('group/')
+ ? `企微群 · ${userId.slice(-6)}`
+ : `企业微信 · ${userId.slice(-6)}`,
+ generatedTitlePrefix: '企业微信 · ',
+ workspaceKind: 'dialogue',
+ ensureWorkingDir,
+ extraInsertColumns: (botId, userId) => ({
+ imBotContextId: botId,
+ imUserId: userId,
+ }),
+ },
+ processingEmoji: '',
+ buildVendorOptions: (userId) => ({
+ source: 'wecom',
+ wecomConversationId: userId,
+ }),
+ handleTextInteraction: (userId, request) => interactions.handle(userId, request),
+ };
+}
diff --git a/apps/desktop/src/main/im/wecom/index.ts b/apps/desktop/src/main/im/wecom/index.ts
new file mode 100644
index 0000000000..c10bfdd569
--- /dev/null
+++ b/apps/desktop/src/main/im/wecom/index.ts
@@ -0,0 +1,11 @@
+import type { WecomIM } from '@cindy/im';
+
+import { createImOrchestrator } from '../shared/orchestrator';
+import type { ImOrchestratorConfig } from '../shared/types';
+import { buildWecomAdapter } from './adapter';
+import { WecomTextInteractions } from './textInteractions';
+
+export function wireWecomOrchestrator(wecomIm: WecomIM, config: ImOrchestratorConfig): void {
+ const interactions = new WecomTextInteractions(wecomIm);
+ createImOrchestrator(buildWecomAdapter(wecomIm, interactions, config));
+}
diff --git a/apps/desktop/src/main/im/wecom/textInteractions.ts b/apps/desktop/src/main/im/wecom/textInteractions.ts
new file mode 100644
index 0000000000..822cefdcfb
--- /dev/null
+++ b/apps/desktop/src/main/im/wecom/textInteractions.ts
@@ -0,0 +1,148 @@
+import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core';
+import type { IMMessageEvent, WecomIM } from '@cindy/im';
+
+interface PendingInteraction {
+ request: InteractionRequest;
+ resolve: (decision: InteractionDecision) => void;
+ timer: ReturnType<typeof setTimeout>;
+}
+
+const INTERACTION_TIMEOUT_MS = 10 * 60_000;
+
+export class WecomTextInteractions {
+ private readonly pending = new Map<string, PendingInteraction>();
+
+ constructor(private readonly im: WecomIM) {
+ im.onTextMessageIntercept((event) => this.consume(event));
+ im.onStatusChange((status) => {
+ if (status.kind === 'idle') this.cancelAll('wecom_interaction_disconnected');
+ });
+ }
+
+ async handle(userId: string, request: InteractionRequest): Promise<InteractionDecision> {
+ const previous = this.pending.get(userId);
+ if (previous) {
+ clearTimeout(previous.timer);
+ previous.resolve(defaultDecision(previous.request, 'replaced_by_new_request'));
+ }
+
+ let resolvePending!: (decision: InteractionDecision) => void;
+ const result = new Promise<InteractionDecision>((resolve) => {
+ resolvePending = resolve;
+ });
+ const timer = setTimeout(() => {
+ this.pending.delete(userId);
+ resolvePending(defaultDecision(request, 'wecom_interaction_timeout'));
+ }, INTERACTION_TIMEOUT_MS);
+ timer.unref?.();
+ this.pending.set(userId, { request, resolve: resolvePending, timer });
+
+ try {
+ await this.im.sendText(userId, formatPrompt(request));
+ } catch (error) {
+ const current = this.pending.get(userId);
+ if (current?.request.requestId === request.requestId) {
+ clearTimeout(current.timer);
+ this.pending.delete(userId);
+ }
+ return defaultDecision(
+ request,
+ error instanceof Error ? error.message : 'wecom_interaction_send_failed',
+ );
+ }
+ return result;
+ }
+
+ private cancelAll(reason: string): void {
+ for (const pending of this.pending.values()) {
+ clearTimeout(pending.timer);
+ pending.resolve(defaultDecision(pending.request, reason));
+ }
+ this.pending.clear();
+ }
+
+ private consume(event: IMMessageEvent): boolean {
+ const pending = this.pending.get(event.senderId);
+ if (!pending) return false;
+ const decision = parseReply(pending.request, event.text);
+ if (!decision) {
+ void this.im.sendText(
+ event.senderId,
+ '回复格式不正确。请按上一条消息提示回复;权限确认只支持“允许”或“拒绝”。',
+ );
+ return true;
+ }
+ clearTimeout(pending.timer);
+ this.pending.delete(event.senderId);
+ pending.resolve(decision);
+ void this.im.sendText(event.senderId, '已收到你的选择,继续处理。');
+ return true;
+ }
+}
+
+function formatPrompt(request: InteractionRequest): string {
+ if (request.kind === 'permission') {
+ return `需要确认工具“${request.displayName ?? request.toolName}”。
+回复“允许”执行一次,或回复“拒绝”取消本次操作。企业微信内不支持永久授权。`;
+ }
+ if (request.kind === 'plan_review') {
+ const plan = request.plan.length > 6_000 ? `${request.plan.slice(0, 6_000)}…` : request.plan;
+ return `Agent 提交了一份执行计划:
+
+${plan}
+
+回复“批准”继续,或回复“拒绝”取消。`;
+ }
+ const question = request.questions[0];
+ if (!question) return 'Agent 正在等待你的回答,但没有可显示的问题。请回复“继续”。';
+ const options = (question.options ?? [])
+ .slice(0, 9)
+ .map((option, index) => `${index + 1}. ${option.label}`)
+ .join('\n');
+ return `Agent 需要你的回答:
+${question.question}
+${options ? `\n${options}\n` : ''}
+请回复选项序号,或直接输入你的回答。`;
+}
+
+function defaultDecision(request: InteractionRequest, reason: string): InteractionDecision {
+ if (request.kind === 'ask_user_question') {
+ return { kind: 'ask_user_question', answers: {} };
+ }
+ if (request.kind === 'plan_review') {
+ return { kind: 'plan_review', behavior: 'deny', reason };
+ }
+ return { kind: 'permission', behavior: 'deny', reason };
+}
+
+function parseReply(request: InteractionRequest, rawText: string): InteractionDecision | null {
+ const text = rawText.trim();
+ if (!text) return null;
+ const normalized = text.toLowerCase();
+ if (request.kind === 'permission') {
+ if (['允许', '同意', '确认', 'allow', 'yes', 'y'].includes(normalized)) {
+ return { kind: 'permission', behavior: 'allow' };
+ }
+ if (['拒绝', '不允许', '取消', 'deny', 'no', 'n'].includes(normalized)) {
+ return { kind: 'permission', behavior: 'deny', reason: 'wecom_user_denied' };
+ }
+ return null;
+ }
+ if (request.kind === 'plan_review') {
+ if (['批准', '同意', '确认', '继续', 'approve', 'allow', 'yes', 'y'].includes(normalized)) {
+ return { kind: 'plan_review', behavior: 'allow' };
+ }
+ if (['拒绝', '取消', 'deny', 'no', 'n'].includes(normalized)) {
+ return { kind: 'plan_review', behavior: 'deny', reason: 'wecom_user_denied' };
+ }
+ return null;
+ }
+ const question = request.questions[0];
+ if (!question) return { kind: 'ask_user_question', answers: {} };
+ const index = Number.parseInt(text, 10);
+ const option = Number.isInteger(index) && index >= 1 ? question.options?.[index - 1] : undefined;
+ return {
+ kind: 'ask_user_question',
+ answers: { [question.question]: option?.label ?? text },
+ };
+}
diff --git a/apps/desktop/src/main/im/wecom/uiText.ts b/apps/desktop/src/main/im/wecom/uiText.ts
new file mode 100644
index 0000000000..0b36527282
--- /dev/null
+++ b/apps/desktop/src/main/im/wecom/uiText.ts
@@ -0,0 +1,140 @@
+import type { IMUnsupportedEntry } from '@cindy/im';
+
+import type { ImUiTextPack } from '../shared/types';
+
+export const ui = {
+ slash: {
+ new: '🌱 新会话已开始,之前的上下文已清空。',
+ help: `🤖 可用命令:
+
+/new 开始新会话
+/model 切换模型
+/permission 调整权限模式
+/ctr 接管 desktop 会话
+/exctr 结束接管,回到企业微信会话
+/help 查看帮助
+
+任务运行中可发送 \`!stop\` 中止当前任务并清空排队消息。`,
+ unknownCommand: (cmd: string) =>
+ `未识别命令 \`${cmd}\`。可用命令:/new、/model、/permission、/ctr、/exctr、/help`,
+ detachedBySlash: '🚪 已结束接管,后续消息回到企业微信会话。',
+ detachedByRevoke: '⚠️ desktop 端已收回接管,后续消息回到企业微信会话。',
+ notAttached: '当前没有正在接管的会话。',
+ },
+ agent: {
+ completedNoText: '✅ 任务已完成(本轮没有文本输出)',
+ runtimeError: (errMsg: string) => `⚠️ Agent 执行失败:${errMsg.slice(0, 200)}`,
+ sendInternalError: (errMsg: string) => `❌ 消息发送失败:${errMsg}`,
+ apiKeyMissing: '⚠️ 当前模型尚未完成认证。请在 desktop 的设置中连接模型供应商后重试。',
+ authMissing: ({ providerLabel, providerId, missing, agentKind, model, attached }) => {
+ const provider = providerLabel ?? providerId ?? '当前供应商';
+ const reason =
+ missing === 'gateway-key'
+ ? '需要先配置 Cindy AI Key'
+ : missing === 'provider-key'
+ ? '尚未配置该供应商的 API Key'
+ : missing === 'provider-disconnected'
+ ? '连接已断开或失效'
+ : `需要先登录 ${agentKind}`;
+ const message = `⚠️ 当前企业微信会话使用「${provider}」(${model}),${reason}。`;
+ return attached
+ ? `${message}\n请在 desktop 修复认证后继续发送消息。`
+ : `${message}\n修改后请发送 \`/new\` 开始新会话。`;
+ },
+ controlInProgress: '🎮 接管选择尚未完成,请先处理上一条交互消息。',
+ credentialBusy: '⏳ 本地 Agent 正在运行,暂时不能切换凭证模式,请稍后重试。',
+ queuedNotice: (position: number) =>
+ position <= 1
+ ? '⏳ 上一轮仍在运行,这条消息已排队。需要中止可发送 `!stop`。'
+ : `⏳ 上一轮仍在运行,这条消息排在第 ${position} 位。需要中止可发送 \`!stop\`。`,
+ stopDone: (droppedQueued: number) =>
+ droppedQueued > 0
+ ? `⏹ 已中止当前任务,并移除 ${droppedQueued} 条排队消息。`
+ : '⏹ 已中止当前任务。',
+ stopIdle: '当前没有正在运行或排队的任务。',
+ scheduledTaskHeader: (name: string | null) => (name ? `🤖 自动任务「${name}」` : '🤖 自动任务'),
+ unsupportedOnly: (entries: IMUnsupportedEntry[]) =>
+ `🙏 暂时无法处理这条消息:\n${entries.map((entry) => `• ${entry.label}`).join('\n')}`,
+ unsupportedNotice: (entries: IMUnsupportedEntry[]) =>
+ `ℹ️ 以下内容未能处理:\n${entries.map((entry) => `• ${entry.label}`).join('\n')}\n\n其它内容将继续处理。`,
+ },
+ cards: {
+ permission: {
+ title: (toolName: string) => `🔧 工具调用:${toolName}`,
+ paramsLabel: '**参数预览**',
+ btnAllowOnce: '✅ 仅本次允许',
+ btnAllowAlways: '✅ 总是允许',
+ btnDeny: '❌ 拒绝',
+ resolvedAllowOnce: '✅ 已允许(仅本次)',
+ resolvedAllowAlways: '✅ 已允许(以后均允许)',
+ resolvedDeny: '❌ 已拒绝',
+ },
+ ask: {
+ title: (header: string) => `❓ ${header}`,
+ noOptionsHint: '_请直接回复文字。_',
+ resolved: (optionLabel: string) => `✅ 已选择:${optionLabel}`,
+ },
+ plan: {
+ title: '📋 执行计划',
+ btnApprove: '✅ 批准',
+ btnReject: '❌ 拒绝',
+ resolvedApproved: '✅ 已批准',
+ resolvedRejected: '❌ 已拒绝',
+ },
+ model: {
+ title: '🤖 切换模型',
+ currentLine: (label: string, effort: string | null, description: string) =>
+ effort
+ ? `**当前**:${label} · effort \`${effort}\`\n_${description}_`
+ : `**当前**:${label}\n_${description}_`,
+ hint: '请选择要使用的模型。',
+ optionLabel: (providerName: string, label: string, effort: string | null) =>
+ effort ? `${providerName} / ${label} · ${effort}` : `${providerName} / ${label}`,
+ resolved: (label: string, effort: string | null) =>
+ effort ? `✅ 已切换到 ${label}(effort:${effort})` : `✅ 已切换到 ${label}`,
+ failed: (reason: string) => `❌ 模型切换失败:${reason}`,
+ },
+ permissionMode: {
+ title: '🛡️ 调整权限模式',
+ currentLine: (label: string, description: string) => `**当前**:${label}\n_${description}_`,
+ hint: '请选择权限模式。',
+ optionLabel: (label: string) => label,
+ resolved: (label: string) => `✅ 权限模式已切换到 ${label}`,
+ failed: (reason: string) => `❌ 权限模式切换失败:${reason}`,
+ fullAccessConfirmTitle: '⚠️ 确认开启 Full access?',
+ fullAccessConfirmBody:
+ 'Full access 会关闭工作区沙箱并跳过常规审批。Cindy 可以修改工作区外文件并执行联网命令;内置高风险操作仍会要求确认。',
+ btnConfirmFullAccess: '开启 Full access',
+ btnCancelFullAccess: '保留当前权限',
+ fullAccessCancelled: '已取消,保留当前权限',
+ },
+ control: {
+ title: '🎮 选择工作区',
+ emptyBody: '_暂时没有可接管的工作区,请先在 desktop 创建会话。_',
+ hint: '选择工作区继续,或退出本次操作。',
+ attachedSwitchHint: (sessionTitle: string) => `当前正在接管:**${sessionTitle}**`,
+ btnExit: '🚪 退出',
+ resolvedExit: '🚪 已退出接管',
+ sessionPickerTitle: (displayName: string) => `🎮 ${displayName} 中的会话`,
+ sessionPickerHint: '选择会话、创建新会话或返回上一步。',
+ sessionPickerEmptyBody: (displayName: string) => `_${displayName} 中暂时没有可用会话。_`,
+ btnNew: '➕ 新建',
+ btnBack: '↩️ 返回',
+ resolvedSessionPick: (sessionTitle: string, workspaceName: string) =>
+ `🎯 已接管 **${sessionTitle}**(${workspaceName})`,
+ resolvedNewSession: (workspaceName: string) => `✨ 已在 **${workspaceName}** 新建并接管会话`,
+ attachFailed: (reason: string) => `❌ 接管失败:${reason}`,
+ sessionBusyOldCardPlaceholder: '⏳ 该会话仍在运行,请稍后重试。',
+ sessionBusyPrompts: [
+ (sessionTitle: string) => `⏳ **${sessionTitle}** 正在运行,请等待当前回合结束。`,
+ ],
+ takeoverLoadingPrompts: [(sessionTitle: string) => `⏳ 正在接管 **${sessionTitle}**…`],
+ sessionAttachedOneshotPrompts: [
+ '我已从企业微信接管此会话。请简要同步当前进度,并询问下一步指令。',
+ ],
+ newSessionWelcomePrompts: [
+ (workspaceName: string) => `✨ 已在 **${workspaceName}** 创建新会话,可以发送第一条指令。`,
+ ],
+ },
+ },
+} satisfies ImUiTextPack;
diff --git a/apps/desktop/src/main/localDb/mapper.ts b/apps/desktop/src/main/localDb/mapper.ts
index 4419bffe9c..762cbe2999 100644
--- a/apps/desktop/src/main/localDb/mapper.ts
+++ b/apps/desktop/src/main/localDb/mapper.ts
@@ -555,6 +555,7 @@ export function scheduleToCamel(row: ScheduleRow): Schedule {
notify: {
desktop: !!row.notifyDesktop,
feishu: !!row.notifyFeishu,
+ ...(row.notifyWecomGroup ? { wecomGroup: true } : {}),
},
status: row.status as ScheduleStatus,
createdAt: row.createdAt,
@@ -599,6 +600,7 @@ export function scheduleCreateToRow(s: Schedule): ScheduleInsert {
preRunHookTimeoutMs: s.preRunHook?.timeoutMs ?? null,
notifyDesktop: s.notify.desktop,
notifyFeishu: s.notify.feishu,
+ notifyWecomGroup: s.notify.wecomGroup === true,
status: s.status,
createdAt: s.createdAt,
updatedAt: s.updatedAt,
@@ -655,9 +657,10 @@ export function schedulePatchToRow(patch: Partial<Schedule>): Partial<ScheduleIn
}
if (hasKey(patch, 'notify')) {
// 嵌套对象整体替换:必须两列同时写
- const n = patch.notify ?? { desktop: false, feishu: false };
+ const n = patch.notify ?? { desktop: false, feishu: false, wecomGroup: false };
out.notifyDesktop = !!n.desktop;
out.notifyFeishu = !!n.feishu;
+ out.notifyWecomGroup = !!n.wecomGroup;
}
if (hasKey(patch, 'status')) out.status = patch.status as ScheduleStatus;
if (hasKey(patch, 'createdAt')) out.createdAt = patch.createdAt as number;
diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.ts
index 9ef1420faf..671a37f008 100644
--- a/apps/desktop/src/main/localDb/schema.ts
+++ b/apps/desktop/src/main/localDb/schema.ts
@@ -29,6 +29,7 @@ const SESSION_SOURCES = [
'discord',
'wechat',
'dingtalk',
+ 'wecom',
'scheduler',
'learn',
'shared',
@@ -778,6 +779,7 @@ export const schedules = sqliteTable(
}),
notifyDesktop: integer('notify_desktop', { mode: 'boolean' }).notNull().default(true),
notifyFeishu: integer('notify_feishu', { mode: 'boolean' }).notNull().default(false),
+ notifyWecomGroup: integer('notify_wecom_group', { mode: 'boolean' }).notNull().default(false),
status: text('status', { enum: ['active', 'paused', 'expired'] })
.notNull()
.default('active'),
diff --git a/apps/desktop/src/main/notificationService.ts b/apps/desktop/src/main/notificationService.ts
index a119e5a550..a529c746ba 100644
--- a/apps/desktop/src/main/notificationService.ts
+++ b/apps/desktop/src/main/notificationService.ts
@@ -32,6 +32,7 @@ import { getMobileNotifyGeneration, sendMobileSessionNotify } from './device-lin
import { latestMessageText } from './localDb/latestMessageText';
import { drainPersistQueue } from './messagePersistBroadcaster';
import { createLogger } from './logger';
+import type { WecomGroupNotificationPublisher } from './wecomGroupNotification';
const log = createLogger('notificationService');
let desktopNotificationsEnabled = true;
@@ -75,7 +76,7 @@ interface ShowSessionEventPayload {
* mobile 通道没有桌面侧开关:是否收到由手机端自行注册/注销推送 token 决定,
* 发送侧的防打扰(远程正在看该会话 / 短窗去重)在 device-link 模块内收口。
*/
- channels?: { desktop?: boolean; feishu?: boolean; mobile?: boolean };
+ channels?: { desktop?: boolean; feishu?: boolean; wecomGroup?: boolean; mobile?: boolean };
}
/**
@@ -99,7 +100,7 @@ function buildBody(kind: SessionEventKind): string {
* 飞书私聊文案 — 单行纯文本(lark_md 渲染),保持极简,与桌面 toast 信息一致。
* 标题 + 状态合并到一行,避免飞书消息列表里显得空荡。
*/
-function buildFeishuText(title: string, kind: SessionEventKind): string {
+function buildExternalNotificationText(title: string, kind: SessionEventKind): string {
const status = kind === 'needs-reply'
? '需要你回复'
: kind === 'error'
@@ -158,10 +159,11 @@ export interface NotificationServiceDeps {
* (main/im 模块单例),保证 owner openId 与卡片回执等行为一致。
*/
feishuIm: FeishuIM;
+ wecomGroupPublisher?: WecomGroupNotificationPublisher;
}
export function initNotificationService(deps: NotificationServiceDeps): void {
- const { getWindow, feishuIm } = deps;
+ const { getWindow, feishuIm, wecomGroupPublisher } = deps;
ipcMain.handle('notification:set-desktop-enabled', (_event, enabled: unknown) => {
if (typeof enabled !== 'boolean') {
@@ -186,6 +188,7 @@ export function initNotificationService(deps: NotificationServiceDeps): void {
// channels 缺省/未传 → 默认仅桌面 (防御漏传,见 ShowSessionEventPayload 注释)。
const wantDesktop = channels?.desktop ?? true;
const wantFeishu = channels?.feishu === true;
+ const wantWecomGroup = channels?.wecomGroup === true;
if (wantDesktop) {
showDesktopSessionEvent(getWindow, { sessionId, title: safeTitle, kind });
@@ -229,6 +232,15 @@ export function initNotificationService(deps: NotificationServiceDeps): void {
if (wantFeishu) {
await sendFeishuMessage(feishuIm, safeTitle, kind);
}
+ if (wantWecomGroup && wecomGroupPublisher) {
+ try {
+ await wecomGroupPublisher.publishMarkdown(buildExternalNotificationText(safeTitle, kind));
+ } catch (err) {
+ log.warn('[notification] WeCom group notification failed (non-fatal)', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
},
);
}
@@ -309,7 +321,7 @@ async function sendFeishuMessage(
return;
}
try {
- await feishuIm.sendMarkdownText(ownerOpenId, buildFeishuText(safeTitle, kind));
+ await feishuIm.sendMarkdownText(ownerOpenId, buildExternalNotificationText(safeTitle, kind));
} catch (err) {
// 飞书 SDK 包了一层 axios; 400 等业务错误的真正 message 在 response.data 里,
// 显式拆出来 log。与 scheduler-host/notifier.ts 的 catch 写法对齐。
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/notifier.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/notifier.test.ts
index 32f55713c4..cdaadd1667 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/notifier.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/notifier.test.ts
@@ -37,13 +37,16 @@ function run(status: ScheduleRun['status']): ScheduleRun {
function createNotifier(opts?: {
sendMarkdownText?: ReturnType<typeof vi.fn>;
shouldNotifyDesktop?: () => boolean;
+ publishMarkdown?: ReturnType<typeof vi.fn>;
}): {
notifier: DesktopNotifier;
sendMarkdownText: ReturnType<typeof vi.fn>;
warn: ReturnType<typeof vi.fn>;
+ publishMarkdown: ReturnType<typeof vi.fn>;
} {
const sendMarkdownText = opts?.sendMarkdownText ?? vi.fn(async () => ({ messageId: 'msg-1' }));
const warn = vi.fn();
+ const publishMarkdown = opts?.publishMarkdown ?? vi.fn(async () => undefined);
const notifier = new DesktopNotifier({
getMainWindow: () => null as BrowserWindow | null,
feishuIm: {
@@ -52,8 +55,9 @@ function createNotifier(opts?: {
} as unknown as FeishuIM,
logger: { warn },
shouldNotifyDesktop: opts?.shouldNotifyDesktop ?? (() => true),
+ wecomGroupPublisher: { publishMarkdown },
});
- return { notifier, sendMarkdownText, warn };
+ return { notifier, sendMarkdownText, warn, publishMarkdown };
}
describe('DesktopNotifier desktop status mapping', () => {
@@ -172,4 +176,23 @@ describe('DesktopNotifier desktop status mapping', () => {
);
expect(warn).toHaveBeenCalledWith('feishu notify failed', sendError);
});
+
+ it('sends a WeCom group notification and keeps failures non-fatal', async () => {
+ const sendError = new Error('Webhook unavailable');
+ const publishMarkdown = vi
+ .fn()
+ .mockResolvedValueOnce(undefined)
+ .mockRejectedValueOnce(sendError);
+ const { notifier, warn } = createNotifier({ publishMarkdown });
+ const groupSchedule = {
+ ...schedule,
+ notify: { desktop: false, feishu: false, wecomGroup: true },
+ } as Schedule;
+
+ await notifier.notify(groupSchedule, { ...run('success'), resultText: '检查通过' });
+ expect(publishMarkdown).toHaveBeenCalledWith(expect.stringContaining('检查通过'));
+
+ await expect(notifier.notify(groupSchedule, run('failed'))).resolves.toBeUndefined();
+ expect(warn).toHaveBeenCalledWith('WeCom group notify failed', sendError);
+ });
});
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts
index dfb5bee4aa..f01d9887e6 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts
@@ -153,6 +153,7 @@ const SCHEDULER_DDL = [
skip_log_session_id TEXT REFERENCES sessions(id) ON DELETE SET NULL,
notify_desktop INTEGER NOT NULL DEFAULT 1,
notify_feishu INTEGER NOT NULL DEFAULT 0,
+ notify_wecom_group INTEGER NOT NULL DEFAULT 0,
status TEXT NOT NULL DEFAULT 'active',
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
diff --git a/apps/desktop/src/main/scheduler-host/index.ts b/apps/desktop/src/main/scheduler-host/index.ts
index d686000a41..95c9eb25d1 100644
--- a/apps/desktop/src/main/scheduler-host/index.ts
+++ b/apps/desktop/src/main/scheduler-host/index.ts
@@ -45,6 +45,7 @@ import { ScriptScheduleRunner } from './script-runner';
import { SchedulerScriptCapabilityBroker } from './script-capability-broker';
import { DesktopNotifier } from './notifier';
import { withScheduleLock } from './scheduleLock';
+import { wecomGroupNotificationService } from '../wecomGroupNotification';
export interface StartSchedulerDeps {
maker: Maker;
@@ -71,6 +72,7 @@ export async function startScheduler(deps: StartSchedulerDeps): Promise<Schedule
logger: deps.logger,
shouldNotifyDesktop: () =>
getDesktopNotificationsEnabled() && !(getAgentIslandService()?.isEnabled() ?? false),
+ wecomGroupPublisher: wecomGroupNotificationService,
});
const promptRunner = new MakerScheduleRunner({
maker: deps.maker,
diff --git a/apps/desktop/src/main/scheduler-host/notifier.ts b/apps/desktop/src/main/scheduler-host/notifier.ts
index 85df0ebdc3..e0982ff4b0 100644
--- a/apps/desktop/src/main/scheduler-host/notifier.ts
+++ b/apps/desktop/src/main/scheduler-host/notifier.ts
@@ -19,6 +19,7 @@ import type { Logger } from '@cindy/maker-scheduler';
import { stripTrailingPathSeparators } from '../../shared/pathText';
import { showDesktopSessionEvent } from '../notificationService';
import { getMobileNotifyGeneration, sendMobileSessionNotify } from '../device-link';
+import type { WecomGroupNotificationPublisher } from '../wecomGroupNotification';
export interface DesktopNotifierDeps {
getMainWindow: () => BrowserWindow | null;
@@ -26,6 +27,7 @@ export interface DesktopNotifierDeps {
logger: Logger;
/** Global desktop preference and Agent Island arbitration, evaluated at send time. */
shouldNotifyDesktop: () => boolean;
+ wecomGroupPublisher?: WecomGroupNotificationPublisher;
}
export class DesktopNotifier implements Notifier {
@@ -49,11 +51,21 @@ export class DesktopNotifier implements Notifier {
this.deps.logger.warn?.('feishu notify failed', err);
}
}
+ if (schedule.notify.wecomGroup && this.deps.wecomGroupPublisher) {
+ try {
+ await this.deps.wecomGroupPublisher.publishMarkdown(renderExternalMessage(schedule, run));
+ } catch (err) {
+ this.deps.logger.warn?.('WeCom group notify failed', err);
+ }
+ }
// 手机推送随 schedule 的通知意愿走:desktop / feishu 全关表示用户不想被这个
// 调度打扰,mobile 不得绕过(schedule 级暂无独立 mobile 开关,任一通道开启即
// 视为允许提醒);是否真的收到仍由手机端注册 token 决定,发送侧防打扰在
// device-link 模块收口,失败静默。
- if (run.sessionId && (schedule.notify.desktop || schedule.notify.feishu)) {
+ if (
+ run.sessionId &&
+ (schedule.notify.desktop || schedule.notify.feishu || schedule.notify.wecomGroup)
+ ) {
try {
// 正文带运行结果摘要(与飞书卡片同源素材):成功给 resultText,失败给
// errorMsg;缺省回退终态短文案。截断由 mobileNotify 按协议上限统一处理。
@@ -92,7 +104,7 @@ export class DesktopNotifier implements Notifier {
);
return;
}
- const text = renderFeishuMessage(schedule, run);
+ const text = renderExternalMessage(schedule, run);
try {
await this.deps.feishuIm.sendMarkdownText(ownerOpenId, text);
} catch (err) {
@@ -121,7 +133,7 @@ export class DesktopNotifier implements Notifier {
* - URL 直接写,飞书自动识别成可点击链接
* - 不要带 `code` (cards.ts 里 stripInlineCode 会把 backtick 整对剥掉)
*/
-function renderFeishuMessage(schedule: Schedule, run: ScheduleRun): string {
+function renderExternalMessage(schedule: Schedule, run: ScheduleRun): string {
const lines: string[] = [`${statusEmoji(run.status)} **${schedule.name}**`];
if (run.status === 'failed' && run.errorMsg) {
diff --git a/apps/desktop/src/main/scheduler-host/project-automation-loader.ts b/apps/desktop/src/main/scheduler-host/project-automation-loader.ts
index 51324d32c2..10c5c083f5 100644
--- a/apps/desktop/src/main/scheduler-host/project-automation-loader.ts
+++ b/apps/desktop/src/main/scheduler-host/project-automation-loader.ts
@@ -62,7 +62,7 @@ export interface ProjectScheduleConfig {
* 删掉即清空 DB 里的 hook。与 renderer projectAutomationConfig.ts 同形。
*/
preRunHook?: { command: string; timeoutMs?: number };
- notify?: { desktop?: boolean; feishu?: boolean };
+ notify?: { desktop?: boolean; feishu?: boolean; wecomGroup?: boolean };
}
export interface ReconcileResult {
@@ -505,7 +505,8 @@ export function schedulesDiffer(
(schedule.preRunHook?.command ?? '') !== (expected.preRunHook?.command ?? '') ||
(schedule.preRunHook?.timeoutMs ?? undefined) !== (expected.preRunHook?.timeoutMs ?? undefined) ||
schedule.notify.desktop !== expected.notify?.desktop ||
- schedule.notify.feishu !== expected.notify?.feishu
+ schedule.notify.feishu !== expected.notify?.feishu ||
+ schedule.notify.wecomGroup !== expected.notify?.wecomGroup
);
}
@@ -515,6 +516,7 @@ function normalizeNotify(
return {
desktop: notify?.desktop ?? true,
feishu: notify?.feishu ?? false,
+ ...(notify?.wecomGroup === true ? { wecomGroup: true } : {}),
};
}
@@ -597,8 +599,12 @@ function optionalAgentKind(value: unknown): boolean {
function optionalNotify(value: unknown): boolean {
if (value === undefined) return true;
if (!value || typeof value !== 'object') return false;
- const notify = value as { desktop?: unknown; feishu?: unknown };
- return optionalBoolean(notify.desktop) && optionalBoolean(notify.feishu);
+ const notify = value as { desktop?: unknown; feishu?: unknown; wecomGroup?: unknown };
+ return (
+ optionalBoolean(notify.desktop) &&
+ optionalBoolean(notify.feishu) &&
+ optionalBoolean(notify.wecomGroup)
+ );
}
function isNodeError(err: unknown): err is NodeJS.ErrnoException {
diff --git a/apps/desktop/src/main/wecomGroupNotification.ts b/apps/desktop/src/main/wecomGroupNotification.ts
new file mode 100644
index 0000000000..dec40d8a21
--- /dev/null
+++ b/apps/desktop/src/main/wecomGroupNotification.ts
@@ -0,0 +1,244 @@
+import { ipcMain, net } from 'electron';
+
+import {
+ captureImAccountGeneration,
+ ImAccountScopeClosedError,
+ isImAccountGenerationCurrent,
+ runInImAccountGeneration,
+} from './im/accountBoundary';
+import { ownerScopedImSecrets } from './im/ownerScopedStorage';
+import { createLogger } from './logger';
+import { assertTrustedAppRendererEvent } from './security/trustedAppRenderer';
+
+const log = createLogger('wecom-group-notification');
+const WEBHOOK_SECRET_NAME = 'wecom-group-webhook-url';
+const WEBHOOK_HOST = 'qyapi.weixin.qq.com';
+const WEBHOOK_PATH = '/cgi-bin/webhook/send';
+const REQUEST_TIMEOUT_MS = 10_000;
+const MAX_RESPONSE_BYTES = 16 * 1024;
+const MAX_MARKDOWN_BYTES = 4_000;
+
+export interface WecomGroupNotificationState {
+ configured: boolean;
+ maskedKey?: string;
+}
+
+export interface WecomGroupNotificationPublisher {
+ publishMarkdown(markdown: string): Promise<void>;
+}
+
+type FetchLike = (input: string, init: RequestInit) => Promise<Response>;
+type SecretStore = Pick<typeof ownerScopedImSecrets, 'read' | 'write' | 'remove'>;
+
+function parseWebhookUrl(raw: string): URL {
+ const trimmed = raw.trim();
+ if (!trimmed || trimmed.length > 2_048) {
+ throw new Error('WECOM_GROUP_WEBHOOK_INVALID');
+ }
+
+ let url: URL;
+ try {
+ url = new URL(trimmed);
+ } catch {
+ throw new Error('WECOM_GROUP_WEBHOOK_INVALID');
+ }
+
+ const queryNames = [...url.searchParams.keys()];
+ const key = url.searchParams.get('key');
+ if (
+ url.protocol !== 'https:' ||
+ url.hostname !== WEBHOOK_HOST ||
+ url.port !== '' ||
+ url.pathname !== WEBHOOK_PATH ||
+ url.username !== '' ||
+ url.password !== '' ||
+ url.hash !== '' ||
+ queryNames.length !== 1 ||
+ queryNames[0] !== 'key' ||
+ !key ||
+ key.length > 256
+ ) {
+ throw new Error('WECOM_GROUP_WEBHOOK_INVALID');
+ }
+ return url;
+}
+
+function maskWebhookKey(url: URL): string {
+ const key = url.searchParams.get('key') ?? '';
+ return key.length <= 4 ? '••••' : `••••${key.slice(-4)}`;
+}
+
+function splitUtf8(text: string, maxBytes = MAX_MARKDOWN_BYTES): string[] {
+ const chunks: string[] = [];
+ let current = '';
+ let currentBytes = 0;
+
+ for (const char of text) {
+ const bytes = Buffer.byteLength(char, 'utf8');
+ if (current && currentBytes + bytes > maxBytes) {
+ chunks.push(current);
+ current = '';
+ currentBytes = 0;
+ }
+ current += char;
+ currentBytes += bytes;
+ }
+ if (current) chunks.push(current);
+ return chunks;
+}
+
+async function readResponseText(response: Response): Promise<string> {
+ const reader = response.body?.getReader();
+ if (!reader) return '';
+
+ const parts: Uint8Array[] = [];
+ let total = 0;
+ try {
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ if (!value) continue;
+ total += value.byteLength;
+ if (total > MAX_RESPONSE_BYTES) {
+ throw new Error('WECOM_GROUP_RESPONSE_TOO_LARGE');
+ }
+ parts.push(value);
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ return Buffer.concat(parts).toString('utf8');
+}
+
+export class WecomGroupNotificationService implements WecomGroupNotificationPublisher {
+ private publishTail: Promise<void> = Promise.resolve();
+
+ constructor(
+ private readonly fetchImpl: FetchLike = (input, init) => net.fetch(input, init),
+ private readonly secrets: SecretStore = ownerScopedImSecrets,
+ ) {}
+
+ getState(): WecomGroupNotificationState {
+ const stored = this.secrets.read(WEBHOOK_SECRET_NAME);
+ if (!stored) return { configured: false };
+ try {
+ return { configured: true, maskedKey: maskWebhookKey(parseWebhookUrl(stored)) };
+ } catch {
+ log.warn('stored webhook URL is invalid; treating it as unconfigured');
+ return { configured: false };
+ }
+ }
+
+ async saveAndTest(
+ rawUrl: string,
+ isAccountCurrent: () => boolean = () => true,
+ ): Promise<WecomGroupNotificationState> {
+ const url = parseWebhookUrl(rawUrl);
+ await this.enqueue(() => {
+ if (!isAccountCurrent()) throw new ImAccountScopeClosedError();
+ return this.send(url, 'Cindy 企业微信群通知测试成功');
+ });
+ if (!isAccountCurrent()) {
+ throw new ImAccountScopeClosedError();
+ }
+ if (!this.secrets.write(WEBHOOK_SECRET_NAME, url.toString())) {
+ throw new Error('WECOM_GROUP_WEBHOOK_SAVE_FAILED');
+ }
+ return { configured: true, maskedKey: maskWebhookKey(url) };
+ }
+
+ async test(): Promise<void> {
+ const url = this.requireStoredUrl();
+ await this.enqueue(() => this.send(url, 'Cindy 企业微信群通知测试成功'));
+ }
+
+ clear(): WecomGroupNotificationState {
+ this.secrets.remove(WEBHOOK_SECRET_NAME);
+ return { configured: false };
+ }
+
+ async publishMarkdown(markdown: string): Promise<void> {
+ return this.enqueue(async () => {
+ const url = this.requireStoredUrl();
+ const chunks = splitUtf8(markdown.trim() || 'Cindy 通知');
+ for (const chunk of chunks) {
+ await this.send(url, chunk);
+ }
+ });
+ }
+
+ private enqueue(operation: () => Promise<void>): Promise<void> {
+ const queued = this.publishTail
+ .catch(() => {
+ // A failed notification must not block later notifications.
+ })
+ .then(operation);
+ this.publishTail = queued;
+ return queued;
+ }
+
+ private requireStoredUrl(): URL {
+ const stored = this.secrets.read(WEBHOOK_SECRET_NAME);
+ if (!stored) throw new Error('WECOM_GROUP_WEBHOOK_NOT_CONFIGURED');
+ return parseWebhookUrl(stored);
+ }
+
+ private async send(url: URL, markdown: string): Promise<void> {
+ const response = await this.fetchImpl(url.toString(), {
+ method: 'POST',
+ headers: { 'content-type': 'application/json; charset=utf-8' },
+ body: JSON.stringify({ msgtype: 'markdown', markdown: { content: markdown } }),
+ redirect: 'manual',
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
+ });
+ if (response.status >= 300 && response.status < 400) {
+ throw new Error('WECOM_GROUP_REDIRECT_REJECTED');
+ }
+
+ const responseText = await readResponseText(response);
+ let result: { errcode?: unknown; errmsg?: unknown } = {};
+ try {
+ result = JSON.parse(responseText) as typeof result;
+ } catch {
+ throw new Error('WECOM_GROUP_RESPONSE_INVALID');
+ }
+ if (!response.ok || result.errcode !== 0) {
+ const code = typeof result.errcode === 'number' ? result.errcode : response.status;
+ throw new Error(`WECOM_GROUP_SEND_FAILED:${code}`);
+ }
+ }
+}
+
+export const wecomGroupNotificationService = new WecomGroupNotificationService();
+
+export function initWecomGroupNotificationIpc(): void {
+ ipcMain.handle('wecomGroupNotification:get-state', (event) => {
+ assertTrustedAppRendererEvent(event);
+ return wecomGroupNotificationService.getState();
+ });
+ ipcMain.handle('wecomGroupNotification:save-and-test', async (event, webhookUrl: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (typeof webhookUrl !== 'string') throw new TypeError('webhookUrl must be a string');
+ const accountGeneration = captureImAccountGeneration();
+ if (accountGeneration === null) throw new ImAccountScopeClosedError();
+ return runInImAccountGeneration(accountGeneration, () =>
+ wecomGroupNotificationService.saveAndTest(webhookUrl, () =>
+ isImAccountGenerationCurrent(accountGeneration),
+ ),
+ );
+ });
+ ipcMain.handle('wecomGroupNotification:test', async (event) => {
+ assertTrustedAppRendererEvent(event);
+ await wecomGroupNotificationService.test();
+ return { ok: true as const };
+ });
+ ipcMain.handle('wecomGroupNotification:clear', (event) => {
+ assertTrustedAppRendererEvent(event);
+ return wecomGroupNotificationService.clear();
+ });
+}
+
+export const __testing = {
+ parseWebhookUrl,
+ splitUtf8,
+};
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index a2b70c604d..75b4c947e7 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -394,6 +394,7 @@ const fanOutDiscordBotStatusChange = createIpcFanOut('discordBot:status-change')
const fanOutTelegramBotStatusChange = createIpcFanOut('telegramBot:status-change');
const fanOutDingTalkBotStatusChange = createIpcFanOut('dingtalkBot:status-change');
const fanOutDingTalkBotOwnerChange = createIpcFanOut('dingtalkBot:owner-change');
+const fanOutWecomBotStatusChange = createIpcFanOut('wecomBot:status-changed');
// Personal WeChat: main owns auth/polling and broadcasts a credential-free state snapshot.
const fanOutWechatBotStateChange = createIpcFanOut('wechatBot:state-changed');
const fanOutVoiceInputEvent = createIpcFanOut('voice-input:event');
@@ -1656,6 +1657,57 @@ contextBridge.exposeInMainWorld('electronAPI', {
onOwnerChange: fanOutDingTalkBotOwnerChange,
},
+ // ── WeCom intelligent bot (Settings → IM Bot → Personal) ──
+ wecomBot: {
+ getStatus: (): Promise<{
+ status:
+ | { kind: 'idle' }
+ | { kind: 'connecting' }
+ | { kind: 'connected'; appId: string }
+ | { kind: 'conflict'; appId: string }
+ | { kind: 'error'; reason: string };
+ botId: string | null;
+ ownerUserId: string | null;
+ }> => ipcRenderer.invoke('wecomBot:get-status'),
+ setConfig: (payload: { botId: string; secret: string }): Promise<{
+ status:
+ | { kind: 'idle' }
+ | { kind: 'connecting' }
+ | { kind: 'connected'; appId: string }
+ | { kind: 'conflict'; appId: string }
+ | { kind: 'error'; reason: string };
+ saveErrorStatus?:
+ | { kind: 'idle' }
+ | { kind: 'connecting' }
+ | { kind: 'connected'; appId: string }
+ | { kind: 'conflict'; appId: string }
+ | { kind: 'error'; reason: string };
+ botId: string | null;
+ ownerUserId: string | null;
+ }> => ipcRenderer.invoke('wecomBot:set-config', payload),
+ reconnect: (): Promise<{
+ status:
+ | { kind: 'idle' }
+ | { kind: 'connecting' }
+ | { kind: 'connected'; appId: string }
+ | { kind: 'conflict'; appId: string }
+ | { kind: 'error'; reason: string };
+ botId: string | null;
+ ownerUserId: string | null;
+ }> => ipcRenderer.invoke('wecomBot:reconnect'),
+ disconnect: (): Promise<{
+ status:
+ | { kind: 'idle' }
+ | { kind: 'connecting' }
+ | { kind: 'connected'; appId: string }
+ | { kind: 'conflict'; appId: string }
+ | { kind: 'error'; reason: string };
+ botId: string | null;
+ ownerUserId: string | null;
+ }> => ipcRenderer.invoke('wecomBot:disconnect'),
+ onStatusChange: fanOutWecomBotStatusChange,
+ },
+
// ── Personal WeChat (Settings → IM Bot → Personal) ──
// Renderer receives state only. Authorization URLs and credentials never
// cross preload; main opens the Tencent page in the system browser.
@@ -2564,11 +2616,20 @@ contextBridge.exposeInMainWorld('electronAPI', {
sessionId: string;
title: string;
kind: 'done' | 'error' | 'needs-reply';
- channels?: { desktop?: boolean; feishu?: boolean; mobile?: boolean };
+ channels?: { desktop?: boolean; feishu?: boolean; wecomGroup?: boolean; mobile?: boolean };
}): Promise<void> =>
ipcRenderer.invoke('notification:show-session-event', payload),
notificationSetDesktopEnabled: (enabled: boolean): Promise<{ ok: true }> =>
ipcRenderer.invoke('notification:set-desktop-enabled', enabled),
+ wecomGroupNotification: {
+ getState: (): Promise<{ configured: boolean; maskedKey?: string }> =>
+ ipcRenderer.invoke('wecomGroupNotification:get-state'),
+ saveAndTest: (webhookUrl: string): Promise<{ configured: boolean; maskedKey?: string }> =>
+ ipcRenderer.invoke('wecomGroupNotification:save-and-test', webhookUrl),
+ test: (): Promise<{ ok: true }> => ipcRenderer.invoke('wecomGroupNotification:test'),
+ clear: (): Promise<{ configured: boolean }> =>
+ ipcRenderer.invoke('wecomGroupNotification:clear'),
+ },
notificationMarkSessionAttention: (sessionId: string): Promise<void> =>
ipcRenderer.invoke('notification:mark-session-attention', sessionId),
// intent:'explicit' = 用户真实看到了内容(报错 banner 聚焦驻留 / 全部标为已读等);
diff --git a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
index 3154de6323..e70fbaf4d0 100644
--- a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
+++ b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
@@ -112,6 +112,7 @@ describe('automation-generated sessions', () => {
'discord',
'wechat',
'dingtalk',
+ 'wecom',
'scheduler',
'learn',
'shared',
@@ -130,6 +131,7 @@ describe('automation-generated sessions', () => {
expect(normalizeSessionSource('telegram')).toBe('telegram');
expect(normalizeSessionSource('discord')).toBe('discord');
expect(normalizeSessionSource('dingtalk')).toBe('dingtalk');
+ expect(normalizeSessionSource('wecom')).toBe('wecom');
expect(normalizeSessionSource('plugin')).toBe('plugin');
expect(normalizeSessionSource(null)).toBe('desktop');
expect(normalizeSessionSource('unknown')).toBe('desktop');
diff --git a/apps/desktop/src/renderer/__tests__/makerSharedFixtureParity.test.ts b/apps/desktop/src/renderer/__tests__/makerSharedFixtureParity.test.ts
index 7efc4e049d..e93716553d 100644
--- a/apps/desktop/src/renderer/__tests__/makerSharedFixtureParity.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerSharedFixtureParity.test.ts
@@ -82,6 +82,7 @@ function toDesktopScheduleFormState(schedule: RemoteSchedule): ScheduleFormState
preRunHookTimeoutSec: '',
notifyDesktop: schedule.notify?.desktop !== false,
notifyFeishu: schedule.notify?.feishu === true,
+ ...(schedule.notify?.wecomGroup === true ? { notifyWecomGroup: true } : {}),
};
}
diff --git a/apps/desktop/src/renderer/__tests__/schedulerTemplateEntry.test.ts b/apps/desktop/src/renderer/__tests__/schedulerTemplateEntry.test.ts
index a3e55e0ad3..446cf0bc2d 100644
--- a/apps/desktop/src/renderer/__tests__/schedulerTemplateEntry.test.ts
+++ b/apps/desktop/src/renderer/__tests__/schedulerTemplateEntry.test.ts
@@ -64,7 +64,8 @@ vi.mock('@radix-ui/react-dialog', async () => {
return {
Root: ({ open, children }: { open: boolean; children: ReactNode }) =>
React.createElement(DialogContext.Provider, { value: open }, open ? children : null),
- Portal: ({ children }: { children: ReactNode }) => React.createElement(React.Fragment, null, children),
+ Portal: ({ children }: { children: ReactNode }) =>
+ React.createElement(React.Fragment, null, children),
Overlay: (props: Record<string, unknown>) => React.createElement('div', props),
Content: ({
children,
@@ -95,7 +96,8 @@ vi.mock('@/components/ui/confirm-dialog-provider', () => ({
vi.mock('@/components/ui/tooltip', async () => {
const React = await import('react');
return {
- Tip: ({ children }: { children: ReactNode }) => React.createElement(React.Fragment, null, children),
+ Tip: ({ children }: { children: ReactNode }) =>
+ React.createElement(React.Fragment, null, children),
};
});
@@ -194,6 +196,12 @@ beforeEach(() => {
},
});
(window as unknown as { electronAPI: unknown }).electronAPI = {
+ wecomGroupNotification: {
+ getState: vi.fn(async () => ({ configured: false })),
+ saveAndTest: vi.fn(),
+ test: vi.fn(),
+ clear: vi.fn(),
+ },
maker: {
schedule: {
listTemplates: vi.fn(async () => [template]),
@@ -230,7 +238,9 @@ describe('Scheduler template entry', () => {
expect(screen.getByTestId('agent-kind').textContent).toBe('claude-code');
expect(screen.getByTestId('model-value').textContent).toBe('claude-sonnet-4-6');
- fireEvent.click(screen.getByRole('button', { name: 'scheduler.editor.promptDialog.createAria' }));
+ fireEvent.click(
+ screen.getByRole('button', { name: 'scheduler.editor.promptDialog.createAria' }),
+ );
await waitFor(() => expect(createSchedule).toHaveBeenCalledTimes(1));
expect(createSchedule).toHaveBeenCalledWith(
@@ -242,7 +252,7 @@ describe('Scheduler template entry', () => {
recurring: true,
agentKind: 'claude-code',
model: 'claude-sonnet-4-6',
- notify: { desktop: true, feishu: false },
+ notify: { desktop: true, feishu: false, wecomGroup: false },
}),
);
});
diff --git a/apps/desktop/src/renderer/components/settings/ImBotSection.tsx b/apps/desktop/src/renderer/components/settings/ImBotSection.tsx
index 25f67b447b..54e2f8a187 100644
--- a/apps/desktop/src/renderer/components/settings/ImBotSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ImBotSection.tsx
@@ -31,6 +31,7 @@ import { FeishuBotSection } from './FeishuBotSection';
import { HookConnectionsSection } from './HookConnectionsSection';
import { TelegramBotSection } from './TelegramBotSection';
import { WechatBotSection } from './WechatBotSection';
+import { WecomBotSection } from './WecomBotSection';
import {
showCindyGroup,
showDiscordBot,
@@ -73,16 +74,19 @@ function PersonalGroupContent({
showTelegram: boolean;
}) {
const [expandedChannel, setExpandedChannel] = useState<
- 'wechat' | 'feishu' | 'discord' | 'telegram' | 'dingtalk' | null
+ 'wechat' | 'wecom' | 'feishu' | 'discord' | 'telegram' | 'dingtalk' | null
>(null);
- const toggle = (channel: 'wechat' | 'feishu' | 'discord' | 'telegram' | 'dingtalk') => {
+ const toggle = (
+ channel: 'wechat' | 'wecom' | 'feishu' | 'discord' | 'telegram' | 'dingtalk',
+ ) => {
setExpandedChannel((current) => (current === channel ? null : channel));
};
return (
<div className="flex flex-col gap-3">
<WechatBotSection expanded={expandedChannel === 'wechat'} onToggle={() => toggle('wechat')} />
+ <WecomBotSection expanded={expandedChannel === 'wecom'} onToggle={() => toggle('wecom')} />
<FeishuBotSection
expanded={expandedChannel === 'feishu'}
onToggle={() => toggle('feishu')}
diff --git a/apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx b/apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx
index 60a6cc1d4b..cb4820c73e 100644
--- a/apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx
@@ -5,7 +5,11 @@
* 静默改写;非 thread 渠道通过 `/new` 显式应用。
*/
-import { connectedProvidersForAgent, getModel, isAgentSelectableModel } from '@cindy/model-providers';
+import {
+ connectedProvidersForAgent,
+ getModel,
+ isAgentSelectableModel,
+} from '@cindy/model-providers';
import { MessageSquare } from 'lucide-react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -30,7 +34,7 @@ import {
type ImDefaultSettingsState,
isImDefaultEffort,
isImDefaultPermissionMode,
- isWechatUnsupportedPermissionMode,
+ isRemoteImUnsupportedPermissionMode,
} from '../../../shared/imDefaultSettings';
import { DefaultOverrideControls } from './DefaultOverrideControls';
import { buildAgentSettingsPatch, mergeSettingsPatch } from './imDefaultSettingsLogic';
@@ -62,6 +66,8 @@ export function ImDefaultSettingsSection({
onSummaryChange?: (summary: ImDefaultSettingsSummary | null) => void;
}) {
const { t } = useTranslation();
+ const remotePermissionKey =
+ channel === 'wechat' ? 'settings.wechatBot.permission' : 'settings.imBot.remotePermission';
const { providers } = useProviders();
const cc = useAgentCapabilities('claude-code');
const codex = useAgentCapabilities('codex');
@@ -99,7 +105,9 @@ export function ImDefaultSettingsSection({
// 准入口径:IM 默认模型是「从零挑一个」的清单,停用的供应商/模型与能力模型
// 不该可选 —— 否则 headless runner 派发时才降级换模型,用户无感(PR #744 review)。
const fromProviders = {
- 'claude-code': deriveModelsFromProviders(providers, 'claude-code', { admissionFiltered: true }),
+ 'claude-code': deriveModelsFromProviders(providers, 'claude-code', {
+ admissionFiltered: true,
+ }),
codex: deriveModelsFromProviders(providers, 'codex', { admissionFiltered: true }),
};
return {
@@ -228,7 +236,7 @@ export function ImDefaultSettingsSection({
const changePermissionMode = (permissionMode: string) => {
if (
!isImDefaultPermissionMode(permissionMode) ||
- isWechatUnsupportedPermissionMode(permissionMode) ||
+ isRemoteImUnsupportedPermissionMode(channel, permissionMode) ||
permissionMode === settings.permissionMode
) {
return;
@@ -329,10 +337,10 @@ export function ImDefaultSettingsSection({
</div>
</div>
- {channel === 'wechat' && (
+ {(channel === 'wechat' || channel === 'wecom') && (
<div className="flex flex-col gap-2">
<span className="text-[12px] font-medium text-[var(--text-secondary)]">
- {t('settings.wechatBot.permission.label')}
+ {t(`${remotePermissionKey}.label`)}
</span>
<PermissionSelector
permissionMode={settings.permissionMode}
@@ -340,14 +348,14 @@ export function ImDefaultSettingsSection({
vendorKey={vendorKeyFor(settings.agentKind)}
disabled={pending}
triggerVariant="field"
- ariaContext={t('settings.wechatBot.permission.label')}
+ ariaContext={t(`${remotePermissionKey}.label`)}
disabledModes={{
- bypassPermissions: t('settings.wechatBot.permission.fullAccessDisabled'),
- acceptEdits: t('settings.wechatBot.permission.permissionModeDisabled'),
+ bypassPermissions: t(`${remotePermissionKey}.fullAccessDisabled`),
+ acceptEdits: t(`${remotePermissionKey}.permissionModeDisabled`),
}}
/>
<p className="text-[12px] leading-[1.5] text-[var(--settings-section-desc)]">
- {t('settings.wechatBot.permission.hint')}
+ {t(`${remotePermissionKey}.hint`)}
</p>
</div>
)}
diff --git a/apps/desktop/src/renderer/components/settings/NotificationSection.tsx b/apps/desktop/src/renderer/components/settings/NotificationSection.tsx
index 5fa0accc02..d66e34b25c 100644
--- a/apps/desktop/src/renderer/components/settings/NotificationSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/NotificationSection.tsx
@@ -11,14 +11,17 @@
* 沿用 AppearanceSection 的卡片样式(rounded 12 / Card bg / 1px Board / padding 20)。
*/
-import { useEffect } from 'react';
+import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { Loader2, Send, Trash2 } from 'lucide-react';
+import { toast } from '@/lib/toast';
import { Switch } from '@/components/ui/switch';
import { cn } from '@/lib/utils';
import { useNotificationSettings } from '@/hooks/useNotificationSettings';
import { useFeishuNotificationSettings } from '@/hooks/useFeishuNotificationSettings';
import { useFeishuBot } from '@/hooks/useFeishuBot';
+import { useWecomGroupNotificationSettings } from '@/hooks/useWecomGroupNotificationSettings';
export function NotificationSection() {
const { enabled, setEnabled } = useNotificationSettings();
@@ -26,6 +29,8 @@ export function NotificationSection() {
// ownerOpenId 才是 sendMarkdownText 的硬前置(status='connected' 也可能 owner 未绑),
// 用它作为飞书开关的可用门槛,与主进程实际兜底逻辑对齐。
const { ownerOpenId } = useFeishuBot();
+ const wecomGroup = useWecomGroupNotificationSettings();
+ const [webhookUrl, setWebhookUrl] = useState('');
const feishuReady = Boolean(ownerOpenId);
const { t } = useTranslation();
@@ -101,6 +106,124 @@ export function NotificationSection() {
aria-label={t('settings.notifications.feishuAria')}
/>
</div>
+
+ <div
+ className={cn(
+ 'flex flex-col gap-4 rounded-xl p-5',
+ 'bg-[var(--settings-theme-card-bg)]',
+ 'border border-[var(--settings-theme-card-border)]',
+ )}
+ >
+ <div className="flex items-center justify-between gap-3">
+ <div className="flex min-w-0 flex-col gap-1">
+ <p
+ className="text-13 font-medium text-[var(--settings-section-sublabel)]"
+ style={{ letterSpacing: '0.12px' }}
+ >
+ {t('settings.notifications.wecomGroupLabel')}
+ </p>
+ <p className="text-12 leading-[1.4] text-[var(--settings-section-sublabel)] opacity-70">
+ {wecomGroup.configured
+ ? t('settings.notifications.wecomGroupConfiguredHint', {
+ maskedKey: wecomGroup.maskedKey,
+ })
+ : t('settings.notifications.wecomGroupHint')}
+ </p>
+ </div>
+ <Switch
+ checked={wecomGroup.enabled && wecomGroup.configured}
+ onCheckedChange={wecomGroup.setEnabled}
+ disabled={!wecomGroup.configured || wecomGroup.loading}
+ aria-label={t('settings.notifications.wecomGroupAria')}
+ />
+ </div>
+
+ {wecomGroup.configured ? (
+ <div className="flex gap-2">
+ <button
+ type="button"
+ disabled={wecomGroup.busy}
+ onClick={() => {
+ void wecomGroup
+ .test()
+ .then(() => toast.success(t('settings.notifications.wecomGroupTestSuccess')))
+ .catch(() => toast.error(t('settings.notifications.wecomGroupTestFailed')));
+ }}
+ className={cn(
+ 'flex h-9 flex-1 items-center justify-center gap-1.5 rounded-full',
+ 'border border-[var(--settings-btn-secondary-border)]',
+ 'bg-[var(--settings-btn-secondary-bg)] text-12 font-medium',
+ 'text-[var(--settings-btn-secondary-text)]',
+ wecomGroup.busy && 'cursor-not-allowed opacity-40',
+ )}
+ >
+ {wecomGroup.busy ? <Loader2 size={13} className="animate-spin" /> : <Send size={13} />}
+ {t('settings.notifications.wecomGroupTest')}
+ </button>
+ <button
+ type="button"
+ disabled={wecomGroup.busy}
+ onClick={() => {
+ void wecomGroup
+ .clear()
+ .then(() => toast.success(t('settings.notifications.wecomGroupCleared')))
+ .catch(() => toast.error(t('settings.notifications.wecomGroupClearFailed')));
+ }}
+ className={cn(
+ 'flex h-9 flex-1 items-center justify-center gap-1.5 rounded-full',
+ 'border border-[var(--settings-btn-secondary-border)]',
+ 'bg-[var(--settings-btn-secondary-bg)] text-12 font-medium',
+ 'text-[var(--settings-btn-secondary-text)]',
+ wecomGroup.busy && 'cursor-not-allowed opacity-40',
+ )}
+ >
+ <Trash2 size={13} />
+ {t('settings.notifications.wecomGroupClear')}
+ </button>
+ </div>
+ ) : (
+ <div className="flex flex-col gap-2">
+ <input
+ type="password"
+ value={webhookUrl}
+ onChange={(event) => setWebhookUrl(event.target.value)}
+ placeholder={t('settings.notifications.wecomGroupPlaceholder')}
+ autoComplete="new-password"
+ spellCheck={false}
+ className={cn(
+ 'h-[42px] w-full rounded-full px-[14px]',
+ 'border border-[var(--settings-input-border)]',
+ 'bg-[var(--settings-input-bg)] text-13 text-[var(--settings-input-text)]',
+ 'placeholder:text-[var(--settings-input-placeholder)] outline-none',
+ 'focus:border-[var(--settings-input-border-focus)]',
+ )}
+ />
+ <button
+ type="button"
+ disabled={wecomGroup.busy || !webhookUrl.trim()}
+ onClick={() => {
+ void wecomGroup
+ .saveAndTest(webhookUrl)
+ .then(() => {
+ setWebhookUrl('');
+ toast.success(t('settings.notifications.wecomGroupSaveSuccess'));
+ })
+ .catch(() => toast.error(t('settings.notifications.wecomGroupSaveFailed')));
+ }}
+ className={cn(
+ 'flex h-[42px] items-center justify-center gap-1.5 rounded-full',
+ 'border border-[var(--settings-btn-primary-border)]',
+ 'bg-[var(--settings-btn-primary-bg)] text-13 font-medium',
+ 'text-[var(--settings-btn-primary-text)]',
+ (wecomGroup.busy || !webhookUrl.trim()) && 'cursor-not-allowed opacity-40',
+ )}
+ >
+ {wecomGroup.busy ? <Loader2 size={14} className="animate-spin" /> : <Send size={14} />}
+ {t('settings.notifications.wecomGroupSaveAndTest')}
+ </button>
+ </div>
+ )}
+ </div>
</div>
);
}
diff --git a/apps/desktop/src/renderer/components/settings/WecomBotSection.tsx b/apps/desktop/src/renderer/components/settings/WecomBotSection.tsx
new file mode 100644
index 0000000000..73b69d7e21
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/WecomBotSection.tsx
@@ -0,0 +1,253 @@
+import { useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Check, Eye, EyeOff, Loader2, Trash2 } from 'lucide-react';
+
+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
+import { useWecomBot } from '@/hooks/useWecomBot';
+import { cn } from '@/lib/utils';
+import { ImChannelSettingsCard, useImChannelSettingsSummary } from './ImChannelSettingsCard';
+import { ImDefaultSettingsSection } from './ImDefaultSettingsSection';
+
+const STATUS_KEY: Record<WecomBotTransportStatus['kind'], string> = {
+ idle: 'settings.wecomBot.status.needsConfig',
+ connecting: 'settings.wecomBot.status.connecting',
+ connected: 'settings.wecomBot.status.connected',
+ conflict: 'settings.wecomBot.status.conflict',
+ error: 'settings.wecomBot.status.error',
+};
+
+function statusColor(status: WecomBotTransportStatus): string {
+ switch (status.kind) {
+ case 'idle':
+ return 'var(--settings-badge-needs-config)';
+ case 'connecting':
+ case 'conflict':
+ return 'var(--settings-badge-saved)';
+ case 'connected':
+ return 'var(--settings-badge-connected)';
+ case 'error':
+ return 'var(--settings-badge-error)';
+ }
+}
+
+const fieldClassName = cn(
+ 'h-[42px] w-full rounded-full px-[14px]',
+ 'border border-[var(--settings-input-border)] bg-[var(--settings-input-bg)]',
+ 'text-13 text-[var(--settings-input-text)] placeholder:text-[var(--settings-input-placeholder)]',
+ 'outline-none transition-colors focus:border-[var(--settings-input-border-focus)]',
+);
+
+export function WecomBotSection({
+ expanded,
+ onToggle,
+}: {
+ expanded: boolean;
+ onToggle: () => void;
+}) {
+ const {
+ botId,
+ setBotId,
+ secret,
+ setSecret,
+ ownerUserId,
+ status,
+ validationError,
+ isSaving,
+ isDisconnecting,
+ canConnect,
+ canReconnect,
+ connect,
+ reconnect,
+ disconnect,
+ } = useWecomBot();
+ const [showSecret, setShowSecret] = useState(false);
+ const [routeSummary, setRouteSummary] = useImChannelSettingsSummary('wecom');
+ const { confirm } = useConfirmDialog();
+ const { t } = useTranslation();
+
+ const handleDisconnect = useCallback(async () => {
+ const approved = await confirm({
+ title: t('settings.wecomBot.disconnectConfirm.title'),
+ description: t('settings.wecomBot.disconnectConfirm.description'),
+ confirmText: t('settings.wecomBot.disconnectConfirm.confirm'),
+ cancelText: t('settings.wecomBot.disconnectConfirm.cancel'),
+ });
+ if (approved) await disconnect();
+ }, [confirm, disconnect, t]);
+
+ return (
+ <ImChannelSettingsCard
+ id="personal-im-wecom"
+ title={t('settings.wecomBot.title')}
+ description={t('settings.wecomBot.description')}
+ routeSummary={
+ routeSummary
+ ? `${t(`settings.imBot.defaults.agents.${routeSummary.agentKind}`)} · ${routeSummary.model}`
+ : null
+ }
+ expanded={expanded}
+ onToggle={onToggle}
+ status={
+ <span
+ className={cn(
+ 'inline-flex items-center gap-1.5 rounded-full',
+ 'border border-[var(--settings-badge-border)] bg-[var(--settings-badge-bg)]',
+ 'px-2.5 py-1 text-11 font-medium',
+ )}
+ style={{
+ color:
+ status.kind === 'connected'
+ ? 'var(--settings-badge-connected-text)'
+ : statusColor(status),
+ }}
+ role="status"
+ aria-live="polite"
+ >
+ <span
+ className="h-1.5 w-1.5 rounded-full"
+ style={{ backgroundColor: statusColor(status) }}
+ aria-hidden
+ />
+ {t(STATUS_KEY[status.kind])}
+ </span>
+ }
+ >
+ <ImDefaultSettingsSection channel="wecom" embedded onSummaryChange={setRouteSummary} />
+ <div className="h-px w-full bg-[var(--border-default)]" />
+
+ {status.kind === 'connected' ? (
+ <div
+ className={cn(
+ 'flex flex-col gap-3 rounded-xl p-5',
+ 'border border-[var(--settings-theme-card-border)]',
+ 'bg-[var(--settings-theme-card-bg)]',
+ )}
+ >
+ <div className="flex items-start gap-3">
+ <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-[var(--settings-badge-border)] bg-[var(--settings-badge-bg)] text-[var(--settings-badge-connected)]">
+ <Check size={16} />
+ </span>
+ <div>
+ <div className="text-13 font-medium text-[var(--settings-section-title)]">
+ {t('settings.wecomBot.connected.heading')}
+ </div>
+ <div className="mt-1 text-12 leading-[1.6] text-[var(--settings-section-desc)]">
+ {ownerUserId
+ ? t('settings.wecomBot.connected.ownerBound', { ownerUserId })
+ : t('settings.wecomBot.connected.awaitingOwner')}
+ </div>
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={() => void handleDisconnect()}
+ disabled={isDisconnecting}
+ className={cn(
+ 'flex h-[36px] items-center justify-center gap-1.5 rounded-full',
+ 'border border-[var(--settings-btn-secondary-border)] bg-[var(--settings-btn-secondary-bg)]',
+ 'text-12 font-medium text-[var(--settings-btn-secondary-text)]',
+ isDisconnecting && 'cursor-not-allowed opacity-40',
+ )}
+ >
+ {isDisconnecting ? (
+ <Loader2 size={13} className="animate-spin" />
+ ) : (
+ <Trash2 size={13} />
+ )}
+ {t('settings.wecomBot.disconnect')}
+ </button>
+ </div>
+ ) : (
+ <div className="flex flex-col gap-3">
+ <p className="text-12 leading-[1.6] text-[var(--settings-section-desc)]">
+ {t('settings.wecomBot.setupHint')}
+ </p>
+ <label className="text-12 font-medium text-[var(--settings-section-desc)]">
+ {t('settings.wecomBot.botIdLabel')}
+ </label>
+ <input
+ type="text"
+ value={botId}
+ onChange={(event) => setBotId(event.target.value)}
+ placeholder={t('settings.wecomBot.botIdPlaceholder')}
+ spellCheck={false}
+ autoComplete="off"
+ className={fieldClassName}
+ />
+ <label className="text-12 font-medium text-[var(--settings-section-desc)]">
+ {t('settings.wecomBot.secretLabel')}
+ </label>
+ <div className="relative">
+ <input
+ type={showSecret ? 'text' : 'password'}
+ value={secret}
+ onChange={(event) => setSecret(event.target.value)}
+ placeholder={t('settings.wecomBot.secretPlaceholder')}
+ spellCheck={false}
+ autoComplete="new-password"
+ className={cn(fieldClassName, 'pr-10')}
+ />
+ <button
+ type="button"
+ onClick={() => setShowSecret((shown) => !shown)}
+ className="absolute right-[14px] top-1/2 -translate-y-1/2 text-[var(--settings-eye-icon)] hover:text-[var(--settings-eye-icon-hover)]"
+ aria-label={
+ showSecret ? t('settings.wecomBot.hideSecret') : t('settings.wecomBot.showSecret')
+ }
+ >
+ {showSecret ? <Eye size={18} /> : <EyeOff size={18} />}
+ </button>
+ </div>
+ {validationError || status.kind === 'error' ? (
+ <p className="text-12 text-[var(--settings-error-text)]" role="alert">
+ {validationError ?? (status.kind === 'error' ? status.reason : '')}
+ </p>
+ ) : (
+ <p className="text-12 text-[var(--settings-source-meta)]">
+ {t('settings.wecomBot.ownerHint')}
+ </p>
+ )}
+ <div className="flex flex-col gap-2 sm:flex-row">
+ {botId.trim() && !secret.trim() ? (
+ <button
+ type="button"
+ onClick={() => void reconnect()}
+ disabled={!canReconnect}
+ className={cn(
+ 'flex h-[42px] flex-1 items-center justify-center gap-1.5 rounded-full',
+ 'border border-[var(--settings-btn-primary-border)] bg-[var(--settings-btn-primary-bg)]',
+ 'text-13 font-medium text-[var(--settings-btn-primary-text)]',
+ 'hover:bg-[var(--settings-btn-primary-hover-bg)]',
+ !canReconnect && 'cursor-not-allowed opacity-40',
+ )}
+ >
+ {isSaving ? <Loader2 size={14} className="animate-spin" /> : null}
+ {isSaving
+ ? t('settings.wecomBot.connectingAction')
+ : t('settings.wecomBot.reconnect')}
+ </button>
+ ) : (
+ <button
+ type="button"
+ onClick={() => void connect()}
+ disabled={!canConnect}
+ className={cn(
+ 'flex h-[42px] flex-1 items-center justify-center gap-1.5 rounded-full',
+ 'border border-[var(--settings-btn-primary-border)] bg-[var(--settings-btn-primary-bg)]',
+ 'text-13 font-medium text-[var(--settings-btn-primary-text)]',
+ 'hover:bg-[var(--settings-btn-primary-hover-bg)]',
+ !canConnect && 'cursor-not-allowed opacity-40',
+ )}
+ >
+ {isSaving ? <Loader2 size={14} className="animate-spin" /> : null}
+ {isSaving
+ ? t('settings.wecomBot.connectingAction')
+ : t('settings.wecomBot.connect')}
+ </button>
+ )}
+ </div>
+ </div>
+ )}
+ </ImChannelSettingsCard>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index e18284a20f..feb9e93d59 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -65,6 +65,7 @@ import { useAttachedSessionIds } from '@/hooks/useAttachedSessionIds';
import { useActiveMainView } from '@/hooks/useActiveMainView';
import { getNotificationsEnabled } from '@/hooks/useNotificationSettings';
import { getFeishuNotificationsEnabled } from '@/hooks/useFeishuNotificationSettings';
+import { getWecomGroupNotificationsEnabled } from '@/hooks/useWecomGroupNotificationSettings';
import { getAgentIslandEnabled, isAgentIslandSupported } from '@/hooks/useAgentIslandSettings';
import type { Session } from '@/lib/ccAgent.types';
import {
@@ -800,6 +801,7 @@ function ExpandedView({
const islandActive = isAgentIslandSupported() && getAgentIslandEnabled();
const desktopEnabled = getNotificationsEnabled() && !islandActive;
const feishuEnabled = getFeishuNotificationsEnabled();
+ const wecomGroupEnabled = getWecomGroupNotificationsEnabled();
// 失焦才推 —— 见上注释。
if (typeof document !== 'undefined' && document.hasFocus()) return;
const session = sessionsRef.current.find((s) => s.id === sessionId);
@@ -819,7 +821,12 @@ function ExpandedView({
sessionId,
title,
kind,
- channels: { desktop: desktopEnabled, feishu: feishuEnabled, mobile: true },
+ channels: {
+ desktop: desktopEnabled,
+ feishu: feishuEnabled,
+ wecomGroup: wecomGroupEnabled,
+ mobile: true,
+ },
});
}, []);
const handleSessionDone = useCallback(
diff --git a/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx b/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx
index 48f2ffd0b5..3cfa4d647f 100644
--- a/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx
+++ b/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx
@@ -15,6 +15,7 @@ import { sessionModelSupportsFastMode } from '@cindy/model-providers';
import type { UtilityTextAttemptReason, UtilityTextFailure } from '../../../../shared/utilityTextResult';
import { useFeishuBot } from '@/hooks/useFeishuBot';
import { useProjectPickerOptions } from '@/hooks/useProjectPickerOptions';
+import { useWecomGroupNotificationSettings } from '@/hooks/useWecomGroupNotificationSettings';
import type { Schedule, CreateScheduleInput, ScheduleTemplate, UpdateScheduleInput } from '@cindy/maker-scheduler';
import { applyTemplateParams } from '@cindy/maker-scheduler/template-engine';
import { ScriptCapabilityMultiSelect } from './ScriptCapabilityMultiSelect';
@@ -350,6 +351,7 @@ export function ScheduleFormDialog({
if (template.notify) {
setField('notifyDesktop', template.notify.desktop);
setField('notifyFeishu', template.notify.feishu);
+ setField('notifyWecomGroup', template.notify.wecomGroup === true);
}
const initParams: Record<string, string> = {};
for (const parameter of template.parameters ?? []) {
@@ -379,6 +381,7 @@ export function ScheduleFormDialog({
}, [selectedTemplate, paramValues, promptDirty, setField]);
const feishuBotReady = useFeishuBot().status === 'connected';
+ const wecomGroupReady = useWecomGroupNotificationSettings().configured;
const navigate = useNavigate();
const openReferencedSession = useCallback(
async (sessionId: string) => {
@@ -401,6 +404,10 @@ export function ScheduleFormDialog({
// 飞书机器人在「IM 机器人」页的「个人」分栏,缺省 imGroup 会落到默认的 Cindy 栏
navigate('/settings?tab=im-bot&imGroup=personal');
};
+ const goConfigWecomGroup = () => {
+ onOpenChange(false);
+ navigate('/settings?tab=general&section=notifications');
+ };
const projectOptions = useProjectPickerOptions();
@@ -938,6 +945,45 @@ export function ScheduleFormDialog({
{t('scheduler.editor.fields.configFeishu')}
</button>
)}
+ {wecomGroupReady ? (
+ <button
+ type="button"
+ role="checkbox"
+ aria-checked={form.notifyWecomGroup === true}
+ onClick={() => setField('notifyWecomGroup', form.notifyWecomGroup !== true)}
+ className={cn(
+ 'inline-flex h-[34px] items-center gap-2 rounded-md px-1.5',
+ 'text-13 leading-none text-[var(--settings-btn-secondary-text)]',
+ 'transition-colors hover:bg-[var(--surface-hover)] focus:outline-none',
+ )}
+ >
+ <span
+ className={cn(
+ 'inline-flex h-[14px] w-[14px] shrink-0 items-center justify-center rounded-[3px] border-[1.5px] transition-colors',
+ form.notifyWecomGroup
+ ? 'border-[var(--lightbox-cta-bg)] bg-[var(--lightbox-cta-bg)] text-[var(--lightbox-cta-fg)]'
+ : 'border-[var(--cmd-palette-item-meta)] bg-transparent dark:border-[var(--settings-section-desc)]',
+ )}
+ aria-hidden
+ >
+ {form.notifyWecomGroup && <Check size={10} strokeWidth={3} aria-hidden />}
+ </span>
+ {t('scheduler.editor.fields.finishSendToWecomGroup')}
+ </button>
+ ) : (
+ <button
+ type="button"
+ onClick={goConfigWecomGroup}
+ className={cn(
+ 'inline-flex h-[34px] items-center rounded-md px-2',
+ 'text-13 leading-none text-[var(--settings-btn-secondary-text)]',
+ 'transition-colors hover:bg-[var(--surface-hover)]',
+ 'focus:outline-none underline-offset-2 hover:underline',
+ )}
+ >
+ {t('scheduler.editor.fields.configWecomGroup')}
+ </button>
+ )}
</div>
{/* bound 态:单行会话选择器(换选即换绑,选择器旁带"打开会话")。
不再叠加绑定卡片 —— 标题在 select 里已可见,单独的"解除绑定"
diff --git a/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.ts b/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.ts
index ef0f6e55f6..1caa233f83 100644
--- a/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.ts
+++ b/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.ts
@@ -58,6 +58,7 @@ const DEFAULT_FORM: ScheduleFormState = {
preRunHookTimeoutSec: '',
notifyDesktop: true,
notifyFeishu: false,
+ notifyWecomGroup: false,
};
const SCHEDULE_FORM_PREFS_KEY = 'xdt:scheduleFormPrefs:v1';
@@ -244,6 +245,7 @@ export function makeFormFromSchedule(s: Schedule | null): ScheduleFormState {
: '',
notifyDesktop: s.notify.desktop,
notifyFeishu: s.notify.feishu,
+ notifyWecomGroup: s.notify.wecomGroup === true,
};
}
diff --git a/apps/desktop/src/renderer/features/scheduler/lib/projectAutomationConfig.ts b/apps/desktop/src/renderer/features/scheduler/lib/projectAutomationConfig.ts
index 9b2d3049db..3b890858bc 100644
--- a/apps/desktop/src/renderer/features/scheduler/lib/projectAutomationConfig.ts
+++ b/apps/desktop/src/renderer/features/scheduler/lib/projectAutomationConfig.ts
@@ -28,7 +28,7 @@ export interface ProjectScheduleConfig {
* ⚠️ 与 main 侧 project-automation-loader.ts 的 ProjectScheduleConfig 保持同形。
*/
preRunHook?: { command: string; timeoutMs?: number };
- notify?: { desktop?: boolean; feishu?: boolean };
+ notify?: { desktop?: boolean; feishu?: boolean; wecomGroup?: boolean };
}
export function generateProjectScheduleId(): string {
@@ -93,6 +93,10 @@ export function formToProjectConfig(
// 与 buildScheduleInput 同源:未启用为 undefined(JSON 序列化时省略该字段;
// 类型上抹掉 null——那是 update patch 的清空语义,config 文件里用"字段缺席"表达)
preRunHook: buildPreRunHook(form) ?? undefined,
- notify: { desktop: form.notifyDesktop, feishu: form.notifyFeishu },
+ notify: {
+ desktop: form.notifyDesktop,
+ feishu: form.notifyFeishu,
+ wecomGroup: form.notifyWecomGroup === true,
+ },
};
}
diff --git a/apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.ts b/apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.ts
index 434e0a16ac..be3477ce8e 100644
--- a/apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.ts
+++ b/apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.ts
@@ -120,6 +120,7 @@ export interface ScheduleFormState {
preRunHookTimeoutSec: string;
notifyDesktop: boolean;
notifyFeishu: boolean;
+ notifyWecomGroup?: boolean;
}
/** bound 态"已选绑定但尚未挑会话"的占位 id;validate 用 selectThread 拦截。 */
@@ -432,7 +433,11 @@ export function buildScheduleInput(form: ScheduleFormState): CreateScheduleInput
silentWhenIdle: !isScript && form.silentWhenIdle,
targetSessionId: !isScript ? (form.targetSessionId.trim() || undefined) : undefined,
preRunHook: buildPreRunHook(form),
- notify: { desktop: form.notifyDesktop, feishu: form.notifyFeishu },
+ notify: {
+ desktop: form.notifyDesktop,
+ feishu: form.notifyFeishu,
+ wecomGroup: form.notifyWecomGroup === true,
+ },
};
if (isScript) {
diff --git a/apps/desktop/src/renderer/hooks/useWecomBot.ts b/apps/desktop/src/renderer/hooks/useWecomBot.ts
new file mode 100644
index 0000000000..0e0a1d067a
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/useWecomBot.ts
@@ -0,0 +1,185 @@
+import { useCallback, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { createLogger } from '@/lib/logger';
+import { toast } from '@/lib/toast';
+
+const log = createLogger('useWecomBot');
+
+interface CachedState {
+ status: WecomBotTransportStatus;
+ botId: string;
+ ownerUserId: string;
+}
+
+let cachedState: CachedState | null = null;
+
+export function useWecomBot() {
+ const { t } = useTranslation();
+ const [botId, setBotId] = useState(() => cachedState?.botId ?? '');
+ const [secret, setSecret] = useState('');
+ const [ownerUserId, setOwnerUserId] = useState(() => cachedState?.ownerUserId ?? '');
+ const [status, setStatus] = useState<WecomBotTransportStatus>(
+ () => cachedState?.status ?? { kind: 'idle' },
+ );
+ const [isSaving, setIsSaving] = useState(false);
+ const [isDisconnecting, setIsDisconnecting] = useState(false);
+ const [validationError, setValidationError] = useState<string | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ void window.electronAPI.wecomBot
+ .getStatus()
+ .then((state) => {
+ if (cancelled) return;
+ const next = {
+ status: state.status,
+ botId: state.botId ?? '',
+ ownerUserId: state.ownerUserId ?? '',
+ };
+ cachedState = next;
+ setStatus(next.status);
+ setBotId(next.botId);
+ setOwnerUserId(next.ownerUserId);
+ })
+ .catch((error) => {
+ log.error('getStatus failed:', error instanceof Error ? error.message : String(error));
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ useEffect(
+ () =>
+ window.electronAPI.wecomBot.onStatusChange((state) => {
+ const next = {
+ status: state.status,
+ botId: state.botId ?? cachedState?.botId ?? '',
+ ownerUserId: state.ownerUserId ?? '',
+ };
+ cachedState = next;
+ setStatus(next.status);
+ setBotId(next.botId);
+ setOwnerUserId(next.ownerUserId);
+ }),
+ [],
+ );
+
+ const connect = useCallback(async () => {
+ if (isSaving) return false;
+ const nextBotId = botId.trim();
+ const nextSecret = secret.trim();
+ if (!nextBotId || !nextSecret) {
+ setValidationError(t('settings.wecomBot.fieldsRequired'));
+ return false;
+ }
+ setValidationError(null);
+ setIsSaving(true);
+ try {
+ const result = await window.electronAPI.wecomBot.setConfig({
+ botId: nextBotId,
+ secret: nextSecret,
+ });
+ const next = {
+ status: result.status,
+ botId: result.botId ?? nextBotId,
+ ownerUserId: result.ownerUserId ?? '',
+ };
+ cachedState = next;
+ setStatus(next.status);
+ setBotId(next.botId);
+ setOwnerUserId(next.ownerUserId);
+ setSecret('');
+ if (result.saveErrorStatus?.kind === 'error' || result.status.kind === 'error') {
+ toast.error(t('settings.wecomBot.connectFailed'));
+ return false;
+ }
+ toast.success(t('settings.wecomBot.configSaved'));
+ return true;
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ log.error('setConfig failed:', message);
+ toast.error(t('settings.wecomBot.saveFailed', { message }));
+ return false;
+ } finally {
+ setIsSaving(false);
+ }
+ }, [botId, isSaving, secret, t]);
+
+ const reconnect = useCallback(async () => {
+ if (isSaving || !botId.trim()) return false;
+ setValidationError(null);
+ setIsSaving(true);
+ try {
+ const result = await window.electronAPI.wecomBot.reconnect();
+ const next = {
+ status: result.status,
+ botId: result.botId ?? botId.trim(),
+ ownerUserId: result.ownerUserId ?? '',
+ };
+ cachedState = next;
+ setStatus(next.status);
+ setBotId(next.botId);
+ setOwnerUserId(next.ownerUserId);
+ if (result.status.kind === 'error') {
+ toast.error(t('settings.wecomBot.connectFailed'));
+ return false;
+ }
+ toast.success(t('settings.wecomBot.reconnecting'));
+ return true;
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ log.error('reconnect failed:', message);
+ toast.error(t('settings.wecomBot.reconnectFailed', { message }));
+ return false;
+ } finally {
+ setIsSaving(false);
+ }
+ }, [botId, isSaving, t]);
+
+ const disconnect = useCallback(async () => {
+ if (isDisconnecting) return;
+ setIsDisconnecting(true);
+ try {
+ const result = await window.electronAPI.wecomBot.disconnect();
+ const next = { status: result.status, botId: '', ownerUserId: '' };
+ cachedState = next;
+ setStatus(next.status);
+ setBotId('');
+ setSecret('');
+ setOwnerUserId('');
+ setValidationError(null);
+ toast.success(t('settings.wecomBot.disconnected'));
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ log.error('disconnect failed:', message);
+ toast.error(t('settings.wecomBot.disconnectFailed', { message }));
+ } finally {
+ setIsDisconnecting(false);
+ }
+ }, [isDisconnecting, t]);
+
+ return {
+ botId,
+ setBotId: (value: string) => {
+ setBotId(value);
+ setValidationError(null);
+ },
+ secret,
+ setSecret: (value: string) => {
+ setSecret(value);
+ setValidationError(null);
+ },
+ ownerUserId,
+ status,
+ validationError,
+ isSaving,
+ isDisconnecting,
+ canConnect: Boolean(botId.trim() && secret.trim() && !isSaving && !isDisconnecting),
+ canReconnect: Boolean(botId.trim() && !secret.trim() && !isSaving && !isDisconnecting),
+ connect,
+ reconnect,
+ disconnect,
+ };
+}
diff --git a/apps/desktop/src/renderer/hooks/useWecomGroupNotificationSettings.ts b/apps/desktop/src/renderer/hooks/useWecomGroupNotificationSettings.ts
new file mode 100644
index 0000000000..bc1fe68005
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/useWecomGroupNotificationSettings.ts
@@ -0,0 +1,107 @@
+import { useCallback, useEffect, useState } from 'react';
+
+const STORAGE_KEY = 'notifications.wecomGroupEnabled';
+const subscribers = new Set<() => void>();
+
+export function getWecomGroupNotificationsEnabled(): boolean {
+ try {
+ return localStorage.getItem(STORAGE_KEY) === 'true';
+ } catch {
+ return false;
+ }
+}
+
+export function setWecomGroupNotificationsEnabled(next: boolean): void {
+ try {
+ localStorage.setItem(STORAGE_KEY, String(next));
+ } catch {
+ // Keep the in-memory UI usable when localStorage is unavailable.
+ }
+ for (const subscriber of subscribers) subscriber();
+}
+
+export function useWecomGroupNotificationSettings() {
+ const [enabled, setEnabledState] = useState(getWecomGroupNotificationsEnabled);
+ const [configured, setConfigured] = useState(false);
+ const [maskedKey, setMaskedKey] = useState<string>();
+ const [loading, setLoading] = useState(true);
+ const [busy, setBusy] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ void window.electronAPI.wecomGroupNotification
+ .getState()
+ .then((state) => {
+ if (cancelled) return;
+ setConfigured(state.configured);
+ setMaskedKey(state.maskedKey);
+ if (!state.configured) setWecomGroupNotificationsEnabled(false);
+ })
+ .catch(() => {
+ if (!cancelled) {
+ setConfigured(false);
+ setWecomGroupNotificationsEnabled(false);
+ }
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ const onChange = () => setEnabledState(getWecomGroupNotificationsEnabled());
+ subscribers.add(onChange);
+ window.addEventListener('storage', onChange);
+ return () => {
+ cancelled = true;
+ subscribers.delete(onChange);
+ window.removeEventListener('storage', onChange);
+ };
+ }, []);
+
+ const setEnabled = useCallback((next: boolean) => {
+ setWecomGroupNotificationsEnabled(next);
+ }, []);
+
+ const saveAndTest = useCallback(async (webhookUrl: string) => {
+ setBusy(true);
+ try {
+ const state = await window.electronAPI.wecomGroupNotification.saveAndTest(webhookUrl);
+ setConfigured(state.configured);
+ setMaskedKey(state.maskedKey);
+ setWecomGroupNotificationsEnabled(true);
+ } finally {
+ setBusy(false);
+ }
+ }, []);
+
+ const test = useCallback(async () => {
+ setBusy(true);
+ try {
+ await window.electronAPI.wecomGroupNotification.test();
+ } finally {
+ setBusy(false);
+ }
+ }, []);
+
+ const clear = useCallback(async () => {
+ setBusy(true);
+ try {
+ await window.electronAPI.wecomGroupNotification.clear();
+ setConfigured(false);
+ setMaskedKey(undefined);
+ setWecomGroupNotificationsEnabled(false);
+ } finally {
+ setBusy(false);
+ }
+ }, []);
+
+ return {
+ enabled,
+ setEnabled,
+ configured,
+ maskedKey,
+ loading,
+ busy,
+ saveAndTest,
+ test,
+ clear,
+ };
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 45f9534a93..dbb62ff057 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -467,7 +467,21 @@
"feishuLabel": "Send a Feishu / Lark DM when a session finishes or needs a reply",
"feishuHint": "Sends a private message via the linked Feishu or Lark bot; only when the window is unfocused.",
"feishuDisabledHint": "First set up the bot in \"Feishu / Lark Bot\" and DM it once to complete binding.",
- "feishuAria": "Toggle session-done FeiShu notifications"
+ "feishuAria": "Toggle session-done FeiShu notifications",
+ "wecomGroupLabel": "Send notifications to a WeCom group",
+ "wecomGroupHint": "Paste a WeCom group bot Webhook URL. The URL is encrypted on this device and is never shown again.",
+ "wecomGroupConfiguredHint": "Configured (key {{maskedKey}}). Notifications are sent only while the window is unfocused.",
+ "wecomGroupAria": "Toggle WeCom group notifications",
+ "wecomGroupPlaceholder": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=…",
+ "wecomGroupSaveAndTest": "Save and test",
+ "wecomGroupSaveSuccess": "Webhook saved and test message sent",
+ "wecomGroupSaveFailed": "Could not save or test the Webhook",
+ "wecomGroupTest": "Send test",
+ "wecomGroupTestSuccess": "Test message sent",
+ "wecomGroupTestFailed": "Test message failed",
+ "wecomGroupClear": "Remove",
+ "wecomGroupCleared": "Webhook removed",
+ "wecomGroupClearFailed": "Could not remove the Webhook"
},
"windowBehavior": {
"title": "App Behavior",
@@ -1791,6 +1805,48 @@
}
}
},
+ "wecomBot": {
+ "title": "WeCom Intelligent Bot",
+ "description": "Connect a WeCom intelligent bot and use {{appName}} from direct and group chats.",
+ "status": {
+ "needsConfig": "Not configured",
+ "connecting": "Connecting…",
+ "connected": "Connected",
+ "conflict": "Connection replaced",
+ "error": "Connection failed"
+ },
+ "fieldsRequired": "Enter both the Bot ID and Secret",
+ "botIdLabel": "Bot ID",
+ "botIdPlaceholder": "Bot ID from WeCom administration",
+ "secretLabel": "Secret",
+ "secretPlaceholder": "Bot Secret from WeCom administration",
+ "showSecret": "Show Secret",
+ "hideSecret": "Hide Secret",
+ "setupHint": "Create an intelligent bot in WeCom administration, enable long connection, then enter its Bot ID and Secret.",
+ "ownerHint": "After connecting, the first member to DM the bot becomes this computer's owner. Only that member can trigger the Agent.",
+ "connect": "Save and connect",
+ "reconnect": "Reconnect",
+ "connectingAction": "Connecting…",
+ "disconnect": "Unbind",
+ "configSaved": "WeCom bot configuration saved",
+ "connectFailed": "WeCom bot connection failed; check the credentials and network",
+ "reconnecting": "Reconnecting the WeCom bot",
+ "reconnectFailed": "Reconnect failed: {{message}}",
+ "saveFailed": "Save failed: {{message}}",
+ "disconnected": "WeCom bot unbound",
+ "disconnectFailed": "Unbind failed: {{message}}",
+ "connected": {
+ "heading": "WeCom bot connected",
+ "awaitingOwner": "Send the bot a direct message from your WeCom account to bind the owner.",
+ "ownerBound": "Owner on this computer: {{ownerUserId}}"
+ },
+ "disconnectConfirm": {
+ "title": "Unbind the WeCom bot?",
+ "description": "The saved Bot ID, Secret, and owner binding will be removed from this computer.",
+ "confirm": "Unbind",
+ "cancel": "Cancel"
+ }
+ },
"telegramBot": {
"title": "Telegram Bot",
"description": "Connect your own Telegram bot. The desktop connects to Telegram directly, so {{appName}} works from DMs and group chats.",
@@ -2711,8 +2767,8 @@
},
"tips": {
"cindy": "Cindy is the official shared bot — no credentials needed. Connect Slack and just @Cindy to hand off tasks.",
- "personal": "Personal connections include WeChat scan authorization and your own Feishu / Discord / Telegram credentials. Each channel keeps independent new-conversation settings.",
- "personalFeishuOnly": "Personal connections include WeChat scan authorization plus your own Feishu and DingTalk credentials. Each channel keeps independent new-conversation settings."
+ "personal": "Personal connections include WeChat scan authorization and your own WeCom / Feishu / Discord / Telegram credentials. Each channel keeps independent new-conversation settings.",
+ "personalFeishuOnly": "Personal connections include WeChat scan authorization plus your own WeCom, Feishu, and DingTalk credentials. Each channel keeps independent new-conversation settings."
},
"defaults": {
"title": "New Conversation Configuration",
@@ -2722,7 +2778,8 @@
"discord": "New Discord conversations use this Agent and model. Send /new in an existing DM to apply it.",
"wechat": "New WeChat conversations use this Agent, model, and permission mode. Send /new in an existing chat to apply them.",
"telegram": "New Telegram conversations use this Agent and model. Send /new in an existing conversation to apply it.",
- "dingtalk": "New DingTalk conversations use this Agent and model. Send /new in an existing conversation to apply it."
+ "dingtalk": "New DingTalk conversations use this Agent and model. Send /new in an existing conversation to apply it.",
+ "wecom": "New WeCom conversations use this Agent, model, and permission mode. Send /new in an existing chat to apply them."
},
"agentLabel": "Agent",
"modelLabel": "Model Configuration",
@@ -3455,6 +3512,12 @@
"mailPrompt": "Help me build my Smart Contacts from email: first check which mail tools I have connected (if none, tell me how to connect one); scan the last 6 months of correspondence and create profiles for real contacts I exchange mail with — confirm high-frequency, clearly-identified people directly, use pending for uncertain ones; skip marketing mail, notification bots, and one-off senders. Report which profiles you created at the end.",
"imPrompt": "Help me build my Smart Contacts from chat tools: first check which IMs I have connected (Feishu / Slack / WeChat etc.; if none, tell me how to connect one); organize the people I chat with regularly into contacts, use pending for uncertain ones, and skip group bots and one-off conversations. Report which profiles you created at the end."
}
+ },
+ "remotePermission": {
+ "label": "Permission mode",
+ "hint": "Remote IM keeps confirmation enabled for actions that need approval.",
+ "fullAccessDisabled": "Full Access is unavailable for remote IM because actions that cannot be safely confirmed must not run directly.",
+ "permissionModeDisabled": "This permission mode is unavailable because remote IM uses Cindy Desktop's confirmation policy."
}
},
"remoteDevice": {
@@ -6598,6 +6661,8 @@
"silentRunTooltip": "When enabled, successful runs do not notify by default. If the task prompt asks to notify under specific conditions, AI will report when those conditions are met. Failures and errors still notify.",
"silentRunInfoAria": "View silent run rules",
"finishSendToFeishu": "Finish Send To FeishuBot",
+ "finishSendToWecomGroup": "Send result to WeCom group",
+ "configWecomGroup": "Configure WeCom group notifications",
"configFeishu": "Config FeishuBot"
},
"runSession": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index e40f46bdf2..cd14a59bc8 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -467,7 +467,21 @@
"feishuLabel": "セッション完了または返信が必要な時に Feishu / Lark メッセージを送信",
"feishuHint": "連携済みの Feishu または Lark ボットからプライベートメッセージを送信します。ウィンドウが非アクティブの場合のみ送信。",
"feishuDisabledHint": "先に「Feishu / Lark ボット」で設定し、ボットに 1 度メッセージを送ってバインドを完了してください。",
- "feishuAria": "セッション完了時の Feishu 通知を切り替え"
+ "feishuAria": "セッション完了時の Feishu 通知を切り替え",
+ "wecomGroupLabel": "WeCom グループに通知を送信",
+ "wecomGroupHint": "WeCom グループボットの Webhook URL を貼り付けます。URL はこのデバイスに暗号化保存され、再表示されません。",
+ "wecomGroupConfiguredHint": "設定済み(キー {{maskedKey}})。ウィンドウが非アクティブの場合のみ送信します。",
+ "wecomGroupAria": "WeCom グループ通知を切り替え",
+ "wecomGroupPlaceholder": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=…",
+ "wecomGroupSaveAndTest": "保存してテスト",
+ "wecomGroupSaveSuccess": "Webhook を保存し、テストメッセージを送信しました",
+ "wecomGroupSaveFailed": "Webhook の保存またはテストに失敗しました",
+ "wecomGroupTest": "テスト送信",
+ "wecomGroupTestSuccess": "テストメッセージを送信しました",
+ "wecomGroupTestFailed": "テストメッセージの送信に失敗しました",
+ "wecomGroupClear": "削除",
+ "wecomGroupCleared": "Webhook を削除しました",
+ "wecomGroupClearFailed": "Webhook を削除できませんでした"
},
"windowBehavior": {
"title": "アプリの動作",
@@ -1790,6 +1804,48 @@
}
}
},
+ "wecomBot": {
+ "title": "WeCom インテリジェントボット",
+ "description": "WeCom インテリジェントボットを接続し、DM とグループチャットから {{appName}} を利用します。",
+ "status": {
+ "needsConfig": "未設定",
+ "connecting": "接続中…",
+ "connected": "接続済み",
+ "conflict": "接続が置き換えられました",
+ "error": "接続失敗"
+ },
+ "fieldsRequired": "Bot ID と Secret を入力してください",
+ "botIdLabel": "Bot ID",
+ "botIdPlaceholder": "WeCom 管理画面の Bot ID",
+ "secretLabel": "Secret",
+ "secretPlaceholder": "WeCom 管理画面の Secret",
+ "showSecret": "Secret を表示",
+ "hideSecret": "Secret を隠す",
+ "setupHint": "WeCom 管理画面でインテリジェントボットを作成し、長時間接続を有効にしてから Bot ID と Secret を入力します。",
+ "ownerHint": "接続後、最初にボットへ DM を送ったメンバーがこのコンピューターの owner になります。そのメンバーだけが Agent を起動できます。",
+ "connect": "保存して接続",
+ "reconnect": "再接続",
+ "connectingAction": "接続中…",
+ "disconnect": "連携解除",
+ "configSaved": "WeCom ボット設定を保存しました",
+ "connectFailed": "WeCom ボットに接続できません。認証情報とネットワークを確認してください",
+ "reconnecting": "WeCom ボットに再接続しています",
+ "reconnectFailed": "再接続に失敗しました:{{message}}",
+ "saveFailed": "保存失敗:{{message}}",
+ "disconnected": "WeCom ボットの連携を解除しました",
+ "disconnectFailed": "連携解除に失敗しました:{{message}}",
+ "connected": {
+ "heading": "WeCom ボット接続済み",
+ "awaitingOwner": "WeCom アカウントからボットへ DM を送り、owner を設定してください。",
+ "ownerBound": "このコンピューターの owner:{{ownerUserId}}"
+ },
+ "disconnectConfirm": {
+ "title": "WeCom ボットの連携を解除しますか?",
+ "description": "保存済みの Bot ID、Secret、owner の紐付けをこのコンピューターから削除します。",
+ "confirm": "連携解除",
+ "cancel": "キャンセル"
+ }
+ },
"telegramBot": {
"title": "Telegram ボット",
"description": "自分で作成した Telegram ボットを連携します。デスクトップが Telegram に直接接続し、DM でもグループでも {{appName}} を使えます。",
@@ -2710,8 +2766,8 @@
},
"tips": {
"cindy": "Cindy は公式提供の共有ボットです。認証情報の申請は不要で、Slack を連携して @Cindy にメンションするだけでタスクを任せられます。",
- "personal": "個人接続には WeChat のスキャン認証と、自分の Feishu / Discord / Telegram 認証情報を使用する接続があります。新規会話設定はチャネルごとに保存されます。",
- "personalFeishuOnly": "個人接続には WeChat のスキャン認証と、自分の Feishu / DingTalk 認証情報を使用する接続があります。新規会話設定はチャネルごとに保存されます。"
+ "personal": "個人接続には WeChat のスキャン認証と、自分の WeCom / Feishu / Discord / Telegram 認証情報を使用する接続があります。新規会話設定はチャネルごとに保存されます。",
+ "personalFeishuOnly": "個人接続には WeChat のスキャン認証と、自分の WeCom / Feishu / DingTalk 認証情報を使用する接続があります。新規会話設定はチャネルごとに保存されます。"
},
"defaults": {
"title": "新規会話設定",
@@ -2721,7 +2777,8 @@
"discord": "Discord の新規会話では、この Agent とモデルを使用します。既存の DM には /new で適用します。",
"wechat": "WeChat の新規会話では、この Agent・モデル・権限モードを使用します。既存のチャットには /new で適用します。",
"telegram": "Telegram の新規会話では、この Agent とモデルを使用します。既存の会話には /new で適用します。",
- "dingtalk": "DingTalk の新規会話では、この Agent とモデルを使用します。既存の会話には /new で適用します。"
+ "dingtalk": "DingTalk の新規会話では、この Agent とモデルを使用します。既存の会話には /new で適用します。",
+ "wecom": "WeCom の新規会話では、この Agent・モデル・権限モードを使用します。既存のチャットには /new で適用します。"
},
"agentLabel": "Agent",
"modelLabel": "モデル設定",
@@ -3453,6 +3510,12 @@
"mailPrompt": "メールからスマート連絡先を作成してください:まず接続済みのメールツールを確認し(なければ接続方法を教えてください)、直近 6 か月のやり取りをスキャンして、双方向のやり取りがある実在の連絡先を登録してください——頻度が高く身元が明確な人は確定で、不確かな人は pending で。マーケティングメール、通知ボット、一度きりの送信者はスキップ。最後に作成した項目を報告してください。",
"imPrompt": "チャットツールからスマート連絡先を作成してください:まず接続済みの IM(Feishu / Slack / WeChat など)を確認し(なければ接続方法を教えてください)、最近よく会話する相手を連絡先に整理してください。不確かな人は pending で、グループボットや一時的な会話はスキップ。最後に作成した項目を報告してください。"
}
+ },
+ "remotePermission": {
+ "label": "権限モード",
+ "hint": "リモート IM では、承認が必要な操作の確認フローを維持します。",
+ "fullAccessDisabled": "安全に確認できない操作が直接実行されないよう、リモート IM では Full Access を利用できません。",
+ "permissionModeDisabled": "リモート IM は Cindy Desktop の確認ポリシーを使用するため、この権限モードは利用できません。"
}
},
"remoteDevice": {
@@ -6587,6 +6650,8 @@
"silentRunTooltip": "オンにすると、正常完了時はデフォルトで通知しません。タスク説明で特定条件の通知を求めている場合、AI が条件を満たしたときに自動で上報します。失敗や異常は引き続き通知されます。",
"silentRunInfoAria": "サイレント実行のルールを表示",
"finishSendToFeishu": "完了時に Feishu Bot に送信",
+ "finishSendToWecomGroup": "完了時に WeCom グループへ送信",
+ "configWecomGroup": "WeCom グループ通知を設定",
"configFeishu": "Feishu Bot を設定"
},
"runSession": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index f02f62154d..597dcb36d7 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -467,7 +467,21 @@
"feishuLabel": "세션 완료 또는 응답 필요 시 Feishu / Lark 메시지 전송",
"feishuHint": "연동된 Feishu 또는 Lark 봇을 통해 개인 메시지를 보냅니다. 창이 비활성 상태일 때만 전송됩니다.",
"feishuDisabledHint": "먼저 \"Feishu / Lark 봇\"에서 봇을 설정하고 한 번 메시지를 보내 바인딩을 완료하세요.",
- "feishuAria": "세션 완료 Feishu 알림 전환"
+ "feishuAria": "세션 완료 Feishu 알림 전환",
+ "wecomGroupLabel": "WeCom 그룹으로 알림 보내기",
+ "wecomGroupHint": "WeCom 그룹 봇 Webhook URL을 붙여넣으세요. URL은 이 기기에 암호화되어 저장되며 다시 표시되지 않습니다.",
+ "wecomGroupConfiguredHint": "설정됨(키 {{maskedKey}}). 창이 비활성 상태일 때만 알림을 보냅니다.",
+ "wecomGroupAria": "WeCom 그룹 알림 전환",
+ "wecomGroupPlaceholder": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=…",
+ "wecomGroupSaveAndTest": "저장 및 테스트",
+ "wecomGroupSaveSuccess": "Webhook을 저장하고 테스트 메시지를 보냈습니다",
+ "wecomGroupSaveFailed": "Webhook 저장 또는 테스트에 실패했습니다",
+ "wecomGroupTest": "테스트 전송",
+ "wecomGroupTestSuccess": "테스트 메시지를 보냈습니다",
+ "wecomGroupTestFailed": "테스트 메시지 전송에 실패했습니다",
+ "wecomGroupClear": "삭제",
+ "wecomGroupCleared": "Webhook을 삭제했습니다",
+ "wecomGroupClearFailed": "Webhook을 삭제하지 못했습니다"
},
"windowBehavior": {
"title": "앱 동작",
@@ -1790,6 +1804,48 @@
}
}
},
+ "wecomBot": {
+ "title": "WeCom 지능형 봇",
+ "description": "WeCom 지능형 봇을 연결하고 DM과 그룹 채팅에서 {{appName}}를 사용하세요.",
+ "status": {
+ "needsConfig": "설정되지 않음",
+ "connecting": "연결 중…",
+ "connected": "연결됨",
+ "conflict": "연결이 대체됨",
+ "error": "연결 실패"
+ },
+ "fieldsRequired": "Bot ID와 Secret을 모두 입력하세요",
+ "botIdLabel": "Bot ID",
+ "botIdPlaceholder": "WeCom 관리 화면의 Bot ID",
+ "secretLabel": "Secret",
+ "secretPlaceholder": "WeCom 관리 화면의 Secret",
+ "showSecret": "Secret 표시",
+ "hideSecret": "Secret 숨기기",
+ "setupHint": "WeCom 관리 화면에서 지능형 봇을 만들고 장기 연결을 활성화한 다음 Bot ID와 Secret을 입력하세요.",
+ "ownerHint": "연결 후 봇에 처음 DM을 보낸 구성원이 이 컴퓨터의 owner로 연결됩니다. 해당 구성원만 Agent를 실행할 수 있습니다.",
+ "connect": "저장하고 연결",
+ "reconnect": "다시 연결",
+ "connectingAction": "연결 중…",
+ "disconnect": "연결 해제",
+ "configSaved": "WeCom 봇 설정을 저장했습니다",
+ "connectFailed": "WeCom 봇 연결에 실패했습니다. 자격 증명과 네트워크를 확인하세요",
+ "reconnecting": "WeCom 봇에 다시 연결하는 중입니다",
+ "reconnectFailed": "다시 연결하지 못했습니다: {{message}}",
+ "saveFailed": "저장 실패: {{message}}",
+ "disconnected": "WeCom 봇 연결을 해제했습니다",
+ "disconnectFailed": "연결 해제 실패: {{message}}",
+ "connected": {
+ "heading": "WeCom 봇 연결됨",
+ "awaitingOwner": "WeCom 계정에서 봇으로 DM을 보내 owner를 연결하세요.",
+ "ownerBound": "이 컴퓨터의 owner: {{ownerUserId}}"
+ },
+ "disconnectConfirm": {
+ "title": "WeCom 봇 연결을 해제할까요?",
+ "description": "저장된 Bot ID, Secret 및 owner 연결이 이 컴퓨터에서 삭제됩니다.",
+ "confirm": "연결 해제",
+ "cancel": "취소"
+ }
+ },
"telegramBot": {
"title": "Telegram 봇",
"description": "직접 만든 Telegram 봇을 연결하세요. 데스크톱이 Telegram에 직접 연결되어 DM과 그룹 채팅에서 {{appName}}를 사용할 수 있습니다.",
@@ -2710,8 +2766,8 @@
},
"tips": {
"cindy": "Cindy는 공식 제공 공유 봇입니다. 자격 증명을 신청할 필요 없이 Slack을 연결하고 @Cindy를 멘션하면 바로 작업을 맡길 수 있습니다.",
- "personal": "개인 연결에는 WeChat 스캔 인증과 직접 발급한 Feishu / Discord / Telegram 인증 정보 연결이 포함됩니다. 새 대화 설정은 채널별로 저장됩니다.",
- "personalFeishuOnly": "개인 연결에는 WeChat 스캔 인증과 직접 발급한 Feishu 및 DingTalk 자격 증명 연결이 포함됩니다. 새 대화 설정은 채널별로 저장됩니다."
+ "personal": "개인 연결에는 WeChat 스캔 인증과 직접 발급한 WeCom / Feishu / Discord / Telegram 인증 정보 연결이 포함됩니다. 새 대화 설정은 채널별로 저장됩니다.",
+ "personalFeishuOnly": "개인 연결에는 WeChat 스캔 인증과 직접 발급한 WeCom, Feishu 및 DingTalk 자격 증명 연결이 포함됩니다. 새 대화 설정은 채널별로 저장됩니다."
},
"defaults": {
"title": "새 대화 설정",
@@ -2721,7 +2777,8 @@
"discord": "새 Discord 대화는 이 Agent와 모델을 사용합니다. 기존 DM에는 /new를 보내 적용하세요.",
"wechat": "새 WeChat 대화는 이 Agent, 모델, 권한 모드를 사용합니다. 기존 채팅에는 /new를 보내 적용하세요.",
"telegram": "새 Telegram 대화는 이 Agent와 모델을 사용합니다. 기존 대화에는 /new를 보내 적용하세요.",
- "dingtalk": "새 DingTalk 대화는 이 Agent와 모델을 사용합니다. 기존 대화에는 /new를 보내 적용하세요."
+ "dingtalk": "새 DingTalk 대화는 이 Agent와 모델을 사용합니다. 기존 대화에는 /new를 보내 적용하세요.",
+ "wecom": "새 WeCom 대화는 이 Agent, 모델, 권한 모드를 사용합니다. 기존 채팅에는 /new를 보내 적용하세요."
},
"agentLabel": "Agent",
"modelLabel": "모델 설정",
@@ -3453,6 +3510,12 @@
"mailPrompt": "이메일에서 스마트 연락처를 만들어 주세요: 먼저 연결된 메일 도구를 확인하고(없다면 연결 방법을 알려 주세요), 최근 6개월간의 주고받은 메일을 스캔해 실제로 왕래하는 연락처를 등록해 주세요 — 빈도가 높고 신원이 명확한 사람은 바로 확정, 불확실한 사람은 pending으로. 마케팅 메일, 알림 봇, 일회성 발신자는 건너뜁니다. 마지막에 어떤 프로필을 만들었는지 보고해 주세요.",
"imPrompt": "채팅 도구에서 스마트 연락처를 만들어 주세요: 먼저 연결된 IM(Feishu / Slack / WeChat 등)을 확인하고(없다면 연결 방법을 알려 주세요), 최근 자주 대화하는 사람들을 연락처로 정리해 주세요. 불확실한 사람은 pending으로, 그룹 봇과 일회성 대화는 건너뜁니다. 마지막에 어떤 프로필을 만들었는지 보고해 주세요."
}
+ },
+ "remotePermission": {
+ "label": "권한 모드",
+ "hint": "원격 IM은 승인이 필요한 작업의 확인 절차를 유지합니다.",
+ "fullAccessDisabled": "안전하게 확인할 수 없는 작업이 직접 실행되지 않도록 원격 IM에서는 Full Access를 사용할 수 없습니다.",
+ "permissionModeDisabled": "원격 IM은 Cindy Desktop의 확인 정책을 사용하므로 이 권한 모드를 사용할 수 없습니다."
}
},
"remoteDevice": {
@@ -6587,6 +6650,8 @@
"silentRunTooltip": "켜면 작업이 성공적으로 완료되어도 기본적으로 알림을 보내지 않습니다. 작업 프롬프트에서 특정 조건에 알림을 요청한 경우, AI가 조건이 충족될 때 직접 보고합니다. 실패와 오류는 계속 알림을 보냅니다.",
"silentRunInfoAria": "조용히 실행 규칙 보기",
"finishSendToFeishu": "완료 시 Feishu Bot에 전송",
+ "finishSendToWecomGroup": "완료 시 WeCom 그룹으로 전송",
+ "configWecomGroup": "WeCom 그룹 알림 설정",
"configFeishu": "Feishu Bot 설정"
},
"runSession": {
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 64f23587b3..1e2f57a4a8 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -467,7 +467,21 @@
"feishuLabel": "任务完成或需要回复时发送飞书 / Lark 消息",
"feishuHint": "通过已绑定的飞书或 Lark 机器人,向你私聊发送一条消息;仅在窗口失焦时发送。",
"feishuDisabledHint": "需要先在「飞书 / Lark 机器人」中配置 bot 并向它发送一条消息以完成绑定。",
- "feishuAria": "切换任务完成的飞书通知"
+ "feishuAria": "切换任务完成的飞书通知",
+ "wecomGroupLabel": "发送通知到企业微信群",
+ "wecomGroupHint": "粘贴企微群机器人的 Webhook URL。URL 会加密保存在本机,保存后不再显示。",
+ "wecomGroupConfiguredHint": "已配置(密钥 {{maskedKey}})。仅在窗口失焦时发送通知。",
+ "wecomGroupAria": "切换企微群通知",
+ "wecomGroupPlaceholder": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=…",
+ "wecomGroupSaveAndTest": "保存并测试",
+ "wecomGroupSaveSuccess": "Webhook 已保存,测试消息已发送",
+ "wecomGroupSaveFailed": "Webhook 保存或测试失败",
+ "wecomGroupTest": "发送测试",
+ "wecomGroupTestSuccess": "测试消息已发送",
+ "wecomGroupTestFailed": "测试消息发送失败",
+ "wecomGroupClear": "移除",
+ "wecomGroupCleared": "Webhook 已移除",
+ "wecomGroupClearFailed": "Webhook 移除失败"
},
"windowBehavior": {
"title": "应用行为",
@@ -1790,6 +1804,48 @@
}
}
},
+ "wecomBot": {
+ "title": "企业微信智能机器人",
+ "description": "连接企业微信智能机器人,在单聊和群聊中使用 {{appName}}。",
+ "status": {
+ "needsConfig": "未配置",
+ "connecting": "连接中…",
+ "connected": "已连接",
+ "conflict": "连接被替换",
+ "error": "连接失败"
+ },
+ "fieldsRequired": "请输入 Bot ID 和 Secret",
+ "botIdLabel": "Bot ID",
+ "botIdPlaceholder": "企业微信后台中的机器人 ID",
+ "secretLabel": "Secret",
+ "secretPlaceholder": "企业微信后台中的机器人 Secret",
+ "showSecret": "显示 Secret",
+ "hideSecret": "隐藏 Secret",
+ "setupHint": "在企业微信管理后台创建智能机器人并启用长连接,然后填入 Bot ID 和 Secret。",
+ "ownerHint": "连接后,首个向机器人发送单聊消息的成员会绑定为本机 owner;仅该成员可触发 Agent。",
+ "connect": "保存并连接",
+ "reconnect": "重新连接",
+ "connectingAction": "正在连接…",
+ "disconnect": "解绑",
+ "configSaved": "企业微信机器人配置已保存",
+ "connectFailed": "企业微信机器人连接失败,请检查凭证与网络",
+ "reconnecting": "正在重新连接企业微信机器人",
+ "reconnectFailed": "重新连接失败:{{message}}",
+ "saveFailed": "保存失败:{{message}}",
+ "disconnected": "已解绑企业微信机器人",
+ "disconnectFailed": "解绑失败:{{message}}",
+ "connected": {
+ "heading": "企业微信机器人已连接",
+ "awaitingOwner": "请使用你的企业微信账号向机器人发送一条单聊消息,完成 owner 绑定。",
+ "ownerBound": "本机 owner:{{ownerUserId}}"
+ },
+ "disconnectConfirm": {
+ "title": "解绑企业微信机器人?",
+ "description": "本机保存的 Bot ID、Secret 和 owner 绑定会被清除。",
+ "confirm": "解绑",
+ "cancel": "取消"
+ }
+ },
"telegramBot": {
"title": "Telegram 机器人",
"description": "绑定你自建的 Telegram Bot,桌面端直连 Telegram,私聊和群聊都能找 {{appName}}。",
@@ -2710,8 +2766,8 @@
},
"tips": {
"cindy": "Cindy 是官方提供的共享机器人:无需申请任何凭证,连接 Slack 后 @Cindy 即可直接派活。",
- "personal": "个人连接包括微信扫码,以及使用自有凭证接入飞书 / Discord / Telegram;各渠道独立保存新对话配置。",
- "personalFeishuOnly": "个人连接包括微信扫码,以及使用自有凭证接入飞书和钉钉;各渠道独立保存新对话配置。"
+ "personal": "个人连接包括微信扫码,以及使用自有凭证接入企业微信 / 飞书 / Discord / Telegram;各渠道独立保存新对话配置。",
+ "personalFeishuOnly": "个人连接包括微信扫码,以及使用自有凭证接入企业微信、飞书和钉钉;各渠道独立保存新对话配置。"
},
"defaults": {
"title": "新对话配置",
@@ -2721,7 +2777,8 @@
"discord": "Discord 新对话会使用这组 Agent 和模型;已有私聊发送 /new 后应用。",
"wechat": "微信新对话会使用这组 Agent、模型和权限模式;已有私聊发送 /new 后应用。",
"telegram": "Telegram 新对话会使用这组 Agent 和模型;已有对话发送 /new 后应用。",
- "dingtalk": "钉钉新对话会使用这组 Agent 和模型;已有对话发送 /new 后应用。"
+ "dingtalk": "钉钉新对话会使用这组 Agent 和模型;已有对话发送 /new 后应用。",
+ "wecom": "企业微信新对话会使用这组 Agent、模型和权限模式;已有对话发送 /new 后应用。"
},
"agentLabel": "Agent",
"modelLabel": "模型配置",
@@ -3453,6 +3510,12 @@
"mailPrompt": "帮我从邮件建立智能通讯录:先看看我连接了哪些邮箱工具(没有的话告诉我该怎么连接);扫描最近 6 个月的往来邮件,找出和我有双向往来的真实联系人建档——高频且信息明确的直接确认,拿不准的用 pending;营销邮件、通知机器人、一次性发件人跳过。最后汇报建了哪些档案。",
"imPrompt": "帮我从 IM 工具建立智能通讯录:先看看我连接了哪些 IM(飞书 / Slack / 微信等,没有的话告诉我该怎么连接);把近期经常和我对话的联系人整理进通讯录,拿不准的用 pending,群机器人和一次性对话跳过。最后汇报建了哪些档案。"
}
+ },
+ "remotePermission": {
+ "label": "权限模式",
+ "hint": "远程 IM 会为需要审批的操作保留确认流程。",
+ "fullAccessDisabled": "远程 IM 不支持完全访问,避免无法安全确认的操作被直接执行。",
+ "permissionModeDisabled": "远程 IM 使用 Cindy 桌面端确认策略,因此该权限模式不可用。"
}
},
"remoteDevice": {
@@ -6587,6 +6650,8 @@
"silentRunTooltip": "开启后,任务成功完成时默认不提醒。若任务说明中要求在特定情况提醒,AI 会在满足条件时主动上报;失败和异常仍会提醒。",
"silentRunInfoAria": "查看静默运行规则",
"finishSendToFeishu": "完成时发送到飞书机器人",
+ "finishSendToWecomGroup": "完成时发送到企业微信群",
+ "configWecomGroup": "配置企微群通知",
"configFeishu": "配置飞书机器人"
},
"runSession": {
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 773bca6952..2f3b5d510c 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -419,6 +419,12 @@ type TelegramBotTransportStatus =
| { kind: 'error'; reason: string };
type DingTalkBotTransportStatus = DiscordBotTransportStatus;
+type WecomBotTransportStatus =
+ | { kind: 'idle' }
+ | { kind: 'connecting' }
+ | { kind: 'connected'; appId: string }
+ | { kind: 'conflict'; appId: string }
+ | { kind: 'error'; reason: string };
type WechatBotPhase =
| 'disconnected'
@@ -1826,6 +1832,36 @@ interface ElectronAPI {
callback: (update: { status: DingTalkBotTransportStatus }) => void,
) => () => void;
onOwnerChange: (callback: (update: { ownerUserId: string }) => void) => () => void;
+
+ wecomBot: {
+ getStatus: () => Promise<{
+ status: WecomBotTransportStatus;
+ botId: string | null;
+ ownerUserId: string | null;
+ }>;
+ setConfig: (payload: { botId: string; secret: string }) => Promise<{
+ status: WecomBotTransportStatus;
+ saveErrorStatus?: WecomBotTransportStatus;
+ botId: string | null;
+ ownerUserId: string | null;
+ }>;
+ reconnect: () => Promise<{
+ status: WecomBotTransportStatus;
+ botId: string | null;
+ ownerUserId: string | null;
+ }>;
+ disconnect: () => Promise<{
+ status: WecomBotTransportStatus;
+ botId: string | null;
+ ownerUserId: string | null;
+ }>;
+ onStatusChange: (
+ callback: (update: {
+ status: WecomBotTransportStatus;
+ botId: string | null;
+ ownerUserId: string | null;
+ }) => void,
+ ) => () => void;
};
// ── Personal WeChat (Settings → IM Bot → Personal) ──
@@ -2132,10 +2168,16 @@ interface ElectronAPI {
* mobile = 手机推送:桌面侧无独立开关(手机端注册/注销 token 决定接收),
* 发送侧防打扰在 main 的 device-link 模块收口,renderer 恒传 true。
*/
- channels?: { desktop?: boolean; feishu?: boolean; mobile?: boolean };
+ channels?: { desktop?: boolean; feishu?: boolean; wecomGroup?: boolean; mobile?: boolean };
}) => Promise<void>;
/** Sync the renderer-owned global desktop-notification preference to main. */
notificationSetDesktopEnabled?: (enabled: boolean) => Promise<{ ok: true }>;
+ wecomGroupNotification: {
+ getState: () => Promise<{ configured: boolean; maskedKey?: string }>;
+ saveAndTest: (webhookUrl: string) => Promise<{ configured: boolean; maskedKey?: string }>;
+ test: () => Promise<{ ok: true }>;
+ clear: () => Promise<{ configured: boolean }>;
+ };
/** 将对应 session 标记为需要关注,显示 Dock/taskbar app badge。 */
notificationMarkSessionAttention: (sessionId: string) => Promise<void>;
/** 用户查看对应 session 后,清除系统级 Dock/taskbar attention badge。 */
diff --git a/apps/desktop/src/shared/imDefaultSettings.ts b/apps/desktop/src/shared/imDefaultSettings.ts
index d773f1de80..350b81db7f 100644
--- a/apps/desktop/src/shared/imDefaultSettings.ts
+++ b/apps/desktop/src/shared/imDefaultSettings.ts
@@ -8,7 +8,14 @@ export type ImDefaultEffort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' |
* 刻意读 global(channel=undefined, 见 hook-control/session-runner.ts), 不落
* 在这个键上 — 两者互不影响。
*/
-export type ImDefaultSettingsChannel = 'feishu' | 'slack' | 'discord' | 'wechat' | 'telegram' | 'dingtalk';
+export type ImDefaultSettingsChannel =
+ | 'feishu'
+ | 'slack'
+ | 'discord'
+ | 'wechat'
+ | 'telegram'
+ | 'dingtalk'
+ | 'wecom';
export interface ImDefaultAgentSettings {
providerId: string | null;
@@ -58,6 +65,7 @@ export const IM_DEFAULT_SETTINGS_CHANNELS: readonly ImDefaultSettingsChannel[] =
'wechat',
'telegram',
'dingtalk',
+ 'wecom',
];
export const IM_DEFAULT_EFFORT_OVERRIDES: Readonly<Partial<Record<string, ImDefaultEffort>>> = {
@@ -89,6 +97,11 @@ export const WECHAT_UNSUPPORTED_PERMISSION_MODES: readonly ImDefaultPermissionMo
'bypassPermissions',
];
+export const REMOTE_IM_RESTRICTED_CHANNELS: readonly ImDefaultSettingsChannel[] = [
+ 'wechat',
+ 'wecom',
+];
+
export function isImDefaultAgentKind(value: unknown): value is ImDefaultAgentKind {
return typeof value === 'string' && AGENT_KINDS.has(value as ImDefaultAgentKind);
}
@@ -107,6 +120,17 @@ export function isWechatUnsupportedPermissionMode(
return isImDefaultPermissionMode(value) && WECHAT_UNSUPPORTED_PERMISSION_MODES.includes(value);
}
+export function isRemoteImUnsupportedPermissionMode(
+ channel: ImDefaultSettingsChannel | undefined,
+ value: unknown,
+): value is ImDefaultPermissionMode {
+ return (
+ channel !== undefined &&
+ REMOTE_IM_RESTRICTED_CHANNELS.includes(channel) &&
+ isWechatUnsupportedPermissionMode(value)
+ );
+}
+
export function isImDefaultSettingsChannel(value: unknown): value is ImDefaultSettingsChannel {
return (
typeof value === 'string' &&
diff --git a/apps/desktop/src/shared/sessionSource.ts b/apps/desktop/src/shared/sessionSource.ts
index f9eee855c7..5f55f6ea5c 100644
--- a/apps/desktop/src/shared/sessionSource.ts
+++ b/apps/desktop/src/shared/sessionSource.ts
@@ -7,6 +7,7 @@ export const SESSION_SOURCES = [
'discord',
'wechat',
'dingtalk',
+ 'wecom',
'scheduler',
'learn',
'shared',
@@ -37,6 +38,7 @@ export const DESKTOP_VISIBLE_SESSION_SOURCES: SessionSource[] = [
'discord',
'wechat',
'dingtalk',
+ 'wecom',
'scheduler',
'learn',
'shared',
@@ -51,6 +53,7 @@ export function normalizeSessionSource(source: unknown): SessionSource {
source === 'discord' ||
source === 'wechat' ||
source === 'dingtalk' ||
+ source === 'wecom' ||
source === 'scheduler' ||
source === 'learn' ||
source === 'shared' ||
diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.md
index 876e889ab1..7ee54110ab 100644
--- a/i18n/GLOSSARY.md
+++ b/i18n/GLOSSARY.md
@@ -257,6 +257,18 @@ macOS TCC 的 kTCCServiceListenEvent(系统设置里叫「输入监控」)在 Ci
个人微信连接的产品名称,沿用微信官方品牌写法;先登记为 proposed,待产品术语评审后再决定是否固化。
+### WeCom
+
+企业微信官方英文品牌名,用于智能机器人和群机器人能力;先登记为 proposed,待产品术语评审后再决定是否固化。
+
+### WeCom group bot
+
+企业微信群 Webhook 单向通知能力的名称;先登记为 proposed。
+
+### WeCom Intelligent Bot
+
+企业微信 WebSocket 长连接双向 IM 能力在设置页中的名称;先登记为 proposed。
+
## 怎么加一条术语
1. 在 `i18n/glossary.json` 的 `terms` 里加条目,`note` 必填——写清楚**为什么**这么定,
diff --git a/i18n/glossary.json b/i18n/glossary.json
index 108e79aaac..fb1bab5199 100644
--- a/i18n/glossary.json
+++ b/i18n/glossary.json
@@ -109,6 +109,39 @@
},
"note": "钉钉机器人连接的产品名称,沿用官方品牌写法;先登记为 proposed,待产品术语评审后再决定是否固化。"
},
+ {
+ "id": "wecom",
+ "status": "proposed",
+ "en": "WeCom",
+ "translations": {
+ "zh-CN": "企业微信",
+ "ja": "WeCom",
+ "ko": "WeCom"
+ },
+ "note": "企业微信官方英文品牌名,用于智能机器人和群机器人能力;先登记为 proposed,待产品术语评审后再决定是否固化。"
+ },
+ {
+ "id": "wecom-intelligent-bot",
+ "status": "proposed",
+ "en": "WeCom Intelligent Bot",
+ "translations": {
+ "zh-CN": "企业微信智能机器人",
+ "ja": "WeCom インテリジェントボット",
+ "ko": "WeCom 지능형 봇"
+ },
+ "note": "企业微信 WebSocket 长连接双向 IM 能力在设置页中的名称;先登记为 proposed。"
+ },
+ {
+ "id": "wecom-group-bot",
+ "status": "proposed",
+ "en": "WeCom group bot",
+ "translations": {
+ "zh-CN": "企微群机器人",
+ "ja": "WeCom グループボット",
+ "ko": "WeCom 그룹 봇"
+ },
+ "note": "企业微信群 Webhook 单向通知能力的名称;先登记为 proposed。"
+ },
{
"id": "openclaw",
"status": "proposed",
diff --git a/packages/lizi-im/package.json b/packages/lizi-im/package.json
index 06a502547f..8e8a51fdc1 100644
--- a/packages/lizi-im/package.json
+++ b/packages/lizi-im/package.json
@@ -22,6 +22,7 @@
"dependencies": {
"@larksuiteoapi/node-sdk": "^1.60.0",
"dingtalk-stream": "^2.1.5",
+ "@wecom/aibot-node-sdk": "1.0.7",
"discord.js": "^14.16.0"
},
"devDependencies": {
diff --git a/packages/lizi-im/src/index.ts b/packages/lizi-im/src/index.ts
index 31f83f1a32..2ca4599bba 100644
--- a/packages/lizi-im/src/index.ts
+++ b/packages/lizi-im/src/index.ts
@@ -43,6 +43,13 @@ export { TelegramIM, createTelegramIM } from './telegram/index.js';
export type { TelegramIMOptions, TelegramGroupWindowEntry } from './telegram/index.js';
export { TELEGRAM_DEFAULT_BEHAVIOR } from './telegram/index.js';
export type { TelegramBehaviorConfig } from './telegram/index.js';
+export { WecomIM, createWecomIM } from './wecom/index.js';
+export type { WecomIMOptions } from './wecom/index.js';
+export {
+ decodeWecomLane,
+ encodeWecomGroupLane,
+ chunkWecomMarkdown,
+} from './wecom/codec.js';
export {
decodeLaneUserId as decodeTelegramLaneUserId,
encodeLaneUserId as encodeTelegramLaneUserId,
diff --git a/packages/lizi-im/src/types.ts b/packages/lizi-im/src/types.ts
index 80ee8ec0c4..c50862abad 100644
--- a/packages/lizi-im/src/types.ts
+++ b/packages/lizi-im/src/types.ts
@@ -60,6 +60,8 @@ export interface IMHost {
discordMediaDir?: string;
/** Root for downloaded telegram media. Optional — only hosts that wire the telegram channel provide it. */
telegramMediaDir?: string;
+ /** Root for downloaded WeCom files and videos. */
+ wecomMediaDir?: string;
};
/**
@@ -85,7 +87,7 @@ export interface IMHost {
export interface IMHostMediaCache {
/** 图片字节入 host 总仓;返回仓内绝对路径(喂 agent)+ 渲染 URL(cindy-media://)。 */
cacheImage(params: {
- integration: 'feishu' | 'discord' | 'telegram' | 'dingtalk';
+ integration: 'feishu' | 'discord' | 'telegram' | 'dingtalk' | 'wecom';
/** 平台侧稳定 token(feishu image_key / discord attachment id / telegram file_id),host 据此免重下。 */
token: string;
buffer: Uint8Array;
@@ -93,7 +95,7 @@ export interface IMHostMediaCache {
}): Promise<{ absPath: string; url: string }>;
/** 按 token 查已缓存图片;未缓存返回 null(调用方去真下载)。 */
getCachedImage(
- integration: 'feishu' | 'discord' | 'telegram' | 'dingtalk',
+ integration: 'feishu' | 'discord' | 'telegram' | 'dingtalk' | 'wecom',
token: string,
): Promise<{ absPath: string; url: string; mimeType: string } | null>;
/** host 托管媒体 URL(cindy-media://)→ 绝对路径;认不出返回 null(出站上传用)。 */
diff --git a/packages/lizi-im/src/wecom/__tests__/codec.test.ts b/packages/lizi-im/src/wecom/__tests__/codec.test.ts
new file mode 100644
index 0000000000..10845b359a
--- /dev/null
+++ b/packages/lizi-im/src/wecom/__tests__/codec.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ chunkWecomMarkdown,
+ decodeWecomLane,
+ encodeWecomGroupLane,
+ escapeWecomMarkdown,
+} from "../codec.js";
+
+describe("WeCom lane codec", () => {
+ it("round-trips group chat ids without exposing path separators", () => {
+ const lane = encodeWecomGroupLane("chat/with spaces/中文");
+ expect(lane).toMatch(/^group\/[A-Za-z0-9_-]+$/);
+ expect(decodeWecomLane(lane)).toEqual({
+ kind: "group",
+ targetId: "chat/with spaces/中文",
+ });
+ });
+
+ it("treats ordinary ids as single-chat targets", () => {
+ expect(decodeWecomLane("zhangsan")).toEqual({
+ kind: "single",
+ targetId: "zhangsan",
+ });
+ });
+});
+
+describe("WeCom markdown chunking", () => {
+ it("keeps every chunk under the transport byte limit", () => {
+ const chunks = chunkWecomMarkdown("中".repeat(20_000));
+ expect(chunks.length).toBeGreaterThan(1);
+ expect(
+ chunks.every((chunk) => Buffer.byteLength(chunk, "utf8") <= 18 * 1024),
+ ).toBe(true);
+ expect(chunks.join("")).toBe("中".repeat(20_000));
+ });
+
+ it("normalizes an empty final response", () => {
+ expect(chunkWecomMarkdown(" \r\n ")).toEqual(["✅ (本轮无文本输出)"]);
+ });
+
+ it("escapes plain text before sending it through markdown", () => {
+ expect(escapeWecomMarkdown("**not bold** [link](x)")).toBe(
+ "\\*\\*not bold\\*\\* \\[link\\]\\(x\\)",
+ );
+ });
+});
diff --git a/packages/lizi-im/src/wecom/__tests__/index.test.ts b/packages/lizi-im/src/wecom/__tests__/index.test.ts
new file mode 100644
index 0000000000..5dc23f192d
--- /dev/null
+++ b/packages/lizi-im/src/wecom/__tests__/index.test.ts
@@ -0,0 +1,236 @@
+import { describe, expect, it, vi } from "vitest";
+
+import type { IMHost, IMMessageEvent } from "../../types.js";
+import { decodeWecomLane } from "../codec.js";
+import { WecomIM } from "../index.js";
+
+type Handler = (...args: any[]) => void;
+
+class FakeClient {
+ readonly handlers = new Map<string, Handler[]>();
+ readonly sendMessage = vi.fn(async () => ({}));
+ readonly sendMediaMessage = vi.fn(async () => ({}));
+ readonly replyStream = vi.fn(async () => ({}));
+ readonly replyMedia = vi.fn(async () => ({}));
+ readonly uploadMedia = vi.fn(async () => ({ media_id: "media-1" }));
+ readonly downloadFile = vi.fn(async () => ({
+ buffer: Buffer.from("image"),
+ filename: "photo.jpg",
+ }));
+ isConnected = false;
+ connectError: Error | null = null;
+
+ on(event: string, handler: Handler) {
+ const entries = this.handlers.get(event) ?? [];
+ entries.push(handler);
+ this.handlers.set(event, entries);
+ return this;
+ }
+
+ connect() {
+ if (this.connectError) throw this.connectError;
+ this.isConnected = true;
+ this.emit("authenticated");
+ return this;
+ }
+
+ disconnect() {
+ this.isConnected = false;
+ }
+
+ emit(event: string, payload?: unknown) {
+ for (const handler of this.handlers.get(event) ?? []) handler(payload);
+ }
+}
+
+function createHost() {
+ const secrets = new Map<string, string>([
+ ["wecom-bot-id", "bot-1"],
+ ["wecom-bot-secret", "secret-1"],
+ ]);
+ const broadcasts: unknown[] = [];
+ const host: IMHost = {
+ secrets: {
+ read: (name) => secrets.get(name) ?? null,
+ write: (name, value) => {
+ secrets.set(name, value);
+ return true;
+ },
+ remove: (name) => void secrets.delete(name),
+ isAvailable: () => true,
+ },
+ ipc: {
+ handle: vi.fn(),
+ broadcast: (_channel, payload) => broadcasts.push(payload),
+ },
+ paths: {
+ feishuMediaDir: "unused",
+ wecomMediaDir: "unused",
+ },
+ httpPostForm: async () => ({ status: 200, body: {} }),
+ };
+ return { host, secrets, broadcasts };
+}
+
+function message(args: {
+ id: string;
+ sender: string;
+ text: string;
+ chatId?: string;
+}) {
+ return {
+ body: {
+ msgid: args.id,
+ aibotid: "bot-1",
+ chattype: args.chatId ? "group" : "single",
+ ...(args.chatId ? { chatid: args.chatId } : {}),
+ from: { userid: args.sender },
+ msgtype: "text",
+ text: { content: args.text },
+ },
+ };
+}
+
+const flush = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
+
+describe("WecomIM routing and ownership", () => {
+ it("TOFU-binds the first DM sender and only accepts that owner afterwards", async () => {
+ const { host, secrets } = createHost();
+ const client = new FakeClient();
+ const im = new WecomIM(host, {
+ clientFactory: () => client as never,
+ });
+ const received: IMMessageEvent[] = [];
+ im.onMessage((event) => received.push(event));
+
+ await im.init();
+ client.emit(
+ "message.text",
+ message({ id: "m1", sender: "owner", text: "hello" }),
+ );
+ client.emit(
+ "message.text",
+ message({ id: "m2", sender: "other", text: "blocked" }),
+ );
+ await flush();
+
+ expect(secrets.get("wecom-owner-user-id")).toBe("owner");
+ expect(received.map((event) => event.text)).toEqual(["hello"]);
+ });
+
+ it("routes owner group messages through an encoded lane and active fallback uses chatid", async () => {
+ const { host, secrets } = createHost();
+ secrets.set("wecom-owner-user-id", "owner");
+ const client = new FakeClient();
+ const im = new WecomIM(host, { clientFactory: () => client as never });
+ const received: IMMessageEvent[] = [];
+ im.onMessage((event) => received.push(event));
+
+ await im.init();
+ client.emit(
+ "message.text",
+ message({
+ id: "m-group",
+ sender: "owner",
+ text: "group task",
+ chatId: "chat-123",
+ }),
+ );
+ await flush();
+
+ const lane = received[0]!.senderId;
+ expect(decodeWecomLane(lane)).toEqual({
+ kind: "group",
+ targetId: "chat-123",
+ });
+ await im.sendMarkdownText(lane, "**ack**");
+ expect(client.replyStream).toHaveBeenCalledOnce();
+
+ await im.sendMarkdownText(lane, "**active**");
+ expect(client.sendMessage).toHaveBeenCalledWith("chat-123", {
+ msgtype: "markdown",
+ markdown: { content: "**active**" },
+ });
+ });
+
+ it("deduplicates repeated callback message ids", async () => {
+ const { host, secrets } = createHost();
+ secrets.set("wecom-owner-user-id", "owner");
+ const client = new FakeClient();
+ const im = new WecomIM(host, { clientFactory: () => client as never });
+ const received = vi.fn();
+ im.onMessage(received);
+
+ await im.init();
+ const frame = message({ id: "same", sender: "owner", text: "once" });
+ client.emit("message.text", frame);
+ client.emit("message.text", frame);
+ await flush();
+
+ expect(received).toHaveBeenCalledOnce();
+ });
+
+ it("surfaces a synchronous SDK startup failure instead of staying connecting", async () => {
+ const { host } = createHost();
+ const client = new FakeClient();
+ client.connectError = new Error("invalid credentials");
+ const im = new WecomIM(host, { clientFactory: () => client as never });
+
+ await expect(im.init()).resolves.toBeUndefined();
+
+ expect(im.getStatus()).toEqual({
+ kind: "error",
+ reason: "invalid credentials",
+ });
+ });
+
+ it("preserves arrival order when media download is slower than a following text message", async () => {
+ const { host, secrets } = createHost();
+ secrets.set("wecom-owner-user-id", "owner");
+ const client = new FakeClient();
+ let releaseDownload!: () => void;
+ client.downloadFile.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ releaseDownload = () =>
+ resolve({ buffer: Buffer.from("image"), filename: "photo.jpg" });
+ }),
+ );
+ host.media = {
+ getCachedImage: async () => null,
+ cacheImage: async () => ({
+ absPath: "C:\\managed\\photo.jpg",
+ url: "cindy-media://image",
+ }),
+ resolveMediaUrl: () => null,
+ };
+ const im = new WecomIM(host, { clientFactory: () => client as never });
+ const received: string[] = [];
+ im.onMessage((event) =>
+ received.push(event.text || event.attachments[0]?.kind || "empty"),
+ );
+
+ await im.init();
+ client.emit("message.image", {
+ body: {
+ msgid: "image-first",
+ aibotid: "bot-1",
+ chattype: "single",
+ from: { userid: "owner" },
+ msgtype: "image",
+ image: { url: "https://example.invalid/image" },
+ },
+ });
+ client.emit(
+ "message.text",
+ message({ id: "text-second", sender: "owner", text: "second" }),
+ );
+ await flush();
+ expect(received).toEqual([]);
+
+ releaseDownload();
+ await flush();
+ await flush();
+ expect(received).toEqual(["image", "second"]);
+ });
+});
diff --git a/packages/lizi-im/src/wecom/__tests__/media.test.ts b/packages/lizi-im/src/wecom/__tests__/media.test.ts
new file mode 100644
index 0000000000..386c2ad5e6
--- /dev/null
+++ b/packages/lizi-im/src/wecom/__tests__/media.test.ts
@@ -0,0 +1,53 @@
+import fs from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+import { afterEach, describe, expect, it } from "vitest";
+
+import {
+ mimeTypeForFilename,
+ persistWecomDownload,
+ readWecomOutboundFile,
+ safeWecomFilename,
+} from "../media.js";
+
+const tempDirs: string[] = [];
+
+afterEach(async () => {
+ await Promise.all(
+ tempDirs
+ .splice(0)
+ .map((dir) => fs.rm(dir, { recursive: true, force: true })),
+ );
+});
+
+describe("WeCom media helpers", () => {
+ it("removes path traversal and reserved filename characters", () => {
+ expect(safeWecomFilename("../../bad:name?.png")).toBe("bad_name_.png");
+ });
+
+ it("persists a downloaded file below the channel directory", async () => {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), "cindy-wecom-"));
+ tempDirs.push(dir);
+ const stored = await persistWecomDownload({
+ mediaDir: dir,
+ buffer: Buffer.from("hello"),
+ filename: "../notes.txt",
+ });
+ expect(path.dirname(stored.absPath)).toBe(dir);
+ expect(await fs.readFile(stored.absPath, "utf8")).toBe("hello");
+ expect(stored.originalName).toBe("notes.txt");
+ expect(stored.mimeType).toBe("text/plain");
+ });
+
+ it("selects outbound media types from safe metadata", async () => {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), "cindy-wecom-"));
+ tempDirs.push(dir);
+ const file = path.join(dir, "picture.png");
+ await fs.writeFile(file, Buffer.from([1, 2, 3]));
+ const outbound = await readWecomOutboundFile(file);
+ expect(outbound.mediaType).toBe("image");
+ expect(outbound.filename).toBe("picture.png");
+ expect(mimeTypeForFilename("README")).toBe("application/octet-stream");
+ });
+});
diff --git a/packages/lizi-im/src/wecom/codec.ts b/packages/lizi-im/src/wecom/codec.ts
new file mode 100644
index 0000000000..1011750884
--- /dev/null
+++ b/packages/lizi-im/src/wecom/codec.ts
@@ -0,0 +1,47 @@
+const GROUP_LANE_PREFIX = "group/";
+const MAX_MESSAGE_BYTES = 18 * 1024;
+
+export interface WecomLane {
+ kind: "single" | "group";
+ targetId: string;
+}
+
+export function encodeWecomGroupLane(chatId: string): string {
+ if (!chatId) throw new Error("WECOM_CHAT_ID_REQUIRED");
+ return `${GROUP_LANE_PREFIX}${Buffer.from(chatId, "utf8").toString("base64url")}`;
+}
+
+export function decodeWecomLane(userId: string): WecomLane {
+ if (!userId.startsWith(GROUP_LANE_PREFIX)) {
+ if (!userId) throw new Error("WECOM_USER_ID_REQUIRED");
+ return { kind: "single", targetId: userId };
+ }
+ const encoded = userId.slice(GROUP_LANE_PREFIX.length);
+ if (!encoded) throw new Error("WECOM_GROUP_LANE_INVALID");
+ const targetId = Buffer.from(encoded, "base64url").toString("utf8");
+ if (!targetId) throw new Error("WECOM_GROUP_LANE_INVALID");
+ return { kind: "group", targetId };
+}
+
+export function chunkWecomMarkdown(source: string): string[] {
+ const normalized = source.replace(/\r\n?/g, "\n").trim();
+ if (!normalized) return ["✅ (本轮无文本输出)"];
+
+ const chunks: string[] = [];
+ let current = "";
+ for (const point of normalized) {
+ const candidate = current + point;
+ if (Buffer.byteLength(candidate, "utf8") > MAX_MESSAGE_BYTES && current) {
+ chunks.push(current);
+ current = point;
+ } else {
+ current = candidate;
+ }
+ }
+ if (current) chunks.push(current);
+ return chunks;
+}
+
+export function escapeWecomMarkdown(source: string): string {
+ return source.replace(/([\\`*_{}\[\]()#+\-.!>])/g, "\\$1");
+}
diff --git a/packages/lizi-im/src/wecom/index.ts b/packages/lizi-im/src/wecom/index.ts
new file mode 100644
index 0000000000..f0e79e5c02
--- /dev/null
+++ b/packages/lizi-im/src/wecom/index.ts
@@ -0,0 +1,862 @@
+import { randomUUID } from "node:crypto";
+
+import {
+ WSClient,
+ type BaseMessage,
+ type FileMessage,
+ type ImageMessage,
+ type MixedMessage,
+ type TextMessage,
+ type VideoMessage,
+ type VoiceMessage,
+ type WSClientOptions,
+ type WsFrame,
+} from "@wecom/aibot-node-sdk";
+
+import { BaseIM } from "../BaseIM.js";
+import type { ImFinalOutput, TextChannelIM } from "../channelIM.js";
+import type { Logger } from "../logger.js";
+import type {
+ IMAttachment,
+ IMHost,
+ IMMessageEvent,
+ IMStatus,
+ IMUnsupportedEntry,
+ SendFileResult,
+} from "../types.js";
+import {
+ chunkWecomMarkdown,
+ decodeWecomLane,
+ encodeWecomGroupLane,
+ escapeWecomMarkdown,
+} from "./codec.js";
+import {
+ mimeTypeForFilename,
+ persistWecomDownload,
+ readWecomOutboundFile,
+ safeWecomFilename,
+} from "./media.js";
+
+const BOT_ID_SECRET_KEY = "wecom-bot-id";
+const BOT_SECRET_SECRET_KEY = "wecom-bot-secret";
+const OWNER_USER_ID_SECRET_KEY = "wecom-owner-user-id";
+const CALLBACK_TTL_MS = 4 * 60_000;
+const CALLBACK_QUEUE_CAPACITY = 64;
+const DEDUPE_CAPACITY = 2_048;
+const SECRET_WRITE_FAILED_REASON = "无法使用系统安全存储保存企业微信机器人凭证";
+
+type MessageHandler = (event: IMMessageEvent) => void;
+type StatusHandler = (status: IMStatus) => void;
+type TextInterceptor = (event: IMMessageEvent) => boolean;
+type WecomFrame = WsFrame<BaseMessage>;
+
+interface PendingFrame {
+ frame: WecomFrame;
+ receivedAt: number;
+}
+
+export interface WecomIMOptions {
+ clientFactory?: (options: WSClientOptions) => WSClient;
+ now?: () => number;
+}
+
+export class WecomIM extends BaseIM implements TextChannelIM {
+ private readonly messageHandlers = new Set<MessageHandler>();
+ private readonly statusHandlers = new Set<StatusHandler>();
+ private readonly textInterceptors = new Set<TextInterceptor>();
+ private readonly pendingFrames = new Map<string, PendingFrame[]>();
+ private readonly inboundTails = new Map<string, Promise<void>>();
+ private readonly seenMessageIds = new Set<string>();
+ private readonly mediaDir: string;
+ private readonly now: () => number;
+ private client: WSClient | null = null;
+ private status: IMStatus = { kind: "idle" };
+ private botId = "";
+ private ownerUserId = "";
+ private generation = 0;
+
+ constructor(
+ host: IMHost,
+ private readonly options: WecomIMOptions = {},
+ ) {
+ super("wecom", host);
+ if (!host.paths.wecomMediaDir) {
+ throw new Error(
+ "IMHost.paths.wecomMediaDir is required to wire the WeCom channel",
+ );
+ }
+ this.mediaDir = host.paths.wecomMediaDir;
+ this.now = options.now ?? Date.now;
+ }
+
+ async init(): Promise<void> {
+ this.botId = this.host.secrets.read(BOT_ID_SECRET_KEY)?.trim() ?? "";
+ this.ownerUserId =
+ this.host.secrets.read(OWNER_USER_ID_SECRET_KEY)?.trim() ?? "";
+ const secret = this.host.secrets.read(BOT_SECRET_SECRET_KEY)?.trim() ?? "";
+ if (!this.botId || !secret) {
+ this.setStatus({ kind: "idle" });
+ return;
+ }
+ this.connect(this.botId, secret);
+ }
+
+ async dispose(): Promise<void> {
+ this.generation += 1;
+ this.pendingFrames.clear();
+ this.inboundTails.clear();
+ this.seenMessageIds.clear();
+ this.client?.disconnect();
+ this.client = null;
+ this.setStatus({ kind: "idle" });
+ }
+
+ registerIpc(): void {
+ const state = (saveErrorStatus?: IMStatus) => ({
+ status: this.status,
+ botId: this.botId || null,
+ ownerUserId: this.ownerUserId || null,
+ ...(saveErrorStatus ? { saveErrorStatus } : {}),
+ });
+
+ this.host.ipc.handle("wecomBot:get-status", () => state());
+ this.host.ipc.handle("wecomBot:set-config", async (payload) => {
+ const record = isRecord(payload) ? payload : {};
+ const botId = typeof record.botId === "string" ? record.botId.trim() : "";
+ const secret =
+ typeof record.secret === "string" ? record.secret.trim() : "";
+ if (!botId || !secret) {
+ const failed: IMStatus = {
+ kind: "error",
+ reason: "Bot ID 和 Secret 不能为空",
+ };
+ this.setStatus(failed);
+ return state(failed);
+ }
+ if (!this.host.secrets.isAvailable()) {
+ const failed: IMStatus = {
+ kind: "error",
+ reason: SECRET_WRITE_FAILED_REASON,
+ };
+ this.setStatus(failed);
+ return state(failed);
+ }
+
+ const previousBotId = this.host.secrets.read(BOT_ID_SECRET_KEY);
+ const previousSecret = this.host.secrets.read(BOT_SECRET_SECRET_KEY);
+ const previousOwner = this.host.secrets.read(OWNER_USER_ID_SECRET_KEY);
+ const botChanged = Boolean(
+ previousBotId?.trim() && previousBotId.trim() !== botId,
+ );
+ const saved =
+ this.host.secrets.write(BOT_ID_SECRET_KEY, botId) &&
+ this.host.secrets.write(BOT_SECRET_SECRET_KEY, secret);
+ if (!saved) {
+ this.restoreSecret(BOT_ID_SECRET_KEY, previousBotId);
+ this.restoreSecret(BOT_SECRET_SECRET_KEY, previousSecret);
+ this.restoreSecret(OWNER_USER_ID_SECRET_KEY, previousOwner);
+ const failed: IMStatus = {
+ kind: "error",
+ reason: SECRET_WRITE_FAILED_REASON,
+ };
+ this.setStatus(failed);
+ return state(failed);
+ }
+ if (botChanged) {
+ this.host.secrets.remove(OWNER_USER_ID_SECRET_KEY);
+ this.ownerUserId = "";
+ }
+ this.botId = botId;
+ this.connect(botId, secret);
+ return state();
+ });
+ this.host.ipc.handle("wecomBot:reconnect", () => {
+ const botId = this.host.secrets.read(BOT_ID_SECRET_KEY)?.trim() ?? "";
+ const secret =
+ this.host.secrets.read(BOT_SECRET_SECRET_KEY)?.trim() ?? "";
+ if (botId && secret) this.connect(botId, secret);
+ return state();
+ });
+ this.host.ipc.handle("wecomBot:disconnect", async () => {
+ this.generation += 1;
+ this.client?.disconnect();
+ this.client = null;
+ this.pendingFrames.clear();
+ this.inboundTails.clear();
+ this.seenMessageIds.clear();
+ this.host.secrets.remove(BOT_ID_SECRET_KEY);
+ this.host.secrets.remove(BOT_SECRET_SECRET_KEY);
+ this.host.secrets.remove(OWNER_USER_ID_SECRET_KEY);
+ this.botId = "";
+ this.ownerUserId = "";
+ this.setStatus({ kind: "idle" });
+ return state();
+ });
+ }
+
+ onMessage(handler: MessageHandler): () => void {
+ this.messageHandlers.add(handler);
+ return () => this.messageHandlers.delete(handler);
+ }
+
+ onStatusChange(handler: StatusHandler): () => void {
+ this.statusHandlers.add(handler);
+ return () => this.statusHandlers.delete(handler);
+ }
+
+ onTextMessageIntercept(handler: TextInterceptor): () => void {
+ this.textInterceptors.add(handler);
+ return () => this.textInterceptors.delete(handler);
+ }
+
+ getStatus(): IMStatus {
+ return this.status;
+ }
+
+ async sendText(userId: string, text: string): Promise<{ messageId: string }> {
+ const chunks = chunkWecomMarkdown(escapeWecomMarkdown(text));
+ return this.sendChunks(userId, chunks);
+ }
+
+ async sendMarkdownText(
+ userId: string,
+ markdown: string,
+ ): Promise<{ messageId: string }> {
+ return this.sendChunks(userId, chunkWecomMarkdown(markdown));
+ }
+
+ async sendFile(
+ userId: string,
+ absPath: string,
+ displayName?: string,
+ ): Promise<SendFileResult> {
+ let uploaded = false;
+ try {
+ const client = this.requireConnectedClient();
+ const local = await readWecomOutboundFile(absPath, displayName);
+ const result = await client.uploadMedia(local.buffer, {
+ type: local.mediaType,
+ filename: local.filename,
+ });
+ uploaded = true;
+ const lane = decodeWecomLane(userId);
+ const frame = this.claimNewestFrame(userId);
+ if (frame) {
+ try {
+ await client.replyMedia(frame, local.mediaType, result.media_id);
+ return { ok: true, messageId: randomUUID() };
+ } catch (error) {
+ this.log.warn(
+ "passive media reply failed; using active send",
+ safeError(error),
+ );
+ }
+ }
+ await client.sendMediaMessage(
+ lane.targetId,
+ local.mediaType,
+ result.media_id,
+ );
+ return { ok: true, messageId: randomUUID() };
+ } catch (error) {
+ const code = errorCode(error);
+ if (code === "ENOENT" || code === "WECOM_FILE_NOT_FOUND") {
+ return { ok: false, reason: "NOT_FOUND" };
+ }
+ if (code === "WECOM_FILE_EMPTY") return { ok: false, reason: "EMPTY" };
+ if (code === "WECOM_FILE_TOO_LARGE")
+ return { ok: false, reason: "TOO_LARGE" };
+ if (error instanceof Error && error.message === "WECOM_NOT_CONNECTED") {
+ return { ok: false, reason: "SEND_FAIL" };
+ }
+ this.log.warn("failed to send media", safeError(error));
+ return { ok: false, reason: uploaded ? "SEND_FAIL" : "UPLOAD_FAIL" };
+ }
+ }
+
+ async commitFinal(output: ImFinalOutput): Promise<void> {
+ const chunks = chunkWecomMarkdown(output.text);
+ await this.sendChunks(output.userId, chunks, "oldest");
+ for (const absPath of output.mediaAbsPaths?.slice(0, 4) ?? []) {
+ const result = await this.sendFile(output.userId, absPath);
+ if (!result.ok) {
+ this.log.warn("failed to send terminal attachment", {
+ reason: result.reason,
+ });
+ }
+ }
+ }
+
+ private connect(botId: string, secret: string): void {
+ const generation = (this.generation += 1);
+ this.client?.disconnect();
+ this.pendingFrames.clear();
+ this.setStatus({ kind: "connecting" });
+
+ const clientFactory =
+ this.options.clientFactory ?? ((options) => new WSClient(options));
+ const client = clientFactory({
+ botId,
+ secret,
+ maxReconnectAttempts: -1,
+ maxAuthFailureAttempts: 3,
+ logger: createSdkLogger(this.log, botId, secret),
+ });
+ this.client = client;
+
+ client.on("authenticated", () => {
+ if (!this.isCurrent(client, generation)) return;
+ this.setStatus({ kind: "connected", appId: botId });
+ });
+ client.on("reconnecting", () => {
+ if (!this.isCurrent(client, generation)) return;
+ this.setStatus({ kind: "connecting" });
+ });
+ client.on("disconnected", (reason) => {
+ if (!this.isCurrent(client, generation)) return;
+ this.log.warn("connection disconnected", sanitizeReason(reason));
+ this.setStatus({ kind: "connecting" });
+ });
+ client.on("error", (error) => {
+ if (!this.isCurrent(client, generation)) return;
+ this.log.warn("connection error", safeError(error));
+ this.setStatus({ kind: "error", reason: sanitizeReason(error.message) });
+ });
+ client.on("event.disconnected_event", () => {
+ if (!this.isCurrent(client, generation)) return;
+ this.setStatus({ kind: "conflict", appId: botId });
+ });
+ client.on("message.text", (frame) =>
+ this.queueInbound(frame, () =>
+ this.processText(frame, client, generation),
+ ),
+ );
+ client.on("message.image", (frame) =>
+ this.queueInbound(frame, () =>
+ this.processImage(frame, client, generation),
+ ),
+ );
+ client.on("message.mixed", (frame) =>
+ this.queueInbound(frame, () =>
+ this.processMixed(frame, client, generation),
+ ),
+ );
+ client.on("message.voice", (frame) =>
+ this.queueInbound(frame, () =>
+ this.processVoice(frame, client, generation),
+ ),
+ );
+ client.on("message.file", (frame) =>
+ this.queueInbound(frame, () =>
+ this.processFile(frame, client, generation),
+ ),
+ );
+ client.on("message.video", (frame) =>
+ this.queueInbound(frame, () =>
+ this.processVideo(frame, client, generation),
+ ),
+ );
+ try {
+ client.connect();
+ } catch (error) {
+ if (!this.isCurrent(client, generation)) return;
+ this.client = null;
+ const reason = sanitizeReason(
+ error instanceof Error ? error.message : String(error),
+ );
+ this.log.warn("connection start failed", safeError(error));
+ this.setStatus({ kind: "error", reason });
+ }
+ }
+
+ private async processText(
+ frame: WsFrame<TextMessage>,
+ client: WSClient,
+ generation: number,
+ ): Promise<void> {
+ await this.emitInbound(frame, client, generation, async () => ({
+ text: frame.body?.text.content ?? "",
+ attachments: [],
+ unsupported: [],
+ }));
+ }
+
+ private async processImage(
+ frame: WsFrame<ImageMessage>,
+ client: WSClient,
+ generation: number,
+ ): Promise<void> {
+ await this.emitInbound(frame, client, generation, async () => {
+ const image = frame.body?.image;
+ if (!image) return unsupportedPayload("image", "图片内容缺失");
+ const attachment = await this.downloadImage(
+ client,
+ frame.body!.msgid,
+ 0,
+ image,
+ );
+ return attachment
+ ? { text: "", attachments: [attachment], unsupported: [] }
+ : unsupportedPayload("image:download-failed", "图片下载失败");
+ });
+ }
+
+ private async processMixed(
+ frame: WsFrame<MixedMessage>,
+ client: WSClient,
+ generation: number,
+ ): Promise<void> {
+ await this.emitInbound(frame, client, generation, async () => {
+ const text: string[] = [];
+ const attachments: IMAttachment[] = [];
+ const unsupported: IMUnsupportedEntry[] = [];
+ for (const [index, item] of (
+ frame.body?.mixed.msg_item ?? []
+ ).entries()) {
+ if (item.msgtype === "text") {
+ if (item.text?.content) text.push(item.text.content);
+ continue;
+ }
+ if (item.msgtype === "image" && item.image) {
+ const attachment = await this.downloadImage(
+ client,
+ frame.body!.msgid,
+ index,
+ item.image,
+ );
+ if (attachment) attachments.push(attachment);
+ else
+ unsupported.push({
+ type: "image:download-failed",
+ label: "图片下载失败",
+ });
+ }
+ }
+ return { text: text.join("\n"), attachments, unsupported };
+ });
+ }
+
+ private async processVoice(
+ frame: WsFrame<VoiceMessage>,
+ client: WSClient,
+ generation: number,
+ ): Promise<void> {
+ await this.emitInbound(frame, client, generation, async () => ({
+ text: frame.body?.voice.content ?? "",
+ attachments: [],
+ unsupported: frame.body?.voice.content
+ ? []
+ : [{ type: "voice:empty", label: "语音未能识别为文字" }],
+ }));
+ }
+
+ private async processFile(
+ frame: WsFrame<FileMessage>,
+ client: WSClient,
+ generation: number,
+ ): Promise<void> {
+ await this.emitInbound(frame, client, generation, async () => {
+ const file = frame.body?.file;
+ if (!file) return unsupportedPayload("file", "文件内容缺失");
+ try {
+ const downloaded = await client.downloadFile(file.url, file.aeskey);
+ const persisted = await persistWecomDownload({
+ mediaDir: this.mediaDir,
+ buffer: downloaded.buffer,
+ filename: downloaded.filename,
+ });
+ return {
+ text: "",
+ attachments: [{ kind: "file", ...persisted }],
+ unsupported: [],
+ };
+ } catch (error) {
+ this.log.warn("failed to stage inbound file", safeError(error));
+ return unsupportedPayload("file:download-failed", "文件下载失败");
+ }
+ });
+ }
+
+ private async processVideo(
+ frame: WsFrame<VideoMessage>,
+ client: WSClient,
+ generation: number,
+ ): Promise<void> {
+ await this.emitInbound(frame, client, generation, async () => {
+ const video = frame.body?.video;
+ if (!video) return unsupportedPayload("video", "视频内容缺失");
+ try {
+ const downloaded = await client.downloadFile(video.url, video.aeskey);
+ const persisted = await persistWecomDownload({
+ mediaDir: this.mediaDir,
+ buffer: downloaded.buffer,
+ filename: downloaded.filename,
+ fallbackExtension: ".mp4",
+ });
+ return {
+ text: "",
+ attachments: [{ kind: "file", ...persisted }],
+ unsupported: [],
+ };
+ } catch (error) {
+ this.log.warn("failed to stage inbound video", safeError(error));
+ return unsupportedPayload("video:download-failed", "视频下载失败");
+ }
+ });
+ }
+
+ private async emitInbound(
+ frame: WecomFrame,
+ client: WSClient,
+ generation: number,
+ normalize: () => Promise<{
+ text: string;
+ attachments: IMAttachment[];
+ unsupported: IMUnsupportedEntry[];
+ }>,
+ ): Promise<void> {
+ if (!this.isCurrent(client, generation)) return;
+ const body = frame.body;
+ if (!body || !body.msgid || !body.from?.userid || this.hasSeen(body.msgid))
+ return;
+
+ const isOwner = await this.acceptOwner(body);
+ if (!isOwner || !this.isCurrent(client, generation)) return;
+ const lane =
+ body.chattype === "group" && body.chatid
+ ? encodeWecomGroupLane(body.chatid)
+ : body.from.userid;
+ this.enqueueFrame(lane, frame);
+
+ let normalized: Awaited<ReturnType<typeof normalize>>;
+ try {
+ normalized = await normalize();
+ } catch (error) {
+ this.log.warn("failed to normalize inbound message", safeError(error));
+ normalized = unsupportedPayload(body.msgtype, `${body.msgtype} 处理失败`);
+ }
+ if (!this.isCurrent(client, generation)) return;
+
+ const quoted = quoteContext(body);
+ const event: IMMessageEvent = {
+ channelName: this.name,
+ senderId: lane,
+ chatId: body.chatid || body.from.userid,
+ contextId: body.aibotid || this.botId,
+ messageId: body.msgid,
+ text: normalized.text,
+ attachments: normalized.attachments,
+ unsupported: normalized.unsupported,
+ ...(body.chattype === "group"
+ ? {
+ speaker: {
+ id: body.from.userid,
+ name: body.from.userid,
+ isOwner: true,
+ },
+ }
+ : {}),
+ ...(quoted ? { replyContext: quoted } : {}),
+ };
+ if (
+ event.text.trim() &&
+ event.attachments.length === 0 &&
+ [...this.textInterceptors].some((handler) => handler(event))
+ ) {
+ return;
+ }
+ for (const handler of this.messageHandlers) handler(event);
+ }
+
+ private async acceptOwner(body: BaseMessage): Promise<boolean> {
+ const sender = body.from.userid.trim();
+ if (!sender) return false;
+ if (this.ownerUserId) return sender === this.ownerUserId;
+ if (body.chattype !== "single") return false;
+ if (!this.host.secrets.write(OWNER_USER_ID_SECRET_KEY, sender)) {
+ this.log.warn("failed to persist first owner binding");
+ return false;
+ }
+ this.ownerUserId = sender;
+ this.host.ipc.broadcast("wecomBot:status-changed", {
+ status: this.status,
+ botId: this.botId,
+ ownerUserId: sender,
+ });
+ return true;
+ }
+
+ private async downloadImage(
+ client: WSClient,
+ messageId: string,
+ index: number,
+ image: { url: string; aeskey?: string },
+ ): Promise<IMAttachment | null> {
+ const token = `${messageId}:${index}`;
+ const cached = await this.host.media?.getCachedImage("wecom", token);
+ if (cached) {
+ return {
+ kind: "image",
+ absPath: cached.absPath,
+ originalName: safeWecomFilename(
+ undefined,
+ extensionForMime(cached.mimeType),
+ ),
+ mimeType: cached.mimeType,
+ url: cached.url,
+ };
+ }
+ try {
+ const downloaded = await client.downloadFile(image.url, image.aeskey);
+ const filename = safeWecomFilename(downloaded.filename, ".jpg");
+ const mimeType = mimeTypeForFilename(filename);
+ if (this.host.media) {
+ const stored = await this.host.media.cacheImage({
+ integration: "wecom",
+ token,
+ buffer: downloaded.buffer,
+ mimeType,
+ });
+ return {
+ kind: "image",
+ absPath: stored.absPath,
+ originalName: filename,
+ mimeType,
+ url: stored.url,
+ };
+ }
+ const persisted = await persistWecomDownload({
+ mediaDir: this.mediaDir,
+ buffer: downloaded.buffer,
+ filename,
+ fallbackExtension: ".jpg",
+ });
+ return { kind: "image", ...persisted };
+ } catch (error) {
+ this.log.warn("failed to stage inbound image", safeError(error));
+ return null;
+ }
+ }
+
+ private async sendChunks(
+ userId: string,
+ chunks: string[],
+ framePreference: "newest" | "oldest" = "newest",
+ ): Promise<{ messageId: string }> {
+ const client = this.requireConnectedClient();
+ const lane = decodeWecomLane(userId);
+ const firstId = randomUUID();
+ const frame =
+ framePreference === "oldest"
+ ? this.claimOldestFrame(userId)
+ : this.claimNewestFrame(userId);
+
+ let start = 0;
+ if (frame) {
+ try {
+ await client.replyStream(frame, firstId, chunks[0]!, true);
+ start = 1;
+ } catch (error) {
+ this.log.warn(
+ "passive text reply failed; using active send",
+ safeError(error),
+ );
+ }
+ }
+ for (let index = start; index < chunks.length; index += 1) {
+ await client.sendMessage(lane.targetId, {
+ msgtype: "markdown",
+ markdown: { content: chunks[index]! },
+ });
+ }
+ return { messageId: firstId };
+ }
+
+ private requireConnectedClient(): WSClient {
+ if (!this.client || !this.client.isConnected)
+ throw new Error("WECOM_NOT_CONNECTED");
+ return this.client;
+ }
+
+ private queueInbound(
+ frame: WecomFrame,
+ operation: () => Promise<void>,
+ ): void {
+ const body = frame.body;
+ const lane =
+ body?.chattype === "group" && body.chatid
+ ? `group:${body.chatid}`
+ : `single:${body?.from?.userid ?? "unknown"}`;
+ const previous = this.inboundTails.get(lane) ?? Promise.resolve();
+ const current = previous
+ .catch(() => {
+ // One malformed message must not block later messages in the lane.
+ })
+ .then(operation)
+ .catch((error) => {
+ this.log.warn("inbound message processing failed", safeError(error));
+ });
+ this.inboundTails.set(lane, current);
+ void current.finally(() => {
+ if (this.inboundTails.get(lane) === current)
+ this.inboundTails.delete(lane);
+ });
+ }
+
+ private enqueueFrame(lane: string, frame: WecomFrame): void {
+ const queue = this.pendingFrames.get(lane) ?? [];
+ queue.push({ frame, receivedAt: this.now() });
+ while (queue.length > CALLBACK_QUEUE_CAPACITY) queue.shift();
+ this.pendingFrames.set(lane, queue);
+ }
+
+ private claimNewestFrame(lane: string): WecomFrame | null {
+ const queue = this.liveFrames(lane);
+ const found = queue.pop()?.frame ?? null;
+ this.updateFrameQueue(lane, queue);
+ return found;
+ }
+
+ private claimOldestFrame(lane: string): WecomFrame | null {
+ const queue = this.liveFrames(lane);
+ const found = queue.shift()?.frame ?? null;
+ this.updateFrameQueue(lane, queue);
+ return found;
+ }
+
+ private liveFrames(lane: string): PendingFrame[] {
+ const minimum = this.now() - CALLBACK_TTL_MS;
+ return (this.pendingFrames.get(lane) ?? []).filter(
+ (item) => item.receivedAt >= minimum,
+ );
+ }
+
+ private updateFrameQueue(lane: string, queue: PendingFrame[]): void {
+ if (queue.length) this.pendingFrames.set(lane, queue);
+ else this.pendingFrames.delete(lane);
+ }
+
+ private hasSeen(messageId: string): boolean {
+ if (this.seenMessageIds.has(messageId)) return true;
+ this.seenMessageIds.add(messageId);
+ while (this.seenMessageIds.size > DEDUPE_CAPACITY) {
+ const oldest = this.seenMessageIds.values().next().value;
+ if (oldest === undefined) break;
+ this.seenMessageIds.delete(oldest);
+ }
+ return false;
+ }
+
+ private isCurrent(client: WSClient, generation: number): boolean {
+ return this.client === client && this.generation === generation;
+ }
+
+ private setStatus(status: IMStatus): void {
+ this.status = status;
+ for (const handler of this.statusHandlers) handler(status);
+ this.host.ipc.broadcast("wecomBot:status-changed", {
+ status,
+ botId: this.botId || null,
+ ownerUserId: this.ownerUserId || null,
+ });
+ }
+
+ private restoreSecret(key: string, previous: string | null): void {
+ if (previous === null) this.host.secrets.remove(key);
+ else this.host.secrets.write(key, previous);
+ }
+}
+
+export function createWecomIM(host: IMHost, options?: WecomIMOptions): WecomIM {
+ return new WecomIM(host, options);
+}
+
+function createSdkLogger(
+ logger: Logger,
+ botId: string,
+ secret: string,
+): NonNullable<WSClientOptions["logger"]> {
+ const clean = (message: string) => redactSdkMessage(message, botId, secret);
+ return {
+ debug: (message) => logger.debug(clean(message)),
+ info: (message) => logger.info(clean(message)),
+ warn: (message) => logger.warn(clean(message)),
+ error: (message) => logger.error(clean(message)),
+ };
+}
+
+function redactSdkMessage(
+ message: string,
+ botId: string,
+ secret: string,
+): string {
+ let redacted = String(message).replace(/https?:\/\/\S+/giu, "[url]");
+ for (const value of [botId, secret]) {
+ if (value) redacted = redacted.split(value).join("[redacted]");
+ }
+ return redacted.slice(0, 500);
+}
+
+function quoteContext(
+ body: BaseMessage,
+): IMMessageEvent["replyContext"] | null {
+ const quote = body.quote;
+ if (!quote) return null;
+ const mixedText =
+ quote.mixed?.msg_item
+ .filter((item) => item.msgtype === "text")
+ .map((item) => item.text?.content ?? "")
+ .filter(Boolean)
+ .join("\n") ?? "";
+ const text = quote.text?.content ?? quote.voice?.content ?? mixedText;
+ const attachmentCount =
+ Number(Boolean(quote.image)) +
+ Number(Boolean(quote.file)) +
+ (quote.mixed?.msg_item.filter((item) => item.msgtype === "image").length ??
+ 0);
+ return {
+ author: "引用消息",
+ text: text || "[附件]",
+ ...(attachmentCount ? { attachmentCount } : {}),
+ };
+}
+
+function unsupportedPayload(type: string, label: string) {
+ return {
+ text: "",
+ attachments: [] as IMAttachment[],
+ unsupported: [{ type, label }],
+ };
+}
+
+function extensionForMime(mimeType: string): string {
+ if (mimeType === "image/png") return ".png";
+ if (mimeType === "image/gif") return ".gif";
+ if (mimeType === "image/webp") return ".webp";
+ return ".jpg";
+}
+
+function sanitizeReason(reason: string): string {
+ return String(reason)
+ .replace(/https?:\/\/\S+/giu, "[url]")
+ .replace(/[A-Za-z0-9_-]{32,}/g, "[redacted]")
+ .slice(0, 240);
+}
+
+function safeError(error: unknown): { code: string; message: string } {
+ return {
+ code: errorCode(error),
+ message: sanitizeReason(
+ error instanceof Error ? error.message : String(error),
+ ),
+ };
+}
+
+function errorCode(error: unknown): string {
+ if (!error || typeof error !== "object" || !("code" in error)) return "";
+ return String(error.code);
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
+}
diff --git a/packages/lizi-im/src/wecom/media.ts b/packages/lizi-im/src/wecom/media.ts
new file mode 100644
index 0000000000..a499ebd9aa
--- /dev/null
+++ b/packages/lizi-im/src/wecom/media.ts
@@ -0,0 +1,93 @@
+import { randomUUID } from "node:crypto";
+import fs from "node:fs/promises";
+import path from "node:path";
+
+const MAX_MEDIA_BYTES = 50 * 1024 * 1024;
+const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
+
+const MIME_BY_EXTENSION: Readonly<Record<string, string>> = {
+ ".gif": "image/gif",
+ ".jpeg": "image/jpeg",
+ ".jpg": "image/jpeg",
+ ".png": "image/png",
+ ".webp": "image/webp",
+ ".pdf": "application/pdf",
+ ".txt": "text/plain",
+ ".md": "text/markdown",
+ ".json": "application/json",
+ ".csv": "text/csv",
+ ".zip": "application/zip",
+ ".mp4": "video/mp4",
+ ".mov": "video/quicktime",
+ ".mp3": "audio/mpeg",
+ ".wav": "audio/wav",
+};
+
+export function mimeTypeForFilename(filename: string | undefined): string {
+ const extension = path.extname(filename ?? "").toLowerCase();
+ return MIME_BY_EXTENSION[extension] ?? "application/octet-stream";
+}
+
+export function safeWecomFilename(
+ filename: string | undefined,
+ fallbackExtension = "",
+): string {
+ const base = path
+ .basename(filename?.trim() || `attachment${fallbackExtension}`)
+ .replace(/[<>:"/\\|?*\u0000-\u001f]/g, "_")
+ .replace(/[. ]+$/g, "")
+ .slice(0, 160);
+ return base || `attachment${fallbackExtension}`;
+}
+
+export async function persistWecomDownload(args: {
+ mediaDir: string;
+ buffer: Buffer;
+ filename?: string;
+ fallbackExtension?: string;
+}): Promise<{ absPath: string; originalName: string; mimeType: string }> {
+ if (args.buffer.length === 0) throw new Error("WECOM_MEDIA_EMPTY");
+ if (args.buffer.length > MAX_MEDIA_BYTES)
+ throw new Error("WECOM_MEDIA_TOO_LARGE");
+
+ const originalName = safeWecomFilename(args.filename, args.fallbackExtension);
+ const storageName = `${randomUUID()}-${originalName}`;
+ await fs.mkdir(args.mediaDir, { recursive: true });
+ const absPath = path.join(args.mediaDir, storageName);
+ await fs.writeFile(absPath, args.buffer, { flag: "wx" });
+ return {
+ absPath,
+ originalName,
+ mimeType: mimeTypeForFilename(originalName),
+ };
+}
+
+export async function readWecomOutboundFile(
+ absPath: string,
+ displayName?: string,
+): Promise<{
+ buffer: Buffer;
+ filename: string;
+ mediaType: "file" | "image" | "voice" | "video";
+}> {
+ const stat = await fs.stat(absPath);
+ if (!stat.isFile()) throw new Error("WECOM_FILE_NOT_FOUND");
+ if (stat.size === 0) throw new Error("WECOM_FILE_EMPTY");
+ if (stat.size > MAX_MEDIA_BYTES) throw new Error("WECOM_FILE_TOO_LARGE");
+
+ const filename = safeWecomFilename(displayName || path.basename(absPath));
+ const mimeType = mimeTypeForFilename(filename);
+ const mediaType =
+ mimeType.startsWith("image/") && stat.size <= MAX_IMAGE_BYTES
+ ? "image"
+ : mimeType.startsWith("video/")
+ ? "video"
+ : mimeType.startsWith("audio/")
+ ? "voice"
+ : "file";
+ return {
+ buffer: await fs.readFile(absPath),
+ filename,
+ mediaType,
+ };
+}
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 64aa5db3cf..aec9e6c468 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -836,7 +836,11 @@ export interface SendOptions {
export type TurnPermissionOrigin =
| { kind: 'desktop' }
- | { kind: 'im'; channel: 'feishu' | 'discord' | 'slack' | 'wechat' | 'telegram' | 'dingtalk'; taskId?: string }
+ | {
+ kind: 'im';
+ channel: 'feishu' | 'discord' | 'slack' | 'wechat' | 'telegram' | 'dingtalk' | 'wecom';
+ taskId?: string;
+ }
| { kind: 'scheduler' }
| { kind: 'hook'; source: string };
diff --git a/packages/maker-scheduler/src/types.ts b/packages/maker-scheduler/src/types.ts
index 603299b871..1de5a3467b 100644
--- a/packages/maker-scheduler/src/types.ts
+++ b/packages/maker-scheduler/src/types.ts
@@ -116,6 +116,7 @@ export type JobType = 'prompt' | 'issue-triage';
export interface ScheduleNotifyConfig {
desktop: boolean;
feishu: boolean;
+ wecomGroup?: boolean;
}
/**
diff --git a/packages/maker-shared/src/scheduleForm.ts b/packages/maker-shared/src/scheduleForm.ts
index e1778d9c80..3fc05ccfab 100644
--- a/packages/maker-shared/src/scheduleForm.ts
+++ b/packages/maker-shared/src/scheduleForm.ts
@@ -44,6 +44,7 @@ export interface MobileScheduleDraft {
useWorktree: boolean;
notifyDesktop: boolean;
notifyFeishu: boolean;
+ notifyWecomGroup?: boolean;
targetSessionId: string;
persistentSession: boolean;
silentWhenIdle: boolean;
@@ -106,6 +107,7 @@ export function createMobileScheduleDraft(
useWorktree: workspaceKind === 'project' && !!schedule.useWorktree,
notifyDesktop: schedule.notify?.desktop !== false,
notifyFeishu: schedule.notify?.feishu === true,
+ ...(schedule.notify?.wecomGroup === true ? { notifyWecomGroup: true } : {}),
targetSessionId: schedule.targetSessionId ?? '',
persistentSession: !!schedule.persistentSession,
silentWhenIdle: !!schedule.silentWhenIdle,
@@ -150,6 +152,9 @@ export function applyTemplateToMobileScheduleDraft(
persistentSession: template.persistentSession ?? draft.persistentSession,
notifyDesktop: template.notify?.desktop ?? draft.notifyDesktop,
notifyFeishu: template.notify?.feishu ?? draft.notifyFeishu,
+ ...((template.notify?.wecomGroup ?? draft.notifyWecomGroup) !== undefined
+ ? { notifyWecomGroup: template.notify?.wecomGroup ?? draft.notifyWecomGroup }
+ : {}),
};
}
@@ -253,6 +258,7 @@ export function buildMobileScheduleInput(draft: MobileScheduleDraft): RemoteSche
notify: {
desktop: draft.notifyDesktop,
feishu: draft.notifyFeishu,
+ ...(draft.notifyWecomGroup === true ? { wecomGroup: true } : {}),
},
};
diff --git a/packages/maker-shared/src/scheduleTypes.ts b/packages/maker-shared/src/scheduleTypes.ts
index 2b7af63920..75f2d7a247 100644
--- a/packages/maker-shared/src/scheduleTypes.ts
+++ b/packages/maker-shared/src/scheduleTypes.ts
@@ -9,6 +9,7 @@ export type RemoteTimestamp = number | string | null | undefined;
export interface RemoteScheduleNotifyConfig {
desktop?: boolean;
feishu?: boolean;
+ wecomGroup?: boolean;
}
export interface RemoteScheduleWriteInput {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6d98aba3f5..b5d09d2d71 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -965,6 +965,9 @@ importers:
dingtalk-stream:
specifier: ^2.1.5
version: 2.1.5
+ '@wecom/aibot-node-sdk':
+ specifier: 1.0.7
+ version: 1.0.7
discord.js:
specifier: ^14.16.0
version: 14.27.0
@@ -4752,6 +4755,9 @@ packages:
'@webassemblyjs/[email protected]':
resolution: {integrity: sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw==}
+ '@wecom/[email protected]':
+ resolution: {integrity: sha512-51w+sTqunry6GD3HFvmuh0gArMSJDFE418vyvR1wMJHj1N6DaFuGD3HuaY2fazZs3mb9FWeQFX3+vU5t0Qhwmw==}
+
'@xmldom/[email protected]':
resolution: {integrity: sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==}
engines: {node: '>=10.0.0'}
@@ -14622,6 +14628,17 @@ snapshots:
'@webassemblyjs/ast': 1.14.1
'@xtuc/long': 4.2.2
+ '@wecom/[email protected]':
+ dependencies:
+ axios: 1.18.1
+ eventemitter3: 5.0.4
+ ws: 8.21.1
+ transitivePeerDependencies:
+ - bufferutil
+ - debug
+ - supports-color
+ - utf-8-validate
+
'@xmldom/[email protected]': {}
'@xmldom/[email protected]': {}