odant-work 1.0.113 → 1.0.114

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,910 +1,1578 @@
1
- const CHAT_PREVIEW_EXTS = new Set([
2
- 'task', 'call',
3
- 'png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'bmp', 'avif', 'ico',
4
- 'mp4', 'webm', 'ogv', 'mov', 'm4v',
5
- 'mp3', 'wav', 'ogg', 'm4a', 'flac', 'aac', 'opus',
6
- ]);
7
-
8
- export default {
9
- imports: 'oda//button, oda//icon, ~/lib//node-explorer.js',
10
- }
11
-
12
- ODA({is: 'chat-item',
13
- imports: 'oda//button, oda//icon, ~/lib//node-explorer.js',
14
- template: /* html */`
15
- <style>
16
- :host {
17
- @apply --horizontal;
18
- max-height: var(--chat-card-max, none);
19
- min-height: 0;
20
- flex-shrink: 0;
21
- overflow: hidden;
22
- border-radius: 4px;
23
- opacity: 0;
24
- transition: opacity .2s ease;
25
- }
26
- :host([visible]){
27
- opacity: 1;
28
- }
29
- :host([expanded]){
30
- position: fixed;
31
- z-index: 30;
32
- border-radius: 0px;
33
- top: 0px;
34
- left: 0px;
35
- right: 0px;
36
- bottom: 0px;
37
- max-height: none;
38
- overflow: auto;
39
- }
40
- :host([expanded]) .card{
41
- border-radius: 0px;
42
- }
43
- :host([expanded]) .title{
44
- @apply --accent-invert;
45
- }
46
-
47
- .card {
48
- min-width: 70px;
49
- min-height: 0;
50
- max-height: 100%;
51
- overflow: hidden;
52
- border-radius: 8px;
53
- width: min-content;
54
- }
55
- .preview {
56
- min-height: 0;
57
- overflow: auto;
58
- width: stretch;
59
- }
60
- :host([compact]) {
61
- width: 100%;
62
- border-radius: 0;
63
- box-sizing: border-box;
64
- }
65
- :host([compact]) .card {
66
- width: 100%;
67
- border-radius: 0;
68
- border: 1px solid var(--border-color);
69
- box-shadow: none;
70
- box-sizing: border-box;
71
- }
72
- :host([compact]) .preview {
73
- max-height: 220px;
74
- border-top: 1px solid var(--border-color);
75
- }
76
- .card[raised] {
77
- border-radius: 0px !important;
78
- }
79
- .sender {
80
- position: sticky;
81
- bottom: 0px;
82
- border-radius: 50% !important;
83
- }
84
- .body {
85
- user-select: text;
86
- overflow: hidden;
87
- }
88
- oda-button {
89
- scale: .8;
90
- border-radius: 50%;
91
- }
92
- oda-button:hover {
93
- @apply --hover;
94
- }
95
- .title {
96
- font-size: xx-small;
97
- min-height: 26px;
98
- flex-shrink: 0;
99
- transition: background-color .5s;
100
- }
101
- item-node{
102
- padding: 2px 8px;
103
- font-size: x-small;
104
- }
105
- .file-time{
106
- @apply --no-flex;
107
- font-size: xx-small;
108
- opacity: .55;
109
- margin-left: 6px;
110
- white-space: nowrap;
111
- align-self: center;
112
- }
113
- </style>
114
- <div vertical ~if="!compact && !hideAvatar && !expanded && !isTask && hasSenderAvatar" ~style="{padding: '0px 8px', order: (!isTask && !isSender) ? 2 : 0}">
115
- <div flex></div>
116
- <item-icon class="sender" icon-size="24" :$item="sender" :icon="isAgentSender ? 'bootstrap:robot' : ''" :title="isAgentSender ? agentSenderTitle : ''" :default="isAgentSender ? 'bootstrap:robot' : ''"></item-icon>
117
- </div>
118
- <div class="card" shadow :flex="expanded || compact" vertical ~style="cardLayoutStyle" @tap="onCardTap($event)">
119
- <div class="title" no-flex light horizontal ~if="!(expanded && bodyHeader)" style="justify-content: space-between; align-items: center;">
120
- <item-node auto-run :icon-size :$item="$file" :label="fileLabel" :hide-icon="isText || !!missingTargetPath" hide-history-time>
121
- <span class="file-time" ~if="fileTime">{{fileTime}}</span>
122
- </item-node>
123
- <oda-button ~if="!compact && !isOperationLog && !missingTargetPath && hasPreview" :icon-size :icon="expanderIcon" :error="expanded" @tap="expanded = !expanded"></oda-button>
124
- </div>
125
- <div class="preview missing-file-box" ~if="!expanded && missingTargetPath" horizontal style="align-items: center; justify-content: space-between; gap: 12px; padding: 8px 12px;">
126
- <div horizontal style="align-items: center; gap: 8px; min-width: 0; color: var(--error-color, #dc2626);">
127
- <oda-icon icon="icons:warning" :icon-size="18" style="flex-shrink: 0;"></oda-icon>
128
- <span style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" :title="missingTargetPath">
129
- Такого файла нет: <b>{{missingTargetLabel}}</b>
130
- </span>
131
- </div>
132
- <oda-button ~if="isAdminRole" class="delete-log-btn" error-invert icon="icons:delete" :icon-size="16" label="Удалить лог" title="Удалить запись лога об отсутствующем файле" @down.stop @tap.stop="deleteMissingLog($event)" style="border-radius: 6px; padding: 3px 10px; scale: 1; flex-shrink: 0;"></oda-button>
133
- </div>
134
- <div class="preview" ~if="!compact && !expanded && !missingTargetPath && hasPreview && $file" ~is="previewTag" flex :$item="$file" :log="log" :log-content="logContent" style="user-select: text;" @expand-card.stop="expanded = true"></div>
135
- <div class="preview" ~if="!compact && !expanded && !missingTargetPath && !$file && !hasTargetFilePath && logContent" flex style="padding: 6px 12px; white-space: pre-wrap; user-select: text;">{{logContent}}</div>
136
- <div class="approval-box" ~if="!compact && !expanded && log?.chatMessage?.kind === 'approval'" horizontal style="align-items: center; gap: 8px; padding: 4px 12px 8px;">
137
- <span ~if="approvalStatus === 'approved'" style="font-size: 12px; font-weight: 700; color: #059669;">✓ Утверждено</span>
138
- <span ~if="approvalStatus === 'rejected'" style="font-size: 12px; font-weight: 700; color: #dc2626;">✕ Отклонено</span>
139
- <oda-button ~if="approvalStatus === 'pending'" icon="icons:check" info-invert label="Утвердить" @down.stop @tap.stop="_resolveChatApproval('approve')" style="border-radius: 6px; padding: 3px 10px; scale: 1;"></oda-button>
140
- <oda-button ~if="approvalStatus === 'pending'" icon="icons:close" label="Отклонить" @down.stop @tap.stop="_resolveChatApproval('reject')" style="border-radius: 6px; padding: 3px 10px; scale: 1;"></oda-button>
141
- </div>
142
- <div header ~if="!expanded && !missingTargetPath && includeFiles?.length" vertical style="padding: 8px; gap: 8px;">
143
- <chat-item ~for="includeFiles" visible history compact :$file="$for.item"></chat-item>
144
- </div>
145
- <div class="body" flex vertical ~if="expanded && !missingTargetPath">
146
- <div ~is="formTag" flex :$item="$file" @own-header="bodyHeader = true" @close-view="expanded = false"></div>
147
- </div>
148
- </div>
149
- `,
150
- get formTag() {
151
- return Promise.resolve(this.$file).then(async file => {
152
- if (!file)
153
- return 'item-node';
154
- const name = file.form || 'file';
155
- const view = await file.get_item('/~/handlers//form/' + name);
156
- const ext = String(file.ext || '').toLowerCase();
157
- const is = ext ? `item-${name}-${ext}` : `item-${name}`;
158
- await view?.importView?.(is);
159
- if (!customElements.get(is)) {
160
- console.error(`[chat-item] вид '${name}' не зарегистрирован как <${is}>`);
161
- return 'item-node';
162
- }
163
- return is;
164
- });
165
- },
166
- get includeFiles() {
167
- // карточка задачи показывает все файлы сама (превью .task: вложения + созданное агентом) — вложения записи журнала не дублируем
168
- if (String(this.$file?.ext || '').toLowerCase() === 'task')
169
- return [];
170
- const raw = this.log?.includes;
171
- let paths = raw;
172
- if (!Array.isArray(paths)) {
173
- if (typeof raw !== 'string' || !raw.trim())
174
- return [];
175
- const s = raw.trim();
176
- if (s[0] === '[') {
177
- try {
178
- const parsed = JSON.parse(s);
179
- paths = Array.isArray(parsed) ? parsed : [s];
180
- } catch {
181
- paths = s.includes(',/') ? s.split(',') : [s];
182
- }
183
- } else
184
- paths = s.includes(',/') ? s.split(',') : [s];
185
- }
186
- if (!paths.length)
187
- return [];
188
- return Promise.all(paths.map(p => {
189
- p = String(p ?? '').trim();
190
- if (!p)
191
- return null;
192
- return WORK.get_item(p.startsWith('/') ? p : '/' + p, 'info');
193
- })).then(items => items.filter(Boolean));
194
- },
195
- /** Развёрнутое представление со своей шапкой (событие own-header) — своя полоса title не нужна; закрытие — close-view. */
196
- bodyHeader: false,
197
- get expanderIcon(){
198
- return this.expanded?'icons:close':'box:i-expand';
199
- },
200
- expanded: {
201
- $attr: true,
202
- $def: false,
203
- set(n) {
204
- try {
205
- this.dispatchEvent(new CustomEvent('chat-item-expanded', {
206
- bubbles: true,
207
- composed: true,
208
- detail: { expanded: Boolean(n), card: this },
209
- }));
210
- }
211
- catch { /* ignore */ }
212
- if (n) {
213
- const root = this.parentElement?.parentElement?.parentElement || this.getRootNode?.()?.host;
214
- const allCards = root?.$$ ? root.$$('chat-item') : (this.parentElement?.querySelectorAll?.('chat-item') || []);
215
- for (const other of allCards) {
216
- if (other && other !== this && other.expanded)
217
- other.expanded = false;
218
- }
219
- return;
220
- }
221
- if (!this._rebindClosing) {
222
- let p = this.parentElement || this.host || this.getRootNode?.()?.host;
223
- while (p && p.localName !== 'chat-day')
224
- p = p.parentElement || p.host || p.getRootNode?.()?.host;
225
- const myId = this._currentItemIdentity || '';
226
- if (p && p._expandedTaskKey && myId === 'task:' + p._expandedTaskKey)
227
- p._expandedTaskKey = '';
228
- }
229
- this.bodyHeader = false;
230
- this._resetBodyCache();
231
- },
232
- },
233
- get isAgentSender() {
234
- if (this.log?.sender === '$twin' || this.log?.chatMessage?.sender === '$twin')
235
- return true;
236
- if (this.log?.sender === 'WORK')
237
- return true;
238
- const act = String(this.log?.actor || '');
239
- if (act === 'AI' || act.startsWith('/MODULES/Модели/'))
240
- return true;
241
- if (Array.isArray(this.log?.receivers) && this.log?.receivers.length === 1 && this.log.receivers[0] === this.log?.sender && !this.log?.path)
242
- return true;
243
- return false;
244
- },
245
- get agentSenderTitle() {
246
- if (this.log?.sender === '$twin' || this.log?.chatMessage?.sender === '$twin') {
247
- const nl = this.log?.chatMessage?.nodeLabel;
248
- return nl ? `Цифровой двойник «${nl}»` : 'Цифровой двойник узла';
249
- }
250
- if (this.log?.sender === 'WORK')
251
- return 'Система WORK';
252
- const act = String(this.log?.actor || '');
253
- if (this.log?.actorLabel)
254
- return String(this.log.actorLabel);
255
- if (act.startsWith('/MODULES/Модели/'))
256
- return 'ИИ-агент (' + act.split('/').pop() + ')';
257
- return 'ИИ-агент WORK';
258
- },
259
- get approvalStatus() {
260
- return this.log?.chatMessage?.meta?.status || 'pending';
261
- },
262
- async _resolveChatApproval(action) {
263
- const cm = this.log?.chatMessage;
264
- if (!cm?.id || !cm?.threadId)
265
- return;
266
- const owner = this._resolveFeedOwner();
267
- if (!owner?.fetch)
268
- return;
269
- try {
270
- const res = await owner.fetch('chat_action', { threadId: cm.threadId, messageId: cm.id, action });
271
- if (res?.meta) {
272
- this.log = {
273
- ...this.log,
274
- chatMessage: { ...cm, meta: res.meta },
275
- };
276
- this.render?.();
277
- }
278
- }
279
- catch (err) {
280
- console.warn('[chat-item] chat_action:', err);
281
- }
282
- },
283
- get isSender(){
284
- if (this.isAgentSender)
285
- return false;
286
- return this.senderId === WORK.uid;
287
- },
288
- get isTask() {
289
- const ext = String(this.ext || this.log?.ext || this.$file?.ext || '').toLowerCase();
290
- if (ext === 'task')
291
- return true;
292
- const p = String(this.log?.path || this.$item?.path || this.$item?.id || '');
293
- return p.endsWith('.task');
294
- },
295
- get isOperationLog() {
296
- const ext = String(this.log?.ext || '').toLowerCase();
297
- return ext === 'operation' || ext === 'object';
298
- },
299
- /**
300
- * Раскладка на ленте чата подразделения:
301
- * - исходящие от текущего пользователя (isSender && !isTask) — слева;
302
- * - входящие от других пользователей (!isSender && !isTask) — справа;
303
- * - задачи ИИ (isTask) — по центру с отступом слева и справа.
304
- */
305
- get cardLayoutStyle() {
306
- if (this.expanded || this.compact) {
307
- return { order: 1 };
308
- }
309
- if (this.isTask) {
310
- return {
311
- order: 1,
312
- marginLeft: 'auto',
313
- marginRight: 'auto',
314
- width: '100%',
315
- maxWidth: 'min(820px, 100%)',
316
- boxSizing: 'border-box',
317
- };
318
- }
319
- if (this.isSender) {
320
- return {
321
- order: 1,
322
- marginLeft: '0px',
323
- marginRight: 'auto',
324
- maxWidth: '78%',
325
- };
326
- }
327
- return {
328
- order: 1,
329
- marginLeft: 'auto',
330
- marginRight: '0px',
331
- maxWidth: '78%',
332
- };
333
- },
334
- async onCardTap(e) {
335
- if (!this.isOperationLog || !this.log)
336
- return;
337
- e?.stopPropagation?.();
338
- const rawPath = String(this.log.path || '');
339
- const classPath = this.log.classPath || rawPath.split('/').slice(0, -1).join('/');
340
- const objectId = this.log.objectId || rawPath.split('/').pop();
341
- if (!classPath || !objectId)
342
- return;
343
- const clsItem = await WORK.get_item(classPath).catch(() => null);
344
- if (!clsItem)
345
- return;
346
- const wf = document.querySelector?.('pages-form')?.$?.('work-form') || this.domHost?.domHost;
347
- if (wf && typeof wf.openFormTab === 'function')
348
- await wf.openFormTab(clsItem, { view: 'objects/object', objectId });
349
- else if (typeof window.top?.execute === 'function')
350
- window.top.execute(clsItem, { view: 'objects/object', objectId });
351
- },
352
- colorMode: {
353
- $def: 'light',
354
- set(n) {
355
- const targets = [this.$('.card'), this.$('.body')].filter(Boolean);
356
- if (this._color) {
357
- for (const el of targets)
358
- el.removeAttribute(this._color);
359
- }
360
- this._color = n || '';
361
- if (this._color) {
362
- for (const el of targets)
363
- el.setAttribute(this._color, '');
364
- }
365
- }
366
- },
367
- attached() {
368
- this.async(() => {
369
- this.colorMode = this._color || 'light';
370
- });
371
- this._watchLog();
372
- this._revealIfReady();
373
- },
374
- history: {
375
- $attr: true,
376
- $def: false,
377
- set(n) {
378
- if (n)
379
- this.applyHistoryFile();
380
- }
381
- },
382
- compact: {
383
- $attr: true,
384
- $def: false,
385
- },
386
- visible:{
387
- $def: false,
388
- $attr: true,
389
- },
390
- previewIsReady: false,
391
- senderIsReady: false,
392
- _senderFromRef(ref) {
393
- if (!ref) return '';
394
- const path = ref.path;
395
- if (path) {
396
- const parsed = CORE.$file.parseHistoryEntryPath(path);
397
- if (parsed?.userId) return parsed.userId;
398
- }
399
- const id = ref.id || (path ? String(path).split('/').pop() : '') || '';
400
- const extDot = id.lastIndexOf('.');
401
- const name = extDot > 0 ? id.slice(0, extDot) : id;
402
- const nameParts = name.split('.');
403
- if (nameParts.length > 1 && /^\d+$/.test(nameParts[0]))
404
- return nameParts.slice(1).join('.');
405
- return '';
406
- },
407
- _applySenderFromRef(ref) {
408
- const uid = this._senderFromRef(ref);
409
- if (uid)
410
- this.senderId = uid;
411
- else if (!ref)
412
- this._markSenderReady();
413
- },
414
- _markSenderReady() {
415
- this.senderIsReady = true;
416
- this._revealIfReady();
417
- },
418
- _revealIfReady() {
419
- if (this.senderIsReady)
420
- this.visible = true;
421
- },
422
- previewTag: 'item-node',
423
- hasPreview: false,
424
- missingTargetPath: '',
425
- get hasTargetFilePath() {
426
- const p = String(this.log?.path || '').trim();
427
- const ext = String(this.log?.ext || '').toLowerCase();
428
- return Boolean(p && !p.endsWith('.logs') && ext !== 'operation' && ext !== 'object');
429
- },
430
- get missingTargetLabel() {
431
- const p = String(this.missingTargetPath || '').trim();
432
- if (!p)
433
- return '';
434
- return p.split('/').filter(Boolean).pop() || p;
435
- },
436
- _resolveFeedOwner() {
437
- let p = this.parentElement || this.host || this.getRootNode?.()?.host;
438
- while (p) {
439
- const candidate = p.$item;
440
- if (candidate && candidate !== this.$item && typeof candidate.fetch === 'function')
441
- return candidate;
442
- p = p.parentElement || p.host || p.getRootNode?.()?.host;
443
- }
444
- const wf = typeof document !== 'undefined' ? document.querySelector?.('pages-form')?.$?.('work-form') : null;
445
- if (wf?.currentItem && typeof wf.currentItem.fetch === 'function')
446
- return wf.currentItem;
447
- if (typeof window !== 'undefined' && window.$context && typeof window.$context.fetch === 'function')
448
- return window.$context;
449
- return globalThis.WORK;
450
- },
451
- get isAdminRole() {
452
- if (globalThis.WORK?.DEV_MODE)
453
- return true;
454
- const owner = this._resolveFeedOwner();
455
- if (owner?.type === '$user')
456
- return true;
457
- if (this.log?.sender && globalThis.WORK?.uid && this.log.sender === globalThis.WORK.uid)
458
- return true;
459
- const pdpRole = owner?.role;
460
- if (pdpRole)
461
- return pdpRole === 'BOSS';
462
- const wf = typeof document !== 'undefined' ? document.querySelector?.('pages-form')?.$?.('work-form') : null;
463
- if (wf?.activeRole)
464
- return wf.activeRole === 'BOSS';
465
- return true;
466
- },
467
- async deleteMissingLog(e) {
468
- e?.stopPropagation?.();
469
- e?.preventDefault?.();
470
- const owner = this._resolveFeedOwner();
471
- if (!owner || typeof owner.fetch !== 'function')
472
- return;
473
- const payload = {
474
- stubPath: this.log?.logsFilePath || this.$item?.path || '',
475
- path: this.missingTargetPath || this.log?.path || '',
476
- time: this.log?.time || 0,
477
- sender: this.log?.sender || '',
478
- };
479
- try {
480
- await owner.fetch('delete_log_entry', { ...payload, role: 'BOSS' });
481
- let p = this.parentElement || this.host || this.getRootNode?.()?.host;
482
- while (p && p.localName !== 'chat-day')
483
- p = p.parentElement || p.host || p.getRootNode?.()?.host;
484
- this.style.display = 'none';
485
- if (p && Array.isArray(p.logItems)) {
486
- const curId = this.$item?.id;
487
- const targetPath = this.missingTargetPath || this.log?.path || '';
488
- if (curId && p._wrappedById instanceof Map)
489
- p._wrappedById.delete(curId);
490
- p.logItems = p.logItems.filter(it => {
491
- if (it === this.$item)
492
- return false;
493
- if (curId && it?.id === curId)
494
- return false;
495
- if (targetPath && (it?.path === targetPath || it?.logRow?.path === targetPath))
496
- return false;
497
- return true;
498
- });
499
- p.invalidate?.('logs');
500
- p.render?.();
501
- }
502
- this.remove?.();
503
- }
504
- catch (err) {
505
- console.warn('[chat-item] delete_log_entry:', err);
506
- }
507
- },
508
- _bodyCacheKeys: ['itemBody', 'fileLabel', 'fileTime', 'sender', 'log', 'logContent', 'isText', 'hideAvatar'],
509
- _resetBodyCache() {
510
- this.invalidate(...this._bodyCacheKeys);
511
- },
512
- log: null,
513
- get logContent() {
514
- return this.log?.content ?? '';
515
- },
516
- get isText() {
517
- return this.ext === 'txt' || this.ext === 'md';
518
- },
519
- get fileTime() {
520
- if (this.compact)
521
- return '';
522
- return Promise.resolve(this.itemBody).then(body => {
523
- const ms = +(body?.time || this.log?.time);
524
- if (!Number.isFinite(ms) || ms <= 0)
525
- return '';
526
- const d = new Date(ms);
527
- if (isNaN(d))
528
- return '';
529
- const time = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
530
- const dd = String(d.getDate()).padStart(2, '0');
531
- const mm = String(d.getMonth() + 1).padStart(2, '0');
532
- return dd + '.' + mm + ' ' + time;
533
- });
534
- },
535
- get ext() {
536
- if (this._includeFile?.ext)
537
- return this._includeFile.ext;
538
- const path = this.log?.path || this._includeFile?.path || '';
539
- const id = String(path).split('/').pop() || '';
540
- const idx = id.lastIndexOf('.');
541
- return idx > -1 ? id.slice(idx + 1) : '';
542
- },
543
- async buildHistoryBody($file) {
544
- $file = await Promise.resolve($file);
545
- if (!$file?.path)
546
- return null;
547
- const parsed = CORE.$file.parseHistoryEntryPath($file.path) || {};
548
- return {
549
- path: $file.path,
550
- time: +parsed.timestamp || 0,
551
- sender: parsed.userId || '',
552
- type: '$file',
553
- ext: this.ext,
554
- };
555
- },
556
- isHistoryFile($file = this._includeFile) {
557
- return !!$file?.path?.includes('/history/');
558
- },
559
- async applyHistoryFile() {
560
- if (!this.history || !this._includeFile)
561
- return null;
562
- const body = await this.buildHistoryBody(this._includeFile);
563
- if (!body)
564
- return null;
565
- this._historyBody = body;
566
- if (body.sender)
567
- this.senderId = body.sender;
568
- else
569
- this._markSenderReady();
570
- this.log = body;
571
- this.previewIsReady = true;
572
- this.render();
573
- return body;
574
- },
575
- get itemBody() {
576
- if (this.log?.time)
577
- return Promise.resolve(this.log);
578
- if (this.history && this._includeFile) {
579
- if (this._historyBody)
580
- return Promise.resolve(this._historyBody);
581
- return this.applyHistoryFile().catch(e => {
582
- console.warn('[chat-item] history', e);
583
- return null;
584
- });
585
- }
586
- return Promise.resolve(this.$item).then(item => {
587
- if (!item)
588
- return null;
589
- if (typeof item.load !== 'function')
590
- return null;
591
- return item.load().then(raw => {
592
- const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
593
- if (!data.path && item.path && item.ext !== 'logs')
594
- data.path = item.path;
595
- // сам .task-файл (карточка принята в ленту напрямую): время — из имени файла <мс>.<uid>.task, как у записи журнала
596
- if (!data.time && item.ext === 'task') {
597
- const ts = parseInt(String(item.id || '').split('.')[0], 10);
598
- if (ts > 0)
599
- data.time = ts;
600
- }
601
- if (data.sender && !this.senderIsReady)
602
- this.senderId = data.sender;
603
- else if (!this.senderIsReady)
604
- this._markSenderReady();
605
- this.previewIsReady = true;
606
- this.log = data;
607
- this.render();
608
- return data;
609
- }).catch(e => {
610
- console.warn('[chat-item] load', e);
611
- return null;
612
- });
613
- });
614
- },
615
- get fileLabel() {
616
- if (this._includeFile?.path)
617
- return this._labelForItem(this._includeFile.path, this._includeFile);
618
- return Promise.resolve(this.itemBody).then(body => this._labelForLog(body));
619
- },
620
- _labelForItem(path, file) {
621
- if (String(path || '').includes('/history/'))
622
- return CORE.historyEntryLabel(path);
623
- const ext = String(file?.ext || this.ext || '').toLowerCase();
624
- if (this.compact && !['task', 'ics', 'eml'].includes(ext))
625
- return file?.DATA?.label || file?.id || String(path || '').split('/').pop() || '';
626
- return this._nameFromDataFile(file);
627
- },
628
- async _labelForLog(body) {
629
- if (!body)
630
- return '';
631
- if (body.chatMessage) {
632
- if (body.chatMessage.kind === 'approval')
633
- return 'Запрос подтверждения';
634
- return body.chatMessage.sender === '$twin' ? (body.chatMessage.nodeLabel ? `Двойник «${body.chatMessage.nodeLabel}»` : 'Цифровой двойник') : '';
635
- }
636
- if (String(body.path || '').includes('/history/'))
637
- return CORE.historyEntryLabel(body.path);
638
- try {
639
- const raw = body.content;
640
- const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
641
- if (data?.name)
642
- return data.name;
643
- } catch { /* content не JSON точки */ }
644
- return (await this._nameFromDataFile(await this.$file)) || body.ext || '';
645
- },
646
- async _nameFromDataFile(file) {
647
- const ext = String(file?.ext || '').toLowerCase();
648
- if (!['task', 'ics', 'eml'].includes(ext))
649
- return file?.DATA?.label || file?.id || file?.ext || '';
650
- if (!file?.load)
651
- return file?.ext || '';
652
- try {
653
- const raw = await file.load();
654
- const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
655
- if (data?.name)
656
- return data.name;
657
- } catch { /* не JSON */ }
658
- return file.ext || '';
659
- },
660
- async loadPreview($file) {
661
- if (!$file) {
662
- this.hasPreview = !this.compact;
663
- this.previewIsReady = true;
664
- this.render();
665
- return;
666
- }
667
- const ext = String($file?.ext || this.ext || '').toLowerCase();
668
- if (this.compact || !CHAT_PREVIEW_EXTS.has(ext)) {
669
- this.hasPreview = false;
670
- this.previewTag = 'item-node';
671
- this.previousElementSibling?.invalidate?.('hideAvatar');
672
- this.previewIsReady = true;
673
- this.render();
674
- return;
675
- }
676
- try {
677
- this.hasPreview = await CORE.$file.loadPreview($file);
678
- if (this.hasPreview)
679
- this.previewTag = ($file?.ext || 'file') + '-preview';
680
- else
681
- this.previewTag = 'item-node';
682
- }
683
- catch (e) {
684
- console.warn('[chat-item] loadPreview error:', e.message);
685
- this.hasPreview = false;
686
- this.previewTag = 'item-node';
687
- }
688
- finally {
689
- // соседа DOM реактивность не видит — hideAvatar предыдущей карточки сбрасываем явно
690
- this.previousElementSibling?.invalidate?.('hideAvatar');
691
- this.previewIsReady = true;
692
- this.render();
693
- }
694
- },
695
- $file: {
696
- get() {
697
- if (this._includeFile)
698
- return this._includeFile;
699
- if (this.history || (!this.$item && !this.log?.path))
700
- return null;
701
- // Если $item уже является самим файлом .task (принят через adoptTask), используем его напрямую без ожидания itemBody
702
- if (this.$item && !this.$item.logRow && (this.$item.ext === 'task' || String(this.$item.id || '').endsWith('.task'))) {
703
- const taskFile = this.$item;
704
- this.missingTargetPath = '';
705
- return this.loadPreview(taskFile).then(() => taskFile);
706
- }
707
- return Promise.resolve(this.itemBody).then(async body => {
708
- if (body?.chatMessage)
709
- return null;
710
- if (!body?.path || String(body.path).endsWith('.logs') || body?.ext === 'operation' || body?.ext === 'object') {
711
- if (body?.ext === 'operation' || body?.ext === 'object')
712
- this.hasPreview = true;
713
- return null;
714
- }
715
- let $file = null;
716
- try {
717
- $file = await WORK.get_item(body.path, 'info');
718
- }
719
- catch {
720
- $file = null;
721
- }
722
- if (!$file || (typeof $file === 'object' && !$file.path && !$file.id && !$file.type)) {
723
- this.missingTargetPath = String(body.path);
724
- this.hasPreview = false;
725
- this.previewIsReady = true;
726
- this.render();
727
- return null;
728
- }
729
- this.missingTargetPath = '';
730
- if ($file && !$file.id && $file.path) {
731
- $file.DATA ??= {};
732
- $file.DATA.id = $file.path.split('/').pop();
733
- }
734
- await this.loadPreview($file);
735
- return $file;
736
- })
737
- },
738
- set($file) {
739
- const run = async (file) => {
740
- if (file && this._includeFile === file && (this.previewIsReady || this._loadingIncludeFile === file))
741
- return;
742
- this._loadingIncludeFile = file;
743
- this._includeFile = file;
744
- this._historyBody = null;
745
- this._resetBodyCache();
746
- if (this[R]?.cache)
747
- this[R].cache.$file = file;
748
- this.previewIsReady = false;
749
- this.senderIsReady = false;
750
- this._applySenderFromRef(file);
751
- await this.loadPreview(file);
752
- if (this.history) {
753
- await this.applyHistoryFile();
754
- }
755
- else if (this.log?.time) {
756
- this.previewIsReady = true;
757
- this.render();
758
- }
759
- if (this[R]?.cache && this._includeFile === file)
760
- this[R].cache.$file = file;
761
- };
762
- if ($file != null && typeof $file.then === 'function')
763
- $file.then(run).catch(() => {});
764
- else
765
- run($file).catch(() => {});
766
- }
767
- },
768
- _identityOfItem(item) {
769
- if (!item)
770
- return '';
771
- const targetPath = String(item.logRow?.path || item.DATA?.logRow?.path || item.path || '');
772
- const taskMatch = targetPath.match(/([^/\\]+\.task)$/i) || String(item.id || '').match(/([^/\\]+\.task)$/i);
773
- if (taskMatch)
774
- return 'task:' + taskMatch[1];
775
- const logsTask = String(item.id || '').replace(/\.logs$/i, '.task');
776
- if (logsTask.endsWith('.task') && (item.logRow?.ext === 'task' || item.DATA?.logRow?.ext === 'task'))
777
- return 'task:' + logsTask;
778
- return String(item.path || item.id || '');
779
- },
780
- $item: {
781
- $def: null,
782
- set(n) {
783
- const nextKey = n ? String(n.path || n.id || '') : '';
784
- const nextIdentity = this._identityOfItem(n);
785
- if (this._currentItemIdentity && nextIdentity !== this._currentItemIdentity && this.expanded) {
786
- this._rebindClosing = true;
787
- try {
788
- this.expanded = false;
789
- }
790
- finally {
791
- this._rebindClosing = false;
792
- }
793
- }
794
- this._currentItemIdentity = nextIdentity;
795
- if (nextKey && this._currentItemKey === nextKey && this.log) {
796
- const nextRow = n?.logRow || n?.DATA?.logRow;
797
- if (nextRow && typeof nextRow === 'object' && typeof nextRow.then !== 'function') {
798
- this.log = { ...nextRow };
799
- this.invalidate('sender', 'isAgentSender', 'isTask', 'fileLabel', 'fileTime', 'logContent');
800
- }
801
- return;
802
- }
803
- this._currentItemKey = nextKey;
804
- this.missingTargetPath = '';
805
- this._resetBodyCache();
806
- this.previewIsReady = false;
807
- this.senderIsReady = false;
808
- this._includeFile = null;
809
- this.log = null;
810
- this._unwatchLog();
811
- this._applySenderFromRef(n);
812
- const logRow = n?.logRow || n?.DATA?.logRow;
813
- if (logRow && typeof logRow === 'object' && typeof logRow.then !== 'function') {
814
- const data = { ...logRow };
815
- this.log = data;
816
- this.invalidate('sender', 'isAgentSender', 'isTask', 'fileLabel', 'fileTime', 'logContent');
817
- if (data.sender && !this.senderIsReady)
818
- this.senderId = data.sender;
819
- else if (!this.senderIsReady)
820
- this._markSenderReady();
821
- this.previewIsReady = true;
822
- this.render();
823
- return;
824
- }
825
- if (n?.listen && n?.id?.endsWith?.('.logs')) {
826
- const applyLog = raw => {
827
- const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
828
- if (!data?.time)
829
- return;
830
- this.log = { ...data };
831
- this.invalidate('sender', 'isAgentSender', 'isTask', 'fileLabel', 'fileTime', 'logContent');
832
- if (data.sender && !this.senderIsReady)
833
- this.senderId = data.sender;
834
- else if (!this.senderIsReady)
835
- this._markSenderReady();
836
- this.render();
837
- };
838
- if (typeof n.load === 'function') {
839
- n.load().then(applyLog).catch(() => {});
840
- }
841
- this._watched = { item: n, fn: () => n.load().then(applyLog).catch(() => {}) };
842
- this._watchLog();
843
- }
844
- }
845
- },
846
- /** Подписка на изменения записи: ровно одна, снимается при смене элемента и уходе из DOM. */
847
- _watchLog() {
848
- const w = this._watched;
849
- if (w && !w.on) {
850
- w.item.listen('changed', w.fn);
851
- w.on = true;
852
- }
853
- },
854
- _unwatchLog() {
855
- const w = this._watched;
856
- if (w?.on)
857
- w.item.unlisten('changed', w.fn);
858
- this._watched = null;
859
- },
860
- detached() {
861
- const w = this._watched;
862
- if (w?.on) {
863
- w.item.unlisten('changed', w.fn);
864
- w.on = false;
865
- }
866
- try {
867
- this.dispatchEvent(new CustomEvent('chat-item-expanded', {
868
- bubbles: true,
869
- composed: true,
870
- detail: { expanded: false, card: this },
871
- }));
872
- }
873
- catch { /* ignore */ }
874
- },
875
- senderId: {
876
- $type: String,
877
- set(n) {
878
- this.senderIsReady = true;
879
- this._revealIfReady();
880
- }
881
- },
882
- _hasResolvedSender: false,
883
- get hasSenderAvatar() {
884
- return Boolean(this.isAgentSender || this._hasResolvedSender);
885
- },
886
- get sender() {
887
- return Promise.resolve(this.itemBody).then(async body => {
888
- if (this.isAgentSender) {
889
- this._hasResolvedSender = false;
890
- if (!this.senderIsReady)
891
- this._markSenderReady();
892
- return null;
893
- }
894
- if (!body?.sender) {
895
- this._hasResolvedSender = false;
896
- if (!this.senderIsReady)
897
- this._markSenderReady();
898
- return null;
899
- }
900
- let users = await WORK.users;
901
- const found = users.find(u => u.id === body.sender) || null;
902
- this._hasResolvedSender = Boolean(found);
903
- this.senderId = body.sender;
904
- return found;
905
- })
906
- },
907
- get hideAvatar() {
908
- return this.isTask;
909
- },
910
- })
1
+ const CHAT_PREVIEW_EXTS = new Set([
2
+ 'task', 'call',
3
+ 'png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'bmp', 'avif', 'ico',
4
+ 'mp4', 'webm', 'ogv', 'mov', 'm4v',
5
+ 'mp3', 'wav', 'ogg', 'm4a', 'flac', 'aac', 'opus',
6
+ ]);
7
+
8
+ const IMAGE_EXTS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'bmp', 'avif', 'ico']);
9
+ const VIDEO_EXTS = new Set(['mp4', 'webm', 'ogv', 'mov', 'm4v']);
10
+ const AUDIO_EXTS = new Set(['mp3', 'wav', 'ogg', 'm4a', 'flac', 'aac', 'opus']);
11
+
12
+ const AUTHOR_COLORS = [
13
+ '#2563eb', '#7c3aed', '#059669', '#d97706', '#dc2626', '#0891b2', '#db2777', '#4f46e5',
14
+ ];
15
+
16
+ function authorColorFor(id) {
17
+ const s = String(id || '');
18
+ let h = 0;
19
+ for (let i = 0; i < s.length; i++)
20
+ h = ((h << 5) - h + s.charCodeAt(i)) | 0;
21
+ return AUTHOR_COLORS[Math.abs(h) % AUTHOR_COLORS.length];
22
+ }
23
+
24
+ function extOfPath(p) {
25
+ const base = String(p || '').split('/').pop() || '';
26
+ const idx = base.lastIndexOf('.');
27
+ return idx > -1 ? base.slice(idx + 1).toLowerCase() : '';
28
+ }
29
+
30
+ function fileUrlOf(p) {
31
+ if (!p) return '';
32
+ const norm = String(p).startsWith('/') ? String(p) : '/' + String(p);
33
+ try {
34
+ return encodeURI((globalThis.location?.origin || '') + norm);
35
+ }
36
+ catch {
37
+ return norm;
38
+ }
39
+ }
40
+
41
+ export default {
42
+ imports: 'oda//button, oda//icon, ~/lib//node-explorer.js',
43
+ }
44
+
45
+ ODA({is: 'chat-item',
46
+ imports: 'oda//button, oda//icon, ~/lib//node-explorer.js',
47
+ template: /* html */`
48
+ <style>
49
+ :host {
50
+ @apply --horizontal;
51
+ max-height: var(--chat-card-max, none);
52
+ min-height: 0;
53
+ flex-shrink: 0;
54
+ overflow: visible;
55
+ border-radius: 4px;
56
+ opacity: 0;
57
+ transition: opacity .16s ease;
58
+ box-sizing: border-box;
59
+ }
60
+ :host([visible]){
61
+ opacity: 1;
62
+ }
63
+ :host([expanded]){
64
+ position: fixed;
65
+ z-index: 30;
66
+ border-radius: 0px;
67
+ top: 0px;
68
+ left: 0px;
69
+ right: 0px;
70
+ bottom: 0px;
71
+ max-height: none;
72
+ overflow: auto;
73
+ background: var(--content-background, #fff);
74
+ }
75
+ :host([expanded]) .card{
76
+ border-radius: 0px;
77
+ }
78
+ :host([expanded]) .title{
79
+ @apply --accent-invert;
80
+ }
81
+
82
+ .card {
83
+ min-width: 70px;
84
+ min-height: 0;
85
+ max-height: 100%;
86
+ overflow: hidden;
87
+ border-radius: 10px;
88
+ width: min-content;
89
+ }
90
+ .preview {
91
+ min-height: 0;
92
+ overflow: auto;
93
+ width: stretch;
94
+ }
95
+ :host([compact]) {
96
+ width: 100%;
97
+ border-radius: 0;
98
+ box-sizing: border-box;
99
+ }
100
+ :host([compact]) .card {
101
+ width: 100%;
102
+ border-radius: 0;
103
+ border: 1px solid var(--border-color);
104
+ box-shadow: none;
105
+ box-sizing: border-box;
106
+ }
107
+ :host([compact]) .preview {
108
+ max-height: 220px;
109
+ border-top: 1px solid var(--border-color);
110
+ }
111
+ .card[raised] {
112
+ border-radius: 0px !important;
113
+ }
114
+ .sender {
115
+ position: sticky;
116
+ bottom: 0px;
117
+ border-radius: 50% !important;
118
+ }
119
+ .body {
120
+ user-select: text;
121
+ overflow: hidden;
122
+ }
123
+ .title {
124
+ font-size: xx-small;
125
+ min-height: 26px;
126
+ flex-shrink: 0;
127
+ transition: background-color .5s;
128
+ }
129
+ .title oda-button {
130
+ scale: .8;
131
+ border-radius: 50%;
132
+ }
133
+ .title oda-button:hover {
134
+ @apply --hover;
135
+ }
136
+ item-node{
137
+ padding: 2px 8px;
138
+ font-size: x-small;
139
+ }
140
+ .file-time{
141
+ @apply --no-flex;
142
+ font-size: xx-small;
143
+ opacity: .55;
144
+ margin-left: 6px;
145
+ white-space: nowrap;
146
+ align-self: center;
147
+ }
148
+
149
+ /* --- Пузыри мессенджера --- */
150
+ .avatar-slot {
151
+ display: flex;
152
+ flex-direction: column;
153
+ justify-content: flex-end;
154
+ width: 32px;
155
+ flex-shrink: 0;
156
+ margin-right: 6px;
157
+ }
158
+ .avatar-slot.hidden-avatar {
159
+ visibility: hidden;
160
+ }
161
+ .bubble-row {
162
+ display: flex;
163
+ align-items: flex-end;
164
+ gap: 6px;
165
+ min-width: 0;
166
+ max-width: min(76%, 640px);
167
+ position: relative;
168
+ }
169
+ .bubble-row.own {
170
+ flex-direction: row-reverse;
171
+ }
172
+ .bubble {
173
+ position: relative;
174
+ display: flex;
175
+ flex-direction: column;
176
+ gap: 4px;
177
+ min-width: 68px;
178
+ max-width: 100%;
179
+ padding: 7px 11px 6px;
180
+ box-sizing: border-box;
181
+ border-radius: 15px;
182
+ font-size: 14px;
183
+ line-height: 1.42;
184
+ color: var(--content-color, #0f172a);
185
+ background: var(--content-background, #ffffff);
186
+ border: 1px solid color-mix(in oklch, var(--border-color, #cbd5e1) 55%, transparent);
187
+ box-shadow: 0 1px 2px rgba(15, 23, 42, 0.08);
188
+ transition: background-color .15s ease, box-shadow .15s ease;
189
+ }
190
+ .bubble.own {
191
+ background: color-mix(in oklch, var(--accent-color, #4f46e5) 14%, var(--content-background, #ffffff));
192
+ border-color: color-mix(in oklch, var(--accent-color, #4f46e5) 26%, transparent);
193
+ }
194
+ .bubble.peer.grp-last {
195
+ border-bottom-left-radius: 4px;
196
+ }
197
+ .bubble.peer:not(.grp-first) {
198
+ border-top-left-radius: 6px;
199
+ }
200
+ .bubble.own.grp-last {
201
+ border-bottom-right-radius: 4px;
202
+ }
203
+ .bubble.own:not(.grp-first) {
204
+ border-top-right-radius: 6px;
205
+ }
206
+ .bubble.pending {
207
+ opacity: .78;
208
+ }
209
+ .bubble.send-error {
210
+ border-color: var(--error-color, #dc2626);
211
+ background: color-mix(in oklch, var(--error-color, #dc2626) 8%, var(--content-background, #ffffff));
212
+ }
213
+ .bubble-author {
214
+ font-size: 12px;
215
+ font-weight: 700;
216
+ line-height: 1.25;
217
+ margin-bottom: 1px;
218
+ overflow: hidden;
219
+ text-overflow: ellipsis;
220
+ white-space: nowrap;
221
+ }
222
+ .reply-quote {
223
+ display: flex;
224
+ flex-direction: column;
225
+ gap: 1px;
226
+ padding: 4px 8px;
227
+ border-radius: 8px;
228
+ border-left: 3px solid var(--accent-color, #4f46e5);
229
+ background: color-mix(in oklch, var(--accent-color, #4f46e5) 9%, transparent);
230
+ cursor: pointer;
231
+ font-size: 12px;
232
+ line-height: 1.3;
233
+ max-width: 100%;
234
+ box-sizing: border-box;
235
+ }
236
+ .reply-quote:hover {
237
+ background: color-mix(in oklch, var(--accent-color, #4f46e5) 15%, transparent);
238
+ }
239
+ .reply-quote-author {
240
+ font-weight: 700;
241
+ color: var(--accent-color, #4f46e5);
242
+ overflow: hidden;
243
+ text-overflow: ellipsis;
244
+ white-space: nowrap;
245
+ }
246
+ .reply-quote-text {
247
+ opacity: .8;
248
+ overflow: hidden;
249
+ text-overflow: ellipsis;
250
+ white-space: nowrap;
251
+ }
252
+ .bubble-atts {
253
+ display: flex;
254
+ flex-direction: column;
255
+ gap: 6px;
256
+ margin: 2px 0;
257
+ }
258
+ .att-img {
259
+ display: block;
260
+ max-width: min(320px, 100%);
261
+ max-height: 280px;
262
+ border-radius: 10px;
263
+ object-fit: cover;
264
+ cursor: pointer;
265
+ background: rgba(0, 0, 0, 0.04);
266
+ }
267
+ .att-video {
268
+ display: block;
269
+ max-width: min(340px, 100%);
270
+ max-height: 240px;
271
+ border-radius: 10px;
272
+ background: #000;
273
+ }
274
+ .att-audio {
275
+ width: min(280px, 100%);
276
+ height: 36px;
277
+ }
278
+ .att-file {
279
+ display: flex;
280
+ align-items: center;
281
+ gap: 8px;
282
+ padding: 6px 8px;
283
+ border-radius: 10px;
284
+ background: color-mix(in oklch, var(--content-background, #fff) 75%, var(--subtle-background, #f1f5f9));
285
+ border: 1px solid color-mix(in oklch, var(--border-color, #cbd5e1) 70%, transparent);
286
+ cursor: pointer;
287
+ min-width: 180px;
288
+ max-width: 340px;
289
+ box-sizing: border-box;
290
+ }
291
+ .att-file:hover {
292
+ border-color: var(--accent-color, #4f46e5);
293
+ }
294
+ .att-file-meta {
295
+ flex: 1 1 auto;
296
+ min-width: 0;
297
+ display: flex;
298
+ flex-direction: column;
299
+ }
300
+ .att-file-name {
301
+ font-size: 13px;
302
+ font-weight: 600;
303
+ overflow: hidden;
304
+ text-overflow: ellipsis;
305
+ white-space: nowrap;
306
+ }
307
+ .att-file-sub {
308
+ font-size: 11px;
309
+ opacity: .6;
310
+ }
311
+ .att-act {
312
+ border-radius: 50%;
313
+ flex-shrink: 0;
314
+ opacity: .72;
315
+ }
316
+ .att-act:hover {
317
+ opacity: 1;
318
+ @apply --hover;
319
+ }
320
+ .bubble-body-line {
321
+ display: flex;
322
+ flex-direction: column;
323
+ min-width: 0;
324
+ }
325
+ .bubble-text {
326
+ white-space: pre-wrap;
327
+ word-break: break-word;
328
+ user-select: text;
329
+ min-width: 0;
330
+ }
331
+ .bubble-meta {
332
+ display: inline-flex;
333
+ align-items: center;
334
+ justify-content: flex-end;
335
+ gap: 4px;
336
+ align-self: flex-end;
337
+ margin-top: 1px;
338
+ font-size: 11px;
339
+ line-height: 1;
340
+ opacity: .68;
341
+ user-select: none;
342
+ white-space: nowrap;
343
+ }
344
+ .bubble.own .bubble-meta {
345
+ opacity: .78;
346
+ }
347
+ .edited-tag {
348
+ font-style: italic;
349
+ font-size: 10.5px;
350
+ }
351
+ .ticks {
352
+ display: inline-flex;
353
+ align-items: center;
354
+ color: currentColor;
355
+ }
356
+ .ticks.read {
357
+ color: var(--accent-color, #2563eb);
358
+ opacity: 1;
359
+ }
360
+ .send-err-box {
361
+ display: flex;
362
+ align-items: center;
363
+ flex-wrap: wrap;
364
+ gap: 6px;
365
+ margin-top: 2px;
366
+ font-size: 12px;
367
+ color: var(--error-color, #dc2626);
368
+ }
369
+ .send-err-btn {
370
+ border: 1px solid currentColor;
371
+ background: transparent;
372
+ color: inherit;
373
+ border-radius: 999px;
374
+ padding: 2px 8px;
375
+ font: inherit;
376
+ font-size: 11px;
377
+ font-weight: 600;
378
+ cursor: pointer;
379
+ }
380
+ .send-err-btn:hover {
381
+ background: color-mix(in oklch, var(--error-color, #dc2626) 12%, transparent);
382
+ }
383
+ .hover-actions {
384
+ display: flex;
385
+ align-items: center;
386
+ gap: 2px;
387
+ opacity: 0;
388
+ pointer-events: none;
389
+ transition: opacity .14s ease;
390
+ flex-shrink: 0;
391
+ align-self: center;
392
+ background: color-mix(in oklch, var(--content-background, #fff) 92%, transparent);
393
+ border: 1px solid color-mix(in oklch, var(--border-color, #cbd5e1) 60%, transparent);
394
+ border-radius: 999px;
395
+ padding: 1px 3px;
396
+ box-shadow: 0 2px 6px rgba(15, 23, 42, 0.1);
397
+ }
398
+ .bubble-row:hover .hover-actions,
399
+ .bubble-row:focus-within .hover-actions {
400
+ opacity: 1;
401
+ pointer-events: auto;
402
+ }
403
+ .hover-btn {
404
+ border: none;
405
+ background: transparent;
406
+ color: var(--content-color, #334155);
407
+ width: 24px;
408
+ height: 24px;
409
+ border-radius: 50%;
410
+ display: inline-flex;
411
+ align-items: center;
412
+ justify-content: center;
413
+ cursor: pointer;
414
+ padding: 0;
415
+ }
416
+ .hover-btn:hover {
417
+ background: color-mix(in oklch, var(--accent-color, #4f46e5) 14%, transparent);
418
+ color: var(--accent-color, #4f46e5);
419
+ }
420
+ @media (max-width: 768px) {
421
+ .bubble-row {
422
+ max-width: min(88%, 640px);
423
+ }
424
+ }
425
+ </style>
426
+
427
+ <!-- Режим пузыря мессенджера -->
428
+ <div class="avatar-slot" ~if="isBubble && !isSender && !isDm && hasSenderAvatar" ~class="{'hidden-avatar': !groupLast}">
429
+ <item-icon class="sender" icon-size="28" :$item="sender" :icon="isAgentSender ? 'bootstrap:robot' : ''" :title="isAgentSender ? agentSenderTitle : ''" :default="isAgentSender ? 'bootstrap:robot' : ''"></item-icon>
430
+ </div>
431
+ <div class="bubble-row" ~if="isBubble" ~class="{ own: isSender, peer: !isSender }" ~style="cardLayoutStyle">
432
+ <div class="bubble" ~class="{ own: isSender, peer: !isSender, 'grp-first': groupFirst, 'grp-last': groupLast, pending: isPending, 'send-error': Boolean(sendError) }" @contextmenu.prevent.stop="openMessageMenu($event)">
433
+ <div class="bubble-author" ~if="!isDm && !isSender && groupFirst && senderDisplayName" ~style="{ color: authorColor }">{{senderDisplayName}}</div>
434
+ <div class="reply-quote" ~if="replyInfo" @tap.stop="scrollToReply($event)">
435
+ <div class="reply-quote-author">{{replyInfo.senderLabel || replyInfo.sender || 'Сообщение'}}</div>
436
+ <div class="reply-quote-text">{{replyInfo.preview}}</div>
437
+ </div>
438
+ <div class="bubble-atts" ~if="attachmentItems.length">
439
+ <div ~for="attachmentItems" style="display: contents;">
440
+ <img ~if="$for.item.isImage" class="att-img" loading="lazy" :src="$for.item.url" :alt="$for.item.name" @tap.stop="openAttachment($for.item, $event)" @contextmenu.prevent.stop="openAttachmentMenu($for.item, $event)">
441
+ <video ~if="$for.item.isVideo" class="att-video" controls preload="metadata" :src="$for.item.url" @contextmenu.prevent.stop="openAttachmentMenu($for.item, $event)"></video>
442
+ <audio ~if="$for.item.isAudio" class="att-audio" controls preload="metadata" :src="$for.item.url" @contextmenu.prevent.stop="openAttachmentMenu($for.item, $event)"></audio>
443
+ <div ~if="!$for.item.isImage && !$for.item.isVideo && !$for.item.isAudio" class="att-file" @tap.stop="openAttachment($for.item, $event)" @contextmenu.prevent.stop="openAttachmentMenu($for.item, $event)">
444
+ <item-icon :$item="$for.item.item" icon="icons:insert-drive-file" icon-size="24"></item-icon>
445
+ <div class="att-file-meta">
446
+ <div class="att-file-name" :title="$for.item.name">{{$for.item.name}}</div>
447
+ <div class="att-file-sub" ~if="$for.item.ext">{{$for.item.ext.toUpperCase()}}</div>
448
+ </div>
449
+ <oda-button class="att-act" icon="icons:file-download" :icon-size="16" title="Скачать" @down.stop @tap.stop="downloadAttachment($for.item, $event)"></oda-button>
450
+ <oda-button class="att-act" icon="icons:more-vert" :icon-size="16" title="Меню файла" @down.stop @tap.stop="openAttachmentMenu($for.item, $event)"></oda-button>
451
+ </div>
452
+ </div>
453
+ </div>
454
+ <div class="bubble-body-line" ~if="logContent">
455
+ <div class="bubble-text">{{logContent}}</div>
456
+ </div>
457
+ <div class="approval-box" ~if="log?.chatMessage?.kind === 'approval'" horizontal style="align-items: center; gap: 8px; padding: 4px 0 2px;">
458
+ <span ~if="approvalStatus === 'approved'" style="font-size: 12px; font-weight: 700; color: #059669;">✓ Утверждено</span>
459
+ <span ~if="approvalStatus === 'rejected'" style="font-size: 12px; font-weight: 700; color: #dc2626;">✕ Отклонено</span>
460
+ <oda-button ~if="approvalStatus === 'pending'" icon="icons:check" info-invert label="Утвердить" @down.stop @tap.stop="_resolveChatApproval('approve')" style="border-radius: 6px; padding: 3px 10px; scale: 1;"></oda-button>
461
+ <oda-button ~if="approvalStatus === 'pending'" icon="icons:close" label="Отклонить" @down.stop @tap.stop="_resolveChatApproval('reject')" style="border-radius: 6px; padding: 3px 10px; scale: 1;"></oda-button>
462
+ </div>
463
+ <div class="send-err-box" ~if="sendError">
464
+ <span>Не отправлено</span>
465
+ <button type="button" class="send-err-btn" @tap.stop="_retryFailedSend($event)">Повторить</button>
466
+ <button type="button" class="send-err-btn" @tap.stop="_dismissFailedSend($event)">Убрать</button>
467
+ </div>
468
+ <div class="bubble-meta" ~if="shortTime || isSender">
469
+ <span class="edited-tag" ~if="isEdited">изм.</span>
470
+ <span class="msg-time" ~if="shortTime">{{shortTime}}</span>
471
+ <span ~if="isSender && sendError" class="ticks" style="color: var(--error-color, #dc2626);" :title="sendError">!</span>
472
+ <span ~if="isSender && !sendError && isPending" class="ticks" title="Отправляется…">
473
+ <oda-icon icon="icons:schedule" :icon-size="12"></oda-icon>
474
+ </span>
475
+ <span ~if="isSender && !sendError && !isPending && isReadByPeer" class="ticks read" title="Прочитано">
476
+ <svg width="16" height="11" viewBox="0 0 16 11" fill="none" aria-hidden="true"><path d="M1 5.5L4.2 8.7L10.5 2" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M5.5 8.7L14.5 2" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>
477
+ </span>
478
+ <span ~if="isSender && !sendError && !isPending && !isReadByPeer && cmId > 0" class="ticks sent" title="Отправлено">
479
+ <svg width="12" height="11" viewBox="0 0 12 11" fill="none" aria-hidden="true"><path d="M1 5.5L4.2 8.7L10.5 2" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>
480
+ </span>
481
+ </div>
482
+ </div>
483
+ <div class="hover-actions" ~if="!isPending && !sendError">
484
+ <button type="button" class="hover-btn" title="Ответить" @down.stop @tap.stop="_replyAction($event)">
485
+ <oda-icon icon="icons:reply" :icon-size="15"></oda-icon>
486
+ </button>
487
+ <button type="button" class="hover-btn" title="Действия" @down.stop @tap.stop="openMessageMenu($event)">
488
+ <oda-icon icon="icons:more-vert" :icon-size="15"></oda-icon>
489
+ </button>
490
+ </div>
491
+ </div>
492
+
493
+ <!-- Режим карточки (задачи .task, звонки, операции, missingTargetPath, compact, history, expanded) -->
494
+ <div class="card" ~if="!isBubble" shadow :flex="expanded || compact" vertical ~style="cardLayoutStyle" @tap="onCardTap($event)">
495
+ <div class="title" no-flex light horizontal ~if="!(expanded && bodyHeader)" style="justify-content: space-between; align-items: center;">
496
+ <item-node auto-run :icon-size :$item="activeCardFile" :label="fileLabel" :hide-icon="isText || !!missingTargetPath" hide-history-time>
497
+ <span class="file-time" ~if="fileTime">{{fileTime}}</span>
498
+ </item-node>
499
+ <oda-button ~if="!compact && !isOperationLog && !missingTargetPath && (hasPreview || _expandedFile)" :icon-size :icon="expanderIcon" :error="expanded" @tap="expanded = !expanded"></oda-button>
500
+ </div>
501
+ <div class="preview missing-file-box" ~if="!expanded && missingTargetPath" horizontal style="align-items: center; justify-content: space-between; gap: 12px; padding: 8px 12px;">
502
+ <div horizontal style="align-items: center; gap: 8px; min-width: 0; color: var(--error-color, #dc2626);">
503
+ <oda-icon icon="icons:warning" :icon-size="18" style="flex-shrink: 0;"></oda-icon>
504
+ <span style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" :title="missingTargetPath">
505
+ Такого файла нет: <b>{{missingTargetLabel}}</b>
506
+ </span>
507
+ </div>
508
+ <oda-button ~if="isAdminRole" class="delete-log-btn" error-invert icon="icons:delete" :icon-size="16" label="Удалить лог" title="Удалить запись лога об отсутствующем файле" @down.stop @tap.stop="deleteMissingLog($event)" style="border-radius: 6px; padding: 3px 10px; scale: 1; flex-shrink: 0;"></oda-button>
509
+ </div>
510
+ <div class="preview" ~if="!compact && !expanded && !missingTargetPath && hasPreview && $file" ~is="previewTag" flex :$item="$file" :log="log" :log-content="logContent" style="user-select: text;" @expand-card.stop="expanded = true"></div>
511
+ <div class="preview" ~if="!compact && !expanded && !missingTargetPath && !$file && !hasTargetFilePath && logContent" flex style="padding: 6px 12px; white-space: pre-wrap; user-select: text;">{{logContent}}</div>
512
+ <div class="approval-box" ~if="!compact && !expanded && log?.chatMessage?.kind === 'approval'" horizontal style="align-items: center; gap: 8px; padding: 4px 12px 8px;">
513
+ <span ~if="approvalStatus === 'approved'" style="font-size: 12px; font-weight: 700; color: #059669;">✓ Утверждено</span>
514
+ <span ~if="approvalStatus === 'rejected'" style="font-size: 12px; font-weight: 700; color: #dc2626;">✕ Отклонено</span>
515
+ <oda-button ~if="approvalStatus === 'pending'" icon="icons:check" info-invert label="Утвердить" @down.stop @tap.stop="_resolveChatApproval('approve')" style="border-radius: 6px; padding: 3px 10px; scale: 1;"></oda-button>
516
+ <oda-button ~if="approvalStatus === 'pending'" icon="icons:close" label="Отклонить" @down.stop @tap.stop="_resolveChatApproval('reject')" style="border-radius: 6px; padding: 3px 10px; scale: 1;"></oda-button>
517
+ </div>
518
+ <div header ~if="!expanded && !missingTargetPath && includeFiles?.length" vertical style="padding: 8px; gap: 8px;">
519
+ <chat-item ~for="includeFiles" visible history compact :$file="$for.item"></chat-item>
520
+ </div>
521
+ <div class="body" flex vertical ~if="expanded && !missingTargetPath">
522
+ <div ~is="formTag" flex :$item="activeCardFile" @own-header="bodyHeader = true" @close-view="expanded = false"></div>
523
+ </div>
524
+ </div>
525
+ `,
526
+ isDm: false,
527
+ groupFirst: true,
528
+ groupLast: true,
529
+ peerLastReadId: 0,
530
+ _expandedFile: null,
531
+ get activeCardFile() {
532
+ return this._expandedFile || this.$file;
533
+ },
534
+ get isCall() {
535
+ const ext = String(this.ext || this.log?.ext || this.$file?.ext || '').toLowerCase();
536
+ return ext === 'call';
537
+ },
538
+ get isBubble() {
539
+ if (this.compact || this.expanded || this.history || this.isTask || this.isCall || this.isOperationLog || this.missingTargetPath)
540
+ return false;
541
+ return true;
542
+ },
543
+ get cmId() {
544
+ return Number(this.log?.chatMessage?.id) || 0;
545
+ },
546
+ get isPending() {
547
+ return Boolean(this.log?.chatMessage?.meta?.pending);
548
+ },
549
+ get sendError() {
550
+ return String(this.log?.chatMessage?.meta?.sendError || '');
551
+ },
552
+ get isEdited() {
553
+ return Boolean(this.log?.chatMessage?.meta?.editedAt);
554
+ },
555
+ get isReadByPeer() {
556
+ return Boolean(this.cmId > 0 && Number(this.peerLastReadId) >= this.cmId);
557
+ },
558
+ get authorColor() {
559
+ return authorColorFor(this.senderId || this.log?.sender || 'user');
560
+ },
561
+ get senderDisplayName() {
562
+ if (this.isAgentSender)
563
+ return this.agentSenderTitle;
564
+ const resolved = this._resolvedSenderObj;
565
+ if (resolved)
566
+ return resolved.DATA?.label || resolved.label || resolved.id || this.senderId || '';
567
+ return this.log?.chatMessage?.senderLabel || this.senderId || this.log?.sender || '';
568
+ },
569
+ flashHighlight() {
570
+ const b = this.$?.('.bubble') || this.$?.('.card');
571
+ if (!b) return;
572
+ b.style.transition = 'box-shadow .25s ease';
573
+ b.style.boxShadow = '0 0 0 3px var(--accent-color, #4f46e5)';
574
+ setTimeout(() => {
575
+ if (b) b.style.boxShadow = '';
576
+ }, 1400);
577
+ },
578
+ get replyInfo() {
579
+ const rp = this.log?.chatMessage?.meta?.replyPreview;
580
+ if (!rp || (!rp.id && !rp.content))
581
+ return null;
582
+ const preview = String(rp.content || '').trim() || (rp.attachmentsCount ? `Вложение (${rp.attachmentsCount})` : 'Сообщение');
583
+ let senderLabel = rp.senderLabel || '';
584
+ if (!senderLabel && rp.sender) {
585
+ if (rp.sender === '$twin')
586
+ senderLabel = 'Цифровой двойник';
587
+ else if (rp.sender === WORK.uid)
588
+ senderLabel = WORK.USER?.DATA?.label || WORK.USER?.label || WORK.uid;
589
+ else
590
+ senderLabel = rp.sender;
591
+ }
592
+ return { ...rp, senderLabel, preview };
593
+ },
594
+ get shortTime() {
595
+ const ms = +(this.log?.time || this.log?.chatMessage?.created || 0);
596
+ if (!Number.isFinite(ms) || ms <= 0)
597
+ return '';
598
+ const d = new Date(ms);
599
+ if (isNaN(d))
600
+ return '';
601
+ return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
602
+ },
603
+ get attachmentItems() {
604
+ const list = [];
605
+ const seen = new Set();
606
+ const add = (path, name = '') => {
607
+ const raw = String(path || '').trim();
608
+ if (!raw || raw.endsWith('.logs') || raw.endsWith('.task') || raw.endsWith('.call'))
609
+ return;
610
+ const norm = raw.startsWith('/') ? raw : '/' + raw;
611
+ if (seen.has(norm))
612
+ return;
613
+ seen.add(norm);
614
+ const fname = name || norm.split('/').pop() || 'file';
615
+ const ext = extOfPath(norm);
616
+ const cached = this._attCache?.[norm] || null;
617
+ list.push({
618
+ path: norm,
619
+ name: cached?.DATA?.label || cached?.label || fname,
620
+ ext,
621
+ isImage: IMAGE_EXTS.has(ext),
622
+ isVideo: VIDEO_EXTS.has(ext),
623
+ isAudio: AUDIO_EXTS.has(ext),
624
+ url: cached?.url || fileUrlOf(norm),
625
+ item: cached,
626
+ });
627
+ if (!cached && !this._attLoading?.[norm] && typeof WORK?.get_item === 'function') {
628
+ (this._attLoading ??= {})[norm] = true;
629
+ WORK.get_item(norm, 'info').then(it => {
630
+ if (it && (it.path || it.id || it.type)) {
631
+ (this._attCache ??= {})[norm] = it;
632
+ this.invalidate?.('attachmentItems');
633
+ this.render?.();
634
+ }
635
+ }).catch(() => {});
636
+ }
637
+ };
638
+ for (const a of (this.log?.chatMessage?.attachments || [])) {
639
+ if (a?.path) add(a.path, a.name);
640
+ }
641
+ const inc = this.log?.includes;
642
+ if (Array.isArray(inc)) {
643
+ for (const p of inc) add(p);
644
+ }
645
+ else if (typeof inc === 'string' && inc.trim()) {
646
+ const s = inc.trim();
647
+ let parsed = [s];
648
+ if (s[0] === '[') {
649
+ try { const arr = JSON.parse(s); if (Array.isArray(arr)) parsed = arr; } catch {}
650
+ }
651
+ else if (s.includes(',/')) parsed = s.split(',');
652
+ for (const p of parsed) add(p);
653
+ }
654
+ if (this.hasTargetFilePath && this.log?.path)
655
+ add(this.log.path);
656
+ return list;
657
+ },
658
+ async _ensureAttItem(att) {
659
+ if (att?.item) return att.item;
660
+ if (!att?.path || typeof WORK?.get_item !== 'function') return null;
661
+ const it = await WORK.get_item(att.path, 'info').catch(() => null);
662
+ if (it) {
663
+ (this._attCache ??= {})[att.path] = it;
664
+ att.item = it;
665
+ }
666
+ return it;
667
+ },
668
+ async openAttachment(att, e) {
669
+ e?.stopPropagation?.();
670
+ const item = await this._ensureAttItem(att);
671
+ if (!item) {
672
+ if (att?.url) window.open(att.url, '_blank');
673
+ return;
674
+ }
675
+ this._expandedFile = item;
676
+ this.expanded = true;
677
+ },
678
+ async downloadAttachment(att, e) {
679
+ e?.stopPropagation?.();
680
+ const item = await this._ensureAttItem(att);
681
+ if (item && typeof item.download === 'function') {
682
+ item.download();
683
+ return;
684
+ }
685
+ if (att?.url) {
686
+ const a = document.createElement('a');
687
+ a.href = att.url + (att.url.includes('?') ? '&' : '?') + 'download=1';
688
+ a.download = att.name || 'file';
689
+ a.click();
690
+ }
691
+ },
692
+ async openAttachmentMenu(att, e) {
693
+ e?.preventDefault?.();
694
+ e?.stopPropagation?.();
695
+ const item = await this._ensureAttItem(att);
696
+ const tools = [
697
+ { label: 'Открыть', icon: 'icons:open-in-new', execute: () => this.openAttachment(att) },
698
+ { label: 'Скачать', icon: 'icons:file-download', execute: () => this.downloadAttachment(att) },
699
+ ];
700
+ if (item && typeof item.execute === 'function') {
701
+ tools.push({ label: 'Открыть в отдельной вкладке', icon: 'icons:launch', execute: () => item.execute() });
702
+ }
703
+ if (typeof WORK?.showMenu === 'function') {
704
+ WORK.showMenu({
705
+ ...(item ? { $item: item, mode: 'both' } : { mode: 'tools' }),
706
+ customTools: tools,
707
+ }, e);
708
+ }
709
+ },
710
+ _messageActionDetail() {
711
+ return {
712
+ message: this.log?.chatMessage || null,
713
+ log: this.log,
714
+ senderId: this.senderId || this.log?.sender || '',
715
+ senderLabel: this.senderDisplayName || (this.isSender ? (WORK.USER?.DATA?.label || WORK.USER?.label || 'Вы') : 'Собеседник'),
716
+ content: this.logContent || '',
717
+ attachments: this.attachmentItems || [],
718
+ };
719
+ },
720
+ _replyAction(e) {
721
+ e?.stopPropagation?.();
722
+ this.dispatchEvent(new CustomEvent('chat-reply', {
723
+ bubbles: true,
724
+ composed: true,
725
+ detail: this._messageActionDetail(),
726
+ }));
727
+ },
728
+ openMessageMenu(e) {
729
+ const sel = typeof window?.getSelection === 'function' ? String(window.getSelection() || '').trim() : '';
730
+ if (e?.type === 'contextmenu' && sel)
731
+ return; // при выделении текста не мешаем стандартному копированию
732
+ e?.preventDefault?.();
733
+ e?.stopPropagation?.();
734
+ const cm = this.log?.chatMessage;
735
+ const tools = [];
736
+ if (cm?.id) {
737
+ tools.push({
738
+ label: 'Ответить',
739
+ icon: 'icons:reply',
740
+ execute: () => this._replyAction(),
741
+ });
742
+ }
743
+ if (this.logContent) {
744
+ tools.push({
745
+ label: 'Копировать текст',
746
+ icon: 'icons:content-copy',
747
+ execute: async () => {
748
+ try {
749
+ await navigator.clipboard?.writeText?.(this.logContent);
750
+ ODA.showMessage?.('Скопировано');
751
+ } catch { /* ignore */ }
752
+ },
753
+ });
754
+ }
755
+ if (cm?.id && this.isSender && (!cm.kind || ['text', 'dm', 'twin'].includes(cm.kind)) && !this.isPending && !this.sendError) {
756
+ tools.push({
757
+ label: 'Редактировать',
758
+ icon: 'icons:edit',
759
+ execute: () => this.dispatchEvent(new CustomEvent('chat-edit', {
760
+ bubbles: true,
761
+ composed: true,
762
+ detail: this._messageActionDetail(),
763
+ })),
764
+ });
765
+ }
766
+ if (cm?.id && this.isSender) {
767
+ tools.push({
768
+ label: 'Удалить',
769
+ icon: 'icons:delete',
770
+ execute: () => this.dispatchEvent(new CustomEvent('chat-delete', {
771
+ bubbles: true,
772
+ composed: true,
773
+ detail: this._messageActionDetail(),
774
+ })),
775
+ });
776
+ }
777
+ if (tools.length && typeof WORK?.showMenu === 'function') {
778
+ WORK.showMenu({ mode: 'tools', customTools: tools }, e);
779
+ }
780
+ },
781
+ scrollToReply(e) {
782
+ e?.stopPropagation?.();
783
+ const id = Number(this.replyInfo?.id || this.log?.chatMessage?.replyTo || 0);
784
+ if (!id) return;
785
+ this.dispatchEvent(new CustomEvent('chat-scroll-to-message', {
786
+ bubbles: true,
787
+ composed: true,
788
+ detail: { messageId: id },
789
+ }));
790
+ },
791
+ _retryFailedSend(e) {
792
+ e?.stopPropagation?.();
793
+ this.dispatchEvent(new CustomEvent('chat-retry-send', {
794
+ bubbles: true,
795
+ composed: true,
796
+ detail: this._messageActionDetail(),
797
+ }));
798
+ },
799
+ _dismissFailedSend(e) {
800
+ e?.stopPropagation?.();
801
+ this.dispatchEvent(new CustomEvent('chat-dismiss-send', {
802
+ bubbles: true,
803
+ composed: true,
804
+ detail: this._messageActionDetail(),
805
+ }));
806
+ },
807
+ get formTag() {
808
+ return Promise.resolve(this.activeCardFile).then(async file => {
809
+ if (!file)
810
+ return 'item-node';
811
+ const name = file.form || 'file';
812
+ const view = await file.get_item('/~/handlers//form/' + name);
813
+ const ext = String(file.ext || '').toLowerCase();
814
+ const is = ext ? `item-${name}-${ext}` : `item-${name}`;
815
+ await view?.importView?.(is);
816
+ if (!customElements.get(is)) {
817
+ console.error(`[chat-item] вид '${name}' не зарегистрирован как <${is}>`);
818
+ return 'item-node';
819
+ }
820
+ return is;
821
+ });
822
+ },
823
+ get includeFiles() {
824
+ // карточка задачи показывает все файлы сама (превью .task: вложения + созданное агентом) — вложения записи журнала не дублируем
825
+ if (String(this.$file?.ext || '').toLowerCase() === 'task')
826
+ return [];
827
+ const raw = this.log?.includes;
828
+ let paths = raw;
829
+ if (!Array.isArray(paths)) {
830
+ if (typeof raw !== 'string' || !raw.trim())
831
+ return [];
832
+ const s = raw.trim();
833
+ if (s[0] === '[') {
834
+ try {
835
+ const parsed = JSON.parse(s);
836
+ paths = Array.isArray(parsed) ? parsed : [s];
837
+ } catch {
838
+ paths = s.includes(',/') ? s.split(',') : [s];
839
+ }
840
+ } else
841
+ paths = s.includes(',/') ? s.split(',') : [s];
842
+ }
843
+ if (!paths.length)
844
+ return [];
845
+ return Promise.all(paths.map(p => {
846
+ p = String(p ?? '').trim();
847
+ if (!p)
848
+ return null;
849
+ return WORK.get_item(p.startsWith('/') ? p : '/' + p, 'info');
850
+ })).then(items => items.filter(Boolean));
851
+ },
852
+ /** Развёрнутое представление со своей шапкой (событие own-header) — своя полоса title не нужна; закрытие — close-view. */
853
+ bodyHeader: false,
854
+ get expanderIcon(){
855
+ return this.expanded?'icons:close':'box:i-expand';
856
+ },
857
+ expanded: {
858
+ $attr: true,
859
+ $def: false,
860
+ set(n) {
861
+ try {
862
+ this.dispatchEvent(new CustomEvent('chat-item-expanded', {
863
+ bubbles: true,
864
+ composed: true,
865
+ detail: { expanded: Boolean(n), card: this },
866
+ }));
867
+ }
868
+ catch { /* ignore */ }
869
+ if (n) {
870
+ const root = this.parentElement?.parentElement?.parentElement || this.getRootNode?.()?.host;
871
+ const allCards = root?.$$ ? root.$$('chat-item') : (this.parentElement?.querySelectorAll?.('chat-item') || []);
872
+ for (const other of allCards) {
873
+ if (other && other !== this && other.expanded)
874
+ other.expanded = false;
875
+ }
876
+ return;
877
+ }
878
+ this._expandedFile = null;
879
+ if (!this._rebindClosing) {
880
+ let p = this.parentElement || this.host || this.getRootNode?.()?.host;
881
+ while (p && p.localName !== 'chat-day')
882
+ p = p.parentElement || p.host || p.getRootNode?.()?.host;
883
+ const myId = this._currentItemIdentity || '';
884
+ if (p && p._expandedTaskKey && myId === 'task:' + p._expandedTaskKey)
885
+ p._expandedTaskKey = '';
886
+ }
887
+ this.bodyHeader = false;
888
+ this._resetBodyCache();
889
+ },
890
+ },
891
+ get isAgentSender() {
892
+ if (this.log?.sender === '$twin' || this.log?.chatMessage?.sender === '$twin')
893
+ return true;
894
+ if (this.log?.sender === 'WORK')
895
+ return true;
896
+ const act = String(this.log?.actor || '');
897
+ if (act === 'AI' || act.startsWith('/MODULES/Модели/'))
898
+ return true;
899
+ if (Array.isArray(this.log?.receivers) && this.log?.receivers.length === 1 && this.log.receivers[0] === this.log?.sender && !this.log?.path)
900
+ return true;
901
+ return false;
902
+ },
903
+ get agentSenderTitle() {
904
+ if (this.log?.sender === '$twin' || this.log?.chatMessage?.sender === '$twin') {
905
+ const nl = this.log?.chatMessage?.nodeLabel;
906
+ return nl ? `Цифровой двойник «${nl}»` : 'Цифровой двойник узла';
907
+ }
908
+ if (this.log?.sender === 'WORK')
909
+ return 'Система WORK';
910
+ const act = String(this.log?.actor || '');
911
+ if (this.log?.actorLabel)
912
+ return String(this.log.actorLabel);
913
+ if (act.startsWith('/MODULES/Модели/'))
914
+ return 'ИИ-агент (' + act.split('/').pop() + ')';
915
+ return 'ИИ-агент WORK';
916
+ },
917
+ get approvalStatus() {
918
+ return this.log?.chatMessage?.meta?.status || 'pending';
919
+ },
920
+ async _resolveChatApproval(action) {
921
+ const cm = this.log?.chatMessage;
922
+ if (!cm?.id || !cm?.threadId)
923
+ return;
924
+ const owner = this._resolveFeedOwner();
925
+ if (!owner?.fetch)
926
+ return;
927
+ try {
928
+ const res = await owner.fetch('chat_action', { threadId: cm.threadId, messageId: cm.id, action });
929
+ if (res?.meta) {
930
+ this.log = {
931
+ ...this.log,
932
+ chatMessage: { ...cm, meta: res.meta },
933
+ };
934
+ this.render?.();
935
+ }
936
+ }
937
+ catch (err) {
938
+ console.warn('[chat-item] chat_action:', err);
939
+ }
940
+ },
941
+ get isSender(){
942
+ if (this.isAgentSender)
943
+ return false;
944
+ return this.senderId === WORK.uid;
945
+ },
946
+ get isTask() {
947
+ const ext = String(this.ext || this.log?.ext || this.$file?.ext || '').toLowerCase();
948
+ if (ext === 'task')
949
+ return true;
950
+ const p = String(this.log?.path || this.$item?.path || this.$item?.id || '');
951
+ return p.endsWith('.task');
952
+ },
953
+ get isOperationLog() {
954
+ const ext = String(this.log?.ext || '').toLowerCase();
955
+ return ext === 'operation' || ext === 'object';
956
+ },
957
+ /**
958
+ * Раскладка на ленте чата:
959
+ * - исходящие от текущего пользователя (isSender && !isTask) — справа;
960
+ * - входящие от других пользователей / двойника (!isSender && !isTask) — слева;
961
+ * - задачи ИИ (isTask) — по центру с отступом слева и справа.
962
+ */
963
+ get cardLayoutStyle() {
964
+ if (this.expanded || this.compact) {
965
+ return { order: 1 };
966
+ }
967
+ if (this.isTask) {
968
+ return {
969
+ order: 1,
970
+ marginLeft: 'auto',
971
+ marginRight: 'auto',
972
+ width: '100%',
973
+ maxWidth: 'min(820px, 100%)',
974
+ boxSizing: 'border-box',
975
+ };
976
+ }
977
+ if (this.isSender) {
978
+ return {
979
+ order: 1,
980
+ marginLeft: 'auto',
981
+ marginRight: '0px',
982
+ maxWidth: '78%',
983
+ };
984
+ }
985
+ return {
986
+ order: 1,
987
+ marginLeft: '0px',
988
+ marginRight: 'auto',
989
+ maxWidth: '78%',
990
+ };
991
+ },
992
+ async onCardTap(e) {
993
+ if (!this.isOperationLog || !this.log)
994
+ return;
995
+ e?.stopPropagation?.();
996
+ const rawPath = String(this.log.path || '');
997
+ const classPath = this.log.classPath || rawPath.split('/').slice(0, -1).join('/');
998
+ const objectId = this.log.objectId || rawPath.split('/').pop();
999
+ if (!classPath || !objectId)
1000
+ return;
1001
+ const clsItem = await WORK.get_item(classPath).catch(() => null);
1002
+ if (!clsItem)
1003
+ return;
1004
+ const wf = document.querySelector?.('pages-form')?.$?.('work-form') || this.domHost?.domHost;
1005
+ if (wf && typeof wf.openFormTab === 'function')
1006
+ await wf.openFormTab(clsItem, { view: 'objects/object', objectId });
1007
+ else if (typeof window.top?.execute === 'function')
1008
+ window.top.execute(clsItem, { view: 'objects/object', objectId });
1009
+ },
1010
+ colorMode: {
1011
+ $def: 'light',
1012
+ set(n) {
1013
+ const targets = [this.$('.card'), this.$('.body')].filter(Boolean);
1014
+ if (this._color) {
1015
+ for (const el of targets)
1016
+ el.removeAttribute(this._color);
1017
+ }
1018
+ this._color = n || '';
1019
+ if (this._color) {
1020
+ for (const el of targets)
1021
+ el.setAttribute(this._color, '');
1022
+ }
1023
+ }
1024
+ },
1025
+ attached() {
1026
+ this.async(() => {
1027
+ this.colorMode = this._color || 'light';
1028
+ });
1029
+ this._watchLog();
1030
+ this._revealIfReady();
1031
+ },
1032
+ history: {
1033
+ $attr: true,
1034
+ $def: false,
1035
+ set(n) {
1036
+ if (n)
1037
+ this.applyHistoryFile();
1038
+ }
1039
+ },
1040
+ compact: {
1041
+ $attr: true,
1042
+ $def: false,
1043
+ },
1044
+ visible:{
1045
+ $def: false,
1046
+ $attr: true,
1047
+ },
1048
+ previewIsReady: false,
1049
+ senderIsReady: false,
1050
+ _senderFromRef(ref) {
1051
+ if (!ref) return '';
1052
+ const path = ref.path;
1053
+ if (path) {
1054
+ const parsed = CORE.$file.parseHistoryEntryPath(path);
1055
+ if (parsed?.userId) return parsed.userId;
1056
+ }
1057
+ const id = ref.id || (path ? String(path).split('/').pop() : '') || '';
1058
+ const extDot = id.lastIndexOf('.');
1059
+ const name = extDot > 0 ? id.slice(0, extDot) : id;
1060
+ const nameParts = name.split('.');
1061
+ if (nameParts.length > 1 && /^\d+$/.test(nameParts[0]))
1062
+ return nameParts.slice(1).join('.');
1063
+ return '';
1064
+ },
1065
+ _applySenderFromRef(ref) {
1066
+ const uid = this._senderFromRef(ref);
1067
+ if (uid)
1068
+ this.senderId = uid;
1069
+ else if (!ref)
1070
+ this._markSenderReady();
1071
+ },
1072
+ _markSenderReady() {
1073
+ this.senderIsReady = true;
1074
+ this._revealIfReady();
1075
+ },
1076
+ _revealIfReady() {
1077
+ if (this.senderIsReady)
1078
+ this.visible = true;
1079
+ },
1080
+ previewTag: 'item-node',
1081
+ hasPreview: false,
1082
+ missingTargetPath: '',
1083
+ get hasTargetFilePath() {
1084
+ const p = String(this.log?.path || '').trim();
1085
+ const ext = String(this.log?.ext || '').toLowerCase();
1086
+ return Boolean(p && !p.endsWith('.logs') && ext !== 'operation' && ext !== 'object');
1087
+ },
1088
+ get missingTargetLabel() {
1089
+ const p = String(this.missingTargetPath || '').trim();
1090
+ if (!p)
1091
+ return '';
1092
+ return p.split('/').filter(Boolean).pop() || p;
1093
+ },
1094
+ _resolveFeedOwner() {
1095
+ let p = this.parentElement || this.host || this.getRootNode?.()?.host;
1096
+ while (p) {
1097
+ const candidate = p.$item;
1098
+ if (candidate && candidate !== this.$item && typeof candidate.fetch === 'function')
1099
+ return candidate;
1100
+ p = p.parentElement || p.host || p.getRootNode?.()?.host;
1101
+ }
1102
+ const wf = typeof document !== 'undefined' ? document.querySelector?.('pages-form')?.$?.('work-form') : null;
1103
+ if (wf?.currentItem && typeof wf.currentItem.fetch === 'function')
1104
+ return wf.currentItem;
1105
+ if (typeof window !== 'undefined' && window.$context && typeof window.$context.fetch === 'function')
1106
+ return window.$context;
1107
+ return globalThis.WORK;
1108
+ },
1109
+ get isAdminRole() {
1110
+ if (globalThis.WORK?.DEV_MODE)
1111
+ return true;
1112
+ const owner = this._resolveFeedOwner();
1113
+ if (owner?.type === '$user')
1114
+ return true;
1115
+ if (this.log?.sender && globalThis.WORK?.uid && this.log.sender === globalThis.WORK.uid)
1116
+ return true;
1117
+ const pdpRole = owner?.role;
1118
+ if (pdpRole)
1119
+ return pdpRole === 'BOSS';
1120
+ const wf = typeof document !== 'undefined' ? document.querySelector?.('pages-form')?.$?.('work-form') : null;
1121
+ if (wf?.activeRole)
1122
+ return wf.activeRole === 'BOSS';
1123
+ return true;
1124
+ },
1125
+ async deleteMissingLog(e) {
1126
+ e?.stopPropagation?.();
1127
+ e?.preventDefault?.();
1128
+ const owner = this._resolveFeedOwner();
1129
+ if (!owner || typeof owner.fetch !== 'function')
1130
+ return;
1131
+ const payload = {
1132
+ stubPath: this.log?.logsFilePath || this.$item?.path || '',
1133
+ path: this.missingTargetPath || this.log?.path || '',
1134
+ time: this.log?.time || 0,
1135
+ sender: this.log?.sender || '',
1136
+ };
1137
+ try {
1138
+ await owner.fetch('delete_log_entry', { ...payload, role: 'BOSS' });
1139
+ let p = this.parentElement || this.host || this.getRootNode?.()?.host;
1140
+ while (p && p.localName !== 'chat-day')
1141
+ p = p.parentElement || p.host || p.getRootNode?.()?.host;
1142
+ this.style.display = 'none';
1143
+ if (p && Array.isArray(p.logItems)) {
1144
+ const curId = this.$item?.id;
1145
+ const targetPath = this.missingTargetPath || this.log?.path || '';
1146
+ if (curId && p._wrappedById instanceof Map)
1147
+ p._wrappedById.delete(curId);
1148
+ p.logItems = p.logItems.filter(it => {
1149
+ if (it === this.$item)
1150
+ return false;
1151
+ if (curId && it?.id === curId)
1152
+ return false;
1153
+ if (targetPath && (it?.path === targetPath || it?.logRow?.path === targetPath))
1154
+ return false;
1155
+ return true;
1156
+ });
1157
+ p.invalidate?.('logs');
1158
+ p.render?.();
1159
+ }
1160
+ this.remove?.();
1161
+ }
1162
+ catch (err) {
1163
+ console.warn('[chat-item] delete_log_entry:', err);
1164
+ }
1165
+ },
1166
+ _bodyCacheKeys: ['itemBody', 'fileLabel', 'fileTime', 'shortTime', 'sender', 'senderDisplayName', 'log', 'logContent', 'isText', 'hideAvatar', 'attachmentItems', 'replyInfo', 'isBubble'],
1167
+ _resetBodyCache() {
1168
+ this.invalidate(...this._bodyCacheKeys);
1169
+ },
1170
+ log: null,
1171
+ get logContent() {
1172
+ return this.log?.content ?? '';
1173
+ },
1174
+ get isText() {
1175
+ return this.ext === 'txt' || this.ext === 'md';
1176
+ },
1177
+ get fileTime() {
1178
+ if (this.compact)
1179
+ return '';
1180
+ return Promise.resolve(this.itemBody).then(body => {
1181
+ const ms = +(body?.time || this.log?.time);
1182
+ if (!Number.isFinite(ms) || ms <= 0)
1183
+ return '';
1184
+ const d = new Date(ms);
1185
+ if (isNaN(d))
1186
+ return '';
1187
+ const time = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
1188
+ const dd = String(d.getDate()).padStart(2, '0');
1189
+ const mm = String(d.getMonth() + 1).padStart(2, '0');
1190
+ return dd + '.' + mm + ' ' + time;
1191
+ });
1192
+ },
1193
+ get ext() {
1194
+ if (this._includeFile?.ext)
1195
+ return this._includeFile.ext;
1196
+ const path = this.log?.path || this._includeFile?.path || '';
1197
+ const id = String(path).split('/').pop() || '';
1198
+ const idx = id.lastIndexOf('.');
1199
+ return idx > -1 ? id.slice(idx + 1) : '';
1200
+ },
1201
+ async buildHistoryBody($file) {
1202
+ $file = await Promise.resolve($file);
1203
+ if (!$file?.path)
1204
+ return null;
1205
+ const parsed = CORE.$file.parseHistoryEntryPath($file.path) || {};
1206
+ return {
1207
+ path: $file.path,
1208
+ time: +parsed.timestamp || 0,
1209
+ sender: parsed.userId || '',
1210
+ type: '$file',
1211
+ ext: this.ext,
1212
+ };
1213
+ },
1214
+ isHistoryFile($file = this._includeFile) {
1215
+ return !!$file?.path?.includes('/history/');
1216
+ },
1217
+ async applyHistoryFile() {
1218
+ if (!this.history || !this._includeFile)
1219
+ return null;
1220
+ const body = await this.buildHistoryBody(this._includeFile);
1221
+ if (!body)
1222
+ return null;
1223
+ this._historyBody = body;
1224
+ if (body.sender)
1225
+ this.senderId = body.sender;
1226
+ else
1227
+ this._markSenderReady();
1228
+ this.log = body;
1229
+ this.previewIsReady = true;
1230
+ this.render();
1231
+ return body;
1232
+ },
1233
+ get itemBody() {
1234
+ if (this.log?.time)
1235
+ return Promise.resolve(this.log);
1236
+ if (this.history && this._includeFile) {
1237
+ if (this._historyBody)
1238
+ return Promise.resolve(this._historyBody);
1239
+ return this.applyHistoryFile().catch(e => {
1240
+ console.warn('[chat-item] history', e);
1241
+ return null;
1242
+ });
1243
+ }
1244
+ return Promise.resolve(this.$item).then(item => {
1245
+ if (!item)
1246
+ return null;
1247
+ if (typeof item.load !== 'function')
1248
+ return null;
1249
+ return item.load().then(raw => {
1250
+ const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
1251
+ if (!data.path && item.path && item.ext !== 'logs')
1252
+ data.path = item.path;
1253
+ // сам .task-файл (карточка принята в ленту напрямую): время — из имени файла <мс>.<uid>.task, как у записи журнала
1254
+ if (!data.time && item.ext === 'task') {
1255
+ const ts = parseInt(String(item.id || '').split('.')[0], 10);
1256
+ if (ts > 0)
1257
+ data.time = ts;
1258
+ }
1259
+ if (data.sender && !this.senderIsReady)
1260
+ this.senderId = data.sender;
1261
+ else if (!this.senderIsReady)
1262
+ this._markSenderReady();
1263
+ this.previewIsReady = true;
1264
+ this.log = data;
1265
+ this.render();
1266
+ return data;
1267
+ }).catch(e => {
1268
+ console.warn('[chat-item] load', e);
1269
+ return null;
1270
+ });
1271
+ });
1272
+ },
1273
+ get fileLabel() {
1274
+ if (this._expandedFile?.path)
1275
+ return this._labelForItem(this._expandedFile.path, this._expandedFile);
1276
+ if (this._includeFile?.path)
1277
+ return this._labelForItem(this._includeFile.path, this._includeFile);
1278
+ return Promise.resolve(this.itemBody).then(body => this._labelForLog(body));
1279
+ },
1280
+ _labelForItem(path, file) {
1281
+ if (String(path || '').includes('/history/'))
1282
+ return CORE.historyEntryLabel(path);
1283
+ const ext = String(file?.ext || this.ext || '').toLowerCase();
1284
+ if (this.compact && !['task', 'ics', 'eml'].includes(ext))
1285
+ return file?.DATA?.label || file?.id || String(path || '').split('/').pop() || '';
1286
+ return this._nameFromDataFile(file);
1287
+ },
1288
+ async _labelForLog(body) {
1289
+ if (!body)
1290
+ return '';
1291
+ if (body.chatMessage) {
1292
+ if (body.chatMessage.kind === 'approval')
1293
+ return 'Запрос подтверждения';
1294
+ return body.chatMessage.sender === '$twin' ? (body.chatMessage.nodeLabel ? `Двойник «${body.chatMessage.nodeLabel}»` : 'Цифровой двойник') : '';
1295
+ }
1296
+ if (String(body.path || '').includes('/history/'))
1297
+ return CORE.historyEntryLabel(body.path);
1298
+ try {
1299
+ const raw = body.content;
1300
+ const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
1301
+ if (data?.name)
1302
+ return data.name;
1303
+ } catch { /* content не JSON точки */ }
1304
+ return (await this._nameFromDataFile(await this.$file)) || body.ext || '';
1305
+ },
1306
+ async _nameFromDataFile(file) {
1307
+ const ext = String(file?.ext || '').toLowerCase();
1308
+ if (!['task', 'ics', 'eml'].includes(ext))
1309
+ return file?.DATA?.label || file?.id || file?.ext || '';
1310
+ if (!file?.load)
1311
+ return file?.ext || '';
1312
+ try {
1313
+ const raw = await file.load();
1314
+ const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
1315
+ if (data?.name)
1316
+ return data.name;
1317
+ } catch { /* не JSON */ }
1318
+ return file.ext || '';
1319
+ },
1320
+ async loadPreview($file) {
1321
+ if (!$file) {
1322
+ this.hasPreview = !this.compact;
1323
+ this.previewIsReady = true;
1324
+ this.render();
1325
+ return;
1326
+ }
1327
+ const ext = String($file?.ext || this.ext || '').toLowerCase();
1328
+ if (this.compact || !CHAT_PREVIEW_EXTS.has(ext)) {
1329
+ this.hasPreview = false;
1330
+ this.previewTag = 'item-node';
1331
+ this.previousElementSibling?.invalidate?.('hideAvatar');
1332
+ this.previewIsReady = true;
1333
+ this.render();
1334
+ return;
1335
+ }
1336
+ try {
1337
+ this.hasPreview = await CORE.$file.loadPreview($file);
1338
+ if (this.hasPreview)
1339
+ this.previewTag = ($file?.ext || 'file') + '-preview';
1340
+ else
1341
+ this.previewTag = 'item-node';
1342
+ }
1343
+ catch (e) {
1344
+ console.warn('[chat-item] loadPreview error:', e.message);
1345
+ this.hasPreview = false;
1346
+ this.previewTag = 'item-node';
1347
+ }
1348
+ finally {
1349
+ // соседа DOM реактивность не видит — hideAvatar предыдущей карточки сбрасываем явно
1350
+ this.previousElementSibling?.invalidate?.('hideAvatar');
1351
+ this.previewIsReady = true;
1352
+ this.render();
1353
+ }
1354
+ },
1355
+ $file: {
1356
+ get() {
1357
+ if (this._includeFile)
1358
+ return this._includeFile;
1359
+ if (this.history || (!this.$item && !this.log?.path))
1360
+ return null;
1361
+ // Если $item уже является самим файлом .task (принят через adoptTask), используем его напрямую без ожидания itemBody
1362
+ if (this.$item && !this.$item.logRow && (this.$item.ext === 'task' || String(this.$item.id || '').endsWith('.task'))) {
1363
+ const taskFile = this.$item;
1364
+ this.missingTargetPath = '';
1365
+ return this.loadPreview(taskFile).then(() => taskFile);
1366
+ }
1367
+ return Promise.resolve(this.itemBody).then(async body => {
1368
+ if (body?.chatMessage)
1369
+ return null;
1370
+ if (!body?.path || String(body.path).endsWith('.logs') || body?.ext === 'operation' || body?.ext === 'object') {
1371
+ if (body?.ext === 'operation' || body?.ext === 'object')
1372
+ this.hasPreview = true;
1373
+ return null;
1374
+ }
1375
+ let $file = null;
1376
+ try {
1377
+ $file = await WORK.get_item(body.path, 'info');
1378
+ }
1379
+ catch {
1380
+ $file = null;
1381
+ }
1382
+ if (!$file || (typeof $file === 'object' && !$file.path && !$file.id && !$file.type)) {
1383
+ this.missingTargetPath = String(body.path);
1384
+ this.hasPreview = false;
1385
+ this.previewIsReady = true;
1386
+ this.render();
1387
+ return null;
1388
+ }
1389
+ this.missingTargetPath = '';
1390
+ if ($file && !$file.id && $file.path) {
1391
+ $file.DATA ??= {};
1392
+ $file.DATA.id = $file.path.split('/').pop();
1393
+ }
1394
+ await this.loadPreview($file);
1395
+ return $file;
1396
+ })
1397
+ },
1398
+ set($file) {
1399
+ const run = async (file) => {
1400
+ if (file && this._includeFile === file && (this.previewIsReady || this._loadingIncludeFile === file))
1401
+ return;
1402
+ this._loadingIncludeFile = file;
1403
+ this._includeFile = file;
1404
+ this._historyBody = null;
1405
+ this._resetBodyCache();
1406
+ if (this[R]?.cache)
1407
+ this[R].cache.$file = file;
1408
+ this.previewIsReady = false;
1409
+ this.senderIsReady = false;
1410
+ this._applySenderFromRef(file);
1411
+ await this.loadPreview(file);
1412
+ if (this.history) {
1413
+ await this.applyHistoryFile();
1414
+ }
1415
+ else if (this.log?.time) {
1416
+ this.previewIsReady = true;
1417
+ this.render();
1418
+ }
1419
+ if (this[R]?.cache && this._includeFile === file)
1420
+ this[R].cache.$file = file;
1421
+ };
1422
+ if ($file != null && typeof $file.then === 'function')
1423
+ $file.then(run).catch(() => {});
1424
+ else
1425
+ run($file).catch(() => {});
1426
+ }
1427
+ },
1428
+ _identityOfItem(item) {
1429
+ if (!item)
1430
+ return '';
1431
+ const targetPath = String(item.logRow?.path || item.DATA?.logRow?.path || item.path || '');
1432
+ const taskMatch = targetPath.match(/([^/\\]+\.task)$/i) || String(item.id || '').match(/([^/\\]+\.task)$/i);
1433
+ if (taskMatch)
1434
+ return 'task:' + taskMatch[1];
1435
+ const logsTask = String(item.id || '').replace(/\.logs$/i, '.task');
1436
+ if (logsTask.endsWith('.task') && (item.logRow?.ext === 'task' || item.DATA?.logRow?.ext === 'task'))
1437
+ return 'task:' + logsTask;
1438
+ return String(item.path || item.id || '');
1439
+ },
1440
+ $item: {
1441
+ $def: null,
1442
+ set(n) {
1443
+ const nextKey = n ? String(n.path || n.id || '') : '';
1444
+ const nextIdentity = this._identityOfItem(n);
1445
+ if (this._currentItemIdentity && nextIdentity !== this._currentItemIdentity && this.expanded) {
1446
+ this._rebindClosing = true;
1447
+ try {
1448
+ this.expanded = false;
1449
+ }
1450
+ finally {
1451
+ this._rebindClosing = false;
1452
+ }
1453
+ }
1454
+ this._currentItemIdentity = nextIdentity;
1455
+ if (nextKey && this._currentItemKey === nextKey && this.log) {
1456
+ const nextRow = n?.logRow || n?.DATA?.logRow;
1457
+ if (nextRow && typeof nextRow === 'object' && typeof nextRow.then !== 'function') {
1458
+ this.log = { ...nextRow };
1459
+ this.invalidate('sender', 'isAgentSender', 'isTask', 'isCall', 'fileLabel', 'fileTime', 'shortTime', 'logContent', 'attachmentItems', 'replyInfo', 'isPending', 'sendError', 'isEdited', 'isReadByPeer', 'cmId', 'isBubble');
1460
+ this.render?.();
1461
+ }
1462
+ return;
1463
+ }
1464
+ this._currentItemKey = nextKey;
1465
+ this.missingTargetPath = '';
1466
+ this._attCache = null;
1467
+ this._attLoading = null;
1468
+ this._resolvedSenderObj = null;
1469
+ this._hasResolvedSender = false;
1470
+ this._resetBodyCache();
1471
+ this.previewIsReady = false;
1472
+ this.senderIsReady = false;
1473
+ this._includeFile = null;
1474
+ this.log = null;
1475
+ this._unwatchLog();
1476
+ this._applySenderFromRef(n);
1477
+ const logRow = n?.logRow || n?.DATA?.logRow;
1478
+ if (logRow && typeof logRow === 'object' && typeof logRow.then !== 'function') {
1479
+ const data = { ...logRow };
1480
+ this.log = data;
1481
+ this.invalidate('sender', 'isAgentSender', 'isTask', 'isCall', 'fileLabel', 'fileTime', 'shortTime', 'logContent', 'attachmentItems', 'replyInfo', 'isPending', 'sendError', 'isEdited', 'isReadByPeer', 'cmId', 'isBubble');
1482
+ if (data.sender && !this.senderIsReady)
1483
+ this.senderId = data.sender;
1484
+ else if (!this.senderIsReady)
1485
+ this._markSenderReady();
1486
+ this.previewIsReady = true;
1487
+ this.render();
1488
+ return;
1489
+ }
1490
+ if (n?.listen && n?.id?.endsWith?.('.logs')) {
1491
+ const applyLog = raw => {
1492
+ const data = typeof raw === 'string' ? JSON.parse(raw) : raw;
1493
+ if (!data?.time)
1494
+ return;
1495
+ this.log = { ...data };
1496
+ this.invalidate('sender', 'isAgentSender', 'isTask', 'isCall', 'fileLabel', 'fileTime', 'shortTime', 'logContent', 'attachmentItems', 'replyInfo', 'isPending', 'sendError', 'isEdited', 'isReadByPeer', 'cmId', 'isBubble');
1497
+ if (data.sender && !this.senderIsReady)
1498
+ this.senderId = data.sender;
1499
+ else if (!this.senderIsReady)
1500
+ this._markSenderReady();
1501
+ this.render();
1502
+ };
1503
+ if (typeof n.load === 'function') {
1504
+ n.load().then(applyLog).catch(() => {});
1505
+ }
1506
+ this._watched = { item: n, fn: () => n.load().then(applyLog).catch(() => {}) };
1507
+ this._watchLog();
1508
+ }
1509
+ }
1510
+ },
1511
+ /** Подписка на изменения записи: ровно одна, снимается при смене элемента и уходе из DOM. */
1512
+ _watchLog() {
1513
+ const w = this._watched;
1514
+ if (w && !w.on) {
1515
+ w.item.listen('changed', w.fn);
1516
+ w.on = true;
1517
+ }
1518
+ },
1519
+ _unwatchLog() {
1520
+ const w = this._watched;
1521
+ if (w?.on)
1522
+ w.item.unlisten('changed', w.fn);
1523
+ this._watched = null;
1524
+ },
1525
+ detached() {
1526
+ const w = this._watched;
1527
+ if (w?.on) {
1528
+ w.item.unlisten('changed', w.fn);
1529
+ w.on = false;
1530
+ }
1531
+ try {
1532
+ this.dispatchEvent(new CustomEvent('chat-item-expanded', {
1533
+ bubbles: true,
1534
+ composed: true,
1535
+ detail: { expanded: false, card: this },
1536
+ }));
1537
+ }
1538
+ catch { /* ignore */ }
1539
+ },
1540
+ senderId: {
1541
+ $type: String,
1542
+ set(n) {
1543
+ this.senderIsReady = true;
1544
+ this._revealIfReady();
1545
+ }
1546
+ },
1547
+ _hasResolvedSender: false,
1548
+ get hasSenderAvatar() {
1549
+ return Boolean(this.isAgentSender || this._hasResolvedSender);
1550
+ },
1551
+ get sender() {
1552
+ return Promise.resolve(this.itemBody).then(async body => {
1553
+ if (this.isAgentSender) {
1554
+ this._hasResolvedSender = false;
1555
+ if (!this.senderIsReady)
1556
+ this._markSenderReady();
1557
+ return null;
1558
+ }
1559
+ if (!body?.sender) {
1560
+ this._hasResolvedSender = false;
1561
+ if (!this.senderIsReady)
1562
+ this._markSenderReady();
1563
+ return null;
1564
+ }
1565
+ let users = await WORK.users;
1566
+ const found = users.find(u => u.id === body.sender) || null;
1567
+ this._resolvedSenderObj = found;
1568
+ this._hasResolvedSender = Boolean(found);
1569
+ this.senderId = body.sender;
1570
+ this.invalidate?.('hasSenderAvatar', 'senderDisplayName');
1571
+ this.render?.();
1572
+ return found;
1573
+ })
1574
+ },
1575
+ get hideAvatar() {
1576
+ return this.isTask;
1577
+ },
1578
+ })