odant-work 1.0.113 → 1.0.115

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.
@@ -144,11 +144,18 @@ ODA({
144
144
  if (WORK?.uid && !WORK._userSettingsLoaded && typeof WORK.loadUserSettings === 'function') {
145
145
  await WORK.loadUserSettings().catch(() => {});
146
146
  }
147
+ const chatModels = typeof WORK?.fetch === 'function'
148
+ ? await WORK.fetch('/', 'agent_chat_models').catch(() => null)
149
+ : null;
150
+ const validPaths = Array.isArray(chatModels) ? new Set(chatModels.map(m => m?.path).filter(Boolean)) : null;
147
151
  let userModel = getUserPreferredModel();
148
- if (userModel && typeof WORK?.get_item === 'function') {
149
- const existing = await WORK.get_item(userModel).catch(() => null);
150
- if (!existing || existing.type !== '$ai' || !isChatModel(existing)) {
151
- userModel = '';
152
+ if (userModel) {
153
+ if (validPaths) {
154
+ if (!validPaths.has(userModel)) userModel = '';
155
+ } else if (typeof WORK?.get_item === 'function') {
156
+ const existing = await WORK.get_item(userModel).catch(() => null);
157
+ if (!existing || existing.type !== '$ai' || !isChatModel(existing))
158
+ userModel = '';
152
159
  }
153
160
  }
154
161
  if (userModel) {
@@ -160,20 +167,11 @@ ODA({
160
167
  let path = '';
161
168
  if (typeof WORK?.fetch === 'function') {
162
169
  const srvDefault = await WORK.fetch('/', 'agent_default_model', { nodePath: this.$item?.path || '/' }).catch(() => '');
163
- if (typeof srvDefault === 'string' && srvDefault.startsWith('/')) {
164
- const check = await WORK.get_item(srvDefault).catch(() => null);
165
- if (check && isChatModel(check))
166
- path = srvDefault;
167
- }
170
+ if (typeof srvDefault === 'string' && srvDefault.startsWith('/'))
171
+ path = srvDefault;
168
172
  }
169
- if (!path) {
170
- const modelsPath = '/' + ['MODULES', 'Модели'].join('/');
171
- const modelsRoot = await WORK.get_item(modelsPath).catch(() => null);
172
- if (modelsRoot) {
173
- const tree = await modelsRoot.info({ deep: 2 });
174
- const leaf = await firstChatLeaf(tree);
175
- path = leaf?.path || '';
176
- }
173
+ if (!path && Array.isArray(chatModels) && chatModels.length) {
174
+ path = chatModels[0]?.path || '';
177
175
  }
178
176
  if (path) {
179
177
  this.model = path;
@@ -457,6 +455,37 @@ ODA({
457
455
  overflow: visible;
458
456
  padding-bottom: var(--safe-bottom, 0px);
459
457
  }
458
+ .composer-banner {
459
+ align-items: center;
460
+ gap: 8px;
461
+ padding: 6px 12px;
462
+ background: color-mix(in oklch, var(--accent-color, #4f46e5) 8%, var(--content-background, #fff));
463
+ border-bottom: 1px solid color-mix(in oklch, var(--accent-color, #4f46e5) 22%, transparent);
464
+ font-size: 12.5px;
465
+ }
466
+ .composer-banner .banner-icon {
467
+ color: var(--accent-color, #4f46e5);
468
+ flex-shrink: 0;
469
+ }
470
+ .composer-banner .banner-body {
471
+ min-width: 0;
472
+ border-left: 2.5px solid var(--accent-color, #4f46e5);
473
+ padding-left: 8px;
474
+ }
475
+ .composer-banner .banner-title {
476
+ font-weight: 700;
477
+ color: var(--accent-color, #4f46e5);
478
+ font-size: 12px;
479
+ overflow: hidden;
480
+ text-overflow: ellipsis;
481
+ white-space: nowrap;
482
+ }
483
+ .composer-banner .banner-text {
484
+ opacity: .78;
485
+ overflow: hidden;
486
+ text-overflow: ellipsis;
487
+ white-space: nowrap;
488
+ }
460
489
  @media (max-width: 768px) {
461
490
  .feed-top-bar {
462
491
  padding: 4px 8px;
@@ -499,18 +528,26 @@ ODA({
499
528
  }
500
529
  </style>
501
530
  <div class="back"></div>
502
- <chat-ribbon id="ribbon" :$item @chat-item-expanded="onCardExpanded($event)"></chat-ribbon>
531
+ <chat-ribbon id="ribbon" :$item
532
+ @chat-item-expanded="onCardExpanded($event)"
533
+ @chat-reply="onMessageReply($event)"
534
+ @chat-edit="onMessageEdit($event)"
535
+ @chat-delete="onMessageDelete($event)"
536
+ @chat-scroll-to-message="onScrollToMessage($event)"
537
+ @chat-retry-send="onRetrySend($event)"
538
+ @chat-dismiss-send="onDismissSend($event)"></chat-ribbon>
503
539
  <div class="mover" vertical hidden>
504
540
  <oda-button :hidden="$('#ribbon').scrollTop < 0" content shadow icon="icons:chevron-right:270" @tap="$('#ribbon').scrollTop = -($('#ribbon').scrollHeight)"></oda-button>
505
541
  <oda-button :hidden="$('#ribbon').scrollTop > 0" content shadow icon="icons:chevron-right:90" @tap="$('#ribbon').scrollTop = 0"></oda-button>
506
542
  </div>
507
543
  <div vertical shadow content :hidden="hasExpandedCard" class="chat-composer">
508
- <div ~if="replyTarget" horizontal accent-invert style="padding: 4px;">
509
- <div horizontal flex style="overflow: auto; align-self: center;"></div>
510
- <oda-button icon="icons:close" @tap="clear" style="padding: 0"></oda-button>
511
- </div>
512
- <div ~if="replyTarget" light vertical style="overflow-y: auto;" disabled>
513
- <chat-item reply :$file="replyTarget"></chat-item>
544
+ <div class="composer-banner" ~if="replyTarget || editingTarget" horizontal>
545
+ <oda-icon :icon="editingTarget ? 'icons:edit' : 'icons:reply'" :icon-size="16" class="banner-icon"></oda-icon>
546
+ <div class="banner-body" flex vertical>
547
+ <div class="banner-title">{{editingTarget ? 'Редактирование сообщения' : ('Ответ для ' + (replyTarget.senderLabel || 'собеседника'))}}</div>
548
+ <div class="banner-text">{{editingTarget ? editingTarget.content : replyTarget.previewText}}</div>
549
+ </div>
550
+ <oda-button icon="icons:close" :icon-size="16" @tap="cancelComposerMode" title="Отменить"></oda-button>
514
551
  </div>
515
552
  <microchat-voice ~if="voiceOn"></microchat-voice>
516
553
  <work-prompt-bar style="margin: 8px;" @tap="focusedItem = null"
@@ -545,6 +582,8 @@ ODA({
545
582
  return Boolean(this.$pdp?.isPrivate && this.$pdp?.$item?.id && WORK?.uid && this.$pdp.$item.id !== WORK.uid);
546
583
  },
547
584
  get placeholder() {
585
+ if (this.editingTarget)
586
+ return 'Редактировать сообщение ...';
548
587
  if (this.isForeignPrivate) {
549
588
  const lbl = this.$pdp.$item?.DATA?.label || this.$pdp.$item?.label || 'пользователя';
550
589
  return 'Сообщение для ' + lbl + ' ...';
@@ -627,10 +666,96 @@ ODA({
627
666
  this.value = '';
628
667
  this.files = [];
629
668
  this.$pdp.replyTarget = null;
669
+ this.editingTarget = null;
630
670
  this.$pdp.files = [];
631
671
  this.$('#ribbon').lastIdxHistory = -1;
632
672
  this.focusInput();
633
673
  },
674
+ editingTarget: null,
675
+ cancelComposerMode() {
676
+ const wasEdit = Boolean(this.editingTarget);
677
+ this.editingTarget = null;
678
+ this.$pdp.replyTarget = null;
679
+ if (wasEdit)
680
+ this.value = '';
681
+ this.focusInput();
682
+ },
683
+ onMessageReply(e) {
684
+ const d = e?.detail;
685
+ const cm = d?.message;
686
+ if (!cm?.id) return;
687
+ this.editingTarget = null;
688
+ const previewText = String(d.content || '').trim() || (d.attachments?.length ? `Вложение (${d.attachments.length})` : 'Сообщение');
689
+ this.$pdp.replyTarget = {
690
+ id: Number(cm.id),
691
+ sender: cm.sender || d.senderId || '',
692
+ senderLabel: d.senderLabel || cm.sender || 'Собеседник',
693
+ kind: cm.kind || 'text',
694
+ content: previewText,
695
+ previewText,
696
+ attachmentsCount: Array.isArray(d.attachments) ? d.attachments.length : (cm.attachments?.length || 0),
697
+ };
698
+ this.focusInput();
699
+ },
700
+ onMessageEdit(e) {
701
+ const d = e?.detail;
702
+ const cm = d?.message;
703
+ if (!cm?.id) return;
704
+ this.$pdp.replyTarget = null;
705
+ this.editingTarget = {
706
+ id: Number(cm.id),
707
+ threadId: cm.threadId || this.$('#ribbon')?._threadId || '',
708
+ content: String(d.content ?? cm.content ?? ''),
709
+ };
710
+ this.value = this.editingTarget.content;
711
+ this.focusInput();
712
+ },
713
+ async onMessageDelete(e) {
714
+ const d = e?.detail;
715
+ const cm = d?.message;
716
+ const threadId = cm?.threadId || this.$('#ribbon')?._threadId || '';
717
+ const ribbon = this.$('#ribbon');
718
+ if (!cm?.id) return;
719
+ if (cm.meta?.pending || cm.meta?.sendError) {
720
+ ribbon?.removeOptimisticByNonce?.(cm.meta?.clientNonce);
721
+ return;
722
+ }
723
+ if (!threadId || !this.$item?.fetch) return;
724
+ if (typeof WORK?.showConfirm === 'function') {
725
+ try {
726
+ await WORK.showConfirm('Удалить это сообщение?');
727
+ } catch {
728
+ return;
729
+ }
730
+ }
731
+ try {
732
+ await this.$item.fetch('chat_delete', {}, JSON.stringify({ threadId, messageId: Number(cm.id) }));
733
+ ribbon?.applyDeletedMessage?.(Number(cm.id));
734
+ } catch (err) {
735
+ ODA.showMessage?.('Не удалось удалить: ' + (err?.message || err));
736
+ }
737
+ },
738
+ onScrollToMessage(e) {
739
+ const msgId = Number(e?.detail?.messageId);
740
+ if (!msgId) return;
741
+ this.$('#ribbon')?.scrollToMessage?.(msgId);
742
+ },
743
+ async onRetrySend(e) {
744
+ const d = e?.detail;
745
+ const cm = d?.message;
746
+ const nonce = cm?.meta?.clientNonce;
747
+ const retryDraft = cm?.meta?.retryDraft;
748
+ if (!nonce || !retryDraft) return;
749
+ this.$('#ribbon')?.removeOptimisticByNonce?.(nonce);
750
+ this.value = retryDraft.value || '';
751
+ this.files = retryDraft.files || [];
752
+ this.$pdp.replyTarget = retryDraft.reply || null;
753
+ await this.send();
754
+ },
755
+ onDismissSend(e) {
756
+ const nonce = e?.detail?.message?.meta?.clientNonce;
757
+ if (nonce) this.$('#ribbon')?.removeOptimisticByNonce?.(nonce);
758
+ },
634
759
  $public: {
635
760
  showDatePanel: {
636
761
  $def: false,
@@ -683,7 +808,10 @@ ODA({
683
808
  detached() {
684
809
  if (this._onWsChatMsg && globalThis.WORK?.chatEvents) {
685
810
  globalThis.WORK.chatEvents.removeEventListener('chat:message', this._onWsChatMsg);
811
+ globalThis.WORK.chatEvents.removeEventListener('chat:edit', this._onWsChatMsg);
812
+ globalThis.WORK.chatEvents.removeEventListener('chat:delete', this._onWsChatMsg);
686
813
  globalThis.WORK.chatEvents.removeEventListener('chat:action', this._onWsChatMsg);
814
+ globalThis.WORK.chatEvents.removeEventListener('chat:read', this._onWsChatMsg);
687
815
  globalThis.WORK.chatEvents.removeEventListener('task.moved', this._onWsTaskMoved);
688
816
  this._onWsChatMsg = null;
689
817
  this._onWsTaskMoved = null;
@@ -766,20 +894,60 @@ ODA({
766
894
  await ribbon.refreshDates?.(true);
767
895
  await this._openCreated(path);
768
896
  },
897
+ _matchesChatEvent(d) {
898
+ const cur = this.$item;
899
+ if (!d || !cur) return false;
900
+ const curPath = String(cur.path || '/').replace(/\/+$/, '') || '/';
901
+ if (d.kind === 'twin')
902
+ return d.nodePath === curPath;
903
+ if (d.kind === 'dm' && cur.type === '$user') {
904
+ const ribId = this.$('#ribbon')?._threadId;
905
+ if (ribId && d.threadId)
906
+ return d.threadId === ribId;
907
+ if (d.threadId && String(d.threadId).startsWith('dm:')) {
908
+ const parts = String(d.threadId).slice(3).split('|');
909
+ if (parts.length === 2) {
910
+ if (cur.id === WORK.uid)
911
+ return parts[0] === WORK.uid && parts[1] === WORK.uid;
912
+ return parts.includes(cur.id) && parts.includes(WORK.uid);
913
+ }
914
+ }
915
+ return d.message?.sender === cur.id || d.message?.sender === WORK.uid;
916
+ }
917
+ return Boolean(d.threadId && this.$('#ribbon')?._threadId === d.threadId);
918
+ },
769
919
  _bindChatSocket() {
770
920
  if (this._onWsChatMsg) return;
771
921
  globalThis.WORK.chatEvents ??= new EventTarget();
772
922
  this._onWsChatMsg = ev => {
773
923
  const d = ev?.detail;
774
924
  const cur = this.$item;
775
- if (!d || !cur) return;
925
+ if (!d || !cur || !this._matchesChatEvent(d)) return;
926
+ const ribbon = this.$('#ribbon');
776
927
  const curPath = String(cur.path || '/').replace(/\/+$/, '') || '/';
777
- const hitTwin = d.kind === 'twin' && d.nodePath === curPath;
778
- const hitDm = d.kind === 'dm' && cur.type === '$user' && (d.message?.sender === cur.id || d.message?.sender === WORK.uid);
779
- const hitThread = d.threadId && this.$('#ribbon')?._threadId === d.threadId;
780
- if (hitTwin || hitDm || hitThread) {
781
- this.$('#ribbon')?.refreshFeed?.();
782
- if (d.threadId && ev.type === 'chat:message') {
928
+ if (ev.type === 'chat:read') {
929
+ if (d.uid && d.uid !== WORK.uid && d.lastReadId != null)
930
+ ribbon?.applyPeerRead?.(d.lastReadId);
931
+ return;
932
+ }
933
+ if (ev.type === 'chat:delete') {
934
+ if (d.messageId != null)
935
+ ribbon?.applyDeletedMessage?.(d.messageId);
936
+ return;
937
+ }
938
+ if (ev.type === 'chat:edit' || ev.type === 'chat:action') {
939
+ if (d.message)
940
+ ribbon?.applyUpdatedMessage?.(d.message);
941
+ else
942
+ ribbon?.refreshFeed?.();
943
+ return;
944
+ }
945
+ if (ev.type === 'chat:message') {
946
+ if (d.message)
947
+ ribbon?.applyIncomingMessage?.(d.message, d.threadId);
948
+ else
949
+ ribbon?.refreshFeed?.();
950
+ if (d.threadId && d.message?.sender !== WORK.uid) {
783
951
  cur.fetch?.('chat_mark_read', {
784
952
  threadId: d.threadId
785
953
  })?.then?.(res => WORK.applyChatReadLocal?.(res || {
@@ -792,7 +960,10 @@ ODA({
792
960
  }
793
961
  };
794
962
  globalThis.WORK.chatEvents.addEventListener('chat:message', this._onWsChatMsg);
963
+ globalThis.WORK.chatEvents.addEventListener('chat:edit', this._onWsChatMsg);
964
+ globalThis.WORK.chatEvents.addEventListener('chat:delete', this._onWsChatMsg);
795
965
  globalThis.WORK.chatEvents.addEventListener('chat:action', this._onWsChatMsg);
966
+ globalThis.WORK.chatEvents.addEventListener('chat:read', this._onWsChatMsg);
796
967
  },
797
968
  focusInput() {
798
969
  this.$('work-prompt-bar')?.focusInput();
@@ -1046,10 +1217,33 @@ ODA({
1046
1217
  async send() {
1047
1218
  // Один send за раз: повторные Enter/клики игнорируются, иначе каждый клик создаст свою задачу-дубликат.
1048
1219
  if (this._sending) return;
1220
+ const ribbon = this.$('#ribbon');
1221
+ if (this.editingTarget) {
1222
+ const nextText = String(this.value ?? '').trim();
1223
+ if (!nextText) return;
1224
+ const editInfo = { ...this.editingTarget };
1225
+ this._sending = true;
1226
+ try {
1227
+ const res = await this.$item?.fetch?.('chat_edit', {}, JSON.stringify({
1228
+ threadId: editInfo.threadId || ribbon?._threadId || '',
1229
+ messageId: editInfo.id,
1230
+ message: nextText,
1231
+ }));
1232
+ if (res?.message)
1233
+ ribbon?.applyUpdatedMessage?.(res.message);
1234
+ this.editingTarget = null;
1235
+ this.clear();
1236
+ } catch (err) {
1237
+ ODA.showMessage?.('Не удалось изменить сообщение: ' + (err?.message || err));
1238
+ } finally {
1239
+ this._sending = false;
1240
+ }
1241
+ return;
1242
+ }
1049
1243
  const files = this.$('work-prompt-bar')?.files ?? this.files;
1050
1244
  if (!(this.value || files.length)) return;
1051
1245
  chatDebug('send: клик');
1052
- this.$('#ribbon').scrollDown = true;
1246
+ if (ribbon) ribbon.scrollDown = true;
1053
1247
  const text = String(this.value ?? '').trim();
1054
1248
  const list = [...files];
1055
1249
  // Черновик на случай сбоя: поле очищается до сохранения — при ошибке вернуть текст и вложения.
@@ -1068,107 +1262,153 @@ ODA({
1068
1262
  files: list,
1069
1263
  draft
1070
1264
  });
1071
- } else if (this.isForeignPrivate) {
1072
- const uploadedPaths = [];
1073
- if (list.length) {
1074
- const uploadTarget = (await this._ownCabinet()) || this.$pdp.$item;
1075
- const formData = new FormData();
1076
- for (const file of list) formData.append('file', file, file.name);
1077
- const fileParams = {
1078
- encoding: 'utf-8',
1079
- ...(WORK.uid ? { sender: WORK.uid } : {}),
1080
- ignore_save_logs: true
1081
- };
1082
- const savedLogs = await uploadTarget.save_files(formData, fileParams);
1083
- const arr = Array.isArray(savedLogs) ? savedLogs : savedLogs ? [savedLogs] : [];
1084
- for (const l of arr) {
1085
- const p = await pathOfLog(l);
1086
- if (p) uploadedPaths.push(p.startsWith('/') ? p : '/' + p);
1087
- }
1088
- }
1089
- const chatTarget = this.$pdp.$item;
1090
- if (chatTarget?.fetch && (text || uploadedPaths.length)) {
1091
- const chatPayload = {
1092
- kind: 'dm',
1093
- peerId: chatTarget.id,
1094
- message: text,
1095
- attachments: uploadedPaths.map(p => ({
1096
- path: p,
1097
- name: p.split('/').pop() || 'file'
1098
- }))
1099
- };
1100
- await chatTarget.fetch('chat_send', {}, JSON.stringify(chatPayload));
1101
- }
1102
- this.clear();
1103
- this.$('#ribbon')?.refreshFeed?.();
1104
1265
  } else {
1105
- const params = {
1106
- encoding: 'utf-8'
1107
- };
1108
- if (WORK.uid) params.sender = WORK.uid;
1109
- if (this.$pdp.isPrivate && this.$pdp.$item.id !== WORK.uid) params.receivers = [this.$pdp.$item.id];else if (this.$pdp.receivers.length) params.receivers = this.$pdp.receivers.map(u => u.id);
1110
- const uploadedPaths = [];
1111
- const isForeignDm = Boolean(this.$pdp.isPrivate && this.$pdp.$item?.id && this.$pdp.$item.id !== WORK.uid);
1112
- const runWrite = typeof this._runWithCabinetFallback === 'function' ? fn => this._runWithCabinetFallback(fn) : async fn => ({
1113
- target: this.$pdp.$item,
1114
- result: await fn(this.$pdp.$item)
1266
+ const reply = draft.reply;
1267
+ const replyTo = reply?.id ? Number(reply.id) : null;
1268
+ const replyPreview = reply?.id ? {
1269
+ id: Number(reply.id),
1270
+ sender: reply.sender || '',
1271
+ senderLabel: reply.senderLabel || reply.sender || '',
1272
+ kind: reply.kind || 'text',
1273
+ content: String(reply.previewText || reply.content || '').slice(0, 180),
1274
+ attachmentsCount: Number(reply.attachmentsCount) || 0,
1275
+ } : null;
1276
+ const clientNonce = `tmp_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`;
1277
+ const isPrivate = Boolean(this.$pdp.isPrivate);
1278
+ const isForeignDm = Boolean(isPrivate && this.$pdp.$item?.id && this.$pdp.$item.id !== WORK.uid);
1279
+
1280
+ this.clear();
1281
+ ribbon?.addOptimisticMessage?.({
1282
+ clientNonce,
1283
+ sender: WORK.uid,
1284
+ content: text,
1285
+ attachments: list.map(f => ({ path: '', name: f.name })),
1286
+ replyTo,
1287
+ replyPreview,
1288
+ created: Date.now(),
1115
1289
  });
1116
- await runWrite(async target => {
1117
- uploadedPaths.length = 0;
1118
- const uploadTarget = isForeignDm ? (await this._ownCabinet()) || target : target;
1119
- if (list.length) {
1120
- const formData = new FormData();
1121
- for (const file of list) formData.append('file', file, file.name);
1122
- const fileParams = text || isForeignDm ? {
1123
- ...params,
1124
- ignore_save_logs: true
1125
- } : params;
1126
- const savedLogs = await uploadTarget.save_files(formData, fileParams);
1127
- const arr = Array.isArray(savedLogs) ? savedLogs : savedLogs ? [savedLogs] : [];
1128
- for (const l of arr) {
1129
- const p = await pathOfLog(l);
1130
- if (p) uploadedPaths.push(p.startsWith('/') ? p : '/' + p);
1290
+
1291
+ try {
1292
+ if (this.isForeignPrivate) {
1293
+ const uploadedPaths = [];
1294
+ if (list.length) {
1295
+ const uploadTarget = (await this._ownCabinet()) || this.$pdp.$item;
1296
+ const formData = new FormData();
1297
+ for (const file of list) formData.append('file', file, file.name);
1298
+ const fileParams = {
1299
+ encoding: 'utf-8',
1300
+ ...(WORK.uid ? { sender: WORK.uid } : {}),
1301
+ ignore_save_logs: true
1302
+ };
1303
+ const savedLogs = await uploadTarget.save_files(formData, fileParams);
1304
+ const arr = Array.isArray(savedLogs) ? savedLogs : savedLogs ? [savedLogs] : [];
1305
+ for (const l of arr) {
1306
+ const p = await pathOfLog(l);
1307
+ if (p) uploadedPaths.push(p.startsWith('/') ? p : '/' + p);
1308
+ }
1131
1309
  }
1132
- }
1133
- if (text && !isForeignDm) {
1134
- const msgParams = {
1135
- ...params,
1136
- message: text
1137
- };
1138
- if (uploadedPaths.length) msgParams.includes = JSON.stringify(uploadedPaths);
1139
- await target.fetch('save_message', msgParams);
1140
- }
1141
- const chatTarget = this.$pdp.$item || target;
1142
- if (chatTarget?.fetch && (text || uploadedPaths.length)) {
1143
- const chatPayload = {
1144
- kind: this.$pdp.isPrivate ? 'dm' : 'twin',
1145
- ...(this.$pdp.isPrivate ? {
1146
- peerId: this.$pdp.$item?.id || WORK.uid
1147
- } : {}),
1148
- message: text,
1149
- attachments: uploadedPaths.map(p => ({
1150
- path: p,
1151
- name: p.split('/').pop() || 'file'
1152
- }))
1310
+ const chatTarget = this.$pdp.$item;
1311
+ let savedMsg = null;
1312
+ if (chatTarget?.fetch && (text || uploadedPaths.length)) {
1313
+ const chatPayload = {
1314
+ kind: 'dm',
1315
+ peerId: chatTarget.id,
1316
+ message: text,
1317
+ ...(replyTo ? { replyTo } : {}),
1318
+ meta: { clientNonce, ...(replyPreview ? { replyPreview } : {}) },
1319
+ attachments: uploadedPaths.map(p => ({
1320
+ path: p,
1321
+ name: p.split('/').pop() || 'file'
1322
+ }))
1323
+ };
1324
+ savedMsg = await chatTarget.fetch('chat_send', {}, JSON.stringify(chatPayload));
1325
+ }
1326
+ if (savedMsg?.id)
1327
+ ribbon?.resolveOptimisticMessage?.(clientNonce, savedMsg);
1328
+ else
1329
+ ribbon?.removeOptimisticByNonce?.(clientNonce);
1330
+ } else {
1331
+ const params = {
1332
+ encoding: 'utf-8'
1153
1333
  };
1154
- await chatTarget.fetch('chat_send', {}, JSON.stringify(chatPayload))?.catch?.(() => {});
1334
+ if (WORK.uid) params.sender = WORK.uid;
1335
+ if (isPrivate && this.$pdp.$item.id !== WORK.uid) params.receivers = [this.$pdp.$item.id];
1336
+ else if (this.$pdp.receivers.length) params.receivers = this.$pdp.receivers.map(u => u.id);
1337
+ const uploadedPaths = [];
1338
+ const runWrite = typeof this._runWithCabinetFallback === 'function' ? fn => this._runWithCabinetFallback(fn) : async fn => ({
1339
+ target: this.$pdp.$item,
1340
+ result: await fn(this.$pdp.$item)
1341
+ });
1342
+ let savedMsg = null;
1343
+ await runWrite(async target => {
1344
+ uploadedPaths.length = 0;
1345
+ const uploadTarget = isForeignDm ? (await this._ownCabinet()) || target : target;
1346
+ if (list.length) {
1347
+ const formData = new FormData();
1348
+ for (const file of list) formData.append('file', file, file.name);
1349
+ const fileParams = (text || isPrivate) ? {
1350
+ ...params,
1351
+ ignore_save_logs: true
1352
+ } : params;
1353
+ const savedLogs = await uploadTarget.save_files(formData, fileParams);
1354
+ const arr = Array.isArray(savedLogs) ? savedLogs : savedLogs ? [savedLogs] : [];
1355
+ for (const l of arr) {
1356
+ const p = await pathOfLog(l);
1357
+ if (p) uploadedPaths.push(p.startsWith('/') ? p : '/' + p);
1358
+ }
1359
+ }
1360
+ if (text && !isPrivate) {
1361
+ const msgParams = {
1362
+ ...params,
1363
+ message: text
1364
+ };
1365
+ if (uploadedPaths.length) msgParams.includes = JSON.stringify(uploadedPaths);
1366
+ await target.fetch('save_message', msgParams);
1367
+ }
1368
+ const chatTarget = this.$pdp.$item || target;
1369
+ if (chatTarget?.fetch && (text || uploadedPaths.length)) {
1370
+ const chatPayload = {
1371
+ kind: isPrivate ? 'dm' : 'twin',
1372
+ ...(isPrivate ? {
1373
+ peerId: this.$pdp.$item?.id || WORK.uid
1374
+ } : {}),
1375
+ message: text,
1376
+ ...(replyTo ? { replyTo } : {}),
1377
+ meta: { clientNonce, ...(replyPreview ? { replyPreview } : {}) },
1378
+ attachments: uploadedPaths.map(p => ({
1379
+ path: p,
1380
+ name: p.split('/').pop() || 'file'
1381
+ }))
1382
+ };
1383
+ savedMsg = await chatTarget.fetch('chat_send', {}, JSON.stringify(chatPayload));
1384
+ }
1385
+ });
1386
+ if (savedMsg?.id)
1387
+ ribbon?.resolveOptimisticMessage?.(clientNonce, savedMsg);
1388
+ else
1389
+ ribbon?.removeOptimisticByNonce?.(clientNonce);
1155
1390
  }
1156
- });
1157
- this.clear();
1158
- this.$('#ribbon')?.refreshFeed?.();
1391
+ } catch (sendErr) {
1392
+ ribbon?.markOptimisticError?.(clientNonce, sendErr?.message || String(sendErr), draft);
1393
+ throw sendErr;
1394
+ }
1159
1395
  }
1160
1396
  } catch (err) {
1161
1397
  console.warn('[chat] send', err);
1162
- // Сбой — черновик не теряем: текст и вложения обратно в поле.
1163
- this.value = draft.value;
1164
- this.files = draft.files;
1165
- this.$pdp.replyTarget = draft.reply;
1166
- ODA.showMessage?.('Не удалось отправить: ' + (err?.message || err));
1167
- this.focusInput();
1398
+ if (!this.isAIMode && ribbon?._hasOptimisticNonce?.()) {
1399
+ ODA.showMessage?.('Не удалось отправить: ' + (err?.message || err));
1400
+ } else {
1401
+ // Сбой до вставки — черновик возвращаем в поле.
1402
+ this.value = draft.value;
1403
+ this.files = draft.files;
1404
+ this.$pdp.replyTarget = draft.reply;
1405
+ ODA.showMessage?.('Не удалось отправить: ' + (err?.message || err));
1406
+ this.focusInput();
1407
+ }
1168
1408
  } finally {
1169
1409
  this._sending = false;
1170
1410
  }
1171
- this.$('#ribbon').scrollDown = true;
1411
+ if (ribbon) ribbon.scrollDown = true;
1172
1412
  },
1173
1413
  _collectKnownLogKeys() {
1174
1414
  const ribbon = this.$('#ribbon');
@@ -1656,6 +1896,9 @@ ODA({
1656
1896
  get isLocalFeed() {
1657
1897
  return this.$pdp?.feedMode === 'local';
1658
1898
  },
1899
+ get isPrivateFeed() {
1900
+ return Boolean(this.$pdp?.isPrivate || this.$item?.DATA?.isUser);
1901
+ },
1659
1902
  get isForeignUser() {
1660
1903
  return Boolean(this.$pdp?.isPrivate && this.$item?.id && WORK?.uid && this.$item.id !== WORK.uid);
1661
1904
  },
@@ -1663,6 +1906,7 @@ ODA({
1663
1906
  return !this.isLocalFeed && this.$pdp?.feedMode !== 'audit';
1664
1907
  },
1665
1908
  _threadId: '',
1909
+ _peerLastReadId: 0,
1666
1910
  _threadMessages: [],
1667
1911
  _threadMessagesByDay: null,
1668
1912
  _localDayOf(ms) {
@@ -1677,6 +1921,187 @@ ODA({
1677
1921
  if (!day || !(this._threadMessagesByDay instanceof Map)) return [];
1678
1922
  return this._threadMessagesByDay.get(day) || [];
1679
1923
  },
1924
+ _syncThreadByDay() {
1925
+ const byDay = new Map();
1926
+ for (const msg of this._threadMessages || []) {
1927
+ const d = this._localDayOf(msg.created);
1928
+ if (!d) continue;
1929
+ let arr = byDay.get(d);
1930
+ if (!arr) {
1931
+ arr = [];
1932
+ byDay.set(d, arr);
1933
+ }
1934
+ arr.push(msg);
1935
+ }
1936
+ this._threadMessagesByDay = byDay;
1937
+ return byDay;
1938
+ },
1939
+ _hasOptimisticNonce() {
1940
+ return (this._threadMessages || []).some(m => m?.meta?.clientNonce && m?.meta?.sendError);
1941
+ },
1942
+ addOptimisticMessage({ clientNonce, sender, content, attachments = [], replyTo = null, replyPreview = null, created = Date.now() }) {
1943
+ const tmpId = -Math.floor(Date.now() + Math.random() * 1000);
1944
+ const msg = {
1945
+ id: tmpId,
1946
+ threadId: this._threadId || '',
1947
+ sender: sender || WORK.uid || '',
1948
+ kind: 'text',
1949
+ content: String(content || ''),
1950
+ replyTo,
1951
+ attachments,
1952
+ meta: {
1953
+ pending: true,
1954
+ clientNonce,
1955
+ ...(replyPreview ? { replyPreview } : {}),
1956
+ },
1957
+ created,
1958
+ };
1959
+ this.applyIncomingMessage(msg, this._threadId);
1960
+ return msg;
1961
+ },
1962
+ resolveOptimisticMessage(clientNonce, saved) {
1963
+ if (!saved) return;
1964
+ const list = Array.isArray(this._threadMessages) ? [...this._threadMessages] : [];
1965
+ const optIdx = clientNonce ? list.findIndex(m => m?.meta?.clientNonce === clientNonce) : -1;
1966
+ const dupIdx = list.findIndex(m => Number(m?.id) === Number(saved.id));
1967
+ if (optIdx >= 0 && dupIdx >= 0 && optIdx !== dupIdx) {
1968
+ list.splice(optIdx, 1);
1969
+ } else if (optIdx >= 0) {
1970
+ list[optIdx] = saved;
1971
+ } else if (dupIdx >= 0) {
1972
+ list[dupIdx] = saved;
1973
+ } else {
1974
+ list.push(saved);
1975
+ }
1976
+ this._threadMessages = list;
1977
+ if (saved.threadId) this._threadId = saved.threadId;
1978
+ this._syncThreadByDay();
1979
+ const day = this._localDayOf(saved.created);
1980
+ if (day && !this.dateList.includes(day)) {
1981
+ this.dateList = [...this.dateList, day].sort();
1982
+ this.render();
1983
+ }
1984
+ const dayEl = [...(this.$$('chat-day') || [])].find(d => d.day === day);
1985
+ if (dayEl)
1986
+ dayEl.replaceOptimisticMessage?.(clientNonce, saved);
1987
+ },
1988
+ removeOptimisticByNonce(clientNonce) {
1989
+ if (!clientNonce) return;
1990
+ const prev = Array.isArray(this._threadMessages) ? this._threadMessages : [];
1991
+ const next = prev.filter(m => m?.meta?.clientNonce !== clientNonce);
1992
+ if (next.length === prev.length) return;
1993
+ this._threadMessages = next;
1994
+ this._syncThreadByDay();
1995
+ for (const dayEl of this.$$('chat-day') || []) {
1996
+ dayEl.removeOptimisticByNonce?.(clientNonce);
1997
+ }
1998
+ },
1999
+ markOptimisticError(clientNonce, errText, retryDraft) {
2000
+ if (!clientNonce) return;
2001
+ const list = Array.isArray(this._threadMessages) ? this._threadMessages : [];
2002
+ const target = list.find(m => m?.meta?.clientNonce === clientNonce);
2003
+ if (!target) return;
2004
+ const updated = {
2005
+ ...target,
2006
+ meta: {
2007
+ ...(target.meta || {}),
2008
+ pending: false,
2009
+ sendError: String(errText || 'Ошибка отправки'),
2010
+ retryDraft,
2011
+ },
2012
+ };
2013
+ const idx = list.indexOf(target);
2014
+ list[idx] = updated;
2015
+ this._threadMessages = [...list];
2016
+ this._syncThreadByDay();
2017
+ const day = this._localDayOf(updated.created);
2018
+ const dayEl = [...(this.$$('chat-day') || [])].find(d => d.day === day);
2019
+ dayEl?.upsertThreadMessage?.(updated);
2020
+ },
2021
+ applyIncomingMessage(msg, threadId = '') {
2022
+ if (!msg) return;
2023
+ if (threadId && !this._threadId) this._threadId = threadId;
2024
+ const nonce = msg.meta?.clientNonce;
2025
+ const list = Array.isArray(this._threadMessages) ? [...this._threadMessages] : [];
2026
+ const byIdIdx = msg.id != null ? list.findIndex(m => Number(m?.id) === Number(msg.id)) : -1;
2027
+ const byNonceIdx = nonce ? list.findIndex(m => m?.meta?.clientNonce === nonce) : -1;
2028
+ if (byIdIdx >= 0) {
2029
+ list[byIdIdx] = msg;
2030
+ if (byNonceIdx >= 0 && byNonceIdx !== byIdIdx) list.splice(byNonceIdx, 1);
2031
+ } else if (byNonceIdx >= 0) {
2032
+ list[byNonceIdx] = msg;
2033
+ } else {
2034
+ list.push(msg);
2035
+ }
2036
+ this._threadMessages = list;
2037
+ this._syncThreadByDay();
2038
+ const day = this._localDayOf(msg.created || Date.now());
2039
+ if (day && !this.dateList.includes(day)) {
2040
+ this.dateList = [...this.dateList, day].sort();
2041
+ this.render();
2042
+ }
2043
+ const dayEl = [...(this.$$('chat-day') || [])].find(d => d.day === day);
2044
+ if (dayEl) {
2045
+ if (nonce && byNonceIdx >= 0)
2046
+ dayEl.replaceOptimisticMessage?.(nonce, msg);
2047
+ else
2048
+ dayEl.upsertThreadMessage?.(msg);
2049
+ }
2050
+ this.scrollDown = true;
2051
+ this.async(() => {
2052
+ if (this.scrollDown) {
2053
+ this._savedScrollTop = 0;
2054
+ this.scrollTop = 0;
2055
+ }
2056
+ }, 10);
2057
+ },
2058
+ applyUpdatedMessage(msg) {
2059
+ if (!msg?.id) return;
2060
+ const list = Array.isArray(this._threadMessages) ? [...this._threadMessages] : [];
2061
+ const idx = list.findIndex(m => Number(m?.id) === Number(msg.id));
2062
+ if (idx >= 0) {
2063
+ list[idx] = msg;
2064
+ this._threadMessages = list;
2065
+ this._syncThreadByDay();
2066
+ }
2067
+ const day = this._localDayOf(msg.created || Date.now());
2068
+ const dayEl = [...(this.$$('chat-day') || [])].find(d => d.day === day) || [...(this.$$('chat-day') || [])].find(d => d._wrappedById?.has(`chatmsg.${msg.id}.msg`));
2069
+ dayEl?.upsertThreadMessage?.(msg);
2070
+ },
2071
+ applyDeletedMessage(messageId) {
2072
+ const idNum = Number(messageId);
2073
+ if (!idNum) return;
2074
+ this._threadMessages = (this._threadMessages || []).filter(m => Number(m?.id) !== idNum);
2075
+ this._syncThreadByDay();
2076
+ for (const dayEl of this.$$('chat-day') || []) {
2077
+ dayEl.removeThreadMessage?.(idNum);
2078
+ }
2079
+ },
2080
+ applyPeerRead(lastReadId) {
2081
+ const next = Math.max(Number(this._peerLastReadId) || 0, Number(lastReadId) || 0);
2082
+ if (next <= (this._peerLastReadId || 0)) return;
2083
+ this._peerLastReadId = next;
2084
+ for (const dayEl of this.$$('chat-day') || []) {
2085
+ dayEl.peerLastReadId = next;
2086
+ for (const ci of dayEl.$$?.('chat-item') || []) {
2087
+ ci.peerLastReadId = next;
2088
+ ci.invalidate?.('isReadByPeer');
2089
+ ci.render?.();
2090
+ }
2091
+ }
2092
+ },
2093
+ scrollToMessage(messageId) {
2094
+ const targetId = `chatmsg.${Number(messageId)}.msg`;
2095
+ for (const dayEl of this.$$('chat-day') || []) {
2096
+ const card = [...(dayEl.$$?.('chat-item') || [])].find(ci => ci.$item?.id === targetId || ci.cmId === Number(messageId));
2097
+ if (card) {
2098
+ if (!dayEl.expanded) dayEl.expanded = true;
2099
+ card.scrollIntoView?.({ behavior: 'smooth', block: 'center' });
2100
+ card.flashHighlight?.();
2101
+ return;
2102
+ }
2103
+ }
2104
+ },
1680
2105
  async _resolveLogsSource() {
1681
2106
  return this.$item || null;
1682
2107
  },
@@ -1687,11 +2112,12 @@ ODA({
1687
2112
  if (source && source !== this.$item) source.listen?.('changed', this.onChanged);
1688
2113
  },
1689
2114
  async refreshFeed() {
1690
- this.dateList = [];
1691
2115
  await this.refreshDates(true);
1692
2116
  for (const dayEl of this.$$('chat-day') || []) {
1693
- dayEl._logsInit = false;
1694
- dayEl._ensureLogsInit?.();
2117
+ if (dayEl._logsInit)
2118
+ dayEl._onLogsChangedRun?.();
2119
+ else
2120
+ dayEl._ensureLogsInit?.();
1695
2121
  }
1696
2122
  },
1697
2123
  async refreshDates(force = false) {
@@ -1728,9 +2154,18 @@ ODA({
1728
2154
  const dateSet = new Set((Array.isArray(rawDates) ? rawDates : []).slice().reverse());
1729
2155
  const byDay = new Map();
1730
2156
  const msgs = Array.isArray(threadRes?.messages) ? threadRes.messages : [];
2157
+ const pendingOpt = (this._threadMessages || []).filter(m => m?.meta?.clientNonce && (m?.meta?.pending || m?.meta?.sendError));
1731
2158
  this._threadId = threadRes?.thread?.id || '';
1732
- this._threadMessages = msgs;
1733
- for (const msg of msgs) {
2159
+ const parts = Array.isArray(threadRes?.thread?.participants) ? threadRes.thread.participants : [];
2160
+ const peerReads = parts.filter(p => p?.uid && (this.$item.id === WORK.uid ? p.uid === WORK.uid : p.uid !== WORK.uid)).map(p => Number(p.lastReadId) || 0);
2161
+ this._peerLastReadId = peerReads.length ? Math.max(...peerReads) : 0;
2162
+ const mergedMsgs = [...msgs];
2163
+ for (const opt of pendingOpt) {
2164
+ if (!mergedMsgs.some(m => m?.meta?.clientNonce === opt.meta.clientNonce))
2165
+ mergedMsgs.push(opt);
2166
+ }
2167
+ this._threadMessages = mergedMsgs;
2168
+ for (const msg of mergedMsgs) {
1734
2169
  const d = this._localDayOf(msg.created);
1735
2170
  if (!d) continue;
1736
2171
  dateSet.add(d);
@@ -1770,6 +2205,11 @@ ODA({
1770
2205
  this.render();
1771
2206
  return true;
1772
2207
  }
2208
+ for (const dayEl of this.$$('chat-day') || []) {
2209
+ dayEl.peerLastReadId = this._peerLastReadId;
2210
+ if (dayEl._logsInit && this._threadMessagesByDay?.get(dayEl.day)?.length)
2211
+ dayEl._onLogsChangedRun?.();
2212
+ }
1773
2213
  return false;
1774
2214
  },
1775
2215
  get onChanged() {
@@ -1836,8 +2276,8 @@ ODA({
1836
2276
  width: -webkit-fill-available;
1837
2277
  }
1838
2278
  .day-ribbon{
1839
- gap: 8px;
1840
- padding: 8px;
2279
+ gap: 2px;
2280
+ padding: 8px 12px;
1841
2281
  opacity: 0;
1842
2282
  }
1843
2283
  </style>
@@ -1849,9 +2289,51 @@ ODA({
1849
2289
  </div>
1850
2290
 
1851
2291
  <div class="day-ribbon" flex vertical ~if="expanded">
1852
- <chat-item @tap="setFocus" ~for="logs" :$item="$for.item"></chat-item>
2292
+ <chat-item @tap="setFocus"
2293
+ ~for="logs"
2294
+ :$item="$for.item"
2295
+ :is-dm="isDmFeed"
2296
+ :peer-last-read-id="peerLastReadId"
2297
+ :group-first="_isGroupFirst($for.index)"
2298
+ :group-last="_isGroupLast($for.index)"
2299
+ ~style="{ marginTop: _isGroupFirst($for.index) && $for.index > 0 ? '6px' : '0px' }"></chat-item>
1853
2300
  </div>
1854
2301
  `,
2302
+ get isDmFeed() {
2303
+ return Boolean(this.$pdp?.isPrivateFeed);
2304
+ },
2305
+ get peerLastReadId() {
2306
+ return Number(this.$pdp?._peerLastReadId) || 0;
2307
+ },
2308
+ _itemGroupInfo(it) {
2309
+ if (!it) return null;
2310
+ const row = it.logRow || it.DATA?.logRow;
2311
+ const ext = String(row?.ext || it.ext || '').toLowerCase();
2312
+ const p = String(row?.path || it.path || it.id || '');
2313
+ if (ext === 'task' || ext === 'call' || ext === 'operation' || ext === 'object' || p.endsWith('.task') || p.endsWith('.call'))
2314
+ return null;
2315
+ const sender = String(row?.sender || row?.chatMessage?.sender || '').trim();
2316
+ if (!sender) return null;
2317
+ return { sender, time: this._logItemTime(it) };
2318
+ },
2319
+ _isGroupFirst(idx) {
2320
+ const items = Array.isArray(this.logItems) ? this.logItems : [];
2321
+ const cur = this._itemGroupInfo(items[idx]);
2322
+ if (!cur) return true;
2323
+ const prev = idx > 0 ? this._itemGroupInfo(items[idx - 1]) : null;
2324
+ if (!prev || prev.sender !== cur.sender) return true;
2325
+ if (cur.time && prev.time && Math.abs(cur.time - prev.time) > 5 * 60 * 1000) return true;
2326
+ return false;
2327
+ },
2328
+ _isGroupLast(idx) {
2329
+ const items = Array.isArray(this.logItems) ? this.logItems : [];
2330
+ const cur = this._itemGroupInfo(items[idx]);
2331
+ if (!cur) return true;
2332
+ const next = idx + 1 < items.length ? this._itemGroupInfo(items[idx + 1]) : null;
2333
+ if (!next || next.sender !== cur.sender) return true;
2334
+ if (next.time && cur.time && Math.abs(next.time - cur.time) > 5 * 60 * 1000) return true;
2335
+ return false;
2336
+ },
1855
2337
  get expanderIcon() {
1856
2338
  return this.expanded ? 'icons:chevron-right:90' : 'icons:chevron-right';
1857
2339
  },
@@ -2047,6 +2529,89 @@ ODA({
2047
2529
  this._wrappedById.set(id, wrapped);
2048
2530
  return wrapped;
2049
2531
  },
2532
+ _syncCardWithWrapped(wrapped) {
2533
+ if (!wrapped?.id) return;
2534
+ for (const card of this.$$?.('chat-item') || []) {
2535
+ if (card.$item === wrapped || card.$item?.id === wrapped.id) {
2536
+ card.log = { ...wrapped.logRow };
2537
+ card.invalidate?.('log', 'logContent', 'isEdited', 'isPending', 'sendError', 'isReadByPeer', 'cmId', 'attachmentItems', 'replyInfo', 'shortTime');
2538
+ card.render?.();
2539
+ }
2540
+ }
2541
+ },
2542
+ upsertThreadMessage(msg) {
2543
+ if (!msg || !msg.id) return;
2544
+ if (!this._logsInit) {
2545
+ this._ensureLogsInit();
2546
+ return;
2547
+ }
2548
+ const w = this._wrapThreadMessage(msg);
2549
+ if (!w) return;
2550
+ const prev = Array.isArray(this.logItems) ? [...this.logItems] : [];
2551
+ const idx = prev.findIndex(it => it?.id === w.id || (msg.meta?.clientNonce && it?.logRow?.chatMessage?.meta?.clientNonce === msg.meta.clientNonce));
2552
+ if (idx >= 0) {
2553
+ prev[idx] = w;
2554
+ this.logItems = this._sortLogFiles(prev);
2555
+ this.render();
2556
+ this._syncCardWithWrapped(w);
2557
+ return;
2558
+ }
2559
+ this.logItems = this._sortLogFiles([...prev, w]);
2560
+ this.expanded = true;
2561
+ this.render();
2562
+ this._scrollRibbonDown();
2563
+ },
2564
+ replaceOptimisticMessage(clientNonce, saved) {
2565
+ if (!saved) return;
2566
+ if (!this._logsInit) {
2567
+ this._ensureLogsInit();
2568
+ return;
2569
+ }
2570
+ const w = this._wrapThreadMessage(saved);
2571
+ if (!w) return;
2572
+ const prev = Array.isArray(this.logItems) ? [...this.logItems] : [];
2573
+ const optIdx = clientNonce ? prev.findIndex(it => it?.logRow?.chatMessage?.meta?.clientNonce === clientNonce) : -1;
2574
+ const dupIdx = prev.findIndex(it => it?.id === w.id);
2575
+ if (optIdx >= 0 && dupIdx >= 0 && optIdx !== dupIdx) {
2576
+ const oldOpt = prev[optIdx];
2577
+ prev.splice(optIdx, 1);
2578
+ if (oldOpt?.id && this._wrappedById instanceof Map) this._wrappedById.delete(oldOpt.id);
2579
+ } else if (optIdx >= 0) {
2580
+ const oldOpt = prev[optIdx];
2581
+ if (oldOpt?.id && oldOpt.id !== w.id && this._wrappedById instanceof Map) this._wrappedById.delete(oldOpt.id);
2582
+ prev[optIdx] = w;
2583
+ } else if (dupIdx >= 0) {
2584
+ prev[dupIdx] = w;
2585
+ } else {
2586
+ prev.push(w);
2587
+ }
2588
+ this.logItems = this._sortLogFiles(prev);
2589
+ this.expanded = true;
2590
+ this.render();
2591
+ this._syncCardWithWrapped(w);
2592
+ },
2593
+ removeOptimisticByNonce(clientNonce) {
2594
+ if (!clientNonce || !Array.isArray(this.logItems)) return;
2595
+ const next = this.logItems.filter(it => {
2596
+ const match = it?.logRow?.chatMessage?.meta?.clientNonce === clientNonce;
2597
+ if (match && it?.id && this._wrappedById instanceof Map) this._wrappedById.delete(it.id);
2598
+ return !match;
2599
+ });
2600
+ if (next.length !== this.logItems.length) {
2601
+ this.logItems = next;
2602
+ this.render();
2603
+ }
2604
+ },
2605
+ removeThreadMessage(messageId) {
2606
+ const idStr = `chatmsg.${Number(messageId)}.msg`;
2607
+ if (this._wrappedById instanceof Map) this._wrappedById.delete(idStr);
2608
+ if (!Array.isArray(this.logItems)) return;
2609
+ const next = this.logItems.filter(it => it?.id !== idStr);
2610
+ if (next.length !== this.logItems.length) {
2611
+ this.logItems = next;
2612
+ this.render();
2613
+ }
2614
+ },
2050
2615
  async _bindLogsFolder() {
2051
2616
  const source = await Promise.resolve(this.logsSource);
2052
2617
  return !!source;
@@ -2112,6 +2677,7 @@ ODA({
2112
2677
  }
2113
2678
  const msgs = this.$pdp.threadMessagesForDay(this.day);
2114
2679
  for (const m of msgs) {
2680
+ if (m.meta?.deleted) continue;
2115
2681
  if (m.taskPath && taskKeys.has(taskKeyOf(m.taskPath))) continue;
2116
2682
  if (!String(m.content || '').trim() && !m.attachments?.length && m.kind !== 'approval') continue;
2117
2683
  if (m.sender !== '$twin' && m.kind === 'text' && rows.some(r => r?.sender === m.sender && String(r?.content || '').trim() === String(m.content || '').trim() && Math.abs((Number(r?.time) || 0) - (Number(m.created) || 0)) < 5000)) continue;
@@ -2188,10 +2754,14 @@ ODA({
2188
2754
  const items = await this._fetchLogFiles();
2189
2755
  const prev = Array.isArray(this.logItems) ? this.logItems : [];
2190
2756
  const prevLen = prev.length;
2191
- const sameList = prev.length === items.length && items.every((it, idx) => it === prev[idx] || it?.id && it.id === prev[idx]?.id);
2757
+ const sigOf = it => `${it?.id || ''}|${it?.logRow?.content || ''}|${it?.logRow?.chatMessage?.meta?.editedAt || ''}|${it?.logRow?.chatMessage?.meta?.status || ''}|${it?.logRow?.chatMessage?.meta?.pending ? 1 : 0}|${it?.logRow?.chatMessage?.meta?.sendError || ''}`;
2758
+ const sameList = prev.length === items.length && items.every((it, idx) => (it === prev[idx] || (it?.id && it.id === prev[idx]?.id)) && sigOf(it) === sigOf(prev[idx]));
2192
2759
  if (!sameList) {
2193
2760
  this.logItems = items;
2194
2761
  this.render();
2762
+ for (const it of items) {
2763
+ if (it?.id?.startsWith?.('chatmsg.')) this._syncCardWithWrapped(it);
2764
+ }
2195
2765
  this._syncExpandedTaskCard();
2196
2766
  if (items.length > prevLen) this._scrollRibbonDown();
2197
2767
  }