@zhin.js/adapter-sandbox 1.1.33 → 1.1.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,63 @@
1
1
  # @zhin.js/adapter-process
2
2
 
3
+ ## 1.1.34
4
+
5
+ ### Patch Changes
6
+
7
+ - e6d7cc1: 配置表单与插件显示名的多语言约定(#1250):Schema 节点沿用已有的 `x-i18n`(`Schema#i18n()`),按 `zh-CN` / `en` 分别声明字段的 `title`、`description` 与 `enumLabels`;插件 `metadata`(`definePlugin` 或 `package.json#zhin.metadata`)新增可选的 `displayNameI18n: { 'zh-CN'?, en? }`,与 `displayName` 一样只能在一处声明,清单只接受这两个键且值必须是非空字符串。Console 插件列表(`/api/plugins`、插件详情)和 `feature.list` / `feature.matrix` 原样带出 `displayNameI18n`,由 Console 按界面语言选择(当前语言 → `en` → `displayName` → 实例 key)。没有这些字段时行为不变。
8
+
9
+ 官方插件补齐中英文配置字段标题与说明(group-suite、repeater、roulette、answers、calendar、ledger、reminder、rss、earthquake、bilibili、content-moderation、lottery、nettools、60s、process-monitor、activity-feedback)以及全部官方插件的中英文显示名。
10
+
11
+ - 70ddaf4: 插件市场元数据(#1250 marketplace-metadata):`package.json#zhin.metadata` 新增可选的 `descriptionI18n: { 'zh-CN'?, en? }`(本地化描述)与 `category`(`adapter`、`ai`、`admin`、`community`、`entertainment`、`game`、`information`、`moderation`、`service`、`utility` 之一),校验方式与 `displayNameI18n` 相同:只接受这两个语言键、值为非空字符串、分类必须在枚举内。这两个字段只能写在清单里,插件市场才能从发布的 `package.json` 读到。`@zhin.js/plugin-runtime` 导出 `PLUGIN_CATEGORIES`、`PLUGIN_CATEGORY_LABELS`、`informativeKeywords`、`packageAuthorName`、`readPluginMarketplaceMetadata` 等读取工具。
12
+
13
+ 市场读取侧:`/pub/marketplace/search` 带出 `displayNameI18n` / `descriptionI18n`,分类读声明的 `category`(旧索引的 `util` 等按别名映射),可选 `locale=zh-CN|en` 按语言解析显示名与描述,并按两种语言的名称与描述搜索;`/pub/marketplace/detail/*` 带出发布清单的显示名、描述翻译与分类。作者一律取 `author`(没有时取 `maintainers`),不再显示发布账号——此前 `plugins.json` 生成脚本优先读 `_npmUser`,CI 可信发布的包因此都显示为「GitHub Actions」。keywords 去掉 `zhin`、`zhin.js`、`bot` 等通用词后展示与参与搜索。`zhin search` / `zhin info` 同样显示中文描述、分类和维护者,`zhin info` 不再读不存在的 `zhin.displayName` / `zhin.category`。
14
+
15
+ 官方插件与适配器:显示名移到 `package.json#zhin.metadata`,补齐中英文描述、分类、3–6 个有信息量的 keywords,author 统一为 `{ name: "lc-cn", url: "https://github.com/zhinjs/zhin" }`(不再发布邮箱);npm `description` 与英文描述一致。
16
+
17
+ - 704c7a4: Sandbox 会话页与功能自助反馈(#1250):
18
+
19
+ - 审批标记:`UserInteractionRequest` 新增可选 `purpose: 'approval'`,Core 渲染为 keyboard 段 `data.purpose`(经正常出站链);IM 审批端口(`createRuntimeApprovalPort`)发出的「操作确认」带此标记。Sandbox 页面只给带 `data.purpose === 'approval'` 的收到消息标「需要你的确认」,游戏卡片的「放弃」、菜单分页等普通按钮消息不再被误标。
20
+ - Sandbox 输入区:顶栏只保留状态、停止 / 重试、对话与轨迹,其余(模拟发送者、运行环境、运行检查器、清空会话)收进「更多」菜单;底部快捷键提示改为可折叠;快捷命令不再写死 `/help`、`ping`、`/status`,改由新接口 `GET /api/conversations/workspaces/commands`(权限 `endpoint.view`)按该会话的命令索引与 endpoint 实际 `commandPrefix` 生成(菜单的真实命令名优先,无前缀不带 `/`,未注册的命令不出现)。
21
+ - 功能覆盖记录操作者:`feature_overrides.updated_by` 在同一文本列内记录结构化写入者(来源 `chat` / `console` / `cli`、聊天身份 adapter + 平台用户 ID + 显示名,或 Console 用户 principal id + 显示名),旧记录照常读取(`chat:…` / `user:…` 推出身份)。`feature.get` 与 `feature.conversations` 返回可选 `operator`:只有对该层级有 `feature.configure` 的调用方看到完整写入者(Console 用户 id 与显示名、聊天身份与名字),仅有 `feature.view` 的只看到来源(`{ source }`)。能解析时返回会话显示名(Sandbox 会话名),只按该会话所属的 Sandbox Endpoint(适配器 + Endpoint)及其当前 owner 匹配,且只返回给同时有 `endpoint.view` 的调用方(与工作区目录同一权限)。**降级注意**:写入过结构化写入者的行,在旧版本里 `updatedBy` 会原样显示为 JSON 字符串(`{"f":1,"by":…,"op":…}`),不影响读取与覆盖生效。
22
+ - Sandbox 输入区新增「@ 机器人」按钮:插入对当前机器人(ready 帧的 endpoint id)的 mention,文本形式为 `[@<机器人 id>]`,与入站 `[@机器人名]` 解析一致;@ 候选列表里的机器人条目改为真实 id;快捷操作帮助同步说明。
23
+ - 页面兜底渲染:不认识的段不再只显示 `[type]`——`markdown` 显示原文,keyboard 与未渲染的 JSX(`{"$jsx":…}`)读出文本、按钮降级为 `[按钮标签]`,不再出现原始 JSX 对象。
24
+
25
+ 已知限制:Sandbox 页面的「需要你的确认」标记只用于展示,依据收到消息里 keyboard 段的 `data.purpose`;能自行构造该段的插件可以让普通按钮也显示这个标记(不影响审批本身的鉴权)。
26
+
27
+ - 4922472: 沙盒(#1250):会话记录加载期间消息区保持与空状态相同的高度并显示「正在加载会话记录…」;快捷命令按钮可用键盘到达(Tab),鼠标点击不会把焦点留在按钮上;点击后只预填输入框并把焦点移到输入框,由回车或「发送」发出,避免布局变化后一次点击加一次回车连发两条。输入框为空时直接填入命令;已有草稿(文字、图片、表情、@)时把命令插入到光标处(光标不在输入框内则插到开头),不删除草稿,并保留撤销记录。
28
+ - 713853a: Sandbox:群聊里输入的 `[@<机器人 id 或 nickname>]` 现在解析为对机器人的 mention(此前只是普通文本,消息被静默忽略);其他 `[@名称]` 解析为普通 mention 段。(#1250)
29
+ - Updated dependencies [ab14f22]
30
+ - Updated dependencies [b3ba941]
31
+ - Updated dependencies [7cd299e]
32
+ - Updated dependencies [7cd299e]
33
+ - Updated dependencies [7126d03]
34
+ - Updated dependencies [9026329]
35
+ - Updated dependencies [1d1746e]
36
+ - Updated dependencies [252d5dc]
37
+ - Updated dependencies [71aa159]
38
+ - Updated dependencies [ccab2c1]
39
+ - Updated dependencies [b00725c]
40
+ - Updated dependencies [c6b5563]
41
+ - Updated dependencies [f1a9745]
42
+ - Updated dependencies [e0b4e51]
43
+ - Updated dependencies [cca4427]
44
+ - Updated dependencies [627fb5e]
45
+ - Updated dependencies [70ddaf4]
46
+ - Updated dependencies [b08cff2]
47
+ - Updated dependencies [dbdfca3]
48
+ - Updated dependencies [704c7a4]
49
+ - Updated dependencies [b56cca9]
50
+ - Updated dependencies [f3910f1]
51
+ - Updated dependencies [07bd3dc]
52
+ - @zhin.js/client@1.2.0
53
+ - @zhin.js/host-http@1.3.0
54
+ - @zhin.js/core@1.8.0
55
+ - @zhin.js/adapter@1.3.0
56
+ - @zhin.js/im-contract@1.2.0
57
+ - @zhin.js/console-contract@1.2.0
58
+ - @zhin.js/page@1.1.20
59
+ - @zhin.js/feature-kit@1.1.18
60
+
3
61
  ## 1.1.33
4
62
 
5
63
  ### Patch Changes
package/README.md CHANGED
@@ -150,6 +150,7 @@ Console 沙盒页和自己写的测试客户端都用这套协议。每个 WebSo
150
150
 
151
151
  - 帧内容不是 JSON 时,整段文本按一条纯文本消息处理。
152
152
  - 消息的发送者固定为 endpoint 的 `owner`。
153
+ - **@ 提及**:文本里的 `[@名称]` 解析为 `mention` 段。名称等于 endpoint 的 `id`(如 `sandbox-bot`)或配置的 `nickname`(不区分大小写)时视为 @ 机器人:群聊里 `[@sandbox-bot] /help` 会被识别为对机器人说话,且命令文本去掉这段提及(`/help`);其他名称保留为 `@名称`。从输入框 @ 选择器插入的 `mention` 段若带的是机器人名称,也会改写成机器人 `id`。
153
154
  - **按钮回传**:`content` 中的 `{ "type": "action", "data": { "id": "...", "payload": "..." } }` 段会作为交互动作交给命令或 Agent;只填 `id` 或 `payload` 时,另一个取相同的值。消息里没有文本时,`payload` 作为消息文本。
154
155
 
155
156
  `agentRun` 字段:
package/lib/endpoint.js CHANGED
@@ -277,7 +277,10 @@ export class SandboxWsEndpoint extends SandboxClient {
277
277
  }));
278
278
  return;
279
279
  }
280
- const frame = parseSandboxWsFrame(raw);
280
+ const frame = parseSandboxWsFrame(raw, {
281
+ id: this.#options.defaults.id,
282
+ ...(this.#options.defaults.nickname ? { names: [this.#options.defaults.nickname] } : {}),
283
+ });
281
284
  if (frame.kind === 'invalid') {
282
285
  socket.send(JSON.stringify({
283
286
  type: 'error', endpoint: target, connectionId,
package/lib/protocol.d.ts CHANGED
@@ -29,6 +29,8 @@ export type ResolvedSandboxBot = {
29
29
  readonly randomNamePerConnection: boolean;
30
30
  readonly streaming: boolean;
31
31
  readonly streamingIntervalMs: number;
32
+ /** Configured `nickname`; `[@nickname]` also mentions this bot. */
33
+ readonly nickname?: string;
32
34
  };
33
35
  /** One endpoint config after AdapterIndex expands `plugins.<instanceKey>.endpoints`. */
34
36
  export interface SandboxEndpointConfig extends EndpointProfileConfiguration {
@@ -74,9 +76,18 @@ export type SandboxWsFrame = {
74
76
  } | {
75
77
  readonly kind: 'invalid';
76
78
  };
79
+ /**
80
+ * The bot this socket talks to. Typed `[@<id or name>]` text (the input hint the Sandbox page shows)
81
+ * becomes a mention segment; a match on `id` or one of `names` (case-insensitive) targets `id`,
82
+ * so the IM layer recognises it as a mention of the bot.
83
+ */
84
+ export interface SandboxSelfMention {
85
+ readonly id: string;
86
+ readonly names?: readonly string[];
87
+ }
77
88
  /** Control frames never fall through into chat or platform message hooks. */
78
- export declare function parseSandboxWsFrame(raw: string): SandboxWsFrame;
79
- export declare function parseSandboxWsPayload(raw: string): SandboxParsedMessage;
89
+ export declare function parseSandboxWsFrame(raw: string, self?: SandboxSelfMention): SandboxWsFrame;
90
+ export declare function parseSandboxWsPayload(raw: string, self?: SandboxSelfMention): SandboxParsedMessage;
80
91
  export declare const parseSandboxInboundPayload: typeof parseSandboxWsPayload;
81
92
  /**
82
93
  * 入站归一化 → ConversationRef。sandbox 无平台社交图谱:
package/lib/protocol.js CHANGED
@@ -47,6 +47,7 @@ export function resolveSandboxEndpoint(config) {
47
47
  randomNamePerConnection: false,
48
48
  streaming: config.streaming !== false,
49
49
  streamingIntervalMs,
50
+ ...(optionalEndpointField(config.nickname) ? { nickname: optionalEndpointField(config.nickname) } : {}),
50
51
  };
51
52
  }
52
53
  function optionalEndpointField(value) {
@@ -106,8 +107,65 @@ function readSandboxWirePayload(raw) {
106
107
  return { text: raw };
107
108
  }
108
109
  }
110
+ const TYPED_MENTION = /\[@([^\[\]\n]{1,64})\]/gu;
111
+ function expandTypedMentions(content, text, self) {
112
+ const selfKeys = new Set([self?.id, ...(self?.names ?? [])]
113
+ .flatMap(value => typeof value === 'string' && value.trim() ? [value.trim().toLowerCase()] : []));
114
+ const resolve = (name) => {
115
+ const trimmed = name.trim();
116
+ return self && selfKeys.has(trimmed.toLowerCase()) ? { target: self.id, self: true } : { target: trimmed, self: false };
117
+ };
118
+ let expanded = false;
119
+ const next = [];
120
+ for (const segment of content) {
121
+ // A picked mention (`mention` segment) may carry the bot's name instead of its id.
122
+ if ((segment.type === 'mention' || segment.type === 'at') && self && typeof segment.data?.target === 'string'
123
+ && segment.data.target !== self.id && selfKeys.has(segment.data.target.trim().toLowerCase())) {
124
+ expanded = true;
125
+ next.push({ ...segment, data: { ...segment.data, target: self.id } });
126
+ continue;
127
+ }
128
+ const value = segment.type === 'text' ? segment.data?.text : undefined;
129
+ if (typeof value !== 'string' || !value.includes('[@')) {
130
+ next.push(segment);
131
+ continue;
132
+ }
133
+ let last = 0;
134
+ for (const match of value.matchAll(TYPED_MENTION)) {
135
+ const name = match[1];
136
+ if (!name.trim())
137
+ continue;
138
+ expanded = true;
139
+ if (match.index > last)
140
+ next.push({ type: 'text', data: { text: value.slice(last, match.index) } });
141
+ const { target } = resolve(name);
142
+ next.push({ type: 'mention', data: { target, name: name.trim() } });
143
+ last = match.index + match[0].length;
144
+ }
145
+ if (last === 0)
146
+ next.push(segment);
147
+ else if (last < value.length)
148
+ next.push({ type: 'text', data: { text: value.slice(last) } });
149
+ }
150
+ if (!expanded)
151
+ return { content, text };
152
+ // Plain-text view: drop mentions of the bot (like other platforms strip the at-self prefix),
153
+ // keep `@name` for anyone else so commands and the Agent still see who was addressed.
154
+ let removedSelf = false;
155
+ const plain = text.replace(TYPED_MENTION, (whole, name) => {
156
+ if (!name.trim())
157
+ return whole;
158
+ const resolved = resolve(name);
159
+ if (resolved.self) {
160
+ removedSelf = true;
161
+ return '';
162
+ }
163
+ return `@${resolved.target}`;
164
+ });
165
+ return { content: next, text: removedSelf ? plain.replace(/[ \t]{2,}/gu, ' ').trim() : plain };
166
+ }
109
167
  /** Control frames never fall through into chat or platform message hooks. */
110
- export function parseSandboxWsFrame(raw) {
168
+ export function parseSandboxWsFrame(raw, self) {
111
169
  const payload = readSandboxWirePayload(raw);
112
170
  if ('op' in payload) {
113
171
  const conversation = payload.conversation;
@@ -117,25 +175,25 @@ export function parseSandboxWsFrame(raw) {
117
175
  return { kind: 'invalid' };
118
176
  return { kind: 'subscribe', conversation: { type: conversation.type, id: conversation.id } };
119
177
  }
120
- const message = normalizeSandboxWsPayload(payload, raw);
178
+ const message = normalizeSandboxWsPayload(payload, raw, self);
121
179
  if (!['private', 'direct', 'group', 'channel', 'guild'].includes(message.type)
122
180
  || typeof message.id !== 'string')
123
181
  return { kind: 'invalid' };
124
182
  return { kind: 'message', message };
125
183
  }
126
- export function parseSandboxWsPayload(raw) {
127
- return normalizeSandboxWsPayload(readSandboxWirePayload(raw), raw);
184
+ export function parseSandboxWsPayload(raw, self) {
185
+ return normalizeSandboxWsPayload(readSandboxWirePayload(raw), raw, self);
128
186
  }
129
187
  export const parseSandboxInboundPayload = parseSandboxWsPayload;
130
- function normalizeSandboxWsPayload(payload, raw) {
188
+ function normalizeSandboxWsPayload(payload, raw, self) {
131
189
  const type = payload.type ?? 'private';
132
190
  const id = payload.id ?? 'sandbox-user';
133
- const content = typeof payload.content === 'string'
191
+ const wireContent = typeof payload.content === 'string'
134
192
  ? [{ type: 'text', data: { text: payload.content } }]
135
193
  : Array.isArray(payload.content)
136
194
  ? payload.content
137
195
  : [{ type: 'text', data: { text: payload.text ?? raw } }];
138
- const actionSegment = content.find((segment) => segment.type === 'action');
196
+ const actionSegment = wireContent.find((segment) => segment.type === 'action');
139
197
  let action;
140
198
  if (actionSegment?.data) {
141
199
  const actionPayload = typeof actionSegment.data.payload === 'string'
@@ -150,7 +208,7 @@ function normalizeSandboxWsPayload(payload, raw) {
150
208
  action = { id: actionId || actionPayload, payload: actionPayload || actionId };
151
209
  }
152
210
  }
153
- let text = content
211
+ let text = wireContent
154
212
  .flatMap((segment) => (segment.type === 'text' && typeof segment.data?.text === 'string'
155
213
  ? [segment.data.text]
156
214
  : []))
@@ -160,6 +218,9 @@ function normalizeSandboxWsPayload(payload, raw) {
160
218
  ? payload.text
161
219
  : action?.payload ?? raw;
162
220
  }
221
+ const typed = expandTypedMentions(wireContent, text, self);
222
+ const content = typed.content;
223
+ text = typed.text;
163
224
  const agentRun = normalizeSandboxAgentRunConfig(payload.agentRun);
164
225
  const rawMessageId = typeof payload.messageId === 'string' ? payload.messageId.trim() : '';
165
226
  const messageId = /^[A-Za-z0-9._:-]{1,160}$/u.test(rawMessageId) ? rawMessageId : undefined;
package/package.json CHANGED
@@ -1,7 +1,17 @@
1
1
  {
2
2
  "name": "@zhin.js/adapter-sandbox",
3
- "version": "1.1.33",
4
- "description": "Zhin.js Sandbox adapter for Plugin Runtime (WebSocket /sandbox)",
3
+ "version": "1.1.34",
4
+ "description": "Sandbox adapter: a local chat workspace for the Remote Console, for development and testing without a real platform.",
5
+ "keywords": [
6
+ "zhin.js",
7
+ "sandbox",
8
+ "testing",
9
+ "development"
10
+ ],
11
+ "author": {
12
+ "name": "lc-cn",
13
+ "url": "https://github.com/zhinjs/zhin"
14
+ },
5
15
  "type": "module",
6
16
  "main": "./lib/index.js",
7
17
  "types": "./lib/index.d.ts",
@@ -21,21 +31,6 @@
21
31
  "README.md",
22
32
  "CHANGELOG.md"
23
33
  ],
24
- "keywords": [
25
- "zhin",
26
- "zhin.js",
27
- "bot",
28
- "adapter",
29
- "sandbox",
30
- "test",
31
- "development",
32
- "local"
33
- ],
34
- "author": {
35
- "name": "lc-cn",
36
- "email": "admin@liucl.cn",
37
- "url": "https://github.com/lc-cn"
38
- },
39
34
  "license": "MIT",
40
35
  "repository": {
41
36
  "url": "git+https://github.com/zhinjs/zhin.git",
@@ -44,15 +39,15 @@
44
39
  },
45
40
  "dependencies": {
46
41
  "lucide-react": "^0.525.0",
47
- "@zhin.js/adapter": "1.1.34",
48
- "@zhin.js/client": "1.1.34",
49
- "@zhin.js/console-contract": "1.1.6",
50
- "@zhin.js/core": "1.7.0",
51
- "@zhin.js/feature-kit": "1.1.17",
52
- "@zhin.js/host-http": "1.2.2",
53
- "@zhin.js/im-contract": "1.1.14",
42
+ "@zhin.js/adapter": "1.3.0",
43
+ "@zhin.js/client": "1.2.0",
44
+ "@zhin.js/console-contract": "1.2.0",
45
+ "@zhin.js/core": "1.8.0",
46
+ "@zhin.js/feature-kit": "1.1.18",
47
+ "@zhin.js/host-http": "1.3.0",
48
+ "@zhin.js/im-contract": "1.2.0",
54
49
  "@zhin.js/logger": "1.1.3",
55
- "@zhin.js/page": "1.1.19"
50
+ "@zhin.js/page": "1.1.20"
56
51
  },
57
52
  "devDependencies": {
58
53
  "@types/react": "^19.2.18",
@@ -61,18 +56,18 @@
61
56
  "typescript": "^6.0.3",
62
57
  "vitest": "^4.1.10",
63
58
  "ws": "^8.21.1",
64
- "@zhin.js/pagemanager": "1.1.27",
65
- "@zhin.js/runtime": "1.2.2",
66
- "zhin.js": "1.2.0"
59
+ "@zhin.js/pagemanager": "1.1.28",
60
+ "@zhin.js/runtime": "1.3.0",
61
+ "zhin.js": "1.3.0"
67
62
  },
68
63
  "peerDependencies": {
69
64
  "react": "^19.0.0",
70
- "@zhin.js/adapter": "^1.1.34",
71
- "@zhin.js/console-contract": "^1.1.6",
72
- "@zhin.js/core": "^1.7.0",
73
- "@zhin.js/host-http": "^1.2.2",
74
- "@zhin.js/page": "^1.1.19",
75
- "zhin.js": "^1.2.0"
65
+ "@zhin.js/adapter": "^1.3.0",
66
+ "@zhin.js/console-contract": "^1.2.0",
67
+ "@zhin.js/core": "^1.8.0",
68
+ "@zhin.js/host-http": "^1.3.0",
69
+ "@zhin.js/page": "^1.1.20",
70
+ "zhin.js": "^1.3.0"
76
71
  },
77
72
  "peerDependenciesMeta": {
78
73
  "react": {
@@ -102,7 +97,19 @@
102
97
  "api": "^1.0.0"
103
98
  }
104
99
  ],
105
- "plugins": []
100
+ "plugins": [],
101
+ "metadata": {
102
+ "displayName": "Sandbox Adapter",
103
+ "displayNameI18n": {
104
+ "zh-CN": "沙盒适配器",
105
+ "en": "Sandbox Adapter"
106
+ },
107
+ "descriptionI18n": {
108
+ "zh-CN": "沙盒适配器:为 Remote Console 提供本地会话工作区,用于开发和测试,无需接入真实平台。",
109
+ "en": "Sandbox adapter: a local chat workspace for the Remote Console, for development and testing without a real platform."
110
+ },
111
+ "category": "adapter"
112
+ }
106
113
  },
107
114
  "scripts": {
108
115
  "build": "tsc",
@@ -199,6 +199,55 @@ const RichTextEditor = forwardRef(({ locale = 'zh-CN', placeholder = sandboxText
199
199
  handleChange();
200
200
  }
201
201
  };
202
+ // Quick-command prefill (#1250). An empty composer gets the command; a non-empty draft
203
+ // (text, images, faces, mentions) is never overwritten: the command is inserted at the
204
+ // caret, or at the start when the caret is outside the editor. `insertText` keeps the
205
+ // browser undo stack; the Range fallback dispatches `input` so state stays in sync.
206
+ const setText = (text) => {
207
+ const editor = editorRef.current;
208
+ if (!editor)
209
+ return;
210
+ const draftIsEmpty = (editor.textContent ?? '').trim() === ''
211
+ && editor.querySelector('img, [data-type], [data-url], [contenteditable="false"]') === null;
212
+ const selection = window.getSelection();
213
+ const caretInEditor = !!selection && selection.rangeCount > 0
214
+ && editor.contains(selection.getRangeAt(0).commonAncestorContainer);
215
+ editor.focus();
216
+ if (!selection)
217
+ return;
218
+ const range = document.createRange();
219
+ let insertion = text;
220
+ if (draftIsEmpty) {
221
+ // Only whitespace / <br> placeholders: replace them with the command.
222
+ range.selectNodeContents(editor);
223
+ }
224
+ else if (caretInEditor) {
225
+ // Collapse a selection to its end so no selected draft content is replaced.
226
+ const current = selection.getRangeAt(0);
227
+ range.setStart(current.endContainer, current.endOffset);
228
+ range.collapse(true);
229
+ }
230
+ else {
231
+ range.setStart(editor, 0);
232
+ range.collapse(true);
233
+ insertion = `${text} `;
234
+ }
235
+ selection.removeAllRanges();
236
+ selection.addRange(range);
237
+ // execCommand is deprecated but remains the only undo-preserving insertion API for contentEditable.
238
+ const inserted = typeof document.execCommand === 'function' && document.execCommand('insertText', false, insertion);
239
+ if (!inserted) {
240
+ const node = document.createTextNode(insertion);
241
+ range.deleteContents();
242
+ range.insertNode(node);
243
+ range.setStartAfter(node);
244
+ range.collapse(true);
245
+ selection.removeAllRanges();
246
+ selection.addRange(range);
247
+ editor.dispatchEvent(new Event('input', { bubbles: true }));
248
+ }
249
+ handleChange();
250
+ };
202
251
  // 聚焦编辑器
203
252
  const focus = () => {
204
253
  editorRef.current?.focus();
@@ -339,6 +388,7 @@ const RichTextEditor = forwardRef(({ locale = 'zh-CN', placeholder = sandboxText
339
388
  useImperativeHandle(ref, () => ({
340
389
  focus,
341
390
  clear,
391
+ setText,
342
392
  insertFace,
343
393
  insertImage,
344
394
  insertVideo,
@@ -19,6 +19,8 @@ export interface RichTextEditorProps {
19
19
  export interface RichTextEditorRef {
20
20
  focus: () => void
21
21
  clear: () => void
22
+ /** Quick-command prefill: fills an empty draft, otherwise inserts at the caret without deleting the draft; never sends. */
23
+ setText: (text: string) => void
22
24
  insertFace: (faceId: number) => void
23
25
  insertImage: (url: string) => void
24
26
  insertVideo: (url: string) => void
@@ -236,6 +238,52 @@ const RichTextEditor = forwardRef<RichTextEditorRef, RichTextEditorProps>(
236
238
  }
237
239
  }
238
240
 
241
+ // Quick-command prefill (#1250). An empty composer gets the command; a non-empty draft
242
+ // (text, images, faces, mentions) is never overwritten: the command is inserted at the
243
+ // caret, or at the start when the caret is outside the editor. `insertText` keeps the
244
+ // browser undo stack; the Range fallback dispatches `input` so state stays in sync.
245
+ const setText = (text: string) => {
246
+ const editor = editorRef.current
247
+ if (!editor) return
248
+ const draftIsEmpty = (editor.textContent ?? '').trim() === ''
249
+ && editor.querySelector('img, [data-type], [data-url], [contenteditable="false"]') === null
250
+ const selection = window.getSelection()
251
+ const caretInEditor = !!selection && selection.rangeCount > 0
252
+ && editor.contains(selection.getRangeAt(0).commonAncestorContainer)
253
+ editor.focus()
254
+ if (!selection) return
255
+ const range = document.createRange()
256
+ let insertion = text
257
+ if (draftIsEmpty) {
258
+ // Only whitespace / <br> placeholders: replace them with the command.
259
+ range.selectNodeContents(editor)
260
+ } else if (caretInEditor) {
261
+ // Collapse a selection to its end so no selected draft content is replaced.
262
+ const current = selection.getRangeAt(0)
263
+ range.setStart(current.endContainer, current.endOffset)
264
+ range.collapse(true)
265
+ } else {
266
+ range.setStart(editor, 0)
267
+ range.collapse(true)
268
+ insertion = `${text} `
269
+ }
270
+ selection.removeAllRanges()
271
+ selection.addRange(range)
272
+ // execCommand is deprecated but remains the only undo-preserving insertion API for contentEditable.
273
+ const inserted = typeof document.execCommand === 'function' && document.execCommand('insertText', false, insertion)
274
+ if (!inserted) {
275
+ const node = document.createTextNode(insertion)
276
+ range.deleteContents()
277
+ range.insertNode(node)
278
+ range.setStartAfter(node)
279
+ range.collapse(true)
280
+ selection.removeAllRanges()
281
+ selection.addRange(range)
282
+ editor.dispatchEvent(new Event('input', { bubbles: true }))
283
+ }
284
+ handleChange()
285
+ }
286
+
239
287
  // 聚焦编辑器
240
288
  const focus = () => {
241
289
  editorRef.current?.focus()
@@ -399,6 +447,7 @@ const RichTextEditor = forwardRef<RichTextEditorRef, RichTextEditorProps>(
399
447
  useImperativeHandle(ref, () => ({
400
448
  focus,
401
449
  clear,
450
+ setText,
402
451
  insertFace,
403
452
  insertImage,
404
453
  insertVideo,