ai_co_discuss 0.4.58 → 0.4.60

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.
@@ -13,7 +13,7 @@ import time
13
13
  from .runtime import begin_write, require_owner
14
14
  from .texts import Text, load_texts, save_text
15
15
 
16
- QUEUED_FIELDS = ("author", "text", "reply_to", "kind", "submitted_by", "to", "sequential", "order", "attachment_ids", "submission_id")
16
+ QUEUED_FIELDS = ("author", "text", "reply_to", "kind", "submitted_by", "to", "sequential", "order", "attachment_ids", "attachment_start", "submission_id")
17
17
  QUEUE_ACTIONS = ("send", "edit", "delete", "reorder", "resume", "queueing")
18
18
  QUEUE_ERRORS = (ValueError, TypeError, LookupError, PermissionError, FileExistsError)
19
19
 
@@ -54,8 +54,10 @@ def check_mode_command(connection, room_id, payload):
54
54
  if not parsed:
55
55
  return None
56
56
  mode, command, argument = parsed
57
- if payload.get("to"):
58
- raise ValueError(Text("/{mode} 命令不能同时 @ 成员", mode=mode))
57
+ # The host runs the goal or discussion, so naming it changes nothing; naming anyone else would wake nobody.
58
+ host = connection.execute("SELECT name FROM room_members WHERE room_id=? AND role='host' AND status='active'", (room_id,)).fetchone()
59
+ if any(name != (host["name"] if host else None) for name in payload.get("to") or []):
60
+ raise ValueError(Text("/{mode} 命令只能 @ 主持人;要请其他成员参与,开启后由主持人安排", mode=mode))
59
61
  if mode == "goal":
60
62
  goal_room.check_goal_command(connection, room_id, command, argument)
61
63
  else:
package/backend/server.py CHANGED
@@ -507,6 +507,8 @@ def require_room(connection, room_id):
507
507
  room["texts"] = room_display_texts(connection, room)
508
508
  room["archived"] = bool(connection.execute("SELECT archived FROM room_directory WHERE room_id=?", (room_id,)).fetchone()[0])
509
509
  room["folder_id"] = connection.execute("SELECT folder_id FROM room_folder_assignments WHERE room_id=?", (room_id,)).fetchone()[0]
510
+ # The number the next sent file takes, so the composer shows `[图片 #n]` as it will be saved.
511
+ room["next_attachment_number"] = attachment_number_before(connection, room_id, None)
510
512
  settings = connection.execute("SELECT host,background,boundaries,experts,focus FROM topic_settings WHERE room_id=?",
511
513
  (room_id,)).fetchone()
512
514
  room.update(dict(settings) if settings else topic_defaults())
@@ -1318,6 +1320,51 @@ def attachment_view(row):
1318
1320
  return result
1319
1321
 
1320
1322
 
1323
+ ATTACHMENT_PLACEHOLDER = re.compile(r"\[(图片|文件) #(\d{1,4})\]")
1324
+
1325
+
1326
+ def attachment_number_before(connection, room_id, message_id):
1327
+ """The room-wide number of the first file of message `message_id` (of the next file sent when None).
1328
+
1329
+ Files are numbered across the whole room in message order, as Claude Code numbers pasted images across a
1330
+ conversation, so `[图片 #n]` names one file wherever it is quoted."""
1331
+ if message_id is None:
1332
+ query, params = "SELECT COUNT(*) FROM attachments WHERE room_id=? AND message_id IS NOT NULL", (room_id,)
1333
+ else:
1334
+ query, params = "SELECT COUNT(*) FROM attachments WHERE room_id=? AND message_id IS NOT NULL AND message_id<?", (room_id, message_id)
1335
+ return connection.execute(query, params).fetchone()[0] + 1
1336
+
1337
+
1338
+ def renumber_placeholders(text, payload, count, start):
1339
+ """Turn the sender's `[图片 #n]` numbering into the numbers the files took.
1340
+
1341
+ The sender numbered its `count` files from `attachment_start` (the page shows the room's next number; a CLI
1342
+ member, which sends none, numbers them from 1 within its message); placeholders outside that range are left."""
1343
+ assumed = payload.get("attachment_start")
1344
+ assumed = assumed if isinstance(assumed, int) and not isinstance(assumed, bool) and assumed >= 1 else 1
1345
+ if not count or assumed == start:
1346
+ return text
1347
+ def shift(match):
1348
+ number = int(match.group(2))
1349
+ return f"[{match.group(1)} #{number - assumed + start}]" if assumed <= number < assumed + count else match.group(0)
1350
+ return ATTACHMENT_PLACEHOLDER.sub(shift, text)
1351
+
1352
+
1353
+ def link_message_attachments(connection, room_id, message_id, identifiers, text, payload):
1354
+ """Link the files to their new message and renumber its placeholders room-wide."""
1355
+ for position, identifier in enumerate(identifiers):
1356
+ connection.execute("UPDATE attachments SET message_id=?,position=? WHERE id=?", (message_id, position, identifier))
1357
+ numbered = renumber_placeholders(text, payload, len(identifiers), attachment_number_before(connection, room_id, message_id))
1358
+ if numbered != text:
1359
+ connection.execute("UPDATE messages SET text=? WHERE id=?", (numbered, message_id))
1360
+
1361
+
1362
+ def renumbered_expected(expected, payload, previous):
1363
+ """A retried submission's fields as they were saved: its placeholders renumbered from the files' first number."""
1364
+ files = previous["attachments"]
1365
+ return {**expected, "text": renumber_placeholders(expected["text"], payload, len(files), files[0]["number"])} if files else expected
1366
+
1367
+
1321
1368
  def message_with_attachments(connection, row):
1322
1369
  """Attach the published file list to an original message."""
1323
1370
  message = dict(row)
@@ -1326,8 +1373,9 @@ def message_with_attachments(connection, row):
1326
1373
  return {**message, "text": "", "summary": "", "suggestions": [], "attachments": []}
1327
1374
  message["texts"] = load_texts(connection, "message", message["id"])
1328
1375
  message["suggestions"] = message_suggestions(connection, message["id"])
1329
- message["attachments"] = [attachment_view(item) for item in connection.execute(
1330
- "SELECT * FROM attachments WHERE message_id=? ORDER BY position,id", (message["id"],))]
1376
+ files = connection.execute("SELECT * FROM attachments WHERE message_id=? ORDER BY position,id", (message["id"],)).fetchall()
1377
+ first = attachment_number_before(connection, message["room_id"], message["id"]) if files else 0
1378
+ message["attachments"] = [{**attachment_view(item), "number": first + index} for index, item in enumerate(files)]
1331
1379
  return message
1332
1380
 
1333
1381
 
@@ -1364,7 +1412,8 @@ def query_attachments(connection, room_id, params, token=""):
1364
1412
  total = connection.execute(f"SELECT COUNT(*) FROM attachments WHERE {where}", values).fetchone()[0]
1365
1413
  rows = connection.execute(f"SELECT * FROM attachments WHERE {where} ORDER BY created_at,id LIMIT ? OFFSET ?",
1366
1414
  [*values, PAGE_SIZE, (page - 1) * PAGE_SIZE])
1367
- return {"attachments": [attachment_view(row) for row in rows], "page": page, "total": total,
1415
+ return {"attachments": [{**attachment_view(row), **({"number": attachment_number_before(connection, room_id, row["message_id"]) + row["position"]}
1416
+ if row["message_id"] is not None else {})} for row in rows], "page": page, "total": total,
1368
1417
  "pages": max(1, (total + PAGE_SIZE - 1) // PAGE_SIZE)}
1369
1418
 
1370
1419
 
@@ -1475,7 +1524,7 @@ def append_free_message(connection, room, payload, actor):
1475
1524
  previous = connection.execute(f"{MESSAGE_QUERY} WHERE room_id=? AND submission_id=?", (room_id, submission_id)).fetchone()
1476
1525
  if previous:
1477
1526
  previous = message_with_attachments(connection, previous)
1478
- if (any(previous[key] != expected[key] for key in ("author", "text", "reply_to", "kind", "submitted_by", "summary", "summary_by"))
1527
+ if (any(previous[key] != renumbered_expected(expected, payload, previous)[key] for key in ("author", "text", "reply_to", "kind", "submitted_by", "summary", "summary_by"))
1479
1528
  or [item["id"] for item in previous["attachments"]] != identifiers):
1480
1529
  raise FileExistsError(Text('这个提交编号已被另一条内容使用,请为新发言生成新编号'))
1481
1530
  check_review_retry(connection, room_id, previous["id"], payload)
@@ -1498,8 +1547,7 @@ def append_free_message(connection, room, payload, actor):
1498
1547
  (cursor.lastrowid, "chat", submitted_by))
1499
1548
  connection.execute("INSERT INTO message_summaries (message_id,text,author) VALUES (?,?,?)",
1500
1549
  (cursor.lastrowid, expected["summary"], expected["summary_by"]))
1501
- for position, identifier in enumerate(identifiers):
1502
- connection.execute("UPDATE attachments SET message_id=?,position=? WHERE id=?", (cursor.lastrowid, position, identifier))
1550
+ link_message_attachments(connection, room_id, cursor.lastrowid, identifiers, text, payload)
1503
1551
  # A captured reply keeps its text, but its mentions wake nobody: only a submitted answer may ask for a host.
1504
1552
  if expected["source"] != "auto":
1505
1553
  save_suggestions(connection, room_id, cursor.lastrowid, actor, payload)
@@ -1550,7 +1598,7 @@ def append_free_moderation(connection, room, payload, actor):
1550
1598
  previous = connection.execute(f"{MESSAGE_QUERY} WHERE room_id=? AND submission_id=?", (room["id"], submission_id)).fetchone()
1551
1599
  if previous:
1552
1600
  previous = message_with_attachments(connection, previous)
1553
- if any(previous[key] != expected[key] for key in ("author", "text", "reply_to", "kind", "submitted_by", "summary", "summary_by")) or [item["id"] for item in previous["attachments"]] != identifiers:
1601
+ if any(previous[key] != renumbered_expected(expected, payload, previous)[key] for key in ("author", "text", "reply_to", "kind", "submitted_by", "summary", "summary_by")) or [item["id"] for item in previous["attachments"]] != identifiers:
1554
1602
  raise FileExistsError(Text('这个提交编号已被另一条内容使用,请为新发言生成新编号'))
1555
1603
  return {"message": previous, "duplicate": True}
1556
1604
  check_message_references(connection, room["id"], expected)
@@ -1561,8 +1609,7 @@ def append_free_moderation(connection, room, payload, actor):
1561
1609
  (cursor.lastrowid, "moderation", author))
1562
1610
  connection.execute("INSERT INTO message_summaries (message_id,text,author) VALUES (?,?,?)",
1563
1611
  (cursor.lastrowid, "", ""))
1564
- for position, identifier in enumerate(identifiers):
1565
- connection.execute("UPDATE attachments SET message_id=?,position=? WHERE id=?", (cursor.lastrowid, position, identifier))
1612
+ link_message_attachments(connection, room["id"], cursor.lastrowid, identifiers, text, payload)
1566
1613
  saved_message = connection.execute(f"{MESSAGE_QUERY} WHERE messages.id=?", (cursor.lastrowid,)).fetchone()
1567
1614
  return {"message": message_with_attachments(connection, saved_message), "duplicate": False}
1568
1615
 
package/docs/runner.md CHANGED
@@ -121,7 +121,7 @@ API 成员在房间里的工作由 [Pi](https://github.com/earendil-works/pi)
121
121
 
122
122
  API 成员可以担任专家或主持人。房间指定了项目目录时,它可以用接入程序提供的文件工具读取、搜索项目文件;项目权限设为可写时还能新建和编辑文件,但没有命令行,不能运行测试或构建。`.env`、私钥等密钥文件、`.git` 目录和本机服务目录始终不开放,读到的内容会发给你配置的模型服务商。密钥只保存在本机,调用费用按你的账号计费。
123
123
 
124
- **给成员发截图或文件**:在输入框粘贴、拖入或用回形针添加附件后,输入框上方出现缩略图,正文光标处插入 `[图片 #1]`、`[文件 #2]` 这样的占位,用来说明哪段话对应哪个文件。占位像 @成员一样高亮成小标签,按一次退格或 Delete 就整段删掉;删掉缩略图或删掉占位,两边同步移除。消息发出后,正文里的占位可点开对应附件。被点名的成员收到任务时,附件已下载到这台电脑,任务里按占位列出位置;Claude Code 和 Codex CLI 会像在自己窗口里贴图一样直接看到图片,其他软件按位置自行打开。API 成员要看图,在它卡片的 API 设置里打开“看图”(只在模型本身支持看图时打开,否则请求会出错);没打开时它看不到图片内容。UTF-8 文本附件 API 成员都能按需读取原文;PDF 等其他文件它读不到,回答里会说明没有读取。执行中插话和私聊只能发文字。
124
+ **给成员发截图或文件**:在输入框粘贴、拖入或用回形针添加附件后,输入框上方出现缩略图,正文光标处插入 `[图片 #1]`、`[文件 #2]` 这样的占位,用来说明哪段话对应哪个文件。编号在整个房间里连续、不重复(像 Claude Code 里贴的图那样),翻聊天记录时按编号就能找到那张图。占位像 @成员一样高亮成小标签,按一次退格或 Delete 就整段删掉;删掉缩略图或删掉占位,两边同步移除。消息发出后,正文里的占位可点开对应附件。被点名的成员收到任务时,附件已下载到这台电脑,任务里按占位列出位置;Claude Code 和 Codex CLI 会像在自己窗口里贴图一样直接看到图片,其他软件按位置自行打开。API 成员要看图,在它卡片的 API 设置里打开“看图”(只在模型本身支持看图时打开,否则请求会出错);没打开时它看不到图片内容。UTF-8 文本附件 API 成员都能按需读取原文;PDF 等其他文件它读不到,回答里会说明没有读取。执行中插话和私聊只能发文字。
125
125
 
126
126
  **让成员画图**:新建房间时在“智能调度”下面的“生图”一节添加“OpenAI Images”卡片,翻面填写地址、API Key 和图片模型(如 `gpt-image-2.6-flare`,快;`gpt-image-2.6-sunburst`,改图更精细);建房后也可在“成员与设置 → 协作设置”添加或移出。地址、Key 和模型只存在这台电脑,下次建房自动带出。加了卡片的房间,所有成员都能画:Claude Code、Codex、agy 等本机软件用 `codiscuss launch image` 命令,API 成员用生图工具。它们能按文字生成图片(含 GIF 动图和 SVG 矢量图),也能按你发的图片附件(或项目里的图片)修改、合成,画好的图片作为附件随回答发出,可写项目时还能另存进项目。要谁画由你或主持人按分工派活。图片直接显示在聊天页;要插进 Markdown 文档时,让它把图另存进项目,文档里用相对路径引用即可在文件预览中看到。画图的成员不一定看得到画出来的图,效果请你看图确认。每张图都按你配置的账号计费;OpenAI 要求账号先完成组织验证才能用图片模型,GIF 和 SVG 还需要账号开通相应的预览权限。没加卡片的房间谁都不能画;私聊里不能画图。
127
127
 
@@ -176,7 +176,7 @@
176
176
  "排队消息已变化,请刷新后再调整顺序": "Queued messages changed; refresh before reordering",
177
177
  "action 须为 {value1} 之一": "action must be one of {value1}",
178
178
  "enabled 须为 true 或 false": "enabled must be true or false",
179
- "/{mode} 命令不能同时 @ 成员": "The /{mode} command cannot also @ members",
179
+ "/{mode} 命令只能 @ 主持人;要请其他成员参与,开启后由主持人安排": "The /{mode} command can only @ the host; to involve other members, let the host arrange it once it starts",
180
180
  "Goal 启动请求不存在、不属于你或已处理;只有用户的 /goal 命令能开启 Goal": "The Goal start request does not exist, belongs to someone else, or has been handled. Only the user's /goal command can start Goal",
181
181
  "Goal 已在进行;可用 /goal pause、/goal resume、/goal clear 或 /goal edit 新目标": "Goal is already running. Use /goal pause, /goal resume, /goal clear, or /goal edit with a new objective",
182
182
  "Goal 已经暂停": "Goal is already paused",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai_co_discuss",
3
- "version": "0.4.58",
3
+ "version": "0.4.60",
4
4
  "bin": {
5
5
  "codiscuss": "runner/codiscuss.mjs"
6
6
  },
@@ -179,7 +179,8 @@ function extra_change(directory, path) {
179
179
  }
180
180
 
181
181
  /** Write a non-secret task and a member-only credential file for one execution. */
182
- /** `[图片 #n]` / `[文件 #n]`: how a message's n-th attachment is named in its text and in the task, as on the page. */
182
+ /** `[图片 #n]` / `[文件 #n]`: how an attachment is named in its message's text and in the task, as on the page; n is its
183
+ * room-wide number from the site (files are numbered across the room), else its place in the message for an older site. */
183
184
  export function attachment_placeholder(file, number) {
184
185
  return `[${IMAGE_TYPES.has(file.content_type) ? '图片' : '文件'} #${number}]`;
185
186
  }
@@ -200,7 +201,8 @@ export async function request_attachments(config, execution, member_directory =
200
201
  try { files = (await api(config, `/attachments?message_id=${message_id}`)).attachments || []; }
201
202
  catch { continue; }
202
203
  for (const [index, file] of files.slice(0, MAX_MESSAGE_FILES).entries()) {
203
- const entry = { message_id, number: index + 1, placeholder: attachment_placeholder(file, index + 1), file_name: file.file_name,
204
+ const number = Number.isInteger(file.number) ? file.number : index + 1;
205
+ const entry = { message_id, number, placeholder: attachment_placeholder(file, number), file_name: file.file_name,
204
206
  content_type: file.content_type, size: file.size, id: file.id, path: '' };
205
207
  try { entry.path = await save_attachment(config, member_directory, execution.id, message_id, entry, file.sha256); }
206
208
  catch (error) { entry.error = error.message; }
package/web/app.js CHANGED
@@ -1155,8 +1155,32 @@ function remember_room(room_id) {
1155
1155
  request_json("/api/rooms/last", { room_id }).catch(() => {});
1156
1156
  }
1157
1157
 
1158
+ // Each room keeps its unsent composer (text, files, reply) while another room is open, until this page closes.
1159
+ const room_composer_drafts = new Map();
1160
+
1161
+ /** Keep the open room's unsent text, files and reply aside; true when there was something to keep. */
1162
+ function keep_room_composer() {
1163
+ const room_id = state.room?.id;
1164
+ if (!room_id) return false;
1165
+ const text = element("message-input").value;
1166
+ const reply = state.reply_to ? { id: state.reply_to, label: element("reply-label").textContent } : null;
1167
+ if (!text.trim() && !state.attachment_drafts.length && !reply) { room_composer_drafts.delete(room_id); return false; }
1168
+ room_composer_drafts.set(room_id, { text, drafts: state.attachment_drafts, reply });
1169
+ state.attachment_drafts = [];
1170
+ return true;
1171
+ }
1172
+
1173
+ /** Put back what the room had in its composer when it was left. */
1174
+ function restore_room_composer(room_id) {
1175
+ const kept = room_id && room_composer_drafts.get(room_id);
1176
+ if (!kept) return;
1177
+ room_composer_drafts.delete(room_id);
1178
+ fill_composer(kept.text, kept.drafts, kept.reply);
1179
+ }
1180
+
1158
1181
  async function select_room(room_id) {
1159
1182
  if (room_id) { state.welcome = false; state.welcome_folder = null; }
1183
+ keep_room_composer();
1160
1184
  state.navigation_version++;
1161
1185
  state.refresh_version++;
1162
1186
  const listed = state.rooms.find((room) => room.id === room_id);
@@ -1189,6 +1213,7 @@ async function select_room(room_id) {
1189
1213
  element("search-input").value = "";
1190
1214
  element("mention-filter").setAttribute("aria-pressed", "false");
1191
1215
  cancel_reply();
1216
+ restore_room_composer(state.room?.id);
1192
1217
  select_tab("discussion", { refresh: false });
1193
1218
  history.replaceState(null, "", state.room ? `/?room=${encodeURIComponent(room_id)}` : "/");
1194
1219
  if (state.room) remember_room(room_id);
@@ -1888,7 +1913,8 @@ async function send_message(event) {
1888
1913
  element("message-input").value = "";
1889
1914
  const reply_to = state.reply_to;
1890
1915
  cancel_reply();
1891
- const preview = { author: payload.author, text: payload.text, created_at: new Date().toISOString(), files: drafts.map(file => ({ name: file.file.name, preview_url: file.preview_url })) };
1916
+ const preview = { author: payload.author, text: payload.text, created_at: new Date().toISOString(), attachment_start: draft_start(drafts) || 1,
1917
+ files: drafts.map(file => ({ name: file.file.name, preview_url: file.preview_url })) };
1892
1918
  state.sending_drafts = drafts;
1893
1919
  state.attachment_drafts = [];
1894
1920
  // A message the site will likely queue shows at once as a row in the queue tray instead of a card in the transcript,
@@ -1904,6 +1930,7 @@ async function send_message(event) {
1904
1930
  publish_view();
1905
1931
  try {
1906
1932
  payload.attachment_ids = await upload_message_attachments(room_id, payload.submitted_by, drafts);
1933
+ if (draft_start(drafts)) payload.attachment_start = draft_start(drafts);
1907
1934
  // The saved card shows these files from this browser's own copy rather than reading them back through the relay.
1908
1935
  for (const item of drafts) {
1909
1936
  const path = `/api/rooms/${encodeURIComponent(room_id)}/attachments/${encodeURIComponent(item.uploaded)}/content`;
@@ -2034,6 +2061,8 @@ function add_attachments(files, target = null) {
2034
2061
  const added = selected.map(file => ({ id: new_submission_id(), file,
2035
2062
  preview_url: /^image\/(png|jpeg|gif|webp)$/.test(file.type) ? URL.createObjectURL(file) : "", uploaded: null, actor: null }));
2036
2063
  state.attachment_drafts.push(...added);
2064
+ // Files already in the draft move to the room's current numbers first, so the whole draft counts from one start.
2065
+ renumber_placeholders(null);
2037
2066
  added.forEach(item => { item.placeholder = draft_placeholder(item, state.attachment_drafts.indexOf(item) + 1); });
2038
2067
  insert_placeholders(added.map(item => item.placeholder).join(" "), target);
2039
2068
  }
@@ -2050,9 +2079,24 @@ function choose_attachments(target = null) {
2050
2079
  element("attachment-input").click();
2051
2080
  }
2052
2081
 
2053
- /** `[图片 #n]` for an image the page previews, `[文件 #n]` for any other file. */
2054
- function draft_placeholder(item, number) {
2055
- return `[${item.preview_url ? "图片" : "文件"} #${number}]`;
2082
+ /**
2083
+ * `[图片 #n]` for an image the page previews, `[文件 #n]` for any other file. Files are numbered across the room, as
2084
+ * Claude Code numbers pasted images across a conversation: the `position`-th file of this draft takes the room's next
2085
+ * number plus its place. The site moves the numbers on if another message took them first (`attachment_start`).
2086
+ */
2087
+ function draft_placeholder(item, position) {
2088
+ return `[${item.preview_url ? "图片" : "文件"} #${attachment_base() + position - 1}]`;
2089
+ }
2090
+
2091
+ /** The room-wide number the first file of the draft takes; 1 before a room exists. */
2092
+ function attachment_base() {
2093
+ return state.room?.next_attachment_number || 1;
2094
+ }
2095
+
2096
+ /** The number the draft's first placeholder carries, which the site counts from when it saves the message. */
2097
+ function draft_start(drafts) {
2098
+ const number = Number(/#(\d+)\]$/.exec(drafts[0]?.placeholder || "")?.[1]);
2099
+ return Number.isInteger(number) && number > 0 ? number : undefined;
2056
2100
  }
2057
2101
 
2058
2102
  /** Put placeholders at the caret of the textarea the files came through, else at the end of the message text. */
@@ -2184,8 +2228,12 @@ function attachment_download_attributes(file) {
2184
2228
  */
2185
2229
  function link_attachment_placeholders(html, files = []) {
2186
2230
  if (!files?.length) return html;
2187
- return html.replace(/\[(图片|文件) #(\d{1,2})\]/g, (match, kind, number) => {
2188
- const file = files[Number(number) - 1];
2231
+ // A message saved since files were numbered across the room names them by that number; an older one by its place
2232
+ // in the message, which shows as every placeholder fitting a place while not every one fits a number.
2233
+ const numbers = [...html.matchAll(/\[(?:图片|文件) #(\d{1,4})\]/g)].map(([, number]) => Number(number));
2234
+ const by_number = numbers.every(number => files.some(file => file.number === number)) || !numbers.every(number => number <= files.length);
2235
+ return html.replace(/\[(图片|文件) #(\d{1,4})\]/g, (match, kind, number) => {
2236
+ const file = by_number ? files.find(item => item.number === Number(number)) : files[Number(number) - 1];
2189
2237
  if (!file) return match;
2190
2238
  const previewable = file.content_type.startsWith("image/") || file.content_type === "application/pdf" || is_text_attachment(file);
2191
2239
  // The stored `[图片 #n]` / `[文件 #n]` is protocol text; only the shown label follows the page language.