@keyou007/agent-bot 0.1.27-alpha.4 → 0.1.27-alpha.5

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.
Files changed (63) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +37 -18
  3. package/README.zh.md +37 -18
  4. package/assets/workspace-sessions.js +959 -229
  5. package/assets/workspace.css +241 -57
  6. package/assets/workspace.js +1463 -227
  7. package/dist/feishu/FeishuTurnPresenter.js +26 -9
  8. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  9. package/dist/local-files/GitDiffPreview.js +69 -7
  10. package/dist/local-files/GitDiffPreview.js.map +1 -1
  11. package/dist/local-files/LocalFileViewerServer.js +10 -7
  12. package/dist/local-files/LocalFileViewerServer.js.map +1 -1
  13. package/dist/local-files/PreviewSyntaxHighlight.js +1 -1
  14. package/dist/local-files/PreviewSyntaxHighlight.js.map +1 -1
  15. package/dist/local-files/TurnPreviewPage.js +30 -7
  16. package/dist/local-files/TurnPreviewPage.js.map +1 -1
  17. package/dist/local-files/WorkspaceImages.js +28 -0
  18. package/dist/local-files/WorkspaceImages.js.map +1 -1
  19. package/dist/local-files/WorkspacePage.js +5 -2
  20. package/dist/local-files/WorkspacePage.js.map +1 -1
  21. package/dist/local-files/WorkspaceSessions.js +343 -96
  22. package/dist/local-files/WorkspaceSessions.js.map +1 -1
  23. package/dist/local-files/WorkspaceTimeline.js +34 -10
  24. package/dist/local-files/WorkspaceTimeline.js.map +1 -1
  25. package/dist/presentation/OutboundRouter.js +3 -1
  26. package/dist/presentation/OutboundRouter.js.map +1 -1
  27. package/dist/presentation/TurnStateReducer.js +3 -1
  28. package/dist/presentation/TurnStateReducer.js.map +1 -1
  29. package/dist/proxy/ProxySessionController.js +130 -45
  30. package/dist/proxy/ProxySessionController.js.map +1 -1
  31. package/dist/scheduling/ScheduledTaskStore.js +6 -4
  32. package/dist/scheduling/ScheduledTaskStore.js.map +1 -1
  33. package/dist/scheduling/types.js +2 -1
  34. package/dist/scheduling/types.js.map +1 -1
  35. package/dist/state/StateStore.js +77 -13
  36. package/dist/state/StateStore.js.map +1 -1
  37. package/dist/state/TurnPreviewJournal.js +24 -13
  38. package/dist/state/TurnPreviewJournal.js.map +1 -1
  39. package/dist/utils/promptAttachments.js +4 -2
  40. package/dist/utils/promptAttachments.js.map +1 -1
  41. package/dist/utils/promptQuotes.js +47 -0
  42. package/dist/utils/promptQuotes.js.map +1 -0
  43. package/npm-shrinkwrap.json +2 -2
  44. package/package.json +1 -1
  45. package/src/feishu/FeishuTurnPresenter.ts +27 -8
  46. package/src/local-files/GitDiffPreview.ts +72 -8
  47. package/src/local-files/LocalFileViewerServer.ts +10 -7
  48. package/src/local-files/PreviewSyntaxHighlight.ts +1 -1
  49. package/src/local-files/TurnPreviewPage.ts +35 -7
  50. package/src/local-files/WorkspaceImages.ts +25 -0
  51. package/src/local-files/WorkspacePage.ts +5 -2
  52. package/src/local-files/WorkspaceSessions.ts +318 -101
  53. package/src/local-files/WorkspaceTimeline.ts +41 -15
  54. package/src/presentation/OutboundRouter.ts +3 -0
  55. package/src/presentation/TurnStateReducer.ts +3 -1
  56. package/src/presentation/turnViewTypes.ts +1 -1
  57. package/src/proxy/ProxySessionController.ts +135 -44
  58. package/src/scheduling/ScheduledTaskStore.ts +6 -4
  59. package/src/scheduling/types.ts +4 -1
  60. package/src/state/StateStore.ts +83 -17
  61. package/src/state/TurnPreviewJournal.ts +27 -14
  62. package/src/utils/promptAttachments.ts +5 -2
  63. package/src/utils/promptQuotes.ts +48 -0
@@ -55,7 +55,39 @@
55
55
  const imageTypesByExtension = {png:'image/png',jpg:'image/jpeg',jpeg:'image/jpeg',gif:'image/gif',webp:'image/webp'};
56
56
  const imageLimit = 5 * 1024 * 1024, draftLimit = 12 * 1024 * 1024, imageCount = 4;
57
57
  const chatImageSizeLimit = 256;
58
- const chatAnchorParts = '.session-message-text,.session-message-images > *,.session-message-files,.markdown-body > *';
58
+ const chatAnchorParts = '.session-message-text,.session-prompt-quote,.session-message-images > *,.session-message-files,.markdown-body > *';
59
+ const numberChatCode = (code,diff) => {
60
+ const source = code.textContent.replace(/\r\n?/gu,'\n');
61
+ const lines = source.split('\n'), highlighted = workspaceHighlightedLines(code.innerHTML.replace(/\r\n?/gu,'\n'));
62
+ if (highlighted.length !== lines.length) return;
63
+ const tail = source.endsWith('\n') ? '\n' : '';
64
+ if (tail) lines.pop();
65
+ const hunks = diff && lines.some(line => workspacePatchHunkHeader.test(line));
66
+ let oldLine = 0, newLine = 0, oldRemaining = 0, newRemaining = 0, oldWidth = 2, newWidth = 2;
67
+ const rows = lines.map((line,index) => {
68
+ let oldNumber = '', number = hunks ? '' : index+1, change = '';
69
+ const hunk = hunks && workspacePatchHunkHeader.exec(line);
70
+ if (hunk) {
71
+ oldLine = Number(hunk[1]); oldRemaining = Number(hunk[2] ?? 1);
72
+ newLine = Number(hunk[3]); newRemaining = Number(hunk[4] ?? 1);
73
+ } else if (hunks && line.startsWith('+') && newRemaining > 0) {
74
+ number = newLine++; newRemaining--; change = ' session-code-added';
75
+ } else if (hunks && line.startsWith('-') && oldRemaining > 0) {
76
+ oldNumber = oldLine++; oldRemaining--; change = ' session-code-deleted';
77
+ } else if (hunks && line.startsWith(' ') && oldRemaining > 0 && newRemaining > 0) {
78
+ oldNumber = oldLine++; oldRemaining--; number = newLine++; newRemaining--;
79
+ } else if (diff && !hunks) {
80
+ if (highlighted[index].startsWith('<span class="hljs-addition">')) change = ' session-code-added';
81
+ if (highlighted[index].startsWith('<span class="hljs-deletion">')) change = ' session-code-deleted';
82
+ }
83
+ oldWidth = Math.max(oldWidth,String(oldNumber).length); newWidth = Math.max(newWidth,String(number).length);
84
+ return `<span class="session-code-line${change}" data-line="${number}"${hunks ? ` data-old-line="${oldNumber}"` : ''}>${highlighted[index]}</span>`;
85
+ });
86
+ code.classList.add('session-code-lines');
87
+ code.style.setProperty('--code-line-width',newWidth+'ch');
88
+ if (hunks) code.style.setProperty('--old-code-line-width',oldWidth+'ch');
89
+ code.innerHTML = rows.join('\n')+tail;
90
+ };
59
91
  const clipboardFiles = clipboard => {
60
92
  const files = Array.from(clipboard?.files ?? []);
61
93
  if (files.length) return files;
@@ -76,26 +108,55 @@
76
108
  });
77
109
  const effortLabel = value => ({none:'无',minimal:'极低',low:'低',medium:'中',high:'高',xhigh:'极高',max:'最高'})[value] ?? value;
78
110
  const revokeAttachment = attachment => { if (attachment.src) URL.revokeObjectURL(attachment.src); };
79
- const draftAttachment = (file,annotation) => {
111
+ const draftAttachment = (file,metadata) => {
80
112
  const type = file.size && previewImageType(file);
81
113
  const preview = type ? (file.type === type ? file : file.slice(0,file.size,type)) : undefined;
82
- return {id:uuid(),file,src:preview ? URL.createObjectURL(preview) : undefined,annotation};
114
+ const displaySize = type === 'image/png' ? preview.slice(0,workspacePngHeaderBytes).arrayBuffer()
115
+ .then(bytes => workspacePngDisplaySize(new DataView(bytes))).catch(() => undefined) : undefined;
116
+ return {id:uuid(),file,src:preview ? URL.createObjectURL(preview) : undefined,displaySize,...metadata};
117
+ };
118
+ const declaredChatImageSize = src => {
119
+ const size = /#size=([1-9]\d{0,5})x([1-9]\d{0,5})$/u.exec(src);
120
+ if (size) return [Number(size[1]),Number(size[2])];
83
121
  };
84
122
  const annotationLocation = item => [item.line && `第 ${item.line} 行`,item.originalLine && `变更前第 ${item.originalLine} 行`].filter(Boolean).join(' · ');
85
- const annotationTitle = item => item.path ? `${item.path.split(/[\\/]/u).at(-1)}:${item.line || item.originalLine}` : item.label;
86
- const annotationPrompt = (text,attachments) => text.trim() || (attachments.some(item => item.annotation) ? '请阅读所附批注,并处理其中提出的要求。' : '');
87
- const annotationBlock = text => text.split('\n').map(line => ' '+line).join('\n');
88
- const annotationMarkdown = item => {
89
- const source = item.path ? ['# 文件批注',`文件路径\n\n${annotationBlock(item.path)}`,`行号\n\n${annotationBlock(annotationLocation(item))}`,
90
- ...(item.originalPath ? [`变更前的文件路径\n\n${annotationBlock(item.originalPath)}`] : [])]
91
- : ['# 聊天批注',`消息来源\n\n${annotationBlock(item.label)}`,...(item.turn ? [`轮次\n\n${annotationBlock(item.turn)}`] : [])];
92
- return [...source,`选中的原文\n\n${annotationBlock(item.quote)}`,`用户批注\n\n${item.note}`].join('\n\n');
123
+ const sourceTitle = item => {
124
+ const line = item.line || item.originalLine;
125
+ return item.path ? (item.path.split(/[\\/]/u).filter(Boolean).at(-1) || item.path)+(line ? ':'+line : '') : item.title || item.label;
93
126
  };
127
+ const attachmentPrompt = (text,attachments) => text.trim() || (attachments.some(item => item.annotation)
128
+ ? '请阅读所附批注,并处理其中提出的要求。' : attachments.some(item => item.reference) ? '请查看所附引用。' : '');
129
+ const queueCommandText = text => {
130
+ const command = /^\s*\/([a-z]+)(?=\s|$)/iu.exec(text);
131
+ if (command && 'queue'.startsWith(command[1].toLowerCase())) return text.slice(command[0].length).trimStart();
132
+ };
133
+ const validAnnotationNote = note => typeof note === 'string' && note.length <= 8000 && Boolean(note.trim());
134
+ const quoteDetails = source => source.path
135
+ ? [source.path,annotationLocation(source),source.originalPath && '变更前的文件:'+source.originalPath].filter(Boolean).join(' · ')
136
+ : source.sessionId ? '会话 ID '+source.sessionId
137
+ : [source.label,source.url,source.turn && '轮次 '+source.turn].filter(Boolean).join(' · ');
138
+ const promptQuotes = attachments => attachments.flatMap(({annotation,reference}) => {
139
+ const item = annotation || reference;
140
+ if (!item) return [];
141
+ const {quote,note,anchor: _anchor,...source} = item;
142
+ return [annotation ? {kind:'annotation',source,quote,note} : {kind:'reference',source,quote}];
143
+ });
144
+ const draftQuote = ({kind,source,quote,note}) => ({id:uuid(),...(kind === 'annotation'
145
+ ? {annotation:{...source,quote,note}} : {reference:{...source,quote}})});
146
+ const attachmentName = item => item.file?.name || sourceTitle(item.annotation || item.reference || {});
147
+ const attachmentBytes = item => item.file?.size ?? 0;
148
+ const validFileSource = item => typeof item.path === 'string' && Boolean(item.path) && item.path.length <= 4096
149
+ && [item.line,item.originalLine].every(line => line === undefined || typeof line === 'string' && /^\d{1,10}(?:–\d{1,10})?$/u.test(line))
150
+ && (item.originalPath === undefined || typeof item.originalPath === 'string' && item.originalPath.length <= 4096);
151
+ const validChatSource = item => typeof item.label === 'string' && Boolean(item.label) && item.label.length <= 120
152
+ && (item.turn === undefined || typeof item.turn === 'string' && item.turn.length <= 400);
94
153
  const encodeAttachments = async attachments => {
95
- const entries = await Promise.all(attachments.map(async attachment => ({attachment,data:await readAttachment(attachment.file)})));
154
+ const quotes = promptQuotes(attachments);
155
+ const entries = await Promise.all(attachments.filter(attachment => attachment.file && !attachment.annotation && !attachment.reference)
156
+ .map(async attachment => ({attachment,data:await readAttachment(attachment.file)})));
96
157
  const images = entries.filter(({attachment})=>attachment.src).map(({data})=>data);
97
158
  const files = entries.filter(({attachment})=>!attachment.src).map(({attachment,data})=>({name:attachment.file.name?.slice(0,255) || 'file',data}));
98
- return {...(images.length?{images}:{}),...(files.length?{files}:{})};
159
+ return {...(images.length?{images}:{}),...(files.length?{files}:{}),...(quotes.length?{quotes}:{})};
99
160
  };
100
161
  const timeTool = tool => {
101
162
  const start = tool.startedAt, end = tool.completedAt;
@@ -118,6 +179,13 @@
118
179
  const taskClock = new Intl.DateTimeFormat('zh-CN',{hour:'2-digit',minute:'2-digit',hourCycle:'h23'});
119
180
  const taskDate = new Intl.DateTimeFormat('zh-CN',{month:'long',day:'numeric'});
120
181
  const taskFullDate = new Intl.DateTimeFormat('zh-CN',{year:'numeric',month:'long',day:'numeric'});
182
+ const chatTime = (timestamp,className) => {
183
+ const date = new Date(timestamp);
184
+ const time = make('time',className,date.toDateString() === new Date().toDateString()
185
+ ? taskClock.format(date) : date.toLocaleString(undefined,{month:'short',day:'numeric',hour:'2-digit',minute:'2-digit'}));
186
+ time.setAttribute('datetime',date.toISOString());
187
+ return time;
188
+ };
121
189
  const taskDateLabel = (date, today = new Date()) => {
122
190
  if (date.toDateString() === today.toDateString()) return taskClock.format(date);
123
191
  const yesterday = new Date(today);
@@ -154,6 +222,8 @@
154
222
  return merged;
155
223
  };
156
224
  const activeTurn = value => ['running','tool_running','waiting_for_approval'].includes(value);
225
+ const queueableTurn = state => state === 'starting' || activeTurn(state);
226
+ const queuedMessage = message => message.queued ?? (message.payload.action === 'queue' && !message.accepted);
157
227
  const read = (key,fallback,storage = 'localStorage') => { try { return JSON.parse(window[storage]?.getItem(key)) ?? fallback; } catch { return fallback; } };
158
228
  const save = (key,value,storage = 'localStorage') => {
159
229
  try { window[storage].setItem(key,JSON.stringify(value)); return true; } catch { return false; }
@@ -175,6 +245,9 @@
175
245
  this.chatImageSizeKey = 'agentbot-workspace-chat-image-sizes:'+base;
176
246
  const imageSizes = read(this.chatImageSizeKey,[],'sessionStorage');
177
247
  this.chatImageSizes = new Map(Array.isArray(imageSizes) ? imageSizes.slice(-chatImageSizeLimit).filter(Array.isArray) : []);
248
+ this.chatImageHandoffs = new Map();
249
+ this.syncChatImageDpr();
250
+ window.addEventListener('resize',this.syncChatImageDpr);
178
251
  this.newDraftKey = 'agentbot-workspace-new-draft:'+base;
179
252
  const savedDraft = read(this.newDraftKey,null,'sessionStorage');
180
253
  if (typeof savedDraft?.draft?.id === 'string') {
@@ -182,9 +255,10 @@
182
255
  this.newDraftSaved = true;
183
256
  }
184
257
  this.pendingTurnActions = new Set();
258
+ this.sendingFromQueue = new Map();
185
259
  const outbox = read('agentbot-workspace-outbox',[],'sessionStorage');
186
260
  this.outboxes = new Map((Array.isArray(outbox) ? outbox : []).map(([task,items]) => [task,
187
- new Map(items.map(([id,payload,error]) => [id,{payload,error,images:noImages,restored:true}]))]));
261
+ new Map(items.map(([id,payload,error,startedAt]) => [id,{payload,error,startedAt,images:noImages,restored:true}]))]));
188
262
  this.left.classList.add('session-task-pane'); this.chat.classList.add('session-chat-pane');
189
263
  this.locked('正在检查工作台会话…'); void this.session();
190
264
  this.offline = () => { if (this.csrf) { this.connected = false; this.app.updateSessionStatus(false,'网络已断开'); } };
@@ -317,6 +391,8 @@
317
391
  }
318
392
  dispose() {
319
393
  this.timelineObserver?.disconnect(); this.closeSettingsMenu(); this.resetImageDrafts(); this.resetOutboxes(); this.clearImageInteractions();
394
+ this.chatImageResolution?.removeEventListener?.('change',this.syncChatImageDpr);
395
+ window.removeEventListener('resize',this.syncChatImageDpr);
320
396
  this.scheduleDialog?.close();
321
397
  this.draftFiles.dispose();
322
398
  this.disposed = true; this.stream?.close(); this.selection?.abort(); this.groupRequest?.abort(); this.resetNewer(); clearTimeout(this.searchTimer); clearTimeout(this.watchdog);
@@ -357,8 +433,13 @@
357
433
  try {
358
434
  const data = {...JSON.parse(event.data), version:Number(event.lastEventId), epoch:this.connectionEpoch};
359
435
  if (data.taskId !== this.target || data.generation !== this.generation) return;
360
- if (this.selecting || this.refreshing || this.newerRequest) this.bufferedTail = data;
361
- else if (data.taskId === this.task?.id) this.applyTail(data.value);
436
+ if (this.selecting || this.refreshing || this.newerRequest) {
437
+ const previous = this.bufferedTail;
438
+ if (data.value?.queuedPrompts !== undefined) {
439
+ data.queue = {version:data.version,queued:data.value.queued,queuedPrompts:data.value.queuedPrompts};
440
+ } else if (data.value && previous?.epoch === data.epoch) data.queue = previous.queue;
441
+ this.bufferedTail = data;
442
+ } else if (data.taskId === this.task?.id) this.applyTail(data.value);
362
443
  } catch { this.setChatError('实时更新无法读取,请刷新对话。',true); }
363
444
  });
364
445
  stream.onerror = () => {
@@ -408,22 +489,69 @@
408
489
  annotationTask() { return this.csrf && !this.input?.disabled ? this.newDraft?.id ?? this.task?.id : undefined; }
409
490
  addAnnotation(item,task) {
410
491
  if (!task || task !== this.annotationTask()) return '当前任务已切换或无法输入消息。';
411
- if (typeof item?.note !== 'string' || !item.note.trim() || item.note.length > 8000 || typeof item.quote !== 'string' || !item.quote.trim()) return '批注内容无效。';
492
+ if (!validAnnotationNote(item?.note) || typeof item.quote !== 'string' || !item.quote.trim()) return '批注内容无效。';
412
493
  if (item.quote.length > 100_000) return '选中的文字过长,请缩小选区后再添加批注。';
413
- if (item.path !== undefined ? typeof item.path !== 'string' || !item.path || item.path.length > 4096
414
- || ![item.line,item.originalLine].some(Boolean)
415
- || [item.line,item.originalLine].some(line => line !== undefined && (typeof line !== 'string' || !/^\d{1,10}(?:–\d{1,10})?$/u.test(line)))
416
- || item.originalPath !== undefined && (typeof item.originalPath !== 'string' || item.originalPath.length > 4096)
417
- : typeof item.label !== 'string' || !item.label || item.label.length > 120 || item.turn !== undefined && (typeof item.turn !== 'string' || item.turn.length > 400)) return '批注来源无效。';
418
- const stem = (item.path ? item.path.split(/[\\/]/u).at(-1) : item.label).slice(0,120).replace(/[\x00-\x1f<>:"/\\|?*]/gu,'_');
419
- const lines = item.line || item.originalLine;
420
- const file = new File([annotationMarkdown(item)],`批注 - ${stem}${lines ? ' - '+lines : ''}.md`,{type:'text/markdown'});
421
- if (!this.addAttachments([file],item)) return '附件已达到上限,请先移除一个附件。';
494
+ if (item.path !== undefined ? !validFileSource(item) || ![item.line,item.originalLine].some(Boolean) : !validChatSource(item)) return '批注来源无效。';
495
+ return this.addDraftQuote(task,{annotation:item});
496
+ }
497
+ addReference(item,task) {
498
+ if (!task || task !== this.annotationTask()) return '当前任务已切换或无法输入消息。';
499
+ if (!item || item.quote !== undefined && (typeof item.quote !== 'string' || !item.quote.trim())) return '引用内容无效。';
500
+ if (item.quote?.length > 100_000) return '选中的文字过长,请缩小选区后再添加引用。';
501
+ let reference;
502
+ if (item.url !== undefined) {
503
+ let url;
504
+ if (typeof item.url !== 'string' || item.url.length > 4096) return '引用网址无效。';
505
+ try { url = new URL(item.url); } catch { return '引用网址无效。'; }
506
+ if (!['http:','https:'].includes(url.protocol) || url.username || url.password) return '引用网址无效。';
507
+ reference = {url:url.href,label:typeof item.label === 'string' && item.label.trim().slice(0,160) || url.hostname};
508
+ } else if (item.path !== undefined) {
509
+ if (!validFileSource(item) || !/^[\\/]|^[a-z]:[\\/]/iu.test(item.path)) return '引用文件路径无效。';
510
+ const {path,line,originalLine,originalPath,quote} = item;
511
+ reference = {path,line,originalLine,originalPath,quote,...(item.directory === true ? {directory:true} : {}),
512
+ ...(item.wholeLines === true ? {wholeLines:true} : {})};
513
+ } else if (item.sessionId !== undefined) {
514
+ const {sessionId,title} = item;
515
+ if (typeof sessionId !== 'string' || !/^[^\x00-\x1f\x7f]{1,200}$/u.test(sessionId)
516
+ || typeof title !== 'string' || !title.trim() || title.length > 200) return '引用会话无效。';
517
+ reference = {sessionId,title:title.trim()};
518
+ } else {
519
+ if (!item.quote || !validChatSource(item)) return '引用来源无效。';
520
+ const {label,turn,quote} = item;
521
+ reference = {label,turn,quote};
522
+ }
523
+ return this.addDraftQuote(task,{reference});
524
+ }
525
+ addDraftQuote(task,item) {
526
+ const items = this.images(task);
527
+ if (items.length >= imageCount) return '附件已达到上限,请先移除一个附件。';
528
+ const position = this.position(true);
529
+ this.replaceImages(task,[...items,{id:uuid(),...item}]);
530
+ this.noticeImages(''); this.updateComposer(); this.keepComposerPosition(position);
531
+ this.attachments.scrollLeft = this.attachments.scrollWidth;
532
+ }
533
+ editAnnotation(id,note,task,{fileOnly = false} = {}) {
534
+ if (!task || task !== this.annotationTask()) return '当前任务已切换或无法输入消息。';
535
+ if (!validAnnotationNote(note)) return '批注内容无效。';
536
+ const images = this.images(task), existing = images.find(item => item.id === id);
537
+ if (!existing?.annotation || fileOnly && !existing.annotation.path) return '这条批注已从草稿移除。';
538
+ if (existing.annotation.note === note.trim()) return;
539
+ const annotation = {...existing.annotation,note:note.trim()};
540
+ const position = this.position(true);
541
+ this.replaceImages(task,images.map(item => item === existing ? {...item,annotation} : item));
542
+ this.updateComposer(); this.keepComposerPosition(position);
543
+ }
544
+ removeAnnotation(id,task,{fileOnly = false} = {}) {
545
+ if (!task || task !== this.annotationTask()) return '当前任务已切换或无法输入消息。';
546
+ const existing = this.images(task).find(item => item.id === id);
547
+ if (!existing) return;
548
+ if (!existing.annotation || fileOnly && !existing.annotation.path) return '无法移除这条批注。';
549
+ this.removeImage(task,id,{focus:false});
422
550
  }
423
551
  openSchedule() {
424
552
  if (!this.task || this.newDraft || this.selecting || this.scheduleDialog?.open) return;
425
553
  const task = this.task.id, grant = this.csrf, editor = this.input, original = editor.value, attachments = this.images(task);
426
- const prompt = annotationPrompt(original,attachments);
554
+ const prompt = attachmentPrompt(original,attachments);
427
555
  const dialog = this.scheduleDialog = this.createDialog('定时任务',this.chat);
428
556
  dialog.classList.add('session-schedule-dialog');
429
557
  const current = () => dialog.open && this.task?.id === task && this.csrf === grant;
@@ -482,7 +610,7 @@
482
610
  summary.append(make('span','session-schedule-prompt',job.name || job.prompt),make('small','session-muted',details.join(' · ')));
483
611
  row.append(summary);
484
612
  if (job.prompt) row.append(make('p','session-schedule-preview',job.prompt));
485
- const names = [...(job.images ? [`${job.images} 张图片`] : []),...(job.files || [])];
613
+ const names = [...(job.images ? [`${job.images} 张图片`] : []),...(job.files || []),...(job.quotes ? [`${job.quotes} 条引用或批注`] : [])];
486
614
  if (names.length) row.append(make('div','session-muted session-schedule-attachments',names.join(' · ')));
487
615
  if (job.notice) row.append(make('p','session-muted',job.notice));
488
616
  const actions = make('div','session-schedule-actions'), feedback = make('div','session-muted'); feedback.setAttribute('role','status');
@@ -523,7 +651,7 @@
523
651
  if (initialTime !== undefined) date.value = localDateTime(new Date(initialTime),timeZone.value);
524
652
  if (job?.endsAt) end.value = localDateTime(new Date(job.endsAt),timeZone.value);
525
653
  name.maxLength = 120; name.placeholder = '定时任务';
526
- name.value = job?.name || prompt.split('\n')[0].slice(0,120) || attachments[0]?.file.name.slice(0,120) || '';
654
+ name.value = job?.name || prompt.split('\n')[0].slice(0,120) || (attachments[0] && attachmentName(attachments[0])?.slice(0,120)) || '';
527
655
  for (const [value,label] of scheduleOptions) {
528
656
  const option = make('option',null,label); option.value = value; option.selected = value === (job?.cron ? 'cron' : 'once'); frequency.append(option);
529
657
  }
@@ -534,7 +662,8 @@
534
662
  message = make('textarea'); message.rows = 3; message.maxLength = 24_000; message.value = job.prompt;
535
663
  this.dialogField(form,'Prompt',message);
536
664
  } else if (prompt) form.append(make('p','session-schedule-preview',prompt));
537
- const names = job ? [...(job.images ? [`${job.images} 张图片`] : []),...(job.files || [])] : attachments.map(item => item.file.name);
665
+ const names = job ? [...(job.images ? [`${job.images} 张图片`] : []),...(job.files || []),...(job.quotes ? [`${job.quotes} 条引用或批注`] : [])]
666
+ : attachments.map(attachmentName);
538
667
  if (names.length) form.append(make('div','session-muted session-schedule-attachments',names.join(' · ')));
539
668
  form.append(fields); this.dialogField(fields,'频率',frequency); this.dialogField(fields,'执行时间',date); this.dialogField(form,'Cron 表达式(五段)',cron);
540
669
  const advanced = make('details','session-schedule-advanced'), settings = make('div','session-schedule-fields');
@@ -603,7 +732,7 @@
603
732
  if (resume) void this.restoreDraftFiles(draft.id);
604
733
  this.setChatError('');
605
734
  this.input.value = draft.text; this.noticeImages(''); this.updateDraftView();
606
- this.app.navigate(() => this.app.selectPane('chat'));
735
+ this.app.navigate(() => { this.app.selectPane('chat'); this.app.applyLayout(); });
607
736
  this.input.focus();
608
737
  if (draft.agents) return;
609
738
  const grant = this.csrf;
@@ -624,23 +753,30 @@
624
753
  if (this.settingsDialog?.open) this.settingsDialog.close();
625
754
  this.input.value = this.task ? this.draft(this.task.id) : '';
626
755
  this.noticeImages(''); this.setChatError(''); this.updateDraftView();
756
+ this.app.applyLayout();
627
757
  }
628
758
  saveNewTaskDraft() {
629
759
  const draft = this.newDraft ?? this.parkedDraft;
630
760
  if (draft) {
631
- const {id,request,text,directory,agent,model,thinking,creationTitle} = draft;
761
+ const {id,request,text,directory,agent,model,thinking,creationTitle,filesCollapsed} = draft;
632
762
  this.newDraftSaved = save(this.newDraftKey,{active:Boolean(this.newDraft || this.resumeNewDraft),
633
- draft:{id,request,text,directory,agent,model,thinking,creationTitle}},'sessionStorage');
763
+ draft:{id,request,text,directory,agent,model,thinking,creationTitle,filesCollapsed}},'sessionStorage');
634
764
  } else if (this.newDraftSaved) {
635
765
  this.newDraftSaved = false;
636
766
  save(this.newDraftKey,null,'sessionStorage');
637
767
  }
638
768
  }
639
769
  updateDraftView() {
640
- const draft = this.newDraft;
770
+ const draft = this.newDraft, submission = draft?.sending;
641
771
  this.saveNewTaskDraft();
642
772
  this.chat.toggleAttribute('data-draft',Boolean(draft));
643
- this.body.hidden = Boolean(draft);
773
+ this.body.hidden = Boolean(draft && !submission);
774
+ this.composer.hidden = Boolean(submission);
775
+ this.draftPreview.hidden = !submission;
776
+ if (!submission) this.draftPreview.replaceChildren();
777
+ else if (!this.draftPreview.firstElementChild)
778
+ this.draftPreview.append(this.outgoingNode(submission.message),this.pendingOutput(submission.label));
779
+ else setText(this.draftPreview.lastElementChild,submission.label);
644
780
  this.updatePlan(this.headPlan);
645
781
  this.draftTools.hidden = !draft;
646
782
  this.draftTools.replaceChildren();
@@ -733,6 +869,7 @@
733
869
  }
734
870
  async loadGroup(view, more = false, refresh = false) {
735
871
  if (!this.csrf) return;
872
+ if (this.taskRename?.view === view && this.taskRename.row.isConnected) return;
736
873
  if (view.loading) { if (refresh) view.refresh = true; return; }
737
874
  view.loading = true; view.refresh = false;
738
875
  const sequence = ++view.sequence, params = this.listParams();
@@ -747,13 +884,13 @@
747
884
  if (merged.length === items.length) break;
748
885
  items = merged; hasMore = next.more;
749
886
  }
750
- if (!current()) return;
887
+ if (!current() || this.taskRename?.view === view && this.taskRename.row.isConnected) return;
751
888
  if (more) items = [...new Map([...view.items,...items].map(item => [item.id,item])).values()];
752
889
  const signature = JSON.stringify([items,hasMore]);
753
890
  if (signature !== view.signature) {
754
891
  const focused = document.activeElement?.dataset?.sessionTask;
755
892
  view.items = items; view.signature = signature;
756
- view.rows.replaceChildren(...items.map(item => this.taskButton(item)));
893
+ view.rows.replaceChildren(...items.map(item => this.taskButton(item,view)));
757
894
  if (hasMore) view.rows.append(button('更多任务',() => this.loadGroup(view,true),'session-more'));
758
895
  if (focused) [...view.rows.querySelectorAll('[data-session-task]')].find(node => node.dataset.sessionTask === focused)?.focus({preventScroll:true});
759
896
  }
@@ -764,7 +901,7 @@
764
901
  if (view.refresh && view.node.isConnected && view.node.open) { view.refresh = false; void this.loadGroup(view,false,true); }
765
902
  }
766
903
  }
767
- taskButton(item) {
904
+ taskButton(item,view) {
768
905
  const label = item.title || '未命名任务';
769
906
  const node = button('',() => this.choose(item.id),'session-task'), title = make('span','session-task-title',label);
770
907
  const dot = make('span','session-dot'); dot.dataset.status = item.status; dot.setAttribute('aria-hidden','true');
@@ -783,15 +920,75 @@
783
920
  node.append(dot,details); node.dataset.sessionTask = item.id;
784
921
  node.dataset.tooltipOverflow = '.session-task-title';
785
922
  labelButton(node,[label,subtitle,!progress && item.promptPreview ? status(item.status) : null,item.agent,updatedLabel].filter(Boolean).join(' · '));
923
+ node.oncontextmenu = event => {
924
+ const task = this.annotationTask(), annotations = this.app.annotations;
925
+ annotations.showReferenceMenu(event,node,[
926
+ ['quote','引用该会话',() => annotations.addReference({sessionId:item.id,title:label},task)],
927
+ ['pencil','重命名',() => this.beginTaskRename(item,view,node)],
928
+ ]);
929
+ };
786
930
  if (item.id === this.task?.id) node.setAttribute('aria-current','true'); return node;
787
931
  }
932
+ beginTaskRename(item,view,node) {
933
+ if (!node.isConnected || this.taskRename?.saving) return;
934
+ if (this.taskRename) this.finishTaskRename(this.taskRename);
935
+ const row = make('div','session-task session-task-editing');
936
+ row.dataset.sessionTask = item.id;
937
+ if (item.id === this.task?.id) row.setAttribute('aria-current','true');
938
+ row.append(...node.childNodes); node.replaceWith(row);
939
+ const input = make('input','session-task-rename');
940
+ input.type = 'text'; input.maxLength = 120; input.value = item.title || '';
941
+ input.setAttribute('aria-label','会话标题'); input.setAttribute('enterkeyhint','done');
942
+ row.querySelector('.session-task-title').replaceWith(input);
943
+ const error = make('span','session-task-rename-error'); error.hidden = true;
944
+ error.setAttribute('role','alert'); row.querySelector('.session-task-details').append(error);
945
+ const edit = this.taskRename = {item,view,row,input,error};
946
+ input.oninput = () => { error.hidden = true; };
947
+ input.onkeydown = event => {
948
+ if (event.isComposing || event.keyCode === 229 || !['Enter','Escape'].includes(event.key)) return;
949
+ event.preventDefault(); event.stopPropagation();
950
+ if (edit.saving) return;
951
+ if (event.key === 'Escape') this.finishTaskRename(edit);
952
+ else void this.saveTaskRename(edit);
953
+ };
954
+ input.focus({preventScroll:true}); input.select?.();
955
+ }
956
+ async saveTaskRename(edit) {
957
+ const title = edit.input.value.trim();
958
+ if (!title) { edit.error.textContent = '请输入会话标题。'; edit.error.hidden = false; return; }
959
+ if (title === edit.item.title) { this.finishTaskRename(edit); return; }
960
+ edit.saving = true; edit.input.readOnly = true; edit.error.hidden = true;
961
+ try {
962
+ const saved = await this.fetch('/task-title',{method:'POST',body:{task:edit.item.id,title}});
963
+ edit.item.title = saved.title;
964
+ if (this.task?.id === edit.item.id) {
965
+ this.task.title = saved.title;
966
+ this.renderChatHeader();
967
+ }
968
+ this.finishTaskRename(edit);
969
+ } catch (error) {
970
+ edit.saving = false; edit.input.readOnly = false;
971
+ edit.error.textContent = error.message; edit.error.hidden = false;
972
+ }
973
+ }
974
+ finishTaskRename(edit) {
975
+ if (this.taskRename !== edit) return;
976
+ this.taskRename = undefined;
977
+ if (!edit.row.isConnected) return;
978
+ const focused = document.activeElement === edit.input;
979
+ const node = this.taskButton(edit.item,edit.view);
980
+ edit.row.replaceWith(node);
981
+ if (focused) node.focus({preventScroll:true});
982
+ if (edit.view.loading) edit.view.sequence++;
983
+ void this.loadGroup(edit.view,false,true);
984
+ }
788
985
  updateSelected() {
789
986
  for (const node of this.groupList?.querySelectorAll('[data-session-task]') || []) {
790
987
  if (node.dataset.sessionTask === this.task?.id) node.setAttribute('aria-current','true'); else node.removeAttribute('aria-current');
791
988
  }
792
989
  }
793
990
  async choose(taskId, nav = {}) {
794
- if (this.newDraft) this.leaveDraft();
991
+ if (this.newDraft && this.newDraft !== nav.sentDraft) this.leaveDraft();
795
992
  if (!this.csrf || !taskId || this.task?.id === taskId && !nav.history && !this.selecting) {
796
993
  if (this.task?.id === taskId) this.app.navigate(() => this.app.selectPane('chat'),true);
797
994
  return;
@@ -805,17 +1002,20 @@
805
1002
  const position = nav.position?.chat || (nav.href ? this.app.chatPositionFromUrl(nav.href) : this.app.savedSessionChat(taskId));
806
1003
  const anchor = position?.turn;
807
1004
  let snapshot;
808
- this.setChatError('正在打开任务…'); this.updateComposer();
1005
+ if (!nav.sentDraft) this.setChatError('正在打开任务…');
1006
+ this.updateComposer();
809
1007
  try {
810
1008
  const [data] = await Promise.all([this.loadTask(taskId,generation,anchor,controller.signal),this.restoreDraftFiles(taskId)]);
811
1009
  snapshot = data;
812
1010
  if (controller.signal.aborted || !this.csrf || generation !== this.generation) return;
813
1011
  this.app.activateTaskPanel(data.task,nav,() => {
1012
+ if (nav.sentDraft && this.newDraft === nav.sentDraft) this.leaveDraft(true);
814
1013
  this.imageDialog?.open && this.imageDialog.close();
815
1014
  this.imageNotice.hidden = true;
816
1015
  this.task = data.task; this.updateHead(data.head,data.headStatus,data.execution);
817
1016
  this.setPlanOpen(false); this.updatePlan(data.plan);
818
1017
  this.turns = data.turns; this.more = data.more; this.turnNodes.clear(); this.timeline.replaceChildren();
1018
+ this.clearChatImageHandoffs();
819
1019
  this.restoredPosition = undefined; this.pendingPosition = position || {bottom:true};
820
1020
  this.input.value = this.draft(taskId); this.checkOperation(taskId,false);
821
1021
  this.outboxRows = new Map(); this.outbox.replaceChildren();
@@ -827,6 +1027,7 @@
827
1027
  if (!nav.history && !nav.initial && !this.left.clientHeight) this.chatTitle.focus({preventScroll:true});
828
1028
  } catch (error) {
829
1029
  if (!controller.signal.aborted && this.csrf) {
1030
+ if (nav.sentDraft && this.newDraft === nav.sentDraft) this.leaveDraft(true);
830
1031
  const message = `无法打开任务:${error.status ? error.message : '连接失败,请重试。'}`;
831
1032
  const retry = () => this.choose(taskId,nav);
832
1033
  this.setChatError(message,false,retry);
@@ -852,8 +1053,13 @@
852
1053
  }
853
1054
  drainTail(snapshot) {
854
1055
  const tail = this.bufferedTail; this.bufferedTail = undefined;
855
- if (tail && tail.taskId === this.task?.id && tail.generation === this.generation && tail.epoch === this.connectionEpoch
856
- && (snapshot?.epoch !== tail.epoch || tail.version > snapshot.version)) this.applyTail(tail.value);
1056
+ if (!tail || tail.taskId !== this.task?.id || tail.generation !== this.generation || tail.epoch !== this.connectionEpoch) return;
1057
+ const afterSnapshot = version => snapshot?.epoch !== tail.epoch || version > snapshot.version;
1058
+ if (!afterSnapshot(tail.version)) return;
1059
+ const queue = tail.queue;
1060
+ const value = tail.value && queue && afterSnapshot(queue.version)
1061
+ ? {...tail.value,queued:queue.queued,queuedPrompts:queue.queuedPrompts} : tail.value;
1062
+ this.applyTail(value);
857
1063
  }
858
1064
  updateHead(head, status, execution) {
859
1065
  this.head = head; this.headStatus = status; this.execution = execution;
@@ -944,6 +1150,7 @@
944
1150
  }
945
1151
  }
946
1152
  renderChat() {
1153
+ this.clearChatImageHandoffs();
947
1154
  this.composing = false;
948
1155
  this.chatHeader = make('header','session-chat-header');
949
1156
  this.chatTitle = make('h2',null,'聊天'); this.chatTitle.tabIndex = -1;
@@ -952,8 +1159,8 @@
952
1159
  this.chatMeta.tabIndex = 0; this.chatMeta.setAttribute('role','group'); this.chatMeta.setAttribute('aria-label','任务信息');
953
1160
  this.chatState = make('span','session-state'); this.chatAgent = make('span','session-agent');
954
1161
  this.chatTurns = make('span','session-turn-count'); this.chatTokens = make('span','session-token-usage');
955
- this.chatStorage = make('span','session-storage-size'); this.chatModel = make('span','session-model');
956
- this.chatMeta.append(this.chatState,this.chatAgent,this.chatTurns,this.chatTokens,this.chatStorage,this.chatModel);
1162
+ this.chatStorage = make('span','session-storage-size');
1163
+ this.chatMeta.append(this.chatState,this.chatAgent,this.chatTurns,this.chatTokens,this.chatStorage);
957
1164
  this.chatError = make('div','session-chat-error'); this.chatError.setAttribute('role','status'); this.chatError.hidden = true;
958
1165
  const body = this.body = make('div','chat-body session-chat-body'); body.tabIndex = 0; body.setAttribute('role','region'); body.setAttribute('aria-label','对话记录');
959
1166
  const reading = make('div','session-chat-reading');
@@ -979,10 +1186,11 @@
979
1186
  this.older = button('加载更早的对话',() => this.loadOlder(),'session-more session-older'); this.older.hidden = true;
980
1187
  this.timeline = make('div','session-timeline'); this.turnNodes = new Map();
981
1188
  this.outbox = make('div','session-outbox'); this.outboxRows = new Map();
1189
+ this.draftPreview = make('div','session-outbox session-draft-preview'); this.draftPreview.hidden = true;
982
1190
  this.timelineObserver?.disconnect(); this.closeSettingsMenu();
983
1191
  this.chat.removeAttribute('data-draft');
984
1192
  const stabilizeReadingPosition = () => {
985
- if (!this.task || !body.clientHeight) return;
1193
+ if (!this.task || this.newDraft || !body.clientHeight) return;
986
1194
  this.pendingPosition ||= this.lastPosition;
987
1195
  if (body.clientHeight === this.chatBodyHeight) this.restorePosition();
988
1196
  else window.requestAnimationFrame(() => { if (this.body === body && body.isConnected) this.restorePosition(); });
@@ -1003,7 +1211,7 @@
1003
1211
  }
1004
1212
  }, true);
1005
1213
  this.timeline.append(make('div','session-empty','从左侧选择一个任务,查看对话并继续工作。'));
1006
- this.body.append(this.older,this.timeline,this.outbox);
1214
+ this.body.append(this.older,this.timeline,this.outbox,this.draftPreview);
1007
1215
  body.addEventListener('click', event => {
1008
1216
  if (this.previewChatImage(event)) return;
1009
1217
  const link = event.target.closest?.('[data-chat-file]');
@@ -1016,12 +1224,13 @@
1016
1224
  this.jump = iconButton('回到最新','M12 4v16m-6-6 6 6 6-6','session-jump',() => this.jumpToBottom());
1017
1225
  this.jump.hidden = true;
1018
1226
  body.onscroll = () => {
1227
+ if (!this.task || this.newDraft || !body.clientHeight) return;
1228
+ this.jump.hidden = this.atBottom();
1019
1229
  // A growing editor changes the scroll range before the resize observer restores the reading position.
1020
- if (!this.task || !this.chatBodyHeight || body.clientHeight !== this.chatBodyHeight || this.pendingPosition) return;
1230
+ if (body.clientHeight !== this.chatBodyHeight || this.pendingPosition) return;
1021
1231
  if (this.restoredPosition?.top === body.scrollTop) return;
1022
1232
  this.restoredPosition = undefined;
1023
1233
  this.lastPosition = this.position(true);
1024
- this.jump.hidden = this.atBottom();
1025
1234
  };
1026
1235
  const form = this.composer = make('form','session-composer'), field = make('div','session-composer-field');
1027
1236
  this.composerMirror = window.CSS?.supports('field-sizing','content') ? undefined : field;
@@ -1037,7 +1246,7 @@
1037
1246
  this.keepComposerPosition(position);
1038
1247
  };
1039
1248
  this.input.onkeydown = event => {
1040
- if (event.key !== 'Enter' || event.isComposing || this.composing || event.keyCode === 229) return;
1249
+ if (event.key !== 'Enter' || event.shiftKey || event.isComposing || this.composing || event.keyCode === 229) return;
1041
1250
  event.preventDefault();
1042
1251
  if (event.altKey) {
1043
1252
  const {value,selectionStart,selectionEnd,maxLength} = this.input;
@@ -1045,7 +1254,7 @@
1045
1254
  this.input.setRangeText('\n',selectionStart,selectionEnd,'end');
1046
1255
  this.input.dispatchEvent(new Event('input',{bubbles:true}));
1047
1256
  }
1048
- } else this.submit(event.shiftKey || event.ctrlKey || event.metaKey ? 'queue' : 'send');
1257
+ } else this.submit(event.ctrlKey || event.metaKey ? 'queue' : 'send');
1049
1258
  };
1050
1259
  this.input.setAttribute('aria-keyshortcuts','Enter Shift+Enter Control+Enter Meta+Enter Alt+Enter');
1051
1260
  this.input.oncompositionstart = () => { this.composing = true; }; this.input.oncompositionend = () => { this.composing = false; };
@@ -1078,6 +1287,13 @@
1078
1287
  this.stop = iconButton('停止','M6 6h12v12H6Z','session-stop',() => this.submit('stop')); this.stop.hidden = true;
1079
1288
  this.send = iconButton('发送','M12 20V4m-6 6 6-6 6 6','session-primary'); this.send.type = 'submit';
1080
1289
  this.send.setAttribute('aria-keyshortcuts','Enter');
1290
+ const narrow = window.matchMedia?.('(max-width:650px),(max-width:950px) and (max-height:500px)');
1291
+ this.bindSendLongPress(this.send,narrow);
1292
+ this.send.tooltipDetail = () => this.send.dataset.tooltipDetailShortcut ? '发送排队消息' : '';
1293
+ this.send.tooltipNote = () => {
1294
+ if (!this.send.dataset.tooltipDetailShortcut) return '';
1295
+ return narrow?.matches ? '输入 /queue 或长按发送键 1 秒也可排队' : '输入 /queue 也可排队';
1296
+ };
1081
1297
  for (const control of [this.attach,this.stop,this.schedule,this.send]) control.dataset.tooltip = '';
1082
1298
  form.onsubmit = event => { event.preventDefault(); void this.submit('send'); };
1083
1299
  this.attachments = make('div','session-draft-images'); this.attachments.setAttribute('role','group'); this.attachments.setAttribute('aria-label','待发送附件');
@@ -1087,11 +1303,13 @@
1087
1303
  const dialog = this.imageDialog = make('dialog','session-image-dialog'); dialog.setAttribute('aria-label','图片预览');
1088
1304
  const dismiss = iconButton('关闭图片预览','M6 6l12 12M18 6 6 18','session-image-dismiss',() => dialog.close());
1089
1305
  dismiss.autofocus = true; dismiss.setAttribute('aria-keyshortcuts','Escape');
1090
- this.imagePreview = make('img'); this.imagePreview.alt = '';
1091
- dialog.append(this.imagePreview,dismiss);
1092
- dialog.onclick = event => { if (event.target === dialog) dialog.close(); };
1093
- const preview = this.imagePreview;
1094
- dialog.onclose = () => { if (!dialog.open) preview.removeAttribute('src'); };
1306
+ const preview = this.imagePreview = make('img'); preview.alt = '';
1307
+ preview.onload = () => this.applyChatImagePixels(preview,[preview.naturalWidth,preview.naturalHeight]);
1308
+ dialog.append(preview,dismiss);
1309
+ dialog.onclick = event => { if (event.target === dialog || event.target === preview) dialog.close(); };
1310
+ dialog.onclose = () => {
1311
+ if (!dialog.open) { this.imagePreviewLoad?.abort(); preview.removeAttribute('src'); }
1312
+ };
1095
1313
  const settings = make('div','session-compose-settings');
1096
1314
  this.modelButton = button('',() => this.openTaskSettings('model'),'session-compose-model');
1097
1315
  this.thinkingButton = button('',() => this.openTaskSettings('thinking'),'session-compose-thinking');
@@ -1107,18 +1325,54 @@
1107
1325
  controls.append(this.stop,this.schedule,this.send); trailing.append(settings,controls); actions.append(this.attach,trailing);
1108
1326
  form.append(this.attachments,field,actions,menu);
1109
1327
  this.draftTools = make('div','session-new-draft-tools'); this.draftTools.hidden = true;
1110
- this.executionBar = make('div','session-run-status'); this.executionBar.hidden = true;
1328
+ this.executionBar = make('div','session-run-status'); this.executionBar.hidden = true; this.executionBar.tabIndex = 0;
1111
1329
  this.executionBar.setAttribute('role','group'); this.executionBar.setAttribute('aria-label','本轮执行信息');
1112
- const duration = make('span','session-run-duration','耗时 ');
1330
+ const duration = make('span','session-run-duration');
1113
1331
  this.elapsedTime = make('time'); duration.append(this.elapsedTime);
1114
1332
  this.executionModel = make('span','session-run-model'); this.executionThinking = make('span','session-run-thinking');
1115
- this.executionBar.append(duration,this.executionModel,this.executionThinking);
1333
+ this.executionTokens = make('span','session-run-tokens'); this.executionTokens.hidden = true;
1334
+ this.executionBar.append(duration,this.executionModel,this.executionThinking,this.executionTokens);
1116
1335
  this.queueList = make('ol','session-prompt-queue'); this.queueList.setAttribute('aria-label','已排队的消息');
1117
1336
  this.queueRows = new Map(); this.queueEdit = undefined;
1118
1337
  const footer = make('div','session-chat-footer'); footer.append(this.jump,this.planButton,this.opNote,this.imageNotice,this.draftStorageNote,this.draftTools,this.executionBar,this.queueList,form);
1119
1338
  this.chat.replaceChildren(this.chatHeader,this.chatError,reading,footer,dialog);
1120
1339
  this.updateComposer();
1121
1340
  }
1341
+ bindSendLongPress(send,narrow) {
1342
+ let press;
1343
+ send.onpointerdown = event => {
1344
+ if (!event.isPrimary || event.button !== 0) return;
1345
+ clearTimeout(press?.timer); press = undefined;
1346
+ if (!narrow?.matches || send.disabled || !this.task || this.newDraft) return;
1347
+ const {pointerId,clientX,clientY} = event, generation = this.generation;
1348
+ const current = press = {pointerId,clientX,clientY,down:true};
1349
+ current.timer = setTimeout(() => {
1350
+ current.suppressClick = true;
1351
+ if (press === current && !this.disposed && generation === this.generation && !this.newDraft
1352
+ && this.send === send && !send.disabled && send.getClientRects().length && !document.hidden && narrow.matches) {
1353
+ this.submit('queue',true);
1354
+ }
1355
+ },1000);
1356
+ send.setPointerCapture?.(pointerId);
1357
+ };
1358
+ send.onpointermove = event => {
1359
+ if (!press?.down || press.pointerId !== event.pointerId) return;
1360
+ if (Math.hypot(event.clientX-press.clientX,event.clientY-press.clientY) <= 10) return;
1361
+ clearTimeout(press.timer); press.suppressClick = true;
1362
+ };
1363
+ send.onpointerup = send.onlostpointercapture = event => {
1364
+ if (!press || press.pointerId !== event.pointerId) return;
1365
+ clearTimeout(press.timer); press.down = false;
1366
+ };
1367
+ send.onpointercancel = event => {
1368
+ if (!press || press.pointerId !== event.pointerId) return;
1369
+ clearTimeout(press.timer); press = undefined;
1370
+ };
1371
+ send.oncontextmenu = event => { if (press?.down) event.preventDefault(); };
1372
+ send.onclick = event => {
1373
+ if (event.detail > 0 && press?.suppressClick) event.preventDefault();
1374
+ };
1375
+ }
1122
1376
  setPlanOpen(open) {
1123
1377
  this.chat.toggleAttribute('data-plan-open',open);
1124
1378
  this.planButton.setAttribute('aria-expanded',String(open));
@@ -1296,7 +1550,6 @@
1296
1550
  [this.chatTurns,Number.isSafeInteger(turnCount) ? headerNumbers.format(turnCount)+' 轮' : ''],
1297
1551
  [this.chatTokens,Number.isSafeInteger(totalTokens) ? headerTokens.format(totalTokens)+' tokens' : ''],
1298
1552
  [this.chatStorage,storageSize ? '磁盘 '+storageSize : ''],
1299
- [this.chatModel,[task.provider,task.model].filter(Boolean).join(' · ')],
1300
1553
  ];
1301
1554
  for (const [node,text] of items) {
1302
1555
  setText(node,text || ''); node.hidden = !text;
@@ -1311,12 +1564,29 @@
1311
1564
  redraw() {
1312
1565
  let position = this.pendingPosition || this.position();
1313
1566
  const messages = this.messages(this.task.id), matched = new Set();
1567
+ const removed = [];
1568
+ const reconcile = request => {
1569
+ const message = this.removeMessage(this.task.id,request);
1570
+ if (message) removed.push(...message.images);
1571
+ };
1572
+ for (const prompt of this.task.queuedPrompts || []) {
1573
+ if (prompt.id.startsWith('workspace:')) reconcile(prompt.id.slice('workspace:'.length));
1574
+ }
1314
1575
  if (messages.size) for (const turn of this.turns) {
1315
1576
  if (turn.promptRequestId && messages.has(turn.promptRequestId)) {
1316
- if (turn.id.startsWith('pending_')) matched.add(turn.promptRequestId);
1317
- else this.removeMessage(this.task.id,turn.promptRequestId);
1577
+ if (turn.id.startsWith('pending_')) {
1578
+ const message = messages.get(turn.promptRequestId);
1579
+ message.queued = false; matched.add(turn.promptRequestId);
1580
+ }
1581
+ else reconcile(turn.promptRequestId);
1318
1582
  }
1319
- for (const item of turn.timeline) if (item.kind === 'user' && item.requestId) this.removeMessage(this.task.id,item.requestId);
1583
+ for (const item of turn.timeline) if (item.kind === 'user' && item.requestId) reconcile(item.requestId);
1584
+ }
1585
+ const steers = new Map();
1586
+ for (const [id,message] of messages) {
1587
+ if (message.payload.action !== 'steer' || (queuedMessage(message) && this.task.status !== 'closed')) continue;
1588
+ const list = steers.get(message.payload.turn) ?? [];
1589
+ list.push([id,message]); steers.set(message.payload.turn,list);
1320
1590
  }
1321
1591
  if (!this.turns.length) {
1322
1592
  this.timeline.replaceChildren(...(messages.size ? [] : [make('div','session-empty','还没有对话。发送一条消息,开始新的轮次。')]));
@@ -1339,31 +1609,46 @@
1339
1609
  for (const [id,state] of this.turnNodes) if (!keep.has(id)) { state.node.remove(); this.turnNodes.delete(id); }
1340
1610
  let previous = null;
1341
1611
  for (const turn of this.turns) {
1342
- const node = this.renderTurn(turn,messages.get(turn.promptRequestId)), next = previous ? previous.nextSibling : this.timeline.firstChild;
1343
- if (node !== next) this.timeline.insertBefore(node,next);
1612
+ const pendingSteers = steers.get(turn.id);
1613
+ for (const [id] of pendingSteers || []) matched.add(id);
1614
+ const node = this.renderTurn(turn,messages.get(turn.promptRequestId),pendingSteers), next = previous ? previous.nextSibling : this.timeline.firstChild;
1615
+ if (node !== next) {
1616
+ if (typeof this.timeline.moveBefore === 'function' && node.isConnected) this.timeline.moveBefore(node,next);
1617
+ else this.timeline.insertBefore(node,next);
1618
+ }
1344
1619
  previous = node;
1345
1620
  }
1346
1621
  }
1347
1622
  this.renderOutbox(messages,matched);
1623
+ for (const image of removed) if (!this.chatImageHandoffs.has(image.src)) revokeAttachment(image);
1624
+ for (const [src,handoff] of this.chatImageHandoffs) if (!handoff.image.isConnected) this.releaseChatImageHandoff(src);
1625
+ this.renderExecutionStatus();
1348
1626
  this.pendingPosition = position; this.restorePosition();
1349
1627
  }
1350
- renderTurn(turn,op) {
1628
+ createTurnEntry(separateTurn) {
1629
+ const content = make('div','session-turn-content');
1630
+ if (!separateTurn) return {node:content,content,rows:new Map()};
1631
+ const node = make('article','session-turn'), meta = make('div','session-turn-meta');
1632
+ meta.hidden = true; node.append(content);
1633
+ return {node,content,meta,rows:new Map()};
1634
+ }
1635
+ renderTurn(turn,op,steers) {
1351
1636
  let entry = this.turnNodes.get(turn.id);
1352
1637
  if (!entry) {
1353
- const node = make('article','session-turn'); node.dataset.turn = turn.id;
1354
- const header = make('div','session-turn-meta'), content = make('div','session-turn-content');
1355
- node.append(header,content);
1356
- entry = {node,header,content,rows:new Map()}; this.turnNodes.set(turn.id,entry);
1638
+ const outgoing = this.outboxRows.get(turn.promptRequestId);
1639
+ entry = outgoing?.meta ? outgoing : this.createTurnEntry(true);
1640
+ entry.node.dataset.turn = turn.id; this.turnNodes.set(turn.id,entry);
1357
1641
  }
1358
1642
  const error = op?.error, closed = this.task.status === 'closed';
1359
- if (entry.turn === turn && entry.error === error && entry.closed === closed) return entry.node;
1360
- const signature = JSON.stringify([turn,error,closed]);
1361
- Object.assign(entry,{turn,error,closed});
1643
+ const active = !closed && turn.id === this.head && !turn.final && (turn.status === 'starting' || turn.status === 'running' || turn.status === 'tool_running');
1644
+ const steerState = steers && JSON.stringify(steers.map(([id,message]) => [id,message.error,message.stale,message.accepted,message.restored]));
1645
+ if (entry.turn === turn && entry.error === error && entry.closed === closed && entry.active === active && entry.steerState === steerState) return entry.node;
1646
+ const signature = JSON.stringify([turn,error,closed,active,steerState]);
1647
+ Object.assign(entry,{turn,error,closed,active,steerState});
1362
1648
  if (entry.signature === signature) return entry.node;
1363
1649
  entry.signature = signature;
1364
- const time = Number.isFinite(turn.startedAt) && turn.startedAt > 0 ? new Date(turn.startedAt).toLocaleString(undefined,{month:'short',day:'numeric',hour:'2-digit',minute:'2-digit'}) : '';
1365
- setText(entry.header,[time,turn.status === 'completed' ? null : status(turn.status),turn.summary?'仅有摘要':null,turn.delivered === false?'飞书待投递':null].filter(Boolean).join(' · '));
1366
- entry.header.hidden = !entry.header.textContent;
1650
+ setText(entry.meta,[['completed','starting','running','tool_running'].includes(turn.status) ? null : status(turn.status),turn.summary?'仅有摘要':null,turn.delivered === false?'飞书待投递':null].filter(Boolean).join(' · '));
1651
+ entry.meta.hidden = !entry.meta.textContent;
1367
1652
  const rows = new Map(), usedGroups = new Set();
1368
1653
  const visibleTools = turn.compact ? new Set(turn.timeline.flatMap(item => item.kind === 'execution' ? item.tools.map(tool => tool.id) : [])) : undefined;
1369
1654
  const groupsByTool = new Map();
@@ -1374,20 +1659,36 @@
1374
1659
  const old = entry.rows.get(key), signature = JSON.stringify(value);
1375
1660
  rows.set(key,old?.signature === signature ? old : {signature,node:build()});
1376
1661
  };
1377
- const message = (key, role, text, images, answer, note, outgoing, files, request) => {
1378
- const previous = entry.rows.get(key) ?? this.outboxRows.get(request);
1379
- const signature = JSON.stringify([role,text,images,answer,note,outgoing?.error,outgoing?.error && this.task.status,files]);
1662
+ const message = (key, role, text, images, answer, note, outgoing, files, request, startedAt, quotes) => {
1663
+ const previous = entry.rows.get(key) ?? this.outboxRows.get(request)?.rows.get('prompt');
1664
+ startedAt ??= previous?.startedAt;
1665
+ const signature = JSON.stringify([role,text,images,answer,note,outgoing?.error,outgoing?.error && this.task.status,files,startedAt,quotes]);
1380
1666
  if (previous?.signature === signature) { rows.set(key,previous); return; }
1381
- const node = this.messageNode(role,text,images,answer,note,outgoing,files);
1382
- if (previous?.node.matches('.session-message') && node.matches('.session-message')) {
1667
+ const node = this.messageNode(role,text,images,answer,note,outgoing,files,startedAt,quotes);
1668
+ if (previous?.node.localName === node.localName && !outgoing?.error && !previous.node.querySelector('.session-send-retry')) {
1669
+ if (role === 'user' && request) {
1670
+ const oldImages = previous.node.querySelectorAll('.session-message-images > *');
1671
+ for (const [index,image] of [...node.querySelectorAll('.session-message-images > *')].entries()) {
1672
+ const old = oldImages[index];
1673
+ if (image.tagName === 'IMG' && old?.tagName === 'IMG') {
1674
+ if (!image.hasAttribute('data-chat-image-sized')) {
1675
+ this.applyChatImageSize(image,[Number(old.getAttribute('width')) || old.naturalWidth,
1676
+ Number(old.getAttribute('height')) || old.naturalHeight]);
1677
+ }
1678
+ this.applyChatImagePixels(image,[old.naturalWidth,old.naturalHeight]);
1679
+ this.handoffChatImage(old,image);
1680
+ }
1681
+ }
1682
+ }
1383
1683
  window.agentBotLiveMarkup.patchNode(previous.node,node);
1384
- previous.signature = signature; rows.set(key,previous);
1385
- } else rows.set(key,{signature,node});
1684
+ Object.assign(previous,{signature,startedAt}); rows.set(key,previous);
1685
+ } else rows.set(key,{signature,node,startedAt});
1386
1686
  };
1387
- if (turn.prompt || turn.promptImages?.length || turn.promptFiles?.length)
1388
- message('prompt','user',turn.prompt,turn.promptImages,undefined,undefined,op,turn.promptFiles,turn.promptRequestId);
1687
+ let awaitingOutput = !turn.answer;
1688
+ if (turn.prompt || turn.promptImages?.length || turn.promptFiles?.length || turn.promptQuotes?.length)
1689
+ message('prompt','user',turn.prompt,turn.promptImages,undefined,undefined,op,turn.promptFiles,turn.promptRequestId,turn.startedAt,turn.promptQuotes);
1389
1690
  for (const item of turn.timeline) {
1390
- const key = 'activity:'+item.id;
1691
+ const key = item.kind === 'user' && item.requestId ? 'steer:'+item.requestId : 'activity:'+item.id;
1391
1692
  if (item.kind === 'execution') {
1392
1693
  const exact = entry.rows.get(key);
1393
1694
  const old = exact && !usedGroups.has(exact) ? exact
@@ -1395,54 +1696,117 @@
1395
1696
  const group = this.executionGroup(turn,item,old,visibleTools);
1396
1697
  usedGroups.add(group); rows.set(key,group);
1397
1698
  }
1398
- else if (item.kind === 'user') message(key,'user',item.text,item.images,undefined,undefined,undefined,item.files,item.requestId);
1399
- else message(key,'assistant',item.text,undefined,item.rich,item.kind === 'system' ? 'session-system'
1400
- : item.kind === 'reasoning' ? 'session-thinking' : 'session-commentary');
1699
+ else if (item.kind === 'reasoning') rows.set(key,this.thinkingSummary(item,entry.rows.get(key)));
1700
+ else if (item.kind === 'user') message(key,'user',item.text,item.images,undefined,undefined,undefined,item.files,item.requestId,item.startedAt,item.quotes);
1701
+ else message(key,'assistant',item.text,undefined,item.rich,item.kind === 'system' ? 'session-system' : 'session-commentary');
1702
+ if (item.kind !== 'system') awaitingOutput = item.kind === 'user';
1703
+ }
1704
+ let outgoingSteer;
1705
+ for (const [id,outgoing] of steers || []) {
1706
+ const key = 'steer:'+id;
1707
+ rows.set(key,this.outgoingRow(outgoing,entry.rows.get(key) ?? this.outboxRows.get(id)?.rows.get('prompt')));
1708
+ if (!outgoing.error && !outgoing.restored && !closed) outgoingSteer = outgoing;
1709
+ }
1710
+ if (active && !turn.answer) {
1711
+ let label = '';
1712
+ if (outgoingSteer && !outgoingSteer.accepted) label = '正在发送';
1713
+ else if (outgoingSteer || awaitingOutput) label = turn.status === 'starting' ? '正在启动 Agent' : '等待 Agent 输出';
1714
+ place('pending-output',label,() => this.pendingOutput(label));
1401
1715
  }
1402
1716
  if (turn.hasDetails) rows.set('overview',this.executionOverview(turn,entry.rows.get('overview')));
1403
- if (turn.compact) place('compact',true,() => make('p','session-muted session-compact','仅显示已保存的部分活动,完整记录请查看 Turn Preview。'));
1717
+ if (turn.compact) place('compact',true,() => make('p','session-muted session-compact','此轮的部分活动记录已不可用。'));
1404
1718
  if (turn.answer) message('answer','assistant',undefined,undefined,turn.answer);
1405
- if (turn.final && turn.answerExport) place('answer-actions',[turn.status,turn.previewUrl,closed],() => this.answerActions(turn,closed));
1406
1719
  if (turn.error) place('error',turn.error,() => make('p','session-error session-turn-error',turn.error));
1407
1720
  if (turn.status === 'waiting_for_approval') place('approval',true,() => make('p','session-waiting','请到任务原来的飞书会话确认。'));
1721
+ const answerActions = Boolean(turn.final && turn.answerExport);
1722
+ if (answerActions || turn.completedAt != null || turn.durationMs != null || turn.usage?.length) {
1723
+ place('answer-actions',[turn.status,turn.previewUrl,closed,answerActions],
1724
+ () => this.answerActions(turn,closed,answerActions));
1725
+ const actions = rows.get('answer-actions');
1726
+ const metadata = JSON.stringify([turn.completedAt,turn.durationMs,turn.usage]);
1727
+ if (actions.metadata !== metadata) {
1728
+ this.updateAnswerMetadata(actions.node.querySelector('.session-answer-timing'),turn);
1729
+ actions.metadata = metadata;
1730
+ }
1731
+ }
1408
1732
  if (!rows.size) place('waiting',true,() => make('div','session-muted','正在等待 Agent 的输出…'));
1733
+ rows.set('meta',entry.rows.get('meta') ?? {node:entry.meta});
1409
1734
  const displayed = keepOpenGroups(entry.rows,rows,visibleTools);
1735
+ if (displayed !== rows) {
1736
+ for (const [key,group] of displayed) {
1737
+ if (!rows.has(key) && group.node.hasAttribute('data-tool-running')) this.setExecutionGroupRunning(group,false);
1738
+ }
1739
+ }
1410
1740
  syncRows(entry.content,entry.rows,displayed);
1411
1741
  entry.rows = displayed;
1412
1742
  return entry.node;
1413
1743
  }
1414
- answerActions(turn,closed) {
1744
+ answerActions(turn,closed,showActions) {
1415
1745
  const row = make('div','session-answer-actions'), feedback = make('span','session-muted');
1416
- row.setAttribute('role','group'); row.setAttribute('aria-label','最终回答操作');
1746
+ row.setAttribute('role','group'); row.setAttribute('aria-label',showActions ? '最终回答操作' : '轮次信息');
1417
1747
  feedback.setAttribute('role','status');
1418
- const actions = [
1748
+ const actions = showActions ? [
1419
1749
  ['copy','复制 Markdown','M9 9h11v12H9zM15 9V4H4v12h5'],
1420
1750
  ['download','下载 Markdown','M12 3v12m-5-5 5 5 5-5M5 16v5h14v-5'],
1421
- ['reset','重置当前聊天到这一轮','M4 10a8 8 0 1 1 2 8m-2-8V4m0 6h6'],
1751
+ ['reset','重置当前聊天到这一轮','M5 5v14M19 6l-9 6 9 6z'],
1422
1752
  ['fork','从这一轮创建分支','M6 3a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm0 14a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm0 0V7m0 7h4a7 7 0 0 0 7-7m0-4a2 2 0 1 0 0 4 2 2 0 0 0 0-4z'],
1423
- ['share','复制 Turn Preview 链接','M10 13a4 4 0 0 0 6 0l4-4a4 4 0 1 0-6-6l-2 2m2 6a4 4 0 0 0-6 0l-4 4a4 4 0 1 0 6 6l2-2'],
1424
- ];
1753
+ ] : [];
1425
1754
  const task = this.task.id;
1426
1755
  for (const [action,label,path] of actions) {
1427
1756
  const control = iconButton(label,path,'session-answer-action',() => void this.runAnswerAction(task,turn,action,control,feedback));
1428
1757
  control.dataset.answerAction = action;
1429
- control.disabled = action === 'share' ? !turn.previewUrl : action === 'reset' ? closed || turn.status !== 'completed'
1758
+ control.dataset.tooltip = label;
1759
+ control.disabled = action === 'reset' ? closed || turn.status !== 'completed'
1430
1760
  : action === 'fork' && turn.status !== 'completed';
1431
1761
  row.append(control);
1432
1762
  }
1433
- row.append(feedback);
1763
+ if (showActions) {
1764
+ const share = make(turn.previewUrl ? 'a' : 'button','session-answer-action');
1765
+ if (turn.previewUrl) {
1766
+ share.href = turn.previewUrl; share.target = '_blank'; share.rel = 'noopener noreferrer';
1767
+ } else { share.type = 'button'; share.disabled = true; }
1768
+ share.dataset.answerAction = 'share'; share.dataset.tooltip = '分享 · 打开 Turn Preview';
1769
+ labelButton(share,share.dataset.tooltip);
1770
+ share.append(this.app.createIcon('share')); row.append(share,feedback);
1771
+ }
1772
+ row.append(make('span','session-answer-timing'));
1434
1773
  return row;
1435
1774
  }
1775
+ updateAnswerMetadata(timing,turn) {
1776
+ const fields = [];
1777
+ if (Number.isFinite(turn.completedAt) && turn.completedAt > 0) {
1778
+ const end = make('span','session-answer-ended','结束 ');
1779
+ end.append(chatTime(turn.completedAt));
1780
+ fields.push(end);
1781
+ }
1782
+ if (Number.isFinite(turn.durationMs) && turn.durationMs >= 0) {
1783
+ const seconds = Math.floor(turn.durationMs/1000), duration = make('time',null,executionClock(seconds));
1784
+ duration.setAttribute('datetime','PT'+seconds+'S');
1785
+ const elapsed = make('span','session-answer-elapsed','耗时 ');
1786
+ elapsed.append(duration);
1787
+ fields.push(elapsed);
1788
+ }
1789
+ const usage = turn.usage ?? [];
1790
+ timing.toggleAttribute('data-tooltip-on-click',Boolean(usage.length));
1791
+ if (usage.length) {
1792
+ if (!fields.length) fields.push(make('span','session-answer-elapsed','耗时未记录'));
1793
+ timing.tabIndex = 0;
1794
+ timing.dataset.tooltip = '本轮统计';
1795
+ timing.tooltipDetail = () => usage.map(item => item.text).join(' · ');
1796
+ } else {
1797
+ timing.removeAttribute('tabindex');
1798
+ delete timing.dataset.tooltip;
1799
+ timing.tooltipDetail = undefined;
1800
+ }
1801
+ timing.replaceChildren(...fields);
1802
+ }
1436
1803
  async runAnswerAction(task, turn, action, control, feedback) {
1437
1804
  const generation = this.generation, mutates = action === 'reset' || action === 'fork';
1438
1805
  if (control.disabled || task !== this.task?.id || mutates && (this.selecting || this.pendingTurnActions.has(task))) return;
1439
1806
  if (mutates) this.pendingTurnActions.add(task);
1440
1807
  control.disabled = true; feedback.textContent = '';
1441
1808
  try {
1442
- if (action === 'share') {
1443
- await window.agentBotMarkdown.copy(turn.previewUrl);
1444
- feedback.textContent = '已复制分享链接';
1445
- } else if (action === 'copy' || action === 'download') {
1809
+ if (action === 'copy' || action === 'download') {
1446
1810
  const answer = this.fetch('/answer',{params:{task,turn:turn.id}});
1447
1811
  if (action === 'copy') await window.agentBotMarkdown.copy(answer.then(data => data.markdown));
1448
1812
  else {
@@ -1464,24 +1828,39 @@
1464
1828
  }
1465
1829
  }
1466
1830
  } catch (error) {
1467
- feedback.textContent = error.status ? error.message : action === 'copy' || action === 'share'
1831
+ feedback.textContent = error.status ? error.message : action === 'copy'
1468
1832
  ? '复制失败,请检查剪贴板权限或网络连接。' : action === 'download' ? '下载失败,请重试。' : '无法确认操作结果,请刷新任务列表。';
1469
1833
  } finally {
1470
1834
  if (mutates) this.pendingTurnActions.delete(task);
1471
1835
  control.disabled = false;
1472
1836
  }
1473
1837
  }
1474
- messageNode(role,text,images,answer,note,outgoing,files) {
1838
+ messageNode(role,text,images,answer,note,outgoing,files,startedAt,quotes) {
1475
1839
  const node = make('section','session-message '+role+(note?' '+note:''));
1476
1840
  node.setAttribute('aria-label',role === 'user' ? '你的消息' : note === 'session-commentary' ? '进展说明'
1477
- : note === 'session-thinking' ? '思考摘要' : note ? '运行提示' : 'Agent 回答');
1841
+ : note ? '运行提示' : 'Agent 回答');
1478
1842
  if (text) node.append(make('div','session-message-text',text));
1843
+ for (const {source,quote,note} of quotes || []) {
1844
+ const block = make('blockquote','session-prompt-quote');
1845
+ block.append(make('div','session-quote-text',quote || (source.directory ? source.path : sourceTitle(source))));
1846
+ if (note) block.append(make('div','session-quote-note',note));
1847
+ block.tabIndex = 0;
1848
+ block.dataset.tooltip = note ? '批注来源' : '引用来源';
1849
+ block.dataset.tooltipOnClick = '';
1850
+ block.dataset.tooltipDetail = quoteDetails(source);
1851
+ node.append(block);
1852
+ }
1479
1853
  if (images?.length) {
1480
1854
  const attachments = make('div','session-message-images');
1481
- for (const [index,src] of images.entries()) {
1855
+ for (const [index,item] of images.entries()) {
1856
+ const src = typeof item === 'string' ? item : item?.src;
1482
1857
  if (!src) { attachments.append(make('span','session-image-unavailable','图片不可用')); continue; }
1483
1858
  const image = make('img'); image.alt = `附件 ${index+1}`; image.loading = 'lazy'; image.decoding = 'async'; image.src = src;
1484
1859
  this.prepareChatImage(image); attachments.append(image);
1860
+ if (item.displaySize) {
1861
+ image.previewDisplaySize = item.displaySize;
1862
+ void item.displaySize.then(size => this.applyChatImageSize(image,size));
1863
+ }
1485
1864
  }
1486
1865
  node.append(attachments);
1487
1866
  }
@@ -1498,36 +1877,98 @@
1498
1877
  node.append(this.markdown(answer));
1499
1878
  if (answer.truncated) node.append(make('small','session-muted','内容较长,此处只显示前一部分。'));
1500
1879
  }
1501
- if (!outgoing?.error) return node;
1502
- const row = make('div','session-user-row'), retry = iconButton(outgoing.stale?'恢复到输入框':'重试发送',
1503
- 'M20 5v5h-5m-11 4v5h5m10.4-9A8 8 0 0 0 5.5 7m-.9 7a8 8 0 0 0 13.9 3','session-send-retry',
1504
- () => outgoing.stale ? this.restoreUnsentMessage(outgoing) : this.sendMessage(outgoing,true));
1505
- retry.dataset.tooltip = ''; retry.tooltipDetail = () => outgoing.error;
1506
- retry.disabled = this.task.status === 'closed';
1507
- row.append(retry,node);
1880
+ if (role !== 'user') return node;
1881
+ const row = make('div','session-user-row');
1882
+ if (outgoing?.error) {
1883
+ const retry = iconButton(outgoing.stale?'恢复到输入框':'重试发送',
1884
+ 'M20 5v5h-5m-11 4v5h5m10.4-9A8 8 0 0 0 5.5 7m-.9 7a8 8 0 0 0 13.9 3','session-send-retry',
1885
+ () => outgoing.stale ? this.restoreUnsentMessage(outgoing) : this.sendMessage(outgoing,true));
1886
+ retry.dataset.tooltip = ''; retry.tooltipDetail = () => outgoing.error;
1887
+ retry.disabled = this.task.status === 'closed';
1888
+ row.append(retry);
1889
+ }
1890
+ row.append(node);
1891
+ if (Number.isFinite(startedAt) && startedAt > 0) row.append(chatTime(startedAt,'session-prompt-time'));
1508
1892
  return row;
1509
1893
  }
1894
+ pendingOutput(label) {
1895
+ const node = make('p',label ? 'session-pending-output' : 'session-thinking-progress',label);
1896
+ node.setAttribute('role','status');
1897
+ if (!label) {
1898
+ node.setAttribute('aria-label','正在思考');
1899
+ for (let index = 0; index < 3; index++) {
1900
+ const dot = make('span'); dot.setAttribute('aria-hidden','true'); node.append(dot);
1901
+ }
1902
+ }
1903
+ return node;
1904
+ }
1905
+ outgoingNode(message) {
1906
+ return this.messageNode('user',message.payload.text,message.images.filter(image=>image.src),
1907
+ undefined,undefined,message,message.images.filter(image=>image.file && !image.src && !image.annotation && !image.reference)
1908
+ .map(image=>({name:image.file.name})),message.startedAt,promptQuotes(message.images));
1909
+ }
1910
+ outgoingRow(message,previous) {
1911
+ const signature = JSON.stringify([message.error,message.error && message.stale,this.task.status === 'closed']);
1912
+ return previous?.signature === signature ? previous : {signature,node:this.outgoingNode(message),startedAt:message.startedAt};
1913
+ }
1510
1914
  renderOutbox(messages,matched) {
1511
- const rows = new Map();
1915
+ const entries = new Map();
1512
1916
  for (const [id,message] of messages) {
1513
- if (matched.has(id)) continue;
1514
- const signature = JSON.stringify([message.error,message.stale,this.task.status === 'closed']);
1515
- const previous = this.outboxRows.get(id);
1516
- if (previous?.signature === signature) rows.set(id,previous);
1517
- else rows.set(id,{signature,node:this.messageNode('user',message.payload.text,message.images.flatMap(image=>image.src?[image.src]:[]),
1518
- undefined,undefined,message,message.images.filter(image=>!image.src).map(image=>({name:image.file.name})))});
1917
+ if (matched.has(id) || this.task.status !== 'closed' && queuedMessage(message)) continue;
1918
+ const entry = this.outboxRows.get(id) ?? this.createTurnEntry(message.payload.action !== 'steer');
1919
+ const rows = new Map();
1920
+ rows.set('prompt',this.outgoingRow(message,entry.rows.get('prompt')));
1921
+ if (!message.error && !message.restored && this.task.status !== 'closed') {
1922
+ const label = message.accepted ? '等待 Agent 输出' : '正在发送';
1923
+ const old = entry.rows.get('pending-output');
1924
+ rows.set('pending-output',old?.signature === JSON.stringify(label) ? old : {signature:JSON.stringify(label),node:this.pendingOutput(label)});
1925
+ }
1926
+ syncRows(entry.content,entry.rows,rows);
1927
+ entry.rows = rows; entries.set(id,entry);
1519
1928
  }
1520
- syncRows(this.outbox,this.outboxRows,rows); this.outboxRows = rows;
1929
+ syncRows(this.outbox,this.outboxRows,entries); this.outboxRows = entries;
1521
1930
  }
1522
1931
  markdown(data) {
1523
1932
  const rich = make('div','markdown-body'); rich.innerHTML = data.html;
1933
+ for (const code of rich.querySelectorAll('pre>code')) numberChatCode(code,code.classList.contains('language-diff'));
1524
1934
  for (const image of rich.querySelectorAll('img[src]')) this.prepareChatImage(image);
1525
1935
  return rich;
1526
1936
  }
1527
1937
  prepareChatImage(image) {
1528
1938
  image.dataset.chatImage = ''; image.tabIndex = 0;
1529
1939
  image.setAttribute('role','button'); image.setAttribute('aria-label',image.alt ? '查看大图 · '+image.alt : '查看大图');
1530
- this.applyChatImageSize(image,this.chatImageSizes.get(this.chatImageKey(image)));
1940
+ const pixels = this.chatImageSizes.get(this.chatImageKey(image));
1941
+ this.applyChatImageSize(image,declaredChatImageSize(image.getAttribute('src')) ?? pixels);
1942
+ this.applyChatImagePixels(image,image.naturalWidth ? [image.naturalWidth,image.naturalHeight] : pixels);
1943
+ }
1944
+ handoffChatImage(current,incoming) {
1945
+ const src = current.getAttribute('src'), saved = incoming.getAttribute('src');
1946
+ if (!src?.startsWith('blob:') || !saved || src === saved) return;
1947
+ const tracked = this.chatImageHandoffs.get(src);
1948
+ if (tracked?.image === current && tracked.saved === saved) {
1949
+ incoming.src = src; return;
1950
+ }
1951
+ const replacement = incoming.cloneNode(true), handoff = {image:current,saved};
1952
+ this.chatImageHandoffs.set(src,handoff);
1953
+ incoming.src = src;
1954
+ replacement.loading = 'eager'; replacement.decoding = 'sync';
1955
+ replacement.addEventListener('load',() => {
1956
+ if (this.chatImageHandoffs.get(src) !== handoff) return;
1957
+ if (current.isConnected && current.getAttribute('src') === src) {
1958
+ const focused = document.activeElement === current;
1959
+ current.replaceWith(replacement);
1960
+ this.rememberChatImageSize(replacement);
1961
+ if (focused) replacement.focus({preventScroll:true});
1962
+ }
1963
+ this.releaseChatImageHandoff(src);
1964
+ },{once:true});
1965
+ }
1966
+ releaseChatImageHandoff(src) {
1967
+ this.chatImageHandoffs.delete(src);
1968
+ URL.revokeObjectURL(src);
1969
+ }
1970
+ clearChatImageHandoffs() {
1971
+ for (const src of this.chatImageHandoffs.keys()) this.releaseChatImageHandoff(src);
1531
1972
  }
1532
1973
  chatImageKey(image) {
1533
1974
  try {
@@ -1537,18 +1978,39 @@
1537
1978
  return url.pathname+url.search;
1538
1979
  } catch { /* An image with no usable URL cannot have a cached size. */ }
1539
1980
  }
1981
+ syncChatImageDpr = () => {
1982
+ const dpr = window.devicePixelRatio || 1;
1983
+ if (this.chatImageDpr === dpr) return;
1984
+ this.chatImageDpr = dpr;
1985
+ this.app.style.setProperty('--chat-image-dpr',String(Math.max(1,dpr)));
1986
+ this.chatImageResolution?.removeEventListener?.('change',this.syncChatImageDpr);
1987
+ this.chatImageResolution = window.matchMedia?.(`(resolution: ${dpr}dppx)`);
1988
+ this.chatImageResolution?.addEventListener?.('change',this.syncChatImageDpr);
1989
+ };
1990
+ validChatImageSize(size) {
1991
+ return Array.isArray(size) && size.length === 2
1992
+ && size.every(value => Number.isInteger(value) && value > 0 && value <= 1_000_000);
1993
+ }
1540
1994
  applyChatImageSize(image,size) {
1541
- if (!Array.isArray(size) || size.length !== 2 || !size.every(value => Number.isInteger(value) && value > 0 && value <= 1_000_000)) return;
1995
+ if (!this.validChatImageSize(size)) return;
1542
1996
  const [width,height] = size;
1543
1997
  image.setAttribute('width',String(width)); image.setAttribute('height',String(height));
1544
1998
  image.style.setProperty('--chat-image-width',width+'px');
1545
1999
  image.style.setProperty('--chat-image-ratio',String(width/height));
1546
2000
  image.dataset.chatImageSized = '';
1547
2001
  }
2002
+ applyChatImagePixels(image,size) {
2003
+ if (!this.validChatImageSize(size)) return;
2004
+ const [width,height] = size;
2005
+ image.style.setProperty('--chat-image-pixel-width',width+'px');
2006
+ image.style.setProperty('--chat-image-pixel-ratio',String(width/height));
2007
+ if (!image.hasAttribute('data-chat-image-sized')) this.applyChatImageSize(image,size);
2008
+ }
1548
2009
  rememberChatImageSize(image) {
1549
- const key = this.chatImageKey(image), size = [image.naturalWidth,image.naturalHeight], previous = this.chatImageSizes.get(key);
1550
- if (!key || !size.every(Boolean) || previous?.[0] === size[0] && previous[1] === size[1]) return;
1551
- this.applyChatImageSize(image,size);
2010
+ const size = [image.naturalWidth,image.naturalHeight];
2011
+ this.applyChatImagePixels(image,size);
2012
+ const key = this.chatImageKey(image), previous = this.chatImageSizes.get(key);
2013
+ if (!key || !this.validChatImageSize(size) || previous?.[0] === size[0] && previous[1] === size[1]) return;
1552
2014
  this.chatImageSizes.delete(key); this.chatImageSizes.set(key,size);
1553
2015
  if (this.chatImageSizes.size > chatImageSizeLimit) this.chatImageSizes.delete(this.chatImageSizes.keys().next().value);
1554
2016
  save(this.chatImageSizeKey,[...this.chatImageSizes],'sessionStorage');
@@ -1557,12 +2019,46 @@
1557
2019
  const image = event.target.closest?.('[data-chat-image][src]');
1558
2020
  if (!image || event.defaultPrevented) return false;
1559
2021
  event.preventDefault();
1560
- this.openImage(image.currentSrc || image.src,image.alt);
2022
+ this.openImage(image.currentSrc || image.src,image.alt,declaredChatImageSize(image.getAttribute('src')) ?? image.previewDisplaySize,
2023
+ [image.naturalWidth,image.naturalHeight]);
1561
2024
  return true;
1562
2025
  }
1563
- openImage(src,label) {
2026
+ previewImageSize(src,signal) {
2027
+ const data = /^data:image\/png;base64,/iu.exec(src);
2028
+ if (data) {
2029
+ try {
2030
+ const prefix = atob(src.slice(data[0].length,data[0].length+Math.ceil(workspacePngHeaderBytes/3)*4));
2031
+ return workspacePngDisplaySize(new DataView(Uint8Array.from(prefix,char => char.charCodeAt(0)).buffer));
2032
+ } catch { return; }
2033
+ }
2034
+ let url;
2035
+ try { url = new URL(src,window.location.href); } catch { return; }
2036
+ if (url.origin !== window.location.origin || url.pathname !== this.base+'/image'
2037
+ || !/\.png$/iu.test(url.searchParams.get('entry') || '')) return;
2038
+ return fetch(url,{headers:{Range:`bytes=0-${workspacePngHeaderBytes-1}`},redirect:'error',signal})
2039
+ .then(async response => {
2040
+ if (response.status !== 206) { await response.body?.cancel(); return; }
2041
+ return workspacePngDisplaySize(new DataView(await response.arrayBuffer()));
2042
+ }).catch(() => undefined);
2043
+ }
2044
+ openImage(src,label,size,pixels) {
1564
2045
  if (this.imageDialog.open) return;
1565
- this.imagePreview.alt = label || ''; this.imagePreview.src = src;
2046
+ this.imagePreviewLoad?.abort();
2047
+ const controller = this.imagePreviewLoad = new AbortController(), preview = this.imagePreview;
2048
+ preview.removeAttribute('width'); preview.removeAttribute('height'); preview.removeAttribute('data-chat-image-sized');
2049
+ preview.style.removeProperty('visibility');
2050
+ preview.style.removeProperty('--chat-image-pixel-width'); preview.style.removeProperty('--chat-image-pixel-ratio');
2051
+ this.applyChatImagePixels(preview,pixels);
2052
+ const displaySize = size === undefined ? this.previewImageSize(src,controller.signal) : size;
2053
+ if (displaySize?.then) {
2054
+ preview.style.visibility = 'hidden';
2055
+ const timeout = setTimeout(() => controller.abort(),1500);
2056
+ void displaySize.then(dimensions => {
2057
+ if (this.imagePreviewLoad !== controller || !this.imageDialog.open) return;
2058
+ this.applyChatImageSize(preview,dimensions); preview.style.removeProperty('visibility');
2059
+ }).finally(() => clearTimeout(timeout));
2060
+ } else this.applyChatImageSize(preview,displaySize);
2061
+ preview.alt = label || ''; preview.src = src;
1566
2062
  this.imageDialog.showModal();
1567
2063
  }
1568
2064
  keepExecutionTitle(summary, change) {
@@ -1591,18 +2087,88 @@
1591
2087
  const badge = make('span','session-execution-badge');
1592
2088
  summary.append(label,badge); node.append(summary,body);
1593
2089
  this.bindExecutionSummary(node,summary);
1594
- return {node,label,badge,body};
2090
+ return {node,summary,label,badge,body};
2091
+ }
2092
+ setExecutionIcon(row,kind) {
2093
+ if (row.iconKind === kind) return;
2094
+ row.iconKind = kind;
2095
+ row.icon?.remove(); row.icon = this.app.toolIcon(kind); row.summary.prepend(row.icon);
2096
+ }
2097
+ setExecutionGroupRunning(group,running) {
2098
+ group.node.toggleAttribute('data-tool-running',running);
2099
+ this.setExecutionIcon(group,running ? 'hourglass' : 'tool');
2100
+ }
2101
+ rollingTitle(label) {
2102
+ const viewport = make('span','session-execution-title-viewport');
2103
+ label.replaceWith(viewport); viewport.append(label);
2104
+ return viewport;
2105
+ }
2106
+ updateRollingTitle(row,title) {
2107
+ const {label} = row, previous = label.textContent;
2108
+ if (previous === title) return;
2109
+ row.finishTitleChange?.();
2110
+ label.textContent = title;
2111
+ if (!previous || !title || !label.animate || window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return;
2112
+ const outgoing = make('span','session-execution-title-outgoing',previous);
2113
+ outgoing.setAttribute('aria-hidden','true');
2114
+ label.after(outgoing);
2115
+ const timing = {duration:180,easing:'ease-out'};
2116
+ const incomingAnimation = label.animate([{transform:'translateY(100%)'},{transform:'translateY(0)'}],timing);
2117
+ const outgoingAnimation = outgoing.animate([{transform:'translateY(0)'},{transform:'translateY(-100%)'}],timing);
2118
+ const finish = () => {
2119
+ if (row.finishTitleChange !== finish) return;
2120
+ row.finishTitleChange = undefined;
2121
+ incomingAnimation.cancel(); outgoingAnimation.cancel(); outgoing.remove();
2122
+ };
2123
+ row.finishTitleChange = incomingAnimation.onfinish = finish;
2124
+ }
2125
+ thinkingSummary(item,existing) {
2126
+ let row = existing;
2127
+ if (!row) {
2128
+ const node = make('section','session-thinking'), label = make('span','session-execution-title');
2129
+ node.setAttribute('aria-label','思考摘要');
2130
+ row = {node,label,viewport:this.rollingTitle(label),icon:this.app.toolIcon('think')};
2131
+ }
2132
+ const html = item.detail?.html;
2133
+ if (!row.node.firstChild || Boolean(row.body) !== Boolean(html)) {
2134
+ row.open = row.details?.open ?? row.open;
2135
+ const heading = make(html?'summary':'div','session-thinking-heading');
2136
+ heading.append(row.icon,row.viewport);
2137
+ if (html) {
2138
+ row.details = make('details','session-execution');
2139
+ row.body = make('div','session-execution-body session-thinking-detail');
2140
+ row.details.open = row.open ?? false;
2141
+ row.details.append(heading,row.body);
2142
+ this.bindExecutionSummary(row.details,heading);
2143
+ row.node.replaceChildren(row.details);
2144
+ } else {
2145
+ row.details = row.body = undefined;
2146
+ row.node.replaceChildren(heading);
2147
+ }
2148
+ row.detailHtml = undefined;
2149
+ }
2150
+ this.updateRollingTitle(row,item.title ?? item.text ?? '思考摘要');
2151
+ if (row.body && row.detailHtml !== html) {
2152
+ const detail = this.markdown(item.detail);
2153
+ if (row.body.firstElementChild) window.agentBotLiveMarkup.patchNode(row.body.firstElementChild,detail);
2154
+ else row.body.append(detail);
2155
+ row.detailHtml = html;
2156
+ }
2157
+ return row;
1595
2158
  }
1596
2159
  executionGroup(turn,item,existing,visibleTools) {
1597
2160
  let group = existing;
1598
2161
  if (!group) {
1599
2162
  group = this.disclosure('session-execution','');
2163
+ this.rollingTitle(group.label);
1600
2164
  group.tools = make('div','session-tools'); group.rows = new Map();
1601
2165
  group.body.append(group.tools);
1602
2166
  group.node.ontoggle = () => this.refreshExecutionGroup(group);
1603
2167
  }
1604
2168
  group.node.dataset.executionGroup = item.id;
1605
- setText(group.label,item.title);
2169
+ const running = (turn.status === 'starting' || activeTurn(turn.status)) && item.tools.some(tool => tool.status === 'running');
2170
+ this.setExecutionGroupRunning(group,running);
2171
+ this.updateRollingTitle(group,item.title);
1606
2172
  const rows = new Map(visibleTools ? [...group.rows].filter(([id,row]) => row.node.open && !visibleTools.has(id)) : []);
1607
2173
  for (const tool of item.tools) rows.set(tool.id,this.executionTool(turn,tool,group));
1608
2174
  setText(group.badge,rows.size ? `· ${rows.size} 项工具` : '');
@@ -1621,10 +2187,8 @@
1621
2187
  row.node.ontoggle = () => { if (group.node.open && row.node.open) void this.loadExecution(row.body,row.request); };
1622
2188
  }
1623
2189
  const kind = tool.kind || (tool.command ? 'command' : 'tool');
1624
- if (row.node.dataset.toolKind !== kind) {
1625
- row.node.dataset.toolKind = kind;
1626
- row.icon?.remove(); row.icon = this.app.toolIcon(kind); row.label.before(row.icon);
1627
- }
2190
+ row.node.dataset.toolKind = kind;
2191
+ this.setExecutionIcon(row,kind);
1628
2192
  row.label.textContent = tool.title?.replace(/\s+/gu,' ').trim() || '工具';
1629
2193
  row.label.classList.toggle('session-tool-command-title',tool.command === true);
1630
2194
  row.badge.textContent = tool.status === 'completed' ? '' : status(tool.status); row.badge.dataset.status = tool.status;
@@ -1633,6 +2197,7 @@
1633
2197
  }
1634
2198
  executionOverview(turn,existing) {
1635
2199
  const row = existing || this.disclosure('session-execution','文件变更');
2200
+ this.setExecutionIcon(row,'file_change');
1636
2201
  setText(row.badge,turn.fileChangeCount ? ` · ${turn.fileChangeCount}` : '');
1637
2202
  row.request = {route:'/detail',params:{turn:turn.id},revision:turn.detailRevision || turn.status};
1638
2203
  row.node.ontoggle = () => { if (row.node.open) void this.loadExecution(row.body,row.request); };
@@ -1665,14 +2230,15 @@
1665
2230
  if (body.loading === request.revision) body.loading = undefined;
1666
2231
  }
1667
2232
  }
1668
- renderToolFiles(files, truncated) {
2233
+ renderToolFiles(files, truncated, tool, opened) {
1669
2234
  if (!files?.length) return;
1670
2235
  const section = make('div','session-tool-files'), list = make('ul');
1671
2236
  list.setAttribute('aria-label','此工具修改的文件'); section.append(list);
1672
2237
  for (const file of files) {
1673
- const item = make('li'), header = make('div','session-tool-file');
1674
- const name = make(file.entry ? 'a' : 'span','session-tool-file-name',file.name);
1675
- if (file.entry) {
2238
+ const item = make('li'), header = make(file.patch?'summary':'div','session-tool-file');
2239
+ const fileLink = file.entry && !file.patch;
2240
+ const name = make(fileLink?'a':'span','session-tool-file-name',file.name);
2241
+ if (fileLink) {
1676
2242
  name.setAttribute('href',this.app.chatDiffUrl(file));
1677
2243
  name.setAttribute('aria-label','查看 '+file.name+' 的 Diff');
1678
2244
  name.onclick = event => {
@@ -1687,20 +2253,27 @@
1687
2253
  if (Number.isSafeInteger(file.deletions) && file.deletions > 0) counts.append(make('span','session-tool-file-deletions','−'+file.deletions));
1688
2254
  if (file.additions === 0 && file.deletions === 0) counts.append(make('span',null,'0'));
1689
2255
  if (counts.childElementCount) header.append(counts);
1690
- item.append(header);
1691
2256
  if (file.patch) {
1692
- const details = make('details','session-tool-file-patch'), summary = make('summary');
1693
- summary.append(make('span',null,'本次补丁'));
1694
- this.bindExecutionSummary(details,summary);
2257
+ const details = make('details','session-tool-file-patch'), preview = make('div','session-tool-patch-preview');
2258
+ details.dataset.patch = file.patchId || file.name;
2259
+ details.open = opened?.has(details.dataset.patch) ?? false;
2260
+ this.bindExecutionSummary(details,header);
1695
2261
  const patch = make('pre'); patch.tabIndex = 0; patch.setAttribute('aria-label','本次修改的补丁');
1696
2262
  const code = make('code');
1697
2263
  if (file.patchHtml) code.innerHTML = file.patchHtml;
1698
2264
  else code.textContent = file.patch;
1699
- patch.append(code);
1700
- details.append(summary,patch);
2265
+ numberChatCode(code,true);
2266
+ patch.append(code); preview.append(patch);
2267
+ if (tool && file.patchId) {
2268
+ const ref = JSON.stringify([tool.turn,tool.tool,file.patchId]);
2269
+ const open = iconButton('在 Tab 中打开本次修改','M14 3h7v7M21 3l-8 8m7 2v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h6','session-tool-patch-open',
2270
+ () => this.app.openChatFile(file.entry || file.name,'diff',undefined,file.source,file.original,ref));
2271
+ preview.append(open);
2272
+ }
2273
+ details.append(header,preview);
1701
2274
  if (file.patchTruncated) details.append(make('small','session-muted','已保存补丁的开头。'));
1702
2275
  item.append(details);
1703
- }
2276
+ } else item.append(header);
1704
2277
  list.append(item);
1705
2278
  }
1706
2279
  if (truncated) section.append(make('small','session-muted','仅显示前 '+files.length+' 个文件。'));
@@ -1761,7 +2334,8 @@
1761
2334
  issue.hidden = !data.partial;
1762
2335
  };
1763
2336
  append(first);
1764
- const files = this.renderToolFiles(first.files,first.filesTruncated);
2337
+ const opened = new Set([...body.querySelectorAll('.session-tool-file-patch[open]')].map(node => node.dataset.patch));
2338
+ const files = this.renderToolFiles(first.files,first.filesTruncated,request.params,opened);
1765
2339
  const empty = !files && !blocks.size && !first.next ? make('p','session-muted','该工具暂无输出。') : undefined;
1766
2340
  const timing = timeTool(request.tool);
1767
2341
  const footer = timing ? make('div','session-tool-footer',timing) : undefined;
@@ -1802,12 +2376,15 @@
1802
2376
  this.jump.hidden = true;
1803
2377
  this.app.queuePersist();
1804
2378
  }
1805
- atBottom() { return this.body.scrollHeight-this.body.scrollTop-this.body.clientHeight <= 1; }
2379
+ atBottom() { return this.body.scrollHeight-this.body.scrollTop-this.body.clientHeight <= 2; }
1806
2380
  position(measure = false) {
1807
2381
  if (this.pendingPosition && !measure) return this.pendingPosition;
1808
2382
  if (!this.task || !this.body?.clientHeight) return this.lastPosition;
1809
2383
  if (!measure && this.restoredPosition?.top === this.body.scrollTop) return this.restoredPosition.anchor;
1810
2384
  if (this.atBottom()) return {bottom:true};
2385
+ return this.visibleChatPosition() || {bottom:true};
2386
+ }
2387
+ visibleChatPosition() {
1811
2388
  const top = this.body.getBoundingClientRect().top;
1812
2389
  for (const node of this.timeline.children) {
1813
2390
  const rect = node.getBoundingClientRect();
@@ -1816,7 +2393,6 @@
1816
2393
  return {turn,offset:Math.round(top-rect.top),...(target ? {target} : {})};
1817
2394
  }
1818
2395
  }
1819
- return {bottom:true};
1820
2396
  }
1821
2397
  readingTarget(turn,top) {
1822
2398
  for (const [row,{node}] of turn?.rows || []) {
@@ -1832,7 +2408,11 @@
1832
2408
  }
1833
2409
  restorePosition() {
1834
2410
  this.chatBodyHeight = this.body?.clientHeight;
1835
- if (!this.pendingPosition || !this.chatBodyHeight) return;
2411
+ if (!this.chatBodyHeight) return;
2412
+ if (!this.pendingPosition) {
2413
+ this.jump.hidden = this.atBottom();
2414
+ return;
2415
+ }
1836
2416
  const position = this.pendingPosition; this.pendingPosition = undefined;
1837
2417
  const turn = position.turn && this.turnNodes.get(position.turn);
1838
2418
  const target = position.target;
@@ -1854,17 +2434,16 @@
1854
2434
  restoreDraftFiles(task) {
1855
2435
  const loading = this.fileLoads.get(task);
1856
2436
  if (loading) return loading;
1857
- const unpack = attachments => (attachments || []).map(({id,file,preview,annotation}) => ({
1858
- id,file,annotation,...(preview ? {src:draftAttachment(file,annotation).src} : {}),
1859
- }));
2437
+ const unpack = attachments => (attachments || []).map(({id,file,preview,annotation,reference}) => annotation || reference
2438
+ ? {id,annotation,reference} : preview ? draftAttachment(file,{id}) : {id,file});
1860
2439
  this.loadingDraftFiles.add(task);
1861
2440
  const load = this.draftFiles.read(task).then(record => {
1862
2441
  if (!record || this.disposed || this.fileLoads.get(task) !== load) return;
1863
2442
  this.fileRecords.add(task);
1864
2443
  if (record.draft?.length && !this.imageDrafts.has(task)) this.imageDrafts.set(task,unpack(record.draft));
1865
2444
  const messages = this.messages(task);
1866
- for (const [payload,error,attachments] of record.outbox || []) {
1867
- if (!messages.has(payload.request)) messages.set(payload.request,{payload,error,images:unpack(attachments),restored:true});
2445
+ for (const [payload,error,attachments,startedAt] of record.outbox || []) {
2446
+ if (!messages.has(payload.request)) messages.set(payload.request,{payload,error,startedAt,images:unpack(attachments),restored:true});
1868
2447
  }
1869
2448
  if (messages.size) this.outboxes.set(task,messages);
1870
2449
  }).catch(() => {}).finally(() => {
@@ -1876,12 +2455,12 @@
1876
2455
  return load;
1877
2456
  }
1878
2457
  persistDraftFiles(...tasks) {
1879
- const pack = items => items.map(({id,file,src,annotation}) => ({id,file,preview:Boolean(src),annotation}));
2458
+ const pack = items => items.map(({id,file,src,annotation,reference}) => ({id,file,preview:Boolean(src),annotation,reference}));
1880
2459
  const records = [];
1881
2460
  for (const task of new Set(tasks)) {
1882
2461
  const draft = pack(this.images(task));
1883
2462
  const outbox = [...this.messages(task).values()].filter(message => !message.accepted && message.images.length)
1884
- .map(message => [message.payload,message.error,pack(message.images)]);
2463
+ .map(message => [message.payload,message.error,pack(message.images),message.startedAt]);
1885
2464
  if (draft.length || outbox.length) {
1886
2465
  this.fileRecords.add(task); records.push([task,{draft,outbox}]);
1887
2466
  } else if (this.fileRecords.delete(task)) records.push([task,null]);
@@ -1911,32 +2490,33 @@
1911
2490
  this.pendingPosition = position; this.restorePosition();
1912
2491
  }
1913
2492
  }
1914
- addAttachments(files,annotation) {
2493
+ addAttachments(files) {
1915
2494
  const task = this.newDraft?.id ?? this.task?.id;
1916
2495
  if (!task || this.input.disabled || !files?.length) return;
1917
2496
  const position = this.position(true), images = this.images(task), added = [...images];
1918
- let total = images.reduce((size,image) => size+image.file.size,0);
2497
+ let total = images.reduce((size,image) => size+attachmentBytes(image),0);
1919
2498
  const issues = new Set();
1920
2499
  for (const file of files) {
1921
2500
  if (added.length >= imageCount || file.size > imageLimit || total+file.size > draftLimit) {
1922
2501
  issues.add('至多 4 个附件,单个不超过 5 MiB,合计不超过 12 MiB。'); continue;
1923
2502
  }
1924
2503
  total += file.size;
1925
- added.push(draftAttachment(file,annotation));
2504
+ added.push(draftAttachment(file));
1926
2505
  }
1927
2506
  if (added.length !== images.length) this.replaceImages(task,added);
1928
2507
  this.noticeImages([...issues].join(' ')); this.updateComposer(); this.keepComposerPosition(position);
1929
2508
  if (added.length > images.length) this.attachments.scrollLeft = this.attachments.scrollWidth;
1930
2509
  return added.length > images.length;
1931
2510
  }
1932
- removeImage(task,image) {
1933
- const images = this.images(task), index = images.indexOf(image);
2511
+ removeImage(task,id,{focus = true} = {}) {
2512
+ const images = this.images(task), index = images.findIndex(image => image.id === id);
1934
2513
  if (index < 0) return;
1935
- this.replaceImages(task,images.filter(entry=>entry!==image));
2514
+ this.replaceImages(task,images.filter(image => image.id !== id));
1936
2515
  if ((this.newDraft?.id ?? this.task?.id) === task) {
1937
2516
  const position = this.position(true);
1938
2517
  this.noticeImages(''); this.updateComposer(); this.keepComposerPosition(position);
1939
- const next = this.attachments.children[Math.min(index,images.length-2)]?.querySelector('.session-image-remove');
2518
+ if (!focus) return;
2519
+ const next = this.attachments.children[Math.min(index,images.length-2)]?.querySelector('button:not(.session-image-remove)');
1940
2520
  (next || this.attach).focus({preventScroll:true});
1941
2521
  }
1942
2522
  }
@@ -1949,16 +2529,46 @@
1949
2529
  }
1950
2530
  renderPromptQueue() {
1951
2531
  const task = this.task;
1952
- const prompts = !this.newDraft && task?.status !== 'closed' ? task?.queuedPrompts ?? [] : [];
2532
+ const shortcut = !this.newDraft && task && task.status !== 'closed' ? 'Control+Enter Meta+Enter' : '';
2533
+ if (this.send.dataset.tooltipDetailShortcut !== shortcut) this.send.dataset.tooltipDetailShortcut = shortcut;
2534
+ const prompts = !this.newDraft && task && task.status !== 'closed' ? [...(task.queuedPrompts ?? [])] : [];
2535
+ if (!this.newDraft && task && task.status !== 'closed') {
2536
+ const confirmed = new Set(prompts.map(prompt => prompt.id));
2537
+ // A live queue update can arrive before the page containing the new turn.
2538
+ if (this.head && !this.turnNodes.has(this.head) && this.displayedQueue?.task === task.id) {
2539
+ for (const [index,prompt] of this.displayedQueue.prompts.entries()) {
2540
+ if (!confirmed.has(prompt.id)) {
2541
+ prompts.splice(index,0,{...prompt,dispatching:true});
2542
+ confirmed.add(prompt.id);
2543
+ }
2544
+ }
2545
+ }
2546
+ this.displayedQueue = {task:task.id,prompts:[...prompts]};
2547
+ for (const message of this.messages(task.id).values()) {
2548
+ const id = 'workspace:'+message.payload.request;
2549
+ if (queuedMessage(message) && !confirmed.has(id)) prompts.push({id,text:attachmentPrompt(message.payload.text,message.images).slice(0,180),
2550
+ hasAttachments:Boolean(message.images.length),pending:true,error:message.error,request:message.payload.request});
2551
+ }
2552
+ } else this.displayedQueue = undefined;
1953
2553
  if (this.queueEdit && (this.queueEdit.task !== task?.id || this.newDraft || task.status === 'closed')) this.queueEdit = undefined;
1954
- const edit = this.queueEdit, blocked = this.restoringQueue === task?.id || this.selecting;
1955
- const signature = JSON.stringify([task?.id,prompts,blocked,edit?.prompt,edit?.saving]);
2554
+ const edit = this.queueEdit, operation = task && this.operation(task.id);
2555
+ const sendingPrompt = this.sendingFromQueue.get(task?.id);
2556
+ const sending = Boolean(sendingPrompt) || operation?.action === 'sendQueued' && ['pending','unknown'].includes(operation.status);
2557
+ const blocked = this.restoringQueue === task?.id || this.selecting || sending;
2558
+ const visiblePrompts = prompts.map(({id,text,hasAttachments,pending,error,revision,dispatching}) => [id,text,hasAttachments,pending,error,revision,dispatching]);
2559
+ const signature = JSON.stringify([task?.id,visiblePrompts,blocked,sendingPrompt,edit?.prompt,edit?.saving]);
1956
2560
  if (this.queueList.signature === signature) return;
1957
2561
  this.queueList.signature = signature; this.queueList.hidden = !prompts.length && !edit;
1958
2562
  this.queueList.toggleAttribute('data-editing',Boolean(edit));
1959
2563
  const rows = new Map();
1960
2564
  for (const [index,prompt] of prompts.entries()) {
2565
+ const dispatching = Boolean(prompt.dispatching || sendingPrompt === prompt.id);
1961
2566
  if (edit?.prompt === prompt.id) {
2567
+ if (edit.dispatching !== dispatching) {
2568
+ if (dispatching || edit.dispatching) setText(edit.note,dispatching ? '正在发送,可复制这里的内容。' : '');
2569
+ edit.dispatching = dispatching;
2570
+ edit.submit.disabled = dispatching || !edit.revision || edit.saving || Boolean(edit.left);
2571
+ }
1962
2572
  setText(edit.number,(index+1)+'.'); rows.set(prompt.id,edit); continue;
1963
2573
  }
1964
2574
  const existing = this.queueRows.get(prompt.id);
@@ -1966,7 +2576,21 @@
1966
2576
  setText(row.number,(index+1)+'.'); setText(row.label,prompt.text || '附件消息');
1967
2577
  labelButton(row.modify,`修改第 ${index+1} 条排队消息:${row.label.textContent}${prompt.hasAttachments ? ',含附件' : ''}`);
1968
2578
  row.attachment.hidden = !prompt.hasAttachments;
1969
- row.modify.disabled = blocked || Boolean(edit); row.cancel.disabled = blocked;
2579
+ row.sending.hidden = !dispatching;
2580
+ row.modify.disabled = blocked || Boolean(edit) || Boolean(prompt.pending) || dispatching;
2581
+ row.cancel.disabled = blocked || Boolean(prompt.pending) || dispatching;
2582
+ row.send.disabled = row.modify.disabled || !prompt.revision;
2583
+ if (prompt.error) {
2584
+ if (!row.retry) {
2585
+ row.retry = iconButton('重试排队','M20 5v5h-5m-11 4v5h5m10.4-9A8 8 0 0 0 5.5 7m-.9 7a8 8 0 0 0 13.9 3',
2586
+ 'session-send-retry',() => {
2587
+ const message = this.messages(task.id).get(prompt.request);
2588
+ if (message) void this.sendMessage(message,true);
2589
+ });
2590
+ row.retry.dataset.tooltip = ''; row.node.insertBefore(row.retry,row.cancel);
2591
+ }
2592
+ row.retry.tooltipDetail = () => prompt.error; row.retry.disabled = blocked;
2593
+ } else if (row.retry) { row.retry.remove(); row.retry = undefined; }
1970
2594
  rows.set(prompt.id,row);
1971
2595
  }
1972
2596
  if (edit && !rows.has(edit.prompt)) {
@@ -1981,54 +2605,106 @@
1981
2605
  const modify = button('',() => void this.editQueuedPrompt(id),'session-queue-edit');
1982
2606
  const label = make('span','session-queued-prompt'); label.dataset.tooltipOverflow = '';
1983
2607
  const attachment = make('span','session-queue-attachment','附件'); modify.append(label,attachment);
2608
+ const sending = make('span','session-queue-attachment','发送中'); modify.append(sending);
2609
+ const send = iconButton('立即发送','M12 19V5m-6 6 6-6 6 6','session-send-queued',() => void this.sendQueuedPrompt(id));
1984
2610
  const cancel = iconButton('取消排队并恢复到输入框','M6 6l12 12M18 6 6 18','session-cancel-queued',() => void this.restoreQueuedPrompt(id));
1985
- cancel.dataset.tooltip = ''; node.append(number,modify,cancel);
1986
- return {node,number,modify,label,attachment,cancel};
2611
+ send.dataset.tooltip = ''; cancel.dataset.tooltip = ''; node.append(number,modify,send,cancel);
2612
+ return {node,number,modify,label,attachment,sending,send,cancel};
2613
+ }
2614
+ async sendQueuedPrompt(prompt) {
2615
+ const task = this.task?.id, grant = this.csrf;
2616
+ const queued = this.task?.queuedPrompts?.find(item => item.id === prompt);
2617
+ if (!task || !grant || !queued?.revision || queued.dispatching || this.selecting || this.newDraft || this.disposed
2618
+ || this.queueEdit || this.restoringQueue || this.sendingFromQueue.has(task)) return;
2619
+ const request = uuid(), action = 'sendQueued';
2620
+ const current = () => this.task?.id === task && this.csrf === grant && !this.newDraft && !this.disposed;
2621
+ this.sendingFromQueue.set(task,prompt); this.setChatError(''); this.renderPromptQueue();
2622
+ try {
2623
+ let result;
2624
+ try { result = await this.fetch('/queue/send',{body:{task,prompt,request,revision:queued.revision},timeout:60_000}); }
2625
+ catch (error) {
2626
+ if (error.status && error.status !== 408 || this.csrf !== grant || this.disposed) throw error;
2627
+ result = await this.fetch('/operation',{params:{request}}).catch(() => ({status:'unknown'}));
2628
+ }
2629
+ if (this.csrf !== grant || this.disposed) return;
2630
+ if (result.status === 'accepted') {
2631
+ if (current() && (!this.connected || this.task.queuedPrompts?.some(item => item.id === prompt))) await this.refreshConversation(false);
2632
+ return;
2633
+ }
2634
+ if (['pending','unknown'].includes(result.status)) {
2635
+ this.setOperation(task,{request,action,status:result.status,message:result.message || '发送结果待核实。'});
2636
+ } else if (current()) this.setChatError(result.message || '发送排队消息失败。');
2637
+ } catch (error) {
2638
+ if (current()) {
2639
+ this.setChatError(error.message);
2640
+ if (error.status === 404 || error.status === 409) void this.refreshConversation(true);
2641
+ }
2642
+ } finally {
2643
+ this.sendingFromQueue.delete(task);
2644
+ if (current()) this.renderPromptQueue();
2645
+ }
1987
2646
  }
1988
2647
  async editQueuedPrompt(prompt) {
1989
2648
  const task = this.task?.id, grant = this.csrf;
1990
2649
  if (!task || !grant || this.newDraft || this.selecting || this.restoringQueue || this.queueEdit) return;
2650
+ const queued = this.task.queuedPrompts?.find(row => row.id === prompt);
2651
+ if (!queued || queued.dispatching) return;
1991
2652
  const node = make('li','session-queue-editing'), number = make('span','session-queue-number'); number.setAttribute('aria-hidden','true');
1992
2653
  const form = make('form','session-queue-edit-form'), input = make('textarea');
1993
- input.setAttribute('aria-label','修改排队消息'); input.rows = 2; input.maxLength = 24_000; input.disabled = true;
1994
- const actions = make('div','session-queue-edit-actions'), note = make('small','session-queue-edit-note','正在读取…'); note.setAttribute('role','status');
1995
- const close = button('取消',() => this.closeQueueEdit(edit),'session-quiet');
1996
- const submit = make('button','session-queue-save','保存'); submit.type = 'submit'; submit.disabled = true;
1997
- const edit = this.queueEdit = {node,number,task,prompt,grant,input,note,submit,close};
2654
+ const revision = queued.revision, original = queued.editText ?? queued.text;
2655
+ input.setAttribute('aria-label','修改排队消息'); input.rows = 2; input.maxLength = 24_000;
2656
+ input.placeholder = '修改排队消息…';
2657
+ input.value = revision ? original : ''; input.disabled = !revision;
2658
+ const actions = make('div','session-queue-edit-actions'), note = make('small','session-queue-edit-note'); note.setAttribute('role','status');
2659
+ const attachment = make('span','session-queue-attachment','附件'); attachment.hidden = !queued.hasAttachments;
2660
+ const close = button('取消',() => this.closeQueueEdit(edit),'session-queue-edit-close');
2661
+ const submit = make('button','session-queue-save','保存'); submit.type = 'submit'; submit.disabled = !revision;
2662
+ const edit = this.queueEdit = {node,number,task,prompt,grant,input,note,submit,close,revision,original};
1998
2663
  form.onsubmit = event => { event.preventDefault(); void this.saveQueueEdit(edit); };
1999
2664
  input.onkeydown = event => {
2000
2665
  if (event.isComposing || event.keyCode === 229) return;
2001
2666
  if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); this.closeQueueEdit(edit); }
2002
2667
  if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) { event.preventDefault(); void this.saveQueueEdit(edit); }
2003
2668
  };
2004
- actions.append(note,close,submit); form.append(input,actions); node.append(number,form); this.renderPromptQueue();
2669
+ const position = this.position(true);
2670
+ actions.append(attachment,note,close,submit); form.append(input,actions); node.append(number,form);
2671
+ this.renderPromptQueue(); this.keepComposerPosition(position);
2672
+ const bounds = node.getBoundingClientRect(), viewport = this.queueList.getBoundingClientRect();
2673
+ if (bounds.top < viewport.top || bounds.bottom > viewport.bottom) this.queueList.scrollTop += bounds.top-viewport.top;
2674
+ if (revision) { input.focus({preventScroll:true}); return; }
2005
2675
  try {
2006
2676
  const data = await this.fetch('/queue/edit',{params:{task,prompt}});
2007
2677
  if (this.queueEdit !== edit || this.disposed || this.csrf !== grant) return;
2008
2678
  edit.revision = data.revision; edit.original = input.value = data.text;
2009
- input.disabled = false; submit.disabled = Boolean(edit.left);
2010
- if (!edit.left) setText(note,'');
2679
+ input.disabled = false; submit.disabled = Boolean(edit.left || edit.dispatching);
2011
2680
  input.focus({preventScroll:true});
2012
2681
  } catch (error) { if (this.queueEdit === edit && !this.disposed) setText(note,error.message); }
2013
2682
  }
2014
2683
  closeQueueEdit(edit) {
2015
2684
  if (this.queueEdit !== edit || edit.saving) return;
2685
+ const position = this.position(true);
2016
2686
  this.queueEdit = undefined; this.renderPromptQueue();
2687
+ this.keepComposerPosition(position);
2017
2688
  (this.queueRows.get(edit.prompt)?.modify || this.input).focus({preventScroll:true});
2018
2689
  }
2019
2690
  async saveQueueEdit(edit) {
2020
2691
  if (this.queueEdit !== edit || edit.submit.disabled || edit.saving || this.selecting || this.csrf !== edit.grant) return;
2021
2692
  const {task,prompt,revision,input,submit,note,close} = edit;
2022
2693
  const before = this.task.queuedPrompts?.find(row => row.id === prompt);
2023
- if (!before) return;
2694
+ if (!before || before.dispatching) return;
2024
2695
  edit.saving = input.readOnly = close.disabled = submit.disabled = true; setText(note,'正在保存…');
2025
2696
  try {
2026
2697
  const result = await this.fetch('/queue/edit',{body:{task,prompt,revision,text:input.value}});
2027
2698
  if (this.queueEdit !== edit || this.disposed || this.csrf !== edit.grant) return;
2028
- this.task.queuedPrompts = this.task.queuedPrompts?.map(row => row === before ? result : row);
2699
+ this.task.queuedPrompts = this.task.queuedPrompts?.map(row => row.id === prompt && row.revision === before.revision ? result : row);
2029
2700
  edit.saving = false; this.closeQueueEdit(edit);
2030
- } catch (error) { if (this.queueEdit === edit && !this.disposed) setText(note,error.message); }
2031
- finally { edit.saving = input.readOnly = close.disabled = false; submit.disabled = Boolean(edit.left); }
2701
+ } catch (error) {
2702
+ if (this.queueEdit === edit && !this.disposed) {
2703
+ setText(note,error.message);
2704
+ if (error.status === 409 || error.status === 404) void this.refreshConversation(true);
2705
+ }
2706
+ }
2707
+ finally { edit.saving = input.readOnly = close.disabled = false; submit.disabled = Boolean(edit.left || edit.dispatching); }
2032
2708
  }
2033
2709
  async restoreQueuedPrompt(prompt) {
2034
2710
  const task = this.task?.id, grant = this.csrf, position = this.position(true);
@@ -2039,8 +2715,9 @@
2039
2715
  try {
2040
2716
  const queued = await this.fetch('/queue',{params:{task,prompt},signal:controller.signal});
2041
2717
  const sources = [...(queued.images || []).map((url,index) => ({url,name:`图片 ${index+1}`})),...(queued.files || [])];
2718
+ const quotes = (queued.quotes || []).map(draftQuote);
2042
2719
  const previous = this.images(task), text = [queued.text,this.draft(task)].filter(Boolean).join('\n\n');
2043
- if (text.length > 24_000 || previous.length+sources.length > imageCount) throw new Error('请先处理已有草稿,合并后的消息超出输入框限制。');
2720
+ if (text.length > 24_000 || previous.length+sources.length+quotes.length > imageCount) throw new Error('请先处理已有草稿,合并后的消息超出输入框限制。');
2044
2721
  const files = await Promise.all(sources.map(async ({url,name}) => {
2045
2722
  if (!url) throw new Error('排队消息中的附件已不可用。');
2046
2723
  const response = await fetch(url,{cache:'no-store',credentials:'same-origin',signal:controller.signal});
@@ -2048,7 +2725,8 @@
2048
2725
  const blob = await response.blob();
2049
2726
  return new File([blob],name,{type:blob.type});
2050
2727
  }));
2051
- if (files.some(file => file.size > imageLimit) || [...files,...previous.map(image=>image.file)].reduce((total,file)=>total+file.size,0) > draftLimit) {
2728
+ if (files.some(file => file.size > imageLimit) || files.reduce((total,file)=>total+file.size,0)
2729
+ + previous.reduce((total,item)=>total+attachmentBytes(item),0) > draftLimit) {
2052
2730
  throw new Error('请先处理已有附件,合并后的消息超出附件大小限制。');
2053
2731
  }
2054
2732
  if (this.csrf !== grant || this.disposed) return;
@@ -2056,7 +2734,7 @@
2056
2734
  const cancel = () => this.fetch('/queue',{body});
2057
2735
  const result = await cancel().catch(error => { if (error.status || this.csrf !== grant) throw error; return cancel(); });
2058
2736
  if (!result.cancelled) throw new Error('这条消息已离开队列。');
2059
- this.setDraft(task,text); this.replaceImages(task,[...previous,...files.map(file => draftAttachment(file))]);
2737
+ this.setDraft(task,text); this.replaceImages(task,[...previous,...files.map(file => draftAttachment(file)),...quotes]);
2060
2738
  if (visible()) {
2061
2739
  this.task.queuedPrompts = this.task.queuedPrompts?.filter(row => row.id !== prompt);
2062
2740
  this.input.value = text;
@@ -2074,23 +2752,46 @@
2074
2752
  this.app.annotations?.updateDrafts(task,all);
2075
2753
  const existing = new Map([...this.attachments.children].map(node => [node.dataset.image,node]));
2076
2754
  const nodes = all.map((image,index) => {
2077
- const name = image.file.name || `附件 ${index+1}`;
2755
+ const name = attachmentName(image) || `附件 ${index+1}`;
2078
2756
  if (existing.has(image.id)) return existing.get(image.id);
2079
2757
  const tile = make('div','session-image-tile'); tile.dataset.image = image.id;
2080
- const remove = iconButton('移除 '+name,'M6 6l12 12M18 6 6 18','session-image-remove',() => this.removeImage(task,image));
2758
+ const remove = iconButton('移除 '+name,'M6 6l12 12M18 6 6 18','session-image-remove',() => this.removeImage(task,image.id));
2081
2759
  if (!image.src) {
2082
2760
  tile.classList.add('session-file-tile');
2083
- const annotation = image.annotation;
2761
+ const {annotation,reference} = image;
2762
+ const label = button('',() => label.focus({preventScroll:true}),'session-file-label');
2763
+ if (annotation || reference) {
2764
+ labelButton(label,(annotation ? '批注' : '引用')+' · '+name);
2765
+ label.append(this.app.createIcon(annotation ? 'annotation' : 'quote'),make('span',null,name));
2766
+ } else label.textContent = name;
2084
2767
  if (annotation) {
2085
- const title = annotationTitle(annotation), label = make('span','session-file-label session-annotation-label',title);
2086
2768
  const excerpt = annotation.quote.trim().replace(/\s+/gu,' ');
2087
- label.tabIndex = 0; label.dataset.tooltip = title; label.dataset.annotationTooltip = '';
2088
- label.tooltipDetail = () => `原文 · ${excerpt.length > 100 ? excerpt.slice(0,100)+'…' : excerpt}\n批注 · ${annotation.note}`;
2089
- tile.append(label,remove);
2090
- } else tile.append(make('span','session-file-label',name),remove);
2769
+ label.classList.add('session-annotation-label');
2770
+ label.dataset.tooltip = name; label.dataset.annotationTooltip = '';
2771
+ label.tooltipDetail = () => {
2772
+ const current = this.images(task).find(item => item.id === image.id)?.annotation;
2773
+ return current ? `原文 · ${excerpt.length > 150 ? excerpt.slice(0,150)+'…' : excerpt}\n批注 · ${current.note}` : '';
2774
+ };
2775
+ }
2776
+ if (reference) {
2777
+ const details = [reference.path || reference.url || (reference.sessionId && quoteDetails(reference)),
2778
+ reference.quote?.trim().replace(/\s+/gu,' ').slice(0,160)].filter(Boolean);
2779
+ if (details.length) {
2780
+ label.dataset.tooltip = name; label.dataset.tooltipOnClick = '';
2781
+ label.tooltipDetail = () => details.join('\n');
2782
+ }
2783
+ }
2784
+ tile.append(label,remove);
2091
2785
  return tile;
2092
2786
  }
2093
- const open = button('',() => this.openImage(image.src,name),'session-image-open'); labelButton(open,'预览 '+name);
2787
+ let focusedOnPress;
2788
+ const open = button('',event => {
2789
+ open.focus({preventScroll:true});
2790
+ if (window.innerWidth <= 650 && event.detail > 0 && !focusedOnPress) return;
2791
+ this.openImage(image.src,name,image.displaySize ?? null,[thumbnail.naturalWidth,thumbnail.naturalHeight]);
2792
+ },'session-image-open');
2793
+ open.onpointerdown = () => { focusedOnPress = tile.contains(document.activeElement); };
2794
+ labelButton(open,'预览 '+name);
2094
2795
  const thumbnail = make('img'); thumbnail.alt = ''; thumbnail.src = image.src;
2095
2796
  thumbnail.onerror = () => {
2096
2797
  if (!this.images(task).includes(image)) return;
@@ -2119,44 +2820,58 @@
2119
2820
  messages(task) { return this.outboxes.get(task) || new Map(); }
2120
2821
  saveOutboxes() {
2121
2822
  const entries = [...this.outboxes].map(([task,messages]) => [task,[...messages].flatMap(([id,message]) =>
2122
- !message.images.length && !message.accepted ? [[id,message.payload,message.error]] : [])]);
2823
+ !message.images.length && !message.accepted ? [[id,message.payload,message.error,message.startedAt]] : [])]);
2123
2824
  save('agentbot-workspace-outbox',entries.filter(([,items])=>items.length),'sessionStorage');
2124
2825
  }
2125
2826
  removeMessage(task,id) {
2126
2827
  const messages = this.outboxes.get(task), message = messages?.get(id);
2127
2828
  if (!message) return;
2128
- for (const image of message.images) revokeAttachment(image);
2129
2829
  messages.delete(id);
2130
2830
  if (!messages.size) this.outboxes.delete(task);
2131
2831
  this.saveOutboxes();
2132
2832
  void this.persistDraftFiles(task);
2833
+ return message;
2133
2834
  }
2134
2835
  resetOutboxes() {
2836
+ this.clearChatImageHandoffs();
2135
2837
  for (const messages of this.outboxes.values()) for (const message of messages.values())
2136
2838
  for (const image of message.images) revokeAttachment(image);
2137
2839
  this.outboxes.clear();
2138
2840
  }
2139
2841
  operation(id) {
2140
2842
  const op = this.operations.get(id) ?? read('agentbot-workspace-operation:'+id,null,'sessionStorage');
2141
- return op?.action === 'stop' ? op : null;
2843
+ return ['stop','sendQueued'].includes(op?.action) ? op : null;
2142
2844
  }
2143
2845
  setOperation(id,op) {
2144
2846
  this.operations.set(id,op); save('agentbot-workspace-operation:'+id,op,'sessionStorage');
2145
2847
  if (this.task?.id === id) this.updateComposer();
2146
2848
  }
2147
2849
  renderExecutionStatus() {
2148
- const execution = this.task && this.task.status !== 'closed' && !this.newDraft ? this.execution : undefined;
2149
- this.executionBar.hidden = !execution;
2150
- if (execution) {
2151
- this.executionModel.textContent = '模型 '+(execution.model || '未记录');
2152
- this.executionThinking.textContent = '思考强度 '+(effortLabel(execution.thinking) || '未记录');
2850
+ let execution;
2851
+ if (this.task && this.task.status !== 'closed' && !this.newDraft) {
2852
+ execution = this.execution;
2853
+ if (!execution) {
2854
+ const outgoing = [...this.messages(this.task.id).values()].find(message =>
2855
+ message.payload.action === 'send' && !queuedMessage(message) && !message.restored && !message.error);
2856
+ if (outgoing) execution = {startedAt:outgoing.startedAt,model:this.task.model,thinking:this.task.thinking};
2857
+ }
2153
2858
  }
2859
+ this.executionStart = execution?.startedAt;
2860
+ this.executionBar.hidden = !execution;
2861
+ const model = execution?.model || '', thinking = effortLabel(execution?.thinking) || '';
2862
+ const tokens = execution?.tokenUsage?.replace(' tokens · ',' · ') || '';
2863
+ this.executionModel.hidden = !model;
2864
+ this.executionThinking.hidden = !thinking;
2865
+ this.executionTokens.hidden = !tokens;
2866
+ setText(this.executionModel,model);
2867
+ setText(this.executionThinking,thinking);
2868
+ setText(this.executionTokens,tokens);
2154
2869
  this.updateElapsedTime();
2155
2870
  }
2156
2871
  updateElapsedTime() {
2157
2872
  clearTimeout(this.executionTimer); this.executionTimer = undefined;
2158
2873
  if (this.executionBar.hidden || this.disposed) return;
2159
- const start = this.execution?.startedAt;
2874
+ const start = this.executionStart;
2160
2875
  if (!Number.isFinite(start) || start <= 0) {
2161
2876
  this.elapsedTime.removeAttribute('datetime'); this.elapsedTime.textContent = '未记录'; return;
2162
2877
  }
@@ -2165,6 +2880,11 @@
2165
2880
  this.elapsedTime.textContent = executionClock(seconds);
2166
2881
  this.executionTimer = setTimeout(() => this.updateElapsedTime(),1000-elapsed%1000);
2167
2882
  }
2883
+ shouldQueuePrompt() {
2884
+ if (this.newDraft || !this.task) return false;
2885
+ return queueableTurn(this.headStatus ?? this.task.status) || Boolean(this.task.queuedPrompts?.length)
2886
+ || [...this.messages(this.task.id).values()].some(message => queuedMessage(message) && !message.error);
2887
+ }
2168
2888
  updateComposer() {
2169
2889
  const draft = this.newDraft, task = draft ?? this.task, running = !draft && activeTurn(this.headStatus), archived = task?.status === 'closed';
2170
2890
  const op = !draft && task && this.operation(task.id), blocked = !task || archived || this.selecting || Boolean(draft?.sending)
@@ -2178,12 +2898,14 @@
2178
2898
  this.modelButton.disabled = this.thinkingButton.disabled = blocked || savingSettings || Boolean(draft && !draft.agents?.length);
2179
2899
  this.modelButton.firstElementChild.textContent = task?.model || '模型';
2180
2900
  this.thinkingButton.firstElementChild.textContent = effortLabel(task?.thinking) || '思考强度';
2181
- this.send.disabled = blocked || savingSettings || Boolean(draft && !draft.agent) || !(this.input.value.trim() || this.images(task?.id).length);
2901
+ const queuedText = queueCommandText(this.input.value);
2902
+ this.send.disabled = blocked || savingSettings || Boolean(draft && !draft.agent)
2903
+ || !((queuedText ?? this.input.value).trim() || this.images(task?.id).length);
2182
2904
  this.schedule.hidden = Boolean(draft);
2183
2905
  this.schedule.disabled = blocked;
2184
- labelButton(this.send,running && this.head ? '追加到当前轮次' : '发送');
2906
+ labelButton(this.send,!draft && queuedText !== undefined ? '排队发送' : running && this.head ? '追加到当前轮次' : '发送');
2185
2907
  this.stop.hidden = !running || archived;
2186
- this.stop.disabled = blocked || ['pending','unknown'].includes(op?.status);
2908
+ this.stop.disabled = blocked || op?.action === 'stop' && ['pending','unknown'].includes(op.status);
2187
2909
  this.renderPromptQueue();
2188
2910
  if (this.composerMirror && this.composerMirror.dataset.value !== this.input.value) this.composerMirror.dataset.value = this.input.value;
2189
2911
  this.renderDraftImages(task?.id);
@@ -2195,23 +2917,27 @@
2195
2917
  if (op.status === 'unknown') this.opNote.append(button('我已核实',() => this.setOperation(task.id,null),'session-quiet'));
2196
2918
  }
2197
2919
  }
2198
- submit(action) {
2199
- if (action === 'queue' && (this.newDraft || ![this.headStatus,this.task?.status].some(value => value === 'starting' || activeTurn(value)))) action = 'send';
2920
+ submit(action,forceQueue = false) {
2921
+ if (!this.csrf || this.selecting || this.disposed) return;
2922
+ const task = this.task?.id;
2923
+ if (action === 'stop') { if (task && !this.stop.disabled && !this.stop.hidden) void this.submitStop(task); return; }
2924
+ if (this.send.disabled) return;
2925
+ const queuedText = queueCommandText(this.input.value), text = queuedText ?? this.input.value;
2200
2926
  if (this.newDraft) {
2201
- if (action === 'send' && !this.send.disabled) void this.submitDraft(this.newDraft);
2927
+ void this.submitDraft(this.newDraft,text);
2202
2928
  return;
2203
2929
  }
2204
- const task = this.task?.id;
2205
- if (!task || !this.csrf || this.selecting) return;
2206
- if (action === 'stop') { if (!this.stop.disabled && !this.stop.hidden) void this.submitStop(task); return; }
2207
- if (this.send.disabled) return;
2930
+ if (!task) return;
2931
+ if (queuedText !== undefined) action = 'queue';
2932
+ else if (action === 'queue' && !forceQueue && !this.shouldQueuePrompt()) action = 'send';
2208
2933
  const request = uuid(), images = this.images(task);
2934
+ const position = action === 'queue' ? this.position() : {bottom:true};
2209
2935
  const turn = action === 'send' && activeTurn(this.headStatus) ? this.head : undefined;
2210
- const message = {payload:{task,request,text:annotationPrompt(this.input.value,images),...(turn ? {action:'steer',turn} : {action})},images};
2936
+ const message = {payload:{task,request,text:text.trim(),...(turn ? {action:'steer',turn} : {action})},images,startedAt:Date.now()};
2211
2937
  const messages = this.messages(task);
2212
2938
  messages.set(request,message); this.outboxes.set(task,messages);
2213
2939
  this.input.value = ''; this.setDraft(task,''); this.imageDrafts.delete(task); this.noticeImages('');
2214
- this.updateComposer(); this.pendingPosition = {bottom:true};
2940
+ this.updateComposer(); this.pendingPosition = position;
2215
2941
  void this.sendMessage(message); this.app.queuePersist();
2216
2942
  }
2217
2943
  restoreUnsentMessage(message) {
@@ -2224,30 +2950,33 @@
2224
2950
  this.input.value = text; this.setDraft(task,text); this.setChatError('');
2225
2951
  this.updateComposer(); this.updateOutbox(task); this.input.focus();
2226
2952
  }
2227
- async submitDraft(draft) {
2228
- const grant = this.csrf, images = this.images(draft.id), text = annotationPrompt(this.input.value,images);
2229
- draft.sending = true; this.updateDraftView(); this.setChatError('正在提交第一条消息…');
2953
+ async submitDraft(draft,prompt) {
2954
+ const grant = this.csrf, images = this.images(draft.id), text = prompt.trim();
2955
+ const message = {payload:{request:draft.request,action:'send',text},images,startedAt:Date.now()};
2956
+ const submission = draft.sending = {message,label:'正在创建任务'};
2957
+ this.setChatError(''); this.updateDraftView(); this.body.scrollTop = this.body.scrollHeight;
2230
2958
  try {
2231
2959
  const encoded = await encodeAttachments(images);
2232
2960
  if (this.csrf !== grant) return;
2233
- const result = await this.fetch('/tasks',{body:{request:draft.request,title:(draft.creationTitle ??= text.slice(0,200)),
2961
+ const result = await this.fetch('/tasks',{body:{request:draft.request,title:(draft.creationTitle ??= attachmentPrompt(text,images).slice(0,200)),
2234
2962
  agent:draft.agent,directory:draft.directory,model:draft.model,thinking:draft.thinking},timeout:60_000});
2235
2963
  await this.restoreDraftFiles(result.id);
2236
2964
  if (this.csrf !== grant) return;
2237
- const message = {payload:{task:result.id,request:draft.request,action:'send',text},images,encoded};
2965
+ message.payload.task = result.id; message.encoded = encoded;
2966
+ submission.label = '正在发送';
2967
+ if (this.newDraft === draft) this.updateDraftView();
2238
2968
  const messages = this.messages(result.id);
2239
2969
  messages.set(draft.request,message); this.outboxes.set(result.id,messages);
2240
2970
  this.imageDrafts.delete(draft.id);
2241
2971
  await this.persistDraftFiles(result.id,draft.id);
2242
2972
  const visible = this.newDraft === draft;
2243
- if (visible) this.leaveDraft(true);
2244
2973
  if (this.parkedDraft === draft) this.parkedDraft = undefined;
2245
2974
  this.saveNewTaskDraft();
2246
2975
  if (this.search) this.search.value = '';
2247
2976
  if (this.filter) for (const option of this.filter.options) option.selected = option.value === 'open';
2248
2977
  clearTimeout(this.searchTimer);
2249
2978
  void this.sendMessage(message); void this.loadGroups();
2250
- if (visible) void this.choose(result.id);
2979
+ if (visible) await this.choose(result.id,{sentDraft:draft});
2251
2980
  } catch (error) {
2252
2981
  if (this.newDraft === draft && this.csrf === grant) this.setChatError(error.message);
2253
2982
  else if (this.csrf === grant) this.listNote.textContent = error.message;
@@ -2282,18 +3011,17 @@
2282
3011
  }
2283
3012
  updateOutbox(task) {
2284
3013
  this.saveOutboxes();
2285
- if (this.task?.id === task) this.redraw();
3014
+ if (this.task?.id === task) { this.redraw(); this.renderPromptQueue(); }
2286
3015
  return this.persistDraftFiles(task);
2287
3016
  }
2288
3017
  failMessage(message,error) {
2289
3018
  message.error = error; this.updateOutbox(message.payload.task);
2290
3019
  }
2291
3020
  handleMessage(message,result) {
2292
- const {task,request} = message.payload;
3021
+ const {task} = message.payload;
2293
3022
  message.stale = result.status === 'stale';
2294
3023
  if (result.status === 'accepted') {
2295
- if (result.queued) this.removeMessage(task,request);
2296
- else { message.accepted = true; message.error = undefined; }
3024
+ message.accepted = true; message.queued = Boolean(result.queued); message.error = undefined;
2297
3025
  this.updateOutbox(task);
2298
3026
  if (this.task?.id === task && !this.connected) void this.refreshConversation(false);
2299
3027
  } else this.failMessage(message,result.status === 'pending' ? '暂未确认送达,点击重试。'
@@ -2330,13 +3058,15 @@
2330
3058
  }
2331
3059
  handleOperation(task,request,action,result) {
2332
3060
  if (this.operation(task)?.request !== request) return;
2333
- const message = result.status === 'accepted' ? '已请求停止此轮。'
3061
+ const sending = action === 'sendQueued';
3062
+ const message = result.status === 'accepted' ? (sending ? '排队消息已发送。' : '已请求停止此轮。')
2334
3063
  : result.status === 'pending' ? '服务端正在处理,可以稍后核实。'
2335
- : result.status === 'stale' ? '这一轮已结束,没有停止后续轮次。'
2336
- : result.status === 'unknown' ? `停止结果待核实。${result.message ? ' '+result.message : ''}`
3064
+ : result.status === 'stale' ? (sending ? '这条消息已离开队列。' : '这一轮已结束,没有停止后续轮次。')
3065
+ : result.status === 'unknown' ? `${sending ? '发送' : '停止'}结果待核实。${result.message ? ' '+result.message : ''}`
2337
3066
  : result.message || '未提交操作。';
2338
3067
  const notice = {request,action,status:result.status,message};
2339
3068
  this.setOperation(task,notice);
3069
+ if (sending && result.status === 'accepted' && this.task?.id === task) void this.refreshConversation(false);
2340
3070
  if (result.status === 'accepted') setTimeout(() => { if (!this.disposed && this.operations.get(task) === notice) this.setOperation(task,null); },6000);
2341
3071
  }
2342
3072
  async checkOperation(task, explicit) {