ai_co_discuss 0.5.36 → 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.
@@ -1,5 +1,7 @@
1
1
  """Generate PNG or JPEG previews with the Windows system GDI+ codec."""
2
2
  import ctypes
3
+ import os
4
+ import subprocess
3
5
  from contextlib import ExitStack
4
6
  from functools import lru_cache
5
7
  from pathlib import Path
@@ -39,17 +41,25 @@ def graphics_library():
39
41
  return library
40
42
 
41
43
 
42
- def encode_preview(path, width, height, max_width=720):
44
+ def encode_preview(path, width, height, max_width=720, project=False):
43
45
  """Resize a bounded image, preserving transparency."""
44
46
  if not width or not height or width * height > MAX_SOURCE_PIXELS:
45
47
  return None
46
48
  library = graphics_library()
47
- scale = min(1, max_width / width, 1600 / height)
48
- width, height = max(1, round(width * scale)), max(1, round(height * scale))
49
+ max_height = max_width if project else 1600
49
50
  with ExitStack() as cleanup:
50
51
  source, bitmap, graphics = c_void_p(), c_void_p(), c_void_p()
51
52
  checked(library.GdipLoadImageFromFile(str(path), byref(source)))
52
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))
53
63
  checked(library.GdipCreateBitmapFromScan0(width, height, 0, ARGB32, None, byref(bitmap)))
54
64
  cleanup.callback(library.GdipDisposeImage, bitmap)
55
65
  checked(library.GdipGetImageGraphicsContext(bitmap, byref(graphics)))
@@ -60,20 +70,36 @@ def encode_preview(path, width, height, max_width=720):
60
70
  checked(library.GdipCreateImageAttributes(byref(attributes)))
61
71
  cleanup.callback(library.GdipDisposeImageAttributes, attributes)
62
72
  checked(library.GdipSetImageAttributesWrapMode(attributes, 3, 0, 0))
63
- source_width, source_height = c_uint(), c_uint()
64
- checked(library.GdipGetImageWidth(source, byref(source_width)))
65
- checked(library.GdipGetImageHeight(source, byref(source_height)))
66
- if source_width.value * source_height.value > MAX_SOURCE_PIXELS:
67
- return None
68
73
  checked(library.GdipDrawImageRectRectI(graphics, source, 0, 0, width, height, 0, 0,
69
74
  source_width, source_height, 2, attributes, None, None))
70
75
  encoder = preview_encoder(library, bitmap, width, height)
76
+ if project:
77
+ apply_image_orientation(library, source, bitmap)
71
78
  with TemporaryDirectory() as directory:
72
79
  output = Path(directory) / "preview"
73
80
  checked(library.GdipSaveImageToFile(bitmap, str(output), encoder, None))
74
81
  return output.read_bytes()
75
82
 
76
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
+
77
103
  def preview_encoder(library, bitmap, width, height):
78
104
  """Keep transparency in PNG, otherwise use the system JPEG encoder."""
79
105
  pixels = BitmapData()
@@ -86,3 +112,56 @@ def preview_encoder(library, bitmap, width, height):
86
112
  return PNG_ENCODER
87
113
  finally:
88
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)
@@ -58,3 +58,5 @@ Phones support portrait layout only. Tablets support both portrait and landscape
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
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.
60
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.
@@ -59,3 +59,5 @@ npm 安装默认提供本机站点,没有随包可直接使用的公共线上
59
59
  - **只能在电脑上改的项**:软件可执行路径、常用项目范围之外的目录、以及添加新设备,都只能在电脑前操作。
60
60
  - **附件缓存**:经中转看过的图片和文件会缓存在这台设备的浏览器里,在这台设备上解除配对时清除。
61
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 个其他项目目录。建房后打开顶部“房间”页,在“项目目录”区域可增删其他目录,保存后从各成员下一次执行起生效,不中断会话。主目录设置后不能更改;建房时未设的,可在同一行补设一次。成员按各自项目权限读写全部目录。
@@ -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.36",
3
+ "version": "0.5.37",
4
4
  "bin": {
5
5
  "codiscuss": "runner/codiscuss.mjs"
6
6
  },
@@ -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
+ }