ai_co_discuss 0.4.67 → 0.4.69

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.
@@ -3,7 +3,7 @@ import { spawnSync } from 'node:child_process';
3
3
  import { createHash, randomUUID } from 'node:crypto';
4
4
  import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
5
5
  import { basename, join, resolve } from 'node:path';
6
- import { adapter_of, BRANCHABLE_ADAPTERS, branch_session, capabilities_of, cleanup_room, deliver_task, delivery_receipt, session_exists, stored_delivery, takes_images } from './adapters/index.mjs';
6
+ import { adapter_of, BRANCHABLE_ADAPTERS, branch_session, capabilities_of, cleanup_room, deliver_task, delivery_receipt, recover_turn, session_exists, stored_delivery, takes_images } from './adapters/index.mjs';
7
7
  import { api as raw_api, overlapping_directories, read_rule } from './discussion_runner.mjs';
8
8
  import { SegmentLog } from './execution_progress.mjs';
9
9
  import { capture_base, file_diffs } from './file_diff.mjs';
@@ -41,12 +41,10 @@ const NOTICE_EXCERPT = 300;
41
41
  // A manual member's session that refuses a delivery is retried in the same execution, after a wait the owner can cut short.
42
42
  const MAX_DELIVERY_RETRIES = 3;
43
43
  const RETRY_DELAY_SECONDS = 60;
44
- // The cause is gone once the restarted runner is back, so its retry needs no long wait.
45
- const RESTART_RETRY_DELAY_SECONDS = 5;
46
- // The retry reason the site keeps for an execution a runner restart cut off; its redelivery asks to continue.
47
44
  // The failure classes an adapter may report (adapter contract `on_failure(reason, {failure_class, ...})`).
48
- const FAILURE_CLASSES = ['quota', 'auth', 'output_truncated'];
49
- const RESTART_REASON = room_text("本机接入程序重启或异常退出,这次执行的软件进程已结束,未提交回答");
45
+ const FAILURE_CLASSES = ['quota', 'auth', 'output_truncated', 'compaction_failed', 'policy_blocked'];
46
+ const RESTART_REASON = room_text("重启后无法确认上次执行结果");
47
+ // Recognize older versions' pending restart retries so upgrading cannot redeliver them.
50
48
  const RESTART_REASON_CODE = 'runner_restarted';
51
49
  const MAX_RETRY_REASON = 500;
52
50
  const LIVE = ['reserving', 'delivering', 'sidecar_pending', 'running', 'retry_wait'];
@@ -379,16 +377,6 @@ export function interjection_text(item) {
379
377
  return item.author ? `主持人 ${item.author} 插话:${item.text}` : `用户插话:${item.text}`;
380
378
  }
381
379
 
382
- /**
383
- * The preface of a task delivered again after the runner restarted mid-execution: the member's session usually still
384
- * holds the work done so far, so it continues instead of starting over. The original task follows, for a session that
385
- * never received it.
386
- */
387
- export function restart_notice(execution_id) {
388
- return `本机接入程序重启或异常退出,中断了你正在做的这次房间任务(执行 #${execution_id},仍在进行,没有结束)。`
389
- + '如果本会话里已经开始了它,接着完成,已经做完的部分不必重做;完成后照常用 codiscuss 提交这次执行的回答。原任务如下。\n\n';
390
- }
391
-
392
380
  // The fixed opening of a private chat turn: where the words come from and how to answer them; the owner's text follows.
393
381
  const CHAT_PREAMBLE = '房主在私聊窗口直接对你说(不在房间消息流里,其他成员看不到)。像在终端里对话一样直接用文字回答,不要用 codiscuss 提交到房间,除非房主明确要求;可以照常按你的权限读写项目文件。';
394
382
 
@@ -1017,7 +1005,7 @@ export class FreeRoomRunner {
1017
1005
  await this.invoke(member, execution);
1018
1006
  }
1019
1007
  /** Hand the execution to the member's software; only proven non-delivery is released for retry. */
1020
- async invoke(member, execution, { resume = '', preface = '' } = {}) {
1008
+ async invoke(member, execution, { resume = '' } = {}) {
1021
1009
  const adapter = this.config.participants[member.name];
1022
1010
  const review_request = execution.requests?.find(request => request.review?.phase === 'review');
1023
1011
  if (review_request) {
@@ -1072,10 +1060,11 @@ export class FreeRoomRunner {
1072
1060
  session, suggestions: scheduler_suggestions, reviews: review_handoffs, stopped, workflow, room_members: this.room?.members,
1073
1061
  goal: this.room?.goal_state?.goal || null, attachments, room: this.room, model_change,
1074
1062
  });
1063
+ this.store.db.prepare('DELETE FROM metadata WHERE key IN (?,?)').run(`recovery:${execution.id}`, `recovery-denied:${execution.id}`);
1075
1064
  invoked = true;
1076
1065
  this.segments.start(execution.id);
1077
1066
  if (warning) this.note(execution.id, warning);
1078
- const result = await this.deliver(review_request ? structuredClone(task.profile) : task.profile, binding, { ...task, ...(resume ? { prompt: resume, images: [] } : preface ? { prompt: preface + task.prompt } : {}), room_title: this.room_title,
1067
+ const result = await this.deliver(review_request ? structuredClone(task.profile) : task.profile, binding, { ...task, ...(resume ? { prompt: resume, images: [] } : {}), room_title: this.room_title,
1079
1068
  ...(review_request ? { before_model_start: () => this.check_review_delivery(member, review_request) } : {}),
1080
1069
  api_context: { site: this.config.site, room: this.config.room, token: this.config.members[member.name].token,
1081
1070
  home: this.config.api_home, mode: 'free', role: member.role || 'member', execution_id: execution.id,
@@ -1088,6 +1077,10 @@ export class FreeRoomRunner {
1088
1077
  ...(Number.isInteger(this.config.api_max_requests) ? { max_requests: this.config.api_max_requests } : {}),
1089
1078
  ...(this.config.image_generation ? { image_generation: true } : {}),
1090
1079
  ...(task.goal ? { goal: task.goal } : {}), ...(task.room_goal ? { room_goal: task.room_goal } : {}) },
1080
+ on_recovery: record => {
1081
+ if (current()) this.store.db.prepare('INSERT OR REPLACE INTO metadata VALUES (?,?)')
1082
+ .run(`recovery:${live()}`, JSON.stringify({ adapter: task.profile.adapter, record }));
1083
+ },
1091
1084
  on_binding: session => this.store.bind(member.name, session),
1092
1085
  on_process: child => this.track(member.name, child, live()),
1093
1086
  on_output: (path, chunk) => { appendFileSync(path, chunk, { mode: 0o600 }); this.touch(live()); this.segments.mark(live()); },
@@ -1113,11 +1106,18 @@ export class FreeRoomRunner {
1113
1106
  ...(Number.isSafeInteger(reset_at) && reset_at > 0 ? { reset_at } : {}) });
1114
1107
  try { if (this.row(member.name)?.execution_id === live()) this.save(member.name, { error }); } catch { /* Store may already be closed at shutdown. */ }
1115
1108
  },
1116
- on_exit: denial => { if (current()) this.exited.set(live(), denial || ''); },
1109
+ on_exit: denial => {
1110
+ if (!current()) return;
1111
+ this.exited.set(live(), denial || '');
1112
+ if (denial) this.store.db.prepare('INSERT OR REPLACE INTO metadata VALUES (?,?)').run(`recovery-denied:${live()}`, '1');
1113
+ },
1117
1114
  // Shown beside the answer or failure so the owner can allow them; a lost report only hides the list.
1118
1115
  on_denials: denials => {
1119
1116
  // A refused operation means the turn may be unfinished: its last remark is never captured as the answer.
1120
- if (denials?.length && current()) this.denied.add(live());
1117
+ if (denials?.length && current()) {
1118
+ this.denied.add(live());
1119
+ this.store.db.prepare('INSERT OR REPLACE INTO metadata VALUES (?,?)').run(`recovery-denied:${live()}`, '1');
1120
+ }
1121
1121
  api(this.config, `/executions/${live()}`, { action: 'denials', denials }).catch(() => {});
1122
1122
  },
1123
1123
  });
@@ -1224,16 +1224,15 @@ export class FreeRoomRunner {
1224
1224
  return this.save(member.name, { status: 'idle', error: '' });
1225
1225
  }
1226
1226
  if (row.status === 'retry_wait') {
1227
+ const reason_code = this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(`retry-reason:${execution.id}`)?.value;
1228
+ if (reason_code === RESTART_REASON_CODE) return this.recover_orphan(member, row, execution);
1227
1229
  const retry = execution.retry;
1228
1230
  if (retry?.stopped) return this.fail(member.name, execution.id, room_text("{value1}(已停止自动重试)", { value1: retry.reason }));
1229
1231
  if (retry?.retry_at && Date.now() >= retry.retry_at * 1000) {
1230
1232
  await api(this.config, `/executions/${execution.id}`, { action: 'retry_start' });
1231
1233
  this.save(member.name, { status: 'delivering' });
1232
- // Read from the site's retry record, so a second restart during the wait still delivers it as a continuation.
1233
- const reason_code = this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(`retry-reason:${execution.id}`)?.value;
1234
1234
  this.store.db.prepare('DELETE FROM metadata WHERE key=?').run(`retry-reason:${execution.id}`);
1235
- const preface = reason_code === RESTART_REASON_CODE ? restart_notice(execution.id) : '';
1236
- return this.invoke(member, await api(this.config, `/executions/${execution.id}`), { preface });
1235
+ return this.invoke(member, await api(this.config, `/executions/${execution.id}`));
1237
1236
  }
1238
1237
  }
1239
1238
  // A restart between persisting and invoking cannot prove non-delivery, so it never resends.
@@ -1242,10 +1241,9 @@ export class FreeRoomRunner {
1242
1241
  // A paused turn ending is not a failure: the execution waits, renewed, for the owner's words.
1243
1242
  if (await this.hold_paused(member, row, execution)) return;
1244
1243
  } else {
1245
- // Inherited from a runner that stopped or crashed: once its software processes are gone, no answer can come, so the
1246
- // same execution is delivered again after the retry wait instead of handing the failure to the host.
1244
+ // A dead inherited process is never redelivered: reconcile its exact recorded turn first.
1247
1245
  if (row.status === 'running' && this.orphan(execution.id)?.alive === false) {
1248
- return this.retry_or_fail(member.name, execution, RESTART_REASON, { restarted: true });
1246
+ return this.recover_orphan(member, row, execution);
1249
1247
  }
1250
1248
  if (row.error) return this.retry_or_fail(member.name, execution, row.error);
1251
1249
  if (this.exited.has(execution.id)) {
@@ -1496,25 +1494,47 @@ export class FreeRoomRunner {
1496
1494
  catch (error) { if (!/HTTP (404|409)/.test(error.message)) throw error; }
1497
1495
  }
1498
1496
  }
1499
- /**
1500
- * A manual member's session refused the delivery, or the software failed before any turn ran: keep the execution and
1501
- * deliver again after a wait shown on the website, up to MAX_DELIVERY_RETRIES times; so is an execution whose software
1502
- * ended with the previous runner process (`restarted`). Anything else, or the last attempt, fails as before.
1503
- */
1504
- async retry_or_fail(name, execution, reason, { restarted = false } = {}) {
1497
+ /** Check the website before reading local evidence; recovery never invokes software or schedules a retry. */
1498
+ async recover_orphan(member, row, execution) {
1499
+ const latest = await api(this.config, `/executions/${execution.id}`);
1500
+ if (!['dispatched', 'started'].includes(latest.status)) {
1501
+ this.forget_owner(execution.id);
1502
+ return this.save(member.name, { status: 'idle', error: '' });
1503
+ }
1504
+ const submitted = ['accepted', 'rejected'].includes(latest.delivery?.last_submission?.outcome);
1505
+ if (submitted) return this.fail(member.name, execution.id, room_text("{value1} 会话已结束,但未提交本次回答;请核对原会话确认是否已有内容", { value1: member.name }));
1506
+ let saved;
1507
+ try { saved = JSON.parse(this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(`recovery:${execution.id}`)?.value || 'null'); }
1508
+ catch { /* Invalid or old local records cannot identify a turn. */ }
1509
+ const result = !row.error && saved?.adapter === this.config.participants[member.name]?.adapter
1510
+ ? await recover_turn(saved.adapter, saved.record) : { status: 'unknown' };
1511
+ if (result.status === 'completed' && result.exact) {
1512
+ this.replies.set(execution.id, result.text || '');
1513
+ if (result.denied
1514
+ || this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(`recovery-denied:${execution.id}`)) this.denied.add(execution.id);
1515
+ if (await this.capture_reply(member.name, execution.id, latest)) {
1516
+ this.forget_owner(execution.id);
1517
+ return this.save(member.name, { status: 'idle', error: '' });
1518
+ }
1519
+ return this.fail(member.name, execution.id, room_text("{value1} 会话已结束,但未提交本次回答;请核对原会话确认是否已有内容", { value1: member.name }));
1520
+ }
1521
+ return this.fail(member.name, execution.id, RESTART_REASON);
1522
+ }
1523
+ /** Retry only deliveries known not to have started, or a manual member's refused delivery. */
1524
+ async retry_or_fail(name, execution, reason) {
1505
1525
  const attempt = (execution.retry?.attempt || 0) + 1;
1506
1526
  const not_started = this.not_started.delete(execution.id);
1507
1527
  if (this.not_retryable.delete(execution.id)) return this.fail(name, execution.id, reason);
1508
- if (!restarted && this.config.participants[name]?.project_access !== 'own' && !not_started) return this.fail(name, execution.id, reason);
1528
+ if (this.config.participants[name]?.project_access !== 'own' && !not_started) return this.fail(name, execution.id, reason);
1509
1529
  if (attempt > MAX_DELIVERY_RETRIES) return this.fail(name, execution.id, room_text("{value1}(已自动重试 {value2} 次)", { value1: reason, value2: MAX_DELIVERY_RETRIES }));
1510
1530
  this.stop_member(name);
1511
1531
  this.exited.delete(execution.id);
1512
1532
  this.replies.delete(execution.id);
1513
1533
  this.denied.delete(execution.id);
1514
1534
  this.store.db.prepare('INSERT INTO metadata VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value')
1515
- .run(`retry-reason:${execution.id}`, restarted ? RESTART_REASON_CODE : 'delivery_failed');
1535
+ .run(`retry-reason:${execution.id}`, 'delivery_failed');
1516
1536
  await api(this.config, `/executions/${execution.id}`, { action: 'retry_wait', attempt,
1517
- retry_at: Math.floor(Date.now() / 1000) + (restarted ? RESTART_RETRY_DELAY_SECONDS : RETRY_DELAY_SECONDS), reason: reason.slice(0, MAX_RETRY_REASON) });
1537
+ retry_at: Math.floor(Date.now() / 1000) + RETRY_DELAY_SECONDS, reason: reason.slice(0, MAX_RETRY_REASON) });
1518
1538
  this.save(name, { status: 'retry_wait', error: '' });
1519
1539
  }
1520
1540
  /**
@@ -1,5 +1,6 @@
1
1
  /** English CLI strings. */
2
2
  export default {
3
+ "CLI 运行超过 {seconds} 秒仍未结束,已终止": "CLI exceeded the runtime limit of {seconds} seconds and was terminated",
3
4
  "room-invite 创建待签到席位并签发邀请;提供 member_id 时重发该席位链接,旧链接失效。须提供 room_id、token,可选 level(discuss/read)、folders、duration(1h/today/3d)、site_url;程序先读名单 revision 再建席位。链接有效 10 分钟,未签到席位 7 天结束;未绑定线上站点时只建立席位。": "room-invite reserves a seat and issues an invitation; member_id regenerates that seat's link and invalidates the old one. Requires room_id and token; optional level (discuss/read), folders, duration (1h/today/3d), site_url. The runner reads the roster revision before creating a seat. Links last 10 minutes; unclaimed seats end after 7 days. Without a connected hosted site, only the seat is created.",
4
5
  "连不上 {host}:{seconds} 秒内没有响应,请检查这台电脑的网络或代理后重试": "Cannot connect to {host}: no response within {seconds} seconds. Check this computer's network or proxy and try again",
5
6
  "连不上 {host}:连接被断开({reason}),请检查这台电脑的网络或代理后重试": "Cannot connect to {host}: the connection was closed ({reason}). Check this computer's network or proxy and try again",
package/web/app.js CHANGED
@@ -124,7 +124,7 @@ const PLATFORM_IDENTITIES = {
124
124
  // An instance shows its platform's nickname with its own suffix: Antigravity-2 → Gemini-2.
125
125
  const EXTERNAL_ICON = 'data:image/svg+xml,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#a5a8b3" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="3" width="16" height="12" rx="2"/><path d="M2 19h20"/></svg>');
126
126
  const IDENTITIES = by_platform(PLATFORM_IDENTITIES, (identity, name) => external_identity(name)
127
- ? { label: t('另一台电脑'), icon: EXTERNAL_ICON, style: 'external', description: t('另一台电脑') }
127
+ ? { label: t('外部专家'), icon: EXTERNAL_ICON, style: 'external', description: t('外部专家') }
128
128
  : ({ ...identity, label: identity.label ? identity.label + name.slice(platform_of(name).length) : name, description: t('AI 实例') }));
129
129
 
130
130
  /** Reserved external names also retain their identity when shown in historical records. */
@@ -2245,6 +2245,9 @@ async function upload_message_attachments(room_id, actor, drafts) {
2245
2245
  item.uploaded = result.attachment.id;
2246
2246
  }
2247
2247
  identifiers.push(item.uploaded);
2248
+ // The sending card shows each file as uploading until it is in; the card's status says what is left.
2249
+ const preview = state.sending_drafts === drafts && state.sending_preview?.files?.[index];
2250
+ if (preview && !preview.uploaded) { preview.uploaded = true; state.sending_preview = { ...state.sending_preview, files: [...state.sending_preview.files] }; publish_view(); }
2248
2251
  }
2249
2252
  return identifiers;
2250
2253
  }
@@ -3264,18 +3267,51 @@ function relay_file_url(path, { urgent = false } = {}) {
3264
3267
  }
3265
3268
 
3266
3269
  /** Read a relayed image or media file once it nears the screen. */
3270
+ // The box around a relayed image is watched, not the image: an image waiting for its file is hidden (display: none,
3271
+ // markdown.css) behind a spinner, and a hidden element never intersects, so watching it left the image unread forever
3272
+ // (2026-11-16, iPhone: a message's own screenshots kept spinning).
3273
+ const relay_media_boxes = new WeakMap();
3274
+ const relay_media_box = (media) => media.closest(".attachment-image, .attachment-media") || media;
3267
3275
  const relay_media_observer = typeof IntersectionObserver === "function" ? new IntersectionObserver((entries) => {
3268
3276
  for (const entry of entries) {
3269
3277
  if (!entry.isIntersecting) continue;
3270
3278
  relay_media_observer.unobserve(entry.target);
3271
- load_relay_media(entry.target);
3279
+ for (const media of relay_media_boxes.get(entry.target) || []) load_relay_media(media);
3280
+ relay_media_boxes.delete(entry.target);
3272
3281
  }
3273
3282
  }, { rootMargin: RELAY_MEDIA_MARGIN }) : null;
3274
3283
 
3284
+ /** Watch the visible box of one relayed image or media element until it nears the screen. */
3285
+ function watch_relay_media(media) {
3286
+ const box = relay_media_box(media);
3287
+ relay_media_boxes.set(box, [...(relay_media_boxes.get(box) || []), media]);
3288
+ relay_media_observer.observe(box);
3289
+ }
3290
+
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");
3295
+
3275
3296
  /** Give one relayed image or media element its file; one that cannot be read keeps its name. */
3276
3297
  function load_relay_media(media) {
3277
3298
  if (!media.isConnected || media.getAttribute("src")) return;
3278
- relay_file_url(media.dataset.relaySrc).then(url => { media.src = url; }).catch(() => { media.dataset.relayFailed = "1"; });
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
+ }
3313
+ media.src = url;
3314
+ }).catch(() => { media.dataset.relayFailed = "1"; });
3279
3315
  }
3280
3316
 
3281
3317
  /** Show images of the computer's rooms as they appear; one that cannot be read keeps its name. */
@@ -3286,12 +3322,16 @@ function show_relay_images(records) {
3286
3322
  // A node taken off the page before it neared the screen is no longer watched.
3287
3323
  if (relay_media_observer) for (const node of record.removedNodes) {
3288
3324
  if (node.nodeType !== Node.ELEMENT_NODE) continue;
3289
- for (const image of node.matches("[data-relay-src]") ? [node] : node.querySelectorAll("[data-relay-src]")) relay_media_observer.unobserve(image);
3325
+ for (const image of node.matches("[data-relay-src]") ? [node] : node.querySelectorAll("[data-relay-src]")) {
3326
+ const box = relay_media_box(image);
3327
+ relay_media_observer.unobserve(box);
3328
+ relay_media_boxes.delete(box);
3329
+ }
3290
3330
  }
3291
3331
  for (const node of record.addedNodes) {
3292
3332
  if (node.nodeType !== Node.ELEMENT_NODE || !node.isConnected) continue;
3293
3333
  for (const image of node.matches(selector) ? [node] : node.querySelectorAll(selector)) {
3294
- if (relay_media_observer) relay_media_observer.observe(image);
3334
+ if (relay_media_observer) watch_relay_media(image);
3295
3335
  else load_relay_media(image);
3296
3336
  }
3297
3337
  }