ai_co_discuss 0.5.28 → 0.5.29

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.
@@ -76,6 +76,8 @@ CREATE TABLE IF NOT EXISTS attachments (
76
76
  -- Pixel size as shown (EXIF rotation applied) of PNG/JPEG/GIF/WebP images; 0 when the header gives none,
77
77
  -- NULL when not measured yet.
78
78
  width INTEGER, height INTEGER,
79
+ -- The type (image/webp or image/jpeg) of a smaller copy a page made for showing in messages; NULL when none.
80
+ thumbnail_type TEXT,
79
81
  UNIQUE(room_id, submission_id)
80
82
  );
81
83
  CREATE INDEX IF NOT EXISTS attachments_message ON attachments(message_id, position);
package/backend/server.py CHANGED
@@ -27,7 +27,7 @@ from contextlib import closing
27
27
  from datetime import datetime, timedelta, timezone
28
28
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
29
29
  from pathlib import Path
30
- from urllib.parse import parse_qs, quote, urlsplit
30
+ from urllib.parse import parse_qs, quote, unquote, urlsplit
31
31
 
32
32
  from .entry_guard import (BROWSER_COOKIE_SECONDS, HELLO_PATH, OPEN_PATH, PUBLIC_PATHS, EntryPolicy, answer_hello, browser_admitted,
33
33
  browser_cookie_name, open_link_key, proof, request_proven)
@@ -78,6 +78,13 @@ MAX_BODY_BYTES = 512 * 1024
78
78
  MAX_FILE_PART_BODY_BYTES = 5 * 1024 * 1024
79
79
  MAX_IMPORT_BYTES = 32 * 1024 * 1024
80
80
  MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024
81
+ # A smaller copy of an image a page made (WebP or JPEG), shown in messages in place of the original: at most this many
82
+ # bytes and this many pixels on its longer side, and its shape within THUMBNAIL_RATIO_TOLERANCE of the original's.
83
+ MAX_THUMBNAIL_BYTES = 512 * 1024
84
+ MAX_THUMBNAIL_SIDE = 1600
85
+ THUMBNAIL_RATIO_TOLERANCE = 0.03
86
+ THUMBNAIL_TYPES = ("image/webp", "image/jpeg")
87
+ THUMBNAIL_SUFFIX = ".thumbnail"
81
88
  # Files uploaded while the message is still being written are dropped if never sent within this time.
82
89
  UNSENT_ATTACHMENT_TTL = timedelta(hours=24)
83
90
  ATTACHMENT_SWEEP_SECONDS = 6 * 60 * 60
@@ -105,6 +112,12 @@ DIRECTORY_PICKER_TIMEOUT = 600 # the folder dialog waits for the person at the
105
112
  FILE_CHUNK_BYTES = 1024 * 1024
106
113
  # A project media file the local page plays is served by a random ticket for this long after the runner checked access.
107
114
  MEDIA_TICKET_SECONDS = 600
115
+ # A project page the computer's own browser opens in a tab keeps reading the files beside it (lazy images, scripts) for
116
+ # this long; its address is a random ticket naming the project folder, never a path.
117
+ PAGE_TICKET_SECONDS = 12 * 3600
118
+ # The page runs as an opaque origin (no allow-same-origin), so it can read nothing of this site; it may run its scripts,
119
+ # open pop-ups and dialogs, and load anything from the folder or the web. No forms: a write to this site needs its origin.
120
+ PAGE_POLICY = "sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox allow-modals allow-downloads"
108
121
  MAX_MEDIA_TICKETS = 64
109
122
  MAX_TEXT_LENGTH = 32000
110
123
  SESSION_ID_PATTERN = re.compile(r"[0-9A-Za-z_-]{8,128}")
@@ -574,6 +587,8 @@ def init_database(database, seed=True):
574
587
  for name in ("width", "height"):
575
588
  if name not in attachment_columns:
576
589
  connection.execute(f"ALTER TABLE attachments ADD COLUMN {name} INTEGER")
590
+ if "thumbnail_type" not in attachment_columns:
591
+ connection.execute("ALTER TABLE attachments ADD COLUMN thumbnail_type TEXT")
577
592
  if connection.execute("INSERT OR IGNORE INTO site_preferences (key,value) VALUES ('child_folders_migrated','1')").rowcount:
578
593
  connection.execute("""UPDATE room_folder_assignments AS child SET folder_id=parent.folder_id
579
594
  FROM room_links l JOIN room_folder_assignments parent ON parent.room_id=l.other_room_id
@@ -1839,6 +1854,7 @@ def finish_destruction_files(database, room_id):
1839
1854
  for file_id in files.get("ids", []):
1840
1855
  path = attachment_path(database, {"id": file_id})
1841
1856
  try:
1857
+ thumbnail_path(database, {"id": file_id}).unlink(missing_ok=True)
1842
1858
  path.unlink(missing_ok=True)
1843
1859
  except OSError:
1844
1860
  logging.exception("Attachment cleanup failed: %s", file_id)
@@ -2321,6 +2337,8 @@ def attachment_view(row):
2321
2337
  result = dict(row)
2322
2338
  base = f"/api/rooms/{result['room_id']}/attachments/{result['id']}/content"
2323
2339
  result.update(url=base, download_url=base + "?download=1")
2340
+ if result.get("thumbnail_type"):
2341
+ result["thumbnail_url"] = f"/api/rooms/{result['room_id']}/attachments/{result['id']}/thumbnail"
2324
2342
  return result
2325
2343
 
2326
2344
 
@@ -2440,6 +2458,43 @@ def attachment_path(database, attachment):
2440
2458
  return root / attachment["id"]
2441
2459
 
2442
2460
 
2461
+ def thumbnail_path(database, attachment):
2462
+ """Where the smaller copy of an image attachment is kept, beside the original."""
2463
+ return attachment_path(database, {"id": attachment["id"] + THUMBNAIL_SUFFIX})
2464
+
2465
+
2466
+ def store_attachment_thumbnail(connection, database, room_id, identifier, token, data):
2467
+ """Keep the smaller copy of an image attachment a room participant's page made; the first one stored stays.
2468
+
2469
+ The site cannot decode images, so it checks what it can read from the headers: a WebP or JPEG no larger than
2470
+ MAX_THUMBNAIL_SIDE pixels, smaller than the original, with the original's shape.
2471
+
2472
+ Returns:
2473
+ {"attachment": the attachment with its thumbnail_url, "duplicate": whether a thumbnail was already kept}.
2474
+ """
2475
+ begin_write(connection)
2476
+ try:
2477
+ require_owner(connection, room_id, token)
2478
+ except PermissionError:
2479
+ require_member(connection, room_id, token)
2480
+ attachment = get_attachment(connection, room_id, identifier)
2481
+ if attachment.get("thumbnail_type"):
2482
+ return {"attachment": attachment, "duplicate": True}
2483
+ content_type = attachment_content_type(data)
2484
+ width, height = image_size(io.BytesIO(data))
2485
+ original_width, original_height = attachment.get("width") or 0, attachment.get("height") or 0
2486
+ if (attachment["content_type"] not in SIZED_IMAGE_TYPES or content_type not in THUMBNAIL_TYPES or not width
2487
+ or max(width, height) > MAX_THUMBNAIL_SIDE or len(data) >= attachment["size"] or not original_width
2488
+ or abs(width / height - original_width / original_height) > THUMBNAIL_RATIO_TOLERANCE * original_width / original_height):
2489
+ raise ValueError(Text('缩略图不符合要求'))
2490
+ path = thumbnail_path(database, attachment)
2491
+ path.parent.mkdir(parents=True, exist_ok=True)
2492
+ path.write_bytes(data)
2493
+ connection.execute("UPDATE attachments SET thumbnail_type=? WHERE id=?", (content_type, identifier))
2494
+ connection.commit()
2495
+ return {"attachment": get_attachment(connection, room_id, identifier), "duplicate": False}
2496
+
2497
+
2443
2498
  def store_attachment(connection, database, room_id, metadata, data):
2444
2499
  """Persist one immutable upload; exact retries return the original file."""
2445
2500
  begin_write(connection)
@@ -2484,6 +2539,7 @@ def remove_attachment_files(connection, database, rows):
2484
2539
  for row in rows:
2485
2540
  connection.execute("DELETE FROM attachments WHERE id=? AND message_id IS NULL", (row["id"],))
2486
2541
  attachment_path(database, row).unlink(missing_ok=True)
2542
+ thumbnail_path(database, row).unlink(missing_ok=True)
2487
2543
 
2488
2544
 
2489
2545
  def prune_unsent_attachments(connection, database, room_id):
@@ -2517,11 +2573,13 @@ def sweep_attachments(database):
2517
2573
  registered = {os.path.normcase(row[0]) for row in connection.execute("SELECT id FROM attachments")}
2518
2574
  cutoff = time.time() - ORPHAN_ATTACHMENT_GRACE_SECONDS
2519
2575
  for path in root.iterdir():
2520
- if os.path.normcase(path.name) in registered:
2576
+ # A thumbnail goes with its original.
2577
+ name = path.name.removesuffix(THUMBNAIL_SUFFIX)
2578
+ if os.path.normcase(name) in registered:
2521
2579
  continue
2522
2580
  try:
2523
2581
  info = path.lstat()
2524
- if stat.S_ISREG(info.st_mode) and (path.name in expired or info.st_mtime < cutoff):
2582
+ if stat.S_ISREG(info.st_mode) and (name in expired or info.st_mtime < cutoff):
2525
2583
  path.unlink()
2526
2584
  except FileNotFoundError:
2527
2585
  pass
@@ -3450,6 +3508,8 @@ class DiscussionServer(ThreadingHTTPServer):
3450
3508
  self.local_launch = local_launch
3451
3509
  # Project media the local page may play: ticket -> (path, size, mtime_ns, content_type, name, expires).
3452
3510
  self.media_tickets = {}
3511
+ # Project pages opened in a tab of the computer's own browser: ticket -> (project folder, expires).
3512
+ self.page_tickets = {}
3453
3513
  self.media_lock = threading.Lock()
3454
3514
  self.local_site = not hub and address[0] in ("127.0.0.1", "::1", "localhost")
3455
3515
  self.admin_setup_key = os.getenv("DISCUSS_ADMIN_SETUP_KEY") or secrets.token_urlsafe(18)
@@ -3692,6 +3752,8 @@ class DiscussionHandler(BaseHTTPRequestHandler):
3692
3752
  self.bridged = self.relay_bridge(parts)
3693
3753
  if parts[:3] == ["api", "local", "media"] and len(parts) == 4 and method == "GET":
3694
3754
  return self.serve_media_ticket(parts[3])
3755
+ if parts[:3] == ["api", "local", "page"] and len(parts) >= 5 and method == "GET":
3756
+ return self.serve_page_ticket(parts[3], parts[4:])
3695
3757
  if parts[:2] == ["api", "local"]:
3696
3758
  return self.handle_local_launch(parts, method)
3697
3759
  if parts == ["api", "updates"] and method == "GET":
@@ -3927,9 +3989,12 @@ class DiscussionHandler(BaseHTTPRequestHandler):
3927
3989
 
3928
3990
  The page never learns the file's path; the ticket names one file as it was checked and expires.
3929
3991
  """
3992
+ if payload.get("page") is True:
3993
+ return self.issue_page_ticket(payload)
3930
3994
  status, result = self.local_command_result("room-media", payload)
3931
3995
  if status != 200:
3932
3996
  return self.respond(result, status)
3997
+ result.pop("directory", None)
3933
3998
  path = Path(result.pop("file"))
3934
3999
  info = path.stat()
3935
4000
  ticket = secrets.token_urlsafe(32)
@@ -3945,6 +4010,48 @@ class DiscussionHandler(BaseHTTPRequestHandler):
3945
4010
  tickets[ticket] = (path, info.st_size, info.st_mtime_ns, result["content_type"], path.name, now + MEDIA_TICKET_SECONDS, disposition)
3946
4011
  return self.respond({**result, "url": f"/api/local/media/{ticket}"})
3947
4012
 
4013
+ def issue_page_ticket(self, payload):
4014
+ """Open a project HTML file in a tab of this computer's browser straight from disk, with the files beside it.
4015
+
4016
+ The runner checks the member's access to the file as for media; the ticket names the project folder, and the
4017
+ address mirrors the file's place in it, so relative references resolve inside the folder.
4018
+ """
4019
+ if not re.search(r"\.html?$", str(payload.get("path", "")), re.I):
4020
+ raise ValueError(Text('只能打开 HTML 文件'))
4021
+ status, result = self.local_command_result("room-media", {**{key: value for key, value in payload.items() if key != "page"}, "download": True})
4022
+ if status != 200:
4023
+ return self.respond(result, status)
4024
+ root, path = Path(result["directory"]).resolve(), Path(result["file"]).resolve()
4025
+ ticket = secrets.token_urlsafe(32)
4026
+ now = time.time()
4027
+ with self.server.media_lock:
4028
+ tickets = self.server.page_tickets
4029
+ for key in [key for key, item in tickets.items() if item[1] <= now]:
4030
+ del tickets[key]
4031
+ while len(tickets) >= MAX_MEDIA_TICKETS:
4032
+ del tickets[next(iter(tickets))]
4033
+ tickets[ticket] = (root, now + PAGE_TICKET_SECONDS)
4034
+ relative = "/".join(quote(part) for part in path.relative_to(root).parts)
4035
+ return self.respond({"url": f"/api/local/page/{ticket}/{relative}"})
4036
+
4037
+ def serve_page_ticket(self, ticket, parts):
4038
+ """Serve one file of the project folder a page ticket names, sandboxed; nothing outside the folder."""
4039
+ with self.server.media_lock:
4040
+ item = self.server.page_tickets.get(ticket)
4041
+ if not item or item[1] <= time.time():
4042
+ raise LookupError(Text('页面地址已过期,请重新打开文件'))
4043
+ root = item[0]
4044
+ names = [unquote(part) for part in parts]
4045
+ if any(name in ("", ".", "..") or ":" in name or "\\" in name for name in names):
4046
+ raise LookupError(Text('文件不存在'))
4047
+ path = root.joinpath(*names).resolve()
4048
+ if not path.is_relative_to(root) or not path.is_file():
4049
+ raise LookupError(Text('文件不存在'))
4050
+ content_type = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
4051
+ if content_type.startswith("text/") or content_type in ("application/javascript", "application/json"):
4052
+ content_type += "; charset=utf-8"
4053
+ self.send_file(path, content_type, path.name, "inline", policy=PAGE_POLICY)
4054
+
3948
4055
  def serve_media_ticket(self, ticket):
3949
4056
  """Stream the project media file a ticket names, refusing it once expired or changed since it was checked."""
3950
4057
  with self.server.media_lock:
@@ -4565,6 +4672,15 @@ class DiscussionHandler(BaseHTTPRequestHandler):
4565
4672
  return self.respond(discard_attachment(connection, self.server.database, room_id, parts[4], self.headers.get("X-Discussion-Token", "")))
4566
4673
  if method == "POST" and len(parts) == 6 and parts[5] == "import":
4567
4674
  return self.import_attachment(connection, room_id, parts[4])
4675
+ if method == "POST" and len(parts) == 6 and parts[5] == "thumbnail":
4676
+ length = int(self.headers.get("Content-Length", "-1"))
4677
+ if not 0 < length <= MAX_THUMBNAIL_BYTES:
4678
+ return self.respond({"error": Text('缩略图不符合要求')}, 413)
4679
+ data = self.rfile.read(length)
4680
+ if len(data) != length:
4681
+ raise ValueError(Text('附件内容不完整'))
4682
+ return self.respond(store_attachment_thumbnail(connection, self.server.database, room_id, parts[4],
4683
+ self.headers.get("X-Discussion-Token", ""), data))
4568
4684
  if method == "GET" and len(parts) in (5, 6):
4569
4685
  attachment = get_attachment(connection, room_id, parts[4], params, self.headers.get("X-Discussion-Token", ""),
4570
4686
  content=len(parts) == 6)
@@ -4572,6 +4688,11 @@ class DiscussionHandler(BaseHTTPRequestHandler):
4572
4688
  return self.respond(attachment)
4573
4689
  if parts[5] == "content":
4574
4690
  return self.respond_attachment(attachment, params.get("download") == "1")
4691
+ if parts[5] == "thumbnail":
4692
+ path = thumbnail_path(self.server.database, attachment)
4693
+ if not attachment.get("thumbnail_type") or not path.is_file():
4694
+ raise LookupError(Text('附件不存在'))
4695
+ return self.send_file(path, attachment["thumbnail_type"], attachment["file_name"], "inline")
4575
4696
  if parts[5] == "zip":
4576
4697
  path = attachment_path(self.server.database, attachment)
4577
4698
  if not path.is_file():
@@ -4606,8 +4727,11 @@ class DiscussionHandler(BaseHTTPRequestHandler):
4606
4727
  disposition = "attachment" if download or attachment["content_type"] == "application/octet-stream" else "inline"
4607
4728
  self.send_file(path, attachment["content_type"], attachment["file_name"], disposition, {"X-Content-SHA256": attachment["sha256"]})
4608
4729
 
4609
- def send_file(self, path, content_type, file_name, disposition, extra=None, data=None):
4610
- """Send one stored file, or the single byte range a player asks for, never as executable content."""
4730
+ def send_file(self, path, content_type, file_name, disposition, extra=None, data=None, policy="default-src 'none'; sandbox"):
4731
+ """Send one stored file, or the single byte range a player asks for, never as executable content.
4732
+
4733
+ `policy` is the Content-Security-Policy; a project page opened in its own tab runs sandboxed (PAGE_POLICY).
4734
+ """
4611
4735
  size = path.stat().st_size if data is None else len(data)
4612
4736
  start, end, status = 0, size - 1, 200
4613
4737
  match = re.fullmatch(r"bytes=(\d*)-(\d*)", self.headers.get("Range", "").strip())
@@ -4633,7 +4757,7 @@ class DiscussionHandler(BaseHTTPRequestHandler):
4633
4757
  for name, value in (extra or {}).items():
4634
4758
  self.send_header(name, value)
4635
4759
  self.send_header("X-Content-Type-Options", "nosniff")
4636
- self.send_header("Content-Security-Policy", "default-src 'none'; sandbox")
4760
+ self.send_header("Content-Security-Policy", policy)
4637
4761
  self.send_header("Cache-Control", "no-store")
4638
4762
  self.send_header("Referrer-Policy", "no-referrer")
4639
4763
  self.end_headers()
@@ -52,7 +52,7 @@ Rooms created by a host inherit its folder. Select the arrow to the left of the
52
52
  ### 4. Send and view attachments
53
53
 
54
54
  - **Attach files.** Paste or drag files into the composer, or use the paperclip button at the bottom-left. Each message can contain up to 10 files, 20 MiB each. Thumbnails appear above the composer. A placeholder such as `[Image #1]` or `[File #2]` is inserted at the cursor. Removing the thumbnail or deleting its placeholder with Backspace removes both. After sending, images first referenced in a paragraph or list item appear right below it in a two-column half-width grid (full width for a single image on phones, two columns for multiple, with `#n` badges when a message carries more than one image) and are not listed again below; other attachments stay listed under the message. The site automatically clears uploads left unsent for more than 24 hours. Attachments in sent or queued messages are kept.
55
- - **View attachments.** After sending a message, select its placeholder or attachment card. Images can be enlarged full-screen, zoomed, rotated, and saved. Audio and video play in the message. Documents and code open in the file preview.
55
+ - **View attachments.** After sending a message, select its placeholder or attachment card. Images can be enlarged full-screen, zoomed, rotated, and saved; when the room has several images, the side buttons or the left and right arrow keys step between them. Audio and video play in the message. Documents and code open in the file preview.
56
56
  - **Interactive visualizations.** A member can place a small web page you can operate (drag a slider, press a button, watch the result change) inside the answer text. It appears at that point in the answer, follows the room theme and light or dark mode, and also appears in place on a phone. It starts running when you scroll near it. The row below lets you “Collapse” it (your choice is remembered), view the “Source”, “Open larger preview” in the file preview, open it in a “New tab”, or “Download” it as an `.html` file. Read-only share pages, read-aloud, and collapsed message previews show a single “Interactive visualization” line instead, so rely on the member's written conclusion. `.html` attachments do not run inside messages; select the file card to open them in the preview or a new tab. Some visualizations are question panels: after you rank, allocate, or adjust and press the panel's submit button, the result is added above the message box as a quote rather than sent. You can edit or remove it, and it counts as your reply only when you send it. Submitting the same panel again replaces its earlier result.
57
57
  - **Member access to attachments.** For supported automatic runs, the local service downloads the file and passes its information to the receiving member. Claude Code and Codex CLI can view images directly. For API members, enable “Images” on the member card to view images. UTF-8 text attachments can be read on request. Members will say when they cannot read a format such as PDF.
58
58
 
@@ -28,7 +28,7 @@ Room work can run on several lines in parallel. Labels at the top of a card show
28
28
  - A directly mentioned member starts immediately when idle. If busy, its request waits in the queue until it is free. If one message mentions both idle and busy members, idle members start at once while the busy members’ work waits.
29
29
  - When a main-line member’s turn arrives, it waits for that member to finish its active branch work.
30
30
  - Your unmentioned messages, `@all`, and `@all-seq` wait until the room is idle, then go out in order. Background work assigned by the host does not hold up your new messages.
31
- - **Where things sit on a card.** Every member card has, from top to bottom: the header, the body, what it delivers (answer summary, attachments, delivered files) and the run’s record (progress notes with step count, file changes, refused operations). File changes list only files the member was recorded writing during that run. Git files in the main project and additional writable projects support diff previews. The execution timeline counts the same files. The left of the header says who: the name, labels, and the model and effort this run used. The right says how this one went: status, time, number and duration, with the duration always last. A coloured status only means something went wrong (red for failed; amber for stopped, voided or skipped), and nothing is shown when all is well; on your own messages, the right shows how each member is handling it. On a phone, the buttons for retracting, editing, private chat and the like sit at the top right of the card, level with the name; the model, status, time, number and duration run from the left under the name. Stop and retry sit at the right end of the line they act on. Project files mentioned in an answer appear as clickable cards once verified as deliverables for that execution.
31
+ - **Where things sit on a card.** Every member card has, from top to bottom: the header, the body, what it delivers (answer summary, attachments, delivered files) and the run’s record (progress notes with step count, file changes, refused operations). File changes list only files the member was recorded writing during that run. Git files in the main project and additional writable projects support diff previews. The execution timeline counts the same files. The left of the header says who: the name, labels, and the model and effort this run used. The right says how this one went: status, time, number and duration, with the duration always last. A coloured status only means something went wrong (red for failed; amber for stopped, voided or skipped), and nothing is shown when all is well; on your own messages, the right shows how each member is handling it. On a phone, the buttons for retracting, editing, private chat and the like sit at the top right of the card, level with the name; the model, status, time, number and duration run from the left under the name. Stop and retry sit at the right end of the line they act on. Project files mentioned in an answer appear as clickable cards once verified as deliverables for that execution; a web page card also has “Open in new tab”, which shows the page whole in an isolated tab: on this computer it opens straight from disk with the images and scripts beside it, at any size; on other devices it is read through the computer, up to 64 MB (the preview window shows pages of the same size).
32
32
  - **Card labels.** Where the card came from comes first, then where the work goes next. The usual channels (own message, CLI, API) are no longer labelled; only rare sources such as sent on someone’s behalf, proactive messages and auto-captured answers are.
33
33
  - “Host” identifies a message from the current host, host notes included.
34
34
  - “Main line · step {n}” is a host-arranged order. “Main line · #{n} in turn” is `@all-seq`.
@@ -50,7 +50,7 @@
50
50
  ### 4. 发送与查看附件
51
51
 
52
52
  - **添加附件**:在输入框粘贴、拖入文件,或点左下角回形针按钮选择文件(每条消息最多 10 个,单个最多 20 MiB)。添加后输入框上方出现缩略图,正文光标处插入 `[图片 #1]`、`[文件 #2]` 等房间内连续编号的占位标签;删掉缩略图或按退格删掉占位,两边同步移除。发出后,正文里首次写到 `[图片 #n]` 的图片会紧跟在所在段落或列表项下方以半宽两列排布显示(手机上单张占满整宽、多张两列并排,多图消息附带 `#n` 角标),附件列表不再重复列出;其他附件仍列在消息下方。 已上传但一直未发送的附件超过 24 小时后会自动清理;已发送或仍在排队消息里的附件会保留。
53
- - **查看附件**:消息发出后点正文占位或附件卡片即可打开;图片支持全屏缩放、旋转与保存,音视频直接在消息里播放,文档与代码在文件预览窗口打开。
53
+ - **查看附件**:消息发出后点正文占位或附件卡片即可打开;图片支持全屏缩放、旋转与保存,房间里有多张图片时可用两侧按钮或键盘左右方向键切换,音视频直接在消息里播放,文档与代码在文件预览窗口打开。
54
54
  - **交互式可视化**:成员可以在回答正文里放一段可以操作的网页(拖动滑块、点按钮看结果变化),它显示在正文中的原位置,跟随房间主题和深浅色,手机上同样直接显示。滚到它附近才开始运行。下方一行可“收起”(会记住选择)、看“源码”、“放大”到文件预览窗口、在“新标签页”打开或“下载”为 `.html` 文件。只读分享页、朗读和消息折叠时的预览只显示“交互式可视化”一行,结论以成员写在正文里的文字为准。`.html` 附件不在消息内显示,点文件卡片在预览窗口或新标签页打开。有的可视化是提问面板:你在里面排序、分配或调整后点它的提交按钮,结果会作为引用放到输入框上方,不会直接发出;你可以删改,点发送才算回答。同一面板再次提交会替换上一次的结果。
55
55
  - **成员读取附件**:本机服务为支持附件的自动执行下载文件,并把文件信息交给接收任务的成员。Claude Code 和 Codex CLI 可直接看图;API 成员需在卡片设置中打开“看图”才能看图,UTF-8 文本附件可按需读取,PDF 等其他文件读不到时会如实说明。
56
56
 
@@ -28,7 +28,7 @@
28
28
  - 被你直接 `@` 的成员空闲就立即开始,正忙就进入排队区,一空闲立刻收到。如果一条消息同时 `@` 了空闲成员和忙碌成员,空闲的立刻开工,忙碌的那份留在排队区等它空闲。
29
29
  - 主线轮到某位成员时,会等它做完手头支线再继续。
30
30
  - 你发出的未点名消息、`@全体成员`、`@全体依次` 等整个房间空闲后再按顺序发出(主持人派出的后台任务不会阻塞你的新消息)。
31
- - **卡片的固定位置**:每张成员卡从上到下依次是卡头、正文、交付(回答摘要、附件、交付文件)、过程记录(过程说明与步数、文件改动、被拒操作)。文件改动只列出能确认由该成员在本次执行中写过的文件。主项目和额外可写项目里的 Git 文件均可查看差异;执行时间线按同一范围计数。卡头左边说“是谁”:名字、标签和这次用的模型与强度;右边说“这一次怎么样”:状态、时间、编号、耗时,耗时总在最右。带颜色的状态只表示出了问题(红色失败,琥珀色停止、作废、跳过),正常时不标;你发的消息上,右边是各成员的处理状态。手机上撤回、编辑、私聊等按钮在卡片右上角,和名字同一行;模型、状态、时间、编号、耗时在名字下方从左排起。停止、重试按钮在它作用的那一行右端。回答中提到的项目文件经核实属于本次交付后,才会显示为可打开的卡片。
31
+ - **卡片的固定位置**:每张成员卡从上到下依次是卡头、正文、交付(回答摘要、附件、交付文件)、过程记录(过程说明与步数、文件改动、被拒操作)。文件改动只列出能确认由该成员在本次执行中写过的文件。主项目和额外可写项目里的 Git 文件均可查看差异;执行时间线按同一范围计数。卡头左边说“是谁”:名字、标签和这次用的模型与强度;右边说“这一次怎么样”:状态、时间、编号、耗时,耗时总在最右。带颜色的状态只表示出了问题(红色失败,琥珀色停止、作废、跳过),正常时不标;你发的消息上,右边是各成员的处理状态。手机上撤回、编辑、私聊等按钮在卡片右上角,和名字同一行;模型、状态、时间、编号、耗时在名字下方从左排起。停止、重试按钮在它作用的那一行右端。回答中提到的项目文件经核实属于本次交付后,才会显示为可打开的卡片;网页文件的卡片上另有“在新标签页打开”按钮,在隔离的页面里完整显示:在这台电脑上直接从磁盘打开,同目录的图片、脚本照常加载,大小不限;在其他设备上经电脑读取后打开,最大 64 MB(同样适用于预览窗口)。
32
32
  - **卡片头部标签**:先写这张卡从哪来,再写接下来去哪。常见的发言渠道(本人发言、CLI、API)不再标出,只标代发、主动发言、自动收录这类少见来源。
33
33
  - “主持”:当前主持人的发言,主持说明卡也用它。
34
34
  - “主线 · 第 n 棒”(主持人安排的顺序)或“主线 · 第 n 位”(`@全体依次`)。
@@ -544,6 +544,9 @@
544
544
  "分享卡:{name}": "Share card: {name}",
545
545
  "复制图片": "Copy image",
546
546
  "保存图片": "Save image",
547
+ "上一张": "Previous image",
548
+ "下一张": "Next image",
549
+ "{name} · {index}/{total}": "{name} · {index}/{total}",
547
550
  "共议 AI CoDiscuss": "AI CoDiscuss",
548
551
  "多个 AI 在同一个房间协作": "Several AIs working in one room",
549
552
  "问题": "Question",
@@ -596,6 +599,8 @@
596
599
  "「{name}」还在清理,可在房间目录“…”里的“销毁记录”查看进度或重试。": "“{name}” is still being cleaned up; follow it or retry under “Destruction records” in the room list's “…” menu.",
597
600
  "部署为网站": "Deploy as website",
598
601
  "把 {value1} 部署为网站": "Deploy {value1} as a website",
602
+ "在新标签页打开 {value1}": "Open {value1} in a new tab",
603
+ "正在读取 {value1}…": "Reading {value1}…",
599
604
  "已上线 · {time} 前有效": "Live · until {time}",
600
605
  "已过期": "Expired",
601
606
  "已被运营方下架": "Taken down by the operator",
@@ -138,6 +138,10 @@
138
138
  "房间没有进行中的讨论会话": "Room has no ongoing discussion session",
139
139
  "附件上传者须与凭据身份一致": "Attachment uploader must match the credential identity",
140
140
  "附件内容不完整": "Attachment content is incomplete",
141
+ "缩略图不符合要求": "The thumbnail does not meet the requirements",
142
+ "只能打开 HTML 文件": "Only HTML files can be opened",
143
+ "页面地址已过期,请重新打开文件": "The page address has expired. Open the file again.",
144
+ "文件不存在": "The file does not exist",
141
145
  "只有当前 AI 主持人可以安排讨论发言": "Only the current AI host can schedule discussion turns",
142
146
  "只有当前 AI 主持人可以转交讨论追问": "Only the current AI host can hand off discussion follow-ups",
143
147
  "只有当前 AI 主持人可以继续讨论安排": "Only the current AI host can continue the discussion schedule",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai_co_discuss",
3
- "version": "0.5.28",
3
+ "version": "0.5.29",
4
4
  "bin": {
5
5
  "codiscuss": "runner/codiscuss.mjs"
6
6
  },
@@ -706,8 +706,14 @@ export async function remote_room_files(home, input) {
706
706
  return room_files(home, input, { trust: true });
707
707
  }
708
708
 
709
- // A relayed answer carries this much of a page at a time, within the relay's encrypted envelope after base64.
710
- const PAGE_PART_BYTES = 192 * 1024;
709
+ // A relayed answer carries this much of a page at a time, within the relay's encrypted envelope after base64
710
+ // (gzip takes back the inner base64, so a part of this size stays near 700 KB in a frame of 1 MB).
711
+ const PAGE_PART_BYTES = 512 * 1024;
712
+ // The page another device is reading part by part: put together when it asks for the first part and reused for the
713
+ // rest, instead of again for every part (a 38 MB page in 512 KB parts), and dropped once its last part is sent. A file
714
+ // changing meanwhile shows when the page is read again; `version` is the same for every part of one read.
715
+ let reading_page = null;
716
+
711
717
 
712
718
  /**
713
719
  * One HTML file of the room's project with the files it refers to inlined (see `bundle_project_page`), or the images a
@@ -722,8 +728,11 @@ export async function room_page(home, raw, { trust = false, parts = false } = {}
722
728
  const directory = files_root(home, config, root);
723
729
  if (!Number.isSafeInteger(offset) || offset < 0) throw new Error('页面读取位置无效');
724
730
  const bundle = /\.(md|markdown)$/i.test(String(input.path || '')) ? bundle_project_markdown : bundle_project_page;
725
- const { bytes, ...page } = bundle(directory, input.path);
731
+ const key = `${directory}\n${input.path}`;
732
+ const reuse = parts && offset > 0 && reading_page?.key === key;
733
+ const { bytes, ...page } = reuse ? reading_page.page : bundle(directory, input.path);
726
734
  const part = bytes.subarray(offset, parts ? offset + PAGE_PART_BYTES : bytes.length);
735
+ if (parts) reading_page = offset + part.length < bytes.length ? { key, page: { bytes, ...page } } : null;
727
736
  return { room_id: input.room_id, root, ...page, total: bytes.length, offset, data: part.toString('base64') };
728
737
  }
729
738
 
@@ -744,7 +753,8 @@ export async function room_media(home, raw, { trust = false, parts = false } = {
744
753
  if (!Number.isSafeInteger(offset) || offset < 0) throw new Error('文件读取位置无效');
745
754
  // `download` reads any regular file for saving, not only the kinds the preview shows.
746
755
  const { file, ...media } = project_media(directory, input.path, { download: input.download === true });
747
- if (!parts) return { room_id: input.room_id, root, ...media, file };
756
+ // The folder goes to the computer's own website alone, for a page opened in a tab (it never reaches a page).
757
+ if (!parts) return { room_id: input.room_id, root, ...media, file, directory };
748
758
  if (media.size > REMOTE_MEDIA_MAX_BYTES) {
749
759
  throw new Error(input.download === true
750
760
  ? `文件 ${Math.ceil(media.size / 1024 / 1024)} MB,超过其他设备可下载的 ${REMOTE_MEDIA_MAX_BYTES / 1024 / 1024} MB 上限;请在这台电脑上取用,或让 AI 处理`
@@ -3585,7 +3595,6 @@ export async function launch_main(args = process.argv.slice(2), input_text) {
3585
3595
  ? { ...input, extra_directories: input.extra_directories.map(item => typeof item === 'string' ? item : item?.path) } : input;
3586
3596
  const kept = await kept_directories(home, positionals[0], input, { folders: Boolean(values.remote) && !restricted });
3587
3597
  guard_remote_request(positionals[0], guard_input, { projects: granted_projects(home), participants: launch_settings(home).participants, home, kept });
3588
- if (values.remote && positionals[0] === 'room-workflow' && input?.action === 'host') throw new Error('主持人权限只能在电脑上开启');
3589
3598
  if (restricted && positionals[0] === 'pick-directory') throw new Error('此账号只能使用自己的项目文件夹');
3590
3599
  // Another device repeats the saved program locations it cannot see; keep them rather than dropping them.
3591
3600
  if (positionals[0] === 'settings' && input?.participants) input.participants = keep_saved_locations(home, input.participants);
@@ -271,6 +271,9 @@ export function read_project_folders(cwd, folders) {
271
271
 
272
272
  // An HTML page with the files it refers to inlined stays within this size; references past it are left as they are.
273
273
  export const PAGE_MAX_BYTES = 8 * 1024 * 1024;
274
+ // The largest HTML file shown in full; a self-contained page (images inlined) is often far past PAGE_MAX_BYTES itself,
275
+ // and then nothing it refers to is inlined (2026-11-26: a 38 MB catalogue page only showed its first 128 KB as text).
276
+ export const PAGE_FILE_MAX_BYTES = 64 * 1024 * 1024;
274
277
  // Media types of the files a page may refer to; others are left as they are.
275
278
  const PAGE_TYPES = {
276
279
  css: 'text/css', js: 'text/javascript', mjs: 'text/javascript', json: 'application/json', txt: 'text/plain', csv: 'text/csv',
@@ -354,10 +357,10 @@ export function bundle_project_page(cwd, path) {
354
357
  if (!/\.html?$/i.test(target)) throw new Error('只能打开 HTML 文件');
355
358
  const info = statSync(target);
356
359
  if (!info.isFile()) throw new Error('只能预览普通文件');
357
- if (info.size > PAGE_MAX_BYTES) throw new Error('HTML 文件超过 8 MiB,无法完整显示');
360
+ if (info.size > PAGE_FILE_MAX_BYTES) throw new Error('HTML 文件超过 64 MiB,无法完整显示');
358
361
  const normalized = path.replaceAll('\\', '/').split('/').filter(part => part && part !== '.').join('/');
359
362
  const base = posix.dirname(normalized);
360
- const state = { root, budget: PAGE_MAX_BYTES - info.size, inlined: new Map(), missing: new Set(), skipped: new Set() };
363
+ const state = { root, budget: Math.max(0, PAGE_MAX_BYTES - info.size), inlined: new Map(), missing: new Set(), skipped: new Set() };
361
364
  const html = readFileSync(target, 'utf8').replace(PAGE_PARTS, (whole, script_open, script_body, script_close, style_open, style_body, style_close, comment, tag) => {
362
365
  if (script_open) return page_tag(script_open, base, state) + script_body + script_close;
363
366
  if (style_open) return style_open + page_css(style_body, base, state, 0) + style_close;
@@ -50,7 +50,7 @@ const BACKLOG_LOG_MS = 60000;
50
50
  const ROOM_API_PATH = /^\/api\/(rooms|folders|revisions|sites)(\/[A-Za-z0-9_.~-]+)*(\?[A-Za-z0-9_.~%=&,:+-]*)?$/;
51
51
  const RELAY_READ_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
52
52
  // Attachment uploads arrive in parts and are sent to the local website whole, as one browser upload would be.
53
- const UPLOAD_PATH = /^\/api\/rooms\/[A-Za-z0-9_-]+\/attachments(\/[A-Za-z0-9_-]+\/import)?(\?[A-Za-z0-9_.~%=&,:+-]*)?$/;
53
+ const UPLOAD_PATH = /^\/api\/rooms\/[A-Za-z0-9_-]+\/attachments(\/[A-Za-z0-9_-]+\/(import|thumbnail))?(\?[A-Za-z0-9_.~%=&,:+-]*)?$/;
54
54
  const UPLOAD_MAX_BYTES = 20 * 1024 * 1024;
55
55
  const UPLOAD_TTL_MS = 10 * 60 * 1000;
56
56
  const uploads = new Map();
@@ -135,8 +135,10 @@ export async function room_api(home, site, payload, { fetcher = site_fetch, devi
135
135
  if (body !== undefined) headers['Content-Type'] = 'application/json';
136
136
  // A read the device already holds is asked conditionally; unchanged, the answer is a bare 304 with no body.
137
137
  if (method === 'GET' && typeof etag === 'string' && /^"[0-9a-f]{1,64}"$/.test(etag)) headers['If-None-Match'] = etag;
138
- const zip_range = method === 'GET' && /^\/api\/rooms\/[\w-]+\/attachments\/[\w-]+\/zip\?entry=/.test(path);
139
- if (zip_range) headers.Range = 'bytes=' + offset + '-' + (offset + RESPONSE_MAX_BYTES - 1);
138
+ // An attachment's bytes and a zip entry are asked from the local website for the part needed alone, not whole for
139
+ // every part (a 20 MB PDF read in pieces would read 20 MB per piece).
140
+ const ranged = method === 'GET' && /^\/api\/rooms\/[\w-]+\/attachments\/[\w-]+\/(zip\?entry=|(content|thumbnail)$)/.test(path);
141
+ if (ranged) headers.Range = 'bytes=' + offset + '-' + (offset + RESPONSE_MAX_BYTES - 1);
140
142
  const on_request = timing?.route ? () => { timing.local_request_at = performance.now(); } : undefined;
141
143
  if (on_request) headers['X-CoDiscuss-Relay-Request-Id'] = timing.id;
142
144
  const response = await fetcher(`${local_origin(home)}${path}`, { method, headers, redirect: 'error',
@@ -147,7 +149,11 @@ export async function room_api(home, site, payload, { fetcher = site_fetch, devi
147
149
  if (type.startsWith('application/json')) return { status: response.status, body: await response.json(), ...(tag ? { etag: tag } : {}) };
148
150
  // A file larger than one frame comes back in parts; the device asks again from where the previous part ended.
149
151
  const bytes = Buffer.from(await response.arrayBuffer());
150
- if (zip_range && response.status === 206) {
152
+ // Asked from past the end (an empty file): no bytes, and the size the website gives.
153
+ if (ranged && response.status === 416) {
154
+ return { status: 200, content_type: type, offset, total: Number(/\/(\d+)$/.exec(response.headers.get('Content-Range') || '')?.[1] || 0), body_base64: '' };
155
+ }
156
+ if (ranged && response.status === 206) {
151
157
  const range = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(response.headers.get('Content-Range') || '');
152
158
  if (!range || Number(range[1]) !== offset || Number(range[2]) - offset + 1 !== bytes.length
153
159
  || Number(range[3]) <= Number(range[2])) throw new Error(t('无法读取这个压缩包条目'));