ai_co_discuss 0.4.57 → 0.4.59

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.57",
3
+ "version": "0.4.59",
4
4
  "bin": {
5
5
  "codiscuss": "runner/codiscuss.mjs"
6
6
  },
@@ -414,7 +414,7 @@ async function confirm_restart(reason, options) {
414
414
 
415
415
  /** Configure Python, selected clients and skills, returning partial results on startup failure. */
416
416
  async function setup(options) {
417
- intro(t('配置 AI CoDiscuss'), PACKAGE.version, PACKAGE.description);
417
+ intro(t('配置 AI CoDiscuss'), PACKAGE.version, t('让不同 AI 在各自软件中协作的共享讨论空间'));
418
418
  const { home, previous, python, port } = setup_environment(options);
419
419
  if (styled && !process.env.CODISCUSS_TUI_NESTED) step(t('运行环境就绪'), [environment_line(python, port)]);
420
420
  const scan = spinner(t('检测已安装的 AI 软件'));
@@ -93,11 +93,25 @@ function redraw(output, lines, drawn) {
93
93
  return lines.reduce((sum, line) => sum + Math.max(1, Math.ceil(text_width(line) / columns)), 0);
94
94
  }
95
95
 
96
- /** Animate a step while asynchronous work runs; synchronous work simply shows the first frame. */
96
+ /** Cut text to a display width, ending in … when shortened. */
97
+ function fit(text, width) {
98
+ if (text_width(text) <= width) return text;
99
+ let kept = '';
100
+ for (const char of text) { if (text_width(`${kept}${char}`) > width - 1) break; kept += char; }
101
+ return `${kept}…`;
102
+ }
103
+
104
+ /** Items of a short list in the interface language (、 in Chinese, a comma in English). */
105
+ export const list_text = items => items.join(t('、'));
106
+
107
+ /**
108
+ * Animate a step while asynchronous work runs; synchronous work simply shows the first frame. The line is kept to one
109
+ * terminal row: `\r` returns only to the start of the last row, so a wrapped line would leave a copy at every frame.
110
+ */
97
111
  export function spinner(title) {
98
112
  if (!styled) return { done: () => {}, fail: () => {} };
99
113
  let frame = 0;
100
- const render = () => write(`\r\x1b[2K${tone.cyan(SPIN_FRAMES[frame++ % SPIN_FRAMES.length])} ${title}${tone.dim('…')}`);
114
+ const render = () => write(`\r\x1b[2K${tone.cyan(SPIN_FRAMES[frame++ % SPIN_FRAMES.length])} ${fit(title, (process.stderr.columns || 80) - 5)}${tone.dim('…')}`);
101
115
  render();
102
116
  const timer = setInterval(render, SPIN_MS);
103
117
  const clear = () => { clearInterval(timer); write('\r\x1b[2K'); };
@@ -161,7 +175,7 @@ export function checkbox_prompt(message, items, input = process.stdin, output =
161
175
  input.off('keypress', on_key);
162
176
  input.setRawMode(false);
163
177
  input.pause();
164
- const chosen = items.filter((_, index) => checked[index]).map(item => item.label).join('、') || t('不接入软件,只配置网站');
178
+ const chosen = list_text(items.filter((_, index) => checked[index]).map(item => item.label)) || t('不接入软件,只配置网站');
165
179
  draw(error ? [`${tone.red('■')} ${message}`, `${bar()} ${tone.dim(t('已取消'))}`] : [`${tone.green('◇')} ${message}`, `${bar()} ${tone.dim(chosen)}`, bar()]);
166
180
  output.write('\x1b[?25h');
167
181
  if (error) fail(error); else done(checked);
@@ -233,7 +247,7 @@ export function tree_prompt(message, groups, input = process.stdin, output = pro
233
247
  input.off('keypress', on_key);
234
248
  input.setRawMode(false);
235
249
  input.pause();
236
- const summary = groups.map((group, index) => `${group.label}:${group.items.filter((_, item) => checked[index][item]).map(item => item.label).join('、') || t('不安装')}`);
250
+ const summary = groups.map((group, index) => t('{value1}:{value2}', { value1: group.label, value2: list_text(group.items.filter((_, item) => checked[index][item]).map(item => item.label)) || t('不安装') }));
237
251
  draw(error ? [`${tone.red('■')} ${message}`, `${bar()} ${tone.dim(t('已取消'))}`]
238
252
  : [`${tone.green('◇')} ${message}`, ...summary.map(line => `${bar()} ${tone.dim(line)}`), bar()]);
239
253
  output.write('\x1b[?25h');
@@ -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; }
@@ -405,5 +405,8 @@ export default {
405
405
  "问题 #{id} 已交给主持人处理,这条回复没有作答;需要补充请在房间里说。": "Question #{id} is with the host; this reply answered nothing. To add something, say it in the room.",
406
406
  "问题 #{id} 已更新到第 {version} 版(例如主持人给了推荐),这条回复没有作答;新版本会另发通知。": "Question #{id} is now at version {version} (for example the host recommended an answer); this reply answered nothing. The new version will be sent to you.",
407
407
  "已按 {picked}回答问题 #{id}。": "Answered question #{id} with {picked}.",
408
- "已把你的回复交给主持人判断(问题 #{id}),它会代为选择或在房间里追问。": "Your reply went to the host (question #{id}); it will choose for you or ask in the room."
408
+ "已把你的回复交给主持人判断(问题 #{id}),它会代为选择或在房间里追问。": "Your reply went to the host (question #{id}); it will choose for you or ask in the room.",
409
+ "、": ", ",
410
+ "{value1}:{value2}": "{value1}: {value2}",
411
+ "让不同 AI 在各自软件中协作的共享讨论空间": "A shared discussion space where different AIs work together, each in its own app"
409
412
  };
@@ -8,7 +8,7 @@
8
8
  * after moving them.
9
9
  */
10
10
  import { spawnSync } from 'node:child_process';
11
- import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
11
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
12
12
  import { homedir, tmpdir } from 'node:os';
13
13
  import { dirname, join } from 'node:path';
14
14
  import { fileURLToPath } from 'node:url';
@@ -277,11 +277,21 @@ static class TrayMenu {
277
277
  return strip;
278
278
  }
279
279
 
280
+ // An invisible window that never has a taskbar button. Making the menu itself the foreground window gave it one: an
281
+ // ownerless top-level window there gets a taskbar button (seen 2026-11-15 on both computers).
282
+ static Form anchor;
283
+
280
284
  public static void Show(ContextMenuStrip strip, Point at) {
285
+ if (anchor == null) {
286
+ anchor = new Form();
287
+ anchor.ShowInTaskbar = false; anchor.FormBorderStyle = FormBorderStyle.None; anchor.StartPosition = FormStartPosition.Manual;
288
+ anchor.Location = new Point(-32000, -32000); anchor.Size = new Size(1, 1); anchor.Opacity = 0;
289
+ anchor.Show();
290
+ }
291
+ // A menu closes on an outside click only when this program is in the foreground.
292
+ SetForegroundWindow(anchor.Handle);
281
293
  // Opened downward from one menu-height above the pointer, so it sits up and to the right of it.
282
294
  strip.Show(new Point(at.X, at.Y - strip.Height), ToolStripDropDownDirection.BelowRight);
283
- // A menu closes on an outside click only when this program is in the foreground.
284
- SetForegroundWindow(strip.Handle);
285
295
  }
286
296
  }
287
297
 
@@ -578,6 +588,20 @@ export function launcher_installed(home = join(homedir(), '.codiscuss')) {
578
588
  return Boolean(desktop) && existsSync(join(desktop, SHORTCUT_NAME));
579
589
  }
580
590
 
591
+ /**
592
+ * Put a new exe in place of one that may be running. Windows lets a running exe be renamed but not overwritten or
593
+ * deleted, so it is moved aside (its icon keeps working until it is restarted) and removed on a later run.
594
+ */
595
+ function replace_running(draft, exe) {
596
+ const folder = dirname(exe);
597
+ // An old one still running (its icon not restarted yet) stays until a later run.
598
+ for (const name of readdirSync(folder)) if (name.endsWith('.old')) try { rmSync(join(folder, name), { force: true }); } catch { /* still running */ }
599
+ if (existsSync(exe)) {
600
+ try { rmSync(exe); } catch { renameSync(exe, join(folder, `launcher-${Date.now()}.old`)); }
601
+ }
602
+ renameSync(draft, exe);
603
+ }
604
+
581
605
  /**
582
606
  * Build 共议.exe and its shortcuts.
583
607
  *
@@ -594,9 +618,12 @@ export function install_launcher(home = join(homedir(), '.codiscuss')) {
594
618
  const source = join(folder, 'launcher.cs'), exe = launcher_path(home);
595
619
  writeFileSync(source, `\ufeff${launcher_source({ node: process.execPath, local_script: installed_script('discussion_local.mjs'),
596
620
  panel_script: installed_script('admin_panel.mjs'), home })}`, 'utf8');
621
+ // Compiled beside it first: the running exe (it hosts the taskbar icon) cannot be overwritten (CS0016, seen 2026-11-15).
622
+ const draft = join(folder, 'launcher.new.exe');
597
623
  const result = spawnSync(CSC, ['/nologo', '/target:winexe', '/codepage:65001', '/optimize+', '/r:System.Windows.Forms.dll', '/r:System.Drawing.dll',
598
- `/out:${exe}`, ...(icon ? [`/win32icon:${icon}`] : []), source], { encoding: 'utf8', windowsHide: true });
624
+ `/out:${draft}`, ...(icon ? [`/win32icon:${icon}`] : []), source], { encoding: 'utf8', windowsHide: true });
599
625
  if (result.status !== 0) throw new Error(t('编译启动器失败:{value1}', { value1: (result.stdout || result.stderr).trim() }));
626
+ replace_running(draft, exe);
600
627
  const shortcuts = ['Desktop', 'Programs'].map(place => write_shortcut(place, exe, icon));
601
628
  return { exe, icon, shortcuts };
602
629
  }
@@ -264,8 +264,13 @@ export function run_as_user(data, account, script, { files = {}, folders = {}, v
264
264
  writeFileSync(job, `\ufeff[Console]::OutputEncoding = [Text.Encoding]::UTF8\n$Job = ${quote(folder)}\n$Out = ${quote(join(folder, 'out'))}\n${script}\n`, 'utf8');
265
265
  const command = visible ? `-NoProfile -ExecutionPolicy Bypass -NoExit -File ${quote(job)}`
266
266
  : `-NoProfile -ExecutionPolicy Bypass -Command & ${quote(job)} *> ${quote(output)}`;
267
+ // Start-Process -Credential hands the new process this PowerShell's standard output and error, which are the pipes the
268
+ // caller's spawnSync reads to their end: a process left running would hold this start (and the panel's whole event
269
+ // loop) until its timeout (seen 2026-11-15: a sign-in froze the panel and its taskbar icon for two minutes). Not waiting,
270
+ // they go to files in the job folder instead, which only the owner writes.
271
+ const detach = wait ? '' : `-RedirectStandardOutput ${quote(join(folder, 'start-out.txt'))} -RedirectStandardError ${quote(join(folder, 'start-error.txt'))}`;
267
272
  const start = `$credential = New-Object System.Management.Automation.PSCredential(${quote(record.user)}, ${secure_secret(record.secret)})
268
- $process = Start-Process ${POWERSHELL} -Credential $credential -LoadUserProfile -WorkingDirectory ${quote(folder)} -PassThru ${visible ? '' : '-WindowStyle Hidden'} -ArgumentList ${quote(command)}
273
+ $process = Start-Process ${POWERSHELL} -Credential $credential -LoadUserProfile -WorkingDirectory ${quote(folder)} -PassThru ${visible ? '' : '-WindowStyle Hidden'} ${detach} -ArgumentList ${quote(command)}
269
274
  ${wait ? `if (-not $process.WaitForExit(${timeout})) { $process.Kill(); throw '运行超时' }` : ''}
270
275
  $process.Id`;
271
276
  try {
package/web/app.js CHANGED
@@ -1888,7 +1888,8 @@ async function send_message(event) {
1888
1888
  element("message-input").value = "";
1889
1889
  const reply_to = state.reply_to;
1890
1890
  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 })) };
1891
+ const preview = { author: payload.author, text: payload.text, created_at: new Date().toISOString(), attachment_start: draft_start(drafts) || 1,
1892
+ files: drafts.map(file => ({ name: file.file.name, preview_url: file.preview_url })) };
1892
1893
  state.sending_drafts = drafts;
1893
1894
  state.attachment_drafts = [];
1894
1895
  // 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 +1905,7 @@ async function send_message(event) {
1904
1905
  publish_view();
1905
1906
  try {
1906
1907
  payload.attachment_ids = await upload_message_attachments(room_id, payload.submitted_by, drafts);
1908
+ if (draft_start(drafts)) payload.attachment_start = draft_start(drafts);
1907
1909
  // The saved card shows these files from this browser's own copy rather than reading them back through the relay.
1908
1910
  for (const item of drafts) {
1909
1911
  const path = `/api/rooms/${encodeURIComponent(room_id)}/attachments/${encodeURIComponent(item.uploaded)}/content`;
@@ -2034,6 +2036,8 @@ function add_attachments(files, target = null) {
2034
2036
  const added = selected.map(file => ({ id: new_submission_id(), file,
2035
2037
  preview_url: /^image\/(png|jpeg|gif|webp)$/.test(file.type) ? URL.createObjectURL(file) : "", uploaded: null, actor: null }));
2036
2038
  state.attachment_drafts.push(...added);
2039
+ // Files already in the draft move to the room's current numbers first, so the whole draft counts from one start.
2040
+ renumber_placeholders(null);
2037
2041
  added.forEach(item => { item.placeholder = draft_placeholder(item, state.attachment_drafts.indexOf(item) + 1); });
2038
2042
  insert_placeholders(added.map(item => item.placeholder).join(" "), target);
2039
2043
  }
@@ -2050,9 +2054,24 @@ function choose_attachments(target = null) {
2050
2054
  element("attachment-input").click();
2051
2055
  }
2052
2056
 
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}]`;
2057
+ /**
2058
+ * `[图片 #n]` for an image the page previews, `[文件 #n]` for any other file. Files are numbered across the room, as
2059
+ * Claude Code numbers pasted images across a conversation: the `position`-th file of this draft takes the room's next
2060
+ * number plus its place. The site moves the numbers on if another message took them first (`attachment_start`).
2061
+ */
2062
+ function draft_placeholder(item, position) {
2063
+ return `[${item.preview_url ? "图片" : "文件"} #${attachment_base() + position - 1}]`;
2064
+ }
2065
+
2066
+ /** The room-wide number the first file of the draft takes; 1 before a room exists. */
2067
+ function attachment_base() {
2068
+ return state.room?.next_attachment_number || 1;
2069
+ }
2070
+
2071
+ /** The number the draft's first placeholder carries, which the site counts from when it saves the message. */
2072
+ function draft_start(drafts) {
2073
+ const number = Number(/#(\d+)\]$/.exec(drafts[0]?.placeholder || "")?.[1]);
2074
+ return Number.isInteger(number) && number > 0 ? number : undefined;
2056
2075
  }
2057
2076
 
2058
2077
  /** Put placeholders at the caret of the textarea the files came through, else at the end of the message text. */
@@ -2184,8 +2203,12 @@ function attachment_download_attributes(file) {
2184
2203
  */
2185
2204
  function link_attachment_placeholders(html, files = []) {
2186
2205
  if (!files?.length) return html;
2187
- return html.replace(/\[(图片|文件) #(\d{1,2})\]/g, (match, kind, number) => {
2188
- const file = files[Number(number) - 1];
2206
+ // A message saved since files were numbered across the room names them by that number; an older one by its place
2207
+ // in the message, which shows as every placeholder fitting a place while not every one fits a number.
2208
+ const numbers = [...html.matchAll(/\[(?:图片|文件) #(\d{1,4})\]/g)].map(([, number]) => Number(number));
2209
+ const by_number = numbers.every(number => files.some(file => file.number === number)) || !numbers.every(number => number <= files.length);
2210
+ return html.replace(/\[(图片|文件) #(\d{1,4})\]/g, (match, kind, number) => {
2211
+ const file = by_number ? files.find(item => item.number === Number(number)) : files[Number(number) - 1];
2189
2212
  if (!file) return match;
2190
2213
  const previewable = file.content_type.startsWith("image/") || file.content_type === "application/pdf" || is_text_attachment(file);
2191
2214
  // The stored `[图片 #n]` / `[文件 #n]` is protocol text; only the shown label follows the page language.