ai_co_discuss 0.4.69 → 0.4.71

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.
@@ -55,6 +55,9 @@ CREATE TABLE IF NOT EXISTS attachments (
55
55
  file_name TEXT NOT NULL, content_type TEXT NOT NULL,
56
56
  size INTEGER NOT NULL, sha256 TEXT NOT NULL,
57
57
  actor TEXT NOT NULL, submission_id TEXT NOT NULL, created_at TEXT NOT NULL,
58
+ -- Pixel size as shown (EXIF rotation applied) of PNG/JPEG/GIF/WebP images; 0 when the header gives none,
59
+ -- NULL when not measured yet.
60
+ width INTEGER, height INTEGER,
58
61
  UNIQUE(room_id, submission_id)
59
62
  );
60
63
  CREATE TABLE IF NOT EXISTS execution_segments (
@@ -66,6 +66,9 @@ CREATE TABLE IF NOT EXISTS attachments (
66
66
  file_name TEXT NOT NULL, content_type TEXT NOT NULL,
67
67
  size INTEGER NOT NULL, sha256 TEXT NOT NULL,
68
68
  actor TEXT NOT NULL, submission_id TEXT NOT NULL, created_at TEXT NOT NULL,
69
+ -- Pixel size as shown (EXIF rotation applied) of PNG/JPEG/GIF/WebP images; 0 when the header gives none,
70
+ -- NULL when not measured yet.
71
+ width INTEGER, height INTEGER,
69
72
  UNIQUE(room_id, submission_id)
70
73
  );
71
74
  CREATE INDEX IF NOT EXISTS attachments_message ON attachments(message_id, position);
package/backend/server.py CHANGED
@@ -5,6 +5,7 @@ import collections
5
5
  import copy
6
6
  import hashlib
7
7
  import hmac
8
+ import io
8
9
  import json
9
10
  import logging
10
11
  import mimetypes
@@ -13,6 +14,7 @@ import re
13
14
  import secrets
14
15
  import socket
15
16
  import sqlite3
17
+ import struct
16
18
  import subprocess
17
19
  import threading
18
20
  import time
@@ -67,6 +69,8 @@ UPDATE_LOG_SIZE = 256
67
69
  MAX_BODY_BYTES = 512 * 1024
68
70
  MAX_IMPORT_BYTES = 32 * 1024 * 1024
69
71
  MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024
72
+ # Files uploaded while the message is still being written are dropped if never sent within this time.
73
+ UNSENT_ATTACHMENT_TTL = timedelta(hours=24)
70
74
  MAX_MESSAGE_ATTACHMENTS = 10
71
75
  MAX_FILENAME_LENGTH = 255
72
76
  # A revision check names at most this many rooms; a runner or page asks only for the rooms it follows.
@@ -485,6 +489,11 @@ def init_database(database, seed=True):
485
489
  connection.executescript(SCHEMA)
486
490
  if "directories" not in {row[1] for row in connection.execute("PRAGMA table_info(topic_folders)")}:
487
491
  connection.execute("ALTER TABLE topic_folders ADD COLUMN directories TEXT NOT NULL DEFAULT '[]'")
492
+ # Images stored before sizes were recorded keep NULL here and are measured when first read (with_image_sizes).
493
+ attachment_columns = {row[1] for row in connection.execute("PRAGMA table_info(attachments)")}
494
+ for name in ("width", "height"):
495
+ if name not in attachment_columns:
496
+ connection.execute(f"ALTER TABLE attachments ADD COLUMN {name} INTEGER")
488
497
  migrate_free_tables(connection)
489
498
  if seed and is_new:
490
499
  seed_demo(connection)
@@ -512,8 +521,11 @@ def require_room(connection, room_id):
512
521
  room["texts"] = room_display_texts(connection, room)
513
522
  room["archived"] = bool(connection.execute("SELECT archived FROM room_directory WHERE room_id=?", (room_id,)).fetchone()[0])
514
523
  room["folder_id"] = connection.execute("SELECT folder_id FROM room_folder_assignments WHERE room_id=?", (room_id,)).fetchone()[0]
515
- # The number the next sent file takes, so the composer shows `[图片 #n]` as it will be saved.
516
- room["next_attachment_number"] = attachment_number_before(connection, room_id, None)
524
+ # The number the next sent file takes, so the composer shows `[图片 #n]` as it will be saved. Queued messages post
525
+ # first and take the numbers before it, so a new draft does not repeat a queued message's `[图片 #n]`.
526
+ queued_files = sum(len(json.loads(row[0]).get("attachment_ids") or []) for row in
527
+ connection.execute("SELECT payload FROM queued_messages WHERE room_id=?", (room_id,)))
528
+ room["next_attachment_number"] = attachment_number_before(connection, room_id, None) + queued_files
517
529
  settings = connection.execute("SELECT host,background,boundaries,experts,focus FROM topic_settings WHERE room_id=?",
518
530
  (room_id,)).fetchone()
519
531
  room.update(dict(settings) if settings else topic_defaults())
@@ -1320,6 +1332,121 @@ def media_content_type(data):
1320
1332
  return "application/octet-stream"
1321
1333
 
1322
1334
 
1335
+ # Images whose pixel size is read from their header, so the page can hold their place before the bytes arrive.
1336
+ SIZED_IMAGE_TYPES = ("image/png", "image/jpeg", "image/gif", "image/webp")
1337
+ # JPEG markers that start a frame header (SOF0–SOF15 except DHT, JPG and DAC), which holds the image size.
1338
+ JPEG_FRAME_MARKERS = frozenset((0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF))
1339
+ # JPEG markers without a length field.
1340
+ JPEG_STANDALONE_MARKERS = frozenset((0x01, *range(0xD0, 0xD8)))
1341
+ # EXIF orientations that turn the picture a quarter, so it shows with width and height swapped.
1342
+ EXIF_QUARTER_TURNS = (5, 6, 7, 8)
1343
+ EXIF_ORIENTATION_TAG = 0x0112
1344
+
1345
+
1346
+ def image_size(stream):
1347
+ """Return the (width, height) a PNG/JPEG/GIF/WebP image shows at, read from its header without decoding it.
1348
+
1349
+ Args:
1350
+ stream: A binary file object at the start of the image; only headers are read, a JPEG's segments skipped.
1351
+
1352
+ Returns:
1353
+ Positive integers, or (0, 0) when the header is not one of those formats or gives no size.
1354
+ """
1355
+ try:
1356
+ head = stream.read(32)
1357
+ if head.startswith(b"\x89PNG\r\n\x1a\n") and head[12:16] == b"IHDR":
1358
+ size = struct.unpack(">II", head[16:24])
1359
+ elif head[:6] in (b"GIF87a", b"GIF89a"):
1360
+ size = struct.unpack("<HH", head[6:10])
1361
+ elif head.startswith(b"RIFF") and head[8:12] == b"WEBP":
1362
+ size = webp_size(head)
1363
+ elif head.startswith(b"\xff\xd8"):
1364
+ stream.seek(2)
1365
+ size = jpeg_size(stream)
1366
+ else:
1367
+ size = (0, 0)
1368
+ except struct.error:
1369
+ size = (0, 0)
1370
+ return size if min(size) > 0 else (0, 0)
1371
+
1372
+
1373
+ def webp_size(head):
1374
+ """The canvas size in the first chunk of a WebP file: lossy (VP8), lossless (VP8L) or extended (VP8X)."""
1375
+ chunk = head[12:16]
1376
+ if chunk == b"VP8 " and head[23:26] == b"\x9d\x01\x2a":
1377
+ width, height = struct.unpack("<HH", head[26:30])
1378
+ return width & 0x3FFF, height & 0x3FFF
1379
+ if chunk == b"VP8L" and head[20] == 0x2F:
1380
+ bits = struct.unpack("<I", head[21:25])[0]
1381
+ return (bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1
1382
+ if chunk == b"VP8X":
1383
+ return int.from_bytes(head[24:27], "little") + 1, int.from_bytes(head[27:30], "little") + 1
1384
+ return 0, 0
1385
+
1386
+
1387
+ def jpeg_size(stream):
1388
+ """Walk JPEG segments to the frame header; a quarter-turn EXIF orientation swaps the size, as browsers show it."""
1389
+ orientation = 1
1390
+ while stream.read(1) == b"\xff":
1391
+ marker = stream.read(1)
1392
+ while marker == b"\xff":
1393
+ marker = stream.read(1)
1394
+ if not marker or marker[0] in (0xD9, 0xDA):
1395
+ break
1396
+ if marker[0] in JPEG_STANDALONE_MARKERS:
1397
+ continue
1398
+ length = struct.unpack(">H", stream.read(2))[0]
1399
+ if marker[0] in JPEG_FRAME_MARKERS:
1400
+ height, width = struct.unpack(">xHH", stream.read(5))
1401
+ return (height, width) if orientation in EXIF_QUARTER_TURNS else (width, height)
1402
+ if marker[0] == 0xE1 and orientation == 1:
1403
+ orientation = exif_orientation(stream.read(max(0, length - 2)))
1404
+ else:
1405
+ stream.seek(max(0, length - 2), io.SEEK_CUR)
1406
+ return 0, 0
1407
+
1408
+
1409
+ def exif_orientation(segment):
1410
+ """The orientation tag of an APP1 segment's EXIF data; 1 (upright) when it has none."""
1411
+ if not segment.startswith(b"Exif\x00\x00"):
1412
+ return 1
1413
+ tiff = segment[6:]
1414
+ order = {b"II": "<", b"MM": ">"}.get(tiff[:2])
1415
+ try:
1416
+ offset = struct.unpack(order + "I", tiff[4:8])[0]
1417
+ for index in range(struct.unpack(order + "H", tiff[offset:offset + 2])[0]):
1418
+ entry = offset + 2 + index * 12
1419
+ if struct.unpack(order + "H", tiff[entry:entry + 2])[0] == EXIF_ORIENTATION_TAG:
1420
+ return struct.unpack(order + "H", tiff[entry + 8:entry + 10])[0]
1421
+ except (TypeError, struct.error):
1422
+ pass
1423
+ return 1
1424
+
1425
+
1426
+ def with_image_sizes(connection, rows):
1427
+ """Return attachment rows as dicts, measuring once each image stored before sizes were recorded.
1428
+
1429
+ The size is written back; a read request commits it at once, a write transaction keeps it with its own changes.
1430
+ An imported image whose bytes have not arrived yet stays unmeasured until they do.
1431
+ """
1432
+ files = [dict(row) for row in rows]
1433
+ missing = [item for item in files if item.get("width") is None and item["content_type"] in SIZED_IMAGE_TYPES]
1434
+ if not missing:
1435
+ return files
1436
+ began = connection.in_transaction
1437
+ database = connection.execute("PRAGMA database_list").fetchone()["file"]
1438
+ for item in missing:
1439
+ try:
1440
+ with attachment_path(database, item).open("rb") as stream:
1441
+ item["width"], item["height"] = image_size(stream)
1442
+ except OSError:
1443
+ continue
1444
+ connection.execute("UPDATE attachments SET width=?,height=? WHERE id=?", (item["width"], item["height"], item["id"]))
1445
+ if not began:
1446
+ connection.commit()
1447
+ return files
1448
+
1449
+
1323
1450
  def attachment_view(row):
1324
1451
  """Return attachment metadata and room-scoped content URLs."""
1325
1452
  result = dict(row)
@@ -1381,8 +1508,9 @@ def message_with_attachments(connection, row):
1381
1508
  return {**message, "text": "", "summary": "", "suggestions": [], "attachments": []}
1382
1509
  message["texts"] = load_texts(connection, "message", message["id"])
1383
1510
  message["suggestions"] = message_suggestions(connection, message["id"])
1384
- files = connection.execute("SELECT * FROM attachments WHERE message_id=? ORDER BY position,id", (message["id"],)).fetchall()
1385
- first = attachment_number_before(connection, message["room_id"], message["id"]) if files else 0
1511
+ files = with_image_sizes(connection, connection.execute("SELECT * FROM attachments WHERE message_id=? ORDER BY position,id",
1512
+ (message["id"],)))
1513
+ first =attachment_number_before(connection, message["room_id"], message["id"]) if files else 0
1386
1514
  message["attachments"] = [{**attachment_view(item), "number": first + index} for index, item in enumerate(files)]
1387
1515
  return message
1388
1516
 
@@ -1418,8 +1546,8 @@ def query_attachments(connection, room_id, params, token=""):
1418
1546
  values.append(int(params["message_id"]))
1419
1547
  page = max(1, int(params.get("page", 1)))
1420
1548
  total = connection.execute(f"SELECT COUNT(*) FROM attachments WHERE {where}", values).fetchone()[0]
1421
- rows = connection.execute(f"SELECT * FROM attachments WHERE {where} ORDER BY created_at,id LIMIT ? OFFSET ?",
1422
- [*values, PAGE_SIZE, (page - 1) * PAGE_SIZE])
1549
+ rows = with_image_sizes(connection, connection.execute(f"SELECT * FROM attachments WHERE {where} ORDER BY created_at,id LIMIT ? OFFSET ?",
1550
+ [*values, PAGE_SIZE, (page - 1) * PAGE_SIZE]))
1423
1551
  return {"attachments": [{**attachment_view(row), **({"number": attachment_number_before(connection, room_id, row["message_id"]) + row["position"]}
1424
1552
  if row["message_id"] is not None else {})} for row in rows], "page": page, "total": total,
1425
1553
  "pages": max(1, (total + PAGE_SIZE - 1) // PAGE_SIZE)}
@@ -1434,7 +1562,7 @@ def get_attachment(connection, room_id, identifier, params=None, token="", conte
1434
1562
  if cutoff is not None and row["message_id"] is not None and row["message_id"] > cutoff:
1435
1563
  raise BoundaryError(Text('该附件所在的消息超出本请求读取上界 #{until}', until=cutoff),
1436
1564
  code="reading_boundary", read_scope={"request_read_until": cutoff, "boundary_applied": True})
1437
- return attachment_view(row)
1565
+ return attachment_view(with_image_sizes(connection, [row])[0])
1438
1566
 
1439
1567
 
1440
1568
  def attachment_path(database, attachment):
@@ -1455,15 +1583,18 @@ def store_attachment(connection, database, room_id, metadata, data):
1455
1583
  if any(previous[key] != value for key, value in expected.items()):
1456
1584
  raise FileExistsError(Text('这个附件提交编号已被其他文件使用'))
1457
1585
  return {"attachment": attachment_view(previous), "duplicate": True}
1458
- record = {"id": uuid.uuid4().hex, "room_id": room_id, **expected, "created_at": utc_now()}
1586
+ prune_unsent_attachments(connection, database, room_id)
1587
+ # Kept out of `expected`: a retry of a file stored before sizes were recorded still matches it.
1588
+ width, height = image_size(io.BytesIO(data)) if expected["content_type"] in SIZED_IMAGE_TYPES else (None, None)
1589
+ record = {"id": uuid.uuid4().hex, "room_id": room_id, **expected, "width": width, "height": height, "created_at": utc_now()}
1459
1590
  path = attachment_path(database, record)
1460
1591
  path.parent.mkdir(parents=True, exist_ok=True)
1461
1592
  try:
1462
1593
  with path.open("xb") as target:
1463
1594
  target.write(data)
1464
1595
  connection.execute("""INSERT INTO attachments
1465
- (id,room_id,file_name,actor,submission_id,size,sha256,content_type,created_at)
1466
- VALUES (:id,:room_id,:file_name,:actor,:submission_id,:size,:sha256,:content_type,:created_at)""", record)
1596
+ (id,room_id,file_name,actor,submission_id,size,sha256,content_type,width,height,created_at)
1597
+ VALUES (:id,:room_id,:file_name,:actor,:submission_id,:size,:sha256,:content_type,:width,:height,:created_at)""", record)
1467
1598
  connection.commit()
1468
1599
  except Exception:
1469
1600
  path.unlink(missing_ok=True)
@@ -1471,6 +1602,42 @@ def store_attachment(connection, database, room_id, metadata, data):
1471
1602
  return {"attachment": get_attachment(connection, room_id, record["id"]), "duplicate": False}
1472
1603
 
1473
1604
 
1605
+ def unsent_attachment_rows(connection, room_id):
1606
+ """Files uploaded in this room that no message took and no queued message is waiting to send."""
1607
+ queued = {identifier for row in connection.execute("SELECT payload FROM queued_messages WHERE room_id=?", (room_id,))
1608
+ for identifier in json.loads(row[0]).get("attachment_ids") or []}
1609
+ return [row for row in connection.execute("SELECT * FROM attachments WHERE room_id=? AND message_id IS NULL", (room_id,))
1610
+ if row["id"] not in queued]
1611
+
1612
+
1613
+ def remove_attachment_files(connection, database, rows):
1614
+ """Delete unsent uploads and their bytes; the caller commits."""
1615
+ for row in rows:
1616
+ connection.execute("DELETE FROM attachments WHERE id=? AND message_id IS NULL", (row["id"],))
1617
+ attachment_path(database, row).unlink(missing_ok=True)
1618
+
1619
+
1620
+ def prune_unsent_attachments(connection, database, room_id):
1621
+ """Drop files uploaded ahead of sending but never sent, once they are older than a draft could still be waiting."""
1622
+ cutoff = datetime.now(timezone.utc) - UNSENT_ATTACHMENT_TTL
1623
+ remove_attachment_files(connection, database, [row for row in unsent_attachment_rows(connection, room_id)
1624
+ if datetime.fromisoformat(row["created_at"]) < cutoff])
1625
+
1626
+
1627
+ def discard_attachment(connection, database, room_id, identifier, token):
1628
+ """The uploader takes back a file it uploaded ahead of sending; a sent or queued file stays."""
1629
+ attachment = get_attachment(connection, room_id, identifier)
1630
+ actor = authorize_free_write(connection, room_id, token, "attachments", {"author": attachment["actor"]})
1631
+ if (actor if isinstance(actor, str) else actor["name"]) != attachment["actor"]:
1632
+ raise PermissionError(Text('只能撤下自己上传的附件'))
1633
+ row = next((item for item in unsent_attachment_rows(connection, room_id) if item["id"] == identifier), None)
1634
+ if row is None:
1635
+ raise FileExistsError(Text('附件已随消息发出或正在排队,不能撤下'))
1636
+ remove_attachment_files(connection, database, [row])
1637
+ connection.commit()
1638
+ return {"discarded": identifier}
1639
+
1640
+
1474
1641
  def check_message_attachments(connection, room_id, actor, identifiers):
1475
1642
  """Reject references to another room, uploader, or already published message."""
1476
1643
  for identifier in identifiers:
@@ -3250,6 +3417,8 @@ class DiscussionHandler(BaseHTTPRequestHandler):
3250
3417
  raise ValueError(Text('附件内容不完整'))
3251
3418
  result = store_attachment(connection, self.server.database, room_id, metadata, data)
3252
3419
  return self.respond(result, 200 if result["duplicate"] else 201)
3420
+ if method == "POST" and len(parts) == 6 and parts[5] == "discard":
3421
+ return self.respond(discard_attachment(connection, self.server.database, room_id, parts[4], self.headers.get("X-Discussion-Token", "")))
3253
3422
  if method == "POST" and len(parts) == 6 and parts[5] == "import":
3254
3423
  return self.import_attachment(connection, room_id, parts[4])
3255
3424
  if method == "GET" and len(parts) in (5, 6):
@@ -83,6 +83,7 @@
83
83
  "进入房间后查看本次议题。": "Enter a room to see its topic.",
84
84
  "留言最多 {value1} 字,原文已保留,请调整后提交": "Messages can contain up to {value1} characters. Your draft is kept. Edit it and submit again.",
85
85
  "建房偏好未保存:{value1}": "Room preferences not saved: {value1}",
86
+ "模型与强度偏好未保存:{value1}": "Model and effort preference not saved: {value1}",
86
87
  "建房偏好未读取:{value1}": "Room preferences not loaded: {value1}",
87
88
  "默认描述未保存:{value1}": "Default description not saved: {value1}",
88
89
  "已存为预设「{value1}」": "Saved as preset “{value1}”",
@@ -63,6 +63,8 @@
63
63
  "项目路径重复:{value1}": "Duplicate project path: {value1}",
64
64
  "目标房间不存在或与当前房间相同": "Target room does not exist or is the current room",
65
65
  "这个附件提交编号已被其他文件使用": "This attachment submission ID was used for another file",
66
+ "只能撤下自己上传的附件": "You can only take back attachments you uploaded",
67
+ "附件已随消息发出或正在排队,不能撤下": "This attachment was already sent with a message or is queued, so it cannot be taken back",
66
68
  "附件已用于其他消息,或不属于本次实际提交者": "Attachment belongs to another message or another actual submitter",
67
69
  "主持说明不能声明评审授权、依次接力或申请轮数;请在派活时提交": "Host notes cannot grant review access, relay work or request rounds; submit those when assigning work",
68
70
  "这个提交编号已被另一条内容使用,请为新发言生成新编号": "This submission ID was used for different content; generate a new ID for a new message",
@@ -754,12 +754,20 @@
754
754
  "已重试,新的执行接在下方": "Retried; the new run follows below",
755
755
  "已修改 {count} 个文件": "Edited {count} files",
756
756
  "二进制文件": "Binary file",
757
- "文件过大": "File too large",
757
+ "未记录差异": "No line diff",
758
+ "关闭预览": "Close preview",
759
+ "文件超过 1 MB,只记录了改动,没有保存逐行差异": "Over 1 MB: the change is recorded, its line diff is not",
758
760
  "正在读取改动…": "Reading changes…",
759
761
  "读取改动失败:{value1}": "Could not read changes: {value1}",
760
762
  "改动较长,只显示前面一部分": "Long change; only the first part is shown",
761
- "这些文件在同一时间被改动,但不是这位成员的编辑工具写的,可能来自其他窗口或成员": "These files changed meanwhile but not through this member's edit tools; another window or member may have changed them",
762
- "另有 {count} 个文件同期被改动,不是它写的": "{count} more files changed meanwhile, not by this member",
763
+ "其他来源 {count} 个文件": "{count} files from other sources",
764
+ "同一时间被改动、但不是这位成员的编辑工具写的文件,可能来自其他窗口、成员或构建": "Files changed at the same time but not written by this member's edit tools; they may come from another window, member or a build",
763
765
  "正在上传附件 {value1}/{value2}…": "Uploading attachments {value1}/{value2}…",
764
- "正在上传": "Uploading"
766
+ "正在上传": "Uploading",
767
+ "{value1} 已停止": "{value1} stopped",
768
+ "{name} 的发言已跳过": "{name}'s turn was skipped",
769
+ "{name} {state}:{reason}": "{name} {state}: {reason}",
770
+ "未回答": "no answer",
771
+ "安排 #{value1}": "Arrangement #{value1}",
772
+ "执行 #{value1}": "Run #{value1}"
765
773
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai_co_discuss",
3
- "version": "0.4.69",
3
+ "version": "0.4.71",
4
4
  "bin": {
5
5
  "codiscuss": "runner/codiscuss.mjs"
6
6
  },
@@ -612,6 +612,32 @@ function valid_scheduler_preference(value) {
612
612
  return Object.entries(value).every(([field, item]) => Object.hasOwn(fields, field) && fields[field](item));
613
613
  }
614
614
 
615
+ /** Model and effort picked on a platform's card are usage preferences, remembered as that platform's default. */
616
+ function validate_participant_choices(input) {
617
+ if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error('模型与强度偏好须为对象');
618
+ for (const [name, choice] of Object.entries(input)) {
619
+ if (!clients_of(name) || platform_of(name) !== name) throw new Error(`本机默认配置按平台保存;${name} 的模型与强度只用于本场讨论`);
620
+ if (!choice || typeof choice !== 'object' || Array.isArray(choice)
621
+ || Object.entries(choice).some(([field, value]) => !['model', 'effort'].includes(field) || typeof value !== 'string')) throw new Error(`${name} 的模型与强度偏好无效`);
622
+ }
623
+ return input;
624
+ }
625
+
626
+ /** Merge only model and effort into each platform's saved software settings; empty text goes back to the software default. */
627
+ function merge_participant_choices(participants, choices) {
628
+ const merged = { ...participants };
629
+ for (const [name, choice] of Object.entries(choices)) {
630
+ const profile = { ...merged[name] };
631
+ for (const [field, value] of Object.entries(choice)) {
632
+ if (value) profile[field] = value;
633
+ else delete profile[field];
634
+ }
635
+ validate_profile(name, profile);
636
+ merged[name] = profile;
637
+ }
638
+ return merged;
639
+ }
640
+
615
641
  /** Update software defaults or form preferences independently, preserving the other section. */
616
642
  export function save_launch_settings(home, input) {
617
643
  const patch = {};
@@ -628,6 +654,7 @@ export function save_launch_settings(home, input) {
628
654
  validate_create_preferences(input.create_preferences);
629
655
  patch.create_preferences = input.create_preferences;
630
656
  }
657
+ const choices = Object.hasOwn(input, 'participant_choices') ? validate_participant_choices(input.participant_choices) : null;
631
658
  mkdirSync(home, { recursive: true, mode: 0o700 });
632
659
  const lock = new DatabaseSync(join(home, 'launch-settings-lock.sqlite3'));
633
660
  try {
@@ -635,6 +662,7 @@ export function save_launch_settings(home, input) {
635
662
  const previous = launch_settings(home);
636
663
  const settings = { ...previous, ...patch };
637
664
  if (patch.create_preferences) settings.create_preferences = { ...previous.create_preferences, ...patch.create_preferences };
665
+ if (choices) settings.participants = merge_participant_choices(settings.participants, choices);
638
666
  atomic_json(join(home, 'launch-settings.json'), settings);
639
667
  lock.exec('COMMIT');
640
668
  return settings;
@@ -8,7 +8,8 @@ import { readFileSync, statSync } from 'node:fs';
8
8
  import { join } from 'node:path';
9
9
 
10
10
  // Files larger than this are listed without lines; patches are kept short enough to travel with the room.
11
- const MAX_DIFF_BYTES = 256 * 1024;
11
+ // 1 MiB: the project's own largest sources (about 290 KB) still get lines (user 2026-11-17).
12
+ const MAX_DIFF_BYTES = 1024 * 1024;
12
13
  const MAX_PATCH_LINES = 400;
13
14
  const MAX_TOTAL_PATCH_CHARS = 400 * 1024;
14
15
  const MAX_FILES = 200;
@@ -47,6 +47,8 @@ const UPLOAD_PATH = /^\/api\/rooms\/[A-Za-z0-9_-]+\/attachments(\/[A-Za-z0-9_-]+
47
47
  const UPLOAD_MAX_BYTES = 20 * 1024 * 1024;
48
48
  const UPLOAD_TTL_MS = 10 * 60 * 1000;
49
49
  const uploads = new Map();
50
+ // Answers of uploads already handed to the local website, by upload id, kept as long as unfinished uploads are.
51
+ const finished_uploads = new Map();
50
52
  // The hosted accounts' entry over the relay (backend/entry_worker.mjs): answer parts per frame (sent as base64 within the
51
53
  // 1 MiB frame), the largest request taken, and when to pause reading an answer the connection has not sent on yet.
52
54
  const ENTRY_PART_BYTES = 512 * 1024;
@@ -127,7 +129,9 @@ function bridge_headers(home, site) {
127
129
 
128
130
  /**
129
131
  * Collect one part of an attachment upload; once every part has arrived, send the whole file to the local website as
130
- * the bridge. Parts may be resent; an unfinished upload is dropped after ten minutes.
132
+ * the bridge. Parts may arrive in any order and be resent; an unfinished upload answers which parts it still lacks and
133
+ * is dropped after ten minutes. A part resent after the file was handed on (its answer lost on the way) gets that same
134
+ * answer, so the device does not start the file over.
131
135
  */
132
136
  export async function room_upload(home, site, payload, { fetcher = site_fetch, now = Date.now() } = {}) {
133
137
  const { id, path, index, total, size, content_type = 'application/octet-stream', data } = payload || {};
@@ -136,20 +140,34 @@ export async function room_upload(home, site, payload, { fetcher = site_fetch, n
136
140
  || !Number.isSafeInteger(size) || size < 0 || size > UPLOAD_MAX_BYTES || typeof data !== 'string' || typeof content_type !== 'string') {
137
141
  return { status: 400, body: { error: '附件上传请求无效' } };
138
142
  }
139
- for (const [key, item] of uploads) if (now - item.at > UPLOAD_TTL_MS) uploads.delete(key);
143
+ for (const store of [uploads, finished_uploads]) for (const [key, item] of store) if (now - item.at > UPLOAD_TTL_MS) store.delete(key);
144
+ const finished = finished_uploads.get(id);
145
+ if (finished) return finished.path === path ? finished.answer : { status: 400, body: { error: '附件上传请求无效' } };
140
146
  const upload = uploads.get(id) ?? { path, total, size, parts: [], at: now };
141
147
  if (upload.path !== path || upload.total !== total || upload.size !== size) return { status: 400, body: { error: '附件上传请求无效' } };
142
148
  upload.parts[index] = Buffer.from(data, 'base64');
143
149
  upload.at = now;
144
150
  uploads.set(id, upload);
145
- const received = upload.parts.filter(Boolean).length;
146
- if (received < total) return { status: 200, body: { received } };
151
+ const missing = [];
152
+ for (let part = 0; part < total; part++) if (!upload.parts[part]) missing.push(part);
153
+ if (missing.length) return { status: 200, body: { received: total - missing.length, missing } };
147
154
  uploads.delete(id);
148
155
  const bytes = Buffer.concat(upload.parts);
149
156
  if (bytes.length !== size) return { status: 400, body: { error: '附件不完整,请重新上传' } };
150
- const response = await fetcher(`${local_origin(home)}${path}`, { method: 'POST', redirect: 'error', body: bytes,
151
- headers: { ...bridge_headers(home, site), 'Content-Type': content_type }, signal: AbortSignal.timeout(LOCAL_TIMEOUT_MS) });
152
- return { status: response.status, body: await response.json() };
157
+ // Kept while the hand-over runs, so a part resent meanwhile waits for the same answer.
158
+ const answer = fetcher(`${local_origin(home)}${path}`, { method: 'POST', redirect: 'error', body: bytes,
159
+ headers: { ...bridge_headers(home, site), 'Content-Type': content_type }, signal: AbortSignal.timeout(LOCAL_TIMEOUT_MS) })
160
+ .then(async (response) => ({ status: response.status, body: await response.json() }));
161
+ finished_uploads.set(id, { path, at: now, answer });
162
+ try {
163
+ const result = await answer;
164
+ // A refused file is not kept: sending it again is a new attempt.
165
+ if (result.status >= 400) finished_uploads.delete(id);
166
+ return result;
167
+ } catch (error) {
168
+ finished_uploads.delete(id);
169
+ throw error;
170
+ }
153
171
  }
154
172
 
155
173
  /** Room credentials and website of the rooms this computer serves on its own local website, by room. */