ai_co_discuss 0.4.69 → 0.4.71

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/web/app.js CHANGED
@@ -79,8 +79,23 @@ const RELAY_PROTOCOL = "codiscuss-relay";
79
79
  const RELAY_PING_MS = 25000;
80
80
  const ROOM_RELAY_PATH = /^\/api\/(rooms|folders|revisions)(\/|\?|$)/;
81
81
  // One part is base64-encoded, encrypted and base64-encoded again (about 16/9 of its size), and the sealed request
82
- // must stay inside the hosted site's 512 KiB request limit (backend/worker.mjs MAX_BODY_BYTES).
83
- const RELAY_UPLOAD_PART_BYTES = 256 * 1024;
82
+ // must stay inside the hosted site's 512 KiB request limit (backend/worker.mjs MAX_BODY_BYTES). Parts stay small enough
83
+ // for a slow phone network to carry one well inside its wait: 256 KiB parts took 3.4 s each on a phone, and one that ran
84
+ // out of time failed the whole file, which then started over from its first part (2026-11-17: a 12 MiB recording
85
+ // arrived on the fifth try, after 72 parts had been sent for nothing).
86
+ const RELAY_UPLOAD_PART_BYTES = 128 * 1024;
87
+ // Parts in flight at once: each pays a round trip through the relay to the computer, and two overlap it.
88
+ const RELAY_UPLOAD_PARALLEL = 2;
89
+ // How long (ms) the relay waits for the computer to take one part; the page allows this plus its margin, which also
90
+ // covers sending the part over a slow network.
91
+ const RELAY_UPLOAD_WAIT_MS = 30000;
92
+ // A part lost on the way is sent again after these pauses; the computer keeps parts by number, so it stores it once.
93
+ const RELAY_UPLOAD_RETRY_MS = [1000, 2000, 4000, 8000, 15000];
94
+ // Passes over one file: its parts, then any the computer says it lacks.
95
+ const RELAY_UPLOAD_ROUNDS = 4;
96
+ // Uploads under way by file: a send tried again (SEND_RETRY_MS, or the composer's early upload) carries on from the parts
97
+ // the computer already has, under the same upload id.
98
+ const relay_uploads = new WeakMap();
84
99
  // Files of the computer's rooms come back in frames of about 1 MB over the one relay connection that also carries every
85
100
  // room read: only this many are read at once, so a room full of images cannot hold back its messages until they time out
86
101
  // (2026-11-16: opening a room with 51 screenshots read 46 MB at once; message reads and sends timed out, and the retried
@@ -213,6 +228,7 @@ state.create_api_max_requests = DEFAULT_API_MAX_REQUESTS;
213
228
  // Whether the new room lets its members draw with this computer's image service; chosen per room, never remembered.
214
229
  state.create_image_generation = false;
215
230
  let create_preferences_pending = {}, create_preferences_saving = null, create_preferences_version = 0;
231
+ let participant_choices_pending = {}, participant_choices_saving = null;
216
232
  const PLATFORM_CLIENTS = { Codex: [{ value: "codex_cli", label: "Codex CLI" }, { value: "codex", label: "Codex App" }],
217
233
  Claude: [{ value: "claude", label: "Claude Code CLI" }],
218
234
  Antigravity: [{ value: "antigravity_cli", label: "Antigravity CLI" }, { value: "antigravity", label: "Antigravity App" }] };
@@ -1110,7 +1126,15 @@ async function refresh_room_content(room_id, version, versions) {
1110
1126
  await Promise.all([room_read, history_read]);
1111
1127
  if (current()) publish_view();
1112
1128
  } catch (error) {
1113
- if (current()) { state.messages_loading = false; state.messages_failure = error.message; publish_view(); }
1129
+ // With the room's messages already on screen a failed re-read changes nothing there: the connection status says it,
1130
+ // and reconnecting reads again by itself. Only a room with nothing to show tells why in its place (2026-11-17: a
1131
+ // relay blip put a full-width error under the cards every few minutes).
1132
+ if (current()) {
1133
+ state.messages_loading = false;
1134
+ if (!state.messages.length) state.messages_failure = error.message;
1135
+ else set_connection(false);
1136
+ publish_view();
1137
+ }
1114
1138
  throw error;
1115
1139
  }
1116
1140
  }
@@ -1262,7 +1286,7 @@ async function select_room(room_id) {
1262
1286
  publish_view();
1263
1287
  const reading = state.opening = refresh_room();
1264
1288
  try { await reading; }
1265
- catch (error) { if (state.room?.id === room_id) state.messages_failure = error.message; throw error; }
1289
+ catch (error) { if (state.room?.id === room_id && !state.messages.length) state.messages_failure = error.message; throw error; }
1266
1290
  finally {
1267
1291
  if (state.opening === reading) state.opening = null;
1268
1292
  if (state.messages_loading && state.room?.id === room_id) { state.messages_loading = false; publish_view(); }
@@ -1949,7 +1973,7 @@ async function send_message(event) {
1949
1973
  const reply_to = state.reply_to;
1950
1974
  cancel_reply();
1951
1975
  const preview = { author: payload.author, text: payload.text, created_at: new Date().toISOString(), attachment_start: draft_start(drafts) || 1,
1952
- files: drafts.map(file => ({ name: file.file.name, preview_url: file.preview_url })) };
1976
+ files: drafts.map(file => ({ name: file.file.name, preview_url: file.preview_url, uploaded: Boolean(file.uploaded) })) };
1953
1977
  state.sending_drafts = drafts;
1954
1978
  state.attachment_drafts = [];
1955
1979
  // A message the site will likely queue shows at once as a row in the queue tray instead of a card in the transcript,
@@ -2055,6 +2079,8 @@ function discard_sending(id) {
2055
2079
  const failed = state.failed_sends.find((item) => item.id === id);
2056
2080
  if (!failed) return;
2057
2081
  release_files(failed.drafts);
2082
+ // Files of a send the site never saved are taken back; one it did save refuses, and stays with its message.
2083
+ failed.drafts.forEach(discard_draft_upload);
2058
2084
  state.failed_sends = state.failed_sends.filter((item) => item !== failed);
2059
2085
  }
2060
2086
 
@@ -2119,6 +2145,7 @@ function add_attachments(files, target = null) {
2119
2145
  renumber_placeholders(null);
2120
2146
  added.forEach(item => { item.placeholder = draft_placeholder(item, state.attachment_drafts.indexOf(item) + 1); });
2121
2147
  insert_placeholders(added.map(item => item.placeholder).join(" "), target);
2148
+ preupload_drafts(added);
2122
2149
  }
2123
2150
  render_attachment_drafts();
2124
2151
  publish_view();
@@ -2213,6 +2240,7 @@ function remove_attachment(ids) {
2213
2240
  if (!file) continue;
2214
2241
  if (file.preview_url) URL.revokeObjectURL(file.preview_url);
2215
2242
  state.attachment_drafts = state.attachment_drafts.filter(item => item !== file);
2243
+ discard_draft_upload(file);
2216
2244
  renumber_placeholders(file);
2217
2245
  }
2218
2246
  render_attachment_drafts();
@@ -2229,20 +2257,51 @@ function render_attachment_drafts() {
2229
2257
  element("attachment-status").textContent = state.upload_status;
2230
2258
  }
2231
2259
 
2260
+ /** Upload one draft file as `actor`; an earlier upload under another actor is replaced by a fresh submission. */
2261
+ async function upload_draft(room_id, actor, item) {
2262
+ item.upload_submission ??= item.id;
2263
+ if (item.actor && item.actor !== actor) { item.upload_submission = new_submission_id(); item.uploaded = null; }
2264
+ item.actor = actor;
2265
+ item.room_id = room_id;
2266
+ const params = new URLSearchParams({ file_name: item.file.name, actor, submission_id: item.upload_submission });
2267
+ const result = await post_room_file(`/api/rooms/${room_id}/attachments?${params}`, item.file, localStorage.getItem(`discuss-access:${room_id}`));
2268
+ item.uploaded = result.attachment.id;
2269
+ }
2270
+
2271
+ /**
2272
+ * Start uploading files as soon as they are in the composer, one after another, so sending has only the text left to
2273
+ * post. A failure here stays silent: sending uploads the file again and reports there. The welcome page has no room yet.
2274
+ */
2275
+ let preupload_chain = Promise.resolve();
2276
+ function preupload_drafts(items) {
2277
+ const room = state.room;
2278
+ if (!room || room.archived) return;
2279
+ for (const item of items) {
2280
+ item.uploading = preupload_chain = preupload_chain.then(() => item.removed || item.uploaded ? null : upload_draft(room.id, "用户", item))
2281
+ .catch(() => null).finally(() => { item.uploading = null; if (item.removed) discard_draft_upload(item); });
2282
+ }
2283
+ }
2284
+
2285
+ /** Take back a removed file uploaded ahead of sending; files never sent are also cleared by the site after a day. */
2286
+ function discard_draft_upload(item) {
2287
+ item.removed = true;
2288
+ if (item.uploading || !item.uploaded || !item.room_id) return;
2289
+ const path = `/api/rooms/${encodeURIComponent(item.room_id)}/attachments/${encodeURIComponent(item.uploaded)}/discard`;
2290
+ item.uploaded = null;
2291
+ request_json(path, {}).catch(() => null);
2292
+ }
2293
+
2232
2294
  /** Upload once per actual uploader, retaining receipts across ambiguous send failures. */
2233
2295
  async function upload_message_attachments(room_id, actor, drafts) {
2234
2296
  const identifiers = [];
2235
2297
  for (const [index, item] of drafts.entries()) {
2298
+ // A file still uploading from the composer finishes first, so it is not sent twice.
2299
+ if (item.uploading) await item.uploading;
2236
2300
  if (!item.uploaded || item.actor !== actor) {
2237
- item.upload_submission ??= item.id;
2238
- if (item.actor && item.actor !== actor) { item.upload_submission = new_submission_id(); item.uploaded = null; }
2239
- item.actor = actor;
2240
2301
  state.upload_status = t('正在上传 {value1}/{value2} · {value3}', { value1: index + 1, value2: drafts.length, value3: item.file.name });
2241
2302
  render_attachment_drafts();
2242
2303
  publish_view();
2243
- const params = new URLSearchParams({ file_name: item.file.name, actor, submission_id: item.upload_submission });
2244
- const result = await post_room_file(`/api/rooms/${room_id}/attachments?${params}`, item.file, localStorage.getItem(`discuss-access:${room_id}`));
2245
- item.uploaded = result.attachment.id;
2304
+ await upload_draft(room_id, actor, item);
2246
2305
  }
2247
2306
  identifiers.push(item.uploaded);
2248
2307
  // The sending card shows each file as uploading until it is in; the card's status says what is left.
@@ -2300,6 +2359,21 @@ function link_attachment_placeholders(html, files = []) {
2300
2359
  });
2301
2360
  }
2302
2361
 
2362
+ // The largest box a message image shows in (frontend/markdown.css `.attachment-image img`).
2363
+ const ATTACHMENT_IMAGE_MAX_WIDTH = 360, ATTACHMENT_IMAGE_MAX_HEIGHT = 320;
2364
+
2365
+ /**
2366
+ * The size an image the site measured shows at, as CSS variables on its button: the image and its loading box both
2367
+ * take it, so the image arriving pushes nothing below it down (2026-11-17: a screenshot growing from the 160×120 box
2368
+ * to 320px moved the cards under it on a phone). An image without a size keeps the box and its own height.
2369
+ */
2370
+ function attachment_image_style(file) {
2371
+ const width = Number(file.width), height = Number(file.height);
2372
+ if (!(width > 0 && height > 0)) return "";
2373
+ const shown = Math.max(1, Math.floor(Math.min(width, ATTACHMENT_IMAGE_MAX_WIDTH, ATTACHMENT_IMAGE_MAX_HEIGHT * width / height)));
2374
+ return ` style="--image-width: ${shown}px; --image-ratio: ${width} / ${height}"`;
2375
+ }
2376
+
2303
2377
  /** Render immutable file cards shared by messages, original-message dialogs, and themes. */
2304
2378
  function attachment_markup(files = []) {
2305
2379
  if (!files.length) return "";
@@ -2310,7 +2384,7 @@ function attachment_markup(files = []) {
2310
2384
  // Files of the computer's rooms are not on this website: they are read through the relay once shown or clicked.
2311
2385
  const source = state.remote_rooms ? `data-relay-src="${url}"` : `src="${url}"`;
2312
2386
  const download = attachment_download_attributes(file);
2313
- if (file.content_type.startsWith("image/")) return `<button type="button" class="attachment-image" ${preview_attributes}>
2387
+ if (file.content_type.startsWith("image/")) return `<button type="button" class="attachment-image" ${preview_attributes}${attachment_image_style(file)}>
2314
2388
  <img ${source} alt="${name}" loading="lazy"></button>`;
2315
2389
  // Audio and video play in place with the browser's own controls; a format it cannot decode still has its download.
2316
2390
  if (/^(audio|video)\//.test(file.content_type)) {
@@ -3213,17 +3287,56 @@ async function relay_room_bytes(path) {
3213
3287
  return new Blob(parts, { type });
3214
3288
  }
3215
3289
 
3216
- /** Send a file to a room route on the computer in parts; the computer hands it to its website whole. */
3290
+ /** Send one part of an upload, again after a loss on the way (network, timeout, the relay reconnecting). */
3291
+ async function relay_upload_part(payload) {
3292
+ for (let attempt = 0; ; attempt += 1) {
3293
+ try {
3294
+ const answer = await relay_exchange("room-upload", payload, RELAY_UPLOAD_WAIT_MS);
3295
+ if (answer.status >= 400) throw Object.assign(new Error(server_text(answer.body?.error_text, answer.body?.error) || t('附件上传失败')), { status: answer.status, refused: true });
3296
+ return answer;
3297
+ } catch (error) {
3298
+ const lost = !error.refused && (error.unconfirmed || error.offline || error instanceof TypeError || error.status >= 500 || error.status === 429);
3299
+ if (!lost || attempt >= RELAY_UPLOAD_RETRY_MS.length) throw error;
3300
+ await new Promise((resolve) => setTimeout(resolve, RELAY_UPLOAD_RETRY_MS[attempt]));
3301
+ }
3302
+ }
3303
+ }
3304
+
3305
+ /**
3306
+ * Send a file to a room route on the computer in parts, a few at a time; the computer hands it to its website whole.
3307
+ * Parts it already has are not sent again when the same file is tried again (relay_uploads).
3308
+ */
3217
3309
  async function relay_upload(path, data) {
3218
3310
  const bytes = new Uint8Array(data instanceof Blob ? await data.arrayBuffer() : data);
3219
- const id = crypto.randomUUID(), total = Math.max(1, Math.ceil(bytes.length / RELAY_UPLOAD_PART_BYTES));
3220
- let answer;
3221
- for (let index = 0; index < total; index++) {
3222
- const part = bytes.subarray(index * RELAY_UPLOAD_PART_BYTES, (index + 1) * RELAY_UPLOAD_PART_BYTES);
3223
- answer = await relay_exchange("room-upload", { id, path, index, total, size: bytes.length, data: bytes_to_base64(part) });
3224
- if (answer.status >= 400) throw Object.assign(new Error(server_text(answer.body?.error_text, answer.body?.error) || t('附件上传失败')), { status: answer.status });
3311
+ const total = Math.max(1, Math.ceil(bytes.length / RELAY_UPLOAD_PART_BYTES));
3312
+ let upload = relay_uploads.get(data);
3313
+ if (upload?.path !== path || upload.total !== total) relay_uploads.set(data, upload = { path, total, id: crypto.randomUUID(), done: new Set() });
3314
+ // Rounds: the parts not yet taken; then the parts the computer says it lacks (it restarted, or a part's answer went
3315
+ // astray). A computer too old to say which starts over once, under a new id.
3316
+ for (let round = 0; round < RELAY_UPLOAD_ROUNDS; round += 1) {
3317
+ const queue = [...Array(total).keys()].filter((index) => !upload.done.has(index));
3318
+ // Every part taken but no answer for the file (the last answer was lost): the last part asks for it again.
3319
+ if (!queue.length) queue.push(total - 1);
3320
+ let finished = null, missing = null, failure = null;
3321
+ const send = async () => {
3322
+ for (let index; !failure && (index = queue.shift()) !== undefined;) {
3323
+ const payload = { id: upload.id, path, index, total, size: bytes.length,
3324
+ data: bytes_to_base64(bytes.subarray(index * RELAY_UPLOAD_PART_BYTES, (index + 1) * RELAY_UPLOAD_PART_BYTES)) };
3325
+ try {
3326
+ const answer = await relay_upload_part(payload);
3327
+ upload.done.add(index);
3328
+ if (answer.body?.attachment) finished = answer.body;
3329
+ else if (Array.isArray(answer.body?.missing)) missing = answer.body.missing;
3330
+ } catch (error) { failure = error; }
3331
+ }
3332
+ };
3333
+ await Promise.all(Array.from({ length: Math.min(RELAY_UPLOAD_PARALLEL, queue.length) }, send));
3334
+ if (failure) throw failure;
3335
+ if (finished) { relay_uploads.delete(data); return finished; }
3336
+ if (missing) for (const index of missing) upload.done.delete(index);
3337
+ else relay_uploads.set(data, upload = { path, total, id: crypto.randomUUID(), done: new Set() });
3225
3338
  }
3226
- return answer.body;
3339
+ throw new Error(t('附件上传失败'));
3227
3340
  }
3228
3341
 
3229
3342
  /** Send file bytes to a room route on this website, or on the paired computer while its rooms are shown. */
@@ -3288,28 +3401,26 @@ function watch_relay_media(media) {
3288
3401
  relay_media_observer.observe(box);
3289
3402
  }
3290
3403
 
3291
- // WebKit (every iPhone browser) has no scroll anchoring: an image above the screen growing from its spinner box to its
3292
- // own height pushed everything shown down, and images arriving one after another over a slow relay made the transcript
3293
- // glide on by itself (2026-11-16, iPhone). There the position is kept by hand when such an image has loaded.
3294
- const NATIVE_SCROLL_ANCHORING = typeof CSS !== "undefined" && CSS.supports?.("overflow-anchor", "auto");
3404
+ /**
3405
+ * Resolve once the reader has stopped scrolling the transcript (it carries data-reader-scrolling meanwhile). An image
3406
+ * growing from its spinner box to its own height above the screen pushes what the reader sees down; landing after the
3407
+ * scroll, that growth is offset in the same frame (by the page on WebKit, by the browser elsewhere), where in the middle
3408
+ * of a touch scroll on an iPhone it could only jump (2026-11-17 recording: 320px).
3409
+ */
3410
+ function transcript_settled(scroller) {
3411
+ if (!scroller?.hasAttribute("data-reader-scrolling")) return Promise.resolve();
3412
+ return new Promise(resolve => scroller.addEventListener("reader-settled", resolve, { once: true }));
3413
+ }
3295
3414
 
3296
3415
  /** Give one relayed image or media element its file; one that cannot be read keeps its name. */
3297
3416
  function load_relay_media(media) {
3298
3417
  if (!media.isConnected || media.getAttribute("src")) return;
3299
- relay_file_url(media.dataset.relaySrc).then(url => {
3300
- const scroller = !NATIVE_SCROLL_ANCHORING && media.closest(".channel-transcript");
3301
- if (scroller) {
3302
- const box = relay_media_box(media), before = box.getBoundingClientRect().height;
3303
- const keep = () => {
3304
- if (!box.isConnected) return;
3305
- // Only a box that was wholly above the top of the shown area (judged by its bottom before it grew) moves what
3306
- // the reader sees.
3307
- const rect = box.getBoundingClientRect(), grown = rect.height - before;
3308
- if (grown && rect.bottom - grown <= scroller.getBoundingClientRect().top) scroller.scrollTop += grown;
3309
- };
3310
- media.addEventListener("load", keep, { once: true });
3311
- media.addEventListener("loadedmetadata", keep, { once: true });
3312
- }
3418
+ relay_file_url(media.dataset.relaySrc).then(async url => {
3419
+ const scroller = media.closest(".channel-transcript");
3420
+ // Decoded first, the image has its size the moment it gets its file, so the growth and its offset share one frame.
3421
+ if (scroller && media.tagName === "IMG") await Object.assign(new Image(), { src: url }).decode().catch(() => null);
3422
+ await transcript_settled(scroller);
3423
+ if (!media.isConnected || media.getAttribute("src")) return;
3313
3424
  media.src = url;
3314
3425
  }).catch(() => { media.dataset.relayFailed = "1"; });
3315
3426
  }
@@ -3997,6 +4108,27 @@ function default_launch_entry(name) {
3997
4108
  if (!LAUNCH_CLIENTS[name]?.some(item => item.value !== "api") && !state.launch.profiles[name]?.adapter) write_launch_field(name, "adapter", "api");
3998
4109
  }
3999
4110
 
4111
+ /** A platform card's model and effort are usage preferences: remember them as that software's default, like other form
4112
+ * choices. Instances from presets and a card switched to another entry than the saved one keep theirs to this room. */
4113
+ function remember_participant_choice(name, field, value) {
4114
+ const saved = state.launch.saved_profiles?.[name];
4115
+ if (!state.launch.available || platform_of(name) !== name || !saved || saved.adapter !== state.launch.profiles[name].adapter) return;
4116
+ if ((saved[field] || "") === value) return;
4117
+ if (value) saved[field] = value; else delete saved[field];
4118
+ participant_choices_pending = { ...participant_choices_pending, [name]: { ...participant_choices_pending[name], [field]: value } };
4119
+ flush_participant_choices();
4120
+ }
4121
+
4122
+ /** Serialize choice saves so a slower earlier save cannot overwrite the latest pick. */
4123
+ function flush_participant_choices() {
4124
+ if (participant_choices_saving || !Object.keys(participant_choices_pending).length) return;
4125
+ const patch = participant_choices_pending;
4126
+ participant_choices_pending = {};
4127
+ participant_choices_saving = local_launch_request("settings", { participant_choices: patch })
4128
+ .catch(error => notify("error", t('模型与强度偏好未保存:{value1}', { value1: error.message })))
4129
+ .finally(() => { participant_choices_saving = null; flush_participant_choices(); });
4130
+ }
4131
+
4000
4132
  /** Keep software drafts separate from shared room records and from discussion advancement mode. */
4001
4133
  function write_launch_field(name, field, value) {
4002
4134
  if (name === "workspace") state.launch.workspace[field] = value;
@@ -4014,6 +4146,7 @@ function write_launch_field(name, field, value) {
4014
4146
  }
4015
4147
  if (field === "base_url") delete state.launch.profiles[name].api_key_ref;
4016
4148
  fill_api_key(state.launch.profiles[name]);
4149
+ if (["model", "effort"].includes(field)) remember_participant_choice(name, field, value);
4017
4150
  }
4018
4151
  if (field === "adapter") render_launch_settings();
4019
4152
  else render_launch_summaries();