@kabxx/dsh-message-revision 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -2
- package/cordis.patch.yml +3 -0
- package/icon.svg +23 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +45 -4
- package/src/bounded-commit.js +121 -0
- package/src/bounded-revision.js +250 -0
- package/src/client.js +1421 -0
- package/src/index.js +742 -0
- package/src/native-lease.js +143 -0
- package/src/platform.js +623 -0
- package/src/revision-candidates.js +341 -0
- package/src/revision-notifications.js +122 -0
- package/src/revision.js +601 -0
- package/src/rewrite-journal.js +895 -0
- package/src/rollback-events.js +8 -0
- package/src/rollout-process.js +259 -0
- package/src/rollout-stream.js +521 -0
- package/src/rollout-worker.js +452 -0
package/src/client.js
ADDED
|
@@ -0,0 +1,1421 @@
|
|
|
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
|
+
historicalImageSize: '旧图片的原始上传大小无法核对。请移除旧图片,或用原文件重新添加后再发送。',
|
|
14
|
+
fileUnavailable: '当前会话无法添加附件。', fileDirectory: '不支持直接添加文件夹,请选择单个文件。',
|
|
15
|
+
anotherEdit: '请先完成或取消当前编辑。',
|
|
16
|
+
missing: '未找到该消息,请刷新后重试。', unsupported: '此消息不支持编辑。',
|
|
17
|
+
nonIndependentTurn: '此消息没有可独立回退的对话轮次。',
|
|
18
|
+
subagentUnsupported: '子智能体会话不支持直接编辑,请在主会话中操作。',
|
|
19
|
+
queuePending: '会话仍有排队消息,请等队列清空后再试。',
|
|
20
|
+
inheritedDuplicate: '无法替换继承历史中的同一条消息。',
|
|
21
|
+
locked: '会话正被占用,暂时无法编辑。', changed: '会话状态已变更,请重新打开编辑框。',
|
|
22
|
+
'composer-unavailable': '输入框未能加载,请刷新页面后重试。',
|
|
23
|
+
'toolbar-update': '插件前后端版本不一致,请重新加载插件。',
|
|
24
|
+
'child-conflict': '关联的子智能体会话无法回退,暂不支持编辑此消息。',
|
|
25
|
+
syncing: '消息已更新,请重新打开会话刷新视图。',
|
|
26
|
+
draftSaved: '草稿已保留。',
|
|
27
|
+
deliveryUnknown: '连接已中断,请先检查原会话是否已更新。',
|
|
28
|
+
draftConflict: '原消息已变更,请先复制草稿后关闭重试。',
|
|
29
|
+
textPart: '正文', sendPart: '发送',
|
|
30
|
+
'reconnect-unavailable': '会话连接不可用,请重新打开会话。',
|
|
31
|
+
'authentication-required': '请先完成登录认证。', failed: '编辑失败,请重试。',
|
|
32
|
+
},
|
|
33
|
+
en: {
|
|
34
|
+
edit: 'Edit message', cancel: 'Cancel',
|
|
35
|
+
busy: 'Reply in progress. Stop or wait for it to finish.', done: 'Message updated and resent',
|
|
36
|
+
cleanupPending: 'Message updated and resent; some old records remain.',
|
|
37
|
+
unchanged: 'No changes to send', tooLong: 'Message exceeds 200,000 characters.',
|
|
38
|
+
uploadWait: 'Wait for uploads to finish or remove failed attachments.',
|
|
39
|
+
historicalImageSize: 'The upload size of an existing image is unavailable. Remove existing images or reattach them from the original files before sending.',
|
|
40
|
+
fileUnavailable: 'Attachments are unavailable for this session.', fileDirectory: 'Folders are not supported; select individual files.',
|
|
41
|
+
anotherEdit: 'Finish or cancel the current edit first.',
|
|
42
|
+
missing: 'Message not found. Refresh and try again.', unsupported: 'This message cannot be edited.',
|
|
43
|
+
nonIndependentTurn: 'This message does not have an independently rewindable turn.',
|
|
44
|
+
subagentUnsupported: 'Subagent sessions cannot be edited directly. Edit from the main session instead.',
|
|
45
|
+
queuePending: 'Queued messages are still pending. Wait for the queue to clear and try again.',
|
|
46
|
+
inheritedDuplicate: 'Cannot replace a message that also appears in inherited history.',
|
|
47
|
+
locked: 'Session is in use and cannot be edited right now.', changed: 'Session state changed. Reopen the editor.',
|
|
48
|
+
'composer-unavailable': 'Failed to load the editor. Refresh the page and try again.',
|
|
49
|
+
'toolbar-update': 'Plugin version mismatch. Reload the plugin.',
|
|
50
|
+
'child-conflict': 'Cannot rewind associated subagent sessions for this message.',
|
|
51
|
+
syncing: 'Message updated. Reopen the session to refresh.',
|
|
52
|
+
draftSaved: 'Draft preserved.',
|
|
53
|
+
deliveryUnknown: 'The connection dropped. Check whether the conversation was updated.',
|
|
54
|
+
draftConflict: 'Original message changed. Copy your draft and reopen to edit.',
|
|
55
|
+
textPart: 'Text block', sendPart: 'Send',
|
|
56
|
+
'reconnect-unavailable': 'Session connection unavailable. Reopen this session.',
|
|
57
|
+
'authentication-required': 'Sign in required.', failed: 'Failed to update message. Try again.',
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
const zhErrorCodes = new Map(Object.entries(strings.zh).map(([key, value]) => [value, key]));
|
|
61
|
+
const messageSeat = '[data-slot="conversation.chat.user.before"]';
|
|
62
|
+
const editingRow = `div:has(> ${messageSeat} > .dsh-revision-editor)`;
|
|
63
|
+
const originalContent = `${editingRow} > ${messageSeat} + *`;
|
|
64
|
+
const originalBubble = `${originalContent} > [data-message-bubble]`;
|
|
65
|
+
const css = `
|
|
66
|
+
/* rc.5 seats this contribution before the user bubble and Copy after it. */
|
|
67
|
+
div:has(> ${messageSeat} > .dsh-revision-pencil):has(> [data-clock="start"]) { position: relative; }
|
|
68
|
+
div:has(> ${messageSeat} > .dsh-revision-pencil) > [data-clock="start"] > button {
|
|
69
|
+
margin-left: calc(36px + var(--dsh-content-font-delta, 0px));
|
|
70
|
+
}
|
|
71
|
+
div:has(> [data-clock="start"]) > ${messageSeat} > .dsh-revision-pencil { display: inline-grid; }
|
|
72
|
+
.dsh-revision-pencil {
|
|
73
|
+
position: absolute;
|
|
74
|
+
right: calc(36px + var(--dsh-content-font-delta, 0px));
|
|
75
|
+
bottom: 0;
|
|
76
|
+
display: none;
|
|
77
|
+
place-items: center;
|
|
78
|
+
width: calc(28px + var(--dsh-content-font-delta, 0px));
|
|
79
|
+
height: calc(28px + var(--dsh-content-font-delta, 0px));
|
|
80
|
+
padding: 0;
|
|
81
|
+
border: 0;
|
|
82
|
+
border-radius: var(--dsw-radius-sm, 6px);
|
|
83
|
+
background: transparent;
|
|
84
|
+
color: var(--dsw-alias-label-tertiary);
|
|
85
|
+
cursor: pointer;
|
|
86
|
+
}
|
|
87
|
+
.dsh-revision-pencil svg {
|
|
88
|
+
width: calc(15px + var(--dsh-content-font-delta, 0px));
|
|
89
|
+
height: calc(15px + var(--dsh-content-font-delta, 0px));
|
|
90
|
+
}
|
|
91
|
+
.dsh-revision-pencil:hover {
|
|
92
|
+
background: var(--dsw-alias-interactive-bg-hover);
|
|
93
|
+
color: var(--dsw-alias-label-secondary);
|
|
94
|
+
}
|
|
95
|
+
.dsh-revision-pencil[aria-busy="true"] { cursor: progress; }
|
|
96
|
+
.dsh-revision-pencil::after {
|
|
97
|
+
content: attr(data-tooltip);
|
|
98
|
+
position: absolute;
|
|
99
|
+
z-index: 2;
|
|
100
|
+
top: calc(100% + 6px);
|
|
101
|
+
left: 50%;
|
|
102
|
+
transform: translateX(-50%);
|
|
103
|
+
padding: 4px 8px;
|
|
104
|
+
border-radius: var(--dsw-radius-sm, 6px);
|
|
105
|
+
background: var(--dsw-alias-tooltip-bg);
|
|
106
|
+
color: var(--dsw-alias-tooltip-label);
|
|
107
|
+
font: 12px / 18px var(--dsw-font-family);
|
|
108
|
+
white-space: nowrap;
|
|
109
|
+
pointer-events: none;
|
|
110
|
+
visibility: hidden;
|
|
111
|
+
opacity: 0;
|
|
112
|
+
transition: opacity 100ms ease;
|
|
113
|
+
}
|
|
114
|
+
.dsh-revision-pencil:not([data-tooltip-dismissed]):focus-visible::after {
|
|
115
|
+
visibility: visible;
|
|
116
|
+
opacity: 1;
|
|
117
|
+
}
|
|
118
|
+
@media (hover: hover) {
|
|
119
|
+
.dsh-revision-pencil:not([data-tooltip-dismissed]):hover::after {
|
|
120
|
+
visibility: visible;
|
|
121
|
+
opacity: 1;
|
|
122
|
+
transition-delay: 250ms;
|
|
123
|
+
}
|
|
124
|
+
[data-chat-flow-kind="user"]:has(~ :is([data-chat-flow-kind="user"], [data-chat-flow-kind="steering"])) .dsh-revision-pencil {
|
|
125
|
+
opacity: 0;
|
|
126
|
+
}
|
|
127
|
+
[data-chat-flow-kind="user"]:has(~ :is([data-chat-flow-kind="user"], [data-chat-flow-kind="steering"])):is(:hover, :focus-within) .dsh-revision-pencil {
|
|
128
|
+
opacity: 1;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/* The native composer renders the editable attachment rail. Keep the original
|
|
132
|
+
message's references and extra blocks visible around it. */
|
|
133
|
+
${editingRow} > [data-clock="start"],
|
|
134
|
+
${originalContent}:has(> [data-message-bubble]:only-child > span:only-child),
|
|
135
|
+
${originalBubble}:has(> span:only-child),
|
|
136
|
+
${originalBubble} > span:first-child,
|
|
137
|
+
${originalContent} > [data-message-attachments] { display: none; }
|
|
138
|
+
.dsh-revision-editor {
|
|
139
|
+
box-sizing: border-box;
|
|
140
|
+
order: 1;
|
|
141
|
+
align-self: center;
|
|
142
|
+
width: calc(100% + 32px);
|
|
143
|
+
min-width: 0;
|
|
144
|
+
--dsh-composer-side-clearance: 0px;
|
|
145
|
+
}
|
|
146
|
+
.dsh-revision-text-part { display: grid; gap: 4px; margin: 6px 0; }
|
|
147
|
+
.dsh-revision-text-part textarea {
|
|
148
|
+
box-sizing: border-box;
|
|
149
|
+
padding: 6px 10px;
|
|
150
|
+
color: inherit;
|
|
151
|
+
font: inherit;
|
|
152
|
+
background: transparent;
|
|
153
|
+
border: 1px solid var(--dsw-alias-border-primary, currentColor);
|
|
154
|
+
border-radius: var(--dsw-radius-sm, 6px);
|
|
155
|
+
field-sizing: content;
|
|
156
|
+
resize: none;
|
|
157
|
+
}
|
|
158
|
+
.dsh-revision-editor [data-composer-card] > :has(> .dsh-revision-cancel) { display: contents; }
|
|
159
|
+
.dsh-revision-editor .dsh-revision-cancel {
|
|
160
|
+
position: absolute;
|
|
161
|
+
z-index: 2;
|
|
162
|
+
top: 6px;
|
|
163
|
+
right: 8px;
|
|
164
|
+
display: grid;
|
|
165
|
+
place-items: center;
|
|
166
|
+
width: 28px;
|
|
167
|
+
height: 28px;
|
|
168
|
+
padding: 0;
|
|
169
|
+
border: 0;
|
|
170
|
+
border-radius: var(--dsw-radius-sm);
|
|
171
|
+
background: transparent;
|
|
172
|
+
color: var(--dsw-alias-label-secondary);
|
|
173
|
+
cursor: pointer;
|
|
174
|
+
}
|
|
175
|
+
.dsh-revision-editor .dsh-revision-cancel:not(:disabled):hover {
|
|
176
|
+
background: var(--dsw-alias-interactive-bg-hover);
|
|
177
|
+
}
|
|
178
|
+
/* Preserve the native scrollport and reserve space for the close button. */
|
|
179
|
+
.dsh-revision-editor [contenteditable] { padding-inline-end: 36px; }
|
|
180
|
+
.dsh-revision-feedback {
|
|
181
|
+
position: fixed;
|
|
182
|
+
z-index: 1000;
|
|
183
|
+
top: var(--dsw-spacing-xl, 24px);
|
|
184
|
+
left: 50%;
|
|
185
|
+
max-width: min(90vw, 32rem);
|
|
186
|
+
padding: 8px 12px;
|
|
187
|
+
transform: translateX(-50%);
|
|
188
|
+
border-radius: var(--dsw-radius-sm);
|
|
189
|
+
background: var(--dsw-alias-tooltip-bg);
|
|
190
|
+
color: var(--dsw-alias-tooltip-label);
|
|
191
|
+
}
|
|
192
|
+
`;
|
|
193
|
+
|
|
194
|
+
/*!
|
|
195
|
+
* Tabler Icons v3.31.0, outline pencil and x.
|
|
196
|
+
* https://github.com/tabler/tabler-icons/tree/v3.31.0/icons/outline
|
|
197
|
+
* MIT License
|
|
198
|
+
* Copyright (c) 2020-2024 Paweł Kuna
|
|
199
|
+
*
|
|
200
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
201
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
202
|
+
* in the Software without restriction, including without limitation the rights
|
|
203
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
204
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
205
|
+
* furnished to do so, subject to the following conditions:
|
|
206
|
+
*
|
|
207
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
208
|
+
* copies or substantial portions of the Software.
|
|
209
|
+
*
|
|
210
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
211
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
212
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
213
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
214
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
215
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
216
|
+
* SOFTWARE.
|
|
217
|
+
*/
|
|
218
|
+
const tablerPaths = {
|
|
219
|
+
pencil: ['M4 20h4l10.5 -10.5a2.828 2.828 0 1 0 -4 -4l-10.5 10.5v4', 'M13.5 6.5l4 4'],
|
|
220
|
+
x: ['M18 6l-12 12', 'M6 6l12 12'],
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
function TablerIcon({ name, size = 16, strokeWidth = 2 }) {
|
|
224
|
+
return h('svg', { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor',
|
|
225
|
+
strokeWidth, strokeLinecap: 'round', strokeLinejoin: 'round', focusable: 'false', 'aria-hidden': true },
|
|
226
|
+
tablerPaths[name].map(d => h('path', { d, key: d })));
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const composerSlot = 'conversation.composer.bar';
|
|
230
|
+
const editorFactory = 'dsh-message-revision.editor';
|
|
231
|
+
const toastFactory = 'workspace.toast.content';
|
|
232
|
+
const emptyUploads = Object.freeze({});
|
|
233
|
+
const emptyUploadSource = Object.freeze({ getSnapshot: () => emptyUploads, subscribe: () => () => {} });
|
|
234
|
+
const closedMenu = select => select(null);
|
|
235
|
+
|
|
236
|
+
function replaceMethod(object, key, next) {
|
|
237
|
+
const previous = Object.getOwnPropertyDescriptor(object, key);
|
|
238
|
+
Object.defineProperty(object, key, { configurable: true, writable: true, value: next });
|
|
239
|
+
return () => {
|
|
240
|
+
if (object[key] !== next) return;
|
|
241
|
+
if (previous) Object.defineProperty(object, key, previous);
|
|
242
|
+
else delete object[key];
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function sessionRuntime(ctx) {
|
|
247
|
+
const service = ctx.get('sessions');
|
|
248
|
+
return service?.[Symbol.for('cordis.original')] ?? service;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function sessionView(sessions, sessionId) {
|
|
252
|
+
const binding = sessions.binding?.(sessionId);
|
|
253
|
+
const session = binding?.session;
|
|
254
|
+
if (typeof session?.resync !== 'function' || typeof session.getSnapshot !== 'function'
|
|
255
|
+
|| typeof session.projections?.clear !== 'function') return undefined;
|
|
256
|
+
return binding;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function holdComposerSubmission(binding) {
|
|
260
|
+
const service = binding.ctx?.get('conversation');
|
|
261
|
+
const conversation = service?.[Symbol.for('cordis.original')] ?? service;
|
|
262
|
+
const send = conversation?.sendSession;
|
|
263
|
+
if (typeof send !== 'function') return () => {};
|
|
264
|
+
return replaceMethod(conversation, 'sendSession', function (session, ...args) {
|
|
265
|
+
if (session?.sessionId === binding.sessionId) return Promise.resolve({ kind: 'error' });
|
|
266
|
+
return send.call(this, session, ...args);
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function rebindComposerAttachments(binding) {
|
|
271
|
+
const conversation = binding.ctx?.get('conversation');
|
|
272
|
+
if (typeof conversation?.rebindDraftFiles !== 'function') return;
|
|
273
|
+
const input = conversation.input.for(binding.ctx);
|
|
274
|
+
const { attachmentIds } = input.state.getSnapshot();
|
|
275
|
+
if (attachmentIds.length > 0) {
|
|
276
|
+
// Reuse the File objects and draft IDs. The native service marks them
|
|
277
|
+
// uploading immediately and replaces receipts scoped to the old Agent.
|
|
278
|
+
conversation.rebindDraftFiles(binding.sessionId, attachmentIds, binding.session.getSnapshot().subagent === null);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function clearSessionProjections(manager, sessionId, projections) {
|
|
283
|
+
manager.projectionInflight?.get(sessionId)?.controller.abort();
|
|
284
|
+
manager.projectionInflight?.delete(sessionId);
|
|
285
|
+
manager.projectionLoads?.delete(sessionId);
|
|
286
|
+
projections?.clear?.();
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const inheritedWindows = new WeakMap();
|
|
290
|
+
const inheritedNodes = new WeakMap();
|
|
291
|
+
const emptySubscribe = () => () => {};
|
|
292
|
+
|
|
293
|
+
function inheritedBoundary(eventSource) {
|
|
294
|
+
const window = eventSource?.getSnapshot();
|
|
295
|
+
if (!window) return -1;
|
|
296
|
+
const previous = inheritedWindows.get(eventSource);
|
|
297
|
+
if (previous?.revision === window.revision) return previous.boundary;
|
|
298
|
+
const change = window.change;
|
|
299
|
+
const incremental = previous?.revision + 1 === window.revision && change?.kind !== 'replace';
|
|
300
|
+
let boundary = incremental ? previous.boundary : -1;
|
|
301
|
+
const entries = incremental ? change?.entries : window.entries;
|
|
302
|
+
for (const { event } of entries ?? []) {
|
|
303
|
+
if (event.type === 'session/end-seed' && event.data?.inherited === true) boundary = Math.max(event.seq, boundary);
|
|
304
|
+
}
|
|
305
|
+
inheritedWindows.set(eventSource, { revision: window.revision, boundary });
|
|
306
|
+
return boundary;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function isInheritedMessage(nodes, source, boundary) {
|
|
310
|
+
if (!nodes || boundary < 0) return false;
|
|
311
|
+
// The native store identity survives history pagination. Its values
|
|
312
|
+
// snapshot changes when new rows become available.
|
|
313
|
+
const values = nodes.values();
|
|
314
|
+
let indexed = inheritedNodes.get(values);
|
|
315
|
+
if (indexed?.boundary !== boundary) {
|
|
316
|
+
const sources = new Map();
|
|
317
|
+
for (const node of values) {
|
|
318
|
+
if (node.kind !== 'user') continue;
|
|
319
|
+
const own = node.data.seq >= boundary;
|
|
320
|
+
sources.set(node.data.source, own || sources.get(node.data.source) === true);
|
|
321
|
+
}
|
|
322
|
+
indexed = { boundary, sources };
|
|
323
|
+
inheritedNodes.set(values, indexed);
|
|
324
|
+
}
|
|
325
|
+
return indexed.sources.get(source) === false;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function isEditableSessionMessage({ allowed, subagent, inherited }) {
|
|
329
|
+
return Boolean(allowed) && !subagent && !inherited;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
async function resyncSessionView(sessions, sessionId, binding) {
|
|
333
|
+
clearSessionProjections(sessions.manager, sessionId, binding.session.projections);
|
|
334
|
+
await binding.session.resync();
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function watchSessionViews(sessions) {
|
|
338
|
+
const manager = sessions?.manager;
|
|
339
|
+
const remove = manager?.handleSessionRemoved;
|
|
340
|
+
const add = manager?.handleSessionAdded;
|
|
341
|
+
if (typeof remove !== 'function' || typeof add !== 'function') return undefined;
|
|
342
|
+
const holds = new Map();
|
|
343
|
+
const transitions = new WeakMap();
|
|
344
|
+
let childReloads = Promise.resolve();
|
|
345
|
+
let disposed = false;
|
|
346
|
+
|
|
347
|
+
function reloadParentCatalogs(ids) {
|
|
348
|
+
if (disposed || !Array.isArray(ids) || ids.length === 0 || ids.length > 128) return childReloads;
|
|
349
|
+
// An older list pull also writes these stores. Let that specific pull
|
|
350
|
+
// settle before clearing the old sequence watermark.
|
|
351
|
+
const listBeforeRevision = manager.listInflight;
|
|
352
|
+
if (listBeforeRevision) {
|
|
353
|
+
childReloads = childReloads.then(() => listBeforeRevision).catch(() => {});
|
|
354
|
+
}
|
|
355
|
+
for (const id of new Set(ids)) {
|
|
356
|
+
if (typeof id !== 'string' || id.length === 0 || id.length > 2048) continue;
|
|
357
|
+
childReloads = childReloads.then(async () => {
|
|
358
|
+
if (disposed) return;
|
|
359
|
+
const store = manager.projectionStores?.get(id);
|
|
360
|
+
if (!store) return;
|
|
361
|
+
// A rewrite lowers the native projection watermark. List-only tabs
|
|
362
|
+
// keep this store without ever binding or opening the conversation.
|
|
363
|
+
clearSessionProjections(manager, id, store);
|
|
364
|
+
await manager.refreshProjections?.(id);
|
|
365
|
+
}).catch(() => {});
|
|
366
|
+
}
|
|
367
|
+
return childReloads;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function reloadChildren(rewritten, withdrawn, affectedParentIds) {
|
|
371
|
+
if (disposed) return childReloads;
|
|
372
|
+
reloadParentCatalogs(affectedParentIds);
|
|
373
|
+
const changes = new Map();
|
|
374
|
+
for (const [ids, removed] of [[rewritten, false], [withdrawn, true]]) {
|
|
375
|
+
if (!Array.isArray(ids) || ids.length > 127) continue;
|
|
376
|
+
for (const id of ids) {
|
|
377
|
+
if (typeof id === 'string' && id.length > 0 && id.length <= 2048) changes.set(id, removed);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
if (changes.size > 127) return childReloads;
|
|
381
|
+
for (const [id, withdrawnChild] of changes) {
|
|
382
|
+
childReloads = childReloads.then(async () => {
|
|
383
|
+
if (disposed) return;
|
|
384
|
+
const binding = sessionView(sessions, id);
|
|
385
|
+
if (!binding) {
|
|
386
|
+
clearSessionProjections(manager, id, manager.projectionStores?.get(id));
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
const { session } = binding;
|
|
390
|
+
const snapshot = session.getSnapshot();
|
|
391
|
+
if (snapshot.openState === 'cold' || (snapshot.removed && !withdrawnChild)) {
|
|
392
|
+
clearSessionProjections(manager, id, session.projections);
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
let transition = transitions.get(binding);
|
|
396
|
+
if (withdrawnChild && !transition) {
|
|
397
|
+
transition = { removal: 0, addition: 0, scheduled: -1, work: Promise.resolve() };
|
|
398
|
+
transitions.set(binding, transition);
|
|
399
|
+
}
|
|
400
|
+
const removal = transition?.removal;
|
|
401
|
+
let addition = transition?.addition;
|
|
402
|
+
await resyncSessionView(sessions, id, binding);
|
|
403
|
+
if (!withdrawnChild) return;
|
|
404
|
+
const currentBinding = () => !disposed && sessions.binding(id) === binding && transition.removal === removal;
|
|
405
|
+
if (!currentBinding()) return;
|
|
406
|
+
const notFound = ({ openState, openError }) => openState === 'error'
|
|
407
|
+
&& (openError?.code === 'subagent/not-found' || openError?.code === 'session/not-found');
|
|
408
|
+
let current = session.getSnapshot();
|
|
409
|
+
// An addition while the read is pending may refer to a replacement
|
|
410
|
+
// under the same ID. Discard stale absence and verify the new view.
|
|
411
|
+
if (notFound(current) && transition.addition !== addition) {
|
|
412
|
+
addition = transition.addition;
|
|
413
|
+
await resyncSessionView(sessions, id, binding);
|
|
414
|
+
if (!currentBinding()) return;
|
|
415
|
+
current = session.getSnapshot();
|
|
416
|
+
}
|
|
417
|
+
if (notFound(current) && transition.addition === addition) {
|
|
418
|
+
session.installWindow?.([], false);
|
|
419
|
+
session.handleRemoved?.();
|
|
420
|
+
} else if (current.openState === 'open' && session.removed === true) {
|
|
421
|
+
session.removed = false;
|
|
422
|
+
session.notifier?.markDirty();
|
|
423
|
+
}
|
|
424
|
+
}).catch(() => {});
|
|
425
|
+
}
|
|
426
|
+
return childReloads;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
const undoRemove = replaceMethod(manager, 'handleSessionRemoved', function (id) {
|
|
430
|
+
const binding = sessionView(sessions, id);
|
|
431
|
+
const transition = binding && transitions.get(binding);
|
|
432
|
+
if (transition) transition.removal++;
|
|
433
|
+
const hold = holds.get(id);
|
|
434
|
+
if (hold) {
|
|
435
|
+
hold.removed();
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
return remove.call(this, id);
|
|
439
|
+
});
|
|
440
|
+
let undoAdd;
|
|
441
|
+
try {
|
|
442
|
+
undoAdd = replaceMethod(manager, 'handleSessionAdded', function (summary) {
|
|
443
|
+
const id = summary.sessionId;
|
|
444
|
+
const binding = sessionView(sessions, id);
|
|
445
|
+
const session = binding?.session;
|
|
446
|
+
// Native removal can discard the Manager's entry while the retained
|
|
447
|
+
// Session still uses the store. Rejoin before the new list seed lands.
|
|
448
|
+
if (summary.agentAvailable === true && session?.getSnapshot().removed
|
|
449
|
+
&& manager.projectionStores?.get(id) !== session.projections) {
|
|
450
|
+
manager.projectionStores?.set(id, session.projections);
|
|
451
|
+
}
|
|
452
|
+
const result = add.call(this, summary);
|
|
453
|
+
if (disposed || summary.agentAvailable !== true) return result;
|
|
454
|
+
const activeTransition = binding && transitions.get(binding);
|
|
455
|
+
if (activeTransition) activeTransition.addition++;
|
|
456
|
+
const hold = holds.get(id);
|
|
457
|
+
if (hold) {
|
|
458
|
+
hold.added();
|
|
459
|
+
return result;
|
|
460
|
+
}
|
|
461
|
+
if (!session?.getSnapshot().removed || session.removed !== true || typeof session.notifier?.markDirty !== 'function') {
|
|
462
|
+
return result;
|
|
463
|
+
}
|
|
464
|
+
// Each tab receives the native event pair. An ordinary deletion remains
|
|
465
|
+
// removed. A live addition for the same ID establishes a new history
|
|
466
|
+
// generation, including when another tab performed the rewrite.
|
|
467
|
+
let transition = transitions.get(binding);
|
|
468
|
+
if (!transition) {
|
|
469
|
+
transition = { removal: 0, addition: 0, scheduled: -1, work: Promise.resolve() };
|
|
470
|
+
transitions.set(binding, transition);
|
|
471
|
+
}
|
|
472
|
+
const removal = transition.removal;
|
|
473
|
+
if (transition.scheduled === removal) return result;
|
|
474
|
+
transition.scheduled = removal;
|
|
475
|
+
const current = () => !disposed && sessions.binding(id) === binding && transition.removal === removal;
|
|
476
|
+
transition.work = transition.work.then(async () => {
|
|
477
|
+
if (!current()) return;
|
|
478
|
+
rebindComposerAttachments(binding);
|
|
479
|
+
await resyncSessionView(sessions, id, binding);
|
|
480
|
+
if (!current() || session.getSnapshot().openState !== 'open') return;
|
|
481
|
+
// rc.5's native removal flag is one-way on a retained Session.
|
|
482
|
+
session.removed = false;
|
|
483
|
+
session.notifier.markDirty();
|
|
484
|
+
}).catch(() => {
|
|
485
|
+
// A failed sync leaves the view unavailable. Allow a later addition to retry.
|
|
486
|
+
}).finally(() => {
|
|
487
|
+
if (transition.scheduled === removal) transition.scheduled = -1;
|
|
488
|
+
});
|
|
489
|
+
return result;
|
|
490
|
+
});
|
|
491
|
+
} catch (error) {
|
|
492
|
+
undoRemove();
|
|
493
|
+
throw error;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
function holdSessionView(sessionId) {
|
|
497
|
+
const binding = sessionView(sessions, sessionId);
|
|
498
|
+
const session = binding?.session;
|
|
499
|
+
if (disposed || !binding || session.getSnapshot().removed || holds.has(sessionId)) {
|
|
500
|
+
throw new Error('reconnect-unavailable');
|
|
501
|
+
}
|
|
502
|
+
let removed = false;
|
|
503
|
+
let removalVersion = 0;
|
|
504
|
+
let resyncedRemoval = -1;
|
|
505
|
+
let readded = false;
|
|
506
|
+
let rebound = false;
|
|
507
|
+
let released = false;
|
|
508
|
+
let notifyAddition;
|
|
509
|
+
const releaseComposer = holdComposerSubmission(binding);
|
|
510
|
+
const rebind = () => {
|
|
511
|
+
if (rebound || disposed || released || sessions.binding(sessionId) !== binding) return;
|
|
512
|
+
rebindComposerAttachments(binding);
|
|
513
|
+
rebound = true;
|
|
514
|
+
releaseComposer();
|
|
515
|
+
};
|
|
516
|
+
const hold = {
|
|
517
|
+
removed() { removed = true; removalVersion++; readded = false; rebound = false; },
|
|
518
|
+
added() {
|
|
519
|
+
if (!removed || readded) return;
|
|
520
|
+
readded = true;
|
|
521
|
+
notifyAddition?.();
|
|
522
|
+
rebind();
|
|
523
|
+
},
|
|
524
|
+
release() {
|
|
525
|
+
if (released) return;
|
|
526
|
+
released = true;
|
|
527
|
+
holds.delete(sessionId);
|
|
528
|
+
notifyAddition?.();
|
|
529
|
+
releaseComposer();
|
|
530
|
+
if (removed && !readded && resyncedRemoval !== removalVersion) manager.handleSessionRemoved(sessionId);
|
|
531
|
+
},
|
|
532
|
+
};
|
|
533
|
+
holds.set(sessionId, hold);
|
|
534
|
+
return {
|
|
535
|
+
get removed() { return removed; },
|
|
536
|
+
release: hold.release,
|
|
537
|
+
async reconnect() {
|
|
538
|
+
if (!readded && !released) {
|
|
539
|
+
// The HTTP response and the native event stream can arrive in either order.
|
|
540
|
+
await new Promise(resolve => {
|
|
541
|
+
const timer = setTimeout(() => notifyAddition?.(), 1200);
|
|
542
|
+
notifyAddition = () => {
|
|
543
|
+
clearTimeout(timer);
|
|
544
|
+
notifyAddition = undefined;
|
|
545
|
+
resolve();
|
|
546
|
+
};
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
if (released || sessions.binding(sessionId) !== binding) return;
|
|
550
|
+
const verifyingRemoval = removalVersion;
|
|
551
|
+
await resyncSessionView(sessions, sessionId, binding);
|
|
552
|
+
if (released || sessions.binding(sessionId) !== binding) return;
|
|
553
|
+
const snapshot = session.getSnapshot();
|
|
554
|
+
if (snapshot.openState !== 'open' || snapshot.removed || verifyingRemoval !== removalVersion) {
|
|
555
|
+
throw new Error('syncing');
|
|
556
|
+
}
|
|
557
|
+
resyncedRemoval = verifyingRemoval;
|
|
558
|
+
rebind();
|
|
559
|
+
},
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
function reloadOpenChildren() {
|
|
564
|
+
let batch = [];
|
|
565
|
+
for (const id of sessions.scopes?.keys?.() ?? []) {
|
|
566
|
+
const snapshot = sessionView(sessions, id)?.session.getSnapshot();
|
|
567
|
+
if (!snapshot?.subagent || snapshot.openState === 'cold') continue;
|
|
568
|
+
batch.push(id);
|
|
569
|
+
if (batch.length === 127) {
|
|
570
|
+
reloadChildren([], batch);
|
|
571
|
+
batch = [];
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
return reloadChildren([], batch);
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
function refreshAfterNotificationGap() {
|
|
578
|
+
let batch = [];
|
|
579
|
+
for (const [id, projection] of manager.projectionStores ?? []) {
|
|
580
|
+
if (!projection.values?.()?.subagentCatalog?.length) continue;
|
|
581
|
+
batch.push(id);
|
|
582
|
+
if (batch.length === 128) {
|
|
583
|
+
reloadParentCatalogs(batch);
|
|
584
|
+
batch = [];
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
reloadParentCatalogs(batch);
|
|
588
|
+
return reloadOpenChildren();
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
return {
|
|
592
|
+
holdSessionView,
|
|
593
|
+
reloadChildren,
|
|
594
|
+
refreshAfterNotificationGap,
|
|
595
|
+
eventSource: sessionId => sessions.binding?.(sessionId)?.eventSource,
|
|
596
|
+
dispose() {
|
|
597
|
+
disposed = true;
|
|
598
|
+
for (const hold of holds.values()) hold.release();
|
|
599
|
+
undoAdd();
|
|
600
|
+
undoRemove();
|
|
601
|
+
},
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
// The corresponding Host descriptor is in revision-notifications.js.
|
|
606
|
+
const revisionRemoteName = 'messageRevisionEvents';
|
|
607
|
+
const revisionRemotePackage = '@kabxx/dsh-message-revision';
|
|
608
|
+
const revisionCursorPattern = /^[\da-f-]{36}:\d{1,16}$/u;
|
|
609
|
+
function revisionCodec(name, validate) {
|
|
610
|
+
return { mode: 'strict', typeSymbol: `${revisionRemotePackage}#${name}`, create: () => ({ parse(value) {
|
|
611
|
+
if (!validate(value)) throw new TypeError(`Invalid revision notification ${name}`);
|
|
612
|
+
return value;
|
|
613
|
+
} }) };
|
|
614
|
+
}
|
|
615
|
+
const revisionEventsContribution = { package: revisionRemotePackage, descriptors: [{
|
|
616
|
+
id: `${revisionRemotePackage}#${revisionRemoteName}/watch`, service: revisionRemoteName,
|
|
617
|
+
namespace: revisionRemoteName, method: 'watch', invocation: { kind: 'direct' },
|
|
618
|
+
mode: 'stream', cancellation: { parameter: 'signal' },
|
|
619
|
+
parameters: [{ name: 'cursor', wire: 'cursor', source: 'json', codec: revisionCodec('Cursor', value =>
|
|
620
|
+
value === null || (typeof value === 'string' && revisionCursorPattern.test(value))) }],
|
|
621
|
+
result: revisionCodec('Notice', value => {
|
|
622
|
+
const ids = (items, limit = 127) => Array.isArray(items) && items.length <= limit
|
|
623
|
+
&& items.every(id => typeof id === 'string' && id.length > 0 && id.length <= 2048);
|
|
624
|
+
return value && typeof value.cursor === 'string' && revisionCursorPattern.test(value.cursor)
|
|
625
|
+
&& (value.type === 'reset' || (value.type === 'revision' && ids(value.rewrittenChildren)
|
|
626
|
+
&& ids(value.withdrawnChildren) && value.rewrittenChildren.length + value.withdrawnChildren.length <= 127
|
|
627
|
+
&& (value.affectedParentIds === undefined || ids(value.affectedParentIds, 128))));
|
|
628
|
+
}),
|
|
629
|
+
}] };
|
|
630
|
+
|
|
631
|
+
function connectRevisionViews(views, remote, watch) {
|
|
632
|
+
let disposed = false;
|
|
633
|
+
let stream;
|
|
634
|
+
let retry;
|
|
635
|
+
let delay = 1000;
|
|
636
|
+
let cursor = null;
|
|
637
|
+
async function connect() {
|
|
638
|
+
if (disposed) return;
|
|
639
|
+
try {
|
|
640
|
+
stream = remote.$stream({
|
|
641
|
+
name: 'message revision history changes',
|
|
642
|
+
open: signal => watch(cursor, signal),
|
|
643
|
+
ended: () => new Error('Message revision history stream ended'),
|
|
644
|
+
});
|
|
645
|
+
for await (const item of stream) {
|
|
646
|
+
if (disposed) return;
|
|
647
|
+
const change = item.value;
|
|
648
|
+
if (change.type === 'reset') await views.refreshAfterNotificationGap();
|
|
649
|
+
else await views.reloadChildren(change.rewrittenChildren, change.withdrawnChildren, change.affectedParentIds);
|
|
650
|
+
if (disposed) return;
|
|
651
|
+
cursor = change.cursor;
|
|
652
|
+
delay = 1000;
|
|
653
|
+
item.accept();
|
|
654
|
+
}
|
|
655
|
+
} catch { /* A terminal failure may be temporary, such as a Host plugin reload. */ }
|
|
656
|
+
if (!disposed) {
|
|
657
|
+
retry = setTimeout(connect, delay);
|
|
658
|
+
delay = Math.min(delay * 2, 30_000);
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
void connect();
|
|
662
|
+
return async () => {
|
|
663
|
+
disposed = true;
|
|
664
|
+
clearTimeout(retry);
|
|
665
|
+
await stream?.dispose();
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
function hookFor(source) {
|
|
670
|
+
const subscribe = listener => source.subscribe(listener);
|
|
671
|
+
const getSnapshot = () => source.getSnapshot();
|
|
672
|
+
return select => select(useSyncExternalStore(subscribe, getSnapshot));
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
// rc.5 exposes the native bar as a slot entry, not a separately exported React component.
|
|
676
|
+
// Take the component from its registration, without replacing the resident slot.
|
|
677
|
+
function nativeComposerEntry(slots) {
|
|
678
|
+
const entries = slots.entries?.(composerSlot) ?? [];
|
|
679
|
+
const native = entries.filter(entry => entry.locale === 'conversation'
|
|
680
|
+
&& typeof entry.inject === 'function' && entry.children?.['conversation.input.model']
|
|
681
|
+
&& entry.children?.['conversation.input.attachments']);
|
|
682
|
+
return native.length === 1 ? native[0] : undefined;
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
function revisionDraftKey(sessionId, messageId) {
|
|
686
|
+
return JSON.stringify([sessionId, messageId]);
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
function snapshotRevisionDraft(edit, text, attachmentIds, textParts) {
|
|
690
|
+
const { retained, conversation } = edit.composer;
|
|
691
|
+
const retainedIndices = [];
|
|
692
|
+
const fileIds = [];
|
|
693
|
+
for (const id of attachmentIds) {
|
|
694
|
+
if (retained.has(id)) retainedIndices.push(retained.get(id).index);
|
|
695
|
+
else fileIds.push(id);
|
|
696
|
+
}
|
|
697
|
+
const available = new Map((conversation?.resolveDraftAttachments(fileIds) ?? []).map(item => [item.id, item.file]));
|
|
698
|
+
const files = fileIds.map(id => available.get(id));
|
|
699
|
+
if (files.some(file => !file)) throw new Error('fileUnavailable');
|
|
700
|
+
return {
|
|
701
|
+
text, textParts, files, retainedIndices, settings: { ...edit.settings },
|
|
702
|
+
original: edit.original, originalTextParts: edit.originalTextParts, originalAttachments: edit.originalAttachments,
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
function canRestoreRevisionDraft(saved, preview) {
|
|
707
|
+
return saved.original === preview.text
|
|
708
|
+
&& JSON.stringify(saved.originalTextParts) === JSON.stringify(preview.textParts)
|
|
709
|
+
&& saved.originalAttachments === JSON.stringify(preview.attachments);
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
function seedRevisionDraft(shell, retained, uploaded, conversation, sessionId, text, saved) {
|
|
713
|
+
shell.setDraft(saved?.text ?? text);
|
|
714
|
+
const retainedIndices = saved && new Set(saved.retainedIndices);
|
|
715
|
+
const ids = [...retained].filter(([, attachment]) => !retainedIndices || retainedIndices.has(attachment.index))
|
|
716
|
+
.map(([id]) => id);
|
|
717
|
+
for (const file of saved?.files ?? []) {
|
|
718
|
+
const [attachment] = conversation?.createDrafts(sessionId, [file], true) ?? [];
|
|
719
|
+
if (!attachment) throw new Error('fileUnavailable');
|
|
720
|
+
uploaded.add(attachment.id);
|
|
721
|
+
ids.push(attachment.id);
|
|
722
|
+
}
|
|
723
|
+
if (!shell.addAttachments(ids)) throw new Error('composer-unavailable');
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
function openDraft(ctx, native, sessionId, text, attachments, submit, saved) {
|
|
727
|
+
const injected = native.inject(sessionId);
|
|
728
|
+
const original = injected?.keyboard;
|
|
729
|
+
if (typeof original?.constructor !== 'function' || typeof original.deps?.defaultSink !== 'function'
|
|
730
|
+
|| typeof original.editor?.getRootElement !== 'function' || !injected.hooks) {
|
|
731
|
+
throw new Error('composer-unavailable');
|
|
732
|
+
}
|
|
733
|
+
const conversation = ctx.get('conversation');
|
|
734
|
+
const imageService = ctx.get('uiConversation');
|
|
735
|
+
const retained = new Map(attachments.map(({ index, block }) => {
|
|
736
|
+
const ref = block.attachment;
|
|
737
|
+
const image = block.type === 'image';
|
|
738
|
+
return [`revision-attachment:${index}`, {
|
|
739
|
+
index, image, ref,
|
|
740
|
+
descriptor: {
|
|
741
|
+
kind: image ? 'image' : 'file', id: `revision-attachment:${index}`,
|
|
742
|
+
// Display metadata only. The original bytes and immutable native ref stay on the host.
|
|
743
|
+
file: { name: ref.name ?? '', size: ref.bytes, type: ref.mediaType ?? '' },
|
|
744
|
+
},
|
|
745
|
+
}];
|
|
746
|
+
}));
|
|
747
|
+
const uploaded = new Set();
|
|
748
|
+
const shell = new original.constructor({
|
|
749
|
+
actx: original.deps.actx,
|
|
750
|
+
quoteRemoveLabel: original.deps.quoteRemoveLabel,
|
|
751
|
+
defaultSink: submit,
|
|
752
|
+
});
|
|
753
|
+
const useDraft = hookFor(shell.state);
|
|
754
|
+
const useFileUploads = hookFor(conversation?.fileUploads ?? emptyUploadSource);
|
|
755
|
+
function dispose() {
|
|
756
|
+
shell.dispose();
|
|
757
|
+
for (const id of uploaded) conversation.releaseDraftAttachment(id);
|
|
758
|
+
uploaded.clear();
|
|
759
|
+
}
|
|
760
|
+
try {
|
|
761
|
+
seedRevisionDraft(shell, retained, uploaded, conversation, sessionId, text, saved);
|
|
762
|
+
return {
|
|
763
|
+
shell, retained, conversation, imageService, uploaded, dispose, useDraft, useFileUploads,
|
|
764
|
+
registerFileIntake: injected.registerFileIntake,
|
|
765
|
+
useNotices: hookFor(shell.notices), useLexicon: hookFor(shell.lexicon),
|
|
766
|
+
useBusyEnter: hookFor(injected.hooks.busyEnter), useStopShortcut: hookFor(injected.hooks.stopShortcut),
|
|
767
|
+
};
|
|
768
|
+
} catch (error) {
|
|
769
|
+
dispose();
|
|
770
|
+
throw error;
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
function modelDirectoryWithSelection(directory, selection) {
|
|
775
|
+
if (!selection || !directory) return directory;
|
|
776
|
+
let previous, overlay;
|
|
777
|
+
return {
|
|
778
|
+
subscribe: listener => directory.subscribe(listener),
|
|
779
|
+
getSnapshot() {
|
|
780
|
+
const snapshot = directory.getSnapshot();
|
|
781
|
+
if (previous !== snapshot) {
|
|
782
|
+
previous = snapshot;
|
|
783
|
+
const entry = snapshot.groups.find(group => group.id === selection.provider)
|
|
784
|
+
?.models.find(model => model.id === selection.model);
|
|
785
|
+
const reasoning = entry?.reasoning;
|
|
786
|
+
const effort = selection.reasoningEffort ?? reasoning?.defaultEffort;
|
|
787
|
+
overlay = {
|
|
788
|
+
...snapshot, current: selection, routable: snapshot.routable === null ? null : entry !== undefined,
|
|
789
|
+
retainedEffort: effort === undefined ? undefined : reasoning?.efforts.find(level => level.id === effort)?.name ?? effort,
|
|
790
|
+
};
|
|
791
|
+
}
|
|
792
|
+
return overlay;
|
|
793
|
+
},
|
|
794
|
+
};
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
function NativeEditor({ edit, cancel, cancelLabel, requestPending, renderSlot, t, ...props }) {
|
|
798
|
+
const { shell, useDraft, useNotices, useLexicon, useBusyEnter, useStopShortcut,
|
|
799
|
+
useFileUploads, retained, conversation, imageService, uploaded, registerFileIntake } = edit.composer;
|
|
800
|
+
const phase = useDraft(state => state.phase);
|
|
801
|
+
const pending = requestPending || phase === 'sending' || phase === 'adjudicating' || phase === 'submitting';
|
|
802
|
+
const locked = pending || props.disabled;
|
|
803
|
+
const editingLocked = () => locked || edit.isSubmitting();
|
|
804
|
+
// Voice transcription can finish after a send, even when the control is locked.
|
|
805
|
+
const activityActions = useMemo(() => ({
|
|
806
|
+
...shell.actions,
|
|
807
|
+
insertText: (text, span) => !edit.isSubmitting() && shell.actions.insertText(text, span),
|
|
808
|
+
}), [edit, shell]);
|
|
809
|
+
const [model, setModel] = useState(edit.settings.model);
|
|
810
|
+
const [permission, setPermission] = useState(edit.settings.permissionPreset);
|
|
811
|
+
const [previews, setPreviews] = useState({});
|
|
812
|
+
const [, setPartsVersion] = useState(0);
|
|
813
|
+
const draftText = useDraft(state => state.draft);
|
|
814
|
+
const draftAttachments = useDraft(state => state.attachmentIds);
|
|
815
|
+
const sendRemainingText = edit.additionalText.length > 0 && !draftText.trim()
|
|
816
|
+
&& draftAttachments.length === 0 && edit.additionalText.some(value => value.trim());
|
|
817
|
+
const dropTarget = useRef(null);
|
|
818
|
+
const modelDirectory = useMemo(() => modelDirectoryWithSelection(edit.modelDirectory, model),
|
|
819
|
+
[edit, model]);
|
|
820
|
+
const historicalUploads = useMemo(() => Object.fromEntries([...retained.keys()].map(id => [id, { status: 'ready' }])), [retained]);
|
|
821
|
+
const useCombinedUploads = select => useFileUploads(snapshot => select({ ...historicalUploads, ...snapshot }));
|
|
822
|
+
useEffect(() => {
|
|
823
|
+
if (edit.restored) shell.focus();
|
|
824
|
+
}, [edit, shell]);
|
|
825
|
+
useEffect(() => {
|
|
826
|
+
if (!imageService) return undefined;
|
|
827
|
+
let mounted = true;
|
|
828
|
+
for (const [id, item] of retained) {
|
|
829
|
+
if (!item.image) continue;
|
|
830
|
+
void imageService.imageUrl(props.sessionId, item.ref).then(url => {
|
|
831
|
+
if (mounted) setPreviews(previous => ({ ...previous, [id]: url }));
|
|
832
|
+
}).catch(() => { /* A missing preview does not discard the original ref. */ });
|
|
833
|
+
}
|
|
834
|
+
return () => { mounted = false; };
|
|
835
|
+
}, [imageService, retained, props.sessionId]);
|
|
836
|
+
|
|
837
|
+
const resolveDraftAttachments = useCallback(ids => {
|
|
838
|
+
const picked = new Map((conversation?.resolveDraftAttachments(ids) ?? []).map(item => [item.id, item]));
|
|
839
|
+
return ids.flatMap(id => {
|
|
840
|
+
const existing = retained.get(id);
|
|
841
|
+
if (existing) return [{ ...existing.descriptor, ...(existing.image ? { previewUrl: previews[id] } : {}) }];
|
|
842
|
+
const current = picked.get(id);
|
|
843
|
+
return current ? [current] : [];
|
|
844
|
+
});
|
|
845
|
+
}, [conversation, retained, previews]);
|
|
846
|
+
function addFiles(files, directories) {
|
|
847
|
+
if (directories?.size > 0) return edit.labels.fileDirectory;
|
|
848
|
+
if (editingLocked() || typeof conversation?.createDrafts !== 'function') {
|
|
849
|
+
return edit.labels.fileUnavailable;
|
|
850
|
+
}
|
|
851
|
+
const drafts = [];
|
|
852
|
+
try {
|
|
853
|
+
for (const file of files) drafts.push(...conversation.createDrafts(props.sessionId, [file], true));
|
|
854
|
+
if (shell.addAttachments(drafts.map(item => item.id))) {
|
|
855
|
+
for (const item of drafts) uploaded.add(item.id);
|
|
856
|
+
return null;
|
|
857
|
+
}
|
|
858
|
+
} catch (error) {
|
|
859
|
+
for (const item of drafts) conversation.releaseDraftAttachment(item.id);
|
|
860
|
+
return error instanceof Error ? error.message : String(error);
|
|
861
|
+
}
|
|
862
|
+
for (const item of drafts) conversation.releaseDraftAttachment(item.id);
|
|
863
|
+
return edit.labels.fileUnavailable;
|
|
864
|
+
}
|
|
865
|
+
function removeAttachment(id) {
|
|
866
|
+
if (editingLocked() || !shell.removeAttachment(id)) return;
|
|
867
|
+
if (uploaded.delete(id)) conversation.releaseDraftAttachment(id);
|
|
868
|
+
}
|
|
869
|
+
const usePermissionProjection = (key, select) => props.useProjection(key, value => {
|
|
870
|
+
const view = key === 'permissions' && value !== undefined && value !== null && permission
|
|
871
|
+
? { ...value, currentValue: permission } : value;
|
|
872
|
+
return select ? select(view) : view;
|
|
873
|
+
});
|
|
874
|
+
const renderEditorSlot = (name, owner) => {
|
|
875
|
+
if (name === 'conversation.input.attachments') {
|
|
876
|
+
dropTarget.current = owner;
|
|
877
|
+
return renderSlot(name, { ...owner, canAcceptDrop: false });
|
|
878
|
+
}
|
|
879
|
+
if (name === 'conversation.input.permission') return renderSlot(name, {
|
|
880
|
+
...owner, useProjection: usePermissionProjection,
|
|
881
|
+
select: async preset => {
|
|
882
|
+
if (editingLocked()) return false;
|
|
883
|
+
edit.settings.permissionPreset = preset;
|
|
884
|
+
setPermission(preset);
|
|
885
|
+
return true;
|
|
886
|
+
},
|
|
887
|
+
});
|
|
888
|
+
if (name === 'conversation.input.model') return renderSlot(name, {
|
|
889
|
+
...owner,
|
|
890
|
+
...(modelDirectory === undefined ? { locked: true } : {
|
|
891
|
+
directory: modelDirectory,
|
|
892
|
+
select: async selection => {
|
|
893
|
+
if (editingLocked()) return { ok: false, error: { code: 'revision/busy', message: t('busy') } };
|
|
894
|
+
edit.settings.model = selection;
|
|
895
|
+
setModel(selection);
|
|
896
|
+
return { ok: true, value: undefined };
|
|
897
|
+
},
|
|
898
|
+
}),
|
|
899
|
+
});
|
|
900
|
+
if (name === 'conversation.input.activity') {
|
|
901
|
+
return renderSlot(name, { ...owner, inputActions: activityActions });
|
|
902
|
+
}
|
|
903
|
+
if (name === 'conversation.input.plan') return renderSlot(name, { ...owner, locked: true });
|
|
904
|
+
if (name === 'conversation.composer.dock') return renderSlot(name, owner);
|
|
905
|
+
// Extension controls address the resident draft through their session scope.
|
|
906
|
+
if (name === 'conversation.input.left' || name === 'conversation.input.right') {
|
|
907
|
+
return h('div', { inert: true }, renderSlot(name, owner));
|
|
908
|
+
}
|
|
909
|
+
return null;
|
|
910
|
+
};
|
|
911
|
+
function targetFileDrag(event, drop = false) {
|
|
912
|
+
const transfer = event.dataTransfer;
|
|
913
|
+
if (!transfer || !transfer.types.some(type => type === 'Files' || type === 'application/x-dsh-file')) return;
|
|
914
|
+
event.preventDefault();
|
|
915
|
+
event.stopPropagation();
|
|
916
|
+
const target = dropTarget.current;
|
|
917
|
+
transfer.dropEffect = target?.canAcceptDrop ? 'copy' : 'none';
|
|
918
|
+
if (!drop || !target?.canAcceptDrop) return;
|
|
919
|
+
const applicationFile = edit.readFileDrag?.(transfer);
|
|
920
|
+
const files = applicationFile === undefined ? [...transfer.files] : [applicationFile];
|
|
921
|
+
const directories = new Set();
|
|
922
|
+
let index = 0;
|
|
923
|
+
for (const item of transfer.items) {
|
|
924
|
+
if (item.kind !== 'file') continue;
|
|
925
|
+
const file = files[index++];
|
|
926
|
+
if (file && item.webkitGetAsEntry?.()?.isDirectory) directories.add(file);
|
|
927
|
+
}
|
|
928
|
+
target.onAddFiles(files, directories);
|
|
929
|
+
}
|
|
930
|
+
const canUpload = typeof conversation?.createDrafts === 'function' && typeof shell.pickFiles === 'function';
|
|
931
|
+
const uploadAllowed = props.useAccess('fileUploads/upload') !== false;
|
|
932
|
+
return h('div', {
|
|
933
|
+
className: 'dsh-revision-editor',
|
|
934
|
+
'aria-busy': requestPending || undefined,
|
|
935
|
+
onDragEnterCapture: event => targetFileDrag(event),
|
|
936
|
+
onDragOverCapture: event => targetFileDrag(event),
|
|
937
|
+
onDropCapture: event => targetFileDrag(event, true),
|
|
938
|
+
onKeyDown: event => {
|
|
939
|
+
if (event.key !== 'Escape' || event.defaultPrevented || event.nativeEvent.isComposing
|
|
940
|
+
|| !event.currentTarget.contains(event.target)
|
|
941
|
+
|| !event.target.closest('[contenteditable], .dsh-revision-cancel, .dsh-revision-text-part textarea')) return;
|
|
942
|
+
event.preventDefault();
|
|
943
|
+
event.stopPropagation();
|
|
944
|
+
if (!pending) cancel();
|
|
945
|
+
},
|
|
946
|
+
}, edit.additionalText.map((value, index) => h('label', {
|
|
947
|
+
key: index, className: 'dsh-revision-text-part',
|
|
948
|
+
}, `${edit.labels.textPart} ${index + 2}`, h('textarea', {
|
|
949
|
+
defaultValue: value, disabled: locked,
|
|
950
|
+
onChange: event => {
|
|
951
|
+
if (editingLocked()) return;
|
|
952
|
+
edit.additionalText[index] = event.currentTarget.value;
|
|
953
|
+
setPartsVersion(version => version + 1);
|
|
954
|
+
},
|
|
955
|
+
}))), h(edit.native.component, {
|
|
956
|
+
...props,
|
|
957
|
+
disabled: locked,
|
|
958
|
+
t: (key, ...args) => t(key === 'input.commands' ? 'input.file' : key, ...args),
|
|
959
|
+
variant: 'composer', occurrence: 'embedded',
|
|
960
|
+
renderSlot: renderEditorSlot, useInput: useDraft, inputActions: shell.actions,
|
|
961
|
+
keyboard: shell, useNotices, useMenuLauncher: closedMenu, useLexicon,
|
|
962
|
+
useBusyEnter, useStopShortcut, useFileUploads: useCombinedUploads,
|
|
963
|
+
registerFileIntake, resolveDraftAttachments, removeAttachment,
|
|
964
|
+
addFiles: canUpload ? addFiles : undefined,
|
|
965
|
+
retryFileUpload: id => { if (!editingLocked() && uploaded.has(id)) conversation.retryFileUpload(props.sessionId, id); },
|
|
966
|
+
toggleCommandMenu: canUpload && uploadAllowed ? () => { if (!editingLocked()) shell.pickFiles(); } : undefined,
|
|
967
|
+
retry: undefined, stop: undefined,
|
|
968
|
+
accessory: h('button', { type: 'button', className: 'dsh-revision-cancel', disabled: pending,
|
|
969
|
+
title: cancelLabel, 'aria-label': cancelLabel, onClick: cancel }, h(TablerIcon, { name: 'x' })),
|
|
970
|
+
}), sendRemainingText && h('button', { type: 'button', disabled: locked,
|
|
971
|
+
onClick: () => { if (!editingLocked()) void edit.submit(draftText, draftAttachments); },
|
|
972
|
+
}, edit.labels.sendPart));
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
return {
|
|
976
|
+
inject: ['slots', 'locale'],
|
|
977
|
+
apply(ctx) {
|
|
978
|
+
const lifetime = new AbortController();
|
|
979
|
+
let activeEditor;
|
|
980
|
+
let sessionViews;
|
|
981
|
+
const sessionViewListeners = new Set();
|
|
982
|
+
const readSessionViews = () => sessionViews;
|
|
983
|
+
const observeSessionViews = listener => {
|
|
984
|
+
sessionViewListeners.add(listener);
|
|
985
|
+
return () => sessionViewListeners.delete(listener);
|
|
986
|
+
};
|
|
987
|
+
function setSessionViews(next) {
|
|
988
|
+
if (sessionViews === next) return;
|
|
989
|
+
sessionViews = next;
|
|
990
|
+
for (const listener of sessionViewListeners) listener();
|
|
991
|
+
}
|
|
992
|
+
let pendingUnmount = Promise.resolve();
|
|
993
|
+
let submitting = false;
|
|
994
|
+
const savedDrafts = new Map();
|
|
995
|
+
const draftListeners = new Set();
|
|
996
|
+
let draftVersion = 0;
|
|
997
|
+
const readDraftVersion = () => draftVersion;
|
|
998
|
+
const observeDrafts = listener => {
|
|
999
|
+
draftListeners.add(listener);
|
|
1000
|
+
return () => draftListeners.delete(listener);
|
|
1001
|
+
};
|
|
1002
|
+
function keepDraft(key, saved) {
|
|
1003
|
+
savedDrafts.set(key, saved);
|
|
1004
|
+
draftVersion++;
|
|
1005
|
+
for (const listener of draftListeners) listener();
|
|
1006
|
+
}
|
|
1007
|
+
let currentNotice = null;
|
|
1008
|
+
let noticeSequence = 0;
|
|
1009
|
+
const noticeListeners = new Set();
|
|
1010
|
+
const observeNotices = listener => {
|
|
1011
|
+
noticeListeners.add(listener);
|
|
1012
|
+
return () => noticeListeners.delete(listener);
|
|
1013
|
+
};
|
|
1014
|
+
const readNotice = () => currentNotice;
|
|
1015
|
+
function publishNotice(notice) {
|
|
1016
|
+
currentNotice = notice;
|
|
1017
|
+
for (const listener of noticeListeners) listener();
|
|
1018
|
+
}
|
|
1019
|
+
function notify(text, tone = 'warning') {
|
|
1020
|
+
publishNotice({ text, tone, seq: ++noticeSequence });
|
|
1021
|
+
}
|
|
1022
|
+
function Feedback({ renderFactorySlot }) {
|
|
1023
|
+
const notice = useSyncExternalStore(observeNotices, readNotice);
|
|
1024
|
+
if (!notice) return null;
|
|
1025
|
+
const onDone = () => { if (currentNotice === notice) publishNotice(null); };
|
|
1026
|
+
return renderFactorySlot(toastFactory, { ...notice, onDone }, {
|
|
1027
|
+
fallback: h(FallbackNotice, { key: notice.seq, notice, onDone }),
|
|
1028
|
+
});
|
|
1029
|
+
}
|
|
1030
|
+
function FallbackNotice({ notice, onDone }) {
|
|
1031
|
+
useEffect(() => {
|
|
1032
|
+
const timer = setTimeout(onDone, 2400);
|
|
1033
|
+
return () => clearTimeout(timer);
|
|
1034
|
+
}, [onDone]);
|
|
1035
|
+
return h('div', { role: notice.tone === 'success' ? 'status' : 'alert', className: 'dsh-revision-feedback' }, notice.text);
|
|
1036
|
+
}
|
|
1037
|
+
let composerFactoryLive = false;
|
|
1038
|
+
|
|
1039
|
+
async function requestRevision(payload) {
|
|
1040
|
+
let response;
|
|
1041
|
+
try {
|
|
1042
|
+
response = await fetch('/api/message-revision', {
|
|
1043
|
+
method: 'POST', credentials: 'same-origin', signal: lifetime.signal,
|
|
1044
|
+
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload),
|
|
1045
|
+
});
|
|
1046
|
+
} catch (cause) {
|
|
1047
|
+
throw Object.assign(new Error('deliveryUnknown', { cause }), { deliveryUnknown: true });
|
|
1048
|
+
}
|
|
1049
|
+
if (response.status === 401 || response.status === 403) throw new Error('authentication-required');
|
|
1050
|
+
const result = await response.json().catch(() => null);
|
|
1051
|
+
if (result === null) throw Object.assign(new Error('deliveryUnknown'), { deliveryUnknown: true });
|
|
1052
|
+
if (!response.ok || result?.ok !== true) {
|
|
1053
|
+
throw Object.assign(new Error('failed'), {
|
|
1054
|
+
hostError: typeof result?.error === 'string' ? result.error : '',
|
|
1055
|
+
reconnect: result?.reconnect === true,
|
|
1056
|
+
});
|
|
1057
|
+
}
|
|
1058
|
+
return result;
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
const ownerAccessAction = 'settings/describe';
|
|
1062
|
+
|
|
1063
|
+
function RevisionAction({ t, matched, sessionId, useChat, useSession, useSessions, useAccess, useRemoteAccess, renderFactorySlot }) {
|
|
1064
|
+
// Exact Host routes (/api/message-revision) admit only the Host owner.
|
|
1065
|
+
// Core owner-only endpoints stay excluded from LiveShare viewer grants.
|
|
1066
|
+
const owner = useRemoteAccess(ownerAccessAction);
|
|
1067
|
+
const canPrompt = useAccess('session/prompt');
|
|
1068
|
+
const canUpdateQueue = useAccess('session/updateQueue');
|
|
1069
|
+
const allowed = owner && canPrompt && canUpdateQueue;
|
|
1070
|
+
const subagentAddress = useSession(s => s.subagent != null) ?? false;
|
|
1071
|
+
const subagentOrigin = useSessions(s => s.byId?.[sessionId]?.origin === 'subagent') ?? false;
|
|
1072
|
+
const subagent = subagentAddress || subagentOrigin;
|
|
1073
|
+
const status = useSession(s => s.removed || s.openState !== 'open' ? 'unavailable'
|
|
1074
|
+
: s.running || s.pendingSubmissions.length > 0 ? 'busy' : 'idle');
|
|
1075
|
+
const busy = status === 'busy';
|
|
1076
|
+
const nodes = useChat(s => s.nodes);
|
|
1077
|
+
const views = useSyncExternalStore(observeSessionViews, readSessionViews);
|
|
1078
|
+
const eventSource = views?.eventSource(sessionId);
|
|
1079
|
+
const subscribeToHistory = useCallback(listener => eventSource?.subscribe(listener) ?? emptySubscribe(), [eventSource]);
|
|
1080
|
+
const readInheritedBoundary = useCallback(() => inheritedBoundary(eventSource), [eventSource]);
|
|
1081
|
+
const inherited = useSyncExternalStore(subscribeToHistory, readInheritedBoundary);
|
|
1082
|
+
const inheritedMessage = isInheritedMessage(nodes, matched, inherited);
|
|
1083
|
+
const editable = isEditableSessionMessage({ allowed, subagent, inherited: inheritedMessage });
|
|
1084
|
+
const editableRef = useRef(editable);
|
|
1085
|
+
editableRef.current = editable;
|
|
1086
|
+
const savedVersion = useSyncExternalStore(observeDrafts, readDraftVersion);
|
|
1087
|
+
const [edit, setEdit] = useState(null);
|
|
1088
|
+
const [opening, setOpening] = useState(false);
|
|
1089
|
+
const [requestPending, setRequestPending] = useState(false);
|
|
1090
|
+
const [tooltipDismissed, setTooltipDismissed] = useState(false);
|
|
1091
|
+
const pencil = useRef(null);
|
|
1092
|
+
const restoreFocus = useRef(false);
|
|
1093
|
+
const pending = useRef(false);
|
|
1094
|
+
const ownerClaim = useRef(Symbol());
|
|
1095
|
+
const draft = useRef(null);
|
|
1096
|
+
useEffect(() => {
|
|
1097
|
+
setEdit(null);
|
|
1098
|
+
setOpening(false);
|
|
1099
|
+
return () => {
|
|
1100
|
+
if (activeEditor === ownerClaim.current) activeEditor = undefined;
|
|
1101
|
+
draft.current?.dispose();
|
|
1102
|
+
draft.current = null;
|
|
1103
|
+
};
|
|
1104
|
+
}, [sessionId, matched]);
|
|
1105
|
+
useLayoutEffect(() => {
|
|
1106
|
+
if (editable) return;
|
|
1107
|
+
setEdit(null);
|
|
1108
|
+
setOpening(false);
|
|
1109
|
+
if (activeEditor === ownerClaim.current) activeEditor = undefined;
|
|
1110
|
+
draft.current?.dispose();
|
|
1111
|
+
draft.current = null;
|
|
1112
|
+
}, [editable]);
|
|
1113
|
+
useLayoutEffect(() => {
|
|
1114
|
+
if (!edit && restoreFocus.current) {
|
|
1115
|
+
restoreFocus.current = false;
|
|
1116
|
+
pencil.current?.focus({ preventScroll: true });
|
|
1117
|
+
}
|
|
1118
|
+
}, [edit]);
|
|
1119
|
+
useEffect(() => {
|
|
1120
|
+
if (!editable || status !== 'idle' || edit || opening || activeEditor !== undefined || submitting) return;
|
|
1121
|
+
const node = messageInRow(pencil.current);
|
|
1122
|
+
if (!node) return;
|
|
1123
|
+
const saved = savedDrafts.get(revisionDraftKey(sessionId, node.data.messageId));
|
|
1124
|
+
if (saved?.reopenInView !== window.location.href) return;
|
|
1125
|
+
saved.reopenInView = undefined;
|
|
1126
|
+
void openEditor(node, saved);
|
|
1127
|
+
}, [editable, status, edit, opening, nodes, matched, sessionId, savedVersion]);
|
|
1128
|
+
if (!editable) return null;
|
|
1129
|
+
|
|
1130
|
+
function errorMessage(error) {
|
|
1131
|
+
const message = typeof error?.hostError === 'string' ? error.hostError.trim() : '';
|
|
1132
|
+
const code = (Object.hasOwn(strings.zh, message) ? message : zhErrorCodes.get(message))
|
|
1133
|
+
?? (Object.hasOwn(strings.zh, error?.message) ? error.message : zhErrorCodes.get(error?.message))
|
|
1134
|
+
?? null;
|
|
1135
|
+
return code ? t(code) : (message.slice(0, 240) || t('failed'));
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
function messageInRow(target) {
|
|
1139
|
+
const key = target?.closest('[data-chat-flow-kind="user"][data-chat-node-key]')?.dataset.chatNodeKey;
|
|
1140
|
+
const node = key === undefined ? undefined : nodes.get(key);
|
|
1141
|
+
return node?.kind === 'user' && node.data.source === matched && typeof node.data.messageId === 'string'
|
|
1142
|
+
? node : undefined;
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
function open(event) {
|
|
1146
|
+
if (status !== 'idle') { notify(t(busy ? 'busy' : 'reconnect-unavailable')); return; }
|
|
1147
|
+
if (activeEditor !== undefined || submitting) {
|
|
1148
|
+
if (!opening) notify(t('anotherEdit'));
|
|
1149
|
+
return;
|
|
1150
|
+
}
|
|
1151
|
+
const node = messageInRow(event.currentTarget);
|
|
1152
|
+
if (!node) { notify(t('missing')); return; }
|
|
1153
|
+
const saved = savedDrafts.get(revisionDraftKey(sessionId, node.data.messageId));
|
|
1154
|
+
void openEditor(node, saved);
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
async function openEditor(node, saved) {
|
|
1158
|
+
const content = node.data.content;
|
|
1159
|
+
if (!Array.isArray(content)) { notify(t('unsupported')); return; }
|
|
1160
|
+
const native = nativeComposerEntry(ctx.slots);
|
|
1161
|
+
if (!native || !composerFactoryLive) { notify(t('composer-unavailable')); return; }
|
|
1162
|
+
const claim = ownerClaim.current = Symbol();
|
|
1163
|
+
activeEditor = claim;
|
|
1164
|
+
setOpening(true);
|
|
1165
|
+
try {
|
|
1166
|
+
const result = await requestRevision({ sessionId, messageId: node.data.messageId });
|
|
1167
|
+
if (activeEditor !== claim || !editableRef.current || lifetime.signal.aborted) {
|
|
1168
|
+
if (activeEditor === claim) activeEditor = undefined;
|
|
1169
|
+
setOpening(false);
|
|
1170
|
+
return;
|
|
1171
|
+
}
|
|
1172
|
+
if (typeof result.revision !== 'string' || typeof result.text !== 'string') throw new Error('failed');
|
|
1173
|
+
if (result.toolbarRevision !== 1 || !Array.isArray(result.attachments)
|
|
1174
|
+
|| !Array.isArray(result.textParts) || result.textParts.some(part => typeof part !== 'string')
|
|
1175
|
+
|| result.textParts.join('') !== result.text) throw new Error('toolbar-update');
|
|
1176
|
+
const conflicted = saved !== undefined && !canRestoreRevisionDraft(saved, result);
|
|
1177
|
+
const key = revisionDraftKey(sessionId, node.data.messageId);
|
|
1178
|
+
const initialParts = (conflicted ? undefined : saved?.textParts) ?? result.textParts ?? [result.text];
|
|
1179
|
+
const hasSegments = initialParts.length > 1;
|
|
1180
|
+
const firstText = conflicted ? saved.text : hasSegments ? initialParts[0] : result.text;
|
|
1181
|
+
const edit = {
|
|
1182
|
+
key, conflicted, restored: saved !== undefined,
|
|
1183
|
+
messageId: node.data.messageId, revision: result.revision, original: result.text, native,
|
|
1184
|
+
originalTextParts: result.textParts,
|
|
1185
|
+
additionalText: hasSegments && !conflicted ? initialParts.slice(1) : [],
|
|
1186
|
+
originalAttachments: JSON.stringify(result.attachments), settings: { ...saved?.settings },
|
|
1187
|
+
originalSettings: result.settings ?? {},
|
|
1188
|
+
modelDirectory: ctx.slots.entries('conversation.input.model')
|
|
1189
|
+
.find(entry => entry.locale === 'model')?.inject?.(sessionId)?.directory,
|
|
1190
|
+
readFileDrag: transfer => ctx.get('fileDrag')?.read(transfer),
|
|
1191
|
+
labels: { fileDirectory: t('fileDirectory'), fileUnavailable: t('fileUnavailable'), textPart: t('textPart'), sendPart: t('sendPart') },
|
|
1192
|
+
isSubmitting: () => pending.current,
|
|
1193
|
+
submit: (text, attachmentIds) => submit(edit, text, attachmentIds, claim),
|
|
1194
|
+
};
|
|
1195
|
+
edit.composer = openDraft(ctx, native, sessionId, firstText, result.attachments,
|
|
1196
|
+
edit.submit,
|
|
1197
|
+
conflicted ? { ...saved, retainedIndices: [] } : hasSegments && saved ? { ...saved, text: firstText } : saved);
|
|
1198
|
+
if (conflicted) notify(t('draftConflict'));
|
|
1199
|
+
if (savedDrafts.get(key) === saved) savedDrafts.delete(key);
|
|
1200
|
+
draft.current = edit.composer;
|
|
1201
|
+
setOpening(false);
|
|
1202
|
+
setEdit(edit);
|
|
1203
|
+
} catch (error) {
|
|
1204
|
+
if (activeEditor !== claim || !editableRef.current || lifetime.signal.aborted) {
|
|
1205
|
+
if (activeEditor === claim) activeEditor = undefined;
|
|
1206
|
+
setOpening(false);
|
|
1207
|
+
return;
|
|
1208
|
+
}
|
|
1209
|
+
activeEditor = undefined;
|
|
1210
|
+
setOpening(false);
|
|
1211
|
+
notify(errorMessage(error));
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
function dismiss(restore = true) {
|
|
1216
|
+
if (activeEditor === ownerClaim.current) activeEditor = undefined;
|
|
1217
|
+
restoreFocus.current = restore === true;
|
|
1218
|
+
const composer = draft.current;
|
|
1219
|
+
draft.current = null;
|
|
1220
|
+
setEdit(null);
|
|
1221
|
+
composer?.dispose();
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
function cancel() {
|
|
1225
|
+
if (!pending.current) dismiss();
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
async function submit(edit, text, attachmentIds, claim) {
|
|
1229
|
+
if (edit.conflicted) {
|
|
1230
|
+
notify(t('draftConflict'));
|
|
1231
|
+
return { kind: 'error' };
|
|
1232
|
+
}
|
|
1233
|
+
const textParts = edit.additionalText.length ? [text, ...edit.additionalText] : undefined;
|
|
1234
|
+
if (textParts) text = textParts.join('');
|
|
1235
|
+
if (submitting || pending.current || activeEditor !== claim || !editableRef.current || (!text.trim() && attachmentIds.length === 0)) {
|
|
1236
|
+
return { kind: 'error' };
|
|
1237
|
+
}
|
|
1238
|
+
const { retained, conversation } = edit.composer;
|
|
1239
|
+
const remaining = new Set(attachmentIds);
|
|
1240
|
+
const removedAttachments = [...retained].filter(([id]) => !remaining.has(id)).map(([, item]) => item.index);
|
|
1241
|
+
const uploads = conversation?.fileUploads.getSnapshot() ?? emptyUploads;
|
|
1242
|
+
const receiptIds = [];
|
|
1243
|
+
for (const id of attachmentIds) {
|
|
1244
|
+
if (retained.has(id)) continue;
|
|
1245
|
+
const upload = uploads[id];
|
|
1246
|
+
if (upload?.status !== 'ready' || typeof upload.receiptId !== 'string') {
|
|
1247
|
+
notify(t('uploadWait'));
|
|
1248
|
+
return { kind: 'error' };
|
|
1249
|
+
}
|
|
1250
|
+
receiptIds.push(upload.receiptId);
|
|
1251
|
+
}
|
|
1252
|
+
const selectedModel = edit.settings.model;
|
|
1253
|
+
const originalModel = edit.originalSettings.model;
|
|
1254
|
+
const modelGroup = edit.modelDirectory?.getSnapshot()?.groups?.find(group => group.id === originalModel?.provider);
|
|
1255
|
+
const defaultEffort = modelGroup?.models.find(model => model.id === originalModel?.model)?.reasoning?.defaultEffort;
|
|
1256
|
+
const sameModel = selectedModel === undefined || (selectedModel.provider === originalModel?.provider
|
|
1257
|
+
&& selectedModel.model === originalModel?.model
|
|
1258
|
+
&& (selectedModel.reasoningEffort ?? defaultEffort) === (originalModel?.reasoningEffort ?? defaultEffort));
|
|
1259
|
+
const samePermission = edit.settings.permissionPreset === undefined
|
|
1260
|
+
|| edit.settings.permissionPreset === edit.originalSettings.permissionPreset;
|
|
1261
|
+
const sameText = text === edit.original
|
|
1262
|
+
&& (textParts === undefined || textParts.every((part, index) => part === edit.originalTextParts[index]));
|
|
1263
|
+
if (sameText && removedAttachments.length === 0 && receiptIds.length === 0
|
|
1264
|
+
&& sameModel && samePermission) {
|
|
1265
|
+
dismiss();
|
|
1266
|
+
return { kind: 'success' };
|
|
1267
|
+
}
|
|
1268
|
+
if (text.length > 200_000) {
|
|
1269
|
+
notify(t('tooLong'));
|
|
1270
|
+
return { kind: 'error' };
|
|
1271
|
+
}
|
|
1272
|
+
let saved;
|
|
1273
|
+
try {
|
|
1274
|
+
saved = snapshotRevisionDraft(edit, text, attachmentIds, textParts);
|
|
1275
|
+
} catch (error) {
|
|
1276
|
+
notify(errorMessage(error));
|
|
1277
|
+
return { kind: 'error' };
|
|
1278
|
+
}
|
|
1279
|
+
const view = window.location.href;
|
|
1280
|
+
submitting = true;
|
|
1281
|
+
pending.current = true;
|
|
1282
|
+
setRequestPending(true);
|
|
1283
|
+
let reconnect;
|
|
1284
|
+
let restoreDraft = false;
|
|
1285
|
+
let deliveryUnknown = false;
|
|
1286
|
+
let savedForRetry = false;
|
|
1287
|
+
const inView = () => !lifetime.signal.aborted && window.location.href === view;
|
|
1288
|
+
try {
|
|
1289
|
+
if (!sessionViews) throw new Error('reconnect-unavailable');
|
|
1290
|
+
reconnect = sessionViews.holdSessionView(sessionId);
|
|
1291
|
+
let result;
|
|
1292
|
+
try {
|
|
1293
|
+
result = await requestRevision({ sessionId, messageId: edit.messageId,
|
|
1294
|
+
toolbarRevision: 1, text, textParts, expectedRevision: edit.revision,
|
|
1295
|
+
removedAttachments, receiptIds, ...edit.settings });
|
|
1296
|
+
} catch (error) {
|
|
1297
|
+
deliveryUnknown = error.deliveryUnknown === true;
|
|
1298
|
+
if (error.reconnect || reconnect.removed) {
|
|
1299
|
+
restoreDraft = true;
|
|
1300
|
+
await reconnect.reconnect().catch(() => {});
|
|
1301
|
+
}
|
|
1302
|
+
throw error;
|
|
1303
|
+
}
|
|
1304
|
+
try {
|
|
1305
|
+
if (result.unchanged === true) {
|
|
1306
|
+
if (inView() && activeEditor === claim) dismiss();
|
|
1307
|
+
return { kind: 'success' };
|
|
1308
|
+
}
|
|
1309
|
+
if (result.reload === true || reconnect.removed) await reconnect.reconnect();
|
|
1310
|
+
if (inView()) {
|
|
1311
|
+
if (activeEditor === claim) dismiss();
|
|
1312
|
+
if (result.cleanupWarning) notify(t('cleanupPending'));
|
|
1313
|
+
else notify(t('done'), 'success');
|
|
1314
|
+
}
|
|
1315
|
+
} catch {
|
|
1316
|
+
if (inView()) {
|
|
1317
|
+
if (activeEditor === claim) dismiss();
|
|
1318
|
+
notify(t('syncing'));
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
return { kind: 'success' };
|
|
1322
|
+
} catch (error) {
|
|
1323
|
+
savedForRetry = !lifetime.signal.aborted && editableRef.current && (deliveryUnknown || restoreDraft || draft.current !== edit.composer);
|
|
1324
|
+
if (savedForRetry && activeEditor === claim) dismiss(false);
|
|
1325
|
+
if (inView()) notify(savedForRetry ? `${errorMessage(error)} ${t('draftSaved')}` : errorMessage(error));
|
|
1326
|
+
return { kind: 'error' };
|
|
1327
|
+
} finally {
|
|
1328
|
+
pending.current = false;
|
|
1329
|
+
try {
|
|
1330
|
+
reconnect?.release();
|
|
1331
|
+
} finally {
|
|
1332
|
+
submitting = false;
|
|
1333
|
+
setRequestPending(false);
|
|
1334
|
+
if (savedForRetry) keepDraft(edit.key, { ...saved, reopenInView: inView() && (!deliveryUnknown || restoreDraft) ? view : undefined });
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
return h(Fragment, null,
|
|
1340
|
+
!edit && h('button', {
|
|
1341
|
+
ref: pencil, type: 'button', className: 'dsh-revision-pencil', onClick: open,
|
|
1342
|
+
'aria-label': t('edit'), 'aria-busy': opening || undefined,
|
|
1343
|
+
'data-tooltip': t('edit'), 'data-tooltip-dismissed': (opening || tooltipDismissed) || undefined,
|
|
1344
|
+
onFocus: () => setTooltipDismissed(false),
|
|
1345
|
+
onPointerLeave: () => setTooltipDismissed(false),
|
|
1346
|
+
onKeyDown: event => { if (event.key === 'Escape') setTooltipDismissed(true); },
|
|
1347
|
+
}, h(TablerIcon, { name: 'pencil', strokeWidth: 1.5 })),
|
|
1348
|
+
edit && renderFactorySlot(editorFactory, {
|
|
1349
|
+
edit, cancel, requestPending, cancelLabel: t('cancel'), disabled: busy,
|
|
1350
|
+
}));
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
ctx.effect(() => () => lifetime.abort());
|
|
1354
|
+
// The same native child seats remain available to the registered native bar.
|
|
1355
|
+
const composerChildren = {
|
|
1356
|
+
'conversation.input.attachments': { kind: 'single', scope: 'session-maybe' },
|
|
1357
|
+
'conversation.input.permission': { kind: 'single', scope: 'session' },
|
|
1358
|
+
'conversation.input.plan': { kind: 'single', scope: 'session' },
|
|
1359
|
+
'conversation.input.model': { kind: 'single', scope: 'session' },
|
|
1360
|
+
'conversation.input.activity': { kind: 'single', scope: 'session' },
|
|
1361
|
+
'conversation.input.left': { kind: 'list', scope: 'session' },
|
|
1362
|
+
'conversation.input.right': { kind: 'list', scope: 'session' },
|
|
1363
|
+
'conversation.composer.dock': { kind: 'list', scope: 'session' },
|
|
1364
|
+
};
|
|
1365
|
+
// Only the Host owner can call /api/message-revision or watch revision events.
|
|
1366
|
+
ctx.inject(['remoteAccess'], accessScope => accessScope.remoteAccess.whenAccess(ownerAccessAction, function* () {
|
|
1367
|
+
const sessions = accessScope.inject(['sessions'], scoped => scoped.effect(() => {
|
|
1368
|
+
const views = watchSessionViews(sessionRuntime(scoped));
|
|
1369
|
+
setSessionViews(views);
|
|
1370
|
+
if (views) scoped.inject(['remote'], remoteScope => remoteScope.effect(async () => {
|
|
1371
|
+
await pendingUnmount.catch(() => {});
|
|
1372
|
+
if (lifetime.signal.aborted || sessionViews !== views) return undefined;
|
|
1373
|
+
const unmount = await remoteScope.remote.$mount(revisionEventsContribution);
|
|
1374
|
+
let subscription;
|
|
1375
|
+
try {
|
|
1376
|
+
subscription = remoteScope.inject([`remote.${revisionRemoteName}`], ready => ready.effect(() =>
|
|
1377
|
+
connectRevisionViews(views, ready.remote, (cursor, signal) => ready.remote[revisionRemoteName].watch(cursor, signal))));
|
|
1378
|
+
} catch (error) {
|
|
1379
|
+
const cleanup = Promise.resolve().then(() => unmount());
|
|
1380
|
+
pendingUnmount = cleanup;
|
|
1381
|
+
await cleanup;
|
|
1382
|
+
throw error;
|
|
1383
|
+
}
|
|
1384
|
+
return () => {
|
|
1385
|
+
const cleanup = (async () => {
|
|
1386
|
+
try { await subscription.dispose(); } finally { await unmount(); }
|
|
1387
|
+
})();
|
|
1388
|
+
pendingUnmount = cleanup;
|
|
1389
|
+
return cleanup;
|
|
1390
|
+
};
|
|
1391
|
+
}));
|
|
1392
|
+
return () => {
|
|
1393
|
+
if (sessionViews === views) setSessionViews(undefined);
|
|
1394
|
+
views?.dispose();
|
|
1395
|
+
};
|
|
1396
|
+
}));
|
|
1397
|
+
yield () => { void sessions.dispose(); };
|
|
1398
|
+
yield accessScope.locale.register(locale, strings);
|
|
1399
|
+
yield accessScope.slots.inject(composerSlot, () => {
|
|
1400
|
+
// rc.5 registers and tears down only own child declarations, but the
|
|
1401
|
+
// Factory renderer resolves their specs by lookup. Borrow the already
|
|
1402
|
+
// live slots without owning them so unloading leaves the host intact.
|
|
1403
|
+
const borrowedChildren = Object.freeze(Object.create(Object.freeze(composerChildren)));
|
|
1404
|
+
const dispose = accessScope.slots.registerFactory({
|
|
1405
|
+
name: editorFactory, scope: 'session', locale: 'conversation', children: borrowedChildren,
|
|
1406
|
+
}, NativeEditor);
|
|
1407
|
+
composerFactoryLive = true;
|
|
1408
|
+
return () => { composerFactoryLive = false; dispose(); };
|
|
1409
|
+
});
|
|
1410
|
+
yield accessScope.slots.inject('shell.overlay', () => accessScope.slots.register({
|
|
1411
|
+
name: 'shell.overlay', id: 'message-revision.styles', locale,
|
|
1412
|
+
}, props => h(Fragment, null, h('style', null, css), h(Feedback, props))));
|
|
1413
|
+
yield accessScope.slots.inject('conversation.chat.user.before', () => accessScope.slots.register({
|
|
1414
|
+
name: 'conversation.chat.user.before', locale, order: 10000,
|
|
1415
|
+
select: ({ kind, source }) => kind === 'user' && source?.kind === 'user' ? source : null,
|
|
1416
|
+
}, RevisionAction));
|
|
1417
|
+
}));
|
|
1418
|
+
},
|
|
1419
|
+
};
|
|
1420
|
+
},
|
|
1421
|
+
});
|