@keyou007/agent-bot 0.1.27-alpha.3 → 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 (159) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +102 -18
  3. package/README.zh.md +102 -18
  4. package/assets/agent-bot.ico +0 -0
  5. package/assets/roboto-mono-OFL.txt +93 -0
  6. package/assets/roboto-mono-latin.woff2 +0 -0
  7. package/assets/workspace-drafts.js +88 -0
  8. package/assets/workspace-sessions.js +2676 -243
  9. package/assets/workspace.css +553 -44
  10. package/assets/workspace.js +3429 -327
  11. package/dist/cli/SelfUpdateObserver.js +124 -0
  12. package/dist/cli/SelfUpdateObserver.js.map +1 -0
  13. package/dist/cli/SelfUpdateRunner.js +267 -70
  14. package/dist/cli/SelfUpdateRunner.js.map +1 -1
  15. package/dist/cli/SelfUpdater.js +54 -15
  16. package/dist/cli/SelfUpdater.js.map +1 -1
  17. package/dist/cli/controlProtocol.js.map +1 -1
  18. package/dist/cli/help.js +6 -0
  19. package/dist/cli/help.js.map +1 -1
  20. package/dist/cli.js +85 -6
  21. package/dist/cli.js.map +1 -1
  22. package/dist/codex/CodexEventMapper.js +29 -5
  23. package/dist/codex/CodexEventMapper.js.map +1 -1
  24. package/dist/codex/CodexRuntime.js +3 -0
  25. package/dist/codex/CodexRuntime.js.map +1 -1
  26. package/dist/feishu/CardRenderer.js +45 -13
  27. package/dist/feishu/CardRenderer.js.map +1 -1
  28. package/dist/feishu/ConsoleFeishuClient.js +4 -0
  29. package/dist/feishu/ConsoleFeishuClient.js.map +1 -1
  30. package/dist/feishu/FeishuMarkdown.js +2 -14
  31. package/dist/feishu/FeishuMarkdown.js.map +1 -1
  32. package/dist/feishu/FeishuMessageClient.js +9 -0
  33. package/dist/feishu/FeishuMessageClient.js.map +1 -1
  34. package/dist/feishu/FeishuTurnPresenter.js +51 -22
  35. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  36. package/dist/index.js +47 -12
  37. package/dist/index.js.map +1 -1
  38. package/dist/local-files/DiagramPreview.js +11 -6
  39. package/dist/local-files/DiagramPreview.js.map +1 -1
  40. package/dist/local-files/GitDiffPreview.js +106 -14
  41. package/dist/local-files/GitDiffPreview.js.map +1 -1
  42. package/dist/local-files/LiveMarkup.js +104 -0
  43. package/dist/local-files/LiveMarkup.js.map +1 -0
  44. package/dist/local-files/LocalFileViewerServer.js +141 -122
  45. package/dist/local-files/LocalFileViewerServer.js.map +1 -1
  46. package/dist/local-files/MarkdownExport.js +54 -0
  47. package/dist/local-files/MarkdownExport.js.map +1 -0
  48. package/dist/local-files/PreviewCodeFont.js +11 -0
  49. package/dist/local-files/PreviewCodeFont.js.map +1 -0
  50. package/dist/local-files/PreviewSyntaxHighlight.js +73 -0
  51. package/dist/local-files/PreviewSyntaxHighlight.js.map +1 -1
  52. package/dist/local-files/ToolCommandDisplay.js +111 -0
  53. package/dist/local-files/ToolCommandDisplay.js.map +1 -0
  54. package/dist/local-files/TurnPreviewPage.js +53 -276
  55. package/dist/local-files/TurnPreviewPage.js.map +1 -1
  56. package/dist/local-files/WorkspaceFileEvents.js +206 -0
  57. package/dist/local-files/WorkspaceFileEvents.js.map +1 -0
  58. package/dist/local-files/WorkspaceFiles.js +79 -3
  59. package/dist/local-files/WorkspaceFiles.js.map +1 -1
  60. package/dist/local-files/WorkspaceImages.js +43 -0
  61. package/dist/local-files/WorkspaceImages.js.map +1 -0
  62. package/dist/local-files/WorkspacePage.js +24 -6
  63. package/dist/local-files/WorkspacePage.js.map +1 -1
  64. package/dist/local-files/WorkspaceSessions.js +1153 -104
  65. package/dist/local-files/WorkspaceSessions.js.map +1 -1
  66. package/dist/local-files/WorkspaceTimeline.js +129 -0
  67. package/dist/local-files/WorkspaceTimeline.js.map +1 -0
  68. package/dist/presentation/OutboundRouter.js +15 -6
  69. package/dist/presentation/OutboundRouter.js.map +1 -1
  70. package/dist/presentation/TurnStateReducer.js +31 -22
  71. package/dist/presentation/TurnStateReducer.js.map +1 -1
  72. package/dist/proxy/ProxySessionController.js +335 -113
  73. package/dist/proxy/ProxySessionController.js.map +1 -1
  74. package/dist/proxy/TaskMetadata.js +86 -0
  75. package/dist/proxy/TaskMetadata.js.map +1 -0
  76. package/dist/scheduling/ScheduleCards.js +10 -4
  77. package/dist/scheduling/ScheduleCards.js.map +1 -1
  78. package/dist/scheduling/ScheduleCommand.js +4 -0
  79. package/dist/scheduling/ScheduleCommand.js.map +1 -1
  80. package/dist/scheduling/ScheduledTaskStore.js +53 -12
  81. package/dist/scheduling/ScheduledTaskStore.js.map +1 -1
  82. package/dist/scheduling/types.js +19 -4
  83. package/dist/scheduling/types.js.map +1 -1
  84. package/dist/state/StateStore.js +213 -23
  85. package/dist/state/StateStore.js.map +1 -1
  86. package/dist/state/TurnPreviewJournal.js +157 -39
  87. package/dist/state/TurnPreviewJournal.js.map +1 -1
  88. package/dist/state/TurnToolText.js +172 -0
  89. package/dist/state/TurnToolText.js.map +1 -0
  90. package/dist/state/migrations.js +4 -0
  91. package/dist/state/migrations.js.map +1 -1
  92. package/dist/supervision/SafeRestartNotifier.js +9 -6
  93. package/dist/supervision/SafeRestartNotifier.js.map +1 -1
  94. package/dist/terminal/TerminalPage.js +5 -0
  95. package/dist/terminal/TerminalPage.js.map +1 -1
  96. package/dist/updates/AutomaticUpdatePreparer.js +63 -12
  97. package/dist/updates/AutomaticUpdatePreparer.js.map +1 -1
  98. package/dist/updates/ManualUpdateController.js +7 -2
  99. package/dist/updates/ManualUpdateController.js.map +1 -1
  100. package/dist/utils/promptAttachments.js +22 -0
  101. package/dist/utils/promptAttachments.js.map +1 -0
  102. package/dist/utils/promptQuotes.js +47 -0
  103. package/dist/utils/promptQuotes.js.map +1 -0
  104. package/dist/utils/toolTimestamp.js +6 -0
  105. package/dist/utils/toolTimestamp.js.map +1 -0
  106. package/npm-shrinkwrap.json +2 -2
  107. package/package.json +1 -1
  108. package/skills/agent-bot/SKILL.md +23 -2
  109. package/src/cli/SelfUpdateObserver.ts +111 -0
  110. package/src/cli/SelfUpdateRunner.ts +271 -85
  111. package/src/cli/SelfUpdater.ts +53 -16
  112. package/src/cli/controlProtocol.ts +1 -0
  113. package/src/cli/help.ts +6 -0
  114. package/src/cli.ts +71 -5
  115. package/src/codex/CodexEventMapper.ts +25 -5
  116. package/src/codex/CodexRuntime.ts +4 -0
  117. package/src/feishu/CardRenderer.ts +48 -13
  118. package/src/feishu/ConsoleFeishuClient.ts +6 -1
  119. package/src/feishu/FeishuMarkdown.ts +2 -14
  120. package/src/feishu/FeishuMessageClient.ts +10 -0
  121. package/src/feishu/FeishuTurnPresenter.ts +49 -16
  122. package/src/feishu/types.ts +1 -0
  123. package/src/index.ts +47 -12
  124. package/src/local-files/DiagramPreview.ts +11 -6
  125. package/src/local-files/GitDiffPreview.ts +107 -15
  126. package/src/local-files/LiveMarkup.ts +103 -0
  127. package/src/local-files/LocalFileViewerServer.ts +128 -125
  128. package/src/local-files/MarkdownExport.ts +54 -0
  129. package/src/local-files/PreviewCodeFont.ts +12 -0
  130. package/src/local-files/PreviewSyntaxHighlight.ts +75 -0
  131. package/src/local-files/ToolCommandDisplay.ts +104 -0
  132. package/src/local-files/TurnPreviewPage.ts +58 -261
  133. package/src/local-files/WorkspaceFileEvents.ts +186 -0
  134. package/src/local-files/WorkspaceFiles.ts +72 -5
  135. package/src/local-files/WorkspaceImages.ts +35 -0
  136. package/src/local-files/WorkspacePage.ts +24 -6
  137. package/src/local-files/WorkspaceSessions.ts +1057 -111
  138. package/src/local-files/WorkspaceTimeline.ts +135 -0
  139. package/src/presentation/OutboundRouter.ts +18 -4
  140. package/src/presentation/TurnStateReducer.ts +30 -19
  141. package/src/presentation/turnViewTypes.ts +3 -1
  142. package/src/proxy/ProxySessionController.ts +336 -96
  143. package/src/proxy/TaskMetadata.ts +81 -0
  144. package/src/runtime/types.ts +2 -1
  145. package/src/scheduling/ScheduleCards.ts +10 -4
  146. package/src/scheduling/ScheduleCommand.ts +4 -0
  147. package/src/scheduling/ScheduledTaskStore.ts +56 -9
  148. package/src/scheduling/types.ts +27 -4
  149. package/src/state/StateStore.ts +227 -24
  150. package/src/state/TurnPreviewJournal.ts +155 -38
  151. package/src/state/TurnToolText.ts +156 -0
  152. package/src/state/migrations.ts +4 -0
  153. package/src/supervision/SafeRestartNotifier.ts +9 -6
  154. package/src/terminal/TerminalPage.ts +5 -0
  155. package/src/updates/AutomaticUpdatePreparer.ts +52 -11
  156. package/src/updates/ManualUpdateController.ts +8 -3
  157. package/src/utils/promptAttachments.ts +27 -0
  158. package/src/utils/promptQuotes.ts +48 -0
  159. package/src/utils/toolTimestamp.ts +5 -0
@@ -8,11 +8,226 @@
8
8
  const button = (text, handler, className) => {
9
9
  const node = make('button',className,text); node.type = 'button'; node.onclick = handler; return node;
10
10
  };
11
+ const plainLinkClick = event => event.button === 0 && !event.ctrlKey && !event.metaKey && !event.shiftKey && !event.altKey;
12
+ const headerNumbers = new Intl.NumberFormat('zh-CN');
13
+ const headerTokens = new Intl.NumberFormat('en',{notation:'compact',maximumFractionDigits:1});
14
+ const localDateTime = (date,timeZone) => new Intl.DateTimeFormat('sv-SE',{
15
+ timeZone,year:'numeric',month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',hourCycle:'h23',
16
+ }).format(date).replace(' ','T');
17
+ const scheduleDate = (value,timeZone) => {
18
+ const nominal = Date.parse(value+'Z');
19
+ let time = nominal;
20
+ for (let attempt = 0; attempt < 3 && Number.isFinite(time); attempt++) {
21
+ const formatted = localDateTime(time,timeZone);
22
+ if (formatted === value) return new Date(time);
23
+ time += nominal-Date.parse(formatted+'Z');
24
+ }
25
+ throw new Error('该时区中没有这个日期或时间。');
26
+ };
27
+ const scheduleStatuses = {draft:'草稿',enabled:'已启用',paused:'已暂停',completed:'已完成',deleted:'已删除'};
28
+ const scheduleFrequency = cron => {
29
+ if (!cron) return '仅一次';
30
+ const [minute,hour,day,month,week] = cron.split(/\s+/u);
31
+ if (/^\d+$/u.test(minute) && hour === '*' && day === '*' && month === '*' && week === '*') return '每小时';
32
+ if (!/^\d+$/u.test(minute) || !/^\d+$/u.test(hour)) return cron;
33
+ if (/^\d+$/u.test(day) && /^\d+$/u.test(month) && week === '*') return '每年';
34
+ if (month !== '*') return cron;
35
+ if (day === '*' && week === '*') return '每天';
36
+ if (day === '*' && week === '1-5') return '工作日';
37
+ if (day === '*' && /^[0-6]$/u.test(week)) return '每周';
38
+ if (/^\d+$/u.test(day) && week === '*') return '每月';
39
+ return cron;
40
+ };
41
+ const scheduleOptions = [['once','仅一次'],['hourly','每小时'],['daily','每天'],['weekdays','工作日'],
42
+ ['weekly','每周'],['monthly','每月'],['yearly','每年'],['cron','自定义 Cron']];
43
+ const scheduleRunStatuses = {queued:'排队中',dispatching:'准备中',submitting:'提交中',running:'运行中',completed:'已完成',
44
+ failed:'失败',cancelled:'已取消',expired:'已过期',skipped:'已跳过',unknown:'待核实'};
45
+ const labelButton = (node,label) => { if (node.getAttribute('aria-label') !== label) node.setAttribute('aria-label',label); };
46
+ const setText = (node,text) => { if (node.textContent !== text) node.textContent = text; };
47
+ const iconButton = (label,path,className,handler) => {
48
+ const node = button('',handler,className);
49
+ labelButton(node,label);
50
+ node.innerHTML = '<svg class="workspace-icon" aria-hidden="true" focusable="false" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="'+path+'"/></svg>';
51
+ return node;
52
+ };
53
+ const noImages = [];
54
+ const imageTypes = ['image/png','image/jpeg','image/gif','image/webp'];
55
+ const imageTypesByExtension = {png:'image/png',jpg:'image/jpeg',jpeg:'image/jpeg',gif:'image/gif',webp:'image/webp'};
56
+ const imageLimit = 5 * 1024 * 1024, draftLimit = 12 * 1024 * 1024, imageCount = 4;
57
+ const chatImageSizeLimit = 256;
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
+ };
91
+ const clipboardFiles = clipboard => {
92
+ const files = Array.from(clipboard?.files ?? []);
93
+ if (files.length) return files;
94
+ return Array.from(clipboard?.items ?? []).filter(item=>item.kind === 'file')
95
+ .map(item=>item.getAsFile()).filter(Boolean);
96
+ };
97
+ const previewImageType = file => {
98
+ if (imageTypes.includes(file.type)) return file.type;
99
+ if (file.type && file.type !== 'application/octet-stream') return;
100
+ const extension = /\.(png|jpe?g|gif|webp)$/iu.exec(file.name)?.[1].toLowerCase();
101
+ return imageTypesByExtension[extension];
102
+ };
103
+ const readAttachment = file => new Promise((resolve,reject) => {
104
+ const reader = new FileReader();
105
+ reader.onload = () => resolve(String(reader.result).split(',',2)[1]);
106
+ reader.onerror = reader.onabort = () => reject(new Error('无法读取附件,请移除后重新添加。'));
107
+ reader.readAsDataURL(file);
108
+ });
109
+ const effortLabel = value => ({none:'无',minimal:'极低',low:'低',medium:'中',high:'高',xhigh:'极高',max:'最高'})[value] ?? value;
110
+ const revokeAttachment = attachment => { if (attachment.src) URL.revokeObjectURL(attachment.src); };
111
+ const draftAttachment = (file,metadata) => {
112
+ const type = file.size && previewImageType(file);
113
+ const preview = type ? (file.type === type ? file : file.slice(0,file.size,type)) : undefined;
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])];
121
+ };
122
+ const annotationLocation = item => [item.line && `第 ${item.line} 行`,item.originalLine && `变更前第 ${item.originalLine} 行`].filter(Boolean).join(' · ');
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;
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);
153
+ const encodeAttachments = async attachments => {
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)})));
157
+ const images = entries.filter(({attachment})=>attachment.src).map(({data})=>data);
158
+ const files = entries.filter(({attachment})=>!attachment.src).map(({attachment,data})=>({name:attachment.file.name?.slice(0,255) || 'file',data}));
159
+ return {...(images.length?{images}:{}),...(files.length?{files}:{}),...(quotes.length?{quotes}:{})};
160
+ };
161
+ const timeTool = tool => {
162
+ const start = tool.startedAt, end = tool.completedAt;
163
+ if (!start) return '';
164
+ const format = ms => ms < 1000 ? `${Math.round(ms)} 毫秒` : ms < 60_000 ? `${Number((ms/1000).toFixed(1))} 秒` : `${Math.floor(ms/60_000)} 分 ${Math.floor(ms/1000)%60} 秒`;
165
+ const clock = {hour:'2-digit',minute:'2-digit',second:'2-digit',hour12:false};
166
+ const startText = new Date(start).toLocaleTimeString('zh-CN',clock);
167
+ const elapsed = end && end >= start ? `耗时 ${format(end-start)}` : '';
168
+ return elapsed ? `开始 ${startText} · ${elapsed}` : `开始 ${startText}`;
169
+ };
170
+ const executionClock = seconds => {
171
+ const hours = Math.floor(seconds/3600);
172
+ const parts = [Math.floor(seconds/60)%60,seconds%60];
173
+ if (hours) parts.unshift(hours);
174
+ return parts.map(part=>String(part).padStart(2,'0')).join(':');
175
+ };
11
176
  const labels = {ready:'空闲',starting:'启动中',running:'执行中',tool_running:'执行中',waiting_for_approval:'等待确认',completed:'已完成',failed:'失败',cancelled:'已停止',unknown:'待核实',closed:'已归档'};
12
177
  const status = value => labels[value] || '空闲';
178
+ const taskProgress = {starting:'启动中',running:'正在执行',tool_running:'正在执行',waiting_for_approval:'等待确认'};
179
+ const taskClock = new Intl.DateTimeFormat('zh-CN',{hour:'2-digit',minute:'2-digit',hourCycle:'h23'});
180
+ const taskDate = new Intl.DateTimeFormat('zh-CN',{month:'long',day:'numeric'});
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
+ };
189
+ const taskDateLabel = (date, today = new Date()) => {
190
+ if (date.toDateString() === today.toDateString()) return taskClock.format(date);
191
+ const yesterday = new Date(today);
192
+ yesterday.setDate(yesterday.getDate()-1);
193
+ if (date.toDateString() === yesterday.toDateString()) return '昨天';
194
+ return (date.getFullYear() === today.getFullYear() ? taskDate : taskFullDate).format(date);
195
+ };
196
+ const syncRows = (container, before, rows) => {
197
+ const retained = new Set(rows.values());
198
+ for (const row of before.values()) if (!retained.has(row) && row.node.parentNode === container) row.node.remove();
199
+ let next = container.firstChild;
200
+ for (const {node} of rows.values()) {
201
+ if (node !== next) container.insertBefore(node,next);
202
+ next = node.nextSibling;
203
+ }
204
+ };
205
+ const keepOpenGroups = (previous, rows, visibleTools) => {
206
+ if (!visibleTools) return rows;
207
+ const current = new Map([...rows].map(([key,row]) => [row,key])), held = new Map();
208
+ let after = rows.has('prompt') ? 'prompt' : undefined;
209
+ for (const [key,row] of previous) {
210
+ if (current.has(row)) after = current.get(row);
211
+ else if (row.rows && row.node.open && ![...row.rows.keys()].some(id => visibleTools.has(id))) {
212
+ const earlier = held.get(after) || [];
213
+ earlier.push([key,row]); held.set(after,earlier);
214
+ }
215
+ }
216
+ if (!held.size) return rows;
217
+ const merged = new Map(held.get(undefined));
218
+ for (const [key,row] of rows) {
219
+ merged.set(key,row);
220
+ for (const [heldKey,heldRow] of held.get(key) || []) merged.set(heldKey,heldRow);
221
+ }
222
+ return merged;
223
+ };
13
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);
14
227
  const read = (key,fallback,storage = 'localStorage') => { try { return JSON.parse(window[storage]?.getItem(key)) ?? fallback; } catch { return fallback; } };
15
- const save = (key,value,storage = 'localStorage') => { try { window[storage]?.setItem(key,JSON.stringify(value)); } catch {} };
228
+ const save = (key,value,storage = 'localStorage') => {
229
+ try { window[storage].setItem(key,JSON.stringify(value)); return true; } catch { return false; }
230
+ };
16
231
  const uuid = () => {
17
232
  const bytes = crypto.getRandomValues(new Uint8Array(16)); bytes[6] = bytes[6]&15|64; bytes[8] = bytes[8]&63|128;
18
233
  return Array.from(bytes,(byte,index) => ([4,6,8,10].includes(index)?'-':'')+byte.toString(16).padStart(2,'0')).join('');
@@ -24,7 +239,26 @@
24
239
  this.page = uuid(); this.generation = this.connectionEpoch = 0;
25
240
  const groups = read('agentbot-workspace-groups',[]);
26
241
  this.openGroups = new Set(Array.isArray(groups) ? groups.filter(item => typeof item === 'string') : []); this.projects = new Map();
27
- this.drafts = new Map(); this.operations = new Map(); this.heading = make('h2','pane-heading','任务');
242
+ this.drafts = new Map(); this.imageDrafts = new Map(); this.operations = new Map(); this.pendingSettings = new Set(); this.heading = make('h2','pane-heading','任务');
243
+ this.draftFiles = new window.AgentBotWorkspaceDraftFiles(base,uuid);
244
+ this.fileRecords = new Set(); this.fileLoads = new Map(); this.loadingDraftFiles = new Set();
245
+ this.chatImageSizeKey = 'agentbot-workspace-chat-image-sizes:'+base;
246
+ const imageSizes = read(this.chatImageSizeKey,[],'sessionStorage');
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);
251
+ this.newDraftKey = 'agentbot-workspace-new-draft:'+base;
252
+ const savedDraft = read(this.newDraftKey,null,'sessionStorage');
253
+ if (typeof savedDraft?.draft?.id === 'string') {
254
+ this.parkedDraft = savedDraft.draft; this.resumeNewDraft = savedDraft.active === true;
255
+ this.newDraftSaved = true;
256
+ }
257
+ this.pendingTurnActions = new Set();
258
+ this.sendingFromQueue = new Map();
259
+ const outbox = read('agentbot-workspace-outbox',[],'sessionStorage');
260
+ this.outboxes = new Map((Array.isArray(outbox) ? outbox : []).map(([task,items]) => [task,
261
+ new Map(items.map(([id,payload,error,startedAt]) => [id,{payload,error,startedAt,images:noImages,restored:true}]))]));
28
262
  this.left.classList.add('session-task-pane'); this.chat.classList.add('session-chat-pane');
29
263
  this.locked('正在检查工作台会话…'); void this.session();
30
264
  this.offline = () => { if (this.csrf) { this.connected = false; this.app.updateSessionStatus(false,'网络已断开'); } };
@@ -34,17 +268,19 @@
34
268
  async fetch(route, options = {}) {
35
269
  const {params,body,signal} = options, url = new URL(this.base+route,window.location.href);
36
270
  for (const [name,value] of Object.entries(params || {})) if (value !== undefined) url.searchParams.set(name,value);
37
- const controller = new AbortController(), timeout = setTimeout(() => controller.abort(), 15_000);
271
+ const controller = new AbortController(), timeout = setTimeout(() => controller.abort(), options.timeout ?? (body?.images?.length || body?.files?.length ? 60_000 : 15_000));
38
272
  const abort = () => controller.abort(); if (signal?.aborted) abort(); else signal?.addEventListener('abort',abort,{once:true});
39
273
  try {
40
274
  const response = await fetch(url,{cache:'no-store',credentials:'same-origin',signal:controller.signal,
41
275
  ...(body === undefined ? {} : {method:'POST',headers:{'content-type':'application/json','x-workspace-csrf':this.csrf || ''},body:JSON.stringify(body)})});
276
+ const reloading = (route === '/session' || response.status === 401)
277
+ && this.app.reloadWorkspaceIfUpdated(response.headers?.get('X-AgentBot-Workspace-Revision'),response.headers?.get('X-AgentBot-Workspace-Instance'));
42
278
  const data = await response.json();
43
279
  if (!response.ok) {
44
- if (response.status === 401 && route !== '/login' && this.csrf) this.expire();
280
+ if (response.status === 401 && route !== '/login' && this.csrf && !reloading) this.expire();
45
281
  throw Object.assign(new Error(data.error || `请求失败(HTTP ${response.status})`),{status:response.status});
46
282
  }
47
- return data;
283
+ return reloading ? {...data,reloading:true} : data;
48
284
  } finally { clearTimeout(timeout); signal?.removeEventListener('abort',abort); }
49
285
  }
50
286
  session(autoLogin = true, note) {
@@ -52,7 +288,7 @@
52
288
  }
53
289
  async checkSession(autoLogin, note) {
54
290
  try {
55
- const data = await this.fetch('/session'); if (this.disposed) return;
291
+ const data = await this.fetch('/session'); if (this.disposed || data.reloading) return;
56
292
  if (data.csrf) this.unlock(data.csrf);
57
293
  else if (data.auth === 'automatic' && autoLogin) {
58
294
  const login = await this.fetch('/login',{body:{}});
@@ -73,7 +309,13 @@
73
309
  this.left.querySelector('.session-login input,.session-primary')?.focus({preventScroll:true});
74
310
  }
75
311
  locked(message, mode, hint) {
76
- this.timelineObserver?.disconnect();
312
+ this.timelineObserver?.disconnect(); this.closeSettingsMenu();
313
+ this.scheduleDialog?.close();
314
+ if (this.loggingOut) {
315
+ this.resetImageDrafts(); this.resetOutboxes(); this.saveOutboxes();
316
+ this.draftFiles.clear(); this.fileRecords.clear(); this.fileLoads.clear(); this.loadingDraftFiles.clear();
317
+ }
318
+ this.clearImageInteractions();
77
319
  const box = make('div','session-empty'); box.append(make('strong',null,message));
78
320
  if (hint) box.append(make('p',null,hint));
79
321
  this.left.replaceChildren(this.heading,box);
@@ -106,13 +348,27 @@
106
348
  const afterLogin = this.afterLogin; this.afterLogin = undefined; afterLogin?.();
107
349
  void this.loadGroups();
108
350
  const href = window.location.href, task = this.app.taskFromUrl(href);
109
- if (task) void this.choose(task,{initial:true,href});
351
+ const selection = task ? this.choose(task,{initial:true,href}) : undefined;
352
+ if (this.resumeNewDraft) {
353
+ this.resumeNewDraft = false;
354
+ void Promise.resolve(selection).then(() => {
355
+ if (!this.disposed && this.csrf === csrf && this.parkedDraft) this.openNewTask();
356
+ });
357
+ }
110
358
  }
111
359
  expire() {
112
360
  if (!this.csrf) return;
361
+ this.app.annotations?.cancel();
113
362
  this.csrf = undefined; this.stream?.close(); clearTimeout(this.watchdog); this.connected = false;
114
- this.selection?.abort(); this.groupRequest?.abort(); this.generation++;
115
- this.app.releaseSessionPanels(); this.task = undefined; this.projects.clear();
363
+ clearTimeout(this.executionTimer); this.executionTimer = undefined; this.updateHead();
364
+ if (!this.loggingOut) {
365
+ if (this.newDraft) { this.parkedDraft = this.newDraft; this.newDraft = undefined; this.resumeNewDraft = true; }
366
+ } else {
367
+ this.newDraft = this.parkedDraft = undefined; this.resumeNewDraft = false;
368
+ }
369
+ this.saveNewTaskDraft();
370
+ this.selection?.abort(); this.groupRequest?.abort(); this.resetNewer(); this.generation++;
371
+ this.app.releaseSessionPanels(); this.task = undefined; this.headPlan = []; this.projects.clear();
116
372
  this.selecting = false; this.refreshing = undefined; this.app.dataset.taskPending = 'false';
117
373
  this.locked('正在检查工作台会话…');
118
374
  this.app.updateSessionStatus(false,'未登录');
@@ -122,17 +378,25 @@
122
378
  this.selection?.abort(); this.generation++; this.selecting = false; this.target = this.task?.id;
123
379
  this.app.dataset.taskPending = 'false'; this.setChatError(''); this.updateComposer();
124
380
  if (this.connected && this.task) void this.refreshConversation(true);
381
+ else void this.loadNewer();
125
382
  }
126
383
  clearTask() {
127
- this.selection?.abort(); this.generation++; this.target = undefined; this.selecting = false; this.refreshing = undefined;
128
- this.app.dataset.taskPending = 'false'; this.task = this.head = undefined; this.turns = [];
129
- this.lastPosition = this.pendingPosition = undefined;
384
+ this.app.annotations?.cancel();
385
+ this.leaveDraft();
386
+ this.selection?.abort(); this.resetNewer(); this.generation++; this.target = undefined; this.selecting = false; this.refreshing = undefined;
387
+ this.app.dataset.taskPending = 'false'; this.task = undefined; this.updateHead(); this.turns = []; this.headPlan = [];
388
+ this.lastPosition = this.pendingPosition = this.restoredPosition = undefined;
130
389
  this.renderChat(); this.updateSelected();
131
390
  if (this.connected) void this.fetch('/focus',{body:{page:this.page,generation:this.generation}}).catch(() => {});
132
391
  }
133
392
  dispose() {
134
- this.timelineObserver?.disconnect();
135
- this.disposed = true; this.stream?.close(); this.selection?.abort(); this.groupRequest?.abort(); clearTimeout(this.searchTimer); clearTimeout(this.watchdog);
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);
396
+ this.scheduleDialog?.close();
397
+ this.draftFiles.dispose();
398
+ this.disposed = true; this.stream?.close(); this.selection?.abort(); this.groupRequest?.abort(); this.resetNewer(); clearTimeout(this.searchTimer); clearTimeout(this.watchdog);
399
+ clearTimeout(this.executionTimer);
136
400
  window.removeEventListener('offline',this.offline); window.removeEventListener('online',this.online);
137
401
  }
138
402
  connect() {
@@ -143,11 +407,20 @@
143
407
  if (this.stream !== stream || !this.csrf) return;
144
408
  clearTimeout(this.watchdog);
145
409
  this.watchdog = setTimeout(() => { this.app.updateSessionStatus(false,'正在重连'); this.connect(); },36_000);
410
+ const today = new Date(), day = today.toDateString();
411
+ if (day !== this.taskDatesDay) {
412
+ this.taskDatesDay = day;
413
+ for (const time of this.groupList.querySelectorAll('.session-task-time')) time.textContent = taskDateLabel(new Date(time.getAttribute('datetime')),today);
414
+ }
146
415
  };
147
416
  watch(); stream.addEventListener('heartbeat',watch);
148
- stream.addEventListener('sync',() => {
149
- watch();
417
+ stream.addEventListener('sync',event => {
150
418
  if (this.stream !== stream) return;
419
+ try {
420
+ const version = JSON.parse(event.data);
421
+ if (this.app.reloadWorkspaceIfUpdated(version?.revision,version?.instance)) return;
422
+ } catch { /* Older servers may omit restart metadata. */ }
423
+ watch();
151
424
  const wasConnected = this.everConnected; this.connected = this.everConnected = true; this.connectionEpoch++;
152
425
  this.app.updateSessionStatus(true,'实时连接');
153
426
  if (!this.selecting && this.task) void this.refreshConversation(true);
@@ -160,16 +433,23 @@
160
433
  try {
161
434
  const data = {...JSON.parse(event.data), version:Number(event.lastEventId), epoch:this.connectionEpoch};
162
435
  if (data.taskId !== this.target || data.generation !== this.generation) return;
163
- if (this.selecting || this.refreshing) this.bufferedTail = data;
164
- 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);
165
443
  } catch { this.setChatError('实时更新无法读取,请刷新对话。',true); }
166
444
  });
167
445
  stream.onerror = () => {
168
446
  if (this.stream !== stream || !this.csrf) return;
169
447
  this.connected = false; this.app.updateSessionStatus(false,'正在重连');
448
+ this.app.scheduleWorkspaceVersionCheck(2000);
170
449
  if (!this.probing) {
171
450
  this.probing = true;
172
- void this.fetch('/session').then(data => { if (!data.csrf) this.expire(); }).catch(() => {}).finally(() => { this.probing = false; });
451
+ void this.fetch('/session').then(data => { if (this.stream === stream && !data.reloading && !data.csrf) this.expire(); })
452
+ .catch(() => {}).finally(() => { this.probing = false; });
173
453
  }
174
454
  };
175
455
  }
@@ -181,7 +461,9 @@
181
461
  catch (error) { if (this.csrf) this.listNote.textContent = error.message; }
182
462
  finally { logout.disabled = false; this.loggingOut = false; }
183
463
  },'session-quiet'); logout.setAttribute('aria-label','退出工作台');
184
- bar.append(heading,logout);
464
+ const actions = make('div','session-task-actions');
465
+ const create = button('新建任务',() => this.openNewTask(),'session-new-task');
466
+ actions.append(create,logout); bar.append(heading,actions);
185
467
  const controls = make('div','session-task-controls'), field = this.search = make('input');
186
468
  field.type = 'search'; field.placeholder = '搜索任务或项目'; field.setAttribute('aria-label','搜索任务或项目'); field.maxLength = 160;
187
469
  const filter = this.filter = make('select'); filter.setAttribute('aria-label','任务筛选');
@@ -193,9 +475,356 @@
193
475
  filter.onchange = () => { clearTimeout(this.searchTimer); void this.loadGroups(); };
194
476
  controls.append(field,filter); this.left.replaceChildren(bar,controls,this.listNote,this.groupList);
195
477
  }
478
+ createDialog(caption,parent) {
479
+ const dialog = make('dialog','session-form-dialog'), header = make('header');
480
+ const title = make('h2',null,caption); title.id = 'session-dialog-'+uuid();
481
+ const close = iconButton('关闭','M6 6l12 12M18 6 6 18','session-dialog-close',() => dialog.close());
482
+ dialog.setAttribute('aria-labelledby',title.id); header.append(title,close); dialog.append(header);
483
+ dialog.onclick = event => { if (event.target === dialog) dialog.close(); };
484
+ parent.append(dialog); return dialog;
485
+ }
486
+ dialogField(form,name,field) {
487
+ const label = make('label','session-dialog-field'); label.append(make('span',null,name),field); form.append(label);
488
+ }
489
+ annotationTask() { return this.csrf && !this.input?.disabled ? this.newDraft?.id ?? this.task?.id : undefined; }
490
+ addAnnotation(item,task) {
491
+ if (!task || task !== this.annotationTask()) return '当前任务已切换或无法输入消息。';
492
+ if (!validAnnotationNote(item?.note) || typeof item.quote !== 'string' || !item.quote.trim()) return '批注内容无效。';
493
+ if (item.quote.length > 100_000) 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});
550
+ }
551
+ openSchedule() {
552
+ if (!this.task || this.newDraft || this.selecting || this.scheduleDialog?.open) return;
553
+ const task = this.task.id, grant = this.csrf, editor = this.input, original = editor.value, attachments = this.images(task);
554
+ const prompt = attachmentPrompt(original,attachments);
555
+ const dialog = this.scheduleDialog = this.createDialog('定时任务',this.chat);
556
+ dialog.classList.add('session-schedule-dialog');
557
+ const current = () => dialog.open && this.task?.id === task && this.csrf === grant;
558
+ dialog.onclose = () => dialog.remove();
559
+ const history = make('div','session-schedule-history'); history.setAttribute('aria-label','本会话的定时任务');
560
+ const feedback = make('p','session-schedule-feedback'); feedback.setAttribute('role','status');
561
+ const area = make('div'); dialog.append(area,history,feedback);
562
+ let offset = 0, version = 0;
563
+ const load = async (more = false) => {
564
+ const loading = ++version;
565
+ if (!more) { offset = 0; history.replaceChildren(make('p','session-muted','正在读取定时任务…')); }
566
+ try {
567
+ const data = await this.fetch('/schedules',{params:{task,offset}});
568
+ if (!current() || version !== loading) return;
569
+ if (!more) history.replaceChildren();
570
+ for (const job of data.jobs) history.append(this.scheduleRow(job,current,edit,async (action,revision) => {
571
+ await this.fetch('/schedules/action',{body:{task,job:job.id,revision,action},timeout:60_000});
572
+ if (current()) { feedback.textContent = '定时任务已更新。'; void load(); }
573
+ }));
574
+ offset += data.jobs.length;
575
+ if (!offset) history.append(make('p','session-muted','暂无定时任务。'));
576
+ if (data.more) {
577
+ const next = button('更多',() => { next.remove(); void load(true); },'session-more'); history.append(next);
578
+ }
579
+ } catch (error) { if (current() && version === loading) history.replaceChildren(make('p','session-error',error.message),button('重试',() => void load(),'session-more')); }
580
+ };
581
+ let usedDraft = false;
582
+ const edit = job => {
583
+ feedback.textContent = '';
584
+ if (!job && (usedDraft || !(prompt || attachments.length))) {
585
+ area.replaceChildren(make('p','session-schedule-feedback','在聊天框输入消息或添加附件后可创建定时任务。')); return;
586
+ }
587
+ area.replaceChildren(this.scheduleForm(job,prompt,attachments,current,async (schedule,request) => {
588
+ if (job) {
589
+ await this.fetch('/schedules/action',{body:{task,job:job.id,revision:job.revision,action:'edit',schedule}});
590
+ } else {
591
+ const encoded = await encodeAttachments(attachments);
592
+ if (!current()) return;
593
+ await this.fetch('/schedules',{body:{task,request,schedule,...encoded}});
594
+ usedDraft = true;
595
+ if (this.task?.id === task && this.csrf === grant && this.images(task) === attachments && editor === this.input && editor.value === original) {
596
+ editor.value = ''; this.setDraft(task,''); this.replaceImages(task,[]); this.updateComposer();
597
+ }
598
+ }
599
+ if (current()) { edit(); feedback.textContent = job ? '定时任务已保存。' : '定时任务已创建。'; void load(); }
600
+ },() => edit()));
601
+ };
602
+ edit();
603
+ dialog.showModal(); void load();
604
+ }
605
+ scheduleRow(job,current,onEdit,onAction) {
606
+ const row = make('details','session-schedule-row'), summary = make('summary');
607
+ const time = job.nextRunAt ?? (job.at ? Date.parse(job.at) : undefined);
608
+ const dateLabel = value => new Intl.DateTimeFormat('zh-CN',{dateStyle:'short',timeStyle:'short',timeZone:job.timeZone}).format(value);
609
+ const details = [scheduleStatuses[job.status] || job.status,scheduleFrequency(job.cron),time === undefined ? '' : dateLabel(time)].filter(Boolean);
610
+ summary.append(make('span','session-schedule-prompt',job.name || job.prompt),make('small','session-muted',details.join(' · ')));
611
+ row.append(summary);
612
+ if (job.prompt) row.append(make('p','session-schedule-preview',job.prompt));
613
+ const names = [...(job.images ? [`${job.images} 张图片`] : []),...(job.files || []),...(job.quotes ? [`${job.quotes} 条引用或批注`] : [])];
614
+ if (names.length) row.append(make('div','session-muted session-schedule-attachments',names.join(' · ')));
615
+ if (job.notice) row.append(make('p','session-muted',job.notice));
616
+ const actions = make('div','session-schedule-actions'), feedback = make('div','session-muted'); feedback.setAttribute('role','status');
617
+ const runAction = (label,action) => button(label,async () => {
618
+ const controls = [...actions.querySelectorAll('button')]; controls.forEach(control => { control.disabled = true; });
619
+ try { await onAction(action,job.revision); }
620
+ catch (error) { if (current()) feedback.textContent = error.message; }
621
+ finally { controls.forEach(control => { control.disabled = false; }); }
622
+ },'session-quiet');
623
+ actions.append(button('编辑',() => onEdit(job),'session-quiet'));
624
+ if (job.status === 'draft') actions.append(runAction('启用','confirm'));
625
+ if (job.status === 'enabled') actions.append(runAction('暂停','pause'));
626
+ if (job.status === 'paused') actions.append(runAction('恢复','resume'));
627
+ if (job.status !== 'draft') actions.append(runAction('立即执行','run'));
628
+ const remove = runAction('确认删除','delete'); remove.hidden = true;
629
+ const ask = button('删除',() => { remove.hidden = !remove.hidden; },'session-quiet');
630
+ actions.append(ask,remove);
631
+ const runs = make('details','session-schedule-runs'); runs.append(make('summary',null,'最近运行'));
632
+ const log = make('ul'); runs.append(log);
633
+ runs.ontoggle = async () => {
634
+ if (!runs.open) return;
635
+ log.replaceChildren(make('li','session-muted','正在读取…'));
636
+ try {
637
+ const data = await this.fetch('/schedules/runs',{params:{task:this.task.id,job:job.id}});
638
+ if (!current() || !runs.open) return;
639
+ log.replaceChildren(...data.runs.map(run => make('li',null,[dateLabel(run.scheduledFor),scheduleRunStatuses[run.status],run.detail].filter(Boolean).join(' · '))));
640
+ if (!data.runs.length) log.append(make('li','session-muted','暂无运行记录。'));
641
+ } catch (error) { if (current()) log.replaceChildren(make('li','session-muted',error.message)); }
642
+ };
643
+ row.append(actions,feedback,runs); return row;
644
+ }
645
+ scheduleForm(job,prompt,attachments,current,saveSchedule,cancel) {
646
+ const form = make('form','session-schedule-form'), fields = make('div','session-schedule-fields');
647
+ const name = make('input'), frequency = make('select'), date = make('input'), cron = make('input'), timeZone = make('input'), end = make('input');
648
+ timeZone.value = job?.timeZone || Intl.DateTimeFormat().resolvedOptions().timeZone; timeZone.required = true;
649
+ date.type = end.type = 'datetime-local';
650
+ const initialTime = job ? job.at ?? job.startsAt : Date.now()+30*60_000;
651
+ if (initialTime !== undefined) date.value = localDateTime(new Date(initialTime),timeZone.value);
652
+ if (job?.endsAt) end.value = localDateTime(new Date(job.endsAt),timeZone.value);
653
+ name.maxLength = 120; name.placeholder = '定时任务';
654
+ name.value = job?.name || prompt.split('\n')[0].slice(0,120) || (attachments[0] && attachmentName(attachments[0])?.slice(0,120)) || '';
655
+ for (const [value,label] of scheduleOptions) {
656
+ const option = make('option',null,label); option.value = value; option.selected = value === (job?.cron ? 'cron' : 'once'); frequency.append(option);
657
+ }
658
+ cron.value = job?.cron || ''; cron.maxLength = 120; cron.placeholder = '0 9 * * 1-5';
659
+ let message;
660
+ this.dialogField(form,'名称',name);
661
+ if (job) {
662
+ message = make('textarea'); message.rows = 3; message.maxLength = 24_000; message.value = job.prompt;
663
+ this.dialogField(form,'Prompt',message);
664
+ } else if (prompt) form.append(make('p','session-schedule-preview',prompt));
665
+ const names = job ? [...(job.images ? [`${job.images} 张图片`] : []),...(job.files || []),...(job.quotes ? [`${job.quotes} 条引用或批注`] : [])]
666
+ : attachments.map(attachmentName);
667
+ if (names.length) form.append(make('div','session-muted session-schedule-attachments',names.join(' · ')));
668
+ form.append(fields); this.dialogField(fields,'频率',frequency); this.dialogField(fields,'执行时间',date); this.dialogField(form,'Cron 表达式(五段)',cron);
669
+ const advanced = make('details','session-schedule-advanced'), settings = make('div','session-schedule-fields');
670
+ advanced.append(make('summary',null,'高级设置'),settings);
671
+ const maxDelay = make('input'), catchUp = make('input');
672
+ for (const [input,min,value] of [[maxDelay,1,job?.maxDelayMinutes ?? 60],[catchUp,0,job?.catchUpMinutes ?? 0]]) {
673
+ input.type = 'number'; input.min = String(min); input.max = '10080'; input.value = String(value); input.required = true;
674
+ }
675
+ this.dialogField(settings,'时区(IANA)',timeZone); this.dialogField(settings,'结束时间(可选)',end);
676
+ this.dialogField(settings,'最长等待(分钟)',maxDelay); this.dialogField(settings,'补跑窗口(分钟,0 为跳过)',catchUp);
677
+ form.append(advanced);
678
+ const syncFields = () => {
679
+ const once = frequency.value === 'once', custom = frequency.value === 'cron';
680
+ date.required = !custom;
681
+ date.parentElement.firstElementChild.textContent = `${once ? '执行时间' : '开始时间'}(${timeZone.value.trim()})`;
682
+ cron.required = custom; cron.parentElement.hidden = !custom; end.parentElement.hidden = once;
683
+ };
684
+ frequency.onchange = timeZone.oninput = syncFields; syncFields();
685
+ const actions = make('div','session-schedule-actions'), feedback = make('div','session-muted'); feedback.setAttribute('role','status');
686
+ const submit = button(job ? '保存设置' : '创建定时任务',undefined,'session-primary'); submit.type = 'submit';
687
+ if (job) actions.append(button('取消编辑',cancel,'session-quiet'));
688
+ actions.append(submit); form.append(actions,feedback);
689
+ let sent, request;
690
+ form.onsubmit = async event => {
691
+ event.preventDefault(); if (!current() || submit.disabled) return;
692
+ const timeZoneName = timeZone.value.trim(), type = frequency.value;
693
+ try {
694
+ if (!timeZoneName) throw new Error('请输入时区。');
695
+ const start = date.value ? scheduleDate(date.value,timeZoneName) : undefined;
696
+ const timing = {};
697
+ if (type === 'once') {
698
+ if (!start || start.getTime() <= Date.now()) throw new Error('请选择未来的执行时间。');
699
+ timing.at = start.toISOString();
700
+ } else {
701
+ if (type === 'cron') timing.cron = cron.value.trim();
702
+ else {
703
+ const nominal = new Date(date.value+'Z'), minute = nominal.getUTCMinutes(), hour = nominal.getUTCHours(), day = nominal.getUTCDate();
704
+ const rules = {hourly:'* * * *',daily:`${hour} * * *`,weekdays:`${hour} * * 1-5`,weekly:`${hour} * * ${nominal.getUTCDay()}`,
705
+ monthly:`${hour} ${day} * *`,yearly:`${hour} ${day} ${nominal.getUTCMonth()+1} *`};
706
+ timing.cron = `${minute} ${rules[type]}`;
707
+ }
708
+ if (start) timing.startsAt = start.toISOString();
709
+ if (end.value) timing.endsAt = scheduleDate(end.value,timeZoneName).toISOString();
710
+ }
711
+ const schedule = { name:name.value.trim() || '定时任务',prompt:message ? message.value.trim() : prompt,timeZone:timeZoneName,
712
+ maxDelayMinutes:Number(maxDelay.value),catchUpMinutes:Number(catchUp.value),...timing };
713
+ const next = JSON.stringify(schedule);
714
+ if (sent !== next) { sent = next; request = uuid(); }
715
+ submit.disabled = true; feedback.textContent = '';
716
+ await saveSchedule(schedule,request);
717
+ } catch (error) { if (current()) feedback.textContent = error.message; }
718
+ finally { submit.disabled = false; }
719
+ };
720
+ return form;
721
+ }
722
+ openNewTask() {
723
+ if (!this.csrf) return;
724
+ this.app.annotations?.cancel();
725
+ if (this.selecting) this.cancelSelection();
726
+ const resume = this.newDraft || this.parkedDraft;
727
+ if (!this.newDraft) this.newDraft = this.parkedDraft || {
728
+ id:uuid(),request:uuid(),text:'',directory:this.task?.project.root,agent:this.task?.agent,
729
+ };
730
+ this.parkedDraft = undefined;
731
+ const draft = this.newDraft;
732
+ if (resume) void this.restoreDraftFiles(draft.id);
733
+ this.setChatError('');
734
+ this.input.value = draft.text; this.noticeImages(''); this.updateDraftView();
735
+ this.app.navigate(() => { this.app.selectPane('chat'); this.app.applyLayout(); });
736
+ this.input.focus();
737
+ if (draft.agents) return;
738
+ const grant = this.csrf;
739
+ void this.fetch('/task-agents').then(data => {
740
+ if (this.csrf !== grant || (this.newDraft !== draft && this.parkedDraft !== draft)) return;
741
+ draft.agents = data.agents;
742
+ if (!data.agents.some(agent=>agent.name === draft.agent)) draft.agent = data.defaultAgent;
743
+ if (this.newDraft === draft) { this.updateDraftView(); if (!draft.agent) this.setChatError('未配置支持 Workspace 的 App Server Agent。'); }
744
+ }).catch(error => { if (this.newDraft === draft && this.csrf === grant) this.setChatError(error.message); });
745
+ }
746
+ leaveDraft(discard = false) {
747
+ const draft = this.newDraft;
748
+ if (!draft) return;
749
+ this.app.annotations?.cancel();
750
+ draft.text = this.input.value; this.newDraft = undefined;
751
+ if (discard) this.replaceImages(draft.id,[]);
752
+ else this.parkedDraft = draft;
753
+ if (this.settingsDialog?.open) this.settingsDialog.close();
754
+ this.input.value = this.task ? this.draft(this.task.id) : '';
755
+ this.noticeImages(''); this.setChatError(''); this.updateDraftView();
756
+ this.app.applyLayout();
757
+ }
758
+ saveNewTaskDraft() {
759
+ const draft = this.newDraft ?? this.parkedDraft;
760
+ if (draft) {
761
+ const {id,request,text,directory,agent,model,thinking,creationTitle,filesCollapsed} = draft;
762
+ this.newDraftSaved = save(this.newDraftKey,{active:Boolean(this.newDraft || this.resumeNewDraft),
763
+ draft:{id,request,text,directory,agent,model,thinking,creationTitle,filesCollapsed}},'sessionStorage');
764
+ } else if (this.newDraftSaved) {
765
+ this.newDraftSaved = false;
766
+ save(this.newDraftKey,null,'sessionStorage');
767
+ }
768
+ }
769
+ updateDraftView() {
770
+ const draft = this.newDraft, submission = draft?.sending;
771
+ this.saveNewTaskDraft();
772
+ this.chat.toggleAttribute('data-draft',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);
780
+ this.updatePlan(this.headPlan);
781
+ this.draftTools.hidden = !draft;
782
+ this.draftTools.replaceChildren();
783
+ if (draft) {
784
+ const project = button(draft.directory ? draft.directory.split(/[\\/]/u).filter(Boolean).at(-1) : '选择项目目录',
785
+ () => this.openDraftProject(draft),'session-draft-project');
786
+ if (draft.directory) project.dataset.tooltip = draft.directory;
787
+ project.disabled = Boolean(draft.sending);
788
+ this.draftTools.append(project);
789
+ if (draft.directory) {
790
+ const clear = iconButton('清除项目','M6 6l12 12M18 6 6 18','session-clear-project',() => {
791
+ draft.directory = undefined; draft.request = uuid(); this.updateDraftView();
792
+ });
793
+ clear.disabled = project.disabled; this.draftTools.append(clear);
794
+ }
795
+ const cancel = button('取消草稿',() => this.leaveDraft(true),'session-quiet'); cancel.disabled = project.disabled;
796
+ this.draftTools.append(cancel);
797
+ }
798
+ this.renderChatHeader(); this.updateComposer();
799
+ }
800
+ openDraftProject(draft) {
801
+ if (draft.sending) return;
802
+ const dialog = this.createDialog('选择项目目录',this.chat);
803
+ const form = make('form'), input = make('input');
804
+ input.placeholder = '输入主机上的绝对目录路径'; input.required = true; input.maxLength = 4096; input.value = draft.directory || '';
805
+ this.dialogField(form,'目录路径',input);
806
+ const apply = make('button','session-dialog-submit','选择目录'); apply.type = 'submit';
807
+ const chooseProject = root => {
808
+ draft.directory = root; draft.request = uuid(); dialog.close(); this.setChatError(''); this.updateDraftView();
809
+ };
810
+ const projects = make('div','session-project-choices');
811
+ for (const { group:project } of this.projects.values()) {
812
+ if (!project?.root) continue;
813
+ const choice = button(project.name,() => chooseProject(project.root)); choice.dataset.tooltip = project.root; projects.append(choice);
814
+ }
815
+ form.append(projects,apply); dialog.append(form);
816
+ form.onsubmit = event => { event.preventDefault(); const root = input.value.trim().replace(/^"(.+)"$/u,'$1'); if (root) chooseProject(root); };
817
+ dialog.addEventListener('close',() => dialog.remove(),{once:true});
818
+ dialog.showModal(); input.focus();
819
+ }
196
820
  listParams() { return {q:this.search.value.trim(),archived:this.filter.value === 'archived'?'1':undefined}; }
197
821
  async loadGroups(refresh = false, more = false) {
198
- if (!this.csrf || refresh && (this.groupPending || this.projects.size > 30)) return;
822
+ if (!this.csrf || this.disposed) return;
823
+ if (refresh && this.groupPending) { this.groupRefresh = true; return; }
824
+ if (refresh && this.projects.size > 30) {
825
+ for (const view of this.projects.values()) if (view.node.open) void this.loadGroup(view,false,true);
826
+ return;
827
+ }
199
828
  this.groupRequest?.abort(); const controller = this.groupRequest = new AbortController();
200
829
  this.groupPending = true;
201
830
  const params = this.listParams(), last = more ? [...this.projects.keys()].at(-1) : undefined;
@@ -211,7 +840,7 @@
211
840
  let view = this.projects.get(group.id);
212
841
  if (!view) { view = this.createGroup(group); this.projects.set(group.id,view); }
213
842
  view.title.textContent = group.name; view.count.textContent = String(group.count);
214
- view.title.title = group.root || group.name;
843
+ view.summary.dataset.tooltip = group.root || group.name;
215
844
  if (view.node.open) void this.loadGroup(view,false,refresh);
216
845
  }
217
846
  this.groupMore?.remove();
@@ -219,77 +848,186 @@
219
848
  if (!this.projects.size) this.listNote.textContent = params.q ? '没有匹配的任务。' : '暂无'+(params.archived?'已归档':'未归档')+'任务。';
220
849
  } catch (error) {
221
850
  if (!controller.signal.aborted && this.csrf) this.listNote.replaceChildren(make('span','session-error',refresh?'任务列表暂未更新。':error.message),button('重试',() => this.loadGroups(),'session-quiet'));
222
- } finally { if (this.groupRequest === controller) this.groupPending = false; }
851
+ } finally {
852
+ if (this.groupRequest === controller) {
853
+ this.groupPending = false;
854
+ if (this.groupRefresh) { this.groupRefresh = false; void this.loadGroups(true); }
855
+ }
856
+ }
223
857
  }
224
858
  createGroup(group) {
225
859
  const node = make('details','session-project'), summary = make('summary'), title = make('span','session-project-title',group.name), count = make('span','session-project-count'), rows = make('div','session-task-rows');
226
- const view = {node,title,count,rows,group,items:[],sequence:0};
860
+ const view = {node,summary,title,count,rows,group,items:[],sequence:0};
227
861
  summary.append(title,count); node.append(summary,rows); this.groupList.append(node);
228
862
  node.open = Boolean(this.search.value || this.openGroups.has(group.id) || this.task?.project.id === group.id || this.projects.size === 0);
229
863
  node.ontoggle = () => {
230
- if (node.open) { this.openGroups.add(group.id); if (!view.items.length) void this.loadGroup(view); }
864
+ if (node.open) { this.openGroups.add(group.id); void this.loadGroup(view,false,Boolean(view.signature)); }
231
865
  else this.openGroups.delete(group.id);
232
866
  if (!this.search.value) save('agentbot-workspace-groups',[...this.openGroups].slice(-100));
233
867
  };
234
868
  return view;
235
869
  }
236
870
  async loadGroup(view, more = false, refresh = false) {
237
- if (!this.csrf || view.loading || refresh && view.items.length > 20) return;
238
- view.loading = true; const sequence = ++view.sequence, params = this.listParams();
871
+ if (!this.csrf) return;
872
+ if (this.taskRename?.view === view && this.taskRename.row.isConnected) return;
873
+ if (view.loading) { if (refresh) view.refresh = true; return; }
874
+ view.loading = true; view.refresh = false;
875
+ const sequence = ++view.sequence, params = this.listParams();
239
876
  if (!refresh && !more) view.rows.replaceChildren(make('div','session-list-note','加载任务…'));
240
877
  try {
241
- const data = await this.fetch('/tasks',{params:{...params,project:view.group.id,after:more?view.items.at(-1)?.id:undefined}});
242
- if (!view.node.isConnected || sequence !== view.sequence || !this.csrf) return;
243
- const items = more ? [...new Map([...view.items,...data.items].map(item => [item.id,item])).values()] : data.items;
244
- const signature = JSON.stringify([items,data.more]);
878
+ const readPage = after => this.fetch('/tasks',{params:{...params,project:view.group.id,after}});
879
+ let {items,more:hasMore} = await readPage(more ? view.items.at(-1)?.id : undefined);
880
+ const current = () => view.node.isConnected && sequence === view.sequence && Boolean(this.csrf);
881
+ while (current() && refresh && hasMore && items.length && items.length < view.items.length) {
882
+ const next = await readPage(items.at(-1).id);
883
+ const merged = [...new Map([...items,...next.items].map(item => [item.id,item])).values()];
884
+ if (merged.length === items.length) break;
885
+ items = merged; hasMore = next.more;
886
+ }
887
+ if (!current() || this.taskRename?.view === view && this.taskRename.row.isConnected) return;
888
+ if (more) items = [...new Map([...view.items,...items].map(item => [item.id,item])).values()];
889
+ const signature = JSON.stringify([items,hasMore]);
245
890
  if (signature !== view.signature) {
246
891
  const focused = document.activeElement?.dataset?.sessionTask;
247
892
  view.items = items; view.signature = signature;
248
- view.rows.replaceChildren(...items.map(item => this.taskButton(item)));
249
- if (data.more) view.rows.append(button('更多任务',() => this.loadGroup(view,true),'session-more'));
893
+ view.rows.replaceChildren(...items.map(item => this.taskButton(item,view)));
894
+ if (hasMore) view.rows.append(button('更多任务',() => this.loadGroup(view,true),'session-more'));
250
895
  if (focused) [...view.rows.querySelectorAll('[data-session-task]')].find(node => node.dataset.sessionTask === focused)?.focus({preventScroll:true});
251
896
  }
252
897
  } catch (error) {
253
898
  if (view.node.isConnected && !refresh) { view.signature = undefined; view.rows.replaceChildren(make('span','session-list-note session-error',error.message),button('重试',() => this.loadGroup(view),'session-quiet')); }
254
- } finally { view.loading = false; }
899
+ } finally {
900
+ view.loading = false;
901
+ if (view.refresh && view.node.isConnected && view.node.open) { view.refresh = false; void this.loadGroup(view,false,true); }
902
+ }
255
903
  }
256
- taskButton(item) {
257
- const node = button('',() => this.choose(item.id),'session-task'), title = make('span','session-task-title',item.title);
904
+ taskButton(item,view) {
905
+ const label = item.title || '未命名任务';
906
+ const node = button('',() => this.choose(item.id),'session-task'), title = make('span','session-task-title',label);
258
907
  const dot = make('span','session-dot'); dot.dataset.status = item.status; dot.setAttribute('aria-hidden','true');
259
- node.append(dot,title); node.dataset.sessionTask = item.id; node.title = `${item.title} · ${status(item.status)} · ${item.agent}`;
260
- node.setAttribute('aria-label',node.title);
908
+ const details = make('span','session-task-details'), line = make('span','session-task-line');
909
+ const progress = taskProgress[item.status], subtitle = progress
910
+ ? (item.promptPreview ? progress+':'+item.promptPreview : progress) : item.promptPreview || status(item.status);
911
+ line.append(title);
912
+ const updated = new Date(item.updatedAt);
913
+ let updatedLabel;
914
+ if (item.updatedAt && Number.isFinite(updated.getTime())) {
915
+ const time = make('time','session-task-time',taskDateLabel(updated));
916
+ time.setAttribute('datetime',updated.toISOString()); line.append(time);
917
+ updatedLabel = '更新于 '+taskFullDate.format(updated)+' '+taskClock.format(updated);
918
+ }
919
+ details.append(line,make('span','session-task-subtitle',subtitle));
920
+ node.append(dot,details); node.dataset.sessionTask = item.id;
921
+ node.dataset.tooltipOverflow = '.session-task-title';
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
+ };
261
930
  if (item.id === this.task?.id) node.setAttribute('aria-current','true'); return node;
262
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
+ }
263
985
  updateSelected() {
264
986
  for (const node of this.groupList?.querySelectorAll('[data-session-task]') || []) {
265
987
  if (node.dataset.sessionTask === this.task?.id) node.setAttribute('aria-current','true'); else node.removeAttribute('aria-current');
266
988
  }
267
989
  }
268
990
  async choose(taskId, nav = {}) {
991
+ if (this.newDraft && this.newDraft !== nav.sentDraft) this.leaveDraft();
269
992
  if (!this.csrf || !taskId || this.task?.id === taskId && !nav.history && !this.selecting) {
270
993
  if (this.task?.id === taskId) this.app.navigate(() => this.app.selectPane('chat'),true);
271
994
  return;
272
995
  }
273
- this.selection?.abort(); const controller = this.selection = new AbortController();
996
+ if (this.task?.id !== taskId) this.app.annotations?.cancel();
997
+ this.selection?.abort(); this.resetNewer(); const controller = this.selection = new AbortController();
998
+ if (this.settingsDialog?.open) this.settingsDialog.close();
999
+ if (this.scheduleDialog?.open) this.scheduleDialog.close();
274
1000
  const generation = ++this.generation; this.target = taskId; this.selecting = true; this.bufferedTail = undefined; this.refreshing = undefined;
275
1001
  this.app.dataset.taskPending = 'true';
276
1002
  const position = nav.position?.chat || (nav.href ? this.app.chatPositionFromUrl(nav.href) : this.app.savedSessionChat(taskId));
277
1003
  const anchor = position?.turn;
278
1004
  let snapshot;
279
- this.setChatError('正在打开任务…'); this.updateComposer();
1005
+ if (!nav.sentDraft) this.setChatError('正在打开任务…');
1006
+ this.updateComposer();
280
1007
  try {
281
- const data = snapshot = await this.loadTask(taskId,generation,anchor,controller.signal);
1008
+ const [data] = await Promise.all([this.loadTask(taskId,generation,anchor,controller.signal),this.restoreDraftFiles(taskId)]);
1009
+ snapshot = data;
282
1010
  if (controller.signal.aborted || !this.csrf || generation !== this.generation) return;
283
1011
  this.app.activateTaskPanel(data.task,nav,() => {
284
- this.task = data.task; this.head = data.head; this.headStatus = data.headStatus; this.anchored = data.anchored;
1012
+ if (nav.sentDraft && this.newDraft === nav.sentDraft) this.leaveDraft(true);
1013
+ this.imageDialog?.open && this.imageDialog.close();
1014
+ this.imageNotice.hidden = true;
1015
+ this.task = data.task; this.updateHead(data.head,data.headStatus,data.execution);
1016
+ this.setPlanOpen(false); this.updatePlan(data.plan);
285
1017
  this.turns = data.turns; this.more = data.more; this.turnNodes.clear(); this.timeline.replaceChildren();
286
- this.pendingPosition = position || {bottom:true}; this.input.value = this.draft(taskId); this.checkOperation(taskId,false);
287
- this.renderConversation(); this.updateSelected();
1018
+ this.clearChatImageHandoffs();
1019
+ this.restoredPosition = undefined; this.pendingPosition = position || {bottom:true};
1020
+ this.input.value = this.draft(taskId); this.checkOperation(taskId,false);
1021
+ this.outboxRows = new Map(); this.outbox.replaceChildren();
1022
+ this.renderConversation(); this.updateSelected(); this.checkRestoredMessages(taskId);
1023
+ const project = this.projects.get(this.task.project.id);
1024
+ if (project && !project.node.open) project.node.open = true;
288
1025
  });
289
1026
  this.setChatError('');
290
1027
  if (!nav.history && !nav.initial && !this.left.clientHeight) this.chatTitle.focus({preventScroll:true});
291
1028
  } catch (error) {
292
1029
  if (!controller.signal.aborted && this.csrf) {
1030
+ if (nav.sentDraft && this.newDraft === nav.sentDraft) this.leaveDraft(true);
293
1031
  const message = `无法打开任务:${error.status ? error.message : '连接失败,请重试。'}`;
294
1032
  const retry = () => this.choose(taskId,nav);
295
1033
  this.setChatError(message,false,retry);
@@ -300,8 +1038,8 @@
300
1038
  if (generation === this.generation) {
301
1039
  this.selecting = false; this.app.dataset.taskPending = 'false'; this.updateComposer(); this.restorePosition();
302
1040
  if (!snapshot) this.target = this.task?.id;
303
- this.drainTail(snapshot);
304
1041
  if (this.connected && this.task && (!snapshot || snapshot.epoch !== this.connectionEpoch)) void this.refreshConversation(true);
1042
+ else { this.drainTail(snapshot); void this.loadNewer(); }
305
1043
  }
306
1044
  }
307
1045
  }
@@ -315,282 +1053,1863 @@
315
1053
  }
316
1054
  drainTail(snapshot) {
317
1055
  const tail = this.bufferedTail; this.bufferedTail = undefined;
318
- if (tail && tail.taskId === this.task?.id && tail.generation === this.generation && tail.epoch === this.connectionEpoch
319
- && (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);
1063
+ }
1064
+ updateHead(head, status, execution) {
1065
+ this.head = head; this.headStatus = status; this.execution = execution;
320
1066
  }
321
1067
  applyTail(data) {
322
1068
  if (!this.task) return;
323
- if (!data) { this.setChatError('此任务已不可用。'); this.task.status = 'closed'; this.updateComposer(); return; }
324
- const previous = this.head;
325
- Object.assign(this.task,data.task,{queued:data.queued});
326
- this.headStatus = data.turn?.status;
327
- if ((data.turn?.id || undefined) !== previous) {
328
- if (!this.anchored) void this.refreshConversation(false);
329
- else { this.head = data.turn?.id; this.jump.hidden = false; }
330
- } else if (data.turn) {
331
- const i = this.turns.findIndex(turn => turn.id === data.turn.id);
332
- if (i >= 0) { this.turns[i] = data.turn; this.redraw(); }
333
- }
1069
+ if (!data) { this.resetNewer(); this.updateHead(); this.updatePlan(); this.setChatError('此任务已不可用。'); this.task.status = 'closed'; this.updateComposer(); return; }
1070
+ Object.assign(this.task,data.task);
1071
+ if (data.queued !== undefined) this.task.queued = data.queued;
1072
+ if (data.queuedPrompts !== undefined) this.task.queuedPrompts = data.queuedPrompts;
1073
+ this.app.filesPanel.setTaskDirectories(this.task.directories);
1074
+ const next = data.turn, last = this.turns.at(-1);
1075
+ this.updateHead(next?.id,next?.status,data.execution);
1076
+ this.updatePlan(data.plan);
1077
+ const promoted = next?.promptRequestId && next.promptRequestId === last?.promptRequestId
1078
+ && last.id.startsWith('pending_') && !next.id.startsWith('pending_');
1079
+ if (next && (next.id === last?.id || promoted)) {
1080
+ this.turns[this.turns.length-1] = next;
1081
+ this.redraw();
1082
+ } else if (next && (data.parent === last?.id || !last && !data.parent)) {
1083
+ this.turns.push(next); this.redraw();
1084
+ } else if (!last || !next) {
1085
+ if (last || next) void this.refreshConversation(false);
1086
+ } else void this.loadNewer();
1087
+ if (this.newerFailed && this.head && !this.hasNewer()) { this.newerFailed = false; this.setChatError(''); }
334
1088
  this.updateComposer(); this.renderChatHeader();
335
1089
  }
336
- async refreshConversation(refocus, latest = false) {
1090
+ hasNewer() { return Boolean(this.head && this.turns.length && this.turns.at(-1).id !== this.head); }
1091
+ resetNewer() { this.newerRequest?.abort(); this.newerRequest = undefined; this.newerFailed = false; }
1092
+ async loadNewer() {
1093
+ if (!this.csrf || !this.task || this.selecting || this.refreshing || this.newerRequest || this.newerFailed || !this.hasNewer()) return;
1094
+ const task = this.task.id, after = this.turns.at(-1).id, epoch = this.connectionEpoch;
1095
+ const controller = this.newerRequest = new AbortController();
1096
+ let snapshot, resetBranch = false;
1097
+ try {
1098
+ const data = await this.fetch('/task',{params:{task,after,page:this.connected?this.page:undefined},signal:controller.signal});
1099
+ if (this.newerRequest !== controller) return;
1100
+ if (data.turns.length === 0 && data.head !== after) throw new Error('未能继续读取对话。');
1101
+ snapshot = data.version === undefined ? undefined : {...data,epoch};
1102
+ this.pendingPosition = this.position();
1103
+ this.turns.push(...data.turns);
1104
+ this.updateHead(data.head,data.headStatus,data.execution); this.task = data.task; this.updatePlan(data.plan);
1105
+ this.app.filesPanel.setTaskDirectories(this.task.directories);
1106
+ this.renderConversation(); this.setChatError('');
1107
+ } catch (error) {
1108
+ if (this.newerRequest !== controller) return;
1109
+ if (error.status === 409) resetBranch = true;
1110
+ else {
1111
+ this.newerFailed = true;
1112
+ this.setChatError('后续对话读取失败:'+error.message,false,() => { this.newerFailed = false; void this.loadNewer(); });
1113
+ }
1114
+ } finally {
1115
+ if (this.newerRequest === controller) {
1116
+ this.newerRequest = undefined;
1117
+ if (resetBranch) void this.refreshConversation(false,{anchor:this.position()?.turn});
1118
+ else { this.drainTail(snapshot); void this.loadNewer(); }
1119
+ }
1120
+ }
1121
+ }
1122
+ async refreshConversation(refocus, {anchor = this.turns.at(-1)?.id, position: requestedPosition} = {}) {
337
1123
  const task = this.task?.id;
338
- if (!task || this.selecting || this.refreshing && !refocus && !latest) return;
1124
+ if (!task || this.selecting || this.refreshing && !refocus) return;
1125
+ this.resetNewer();
339
1126
  const generation = this.generation, refresh = this.refreshing = {};
340
- let snapshot;
341
- const position = latest ? {bottom:true} : this.position();
1127
+ let snapshot, updated = false;
1128
+ const startPosition = requestedPosition || this.position();
342
1129
  try {
343
- const anchor = this.anchored && !latest ? position?.turn : undefined;
344
1130
  const data = snapshot = await this.loadTask(task,generation,anchor);
345
1131
  if (generation !== this.generation || refresh !== this.refreshing || this.selecting) return;
1132
+ const position = requestedPosition || this.position() || startPosition;
346
1133
  const first = data.turns[0]?.id, overlap = this.turns.findIndex(turn => turn.id === first);
347
- this.turns = !latest && overlap >= 0 ? [...this.turns.slice(0,overlap),...data.turns] : data.turns;
348
- this.more = !latest && overlap > 0 ? this.more : data.more;
349
- this.head = data.head; this.headStatus = data.headStatus; this.anchored = data.anchored; this.task = data.task;
350
- this.pendingPosition = position; this.renderConversation(); this.setChatError('');
351
- } catch (error) { if (generation === this.generation && this.csrf) this.setChatError('对话更新失败:'+error.message,true); }
1134
+ this.turns = overlap > 0 ? [...this.turns.slice(0,overlap),...data.turns] : data.turns;
1135
+ this.more = overlap > 0 ? this.more : data.more;
1136
+ this.updateHead(data.head,data.headStatus,data.execution); this.task = data.task; this.updatePlan(data.plan);
1137
+ this.app.filesPanel.setTaskDirectories(this.task.directories);
1138
+ this.pendingPosition = position; this.renderConversation(); this.setChatError(''); updated = true;
1139
+ } catch (error) {
1140
+ if (refresh === this.refreshing && generation === this.generation && this.csrf) {
1141
+ this.setChatError('对话更新失败:'+error.message,false,() => this.refreshConversation(true,{anchor,position:requestedPosition}));
1142
+ }
1143
+ }
352
1144
  finally {
353
1145
  if (this.refreshing === refresh) {
354
1146
  this.refreshing = undefined;
355
1147
  this.drainTail(snapshot);
1148
+ if (updated) void this.loadNewer();
356
1149
  }
357
1150
  }
358
1151
  }
359
1152
  renderChat() {
1153
+ this.clearChatImageHandoffs();
1154
+ this.composing = false;
360
1155
  this.chatHeader = make('header','session-chat-header');
361
- this.chatTitle = make('h2',null,'聊天'); this.chatTitle.tabIndex = -1; this.chatMeta = make('div','session-chat-meta'); this.chatHeader.append(this.chatTitle,this.chatMeta);
1156
+ this.chatTitle = make('h2',null,'聊天'); this.chatTitle.tabIndex = -1;
1157
+ this.chatTitle.dataset.tooltipOverflow = '';
1158
+ this.chatMeta = make('div','session-chat-meta'); this.chatMeta.hidden = true; this.chatHeader.append(this.chatTitle,this.chatMeta);
1159
+ this.chatMeta.tabIndex = 0; this.chatMeta.setAttribute('role','group'); this.chatMeta.setAttribute('aria-label','任务信息');
1160
+ this.chatState = make('span','session-state'); this.chatAgent = make('span','session-agent');
1161
+ this.chatTurns = make('span','session-turn-count'); this.chatTokens = make('span','session-token-usage');
1162
+ this.chatStorage = make('span','session-storage-size');
1163
+ this.chatMeta.append(this.chatState,this.chatAgent,this.chatTurns,this.chatTokens,this.chatStorage);
362
1164
  this.chatError = make('div','session-chat-error'); this.chatError.setAttribute('role','status'); this.chatError.hidden = true;
363
- this.body = make('div','chat-body session-chat-body'); this.body.tabIndex = 0; this.body.setAttribute('role','region'); this.body.setAttribute('aria-label','对话记录');
1165
+ const body = this.body = make('div','chat-body session-chat-body'); body.tabIndex = 0; body.setAttribute('role','region'); body.setAttribute('aria-label','对话记录');
1166
+ const reading = make('div','session-chat-reading');
1167
+ this.planPanel = make('aside','session-plan-sidebar'); this.planPanel.id = 'workspace-plan-'+this.page;
1168
+ this.planPanel.setAttribute('aria-label','执行计划'); this.planPanel.tabIndex = -1;
1169
+ const planHeader = make('header');
1170
+ this.planProgress = make('span','session-plan-progress');
1171
+ planHeader.append(make('h3',null,'执行计划'),this.planProgress);
1172
+ this.planSteps = make('ol','session-plan-steps'); this.planPanel.append(planHeader,this.planSteps);
1173
+ this.planButton = button('',() => {
1174
+ const open = this.planButton.getAttribute('aria-expanded') !== 'true';
1175
+ this.setPlanOpen(open);
1176
+ if (open) this.planPanel.focus({preventScroll:true});
1177
+ },'session-plan-trigger');
1178
+ this.planButton.setAttribute('aria-controls',this.planPanel.id);
1179
+ this.planPanel.onkeydown = this.planButton.onkeydown = event => {
1180
+ if (event.key !== 'Escape' || this.planButton.getAttribute('aria-expanded') !== 'true') return;
1181
+ event.preventDefault(); event.stopPropagation();
1182
+ this.setPlanOpen(false); this.planButton.focus({preventScroll:true});
1183
+ };
1184
+ this.setPlanOpen(false); this.planSignature = undefined; this.updatePlan(this.headPlan);
1185
+ reading.append(body,this.planPanel);
364
1186
  this.older = button('加载更早的对话',() => this.loadOlder(),'session-more session-older'); this.older.hidden = true;
365
1187
  this.timeline = make('div','session-timeline'); this.turnNodes = new Map();
366
- this.timelineObserver?.disconnect();
367
- this.timelineObserver = new ResizeObserver(() => {
368
- if (!this.task || !this.body.clientHeight) return;
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;
1190
+ this.timelineObserver?.disconnect(); this.closeSettingsMenu();
1191
+ this.chat.removeAttribute('data-draft');
1192
+ const stabilizeReadingPosition = () => {
1193
+ if (!this.task || this.newDraft || !body.clientHeight) return;
369
1194
  this.pendingPosition ||= this.lastPosition;
370
- this.restorePosition();
371
- });
1195
+ if (body.clientHeight === this.chatBodyHeight) this.restorePosition();
1196
+ else window.requestAnimationFrame(() => { if (this.body === body && body.isConnected) this.restorePosition(); });
1197
+ };
1198
+ this.timelineObserver = new ResizeObserver(stabilizeReadingPosition);
372
1199
  this.timelineObserver.observe(this.timeline);
373
- this.timeline.addEventListener('error', event => {
1200
+ this.timelineObserver.observe(this.outbox);
1201
+ this.timelineObserver.observe(body);
1202
+ body.addEventListener('load', event => {
374
1203
  const image = event.target;
375
- if (image instanceof HTMLImageElement) image.replaceWith(make('span','session-image-unavailable',image.alt ? `图片不可用:${image.alt}` : '图片不可用'));
1204
+ if (image.matches?.('img[data-chat-image]')) { this.rememberChatImageSize(image); stabilizeReadingPosition(); }
1205
+ }, true);
1206
+ body.addEventListener('error', event => {
1207
+ const image = event.target;
1208
+ if (image instanceof HTMLImageElement) {
1209
+ image.replaceWith(make('span','session-image-unavailable',image.alt ? `图片不可用:${image.alt}` : '图片不可用'));
1210
+ stabilizeReadingPosition();
1211
+ }
376
1212
  }, true);
377
1213
  this.timeline.append(make('div','session-empty','从左侧选择一个任务,查看对话并继续工作。'));
378
- this.body.append(this.older,this.timeline);
379
- this.jump = button('回到最新',() => this.refreshConversation(false,true),'session-jump'); this.jump.hidden = true;
380
- this.body.onscroll = () => {
381
- if (!this.task || !this.body.clientHeight) return;
382
- if (!this.pendingPosition) this.lastPosition = this.position(true);
383
- if (!this.anchored) this.jump.hidden = this.atBottom();
384
- };
385
- const form = this.composer = make('form','chat-composer session-composer');
1214
+ this.body.append(this.older,this.timeline,this.outbox,this.draftPreview);
1215
+ body.addEventListener('click', event => {
1216
+ if (this.previewChatImage(event)) return;
1217
+ const link = event.target.closest?.('[data-chat-file]');
1218
+ if (!link || !plainLinkClick(event)) return;
1219
+ event.preventDefault(); this.app.openChatFile(link.dataset.chatFile,'file',link.hash || undefined);
1220
+ });
1221
+ body.addEventListener('keydown',event => {
1222
+ if (event.key === 'Enter' || event.key === ' ') this.previewChatImage(event);
1223
+ });
1224
+ this.jump = iconButton('回到最新','M12 4v16m-6-6 6 6 6-6','session-jump',() => this.jumpToBottom());
1225
+ this.jump.hidden = true;
1226
+ body.onscroll = () => {
1227
+ if (!this.task || this.newDraft || !body.clientHeight) return;
1228
+ this.jump.hidden = this.atBottom();
1229
+ // A growing editor changes the scroll range before the resize observer restores the reading position.
1230
+ if (body.clientHeight !== this.chatBodyHeight || this.pendingPosition) return;
1231
+ if (this.restoredPosition?.top === body.scrollTop) return;
1232
+ this.restoredPosition = undefined;
1233
+ this.lastPosition = this.position(true);
1234
+ };
1235
+ const form = this.composer = make('form','session-composer'), field = make('div','session-composer-field');
1236
+ this.composerMirror = window.CSS?.supports('field-sizing','content') ? undefined : field;
386
1237
  this.input = make('textarea'); this.input.rows = 2; this.input.maxLength = 24_000; this.input.setAttribute('aria-label','发送给 Agent 的消息');
387
- this.input.oninput = () => { if (this.task) this.setDraft(this.task.id,this.input.value); this.updateComposer(); };
388
- this.input.onkeydown = event => { if (event.key === 'Enter' && !event.isComposing && !this.composing && (event.ctrlKey || event.metaKey)) { event.preventDefault(); void this.submit('send'); } };
1238
+ field.append(this.input);
1239
+ let beforeEdit;
1240
+ this.input.onbeforeinput = () => { beforeEdit = this.position(true); };
1241
+ this.input.oninput = () => {
1242
+ const position = beforeEdit; beforeEdit = undefined;
1243
+ if (this.newDraft) { this.newDraft.text = this.input.value; this.saveNewTaskDraft(); }
1244
+ else if (this.task) this.setDraft(this.task.id,this.input.value);
1245
+ this.updateComposer();
1246
+ this.keepComposerPosition(position);
1247
+ };
1248
+ this.input.onkeydown = event => {
1249
+ if (event.key !== 'Enter' || event.shiftKey || event.isComposing || this.composing || event.keyCode === 229) return;
1250
+ event.preventDefault();
1251
+ if (event.altKey) {
1252
+ const {value,selectionStart,selectionEnd,maxLength} = this.input;
1253
+ if (value.length - (selectionEnd-selectionStart) < maxLength) {
1254
+ this.input.setRangeText('\n',selectionStart,selectionEnd,'end');
1255
+ this.input.dispatchEvent(new Event('input',{bubbles:true}));
1256
+ }
1257
+ } else this.submit(event.ctrlKey || event.metaKey ? 'queue' : 'send');
1258
+ };
1259
+ this.input.setAttribute('aria-keyshortcuts','Enter Shift+Enter Control+Enter Meta+Enter Alt+Enter');
389
1260
  this.input.oncompositionstart = () => { this.composing = true; }; this.input.oncompositionend = () => { this.composing = false; };
390
1261
  this.opNote = make('div','session-operation'); this.opNote.setAttribute('role','status'); this.opNote.hidden = true;
391
- const actions = make('div','session-composer-actions'); this.queue = button('排队',() => this.submit('queue'),'session-quiet');
392
- this.stop = button('停止',() => this.submit('stop'),'session-stop'); this.stop.hidden = true;
393
- this.send = make('button','session-primary','发送'); this.send.type = 'submit'; this.send.title = 'Ctrl / ⌘ + Enter';
394
- this.queueCount = make('small','session-queued'); actions.append(this.queueCount,this.stop,this.queue,this.send); form.append(this.input,actions);
1262
+ const actions = make('div','session-composer-actions');
1263
+ const picker = make('input'); picker.type = 'file'; picker.multiple = true; picker.hidden = true;
1264
+ picker.onchange = () => { this.addAttachments(picker.files); picker.value = ''; };
1265
+ this.attach = iconButton('添加附件','M12 5v14M5 12h14','session-attach',() => picker.click());
1266
+ form.append(picker);
1267
+ form.addEventListener('paste',event => {
1268
+ if (event.defaultPrevented || this.input.disabled) return;
1269
+ const files = clipboardFiles(event.clipboardData);
1270
+ if (!files.length) return;
1271
+ event.preventDefault();
1272
+ this.addAttachments(files);
1273
+ });
1274
+ this.chat.ondragover = event => {
1275
+ if (!event.dataTransfer?.types.includes('Files')) return;
1276
+ event.preventDefault(); event.dataTransfer.dropEffect = this.input.disabled ? 'none' : 'copy';
1277
+ form.toggleAttribute('data-drop',!this.input.disabled);
1278
+ };
1279
+ this.chat.ondragleave = event => { if (!this.chat.contains(event.relatedTarget)) form.removeAttribute('data-drop'); };
1280
+ this.chat.ondragend = () => form.removeAttribute('data-drop');
1281
+ this.chat.ondrop = event => {
1282
+ if (!event.dataTransfer?.files.length) return;
1283
+ event.preventDefault(); form.removeAttribute('data-drop'); this.addAttachments(event.dataTransfer.files);
1284
+ };
1285
+ this.schedule = iconButton('定时任务','M12 7v5l3 2m6-2a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z','session-schedule',() => this.openSchedule());
1286
+ this.schedule.setAttribute('aria-haspopup','dialog');
1287
+ this.stop = iconButton('停止','M6 6h12v12H6Z','session-stop',() => this.submit('stop')); this.stop.hidden = true;
1288
+ this.send = iconButton('发送','M12 20V4m-6 6 6-6 6 6','session-primary'); this.send.type = 'submit';
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
+ };
1297
+ for (const control of [this.attach,this.stop,this.schedule,this.send]) control.dataset.tooltip = '';
395
1298
  form.onsubmit = event => { event.preventDefault(); void this.submit('send'); };
396
- this.chat.replaceChildren(this.chatHeader,this.chatError,this.body,this.jump,this.opNote,form);
1299
+ this.attachments = make('div','session-draft-images'); this.attachments.setAttribute('role','group'); this.attachments.setAttribute('aria-label','待发送附件');
1300
+ this.imageNotice = make('div','session-image-notice session-error'); this.imageNotice.setAttribute('role','status'); this.imageNotice.hidden = true;
1301
+ this.draftStorageNote = make('div','session-image-notice session-error','草稿附件暂未保存,刷新可能会丢失。');
1302
+ this.draftStorageNote.setAttribute('role','status'); this.draftStorageNote.hidden = true;
1303
+ const dialog = this.imageDialog = make('dialog','session-image-dialog'); dialog.setAttribute('aria-label','图片预览');
1304
+ const dismiss = iconButton('关闭图片预览','M6 6l12 12M18 6 6 18','session-image-dismiss',() => dialog.close());
1305
+ dismiss.autofocus = true; dismiss.setAttribute('aria-keyshortcuts','Escape');
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
+ };
1313
+ const settings = make('div','session-compose-settings');
1314
+ this.modelButton = button('',() => this.openTaskSettings('model'),'session-compose-model');
1315
+ this.thinkingButton = button('',() => this.openTaskSettings('thinking'),'session-compose-thinking');
1316
+ this.modelButton.setAttribute('aria-label','切换模型'); this.thinkingButton.setAttribute('aria-label','切换思考强度');
1317
+ const menu = this.settingsMenu = make('div','session-settings-picker'); menu.hidden = true;
1318
+ menu.id = 'session-settings-'+this.page; menu.tabIndex = -1; menu.setAttribute('role','dialog');
1319
+ for (const control of [this.modelButton,this.thinkingButton]) {
1320
+ control.append(make('span')); control.setAttribute('aria-haspopup','dialog');
1321
+ control.setAttribute('aria-controls',menu.id); control.setAttribute('aria-expanded','false');
1322
+ }
1323
+ settings.append(this.modelButton,this.thinkingButton);
1324
+ const trailing = make('div','session-composer-trailing'), controls = make('div','session-composer-controls');
1325
+ controls.append(this.stop,this.schedule,this.send); trailing.append(settings,controls); actions.append(this.attach,trailing);
1326
+ form.append(this.attachments,field,actions,menu);
1327
+ this.draftTools = make('div','session-new-draft-tools'); this.draftTools.hidden = true;
1328
+ this.executionBar = make('div','session-run-status'); this.executionBar.hidden = true; this.executionBar.tabIndex = 0;
1329
+ this.executionBar.setAttribute('role','group'); this.executionBar.setAttribute('aria-label','本轮执行信息');
1330
+ const duration = make('span','session-run-duration');
1331
+ this.elapsedTime = make('time'); duration.append(this.elapsedTime);
1332
+ this.executionModel = make('span','session-run-model'); this.executionThinking = make('span','session-run-thinking');
1333
+ this.executionTokens = make('span','session-run-tokens'); this.executionTokens.hidden = true;
1334
+ this.executionBar.append(duration,this.executionModel,this.executionThinking,this.executionTokens);
1335
+ this.queueList = make('ol','session-prompt-queue'); this.queueList.setAttribute('aria-label','已排队的消息');
1336
+ this.queueRows = new Map(); this.queueEdit = undefined;
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);
1338
+ this.chat.replaceChildren(this.chatHeader,this.chatError,reading,footer,dialog);
397
1339
  this.updateComposer();
398
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
+ }
1376
+ setPlanOpen(open) {
1377
+ this.chat.toggleAttribute('data-plan-open',open);
1378
+ this.planButton.setAttribute('aria-expanded',String(open));
1379
+ }
1380
+ updatePlan(plan = []) {
1381
+ this.headPlan = plan;
1382
+ if (!this.planPanel) return;
1383
+ const hidden = !this.task || !plan.length || Boolean(this.newDraft);
1384
+ this.planPanel.hidden = this.planButton.hidden = hidden;
1385
+ this.body.parentElement?.toggleAttribute('hidden',Boolean(this.newDraft));
1386
+ if (hidden) this.setPlanOpen(false);
1387
+ const signature = JSON.stringify(plan);
1388
+ if (this.planSignature === signature) return;
1389
+ this.planSignature = signature;
1390
+ const progress = plan.filter(step => step.status === 'completed').length+'/'+plan.length;
1391
+ this.planButton.textContent = this.planProgress.textContent = progress;
1392
+ labelButton(this.planButton,'执行计划 '+progress);
1393
+ const names = {pending:'待执行',in_progress:'执行中',completed:'已完成'};
1394
+ this.planSteps.replaceChildren(...plan.map(step => {
1395
+ const item = make('li'); item.dataset.status = step.status;
1396
+ const mark = make('span','session-plan-mark'); mark.setAttribute('aria-hidden','true');
1397
+ item.append(mark,make('span',null,step.text));
1398
+ item.setAttribute('aria-label',(names[step.status] || names.pending)+' · '+step.text);
1399
+ return item;
1400
+ }));
1401
+ }
1402
+ openTaskSettings(preferred) {
1403
+ if (this.newDraft) { this.openDraftSettings(this.newDraft,preferred); return; }
1404
+ const task = this.task?.id, grant = this.csrf;
1405
+ if (!task || !grant || this.selecting || this.task.status === 'closed' || this.pendingSettings.has(task)) return;
1406
+ const anchor = preferred === 'thinking' ? this.thinkingButton : this.modelButton;
1407
+ if (this.settingsMenuState?.anchor === anchor) { this.closeSettingsMenu(true); return; }
1408
+ this.closeSettingsMenu();
1409
+ const menu = this.settingsMenu, choices = make('div','session-settings-options');
1410
+ const note = make('div','session-dialog-status','正在读取…'); note.setAttribute('role','status');
1411
+ const view = this.settingsMenuState = {task,anchor,events:new AbortController()};
1412
+ const current = () => this.settingsMenuState === view && menu.isConnected && this.task?.id === task && this.csrf === grant;
1413
+ menu.replaceChildren(choices,note); menu.setAttribute('aria-label',preferred === 'thinking' ? '选择思考强度' : '选择模型');
1414
+ menu.hidden = false; anchor.setAttribute('aria-expanded','true'); menu.focus({preventScroll:true});
1415
+ const outside = event => {
1416
+ if (!menu.contains(event.target) && !this.modelButton.contains(event.target) && !this.thinkingButton.contains(event.target)) this.closeSettingsMenu();
1417
+ };
1418
+ const {signal} = view.events;
1419
+ document.addEventListener('pointerdown',outside,{signal}); document.addEventListener('focusin',outside,{signal});
1420
+ document.addEventListener('keydown',event => {
1421
+ if (event.key === 'Escape') { event.preventDefault(); this.closeSettingsMenu(true); return; }
1422
+ if (!menu.contains(event.target)) return;
1423
+ const option = event.target.closest('.session-settings-option');
1424
+ if (event.key === 'Enter' && option) { event.preventDefault(); option.click(); return; }
1425
+ if (!['ArrowDown','ArrowUp','Home','End'].includes(event.key)) return;
1426
+ const options = [...choices.querySelectorAll('button:not(:disabled)')]; if (!options.length) return;
1427
+ event.preventDefault();
1428
+ const index = options.indexOf(document.activeElement), last = options.length-1;
1429
+ const next = event.key === 'Home' ? 0 : event.key === 'End' ? last : event.key === 'ArrowDown'
1430
+ ? (index+1)%options.length : index <= 0 ? last : index-1;
1431
+ options[next].focus();
1432
+ },{signal});
1433
+ const showNote = (text,error = false) => {
1434
+ note.textContent = text; note.hidden = !text; note.classList.toggle('session-error',error);
1435
+ };
1436
+ let state;
1437
+ const render = (data,error) => {
1438
+ state = data;
1439
+ const models = preferred === 'model', selected = models ? data.model : data.thinking;
1440
+ const items = models ? data.models.map(item=>[item.id,item.displayName || item.id]) : data.reasoningOptions.map(item=>[item.value,effortLabel(item.value)]);
1441
+ choices.replaceChildren(...items.map(([value,label]) => {
1442
+ const option = button('',() => saveSetting(value),'session-settings-option');
1443
+ option.setAttribute('aria-pressed',String(value === selected));
1444
+ option.append(make('span',null,label));
1445
+ if (value === selected) { const mark = make('span','session-settings-check','✓'); mark.setAttribute('aria-hidden','true'); option.append(mark); }
1446
+ return option;
1447
+ }));
1448
+ showNote(error || (data.pending ? '当前轮次完成后生效。' : items.length ? '' : models ? '没有可选模型。' : '当前模型不支持切换思考强度。'),Boolean(error));
1449
+ const selectedOption = choices.querySelector('[aria-pressed=true]') || choices.firstElementChild;
1450
+ (selectedOption || menu).focus({preventScroll:true});
1451
+ selectedOption?.scrollIntoView({block:'nearest'});
1452
+ };
1453
+ const saveSetting = async value => {
1454
+ if (!current() || !value || this.pendingSettings.has(task)) return;
1455
+ if (value === state[preferred]) { this.closeSettingsMenu(true); return; }
1456
+ this.pendingSettings.add(task); this.updateComposer();
1457
+ menu.focus({preventScroll:true});
1458
+ for (const choice of choices.children) choice.disabled = true;
1459
+ showNote('正在保存…');
1460
+ let saved = false;
1461
+ try {
1462
+ const data = await this.fetch('/task-settings',{body:{task,setting:preferred,value},timeout:60_000});
1463
+ if (!data.pending && this.task?.id === task && this.csrf === grant) {
1464
+ Object.assign(this.task,{model:data.model,provider:data.provider,thinking:data.thinking}); this.renderChatHeader();
1465
+ }
1466
+ if (current() && data.pending) render(data);
1467
+ saved = !data.pending;
1468
+ } catch (error) { if (current()) render(state,error.message); }
1469
+ finally {
1470
+ this.pendingSettings.delete(task); if (this.task?.id === task) this.updateComposer();
1471
+ if (saved && current()) this.closeSettingsMenu(true);
1472
+ }
1473
+ };
1474
+ void this.fetch('/task-settings',{params:{task},timeout:60_000}).then(data => {
1475
+ if (current()) render(data);
1476
+ }).catch(error => { if (current()) showNote(error.message,true); });
1477
+ }
1478
+ closeSettingsMenu(focus = false) {
1479
+ const view = this.settingsMenuState; if (!view) return;
1480
+ this.settingsMenuState = undefined; view.events.abort();
1481
+ this.settingsMenu.hidden = true; view.anchor.setAttribute('aria-expanded','false');
1482
+ if (focus && !view.anchor.disabled) view.anchor.focus({preventScroll:true});
1483
+ }
1484
+ openDraftSettings(draft,preferred) {
1485
+ if (!draft.agents?.length || draft.sending || this.settingsDialog?.open) return;
1486
+ const dialog = this.settingsDialog = this.createDialog('运行设置',this.chat);
1487
+ const anchor = preferred === 'thinking' ? this.thinkingButton : this.modelButton;
1488
+ dialog.id = this.settingsMenu.id+'-draft';
1489
+ anchor.setAttribute('aria-controls',dialog.id); anchor.setAttribute('aria-expanded','true');
1490
+ const form = make('form'), agent = make('select'), model = make('select'), thinking = make('select');
1491
+ const note = make('div','session-dialog-status'); note.setAttribute('role','status');
1492
+ const options = (node,items,value,fallback) => {
1493
+ node.replaceChildren();
1494
+ for (const [key,label] of [[null,fallback],...items]) {
1495
+ const option = make('option',null,label); option.value = key || ''; option.selected = (key || undefined) === value; node.append(option);
1496
+ }
1497
+ node.disabled = !items.length;
1498
+ };
1499
+ options(agent,draft.agents.map(item=>[item.name,item.title]),draft.agent,'选择 Agent');
1500
+ this.dialogField(form,'Agent',agent); this.dialogField(form,'模型',model); this.dialogField(form,'思考强度',thinking);
1501
+ form.append(note); dialog.append(form); form.onsubmit = event => event.preventDefault();
1502
+ dialog.addEventListener('close',() => {
1503
+ anchor.setAttribute('aria-controls',this.settingsMenu.id); anchor.setAttribute('aria-expanded','false'); dialog.remove();
1504
+ },{once:true});
1505
+ dialog.showModal();
1506
+ let details, sequence = 0;
1507
+ const renderThinking = () => {
1508
+ const selected = details.models.find(item=>item.id === (draft.model || details.model)) ?? details.models.find(item=>item.isDefault);
1509
+ const levels = selected?.supportedReasoningEfforts || [];
1510
+ if (draft.thinking && !levels.some(item=>item.value === draft.thinking)) draft.thinking = undefined;
1511
+ options(thinking,levels.map(item=>[item.value,effortLabel(item.value)]),draft.thinking,'使用模型默认值');
1512
+ };
1513
+ const load = async () => {
1514
+ const version = ++sequence, current = () => dialog.open && this.newDraft === draft && sequence === version;
1515
+ model.disabled = thinking.disabled = true; note.textContent = '正在读取…';
1516
+ if (!draft.agent) return;
1517
+ try {
1518
+ const data = await this.fetch('/draft-settings',{params:{agent:draft.agent},timeout:60_000});
1519
+ if (!current()) return;
1520
+ details = data; options(model,data.models.map(item=>[item.id,item.displayName || item.id]),draft.model,'使用 Agent 默认模型');
1521
+ renderThinking(); note.textContent = '发送第一条消息时应用。';
1522
+ (preferred === 'thinking' && !thinking.disabled ? thinking : model).focus();
1523
+ } catch (error) { if (current()) note.textContent = error.message; }
1524
+ };
1525
+ agent.onchange = () => {
1526
+ if (!agent.value) return;
1527
+ Object.assign(draft,{agent:agent.value,model:undefined,thinking:undefined,request:uuid()});
1528
+ this.updateComposer(); void load();
1529
+ };
1530
+ model.onchange = () => { draft.model = model.value || undefined; draft.request = uuid(); renderThinking(); this.saveNewTaskDraft(); this.updateComposer(); };
1531
+ thinking.onchange = () => { draft.thinking = thinking.value || undefined; draft.request = uuid(); this.saveNewTaskDraft(); this.updateComposer(); };
1532
+ void load();
1533
+ }
399
1534
  setChatError(message, retry = false, action) {
400
1535
  if (!this.chatError?.isConnected) return;
401
1536
  this.chatError.replaceChildren(make('span',null,message)); this.chatError.hidden = !message;
402
1537
  if (retry || action) this.chatError.append(button('重试',action || (() => this.refreshConversation(true)),'session-quiet'));
403
1538
  }
404
1539
  renderChatHeader() {
405
- const task = this.task;
406
- this.chatTitle.textContent = task?.title || '聊天'; this.chatTitle.title = this.chatTitle.textContent;
407
- this.chatMeta.replaceChildren();
1540
+ const task = this.task, draft = Boolean(this.newDraft);
1541
+ setText(this.chatTitle,draft ? '新建任务' : task ? task.title || '未命名任务' : '聊天');
1542
+ this.chatMeta.hidden = draft || !task;
1543
+ if (draft) return;
1544
+ this.app.updateTaskTitle(task);
408
1545
  if (!task) return;
409
- const badge = make('span','session-state',status(task.status)); badge.dataset.status = task.status;
410
- const info = make('span','session-model',[task.agent,task.provider,task.model].filter(Boolean).join(' · ')); info.title = info.textContent;
411
- this.chatMeta.append(badge,info);
1546
+ const {turnCount,totalTokens,storageSize} = task.metrics ?? {};
1547
+ const items = [
1548
+ [this.chatState,status(task.status)],
1549
+ [this.chatAgent,task.agent],
1550
+ [this.chatTurns,Number.isSafeInteger(turnCount) ? headerNumbers.format(turnCount)+' 轮' : ''],
1551
+ [this.chatTokens,Number.isSafeInteger(totalTokens) ? headerTokens.format(totalTokens)+' tokens' : ''],
1552
+ [this.chatStorage,storageSize ? '磁盘 '+storageSize : ''],
1553
+ ];
1554
+ for (const [node,text] of items) {
1555
+ setText(node,text || ''); node.hidden = !text;
1556
+ }
1557
+ this.chatState.dataset.status = task.status;
412
1558
  }
413
1559
  renderConversation() {
414
1560
  this.renderChatHeader(); this.redraw(); this.updateComposer();
415
1561
  this.older.hidden = !this.more;
416
- if (this.anchored) this.jump.hidden = false;
1562
+ this.jump.hidden = this.atBottom();
417
1563
  }
418
1564
  redraw() {
419
- const position = this.pendingPosition || this.position();
420
- if (!this.turns.length) this.timeline.replaceChildren(make('div','session-empty','还没有对话。发送一条消息,开始新的轮次。'));
1565
+ let position = this.pendingPosition || this.position();
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
+ }
1575
+ if (messages.size) for (const turn of this.turns) {
1576
+ if (turn.promptRequestId && messages.has(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);
1582
+ }
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);
1590
+ }
1591
+ if (!this.turns.length) {
1592
+ this.timeline.replaceChildren(...(messages.size ? [] : [make('div','session-empty','还没有对话。发送一条消息,开始新的轮次。')]));
1593
+ this.turnNodes.clear();
1594
+ }
421
1595
  else {
422
1596
  this.timeline.querySelector('.session-empty')?.remove();
1597
+ const pending = new Map([...this.turnNodes].flatMap(([id,entry]) => id.startsWith('pending_') && entry.turn?.promptRequestId
1598
+ ? [[entry.turn.promptRequestId,entry]] : []));
1599
+ for (const turn of this.turns) {
1600
+ const entry = pending.get(turn.promptRequestId);
1601
+ if (!entry || turn.id.startsWith('pending_') || this.turnNodes.has(turn.id)) continue;
1602
+ const temporary = entry.node.dataset.turn;
1603
+ this.turnNodes.delete(temporary);
1604
+ entry.node.dataset.turn = turn.id;
1605
+ this.turnNodes.set(turn.id,entry);
1606
+ if (position?.turn === temporary) position = {...position,turn:turn.id};
1607
+ }
423
1608
  const keep = new Set(this.turns.map(turn => turn.id));
424
1609
  for (const [id,state] of this.turnNodes) if (!keep.has(id)) { state.node.remove(); this.turnNodes.delete(id); }
425
1610
  let previous = null;
426
1611
  for (const turn of this.turns) {
427
- const node = this.renderTurn(turn), next = previous ? previous.nextSibling : this.timeline.firstChild;
428
- 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
+ }
429
1619
  previous = node;
430
1620
  }
431
1621
  }
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();
432
1626
  this.pendingPosition = position; this.restorePosition();
433
1627
  }
434
- renderTurn(turn) {
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) {
435
1636
  let entry = this.turnNodes.get(turn.id);
436
1637
  if (!entry) {
437
- const node = make('article','session-turn'); node.dataset.turn = turn.id;
438
- const header = make('div','session-turn-meta'), content = make('div','session-turn-content'), details = make('details','session-turn-details');
439
- const summary = make('summary',null,'执行过程'), body = make('div','session-detail-body');
440
- details.append(summary,body); node.append(header,content,details);
441
- entry = {node,header,content,details,body,rows:new Map()}; this.turnNodes.set(turn.id,entry);
442
- details.ontoggle = () => { if (details.open && !entry.loaded) void this.loadDetail(turn.id,entry); };
443
- }
444
- const signature = JSON.stringify(turn);
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);
1641
+ }
1642
+ const error = op?.error, closed = this.task.status === '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});
445
1648
  if (entry.signature === signature) return entry.node;
446
1649
  entry.signature = signature;
447
- 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'}) : '';
448
- entry.header.textContent = [time,status(turn.status),turn.summary?'仅有摘要':null,turn.delivered === false?'飞书待投递':null].filter(Boolean).join(' · ');
449
- const rows = new Map();
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;
1652
+ const rows = new Map(), usedGroups = new Set();
1653
+ const visibleTools = turn.compact ? new Set(turn.timeline.flatMap(item => item.kind === 'execution' ? item.tools.map(tool => tool.id) : [])) : undefined;
1654
+ const groupsByTool = new Map();
1655
+ for (const existing of entry.rows.values()) {
1656
+ for (const toolId of existing.rows?.keys() || []) groupsByTool.set(toolId,existing);
1657
+ }
450
1658
  const place = (key, value, build) => {
451
1659
  const old = entry.rows.get(key), signature = JSON.stringify(value);
452
1660
  rows.set(key,old?.signature === signature ? old : {signature,node:build()});
453
1661
  };
454
- const message = (key, name, role, text, images, answer) => place(key,[role,text,images,answer],() => {
455
- const node = make('section','session-message '+role); node.append(make('div','session-message-label',name));
456
- if (text) node.append(make('div','session-message-text',text));
457
- if (images?.length) {
458
- const attachments = make('div','session-message-images');
459
- for (const [index,src] of images.entries()) {
460
- if (!src) { attachments.append(make('span','session-image-unavailable','图片不可用')); continue; }
461
- const image = make('img'); image.alt = `附件 ${index+1}`; image.loading = 'lazy'; image.decoding = 'async'; image.src = src;
462
- attachments.append(image);
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]);
1666
+ if (previous?.signature === signature) { rows.set(key,previous); return; }
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
+ }
463
1682
  }
464
- node.append(attachments);
465
- }
466
- if (answer) {
467
- const rich = make('div','markdown-body'); rich.innerHTML = answer.html;
468
- rich.onclick = event => {
469
- const a = event.target.closest('[data-chat-file]'); if (!a || event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
470
- event.preventDefault(); this.app.openChatFile(a.dataset.chatFile,'file',a.getAttribute('href')?.slice(1)?a.getAttribute('href'):undefined);
471
- };
472
- node.append(rich); if (answer.truncated) node.append(make('small','session-muted','回答较长,此处只显示前一部分。'));
1683
+ window.agentBotLiveMarkup.patchNode(previous.node,node);
1684
+ Object.assign(previous,{signature,startedAt}); rows.set(key,previous);
1685
+ } else rows.set(key,{signature,node,startedAt});
1686
+ };
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);
1690
+ for (const item of turn.timeline) {
1691
+ const key = item.kind === 'user' && item.requestId ? 'steer:'+item.requestId : 'activity:'+item.id;
1692
+ if (item.kind === 'execution') {
1693
+ const exact = entry.rows.get(key);
1694
+ const old = exact && !usedGroups.has(exact) ? exact
1695
+ : item.tools.map(tool => groupsByTool.get(tool.id)).find(group => group && !usedGroups.has(group));
1696
+ const group = this.executionGroup(turn,item,old,visibleTools);
1697
+ usedGroups.add(group); rows.set(key,group);
473
1698
  }
474
- return node;
475
- });
476
- if (turn.prompt || turn.promptImages?.length) message('prompt','你','user',turn.prompt,turn.promptImages);
477
- for (const item of turn.messages) message('message:'+item.id,item.role === 'user'?'你 · 追加':'Agent',item.role,item.text,item.images,item.rich);
478
- if (turn.answer) message('answer','Agent','assistant',undefined,undefined,turn.answer);
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));
1715
+ }
1716
+ if (turn.hasDetails) rows.set('overview',this.executionOverview(turn,entry.rows.get('overview')));
1717
+ if (turn.compact) place('compact',true,() => make('p','session-muted session-compact','此轮的部分活动记录已不可用。'));
1718
+ if (turn.answer) message('answer','assistant',undefined,undefined,turn.answer);
479
1719
  if (turn.error) place('error',turn.error,() => make('p','session-error session-turn-error',turn.error));
480
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
+ }
481
1732
  if (!rows.size) place('waiting',true,() => make('div','session-muted','正在等待 Agent 的输出…'));
482
- for (const [key,old] of entry.rows) if (rows.get(key) !== old) old.node.remove();
483
- let next = entry.content.firstChild;
484
- for (const {node} of rows.values()) {
485
- if (node !== next) entry.content.insertBefore(node,next);
486
- next = node.nextSibling;
487
- }
488
- entry.rows = rows;
489
- if (entry.details.open && entry.loaded && entry.loadedStatus !== turn.status) { entry.loaded = false; void this.loadDetail(turn.id,entry); }
490
- entry.status = turn.status; return entry.node;
491
- }
492
- async loadDetail(id, entry) {
493
- if (entry.loading || !this.task) return;
494
- const task = this.task.id, generation = this.generation; entry.loading = true;
495
- entry.body.replaceChildren(make('span','session-muted','正在读取执行过程…'));
1733
+ rows.set('meta',entry.rows.get('meta') ?? {node:entry.meta});
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
+ }
1740
+ syncRows(entry.content,entry.rows,displayed);
1741
+ entry.rows = displayed;
1742
+ return entry.node;
1743
+ }
1744
+ answerActions(turn,closed,showActions) {
1745
+ const row = make('div','session-answer-actions'), feedback = make('span','session-muted');
1746
+ row.setAttribute('role','group'); row.setAttribute('aria-label',showActions ? '最终回答操作' : '轮次信息');
1747
+ feedback.setAttribute('role','status');
1748
+ const actions = showActions ? [
1749
+ ['copy','复制 Markdown','M9 9h11v12H9zM15 9V4H4v12h5'],
1750
+ ['download','下载 Markdown','M12 3v12m-5-5 5 5 5-5M5 16v5h14v-5'],
1751
+ ['reset','重置当前聊天到这一轮','M5 5v14M19 6l-9 6 9 6z'],
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'],
1753
+ ] : [];
1754
+ const task = this.task.id;
1755
+ for (const [action,label,path] of actions) {
1756
+ const control = iconButton(label,path,'session-answer-action',() => void this.runAnswerAction(task,turn,action,control,feedback));
1757
+ control.dataset.answerAction = action;
1758
+ control.dataset.tooltip = label;
1759
+ control.disabled = action === 'reset' ? closed || turn.status !== 'completed'
1760
+ : action === 'fork' && turn.status !== 'completed';
1761
+ row.append(control);
1762
+ }
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'));
1773
+ return row;
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
+ }
1803
+ async runAnswerAction(task, turn, action, control, feedback) {
1804
+ const generation = this.generation, mutates = action === 'reset' || action === 'fork';
1805
+ if (control.disabled || task !== this.task?.id || mutates && (this.selecting || this.pendingTurnActions.has(task))) return;
1806
+ if (mutates) this.pendingTurnActions.add(task);
1807
+ control.disabled = true; feedback.textContent = '';
496
1808
  try {
497
- const data = await this.fetch('/detail',{params:{task,turn:id}});
498
- if (generation !== this.generation || this.turnNodes.get(id) !== entry) return;
499
- entry.body.replaceChildren();
500
- if (data.plan.length) {
501
- const list = make('ol','session-plan'); for (const item of data.plan) list.append(make('li',null,`${item.status === 'completed'?'✓ ':''}${item.text}`)); entry.body.append(list);
502
- }
503
- for (const tool of data.tools) {
504
- const details = make('details','session-tool'), summary = make('summary',null,`${tool.title || '工具'} · ${status(tool.status)}`), output = make('div','session-tool-output');
505
- details.append(summary); if (tool.command) details.append(make('pre',null,tool.command)); details.append(output); entry.body.append(details);
506
- if (!tool.hasOutput) continue;
507
- let loading = false, loaded = false;
508
- const fetchOutput = async () => {
509
- if (loading || loaded || generation !== this.generation) return;
510
- loading = true; output.replaceChildren(make('span','session-muted','正在读取工具输出…'));
511
- try {
512
- const result = await this.fetch('/tool',{params:{task,turn:id,tool:tool.id}});
513
- if (!output.isConnected || generation !== this.generation) return;
514
- loaded = tool.status !== 'running'; output.replaceChildren();
515
- const text = [result.output,result.error].filter(Boolean).join('\n\n');
516
- if (text) output.append(make('pre',null,text)); else output.append(make('span','session-muted','该工具暂无输出。'));
517
- if (result.truncated) output.append(make('p','session-muted','仅显示部分输出。完整记录请在原飞书会话打开 Turn Preview。'));
518
- } catch (error) {
519
- if (output.isConnected && generation === this.generation) output.replaceChildren(make('span','session-error',error.message),button('重试',fetchOutput,'session-quiet'));
520
- } finally { loading = false; }
521
- };
522
- details.ontoggle = () => { if (details.open) void fetchOutput(); };
1809
+ if (action === 'copy' || action === 'download') {
1810
+ const answer = this.fetch('/answer',{params:{task,turn:turn.id}});
1811
+ if (action === 'copy') await window.agentBotMarkdown.copy(answer.then(data => data.markdown));
1812
+ else {
1813
+ const {markdown,filename} = await answer;
1814
+ window.agentBotMarkdown.download(markdown,filename);
1815
+ }
1816
+ feedback.textContent = action === 'copy' ? '已复制 Markdown' : '已开始下载';
1817
+ } else {
1818
+ feedback.textContent = action === 'reset' ? '正在重置…' : '正在创建分支…';
1819
+ const data = await this.fetch('/turn-action',{body:{task,turn:turn.id,action},timeout:300_000});
1820
+ if (this.generation !== generation || this.task?.id !== task) return;
1821
+ if (action === 'reset') {
1822
+ await this.refreshConversation(true,{anchor:turn.id,position:{bottom:true}});
1823
+ feedback.textContent = '已重置到这一轮';
1824
+ } else {
1825
+ feedback.textContent = '已创建分支';
1826
+ await this.choose(data.id);
1827
+ void this.loadGroups(true);
1828
+ }
1829
+ }
1830
+ } catch (error) {
1831
+ feedback.textContent = error.status ? error.message : action === 'copy'
1832
+ ? '复制失败,请检查剪贴板权限或网络连接。' : action === 'download' ? '下载失败,请重试。' : '无法确认操作结果,请刷新任务列表。';
1833
+ } finally {
1834
+ if (mutates) this.pendingTurnActions.delete(task);
1835
+ control.disabled = false;
1836
+ }
1837
+ }
1838
+ messageNode(role,text,images,answer,note,outgoing,files,startedAt,quotes) {
1839
+ const node = make('section','session-message '+role+(note?' '+note:''));
1840
+ node.setAttribute('aria-label',role === 'user' ? '你的消息' : note === 'session-commentary' ? '进展说明'
1841
+ : note ? '运行提示' : 'Agent 回答');
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
+ }
1853
+ if (images?.length) {
1854
+ const attachments = make('div','session-message-images');
1855
+ for (const [index,item] of images.entries()) {
1856
+ const src = typeof item === 'string' ? item : item?.src;
1857
+ if (!src) { attachments.append(make('span','session-image-unavailable','图片不可用')); continue; }
1858
+ const image = make('img'); image.alt = `附件 ${index+1}`; image.loading = 'lazy'; image.decoding = 'async'; image.src = src;
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
+ }
1864
+ }
1865
+ node.append(attachments);
1866
+ }
1867
+ if (files?.length) {
1868
+ const list = make('ul','session-message-files');
1869
+ for (const file of files) {
1870
+ const item = make('li'), label = make(file.url?'a':'span',null,file.name);
1871
+ if (file.url) label.href = file.url;
1872
+ item.append(label); list.append(item);
523
1873
  }
524
- for (const change of data.changes) {
525
- entry.body.append(change.entry ? button(change.name,() => this.app.openChatFile(change.entry,'diff'), 'session-quiet') : make('div','session-muted',change.name));
1874
+ node.append(list);
1875
+ }
1876
+ if (answer) {
1877
+ node.append(this.markdown(answer));
1878
+ if (answer.truncated) node.append(make('small','session-muted','内容较长,此处只显示前一部分。'));
1879
+ }
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'));
1892
+ return row;
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
+ }
1914
+ renderOutbox(messages,matched) {
1915
+ const entries = new Map();
1916
+ for (const [id,message] of messages) {
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)});
526
1925
  }
527
- if (data.changes.length) entry.body.append(make('div','session-muted','文件名来自本轮记录,打开的是当前 Git 工作区的变更。'));
528
- if (!entry.body.firstChild || data.compact) entry.body.append(make('div','session-muted',entry.body.firstChild?'此处显示已保存的执行摘要。':'暂无可显示的执行过程。'));
529
- entry.loaded = true; entry.loadedStatus = entry.status;
1926
+ syncRows(entry.content,entry.rows,rows);
1927
+ entry.rows = rows; entries.set(id,entry);
1928
+ }
1929
+ syncRows(this.outbox,this.outboxRows,entries); this.outboxRows = entries;
1930
+ }
1931
+ markdown(data) {
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'));
1934
+ for (const image of rich.querySelectorAll('img[src]')) this.prepareChatImage(image);
1935
+ return rich;
1936
+ }
1937
+ prepareChatImage(image) {
1938
+ image.dataset.chatImage = ''; image.tabIndex = 0;
1939
+ image.setAttribute('role','button'); image.setAttribute('aria-label',image.alt ? '查看大图 · '+image.alt : '查看大图');
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);
1972
+ }
1973
+ chatImageKey(image) {
1974
+ try {
1975
+ const url = new URL(image.getAttribute('src'),window.location.href);
1976
+ if (!['http:','https:'].includes(url.protocol) || url.origin !== window.location.origin) return;
1977
+ if (url.pathname === this.base+'/image') url.searchParams.delete('proof');
1978
+ return url.pathname+url.search;
1979
+ } catch { /* An image with no usable URL cannot have a cached size. */ }
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
+ }
1994
+ applyChatImageSize(image,size) {
1995
+ if (!this.validChatImageSize(size)) return;
1996
+ const [width,height] = size;
1997
+ image.setAttribute('width',String(width)); image.setAttribute('height',String(height));
1998
+ image.style.setProperty('--chat-image-width',width+'px');
1999
+ image.style.setProperty('--chat-image-ratio',String(width/height));
2000
+ image.dataset.chatImageSized = '';
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
+ }
2009
+ rememberChatImageSize(image) {
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;
2014
+ this.chatImageSizes.delete(key); this.chatImageSizes.set(key,size);
2015
+ if (this.chatImageSizes.size > chatImageSizeLimit) this.chatImageSizes.delete(this.chatImageSizes.keys().next().value);
2016
+ save(this.chatImageSizeKey,[...this.chatImageSizes],'sessionStorage');
2017
+ }
2018
+ previewChatImage(event) {
2019
+ const image = event.target.closest?.('[data-chat-image][src]');
2020
+ if (!image || event.defaultPrevented) return false;
2021
+ event.preventDefault();
2022
+ this.openImage(image.currentSrc || image.src,image.alt,declaredChatImageSize(image.getAttribute('src')) ?? image.previewDisplaySize,
2023
+ [image.naturalWidth,image.naturalHeight]);
2024
+ return true;
2025
+ }
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) {
2045
+ if (this.imageDialog.open) return;
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;
2062
+ this.imageDialog.showModal();
2063
+ }
2064
+ keepExecutionTitle(summary, change) {
2065
+ const body = this.body, title = summary?.getBoundingClientRect();
2066
+ const viewport = body?.getBoundingClientRect();
2067
+ if (!this.task || !body?.clientHeight || !title || title.bottom <= viewport.top || title.top >= viewport.bottom) {
2068
+ change(); return;
2069
+ }
2070
+ change();
2071
+ const shift = summary.getBoundingClientRect().top-title.top;
2072
+ if (shift) body.scrollTop += shift;
2073
+ // The resize observer also uses this position when newly expanded content grows the timeline.
2074
+ this.pendingPosition = this.restoredPosition = undefined;
2075
+ this.lastPosition = this.position(true);
2076
+ this.jump.hidden = this.atBottom();
2077
+ }
2078
+ bindExecutionSummary(details, summary) {
2079
+ summary.onclick = event => {
2080
+ if (event.defaultPrevented || details.open) return;
2081
+ event.preventDefault();
2082
+ this.keepExecutionTitle(summary,() => { details.open = true; });
2083
+ };
2084
+ }
2085
+ disclosure(className,title) {
2086
+ const node = make('details',className), summary = make('summary'), label = make('span','session-execution-title',title), body = make('div','session-execution-body');
2087
+ const badge = make('span','session-execution-badge');
2088
+ summary.append(label,badge); node.append(summary,body);
2089
+ this.bindExecutionSummary(node,summary);
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;
2158
+ }
2159
+ executionGroup(turn,item,existing,visibleTools) {
2160
+ let group = existing;
2161
+ if (!group) {
2162
+ group = this.disclosure('session-execution','');
2163
+ this.rollingTitle(group.label);
2164
+ group.tools = make('div','session-tools'); group.rows = new Map();
2165
+ group.body.append(group.tools);
2166
+ group.node.ontoggle = () => this.refreshExecutionGroup(group);
2167
+ }
2168
+ group.node.dataset.executionGroup = item.id;
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);
2172
+ const rows = new Map(visibleTools ? [...group.rows].filter(([id,row]) => row.node.open && !visibleTools.has(id)) : []);
2173
+ for (const tool of item.tools) rows.set(tool.id,this.executionTool(turn,tool,group));
2174
+ setText(group.badge,rows.size ? `· ${rows.size} 项工具` : '');
2175
+ syncRows(group.tools,group.rows,rows); group.rows = rows;
2176
+ this.refreshExecutionGroup(group);
2177
+ return group;
2178
+ }
2179
+ refreshExecutionGroup(group) {
2180
+ if (!group.node.open) return;
2181
+ for (const row of group.rows.values()) if (row.node.open) void this.loadExecution(row.body,row.request);
2182
+ }
2183
+ executionTool(turn,tool,group) {
2184
+ let row = group.rows.get(tool.id);
2185
+ if (!row) {
2186
+ row = this.disclosure('session-tool',''); row.node.dataset.tool = tool.id;
2187
+ row.node.ontoggle = () => { if (group.node.open && row.node.open) void this.loadExecution(row.body,row.request); };
2188
+ }
2189
+ const kind = tool.kind || (tool.command ? 'command' : 'tool');
2190
+ row.node.dataset.toolKind = kind;
2191
+ this.setExecutionIcon(row,kind);
2192
+ row.label.textContent = tool.title?.replace(/\s+/gu,' ').trim() || '工具';
2193
+ row.label.classList.toggle('session-tool-command-title',tool.command === true);
2194
+ row.badge.textContent = tool.status === 'completed' ? '' : status(tool.status); row.badge.dataset.status = tool.status;
2195
+ row.request = {route:'/tool',params:{turn:turn.id,tool:tool.id},tool,revision:`${turn.id}:${tool.status}:${tool.completedAt}:${tool.status === 'running' ? turn.status : ''}`};
2196
+ return row;
2197
+ }
2198
+ executionOverview(turn,existing) {
2199
+ const row = existing || this.disclosure('session-execution','文件变更');
2200
+ this.setExecutionIcon(row,'file_change');
2201
+ setText(row.badge,turn.fileChangeCount ? ` · ${turn.fileChangeCount}` : '');
2202
+ row.request = {route:'/detail',params:{turn:turn.id},revision:turn.detailRevision || turn.status};
2203
+ row.node.ontoggle = () => { if (row.node.open) void this.loadExecution(row.body,row.request); };
2204
+ if (row.node.open) void this.loadExecution(row.body,row.request);
2205
+ return row;
2206
+ }
2207
+ async loadExecution(body, request) {
2208
+ if (!this.task || !request || body.loading === request.revision || body.loaded === request.revision) return;
2209
+ const generation = this.generation, task = this.task.id;
2210
+ body.loading = request.revision;
2211
+ const update = change => this.keepExecutionTitle(body.previousElementSibling,change);
2212
+ if (!body.firstChild) update(() => body.append(make('p','session-muted','正在读取…')));
2213
+ const current = () => body.isConnected && generation === this.generation && body.loading === request.revision;
2214
+ try {
2215
+ const data = await this.fetch(request.route,{params:{task,...request.params}});
2216
+ if (!current()) return;
2217
+ const nodes = [];
2218
+ if (request.route === '/tool') {
2219
+ update(() => this.renderToolDetails(body,request,data,task,generation));
2220
+ body.loaded = request.revision;
2221
+ return;
2222
+ }
2223
+ const changes = this.renderToolFiles(data.changes,data.changesTruncated);
2224
+ if (changes) nodes.push(changes);
2225
+ if (data.truncated) nodes.push(make('p','session-muted','仅显示部分内容,完整记录请查看 Turn Preview。'));
2226
+ update(() => body.replaceChildren(...nodes)); body.loaded = request.revision;
530
2227
  } catch (error) {
531
- if (generation === this.generation) entry.body.replaceChildren(make('span','session-error',error.message),button('重试',() => this.loadDetail(id,entry),'session-quiet'));
532
- } finally { entry.loading = false; }
2228
+ if (current()) update(() => body.replaceChildren(make('span','session-error',error.message),button('重试',() => this.loadExecution(body,request),'session-quiet')));
2229
+ } finally {
2230
+ if (body.loading === request.revision) body.loading = undefined;
2231
+ }
2232
+ }
2233
+ renderToolFiles(files, truncated, tool, opened) {
2234
+ if (!files?.length) return;
2235
+ const section = make('div','session-tool-files'), list = make('ul');
2236
+ list.setAttribute('aria-label','此工具修改的文件'); section.append(list);
2237
+ for (const file of files) {
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) {
2242
+ name.setAttribute('href',this.app.chatDiffUrl(file));
2243
+ name.setAttribute('aria-label','查看 '+file.name+' 的 Diff');
2244
+ name.onclick = event => {
2245
+ if (!plainLinkClick(event)) return;
2246
+ event.preventDefault();
2247
+ this.app.openChatFile(file.entry,'diff',undefined,file.source,file.original);
2248
+ };
2249
+ }
2250
+ header.append(name);
2251
+ const counts = make('span','session-tool-file-counts');
2252
+ if (Number.isSafeInteger(file.additions) && file.additions > 0) counts.append(make('span','session-tool-file-additions','+'+file.additions));
2253
+ if (Number.isSafeInteger(file.deletions) && file.deletions > 0) counts.append(make('span','session-tool-file-deletions','−'+file.deletions));
2254
+ if (file.additions === 0 && file.deletions === 0) counts.append(make('span',null,'0'));
2255
+ if (counts.childElementCount) header.append(counts);
2256
+ if (file.patch) {
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);
2261
+ const patch = make('pre'); patch.tabIndex = 0; patch.setAttribute('aria-label','本次修改的补丁');
2262
+ const code = make('code');
2263
+ if (file.patchHtml) code.innerHTML = file.patchHtml;
2264
+ else code.textContent = file.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);
2274
+ if (file.patchTruncated) details.append(make('small','session-muted','已保存补丁的开头。'));
2275
+ item.append(details);
2276
+ } else item.append(header);
2277
+ list.append(item);
2278
+ }
2279
+ if (truncated) section.append(make('small','session-muted','仅显示前 '+files.length+' 个文件。'));
2280
+ return section;
2281
+ }
2282
+ renderToolDetails(body,request,first,task,generation) {
2283
+ const texts = make('div','session-tool-texts'), previous = body.querySelector('.session-tool-texts');
2284
+ texts.tabIndex = 0; texts.setAttribute('role','region'); texts.setAttribute('aria-label','工具命令与输出');
2285
+ const fields = [['command','命令','$'],['output',first.outputIsError?'执行错误':'结果'],['error','错误']];
2286
+ const blocks = new Map();
2287
+ const more = button('加载更多输出',() => void loadMore(true),'session-more');
2288
+ const issue = make('p','session-muted'); issue.setAttribute('role','status');
2289
+ let offset, revision = first.revision, failure;
2290
+ const current = () => generation === this.generation && more.isConnected && body.loaded === request.revision;
2291
+ const loadMore = async explicit => {
2292
+ if (!current() || offset === undefined || more.disabled || failure && !explicit) return;
2293
+ if (failure === 409) { body.loaded = undefined; void this.loadExecution(body,request); return; }
2294
+ more.disabled = true; more.textContent = '正在读取…';
2295
+ try {
2296
+ const data = await this.fetch('/tool',{params:{task,...request.params,offset,revision}});
2297
+ if (current()) append(data);
2298
+ } catch (error) {
2299
+ if (current()) {
2300
+ failure = error.status ?? true; more.textContent = failure === 409?'重新读取':'重试读取';
2301
+ issue.textContent = error.message; issue.hidden = false;
2302
+ }
2303
+ } finally { more.disabled = false; }
2304
+ };
2305
+ const append = data => {
2306
+ for (const [key,label,marker] of fields) {
2307
+ const page = key === 'command' ? data.displayCommand ?? data.command : data[key];
2308
+ if (!page) continue;
2309
+ if (!blocks.has(key)) {
2310
+ const section = make('div','session-tool-log session-tool-'+key+'-section'), pre = make('pre','session-tool-'+key);
2311
+ pre.setAttribute('aria-label',label);
2312
+ if (key === 'error' || key === 'output' && first.outputIsError) {
2313
+ section.classList.add('session-tool-error-section');
2314
+ section.append(make('span','session-tool-error-label',label));
2315
+ }
2316
+ if (marker) {
2317
+ const mark = make('span','session-tool-marker',marker); mark.setAttribute('aria-hidden','true'); section.append(mark);
2318
+ }
2319
+ section.append(pre); blocks.set(key,{pre,section});
2320
+ }
2321
+ const pre = blocks.get(key).pre, last = pre.lastChild;
2322
+ const joinsPair = last && /[\uD800-\uDBFF]$/u.test(last.data) && /^[\uDC00-\uDFFF]/u.test(page);
2323
+ if (joinsPair) last.appendData(page[0]);
2324
+ pre.append(joinsPair ? page.slice(1) : page);
2325
+ }
2326
+ let index = 0;
2327
+ for (const [key] of fields) {
2328
+ const block = blocks.get(key);
2329
+ if (block && texts.children[index++] !== block.section) texts.insertBefore(block.section,texts.children[index-1] || null);
2330
+ }
2331
+ offset = data.next; revision = data.revision; failure = undefined;
2332
+ more.hidden = offset === undefined; more.textContent = '加载更多输出'; issue.replaceChildren();
2333
+ if (data.partial) issue.textContent = data.reason ? `未能读取原始工具日志:${data.reason}` : '未找到完整的原始工具日志,上方是已保存的摘要。';
2334
+ issue.hidden = !data.partial;
2335
+ };
2336
+ append(first);
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);
2339
+ const empty = !files && !blocks.size && !first.next ? make('p','session-muted','该工具暂无输出。') : undefined;
2340
+ const timing = timeTool(request.tool);
2341
+ const footer = timing ? make('div','session-tool-footer',timing) : undefined;
2342
+ const left = previous?.scrollLeft || 0, top = previous?.scrollTop || 0;
2343
+ const hadFocus = document.activeElement === previous;
2344
+ body.replaceChildren(...(files?[files]:[]),texts,...(empty?[empty]:[]),more,issue,...(footer?[footer]:[]));
2345
+ texts.scrollLeft = left; texts.scrollTop = top;
2346
+ if (hadFocus && blocks.size) texts.focus({preventScroll:true});
2347
+ let lastLeft = texts.scrollLeft, lastTop = texts.scrollTop;
2348
+ texts.addEventListener('scroll',() => {
2349
+ const {scrollLeft,scrollTop,clientWidth,clientHeight,scrollWidth,scrollHeight} = texts;
2350
+ const vertical = scrollHeight-clientHeight;
2351
+ const nearEnd = vertical > 0 ? scrollTop > lastTop && vertical-scrollTop <= 64
2352
+ : scrollLeft > lastLeft && scrollWidth-clientWidth-scrollLeft <= 64;
2353
+ lastLeft = scrollLeft; lastTop = scrollTop;
2354
+ if (clientWidth > 0 && clientHeight > 0 && nearEnd) void loadMore(false);
2355
+ },{passive:true});
533
2356
  }
534
2357
  async loadOlder() {
535
- if (!this.task || !this.more || !this.turns.length || this.older.disabled) return;
536
- const generation = this.generation, task = this.task.id, before = this.turns[0].id;
537
- this.older.disabled = true; this.older.textContent = '正在加载…';
2358
+ if (!this.task || this.selecting || this.refreshing || !this.more || !this.turns.length || this.older.disabled) return;
2359
+ const generation = this.generation, task = this.task.id, before = this.turns[0].id, older = this.older;
2360
+ const current = () => !this.disposed && generation === this.generation && !this.refreshing && this.turns[0]?.id === before;
2361
+ older.disabled = true; older.textContent = '正在加载…';
538
2362
  try {
539
2363
  const data = await this.fetch('/task',{params:{task,before}});
540
- if (generation !== this.generation) return;
2364
+ if (!current()) return;
541
2365
  this.pendingPosition = this.position(); this.turns = [...new Map([...data.turns,...this.turns].map(turn => [turn.id,turn])).values()]; this.more = data.more;
542
2366
  this.renderConversation();
543
- } catch (error) { if (generation === this.generation) this.setChatError('历史读取失败:'+error.message,false,() => error.status === 409 ? this.refreshConversation(false,true) : this.loadOlder()); }
544
- finally { this.older.disabled = false; this.older.textContent = '加载更早的对话'; }
2367
+ } catch (error) { if (current()) this.setChatError('历史读取失败:'+error.message,false,() => error.status === 409 ? this.refreshConversation(false) : this.loadOlder()); }
2368
+ finally { older.disabled = false; older.textContent = '加载更早的对话'; }
545
2369
  }
546
2370
  restoreHistoryPosition(position) {
547
- this.pendingPosition = position;
548
- if (position.bottom && this.anchored) void this.refreshConversation(false,true);
549
- else if (position.turn && !this.turnNodes.has(position.turn)) {
550
- this.anchored = true;
551
- void this.refreshConversation(true);
552
- } else this.restorePosition();
553
- }
554
- atBottom() { return this.body.scrollHeight-this.body.scrollTop-this.body.clientHeight < 36; }
2371
+ if (position.turn && !this.turnNodes.has(position.turn)) void this.refreshConversation(true,{anchor:position.turn,position});
2372
+ else { this.pendingPosition = position; this.restorePosition(); }
2373
+ }
2374
+ jumpToBottom() {
2375
+ this.pendingPosition = {bottom:true}; this.restorePosition();
2376
+ this.jump.hidden = true;
2377
+ this.app.queuePersist();
2378
+ }
2379
+ atBottom() { return this.body.scrollHeight-this.body.scrollTop-this.body.clientHeight <= 2; }
555
2380
  position(measure = false) {
556
2381
  if (this.pendingPosition && !measure) return this.pendingPosition;
557
2382
  if (!this.task || !this.body?.clientHeight) return this.lastPosition;
558
- if (!this.anchored && this.atBottom()) return {bottom:true};
2383
+ if (!measure && this.restoredPosition?.top === this.body.scrollTop) return this.restoredPosition.anchor;
2384
+ if (this.atBottom()) return {bottom:true};
2385
+ return this.visibleChatPosition() || {bottom:true};
2386
+ }
2387
+ visibleChatPosition() {
559
2388
  const top = this.body.getBoundingClientRect().top;
560
2389
  for (const node of this.timeline.children) {
561
2390
  const rect = node.getBoundingClientRect();
562
- if (node.dataset.turn && rect.bottom > top + 1) return {turn:node.dataset.turn,offset:Math.round(top-rect.top)};
2391
+ if (node.dataset.turn && rect.bottom > top + 1) {
2392
+ const turn = node.dataset.turn, target = this.readingTarget(this.turnNodes.get(turn),top);
2393
+ return {turn,offset:Math.round(top-rect.top),...(target ? {target} : {})};
2394
+ }
2395
+ }
2396
+ }
2397
+ readingTarget(turn,top) {
2398
+ for (const [row,{node}] of turn?.rows || []) {
2399
+ const rect = node.getBoundingClientRect?.();
2400
+ if (!rect || rect.top > top+1 || rect.bottom <= top+1) continue;
2401
+ const parts = [...node.querySelectorAll(chatAnchorParts)];
2402
+ for (const [part,element] of parts.entries()) {
2403
+ const bounds = element.getBoundingClientRect?.();
2404
+ if (bounds && bounds.top <= top+1 && bounds.bottom > top+1) return {row,part,offset:Math.round(top-bounds.top)};
2405
+ }
2406
+ return {row,offset:Math.round(top-rect.top)};
563
2407
  }
564
- return {bottom:true};
565
2408
  }
566
2409
  restorePosition() {
567
- if (!this.pendingPosition || !this.body?.clientHeight) return;
2410
+ this.chatBodyHeight = this.body?.clientHeight;
2411
+ if (!this.chatBodyHeight) return;
2412
+ if (!this.pendingPosition) {
2413
+ this.jump.hidden = this.atBottom();
2414
+ return;
2415
+ }
568
2416
  const position = this.pendingPosition; this.pendingPosition = undefined;
569
- if (position.bottom) this.body.scrollTop = this.body.scrollHeight;
2417
+ const turn = position.turn && this.turnNodes.get(position.turn);
2418
+ const target = position.target;
2419
+ const row = target && turn?.rows.get(target.row)?.node;
2420
+ const part = target?.part === undefined ? row : row?.querySelectorAll(chatAnchorParts)[target.part];
2421
+ const node = part || turn?.node;
2422
+ if (!node) this.body.scrollTop = this.body.scrollHeight;
570
2423
  else {
571
- const node = this.turnNodes.get(position.turn)?.node;
572
- if (node) this.body.scrollTop += node.getBoundingClientRect().top - this.body.getBoundingClientRect().top + position.offset;
573
- else this.body.scrollTop = this.body.scrollHeight;
2424
+ const offset = part ? target.offset : position.offset;
2425
+ const top = this.body.scrollTop + node.getBoundingClientRect().top - this.body.getBoundingClientRect().top + offset;
2426
+ this.body.scrollTop = top;
574
2427
  }
575
- this.lastPosition = this.position(true); this.jump.hidden = !this.anchored && this.atBottom();
2428
+ // A short history page or unloaded image can temporarily clamp scrollTop.
2429
+ this.lastPosition = node ? position : {bottom:true};
2430
+ this.restoredPosition = {top:this.body.scrollTop,anchor:this.lastPosition};
2431
+ this.jump.hidden = this.atBottom();
2432
+ }
2433
+ images(id) { return this.imageDrafts.get(id) || noImages; }
2434
+ restoreDraftFiles(task) {
2435
+ const loading = this.fileLoads.get(task);
2436
+ if (loading) return loading;
2437
+ const unpack = attachments => (attachments || []).map(({id,file,preview,annotation,reference}) => annotation || reference
2438
+ ? {id,annotation,reference} : preview ? draftAttachment(file,{id}) : {id,file});
2439
+ this.loadingDraftFiles.add(task);
2440
+ const load = this.draftFiles.read(task).then(record => {
2441
+ if (!record || this.disposed || this.fileLoads.get(task) !== load) return;
2442
+ this.fileRecords.add(task);
2443
+ if (record.draft?.length && !this.imageDrafts.has(task)) this.imageDrafts.set(task,unpack(record.draft));
2444
+ const messages = this.messages(task);
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});
2447
+ }
2448
+ if (messages.size) this.outboxes.set(task,messages);
2449
+ }).catch(() => {}).finally(() => {
2450
+ if (this.fileLoads.get(task) !== load) return;
2451
+ this.loadingDraftFiles.delete(task);
2452
+ if (!this.disposed && (this.newDraft?.id ?? this.task?.id) === task && this.composer?.isConnected) this.updateComposer();
2453
+ });
2454
+ this.fileLoads.set(task,load);
2455
+ return load;
2456
+ }
2457
+ persistDraftFiles(...tasks) {
2458
+ const pack = items => items.map(({id,file,src,annotation,reference}) => ({id,file,preview:Boolean(src),annotation,reference}));
2459
+ const records = [];
2460
+ for (const task of new Set(tasks)) {
2461
+ const draft = pack(this.images(task));
2462
+ const outbox = [...this.messages(task).values()].filter(message => !message.accepted && message.images.length)
2463
+ .map(message => [message.payload,message.error,pack(message.images),message.startedAt]);
2464
+ if (draft.length || outbox.length) {
2465
+ this.fileRecords.add(task); records.push([task,{draft,outbox}]);
2466
+ } else if (this.fileRecords.delete(task)) records.push([task,null]);
2467
+ }
2468
+ if (!records.length) return;
2469
+ return this.draftFiles.write(records).then(() => {
2470
+ if (!this.disposed && this.draftStorageNote) this.updateDraftStorageNotice();
2471
+ });
2472
+ }
2473
+ updateDraftStorageNotice() {
2474
+ const task = this.newDraft?.id ?? this.task?.id;
2475
+ this.draftStorageNote.hidden = !this.draftFiles.failed.has(task);
2476
+ }
2477
+ resetImageDrafts() {
2478
+ for (const images of this.imageDrafts.values()) for (const image of images) revokeAttachment(image);
2479
+ this.imageDrafts.clear();
2480
+ }
2481
+ clearImageInteractions() {
2482
+ if (this.imageDialog?.open) this.imageDialog.close();
2483
+ this.chat.ondragover = this.chat.ondragleave = this.chat.ondragend = this.chat.ondrop = null;
2484
+ }
2485
+ noticeImages(text) {
2486
+ this.imageNotice.textContent = text; this.imageNotice.hidden = !text;
2487
+ }
2488
+ keepComposerPosition(position) {
2489
+ if (position && this.body.clientHeight !== this.chatBodyHeight) {
2490
+ this.pendingPosition = position; this.restorePosition();
2491
+ }
2492
+ }
2493
+ addAttachments(files) {
2494
+ const task = this.newDraft?.id ?? this.task?.id;
2495
+ if (!task || this.input.disabled || !files?.length) return;
2496
+ const position = this.position(true), images = this.images(task), added = [...images];
2497
+ let total = images.reduce((size,image) => size+attachmentBytes(image),0);
2498
+ const issues = new Set();
2499
+ for (const file of files) {
2500
+ if (added.length >= imageCount || file.size > imageLimit || total+file.size > draftLimit) {
2501
+ issues.add('至多 4 个附件,单个不超过 5 MiB,合计不超过 12 MiB。'); continue;
2502
+ }
2503
+ total += file.size;
2504
+ added.push(draftAttachment(file));
2505
+ }
2506
+ if (added.length !== images.length) this.replaceImages(task,added);
2507
+ this.noticeImages([...issues].join(' ')); this.updateComposer(); this.keepComposerPosition(position);
2508
+ if (added.length > images.length) this.attachments.scrollLeft = this.attachments.scrollWidth;
2509
+ return added.length > images.length;
2510
+ }
2511
+ removeImage(task,id,{focus = true} = {}) {
2512
+ const images = this.images(task), index = images.findIndex(image => image.id === id);
2513
+ if (index < 0) return;
2514
+ this.replaceImages(task,images.filter(image => image.id !== id));
2515
+ if ((this.newDraft?.id ?? this.task?.id) === task) {
2516
+ const position = this.position(true);
2517
+ this.noticeImages(''); this.updateComposer(); this.keepComposerPosition(position);
2518
+ if (!focus) return;
2519
+ const next = this.attachments.children[Math.min(index,images.length-2)]?.querySelector('button:not(.session-image-remove)');
2520
+ (next || this.attach).focus({preventScroll:true});
2521
+ }
2522
+ }
2523
+ replaceImages(task,remaining) {
2524
+ const keep = new Set(remaining);
2525
+ for (const image of this.images(task)) if (!keep.has(image)) revokeAttachment(image);
2526
+ if (remaining.length) this.imageDrafts.set(task,remaining);
2527
+ else this.imageDrafts.delete(task);
2528
+ void this.persistDraftFiles(task);
2529
+ }
2530
+ renderPromptQueue() {
2531
+ const task = this.task;
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;
2553
+ if (this.queueEdit && (this.queueEdit.task !== task?.id || this.newDraft || task.status === 'closed')) this.queueEdit = undefined;
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]);
2560
+ if (this.queueList.signature === signature) return;
2561
+ this.queueList.signature = signature; this.queueList.hidden = !prompts.length && !edit;
2562
+ this.queueList.toggleAttribute('data-editing',Boolean(edit));
2563
+ const rows = new Map();
2564
+ for (const [index,prompt] of prompts.entries()) {
2565
+ const dispatching = Boolean(prompt.dispatching || sendingPrompt === prompt.id);
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
+ }
2572
+ setText(edit.number,(index+1)+'.'); rows.set(prompt.id,edit); continue;
2573
+ }
2574
+ const existing = this.queueRows.get(prompt.id);
2575
+ const row = existing?.label ? existing : this.queuedPromptRow(prompt.id);
2576
+ setText(row.number,(index+1)+'.'); setText(row.label,prompt.text || '附件消息');
2577
+ labelButton(row.modify,`修改第 ${index+1} 条排队消息:${row.label.textContent}${prompt.hasAttachments ? ',含附件' : ''}`);
2578
+ row.attachment.hidden = !prompt.hasAttachments;
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; }
2594
+ rows.set(prompt.id,row);
2595
+ }
2596
+ if (edit && !rows.has(edit.prompt)) {
2597
+ edit.left = true; edit.number.hidden = true; edit.submit.disabled = true;
2598
+ setText(edit.note,'这条消息已离开队列,可复制这里的内容。');
2599
+ rows.set(edit.prompt,edit);
2600
+ }
2601
+ syncRows(this.queueList,this.queueRows,rows); this.queueRows = rows;
2602
+ }
2603
+ queuedPromptRow(id) {
2604
+ const node = make('li'), number = make('span','session-queue-number'); number.setAttribute('aria-hidden','true');
2605
+ const modify = button('',() => void this.editQueuedPrompt(id),'session-queue-edit');
2606
+ const label = make('span','session-queued-prompt'); label.dataset.tooltipOverflow = '';
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));
2610
+ const cancel = iconButton('取消排队并恢复到输入框','M6 6l12 12M18 6 6 18','session-cancel-queued',() => void this.restoreQueuedPrompt(id));
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
+ }
2646
+ }
2647
+ async editQueuedPrompt(prompt) {
2648
+ const task = this.task?.id, grant = this.csrf;
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;
2652
+ const node = make('li','session-queue-editing'), number = make('span','session-queue-number'); number.setAttribute('aria-hidden','true');
2653
+ const form = make('form','session-queue-edit-form'), input = make('textarea');
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};
2663
+ form.onsubmit = event => { event.preventDefault(); void this.saveQueueEdit(edit); };
2664
+ input.onkeydown = event => {
2665
+ if (event.isComposing || event.keyCode === 229) return;
2666
+ if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); this.closeQueueEdit(edit); }
2667
+ if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) { event.preventDefault(); void this.saveQueueEdit(edit); }
2668
+ };
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; }
2675
+ try {
2676
+ const data = await this.fetch('/queue/edit',{params:{task,prompt}});
2677
+ if (this.queueEdit !== edit || this.disposed || this.csrf !== grant) return;
2678
+ edit.revision = data.revision; edit.original = input.value = data.text;
2679
+ input.disabled = false; submit.disabled = Boolean(edit.left || edit.dispatching);
2680
+ input.focus({preventScroll:true});
2681
+ } catch (error) { if (this.queueEdit === edit && !this.disposed) setText(note,error.message); }
2682
+ }
2683
+ closeQueueEdit(edit) {
2684
+ if (this.queueEdit !== edit || edit.saving) return;
2685
+ const position = this.position(true);
2686
+ this.queueEdit = undefined; this.renderPromptQueue();
2687
+ this.keepComposerPosition(position);
2688
+ (this.queueRows.get(edit.prompt)?.modify || this.input).focus({preventScroll:true});
2689
+ }
2690
+ async saveQueueEdit(edit) {
2691
+ if (this.queueEdit !== edit || edit.submit.disabled || edit.saving || this.selecting || this.csrf !== edit.grant) return;
2692
+ const {task,prompt,revision,input,submit,note,close} = edit;
2693
+ const before = this.task.queuedPrompts?.find(row => row.id === prompt);
2694
+ if (!before || before.dispatching) return;
2695
+ edit.saving = input.readOnly = close.disabled = submit.disabled = true; setText(note,'正在保存…');
2696
+ try {
2697
+ const result = await this.fetch('/queue/edit',{body:{task,prompt,revision,text:input.value}});
2698
+ if (this.queueEdit !== edit || this.disposed || this.csrf !== edit.grant) return;
2699
+ this.task.queuedPrompts = this.task.queuedPrompts?.map(row => row.id === prompt && row.revision === before.revision ? result : row);
2700
+ edit.saving = false; this.closeQueueEdit(edit);
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); }
2708
+ }
2709
+ async restoreQueuedPrompt(prompt) {
2710
+ const task = this.task?.id, grant = this.csrf, position = this.position(true);
2711
+ if (!task || !grant || this.newDraft || this.input.disabled || this.restoringQueue) return;
2712
+ this.restoringQueue = task; this.updateComposer(); this.setChatError('');
2713
+ const visible = () => this.task?.id === task && !this.newDraft && !this.disposed;
2714
+ const controller = new AbortController(), timeout = setTimeout(() => controller.abort(),30_000);
2715
+ try {
2716
+ const queued = await this.fetch('/queue',{params:{task,prompt},signal:controller.signal});
2717
+ const sources = [...(queued.images || []).map((url,index) => ({url,name:`图片 ${index+1}`})),...(queued.files || [])];
2718
+ const quotes = (queued.quotes || []).map(draftQuote);
2719
+ const previous = this.images(task), text = [queued.text,this.draft(task)].filter(Boolean).join('\n\n');
2720
+ if (text.length > 24_000 || previous.length+sources.length+quotes.length > imageCount) throw new Error('请先处理已有草稿,合并后的消息超出输入框限制。');
2721
+ const files = await Promise.all(sources.map(async ({url,name}) => {
2722
+ if (!url) throw new Error('排队消息中的附件已不可用。');
2723
+ const response = await fetch(url,{cache:'no-store',credentials:'same-origin',signal:controller.signal});
2724
+ if (!response.ok) throw new Error('无法恢复排队消息中的附件。');
2725
+ const blob = await response.blob();
2726
+ return new File([blob],name,{type:blob.type});
2727
+ }));
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) {
2730
+ throw new Error('请先处理已有附件,合并后的消息超出附件大小限制。');
2731
+ }
2732
+ if (this.csrf !== grant || this.disposed) return;
2733
+ const body = {task,prompt,request:uuid(),revision:queued.revision};
2734
+ const cancel = () => this.fetch('/queue',{body});
2735
+ const result = await cancel().catch(error => { if (error.status || this.csrf !== grant) throw error; return cancel(); });
2736
+ if (!result.cancelled) throw new Error('这条消息已离开队列。');
2737
+ this.setDraft(task,text); this.replaceImages(task,[...previous,...files.map(file => draftAttachment(file)),...quotes]);
2738
+ if (visible()) {
2739
+ this.task.queuedPrompts = this.task.queuedPrompts?.filter(row => row.id !== prompt);
2740
+ this.input.value = text;
2741
+ }
2742
+ } catch (error) { if (visible()) this.setChatError(error.message); }
2743
+ finally {
2744
+ clearTimeout(timeout); this.restoringQueue = undefined;
2745
+ if (visible()) { this.updateComposer(); this.keepComposerPosition(position); this.input.focus(); }
2746
+ }
2747
+ }
2748
+ renderDraftImages(task) {
2749
+ const all = this.images(task);
2750
+ if (this.renderedDraftImages === all && this.renderedDraftTask === task && this.attachments.childElementCount === all.length) return;
2751
+ this.renderedDraftImages = all; this.renderedDraftTask = task;
2752
+ this.app.annotations?.updateDrafts(task,all);
2753
+ const existing = new Map([...this.attachments.children].map(node => [node.dataset.image,node]));
2754
+ const nodes = all.map((image,index) => {
2755
+ const name = attachmentName(image) || `附件 ${index+1}`;
2756
+ if (existing.has(image.id)) return existing.get(image.id);
2757
+ const tile = make('div','session-image-tile'); tile.dataset.image = image.id;
2758
+ const remove = iconButton('移除 '+name,'M6 6l12 12M18 6 6 18','session-image-remove',() => this.removeImage(task,image.id));
2759
+ if (!image.src) {
2760
+ tile.classList.add('session-file-tile');
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;
2767
+ if (annotation) {
2768
+ const excerpt = annotation.quote.trim().replace(/\s+/gu,' ');
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);
2785
+ return tile;
2786
+ }
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);
2795
+ const thumbnail = make('img'); thumbnail.alt = ''; thumbnail.src = image.src;
2796
+ thumbnail.onerror = () => {
2797
+ if (!this.images(task).includes(image)) return;
2798
+ this.replaceImages(task,this.images(task).map(entry=>entry === image ? {id:uuid(),file:image.file} : entry));
2799
+ if ((this.newDraft?.id ?? this.task?.id) === task && this.attachments.isConnected) {
2800
+ this.noticeImages('此图片无法预览,已作为文件添加。'); this.updateComposer();
2801
+ }
2802
+ };
2803
+ open.append(thumbnail); tile.append(open,remove);
2804
+ return tile;
2805
+ });
2806
+ const keep = new Set(nodes);
2807
+ for (const node of existing.values()) if (!keep.has(node)) node.remove();
2808
+ for (const node of nodes) if (!node.isConnected) this.attachments.append(node);
2809
+ this.attachments.hidden = !nodes.length;
576
2810
  }
577
2811
  draft(id) { return this.drafts.get(id) ?? read('agentbot-workspace-draft:'+id,'','sessionStorage'); }
578
2812
  setDraft(id,text) { this.drafts.set(id,text); save('agentbot-workspace-draft:'+id,text,'sessionStorage'); }
579
- operation(id) { return this.operations.get(id) ?? read('agentbot-workspace-operation:'+id,null,'sessionStorage'); }
2813
+ hasUnstoredDraft() {
2814
+ const draft = this.newDraft ?? this.parkedDraft;
2815
+ const queueEdit = this.queueEdit;
2816
+ return Boolean(draft && (!this.newDraftSaved || draft.sending) || this.composing || this.restoringQueue
2817
+ || queueEdit?.revision && queueEdit.input.value !== queueEdit.original
2818
+ || this.app.annotations?.hasDraft() || this.draftFiles.hasUnstored());
2819
+ }
2820
+ messages(task) { return this.outboxes.get(task) || new Map(); }
2821
+ saveOutboxes() {
2822
+ const entries = [...this.outboxes].map(([task,messages]) => [task,[...messages].flatMap(([id,message]) =>
2823
+ !message.images.length && !message.accepted ? [[id,message.payload,message.error,message.startedAt]] : [])]);
2824
+ save('agentbot-workspace-outbox',entries.filter(([,items])=>items.length),'sessionStorage');
2825
+ }
2826
+ removeMessage(task,id) {
2827
+ const messages = this.outboxes.get(task), message = messages?.get(id);
2828
+ if (!message) return;
2829
+ messages.delete(id);
2830
+ if (!messages.size) this.outboxes.delete(task);
2831
+ this.saveOutboxes();
2832
+ void this.persistDraftFiles(task);
2833
+ return message;
2834
+ }
2835
+ resetOutboxes() {
2836
+ this.clearChatImageHandoffs();
2837
+ for (const messages of this.outboxes.values()) for (const message of messages.values())
2838
+ for (const image of message.images) revokeAttachment(image);
2839
+ this.outboxes.clear();
2840
+ }
2841
+ operation(id) {
2842
+ const op = this.operations.get(id) ?? read('agentbot-workspace-operation:'+id,null,'sessionStorage');
2843
+ return ['stop','sendQueued'].includes(op?.action) ? op : null;
2844
+ }
580
2845
  setOperation(id,op) {
581
2846
  this.operations.set(id,op); save('agentbot-workspace-operation:'+id,op,'sessionStorage');
582
2847
  if (this.task?.id === id) this.updateComposer();
583
2848
  }
2849
+ renderExecutionStatus() {
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
+ }
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);
2869
+ this.updateElapsedTime();
2870
+ }
2871
+ updateElapsedTime() {
2872
+ clearTimeout(this.executionTimer); this.executionTimer = undefined;
2873
+ if (this.executionBar.hidden || this.disposed) return;
2874
+ const start = this.executionStart;
2875
+ if (!Number.isFinite(start) || start <= 0) {
2876
+ this.elapsedTime.removeAttribute('datetime'); this.elapsedTime.textContent = '未记录'; return;
2877
+ }
2878
+ const elapsed = Math.max(0,Date.now()-start), seconds = Math.floor(elapsed/1000);
2879
+ this.elapsedTime.setAttribute('datetime','PT'+seconds+'S');
2880
+ this.elapsedTime.textContent = executionClock(seconds);
2881
+ this.executionTimer = setTimeout(() => this.updateElapsedTime(),1000-elapsed%1000);
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
+ }
584
2888
  updateComposer() {
585
- const task = this.task, running = activeTurn(this.headStatus), archived = task?.status === 'closed';
586
- const op = task && this.operation(task.id), blocked = !task || archived || this.selecting || Boolean(op?.status === 'pending' || op?.status === 'unknown');
587
- this.input.disabled = !task || archived || Boolean(this.selecting);
2889
+ const draft = this.newDraft, task = draft ?? this.task, running = !draft && activeTurn(this.headStatus), archived = task?.status === 'closed';
2890
+ const op = !draft && task && this.operation(task.id), blocked = !task || archived || this.selecting || Boolean(draft?.sending)
2891
+ || this.restoringQueue === task?.id || this.loadingDraftFiles.has(task?.id);
2892
+ this.renderExecutionStatus();
2893
+ this.input.disabled = blocked;
588
2894
  this.input.placeholder = archived ? '任务已归档' : !task ? '选择任务后继续' : '输入消息…';
589
- this.send.disabled = this.queue.disabled = blocked || !this.input.value.trim();
590
- this.send.textContent = running ? '追加' : '发送';
2895
+ this.attach.disabled = this.input.disabled;
2896
+ const savingSettings = this.pendingSettings.has(task?.id);
2897
+ if (this.settingsMenuState && (blocked || draft || this.settingsMenuState.task !== task?.id)) this.closeSettingsMenu();
2898
+ this.modelButton.disabled = this.thinkingButton.disabled = blocked || savingSettings || Boolean(draft && !draft.agents?.length);
2899
+ this.modelButton.firstElementChild.textContent = task?.model || '模型';
2900
+ this.thinkingButton.firstElementChild.textContent = effortLabel(task?.thinking) || '思考强度';
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);
2904
+ this.schedule.hidden = Boolean(draft);
2905
+ this.schedule.disabled = blocked;
2906
+ labelButton(this.send,!draft && queuedText !== undefined ? '排队发送' : running && this.head ? '追加到当前轮次' : '发送');
591
2907
  this.stop.hidden = !running || archived;
592
- this.stop.disabled = blocked;
593
- this.queueCount.textContent = task?.queued ? `${task.queued} 条排队` : '';
2908
+ this.stop.disabled = blocked || op?.action === 'stop' && ['pending','unknown'].includes(op.status);
2909
+ this.renderPromptQueue();
2910
+ if (this.composerMirror && this.composerMirror.dataset.value !== this.input.value) this.composerMirror.dataset.value = this.input.value;
2911
+ this.renderDraftImages(task?.id);
2912
+ this.updateDraftStorageNotice();
594
2913
  this.opNote.replaceChildren(); this.opNote.hidden = !op?.message;
595
2914
  if (op?.message) {
596
2915
  this.opNote.append(make('span',op.status === 'unknown' || op.status === 'failed'?'session-error':null,op.message));
@@ -598,43 +2917,157 @@
598
2917
  if (op.status === 'unknown') this.opNote.append(button('我已核实',() => this.setOperation(task.id,null),'session-quiet'));
599
2918
  }
600
2919
  }
601
- async submit(action) {
2920
+ submit(action,forceQueue = false) {
2921
+ if (!this.csrf || this.selecting || this.disposed) return;
602
2922
  const task = this.task?.id;
603
- if (!task || this.selecting || (action === 'stop' ? this.stop.disabled || this.stop.hidden : this.send.disabled)) return;
604
- const text = this.input.value.trim(), request = uuid(), turn = this.head;
605
- const payload = {task,request,action,...(action === 'stop'?{turn}:{text})};
606
- const pending = {request,action,submittedText:action === 'stop'?undefined:text};
607
- this.setOperation(task,{...pending,status:'pending',message:action === 'stop'?'正在请求停止…':'正在提交…'});
608
- try { this.handleOperation(task,request,action,await this.fetch('/operation',{body:payload}),text); }
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;
2926
+ if (this.newDraft) {
2927
+ void this.submitDraft(this.newDraft,text);
2928
+ return;
2929
+ }
2930
+ if (!task) return;
2931
+ if (queuedText !== undefined) action = 'queue';
2932
+ else if (action === 'queue' && !forceQueue && !this.shouldQueuePrompt()) action = 'send';
2933
+ const request = uuid(), images = this.images(task);
2934
+ const position = action === 'queue' ? this.position() : {bottom:true};
2935
+ const turn = action === 'send' && activeTurn(this.headStatus) ? this.head : undefined;
2936
+ const message = {payload:{task,request,text:text.trim(),...(turn ? {action:'steer',turn} : {action})},images,startedAt:Date.now()};
2937
+ const messages = this.messages(task);
2938
+ messages.set(request,message); this.outboxes.set(task,messages);
2939
+ this.input.value = ''; this.setDraft(task,''); this.imageDrafts.delete(task); this.noticeImages('');
2940
+ this.updateComposer(); this.pendingPosition = position;
2941
+ void this.sendMessage(message); this.app.queuePersist();
2942
+ }
2943
+ restoreUnsentMessage(message) {
2944
+ const {task,request,text} = message.payload, messages = this.outboxes.get(task);
2945
+ if (this.task?.id !== task || this.input.disabled || this.newDraft || messages?.get(request) !== message) return;
2946
+ if (this.input.value || this.images(task).length) { this.setChatError('请先处理输入框中已有的草稿。'); return; }
2947
+ messages.delete(request);
2948
+ if (!messages.size) this.outboxes.delete(task);
2949
+ this.replaceImages(task,message.images);
2950
+ this.input.value = text; this.setDraft(task,text); this.setChatError('');
2951
+ this.updateComposer(); this.updateOutbox(task); this.input.focus();
2952
+ }
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;
2958
+ try {
2959
+ const encoded = await encodeAttachments(images);
2960
+ if (this.csrf !== grant) return;
2961
+ const result = await this.fetch('/tasks',{body:{request:draft.request,title:(draft.creationTitle ??= attachmentPrompt(text,images).slice(0,200)),
2962
+ agent:draft.agent,directory:draft.directory,model:draft.model,thinking:draft.thinking},timeout:60_000});
2963
+ await this.restoreDraftFiles(result.id);
2964
+ if (this.csrf !== grant) return;
2965
+ message.payload.task = result.id; message.encoded = encoded;
2966
+ submission.label = '正在发送';
2967
+ if (this.newDraft === draft) this.updateDraftView();
2968
+ const messages = this.messages(result.id);
2969
+ messages.set(draft.request,message); this.outboxes.set(result.id,messages);
2970
+ this.imageDrafts.delete(draft.id);
2971
+ await this.persistDraftFiles(result.id,draft.id);
2972
+ const visible = this.newDraft === draft;
2973
+ if (this.parkedDraft === draft) this.parkedDraft = undefined;
2974
+ this.saveNewTaskDraft();
2975
+ if (this.search) this.search.value = '';
2976
+ if (this.filter) for (const option of this.filter.options) option.selected = option.value === 'open';
2977
+ clearTimeout(this.searchTimer);
2978
+ void this.sendMessage(message); void this.loadGroups();
2979
+ if (visible) await this.choose(result.id,{sentDraft:draft});
2980
+ } catch (error) {
2981
+ if (this.newDraft === draft && this.csrf === grant) this.setChatError(error.message);
2982
+ else if (this.csrf === grant) this.listNote.textContent = error.message;
2983
+ } finally {
2984
+ draft.sending = false;
2985
+ if (this.newDraft === draft) this.updateDraftView();
2986
+ }
2987
+ }
2988
+ async sendMessage(message,retry = false) {
2989
+ const {payload,images} = message, {task,request} = payload, grant = this.csrf;
2990
+ if (!grant || this.disposed || this.outboxes.get(task)?.get(request) !== message
2991
+ || retry && (!message.error || this.task?.id !== task || this.selecting || this.task.status === 'closed')) return;
2992
+ const attempt = message.attempt = {};
2993
+ const current = () => !this.disposed && message.attempt === attempt && this.outboxes.get(task)?.get(request) === message;
2994
+ message.error = undefined; message.restored = false;
2995
+ const saved = this.updateOutbox(task);
2996
+ if (saved) await saved;
2997
+ let encoded;
2998
+ try { encoded = message.encoded ?? (images.length ? await encodeAttachments(images) : undefined); }
2999
+ catch (error) { if (current()) this.failMessage(message,error.message); return; }
3000
+ if (!current()) return;
3001
+ if (this.csrf !== grant) { this.failMessage(message,'会话已过期,登录后可重试。'); return; }
3002
+ try {
3003
+ const result = await this.fetch('/operation',{params:retry?{retry:1}:undefined,body:encoded?{...payload,...encoded}:payload});
3004
+ if (current()) this.handleMessage(message,result);
3005
+ } catch (error) {
3006
+ if (!current()) return;
3007
+ const rejected = error.status >= 400 && error.status < 500 && error.status !== 408 || error.status === 503 && error.message.includes('未提交');
3008
+ this.failMessage(message,rejected ? error.message : '暂未确认送达,点击重试。');
3009
+ if (!rejected && this.csrf === grant) void this.checkMessage(message,attempt);
3010
+ }
3011
+ }
3012
+ updateOutbox(task) {
3013
+ this.saveOutboxes();
3014
+ if (this.task?.id === task) { this.redraw(); this.renderPromptQueue(); }
3015
+ return this.persistDraftFiles(task);
3016
+ }
3017
+ failMessage(message,error) {
3018
+ message.error = error; this.updateOutbox(message.payload.task);
3019
+ }
3020
+ handleMessage(message,result) {
3021
+ const {task} = message.payload;
3022
+ message.stale = result.status === 'stale';
3023
+ if (result.status === 'accepted') {
3024
+ message.accepted = true; message.queued = Boolean(result.queued); message.error = undefined;
3025
+ this.updateOutbox(task);
3026
+ if (this.task?.id === task && !this.connected) void this.refreshConversation(false);
3027
+ } else this.failMessage(message,result.status === 'pending' ? '暂未确认送达,点击重试。'
3028
+ : result.status === 'unknown' ? `${result.posted?'已发到飞书,Agent 提交结果待核实':'发送结果待核实'},不会重复发送。${result.message ? ' '+result.message : ''}`
3029
+ : result.message || '发送失败,点击重试。');
3030
+ if (message.stale && this.task?.id === task) void this.refreshConversation(false);
3031
+ }
3032
+ async checkMessage(message,attempt) {
3033
+ const {task,request} = message.payload;
3034
+ try {
3035
+ const result = await this.fetch('/operation',{params:{request}});
3036
+ if (!this.disposed && message.attempt === attempt && this.outboxes.get(task)?.get(request) === message) this.handleMessage(message,result);
3037
+ } catch { /* Leave the retry control available; a lookup never resubmits. */ }
3038
+ }
3039
+ checkRestoredMessages(task) {
3040
+ for (const message of this.messages(task).values()) if (message.restored) {
3041
+ message.restored = false;
3042
+ this.failMessage(message,message.error || '暂未确认送达,点击重试。');
3043
+ void this.checkMessage(message,message.attempt);
3044
+ }
3045
+ }
3046
+ async submitStop(task) {
3047
+ const request = uuid(), action = 'stop', turn = this.head, pending = {request,action,status:'pending',message:'正在请求停止…'};
3048
+ this.setOperation(task,pending);
3049
+ try { this.handleOperation(task,request,action,await this.fetch('/operation',{body:{task,request,action,turn}})); }
609
3050
  catch (error) {
610
- if ((error.status >= 400 && error.status < 500 && error.status !== 408) || (error.status === 503 && error.message.includes('未提交'))) {
3051
+ if (error.status >= 400 && error.status < 500 && error.status !== 408 || error.status === 503 && error.message.includes('未提交')) {
611
3052
  this.setOperation(task,{request,action,status:'failed',message:error.message});
612
- }
613
- else {
3053
+ } else {
614
3054
  this.setOperation(task,{...pending,status:'unknown',message:'连接中断,结果待核实。没有自动重发。'});
615
3055
  void this.checkOperation(task,false);
616
3056
  }
617
3057
  }
618
3058
  }
619
- handleOperation(task,request,action,result,text) {
620
- const op = this.operation(task); if (op?.request !== request) return;
621
- text ??= op.submittedText;
622
- if (result.status === 'accepted' && action !== 'stop' && text !== undefined && this.draft(task).trim() === text) {
623
- this.setDraft(task,''); if (this.task?.id === task) this.input.value = '';
624
- }
625
- const message = result.status === 'accepted' ? ({send:'消息已受理,正在等待 Agent。',queue:'已加入队列。',stop:'已请求停止此轮。'})[action]
3059
+ handleOperation(task,request,action,result) {
3060
+ if (this.operation(task)?.request !== request) return;
3061
+ const sending = action === 'sendQueued';
3062
+ const message = result.status === 'accepted' ? (sending ? '排队消息已发送。' : '已请求停止此轮。')
626
3063
  : result.status === 'pending' ? '服务端正在处理,可以稍后核实。'
627
- : result.status === 'stale' ? '这一轮已结束,没有停止后续轮次。'
628
- : result.status === 'unknown' ? `${result.posted?'消息已发到飞书,Agent 提交结果待核实。':'操作结果待核实。'}没有自动重发。`
3064
+ : result.status === 'stale' ? (sending ? '这条消息已离开队列。' : '这一轮已结束,没有停止后续轮次。')
3065
+ : result.status === 'unknown' ? `${sending ? '发送' : '停止'}结果待核实。${result.message ? ' '+result.message : ''}`
629
3066
  : result.message || '未提交操作。';
630
- const notice = {request,action,status:result.status,
631
- submittedText:['pending','unknown'].includes(result.status)?text:undefined,
632
- message:result.status === 'unknown' && result.message ? message+' '+result.message : message};
3067
+ const notice = {request,action,status:result.status,message};
633
3068
  this.setOperation(task,notice);
634
- if (result.status === 'accepted') {
635
- setTimeout(() => { if (!this.disposed && this.operations.get(task) === notice) this.setOperation(task,null); },6000);
636
- if (action === 'send' && this.task?.id === task && !this.selecting) void this.refreshConversation(false,true);
637
- }
3069
+ if (sending && result.status === 'accepted' && this.task?.id === task) void this.refreshConversation(false);
3070
+ if (result.status === 'accepted') setTimeout(() => { if (!this.disposed && this.operations.get(task) === notice) this.setOperation(task,null); },6000);
638
3071
  }
639
3072
  async checkOperation(task, explicit) {
640
3073
  const op = this.operation(task); if (!op || !['pending','unknown'].includes(op.status)) return;