ai_co_discuss 0.5.35 → 0.5.37

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
@@ -52,6 +52,7 @@ from .room_trace import message_trace
52
52
  from .free_room import review_capability, review_roster, checked_review_plan, save_review_plan, check_review_retry
53
53
  from .free_room import review_ready, advance_review, late_answer, execution_changes, execution_changes_batch, execution_diffs
54
54
  from .free_room import checked_sequence, continue_sequence, sequence_view
55
+ from .windows_thumbnail import encode_preview
55
56
  from . import questions
56
57
  from .visual_fences import fold_message_visuals
57
58
  from .identity import MAX_ROOM_AGENTS, PARTICIPANTS, default_label_text, is_ai, is_participant
@@ -2485,7 +2486,7 @@ def thumbnail_path(database, attachment):
2485
2486
  def store_attachment_thumbnail(connection, database, room_id, identifier, token, data):
2486
2487
  """Keep the smaller copy of an image attachment a room participant's page made; the first one stored stays.
2487
2488
 
2488
- The site cannot decode images, so it checks what it can read from the headers: a WebP or JPEG no larger than
2489
+ Validate a client-supplied preview using its headers: a WebP or JPEG no larger than
2489
2490
  MAX_THUMBNAIL_SIDE pixels, smaller than the original, with the original's shape.
2490
2491
 
2491
2492
  Returns:
@@ -2514,6 +2515,45 @@ def store_attachment_thumbnail(connection, database, room_id, identifier, token,
2514
2515
  return {"attachment": get_attachment(connection, room_id, identifier), "duplicate": False}
2515
2516
 
2516
2517
 
2518
+ def generate_attachment_thumbnail(connection, database, attachment):
2519
+ """Keep a smaller PNG attachment preview, if the local codec and original are available."""
2520
+ if (os.name != "nt" or attachment["content_type"] != "image/png"
2521
+ or attachment.get("thumbnail_type")):
2522
+ return False
2523
+ path = attachment_path(database, attachment)
2524
+ try:
2525
+ with path.open("rb") as source:
2526
+ width, height = image_size(source)
2527
+ data = encode_preview(path, width, height)
2528
+ if data and data.startswith(b"\x89PNG") and len(data) > MAX_THUMBNAIL_BYTES:
2529
+ data = encode_preview(path, width, height, max_width=360)
2530
+ if not data or len(data) > MAX_THUMBNAIL_BYTES or len(data) * 2 >= attachment["size"]:
2531
+ return False
2532
+ with connection:
2533
+ begin_write(connection)
2534
+ updated = connection.execute("UPDATE attachments SET thumbnail_type=? "
2535
+ "WHERE id=? AND thumbnail_type IS NULL", (attachment_content_type(data), attachment["id"]))
2536
+ if not updated.rowcount:
2537
+ return False
2538
+ thumbnail_path(database, attachment).write_bytes(data)
2539
+ return True
2540
+ except (OSError, ValueError, sqlite3.Error):
2541
+ logging.debug("Preview unavailable for %s", attachment["id"], exc_info=True)
2542
+ return False
2543
+
2544
+
2545
+ def backfill_thumbnails(database, room_id):
2546
+ """Generate missing previews in one room, one file at a time outside the write lock."""
2547
+ with closing(connect_db(database)) as connection:
2548
+ require_room(connection, room_id)
2549
+ rows = connection.execute("SELECT id,content_type,size,thumbnail_type FROM attachments "
2550
+ "WHERE room_id=? AND content_type='image/png' AND thumbnail_type IS NULL "
2551
+ "AND message_id IS NOT NULL",
2552
+ (room_id,)).fetchall()
2553
+ generated = sum(generate_attachment_thumbnail(connection, database, dict(row)) for row in rows)
2554
+ logging.info("Generated %d of %d missing PNG previews", generated, len(rows))
2555
+
2556
+
2517
2557
  def store_attachment(connection, database, room_id, metadata, data):
2518
2558
  """Persist one immutable upload; exact retries return the original file."""
2519
2559
  begin_write(connection)
@@ -2542,6 +2582,7 @@ def store_attachment(connection, database, room_id, metadata, data):
2542
2582
  except Exception:
2543
2583
  path.unlink(missing_ok=True)
2544
2584
  raise
2585
+ generate_attachment_thumbnail(connection, database, record)
2545
2586
  return {"attachment": get_attachment(connection, room_id, record["id"]), "duplicate": False}
2546
2587
 
2547
2588
 
@@ -5151,8 +5192,12 @@ def main():
5151
5192
  parser.add_argument("--no-demo", action="store_true", help="Do not seed sample data in a new database")
5152
5193
  parser.add_argument("--local-launch", action="store_true", help="Enable local AI launch and configuration (127.0.0.1 only)")
5153
5194
  parser.add_argument("--reset-admin", action="store_true", help="Delete the administrator account and sessions, then exit")
5195
+ parser.add_argument("--backfill-thumbnails", metavar="ROOM", help="Generate missing PNG previews / 补齐房间 PNG 预览图")
5154
5196
  args = parser.parse_args()
5155
5197
  logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
5198
+ if args.backfill_thumbnails:
5199
+ backfill_thumbnails(args.database, args.backfill_thumbnails)
5200
+ return
5156
5201
  init_database(args.database, seed=not args.no_demo)
5157
5202
  retry_destruction(args.database)
5158
5203
  if args.reset_admin:
@@ -0,0 +1,167 @@
1
+ """Generate PNG or JPEG previews with the Windows system GDI+ codec."""
2
+ import ctypes
3
+ import os
4
+ import subprocess
5
+ from contextlib import ExitStack
6
+ from functools import lru_cache
7
+ from pathlib import Path
8
+ from tempfile import TemporaryDirectory
9
+ from uuid import UUID
10
+
11
+ from ctypes import byref, c_int, c_uint, c_void_p, c_size_t, Structure
12
+
13
+
14
+ class StartupInput(Structure):
15
+ _fields_ = [("version", c_uint), ("callback", c_void_p), ("no_thread", c_int), ("no_codec", c_int)]
16
+
17
+
18
+ class BitmapData(Structure):
19
+ _fields_ = [("width", c_uint), ("height", c_uint), ("stride", c_int), ("format", c_int),
20
+ ("pixels", c_void_p), ("reserved", c_size_t)]
21
+
22
+
23
+ ARGB32 = 0x26200A
24
+ PNG_ENCODER = UUID("557cf406-1a04-11d3-9a73-0000f81ef32e").bytes_le
25
+ JPEG_ENCODER = UUID("557cf401-1a04-11d3-9a73-0000f81ef32e").bytes_le
26
+ MAX_SOURCE_PIXELS = 24_000_000
27
+
28
+
29
+ def checked(status):
30
+ """Raise when the native image operation fails."""
31
+ if status:
32
+ raise ValueError(f"GDI+ status {status}")
33
+
34
+
35
+ @lru_cache(maxsize=1)
36
+ def graphics_library():
37
+ """Initialize the system codec for the process lifetime."""
38
+ library = ctypes.WinDLL("gdiplus", winmode=0x800)
39
+ token = c_size_t()
40
+ checked(library.GdiplusStartup(byref(token), byref(StartupInput(1)), None))
41
+ return library
42
+
43
+
44
+ def encode_preview(path, width, height, max_width=720, project=False):
45
+ """Resize a bounded image, preserving transparency."""
46
+ if not width or not height or width * height > MAX_SOURCE_PIXELS:
47
+ return None
48
+ library = graphics_library()
49
+ max_height = max_width if project else 1600
50
+ with ExitStack() as cleanup:
51
+ source, bitmap, graphics = c_void_p(), c_void_p(), c_void_p()
52
+ checked(library.GdipLoadImageFromFile(str(path), byref(source)))
53
+ cleanup.callback(library.GdipDisposeImage, source)
54
+ source_width, source_height = c_uint(), c_uint()
55
+ checked(library.GdipGetImageWidth(source, byref(source_width)))
56
+ checked(library.GdipGetImageHeight(source, byref(source_height)))
57
+ if source_width.value * source_height.value > MAX_SOURCE_PIXELS:
58
+ return None
59
+ # JPEG header dimensions may already include EXIF rotation. Draw in native pixel space first.
60
+ scale = min(1, max_width / source_width.value, max_height / source_height.value)
61
+ width = max(1, round(source_width.value * scale))
62
+ height = max(1, round(source_height.value * scale))
63
+ checked(library.GdipCreateBitmapFromScan0(width, height, 0, ARGB32, None, byref(bitmap)))
64
+ cleanup.callback(library.GdipDisposeImage, bitmap)
65
+ checked(library.GdipGetImageGraphicsContext(bitmap, byref(graphics)))
66
+ cleanup.callback(library.GdipDeleteGraphics, graphics)
67
+ checked(library.GdipSetInterpolationMode(graphics, 7))
68
+ # TileFlipXY extends the edge pixels during bicubic filtering.
69
+ attributes = c_void_p()
70
+ checked(library.GdipCreateImageAttributes(byref(attributes)))
71
+ cleanup.callback(library.GdipDisposeImageAttributes, attributes)
72
+ checked(library.GdipSetImageAttributesWrapMode(attributes, 3, 0, 0))
73
+ checked(library.GdipDrawImageRectRectI(graphics, source, 0, 0, width, height, 0, 0,
74
+ source_width, source_height, 2, attributes, None, None))
75
+ encoder = preview_encoder(library, bitmap, width, height)
76
+ if project:
77
+ apply_image_orientation(library, source, bitmap)
78
+ with TemporaryDirectory() as directory:
79
+ output = Path(directory) / "preview"
80
+ checked(library.GdipSaveImageToFile(bitmap, str(output), encoder, None))
81
+ return output.read_bytes()
82
+
83
+
84
+ def apply_image_orientation(library, source, bitmap):
85
+ """Apply the source EXIF orientation to the rendered bitmap before exporting without metadata."""
86
+ tag = 0x112
87
+ size = c_uint()
88
+ if library.GdipGetPropertyItemSize(source, tag, byref(size)) or not size.value:
89
+ return
90
+ class PropertyItem(Structure):
91
+ _fields_ = [("tag", c_uint), ("length", c_uint), ("type", ctypes.c_ushort), ("value", c_void_p)]
92
+ buffer = ctypes.create_string_buffer(size.value)
93
+ if library.GdipGetPropertyItem(source, tag, size, buffer):
94
+ return
95
+ item = PropertyItem.from_buffer(buffer)
96
+ if item.type == 3 and item.length == 2 and item.value:
97
+ orientation = ctypes.c_ushort.from_address(item.value).value
98
+ rotation = {2: 4, 3: 2, 4: 6, 5: 5, 6: 1, 7: 7, 8: 3}.get(orientation)
99
+ if rotation is not None:
100
+ checked(library.GdipImageRotateFlip(bitmap, rotation))
101
+
102
+
103
+ def preview_encoder(library, bitmap, width, height):
104
+ """Keep transparency in PNG, otherwise use the system JPEG encoder."""
105
+ pixels = BitmapData()
106
+ checked(library.GdipBitmapLockBits(bitmap, None, 1, ARGB32, byref(pixels)))
107
+ try:
108
+ if pixels.stride == width * 4:
109
+ alpha = ctypes.string_at(pixels.pixels, pixels.stride * height)[3::4]
110
+ if alpha.count(255) == len(alpha):
111
+ return JPEG_ENCODER
112
+ return PNG_ENCODER
113
+ finally:
114
+ library.GdipBitmapUnlockBits(bitmap, byref(pixels))
115
+
116
+ def decode_system_webp(path, output):
117
+ """Use the Windows Imaging Component WebP decoder if registered, keeping transparency."""
118
+ command = r"""
119
+ $ErrorActionPreference = 'Stop'
120
+ Add-Type -AssemblyName PresentationCore
121
+ $decoder = [Windows.Media.Imaging.BitmapDecoder]::Create(
122
+ [Uri]::new($env:CODISCUSS_WEBP_INPUT), 'PreservePixelFormat', 'OnLoad')
123
+ $frame = $decoder.Frames[0]
124
+ $encoder = [Windows.Media.Imaging.PngBitmapEncoder]::new()
125
+ $encoder.Frames.Add($frame)
126
+ $stream = [IO.File]::Create($env:CODISCUSS_WEBP_OUTPUT)
127
+ try { $encoder.Save($stream) } finally { $stream.Dispose() }
128
+ """
129
+ powershell = Path(os.environ["SystemRoot"]) / "System32/WindowsPowerShell/v1.0/powershell.exe"
130
+ subprocess.run([str(powershell), "-NoProfile", "-NonInteractive", "-Command", command],
131
+ env={**os.environ, "CODISCUSS_WEBP_INPUT": str(path), "CODISCUSS_WEBP_OUTPUT": str(output)},
132
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True, timeout=8,
133
+ creationflags=subprocess.CREATE_NO_WINDOW)
134
+
135
+
136
+ if __name__ == "__main__":
137
+ # The runner supplies an already opened project file as stdin. Never resolve a project-supplied module.
138
+ import sys
139
+
140
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
141
+ from backend.server import image_size
142
+
143
+ with TemporaryDirectory() as directory:
144
+ path = Path(directory) / "source"
145
+ remaining = os.fstat(sys.stdin.fileno()).st_size
146
+ if not 0 < remaining <= 64 * 1024 * 1024:
147
+ sys.exit(0)
148
+ with path.open("wb") as out:
149
+ while remaining:
150
+ chunk = sys.stdin.buffer.read(min(remaining, 1024 * 1024))
151
+ if not chunk:
152
+ sys.exit(0)
153
+ out.write(chunk)
154
+ remaining -= len(chunk)
155
+ with path.open("rb") as source:
156
+ width, height = image_size(source)
157
+ source.seek(0)
158
+ webp = source.read(12)[8:12] == b"WEBP"
159
+ if not width or not height or width * height > MAX_SOURCE_PIXELS:
160
+ sys.exit(0)
161
+ if webp:
162
+ decoded = Path(directory) / "decoded.png"
163
+ decode_system_webp(path, decoded)
164
+ path = decoded
165
+ result = encode_preview(path, width, height, 1440, project=True)
166
+ if result and len(result) < os.fstat(sys.stdin.fileno()).st_size:
167
+ sys.stdout.buffer.write(result)
@@ -56,4 +56,7 @@ Phones support portrait layout only. Tablets support both portrait and landscape
56
56
  - **Rooms are unavailable when the computer is offline:** If the computer is off, asleep, or its local service is stopped, the room list shows **Rooms (computer offline)** or **Rooms (computer not connected)**. It reconnects when the computer comes back online.
57
57
  - **Timed-out requests are not resent automatically:** If the computer does not respond in time, the page says “Result unconfirmed.”. Check the room to see whether the action took effect before trying again.
58
58
  - **Some changes require the computer:** Changing software executable paths, browsing outside Saved projects, and adding a new device must be done at the computer.
59
+ - **Attachment cache:** Pictures and files viewed through the relay are cached in this device’s browser and cleared when you unpair on this device.
59
60
  - **Clearing browser data requires pairing again:** Clearing browser data removes the device key. The handoff command also expires after 10 minutes, so keep the phone's clock reasonably accurate.
61
+
62
+ **View file relay timings.** On your phone, open Settings → Account → Paired devices and expand Recent relay timings (ms). The latest 12 file requests show response frame sizes in bytes and estimates for the phone link, site processing, computer link and local processing. The two location codes identify the phone request and computer connection ingress respectively. A dash means unavailable.
@@ -42,6 +42,8 @@ Rooms created by a host inherit its folder. Select the arrow to the left of the
42
42
 
43
43
  ### 3. Set project directories and browse project files
44
44
 
45
+ When viewing a project image through the relay on another device, supported images open as a “Reduced preview”. Choose “View original” for full detail (under file actions on narrow screens). Save downloads the original file. The local computer displays the original directly, as do other devices when a smaller preview cannot be generated.
46
+
45
47
  “File changes” below an answer shows the number of changed files and lines added or removed. Lists of five files or fewer open by default. Select the file count to open a longer list. Read-only visitors can see the list, but only the room owner can view patches.
46
48
 
47
49
  - **Add or remove directories.** A room supports one primary directory and up to eight additional directories. After creating a room, open the “Room” tab at the top of the room and find “Project folder”. Add or remove additional directories there. Changes apply from each member’s next run and do not interrupt a session. A primary directory cannot be changed after it is set. If the room was created without one, you can set it once in the same section. Members can access all room directories subject to their individual project permissions.
@@ -53,8 +55,8 @@ Rooms created by a host inherit its folder. Select the arrow to the left of the
53
55
 
54
56
  ### 4. Send and view attachments
55
57
 
56
- - **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.
57
- - **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.
58
+ - **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. Windows sites automatically generate smaller previews for eligible PNG 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.
59
+ - **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.
58
60
  - **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.
59
61
  - **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.
60
62
 
@@ -57,4 +57,7 @@ npm 安装默认提供本机站点,没有随包可直接使用的公共线上
57
57
  - **电脑离线时看不到房间**:电脑关机、休眠或本机服务未运行时,手机目录标题会显示“协作房间(电脑离线)”或“协作房间(电脑未连接)”;电脑恢复在线后页面自动重连。
58
58
  - **超时不自动重发**:电脑没及时答复时,页面会提示“结果待确认”,不会自动重发;先看房间确认是否已生效。
59
59
  - **只能在电脑上改的项**:软件可执行路径、常用项目范围之外的目录、以及添加新设备,都只能在电脑前操作。
60
+ - **附件缓存**:经中转看过的图片和文件会缓存在这台设备的浏览器里,在这台设备上解除配对时清除。
60
61
  - **清除浏览器数据需重配**:手机清理浏览器数据会删掉设备密钥,需回到电脑前重新配对;另外转交命令 10 分钟后作废,请保持手机系统时间大致准确。
62
+
63
+ **查看文件中转耗时**:在手机上打开“设置 → 账号 → 已配对的设备”,展开“最近中转耗时(毫秒)”查看最近 12 次文件请求的回应帧字节数与耗时。四列依次估算手机线路、站点内部、电脑线路和本机处理;机房代码依次属于手机请求和电脑连接。缺少测量用横线表示。
@@ -40,6 +40,8 @@
40
40
 
41
41
  ### 3. 设置多个项目目录并浏览项目文件
42
42
 
43
+ 在手机等设备经中转预览项目图片时,支持的图片先显示“缩小图”。需要细节可点“查看原图”(窄屏在“文件操作”菜单中),保存按钮下载原文件。本机网页直接显示原图;电脑无法生成更小的预览时,其他设备也显示原图。
44
+
43
45
  回答下方的“文件改动”显示已修改的文件数和增删行数。改动不超过 5 个文件时默认展开,超过时点击文件数查看清单。可读房间的访客也能看清单,只有房主能看补丁。
44
46
 
45
47
  - **增删项目目录**:一个房间可有 1 个主项目目录和最多 8 个其他项目目录。建房后打开顶部“房间”页,在“项目目录”区域可增删其他目录,保存后从各成员下一次执行起生效,不中断会话。主目录设置后不能更改;建房时未设的,可在同一行补设一次。成员按各自项目权限读写全部目录。
@@ -51,8 +53,8 @@
51
53
 
52
54
  ### 4. 发送与查看附件
53
55
 
54
- - **添加附件**:在输入框粘贴、拖入文件,或点左下角回形针按钮选择文件(每条消息最多 10 个,单个最多 20 MiB)。添加后输入框上方出现缩略图,正文光标处插入 `[图片 #1]`、`[文件 #2]` 等房间内连续编号的占位标签;删掉缩略图或按退格删掉占位,两边同步移除。发出后,正文里首次写到 `[图片 #n]` 的图片会紧跟在所在段落或列表项下方以半宽两列排布显示(手机上单张占满整宽、多张两列并排,多图消息附带 `#n` 角标),附件列表不再重复列出;其他附件仍列在消息下方。 已上传但一直未发送的附件超过 24 小时后会自动清理;已发送或仍在排队消息里的附件会保留。
55
- - **查看附件**:消息发出后点正文占位或附件卡片即可打开;图片支持全屏缩放、旋转与保存,房间里有多张图片时可用两侧按钮或键盘左右方向键切换,音视频直接在消息里播放,文档与代码在文件预览窗口打开。
56
+ - **添加附件**:在输入框粘贴、拖入文件,或点左下角回形针按钮选择文件(每条消息最多 10 个,单个最多 20 MiB)。添加后输入框上方出现缩略图,正文光标处插入 `[图片 #1]`、`[文件 #2]` 等房间内连续编号的占位标签;删掉缩略图或按退格删掉占位,两边同步移除。发出后,正文里首次写到 `[图片 #n]` 的图片会紧跟在所在段落或列表项下方以半宽两列排布显示(手机上单张占满整宽、多张两列并排,多图消息附带 `#n` 角标),附件列表不再重复列出;其他附件仍列在消息下方。 Windows 站点会为上传的 PNG 自动生成较小的预览,点击图片可读原图。 已上传但一直未发送的附件超过 24 小时后会自动清理;已发送或仍在排队消息里的附件会保留。
57
+ - **查看附件**:消息发出后点正文占位或附件卡片即可打开;图片支持全屏缩放、旋转与保存,房间里有多张图片时可用两侧按钮、键盘左右方向键或手机上左右滑动切换(两侧按钮无操作时自动隐藏,移动鼠标或轻点图片即重新出现),音视频直接在消息里播放,文档与代码在文件预览窗口打开。
56
58
  - **交互式可视化**:成员可以在回答正文里放一段可以操作的网页(拖动滑块、点按钮看结果变化),它显示在正文中的原位置,跟随房间主题和深浅色,手机上同样直接显示。滚到它附近才开始运行。下方一行可“收起”(会记住选择)、看“源码”、“放大”到文件预览窗口、在“新标签页”打开或“下载”为 `.html` 文件。只读分享页、朗读和消息折叠时的预览只显示“交互式可视化”一行,结论以成员写在正文里的文字为准。`.html` 附件不在消息内显示,点文件卡片在预览窗口或新标签页打开。有的可视化是提问面板:你在里面排序、分配或调整后点它的提交按钮,结果会作为引用放到输入框上方,不会直接发出;你可以删改,点发送才算回答。同一面板再次提交会替换上一次的结果。
57
59
  - **成员读取附件**:本机服务为支持附件的自动执行下载文件,并把文件信息交给接收任务的成员。Claude Code 和 Codex CLI 可直接看图;API 成员需在卡片设置中打开“看图”才能看图,UTF-8 文本附件可按需读取,PDF 等其他文件读不到时会如实说明。
58
60
 
@@ -1,4 +1,6 @@
1
1
  {
2
+ "查看原图": "View original",
3
+ "缩小图": "Reduced preview",
2
4
  "自动封面": "Automatic cover",
3
5
  "上传封面": "Upload cover",
4
6
  "选择房间图片": "Choose a room image",
@@ -1,4 +1,6 @@
1
1
  {
2
+ "最近中转耗时(毫秒)": "Recent relay timings (ms)",
3
+ "手机线路 {mobile} · 站点 {site} · 电脑线路 {link} · 本机 {local}": "Phone link {mobile} · Site {site} · Computer link {link} · Local {local}",
2
4
  "需连接本机服务": "Local service connection required",
3
5
  "读取中…": "Loading…",
4
6
  "{value1} · 未配置": "{value1} · Not configured",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai_co_discuss",
3
- "version": "0.5.35",
3
+ "version": "0.5.37",
4
4
  "bin": {
5
5
  "codiscuss": "runner/codiscuss.mjs"
6
6
  },
@@ -38,6 +38,7 @@
38
38
  "@vue-flow/core": "1.48.2",
39
39
  "@vue-flow/minimap": "1.5.4",
40
40
  "docx-preview": "0.4.1",
41
+ "fake-indexeddb": "6.2.8",
41
42
  "fflate": "0.8.3",
42
43
  "jsqr": "1.4.0",
43
44
  "katex": "0.18.10",
@@ -1,5 +1,5 @@
1
1
  import { ensure_global_experts_migrated, replace_global_experts, change_project_expert, project_experts } from './experts.mjs';
2
- import { local_settings } from './discussion_setup.mjs';
2
+ import { detect_python, local_settings } from './discussion_setup.mjs';
3
3
  /** Shared launch configuration for an existing AI conversation and the local website. */
4
4
  import { spawn } from 'node:child_process';
5
5
  import { createHash, randomUUID } from 'node:crypto';
@@ -739,6 +739,68 @@ export async function room_page(home, raw, { trust = false, parts = false } = {}
739
739
  // Through the relay a media file comes whole, in parts, so another device plays at most this much.
740
740
  export const REMOTE_MEDIA_MAX_BYTES = 64 * 1024 * 1024;
741
741
 
742
+ const PROJECT_PREVIEW_SLOTS = 12;
743
+ const PROJECT_PREVIEW_CONCURRENCY = 2;
744
+ const PROJECT_PREVIEW_MAX = 8 * 1024 * 1024;
745
+
746
+ /** Keep completed previews in an LRU; queued and running versions share a promise until encoding finishes. */
747
+ export function project_preview_reader(probe) {
748
+ const cached = new Map(), pending = new Map(), waiting = [];
749
+ let python, running = 0;
750
+ async function generate(home, key, encode) {
751
+ if (running === PROJECT_PREVIEW_CONCURRENCY) await new Promise(resolve => waiting.push(resolve));
752
+ else running++;
753
+ try {
754
+ python ??= Promise.resolve().then(() => probe(home));
755
+ const bytes = await encode(await python);
756
+ if (bytes) {
757
+ cached.set(key, bytes);
758
+ if (cached.size > PROJECT_PREVIEW_SLOTS) cached.delete(cached.keys().next().value);
759
+ }
760
+ return bytes;
761
+ } catch { return null; }
762
+ finally {
763
+ pending.delete(key);
764
+ if (waiting.length) waiting.shift()();
765
+ else running--;
766
+ }
767
+ }
768
+ return (home, key, encode) => {
769
+ if (cached.has(key)) {
770
+ const bytes = cached.get(key);
771
+ cached.delete(key);
772
+ cached.set(key, bytes);
773
+ return bytes;
774
+ }
775
+ if (!pending.has(key)) pending.set(key, generate(home, key, encode));
776
+ return pending.get(key);
777
+ };
778
+ }
779
+
780
+ const project_preview_bytes = project_preview_reader(home => detect_python(local_settings(home).python));
781
+
782
+ async function encode_project_preview(preview_python, file) {
783
+ const script = join(import.meta.dirname, '..', 'backend', 'windows_thumbnail.py');
784
+ const fd = openSync(file, 'r');
785
+ let child;
786
+ try {
787
+ child = spawn(preview_python, ['-I', '-B', script], {
788
+ windowsHide: true, timeout: 15000, stdio: [fd, 'pipe', 'ignore'], cwd: dirname(script),
789
+ });
790
+ } finally { closeSync(fd); }
791
+ return new Promise((resolve, reject) => {
792
+ let size = 0;
793
+ const chunks = [];
794
+ child.stdout.on('data', chunk => {
795
+ size += chunk.length;
796
+ if (size <= PROJECT_PREVIEW_MAX) chunks.push(chunk);
797
+ else child.kill();
798
+ });
799
+ child.on('error', reject);
800
+ child.on('close', code => resolve(code === 0 && size && size <= PROJECT_PREVIEW_MAX ? Buffer.concat(chunks) : null));
801
+ });
802
+ }
803
+
742
804
  /**
743
805
  * One image, video or audio file of the room's project (see `project_media`). For the computer's own page it names
744
806
  * the real file, which the local site streams by a ticket and never shows the page; with `parts` (another device,
@@ -760,6 +822,22 @@ export async function room_media(home, raw, { trust = false, parts = false } = {
760
822
  ? `文件 ${Math.ceil(media.size / 1024 / 1024)} MB,超过其他设备可下载的 ${REMOTE_MEDIA_MAX_BYTES / 1024 / 1024} MB 上限;请在这台电脑上取用,或让 AI 处理`
761
823
  : `文件 ${Math.ceil(media.size / 1024 / 1024)} MB,超过其他设备可播放的 ${REMOTE_MEDIA_MAX_BYTES / 1024 / 1024} MB 上限;请在这台电脑上打开`);
762
824
  }
825
+ if (process.platform === 'win32' && input.preview === true && !input.download && /^image\/(png|jpeg|webp)$/.test(media.content_type)) {
826
+ const preview_version = createHash('sha256').update(JSON.stringify([file, media.version, '1440-v2'])).digest('hex');
827
+ if (!offset && input.known_preview === preview_version) return { ...media, preview_version, unchanged: true };
828
+ const bytes = await project_preview_bytes(home, preview_version, python => {
829
+ const ready = project_media(directory, input.path);
830
+ if (ready.file !== file || ready.version !== media.version) return null;
831
+ return encode_project_preview(python, file);
832
+ });
833
+ const current = project_media(directory, input.path);
834
+ if (current.file !== file || current.version !== media.version) throw new Error('文件在读取时发生了变化,请重试');
835
+ if (bytes && bytes.length < media.size) {
836
+ const content_type = bytes[0] === 0xff ? 'image/jpeg' : 'image/png';
837
+ return { room_id: input.room_id, root, ...media, preview_version, content_type, total: bytes.length,
838
+ offset, data: bytes.subarray(offset, offset + PAGE_PART_BYTES).toString('base64') };
839
+ }
840
+ }
763
841
  const part = Buffer.alloc(Math.max(0, Math.min(PAGE_PART_BYTES, media.size - offset)));
764
842
  const handle = openSync(file, 'r');
765
843
  try { readSync(handle, part, 0, part.length, offset); } finally { closeSync(handle); }
@@ -10,6 +10,7 @@ import { join } from 'node:path';
10
10
  import timers from 'node:timers/promises';
11
11
  import { gzipSync } from 'node:zlib';
12
12
 
13
+ import { accept_timing, remember_timing } from './relay_timing.mjs';
13
14
  import { atomic_json } from './files.mjs';
14
15
  import { network_failure, reconnect_reader } from './relay_health.mjs';
15
16
  import { t } from './i18n.mjs';
@@ -101,6 +102,8 @@ export async function seal_compressed(key, value, label) {
101
102
  function relay_read_route(payload) {
102
103
  if ((payload?.method ?? 'GET') !== 'GET' || typeof payload?.path !== 'string') return '';
103
104
  const path = payload.path.split('?', 1)[0];
105
+ if (/\/attachments\/[^/]+\/(content|thumbnail)$/.test(path)) return path.endsWith('/thumbnail') ? 'thumbnail' : 'attachment';
106
+ if (path.endsWith('/room-media')) return 'room-media';
104
107
  if (path === '/api/rooms') return 'directory';
105
108
  if (/^\/api\/rooms\/[A-Za-z0-9_-]+$/.test(path)) return 'room';
106
109
  if (/^\/api\/rooms\/[A-Za-z0-9_-]+\/messages$/.test(path)) return 'messages';
@@ -279,19 +282,51 @@ async function run_command(home, command, run) {
279
282
 
280
283
  /** Answer one relayed request: room routes and uploads go to the local website, everything else to the local entrypoint as before. */
281
284
  export async function answer_request(home, site, link, frame, { run = run_launch_command, fetcher, report, timing } = {}) {
285
+ const started = timing?.received_at ?? performance.now();
282
286
  const { id, envelope } = frame;
283
287
  const key = await relay_cipher(link.private_key, envelope.key);
284
288
  const sealed = await unseal(key, envelope, id);
285
- let response, request = {};
289
+ let response, request = {}, device = null;
290
+ async function finish_response(value) {
291
+ const label = `${id}:response`;
292
+ let envelope = await seal_compressed(key, value, label);
293
+ let answer = { type: 'response', id, envelope };
294
+ let frame_bytes = Buffer.byteLength(JSON.stringify(answer));
295
+ if (frame_bytes > FRAME_MAX_BYTES) {
296
+ value = { status: 413, body: { error: '回应超过中转单帧上限,未能送出' } };
297
+ report?.({ action: request.action, route: '', status: 413 });
298
+ envelope = await seal_compressed(key, value, label);
299
+ answer = { type: 'response', id, envelope, oversized: true };
300
+ frame_bytes = Buffer.byteLength(JSON.stringify({ type: 'response', id, envelope }));
301
+ }
302
+ const elapsed = Math.round(performance.now() - started);
303
+ const action = request.action;
304
+ const category = action === 'room-api' ? relay_read_route(request.payload) || 'room-api'
305
+ : ROOM_ACTIONS.has(action) || DEVICE_ACTIONS.has(action) || ['computer-site', 'room-upload', 'room-media'].includes(action) ? action : 'other';
306
+ if (request.timing_version === 1 && action !== 'timing-report') {
307
+ // Seal the small measurement separately, after the business response has been compressed and encrypted.
308
+ try {
309
+ const diagnostic = await seal_compressed(key, { computer_ms: elapsed, category }, `${id}:timing`);
310
+ const extra_bytes = Buffer.byteLength(JSON.stringify(diagnostic)) + ',"timing":'.length;
311
+ if (frame_bytes + extra_bytes <= FRAME_MAX_BYTES) {
312
+ envelope.timing = diagnostic;
313
+ frame_bytes += extra_bytes;
314
+ }
315
+ } catch { /* A failed timing attachment must not hide a completed operation. */ }
316
+ }
317
+ if (action !== 'timing-report') {
318
+ const measurement = timing ?? {};
319
+ measurement.frame_bytes = frame_bytes;
320
+ remember_timing(home, site, device, id, category, elapsed, value.status, measurement);
321
+ }
322
+ return answer;
323
+ }
286
324
  // An external member's request (or an invite being redeemed) goes to the external gateway alone: it never reaches the
287
325
  // device actions, the local entrypoint or the bridge, and never gains this computer's owner credential.
288
326
  if (is_external_request(sealed)) {
289
327
  ({ request, response } = await answer_external(home, { machine_id: link.id, link, fetcher, on_change: () => sync_remote_launches(home) }, id, sealed));
290
328
  report?.({ action: request.action, route: '', status: response.status });
291
- const answer = { type: 'response', id, envelope: await seal_compressed(key, response, `${id}:response`) };
292
- if (JSON.stringify(answer).length <= FRAME_MAX_BYTES) return answer;
293
- return { type: 'response', id, oversized: true,
294
- envelope: await seal_compressed(key, { status: 413, body: { error: '回应超过中转单帧上限,未能送出' } }, `${id}:response`) };
329
+ return finish_response(response);
295
330
  }
296
331
  try {
297
332
  // Only a paired device's signed request runs; an unpaired browser may only prove a pairing code.
@@ -300,8 +335,9 @@ export async function answer_request(home, site, link, frame, { run = run_launch
300
335
  const { action, payload, target } = request;
301
336
  if (timing && action === 'room-api' && RELAY_READ_ID.test(id)) timing.route = relay_read_route(payload);
302
337
  claim_relayed_command(home, id, request.sent_at);
303
- const device = opened.device_id;
304
- response = DEVICE_ACTIONS.has(action) ? await device_command(home, { site, machine_id: link.id, device_id: device, on_change: () => sync_remote_launches(home) }, action, payload)
338
+ device = opened.device_id;
339
+ accept_timing(home, site, device, request.timing_reports);
340
+ response = action === 'timing-report' && device ? { status: 200, body: {} } : DEVICE_ACTIONS.has(action) ? await device_command(home, { site, machine_id: link.id, device_id: device, on_change: () => sync_remote_launches(home) }, action, payload)
305
341
  : action === 'computer-site' ? { status: 200, body: { site: local_origin(home) } }
306
342
  : action === 'room-api' ? await room_api(home, site, payload, { fetcher, device, timing })
307
343
  : action === 'room-upload' ? await room_upload(home, site, payload, { fetcher })
@@ -309,17 +345,13 @@ export async function answer_request(home, site, link, frame, { run = run_launch
309
345
  if (timing?.local_request_at !== undefined) timing.local_response_at = performance.now();
310
346
  } catch (error) { response = { status: 400, body: { error: error.message, ...(error.need ? { need: error.need } : {}), ...(error.error_text ? { error_text: error.error_text } : {}) } }; }
311
347
  // Remote writes go to this computer's audit log: kind, route, device and outcome, never content. Reads are not logged.
312
- if (request.action && !(request.action === 'room-api' && (request.payload?.method || 'GET') === 'GET') && !DEVICE_ACTIONS.has(request.action) && request.action !== 'computer-site') {
348
+ if (request.action && request.action !== 'timing-report' && !(request.action === 'room-api' && (request.payload?.method || 'GET') === 'GET') && !DEVICE_ACTIONS.has(request.action) && request.action !== 'computer-site') {
313
349
  audit(home, { event: 'command', action: request.action, route: typeof request.payload?.path === 'string' ? request.payload.path.split('?')[0] : '',
314
350
  device: sealed.device_id || null, status: response.status });
315
351
  }
316
352
  // Only what kind of request it was and how it ended: never its content or query.
317
353
  report?.({ action: request.action, route: typeof request.payload?.path === 'string' ? request.payload.path.split('?')[0] : '', status: response.status });
318
- const answer = { type: 'response', id, envelope: await seal_compressed(key, response, `${id}:response`) };
319
- if (JSON.stringify(answer).length <= FRAME_MAX_BYTES) return answer;
320
- report?.({ action: request.action, route: typeof request.payload?.path === 'string' ? request.payload.path.split('?')[0] : '', status: 413 });
321
- return { type: 'response', id, oversized: true,
322
- envelope: await seal_compressed(key, { status: 413, body: { error: '回应超过中转单帧上限,未能送出' } }, `${id}:response`) };
354
+ return finish_response(response);
323
355
  }
324
356
 
325
357
  /** Pass the local website's change notices to the devices while the relay is connected. */
@@ -516,10 +548,10 @@ async function hold_channel(home, site, { connected, log, signal, health, watch
516
548
  const { oversized, ...frame_out } = answer;
517
549
  if (open) {
518
550
  const outgoing = JSON.stringify(frame_out);
551
+ timing.queued_before_send = socket.bufferedAmount;
519
552
  socket.send(outgoing);
520
553
  if (timing.route) {
521
554
  timing.sent_at = performance.now();
522
- timing.frame_bytes = Buffer.byteLength(outgoing);
523
555
  timing.buffered_bytes = socket.bufferedAmount || 0;
524
556
  }
525
557
  }
@@ -0,0 +1,54 @@
1
+ /** Best-effort, bounded diagnostic output. The writer accepts only fixed numeric fields and categories. */
2
+ import { appendFile, stat, truncate } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+
5
+ const pending = new Map();
6
+ const LIMIT = 4 * 1024 * 1024;
7
+ const MAX_PENDING = 256;
8
+ const MAX_MS = 600000;
9
+ let writes = Promise.resolve();
10
+ let queued = 0;
11
+ const millis = value => Number.isInteger(value) && value >= 0 && value <= MAX_MS ? value : null;
12
+ const colo = value => typeof value === 'string' && /^[A-Z]{3}$/.test(value) ? value : null;
13
+
14
+ function finish(key, report = {}) {
15
+ const entry = pending.get(key);
16
+ if (!entry) return;
17
+ clearTimeout(entry.timer);
18
+ pending.delete(key);
19
+ const { home, row, measurement } = entry;
20
+ row.frame_bytes = measurement.frame_bytes;
21
+ row.buffered_bytes = measurement.queued_before_send ?? null;
22
+ const total = millis(report.total), worker = millis(report.worker), relay = millis(report.relay);
23
+ const diff = (a, b) => a !== null && b !== null ? millis(a - b) : null;
24
+ Object.assign(row, { mobile_ms: diff(total, worker), site_ms: diff(worker, relay),
25
+ link_ms: diff(relay, row.local_ms), device_colo: colo(report.dc), machine_colo: colo(report.mc) });
26
+ if (queued >= MAX_PENDING) return;
27
+ queued++;
28
+ writes = writes.then(async () => {
29
+ const file = join(home, 'relay-timing.jsonl');
30
+ const line = JSON.stringify(row) + '\n';
31
+ const size = await stat(file).then(s => s.size, e => { if (e.code === 'ENOENT') return 0; throw e; });
32
+ if (size + Buffer.byteLength(line) > LIMIT) await truncate(file, 0);
33
+ await appendFile(file, line, { mode: 0o600 });
34
+ }).catch(() => {}).finally(() => { queued--; });
35
+ }
36
+
37
+ /** Match feedback only to requests authenticated for this device and site. */
38
+ export function accept_timing(home, site, device, reports) {
39
+ if (!device || !Array.isArray(reports)) return;
40
+ for (const report of reports.slice(0, 16)) {
41
+ if (report && typeof report.id === 'string') finish(JSON.stringify([home, site, device, report.id]), report);
42
+ }
43
+ }
44
+
45
+ /** Flush locally observed requests even if a browser closes before reporting. */
46
+ export function remember_timing(home, site, device, id, category, elapsed, status, measurement) {
47
+ const key = JSON.stringify([home, site, device, id]);
48
+ if (pending.has(key)) finish(key);
49
+ if (pending.size >= MAX_PENDING) finish(pending.keys().next().value);
50
+ const timer = setTimeout(() => finish(key), 30000);
51
+ timer.unref();
52
+ const request_id = typeof id === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(id) ? id : null;
53
+ pending.set(key, { timer, home, measurement, row: { at: Date.now(), request_id, category, local_ms: millis(elapsed), status } });
54
+ }