@kabxx/dsh-message-revision 0.1.0 → 0.1.1

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/src/client.js CHANGED
@@ -10,15 +10,21 @@ window.__ModuleLoader__.load({
10
10
  cleanupPending: '消息已更新并重发,部分旧记录待清理。',
11
11
  unchanged: '内容未修改', tooLong: '消息不能超过 200,000 个字符。',
12
12
  uploadWait: '附件仍在上传或上传失败,请处理后再发送。',
13
+ historicalImageSize: '旧图片的原始上传大小无法核对。请移除旧图片,或用原文件重新添加后再发送。',
13
14
  fileUnavailable: '当前会话无法添加附件。', fileDirectory: '不支持直接添加文件夹,请选择单个文件。',
14
15
  anotherEdit: '请先完成或取消当前编辑。',
15
16
  missing: '未找到该消息,请刷新后重试。', unsupported: '此消息不支持编辑。',
17
+ nonIndependentTurn: '此消息没有可独立回退的对话轮次。',
18
+ subagentUnsupported: '子智能体会话不支持直接编辑,请在主会话中操作。',
19
+ queuePending: '会话仍有排队消息,请等队列清空后再试。',
20
+ inheritedDuplicate: '无法替换继承历史中的同一条消息。',
16
21
  locked: '会话正被占用,暂时无法编辑。', changed: '会话状态已变更,请重新打开编辑框。',
17
22
  'composer-unavailable': '输入框未能加载,请刷新页面后重试。',
18
23
  'toolbar-update': '插件前后端版本不一致,请重新加载插件。',
19
24
  'child-conflict': '关联的子智能体会话无法回退,暂不支持编辑此消息。',
20
25
  syncing: '消息已更新,请重新打开会话刷新视图。',
21
26
  draftSaved: '草稿已保留。',
27
+ deliveryUnknown: '连接已中断,请先检查原会话是否已更新。',
22
28
  draftConflict: '原消息已变更,请先复制草稿后关闭重试。',
23
29
  textPart: '正文', sendPart: '发送',
24
30
  'reconnect-unavailable': '会话连接不可用,请重新打开会话。',
@@ -30,21 +36,28 @@ window.__ModuleLoader__.load({
30
36
  cleanupPending: 'Message updated and resent; some old records remain.',
31
37
  unchanged: 'No changes to send', tooLong: 'Message exceeds 200,000 characters.',
32
38
  uploadWait: 'Wait for uploads to finish or remove failed attachments.',
39
+ historicalImageSize: 'The upload size of an existing image is unavailable. Remove existing images or reattach them from the original files before sending.',
33
40
  fileUnavailable: 'Attachments are unavailable for this session.', fileDirectory: 'Folders are not supported; select individual files.',
34
41
  anotherEdit: 'Finish or cancel the current edit first.',
35
42
  missing: 'Message not found. Refresh and try again.', unsupported: 'This message cannot be edited.',
43
+ nonIndependentTurn: 'This message does not have an independently rewindable turn.',
44
+ subagentUnsupported: 'Subagent sessions cannot be edited directly. Edit from the main session instead.',
45
+ queuePending: 'Queued messages are still pending. Wait for the queue to clear and try again.',
46
+ inheritedDuplicate: 'Cannot replace a message that also appears in inherited history.',
36
47
  locked: 'Session is in use and cannot be edited right now.', changed: 'Session state changed. Reopen the editor.',
37
48
  'composer-unavailable': 'Failed to load the editor. Refresh the page and try again.',
38
49
  'toolbar-update': 'Plugin version mismatch. Reload the plugin.',
39
50
  'child-conflict': 'Cannot rewind associated subagent sessions for this message.',
40
51
  syncing: 'Message updated. Reopen the session to refresh.',
41
52
  draftSaved: 'Draft preserved.',
53
+ deliveryUnknown: 'The connection dropped. Check whether the conversation was updated.',
42
54
  draftConflict: 'Original message changed. Copy your draft and reopen to edit.',
43
55
  textPart: 'Text block', sendPart: 'Send',
44
56
  'reconnect-unavailable': 'Session connection unavailable. Reopen this session.',
45
57
  'authentication-required': 'Sign in required.', failed: 'Failed to update message. Try again.',
46
58
  },
47
59
  };
60
+ const zhErrorCodes = new Map(Object.entries(strings.zh).map(([key, value]) => [value, key]));
48
61
  const messageSeat = '[data-slot="conversation.chat.user.before"]';
49
62
  const editingRow = `div:has(> ${messageSeat} > .dsh-revision-editor)`;
50
63
  const originalContent = `${editingRow} > ${messageSeat} + *`;
@@ -207,9 +220,9 @@ window.__ModuleLoader__.load({
207
220
  x: ['M18 6l-12 12', 'M6 6l12 12'],
208
221
  };
209
222
 
210
- function TablerIcon({ name, size = 16 }) {
223
+ function TablerIcon({ name, size = 16, strokeWidth = 2 }) {
211
224
  return h('svg', { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor',
212
- strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round', focusable: 'false', 'aria-hidden': true },
225
+ strokeWidth, strokeLinecap: 'round', strokeLinejoin: 'round', focusable: 'false', 'aria-hidden': true },
213
226
  tablerPaths[name].map(d => h('path', { d, key: d })));
214
227
  }
215
228
 
@@ -266,12 +279,58 @@ window.__ModuleLoader__.load({
266
279
  }
267
280
  }
268
281
 
269
- async function resyncSessionView(sessions, sessionId, binding) {
270
- const { manager } = sessions;
282
+ function clearSessionProjections(manager, sessionId, projections) {
271
283
  manager.projectionInflight?.get(sessionId)?.controller.abort();
272
284
  manager.projectionInflight?.delete(sessionId);
273
285
  manager.projectionLoads?.delete(sessionId);
274
- binding.session.projections.clear();
286
+ projections?.clear?.();
287
+ }
288
+
289
+ const inheritedWindows = new WeakMap();
290
+ const inheritedNodes = new WeakMap();
291
+ const emptySubscribe = () => () => {};
292
+
293
+ function inheritedBoundary(eventSource) {
294
+ const window = eventSource?.getSnapshot();
295
+ if (!window) return -1;
296
+ const previous = inheritedWindows.get(eventSource);
297
+ if (previous?.revision === window.revision) return previous.boundary;
298
+ const change = window.change;
299
+ const incremental = previous?.revision + 1 === window.revision && change?.kind !== 'replace';
300
+ let boundary = incremental ? previous.boundary : -1;
301
+ const entries = incremental ? change?.entries : window.entries;
302
+ for (const { event } of entries ?? []) {
303
+ if (event.type === 'session/end-seed' && event.data?.inherited === true) boundary = Math.max(event.seq, boundary);
304
+ }
305
+ inheritedWindows.set(eventSource, { revision: window.revision, boundary });
306
+ return boundary;
307
+ }
308
+
309
+ function isInheritedMessage(nodes, source, boundary) {
310
+ if (!nodes || boundary < 0) return false;
311
+ // The native store identity survives history pagination. Its values
312
+ // snapshot changes when new rows become available.
313
+ const values = nodes.values();
314
+ let indexed = inheritedNodes.get(values);
315
+ if (indexed?.boundary !== boundary) {
316
+ const sources = new Map();
317
+ for (const node of values) {
318
+ if (node.kind !== 'user') continue;
319
+ const own = node.data.seq >= boundary;
320
+ sources.set(node.data.source, own || sources.get(node.data.source) === true);
321
+ }
322
+ indexed = { boundary, sources };
323
+ inheritedNodes.set(values, indexed);
324
+ }
325
+ return indexed.sources.get(source) === false;
326
+ }
327
+
328
+ function isEditableSessionMessage({ allowed, subagent, inherited }) {
329
+ return Boolean(allowed) && !subagent && !inherited;
330
+ }
331
+
332
+ async function resyncSessionView(sessions, sessionId, binding) {
333
+ clearSessionProjections(sessions.manager, sessionId, binding.session.projections);
275
334
  await binding.session.resync();
276
335
  }
277
336
 
@@ -282,8 +341,91 @@ window.__ModuleLoader__.load({
282
341
  if (typeof remove !== 'function' || typeof add !== 'function') return undefined;
283
342
  const holds = new Map();
284
343
  const transitions = new WeakMap();
344
+ let childReloads = Promise.resolve();
285
345
  let disposed = false;
286
346
 
347
+ function reloadParentCatalogs(ids) {
348
+ if (disposed || !Array.isArray(ids) || ids.length === 0 || ids.length > 128) return childReloads;
349
+ // An older list pull also writes these stores. Let that specific pull
350
+ // settle before clearing the old sequence watermark.
351
+ const listBeforeRevision = manager.listInflight;
352
+ if (listBeforeRevision) {
353
+ childReloads = childReloads.then(() => listBeforeRevision).catch(() => {});
354
+ }
355
+ for (const id of new Set(ids)) {
356
+ if (typeof id !== 'string' || id.length === 0 || id.length > 2048) continue;
357
+ childReloads = childReloads.then(async () => {
358
+ if (disposed) return;
359
+ const store = manager.projectionStores?.get(id);
360
+ if (!store) return;
361
+ // A rewrite lowers the native projection watermark. List-only tabs
362
+ // keep this store without ever binding or opening the conversation.
363
+ clearSessionProjections(manager, id, store);
364
+ await manager.refreshProjections?.(id);
365
+ }).catch(() => {});
366
+ }
367
+ return childReloads;
368
+ }
369
+
370
+ function reloadChildren(rewritten, withdrawn, affectedParentIds) {
371
+ if (disposed) return childReloads;
372
+ reloadParentCatalogs(affectedParentIds);
373
+ const changes = new Map();
374
+ for (const [ids, removed] of [[rewritten, false], [withdrawn, true]]) {
375
+ if (!Array.isArray(ids) || ids.length > 127) continue;
376
+ for (const id of ids) {
377
+ if (typeof id === 'string' && id.length > 0 && id.length <= 2048) changes.set(id, removed);
378
+ }
379
+ }
380
+ if (changes.size > 127) return childReloads;
381
+ for (const [id, withdrawnChild] of changes) {
382
+ childReloads = childReloads.then(async () => {
383
+ if (disposed) return;
384
+ const binding = sessionView(sessions, id);
385
+ if (!binding) {
386
+ clearSessionProjections(manager, id, manager.projectionStores?.get(id));
387
+ return;
388
+ }
389
+ const { session } = binding;
390
+ const snapshot = session.getSnapshot();
391
+ if (snapshot.openState === 'cold' || (snapshot.removed && !withdrawnChild)) {
392
+ clearSessionProjections(manager, id, session.projections);
393
+ return;
394
+ }
395
+ let transition = transitions.get(binding);
396
+ if (withdrawnChild && !transition) {
397
+ transition = { removal: 0, addition: 0, scheduled: -1, work: Promise.resolve() };
398
+ transitions.set(binding, transition);
399
+ }
400
+ const removal = transition?.removal;
401
+ let addition = transition?.addition;
402
+ await resyncSessionView(sessions, id, binding);
403
+ if (!withdrawnChild) return;
404
+ const currentBinding = () => !disposed && sessions.binding(id) === binding && transition.removal === removal;
405
+ if (!currentBinding()) return;
406
+ const notFound = ({ openState, openError }) => openState === 'error'
407
+ && (openError?.code === 'subagent/not-found' || openError?.code === 'session/not-found');
408
+ let current = session.getSnapshot();
409
+ // An addition while the read is pending may refer to a replacement
410
+ // under the same ID. Discard stale absence and verify the new view.
411
+ if (notFound(current) && transition.addition !== addition) {
412
+ addition = transition.addition;
413
+ await resyncSessionView(sessions, id, binding);
414
+ if (!currentBinding()) return;
415
+ current = session.getSnapshot();
416
+ }
417
+ if (notFound(current) && transition.addition === addition) {
418
+ session.installWindow?.([], false);
419
+ session.handleRemoved?.();
420
+ } else if (current.openState === 'open' && session.removed === true) {
421
+ session.removed = false;
422
+ session.notifier?.markDirty();
423
+ }
424
+ }).catch(() => {});
425
+ }
426
+ return childReloads;
427
+ }
428
+
287
429
  const undoRemove = replaceMethod(manager, 'handleSessionRemoved', function (id) {
288
430
  const binding = sessionView(sessions, id);
289
431
  const transition = binding && transitions.get(binding);
@@ -309,6 +451,8 @@ window.__ModuleLoader__.load({
309
451
  }
310
452
  const result = add.call(this, summary);
311
453
  if (disposed || summary.agentAvailable !== true) return result;
454
+ const activeTransition = binding && transitions.get(binding);
455
+ if (activeTransition) activeTransition.addition++;
312
456
  const hold = holds.get(id);
313
457
  if (hold) {
314
458
  hold.added();
@@ -322,7 +466,7 @@ window.__ModuleLoader__.load({
322
466
  // generation, including when another tab performed the rewrite.
323
467
  let transition = transitions.get(binding);
324
468
  if (!transition) {
325
- transition = { removal: 0, scheduled: -1, work: Promise.resolve() };
469
+ transition = { removal: 0, addition: 0, scheduled: -1, work: Promise.resolve() };
326
470
  transitions.set(binding, transition);
327
471
  }
328
472
  const removal = transition.removal;
@@ -356,6 +500,8 @@ window.__ModuleLoader__.load({
356
500
  throw new Error('reconnect-unavailable');
357
501
  }
358
502
  let removed = false;
503
+ let removalVersion = 0;
504
+ let resyncedRemoval = -1;
359
505
  let readded = false;
360
506
  let rebound = false;
361
507
  let released = false;
@@ -368,7 +514,7 @@ window.__ModuleLoader__.load({
368
514
  releaseComposer();
369
515
  };
370
516
  const hold = {
371
- removed() { removed = true; readded = false; rebound = false; },
517
+ removed() { removed = true; removalVersion++; readded = false; rebound = false; },
372
518
  added() {
373
519
  if (!removed || readded) return;
374
520
  readded = true;
@@ -381,7 +527,7 @@ window.__ModuleLoader__.load({
381
527
  holds.delete(sessionId);
382
528
  notifyAddition?.();
383
529
  releaseComposer();
384
- if (removed && !readded) manager.handleSessionRemoved(sessionId);
530
+ if (removed && !readded && resyncedRemoval !== removalVersion) manager.handleSessionRemoved(sessionId);
385
531
  },
386
532
  };
387
533
  holds.set(sessionId, hold);
@@ -401,17 +547,52 @@ window.__ModuleLoader__.load({
401
547
  });
402
548
  }
403
549
  if (released || sessions.binding(sessionId) !== binding) return;
550
+ const verifyingRemoval = removalVersion;
404
551
  await resyncSessionView(sessions, sessionId, binding);
405
552
  if (released || sessions.binding(sessionId) !== binding) return;
406
553
  const snapshot = session.getSnapshot();
407
- if (snapshot.openState !== 'open' || snapshot.removed) throw new Error('syncing');
554
+ if (snapshot.openState !== 'open' || snapshot.removed || verifyingRemoval !== removalVersion) {
555
+ throw new Error('syncing');
556
+ }
557
+ resyncedRemoval = verifyingRemoval;
408
558
  rebind();
409
559
  },
410
560
  };
411
561
  }
412
562
 
563
+ function reloadOpenChildren() {
564
+ let batch = [];
565
+ for (const id of sessions.scopes?.keys?.() ?? []) {
566
+ const snapshot = sessionView(sessions, id)?.session.getSnapshot();
567
+ if (!snapshot?.subagent || snapshot.openState === 'cold') continue;
568
+ batch.push(id);
569
+ if (batch.length === 127) {
570
+ reloadChildren([], batch);
571
+ batch = [];
572
+ }
573
+ }
574
+ return reloadChildren([], batch);
575
+ }
576
+
577
+ function refreshAfterNotificationGap() {
578
+ let batch = [];
579
+ for (const [id, projection] of manager.projectionStores ?? []) {
580
+ if (!projection.values?.()?.subagentCatalog?.length) continue;
581
+ batch.push(id);
582
+ if (batch.length === 128) {
583
+ reloadParentCatalogs(batch);
584
+ batch = [];
585
+ }
586
+ }
587
+ reloadParentCatalogs(batch);
588
+ return reloadOpenChildren();
589
+ }
590
+
413
591
  return {
414
592
  holdSessionView,
593
+ reloadChildren,
594
+ refreshAfterNotificationGap,
595
+ eventSource: sessionId => sessions.binding?.(sessionId)?.eventSource,
415
596
  dispose() {
416
597
  disposed = true;
417
598
  for (const hold of holds.values()) hold.release();
@@ -421,6 +602,70 @@ window.__ModuleLoader__.load({
421
602
  };
422
603
  }
423
604
 
605
+ // The corresponding Host descriptor is in revision-notifications.js.
606
+ const revisionRemoteName = 'messageRevisionEvents';
607
+ const revisionRemotePackage = '@kabxx/dsh-message-revision';
608
+ const revisionCursorPattern = /^[\da-f-]{36}:\d{1,16}$/u;
609
+ function revisionCodec(name, validate) {
610
+ return { mode: 'strict', typeSymbol: `${revisionRemotePackage}#${name}`, create: () => ({ parse(value) {
611
+ if (!validate(value)) throw new TypeError(`Invalid revision notification ${name}`);
612
+ return value;
613
+ } }) };
614
+ }
615
+ const revisionEventsContribution = { package: revisionRemotePackage, descriptors: [{
616
+ id: `${revisionRemotePackage}#${revisionRemoteName}/watch`, service: revisionRemoteName,
617
+ namespace: revisionRemoteName, method: 'watch', invocation: { kind: 'direct' },
618
+ mode: 'stream', cancellation: { parameter: 'signal' },
619
+ parameters: [{ name: 'cursor', wire: 'cursor', source: 'json', codec: revisionCodec('Cursor', value =>
620
+ value === null || (typeof value === 'string' && revisionCursorPattern.test(value))) }],
621
+ result: revisionCodec('Notice', value => {
622
+ const ids = (items, limit = 127) => Array.isArray(items) && items.length <= limit
623
+ && items.every(id => typeof id === 'string' && id.length > 0 && id.length <= 2048);
624
+ return value && typeof value.cursor === 'string' && revisionCursorPattern.test(value.cursor)
625
+ && (value.type === 'reset' || (value.type === 'revision' && ids(value.rewrittenChildren)
626
+ && ids(value.withdrawnChildren) && value.rewrittenChildren.length + value.withdrawnChildren.length <= 127
627
+ && (value.affectedParentIds === undefined || ids(value.affectedParentIds, 128))));
628
+ }),
629
+ }] };
630
+
631
+ function connectRevisionViews(views, remote, watch) {
632
+ let disposed = false;
633
+ let stream;
634
+ let retry;
635
+ let delay = 1000;
636
+ let cursor = null;
637
+ async function connect() {
638
+ if (disposed) return;
639
+ try {
640
+ stream = remote.$stream({
641
+ name: 'message revision history changes',
642
+ open: signal => watch(cursor, signal),
643
+ ended: () => new Error('Message revision history stream ended'),
644
+ });
645
+ for await (const item of stream) {
646
+ if (disposed) return;
647
+ const change = item.value;
648
+ if (change.type === 'reset') await views.refreshAfterNotificationGap();
649
+ else await views.reloadChildren(change.rewrittenChildren, change.withdrawnChildren, change.affectedParentIds);
650
+ if (disposed) return;
651
+ cursor = change.cursor;
652
+ delay = 1000;
653
+ item.accept();
654
+ }
655
+ } catch { /* A terminal failure may be temporary, such as a Host plugin reload. */ }
656
+ if (!disposed) {
657
+ retry = setTimeout(connect, delay);
658
+ delay = Math.min(delay * 2, 30_000);
659
+ }
660
+ }
661
+ void connect();
662
+ return async () => {
663
+ disposed = true;
664
+ clearTimeout(retry);
665
+ await stream?.dispose();
666
+ };
667
+ }
668
+
424
669
  function hookFor(source) {
425
670
  const subscribe = listener => source.subscribe(listener);
426
671
  const getSnapshot = () => source.getSnapshot();
@@ -535,18 +780,32 @@ window.__ModuleLoader__.load({
535
780
  const snapshot = directory.getSnapshot();
536
781
  if (previous !== snapshot) {
537
782
  previous = snapshot;
538
- overlay = { ...snapshot, current: selection };
783
+ const entry = snapshot.groups.find(group => group.id === selection.provider)
784
+ ?.models.find(model => model.id === selection.model);
785
+ const reasoning = entry?.reasoning;
786
+ const effort = selection.reasoningEffort ?? reasoning?.defaultEffort;
787
+ overlay = {
788
+ ...snapshot, current: selection, routable: snapshot.routable === null ? null : entry !== undefined,
789
+ retainedEffort: effort === undefined ? undefined : reasoning?.efforts.find(level => level.id === effort)?.name ?? effort,
790
+ };
539
791
  }
540
792
  return overlay;
541
793
  },
542
794
  };
543
795
  }
544
796
 
545
- function NativeEditor({ edit, dismiss, cancelLabel, renderSlot, t, ...props }) {
797
+ function NativeEditor({ edit, cancel, cancelLabel, requestPending, renderSlot, t, ...props }) {
546
798
  const { shell, useDraft, useNotices, useLexicon, useBusyEnter, useStopShortcut,
547
799
  useFileUploads, retained, conversation, imageService, uploaded, registerFileIntake } = edit.composer;
548
800
  const phase = useDraft(state => state.phase);
549
- const pending = phase === 'sending' || phase === 'adjudicating' || phase === 'submitting';
801
+ const pending = requestPending || phase === 'sending' || phase === 'adjudicating' || phase === 'submitting';
802
+ const locked = pending || props.disabled;
803
+ const editingLocked = () => locked || edit.isSubmitting();
804
+ // Voice transcription can finish after a send, even when the control is locked.
805
+ const activityActions = useMemo(() => ({
806
+ ...shell.actions,
807
+ insertText: (text, span) => !edit.isSubmitting() && shell.actions.insertText(text, span),
808
+ }), [edit, shell]);
550
809
  const [model, setModel] = useState(edit.settings.model);
551
810
  const [permission, setPermission] = useState(edit.settings.permissionPreset);
552
811
  const [previews, setPreviews] = useState({});
@@ -586,7 +845,7 @@ window.__ModuleLoader__.load({
586
845
  }, [conversation, retained, previews]);
587
846
  function addFiles(files, directories) {
588
847
  if (directories?.size > 0) return edit.labels.fileDirectory;
589
- if (props.disabled || pending || typeof conversation?.createDrafts !== 'function') {
848
+ if (editingLocked() || typeof conversation?.createDrafts !== 'function') {
590
849
  return edit.labels.fileUnavailable;
591
850
  }
592
851
  const drafts = [];
@@ -604,7 +863,7 @@ window.__ModuleLoader__.load({
604
863
  return edit.labels.fileUnavailable;
605
864
  }
606
865
  function removeAttachment(id) {
607
- if (props.disabled || pending || !shell.removeAttachment(id)) return;
866
+ if (editingLocked() || !shell.removeAttachment(id)) return;
608
867
  if (uploaded.delete(id)) conversation.releaseDraftAttachment(id);
609
868
  }
610
869
  const usePermissionProjection = (key, select) => props.useProjection(key, value => {
@@ -620,6 +879,7 @@ window.__ModuleLoader__.load({
620
879
  if (name === 'conversation.input.permission') return renderSlot(name, {
621
880
  ...owner, useProjection: usePermissionProjection,
622
881
  select: async preset => {
882
+ if (editingLocked()) return false;
623
883
  edit.settings.permissionPreset = preset;
624
884
  setPermission(preset);
625
885
  return true;
@@ -630,6 +890,7 @@ window.__ModuleLoader__.load({
630
890
  ...(modelDirectory === undefined ? { locked: true } : {
631
891
  directory: modelDirectory,
632
892
  select: async selection => {
893
+ if (editingLocked()) return { ok: false, error: { code: 'revision/busy', message: t('busy') } };
633
894
  edit.settings.model = selection;
634
895
  setModel(selection);
635
896
  return { ok: true, value: undefined };
@@ -637,7 +898,7 @@ window.__ModuleLoader__.load({
637
898
  }),
638
899
  });
639
900
  if (name === 'conversation.input.activity') {
640
- return renderSlot(name, { ...owner, inputActions: shell.actions });
901
+ return renderSlot(name, { ...owner, inputActions: activityActions });
641
902
  }
642
903
  if (name === 'conversation.input.plan') return renderSlot(name, { ...owner, locked: true });
643
904
  if (name === 'conversation.composer.dock') return renderSlot(name, owner);
@@ -670,6 +931,7 @@ window.__ModuleLoader__.load({
670
931
  const uploadAllowed = props.useAccess('fileUploads/upload') !== false;
671
932
  return h('div', {
672
933
  className: 'dsh-revision-editor',
934
+ 'aria-busy': requestPending || undefined,
673
935
  onDragEnterCapture: event => targetFileDrag(event),
674
936
  onDragOverCapture: event => targetFileDrag(event),
675
937
  onDropCapture: event => targetFileDrag(event, true),
@@ -679,18 +941,20 @@ window.__ModuleLoader__.load({
679
941
  || !event.target.closest('[contenteditable], .dsh-revision-cancel, .dsh-revision-text-part textarea')) return;
680
942
  event.preventDefault();
681
943
  event.stopPropagation();
682
- if (!pending) dismiss();
944
+ if (!pending) cancel();
683
945
  },
684
946
  }, edit.additionalText.map((value, index) => h('label', {
685
947
  key: index, className: 'dsh-revision-text-part',
686
948
  }, `${edit.labels.textPart} ${index + 2}`, h('textarea', {
687
- defaultValue: value, disabled: pending || props.disabled,
949
+ defaultValue: value, disabled: locked,
688
950
  onChange: event => {
951
+ if (editingLocked()) return;
689
952
  edit.additionalText[index] = event.currentTarget.value;
690
953
  setPartsVersion(version => version + 1);
691
954
  },
692
955
  }))), h(edit.native.component, {
693
956
  ...props,
957
+ disabled: locked,
694
958
  t: (key, ...args) => t(key === 'input.commands' ? 'input.file' : key, ...args),
695
959
  variant: 'composer', occurrence: 'embedded',
696
960
  renderSlot: renderEditorSlot, useInput: useDraft, inputActions: shell.actions,
@@ -698,13 +962,13 @@ window.__ModuleLoader__.load({
698
962
  useBusyEnter, useStopShortcut, useFileUploads: useCombinedUploads,
699
963
  registerFileIntake, resolveDraftAttachments, removeAttachment,
700
964
  addFiles: canUpload ? addFiles : undefined,
701
- retryFileUpload: id => { if (uploaded.has(id)) conversation.retryFileUpload(props.sessionId, id); },
702
- toggleCommandMenu: canUpload && uploadAllowed ? () => shell.pickFiles() : undefined,
965
+ retryFileUpload: id => { if (!editingLocked() && uploaded.has(id)) conversation.retryFileUpload(props.sessionId, id); },
966
+ toggleCommandMenu: canUpload && uploadAllowed ? () => { if (!editingLocked()) shell.pickFiles(); } : undefined,
703
967
  retry: undefined, stop: undefined,
704
968
  accessory: h('button', { type: 'button', className: 'dsh-revision-cancel', disabled: pending,
705
- title: cancelLabel, 'aria-label': cancelLabel, onClick: () => dismiss() }, h(TablerIcon, { name: 'x' })),
706
- }), sendRemainingText && h('button', { type: 'button', disabled: pending || props.disabled,
707
- onClick: () => void edit.submit(draftText, draftAttachments),
969
+ title: cancelLabel, 'aria-label': cancelLabel, onClick: cancel }, h(TablerIcon, { name: 'x' })),
970
+ }), sendRemainingText && h('button', { type: 'button', disabled: locked,
971
+ onClick: () => { if (!editingLocked()) void edit.submit(draftText, draftAttachments); },
708
972
  }, edit.labels.sendPart));
709
973
  }
710
974
 
@@ -714,6 +978,18 @@ window.__ModuleLoader__.load({
714
978
  const lifetime = new AbortController();
715
979
  let activeEditor;
716
980
  let sessionViews;
981
+ const sessionViewListeners = new Set();
982
+ const readSessionViews = () => sessionViews;
983
+ const observeSessionViews = listener => {
984
+ sessionViewListeners.add(listener);
985
+ return () => sessionViewListeners.delete(listener);
986
+ };
987
+ function setSessionViews(next) {
988
+ if (sessionViews === next) return;
989
+ sessionViews = next;
990
+ for (const listener of sessionViewListeners) listener();
991
+ }
992
+ let pendingUnmount = Promise.resolve();
717
993
  let submitting = false;
718
994
  const savedDrafts = new Map();
719
995
  const draftListeners = new Set();
@@ -761,12 +1037,18 @@ window.__ModuleLoader__.load({
761
1037
  let composerFactoryLive = false;
762
1038
 
763
1039
  async function requestRevision(payload) {
764
- const response = await fetch('/api/message-revision', {
765
- method: 'POST', credentials: 'same-origin', signal: lifetime.signal,
766
- headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload),
767
- });
768
- const result = await response.json().catch(() => null);
1040
+ let response;
1041
+ try {
1042
+ response = await fetch('/api/message-revision', {
1043
+ method: 'POST', credentials: 'same-origin', signal: lifetime.signal,
1044
+ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload),
1045
+ });
1046
+ } catch (cause) {
1047
+ throw Object.assign(new Error('deliveryUnknown', { cause }), { deliveryUnknown: true });
1048
+ }
769
1049
  if (response.status === 401 || response.status === 403) throw new Error('authentication-required');
1050
+ const result = await response.json().catch(() => null);
1051
+ if (result === null) throw Object.assign(new Error('deliveryUnknown'), { deliveryUnknown: true });
770
1052
  if (!response.ok || result?.ok !== true) {
771
1053
  throw Object.assign(new Error('failed'), {
772
1054
  hostError: typeof result?.error === 'string' ? result.error : '',
@@ -776,30 +1058,58 @@ window.__ModuleLoader__.load({
776
1058
  return result;
777
1059
  }
778
1060
 
779
- function RevisionAction({ t, matched, sessionId, useChat, useSession, useAccess, renderFactorySlot }) {
780
- const allowed = useAccess('session/prompt');
1061
+ const ownerAccessAction = 'settings/describe';
1062
+
1063
+ function RevisionAction({ t, matched, sessionId, useChat, useSession, useSessions, useAccess, useRemoteAccess, renderFactorySlot }) {
1064
+ // Exact Host routes (/api/message-revision) admit only the Host owner.
1065
+ // Core owner-only endpoints stay excluded from LiveShare viewer grants.
1066
+ const owner = useRemoteAccess(ownerAccessAction);
1067
+ const canPrompt = useAccess('session/prompt');
1068
+ const canUpdateQueue = useAccess('session/updateQueue');
1069
+ const allowed = owner && canPrompt && canUpdateQueue;
1070
+ const subagentAddress = useSession(s => s.subagent != null) ?? false;
1071
+ const subagentOrigin = useSessions(s => s.byId?.[sessionId]?.origin === 'subagent') ?? false;
1072
+ const subagent = subagentAddress || subagentOrigin;
781
1073
  const status = useSession(s => s.removed || s.openState !== 'open' ? 'unavailable'
782
1074
  : s.running || s.pendingSubmissions.length > 0 ? 'busy' : 'idle');
783
1075
  const busy = status === 'busy';
784
1076
  const nodes = useChat(s => s.nodes);
1077
+ const views = useSyncExternalStore(observeSessionViews, readSessionViews);
1078
+ const eventSource = views?.eventSource(sessionId);
1079
+ const subscribeToHistory = useCallback(listener => eventSource?.subscribe(listener) ?? emptySubscribe(), [eventSource]);
1080
+ const readInheritedBoundary = useCallback(() => inheritedBoundary(eventSource), [eventSource]);
1081
+ const inherited = useSyncExternalStore(subscribeToHistory, readInheritedBoundary);
1082
+ const inheritedMessage = isInheritedMessage(nodes, matched, inherited);
1083
+ const editable = isEditableSessionMessage({ allowed, subagent, inherited: inheritedMessage });
1084
+ const editableRef = useRef(editable);
1085
+ editableRef.current = editable;
785
1086
  const savedVersion = useSyncExternalStore(observeDrafts, readDraftVersion);
786
1087
  const [edit, setEdit] = useState(null);
787
1088
  const [opening, setOpening] = useState(false);
1089
+ const [requestPending, setRequestPending] = useState(false);
788
1090
  const [tooltipDismissed, setTooltipDismissed] = useState(false);
789
1091
  const pencil = useRef(null);
790
1092
  const restoreFocus = useRef(false);
791
1093
  const pending = useRef(false);
792
- const owner = useRef(Symbol());
1094
+ const ownerClaim = useRef(Symbol());
793
1095
  const draft = useRef(null);
794
1096
  useEffect(() => {
795
1097
  setEdit(null);
796
1098
  setOpening(false);
797
1099
  return () => {
798
- if (activeEditor === owner.current) activeEditor = undefined;
1100
+ if (activeEditor === ownerClaim.current) activeEditor = undefined;
799
1101
  draft.current?.dispose();
800
1102
  draft.current = null;
801
1103
  };
802
1104
  }, [sessionId, matched]);
1105
+ useLayoutEffect(() => {
1106
+ if (editable) return;
1107
+ setEdit(null);
1108
+ setOpening(false);
1109
+ if (activeEditor === ownerClaim.current) activeEditor = undefined;
1110
+ draft.current?.dispose();
1111
+ draft.current = null;
1112
+ }, [editable]);
803
1113
  useLayoutEffect(() => {
804
1114
  if (!edit && restoreFocus.current) {
805
1115
  restoreFocus.current = false;
@@ -807,20 +1117,21 @@ window.__ModuleLoader__.load({
807
1117
  }
808
1118
  }, [edit]);
809
1119
  useEffect(() => {
810
- if (!allowed || status !== 'idle' || edit || opening || activeEditor !== undefined || submitting) return;
1120
+ if (!editable || status !== 'idle' || edit || opening || activeEditor !== undefined || submitting) return;
811
1121
  const node = messageInRow(pencil.current);
812
1122
  if (!node) return;
813
1123
  const saved = savedDrafts.get(revisionDraftKey(sessionId, node.data.messageId));
814
1124
  if (saved?.reopenInView !== window.location.href) return;
815
1125
  saved.reopenInView = undefined;
816
1126
  void openEditor(node, saved);
817
- }, [allowed, status, edit, opening, nodes, matched, sessionId, savedVersion]);
818
- if (!allowed) return null;
1127
+ }, [editable, status, edit, opening, nodes, matched, sessionId, savedVersion]);
1128
+ if (!editable) return null;
819
1129
 
820
1130
  function errorMessage(error) {
821
1131
  const message = typeof error?.hostError === 'string' ? error.hostError.trim() : '';
822
- const code = Object.hasOwn(strings.zh, message) ? message
823
- : Object.hasOwn(strings.zh, error?.message) ? error.message : null;
1132
+ const code = (Object.hasOwn(strings.zh, message) ? message : zhErrorCodes.get(message))
1133
+ ?? (Object.hasOwn(strings.zh, error?.message) ? error.message : zhErrorCodes.get(error?.message))
1134
+ ?? null;
824
1135
  return code ? t(code) : (message.slice(0, 240) || t('failed'));
825
1136
  }
826
1137
 
@@ -848,12 +1159,16 @@ window.__ModuleLoader__.load({
848
1159
  if (!Array.isArray(content)) { notify(t('unsupported')); return; }
849
1160
  const native = nativeComposerEntry(ctx.slots);
850
1161
  if (!native || !composerFactoryLive) { notify(t('composer-unavailable')); return; }
851
- const claim = owner.current = Symbol();
1162
+ const claim = ownerClaim.current = Symbol();
852
1163
  activeEditor = claim;
853
1164
  setOpening(true);
854
1165
  try {
855
1166
  const result = await requestRevision({ sessionId, messageId: node.data.messageId });
856
- if (activeEditor !== claim || lifetime.signal.aborted) return;
1167
+ if (activeEditor !== claim || !editableRef.current || lifetime.signal.aborted) {
1168
+ if (activeEditor === claim) activeEditor = undefined;
1169
+ setOpening(false);
1170
+ return;
1171
+ }
857
1172
  if (typeof result.revision !== 'string' || typeof result.text !== 'string') throw new Error('failed');
858
1173
  if (result.toolbarRevision !== 1 || !Array.isArray(result.attachments)
859
1174
  || !Array.isArray(result.textParts) || result.textParts.some(part => typeof part !== 'string')
@@ -874,6 +1189,7 @@ window.__ModuleLoader__.load({
874
1189
  .find(entry => entry.locale === 'model')?.inject?.(sessionId)?.directory,
875
1190
  readFileDrag: transfer => ctx.get('fileDrag')?.read(transfer),
876
1191
  labels: { fileDirectory: t('fileDirectory'), fileUnavailable: t('fileUnavailable'), textPart: t('textPart'), sendPart: t('sendPart') },
1192
+ isSubmitting: () => pending.current,
877
1193
  submit: (text, attachmentIds) => submit(edit, text, attachmentIds, claim),
878
1194
  };
879
1195
  edit.composer = openDraft(ctx, native, sessionId, firstText, result.attachments,
@@ -885,7 +1201,11 @@ window.__ModuleLoader__.load({
885
1201
  setOpening(false);
886
1202
  setEdit(edit);
887
1203
  } catch (error) {
888
- if (activeEditor !== claim || lifetime.signal.aborted) return;
1204
+ if (activeEditor !== claim || !editableRef.current || lifetime.signal.aborted) {
1205
+ if (activeEditor === claim) activeEditor = undefined;
1206
+ setOpening(false);
1207
+ return;
1208
+ }
889
1209
  activeEditor = undefined;
890
1210
  setOpening(false);
891
1211
  notify(errorMessage(error));
@@ -893,7 +1213,7 @@ window.__ModuleLoader__.load({
893
1213
  }
894
1214
 
895
1215
  function dismiss(restore = true) {
896
- if (activeEditor === owner.current) activeEditor = undefined;
1216
+ if (activeEditor === ownerClaim.current) activeEditor = undefined;
897
1217
  restoreFocus.current = restore === true;
898
1218
  const composer = draft.current;
899
1219
  draft.current = null;
@@ -901,6 +1221,10 @@ window.__ModuleLoader__.load({
901
1221
  composer?.dispose();
902
1222
  }
903
1223
 
1224
+ function cancel() {
1225
+ if (!pending.current) dismiss();
1226
+ }
1227
+
904
1228
  async function submit(edit, text, attachmentIds, claim) {
905
1229
  if (edit.conflicted) {
906
1230
  notify(t('draftConflict'));
@@ -908,7 +1232,7 @@ window.__ModuleLoader__.load({
908
1232
  }
909
1233
  const textParts = edit.additionalText.length ? [text, ...edit.additionalText] : undefined;
910
1234
  if (textParts) text = textParts.join('');
911
- if (submitting || pending.current || activeEditor !== claim || (!text.trim() && attachmentIds.length === 0)) {
1235
+ if (submitting || pending.current || activeEditor !== claim || !editableRef.current || (!text.trim() && attachmentIds.length === 0)) {
912
1236
  return { kind: 'error' };
913
1237
  }
914
1238
  const { retained, conversation } = edit.composer;
@@ -955,8 +1279,10 @@ window.__ModuleLoader__.load({
955
1279
  const view = window.location.href;
956
1280
  submitting = true;
957
1281
  pending.current = true;
1282
+ setRequestPending(true);
958
1283
  let reconnect;
959
1284
  let restoreDraft = false;
1285
+ let deliveryUnknown = false;
960
1286
  let savedForRetry = false;
961
1287
  const inView = () => !lifetime.signal.aborted && window.location.href === view;
962
1288
  try {
@@ -968,6 +1294,7 @@ window.__ModuleLoader__.load({
968
1294
  toolbarRevision: 1, text, textParts, expectedRevision: edit.revision,
969
1295
  removedAttachments, receiptIds, ...edit.settings });
970
1296
  } catch (error) {
1297
+ deliveryUnknown = error.deliveryUnknown === true;
971
1298
  if (error.reconnect || reconnect.removed) {
972
1299
  restoreDraft = true;
973
1300
  await reconnect.reconnect().catch(() => {});
@@ -993,7 +1320,7 @@ window.__ModuleLoader__.load({
993
1320
  }
994
1321
  return { kind: 'success' };
995
1322
  } catch (error) {
996
- savedForRetry = !lifetime.signal.aborted && (restoreDraft || draft.current !== edit.composer);
1323
+ savedForRetry = !lifetime.signal.aborted && editableRef.current && (deliveryUnknown || restoreDraft || draft.current !== edit.composer);
997
1324
  if (savedForRetry && activeEditor === claim) dismiss(false);
998
1325
  if (inView()) notify(savedForRetry ? `${errorMessage(error)} ${t('draftSaved')}` : errorMessage(error));
999
1326
  return { kind: 'error' };
@@ -1003,7 +1330,8 @@ window.__ModuleLoader__.load({
1003
1330
  reconnect?.release();
1004
1331
  } finally {
1005
1332
  submitting = false;
1006
- if (savedForRetry) keepDraft(edit.key, { ...saved, reopenInView: inView() ? view : undefined });
1333
+ setRequestPending(false);
1334
+ if (savedForRetry) keepDraft(edit.key, { ...saved, reopenInView: inView() && (!deliveryUnknown || restoreDraft) ? view : undefined });
1007
1335
  }
1008
1336
  }
1009
1337
  }
@@ -1016,22 +1344,13 @@ window.__ModuleLoader__.load({
1016
1344
  onFocus: () => setTooltipDismissed(false),
1017
1345
  onPointerLeave: () => setTooltipDismissed(false),
1018
1346
  onKeyDown: event => { if (event.key === 'Escape') setTooltipDismissed(true); },
1019
- }, h(TablerIcon, { name: 'pencil' })),
1347
+ }, h(TablerIcon, { name: 'pencil', strokeWidth: 1.5 })),
1020
1348
  edit && renderFactorySlot(editorFactory, {
1021
- edit, dismiss, cancelLabel: t('cancel'), disabled: busy,
1349
+ edit, cancel, requestPending, cancelLabel: t('cancel'), disabled: busy,
1022
1350
  }));
1023
1351
  }
1024
1352
 
1025
1353
  ctx.effect(() => () => lifetime.abort());
1026
- ctx.inject(['sessions'], scoped => scoped.effect(() => {
1027
- const views = watchSessionViews(sessionRuntime(scoped));
1028
- sessionViews = views;
1029
- return () => {
1030
- if (sessionViews === views) sessionViews = undefined;
1031
- views?.dispose();
1032
- };
1033
- }));
1034
- ctx.effect(() => ctx.locale.register(locale, strings));
1035
1354
  // The same native child seats remain available to the registered native bar.
1036
1355
  const composerChildren = {
1037
1356
  'conversation.input.attachments': { kind: 'single', scope: 'session-maybe' },
@@ -1043,24 +1362,59 @@ window.__ModuleLoader__.load({
1043
1362
  'conversation.input.right': { kind: 'list', scope: 'session' },
1044
1363
  'conversation.composer.dock': { kind: 'list', scope: 'session' },
1045
1364
  };
1046
- ctx.slots.inject(composerSlot, () => {
1047
- // rc.5 registers and tears down only own child declarations, but the
1048
- // Factory renderer resolves their specs by lookup. Borrow the already
1049
- // live slots without owning them so unloading leaves the host intact.
1050
- const borrowedChildren = Object.freeze(Object.create(Object.freeze(composerChildren)));
1051
- const dispose = ctx.slots.registerFactory({
1052
- name: editorFactory, scope: 'session', locale: 'conversation', children: borrowedChildren,
1053
- }, NativeEditor);
1054
- composerFactoryLive = true;
1055
- return () => { composerFactoryLive = false; dispose(); };
1056
- });
1057
- ctx.slots.inject('shell.overlay', () => ctx.slots.register({
1058
- name: 'shell.overlay', id: 'message-revision.styles', locale,
1059
- }, props => h(Fragment, null, h('style', null, css), h(Feedback, props))));
1060
- ctx.slots.inject('conversation.chat.user.before', () => ctx.slots.register({
1061
- name: 'conversation.chat.user.before', locale, order: 10000,
1062
- select: ({ kind, source }) => kind === 'user' && source?.kind === 'user' ? source : null,
1063
- }, RevisionAction));
1365
+ // Only the Host owner can call /api/message-revision or watch revision events.
1366
+ ctx.inject(['remoteAccess'], accessScope => accessScope.remoteAccess.whenAccess(ownerAccessAction, function* () {
1367
+ const sessions = accessScope.inject(['sessions'], scoped => scoped.effect(() => {
1368
+ const views = watchSessionViews(sessionRuntime(scoped));
1369
+ setSessionViews(views);
1370
+ if (views) scoped.inject(['remote'], remoteScope => remoteScope.effect(async () => {
1371
+ await pendingUnmount.catch(() => {});
1372
+ if (lifetime.signal.aborted || sessionViews !== views) return undefined;
1373
+ const unmount = await remoteScope.remote.$mount(revisionEventsContribution);
1374
+ let subscription;
1375
+ try {
1376
+ subscription = remoteScope.inject([`remote.${revisionRemoteName}`], ready => ready.effect(() =>
1377
+ connectRevisionViews(views, ready.remote, (cursor, signal) => ready.remote[revisionRemoteName].watch(cursor, signal))));
1378
+ } catch (error) {
1379
+ const cleanup = Promise.resolve().then(() => unmount());
1380
+ pendingUnmount = cleanup;
1381
+ await cleanup;
1382
+ throw error;
1383
+ }
1384
+ return () => {
1385
+ const cleanup = (async () => {
1386
+ try { await subscription.dispose(); } finally { await unmount(); }
1387
+ })();
1388
+ pendingUnmount = cleanup;
1389
+ return cleanup;
1390
+ };
1391
+ }));
1392
+ return () => {
1393
+ if (sessionViews === views) setSessionViews(undefined);
1394
+ views?.dispose();
1395
+ };
1396
+ }));
1397
+ yield () => { void sessions.dispose(); };
1398
+ yield accessScope.locale.register(locale, strings);
1399
+ yield accessScope.slots.inject(composerSlot, () => {
1400
+ // rc.5 registers and tears down only own child declarations, but the
1401
+ // Factory renderer resolves their specs by lookup. Borrow the already
1402
+ // live slots without owning them so unloading leaves the host intact.
1403
+ const borrowedChildren = Object.freeze(Object.create(Object.freeze(composerChildren)));
1404
+ const dispose = accessScope.slots.registerFactory({
1405
+ name: editorFactory, scope: 'session', locale: 'conversation', children: borrowedChildren,
1406
+ }, NativeEditor);
1407
+ composerFactoryLive = true;
1408
+ return () => { composerFactoryLive = false; dispose(); };
1409
+ });
1410
+ yield accessScope.slots.inject('shell.overlay', () => accessScope.slots.register({
1411
+ name: 'shell.overlay', id: 'message-revision.styles', locale,
1412
+ }, props => h(Fragment, null, h('style', null, css), h(Feedback, props))));
1413
+ yield accessScope.slots.inject('conversation.chat.user.before', () => accessScope.slots.register({
1414
+ name: 'conversation.chat.user.before', locale, order: 10000,
1415
+ select: ({ kind, source }) => kind === 'user' && source?.kind === 'user' ? source : null,
1416
+ }, RevisionAction));
1417
+ }));
1064
1418
  },
1065
1419
  };
1066
1420
  },