@keyou007/agent-bot 0.1.27-alpha.3 → 0.1.27-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +77 -12
- package/README.zh.md +77 -12
- package/assets/agent-bot.ico +0 -0
- package/assets/roboto-mono-OFL.txt +93 -0
- package/assets/roboto-mono-latin.woff2 +0 -0
- package/assets/workspace-drafts.js +88 -0
- package/assets/workspace-sessions.js +1935 -232
- package/assets/workspace.css +360 -35
- package/assets/workspace.js +2115 -249
- package/dist/cli/SelfUpdateObserver.js +124 -0
- package/dist/cli/SelfUpdateObserver.js.map +1 -0
- package/dist/cli/SelfUpdateRunner.js +267 -70
- package/dist/cli/SelfUpdateRunner.js.map +1 -1
- package/dist/cli/SelfUpdater.js +54 -15
- package/dist/cli/SelfUpdater.js.map +1 -1
- package/dist/cli/controlProtocol.js.map +1 -1
- package/dist/cli/help.js +6 -0
- package/dist/cli/help.js.map +1 -1
- package/dist/cli.js +85 -6
- package/dist/cli.js.map +1 -1
- package/dist/codex/CodexEventMapper.js +29 -5
- package/dist/codex/CodexEventMapper.js.map +1 -1
- package/dist/codex/CodexRuntime.js +3 -0
- package/dist/codex/CodexRuntime.js.map +1 -1
- package/dist/feishu/CardRenderer.js +45 -13
- package/dist/feishu/CardRenderer.js.map +1 -1
- package/dist/feishu/ConsoleFeishuClient.js +4 -0
- package/dist/feishu/ConsoleFeishuClient.js.map +1 -1
- package/dist/feishu/FeishuMarkdown.js +2 -14
- package/dist/feishu/FeishuMarkdown.js.map +1 -1
- package/dist/feishu/FeishuMessageClient.js +9 -0
- package/dist/feishu/FeishuMessageClient.js.map +1 -1
- package/dist/feishu/FeishuTurnPresenter.js +26 -14
- package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
- package/dist/index.js +47 -12
- package/dist/index.js.map +1 -1
- package/dist/local-files/DiagramPreview.js +11 -6
- package/dist/local-files/DiagramPreview.js.map +1 -1
- package/dist/local-files/GitDiffPreview.js +40 -10
- package/dist/local-files/GitDiffPreview.js.map +1 -1
- package/dist/local-files/LiveMarkup.js +104 -0
- package/dist/local-files/LiveMarkup.js.map +1 -0
- package/dist/local-files/LocalFileViewerServer.js +133 -117
- package/dist/local-files/LocalFileViewerServer.js.map +1 -1
- package/dist/local-files/MarkdownExport.js +54 -0
- package/dist/local-files/MarkdownExport.js.map +1 -0
- package/dist/local-files/PreviewCodeFont.js +11 -0
- package/dist/local-files/PreviewCodeFont.js.map +1 -0
- package/dist/local-files/PreviewSyntaxHighlight.js +73 -0
- package/dist/local-files/PreviewSyntaxHighlight.js.map +1 -1
- package/dist/local-files/ToolCommandDisplay.js +111 -0
- package/dist/local-files/ToolCommandDisplay.js.map +1 -0
- package/dist/local-files/TurnPreviewPage.js +23 -269
- package/dist/local-files/TurnPreviewPage.js.map +1 -1
- package/dist/local-files/WorkspaceFileEvents.js +206 -0
- package/dist/local-files/WorkspaceFileEvents.js.map +1 -0
- package/dist/local-files/WorkspaceFiles.js +79 -3
- package/dist/local-files/WorkspaceFiles.js.map +1 -1
- package/dist/local-files/WorkspaceImages.js +15 -0
- package/dist/local-files/WorkspaceImages.js.map +1 -0
- package/dist/local-files/WorkspacePage.js +20 -5
- package/dist/local-files/WorkspacePage.js.map +1 -1
- package/dist/local-files/WorkspaceSessions.js +881 -79
- package/dist/local-files/WorkspaceSessions.js.map +1 -1
- package/dist/local-files/WorkspaceTimeline.js +105 -0
- package/dist/local-files/WorkspaceTimeline.js.map +1 -0
- package/dist/presentation/OutboundRouter.js +13 -6
- package/dist/presentation/OutboundRouter.js.map +1 -1
- package/dist/presentation/TurnStateReducer.js +28 -21
- package/dist/presentation/TurnStateReducer.js.map +1 -1
- package/dist/proxy/ProxySessionController.js +229 -92
- package/dist/proxy/ProxySessionController.js.map +1 -1
- package/dist/proxy/TaskMetadata.js +86 -0
- package/dist/proxy/TaskMetadata.js.map +1 -0
- package/dist/scheduling/ScheduleCards.js +10 -4
- package/dist/scheduling/ScheduleCards.js.map +1 -1
- package/dist/scheduling/ScheduleCommand.js +4 -0
- package/dist/scheduling/ScheduleCommand.js.map +1 -1
- package/dist/scheduling/ScheduledTaskStore.js +51 -12
- package/dist/scheduling/ScheduledTaskStore.js.map +1 -1
- package/dist/scheduling/types.js +18 -4
- package/dist/scheduling/types.js.map +1 -1
- package/dist/state/StateStore.js +145 -19
- package/dist/state/StateStore.js.map +1 -1
- package/dist/state/TurnPreviewJournal.js +143 -36
- package/dist/state/TurnPreviewJournal.js.map +1 -1
- package/dist/state/TurnToolText.js +172 -0
- package/dist/state/TurnToolText.js.map +1 -0
- package/dist/state/migrations.js +4 -0
- package/dist/state/migrations.js.map +1 -1
- package/dist/supervision/SafeRestartNotifier.js +9 -6
- package/dist/supervision/SafeRestartNotifier.js.map +1 -1
- package/dist/terminal/TerminalPage.js +5 -0
- package/dist/terminal/TerminalPage.js.map +1 -1
- package/dist/updates/AutomaticUpdatePreparer.js +63 -12
- package/dist/updates/AutomaticUpdatePreparer.js.map +1 -1
- package/dist/updates/ManualUpdateController.js +7 -2
- package/dist/updates/ManualUpdateController.js.map +1 -1
- package/dist/utils/promptAttachments.js +20 -0
- package/dist/utils/promptAttachments.js.map +1 -0
- package/dist/utils/toolTimestamp.js +6 -0
- package/dist/utils/toolTimestamp.js.map +1 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/skills/agent-bot/SKILL.md +23 -2
- package/src/cli/SelfUpdateObserver.ts +111 -0
- package/src/cli/SelfUpdateRunner.ts +271 -85
- package/src/cli/SelfUpdater.ts +53 -16
- package/src/cli/controlProtocol.ts +1 -0
- package/src/cli/help.ts +6 -0
- package/src/cli.ts +71 -5
- package/src/codex/CodexEventMapper.ts +25 -5
- package/src/codex/CodexRuntime.ts +4 -0
- package/src/feishu/CardRenderer.ts +48 -13
- package/src/feishu/ConsoleFeishuClient.ts +6 -1
- package/src/feishu/FeishuMarkdown.ts +2 -14
- package/src/feishu/FeishuMessageClient.ts +10 -0
- package/src/feishu/FeishuTurnPresenter.ts +22 -8
- package/src/feishu/types.ts +1 -0
- package/src/index.ts +47 -12
- package/src/local-files/DiagramPreview.ts +11 -6
- package/src/local-files/GitDiffPreview.ts +38 -10
- package/src/local-files/LiveMarkup.ts +103 -0
- package/src/local-files/LocalFileViewerServer.ts +120 -120
- package/src/local-files/MarkdownExport.ts +54 -0
- package/src/local-files/PreviewCodeFont.ts +12 -0
- package/src/local-files/PreviewSyntaxHighlight.ts +75 -0
- package/src/local-files/ToolCommandDisplay.ts +104 -0
- package/src/local-files/TurnPreviewPage.ts +23 -254
- package/src/local-files/WorkspaceFileEvents.ts +186 -0
- package/src/local-files/WorkspaceFiles.ts +72 -5
- package/src/local-files/WorkspaceImages.ts +10 -0
- package/src/local-files/WorkspacePage.ts +20 -5
- package/src/local-files/WorkspaceSessions.ts +811 -82
- package/src/local-files/WorkspaceTimeline.ts +109 -0
- package/src/presentation/OutboundRouter.ts +15 -4
- package/src/presentation/TurnStateReducer.ts +27 -18
- package/src/presentation/turnViewTypes.ts +2 -0
- package/src/proxy/ProxySessionController.ts +226 -77
- package/src/proxy/TaskMetadata.ts +81 -0
- package/src/runtime/types.ts +2 -1
- package/src/scheduling/ScheduleCards.ts +10 -4
- package/src/scheduling/ScheduleCommand.ts +4 -0
- package/src/scheduling/ScheduledTaskStore.ts +54 -9
- package/src/scheduling/types.ts +24 -4
- package/src/state/StateStore.ts +157 -20
- package/src/state/TurnPreviewJournal.ts +138 -34
- package/src/state/TurnToolText.ts +156 -0
- package/src/state/migrations.ts +4 -0
- package/src/supervision/SafeRestartNotifier.ts +9 -6
- package/src/terminal/TerminalPage.ts +5 -0
- package/src/updates/AutomaticUpdatePreparer.ts +52 -11
- package/src/updates/ManualUpdateController.ts +8 -3
- package/src/utils/promptAttachments.ts +24 -0
- package/src/utils/toolTimestamp.ts +5 -0
|
@@ -8,11 +8,156 @@
|
|
|
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-message-images > *,.session-message-files,.markdown-body > *';
|
|
59
|
+
const clipboardFiles = clipboard => {
|
|
60
|
+
const files = Array.from(clipboard?.files ?? []);
|
|
61
|
+
if (files.length) return files;
|
|
62
|
+
return Array.from(clipboard?.items ?? []).filter(item=>item.kind === 'file')
|
|
63
|
+
.map(item=>item.getAsFile()).filter(Boolean);
|
|
64
|
+
};
|
|
65
|
+
const previewImageType = file => {
|
|
66
|
+
if (imageTypes.includes(file.type)) return file.type;
|
|
67
|
+
if (file.type && file.type !== 'application/octet-stream') return;
|
|
68
|
+
const extension = /\.(png|jpe?g|gif|webp)$/iu.exec(file.name)?.[1].toLowerCase();
|
|
69
|
+
return imageTypesByExtension[extension];
|
|
70
|
+
};
|
|
71
|
+
const readAttachment = file => new Promise((resolve,reject) => {
|
|
72
|
+
const reader = new FileReader();
|
|
73
|
+
reader.onload = () => resolve(String(reader.result).split(',',2)[1]);
|
|
74
|
+
reader.onerror = reader.onabort = () => reject(new Error('无法读取附件,请移除后重新添加。'));
|
|
75
|
+
reader.readAsDataURL(file);
|
|
76
|
+
});
|
|
77
|
+
const effortLabel = value => ({none:'无',minimal:'极低',low:'低',medium:'中',high:'高',xhigh:'极高',max:'最高'})[value] ?? value;
|
|
78
|
+
const revokeAttachment = attachment => { if (attachment.src) URL.revokeObjectURL(attachment.src); };
|
|
79
|
+
const draftAttachment = (file,annotation) => {
|
|
80
|
+
const type = file.size && previewImageType(file);
|
|
81
|
+
const preview = type ? (file.type === type ? file : file.slice(0,file.size,type)) : undefined;
|
|
82
|
+
return {id:uuid(),file,src:preview ? URL.createObjectURL(preview) : undefined,annotation};
|
|
83
|
+
};
|
|
84
|
+
const annotationLocation = item => [item.line && `第 ${item.line} 行`,item.originalLine && `变更前第 ${item.originalLine} 行`].filter(Boolean).join(' · ');
|
|
85
|
+
const annotationTitle = item => item.path ? `${item.path.split(/[\\/]/u).at(-1)}:${item.line || item.originalLine}` : item.label;
|
|
86
|
+
const annotationPrompt = (text,attachments) => text.trim() || (attachments.some(item => item.annotation) ? '请阅读所附批注,并处理其中提出的要求。' : '');
|
|
87
|
+
const annotationBlock = text => text.split('\n').map(line => ' '+line).join('\n');
|
|
88
|
+
const annotationMarkdown = item => {
|
|
89
|
+
const source = item.path ? ['# 文件批注',`文件路径\n\n${annotationBlock(item.path)}`,`行号\n\n${annotationBlock(annotationLocation(item))}`,
|
|
90
|
+
...(item.originalPath ? [`变更前的文件路径\n\n${annotationBlock(item.originalPath)}`] : [])]
|
|
91
|
+
: ['# 聊天批注',`消息来源\n\n${annotationBlock(item.label)}`,...(item.turn ? [`轮次\n\n${annotationBlock(item.turn)}`] : [])];
|
|
92
|
+
return [...source,`选中的原文\n\n${annotationBlock(item.quote)}`,`用户批注\n\n${item.note}`].join('\n\n');
|
|
93
|
+
};
|
|
94
|
+
const encodeAttachments = async attachments => {
|
|
95
|
+
const entries = await Promise.all(attachments.map(async attachment => ({attachment,data:await readAttachment(attachment.file)})));
|
|
96
|
+
const images = entries.filter(({attachment})=>attachment.src).map(({data})=>data);
|
|
97
|
+
const files = entries.filter(({attachment})=>!attachment.src).map(({attachment,data})=>({name:attachment.file.name?.slice(0,255) || 'file',data}));
|
|
98
|
+
return {...(images.length?{images}:{}),...(files.length?{files}:{})};
|
|
99
|
+
};
|
|
100
|
+
const timeTool = tool => {
|
|
101
|
+
const start = tool.startedAt, end = tool.completedAt;
|
|
102
|
+
if (!start) return '';
|
|
103
|
+
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} 秒`;
|
|
104
|
+
const clock = {hour:'2-digit',minute:'2-digit',second:'2-digit',hour12:false};
|
|
105
|
+
const startText = new Date(start).toLocaleTimeString('zh-CN',clock);
|
|
106
|
+
const elapsed = end && end >= start ? `耗时 ${format(end-start)}` : '';
|
|
107
|
+
return elapsed ? `开始 ${startText} · ${elapsed}` : `开始 ${startText}`;
|
|
108
|
+
};
|
|
109
|
+
const executionClock = seconds => {
|
|
110
|
+
const hours = Math.floor(seconds/3600);
|
|
111
|
+
const parts = [Math.floor(seconds/60)%60,seconds%60];
|
|
112
|
+
if (hours) parts.unshift(hours);
|
|
113
|
+
return parts.map(part=>String(part).padStart(2,'0')).join(':');
|
|
114
|
+
};
|
|
11
115
|
const labels = {ready:'空闲',starting:'启动中',running:'执行中',tool_running:'执行中',waiting_for_approval:'等待确认',completed:'已完成',failed:'失败',cancelled:'已停止',unknown:'待核实',closed:'已归档'};
|
|
12
116
|
const status = value => labels[value] || '空闲';
|
|
117
|
+
const taskProgress = {starting:'启动中',running:'正在执行',tool_running:'正在执行',waiting_for_approval:'等待确认'};
|
|
118
|
+
const taskClock = new Intl.DateTimeFormat('zh-CN',{hour:'2-digit',minute:'2-digit',hourCycle:'h23'});
|
|
119
|
+
const taskDate = new Intl.DateTimeFormat('zh-CN',{month:'long',day:'numeric'});
|
|
120
|
+
const taskFullDate = new Intl.DateTimeFormat('zh-CN',{year:'numeric',month:'long',day:'numeric'});
|
|
121
|
+
const taskDateLabel = (date, today = new Date()) => {
|
|
122
|
+
if (date.toDateString() === today.toDateString()) return taskClock.format(date);
|
|
123
|
+
const yesterday = new Date(today);
|
|
124
|
+
yesterday.setDate(yesterday.getDate()-1);
|
|
125
|
+
if (date.toDateString() === yesterday.toDateString()) return '昨天';
|
|
126
|
+
return (date.getFullYear() === today.getFullYear() ? taskDate : taskFullDate).format(date);
|
|
127
|
+
};
|
|
128
|
+
const syncRows = (container, before, rows) => {
|
|
129
|
+
const retained = new Set(rows.values());
|
|
130
|
+
for (const row of before.values()) if (!retained.has(row) && row.node.parentNode === container) row.node.remove();
|
|
131
|
+
let next = container.firstChild;
|
|
132
|
+
for (const {node} of rows.values()) {
|
|
133
|
+
if (node !== next) container.insertBefore(node,next);
|
|
134
|
+
next = node.nextSibling;
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
const keepOpenGroups = (previous, rows, visibleTools) => {
|
|
138
|
+
if (!visibleTools) return rows;
|
|
139
|
+
const current = new Map([...rows].map(([key,row]) => [row,key])), held = new Map();
|
|
140
|
+
let after = rows.has('prompt') ? 'prompt' : undefined;
|
|
141
|
+
for (const [key,row] of previous) {
|
|
142
|
+
if (current.has(row)) after = current.get(row);
|
|
143
|
+
else if (row.rows && row.node.open && ![...row.rows.keys()].some(id => visibleTools.has(id))) {
|
|
144
|
+
const earlier = held.get(after) || [];
|
|
145
|
+
earlier.push([key,row]); held.set(after,earlier);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (!held.size) return rows;
|
|
149
|
+
const merged = new Map(held.get(undefined));
|
|
150
|
+
for (const [key,row] of rows) {
|
|
151
|
+
merged.set(key,row);
|
|
152
|
+
for (const [heldKey,heldRow] of held.get(key) || []) merged.set(heldKey,heldRow);
|
|
153
|
+
}
|
|
154
|
+
return merged;
|
|
155
|
+
};
|
|
13
156
|
const activeTurn = value => ['running','tool_running','waiting_for_approval'].includes(value);
|
|
14
157
|
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') => {
|
|
158
|
+
const save = (key,value,storage = 'localStorage') => {
|
|
159
|
+
try { window[storage].setItem(key,JSON.stringify(value)); return true; } catch { return false; }
|
|
160
|
+
};
|
|
16
161
|
const uuid = () => {
|
|
17
162
|
const bytes = crypto.getRandomValues(new Uint8Array(16)); bytes[6] = bytes[6]&15|64; bytes[8] = bytes[8]&63|128;
|
|
18
163
|
return Array.from(bytes,(byte,index) => ([4,6,8,10].includes(index)?'-':'')+byte.toString(16).padStart(2,'0')).join('');
|
|
@@ -24,7 +169,22 @@
|
|
|
24
169
|
this.page = uuid(); this.generation = this.connectionEpoch = 0;
|
|
25
170
|
const groups = read('agentbot-workspace-groups',[]);
|
|
26
171
|
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','任务');
|
|
172
|
+
this.drafts = new Map(); this.imageDrafts = new Map(); this.operations = new Map(); this.pendingSettings = new Set(); this.heading = make('h2','pane-heading','任务');
|
|
173
|
+
this.draftFiles = new window.AgentBotWorkspaceDraftFiles(base,uuid);
|
|
174
|
+
this.fileRecords = new Set(); this.fileLoads = new Map(); this.loadingDraftFiles = new Set();
|
|
175
|
+
this.chatImageSizeKey = 'agentbot-workspace-chat-image-sizes:'+base;
|
|
176
|
+
const imageSizes = read(this.chatImageSizeKey,[],'sessionStorage');
|
|
177
|
+
this.chatImageSizes = new Map(Array.isArray(imageSizes) ? imageSizes.slice(-chatImageSizeLimit).filter(Array.isArray) : []);
|
|
178
|
+
this.newDraftKey = 'agentbot-workspace-new-draft:'+base;
|
|
179
|
+
const savedDraft = read(this.newDraftKey,null,'sessionStorage');
|
|
180
|
+
if (typeof savedDraft?.draft?.id === 'string') {
|
|
181
|
+
this.parkedDraft = savedDraft.draft; this.resumeNewDraft = savedDraft.active === true;
|
|
182
|
+
this.newDraftSaved = true;
|
|
183
|
+
}
|
|
184
|
+
this.pendingTurnActions = new Set();
|
|
185
|
+
const outbox = read('agentbot-workspace-outbox',[],'sessionStorage');
|
|
186
|
+
this.outboxes = new Map((Array.isArray(outbox) ? outbox : []).map(([task,items]) => [task,
|
|
187
|
+
new Map(items.map(([id,payload,error]) => [id,{payload,error,images:noImages,restored:true}]))]));
|
|
28
188
|
this.left.classList.add('session-task-pane'); this.chat.classList.add('session-chat-pane');
|
|
29
189
|
this.locked('正在检查工作台会话…'); void this.session();
|
|
30
190
|
this.offline = () => { if (this.csrf) { this.connected = false; this.app.updateSessionStatus(false,'网络已断开'); } };
|
|
@@ -34,17 +194,19 @@
|
|
|
34
194
|
async fetch(route, options = {}) {
|
|
35
195
|
const {params,body,signal} = options, url = new URL(this.base+route,window.location.href);
|
|
36
196
|
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);
|
|
197
|
+
const controller = new AbortController(), timeout = setTimeout(() => controller.abort(), options.timeout ?? (body?.images?.length || body?.files?.length ? 60_000 : 15_000));
|
|
38
198
|
const abort = () => controller.abort(); if (signal?.aborted) abort(); else signal?.addEventListener('abort',abort,{once:true});
|
|
39
199
|
try {
|
|
40
200
|
const response = await fetch(url,{cache:'no-store',credentials:'same-origin',signal:controller.signal,
|
|
41
201
|
...(body === undefined ? {} : {method:'POST',headers:{'content-type':'application/json','x-workspace-csrf':this.csrf || ''},body:JSON.stringify(body)})});
|
|
202
|
+
const reloading = (route === '/session' || response.status === 401)
|
|
203
|
+
&& this.app.reloadWorkspaceIfUpdated(response.headers?.get('X-AgentBot-Workspace-Revision'),response.headers?.get('X-AgentBot-Workspace-Instance'));
|
|
42
204
|
const data = await response.json();
|
|
43
205
|
if (!response.ok) {
|
|
44
|
-
if (response.status === 401 && route !== '/login' && this.csrf) this.expire();
|
|
206
|
+
if (response.status === 401 && route !== '/login' && this.csrf && !reloading) this.expire();
|
|
45
207
|
throw Object.assign(new Error(data.error || `请求失败(HTTP ${response.status})`),{status:response.status});
|
|
46
208
|
}
|
|
47
|
-
return data;
|
|
209
|
+
return reloading ? {...data,reloading:true} : data;
|
|
48
210
|
} finally { clearTimeout(timeout); signal?.removeEventListener('abort',abort); }
|
|
49
211
|
}
|
|
50
212
|
session(autoLogin = true, note) {
|
|
@@ -52,7 +214,7 @@
|
|
|
52
214
|
}
|
|
53
215
|
async checkSession(autoLogin, note) {
|
|
54
216
|
try {
|
|
55
|
-
const data = await this.fetch('/session'); if (this.disposed) return;
|
|
217
|
+
const data = await this.fetch('/session'); if (this.disposed || data.reloading) return;
|
|
56
218
|
if (data.csrf) this.unlock(data.csrf);
|
|
57
219
|
else if (data.auth === 'automatic' && autoLogin) {
|
|
58
220
|
const login = await this.fetch('/login',{body:{}});
|
|
@@ -73,7 +235,13 @@
|
|
|
73
235
|
this.left.querySelector('.session-login input,.session-primary')?.focus({preventScroll:true});
|
|
74
236
|
}
|
|
75
237
|
locked(message, mode, hint) {
|
|
76
|
-
this.timelineObserver?.disconnect();
|
|
238
|
+
this.timelineObserver?.disconnect(); this.closeSettingsMenu();
|
|
239
|
+
this.scheduleDialog?.close();
|
|
240
|
+
if (this.loggingOut) {
|
|
241
|
+
this.resetImageDrafts(); this.resetOutboxes(); this.saveOutboxes();
|
|
242
|
+
this.draftFiles.clear(); this.fileRecords.clear(); this.fileLoads.clear(); this.loadingDraftFiles.clear();
|
|
243
|
+
}
|
|
244
|
+
this.clearImageInteractions();
|
|
77
245
|
const box = make('div','session-empty'); box.append(make('strong',null,message));
|
|
78
246
|
if (hint) box.append(make('p',null,hint));
|
|
79
247
|
this.left.replaceChildren(this.heading,box);
|
|
@@ -106,13 +274,27 @@
|
|
|
106
274
|
const afterLogin = this.afterLogin; this.afterLogin = undefined; afterLogin?.();
|
|
107
275
|
void this.loadGroups();
|
|
108
276
|
const href = window.location.href, task = this.app.taskFromUrl(href);
|
|
109
|
-
|
|
277
|
+
const selection = task ? this.choose(task,{initial:true,href}) : undefined;
|
|
278
|
+
if (this.resumeNewDraft) {
|
|
279
|
+
this.resumeNewDraft = false;
|
|
280
|
+
void Promise.resolve(selection).then(() => {
|
|
281
|
+
if (!this.disposed && this.csrf === csrf && this.parkedDraft) this.openNewTask();
|
|
282
|
+
});
|
|
283
|
+
}
|
|
110
284
|
}
|
|
111
285
|
expire() {
|
|
112
286
|
if (!this.csrf) return;
|
|
287
|
+
this.app.annotations?.cancel();
|
|
113
288
|
this.csrf = undefined; this.stream?.close(); clearTimeout(this.watchdog); this.connected = false;
|
|
114
|
-
this.
|
|
115
|
-
this.
|
|
289
|
+
clearTimeout(this.executionTimer); this.executionTimer = undefined; this.updateHead();
|
|
290
|
+
if (!this.loggingOut) {
|
|
291
|
+
if (this.newDraft) { this.parkedDraft = this.newDraft; this.newDraft = undefined; this.resumeNewDraft = true; }
|
|
292
|
+
} else {
|
|
293
|
+
this.newDraft = this.parkedDraft = undefined; this.resumeNewDraft = false;
|
|
294
|
+
}
|
|
295
|
+
this.saveNewTaskDraft();
|
|
296
|
+
this.selection?.abort(); this.groupRequest?.abort(); this.resetNewer(); this.generation++;
|
|
297
|
+
this.app.releaseSessionPanels(); this.task = undefined; this.headPlan = []; this.projects.clear();
|
|
116
298
|
this.selecting = false; this.refreshing = undefined; this.app.dataset.taskPending = 'false';
|
|
117
299
|
this.locked('正在检查工作台会话…');
|
|
118
300
|
this.app.updateSessionStatus(false,'未登录');
|
|
@@ -122,17 +304,23 @@
|
|
|
122
304
|
this.selection?.abort(); this.generation++; this.selecting = false; this.target = this.task?.id;
|
|
123
305
|
this.app.dataset.taskPending = 'false'; this.setChatError(''); this.updateComposer();
|
|
124
306
|
if (this.connected && this.task) void this.refreshConversation(true);
|
|
307
|
+
else void this.loadNewer();
|
|
125
308
|
}
|
|
126
309
|
clearTask() {
|
|
127
|
-
this.
|
|
128
|
-
this.
|
|
129
|
-
this.
|
|
310
|
+
this.app.annotations?.cancel();
|
|
311
|
+
this.leaveDraft();
|
|
312
|
+
this.selection?.abort(); this.resetNewer(); this.generation++; this.target = undefined; this.selecting = false; this.refreshing = undefined;
|
|
313
|
+
this.app.dataset.taskPending = 'false'; this.task = undefined; this.updateHead(); this.turns = []; this.headPlan = [];
|
|
314
|
+
this.lastPosition = this.pendingPosition = this.restoredPosition = undefined;
|
|
130
315
|
this.renderChat(); this.updateSelected();
|
|
131
316
|
if (this.connected) void this.fetch('/focus',{body:{page:this.page,generation:this.generation}}).catch(() => {});
|
|
132
317
|
}
|
|
133
318
|
dispose() {
|
|
134
|
-
this.timelineObserver?.disconnect();
|
|
135
|
-
this.
|
|
319
|
+
this.timelineObserver?.disconnect(); this.closeSettingsMenu(); this.resetImageDrafts(); this.resetOutboxes(); this.clearImageInteractions();
|
|
320
|
+
this.scheduleDialog?.close();
|
|
321
|
+
this.draftFiles.dispose();
|
|
322
|
+
this.disposed = true; this.stream?.close(); this.selection?.abort(); this.groupRequest?.abort(); this.resetNewer(); clearTimeout(this.searchTimer); clearTimeout(this.watchdog);
|
|
323
|
+
clearTimeout(this.executionTimer);
|
|
136
324
|
window.removeEventListener('offline',this.offline); window.removeEventListener('online',this.online);
|
|
137
325
|
}
|
|
138
326
|
connect() {
|
|
@@ -143,11 +331,20 @@
|
|
|
143
331
|
if (this.stream !== stream || !this.csrf) return;
|
|
144
332
|
clearTimeout(this.watchdog);
|
|
145
333
|
this.watchdog = setTimeout(() => { this.app.updateSessionStatus(false,'正在重连'); this.connect(); },36_000);
|
|
334
|
+
const today = new Date(), day = today.toDateString();
|
|
335
|
+
if (day !== this.taskDatesDay) {
|
|
336
|
+
this.taskDatesDay = day;
|
|
337
|
+
for (const time of this.groupList.querySelectorAll('.session-task-time')) time.textContent = taskDateLabel(new Date(time.getAttribute('datetime')),today);
|
|
338
|
+
}
|
|
146
339
|
};
|
|
147
340
|
watch(); stream.addEventListener('heartbeat',watch);
|
|
148
|
-
stream.addEventListener('sync',
|
|
149
|
-
watch();
|
|
341
|
+
stream.addEventListener('sync',event => {
|
|
150
342
|
if (this.stream !== stream) return;
|
|
343
|
+
try {
|
|
344
|
+
const version = JSON.parse(event.data);
|
|
345
|
+
if (this.app.reloadWorkspaceIfUpdated(version?.revision,version?.instance)) return;
|
|
346
|
+
} catch { /* Older servers may omit restart metadata. */ }
|
|
347
|
+
watch();
|
|
151
348
|
const wasConnected = this.everConnected; this.connected = this.everConnected = true; this.connectionEpoch++;
|
|
152
349
|
this.app.updateSessionStatus(true,'实时连接');
|
|
153
350
|
if (!this.selecting && this.task) void this.refreshConversation(true);
|
|
@@ -160,16 +357,18 @@
|
|
|
160
357
|
try {
|
|
161
358
|
const data = {...JSON.parse(event.data), version:Number(event.lastEventId), epoch:this.connectionEpoch};
|
|
162
359
|
if (data.taskId !== this.target || data.generation !== this.generation) return;
|
|
163
|
-
if (this.selecting || this.refreshing) this.bufferedTail = data;
|
|
360
|
+
if (this.selecting || this.refreshing || this.newerRequest) this.bufferedTail = data;
|
|
164
361
|
else if (data.taskId === this.task?.id) this.applyTail(data.value);
|
|
165
362
|
} catch { this.setChatError('实时更新无法读取,请刷新对话。',true); }
|
|
166
363
|
});
|
|
167
364
|
stream.onerror = () => {
|
|
168
365
|
if (this.stream !== stream || !this.csrf) return;
|
|
169
366
|
this.connected = false; this.app.updateSessionStatus(false,'正在重连');
|
|
367
|
+
this.app.scheduleWorkspaceVersionCheck(2000);
|
|
170
368
|
if (!this.probing) {
|
|
171
369
|
this.probing = true;
|
|
172
|
-
void this.fetch('/session').then(data => { if (!data.csrf) this.expire(); })
|
|
370
|
+
void this.fetch('/session').then(data => { if (this.stream === stream && !data.reloading && !data.csrf) this.expire(); })
|
|
371
|
+
.catch(() => {}).finally(() => { this.probing = false; });
|
|
173
372
|
}
|
|
174
373
|
};
|
|
175
374
|
}
|
|
@@ -181,7 +380,9 @@
|
|
|
181
380
|
catch (error) { if (this.csrf) this.listNote.textContent = error.message; }
|
|
182
381
|
finally { logout.disabled = false; this.loggingOut = false; }
|
|
183
382
|
},'session-quiet'); logout.setAttribute('aria-label','退出工作台');
|
|
184
|
-
|
|
383
|
+
const actions = make('div','session-task-actions');
|
|
384
|
+
const create = button('新建任务',() => this.openNewTask(),'session-new-task');
|
|
385
|
+
actions.append(create,logout); bar.append(heading,actions);
|
|
185
386
|
const controls = make('div','session-task-controls'), field = this.search = make('input');
|
|
186
387
|
field.type = 'search'; field.placeholder = '搜索任务或项目'; field.setAttribute('aria-label','搜索任务或项目'); field.maxLength = 160;
|
|
187
388
|
const filter = this.filter = make('select'); filter.setAttribute('aria-label','任务筛选');
|
|
@@ -193,9 +394,301 @@
|
|
|
193
394
|
filter.onchange = () => { clearTimeout(this.searchTimer); void this.loadGroups(); };
|
|
194
395
|
controls.append(field,filter); this.left.replaceChildren(bar,controls,this.listNote,this.groupList);
|
|
195
396
|
}
|
|
397
|
+
createDialog(caption,parent) {
|
|
398
|
+
const dialog = make('dialog','session-form-dialog'), header = make('header');
|
|
399
|
+
const title = make('h2',null,caption); title.id = 'session-dialog-'+uuid();
|
|
400
|
+
const close = iconButton('关闭','M6 6l12 12M18 6 6 18','session-dialog-close',() => dialog.close());
|
|
401
|
+
dialog.setAttribute('aria-labelledby',title.id); header.append(title,close); dialog.append(header);
|
|
402
|
+
dialog.onclick = event => { if (event.target === dialog) dialog.close(); };
|
|
403
|
+
parent.append(dialog); return dialog;
|
|
404
|
+
}
|
|
405
|
+
dialogField(form,name,field) {
|
|
406
|
+
const label = make('label','session-dialog-field'); label.append(make('span',null,name),field); form.append(label);
|
|
407
|
+
}
|
|
408
|
+
annotationTask() { return this.csrf && !this.input?.disabled ? this.newDraft?.id ?? this.task?.id : undefined; }
|
|
409
|
+
addAnnotation(item,task) {
|
|
410
|
+
if (!task || task !== this.annotationTask()) return '当前任务已切换或无法输入消息。';
|
|
411
|
+
if (typeof item?.note !== 'string' || !item.note.trim() || item.note.length > 8000 || typeof item.quote !== 'string' || !item.quote.trim()) return '批注内容无效。';
|
|
412
|
+
if (item.quote.length > 100_000) return '选中的文字过长,请缩小选区后再添加批注。';
|
|
413
|
+
if (item.path !== undefined ? typeof item.path !== 'string' || !item.path || item.path.length > 4096
|
|
414
|
+
|| ![item.line,item.originalLine].some(Boolean)
|
|
415
|
+
|| [item.line,item.originalLine].some(line => line !== undefined && (typeof line !== 'string' || !/^\d{1,10}(?:–\d{1,10})?$/u.test(line)))
|
|
416
|
+
|| item.originalPath !== undefined && (typeof item.originalPath !== 'string' || item.originalPath.length > 4096)
|
|
417
|
+
: typeof item.label !== 'string' || !item.label || item.label.length > 120 || item.turn !== undefined && (typeof item.turn !== 'string' || item.turn.length > 400)) return '批注来源无效。';
|
|
418
|
+
const stem = (item.path ? item.path.split(/[\\/]/u).at(-1) : item.label).slice(0,120).replace(/[\x00-\x1f<>:"/\\|?*]/gu,'_');
|
|
419
|
+
const lines = item.line || item.originalLine;
|
|
420
|
+
const file = new File([annotationMarkdown(item)],`批注 - ${stem}${lines ? ' - '+lines : ''}.md`,{type:'text/markdown'});
|
|
421
|
+
if (!this.addAttachments([file],item)) return '附件已达到上限,请先移除一个附件。';
|
|
422
|
+
}
|
|
423
|
+
openSchedule() {
|
|
424
|
+
if (!this.task || this.newDraft || this.selecting || this.scheduleDialog?.open) return;
|
|
425
|
+
const task = this.task.id, grant = this.csrf, editor = this.input, original = editor.value, attachments = this.images(task);
|
|
426
|
+
const prompt = annotationPrompt(original,attachments);
|
|
427
|
+
const dialog = this.scheduleDialog = this.createDialog('定时任务',this.chat);
|
|
428
|
+
dialog.classList.add('session-schedule-dialog');
|
|
429
|
+
const current = () => dialog.open && this.task?.id === task && this.csrf === grant;
|
|
430
|
+
dialog.onclose = () => dialog.remove();
|
|
431
|
+
const history = make('div','session-schedule-history'); history.setAttribute('aria-label','本会话的定时任务');
|
|
432
|
+
const feedback = make('p','session-schedule-feedback'); feedback.setAttribute('role','status');
|
|
433
|
+
const area = make('div'); dialog.append(area,history,feedback);
|
|
434
|
+
let offset = 0, version = 0;
|
|
435
|
+
const load = async (more = false) => {
|
|
436
|
+
const loading = ++version;
|
|
437
|
+
if (!more) { offset = 0; history.replaceChildren(make('p','session-muted','正在读取定时任务…')); }
|
|
438
|
+
try {
|
|
439
|
+
const data = await this.fetch('/schedules',{params:{task,offset}});
|
|
440
|
+
if (!current() || version !== loading) return;
|
|
441
|
+
if (!more) history.replaceChildren();
|
|
442
|
+
for (const job of data.jobs) history.append(this.scheduleRow(job,current,edit,async (action,revision) => {
|
|
443
|
+
await this.fetch('/schedules/action',{body:{task,job:job.id,revision,action},timeout:60_000});
|
|
444
|
+
if (current()) { feedback.textContent = '定时任务已更新。'; void load(); }
|
|
445
|
+
}));
|
|
446
|
+
offset += data.jobs.length;
|
|
447
|
+
if (!offset) history.append(make('p','session-muted','暂无定时任务。'));
|
|
448
|
+
if (data.more) {
|
|
449
|
+
const next = button('更多',() => { next.remove(); void load(true); },'session-more'); history.append(next);
|
|
450
|
+
}
|
|
451
|
+
} catch (error) { if (current() && version === loading) history.replaceChildren(make('p','session-error',error.message),button('重试',() => void load(),'session-more')); }
|
|
452
|
+
};
|
|
453
|
+
let usedDraft = false;
|
|
454
|
+
const edit = job => {
|
|
455
|
+
feedback.textContent = '';
|
|
456
|
+
if (!job && (usedDraft || !(prompt || attachments.length))) {
|
|
457
|
+
area.replaceChildren(make('p','session-schedule-feedback','在聊天框输入消息或添加附件后可创建定时任务。')); return;
|
|
458
|
+
}
|
|
459
|
+
area.replaceChildren(this.scheduleForm(job,prompt,attachments,current,async (schedule,request) => {
|
|
460
|
+
if (job) {
|
|
461
|
+
await this.fetch('/schedules/action',{body:{task,job:job.id,revision:job.revision,action:'edit',schedule}});
|
|
462
|
+
} else {
|
|
463
|
+
const encoded = await encodeAttachments(attachments);
|
|
464
|
+
if (!current()) return;
|
|
465
|
+
await this.fetch('/schedules',{body:{task,request,schedule,...encoded}});
|
|
466
|
+
usedDraft = true;
|
|
467
|
+
if (this.task?.id === task && this.csrf === grant && this.images(task) === attachments && editor === this.input && editor.value === original) {
|
|
468
|
+
editor.value = ''; this.setDraft(task,''); this.replaceImages(task,[]); this.updateComposer();
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
if (current()) { edit(); feedback.textContent = job ? '定时任务已保存。' : '定时任务已创建。'; void load(); }
|
|
472
|
+
},() => edit()));
|
|
473
|
+
};
|
|
474
|
+
edit();
|
|
475
|
+
dialog.showModal(); void load();
|
|
476
|
+
}
|
|
477
|
+
scheduleRow(job,current,onEdit,onAction) {
|
|
478
|
+
const row = make('details','session-schedule-row'), summary = make('summary');
|
|
479
|
+
const time = job.nextRunAt ?? (job.at ? Date.parse(job.at) : undefined);
|
|
480
|
+
const dateLabel = value => new Intl.DateTimeFormat('zh-CN',{dateStyle:'short',timeStyle:'short',timeZone:job.timeZone}).format(value);
|
|
481
|
+
const details = [scheduleStatuses[job.status] || job.status,scheduleFrequency(job.cron),time === undefined ? '' : dateLabel(time)].filter(Boolean);
|
|
482
|
+
summary.append(make('span','session-schedule-prompt',job.name || job.prompt),make('small','session-muted',details.join(' · ')));
|
|
483
|
+
row.append(summary);
|
|
484
|
+
if (job.prompt) row.append(make('p','session-schedule-preview',job.prompt));
|
|
485
|
+
const names = [...(job.images ? [`${job.images} 张图片`] : []),...(job.files || [])];
|
|
486
|
+
if (names.length) row.append(make('div','session-muted session-schedule-attachments',names.join(' · ')));
|
|
487
|
+
if (job.notice) row.append(make('p','session-muted',job.notice));
|
|
488
|
+
const actions = make('div','session-schedule-actions'), feedback = make('div','session-muted'); feedback.setAttribute('role','status');
|
|
489
|
+
const runAction = (label,action) => button(label,async () => {
|
|
490
|
+
const controls = [...actions.querySelectorAll('button')]; controls.forEach(control => { control.disabled = true; });
|
|
491
|
+
try { await onAction(action,job.revision); }
|
|
492
|
+
catch (error) { if (current()) feedback.textContent = error.message; }
|
|
493
|
+
finally { controls.forEach(control => { control.disabled = false; }); }
|
|
494
|
+
},'session-quiet');
|
|
495
|
+
actions.append(button('编辑',() => onEdit(job),'session-quiet'));
|
|
496
|
+
if (job.status === 'draft') actions.append(runAction('启用','confirm'));
|
|
497
|
+
if (job.status === 'enabled') actions.append(runAction('暂停','pause'));
|
|
498
|
+
if (job.status === 'paused') actions.append(runAction('恢复','resume'));
|
|
499
|
+
if (job.status !== 'draft') actions.append(runAction('立即执行','run'));
|
|
500
|
+
const remove = runAction('确认删除','delete'); remove.hidden = true;
|
|
501
|
+
const ask = button('删除',() => { remove.hidden = !remove.hidden; },'session-quiet');
|
|
502
|
+
actions.append(ask,remove);
|
|
503
|
+
const runs = make('details','session-schedule-runs'); runs.append(make('summary',null,'最近运行'));
|
|
504
|
+
const log = make('ul'); runs.append(log);
|
|
505
|
+
runs.ontoggle = async () => {
|
|
506
|
+
if (!runs.open) return;
|
|
507
|
+
log.replaceChildren(make('li','session-muted','正在读取…'));
|
|
508
|
+
try {
|
|
509
|
+
const data = await this.fetch('/schedules/runs',{params:{task:this.task.id,job:job.id}});
|
|
510
|
+
if (!current() || !runs.open) return;
|
|
511
|
+
log.replaceChildren(...data.runs.map(run => make('li',null,[dateLabel(run.scheduledFor),scheduleRunStatuses[run.status],run.detail].filter(Boolean).join(' · '))));
|
|
512
|
+
if (!data.runs.length) log.append(make('li','session-muted','暂无运行记录。'));
|
|
513
|
+
} catch (error) { if (current()) log.replaceChildren(make('li','session-muted',error.message)); }
|
|
514
|
+
};
|
|
515
|
+
row.append(actions,feedback,runs); return row;
|
|
516
|
+
}
|
|
517
|
+
scheduleForm(job,prompt,attachments,current,saveSchedule,cancel) {
|
|
518
|
+
const form = make('form','session-schedule-form'), fields = make('div','session-schedule-fields');
|
|
519
|
+
const name = make('input'), frequency = make('select'), date = make('input'), cron = make('input'), timeZone = make('input'), end = make('input');
|
|
520
|
+
timeZone.value = job?.timeZone || Intl.DateTimeFormat().resolvedOptions().timeZone; timeZone.required = true;
|
|
521
|
+
date.type = end.type = 'datetime-local';
|
|
522
|
+
const initialTime = job ? job.at ?? job.startsAt : Date.now()+30*60_000;
|
|
523
|
+
if (initialTime !== undefined) date.value = localDateTime(new Date(initialTime),timeZone.value);
|
|
524
|
+
if (job?.endsAt) end.value = localDateTime(new Date(job.endsAt),timeZone.value);
|
|
525
|
+
name.maxLength = 120; name.placeholder = '定时任务';
|
|
526
|
+
name.value = job?.name || prompt.split('\n')[0].slice(0,120) || attachments[0]?.file.name.slice(0,120) || '';
|
|
527
|
+
for (const [value,label] of scheduleOptions) {
|
|
528
|
+
const option = make('option',null,label); option.value = value; option.selected = value === (job?.cron ? 'cron' : 'once'); frequency.append(option);
|
|
529
|
+
}
|
|
530
|
+
cron.value = job?.cron || ''; cron.maxLength = 120; cron.placeholder = '0 9 * * 1-5';
|
|
531
|
+
let message;
|
|
532
|
+
this.dialogField(form,'名称',name);
|
|
533
|
+
if (job) {
|
|
534
|
+
message = make('textarea'); message.rows = 3; message.maxLength = 24_000; message.value = job.prompt;
|
|
535
|
+
this.dialogField(form,'Prompt',message);
|
|
536
|
+
} else if (prompt) form.append(make('p','session-schedule-preview',prompt));
|
|
537
|
+
const names = job ? [...(job.images ? [`${job.images} 张图片`] : []),...(job.files || [])] : attachments.map(item => item.file.name);
|
|
538
|
+
if (names.length) form.append(make('div','session-muted session-schedule-attachments',names.join(' · ')));
|
|
539
|
+
form.append(fields); this.dialogField(fields,'频率',frequency); this.dialogField(fields,'执行时间',date); this.dialogField(form,'Cron 表达式(五段)',cron);
|
|
540
|
+
const advanced = make('details','session-schedule-advanced'), settings = make('div','session-schedule-fields');
|
|
541
|
+
advanced.append(make('summary',null,'高级设置'),settings);
|
|
542
|
+
const maxDelay = make('input'), catchUp = make('input');
|
|
543
|
+
for (const [input,min,value] of [[maxDelay,1,job?.maxDelayMinutes ?? 60],[catchUp,0,job?.catchUpMinutes ?? 0]]) {
|
|
544
|
+
input.type = 'number'; input.min = String(min); input.max = '10080'; input.value = String(value); input.required = true;
|
|
545
|
+
}
|
|
546
|
+
this.dialogField(settings,'时区(IANA)',timeZone); this.dialogField(settings,'结束时间(可选)',end);
|
|
547
|
+
this.dialogField(settings,'最长等待(分钟)',maxDelay); this.dialogField(settings,'补跑窗口(分钟,0 为跳过)',catchUp);
|
|
548
|
+
form.append(advanced);
|
|
549
|
+
const syncFields = () => {
|
|
550
|
+
const once = frequency.value === 'once', custom = frequency.value === 'cron';
|
|
551
|
+
date.required = !custom;
|
|
552
|
+
date.parentElement.firstElementChild.textContent = `${once ? '执行时间' : '开始时间'}(${timeZone.value.trim()})`;
|
|
553
|
+
cron.required = custom; cron.parentElement.hidden = !custom; end.parentElement.hidden = once;
|
|
554
|
+
};
|
|
555
|
+
frequency.onchange = timeZone.oninput = syncFields; syncFields();
|
|
556
|
+
const actions = make('div','session-schedule-actions'), feedback = make('div','session-muted'); feedback.setAttribute('role','status');
|
|
557
|
+
const submit = button(job ? '保存设置' : '创建定时任务',undefined,'session-primary'); submit.type = 'submit';
|
|
558
|
+
if (job) actions.append(button('取消编辑',cancel,'session-quiet'));
|
|
559
|
+
actions.append(submit); form.append(actions,feedback);
|
|
560
|
+
let sent, request;
|
|
561
|
+
form.onsubmit = async event => {
|
|
562
|
+
event.preventDefault(); if (!current() || submit.disabled) return;
|
|
563
|
+
const timeZoneName = timeZone.value.trim(), type = frequency.value;
|
|
564
|
+
try {
|
|
565
|
+
if (!timeZoneName) throw new Error('请输入时区。');
|
|
566
|
+
const start = date.value ? scheduleDate(date.value,timeZoneName) : undefined;
|
|
567
|
+
const timing = {};
|
|
568
|
+
if (type === 'once') {
|
|
569
|
+
if (!start || start.getTime() <= Date.now()) throw new Error('请选择未来的执行时间。');
|
|
570
|
+
timing.at = start.toISOString();
|
|
571
|
+
} else {
|
|
572
|
+
if (type === 'cron') timing.cron = cron.value.trim();
|
|
573
|
+
else {
|
|
574
|
+
const nominal = new Date(date.value+'Z'), minute = nominal.getUTCMinutes(), hour = nominal.getUTCHours(), day = nominal.getUTCDate();
|
|
575
|
+
const rules = {hourly:'* * * *',daily:`${hour} * * *`,weekdays:`${hour} * * 1-5`,weekly:`${hour} * * ${nominal.getUTCDay()}`,
|
|
576
|
+
monthly:`${hour} ${day} * *`,yearly:`${hour} ${day} ${nominal.getUTCMonth()+1} *`};
|
|
577
|
+
timing.cron = `${minute} ${rules[type]}`;
|
|
578
|
+
}
|
|
579
|
+
if (start) timing.startsAt = start.toISOString();
|
|
580
|
+
if (end.value) timing.endsAt = scheduleDate(end.value,timeZoneName).toISOString();
|
|
581
|
+
}
|
|
582
|
+
const schedule = { name:name.value.trim() || '定时任务',prompt:message ? message.value.trim() : prompt,timeZone:timeZoneName,
|
|
583
|
+
maxDelayMinutes:Number(maxDelay.value),catchUpMinutes:Number(catchUp.value),...timing };
|
|
584
|
+
const next = JSON.stringify(schedule);
|
|
585
|
+
if (sent !== next) { sent = next; request = uuid(); }
|
|
586
|
+
submit.disabled = true; feedback.textContent = '';
|
|
587
|
+
await saveSchedule(schedule,request);
|
|
588
|
+
} catch (error) { if (current()) feedback.textContent = error.message; }
|
|
589
|
+
finally { submit.disabled = false; }
|
|
590
|
+
};
|
|
591
|
+
return form;
|
|
592
|
+
}
|
|
593
|
+
openNewTask() {
|
|
594
|
+
if (!this.csrf) return;
|
|
595
|
+
this.app.annotations?.cancel();
|
|
596
|
+
if (this.selecting) this.cancelSelection();
|
|
597
|
+
const resume = this.newDraft || this.parkedDraft;
|
|
598
|
+
if (!this.newDraft) this.newDraft = this.parkedDraft || {
|
|
599
|
+
id:uuid(),request:uuid(),text:'',directory:this.task?.project.root,agent:this.task?.agent,
|
|
600
|
+
};
|
|
601
|
+
this.parkedDraft = undefined;
|
|
602
|
+
const draft = this.newDraft;
|
|
603
|
+
if (resume) void this.restoreDraftFiles(draft.id);
|
|
604
|
+
this.setChatError('');
|
|
605
|
+
this.input.value = draft.text; this.noticeImages(''); this.updateDraftView();
|
|
606
|
+
this.app.navigate(() => this.app.selectPane('chat'));
|
|
607
|
+
this.input.focus();
|
|
608
|
+
if (draft.agents) return;
|
|
609
|
+
const grant = this.csrf;
|
|
610
|
+
void this.fetch('/task-agents').then(data => {
|
|
611
|
+
if (this.csrf !== grant || (this.newDraft !== draft && this.parkedDraft !== draft)) return;
|
|
612
|
+
draft.agents = data.agents;
|
|
613
|
+
if (!data.agents.some(agent=>agent.name === draft.agent)) draft.agent = data.defaultAgent;
|
|
614
|
+
if (this.newDraft === draft) { this.updateDraftView(); if (!draft.agent) this.setChatError('未配置支持 Workspace 的 App Server Agent。'); }
|
|
615
|
+
}).catch(error => { if (this.newDraft === draft && this.csrf === grant) this.setChatError(error.message); });
|
|
616
|
+
}
|
|
617
|
+
leaveDraft(discard = false) {
|
|
618
|
+
const draft = this.newDraft;
|
|
619
|
+
if (!draft) return;
|
|
620
|
+
this.app.annotations?.cancel();
|
|
621
|
+
draft.text = this.input.value; this.newDraft = undefined;
|
|
622
|
+
if (discard) this.replaceImages(draft.id,[]);
|
|
623
|
+
else this.parkedDraft = draft;
|
|
624
|
+
if (this.settingsDialog?.open) this.settingsDialog.close();
|
|
625
|
+
this.input.value = this.task ? this.draft(this.task.id) : '';
|
|
626
|
+
this.noticeImages(''); this.setChatError(''); this.updateDraftView();
|
|
627
|
+
}
|
|
628
|
+
saveNewTaskDraft() {
|
|
629
|
+
const draft = this.newDraft ?? this.parkedDraft;
|
|
630
|
+
if (draft) {
|
|
631
|
+
const {id,request,text,directory,agent,model,thinking,creationTitle} = draft;
|
|
632
|
+
this.newDraftSaved = save(this.newDraftKey,{active:Boolean(this.newDraft || this.resumeNewDraft),
|
|
633
|
+
draft:{id,request,text,directory,agent,model,thinking,creationTitle}},'sessionStorage');
|
|
634
|
+
} else if (this.newDraftSaved) {
|
|
635
|
+
this.newDraftSaved = false;
|
|
636
|
+
save(this.newDraftKey,null,'sessionStorage');
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
updateDraftView() {
|
|
640
|
+
const draft = this.newDraft;
|
|
641
|
+
this.saveNewTaskDraft();
|
|
642
|
+
this.chat.toggleAttribute('data-draft',Boolean(draft));
|
|
643
|
+
this.body.hidden = Boolean(draft);
|
|
644
|
+
this.updatePlan(this.headPlan);
|
|
645
|
+
this.draftTools.hidden = !draft;
|
|
646
|
+
this.draftTools.replaceChildren();
|
|
647
|
+
if (draft) {
|
|
648
|
+
const project = button(draft.directory ? draft.directory.split(/[\\/]/u).filter(Boolean).at(-1) : '选择项目目录',
|
|
649
|
+
() => this.openDraftProject(draft),'session-draft-project');
|
|
650
|
+
if (draft.directory) project.dataset.tooltip = draft.directory;
|
|
651
|
+
project.disabled = Boolean(draft.sending);
|
|
652
|
+
this.draftTools.append(project);
|
|
653
|
+
if (draft.directory) {
|
|
654
|
+
const clear = iconButton('清除项目','M6 6l12 12M18 6 6 18','session-clear-project',() => {
|
|
655
|
+
draft.directory = undefined; draft.request = uuid(); this.updateDraftView();
|
|
656
|
+
});
|
|
657
|
+
clear.disabled = project.disabled; this.draftTools.append(clear);
|
|
658
|
+
}
|
|
659
|
+
const cancel = button('取消草稿',() => this.leaveDraft(true),'session-quiet'); cancel.disabled = project.disabled;
|
|
660
|
+
this.draftTools.append(cancel);
|
|
661
|
+
}
|
|
662
|
+
this.renderChatHeader(); this.updateComposer();
|
|
663
|
+
}
|
|
664
|
+
openDraftProject(draft) {
|
|
665
|
+
if (draft.sending) return;
|
|
666
|
+
const dialog = this.createDialog('选择项目目录',this.chat);
|
|
667
|
+
const form = make('form'), input = make('input');
|
|
668
|
+
input.placeholder = '输入主机上的绝对目录路径'; input.required = true; input.maxLength = 4096; input.value = draft.directory || '';
|
|
669
|
+
this.dialogField(form,'目录路径',input);
|
|
670
|
+
const apply = make('button','session-dialog-submit','选择目录'); apply.type = 'submit';
|
|
671
|
+
const chooseProject = root => {
|
|
672
|
+
draft.directory = root; draft.request = uuid(); dialog.close(); this.setChatError(''); this.updateDraftView();
|
|
673
|
+
};
|
|
674
|
+
const projects = make('div','session-project-choices');
|
|
675
|
+
for (const { group:project } of this.projects.values()) {
|
|
676
|
+
if (!project?.root) continue;
|
|
677
|
+
const choice = button(project.name,() => chooseProject(project.root)); choice.dataset.tooltip = project.root; projects.append(choice);
|
|
678
|
+
}
|
|
679
|
+
form.append(projects,apply); dialog.append(form);
|
|
680
|
+
form.onsubmit = event => { event.preventDefault(); const root = input.value.trim().replace(/^"(.+)"$/u,'$1'); if (root) chooseProject(root); };
|
|
681
|
+
dialog.addEventListener('close',() => dialog.remove(),{once:true});
|
|
682
|
+
dialog.showModal(); input.focus();
|
|
683
|
+
}
|
|
196
684
|
listParams() { return {q:this.search.value.trim(),archived:this.filter.value === 'archived'?'1':undefined}; }
|
|
197
685
|
async loadGroups(refresh = false, more = false) {
|
|
198
|
-
if (!this.csrf ||
|
|
686
|
+
if (!this.csrf || this.disposed) return;
|
|
687
|
+
if (refresh && this.groupPending) { this.groupRefresh = true; return; }
|
|
688
|
+
if (refresh && this.projects.size > 30) {
|
|
689
|
+
for (const view of this.projects.values()) if (view.node.open) void this.loadGroup(view,false,true);
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
199
692
|
this.groupRequest?.abort(); const controller = this.groupRequest = new AbortController();
|
|
200
693
|
this.groupPending = true;
|
|
201
694
|
const params = this.listParams(), last = more ? [...this.projects.keys()].at(-1) : undefined;
|
|
@@ -211,7 +704,7 @@
|
|
|
211
704
|
let view = this.projects.get(group.id);
|
|
212
705
|
if (!view) { view = this.createGroup(group); this.projects.set(group.id,view); }
|
|
213
706
|
view.title.textContent = group.name; view.count.textContent = String(group.count);
|
|
214
|
-
view.
|
|
707
|
+
view.summary.dataset.tooltip = group.root || group.name;
|
|
215
708
|
if (view.node.open) void this.loadGroup(view,false,refresh);
|
|
216
709
|
}
|
|
217
710
|
this.groupMore?.remove();
|
|
@@ -219,45 +712,77 @@
|
|
|
219
712
|
if (!this.projects.size) this.listNote.textContent = params.q ? '没有匹配的任务。' : '暂无'+(params.archived?'已归档':'未归档')+'任务。';
|
|
220
713
|
} catch (error) {
|
|
221
714
|
if (!controller.signal.aborted && this.csrf) this.listNote.replaceChildren(make('span','session-error',refresh?'任务列表暂未更新。':error.message),button('重试',() => this.loadGroups(),'session-quiet'));
|
|
222
|
-
} finally {
|
|
715
|
+
} finally {
|
|
716
|
+
if (this.groupRequest === controller) {
|
|
717
|
+
this.groupPending = false;
|
|
718
|
+
if (this.groupRefresh) { this.groupRefresh = false; void this.loadGroups(true); }
|
|
719
|
+
}
|
|
720
|
+
}
|
|
223
721
|
}
|
|
224
722
|
createGroup(group) {
|
|
225
723
|
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};
|
|
724
|
+
const view = {node,summary,title,count,rows,group,items:[],sequence:0};
|
|
227
725
|
summary.append(title,count); node.append(summary,rows); this.groupList.append(node);
|
|
228
726
|
node.open = Boolean(this.search.value || this.openGroups.has(group.id) || this.task?.project.id === group.id || this.projects.size === 0);
|
|
229
727
|
node.ontoggle = () => {
|
|
230
|
-
if (node.open) { this.openGroups.add(group.id);
|
|
728
|
+
if (node.open) { this.openGroups.add(group.id); void this.loadGroup(view,false,Boolean(view.signature)); }
|
|
231
729
|
else this.openGroups.delete(group.id);
|
|
232
730
|
if (!this.search.value) save('agentbot-workspace-groups',[...this.openGroups].slice(-100));
|
|
233
731
|
};
|
|
234
732
|
return view;
|
|
235
733
|
}
|
|
236
734
|
async loadGroup(view, more = false, refresh = false) {
|
|
237
|
-
if (!this.csrf
|
|
238
|
-
view.loading
|
|
735
|
+
if (!this.csrf) return;
|
|
736
|
+
if (view.loading) { if (refresh) view.refresh = true; return; }
|
|
737
|
+
view.loading = true; view.refresh = false;
|
|
738
|
+
const sequence = ++view.sequence, params = this.listParams();
|
|
239
739
|
if (!refresh && !more) view.rows.replaceChildren(make('div','session-list-note','加载任务…'));
|
|
240
740
|
try {
|
|
241
|
-
const
|
|
242
|
-
|
|
243
|
-
const
|
|
244
|
-
|
|
741
|
+
const readPage = after => this.fetch('/tasks',{params:{...params,project:view.group.id,after}});
|
|
742
|
+
let {items,more:hasMore} = await readPage(more ? view.items.at(-1)?.id : undefined);
|
|
743
|
+
const current = () => view.node.isConnected && sequence === view.sequence && Boolean(this.csrf);
|
|
744
|
+
while (current() && refresh && hasMore && items.length && items.length < view.items.length) {
|
|
745
|
+
const next = await readPage(items.at(-1).id);
|
|
746
|
+
const merged = [...new Map([...items,...next.items].map(item => [item.id,item])).values()];
|
|
747
|
+
if (merged.length === items.length) break;
|
|
748
|
+
items = merged; hasMore = next.more;
|
|
749
|
+
}
|
|
750
|
+
if (!current()) return;
|
|
751
|
+
if (more) items = [...new Map([...view.items,...items].map(item => [item.id,item])).values()];
|
|
752
|
+
const signature = JSON.stringify([items,hasMore]);
|
|
245
753
|
if (signature !== view.signature) {
|
|
246
754
|
const focused = document.activeElement?.dataset?.sessionTask;
|
|
247
755
|
view.items = items; view.signature = signature;
|
|
248
756
|
view.rows.replaceChildren(...items.map(item => this.taskButton(item)));
|
|
249
|
-
if (
|
|
757
|
+
if (hasMore) view.rows.append(button('更多任务',() => this.loadGroup(view,true),'session-more'));
|
|
250
758
|
if (focused) [...view.rows.querySelectorAll('[data-session-task]')].find(node => node.dataset.sessionTask === focused)?.focus({preventScroll:true});
|
|
251
759
|
}
|
|
252
760
|
} catch (error) {
|
|
253
761
|
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 {
|
|
762
|
+
} finally {
|
|
763
|
+
view.loading = false;
|
|
764
|
+
if (view.refresh && view.node.isConnected && view.node.open) { view.refresh = false; void this.loadGroup(view,false,true); }
|
|
765
|
+
}
|
|
255
766
|
}
|
|
256
767
|
taskButton(item) {
|
|
257
|
-
const
|
|
768
|
+
const label = item.title || '未命名任务';
|
|
769
|
+
const node = button('',() => this.choose(item.id),'session-task'), title = make('span','session-task-title',label);
|
|
258
770
|
const dot = make('span','session-dot'); dot.dataset.status = item.status; dot.setAttribute('aria-hidden','true');
|
|
259
|
-
|
|
260
|
-
|
|
771
|
+
const details = make('span','session-task-details'), line = make('span','session-task-line');
|
|
772
|
+
const progress = taskProgress[item.status], subtitle = progress
|
|
773
|
+
? (item.promptPreview ? progress+':'+item.promptPreview : progress) : item.promptPreview || status(item.status);
|
|
774
|
+
line.append(title);
|
|
775
|
+
const updated = new Date(item.updatedAt);
|
|
776
|
+
let updatedLabel;
|
|
777
|
+
if (item.updatedAt && Number.isFinite(updated.getTime())) {
|
|
778
|
+
const time = make('time','session-task-time',taskDateLabel(updated));
|
|
779
|
+
time.setAttribute('datetime',updated.toISOString()); line.append(time);
|
|
780
|
+
updatedLabel = '更新于 '+taskFullDate.format(updated)+' '+taskClock.format(updated);
|
|
781
|
+
}
|
|
782
|
+
details.append(line,make('span','session-task-subtitle',subtitle));
|
|
783
|
+
node.append(dot,details); node.dataset.sessionTask = item.id;
|
|
784
|
+
node.dataset.tooltipOverflow = '.session-task-title';
|
|
785
|
+
labelButton(node,[label,subtitle,!progress && item.promptPreview ? status(item.status) : null,item.agent,updatedLabel].filter(Boolean).join(' · '));
|
|
261
786
|
if (item.id === this.task?.id) node.setAttribute('aria-current','true'); return node;
|
|
262
787
|
}
|
|
263
788
|
updateSelected() {
|
|
@@ -266,11 +791,15 @@
|
|
|
266
791
|
}
|
|
267
792
|
}
|
|
268
793
|
async choose(taskId, nav = {}) {
|
|
794
|
+
if (this.newDraft) this.leaveDraft();
|
|
269
795
|
if (!this.csrf || !taskId || this.task?.id === taskId && !nav.history && !this.selecting) {
|
|
270
796
|
if (this.task?.id === taskId) this.app.navigate(() => this.app.selectPane('chat'),true);
|
|
271
797
|
return;
|
|
272
798
|
}
|
|
273
|
-
this.
|
|
799
|
+
if (this.task?.id !== taskId) this.app.annotations?.cancel();
|
|
800
|
+
this.selection?.abort(); this.resetNewer(); const controller = this.selection = new AbortController();
|
|
801
|
+
if (this.settingsDialog?.open) this.settingsDialog.close();
|
|
802
|
+
if (this.scheduleDialog?.open) this.scheduleDialog.close();
|
|
274
803
|
const generation = ++this.generation; this.target = taskId; this.selecting = true; this.bufferedTail = undefined; this.refreshing = undefined;
|
|
275
804
|
this.app.dataset.taskPending = 'true';
|
|
276
805
|
const position = nav.position?.chat || (nav.href ? this.app.chatPositionFromUrl(nav.href) : this.app.savedSessionChat(taskId));
|
|
@@ -278,13 +807,21 @@
|
|
|
278
807
|
let snapshot;
|
|
279
808
|
this.setChatError('正在打开任务…'); this.updateComposer();
|
|
280
809
|
try {
|
|
281
|
-
const data =
|
|
810
|
+
const [data] = await Promise.all([this.loadTask(taskId,generation,anchor,controller.signal),this.restoreDraftFiles(taskId)]);
|
|
811
|
+
snapshot = data;
|
|
282
812
|
if (controller.signal.aborted || !this.csrf || generation !== this.generation) return;
|
|
283
813
|
this.app.activateTaskPanel(data.task,nav,() => {
|
|
284
|
-
this.
|
|
814
|
+
this.imageDialog?.open && this.imageDialog.close();
|
|
815
|
+
this.imageNotice.hidden = true;
|
|
816
|
+
this.task = data.task; this.updateHead(data.head,data.headStatus,data.execution);
|
|
817
|
+
this.setPlanOpen(false); this.updatePlan(data.plan);
|
|
285
818
|
this.turns = data.turns; this.more = data.more; this.turnNodes.clear(); this.timeline.replaceChildren();
|
|
286
|
-
this.pendingPosition = position || {bottom:true};
|
|
287
|
-
this.
|
|
819
|
+
this.restoredPosition = undefined; this.pendingPosition = position || {bottom:true};
|
|
820
|
+
this.input.value = this.draft(taskId); this.checkOperation(taskId,false);
|
|
821
|
+
this.outboxRows = new Map(); this.outbox.replaceChildren();
|
|
822
|
+
this.renderConversation(); this.updateSelected(); this.checkRestoredMessages(taskId);
|
|
823
|
+
const project = this.projects.get(this.task.project.id);
|
|
824
|
+
if (project && !project.node.open) project.node.open = true;
|
|
288
825
|
});
|
|
289
826
|
this.setChatError('');
|
|
290
827
|
if (!nav.history && !nav.initial && !this.left.clientHeight) this.chatTitle.focus({preventScroll:true});
|
|
@@ -300,8 +837,8 @@
|
|
|
300
837
|
if (generation === this.generation) {
|
|
301
838
|
this.selecting = false; this.app.dataset.taskPending = 'false'; this.updateComposer(); this.restorePosition();
|
|
302
839
|
if (!snapshot) this.target = this.task?.id;
|
|
303
|
-
this.drainTail(snapshot);
|
|
304
840
|
if (this.connected && this.task && (!snapshot || snapshot.epoch !== this.connectionEpoch)) void this.refreshConversation(true);
|
|
841
|
+
else { this.drainTail(snapshot); void this.loadNewer(); }
|
|
305
842
|
}
|
|
306
843
|
}
|
|
307
844
|
}
|
|
@@ -318,279 +855,1339 @@
|
|
|
318
855
|
if (tail && tail.taskId === this.task?.id && tail.generation === this.generation && tail.epoch === this.connectionEpoch
|
|
319
856
|
&& (snapshot?.epoch !== tail.epoch || tail.version > snapshot.version)) this.applyTail(tail.value);
|
|
320
857
|
}
|
|
858
|
+
updateHead(head, status, execution) {
|
|
859
|
+
this.head = head; this.headStatus = status; this.execution = execution;
|
|
860
|
+
}
|
|
321
861
|
applyTail(data) {
|
|
322
862
|
if (!this.task) return;
|
|
323
|
-
if (!data) { this.setChatError('此任务已不可用。'); this.task.status = 'closed'; this.updateComposer(); return; }
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
this.
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
863
|
+
if (!data) { this.resetNewer(); this.updateHead(); this.updatePlan(); this.setChatError('此任务已不可用。'); this.task.status = 'closed'; this.updateComposer(); return; }
|
|
864
|
+
Object.assign(this.task,data.task);
|
|
865
|
+
if (data.queued !== undefined) this.task.queued = data.queued;
|
|
866
|
+
if (data.queuedPrompts !== undefined) this.task.queuedPrompts = data.queuedPrompts;
|
|
867
|
+
this.app.filesPanel.setTaskDirectories(this.task.directories);
|
|
868
|
+
const next = data.turn, last = this.turns.at(-1);
|
|
869
|
+
this.updateHead(next?.id,next?.status,data.execution);
|
|
870
|
+
this.updatePlan(data.plan);
|
|
871
|
+
const promoted = next?.promptRequestId && next.promptRequestId === last?.promptRequestId
|
|
872
|
+
&& last.id.startsWith('pending_') && !next.id.startsWith('pending_');
|
|
873
|
+
if (next && (next.id === last?.id || promoted)) {
|
|
874
|
+
this.turns[this.turns.length-1] = next;
|
|
875
|
+
this.redraw();
|
|
876
|
+
} else if (next && (data.parent === last?.id || !last && !data.parent)) {
|
|
877
|
+
this.turns.push(next); this.redraw();
|
|
878
|
+
} else if (!last || !next) {
|
|
879
|
+
if (last || next) void this.refreshConversation(false);
|
|
880
|
+
} else void this.loadNewer();
|
|
881
|
+
if (this.newerFailed && this.head && !this.hasNewer()) { this.newerFailed = false; this.setChatError(''); }
|
|
334
882
|
this.updateComposer(); this.renderChatHeader();
|
|
335
883
|
}
|
|
336
|
-
|
|
884
|
+
hasNewer() { return Boolean(this.head && this.turns.length && this.turns.at(-1).id !== this.head); }
|
|
885
|
+
resetNewer() { this.newerRequest?.abort(); this.newerRequest = undefined; this.newerFailed = false; }
|
|
886
|
+
async loadNewer() {
|
|
887
|
+
if (!this.csrf || !this.task || this.selecting || this.refreshing || this.newerRequest || this.newerFailed || !this.hasNewer()) return;
|
|
888
|
+
const task = this.task.id, after = this.turns.at(-1).id, epoch = this.connectionEpoch;
|
|
889
|
+
const controller = this.newerRequest = new AbortController();
|
|
890
|
+
let snapshot, resetBranch = false;
|
|
891
|
+
try {
|
|
892
|
+
const data = await this.fetch('/task',{params:{task,after,page:this.connected?this.page:undefined},signal:controller.signal});
|
|
893
|
+
if (this.newerRequest !== controller) return;
|
|
894
|
+
if (data.turns.length === 0 && data.head !== after) throw new Error('未能继续读取对话。');
|
|
895
|
+
snapshot = data.version === undefined ? undefined : {...data,epoch};
|
|
896
|
+
this.pendingPosition = this.position();
|
|
897
|
+
this.turns.push(...data.turns);
|
|
898
|
+
this.updateHead(data.head,data.headStatus,data.execution); this.task = data.task; this.updatePlan(data.plan);
|
|
899
|
+
this.app.filesPanel.setTaskDirectories(this.task.directories);
|
|
900
|
+
this.renderConversation(); this.setChatError('');
|
|
901
|
+
} catch (error) {
|
|
902
|
+
if (this.newerRequest !== controller) return;
|
|
903
|
+
if (error.status === 409) resetBranch = true;
|
|
904
|
+
else {
|
|
905
|
+
this.newerFailed = true;
|
|
906
|
+
this.setChatError('后续对话读取失败:'+error.message,false,() => { this.newerFailed = false; void this.loadNewer(); });
|
|
907
|
+
}
|
|
908
|
+
} finally {
|
|
909
|
+
if (this.newerRequest === controller) {
|
|
910
|
+
this.newerRequest = undefined;
|
|
911
|
+
if (resetBranch) void this.refreshConversation(false,{anchor:this.position()?.turn});
|
|
912
|
+
else { this.drainTail(snapshot); void this.loadNewer(); }
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
async refreshConversation(refocus, {anchor = this.turns.at(-1)?.id, position: requestedPosition} = {}) {
|
|
337
917
|
const task = this.task?.id;
|
|
338
|
-
if (!task || this.selecting || this.refreshing && !refocus
|
|
918
|
+
if (!task || this.selecting || this.refreshing && !refocus) return;
|
|
919
|
+
this.resetNewer();
|
|
339
920
|
const generation = this.generation, refresh = this.refreshing = {};
|
|
340
|
-
let snapshot;
|
|
341
|
-
const
|
|
921
|
+
let snapshot, updated = false;
|
|
922
|
+
const startPosition = requestedPosition || this.position();
|
|
342
923
|
try {
|
|
343
|
-
const anchor = this.anchored && !latest ? position?.turn : undefined;
|
|
344
924
|
const data = snapshot = await this.loadTask(task,generation,anchor);
|
|
345
925
|
if (generation !== this.generation || refresh !== this.refreshing || this.selecting) return;
|
|
926
|
+
const position = requestedPosition || this.position() || startPosition;
|
|
346
927
|
const first = data.turns[0]?.id, overlap = this.turns.findIndex(turn => turn.id === first);
|
|
347
|
-
this.turns =
|
|
348
|
-
this.more =
|
|
349
|
-
this.
|
|
350
|
-
this.
|
|
351
|
-
|
|
928
|
+
this.turns = overlap > 0 ? [...this.turns.slice(0,overlap),...data.turns] : data.turns;
|
|
929
|
+
this.more = overlap > 0 ? this.more : data.more;
|
|
930
|
+
this.updateHead(data.head,data.headStatus,data.execution); this.task = data.task; this.updatePlan(data.plan);
|
|
931
|
+
this.app.filesPanel.setTaskDirectories(this.task.directories);
|
|
932
|
+
this.pendingPosition = position; this.renderConversation(); this.setChatError(''); updated = true;
|
|
933
|
+
} catch (error) {
|
|
934
|
+
if (refresh === this.refreshing && generation === this.generation && this.csrf) {
|
|
935
|
+
this.setChatError('对话更新失败:'+error.message,false,() => this.refreshConversation(true,{anchor,position:requestedPosition}));
|
|
936
|
+
}
|
|
937
|
+
}
|
|
352
938
|
finally {
|
|
353
939
|
if (this.refreshing === refresh) {
|
|
354
940
|
this.refreshing = undefined;
|
|
355
941
|
this.drainTail(snapshot);
|
|
942
|
+
if (updated) void this.loadNewer();
|
|
356
943
|
}
|
|
357
944
|
}
|
|
358
945
|
}
|
|
359
946
|
renderChat() {
|
|
947
|
+
this.composing = false;
|
|
360
948
|
this.chatHeader = make('header','session-chat-header');
|
|
361
|
-
this.chatTitle = make('h2',null,'聊天'); this.chatTitle.tabIndex = -1;
|
|
949
|
+
this.chatTitle = make('h2',null,'聊天'); this.chatTitle.tabIndex = -1;
|
|
950
|
+
this.chatTitle.dataset.tooltipOverflow = '';
|
|
951
|
+
this.chatMeta = make('div','session-chat-meta'); this.chatMeta.hidden = true; this.chatHeader.append(this.chatTitle,this.chatMeta);
|
|
952
|
+
this.chatMeta.tabIndex = 0; this.chatMeta.setAttribute('role','group'); this.chatMeta.setAttribute('aria-label','任务信息');
|
|
953
|
+
this.chatState = make('span','session-state'); this.chatAgent = make('span','session-agent');
|
|
954
|
+
this.chatTurns = make('span','session-turn-count'); this.chatTokens = make('span','session-token-usage');
|
|
955
|
+
this.chatStorage = make('span','session-storage-size'); this.chatModel = make('span','session-model');
|
|
956
|
+
this.chatMeta.append(this.chatState,this.chatAgent,this.chatTurns,this.chatTokens,this.chatStorage,this.chatModel);
|
|
362
957
|
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');
|
|
958
|
+
const body = this.body = make('div','chat-body session-chat-body'); body.tabIndex = 0; body.setAttribute('role','region'); body.setAttribute('aria-label','对话记录');
|
|
959
|
+
const reading = make('div','session-chat-reading');
|
|
960
|
+
this.planPanel = make('aside','session-plan-sidebar'); this.planPanel.id = 'workspace-plan-'+this.page;
|
|
961
|
+
this.planPanel.setAttribute('aria-label','执行计划'); this.planPanel.tabIndex = -1;
|
|
962
|
+
const planHeader = make('header');
|
|
963
|
+
this.planProgress = make('span','session-plan-progress');
|
|
964
|
+
planHeader.append(make('h3',null,'执行计划'),this.planProgress);
|
|
965
|
+
this.planSteps = make('ol','session-plan-steps'); this.planPanel.append(planHeader,this.planSteps);
|
|
966
|
+
this.planButton = button('',() => {
|
|
967
|
+
const open = this.planButton.getAttribute('aria-expanded') !== 'true';
|
|
968
|
+
this.setPlanOpen(open);
|
|
969
|
+
if (open) this.planPanel.focus({preventScroll:true});
|
|
970
|
+
},'session-plan-trigger');
|
|
971
|
+
this.planButton.setAttribute('aria-controls',this.planPanel.id);
|
|
972
|
+
this.planPanel.onkeydown = this.planButton.onkeydown = event => {
|
|
973
|
+
if (event.key !== 'Escape' || this.planButton.getAttribute('aria-expanded') !== 'true') return;
|
|
974
|
+
event.preventDefault(); event.stopPropagation();
|
|
975
|
+
this.setPlanOpen(false); this.planButton.focus({preventScroll:true});
|
|
976
|
+
};
|
|
977
|
+
this.setPlanOpen(false); this.planSignature = undefined; this.updatePlan(this.headPlan);
|
|
978
|
+
reading.append(body,this.planPanel);
|
|
364
979
|
this.older = button('加载更早的对话',() => this.loadOlder(),'session-more session-older'); this.older.hidden = true;
|
|
365
980
|
this.timeline = make('div','session-timeline'); this.turnNodes = new Map();
|
|
366
|
-
this.
|
|
367
|
-
this.timelineObserver
|
|
368
|
-
|
|
981
|
+
this.outbox = make('div','session-outbox'); this.outboxRows = new Map();
|
|
982
|
+
this.timelineObserver?.disconnect(); this.closeSettingsMenu();
|
|
983
|
+
this.chat.removeAttribute('data-draft');
|
|
984
|
+
const stabilizeReadingPosition = () => {
|
|
985
|
+
if (!this.task || !body.clientHeight) return;
|
|
369
986
|
this.pendingPosition ||= this.lastPosition;
|
|
370
|
-
this.restorePosition();
|
|
371
|
-
|
|
987
|
+
if (body.clientHeight === this.chatBodyHeight) this.restorePosition();
|
|
988
|
+
else window.requestAnimationFrame(() => { if (this.body === body && body.isConnected) this.restorePosition(); });
|
|
989
|
+
};
|
|
990
|
+
this.timelineObserver = new ResizeObserver(stabilizeReadingPosition);
|
|
372
991
|
this.timelineObserver.observe(this.timeline);
|
|
373
|
-
this.
|
|
992
|
+
this.timelineObserver.observe(this.outbox);
|
|
993
|
+
this.timelineObserver.observe(body);
|
|
994
|
+
body.addEventListener('load', event => {
|
|
374
995
|
const image = event.target;
|
|
375
|
-
if (image
|
|
996
|
+
if (image.matches?.('img[data-chat-image]')) { this.rememberChatImageSize(image); stabilizeReadingPosition(); }
|
|
997
|
+
}, true);
|
|
998
|
+
body.addEventListener('error', event => {
|
|
999
|
+
const image = event.target;
|
|
1000
|
+
if (image instanceof HTMLImageElement) {
|
|
1001
|
+
image.replaceWith(make('span','session-image-unavailable',image.alt ? `图片不可用:${image.alt}` : '图片不可用'));
|
|
1002
|
+
stabilizeReadingPosition();
|
|
1003
|
+
}
|
|
376
1004
|
}, true);
|
|
377
1005
|
this.timeline.append(make('div','session-empty','从左侧选择一个任务,查看对话并继续工作。'));
|
|
378
|
-
this.body.append(this.older,this.timeline);
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
if (!
|
|
383
|
-
|
|
384
|
-
};
|
|
385
|
-
|
|
1006
|
+
this.body.append(this.older,this.timeline,this.outbox);
|
|
1007
|
+
body.addEventListener('click', event => {
|
|
1008
|
+
if (this.previewChatImage(event)) return;
|
|
1009
|
+
const link = event.target.closest?.('[data-chat-file]');
|
|
1010
|
+
if (!link || !plainLinkClick(event)) return;
|
|
1011
|
+
event.preventDefault(); this.app.openChatFile(link.dataset.chatFile,'file',link.hash || undefined);
|
|
1012
|
+
});
|
|
1013
|
+
body.addEventListener('keydown',event => {
|
|
1014
|
+
if (event.key === 'Enter' || event.key === ' ') this.previewChatImage(event);
|
|
1015
|
+
});
|
|
1016
|
+
this.jump = iconButton('回到最新','M12 4v16m-6-6 6 6 6-6','session-jump',() => this.jumpToBottom());
|
|
1017
|
+
this.jump.hidden = true;
|
|
1018
|
+
body.onscroll = () => {
|
|
1019
|
+
// A growing editor changes the scroll range before the resize observer restores the reading position.
|
|
1020
|
+
if (!this.task || !this.chatBodyHeight || body.clientHeight !== this.chatBodyHeight || this.pendingPosition) return;
|
|
1021
|
+
if (this.restoredPosition?.top === body.scrollTop) return;
|
|
1022
|
+
this.restoredPosition = undefined;
|
|
1023
|
+
this.lastPosition = this.position(true);
|
|
1024
|
+
this.jump.hidden = this.atBottom();
|
|
1025
|
+
};
|
|
1026
|
+
const form = this.composer = make('form','session-composer'), field = make('div','session-composer-field');
|
|
1027
|
+
this.composerMirror = window.CSS?.supports('field-sizing','content') ? undefined : field;
|
|
386
1028
|
this.input = make('textarea'); this.input.rows = 2; this.input.maxLength = 24_000; this.input.setAttribute('aria-label','发送给 Agent 的消息');
|
|
387
|
-
|
|
388
|
-
|
|
1029
|
+
field.append(this.input);
|
|
1030
|
+
let beforeEdit;
|
|
1031
|
+
this.input.onbeforeinput = () => { beforeEdit = this.position(true); };
|
|
1032
|
+
this.input.oninput = () => {
|
|
1033
|
+
const position = beforeEdit; beforeEdit = undefined;
|
|
1034
|
+
if (this.newDraft) { this.newDraft.text = this.input.value; this.saveNewTaskDraft(); }
|
|
1035
|
+
else if (this.task) this.setDraft(this.task.id,this.input.value);
|
|
1036
|
+
this.updateComposer();
|
|
1037
|
+
this.keepComposerPosition(position);
|
|
1038
|
+
};
|
|
1039
|
+
this.input.onkeydown = event => {
|
|
1040
|
+
if (event.key !== 'Enter' || event.isComposing || this.composing || event.keyCode === 229) return;
|
|
1041
|
+
event.preventDefault();
|
|
1042
|
+
if (event.altKey) {
|
|
1043
|
+
const {value,selectionStart,selectionEnd,maxLength} = this.input;
|
|
1044
|
+
if (value.length - (selectionEnd-selectionStart) < maxLength) {
|
|
1045
|
+
this.input.setRangeText('\n',selectionStart,selectionEnd,'end');
|
|
1046
|
+
this.input.dispatchEvent(new Event('input',{bubbles:true}));
|
|
1047
|
+
}
|
|
1048
|
+
} else this.submit(event.shiftKey || event.ctrlKey || event.metaKey ? 'queue' : 'send');
|
|
1049
|
+
};
|
|
1050
|
+
this.input.setAttribute('aria-keyshortcuts','Enter Shift+Enter Control+Enter Meta+Enter Alt+Enter');
|
|
389
1051
|
this.input.oncompositionstart = () => { this.composing = true; }; this.input.oncompositionend = () => { this.composing = false; };
|
|
390
1052
|
this.opNote = make('div','session-operation'); this.opNote.setAttribute('role','status'); this.opNote.hidden = true;
|
|
391
|
-
const actions = make('div','session-composer-actions');
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
this.
|
|
1053
|
+
const actions = make('div','session-composer-actions');
|
|
1054
|
+
const picker = make('input'); picker.type = 'file'; picker.multiple = true; picker.hidden = true;
|
|
1055
|
+
picker.onchange = () => { this.addAttachments(picker.files); picker.value = ''; };
|
|
1056
|
+
this.attach = iconButton('添加附件','M12 5v14M5 12h14','session-attach',() => picker.click());
|
|
1057
|
+
form.append(picker);
|
|
1058
|
+
form.addEventListener('paste',event => {
|
|
1059
|
+
if (event.defaultPrevented || this.input.disabled) return;
|
|
1060
|
+
const files = clipboardFiles(event.clipboardData);
|
|
1061
|
+
if (!files.length) return;
|
|
1062
|
+
event.preventDefault();
|
|
1063
|
+
this.addAttachments(files);
|
|
1064
|
+
});
|
|
1065
|
+
this.chat.ondragover = event => {
|
|
1066
|
+
if (!event.dataTransfer?.types.includes('Files')) return;
|
|
1067
|
+
event.preventDefault(); event.dataTransfer.dropEffect = this.input.disabled ? 'none' : 'copy';
|
|
1068
|
+
form.toggleAttribute('data-drop',!this.input.disabled);
|
|
1069
|
+
};
|
|
1070
|
+
this.chat.ondragleave = event => { if (!this.chat.contains(event.relatedTarget)) form.removeAttribute('data-drop'); };
|
|
1071
|
+
this.chat.ondragend = () => form.removeAttribute('data-drop');
|
|
1072
|
+
this.chat.ondrop = event => {
|
|
1073
|
+
if (!event.dataTransfer?.files.length) return;
|
|
1074
|
+
event.preventDefault(); form.removeAttribute('data-drop'); this.addAttachments(event.dataTransfer.files);
|
|
1075
|
+
};
|
|
1076
|
+
this.schedule = iconButton('定时任务','M12 7v5l3 2m6-2a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z','session-schedule',() => this.openSchedule());
|
|
1077
|
+
this.schedule.setAttribute('aria-haspopup','dialog');
|
|
1078
|
+
this.stop = iconButton('停止','M6 6h12v12H6Z','session-stop',() => this.submit('stop')); this.stop.hidden = true;
|
|
1079
|
+
this.send = iconButton('发送','M12 20V4m-6 6 6-6 6 6','session-primary'); this.send.type = 'submit';
|
|
1080
|
+
this.send.setAttribute('aria-keyshortcuts','Enter');
|
|
1081
|
+
for (const control of [this.attach,this.stop,this.schedule,this.send]) control.dataset.tooltip = '';
|
|
395
1082
|
form.onsubmit = event => { event.preventDefault(); void this.submit('send'); };
|
|
396
|
-
this.
|
|
1083
|
+
this.attachments = make('div','session-draft-images'); this.attachments.setAttribute('role','group'); this.attachments.setAttribute('aria-label','待发送附件');
|
|
1084
|
+
this.imageNotice = make('div','session-image-notice session-error'); this.imageNotice.setAttribute('role','status'); this.imageNotice.hidden = true;
|
|
1085
|
+
this.draftStorageNote = make('div','session-image-notice session-error','草稿附件暂未保存,刷新可能会丢失。');
|
|
1086
|
+
this.draftStorageNote.setAttribute('role','status'); this.draftStorageNote.hidden = true;
|
|
1087
|
+
const dialog = this.imageDialog = make('dialog','session-image-dialog'); dialog.setAttribute('aria-label','图片预览');
|
|
1088
|
+
const dismiss = iconButton('关闭图片预览','M6 6l12 12M18 6 6 18','session-image-dismiss',() => dialog.close());
|
|
1089
|
+
dismiss.autofocus = true; dismiss.setAttribute('aria-keyshortcuts','Escape');
|
|
1090
|
+
this.imagePreview = make('img'); this.imagePreview.alt = '';
|
|
1091
|
+
dialog.append(this.imagePreview,dismiss);
|
|
1092
|
+
dialog.onclick = event => { if (event.target === dialog) dialog.close(); };
|
|
1093
|
+
const preview = this.imagePreview;
|
|
1094
|
+
dialog.onclose = () => { if (!dialog.open) preview.removeAttribute('src'); };
|
|
1095
|
+
const settings = make('div','session-compose-settings');
|
|
1096
|
+
this.modelButton = button('',() => this.openTaskSettings('model'),'session-compose-model');
|
|
1097
|
+
this.thinkingButton = button('',() => this.openTaskSettings('thinking'),'session-compose-thinking');
|
|
1098
|
+
this.modelButton.setAttribute('aria-label','切换模型'); this.thinkingButton.setAttribute('aria-label','切换思考强度');
|
|
1099
|
+
const menu = this.settingsMenu = make('div','session-settings-picker'); menu.hidden = true;
|
|
1100
|
+
menu.id = 'session-settings-'+this.page; menu.tabIndex = -1; menu.setAttribute('role','dialog');
|
|
1101
|
+
for (const control of [this.modelButton,this.thinkingButton]) {
|
|
1102
|
+
control.append(make('span')); control.setAttribute('aria-haspopup','dialog');
|
|
1103
|
+
control.setAttribute('aria-controls',menu.id); control.setAttribute('aria-expanded','false');
|
|
1104
|
+
}
|
|
1105
|
+
settings.append(this.modelButton,this.thinkingButton);
|
|
1106
|
+
const trailing = make('div','session-composer-trailing'), controls = make('div','session-composer-controls');
|
|
1107
|
+
controls.append(this.stop,this.schedule,this.send); trailing.append(settings,controls); actions.append(this.attach,trailing);
|
|
1108
|
+
form.append(this.attachments,field,actions,menu);
|
|
1109
|
+
this.draftTools = make('div','session-new-draft-tools'); this.draftTools.hidden = true;
|
|
1110
|
+
this.executionBar = make('div','session-run-status'); this.executionBar.hidden = true;
|
|
1111
|
+
this.executionBar.setAttribute('role','group'); this.executionBar.setAttribute('aria-label','本轮执行信息');
|
|
1112
|
+
const duration = make('span','session-run-duration','耗时 ');
|
|
1113
|
+
this.elapsedTime = make('time'); duration.append(this.elapsedTime);
|
|
1114
|
+
this.executionModel = make('span','session-run-model'); this.executionThinking = make('span','session-run-thinking');
|
|
1115
|
+
this.executionBar.append(duration,this.executionModel,this.executionThinking);
|
|
1116
|
+
this.queueList = make('ol','session-prompt-queue'); this.queueList.setAttribute('aria-label','已排队的消息');
|
|
1117
|
+
this.queueRows = new Map(); this.queueEdit = undefined;
|
|
1118
|
+
const footer = make('div','session-chat-footer'); footer.append(this.jump,this.planButton,this.opNote,this.imageNotice,this.draftStorageNote,this.draftTools,this.executionBar,this.queueList,form);
|
|
1119
|
+
this.chat.replaceChildren(this.chatHeader,this.chatError,reading,footer,dialog);
|
|
397
1120
|
this.updateComposer();
|
|
398
1121
|
}
|
|
1122
|
+
setPlanOpen(open) {
|
|
1123
|
+
this.chat.toggleAttribute('data-plan-open',open);
|
|
1124
|
+
this.planButton.setAttribute('aria-expanded',String(open));
|
|
1125
|
+
}
|
|
1126
|
+
updatePlan(plan = []) {
|
|
1127
|
+
this.headPlan = plan;
|
|
1128
|
+
if (!this.planPanel) return;
|
|
1129
|
+
const hidden = !this.task || !plan.length || Boolean(this.newDraft);
|
|
1130
|
+
this.planPanel.hidden = this.planButton.hidden = hidden;
|
|
1131
|
+
this.body.parentElement?.toggleAttribute('hidden',Boolean(this.newDraft));
|
|
1132
|
+
if (hidden) this.setPlanOpen(false);
|
|
1133
|
+
const signature = JSON.stringify(plan);
|
|
1134
|
+
if (this.planSignature === signature) return;
|
|
1135
|
+
this.planSignature = signature;
|
|
1136
|
+
const progress = plan.filter(step => step.status === 'completed').length+'/'+plan.length;
|
|
1137
|
+
this.planButton.textContent = this.planProgress.textContent = progress;
|
|
1138
|
+
labelButton(this.planButton,'执行计划 '+progress);
|
|
1139
|
+
const names = {pending:'待执行',in_progress:'执行中',completed:'已完成'};
|
|
1140
|
+
this.planSteps.replaceChildren(...plan.map(step => {
|
|
1141
|
+
const item = make('li'); item.dataset.status = step.status;
|
|
1142
|
+
const mark = make('span','session-plan-mark'); mark.setAttribute('aria-hidden','true');
|
|
1143
|
+
item.append(mark,make('span',null,step.text));
|
|
1144
|
+
item.setAttribute('aria-label',(names[step.status] || names.pending)+' · '+step.text);
|
|
1145
|
+
return item;
|
|
1146
|
+
}));
|
|
1147
|
+
}
|
|
1148
|
+
openTaskSettings(preferred) {
|
|
1149
|
+
if (this.newDraft) { this.openDraftSettings(this.newDraft,preferred); return; }
|
|
1150
|
+
const task = this.task?.id, grant = this.csrf;
|
|
1151
|
+
if (!task || !grant || this.selecting || this.task.status === 'closed' || this.pendingSettings.has(task)) return;
|
|
1152
|
+
const anchor = preferred === 'thinking' ? this.thinkingButton : this.modelButton;
|
|
1153
|
+
if (this.settingsMenuState?.anchor === anchor) { this.closeSettingsMenu(true); return; }
|
|
1154
|
+
this.closeSettingsMenu();
|
|
1155
|
+
const menu = this.settingsMenu, choices = make('div','session-settings-options');
|
|
1156
|
+
const note = make('div','session-dialog-status','正在读取…'); note.setAttribute('role','status');
|
|
1157
|
+
const view = this.settingsMenuState = {task,anchor,events:new AbortController()};
|
|
1158
|
+
const current = () => this.settingsMenuState === view && menu.isConnected && this.task?.id === task && this.csrf === grant;
|
|
1159
|
+
menu.replaceChildren(choices,note); menu.setAttribute('aria-label',preferred === 'thinking' ? '选择思考强度' : '选择模型');
|
|
1160
|
+
menu.hidden = false; anchor.setAttribute('aria-expanded','true'); menu.focus({preventScroll:true});
|
|
1161
|
+
const outside = event => {
|
|
1162
|
+
if (!menu.contains(event.target) && !this.modelButton.contains(event.target) && !this.thinkingButton.contains(event.target)) this.closeSettingsMenu();
|
|
1163
|
+
};
|
|
1164
|
+
const {signal} = view.events;
|
|
1165
|
+
document.addEventListener('pointerdown',outside,{signal}); document.addEventListener('focusin',outside,{signal});
|
|
1166
|
+
document.addEventListener('keydown',event => {
|
|
1167
|
+
if (event.key === 'Escape') { event.preventDefault(); this.closeSettingsMenu(true); return; }
|
|
1168
|
+
if (!menu.contains(event.target)) return;
|
|
1169
|
+
const option = event.target.closest('.session-settings-option');
|
|
1170
|
+
if (event.key === 'Enter' && option) { event.preventDefault(); option.click(); return; }
|
|
1171
|
+
if (!['ArrowDown','ArrowUp','Home','End'].includes(event.key)) return;
|
|
1172
|
+
const options = [...choices.querySelectorAll('button:not(:disabled)')]; if (!options.length) return;
|
|
1173
|
+
event.preventDefault();
|
|
1174
|
+
const index = options.indexOf(document.activeElement), last = options.length-1;
|
|
1175
|
+
const next = event.key === 'Home' ? 0 : event.key === 'End' ? last : event.key === 'ArrowDown'
|
|
1176
|
+
? (index+1)%options.length : index <= 0 ? last : index-1;
|
|
1177
|
+
options[next].focus();
|
|
1178
|
+
},{signal});
|
|
1179
|
+
const showNote = (text,error = false) => {
|
|
1180
|
+
note.textContent = text; note.hidden = !text; note.classList.toggle('session-error',error);
|
|
1181
|
+
};
|
|
1182
|
+
let state;
|
|
1183
|
+
const render = (data,error) => {
|
|
1184
|
+
state = data;
|
|
1185
|
+
const models = preferred === 'model', selected = models ? data.model : data.thinking;
|
|
1186
|
+
const items = models ? data.models.map(item=>[item.id,item.displayName || item.id]) : data.reasoningOptions.map(item=>[item.value,effortLabel(item.value)]);
|
|
1187
|
+
choices.replaceChildren(...items.map(([value,label]) => {
|
|
1188
|
+
const option = button('',() => saveSetting(value),'session-settings-option');
|
|
1189
|
+
option.setAttribute('aria-pressed',String(value === selected));
|
|
1190
|
+
option.append(make('span',null,label));
|
|
1191
|
+
if (value === selected) { const mark = make('span','session-settings-check','✓'); mark.setAttribute('aria-hidden','true'); option.append(mark); }
|
|
1192
|
+
return option;
|
|
1193
|
+
}));
|
|
1194
|
+
showNote(error || (data.pending ? '当前轮次完成后生效。' : items.length ? '' : models ? '没有可选模型。' : '当前模型不支持切换思考强度。'),Boolean(error));
|
|
1195
|
+
const selectedOption = choices.querySelector('[aria-pressed=true]') || choices.firstElementChild;
|
|
1196
|
+
(selectedOption || menu).focus({preventScroll:true});
|
|
1197
|
+
selectedOption?.scrollIntoView({block:'nearest'});
|
|
1198
|
+
};
|
|
1199
|
+
const saveSetting = async value => {
|
|
1200
|
+
if (!current() || !value || this.pendingSettings.has(task)) return;
|
|
1201
|
+
if (value === state[preferred]) { this.closeSettingsMenu(true); return; }
|
|
1202
|
+
this.pendingSettings.add(task); this.updateComposer();
|
|
1203
|
+
menu.focus({preventScroll:true});
|
|
1204
|
+
for (const choice of choices.children) choice.disabled = true;
|
|
1205
|
+
showNote('正在保存…');
|
|
1206
|
+
let saved = false;
|
|
1207
|
+
try {
|
|
1208
|
+
const data = await this.fetch('/task-settings',{body:{task,setting:preferred,value},timeout:60_000});
|
|
1209
|
+
if (!data.pending && this.task?.id === task && this.csrf === grant) {
|
|
1210
|
+
Object.assign(this.task,{model:data.model,provider:data.provider,thinking:data.thinking}); this.renderChatHeader();
|
|
1211
|
+
}
|
|
1212
|
+
if (current() && data.pending) render(data);
|
|
1213
|
+
saved = !data.pending;
|
|
1214
|
+
} catch (error) { if (current()) render(state,error.message); }
|
|
1215
|
+
finally {
|
|
1216
|
+
this.pendingSettings.delete(task); if (this.task?.id === task) this.updateComposer();
|
|
1217
|
+
if (saved && current()) this.closeSettingsMenu(true);
|
|
1218
|
+
}
|
|
1219
|
+
};
|
|
1220
|
+
void this.fetch('/task-settings',{params:{task},timeout:60_000}).then(data => {
|
|
1221
|
+
if (current()) render(data);
|
|
1222
|
+
}).catch(error => { if (current()) showNote(error.message,true); });
|
|
1223
|
+
}
|
|
1224
|
+
closeSettingsMenu(focus = false) {
|
|
1225
|
+
const view = this.settingsMenuState; if (!view) return;
|
|
1226
|
+
this.settingsMenuState = undefined; view.events.abort();
|
|
1227
|
+
this.settingsMenu.hidden = true; view.anchor.setAttribute('aria-expanded','false');
|
|
1228
|
+
if (focus && !view.anchor.disabled) view.anchor.focus({preventScroll:true});
|
|
1229
|
+
}
|
|
1230
|
+
openDraftSettings(draft,preferred) {
|
|
1231
|
+
if (!draft.agents?.length || draft.sending || this.settingsDialog?.open) return;
|
|
1232
|
+
const dialog = this.settingsDialog = this.createDialog('运行设置',this.chat);
|
|
1233
|
+
const anchor = preferred === 'thinking' ? this.thinkingButton : this.modelButton;
|
|
1234
|
+
dialog.id = this.settingsMenu.id+'-draft';
|
|
1235
|
+
anchor.setAttribute('aria-controls',dialog.id); anchor.setAttribute('aria-expanded','true');
|
|
1236
|
+
const form = make('form'), agent = make('select'), model = make('select'), thinking = make('select');
|
|
1237
|
+
const note = make('div','session-dialog-status'); note.setAttribute('role','status');
|
|
1238
|
+
const options = (node,items,value,fallback) => {
|
|
1239
|
+
node.replaceChildren();
|
|
1240
|
+
for (const [key,label] of [[null,fallback],...items]) {
|
|
1241
|
+
const option = make('option',null,label); option.value = key || ''; option.selected = (key || undefined) === value; node.append(option);
|
|
1242
|
+
}
|
|
1243
|
+
node.disabled = !items.length;
|
|
1244
|
+
};
|
|
1245
|
+
options(agent,draft.agents.map(item=>[item.name,item.title]),draft.agent,'选择 Agent');
|
|
1246
|
+
this.dialogField(form,'Agent',agent); this.dialogField(form,'模型',model); this.dialogField(form,'思考强度',thinking);
|
|
1247
|
+
form.append(note); dialog.append(form); form.onsubmit = event => event.preventDefault();
|
|
1248
|
+
dialog.addEventListener('close',() => {
|
|
1249
|
+
anchor.setAttribute('aria-controls',this.settingsMenu.id); anchor.setAttribute('aria-expanded','false'); dialog.remove();
|
|
1250
|
+
},{once:true});
|
|
1251
|
+
dialog.showModal();
|
|
1252
|
+
let details, sequence = 0;
|
|
1253
|
+
const renderThinking = () => {
|
|
1254
|
+
const selected = details.models.find(item=>item.id === (draft.model || details.model)) ?? details.models.find(item=>item.isDefault);
|
|
1255
|
+
const levels = selected?.supportedReasoningEfforts || [];
|
|
1256
|
+
if (draft.thinking && !levels.some(item=>item.value === draft.thinking)) draft.thinking = undefined;
|
|
1257
|
+
options(thinking,levels.map(item=>[item.value,effortLabel(item.value)]),draft.thinking,'使用模型默认值');
|
|
1258
|
+
};
|
|
1259
|
+
const load = async () => {
|
|
1260
|
+
const version = ++sequence, current = () => dialog.open && this.newDraft === draft && sequence === version;
|
|
1261
|
+
model.disabled = thinking.disabled = true; note.textContent = '正在读取…';
|
|
1262
|
+
if (!draft.agent) return;
|
|
1263
|
+
try {
|
|
1264
|
+
const data = await this.fetch('/draft-settings',{params:{agent:draft.agent},timeout:60_000});
|
|
1265
|
+
if (!current()) return;
|
|
1266
|
+
details = data; options(model,data.models.map(item=>[item.id,item.displayName || item.id]),draft.model,'使用 Agent 默认模型');
|
|
1267
|
+
renderThinking(); note.textContent = '发送第一条消息时应用。';
|
|
1268
|
+
(preferred === 'thinking' && !thinking.disabled ? thinking : model).focus();
|
|
1269
|
+
} catch (error) { if (current()) note.textContent = error.message; }
|
|
1270
|
+
};
|
|
1271
|
+
agent.onchange = () => {
|
|
1272
|
+
if (!agent.value) return;
|
|
1273
|
+
Object.assign(draft,{agent:agent.value,model:undefined,thinking:undefined,request:uuid()});
|
|
1274
|
+
this.updateComposer(); void load();
|
|
1275
|
+
};
|
|
1276
|
+
model.onchange = () => { draft.model = model.value || undefined; draft.request = uuid(); renderThinking(); this.saveNewTaskDraft(); this.updateComposer(); };
|
|
1277
|
+
thinking.onchange = () => { draft.thinking = thinking.value || undefined; draft.request = uuid(); this.saveNewTaskDraft(); this.updateComposer(); };
|
|
1278
|
+
void load();
|
|
1279
|
+
}
|
|
399
1280
|
setChatError(message, retry = false, action) {
|
|
400
1281
|
if (!this.chatError?.isConnected) return;
|
|
401
1282
|
this.chatError.replaceChildren(make('span',null,message)); this.chatError.hidden = !message;
|
|
402
1283
|
if (retry || action) this.chatError.append(button('重试',action || (() => this.refreshConversation(true)),'session-quiet'));
|
|
403
1284
|
}
|
|
404
1285
|
renderChatHeader() {
|
|
405
|
-
const task = this.task;
|
|
406
|
-
this.chatTitle
|
|
407
|
-
this.chatMeta.
|
|
1286
|
+
const task = this.task, draft = Boolean(this.newDraft);
|
|
1287
|
+
setText(this.chatTitle,draft ? '新建任务' : task ? task.title || '未命名任务' : '聊天');
|
|
1288
|
+
this.chatMeta.hidden = draft || !task;
|
|
1289
|
+
if (draft) return;
|
|
1290
|
+
this.app.updateTaskTitle(task);
|
|
408
1291
|
if (!task) return;
|
|
409
|
-
const
|
|
410
|
-
const
|
|
411
|
-
|
|
1292
|
+
const {turnCount,totalTokens,storageSize} = task.metrics ?? {};
|
|
1293
|
+
const items = [
|
|
1294
|
+
[this.chatState,status(task.status)],
|
|
1295
|
+
[this.chatAgent,task.agent],
|
|
1296
|
+
[this.chatTurns,Number.isSafeInteger(turnCount) ? headerNumbers.format(turnCount)+' 轮' : ''],
|
|
1297
|
+
[this.chatTokens,Number.isSafeInteger(totalTokens) ? headerTokens.format(totalTokens)+' tokens' : ''],
|
|
1298
|
+
[this.chatStorage,storageSize ? '磁盘 '+storageSize : ''],
|
|
1299
|
+
[this.chatModel,[task.provider,task.model].filter(Boolean).join(' · ')],
|
|
1300
|
+
];
|
|
1301
|
+
for (const [node,text] of items) {
|
|
1302
|
+
setText(node,text || ''); node.hidden = !text;
|
|
1303
|
+
}
|
|
1304
|
+
this.chatState.dataset.status = task.status;
|
|
412
1305
|
}
|
|
413
1306
|
renderConversation() {
|
|
414
1307
|
this.renderChatHeader(); this.redraw(); this.updateComposer();
|
|
415
1308
|
this.older.hidden = !this.more;
|
|
416
|
-
|
|
1309
|
+
this.jump.hidden = this.atBottom();
|
|
417
1310
|
}
|
|
418
1311
|
redraw() {
|
|
419
|
-
|
|
420
|
-
|
|
1312
|
+
let position = this.pendingPosition || this.position();
|
|
1313
|
+
const messages = this.messages(this.task.id), matched = new Set();
|
|
1314
|
+
if (messages.size) for (const turn of this.turns) {
|
|
1315
|
+
if (turn.promptRequestId && messages.has(turn.promptRequestId)) {
|
|
1316
|
+
if (turn.id.startsWith('pending_')) matched.add(turn.promptRequestId);
|
|
1317
|
+
else this.removeMessage(this.task.id,turn.promptRequestId);
|
|
1318
|
+
}
|
|
1319
|
+
for (const item of turn.timeline) if (item.kind === 'user' && item.requestId) this.removeMessage(this.task.id,item.requestId);
|
|
1320
|
+
}
|
|
1321
|
+
if (!this.turns.length) {
|
|
1322
|
+
this.timeline.replaceChildren(...(messages.size ? [] : [make('div','session-empty','还没有对话。发送一条消息,开始新的轮次。')]));
|
|
1323
|
+
this.turnNodes.clear();
|
|
1324
|
+
}
|
|
421
1325
|
else {
|
|
422
1326
|
this.timeline.querySelector('.session-empty')?.remove();
|
|
1327
|
+
const pending = new Map([...this.turnNodes].flatMap(([id,entry]) => id.startsWith('pending_') && entry.turn?.promptRequestId
|
|
1328
|
+
? [[entry.turn.promptRequestId,entry]] : []));
|
|
1329
|
+
for (const turn of this.turns) {
|
|
1330
|
+
const entry = pending.get(turn.promptRequestId);
|
|
1331
|
+
if (!entry || turn.id.startsWith('pending_') || this.turnNodes.has(turn.id)) continue;
|
|
1332
|
+
const temporary = entry.node.dataset.turn;
|
|
1333
|
+
this.turnNodes.delete(temporary);
|
|
1334
|
+
entry.node.dataset.turn = turn.id;
|
|
1335
|
+
this.turnNodes.set(turn.id,entry);
|
|
1336
|
+
if (position?.turn === temporary) position = {...position,turn:turn.id};
|
|
1337
|
+
}
|
|
423
1338
|
const keep = new Set(this.turns.map(turn => turn.id));
|
|
424
1339
|
for (const [id,state] of this.turnNodes) if (!keep.has(id)) { state.node.remove(); this.turnNodes.delete(id); }
|
|
425
1340
|
let previous = null;
|
|
426
1341
|
for (const turn of this.turns) {
|
|
427
|
-
const node = this.renderTurn(turn), next = previous ? previous.nextSibling : this.timeline.firstChild;
|
|
1342
|
+
const node = this.renderTurn(turn,messages.get(turn.promptRequestId)), next = previous ? previous.nextSibling : this.timeline.firstChild;
|
|
428
1343
|
if (node !== next) this.timeline.insertBefore(node,next);
|
|
429
1344
|
previous = node;
|
|
430
1345
|
}
|
|
431
1346
|
}
|
|
1347
|
+
this.renderOutbox(messages,matched);
|
|
432
1348
|
this.pendingPosition = position; this.restorePosition();
|
|
433
1349
|
}
|
|
434
|
-
renderTurn(turn) {
|
|
1350
|
+
renderTurn(turn,op) {
|
|
435
1351
|
let entry = this.turnNodes.get(turn.id);
|
|
436
1352
|
if (!entry) {
|
|
437
1353
|
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')
|
|
439
|
-
|
|
440
|
-
|
|
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); };
|
|
1354
|
+
const header = make('div','session-turn-meta'), content = make('div','session-turn-content');
|
|
1355
|
+
node.append(header,content);
|
|
1356
|
+
entry = {node,header,content,rows:new Map()}; this.turnNodes.set(turn.id,entry);
|
|
443
1357
|
}
|
|
444
|
-
const
|
|
1358
|
+
const error = op?.error, closed = this.task.status === 'closed';
|
|
1359
|
+
if (entry.turn === turn && entry.error === error && entry.closed === closed) return entry.node;
|
|
1360
|
+
const signature = JSON.stringify([turn,error,closed]);
|
|
1361
|
+
Object.assign(entry,{turn,error,closed});
|
|
445
1362
|
if (entry.signature === signature) return entry.node;
|
|
446
1363
|
entry.signature = signature;
|
|
447
1364
|
const time = Number.isFinite(turn.startedAt) && turn.startedAt > 0 ? new Date(turn.startedAt).toLocaleString(undefined,{month:'short',day:'numeric',hour:'2-digit',minute:'2-digit'}) : '';
|
|
448
|
-
entry.header
|
|
449
|
-
|
|
1365
|
+
setText(entry.header,[time,turn.status === 'completed' ? null : status(turn.status),turn.summary?'仅有摘要':null,turn.delivered === false?'飞书待投递':null].filter(Boolean).join(' · '));
|
|
1366
|
+
entry.header.hidden = !entry.header.textContent;
|
|
1367
|
+
const rows = new Map(), usedGroups = new Set();
|
|
1368
|
+
const visibleTools = turn.compact ? new Set(turn.timeline.flatMap(item => item.kind === 'execution' ? item.tools.map(tool => tool.id) : [])) : undefined;
|
|
1369
|
+
const groupsByTool = new Map();
|
|
1370
|
+
for (const existing of entry.rows.values()) {
|
|
1371
|
+
for (const toolId of existing.rows?.keys() || []) groupsByTool.set(toolId,existing);
|
|
1372
|
+
}
|
|
450
1373
|
const place = (key, value, build) => {
|
|
451
1374
|
const old = entry.rows.get(key), signature = JSON.stringify(value);
|
|
452
1375
|
rows.set(key,old?.signature === signature ? old : {signature,node:build()});
|
|
453
1376
|
};
|
|
454
|
-
const message = (key,
|
|
455
|
-
const
|
|
456
|
-
|
|
457
|
-
if (
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
1377
|
+
const message = (key, role, text, images, answer, note, outgoing, files, request) => {
|
|
1378
|
+
const previous = entry.rows.get(key) ?? this.outboxRows.get(request);
|
|
1379
|
+
const signature = JSON.stringify([role,text,images,answer,note,outgoing?.error,outgoing?.error && this.task.status,files]);
|
|
1380
|
+
if (previous?.signature === signature) { rows.set(key,previous); return; }
|
|
1381
|
+
const node = this.messageNode(role,text,images,answer,note,outgoing,files);
|
|
1382
|
+
if (previous?.node.matches('.session-message') && node.matches('.session-message')) {
|
|
1383
|
+
window.agentBotLiveMarkup.patchNode(previous.node,node);
|
|
1384
|
+
previous.signature = signature; rows.set(key,previous);
|
|
1385
|
+
} else rows.set(key,{signature,node});
|
|
1386
|
+
};
|
|
1387
|
+
if (turn.prompt || turn.promptImages?.length || turn.promptFiles?.length)
|
|
1388
|
+
message('prompt','user',turn.prompt,turn.promptImages,undefined,undefined,op,turn.promptFiles,turn.promptRequestId);
|
|
1389
|
+
for (const item of turn.timeline) {
|
|
1390
|
+
const key = 'activity:'+item.id;
|
|
1391
|
+
if (item.kind === 'execution') {
|
|
1392
|
+
const exact = entry.rows.get(key);
|
|
1393
|
+
const old = exact && !usedGroups.has(exact) ? exact
|
|
1394
|
+
: item.tools.map(tool => groupsByTool.get(tool.id)).find(group => group && !usedGroups.has(group));
|
|
1395
|
+
const group = this.executionGroup(turn,item,old,visibleTools);
|
|
1396
|
+
usedGroups.add(group); rows.set(key,group);
|
|
473
1397
|
}
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
if (turn.
|
|
1398
|
+
else if (item.kind === 'user') message(key,'user',item.text,item.images,undefined,undefined,undefined,item.files,item.requestId);
|
|
1399
|
+
else message(key,'assistant',item.text,undefined,item.rich,item.kind === 'system' ? 'session-system'
|
|
1400
|
+
: item.kind === 'reasoning' ? 'session-thinking' : 'session-commentary');
|
|
1401
|
+
}
|
|
1402
|
+
if (turn.hasDetails) rows.set('overview',this.executionOverview(turn,entry.rows.get('overview')));
|
|
1403
|
+
if (turn.compact) place('compact',true,() => make('p','session-muted session-compact','仅显示已保存的部分活动,完整记录请查看 Turn Preview。'));
|
|
1404
|
+
if (turn.answer) message('answer','assistant',undefined,undefined,turn.answer);
|
|
1405
|
+
if (turn.final && turn.answerExport) place('answer-actions',[turn.status,turn.previewUrl,closed],() => this.answerActions(turn,closed));
|
|
479
1406
|
if (turn.error) place('error',turn.error,() => make('p','session-error session-turn-error',turn.error));
|
|
480
1407
|
if (turn.status === 'waiting_for_approval') place('approval',true,() => make('p','session-waiting','请到任务原来的飞书会话确认。'));
|
|
481
1408
|
if (!rows.size) place('waiting',true,() => make('div','session-muted','正在等待 Agent 的输出…'));
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
1409
|
+
const displayed = keepOpenGroups(entry.rows,rows,visibleTools);
|
|
1410
|
+
syncRows(entry.content,entry.rows,displayed);
|
|
1411
|
+
entry.rows = displayed;
|
|
1412
|
+
return entry.node;
|
|
1413
|
+
}
|
|
1414
|
+
answerActions(turn,closed) {
|
|
1415
|
+
const row = make('div','session-answer-actions'), feedback = make('span','session-muted');
|
|
1416
|
+
row.setAttribute('role','group'); row.setAttribute('aria-label','最终回答操作');
|
|
1417
|
+
feedback.setAttribute('role','status');
|
|
1418
|
+
const actions = [
|
|
1419
|
+
['copy','复制 Markdown','M9 9h11v12H9zM15 9V4H4v12h5'],
|
|
1420
|
+
['download','下载 Markdown','M12 3v12m-5-5 5 5 5-5M5 16v5h14v-5'],
|
|
1421
|
+
['reset','重置当前聊天到这一轮','M4 10a8 8 0 1 1 2 8m-2-8V4m0 6h6'],
|
|
1422
|
+
['fork','从这一轮创建分支','M6 3a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm0 14a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm0 0V7m0 7h4a7 7 0 0 0 7-7m0-4a2 2 0 1 0 0 4 2 2 0 0 0 0-4z'],
|
|
1423
|
+
['share','复制 Turn Preview 链接','M10 13a4 4 0 0 0 6 0l4-4a4 4 0 1 0-6-6l-2 2m2 6a4 4 0 0 0-6 0l-4 4a4 4 0 1 0 6 6l2-2'],
|
|
1424
|
+
];
|
|
1425
|
+
const task = this.task.id;
|
|
1426
|
+
for (const [action,label,path] of actions) {
|
|
1427
|
+
const control = iconButton(label,path,'session-answer-action',() => void this.runAnswerAction(task,turn,action,control,feedback));
|
|
1428
|
+
control.dataset.answerAction = action;
|
|
1429
|
+
control.disabled = action === 'share' ? !turn.previewUrl : action === 'reset' ? closed || turn.status !== 'completed'
|
|
1430
|
+
: action === 'fork' && turn.status !== 'completed';
|
|
1431
|
+
row.append(control);
|
|
1432
|
+
}
|
|
1433
|
+
row.append(feedback);
|
|
1434
|
+
return row;
|
|
1435
|
+
}
|
|
1436
|
+
async runAnswerAction(task, turn, action, control, feedback) {
|
|
1437
|
+
const generation = this.generation, mutates = action === 'reset' || action === 'fork';
|
|
1438
|
+
if (control.disabled || task !== this.task?.id || mutates && (this.selecting || this.pendingTurnActions.has(task))) return;
|
|
1439
|
+
if (mutates) this.pendingTurnActions.add(task);
|
|
1440
|
+
control.disabled = true; feedback.textContent = '';
|
|
496
1441
|
try {
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
if (
|
|
501
|
-
const
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
1442
|
+
if (action === 'share') {
|
|
1443
|
+
await window.agentBotMarkdown.copy(turn.previewUrl);
|
|
1444
|
+
feedback.textContent = '已复制分享链接';
|
|
1445
|
+
} else if (action === 'copy' || action === 'download') {
|
|
1446
|
+
const answer = this.fetch('/answer',{params:{task,turn:turn.id}});
|
|
1447
|
+
if (action === 'copy') await window.agentBotMarkdown.copy(answer.then(data => data.markdown));
|
|
1448
|
+
else {
|
|
1449
|
+
const {markdown,filename} = await answer;
|
|
1450
|
+
window.agentBotMarkdown.download(markdown,filename);
|
|
1451
|
+
}
|
|
1452
|
+
feedback.textContent = action === 'copy' ? '已复制 Markdown' : '已开始下载';
|
|
1453
|
+
} else {
|
|
1454
|
+
feedback.textContent = action === 'reset' ? '正在重置…' : '正在创建分支…';
|
|
1455
|
+
const data = await this.fetch('/turn-action',{body:{task,turn:turn.id,action},timeout:300_000});
|
|
1456
|
+
if (this.generation !== generation || this.task?.id !== task) return;
|
|
1457
|
+
if (action === 'reset') {
|
|
1458
|
+
await this.refreshConversation(true,{anchor:turn.id,position:{bottom:true}});
|
|
1459
|
+
feedback.textContent = '已重置到这一轮';
|
|
1460
|
+
} else {
|
|
1461
|
+
feedback.textContent = '已创建分支';
|
|
1462
|
+
await this.choose(data.id);
|
|
1463
|
+
void this.loadGroups(true);
|
|
1464
|
+
}
|
|
1465
|
+
}
|
|
1466
|
+
} catch (error) {
|
|
1467
|
+
feedback.textContent = error.status ? error.message : action === 'copy' || action === 'share'
|
|
1468
|
+
? '复制失败,请检查剪贴板权限或网络连接。' : action === 'download' ? '下载失败,请重试。' : '无法确认操作结果,请刷新任务列表。';
|
|
1469
|
+
} finally {
|
|
1470
|
+
if (mutates) this.pendingTurnActions.delete(task);
|
|
1471
|
+
control.disabled = false;
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
messageNode(role,text,images,answer,note,outgoing,files) {
|
|
1475
|
+
const node = make('section','session-message '+role+(note?' '+note:''));
|
|
1476
|
+
node.setAttribute('aria-label',role === 'user' ? '你的消息' : note === 'session-commentary' ? '进展说明'
|
|
1477
|
+
: note === 'session-thinking' ? '思考摘要' : note ? '运行提示' : 'Agent 回答');
|
|
1478
|
+
if (text) node.append(make('div','session-message-text',text));
|
|
1479
|
+
if (images?.length) {
|
|
1480
|
+
const attachments = make('div','session-message-images');
|
|
1481
|
+
for (const [index,src] of images.entries()) {
|
|
1482
|
+
if (!src) { attachments.append(make('span','session-image-unavailable','图片不可用')); continue; }
|
|
1483
|
+
const image = make('img'); image.alt = `附件 ${index+1}`; image.loading = 'lazy'; image.decoding = 'async'; image.src = src;
|
|
1484
|
+
this.prepareChatImage(image); attachments.append(image);
|
|
523
1485
|
}
|
|
524
|
-
|
|
525
|
-
|
|
1486
|
+
node.append(attachments);
|
|
1487
|
+
}
|
|
1488
|
+
if (files?.length) {
|
|
1489
|
+
const list = make('ul','session-message-files');
|
|
1490
|
+
for (const file of files) {
|
|
1491
|
+
const item = make('li'), label = make(file.url?'a':'span',null,file.name);
|
|
1492
|
+
if (file.url) label.href = file.url;
|
|
1493
|
+
item.append(label); list.append(item);
|
|
526
1494
|
}
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
1495
|
+
node.append(list);
|
|
1496
|
+
}
|
|
1497
|
+
if (answer) {
|
|
1498
|
+
node.append(this.markdown(answer));
|
|
1499
|
+
if (answer.truncated) node.append(make('small','session-muted','内容较长,此处只显示前一部分。'));
|
|
1500
|
+
}
|
|
1501
|
+
if (!outgoing?.error) return node;
|
|
1502
|
+
const row = make('div','session-user-row'), retry = iconButton(outgoing.stale?'恢复到输入框':'重试发送',
|
|
1503
|
+
'M20 5v5h-5m-11 4v5h5m10.4-9A8 8 0 0 0 5.5 7m-.9 7a8 8 0 0 0 13.9 3','session-send-retry',
|
|
1504
|
+
() => outgoing.stale ? this.restoreUnsentMessage(outgoing) : this.sendMessage(outgoing,true));
|
|
1505
|
+
retry.dataset.tooltip = ''; retry.tooltipDetail = () => outgoing.error;
|
|
1506
|
+
retry.disabled = this.task.status === 'closed';
|
|
1507
|
+
row.append(retry,node);
|
|
1508
|
+
return row;
|
|
1509
|
+
}
|
|
1510
|
+
renderOutbox(messages,matched) {
|
|
1511
|
+
const rows = new Map();
|
|
1512
|
+
for (const [id,message] of messages) {
|
|
1513
|
+
if (matched.has(id)) continue;
|
|
1514
|
+
const signature = JSON.stringify([message.error,message.stale,this.task.status === 'closed']);
|
|
1515
|
+
const previous = this.outboxRows.get(id);
|
|
1516
|
+
if (previous?.signature === signature) rows.set(id,previous);
|
|
1517
|
+
else rows.set(id,{signature,node:this.messageNode('user',message.payload.text,message.images.flatMap(image=>image.src?[image.src]:[]),
|
|
1518
|
+
undefined,undefined,message,message.images.filter(image=>!image.src).map(image=>({name:image.file.name})))});
|
|
1519
|
+
}
|
|
1520
|
+
syncRows(this.outbox,this.outboxRows,rows); this.outboxRows = rows;
|
|
1521
|
+
}
|
|
1522
|
+
markdown(data) {
|
|
1523
|
+
const rich = make('div','markdown-body'); rich.innerHTML = data.html;
|
|
1524
|
+
for (const image of rich.querySelectorAll('img[src]')) this.prepareChatImage(image);
|
|
1525
|
+
return rich;
|
|
1526
|
+
}
|
|
1527
|
+
prepareChatImage(image) {
|
|
1528
|
+
image.dataset.chatImage = ''; image.tabIndex = 0;
|
|
1529
|
+
image.setAttribute('role','button'); image.setAttribute('aria-label',image.alt ? '查看大图 · '+image.alt : '查看大图');
|
|
1530
|
+
this.applyChatImageSize(image,this.chatImageSizes.get(this.chatImageKey(image)));
|
|
1531
|
+
}
|
|
1532
|
+
chatImageKey(image) {
|
|
1533
|
+
try {
|
|
1534
|
+
const url = new URL(image.getAttribute('src'),window.location.href);
|
|
1535
|
+
if (!['http:','https:'].includes(url.protocol) || url.origin !== window.location.origin) return;
|
|
1536
|
+
if (url.pathname === this.base+'/image') url.searchParams.delete('proof');
|
|
1537
|
+
return url.pathname+url.search;
|
|
1538
|
+
} catch { /* An image with no usable URL cannot have a cached size. */ }
|
|
1539
|
+
}
|
|
1540
|
+
applyChatImageSize(image,size) {
|
|
1541
|
+
if (!Array.isArray(size) || size.length !== 2 || !size.every(value => Number.isInteger(value) && value > 0 && value <= 1_000_000)) return;
|
|
1542
|
+
const [width,height] = size;
|
|
1543
|
+
image.setAttribute('width',String(width)); image.setAttribute('height',String(height));
|
|
1544
|
+
image.style.setProperty('--chat-image-width',width+'px');
|
|
1545
|
+
image.style.setProperty('--chat-image-ratio',String(width/height));
|
|
1546
|
+
image.dataset.chatImageSized = '';
|
|
1547
|
+
}
|
|
1548
|
+
rememberChatImageSize(image) {
|
|
1549
|
+
const key = this.chatImageKey(image), size = [image.naturalWidth,image.naturalHeight], previous = this.chatImageSizes.get(key);
|
|
1550
|
+
if (!key || !size.every(Boolean) || previous?.[0] === size[0] && previous[1] === size[1]) return;
|
|
1551
|
+
this.applyChatImageSize(image,size);
|
|
1552
|
+
this.chatImageSizes.delete(key); this.chatImageSizes.set(key,size);
|
|
1553
|
+
if (this.chatImageSizes.size > chatImageSizeLimit) this.chatImageSizes.delete(this.chatImageSizes.keys().next().value);
|
|
1554
|
+
save(this.chatImageSizeKey,[...this.chatImageSizes],'sessionStorage');
|
|
1555
|
+
}
|
|
1556
|
+
previewChatImage(event) {
|
|
1557
|
+
const image = event.target.closest?.('[data-chat-image][src]');
|
|
1558
|
+
if (!image || event.defaultPrevented) return false;
|
|
1559
|
+
event.preventDefault();
|
|
1560
|
+
this.openImage(image.currentSrc || image.src,image.alt);
|
|
1561
|
+
return true;
|
|
1562
|
+
}
|
|
1563
|
+
openImage(src,label) {
|
|
1564
|
+
if (this.imageDialog.open) return;
|
|
1565
|
+
this.imagePreview.alt = label || ''; this.imagePreview.src = src;
|
|
1566
|
+
this.imageDialog.showModal();
|
|
1567
|
+
}
|
|
1568
|
+
keepExecutionTitle(summary, change) {
|
|
1569
|
+
const body = this.body, title = summary?.getBoundingClientRect();
|
|
1570
|
+
const viewport = body?.getBoundingClientRect();
|
|
1571
|
+
if (!this.task || !body?.clientHeight || !title || title.bottom <= viewport.top || title.top >= viewport.bottom) {
|
|
1572
|
+
change(); return;
|
|
1573
|
+
}
|
|
1574
|
+
change();
|
|
1575
|
+
const shift = summary.getBoundingClientRect().top-title.top;
|
|
1576
|
+
if (shift) body.scrollTop += shift;
|
|
1577
|
+
// The resize observer also uses this position when newly expanded content grows the timeline.
|
|
1578
|
+
this.pendingPosition = this.restoredPosition = undefined;
|
|
1579
|
+
this.lastPosition = this.position(true);
|
|
1580
|
+
this.jump.hidden = this.atBottom();
|
|
1581
|
+
}
|
|
1582
|
+
bindExecutionSummary(details, summary) {
|
|
1583
|
+
summary.onclick = event => {
|
|
1584
|
+
if (event.defaultPrevented || details.open) return;
|
|
1585
|
+
event.preventDefault();
|
|
1586
|
+
this.keepExecutionTitle(summary,() => { details.open = true; });
|
|
1587
|
+
};
|
|
1588
|
+
}
|
|
1589
|
+
disclosure(className,title) {
|
|
1590
|
+
const node = make('details',className), summary = make('summary'), label = make('span','session-execution-title',title), body = make('div','session-execution-body');
|
|
1591
|
+
const badge = make('span','session-execution-badge');
|
|
1592
|
+
summary.append(label,badge); node.append(summary,body);
|
|
1593
|
+
this.bindExecutionSummary(node,summary);
|
|
1594
|
+
return {node,label,badge,body};
|
|
1595
|
+
}
|
|
1596
|
+
executionGroup(turn,item,existing,visibleTools) {
|
|
1597
|
+
let group = existing;
|
|
1598
|
+
if (!group) {
|
|
1599
|
+
group = this.disclosure('session-execution','');
|
|
1600
|
+
group.tools = make('div','session-tools'); group.rows = new Map();
|
|
1601
|
+
group.body.append(group.tools);
|
|
1602
|
+
group.node.ontoggle = () => this.refreshExecutionGroup(group);
|
|
1603
|
+
}
|
|
1604
|
+
group.node.dataset.executionGroup = item.id;
|
|
1605
|
+
setText(group.label,item.title);
|
|
1606
|
+
const rows = new Map(visibleTools ? [...group.rows].filter(([id,row]) => row.node.open && !visibleTools.has(id)) : []);
|
|
1607
|
+
for (const tool of item.tools) rows.set(tool.id,this.executionTool(turn,tool,group));
|
|
1608
|
+
setText(group.badge,rows.size ? `· ${rows.size} 项工具` : '');
|
|
1609
|
+
syncRows(group.tools,group.rows,rows); group.rows = rows;
|
|
1610
|
+
this.refreshExecutionGroup(group);
|
|
1611
|
+
return group;
|
|
1612
|
+
}
|
|
1613
|
+
refreshExecutionGroup(group) {
|
|
1614
|
+
if (!group.node.open) return;
|
|
1615
|
+
for (const row of group.rows.values()) if (row.node.open) void this.loadExecution(row.body,row.request);
|
|
1616
|
+
}
|
|
1617
|
+
executionTool(turn,tool,group) {
|
|
1618
|
+
let row = group.rows.get(tool.id);
|
|
1619
|
+
if (!row) {
|
|
1620
|
+
row = this.disclosure('session-tool',''); row.node.dataset.tool = tool.id;
|
|
1621
|
+
row.node.ontoggle = () => { if (group.node.open && row.node.open) void this.loadExecution(row.body,row.request); };
|
|
1622
|
+
}
|
|
1623
|
+
const kind = tool.kind || (tool.command ? 'command' : 'tool');
|
|
1624
|
+
if (row.node.dataset.toolKind !== kind) {
|
|
1625
|
+
row.node.dataset.toolKind = kind;
|
|
1626
|
+
row.icon?.remove(); row.icon = this.app.toolIcon(kind); row.label.before(row.icon);
|
|
1627
|
+
}
|
|
1628
|
+
row.label.textContent = tool.title?.replace(/\s+/gu,' ').trim() || '工具';
|
|
1629
|
+
row.label.classList.toggle('session-tool-command-title',tool.command === true);
|
|
1630
|
+
row.badge.textContent = tool.status === 'completed' ? '' : status(tool.status); row.badge.dataset.status = tool.status;
|
|
1631
|
+
row.request = {route:'/tool',params:{turn:turn.id,tool:tool.id},tool,revision:`${turn.id}:${tool.status}:${tool.completedAt}:${tool.status === 'running' ? turn.status : ''}`};
|
|
1632
|
+
return row;
|
|
1633
|
+
}
|
|
1634
|
+
executionOverview(turn,existing) {
|
|
1635
|
+
const row = existing || this.disclosure('session-execution','文件变更');
|
|
1636
|
+
setText(row.badge,turn.fileChangeCount ? ` · ${turn.fileChangeCount}` : '');
|
|
1637
|
+
row.request = {route:'/detail',params:{turn:turn.id},revision:turn.detailRevision || turn.status};
|
|
1638
|
+
row.node.ontoggle = () => { if (row.node.open) void this.loadExecution(row.body,row.request); };
|
|
1639
|
+
if (row.node.open) void this.loadExecution(row.body,row.request);
|
|
1640
|
+
return row;
|
|
1641
|
+
}
|
|
1642
|
+
async loadExecution(body, request) {
|
|
1643
|
+
if (!this.task || !request || body.loading === request.revision || body.loaded === request.revision) return;
|
|
1644
|
+
const generation = this.generation, task = this.task.id;
|
|
1645
|
+
body.loading = request.revision;
|
|
1646
|
+
const update = change => this.keepExecutionTitle(body.previousElementSibling,change);
|
|
1647
|
+
if (!body.firstChild) update(() => body.append(make('p','session-muted','正在读取…')));
|
|
1648
|
+
const current = () => body.isConnected && generation === this.generation && body.loading === request.revision;
|
|
1649
|
+
try {
|
|
1650
|
+
const data = await this.fetch(request.route,{params:{task,...request.params}});
|
|
1651
|
+
if (!current()) return;
|
|
1652
|
+
const nodes = [];
|
|
1653
|
+
if (request.route === '/tool') {
|
|
1654
|
+
update(() => this.renderToolDetails(body,request,data,task,generation));
|
|
1655
|
+
body.loaded = request.revision;
|
|
1656
|
+
return;
|
|
1657
|
+
}
|
|
1658
|
+
const changes = this.renderToolFiles(data.changes,data.changesTruncated);
|
|
1659
|
+
if (changes) nodes.push(changes);
|
|
1660
|
+
if (data.truncated) nodes.push(make('p','session-muted','仅显示部分内容,完整记录请查看 Turn Preview。'));
|
|
1661
|
+
update(() => body.replaceChildren(...nodes)); body.loaded = request.revision;
|
|
530
1662
|
} catch (error) {
|
|
531
|
-
if (
|
|
532
|
-
} finally {
|
|
1663
|
+
if (current()) update(() => body.replaceChildren(make('span','session-error',error.message),button('重试',() => this.loadExecution(body,request),'session-quiet')));
|
|
1664
|
+
} finally {
|
|
1665
|
+
if (body.loading === request.revision) body.loading = undefined;
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
renderToolFiles(files, truncated) {
|
|
1669
|
+
if (!files?.length) return;
|
|
1670
|
+
const section = make('div','session-tool-files'), list = make('ul');
|
|
1671
|
+
list.setAttribute('aria-label','此工具修改的文件'); section.append(list);
|
|
1672
|
+
for (const file of files) {
|
|
1673
|
+
const item = make('li'), header = make('div','session-tool-file');
|
|
1674
|
+
const name = make(file.entry ? 'a' : 'span','session-tool-file-name',file.name);
|
|
1675
|
+
if (file.entry) {
|
|
1676
|
+
name.setAttribute('href',this.app.chatDiffUrl(file));
|
|
1677
|
+
name.setAttribute('aria-label','查看 '+file.name+' 的 Diff');
|
|
1678
|
+
name.onclick = event => {
|
|
1679
|
+
if (!plainLinkClick(event)) return;
|
|
1680
|
+
event.preventDefault();
|
|
1681
|
+
this.app.openChatFile(file.entry,'diff',undefined,file.source,file.original);
|
|
1682
|
+
};
|
|
1683
|
+
}
|
|
1684
|
+
header.append(name);
|
|
1685
|
+
const counts = make('span','session-tool-file-counts');
|
|
1686
|
+
if (Number.isSafeInteger(file.additions) && file.additions > 0) counts.append(make('span','session-tool-file-additions','+'+file.additions));
|
|
1687
|
+
if (Number.isSafeInteger(file.deletions) && file.deletions > 0) counts.append(make('span','session-tool-file-deletions','−'+file.deletions));
|
|
1688
|
+
if (file.additions === 0 && file.deletions === 0) counts.append(make('span',null,'0'));
|
|
1689
|
+
if (counts.childElementCount) header.append(counts);
|
|
1690
|
+
item.append(header);
|
|
1691
|
+
if (file.patch) {
|
|
1692
|
+
const details = make('details','session-tool-file-patch'), summary = make('summary');
|
|
1693
|
+
summary.append(make('span',null,'本次补丁'));
|
|
1694
|
+
this.bindExecutionSummary(details,summary);
|
|
1695
|
+
const patch = make('pre'); patch.tabIndex = 0; patch.setAttribute('aria-label','本次修改的补丁');
|
|
1696
|
+
const code = make('code');
|
|
1697
|
+
if (file.patchHtml) code.innerHTML = file.patchHtml;
|
|
1698
|
+
else code.textContent = file.patch;
|
|
1699
|
+
patch.append(code);
|
|
1700
|
+
details.append(summary,patch);
|
|
1701
|
+
if (file.patchTruncated) details.append(make('small','session-muted','已保存补丁的开头。'));
|
|
1702
|
+
item.append(details);
|
|
1703
|
+
}
|
|
1704
|
+
list.append(item);
|
|
1705
|
+
}
|
|
1706
|
+
if (truncated) section.append(make('small','session-muted','仅显示前 '+files.length+' 个文件。'));
|
|
1707
|
+
return section;
|
|
1708
|
+
}
|
|
1709
|
+
renderToolDetails(body,request,first,task,generation) {
|
|
1710
|
+
const texts = make('div','session-tool-texts'), previous = body.querySelector('.session-tool-texts');
|
|
1711
|
+
texts.tabIndex = 0; texts.setAttribute('role','region'); texts.setAttribute('aria-label','工具命令与输出');
|
|
1712
|
+
const fields = [['command','命令','$'],['output',first.outputIsError?'执行错误':'结果'],['error','错误']];
|
|
1713
|
+
const blocks = new Map();
|
|
1714
|
+
const more = button('加载更多输出',() => void loadMore(true),'session-more');
|
|
1715
|
+
const issue = make('p','session-muted'); issue.setAttribute('role','status');
|
|
1716
|
+
let offset, revision = first.revision, failure;
|
|
1717
|
+
const current = () => generation === this.generation && more.isConnected && body.loaded === request.revision;
|
|
1718
|
+
const loadMore = async explicit => {
|
|
1719
|
+
if (!current() || offset === undefined || more.disabled || failure && !explicit) return;
|
|
1720
|
+
if (failure === 409) { body.loaded = undefined; void this.loadExecution(body,request); return; }
|
|
1721
|
+
more.disabled = true; more.textContent = '正在读取…';
|
|
1722
|
+
try {
|
|
1723
|
+
const data = await this.fetch('/tool',{params:{task,...request.params,offset,revision}});
|
|
1724
|
+
if (current()) append(data);
|
|
1725
|
+
} catch (error) {
|
|
1726
|
+
if (current()) {
|
|
1727
|
+
failure = error.status ?? true; more.textContent = failure === 409?'重新读取':'重试读取';
|
|
1728
|
+
issue.textContent = error.message; issue.hidden = false;
|
|
1729
|
+
}
|
|
1730
|
+
} finally { more.disabled = false; }
|
|
1731
|
+
};
|
|
1732
|
+
const append = data => {
|
|
1733
|
+
for (const [key,label,marker] of fields) {
|
|
1734
|
+
const page = key === 'command' ? data.displayCommand ?? data.command : data[key];
|
|
1735
|
+
if (!page) continue;
|
|
1736
|
+
if (!blocks.has(key)) {
|
|
1737
|
+
const section = make('div','session-tool-log session-tool-'+key+'-section'), pre = make('pre','session-tool-'+key);
|
|
1738
|
+
pre.setAttribute('aria-label',label);
|
|
1739
|
+
if (key === 'error' || key === 'output' && first.outputIsError) {
|
|
1740
|
+
section.classList.add('session-tool-error-section');
|
|
1741
|
+
section.append(make('span','session-tool-error-label',label));
|
|
1742
|
+
}
|
|
1743
|
+
if (marker) {
|
|
1744
|
+
const mark = make('span','session-tool-marker',marker); mark.setAttribute('aria-hidden','true'); section.append(mark);
|
|
1745
|
+
}
|
|
1746
|
+
section.append(pre); blocks.set(key,{pre,section});
|
|
1747
|
+
}
|
|
1748
|
+
const pre = blocks.get(key).pre, last = pre.lastChild;
|
|
1749
|
+
const joinsPair = last && /[\uD800-\uDBFF]$/u.test(last.data) && /^[\uDC00-\uDFFF]/u.test(page);
|
|
1750
|
+
if (joinsPair) last.appendData(page[0]);
|
|
1751
|
+
pre.append(joinsPair ? page.slice(1) : page);
|
|
1752
|
+
}
|
|
1753
|
+
let index = 0;
|
|
1754
|
+
for (const [key] of fields) {
|
|
1755
|
+
const block = blocks.get(key);
|
|
1756
|
+
if (block && texts.children[index++] !== block.section) texts.insertBefore(block.section,texts.children[index-1] || null);
|
|
1757
|
+
}
|
|
1758
|
+
offset = data.next; revision = data.revision; failure = undefined;
|
|
1759
|
+
more.hidden = offset === undefined; more.textContent = '加载更多输出'; issue.replaceChildren();
|
|
1760
|
+
if (data.partial) issue.textContent = data.reason ? `未能读取原始工具日志:${data.reason}` : '未找到完整的原始工具日志,上方是已保存的摘要。';
|
|
1761
|
+
issue.hidden = !data.partial;
|
|
1762
|
+
};
|
|
1763
|
+
append(first);
|
|
1764
|
+
const files = this.renderToolFiles(first.files,first.filesTruncated);
|
|
1765
|
+
const empty = !files && !blocks.size && !first.next ? make('p','session-muted','该工具暂无输出。') : undefined;
|
|
1766
|
+
const timing = timeTool(request.tool);
|
|
1767
|
+
const footer = timing ? make('div','session-tool-footer',timing) : undefined;
|
|
1768
|
+
const left = previous?.scrollLeft || 0, top = previous?.scrollTop || 0;
|
|
1769
|
+
const hadFocus = document.activeElement === previous;
|
|
1770
|
+
body.replaceChildren(...(files?[files]:[]),texts,...(empty?[empty]:[]),more,issue,...(footer?[footer]:[]));
|
|
1771
|
+
texts.scrollLeft = left; texts.scrollTop = top;
|
|
1772
|
+
if (hadFocus && blocks.size) texts.focus({preventScroll:true});
|
|
1773
|
+
let lastLeft = texts.scrollLeft, lastTop = texts.scrollTop;
|
|
1774
|
+
texts.addEventListener('scroll',() => {
|
|
1775
|
+
const {scrollLeft,scrollTop,clientWidth,clientHeight,scrollWidth,scrollHeight} = texts;
|
|
1776
|
+
const vertical = scrollHeight-clientHeight;
|
|
1777
|
+
const nearEnd = vertical > 0 ? scrollTop > lastTop && vertical-scrollTop <= 64
|
|
1778
|
+
: scrollLeft > lastLeft && scrollWidth-clientWidth-scrollLeft <= 64;
|
|
1779
|
+
lastLeft = scrollLeft; lastTop = scrollTop;
|
|
1780
|
+
if (clientWidth > 0 && clientHeight > 0 && nearEnd) void loadMore(false);
|
|
1781
|
+
},{passive:true});
|
|
533
1782
|
}
|
|
534
1783
|
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.
|
|
1784
|
+
if (!this.task || this.selecting || this.refreshing || !this.more || !this.turns.length || this.older.disabled) return;
|
|
1785
|
+
const generation = this.generation, task = this.task.id, before = this.turns[0].id, older = this.older;
|
|
1786
|
+
const current = () => !this.disposed && generation === this.generation && !this.refreshing && this.turns[0]?.id === before;
|
|
1787
|
+
older.disabled = true; older.textContent = '正在加载…';
|
|
538
1788
|
try {
|
|
539
1789
|
const data = await this.fetch('/task',{params:{task,before}});
|
|
540
|
-
if (
|
|
1790
|
+
if (!current()) return;
|
|
541
1791
|
this.pendingPosition = this.position(); this.turns = [...new Map([...data.turns,...this.turns].map(turn => [turn.id,turn])).values()]; this.more = data.more;
|
|
542
1792
|
this.renderConversation();
|
|
543
|
-
} catch (error) { if (
|
|
544
|
-
finally {
|
|
1793
|
+
} catch (error) { if (current()) this.setChatError('历史读取失败:'+error.message,false,() => error.status === 409 ? this.refreshConversation(false) : this.loadOlder()); }
|
|
1794
|
+
finally { older.disabled = false; older.textContent = '加载更早的对话'; }
|
|
545
1795
|
}
|
|
546
1796
|
restoreHistoryPosition(position) {
|
|
547
|
-
this.
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
1797
|
+
if (position.turn && !this.turnNodes.has(position.turn)) void this.refreshConversation(true,{anchor:position.turn,position});
|
|
1798
|
+
else { this.pendingPosition = position; this.restorePosition(); }
|
|
1799
|
+
}
|
|
1800
|
+
jumpToBottom() {
|
|
1801
|
+
this.pendingPosition = {bottom:true}; this.restorePosition();
|
|
1802
|
+
this.jump.hidden = true;
|
|
1803
|
+
this.app.queuePersist();
|
|
1804
|
+
}
|
|
1805
|
+
atBottom() { return this.body.scrollHeight-this.body.scrollTop-this.body.clientHeight <= 1; }
|
|
555
1806
|
position(measure = false) {
|
|
556
1807
|
if (this.pendingPosition && !measure) return this.pendingPosition;
|
|
557
1808
|
if (!this.task || !this.body?.clientHeight) return this.lastPosition;
|
|
558
|
-
if (!this.
|
|
1809
|
+
if (!measure && this.restoredPosition?.top === this.body.scrollTop) return this.restoredPosition.anchor;
|
|
1810
|
+
if (this.atBottom()) return {bottom:true};
|
|
559
1811
|
const top = this.body.getBoundingClientRect().top;
|
|
560
1812
|
for (const node of this.timeline.children) {
|
|
561
1813
|
const rect = node.getBoundingClientRect();
|
|
562
|
-
if (node.dataset.turn && rect.bottom > top + 1)
|
|
1814
|
+
if (node.dataset.turn && rect.bottom > top + 1) {
|
|
1815
|
+
const turn = node.dataset.turn, target = this.readingTarget(this.turnNodes.get(turn),top);
|
|
1816
|
+
return {turn,offset:Math.round(top-rect.top),...(target ? {target} : {})};
|
|
1817
|
+
}
|
|
563
1818
|
}
|
|
564
1819
|
return {bottom:true};
|
|
565
1820
|
}
|
|
1821
|
+
readingTarget(turn,top) {
|
|
1822
|
+
for (const [row,{node}] of turn?.rows || []) {
|
|
1823
|
+
const rect = node.getBoundingClientRect?.();
|
|
1824
|
+
if (!rect || rect.top > top+1 || rect.bottom <= top+1) continue;
|
|
1825
|
+
const parts = [...node.querySelectorAll(chatAnchorParts)];
|
|
1826
|
+
for (const [part,element] of parts.entries()) {
|
|
1827
|
+
const bounds = element.getBoundingClientRect?.();
|
|
1828
|
+
if (bounds && bounds.top <= top+1 && bounds.bottom > top+1) return {row,part,offset:Math.round(top-bounds.top)};
|
|
1829
|
+
}
|
|
1830
|
+
return {row,offset:Math.round(top-rect.top)};
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
566
1833
|
restorePosition() {
|
|
567
|
-
|
|
1834
|
+
this.chatBodyHeight = this.body?.clientHeight;
|
|
1835
|
+
if (!this.pendingPosition || !this.chatBodyHeight) return;
|
|
568
1836
|
const position = this.pendingPosition; this.pendingPosition = undefined;
|
|
569
|
-
|
|
1837
|
+
const turn = position.turn && this.turnNodes.get(position.turn);
|
|
1838
|
+
const target = position.target;
|
|
1839
|
+
const row = target && turn?.rows.get(target.row)?.node;
|
|
1840
|
+
const part = target?.part === undefined ? row : row?.querySelectorAll(chatAnchorParts)[target.part];
|
|
1841
|
+
const node = part || turn?.node;
|
|
1842
|
+
if (!node) this.body.scrollTop = this.body.scrollHeight;
|
|
570
1843
|
else {
|
|
571
|
-
const
|
|
572
|
-
|
|
573
|
-
|
|
1844
|
+
const offset = part ? target.offset : position.offset;
|
|
1845
|
+
const top = this.body.scrollTop + node.getBoundingClientRect().top - this.body.getBoundingClientRect().top + offset;
|
|
1846
|
+
this.body.scrollTop = top;
|
|
574
1847
|
}
|
|
575
|
-
|
|
1848
|
+
// A short history page or unloaded image can temporarily clamp scrollTop.
|
|
1849
|
+
this.lastPosition = node ? position : {bottom:true};
|
|
1850
|
+
this.restoredPosition = {top:this.body.scrollTop,anchor:this.lastPosition};
|
|
1851
|
+
this.jump.hidden = this.atBottom();
|
|
1852
|
+
}
|
|
1853
|
+
images(id) { return this.imageDrafts.get(id) || noImages; }
|
|
1854
|
+
restoreDraftFiles(task) {
|
|
1855
|
+
const loading = this.fileLoads.get(task);
|
|
1856
|
+
if (loading) return loading;
|
|
1857
|
+
const unpack = attachments => (attachments || []).map(({id,file,preview,annotation}) => ({
|
|
1858
|
+
id,file,annotation,...(preview ? {src:draftAttachment(file,annotation).src} : {}),
|
|
1859
|
+
}));
|
|
1860
|
+
this.loadingDraftFiles.add(task);
|
|
1861
|
+
const load = this.draftFiles.read(task).then(record => {
|
|
1862
|
+
if (!record || this.disposed || this.fileLoads.get(task) !== load) return;
|
|
1863
|
+
this.fileRecords.add(task);
|
|
1864
|
+
if (record.draft?.length && !this.imageDrafts.has(task)) this.imageDrafts.set(task,unpack(record.draft));
|
|
1865
|
+
const messages = this.messages(task);
|
|
1866
|
+
for (const [payload,error,attachments] of record.outbox || []) {
|
|
1867
|
+
if (!messages.has(payload.request)) messages.set(payload.request,{payload,error,images:unpack(attachments),restored:true});
|
|
1868
|
+
}
|
|
1869
|
+
if (messages.size) this.outboxes.set(task,messages);
|
|
1870
|
+
}).catch(() => {}).finally(() => {
|
|
1871
|
+
if (this.fileLoads.get(task) !== load) return;
|
|
1872
|
+
this.loadingDraftFiles.delete(task);
|
|
1873
|
+
if (!this.disposed && (this.newDraft?.id ?? this.task?.id) === task && this.composer?.isConnected) this.updateComposer();
|
|
1874
|
+
});
|
|
1875
|
+
this.fileLoads.set(task,load);
|
|
1876
|
+
return load;
|
|
1877
|
+
}
|
|
1878
|
+
persistDraftFiles(...tasks) {
|
|
1879
|
+
const pack = items => items.map(({id,file,src,annotation}) => ({id,file,preview:Boolean(src),annotation}));
|
|
1880
|
+
const records = [];
|
|
1881
|
+
for (const task of new Set(tasks)) {
|
|
1882
|
+
const draft = pack(this.images(task));
|
|
1883
|
+
const outbox = [...this.messages(task).values()].filter(message => !message.accepted && message.images.length)
|
|
1884
|
+
.map(message => [message.payload,message.error,pack(message.images)]);
|
|
1885
|
+
if (draft.length || outbox.length) {
|
|
1886
|
+
this.fileRecords.add(task); records.push([task,{draft,outbox}]);
|
|
1887
|
+
} else if (this.fileRecords.delete(task)) records.push([task,null]);
|
|
1888
|
+
}
|
|
1889
|
+
if (!records.length) return;
|
|
1890
|
+
return this.draftFiles.write(records).then(() => {
|
|
1891
|
+
if (!this.disposed && this.draftStorageNote) this.updateDraftStorageNotice();
|
|
1892
|
+
});
|
|
1893
|
+
}
|
|
1894
|
+
updateDraftStorageNotice() {
|
|
1895
|
+
const task = this.newDraft?.id ?? this.task?.id;
|
|
1896
|
+
this.draftStorageNote.hidden = !this.draftFiles.failed.has(task);
|
|
1897
|
+
}
|
|
1898
|
+
resetImageDrafts() {
|
|
1899
|
+
for (const images of this.imageDrafts.values()) for (const image of images) revokeAttachment(image);
|
|
1900
|
+
this.imageDrafts.clear();
|
|
1901
|
+
}
|
|
1902
|
+
clearImageInteractions() {
|
|
1903
|
+
if (this.imageDialog?.open) this.imageDialog.close();
|
|
1904
|
+
this.chat.ondragover = this.chat.ondragleave = this.chat.ondragend = this.chat.ondrop = null;
|
|
1905
|
+
}
|
|
1906
|
+
noticeImages(text) {
|
|
1907
|
+
this.imageNotice.textContent = text; this.imageNotice.hidden = !text;
|
|
1908
|
+
}
|
|
1909
|
+
keepComposerPosition(position) {
|
|
1910
|
+
if (position && this.body.clientHeight !== this.chatBodyHeight) {
|
|
1911
|
+
this.pendingPosition = position; this.restorePosition();
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
addAttachments(files,annotation) {
|
|
1915
|
+
const task = this.newDraft?.id ?? this.task?.id;
|
|
1916
|
+
if (!task || this.input.disabled || !files?.length) return;
|
|
1917
|
+
const position = this.position(true), images = this.images(task), added = [...images];
|
|
1918
|
+
let total = images.reduce((size,image) => size+image.file.size,0);
|
|
1919
|
+
const issues = new Set();
|
|
1920
|
+
for (const file of files) {
|
|
1921
|
+
if (added.length >= imageCount || file.size > imageLimit || total+file.size > draftLimit) {
|
|
1922
|
+
issues.add('至多 4 个附件,单个不超过 5 MiB,合计不超过 12 MiB。'); continue;
|
|
1923
|
+
}
|
|
1924
|
+
total += file.size;
|
|
1925
|
+
added.push(draftAttachment(file,annotation));
|
|
1926
|
+
}
|
|
1927
|
+
if (added.length !== images.length) this.replaceImages(task,added);
|
|
1928
|
+
this.noticeImages([...issues].join(' ')); this.updateComposer(); this.keepComposerPosition(position);
|
|
1929
|
+
if (added.length > images.length) this.attachments.scrollLeft = this.attachments.scrollWidth;
|
|
1930
|
+
return added.length > images.length;
|
|
1931
|
+
}
|
|
1932
|
+
removeImage(task,image) {
|
|
1933
|
+
const images = this.images(task), index = images.indexOf(image);
|
|
1934
|
+
if (index < 0) return;
|
|
1935
|
+
this.replaceImages(task,images.filter(entry=>entry!==image));
|
|
1936
|
+
if ((this.newDraft?.id ?? this.task?.id) === task) {
|
|
1937
|
+
const position = this.position(true);
|
|
1938
|
+
this.noticeImages(''); this.updateComposer(); this.keepComposerPosition(position);
|
|
1939
|
+
const next = this.attachments.children[Math.min(index,images.length-2)]?.querySelector('.session-image-remove');
|
|
1940
|
+
(next || this.attach).focus({preventScroll:true});
|
|
1941
|
+
}
|
|
1942
|
+
}
|
|
1943
|
+
replaceImages(task,remaining) {
|
|
1944
|
+
const keep = new Set(remaining);
|
|
1945
|
+
for (const image of this.images(task)) if (!keep.has(image)) revokeAttachment(image);
|
|
1946
|
+
if (remaining.length) this.imageDrafts.set(task,remaining);
|
|
1947
|
+
else this.imageDrafts.delete(task);
|
|
1948
|
+
void this.persistDraftFiles(task);
|
|
1949
|
+
}
|
|
1950
|
+
renderPromptQueue() {
|
|
1951
|
+
const task = this.task;
|
|
1952
|
+
const prompts = !this.newDraft && task?.status !== 'closed' ? task?.queuedPrompts ?? [] : [];
|
|
1953
|
+
if (this.queueEdit && (this.queueEdit.task !== task?.id || this.newDraft || task.status === 'closed')) this.queueEdit = undefined;
|
|
1954
|
+
const edit = this.queueEdit, blocked = this.restoringQueue === task?.id || this.selecting;
|
|
1955
|
+
const signature = JSON.stringify([task?.id,prompts,blocked,edit?.prompt,edit?.saving]);
|
|
1956
|
+
if (this.queueList.signature === signature) return;
|
|
1957
|
+
this.queueList.signature = signature; this.queueList.hidden = !prompts.length && !edit;
|
|
1958
|
+
this.queueList.toggleAttribute('data-editing',Boolean(edit));
|
|
1959
|
+
const rows = new Map();
|
|
1960
|
+
for (const [index,prompt] of prompts.entries()) {
|
|
1961
|
+
if (edit?.prompt === prompt.id) {
|
|
1962
|
+
setText(edit.number,(index+1)+'.'); rows.set(prompt.id,edit); continue;
|
|
1963
|
+
}
|
|
1964
|
+
const existing = this.queueRows.get(prompt.id);
|
|
1965
|
+
const row = existing?.label ? existing : this.queuedPromptRow(prompt.id);
|
|
1966
|
+
setText(row.number,(index+1)+'.'); setText(row.label,prompt.text || '附件消息');
|
|
1967
|
+
labelButton(row.modify,`修改第 ${index+1} 条排队消息:${row.label.textContent}${prompt.hasAttachments ? ',含附件' : ''}`);
|
|
1968
|
+
row.attachment.hidden = !prompt.hasAttachments;
|
|
1969
|
+
row.modify.disabled = blocked || Boolean(edit); row.cancel.disabled = blocked;
|
|
1970
|
+
rows.set(prompt.id,row);
|
|
1971
|
+
}
|
|
1972
|
+
if (edit && !rows.has(edit.prompt)) {
|
|
1973
|
+
edit.left = true; edit.number.hidden = true; edit.submit.disabled = true;
|
|
1974
|
+
setText(edit.note,'这条消息已离开队列,可复制这里的内容。');
|
|
1975
|
+
rows.set(edit.prompt,edit);
|
|
1976
|
+
}
|
|
1977
|
+
syncRows(this.queueList,this.queueRows,rows); this.queueRows = rows;
|
|
1978
|
+
}
|
|
1979
|
+
queuedPromptRow(id) {
|
|
1980
|
+
const node = make('li'), number = make('span','session-queue-number'); number.setAttribute('aria-hidden','true');
|
|
1981
|
+
const modify = button('',() => void this.editQueuedPrompt(id),'session-queue-edit');
|
|
1982
|
+
const label = make('span','session-queued-prompt'); label.dataset.tooltipOverflow = '';
|
|
1983
|
+
const attachment = make('span','session-queue-attachment','附件'); modify.append(label,attachment);
|
|
1984
|
+
const cancel = iconButton('取消排队并恢复到输入框','M6 6l12 12M18 6 6 18','session-cancel-queued',() => void this.restoreQueuedPrompt(id));
|
|
1985
|
+
cancel.dataset.tooltip = ''; node.append(number,modify,cancel);
|
|
1986
|
+
return {node,number,modify,label,attachment,cancel};
|
|
1987
|
+
}
|
|
1988
|
+
async editQueuedPrompt(prompt) {
|
|
1989
|
+
const task = this.task?.id, grant = this.csrf;
|
|
1990
|
+
if (!task || !grant || this.newDraft || this.selecting || this.restoringQueue || this.queueEdit) return;
|
|
1991
|
+
const node = make('li','session-queue-editing'), number = make('span','session-queue-number'); number.setAttribute('aria-hidden','true');
|
|
1992
|
+
const form = make('form','session-queue-edit-form'), input = make('textarea');
|
|
1993
|
+
input.setAttribute('aria-label','修改排队消息'); input.rows = 2; input.maxLength = 24_000; input.disabled = true;
|
|
1994
|
+
const actions = make('div','session-queue-edit-actions'), note = make('small','session-queue-edit-note','正在读取…'); note.setAttribute('role','status');
|
|
1995
|
+
const close = button('取消',() => this.closeQueueEdit(edit),'session-quiet');
|
|
1996
|
+
const submit = make('button','session-queue-save','保存'); submit.type = 'submit'; submit.disabled = true;
|
|
1997
|
+
const edit = this.queueEdit = {node,number,task,prompt,grant,input,note,submit,close};
|
|
1998
|
+
form.onsubmit = event => { event.preventDefault(); void this.saveQueueEdit(edit); };
|
|
1999
|
+
input.onkeydown = event => {
|
|
2000
|
+
if (event.isComposing || event.keyCode === 229) return;
|
|
2001
|
+
if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); this.closeQueueEdit(edit); }
|
|
2002
|
+
if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) { event.preventDefault(); void this.saveQueueEdit(edit); }
|
|
2003
|
+
};
|
|
2004
|
+
actions.append(note,close,submit); form.append(input,actions); node.append(number,form); this.renderPromptQueue();
|
|
2005
|
+
try {
|
|
2006
|
+
const data = await this.fetch('/queue/edit',{params:{task,prompt}});
|
|
2007
|
+
if (this.queueEdit !== edit || this.disposed || this.csrf !== grant) return;
|
|
2008
|
+
edit.revision = data.revision; edit.original = input.value = data.text;
|
|
2009
|
+
input.disabled = false; submit.disabled = Boolean(edit.left);
|
|
2010
|
+
if (!edit.left) setText(note,'');
|
|
2011
|
+
input.focus({preventScroll:true});
|
|
2012
|
+
} catch (error) { if (this.queueEdit === edit && !this.disposed) setText(note,error.message); }
|
|
2013
|
+
}
|
|
2014
|
+
closeQueueEdit(edit) {
|
|
2015
|
+
if (this.queueEdit !== edit || edit.saving) return;
|
|
2016
|
+
this.queueEdit = undefined; this.renderPromptQueue();
|
|
2017
|
+
(this.queueRows.get(edit.prompt)?.modify || this.input).focus({preventScroll:true});
|
|
2018
|
+
}
|
|
2019
|
+
async saveQueueEdit(edit) {
|
|
2020
|
+
if (this.queueEdit !== edit || edit.submit.disabled || edit.saving || this.selecting || this.csrf !== edit.grant) return;
|
|
2021
|
+
const {task,prompt,revision,input,submit,note,close} = edit;
|
|
2022
|
+
const before = this.task.queuedPrompts?.find(row => row.id === prompt);
|
|
2023
|
+
if (!before) return;
|
|
2024
|
+
edit.saving = input.readOnly = close.disabled = submit.disabled = true; setText(note,'正在保存…');
|
|
2025
|
+
try {
|
|
2026
|
+
const result = await this.fetch('/queue/edit',{body:{task,prompt,revision,text:input.value}});
|
|
2027
|
+
if (this.queueEdit !== edit || this.disposed || this.csrf !== edit.grant) return;
|
|
2028
|
+
this.task.queuedPrompts = this.task.queuedPrompts?.map(row => row === before ? result : row);
|
|
2029
|
+
edit.saving = false; this.closeQueueEdit(edit);
|
|
2030
|
+
} catch (error) { if (this.queueEdit === edit && !this.disposed) setText(note,error.message); }
|
|
2031
|
+
finally { edit.saving = input.readOnly = close.disabled = false; submit.disabled = Boolean(edit.left); }
|
|
2032
|
+
}
|
|
2033
|
+
async restoreQueuedPrompt(prompt) {
|
|
2034
|
+
const task = this.task?.id, grant = this.csrf, position = this.position(true);
|
|
2035
|
+
if (!task || !grant || this.newDraft || this.input.disabled || this.restoringQueue) return;
|
|
2036
|
+
this.restoringQueue = task; this.updateComposer(); this.setChatError('');
|
|
2037
|
+
const visible = () => this.task?.id === task && !this.newDraft && !this.disposed;
|
|
2038
|
+
const controller = new AbortController(), timeout = setTimeout(() => controller.abort(),30_000);
|
|
2039
|
+
try {
|
|
2040
|
+
const queued = await this.fetch('/queue',{params:{task,prompt},signal:controller.signal});
|
|
2041
|
+
const sources = [...(queued.images || []).map((url,index) => ({url,name:`图片 ${index+1}`})),...(queued.files || [])];
|
|
2042
|
+
const previous = this.images(task), text = [queued.text,this.draft(task)].filter(Boolean).join('\n\n');
|
|
2043
|
+
if (text.length > 24_000 || previous.length+sources.length > imageCount) throw new Error('请先处理已有草稿,合并后的消息超出输入框限制。');
|
|
2044
|
+
const files = await Promise.all(sources.map(async ({url,name}) => {
|
|
2045
|
+
if (!url) throw new Error('排队消息中的附件已不可用。');
|
|
2046
|
+
const response = await fetch(url,{cache:'no-store',credentials:'same-origin',signal:controller.signal});
|
|
2047
|
+
if (!response.ok) throw new Error('无法恢复排队消息中的附件。');
|
|
2048
|
+
const blob = await response.blob();
|
|
2049
|
+
return new File([blob],name,{type:blob.type});
|
|
2050
|
+
}));
|
|
2051
|
+
if (files.some(file => file.size > imageLimit) || [...files,...previous.map(image=>image.file)].reduce((total,file)=>total+file.size,0) > draftLimit) {
|
|
2052
|
+
throw new Error('请先处理已有附件,合并后的消息超出附件大小限制。');
|
|
2053
|
+
}
|
|
2054
|
+
if (this.csrf !== grant || this.disposed) return;
|
|
2055
|
+
const body = {task,prompt,request:uuid(),revision:queued.revision};
|
|
2056
|
+
const cancel = () => this.fetch('/queue',{body});
|
|
2057
|
+
const result = await cancel().catch(error => { if (error.status || this.csrf !== grant) throw error; return cancel(); });
|
|
2058
|
+
if (!result.cancelled) throw new Error('这条消息已离开队列。');
|
|
2059
|
+
this.setDraft(task,text); this.replaceImages(task,[...previous,...files.map(file => draftAttachment(file))]);
|
|
2060
|
+
if (visible()) {
|
|
2061
|
+
this.task.queuedPrompts = this.task.queuedPrompts?.filter(row => row.id !== prompt);
|
|
2062
|
+
this.input.value = text;
|
|
2063
|
+
}
|
|
2064
|
+
} catch (error) { if (visible()) this.setChatError(error.message); }
|
|
2065
|
+
finally {
|
|
2066
|
+
clearTimeout(timeout); this.restoringQueue = undefined;
|
|
2067
|
+
if (visible()) { this.updateComposer(); this.keepComposerPosition(position); this.input.focus(); }
|
|
2068
|
+
}
|
|
2069
|
+
}
|
|
2070
|
+
renderDraftImages(task) {
|
|
2071
|
+
const all = this.images(task);
|
|
2072
|
+
if (this.renderedDraftImages === all && this.renderedDraftTask === task && this.attachments.childElementCount === all.length) return;
|
|
2073
|
+
this.renderedDraftImages = all; this.renderedDraftTask = task;
|
|
2074
|
+
this.app.annotations?.updateDrafts(task,all);
|
|
2075
|
+
const existing = new Map([...this.attachments.children].map(node => [node.dataset.image,node]));
|
|
2076
|
+
const nodes = all.map((image,index) => {
|
|
2077
|
+
const name = image.file.name || `附件 ${index+1}`;
|
|
2078
|
+
if (existing.has(image.id)) return existing.get(image.id);
|
|
2079
|
+
const tile = make('div','session-image-tile'); tile.dataset.image = image.id;
|
|
2080
|
+
const remove = iconButton('移除 '+name,'M6 6l12 12M18 6 6 18','session-image-remove',() => this.removeImage(task,image));
|
|
2081
|
+
if (!image.src) {
|
|
2082
|
+
tile.classList.add('session-file-tile');
|
|
2083
|
+
const annotation = image.annotation;
|
|
2084
|
+
if (annotation) {
|
|
2085
|
+
const title = annotationTitle(annotation), label = make('span','session-file-label session-annotation-label',title);
|
|
2086
|
+
const excerpt = annotation.quote.trim().replace(/\s+/gu,' ');
|
|
2087
|
+
label.tabIndex = 0; label.dataset.tooltip = title; label.dataset.annotationTooltip = '';
|
|
2088
|
+
label.tooltipDetail = () => `原文 · ${excerpt.length > 100 ? excerpt.slice(0,100)+'…' : excerpt}\n批注 · ${annotation.note}`;
|
|
2089
|
+
tile.append(label,remove);
|
|
2090
|
+
} else tile.append(make('span','session-file-label',name),remove);
|
|
2091
|
+
return tile;
|
|
2092
|
+
}
|
|
2093
|
+
const open = button('',() => this.openImage(image.src,name),'session-image-open'); labelButton(open,'预览 '+name);
|
|
2094
|
+
const thumbnail = make('img'); thumbnail.alt = ''; thumbnail.src = image.src;
|
|
2095
|
+
thumbnail.onerror = () => {
|
|
2096
|
+
if (!this.images(task).includes(image)) return;
|
|
2097
|
+
this.replaceImages(task,this.images(task).map(entry=>entry === image ? {id:uuid(),file:image.file} : entry));
|
|
2098
|
+
if ((this.newDraft?.id ?? this.task?.id) === task && this.attachments.isConnected) {
|
|
2099
|
+
this.noticeImages('此图片无法预览,已作为文件添加。'); this.updateComposer();
|
|
2100
|
+
}
|
|
2101
|
+
};
|
|
2102
|
+
open.append(thumbnail); tile.append(open,remove);
|
|
2103
|
+
return tile;
|
|
2104
|
+
});
|
|
2105
|
+
const keep = new Set(nodes);
|
|
2106
|
+
for (const node of existing.values()) if (!keep.has(node)) node.remove();
|
|
2107
|
+
for (const node of nodes) if (!node.isConnected) this.attachments.append(node);
|
|
2108
|
+
this.attachments.hidden = !nodes.length;
|
|
576
2109
|
}
|
|
577
2110
|
draft(id) { return this.drafts.get(id) ?? read('agentbot-workspace-draft:'+id,'','sessionStorage'); }
|
|
578
2111
|
setDraft(id,text) { this.drafts.set(id,text); save('agentbot-workspace-draft:'+id,text,'sessionStorage'); }
|
|
579
|
-
|
|
2112
|
+
hasUnstoredDraft() {
|
|
2113
|
+
const draft = this.newDraft ?? this.parkedDraft;
|
|
2114
|
+
const queueEdit = this.queueEdit;
|
|
2115
|
+
return Boolean(draft && (!this.newDraftSaved || draft.sending) || this.composing || this.restoringQueue
|
|
2116
|
+
|| queueEdit?.revision && queueEdit.input.value !== queueEdit.original
|
|
2117
|
+
|| this.app.annotations?.hasDraft() || this.draftFiles.hasUnstored());
|
|
2118
|
+
}
|
|
2119
|
+
messages(task) { return this.outboxes.get(task) || new Map(); }
|
|
2120
|
+
saveOutboxes() {
|
|
2121
|
+
const entries = [...this.outboxes].map(([task,messages]) => [task,[...messages].flatMap(([id,message]) =>
|
|
2122
|
+
!message.images.length && !message.accepted ? [[id,message.payload,message.error]] : [])]);
|
|
2123
|
+
save('agentbot-workspace-outbox',entries.filter(([,items])=>items.length),'sessionStorage');
|
|
2124
|
+
}
|
|
2125
|
+
removeMessage(task,id) {
|
|
2126
|
+
const messages = this.outboxes.get(task), message = messages?.get(id);
|
|
2127
|
+
if (!message) return;
|
|
2128
|
+
for (const image of message.images) revokeAttachment(image);
|
|
2129
|
+
messages.delete(id);
|
|
2130
|
+
if (!messages.size) this.outboxes.delete(task);
|
|
2131
|
+
this.saveOutboxes();
|
|
2132
|
+
void this.persistDraftFiles(task);
|
|
2133
|
+
}
|
|
2134
|
+
resetOutboxes() {
|
|
2135
|
+
for (const messages of this.outboxes.values()) for (const message of messages.values())
|
|
2136
|
+
for (const image of message.images) revokeAttachment(image);
|
|
2137
|
+
this.outboxes.clear();
|
|
2138
|
+
}
|
|
2139
|
+
operation(id) {
|
|
2140
|
+
const op = this.operations.get(id) ?? read('agentbot-workspace-operation:'+id,null,'sessionStorage');
|
|
2141
|
+
return op?.action === 'stop' ? op : null;
|
|
2142
|
+
}
|
|
580
2143
|
setOperation(id,op) {
|
|
581
2144
|
this.operations.set(id,op); save('agentbot-workspace-operation:'+id,op,'sessionStorage');
|
|
582
2145
|
if (this.task?.id === id) this.updateComposer();
|
|
583
2146
|
}
|
|
2147
|
+
renderExecutionStatus() {
|
|
2148
|
+
const execution = this.task && this.task.status !== 'closed' && !this.newDraft ? this.execution : undefined;
|
|
2149
|
+
this.executionBar.hidden = !execution;
|
|
2150
|
+
if (execution) {
|
|
2151
|
+
this.executionModel.textContent = '模型 '+(execution.model || '未记录');
|
|
2152
|
+
this.executionThinking.textContent = '思考强度 '+(effortLabel(execution.thinking) || '未记录');
|
|
2153
|
+
}
|
|
2154
|
+
this.updateElapsedTime();
|
|
2155
|
+
}
|
|
2156
|
+
updateElapsedTime() {
|
|
2157
|
+
clearTimeout(this.executionTimer); this.executionTimer = undefined;
|
|
2158
|
+
if (this.executionBar.hidden || this.disposed) return;
|
|
2159
|
+
const start = this.execution?.startedAt;
|
|
2160
|
+
if (!Number.isFinite(start) || start <= 0) {
|
|
2161
|
+
this.elapsedTime.removeAttribute('datetime'); this.elapsedTime.textContent = '未记录'; return;
|
|
2162
|
+
}
|
|
2163
|
+
const elapsed = Math.max(0,Date.now()-start), seconds = Math.floor(elapsed/1000);
|
|
2164
|
+
this.elapsedTime.setAttribute('datetime','PT'+seconds+'S');
|
|
2165
|
+
this.elapsedTime.textContent = executionClock(seconds);
|
|
2166
|
+
this.executionTimer = setTimeout(() => this.updateElapsedTime(),1000-elapsed%1000);
|
|
2167
|
+
}
|
|
584
2168
|
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(
|
|
587
|
-
|
|
2169
|
+
const draft = this.newDraft, task = draft ?? this.task, running = !draft && activeTurn(this.headStatus), archived = task?.status === 'closed';
|
|
2170
|
+
const op = !draft && task && this.operation(task.id), blocked = !task || archived || this.selecting || Boolean(draft?.sending)
|
|
2171
|
+
|| this.restoringQueue === task?.id || this.loadingDraftFiles.has(task?.id);
|
|
2172
|
+
this.renderExecutionStatus();
|
|
2173
|
+
this.input.disabled = blocked;
|
|
588
2174
|
this.input.placeholder = archived ? '任务已归档' : !task ? '选择任务后继续' : '输入消息…';
|
|
589
|
-
this.
|
|
590
|
-
this.
|
|
2175
|
+
this.attach.disabled = this.input.disabled;
|
|
2176
|
+
const savingSettings = this.pendingSettings.has(task?.id);
|
|
2177
|
+
if (this.settingsMenuState && (blocked || draft || this.settingsMenuState.task !== task?.id)) this.closeSettingsMenu();
|
|
2178
|
+
this.modelButton.disabled = this.thinkingButton.disabled = blocked || savingSettings || Boolean(draft && !draft.agents?.length);
|
|
2179
|
+
this.modelButton.firstElementChild.textContent = task?.model || '模型';
|
|
2180
|
+
this.thinkingButton.firstElementChild.textContent = effortLabel(task?.thinking) || '思考强度';
|
|
2181
|
+
this.send.disabled = blocked || savingSettings || Boolean(draft && !draft.agent) || !(this.input.value.trim() || this.images(task?.id).length);
|
|
2182
|
+
this.schedule.hidden = Boolean(draft);
|
|
2183
|
+
this.schedule.disabled = blocked;
|
|
2184
|
+
labelButton(this.send,running && this.head ? '追加到当前轮次' : '发送');
|
|
591
2185
|
this.stop.hidden = !running || archived;
|
|
592
|
-
this.stop.disabled = blocked;
|
|
593
|
-
this.
|
|
2186
|
+
this.stop.disabled = blocked || ['pending','unknown'].includes(op?.status);
|
|
2187
|
+
this.renderPromptQueue();
|
|
2188
|
+
if (this.composerMirror && this.composerMirror.dataset.value !== this.input.value) this.composerMirror.dataset.value = this.input.value;
|
|
2189
|
+
this.renderDraftImages(task?.id);
|
|
2190
|
+
this.updateDraftStorageNotice();
|
|
594
2191
|
this.opNote.replaceChildren(); this.opNote.hidden = !op?.message;
|
|
595
2192
|
if (op?.message) {
|
|
596
2193
|
this.opNote.append(make('span',op.status === 'unknown' || op.status === 'failed'?'session-error':null,op.message));
|
|
@@ -598,43 +2195,149 @@
|
|
|
598
2195
|
if (op.status === 'unknown') this.opNote.append(button('我已核实',() => this.setOperation(task.id,null),'session-quiet'));
|
|
599
2196
|
}
|
|
600
2197
|
}
|
|
601
|
-
|
|
2198
|
+
submit(action) {
|
|
2199
|
+
if (action === 'queue' && (this.newDraft || ![this.headStatus,this.task?.status].some(value => value === 'starting' || activeTurn(value)))) action = 'send';
|
|
2200
|
+
if (this.newDraft) {
|
|
2201
|
+
if (action === 'send' && !this.send.disabled) void this.submitDraft(this.newDraft);
|
|
2202
|
+
return;
|
|
2203
|
+
}
|
|
602
2204
|
const task = this.task?.id;
|
|
603
|
-
if (!task || this.
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
const
|
|
607
|
-
|
|
608
|
-
|
|
2205
|
+
if (!task || !this.csrf || this.selecting) return;
|
|
2206
|
+
if (action === 'stop') { if (!this.stop.disabled && !this.stop.hidden) void this.submitStop(task); return; }
|
|
2207
|
+
if (this.send.disabled) return;
|
|
2208
|
+
const request = uuid(), images = this.images(task);
|
|
2209
|
+
const turn = action === 'send' && activeTurn(this.headStatus) ? this.head : undefined;
|
|
2210
|
+
const message = {payload:{task,request,text:annotationPrompt(this.input.value,images),...(turn ? {action:'steer',turn} : {action})},images};
|
|
2211
|
+
const messages = this.messages(task);
|
|
2212
|
+
messages.set(request,message); this.outboxes.set(task,messages);
|
|
2213
|
+
this.input.value = ''; this.setDraft(task,''); this.imageDrafts.delete(task); this.noticeImages('');
|
|
2214
|
+
this.updateComposer(); this.pendingPosition = {bottom:true};
|
|
2215
|
+
void this.sendMessage(message); this.app.queuePersist();
|
|
2216
|
+
}
|
|
2217
|
+
restoreUnsentMessage(message) {
|
|
2218
|
+
const {task,request,text} = message.payload, messages = this.outboxes.get(task);
|
|
2219
|
+
if (this.task?.id !== task || this.input.disabled || this.newDraft || messages?.get(request) !== message) return;
|
|
2220
|
+
if (this.input.value || this.images(task).length) { this.setChatError('请先处理输入框中已有的草稿。'); return; }
|
|
2221
|
+
messages.delete(request);
|
|
2222
|
+
if (!messages.size) this.outboxes.delete(task);
|
|
2223
|
+
this.replaceImages(task,message.images);
|
|
2224
|
+
this.input.value = text; this.setDraft(task,text); this.setChatError('');
|
|
2225
|
+
this.updateComposer(); this.updateOutbox(task); this.input.focus();
|
|
2226
|
+
}
|
|
2227
|
+
async submitDraft(draft) {
|
|
2228
|
+
const grant = this.csrf, images = this.images(draft.id), text = annotationPrompt(this.input.value,images);
|
|
2229
|
+
draft.sending = true; this.updateDraftView(); this.setChatError('正在提交第一条消息…');
|
|
2230
|
+
try {
|
|
2231
|
+
const encoded = await encodeAttachments(images);
|
|
2232
|
+
if (this.csrf !== grant) return;
|
|
2233
|
+
const result = await this.fetch('/tasks',{body:{request:draft.request,title:(draft.creationTitle ??= text.slice(0,200)),
|
|
2234
|
+
agent:draft.agent,directory:draft.directory,model:draft.model,thinking:draft.thinking},timeout:60_000});
|
|
2235
|
+
await this.restoreDraftFiles(result.id);
|
|
2236
|
+
if (this.csrf !== grant) return;
|
|
2237
|
+
const message = {payload:{task:result.id,request:draft.request,action:'send',text},images,encoded};
|
|
2238
|
+
const messages = this.messages(result.id);
|
|
2239
|
+
messages.set(draft.request,message); this.outboxes.set(result.id,messages);
|
|
2240
|
+
this.imageDrafts.delete(draft.id);
|
|
2241
|
+
await this.persistDraftFiles(result.id,draft.id);
|
|
2242
|
+
const visible = this.newDraft === draft;
|
|
2243
|
+
if (visible) this.leaveDraft(true);
|
|
2244
|
+
if (this.parkedDraft === draft) this.parkedDraft = undefined;
|
|
2245
|
+
this.saveNewTaskDraft();
|
|
2246
|
+
if (this.search) this.search.value = '';
|
|
2247
|
+
if (this.filter) for (const option of this.filter.options) option.selected = option.value === 'open';
|
|
2248
|
+
clearTimeout(this.searchTimer);
|
|
2249
|
+
void this.sendMessage(message); void this.loadGroups();
|
|
2250
|
+
if (visible) void this.choose(result.id);
|
|
2251
|
+
} catch (error) {
|
|
2252
|
+
if (this.newDraft === draft && this.csrf === grant) this.setChatError(error.message);
|
|
2253
|
+
else if (this.csrf === grant) this.listNote.textContent = error.message;
|
|
2254
|
+
} finally {
|
|
2255
|
+
draft.sending = false;
|
|
2256
|
+
if (this.newDraft === draft) this.updateDraftView();
|
|
2257
|
+
}
|
|
2258
|
+
}
|
|
2259
|
+
async sendMessage(message,retry = false) {
|
|
2260
|
+
const {payload,images} = message, {task,request} = payload, grant = this.csrf;
|
|
2261
|
+
if (!grant || this.disposed || this.outboxes.get(task)?.get(request) !== message
|
|
2262
|
+
|| retry && (!message.error || this.task?.id !== task || this.selecting || this.task.status === 'closed')) return;
|
|
2263
|
+
const attempt = message.attempt = {};
|
|
2264
|
+
const current = () => !this.disposed && message.attempt === attempt && this.outboxes.get(task)?.get(request) === message;
|
|
2265
|
+
message.error = undefined; message.restored = false;
|
|
2266
|
+
const saved = this.updateOutbox(task);
|
|
2267
|
+
if (saved) await saved;
|
|
2268
|
+
let encoded;
|
|
2269
|
+
try { encoded = message.encoded ?? (images.length ? await encodeAttachments(images) : undefined); }
|
|
2270
|
+
catch (error) { if (current()) this.failMessage(message,error.message); return; }
|
|
2271
|
+
if (!current()) return;
|
|
2272
|
+
if (this.csrf !== grant) { this.failMessage(message,'会话已过期,登录后可重试。'); return; }
|
|
2273
|
+
try {
|
|
2274
|
+
const result = await this.fetch('/operation',{params:retry?{retry:1}:undefined,body:encoded?{...payload,...encoded}:payload});
|
|
2275
|
+
if (current()) this.handleMessage(message,result);
|
|
2276
|
+
} catch (error) {
|
|
2277
|
+
if (!current()) return;
|
|
2278
|
+
const rejected = error.status >= 400 && error.status < 500 && error.status !== 408 || error.status === 503 && error.message.includes('未提交');
|
|
2279
|
+
this.failMessage(message,rejected ? error.message : '暂未确认送达,点击重试。');
|
|
2280
|
+
if (!rejected && this.csrf === grant) void this.checkMessage(message,attempt);
|
|
2281
|
+
}
|
|
2282
|
+
}
|
|
2283
|
+
updateOutbox(task) {
|
|
2284
|
+
this.saveOutboxes();
|
|
2285
|
+
if (this.task?.id === task) this.redraw();
|
|
2286
|
+
return this.persistDraftFiles(task);
|
|
2287
|
+
}
|
|
2288
|
+
failMessage(message,error) {
|
|
2289
|
+
message.error = error; this.updateOutbox(message.payload.task);
|
|
2290
|
+
}
|
|
2291
|
+
handleMessage(message,result) {
|
|
2292
|
+
const {task,request} = message.payload;
|
|
2293
|
+
message.stale = result.status === 'stale';
|
|
2294
|
+
if (result.status === 'accepted') {
|
|
2295
|
+
if (result.queued) this.removeMessage(task,request);
|
|
2296
|
+
else { message.accepted = true; message.error = undefined; }
|
|
2297
|
+
this.updateOutbox(task);
|
|
2298
|
+
if (this.task?.id === task && !this.connected) void this.refreshConversation(false);
|
|
2299
|
+
} else this.failMessage(message,result.status === 'pending' ? '暂未确认送达,点击重试。'
|
|
2300
|
+
: result.status === 'unknown' ? `${result.posted?'已发到飞书,Agent 提交结果待核实':'发送结果待核实'},不会重复发送。${result.message ? ' '+result.message : ''}`
|
|
2301
|
+
: result.message || '发送失败,点击重试。');
|
|
2302
|
+
if (message.stale && this.task?.id === task) void this.refreshConversation(false);
|
|
2303
|
+
}
|
|
2304
|
+
async checkMessage(message,attempt) {
|
|
2305
|
+
const {task,request} = message.payload;
|
|
2306
|
+
try {
|
|
2307
|
+
const result = await this.fetch('/operation',{params:{request}});
|
|
2308
|
+
if (!this.disposed && message.attempt === attempt && this.outboxes.get(task)?.get(request) === message) this.handleMessage(message,result);
|
|
2309
|
+
} catch { /* Leave the retry control available; a lookup never resubmits. */ }
|
|
2310
|
+
}
|
|
2311
|
+
checkRestoredMessages(task) {
|
|
2312
|
+
for (const message of this.messages(task).values()) if (message.restored) {
|
|
2313
|
+
message.restored = false;
|
|
2314
|
+
this.failMessage(message,message.error || '暂未确认送达,点击重试。');
|
|
2315
|
+
void this.checkMessage(message,message.attempt);
|
|
2316
|
+
}
|
|
2317
|
+
}
|
|
2318
|
+
async submitStop(task) {
|
|
2319
|
+
const request = uuid(), action = 'stop', turn = this.head, pending = {request,action,status:'pending',message:'正在请求停止…'};
|
|
2320
|
+
this.setOperation(task,pending);
|
|
2321
|
+
try { this.handleOperation(task,request,action,await this.fetch('/operation',{body:{task,request,action,turn}})); }
|
|
609
2322
|
catch (error) {
|
|
610
|
-
if (
|
|
2323
|
+
if (error.status >= 400 && error.status < 500 && error.status !== 408 || error.status === 503 && error.message.includes('未提交')) {
|
|
611
2324
|
this.setOperation(task,{request,action,status:'failed',message:error.message});
|
|
612
|
-
}
|
|
613
|
-
else {
|
|
2325
|
+
} else {
|
|
614
2326
|
this.setOperation(task,{...pending,status:'unknown',message:'连接中断,结果待核实。没有自动重发。'});
|
|
615
2327
|
void this.checkOperation(task,false);
|
|
616
2328
|
}
|
|
617
2329
|
}
|
|
618
2330
|
}
|
|
619
|
-
handleOperation(task,request,action,result
|
|
620
|
-
|
|
621
|
-
|
|
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]
|
|
2331
|
+
handleOperation(task,request,action,result) {
|
|
2332
|
+
if (this.operation(task)?.request !== request) return;
|
|
2333
|
+
const message = result.status === 'accepted' ? '已请求停止此轮。'
|
|
626
2334
|
: result.status === 'pending' ? '服务端正在处理,可以稍后核实。'
|
|
627
2335
|
: result.status === 'stale' ? '这一轮已结束,没有停止后续轮次。'
|
|
628
|
-
: result.status === 'unknown' ?
|
|
2336
|
+
: result.status === 'unknown' ? `停止结果待核实。${result.message ? ' '+result.message : ''}`
|
|
629
2337
|
: 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};
|
|
2338
|
+
const notice = {request,action,status:result.status,message};
|
|
633
2339
|
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
|
-
}
|
|
2340
|
+
if (result.status === 'accepted') setTimeout(() => { if (!this.disposed && this.operations.get(task) === notice) this.setOperation(task,null); },6000);
|
|
638
2341
|
}
|
|
639
2342
|
async checkOperation(task, explicit) {
|
|
640
2343
|
const op = this.operation(task); if (!op || !['pending','unknown'].includes(op.status)) return;
|