ai_co_discuss 0.5.65 → 0.5.66

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.
package/backend/server.py CHANGED
@@ -155,6 +155,19 @@ MEDIA_GENERATION_TIMEOUT = 960
155
155
  MEDIA_GENERATION_COMMANDS = ("image-generate", "video-generate")
156
156
  MEDIA_ROOM_COMMANDS = MEDIA_GENERATION_COMMANDS + ("media-job",)
157
157
  MEDIA_COMMANDS = MEDIA_ROOM_COMMANDS + ("video-settings", "video-check")
158
+ MEDIA_META_CHOICES = {
159
+ "mode": {"image", "video"}, "action": {"generate", "edit"},
160
+ "quality": {"auto", "low", "medium", "high", "xhigh", "max"},
161
+ "output_format": {"png", "jpeg", "webp", "gif", "svg", "mp4"},
162
+ "background": {"auto", "opaque", "transparent"}, "complexity": {"low", "medium", "high"},
163
+ "moderation": {"auto", "low"}, "input_fidelity": {"low", "high"},
164
+ }
165
+ MEDIA_META_INTEGERS = {"n": (1, 10), "seconds": (1, 2**53 - 1), "frame_count": (2, 16), "frame_duration_ms": (20, 2000)}
166
+ MEDIA_META_MODEL = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:/@-]{0,127}")
167
+ MEDIA_META_SIZE = re.compile(r"(?:auto|[1-9][0-9]{0,4}x[1-9][0-9]{0,4})")
168
+ MEDIA_META_SECRET = re.compile(
169
+ r"(?i)(?:sk[-_]|gsk_|gh[pousr]_|akia|aiza|eyJ[a-z0-9_-]*\.|data:)|[a-f0-9]{32,}|[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}"
170
+ )
158
171
  MACHINE_COMMAND_POLL_SECONDS = 0.5
159
172
  # Ordering and filing a channel only rearrange the shared directory, like folder edits, so they need no room credential.
160
173
  DIRECTORY_OPERATIONS = ("move", "folder", "detach")
@@ -319,6 +332,7 @@ MESSAGE_QUERY = """SELECT messages.*, COALESCE(details.kind,'opinion') AS kind,
319
332
  COALESCE(details.submitted_by, CASE WHEN messages.source IN ('cli','api','url','user')
320
333
  THEN messages.author ELSE '用户' END) AS submitted_by,
321
334
  COALESCE(summaries.text,'') AS summary, COALESCE(summaries.author,'') AS summary_by, timing.elapsed_seconds,
335
+ media.message_id AS no_wake_id, media.media_meta,
322
336
  answered.execution_id, answered.request_message_id, answered.layout_after, answered.layout_at, COALESCE(withdrawn.kind,'') AS withdrawn,
323
337
  CASE WHEN messages.author='用户' THEN (
324
338
  SELECT CASE WHEN COUNT(parent_id)=COUNT(*) AND MIN(parent_id)=MAX(parent_id) THEN MIN(parent_id) END
@@ -357,6 +371,7 @@ COALESCE(NULLIF(relay.member,''),(SELECT name FROM room_members WHERE room_id=re
357
371
  CASE WHEN relay.message_id IS NOT NULL THEN (SELECT m.name FROM member_requests q JOIN room_members m ON m.id=q.member_id
358
372
  WHERE q.message_id=messages.id ORDER BY q.id LIMIT 1) END AS relay_to
359
373
  FROM messages LEFT JOIN message_details AS details ON details.message_id=messages.id
374
+ LEFT JOIN message_no_wake AS media ON media.message_id=messages.id
360
375
  LEFT JOIN moss_channel_out AS outbound ON outbound.message_id=messages.id
361
376
  LEFT JOIN (SELECT message_id,target_room_id,host,target_message_id,queued_id,interrupted,state FROM room_relay_sends) AS sent
362
377
  ON sent.message_id=messages.id
@@ -818,8 +833,11 @@ def init_database(database, seed=True):
818
833
  moss_results.migrate_delegations(connection)
819
834
  connection.executescript(SCHEMA + cloud_shares.SCHEMA)
820
835
  connection.execute("""CREATE TABLE IF NOT EXISTS message_no_wake (
821
- message_id INTEGER PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE
836
+ message_id INTEGER PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE,
837
+ media_meta TEXT
822
838
  )""")
839
+ if "media_meta" not in {row[1] for row in connection.execute("PRAGMA table_info(message_no_wake)")}:
840
+ connection.execute("ALTER TABLE message_no_wake ADD COLUMN media_meta TEXT")
823
841
  migrate_guest_cancel_reasons(connection)
824
842
  if "redirect_message_id" not in {row[1] for row in connection.execute("PRAGMA table_info(dispatch_withdrawals)")}:
825
843
  connection.execute("ALTER TABLE dispatch_withdrawals ADD COLUMN redirect_message_id INTEGER REFERENCES messages(id) ON DELETE SET NULL")
@@ -2895,6 +2913,9 @@ def record_api_event(database, record):
2895
2913
  data["execution_id"] = execution_id
2896
2914
  redacted_texts = {}
2897
2915
  payload_to_log = record["payload"]
2916
+ if isinstance(payload_to_log, dict) and "media_request" in payload_to_log:
2917
+ # Audit records include rejected writes. Never record the raw display metadata there.
2918
+ payload_to_log = {key: value for key, value in payload_to_log.items() if key != "media_request"}
2898
2919
  if record["path"].startswith("/executions/") and isinstance(payload_to_log, dict):
2899
2920
  payload_to_log = {key: value for key, value in payload_to_log.items() if key != "diagnostics"}
2900
2921
  if isinstance(payload_to_log, dict) and "host_strategy" in payload_to_log:
@@ -3472,6 +3493,8 @@ def renumbered_expected(expected, payload, previous):
3472
3493
  def message_with_attachments(connection, row):
3473
3494
  """Attach the published file list to an original message."""
3474
3495
  message = dict(row)
3496
+ message.pop("no_wake_id", None)
3497
+ media_meta = message.pop("media_meta", None)
3475
3498
  chain, origin, speak = (message.pop(key, None) for key in ("relay_chain", "relay_origin", "relay_speak"))
3476
3499
  if origin:
3477
3500
  message["relay_speak"] = bool(speak)
@@ -3497,6 +3520,8 @@ def message_with_attachments(connection, row):
3497
3520
  if message["withdrawn"] == "retracted":
3498
3521
  # The owner retracted it before anyone handled it: only the page that retracted it keeps the text.
3499
3522
  return {**message, "text": "", "summary": "", "suggestions": [], "attachments": []}
3523
+ if media_meta:
3524
+ message["media_request"] = json.loads(media_meta)
3500
3525
  message["texts"] = load_texts(connection, "message", message["id"])
3501
3526
  template = message["texts"].get("trigger", {}).get("template")
3502
3527
  if template in (STEWARD_PROACTIVE_TEMPLATE, STEWARD_SESSION_TEMPLATE, "steward_scheduled"):
@@ -4853,9 +4878,31 @@ def wake_group_window(connection, room_id, payload):
4853
4878
  return {"request_id": request_id, "message_id": message_id, "duplicate": False}
4854
4879
 
4855
4880
 
4881
+ def clean_media_request(raw):
4882
+ """Keep only bounded, flat display values, without copying arbitrary request fields."""
4883
+ if not isinstance(raw, dict):
4884
+ return None
4885
+ cleaned = {}
4886
+ for key, choices in MEDIA_META_CHOICES.items():
4887
+ value = raw.get(key)
4888
+ if isinstance(value, str) and value in choices:
4889
+ cleaned[key] = value
4890
+ for key, (minimum, maximum) in MEDIA_META_INTEGERS.items():
4891
+ value = raw.get(key)
4892
+ if type(value) is int and minimum <= value <= maximum:
4893
+ cleaned[key] = value
4894
+ for key, pattern in (("model", MEDIA_META_MODEL), ("size", MEDIA_META_SIZE)):
4895
+ value = raw.get(key)
4896
+ if isinstance(value, str) and len(value) <= 128 and pattern.fullmatch(value):
4897
+ if key != "model" or not MEDIA_META_SECRET.match(value):
4898
+ cleaned[key] = value
4899
+ return json.dumps(cleaned, separators=(",", ":"), sort_keys=True) if cleaned else None
4900
+
4901
+
4856
4902
  def append_free_message(connection, room, payload, actor):
4857
4903
  """Append a free-room message: the owner's creates requests, a member's completes its execution."""
4858
4904
  no_wake = payload.get("no_wake") is True
4905
+ media_meta = clean_media_request(payload.get("media_request")) if no_wake else None
4859
4906
  awaiting_user = awaiting_user_flag(payload, actor)
4860
4907
  silent = actor != "用户" and payload.get("execution_id") is not None and room.get("system_kind") == "steward_group"
4861
4908
  if payload.get("kind") == "moderation":
@@ -4886,13 +4933,13 @@ def append_free_message(connection, room, payload, actor):
4886
4933
  identifiers = attachment_ids(payload)
4887
4934
  previous = connection.execute(f"{MESSAGE_QUERY} WHERE room_id=? AND submission_id=?", (room_id, room_id, submission_id)).fetchone()
4888
4935
  if previous:
4936
+ same_media = no_wake == bool(previous["no_wake_id"]) and media_meta == previous["media_meta"]
4889
4937
  previous = message_with_attachments(connection, previous)
4890
4938
  if ((previous.get("relay_room") or None) != (payload.get("relay") or {}).get("room_id")
4891
4939
  or any(previous[key] != renumbered_expected(expected, payload, previous)[key] for key in ("author", "text", "reply_to", "kind", "submitted_by", "summary", "summary_by"))
4892
4940
  or [item["id"] for item in previous["attachments"]] != identifiers
4893
4941
  or silent != previous.get("silent", False)
4894
- or (actor == "用户" and no_wake != bool(connection.execute(
4895
- "SELECT 1 FROM message_no_wake WHERE message_id=?", (previous["id"],)).fetchone()))
4942
+ or (actor == "用户" and not same_media)
4896
4943
  or awaiting_user != bool(connection.execute("SELECT 1 FROM room_waits WHERE message_id=?", (previous["id"],)).fetchone())):
4897
4944
  raise FileExistsError(Text('这个提交编号已被另一条内容使用,请为新发言生成新编号'))
4898
4945
  check_review_retry(connection, room_id, previous["id"], payload)
@@ -4927,7 +4974,7 @@ def append_free_message(connection, room, payload, actor):
4927
4974
  connection.execute("INSERT INTO message_details (message_id,kind,submitted_by) VALUES (?,?,?)",
4928
4975
  (cursor.lastrowid, "chat", submitted_by))
4929
4976
  if no_wake:
4930
- connection.execute("INSERT INTO message_no_wake(message_id) VALUES(?)", (cursor.lastrowid,))
4977
+ connection.execute("INSERT INTO message_no_wake(message_id,media_meta) VALUES(?,?)", (cursor.lastrowid, media_meta))
4931
4978
  if silent:
4932
4979
  connection.execute("INSERT INTO moss_silent_answers(message_id) VALUES(?)", (cursor.lastrowid,))
4933
4980
  connection.execute("INSERT INTO message_summaries (message_id,text,author) VALUES (?,?,?)",
@@ -81,7 +81,7 @@ When viewing a project image through the relay on another device, supported imag
81
81
  ### 4. Send and view attachments
82
82
 
83
83
  - **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 (the administrator’s “local page” streams straight to disk without the default 50 MiB per-file cap, while still counting toward `.codiscuss`’s 10 GiB local data cap—upload very large files under “Project files” instead, or free space via “Manage attachments” in the room menu; other entries default to 50 MiB, configurable in the management panel). 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. Windows sites automatically generate smaller previews for eligible PNG and JPEG uploads. Open the image to view the original. The site automatically clears uploads left unsent for more than 24 hours. Attachments in sent or queued messages are kept.
84
- - **Large files are sent as temporary files.** On the administrator’s “local page” of a computer-hosted install (`127.0.0.1` or `localhost`), attachments stream straight onto this computer without using the cloud space or the default 50 MiB per-file cap (they still count toward `.codiscuss`’s 10 GiB local data cap; upload very large files under “Project files” instead), and videos are not force-compressed (local AI members sending or downloading attachments on the local site likewise stream directly without using the cloud space). With cloud space configured, the app estimates whether switching makes sense for uploads, whole-file downloads with measurable progress, and original image previews on paired devices, including GIFs without thumbnails. It switches at most once per file after two consecutive estimates that predict savings of at least eight seconds and half the remaining time. When no progress can be measured, it tries only after an extended period without receiving or sending bytes. Native previews and PDFs loaded page by page are not interrupted. A slow preview just shows a tip for opening or downloading it via cloud drive. Opening the image viewer immediately stops the relay read for that card and reuses any cloud transfer already in progress. As soon as the viewer gets a cloud link, it shows cloud loading status at the top if a thumbnail is visible, or in the loading placeholder otherwise. The status disappears when the original is ready. A failed preview offers “Open via cloud drive”. Document previews that read the file contents need the bucket to allow cross-origin reads from your CoDiscuss site. Once every byte has been sent, the app waits for confirmation without resending. If an automatic switch fails, the current transfer returns to its original route. If a switch fails or does not save enough time, automatic switching in that direction pauses for 90 seconds. Larger hosted downloads prefer a cloud link immediately. For eligible attachments, the “…” menu on the message card or in the file preview also offers “Download via cloud drive”. Opening and downloading use a 24-hour transfer copy. When a small attachment switches to cloud drive because the upload is slow, the computer retrieves it, saves it as a regular local attachment, and deletes the temporary cloud copy. Images (including GIFs), videos, and other files keep their usual attachment previews and do not expire under the cloud retention policy. On other devices, hosted accounts, or the online website, when an administrator has set up the cloud space (see [Management panel](admin.md)), files larger than the threshold (20 MiB by default, up to 2 GiB each) upload straight to the account's cloud space. Upload progress shows under the thumbnail; removing the thumbnail cancels the upload. They are temporary files, kept 7 days by default (an administrator can set 1–90 days): their cards say “Temporary file · size · Expires in N days” with a clock, “Expires today” in the warning colour under a day, and the card greys out with “Expired” afterwards. To keep one, choose “Keep in cloud drive” before it expires. Messages do not load their thumbnails or players; selecting the card downloads the file, and the “⋯” at its right offers “Preview” (images, audio, video and PDF), “Keep in cloud drive” and “Download”. A preview reads straight from the cloud space: video can be dragged to any point, and when the link expires during a long stop it renews itself and carries on from the same place; a PDF opens in a new tab. When the cloud space cannot be reached or the file was deleted, the card shows “Object storage is unavailable right now” or “Deleted”. Once the cloud space is full, new large uploads fail; delete old files under “Cloud space” on the Files page. Editing, taking back, or taking a queued message back into the composer leaves these files out; add them again. Share pages and exported backups do not include these files. Without the cloud space, files over the attachment limit cannot be added.
84
+ - **Large files are sent as temporary files.** On the administrator’s “local page” of a computer-hosted install (`127.0.0.1` or `localhost`), attachments stream straight onto this computer without using the cloud space or the default 50 MiB per-file cap (they still count toward `.codiscuss`’s 10 GiB local data cap; upload very large files under “Project files” instead), and videos are not force-compressed (local AI members sending or downloading attachments on the local site likewise stream directly without using the cloud space). With cloud space configured, the app estimates whether switching makes sense for uploads, whole-file downloads with measurable progress, and original image previews on paired devices, including GIFs without thumbnails. It uses recent measured speeds before starting and checks again about one second into a transfer. It can switch if it expects to save at least three seconds and half the remaining time. If the original route slows down, two consecutive estimates must meet that same threshold. A transfer that receives or sends no new bytes for 6–12 seconds can also switch. Each file switches at most once, and the app periodically tries the original route to detect recovery. Native previews and PDFs loaded page by page are never interrupted. They only show a tip for opening or downloading via cloud drive, after six seconds when no recent measurements are available. Opening the image viewer immediately stops the relay read for that card and reuses any cloud transfer already in progress. As soon as the viewer gets a cloud link, it shows cloud loading status at the top if a thumbnail is visible, or in the loading placeholder otherwise. The status disappears when the original is ready. A failed preview offers “Open via cloud drive”. Document previews that read the file contents need the bucket to allow cross-origin reads from your CoDiscuss site. Once every byte has been sent, the app waits for confirmation without resending. If an automatic switch fails, the current transfer returns to its original route. If a switch fails or does not save enough time, automatic switching in that direction pauses for 90 seconds. Larger hosted downloads prefer a cloud link immediately. For eligible attachments, the “…” menu on the message card or in the file preview also offers “Download via cloud drive”. Opening and downloading use a 24-hour transfer copy. When a small attachment switches to cloud drive because the upload is slow, the computer retrieves it, saves it as a regular local attachment, and deletes the temporary cloud copy. Images (including GIFs), videos, and other files keep their usual attachment previews and do not expire under the cloud retention policy. On other devices, hosted accounts, or the online website, when an administrator has set up the cloud space (see [Management panel](admin.md)), files larger than the threshold (20 MiB by default, up to 2 GiB each) upload straight to the account's cloud space. Upload progress shows under the thumbnail; removing the thumbnail cancels the upload. They are temporary files, kept 7 days by default (an administrator can set 1–90 days): their cards say “Temporary file · size · Expires in N days” with a clock, “Expires today” in the warning colour under a day, and the card greys out with “Expired” afterwards. To keep one, choose “Keep in cloud drive” before it expires. Messages do not load their thumbnails or players; selecting the card downloads the file, and the “⋯” at its right offers “Preview” (images, audio, video and PDF), “Keep in cloud drive” and “Download”. A preview reads straight from the cloud space: video can be dragged to any point, and when the link expires during a long stop it renews itself and carries on from the same place; a PDF opens in a new tab. When the cloud space cannot be reached or the file was deleted, the card shows “Object storage is unavailable right now” or “Deleted”. Once the cloud space is full, new large uploads fail; delete old files under “Cloud space” on the Files page. Editing, taking back, or taking a queued message back into the composer leaves these files out; add them again. Share pages and exported backups do not include these files. Without the cloud space, files over the attachment limit cannot be added.
85
85
  - **Read cloud attachments as a member.** Before waking a local member, CoDiscuss caches the attachment on that computer and gives the member its path. Read-only members can read that copy, and other members reuse it. The cache holds up to 20 GiB and evicts the least recently used files that no active task needs. If the automatic download fails, or to retrieve an earlier attachment, use `codiscuss attachment download ROOM ID` to save it to the same cache. To keep working on it in a project, have a member copy it from the cache into the project, or download it and upload it to the project.
86
86
  - **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, the left and right arrow keys, or a sideways swipe on a phone step between them (the side buttons hide when idle and return when you move the mouse or tap the image). Audio and video play in the message. Documents and code open in the file preview. An attachment card has at most one button: images have none, and “Keep in cloud drive” and “Download” (save the image) are in the image viewer's bottom toolbar; file, audio and video cards have a “⋯” at their right (beside the file name for audio and video) offering “Keep in cloud drive” (with the cloud space set up) and “Download”. On the administrator's local page, the image viewer's bottom toolbar, attachment card “⋯” menus, and the preview window's “…” menu also offer these two actions. Files that open in the file preview (both project files and message attachments) offer “Download” on the top bar and, when cloud space is configured, “Keep in cloud drive” to its left (temporary files also show “Expires in N days”). Wherever both appear, “Keep in cloud drive” is on the left (on top in a menu) and “Download” on the right. “Keep in cloud drive” copies the attachment into a long-term cloud drive file of the account, leaving the original on the computer or the temporary file as it is; its progress shows in the Files page's transfer list, with one notice at the bottom right when it is done. For one this page has already kept, the viewer's button is greyed out and says “Kept in the cloud drive”.
87
87
  - **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. On a computer, tool buttons appear in its top-right corner when you point at it: view the “Source”, “Open larger preview” in the file preview, open it in a “New tab”, “Download” it as an `.html` file, or “Collapse” it (your choice is remembered). On a phone the corner always shows a “…” menu and the collapse button. A collapsed visualization shows as one “Interactive visualization” line; select “Expand” to bring it back. Members add these on their own when you ask for an illustrated answer, or when they explain a structure, process, or data. When a long answer is folded, its visualizations still appear, and one the fold cuts through shows only its top; select “Show full text” to see all of it. Read-only share pages and read-aloud 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.
@@ -91,7 +91,7 @@ When viewing a project image through the relay on another device, supported imag
91
91
 
92
92
  Enable “Image generation” or “Video generation” in the new-room panel or under “Room → Collaboration settings”. For images, choose “API image generation”, “Codex subscription image generation”, or “Enable both”. API images and video use the service settings on the connected computer. After entering an endpoint, key, model, and limits, select “Test connection” to check the configuration without generating media. Local administrators and owners on paired devices can generate media without importing a separate room credential when the page can manage the room.
93
93
 
94
- - On desktop (over 700 px), point at the mode capsule outside the left edge of the composer to expand it and select “Text”, “Image generation”, or “Video generation”. On narrow screens (700 px or less), tap the slim mode tab outside the left edge of the composer to switch modes from the pop-up menu (and use the same tab to return to “Text”). In a media mode, select “Media options” next to the paperclip to adjust model, size, quality, or format, enter a prompt, and select generate. The result appears as an attachment without waking the host or other members.
94
+ - On desktop (over 700 px), point at the mode capsule outside the left edge of the composer to expand it and select “Text”, “Image generation”, or “Video generation”. On narrow screens (700 px or less), tap the slim mode tab outside the left edge of the composer to expand the mode panel and switch modes (selecting a mode or tapping outside collapses it back; use the same tab to return to “Text”). In a media mode, select “Media options” next to the paperclip to adjust model, size, quality, or format, enter a prompt, and select generate. The result appears as an attachment without waking the host or other members.
95
95
  - On a tablet or touchscreen computer (over 700 px), tap the capsule outside the left edge of the composer to expand it, then tap a mode. Selecting an available mode or tapping outside collapses it. Tapping a dimmed mode tells you why it is unavailable.
96
96
  - To edit an image, add image attachments and choose the reference, mask, or markup in “Media options”. Video generation uses the first image attachment as its reference. In a room that only uses Codex subscription image generation, stay in “Text” mode and ask the host or an image specialist.
97
97
  - If something fails, the notice at the bottom right explains why and the draft stays in place. Refreshing the page or returning to the room resumes checking unfinished jobs. If only some images were saved or posting failed, you can post the retained attachments without generating again. Select “Discard media job” if you no longer want to post them.
@@ -79,7 +79,7 @@
79
79
  ### 4. 发送与查看附件
80
80
 
81
81
  - **添加附件**:在输入框粘贴、拖入文件,或点左下角回形针按钮选择文件(每条消息最多 10 个;管理员“本地网页”直接流式保存不受默认 50 MiB 单个上限限制,但仍计入 `.codiscuss` 的 10 GiB 本机数据上限,超大素材建议改传“项目文件”或在房间菜单“管理附件”清理旧附件;其他入口默认上限 50 MiB,可在管理面板调整)。添加后输入框上方出现缩略图,正文光标处插入 `[图片 #1]`、`[文件 #2]` 等房间内连续编号的占位标签;删掉缩略图或按退格删掉占位,两边同步移除。发出后,正文里首次写到 `[图片 #n]` 的图片会紧跟在所在段落或列表项下方以半宽两列排布显示(手机上单张占满整宽、多张两列并排,多图消息附带 `#n` 角标),附件列表不再重复列出;其他附件仍列在消息下方。 Windows 站点会为上传的 PNG、JPG 自动生成较小的预览,点击图片可读原图。 已上传但一直未发送的附件超过 24 小时后会自动清理;已发送或仍在排队消息里的附件会保留。
82
- - **大文件作为临时文件发送**:在本机部署的管理员“本地网页”(`127.0.0.1` 或 `localhost`)里发附件时,文件直接流式保存在这台电脑上,不经过云空间、不受默认 50 MiB 单个上限限制(计入 `.codiscuss` 10 GiB 本机数据上限,超大素材建议改传“项目文件”),视频也不会强制压缩(同机 AI 成员在本地站点收发附件同样流式直传、不经过云空间)。配置云空间后,可测进度的上传、整包下载和配对设备上的原图预览(含无缩略图的 GIF)会估算换路是否划算。连续两次估计至少节省 8 秒且节省一半时间才自动切换,每个文件最多一次。没有可用进度时只在长时间无字节后试一次。原生预览和按页加载的 PDF 不会被自动打断,等待较久时只提示可手动通过云盘打开或下载。点开看图器会立即中止该卡片的原图中转,已有云盘任务则直接复用。看图器一拿到云盘直链就显示云盘加速状态,已有缩略图时在顶部显示,原图就绪后收起。失败时可手动点“通过云盘打开”。需要读取文件内容的文档预览,要求存储桶允许来自共议站点的跨域读取。全部字节传完后只等确认,不重新上传。自动换路失败时,当前传输回到原路径。换路失败或没达到预估收益时,该方向暂停自动切换 90 秒。托管大附件下载优先用云盘直链。支持云盘下载的附件,也可在消息卡片或文件预览的“⋯”菜单选“通过云盘下载”。打开和下载使用 24 小时中转副本。小附件因上传慢而切到云盘时,电脑会把文件拉回,存成普通本地附件,再删除云端暂存。图片(含 GIF)、视频等沿用普通附件的预览方式,这类附件不会按云空间期限过期。在其他设备、托管账号或线上网站上,管理员配置了云空间(见[管理面板](admin.md))时,大于门槛(默认 20 MiB)的文件(单个最大 2 GiB)会直接上传到本账号的云空间,缩略图下方显示上传进度,删掉缩略图即取消上传。这类附件是临时文件,默认保留 7 天(管理员可设 1–90 天):卡片标“临时文件 · 大小 · N 天后过期”(时钟图标),不足 1 天显示“今天过期”并变成警示色,过期后卡片变灰并显示“已过期”。想长期保留,在到期前选“转存到云盘”。消息里不自动显示缩略图或播放器;点卡片下载;卡片右侧的“⋯”里有“预览”(图片、音视频、PDF)、“转存到云盘”和“下载”。预览直接从云空间读取,视频可拖动进度,放久了链接过期会自动续上、从原位置接着播放;PDF 在新标签页打开。云空间暂时连不上或文件已被删除时,卡片显示“对象存储暂不可用”或“已删除”。云空间用满后新的大文件会上传失败,请到文件页的“云空间”删除旧文件。编辑、撤回或取回排队消息时,这类附件不会放回输入框,需要重新添加。分享页和导出备份不带这类附件的原文件。没有配置云空间时,超过单个附件上限的文件不能添加。
82
+ - **大文件作为临时文件发送**:在本机部署的管理员“本地网页”(`127.0.0.1` 或 `localhost`)里发附件时,文件直接流式保存在这台电脑上,不经过云空间、不受默认 50 MiB 单个上限限制(计入 `.codiscuss` 10 GiB 本机数据上限,超大素材建议改传“项目文件”),视频也不会强制压缩(同机 AI 成员在本地站点收发附件同样流式直传、不经过云空间)。配置云空间后,可测进度的上传、整包下载和配对设备上的原图预览(含无缩略图的 GIF)会估算换路是否划算。系统先用近期实测速率预测,也会在传输开始约 1 秒时快判。预计至少省 3 秒且省一半时间才自动切换。走原路后若掉速,连续两次达到同一门槛,或连续 6–12 秒无新字节,仍可切换,每个文件最多一次。系统会定期试走原路以发现网速恢复。原生预览和按页加载的 PDF 不会被自动打断,只提示可手动通过云盘打开或下载,缺少样本时等 6 秒再提示。点开看图器会立即中止该卡片的原图中转,已有云盘任务则直接复用。看图器一拿到云盘直链就显示云盘加速状态,已有缩略图时在顶部显示,原图就绪后收起。失败时可手动点“通过云盘打开”。需要读取文件内容的文档预览,要求存储桶允许来自共议站点的跨域读取。全部字节传完后只等确认,不重新上传。自动换路失败时,当前传输回到原路径。换路失败或没达到预估收益时,该方向暂停自动切换 90 秒。托管大附件下载优先用云盘直链。支持云盘下载的附件,也可在消息卡片或文件预览的“⋯”菜单选“通过云盘下载”。打开和下载使用 24 小时中转副本。小附件因上传慢而切到云盘时,电脑会把文件拉回,存成普通本地附件,再删除云端暂存。图片(含 GIF)、视频等沿用普通附件的预览方式,这类附件不会按云空间期限过期。在其他设备、托管账号或线上网站上,管理员配置了云空间(见[管理面板](admin.md))时,大于门槛(默认 20 MiB)的文件(单个最大 2 GiB)会直接上传到本账号的云空间,缩略图下方显示上传进度,删掉缩略图即取消上传。这类附件是临时文件,默认保留 7 天(管理员可设 1–90 天):卡片标“临时文件 · 大小 · N 天后过期”(时钟图标),不足 1 天显示“今天过期”并变成警示色,过期后卡片变灰并显示“已过期”。想长期保留,在到期前选“转存到云盘”。消息里不自动显示缩略图或播放器;点卡片下载;卡片右侧的“⋯”里有“预览”(图片、音视频、PDF)、“转存到云盘”和“下载”。预览直接从云空间读取,视频可拖动进度,放久了链接过期会自动续上、从原位置接着播放;PDF 在新标签页打开。云空间暂时连不上或文件已被删除时,卡片显示“对象存储暂不可用”或“已删除”。云空间用满后新的大文件会上传失败,请到文件页的“云空间”删除旧文件。编辑、撤回或取回排队消息时,这类附件不会放回输入框,需要重新添加。分享页和导出备份不带这类附件的原文件。没有配置云空间时,超过单个附件上限的文件不能添加。
83
83
  - **成员读取云空间附件**:共议在唤醒本机成员前把附件放进账号的本机附件缓存,并给成员本机路径。只读成员也可读取,同一附件不用为每位成员重复下载。缓存上限 20 GiB,空间不足时优先清理最久没用且没有任务在用的文件。自动下载失败或查看历史附件时,可用 `codiscuss attachment download ROOM ID` 下载到同一缓存。要放进项目继续加工,由成员从缓存里复制进项目,或你下载后上传到项目。
84
84
  - **查看附件**:消息发出后点正文占位或附件卡片即可打开;图片支持全屏缩放、旋转与保存,房间里有多张图片时可用两侧按钮、键盘左右方向键或手机上左右滑动切换(两侧按钮无操作时自动隐藏,移动鼠标或轻点图片即重新出现),音视频直接在消息里播放,文档与代码在文件预览窗口打开。附件卡片上最多只有一个按钮:图片上没有按钮,“转存到云盘”和“下载”(保存图片)在图片查看器底部的工具栏里;文件和音视频卡片右侧(音视频在文件名右侧)有一个“⋯”,点开是“转存到云盘”(配置了云空间才有)和“下载”。在管理员“本地网页”上,图片查看器底部工具栏、附件卡片的“⋯”和预览窗口的“…”更多操作菜单还会提供这两项操作。能预览的文件(项目文件与消息附件)在预览窗口顶部提供“下载”,配置了云空间时其左侧同时提供“转存到云盘”(临时文件同时显示“N 天后过期”)。两者同时出现时,“转存到云盘”总在左边(菜单里在上面),“下载”在右边。“转存到云盘”把附件复制一份成本账号的云盘文件长期保留,电脑上的原件或原来的临时文件不变;进度显示在文件页的传输列表里,完成时右下角提示一次。本页已转存过的,查看器里的这个按钮置灰并提示“已转存到云盘”。
85
85
  - **交互式可视化**:成员可以在回答正文里放一段可以操作的网页(拖动滑块、点按钮看结果变化),它显示在正文中的原位置,跟随房间主题和深浅色,手机上同样直接显示。滚到它附近才开始运行。右上角的工具按钮在电脑上悬停时出现,可看“源码”、“放大”到文件预览窗口、在“新标签页”打开、“下载”为 `.html` 文件或“收起”(会记住选择);手机上右上角常显“…”菜单与收起按钮。收起后显示为一行“交互式可视化”,点“展开”恢复。成员在你要求“图文并茂”、或讲结构、流程、数据时会主动配图。长回答折叠时,可视化照常显示,被折叠线截到的只露出顶部,点“展开全文”看完整的。只读分享页和朗读只显示“交互式可视化”一行,结论以成员写在正文里的文字为准。`.html` 附件不在消息内显示,点文件卡片在预览窗口或新标签页打开。有的可视化是提问面板:你在里面排序、分配或调整后点它的提交按钮,结果会作为引用放到输入框上方,不会直接发出;你可以删改,点发送才算回答。同一面板再次提交会替换上一次的结果。
@@ -89,7 +89,7 @@
89
89
 
90
90
  在新建房间面板或“房间 → 协作设置”开启“生图”或“视频生成”。生图可选择“API 生图”、“Codex 订阅生图”或“两者都开”。API 生图和视频生成用的是连接电脑上的服务配置。填写地址、密钥、模型及限额后,可以点“测试连接”检查配置,不会生成媒体。 本机管理员和已配对设备上的房主只要有房间管理权限,就能直接生成,不必单独导入房间凭据。
91
91
 
92
- - 桌面(>700px)将鼠标移到输入框左外侧的模式胶囊上展开并选择“文字”、“生图”或“视频生成”;手机等窄屏(≤700px)点输入框左外侧的极窄模式侧翼,从弹出菜单切换(切回“文字”同样点该侧翼选择)。进入媒体模式后,可点底部回形针右侧的“媒体参数”调整模型、尺寸、画质、格式等选项,填写提示词后点右下角生成按钮提交。结果以附件出现在对话里,不会唤醒主持人或其他成员。
92
+ - 桌面(>700px)将鼠标移到输入框左外侧的模式胶囊上展开并选择“文字”、“生图”或“视频生成”;手机等窄屏(≤700px)点输入框左外侧的极窄模式侧翼,展开选择面板切换(切回“文字”同样点该侧翼选择,选完或点面板外自动收起)。进入媒体模式后,可点底部回形针右侧的“媒体参数”调整模型、尺寸、画质、格式等选项,填写提示词后点右下角生成按钮提交。结果以附件出现在对话里,不会唤醒主持人或其他成员。
93
93
  - 平板或触屏电脑(>700px)用手指点输入框左外侧胶囊,先展开,再点所需模式。点选可用模式或点胶囊外会收起。点置灰的模式会提示不可用原因。
94
94
  - 改图时先添加图片附件,再在“媒体参数”指定参考图、蒙版或标注。生成视频时使用第一张图片附件作为参考图。仅开启 Codex 订阅生图的房间,请在“文字”模式下让主持人或生图专家代画。
95
95
  - 失败会在右下角显示原因,原草稿保留。刷新页面或回到房间后,会继续查询未完成的任务。部分图片已保存或发消息失败时,可以发布保留的附件,不会重新生成。若不再需要,点“放弃媒体任务”清除待发布状态。
@@ -1378,5 +1378,33 @@
1378
1378
  "阶段耗时": "Time by phase",
1379
1379
  "执行步骤": "Run steps",
1380
1380
  "首响等待": "Time to first activity",
1381
- "阶段明细读取失败": "Could not load phase details"
1381
+ "阶段明细读取失败": "Could not load phase details",
1382
+ "媒体未能加载": "Could not load media",
1383
+ "正在载入视频…": "Loading video…",
1384
+ "正在渲染视频…": "Rendering video…",
1385
+ "正在解析像素…": "Resolving image…",
1386
+ "正在生成画面…": "Generating image…",
1387
+ "生成的视频": "Generated video",
1388
+ "生成的图片": "Generated image",
1389
+ "图生视频": "Image to video",
1390
+ "改图": "Image edit",
1391
+ "画质:{quality}": "Quality: {quality}",
1392
+ "{count} 张": "{count} images",
1393
+ "{seconds} 秒": "{seconds}s",
1394
+ "透明底": "Transparent",
1395
+ "不透明底": "Opaque",
1396
+ "复杂度:{level}": "Complexity: {level}",
1397
+ "保真度:{level}": "Fidelity: {level}",
1398
+ "{count} 帧": "{count} frames",
1399
+ "{ms} ms/帧": "{ms} ms/frame",
1400
+ "宽松审核": "Low moderation",
1401
+ "正在生成视频…": "Generating video…",
1402
+ "正在生成图片…": "Generating image…",
1403
+ "正在发布…": "Posting…",
1404
+ "部分完成": "Partially completed",
1405
+ "生成失败": "Generation failed",
1406
+ "该张未能保存": "Could not save this image",
1407
+ "生成参数": "Generation options",
1408
+ "输入参考": "Reference",
1409
+ "重试生成": "Retry generation"
1382
1410
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai_co_discuss",
3
- "version": "0.5.65",
3
+ "version": "0.5.66",
4
4
  "bin": {
5
5
  "codiscuss": "runner/codiscuss.mjs"
6
6
  },
@@ -8,7 +8,7 @@
8
8
  "dev": "npm run build && wrangler pages dev --ip 127.0.0.1 --port 8787",
9
9
  "db:local": "wrangler d1 execute DB --local --file backend/schema.sql",
10
10
  "db:remote": "wrangler d1 execute DB --remote --file backend/schema.sql",
11
- "check": "node --check backend/worker.mjs && node --check web/app.js && node --check scripts/sync_optional_skills.mjs && node --check runner/account_space.mjs && node --check runner/admin_account.mjs && node --check runner/admin_panel.mjs && node --check runner/admin_cli.mjs && node --check runner/os_users.mjs && node --check runner/tray.mjs && node --check runner/launcher.mjs && node --check runner/codiscuss.mjs && node --check runner/discussion_api.mjs && node --check runner/discussion_launch.mjs && node --check runner/discussion_local.mjs && node --check runner/discussion_runner.mjs && node --check runner/discussion_service.mjs && node --check runner/discussion_setup.mjs && node --check runner/discussion_sidecar.mjs && node --check runner/discussion_skills.mjs && node --check runner/discussion_tui.mjs && node --check runner/execution_progress.mjs && node --check runner/expert_prompts.mjs && node --check runner/files.mjs && node --check runner/free_runner.mjs && node --check runner/remote_launch.mjs && node --check runner/external_client.mjs && node --check runner/external_gateway.mjs && node --check runner/repo_read.mjs && node --check runner/remote_policy.mjs && node --check runner/device_auth.mjs && node --check runner/webauthn.mjs && node --check runner/scheduler.mjs && node --check runner/session_driver.mjs && node --check runner/share_card.mjs && node --check runner/timeline_metrics.mjs && node --check runner/workflows.mjs && node --check runner/workflow_flow.mjs && node --check runner/slash_names.mjs && node --check runner/weixin.mjs && node --check runner/adapters/antigravity_app.mjs && node --check runner/adapters/antigravity_cli.mjs && node --check runner/adapters/antigravity_sidecar.mjs && node --check runner/adapters/api.mjs && node --check runner/adapters/claude.mjs && node --check runner/adapters/cli.mjs && node --check runner/adapters/codex_app.mjs && node --check runner/adapters/codex_app_client.mjs && node --check runner/adapters/codex_cli.mjs && node --check runner/adapters/common.mjs && node --check runner/adapters/index.mjs && node --check runner/adapters/profiles.mjs",
11
+ "check": "node --check backend/worker.mjs && node --check web/app.js && node --check scripts/sync_optional_skills.mjs && node --check runner/account_space.mjs && node --check runner/admin_account.mjs && node --check runner/admin_panel.mjs && node --check runner/admin_cli.mjs && node --check runner/os_users.mjs && node --check runner/tray.mjs && node --check runner/launcher.mjs && node --check runner/codiscuss.mjs && node --check runner/discussion_api.mjs && node --check runner/discussion_launch.mjs && node --check runner/discussion_local.mjs && node --check runner/discussion_runner.mjs && node --check runner/discussion_service.mjs && node --check runner/discussion_setup.mjs && node --check runner/discussion_sidecar.mjs && node --check runner/discussion_skills.mjs && node --check runner/discussion_tui.mjs && node --check runner/execution_progress.mjs && node --check runner/expert_prompts.mjs && node --check runner/files.mjs && node --check runner/free_runner.mjs && node --check runner/workspace_worker.mjs && node --check runner/remote_launch.mjs && node --check runner/external_client.mjs && node --check runner/external_gateway.mjs && node --check runner/repo_read.mjs && node --check runner/remote_policy.mjs && node --check runner/device_auth.mjs && node --check runner/webauthn.mjs && node --check runner/scheduler.mjs && node --check runner/session_driver.mjs && node --check runner/share_card.mjs && node --check runner/timeline_metrics.mjs && node --check runner/workflows.mjs && node --check runner/workflow_flow.mjs && node --check runner/slash_names.mjs && node --check runner/weixin.mjs && node --check runner/adapters/antigravity_app.mjs && node --check runner/adapters/antigravity_cli.mjs && node --check runner/adapters/antigravity_sidecar.mjs && node --check runner/adapters/api.mjs && node --check runner/adapters/claude.mjs && node --check runner/adapters/cli.mjs && node --check runner/adapters/codex_app.mjs && node --check runner/adapters/codex_app_client.mjs && node --check runner/adapters/codex_cli.mjs && node --check runner/adapters/codex_rollout.mjs && node --check runner/adapters/log_worker.mjs && node --check runner/adapters/common.mjs && node --check runner/adapters/index.mjs && node --check runner/adapters/profiles.mjs",
12
12
  "runner": "node runner/discussion_runner.mjs",
13
13
  "service": "node runner/discussion_service.mjs",
14
14
  "build:ui": "node scripts/build_share_core.mjs && vite build --config frontend/vite.config.mjs --mode i18n && vite build --config frontend/vite.config.mjs --mode markdown &&vite build --config frontend/vite.config.mjs --mode backup && vite build --config frontend/vite.config.mjs --mode office && vite build --config frontend/vite.config.mjs --mode video && vite build --config frontend/vite.config.mjs --mode admin && vite build --config frontend/vite.config.mjs --mode guest && vite build --config frontend/vite.config.mjs",
@@ -11,7 +11,7 @@ import { homedir } from 'node:os';
11
11
  import { dirname, join, resolve } from 'node:path';
12
12
  import { setTimeout as sleep } from 'node:timers/promises';
13
13
  import { CodexAppClient } from './codex_app_client.mjs';
14
- import { branch, codex_skills, codex_usage, desktop_thread, list_sessions, preview_session, remove_session, session_exists, session_path, session_settings } from './codex_cli.mjs';
14
+ import { branch, codex_observe, codex_skills, codex_usage, desktop_thread, list_sessions, preview_session, remove_session, resolve_desktop_thread, session_exists, session_path, session_settings } from './codex_cli.mjs';
15
15
  import { BackgroundTasks, bind_access, CALL_TIMEOUT_MS, not_sent, read_json, run_program, same_path, shell_written_paths } from './common.mjs';
16
16
 
17
17
  // The desktop has no stop or interrupt tool (its tool list, checked 2026-10-30).
@@ -536,7 +536,7 @@ export const codex = {
536
536
  },
537
537
  deliver,
538
538
  chat: (config, binding, task) => codex_chat(config, binding, task),
539
- session: { usage: codex_usage, path: session_path, exists: session_exists, owns: desktop_thread, branch, settings: session_settings,
539
+ session: { usage: codex_usage, observe: codex_observe, resolve_owns: resolve_desktop_thread, path: session_path, exists: session_exists, owns: desktop_thread, branch, settings: session_settings,
540
540
  list: list_sessions, preview: preview_session, remove: remove_session },
541
541
  models: null,
542
542
  skills: codex_skills,
@@ -5,16 +5,17 @@
5
5
  */
6
6
  import { spawn } from 'node:child_process';
7
7
  import { randomUUID } from 'node:crypto';
8
- import { closeSync, existsSync, fstatSync, openSync, readFileSync, readSync, readdirSync, statSync } from 'node:fs';
9
- import { StringDecoder } from 'node:string_decoder';
8
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
10
9
  import { homedir } from 'node:os';
11
10
  import { join, resolve } from 'node:path';
12
11
  import { createInterface } from 'node:readline';
13
12
  import { fileURLToPath } from 'node:url';
14
13
  import { cli_delivery } from './cli.mjs';
15
14
  import { daemon_chat, daemon_link } from './codex_daemon.mjs';
16
- import { BackgroundTasks, background_state, CALL_TIMEOUT_MS, edge_entries, launch_directory, log_entries, marked, model_entry, json_line, newest_record, not_sent,
17
- page_sessions, preview_messages, project_directory, prompt_text, prompt_title, query_catalog, remove_session_files, same_path, shell_written_paths, tree_killable, typed_prompt } from './common.mjs';
15
+ import { BackgroundTasks, background_state, CALL_TIMEOUT_MS, launch_directory, log_entries, model_entry, json_line, not_sent,
16
+ page_sessions, project_directory, prompt_title, query_catalog, remove_session_files, same_path, shell_written_paths, tree_killable, trim_preview } from './common.mjs';
17
+ import { codex_limits, describe_rollout, preview_rollout, rollout_desktop, scan_observation } from './codex_rollout.mjs';
18
+ import { log_scan } from './log_worker.mjs';
18
19
  import { adapter_capabilities } from './profiles.mjs';
19
20
 
20
21
  /** Codex exec may linger after its final event; the finished turn is already saved, so stop it to free the session. */
@@ -373,16 +374,6 @@ export function remove_session(session_id, { env = process.env, home = homedir()
373
374
  return { removed, kept: ['shared_stores'] };
374
375
  }
375
376
 
376
- /** One rollout entry as a conversation message; the instructions and context Codex puts in as user messages are left out. */
377
- function thread_message(entry) {
378
- const payload = entry.payload || {};
379
- if (entry.type !== 'response_item' || payload.type !== 'message' || !['user', 'assistant'].includes(payload.role)) return null;
380
- const parts = Array.isArray(payload.content) ? payload.content : [];
381
- const raw = parts.filter(part => ['input_text', 'output_text', 'text'].includes(part?.type)).map(part => part.text || '').join('\n').trim();
382
- const text = payload.role === 'assistant' ? raw : raw.startsWith('# AGENTS.md instructions') ? '' : typed_prompt(raw);
383
- return text ? { role: payload.role, text, at: entry.timestamp || '' } : null;
384
- }
385
-
386
377
  /** The names Codex gave its threads, from its index (`session_index.jsonl`; a later line replaces an earlier one). */
387
378
  function thread_names(root) {
388
379
  const names = new Map();
@@ -394,11 +385,10 @@ function thread_names(root) {
394
385
 
395
386
  /** What a browsing window shows of one thread; null for a thread Codex started itself (a subagent, a review). */
396
387
  function describe_thread({ file, updated_at, size }, names) {
397
- const { head } = edge_entries(file);
398
- const meta = head.find(entry => entry.type === 'session_meta')?.payload;
399
- if (!meta?.id || (meta.thread_source && meta.thread_source !== 'user')) return null;
400
- const title = names.get(meta.id) || prompt_title(head.map(thread_message).find(message => message?.role === 'user')?.text);
401
- return { id: meta.id, title: String(title || ''), cwd: String(meta.cwd || ''), updated_at, size };
388
+ let meta;
389
+ try { meta = describe_rollout(file, names); } catch { return null; }
390
+ if (!meta) return null;
391
+ return { id: meta.id, title: names.has(meta.id) ? String(meta.title || '') : prompt_title(meta.title), cwd: String(meta.cwd || ''), updated_at, size };
402
392
  }
403
393
 
404
394
  /**
@@ -428,20 +418,7 @@ export function preview_session(session_id, { env = process.env, home = homedir(
428
418
  const info = statSync(file);
429
419
  const described = describe_thread({ file, updated_at: info.mtime.toISOString(), size: info.size }, thread_names(env.CODEX_HOME || join(home, '.codex')));
430
420
  if (!described) throw new Error(`Codex 会话 ${session_id} 不是可续接的对话`);
431
- return { ...described, ...preview_messages(file, thread_message) };
432
- }
433
-
434
- /** Codex turns in order, and the index of the first turn whose user prompt carries a marker (-1 when none does). */
435
- function codex_turns(file, markers) {
436
- const turns = [];
437
- let cut = -1;
438
- for (const entry of log_entries(file)) {
439
- const payload = entry.payload || {};
440
- if (entry.type === 'event_msg' && payload.type === 'task_started' && payload.turn_id) turns.push(payload.turn_id);
441
- else if (cut < 0 && turns.length && entry.type === 'response_item' && payload.type === 'message' && payload.role === 'user'
442
- && marked(prompt_text(payload.content), markers)) cut = turns.length - 1;
443
- }
444
- return { turns, cut };
421
+ return { ...described, ...trim_preview(preview_rollout(file)) };
445
422
  }
446
423
 
447
424
  /** Ask Codex's app server to fork a thread, through `last_turn` when given; returns the new thread's ID. */
@@ -482,18 +459,23 @@ function codex_fork(profile, thread_id, last_turn, spawn_process) {
482
459
  export async function branch(profile, session_id, markers, { always, env, home, spawn_process = spawn }) {
483
460
  const file = session_path(session_id, env, home);
484
461
  if (!file) throw new Error(`本机找不到 Codex 会话 ${session_id}`);
485
- const { turns, cut } = codex_turns(file, markers);
462
+ const { turns, cut } = await log_scan('turns', file, markers);
486
463
  if (cut < 0 && !always) return null;
487
464
  if (cut === 0) return { session_id: '' };
488
465
  return { session_id: await codex_fork(profile, session_id, cut > 0 ? turns[cut - 1] : '', spawn_process) };
489
466
  }
490
467
 
491
- /** Whether a stored thread was started in the Codex desktop, which resumes it through the App rather than the CLI. */
468
+ /** Whether the first rollout record identifies a desktop thread. */
492
469
  export function desktop_thread(session_id, options = {}) {
470
+ const file = session_path(session_id, options.env, options.home);
471
+ return Boolean(file && rollout_desktop(file));
472
+ }
473
+
474
+ /** Use the worker when the metadata does not fit in one read. */
475
+ export async function resolve_desktop_thread(session_id, options = {}) {
493
476
  const file = session_path(session_id, options.env, options.home);
494
477
  if (!file) return false;
495
- for (const line of rollout_lines(file)) return /"originator":"Codex Desktop"/.test(line);
496
- return false;
478
+ return rollout_desktop(file, true) ?? await log_scan('desktop', file);
497
479
  }
498
480
 
499
481
  /** Whether Codex stored a thread by that ID on this machine. */
@@ -501,17 +483,16 @@ export function session_exists(session_id, { env = process.env, home = homedir()
501
483
  return Boolean(session_id && session_path(session_id, env, home));
502
484
  }
503
485
 
504
- /** The model and effort a thread last ran with, from its rollout; no turn is started. Shared by the App adapter. */
505
- export function session_settings(session_id, { env = process.env, home = homedir() } = {}) {
486
+ /** The model and effort a thread last ran with, shared by the App adapter. */
487
+ export function session_settings(session_id, { env, home } = {}) {
488
+ const file = session_path(session_id, env, home);
489
+ return file ? scan_observation(file).settings : null;
490
+ }
491
+
492
+ /** Observe one rollout snapshot off the service thread. */
493
+ export async function codex_observe(session_id, { env, home, include_usage, log_path } = {}) {
506
494
  const file = session_path(session_id, env, home);
507
- if (!file) return null;
508
- const settings = newest_record(file, '"turn_context"', record => record.type === 'turn_context' && typeof record.payload?.model === 'string'
509
- ? { model: record.payload.model, effort: String(record.payload.effort || record.payload.collaboration_mode?.settings?.reasoning_effort || ''),
510
- ...(typeof record.payload.service_tier === 'string' ? { service_tier: record.payload.service_tier } : {}) } : null);
511
- if (!settings || settings.service_tier !== undefined) return settings;
512
- const last = newest_record(file, '"thread_settings_applied"', record => record.type === 'event_msg' &&
513
- record.payload?.type === 'thread_settings_applied' ? record.payload.thread_settings || {} : null);
514
- return typeof last?.service_tier === 'string' ? { ...settings, service_tier: last.service_tier, service_tier_source: 'thread' } : settings;
495
+ return file ? log_scan('observe', file, { session_id, include_usage, log_path }) : { settings: null, usage: null };
515
496
  }
516
497
 
517
498
  /** Read the string keys of a TOML file by table; Codex settings need nothing richer. */
@@ -602,130 +583,18 @@ async function chat(config, binding, task, spawn_process, user_home) {
602
583
  return daemon_chat(link, binding.session_id, task);
603
584
  }
604
585
 
605
- /** Recover only the recorded root turn in its thread; other turns and incomplete evidence cannot supply an answer. */
606
- function recover_turn(record) {
586
+ /** Recover only the recorded root turn in its thread. */
587
+ async function recover_turn(record) {
607
588
  const unknown = { status: 'unknown', exact: false };
608
589
  if (record?.kind !== 'codex_turn' || !record.thread_id || !record.turn_id) return unknown;
609
590
  const file = record.rollout_path || session_path(record.thread_id);
610
- if (!file) return unknown;
611
- const entries = readFileSync(file, 'utf8').trim().split(/\r?\n/).map(line => JSON.parse(line));
612
- const meta = entries.find(entry => entry.type === 'session_meta')?.payload;
613
- if (meta?.id !== record.thread_id || typeof meta.source === 'object') return unknown;
614
- const turns = entries.filter(entry => entry.type === 'event_msg' && entry.payload?.turn_id === record.turn_id).map(entry => entry.payload);
615
- const starts = turns.filter(event => event.type === 'task_started');
616
- const ends = turns.filter(event => ['task_complete', 'turn_aborted'].includes(event.type));
617
- if (starts.length !== 1 || ends.length !== 1) return unknown;
618
- if ([starts[0], ends[0]].some(event => event.root_turn_id !== record.turn_id || event.parent_turn_id)) return unknown;
619
- if (turns.indexOf(ends[0]) < turns.indexOf(starts[0])) return unknown;
620
- if (ends[0].type === 'turn_aborted') return { status: 'interrupted', exact: true };
621
- if (ends[0].error != null) {
622
- const error = ends[0].error;
623
- return typeof error === 'object' && !Array.isArray(error)
624
- && (typeof error.message === 'string' || typeof error.codex_error_info === 'string' || typeof error.codexErrorInfo === 'string')
625
- ? { status: 'failed', exact: true } : unknown;
626
- }
627
- if (ends[0].last_agent_message != null && typeof ends[0].last_agent_message !== 'string') return unknown;
628
- return { status: 'completed', exact: true, text: ends[0].last_agent_message || '' };
629
- }
630
-
631
- function codex_limits(limits, reset_credits) {
632
- const windows = [];
633
- for (const item of [limits?.primary, limits?.secondary]) {
634
- const percent = item?.used_percent ?? item?.usedPercent;
635
- if (!Number.isFinite(percent)) continue;
636
- const minutes = item.window_minutes ?? item.windowDurationMins;
637
- const kind = minutes === 300 ? 'five_hour' : minutes === 10080 ? 'seven_day' : 'other';
638
- windows.push({ kind, minutes, used: percent / 100, resets_at: item.resets_at ?? item.resetsAt });
639
- }
640
- return windows.length ? { windows, plan: limits.planType ?? limits.plan_type,
641
- reset_credits: reset_credits && { available: reset_credits.availableCount } } : null;
642
- }
643
-
644
- const USAGE_TAIL_BYTES = 256 * 1024;
645
- const ROLLOUT_CHUNK_BYTES = 64 * 1024;
646
-
647
- /** Read a snapshot of a log by chunks, skipping an incomplete first line when starting inside the file. */
648
- function* rollout_lines(file, start = 0) {
649
- const fd = openSync(file, 'r');
650
- try {
651
- const size = fstatSync(fd).size;
652
- const buffer = Buffer.allocUnsafe(ROLLOUT_CHUNK_BYTES);
653
- const decoder = new StringDecoder('utf8');
654
- let partial = '', skip = start > 0;
655
- for (let pos = start; pos < size;) {
656
- const length = readSync(fd, buffer, 0, Math.min(buffer.length, size - pos), pos);
657
- if (!length) break;
658
- pos += length;
659
- const lines = (partial + decoder.write(buffer.subarray(0, length))).split('\n');
660
- partial = lines.pop();
661
- for (const line of lines) {
662
- if (skip) skip = false;
663
- else yield line;
664
- }
665
- if (skip) partial = '';
666
- }
667
- if (!skip && partial) yield partial + decoder.end();
668
- } finally { closeSync(fd); }
669
- }
670
-
671
- /** Locate the turn binding in the execution log without parsing tool output. */
672
- function usage_turn_id(log_path, id) {
673
- for (const line of rollout_lines(log_path)) {
674
- if (!line.includes('codiscuss.turn') && !line.includes('codiscuss.entry')) continue;
675
- const entry = json_line(line);
676
- if (['codiscuss.turn', 'codiscuss.entry'].includes(entry?.type) && entry.thread_id === id && entry.turn_id) return entry.turn_id;
677
- }
678
- return null;
679
- }
680
-
681
- /** Difference between the cumulative counters immediately before and at the end of the identified turn. */
682
- function codex_turn_usage(file, turn_id, start) {
683
- let latest = null, before = null, end = null, first = null, first_call = null, active = false;
684
- for (const line of rollout_lines(file, start)) {
685
- if (!line.includes('event_msg') || !/task_started|token_count|task_complete|turn_aborted/.test(line)) continue;
686
- const entry = json_line(line);
687
- if (entry?.type !== 'event_msg') continue;
688
- const event = entry.payload;
689
- if (event?.type === 'task_started') {
690
- if (active) break;
691
- active = event.turn_id === turn_id;
692
- if (active) before = latest;
693
- } else if (event?.type === 'token_count' && event.info?.total_token_usage) {
694
- latest = event.info.total_token_usage;
695
- if (active) {
696
- if (!first) { first = latest; first_call = event.info.last_token_usage; }
697
- end = latest;
698
- }
699
- } else if (active && ['task_complete', 'turn_aborted'].includes(event?.type)) break;
700
- }
701
- // A clipped tail without the prior counter cannot distinguish an inherited counter from a missing record.
702
- if (!end || (!before && (start || !first_call))) return null;
703
- // A fork can inherit counters without retaining the preceding token_count.
704
- const delta = key => before ? (end[key] || 0) - (before[key] || 0)
705
- : (end[key] || 0) - (first[key] || 0) + (first_call[key] || 0);
706
- const cache_read = delta('cached_input_tokens');
707
- const input = delta('input_tokens') - cache_read;
708
- const output = delta('output_tokens');
709
- return Math.min(input, cache_read, output) >= 0 ? { input, cache_read, cache_write: 0, output } : null;
710
- }
711
-
712
- /** Prefer the recent tail. Older turns or baselines outside it fall back to a chunked scan. */
713
- function codex_turn(file, id, log_path) {
714
- if (!log_path || !existsSync(log_path)) return null;
715
- const turn_id = usage_turn_id(log_path, id);
716
- if (!turn_id) return null;
717
- const start = Math.max(0, statSync(file).size - USAGE_TAIL_BYTES);
718
- return (start && codex_turn_usage(file, turn_id, start)) || codex_turn_usage(file, turn_id, 0);
591
+ return file ? log_scan('recover', file, { thread_id: record.thread_id, turn_id: record.turn_id }) : unknown;
719
592
  }
720
593
 
721
594
  /** Read the last model call from a rollout shared by the CLI and desktop app. */
722
- export function codex_usage(id, { env, home, log_path } = {}) {
723
- const file = session_path(id, env, home);
724
- const event = file && newest_record(file, 'token_count', entry =>
725
- entry.type === 'event_msg' && entry.payload?.type === 'token_count' && entry.payload);
726
- if (!event) return null;
727
- return { context: { used: event.info?.last_token_usage?.input_tokens, window: event.info?.model_context_window },
728
- account: codex_limits(event.rate_limits), turn: codex_turn(file, id, log_path) };
595
+ export function codex_usage(session_id, { env, home, log_path } = {}) {
596
+ const file = session_path(session_id, env, home);
597
+ return file ? scan_observation(file, { session_id, log_path, include_usage: true, include_settings: false }).usage : null;
729
598
  }
730
599
 
731
600
  /** Ask the app-server for this account's current rate limits without starting a thread. */
@@ -756,7 +625,8 @@ export const codex_cli = {
756
625
  chat,
757
626
  invocation, lifecycle, exit_error, events,
758
627
  on_stderr: remember_writer_conflict,
759
- session: { usage: codex_usage, path: session_path, exists: session_exists, owns: (id, options) => session_exists(id, options) && !desktop_thread(id, options),
628
+ session: { usage: codex_usage, observe: codex_observe, path: session_path, exists: session_exists, owns: (id, options) => session_exists(id, options) && !desktop_thread(id, options),
629
+ resolve_owns: () => false, // For async adoption, let the desktop adapter check first; CLI is the fallback.
760
630
  branch, settings: session_settings, list: list_sessions, preview: preview_session, remove: remove_session, history: codex_history },
761
631
  models: { list: models, defaults },
762
632
  skills: codex_skills,