@kabxx/dsh-message-revision 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.js ADDED
@@ -0,0 +1,1067 @@
1
+ window.__ModuleLoader__.load({
2
+ id: '@kabxx/dsh-message-revision',
3
+ factory(require) {
4
+ const { Fragment, createElement: h, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } = require('react');
5
+ const locale = 'messageRevision';
6
+ const strings = {
7
+ zh: {
8
+ edit: '编辑消息', cancel: '取消',
9
+ busy: '回复生成中,请先停止或等待完成。', done: '消息已更新并重发',
10
+ cleanupPending: '消息已更新并重发,部分旧记录待清理。',
11
+ unchanged: '内容未修改', tooLong: '消息不能超过 200,000 个字符。',
12
+ uploadWait: '附件仍在上传或上传失败,请处理后再发送。',
13
+ fileUnavailable: '当前会话无法添加附件。', fileDirectory: '不支持直接添加文件夹,请选择单个文件。',
14
+ anotherEdit: '请先完成或取消当前编辑。',
15
+ missing: '未找到该消息,请刷新后重试。', unsupported: '此消息不支持编辑。',
16
+ locked: '会话正被占用,暂时无法编辑。', changed: '会话状态已变更,请重新打开编辑框。',
17
+ 'composer-unavailable': '输入框未能加载,请刷新页面后重试。',
18
+ 'toolbar-update': '插件前后端版本不一致,请重新加载插件。',
19
+ 'child-conflict': '关联的子智能体会话无法回退,暂不支持编辑此消息。',
20
+ syncing: '消息已更新,请重新打开会话刷新视图。',
21
+ draftSaved: '草稿已保留。',
22
+ draftConflict: '原消息已变更,请先复制草稿后关闭重试。',
23
+ textPart: '正文', sendPart: '发送',
24
+ 'reconnect-unavailable': '会话连接不可用,请重新打开会话。',
25
+ 'authentication-required': '请先完成登录认证。', failed: '编辑失败,请重试。',
26
+ },
27
+ en: {
28
+ edit: 'Edit message', cancel: 'Cancel',
29
+ busy: 'Reply in progress. Stop or wait for it to finish.', done: 'Message updated and resent',
30
+ cleanupPending: 'Message updated and resent; some old records remain.',
31
+ unchanged: 'No changes to send', tooLong: 'Message exceeds 200,000 characters.',
32
+ uploadWait: 'Wait for uploads to finish or remove failed attachments.',
33
+ fileUnavailable: 'Attachments are unavailable for this session.', fileDirectory: 'Folders are not supported; select individual files.',
34
+ anotherEdit: 'Finish or cancel the current edit first.',
35
+ missing: 'Message not found. Refresh and try again.', unsupported: 'This message cannot be edited.',
36
+ locked: 'Session is in use and cannot be edited right now.', changed: 'Session state changed. Reopen the editor.',
37
+ 'composer-unavailable': 'Failed to load the editor. Refresh the page and try again.',
38
+ 'toolbar-update': 'Plugin version mismatch. Reload the plugin.',
39
+ 'child-conflict': 'Cannot rewind associated subagent sessions for this message.',
40
+ syncing: 'Message updated. Reopen the session to refresh.',
41
+ draftSaved: 'Draft preserved.',
42
+ draftConflict: 'Original message changed. Copy your draft and reopen to edit.',
43
+ textPart: 'Text block', sendPart: 'Send',
44
+ 'reconnect-unavailable': 'Session connection unavailable. Reopen this session.',
45
+ 'authentication-required': 'Sign in required.', failed: 'Failed to update message. Try again.',
46
+ },
47
+ };
48
+ const messageSeat = '[data-slot="conversation.chat.user.before"]';
49
+ const editingRow = `div:has(> ${messageSeat} > .dsh-revision-editor)`;
50
+ const originalContent = `${editingRow} > ${messageSeat} + *`;
51
+ const originalBubble = `${originalContent} > [data-message-bubble]`;
52
+ const css = `
53
+ /* rc.5 seats this contribution before the user bubble and Copy after it. */
54
+ div:has(> ${messageSeat} > .dsh-revision-pencil):has(> [data-clock="start"]) { position: relative; }
55
+ div:has(> ${messageSeat} > .dsh-revision-pencil) > [data-clock="start"] > button {
56
+ margin-left: calc(36px + var(--dsh-content-font-delta, 0px));
57
+ }
58
+ div:has(> [data-clock="start"]) > ${messageSeat} > .dsh-revision-pencil { display: inline-grid; }
59
+ .dsh-revision-pencil {
60
+ position: absolute;
61
+ right: calc(36px + var(--dsh-content-font-delta, 0px));
62
+ bottom: 0;
63
+ display: none;
64
+ place-items: center;
65
+ width: calc(28px + var(--dsh-content-font-delta, 0px));
66
+ height: calc(28px + var(--dsh-content-font-delta, 0px));
67
+ padding: 0;
68
+ border: 0;
69
+ border-radius: var(--dsw-radius-sm, 6px);
70
+ background: transparent;
71
+ color: var(--dsw-alias-label-tertiary);
72
+ cursor: pointer;
73
+ }
74
+ .dsh-revision-pencil svg {
75
+ width: calc(15px + var(--dsh-content-font-delta, 0px));
76
+ height: calc(15px + var(--dsh-content-font-delta, 0px));
77
+ }
78
+ .dsh-revision-pencil:hover {
79
+ background: var(--dsw-alias-interactive-bg-hover);
80
+ color: var(--dsw-alias-label-secondary);
81
+ }
82
+ .dsh-revision-pencil[aria-busy="true"] { cursor: progress; }
83
+ .dsh-revision-pencil::after {
84
+ content: attr(data-tooltip);
85
+ position: absolute;
86
+ z-index: 2;
87
+ top: calc(100% + 6px);
88
+ left: 50%;
89
+ transform: translateX(-50%);
90
+ padding: 4px 8px;
91
+ border-radius: var(--dsw-radius-sm, 6px);
92
+ background: var(--dsw-alias-tooltip-bg);
93
+ color: var(--dsw-alias-tooltip-label);
94
+ font: 12px / 18px var(--dsw-font-family);
95
+ white-space: nowrap;
96
+ pointer-events: none;
97
+ visibility: hidden;
98
+ opacity: 0;
99
+ transition: opacity 100ms ease;
100
+ }
101
+ .dsh-revision-pencil:not([data-tooltip-dismissed]):focus-visible::after {
102
+ visibility: visible;
103
+ opacity: 1;
104
+ }
105
+ @media (hover: hover) {
106
+ .dsh-revision-pencil:not([data-tooltip-dismissed]):hover::after {
107
+ visibility: visible;
108
+ opacity: 1;
109
+ transition-delay: 250ms;
110
+ }
111
+ [data-chat-flow-kind="user"]:has(~ :is([data-chat-flow-kind="user"], [data-chat-flow-kind="steering"])) .dsh-revision-pencil {
112
+ opacity: 0;
113
+ }
114
+ [data-chat-flow-kind="user"]:has(~ :is([data-chat-flow-kind="user"], [data-chat-flow-kind="steering"])):is(:hover, :focus-within) .dsh-revision-pencil {
115
+ opacity: 1;
116
+ }
117
+ }
118
+ /* The native composer renders the editable attachment rail. Keep the original
119
+ message's references and extra blocks visible around it. */
120
+ ${editingRow} > [data-clock="start"],
121
+ ${originalContent}:has(> [data-message-bubble]:only-child > span:only-child),
122
+ ${originalBubble}:has(> span:only-child),
123
+ ${originalBubble} > span:first-child,
124
+ ${originalContent} > [data-message-attachments] { display: none; }
125
+ .dsh-revision-editor {
126
+ box-sizing: border-box;
127
+ order: 1;
128
+ align-self: center;
129
+ width: calc(100% + 32px);
130
+ min-width: 0;
131
+ --dsh-composer-side-clearance: 0px;
132
+ }
133
+ .dsh-revision-text-part { display: grid; gap: 4px; margin: 6px 0; }
134
+ .dsh-revision-text-part textarea {
135
+ box-sizing: border-box;
136
+ padding: 6px 10px;
137
+ color: inherit;
138
+ font: inherit;
139
+ background: transparent;
140
+ border: 1px solid var(--dsw-alias-border-primary, currentColor);
141
+ border-radius: var(--dsw-radius-sm, 6px);
142
+ field-sizing: content;
143
+ resize: none;
144
+ }
145
+ .dsh-revision-editor [data-composer-card] > :has(> .dsh-revision-cancel) { display: contents; }
146
+ .dsh-revision-editor .dsh-revision-cancel {
147
+ position: absolute;
148
+ z-index: 2;
149
+ top: 6px;
150
+ right: 8px;
151
+ display: grid;
152
+ place-items: center;
153
+ width: 28px;
154
+ height: 28px;
155
+ padding: 0;
156
+ border: 0;
157
+ border-radius: var(--dsw-radius-sm);
158
+ background: transparent;
159
+ color: var(--dsw-alias-label-secondary);
160
+ cursor: pointer;
161
+ }
162
+ .dsh-revision-editor .dsh-revision-cancel:not(:disabled):hover {
163
+ background: var(--dsw-alias-interactive-bg-hover);
164
+ }
165
+ /* Preserve the native scrollport and reserve space for the close button. */
166
+ .dsh-revision-editor [contenteditable] { padding-inline-end: 36px; }
167
+ .dsh-revision-feedback {
168
+ position: fixed;
169
+ z-index: 1000;
170
+ top: var(--dsw-spacing-xl, 24px);
171
+ left: 50%;
172
+ max-width: min(90vw, 32rem);
173
+ padding: 8px 12px;
174
+ transform: translateX(-50%);
175
+ border-radius: var(--dsw-radius-sm);
176
+ background: var(--dsw-alias-tooltip-bg);
177
+ color: var(--dsw-alias-tooltip-label);
178
+ }
179
+ `;
180
+
181
+ /*!
182
+ * Tabler Icons v3.31.0, outline pencil and x.
183
+ * https://github.com/tabler/tabler-icons/tree/v3.31.0/icons/outline
184
+ * MIT License
185
+ * Copyright (c) 2020-2024 Paweł Kuna
186
+ *
187
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
188
+ * of this software and associated documentation files (the "Software"), to deal
189
+ * in the Software without restriction, including without limitation the rights
190
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
191
+ * copies of the Software, and to permit persons to whom the Software is
192
+ * furnished to do so, subject to the following conditions:
193
+ *
194
+ * The above copyright notice and this permission notice shall be included in all
195
+ * copies or substantial portions of the Software.
196
+ *
197
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
198
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
199
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
200
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
201
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
202
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
203
+ * SOFTWARE.
204
+ */
205
+ const tablerPaths = {
206
+ pencil: ['M4 20h4l10.5 -10.5a2.828 2.828 0 1 0 -4 -4l-10.5 10.5v4', 'M13.5 6.5l4 4'],
207
+ x: ['M18 6l-12 12', 'M6 6l12 12'],
208
+ };
209
+
210
+ function TablerIcon({ name, size = 16 }) {
211
+ return h('svg', { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor',
212
+ strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round', focusable: 'false', 'aria-hidden': true },
213
+ tablerPaths[name].map(d => h('path', { d, key: d })));
214
+ }
215
+
216
+ const composerSlot = 'conversation.composer.bar';
217
+ const editorFactory = 'dsh-message-revision.editor';
218
+ const toastFactory = 'workspace.toast.content';
219
+ const emptyUploads = Object.freeze({});
220
+ const emptyUploadSource = Object.freeze({ getSnapshot: () => emptyUploads, subscribe: () => () => {} });
221
+ const closedMenu = select => select(null);
222
+
223
+ function replaceMethod(object, key, next) {
224
+ const previous = Object.getOwnPropertyDescriptor(object, key);
225
+ Object.defineProperty(object, key, { configurable: true, writable: true, value: next });
226
+ return () => {
227
+ if (object[key] !== next) return;
228
+ if (previous) Object.defineProperty(object, key, previous);
229
+ else delete object[key];
230
+ };
231
+ }
232
+
233
+ function sessionRuntime(ctx) {
234
+ const service = ctx.get('sessions');
235
+ return service?.[Symbol.for('cordis.original')] ?? service;
236
+ }
237
+
238
+ function sessionView(sessions, sessionId) {
239
+ const binding = sessions.binding?.(sessionId);
240
+ const session = binding?.session;
241
+ if (typeof session?.resync !== 'function' || typeof session.getSnapshot !== 'function'
242
+ || typeof session.projections?.clear !== 'function') return undefined;
243
+ return binding;
244
+ }
245
+
246
+ function holdComposerSubmission(binding) {
247
+ const service = binding.ctx?.get('conversation');
248
+ const conversation = service?.[Symbol.for('cordis.original')] ?? service;
249
+ const send = conversation?.sendSession;
250
+ if (typeof send !== 'function') return () => {};
251
+ return replaceMethod(conversation, 'sendSession', function (session, ...args) {
252
+ if (session?.sessionId === binding.sessionId) return Promise.resolve({ kind: 'error' });
253
+ return send.call(this, session, ...args);
254
+ });
255
+ }
256
+
257
+ function rebindComposerAttachments(binding) {
258
+ const conversation = binding.ctx?.get('conversation');
259
+ if (typeof conversation?.rebindDraftFiles !== 'function') return;
260
+ const input = conversation.input.for(binding.ctx);
261
+ const { attachmentIds } = input.state.getSnapshot();
262
+ if (attachmentIds.length > 0) {
263
+ // Reuse the File objects and draft IDs. The native service marks them
264
+ // uploading immediately and replaces receipts scoped to the old Agent.
265
+ conversation.rebindDraftFiles(binding.sessionId, attachmentIds, binding.session.getSnapshot().subagent === null);
266
+ }
267
+ }
268
+
269
+ async function resyncSessionView(sessions, sessionId, binding) {
270
+ const { manager } = sessions;
271
+ manager.projectionInflight?.get(sessionId)?.controller.abort();
272
+ manager.projectionInflight?.delete(sessionId);
273
+ manager.projectionLoads?.delete(sessionId);
274
+ binding.session.projections.clear();
275
+ await binding.session.resync();
276
+ }
277
+
278
+ function watchSessionViews(sessions) {
279
+ const manager = sessions?.manager;
280
+ const remove = manager?.handleSessionRemoved;
281
+ const add = manager?.handleSessionAdded;
282
+ if (typeof remove !== 'function' || typeof add !== 'function') return undefined;
283
+ const holds = new Map();
284
+ const transitions = new WeakMap();
285
+ let disposed = false;
286
+
287
+ const undoRemove = replaceMethod(manager, 'handleSessionRemoved', function (id) {
288
+ const binding = sessionView(sessions, id);
289
+ const transition = binding && transitions.get(binding);
290
+ if (transition) transition.removal++;
291
+ const hold = holds.get(id);
292
+ if (hold) {
293
+ hold.removed();
294
+ return;
295
+ }
296
+ return remove.call(this, id);
297
+ });
298
+ let undoAdd;
299
+ try {
300
+ undoAdd = replaceMethod(manager, 'handleSessionAdded', function (summary) {
301
+ const id = summary.sessionId;
302
+ const binding = sessionView(sessions, id);
303
+ const session = binding?.session;
304
+ // Native removal can discard the Manager's entry while the retained
305
+ // Session still uses the store. Rejoin before the new list seed lands.
306
+ if (summary.agentAvailable === true && session?.getSnapshot().removed
307
+ && manager.projectionStores?.get(id) !== session.projections) {
308
+ manager.projectionStores?.set(id, session.projections);
309
+ }
310
+ const result = add.call(this, summary);
311
+ if (disposed || summary.agentAvailable !== true) return result;
312
+ const hold = holds.get(id);
313
+ if (hold) {
314
+ hold.added();
315
+ return result;
316
+ }
317
+ if (!session?.getSnapshot().removed || session.removed !== true || typeof session.notifier?.markDirty !== 'function') {
318
+ return result;
319
+ }
320
+ // Each tab receives the native event pair. An ordinary deletion remains
321
+ // removed. A live addition for the same ID establishes a new history
322
+ // generation, including when another tab performed the rewrite.
323
+ let transition = transitions.get(binding);
324
+ if (!transition) {
325
+ transition = { removal: 0, scheduled: -1, work: Promise.resolve() };
326
+ transitions.set(binding, transition);
327
+ }
328
+ const removal = transition.removal;
329
+ if (transition.scheduled === removal) return result;
330
+ transition.scheduled = removal;
331
+ const current = () => !disposed && sessions.binding(id) === binding && transition.removal === removal;
332
+ transition.work = transition.work.then(async () => {
333
+ if (!current()) return;
334
+ rebindComposerAttachments(binding);
335
+ await resyncSessionView(sessions, id, binding);
336
+ if (!current() || session.getSnapshot().openState !== 'open') return;
337
+ // rc.5's native removal flag is one-way on a retained Session.
338
+ session.removed = false;
339
+ session.notifier.markDirty();
340
+ }).catch(() => {
341
+ // A failed sync leaves the view unavailable. Allow a later addition to retry.
342
+ }).finally(() => {
343
+ if (transition.scheduled === removal) transition.scheduled = -1;
344
+ });
345
+ return result;
346
+ });
347
+ } catch (error) {
348
+ undoRemove();
349
+ throw error;
350
+ }
351
+
352
+ function holdSessionView(sessionId) {
353
+ const binding = sessionView(sessions, sessionId);
354
+ const session = binding?.session;
355
+ if (disposed || !binding || session.getSnapshot().removed || holds.has(sessionId)) {
356
+ throw new Error('reconnect-unavailable');
357
+ }
358
+ let removed = false;
359
+ let readded = false;
360
+ let rebound = false;
361
+ let released = false;
362
+ let notifyAddition;
363
+ const releaseComposer = holdComposerSubmission(binding);
364
+ const rebind = () => {
365
+ if (rebound || disposed || released || sessions.binding(sessionId) !== binding) return;
366
+ rebindComposerAttachments(binding);
367
+ rebound = true;
368
+ releaseComposer();
369
+ };
370
+ const hold = {
371
+ removed() { removed = true; readded = false; rebound = false; },
372
+ added() {
373
+ if (!removed || readded) return;
374
+ readded = true;
375
+ notifyAddition?.();
376
+ rebind();
377
+ },
378
+ release() {
379
+ if (released) return;
380
+ released = true;
381
+ holds.delete(sessionId);
382
+ notifyAddition?.();
383
+ releaseComposer();
384
+ if (removed && !readded) manager.handleSessionRemoved(sessionId);
385
+ },
386
+ };
387
+ holds.set(sessionId, hold);
388
+ return {
389
+ get removed() { return removed; },
390
+ release: hold.release,
391
+ async reconnect() {
392
+ if (!readded && !released) {
393
+ // The HTTP response and the native event stream can arrive in either order.
394
+ await new Promise(resolve => {
395
+ const timer = setTimeout(() => notifyAddition?.(), 1200);
396
+ notifyAddition = () => {
397
+ clearTimeout(timer);
398
+ notifyAddition = undefined;
399
+ resolve();
400
+ };
401
+ });
402
+ }
403
+ if (released || sessions.binding(sessionId) !== binding) return;
404
+ await resyncSessionView(sessions, sessionId, binding);
405
+ if (released || sessions.binding(sessionId) !== binding) return;
406
+ const snapshot = session.getSnapshot();
407
+ if (snapshot.openState !== 'open' || snapshot.removed) throw new Error('syncing');
408
+ rebind();
409
+ },
410
+ };
411
+ }
412
+
413
+ return {
414
+ holdSessionView,
415
+ dispose() {
416
+ disposed = true;
417
+ for (const hold of holds.values()) hold.release();
418
+ undoAdd();
419
+ undoRemove();
420
+ },
421
+ };
422
+ }
423
+
424
+ function hookFor(source) {
425
+ const subscribe = listener => source.subscribe(listener);
426
+ const getSnapshot = () => source.getSnapshot();
427
+ return select => select(useSyncExternalStore(subscribe, getSnapshot));
428
+ }
429
+
430
+ // rc.5 exposes the native bar as a slot entry, not a separately exported React component.
431
+ // Take the component from its registration, without replacing the resident slot.
432
+ function nativeComposerEntry(slots) {
433
+ const entries = slots.entries?.(composerSlot) ?? [];
434
+ const native = entries.filter(entry => entry.locale === 'conversation'
435
+ && typeof entry.inject === 'function' && entry.children?.['conversation.input.model']
436
+ && entry.children?.['conversation.input.attachments']);
437
+ return native.length === 1 ? native[0] : undefined;
438
+ }
439
+
440
+ function revisionDraftKey(sessionId, messageId) {
441
+ return JSON.stringify([sessionId, messageId]);
442
+ }
443
+
444
+ function snapshotRevisionDraft(edit, text, attachmentIds, textParts) {
445
+ const { retained, conversation } = edit.composer;
446
+ const retainedIndices = [];
447
+ const fileIds = [];
448
+ for (const id of attachmentIds) {
449
+ if (retained.has(id)) retainedIndices.push(retained.get(id).index);
450
+ else fileIds.push(id);
451
+ }
452
+ const available = new Map((conversation?.resolveDraftAttachments(fileIds) ?? []).map(item => [item.id, item.file]));
453
+ const files = fileIds.map(id => available.get(id));
454
+ if (files.some(file => !file)) throw new Error('fileUnavailable');
455
+ return {
456
+ text, textParts, files, retainedIndices, settings: { ...edit.settings },
457
+ original: edit.original, originalTextParts: edit.originalTextParts, originalAttachments: edit.originalAttachments,
458
+ };
459
+ }
460
+
461
+ function canRestoreRevisionDraft(saved, preview) {
462
+ return saved.original === preview.text
463
+ && JSON.stringify(saved.originalTextParts) === JSON.stringify(preview.textParts)
464
+ && saved.originalAttachments === JSON.stringify(preview.attachments);
465
+ }
466
+
467
+ function seedRevisionDraft(shell, retained, uploaded, conversation, sessionId, text, saved) {
468
+ shell.setDraft(saved?.text ?? text);
469
+ const retainedIndices = saved && new Set(saved.retainedIndices);
470
+ const ids = [...retained].filter(([, attachment]) => !retainedIndices || retainedIndices.has(attachment.index))
471
+ .map(([id]) => id);
472
+ for (const file of saved?.files ?? []) {
473
+ const [attachment] = conversation?.createDrafts(sessionId, [file], true) ?? [];
474
+ if (!attachment) throw new Error('fileUnavailable');
475
+ uploaded.add(attachment.id);
476
+ ids.push(attachment.id);
477
+ }
478
+ if (!shell.addAttachments(ids)) throw new Error('composer-unavailable');
479
+ }
480
+
481
+ function openDraft(ctx, native, sessionId, text, attachments, submit, saved) {
482
+ const injected = native.inject(sessionId);
483
+ const original = injected?.keyboard;
484
+ if (typeof original?.constructor !== 'function' || typeof original.deps?.defaultSink !== 'function'
485
+ || typeof original.editor?.getRootElement !== 'function' || !injected.hooks) {
486
+ throw new Error('composer-unavailable');
487
+ }
488
+ const conversation = ctx.get('conversation');
489
+ const imageService = ctx.get('uiConversation');
490
+ const retained = new Map(attachments.map(({ index, block }) => {
491
+ const ref = block.attachment;
492
+ const image = block.type === 'image';
493
+ return [`revision-attachment:${index}`, {
494
+ index, image, ref,
495
+ descriptor: {
496
+ kind: image ? 'image' : 'file', id: `revision-attachment:${index}`,
497
+ // Display metadata only. The original bytes and immutable native ref stay on the host.
498
+ file: { name: ref.name ?? '', size: ref.bytes, type: ref.mediaType ?? '' },
499
+ },
500
+ }];
501
+ }));
502
+ const uploaded = new Set();
503
+ const shell = new original.constructor({
504
+ actx: original.deps.actx,
505
+ quoteRemoveLabel: original.deps.quoteRemoveLabel,
506
+ defaultSink: submit,
507
+ });
508
+ const useDraft = hookFor(shell.state);
509
+ const useFileUploads = hookFor(conversation?.fileUploads ?? emptyUploadSource);
510
+ function dispose() {
511
+ shell.dispose();
512
+ for (const id of uploaded) conversation.releaseDraftAttachment(id);
513
+ uploaded.clear();
514
+ }
515
+ try {
516
+ seedRevisionDraft(shell, retained, uploaded, conversation, sessionId, text, saved);
517
+ return {
518
+ shell, retained, conversation, imageService, uploaded, dispose, useDraft, useFileUploads,
519
+ registerFileIntake: injected.registerFileIntake,
520
+ useNotices: hookFor(shell.notices), useLexicon: hookFor(shell.lexicon),
521
+ useBusyEnter: hookFor(injected.hooks.busyEnter), useStopShortcut: hookFor(injected.hooks.stopShortcut),
522
+ };
523
+ } catch (error) {
524
+ dispose();
525
+ throw error;
526
+ }
527
+ }
528
+
529
+ function modelDirectoryWithSelection(directory, selection) {
530
+ if (!selection || !directory) return directory;
531
+ let previous, overlay;
532
+ return {
533
+ subscribe: listener => directory.subscribe(listener),
534
+ getSnapshot() {
535
+ const snapshot = directory.getSnapshot();
536
+ if (previous !== snapshot) {
537
+ previous = snapshot;
538
+ overlay = { ...snapshot, current: selection };
539
+ }
540
+ return overlay;
541
+ },
542
+ };
543
+ }
544
+
545
+ function NativeEditor({ edit, dismiss, cancelLabel, renderSlot, t, ...props }) {
546
+ const { shell, useDraft, useNotices, useLexicon, useBusyEnter, useStopShortcut,
547
+ useFileUploads, retained, conversation, imageService, uploaded, registerFileIntake } = edit.composer;
548
+ const phase = useDraft(state => state.phase);
549
+ const pending = phase === 'sending' || phase === 'adjudicating' || phase === 'submitting';
550
+ const [model, setModel] = useState(edit.settings.model);
551
+ const [permission, setPermission] = useState(edit.settings.permissionPreset);
552
+ const [previews, setPreviews] = useState({});
553
+ const [, setPartsVersion] = useState(0);
554
+ const draftText = useDraft(state => state.draft);
555
+ const draftAttachments = useDraft(state => state.attachmentIds);
556
+ const sendRemainingText = edit.additionalText.length > 0 && !draftText.trim()
557
+ && draftAttachments.length === 0 && edit.additionalText.some(value => value.trim());
558
+ const dropTarget = useRef(null);
559
+ const modelDirectory = useMemo(() => modelDirectoryWithSelection(edit.modelDirectory, model),
560
+ [edit, model]);
561
+ const historicalUploads = useMemo(() => Object.fromEntries([...retained.keys()].map(id => [id, { status: 'ready' }])), [retained]);
562
+ const useCombinedUploads = select => useFileUploads(snapshot => select({ ...historicalUploads, ...snapshot }));
563
+ useEffect(() => {
564
+ if (edit.restored) shell.focus();
565
+ }, [edit, shell]);
566
+ useEffect(() => {
567
+ if (!imageService) return undefined;
568
+ let mounted = true;
569
+ for (const [id, item] of retained) {
570
+ if (!item.image) continue;
571
+ void imageService.imageUrl(props.sessionId, item.ref).then(url => {
572
+ if (mounted) setPreviews(previous => ({ ...previous, [id]: url }));
573
+ }).catch(() => { /* A missing preview does not discard the original ref. */ });
574
+ }
575
+ return () => { mounted = false; };
576
+ }, [imageService, retained, props.sessionId]);
577
+
578
+ const resolveDraftAttachments = useCallback(ids => {
579
+ const picked = new Map((conversation?.resolveDraftAttachments(ids) ?? []).map(item => [item.id, item]));
580
+ return ids.flatMap(id => {
581
+ const existing = retained.get(id);
582
+ if (existing) return [{ ...existing.descriptor, ...(existing.image ? { previewUrl: previews[id] } : {}) }];
583
+ const current = picked.get(id);
584
+ return current ? [current] : [];
585
+ });
586
+ }, [conversation, retained, previews]);
587
+ function addFiles(files, directories) {
588
+ if (directories?.size > 0) return edit.labels.fileDirectory;
589
+ if (props.disabled || pending || typeof conversation?.createDrafts !== 'function') {
590
+ return edit.labels.fileUnavailable;
591
+ }
592
+ const drafts = [];
593
+ try {
594
+ for (const file of files) drafts.push(...conversation.createDrafts(props.sessionId, [file], true));
595
+ if (shell.addAttachments(drafts.map(item => item.id))) {
596
+ for (const item of drafts) uploaded.add(item.id);
597
+ return null;
598
+ }
599
+ } catch (error) {
600
+ for (const item of drafts) conversation.releaseDraftAttachment(item.id);
601
+ return error instanceof Error ? error.message : String(error);
602
+ }
603
+ for (const item of drafts) conversation.releaseDraftAttachment(item.id);
604
+ return edit.labels.fileUnavailable;
605
+ }
606
+ function removeAttachment(id) {
607
+ if (props.disabled || pending || !shell.removeAttachment(id)) return;
608
+ if (uploaded.delete(id)) conversation.releaseDraftAttachment(id);
609
+ }
610
+ const usePermissionProjection = (key, select) => props.useProjection(key, value => {
611
+ const view = key === 'permissions' && value !== undefined && value !== null && permission
612
+ ? { ...value, currentValue: permission } : value;
613
+ return select ? select(view) : view;
614
+ });
615
+ const renderEditorSlot = (name, owner) => {
616
+ if (name === 'conversation.input.attachments') {
617
+ dropTarget.current = owner;
618
+ return renderSlot(name, { ...owner, canAcceptDrop: false });
619
+ }
620
+ if (name === 'conversation.input.permission') return renderSlot(name, {
621
+ ...owner, useProjection: usePermissionProjection,
622
+ select: async preset => {
623
+ edit.settings.permissionPreset = preset;
624
+ setPermission(preset);
625
+ return true;
626
+ },
627
+ });
628
+ if (name === 'conversation.input.model') return renderSlot(name, {
629
+ ...owner,
630
+ ...(modelDirectory === undefined ? { locked: true } : {
631
+ directory: modelDirectory,
632
+ select: async selection => {
633
+ edit.settings.model = selection;
634
+ setModel(selection);
635
+ return { ok: true, value: undefined };
636
+ },
637
+ }),
638
+ });
639
+ if (name === 'conversation.input.activity') {
640
+ return renderSlot(name, { ...owner, inputActions: shell.actions });
641
+ }
642
+ if (name === 'conversation.input.plan') return renderSlot(name, { ...owner, locked: true });
643
+ if (name === 'conversation.composer.dock') return renderSlot(name, owner);
644
+ // Extension controls address the resident draft through their session scope.
645
+ if (name === 'conversation.input.left' || name === 'conversation.input.right') {
646
+ return h('div', { inert: true }, renderSlot(name, owner));
647
+ }
648
+ return null;
649
+ };
650
+ function targetFileDrag(event, drop = false) {
651
+ const transfer = event.dataTransfer;
652
+ if (!transfer || !transfer.types.some(type => type === 'Files' || type === 'application/x-dsh-file')) return;
653
+ event.preventDefault();
654
+ event.stopPropagation();
655
+ const target = dropTarget.current;
656
+ transfer.dropEffect = target?.canAcceptDrop ? 'copy' : 'none';
657
+ if (!drop || !target?.canAcceptDrop) return;
658
+ const applicationFile = edit.readFileDrag?.(transfer);
659
+ const files = applicationFile === undefined ? [...transfer.files] : [applicationFile];
660
+ const directories = new Set();
661
+ let index = 0;
662
+ for (const item of transfer.items) {
663
+ if (item.kind !== 'file') continue;
664
+ const file = files[index++];
665
+ if (file && item.webkitGetAsEntry?.()?.isDirectory) directories.add(file);
666
+ }
667
+ target.onAddFiles(files, directories);
668
+ }
669
+ const canUpload = typeof conversation?.createDrafts === 'function' && typeof shell.pickFiles === 'function';
670
+ const uploadAllowed = props.useAccess('fileUploads/upload') !== false;
671
+ return h('div', {
672
+ className: 'dsh-revision-editor',
673
+ onDragEnterCapture: event => targetFileDrag(event),
674
+ onDragOverCapture: event => targetFileDrag(event),
675
+ onDropCapture: event => targetFileDrag(event, true),
676
+ onKeyDown: event => {
677
+ if (event.key !== 'Escape' || event.defaultPrevented || event.nativeEvent.isComposing
678
+ || !event.currentTarget.contains(event.target)
679
+ || !event.target.closest('[contenteditable], .dsh-revision-cancel, .dsh-revision-text-part textarea')) return;
680
+ event.preventDefault();
681
+ event.stopPropagation();
682
+ if (!pending) dismiss();
683
+ },
684
+ }, edit.additionalText.map((value, index) => h('label', {
685
+ key: index, className: 'dsh-revision-text-part',
686
+ }, `${edit.labels.textPart} ${index + 2}`, h('textarea', {
687
+ defaultValue: value, disabled: pending || props.disabled,
688
+ onChange: event => {
689
+ edit.additionalText[index] = event.currentTarget.value;
690
+ setPartsVersion(version => version + 1);
691
+ },
692
+ }))), h(edit.native.component, {
693
+ ...props,
694
+ t: (key, ...args) => t(key === 'input.commands' ? 'input.file' : key, ...args),
695
+ variant: 'composer', occurrence: 'embedded',
696
+ renderSlot: renderEditorSlot, useInput: useDraft, inputActions: shell.actions,
697
+ keyboard: shell, useNotices, useMenuLauncher: closedMenu, useLexicon,
698
+ useBusyEnter, useStopShortcut, useFileUploads: useCombinedUploads,
699
+ registerFileIntake, resolveDraftAttachments, removeAttachment,
700
+ addFiles: canUpload ? addFiles : undefined,
701
+ retryFileUpload: id => { if (uploaded.has(id)) conversation.retryFileUpload(props.sessionId, id); },
702
+ toggleCommandMenu: canUpload && uploadAllowed ? () => shell.pickFiles() : undefined,
703
+ retry: undefined, stop: undefined,
704
+ accessory: h('button', { type: 'button', className: 'dsh-revision-cancel', disabled: pending,
705
+ title: cancelLabel, 'aria-label': cancelLabel, onClick: () => dismiss() }, h(TablerIcon, { name: 'x' })),
706
+ }), sendRemainingText && h('button', { type: 'button', disabled: pending || props.disabled,
707
+ onClick: () => void edit.submit(draftText, draftAttachments),
708
+ }, edit.labels.sendPart));
709
+ }
710
+
711
+ return {
712
+ inject: ['slots', 'locale'],
713
+ apply(ctx) {
714
+ const lifetime = new AbortController();
715
+ let activeEditor;
716
+ let sessionViews;
717
+ let submitting = false;
718
+ const savedDrafts = new Map();
719
+ const draftListeners = new Set();
720
+ let draftVersion = 0;
721
+ const readDraftVersion = () => draftVersion;
722
+ const observeDrafts = listener => {
723
+ draftListeners.add(listener);
724
+ return () => draftListeners.delete(listener);
725
+ };
726
+ function keepDraft(key, saved) {
727
+ savedDrafts.set(key, saved);
728
+ draftVersion++;
729
+ for (const listener of draftListeners) listener();
730
+ }
731
+ let currentNotice = null;
732
+ let noticeSequence = 0;
733
+ const noticeListeners = new Set();
734
+ const observeNotices = listener => {
735
+ noticeListeners.add(listener);
736
+ return () => noticeListeners.delete(listener);
737
+ };
738
+ const readNotice = () => currentNotice;
739
+ function publishNotice(notice) {
740
+ currentNotice = notice;
741
+ for (const listener of noticeListeners) listener();
742
+ }
743
+ function notify(text, tone = 'warning') {
744
+ publishNotice({ text, tone, seq: ++noticeSequence });
745
+ }
746
+ function Feedback({ renderFactorySlot }) {
747
+ const notice = useSyncExternalStore(observeNotices, readNotice);
748
+ if (!notice) return null;
749
+ const onDone = () => { if (currentNotice === notice) publishNotice(null); };
750
+ return renderFactorySlot(toastFactory, { ...notice, onDone }, {
751
+ fallback: h(FallbackNotice, { key: notice.seq, notice, onDone }),
752
+ });
753
+ }
754
+ function FallbackNotice({ notice, onDone }) {
755
+ useEffect(() => {
756
+ const timer = setTimeout(onDone, 2400);
757
+ return () => clearTimeout(timer);
758
+ }, [onDone]);
759
+ return h('div', { role: notice.tone === 'success' ? 'status' : 'alert', className: 'dsh-revision-feedback' }, notice.text);
760
+ }
761
+ let composerFactoryLive = false;
762
+
763
+ async function requestRevision(payload) {
764
+ const response = await fetch('/api/message-revision', {
765
+ method: 'POST', credentials: 'same-origin', signal: lifetime.signal,
766
+ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload),
767
+ });
768
+ const result = await response.json().catch(() => null);
769
+ if (response.status === 401 || response.status === 403) throw new Error('authentication-required');
770
+ if (!response.ok || result?.ok !== true) {
771
+ throw Object.assign(new Error('failed'), {
772
+ hostError: typeof result?.error === 'string' ? result.error : '',
773
+ reconnect: result?.reconnect === true,
774
+ });
775
+ }
776
+ return result;
777
+ }
778
+
779
+ function RevisionAction({ t, matched, sessionId, useChat, useSession, useAccess, renderFactorySlot }) {
780
+ const allowed = useAccess('session/prompt');
781
+ const status = useSession(s => s.removed || s.openState !== 'open' ? 'unavailable'
782
+ : s.running || s.pendingSubmissions.length > 0 ? 'busy' : 'idle');
783
+ const busy = status === 'busy';
784
+ const nodes = useChat(s => s.nodes);
785
+ const savedVersion = useSyncExternalStore(observeDrafts, readDraftVersion);
786
+ const [edit, setEdit] = useState(null);
787
+ const [opening, setOpening] = useState(false);
788
+ const [tooltipDismissed, setTooltipDismissed] = useState(false);
789
+ const pencil = useRef(null);
790
+ const restoreFocus = useRef(false);
791
+ const pending = useRef(false);
792
+ const owner = useRef(Symbol());
793
+ const draft = useRef(null);
794
+ useEffect(() => {
795
+ setEdit(null);
796
+ setOpening(false);
797
+ return () => {
798
+ if (activeEditor === owner.current) activeEditor = undefined;
799
+ draft.current?.dispose();
800
+ draft.current = null;
801
+ };
802
+ }, [sessionId, matched]);
803
+ useLayoutEffect(() => {
804
+ if (!edit && restoreFocus.current) {
805
+ restoreFocus.current = false;
806
+ pencil.current?.focus({ preventScroll: true });
807
+ }
808
+ }, [edit]);
809
+ useEffect(() => {
810
+ if (!allowed || status !== 'idle' || edit || opening || activeEditor !== undefined || submitting) return;
811
+ const node = messageInRow(pencil.current);
812
+ if (!node) return;
813
+ const saved = savedDrafts.get(revisionDraftKey(sessionId, node.data.messageId));
814
+ if (saved?.reopenInView !== window.location.href) return;
815
+ saved.reopenInView = undefined;
816
+ void openEditor(node, saved);
817
+ }, [allowed, status, edit, opening, nodes, matched, sessionId, savedVersion]);
818
+ if (!allowed) return null;
819
+
820
+ function errorMessage(error) {
821
+ const message = typeof error?.hostError === 'string' ? error.hostError.trim() : '';
822
+ const code = Object.hasOwn(strings.zh, message) ? message
823
+ : Object.hasOwn(strings.zh, error?.message) ? error.message : null;
824
+ return code ? t(code) : (message.slice(0, 240) || t('failed'));
825
+ }
826
+
827
+ function messageInRow(target) {
828
+ const key = target?.closest('[data-chat-flow-kind="user"][data-chat-node-key]')?.dataset.chatNodeKey;
829
+ const node = key === undefined ? undefined : nodes.get(key);
830
+ return node?.kind === 'user' && node.data.source === matched && typeof node.data.messageId === 'string'
831
+ ? node : undefined;
832
+ }
833
+
834
+ function open(event) {
835
+ if (status !== 'idle') { notify(t(busy ? 'busy' : 'reconnect-unavailable')); return; }
836
+ if (activeEditor !== undefined || submitting) {
837
+ if (!opening) notify(t('anotherEdit'));
838
+ return;
839
+ }
840
+ const node = messageInRow(event.currentTarget);
841
+ if (!node) { notify(t('missing')); return; }
842
+ const saved = savedDrafts.get(revisionDraftKey(sessionId, node.data.messageId));
843
+ void openEditor(node, saved);
844
+ }
845
+
846
+ async function openEditor(node, saved) {
847
+ const content = node.data.content;
848
+ if (!Array.isArray(content)) { notify(t('unsupported')); return; }
849
+ const native = nativeComposerEntry(ctx.slots);
850
+ if (!native || !composerFactoryLive) { notify(t('composer-unavailable')); return; }
851
+ const claim = owner.current = Symbol();
852
+ activeEditor = claim;
853
+ setOpening(true);
854
+ try {
855
+ const result = await requestRevision({ sessionId, messageId: node.data.messageId });
856
+ if (activeEditor !== claim || lifetime.signal.aborted) return;
857
+ if (typeof result.revision !== 'string' || typeof result.text !== 'string') throw new Error('failed');
858
+ if (result.toolbarRevision !== 1 || !Array.isArray(result.attachments)
859
+ || !Array.isArray(result.textParts) || result.textParts.some(part => typeof part !== 'string')
860
+ || result.textParts.join('') !== result.text) throw new Error('toolbar-update');
861
+ const conflicted = saved !== undefined && !canRestoreRevisionDraft(saved, result);
862
+ const key = revisionDraftKey(sessionId, node.data.messageId);
863
+ const initialParts = (conflicted ? undefined : saved?.textParts) ?? result.textParts ?? [result.text];
864
+ const hasSegments = initialParts.length > 1;
865
+ const firstText = conflicted ? saved.text : hasSegments ? initialParts[0] : result.text;
866
+ const edit = {
867
+ key, conflicted, restored: saved !== undefined,
868
+ messageId: node.data.messageId, revision: result.revision, original: result.text, native,
869
+ originalTextParts: result.textParts,
870
+ additionalText: hasSegments && !conflicted ? initialParts.slice(1) : [],
871
+ originalAttachments: JSON.stringify(result.attachments), settings: { ...saved?.settings },
872
+ originalSettings: result.settings ?? {},
873
+ modelDirectory: ctx.slots.entries('conversation.input.model')
874
+ .find(entry => entry.locale === 'model')?.inject?.(sessionId)?.directory,
875
+ readFileDrag: transfer => ctx.get('fileDrag')?.read(transfer),
876
+ labels: { fileDirectory: t('fileDirectory'), fileUnavailable: t('fileUnavailable'), textPart: t('textPart'), sendPart: t('sendPart') },
877
+ submit: (text, attachmentIds) => submit(edit, text, attachmentIds, claim),
878
+ };
879
+ edit.composer = openDraft(ctx, native, sessionId, firstText, result.attachments,
880
+ edit.submit,
881
+ conflicted ? { ...saved, retainedIndices: [] } : hasSegments && saved ? { ...saved, text: firstText } : saved);
882
+ if (conflicted) notify(t('draftConflict'));
883
+ if (savedDrafts.get(key) === saved) savedDrafts.delete(key);
884
+ draft.current = edit.composer;
885
+ setOpening(false);
886
+ setEdit(edit);
887
+ } catch (error) {
888
+ if (activeEditor !== claim || lifetime.signal.aborted) return;
889
+ activeEditor = undefined;
890
+ setOpening(false);
891
+ notify(errorMessage(error));
892
+ }
893
+ }
894
+
895
+ function dismiss(restore = true) {
896
+ if (activeEditor === owner.current) activeEditor = undefined;
897
+ restoreFocus.current = restore === true;
898
+ const composer = draft.current;
899
+ draft.current = null;
900
+ setEdit(null);
901
+ composer?.dispose();
902
+ }
903
+
904
+ async function submit(edit, text, attachmentIds, claim) {
905
+ if (edit.conflicted) {
906
+ notify(t('draftConflict'));
907
+ return { kind: 'error' };
908
+ }
909
+ const textParts = edit.additionalText.length ? [text, ...edit.additionalText] : undefined;
910
+ if (textParts) text = textParts.join('');
911
+ if (submitting || pending.current || activeEditor !== claim || (!text.trim() && attachmentIds.length === 0)) {
912
+ return { kind: 'error' };
913
+ }
914
+ const { retained, conversation } = edit.composer;
915
+ const remaining = new Set(attachmentIds);
916
+ const removedAttachments = [...retained].filter(([id]) => !remaining.has(id)).map(([, item]) => item.index);
917
+ const uploads = conversation?.fileUploads.getSnapshot() ?? emptyUploads;
918
+ const receiptIds = [];
919
+ for (const id of attachmentIds) {
920
+ if (retained.has(id)) continue;
921
+ const upload = uploads[id];
922
+ if (upload?.status !== 'ready' || typeof upload.receiptId !== 'string') {
923
+ notify(t('uploadWait'));
924
+ return { kind: 'error' };
925
+ }
926
+ receiptIds.push(upload.receiptId);
927
+ }
928
+ const selectedModel = edit.settings.model;
929
+ const originalModel = edit.originalSettings.model;
930
+ const modelGroup = edit.modelDirectory?.getSnapshot()?.groups?.find(group => group.id === originalModel?.provider);
931
+ const defaultEffort = modelGroup?.models.find(model => model.id === originalModel?.model)?.reasoning?.defaultEffort;
932
+ const sameModel = selectedModel === undefined || (selectedModel.provider === originalModel?.provider
933
+ && selectedModel.model === originalModel?.model
934
+ && (selectedModel.reasoningEffort ?? defaultEffort) === (originalModel?.reasoningEffort ?? defaultEffort));
935
+ const samePermission = edit.settings.permissionPreset === undefined
936
+ || edit.settings.permissionPreset === edit.originalSettings.permissionPreset;
937
+ const sameText = text === edit.original
938
+ && (textParts === undefined || textParts.every((part, index) => part === edit.originalTextParts[index]));
939
+ if (sameText && removedAttachments.length === 0 && receiptIds.length === 0
940
+ && sameModel && samePermission) {
941
+ dismiss();
942
+ return { kind: 'success' };
943
+ }
944
+ if (text.length > 200_000) {
945
+ notify(t('tooLong'));
946
+ return { kind: 'error' };
947
+ }
948
+ let saved;
949
+ try {
950
+ saved = snapshotRevisionDraft(edit, text, attachmentIds, textParts);
951
+ } catch (error) {
952
+ notify(errorMessage(error));
953
+ return { kind: 'error' };
954
+ }
955
+ const view = window.location.href;
956
+ submitting = true;
957
+ pending.current = true;
958
+ let reconnect;
959
+ let restoreDraft = false;
960
+ let savedForRetry = false;
961
+ const inView = () => !lifetime.signal.aborted && window.location.href === view;
962
+ try {
963
+ if (!sessionViews) throw new Error('reconnect-unavailable');
964
+ reconnect = sessionViews.holdSessionView(sessionId);
965
+ let result;
966
+ try {
967
+ result = await requestRevision({ sessionId, messageId: edit.messageId,
968
+ toolbarRevision: 1, text, textParts, expectedRevision: edit.revision,
969
+ removedAttachments, receiptIds, ...edit.settings });
970
+ } catch (error) {
971
+ if (error.reconnect || reconnect.removed) {
972
+ restoreDraft = true;
973
+ await reconnect.reconnect().catch(() => {});
974
+ }
975
+ throw error;
976
+ }
977
+ try {
978
+ if (result.unchanged === true) {
979
+ if (inView() && activeEditor === claim) dismiss();
980
+ return { kind: 'success' };
981
+ }
982
+ if (result.reload === true || reconnect.removed) await reconnect.reconnect();
983
+ if (inView()) {
984
+ if (activeEditor === claim) dismiss();
985
+ if (result.cleanupWarning) notify(t('cleanupPending'));
986
+ else notify(t('done'), 'success');
987
+ }
988
+ } catch {
989
+ if (inView()) {
990
+ if (activeEditor === claim) dismiss();
991
+ notify(t('syncing'));
992
+ }
993
+ }
994
+ return { kind: 'success' };
995
+ } catch (error) {
996
+ savedForRetry = !lifetime.signal.aborted && (restoreDraft || draft.current !== edit.composer);
997
+ if (savedForRetry && activeEditor === claim) dismiss(false);
998
+ if (inView()) notify(savedForRetry ? `${errorMessage(error)} ${t('draftSaved')}` : errorMessage(error));
999
+ return { kind: 'error' };
1000
+ } finally {
1001
+ pending.current = false;
1002
+ try {
1003
+ reconnect?.release();
1004
+ } finally {
1005
+ submitting = false;
1006
+ if (savedForRetry) keepDraft(edit.key, { ...saved, reopenInView: inView() ? view : undefined });
1007
+ }
1008
+ }
1009
+ }
1010
+
1011
+ return h(Fragment, null,
1012
+ !edit && h('button', {
1013
+ ref: pencil, type: 'button', className: 'dsh-revision-pencil', onClick: open,
1014
+ 'aria-label': t('edit'), 'aria-busy': opening || undefined,
1015
+ 'data-tooltip': t('edit'), 'data-tooltip-dismissed': (opening || tooltipDismissed) || undefined,
1016
+ onFocus: () => setTooltipDismissed(false),
1017
+ onPointerLeave: () => setTooltipDismissed(false),
1018
+ onKeyDown: event => { if (event.key === 'Escape') setTooltipDismissed(true); },
1019
+ }, h(TablerIcon, { name: 'pencil' })),
1020
+ edit && renderFactorySlot(editorFactory, {
1021
+ edit, dismiss, cancelLabel: t('cancel'), disabled: busy,
1022
+ }));
1023
+ }
1024
+
1025
+ ctx.effect(() => () => lifetime.abort());
1026
+ ctx.inject(['sessions'], scoped => scoped.effect(() => {
1027
+ const views = watchSessionViews(sessionRuntime(scoped));
1028
+ sessionViews = views;
1029
+ return () => {
1030
+ if (sessionViews === views) sessionViews = undefined;
1031
+ views?.dispose();
1032
+ };
1033
+ }));
1034
+ ctx.effect(() => ctx.locale.register(locale, strings));
1035
+ // The same native child seats remain available to the registered native bar.
1036
+ const composerChildren = {
1037
+ 'conversation.input.attachments': { kind: 'single', scope: 'session-maybe' },
1038
+ 'conversation.input.permission': { kind: 'single', scope: 'session' },
1039
+ 'conversation.input.plan': { kind: 'single', scope: 'session' },
1040
+ 'conversation.input.model': { kind: 'single', scope: 'session' },
1041
+ 'conversation.input.activity': { kind: 'single', scope: 'session' },
1042
+ 'conversation.input.left': { kind: 'list', scope: 'session' },
1043
+ 'conversation.input.right': { kind: 'list', scope: 'session' },
1044
+ 'conversation.composer.dock': { kind: 'list', scope: 'session' },
1045
+ };
1046
+ ctx.slots.inject(composerSlot, () => {
1047
+ // rc.5 registers and tears down only own child declarations, but the
1048
+ // Factory renderer resolves their specs by lookup. Borrow the already
1049
+ // live slots without owning them so unloading leaves the host intact.
1050
+ const borrowedChildren = Object.freeze(Object.create(Object.freeze(composerChildren)));
1051
+ const dispose = ctx.slots.registerFactory({
1052
+ name: editorFactory, scope: 'session', locale: 'conversation', children: borrowedChildren,
1053
+ }, NativeEditor);
1054
+ composerFactoryLive = true;
1055
+ return () => { composerFactoryLive = false; dispose(); };
1056
+ });
1057
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
1058
+ name: 'shell.overlay', id: 'message-revision.styles', locale,
1059
+ }, props => h(Fragment, null, h('style', null, css), h(Feedback, props))));
1060
+ ctx.slots.inject('conversation.chat.user.before', () => ctx.slots.register({
1061
+ name: 'conversation.chat.user.before', locale, order: 10000,
1062
+ select: ({ kind, source }) => kind === 'user' && source?.kind === 'user' ? source : null,
1063
+ }, RevisionAction));
1064
+ },
1065
+ };
1066
+ },
1067
+ });