ai_co_discuss 0.4.68 → 0.4.70

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.
@@ -9,6 +9,7 @@
9
9
  - 用户未表示可以开始时不派实现。
10
10
  - 共享工作目录不加锁:派活写明每位成员负责的目录或文件,并行的部分不让两人改同一文件。
11
11
  - `room view` 的执行报告列有改动文件,交评审时可据此写明范围。
12
+ - 并行实现交回后看 `room view` 的 `free.conflicts`:列出的文件确实被两位成员在同一时段都改过;没列出不代表没有,成员用命令写的文件不在检测范围内。
12
13
  - 同一问题反复不通过,或本链剩余轮数(`free.chain_rounds` 的 `allowed` 减 `used`;null 即不限)不够完成下一轮时,停下向用户说明分歧与现状。
13
14
  - 向用户汇报时写明仍未验证的部分。
14
15
 
@@ -232,13 +232,15 @@ def migrate_free_tables(connection):
232
232
 
233
233
 
234
234
  def migrate_failure_classes(connection):
235
- """Let development databases created when only 'quota' was a failure class also keep 'auth' and 'output_truncated'."""
235
+ """Widen older failure constraints while preserving recorded failures and reset times."""
236
236
  row = connection.execute("SELECT sql FROM sqlite_master WHERE name='execution_failures'").fetchone()
237
- if not row or "'auth'" in row[0]:
237
+ if not row or all(f"'{kind}'" in row[0] for kind in ("compaction_failed", "policy_blocked")):
238
238
  return
239
239
  connection.execute("DROP TABLE IF EXISTS execution_failures_next") # left over if a previous run stopped mid-migration
240
240
  definition = row[0].replace("execution_failures", "execution_failures_next", 1)
241
- connection.execute(definition.replace("IN ('quota')", "IN ('quota','auth','output_truncated')"))
241
+ definition = re.sub(r"CHECK\s*\(failure_class\s+IN\s*\([^)]*\)\)",
242
+ "CHECK(failure_class IN ('quota','auth','output_truncated','compaction_failed','policy_blocked'))", definition)
243
+ connection.execute(definition)
242
244
  columns = ",".join(item[1] for item in connection.execute("PRAGMA table_info(execution_failures)"))
243
245
  connection.execute(f"INSERT INTO execution_failures_next ({columns}) SELECT {columns} FROM execution_failures")
244
246
  connection.execute("DROP TABLE execution_failures")
@@ -633,7 +635,7 @@ def quota_failure(connection, execution_id):
633
635
 
634
636
 
635
637
  def failure_class_of(connection, execution_id):
636
- """The class the runner's adapter gave this failed execution (`quota`, `auth`, `output_truncated`), or ''."""
638
+ """The supported class the runner's adapter gave this failed execution, or ''."""
637
639
  row = connection.execute("SELECT failure_class FROM execution_failures WHERE execution_id=?", (execution_id,)).fetchone()
638
640
  return row["failure_class"] if row else ""
639
641
 
@@ -967,6 +969,7 @@ def recent_executions(connection, room_id, span=None):
967
969
  (SELECT MIN({LAYOUT_AT_SQL}) FROM member_requests r WHERE r.execution_id=e.id) AS layout_at,
968
970
  (SELECT COUNT(*) FROM execution_notes WHERE execution_id=e.id) AS note_count,
969
971
  (SELECT denials FROM execution_denials WHERE execution_id=e.id) AS denials,{CAPABILITY_COLUMNS},
972
+ (SELECT failure_class FROM execution_failures WHERE execution_id=e.id) AS failure_class,
970
973
  (SELECT json_object('created_at',created_at) FROM late_answers WHERE execution_id=e.id) AS late_answer,
971
974
  {BACKGROUND_SQL} AS background
972
975
  FROM member_executions e JOIN room_members m ON m.id=e.member_id WHERE e.room_id=?"""
@@ -986,7 +989,7 @@ def recent_executions(connection, room_id, span=None):
986
989
  "edited": json.loads(row["edited"]) if row["edited"] else None, "diff_stats": diff_stats(row["diffs"]),
987
990
  "answer_id": row["answer_id"], "request_message_id": row["request_message_id"],
988
991
  "layout_after": row["layout_after"], "layout_at": row["layout_at"] or row["created_at"], "requests": requests,
989
- "notes": row["note_count"], "denials": json.loads(row["denials"] or "[]"),
992
+ "notes": row["note_count"], "denials": json.loads(row["denials"] or "[]"), "failure_class": row["failure_class"] or "",
990
993
  "capabilities": reported_capabilities(row), "stop_result": row["stop_result"] or "",
991
994
  "late_answer": json.loads(row["late_answer"]) if row["late_answer"] else None, "background": bool(row["background"]),
992
995
  "retried": bool(row["retried"]),
@@ -1682,6 +1685,10 @@ def wake_after_failure(connection, execution_id, requests, reason):
1682
1685
  text = Text("{name} 额度已用尽,处理 {messages} 的执行失败(执行 #{execution_id}):{reason}。重置时间未知,它暂时长期不可用,程序暂停给它投递;请主持人改派其他成员或告知用户,不要重试。", **facts)
1683
1686
  elif failure_class_of(connection, execution_id) == "auth":
1684
1687
  text = Text("{name} 的登录已失效,处理 {messages} 的执行失败(执行 #{execution_id}):{reason}。需要用户在本机重新登录该软件后才能再用它;程序不自动重试,请主持人改派其他成员或告知用户。", **facts)
1688
+ elif failure_class_of(connection, execution_id) == "compaction_failed":
1689
+ text = Text("{name} 的上下文压缩失败,处理 {messages} 的执行失败(执行 #{execution_id}):{reason}。请缩短输入或拆分任务后再决定是否重试;程序不自动重试。", **facts)
1690
+ elif failure_class_of(connection, execution_id) == "policy_blocked":
1691
+ text = Text("{name} 因安全策略拒绝,处理 {messages} 的执行失败(执行 #{execution_id}):{reason}。请核对请求内容与服务许可要求,不要原样重试;程序不自动重试。", **facts)
1685
1692
  else:
1686
1693
  text = Text("{name} 处理 {messages} 的执行失败(执行 #{execution_id}):{reason}。请主持人决定重试、改派还是告知用户。",
1687
1694
  name=name, messages=messages, execution_id=execution_id, reason=str(reason)[:200])
@@ -3591,17 +3598,16 @@ def execution_action(connection, room_id, execution_id, token, payload, member=N
3591
3598
 
3592
3599
 
3593
3600
  def record_failure_class(connection, room_id, execution_id, payload):
3594
- """Keep the runner's classification of a failure: `quota` (with when it resets), `auth` (signed out) or
3595
- `output_truncated` (the model's reply hit its output cap); anything else stays unclassified."""
3601
+ """Keep an explicitly supported adapter failure class; only quota carries reset times."""
3596
3602
  if payload.get("failure_class") is None:
3597
3603
  return
3598
3604
  reset_at = payload.get("reset_at", 0)
3599
- if payload["failure_class"] in ("auth", "output_truncated"):
3605
+ if payload["failure_class"] in ("auth", "output_truncated", "compaction_failed", "policy_blocked"):
3600
3606
  connection.execute("""INSERT OR REPLACE INTO execution_failures (execution_id,room_id,failure_class,resets,failed_at,reset_at)
3601
3607
  VALUES (?,?,?,?,?,0)""", (execution_id, room_id, payload["failure_class"], "", int(time.time())))
3602
3608
  return
3603
3609
  if payload["failure_class"] != "quota" or not isinstance(payload.get("resets", ""), str) or type(reset_at) is not int:
3604
- raise ValueError(Text("failure_class 只能为 quota、auth 或 output_truncated,resets 须为文字,reset_at 须为整数秒"))
3610
+ raise ValueError(Text("failure_class 只能为 quota、auth、output_truncated、compaction_failed 或 policy_blocked,resets 须为文字,reset_at 须为整数秒"))
3605
3611
  now = int(time.time())
3606
3612
  # A reset already past or implausibly far is the adapter misreading the text: hold for the fixed time instead.
3607
3613
  reset_at = reset_at if now < reset_at <= now + MAX_QUOTA_HOLD_SECONDS else 0
@@ -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);
@@ -345,7 +348,7 @@ CREATE TABLE IF NOT EXISTS execution_denials (
345
348
  CREATE TABLE IF NOT EXISTS execution_failures (
346
349
  execution_id INTEGER PRIMARY KEY REFERENCES member_executions(id) ON DELETE CASCADE,
347
350
  room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,
348
- failure_class TEXT NOT NULL CHECK(failure_class IN ('quota','auth','output_truncated')),
351
+ failure_class TEXT NOT NULL CHECK(failure_class IN ('quota','auth','output_truncated','compaction_failed','policy_blocked')),
349
352
  resets TEXT NOT NULL DEFAULT '',
350
353
  failed_at INTEGER NOT NULL,
351
354
  reset_at INTEGER NOT NULL DEFAULT 0
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):
package/docs/en/runner.md CHANGED
@@ -87,7 +87,7 @@ Invite an AI on another computer into your room: it reads only the project files
87
87
  **Before you start**: both computers install CoDiscuss and run the local service; your computer is [connected to a hosted site](#from-a-hosted-site) with the relay deployed, and the other side reaches your room through that site's encrypted relay. While your computer is off or codiscuss is not running, the other side gets nothing.
88
88
 
89
89
  **Invite (your computer)**:
90
- 1. In the new-room panel or Invite members, choose External → External expert and select the access, folders and membership duration after check-in.
90
+ 1. In the new-room panel or Invite members, click "External expert +" on the External row (once per expert), then on the card's back select the access, folders and membership duration after check-in.
91
91
  2. Choose Add a seat awaiting check-in (automatic when creating the room). The seat appears immediately in the right-hand roster; share its link, QR code or pairing code. The link lasts 10 minutes and binds one member; regenerating it invalidates the previous link. Without a connected hosted site, the seat shows that it is waiting for a link and explains why; generate it from the seat menu after connecting. Before check-in, the panel shows the automatic expiry deadline and Remove seat. Usage, read logs and access adjustments appear after check-in.
92
92
  3. Redemption completes check-in and starts the membership duration, with **no extra approval step**. Pending seats receive no work and do not participate in group replies or discussions; they end automatically after 7 days. An expired link leaves the seat intact.
93
93
  4. `@` it in the room; its answers appear in the conversation as usual. "Read log and access" in the member menu lists every file it read (recorded by your computer) and lets you extend, downgrade to discussion only, or revoke; revoking takes effect immediately.
@@ -163,6 +163,9 @@ After reading the roster, an implementation dispatch may include `--next-review
163
163
  ## Troubleshooting
164
164
 
165
165
  - **A delivery failed** — the room retries automatically up to three times. You can retry immediately or stop it from the failure card. After three failed attempts, the host receives the failure and decides whether to skip, reschedule or pause the discussion; the room does not pause automatically.
166
+ - **The local runner restarted** — it waits if the original app process is still running. Once that process has ended, it checks the site and the exact delivery record without sending the task again. A confirmed completed turn can have its eligible answer captured automatically; no answer is reported as missing, and uncertain outcomes fail with “Unable to confirm the previous run outcome after restart”. You or the host decide whether to retry.
166
167
  - **Codex says the session is in use** — the chat is still held by Codex App; switch the member to the App from the progress board.
167
168
  - **Windows reports two data paths** — manage the service from a regular terminal, or set `DISCUSS_SERVICE_HOME`.
168
169
  - **Uncertain results** — tasks that were delivered but not confirmed are never resent automatically; check the original session and the room first.
170
+
171
+ - **Failure advice** — the card keeps the original reason. For exhausted quota, wait for reset or reassign; for expired login, sign in locally; for output limits, shorten or split the output; for failed context compaction, shorten or split the input (the next run starts a new session); for a policy refusal, review the content and service requirements before retrying. Compaction failures and policy refusals neither trigger automatic retries nor place quota holds.
package/docs/runner.md CHANGED
@@ -118,7 +118,7 @@ codiscuss local connect https://你的站点
118
118
  **前提**:两台电脑都安装共议并运行本机服务;你的电脑已[连接线上网站](#线上网页连接本机)并部署了中转,对方经这个网站的加密中转访问你的房间。你的电脑关机或 codiscuss 未运行时,对方什么也拿不到。
119
119
 
120
120
  **邀请(你的电脑)**:
121
- 1. 建房面板或右栏“邀请成员”里选择“外部 · 外部专家”,设置开放内容、目录和签到后的有效期。
121
+ 1. 建房面板或右栏“邀请成员”里点“外部”一行的“外部专家 +”(可加多位),翻到卡片背面设置开放内容、目录和签到后的有效期。
122
122
  2. 点“添加待签到席位”(建房时自动添加),右栏名单立即显示待签到成员;把席位的链接、二维码或配对码发给对方。链接 10 分钟有效,只能绑定一位成员;重新生成会立即作废旧链接。未绑定线上站点时显示“待生成链接”及原因,绑定站点后从席位菜单生成。待签到面板显示自动结束期限,可“移除席位”;签到后才显示用量、读取记录和授权调整。
123
123
  3. 对方兑换即完成签到,成员有效期从兑换时开始,**没有额外批准步骤**。未签到不收任务、不参与全体回应或讨论,7 天后自动结束;链接过期不会删除席位。
124
124
  4. 在房间里 `@` 它,回答照常出现在对话中。成员菜单的“读取记录与权限”列出它读过的每个文件(由你的电脑记录),可延长、降为只讨论或撤销授权,撤销立即生效。
@@ -221,7 +221,9 @@ API 成员可以担任专家或主持人。房间指定了项目目录时,它
221
221
 
222
222
  ## 常见问题
223
223
 
224
- - **软件送达失败**:查看成员状态与原位失败卡,在对应软件中处理登录或权限;倒计时期间可以立即重试或停止。本机接入程序重启或异常退出、导致进行中的软件进程随之结束时,同样自动重新投递同一执行,间隔缩短为 5 秒,并在原会话里告知成员这是续跑、已做完的部分不必重做。三次重试用尽后,讨论专家的失败交给主持人处理;也可跳过本次发言。
224
+ - **软件送达失败**:查看成员状态与原位失败卡,在对应软件中处理登录或权限;倒计时期间可以立即重试或停止。本机接入程序重启后,若原软件进程已结束,会先查网站与本次投递记录,不自动续跑;确认正常完成且答案符合收录条件时自动收录,没有答案报未提交,无法确认则报“重启后无法确认上次执行结果”,由主持人或你决定是否重试。原进程仍运行时继续等待。三次重试用尽后,讨论专家的失败交给主持人处理;也可跳过本次发言。
225
225
  - **Codex 提示会话被占用**:原聊天仍被 Codex App 占用,可在进度看板切换到 App 接入。
226
226
  - **Windows 报告两处数据路径**:从普通终端管理服务,或设置环境变量 `DISCUSS_SERVICE_HOME`。
227
227
  - **结果不明**:已交付但无法确认的任务不会自动重发,请先在原会话与房间中核对。
228
+
229
+ - **失败处理建议**:失败卡保留原始原因。额度用尽可等待重置或改派;登录失效须在本机重新登录;输出达到上限应缩短输出或拆分任务;上下文压缩失败应缩短输入或拆分任务(下次执行新开会话);安全策略拒绝应核对内容与服务许可要求,不要原样重试。压缩失败和策略拒绝不会自动重试,也不会暂停额度投递。
@@ -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}”",
@@ -1,4 +1,7 @@
1
1
  {
2
+ "会话上下文压缩失败({reason}),下次执行将改用新会话;请缩短输入或拆分任务后重试": "Context compaction failed ({reason}). The next run will use a new session; shorten the input or split the task before retrying",
3
+ "{name} 的上下文压缩失败,处理 {messages} 的执行失败(执行 #{execution_id}):{reason}。请缩短输入或拆分任务后再决定是否重试;程序不自动重试。": "{name}'s context compaction failed while handling {messages} (run #{execution_id}): {reason}. Shorten the input or split the task before deciding whether to retry; there is no automatic retry.",
4
+ "{name} 因安全策略拒绝,处理 {messages} 的执行失败(执行 #{execution_id}):{reason}。请核对请求内容与服务许可要求,不要原样重试;程序不自动重试。": "{name} was blocked by a safety policy while handling {messages} (run #{execution_id}): {reason}. Review the request and service access requirements; do not retry it unchanged. There is no automatic retry.",
2
5
  "备份中的翻译文本没有对应原文": "Translated backup text has no corresponding source text",
3
6
  "备份中的翻译文本与原文不一致": "Translated backup text does not match its source text",
4
7
  "翻译文本数据无效": "Translated text data is invalid",
@@ -60,6 +63,8 @@
60
63
  "项目路径重复:{value1}": "Duplicate project path: {value1}",
61
64
  "目标房间不存在或与当前房间相同": "Target room does not exist or is the current room",
62
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",
63
68
  "附件已用于其他消息,或不属于本次实际提交者": "Attachment belongs to another message or another actual submitter",
64
69
  "主持说明不能声明评审授权、依次接力或申请轮数;请在派活时提交": "Host notes cannot grant review access, relay work or request rounds; submit those when assigning work",
65
70
  "这个提交编号已被另一条内容使用,请为新发言生成新编号": "This submission ID was used for different content; generate a new ID for a new message",
@@ -550,7 +555,7 @@
550
555
  "该成员额度已用尽,暂停投递;等额度重置后重试它失败的执行,或改派其他成员": "This member is out of quota and its deliveries are on hold. Retry its failed execution after the quota resets, or reassign the work",
551
556
  "这次执行因额度用尽失败(重置时间:{resets});额度重置前重试多半仍会失败,可改派其他成员。": "This execution failed because the quota ran out (resets at: {resets}). A retry before the reset will most likely fail again; consider reassigning the work.",
552
557
  "这次执行因额度用尽失败(重置时间未知);额度重置前重试多半仍会失败,可改派其他成员。": "This execution failed because the quota ran out (reset time unknown). A retry before the reset will most likely fail again; consider reassigning the work.",
553
- "failure_class 只能为 quota、auth 或 output_truncated,resets 须为文字,reset_at 须为整数秒": "failure_class can only be quota, auth or output_truncated, resets must be text, and reset_at must be an integer number of seconds",
558
+ "failure_class 只能为 quota、auth、output_truncated、compaction_failed 或 policy_blocked,resets 须为文字,reset_at 须为整数秒": "failure_class must be quota, auth, output_truncated, compaction_failed or policy_blocked; resets must be text and reset_at must be integer seconds",
554
559
  "{name} 的登录已失效,处理 {messages} 的执行失败(执行 #{execution_id}):{reason}。需要用户在本机重新登录该软件后才能再用它;程序不自动重试,请主持人改派其他成员或告知用户。": "{name} is signed out; its execution for {messages} failed (execution #{execution_id}): {reason}. It can work again only after the user signs that software in again on this computer; it is not retried automatically. Host: reassign the work to another member or tell the user.",
555
560
  "这次执行因登录失效失败;用户在本机重新登录该软件之前,重试仍会失败。": "This execution failed because the member is signed out; retrying will keep failing until the user signs that software in again on this computer.",
556
561
  "模型输出在 {tokens} 个 token 处达到输出上限后结束,未提交结果{reply}": "The model's output stopped at its output limit after {tokens} tokens, without submitting a result{reply}",
@@ -562,7 +567,7 @@
562
567
  "专家 {name} 已回答 #{answer_id},请继续安排本轮尚未发言的专家。": "Expert {name} answered in #{answer_id}. Continue scheduling experts who have not spoken this round.",
563
568
  "第 {round} 轮已完成,请判断是否开始下一轮或收束讨论。": "Round {round} is complete. Decide whether to start another round or conclude the discussion.",
564
569
  "[已隐去]": "[Hidden]",
565
- "本机接入程序重启或异常退出,这次执行的软件进程已结束,未提交回答": "The local runner restarted or exited unexpectedly; the app process for this run ended without submitting a reply",
570
+ "重启后无法确认上次执行结果": "Unable to confirm the previous run outcome after restart",
566
571
  "没有模型判断:{value1}": "No model judgment: {value1}",
567
572
  "自动评审交接结果尚未核验": "Automatic review handoff is unverified",
568
573
  "未自动开始下一圈:{value1}": "Did not start the next pass automatically: {value1}",
@@ -1,4 +1,9 @@
1
1
  {
2
+ "额度已用尽,请等待重置或改派其他成员。": "Usage limit reached. Wait for it to reset or assign another member.",
3
+ "登录已失效,请在本机重新登录后再试。": "Sign-in has expired. Sign in again on this computer before retrying.",
4
+ "输出达到上限,请缩短要求的输出或拆分任务。": "Output limit reached. Request a shorter answer or split the task.",
5
+ "上下文压缩失败,请缩短输入或拆分任务后再试。": "Context compaction failed. Shorten the input or split the task before retrying.",
6
+ "安全策略拒绝,请核对请求内容与服务许可要求,不要原样重试。": "Blocked by a safety policy. Review the request and service access requirements; do not retry it unchanged.",
2
7
  "{value1} 是手动启动,轮到它时需到其 AI 会话触发;不接入可在进度看板点「跳过」本次发言": "{value1} is manually started. Trigger its turn in its AI session, or click Skip on the progress board.",
3
8
  "新消息会在 {value1} 回复后交给主持人;可在进度看板点「跳过」本次发言": "New messages go to the host after {value1} replies. Click Skip on the progress board to skip this turn.",
4
9
  "思考中": "Thinking",
@@ -30,6 +30,8 @@
30
30
  "已退出该房间": "Left the room",
31
31
  "邀请外部专家": "Invite an external expert",
32
32
  "外部专家": "External expert",
33
+ "可读:{dirs}": "Reads: {dirs}",
34
+ "目录": "Folders",
33
35
  "移除这张卡片": "Remove this card",
34
36
  "能做什么": "What it may do",
35
37
  "开放目录": "Open directories",
@@ -754,10 +754,19 @@
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
+ "文件超过 1 MB,只记录了改动,没有保存逐行差异": "Over 1 MB: the change is recorded, its line diff is not",
758
759
  "正在读取改动…": "Reading changes…",
759
760
  "读取改动失败:{value1}": "Could not read changes: {value1}",
760
761
  "改动较长,只显示前面一部分": "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
- "同期其他改动:{value1}": "Other changes meanwhile: {value1}"
762
+ "其他来源 {count} 个文件": "{count} files from other sources",
763
+ "同一时间被改动、但不是这位成员的编辑工具写的文件,可能来自其他窗口、成员或构建": "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",
764
+ "正在上传附件 {value1}/{value2}…": "Uploading attachments {value1}/{value2}…",
765
+ "正在上传": "Uploading",
766
+ "{value1} 已停止": "{value1} stopped",
767
+ "{name} 的发言已跳过": "{name}'s turn was skipped",
768
+ "{name} {state}:{reason}": "{name} {state}: {reason}",
769
+ "未回答": "no answer",
770
+ "安排 #{value1}": "Arrangement #{value1}",
771
+ "执行 #{value1}": "Run #{value1}"
763
772
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai_co_discuss",
3
- "version": "0.4.68",
3
+ "version": "0.4.70",
4
4
  "bin": {
5
5
  "codiscuss": "runner/codiscuss.mjs"
6
6
  },
@@ -658,7 +658,7 @@ export const antigravity_cli = {
658
658
  // A deleted room's session records and any legacy private agy projects are removed with it.
659
659
  cleanup: remove_agy_projects, sweep: sweep_legacy_agy_projects,
660
660
  deliver,
661
- invocation, lifecycle, events, failure_class: agy_failure_class,
661
+ invocation, lifecycle, events, failure_class: reason => agy_failure_class(reason),
662
662
  session: { path: session_path, exists: session_exists, owns: session_exists, branch, settings: session_settings,
663
663
  list: list_sessions, preview: preview_session },
664
664
  models: { list: models, effort, defaults, defaults_stamp },
@@ -272,11 +272,12 @@ export function pi_delivery({ cli, profile, key, binding, task, context_file, sy
272
272
  }
273
273
  function settled(event) {
274
274
  if (event.aborted || state.terminal || state.failure) return finish();
275
- if (state.last_error) { fail(`模型请求失败:${state.last_error}`); return finish(); }
276
275
  if (state.compaction_error) {
277
- fail(`会话上下文已满且自动压缩失败(${state.compaction_error}),下次执行将改用新会话;可直接重试`);
276
+ fail(room_text('会话上下文压缩失败({reason}),下次执行将改用新会话;请缩短输入或拆分任务后重试',
277
+ { reason: state.compaction_error }), { failure_class: 'compaction_failed', retryable: false });
278
278
  return finish();
279
279
  }
280
+ if (state.last_error) { fail(`模型请求失败:${state.last_error}`); return finish(); }
280
281
  const reply = state.last_text.slice(0, REPLY_EXCERPT_CHARS);
281
282
  // The provider stopped the reply at its output cap: say so as it happened, without guessing why (V14-V16).
282
283
  if (state.last_stop === 'length') {